• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
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 
19 #include <algorithm>
20 #include <chrono>
21 #include <iterator>
22 #include <limits>
23 #include <map>
24 #include <mutex>
25 #include <optional>
26 
27 #include <android-base/logging.h>
28 #include <android-base/stringprintf.h>
29 #include <android-base/thread_annotations.h>
30 #include <android/input.h>
31 #include <com_android_input_flags.h>
32 #include <ftl/enum.h>
33 #include <input/AccelerationCurve.h>
34 #include <input/PrintTools.h>
35 #include <linux/input-event-codes.h>
36 #include <log/log_main.h>
37 #include <stats_pull_atom_callback.h>
38 #include <statslog.h>
39 #include "InputReaderBase.h"
40 #include "TouchCursorInputMapperCommon.h"
41 #include "TouchpadInputMapper.h"
42 #include "gestures/HardwareProperties.h"
43 #include "gestures/Logging.h"
44 #include "gestures/TimerProvider.h"
45 #include "ui/Rotation.h"
46 
47 namespace input_flags = com::android::input::flags;
48 
49 namespace android {
50 
51 namespace {
52 
createAccelerationCurveForSensitivity(int32_t sensitivity,bool accelerationEnabled,size_t propertySize)53 std::vector<double> createAccelerationCurveForSensitivity(int32_t sensitivity,
54                                                           bool accelerationEnabled,
55                                                           size_t propertySize) {
56     std::vector<AccelerationCurveSegment> segments = accelerationEnabled
57             ? createAccelerationCurveForPointerSensitivity(sensitivity)
58             : createFlatAccelerationCurve(sensitivity);
59     LOG_ALWAYS_FATAL_IF(propertySize < 4 * segments.size());
60     std::vector<double> output(propertySize, 0);
61 
62     // The Gestures library uses functions of the following form to define curve segments, where a,
63     // b, and c can be specified by us:
64     //     output_speed(input_speed_mm) = a * input_speed_mm ^ 2 + b * input_speed_mm + c
65     //
66     // (a, b, and c are also called sqr_, mul_, and int_ in the Gestures library code.)
67     //
68     // createAccelerationCurveForPointerSensitivity gives us parameters for a function of the form:
69     //     gain(input_speed_mm) = baseGain + reciprocal / input_speed_mm
70     // Where "gain" is a multiplier applied to the input speed to produce the output speed:
71     //     output_speed(input_speed_mm) = input_speed_mm * gain(input_speed_mm)
72     //
73     // To put our function in the library's form, we substitute it into the function above:
74     //     output_speed(input_speed_mm) = input_speed_mm * (baseGain + reciprocal / input_speed_mm)
75     // then expand the brackets so that input_speed_mm cancels out for the reciprocal term:
76     //     gain(input_speed_mm) = baseGain * input_speed_mm + reciprocal
77     //
78     // This gives us the following parameters for the Gestures library function form:
79     //     a = 0
80     //     b = baseGain
81     //     c = reciprocal
82 
83     size_t i = 0;
84     for (AccelerationCurveSegment seg : segments) {
85         // The library's curve format consists of four doubles per segment:
86         // * maximum pointer speed for the segment (mm/s)
87         // * multiplier for the x² term (a.k.a. "a" or "sqr")
88         // * multiplier for the x term (a.k.a. "b" or "mul")
89         // * the intercept (a.k.a. "c" or "int")
90         // (see struct CurveSegment in the library's AccelFilterInterpreter)
91         output[i + 0] = seg.maxPointerSpeedMmPerS;
92         output[i + 1] = 0;
93         output[i + 2] = seg.baseGain;
94         output[i + 3] = seg.reciprocal;
95         i += 4;
96     }
97 
98     return output;
99 }
100 
gestureInterpreterCallback(void * clientData,const Gesture * gesture)101 void gestureInterpreterCallback(void* clientData, const Gesture* gesture) {
102     TouchpadInputMapper* mapper = static_cast<TouchpadInputMapper*>(clientData);
103     mapper->consumeGesture(gesture);
104 }
105 
linuxBusToInputDeviceBusEnum(int32_t linuxBus,bool isUsiStylus)106 int32_t linuxBusToInputDeviceBusEnum(int32_t linuxBus, bool isUsiStylus) {
107     if (isUsiStylus) {
108         // This is a stylus connected over the Universal Stylus Initiative (USI) protocol.
109         // For metrics purposes, we treat this protocol as a separate bus.
110         return util::INPUT_DEVICE_USAGE_REPORTED__DEVICE_BUS__USI;
111     }
112 
113     // When adding cases to this switch, also add them to the copy of this method in
114     // InputDeviceMetricsCollector.cpp.
115     // TODO(b/286394420): deduplicate this method with the one in InputDeviceMetricsCollector.cpp.
116     switch (linuxBus) {
117         case BUS_USB:
118             return util::INPUT_DEVICE_USAGE_REPORTED__DEVICE_BUS__USB;
119         case BUS_BLUETOOTH:
120             return util::INPUT_DEVICE_USAGE_REPORTED__DEVICE_BUS__BLUETOOTH;
121         default:
122             return util::INPUT_DEVICE_USAGE_REPORTED__DEVICE_BUS__OTHER;
123     }
124 }
125 
126 class MetricsAccumulator {
127 public:
getInstance()128     static MetricsAccumulator& getInstance() {
129         static MetricsAccumulator sAccumulator;
130         return sAccumulator;
131     }
132 
recordFinger(const TouchpadInputMapper::MetricsIdentifier & id)133     void recordFinger(const TouchpadInputMapper::MetricsIdentifier& id) {
134         std::scoped_lock lock(mLock);
135         mCounters[id].fingers++;
136     }
137 
recordPalm(const TouchpadInputMapper::MetricsIdentifier & id)138     void recordPalm(const TouchpadInputMapper::MetricsIdentifier& id) {
139         std::scoped_lock lock(mLock);
140         mCounters[id].palms++;
141     }
142 
143     // Checks whether a Gesture struct is for the end of a gesture that we log metrics for, and
144     // records it if so.
processGesture(const TouchpadInputMapper::MetricsIdentifier & id,const Gesture & gesture)145     void processGesture(const TouchpadInputMapper::MetricsIdentifier& id, const Gesture& gesture) {
146         std::scoped_lock lock(mLock);
147         Counters& counters = mCounters[id];
148         switch (gesture.type) {
149             case kGestureTypeFling:
150                 if (gesture.details.fling.fling_state == GESTURES_FLING_START) {
151                     // Indicates the end of a two-finger scroll gesture.
152                     counters.twoFingerSwipeGestures++;
153                 }
154                 break;
155             case kGestureTypeSwipeLift:
156                 // The Gestures library occasionally outputs two lift gestures in a row, which can
157                 // cause inaccurate metrics reporting. To work around this, deduplicate successive
158                 // lift gestures.
159                 // TODO(b/404529050): fix the Gestures library, and remove this check.
160                 if (counters.lastGestureType != kGestureTypeSwipeLift) {
161                     counters.threeFingerSwipeGestures++;
162                 }
163                 break;
164             case kGestureTypeFourFingerSwipeLift:
165                 // TODO(b/404529050): fix the Gestures library, and remove this check.
166                 if (counters.lastGestureType != kGestureTypeFourFingerSwipeLift) {
167                     counters.fourFingerSwipeGestures++;
168                 }
169                 break;
170             case kGestureTypePinch:
171                 if (gesture.details.pinch.zoom_state == GESTURES_ZOOM_END) {
172                     counters.pinchGestures++;
173                 }
174                 break;
175             default:
176                 // We're not interested in any other gestures.
177                 break;
178         }
179         counters.lastGestureType = gesture.type;
180     }
181 
182 private:
MetricsAccumulator()183     MetricsAccumulator() {
184         AStatsManager_setPullAtomCallback(android::util::TOUCHPAD_USAGE, /*metadata=*/nullptr,
185                                           MetricsAccumulator::pullAtomCallback, /*cookie=*/nullptr);
186     }
187 
~MetricsAccumulator()188     ~MetricsAccumulator() { AStatsManager_clearPullAtomCallback(android::util::TOUCHPAD_USAGE); }
189 
pullAtomCallback(int32_t atomTag,AStatsEventList * outEventList,void * cookie)190     static AStatsManager_PullAtomCallbackReturn pullAtomCallback(int32_t atomTag,
191                                                                  AStatsEventList* outEventList,
192                                                                  void* cookie) {
193         LOG_ALWAYS_FATAL_IF(atomTag != android::util::TOUCHPAD_USAGE);
194         MetricsAccumulator& accumulator = MetricsAccumulator::getInstance();
195         accumulator.produceAtomsAndReset(*outEventList);
196         return AStatsManager_PULL_SUCCESS;
197     }
198 
produceAtomsAndReset(AStatsEventList & outEventList)199     void produceAtomsAndReset(AStatsEventList& outEventList) {
200         std::scoped_lock lock(mLock);
201         produceAtomsLocked(outEventList);
202         resetCountersLocked();
203     }
204 
produceAtomsLocked(AStatsEventList & outEventList) const205     void produceAtomsLocked(AStatsEventList& outEventList) const REQUIRES(mLock) {
206         for (auto& [id, counters] : mCounters) {
207             auto [busId, vendorId, productId, versionId] = id;
208             addAStatsEvent(&outEventList, android::util::TOUCHPAD_USAGE, vendorId, productId,
209                            versionId, linuxBusToInputDeviceBusEnum(busId, /*isUsi=*/false),
210                            counters.fingers, counters.palms, counters.twoFingerSwipeGestures,
211                            counters.threeFingerSwipeGestures, counters.fourFingerSwipeGestures,
212                            counters.pinchGestures);
213         }
214     }
215 
resetCountersLocked()216     void resetCountersLocked() REQUIRES(mLock) { mCounters.clear(); }
217 
218     // Stores the counters for a specific touchpad model. Fields have the same meanings as those of
219     // the TouchpadUsage atom; see that definition for detailed documentation.
220     struct Counters {
221         int32_t fingers = 0;
222         int32_t palms = 0;
223 
224         int32_t twoFingerSwipeGestures = 0;
225         int32_t threeFingerSwipeGestures = 0;
226         int32_t fourFingerSwipeGestures = 0;
227         int32_t pinchGestures = 0;
228 
229         // Records the last type of gesture received for this device, for deduplication purposes.
230         // TODO(b/404529050): fix the Gestures library and remove this field.
231         GestureType lastGestureType = kGestureTypeContactInitiated;
232     };
233 
234     // Metrics are aggregated by device model and version, so if two devices of the same model and
235     // version are connected at once, they will have the same counters.
236     std::map<TouchpadInputMapper::MetricsIdentifier, Counters> mCounters GUARDED_BY(mLock);
237 
238     // Metrics are pulled by a binder thread, so we need to guard them with a mutex.
239     mutable std::mutex mLock;
240 };
241 
242 } // namespace
243 
TouchpadInputMapper(InputDeviceContext & deviceContext,const InputReaderConfiguration & readerConfig)244 TouchpadInputMapper::TouchpadInputMapper(InputDeviceContext& deviceContext,
245                                          const InputReaderConfiguration& readerConfig)
246       : InputMapper(deviceContext, readerConfig),
247         mGestureInterpreter(NewGestureInterpreter(), DeleteGestureInterpreter),
248         mTimerProvider(*getContext()),
249         mStateConverter(deviceContext, mMotionAccumulator),
250         mGestureConverter(*getContext(), deviceContext, getDeviceId()),
251         mCapturedEventConverter(*getContext(), deviceContext, mMotionAccumulator, getDeviceId()),
252         mMetricsId(metricsIdFromInputDeviceIdentifier(deviceContext.getDeviceIdentifier())) {
253     if (std::optional<RawAbsoluteAxisInfo> slotAxis =
254                 deviceContext.getAbsoluteAxisInfo(ABS_MT_SLOT);
255         slotAxis && slotAxis->maxValue >= 0) {
256         mMotionAccumulator.configure(deviceContext, slotAxis->maxValue + 1, true);
257     } else {
258         LOG(WARNING) << "Touchpad " << deviceContext.getName()
259                      << " doesn't have a valid ABS_MT_SLOT axis, and probably won't work properly.";
260         mMotionAccumulator.configure(deviceContext, 1, true);
261     }
262 
263     mGestureInterpreter->Initialize(GESTURES_DEVCLASS_TOUCHPAD);
264     mHardwareProperties = createHardwareProperties(deviceContext);
265     mGestureInterpreter->SetHardwareProperties(mHardwareProperties);
266     // Even though we don't explicitly delete copy/move semantics, it's safe to
267     // give away pointers to TouchpadInputMapper and its members here because
268     // 1) mGestureInterpreter's lifecycle is determined by TouchpadInputMapper, and
269     // 2) TouchpadInputMapper is stored as a unique_ptr and not moved.
270     mGestureInterpreter->SetPropProvider(const_cast<GesturesPropProvider*>(&gesturePropProvider),
271                                          &mPropertyProvider);
272     mGestureInterpreter->SetTimerProvider(const_cast<GesturesTimerProvider*>(
273                                                   &kGestureTimerProvider),
274                                           &mTimerProvider);
275     mGestureInterpreter->SetCallback(gestureInterpreterCallback, this);
276 }
277 
~TouchpadInputMapper()278 TouchpadInputMapper::~TouchpadInputMapper() {
279     // The gesture interpreter's destructor will try to free its property and timer providers,
280     // calling PropertyProvider::freeProperty and TimerProvider::freeTimer using a raw pointers.
281     // Depending on the declaration order in TouchpadInputMapper.h, those providers may have already
282     // been freed, causing allocation errors or use-after-free bugs. Depending on declaration order
283     // to avoid this seems rather fragile, so explicitly clear the providers here to ensure all the
284     // freeProperty and freeTimer calls happen before the providers are destructed.
285     mGestureInterpreter->SetPropProvider(nullptr, nullptr);
286     mGestureInterpreter->SetTimerProvider(nullptr, nullptr);
287 }
288 
getSources() const289 uint32_t TouchpadInputMapper::getSources() const {
290     return AINPUT_SOURCE_MOUSE | AINPUT_SOURCE_TOUCHPAD;
291 }
292 
populateDeviceInfo(InputDeviceInfo & info)293 void TouchpadInputMapper::populateDeviceInfo(InputDeviceInfo& info) {
294     InputMapper::populateDeviceInfo(info);
295     if (mPointerCaptured) {
296         mCapturedEventConverter.populateMotionRanges(info);
297     } else {
298         mGestureConverter.populateMotionRanges(info);
299     }
300 }
301 
dump(std::string & dump)302 void TouchpadInputMapper::dump(std::string& dump) {
303     dump += INDENT2 "Touchpad Input Mapper:\n";
304     if (mResettingInterpreter) {
305         dump += INDENT3 "Currently resetting gesture interpreter\n";
306     }
307     dump += StringPrintf(INDENT3 "Pointer captured: %s\n", toString(mPointerCaptured));
308     dump += INDENT3 "Gesture converter:\n";
309     dump += addLinePrefix(mGestureConverter.dump(), INDENT4);
310     dump += INDENT3 "Gesture properties:\n";
311     dump += addLinePrefix(mPropertyProvider.dump(), INDENT4);
312     dump += INDENT3 "Timer provider:\n";
313     dump += addLinePrefix(mTimerProvider.dump(), INDENT4);
314     dump += INDENT3 "Captured event converter:\n";
315     dump += addLinePrefix(mCapturedEventConverter.dump(), INDENT4);
316     dump += StringPrintf(INDENT3 "DisplayId: %s\n",
317                          toString(mDisplayId, streamableToString).c_str());
318 }
319 
reconfigure(nsecs_t when,const InputReaderConfiguration & config,ConfigurationChanges changes)320 std::list<NotifyArgs> TouchpadInputMapper::reconfigure(nsecs_t when,
321                                                        const InputReaderConfiguration& config,
322                                                        ConfigurationChanges changes) {
323     if (!changes.any()) {
324         // First time configuration
325         mPropertyProvider.loadPropertiesFromIdcFile(getDeviceContext().getConfiguration());
326     }
327 
328     if (!changes.any() || changes.test(InputReaderConfiguration::Change::DISPLAY_INFO)) {
329         mDisplayId = ui::LogicalDisplayId::INVALID;
330         std::optional<DisplayViewport> resolvedViewport;
331         std::optional<FloatRect> boundsInLogicalDisplay;
332         if (auto assocViewport = mDeviceContext.getAssociatedViewport(); assocViewport) {
333             // This InputDevice is associated with a viewport.
334             // Only generate events for the associated display.
335             mDisplayId = assocViewport->displayId;
336             resolvedViewport = *assocViewport;
337         } else {
338             // The InputDevice is not associated with a viewport, but it controls the mouse pointer.
339             // Always use DISPLAY_ID_NONE for touchpad events.
340             // PointerChoreographer will make it target the correct the displayId later.
341             resolvedViewport = getContext()->getPolicy()->getPointerViewportForAssociatedDisplay();
342             mDisplayId = resolvedViewport ? std::make_optional(ui::LogicalDisplayId::INVALID)
343                                           : std::nullopt;
344         }
345 
346         mGestureConverter.setDisplayId(mDisplayId);
347         mGestureConverter.setOrientation(resolvedViewport
348                                                  ? getInverseRotation(resolvedViewport->orientation)
349                                                  : ui::ROTATION_0);
350 
351         if (!boundsInLogicalDisplay) {
352             boundsInLogicalDisplay = resolvedViewport
353                     ? FloatRect{static_cast<float>(resolvedViewport->logicalLeft),
354                                 static_cast<float>(resolvedViewport->logicalTop),
355                                 static_cast<float>(resolvedViewport->logicalRight - 1),
356                                 static_cast<float>(resolvedViewport->logicalBottom - 1)}
357                     : FloatRect{0, 0, 0, 0};
358         }
359         mGestureConverter.setBoundsInLogicalDisplay(*boundsInLogicalDisplay);
360 
361         bumpGeneration();
362     }
363     std::list<NotifyArgs> out;
364     if (!changes.any() || changes.test(InputReaderConfiguration::Change::TOUCHPAD_SETTINGS)) {
365         mPropertyProvider.getProperty("Use Custom Touchpad Pointer Accel Curve")
366                 .setBoolValues({true});
367         GesturesProp accelCurveProp = mPropertyProvider.getProperty("Pointer Accel Curve");
368         accelCurveProp.setRealValues(
369                 createAccelerationCurveForSensitivity(config.touchpadPointerSpeed,
370                                                       config.touchpadAccelerationEnabled,
371                                                       accelCurveProp.getCount()));
372         mPropertyProvider.getProperty("Use Custom Touchpad Scroll Accel Curve")
373                 .setBoolValues({true});
374         GesturesProp scrollCurveProp = mPropertyProvider.getProperty("Scroll Accel Curve");
375         scrollCurveProp.setRealValues(
376                 createAccelerationCurveForSensitivity(config.touchpadPointerSpeed,
377                                                       config.touchpadAccelerationEnabled,
378                                                       scrollCurveProp.getCount()));
379         mPropertyProvider.getProperty("Scroll X Out Scale").setRealValues({1.0});
380         mPropertyProvider.getProperty("Scroll Y Out Scale").setRealValues({1.0});
381         mPropertyProvider.getProperty("Invert Scrolling")
382                 .setBoolValues({config.touchpadNaturalScrollingEnabled});
383         mPropertyProvider.getProperty("Tap Enable")
384                 .setBoolValues({config.touchpadTapToClickEnabled});
385         mPropertyProvider.getProperty("Tap Drag Enable")
386                 .setBoolValues({config.touchpadTapDraggingEnabled});
387         mPropertyProvider.getProperty("Button Right Click Zone Enable")
388                 .setBoolValues({config.touchpadRightClickZoneEnabled});
389         mTouchpadHardwareStateNotificationsEnabled = config.shouldNotifyTouchpadHardwareState;
390         mGestureConverter.setThreeFingerTapShortcutEnabled(
391                 config.touchpadThreeFingerTapShortcutEnabled);
392         out += mGestureConverter.setEnableSystemGestures(when,
393                                                          config.touchpadSystemGesturesEnabled);
394     }
395     if ((!changes.any() && config.pointerCaptureRequest.isEnable()) ||
396         changes.test(InputReaderConfiguration::Change::POINTER_CAPTURE)) {
397         mPointerCaptured = config.pointerCaptureRequest.isEnable();
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         } else {
405             // We're transitioning from captured to uncaptured.
406             mCapturedEventConverter.reset();
407         }
408         if (changes.any()) {
409             out.push_back(NotifyDeviceResetArgs(getContext()->getNextId(), when, getDeviceId()));
410         }
411     }
412     return out;
413 }
414 
reset(nsecs_t when)415 std::list<NotifyArgs> TouchpadInputMapper::reset(nsecs_t when) {
416     mStateConverter.reset();
417     resetGestureInterpreter(when);
418     std::list<NotifyArgs> out = mGestureConverter.reset(when);
419     out += InputMapper::reset(when);
420     return out;
421 }
422 
resetGestureInterpreter(nsecs_t when)423 void TouchpadInputMapper::resetGestureInterpreter(nsecs_t when) {
424     // The GestureInterpreter has no official reset method, but sending a HardwareState with no
425     // fingers down or buttons pressed should get it into a clean state.
426     HardwareState state;
427     state.timestamp = std::chrono::duration<stime_t>(std::chrono::nanoseconds(when)).count();
428     mResettingInterpreter = true;
429     mGestureInterpreter->PushHardwareState(&state);
430     mResettingInterpreter = false;
431 }
432 
process(const RawEvent & rawEvent)433 std::list<NotifyArgs> TouchpadInputMapper::process(const RawEvent& rawEvent) {
434     if (mPointerCaptured) {
435         return mCapturedEventConverter.process(rawEvent);
436     }
437     if (mMotionAccumulator.getActiveSlotsCount() == 0) {
438         mGestureStartTime = rawEvent.when;
439     }
440     std::optional<SelfContainedHardwareState> state = mStateConverter.processRawEvent(rawEvent);
441     if (state) {
442         if (mTouchpadHardwareStateNotificationsEnabled) {
443             getPolicy()->notifyTouchpadHardwareState(*state, getDeviceId());
444         }
445         updatePalmDetectionMetrics();
446         return sendHardwareState(rawEvent.when, rawEvent.readTime, *state);
447     } else {
448         return {};
449     }
450 }
451 
updatePalmDetectionMetrics()452 void TouchpadInputMapper::updatePalmDetectionMetrics() {
453     std::set<int32_t> currentTrackingIds;
454     for (size_t i = 0; i < mMotionAccumulator.getSlotCount(); i++) {
455         const MultiTouchMotionAccumulator::Slot& slot = mMotionAccumulator.getSlot(i);
456         if (!slot.isInUse()) {
457             continue;
458         }
459         currentTrackingIds.insert(slot.getTrackingId());
460         if (slot.getToolType() == ToolType::PALM) {
461             mPalmTrackingIds.insert(slot.getTrackingId());
462         }
463     }
464     std::vector<int32_t> liftedTouches;
465     std::set_difference(mLastFrameTrackingIds.begin(), mLastFrameTrackingIds.end(),
466                         currentTrackingIds.begin(), currentTrackingIds.end(),
467                         std::inserter(liftedTouches, liftedTouches.begin()));
468     for (int32_t trackingId : liftedTouches) {
469         if (mPalmTrackingIds.erase(trackingId) > 0) {
470             MetricsAccumulator::getInstance().recordPalm(mMetricsId);
471         } else {
472             MetricsAccumulator::getInstance().recordFinger(mMetricsId);
473         }
474     }
475     mLastFrameTrackingIds = currentTrackingIds;
476 }
477 
sendHardwareState(nsecs_t when,nsecs_t readTime,SelfContainedHardwareState schs)478 std::list<NotifyArgs> TouchpadInputMapper::sendHardwareState(nsecs_t when, nsecs_t readTime,
479                                                              SelfContainedHardwareState schs) {
480     ALOGD_IF(debugTouchpadGestures(), "New hardware state: %s", schs.state.String().c_str());
481     mGestureInterpreter->PushHardwareState(&schs.state);
482     return processGestures(when, readTime);
483 }
484 
timeoutExpired(nsecs_t when)485 std::list<NotifyArgs> TouchpadInputMapper::timeoutExpired(nsecs_t when) {
486     mTimerProvider.triggerCallbacks(when);
487     return processGestures(when, when);
488 }
489 
consumeGesture(const Gesture * gesture)490 void TouchpadInputMapper::consumeGesture(const Gesture* gesture) {
491     ALOGD_IF(debugTouchpadGestures(), "Gesture ready: %s", gesture->String().c_str());
492     if (mResettingInterpreter) {
493         // We already handle tidying up fake fingers etc. in GestureConverter::reset, so we should
494         // ignore any gestures produced from the interpreter while we're resetting it.
495         return;
496     }
497     mGesturesToProcess.push_back(*gesture);
498     if (mTouchpadHardwareStateNotificationsEnabled) {
499         getPolicy()->notifyTouchpadGestureInfo(gesture->type, getDeviceId());
500     }
501 }
502 
processGestures(nsecs_t when,nsecs_t readTime)503 std::list<NotifyArgs> TouchpadInputMapper::processGestures(nsecs_t when, nsecs_t readTime) {
504     std::list<NotifyArgs> out = {};
505     if (mDisplayId) {
506         MetricsAccumulator& metricsAccumulator = MetricsAccumulator::getInstance();
507         for (Gesture& gesture : mGesturesToProcess) {
508             out += mGestureConverter.handleGesture(when, readTime, mGestureStartTime, gesture);
509             metricsAccumulator.processGesture(mMetricsId, gesture);
510         }
511     }
512     mGesturesToProcess.clear();
513     return out;
514 }
515 
getAssociatedDisplayId() const516 std::optional<ui::LogicalDisplayId> TouchpadInputMapper::getAssociatedDisplayId() const {
517     return mDisplayId;
518 }
519 
getTouchpadHardwareProperties()520 std::optional<HardwareProperties> TouchpadInputMapper::getTouchpadHardwareProperties() {
521     return mHardwareProperties;
522 }
523 
getGesturePropertyForTesting(const std::string & name)524 std::optional<GesturesProp> TouchpadInputMapper::getGesturePropertyForTesting(
525         const std::string& name) {
526     if (!mPropertyProvider.hasProperty(name)) {
527         return std::nullopt;
528     }
529     return mPropertyProvider.getProperty(name);
530 }
531 
532 } // namespace android
533