blob: d60bcd8fbb7e0073708cf99ed8c3c03d49700477 [file] [log] [blame]
Michael Wrightd02c5b62014-02-10 15:10:22 -08001/*
2 * Copyright (C) 2010 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 "InputDispatcher"
18#define ATRACE_TAG ATRACE_TAG_INPUT
19
John Recke0710582019-09-26 13:46:12 -070020#define LOG_NDEBUG 1
Michael Wrightd02c5b62014-02-10 15:10:22 -080021
22// Log detailed debug messages about each inbound event notification to the dispatcher.
23#define DEBUG_INBOUND_EVENT_DETAILS 0
24
25// Log detailed debug messages about each outbound event processed by the dispatcher.
26#define DEBUG_OUTBOUND_EVENT_DETAILS 0
27
28// Log debug messages about the dispatch cycle.
29#define DEBUG_DISPATCH_CYCLE 0
30
Garfield Tan15601662020-09-22 15:32:38 -070031// Log debug messages about channel creation
32#define DEBUG_CHANNEL_CREATION 0
Michael Wrightd02c5b62014-02-10 15:10:22 -080033
34// Log debug messages about input event injection.
35#define DEBUG_INJECTION 0
36
37// Log debug messages about input focus tracking.
Siarhei Vishniakou86587282019-09-09 18:20:15 +010038static constexpr bool DEBUG_FOCUS = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -080039
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +000040// Log debug messages about touch occlusion
41// STOPSHIP(b/169067926): Set to false
42static constexpr bool DEBUG_TOUCH_OCCLUSION = true;
43
Michael Wrightd02c5b62014-02-10 15:10:22 -080044// Log debug messages about the app switch latency optimization.
45#define DEBUG_APP_SWITCH 0
46
47// Log debug messages about hover events.
48#define DEBUG_HOVER 0
49
Michael Wright2b3c3302018-03-02 17:19:13 +000050#include <android-base/chrono_utils.h>
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080051#include <android-base/stringprintf.h>
Siarhei Vishniakou70622952020-07-30 11:17:23 -050052#include <android/os/IInputConstants.h>
Robert Carr4e670e52018-08-15 13:26:12 -070053#include <binder/Binder.h>
Siarhei Vishniakou2508b872020-12-03 16:33:53 -100054#include <binder/IServiceManager.h>
55#include <com/android/internal/compat/IPlatformCompatNative.h>
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -080056#include <input/InputDevice.h>
Michael Wright44753b12020-07-08 13:48:11 +010057#include <input/InputWindow.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070058#include <log/log.h>
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +000059#include <log/log_event_list.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070060#include <powermanager/PowerManager.h>
Michael Wright44753b12020-07-08 13:48:11 +010061#include <statslog.h>
62#include <unistd.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070063#include <utils/Trace.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080064
Michael Wright44753b12020-07-08 13:48:11 +010065#include <cerrno>
66#include <cinttypes>
67#include <climits>
68#include <cstddef>
69#include <ctime>
70#include <queue>
71#include <sstream>
72
73#include "Connection.h"
Chris Yef59a2f42020-10-16 12:55:26 -070074#include "InputDispatcher.h"
Michael Wright44753b12020-07-08 13:48:11 +010075
Michael Wrightd02c5b62014-02-10 15:10:22 -080076#define INDENT " "
77#define INDENT2 " "
78#define INDENT3 " "
79#define INDENT4 " "
80
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080081using android::base::StringPrintf;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -080082using android::os::BlockUntrustedTouchesMode;
Siarhei Vishniakou2508b872020-12-03 16:33:53 -100083using android::os::IInputConstants;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -080084using android::os::InputEventInjectionResult;
85using android::os::InputEventInjectionSync;
Siarhei Vishniakou2508b872020-12-03 16:33:53 -100086using com::android::internal::compat::IPlatformCompatNative;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080087
Garfield Tane84e6f92019-08-29 17:28:41 -070088namespace android::inputdispatcher {
Michael Wrightd02c5b62014-02-10 15:10:22 -080089
90// Default input dispatching timeout if there is no focused application or paused window
91// from which to determine an appropriate dispatching timeout.
Siarhei Vishniakou70622952020-07-30 11:17:23 -050092constexpr std::chrono::duration DEFAULT_INPUT_DISPATCHING_TIMEOUT =
93 std::chrono::milliseconds(android::os::IInputConstants::DEFAULT_DISPATCHING_TIMEOUT_MILLIS);
Michael Wrightd02c5b62014-02-10 15:10:22 -080094
95// Amount of time to allow for all pending events to be processed when an app switch
96// key is on the way. This is used to preempt input dispatch and drop input events
97// when an application takes too long to respond and the user has pressed an app switch key.
Michael Wright2b3c3302018-03-02 17:19:13 +000098constexpr nsecs_t APP_SWITCH_TIMEOUT = 500 * 1000000LL; // 0.5sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080099
100// Amount of time to allow for an event to be dispatched (measured since its eventTime)
101// before considering it stale and dropping it.
Michael Wright2b3c3302018-03-02 17:19:13 +0000102constexpr nsecs_t STALE_EVENT_TIMEOUT = 10000 * 1000000LL; // 10sec
Michael Wrightd02c5b62014-02-10 15:10:22 -0800103
Michael Wrightd02c5b62014-02-10 15:10:22 -0800104// Log a warning when an event takes longer than this to process, even if an ANR does not occur.
Michael Wright2b3c3302018-03-02 17:19:13 +0000105constexpr nsecs_t SLOW_EVENT_PROCESSING_WARNING_TIMEOUT = 2000 * 1000000LL; // 2sec
106
107// Log a warning when an interception call takes longer than this to process.
108constexpr std::chrono::milliseconds SLOW_INTERCEPTION_THRESHOLD = 50ms;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800109
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700110// Additional key latency in case a connection is still processing some motion events.
111// This will help with the case when a user touched a button that opens a new window,
112// and gives us the chance to dispatch the key to this new window.
113constexpr std::chrono::nanoseconds KEY_WAITING_FOR_EVENTS_TIMEOUT = 500ms;
114
Michael Wrightd02c5b62014-02-10 15:10:22 -0800115// Number of recent events to keep for debugging purposes.
Michael Wright2b3c3302018-03-02 17:19:13 +0000116constexpr size_t RECENT_QUEUE_MAX_SIZE = 10;
117
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000118// Event log tags. See EventLogTags.logtags for reference
119constexpr int LOGTAG_INPUT_INTERACTION = 62000;
120constexpr int LOGTAG_INPUT_FOCUS = 62001;
121
Michael Wrightd02c5b62014-02-10 15:10:22 -0800122static inline nsecs_t now() {
123 return systemTime(SYSTEM_TIME_MONOTONIC);
124}
125
126static inline const char* toString(bool value) {
127 return value ? "true" : "false";
128}
129
130static inline int32_t getMotionEventActionPointerIndex(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700131 return (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >>
132 AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800133}
134
135static bool isValidKeyAction(int32_t action) {
136 switch (action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700137 case AKEY_EVENT_ACTION_DOWN:
138 case AKEY_EVENT_ACTION_UP:
139 return true;
140 default:
141 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800142 }
143}
144
145static bool validateKeyEvent(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700146 if (!isValidKeyAction(action)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800147 ALOGE("Key event has invalid action code 0x%x", action);
148 return false;
149 }
150 return true;
151}
152
Michael Wright7b159c92015-05-14 14:48:03 +0100153static bool isValidMotionAction(int32_t action, int32_t actionButton, int32_t pointerCount) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800154 switch (action & AMOTION_EVENT_ACTION_MASK) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700155 case AMOTION_EVENT_ACTION_DOWN:
156 case AMOTION_EVENT_ACTION_UP:
157 case AMOTION_EVENT_ACTION_CANCEL:
158 case AMOTION_EVENT_ACTION_MOVE:
159 case AMOTION_EVENT_ACTION_OUTSIDE:
160 case AMOTION_EVENT_ACTION_HOVER_ENTER:
161 case AMOTION_EVENT_ACTION_HOVER_MOVE:
162 case AMOTION_EVENT_ACTION_HOVER_EXIT:
163 case AMOTION_EVENT_ACTION_SCROLL:
164 return true;
165 case AMOTION_EVENT_ACTION_POINTER_DOWN:
166 case AMOTION_EVENT_ACTION_POINTER_UP: {
167 int32_t index = getMotionEventActionPointerIndex(action);
168 return index >= 0 && index < pointerCount;
169 }
170 case AMOTION_EVENT_ACTION_BUTTON_PRESS:
171 case AMOTION_EVENT_ACTION_BUTTON_RELEASE:
172 return actionButton != 0;
173 default:
174 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800175 }
176}
177
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500178static int64_t millis(std::chrono::nanoseconds t) {
179 return std::chrono::duration_cast<std::chrono::milliseconds>(t).count();
180}
181
Michael Wright7b159c92015-05-14 14:48:03 +0100182static bool validateMotionEvent(int32_t action, int32_t actionButton, size_t pointerCount,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700183 const PointerProperties* pointerProperties) {
184 if (!isValidMotionAction(action, actionButton, pointerCount)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800185 ALOGE("Motion event has invalid action code 0x%x", action);
186 return false;
187 }
188 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Narayan Kamath37764c72014-03-27 14:21:09 +0000189 ALOGE("Motion event has invalid pointer count %zu; value must be between 1 and %d.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700190 pointerCount, MAX_POINTERS);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800191 return false;
192 }
193 BitSet32 pointerIdBits;
194 for (size_t i = 0; i < pointerCount; i++) {
195 int32_t id = pointerProperties[i].id;
196 if (id < 0 || id > MAX_POINTER_ID) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700197 ALOGE("Motion event has invalid pointer id %d; value must be between 0 and %d", id,
198 MAX_POINTER_ID);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800199 return false;
200 }
201 if (pointerIdBits.hasBit(id)) {
202 ALOGE("Motion event has duplicate pointer id %d", id);
203 return false;
204 }
205 pointerIdBits.markBit(id);
206 }
207 return true;
208}
209
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000210static std::string dumpRegion(const Region& region) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800211 if (region.isEmpty()) {
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000212 return "<empty>";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800213 }
214
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000215 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800216 bool first = true;
217 Region::const_iterator cur = region.begin();
218 Region::const_iterator const tail = region.end();
219 while (cur != tail) {
220 if (first) {
221 first = false;
222 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800223 dump += "|";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800224 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800225 dump += StringPrintf("[%d,%d][%d,%d]", cur->left, cur->top, cur->right, cur->bottom);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800226 cur++;
227 }
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000228 return dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800229}
230
Siarhei Vishniakou14411c92020-09-18 21:15:05 -0500231static std::string dumpQueue(const std::deque<DispatchEntry*>& queue, nsecs_t currentTime) {
232 constexpr size_t maxEntries = 50; // max events to print
233 constexpr size_t skipBegin = maxEntries / 2;
234 const size_t skipEnd = queue.size() - maxEntries / 2;
235 // skip from maxEntries / 2 ... size() - maxEntries/2
236 // only print from 0 .. skipBegin and then from skipEnd .. size()
237
238 std::string dump;
239 for (size_t i = 0; i < queue.size(); i++) {
240 const DispatchEntry& entry = *queue[i];
241 if (i >= skipBegin && i < skipEnd) {
242 dump += StringPrintf(INDENT4 "<skipped %zu entries>\n", skipEnd - skipBegin);
243 i = skipEnd - 1; // it will be incremented to "skipEnd" by 'continue'
244 continue;
245 }
246 dump.append(INDENT4);
247 dump += entry.eventEntry->getDescription();
248 dump += StringPrintf(", seq=%" PRIu32
249 ", targetFlags=0x%08x, resolvedAction=%d, age=%" PRId64 "ms",
250 entry.seq, entry.targetFlags, entry.resolvedAction,
251 ns2ms(currentTime - entry.eventEntry->eventTime));
252 if (entry.deliveryTime != 0) {
253 // This entry was delivered, so add information on how long we've been waiting
254 dump += StringPrintf(", wait=%" PRId64 "ms", ns2ms(currentTime - entry.deliveryTime));
255 }
256 dump.append("\n");
257 }
258 return dump;
259}
260
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700261/**
262 * Find the entry in std::unordered_map by key, and return it.
263 * If the entry is not found, return a default constructed entry.
264 *
265 * Useful when the entries are vectors, since an empty vector will be returned
266 * if the entry is not found.
267 * Also useful when the entries are sp<>. If an entry is not found, nullptr is returned.
268 */
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700269template <typename K, typename V>
270static V getValueByKey(const std::unordered_map<K, V>& map, K key) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700271 auto it = map.find(key);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700272 return it != map.end() ? it->second : V{};
Tiger Huang721e26f2018-07-24 22:26:19 +0800273}
274
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700275/**
276 * Find the entry in std::unordered_map by value, and remove it.
277 * If more than one entry has the same value, then all matching
278 * key-value pairs will be removed.
279 *
280 * Return true if at least one value has been removed.
281 */
282template <typename K, typename V>
283static bool removeByValue(std::unordered_map<K, V>& map, const V& value) {
284 bool removed = false;
285 for (auto it = map.begin(); it != map.end();) {
286 if (it->second == value) {
287 it = map.erase(it);
288 removed = true;
289 } else {
290 it++;
291 }
292 }
293 return removed;
294}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800295
chaviwaf87b3e2019-10-01 16:59:28 -0700296static bool haveSameToken(const sp<InputWindowHandle>& first, const sp<InputWindowHandle>& second) {
297 if (first == second) {
298 return true;
299 }
300
301 if (first == nullptr || second == nullptr) {
302 return false;
303 }
304
305 return first->getToken() == second->getToken();
306}
307
Bernardo Rufino1ff9d592021-01-18 16:58:57 +0000308static bool haveSameApplicationToken(const InputWindowInfo* first, const InputWindowInfo* second) {
309 if (first == nullptr || second == nullptr) {
310 return false;
311 }
312 return first->applicationInfo.token != nullptr &&
313 first->applicationInfo.token == second->applicationInfo.token;
314}
315
Siarhei Vishniakouadfd4fa2019-12-20 11:02:58 -0800316static bool isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
317 return currentTime - entry.eventTime >= STALE_EVENT_TIMEOUT;
318}
319
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000320static std::unique_ptr<DispatchEntry> createDispatchEntry(const InputTarget& inputTarget,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700321 std::shared_ptr<EventEntry> eventEntry,
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000322 int32_t inputTargetFlags) {
yunho.shinf4a80b82020-11-16 21:13:57 +0900323 if (eventEntry->type == EventEntry::Type::MOTION) {
324 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
325 if (motionEntry.source & AINPUT_SOURCE_CLASS_JOYSTICK) {
326 const ui::Transform identityTransform;
327 // Use identity transform for joystick events events because they don't depend on
328 // the window info
329 return std::make_unique<DispatchEntry>(eventEntry, inputTargetFlags, identityTransform,
330 1.0f /*globalScaleFactor*/);
331 }
332 }
333
chaviw1ff3d1e2020-07-01 15:53:47 -0700334 if (inputTarget.useDefaultPointerTransform()) {
335 const ui::Transform& transform = inputTarget.getDefaultPointerTransform();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700336 return std::make_unique<DispatchEntry>(eventEntry, inputTargetFlags, transform,
chaviw1ff3d1e2020-07-01 15:53:47 -0700337 inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000338 }
339
340 ALOG_ASSERT(eventEntry->type == EventEntry::Type::MOTION);
341 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
342
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700343 std::vector<PointerCoords> pointerCoords;
344 pointerCoords.resize(motionEntry.pointerCount);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000345
346 // Use the first pointer information to normalize all other pointers. This could be any pointer
347 // as long as all other pointers are normalized to the same value and the final DispatchEntry
chaviw1ff3d1e2020-07-01 15:53:47 -0700348 // uses the transform for the normalized pointer.
349 const ui::Transform& firstPointerTransform =
350 inputTarget.pointerTransforms[inputTarget.pointerIds.firstMarkedBit()];
351 ui::Transform inverseFirstTransform = firstPointerTransform.inverse();
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000352
353 // Iterate through all pointers in the event to normalize against the first.
354 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.pointerCount; pointerIndex++) {
355 const PointerProperties& pointerProperties = motionEntry.pointerProperties[pointerIndex];
356 uint32_t pointerId = uint32_t(pointerProperties.id);
chaviw1ff3d1e2020-07-01 15:53:47 -0700357 const ui::Transform& currTransform = inputTarget.pointerTransforms[pointerId];
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000358
359 pointerCoords[pointerIndex].copyFrom(motionEntry.pointerCoords[pointerIndex]);
chaviw1ff3d1e2020-07-01 15:53:47 -0700360 // First, apply the current pointer's transform to update the coordinates into
361 // window space.
362 pointerCoords[pointerIndex].transform(currTransform);
363 // Next, apply the inverse transform of the normalized coordinates so the
364 // current coordinates are transformed into the normalized coordinate space.
365 pointerCoords[pointerIndex].transform(inverseFirstTransform);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000366 }
367
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700368 std::unique_ptr<MotionEntry> combinedMotionEntry =
369 std::make_unique<MotionEntry>(motionEntry.id, motionEntry.eventTime,
370 motionEntry.deviceId, motionEntry.source,
371 motionEntry.displayId, motionEntry.policyFlags,
372 motionEntry.action, motionEntry.actionButton,
373 motionEntry.flags, motionEntry.metaState,
374 motionEntry.buttonState, motionEntry.classification,
375 motionEntry.edgeFlags, motionEntry.xPrecision,
376 motionEntry.yPrecision, motionEntry.xCursorPosition,
377 motionEntry.yCursorPosition, motionEntry.downTime,
378 motionEntry.pointerCount, motionEntry.pointerProperties,
379 pointerCoords.data(), 0 /* xOffset */, 0 /* yOffset */);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000380
381 if (motionEntry.injectionState) {
382 combinedMotionEntry->injectionState = motionEntry.injectionState;
383 combinedMotionEntry->injectionState->refCount += 1;
384 }
385
386 std::unique_ptr<DispatchEntry> dispatchEntry =
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700387 std::make_unique<DispatchEntry>(std::move(combinedMotionEntry), inputTargetFlags,
388 firstPointerTransform, inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000389 return dispatchEntry;
390}
391
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -0700392static void addGestureMonitors(const std::vector<Monitor>& monitors,
393 std::vector<TouchedMonitor>& outTouchedMonitors, float xOffset = 0,
394 float yOffset = 0) {
395 if (monitors.empty()) {
396 return;
397 }
398 outTouchedMonitors.reserve(monitors.size() + outTouchedMonitors.size());
399 for (const Monitor& monitor : monitors) {
400 outTouchedMonitors.emplace_back(monitor, xOffset, yOffset);
401 }
402}
403
Garfield Tan15601662020-09-22 15:32:38 -0700404static status_t openInputChannelPair(const std::string& name,
405 std::shared_ptr<InputChannel>& serverChannel,
406 std::unique_ptr<InputChannel>& clientChannel) {
407 std::unique_ptr<InputChannel> uniqueServerChannel;
408 status_t result = InputChannel::openInputChannelPair(name, uniqueServerChannel, clientChannel);
409
410 serverChannel = std::move(uniqueServerChannel);
411 return result;
412}
413
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500414template <typename T>
415static bool sharedPointersEqual(const std::shared_ptr<T>& lhs, const std::shared_ptr<T>& rhs) {
416 if (lhs == nullptr && rhs == nullptr) {
417 return true;
418 }
419 if (lhs == nullptr || rhs == nullptr) {
420 return false;
421 }
422 return *lhs == *rhs;
423}
424
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000425static sp<IPlatformCompatNative> getCompatService() {
426 sp<IBinder> service(defaultServiceManager()->getService(String16("platform_compat_native")));
427 if (service == nullptr) {
428 ALOGE("Failed to link to compat service");
429 return nullptr;
430 }
431 return interface_cast<IPlatformCompatNative>(service);
432}
433
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +0000434static KeyEvent createKeyEvent(const KeyEntry& entry) {
435 KeyEvent event;
436 event.initialize(entry.id, entry.deviceId, entry.source, entry.displayId, INVALID_HMAC,
437 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
438 entry.repeatCount, entry.downTime, entry.eventTime);
439 return event;
440}
441
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000442static std::optional<int32_t> findMonitorPidByToken(
443 const std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay,
444 const sp<IBinder>& token) {
445 for (const auto& it : monitorsByDisplay) {
446 const std::vector<Monitor>& monitors = it.second;
447 for (const Monitor& monitor : monitors) {
448 if (monitor.inputChannel->getConnectionToken() == token) {
449 return monitor.pid;
450 }
451 }
452 }
453 return std::nullopt;
454}
455
Michael Wrightd02c5b62014-02-10 15:10:22 -0800456// --- InputDispatcher ---
457
Garfield Tan00f511d2019-06-12 16:55:40 -0700458InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy)
459 : mPolicy(policy),
460 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700461 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800462 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Garfield Tan00f511d2019-06-12 16:55:40 -0700463 mAppSwitchSawKeyDown(false),
464 mAppSwitchDueTime(LONG_LONG_MAX),
465 mNextUnblockedEvent(nullptr),
466 mDispatchEnabled(false),
467 mDispatchFrozen(false),
468 mInputFilterEnabled(false),
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -0800469 // mInTouchMode will be initialized by the WindowManager to the default device config.
470 // To avoid leaking stack in case that call never comes, and for tests,
471 // initialize it here anyways.
472 mInTouchMode(true),
Bernardo Rufinoea97d182020-08-19 14:43:14 +0100473 mMaximumObscuringOpacityForTouch(1.0f),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000474 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
Prabir Pradhan99987712020-11-10 18:43:05 -0800475 mFocusedWindowRequestedPointerCapture(false),
476 mWindowTokenWithPointerCapture(nullptr),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000477 mCompatService(getCompatService()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800478 mLooper = new Looper(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800479 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800480
Yi Kong9b14ac62018-07-17 13:48:38 -0700481 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800482
483 policy->getDispatcherConfiguration(&mConfig);
484}
485
486InputDispatcher::~InputDispatcher() {
487 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800488 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800489
490 resetKeyRepeatLocked();
491 releasePendingEventLocked();
492 drainInboundQueueLocked();
493 }
494
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700495 while (!mConnectionsByFd.empty()) {
496 sp<Connection> connection = mConnectionsByFd.begin()->second;
Garfield Tan15601662020-09-22 15:32:38 -0700497 removeInputChannel(connection->inputChannel->getConnectionToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800498 }
499}
500
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700501status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700502 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700503 return ALREADY_EXISTS;
504 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700505 mThread = std::make_unique<InputThread>(
506 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
507 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700508}
509
510status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700511 if (mThread && mThread->isCallingThread()) {
512 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700513 return INVALID_OPERATION;
514 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700515 mThread.reset();
516 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700517}
518
Michael Wrightd02c5b62014-02-10 15:10:22 -0800519void InputDispatcher::dispatchOnce() {
520 nsecs_t nextWakeupTime = LONG_LONG_MAX;
521 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800522 std::scoped_lock _l(mLock);
523 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800524
525 // Run a dispatch loop if there are no pending commands.
526 // The dispatch loop might enqueue commands to run afterwards.
527 if (!haveCommandsLocked()) {
528 dispatchOnceInnerLocked(&nextWakeupTime);
529 }
530
531 // Run all pending commands if there are any.
532 // If any commands were run then force the next poll to wake up immediately.
533 if (runCommandsLockedInterruptible()) {
534 nextWakeupTime = LONG_LONG_MIN;
535 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800536
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700537 // If we are still waiting for ack on some events,
538 // we might have to wake up earlier to check if an app is anr'ing.
539 const nsecs_t nextAnrCheck = processAnrsLocked();
540 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
541
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800542 // We are about to enter an infinitely long sleep, because we have no commands or
543 // pending or queued events
544 if (nextWakeupTime == LONG_LONG_MAX) {
545 mDispatcherEnteredIdle.notify_all();
546 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800547 } // release lock
548
549 // Wait for callback or timeout or wake. (make sure we round up, not down)
550 nsecs_t currentTime = now();
551 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
552 mLooper->pollOnce(timeoutMillis);
553}
554
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700555/**
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500556 * Raise ANR if there is no focused window.
557 * Before the ANR is raised, do a final state check:
558 * 1. The currently focused application must be the same one we are waiting for.
559 * 2. Ensure we still don't have a focused window.
560 */
561void InputDispatcher::processNoFocusedWindowAnrLocked() {
562 // Check if the application that we are waiting for is still focused.
563 std::shared_ptr<InputApplicationHandle> focusedApplication =
564 getValueByKey(mFocusedApplicationHandlesByDisplay, mAwaitedApplicationDisplayId);
565 if (focusedApplication == nullptr ||
566 focusedApplication->getApplicationToken() !=
567 mAwaitedFocusedApplication->getApplicationToken()) {
568 // Unexpected because we should have reset the ANR timer when focused application changed
569 ALOGE("Waited for a focused window, but focused application has already changed to %s",
570 focusedApplication->getName().c_str());
571 return; // The focused application has changed.
572 }
573
574 const sp<InputWindowHandle>& focusedWindowHandle =
575 getFocusedWindowHandleLocked(mAwaitedApplicationDisplayId);
576 if (focusedWindowHandle != nullptr) {
577 return; // We now have a focused window. No need for ANR.
578 }
579 onAnrLocked(mAwaitedFocusedApplication);
580}
581
582/**
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700583 * Check if any of the connections' wait queues have events that are too old.
584 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
585 * Return the time at which we should wake up next.
586 */
587nsecs_t InputDispatcher::processAnrsLocked() {
588 const nsecs_t currentTime = now();
589 nsecs_t nextAnrCheck = LONG_LONG_MAX;
590 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
591 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
592 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500593 processNoFocusedWindowAnrLocked();
Chris Yea209fde2020-07-22 13:54:51 -0700594 mAwaitedFocusedApplication.reset();
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500595 mNoFocusedWindowTimeoutTime = std::nullopt;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700596 return LONG_LONG_MIN;
597 } else {
Siarhei Vishniakou38a6d272020-10-20 20:29:33 -0500598 // Keep waiting. We will drop the event when mNoFocusedWindowTimeoutTime comes.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700599 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
600 }
601 }
602
603 // Check if any connection ANRs are due
604 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
605 if (currentTime < nextAnrCheck) { // most likely scenario
606 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
607 }
608
609 // If we reached here, we have an unresponsive connection.
610 sp<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
611 if (connection == nullptr) {
612 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
613 return nextAnrCheck;
614 }
615 connection->responsive = false;
616 // Stop waking up for this unresponsive connection
617 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000618 onAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700619 return LONG_LONG_MIN;
620}
621
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500622std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(const sp<IBinder>& token) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700623 sp<InputWindowHandle> window = getWindowHandleLocked(token);
624 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500625 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700626 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500627 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700628}
629
Michael Wrightd02c5b62014-02-10 15:10:22 -0800630void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
631 nsecs_t currentTime = now();
632
Jeff Browndc5992e2014-04-11 01:27:26 -0700633 // Reset the key repeat timer whenever normal dispatch is suspended while the
634 // device is in a non-interactive state. This is to ensure that we abort a key
635 // repeat if the device is just coming out of sleep.
636 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800637 resetKeyRepeatLocked();
638 }
639
640 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
641 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100642 if (DEBUG_FOCUS) {
643 ALOGD("Dispatch frozen. Waiting some more.");
644 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800645 return;
646 }
647
648 // Optimize latency of app switches.
649 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
650 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
651 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
652 if (mAppSwitchDueTime < *nextWakeupTime) {
653 *nextWakeupTime = mAppSwitchDueTime;
654 }
655
656 // Ready to start a new event.
657 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700658 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700659 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800660 if (isAppSwitchDue) {
661 // The inbound queue is empty so the app switch key we were waiting
662 // for will never arrive. Stop waiting for it.
663 resetPendingAppSwitchLocked(false);
664 isAppSwitchDue = false;
665 }
666
667 // Synthesize a key repeat if appropriate.
668 if (mKeyRepeatState.lastKeyEntry) {
669 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
670 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
671 } else {
672 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
673 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
674 }
675 }
676 }
677
678 // Nothing to do if there is no pending event.
679 if (!mPendingEvent) {
680 return;
681 }
682 } else {
683 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700684 mPendingEvent = mInboundQueue.front();
685 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800686 traceInboundQueueLengthLocked();
687 }
688
689 // Poke user activity for this event.
690 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700691 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800692 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800693 }
694
695 // Now we have an event to dispatch.
696 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700697 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800698 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700699 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800700 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700701 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800702 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700703 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800704 }
705
706 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700707 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800708 }
709
710 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700711 case EventEntry::Type::CONFIGURATION_CHANGED: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700712 const ConfigurationChangedEntry& typedEntry =
713 static_cast<const ConfigurationChangedEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700714 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700715 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700716 break;
717 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800718
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700719 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700720 const DeviceResetEntry& typedEntry =
721 static_cast<const DeviceResetEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700722 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700723 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700724 break;
725 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800726
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100727 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700728 std::shared_ptr<FocusEntry> typedEntry =
729 std::static_pointer_cast<FocusEntry>(mPendingEvent);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100730 dispatchFocusLocked(currentTime, typedEntry);
731 done = true;
732 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
733 break;
734 }
735
Prabir Pradhan99987712020-11-10 18:43:05 -0800736 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
737 const auto typedEntry =
738 std::static_pointer_cast<PointerCaptureChangedEntry>(mPendingEvent);
739 dispatchPointerCaptureChangedLocked(currentTime, typedEntry, dropReason);
740 done = true;
741 break;
742 }
743
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700744 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700745 std::shared_ptr<KeyEntry> keyEntry = std::static_pointer_cast<KeyEntry>(mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700746 if (isAppSwitchDue) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700747 if (isAppSwitchKeyEvent(*keyEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700748 resetPendingAppSwitchLocked(true);
749 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700750 } else if (dropReason == DropReason::NOT_DROPPED) {
751 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700752 }
753 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700754 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *keyEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700755 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700756 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700757 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
758 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700759 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700760 done = dispatchKeyLocked(currentTime, keyEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700761 break;
762 }
763
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700764 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700765 std::shared_ptr<MotionEntry> motionEntry =
766 std::static_pointer_cast<MotionEntry>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700767 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
768 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800769 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700770 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *motionEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700771 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700772 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700773 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
774 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700775 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700776 done = dispatchMotionLocked(currentTime, motionEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700777 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800778 }
Chris Yef59a2f42020-10-16 12:55:26 -0700779
780 case EventEntry::Type::SENSOR: {
781 std::shared_ptr<SensorEntry> sensorEntry =
782 std::static_pointer_cast<SensorEntry>(mPendingEvent);
783 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
784 dropReason = DropReason::APP_SWITCH;
785 }
786 // Sensor timestamps use SYSTEM_TIME_BOOTTIME time base, so we can't use
787 // 'currentTime' here, get SYSTEM_TIME_BOOTTIME instead.
788 nsecs_t bootTime = systemTime(SYSTEM_TIME_BOOTTIME);
789 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(bootTime, *sensorEntry)) {
790 dropReason = DropReason::STALE;
791 }
792 dispatchSensorLocked(currentTime, sensorEntry, &dropReason, nextWakeupTime);
793 done = true;
794 break;
795 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800796 }
797
798 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700799 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700800 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800801 }
Michael Wright3a981722015-06-10 15:26:13 +0100802 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800803
804 releasePendingEventLocked();
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700805 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -0800806 }
807}
808
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700809/**
810 * Return true if the events preceding this incoming motion event should be dropped
811 * Return false otherwise (the default behaviour)
812 */
813bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700814 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700815 (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700816
817 // Optimize case where the current application is unresponsive and the user
818 // decides to touch a window in a different application.
819 // If the application takes too long to catch up then we drop all events preceding
820 // the touch into the other window.
821 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700822 int32_t displayId = motionEntry.displayId;
823 int32_t x = static_cast<int32_t>(
824 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
825 int32_t y = static_cast<int32_t>(
826 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
827 sp<InputWindowHandle> touchedWindowHandle =
828 findTouchedWindowAtLocked(displayId, x, y, nullptr);
829 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700830 touchedWindowHandle->getApplicationToken() !=
831 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700832 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700833 ALOGI("Pruning input queue because user touched a different application while waiting "
834 "for %s",
835 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700836 return true;
837 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700838
839 // Alternatively, maybe there's a gesture monitor that could handle this event
840 std::vector<TouchedMonitor> gestureMonitors =
841 findTouchedGestureMonitorsLocked(displayId, {});
842 for (TouchedMonitor& gestureMonitor : gestureMonitors) {
843 sp<Connection> connection =
844 getConnectionLocked(gestureMonitor.monitor.inputChannel->getConnectionToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +0000845 if (connection != nullptr && connection->responsive) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700846 // This monitor could take more input. Drop all events preceding this
847 // event, so that gesture monitor could get a chance to receive the stream
848 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
849 "responsive gesture monitor that may handle the event",
850 mAwaitedFocusedApplication->getName().c_str());
851 return true;
852 }
853 }
854 }
855
856 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
857 // yet been processed by some connections, the dispatcher will wait for these motion
858 // events to be processed before dispatching the key event. This is because these motion events
859 // may cause a new window to be launched, which the user might expect to receive focus.
860 // To prevent waiting forever for such events, just send the key to the currently focused window
861 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
862 ALOGD("Received a new pointer down event, stop waiting for events to process and "
863 "just send the pending key event to the focused window.");
864 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700865 }
866 return false;
867}
868
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700869bool InputDispatcher::enqueueInboundEventLocked(std::unique_ptr<EventEntry> newEntry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700870 bool needWake = mInboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700871 mInboundQueue.push_back(std::move(newEntry));
872 EventEntry& entry = *(mInboundQueue.back());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800873 traceInboundQueueLengthLocked();
874
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700875 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700876 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700877 // Optimize app switch latency.
878 // If the application takes too long to catch up then we drop all events preceding
879 // the app switch key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700880 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700881 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700882 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700883 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700884 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700885 if (mAppSwitchSawKeyDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800886#if DEBUG_APP_SWITCH
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700887 ALOGD("App switch is pending!");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800888#endif
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700889 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700890 mAppSwitchSawKeyDown = false;
891 needWake = true;
892 }
893 }
894 }
895 break;
896 }
897
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700898 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700899 if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(entry))) {
900 mNextUnblockedEvent = mInboundQueue.back();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700901 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800902 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700903 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800904 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100905 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700906 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
907 break;
908 }
909 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -0800910 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -0700911 case EventEntry::Type::SENSOR:
Prabir Pradhan99987712020-11-10 18:43:05 -0800912 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700913 // nothing to do
914 break;
915 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800916 }
917
918 return needWake;
919}
920
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700921void InputDispatcher::addRecentEventLocked(std::shared_ptr<EventEntry> entry) {
Chris Yef59a2f42020-10-16 12:55:26 -0700922 // Do not store sensor event in recent queue to avoid flooding the queue.
923 if (entry->type != EventEntry::Type::SENSOR) {
924 mRecentQueue.push_back(entry);
925 }
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700926 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700927 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800928 }
929}
930
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700931sp<InputWindowHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, int32_t x,
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700932 int32_t y, TouchState* touchState,
933 bool addOutsideTargets,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700934 bool addPortalWindows) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700935 if ((addPortalWindows || addOutsideTargets) && touchState == nullptr) {
936 LOG_ALWAYS_FATAL(
937 "Must provide a valid touch state if adding portal windows or outside targets");
938 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800939 // Traverse windows from front to back to find touched window.
Vishnu Nairad321cd2020-08-20 16:40:21 -0700940 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800941 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800942 const InputWindowInfo* windowInfo = windowHandle->getInfo();
943 if (windowInfo->displayId == displayId) {
Michael Wright44753b12020-07-08 13:48:11 +0100944 auto flags = windowInfo->flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800945
946 if (windowInfo->visible) {
Michael Wright44753b12020-07-08 13:48:11 +0100947 if (!flags.test(InputWindowInfo::Flag::NOT_TOUCHABLE)) {
948 bool isTouchModal = !flags.test(InputWindowInfo::Flag::NOT_FOCUSABLE) &&
949 !flags.test(InputWindowInfo::Flag::NOT_TOUCH_MODAL);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800950 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800951 int32_t portalToDisplayId = windowInfo->portalToDisplayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700952 if (portalToDisplayId != ADISPLAY_ID_NONE &&
953 portalToDisplayId != displayId) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800954 if (addPortalWindows) {
955 // For the monitoring channels of the display.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700956 touchState->addPortalWindow(windowHandle);
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800957 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700958 return findTouchedWindowAtLocked(portalToDisplayId, x, y, touchState,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700959 addOutsideTargets, addPortalWindows);
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800960 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800961 // Found window.
962 return windowHandle;
963 }
964 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800965
Michael Wright44753b12020-07-08 13:48:11 +0100966 if (addOutsideTargets && flags.test(InputWindowInfo::Flag::WATCH_OUTSIDE_TOUCH)) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700967 touchState->addOrUpdateWindow(windowHandle,
968 InputTarget::FLAG_DISPATCH_AS_OUTSIDE,
969 BitSet32(0));
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800970 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800971 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800972 }
973 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700974 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800975}
976
Garfield Tane84e6f92019-08-29 17:28:41 -0700977std::vector<TouchedMonitor> InputDispatcher::findTouchedGestureMonitorsLocked(
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -0700978 int32_t displayId, const std::vector<sp<InputWindowHandle>>& portalWindows) const {
Michael Wright3dd60e22019-03-27 22:06:44 +0000979 std::vector<TouchedMonitor> touchedMonitors;
980
981 std::vector<Monitor> monitors = getValueByKey(mGestureMonitorsByDisplay, displayId);
982 addGestureMonitors(monitors, touchedMonitors);
983 for (const sp<InputWindowHandle>& portalWindow : portalWindows) {
984 const InputWindowInfo* windowInfo = portalWindow->getInfo();
985 monitors = getValueByKey(mGestureMonitorsByDisplay, windowInfo->portalToDisplayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700986 addGestureMonitors(monitors, touchedMonitors, -windowInfo->frameLeft,
987 -windowInfo->frameTop);
Michael Wright3dd60e22019-03-27 22:06:44 +0000988 }
989 return touchedMonitors;
990}
991
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700992void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800993 const char* reason;
994 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700995 case DropReason::POLICY:
Michael Wrightd02c5b62014-02-10 15:10:22 -0800996#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700997 ALOGD("Dropped event because policy consumed it.");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800998#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700999 reason = "inbound event was dropped because the policy consumed it";
1000 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001001 case DropReason::DISABLED:
1002 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001003 ALOGI("Dropped event because input dispatch is disabled.");
1004 }
1005 reason = "inbound event was dropped because input dispatch is disabled";
1006 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001007 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001008 ALOGI("Dropped event because of pending overdue app switch.");
1009 reason = "inbound event was dropped because of pending overdue app switch";
1010 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001011 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001012 ALOGI("Dropped event because the current application is not responding and the user "
1013 "has started interacting with a different application.");
1014 reason = "inbound event was dropped because the current application is not responding "
1015 "and the user has started interacting with a different application";
1016 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001017 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001018 ALOGI("Dropped event because it is stale.");
1019 reason = "inbound event was dropped because it is stale";
1020 break;
Prabir Pradhan99987712020-11-10 18:43:05 -08001021 case DropReason::NO_POINTER_CAPTURE:
1022 ALOGI("Dropped event because there is no window with Pointer Capture.");
1023 reason = "inbound event was dropped because there is no window with Pointer Capture";
1024 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001025 case DropReason::NOT_DROPPED: {
1026 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001027 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001028 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001029 }
1030
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001031 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001032 case EventEntry::Type::KEY: {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001033 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
1034 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001035 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001036 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001037 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001038 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1039 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001040 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
1041 synthesizeCancelationEventsForAllConnectionsLocked(options);
1042 } else {
1043 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
1044 synthesizeCancelationEventsForAllConnectionsLocked(options);
1045 }
1046 break;
1047 }
Chris Yef59a2f42020-10-16 12:55:26 -07001048 case EventEntry::Type::SENSOR: {
1049 break;
1050 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001051 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
1052 break;
1053 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001054 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001055 case EventEntry::Type::CONFIGURATION_CHANGED:
1056 case EventEntry::Type::DEVICE_RESET: {
Chris Yef59a2f42020-10-16 12:55:26 -07001057 LOG_ALWAYS_FATAL("Should not drop %s events", NamedEnum::string(entry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001058 break;
1059 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001060 }
1061}
1062
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001063static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001064 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
1065 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001066}
1067
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001068bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
1069 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
1070 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
1071 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001072}
1073
1074bool InputDispatcher::isAppSwitchPendingLocked() {
1075 return mAppSwitchDueTime != LONG_LONG_MAX;
1076}
1077
1078void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
1079 mAppSwitchDueTime = LONG_LONG_MAX;
1080
1081#if DEBUG_APP_SWITCH
1082 if (handled) {
1083 ALOGD("App switch has arrived.");
1084 } else {
1085 ALOGD("App switch was abandoned.");
1086 }
1087#endif
1088}
1089
Michael Wrightd02c5b62014-02-10 15:10:22 -08001090bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001091 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001092}
1093
1094bool InputDispatcher::runCommandsLockedInterruptible() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001095 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001096 return false;
1097 }
1098
1099 do {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001100 std::unique_ptr<CommandEntry> commandEntry = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001101 mCommandQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001102 Command command = commandEntry->command;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001103 command(*this, commandEntry.get()); // commands are implicitly 'LockedInterruptible'
Michael Wrightd02c5b62014-02-10 15:10:22 -08001104
1105 commandEntry->connection.clear();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001106 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001107 return true;
1108}
1109
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001110void InputDispatcher::postCommandLocked(std::unique_ptr<CommandEntry> commandEntry) {
1111 mCommandQueue.push_back(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001112}
1113
1114void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001115 while (!mInboundQueue.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001116 std::shared_ptr<EventEntry> entry = mInboundQueue.front();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001117 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001118 releaseInboundEventLocked(entry);
1119 }
1120 traceInboundQueueLengthLocked();
1121}
1122
1123void InputDispatcher::releasePendingEventLocked() {
1124 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001125 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001126 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001127 }
1128}
1129
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001130void InputDispatcher::releaseInboundEventLocked(std::shared_ptr<EventEntry> entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001131 InjectionState* injectionState = entry->injectionState;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001132 if (injectionState && injectionState->injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001133#if DEBUG_DISPATCH_CYCLE
1134 ALOGD("Injected inbound event was dropped.");
1135#endif
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001136 setInjectionResult(*entry, InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001137 }
1138 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001139 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001140 }
1141 addRecentEventLocked(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001142}
1143
1144void InputDispatcher::resetKeyRepeatLocked() {
1145 if (mKeyRepeatState.lastKeyEntry) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001146 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001147 }
1148}
1149
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001150std::shared_ptr<KeyEntry> InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
1151 std::shared_ptr<KeyEntry> entry = mKeyRepeatState.lastKeyEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001152
Michael Wright2e732952014-09-24 13:26:59 -07001153 uint32_t policyFlags = entry->policyFlags &
1154 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001155
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001156 std::shared_ptr<KeyEntry> newEntry =
1157 std::make_unique<KeyEntry>(mIdGenerator.nextId(), currentTime, entry->deviceId,
1158 entry->source, entry->displayId, policyFlags, entry->action,
1159 entry->flags, entry->keyCode, entry->scanCode,
1160 entry->metaState, entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001161
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001162 newEntry->syntheticRepeat = true;
1163 mKeyRepeatState.lastKeyEntry = newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001164 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001165 return newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001166}
1167
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001168bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001169 const ConfigurationChangedEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001170#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001171 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry.eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001172#endif
1173
1174 // Reset key repeating in case a keyboard device was added or removed or something.
1175 resetKeyRepeatLocked();
1176
1177 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001178 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
1179 &InputDispatcher::doNotifyConfigurationChangedLockedInterruptible);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001180 commandEntry->eventTime = entry.eventTime;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001181 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001182 return true;
1183}
1184
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001185bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime,
1186 const DeviceResetEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001187#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001188 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry.eventTime,
1189 entry.deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001190#endif
1191
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001192 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, "device was reset");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001193 options.deviceId = entry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001194 synthesizeCancelationEventsForAllConnectionsLocked(options);
1195 return true;
1196}
1197
Vishnu Nairad321cd2020-08-20 16:40:21 -07001198void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nairc519ff72021-01-21 08:23:08 -08001199 const std::string& reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001200 if (mPendingEvent != nullptr) {
1201 // Move the pending event to the front of the queue. This will give the chance
1202 // for the pending event to get dispatched to the newly focused window
1203 mInboundQueue.push_front(mPendingEvent);
1204 mPendingEvent = nullptr;
1205 }
1206
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001207 std::unique_ptr<FocusEntry> focusEntry =
1208 std::make_unique<FocusEntry>(mIdGenerator.nextId(), now(), windowToken, hasFocus,
1209 reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001210
1211 // This event should go to the front of the queue, but behind all other focus events
1212 // Find the last focus event, and insert right after it
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001213 std::deque<std::shared_ptr<EventEntry>>::reverse_iterator it =
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001214 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001215 [](const std::shared_ptr<EventEntry>& event) {
1216 return event->type == EventEntry::Type::FOCUS;
1217 });
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001218
1219 // Maintain the order of focus events. Insert the entry after all other focus events.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001220 mInboundQueue.insert(it.base(), std::move(focusEntry));
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001221}
1222
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001223void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, std::shared_ptr<FocusEntry> entry) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001224 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001225 if (channel == nullptr) {
1226 return; // Window has gone away
1227 }
1228 InputTarget target;
1229 target.inputChannel = channel;
1230 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1231 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001232 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1233 channel->getName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001234 std::string reason = std::string("reason=").append(entry->reason);
1235 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001236 dispatchEventLocked(currentTime, entry, {target});
1237}
1238
Prabir Pradhan99987712020-11-10 18:43:05 -08001239void InputDispatcher::dispatchPointerCaptureChangedLocked(
1240 nsecs_t currentTime, const std::shared_ptr<PointerCaptureChangedEntry>& entry,
1241 DropReason& dropReason) {
1242 const bool haveWindowWithPointerCapture = mWindowTokenWithPointerCapture != nullptr;
1243 if (entry->pointerCaptureEnabled == haveWindowWithPointerCapture) {
1244 LOG_ALWAYS_FATAL_IF(mFocusedWindowRequestedPointerCapture,
1245 "The Pointer Capture state has already been dispatched to the window.");
1246 // Pointer capture was already forcefully disabled because of focus change.
1247 dropReason = DropReason::NOT_DROPPED;
1248 return;
1249 }
1250
1251 // Set drop reason for early returns
1252 dropReason = DropReason::NO_POINTER_CAPTURE;
1253
1254 sp<IBinder> token;
1255 if (entry->pointerCaptureEnabled) {
1256 // Enable Pointer Capture
1257 if (!mFocusedWindowRequestedPointerCapture) {
1258 // This can happen if a window requests capture and immediately releases capture.
1259 ALOGW("No window requested Pointer Capture.");
1260 return;
1261 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08001262 token = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08001263 LOG_ALWAYS_FATAL_IF(!token, "Cannot find focused window for Pointer Capture.");
1264 mWindowTokenWithPointerCapture = token;
1265 } else {
1266 // Disable Pointer Capture
1267 token = mWindowTokenWithPointerCapture;
1268 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan7d030382020-12-21 07:58:35 -08001269 if (mFocusedWindowRequestedPointerCapture) {
1270 mFocusedWindowRequestedPointerCapture = false;
1271 setPointerCaptureLocked(false);
1272 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001273 }
1274
1275 auto channel = getInputChannelLocked(token);
1276 if (channel == nullptr) {
1277 // Window has gone away, clean up Pointer Capture state.
1278 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan7d030382020-12-21 07:58:35 -08001279 if (mFocusedWindowRequestedPointerCapture) {
1280 mFocusedWindowRequestedPointerCapture = false;
1281 setPointerCaptureLocked(false);
1282 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001283 return;
1284 }
1285 InputTarget target;
1286 target.inputChannel = channel;
1287 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1288 entry->dispatchInProgress = true;
1289 dispatchEventLocked(currentTime, entry, {target});
1290
1291 dropReason = DropReason::NOT_DROPPED;
1292}
1293
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001294bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<KeyEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001295 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001296 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001297 if (!entry->dispatchInProgress) {
1298 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1299 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1300 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1301 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001302 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001303 // We have seen two identical key downs in a row which indicates that the device
1304 // driver is automatically generating key repeats itself. We take note of the
1305 // repeat here, but we disable our own next key repeat timer since it is clear that
1306 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001307 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1308 // Make sure we don't get key down from a different device. If a different
1309 // device Id has same key pressed down, the new device Id will replace the
1310 // current one to hold the key repeat with repeat count reset.
1311 // In the future when got a KEY_UP on the device id, drop it and do not
1312 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001313 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1314 resetKeyRepeatLocked();
1315 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
1316 } else {
1317 // Not a repeat. Save key down state in case we do see a repeat later.
1318 resetKeyRepeatLocked();
1319 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1320 }
1321 mKeyRepeatState.lastKeyEntry = entry;
Chris Ye2ad95392020-09-01 13:44:44 -07001322 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1323 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001324 // The key on device 'deviceId' is still down, do not stop key repeat
Chris Ye2ad95392020-09-01 13:44:44 -07001325#if DEBUG_INBOUND_EVENT_DETAILS
1326 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1327#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001328 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001329 resetKeyRepeatLocked();
1330 }
1331
1332 if (entry->repeatCount == 1) {
1333 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1334 } else {
1335 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1336 }
1337
1338 entry->dispatchInProgress = true;
1339
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001340 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001341 }
1342
1343 // Handle case where the policy asked us to try again later last time.
1344 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
1345 if (currentTime < entry->interceptKeyWakeupTime) {
1346 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1347 *nextWakeupTime = entry->interceptKeyWakeupTime;
1348 }
1349 return false; // wait until next wakeup
1350 }
1351 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
1352 entry->interceptKeyWakeupTime = 0;
1353 }
1354
1355 // Give the policy a chance to intercept the key.
1356 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
1357 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001358 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
Siarhei Vishniakou49a350a2019-07-26 18:44:23 -07001359 &InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
Vishnu Nairad321cd2020-08-20 16:40:21 -07001360 sp<IBinder> focusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08001361 mFocusResolver.getFocusedWindowToken(getTargetDisplayId(*entry));
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06001362 commandEntry->connectionToken = focusedWindowToken;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001363 commandEntry->keyEntry = entry;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001364 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001365 return false; // wait for the command to run
1366 } else {
1367 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
1368 }
1369 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001370 if (*dropReason == DropReason::NOT_DROPPED) {
1371 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001372 }
1373 }
1374
1375 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001376 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001377 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001378 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1379 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001380 mReporter->reportDroppedKey(entry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001381 return true;
1382 }
1383
1384 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001385 std::vector<InputTarget> inputTargets;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001386 InputEventInjectionResult injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001387 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001388 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001389 return false;
1390 }
1391
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001392 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001393 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001394 return true;
1395 }
1396
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001397 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001398 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001399
1400 // Dispatch the key.
1401 dispatchEventLocked(currentTime, entry, inputTargets);
1402 return true;
1403}
1404
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001405void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001406#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01001407 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001408 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1409 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001410 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1411 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
1412 entry.repeatCount, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001413#endif
1414}
1415
Chris Yef59a2f42020-10-16 12:55:26 -07001416void InputDispatcher::doNotifySensorLockedInterruptible(CommandEntry* commandEntry) {
1417 mLock.unlock();
1418
1419 const std::shared_ptr<SensorEntry>& entry = commandEntry->sensorEntry;
1420 if (entry->accuracyChanged) {
1421 mPolicy->notifySensorAccuracy(entry->deviceId, entry->sensorType, entry->accuracy);
1422 }
1423 mPolicy->notifySensorEvent(entry->deviceId, entry->sensorType, entry->accuracy,
1424 entry->hwTimestamp, entry->values);
1425 mLock.lock();
1426}
1427
1428void InputDispatcher::dispatchSensorLocked(nsecs_t currentTime, std::shared_ptr<SensorEntry> entry,
1429 DropReason* dropReason, nsecs_t* nextWakeupTime) {
1430#if DEBUG_OUTBOUND_EVENT_DETAILS
1431 ALOGD("notifySensorEvent eventTime=%" PRId64 ", hwTimestamp=%" PRId64 ", deviceId=%d, "
1432 "source=0x%x, sensorType=%s",
1433 entry->eventTime, entry->hwTimestamp, entry->deviceId, entry->source,
1434 NamedEnum::string(sensorType).c_str());
1435#endif
1436 std::unique_ptr<CommandEntry> commandEntry =
1437 std::make_unique<CommandEntry>(&InputDispatcher::doNotifySensorLockedInterruptible);
1438 commandEntry->sensorEntry = entry;
1439 postCommandLocked(std::move(commandEntry));
1440}
1441
1442bool InputDispatcher::flushSensor(int deviceId, InputDeviceSensorType sensorType) {
1443#if DEBUG_OUTBOUND_EVENT_DETAILS
1444 ALOGD("flushSensor deviceId=%d, sensorType=%s", deviceId,
1445 NamedEnum::string(sensorType).c_str());
1446#endif
1447 { // acquire lock
1448 std::scoped_lock _l(mLock);
1449
1450 for (auto it = mInboundQueue.begin(); it != mInboundQueue.end(); it++) {
1451 std::shared_ptr<EventEntry> entry = *it;
1452 if (entry->type == EventEntry::Type::SENSOR) {
1453 it = mInboundQueue.erase(it);
1454 releaseInboundEventLocked(entry);
1455 }
1456 }
1457 }
1458 return true;
1459}
1460
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001461bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, std::shared_ptr<MotionEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001462 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001463 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001464 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001465 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001466 entry->dispatchInProgress = true;
1467
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001468 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001469 }
1470
1471 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001472 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001473 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001474 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1475 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001476 return true;
1477 }
1478
1479 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
1480
1481 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001482 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001483
1484 bool conflictingPointerActions = false;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001485 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001486 if (isPointerEvent) {
1487 // Pointer event. (eg. touchscreen)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001488 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001489 findTouchedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001490 &conflictingPointerActions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001491 } else {
1492 // Non touch event. (eg. trackball)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001493 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001494 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001495 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001496 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001497 return false;
1498 }
1499
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001500 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001501 if (injectionResult == InputEventInjectionResult::PERMISSION_DENIED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001502 ALOGW("Permission denied, dropping the motion (isPointer=%s)", toString(isPointerEvent));
1503 return true;
1504 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001505 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001506 CancelationOptions::Mode mode(isPointerEvent
1507 ? CancelationOptions::CANCEL_POINTER_EVENTS
1508 : CancelationOptions::CANCEL_NON_POINTER_EVENTS);
1509 CancelationOptions options(mode, "input event injection failed");
1510 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001511 return true;
1512 }
1513
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001514 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001515 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001516
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001517 if (isPointerEvent) {
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07001518 std::unordered_map<int32_t, TouchState>::iterator it =
1519 mTouchStatesByDisplay.find(entry->displayId);
1520 if (it != mTouchStatesByDisplay.end()) {
1521 const TouchState& state = it->second;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001522 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001523 // The event has gone through these portal windows, so we add monitoring targets of
1524 // the corresponding displays as well.
1525 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001526 const InputWindowInfo* windowInfo = state.portalWindows[i]->getInfo();
Michael Wright3dd60e22019-03-27 22:06:44 +00001527 addGlobalMonitoringTargetsLocked(inputTargets, windowInfo->portalToDisplayId,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001528 -windowInfo->frameLeft, -windowInfo->frameTop);
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001529 }
1530 }
1531 }
1532 }
1533
Michael Wrightd02c5b62014-02-10 15:10:22 -08001534 // Dispatch the motion.
1535 if (conflictingPointerActions) {
1536 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001537 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001538 synthesizeCancelationEventsForAllConnectionsLocked(options);
1539 }
1540 dispatchEventLocked(currentTime, entry, inputTargets);
1541 return true;
1542}
1543
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001544void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001545#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08001546 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001547 ", policyFlags=0x%x, "
1548 "action=0x%x, actionButton=0x%x, flags=0x%x, "
1549 "metaState=0x%x, buttonState=0x%x,"
1550 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001551 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1552 entry.action, entry.actionButton, entry.flags, entry.metaState, entry.buttonState,
1553 entry.edgeFlags, entry.xPrecision, entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001554
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001555 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001556 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001557 "x=%f, y=%f, pressure=%f, size=%f, "
1558 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1559 "orientation=%f",
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001560 i, entry.pointerProperties[i].id, entry.pointerProperties[i].toolType,
1561 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1562 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1563 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1564 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1565 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1566 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1567 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1568 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1569 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001570 }
1571#endif
1572}
1573
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001574void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
1575 std::shared_ptr<EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001576 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001577 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001578#if DEBUG_DISPATCH_CYCLE
1579 ALOGD("dispatchEventToCurrentInputTargets");
1580#endif
1581
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001582 updateInteractionTokensLocked(*eventEntry, inputTargets);
1583
Michael Wrightd02c5b62014-02-10 15:10:22 -08001584 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1585
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001586 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001587
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001588 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001589 sp<Connection> connection =
1590 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001591 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001592 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001593 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001594 if (DEBUG_FOCUS) {
1595 ALOGD("Dropping event delivery to target with channel '%s' because it "
1596 "is no longer registered with the input dispatcher.",
1597 inputTarget.inputChannel->getName().c_str());
1598 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001599 }
1600 }
1601}
1602
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001603void InputDispatcher::cancelEventsForAnrLocked(const sp<Connection>& connection) {
1604 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
1605 // If the policy decides to close the app, we will get a channel removal event via
1606 // unregisterInputChannel, and will clean up the connection that way. We are already not
1607 // sending new pointers to the connection when it blocked, but focused events will continue to
1608 // pile up.
1609 ALOGW("Canceling events for %s because it is unresponsive",
1610 connection->inputChannel->getName().c_str());
1611 if (connection->status == Connection::STATUS_NORMAL) {
1612 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1613 "application not responding");
1614 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001615 }
1616}
1617
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001618void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001619 if (DEBUG_FOCUS) {
1620 ALOGD("Resetting ANR timeouts.");
1621 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001622
1623 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001624 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07001625 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001626}
1627
Tiger Huang721e26f2018-07-24 22:26:19 +08001628/**
1629 * Get the display id that the given event should go to. If this event specifies a valid display id,
1630 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1631 * Focused display is the display that the user most recently interacted with.
1632 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001633int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001634 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001635 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001636 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001637 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1638 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001639 break;
1640 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001641 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001642 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1643 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001644 break;
1645 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001646 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001647 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001648 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07001649 case EventEntry::Type::DEVICE_RESET:
1650 case EventEntry::Type::SENSOR: {
1651 ALOGE("%s events do not have a target display", NamedEnum::string(entry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001652 return ADISPLAY_ID_NONE;
1653 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001654 }
1655 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1656}
1657
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001658bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
1659 const char* focusedWindowName) {
1660 if (mAnrTracker.empty()) {
1661 // already processed all events that we waited for
1662 mKeyIsWaitingForEventsTimeout = std::nullopt;
1663 return false;
1664 }
1665
1666 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
1667 // Start the timer
1668 ALOGD("Waiting to send key to %s because there are unprocessed events that may cause "
1669 "focus to change",
1670 focusedWindowName);
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001671 mKeyIsWaitingForEventsTimeout = currentTime +
1672 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
1673 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001674 return true;
1675 }
1676
1677 // We still have pending events, and already started the timer
1678 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
1679 return true; // Still waiting
1680 }
1681
1682 // Waited too long, and some connection still hasn't processed all motions
1683 // Just send the key to the focused window
1684 ALOGW("Dispatching key to %s even though there are other unprocessed events",
1685 focusedWindowName);
1686 mKeyIsWaitingForEventsTimeout = std::nullopt;
1687 return false;
1688}
1689
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001690InputEventInjectionResult InputDispatcher::findFocusedWindowTargetsLocked(
1691 nsecs_t currentTime, const EventEntry& entry, std::vector<InputTarget>& inputTargets,
1692 nsecs_t* nextWakeupTime) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001693 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001694
Tiger Huang721e26f2018-07-24 22:26:19 +08001695 int32_t displayId = getTargetDisplayId(entry);
Vishnu Nairad321cd2020-08-20 16:40:21 -07001696 sp<InputWindowHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07001697 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08001698 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1699
Michael Wrightd02c5b62014-02-10 15:10:22 -08001700 // If there is no currently focused window and no focused application
1701 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001702 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
1703 ALOGI("Dropping %s event because there is no focused window or focused application in "
1704 "display %" PRId32 ".",
Chris Yef59a2f42020-10-16 12:55:26 -07001705 NamedEnum::string(entry.type).c_str(), displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001706 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001707 }
1708
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001709 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
1710 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
1711 // start interacting with another application via touch (app switch). This code can be removed
1712 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
1713 // an app is expected to have a focused window.
1714 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
1715 if (!mNoFocusedWindowTimeoutTime.has_value()) {
1716 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001717 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
1718 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
1719 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001720 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05001721 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001722 ALOGW("Waiting because no window has focus but %s may eventually add a "
1723 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001724 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001725 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001726 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001727 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
1728 // Already raised ANR. Drop the event
1729 ALOGE("Dropping %s event because there is no focused window",
Chris Yef59a2f42020-10-16 12:55:26 -07001730 NamedEnum::string(entry.type).c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001731 return InputEventInjectionResult::FAILED;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001732 } else {
1733 // Still waiting for the focused window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001734 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001735 }
1736 }
1737
1738 // we have a valid, non-null focused window
1739 resetNoFocusedWindowTimeoutLocked();
1740
Michael Wrightd02c5b62014-02-10 15:10:22 -08001741 // Check permissions.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001742 if (!checkInjectionPermission(focusedWindowHandle, entry.injectionState)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001743 return InputEventInjectionResult::PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001744 }
1745
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001746 if (focusedWindowHandle->getInfo()->paused) {
1747 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001748 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001749 }
1750
1751 // If the event is a key event, then we must wait for all previous events to
1752 // complete before delivering it because previous events may have the
1753 // side-effect of transferring focus to a different window and we want to
1754 // ensure that the following keys are sent to the new window.
1755 //
1756 // Suppose the user touches a button in a window then immediately presses "A".
1757 // If the button causes a pop-up window to appear then we want to ensure that
1758 // the "A" key is delivered to the new pop-up window. This is because users
1759 // often anticipate pending UI changes when typing on a keyboard.
1760 // To obtain this behavior, we must serialize key events with respect to all
1761 // prior input events.
1762 if (entry.type == EventEntry::Type::KEY) {
1763 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
1764 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001765 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001766 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001767 }
1768
1769 // Success! Output targets.
Tiger Huang721e26f2018-07-24 22:26:19 +08001770 addWindowTargetLocked(focusedWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001771 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS,
1772 BitSet32(0), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001773
1774 // Done.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001775 return InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001776}
1777
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001778/**
1779 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
1780 * that are currently unresponsive.
1781 */
1782std::vector<TouchedMonitor> InputDispatcher::selectResponsiveMonitorsLocked(
1783 const std::vector<TouchedMonitor>& monitors) const {
1784 std::vector<TouchedMonitor> responsiveMonitors;
1785 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
1786 [this](const TouchedMonitor& monitor) REQUIRES(mLock) {
1787 sp<Connection> connection = getConnectionLocked(
1788 monitor.monitor.inputChannel->getConnectionToken());
1789 if (connection == nullptr) {
1790 ALOGE("Could not find connection for monitor %s",
1791 monitor.monitor.inputChannel->getName().c_str());
1792 return false;
1793 }
1794 if (!connection->responsive) {
1795 ALOGW("Unresponsive monitor %s will not get the new gesture",
1796 connection->inputChannel->getName().c_str());
1797 return false;
1798 }
1799 return true;
1800 });
1801 return responsiveMonitors;
1802}
1803
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001804InputEventInjectionResult InputDispatcher::findTouchedWindowTargetsLocked(
1805 nsecs_t currentTime, const MotionEntry& entry, std::vector<InputTarget>& inputTargets,
1806 nsecs_t* nextWakeupTime, bool* outConflictingPointerActions) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001807 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001808 enum InjectionPermission {
1809 INJECTION_PERMISSION_UNKNOWN,
1810 INJECTION_PERMISSION_GRANTED,
1811 INJECTION_PERMISSION_DENIED
1812 };
1813
Michael Wrightd02c5b62014-02-10 15:10:22 -08001814 // For security reasons, we defer updating the touch state until we are sure that
1815 // event injection will be allowed.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001816 int32_t displayId = entry.displayId;
1817 int32_t action = entry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001818 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
1819
1820 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001821 InputEventInjectionResult injectionResult = InputEventInjectionResult::PENDING;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001822 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
Garfield Tandf26e862020-07-01 20:18:19 -07001823 sp<InputWindowHandle> newHoverWindowHandle(mLastHoverWindowHandle);
1824 sp<InputWindowHandle> newTouchedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001825
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001826 // Copy current touch state into tempTouchState.
1827 // This state will be used to update mTouchStatesByDisplay at the end of this function.
1828 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07001829 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001830 TouchState tempTouchState;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07001831 std::unordered_map<int32_t, TouchState>::iterator oldStateIt =
1832 mTouchStatesByDisplay.find(displayId);
1833 if (oldStateIt != mTouchStatesByDisplay.end()) {
1834 oldState = &(oldStateIt->second);
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001835 tempTouchState.copyFrom(*oldState);
Jeff Brownf086ddb2014-02-11 14:28:48 -08001836 }
1837
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001838 bool isSplit = tempTouchState.split;
1839 bool switchedDevice = tempTouchState.deviceId >= 0 && tempTouchState.displayId >= 0 &&
1840 (tempTouchState.deviceId != entry.deviceId || tempTouchState.source != entry.source ||
1841 tempTouchState.displayId != displayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001842 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
1843 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1844 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1845 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
1846 maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001847 const bool isFromMouse = entry.source == AINPUT_SOURCE_MOUSE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001848 bool wrongDevice = false;
1849 if (newGesture) {
1850 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001851 if (switchedDevice && tempTouchState.down && !down && !isHoverAction) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001852 ALOGI("Dropping event because a pointer for a different device is already down "
1853 "in display %" PRId32,
1854 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001855 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001856 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001857 switchedDevice = false;
1858 wrongDevice = true;
1859 goto Failed;
1860 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001861 tempTouchState.reset();
1862 tempTouchState.down = down;
1863 tempTouchState.deviceId = entry.deviceId;
1864 tempTouchState.source = entry.source;
1865 tempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001866 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001867 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001868 ALOGI("Dropping move event because a pointer for a different device is already active "
1869 "in display %" PRId32,
1870 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001871 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001872 injectionResult = InputEventInjectionResult::PERMISSION_DENIED;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001873 switchedDevice = false;
1874 wrongDevice = true;
1875 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001876 }
1877
1878 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
1879 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
1880
Garfield Tan00f511d2019-06-12 16:55:40 -07001881 int32_t x;
1882 int32_t y;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001883 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Garfield Tan00f511d2019-06-12 16:55:40 -07001884 // Always dispatch mouse events to cursor position.
1885 if (isFromMouse) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001886 x = int32_t(entry.xCursorPosition);
1887 y = int32_t(entry.yCursorPosition);
Garfield Tan00f511d2019-06-12 16:55:40 -07001888 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001889 x = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X));
1890 y = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y));
Garfield Tan00f511d2019-06-12 16:55:40 -07001891 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001892 bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Garfield Tandf26e862020-07-01 20:18:19 -07001893 newTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001894 findTouchedWindowAtLocked(displayId, x, y, &tempTouchState,
1895 isDown /*addOutsideTargets*/, true /*addPortalWindows*/);
Michael Wright3dd60e22019-03-27 22:06:44 +00001896
1897 std::vector<TouchedMonitor> newGestureMonitors = isDown
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001898 ? findTouchedGestureMonitorsLocked(displayId, tempTouchState.portalWindows)
Michael Wright3dd60e22019-03-27 22:06:44 +00001899 : std::vector<TouchedMonitor>{};
Michael Wrightd02c5b62014-02-10 15:10:22 -08001900
Michael Wrightd02c5b62014-02-10 15:10:22 -08001901 // Figure out whether splitting will be allowed for this window.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001902 if (newTouchedWindowHandle != nullptr &&
1903 newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Garfield Tanaddb02b2019-06-25 16:36:13 -07001904 // New window supports splitting, but we should never split mouse events.
1905 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001906 } else if (isSplit) {
1907 // New window does not support splitting but we have already split events.
1908 // Ignore the new window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001909 newTouchedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001910 }
1911
1912 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001913 if (newTouchedWindowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001914 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001915 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001916 }
1917
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001918 if (newTouchedWindowHandle != nullptr && newTouchedWindowHandle->getInfo()->paused) {
1919 ALOGI("Not sending touch event to %s because it is paused",
1920 newTouchedWindowHandle->getName().c_str());
1921 newTouchedWindowHandle = nullptr;
1922 }
1923
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001924 // Ensure the window has a connection and the connection is responsive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001925 if (newTouchedWindowHandle != nullptr) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001926 const bool isResponsive = hasResponsiveConnectionLocked(*newTouchedWindowHandle);
1927 if (!isResponsive) {
1928 ALOGW("%s will not receive the new gesture at %" PRIu64,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001929 newTouchedWindowHandle->getName().c_str(), entry.eventTime);
1930 newTouchedWindowHandle = nullptr;
1931 }
1932 }
1933
Bernardo Rufinoea97d182020-08-19 14:43:14 +01001934 // Drop events that can't be trusted due to occlusion
1935 if (newTouchedWindowHandle != nullptr &&
1936 mBlockUntrustedTouchesMode != BlockUntrustedTouchesMode::DISABLED) {
1937 TouchOcclusionInfo occlusionInfo =
1938 computeTouchOcclusionInfoLocked(newTouchedWindowHandle, x, y);
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00001939 if (!isTouchTrustedLocked(occlusionInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00001940 if (DEBUG_TOUCH_OCCLUSION) {
1941 ALOGD("Stack of obscuring windows during untrusted touch (%d, %d):", x, y);
1942 for (const auto& log : occlusionInfo.debugInfo) {
1943 ALOGD("%s", log.c_str());
1944 }
1945 }
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00001946 onUntrustedTouchLocked(occlusionInfo.obscuringPackage);
1947 if (mBlockUntrustedTouchesMode == BlockUntrustedTouchesMode::BLOCK) {
1948 ALOGW("Dropping untrusted touch event due to %s/%d",
1949 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid);
1950 newTouchedWindowHandle = nullptr;
1951 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01001952 }
1953 }
1954
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001955 // Also don't send the new touch event to unresponsive gesture monitors
1956 newGestureMonitors = selectResponsiveMonitorsLocked(newGestureMonitors);
1957
Michael Wright3dd60e22019-03-27 22:06:44 +00001958 if (newTouchedWindowHandle == nullptr && newGestureMonitors.empty()) {
1959 ALOGI("Dropping event because there is no touchable window or gesture monitor at "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001960 "(%d, %d) in display %" PRId32 ".",
1961 x, y, displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001962 injectionResult = InputEventInjectionResult::FAILED;
Michael Wright3dd60e22019-03-27 22:06:44 +00001963 goto Failed;
1964 }
1965
1966 if (newTouchedWindowHandle != nullptr) {
1967 // Set target flags.
1968 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
1969 if (isSplit) {
1970 targetFlags |= InputTarget::FLAG_SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001971 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001972 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1973 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1974 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
1975 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1976 }
1977
1978 // Update hover state.
Garfield Tandf26e862020-07-01 20:18:19 -07001979 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
1980 newHoverWindowHandle = nullptr;
1981 } else if (isHoverAction) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001982 newHoverWindowHandle = newTouchedWindowHandle;
Michael Wright3dd60e22019-03-27 22:06:44 +00001983 }
1984
1985 // Update the temporary touch state.
1986 BitSet32 pointerIds;
1987 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001988 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wright3dd60e22019-03-27 22:06:44 +00001989 pointerIds.markBit(pointerId);
1990 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001991 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001992 }
1993
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001994 tempTouchState.addGestureMonitors(newGestureMonitors);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001995 } else {
1996 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
1997
1998 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001999 if (!tempTouchState.down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002000 if (DEBUG_FOCUS) {
2001 ALOGD("Dropping event because the pointer is not down or we previously "
2002 "dropped the pointer down event in display %" PRId32,
2003 displayId);
2004 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002005 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002006 goto Failed;
2007 }
2008
2009 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002010 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002011 tempTouchState.isSlippery()) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002012 int32_t x = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
2013 int32_t y = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002014
2015 sp<InputWindowHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002016 tempTouchState.getFirstForegroundWindowHandle();
Garfield Tandf26e862020-07-01 20:18:19 -07002017 newTouchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y, &tempTouchState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002018 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
2019 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002020 if (DEBUG_FOCUS) {
2021 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
2022 oldTouchedWindowHandle->getName().c_str(),
2023 newTouchedWindowHandle->getName().c_str(), displayId);
2024 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002025 // Make a slippery exit from the old window.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002026 tempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
2027 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT,
2028 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002029
2030 // Make a slippery entrance into the new window.
2031 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2032 isSplit = true;
2033 }
2034
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002035 int32_t targetFlags =
2036 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002037 if (isSplit) {
2038 targetFlags |= InputTarget::FLAG_SPLIT;
2039 }
2040 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
2041 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002042 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
2043 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002044 }
2045
2046 BitSet32 pointerIds;
2047 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002048 pointerIds.markBit(entry.pointerProperties[0].id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002049 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002050 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002051 }
2052 }
2053 }
2054
2055 if (newHoverWindowHandle != mLastHoverWindowHandle) {
Garfield Tandf26e862020-07-01 20:18:19 -07002056 // Let the previous window know that the hover sequence is over, unless we already did it
2057 // when dispatching it as is to newTouchedWindowHandle.
2058 if (mLastHoverWindowHandle != nullptr &&
2059 (maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT ||
2060 mLastHoverWindowHandle != newTouchedWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002061#if DEBUG_HOVER
2062 ALOGD("Sending hover exit event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002063 mLastHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002064#endif
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002065 tempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
2066 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002067 }
2068
Garfield Tandf26e862020-07-01 20:18:19 -07002069 // Let the new window know that the hover sequence is starting, unless we already did it
2070 // when dispatching it as is to newTouchedWindowHandle.
2071 if (newHoverWindowHandle != nullptr &&
2072 (maskedAction != AMOTION_EVENT_ACTION_HOVER_ENTER ||
2073 newHoverWindowHandle != newTouchedWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002074#if DEBUG_HOVER
2075 ALOGD("Sending hover enter event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002076 newHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002077#endif
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002078 tempTouchState.addOrUpdateWindow(newHoverWindowHandle,
2079 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER,
2080 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002081 }
2082 }
2083
2084 // Check permission to inject into all touched foreground windows and ensure there
2085 // is at least one touched foreground window.
2086 {
2087 bool haveForegroundWindow = false;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002088 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002089 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
2090 haveForegroundWindow = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002091 if (!checkInjectionPermission(touchedWindow.windowHandle, entry.injectionState)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002092 injectionResult = InputEventInjectionResult::PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002093 injectionPermission = INJECTION_PERMISSION_DENIED;
2094 goto Failed;
2095 }
2096 }
2097 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002098 bool hasGestureMonitor = !tempTouchState.gestureMonitors.empty();
Michael Wright3dd60e22019-03-27 22:06:44 +00002099 if (!haveForegroundWindow && !hasGestureMonitor) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002100 ALOGI("Dropping event because there is no touched foreground window in display "
2101 "%" PRId32 " or gesture monitor to receive it.",
2102 displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002103 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002104 goto Failed;
2105 }
2106
2107 // Permission granted to injection into all touched foreground windows.
2108 injectionPermission = INJECTION_PERMISSION_GRANTED;
2109 }
2110
2111 // Check whether windows listening for outside touches are owned by the same UID. If it is
2112 // set the policy flag that we will not reveal coordinate information to this window.
2113 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2114 sp<InputWindowHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002115 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002116 if (foregroundWindowHandle) {
2117 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002118 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002119 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2120 sp<InputWindowHandle> inputWindowHandle = touchedWindow.windowHandle;
2121 if (inputWindowHandle->getInfo()->ownerUid != foregroundWindowUid) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002122 tempTouchState.addOrUpdateWindow(inputWindowHandle,
2123 InputTarget::FLAG_ZERO_COORDS,
2124 BitSet32(0));
Michael Wright3dd60e22019-03-27 22:06:44 +00002125 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002126 }
2127 }
2128 }
2129 }
2130
Michael Wrightd02c5b62014-02-10 15:10:22 -08002131 // If this is the first pointer going down and the touched window has a wallpaper
2132 // then also add the touched wallpaper windows so they are locked in for the duration
2133 // of the touch gesture.
2134 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
2135 // engine only supports touch events. We would need to add a mechanism similar
2136 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
2137 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2138 sp<InputWindowHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002139 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002140 if (foregroundWindowHandle && foregroundWindowHandle->getInfo()->hasWallpaper) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07002141 const std::vector<sp<InputWindowHandle>>& windowHandles =
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002142 getWindowHandlesLocked(displayId);
2143 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002144 const InputWindowInfo* info = windowHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002145 if (info->displayId == displayId &&
Michael Wright44753b12020-07-08 13:48:11 +01002146 windowHandle->getInfo()->type == InputWindowInfo::Type::WALLPAPER) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002147 tempTouchState
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002148 .addOrUpdateWindow(windowHandle,
2149 InputTarget::FLAG_WINDOW_IS_OBSCURED |
2150 InputTarget::
2151 FLAG_WINDOW_IS_PARTIALLY_OBSCURED |
2152 InputTarget::FLAG_DISPATCH_AS_IS,
2153 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002154 }
2155 }
2156 }
2157 }
2158
2159 // Success! Output targets.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002160 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002161
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002162 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002163 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002164 touchedWindow.pointerIds, inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002165 }
2166
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002167 for (const TouchedMonitor& touchedMonitor : tempTouchState.gestureMonitors) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002168 addMonitoringTargetLocked(touchedMonitor.monitor, touchedMonitor.xOffset,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002169 touchedMonitor.yOffset, inputTargets);
Michael Wright3dd60e22019-03-27 22:06:44 +00002170 }
2171
Michael Wrightd02c5b62014-02-10 15:10:22 -08002172 // Drop the outside or hover touch windows since we will not care about them
2173 // in the next iteration.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002174 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002175
2176Failed:
2177 // Check injection permission once and for all.
2178 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002179 if (checkInjectionPermission(nullptr, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002180 injectionPermission = INJECTION_PERMISSION_GRANTED;
2181 } else {
2182 injectionPermission = INJECTION_PERMISSION_DENIED;
2183 }
2184 }
2185
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002186 if (injectionPermission != INJECTION_PERMISSION_GRANTED) {
2187 return injectionResult;
2188 }
2189
Michael Wrightd02c5b62014-02-10 15:10:22 -08002190 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002191 if (!wrongDevice) {
2192 if (switchedDevice) {
2193 if (DEBUG_FOCUS) {
2194 ALOGD("Conflicting pointer actions: Switched to a different device.");
2195 }
2196 *outConflictingPointerActions = true;
2197 }
2198
2199 if (isHoverAction) {
2200 // Started hovering, therefore no longer down.
2201 if (oldState && oldState->down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002202 if (DEBUG_FOCUS) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002203 ALOGD("Conflicting pointer actions: Hover received while pointer was "
2204 "down.");
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002205 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002206 *outConflictingPointerActions = true;
2207 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002208 tempTouchState.reset();
2209 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2210 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
2211 tempTouchState.deviceId = entry.deviceId;
2212 tempTouchState.source = entry.source;
2213 tempTouchState.displayId = displayId;
2214 }
2215 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
2216 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
2217 // All pointers up or canceled.
2218 tempTouchState.reset();
2219 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2220 // First pointer went down.
2221 if (oldState && oldState->down) {
2222 if (DEBUG_FOCUS) {
2223 ALOGD("Conflicting pointer actions: Down received while already down.");
2224 }
2225 *outConflictingPointerActions = true;
2226 }
2227 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2228 // One pointer went up.
2229 if (isSplit) {
2230 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2231 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002232
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002233 for (size_t i = 0; i < tempTouchState.windows.size();) {
2234 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2235 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
2236 touchedWindow.pointerIds.clearBit(pointerId);
2237 if (touchedWindow.pointerIds.isEmpty()) {
2238 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
2239 continue;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002240 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002241 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002242 i += 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002243 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002244 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002245 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002246
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002247 // Save changes unless the action was scroll in which case the temporary touch
2248 // state was only valid for this one action.
2249 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
2250 if (tempTouchState.displayId >= 0) {
2251 mTouchStatesByDisplay[displayId] = tempTouchState;
2252 } else {
2253 mTouchStatesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002254 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002255 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002256
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002257 // Update hover state.
2258 mLastHoverWindowHandle = newHoverWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002259 }
2260
Michael Wrightd02c5b62014-02-10 15:10:22 -08002261 return injectionResult;
2262}
2263
2264void InputDispatcher::addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002265 int32_t targetFlags, BitSet32 pointerIds,
2266 std::vector<InputTarget>& inputTargets) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002267 std::vector<InputTarget>::iterator it =
2268 std::find_if(inputTargets.begin(), inputTargets.end(),
2269 [&windowHandle](const InputTarget& inputTarget) {
2270 return inputTarget.inputChannel->getConnectionToken() ==
2271 windowHandle->getToken();
2272 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002273
Chavi Weingarten114b77f2020-01-15 22:35:10 +00002274 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002275
2276 if (it == inputTargets.end()) {
2277 InputTarget inputTarget;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05002278 std::shared_ptr<InputChannel> inputChannel =
2279 getInputChannelLocked(windowHandle->getToken());
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002280 if (inputChannel == nullptr) {
2281 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
2282 return;
2283 }
2284 inputTarget.inputChannel = inputChannel;
2285 inputTarget.flags = targetFlags;
2286 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
2287 inputTargets.push_back(inputTarget);
2288 it = inputTargets.end() - 1;
2289 }
2290
2291 ALOG_ASSERT(it->flags == targetFlags);
2292 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2293
chaviw1ff3d1e2020-07-01 15:53:47 -07002294 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002295}
2296
Michael Wright3dd60e22019-03-27 22:06:44 +00002297void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002298 int32_t displayId, float xOffset,
2299 float yOffset) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002300 std::unordered_map<int32_t, std::vector<Monitor>>::const_iterator it =
2301 mGlobalMonitorsByDisplay.find(displayId);
2302
2303 if (it != mGlobalMonitorsByDisplay.end()) {
2304 const std::vector<Monitor>& monitors = it->second;
2305 for (const Monitor& monitor : monitors) {
2306 addMonitoringTargetLocked(monitor, xOffset, yOffset, inputTargets);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002307 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002308 }
2309}
2310
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002311void InputDispatcher::addMonitoringTargetLocked(const Monitor& monitor, float xOffset,
2312 float yOffset,
2313 std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002314 InputTarget target;
2315 target.inputChannel = monitor.inputChannel;
2316 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
chaviw1ff3d1e2020-07-01 15:53:47 -07002317 ui::Transform t;
2318 t.set(xOffset, yOffset);
2319 target.setDefaultPointerTransform(t);
Michael Wright3dd60e22019-03-27 22:06:44 +00002320 inputTargets.push_back(target);
2321}
2322
Michael Wrightd02c5b62014-02-10 15:10:22 -08002323bool InputDispatcher::checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002324 const InjectionState* injectionState) {
2325 if (injectionState &&
2326 (windowHandle == nullptr ||
2327 windowHandle->getInfo()->ownerUid != injectionState->injectorUid) &&
2328 !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002329 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002330 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002331 "owned by uid %d",
2332 injectionState->injectorPid, injectionState->injectorUid,
2333 windowHandle->getName().c_str(), windowHandle->getInfo()->ownerUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002334 } else {
2335 ALOGW("Permission denied: injecting event from pid %d uid %d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002336 injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002337 }
2338 return false;
2339 }
2340 return true;
2341}
2342
Robert Carrc9bf1d32020-04-13 17:21:08 -07002343/**
2344 * Indicate whether one window handle should be considered as obscuring
2345 * another window handle. We only check a few preconditions. Actually
2346 * checking the bounds is left to the caller.
2347 */
2348static bool canBeObscuredBy(const sp<InputWindowHandle>& windowHandle,
2349 const sp<InputWindowHandle>& otherHandle) {
2350 // Compare by token so cloned layers aren't counted
2351 if (haveSameToken(windowHandle, otherHandle)) {
2352 return false;
2353 }
2354 auto info = windowHandle->getInfo();
2355 auto otherInfo = otherHandle->getInfo();
2356 if (!otherInfo->visible) {
2357 return false;
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002358 } else if (otherInfo->alpha == 0 &&
2359 otherInfo->flags.test(InputWindowInfo::Flag::NOT_TOUCHABLE)) {
2360 // Those act as if they were invisible, so we don't need to flag them.
2361 // We do want to potentially flag touchable windows even if they have 0
2362 // opacity, since they can consume touches and alter the effects of the
2363 // user interaction (eg. apps that rely on
2364 // FLAG_WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
2365 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
2366 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002367 } else if (info->ownerUid == otherInfo->ownerUid) {
2368 // If ownerUid is the same we don't generate occlusion events as there
2369 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002370 return false;
Chris Yefcdff3e2020-05-10 15:16:04 -07002371 } else if (otherInfo->trustedOverlay) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002372 return false;
2373 } else if (otherInfo->displayId != info->displayId) {
2374 return false;
2375 }
2376 return true;
2377}
2378
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002379/**
2380 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
2381 * untrusted, one should check:
2382 *
2383 * 1. If result.hasBlockingOcclusion is true.
2384 * If it's, it means the touch should be blocked due to a window with occlusion mode of
2385 * BLOCK_UNTRUSTED.
2386 *
2387 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
2388 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
2389 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
2390 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
2391 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
2392 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
2393 *
2394 * If neither of those is true, then it means the touch can be allowed.
2395 */
2396InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
2397 const sp<InputWindowHandle>& windowHandle, int32_t x, int32_t y) const {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002398 const InputWindowInfo* windowInfo = windowHandle->getInfo();
2399 int32_t displayId = windowInfo->displayId;
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002400 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2401 TouchOcclusionInfo info;
2402 info.hasBlockingOcclusion = false;
2403 info.obscuringOpacity = 0;
2404 info.obscuringUid = -1;
2405 std::map<int32_t, float> opacityByUid;
2406 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
2407 if (windowHandle == otherHandle) {
2408 break; // All future windows are below us. Exit early.
2409 }
2410 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00002411 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->frameContainsPoint(x, y) &&
2412 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002413 if (DEBUG_TOUCH_OCCLUSION) {
2414 info.debugInfo.push_back(
2415 dumpWindowForTouchOcclusion(otherInfo, /* isTouchedWindow */ false));
2416 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002417 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
2418 // we perform the checks below to see if the touch can be propagated or not based on the
2419 // window's touch occlusion mode
2420 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
2421 info.hasBlockingOcclusion = true;
2422 info.obscuringUid = otherInfo->ownerUid;
2423 info.obscuringPackage = otherInfo->packageName;
2424 break;
2425 }
2426 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
2427 uint32_t uid = otherInfo->ownerUid;
2428 float opacity =
2429 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
2430 // Given windows A and B:
2431 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
2432 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
2433 opacityByUid[uid] = opacity;
2434 if (opacity > info.obscuringOpacity) {
2435 info.obscuringOpacity = opacity;
2436 info.obscuringUid = uid;
2437 info.obscuringPackage = otherInfo->packageName;
2438 }
2439 }
2440 }
2441 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002442 if (DEBUG_TOUCH_OCCLUSION) {
2443 info.debugInfo.push_back(
2444 dumpWindowForTouchOcclusion(windowInfo, /* isTouchedWindow */ true));
2445 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002446 return info;
2447}
2448
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002449std::string InputDispatcher::dumpWindowForTouchOcclusion(const InputWindowInfo* info,
2450 bool isTouchedWindow) const {
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00002451 return StringPrintf(INDENT2 "* %stype=%s, package=%s/%" PRId32 ", id=%" PRId32
2452 ", mode=%s, alpha=%.2f, "
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00002453 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
2454 "], touchableRegion=%s, window={%s}, applicationInfo=%s, "
2455 "flags={%s}, inputFeatures={%s}, hasToken=%s\n",
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002456 (isTouchedWindow) ? "[TOUCHED] " : "",
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00002457 NamedEnum::string(info->type, "%" PRId32).c_str(),
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00002458 info->packageName.c_str(), info->ownerUid, info->id,
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00002459 toString(info->touchOcclusionMode).c_str(), info->alpha, info->frameLeft,
2460 info->frameTop, info->frameRight, info->frameBottom,
2461 dumpRegion(info->touchableRegion).c_str(), info->name.c_str(),
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00002462 info->applicationInfo.name.c_str(), info->flags.string().c_str(),
2463 info->inputFeatures.string().c_str(), toString(info->token != nullptr));
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002464}
2465
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002466bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
2467 if (occlusionInfo.hasBlockingOcclusion) {
2468 ALOGW("Untrusted touch due to occlusion by %s/%d", occlusionInfo.obscuringPackage.c_str(),
2469 occlusionInfo.obscuringUid);
2470 return false;
2471 }
2472 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
2473 ALOGW("Untrusted touch due to occlusion by %s/%d (obscuring opacity = "
2474 "%.2f, maximum allowed = %.2f)",
2475 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid,
2476 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
2477 return false;
2478 }
2479 return true;
2480}
2481
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002482bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<InputWindowHandle>& windowHandle,
2483 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002484 int32_t displayId = windowHandle->getInfo()->displayId;
Vishnu Nairad321cd2020-08-20 16:40:21 -07002485 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002486 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002487 if (windowHandle == otherHandle) {
2488 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002489 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002490 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002491 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002492 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002493 return true;
2494 }
2495 }
2496 return false;
2497}
2498
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002499bool InputDispatcher::isWindowObscuredLocked(const sp<InputWindowHandle>& windowHandle) const {
2500 int32_t displayId = windowHandle->getInfo()->displayId;
Vishnu Nairad321cd2020-08-20 16:40:21 -07002501 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002502 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002503 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002504 if (windowHandle == otherHandle) {
2505 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002506 }
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002507 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002508 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002509 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002510 return true;
2511 }
2512 }
2513 return false;
2514}
2515
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002516std::string InputDispatcher::getApplicationWindowLabel(
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05002517 const InputApplicationHandle* applicationHandle,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002518 const sp<InputWindowHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002519 if (applicationHandle != nullptr) {
2520 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002521 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002522 } else {
2523 return applicationHandle->getName();
2524 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002525 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002526 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002527 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002528 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002529 }
2530}
2531
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002532void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Prabir Pradhan99987712020-11-10 18:43:05 -08002533 if (eventEntry.type == EventEntry::Type::FOCUS ||
2534 eventEntry.type == EventEntry::Type::POINTER_CAPTURE_CHANGED) {
2535 // Focus or pointer capture changed events are passed to apps, but do not represent user
2536 // activity.
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002537 return;
2538 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002539 int32_t displayId = getTargetDisplayId(eventEntry);
Vishnu Nairad321cd2020-08-20 16:40:21 -07002540 sp<InputWindowHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Tiger Huang721e26f2018-07-24 22:26:19 +08002541 if (focusedWindowHandle != nullptr) {
2542 const InputWindowInfo* info = focusedWindowHandle->getInfo();
Michael Wright44753b12020-07-08 13:48:11 +01002543 if (info->inputFeatures.test(InputWindowInfo::Feature::DISABLE_USER_ACTIVITY)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002544#if DEBUG_DISPATCH_CYCLE
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002545 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002546#endif
2547 return;
2548 }
2549 }
2550
2551 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002552 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002553 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002554 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2555 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002556 return;
2557 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002558
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002559 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002560 eventType = USER_ACTIVITY_EVENT_TOUCH;
2561 }
2562 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002563 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002564 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002565 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2566 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002567 return;
2568 }
2569 eventType = USER_ACTIVITY_EVENT_BUTTON;
2570 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002571 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002572 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002573 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08002574 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07002575 case EventEntry::Type::SENSOR:
Prabir Pradhan99987712020-11-10 18:43:05 -08002576 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002577 LOG_ALWAYS_FATAL("%s events are not user activity",
Chris Yef59a2f42020-10-16 12:55:26 -07002578 NamedEnum::string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002579 break;
2580 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002581 }
2582
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002583 std::unique_ptr<CommandEntry> commandEntry =
2584 std::make_unique<CommandEntry>(&InputDispatcher::doPokeUserActivityLockedInterruptible);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002585 commandEntry->eventTime = eventEntry.eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002586 commandEntry->userActivityEventType = eventType;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002587 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002588}
2589
2590void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002591 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002592 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002593 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002594 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002595 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002596 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002597 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002598 ATRACE_NAME(message.c_str());
2599 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002600#if DEBUG_DISPATCH_CYCLE
2601 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002602 "globalScaleFactor=%f, pointerIds=0x%x %s",
2603 connection->getInputChannelName().c_str(), inputTarget.flags,
2604 inputTarget.globalScaleFactor, inputTarget.pointerIds.value,
2605 inputTarget.getPointerInfoString().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002606#endif
2607
2608 // Skip this event if the connection status is not normal.
2609 // We don't want to enqueue additional outbound events if the connection is broken.
2610 if (connection->status != Connection::STATUS_NORMAL) {
2611#if DEBUG_DISPATCH_CYCLE
2612 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002613 connection->getInputChannelName().c_str(), connection->getStatusLabel());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002614#endif
2615 return;
2616 }
2617
2618 // Split a motion event if needed.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002619 if (inputTarget.flags & InputTarget::FLAG_SPLIT) {
2620 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
2621 "Entry type %s should not have FLAG_SPLIT",
Chris Yef59a2f42020-10-16 12:55:26 -07002622 NamedEnum::string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002623
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002624 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002625 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002626 std::unique_ptr<MotionEntry> splitMotionEntry =
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002627 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002628 if (!splitMotionEntry) {
2629 return; // split event was dropped
2630 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002631 if (DEBUG_FOCUS) {
2632 ALOGD("channel '%s' ~ Split motion event.",
2633 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002634 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002635 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002636 enqueueDispatchEntriesLocked(currentTime, connection, std::move(splitMotionEntry),
2637 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002638 return;
2639 }
2640 }
2641
2642 // Not splitting. Enqueue dispatch entries for the event as is.
2643 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
2644}
2645
2646void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002647 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002648 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002649 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002650 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002651 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002652 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002653 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002654 ATRACE_NAME(message.c_str());
2655 }
2656
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002657 bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002658
2659 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07002660 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002661 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002662 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002663 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07002664 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002665 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07002666 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002667 InputTarget::FLAG_DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07002668 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002669 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002670 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002671 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002672
2673 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002674 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002675 startDispatchCycleLocked(currentTime, connection);
2676 }
2677}
2678
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002679void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002680 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002681 const InputTarget& inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002682 int32_t dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002683 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002684 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
2685 connection->getInputChannelName().c_str(),
2686 dispatchModeToString(dispatchMode).c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002687 ATRACE_NAME(message.c_str());
2688 }
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002689 int32_t inputTargetFlags = inputTarget.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002690 if (!(inputTargetFlags & dispatchMode)) {
2691 return;
2692 }
2693 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
2694
2695 // This is a new event.
2696 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002697 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002698 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002699
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002700 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
2701 // different EventEntry than what was passed in.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002702 EventEntry& newEntry = *(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002703 // Apply target flags and update the connection's input state.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002704 switch (newEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002705 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002706 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002707 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002708 dispatchEntry->resolvedAction = keyEntry.action;
2709 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002710
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002711 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
2712 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002713#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002714 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
2715 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002716#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002717 return; // skip the inconsistent event
2718 }
2719 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002720 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002721
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002722 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002723 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002724 // Assign a default value to dispatchEntry that will never be generated by InputReader,
2725 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
2726 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
2727 static_cast<int32_t>(IdGenerator::Source::OTHER);
2728 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002729 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2730 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
2731 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
2732 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
2733 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
2734 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2735 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
2736 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
2737 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
2738 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
2739 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002740 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002741 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002742 }
2743 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002744 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
2745 motionEntry.displayId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002746#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002747 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter "
2748 "event",
2749 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002750#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002751 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2752 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002753
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002754 dispatchEntry->resolvedFlags = motionEntry.flags;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002755 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
2756 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
2757 }
2758 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
2759 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2760 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002761
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002762 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
2763 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002764#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002765 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
2766 "event",
2767 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002768#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002769 return; // skip the inconsistent event
2770 }
2771
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002772 dispatchEntry->resolvedEventId =
2773 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
2774 ? mIdGenerator.nextId()
2775 : motionEntry.id;
2776 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
2777 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
2778 ") to MotionEvent(id=0x%" PRIx32 ").",
2779 motionEntry.id, dispatchEntry->resolvedEventId);
2780 ATRACE_NAME(message.c_str());
2781 }
2782
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002783 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002784 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002785
2786 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002787 }
Prabir Pradhan99987712020-11-10 18:43:05 -08002788 case EventEntry::Type::FOCUS:
2789 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002790 break;
2791 }
Chris Yef59a2f42020-10-16 12:55:26 -07002792 case EventEntry::Type::SENSOR: {
2793 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
2794 break;
2795 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002796 case EventEntry::Type::CONFIGURATION_CHANGED:
2797 case EventEntry::Type::DEVICE_RESET: {
2798 LOG_ALWAYS_FATAL("%s events should not go to apps",
Chris Yef59a2f42020-10-16 12:55:26 -07002799 NamedEnum::string(newEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002800 break;
2801 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002802 }
2803
2804 // Remember that we are waiting for this dispatch to complete.
2805 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002806 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002807 }
2808
2809 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002810 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002811 traceOutboundQueueLength(connection);
chaviw8c9cf542019-03-25 13:02:48 -07002812}
2813
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00002814/**
2815 * This function is purely for debugging. It helps us understand where the user interaction
2816 * was taking place. For example, if user is touching launcher, we will see a log that user
2817 * started interacting with launcher. In that example, the event would go to the wallpaper as well.
2818 * We will see both launcher and wallpaper in that list.
2819 * Once the interaction with a particular set of connections starts, no new logs will be printed
2820 * until the set of interacted connections changes.
2821 *
2822 * The following items are skipped, to reduce the logspam:
2823 * ACTION_OUTSIDE: any windows that are receiving ACTION_OUTSIDE are not logged
2824 * ACTION_UP: any windows that receive ACTION_UP are not logged (for both keys and motions).
2825 * This includes situations like the soft BACK button key. When the user releases (lifts up the
2826 * finger) the back button, then navigation bar will inject KEYCODE_BACK with ACTION_UP.
2827 * Both of those ACTION_UP events would not be logged
2828 * Monitors (both gesture and global): any gesture monitors or global monitors receiving events
2829 * will not be logged. This is omitted to reduce the amount of data printed.
2830 * If you see <none>, it's likely that one of the gesture monitors pilfered the event, and therefore
2831 * gesture monitor is the only connection receiving the remainder of the gesture.
2832 */
2833void InputDispatcher::updateInteractionTokensLocked(const EventEntry& entry,
2834 const std::vector<InputTarget>& targets) {
2835 // Skip ACTION_UP events, and all events other than keys and motions
2836 if (entry.type == EventEntry::Type::KEY) {
2837 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
2838 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
2839 return;
2840 }
2841 } else if (entry.type == EventEntry::Type::MOTION) {
2842 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
2843 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
2844 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
2845 return;
2846 }
2847 } else {
2848 return; // Not a key or a motion
2849 }
2850
2851 std::unordered_set<sp<IBinder>, IBinderHash> newConnectionTokens;
2852 std::vector<sp<Connection>> newConnections;
2853 for (const InputTarget& target : targets) {
2854 if ((target.flags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) ==
2855 InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2856 continue; // Skip windows that receive ACTION_OUTSIDE
2857 }
2858
2859 sp<IBinder> token = target.inputChannel->getConnectionToken();
2860 sp<Connection> connection = getConnectionLocked(token);
2861 if (connection == nullptr || connection->monitor) {
2862 continue; // We only need to keep track of the non-monitor connections.
2863 }
2864 newConnectionTokens.insert(std::move(token));
2865 newConnections.emplace_back(connection);
2866 }
2867 if (newConnectionTokens == mInteractionConnectionTokens) {
2868 return; // no change
2869 }
2870 mInteractionConnectionTokens = newConnectionTokens;
2871
2872 std::string windowList;
2873 for (const sp<Connection>& connection : newConnections) {
2874 windowList += connection->getWindowName() + ", ";
2875 }
2876 std::string message = "Interaction with windows: " + windowList;
2877 if (windowList.empty()) {
2878 message += "<none>";
2879 }
2880 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
2881}
2882
chaviwfd6d3512019-03-25 13:23:49 -07002883void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07002884 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07002885 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07002886 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
2887 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07002888 return;
2889 }
2890
Vishnu Nairc519ff72021-01-21 08:23:08 -08002891 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07002892 if (focusedToken == token) {
2893 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07002894 return;
2895 }
2896
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002897 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
2898 &InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible);
Vishnu Nairad321cd2020-08-20 16:40:21 -07002899 commandEntry->newToken = token;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002900 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002901}
2902
2903void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002904 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002905 if (ATRACE_ENABLED()) {
2906 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002907 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002908 ATRACE_NAME(message.c_str());
2909 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002910#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002911 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002912#endif
2913
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002914 while (connection->status == Connection::STATUS_NORMAL && !connection->outboundQueue.empty()) {
2915 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002916 dispatchEntry->deliveryTime = currentTime;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05002917 const std::chrono::nanoseconds timeout =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002918 getDispatchingTimeoutLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou70622952020-07-30 11:17:23 -05002919 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002920
2921 // Publish the event.
2922 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002923 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
2924 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002925 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002926 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2927 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002928
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002929 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002930 status = connection->inputPublisher
2931 .publishKeyEvent(dispatchEntry->seq,
2932 dispatchEntry->resolvedEventId, keyEntry.deviceId,
2933 keyEntry.source, keyEntry.displayId,
2934 std::move(hmac), dispatchEntry->resolvedAction,
2935 dispatchEntry->resolvedFlags, keyEntry.keyCode,
2936 keyEntry.scanCode, keyEntry.metaState,
2937 keyEntry.repeatCount, keyEntry.downTime,
2938 keyEntry.eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002939 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002940 }
2941
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002942 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002943 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002944
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002945 PointerCoords scaledCoords[MAX_POINTERS];
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002946 const PointerCoords* usingCoords = motionEntry.pointerCoords;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002947
chaviw82357092020-01-28 13:13:06 -08002948 // Set the X and Y offset and X and Y scale depending on the input source.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002949 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002950 !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
2951 float globalScaleFactor = dispatchEntry->globalScaleFactor;
chaviw82357092020-01-28 13:13:06 -08002952 if (globalScaleFactor != 1.0f) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002953 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
2954 scaledCoords[i] = motionEntry.pointerCoords[i];
chaviw82357092020-01-28 13:13:06 -08002955 // Don't apply window scale here since we don't want scale to affect raw
2956 // coordinates. The scale will be sent back to the client and applied
2957 // later when requesting relative coordinates.
2958 scaledCoords[i].scale(globalScaleFactor, 1 /* windowXScale */,
2959 1 /* windowYScale */);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002960 }
2961 usingCoords = scaledCoords;
2962 }
2963 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002964 // We don't want the dispatch target to know.
2965 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002966 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002967 scaledCoords[i].clear();
2968 }
2969 usingCoords = scaledCoords;
2970 }
2971 }
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002972
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002973 std::array<uint8_t, 32> hmac = getSignature(motionEntry, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002974
2975 // Publish the motion event.
2976 status = connection->inputPublisher
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002977 .publishMotionEvent(dispatchEntry->seq,
2978 dispatchEntry->resolvedEventId,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002979 motionEntry.deviceId, motionEntry.source,
2980 motionEntry.displayId, std::move(hmac),
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002981 dispatchEntry->resolvedAction,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002982 motionEntry.actionButton,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002983 dispatchEntry->resolvedFlags,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002984 motionEntry.edgeFlags, motionEntry.metaState,
2985 motionEntry.buttonState,
2986 motionEntry.classification,
chaviw9eaa22c2020-07-01 16:21:27 -07002987 dispatchEntry->transform,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002988 motionEntry.xPrecision, motionEntry.yPrecision,
2989 motionEntry.xCursorPosition,
2990 motionEntry.yCursorPosition,
2991 motionEntry.downTime, motionEntry.eventTime,
2992 motionEntry.pointerCount,
2993 motionEntry.pointerProperties, usingCoords);
2994 reportTouchEventForStatistics(motionEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002995 break;
2996 }
Prabir Pradhan99987712020-11-10 18:43:05 -08002997
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002998 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002999 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003000 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003001 focusEntry.id,
3002 focusEntry.hasFocus,
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003003 mInTouchMode);
3004 break;
3005 }
3006
Prabir Pradhan99987712020-11-10 18:43:05 -08003007 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3008 const auto& captureEntry =
3009 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3010 status = connection->inputPublisher
3011 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
3012 captureEntry.pointerCaptureEnabled);
3013 break;
3014 }
3015
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003016 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003017 case EventEntry::Type::DEVICE_RESET:
3018 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003019 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Chris Yef59a2f42020-10-16 12:55:26 -07003020 NamedEnum::string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003021 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003022 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003023 }
3024
3025 // Check the result.
3026 if (status) {
3027 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003028 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003029 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003030 "This is unexpected because the wait queue is empty, so the pipe "
3031 "should be empty and we shouldn't have any problems writing an "
3032 "event to it, status=%d",
3033 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003034 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3035 } else {
3036 // Pipe is full and we are waiting for the app to finish process some events
3037 // before sending more events to it.
3038#if DEBUG_DISPATCH_CYCLE
3039 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003040 "waiting for the application to catch up",
3041 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003042#endif
Michael Wrightd02c5b62014-02-10 15:10:22 -08003043 }
3044 } else {
3045 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003046 "status=%d",
3047 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003048 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3049 }
3050 return;
3051 }
3052
3053 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003054 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
3055 connection->outboundQueue.end(),
3056 dispatchEntry));
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003057 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003058 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003059 if (connection->responsive) {
3060 mAnrTracker.insert(dispatchEntry->timeoutTime,
3061 connection->inputChannel->getConnectionToken());
3062 }
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003063 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003064 }
3065}
3066
chaviw09c8d2d2020-08-24 15:48:26 -07003067std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3068 size_t size;
3069 switch (event.type) {
3070 case VerifiedInputEvent::Type::KEY: {
3071 size = sizeof(VerifiedKeyEvent);
3072 break;
3073 }
3074 case VerifiedInputEvent::Type::MOTION: {
3075 size = sizeof(VerifiedMotionEvent);
3076 break;
3077 }
3078 }
3079 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3080 return mHmacKeyManager.sign(start, size);
3081}
3082
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003083const std::array<uint8_t, 32> InputDispatcher::getSignature(
3084 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
3085 int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
3086 if ((actionMasked == AMOTION_EVENT_ACTION_UP) || (actionMasked == AMOTION_EVENT_ACTION_DOWN)) {
3087 // Only sign events up and down events as the purely move events
3088 // are tied to their up/down counterparts so signing would be redundant.
3089 VerifiedMotionEvent verifiedEvent = verifiedMotionEventFromMotionEntry(motionEntry);
3090 verifiedEvent.actionMasked = actionMasked;
3091 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
chaviw09c8d2d2020-08-24 15:48:26 -07003092 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003093 }
3094 return INVALID_HMAC;
3095}
3096
3097const std::array<uint8_t, 32> InputDispatcher::getSignature(
3098 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3099 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3100 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
3101 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07003102 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003103}
3104
Michael Wrightd02c5b62014-02-10 15:10:22 -08003105void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003106 const sp<Connection>& connection, uint32_t seq,
3107 bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003108#if DEBUG_DISPATCH_CYCLE
3109 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003110 connection->getInputChannelName().c_str(), seq, toString(handled));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003111#endif
3112
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003113 if (connection->status == Connection::STATUS_BROKEN ||
3114 connection->status == Connection::STATUS_ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003115 return;
3116 }
3117
3118 // Notify other system components and prepare to start the next dispatch cycle.
3119 onDispatchCycleFinishedLocked(currentTime, connection, seq, handled);
3120}
3121
3122void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003123 const sp<Connection>& connection,
3124 bool notify) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003125#if DEBUG_DISPATCH_CYCLE
3126 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003127 connection->getInputChannelName().c_str(), toString(notify));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003128#endif
3129
3130 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003131 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003132 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003133 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003134 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003135
3136 // The connection appears to be unrecoverably broken.
3137 // Ignore already broken or zombie connections.
3138 if (connection->status == Connection::STATUS_NORMAL) {
3139 connection->status = Connection::STATUS_BROKEN;
3140
3141 if (notify) {
3142 // Notify other system components.
3143 onDispatchCycleBrokenLocked(currentTime, connection);
3144 }
3145 }
3146}
3147
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003148void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
3149 while (!queue.empty()) {
3150 DispatchEntry* dispatchEntry = queue.front();
3151 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003152 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003153 }
3154}
3155
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003156void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003157 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003158 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003159 }
3160 delete dispatchEntry;
3161}
3162
3163int InputDispatcher::handleReceiveCallback(int fd, int events, void* data) {
3164 InputDispatcher* d = static_cast<InputDispatcher*>(data);
3165
3166 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003167 std::scoped_lock _l(d->mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003168
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003169 if (d->mConnectionsByFd.find(fd) == d->mConnectionsByFd.end()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003170 ALOGE("Received spurious receive callback for unknown input channel. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003171 "fd=%d, events=0x%x",
3172 fd, events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003173 return 0; // remove the callback
3174 }
3175
3176 bool notify;
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003177 sp<Connection> connection = d->mConnectionsByFd[fd];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003178 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3179 if (!(events & ALOOPER_EVENT_INPUT)) {
3180 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003181 "events=0x%x",
3182 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003183 return 1;
3184 }
3185
3186 nsecs_t currentTime = now();
3187 bool gotOne = false;
3188 status_t status;
3189 for (;;) {
3190 uint32_t seq;
3191 bool handled;
3192 status = connection->inputPublisher.receiveFinishedSignal(&seq, &handled);
3193 if (status) {
3194 break;
3195 }
3196 d->finishDispatchCycleLocked(currentTime, connection, seq, handled);
3197 gotOne = true;
3198 }
3199 if (gotOne) {
3200 d->runCommandsLockedInterruptible();
3201 if (status == WOULD_BLOCK) {
3202 return 1;
3203 }
3204 }
3205
3206 notify = status != DEAD_OBJECT || !connection->monitor;
3207 if (notify) {
3208 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003209 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003210 }
3211 } else {
3212 // Monitor channels are never explicitly unregistered.
3213 // We do it automatically when the remote endpoint is closed so don't warn
3214 // about them.
arthurhungd352cb32020-04-28 17:09:28 +08003215 const bool stillHaveWindowHandle =
3216 d->getWindowHandleLocked(connection->inputChannel->getConnectionToken()) !=
3217 nullptr;
3218 notify = !connection->monitor && stillHaveWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003219 if (notify) {
3220 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003221 "events=0x%x",
3222 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003223 }
3224 }
3225
Garfield Tan15601662020-09-22 15:32:38 -07003226 // Remove the channel.
3227 d->removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003228 return 0; // remove the callback
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003229 } // release lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08003230}
3231
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003232void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08003233 const CancelationOptions& options) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +00003234 for (const auto& [fd, connection] : mConnectionsByFd) {
3235 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003236 }
3237}
3238
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003239void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003240 const CancelationOptions& options) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003241 synthesizeCancelationEventsForMonitorsLocked(options, mGlobalMonitorsByDisplay);
3242 synthesizeCancelationEventsForMonitorsLocked(options, mGestureMonitorsByDisplay);
3243}
3244
3245void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
3246 const CancelationOptions& options,
3247 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
3248 for (const auto& it : monitorsByDisplay) {
3249 const std::vector<Monitor>& monitors = it.second;
3250 for (const Monitor& monitor : monitors) {
3251 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003252 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003253 }
3254}
3255
Michael Wrightd02c5b62014-02-10 15:10:22 -08003256void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003257 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07003258 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003259 if (connection == nullptr) {
3260 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003261 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003262
3263 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003264}
3265
3266void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
3267 const sp<Connection>& connection, const CancelationOptions& options) {
3268 if (connection->status == Connection::STATUS_BROKEN) {
3269 return;
3270 }
3271
3272 nsecs_t currentTime = now();
3273
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003274 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07003275 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003276
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003277 if (cancelationEvents.empty()) {
3278 return;
3279 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003280#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003281 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
3282 "with reality: %s, mode=%d.",
3283 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
3284 options.mode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003285#endif
Svet Ganov5d3bc372020-01-26 23:11:07 -08003286
3287 InputTarget target;
3288 sp<InputWindowHandle> windowHandle =
3289 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3290 if (windowHandle != nullptr) {
3291 const InputWindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003292 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003293 target.globalScaleFactor = windowInfo->globalScaleFactor;
3294 }
3295 target.inputChannel = connection->inputChannel;
3296 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3297
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003298 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003299 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003300 switch (cancelationEventEntry->type) {
3301 case EventEntry::Type::KEY: {
3302 logOutboundKeyDetails("cancel - ",
3303 static_cast<const KeyEntry&>(*cancelationEventEntry));
3304 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003305 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003306 case EventEntry::Type::MOTION: {
3307 logOutboundMotionDetails("cancel - ",
3308 static_cast<const MotionEntry&>(*cancelationEventEntry));
3309 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003310 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003311 case EventEntry::Type::FOCUS:
3312 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3313 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Chris Yef59a2f42020-10-16 12:55:26 -07003314 NamedEnum::string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003315 break;
3316 }
3317 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003318 case EventEntry::Type::DEVICE_RESET:
3319 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003320 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Chris Yef59a2f42020-10-16 12:55:26 -07003321 NamedEnum::string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003322 break;
3323 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003324 }
3325
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003326 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), target,
3327 InputTarget::FLAG_DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003328 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003329
3330 startDispatchCycleLocked(currentTime, connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003331}
3332
Svet Ganov5d3bc372020-01-26 23:11:07 -08003333void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
3334 const sp<Connection>& connection) {
3335 if (connection->status == Connection::STATUS_BROKEN) {
3336 return;
3337 }
3338
3339 nsecs_t currentTime = now();
3340
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003341 std::vector<std::unique_ptr<EventEntry>> downEvents =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003342 connection->inputState.synthesizePointerDownEvents(currentTime);
3343
3344 if (downEvents.empty()) {
3345 return;
3346 }
3347
3348#if DEBUG_OUTBOUND_EVENT_DETAILS
3349 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
3350 connection->getInputChannelName().c_str(), downEvents.size());
3351#endif
3352
3353 InputTarget target;
3354 sp<InputWindowHandle> windowHandle =
3355 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3356 if (windowHandle != nullptr) {
3357 const InputWindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003358 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003359 target.globalScaleFactor = windowInfo->globalScaleFactor;
3360 }
3361 target.inputChannel = connection->inputChannel;
3362 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3363
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003364 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003365 switch (downEventEntry->type) {
3366 case EventEntry::Type::MOTION: {
3367 logOutboundMotionDetails("down - ",
3368 static_cast<const MotionEntry&>(*downEventEntry));
3369 break;
3370 }
3371
3372 case EventEntry::Type::KEY:
3373 case EventEntry::Type::FOCUS:
3374 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08003375 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07003376 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3377 case EventEntry::Type::SENSOR: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003378 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Chris Yef59a2f42020-10-16 12:55:26 -07003379 NamedEnum::string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08003380 break;
3381 }
3382 }
3383
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003384 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), target,
3385 InputTarget::FLAG_DISPATCH_AS_IS);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003386 }
3387
3388 startDispatchCycleLocked(currentTime, connection);
3389}
3390
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003391std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
3392 const MotionEntry& originalMotionEntry, BitSet32 pointerIds) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003393 ALOG_ASSERT(pointerIds.value != 0);
3394
3395 uint32_t splitPointerIndexMap[MAX_POINTERS];
3396 PointerProperties splitPointerProperties[MAX_POINTERS];
3397 PointerCoords splitPointerCoords[MAX_POINTERS];
3398
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003399 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003400 uint32_t splitPointerCount = 0;
3401
3402 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003403 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003404 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003405 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003406 uint32_t pointerId = uint32_t(pointerProperties.id);
3407 if (pointerIds.hasBit(pointerId)) {
3408 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
3409 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
3410 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003411 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003412 splitPointerCount += 1;
3413 }
3414 }
3415
3416 if (splitPointerCount != pointerIds.count()) {
3417 // This is bad. We are missing some of the pointers that we expected to deliver.
3418 // Most likely this indicates that we received an ACTION_MOVE events that has
3419 // different pointer ids than we expected based on the previous ACTION_DOWN
3420 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
3421 // in this way.
3422 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003423 "we expected there to be %d pointers. This probably means we received "
3424 "a broken sequence of pointer ids from the input device.",
3425 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07003426 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003427 }
3428
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003429 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003430 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003431 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
3432 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003433 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
3434 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003435 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003436 uint32_t pointerId = uint32_t(pointerProperties.id);
3437 if (pointerIds.hasBit(pointerId)) {
3438 if (pointerIds.count() == 1) {
3439 // The first/last pointer went down/up.
3440 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003441 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08003442 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
3443 ? AMOTION_EVENT_ACTION_CANCEL
3444 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003445 } else {
3446 // A secondary pointer went down/up.
3447 uint32_t splitPointerIndex = 0;
3448 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
3449 splitPointerIndex += 1;
3450 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003451 action = maskedAction |
3452 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003453 }
3454 } else {
3455 // An unrelated pointer changed.
3456 action = AMOTION_EVENT_ACTION_MOVE;
3457 }
3458 }
3459
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003460 int32_t newId = mIdGenerator.nextId();
3461 if (ATRACE_ENABLED()) {
3462 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
3463 ") to MotionEvent(id=0x%" PRIx32 ").",
3464 originalMotionEntry.id, newId);
3465 ATRACE_NAME(message.c_str());
3466 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003467 std::unique_ptr<MotionEntry> splitMotionEntry =
3468 std::make_unique<MotionEntry>(newId, originalMotionEntry.eventTime,
3469 originalMotionEntry.deviceId, originalMotionEntry.source,
3470 originalMotionEntry.displayId,
3471 originalMotionEntry.policyFlags, action,
3472 originalMotionEntry.actionButton,
3473 originalMotionEntry.flags, originalMotionEntry.metaState,
3474 originalMotionEntry.buttonState,
3475 originalMotionEntry.classification,
3476 originalMotionEntry.edgeFlags,
3477 originalMotionEntry.xPrecision,
3478 originalMotionEntry.yPrecision,
3479 originalMotionEntry.xCursorPosition,
3480 originalMotionEntry.yCursorPosition,
3481 originalMotionEntry.downTime, splitPointerCount,
3482 splitPointerProperties, splitPointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003483
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003484 if (originalMotionEntry.injectionState) {
3485 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003486 splitMotionEntry->injectionState->refCount += 1;
3487 }
3488
3489 return splitMotionEntry;
3490}
3491
3492void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
3493#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003494 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003495#endif
3496
3497 bool needWake;
3498 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003499 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003500
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003501 std::unique_ptr<ConfigurationChangedEntry> newEntry =
3502 std::make_unique<ConfigurationChangedEntry>(args->id, args->eventTime);
3503 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003504 } // release lock
3505
3506 if (needWake) {
3507 mLooper->wake();
3508 }
3509}
3510
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003511/**
3512 * If one of the meta shortcuts is detected, process them here:
3513 * Meta + Backspace -> generate BACK
3514 * Meta + Enter -> generate HOME
3515 * This will potentially overwrite keyCode and metaState.
3516 */
3517void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003518 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003519 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
3520 int32_t newKeyCode = AKEYCODE_UNKNOWN;
3521 if (keyCode == AKEYCODE_DEL) {
3522 newKeyCode = AKEYCODE_BACK;
3523 } else if (keyCode == AKEYCODE_ENTER) {
3524 newKeyCode = AKEYCODE_HOME;
3525 }
3526 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003527 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003528 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003529 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003530 keyCode = newKeyCode;
3531 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3532 }
3533 } else if (action == AKEY_EVENT_ACTION_UP) {
3534 // In order to maintain a consistent stream of up and down events, check to see if the key
3535 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
3536 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003537 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003538 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003539 auto replacementIt = mReplacedKeys.find(replacement);
3540 if (replacementIt != mReplacedKeys.end()) {
3541 keyCode = replacementIt->second;
3542 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003543 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3544 }
3545 }
3546}
3547
Michael Wrightd02c5b62014-02-10 15:10:22 -08003548void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
3549#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003550 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
3551 "policyFlags=0x%x, action=0x%x, "
3552 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
3553 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
3554 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
3555 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003556#endif
3557 if (!validateKeyEvent(args->action)) {
3558 return;
3559 }
3560
3561 uint32_t policyFlags = args->policyFlags;
3562 int32_t flags = args->flags;
3563 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07003564 // InputDispatcher tracks and generates key repeats on behalf of
3565 // whatever notifies it, so repeatCount should always be set to 0
3566 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003567 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
3568 policyFlags |= POLICY_FLAG_VIRTUAL;
3569 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
3570 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003571 if (policyFlags & POLICY_FLAG_FUNCTION) {
3572 metaState |= AMETA_FUNCTION_ON;
3573 }
3574
3575 policyFlags |= POLICY_FLAG_TRUSTED;
3576
Michael Wright78f24442014-08-06 15:55:28 -07003577 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003578 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07003579
Michael Wrightd02c5b62014-02-10 15:10:22 -08003580 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003581 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08003582 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
3583 args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003584
Michael Wright2b3c3302018-03-02 17:19:13 +00003585 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003586 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003587 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3588 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003589 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003590 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003591
Michael Wrightd02c5b62014-02-10 15:10:22 -08003592 bool needWake;
3593 { // acquire lock
3594 mLock.lock();
3595
3596 if (shouldSendKeyToInputFilterLocked(args)) {
3597 mLock.unlock();
3598
3599 policyFlags |= POLICY_FLAG_FILTERED;
3600 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3601 return; // event was consumed by the filter
3602 }
3603
3604 mLock.lock();
3605 }
3606
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003607 std::unique_ptr<KeyEntry> newEntry =
3608 std::make_unique<KeyEntry>(args->id, args->eventTime, args->deviceId, args->source,
3609 args->displayId, policyFlags, args->action, flags,
3610 keyCode, args->scanCode, metaState, repeatCount,
3611 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003612
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003613 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003614 mLock.unlock();
3615 } // release lock
3616
3617 if (needWake) {
3618 mLooper->wake();
3619 }
3620}
3621
3622bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
3623 return mInputFilterEnabled;
3624}
3625
3626void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
3627#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003628 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3629 "displayId=%" PRId32 ", policyFlags=0x%x, "
Garfield Tan00f511d2019-06-12 16:55:40 -07003630 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
3631 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
Garfield Tanab0ab9c2019-07-10 18:58:28 -07003632 "yCursorPosition=%f, downTime=%" PRId64,
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003633 args->id, args->eventTime, args->deviceId, args->source, args->displayId,
3634 args->policyFlags, args->action, args->actionButton, args->flags, args->metaState,
3635 args->buttonState, args->edgeFlags, args->xPrecision, args->yPrecision,
3636 args->xCursorPosition, args->yCursorPosition, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003637 for (uint32_t i = 0; i < args->pointerCount; i++) {
3638 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003639 "x=%f, y=%f, pressure=%f, size=%f, "
3640 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
3641 "orientation=%f",
3642 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
3643 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
3644 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
3645 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3646 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
3647 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3648 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3649 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3650 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3651 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003652 }
3653#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003654 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
3655 args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003656 return;
3657 }
3658
3659 uint32_t policyFlags = args->policyFlags;
3660 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003661
3662 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08003663 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003664 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3665 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003666 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003667 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003668
3669 bool needWake;
3670 { // acquire lock
3671 mLock.lock();
3672
3673 if (shouldSendMotionToInputFilterLocked(args)) {
3674 mLock.unlock();
3675
3676 MotionEvent event;
chaviw9eaa22c2020-07-01 16:21:27 -07003677 ui::Transform transform;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003678 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
3679 args->action, args->actionButton, args->flags, args->edgeFlags,
chaviw9eaa22c2020-07-01 16:21:27 -07003680 args->metaState, args->buttonState, args->classification, transform,
3681 args->xPrecision, args->yPrecision, args->xCursorPosition,
3682 args->yCursorPosition, args->downTime, args->eventTime,
3683 args->pointerCount, args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003684
3685 policyFlags |= POLICY_FLAG_FILTERED;
3686 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3687 return; // event was consumed by the filter
3688 }
3689
3690 mLock.lock();
3691 }
3692
3693 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003694 std::unique_ptr<MotionEntry> newEntry =
3695 std::make_unique<MotionEntry>(args->id, args->eventTime, args->deviceId,
3696 args->source, args->displayId, policyFlags,
3697 args->action, args->actionButton, args->flags,
3698 args->metaState, args->buttonState,
3699 args->classification, args->edgeFlags,
3700 args->xPrecision, args->yPrecision,
3701 args->xCursorPosition, args->yCursorPosition,
3702 args->downTime, args->pointerCount,
3703 args->pointerProperties, args->pointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003704
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003705 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003706 mLock.unlock();
3707 } // release lock
3708
3709 if (needWake) {
3710 mLooper->wake();
3711 }
3712}
3713
Chris Yef59a2f42020-10-16 12:55:26 -07003714void InputDispatcher::notifySensor(const NotifySensorArgs* args) {
3715#if DEBUG_INBOUND_EVENT_DETAILS
3716 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3717 " sensorType=%s",
3718 args->id, args->eventTime, args->deviceId, args->source,
3719 NamedEnum::string(args->sensorType).c_str());
3720#endif
3721
3722 bool needWake;
3723 { // acquire lock
3724 mLock.lock();
3725
3726 // Just enqueue a new sensor event.
3727 std::unique_ptr<SensorEntry> newEntry =
3728 std::make_unique<SensorEntry>(args->id, args->eventTime, args->deviceId,
3729 args->source, 0 /* policyFlags*/, args->hwTimestamp,
3730 args->sensorType, args->accuracy,
3731 args->accuracyChanged, args->values);
3732
3733 needWake = enqueueInboundEventLocked(std::move(newEntry));
3734 mLock.unlock();
3735 } // release lock
3736
3737 if (needWake) {
3738 mLooper->wake();
3739 }
3740}
3741
Michael Wrightd02c5b62014-02-10 15:10:22 -08003742bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08003743 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003744}
3745
3746void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
3747#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003748 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003749 "switchMask=0x%08x",
3750 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003751#endif
3752
3753 uint32_t policyFlags = args->policyFlags;
3754 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003755 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003756}
3757
3758void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
3759#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003760 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
3761 args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003762#endif
3763
3764 bool needWake;
3765 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003766 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003767
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003768 std::unique_ptr<DeviceResetEntry> newEntry =
3769 std::make_unique<DeviceResetEntry>(args->id, args->eventTime, args->deviceId);
3770 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003771 } // release lock
3772
3773 if (needWake) {
3774 mLooper->wake();
3775 }
3776}
3777
Prabir Pradhan7e186182020-11-10 13:56:45 -08003778void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs* args) {
3779#if DEBUG_INBOUND_EVENT_DETAILS
3780 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args->eventTime,
3781 args->enabled ? "true" : "false");
3782#endif
3783
Prabir Pradhan99987712020-11-10 18:43:05 -08003784 bool needWake;
3785 { // acquire lock
3786 std::scoped_lock _l(mLock);
3787 auto entry = std::make_unique<PointerCaptureChangedEntry>(args->id, args->eventTime,
3788 args->enabled);
3789 needWake = enqueueInboundEventLocked(std::move(entry));
3790 } // release lock
3791
3792 if (needWake) {
3793 mLooper->wake();
3794 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08003795}
3796
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003797InputEventInjectionResult InputDispatcher::injectInputEvent(
3798 const InputEvent* event, int32_t injectorPid, int32_t injectorUid,
3799 InputEventInjectionSync syncMode, std::chrono::milliseconds timeout, uint32_t policyFlags) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003800#if DEBUG_INBOUND_EVENT_DETAILS
3801 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003802 "syncMode=%d, timeout=%lld, policyFlags=0x%08x",
3803 event->getType(), injectorPid, injectorUid, syncMode, timeout.count(), policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003804#endif
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003805 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003806
3807 policyFlags |= POLICY_FLAG_INJECTED;
3808 if (hasInjectionPermission(injectorPid, injectorUid)) {
3809 policyFlags |= POLICY_FLAG_TRUSTED;
3810 }
3811
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003812 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003813 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003814 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003815 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
3816 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003817 if (!validateKeyEvent(action)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003818 return InputEventInjectionResult::FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003819 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003820
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003821 int32_t flags = incomingKey.getFlags();
3822 int32_t keyCode = incomingKey.getKeyCode();
3823 int32_t metaState = incomingKey.getMetaState();
3824 accelerateMetaShortcuts(VIRTUAL_KEYBOARD_ID, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003825 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003826 KeyEvent keyEvent;
Garfield Tan4cc839f2020-01-24 11:26:14 -08003827 keyEvent.initialize(incomingKey.getId(), VIRTUAL_KEYBOARD_ID, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003828 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
3829 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
3830 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003831
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003832 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
3833 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00003834 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003835
3836 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3837 android::base::Timer t;
3838 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
3839 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3840 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
3841 std::to_string(t.duration().count()).c_str());
3842 }
3843 }
3844
3845 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003846 std::unique_ptr<KeyEntry> injectedEntry =
3847 std::make_unique<KeyEntry>(incomingKey.getId(), incomingKey.getEventTime(),
3848 VIRTUAL_KEYBOARD_ID, incomingKey.getSource(),
3849 incomingKey.getDisplayId(), policyFlags, action,
3850 flags, keyCode, incomingKey.getScanCode(), metaState,
3851 incomingKey.getRepeatCount(),
3852 incomingKey.getDownTime());
3853 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003854 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003855 }
3856
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003857 case AINPUT_EVENT_TYPE_MOTION: {
3858 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
3859 int32_t action = motionEvent->getAction();
3860 size_t pointerCount = motionEvent->getPointerCount();
3861 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
3862 int32_t actionButton = motionEvent->getActionButton();
3863 int32_t displayId = motionEvent->getDisplayId();
3864 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003865 return InputEventInjectionResult::FAILED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003866 }
3867
3868 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3869 nsecs_t eventTime = motionEvent->getEventTime();
3870 android::base::Timer t;
3871 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
3872 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3873 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
3874 std::to_string(t.duration().count()).c_str());
3875 }
3876 }
3877
3878 mLock.lock();
3879 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
3880 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003881 std::unique_ptr<MotionEntry> injectedEntry =
3882 std::make_unique<MotionEntry>(motionEvent->getId(), *sampleEventTimes,
3883 VIRTUAL_KEYBOARD_ID, motionEvent->getSource(),
3884 motionEvent->getDisplayId(), policyFlags, action,
3885 actionButton, motionEvent->getFlags(),
3886 motionEvent->getMetaState(),
3887 motionEvent->getButtonState(),
3888 motionEvent->getClassification(),
3889 motionEvent->getEdgeFlags(),
3890 motionEvent->getXPrecision(),
3891 motionEvent->getYPrecision(),
3892 motionEvent->getRawXCursorPosition(),
3893 motionEvent->getRawYCursorPosition(),
3894 motionEvent->getDownTime(),
3895 uint32_t(pointerCount), pointerProperties,
3896 samplePointerCoords, motionEvent->getXOffset(),
3897 motionEvent->getYOffset());
3898 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003899 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
3900 sampleEventTimes += 1;
3901 samplePointerCoords += pointerCount;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003902 std::unique_ptr<MotionEntry> nextInjectedEntry =
3903 std::make_unique<MotionEntry>(motionEvent->getId(), *sampleEventTimes,
3904 VIRTUAL_KEYBOARD_ID, motionEvent->getSource(),
3905 motionEvent->getDisplayId(), policyFlags,
3906 action, actionButton, motionEvent->getFlags(),
3907 motionEvent->getMetaState(),
3908 motionEvent->getButtonState(),
3909 motionEvent->getClassification(),
3910 motionEvent->getEdgeFlags(),
3911 motionEvent->getXPrecision(),
3912 motionEvent->getYPrecision(),
3913 motionEvent->getRawXCursorPosition(),
3914 motionEvent->getRawYCursorPosition(),
3915 motionEvent->getDownTime(),
3916 uint32_t(pointerCount), pointerProperties,
3917 samplePointerCoords,
3918 motionEvent->getXOffset(),
3919 motionEvent->getYOffset());
3920 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003921 }
3922 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003923 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003924
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003925 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08003926 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003927 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003928 }
3929
3930 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003931 if (syncMode == InputEventInjectionSync::NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003932 injectionState->injectionIsAsync = true;
3933 }
3934
3935 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003936 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003937
3938 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003939 while (!injectedEntries.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003940 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003941 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003942 }
3943
3944 mLock.unlock();
3945
3946 if (needWake) {
3947 mLooper->wake();
3948 }
3949
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003950 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003951 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003952 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003953
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003954 if (syncMode == InputEventInjectionSync::NONE) {
3955 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003956 } else {
3957 for (;;) {
3958 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003959 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003960 break;
3961 }
3962
3963 nsecs_t remainingTimeout = endTime - now();
3964 if (remainingTimeout <= 0) {
3965#if DEBUG_INJECTION
3966 ALOGD("injectInputEvent - Timed out waiting for injection result "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003967 "to become available.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003968#endif
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003969 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003970 break;
3971 }
3972
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003973 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003974 }
3975
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003976 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
3977 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003978 while (injectionState->pendingForegroundDispatches != 0) {
3979#if DEBUG_INJECTION
3980 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003981 injectionState->pendingForegroundDispatches);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003982#endif
3983 nsecs_t remainingTimeout = endTime - now();
3984 if (remainingTimeout <= 0) {
3985#if DEBUG_INJECTION
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003986 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
3987 "dispatches to finish.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003988#endif
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003989 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003990 break;
3991 }
3992
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003993 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003994 }
3995 }
3996 }
3997
3998 injectionState->release();
3999 } // release lock
4000
4001#if DEBUG_INJECTION
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004002 ALOGD("injectInputEvent - Finished with result %d. injectorPid=%d, injectorUid=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004003 injectionResult, injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004004#endif
4005
4006 return injectionResult;
4007}
4008
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004009std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004010 std::array<uint8_t, 32> calculatedHmac;
4011 std::unique_ptr<VerifiedInputEvent> result;
4012 switch (event.getType()) {
4013 case AINPUT_EVENT_TYPE_KEY: {
4014 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4015 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4016 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004017 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004018 break;
4019 }
4020 case AINPUT_EVENT_TYPE_MOTION: {
4021 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4022 VerifiedMotionEvent verifiedMotionEvent =
4023 verifiedMotionEventFromMotionEvent(motionEvent);
4024 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004025 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004026 break;
4027 }
4028 default: {
4029 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4030 return nullptr;
4031 }
4032 }
4033 if (calculatedHmac == INVALID_HMAC) {
4034 return nullptr;
4035 }
4036 if (calculatedHmac != event.getHmac()) {
4037 return nullptr;
4038 }
4039 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004040}
4041
Michael Wrightd02c5b62014-02-10 15:10:22 -08004042bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004043 return injectorUid == 0 ||
4044 mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004045}
4046
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004047void InputDispatcher::setInjectionResult(EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004048 InputEventInjectionResult injectionResult) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004049 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004050 if (injectionState) {
4051#if DEBUG_INJECTION
4052 ALOGD("Setting input event injection result to %d. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004053 "injectorPid=%d, injectorUid=%d",
4054 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004055#endif
4056
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004057 if (injectionState->injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004058 // Log the outcome since the injector did not wait for the injection result.
4059 switch (injectionResult) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004060 case InputEventInjectionResult::SUCCEEDED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004061 ALOGV("Asynchronous input event injection succeeded.");
4062 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004063 case InputEventInjectionResult::FAILED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004064 ALOGW("Asynchronous input event injection failed.");
4065 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004066 case InputEventInjectionResult::PERMISSION_DENIED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004067 ALOGW("Asynchronous input event injection permission denied.");
4068 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004069 case InputEventInjectionResult::TIMED_OUT:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004070 ALOGW("Asynchronous input event injection timed out.");
4071 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004072 case InputEventInjectionResult::PENDING:
4073 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4074 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004075 }
4076 }
4077
4078 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004079 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004080 }
4081}
4082
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004083void InputDispatcher::incrementPendingForegroundDispatches(EventEntry& entry) {
4084 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004085 if (injectionState) {
4086 injectionState->pendingForegroundDispatches += 1;
4087 }
4088}
4089
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004090void InputDispatcher::decrementPendingForegroundDispatches(EventEntry& entry) {
4091 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004092 if (injectionState) {
4093 injectionState->pendingForegroundDispatches -= 1;
4094
4095 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004096 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004097 }
4098 }
4099}
4100
Vishnu Nairad321cd2020-08-20 16:40:21 -07004101const std::vector<sp<InputWindowHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004102 int32_t displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004103 static const std::vector<sp<InputWindowHandle>> EMPTY_WINDOW_HANDLES;
4104 auto it = mWindowHandlesByDisplay.find(displayId);
4105 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08004106}
4107
Michael Wrightd02c5b62014-02-10 15:10:22 -08004108sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08004109 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08004110 if (windowHandleToken == nullptr) {
4111 return nullptr;
4112 }
4113
Arthur Hungb92218b2018-08-14 12:00:21 +08004114 for (auto& it : mWindowHandlesByDisplay) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004115 const std::vector<sp<InputWindowHandle>>& windowHandles = it.second;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004116 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004117 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004118 return windowHandle;
4119 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004120 }
4121 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004122 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004123}
4124
Vishnu Nairad321cd2020-08-20 16:40:21 -07004125sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
4126 int displayId) const {
4127 if (windowHandleToken == nullptr) {
4128 return nullptr;
4129 }
4130
4131 for (const sp<InputWindowHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
4132 if (windowHandle->getToken() == windowHandleToken) {
4133 return windowHandle;
4134 }
4135 }
4136 return nullptr;
4137}
4138
4139sp<InputWindowHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
Vishnu Nairc519ff72021-01-21 08:23:08 -08004140 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07004141 return getWindowHandleLocked(focusedToken, displayId);
4142}
4143
Mady Mellor017bcd12020-06-23 19:12:00 +00004144bool InputDispatcher::hasWindowHandleLocked(const sp<InputWindowHandle>& windowHandle) const {
4145 for (auto& it : mWindowHandlesByDisplay) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004146 const std::vector<sp<InputWindowHandle>>& windowHandles = it.second;
Mady Mellor017bcd12020-06-23 19:12:00 +00004147 for (const sp<InputWindowHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08004148 if (handle->getId() == windowHandle->getId() &&
4149 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004150 if (windowHandle->getInfo()->displayId != it.first) {
4151 ALOGE("Found window %s in display %" PRId32
4152 ", but it should belong to display %" PRId32,
4153 windowHandle->getName().c_str(), it.first,
4154 windowHandle->getInfo()->displayId);
4155 }
4156 return true;
Arthur Hungb92218b2018-08-14 12:00:21 +08004157 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004158 }
4159 }
4160 return false;
4161}
4162
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004163bool InputDispatcher::hasResponsiveConnectionLocked(InputWindowHandle& windowHandle) const {
4164 sp<Connection> connection = getConnectionLocked(windowHandle.getToken());
4165 const bool noInputChannel =
4166 windowHandle.getInfo()->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
4167 if (connection != nullptr && noInputChannel) {
4168 ALOGW("%s has feature NO_INPUT_CHANNEL, but it matched to connection %s",
4169 windowHandle.getName().c_str(), connection->inputChannel->getName().c_str());
4170 return false;
4171 }
4172
4173 if (connection == nullptr) {
4174 if (!noInputChannel) {
4175 ALOGI("Could not find connection for %s", windowHandle.getName().c_str());
4176 }
4177 return false;
4178 }
4179 if (!connection->responsive) {
4180 ALOGW("Window %s is not responsive", windowHandle.getName().c_str());
4181 return false;
4182 }
4183 return true;
4184}
4185
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004186std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
4187 const sp<IBinder>& token) const {
Robert Carr5c8a0262018-10-03 16:30:44 -07004188 size_t count = mInputChannelsByToken.count(token);
4189 if (count == 0) {
4190 return nullptr;
4191 }
4192 return mInputChannelsByToken.at(token);
4193}
4194
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004195void InputDispatcher::updateWindowHandlesForDisplayLocked(
4196 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
4197 if (inputWindowHandles.empty()) {
4198 // Remove all handles on a display if there are no windows left.
4199 mWindowHandlesByDisplay.erase(displayId);
4200 return;
4201 }
4202
4203 // Since we compare the pointer of input window handles across window updates, we need
4204 // to make sure the handle object for the same window stays unchanged across updates.
4205 const std::vector<sp<InputWindowHandle>>& oldHandles = getWindowHandlesLocked(displayId);
chaviwaf87b3e2019-10-01 16:59:28 -07004206 std::unordered_map<int32_t /*id*/, sp<InputWindowHandle>> oldHandlesById;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004207 for (const sp<InputWindowHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07004208 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004209 }
4210
4211 std::vector<sp<InputWindowHandle>> newHandles;
4212 for (const sp<InputWindowHandle>& handle : inputWindowHandles) {
4213 if (!handle->updateInfo()) {
4214 // handle no longer valid
4215 continue;
4216 }
4217
4218 const InputWindowInfo* info = handle->getInfo();
4219 if ((getInputChannelLocked(handle->getToken()) == nullptr &&
4220 info->portalToDisplayId == ADISPLAY_ID_NONE)) {
4221 const bool noInputChannel =
Michael Wright44753b12020-07-08 13:48:11 +01004222 info->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
4223 const bool canReceiveInput = !info->flags.test(InputWindowInfo::Flag::NOT_TOUCHABLE) ||
4224 !info->flags.test(InputWindowInfo::Flag::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004225 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07004226 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004227 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07004228 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004229 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004230 }
4231
4232 if (info->displayId != displayId) {
4233 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
4234 handle->getName().c_str(), displayId, info->displayId);
4235 continue;
4236 }
4237
Robert Carredd13602020-04-13 17:24:34 -07004238 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
4239 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviwaf87b3e2019-10-01 16:59:28 -07004240 const sp<InputWindowHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004241 oldHandle->updateFrom(handle);
4242 newHandles.push_back(oldHandle);
4243 } else {
4244 newHandles.push_back(handle);
4245 }
4246 }
4247
4248 // Insert or replace
4249 mWindowHandlesByDisplay[displayId] = newHandles;
4250}
4251
Arthur Hung72d8dc32020-03-28 00:48:39 +00004252void InputDispatcher::setInputWindows(
4253 const std::unordered_map<int32_t, std::vector<sp<InputWindowHandle>>>& handlesPerDisplay) {
4254 { // acquire lock
4255 std::scoped_lock _l(mLock);
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004256 for (const auto& [displayId, handles] : handlesPerDisplay) {
4257 setInputWindowsLocked(handles, displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004258 }
4259 }
4260 // Wake up poll loop since it may need to make new input dispatching choices.
4261 mLooper->wake();
4262}
4263
Arthur Hungb92218b2018-08-14 12:00:21 +08004264/**
4265 * Called from InputManagerService, update window handle list by displayId that can receive input.
4266 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
4267 * If set an empty list, remove all handles from the specific display.
4268 * For focused handle, check if need to change and send a cancel event to previous one.
4269 * For removed handle, check if need to send a cancel event if already in touch.
4270 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00004271void InputDispatcher::setInputWindowsLocked(
4272 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004273 if (DEBUG_FOCUS) {
4274 std::string windowList;
4275 for (const sp<InputWindowHandle>& iwh : inputWindowHandles) {
4276 windowList += iwh->getName() + " ";
4277 }
4278 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
4279 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004280
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004281 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
4282 for (const sp<InputWindowHandle>& window : inputWindowHandles) {
4283 const bool noInputWindow =
4284 window->getInfo()->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
4285 if (noInputWindow && window->getToken() != nullptr) {
4286 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
4287 window->getName().c_str());
4288 window->releaseChannel();
4289 }
4290 }
4291
Arthur Hung72d8dc32020-03-28 00:48:39 +00004292 // Copy old handles for release if they are no longer present.
4293 const std::vector<sp<InputWindowHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004294
Arthur Hung72d8dc32020-03-28 00:48:39 +00004295 updateWindowHandlesForDisplayLocked(inputWindowHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004296
Vishnu Nair958da932020-08-21 17:12:37 -07004297 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
4298 if (mLastHoverWindowHandle &&
4299 std::find(windowHandles.begin(), windowHandles.end(), mLastHoverWindowHandle) ==
4300 windowHandles.end()) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004301 mLastHoverWindowHandle = nullptr;
4302 }
4303
Vishnu Nairc519ff72021-01-21 08:23:08 -08004304 std::optional<FocusResolver::FocusChanges> changes =
4305 mFocusResolver.setInputWindows(displayId, windowHandles);
4306 if (changes) {
4307 onFocusChangedLocked(*changes);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004308 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004309
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004310 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4311 mTouchStatesByDisplay.find(displayId);
4312 if (stateIt != mTouchStatesByDisplay.end()) {
4313 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00004314 for (size_t i = 0; i < state.windows.size();) {
4315 TouchedWindow& touchedWindow = state.windows[i];
Mady Mellor017bcd12020-06-23 19:12:00 +00004316 if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004317 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004318 ALOGD("Touched window was removed: %s in display %" PRId32,
4319 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004320 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004321 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00004322 getInputChannelLocked(touchedWindow.windowHandle->getToken());
4323 if (touchedInputChannel != nullptr) {
4324 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4325 "touched window was removed");
4326 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004327 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004328 state.windows.erase(state.windows.begin() + i);
4329 } else {
4330 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004331 }
4332 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004333 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004334
Arthur Hung72d8dc32020-03-28 00:48:39 +00004335 // Release information for windows that are no longer present.
4336 // This ensures that unused input channels are released promptly.
4337 // Otherwise, they might stick around until the window handle is destroyed
4338 // which might not happen until the next GC.
4339 for (const sp<InputWindowHandle>& oldWindowHandle : oldWindowHandles) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004340 if (!hasWindowHandleLocked(oldWindowHandle)) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004341 if (DEBUG_FOCUS) {
4342 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00004343 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004344 oldWindowHandle->releaseChannel();
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004345 // To avoid making too many calls into the compat framework, only
4346 // check for window flags when windows are going away.
4347 // TODO(b/157929241) : delete this. This is only needed temporarily
4348 // in order to gather some data about the flag usage
4349 if (oldWindowHandle->getInfo()->flags.test(InputWindowInfo::Flag::SLIPPERY)) {
4350 ALOGW("%s has FLAG_SLIPPERY. Please report this in b/157929241",
4351 oldWindowHandle->getName().c_str());
4352 if (mCompatService != nullptr) {
4353 mCompatService->reportChangeByUid(IInputConstants::BLOCK_FLAG_SLIPPERY,
4354 oldWindowHandle->getInfo()->ownerUid);
4355 }
4356 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004357 }
chaviw291d88a2019-02-14 10:33:58 -08004358 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004359}
4360
4361void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07004362 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004363 if (DEBUG_FOCUS) {
4364 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
4365 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
4366 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004367 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004368 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004369
Chris Yea209fde2020-07-22 13:54:51 -07004370 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08004371 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004372
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004373 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
4374 return; // This application is already focused. No need to wake up or change anything.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004375 }
4376
Chris Yea209fde2020-07-22 13:54:51 -07004377 // Set the new application handle.
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004378 if (inputApplicationHandle != nullptr) {
4379 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
4380 } else {
4381 mFocusedApplicationHandlesByDisplay.erase(displayId);
4382 }
4383
4384 // No matter what the old focused application was, stop waiting on it because it is
4385 // no longer focused.
4386 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004387 } // release lock
4388
4389 // Wake up poll loop since it may need to make new input dispatching choices.
4390 mLooper->wake();
4391}
4392
Tiger Huang721e26f2018-07-24 22:26:19 +08004393/**
4394 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
4395 * the display not specified.
4396 *
4397 * We track any unreleased events for each window. If a window loses the ability to receive the
4398 * released event, we will send a cancel event to it. So when the focused display is changed, we
4399 * cancel all the unreleased display-unspecified events for the focused window on the old focused
4400 * display. The display-specified events won't be affected.
4401 */
4402void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004403 if (DEBUG_FOCUS) {
4404 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
4405 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004406 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004407 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08004408
4409 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004410 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08004411 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07004412 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004413 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07004414 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08004415 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004416 CancelationOptions
4417 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
4418 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004419 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08004420 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
4421 }
4422 }
4423 mFocusedDisplayId = displayId;
4424
Chris Ye3c2d6f52020-08-09 10:39:48 -07004425 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08004426 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07004427 notifyFocusChangedLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08004428
Vishnu Nairad321cd2020-08-20 16:40:21 -07004429 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08004430 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08004431 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004432 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08004433 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08004434 }
4435 }
4436 }
4437
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004438 if (DEBUG_FOCUS) {
4439 logDispatchStateLocked();
4440 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004441 } // release lock
4442
4443 // Wake up poll loop since it may need to make new input dispatching choices.
4444 mLooper->wake();
4445}
4446
Michael Wrightd02c5b62014-02-10 15:10:22 -08004447void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004448 if (DEBUG_FOCUS) {
4449 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
4450 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004451
4452 bool changed;
4453 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004454 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004455
4456 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
4457 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004458 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004459 }
4460
4461 if (mDispatchEnabled && !enabled) {
4462 resetAndDropEverythingLocked("dispatcher is being disabled");
4463 }
4464
4465 mDispatchEnabled = enabled;
4466 mDispatchFrozen = frozen;
4467 changed = true;
4468 } else {
4469 changed = false;
4470 }
4471
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004472 if (DEBUG_FOCUS) {
4473 logDispatchStateLocked();
4474 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004475 } // release lock
4476
4477 if (changed) {
4478 // Wake up poll loop since it may need to make new input dispatching choices.
4479 mLooper->wake();
4480 }
4481}
4482
4483void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004484 if (DEBUG_FOCUS) {
4485 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
4486 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004487
4488 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004489 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004490
4491 if (mInputFilterEnabled == enabled) {
4492 return;
4493 }
4494
4495 mInputFilterEnabled = enabled;
4496 resetAndDropEverythingLocked("input filter is being enabled or disabled");
4497 } // release lock
4498
4499 // Wake up poll loop since there might be work to do to drop everything.
4500 mLooper->wake();
4501}
4502
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08004503void InputDispatcher::setInTouchMode(bool inTouchMode) {
4504 std::scoped_lock lock(mLock);
4505 mInTouchMode = inTouchMode;
4506}
4507
Bernardo Rufinoea97d182020-08-19 14:43:14 +01004508void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
4509 if (opacity < 0 || opacity > 1) {
4510 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
4511 return;
4512 }
4513
4514 std::scoped_lock lock(mLock);
4515 mMaximumObscuringOpacityForTouch = opacity;
4516}
4517
4518void InputDispatcher::setBlockUntrustedTouchesMode(BlockUntrustedTouchesMode mode) {
4519 std::scoped_lock lock(mLock);
4520 mBlockUntrustedTouchesMode = mode;
4521}
4522
chaviwfbe5d9c2018-12-26 12:23:37 -08004523bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken) {
4524 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004525 if (DEBUG_FOCUS) {
4526 ALOGD("Trivial transfer to same window.");
4527 }
chaviwfbe5d9c2018-12-26 12:23:37 -08004528 return true;
4529 }
4530
Michael Wrightd02c5b62014-02-10 15:10:22 -08004531 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004532 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004533
chaviwfbe5d9c2018-12-26 12:23:37 -08004534 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromToken);
4535 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toToken);
Yi Kong9b14ac62018-07-17 13:48:38 -07004536 if (fromWindowHandle == nullptr || toWindowHandle == nullptr) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004537 ALOGW("Cannot transfer focus because from or to window not found.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004538 return false;
4539 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004540 if (DEBUG_FOCUS) {
4541 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
4542 fromWindowHandle->getName().c_str(), toWindowHandle->getName().c_str());
4543 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004544 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004545 if (DEBUG_FOCUS) {
4546 ALOGD("Cannot transfer focus because windows are on different displays.");
4547 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004548 return false;
4549 }
4550
4551 bool found = false;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004552 for (std::pair<const int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4553 TouchState& state = pair.second;
Jeff Brownf086ddb2014-02-11 14:28:48 -08004554 for (size_t i = 0; i < state.windows.size(); i++) {
4555 const TouchedWindow& touchedWindow = state.windows[i];
4556 if (touchedWindow.windowHandle == fromWindowHandle) {
4557 int32_t oldTargetFlags = touchedWindow.targetFlags;
4558 BitSet32 pointerIds = touchedWindow.pointerIds;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004559
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004560 state.windows.erase(state.windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004561
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004562 int32_t newTargetFlags = oldTargetFlags &
4563 (InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_SPLIT |
4564 InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004565 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004566
Jeff Brownf086ddb2014-02-11 14:28:48 -08004567 found = true;
4568 goto Found;
4569 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004570 }
4571 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004572 Found:
Michael Wrightd02c5b62014-02-10 15:10:22 -08004573
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004574 if (!found) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004575 if (DEBUG_FOCUS) {
4576 ALOGD("Focus transfer failed because from window did not have focus.");
4577 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004578 return false;
4579 }
4580
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004581 sp<Connection> fromConnection = getConnectionLocked(fromToken);
4582 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004583 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004584 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004585 CancelationOptions
4586 options(CancelationOptions::CANCEL_POINTER_EVENTS,
4587 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004588 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004589 synthesizePointerDownEventsForConnectionLocked(toConnection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004590 }
4591
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004592 if (DEBUG_FOCUS) {
4593 logDispatchStateLocked();
4594 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004595 } // release lock
4596
4597 // Wake up poll loop since it may need to make new input dispatching choices.
4598 mLooper->wake();
4599 return true;
4600}
4601
4602void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004603 if (DEBUG_FOCUS) {
4604 ALOGD("Resetting and dropping all events (%s).", reason);
4605 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004606
4607 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
4608 synthesizeCancelationEventsForAllConnectionsLocked(options);
4609
4610 resetKeyRepeatLocked();
4611 releasePendingEventLocked();
4612 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004613 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004614
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004615 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08004616 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004617 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07004618 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004619}
4620
4621void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004622 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004623 dumpDispatchStateLocked(dump);
4624
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004625 std::istringstream stream(dump);
4626 std::string line;
4627
4628 while (std::getline(stream, line, '\n')) {
4629 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004630 }
4631}
4632
Prabir Pradhan99987712020-11-10 18:43:05 -08004633std::string InputDispatcher::dumpPointerCaptureStateLocked() {
4634 std::string dump;
4635
4636 dump += StringPrintf(INDENT "FocusedWindowRequestedPointerCapture: %s\n",
4637 toString(mFocusedWindowRequestedPointerCapture));
4638
4639 std::string windowName = "None";
4640 if (mWindowTokenWithPointerCapture) {
4641 const sp<InputWindowHandle> captureWindowHandle =
4642 getWindowHandleLocked(mWindowTokenWithPointerCapture);
4643 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
4644 : "token has capture without window";
4645 }
4646 dump += StringPrintf(INDENT "CurrentWindowWithPointerCapture: %s\n", windowName.c_str());
4647
4648 return dump;
4649}
4650
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004651void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07004652 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
4653 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
4654 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08004655 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004656
Tiger Huang721e26f2018-07-24 22:26:19 +08004657 if (!mFocusedApplicationHandlesByDisplay.empty()) {
4658 dump += StringPrintf(INDENT "FocusedApplications:\n");
4659 for (auto& it : mFocusedApplicationHandlesByDisplay) {
4660 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07004661 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05004662 const std::chrono::duration timeout =
4663 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004664 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004665 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05004666 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08004667 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004668 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08004669 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004670 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004671
Vishnu Nairc519ff72021-01-21 08:23:08 -08004672 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08004673 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004674
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004675 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004676 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004677 for (const std::pair<int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4678 const TouchState& state = pair.second;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004679 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004680 state.displayId, toString(state.down), toString(state.split),
4681 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004682 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004683 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004684 for (size_t i = 0; i < state.windows.size(); i++) {
4685 const TouchedWindow& touchedWindow = state.windows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004686 dump += StringPrintf(INDENT4
4687 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
4688 i, touchedWindow.windowHandle->getName().c_str(),
4689 touchedWindow.pointerIds.value, touchedWindow.targetFlags);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004690 }
4691 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004692 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004693 }
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004694 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004695 dump += INDENT3 "Portal windows:\n";
4696 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004697 const sp<InputWindowHandle> portalWindowHandle = state.portalWindows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004698 dump += StringPrintf(INDENT4 "%zu: name='%s'\n", i,
4699 portalWindowHandle->getName().c_str());
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004700 }
4701 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004702 }
4703 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004704 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004705 }
4706
Arthur Hungb92218b2018-08-14 12:00:21 +08004707 if (!mWindowHandlesByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004708 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004709 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08004710 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", it.first);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004711 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004712 dump += INDENT2 "Windows:\n";
4713 for (size_t i = 0; i < windowHandles.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004714 const sp<InputWindowHandle>& windowHandle = windowHandles[i];
Arthur Hungb92218b2018-08-14 12:00:21 +08004715 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004716
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00004717 dump += StringPrintf(INDENT3 "%zu: name='%s', id=%" PRId32 ", displayId=%d, "
Vishnu Nair47074b82020-08-14 11:54:47 -07004718 "portalToDisplayId=%d, paused=%s, focusable=%s, "
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00004719 "hasWallpaper=%s, visible=%s, alpha=%.2f, "
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00004720 "flags=%s, type=%s, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004721 "frame=[%d,%d][%d,%d], globalScale=%f, "
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004722 "applicationInfo=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07004723 "touchableRegion=",
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00004724 i, windowInfo->name.c_str(), windowInfo->id,
4725 windowInfo->displayId, windowInfo->portalToDisplayId,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004726 toString(windowInfo->paused),
Vishnu Nair47074b82020-08-14 11:54:47 -07004727 toString(windowInfo->focusable),
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004728 toString(windowInfo->hasWallpaper),
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00004729 toString(windowInfo->visible), windowInfo->alpha,
Michael Wright8759d672020-07-21 00:46:45 +01004730 windowInfo->flags.string().c_str(),
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00004731 NamedEnum::string(windowInfo->type).c_str(),
Michael Wright44753b12020-07-08 13:48:11 +01004732 windowInfo->frameLeft, windowInfo->frameTop,
4733 windowInfo->frameRight, windowInfo->frameBottom,
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004734 windowInfo->globalScaleFactor,
4735 windowInfo->applicationInfo.name.c_str());
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00004736 dump += dumpRegion(windowInfo->touchableRegion);
Michael Wright44753b12020-07-08 13:48:11 +01004737 dump += StringPrintf(", inputFeatures=%s",
4738 windowInfo->inputFeatures.string().c_str());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004739 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00004740 "ms, trustedOverlay=%s, hasToken=%s, "
4741 "touchOcclusionMode=%s\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004742 windowInfo->ownerPid, windowInfo->ownerUid,
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00004743 millis(windowInfo->dispatchingTimeout),
4744 toString(windowInfo->trustedOverlay),
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00004745 toString(windowInfo->token != nullptr),
4746 toString(windowInfo->touchOcclusionMode).c_str());
chaviw85b44202020-07-24 11:46:21 -07004747 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08004748 }
4749 } else {
4750 dump += INDENT2 "Windows: <none>\n";
4751 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004752 }
4753 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08004754 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004755 }
4756
Michael Wright3dd60e22019-03-27 22:06:44 +00004757 if (!mGlobalMonitorsByDisplay.empty() || !mGestureMonitorsByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004758 for (auto& it : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004759 const std::vector<Monitor>& monitors = it.second;
4760 dump += StringPrintf(INDENT "Global monitors in display %" PRId32 ":\n", it.first);
4761 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004762 }
4763 for (auto& it : mGestureMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004764 const std::vector<Monitor>& monitors = it.second;
4765 dump += StringPrintf(INDENT "Gesture monitors in display %" PRId32 ":\n", it.first);
4766 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004767 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004768 } else {
Michael Wright3dd60e22019-03-27 22:06:44 +00004769 dump += INDENT "Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004770 }
4771
4772 nsecs_t currentTime = now();
4773
4774 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004775 if (!mRecentQueue.empty()) {
4776 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004777 for (std::shared_ptr<EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004778 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05004779 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004780 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004781 }
4782 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004783 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004784 }
4785
4786 // Dump event currently being dispatched.
4787 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004788 dump += INDENT "PendingEvent:\n";
4789 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05004790 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004791 dump += StringPrintf(", age=%" PRId64 "ms\n",
4792 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004793 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004794 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004795 }
4796
4797 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004798 if (!mInboundQueue.empty()) {
4799 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004800 for (std::shared_ptr<EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004801 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05004802 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004803 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004804 }
4805 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004806 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004807 }
4808
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004809 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004810 dump += INDENT "ReplacedKeys:\n";
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004811 for (const std::pair<KeyReplacement, int32_t>& pair : mReplacedKeys) {
4812 const KeyReplacement& replacement = pair.first;
4813 int32_t newKeyCode = pair.second;
4814 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004815 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07004816 }
4817 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004818 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07004819 }
4820
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004821 if (!mConnectionsByFd.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004822 dump += INDENT "Connections:\n";
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004823 for (const auto& pair : mConnectionsByFd) {
4824 const sp<Connection>& connection = pair.second;
4825 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004826 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004827 pair.first, connection->getInputChannelName().c_str(),
4828 connection->getWindowName().c_str(), connection->getStatusLabel(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004829 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004830
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004831 if (!connection->outboundQueue.empty()) {
4832 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
4833 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05004834 dump += dumpQueue(connection->outboundQueue, currentTime);
4835
Michael Wrightd02c5b62014-02-10 15:10:22 -08004836 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004837 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004838 }
4839
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004840 if (!connection->waitQueue.empty()) {
4841 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
4842 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05004843 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004844 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004845 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004846 }
4847 }
4848 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004849 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004850 }
4851
4852 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004853 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
4854 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004855 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004856 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004857 }
4858
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004859 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004860 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
4861 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
4862 ns2ms(mConfig.keyRepeatTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004863}
4864
Michael Wright3dd60e22019-03-27 22:06:44 +00004865void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
4866 const size_t numMonitors = monitors.size();
4867 for (size_t i = 0; i < numMonitors; i++) {
4868 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004869 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00004870 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
4871 dump += "\n";
4872 }
4873}
4874
Garfield Tan15601662020-09-22 15:32:38 -07004875base::Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(
4876 const std::string& name) {
4877#if DEBUG_CHANNEL_CREATION
4878 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004879#endif
4880
Garfield Tan15601662020-09-22 15:32:38 -07004881 std::shared_ptr<InputChannel> serverChannel;
4882 std::unique_ptr<InputChannel> clientChannel;
4883 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
4884
4885 if (result) {
4886 return base::Error(result) << "Failed to open input channel pair with name " << name;
4887 }
4888
Michael Wrightd02c5b62014-02-10 15:10:22 -08004889 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004890 std::scoped_lock _l(mLock);
Garfield Tan15601662020-09-22 15:32:38 -07004891 sp<Connection> connection = new Connection(serverChannel, false /*monitor*/, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004892
Garfield Tan15601662020-09-22 15:32:38 -07004893 int fd = serverChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004894 mConnectionsByFd[fd] = connection;
Garfield Tan15601662020-09-22 15:32:38 -07004895 mInputChannelsByToken[serverChannel->getConnectionToken()] = serverChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004896
Michael Wrightd02c5b62014-02-10 15:10:22 -08004897 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
4898 } // release lock
4899
4900 // Wake the looper because some connections have changed.
4901 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07004902 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004903}
4904
Garfield Tan15601662020-09-22 15:32:38 -07004905base::Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(
Siarhei Vishniakou58cfc602020-12-14 23:21:30 +00004906 int32_t displayId, bool isGestureMonitor, const std::string& name, int32_t pid) {
Garfield Tan15601662020-09-22 15:32:38 -07004907 std::shared_ptr<InputChannel> serverChannel;
4908 std::unique_ptr<InputChannel> clientChannel;
4909 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
4910 if (result) {
4911 return base::Error(result) << "Failed to open input channel pair with name " << name;
4912 }
4913
Michael Wright3dd60e22019-03-27 22:06:44 +00004914 { // acquire lock
4915 std::scoped_lock _l(mLock);
4916
4917 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07004918 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
4919 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00004920 }
4921
Garfield Tan15601662020-09-22 15:32:38 -07004922 sp<Connection> connection = new Connection(serverChannel, true /*monitor*/, mIdGenerator);
Michael Wright3dd60e22019-03-27 22:06:44 +00004923
Garfield Tan15601662020-09-22 15:32:38 -07004924 const int fd = serverChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004925 mConnectionsByFd[fd] = connection;
Garfield Tan15601662020-09-22 15:32:38 -07004926 mInputChannelsByToken[serverChannel->getConnectionToken()] = serverChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00004927
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004928 auto& monitorsByDisplay =
4929 isGestureMonitor ? mGestureMonitorsByDisplay : mGlobalMonitorsByDisplay;
Siarhei Vishniakou58cfc602020-12-14 23:21:30 +00004930 monitorsByDisplay[displayId].emplace_back(serverChannel, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00004931
4932 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
Michael Wright3dd60e22019-03-27 22:06:44 +00004933 }
Garfield Tan15601662020-09-22 15:32:38 -07004934
Michael Wright3dd60e22019-03-27 22:06:44 +00004935 // Wake the looper because some connections have changed.
4936 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07004937 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00004938}
4939
Garfield Tan15601662020-09-22 15:32:38 -07004940status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004941 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004942 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004943
Garfield Tan15601662020-09-22 15:32:38 -07004944 status_t status = removeInputChannelLocked(connectionToken, false /*notify*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004945 if (status) {
4946 return status;
4947 }
4948 } // release lock
4949
4950 // Wake the poll loop because removing the connection may have changed the current
4951 // synchronization state.
4952 mLooper->wake();
4953 return OK;
4954}
4955
Garfield Tan15601662020-09-22 15:32:38 -07004956status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
4957 bool notify) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004958 sp<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004959 if (connection == nullptr) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004960 ALOGW("Attempted to unregister already unregistered input channel");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004961 return BAD_VALUE;
4962 }
4963
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004964 removeConnectionLocked(connection);
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004965 mInputChannelsByToken.erase(connectionToken);
Robert Carr5c8a0262018-10-03 16:30:44 -07004966
Michael Wrightd02c5b62014-02-10 15:10:22 -08004967 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004968 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004969 }
4970
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004971 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004972
4973 nsecs_t currentTime = now();
4974 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
4975
4976 connection->status = Connection::STATUS_ZOMBIE;
4977 return OK;
4978}
4979
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004980void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
4981 removeMonitorChannelLocked(connectionToken, mGlobalMonitorsByDisplay);
4982 removeMonitorChannelLocked(connectionToken, mGestureMonitorsByDisplay);
Michael Wright3dd60e22019-03-27 22:06:44 +00004983}
4984
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004985void InputDispatcher::removeMonitorChannelLocked(
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004986 const sp<IBinder>& connectionToken,
Michael Wright3dd60e22019-03-27 22:06:44 +00004987 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004988 for (auto it = monitorsByDisplay.begin(); it != monitorsByDisplay.end();) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004989 std::vector<Monitor>& monitors = it->second;
4990 const size_t numMonitors = monitors.size();
4991 for (size_t i = 0; i < numMonitors; i++) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004992 if (monitors[i].inputChannel->getConnectionToken() == connectionToken) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004993 monitors.erase(monitors.begin() + i);
4994 break;
4995 }
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004996 }
Michael Wright3dd60e22019-03-27 22:06:44 +00004997 if (monitors.empty()) {
4998 it = monitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004999 } else {
5000 ++it;
5001 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005002 }
5003}
5004
Michael Wright3dd60e22019-03-27 22:06:44 +00005005status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
5006 { // acquire lock
5007 std::scoped_lock _l(mLock);
5008 std::optional<int32_t> foundDisplayId = findGestureMonitorDisplayByTokenLocked(token);
5009
5010 if (!foundDisplayId) {
5011 ALOGW("Attempted to pilfer pointers from an un-registered monitor or invalid token");
5012 return BAD_VALUE;
5013 }
5014 int32_t displayId = foundDisplayId.value();
5015
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005016 std::unordered_map<int32_t, TouchState>::iterator stateIt =
5017 mTouchStatesByDisplay.find(displayId);
5018 if (stateIt == mTouchStatesByDisplay.end()) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005019 ALOGW("Failed to pilfer pointers: no pointers on display %" PRId32 ".", displayId);
5020 return BAD_VALUE;
5021 }
5022
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005023 TouchState& state = stateIt->second;
Michael Wright3dd60e22019-03-27 22:06:44 +00005024 std::optional<int32_t> foundDeviceId;
5025 for (const TouchedMonitor& touchedMonitor : state.gestureMonitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005026 if (touchedMonitor.monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005027 foundDeviceId = state.deviceId;
5028 }
5029 }
5030 if (!foundDeviceId || !state.down) {
5031 ALOGW("Attempted to pilfer points from a monitor without any on-going pointer streams."
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005032 " Ignoring.");
Michael Wright3dd60e22019-03-27 22:06:44 +00005033 return BAD_VALUE;
5034 }
5035 int32_t deviceId = foundDeviceId.value();
5036
5037 // Send cancel events to all the input channels we're stealing from.
5038 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005039 "gesture monitor stole pointer stream");
Michael Wright3dd60e22019-03-27 22:06:44 +00005040 options.deviceId = deviceId;
5041 options.displayId = displayId;
5042 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005043 std::shared_ptr<InputChannel> channel =
5044 getInputChannelLocked(window.windowHandle->getToken());
Michael Wright3a240c42019-12-10 20:53:41 +00005045 if (channel != nullptr) {
5046 synthesizeCancelationEventsForInputChannelLocked(channel, options);
5047 }
Michael Wright3dd60e22019-03-27 22:06:44 +00005048 }
5049 // Then clear the current touch state so we stop dispatching to them as well.
5050 state.filterNonMonitors();
5051 }
5052 return OK;
5053}
5054
Prabir Pradhan99987712020-11-10 18:43:05 -08005055void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
5056 { // acquire lock
5057 std::scoped_lock _l(mLock);
5058 if (DEBUG_FOCUS) {
5059 const sp<InputWindowHandle> windowHandle = getWindowHandleLocked(windowToken);
5060 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
5061 windowHandle != nullptr ? windowHandle->getName().c_str()
5062 : "token without window");
5063 }
5064
Vishnu Nairc519ff72021-01-21 08:23:08 -08005065 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08005066 if (focusedToken != windowToken) {
5067 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
5068 enabled ? "enable" : "disable");
5069 return;
5070 }
5071
5072 if (enabled == mFocusedWindowRequestedPointerCapture) {
5073 ALOGW("Ignoring request to %s Pointer Capture: "
5074 "window has %s requested pointer capture.",
5075 enabled ? "enable" : "disable", enabled ? "already" : "not");
5076 return;
5077 }
5078
5079 mFocusedWindowRequestedPointerCapture = enabled;
5080 setPointerCaptureLocked(enabled);
5081 } // release lock
5082
5083 // Wake the thread to process command entries.
5084 mLooper->wake();
5085}
5086
Michael Wright3dd60e22019-03-27 22:06:44 +00005087std::optional<int32_t> InputDispatcher::findGestureMonitorDisplayByTokenLocked(
5088 const sp<IBinder>& token) {
5089 for (const auto& it : mGestureMonitorsByDisplay) {
5090 const std::vector<Monitor>& monitors = it.second;
5091 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005092 if (monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005093 return it.first;
5094 }
5095 }
5096 }
5097 return std::nullopt;
5098}
5099
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005100std::optional<int32_t> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
5101 std::optional<int32_t> gesturePid = findMonitorPidByToken(mGestureMonitorsByDisplay, token);
5102 if (gesturePid.has_value()) {
5103 return gesturePid;
5104 }
5105 return findMonitorPidByToken(mGlobalMonitorsByDisplay, token);
5106}
5107
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005108sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005109 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005110 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08005111 }
5112
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005113 for (const auto& pair : mConnectionsByFd) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005114 const sp<Connection>& connection = pair.second;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005115 if (connection->inputChannel->getConnectionToken() == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005116 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005117 }
5118 }
Robert Carr4e670e52018-08-15 13:26:12 -07005119
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005120 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005121}
5122
Siarhei Vishniakouad991402020-10-28 11:40:09 -05005123std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
5124 sp<Connection> connection = getConnectionLocked(connectionToken);
5125 if (connection == nullptr) {
5126 return "<nullptr>";
5127 }
5128 return connection->getInputChannelName();
5129}
5130
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005131void InputDispatcher::removeConnectionLocked(const sp<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005132 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005133 removeByValue(mConnectionsByFd, connection);
5134}
5135
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005136void InputDispatcher::onDispatchCycleFinishedLocked(nsecs_t currentTime,
5137 const sp<Connection>& connection, uint32_t seq,
5138 bool handled) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005139 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5140 &InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005141 commandEntry->connection = connection;
5142 commandEntry->eventTime = currentTime;
5143 commandEntry->seq = seq;
5144 commandEntry->handled = handled;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005145 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005146}
5147
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005148void InputDispatcher::onDispatchCycleBrokenLocked(nsecs_t currentTime,
5149 const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005150 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005151 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005152
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005153 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5154 &InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005155 commandEntry->connection = connection;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005156 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005157}
5158
Vishnu Nairad321cd2020-08-20 16:40:21 -07005159void InputDispatcher::notifyFocusChangedLocked(const sp<IBinder>& oldToken,
5160 const sp<IBinder>& newToken) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005161 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5162 &InputDispatcher::doNotifyFocusChangedLockedInterruptible);
chaviw0c06c6e2019-01-09 13:27:07 -08005163 commandEntry->oldToken = oldToken;
5164 commandEntry->newToken = newToken;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005165 postCommandLocked(std::move(commandEntry));
Robert Carrf759f162018-11-13 12:57:11 -08005166}
5167
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005168void InputDispatcher::onAnrLocked(const sp<Connection>& connection) {
5169 if (connection == nullptr) {
5170 LOG_ALWAYS_FATAL("Caller must check for nullness");
5171 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005172 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
5173 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005174 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005175 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005176 connection->inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005177 return;
5178 }
5179 /**
5180 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
5181 * may not be the one that caused the timeout to occur. One possibility is that window timeout
5182 * has changed. This could cause newer entries to time out before the already dispatched
5183 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
5184 * processes the events linearly. So providing information about the oldest entry seems to be
5185 * most useful.
5186 */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005187 DispatchEntry* oldestEntry = *connection->waitQueue.begin();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005188 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
5189 std::string reason =
5190 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005191 connection->inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005192 ns2ms(currentWait),
5193 oldestEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005194 sp<IBinder> connectionToken = connection->inputChannel->getConnectionToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06005195 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005196
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005197 processConnectionUnresponsiveLocked(*connection, std::move(reason));
5198
5199 // Stop waking up for events on this connection, it is already unresponsive
5200 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005201}
5202
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005203void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
5204 std::string reason =
5205 StringPrintf("%s does not have a focused window", application->getName().c_str());
5206 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005207
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005208 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5209 &InputDispatcher::doNotifyNoFocusedWindowAnrLockedInterruptible);
5210 commandEntry->inputApplicationHandle = std::move(application);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005211 postCommandLocked(std::move(commandEntry));
5212}
5213
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00005214void InputDispatcher::onUntrustedTouchLocked(const std::string& obscuringPackage) {
5215 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5216 &InputDispatcher::doNotifyUntrustedTouchLockedInterruptible);
5217 commandEntry->obscuringPackage = obscuringPackage;
5218 postCommandLocked(std::move(commandEntry));
5219}
5220
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005221void InputDispatcher::updateLastAnrStateLocked(const sp<InputWindowHandle>& window,
5222 const std::string& reason) {
5223 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
5224 updateLastAnrStateLocked(windowLabel, reason);
5225}
5226
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005227void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
5228 const std::string& reason) {
5229 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005230 updateLastAnrStateLocked(windowLabel, reason);
5231}
5232
5233void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
5234 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005235 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07005236 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005237 struct tm tm;
5238 localtime_r(&t, &tm);
5239 char timestr[64];
5240 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005241 mLastAnrState.clear();
5242 mLastAnrState += INDENT "ANR:\n";
5243 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005244 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
5245 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005246 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005247}
5248
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005249void InputDispatcher::doNotifyConfigurationChangedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005250 mLock.unlock();
5251
5252 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
5253
5254 mLock.lock();
5255}
5256
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005257void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005258 sp<Connection> connection = commandEntry->connection;
5259
5260 if (connection->status != Connection::STATUS_ZOMBIE) {
5261 mLock.unlock();
5262
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005263 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005264
5265 mLock.lock();
5266 }
5267}
5268
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005269void InputDispatcher::doNotifyFocusChangedLockedInterruptible(CommandEntry* commandEntry) {
chaviw0c06c6e2019-01-09 13:27:07 -08005270 sp<IBinder> oldToken = commandEntry->oldToken;
5271 sp<IBinder> newToken = commandEntry->newToken;
Robert Carrf759f162018-11-13 12:57:11 -08005272 mLock.unlock();
chaviw0c06c6e2019-01-09 13:27:07 -08005273 mPolicy->notifyFocusChanged(oldToken, newToken);
Robert Carrf759f162018-11-13 12:57:11 -08005274 mLock.lock();
5275}
5276
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005277void InputDispatcher::doNotifyNoFocusedWindowAnrLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005278 mLock.unlock();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005279
5280 mPolicy->notifyNoFocusedWindowAnr(commandEntry->inputApplicationHandle);
5281
5282 mLock.lock();
5283}
5284
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005285void InputDispatcher::doNotifyWindowUnresponsiveLockedInterruptible(CommandEntry* commandEntry) {
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005286 mLock.unlock();
5287
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005288 mPolicy->notifyWindowUnresponsive(commandEntry->connectionToken, commandEntry->reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005289
5290 mLock.lock();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005291}
5292
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005293void InputDispatcher::doNotifyMonitorUnresponsiveLockedInterruptible(CommandEntry* commandEntry) {
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005294 mLock.unlock();
5295
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005296 mPolicy->notifyMonitorUnresponsive(commandEntry->pid, commandEntry->reason);
5297
5298 mLock.lock();
5299}
5300
5301void InputDispatcher::doNotifyWindowResponsiveLockedInterruptible(CommandEntry* commandEntry) {
5302 mLock.unlock();
5303
5304 mPolicy->notifyWindowResponsive(commandEntry->connectionToken);
5305
5306 mLock.lock();
5307}
5308
5309void InputDispatcher::doNotifyMonitorResponsiveLockedInterruptible(CommandEntry* commandEntry) {
5310 mLock.unlock();
5311
5312 mPolicy->notifyMonitorResponsive(commandEntry->pid);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005313
5314 mLock.lock();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005315}
5316
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00005317void InputDispatcher::doNotifyUntrustedTouchLockedInterruptible(CommandEntry* commandEntry) {
5318 mLock.unlock();
5319
5320 mPolicy->notifyUntrustedTouch(commandEntry->obscuringPackage);
5321
5322 mLock.lock();
5323}
5324
Michael Wrightd02c5b62014-02-10 15:10:22 -08005325void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
5326 CommandEntry* commandEntry) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005327 KeyEntry& entry = *(commandEntry->keyEntry);
5328 KeyEvent event = createKeyEvent(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005329
5330 mLock.unlock();
5331
Michael Wright2b3c3302018-03-02 17:19:13 +00005332 android::base::Timer t;
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06005333 const sp<IBinder>& token = commandEntry->connectionToken;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005334 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(token, &event, entry.policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00005335 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
5336 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005337 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00005338 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005339
5340 mLock.lock();
5341
5342 if (delay < 0) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005343 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005344 } else if (!delay) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005345 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005346 } else {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005347 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
5348 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005349 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005350}
5351
chaviwfd6d3512019-03-25 13:23:49 -07005352void InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible(CommandEntry* commandEntry) {
5353 mLock.unlock();
5354 mPolicy->onPointerDownOutsideFocus(commandEntry->newToken);
5355 mLock.lock();
5356}
5357
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005358/**
5359 * Connection is responsive if it has no events in the waitQueue that are older than the
5360 * current time.
5361 */
5362static bool isConnectionResponsive(const Connection& connection) {
5363 const nsecs_t currentTime = now();
5364 for (const DispatchEntry* entry : connection.waitQueue) {
5365 if (entry->timeoutTime < currentTime) {
5366 return false;
5367 }
5368 }
5369 return true;
5370}
5371
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005372void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005373 sp<Connection> connection = commandEntry->connection;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005374 const nsecs_t finishTime = commandEntry->eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005375 uint32_t seq = commandEntry->seq;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005376 const bool handled = commandEntry->handled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005377
5378 // Handle post-event policy actions.
Garfield Tane84e6f92019-08-29 17:28:41 -07005379 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005380 if (dispatchEntryIt == connection->waitQueue.end()) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005381 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005382 }
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005383 DispatchEntry* dispatchEntry = *dispatchEntryIt;
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07005384 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005385 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005386 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
5387 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005388 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07005389 reportDispatchStatistics(std::chrono::nanoseconds(eventDuration), *connection, handled);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005390
5391 bool restartEvent;
Siarhei Vishniakou49483272019-10-22 13:13:47 -07005392 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005393 KeyEntry& keyEntry = static_cast<KeyEntry&>(*(dispatchEntry->eventEntry));
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005394 restartEvent =
5395 afterKeyEventLockedInterruptible(connection, dispatchEntry, keyEntry, handled);
Siarhei Vishniakou49483272019-10-22 13:13:47 -07005396 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005397 MotionEntry& motionEntry = static_cast<MotionEntry&>(*(dispatchEntry->eventEntry));
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005398 restartEvent = afterMotionEventLockedInterruptible(connection, dispatchEntry, motionEntry,
5399 handled);
5400 } else {
5401 restartEvent = false;
5402 }
5403
5404 // Dequeue the event and start the next cycle.
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07005405 // Because the lock might have been released, it is possible that the
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005406 // contents of the wait queue to have been drained, so we need to double-check
5407 // a few things.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005408 dispatchEntryIt = connection->findWaitQueueEntry(seq);
5409 if (dispatchEntryIt != connection->waitQueue.end()) {
5410 dispatchEntry = *dispatchEntryIt;
5411 connection->waitQueue.erase(dispatchEntryIt);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005412 const sp<IBinder>& connectionToken = connection->inputChannel->getConnectionToken();
5413 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005414 if (!connection->responsive) {
5415 connection->responsive = isConnectionResponsive(*connection);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005416 if (connection->responsive) {
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005417 // The connection was unresponsive, and now it's responsive.
5418 processConnectionResponsiveLocked(*connection);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005419 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005420 }
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005421 traceWaitQueueLength(connection);
5422 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005423 connection->outboundQueue.push_front(dispatchEntry);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005424 traceOutboundQueueLength(connection);
5425 } else {
5426 releaseDispatchEntry(dispatchEntry);
5427 }
5428 }
5429
5430 // Start the next dispatch cycle for this connection.
5431 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005432}
5433
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005434void InputDispatcher::sendMonitorUnresponsiveCommandLocked(int32_t pid, std::string reason) {
5435 std::unique_ptr<CommandEntry> monitorUnresponsiveCommand = std::make_unique<CommandEntry>(
5436 &InputDispatcher::doNotifyMonitorUnresponsiveLockedInterruptible);
5437 monitorUnresponsiveCommand->pid = pid;
5438 monitorUnresponsiveCommand->reason = std::move(reason);
5439 postCommandLocked(std::move(monitorUnresponsiveCommand));
5440}
5441
5442void InputDispatcher::sendWindowUnresponsiveCommandLocked(sp<IBinder> connectionToken,
5443 std::string reason) {
5444 std::unique_ptr<CommandEntry> windowUnresponsiveCommand = std::make_unique<CommandEntry>(
5445 &InputDispatcher::doNotifyWindowUnresponsiveLockedInterruptible);
5446 windowUnresponsiveCommand->connectionToken = std::move(connectionToken);
5447 windowUnresponsiveCommand->reason = std::move(reason);
5448 postCommandLocked(std::move(windowUnresponsiveCommand));
5449}
5450
5451void InputDispatcher::sendMonitorResponsiveCommandLocked(int32_t pid) {
5452 std::unique_ptr<CommandEntry> monitorResponsiveCommand = std::make_unique<CommandEntry>(
5453 &InputDispatcher::doNotifyMonitorResponsiveLockedInterruptible);
5454 monitorResponsiveCommand->pid = pid;
5455 postCommandLocked(std::move(monitorResponsiveCommand));
5456}
5457
5458void InputDispatcher::sendWindowResponsiveCommandLocked(sp<IBinder> connectionToken) {
5459 std::unique_ptr<CommandEntry> windowResponsiveCommand = std::make_unique<CommandEntry>(
5460 &InputDispatcher::doNotifyWindowResponsiveLockedInterruptible);
5461 windowResponsiveCommand->connectionToken = std::move(connectionToken);
5462 postCommandLocked(std::move(windowResponsiveCommand));
5463}
5464
5465/**
5466 * Tell the policy that a connection has become unresponsive so that it can start ANR.
5467 * Check whether the connection of interest is a monitor or a window, and add the corresponding
5468 * command entry to the command queue.
5469 */
5470void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
5471 std::string reason) {
5472 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
5473 if (connection.monitor) {
5474 ALOGW("Monitor %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
5475 reason.c_str());
5476 std::optional<int32_t> pid = findMonitorPidByTokenLocked(connectionToken);
5477 if (!pid.has_value()) {
5478 ALOGE("Could not find unresponsive monitor for connection %s",
5479 connection.inputChannel->getName().c_str());
5480 return;
5481 }
5482 sendMonitorUnresponsiveCommandLocked(pid.value(), std::move(reason));
5483 return;
5484 }
5485 // If not a monitor, must be a window
5486 ALOGW("Window %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
5487 reason.c_str());
5488 sendWindowUnresponsiveCommandLocked(connectionToken, std::move(reason));
5489}
5490
5491/**
5492 * Tell the policy that a connection has become responsive so that it can stop ANR.
5493 */
5494void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
5495 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
5496 if (connection.monitor) {
5497 std::optional<int32_t> pid = findMonitorPidByTokenLocked(connectionToken);
5498 if (!pid.has_value()) {
5499 ALOGE("Could not find responsive monitor for connection %s",
5500 connection.inputChannel->getName().c_str());
5501 return;
5502 }
5503 sendMonitorResponsiveCommandLocked(pid.value());
5504 return;
5505 }
5506 // If not a monitor, must be a window
5507 sendWindowResponsiveCommandLocked(connectionToken);
5508}
5509
Michael Wrightd02c5b62014-02-10 15:10:22 -08005510bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005511 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005512 KeyEntry& keyEntry, bool handled) {
5513 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005514 if (!handled) {
5515 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005516 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005517 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005518 return false;
5519 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005520
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005521 // Get the fallback key state.
5522 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005523 int32_t originalKeyCode = keyEntry.keyCode;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005524 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005525 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005526 connection->inputState.removeFallbackKey(originalKeyCode);
5527 }
5528
5529 if (handled || !dispatchEntry->hasForegroundTarget()) {
5530 // If the application handles the original key for which we previously
5531 // generated a fallback or if the window is not a foreground window,
5532 // then cancel the associated fallback key, if any.
5533 if (fallbackKeyCode != -1) {
5534 // Dispatch the unhandled key to the policy with the cancel flag.
Michael Wrightd02c5b62014-02-10 15:10:22 -08005535#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005536 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005537 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005538 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005539#endif
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005540 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005541 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005542
5543 mLock.unlock();
5544
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005545 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005546 keyEntry.policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005547
5548 mLock.lock();
5549
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005550 // Cancel the fallback key.
5551 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005552 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005553 "application handled the original non-fallback key "
5554 "or is no longer a foreground target, "
5555 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005556 options.keyCode = fallbackKeyCode;
5557 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005558 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005559 connection->inputState.removeFallbackKey(originalKeyCode);
5560 }
5561 } else {
5562 // If the application did not handle a non-fallback key, first check
5563 // that we are in a good state to perform unhandled key event processing
5564 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005565 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005566 if (fallbackKeyCode == -1 && !initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005567#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005568 ALOGD("Unhandled key event: Skipping unhandled key event processing "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005569 "since this is not an initial down. "
5570 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005571 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005572#endif
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005573 return false;
5574 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005575
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005576 // Dispatch the unhandled key to the policy.
5577#if DEBUG_OUTBOUND_EVENT_DETAILS
5578 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005579 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005580 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005581#endif
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005582 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005583
5584 mLock.unlock();
5585
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005586 bool fallback =
5587 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005588 &event, keyEntry.policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005589
5590 mLock.lock();
5591
5592 if (connection->status != Connection::STATUS_NORMAL) {
5593 connection->inputState.removeFallbackKey(originalKeyCode);
5594 return false;
5595 }
5596
5597 // Latch the fallback keycode for this key on an initial down.
5598 // The fallback keycode cannot change at any other point in the lifecycle.
5599 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005600 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005601 fallbackKeyCode = event.getKeyCode();
5602 } else {
5603 fallbackKeyCode = AKEYCODE_UNKNOWN;
5604 }
5605 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
5606 }
5607
5608 ALOG_ASSERT(fallbackKeyCode != -1);
5609
5610 // Cancel the fallback key if the policy decides not to send it anymore.
5611 // We will continue to dispatch the key to the policy but we will no
5612 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005613 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
5614 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005615#if DEBUG_OUTBOUND_EVENT_DETAILS
5616 if (fallback) {
5617 ALOGD("Unhandled key event: Policy requested to send key %d"
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005618 "as a fallback for %d, but on the DOWN it had requested "
5619 "to send %d instead. Fallback canceled.",
5620 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005621 } else {
5622 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005623 "but on the DOWN it had requested to send %d. "
5624 "Fallback canceled.",
5625 originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005626 }
5627#endif
5628
5629 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
5630 "canceling fallback, policy no longer desires it");
5631 options.keyCode = fallbackKeyCode;
5632 synthesizeCancelationEventsForConnectionLocked(connection, options);
5633
5634 fallback = false;
5635 fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005636 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005637 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005638 }
5639 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005640
5641#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005642 {
5643 std::string msg;
5644 const KeyedVector<int32_t, int32_t>& fallbackKeys =
5645 connection->inputState.getFallbackKeys();
5646 for (size_t i = 0; i < fallbackKeys.size(); i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005647 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005648 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005649 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005650 fallbackKeys.size(), msg.c_str());
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005651 }
5652#endif
5653
5654 if (fallback) {
5655 // Restart the dispatch cycle using the fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005656 keyEntry.eventTime = event.getEventTime();
5657 keyEntry.deviceId = event.getDeviceId();
5658 keyEntry.source = event.getSource();
5659 keyEntry.displayId = event.getDisplayId();
5660 keyEntry.flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
5661 keyEntry.keyCode = fallbackKeyCode;
5662 keyEntry.scanCode = event.getScanCode();
5663 keyEntry.metaState = event.getMetaState();
5664 keyEntry.repeatCount = event.getRepeatCount();
5665 keyEntry.downTime = event.getDownTime();
5666 keyEntry.syntheticRepeat = false;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005667
5668#if DEBUG_OUTBOUND_EVENT_DETAILS
5669 ALOGD("Unhandled key event: Dispatching fallback key. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005670 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005671 originalKeyCode, fallbackKeyCode, keyEntry.metaState);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005672#endif
5673 return true; // restart the event
5674 } else {
5675#if DEBUG_OUTBOUND_EVENT_DETAILS
5676 ALOGD("Unhandled key event: No fallback key.");
5677#endif
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005678
5679 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005680 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005681 }
5682 }
5683 return false;
5684}
5685
5686bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005687 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005688 MotionEntry& motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005689 return false;
5690}
5691
5692void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
5693 mLock.unlock();
5694
5695 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
5696
5697 mLock.lock();
5698}
5699
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07005700void InputDispatcher::reportDispatchStatistics(std::chrono::nanoseconds eventDuration,
5701 const Connection& connection, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005702 // TODO Write some statistics about how long we spend waiting.
5703}
5704
Siarhei Vishniakoude4bf152019-08-16 11:12:52 -05005705/**
5706 * Report the touch event latency to the statsd server.
5707 * Input events are reported for statistics if:
5708 * - This is a touchscreen event
5709 * - InputFilter is not enabled
5710 * - Event is not injected or synthesized
5711 *
5712 * Statistics should be reported before calling addValue, to prevent a fresh new sample
5713 * from getting aggregated with the "old" data.
5714 */
5715void InputDispatcher::reportTouchEventForStatistics(const MotionEntry& motionEntry)
5716 REQUIRES(mLock) {
5717 const bool reportForStatistics = (motionEntry.source == AINPUT_SOURCE_TOUCHSCREEN) &&
5718 !(motionEntry.isSynthesized()) && !mInputFilterEnabled;
5719 if (!reportForStatistics) {
5720 return;
5721 }
5722
5723 if (mTouchStatistics.shouldReport()) {
5724 android::util::stats_write(android::util::TOUCH_EVENT_REPORTED, mTouchStatistics.getMin(),
5725 mTouchStatistics.getMax(), mTouchStatistics.getMean(),
5726 mTouchStatistics.getStDev(), mTouchStatistics.getCount());
5727 mTouchStatistics.reset();
5728 }
5729 const float latencyMicros = nanoseconds_to_microseconds(now() - motionEntry.eventTime);
5730 mTouchStatistics.addValue(latencyMicros);
5731}
5732
Michael Wrightd02c5b62014-02-10 15:10:22 -08005733void InputDispatcher::traceInboundQueueLengthLocked() {
5734 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005735 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005736 }
5737}
5738
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08005739void InputDispatcher::traceOutboundQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005740 if (ATRACE_ENABLED()) {
5741 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08005742 snprintf(counterName, sizeof(counterName), "oq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005743 ATRACE_INT(counterName, connection->outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005744 }
5745}
5746
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08005747void InputDispatcher::traceWaitQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005748 if (ATRACE_ENABLED()) {
5749 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08005750 snprintf(counterName, sizeof(counterName), "wq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005751 ATRACE_INT(counterName, connection->waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005752 }
5753}
5754
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005755void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005756 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005757
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005758 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005759 dumpDispatchStateLocked(dump);
5760
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005761 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005762 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005763 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005764 }
5765}
5766
5767void InputDispatcher::monitor() {
5768 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005769 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005770 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005771 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005772}
5773
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08005774/**
5775 * Wake up the dispatcher and wait until it processes all events and commands.
5776 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
5777 * this method can be safely called from any thread, as long as you've ensured that
5778 * the work you are interested in completing has already been queued.
5779 */
5780bool InputDispatcher::waitForIdle() {
5781 /**
5782 * Timeout should represent the longest possible time that a device might spend processing
5783 * events and commands.
5784 */
5785 constexpr std::chrono::duration TIMEOUT = 100ms;
5786 std::unique_lock lock(mLock);
5787 mLooper->wake();
5788 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
5789 return result == std::cv_status::no_timeout;
5790}
5791
Vishnu Naire798b472020-07-23 13:52:21 -07005792/**
5793 * Sets focus to the window identified by the token. This must be called
5794 * after updating any input window handles.
5795 *
5796 * Params:
5797 * request.token - input channel token used to identify the window that should gain focus.
5798 * request.focusedToken - the token that the caller expects currently to be focused. If the
5799 * specified token does not match the currently focused window, this request will be dropped.
5800 * If the specified focused token matches the currently focused window, the call will succeed.
5801 * Set this to "null" if this call should succeed no matter what the currently focused token is.
5802 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
5803 * when requesting the focus change. This determines which request gets
5804 * precedence if there is a focus change request from another source such as pointer down.
5805 */
Vishnu Nair958da932020-08-21 17:12:37 -07005806void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
5807 { // acquire lock
5808 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08005809 std::optional<FocusResolver::FocusChanges> changes =
5810 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
5811 if (changes) {
5812 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07005813 }
5814 } // release lock
5815 // Wake up poll loop since it may need to make new input dispatching choices.
5816 mLooper->wake();
5817}
5818
Vishnu Nairc519ff72021-01-21 08:23:08 -08005819void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes) {
5820 if (changes.oldFocus) {
5821 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(changes.oldFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005822 if (focusedInputChannel) {
5823 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
5824 "focus left window");
5825 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Vishnu Nairc519ff72021-01-21 08:23:08 -08005826 enqueueFocusEventLocked(changes.oldFocus, false /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005827 }
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005828 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08005829 if (changes.newFocus) {
5830 enqueueFocusEventLocked(changes.newFocus, true /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005831 }
5832
Prabir Pradhan99987712020-11-10 18:43:05 -08005833 // If a window has pointer capture, then it must have focus. We need to ensure that this
5834 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
5835 // If the window loses focus before it loses pointer capture, then the window can be in a state
5836 // where it has pointer capture but not focus, violating the contract. Therefore we must
5837 // dispatch the pointer capture event before the focus event. Since focus events are added to
5838 // the front of the queue (above), we add the pointer capture event to the front of the queue
5839 // after the focus events are added. This ensures the pointer capture event ends up at the
5840 // front.
5841 disablePointerCaptureForcedLocked();
5842
Vishnu Nairc519ff72021-01-21 08:23:08 -08005843 if (mFocusedDisplayId == changes.displayId) {
5844 notifyFocusChangedLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005845 }
5846}
Vishnu Nair958da932020-08-21 17:12:37 -07005847
Prabir Pradhan99987712020-11-10 18:43:05 -08005848void InputDispatcher::disablePointerCaptureForcedLocked() {
5849 if (!mFocusedWindowRequestedPointerCapture && !mWindowTokenWithPointerCapture) {
5850 return;
5851 }
5852
5853 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
5854
5855 if (mFocusedWindowRequestedPointerCapture) {
5856 mFocusedWindowRequestedPointerCapture = false;
5857 setPointerCaptureLocked(false);
5858 }
5859
5860 if (!mWindowTokenWithPointerCapture) {
5861 // No need to send capture changes because no window has capture.
5862 return;
5863 }
5864
5865 if (mPendingEvent != nullptr) {
5866 // Move the pending event to the front of the queue. This will give the chance
5867 // for the pending event to be dropped if it is a captured event.
5868 mInboundQueue.push_front(mPendingEvent);
5869 mPendingEvent = nullptr;
5870 }
5871
5872 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
5873 false /* hasCapture */);
5874 mInboundQueue.push_front(std::move(entry));
5875}
5876
Prabir Pradhan99987712020-11-10 18:43:05 -08005877void InputDispatcher::setPointerCaptureLocked(bool enabled) {
5878 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5879 &InputDispatcher::doSetPointerCaptureLockedInterruptible);
5880 commandEntry->enabled = enabled;
5881 postCommandLocked(std::move(commandEntry));
5882}
5883
5884void InputDispatcher::doSetPointerCaptureLockedInterruptible(
5885 android::inputdispatcher::CommandEntry* commandEntry) {
5886 mLock.unlock();
5887
5888 mPolicy->setPointerCapture(commandEntry->enabled);
5889
5890 mLock.lock();
5891}
5892
Garfield Tane84e6f92019-08-29 17:28:41 -07005893} // namespace android::inputdispatcher