blob: b826ab9d112e6695b1b773fdcdbaf466f1dd9b0d [file] [log] [blame]
Harry Cutts79cc9fa2022-10-28 15:32:39 +00001/*
2 * Copyright 2022 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "../Macros.h"
18
Harry Cuttsa34de522023-06-06 15:52:54 +000019#include <algorithm>
Harry Cuttsbb24e272023-03-21 10:49:47 +000020#include <chrono>
Harry Cuttsa34de522023-06-06 15:52:54 +000021#include <iterator>
Harry Cuttsd35a24b2023-01-30 15:09:30 +000022#include <limits>
Harry Cuttsa34de522023-06-06 15:52:54 +000023#include <map>
Harry Cuttsedf6ce72023-01-04 12:15:53 +000024#include <optional>
25
Harry Cuttsbb24e272023-03-21 10:49:47 +000026#include <android-base/stringprintf.h>
Harry Cutts74235542022-11-24 15:52:53 +000027#include <android/input.h>
Harry Cutts2b67ff12023-03-13 11:32:06 +000028#include <ftl/enum.h>
Harry Cuttsea73eaa2023-01-16 17:55:46 +000029#include <input/PrintTools.h>
Harry Cutts4fb941a2022-12-14 19:14:04 +000030#include <linux/input-event-codes.h>
Harry Cutts74235542022-11-24 15:52:53 +000031#include <log/log_main.h>
Harry Cuttsa34de522023-06-06 15:52:54 +000032#include <stats_pull_atom_callback.h>
33#include <statslog.h>
Harry Cutts74235542022-11-24 15:52:53 +000034#include "TouchCursorInputMapperCommon.h"
Harry Cutts79cc9fa2022-10-28 15:32:39 +000035#include "TouchpadInputMapper.h"
Harry Cuttsedf6ce72023-01-04 12:15:53 +000036#include "ui/Rotation.h"
Harry Cutts79cc9fa2022-10-28 15:32:39 +000037
38namespace android {
39
Harry Cutts1f48a442022-11-15 17:38:36 +000040namespace {
41
Harry Cuttsc5025372023-02-21 16:04:45 +000042/**
43 * Log details of each gesture output by the gestures library.
44 * Enable this via "adb shell setprop log.tag.TouchpadInputMapperGestures DEBUG" (requires
45 * restarting the shell)
46 */
47const bool DEBUG_TOUCHPAD_GESTURES =
48 __android_log_is_loggable(ANDROID_LOG_DEBUG, "TouchpadInputMapperGestures",
49 ANDROID_LOG_INFO);
50
Harry Cuttsd35a24b2023-01-30 15:09:30 +000051// Describes a segment of the acceleration curve.
52struct CurveSegment {
53 // The maximum pointer speed which this segment should apply. The last segment in a curve should
54 // always set this to infinity.
55 double maxPointerSpeedMmPerS;
56 double slope;
57 double intercept;
58};
59
60const std::vector<CurveSegment> segments = {
Wenxin Fenge5d6d042023-07-06 17:40:45 -070061 {32.002, 3.19, 0},
62 {52.83, 4.79, -51.254},
63 {119.124, 7.28, -182.737},
64 {std::numeric_limits<double>::infinity(), 15.04, -1107.556},
Harry Cuttsd35a24b2023-01-30 15:09:30 +000065};
66
Wenxin Fenge5d6d042023-07-06 17:40:45 -070067const std::vector<double> sensitivityFactors = {1, 2, 4, 6, 7, 8, 9, 10,
68 11, 12, 13, 14, 16, 18, 20};
Harry Cuttsd35a24b2023-01-30 15:09:30 +000069
70std::vector<double> createAccelerationCurveForSensitivity(int32_t sensitivity,
71 size_t propertySize) {
72 LOG_ALWAYS_FATAL_IF(propertySize < 4 * segments.size());
73 std::vector<double> output(propertySize, 0);
74
75 // The Gestures library uses functions of the following form to define curve segments, where a,
76 // b, and c can be specified by us:
77 // output_speed(input_speed_mm) = a * input_speed_mm ^ 2 + b * input_speed_mm + c
78 //
79 // (a, b, and c are also called sqr_, mul_, and int_ in the Gestures library code.)
80 //
81 // We are trying to implement the following function, where slope and intercept are the
82 // parameters specified in the `segments` array above:
83 // gain(input_speed_mm) =
84 // 0.64 * (sensitivityFactor / 10) * (slope + intercept / input_speed_mm)
85 // Where "gain" is a multiplier applied to the input speed to produce the output speed:
86 // output_speed(input_speed_mm) = input_speed_mm * gain(input_speed_mm)
87 //
88 // To put our function in the library's form, we substitute it into the function above:
89 // output_speed(input_speed_mm) =
90 // input_speed_mm * (0.64 * (sensitivityFactor / 10) *
91 // (slope + 25.4 * intercept / input_speed_mm))
92 // then expand the brackets so that input_speed_mm cancels out for the intercept term:
93 // gain(input_speed_mm) =
94 // 0.64 * (sensitivityFactor / 10) * slope * input_speed_mm +
95 // 0.64 * (sensitivityFactor / 10) * intercept
96 //
97 // This gives us the following parameters for the Gestures library function form:
98 // a = 0
99 // b = 0.64 * (sensitivityFactor / 10) * slope
100 // c = 0.64 * (sensitivityFactor / 10) * intercept
101
102 double commonFactor = 0.64 * sensitivityFactors[sensitivity + 7] / 10;
103
104 size_t i = 0;
105 for (CurveSegment seg : segments) {
106 // The library's curve format consists of four doubles per segment:
107 // * maximum pointer speed for the segment (mm/s)
108 // * multiplier for the x² term (a.k.a. "a" or "sqr")
109 // * multiplier for the x term (a.k.a. "b" or "mul")
110 // * the intercept (a.k.a. "c" or "int")
111 // (see struct CurveSegment in the library's AccelFilterInterpreter)
112 output[i + 0] = seg.maxPointerSpeedMmPerS;
113 output[i + 1] = 0;
114 output[i + 2] = commonFactor * seg.slope;
115 output[i + 3] = commonFactor * seg.intercept;
116 i += 4;
117 }
118
119 return output;
120}
121
Harry Cutts1f48a442022-11-15 17:38:36 +0000122short getMaxTouchCount(const InputDeviceContext& context) {
Harry Cuttsb2552152022-12-13 17:18:09 +0000123 if (context.hasScanCode(BTN_TOOL_QUINTTAP)) return 5;
124 if (context.hasScanCode(BTN_TOOL_QUADTAP)) return 4;
125 if (context.hasScanCode(BTN_TOOL_TRIPLETAP)) return 3;
126 if (context.hasScanCode(BTN_TOOL_DOUBLETAP)) return 2;
127 if (context.hasScanCode(BTN_TOOL_FINGER)) return 1;
Harry Cutts1f48a442022-11-15 17:38:36 +0000128 return 0;
129}
130
131HardwareProperties createHardwareProperties(const InputDeviceContext& context) {
132 HardwareProperties props;
133 RawAbsoluteAxisInfo absMtPositionX;
134 context.getAbsoluteAxisInfo(ABS_MT_POSITION_X, &absMtPositionX);
135 props.left = absMtPositionX.minValue;
136 props.right = absMtPositionX.maxValue;
137 props.res_x = absMtPositionX.resolution;
138
139 RawAbsoluteAxisInfo absMtPositionY;
140 context.getAbsoluteAxisInfo(ABS_MT_POSITION_Y, &absMtPositionY);
141 props.top = absMtPositionY.minValue;
142 props.bottom = absMtPositionY.maxValue;
143 props.res_y = absMtPositionY.resolution;
144
145 RawAbsoluteAxisInfo absMtOrientation;
146 context.getAbsoluteAxisInfo(ABS_MT_ORIENTATION, &absMtOrientation);
147 props.orientation_minimum = absMtOrientation.minValue;
148 props.orientation_maximum = absMtOrientation.maxValue;
149
150 RawAbsoluteAxisInfo absMtSlot;
151 context.getAbsoluteAxisInfo(ABS_MT_SLOT, &absMtSlot);
152 props.max_finger_cnt = absMtSlot.maxValue - absMtSlot.minValue + 1;
153 props.max_touch_cnt = getMaxTouchCount(context);
154
155 // T5R2 ("Track 5, Report 2") is a feature of some old Synaptics touchpads that could track 5
156 // fingers but only report the coordinates of 2 of them. We don't know of any external touchpads
157 // that did this, so assume false.
158 props.supports_t5r2 = false;
159
160 props.support_semi_mt = context.hasInputProperty(INPUT_PROP_SEMI_MT);
161 props.is_button_pad = context.hasInputProperty(INPUT_PROP_BUTTONPAD);
162
163 // Mouse-only properties, which will always be false.
164 props.has_wheel = false;
165 props.wheel_is_hi_res = false;
166
167 // Linux Kernel haptic touchpad support isn't merged yet, so for now assume that no touchpads
168 // are haptic.
169 props.is_haptic_pad = false;
Harry Cuttsce3c71e2023-08-21 09:18:09 +0000170
171 RawAbsoluteAxisInfo absMtPressure;
172 context.getAbsoluteAxisInfo(ABS_MT_PRESSURE, &absMtPressure);
173 props.reports_pressure = absMtPressure.valid;
Harry Cutts1f48a442022-11-15 17:38:36 +0000174 return props;
175}
176
Harry Cutts74235542022-11-24 15:52:53 +0000177void gestureInterpreterCallback(void* clientData, const Gesture* gesture) {
178 TouchpadInputMapper* mapper = static_cast<TouchpadInputMapper*>(clientData);
179 mapper->consumeGesture(gesture);
180}
181
Harry Cuttsa34de522023-06-06 15:52:54 +0000182int32_t linuxBusToInputDeviceBusEnum(int32_t linuxBus) {
183 // When adding cases to this switch, also add them to the copy of this method in
184 // InputDeviceMetricsCollector.cpp.
185 // TODO(b/286394420): deduplicate this method with the one in InputDeviceMetricsCollector.cpp.
186 switch (linuxBus) {
187 case BUS_USB:
188 return util::INPUT_DEVICE_USAGE_REPORTED__DEVICE_BUS__USB;
189 case BUS_BLUETOOTH:
190 return util::INPUT_DEVICE_USAGE_REPORTED__DEVICE_BUS__BLUETOOTH;
191 default:
192 return util::INPUT_DEVICE_USAGE_REPORTED__DEVICE_BUS__OTHER;
193 }
194}
195
196class MetricsAccumulator {
197public:
198 static MetricsAccumulator& getInstance() {
199 static MetricsAccumulator sAccumulator;
200 return sAccumulator;
201 }
202
203 void recordFinger(const TouchpadInputMapper::MetricsIdentifier& id) { mCounters[id].fingers++; }
204
205 void recordPalm(const TouchpadInputMapper::MetricsIdentifier& id) { mCounters[id].palms++; }
206
207 // Checks whether a Gesture struct is for the end of a gesture that we log metrics for, and
208 // records it if so.
209 void processGesture(const TouchpadInputMapper::MetricsIdentifier& id, const Gesture& gesture) {
210 switch (gesture.type) {
211 case kGestureTypeFling:
212 if (gesture.details.fling.fling_state == GESTURES_FLING_START) {
213 // Indicates the end of a two-finger scroll gesture.
214 mCounters[id].twoFingerSwipeGestures++;
215 }
216 break;
217 case kGestureTypeSwipeLift:
218 mCounters[id].threeFingerSwipeGestures++;
219 break;
220 case kGestureTypeFourFingerSwipeLift:
221 mCounters[id].fourFingerSwipeGestures++;
222 break;
223 case kGestureTypePinch:
224 if (gesture.details.pinch.zoom_state == GESTURES_ZOOM_END) {
225 mCounters[id].pinchGestures++;
226 }
227 break;
228 default:
229 // We're not interested in any other gestures.
230 break;
231 }
232 }
233
234private:
235 MetricsAccumulator() {
236 AStatsManager_setPullAtomCallback(android::util::TOUCHPAD_USAGE, /*metadata=*/nullptr,
237 MetricsAccumulator::pullAtomCallback, /*cookie=*/nullptr);
238 }
239
240 ~MetricsAccumulator() { AStatsManager_clearPullAtomCallback(android::util::TOUCHPAD_USAGE); }
241
242 static AStatsManager_PullAtomCallbackReturn pullAtomCallback(int32_t atomTag,
243 AStatsEventList* outEventList,
244 void* cookie) {
245 LOG_ALWAYS_FATAL_IF(atomTag != android::util::TOUCHPAD_USAGE);
246 MetricsAccumulator& accumulator = MetricsAccumulator::getInstance();
247 accumulator.produceAtoms(outEventList);
248 accumulator.resetCounters();
249 return AStatsManager_PULL_SUCCESS;
250 }
251
252 void produceAtoms(AStatsEventList* outEventList) const {
253 for (auto& [id, counters] : mCounters) {
254 auto [busId, vendorId, productId, versionId] = id;
255 addAStatsEvent(outEventList, android::util::TOUCHPAD_USAGE, vendorId, productId,
256 versionId, linuxBusToInputDeviceBusEnum(busId), counters.fingers,
257 counters.palms, counters.twoFingerSwipeGestures,
258 counters.threeFingerSwipeGestures, counters.fourFingerSwipeGestures,
259 counters.pinchGestures);
260 }
261 }
262
263 void resetCounters() { mCounters.clear(); }
264
265 // Stores the counters for a specific touchpad model. Fields have the same meanings as those of
266 // the TouchpadUsage atom; see that definition for detailed documentation.
267 struct Counters {
268 int32_t fingers = 0;
269 int32_t palms = 0;
270
271 int32_t twoFingerSwipeGestures = 0;
272 int32_t threeFingerSwipeGestures = 0;
273 int32_t fourFingerSwipeGestures = 0;
274 int32_t pinchGestures = 0;
275 };
276
277 // Metrics are aggregated by device model and version, so if two devices of the same model and
278 // version are connected at once, they will have the same counters.
279 std::map<TouchpadInputMapper::MetricsIdentifier, Counters> mCounters;
280};
281
Harry Cutts1f48a442022-11-15 17:38:36 +0000282} // namespace
283
Arpit Singh8e6fb252023-04-06 11:49:17 +0000284TouchpadInputMapper::TouchpadInputMapper(InputDeviceContext& deviceContext,
285 const InputReaderConfiguration& readerConfig)
286 : InputMapper(deviceContext, readerConfig),
Harry Cutts1f48a442022-11-15 17:38:36 +0000287 mGestureInterpreter(NewGestureInterpreter(), DeleteGestureInterpreter),
Harry Cutts74235542022-11-24 15:52:53 +0000288 mPointerController(getContext()->getPointerController(getDeviceId())),
Harry Cuttsbb24e272023-03-21 10:49:47 +0000289 mStateConverter(deviceContext, mMotionAccumulator),
290 mGestureConverter(*getContext(), deviceContext, getDeviceId()),
Harry Cuttsa34de522023-06-06 15:52:54 +0000291 mCapturedEventConverter(*getContext(), deviceContext, mMotionAccumulator, getDeviceId()),
292 mMetricsId(metricsIdFromInputDeviceIdentifier(deviceContext.getDeviceIdentifier())) {
Harry Cuttsbb24e272023-03-21 10:49:47 +0000293 RawAbsoluteAxisInfo slotAxisInfo;
294 deviceContext.getAbsoluteAxisInfo(ABS_MT_SLOT, &slotAxisInfo);
295 if (!slotAxisInfo.valid || slotAxisInfo.maxValue <= 0) {
296 ALOGW("Touchpad \"%s\" doesn't have a valid ABS_MT_SLOT axis, and probably won't work "
297 "properly.",
298 deviceContext.getName().c_str());
299 }
300 mMotionAccumulator.configure(deviceContext, slotAxisInfo.maxValue + 1, true);
301
Harry Cutts1f48a442022-11-15 17:38:36 +0000302 mGestureInterpreter->Initialize(GESTURES_DEVCLASS_TOUCHPAD);
303 mGestureInterpreter->SetHardwareProperties(createHardwareProperties(deviceContext));
Harry Cutts74235542022-11-24 15:52:53 +0000304 // Even though we don't explicitly delete copy/move semantics, it's safe to
Harry Cutts1b217912023-01-03 17:13:19 +0000305 // give away pointers to TouchpadInputMapper and its members here because
Harry Cutts74235542022-11-24 15:52:53 +0000306 // 1) mGestureInterpreter's lifecycle is determined by TouchpadInputMapper, and
307 // 2) TouchpadInputMapper is stored as a unique_ptr and not moved.
Harry Cutts1b217912023-01-03 17:13:19 +0000308 mGestureInterpreter->SetPropProvider(const_cast<GesturesPropProvider*>(&gesturePropProvider),
309 &mPropertyProvider);
Harry Cutts74235542022-11-24 15:52:53 +0000310 mGestureInterpreter->SetCallback(gestureInterpreterCallback, this);
Harry Cutts1f48a442022-11-15 17:38:36 +0000311 // TODO(b/251196347): set a timer provider, so the library can use timers.
Harry Cutts1f48a442022-11-15 17:38:36 +0000312}
Harry Cutts79cc9fa2022-10-28 15:32:39 +0000313
Harry Cutts74235542022-11-24 15:52:53 +0000314TouchpadInputMapper::~TouchpadInputMapper() {
315 if (mPointerController != nullptr) {
316 mPointerController->fade(PointerControllerInterface::Transition::IMMEDIATE);
317 }
Harry Cutts1b217912023-01-03 17:13:19 +0000318
319 // The gesture interpreter's destructor will call its property provider's free function for all
320 // gesture properties, in this case calling PropertyProvider::freeProperty using a raw pointer
321 // to mPropertyProvider. Depending on the declaration order in TouchpadInputMapper.h, this may
322 // happen after mPropertyProvider has been destructed, causing allocation errors. Depending on
323 // declaration order to avoid crashes seems rather fragile, so explicitly clear the property
324 // provider here to ensure all the freeProperty calls happen before mPropertyProvider is
325 // destructed.
326 mGestureInterpreter->SetPropProvider(nullptr, nullptr);
Harry Cutts74235542022-11-24 15:52:53 +0000327}
328
Harry Cutts79cc9fa2022-10-28 15:32:39 +0000329uint32_t TouchpadInputMapper::getSources() const {
330 return AINPUT_SOURCE_MOUSE | AINPUT_SOURCE_TOUCHPAD;
331}
332
Harry Cuttsd02ea102023-03-17 18:21:30 +0000333void TouchpadInputMapper::populateDeviceInfo(InputDeviceInfo& info) {
Harry Cutts8cd2abd2023-03-15 16:35:56 +0000334 InputMapper::populateDeviceInfo(info);
Harry Cuttsbb24e272023-03-21 10:49:47 +0000335 if (mPointerCaptured) {
336 mCapturedEventConverter.populateMotionRanges(info);
337 } else {
338 mGestureConverter.populateMotionRanges(info);
339 }
Harry Cutts8cd2abd2023-03-15 16:35:56 +0000340}
341
Harry Cuttsea73eaa2023-01-16 17:55:46 +0000342void TouchpadInputMapper::dump(std::string& dump) {
343 dump += INDENT2 "Touchpad Input Mapper:\n";
Harry Cuttsbb24e272023-03-21 10:49:47 +0000344 if (mProcessing) {
345 dump += INDENT3 "Currently processing a hardware state\n";
346 }
347 if (mResettingInterpreter) {
348 dump += INDENT3 "Currently resetting gesture interpreter\n";
349 }
350 dump += StringPrintf(INDENT3 "Pointer captured: %s\n", toString(mPointerCaptured));
Harry Cuttsea73eaa2023-01-16 17:55:46 +0000351 dump += INDENT3 "Gesture converter:\n";
352 dump += addLinePrefix(mGestureConverter.dump(), INDENT4);
353 dump += INDENT3 "Gesture properties:\n";
354 dump += addLinePrefix(mPropertyProvider.dump(), INDENT4);
Harry Cuttsbb24e272023-03-21 10:49:47 +0000355 dump += INDENT3 "Captured event converter:\n";
356 dump += addLinePrefix(mCapturedEventConverter.dump(), INDENT4);
Josep del Riod0746382023-07-29 13:18:25 +0000357 dump += StringPrintf(INDENT3 "DisplayId: %s\n", toString(mDisplayId).c_str());
Harry Cuttsea73eaa2023-01-16 17:55:46 +0000358}
359
Arpit Singh4be4eef2023-03-28 14:26:01 +0000360std::list<NotifyArgs> TouchpadInputMapper::reconfigure(nsecs_t when,
Arpit Singhed6c3de2023-04-05 19:24:37 +0000361 const InputReaderConfiguration& config,
Prabir Pradhan4bf6d452023-04-18 21:26:56 +0000362 ConfigurationChanges changes) {
363 if (!changes.any()) {
Harry Cutts2b67ff12023-03-13 11:32:06 +0000364 // First time configuration
365 mPropertyProvider.loadPropertiesFromIdcFile(getDeviceContext().getConfiguration());
366 }
367
Prabir Pradhan4bf6d452023-04-18 21:26:56 +0000368 if (!changes.any() || changes.test(InputReaderConfiguration::Change::DISPLAY_INFO)) {
Josep del Riod0746382023-07-29 13:18:25 +0000369 mDisplayId = ADISPLAY_ID_NONE;
370 if (auto viewport = mDeviceContext.getAssociatedViewport(); viewport) {
371 // This InputDevice is associated with a viewport.
372 // Only generate events for the associated display.
373 const bool mismatchedPointerDisplay =
374 (viewport->displayId != mPointerController->getDisplayId());
375 if (mismatchedPointerDisplay) {
376 ALOGW("Touchpad \"%s\" associated viewport display does not match pointer "
377 "controller",
378 mDeviceContext.getName().c_str());
379 }
380 mDisplayId = mismatchedPointerDisplay ? std::nullopt
381 : std::make_optional(viewport->displayId);
382 } else {
383 // The InputDevice is not associated with a viewport, but it controls the mouse pointer.
384 mDisplayId = mPointerController->getDisplayId();
385 }
386
Harry Cuttsedf6ce72023-01-04 12:15:53 +0000387 ui::Rotation orientation = ui::ROTATION_0;
Josep del Riod0746382023-07-29 13:18:25 +0000388 if (mDisplayId.has_value()) {
389 if (auto viewport = config.getDisplayViewportById(*mDisplayId); viewport) {
Harry Cuttsedf6ce72023-01-04 12:15:53 +0000390 orientation = getInverseRotation(viewport->orientation);
391 }
392 }
Josep del Riod0746382023-07-29 13:18:25 +0000393 mGestureConverter.setDisplayId(mDisplayId);
Harry Cuttsedf6ce72023-01-04 12:15:53 +0000394 mGestureConverter.setOrientation(orientation);
395 }
Prabir Pradhan4bf6d452023-04-18 21:26:56 +0000396 if (!changes.any() || changes.test(InputReaderConfiguration::Change::TOUCHPAD_SETTINGS)) {
Harry Cuttsd35a24b2023-01-30 15:09:30 +0000397 mPropertyProvider.getProperty("Use Custom Touchpad Pointer Accel Curve")
398 .setBoolValues({true});
399 GesturesProp accelCurveProp = mPropertyProvider.getProperty("Pointer Accel Curve");
400 accelCurveProp.setRealValues(
Arpit Singhed6c3de2023-04-05 19:24:37 +0000401 createAccelerationCurveForSensitivity(config.touchpadPointerSpeed,
Harry Cuttsd35a24b2023-01-30 15:09:30 +0000402 accelCurveProp.getCount()));
Wenxin Feng1ca50662023-05-03 14:00:12 -0700403 mPropertyProvider.getProperty("Use Custom Touchpad Scroll Accel Curve")
404 .setBoolValues({true});
405 GesturesProp scrollCurveProp = mPropertyProvider.getProperty("Scroll Accel Curve");
406 scrollCurveProp.setRealValues(
407 createAccelerationCurveForSensitivity(config.touchpadPointerSpeed,
408 scrollCurveProp.getCount()));
409 mPropertyProvider.getProperty("Scroll X Out Scale").setRealValues({1.0});
410 mPropertyProvider.getProperty("Scroll Y Out Scale").setRealValues({1.0});
Harry Cuttsa546ba82023-01-13 17:21:00 +0000411 mPropertyProvider.getProperty("Invert Scrolling")
Arpit Singhed6c3de2023-04-05 19:24:37 +0000412 .setBoolValues({config.touchpadNaturalScrollingEnabled});
Harry Cuttsa546ba82023-01-13 17:21:00 +0000413 mPropertyProvider.getProperty("Tap Enable")
Arpit Singhed6c3de2023-04-05 19:24:37 +0000414 .setBoolValues({config.touchpadTapToClickEnabled});
Harry Cuttsa546ba82023-01-13 17:21:00 +0000415 mPropertyProvider.getProperty("Button Right Click Zone Enable")
Arpit Singhed6c3de2023-04-05 19:24:37 +0000416 .setBoolValues({config.touchpadRightClickZoneEnabled});
Harry Cuttsa546ba82023-01-13 17:21:00 +0000417 }
Harry Cuttsbb24e272023-03-21 10:49:47 +0000418 std::list<NotifyArgs> out;
419 if ((!changes.any() && config.pointerCaptureRequest.enable) ||
420 changes.test(InputReaderConfiguration::Change::POINTER_CAPTURE)) {
421 mPointerCaptured = config.pointerCaptureRequest.enable;
422 // The motion ranges are going to change, so bump the generation to clear the cached ones.
423 bumpGeneration();
424 if (mPointerCaptured) {
425 // The touchpad is being captured, so we need to tidy up any fake fingers etc. that are
426 // still being reported for a gesture in progress.
427 out += reset(when);
428 mPointerController->fade(PointerControllerInterface::Transition::IMMEDIATE);
429 } else {
430 // We're transitioning from captured to uncaptured.
431 mCapturedEventConverter.reset();
432 }
433 if (changes.any()) {
434 out.push_back(NotifyDeviceResetArgs(getContext()->getNextId(), when, getDeviceId()));
435 }
436 }
437 return out;
Harry Cuttsedf6ce72023-01-04 12:15:53 +0000438}
439
Harry Cutts1f48a442022-11-15 17:38:36 +0000440std::list<NotifyArgs> TouchpadInputMapper::reset(nsecs_t when) {
Harry Cutts47db1c72022-12-13 19:20:47 +0000441 mStateConverter.reset();
Harry Cuttsbb24e272023-03-21 10:49:47 +0000442 resetGestureInterpreter(when);
Harry Cuttse9b71422023-03-14 16:54:44 +0000443 std::list<NotifyArgs> out = mGestureConverter.reset(when);
444 out += InputMapper::reset(when);
445 return out;
Harry Cutts1f48a442022-11-15 17:38:36 +0000446}
447
Harry Cuttsbb24e272023-03-21 10:49:47 +0000448void TouchpadInputMapper::resetGestureInterpreter(nsecs_t when) {
449 // The GestureInterpreter has no official reset method, but sending a HardwareState with no
450 // fingers down or buttons pressed should get it into a clean state.
451 HardwareState state;
452 state.timestamp = std::chrono::duration<stime_t>(std::chrono::nanoseconds(when)).count();
453 mResettingInterpreter = true;
454 mGestureInterpreter->PushHardwareState(&state);
455 mResettingInterpreter = false;
456}
457
Harry Cutts79cc9fa2022-10-28 15:32:39 +0000458std::list<NotifyArgs> TouchpadInputMapper::process(const RawEvent* rawEvent) {
Harry Cuttsbb24e272023-03-21 10:49:47 +0000459 if (mPointerCaptured) {
460 return mCapturedEventConverter.process(*rawEvent);
461 }
Harry Cutts47db1c72022-12-13 19:20:47 +0000462 std::optional<SelfContainedHardwareState> state = mStateConverter.processRawEvent(rawEvent);
463 if (state) {
Harry Cuttsa34de522023-06-06 15:52:54 +0000464 updatePalmDetectionMetrics();
Harry Cutts47db1c72022-12-13 19:20:47 +0000465 return sendHardwareState(rawEvent->when, rawEvent->readTime, *state);
466 } else {
467 return {};
Harry Cutts1f48a442022-11-15 17:38:36 +0000468 }
Harry Cutts79cc9fa2022-10-28 15:32:39 +0000469}
470
Harry Cuttsa34de522023-06-06 15:52:54 +0000471void TouchpadInputMapper::updatePalmDetectionMetrics() {
472 std::set<int32_t> currentTrackingIds;
473 for (size_t i = 0; i < mMotionAccumulator.getSlotCount(); i++) {
474 const MultiTouchMotionAccumulator::Slot& slot = mMotionAccumulator.getSlot(i);
475 if (!slot.isInUse()) {
476 continue;
477 }
478 currentTrackingIds.insert(slot.getTrackingId());
479 if (slot.getToolType() == ToolType::PALM) {
480 mPalmTrackingIds.insert(slot.getTrackingId());
481 }
482 }
483 std::vector<int32_t> liftedTouches;
484 std::set_difference(mLastFrameTrackingIds.begin(), mLastFrameTrackingIds.end(),
485 currentTrackingIds.begin(), currentTrackingIds.end(),
486 std::inserter(liftedTouches, liftedTouches.begin()));
487 for (int32_t trackingId : liftedTouches) {
488 if (mPalmTrackingIds.erase(trackingId) > 0) {
489 MetricsAccumulator::getInstance().recordPalm(mMetricsId);
490 } else {
491 MetricsAccumulator::getInstance().recordFinger(mMetricsId);
492 }
493 }
494 mLastFrameTrackingIds = currentTrackingIds;
495}
496
Harry Cutts47db1c72022-12-13 19:20:47 +0000497std::list<NotifyArgs> TouchpadInputMapper::sendHardwareState(nsecs_t when, nsecs_t readTime,
498 SelfContainedHardwareState schs) {
Harry Cutts287e19f2023-02-27 17:09:24 +0000499 ALOGD_IF(DEBUG_TOUCHPAD_GESTURES, "New hardware state: %s", schs.state.String().c_str());
Harry Cutts74235542022-11-24 15:52:53 +0000500 mProcessing = true;
Harry Cutts47db1c72022-12-13 19:20:47 +0000501 mGestureInterpreter->PushHardwareState(&schs.state);
Harry Cutts74235542022-11-24 15:52:53 +0000502 mProcessing = false;
503
Harry Cutts47db1c72022-12-13 19:20:47 +0000504 return processGestures(when, readTime);
Harry Cutts74235542022-11-24 15:52:53 +0000505}
506
507void TouchpadInputMapper::consumeGesture(const Gesture* gesture) {
Harry Cuttsc5025372023-02-21 16:04:45 +0000508 ALOGD_IF(DEBUG_TOUCHPAD_GESTURES, "Gesture ready: %s", gesture->String().c_str());
Harry Cuttsbb24e272023-03-21 10:49:47 +0000509 if (mResettingInterpreter) {
510 // We already handle tidying up fake fingers etc. in GestureConverter::reset, so we should
511 // ignore any gestures produced from the interpreter while we're resetting it.
512 return;
513 }
Harry Cutts74235542022-11-24 15:52:53 +0000514 if (!mProcessing) {
515 ALOGE("Received gesture outside of the normal processing flow; ignoring it.");
516 return;
517 }
518 mGesturesToProcess.push_back(*gesture);
519}
520
521std::list<NotifyArgs> TouchpadInputMapper::processGestures(nsecs_t when, nsecs_t readTime) {
522 std::list<NotifyArgs> out = {};
Josep del Riod0746382023-07-29 13:18:25 +0000523 if (mDisplayId) {
524 MetricsAccumulator& metricsAccumulator = MetricsAccumulator::getInstance();
525 for (Gesture& gesture : mGesturesToProcess) {
526 out += mGestureConverter.handleGesture(when, readTime, gesture);
527 metricsAccumulator.processGesture(mMetricsId, gesture);
528 }
Harry Cutts74235542022-11-24 15:52:53 +0000529 }
530 mGesturesToProcess.clear();
531 return out;
532}
533
Josep del Riod0746382023-07-29 13:18:25 +0000534std::optional<int32_t> TouchpadInputMapper::getAssociatedDisplayId() {
535 return mDisplayId;
536}
537
Harry Cutts79cc9fa2022-10-28 15:32:39 +0000538} // namespace android