blob: f558ba1196c83c33b1726f0d7e379eed30d8b0c0 [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 Cuttse78184b2024-01-08 15:54:58 +000032#include <input/AccelerationCurve.h>
Harry Cuttsea73eaa2023-01-16 17:55:46 +000033#include <input/PrintTools.h>
Harry Cutts4fb941a2022-12-14 19:14:04 +000034#include <linux/input-event-codes.h>
Harry Cutts74235542022-11-24 15:52:53 +000035#include <log/log_main.h>
Harry Cuttsa34de522023-06-06 15:52:54 +000036#include <stats_pull_atom_callback.h>
37#include <statslog.h>
Harry Cutts74235542022-11-24 15:52:53 +000038#include "TouchCursorInputMapperCommon.h"
Harry Cutts79cc9fa2022-10-28 15:32:39 +000039#include "TouchpadInputMapper.h"
Harry Cutts3952c832023-08-22 15:26:56 +000040#include "gestures/HardwareProperties.h"
Harry Cutts8c7cb592023-08-23 17:20:13 +000041#include "gestures/TimerProvider.h"
Harry Cuttsedf6ce72023-01-04 12:15:53 +000042#include "ui/Rotation.h"
Harry Cutts79cc9fa2022-10-28 15:32:39 +000043
Harry Cutts8c7cb592023-08-23 17:20:13 +000044namespace input_flags = com::android::input::flags;
45
Harry Cutts79cc9fa2022-10-28 15:32:39 +000046namespace android {
47
Harry Cutts1f48a442022-11-15 17:38:36 +000048namespace {
49
Prabir Pradhanc8377b02024-02-26 21:20:30 +000050static const bool ENABLE_POINTER_CHOREOGRAPHER = input_flags::enable_pointer_choreographer();
51
Harry Cuttsc5025372023-02-21 16:04:45 +000052/**
53 * Log details of each gesture output by the gestures library.
54 * Enable this via "adb shell setprop log.tag.TouchpadInputMapperGestures DEBUG" (requires
55 * restarting the shell)
56 */
57const bool DEBUG_TOUCHPAD_GESTURES =
58 __android_log_is_loggable(ANDROID_LOG_DEBUG, "TouchpadInputMapperGestures",
59 ANDROID_LOG_INFO);
60
Harry Cuttsd35a24b2023-01-30 15:09:30 +000061std::vector<double> createAccelerationCurveForSensitivity(int32_t sensitivity,
62 size_t propertySize) {
Harry Cuttse78184b2024-01-08 15:54:58 +000063 std::vector<AccelerationCurveSegment> segments =
64 createAccelerationCurveForPointerSensitivity(sensitivity);
Harry Cuttsd35a24b2023-01-30 15:09:30 +000065 LOG_ALWAYS_FATAL_IF(propertySize < 4 * segments.size());
66 std::vector<double> output(propertySize, 0);
67
68 // The Gestures library uses functions of the following form to define curve segments, where a,
69 // b, and c can be specified by us:
70 // output_speed(input_speed_mm) = a * input_speed_mm ^ 2 + b * input_speed_mm + c
71 //
72 // (a, b, and c are also called sqr_, mul_, and int_ in the Gestures library code.)
73 //
Harry Cuttse78184b2024-01-08 15:54:58 +000074 // createAccelerationCurveForPointerSensitivity gives us parameters for a function of the form:
75 // gain(input_speed_mm) = baseGain + reciprocal / input_speed_mm
Harry Cuttsd35a24b2023-01-30 15:09:30 +000076 // Where "gain" is a multiplier applied to the input speed to produce the output speed:
77 // output_speed(input_speed_mm) = input_speed_mm * gain(input_speed_mm)
78 //
79 // To put our function in the library's form, we substitute it into the function above:
Harry Cuttse78184b2024-01-08 15:54:58 +000080 // output_speed(input_speed_mm) = input_speed_mm * (baseGain + reciprocal / input_speed_mm)
81 // then expand the brackets so that input_speed_mm cancels out for the reciprocal term:
82 // gain(input_speed_mm) = baseGain * input_speed_mm + reciprocal
Harry Cuttsd35a24b2023-01-30 15:09:30 +000083 //
84 // This gives us the following parameters for the Gestures library function form:
85 // a = 0
Harry Cuttse78184b2024-01-08 15:54:58 +000086 // b = baseGain
87 // c = reciprocal
Harry Cuttsd35a24b2023-01-30 15:09:30 +000088
89 size_t i = 0;
Harry Cuttse78184b2024-01-08 15:54:58 +000090 for (AccelerationCurveSegment seg : segments) {
Harry Cuttsd35a24b2023-01-30 15:09:30 +000091 // The library's curve format consists of four doubles per segment:
92 // * maximum pointer speed for the segment (mm/s)
93 // * multiplier for the x² term (a.k.a. "a" or "sqr")
94 // * multiplier for the x term (a.k.a. "b" or "mul")
95 // * the intercept (a.k.a. "c" or "int")
96 // (see struct CurveSegment in the library's AccelFilterInterpreter)
97 output[i + 0] = seg.maxPointerSpeedMmPerS;
98 output[i + 1] = 0;
Harry Cuttse78184b2024-01-08 15:54:58 +000099 output[i + 2] = seg.baseGain;
100 output[i + 3] = seg.reciprocal;
Harry Cuttsd35a24b2023-01-30 15:09:30 +0000101 i += 4;
102 }
103
104 return output;
105}
106
Harry Cutts74235542022-11-24 15:52:53 +0000107void gestureInterpreterCallback(void* clientData, const Gesture* gesture) {
108 TouchpadInputMapper* mapper = static_cast<TouchpadInputMapper*>(clientData);
109 mapper->consumeGesture(gesture);
110}
111
Prabir Pradhan67d09ca2023-09-08 20:28:55 +0000112int32_t linuxBusToInputDeviceBusEnum(int32_t linuxBus, bool isUsiStylus) {
113 if (isUsiStylus) {
114 // This is a stylus connected over the Universal Stylus Initiative (USI) protocol.
115 // For metrics purposes, we treat this protocol as a separate bus.
116 return util::INPUT_DEVICE_USAGE_REPORTED__DEVICE_BUS__USI;
117 }
118
Harry Cuttsa34de522023-06-06 15:52:54 +0000119 // When adding cases to this switch, also add them to the copy of this method in
120 // InputDeviceMetricsCollector.cpp.
121 // TODO(b/286394420): deduplicate this method with the one in InputDeviceMetricsCollector.cpp.
122 switch (linuxBus) {
123 case BUS_USB:
124 return util::INPUT_DEVICE_USAGE_REPORTED__DEVICE_BUS__USB;
125 case BUS_BLUETOOTH:
126 return util::INPUT_DEVICE_USAGE_REPORTED__DEVICE_BUS__BLUETOOTH;
127 default:
128 return util::INPUT_DEVICE_USAGE_REPORTED__DEVICE_BUS__OTHER;
129 }
130}
131
132class MetricsAccumulator {
133public:
134 static MetricsAccumulator& getInstance() {
135 static MetricsAccumulator sAccumulator;
136 return sAccumulator;
137 }
138
Harry Cutts938c65d2023-12-13 19:04:02 +0000139 void recordFinger(const TouchpadInputMapper::MetricsIdentifier& id) {
140 std::scoped_lock lock(mLock);
141 mCounters[id].fingers++;
142 }
Harry Cuttsa34de522023-06-06 15:52:54 +0000143
Harry Cutts938c65d2023-12-13 19:04:02 +0000144 void recordPalm(const TouchpadInputMapper::MetricsIdentifier& id) {
145 std::scoped_lock lock(mLock);
146 mCounters[id].palms++;
147 }
Harry Cuttsa34de522023-06-06 15:52:54 +0000148
149 // Checks whether a Gesture struct is for the end of a gesture that we log metrics for, and
150 // records it if so.
151 void processGesture(const TouchpadInputMapper::MetricsIdentifier& id, const Gesture& gesture) {
Harry Cutts938c65d2023-12-13 19:04:02 +0000152 std::scoped_lock lock(mLock);
Harry Cuttsa34de522023-06-06 15:52:54 +0000153 switch (gesture.type) {
154 case kGestureTypeFling:
155 if (gesture.details.fling.fling_state == GESTURES_FLING_START) {
156 // Indicates the end of a two-finger scroll gesture.
157 mCounters[id].twoFingerSwipeGestures++;
158 }
159 break;
160 case kGestureTypeSwipeLift:
161 mCounters[id].threeFingerSwipeGestures++;
162 break;
163 case kGestureTypeFourFingerSwipeLift:
164 mCounters[id].fourFingerSwipeGestures++;
165 break;
166 case kGestureTypePinch:
167 if (gesture.details.pinch.zoom_state == GESTURES_ZOOM_END) {
168 mCounters[id].pinchGestures++;
169 }
170 break;
171 default:
172 // We're not interested in any other gestures.
173 break;
174 }
175 }
176
177private:
178 MetricsAccumulator() {
179 AStatsManager_setPullAtomCallback(android::util::TOUCHPAD_USAGE, /*metadata=*/nullptr,
180 MetricsAccumulator::pullAtomCallback, /*cookie=*/nullptr);
181 }
182
183 ~MetricsAccumulator() { AStatsManager_clearPullAtomCallback(android::util::TOUCHPAD_USAGE); }
184
185 static AStatsManager_PullAtomCallbackReturn pullAtomCallback(int32_t atomTag,
186 AStatsEventList* outEventList,
187 void* cookie) {
Harry Cutts53c5e772024-04-05 16:56:08 +0000188 ALOGI("Received pull request for touchpad usage atom");
Harry Cuttsa34de522023-06-06 15:52:54 +0000189 LOG_ALWAYS_FATAL_IF(atomTag != android::util::TOUCHPAD_USAGE);
190 MetricsAccumulator& accumulator = MetricsAccumulator::getInstance();
Harry Cutts938c65d2023-12-13 19:04:02 +0000191 accumulator.produceAtomsAndReset(*outEventList);
Harry Cuttsa34de522023-06-06 15:52:54 +0000192 return AStatsManager_PULL_SUCCESS;
193 }
194
Harry Cutts938c65d2023-12-13 19:04:02 +0000195 void produceAtomsAndReset(AStatsEventList& outEventList) {
Harry Cutts53c5e772024-04-05 16:56:08 +0000196 ALOGI("Acquiring lock for touchpad usage metrics...");
Harry Cutts938c65d2023-12-13 19:04:02 +0000197 std::scoped_lock lock(mLock);
198 produceAtomsLocked(outEventList);
199 resetCountersLocked();
200 }
201
202 void produceAtomsLocked(AStatsEventList& outEventList) const REQUIRES(mLock) {
Harry Cuttsc24483a2024-03-22 17:31:15 +0000203 ALOGI("Producing touchpad usage atoms for %zu counters", mCounters.size());
Harry Cuttsa34de522023-06-06 15:52:54 +0000204 for (auto& [id, counters] : mCounters) {
205 auto [busId, vendorId, productId, versionId] = id;
Harry Cutts938c65d2023-12-13 19:04:02 +0000206 addAStatsEvent(&outEventList, android::util::TOUCHPAD_USAGE, vendorId, productId,
Prabir Pradhan67d09ca2023-09-08 20:28:55 +0000207 versionId, linuxBusToInputDeviceBusEnum(busId, /*isUsi=*/false),
208 counters.fingers, counters.palms, counters.twoFingerSwipeGestures,
Harry Cuttsa34de522023-06-06 15:52:54 +0000209 counters.threeFingerSwipeGestures, counters.fourFingerSwipeGestures,
210 counters.pinchGestures);
211 }
212 }
213
Harry Cutts938c65d2023-12-13 19:04:02 +0000214 void resetCountersLocked() REQUIRES(mLock) { mCounters.clear(); }
Harry Cuttsa34de522023-06-06 15:52:54 +0000215
216 // Stores the counters for a specific touchpad model. Fields have the same meanings as those of
217 // the TouchpadUsage atom; see that definition for detailed documentation.
218 struct Counters {
219 int32_t fingers = 0;
220 int32_t palms = 0;
221
222 int32_t twoFingerSwipeGestures = 0;
223 int32_t threeFingerSwipeGestures = 0;
224 int32_t fourFingerSwipeGestures = 0;
225 int32_t pinchGestures = 0;
226 };
227
228 // Metrics are aggregated by device model and version, so if two devices of the same model and
229 // version are connected at once, they will have the same counters.
Harry Cutts938c65d2023-12-13 19:04:02 +0000230 std::map<TouchpadInputMapper::MetricsIdentifier, Counters> mCounters GUARDED_BY(mLock);
231
232 // Metrics are pulled by a binder thread, so we need to guard them with a mutex.
233 mutable std::mutex mLock;
Harry Cuttsa34de522023-06-06 15:52:54 +0000234};
235
Harry Cutts1f48a442022-11-15 17:38:36 +0000236} // namespace
237
Arpit Singh8e6fb252023-04-06 11:49:17 +0000238TouchpadInputMapper::TouchpadInputMapper(InputDeviceContext& deviceContext,
239 const InputReaderConfiguration& readerConfig)
Prabir Pradhanc8377b02024-02-26 21:20:30 +0000240 : TouchpadInputMapper(deviceContext, readerConfig, ENABLE_POINTER_CHOREOGRAPHER) {}
241
242TouchpadInputMapper::TouchpadInputMapper(InputDeviceContext& deviceContext,
243 const InputReaderConfiguration& readerConfig,
244 bool enablePointerChoreographer)
Arpit Singh8e6fb252023-04-06 11:49:17 +0000245 : InputMapper(deviceContext, readerConfig),
Harry Cutts1f48a442022-11-15 17:38:36 +0000246 mGestureInterpreter(NewGestureInterpreter(), DeleteGestureInterpreter),
Harry Cutts74235542022-11-24 15:52:53 +0000247 mPointerController(getContext()->getPointerController(getDeviceId())),
Harry Cutts8c7cb592023-08-23 17:20:13 +0000248 mTimerProvider(*getContext()),
Harry Cuttsbb24e272023-03-21 10:49:47 +0000249 mStateConverter(deviceContext, mMotionAccumulator),
250 mGestureConverter(*getContext(), deviceContext, getDeviceId()),
Harry Cuttsa34de522023-06-06 15:52:54 +0000251 mCapturedEventConverter(*getContext(), deviceContext, mMotionAccumulator, getDeviceId()),
Byoungho Jungee6268f2023-10-30 17:27:26 +0900252 mMetricsId(metricsIdFromInputDeviceIdentifier(deviceContext.getDeviceIdentifier())),
Prabir Pradhanc8377b02024-02-26 21:20:30 +0000253 mEnablePointerChoreographer(enablePointerChoreographer) {
Harry Cuttsbb24e272023-03-21 10:49:47 +0000254 RawAbsoluteAxisInfo slotAxisInfo;
255 deviceContext.getAbsoluteAxisInfo(ABS_MT_SLOT, &slotAxisInfo);
256 if (!slotAxisInfo.valid || slotAxisInfo.maxValue <= 0) {
257 ALOGW("Touchpad \"%s\" doesn't have a valid ABS_MT_SLOT axis, and probably won't work "
258 "properly.",
259 deviceContext.getName().c_str());
260 }
261 mMotionAccumulator.configure(deviceContext, slotAxisInfo.maxValue + 1, true);
262
Harry Cutts1f48a442022-11-15 17:38:36 +0000263 mGestureInterpreter->Initialize(GESTURES_DEVCLASS_TOUCHPAD);
264 mGestureInterpreter->SetHardwareProperties(createHardwareProperties(deviceContext));
Harry Cutts74235542022-11-24 15:52:53 +0000265 // Even though we don't explicitly delete copy/move semantics, it's safe to
Harry Cutts1b217912023-01-03 17:13:19 +0000266 // give away pointers to TouchpadInputMapper and its members here because
Harry Cutts74235542022-11-24 15:52:53 +0000267 // 1) mGestureInterpreter's lifecycle is determined by TouchpadInputMapper, and
268 // 2) TouchpadInputMapper is stored as a unique_ptr and not moved.
Harry Cutts1b217912023-01-03 17:13:19 +0000269 mGestureInterpreter->SetPropProvider(const_cast<GesturesPropProvider*>(&gesturePropProvider),
270 &mPropertyProvider);
Harry Cutts8c7cb592023-08-23 17:20:13 +0000271 if (input_flags::enable_gestures_library_timer_provider()) {
272 mGestureInterpreter->SetTimerProvider(const_cast<GesturesTimerProvider*>(
273 &kGestureTimerProvider),
274 &mTimerProvider);
275 }
Harry Cutts74235542022-11-24 15:52:53 +0000276 mGestureInterpreter->SetCallback(gestureInterpreterCallback, this);
Harry Cutts1f48a442022-11-15 17:38:36 +0000277}
Harry Cutts79cc9fa2022-10-28 15:32:39 +0000278
Harry Cutts74235542022-11-24 15:52:53 +0000279TouchpadInputMapper::~TouchpadInputMapper() {
280 if (mPointerController != nullptr) {
281 mPointerController->fade(PointerControllerInterface::Transition::IMMEDIATE);
282 }
Harry Cutts1b217912023-01-03 17:13:19 +0000283
Harry Cutts8c7cb592023-08-23 17:20:13 +0000284 // The gesture interpreter's destructor will try to free its property and timer providers,
285 // calling PropertyProvider::freeProperty and TimerProvider::freeTimer using a raw pointers.
286 // Depending on the declaration order in TouchpadInputMapper.h, those providers may have already
287 // been freed, causing allocation errors or use-after-free bugs. Depending on declaration order
288 // to avoid this seems rather fragile, so explicitly clear the providers here to ensure all the
289 // freeProperty and freeTimer calls happen before the providers are destructed.
Harry Cutts1b217912023-01-03 17:13:19 +0000290 mGestureInterpreter->SetPropProvider(nullptr, nullptr);
Harry Cutts8c7cb592023-08-23 17:20:13 +0000291 mGestureInterpreter->SetTimerProvider(nullptr, nullptr);
Harry Cutts74235542022-11-24 15:52:53 +0000292}
293
Harry Cutts79cc9fa2022-10-28 15:32:39 +0000294uint32_t TouchpadInputMapper::getSources() const {
295 return AINPUT_SOURCE_MOUSE | AINPUT_SOURCE_TOUCHPAD;
296}
297
Harry Cuttsd02ea102023-03-17 18:21:30 +0000298void TouchpadInputMapper::populateDeviceInfo(InputDeviceInfo& info) {
Harry Cutts8cd2abd2023-03-15 16:35:56 +0000299 InputMapper::populateDeviceInfo(info);
Harry Cuttsbb24e272023-03-21 10:49:47 +0000300 if (mPointerCaptured) {
301 mCapturedEventConverter.populateMotionRanges(info);
302 } else {
303 mGestureConverter.populateMotionRanges(info);
304 }
Harry Cutts8cd2abd2023-03-15 16:35:56 +0000305}
306
Harry Cuttsea73eaa2023-01-16 17:55:46 +0000307void TouchpadInputMapper::dump(std::string& dump) {
308 dump += INDENT2 "Touchpad Input Mapper:\n";
Harry Cuttsbb24e272023-03-21 10:49:47 +0000309 if (mResettingInterpreter) {
310 dump += INDENT3 "Currently resetting gesture interpreter\n";
311 }
312 dump += StringPrintf(INDENT3 "Pointer captured: %s\n", toString(mPointerCaptured));
Harry Cuttsea73eaa2023-01-16 17:55:46 +0000313 dump += INDENT3 "Gesture converter:\n";
314 dump += addLinePrefix(mGestureConverter.dump(), INDENT4);
315 dump += INDENT3 "Gesture properties:\n";
316 dump += addLinePrefix(mPropertyProvider.dump(), INDENT4);
Harry Cutts8c7cb592023-08-23 17:20:13 +0000317 if (input_flags::enable_gestures_library_timer_provider()) {
318 dump += INDENT3 "Timer provider:\n";
319 dump += addLinePrefix(mTimerProvider.dump(), INDENT4);
320 } else {
321 dump += INDENT3 "Timer provider: disabled by flag\n";
322 }
Harry Cuttsbb24e272023-03-21 10:49:47 +0000323 dump += INDENT3 "Captured event converter:\n";
324 dump += addLinePrefix(mCapturedEventConverter.dump(), INDENT4);
Josep del Riod0746382023-07-29 13:18:25 +0000325 dump += StringPrintf(INDENT3 "DisplayId: %s\n", toString(mDisplayId).c_str());
Harry Cuttsea73eaa2023-01-16 17:55:46 +0000326}
327
Arpit Singh4be4eef2023-03-28 14:26:01 +0000328std::list<NotifyArgs> TouchpadInputMapper::reconfigure(nsecs_t when,
Arpit Singhed6c3de2023-04-05 19:24:37 +0000329 const InputReaderConfiguration& config,
Prabir Pradhan4bf6d452023-04-18 21:26:56 +0000330 ConfigurationChanges changes) {
331 if (!changes.any()) {
Harry Cutts2b67ff12023-03-13 11:32:06 +0000332 // First time configuration
333 mPropertyProvider.loadPropertiesFromIdcFile(getDeviceContext().getConfiguration());
334 }
335
Prabir Pradhan4bf6d452023-04-18 21:26:56 +0000336 if (!changes.any() || changes.test(InputReaderConfiguration::Change::DISPLAY_INFO)) {
Josep del Riod0746382023-07-29 13:18:25 +0000337 mDisplayId = ADISPLAY_ID_NONE;
Byoungho Jungee6268f2023-10-30 17:27:26 +0900338 std::optional<DisplayViewport> resolvedViewport;
339 std::optional<FloatRect> boundsInLogicalDisplay;
340 if (auto assocViewport = mDeviceContext.getAssociatedViewport(); assocViewport) {
Josep del Riod0746382023-07-29 13:18:25 +0000341 // This InputDevice is associated with a viewport.
342 // Only generate events for the associated display.
Byoungho Jungee6268f2023-10-30 17:27:26 +0900343 mDisplayId = assocViewport->displayId;
344 resolvedViewport = *assocViewport;
345 if (!mEnablePointerChoreographer) {
346 const bool mismatchedPointerDisplay =
347 (assocViewport->displayId != mPointerController->getDisplayId());
348 if (mismatchedPointerDisplay) {
349 ALOGW("Touchpad \"%s\" associated viewport display does not match pointer "
350 "controller",
351 mDeviceContext.getName().c_str());
352 mDisplayId.reset();
353 }
Josep del Riod0746382023-07-29 13:18:25 +0000354 }
Josep del Riod0746382023-07-29 13:18:25 +0000355 } else {
356 // The InputDevice is not associated with a viewport, but it controls the mouse pointer.
Byoungho Jungee6268f2023-10-30 17:27:26 +0900357 if (mEnablePointerChoreographer) {
358 // Always use DISPLAY_ID_NONE for touchpad events.
359 // PointerChoreographer will make it target the correct the displayId later.
360 resolvedViewport =
361 getContext()->getPolicy()->getPointerViewportForAssociatedDisplay();
362 mDisplayId = resolvedViewport ? std::make_optional(ADISPLAY_ID_NONE) : std::nullopt;
363 } else {
364 mDisplayId = mPointerController->getDisplayId();
365 if (auto v = config.getDisplayViewportById(*mDisplayId); v) {
366 resolvedViewport = *v;
367 }
368 if (auto bounds = mPointerController->getBounds(); bounds) {
369 boundsInLogicalDisplay = *bounds;
370 }
Harry Cuttsedf6ce72023-01-04 12:15:53 +0000371 }
372 }
Byoungho Jungee6268f2023-10-30 17:27:26 +0900373
Josep del Riod0746382023-07-29 13:18:25 +0000374 mGestureConverter.setDisplayId(mDisplayId);
Byoungho Jungee6268f2023-10-30 17:27:26 +0900375 mGestureConverter.setOrientation(resolvedViewport
376 ? getInverseRotation(resolvedViewport->orientation)
377 : ui::ROTATION_0);
378
379 if (!boundsInLogicalDisplay) {
380 boundsInLogicalDisplay = resolvedViewport
381 ? FloatRect{static_cast<float>(resolvedViewport->logicalLeft),
382 static_cast<float>(resolvedViewport->logicalTop),
383 static_cast<float>(resolvedViewport->logicalRight - 1),
384 static_cast<float>(resolvedViewport->logicalBottom - 1)}
385 : FloatRect{0, 0, 0, 0};
386 }
387 mGestureConverter.setBoundsInLogicalDisplay(*boundsInLogicalDisplay);
Harry Cutts5ab90572024-01-08 14:00:48 +0000388
389 bumpGeneration();
Harry Cuttsedf6ce72023-01-04 12:15:53 +0000390 }
Prabir Pradhan4bf6d452023-04-18 21:26:56 +0000391 if (!changes.any() || changes.test(InputReaderConfiguration::Change::TOUCHPAD_SETTINGS)) {
Harry Cuttsd35a24b2023-01-30 15:09:30 +0000392 mPropertyProvider.getProperty("Use Custom Touchpad Pointer Accel Curve")
393 .setBoolValues({true});
394 GesturesProp accelCurveProp = mPropertyProvider.getProperty("Pointer Accel Curve");
395 accelCurveProp.setRealValues(
Arpit Singhed6c3de2023-04-05 19:24:37 +0000396 createAccelerationCurveForSensitivity(config.touchpadPointerSpeed,
Harry Cuttsd35a24b2023-01-30 15:09:30 +0000397 accelCurveProp.getCount()));
Wenxin Feng1ca50662023-05-03 14:00:12 -0700398 mPropertyProvider.getProperty("Use Custom Touchpad Scroll Accel Curve")
399 .setBoolValues({true});
400 GesturesProp scrollCurveProp = mPropertyProvider.getProperty("Scroll Accel Curve");
401 scrollCurveProp.setRealValues(
402 createAccelerationCurveForSensitivity(config.touchpadPointerSpeed,
403 scrollCurveProp.getCount()));
404 mPropertyProvider.getProperty("Scroll X Out Scale").setRealValues({1.0});
405 mPropertyProvider.getProperty("Scroll Y Out Scale").setRealValues({1.0});
Harry Cuttsa546ba82023-01-13 17:21:00 +0000406 mPropertyProvider.getProperty("Invert Scrolling")
Arpit Singhed6c3de2023-04-05 19:24:37 +0000407 .setBoolValues({config.touchpadNaturalScrollingEnabled});
Harry Cuttsa546ba82023-01-13 17:21:00 +0000408 mPropertyProvider.getProperty("Tap Enable")
Arpit Singhed6c3de2023-04-05 19:24:37 +0000409 .setBoolValues({config.touchpadTapToClickEnabled});
Harry Cuttse0e799d2024-01-24 16:27:56 +0000410 mPropertyProvider.getProperty("Tap Drag Enable")
411 .setBoolValues({config.touchpadTapDraggingEnabled});
Harry Cuttsa546ba82023-01-13 17:21:00 +0000412 mPropertyProvider.getProperty("Button Right Click Zone Enable")
Arpit Singhed6c3de2023-04-05 19:24:37 +0000413 .setBoolValues({config.touchpadRightClickZoneEnabled});
Harry Cuttsa546ba82023-01-13 17:21:00 +0000414 }
Harry Cuttsbb24e272023-03-21 10:49:47 +0000415 std::list<NotifyArgs> out;
Hiroki Sato25040232024-02-22 17:21:22 +0900416 if ((!changes.any() && config.pointerCaptureRequest.isEnable()) ||
Harry Cuttsbb24e272023-03-21 10:49:47 +0000417 changes.test(InputReaderConfiguration::Change::POINTER_CAPTURE)) {
Hiroki Sato25040232024-02-22 17:21:22 +0900418 mPointerCaptured = config.pointerCaptureRequest.isEnable();
Harry Cuttsbb24e272023-03-21 10:49:47 +0000419 // The motion ranges are going to change, so bump the generation to clear the cached ones.
420 bumpGeneration();
421 if (mPointerCaptured) {
422 // The touchpad is being captured, so we need to tidy up any fake fingers etc. that are
423 // still being reported for a gesture in progress.
424 out += reset(when);
425 mPointerController->fade(PointerControllerInterface::Transition::IMMEDIATE);
426 } else {
427 // We're transitioning from captured to uncaptured.
428 mCapturedEventConverter.reset();
429 }
430 if (changes.any()) {
431 out.push_back(NotifyDeviceResetArgs(getContext()->getNextId(), when, getDeviceId()));
432 }
433 }
434 return out;
Harry Cuttsedf6ce72023-01-04 12:15:53 +0000435}
436
Harry Cutts1f48a442022-11-15 17:38:36 +0000437std::list<NotifyArgs> TouchpadInputMapper::reset(nsecs_t when) {
Harry Cutts47db1c72022-12-13 19:20:47 +0000438 mStateConverter.reset();
Harry Cuttsbb24e272023-03-21 10:49:47 +0000439 resetGestureInterpreter(when);
Harry Cuttse9b71422023-03-14 16:54:44 +0000440 std::list<NotifyArgs> out = mGestureConverter.reset(when);
441 out += InputMapper::reset(when);
442 return out;
Harry Cutts1f48a442022-11-15 17:38:36 +0000443}
444
Harry Cuttsbb24e272023-03-21 10:49:47 +0000445void TouchpadInputMapper::resetGestureInterpreter(nsecs_t when) {
446 // The GestureInterpreter has no official reset method, but sending a HardwareState with no
447 // fingers down or buttons pressed should get it into a clean state.
448 HardwareState state;
449 state.timestamp = std::chrono::duration<stime_t>(std::chrono::nanoseconds(when)).count();
450 mResettingInterpreter = true;
451 mGestureInterpreter->PushHardwareState(&state);
452 mResettingInterpreter = false;
453}
454
Harry Cutts79cc9fa2022-10-28 15:32:39 +0000455std::list<NotifyArgs> TouchpadInputMapper::process(const RawEvent* rawEvent) {
Harry Cuttsbb24e272023-03-21 10:49:47 +0000456 if (mPointerCaptured) {
457 return mCapturedEventConverter.process(*rawEvent);
458 }
Arpit Singh33a10a62023-10-12 13:06:54 +0000459 if (mMotionAccumulator.getActiveSlotsCount() == 0) {
460 mGestureStartTime = rawEvent->when;
461 }
Harry Cutts47db1c72022-12-13 19:20:47 +0000462 std::optional<SelfContainedHardwareState> state = mStateConverter.processRawEvent(rawEvent);
463 if (state) {
Harry Cuttsa34de522023-06-06 15:52:54 +0000464 updatePalmDetectionMetrics();
Harry Cutts47db1c72022-12-13 19:20:47 +0000465 return sendHardwareState(rawEvent->when, rawEvent->readTime, *state);
466 } else {
467 return {};
Harry Cutts1f48a442022-11-15 17:38:36 +0000468 }
Harry Cutts79cc9fa2022-10-28 15:32:39 +0000469}
470
Harry Cuttsa34de522023-06-06 15:52:54 +0000471void TouchpadInputMapper::updatePalmDetectionMetrics() {
472 std::set<int32_t> currentTrackingIds;
473 for (size_t i = 0; i < mMotionAccumulator.getSlotCount(); i++) {
474 const MultiTouchMotionAccumulator::Slot& slot = mMotionAccumulator.getSlot(i);
475 if (!slot.isInUse()) {
476 continue;
477 }
478 currentTrackingIds.insert(slot.getTrackingId());
479 if (slot.getToolType() == ToolType::PALM) {
480 mPalmTrackingIds.insert(slot.getTrackingId());
481 }
482 }
483 std::vector<int32_t> liftedTouches;
484 std::set_difference(mLastFrameTrackingIds.begin(), mLastFrameTrackingIds.end(),
485 currentTrackingIds.begin(), currentTrackingIds.end(),
486 std::inserter(liftedTouches, liftedTouches.begin()));
487 for (int32_t trackingId : liftedTouches) {
488 if (mPalmTrackingIds.erase(trackingId) > 0) {
489 MetricsAccumulator::getInstance().recordPalm(mMetricsId);
490 } else {
491 MetricsAccumulator::getInstance().recordFinger(mMetricsId);
492 }
493 }
494 mLastFrameTrackingIds = currentTrackingIds;
495}
496
Harry Cutts47db1c72022-12-13 19:20:47 +0000497std::list<NotifyArgs> TouchpadInputMapper::sendHardwareState(nsecs_t when, nsecs_t readTime,
498 SelfContainedHardwareState schs) {
Harry Cutts287e19f2023-02-27 17:09:24 +0000499 ALOGD_IF(DEBUG_TOUCHPAD_GESTURES, "New hardware state: %s", schs.state.String().c_str());
Harry Cutts47db1c72022-12-13 19:20:47 +0000500 mGestureInterpreter->PushHardwareState(&schs.state);
Harry Cutts47db1c72022-12-13 19:20:47 +0000501 return processGestures(when, readTime);
Harry Cutts74235542022-11-24 15:52:53 +0000502}
503
Harry Cutts8c7cb592023-08-23 17:20:13 +0000504std::list<NotifyArgs> TouchpadInputMapper::timeoutExpired(nsecs_t when) {
505 if (!input_flags::enable_gestures_library_timer_provider()) {
506 return {};
507 }
508 mTimerProvider.triggerCallbacks(when);
509 return processGestures(when, when);
510}
511
Harry Cutts74235542022-11-24 15:52:53 +0000512void TouchpadInputMapper::consumeGesture(const Gesture* gesture) {
Harry Cuttsc5025372023-02-21 16:04:45 +0000513 ALOGD_IF(DEBUG_TOUCHPAD_GESTURES, "Gesture ready: %s", gesture->String().c_str());
Harry Cuttsbb24e272023-03-21 10:49:47 +0000514 if (mResettingInterpreter) {
515 // We already handle tidying up fake fingers etc. in GestureConverter::reset, so we should
516 // ignore any gestures produced from the interpreter while we're resetting it.
517 return;
518 }
Harry Cutts74235542022-11-24 15:52:53 +0000519 mGesturesToProcess.push_back(*gesture);
520}
521
522std::list<NotifyArgs> TouchpadInputMapper::processGestures(nsecs_t when, nsecs_t readTime) {
523 std::list<NotifyArgs> out = {};
Josep del Riod0746382023-07-29 13:18:25 +0000524 if (mDisplayId) {
525 MetricsAccumulator& metricsAccumulator = MetricsAccumulator::getInstance();
526 for (Gesture& gesture : mGesturesToProcess) {
Arpit Singh33a10a62023-10-12 13:06:54 +0000527 out += mGestureConverter.handleGesture(when, readTime, mGestureStartTime, gesture);
Josep del Riod0746382023-07-29 13:18:25 +0000528 metricsAccumulator.processGesture(mMetricsId, gesture);
529 }
Harry Cutts74235542022-11-24 15:52:53 +0000530 }
531 mGesturesToProcess.clear();
532 return out;
533}
534
Josep del Riod0746382023-07-29 13:18:25 +0000535std::optional<int32_t> TouchpadInputMapper::getAssociatedDisplayId() {
536 return mDisplayId;
537}
538
Harry Cutts79cc9fa2022-10-28 15:32:39 +0000539} // namespace android