blob: ca4dd1e806daf939a0236879bea7c9a9d613575a [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 = {
61 {10.922, 3.19, 0},
62 {31.750, 4.79, -17.526},
63 {98.044, 7.28, -96.52},
64 {std::numeric_limits<double>::infinity(), 15.04, -857.758},
65};
66
Wenxin Fenge0320e72023-04-08 19:26:02 -070067const std::vector<double> sensitivityFactors = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 14, 16, 18};
Harry Cuttsd35a24b2023-01-30 15:09:30 +000068
69std::vector<double> createAccelerationCurveForSensitivity(int32_t sensitivity,
70 size_t propertySize) {
71 LOG_ALWAYS_FATAL_IF(propertySize < 4 * segments.size());
72 std::vector<double> output(propertySize, 0);
73
74 // The Gestures library uses functions of the following form to define curve segments, where a,
75 // b, and c can be specified by us:
76 // output_speed(input_speed_mm) = a * input_speed_mm ^ 2 + b * input_speed_mm + c
77 //
78 // (a, b, and c are also called sqr_, mul_, and int_ in the Gestures library code.)
79 //
80 // We are trying to implement the following function, where slope and intercept are the
81 // parameters specified in the `segments` array above:
82 // gain(input_speed_mm) =
83 // 0.64 * (sensitivityFactor / 10) * (slope + intercept / input_speed_mm)
84 // Where "gain" is a multiplier applied to the input speed to produce the output speed:
85 // output_speed(input_speed_mm) = input_speed_mm * gain(input_speed_mm)
86 //
87 // To put our function in the library's form, we substitute it into the function above:
88 // output_speed(input_speed_mm) =
89 // input_speed_mm * (0.64 * (sensitivityFactor / 10) *
90 // (slope + 25.4 * intercept / input_speed_mm))
91 // then expand the brackets so that input_speed_mm cancels out for the intercept term:
92 // gain(input_speed_mm) =
93 // 0.64 * (sensitivityFactor / 10) * slope * input_speed_mm +
94 // 0.64 * (sensitivityFactor / 10) * intercept
95 //
96 // This gives us the following parameters for the Gestures library function form:
97 // a = 0
98 // b = 0.64 * (sensitivityFactor / 10) * slope
99 // c = 0.64 * (sensitivityFactor / 10) * intercept
100
101 double commonFactor = 0.64 * sensitivityFactors[sensitivity + 7] / 10;
102
103 size_t i = 0;
104 for (CurveSegment seg : segments) {
105 // The library's curve format consists of four doubles per segment:
106 // * maximum pointer speed for the segment (mm/s)
107 // * multiplier for the x² term (a.k.a. "a" or "sqr")
108 // * multiplier for the x term (a.k.a. "b" or "mul")
109 // * the intercept (a.k.a. "c" or "int")
110 // (see struct CurveSegment in the library's AccelFilterInterpreter)
111 output[i + 0] = seg.maxPointerSpeedMmPerS;
112 output[i + 1] = 0;
113 output[i + 2] = commonFactor * seg.slope;
114 output[i + 3] = commonFactor * seg.intercept;
115 i += 4;
116 }
117
118 return output;
119}
120
Harry Cutts1f48a442022-11-15 17:38:36 +0000121short getMaxTouchCount(const InputDeviceContext& context) {
Harry Cuttsb2552152022-12-13 17:18:09 +0000122 if (context.hasScanCode(BTN_TOOL_QUINTTAP)) return 5;
123 if (context.hasScanCode(BTN_TOOL_QUADTAP)) return 4;
124 if (context.hasScanCode(BTN_TOOL_TRIPLETAP)) return 3;
125 if (context.hasScanCode(BTN_TOOL_DOUBLETAP)) return 2;
126 if (context.hasScanCode(BTN_TOOL_FINGER)) return 1;
Harry Cutts1f48a442022-11-15 17:38:36 +0000127 return 0;
128}
129
130HardwareProperties createHardwareProperties(const InputDeviceContext& context) {
131 HardwareProperties props;
132 RawAbsoluteAxisInfo absMtPositionX;
133 context.getAbsoluteAxisInfo(ABS_MT_POSITION_X, &absMtPositionX);
134 props.left = absMtPositionX.minValue;
135 props.right = absMtPositionX.maxValue;
136 props.res_x = absMtPositionX.resolution;
137
138 RawAbsoluteAxisInfo absMtPositionY;
139 context.getAbsoluteAxisInfo(ABS_MT_POSITION_Y, &absMtPositionY);
140 props.top = absMtPositionY.minValue;
141 props.bottom = absMtPositionY.maxValue;
142 props.res_y = absMtPositionY.resolution;
143
144 RawAbsoluteAxisInfo absMtOrientation;
145 context.getAbsoluteAxisInfo(ABS_MT_ORIENTATION, &absMtOrientation);
146 props.orientation_minimum = absMtOrientation.minValue;
147 props.orientation_maximum = absMtOrientation.maxValue;
148
149 RawAbsoluteAxisInfo absMtSlot;
150 context.getAbsoluteAxisInfo(ABS_MT_SLOT, &absMtSlot);
151 props.max_finger_cnt = absMtSlot.maxValue - absMtSlot.minValue + 1;
152 props.max_touch_cnt = getMaxTouchCount(context);
153
154 // T5R2 ("Track 5, Report 2") is a feature of some old Synaptics touchpads that could track 5
155 // fingers but only report the coordinates of 2 of them. We don't know of any external touchpads
156 // that did this, so assume false.
157 props.supports_t5r2 = false;
158
159 props.support_semi_mt = context.hasInputProperty(INPUT_PROP_SEMI_MT);
160 props.is_button_pad = context.hasInputProperty(INPUT_PROP_BUTTONPAD);
161
162 // Mouse-only properties, which will always be false.
163 props.has_wheel = false;
164 props.wheel_is_hi_res = false;
165
166 // Linux Kernel haptic touchpad support isn't merged yet, so for now assume that no touchpads
167 // are haptic.
168 props.is_haptic_pad = false;
169 return props;
170}
171
Harry Cutts74235542022-11-24 15:52:53 +0000172void gestureInterpreterCallback(void* clientData, const Gesture* gesture) {
173 TouchpadInputMapper* mapper = static_cast<TouchpadInputMapper*>(clientData);
174 mapper->consumeGesture(gesture);
175}
176
Harry Cuttsa34de522023-06-06 15:52:54 +0000177int32_t linuxBusToInputDeviceBusEnum(int32_t linuxBus) {
178 // When adding cases to this switch, also add them to the copy of this method in
179 // InputDeviceMetricsCollector.cpp.
180 // TODO(b/286394420): deduplicate this method with the one in InputDeviceMetricsCollector.cpp.
181 switch (linuxBus) {
182 case BUS_USB:
183 return util::INPUT_DEVICE_USAGE_REPORTED__DEVICE_BUS__USB;
184 case BUS_BLUETOOTH:
185 return util::INPUT_DEVICE_USAGE_REPORTED__DEVICE_BUS__BLUETOOTH;
186 default:
187 return util::INPUT_DEVICE_USAGE_REPORTED__DEVICE_BUS__OTHER;
188 }
189}
190
191class MetricsAccumulator {
192public:
193 static MetricsAccumulator& getInstance() {
194 static MetricsAccumulator sAccumulator;
195 return sAccumulator;
196 }
197
198 void recordFinger(const TouchpadInputMapper::MetricsIdentifier& id) { mCounters[id].fingers++; }
199
200 void recordPalm(const TouchpadInputMapper::MetricsIdentifier& id) { mCounters[id].palms++; }
201
202 // Checks whether a Gesture struct is for the end of a gesture that we log metrics for, and
203 // records it if so.
204 void processGesture(const TouchpadInputMapper::MetricsIdentifier& id, const Gesture& gesture) {
205 switch (gesture.type) {
206 case kGestureTypeFling:
207 if (gesture.details.fling.fling_state == GESTURES_FLING_START) {
208 // Indicates the end of a two-finger scroll gesture.
209 mCounters[id].twoFingerSwipeGestures++;
210 }
211 break;
212 case kGestureTypeSwipeLift:
213 mCounters[id].threeFingerSwipeGestures++;
214 break;
215 case kGestureTypeFourFingerSwipeLift:
216 mCounters[id].fourFingerSwipeGestures++;
217 break;
218 case kGestureTypePinch:
219 if (gesture.details.pinch.zoom_state == GESTURES_ZOOM_END) {
220 mCounters[id].pinchGestures++;
221 }
222 break;
223 default:
224 // We're not interested in any other gestures.
225 break;
226 }
227 }
228
229private:
230 MetricsAccumulator() {
231 AStatsManager_setPullAtomCallback(android::util::TOUCHPAD_USAGE, /*metadata=*/nullptr,
232 MetricsAccumulator::pullAtomCallback, /*cookie=*/nullptr);
233 }
234
235 ~MetricsAccumulator() { AStatsManager_clearPullAtomCallback(android::util::TOUCHPAD_USAGE); }
236
237 static AStatsManager_PullAtomCallbackReturn pullAtomCallback(int32_t atomTag,
238 AStatsEventList* outEventList,
239 void* cookie) {
240 LOG_ALWAYS_FATAL_IF(atomTag != android::util::TOUCHPAD_USAGE);
241 MetricsAccumulator& accumulator = MetricsAccumulator::getInstance();
242 accumulator.produceAtoms(outEventList);
243 accumulator.resetCounters();
244 return AStatsManager_PULL_SUCCESS;
245 }
246
247 void produceAtoms(AStatsEventList* outEventList) const {
248 for (auto& [id, counters] : mCounters) {
249 auto [busId, vendorId, productId, versionId] = id;
250 addAStatsEvent(outEventList, android::util::TOUCHPAD_USAGE, vendorId, productId,
251 versionId, linuxBusToInputDeviceBusEnum(busId), counters.fingers,
252 counters.palms, counters.twoFingerSwipeGestures,
253 counters.threeFingerSwipeGestures, counters.fourFingerSwipeGestures,
254 counters.pinchGestures);
255 }
256 }
257
258 void resetCounters() { mCounters.clear(); }
259
260 // Stores the counters for a specific touchpad model. Fields have the same meanings as those of
261 // the TouchpadUsage atom; see that definition for detailed documentation.
262 struct Counters {
263 int32_t fingers = 0;
264 int32_t palms = 0;
265
266 int32_t twoFingerSwipeGestures = 0;
267 int32_t threeFingerSwipeGestures = 0;
268 int32_t fourFingerSwipeGestures = 0;
269 int32_t pinchGestures = 0;
270 };
271
272 // Metrics are aggregated by device model and version, so if two devices of the same model and
273 // version are connected at once, they will have the same counters.
274 std::map<TouchpadInputMapper::MetricsIdentifier, Counters> mCounters;
275};
276
Harry Cutts1f48a442022-11-15 17:38:36 +0000277} // namespace
278
Arpit Singh8e6fb252023-04-06 11:49:17 +0000279TouchpadInputMapper::TouchpadInputMapper(InputDeviceContext& deviceContext,
280 const InputReaderConfiguration& readerConfig)
281 : InputMapper(deviceContext, readerConfig),
Harry Cutts1f48a442022-11-15 17:38:36 +0000282 mGestureInterpreter(NewGestureInterpreter(), DeleteGestureInterpreter),
Harry Cutts74235542022-11-24 15:52:53 +0000283 mPointerController(getContext()->getPointerController(getDeviceId())),
Harry Cuttsbb24e272023-03-21 10:49:47 +0000284 mStateConverter(deviceContext, mMotionAccumulator),
285 mGestureConverter(*getContext(), deviceContext, getDeviceId()),
Harry Cuttsa34de522023-06-06 15:52:54 +0000286 mCapturedEventConverter(*getContext(), deviceContext, mMotionAccumulator, getDeviceId()),
287 mMetricsId(metricsIdFromInputDeviceIdentifier(deviceContext.getDeviceIdentifier())) {
Harry Cuttsbb24e272023-03-21 10:49:47 +0000288 RawAbsoluteAxisInfo slotAxisInfo;
289 deviceContext.getAbsoluteAxisInfo(ABS_MT_SLOT, &slotAxisInfo);
290 if (!slotAxisInfo.valid || slotAxisInfo.maxValue <= 0) {
291 ALOGW("Touchpad \"%s\" doesn't have a valid ABS_MT_SLOT axis, and probably won't work "
292 "properly.",
293 deviceContext.getName().c_str());
294 }
295 mMotionAccumulator.configure(deviceContext, slotAxisInfo.maxValue + 1, true);
296
Harry Cutts1f48a442022-11-15 17:38:36 +0000297 mGestureInterpreter->Initialize(GESTURES_DEVCLASS_TOUCHPAD);
298 mGestureInterpreter->SetHardwareProperties(createHardwareProperties(deviceContext));
Harry Cutts74235542022-11-24 15:52:53 +0000299 // Even though we don't explicitly delete copy/move semantics, it's safe to
Harry Cutts1b217912023-01-03 17:13:19 +0000300 // give away pointers to TouchpadInputMapper and its members here because
Harry Cutts74235542022-11-24 15:52:53 +0000301 // 1) mGestureInterpreter's lifecycle is determined by TouchpadInputMapper, and
302 // 2) TouchpadInputMapper is stored as a unique_ptr and not moved.
Harry Cutts1b217912023-01-03 17:13:19 +0000303 mGestureInterpreter->SetPropProvider(const_cast<GesturesPropProvider*>(&gesturePropProvider),
304 &mPropertyProvider);
Harry Cutts74235542022-11-24 15:52:53 +0000305 mGestureInterpreter->SetCallback(gestureInterpreterCallback, this);
Harry Cutts1f48a442022-11-15 17:38:36 +0000306 // TODO(b/251196347): set a timer provider, so the library can use timers.
Harry Cutts1f48a442022-11-15 17:38:36 +0000307}
Harry Cutts79cc9fa2022-10-28 15:32:39 +0000308
Harry Cutts74235542022-11-24 15:52:53 +0000309TouchpadInputMapper::~TouchpadInputMapper() {
310 if (mPointerController != nullptr) {
311 mPointerController->fade(PointerControllerInterface::Transition::IMMEDIATE);
312 }
Harry Cutts1b217912023-01-03 17:13:19 +0000313
314 // The gesture interpreter's destructor will call its property provider's free function for all
315 // gesture properties, in this case calling PropertyProvider::freeProperty using a raw pointer
316 // to mPropertyProvider. Depending on the declaration order in TouchpadInputMapper.h, this may
317 // happen after mPropertyProvider has been destructed, causing allocation errors. Depending on
318 // declaration order to avoid crashes seems rather fragile, so explicitly clear the property
319 // provider here to ensure all the freeProperty calls happen before mPropertyProvider is
320 // destructed.
321 mGestureInterpreter->SetPropProvider(nullptr, nullptr);
Harry Cutts74235542022-11-24 15:52:53 +0000322}
323
Harry Cutts79cc9fa2022-10-28 15:32:39 +0000324uint32_t TouchpadInputMapper::getSources() const {
325 return AINPUT_SOURCE_MOUSE | AINPUT_SOURCE_TOUCHPAD;
326}
327
Harry Cuttsd02ea102023-03-17 18:21:30 +0000328void TouchpadInputMapper::populateDeviceInfo(InputDeviceInfo& info) {
Harry Cutts8cd2abd2023-03-15 16:35:56 +0000329 InputMapper::populateDeviceInfo(info);
Harry Cuttsbb24e272023-03-21 10:49:47 +0000330 if (mPointerCaptured) {
331 mCapturedEventConverter.populateMotionRanges(info);
332 } else {
333 mGestureConverter.populateMotionRanges(info);
334 }
Harry Cutts8cd2abd2023-03-15 16:35:56 +0000335}
336
Harry Cuttsea73eaa2023-01-16 17:55:46 +0000337void TouchpadInputMapper::dump(std::string& dump) {
338 dump += INDENT2 "Touchpad Input Mapper:\n";
Harry Cuttsbb24e272023-03-21 10:49:47 +0000339 if (mProcessing) {
340 dump += INDENT3 "Currently processing a hardware state\n";
341 }
342 if (mResettingInterpreter) {
343 dump += INDENT3 "Currently resetting gesture interpreter\n";
344 }
345 dump += StringPrintf(INDENT3 "Pointer captured: %s\n", toString(mPointerCaptured));
Harry Cuttsea73eaa2023-01-16 17:55:46 +0000346 dump += INDENT3 "Gesture converter:\n";
347 dump += addLinePrefix(mGestureConverter.dump(), INDENT4);
348 dump += INDENT3 "Gesture properties:\n";
349 dump += addLinePrefix(mPropertyProvider.dump(), INDENT4);
Harry Cuttsbb24e272023-03-21 10:49:47 +0000350 dump += INDENT3 "Captured event converter:\n";
351 dump += addLinePrefix(mCapturedEventConverter.dump(), INDENT4);
Harry Cuttsea73eaa2023-01-16 17:55:46 +0000352}
353
Arpit Singh4be4eef2023-03-28 14:26:01 +0000354std::list<NotifyArgs> TouchpadInputMapper::reconfigure(nsecs_t when,
Arpit Singhed6c3de2023-04-05 19:24:37 +0000355 const InputReaderConfiguration& config,
Prabir Pradhan4bf6d452023-04-18 21:26:56 +0000356 ConfigurationChanges changes) {
357 if (!changes.any()) {
Harry Cutts2b67ff12023-03-13 11:32:06 +0000358 // First time configuration
359 mPropertyProvider.loadPropertiesFromIdcFile(getDeviceContext().getConfiguration());
360 }
361
Prabir Pradhan4bf6d452023-04-18 21:26:56 +0000362 if (!changes.any() || changes.test(InputReaderConfiguration::Change::DISPLAY_INFO)) {
Harry Cuttsedf6ce72023-01-04 12:15:53 +0000363 std::optional<int32_t> displayId = mPointerController->getDisplayId();
364 ui::Rotation orientation = ui::ROTATION_0;
365 if (displayId.has_value()) {
Arpit Singhed6c3de2023-04-05 19:24:37 +0000366 if (auto viewport = config.getDisplayViewportById(*displayId); viewport) {
Harry Cuttsedf6ce72023-01-04 12:15:53 +0000367 orientation = getInverseRotation(viewport->orientation);
368 }
369 }
370 mGestureConverter.setOrientation(orientation);
371 }
Prabir Pradhan4bf6d452023-04-18 21:26:56 +0000372 if (!changes.any() || changes.test(InputReaderConfiguration::Change::TOUCHPAD_SETTINGS)) {
Harry Cuttsd35a24b2023-01-30 15:09:30 +0000373 mPropertyProvider.getProperty("Use Custom Touchpad Pointer Accel Curve")
374 .setBoolValues({true});
375 GesturesProp accelCurveProp = mPropertyProvider.getProperty("Pointer Accel Curve");
376 accelCurveProp.setRealValues(
Arpit Singhed6c3de2023-04-05 19:24:37 +0000377 createAccelerationCurveForSensitivity(config.touchpadPointerSpeed,
Harry Cuttsd35a24b2023-01-30 15:09:30 +0000378 accelCurveProp.getCount()));
Wenxin Feng1ca50662023-05-03 14:00:12 -0700379 mPropertyProvider.getProperty("Use Custom Touchpad Scroll Accel Curve")
380 .setBoolValues({true});
381 GesturesProp scrollCurveProp = mPropertyProvider.getProperty("Scroll Accel Curve");
382 scrollCurveProp.setRealValues(
383 createAccelerationCurveForSensitivity(config.touchpadPointerSpeed,
384 scrollCurveProp.getCount()));
385 mPropertyProvider.getProperty("Scroll X Out Scale").setRealValues({1.0});
386 mPropertyProvider.getProperty("Scroll Y Out Scale").setRealValues({1.0});
Harry Cuttsa546ba82023-01-13 17:21:00 +0000387 mPropertyProvider.getProperty("Invert Scrolling")
Arpit Singhed6c3de2023-04-05 19:24:37 +0000388 .setBoolValues({config.touchpadNaturalScrollingEnabled});
Harry Cuttsa546ba82023-01-13 17:21:00 +0000389 mPropertyProvider.getProperty("Tap Enable")
Arpit Singhed6c3de2023-04-05 19:24:37 +0000390 .setBoolValues({config.touchpadTapToClickEnabled});
Harry Cuttsa546ba82023-01-13 17:21:00 +0000391 mPropertyProvider.getProperty("Button Right Click Zone Enable")
Arpit Singhed6c3de2023-04-05 19:24:37 +0000392 .setBoolValues({config.touchpadRightClickZoneEnabled});
Harry Cuttsa546ba82023-01-13 17:21:00 +0000393 }
Harry Cuttsbb24e272023-03-21 10:49:47 +0000394 std::list<NotifyArgs> out;
395 if ((!changes.any() && config.pointerCaptureRequest.enable) ||
396 changes.test(InputReaderConfiguration::Change::POINTER_CAPTURE)) {
397 mPointerCaptured = config.pointerCaptureRequest.enable;
398 // The motion ranges are going to change, so bump the generation to clear the cached ones.
399 bumpGeneration();
400 if (mPointerCaptured) {
401 // The touchpad is being captured, so we need to tidy up any fake fingers etc. that are
402 // still being reported for a gesture in progress.
403 out += reset(when);
404 mPointerController->fade(PointerControllerInterface::Transition::IMMEDIATE);
405 } else {
406 // We're transitioning from captured to uncaptured.
407 mCapturedEventConverter.reset();
408 }
409 if (changes.any()) {
410 out.push_back(NotifyDeviceResetArgs(getContext()->getNextId(), when, getDeviceId()));
411 }
412 }
413 return out;
Harry Cuttsedf6ce72023-01-04 12:15:53 +0000414}
415
Harry Cutts1f48a442022-11-15 17:38:36 +0000416std::list<NotifyArgs> TouchpadInputMapper::reset(nsecs_t when) {
Harry Cutts47db1c72022-12-13 19:20:47 +0000417 mStateConverter.reset();
Harry Cuttsbb24e272023-03-21 10:49:47 +0000418 resetGestureInterpreter(when);
Harry Cuttse9b71422023-03-14 16:54:44 +0000419 std::list<NotifyArgs> out = mGestureConverter.reset(when);
420 out += InputMapper::reset(when);
421 return out;
Harry Cutts1f48a442022-11-15 17:38:36 +0000422}
423
Harry Cuttsbb24e272023-03-21 10:49:47 +0000424void TouchpadInputMapper::resetGestureInterpreter(nsecs_t when) {
425 // The GestureInterpreter has no official reset method, but sending a HardwareState with no
426 // fingers down or buttons pressed should get it into a clean state.
427 HardwareState state;
428 state.timestamp = std::chrono::duration<stime_t>(std::chrono::nanoseconds(when)).count();
429 mResettingInterpreter = true;
430 mGestureInterpreter->PushHardwareState(&state);
431 mResettingInterpreter = false;
432}
433
Harry Cutts79cc9fa2022-10-28 15:32:39 +0000434std::list<NotifyArgs> TouchpadInputMapper::process(const RawEvent* rawEvent) {
Harry Cuttsbb24e272023-03-21 10:49:47 +0000435 if (mPointerCaptured) {
436 return mCapturedEventConverter.process(*rawEvent);
437 }
Harry Cutts47db1c72022-12-13 19:20:47 +0000438 std::optional<SelfContainedHardwareState> state = mStateConverter.processRawEvent(rawEvent);
439 if (state) {
Harry Cuttsa34de522023-06-06 15:52:54 +0000440 updatePalmDetectionMetrics();
Harry Cutts47db1c72022-12-13 19:20:47 +0000441 return sendHardwareState(rawEvent->when, rawEvent->readTime, *state);
442 } else {
443 return {};
Harry Cutts1f48a442022-11-15 17:38:36 +0000444 }
Harry Cutts79cc9fa2022-10-28 15:32:39 +0000445}
446
Harry Cuttsa34de522023-06-06 15:52:54 +0000447void TouchpadInputMapper::updatePalmDetectionMetrics() {
448 std::set<int32_t> currentTrackingIds;
449 for (size_t i = 0; i < mMotionAccumulator.getSlotCount(); i++) {
450 const MultiTouchMotionAccumulator::Slot& slot = mMotionAccumulator.getSlot(i);
451 if (!slot.isInUse()) {
452 continue;
453 }
454 currentTrackingIds.insert(slot.getTrackingId());
455 if (slot.getToolType() == ToolType::PALM) {
456 mPalmTrackingIds.insert(slot.getTrackingId());
457 }
458 }
459 std::vector<int32_t> liftedTouches;
460 std::set_difference(mLastFrameTrackingIds.begin(), mLastFrameTrackingIds.end(),
461 currentTrackingIds.begin(), currentTrackingIds.end(),
462 std::inserter(liftedTouches, liftedTouches.begin()));
463 for (int32_t trackingId : liftedTouches) {
464 if (mPalmTrackingIds.erase(trackingId) > 0) {
465 MetricsAccumulator::getInstance().recordPalm(mMetricsId);
466 } else {
467 MetricsAccumulator::getInstance().recordFinger(mMetricsId);
468 }
469 }
470 mLastFrameTrackingIds = currentTrackingIds;
471}
472
Harry Cutts47db1c72022-12-13 19:20:47 +0000473std::list<NotifyArgs> TouchpadInputMapper::sendHardwareState(nsecs_t when, nsecs_t readTime,
474 SelfContainedHardwareState schs) {
Harry Cutts287e19f2023-02-27 17:09:24 +0000475 ALOGD_IF(DEBUG_TOUCHPAD_GESTURES, "New hardware state: %s", schs.state.String().c_str());
Harry Cutts74235542022-11-24 15:52:53 +0000476 mProcessing = true;
Harry Cutts47db1c72022-12-13 19:20:47 +0000477 mGestureInterpreter->PushHardwareState(&schs.state);
Harry Cutts74235542022-11-24 15:52:53 +0000478 mProcessing = false;
479
Harry Cutts47db1c72022-12-13 19:20:47 +0000480 return processGestures(when, readTime);
Harry Cutts74235542022-11-24 15:52:53 +0000481}
482
483void TouchpadInputMapper::consumeGesture(const Gesture* gesture) {
Harry Cuttsc5025372023-02-21 16:04:45 +0000484 ALOGD_IF(DEBUG_TOUCHPAD_GESTURES, "Gesture ready: %s", gesture->String().c_str());
Harry Cuttsbb24e272023-03-21 10:49:47 +0000485 if (mResettingInterpreter) {
486 // We already handle tidying up fake fingers etc. in GestureConverter::reset, so we should
487 // ignore any gestures produced from the interpreter while we're resetting it.
488 return;
489 }
Harry Cutts74235542022-11-24 15:52:53 +0000490 if (!mProcessing) {
491 ALOGE("Received gesture outside of the normal processing flow; ignoring it.");
492 return;
493 }
494 mGesturesToProcess.push_back(*gesture);
495}
496
497std::list<NotifyArgs> TouchpadInputMapper::processGestures(nsecs_t when, nsecs_t readTime) {
498 std::list<NotifyArgs> out = {};
Harry Cuttsa34de522023-06-06 15:52:54 +0000499 MetricsAccumulator& metricsAccumulator = MetricsAccumulator::getInstance();
Harry Cutts74235542022-11-24 15:52:53 +0000500 for (Gesture& gesture : mGesturesToProcess) {
Harry Cutts4fb941a2022-12-14 19:14:04 +0000501 out += mGestureConverter.handleGesture(when, readTime, gesture);
Harry Cuttsa34de522023-06-06 15:52:54 +0000502 metricsAccumulator.processGesture(mMetricsId, gesture);
Harry Cutts74235542022-11-24 15:52:53 +0000503 }
504 mGesturesToProcess.clear();
505 return out;
506}
507
Harry Cutts79cc9fa2022-10-28 15:32:39 +0000508} // namespace android