blob: 255f02d278f524e880b359a26f9a63c6f1ee7782 [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 Cutts938c65d2023-12-13 19:04:02 +000024#include <mutex>
Harry Cuttsedf6ce72023-01-04 12:15:53 +000025#include <optional>
26
Harry Cuttsbb24e272023-03-21 10:49:47 +000027#include <android-base/stringprintf.h>
Harry Cutts938c65d2023-12-13 19:04:02 +000028#include <android-base/thread_annotations.h>
Harry Cutts74235542022-11-24 15:52:53 +000029#include <android/input.h>
Harry Cutts8c7cb592023-08-23 17:20:13 +000030#include <com_android_input_flags.h>
Harry Cutts2b67ff12023-03-13 11:32:06 +000031#include <ftl/enum.h>
Harry Cuttsea73eaa2023-01-16 17:55:46 +000032#include <input/PrintTools.h>
Harry Cutts4fb941a2022-12-14 19:14:04 +000033#include <linux/input-event-codes.h>
Harry Cutts74235542022-11-24 15:52:53 +000034#include <log/log_main.h>
Harry Cuttsa34de522023-06-06 15:52:54 +000035#include <stats_pull_atom_callback.h>
36#include <statslog.h>
Harry Cutts74235542022-11-24 15:52:53 +000037#include "TouchCursorInputMapperCommon.h"
Harry Cutts79cc9fa2022-10-28 15:32:39 +000038#include "TouchpadInputMapper.h"
Harry Cutts3952c832023-08-22 15:26:56 +000039#include "gestures/HardwareProperties.h"
Harry Cutts8c7cb592023-08-23 17:20:13 +000040#include "gestures/TimerProvider.h"
Harry Cuttsedf6ce72023-01-04 12:15:53 +000041#include "ui/Rotation.h"
Harry Cutts79cc9fa2022-10-28 15:32:39 +000042
Harry Cutts8c7cb592023-08-23 17:20:13 +000043namespace input_flags = com::android::input::flags;
44
Harry Cutts79cc9fa2022-10-28 15:32:39 +000045namespace android {
46
Harry Cutts1f48a442022-11-15 17:38:36 +000047namespace {
48
Harry Cuttsc5025372023-02-21 16:04:45 +000049/**
50 * Log details of each gesture output by the gestures library.
51 * Enable this via "adb shell setprop log.tag.TouchpadInputMapperGestures DEBUG" (requires
52 * restarting the shell)
53 */
54const bool DEBUG_TOUCHPAD_GESTURES =
55 __android_log_is_loggable(ANDROID_LOG_DEBUG, "TouchpadInputMapperGestures",
56 ANDROID_LOG_INFO);
57
Harry Cuttsd35a24b2023-01-30 15:09:30 +000058// Describes a segment of the acceleration curve.
59struct CurveSegment {
60 // The maximum pointer speed which this segment should apply. The last segment in a curve should
61 // always set this to infinity.
62 double maxPointerSpeedMmPerS;
63 double slope;
64 double intercept;
65};
66
67const std::vector<CurveSegment> segments = {
Wenxin Fenge5d6d042023-07-06 17:40:45 -070068 {32.002, 3.19, 0},
69 {52.83, 4.79, -51.254},
70 {119.124, 7.28, -182.737},
71 {std::numeric_limits<double>::infinity(), 15.04, -1107.556},
Harry Cuttsd35a24b2023-01-30 15:09:30 +000072};
73
Wenxin Fenge5d6d042023-07-06 17:40:45 -070074const std::vector<double> sensitivityFactors = {1, 2, 4, 6, 7, 8, 9, 10,
75 11, 12, 13, 14, 16, 18, 20};
Harry Cuttsd35a24b2023-01-30 15:09:30 +000076
77std::vector<double> createAccelerationCurveForSensitivity(int32_t sensitivity,
78 size_t propertySize) {
79 LOG_ALWAYS_FATAL_IF(propertySize < 4 * segments.size());
80 std::vector<double> output(propertySize, 0);
81
82 // The Gestures library uses functions of the following form to define curve segments, where a,
83 // b, and c can be specified by us:
84 // output_speed(input_speed_mm) = a * input_speed_mm ^ 2 + b * input_speed_mm + c
85 //
86 // (a, b, and c are also called sqr_, mul_, and int_ in the Gestures library code.)
87 //
88 // We are trying to implement the following function, where slope and intercept are the
89 // parameters specified in the `segments` array above:
90 // gain(input_speed_mm) =
91 // 0.64 * (sensitivityFactor / 10) * (slope + intercept / input_speed_mm)
92 // Where "gain" is a multiplier applied to the input speed to produce the output speed:
93 // output_speed(input_speed_mm) = input_speed_mm * gain(input_speed_mm)
94 //
95 // To put our function in the library's form, we substitute it into the function above:
96 // output_speed(input_speed_mm) =
97 // input_speed_mm * (0.64 * (sensitivityFactor / 10) *
98 // (slope + 25.4 * intercept / input_speed_mm))
99 // then expand the brackets so that input_speed_mm cancels out for the intercept term:
100 // gain(input_speed_mm) =
101 // 0.64 * (sensitivityFactor / 10) * slope * input_speed_mm +
102 // 0.64 * (sensitivityFactor / 10) * intercept
103 //
104 // This gives us the following parameters for the Gestures library function form:
105 // a = 0
106 // b = 0.64 * (sensitivityFactor / 10) * slope
107 // c = 0.64 * (sensitivityFactor / 10) * intercept
108
109 double commonFactor = 0.64 * sensitivityFactors[sensitivity + 7] / 10;
110
111 size_t i = 0;
112 for (CurveSegment seg : segments) {
113 // The library's curve format consists of four doubles per segment:
114 // * maximum pointer speed for the segment (mm/s)
115 // * multiplier for the x² term (a.k.a. "a" or "sqr")
116 // * multiplier for the x term (a.k.a. "b" or "mul")
117 // * the intercept (a.k.a. "c" or "int")
118 // (see struct CurveSegment in the library's AccelFilterInterpreter)
119 output[i + 0] = seg.maxPointerSpeedMmPerS;
120 output[i + 1] = 0;
121 output[i + 2] = commonFactor * seg.slope;
122 output[i + 3] = commonFactor * seg.intercept;
123 i += 4;
124 }
125
126 return output;
127}
128
Harry Cutts74235542022-11-24 15:52:53 +0000129void gestureInterpreterCallback(void* clientData, const Gesture* gesture) {
130 TouchpadInputMapper* mapper = static_cast<TouchpadInputMapper*>(clientData);
131 mapper->consumeGesture(gesture);
132}
133
Prabir Pradhan67d09ca2023-09-08 20:28:55 +0000134int32_t linuxBusToInputDeviceBusEnum(int32_t linuxBus, bool isUsiStylus) {
135 if (isUsiStylus) {
136 // This is a stylus connected over the Universal Stylus Initiative (USI) protocol.
137 // For metrics purposes, we treat this protocol as a separate bus.
138 return util::INPUT_DEVICE_USAGE_REPORTED__DEVICE_BUS__USI;
139 }
140
Harry Cuttsa34de522023-06-06 15:52:54 +0000141 // When adding cases to this switch, also add them to the copy of this method in
142 // InputDeviceMetricsCollector.cpp.
143 // TODO(b/286394420): deduplicate this method with the one in InputDeviceMetricsCollector.cpp.
144 switch (linuxBus) {
145 case BUS_USB:
146 return util::INPUT_DEVICE_USAGE_REPORTED__DEVICE_BUS__USB;
147 case BUS_BLUETOOTH:
148 return util::INPUT_DEVICE_USAGE_REPORTED__DEVICE_BUS__BLUETOOTH;
149 default:
150 return util::INPUT_DEVICE_USAGE_REPORTED__DEVICE_BUS__OTHER;
151 }
152}
153
154class MetricsAccumulator {
155public:
156 static MetricsAccumulator& getInstance() {
157 static MetricsAccumulator sAccumulator;
158 return sAccumulator;
159 }
160
Harry Cutts938c65d2023-12-13 19:04:02 +0000161 void recordFinger(const TouchpadInputMapper::MetricsIdentifier& id) {
162 std::scoped_lock lock(mLock);
163 mCounters[id].fingers++;
164 }
Harry Cuttsa34de522023-06-06 15:52:54 +0000165
Harry Cutts938c65d2023-12-13 19:04:02 +0000166 void recordPalm(const TouchpadInputMapper::MetricsIdentifier& id) {
167 std::scoped_lock lock(mLock);
168 mCounters[id].palms++;
169 }
Harry Cuttsa34de522023-06-06 15:52:54 +0000170
171 // Checks whether a Gesture struct is for the end of a gesture that we log metrics for, and
172 // records it if so.
173 void processGesture(const TouchpadInputMapper::MetricsIdentifier& id, const Gesture& gesture) {
Harry Cutts938c65d2023-12-13 19:04:02 +0000174 std::scoped_lock lock(mLock);
Harry Cuttsa34de522023-06-06 15:52:54 +0000175 switch (gesture.type) {
176 case kGestureTypeFling:
177 if (gesture.details.fling.fling_state == GESTURES_FLING_START) {
178 // Indicates the end of a two-finger scroll gesture.
179 mCounters[id].twoFingerSwipeGestures++;
180 }
181 break;
182 case kGestureTypeSwipeLift:
183 mCounters[id].threeFingerSwipeGestures++;
184 break;
185 case kGestureTypeFourFingerSwipeLift:
186 mCounters[id].fourFingerSwipeGestures++;
187 break;
188 case kGestureTypePinch:
189 if (gesture.details.pinch.zoom_state == GESTURES_ZOOM_END) {
190 mCounters[id].pinchGestures++;
191 }
192 break;
193 default:
194 // We're not interested in any other gestures.
195 break;
196 }
197 }
198
199private:
200 MetricsAccumulator() {
201 AStatsManager_setPullAtomCallback(android::util::TOUCHPAD_USAGE, /*metadata=*/nullptr,
202 MetricsAccumulator::pullAtomCallback, /*cookie=*/nullptr);
203 }
204
205 ~MetricsAccumulator() { AStatsManager_clearPullAtomCallback(android::util::TOUCHPAD_USAGE); }
206
207 static AStatsManager_PullAtomCallbackReturn pullAtomCallback(int32_t atomTag,
208 AStatsEventList* outEventList,
209 void* cookie) {
210 LOG_ALWAYS_FATAL_IF(atomTag != android::util::TOUCHPAD_USAGE);
211 MetricsAccumulator& accumulator = MetricsAccumulator::getInstance();
Harry Cutts938c65d2023-12-13 19:04:02 +0000212 accumulator.produceAtomsAndReset(*outEventList);
Harry Cuttsa34de522023-06-06 15:52:54 +0000213 return AStatsManager_PULL_SUCCESS;
214 }
215
Harry Cutts938c65d2023-12-13 19:04:02 +0000216 void produceAtomsAndReset(AStatsEventList& outEventList) {
217 std::scoped_lock lock(mLock);
218 produceAtomsLocked(outEventList);
219 resetCountersLocked();
220 }
221
222 void produceAtomsLocked(AStatsEventList& outEventList) const REQUIRES(mLock) {
Harry Cuttsa34de522023-06-06 15:52:54 +0000223 for (auto& [id, counters] : mCounters) {
224 auto [busId, vendorId, productId, versionId] = id;
Harry Cutts938c65d2023-12-13 19:04:02 +0000225 addAStatsEvent(&outEventList, android::util::TOUCHPAD_USAGE, vendorId, productId,
Prabir Pradhan67d09ca2023-09-08 20:28:55 +0000226 versionId, linuxBusToInputDeviceBusEnum(busId, /*isUsi=*/false),
227 counters.fingers, counters.palms, counters.twoFingerSwipeGestures,
Harry Cuttsa34de522023-06-06 15:52:54 +0000228 counters.threeFingerSwipeGestures, counters.fourFingerSwipeGestures,
229 counters.pinchGestures);
230 }
231 }
232
Harry Cutts938c65d2023-12-13 19:04:02 +0000233 void resetCountersLocked() REQUIRES(mLock) { mCounters.clear(); }
Harry Cuttsa34de522023-06-06 15:52:54 +0000234
235 // Stores the counters for a specific touchpad model. Fields have the same meanings as those of
236 // the TouchpadUsage atom; see that definition for detailed documentation.
237 struct Counters {
238 int32_t fingers = 0;
239 int32_t palms = 0;
240
241 int32_t twoFingerSwipeGestures = 0;
242 int32_t threeFingerSwipeGestures = 0;
243 int32_t fourFingerSwipeGestures = 0;
244 int32_t pinchGestures = 0;
245 };
246
247 // Metrics are aggregated by device model and version, so if two devices of the same model and
248 // version are connected at once, they will have the same counters.
Harry Cutts938c65d2023-12-13 19:04:02 +0000249 std::map<TouchpadInputMapper::MetricsIdentifier, Counters> mCounters GUARDED_BY(mLock);
250
251 // Metrics are pulled by a binder thread, so we need to guard them with a mutex.
252 mutable std::mutex mLock;
Harry Cuttsa34de522023-06-06 15:52:54 +0000253};
254
Harry Cutts1f48a442022-11-15 17:38:36 +0000255} // namespace
256
Arpit Singh8e6fb252023-04-06 11:49:17 +0000257TouchpadInputMapper::TouchpadInputMapper(InputDeviceContext& deviceContext,
258 const InputReaderConfiguration& readerConfig)
259 : InputMapper(deviceContext, readerConfig),
Harry Cutts1f48a442022-11-15 17:38:36 +0000260 mGestureInterpreter(NewGestureInterpreter(), DeleteGestureInterpreter),
Harry Cutts74235542022-11-24 15:52:53 +0000261 mPointerController(getContext()->getPointerController(getDeviceId())),
Harry Cutts8c7cb592023-08-23 17:20:13 +0000262 mTimerProvider(*getContext()),
Harry Cuttsbb24e272023-03-21 10:49:47 +0000263 mStateConverter(deviceContext, mMotionAccumulator),
264 mGestureConverter(*getContext(), deviceContext, getDeviceId()),
Harry Cuttsa34de522023-06-06 15:52:54 +0000265 mCapturedEventConverter(*getContext(), deviceContext, mMotionAccumulator, getDeviceId()),
Byoungho Jungee6268f2023-10-30 17:27:26 +0900266 mMetricsId(metricsIdFromInputDeviceIdentifier(deviceContext.getDeviceIdentifier())),
267 mEnablePointerChoreographer(input_flags::enable_pointer_choreographer()) {
Harry Cuttsbb24e272023-03-21 10:49:47 +0000268 RawAbsoluteAxisInfo slotAxisInfo;
269 deviceContext.getAbsoluteAxisInfo(ABS_MT_SLOT, &slotAxisInfo);
270 if (!slotAxisInfo.valid || slotAxisInfo.maxValue <= 0) {
271 ALOGW("Touchpad \"%s\" doesn't have a valid ABS_MT_SLOT axis, and probably won't work "
272 "properly.",
273 deviceContext.getName().c_str());
274 }
275 mMotionAccumulator.configure(deviceContext, slotAxisInfo.maxValue + 1, true);
276
Harry Cutts1f48a442022-11-15 17:38:36 +0000277 mGestureInterpreter->Initialize(GESTURES_DEVCLASS_TOUCHPAD);
278 mGestureInterpreter->SetHardwareProperties(createHardwareProperties(deviceContext));
Harry Cutts74235542022-11-24 15:52:53 +0000279 // Even though we don't explicitly delete copy/move semantics, it's safe to
Harry Cutts1b217912023-01-03 17:13:19 +0000280 // give away pointers to TouchpadInputMapper and its members here because
Harry Cutts74235542022-11-24 15:52:53 +0000281 // 1) mGestureInterpreter's lifecycle is determined by TouchpadInputMapper, and
282 // 2) TouchpadInputMapper is stored as a unique_ptr and not moved.
Harry Cutts1b217912023-01-03 17:13:19 +0000283 mGestureInterpreter->SetPropProvider(const_cast<GesturesPropProvider*>(&gesturePropProvider),
284 &mPropertyProvider);
Harry Cutts8c7cb592023-08-23 17:20:13 +0000285 if (input_flags::enable_gestures_library_timer_provider()) {
286 mGestureInterpreter->SetTimerProvider(const_cast<GesturesTimerProvider*>(
287 &kGestureTimerProvider),
288 &mTimerProvider);
289 }
Harry Cutts74235542022-11-24 15:52:53 +0000290 mGestureInterpreter->SetCallback(gestureInterpreterCallback, this);
Harry Cutts1f48a442022-11-15 17:38:36 +0000291}
Harry Cutts79cc9fa2022-10-28 15:32:39 +0000292
Harry Cutts74235542022-11-24 15:52:53 +0000293TouchpadInputMapper::~TouchpadInputMapper() {
294 if (mPointerController != nullptr) {
295 mPointerController->fade(PointerControllerInterface::Transition::IMMEDIATE);
296 }
Harry Cutts1b217912023-01-03 17:13:19 +0000297
Harry Cutts8c7cb592023-08-23 17:20:13 +0000298 // The gesture interpreter's destructor will try to free its property and timer providers,
299 // calling PropertyProvider::freeProperty and TimerProvider::freeTimer using a raw pointers.
300 // Depending on the declaration order in TouchpadInputMapper.h, those providers may have already
301 // been freed, causing allocation errors or use-after-free bugs. Depending on declaration order
302 // to avoid this seems rather fragile, so explicitly clear the providers here to ensure all the
303 // freeProperty and freeTimer calls happen before the providers are destructed.
Harry Cutts1b217912023-01-03 17:13:19 +0000304 mGestureInterpreter->SetPropProvider(nullptr, nullptr);
Harry Cutts8c7cb592023-08-23 17:20:13 +0000305 mGestureInterpreter->SetTimerProvider(nullptr, nullptr);
Harry Cutts74235542022-11-24 15:52:53 +0000306}
307
Harry Cutts79cc9fa2022-10-28 15:32:39 +0000308uint32_t TouchpadInputMapper::getSources() const {
309 return AINPUT_SOURCE_MOUSE | AINPUT_SOURCE_TOUCHPAD;
310}
311
Harry Cuttsd02ea102023-03-17 18:21:30 +0000312void TouchpadInputMapper::populateDeviceInfo(InputDeviceInfo& info) {
Harry Cutts8cd2abd2023-03-15 16:35:56 +0000313 InputMapper::populateDeviceInfo(info);
Harry Cuttsbb24e272023-03-21 10:49:47 +0000314 if (mPointerCaptured) {
315 mCapturedEventConverter.populateMotionRanges(info);
316 } else {
317 mGestureConverter.populateMotionRanges(info);
318 }
Harry Cutts8cd2abd2023-03-15 16:35:56 +0000319}
320
Harry Cuttsea73eaa2023-01-16 17:55:46 +0000321void TouchpadInputMapper::dump(std::string& dump) {
322 dump += INDENT2 "Touchpad Input Mapper:\n";
Harry Cuttsbb24e272023-03-21 10:49:47 +0000323 if (mResettingInterpreter) {
324 dump += INDENT3 "Currently resetting gesture interpreter\n";
325 }
326 dump += StringPrintf(INDENT3 "Pointer captured: %s\n", toString(mPointerCaptured));
Harry Cuttsea73eaa2023-01-16 17:55:46 +0000327 dump += INDENT3 "Gesture converter:\n";
328 dump += addLinePrefix(mGestureConverter.dump(), INDENT4);
329 dump += INDENT3 "Gesture properties:\n";
330 dump += addLinePrefix(mPropertyProvider.dump(), INDENT4);
Harry Cutts8c7cb592023-08-23 17:20:13 +0000331 if (input_flags::enable_gestures_library_timer_provider()) {
332 dump += INDENT3 "Timer provider:\n";
333 dump += addLinePrefix(mTimerProvider.dump(), INDENT4);
334 } else {
335 dump += INDENT3 "Timer provider: disabled by flag\n";
336 }
Harry Cuttsbb24e272023-03-21 10:49:47 +0000337 dump += INDENT3 "Captured event converter:\n";
338 dump += addLinePrefix(mCapturedEventConverter.dump(), INDENT4);
Josep del Riod0746382023-07-29 13:18:25 +0000339 dump += StringPrintf(INDENT3 "DisplayId: %s\n", toString(mDisplayId).c_str());
Harry Cuttsea73eaa2023-01-16 17:55:46 +0000340}
341
Arpit Singh4be4eef2023-03-28 14:26:01 +0000342std::list<NotifyArgs> TouchpadInputMapper::reconfigure(nsecs_t when,
Arpit Singhed6c3de2023-04-05 19:24:37 +0000343 const InputReaderConfiguration& config,
Prabir Pradhan4bf6d452023-04-18 21:26:56 +0000344 ConfigurationChanges changes) {
345 if (!changes.any()) {
Harry Cutts2b67ff12023-03-13 11:32:06 +0000346 // First time configuration
347 mPropertyProvider.loadPropertiesFromIdcFile(getDeviceContext().getConfiguration());
348 }
349
Prabir Pradhan4bf6d452023-04-18 21:26:56 +0000350 if (!changes.any() || changes.test(InputReaderConfiguration::Change::DISPLAY_INFO)) {
Josep del Riod0746382023-07-29 13:18:25 +0000351 mDisplayId = ADISPLAY_ID_NONE;
Byoungho Jungee6268f2023-10-30 17:27:26 +0900352 std::optional<DisplayViewport> resolvedViewport;
353 std::optional<FloatRect> boundsInLogicalDisplay;
354 if (auto assocViewport = mDeviceContext.getAssociatedViewport(); assocViewport) {
Josep del Riod0746382023-07-29 13:18:25 +0000355 // This InputDevice is associated with a viewport.
356 // Only generate events for the associated display.
Byoungho Jungee6268f2023-10-30 17:27:26 +0900357 mDisplayId = assocViewport->displayId;
358 resolvedViewport = *assocViewport;
359 if (!mEnablePointerChoreographer) {
360 const bool mismatchedPointerDisplay =
361 (assocViewport->displayId != mPointerController->getDisplayId());
362 if (mismatchedPointerDisplay) {
363 ALOGW("Touchpad \"%s\" associated viewport display does not match pointer "
364 "controller",
365 mDeviceContext.getName().c_str());
366 mDisplayId.reset();
367 }
Josep del Riod0746382023-07-29 13:18:25 +0000368 }
Josep del Riod0746382023-07-29 13:18:25 +0000369 } else {
370 // The InputDevice is not associated with a viewport, but it controls the mouse pointer.
Byoungho Jungee6268f2023-10-30 17:27:26 +0900371 if (mEnablePointerChoreographer) {
372 // Always use DISPLAY_ID_NONE for touchpad events.
373 // PointerChoreographer will make it target the correct the displayId later.
374 resolvedViewport =
375 getContext()->getPolicy()->getPointerViewportForAssociatedDisplay();
376 mDisplayId = resolvedViewport ? std::make_optional(ADISPLAY_ID_NONE) : std::nullopt;
377 } else {
378 mDisplayId = mPointerController->getDisplayId();
379 if (auto v = config.getDisplayViewportById(*mDisplayId); v) {
380 resolvedViewport = *v;
381 }
382 if (auto bounds = mPointerController->getBounds(); bounds) {
383 boundsInLogicalDisplay = *bounds;
384 }
Harry Cuttsedf6ce72023-01-04 12:15:53 +0000385 }
386 }
Byoungho Jungee6268f2023-10-30 17:27:26 +0900387
Josep del Riod0746382023-07-29 13:18:25 +0000388 mGestureConverter.setDisplayId(mDisplayId);
Byoungho Jungee6268f2023-10-30 17:27:26 +0900389 mGestureConverter.setOrientation(resolvedViewport
390 ? getInverseRotation(resolvedViewport->orientation)
391 : ui::ROTATION_0);
392
393 if (!boundsInLogicalDisplay) {
394 boundsInLogicalDisplay = resolvedViewport
395 ? FloatRect{static_cast<float>(resolvedViewport->logicalLeft),
396 static_cast<float>(resolvedViewport->logicalTop),
397 static_cast<float>(resolvedViewport->logicalRight - 1),
398 static_cast<float>(resolvedViewport->logicalBottom - 1)}
399 : FloatRect{0, 0, 0, 0};
400 }
401 mGestureConverter.setBoundsInLogicalDisplay(*boundsInLogicalDisplay);
Harry Cuttsedf6ce72023-01-04 12:15:53 +0000402 }
Prabir Pradhan4bf6d452023-04-18 21:26:56 +0000403 if (!changes.any() || changes.test(InputReaderConfiguration::Change::TOUCHPAD_SETTINGS)) {
Harry Cuttsd35a24b2023-01-30 15:09:30 +0000404 mPropertyProvider.getProperty("Use Custom Touchpad Pointer Accel Curve")
405 .setBoolValues({true});
406 GesturesProp accelCurveProp = mPropertyProvider.getProperty("Pointer Accel Curve");
407 accelCurveProp.setRealValues(
Arpit Singhed6c3de2023-04-05 19:24:37 +0000408 createAccelerationCurveForSensitivity(config.touchpadPointerSpeed,
Harry Cuttsd35a24b2023-01-30 15:09:30 +0000409 accelCurveProp.getCount()));
Wenxin Feng1ca50662023-05-03 14:00:12 -0700410 mPropertyProvider.getProperty("Use Custom Touchpad Scroll Accel Curve")
411 .setBoolValues({true});
412 GesturesProp scrollCurveProp = mPropertyProvider.getProperty("Scroll Accel Curve");
413 scrollCurveProp.setRealValues(
414 createAccelerationCurveForSensitivity(config.touchpadPointerSpeed,
415 scrollCurveProp.getCount()));
416 mPropertyProvider.getProperty("Scroll X Out Scale").setRealValues({1.0});
417 mPropertyProvider.getProperty("Scroll Y Out Scale").setRealValues({1.0});
Harry Cuttsa546ba82023-01-13 17:21:00 +0000418 mPropertyProvider.getProperty("Invert Scrolling")
Arpit Singhed6c3de2023-04-05 19:24:37 +0000419 .setBoolValues({config.touchpadNaturalScrollingEnabled});
Harry Cuttsa546ba82023-01-13 17:21:00 +0000420 mPropertyProvider.getProperty("Tap Enable")
Arpit Singhed6c3de2023-04-05 19:24:37 +0000421 .setBoolValues({config.touchpadTapToClickEnabled});
Harry Cuttsa546ba82023-01-13 17:21:00 +0000422 mPropertyProvider.getProperty("Button Right Click Zone Enable")
Arpit Singhed6c3de2023-04-05 19:24:37 +0000423 .setBoolValues({config.touchpadRightClickZoneEnabled});
Harry Cuttsa546ba82023-01-13 17:21:00 +0000424 }
Harry Cuttsbb24e272023-03-21 10:49:47 +0000425 std::list<NotifyArgs> out;
426 if ((!changes.any() && config.pointerCaptureRequest.enable) ||
427 changes.test(InputReaderConfiguration::Change::POINTER_CAPTURE)) {
428 mPointerCaptured = config.pointerCaptureRequest.enable;
429 // The motion ranges are going to change, so bump the generation to clear the cached ones.
430 bumpGeneration();
431 if (mPointerCaptured) {
432 // The touchpad is being captured, so we need to tidy up any fake fingers etc. that are
433 // still being reported for a gesture in progress.
434 out += reset(when);
435 mPointerController->fade(PointerControllerInterface::Transition::IMMEDIATE);
436 } else {
437 // We're transitioning from captured to uncaptured.
438 mCapturedEventConverter.reset();
439 }
440 if (changes.any()) {
441 out.push_back(NotifyDeviceResetArgs(getContext()->getNextId(), when, getDeviceId()));
442 }
443 }
444 return out;
Harry Cuttsedf6ce72023-01-04 12:15:53 +0000445}
446
Harry Cutts1f48a442022-11-15 17:38:36 +0000447std::list<NotifyArgs> TouchpadInputMapper::reset(nsecs_t when) {
Harry Cutts47db1c72022-12-13 19:20:47 +0000448 mStateConverter.reset();
Harry Cuttsbb24e272023-03-21 10:49:47 +0000449 resetGestureInterpreter(when);
Harry Cuttse9b71422023-03-14 16:54:44 +0000450 std::list<NotifyArgs> out = mGestureConverter.reset(when);
451 out += InputMapper::reset(when);
452 return out;
Harry Cutts1f48a442022-11-15 17:38:36 +0000453}
454
Harry Cuttsbb24e272023-03-21 10:49:47 +0000455void TouchpadInputMapper::resetGestureInterpreter(nsecs_t when) {
456 // The GestureInterpreter has no official reset method, but sending a HardwareState with no
457 // fingers down or buttons pressed should get it into a clean state.
458 HardwareState state;
459 state.timestamp = std::chrono::duration<stime_t>(std::chrono::nanoseconds(when)).count();
460 mResettingInterpreter = true;
461 mGestureInterpreter->PushHardwareState(&state);
462 mResettingInterpreter = false;
463}
464
Harry Cutts79cc9fa2022-10-28 15:32:39 +0000465std::list<NotifyArgs> TouchpadInputMapper::process(const RawEvent* rawEvent) {
Harry Cuttsbb24e272023-03-21 10:49:47 +0000466 if (mPointerCaptured) {
467 return mCapturedEventConverter.process(*rawEvent);
468 }
Arpit Singh33a10a62023-10-12 13:06:54 +0000469 if (mMotionAccumulator.getActiveSlotsCount() == 0) {
470 mGestureStartTime = rawEvent->when;
471 }
Harry Cutts47db1c72022-12-13 19:20:47 +0000472 std::optional<SelfContainedHardwareState> state = mStateConverter.processRawEvent(rawEvent);
473 if (state) {
Harry Cuttsa34de522023-06-06 15:52:54 +0000474 updatePalmDetectionMetrics();
Harry Cutts47db1c72022-12-13 19:20:47 +0000475 return sendHardwareState(rawEvent->when, rawEvent->readTime, *state);
476 } else {
477 return {};
Harry Cutts1f48a442022-11-15 17:38:36 +0000478 }
Harry Cutts79cc9fa2022-10-28 15:32:39 +0000479}
480
Harry Cuttsa34de522023-06-06 15:52:54 +0000481void TouchpadInputMapper::updatePalmDetectionMetrics() {
482 std::set<int32_t> currentTrackingIds;
483 for (size_t i = 0; i < mMotionAccumulator.getSlotCount(); i++) {
484 const MultiTouchMotionAccumulator::Slot& slot = mMotionAccumulator.getSlot(i);
485 if (!slot.isInUse()) {
486 continue;
487 }
488 currentTrackingIds.insert(slot.getTrackingId());
489 if (slot.getToolType() == ToolType::PALM) {
490 mPalmTrackingIds.insert(slot.getTrackingId());
491 }
492 }
493 std::vector<int32_t> liftedTouches;
494 std::set_difference(mLastFrameTrackingIds.begin(), mLastFrameTrackingIds.end(),
495 currentTrackingIds.begin(), currentTrackingIds.end(),
496 std::inserter(liftedTouches, liftedTouches.begin()));
497 for (int32_t trackingId : liftedTouches) {
498 if (mPalmTrackingIds.erase(trackingId) > 0) {
499 MetricsAccumulator::getInstance().recordPalm(mMetricsId);
500 } else {
501 MetricsAccumulator::getInstance().recordFinger(mMetricsId);
502 }
503 }
504 mLastFrameTrackingIds = currentTrackingIds;
505}
506
Harry Cutts47db1c72022-12-13 19:20:47 +0000507std::list<NotifyArgs> TouchpadInputMapper::sendHardwareState(nsecs_t when, nsecs_t readTime,
508 SelfContainedHardwareState schs) {
Harry Cutts287e19f2023-02-27 17:09:24 +0000509 ALOGD_IF(DEBUG_TOUCHPAD_GESTURES, "New hardware state: %s", schs.state.String().c_str());
Harry Cutts47db1c72022-12-13 19:20:47 +0000510 mGestureInterpreter->PushHardwareState(&schs.state);
Harry Cutts47db1c72022-12-13 19:20:47 +0000511 return processGestures(when, readTime);
Harry Cutts74235542022-11-24 15:52:53 +0000512}
513
Harry Cutts8c7cb592023-08-23 17:20:13 +0000514std::list<NotifyArgs> TouchpadInputMapper::timeoutExpired(nsecs_t when) {
515 if (!input_flags::enable_gestures_library_timer_provider()) {
516 return {};
517 }
518 mTimerProvider.triggerCallbacks(when);
519 return processGestures(when, when);
520}
521
Harry Cutts74235542022-11-24 15:52:53 +0000522void TouchpadInputMapper::consumeGesture(const Gesture* gesture) {
Harry Cuttsc5025372023-02-21 16:04:45 +0000523 ALOGD_IF(DEBUG_TOUCHPAD_GESTURES, "Gesture ready: %s", gesture->String().c_str());
Harry Cuttsbb24e272023-03-21 10:49:47 +0000524 if (mResettingInterpreter) {
525 // We already handle tidying up fake fingers etc. in GestureConverter::reset, so we should
526 // ignore any gestures produced from the interpreter while we're resetting it.
527 return;
528 }
Harry Cutts74235542022-11-24 15:52:53 +0000529 mGesturesToProcess.push_back(*gesture);
530}
531
532std::list<NotifyArgs> TouchpadInputMapper::processGestures(nsecs_t when, nsecs_t readTime) {
533 std::list<NotifyArgs> out = {};
Josep del Riod0746382023-07-29 13:18:25 +0000534 if (mDisplayId) {
535 MetricsAccumulator& metricsAccumulator = MetricsAccumulator::getInstance();
536 for (Gesture& gesture : mGesturesToProcess) {
Arpit Singh33a10a62023-10-12 13:06:54 +0000537 out += mGestureConverter.handleGesture(when, readTime, mGestureStartTime, gesture);
Josep del Riod0746382023-07-29 13:18:25 +0000538 metricsAccumulator.processGesture(mMetricsId, gesture);
539 }
Harry Cutts74235542022-11-24 15:52:53 +0000540 }
541 mGesturesToProcess.clear();
542 return out;
543}
544
Josep del Riod0746382023-07-29 13:18:25 +0000545std::optional<int32_t> TouchpadInputMapper::getAssociatedDisplayId() {
546 return mDisplayId;
547}
548
Harry Cutts79cc9fa2022-10-28 15:32:39 +0000549} // namespace android