blob: 4744db0a17395af5dad7a0697660bec24c0cdf4f [file] [log] [blame]
Siarhei Vishniakouba0a8752021-09-14 14:43:25 -07001/*
2 * Copyright (C) 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#define LOG_TAG "UnwantedInteractionBlocker"
18#include "UnwantedInteractionBlocker.h"
19
20#include <android-base/stringprintf.h>
Siarhei Vishniakoua91d8572022-05-17 05:03:42 -070021#include <input/PrintTools.h>
Siarhei Vishniakouba0a8752021-09-14 14:43:25 -070022#include <inttypes.h>
23#include <linux/input-event-codes.h>
24#include <linux/input.h>
25#include <server_configurable_flags/get_flags.h>
26
27#include "ui/events/ozone/evdev/touch_filter/neural_stylus_palm_detection_filter.h"
28#include "ui/events/ozone/evdev/touch_filter/palm_model/onedevice_train_palm_detection_filter_model.h"
29
30using android::base::StringPrintf;
31
Siarhei Vishniakou15a5c5a2022-07-06 15:42:57 -070032/**
33 * This type is declared here to ensure consistency between the instantiated type (used in the
34 * constructor via std::make_unique) and the cast-to type (used in PalmRejector::dump() with
35 * static_cast). Due to the lack of rtti support, dynamic_cast is not available, so this can't be
36 * checked at runtime to avoid undefined behaviour.
37 */
38using PalmFilterImplementation = ::ui::NeuralStylusPalmDetectionFilter;
39
Siarhei Vishniakouba0a8752021-09-14 14:43:25 -070040namespace android {
41
Siarhei Vishniakoud5fe5182022-07-20 23:28:40 +000042/**
43 * Log detailed debug messages about each inbound motion event notification to the blocker.
44 * Enable this via "adb shell setprop log.tag.UnwantedInteractionBlockerInboundMotion DEBUG"
45 * (requires restart)
46 */
47const bool DEBUG_INBOUND_MOTION =
48 __android_log_is_loggable(ANDROID_LOG_DEBUG, LOG_TAG "InboundMotion", ANDROID_LOG_INFO);
49
50/**
51 * Log detailed debug messages about each outbound motion event processed by the blocker.
52 * Enable this via "adb shell setprop log.tag.UnwantedInteractionBlockerOutboundMotion DEBUG"
53 * (requires restart)
54 */
55const bool DEBUG_OUTBOUND_MOTION =
56 __android_log_is_loggable(ANDROID_LOG_DEBUG, LOG_TAG "OutboundMotion", ANDROID_LOG_INFO);
57
58/**
59 * Log the data sent to the model and received back from the model.
60 * Enable this via "adb shell setprop log.tag.UnwantedInteractionBlockerModel DEBUG"
61 * (requires restart)
62 */
63const bool DEBUG_MODEL =
64 __android_log_is_loggable(ANDROID_LOG_DEBUG, LOG_TAG "Model", ANDROID_LOG_INFO);
65
Siarhei Vishniakouba0a8752021-09-14 14:43:25 -070066// Category (=namespace) name for the input settings that are applied at boot time
67static const char* INPUT_NATIVE_BOOT = "input_native_boot";
68/**
69 * Feature flag name. This flag determines whether palm rejection is enabled. To enable, specify
70 * 'true' (not case sensitive) or '1'. To disable, specify any other value.
71 */
72static const char* PALM_REJECTION_ENABLED = "palm_rejection_enabled";
73
74static std::string toLower(std::string s) {
75 std::transform(s.begin(), s.end(), s.begin(), [](unsigned char c) { return std::tolower(c); });
76 return s;
77}
78
79static bool isFromTouchscreen(int32_t source) {
Siarhei Vishniakouf6db4c32022-02-10 19:46:34 -080080 return isFromSource(source, AINPUT_SOURCE_TOUCHSCREEN) &&
81 !isFromSource(source, AINPUT_SOURCE_STYLUS);
Siarhei Vishniakouba0a8752021-09-14 14:43:25 -070082}
83
84static ::base::TimeTicks toChromeTimestamp(nsecs_t eventTime) {
Siarhei Vishniakou229a8802022-07-28 21:58:56 +000085 return ::base::TimeTicks::UnixEpoch() + ::base::TimeDelta::FromNanosecondsD(eventTime);
Siarhei Vishniakouba0a8752021-09-14 14:43:25 -070086}
87
88/**
89 * Return true if palm rejection is enabled via the server configurable flags. Return false
90 * otherwise.
91 */
92static bool isPalmRejectionEnabled() {
93 std::string value = toLower(
94 server_configurable_flags::GetServerConfigurableFlag(INPUT_NATIVE_BOOT,
95 PALM_REJECTION_ENABLED, "false"));
96 if (value == "true" || value == "1") {
97 return true;
98 }
99 return false;
100}
101
102static int getLinuxToolType(int32_t toolType) {
103 switch (toolType) {
104 case AMOTION_EVENT_TOOL_TYPE_FINGER:
105 return MT_TOOL_FINGER;
106 case AMOTION_EVENT_TOOL_TYPE_STYLUS:
107 return MT_TOOL_PEN;
108 case AMOTION_EVENT_TOOL_TYPE_PALM:
109 return MT_TOOL_PALM;
110 }
111 ALOGW("Got tool type %" PRId32 ", converting to MT_TOOL_FINGER", toolType);
112 return MT_TOOL_FINGER;
113}
114
Siarhei Vishniakouba0a8752021-09-14 14:43:25 -0700115static int32_t getActionUpForPointerId(const NotifyMotionArgs& args, int32_t pointerId) {
116 for (size_t i = 0; i < args.pointerCount; i++) {
117 if (pointerId == args.pointerProperties[i].id) {
118 return AMOTION_EVENT_ACTION_POINTER_UP |
119 (i << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
120 }
121 }
122 LOG_ALWAYS_FATAL("Can't find pointerId %" PRId32 " in %s", pointerId, args.dump().c_str());
123}
124
125/**
126 * Find the action for individual pointer at the given pointer index.
127 * This is always equal to MotionEvent::getActionMasked, except for
128 * POINTER_UP or POINTER_DOWN events. For example, in a POINTER_UP event, the action for
129 * the active pointer is ACTION_POINTER_UP, while the action for the other pointers is ACTION_MOVE.
130 */
131static int32_t resolveActionForPointer(uint8_t pointerIndex, int32_t action) {
132 const int32_t actionMasked = MotionEvent::getActionMasked(action);
133 if (actionMasked != AMOTION_EVENT_ACTION_POINTER_DOWN &&
134 actionMasked != AMOTION_EVENT_ACTION_POINTER_UP) {
135 return actionMasked;
136 }
137 // This is a POINTER_DOWN or POINTER_UP event
138 const uint8_t actionIndex = MotionEvent::getActionIndex(action);
139 if (pointerIndex == actionIndex) {
140 return actionMasked;
141 }
142 // When POINTER_DOWN or POINTER_UP happens, it's actually a MOVE for all of the other
143 // pointers
144 return AMOTION_EVENT_ACTION_MOVE;
145}
146
Siarhei Vishniakouba0a8752021-09-14 14:43:25 -0700147/**
148 * Remove the data for the provided pointers from the args. The pointers are identified by their
149 * pointerId, not by the index inside the array.
150 * Return the new NotifyMotionArgs struct that has the remaining pointers.
151 * The only fields that may be different in the returned args from the provided args are:
152 * - action
153 * - pointerCount
154 * - pointerProperties
155 * - pointerCoords
156 * Action might change because it contains a pointer index. If another pointer is removed, the
157 * active pointer index would be shifted.
158 * Do not call this function for events with POINTER_UP or POINTER_DOWN events when removed pointer
159 * id is the acting pointer id.
160 *
161 * @param args the args from which the pointers should be removed
162 * @param pointerIds the pointer ids of the pointers that should be removed
163 */
164NotifyMotionArgs removePointerIds(const NotifyMotionArgs& args,
165 const std::set<int32_t>& pointerIds) {
166 const uint8_t actionIndex = MotionEvent::getActionIndex(args.action);
167 const int32_t actionMasked = MotionEvent::getActionMasked(args.action);
168 const bool isPointerUpOrDownAction = actionMasked == AMOTION_EVENT_ACTION_POINTER_DOWN ||
169 actionMasked == AMOTION_EVENT_ACTION_POINTER_UP;
170
171 NotifyMotionArgs newArgs{args};
172 newArgs.pointerCount = 0;
173 int32_t newActionIndex = 0;
174 for (uint32_t i = 0; i < args.pointerCount; i++) {
175 const int32_t pointerId = args.pointerProperties[i].id;
176 if (pointerIds.find(pointerId) != pointerIds.end()) {
177 // skip this pointer
178 if (isPointerUpOrDownAction && i == actionIndex) {
179 // The active pointer is being removed, so the action is no longer valid.
180 // Set the action to 'UNKNOWN' here. The caller is responsible for updating this
181 // action later to a proper value.
182 newArgs.action = ACTION_UNKNOWN;
183 }
184 continue;
185 }
186 newArgs.pointerProperties[newArgs.pointerCount].copyFrom(args.pointerProperties[i]);
187 newArgs.pointerCoords[newArgs.pointerCount].copyFrom(args.pointerCoords[i]);
188 if (i == actionIndex) {
189 newActionIndex = newArgs.pointerCount;
190 }
191 newArgs.pointerCount++;
192 }
193 // Update POINTER_DOWN or POINTER_UP actions
194 if (isPointerUpOrDownAction && newArgs.action != ACTION_UNKNOWN) {
195 newArgs.action =
196 actionMasked | (newActionIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
197 // Convert POINTER_DOWN and POINTER_UP to DOWN and UP if there's only 1 pointer remaining
198 if (newArgs.pointerCount == 1) {
199 if (actionMasked == AMOTION_EVENT_ACTION_POINTER_DOWN) {
200 newArgs.action = AMOTION_EVENT_ACTION_DOWN;
201 } else if (actionMasked == AMOTION_EVENT_ACTION_POINTER_UP) {
202 newArgs.action = AMOTION_EVENT_ACTION_UP;
203 }
204 }
205 }
206 return newArgs;
207}
208
209std::optional<AndroidPalmFilterDeviceInfo> createPalmFilterDeviceInfo(
210 const InputDeviceInfo& deviceInfo) {
211 if (!isFromTouchscreen(deviceInfo.getSources())) {
212 return std::nullopt;
213 }
214 AndroidPalmFilterDeviceInfo out;
215 const InputDeviceInfo::MotionRange* axisX =
216 deviceInfo.getMotionRange(AMOTION_EVENT_AXIS_X, AINPUT_SOURCE_TOUCHSCREEN);
217 if (axisX != nullptr) {
218 out.max_x = axisX->max;
219 out.x_res = axisX->resolution;
220 } else {
221 ALOGW("Palm rejection is disabled for %s because AXIS_X is not supported",
222 deviceInfo.getDisplayName().c_str());
223 return std::nullopt;
224 }
225 const InputDeviceInfo::MotionRange* axisY =
226 deviceInfo.getMotionRange(AMOTION_EVENT_AXIS_Y, AINPUT_SOURCE_TOUCHSCREEN);
227 if (axisY != nullptr) {
228 out.max_y = axisY->max;
229 out.y_res = axisY->resolution;
230 } else {
231 ALOGW("Palm rejection is disabled for %s because AXIS_Y is not supported",
232 deviceInfo.getDisplayName().c_str());
233 return std::nullopt;
234 }
235 const InputDeviceInfo::MotionRange* axisMajor =
236 deviceInfo.getMotionRange(AMOTION_EVENT_AXIS_TOUCH_MAJOR, AINPUT_SOURCE_TOUCHSCREEN);
237 if (axisMajor != nullptr) {
238 out.major_radius_res = axisMajor->resolution;
239 out.touch_major_res = axisMajor->resolution;
240 } else {
241 return std::nullopt;
242 }
243 const InputDeviceInfo::MotionRange* axisMinor =
244 deviceInfo.getMotionRange(AMOTION_EVENT_AXIS_TOUCH_MINOR, AINPUT_SOURCE_TOUCHSCREEN);
245 if (axisMinor != nullptr) {
246 out.minor_radius_res = axisMinor->resolution;
247 out.touch_minor_res = axisMinor->resolution;
248 out.minor_radius_supported = true;
249 } else {
250 out.minor_radius_supported = false;
251 }
252
253 return out;
254}
255
256/**
257 * Synthesize CANCEL events for any new pointers that should be canceled, while removing pointers
258 * that have already been canceled.
259 * The flow of the function is as follows:
260 * 1. Remove all already canceled pointers
261 * 2. Cancel all newly suppressed pointers
262 * 3. Decide what to do with the current event : keep it, or drop it
263 * The pointers can never be "unsuppressed": once a pointer is canceled, it will never become valid.
264 */
265std::vector<NotifyMotionArgs> cancelSuppressedPointers(
266 const NotifyMotionArgs& args, const std::set<int32_t>& oldSuppressedPointerIds,
267 const std::set<int32_t>& newSuppressedPointerIds) {
268 LOG_ALWAYS_FATAL_IF(args.pointerCount == 0, "0 pointers in %s", args.dump().c_str());
269
270 // First, let's remove the old suppressed pointers. They've already been canceled previously.
271 NotifyMotionArgs oldArgs = removePointerIds(args, oldSuppressedPointerIds);
272
273 // Cancel any newly suppressed pointers.
274 std::vector<NotifyMotionArgs> out;
275 const int32_t activePointerId =
276 args.pointerProperties[MotionEvent::getActionIndex(args.action)].id;
277 const int32_t actionMasked = MotionEvent::getActionMasked(args.action);
278 // We will iteratively remove pointers from 'removedArgs'.
279 NotifyMotionArgs removedArgs{oldArgs};
280 for (uint32_t i = 0; i < oldArgs.pointerCount; i++) {
281 const int32_t pointerId = oldArgs.pointerProperties[i].id;
282 if (newSuppressedPointerIds.find(pointerId) == newSuppressedPointerIds.end()) {
283 // This is a pointer that should not be canceled. Move on.
284 continue;
285 }
286 if (pointerId == activePointerId && actionMasked == AMOTION_EVENT_ACTION_POINTER_DOWN) {
287 // Remove this pointer, but don't cancel it. We'll just not send the POINTER_DOWN event
288 removedArgs = removePointerIds(removedArgs, {pointerId});
289 continue;
290 }
291
292 if (removedArgs.pointerCount == 1) {
293 // We are about to remove the last pointer, which means there will be no more gesture
294 // remaining. This is identical to canceling all pointers, so just send a single CANCEL
295 // event, without any of the preceding POINTER_UP with FLAG_CANCELED events.
296 oldArgs.flags |= AMOTION_EVENT_FLAG_CANCELED;
297 oldArgs.action = AMOTION_EVENT_ACTION_CANCEL;
298 return {oldArgs};
299 }
300 // Cancel the current pointer
301 out.push_back(removedArgs);
302 out.back().flags |= AMOTION_EVENT_FLAG_CANCELED;
303 out.back().action = getActionUpForPointerId(out.back(), pointerId);
304
305 // Remove the newly canceled pointer from the args
306 removedArgs = removePointerIds(removedArgs, {pointerId});
307 }
308
309 // Now 'removedArgs' contains only pointers that are valid.
310 if (removedArgs.pointerCount <= 0 || removedArgs.action == ACTION_UNKNOWN) {
311 return out;
312 }
313 out.push_back(removedArgs);
314 return out;
315}
316
317UnwantedInteractionBlocker::UnwantedInteractionBlocker(InputListenerInterface& listener)
318 : UnwantedInteractionBlocker(listener, isPalmRejectionEnabled()){};
319
320UnwantedInteractionBlocker::UnwantedInteractionBlocker(InputListenerInterface& listener,
321 bool enablePalmRejection)
Siarhei Vishniakoua91d8572022-05-17 05:03:42 -0700322 : mQueuedListener(listener), mEnablePalmRejection(enablePalmRejection) {}
Siarhei Vishniakouba0a8752021-09-14 14:43:25 -0700323
324void UnwantedInteractionBlocker::notifyConfigurationChanged(
325 const NotifyConfigurationChangedArgs* args) {
Siarhei Vishniakoua91d8572022-05-17 05:03:42 -0700326 mQueuedListener.notifyConfigurationChanged(args);
327 mQueuedListener.flush();
Siarhei Vishniakouba0a8752021-09-14 14:43:25 -0700328}
329
330void UnwantedInteractionBlocker::notifyKey(const NotifyKeyArgs* args) {
Siarhei Vishniakoua91d8572022-05-17 05:03:42 -0700331 mQueuedListener.notifyKey(args);
332 mQueuedListener.flush();
Siarhei Vishniakouba0a8752021-09-14 14:43:25 -0700333}
334
335void UnwantedInteractionBlocker::notifyMotion(const NotifyMotionArgs* args) {
Siarhei Vishniakoud5fe5182022-07-20 23:28:40 +0000336 ALOGD_IF(DEBUG_INBOUND_MOTION, "%s: %s", __func__, args->dump().c_str());
Siarhei Vishniakoua91d8572022-05-17 05:03:42 -0700337 { // acquire lock
338 std::scoped_lock lock(mLock);
339 const std::vector<NotifyMotionArgs> processedArgs =
340 mPreferStylusOverTouchBlocker.processMotion(*args);
341 for (const NotifyMotionArgs& loopArgs : processedArgs) {
342 notifyMotionLocked(&loopArgs);
343 }
344 } // release lock
345
346 // Call out to the next stage without holding the lock
347 mQueuedListener.flush();
Siarhei Vishniakou814ace32022-03-04 15:12:16 -0800348}
349
Siarhei Vishniakoud5fe5182022-07-20 23:28:40 +0000350void UnwantedInteractionBlocker::enqueueOutboundMotionLocked(const NotifyMotionArgs& args) {
351 ALOGD_IF(DEBUG_OUTBOUND_MOTION, "%s: %s", __func__, args.dump().c_str());
352 mQueuedListener.notifyMotion(&args);
353}
354
Siarhei Vishniakoua91d8572022-05-17 05:03:42 -0700355void UnwantedInteractionBlocker::notifyMotionLocked(const NotifyMotionArgs* args) {
Siarhei Vishniakouba0a8752021-09-14 14:43:25 -0700356 auto it = mPalmRejectors.find(args->deviceId);
357 const bool sendToPalmRejector = it != mPalmRejectors.end() && isFromTouchscreen(args->source);
358 if (!sendToPalmRejector) {
Siarhei Vishniakoud5fe5182022-07-20 23:28:40 +0000359 enqueueOutboundMotionLocked(*args);
Siarhei Vishniakouba0a8752021-09-14 14:43:25 -0700360 return;
361 }
362
Siarhei Vishniakoua91d8572022-05-17 05:03:42 -0700363 std::vector<NotifyMotionArgs> processedArgs = it->second.processMotion(*args);
364 for (const NotifyMotionArgs& loopArgs : processedArgs) {
Siarhei Vishniakoud5fe5182022-07-20 23:28:40 +0000365 enqueueOutboundMotionLocked(loopArgs);
Siarhei Vishniakouba0a8752021-09-14 14:43:25 -0700366 }
367}
368
369void UnwantedInteractionBlocker::notifySwitch(const NotifySwitchArgs* args) {
Siarhei Vishniakoua91d8572022-05-17 05:03:42 -0700370 mQueuedListener.notifySwitch(args);
371 mQueuedListener.flush();
Siarhei Vishniakouba0a8752021-09-14 14:43:25 -0700372}
373
374void UnwantedInteractionBlocker::notifySensor(const NotifySensorArgs* args) {
Siarhei Vishniakoua91d8572022-05-17 05:03:42 -0700375 mQueuedListener.notifySensor(args);
376 mQueuedListener.flush();
Siarhei Vishniakouba0a8752021-09-14 14:43:25 -0700377}
378
379void UnwantedInteractionBlocker::notifyVibratorState(const NotifyVibratorStateArgs* args) {
Siarhei Vishniakoua91d8572022-05-17 05:03:42 -0700380 mQueuedListener.notifyVibratorState(args);
381 mQueuedListener.flush();
Siarhei Vishniakouba0a8752021-09-14 14:43:25 -0700382}
383void UnwantedInteractionBlocker::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
Siarhei Vishniakoua91d8572022-05-17 05:03:42 -0700384 { // acquire lock
385 std::scoped_lock lock(mLock);
386 auto it = mPalmRejectors.find(args->deviceId);
387 if (it != mPalmRejectors.end()) {
388 AndroidPalmFilterDeviceInfo info = it->second.getPalmFilterDeviceInfo();
389 // Re-create the object instead of resetting it
390 mPalmRejectors.erase(it);
391 mPalmRejectors.emplace(args->deviceId, info);
392 }
393 mQueuedListener.notifyDeviceReset(args);
394 mPreferStylusOverTouchBlocker.notifyDeviceReset(*args);
395 } // release lock
396 // Send events to the next stage without holding the lock
397 mQueuedListener.flush();
Siarhei Vishniakouba0a8752021-09-14 14:43:25 -0700398}
399
400void UnwantedInteractionBlocker::notifyPointerCaptureChanged(
401 const NotifyPointerCaptureChangedArgs* args) {
Siarhei Vishniakoua91d8572022-05-17 05:03:42 -0700402 mQueuedListener.notifyPointerCaptureChanged(args);
403 mQueuedListener.flush();
Siarhei Vishniakouba0a8752021-09-14 14:43:25 -0700404}
405
406void UnwantedInteractionBlocker::notifyInputDevicesChanged(
407 const std::vector<InputDeviceInfo>& inputDevices) {
Siarhei Vishniakoua91d8572022-05-17 05:03:42 -0700408 std::scoped_lock lock(mLock);
Siarhei Vishniakouba0a8752021-09-14 14:43:25 -0700409 if (!mEnablePalmRejection) {
410 // Palm rejection is disabled. Don't create any palm rejector objects.
411 return;
412 }
413
414 // Let's see which of the existing devices didn't change, so that we can keep them
415 // and prevent event stream disruption
416 std::set<int32_t /*deviceId*/> devicesToKeep;
417 for (const InputDeviceInfo& device : inputDevices) {
418 std::optional<AndroidPalmFilterDeviceInfo> info = createPalmFilterDeviceInfo(device);
419 if (!info) {
420 continue;
421 }
422
423 auto [it, emplaced] = mPalmRejectors.try_emplace(device.getId(), *info);
424 if (!emplaced && *info != it->second.getPalmFilterDeviceInfo()) {
425 // Re-create the PalmRejector because the device info has changed.
426 mPalmRejectors.erase(it);
427 mPalmRejectors.emplace(device.getId(), *info);
428 }
429 devicesToKeep.insert(device.getId());
430 }
431 // Delete all devices that we don't need to keep
432 std::erase_if(mPalmRejectors, [&devicesToKeep](const auto& item) {
433 auto const& [deviceId, _] = item;
434 return devicesToKeep.find(deviceId) == devicesToKeep.end();
435 });
Siarhei Vishniakou814ace32022-03-04 15:12:16 -0800436 mPreferStylusOverTouchBlocker.notifyInputDevicesChanged(inputDevices);
Siarhei Vishniakouba0a8752021-09-14 14:43:25 -0700437}
438
439void UnwantedInteractionBlocker::dump(std::string& dump) {
Siarhei Vishniakoua91d8572022-05-17 05:03:42 -0700440 std::scoped_lock lock(mLock);
Siarhei Vishniakouba0a8752021-09-14 14:43:25 -0700441 dump += "UnwantedInteractionBlocker:\n";
Siarhei Vishniakou814ace32022-03-04 15:12:16 -0800442 dump += " mPreferStylusOverTouchBlocker:\n";
Siarhei Vishniakoua91d8572022-05-17 05:03:42 -0700443 dump += addLinePrefix(mPreferStylusOverTouchBlocker.dump(), " ");
Siarhei Vishniakou15a5c5a2022-07-06 15:42:57 -0700444 dump += StringPrintf(" mEnablePalmRejection: %s\n",
445 std::to_string(mEnablePalmRejection).c_str());
Siarhei Vishniakouba0a8752021-09-14 14:43:25 -0700446 dump += StringPrintf(" isPalmRejectionEnabled (flag value): %s\n",
Siarhei Vishniakou15a5c5a2022-07-06 15:42:57 -0700447 std::to_string(isPalmRejectionEnabled()).c_str());
Siarhei Vishniakouba0a8752021-09-14 14:43:25 -0700448 dump += mPalmRejectors.empty() ? " mPalmRejectors: None\n" : " mPalmRejectors:\n";
449 for (const auto& [deviceId, palmRejector] : mPalmRejectors) {
450 dump += StringPrintf(" deviceId = %" PRId32 ":\n", deviceId);
Siarhei Vishniakoua91d8572022-05-17 05:03:42 -0700451 dump += addLinePrefix(palmRejector.dump(), " ");
Siarhei Vishniakouba0a8752021-09-14 14:43:25 -0700452 }
453}
454
Siarhei Vishniakoua91d8572022-05-17 05:03:42 -0700455void UnwantedInteractionBlocker::monitor() {
456 std::scoped_lock lock(mLock);
457}
Siarhei Vishniakouba0a8752021-09-14 14:43:25 -0700458
459UnwantedInteractionBlocker::~UnwantedInteractionBlocker() {}
460
461void SlotState::update(const NotifyMotionArgs& args) {
462 for (size_t i = 0; i < args.pointerCount; i++) {
463 const int32_t pointerId = args.pointerProperties[i].id;
464 const int32_t resolvedAction = resolveActionForPointer(i, args.action);
465 processPointerId(pointerId, resolvedAction);
466 }
467}
468
469size_t SlotState::findUnusedSlot() const {
470 size_t unusedSlot = 0;
471 // Since the collection is ordered, we can rely on the in-order traversal
472 for (const auto& [slot, trackingId] : mPointerIdsBySlot) {
473 if (unusedSlot != slot) {
474 break;
475 }
476 unusedSlot++;
477 }
478 return unusedSlot;
479}
480
481void SlotState::processPointerId(int pointerId, int32_t actionMasked) {
482 switch (MotionEvent::getActionMasked(actionMasked)) {
483 case AMOTION_EVENT_ACTION_DOWN:
484 case AMOTION_EVENT_ACTION_POINTER_DOWN:
485 case AMOTION_EVENT_ACTION_HOVER_ENTER: {
486 // New pointer going down
487 size_t newSlot = findUnusedSlot();
488 mPointerIdsBySlot[newSlot] = pointerId;
489 mSlotsByPointerId[pointerId] = newSlot;
490 return;
491 }
492 case AMOTION_EVENT_ACTION_MOVE:
493 case AMOTION_EVENT_ACTION_HOVER_MOVE: {
494 return;
495 }
496 case AMOTION_EVENT_ACTION_CANCEL:
497 case AMOTION_EVENT_ACTION_POINTER_UP:
498 case AMOTION_EVENT_ACTION_UP:
499 case AMOTION_EVENT_ACTION_HOVER_EXIT: {
500 auto it = mSlotsByPointerId.find(pointerId);
501 LOG_ALWAYS_FATAL_IF(it == mSlotsByPointerId.end());
502 size_t slot = it->second;
503 // Erase this pointer from both collections
504 mPointerIdsBySlot.erase(slot);
505 mSlotsByPointerId.erase(pointerId);
506 return;
507 }
508 }
509 LOG_ALWAYS_FATAL("Unhandled action : %s", MotionEvent::actionToString(actionMasked).c_str());
510 return;
511}
512
513std::optional<size_t> SlotState::getSlotForPointerId(int32_t pointerId) const {
514 auto it = mSlotsByPointerId.find(pointerId);
515 if (it == mSlotsByPointerId.end()) {
516 return std::nullopt;
517 }
518 return it->second;
519}
520
521std::string SlotState::dump() const {
522 std::string out = "mSlotsByPointerId:\n";
Siarhei Vishniakoua91d8572022-05-17 05:03:42 -0700523 out += addLinePrefix(dumpMap(mSlotsByPointerId), " ") + "\n";
Siarhei Vishniakouba0a8752021-09-14 14:43:25 -0700524 out += "mPointerIdsBySlot:\n";
Siarhei Vishniakoua91d8572022-05-17 05:03:42 -0700525 out += addLinePrefix(dumpMap(mPointerIdsBySlot), " ") + "\n";
Siarhei Vishniakouba0a8752021-09-14 14:43:25 -0700526 return out;
527}
528
Siarhei Vishniakou4aeef8c2022-06-13 11:19:34 -0700529class AndroidPalmRejectionModel : public ::ui::OneDeviceTrainNeuralStylusPalmDetectionFilterModel {
530public:
531 AndroidPalmRejectionModel()
532 : ::ui::OneDeviceTrainNeuralStylusPalmDetectionFilterModel(/*default version*/ "",
Siarhei Vishniakou127b45d2022-06-13 13:56:56 -0700533 std::vector<float>()) {
Siarhei Vishniakou5d673462022-07-08 10:47:57 -0700534 config_.resample_period = ::ui::kResamplePeriod;
Siarhei Vishniakou127b45d2022-06-13 13:56:56 -0700535 }
Siarhei Vishniakou4aeef8c2022-06-13 11:19:34 -0700536};
537
Siarhei Vishniakouba0a8752021-09-14 14:43:25 -0700538PalmRejector::PalmRejector(const AndroidPalmFilterDeviceInfo& info,
539 std::unique_ptr<::ui::PalmDetectionFilter> filter)
540 : mSharedPalmState(std::make_unique<::ui::SharedPalmDetectionFilterState>()),
541 mDeviceInfo(info),
542 mPalmDetectionFilter(std::move(filter)) {
543 if (mPalmDetectionFilter != nullptr) {
544 // This path is used for testing. Non-testing invocations should let this constructor
545 // create a real PalmDetectionFilter
546 return;
547 }
548 std::unique_ptr<::ui::NeuralStylusPalmDetectionFilterModel> model =
Siarhei Vishniakou4aeef8c2022-06-13 11:19:34 -0700549 std::make_unique<AndroidPalmRejectionModel>();
Siarhei Vishniakou15a5c5a2022-07-06 15:42:57 -0700550 mPalmDetectionFilter = std::make_unique<PalmFilterImplementation>(mDeviceInfo, std::move(model),
551 mSharedPalmState.get());
Siarhei Vishniakouba0a8752021-09-14 14:43:25 -0700552}
553
554std::vector<::ui::InProgressTouchEvdev> getTouches(const NotifyMotionArgs& args,
555 const AndroidPalmFilterDeviceInfo& deviceInfo,
556 const SlotState& oldSlotState,
557 const SlotState& newSlotState) {
558 std::vector<::ui::InProgressTouchEvdev> touches;
559
560 for (size_t i = 0; i < args.pointerCount; i++) {
561 const int32_t pointerId = args.pointerProperties[i].id;
562 touches.emplace_back(::ui::InProgressTouchEvdev());
563 touches.back().major = args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR);
564 touches.back().minor = args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR);
565 touches.back().tool_type = getLinuxToolType(args.pointerProperties[i].toolType);
566
567 // Whether there is new information for the touch.
568 touches.back().altered = true;
569
570 // Whether the touch was cancelled. Touch events should be ignored till a
571 // new touch is initiated.
572 touches.back().was_cancelled = false;
573
574 // Whether the touch is going to be canceled.
575 touches.back().cancelled = false;
576
577 // Whether the touch is delayed at first appearance. Will not be reported yet.
578 touches.back().delayed = false;
579
580 // Whether the touch was delayed before.
581 touches.back().was_delayed = false;
582
583 // Whether the touch is held until end or no longer held.
584 touches.back().held = false;
585
586 // Whether this touch was held before being sent.
587 touches.back().was_held = false;
588
589 const int32_t resolvedAction = resolveActionForPointer(i, args.action);
590 const bool isDown = resolvedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
591 resolvedAction == AMOTION_EVENT_ACTION_DOWN;
592 touches.back().was_touching = !isDown;
593
594 const bool isUpOrCancel = resolvedAction == AMOTION_EVENT_ACTION_CANCEL ||
595 resolvedAction == AMOTION_EVENT_ACTION_UP ||
596 resolvedAction == AMOTION_EVENT_ACTION_POINTER_UP;
597
598 touches.back().x = args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X);
599 touches.back().y = args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y);
600
601 std::optional<size_t> slot = newSlotState.getSlotForPointerId(pointerId);
602 if (!slot) {
603 slot = oldSlotState.getSlotForPointerId(pointerId);
604 }
605 LOG_ALWAYS_FATAL_IF(!slot, "Could not find slot for pointer %d", pointerId);
606 touches.back().slot = *slot;
607 touches.back().tracking_id = (!isUpOrCancel) ? pointerId : -1;
608 touches.back().touching = !isUpOrCancel;
609
610 // The fields 'radius_x' and 'radius_x' are not used for palm rejection
611 touches.back().pressure = args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE);
612 touches.back().tool_code = BTN_TOOL_FINGER;
613 // The field 'orientation' is not used for palm rejection
614 // The fields 'tilt_x' and 'tilt_y' are not used for palm rejection
615 touches.back().reported_tool_type = ::ui::EventPointerType::kTouch;
616 touches.back().stylus_button = false;
617 }
618 return touches;
619}
620
621std::vector<NotifyMotionArgs> PalmRejector::processMotion(const NotifyMotionArgs& args) {
622 if (mPalmDetectionFilter == nullptr) {
623 return {args};
624 }
625 const bool skipThisEvent = args.action == AMOTION_EVENT_ACTION_HOVER_ENTER ||
626 args.action == AMOTION_EVENT_ACTION_HOVER_MOVE ||
627 args.action == AMOTION_EVENT_ACTION_HOVER_EXIT ||
628 args.action == AMOTION_EVENT_ACTION_BUTTON_PRESS ||
629 args.action == AMOTION_EVENT_ACTION_BUTTON_RELEASE ||
630 args.action == AMOTION_EVENT_ACTION_SCROLL;
631 if (skipThisEvent) {
632 // Lets not process hover events, button events, or scroll for now.
633 return {args};
634 }
635 if (args.action == AMOTION_EVENT_ACTION_DOWN) {
636 mSuppressedPointerIds.clear();
637 }
638 std::bitset<::ui::kNumTouchEvdevSlots> slotsToHold;
639 std::bitset<::ui::kNumTouchEvdevSlots> slotsToSuppress;
640
641 // Store the slot state before we call getTouches and update it. This way, we can find
642 // the slots that have been removed due to the incoming event.
643 SlotState oldSlotState = mSlotState;
644 mSlotState.update(args);
645 std::vector<::ui::InProgressTouchEvdev> touches =
646 getTouches(args, mDeviceInfo, oldSlotState, mSlotState);
647 ::base::TimeTicks chromeTimestamp = toChromeTimestamp(args.eventTime);
648
Siarhei Vishniakoud5fe5182022-07-20 23:28:40 +0000649 if (DEBUG_MODEL) {
650 std::stringstream touchesStream;
651 for (const ::ui::InProgressTouchEvdev& touch : touches) {
652 touchesStream << touch.tracking_id << " : " << touch << "\n";
653 }
654 ALOGD("Filter: touches = %s", touchesStream.str().c_str());
655 }
Siarhei Vishniakouba0a8752021-09-14 14:43:25 -0700656 mPalmDetectionFilter->Filter(touches, chromeTimestamp, &slotsToHold, &slotsToSuppress);
657
Siarhei Vishniakoud5fe5182022-07-20 23:28:40 +0000658 ALOGD_IF(DEBUG_MODEL, "Response: slotsToHold = %s, slotsToSuppress = %s",
659 slotsToHold.to_string().c_str(), slotsToSuppress.to_string().c_str());
660
Siarhei Vishniakouba0a8752021-09-14 14:43:25 -0700661 // Now that we know which slots should be suppressed, let's convert those to pointer id's.
662 std::set<int32_t> oldSuppressedIds;
663 std::swap(oldSuppressedIds, mSuppressedPointerIds);
664 for (size_t i = 0; i < args.pointerCount; i++) {
665 const int32_t pointerId = args.pointerProperties[i].id;
666 std::optional<size_t> slot = oldSlotState.getSlotForPointerId(pointerId);
667 if (!slot) {
668 slot = mSlotState.getSlotForPointerId(pointerId);
669 LOG_ALWAYS_FATAL_IF(!slot, "Could not find slot for pointer id %" PRId32, pointerId);
670 }
671 if (slotsToSuppress.test(*slot)) {
672 mSuppressedPointerIds.insert(pointerId);
673 }
674 }
675
676 std::vector<NotifyMotionArgs> argsWithoutUnwantedPointers =
677 cancelSuppressedPointers(args, oldSuppressedIds, mSuppressedPointerIds);
678 for (const NotifyMotionArgs& checkArgs : argsWithoutUnwantedPointers) {
679 LOG_ALWAYS_FATAL_IF(checkArgs.action == ACTION_UNKNOWN, "%s", checkArgs.dump().c_str());
680 }
681
Siarhei Vishniakou15a5c5a2022-07-06 15:42:57 -0700682 // Only log if new pointers are getting rejected. That means mSuppressedPointerIds is not a
683 // subset of oldSuppressedIds.
684 if (!std::includes(oldSuppressedIds.begin(), oldSuppressedIds.end(),
685 mSuppressedPointerIds.begin(), mSuppressedPointerIds.end())) {
686 ALOGI("Palm detected, removing pointer ids %s after %" PRId64 "ms from %s",
687 dumpSet(mSuppressedPointerIds).c_str(), ns2ms(args.eventTime - args.downTime),
688 args.dump().c_str());
Siarhei Vishniakouba0a8752021-09-14 14:43:25 -0700689 }
690
691 return argsWithoutUnwantedPointers;
692}
693
694const AndroidPalmFilterDeviceInfo& PalmRejector::getPalmFilterDeviceInfo() {
695 return mDeviceInfo;
696}
697
698std::string PalmRejector::dump() const {
699 std::string out;
700 out += "mDeviceInfo:\n";
Siarhei Vishniakou15a5c5a2022-07-06 15:42:57 -0700701 std::stringstream deviceInfo;
702 deviceInfo << mDeviceInfo << ", touch_major_res=" << mDeviceInfo.touch_major_res
703 << ", touch_minor_res=" << mDeviceInfo.touch_minor_res << "\n";
704 out += addLinePrefix(deviceInfo.str(), " ");
Siarhei Vishniakouba0a8752021-09-14 14:43:25 -0700705 out += "mSlotState:\n";
Siarhei Vishniakoua91d8572022-05-17 05:03:42 -0700706 out += addLinePrefix(mSlotState.dump(), " ");
Siarhei Vishniakouba0a8752021-09-14 14:43:25 -0700707 out += "mSuppressedPointerIds: ";
708 out += dumpSet(mSuppressedPointerIds) + "\n";
Siarhei Vishniakou15a5c5a2022-07-06 15:42:57 -0700709 std::stringstream state;
710 state << *mSharedPalmState;
711 out += "mSharedPalmState: " + state.str() + "\n";
712 std::stringstream filter;
713 filter << static_cast<const PalmFilterImplementation&>(*mPalmDetectionFilter);
714 out += "mPalmDetectionFilter:\n";
715 out += addLinePrefix(filter.str(), " ") + "\n";
Siarhei Vishniakouba0a8752021-09-14 14:43:25 -0700716 return out;
717}
718
719} // namespace android