blob: 721cdfdfb040abdfe8b83bf9463f33b60212990d [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) {
188 LOG_ALWAYS_FATAL_IF(atomTag != android::util::TOUCHPAD_USAGE);
189 MetricsAccumulator& accumulator = MetricsAccumulator::getInstance();
Harry Cutts938c65d2023-12-13 19:04:02 +0000190 accumulator.produceAtomsAndReset(*outEventList);
Harry Cuttsa34de522023-06-06 15:52:54 +0000191 return AStatsManager_PULL_SUCCESS;
192 }
193
Harry Cutts938c65d2023-12-13 19:04:02 +0000194 void produceAtomsAndReset(AStatsEventList& outEventList) {
195 std::scoped_lock lock(mLock);
196 produceAtomsLocked(outEventList);
197 resetCountersLocked();
198 }
199
200 void produceAtomsLocked(AStatsEventList& outEventList) const REQUIRES(mLock) {
Harry Cuttsc24483a2024-03-22 17:31:15 +0000201 ALOGI("Producing touchpad usage atoms for %zu counters", mCounters.size());
Harry Cuttsa34de522023-06-06 15:52:54 +0000202 for (auto& [id, counters] : mCounters) {
203 auto [busId, vendorId, productId, versionId] = id;
Harry Cutts938c65d2023-12-13 19:04:02 +0000204 addAStatsEvent(&outEventList, android::util::TOUCHPAD_USAGE, vendorId, productId,
Prabir Pradhan67d09ca2023-09-08 20:28:55 +0000205 versionId, linuxBusToInputDeviceBusEnum(busId, /*isUsi=*/false),
206 counters.fingers, counters.palms, counters.twoFingerSwipeGestures,
Harry Cuttsa34de522023-06-06 15:52:54 +0000207 counters.threeFingerSwipeGestures, counters.fourFingerSwipeGestures,
208 counters.pinchGestures);
209 }
210 }
211
Harry Cutts938c65d2023-12-13 19:04:02 +0000212 void resetCountersLocked() REQUIRES(mLock) { mCounters.clear(); }
Harry Cuttsa34de522023-06-06 15:52:54 +0000213
214 // Stores the counters for a specific touchpad model. Fields have the same meanings as those of
215 // the TouchpadUsage atom; see that definition for detailed documentation.
216 struct Counters {
217 int32_t fingers = 0;
218 int32_t palms = 0;
219
220 int32_t twoFingerSwipeGestures = 0;
221 int32_t threeFingerSwipeGestures = 0;
222 int32_t fourFingerSwipeGestures = 0;
223 int32_t pinchGestures = 0;
224 };
225
226 // Metrics are aggregated by device model and version, so if two devices of the same model and
227 // version are connected at once, they will have the same counters.
Harry Cutts938c65d2023-12-13 19:04:02 +0000228 std::map<TouchpadInputMapper::MetricsIdentifier, Counters> mCounters GUARDED_BY(mLock);
229
230 // Metrics are pulled by a binder thread, so we need to guard them with a mutex.
231 mutable std::mutex mLock;
Harry Cuttsa34de522023-06-06 15:52:54 +0000232};
233
Harry Cutts1f48a442022-11-15 17:38:36 +0000234} // namespace
235
Arpit Singh8e6fb252023-04-06 11:49:17 +0000236TouchpadInputMapper::TouchpadInputMapper(InputDeviceContext& deviceContext,
237 const InputReaderConfiguration& readerConfig)
Prabir Pradhanc8377b02024-02-26 21:20:30 +0000238 : TouchpadInputMapper(deviceContext, readerConfig, ENABLE_POINTER_CHOREOGRAPHER) {}
239
240TouchpadInputMapper::TouchpadInputMapper(InputDeviceContext& deviceContext,
241 const InputReaderConfiguration& readerConfig,
242 bool enablePointerChoreographer)
Arpit Singh8e6fb252023-04-06 11:49:17 +0000243 : InputMapper(deviceContext, readerConfig),
Harry Cutts1f48a442022-11-15 17:38:36 +0000244 mGestureInterpreter(NewGestureInterpreter(), DeleteGestureInterpreter),
Harry Cutts74235542022-11-24 15:52:53 +0000245 mPointerController(getContext()->getPointerController(getDeviceId())),
Harry Cutts8c7cb592023-08-23 17:20:13 +0000246 mTimerProvider(*getContext()),
Harry Cuttsbb24e272023-03-21 10:49:47 +0000247 mStateConverter(deviceContext, mMotionAccumulator),
248 mGestureConverter(*getContext(), deviceContext, getDeviceId()),
Harry Cuttsa34de522023-06-06 15:52:54 +0000249 mCapturedEventConverter(*getContext(), deviceContext, mMotionAccumulator, getDeviceId()),
Byoungho Jungee6268f2023-10-30 17:27:26 +0900250 mMetricsId(metricsIdFromInputDeviceIdentifier(deviceContext.getDeviceIdentifier())),
Prabir Pradhanc8377b02024-02-26 21:20:30 +0000251 mEnablePointerChoreographer(enablePointerChoreographer) {
Harry Cuttsbb24e272023-03-21 10:49:47 +0000252 RawAbsoluteAxisInfo slotAxisInfo;
253 deviceContext.getAbsoluteAxisInfo(ABS_MT_SLOT, &slotAxisInfo);
254 if (!slotAxisInfo.valid || slotAxisInfo.maxValue <= 0) {
255 ALOGW("Touchpad \"%s\" doesn't have a valid ABS_MT_SLOT axis, and probably won't work "
256 "properly.",
257 deviceContext.getName().c_str());
258 }
259 mMotionAccumulator.configure(deviceContext, slotAxisInfo.maxValue + 1, true);
260
Harry Cutts1f48a442022-11-15 17:38:36 +0000261 mGestureInterpreter->Initialize(GESTURES_DEVCLASS_TOUCHPAD);
262 mGestureInterpreter->SetHardwareProperties(createHardwareProperties(deviceContext));
Harry Cutts74235542022-11-24 15:52:53 +0000263 // Even though we don't explicitly delete copy/move semantics, it's safe to
Harry Cutts1b217912023-01-03 17:13:19 +0000264 // give away pointers to TouchpadInputMapper and its members here because
Harry Cutts74235542022-11-24 15:52:53 +0000265 // 1) mGestureInterpreter's lifecycle is determined by TouchpadInputMapper, and
266 // 2) TouchpadInputMapper is stored as a unique_ptr and not moved.
Harry Cutts1b217912023-01-03 17:13:19 +0000267 mGestureInterpreter->SetPropProvider(const_cast<GesturesPropProvider*>(&gesturePropProvider),
268 &mPropertyProvider);
Harry Cutts8c7cb592023-08-23 17:20:13 +0000269 if (input_flags::enable_gestures_library_timer_provider()) {
270 mGestureInterpreter->SetTimerProvider(const_cast<GesturesTimerProvider*>(
271 &kGestureTimerProvider),
272 &mTimerProvider);
273 }
Harry Cutts74235542022-11-24 15:52:53 +0000274 mGestureInterpreter->SetCallback(gestureInterpreterCallback, this);
Harry Cutts1f48a442022-11-15 17:38:36 +0000275}
Harry Cutts79cc9fa2022-10-28 15:32:39 +0000276
Harry Cutts74235542022-11-24 15:52:53 +0000277TouchpadInputMapper::~TouchpadInputMapper() {
278 if (mPointerController != nullptr) {
279 mPointerController->fade(PointerControllerInterface::Transition::IMMEDIATE);
280 }
Harry Cutts1b217912023-01-03 17:13:19 +0000281
Harry Cutts8c7cb592023-08-23 17:20:13 +0000282 // The gesture interpreter's destructor will try to free its property and timer providers,
283 // calling PropertyProvider::freeProperty and TimerProvider::freeTimer using a raw pointers.
284 // Depending on the declaration order in TouchpadInputMapper.h, those providers may have already
285 // been freed, causing allocation errors or use-after-free bugs. Depending on declaration order
286 // to avoid this seems rather fragile, so explicitly clear the providers here to ensure all the
287 // freeProperty and freeTimer calls happen before the providers are destructed.
Harry Cutts1b217912023-01-03 17:13:19 +0000288 mGestureInterpreter->SetPropProvider(nullptr, nullptr);
Harry Cutts8c7cb592023-08-23 17:20:13 +0000289 mGestureInterpreter->SetTimerProvider(nullptr, nullptr);
Harry Cutts74235542022-11-24 15:52:53 +0000290}
291
Harry Cutts79cc9fa2022-10-28 15:32:39 +0000292uint32_t TouchpadInputMapper::getSources() const {
293 return AINPUT_SOURCE_MOUSE | AINPUT_SOURCE_TOUCHPAD;
294}
295
Harry Cuttsd02ea102023-03-17 18:21:30 +0000296void TouchpadInputMapper::populateDeviceInfo(InputDeviceInfo& info) {
Harry Cutts8cd2abd2023-03-15 16:35:56 +0000297 InputMapper::populateDeviceInfo(info);
Harry Cuttsbb24e272023-03-21 10:49:47 +0000298 if (mPointerCaptured) {
299 mCapturedEventConverter.populateMotionRanges(info);
300 } else {
301 mGestureConverter.populateMotionRanges(info);
302 }
Harry Cutts8cd2abd2023-03-15 16:35:56 +0000303}
304
Harry Cuttsea73eaa2023-01-16 17:55:46 +0000305void TouchpadInputMapper::dump(std::string& dump) {
306 dump += INDENT2 "Touchpad Input Mapper:\n";
Harry Cuttsbb24e272023-03-21 10:49:47 +0000307 if (mResettingInterpreter) {
308 dump += INDENT3 "Currently resetting gesture interpreter\n";
309 }
310 dump += StringPrintf(INDENT3 "Pointer captured: %s\n", toString(mPointerCaptured));
Harry Cuttsea73eaa2023-01-16 17:55:46 +0000311 dump += INDENT3 "Gesture converter:\n";
312 dump += addLinePrefix(mGestureConverter.dump(), INDENT4);
313 dump += INDENT3 "Gesture properties:\n";
314 dump += addLinePrefix(mPropertyProvider.dump(), INDENT4);
Harry Cutts8c7cb592023-08-23 17:20:13 +0000315 if (input_flags::enable_gestures_library_timer_provider()) {
316 dump += INDENT3 "Timer provider:\n";
317 dump += addLinePrefix(mTimerProvider.dump(), INDENT4);
318 } else {
319 dump += INDENT3 "Timer provider: disabled by flag\n";
320 }
Harry Cuttsbb24e272023-03-21 10:49:47 +0000321 dump += INDENT3 "Captured event converter:\n";
322 dump += addLinePrefix(mCapturedEventConverter.dump(), INDENT4);
Josep del Riod0746382023-07-29 13:18:25 +0000323 dump += StringPrintf(INDENT3 "DisplayId: %s\n", toString(mDisplayId).c_str());
Harry Cuttsea73eaa2023-01-16 17:55:46 +0000324}
325
Arpit Singh4be4eef2023-03-28 14:26:01 +0000326std::list<NotifyArgs> TouchpadInputMapper::reconfigure(nsecs_t when,
Arpit Singhed6c3de2023-04-05 19:24:37 +0000327 const InputReaderConfiguration& config,
Prabir Pradhan4bf6d452023-04-18 21:26:56 +0000328 ConfigurationChanges changes) {
329 if (!changes.any()) {
Harry Cutts2b67ff12023-03-13 11:32:06 +0000330 // First time configuration
331 mPropertyProvider.loadPropertiesFromIdcFile(getDeviceContext().getConfiguration());
332 }
333
Prabir Pradhan4bf6d452023-04-18 21:26:56 +0000334 if (!changes.any() || changes.test(InputReaderConfiguration::Change::DISPLAY_INFO)) {
Josep del Riod0746382023-07-29 13:18:25 +0000335 mDisplayId = ADISPLAY_ID_NONE;
Byoungho Jungee6268f2023-10-30 17:27:26 +0900336 std::optional<DisplayViewport> resolvedViewport;
337 std::optional<FloatRect> boundsInLogicalDisplay;
338 if (auto assocViewport = mDeviceContext.getAssociatedViewport(); assocViewport) {
Josep del Riod0746382023-07-29 13:18:25 +0000339 // This InputDevice is associated with a viewport.
340 // Only generate events for the associated display.
Byoungho Jungee6268f2023-10-30 17:27:26 +0900341 mDisplayId = assocViewport->displayId;
342 resolvedViewport = *assocViewport;
343 if (!mEnablePointerChoreographer) {
344 const bool mismatchedPointerDisplay =
345 (assocViewport->displayId != mPointerController->getDisplayId());
346 if (mismatchedPointerDisplay) {
347 ALOGW("Touchpad \"%s\" associated viewport display does not match pointer "
348 "controller",
349 mDeviceContext.getName().c_str());
350 mDisplayId.reset();
351 }
Josep del Riod0746382023-07-29 13:18:25 +0000352 }
Josep del Riod0746382023-07-29 13:18:25 +0000353 } else {
354 // The InputDevice is not associated with a viewport, but it controls the mouse pointer.
Byoungho Jungee6268f2023-10-30 17:27:26 +0900355 if (mEnablePointerChoreographer) {
356 // Always use DISPLAY_ID_NONE for touchpad events.
357 // PointerChoreographer will make it target the correct the displayId later.
358 resolvedViewport =
359 getContext()->getPolicy()->getPointerViewportForAssociatedDisplay();
360 mDisplayId = resolvedViewport ? std::make_optional(ADISPLAY_ID_NONE) : std::nullopt;
361 } else {
362 mDisplayId = mPointerController->getDisplayId();
363 if (auto v = config.getDisplayViewportById(*mDisplayId); v) {
364 resolvedViewport = *v;
365 }
366 if (auto bounds = mPointerController->getBounds(); bounds) {
367 boundsInLogicalDisplay = *bounds;
368 }
Harry Cuttsedf6ce72023-01-04 12:15:53 +0000369 }
370 }
Byoungho Jungee6268f2023-10-30 17:27:26 +0900371
Josep del Riod0746382023-07-29 13:18:25 +0000372 mGestureConverter.setDisplayId(mDisplayId);
Byoungho Jungee6268f2023-10-30 17:27:26 +0900373 mGestureConverter.setOrientation(resolvedViewport
374 ? getInverseRotation(resolvedViewport->orientation)
375 : ui::ROTATION_0);
376
377 if (!boundsInLogicalDisplay) {
378 boundsInLogicalDisplay = resolvedViewport
379 ? FloatRect{static_cast<float>(resolvedViewport->logicalLeft),
380 static_cast<float>(resolvedViewport->logicalTop),
381 static_cast<float>(resolvedViewport->logicalRight - 1),
382 static_cast<float>(resolvedViewport->logicalBottom - 1)}
383 : FloatRect{0, 0, 0, 0};
384 }
385 mGestureConverter.setBoundsInLogicalDisplay(*boundsInLogicalDisplay);
Harry Cutts5ab90572024-01-08 14:00:48 +0000386
387 bumpGeneration();
Harry Cuttsedf6ce72023-01-04 12:15:53 +0000388 }
Prabir Pradhan4bf6d452023-04-18 21:26:56 +0000389 if (!changes.any() || changes.test(InputReaderConfiguration::Change::TOUCHPAD_SETTINGS)) {
Harry Cuttsd35a24b2023-01-30 15:09:30 +0000390 mPropertyProvider.getProperty("Use Custom Touchpad Pointer Accel Curve")
391 .setBoolValues({true});
392 GesturesProp accelCurveProp = mPropertyProvider.getProperty("Pointer Accel Curve");
393 accelCurveProp.setRealValues(
Arpit Singhed6c3de2023-04-05 19:24:37 +0000394 createAccelerationCurveForSensitivity(config.touchpadPointerSpeed,
Harry Cuttsd35a24b2023-01-30 15:09:30 +0000395 accelCurveProp.getCount()));
Wenxin Feng1ca50662023-05-03 14:00:12 -0700396 mPropertyProvider.getProperty("Use Custom Touchpad Scroll Accel Curve")
397 .setBoolValues({true});
398 GesturesProp scrollCurveProp = mPropertyProvider.getProperty("Scroll Accel Curve");
399 scrollCurveProp.setRealValues(
400 createAccelerationCurveForSensitivity(config.touchpadPointerSpeed,
401 scrollCurveProp.getCount()));
402 mPropertyProvider.getProperty("Scroll X Out Scale").setRealValues({1.0});
403 mPropertyProvider.getProperty("Scroll Y Out Scale").setRealValues({1.0});
Harry Cuttsa546ba82023-01-13 17:21:00 +0000404 mPropertyProvider.getProperty("Invert Scrolling")
Arpit Singhed6c3de2023-04-05 19:24:37 +0000405 .setBoolValues({config.touchpadNaturalScrollingEnabled});
Harry Cuttsa546ba82023-01-13 17:21:00 +0000406 mPropertyProvider.getProperty("Tap Enable")
Arpit Singhed6c3de2023-04-05 19:24:37 +0000407 .setBoolValues({config.touchpadTapToClickEnabled});
Harry Cuttse0e799d2024-01-24 16:27:56 +0000408 mPropertyProvider.getProperty("Tap Drag Enable")
409 .setBoolValues({config.touchpadTapDraggingEnabled});
Harry Cuttsa546ba82023-01-13 17:21:00 +0000410 mPropertyProvider.getProperty("Button Right Click Zone Enable")
Arpit Singhed6c3de2023-04-05 19:24:37 +0000411 .setBoolValues({config.touchpadRightClickZoneEnabled});
Harry Cuttsa546ba82023-01-13 17:21:00 +0000412 }
Harry Cuttsbb24e272023-03-21 10:49:47 +0000413 std::list<NotifyArgs> out;
Hiroki Sato25040232024-02-22 17:21:22 +0900414 if ((!changes.any() && config.pointerCaptureRequest.isEnable()) ||
Harry Cuttsbb24e272023-03-21 10:49:47 +0000415 changes.test(InputReaderConfiguration::Change::POINTER_CAPTURE)) {
Hiroki Sato25040232024-02-22 17:21:22 +0900416 mPointerCaptured = config.pointerCaptureRequest.isEnable();
Harry Cuttsbb24e272023-03-21 10:49:47 +0000417 // The motion ranges are going to change, so bump the generation to clear the cached ones.
418 bumpGeneration();
419 if (mPointerCaptured) {
420 // The touchpad is being captured, so we need to tidy up any fake fingers etc. that are
421 // still being reported for a gesture in progress.
422 out += reset(when);
423 mPointerController->fade(PointerControllerInterface::Transition::IMMEDIATE);
424 } else {
425 // We're transitioning from captured to uncaptured.
426 mCapturedEventConverter.reset();
427 }
428 if (changes.any()) {
429 out.push_back(NotifyDeviceResetArgs(getContext()->getNextId(), when, getDeviceId()));
430 }
431 }
432 return out;
Harry Cuttsedf6ce72023-01-04 12:15:53 +0000433}
434
Harry Cutts1f48a442022-11-15 17:38:36 +0000435std::list<NotifyArgs> TouchpadInputMapper::reset(nsecs_t when) {
Harry Cutts47db1c72022-12-13 19:20:47 +0000436 mStateConverter.reset();
Harry Cuttsbb24e272023-03-21 10:49:47 +0000437 resetGestureInterpreter(when);
Harry Cuttse9b71422023-03-14 16:54:44 +0000438 std::list<NotifyArgs> out = mGestureConverter.reset(when);
439 out += InputMapper::reset(when);
440 return out;
Harry Cutts1f48a442022-11-15 17:38:36 +0000441}
442
Harry Cuttsbb24e272023-03-21 10:49:47 +0000443void TouchpadInputMapper::resetGestureInterpreter(nsecs_t when) {
444 // The GestureInterpreter has no official reset method, but sending a HardwareState with no
445 // fingers down or buttons pressed should get it into a clean state.
446 HardwareState state;
447 state.timestamp = std::chrono::duration<stime_t>(std::chrono::nanoseconds(when)).count();
448 mResettingInterpreter = true;
449 mGestureInterpreter->PushHardwareState(&state);
450 mResettingInterpreter = false;
451}
452
Harry Cutts79cc9fa2022-10-28 15:32:39 +0000453std::list<NotifyArgs> TouchpadInputMapper::process(const RawEvent* rawEvent) {
Harry Cuttsbb24e272023-03-21 10:49:47 +0000454 if (mPointerCaptured) {
455 return mCapturedEventConverter.process(*rawEvent);
456 }
Arpit Singh33a10a62023-10-12 13:06:54 +0000457 if (mMotionAccumulator.getActiveSlotsCount() == 0) {
458 mGestureStartTime = rawEvent->when;
459 }
Harry Cutts47db1c72022-12-13 19:20:47 +0000460 std::optional<SelfContainedHardwareState> state = mStateConverter.processRawEvent(rawEvent);
461 if (state) {
Harry Cuttsa34de522023-06-06 15:52:54 +0000462 updatePalmDetectionMetrics();
Harry Cutts47db1c72022-12-13 19:20:47 +0000463 return sendHardwareState(rawEvent->when, rawEvent->readTime, *state);
464 } else {
465 return {};
Harry Cutts1f48a442022-11-15 17:38:36 +0000466 }
Harry Cutts79cc9fa2022-10-28 15:32:39 +0000467}
468
Harry Cuttsa34de522023-06-06 15:52:54 +0000469void TouchpadInputMapper::updatePalmDetectionMetrics() {
470 std::set<int32_t> currentTrackingIds;
471 for (size_t i = 0; i < mMotionAccumulator.getSlotCount(); i++) {
472 const MultiTouchMotionAccumulator::Slot& slot = mMotionAccumulator.getSlot(i);
473 if (!slot.isInUse()) {
474 continue;
475 }
476 currentTrackingIds.insert(slot.getTrackingId());
477 if (slot.getToolType() == ToolType::PALM) {
478 mPalmTrackingIds.insert(slot.getTrackingId());
479 }
480 }
481 std::vector<int32_t> liftedTouches;
482 std::set_difference(mLastFrameTrackingIds.begin(), mLastFrameTrackingIds.end(),
483 currentTrackingIds.begin(), currentTrackingIds.end(),
484 std::inserter(liftedTouches, liftedTouches.begin()));
485 for (int32_t trackingId : liftedTouches) {
486 if (mPalmTrackingIds.erase(trackingId) > 0) {
487 MetricsAccumulator::getInstance().recordPalm(mMetricsId);
488 } else {
489 MetricsAccumulator::getInstance().recordFinger(mMetricsId);
490 }
491 }
492 mLastFrameTrackingIds = currentTrackingIds;
493}
494
Harry Cutts47db1c72022-12-13 19:20:47 +0000495std::list<NotifyArgs> TouchpadInputMapper::sendHardwareState(nsecs_t when, nsecs_t readTime,
496 SelfContainedHardwareState schs) {
Harry Cutts287e19f2023-02-27 17:09:24 +0000497 ALOGD_IF(DEBUG_TOUCHPAD_GESTURES, "New hardware state: %s", schs.state.String().c_str());
Harry Cutts47db1c72022-12-13 19:20:47 +0000498 mGestureInterpreter->PushHardwareState(&schs.state);
Harry Cutts47db1c72022-12-13 19:20:47 +0000499 return processGestures(when, readTime);
Harry Cutts74235542022-11-24 15:52:53 +0000500}
501
Harry Cutts8c7cb592023-08-23 17:20:13 +0000502std::list<NotifyArgs> TouchpadInputMapper::timeoutExpired(nsecs_t when) {
503 if (!input_flags::enable_gestures_library_timer_provider()) {
504 return {};
505 }
506 mTimerProvider.triggerCallbacks(when);
507 return processGestures(when, when);
508}
509
Harry Cutts74235542022-11-24 15:52:53 +0000510void TouchpadInputMapper::consumeGesture(const Gesture* gesture) {
Harry Cuttsc5025372023-02-21 16:04:45 +0000511 ALOGD_IF(DEBUG_TOUCHPAD_GESTURES, "Gesture ready: %s", gesture->String().c_str());
Harry Cuttsbb24e272023-03-21 10:49:47 +0000512 if (mResettingInterpreter) {
513 // We already handle tidying up fake fingers etc. in GestureConverter::reset, so we should
514 // ignore any gestures produced from the interpreter while we're resetting it.
515 return;
516 }
Harry Cutts74235542022-11-24 15:52:53 +0000517 mGesturesToProcess.push_back(*gesture);
518}
519
520std::list<NotifyArgs> TouchpadInputMapper::processGestures(nsecs_t when, nsecs_t readTime) {
521 std::list<NotifyArgs> out = {};
Josep del Riod0746382023-07-29 13:18:25 +0000522 if (mDisplayId) {
523 MetricsAccumulator& metricsAccumulator = MetricsAccumulator::getInstance();
524 for (Gesture& gesture : mGesturesToProcess) {
Arpit Singh33a10a62023-10-12 13:06:54 +0000525 out += mGestureConverter.handleGesture(when, readTime, mGestureStartTime, gesture);
Josep del Riod0746382023-07-29 13:18:25 +0000526 metricsAccumulator.processGesture(mMetricsId, gesture);
527 }
Harry Cutts74235542022-11-24 15:52:53 +0000528 }
529 mGesturesToProcess.clear();
530 return out;
531}
532
Josep del Riod0746382023-07-29 13:18:25 +0000533std::optional<int32_t> TouchpadInputMapper::getAssociatedDisplayId() {
534 return mDisplayId;
535}
536
Harry Cutts79cc9fa2022-10-28 15:32:39 +0000537} // namespace android