blob: c3c9fdb63aa1f361fe1af3142cba87f2ec9ceb3c [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 Cutts3952c832023-08-22 15:26:56 +000036#include "gestures/HardwareProperties.h"
Harry Cuttsedf6ce72023-01-04 12:15:53 +000037#include "ui/Rotation.h"
Harry Cutts79cc9fa2022-10-28 15:32:39 +000038
39namespace android {
40
Harry Cutts1f48a442022-11-15 17:38:36 +000041namespace {
42
Harry Cuttsc5025372023-02-21 16:04:45 +000043/**
44 * Log details of each gesture output by the gestures library.
45 * Enable this via "adb shell setprop log.tag.TouchpadInputMapperGestures DEBUG" (requires
46 * restarting the shell)
47 */
48const bool DEBUG_TOUCHPAD_GESTURES =
49 __android_log_is_loggable(ANDROID_LOG_DEBUG, "TouchpadInputMapperGestures",
50 ANDROID_LOG_INFO);
51
Harry Cuttsd35a24b2023-01-30 15:09:30 +000052// Describes a segment of the acceleration curve.
53struct CurveSegment {
54 // The maximum pointer speed which this segment should apply. The last segment in a curve should
55 // always set this to infinity.
56 double maxPointerSpeedMmPerS;
57 double slope;
58 double intercept;
59};
60
61const std::vector<CurveSegment> segments = {
Wenxin Fenge5d6d042023-07-06 17:40:45 -070062 {32.002, 3.19, 0},
63 {52.83, 4.79, -51.254},
64 {119.124, 7.28, -182.737},
65 {std::numeric_limits<double>::infinity(), 15.04, -1107.556},
Harry Cuttsd35a24b2023-01-30 15:09:30 +000066};
67
Wenxin Fenge5d6d042023-07-06 17:40:45 -070068const std::vector<double> sensitivityFactors = {1, 2, 4, 6, 7, 8, 9, 10,
69 11, 12, 13, 14, 16, 18, 20};
Harry Cuttsd35a24b2023-01-30 15:09:30 +000070
71std::vector<double> createAccelerationCurveForSensitivity(int32_t sensitivity,
72 size_t propertySize) {
73 LOG_ALWAYS_FATAL_IF(propertySize < 4 * segments.size());
74 std::vector<double> output(propertySize, 0);
75
76 // The Gestures library uses functions of the following form to define curve segments, where a,
77 // b, and c can be specified by us:
78 // output_speed(input_speed_mm) = a * input_speed_mm ^ 2 + b * input_speed_mm + c
79 //
80 // (a, b, and c are also called sqr_, mul_, and int_ in the Gestures library code.)
81 //
82 // We are trying to implement the following function, where slope and intercept are the
83 // parameters specified in the `segments` array above:
84 // gain(input_speed_mm) =
85 // 0.64 * (sensitivityFactor / 10) * (slope + intercept / input_speed_mm)
86 // Where "gain" is a multiplier applied to the input speed to produce the output speed:
87 // output_speed(input_speed_mm) = input_speed_mm * gain(input_speed_mm)
88 //
89 // To put our function in the library's form, we substitute it into the function above:
90 // output_speed(input_speed_mm) =
91 // input_speed_mm * (0.64 * (sensitivityFactor / 10) *
92 // (slope + 25.4 * intercept / input_speed_mm))
93 // then expand the brackets so that input_speed_mm cancels out for the intercept term:
94 // gain(input_speed_mm) =
95 // 0.64 * (sensitivityFactor / 10) * slope * input_speed_mm +
96 // 0.64 * (sensitivityFactor / 10) * intercept
97 //
98 // This gives us the following parameters for the Gestures library function form:
99 // a = 0
100 // b = 0.64 * (sensitivityFactor / 10) * slope
101 // c = 0.64 * (sensitivityFactor / 10) * intercept
102
103 double commonFactor = 0.64 * sensitivityFactors[sensitivity + 7] / 10;
104
105 size_t i = 0;
106 for (CurveSegment seg : segments) {
107 // The library's curve format consists of four doubles per segment:
108 // * maximum pointer speed for the segment (mm/s)
109 // * multiplier for the x² term (a.k.a. "a" or "sqr")
110 // * multiplier for the x term (a.k.a. "b" or "mul")
111 // * the intercept (a.k.a. "c" or "int")
112 // (see struct CurveSegment in the library's AccelFilterInterpreter)
113 output[i + 0] = seg.maxPointerSpeedMmPerS;
114 output[i + 1] = 0;
115 output[i + 2] = commonFactor * seg.slope;
116 output[i + 3] = commonFactor * seg.intercept;
117 i += 4;
118 }
119
120 return output;
121}
122
Harry Cutts74235542022-11-24 15:52:53 +0000123void gestureInterpreterCallback(void* clientData, const Gesture* gesture) {
124 TouchpadInputMapper* mapper = static_cast<TouchpadInputMapper*>(clientData);
125 mapper->consumeGesture(gesture);
126}
127
Prabir Pradhan67d09ca2023-09-08 20:28:55 +0000128int32_t linuxBusToInputDeviceBusEnum(int32_t linuxBus, bool isUsiStylus) {
129 if (isUsiStylus) {
130 // This is a stylus connected over the Universal Stylus Initiative (USI) protocol.
131 // For metrics purposes, we treat this protocol as a separate bus.
132 return util::INPUT_DEVICE_USAGE_REPORTED__DEVICE_BUS__USI;
133 }
134
Harry Cuttsa34de522023-06-06 15:52:54 +0000135 // When adding cases to this switch, also add them to the copy of this method in
136 // InputDeviceMetricsCollector.cpp.
137 // TODO(b/286394420): deduplicate this method with the one in InputDeviceMetricsCollector.cpp.
138 switch (linuxBus) {
139 case BUS_USB:
140 return util::INPUT_DEVICE_USAGE_REPORTED__DEVICE_BUS__USB;
141 case BUS_BLUETOOTH:
142 return util::INPUT_DEVICE_USAGE_REPORTED__DEVICE_BUS__BLUETOOTH;
143 default:
144 return util::INPUT_DEVICE_USAGE_REPORTED__DEVICE_BUS__OTHER;
145 }
146}
147
148class MetricsAccumulator {
149public:
150 static MetricsAccumulator& getInstance() {
151 static MetricsAccumulator sAccumulator;
152 return sAccumulator;
153 }
154
155 void recordFinger(const TouchpadInputMapper::MetricsIdentifier& id) { mCounters[id].fingers++; }
156
157 void recordPalm(const TouchpadInputMapper::MetricsIdentifier& id) { mCounters[id].palms++; }
158
159 // Checks whether a Gesture struct is for the end of a gesture that we log metrics for, and
160 // records it if so.
161 void processGesture(const TouchpadInputMapper::MetricsIdentifier& id, const Gesture& gesture) {
162 switch (gesture.type) {
163 case kGestureTypeFling:
164 if (gesture.details.fling.fling_state == GESTURES_FLING_START) {
165 // Indicates the end of a two-finger scroll gesture.
166 mCounters[id].twoFingerSwipeGestures++;
167 }
168 break;
169 case kGestureTypeSwipeLift:
170 mCounters[id].threeFingerSwipeGestures++;
171 break;
172 case kGestureTypeFourFingerSwipeLift:
173 mCounters[id].fourFingerSwipeGestures++;
174 break;
175 case kGestureTypePinch:
176 if (gesture.details.pinch.zoom_state == GESTURES_ZOOM_END) {
177 mCounters[id].pinchGestures++;
178 }
179 break;
180 default:
181 // We're not interested in any other gestures.
182 break;
183 }
184 }
185
186private:
187 MetricsAccumulator() {
188 AStatsManager_setPullAtomCallback(android::util::TOUCHPAD_USAGE, /*metadata=*/nullptr,
189 MetricsAccumulator::pullAtomCallback, /*cookie=*/nullptr);
190 }
191
192 ~MetricsAccumulator() { AStatsManager_clearPullAtomCallback(android::util::TOUCHPAD_USAGE); }
193
194 static AStatsManager_PullAtomCallbackReturn pullAtomCallback(int32_t atomTag,
195 AStatsEventList* outEventList,
196 void* cookie) {
197 LOG_ALWAYS_FATAL_IF(atomTag != android::util::TOUCHPAD_USAGE);
198 MetricsAccumulator& accumulator = MetricsAccumulator::getInstance();
199 accumulator.produceAtoms(outEventList);
200 accumulator.resetCounters();
201 return AStatsManager_PULL_SUCCESS;
202 }
203
204 void produceAtoms(AStatsEventList* outEventList) const {
205 for (auto& [id, counters] : mCounters) {
206 auto [busId, vendorId, productId, versionId] = id;
207 addAStatsEvent(outEventList, android::util::TOUCHPAD_USAGE, vendorId, productId,
Prabir Pradhan67d09ca2023-09-08 20:28:55 +0000208 versionId, linuxBusToInputDeviceBusEnum(busId, /*isUsi=*/false),
209 counters.fingers, counters.palms, counters.twoFingerSwipeGestures,
Harry Cuttsa34de522023-06-06 15:52:54 +0000210 counters.threeFingerSwipeGestures, counters.fourFingerSwipeGestures,
211 counters.pinchGestures);
212 }
213 }
214
215 void resetCounters() { mCounters.clear(); }
216
217 // Stores the counters for a specific touchpad model. Fields have the same meanings as those of
218 // the TouchpadUsage atom; see that definition for detailed documentation.
219 struct Counters {
220 int32_t fingers = 0;
221 int32_t palms = 0;
222
223 int32_t twoFingerSwipeGestures = 0;
224 int32_t threeFingerSwipeGestures = 0;
225 int32_t fourFingerSwipeGestures = 0;
226 int32_t pinchGestures = 0;
227 };
228
229 // Metrics are aggregated by device model and version, so if two devices of the same model and
230 // version are connected at once, they will have the same counters.
231 std::map<TouchpadInputMapper::MetricsIdentifier, Counters> mCounters;
232};
233
Harry Cutts1f48a442022-11-15 17:38:36 +0000234} // namespace
235
Arpit Singh8e6fb252023-04-06 11:49:17 +0000236TouchpadInputMapper::TouchpadInputMapper(InputDeviceContext& deviceContext,
237 const InputReaderConfiguration& readerConfig)
238 : InputMapper(deviceContext, readerConfig),
Harry Cutts1f48a442022-11-15 17:38:36 +0000239 mGestureInterpreter(NewGestureInterpreter(), DeleteGestureInterpreter),
Harry Cutts74235542022-11-24 15:52:53 +0000240 mPointerController(getContext()->getPointerController(getDeviceId())),
Harry Cuttsbb24e272023-03-21 10:49:47 +0000241 mStateConverter(deviceContext, mMotionAccumulator),
242 mGestureConverter(*getContext(), deviceContext, getDeviceId()),
Harry Cuttsa34de522023-06-06 15:52:54 +0000243 mCapturedEventConverter(*getContext(), deviceContext, mMotionAccumulator, getDeviceId()),
244 mMetricsId(metricsIdFromInputDeviceIdentifier(deviceContext.getDeviceIdentifier())) {
Harry Cuttsbb24e272023-03-21 10:49:47 +0000245 RawAbsoluteAxisInfo slotAxisInfo;
246 deviceContext.getAbsoluteAxisInfo(ABS_MT_SLOT, &slotAxisInfo);
247 if (!slotAxisInfo.valid || slotAxisInfo.maxValue <= 0) {
248 ALOGW("Touchpad \"%s\" doesn't have a valid ABS_MT_SLOT axis, and probably won't work "
249 "properly.",
250 deviceContext.getName().c_str());
251 }
252 mMotionAccumulator.configure(deviceContext, slotAxisInfo.maxValue + 1, true);
253
Harry Cutts1f48a442022-11-15 17:38:36 +0000254 mGestureInterpreter->Initialize(GESTURES_DEVCLASS_TOUCHPAD);
255 mGestureInterpreter->SetHardwareProperties(createHardwareProperties(deviceContext));
Harry Cutts74235542022-11-24 15:52:53 +0000256 // Even though we don't explicitly delete copy/move semantics, it's safe to
Harry Cutts1b217912023-01-03 17:13:19 +0000257 // give away pointers to TouchpadInputMapper and its members here because
Harry Cutts74235542022-11-24 15:52:53 +0000258 // 1) mGestureInterpreter's lifecycle is determined by TouchpadInputMapper, and
259 // 2) TouchpadInputMapper is stored as a unique_ptr and not moved.
Harry Cutts1b217912023-01-03 17:13:19 +0000260 mGestureInterpreter->SetPropProvider(const_cast<GesturesPropProvider*>(&gesturePropProvider),
261 &mPropertyProvider);
Harry Cutts74235542022-11-24 15:52:53 +0000262 mGestureInterpreter->SetCallback(gestureInterpreterCallback, this);
Harry Cutts1f48a442022-11-15 17:38:36 +0000263 // TODO(b/251196347): set a timer provider, so the library can use timers.
Harry Cutts1f48a442022-11-15 17:38:36 +0000264}
Harry Cutts79cc9fa2022-10-28 15:32:39 +0000265
Harry Cutts74235542022-11-24 15:52:53 +0000266TouchpadInputMapper::~TouchpadInputMapper() {
267 if (mPointerController != nullptr) {
268 mPointerController->fade(PointerControllerInterface::Transition::IMMEDIATE);
269 }
Harry Cutts1b217912023-01-03 17:13:19 +0000270
271 // The gesture interpreter's destructor will call its property provider's free function for all
272 // gesture properties, in this case calling PropertyProvider::freeProperty using a raw pointer
273 // to mPropertyProvider. Depending on the declaration order in TouchpadInputMapper.h, this may
274 // happen after mPropertyProvider has been destructed, causing allocation errors. Depending on
275 // declaration order to avoid crashes seems rather fragile, so explicitly clear the property
276 // provider here to ensure all the freeProperty calls happen before mPropertyProvider is
277 // destructed.
278 mGestureInterpreter->SetPropProvider(nullptr, nullptr);
Harry Cutts74235542022-11-24 15:52:53 +0000279}
280
Harry Cutts79cc9fa2022-10-28 15:32:39 +0000281uint32_t TouchpadInputMapper::getSources() const {
282 return AINPUT_SOURCE_MOUSE | AINPUT_SOURCE_TOUCHPAD;
283}
284
Harry Cuttsd02ea102023-03-17 18:21:30 +0000285void TouchpadInputMapper::populateDeviceInfo(InputDeviceInfo& info) {
Harry Cutts8cd2abd2023-03-15 16:35:56 +0000286 InputMapper::populateDeviceInfo(info);
Harry Cuttsbb24e272023-03-21 10:49:47 +0000287 if (mPointerCaptured) {
288 mCapturedEventConverter.populateMotionRanges(info);
289 } else {
290 mGestureConverter.populateMotionRanges(info);
291 }
Harry Cutts8cd2abd2023-03-15 16:35:56 +0000292}
293
Harry Cuttsea73eaa2023-01-16 17:55:46 +0000294void TouchpadInputMapper::dump(std::string& dump) {
295 dump += INDENT2 "Touchpad Input Mapper:\n";
Harry Cuttsbb24e272023-03-21 10:49:47 +0000296 if (mProcessing) {
297 dump += INDENT3 "Currently processing a hardware state\n";
298 }
299 if (mResettingInterpreter) {
300 dump += INDENT3 "Currently resetting gesture interpreter\n";
301 }
302 dump += StringPrintf(INDENT3 "Pointer captured: %s\n", toString(mPointerCaptured));
Harry Cuttsea73eaa2023-01-16 17:55:46 +0000303 dump += INDENT3 "Gesture converter:\n";
304 dump += addLinePrefix(mGestureConverter.dump(), INDENT4);
305 dump += INDENT3 "Gesture properties:\n";
306 dump += addLinePrefix(mPropertyProvider.dump(), INDENT4);
Harry Cuttsbb24e272023-03-21 10:49:47 +0000307 dump += INDENT3 "Captured event converter:\n";
308 dump += addLinePrefix(mCapturedEventConverter.dump(), INDENT4);
Josep del Riod0746382023-07-29 13:18:25 +0000309 dump += StringPrintf(INDENT3 "DisplayId: %s\n", toString(mDisplayId).c_str());
Harry Cuttsea73eaa2023-01-16 17:55:46 +0000310}
311
Arpit Singh4be4eef2023-03-28 14:26:01 +0000312std::list<NotifyArgs> TouchpadInputMapper::reconfigure(nsecs_t when,
Arpit Singhed6c3de2023-04-05 19:24:37 +0000313 const InputReaderConfiguration& config,
Prabir Pradhan4bf6d452023-04-18 21:26:56 +0000314 ConfigurationChanges changes) {
315 if (!changes.any()) {
Harry Cutts2b67ff12023-03-13 11:32:06 +0000316 // First time configuration
317 mPropertyProvider.loadPropertiesFromIdcFile(getDeviceContext().getConfiguration());
318 }
319
Prabir Pradhan4bf6d452023-04-18 21:26:56 +0000320 if (!changes.any() || changes.test(InputReaderConfiguration::Change::DISPLAY_INFO)) {
Josep del Riod0746382023-07-29 13:18:25 +0000321 mDisplayId = ADISPLAY_ID_NONE;
322 if (auto viewport = mDeviceContext.getAssociatedViewport(); viewport) {
323 // This InputDevice is associated with a viewport.
324 // Only generate events for the associated display.
325 const bool mismatchedPointerDisplay =
326 (viewport->displayId != mPointerController->getDisplayId());
327 if (mismatchedPointerDisplay) {
328 ALOGW("Touchpad \"%s\" associated viewport display does not match pointer "
329 "controller",
330 mDeviceContext.getName().c_str());
331 }
332 mDisplayId = mismatchedPointerDisplay ? std::nullopt
333 : std::make_optional(viewport->displayId);
334 } else {
335 // The InputDevice is not associated with a viewport, but it controls the mouse pointer.
336 mDisplayId = mPointerController->getDisplayId();
337 }
338
Harry Cuttsedf6ce72023-01-04 12:15:53 +0000339 ui::Rotation orientation = ui::ROTATION_0;
Josep del Riod0746382023-07-29 13:18:25 +0000340 if (mDisplayId.has_value()) {
341 if (auto viewport = config.getDisplayViewportById(*mDisplayId); viewport) {
Harry Cuttsedf6ce72023-01-04 12:15:53 +0000342 orientation = getInverseRotation(viewport->orientation);
343 }
344 }
Josep del Riod0746382023-07-29 13:18:25 +0000345 mGestureConverter.setDisplayId(mDisplayId);
Harry Cuttsedf6ce72023-01-04 12:15:53 +0000346 mGestureConverter.setOrientation(orientation);
347 }
Prabir Pradhan4bf6d452023-04-18 21:26:56 +0000348 if (!changes.any() || changes.test(InputReaderConfiguration::Change::TOUCHPAD_SETTINGS)) {
Harry Cuttsd35a24b2023-01-30 15:09:30 +0000349 mPropertyProvider.getProperty("Use Custom Touchpad Pointer Accel Curve")
350 .setBoolValues({true});
351 GesturesProp accelCurveProp = mPropertyProvider.getProperty("Pointer Accel Curve");
352 accelCurveProp.setRealValues(
Arpit Singhed6c3de2023-04-05 19:24:37 +0000353 createAccelerationCurveForSensitivity(config.touchpadPointerSpeed,
Harry Cuttsd35a24b2023-01-30 15:09:30 +0000354 accelCurveProp.getCount()));
Wenxin Feng1ca50662023-05-03 14:00:12 -0700355 mPropertyProvider.getProperty("Use Custom Touchpad Scroll Accel Curve")
356 .setBoolValues({true});
357 GesturesProp scrollCurveProp = mPropertyProvider.getProperty("Scroll Accel Curve");
358 scrollCurveProp.setRealValues(
359 createAccelerationCurveForSensitivity(config.touchpadPointerSpeed,
360 scrollCurveProp.getCount()));
361 mPropertyProvider.getProperty("Scroll X Out Scale").setRealValues({1.0});
362 mPropertyProvider.getProperty("Scroll Y Out Scale").setRealValues({1.0});
Harry Cuttsa546ba82023-01-13 17:21:00 +0000363 mPropertyProvider.getProperty("Invert Scrolling")
Arpit Singhed6c3de2023-04-05 19:24:37 +0000364 .setBoolValues({config.touchpadNaturalScrollingEnabled});
Harry Cuttsa546ba82023-01-13 17:21:00 +0000365 mPropertyProvider.getProperty("Tap Enable")
Arpit Singhed6c3de2023-04-05 19:24:37 +0000366 .setBoolValues({config.touchpadTapToClickEnabled});
Harry Cuttsa546ba82023-01-13 17:21:00 +0000367 mPropertyProvider.getProperty("Button Right Click Zone Enable")
Arpit Singhed6c3de2023-04-05 19:24:37 +0000368 .setBoolValues({config.touchpadRightClickZoneEnabled});
Harry Cuttsa546ba82023-01-13 17:21:00 +0000369 }
Harry Cuttsbb24e272023-03-21 10:49:47 +0000370 std::list<NotifyArgs> out;
371 if ((!changes.any() && config.pointerCaptureRequest.enable) ||
372 changes.test(InputReaderConfiguration::Change::POINTER_CAPTURE)) {
373 mPointerCaptured = config.pointerCaptureRequest.enable;
374 // The motion ranges are going to change, so bump the generation to clear the cached ones.
375 bumpGeneration();
376 if (mPointerCaptured) {
377 // The touchpad is being captured, so we need to tidy up any fake fingers etc. that are
378 // still being reported for a gesture in progress.
379 out += reset(when);
380 mPointerController->fade(PointerControllerInterface::Transition::IMMEDIATE);
381 } else {
382 // We're transitioning from captured to uncaptured.
383 mCapturedEventConverter.reset();
384 }
385 if (changes.any()) {
386 out.push_back(NotifyDeviceResetArgs(getContext()->getNextId(), when, getDeviceId()));
387 }
388 }
389 return out;
Harry Cuttsedf6ce72023-01-04 12:15:53 +0000390}
391
Harry Cutts1f48a442022-11-15 17:38:36 +0000392std::list<NotifyArgs> TouchpadInputMapper::reset(nsecs_t when) {
Harry Cutts47db1c72022-12-13 19:20:47 +0000393 mStateConverter.reset();
Harry Cuttsbb24e272023-03-21 10:49:47 +0000394 resetGestureInterpreter(when);
Harry Cuttse9b71422023-03-14 16:54:44 +0000395 std::list<NotifyArgs> out = mGestureConverter.reset(when);
396 out += InputMapper::reset(when);
397 return out;
Harry Cutts1f48a442022-11-15 17:38:36 +0000398}
399
Harry Cuttsbb24e272023-03-21 10:49:47 +0000400void TouchpadInputMapper::resetGestureInterpreter(nsecs_t when) {
401 // The GestureInterpreter has no official reset method, but sending a HardwareState with no
402 // fingers down or buttons pressed should get it into a clean state.
403 HardwareState state;
404 state.timestamp = std::chrono::duration<stime_t>(std::chrono::nanoseconds(when)).count();
405 mResettingInterpreter = true;
406 mGestureInterpreter->PushHardwareState(&state);
407 mResettingInterpreter = false;
408}
409
Harry Cutts79cc9fa2022-10-28 15:32:39 +0000410std::list<NotifyArgs> TouchpadInputMapper::process(const RawEvent* rawEvent) {
Harry Cuttsbb24e272023-03-21 10:49:47 +0000411 if (mPointerCaptured) {
412 return mCapturedEventConverter.process(*rawEvent);
413 }
Harry Cutts47db1c72022-12-13 19:20:47 +0000414 std::optional<SelfContainedHardwareState> state = mStateConverter.processRawEvent(rawEvent);
415 if (state) {
Harry Cuttsa34de522023-06-06 15:52:54 +0000416 updatePalmDetectionMetrics();
Harry Cutts47db1c72022-12-13 19:20:47 +0000417 return sendHardwareState(rawEvent->when, rawEvent->readTime, *state);
418 } else {
419 return {};
Harry Cutts1f48a442022-11-15 17:38:36 +0000420 }
Harry Cutts79cc9fa2022-10-28 15:32:39 +0000421}
422
Harry Cuttsa34de522023-06-06 15:52:54 +0000423void TouchpadInputMapper::updatePalmDetectionMetrics() {
424 std::set<int32_t> currentTrackingIds;
425 for (size_t i = 0; i < mMotionAccumulator.getSlotCount(); i++) {
426 const MultiTouchMotionAccumulator::Slot& slot = mMotionAccumulator.getSlot(i);
427 if (!slot.isInUse()) {
428 continue;
429 }
430 currentTrackingIds.insert(slot.getTrackingId());
431 if (slot.getToolType() == ToolType::PALM) {
432 mPalmTrackingIds.insert(slot.getTrackingId());
433 }
434 }
435 std::vector<int32_t> liftedTouches;
436 std::set_difference(mLastFrameTrackingIds.begin(), mLastFrameTrackingIds.end(),
437 currentTrackingIds.begin(), currentTrackingIds.end(),
438 std::inserter(liftedTouches, liftedTouches.begin()));
439 for (int32_t trackingId : liftedTouches) {
440 if (mPalmTrackingIds.erase(trackingId) > 0) {
441 MetricsAccumulator::getInstance().recordPalm(mMetricsId);
442 } else {
443 MetricsAccumulator::getInstance().recordFinger(mMetricsId);
444 }
445 }
446 mLastFrameTrackingIds = currentTrackingIds;
447}
448
Harry Cutts47db1c72022-12-13 19:20:47 +0000449std::list<NotifyArgs> TouchpadInputMapper::sendHardwareState(nsecs_t when, nsecs_t readTime,
450 SelfContainedHardwareState schs) {
Harry Cutts287e19f2023-02-27 17:09:24 +0000451 ALOGD_IF(DEBUG_TOUCHPAD_GESTURES, "New hardware state: %s", schs.state.String().c_str());
Harry Cutts74235542022-11-24 15:52:53 +0000452 mProcessing = true;
Harry Cutts47db1c72022-12-13 19:20:47 +0000453 mGestureInterpreter->PushHardwareState(&schs.state);
Harry Cutts74235542022-11-24 15:52:53 +0000454 mProcessing = false;
455
Harry Cutts47db1c72022-12-13 19:20:47 +0000456 return processGestures(when, readTime);
Harry Cutts74235542022-11-24 15:52:53 +0000457}
458
459void TouchpadInputMapper::consumeGesture(const Gesture* gesture) {
Harry Cuttsc5025372023-02-21 16:04:45 +0000460 ALOGD_IF(DEBUG_TOUCHPAD_GESTURES, "Gesture ready: %s", gesture->String().c_str());
Harry Cuttsbb24e272023-03-21 10:49:47 +0000461 if (mResettingInterpreter) {
462 // We already handle tidying up fake fingers etc. in GestureConverter::reset, so we should
463 // ignore any gestures produced from the interpreter while we're resetting it.
464 return;
465 }
Harry Cutts74235542022-11-24 15:52:53 +0000466 if (!mProcessing) {
467 ALOGE("Received gesture outside of the normal processing flow; ignoring it.");
468 return;
469 }
470 mGesturesToProcess.push_back(*gesture);
471}
472
473std::list<NotifyArgs> TouchpadInputMapper::processGestures(nsecs_t when, nsecs_t readTime) {
474 std::list<NotifyArgs> out = {};
Josep del Riod0746382023-07-29 13:18:25 +0000475 if (mDisplayId) {
476 MetricsAccumulator& metricsAccumulator = MetricsAccumulator::getInstance();
477 for (Gesture& gesture : mGesturesToProcess) {
478 out += mGestureConverter.handleGesture(when, readTime, gesture);
479 metricsAccumulator.processGesture(mMetricsId, gesture);
480 }
Harry Cutts74235542022-11-24 15:52:53 +0000481 }
482 mGesturesToProcess.clear();
483 return out;
484}
485
Josep del Riod0746382023-07-29 13:18:25 +0000486std::optional<int32_t> TouchpadInputMapper::getAssociatedDisplayId() {
487 return mDisplayId;
488}
489
Harry Cutts79cc9fa2022-10-28 15:32:39 +0000490} // namespace android