blob: 34ca0b37672fe1e7512985015e2fb11e22bbea67 [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 Cutts8c7cb592023-08-23 17:20:13 +000028#include <com_android_input_flags.h>
Harry Cutts2b67ff12023-03-13 11:32:06 +000029#include <ftl/enum.h>
Harry Cuttsea73eaa2023-01-16 17:55:46 +000030#include <input/PrintTools.h>
Harry Cutts4fb941a2022-12-14 19:14:04 +000031#include <linux/input-event-codes.h>
Harry Cutts74235542022-11-24 15:52:53 +000032#include <log/log_main.h>
Harry Cuttsa34de522023-06-06 15:52:54 +000033#include <stats_pull_atom_callback.h>
34#include <statslog.h>
Harry Cutts74235542022-11-24 15:52:53 +000035#include "TouchCursorInputMapperCommon.h"
Harry Cutts79cc9fa2022-10-28 15:32:39 +000036#include "TouchpadInputMapper.h"
Harry Cutts3952c832023-08-22 15:26:56 +000037#include "gestures/HardwareProperties.h"
Harry Cutts8c7cb592023-08-23 17:20:13 +000038#include "gestures/TimerProvider.h"
Harry Cuttsedf6ce72023-01-04 12:15:53 +000039#include "ui/Rotation.h"
Harry Cutts79cc9fa2022-10-28 15:32:39 +000040
Harry Cutts8c7cb592023-08-23 17:20:13 +000041namespace input_flags = com::android::input::flags;
42
Harry Cutts79cc9fa2022-10-28 15:32:39 +000043namespace android {
44
Harry Cutts1f48a442022-11-15 17:38:36 +000045namespace {
46
Harry Cuttsc5025372023-02-21 16:04:45 +000047/**
48 * Log details of each gesture output by the gestures library.
49 * Enable this via "adb shell setprop log.tag.TouchpadInputMapperGestures DEBUG" (requires
50 * restarting the shell)
51 */
52const bool DEBUG_TOUCHPAD_GESTURES =
53 __android_log_is_loggable(ANDROID_LOG_DEBUG, "TouchpadInputMapperGestures",
54 ANDROID_LOG_INFO);
55
Harry Cuttsd35a24b2023-01-30 15:09:30 +000056// Describes a segment of the acceleration curve.
57struct CurveSegment {
58 // The maximum pointer speed which this segment should apply. The last segment in a curve should
59 // always set this to infinity.
60 double maxPointerSpeedMmPerS;
61 double slope;
62 double intercept;
63};
64
65const std::vector<CurveSegment> segments = {
Wenxin Fenge5d6d042023-07-06 17:40:45 -070066 {32.002, 3.19, 0},
67 {52.83, 4.79, -51.254},
68 {119.124, 7.28, -182.737},
69 {std::numeric_limits<double>::infinity(), 15.04, -1107.556},
Harry Cuttsd35a24b2023-01-30 15:09:30 +000070};
71
Wenxin Fenge5d6d042023-07-06 17:40:45 -070072const std::vector<double> sensitivityFactors = {1, 2, 4, 6, 7, 8, 9, 10,
73 11, 12, 13, 14, 16, 18, 20};
Harry Cuttsd35a24b2023-01-30 15:09:30 +000074
75std::vector<double> createAccelerationCurveForSensitivity(int32_t sensitivity,
76 size_t propertySize) {
77 LOG_ALWAYS_FATAL_IF(propertySize < 4 * segments.size());
78 std::vector<double> output(propertySize, 0);
79
80 // The Gestures library uses functions of the following form to define curve segments, where a,
81 // b, and c can be specified by us:
82 // output_speed(input_speed_mm) = a * input_speed_mm ^ 2 + b * input_speed_mm + c
83 //
84 // (a, b, and c are also called sqr_, mul_, and int_ in the Gestures library code.)
85 //
86 // We are trying to implement the following function, where slope and intercept are the
87 // parameters specified in the `segments` array above:
88 // gain(input_speed_mm) =
89 // 0.64 * (sensitivityFactor / 10) * (slope + intercept / input_speed_mm)
90 // Where "gain" is a multiplier applied to the input speed to produce the output speed:
91 // output_speed(input_speed_mm) = input_speed_mm * gain(input_speed_mm)
92 //
93 // To put our function in the library's form, we substitute it into the function above:
94 // output_speed(input_speed_mm) =
95 // input_speed_mm * (0.64 * (sensitivityFactor / 10) *
96 // (slope + 25.4 * intercept / input_speed_mm))
97 // then expand the brackets so that input_speed_mm cancels out for the intercept term:
98 // gain(input_speed_mm) =
99 // 0.64 * (sensitivityFactor / 10) * slope * input_speed_mm +
100 // 0.64 * (sensitivityFactor / 10) * intercept
101 //
102 // This gives us the following parameters for the Gestures library function form:
103 // a = 0
104 // b = 0.64 * (sensitivityFactor / 10) * slope
105 // c = 0.64 * (sensitivityFactor / 10) * intercept
106
107 double commonFactor = 0.64 * sensitivityFactors[sensitivity + 7] / 10;
108
109 size_t i = 0;
110 for (CurveSegment seg : segments) {
111 // The library's curve format consists of four doubles per segment:
112 // * maximum pointer speed for the segment (mm/s)
113 // * multiplier for the x² term (a.k.a. "a" or "sqr")
114 // * multiplier for the x term (a.k.a. "b" or "mul")
115 // * the intercept (a.k.a. "c" or "int")
116 // (see struct CurveSegment in the library's AccelFilterInterpreter)
117 output[i + 0] = seg.maxPointerSpeedMmPerS;
118 output[i + 1] = 0;
119 output[i + 2] = commonFactor * seg.slope;
120 output[i + 3] = commonFactor * seg.intercept;
121 i += 4;
122 }
123
124 return output;
125}
126
Harry Cutts74235542022-11-24 15:52:53 +0000127void gestureInterpreterCallback(void* clientData, const Gesture* gesture) {
128 TouchpadInputMapper* mapper = static_cast<TouchpadInputMapper*>(clientData);
129 mapper->consumeGesture(gesture);
130}
131
Prabir Pradhan67d09ca2023-09-08 20:28:55 +0000132int32_t linuxBusToInputDeviceBusEnum(int32_t linuxBus, bool isUsiStylus) {
133 if (isUsiStylus) {
134 // This is a stylus connected over the Universal Stylus Initiative (USI) protocol.
135 // For metrics purposes, we treat this protocol as a separate bus.
136 return util::INPUT_DEVICE_USAGE_REPORTED__DEVICE_BUS__USI;
137 }
138
Harry Cuttsa34de522023-06-06 15:52:54 +0000139 // When adding cases to this switch, also add them to the copy of this method in
140 // InputDeviceMetricsCollector.cpp.
141 // TODO(b/286394420): deduplicate this method with the one in InputDeviceMetricsCollector.cpp.
142 switch (linuxBus) {
143 case BUS_USB:
144 return util::INPUT_DEVICE_USAGE_REPORTED__DEVICE_BUS__USB;
145 case BUS_BLUETOOTH:
146 return util::INPUT_DEVICE_USAGE_REPORTED__DEVICE_BUS__BLUETOOTH;
147 default:
148 return util::INPUT_DEVICE_USAGE_REPORTED__DEVICE_BUS__OTHER;
149 }
150}
151
152class MetricsAccumulator {
153public:
154 static MetricsAccumulator& getInstance() {
155 static MetricsAccumulator sAccumulator;
156 return sAccumulator;
157 }
158
159 void recordFinger(const TouchpadInputMapper::MetricsIdentifier& id) { mCounters[id].fingers++; }
160
161 void recordPalm(const TouchpadInputMapper::MetricsIdentifier& id) { mCounters[id].palms++; }
162
163 // Checks whether a Gesture struct is for the end of a gesture that we log metrics for, and
164 // records it if so.
165 void processGesture(const TouchpadInputMapper::MetricsIdentifier& id, const Gesture& gesture) {
166 switch (gesture.type) {
167 case kGestureTypeFling:
168 if (gesture.details.fling.fling_state == GESTURES_FLING_START) {
169 // Indicates the end of a two-finger scroll gesture.
170 mCounters[id].twoFingerSwipeGestures++;
171 }
172 break;
173 case kGestureTypeSwipeLift:
174 mCounters[id].threeFingerSwipeGestures++;
175 break;
176 case kGestureTypeFourFingerSwipeLift:
177 mCounters[id].fourFingerSwipeGestures++;
178 break;
179 case kGestureTypePinch:
180 if (gesture.details.pinch.zoom_state == GESTURES_ZOOM_END) {
181 mCounters[id].pinchGestures++;
182 }
183 break;
184 default:
185 // We're not interested in any other gestures.
186 break;
187 }
188 }
189
190private:
191 MetricsAccumulator() {
192 AStatsManager_setPullAtomCallback(android::util::TOUCHPAD_USAGE, /*metadata=*/nullptr,
193 MetricsAccumulator::pullAtomCallback, /*cookie=*/nullptr);
194 }
195
196 ~MetricsAccumulator() { AStatsManager_clearPullAtomCallback(android::util::TOUCHPAD_USAGE); }
197
198 static AStatsManager_PullAtomCallbackReturn pullAtomCallback(int32_t atomTag,
199 AStatsEventList* outEventList,
200 void* cookie) {
201 LOG_ALWAYS_FATAL_IF(atomTag != android::util::TOUCHPAD_USAGE);
202 MetricsAccumulator& accumulator = MetricsAccumulator::getInstance();
203 accumulator.produceAtoms(outEventList);
204 accumulator.resetCounters();
205 return AStatsManager_PULL_SUCCESS;
206 }
207
208 void produceAtoms(AStatsEventList* outEventList) const {
209 for (auto& [id, counters] : mCounters) {
210 auto [busId, vendorId, productId, versionId] = id;
211 addAStatsEvent(outEventList, android::util::TOUCHPAD_USAGE, vendorId, productId,
Prabir Pradhan67d09ca2023-09-08 20:28:55 +0000212 versionId, linuxBusToInputDeviceBusEnum(busId, /*isUsi=*/false),
213 counters.fingers, counters.palms, counters.twoFingerSwipeGestures,
Harry Cuttsa34de522023-06-06 15:52:54 +0000214 counters.threeFingerSwipeGestures, counters.fourFingerSwipeGestures,
215 counters.pinchGestures);
216 }
217 }
218
219 void resetCounters() { mCounters.clear(); }
220
221 // Stores the counters for a specific touchpad model. Fields have the same meanings as those of
222 // the TouchpadUsage atom; see that definition for detailed documentation.
223 struct Counters {
224 int32_t fingers = 0;
225 int32_t palms = 0;
226
227 int32_t twoFingerSwipeGestures = 0;
228 int32_t threeFingerSwipeGestures = 0;
229 int32_t fourFingerSwipeGestures = 0;
230 int32_t pinchGestures = 0;
231 };
232
233 // Metrics are aggregated by device model and version, so if two devices of the same model and
234 // version are connected at once, they will have the same counters.
235 std::map<TouchpadInputMapper::MetricsIdentifier, Counters> mCounters;
236};
237
Harry Cutts1f48a442022-11-15 17:38:36 +0000238} // namespace
239
Arpit Singh8e6fb252023-04-06 11:49:17 +0000240TouchpadInputMapper::TouchpadInputMapper(InputDeviceContext& deviceContext,
241 const InputReaderConfiguration& readerConfig)
242 : InputMapper(deviceContext, readerConfig),
Harry Cutts1f48a442022-11-15 17:38:36 +0000243 mGestureInterpreter(NewGestureInterpreter(), DeleteGestureInterpreter),
Harry Cutts74235542022-11-24 15:52:53 +0000244 mPointerController(getContext()->getPointerController(getDeviceId())),
Harry Cutts8c7cb592023-08-23 17:20:13 +0000245 mTimerProvider(*getContext()),
Harry Cuttsbb24e272023-03-21 10:49:47 +0000246 mStateConverter(deviceContext, mMotionAccumulator),
247 mGestureConverter(*getContext(), deviceContext, getDeviceId()),
Harry Cuttsa34de522023-06-06 15:52:54 +0000248 mCapturedEventConverter(*getContext(), deviceContext, mMotionAccumulator, getDeviceId()),
Byoungho Jungee6268f2023-10-30 17:27:26 +0900249 mMetricsId(metricsIdFromInputDeviceIdentifier(deviceContext.getDeviceIdentifier())),
250 mEnablePointerChoreographer(input_flags::enable_pointer_choreographer()) {
Harry Cuttsbb24e272023-03-21 10:49:47 +0000251 RawAbsoluteAxisInfo slotAxisInfo;
252 deviceContext.getAbsoluteAxisInfo(ABS_MT_SLOT, &slotAxisInfo);
253 if (!slotAxisInfo.valid || slotAxisInfo.maxValue <= 0) {
254 ALOGW("Touchpad \"%s\" doesn't have a valid ABS_MT_SLOT axis, and probably won't work "
255 "properly.",
256 deviceContext.getName().c_str());
257 }
258 mMotionAccumulator.configure(deviceContext, slotAxisInfo.maxValue + 1, true);
259
Harry Cutts1f48a442022-11-15 17:38:36 +0000260 mGestureInterpreter->Initialize(GESTURES_DEVCLASS_TOUCHPAD);
261 mGestureInterpreter->SetHardwareProperties(createHardwareProperties(deviceContext));
Harry Cutts74235542022-11-24 15:52:53 +0000262 // Even though we don't explicitly delete copy/move semantics, it's safe to
Harry Cutts1b217912023-01-03 17:13:19 +0000263 // give away pointers to TouchpadInputMapper and its members here because
Harry Cutts74235542022-11-24 15:52:53 +0000264 // 1) mGestureInterpreter's lifecycle is determined by TouchpadInputMapper, and
265 // 2) TouchpadInputMapper is stored as a unique_ptr and not moved.
Harry Cutts1b217912023-01-03 17:13:19 +0000266 mGestureInterpreter->SetPropProvider(const_cast<GesturesPropProvider*>(&gesturePropProvider),
267 &mPropertyProvider);
Harry Cutts8c7cb592023-08-23 17:20:13 +0000268 if (input_flags::enable_gestures_library_timer_provider()) {
269 mGestureInterpreter->SetTimerProvider(const_cast<GesturesTimerProvider*>(
270 &kGestureTimerProvider),
271 &mTimerProvider);
272 }
Harry Cutts74235542022-11-24 15:52:53 +0000273 mGestureInterpreter->SetCallback(gestureInterpreterCallback, this);
Harry Cutts1f48a442022-11-15 17:38:36 +0000274}
Harry Cutts79cc9fa2022-10-28 15:32:39 +0000275
Harry Cutts74235542022-11-24 15:52:53 +0000276TouchpadInputMapper::~TouchpadInputMapper() {
277 if (mPointerController != nullptr) {
278 mPointerController->fade(PointerControllerInterface::Transition::IMMEDIATE);
279 }
Harry Cutts1b217912023-01-03 17:13:19 +0000280
Harry Cutts8c7cb592023-08-23 17:20:13 +0000281 // The gesture interpreter's destructor will try to free its property and timer providers,
282 // calling PropertyProvider::freeProperty and TimerProvider::freeTimer using a raw pointers.
283 // Depending on the declaration order in TouchpadInputMapper.h, those providers may have already
284 // been freed, causing allocation errors or use-after-free bugs. Depending on declaration order
285 // to avoid this seems rather fragile, so explicitly clear the providers here to ensure all the
286 // freeProperty and freeTimer calls happen before the providers are destructed.
Harry Cutts1b217912023-01-03 17:13:19 +0000287 mGestureInterpreter->SetPropProvider(nullptr, nullptr);
Harry Cutts8c7cb592023-08-23 17:20:13 +0000288 mGestureInterpreter->SetTimerProvider(nullptr, nullptr);
Harry Cutts74235542022-11-24 15:52:53 +0000289}
290
Harry Cutts79cc9fa2022-10-28 15:32:39 +0000291uint32_t TouchpadInputMapper::getSources() const {
292 return AINPUT_SOURCE_MOUSE | AINPUT_SOURCE_TOUCHPAD;
293}
294
Harry Cuttsd02ea102023-03-17 18:21:30 +0000295void TouchpadInputMapper::populateDeviceInfo(InputDeviceInfo& info) {
Harry Cutts8cd2abd2023-03-15 16:35:56 +0000296 InputMapper::populateDeviceInfo(info);
Harry Cuttsbb24e272023-03-21 10:49:47 +0000297 if (mPointerCaptured) {
298 mCapturedEventConverter.populateMotionRanges(info);
299 } else {
300 mGestureConverter.populateMotionRanges(info);
301 }
Harry Cutts8cd2abd2023-03-15 16:35:56 +0000302}
303
Harry Cuttsea73eaa2023-01-16 17:55:46 +0000304void TouchpadInputMapper::dump(std::string& dump) {
305 dump += INDENT2 "Touchpad Input Mapper:\n";
Harry Cuttsbb24e272023-03-21 10:49:47 +0000306 if (mResettingInterpreter) {
307 dump += INDENT3 "Currently resetting gesture interpreter\n";
308 }
309 dump += StringPrintf(INDENT3 "Pointer captured: %s\n", toString(mPointerCaptured));
Harry Cuttsea73eaa2023-01-16 17:55:46 +0000310 dump += INDENT3 "Gesture converter:\n";
311 dump += addLinePrefix(mGestureConverter.dump(), INDENT4);
312 dump += INDENT3 "Gesture properties:\n";
313 dump += addLinePrefix(mPropertyProvider.dump(), INDENT4);
Harry Cutts8c7cb592023-08-23 17:20:13 +0000314 if (input_flags::enable_gestures_library_timer_provider()) {
315 dump += INDENT3 "Timer provider:\n";
316 dump += addLinePrefix(mTimerProvider.dump(), INDENT4);
317 } else {
318 dump += INDENT3 "Timer provider: disabled by flag\n";
319 }
Harry Cuttsbb24e272023-03-21 10:49:47 +0000320 dump += INDENT3 "Captured event converter:\n";
321 dump += addLinePrefix(mCapturedEventConverter.dump(), INDENT4);
Josep del Riod0746382023-07-29 13:18:25 +0000322 dump += StringPrintf(INDENT3 "DisplayId: %s\n", toString(mDisplayId).c_str());
Harry Cuttsea73eaa2023-01-16 17:55:46 +0000323}
324
Arpit Singh4be4eef2023-03-28 14:26:01 +0000325std::list<NotifyArgs> TouchpadInputMapper::reconfigure(nsecs_t when,
Arpit Singhed6c3de2023-04-05 19:24:37 +0000326 const InputReaderConfiguration& config,
Prabir Pradhan4bf6d452023-04-18 21:26:56 +0000327 ConfigurationChanges changes) {
328 if (!changes.any()) {
Harry Cutts2b67ff12023-03-13 11:32:06 +0000329 // First time configuration
330 mPropertyProvider.loadPropertiesFromIdcFile(getDeviceContext().getConfiguration());
331 }
332
Prabir Pradhan4bf6d452023-04-18 21:26:56 +0000333 if (!changes.any() || changes.test(InputReaderConfiguration::Change::DISPLAY_INFO)) {
Josep del Riod0746382023-07-29 13:18:25 +0000334 mDisplayId = ADISPLAY_ID_NONE;
Byoungho Jungee6268f2023-10-30 17:27:26 +0900335 std::optional<DisplayViewport> resolvedViewport;
336 std::optional<FloatRect> boundsInLogicalDisplay;
337 if (auto assocViewport = mDeviceContext.getAssociatedViewport(); assocViewport) {
Josep del Riod0746382023-07-29 13:18:25 +0000338 // This InputDevice is associated with a viewport.
339 // Only generate events for the associated display.
Byoungho Jungee6268f2023-10-30 17:27:26 +0900340 mDisplayId = assocViewport->displayId;
341 resolvedViewport = *assocViewport;
342 if (!mEnablePointerChoreographer) {
343 const bool mismatchedPointerDisplay =
344 (assocViewport->displayId != mPointerController->getDisplayId());
345 if (mismatchedPointerDisplay) {
346 ALOGW("Touchpad \"%s\" associated viewport display does not match pointer "
347 "controller",
348 mDeviceContext.getName().c_str());
349 mDisplayId.reset();
350 }
Josep del Riod0746382023-07-29 13:18:25 +0000351 }
Josep del Riod0746382023-07-29 13:18:25 +0000352 } else {
353 // The InputDevice is not associated with a viewport, but it controls the mouse pointer.
Byoungho Jungee6268f2023-10-30 17:27:26 +0900354 if (mEnablePointerChoreographer) {
355 // Always use DISPLAY_ID_NONE for touchpad events.
356 // PointerChoreographer will make it target the correct the displayId later.
357 resolvedViewport =
358 getContext()->getPolicy()->getPointerViewportForAssociatedDisplay();
359 mDisplayId = resolvedViewport ? std::make_optional(ADISPLAY_ID_NONE) : std::nullopt;
360 } else {
361 mDisplayId = mPointerController->getDisplayId();
362 if (auto v = config.getDisplayViewportById(*mDisplayId); v) {
363 resolvedViewport = *v;
364 }
365 if (auto bounds = mPointerController->getBounds(); bounds) {
366 boundsInLogicalDisplay = *bounds;
367 }
Harry Cuttsedf6ce72023-01-04 12:15:53 +0000368 }
369 }
Byoungho Jungee6268f2023-10-30 17:27:26 +0900370
Josep del Riod0746382023-07-29 13:18:25 +0000371 mGestureConverter.setDisplayId(mDisplayId);
Byoungho Jungee6268f2023-10-30 17:27:26 +0900372 mGestureConverter.setOrientation(resolvedViewport
373 ? getInverseRotation(resolvedViewport->orientation)
374 : ui::ROTATION_0);
375
376 if (!boundsInLogicalDisplay) {
377 boundsInLogicalDisplay = resolvedViewport
378 ? FloatRect{static_cast<float>(resolvedViewport->logicalLeft),
379 static_cast<float>(resolvedViewport->logicalTop),
380 static_cast<float>(resolvedViewport->logicalRight - 1),
381 static_cast<float>(resolvedViewport->logicalBottom - 1)}
382 : FloatRect{0, 0, 0, 0};
383 }
384 mGestureConverter.setBoundsInLogicalDisplay(*boundsInLogicalDisplay);
Harry Cuttsedf6ce72023-01-04 12:15:53 +0000385 }
Prabir Pradhan4bf6d452023-04-18 21:26:56 +0000386 if (!changes.any() || changes.test(InputReaderConfiguration::Change::TOUCHPAD_SETTINGS)) {
Harry Cuttsd35a24b2023-01-30 15:09:30 +0000387 mPropertyProvider.getProperty("Use Custom Touchpad Pointer Accel Curve")
388 .setBoolValues({true});
389 GesturesProp accelCurveProp = mPropertyProvider.getProperty("Pointer Accel Curve");
390 accelCurveProp.setRealValues(
Arpit Singhed6c3de2023-04-05 19:24:37 +0000391 createAccelerationCurveForSensitivity(config.touchpadPointerSpeed,
Harry Cuttsd35a24b2023-01-30 15:09:30 +0000392 accelCurveProp.getCount()));
Wenxin Feng1ca50662023-05-03 14:00:12 -0700393 mPropertyProvider.getProperty("Use Custom Touchpad Scroll Accel Curve")
394 .setBoolValues({true});
395 GesturesProp scrollCurveProp = mPropertyProvider.getProperty("Scroll Accel Curve");
396 scrollCurveProp.setRealValues(
397 createAccelerationCurveForSensitivity(config.touchpadPointerSpeed,
398 scrollCurveProp.getCount()));
399 mPropertyProvider.getProperty("Scroll X Out Scale").setRealValues({1.0});
400 mPropertyProvider.getProperty("Scroll Y Out Scale").setRealValues({1.0});
Harry Cuttsa546ba82023-01-13 17:21:00 +0000401 mPropertyProvider.getProperty("Invert Scrolling")
Arpit Singhed6c3de2023-04-05 19:24:37 +0000402 .setBoolValues({config.touchpadNaturalScrollingEnabled});
Harry Cuttsa546ba82023-01-13 17:21:00 +0000403 mPropertyProvider.getProperty("Tap Enable")
Arpit Singhed6c3de2023-04-05 19:24:37 +0000404 .setBoolValues({config.touchpadTapToClickEnabled});
Harry Cuttsa546ba82023-01-13 17:21:00 +0000405 mPropertyProvider.getProperty("Button Right Click Zone Enable")
Arpit Singhed6c3de2023-04-05 19:24:37 +0000406 .setBoolValues({config.touchpadRightClickZoneEnabled});
Harry Cuttsa546ba82023-01-13 17:21:00 +0000407 }
Harry Cuttsbb24e272023-03-21 10:49:47 +0000408 std::list<NotifyArgs> out;
409 if ((!changes.any() && config.pointerCaptureRequest.enable) ||
410 changes.test(InputReaderConfiguration::Change::POINTER_CAPTURE)) {
411 mPointerCaptured = config.pointerCaptureRequest.enable;
412 // The motion ranges are going to change, so bump the generation to clear the cached ones.
413 bumpGeneration();
414 if (mPointerCaptured) {
415 // The touchpad is being captured, so we need to tidy up any fake fingers etc. that are
416 // still being reported for a gesture in progress.
417 out += reset(when);
418 mPointerController->fade(PointerControllerInterface::Transition::IMMEDIATE);
419 } else {
420 // We're transitioning from captured to uncaptured.
421 mCapturedEventConverter.reset();
422 }
423 if (changes.any()) {
424 out.push_back(NotifyDeviceResetArgs(getContext()->getNextId(), when, getDeviceId()));
425 }
426 }
427 return out;
Harry Cuttsedf6ce72023-01-04 12:15:53 +0000428}
429
Harry Cutts1f48a442022-11-15 17:38:36 +0000430std::list<NotifyArgs> TouchpadInputMapper::reset(nsecs_t when) {
Harry Cutts47db1c72022-12-13 19:20:47 +0000431 mStateConverter.reset();
Harry Cuttsbb24e272023-03-21 10:49:47 +0000432 resetGestureInterpreter(when);
Harry Cuttse9b71422023-03-14 16:54:44 +0000433 std::list<NotifyArgs> out = mGestureConverter.reset(when);
434 out += InputMapper::reset(when);
435 return out;
Harry Cutts1f48a442022-11-15 17:38:36 +0000436}
437
Harry Cuttsbb24e272023-03-21 10:49:47 +0000438void TouchpadInputMapper::resetGestureInterpreter(nsecs_t when) {
439 // The GestureInterpreter has no official reset method, but sending a HardwareState with no
440 // fingers down or buttons pressed should get it into a clean state.
441 HardwareState state;
442 state.timestamp = std::chrono::duration<stime_t>(std::chrono::nanoseconds(when)).count();
443 mResettingInterpreter = true;
444 mGestureInterpreter->PushHardwareState(&state);
445 mResettingInterpreter = false;
446}
447
Harry Cutts79cc9fa2022-10-28 15:32:39 +0000448std::list<NotifyArgs> TouchpadInputMapper::process(const RawEvent* rawEvent) {
Harry Cuttsbb24e272023-03-21 10:49:47 +0000449 if (mPointerCaptured) {
450 return mCapturedEventConverter.process(*rawEvent);
451 }
Harry Cutts47db1c72022-12-13 19:20:47 +0000452 std::optional<SelfContainedHardwareState> state = mStateConverter.processRawEvent(rawEvent);
453 if (state) {
Harry Cuttsa34de522023-06-06 15:52:54 +0000454 updatePalmDetectionMetrics();
Harry Cutts47db1c72022-12-13 19:20:47 +0000455 return sendHardwareState(rawEvent->when, rawEvent->readTime, *state);
456 } else {
457 return {};
Harry Cutts1f48a442022-11-15 17:38:36 +0000458 }
Harry Cutts79cc9fa2022-10-28 15:32:39 +0000459}
460
Harry Cuttsa34de522023-06-06 15:52:54 +0000461void TouchpadInputMapper::updatePalmDetectionMetrics() {
462 std::set<int32_t> currentTrackingIds;
463 for (size_t i = 0; i < mMotionAccumulator.getSlotCount(); i++) {
464 const MultiTouchMotionAccumulator::Slot& slot = mMotionAccumulator.getSlot(i);
465 if (!slot.isInUse()) {
466 continue;
467 }
468 currentTrackingIds.insert(slot.getTrackingId());
469 if (slot.getToolType() == ToolType::PALM) {
470 mPalmTrackingIds.insert(slot.getTrackingId());
471 }
472 }
473 std::vector<int32_t> liftedTouches;
474 std::set_difference(mLastFrameTrackingIds.begin(), mLastFrameTrackingIds.end(),
475 currentTrackingIds.begin(), currentTrackingIds.end(),
476 std::inserter(liftedTouches, liftedTouches.begin()));
477 for (int32_t trackingId : liftedTouches) {
478 if (mPalmTrackingIds.erase(trackingId) > 0) {
479 MetricsAccumulator::getInstance().recordPalm(mMetricsId);
480 } else {
481 MetricsAccumulator::getInstance().recordFinger(mMetricsId);
482 }
483 }
484 mLastFrameTrackingIds = currentTrackingIds;
485}
486
Harry Cutts47db1c72022-12-13 19:20:47 +0000487std::list<NotifyArgs> TouchpadInputMapper::sendHardwareState(nsecs_t when, nsecs_t readTime,
488 SelfContainedHardwareState schs) {
Harry Cutts287e19f2023-02-27 17:09:24 +0000489 ALOGD_IF(DEBUG_TOUCHPAD_GESTURES, "New hardware state: %s", schs.state.String().c_str());
Harry Cutts47db1c72022-12-13 19:20:47 +0000490 mGestureInterpreter->PushHardwareState(&schs.state);
Harry Cutts47db1c72022-12-13 19:20:47 +0000491 return processGestures(when, readTime);
Harry Cutts74235542022-11-24 15:52:53 +0000492}
493
Harry Cutts8c7cb592023-08-23 17:20:13 +0000494std::list<NotifyArgs> TouchpadInputMapper::timeoutExpired(nsecs_t when) {
495 if (!input_flags::enable_gestures_library_timer_provider()) {
496 return {};
497 }
498 mTimerProvider.triggerCallbacks(when);
499 return processGestures(when, when);
500}
501
Harry Cutts74235542022-11-24 15:52:53 +0000502void TouchpadInputMapper::consumeGesture(const Gesture* gesture) {
Harry Cuttsc5025372023-02-21 16:04:45 +0000503 ALOGD_IF(DEBUG_TOUCHPAD_GESTURES, "Gesture ready: %s", gesture->String().c_str());
Harry Cuttsbb24e272023-03-21 10:49:47 +0000504 if (mResettingInterpreter) {
505 // We already handle tidying up fake fingers etc. in GestureConverter::reset, so we should
506 // ignore any gestures produced from the interpreter while we're resetting it.
507 return;
508 }
Harry Cutts74235542022-11-24 15:52:53 +0000509 mGesturesToProcess.push_back(*gesture);
510}
511
512std::list<NotifyArgs> TouchpadInputMapper::processGestures(nsecs_t when, nsecs_t readTime) {
513 std::list<NotifyArgs> out = {};
Josep del Riod0746382023-07-29 13:18:25 +0000514 if (mDisplayId) {
515 MetricsAccumulator& metricsAccumulator = MetricsAccumulator::getInstance();
516 for (Gesture& gesture : mGesturesToProcess) {
517 out += mGestureConverter.handleGesture(when, readTime, gesture);
518 metricsAccumulator.processGesture(mMetricsId, gesture);
519 }
Harry Cutts74235542022-11-24 15:52:53 +0000520 }
521 mGesturesToProcess.clear();
522 return out;
523}
524
Josep del Riod0746382023-07-29 13:18:25 +0000525std::optional<int32_t> TouchpadInputMapper::getAssociatedDisplayId() {
526 return mDisplayId;
527}
528
Harry Cutts79cc9fa2022-10-28 15:32:39 +0000529} // namespace android