blob: 13de53dc2032b9204201c824513cb93ff85c0f5d [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
20//#define LOG_NDEBUG 0
21
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
31// Log debug messages about registrations.
32#define DEBUG_REGISTRATION 0
33
34// Log debug messages about input event injection.
35#define DEBUG_INJECTION 0
36
37// Log debug messages about input focus tracking.
38#define DEBUG_FOCUS 0
39
40// Log debug messages about the app switch latency optimization.
41#define DEBUG_APP_SWITCH 0
42
43// Log debug messages about hover events.
44#define DEBUG_HOVER 0
45
46#include "InputDispatcher.h"
47
Michael Wrightd02c5b62014-02-10 15:10:22 -080048#include <errno.h>
Siarhei Vishniakou443ad902019-03-06 17:25:41 -080049#include <inttypes.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080050#include <limits.h>
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080051#include <sstream>
Mark Salyzyna5e161b2016-09-29 08:08:05 -070052#include <stddef.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080053#include <time.h>
Mark Salyzyna5e161b2016-09-29 08:08:05 -070054#include <unistd.h>
55
Michael Wright2b3c3302018-03-02 17:19:13 +000056#include <android-base/chrono_utils.h>
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080057#include <android-base/stringprintf.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070058#include <log/log.h>
Mark Salyzyna5e161b2016-09-29 08:08:05 -070059#include <utils/Trace.h>
60#include <powermanager/PowerManager.h>
61#include <ui/Region.h>
Robert Carr4e670e52018-08-15 13:26:12 -070062#include <binder/Binder.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080063
64#define INDENT " "
65#define INDENT2 " "
66#define INDENT3 " "
67#define INDENT4 " "
68
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080069using android::base::StringPrintf;
70
Michael Wrightd02c5b62014-02-10 15:10:22 -080071namespace android {
72
73// Default input dispatching timeout if there is no focused application or paused window
74// from which to determine an appropriate dispatching timeout.
Michael Wright2b3c3302018-03-02 17:19:13 +000075constexpr nsecs_t DEFAULT_INPUT_DISPATCHING_TIMEOUT = 5000 * 1000000LL; // 5 sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080076
77// Amount of time to allow for all pending events to be processed when an app switch
78// key is on the way. This is used to preempt input dispatch and drop input events
79// when an application takes too long to respond and the user has pressed an app switch key.
Michael Wright2b3c3302018-03-02 17:19:13 +000080constexpr nsecs_t APP_SWITCH_TIMEOUT = 500 * 1000000LL; // 0.5sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080081
82// Amount of time to allow for an event to be dispatched (measured since its eventTime)
83// before considering it stale and dropping it.
Michael Wright2b3c3302018-03-02 17:19:13 +000084constexpr nsecs_t STALE_EVENT_TIMEOUT = 10000 * 1000000LL; // 10sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080085
86// Amount of time to allow touch events to be streamed out to a connection before requiring
87// that the first event be finished. This value extends the ANR timeout by the specified
88// amount. For example, if streaming is allowed to get ahead by one second relative to the
89// queue of waiting unfinished events, then ANRs will similarly be delayed by one second.
Michael Wright2b3c3302018-03-02 17:19:13 +000090constexpr nsecs_t STREAM_AHEAD_EVENT_TIMEOUT = 500 * 1000000LL; // 0.5sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080091
92// 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 +000093constexpr nsecs_t SLOW_EVENT_PROCESSING_WARNING_TIMEOUT = 2000 * 1000000LL; // 2sec
94
95// Log a warning when an interception call takes longer than this to process.
96constexpr std::chrono::milliseconds SLOW_INTERCEPTION_THRESHOLD = 50ms;
Michael Wrightd02c5b62014-02-10 15:10:22 -080097
98// Number of recent events to keep for debugging purposes.
Michael Wright2b3c3302018-03-02 17:19:13 +000099constexpr size_t RECENT_QUEUE_MAX_SIZE = 10;
100
Prabir Pradhan42611e02018-11-27 14:04:02 -0800101// Sequence number for synthesized or injected events.
102constexpr uint32_t SYNTHESIZED_EVENT_SEQUENCE_NUM = 0;
103
Michael Wrightd02c5b62014-02-10 15:10:22 -0800104
105static inline nsecs_t now() {
106 return systemTime(SYSTEM_TIME_MONOTONIC);
107}
108
109static inline const char* toString(bool value) {
110 return value ? "true" : "false";
111}
112
Siarhei Vishniakoub48188a2018-03-01 20:55:47 -0800113static std::string motionActionToString(int32_t action) {
114 // Convert MotionEvent action to string
115 switch(action & AMOTION_EVENT_ACTION_MASK) {
116 case AMOTION_EVENT_ACTION_DOWN:
117 return "DOWN";
118 case AMOTION_EVENT_ACTION_MOVE:
119 return "MOVE";
120 case AMOTION_EVENT_ACTION_UP:
121 return "UP";
122 case AMOTION_EVENT_ACTION_POINTER_DOWN:
123 return "POINTER_DOWN";
124 case AMOTION_EVENT_ACTION_POINTER_UP:
125 return "POINTER_UP";
126 }
127 return StringPrintf("%" PRId32, action);
128}
129
130static std::string keyActionToString(int32_t action) {
131 // Convert KeyEvent action to string
132 switch(action) {
133 case AKEY_EVENT_ACTION_DOWN:
134 return "DOWN";
135 case AKEY_EVENT_ACTION_UP:
136 return "UP";
137 case AKEY_EVENT_ACTION_MULTIPLE:
138 return "MULTIPLE";
139 }
140 return StringPrintf("%" PRId32, action);
141}
142
Michael Wrightd02c5b62014-02-10 15:10:22 -0800143static inline int32_t getMotionEventActionPointerIndex(int32_t action) {
144 return (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK)
145 >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
146}
147
148static bool isValidKeyAction(int32_t action) {
149 switch (action) {
150 case AKEY_EVENT_ACTION_DOWN:
151 case AKEY_EVENT_ACTION_UP:
152 return true;
153 default:
154 return false;
155 }
156}
157
158static bool validateKeyEvent(int32_t action) {
159 if (! isValidKeyAction(action)) {
160 ALOGE("Key event has invalid action code 0x%x", action);
161 return false;
162 }
163 return true;
164}
165
Michael Wright7b159c92015-05-14 14:48:03 +0100166static bool isValidMotionAction(int32_t action, int32_t actionButton, int32_t pointerCount) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800167 switch (action & AMOTION_EVENT_ACTION_MASK) {
168 case AMOTION_EVENT_ACTION_DOWN:
169 case AMOTION_EVENT_ACTION_UP:
170 case AMOTION_EVENT_ACTION_CANCEL:
171 case AMOTION_EVENT_ACTION_MOVE:
172 case AMOTION_EVENT_ACTION_OUTSIDE:
173 case AMOTION_EVENT_ACTION_HOVER_ENTER:
174 case AMOTION_EVENT_ACTION_HOVER_MOVE:
175 case AMOTION_EVENT_ACTION_HOVER_EXIT:
176 case AMOTION_EVENT_ACTION_SCROLL:
177 return true;
178 case AMOTION_EVENT_ACTION_POINTER_DOWN:
179 case AMOTION_EVENT_ACTION_POINTER_UP: {
180 int32_t index = getMotionEventActionPointerIndex(action);
Dan Albert1bd2fc02016-02-02 15:11:57 -0800181 return index >= 0 && index < pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800182 }
Michael Wright7b159c92015-05-14 14:48:03 +0100183 case AMOTION_EVENT_ACTION_BUTTON_PRESS:
184 case AMOTION_EVENT_ACTION_BUTTON_RELEASE:
185 return actionButton != 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800186 default:
187 return false;
188 }
189}
190
Michael Wright7b159c92015-05-14 14:48:03 +0100191static bool validateMotionEvent(int32_t action, int32_t actionButton, size_t pointerCount,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800192 const PointerProperties* pointerProperties) {
Michael Wright7b159c92015-05-14 14:48:03 +0100193 if (! isValidMotionAction(action, actionButton, pointerCount)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800194 ALOGE("Motion event has invalid action code 0x%x", action);
195 return false;
196 }
197 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Narayan Kamath37764c72014-03-27 14:21:09 +0000198 ALOGE("Motion event has invalid pointer count %zu; value must be between 1 and %d.",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800199 pointerCount, MAX_POINTERS);
200 return false;
201 }
202 BitSet32 pointerIdBits;
203 for (size_t i = 0; i < pointerCount; i++) {
204 int32_t id = pointerProperties[i].id;
205 if (id < 0 || id > MAX_POINTER_ID) {
206 ALOGE("Motion event has invalid pointer id %d; value must be between 0 and %d",
207 id, MAX_POINTER_ID);
208 return false;
209 }
210 if (pointerIdBits.hasBit(id)) {
211 ALOGE("Motion event has duplicate pointer id %d", id);
212 return false;
213 }
214 pointerIdBits.markBit(id);
215 }
216 return true;
217}
218
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800219static void dumpRegion(std::string& dump, const Region& region) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800220 if (region.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800221 dump += "<empty>";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800222 return;
223 }
224
225 bool first = true;
226 Region::const_iterator cur = region.begin();
227 Region::const_iterator const tail = region.end();
228 while (cur != tail) {
229 if (first) {
230 first = false;
231 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800232 dump += "|";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800233 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800234 dump += StringPrintf("[%d,%d][%d,%d]", cur->left, cur->top, cur->right, cur->bottom);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800235 cur++;
236 }
237}
238
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700239/**
240 * Find the entry in std::unordered_map by key, and return it.
241 * If the entry is not found, return a default constructed entry.
242 *
243 * Useful when the entries are vectors, since an empty vector will be returned
244 * if the entry is not found.
245 * Also useful when the entries are sp<>. If an entry is not found, nullptr is returned.
246 */
247template <typename T, typename U>
248static T getValueByKey(const std::unordered_map<U, T>& map, U key) {
249 auto it = map.find(key);
Tiger Huang721e26f2018-07-24 22:26:19 +0800250 return it != map.end() ? it->second : T{};
251}
252
Michael Wrightd02c5b62014-02-10 15:10:22 -0800253
254// --- InputDispatcher ---
255
256InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy) :
257 mPolicy(policy),
Yi Kong9b14ac62018-07-17 13:48:38 -0700258 mPendingEvent(nullptr), mLastDropReason(DROP_REASON_NOT_DROPPED),
Michael Wright3a981722015-06-10 15:26:13 +0100259 mAppSwitchSawKeyDown(false), mAppSwitchDueTime(LONG_LONG_MAX),
Yi Kong9b14ac62018-07-17 13:48:38 -0700260 mNextUnblockedEvent(nullptr),
Michael Wrightd02c5b62014-02-10 15:10:22 -0800261 mDispatchEnabled(false), mDispatchFrozen(false), mInputFilterEnabled(false),
Tiger Huang721e26f2018-07-24 22:26:19 +0800262 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
Michael Wrightd02c5b62014-02-10 15:10:22 -0800263 mInputTargetWaitCause(INPUT_TARGET_WAIT_CAUSE_NONE) {
264 mLooper = new Looper(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800265 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800266
Yi Kong9b14ac62018-07-17 13:48:38 -0700267 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800268
269 policy->getDispatcherConfiguration(&mConfig);
270}
271
272InputDispatcher::~InputDispatcher() {
273 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800274 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800275
276 resetKeyRepeatLocked();
277 releasePendingEventLocked();
278 drainInboundQueueLocked();
279 }
280
281 while (mConnectionsByFd.size() != 0) {
282 unregisterInputChannel(mConnectionsByFd.valueAt(0)->inputChannel);
283 }
284}
285
286void InputDispatcher::dispatchOnce() {
287 nsecs_t nextWakeupTime = LONG_LONG_MAX;
288 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800289 std::scoped_lock _l(mLock);
290 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800291
292 // Run a dispatch loop if there are no pending commands.
293 // The dispatch loop might enqueue commands to run afterwards.
294 if (!haveCommandsLocked()) {
295 dispatchOnceInnerLocked(&nextWakeupTime);
296 }
297
298 // Run all pending commands if there are any.
299 // If any commands were run then force the next poll to wake up immediately.
300 if (runCommandsLockedInterruptible()) {
301 nextWakeupTime = LONG_LONG_MIN;
302 }
303 } // release lock
304
305 // Wait for callback or timeout or wake. (make sure we round up, not down)
306 nsecs_t currentTime = now();
307 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
308 mLooper->pollOnce(timeoutMillis);
309}
310
311void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
312 nsecs_t currentTime = now();
313
Jeff Browndc5992e2014-04-11 01:27:26 -0700314 // Reset the key repeat timer whenever normal dispatch is suspended while the
315 // device is in a non-interactive state. This is to ensure that we abort a key
316 // repeat if the device is just coming out of sleep.
317 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800318 resetKeyRepeatLocked();
319 }
320
321 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
322 if (mDispatchFrozen) {
323#if DEBUG_FOCUS
324 ALOGD("Dispatch frozen. Waiting some more.");
325#endif
326 return;
327 }
328
329 // Optimize latency of app switches.
330 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
331 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
332 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
333 if (mAppSwitchDueTime < *nextWakeupTime) {
334 *nextWakeupTime = mAppSwitchDueTime;
335 }
336
337 // Ready to start a new event.
338 // If we don't already have a pending event, go grab one.
339 if (! mPendingEvent) {
340 if (mInboundQueue.isEmpty()) {
341 if (isAppSwitchDue) {
342 // The inbound queue is empty so the app switch key we were waiting
343 // for will never arrive. Stop waiting for it.
344 resetPendingAppSwitchLocked(false);
345 isAppSwitchDue = false;
346 }
347
348 // Synthesize a key repeat if appropriate.
349 if (mKeyRepeatState.lastKeyEntry) {
350 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
351 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
352 } else {
353 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
354 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
355 }
356 }
357 }
358
359 // Nothing to do if there is no pending event.
360 if (!mPendingEvent) {
361 return;
362 }
363 } else {
364 // Inbound queue has at least one entry.
365 mPendingEvent = mInboundQueue.dequeueAtHead();
366 traceInboundQueueLengthLocked();
367 }
368
369 // Poke user activity for this event.
370 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
371 pokeUserActivityLocked(mPendingEvent);
372 }
373
374 // Get ready to dispatch the event.
375 resetANRTimeoutsLocked();
376 }
377
378 // Now we have an event to dispatch.
379 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700380 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800381 bool done = false;
382 DropReason dropReason = DROP_REASON_NOT_DROPPED;
383 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
384 dropReason = DROP_REASON_POLICY;
385 } else if (!mDispatchEnabled) {
386 dropReason = DROP_REASON_DISABLED;
387 }
388
389 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700390 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800391 }
392
393 switch (mPendingEvent->type) {
394 case EventEntry::TYPE_CONFIGURATION_CHANGED: {
395 ConfigurationChangedEntry* typedEntry =
396 static_cast<ConfigurationChangedEntry*>(mPendingEvent);
397 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
398 dropReason = DROP_REASON_NOT_DROPPED; // configuration changes are never dropped
399 break;
400 }
401
402 case EventEntry::TYPE_DEVICE_RESET: {
403 DeviceResetEntry* typedEntry =
404 static_cast<DeviceResetEntry*>(mPendingEvent);
405 done = dispatchDeviceResetLocked(currentTime, typedEntry);
406 dropReason = DROP_REASON_NOT_DROPPED; // device resets are never dropped
407 break;
408 }
409
410 case EventEntry::TYPE_KEY: {
411 KeyEntry* typedEntry = static_cast<KeyEntry*>(mPendingEvent);
412 if (isAppSwitchDue) {
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800413 if (isAppSwitchKeyEvent(typedEntry)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800414 resetPendingAppSwitchLocked(true);
415 isAppSwitchDue = false;
416 } else if (dropReason == DROP_REASON_NOT_DROPPED) {
417 dropReason = DROP_REASON_APP_SWITCH;
418 }
419 }
420 if (dropReason == DROP_REASON_NOT_DROPPED
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800421 && isStaleEvent(currentTime, typedEntry)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800422 dropReason = DROP_REASON_STALE;
423 }
424 if (dropReason == DROP_REASON_NOT_DROPPED && mNextUnblockedEvent) {
425 dropReason = DROP_REASON_BLOCKED;
426 }
427 done = dispatchKeyLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
428 break;
429 }
430
431 case EventEntry::TYPE_MOTION: {
432 MotionEntry* typedEntry = static_cast<MotionEntry*>(mPendingEvent);
433 if (dropReason == DROP_REASON_NOT_DROPPED && isAppSwitchDue) {
434 dropReason = DROP_REASON_APP_SWITCH;
435 }
436 if (dropReason == DROP_REASON_NOT_DROPPED
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800437 && isStaleEvent(currentTime, typedEntry)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800438 dropReason = DROP_REASON_STALE;
439 }
440 if (dropReason == DROP_REASON_NOT_DROPPED && mNextUnblockedEvent) {
441 dropReason = DROP_REASON_BLOCKED;
442 }
443 done = dispatchMotionLocked(currentTime, typedEntry,
444 &dropReason, nextWakeupTime);
445 break;
446 }
447
448 default:
449 ALOG_ASSERT(false);
450 break;
451 }
452
453 if (done) {
454 if (dropReason != DROP_REASON_NOT_DROPPED) {
455 dropInboundEventLocked(mPendingEvent, dropReason);
456 }
Michael Wright3a981722015-06-10 15:26:13 +0100457 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800458
459 releasePendingEventLocked();
460 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
461 }
462}
463
464bool InputDispatcher::enqueueInboundEventLocked(EventEntry* entry) {
465 bool needWake = mInboundQueue.isEmpty();
466 mInboundQueue.enqueueAtTail(entry);
467 traceInboundQueueLengthLocked();
468
469 switch (entry->type) {
470 case EventEntry::TYPE_KEY: {
471 // Optimize app switch latency.
472 // If the application takes too long to catch up then we drop all events preceding
473 // the app switch key.
474 KeyEntry* keyEntry = static_cast<KeyEntry*>(entry);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800475 if (isAppSwitchKeyEvent(keyEntry)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800476 if (keyEntry->action == AKEY_EVENT_ACTION_DOWN) {
477 mAppSwitchSawKeyDown = true;
478 } else if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
479 if (mAppSwitchSawKeyDown) {
480#if DEBUG_APP_SWITCH
481 ALOGD("App switch is pending!");
482#endif
483 mAppSwitchDueTime = keyEntry->eventTime + APP_SWITCH_TIMEOUT;
484 mAppSwitchSawKeyDown = false;
485 needWake = true;
486 }
487 }
488 }
489 break;
490 }
491
492 case EventEntry::TYPE_MOTION: {
493 // Optimize case where the current application is unresponsive and the user
494 // decides to touch a window in a different application.
495 // If the application takes too long to catch up then we drop all events preceding
496 // the touch into the other window.
497 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
498 if (motionEntry->action == AMOTION_EVENT_ACTION_DOWN
499 && (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER)
500 && mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY
Robert Carr740167f2018-10-11 19:03:41 -0700501 && mInputTargetWaitApplicationToken != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800502 int32_t displayId = motionEntry->displayId;
503 int32_t x = int32_t(motionEntry->pointerCoords[0].
504 getAxisValue(AMOTION_EVENT_AXIS_X));
505 int32_t y = int32_t(motionEntry->pointerCoords[0].
506 getAxisValue(AMOTION_EVENT_AXIS_Y));
507 sp<InputWindowHandle> touchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y);
Yi Kong9b14ac62018-07-17 13:48:38 -0700508 if (touchedWindowHandle != nullptr
Robert Carr740167f2018-10-11 19:03:41 -0700509 && touchedWindowHandle->getApplicationToken()
510 != mInputTargetWaitApplicationToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800511 // User touched a different application than the one we are waiting on.
512 // Flag the event, and start pruning the input queue.
513 mNextUnblockedEvent = motionEntry;
514 needWake = true;
515 }
516 }
517 break;
518 }
519 }
520
521 return needWake;
522}
523
524void InputDispatcher::addRecentEventLocked(EventEntry* entry) {
525 entry->refCount += 1;
526 mRecentQueue.enqueueAtTail(entry);
527 if (mRecentQueue.count() > RECENT_QUEUE_MAX_SIZE) {
528 mRecentQueue.dequeueAtHead()->release();
529 }
530}
531
532sp<InputWindowHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId,
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800533 int32_t x, int32_t y, bool addOutsideTargets, bool addPortalWindows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800534 // Traverse windows from front to back to find touched window.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800535 const std::vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
536 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800537 const InputWindowInfo* windowInfo = windowHandle->getInfo();
538 if (windowInfo->displayId == displayId) {
539 int32_t flags = windowInfo->layoutParamsFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800540
541 if (windowInfo->visible) {
542 if (!(flags & InputWindowInfo::FLAG_NOT_TOUCHABLE)) {
543 bool isTouchModal = (flags & (InputWindowInfo::FLAG_NOT_FOCUSABLE
544 | InputWindowInfo::FLAG_NOT_TOUCH_MODAL)) == 0;
545 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800546 int32_t portalToDisplayId = windowInfo->portalToDisplayId;
547 if (portalToDisplayId != ADISPLAY_ID_NONE
548 && portalToDisplayId != displayId) {
549 if (addPortalWindows) {
550 // For the monitoring channels of the display.
551 mTempTouchState.addPortalWindow(windowHandle);
552 }
553 return findTouchedWindowAtLocked(
554 portalToDisplayId, x, y, addOutsideTargets, addPortalWindows);
555 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800556 // Found window.
557 return windowHandle;
558 }
559 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800560
561 if (addOutsideTargets && (flags & InputWindowInfo::FLAG_WATCH_OUTSIDE_TOUCH)) {
562 mTempTouchState.addOrUpdateWindow(
563 windowHandle, InputTarget::FLAG_DISPATCH_AS_OUTSIDE, BitSet32(0));
564 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800565 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800566 }
567 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700568 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800569}
570
571void InputDispatcher::dropInboundEventLocked(EventEntry* entry, DropReason dropReason) {
572 const char* reason;
573 switch (dropReason) {
574 case DROP_REASON_POLICY:
575#if DEBUG_INBOUND_EVENT_DETAILS
576 ALOGD("Dropped event because policy consumed it.");
577#endif
578 reason = "inbound event was dropped because the policy consumed it";
579 break;
580 case DROP_REASON_DISABLED:
Michael Wright3a981722015-06-10 15:26:13 +0100581 if (mLastDropReason != DROP_REASON_DISABLED) {
582 ALOGI("Dropped event because input dispatch is disabled.");
583 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800584 reason = "inbound event was dropped because input dispatch is disabled";
585 break;
586 case DROP_REASON_APP_SWITCH:
587 ALOGI("Dropped event because of pending overdue app switch.");
588 reason = "inbound event was dropped because of pending overdue app switch";
589 break;
590 case DROP_REASON_BLOCKED:
591 ALOGI("Dropped event because the current application is not responding and the user "
592 "has started interacting with a different application.");
593 reason = "inbound event was dropped because the current application is not responding "
594 "and the user has started interacting with a different application";
595 break;
596 case DROP_REASON_STALE:
597 ALOGI("Dropped event because it is stale.");
598 reason = "inbound event was dropped because it is stale";
599 break;
600 default:
601 ALOG_ASSERT(false);
602 return;
603 }
604
605 switch (entry->type) {
606 case EventEntry::TYPE_KEY: {
607 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
608 synthesizeCancelationEventsForAllConnectionsLocked(options);
609 break;
610 }
611 case EventEntry::TYPE_MOTION: {
612 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
613 if (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) {
614 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
615 synthesizeCancelationEventsForAllConnectionsLocked(options);
616 } else {
617 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
618 synthesizeCancelationEventsForAllConnectionsLocked(options);
619 }
620 break;
621 }
622 }
623}
624
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800625static bool isAppSwitchKeyCode(int32_t keyCode) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800626 return keyCode == AKEYCODE_HOME
627 || keyCode == AKEYCODE_ENDCALL
628 || keyCode == AKEYCODE_APP_SWITCH;
629}
630
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800631bool InputDispatcher::isAppSwitchKeyEvent(KeyEntry* keyEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800632 return ! (keyEntry->flags & AKEY_EVENT_FLAG_CANCELED)
633 && isAppSwitchKeyCode(keyEntry->keyCode)
634 && (keyEntry->policyFlags & POLICY_FLAG_TRUSTED)
635 && (keyEntry->policyFlags & POLICY_FLAG_PASS_TO_USER);
636}
637
638bool InputDispatcher::isAppSwitchPendingLocked() {
639 return mAppSwitchDueTime != LONG_LONG_MAX;
640}
641
642void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
643 mAppSwitchDueTime = LONG_LONG_MAX;
644
645#if DEBUG_APP_SWITCH
646 if (handled) {
647 ALOGD("App switch has arrived.");
648 } else {
649 ALOGD("App switch was abandoned.");
650 }
651#endif
652}
653
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800654bool InputDispatcher::isStaleEvent(nsecs_t currentTime, EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800655 return currentTime - entry->eventTime >= STALE_EVENT_TIMEOUT;
656}
657
658bool InputDispatcher::haveCommandsLocked() const {
659 return !mCommandQueue.isEmpty();
660}
661
662bool InputDispatcher::runCommandsLockedInterruptible() {
663 if (mCommandQueue.isEmpty()) {
664 return false;
665 }
666
667 do {
668 CommandEntry* commandEntry = mCommandQueue.dequeueAtHead();
669
670 Command command = commandEntry->command;
671 (this->*command)(commandEntry); // commands are implicitly 'LockedInterruptible'
672
673 commandEntry->connection.clear();
674 delete commandEntry;
675 } while (! mCommandQueue.isEmpty());
676 return true;
677}
678
679InputDispatcher::CommandEntry* InputDispatcher::postCommandLocked(Command command) {
680 CommandEntry* commandEntry = new CommandEntry(command);
681 mCommandQueue.enqueueAtTail(commandEntry);
682 return commandEntry;
683}
684
685void InputDispatcher::drainInboundQueueLocked() {
686 while (! mInboundQueue.isEmpty()) {
687 EventEntry* entry = mInboundQueue.dequeueAtHead();
688 releaseInboundEventLocked(entry);
689 }
690 traceInboundQueueLengthLocked();
691}
692
693void InputDispatcher::releasePendingEventLocked() {
694 if (mPendingEvent) {
695 resetANRTimeoutsLocked();
696 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -0700697 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800698 }
699}
700
701void InputDispatcher::releaseInboundEventLocked(EventEntry* entry) {
702 InjectionState* injectionState = entry->injectionState;
703 if (injectionState && injectionState->injectionResult == INPUT_EVENT_INJECTION_PENDING) {
704#if DEBUG_DISPATCH_CYCLE
705 ALOGD("Injected inbound event was dropped.");
706#endif
Siarhei Vishniakou62683e82019-03-06 17:59:56 -0800707 setInjectionResult(entry, INPUT_EVENT_INJECTION_FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800708 }
709 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700710 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800711 }
712 addRecentEventLocked(entry);
713 entry->release();
714}
715
716void InputDispatcher::resetKeyRepeatLocked() {
717 if (mKeyRepeatState.lastKeyEntry) {
718 mKeyRepeatState.lastKeyEntry->release();
Yi Kong9b14ac62018-07-17 13:48:38 -0700719 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800720 }
721}
722
723InputDispatcher::KeyEntry* InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
724 KeyEntry* entry = mKeyRepeatState.lastKeyEntry;
725
726 // Reuse the repeated key entry if it is otherwise unreferenced.
Michael Wright2e732952014-09-24 13:26:59 -0700727 uint32_t policyFlags = entry->policyFlags &
728 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800729 if (entry->refCount == 1) {
730 entry->recycle();
731 entry->eventTime = currentTime;
732 entry->policyFlags = policyFlags;
733 entry->repeatCount += 1;
734 } else {
Prabir Pradhan42611e02018-11-27 14:04:02 -0800735 KeyEntry* newEntry = new KeyEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, currentTime,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100736 entry->deviceId, entry->source, entry->displayId, policyFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800737 entry->action, entry->flags, entry->keyCode, entry->scanCode,
738 entry->metaState, entry->repeatCount + 1, entry->downTime);
739
740 mKeyRepeatState.lastKeyEntry = newEntry;
741 entry->release();
742
743 entry = newEntry;
744 }
745 entry->syntheticRepeat = true;
746
747 // Increment reference count since we keep a reference to the event in
748 // mKeyRepeatState.lastKeyEntry in addition to the one we return.
749 entry->refCount += 1;
750
751 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
752 return entry;
753}
754
755bool InputDispatcher::dispatchConfigurationChangedLocked(
756 nsecs_t currentTime, ConfigurationChangedEntry* entry) {
757#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700758 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800759#endif
760
761 // Reset key repeating in case a keyboard device was added or removed or something.
762 resetKeyRepeatLocked();
763
764 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
765 CommandEntry* commandEntry = postCommandLocked(
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800766 & InputDispatcher::doNotifyConfigurationChangedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800767 commandEntry->eventTime = entry->eventTime;
768 return true;
769}
770
771bool InputDispatcher::dispatchDeviceResetLocked(
772 nsecs_t currentTime, DeviceResetEntry* entry) {
773#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700774 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry->eventTime,
775 entry->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800776#endif
777
778 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
779 "device was reset");
780 options.deviceId = entry->deviceId;
781 synthesizeCancelationEventsForAllConnectionsLocked(options);
782 return true;
783}
784
785bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, KeyEntry* entry,
786 DropReason* dropReason, nsecs_t* nextWakeupTime) {
787 // Preprocessing.
788 if (! entry->dispatchInProgress) {
789 if (entry->repeatCount == 0
790 && entry->action == AKEY_EVENT_ACTION_DOWN
791 && (entry->policyFlags & POLICY_FLAG_TRUSTED)
792 && (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
793 if (mKeyRepeatState.lastKeyEntry
794 && mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode) {
795 // We have seen two identical key downs in a row which indicates that the device
796 // driver is automatically generating key repeats itself. We take note of the
797 // repeat here, but we disable our own next key repeat timer since it is clear that
798 // we will not need to synthesize key repeats ourselves.
799 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
800 resetKeyRepeatLocked();
801 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
802 } else {
803 // Not a repeat. Save key down state in case we do see a repeat later.
804 resetKeyRepeatLocked();
805 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
806 }
807 mKeyRepeatState.lastKeyEntry = entry;
808 entry->refCount += 1;
809 } else if (! entry->syntheticRepeat) {
810 resetKeyRepeatLocked();
811 }
812
813 if (entry->repeatCount == 1) {
814 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
815 } else {
816 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
817 }
818
819 entry->dispatchInProgress = true;
820
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800821 logOutboundKeyDetails("dispatchKey - ", entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800822 }
823
824 // Handle case where the policy asked us to try again later last time.
825 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
826 if (currentTime < entry->interceptKeyWakeupTime) {
827 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
828 *nextWakeupTime = entry->interceptKeyWakeupTime;
829 }
830 return false; // wait until next wakeup
831 }
832 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
833 entry->interceptKeyWakeupTime = 0;
834 }
835
836 // Give the policy a chance to intercept the key.
837 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
838 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
839 CommandEntry* commandEntry = postCommandLocked(
840 & InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
Tiger Huang721e26f2018-07-24 22:26:19 +0800841 sp<InputWindowHandle> focusedWindowHandle =
842 getValueByKey(mFocusedWindowHandlesByDisplay, getTargetDisplayId(entry));
843 if (focusedWindowHandle != nullptr) {
Robert Carr740167f2018-10-11 19:03:41 -0700844 commandEntry->inputChannel =
845 getInputChannelLocked(focusedWindowHandle->getToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800846 }
847 commandEntry->keyEntry = entry;
848 entry->refCount += 1;
849 return false; // wait for the command to run
850 } else {
851 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
852 }
853 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
854 if (*dropReason == DROP_REASON_NOT_DROPPED) {
855 *dropReason = DROP_REASON_POLICY;
856 }
857 }
858
859 // Clean up if dropping the event.
860 if (*dropReason != DROP_REASON_NOT_DROPPED) {
Siarhei Vishniakou62683e82019-03-06 17:59:56 -0800861 setInjectionResult(entry, *dropReason == DROP_REASON_POLICY
Michael Wrightd02c5b62014-02-10 15:10:22 -0800862 ? INPUT_EVENT_INJECTION_SUCCEEDED : INPUT_EVENT_INJECTION_FAILED);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800863 mReporter->reportDroppedKey(entry->sequenceNum);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800864 return true;
865 }
866
867 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800868 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800869 int32_t injectionResult = findFocusedWindowTargetsLocked(currentTime,
870 entry, inputTargets, nextWakeupTime);
871 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
872 return false;
873 }
874
Siarhei Vishniakou62683e82019-03-06 17:59:56 -0800875 setInjectionResult(entry, injectionResult);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800876 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
877 return true;
878 }
879
Arthur Hung2fbf37f2018-09-13 18:16:41 +0800880 // Add monitor channels from event's or focused display.
881 addMonitoringTargetsLocked(inputTargets, getTargetDisplayId(entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800882
883 // Dispatch the key.
884 dispatchEventLocked(currentTime, entry, inputTargets);
885 return true;
886}
887
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800888void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800889#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100890 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
891 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
Arthur Hung82a4cad2018-11-15 12:10:30 +0800892 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800893 prefix,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100894 entry->eventTime, entry->deviceId, entry->source, entry->displayId, entry->policyFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800895 entry->action, entry->flags, entry->keyCode, entry->scanCode, entry->metaState,
Arthur Hung82a4cad2018-11-15 12:10:30 +0800896 entry->repeatCount, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800897#endif
898}
899
900bool InputDispatcher::dispatchMotionLocked(
901 nsecs_t currentTime, MotionEntry* entry, DropReason* dropReason, nsecs_t* nextWakeupTime) {
902 // Preprocessing.
903 if (! entry->dispatchInProgress) {
904 entry->dispatchInProgress = true;
905
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800906 logOutboundMotionDetails("dispatchMotion - ", entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800907 }
908
909 // Clean up if dropping the event.
910 if (*dropReason != DROP_REASON_NOT_DROPPED) {
Siarhei Vishniakou62683e82019-03-06 17:59:56 -0800911 setInjectionResult(entry, *dropReason == DROP_REASON_POLICY
Michael Wrightd02c5b62014-02-10 15:10:22 -0800912 ? INPUT_EVENT_INJECTION_SUCCEEDED : INPUT_EVENT_INJECTION_FAILED);
913 return true;
914 }
915
916 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
917
918 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800919 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800920
921 bool conflictingPointerActions = false;
922 int32_t injectionResult;
923 if (isPointerEvent) {
924 // Pointer event. (eg. touchscreen)
925 injectionResult = findTouchedWindowTargetsLocked(currentTime,
926 entry, inputTargets, nextWakeupTime, &conflictingPointerActions);
927 } else {
928 // Non touch event. (eg. trackball)
929 injectionResult = findFocusedWindowTargetsLocked(currentTime,
930 entry, inputTargets, nextWakeupTime);
931 }
932 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
933 return false;
934 }
935
Siarhei Vishniakou62683e82019-03-06 17:59:56 -0800936 setInjectionResult(entry, injectionResult);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800937 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
Michael Wrightfa13dcf2015-06-12 13:25:11 +0100938 if (injectionResult != INPUT_EVENT_INJECTION_PERMISSION_DENIED) {
939 CancelationOptions::Mode mode(isPointerEvent ?
940 CancelationOptions::CANCEL_POINTER_EVENTS :
941 CancelationOptions::CANCEL_NON_POINTER_EVENTS);
942 CancelationOptions options(mode, "input event injection failed");
943 synthesizeCancelationEventsForMonitorsLocked(options);
944 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800945 return true;
946 }
947
Arthur Hung2fbf37f2018-09-13 18:16:41 +0800948 // Add monitor channels from event's or focused display.
949 addMonitoringTargetsLocked(inputTargets, getTargetDisplayId(entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800950
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800951 if (isPointerEvent) {
952 ssize_t stateIndex = mTouchStatesByDisplay.indexOfKey(entry->displayId);
953 if (stateIndex >= 0) {
954 const TouchState& state = mTouchStatesByDisplay.valueAt(stateIndex);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800955 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800956 // The event has gone through these portal windows, so we add monitoring targets of
957 // the corresponding displays as well.
958 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800959 const InputWindowInfo* windowInfo = state.portalWindows[i]->getInfo();
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800960 addMonitoringTargetsLocked(inputTargets, windowInfo->portalToDisplayId,
961 -windowInfo->frameLeft, -windowInfo->frameTop);
962 }
963 }
964 }
965 }
966
Michael Wrightd02c5b62014-02-10 15:10:22 -0800967 // Dispatch the motion.
968 if (conflictingPointerActions) {
969 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
970 "conflicting pointer actions");
971 synthesizeCancelationEventsForAllConnectionsLocked(options);
972 }
973 dispatchEventLocked(currentTime, entry, inputTargets);
974 return true;
975}
976
977
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800978void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800979#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800980 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
981 ", policyFlags=0x%x, "
Michael Wright7b159c92015-05-14 14:48:03 +0100982 "action=0x%x, actionButton=0x%x, flags=0x%x, "
983 "metaState=0x%x, buttonState=0x%x,"
Arthur Hung82a4cad2018-11-15 12:10:30 +0800984 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800985 prefix,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800986 entry->eventTime, entry->deviceId, entry->source, entry->displayId, entry->policyFlags,
Michael Wrightfa13dcf2015-06-12 13:25:11 +0100987 entry->action, entry->actionButton, entry->flags,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800988 entry->metaState, entry->buttonState,
989 entry->edgeFlags, entry->xPrecision, entry->yPrecision,
Arthur Hung82a4cad2018-11-15 12:10:30 +0800990 entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800991
992 for (uint32_t i = 0; i < entry->pointerCount; i++) {
993 ALOGD(" Pointer %d: id=%d, toolType=%d, "
994 "x=%f, y=%f, pressure=%f, size=%f, "
995 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -0800996 "orientation=%f",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800997 i, entry->pointerProperties[i].id,
998 entry->pointerProperties[i].toolType,
999 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1000 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1001 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1002 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1003 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1004 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1005 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1006 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08001007 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001008 }
1009#endif
1010}
1011
1012void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001013 EventEntry* eventEntry, const std::vector<InputTarget>& inputTargets) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001014#if DEBUG_DISPATCH_CYCLE
1015 ALOGD("dispatchEventToCurrentInputTargets");
1016#endif
1017
1018 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1019
1020 pokeUserActivityLocked(eventEntry);
1021
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001022 for (const InputTarget& inputTarget : inputTargets) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001023 ssize_t connectionIndex = getConnectionIndexLocked(inputTarget.inputChannel);
1024 if (connectionIndex >= 0) {
1025 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
1026 prepareDispatchCycleLocked(currentTime, connection, eventEntry, &inputTarget);
1027 } else {
1028#if DEBUG_FOCUS
1029 ALOGD("Dropping event delivery to target with channel '%s' because it "
1030 "is no longer registered with the input dispatcher.",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001031 inputTarget.inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001032#endif
1033 }
1034 }
1035}
1036
1037int32_t InputDispatcher::handleTargetsNotReadyLocked(nsecs_t currentTime,
1038 const EventEntry* entry,
1039 const sp<InputApplicationHandle>& applicationHandle,
1040 const sp<InputWindowHandle>& windowHandle,
1041 nsecs_t* nextWakeupTime, const char* reason) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001042 if (applicationHandle == nullptr && windowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001043 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY) {
1044#if DEBUG_FOCUS
1045 ALOGD("Waiting for system to become ready for input. Reason: %s", reason);
1046#endif
1047 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY;
1048 mInputTargetWaitStartTime = currentTime;
1049 mInputTargetWaitTimeoutTime = LONG_LONG_MAX;
1050 mInputTargetWaitTimeoutExpired = false;
Robert Carr740167f2018-10-11 19:03:41 -07001051 mInputTargetWaitApplicationToken.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001052 }
1053 } else {
1054 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
1055#if DEBUG_FOCUS
1056 ALOGD("Waiting for application to become ready for input: %s. Reason: %s",
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001057 getApplicationWindowLabel(applicationHandle, windowHandle).c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08001058 reason);
1059#endif
1060 nsecs_t timeout;
Yi Kong9b14ac62018-07-17 13:48:38 -07001061 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001062 timeout = windowHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Yi Kong9b14ac62018-07-17 13:48:38 -07001063 } else if (applicationHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001064 timeout = applicationHandle->getDispatchingTimeout(
1065 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
1066 } else {
1067 timeout = DEFAULT_INPUT_DISPATCHING_TIMEOUT;
1068 }
1069
1070 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY;
1071 mInputTargetWaitStartTime = currentTime;
1072 mInputTargetWaitTimeoutTime = currentTime + timeout;
1073 mInputTargetWaitTimeoutExpired = false;
Robert Carr740167f2018-10-11 19:03:41 -07001074 mInputTargetWaitApplicationToken.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001075
Yi Kong9b14ac62018-07-17 13:48:38 -07001076 if (windowHandle != nullptr) {
Robert Carr740167f2018-10-11 19:03:41 -07001077 mInputTargetWaitApplicationToken = windowHandle->getApplicationToken();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001078 }
Robert Carr740167f2018-10-11 19:03:41 -07001079 if (mInputTargetWaitApplicationToken == nullptr && applicationHandle != nullptr) {
1080 mInputTargetWaitApplicationToken = applicationHandle->getApplicationToken();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001081 }
1082 }
1083 }
1084
1085 if (mInputTargetWaitTimeoutExpired) {
1086 return INPUT_EVENT_INJECTION_TIMED_OUT;
1087 }
1088
1089 if (currentTime >= mInputTargetWaitTimeoutTime) {
1090 onANRLocked(currentTime, applicationHandle, windowHandle,
1091 entry->eventTime, mInputTargetWaitStartTime, reason);
1092
1093 // Force poll loop to wake up immediately on next iteration once we get the
1094 // ANR response back from the policy.
1095 *nextWakeupTime = LONG_LONG_MIN;
1096 return INPUT_EVENT_INJECTION_PENDING;
1097 } else {
1098 // Force poll loop to wake up when timeout is due.
1099 if (mInputTargetWaitTimeoutTime < *nextWakeupTime) {
1100 *nextWakeupTime = mInputTargetWaitTimeoutTime;
1101 }
1102 return INPUT_EVENT_INJECTION_PENDING;
1103 }
1104}
1105
Robert Carr803535b2018-08-02 16:38:15 -07001106void InputDispatcher::removeWindowByTokenLocked(const sp<IBinder>& token) {
1107 for (size_t d = 0; d < mTouchStatesByDisplay.size(); d++) {
1108 TouchState& state = mTouchStatesByDisplay.editValueAt(d);
1109 state.removeWindowByToken(token);
1110 }
1111}
1112
Michael Wrightd02c5b62014-02-10 15:10:22 -08001113void InputDispatcher::resumeAfterTargetsNotReadyTimeoutLocked(nsecs_t newTimeout,
1114 const sp<InputChannel>& inputChannel) {
1115 if (newTimeout > 0) {
1116 // Extend the timeout.
1117 mInputTargetWaitTimeoutTime = now() + newTimeout;
1118 } else {
1119 // Give up.
1120 mInputTargetWaitTimeoutExpired = true;
1121
1122 // Input state will not be realistic. Mark it out of sync.
1123 if (inputChannel.get()) {
1124 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
1125 if (connectionIndex >= 0) {
1126 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
Robert Carr803535b2018-08-02 16:38:15 -07001127 sp<IBinder> token = connection->inputChannel->getToken();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001128
Robert Carr803535b2018-08-02 16:38:15 -07001129 if (token != nullptr) {
1130 removeWindowByTokenLocked(token);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001131 }
1132
1133 if (connection->status == Connection::STATUS_NORMAL) {
1134 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1135 "application not responding");
1136 synthesizeCancelationEventsForConnectionLocked(connection, options);
1137 }
1138 }
1139 }
1140 }
1141}
1142
1143nsecs_t InputDispatcher::getTimeSpentWaitingForApplicationLocked(
1144 nsecs_t currentTime) {
1145 if (mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
1146 return currentTime - mInputTargetWaitStartTime;
1147 }
1148 return 0;
1149}
1150
1151void InputDispatcher::resetANRTimeoutsLocked() {
1152#if DEBUG_FOCUS
1153 ALOGD("Resetting ANR timeouts.");
1154#endif
1155
1156 // Reset input target wait timeout.
1157 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_NONE;
Robert Carr740167f2018-10-11 19:03:41 -07001158 mInputTargetWaitApplicationToken.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001159}
1160
Tiger Huang721e26f2018-07-24 22:26:19 +08001161/**
1162 * Get the display id that the given event should go to. If this event specifies a valid display id,
1163 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1164 * Focused display is the display that the user most recently interacted with.
1165 */
1166int32_t InputDispatcher::getTargetDisplayId(const EventEntry* entry) {
1167 int32_t displayId;
1168 switch (entry->type) {
1169 case EventEntry::TYPE_KEY: {
1170 const KeyEntry* typedEntry = static_cast<const KeyEntry*>(entry);
1171 displayId = typedEntry->displayId;
1172 break;
1173 }
1174 case EventEntry::TYPE_MOTION: {
1175 const MotionEntry* typedEntry = static_cast<const MotionEntry*>(entry);
1176 displayId = typedEntry->displayId;
1177 break;
1178 }
1179 default: {
1180 ALOGE("Unsupported event type '%" PRId32 "' for target display.", entry->type);
1181 return ADISPLAY_ID_NONE;
1182 }
1183 }
1184 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1185}
1186
Michael Wrightd02c5b62014-02-10 15:10:22 -08001187int32_t InputDispatcher::findFocusedWindowTargetsLocked(nsecs_t currentTime,
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001188 const EventEntry* entry, std::vector<InputTarget>& inputTargets, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001189 int32_t injectionResult;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001190 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001191
Tiger Huang721e26f2018-07-24 22:26:19 +08001192 int32_t displayId = getTargetDisplayId(entry);
1193 sp<InputWindowHandle> focusedWindowHandle =
1194 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
1195 sp<InputApplicationHandle> focusedApplicationHandle =
1196 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1197
Michael Wrightd02c5b62014-02-10 15:10:22 -08001198 // If there is no currently focused window and no focused application
1199 // then drop the event.
Tiger Huang721e26f2018-07-24 22:26:19 +08001200 if (focusedWindowHandle == nullptr) {
1201 if (focusedApplicationHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001202 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Tiger Huang721e26f2018-07-24 22:26:19 +08001203 focusedApplicationHandle, nullptr, nextWakeupTime,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001204 "Waiting because no window has focus but there is a "
1205 "focused application that may eventually add a window "
1206 "when it finishes starting up.");
1207 goto Unresponsive;
1208 }
1209
Arthur Hung3b413f22018-10-26 18:05:34 +08001210 ALOGI("Dropping event because there is no focused window or focused application in display "
1211 "%" PRId32 ".", displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001212 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1213 goto Failed;
1214 }
1215
1216 // Check permissions.
Tiger Huang721e26f2018-07-24 22:26:19 +08001217 if (!checkInjectionPermission(focusedWindowHandle, entry->injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001218 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1219 goto Failed;
1220 }
1221
Jeff Brownffb49772014-10-10 19:01:34 -07001222 // Check whether the window is ready for more input.
1223 reason = checkWindowReadyForMoreInputLocked(currentTime,
Tiger Huang721e26f2018-07-24 22:26:19 +08001224 focusedWindowHandle, entry, "focused");
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001225 if (!reason.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001226 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Tiger Huang721e26f2018-07-24 22:26:19 +08001227 focusedApplicationHandle, focusedWindowHandle, nextWakeupTime, reason.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001228 goto Unresponsive;
1229 }
1230
1231 // Success! Output targets.
1232 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
Tiger Huang721e26f2018-07-24 22:26:19 +08001233 addWindowTargetLocked(focusedWindowHandle,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001234 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS, BitSet32(0),
1235 inputTargets);
1236
1237 // Done.
1238Failed:
1239Unresponsive:
1240 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001241 updateDispatchStatistics(currentTime, entry, injectionResult, timeSpentWaitingForApplication);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001242#if DEBUG_FOCUS
1243 ALOGD("findFocusedWindow finished: injectionResult=%d, "
1244 "timeSpentWaitingForApplication=%0.1fms",
1245 injectionResult, timeSpentWaitingForApplication / 1000000.0);
1246#endif
1247 return injectionResult;
1248}
1249
1250int32_t InputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime,
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001251 const MotionEntry* entry, std::vector<InputTarget>& inputTargets, nsecs_t* nextWakeupTime,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001252 bool* outConflictingPointerActions) {
1253 enum InjectionPermission {
1254 INJECTION_PERMISSION_UNKNOWN,
1255 INJECTION_PERMISSION_GRANTED,
1256 INJECTION_PERMISSION_DENIED
1257 };
1258
Michael Wrightd02c5b62014-02-10 15:10:22 -08001259 // For security reasons, we defer updating the touch state until we are sure that
1260 // event injection will be allowed.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001261 int32_t displayId = entry->displayId;
1262 int32_t action = entry->action;
1263 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
1264
1265 // Update the touch state as needed based on the properties of the touch event.
1266 int32_t injectionResult = INPUT_EVENT_INJECTION_PENDING;
1267 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
1268 sp<InputWindowHandle> newHoverWindowHandle;
1269
Jeff Brownf086ddb2014-02-11 14:28:48 -08001270 // Copy current touch state into mTempTouchState.
1271 // This state is always reset at the end of this function, so if we don't find state
1272 // for the specified display then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07001273 const TouchState* oldState = nullptr;
Jeff Brownf086ddb2014-02-11 14:28:48 -08001274 ssize_t oldStateIndex = mTouchStatesByDisplay.indexOfKey(displayId);
1275 if (oldStateIndex >= 0) {
1276 oldState = &mTouchStatesByDisplay.valueAt(oldStateIndex);
1277 mTempTouchState.copyFrom(*oldState);
1278 }
1279
1280 bool isSplit = mTempTouchState.split;
1281 bool switchedDevice = mTempTouchState.deviceId >= 0 && mTempTouchState.displayId >= 0
1282 && (mTempTouchState.deviceId != entry->deviceId
1283 || mTempTouchState.source != entry->source
1284 || mTempTouchState.displayId != displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001285 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE
1286 || maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER
1287 || maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1288 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN
1289 || maskedAction == AMOTION_EVENT_ACTION_SCROLL
1290 || isHoverAction);
1291 bool wrongDevice = false;
1292 if (newGesture) {
1293 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001294 if (switchedDevice && mTempTouchState.down && !down && !isHoverAction) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001295#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08001296 ALOGD("Dropping event because a pointer for a different device is already down "
1297 "in display %" PRId32, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001298#endif
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001299 // TODO: test multiple simultaneous input streams.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001300 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1301 switchedDevice = false;
1302 wrongDevice = true;
1303 goto Failed;
1304 }
1305 mTempTouchState.reset();
1306 mTempTouchState.down = down;
1307 mTempTouchState.deviceId = entry->deviceId;
1308 mTempTouchState.source = entry->source;
1309 mTempTouchState.displayId = displayId;
1310 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001311 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
1312#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08001313 ALOGI("Dropping move event because a pointer for a different device is already active "
1314 "in display %" PRId32, displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001315#endif
1316 // TODO: test multiple simultaneous input streams.
1317 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1318 switchedDevice = false;
1319 wrongDevice = true;
1320 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001321 }
1322
1323 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
1324 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
1325
1326 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
1327 int32_t x = int32_t(entry->pointerCoords[pointerIndex].
1328 getAxisValue(AMOTION_EVENT_AXIS_X));
1329 int32_t y = int32_t(entry->pointerCoords[pointerIndex].
1330 getAxisValue(AMOTION_EVENT_AXIS_Y));
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001331 sp<InputWindowHandle> newTouchedWindowHandle = findTouchedWindowAtLocked(
1332 displayId, x, y, maskedAction == AMOTION_EVENT_ACTION_DOWN, true);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001333
Michael Wrightd02c5b62014-02-10 15:10:22 -08001334 // Figure out whether splitting will be allowed for this window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001335 if (newTouchedWindowHandle != nullptr
Michael Wrightd02c5b62014-02-10 15:10:22 -08001336 && newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
1337 // New window supports splitting.
1338 isSplit = true;
1339 } else if (isSplit) {
1340 // New window does not support splitting but we have already split events.
1341 // Ignore the new window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001342 newTouchedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001343 }
1344
1345 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001346 if (newTouchedWindowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001347 // Try to assign the pointer to the first foreground window we find, if there is one.
1348 newTouchedWindowHandle = mTempTouchState.getFirstForegroundWindowHandle();
Yi Kong9b14ac62018-07-17 13:48:38 -07001349 if (newTouchedWindowHandle == nullptr) {
Arthur Hung3b413f22018-10-26 18:05:34 +08001350 ALOGI("Dropping event because there is no touchable window at (%d, %d) in display "
1351 "%" PRId32 ".", x, y, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001352 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1353 goto Failed;
1354 }
1355 }
1356
1357 // Set target flags.
1358 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
1359 if (isSplit) {
1360 targetFlags |= InputTarget::FLAG_SPLIT;
1361 }
1362 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1363 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001364 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
1365 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001366 }
1367
1368 // Update hover state.
1369 if (isHoverAction) {
1370 newHoverWindowHandle = newTouchedWindowHandle;
1371 } else if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
1372 newHoverWindowHandle = mLastHoverWindowHandle;
1373 }
1374
1375 // Update the temporary touch state.
1376 BitSet32 pointerIds;
1377 if (isSplit) {
1378 uint32_t pointerId = entry->pointerProperties[pointerIndex].id;
1379 pointerIds.markBit(pointerId);
1380 }
1381 mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
1382 } else {
1383 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
1384
1385 // If the pointer is not currently down, then ignore the event.
1386 if (! mTempTouchState.down) {
1387#if DEBUG_FOCUS
1388 ALOGD("Dropping event because the pointer is not down or we previously "
Arthur Hung3b413f22018-10-26 18:05:34 +08001389 "dropped the pointer down event in display %" PRId32, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001390#endif
1391 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1392 goto Failed;
1393 }
1394
1395 // Check whether touches should slip outside of the current foreground window.
1396 if (maskedAction == AMOTION_EVENT_ACTION_MOVE
1397 && entry->pointerCount == 1
1398 && mTempTouchState.isSlippery()) {
1399 int32_t x = int32_t(entry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
1400 int32_t y = int32_t(entry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
1401
1402 sp<InputWindowHandle> oldTouchedWindowHandle =
1403 mTempTouchState.getFirstForegroundWindowHandle();
1404 sp<InputWindowHandle> newTouchedWindowHandle =
1405 findTouchedWindowAtLocked(displayId, x, y);
1406 if (oldTouchedWindowHandle != newTouchedWindowHandle
Yi Kong9b14ac62018-07-17 13:48:38 -07001407 && newTouchedWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001408#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08001409 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001410 oldTouchedWindowHandle->getName().c_str(),
Arthur Hung3b413f22018-10-26 18:05:34 +08001411 newTouchedWindowHandle->getName().c_str(),
1412 displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001413#endif
1414 // Make a slippery exit from the old window.
1415 mTempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
1416 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT, BitSet32(0));
1417
1418 // Make a slippery entrance into the new window.
1419 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
1420 isSplit = true;
1421 }
1422
1423 int32_t targetFlags = InputTarget::FLAG_FOREGROUND
1424 | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
1425 if (isSplit) {
1426 targetFlags |= InputTarget::FLAG_SPLIT;
1427 }
1428 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1429 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1430 }
1431
1432 BitSet32 pointerIds;
1433 if (isSplit) {
1434 pointerIds.markBit(entry->pointerProperties[0].id);
1435 }
1436 mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
1437 }
1438 }
1439 }
1440
1441 if (newHoverWindowHandle != mLastHoverWindowHandle) {
1442 // Let the previous window know that the hover sequence is over.
Yi Kong9b14ac62018-07-17 13:48:38 -07001443 if (mLastHoverWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001444#if DEBUG_HOVER
1445 ALOGD("Sending hover exit event to window %s.",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001446 mLastHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001447#endif
1448 mTempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
1449 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
1450 }
1451
1452 // Let the new window know that the hover sequence is starting.
Yi Kong9b14ac62018-07-17 13:48:38 -07001453 if (newHoverWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001454#if DEBUG_HOVER
1455 ALOGD("Sending hover enter event to window %s.",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001456 newHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001457#endif
1458 mTempTouchState.addOrUpdateWindow(newHoverWindowHandle,
1459 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER, BitSet32(0));
1460 }
1461 }
1462
1463 // Check permission to inject into all touched foreground windows and ensure there
1464 // is at least one touched foreground window.
1465 {
1466 bool haveForegroundWindow = false;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001467 for (const TouchedWindow& touchedWindow : mTempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001468 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1469 haveForegroundWindow = true;
1470 if (! checkInjectionPermission(touchedWindow.windowHandle,
1471 entry->injectionState)) {
1472 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1473 injectionPermission = INJECTION_PERMISSION_DENIED;
1474 goto Failed;
1475 }
1476 }
1477 }
1478 if (! haveForegroundWindow) {
1479#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08001480 ALOGD("Dropping event because there is no touched foreground window in display %" PRId32
1481 " to receive it.", displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001482#endif
1483 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1484 goto Failed;
1485 }
1486
1487 // Permission granted to injection into all touched foreground windows.
1488 injectionPermission = INJECTION_PERMISSION_GRANTED;
1489 }
1490
1491 // Check whether windows listening for outside touches are owned by the same UID. If it is
1492 // set the policy flag that we will not reveal coordinate information to this window.
1493 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1494 sp<InputWindowHandle> foregroundWindowHandle =
1495 mTempTouchState.getFirstForegroundWindowHandle();
1496 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001497 for (const TouchedWindow& touchedWindow : mTempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001498 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
1499 sp<InputWindowHandle> inputWindowHandle = touchedWindow.windowHandle;
1500 if (inputWindowHandle->getInfo()->ownerUid != foregroundWindowUid) {
1501 mTempTouchState.addOrUpdateWindow(inputWindowHandle,
1502 InputTarget::FLAG_ZERO_COORDS, BitSet32(0));
1503 }
1504 }
1505 }
1506 }
1507
1508 // Ensure all touched foreground windows are ready for new input.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001509 for (const TouchedWindow& touchedWindow : mTempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001510 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
Jeff Brownffb49772014-10-10 19:01:34 -07001511 // Check whether the window is ready for more input.
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001512 std::string reason = checkWindowReadyForMoreInputLocked(currentTime,
Jeff Brownffb49772014-10-10 19:01:34 -07001513 touchedWindow.windowHandle, entry, "touched");
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001514 if (!reason.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001515 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Yi Kong9b14ac62018-07-17 13:48:38 -07001516 nullptr, touchedWindow.windowHandle, nextWakeupTime, reason.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001517 goto Unresponsive;
1518 }
1519 }
1520 }
1521
1522 // If this is the first pointer going down and the touched window has a wallpaper
1523 // then also add the touched wallpaper windows so they are locked in for the duration
1524 // of the touch gesture.
1525 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
1526 // engine only supports touch events. We would need to add a mechanism similar
1527 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
1528 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1529 sp<InputWindowHandle> foregroundWindowHandle =
1530 mTempTouchState.getFirstForegroundWindowHandle();
1531 if (foregroundWindowHandle->getInfo()->hasWallpaper) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001532 const std::vector<sp<InputWindowHandle>> windowHandles =
1533 getWindowHandlesLocked(displayId);
1534 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001535 const InputWindowInfo* info = windowHandle->getInfo();
1536 if (info->displayId == displayId
1537 && windowHandle->getInfo()->layoutParamsType
1538 == InputWindowInfo::TYPE_WALLPAPER) {
1539 mTempTouchState.addOrUpdateWindow(windowHandle,
1540 InputTarget::FLAG_WINDOW_IS_OBSCURED
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001541 | InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED
Michael Wrightd02c5b62014-02-10 15:10:22 -08001542 | InputTarget::FLAG_DISPATCH_AS_IS,
1543 BitSet32(0));
1544 }
1545 }
1546 }
1547 }
1548
1549 // Success! Output targets.
1550 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
1551
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001552 for (const TouchedWindow& touchedWindow : mTempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001553 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
1554 touchedWindow.pointerIds, inputTargets);
1555 }
1556
1557 // Drop the outside or hover touch windows since we will not care about them
1558 // in the next iteration.
1559 mTempTouchState.filterNonAsIsTouchWindows();
1560
1561Failed:
1562 // Check injection permission once and for all.
1563 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001564 if (checkInjectionPermission(nullptr, entry->injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001565 injectionPermission = INJECTION_PERMISSION_GRANTED;
1566 } else {
1567 injectionPermission = INJECTION_PERMISSION_DENIED;
1568 }
1569 }
1570
1571 // Update final pieces of touch state if the injector had permission.
1572 if (injectionPermission == INJECTION_PERMISSION_GRANTED) {
1573 if (!wrongDevice) {
1574 if (switchedDevice) {
1575#if DEBUG_FOCUS
1576 ALOGD("Conflicting pointer actions: Switched to a different device.");
1577#endif
1578 *outConflictingPointerActions = true;
1579 }
1580
1581 if (isHoverAction) {
1582 // Started hovering, therefore no longer down.
Jeff Brownf086ddb2014-02-11 14:28:48 -08001583 if (oldState && oldState->down) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001584#if DEBUG_FOCUS
1585 ALOGD("Conflicting pointer actions: Hover received while pointer was down.");
1586#endif
1587 *outConflictingPointerActions = true;
1588 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08001589 mTempTouchState.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001590 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER
1591 || maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Jeff Brownf086ddb2014-02-11 14:28:48 -08001592 mTempTouchState.deviceId = entry->deviceId;
1593 mTempTouchState.source = entry->source;
1594 mTempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001595 }
1596 } else if (maskedAction == AMOTION_EVENT_ACTION_UP
1597 || maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
1598 // All pointers up or canceled.
Jeff Brownf086ddb2014-02-11 14:28:48 -08001599 mTempTouchState.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001600 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1601 // First pointer went down.
Jeff Brownf086ddb2014-02-11 14:28:48 -08001602 if (oldState && oldState->down) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001603#if DEBUG_FOCUS
1604 ALOGD("Conflicting pointer actions: Down received while already down.");
1605#endif
1606 *outConflictingPointerActions = true;
1607 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001608 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
1609 // One pointer went up.
1610 if (isSplit) {
1611 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
1612 uint32_t pointerId = entry->pointerProperties[pointerIndex].id;
1613
1614 for (size_t i = 0; i < mTempTouchState.windows.size(); ) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001615 TouchedWindow& touchedWindow = mTempTouchState.windows[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08001616 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
1617 touchedWindow.pointerIds.clearBit(pointerId);
1618 if (touchedWindow.pointerIds.isEmpty()) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001619 mTempTouchState.windows.erase(mTempTouchState.windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001620 continue;
1621 }
1622 }
1623 i += 1;
1624 }
1625 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08001626 }
1627
1628 // Save changes unless the action was scroll in which case the temporary touch
1629 // state was only valid for this one action.
1630 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
1631 if (mTempTouchState.displayId >= 0) {
1632 if (oldStateIndex >= 0) {
1633 mTouchStatesByDisplay.editValueAt(oldStateIndex).copyFrom(mTempTouchState);
1634 } else {
1635 mTouchStatesByDisplay.add(displayId, mTempTouchState);
1636 }
1637 } else if (oldStateIndex >= 0) {
1638 mTouchStatesByDisplay.removeItemsAt(oldStateIndex);
1639 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001640 }
1641
1642 // Update hover state.
1643 mLastHoverWindowHandle = newHoverWindowHandle;
1644 }
1645 } else {
1646#if DEBUG_FOCUS
1647 ALOGD("Not updating touch focus because injection was denied.");
1648#endif
1649 }
1650
1651Unresponsive:
1652 // Reset temporary touch state to ensure we release unnecessary references to input channels.
1653 mTempTouchState.reset();
1654
1655 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001656 updateDispatchStatistics(currentTime, entry, injectionResult, timeSpentWaitingForApplication);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001657#if DEBUG_FOCUS
1658 ALOGD("findTouchedWindow finished: injectionResult=%d, injectionPermission=%d, "
1659 "timeSpentWaitingForApplication=%0.1fms",
1660 injectionResult, injectionPermission, timeSpentWaitingForApplication / 1000000.0);
1661#endif
1662 return injectionResult;
1663}
1664
1665void InputDispatcher::addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001666 int32_t targetFlags, BitSet32 pointerIds, std::vector<InputTarget>& inputTargets) {
Arthur Hungceeb5d72018-12-05 16:14:18 +08001667 sp<InputChannel> inputChannel = getInputChannelLocked(windowHandle->getToken());
1668 if (inputChannel == nullptr) {
1669 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
1670 return;
1671 }
1672
Michael Wrightd02c5b62014-02-10 15:10:22 -08001673 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001674 InputTarget target;
Arthur Hungceeb5d72018-12-05 16:14:18 +08001675 target.inputChannel = inputChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001676 target.flags = targetFlags;
1677 target.xOffset = - windowInfo->frameLeft;
1678 target.yOffset = - windowInfo->frameTop;
Robert Carre07e1032018-11-26 12:55:53 -08001679 target.globalScaleFactor = windowInfo->globalScaleFactor;
1680 target.windowXScale = windowInfo->windowXScale;
1681 target.windowYScale = windowInfo->windowYScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001682 target.pointerIds = pointerIds;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001683 inputTargets.push_back(target);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001684}
1685
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001686void InputDispatcher::addMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001687 int32_t displayId, float xOffset, float yOffset) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001688 std::unordered_map<int32_t, std::vector<sp<InputChannel>>>::const_iterator it =
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001689 mMonitoringChannelsByDisplay.find(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001690
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001691 if (it != mMonitoringChannelsByDisplay.end()) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001692 const std::vector<sp<InputChannel>>& monitoringChannels = it->second;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001693 const size_t numChannels = monitoringChannels.size();
1694 for (size_t i = 0; i < numChannels; i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001695 InputTarget target;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001696 target.inputChannel = monitoringChannels[i];
1697 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001698 target.xOffset = xOffset;
1699 target.yOffset = yOffset;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001700 target.pointerIds.clear();
Robert Carre07e1032018-11-26 12:55:53 -08001701 target.globalScaleFactor = 1.0f;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001702 inputTargets.push_back(target);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001703 }
1704 } else {
1705 // If there is no monitor channel registered or all monitor channel unregistered,
1706 // the display can't detect the extra system gesture by a copy of input events.
Arthur Hung3b413f22018-10-26 18:05:34 +08001707 ALOGW("There is no monitor channel found in display %" PRId32, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001708 }
1709}
1710
1711bool InputDispatcher::checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
1712 const InjectionState* injectionState) {
1713 if (injectionState
Yi Kong9b14ac62018-07-17 13:48:38 -07001714 && (windowHandle == nullptr
Michael Wrightd02c5b62014-02-10 15:10:22 -08001715 || windowHandle->getInfo()->ownerUid != injectionState->injectorUid)
1716 && !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001717 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001718 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
1719 "owned by uid %d",
1720 injectionState->injectorPid, injectionState->injectorUid,
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001721 windowHandle->getName().c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08001722 windowHandle->getInfo()->ownerUid);
1723 } else {
1724 ALOGW("Permission denied: injecting event from pid %d uid %d",
1725 injectionState->injectorPid, injectionState->injectorUid);
1726 }
1727 return false;
1728 }
1729 return true;
1730}
1731
1732bool InputDispatcher::isWindowObscuredAtPointLocked(
1733 const sp<InputWindowHandle>& windowHandle, int32_t x, int32_t y) const {
1734 int32_t displayId = windowHandle->getInfo()->displayId;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001735 const std::vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
1736 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001737 if (otherHandle == windowHandle) {
1738 break;
1739 }
1740
1741 const InputWindowInfo* otherInfo = otherHandle->getInfo();
1742 if (otherInfo->displayId == displayId
1743 && otherInfo->visible && !otherInfo->isTrustedOverlay()
1744 && otherInfo->frameContainsPoint(x, y)) {
1745 return true;
1746 }
1747 }
1748 return false;
1749}
1750
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001751
1752bool InputDispatcher::isWindowObscuredLocked(const sp<InputWindowHandle>& windowHandle) const {
1753 int32_t displayId = windowHandle->getInfo()->displayId;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001754 const std::vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001755 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001756 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001757 if (otherHandle == windowHandle) {
1758 break;
1759 }
1760
1761 const InputWindowInfo* otherInfo = otherHandle->getInfo();
1762 if (otherInfo->displayId == displayId
1763 && otherInfo->visible && !otherInfo->isTrustedOverlay()
1764 && otherInfo->overlaps(windowInfo)) {
1765 return true;
1766 }
1767 }
1768 return false;
1769}
1770
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001771std::string InputDispatcher::checkWindowReadyForMoreInputLocked(nsecs_t currentTime,
Jeff Brownffb49772014-10-10 19:01:34 -07001772 const sp<InputWindowHandle>& windowHandle, const EventEntry* eventEntry,
1773 const char* targetType) {
1774 // If the window is paused then keep waiting.
1775 if (windowHandle->getInfo()->paused) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001776 return StringPrintf("Waiting because the %s window is paused.", targetType);
Jeff Brownffb49772014-10-10 19:01:34 -07001777 }
1778
1779 // If the window's connection is not registered then keep waiting.
Robert Carr5c8a0262018-10-03 16:30:44 -07001780 ssize_t connectionIndex = getConnectionIndexLocked(
1781 getInputChannelLocked(windowHandle->getToken()));
Jeff Brownffb49772014-10-10 19:01:34 -07001782 if (connectionIndex < 0) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001783 return StringPrintf("Waiting because the %s window's input channel is not "
Jeff Brownffb49772014-10-10 19:01:34 -07001784 "registered with the input dispatcher. The window may be in the process "
1785 "of being removed.", targetType);
1786 }
1787
1788 // If the connection is dead then keep waiting.
1789 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
1790 if (connection->status != Connection::STATUS_NORMAL) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001791 return StringPrintf("Waiting because the %s window's input connection is %s."
Jeff Brownffb49772014-10-10 19:01:34 -07001792 "The window may be in the process of being removed.", targetType,
1793 connection->getStatusLabel());
1794 }
1795
1796 // If the connection is backed up then keep waiting.
1797 if (connection->inputPublisherBlocked) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001798 return StringPrintf("Waiting because the %s window's input channel is full. "
Jeff Brownffb49772014-10-10 19:01:34 -07001799 "Outbound queue length: %d. Wait queue length: %d.",
1800 targetType, connection->outboundQueue.count(), connection->waitQueue.count());
1801 }
1802
1803 // Ensure that the dispatch queues aren't too far backed up for this event.
1804 if (eventEntry->type == EventEntry::TYPE_KEY) {
1805 // If the event is a key event, then we must wait for all previous events to
1806 // complete before delivering it because previous events may have the
1807 // side-effect of transferring focus to a different window and we want to
1808 // ensure that the following keys are sent to the new window.
1809 //
1810 // Suppose the user touches a button in a window then immediately presses "A".
1811 // If the button causes a pop-up window to appear then we want to ensure that
1812 // the "A" key is delivered to the new pop-up window. This is because users
1813 // often anticipate pending UI changes when typing on a keyboard.
1814 // To obtain this behavior, we must serialize key events with respect to all
1815 // prior input events.
1816 if (!connection->outboundQueue.isEmpty() || !connection->waitQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001817 return StringPrintf("Waiting to send key event because the %s window has not "
Jeff Brownffb49772014-10-10 19:01:34 -07001818 "finished processing all of the input events that were previously "
1819 "delivered to it. Outbound queue length: %d. Wait queue length: %d.",
1820 targetType, connection->outboundQueue.count(), connection->waitQueue.count());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001821 }
Jeff Brownffb49772014-10-10 19:01:34 -07001822 } else {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001823 // Touch events can always be sent to a window immediately because the user intended
1824 // to touch whatever was visible at the time. Even if focus changes or a new
1825 // window appears moments later, the touch event was meant to be delivered to
1826 // whatever window happened to be on screen at the time.
1827 //
1828 // Generic motion events, such as trackball or joystick events are a little trickier.
1829 // Like key events, generic motion events are delivered to the focused window.
1830 // Unlike key events, generic motion events don't tend to transfer focus to other
1831 // windows and it is not important for them to be serialized. So we prefer to deliver
1832 // generic motion events as soon as possible to improve efficiency and reduce lag
1833 // through batching.
1834 //
1835 // The one case where we pause input event delivery is when the wait queue is piling
1836 // up with lots of events because the application is not responding.
1837 // This condition ensures that ANRs are detected reliably.
1838 if (!connection->waitQueue.isEmpty()
1839 && currentTime >= connection->waitQueue.head->deliveryTime
1840 + STREAM_AHEAD_EVENT_TIMEOUT) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001841 return StringPrintf("Waiting to send non-key event because the %s window has not "
Jeff Brownffb49772014-10-10 19:01:34 -07001842 "finished processing certain input events that were delivered to it over "
1843 "%0.1fms ago. Wait queue length: %d. Wait queue head age: %0.1fms.",
1844 targetType, STREAM_AHEAD_EVENT_TIMEOUT * 0.000001f,
1845 connection->waitQueue.count(),
1846 (currentTime - connection->waitQueue.head->deliveryTime) * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001847 }
1848 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001849 return "";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001850}
1851
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001852std::string InputDispatcher::getApplicationWindowLabel(
Michael Wrightd02c5b62014-02-10 15:10:22 -08001853 const sp<InputApplicationHandle>& applicationHandle,
1854 const sp<InputWindowHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001855 if (applicationHandle != nullptr) {
1856 if (windowHandle != nullptr) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001857 std::string label(applicationHandle->getName());
1858 label += " - ";
1859 label += windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001860 return label;
1861 } else {
1862 return applicationHandle->getName();
1863 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001864 } else if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001865 return windowHandle->getName();
1866 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001867 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001868 }
1869}
1870
1871void InputDispatcher::pokeUserActivityLocked(const EventEntry* eventEntry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001872 int32_t displayId = getTargetDisplayId(eventEntry);
1873 sp<InputWindowHandle> focusedWindowHandle =
1874 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
1875 if (focusedWindowHandle != nullptr) {
1876 const InputWindowInfo* info = focusedWindowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001877 if (info->inputFeatures & InputWindowInfo::INPUT_FEATURE_DISABLE_USER_ACTIVITY) {
1878#if DEBUG_DISPATCH_CYCLE
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001879 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001880#endif
1881 return;
1882 }
1883 }
1884
1885 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
1886 switch (eventEntry->type) {
1887 case EventEntry::TYPE_MOTION: {
1888 const MotionEntry* motionEntry = static_cast<const MotionEntry*>(eventEntry);
1889 if (motionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
1890 return;
1891 }
1892
1893 if (MotionEvent::isTouchEvent(motionEntry->source, motionEntry->action)) {
1894 eventType = USER_ACTIVITY_EVENT_TOUCH;
1895 }
1896 break;
1897 }
1898 case EventEntry::TYPE_KEY: {
1899 const KeyEntry* keyEntry = static_cast<const KeyEntry*>(eventEntry);
1900 if (keyEntry->flags & AKEY_EVENT_FLAG_CANCELED) {
1901 return;
1902 }
1903 eventType = USER_ACTIVITY_EVENT_BUTTON;
1904 break;
1905 }
1906 }
1907
1908 CommandEntry* commandEntry = postCommandLocked(
1909 & InputDispatcher::doPokeUserActivityLockedInterruptible);
1910 commandEntry->eventTime = eventEntry->eventTime;
1911 commandEntry->userActivityEventType = eventType;
1912}
1913
1914void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
1915 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget) {
1916#if DEBUG_DISPATCH_CYCLE
1917 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
Robert Carre07e1032018-11-26 12:55:53 -08001918 "xOffset=%f, yOffset=%f, globalScaleFactor=%f, "
1919 "windowScaleFactor=(%f, %f), pointerIds=0x%x",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08001920 connection->getInputChannelName().c_str(), inputTarget->flags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001921 inputTarget->xOffset, inputTarget->yOffset,
Robert Carre07e1032018-11-26 12:55:53 -08001922 inputTarget->globalScaleFactor,
1923 inputTarget->windowXScale, inputTarget->windowYScale,
1924 inputTarget->pointerIds.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001925#endif
1926
1927 // Skip this event if the connection status is not normal.
1928 // We don't want to enqueue additional outbound events if the connection is broken.
1929 if (connection->status != Connection::STATUS_NORMAL) {
1930#if DEBUG_DISPATCH_CYCLE
1931 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08001932 connection->getInputChannelName().c_str(), connection->getStatusLabel());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001933#endif
1934 return;
1935 }
1936
1937 // Split a motion event if needed.
1938 if (inputTarget->flags & InputTarget::FLAG_SPLIT) {
1939 ALOG_ASSERT(eventEntry->type == EventEntry::TYPE_MOTION);
1940
1941 MotionEntry* originalMotionEntry = static_cast<MotionEntry*>(eventEntry);
1942 if (inputTarget->pointerIds.count() != originalMotionEntry->pointerCount) {
1943 MotionEntry* splitMotionEntry = splitMotionEvent(
1944 originalMotionEntry, inputTarget->pointerIds);
1945 if (!splitMotionEntry) {
1946 return; // split event was dropped
1947 }
1948#if DEBUG_FOCUS
1949 ALOGD("channel '%s' ~ Split motion event.",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08001950 connection->getInputChannelName().c_str());
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001951 logOutboundMotionDetails(" ", splitMotionEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001952#endif
1953 enqueueDispatchEntriesLocked(currentTime, connection,
1954 splitMotionEntry, inputTarget);
1955 splitMotionEntry->release();
1956 return;
1957 }
1958 }
1959
1960 // Not splitting. Enqueue dispatch entries for the event as is.
1961 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
1962}
1963
1964void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
1965 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget) {
1966 bool wasEmpty = connection->outboundQueue.isEmpty();
1967
1968 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07001969 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001970 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07001971 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001972 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07001973 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001974 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07001975 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001976 InputTarget::FLAG_DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07001977 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001978 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07001979 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001980 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
1981
1982 // If the outbound queue was previously empty, start the dispatch cycle going.
1983 if (wasEmpty && !connection->outboundQueue.isEmpty()) {
1984 startDispatchCycleLocked(currentTime, connection);
1985 }
1986}
1987
chaviw8c9cf542019-03-25 13:02:48 -07001988void InputDispatcher::enqueueDispatchEntryLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08001989 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget,
1990 int32_t dispatchMode) {
1991 int32_t inputTargetFlags = inputTarget->flags;
1992 if (!(inputTargetFlags & dispatchMode)) {
1993 return;
1994 }
1995 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
1996
1997 // This is a new event.
1998 // Enqueue a new dispatch entry onto the outbound queue for this connection.
1999 DispatchEntry* dispatchEntry = new DispatchEntry(eventEntry, // increments ref
2000 inputTargetFlags, inputTarget->xOffset, inputTarget->yOffset,
Robert Carre07e1032018-11-26 12:55:53 -08002001 inputTarget->globalScaleFactor, inputTarget->windowXScale,
2002 inputTarget->windowYScale);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002003
2004 // Apply target flags and update the connection's input state.
2005 switch (eventEntry->type) {
2006 case EventEntry::TYPE_KEY: {
2007 KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
2008 dispatchEntry->resolvedAction = keyEntry->action;
2009 dispatchEntry->resolvedFlags = keyEntry->flags;
2010
2011 if (!connection->inputState.trackKey(keyEntry,
2012 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags)) {
2013#if DEBUG_DISPATCH_CYCLE
2014 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002015 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002016#endif
2017 delete dispatchEntry;
2018 return; // skip the inconsistent event
2019 }
2020 break;
2021 }
2022
2023 case EventEntry::TYPE_MOTION: {
2024 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
2025 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2026 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
2027 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
2028 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
2029 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
2030 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2031 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
2032 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
2033 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
2034 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
2035 } else {
2036 dispatchEntry->resolvedAction = motionEntry->action;
2037 }
2038 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE
2039 && !connection->inputState.isHovering(
2040 motionEntry->deviceId, motionEntry->source, motionEntry->displayId)) {
2041#if DEBUG_DISPATCH_CYCLE
2042 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter event",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002043 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002044#endif
2045 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2046 }
2047
2048 dispatchEntry->resolvedFlags = motionEntry->flags;
2049 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
2050 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
2051 }
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002052 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
2053 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2054 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002055
2056 if (!connection->inputState.trackMotion(motionEntry,
2057 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags)) {
2058#if DEBUG_DISPATCH_CYCLE
2059 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion event",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002060 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002061#endif
2062 delete dispatchEntry;
2063 return; // skip the inconsistent event
2064 }
chaviw8c9cf542019-03-25 13:02:48 -07002065
2066 dispatchPointerDownOutsideFocusIfNecessary(motionEntry->source,
2067 dispatchEntry->resolvedAction, inputTarget->inputChannel->getToken());
2068
Michael Wrightd02c5b62014-02-10 15:10:22 -08002069 break;
2070 }
2071 }
2072
2073 // Remember that we are waiting for this dispatch to complete.
2074 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002075 incrementPendingForegroundDispatches(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002076 }
2077
2078 // Enqueue the dispatch entry.
2079 connection->outboundQueue.enqueueAtTail(dispatchEntry);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002080 traceOutboundQueueLength(connection);
chaviw8c9cf542019-03-25 13:02:48 -07002081
2082}
2083
2084void InputDispatcher::dispatchPointerDownOutsideFocusIfNecessary(uint32_t source, int32_t action,
2085 const sp<IBinder>& newToken) {
2086 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
2087 if (source != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
2088 return;
2089 }
2090
2091 sp<InputWindowHandle> inputWindowHandle = getWindowHandleLocked(newToken);
2092 if (inputWindowHandle == nullptr) {
2093 return;
2094 }
2095
2096 int32_t displayId = inputWindowHandle->getInfo()->displayId;
2097 sp<InputWindowHandle> focusedWindowHandle =
2098 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
2099
2100 bool hasFocusChanged = !focusedWindowHandle || focusedWindowHandle->getToken() != newToken;
2101
2102 if (!hasFocusChanged) {
2103 return;
2104 }
2105
2106 // Dispatch onPointerDownOutsideFocus to the policy.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002107}
2108
2109void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
2110 const sp<Connection>& connection) {
2111#if DEBUG_DISPATCH_CYCLE
2112 ALOGD("channel '%s' ~ startDispatchCycle",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002113 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002114#endif
2115
2116 while (connection->status == Connection::STATUS_NORMAL
2117 && !connection->outboundQueue.isEmpty()) {
2118 DispatchEntry* dispatchEntry = connection->outboundQueue.head;
2119 dispatchEntry->deliveryTime = currentTime;
2120
2121 // Publish the event.
2122 status_t status;
2123 EventEntry* eventEntry = dispatchEntry->eventEntry;
2124 switch (eventEntry->type) {
2125 case EventEntry::TYPE_KEY: {
2126 KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
2127
2128 // Publish the key event.
2129 status = connection->inputPublisher.publishKeyEvent(dispatchEntry->seq,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002130 keyEntry->deviceId, keyEntry->source, keyEntry->displayId,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002131 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags,
2132 keyEntry->keyCode, keyEntry->scanCode,
2133 keyEntry->metaState, keyEntry->repeatCount, keyEntry->downTime,
2134 keyEntry->eventTime);
2135 break;
2136 }
2137
2138 case EventEntry::TYPE_MOTION: {
2139 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
2140
2141 PointerCoords scaledCoords[MAX_POINTERS];
2142 const PointerCoords* usingCoords = motionEntry->pointerCoords;
2143
2144 // Set the X and Y offset depending on the input source.
Siarhei Vishniakou635cb712017-11-01 16:32:14 -07002145 float xOffset, yOffset;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002146 if ((motionEntry->source & AINPUT_SOURCE_CLASS_POINTER)
2147 && !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
Robert Carre07e1032018-11-26 12:55:53 -08002148 float globalScaleFactor = dispatchEntry->globalScaleFactor;
2149 float wxs = dispatchEntry->windowXScale;
2150 float wys = dispatchEntry->windowYScale;
2151 xOffset = dispatchEntry->xOffset * wxs;
2152 yOffset = dispatchEntry->yOffset * wys;
2153 if (wxs != 1.0f || wys != 1.0f || globalScaleFactor != 1.0f) {
Narayan Kamathbc6001b2014-05-02 17:53:33 +01002154 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002155 scaledCoords[i] = motionEntry->pointerCoords[i];
Robert Carre07e1032018-11-26 12:55:53 -08002156 scaledCoords[i].scale(globalScaleFactor, wxs, wys);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002157 }
2158 usingCoords = scaledCoords;
2159 }
2160 } else {
2161 xOffset = 0.0f;
2162 yOffset = 0.0f;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002163
2164 // We don't want the dispatch target to know.
2165 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
Narayan Kamathbc6001b2014-05-02 17:53:33 +01002166 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002167 scaledCoords[i].clear();
2168 }
2169 usingCoords = scaledCoords;
2170 }
2171 }
2172
2173 // Publish the motion event.
2174 status = connection->inputPublisher.publishMotionEvent(dispatchEntry->seq,
Tarandeep Singh58641502017-07-31 10:51:54 -07002175 motionEntry->deviceId, motionEntry->source, motionEntry->displayId,
Michael Wright7b159c92015-05-14 14:48:03 +01002176 dispatchEntry->resolvedAction, motionEntry->actionButton,
2177 dispatchEntry->resolvedFlags, motionEntry->edgeFlags,
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08002178 motionEntry->metaState, motionEntry->buttonState, motionEntry->classification,
Michael Wright7b159c92015-05-14 14:48:03 +01002179 xOffset, yOffset, motionEntry->xPrecision, motionEntry->yPrecision,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002180 motionEntry->downTime, motionEntry->eventTime,
2181 motionEntry->pointerCount, motionEntry->pointerProperties,
2182 usingCoords);
2183 break;
2184 }
2185
2186 default:
2187 ALOG_ASSERT(false);
2188 return;
2189 }
2190
2191 // Check the result.
2192 if (status) {
2193 if (status == WOULD_BLOCK) {
2194 if (connection->waitQueue.isEmpty()) {
2195 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
2196 "This is unexpected because the wait queue is empty, so the pipe "
2197 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002198 "event to it, status=%d", connection->getInputChannelName().c_str(),
2199 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002200 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2201 } else {
2202 // Pipe is full and we are waiting for the app to finish process some events
2203 // before sending more events to it.
2204#if DEBUG_DISPATCH_CYCLE
2205 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
2206 "waiting for the application to catch up",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002207 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002208#endif
2209 connection->inputPublisherBlocked = true;
2210 }
2211 } else {
2212 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002213 "status=%d", connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002214 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2215 }
2216 return;
2217 }
2218
2219 // Re-enqueue the event on the wait queue.
2220 connection->outboundQueue.dequeue(dispatchEntry);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002221 traceOutboundQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002222 connection->waitQueue.enqueueAtTail(dispatchEntry);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002223 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002224 }
2225}
2226
2227void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
2228 const sp<Connection>& connection, uint32_t seq, bool handled) {
2229#if DEBUG_DISPATCH_CYCLE
2230 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002231 connection->getInputChannelName().c_str(), seq, toString(handled));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002232#endif
2233
2234 connection->inputPublisherBlocked = false;
2235
2236 if (connection->status == Connection::STATUS_BROKEN
2237 || connection->status == Connection::STATUS_ZOMBIE) {
2238 return;
2239 }
2240
2241 // Notify other system components and prepare to start the next dispatch cycle.
2242 onDispatchCycleFinishedLocked(currentTime, connection, seq, handled);
2243}
2244
2245void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
2246 const sp<Connection>& connection, bool notify) {
2247#if DEBUG_DISPATCH_CYCLE
2248 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002249 connection->getInputChannelName().c_str(), toString(notify));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002250#endif
2251
2252 // Clear the dispatch queues.
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002253 drainDispatchQueue(&connection->outboundQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002254 traceOutboundQueueLength(connection);
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002255 drainDispatchQueue(&connection->waitQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002256 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002257
2258 // The connection appears to be unrecoverably broken.
2259 // Ignore already broken or zombie connections.
2260 if (connection->status == Connection::STATUS_NORMAL) {
2261 connection->status = Connection::STATUS_BROKEN;
2262
2263 if (notify) {
2264 // Notify other system components.
2265 onDispatchCycleBrokenLocked(currentTime, connection);
2266 }
2267 }
2268}
2269
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002270void InputDispatcher::drainDispatchQueue(Queue<DispatchEntry>* queue) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002271 while (!queue->isEmpty()) {
2272 DispatchEntry* dispatchEntry = queue->dequeueAtHead();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002273 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002274 }
2275}
2276
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002277void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002278 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002279 decrementPendingForegroundDispatches(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002280 }
2281 delete dispatchEntry;
2282}
2283
2284int InputDispatcher::handleReceiveCallback(int fd, int events, void* data) {
2285 InputDispatcher* d = static_cast<InputDispatcher*>(data);
2286
2287 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002288 std::scoped_lock _l(d->mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002289
2290 ssize_t connectionIndex = d->mConnectionsByFd.indexOfKey(fd);
2291 if (connectionIndex < 0) {
2292 ALOGE("Received spurious receive callback for unknown input channel. "
2293 "fd=%d, events=0x%x", fd, events);
2294 return 0; // remove the callback
2295 }
2296
2297 bool notify;
2298 sp<Connection> connection = d->mConnectionsByFd.valueAt(connectionIndex);
2299 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
2300 if (!(events & ALOOPER_EVENT_INPUT)) {
2301 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002302 "events=0x%x", connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002303 return 1;
2304 }
2305
2306 nsecs_t currentTime = now();
2307 bool gotOne = false;
2308 status_t status;
2309 for (;;) {
2310 uint32_t seq;
2311 bool handled;
2312 status = connection->inputPublisher.receiveFinishedSignal(&seq, &handled);
2313 if (status) {
2314 break;
2315 }
2316 d->finishDispatchCycleLocked(currentTime, connection, seq, handled);
2317 gotOne = true;
2318 }
2319 if (gotOne) {
2320 d->runCommandsLockedInterruptible();
2321 if (status == WOULD_BLOCK) {
2322 return 1;
2323 }
2324 }
2325
2326 notify = status != DEAD_OBJECT || !connection->monitor;
2327 if (notify) {
2328 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002329 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002330 }
2331 } else {
2332 // Monitor channels are never explicitly unregistered.
2333 // We do it automatically when the remote endpoint is closed so don't warn
2334 // about them.
2335 notify = !connection->monitor;
2336 if (notify) {
2337 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. "
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002338 "events=0x%x", connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002339 }
2340 }
2341
2342 // Unregister the channel.
2343 d->unregisterInputChannelLocked(connection->inputChannel, notify);
2344 return 0; // remove the callback
2345 } // release lock
2346}
2347
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002348void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked (
Michael Wrightd02c5b62014-02-10 15:10:22 -08002349 const CancelationOptions& options) {
2350 for (size_t i = 0; i < mConnectionsByFd.size(); i++) {
2351 synthesizeCancelationEventsForConnectionLocked(
2352 mConnectionsByFd.valueAt(i), options);
2353 }
2354}
2355
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002356void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked (
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002357 const CancelationOptions& options) {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002358 for (auto& it : mMonitoringChannelsByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002359 const std::vector<sp<InputChannel>>& monitoringChannels = it.second;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002360 const size_t numChannels = monitoringChannels.size();
2361 for (size_t i = 0; i < numChannels; i++) {
2362 synthesizeCancelationEventsForInputChannelLocked(monitoringChannels[i], options);
2363 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002364 }
2365}
2366
Michael Wrightd02c5b62014-02-10 15:10:22 -08002367void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
2368 const sp<InputChannel>& channel, const CancelationOptions& options) {
2369 ssize_t index = getConnectionIndexLocked(channel);
2370 if (index >= 0) {
2371 synthesizeCancelationEventsForConnectionLocked(
2372 mConnectionsByFd.valueAt(index), options);
2373 }
2374}
2375
2376void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
2377 const sp<Connection>& connection, const CancelationOptions& options) {
2378 if (connection->status == Connection::STATUS_BROKEN) {
2379 return;
2380 }
2381
2382 nsecs_t currentTime = now();
2383
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002384 std::vector<EventEntry*> cancelationEvents;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002385 connection->inputState.synthesizeCancelationEvents(currentTime,
2386 cancelationEvents, options);
2387
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002388 if (!cancelationEvents.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002389#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002390 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
Michael Wrightd02c5b62014-02-10 15:10:22 -08002391 "with reality: %s, mode=%d.",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002392 connection->getInputChannelName().c_str(), cancelationEvents.size(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002393 options.reason, options.mode);
2394#endif
2395 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002396 EventEntry* cancelationEventEntry = cancelationEvents[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002397 switch (cancelationEventEntry->type) {
2398 case EventEntry::TYPE_KEY:
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002399 logOutboundKeyDetails("cancel - ",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002400 static_cast<KeyEntry*>(cancelationEventEntry));
2401 break;
2402 case EventEntry::TYPE_MOTION:
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002403 logOutboundMotionDetails("cancel - ",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002404 static_cast<MotionEntry*>(cancelationEventEntry));
2405 break;
2406 }
2407
2408 InputTarget target;
chaviwfbe5d9c2018-12-26 12:23:37 -08002409 sp<InputWindowHandle> windowHandle = getWindowHandleLocked(
2410 connection->inputChannel->getToken());
Yi Kong9b14ac62018-07-17 13:48:38 -07002411 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002412 const InputWindowInfo* windowInfo = windowHandle->getInfo();
2413 target.xOffset = -windowInfo->frameLeft;
2414 target.yOffset = -windowInfo->frameTop;
Robert Carre07e1032018-11-26 12:55:53 -08002415 target.globalScaleFactor = windowInfo->globalScaleFactor;
2416 target.windowXScale = windowInfo->windowXScale;
2417 target.windowYScale = windowInfo->windowYScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002418 } else {
2419 target.xOffset = 0;
2420 target.yOffset = 0;
Robert Carre07e1032018-11-26 12:55:53 -08002421 target.globalScaleFactor = 1.0f;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002422 }
2423 target.inputChannel = connection->inputChannel;
2424 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
2425
chaviw8c9cf542019-03-25 13:02:48 -07002426 enqueueDispatchEntryLocked(connection, cancelationEventEntry, // increments ref
Michael Wrightd02c5b62014-02-10 15:10:22 -08002427 &target, InputTarget::FLAG_DISPATCH_AS_IS);
2428
2429 cancelationEventEntry->release();
2430 }
2431
2432 startDispatchCycleLocked(currentTime, connection);
2433 }
2434}
2435
2436InputDispatcher::MotionEntry*
2437InputDispatcher::splitMotionEvent(const MotionEntry* originalMotionEntry, BitSet32 pointerIds) {
2438 ALOG_ASSERT(pointerIds.value != 0);
2439
2440 uint32_t splitPointerIndexMap[MAX_POINTERS];
2441 PointerProperties splitPointerProperties[MAX_POINTERS];
2442 PointerCoords splitPointerCoords[MAX_POINTERS];
2443
2444 uint32_t originalPointerCount = originalMotionEntry->pointerCount;
2445 uint32_t splitPointerCount = 0;
2446
2447 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
2448 originalPointerIndex++) {
2449 const PointerProperties& pointerProperties =
2450 originalMotionEntry->pointerProperties[originalPointerIndex];
2451 uint32_t pointerId = uint32_t(pointerProperties.id);
2452 if (pointerIds.hasBit(pointerId)) {
2453 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
2454 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
2455 splitPointerCoords[splitPointerCount].copyFrom(
2456 originalMotionEntry->pointerCoords[originalPointerIndex]);
2457 splitPointerCount += 1;
2458 }
2459 }
2460
2461 if (splitPointerCount != pointerIds.count()) {
2462 // This is bad. We are missing some of the pointers that we expected to deliver.
2463 // Most likely this indicates that we received an ACTION_MOVE events that has
2464 // different pointer ids than we expected based on the previous ACTION_DOWN
2465 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
2466 // in this way.
2467 ALOGW("Dropping split motion event because the pointer count is %d but "
2468 "we expected there to be %d pointers. This probably means we received "
2469 "a broken sequence of pointer ids from the input device.",
2470 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07002471 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002472 }
2473
2474 int32_t action = originalMotionEntry->action;
2475 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
2476 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
2477 || maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2478 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
2479 const PointerProperties& pointerProperties =
2480 originalMotionEntry->pointerProperties[originalPointerIndex];
2481 uint32_t pointerId = uint32_t(pointerProperties.id);
2482 if (pointerIds.hasBit(pointerId)) {
2483 if (pointerIds.count() == 1) {
2484 // The first/last pointer went down/up.
2485 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
2486 ? AMOTION_EVENT_ACTION_DOWN : AMOTION_EVENT_ACTION_UP;
2487 } else {
2488 // A secondary pointer went down/up.
2489 uint32_t splitPointerIndex = 0;
2490 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
2491 splitPointerIndex += 1;
2492 }
2493 action = maskedAction | (splitPointerIndex
2494 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
2495 }
2496 } else {
2497 // An unrelated pointer changed.
2498 action = AMOTION_EVENT_ACTION_MOVE;
2499 }
2500 }
2501
2502 MotionEntry* splitMotionEntry = new MotionEntry(
Prabir Pradhan42611e02018-11-27 14:04:02 -08002503 originalMotionEntry->sequenceNum,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002504 originalMotionEntry->eventTime,
2505 originalMotionEntry->deviceId,
2506 originalMotionEntry->source,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002507 originalMotionEntry->displayId,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002508 originalMotionEntry->policyFlags,
2509 action,
Michael Wright7b159c92015-05-14 14:48:03 +01002510 originalMotionEntry->actionButton,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002511 originalMotionEntry->flags,
2512 originalMotionEntry->metaState,
2513 originalMotionEntry->buttonState,
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08002514 originalMotionEntry->classification,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002515 originalMotionEntry->edgeFlags,
2516 originalMotionEntry->xPrecision,
2517 originalMotionEntry->yPrecision,
2518 originalMotionEntry->downTime,
Jeff Brownf086ddb2014-02-11 14:28:48 -08002519 splitPointerCount, splitPointerProperties, splitPointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002520
2521 if (originalMotionEntry->injectionState) {
2522 splitMotionEntry->injectionState = originalMotionEntry->injectionState;
2523 splitMotionEntry->injectionState->refCount += 1;
2524 }
2525
2526 return splitMotionEntry;
2527}
2528
2529void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
2530#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002531 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002532#endif
2533
2534 bool needWake;
2535 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002536 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002537
Prabir Pradhan42611e02018-11-27 14:04:02 -08002538 ConfigurationChangedEntry* newEntry =
2539 new ConfigurationChangedEntry(args->sequenceNum, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002540 needWake = enqueueInboundEventLocked(newEntry);
2541 } // release lock
2542
2543 if (needWake) {
2544 mLooper->wake();
2545 }
2546}
2547
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002548/**
2549 * If one of the meta shortcuts is detected, process them here:
2550 * Meta + Backspace -> generate BACK
2551 * Meta + Enter -> generate HOME
2552 * This will potentially overwrite keyCode and metaState.
2553 */
2554void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
2555 int32_t& keyCode, int32_t& metaState) {
2556 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
2557 int32_t newKeyCode = AKEYCODE_UNKNOWN;
2558 if (keyCode == AKEYCODE_DEL) {
2559 newKeyCode = AKEYCODE_BACK;
2560 } else if (keyCode == AKEYCODE_ENTER) {
2561 newKeyCode = AKEYCODE_HOME;
2562 }
2563 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002564 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002565 struct KeyReplacement replacement = {keyCode, deviceId};
2566 mReplacedKeys.add(replacement, newKeyCode);
2567 keyCode = newKeyCode;
2568 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
2569 }
2570 } else if (action == AKEY_EVENT_ACTION_UP) {
2571 // In order to maintain a consistent stream of up and down events, check to see if the key
2572 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
2573 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002574 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002575 struct KeyReplacement replacement = {keyCode, deviceId};
2576 ssize_t index = mReplacedKeys.indexOfKey(replacement);
2577 if (index >= 0) {
2578 keyCode = mReplacedKeys.valueAt(index);
2579 mReplacedKeys.removeItemsAt(index);
2580 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
2581 }
2582 }
2583}
2584
Michael Wrightd02c5b62014-02-10 15:10:22 -08002585void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
2586#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002587 ALOGD("notifyKey - eventTime=%" PRId64
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002588 ", deviceId=%d, source=0x%x, displayId=%" PRId32 "policyFlags=0x%x, action=0x%x, "
Arthur Hung82a4cad2018-11-15 12:10:30 +08002589 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002590 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002591 args->action, args->flags, args->keyCode, args->scanCode,
Arthur Hung82a4cad2018-11-15 12:10:30 +08002592 args->metaState, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002593#endif
2594 if (!validateKeyEvent(args->action)) {
2595 return;
2596 }
2597
2598 uint32_t policyFlags = args->policyFlags;
2599 int32_t flags = args->flags;
2600 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07002601 // InputDispatcher tracks and generates key repeats on behalf of
2602 // whatever notifies it, so repeatCount should always be set to 0
2603 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002604 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
2605 policyFlags |= POLICY_FLAG_VIRTUAL;
2606 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
2607 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002608 if (policyFlags & POLICY_FLAG_FUNCTION) {
2609 metaState |= AMETA_FUNCTION_ON;
2610 }
2611
2612 policyFlags |= POLICY_FLAG_TRUSTED;
2613
Michael Wright78f24442014-08-06 15:55:28 -07002614 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002615 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07002616
Michael Wrightd02c5b62014-02-10 15:10:22 -08002617 KeyEvent event;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002618 event.initialize(args->deviceId, args->source, args->displayId, args->action,
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07002619 flags, keyCode, args->scanCode, metaState, repeatCount,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002620 args->downTime, args->eventTime);
2621
Michael Wright2b3c3302018-03-02 17:19:13 +00002622 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002623 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002624 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2625 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
2626 std::to_string(t.duration().count()).c_str());
2627 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002628
Michael Wrightd02c5b62014-02-10 15:10:22 -08002629 bool needWake;
2630 { // acquire lock
2631 mLock.lock();
2632
2633 if (shouldSendKeyToInputFilterLocked(args)) {
2634 mLock.unlock();
2635
2636 policyFlags |= POLICY_FLAG_FILTERED;
2637 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2638 return; // event was consumed by the filter
2639 }
2640
2641 mLock.lock();
2642 }
2643
Prabir Pradhan42611e02018-11-27 14:04:02 -08002644 KeyEntry* newEntry = new KeyEntry(args->sequenceNum, args->eventTime,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002645 args->deviceId, args->source, args->displayId, policyFlags,
Michael Wright78f24442014-08-06 15:55:28 -07002646 args->action, flags, keyCode, args->scanCode,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002647 metaState, repeatCount, args->downTime);
2648
2649 needWake = enqueueInboundEventLocked(newEntry);
2650 mLock.unlock();
2651 } // release lock
2652
2653 if (needWake) {
2654 mLooper->wake();
2655 }
2656}
2657
2658bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
2659 return mInputFilterEnabled;
2660}
2661
2662void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
2663#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002664 ALOGD("notifyMotion - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
2665 ", policyFlags=0x%x, "
Michael Wright7b159c92015-05-14 14:48:03 +01002666 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x,"
Arthur Hung82a4cad2018-11-15 12:10:30 +08002667 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
2668 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002669 args->action, args->actionButton, args->flags, args->metaState, args->buttonState,
Arthur Hung82a4cad2018-11-15 12:10:30 +08002670 args->edgeFlags, args->xPrecision, args->yPrecision, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002671 for (uint32_t i = 0; i < args->pointerCount; i++) {
2672 ALOGD(" Pointer %d: id=%d, toolType=%d, "
2673 "x=%f, y=%f, pressure=%f, size=%f, "
2674 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
2675 "orientation=%f",
2676 i, args->pointerProperties[i].id,
2677 args->pointerProperties[i].toolType,
2678 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
2679 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
2680 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
2681 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
2682 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
2683 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
2684 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
2685 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
2686 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
2687 }
2688#endif
Michael Wright7b159c92015-05-14 14:48:03 +01002689 if (!validateMotionEvent(args->action, args->actionButton,
2690 args->pointerCount, args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002691 return;
2692 }
2693
2694 uint32_t policyFlags = args->policyFlags;
2695 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00002696
2697 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08002698 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002699 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2700 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
2701 std::to_string(t.duration().count()).c_str());
2702 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002703
2704 bool needWake;
2705 { // acquire lock
2706 mLock.lock();
2707
2708 if (shouldSendMotionToInputFilterLocked(args)) {
2709 mLock.unlock();
2710
2711 MotionEvent event;
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002712 event.initialize(args->deviceId, args->source, args->displayId,
2713 args->action, args->actionButton,
Michael Wright7b159c92015-05-14 14:48:03 +01002714 args->flags, args->edgeFlags, args->metaState, args->buttonState,
Siarhei Vishniakouae478d32019-01-03 14:45:18 -08002715 args->classification, 0, 0, args->xPrecision, args->yPrecision,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002716 args->downTime, args->eventTime,
2717 args->pointerCount, args->pointerProperties, args->pointerCoords);
2718
2719 policyFlags |= POLICY_FLAG_FILTERED;
2720 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2721 return; // event was consumed by the filter
2722 }
2723
2724 mLock.lock();
2725 }
2726
2727 // Just enqueue a new motion event.
Prabir Pradhan42611e02018-11-27 14:04:02 -08002728 MotionEntry* newEntry = new MotionEntry(args->sequenceNum, args->eventTime,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002729 args->deviceId, args->source, args->displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002730 args->action, args->actionButton, args->flags,
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08002731 args->metaState, args->buttonState, args->classification,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002732 args->edgeFlags, args->xPrecision, args->yPrecision, args->downTime,
Jeff Brownf086ddb2014-02-11 14:28:48 -08002733 args->pointerCount, args->pointerProperties, args->pointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002734
2735 needWake = enqueueInboundEventLocked(newEntry);
2736 mLock.unlock();
2737 } // release lock
2738
2739 if (needWake) {
2740 mLooper->wake();
2741 }
2742}
2743
2744bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08002745 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002746}
2747
2748void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
2749#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002750 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
2751 "switchMask=0x%08x",
2752 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002753#endif
2754
2755 uint32_t policyFlags = args->policyFlags;
2756 policyFlags |= POLICY_FLAG_TRUSTED;
2757 mPolicy->notifySwitch(args->eventTime,
2758 args->switchValues, args->switchMask, policyFlags);
2759}
2760
2761void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
2762#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002763 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002764 args->eventTime, args->deviceId);
2765#endif
2766
2767 bool needWake;
2768 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002769 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002770
Prabir Pradhan42611e02018-11-27 14:04:02 -08002771 DeviceResetEntry* newEntry =
2772 new DeviceResetEntry(args->sequenceNum, args->eventTime, args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002773 needWake = enqueueInboundEventLocked(newEntry);
2774 } // release lock
2775
2776 if (needWake) {
2777 mLooper->wake();
2778 }
2779}
2780
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002781int32_t InputDispatcher::injectInputEvent(const InputEvent* event,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002782 int32_t injectorPid, int32_t injectorUid, int32_t syncMode, int32_t timeoutMillis,
2783 uint32_t policyFlags) {
2784#if DEBUG_INBOUND_EVENT_DETAILS
2785 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002786 "syncMode=%d, timeoutMillis=%d, policyFlags=0x%08x",
2787 event->getType(), injectorPid, injectorUid, syncMode, timeoutMillis, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002788#endif
2789
2790 nsecs_t endTime = now() + milliseconds_to_nanoseconds(timeoutMillis);
2791
2792 policyFlags |= POLICY_FLAG_INJECTED;
2793 if (hasInjectionPermission(injectorPid, injectorUid)) {
2794 policyFlags |= POLICY_FLAG_TRUSTED;
2795 }
2796
2797 EventEntry* firstInjectedEntry;
2798 EventEntry* lastInjectedEntry;
2799 switch (event->getType()) {
2800 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002801 KeyEvent keyEvent;
2802 keyEvent.initialize(*static_cast<const KeyEvent*>(event));
2803 int32_t action = keyEvent.getAction();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002804 if (! validateKeyEvent(action)) {
2805 return INPUT_EVENT_INJECTION_FAILED;
2806 }
2807
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002808 int32_t flags = keyEvent.getFlags();
2809 int32_t keyCode = keyEvent.getKeyCode();
2810 int32_t metaState = keyEvent.getMetaState();
2811 accelerateMetaShortcuts(keyEvent.getDeviceId(), action,
2812 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002813 keyEvent.initialize(keyEvent.getDeviceId(), keyEvent.getSource(), keyEvent.getDisplayId(),
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07002814 action, flags, keyCode, keyEvent.getScanCode(), metaState, keyEvent.getRepeatCount(),
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002815 keyEvent.getDownTime(), keyEvent.getEventTime());
2816
Michael Wrightd02c5b62014-02-10 15:10:22 -08002817 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
2818 policyFlags |= POLICY_FLAG_VIRTUAL;
2819 }
2820
2821 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wright2b3c3302018-03-02 17:19:13 +00002822 android::base::Timer t;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002823 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002824 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2825 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
2826 std::to_string(t.duration().count()).c_str());
2827 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002828 }
2829
Michael Wrightd02c5b62014-02-10 15:10:22 -08002830 mLock.lock();
Prabir Pradhan42611e02018-11-27 14:04:02 -08002831 firstInjectedEntry = new KeyEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, keyEvent.getEventTime(),
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002832 keyEvent.getDeviceId(), keyEvent.getSource(), keyEvent.getDisplayId(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002833 policyFlags, action, flags,
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002834 keyEvent.getKeyCode(), keyEvent.getScanCode(), keyEvent.getMetaState(),
2835 keyEvent.getRepeatCount(), keyEvent.getDownTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002836 lastInjectedEntry = firstInjectedEntry;
2837 break;
2838 }
2839
2840 case AINPUT_EVENT_TYPE_MOTION: {
2841 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002842 int32_t action = motionEvent->getAction();
2843 size_t pointerCount = motionEvent->getPointerCount();
2844 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
Michael Wright7b159c92015-05-14 14:48:03 +01002845 int32_t actionButton = motionEvent->getActionButton();
Charles Chen3611f1f2019-01-29 17:26:18 +08002846 int32_t displayId = motionEvent->getDisplayId();
Michael Wright7b159c92015-05-14 14:48:03 +01002847 if (! validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002848 return INPUT_EVENT_INJECTION_FAILED;
2849 }
2850
2851 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
2852 nsecs_t eventTime = motionEvent->getEventTime();
Michael Wright2b3c3302018-03-02 17:19:13 +00002853 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08002854 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002855 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2856 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
2857 std::to_string(t.duration().count()).c_str());
2858 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002859 }
2860
2861 mLock.lock();
2862 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
2863 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
Prabir Pradhan42611e02018-11-27 14:04:02 -08002864 firstInjectedEntry = new MotionEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, *sampleEventTimes,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002865 motionEvent->getDeviceId(), motionEvent->getSource(), motionEvent->getDisplayId(),
2866 policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002867 action, actionButton, motionEvent->getFlags(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002868 motionEvent->getMetaState(), motionEvent->getButtonState(),
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08002869 motionEvent->getClassification(), motionEvent->getEdgeFlags(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002870 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002871 motionEvent->getDownTime(),
Jeff Brownf086ddb2014-02-11 14:28:48 -08002872 uint32_t(pointerCount), pointerProperties, samplePointerCoords,
2873 motionEvent->getXOffset(), motionEvent->getYOffset());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002874 lastInjectedEntry = firstInjectedEntry;
2875 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
2876 sampleEventTimes += 1;
2877 samplePointerCoords += pointerCount;
Prabir Pradhan42611e02018-11-27 14:04:02 -08002878 MotionEntry* nextInjectedEntry = new MotionEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM,
2879 *sampleEventTimes,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002880 motionEvent->getDeviceId(), motionEvent->getSource(),
2881 motionEvent->getDisplayId(), policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002882 action, actionButton, motionEvent->getFlags(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002883 motionEvent->getMetaState(), motionEvent->getButtonState(),
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08002884 motionEvent->getClassification(), motionEvent->getEdgeFlags(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002885 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002886 motionEvent->getDownTime(),
Jeff Brownf086ddb2014-02-11 14:28:48 -08002887 uint32_t(pointerCount), pointerProperties, samplePointerCoords,
2888 motionEvent->getXOffset(), motionEvent->getYOffset());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002889 lastInjectedEntry->next = nextInjectedEntry;
2890 lastInjectedEntry = nextInjectedEntry;
2891 }
2892 break;
2893 }
2894
2895 default:
2896 ALOGW("Cannot inject event of type %d", event->getType());
2897 return INPUT_EVENT_INJECTION_FAILED;
2898 }
2899
2900 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
2901 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
2902 injectionState->injectionIsAsync = true;
2903 }
2904
2905 injectionState->refCount += 1;
2906 lastInjectedEntry->injectionState = injectionState;
2907
2908 bool needWake = false;
Yi Kong9b14ac62018-07-17 13:48:38 -07002909 for (EventEntry* entry = firstInjectedEntry; entry != nullptr; ) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002910 EventEntry* nextEntry = entry->next;
2911 needWake |= enqueueInboundEventLocked(entry);
2912 entry = nextEntry;
2913 }
2914
2915 mLock.unlock();
2916
2917 if (needWake) {
2918 mLooper->wake();
2919 }
2920
2921 int32_t injectionResult;
2922 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002923 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002924
2925 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
2926 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
2927 } else {
2928 for (;;) {
2929 injectionResult = injectionState->injectionResult;
2930 if (injectionResult != INPUT_EVENT_INJECTION_PENDING) {
2931 break;
2932 }
2933
2934 nsecs_t remainingTimeout = endTime - now();
2935 if (remainingTimeout <= 0) {
2936#if DEBUG_INJECTION
2937 ALOGD("injectInputEvent - Timed out waiting for injection result "
2938 "to become available.");
2939#endif
2940 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
2941 break;
2942 }
2943
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002944 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002945 }
2946
2947 if (injectionResult == INPUT_EVENT_INJECTION_SUCCEEDED
2948 && syncMode == INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED) {
2949 while (injectionState->pendingForegroundDispatches != 0) {
2950#if DEBUG_INJECTION
2951 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
2952 injectionState->pendingForegroundDispatches);
2953#endif
2954 nsecs_t remainingTimeout = endTime - now();
2955 if (remainingTimeout <= 0) {
2956#if DEBUG_INJECTION
2957 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
2958 "dispatches to finish.");
2959#endif
2960 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
2961 break;
2962 }
2963
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002964 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002965 }
2966 }
2967 }
2968
2969 injectionState->release();
2970 } // release lock
2971
2972#if DEBUG_INJECTION
2973 ALOGD("injectInputEvent - Finished with result %d. "
2974 "injectorPid=%d, injectorUid=%d",
2975 injectionResult, injectorPid, injectorUid);
2976#endif
2977
2978 return injectionResult;
2979}
2980
2981bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
2982 return injectorUid == 0
2983 || mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
2984}
2985
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002986void InputDispatcher::setInjectionResult(EventEntry* entry, int32_t injectionResult) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002987 InjectionState* injectionState = entry->injectionState;
2988 if (injectionState) {
2989#if DEBUG_INJECTION
2990 ALOGD("Setting input event injection result to %d. "
2991 "injectorPid=%d, injectorUid=%d",
2992 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
2993#endif
2994
2995 if (injectionState->injectionIsAsync
2996 && !(entry->policyFlags & POLICY_FLAG_FILTERED)) {
2997 // Log the outcome since the injector did not wait for the injection result.
2998 switch (injectionResult) {
2999 case INPUT_EVENT_INJECTION_SUCCEEDED:
3000 ALOGV("Asynchronous input event injection succeeded.");
3001 break;
3002 case INPUT_EVENT_INJECTION_FAILED:
3003 ALOGW("Asynchronous input event injection failed.");
3004 break;
3005 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
3006 ALOGW("Asynchronous input event injection permission denied.");
3007 break;
3008 case INPUT_EVENT_INJECTION_TIMED_OUT:
3009 ALOGW("Asynchronous input event injection timed out.");
3010 break;
3011 }
3012 }
3013
3014 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003015 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003016 }
3017}
3018
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003019void InputDispatcher::incrementPendingForegroundDispatches(EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003020 InjectionState* injectionState = entry->injectionState;
3021 if (injectionState) {
3022 injectionState->pendingForegroundDispatches += 1;
3023 }
3024}
3025
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003026void InputDispatcher::decrementPendingForegroundDispatches(EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003027 InjectionState* injectionState = entry->injectionState;
3028 if (injectionState) {
3029 injectionState->pendingForegroundDispatches -= 1;
3030
3031 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003032 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003033 }
3034 }
3035}
3036
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003037std::vector<sp<InputWindowHandle>> InputDispatcher::getWindowHandlesLocked(
3038 int32_t displayId) const {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003039 return getValueByKey(mWindowHandlesByDisplay, displayId);
Arthur Hungb92218b2018-08-14 12:00:21 +08003040}
3041
Michael Wrightd02c5b62014-02-10 15:10:22 -08003042sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08003043 const sp<IBinder>& windowHandleToken) const {
Arthur Hungb92218b2018-08-14 12:00:21 +08003044 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003045 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
3046 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08003047 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003048 return windowHandle;
3049 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003050 }
3051 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003052 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003053}
3054
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003055bool InputDispatcher::hasWindowHandleLocked(const sp<InputWindowHandle>& windowHandle) const {
Arthur Hungb92218b2018-08-14 12:00:21 +08003056 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003057 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
3058 for (const sp<InputWindowHandle>& handle : windowHandles) {
3059 if (handle->getToken() == windowHandle->getToken()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003060 if (windowHandle->getInfo()->displayId != it.first) {
Arthur Hung3b413f22018-10-26 18:05:34 +08003061 ALOGE("Found window %s in display %" PRId32
3062 ", but it should belong to display %" PRId32,
3063 windowHandle->getName().c_str(), it.first,
3064 windowHandle->getInfo()->displayId);
Arthur Hungb92218b2018-08-14 12:00:21 +08003065 }
3066 return true;
3067 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003068 }
3069 }
3070 return false;
3071}
3072
Robert Carr5c8a0262018-10-03 16:30:44 -07003073sp<InputChannel> InputDispatcher::getInputChannelLocked(const sp<IBinder>& token) const {
3074 size_t count = mInputChannelsByToken.count(token);
3075 if (count == 0) {
3076 return nullptr;
3077 }
3078 return mInputChannelsByToken.at(token);
3079}
3080
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003081void InputDispatcher::updateWindowHandlesForDisplayLocked(
3082 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
3083 if (inputWindowHandles.empty()) {
3084 // Remove all handles on a display if there are no windows left.
3085 mWindowHandlesByDisplay.erase(displayId);
3086 return;
3087 }
3088
3089 // Since we compare the pointer of input window handles across window updates, we need
3090 // to make sure the handle object for the same window stays unchanged across updates.
3091 const std::vector<sp<InputWindowHandle>>& oldHandles = getWindowHandlesLocked(displayId);
3092 std::unordered_map<sp<IBinder>, sp<InputWindowHandle>, IBinderHash> oldHandlesByTokens;
3093 for (const sp<InputWindowHandle>& handle : oldHandles) {
3094 oldHandlesByTokens[handle->getToken()] = handle;
3095 }
3096
3097 std::vector<sp<InputWindowHandle>> newHandles;
3098 for (const sp<InputWindowHandle>& handle : inputWindowHandles) {
3099 if (!handle->updateInfo()) {
3100 // handle no longer valid
3101 continue;
3102 }
3103
3104 const InputWindowInfo* info = handle->getInfo();
3105 if ((getInputChannelLocked(handle->getToken()) == nullptr &&
3106 info->portalToDisplayId == ADISPLAY_ID_NONE)) {
3107 const bool noInputChannel =
3108 info->inputFeatures & InputWindowInfo::INPUT_FEATURE_NO_INPUT_CHANNEL;
3109 const bool canReceiveInput =
3110 !(info->layoutParamsFlags & InputWindowInfo::FLAG_NOT_TOUCHABLE) ||
3111 !(info->layoutParamsFlags & InputWindowInfo::FLAG_NOT_FOCUSABLE);
3112 if (canReceiveInput && !noInputChannel) {
3113 ALOGE("Window handle %s has no registered input channel",
3114 handle->getName().c_str());
3115 }
3116 continue;
3117 }
3118
3119 if (info->displayId != displayId) {
3120 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
3121 handle->getName().c_str(), displayId, info->displayId);
3122 continue;
3123 }
3124
3125 if (oldHandlesByTokens.find(handle->getToken()) != oldHandlesByTokens.end()) {
3126 const sp<InputWindowHandle> oldHandle = oldHandlesByTokens.at(handle->getToken());
3127 oldHandle->updateFrom(handle);
3128 newHandles.push_back(oldHandle);
3129 } else {
3130 newHandles.push_back(handle);
3131 }
3132 }
3133
3134 // Insert or replace
3135 mWindowHandlesByDisplay[displayId] = newHandles;
3136}
3137
Arthur Hungb92218b2018-08-14 12:00:21 +08003138/**
3139 * Called from InputManagerService, update window handle list by displayId that can receive input.
3140 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
3141 * If set an empty list, remove all handles from the specific display.
3142 * For focused handle, check if need to change and send a cancel event to previous one.
3143 * For removed handle, check if need to send a cancel event if already in touch.
3144 */
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003145void InputDispatcher::setInputWindows(const std::vector<sp<InputWindowHandle>>& inputWindowHandles,
chaviw291d88a2019-02-14 10:33:58 -08003146 int32_t displayId, const sp<ISetInputWindowsListener>& setInputWindowsListener) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003147#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003148 ALOGD("setInputWindows displayId=%" PRId32, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003149#endif
3150 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003151 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003152
Arthur Hungb92218b2018-08-14 12:00:21 +08003153 // Copy old handles for release if they are no longer present.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003154 const std::vector<sp<InputWindowHandle>> oldWindowHandles =
3155 getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003156
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003157 updateWindowHandlesForDisplayLocked(inputWindowHandles, displayId);
3158
Tiger Huang721e26f2018-07-24 22:26:19 +08003159 sp<InputWindowHandle> newFocusedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003160 bool foundHoveredWindow = false;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003161 for (const sp<InputWindowHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
3162 // Set newFocusedWindowHandle to the top most focused window instead of the last one
3163 if (!newFocusedWindowHandle && windowHandle->getInfo()->hasFocus &&
3164 windowHandle->getInfo()->visible) {
3165 newFocusedWindowHandle = windowHandle;
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003166 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003167 if (windowHandle == mLastHoverWindowHandle) {
3168 foundHoveredWindow = true;
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003169 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003170 }
3171
3172 if (!foundHoveredWindow) {
Yi Kong9b14ac62018-07-17 13:48:38 -07003173 mLastHoverWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003174 }
3175
Tiger Huang721e26f2018-07-24 22:26:19 +08003176 sp<InputWindowHandle> oldFocusedWindowHandle =
3177 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
3178
3179 if (oldFocusedWindowHandle != newFocusedWindowHandle) {
3180 if (oldFocusedWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003181#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003182 ALOGD("Focus left window: %s in display %" PRId32,
3183 oldFocusedWindowHandle->getName().c_str(), displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003184#endif
Robert Carr5c8a0262018-10-03 16:30:44 -07003185 sp<InputChannel> focusedInputChannel = getInputChannelLocked(
3186 oldFocusedWindowHandle->getToken());
Yi Kong9b14ac62018-07-17 13:48:38 -07003187 if (focusedInputChannel != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003188 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
3189 "focus left window");
3190 synthesizeCancelationEventsForInputChannelLocked(
3191 focusedInputChannel, options);
3192 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003193 mFocusedWindowHandlesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003194 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003195 if (newFocusedWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003196#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003197 ALOGD("Focus entered window: %s in display %" PRId32,
3198 newFocusedWindowHandle->getName().c_str(), displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003199#endif
Tiger Huang721e26f2018-07-24 22:26:19 +08003200 mFocusedWindowHandlesByDisplay[displayId] = newFocusedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003201 }
Robert Carrf759f162018-11-13 12:57:11 -08003202
3203 if (mFocusedDisplayId == displayId) {
chaviw0c06c6e2019-01-09 13:27:07 -08003204 onFocusChangedLocked(oldFocusedWindowHandle, newFocusedWindowHandle);
Robert Carrf759f162018-11-13 12:57:11 -08003205 }
3206
Michael Wrightd02c5b62014-02-10 15:10:22 -08003207 }
3208
Arthur Hungb92218b2018-08-14 12:00:21 +08003209 ssize_t stateIndex = mTouchStatesByDisplay.indexOfKey(displayId);
3210 if (stateIndex >= 0) {
3211 TouchState& state = mTouchStatesByDisplay.editValueAt(stateIndex);
Ivan Lozano96f12992017-11-09 14:45:38 -08003212 for (size_t i = 0; i < state.windows.size(); ) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003213 TouchedWindow& touchedWindow = state.windows[i];
Siarhei Vishniakou9224fba2018-08-13 18:55:08 +00003214 if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003215#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003216 ALOGD("Touched window was removed: %s in display %" PRId32,
3217 touchedWindow.windowHandle->getName().c_str(), displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003218#endif
Jeff Brownf086ddb2014-02-11 14:28:48 -08003219 sp<InputChannel> touchedInputChannel =
Robert Carr5c8a0262018-10-03 16:30:44 -07003220 getInputChannelLocked(touchedWindow.windowHandle->getToken());
Yi Kong9b14ac62018-07-17 13:48:38 -07003221 if (touchedInputChannel != nullptr) {
Jeff Brownf086ddb2014-02-11 14:28:48 -08003222 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
3223 "touched window was removed");
3224 synthesizeCancelationEventsForInputChannelLocked(
3225 touchedInputChannel, options);
3226 }
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003227 state.windows.erase(state.windows.begin() + i);
Ivan Lozano96f12992017-11-09 14:45:38 -08003228 } else {
3229 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003230 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003231 }
3232 }
3233
3234 // Release information for windows that are no longer present.
3235 // This ensures that unused input channels are released promptly.
3236 // Otherwise, they might stick around until the window handle is destroyed
3237 // which might not happen until the next GC.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003238 for (const sp<InputWindowHandle>& oldWindowHandle : oldWindowHandles) {
Siarhei Vishniakou9224fba2018-08-13 18:55:08 +00003239 if (!hasWindowHandleLocked(oldWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003240#if DEBUG_FOCUS
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003241 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003242#endif
Arthur Hung3b413f22018-10-26 18:05:34 +08003243 oldWindowHandle->releaseChannel();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003244 }
3245 }
3246 } // release lock
3247
3248 // Wake up poll loop since it may need to make new input dispatching choices.
3249 mLooper->wake();
chaviw291d88a2019-02-14 10:33:58 -08003250
3251 if (setInputWindowsListener) {
3252 setInputWindowsListener->onSetInputWindowsFinished();
3253 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003254}
3255
3256void InputDispatcher::setFocusedApplication(
Tiger Huang721e26f2018-07-24 22:26:19 +08003257 int32_t displayId, const sp<InputApplicationHandle>& inputApplicationHandle) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003258#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003259 ALOGD("setFocusedApplication displayId=%" PRId32, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003260#endif
3261 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003262 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003263
Tiger Huang721e26f2018-07-24 22:26:19 +08003264 sp<InputApplicationHandle> oldFocusedApplicationHandle =
3265 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
Yi Kong9b14ac62018-07-17 13:48:38 -07003266 if (inputApplicationHandle != nullptr && inputApplicationHandle->updateInfo()) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003267 if (oldFocusedApplicationHandle != inputApplicationHandle) {
3268 if (oldFocusedApplicationHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003269 resetANRTimeoutsLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003270 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003271 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003272 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003273 } else if (oldFocusedApplicationHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003274 resetANRTimeoutsLocked();
Tiger Huang721e26f2018-07-24 22:26:19 +08003275 oldFocusedApplicationHandle.clear();
3276 mFocusedApplicationHandlesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003277 }
3278
3279#if DEBUG_FOCUS
3280 //logDispatchStateLocked();
3281#endif
3282 } // release lock
3283
3284 // Wake up poll loop since it may need to make new input dispatching choices.
3285 mLooper->wake();
3286}
3287
Tiger Huang721e26f2018-07-24 22:26:19 +08003288/**
3289 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
3290 * the display not specified.
3291 *
3292 * We track any unreleased events for each window. If a window loses the ability to receive the
3293 * released event, we will send a cancel event to it. So when the focused display is changed, we
3294 * cancel all the unreleased display-unspecified events for the focused window on the old focused
3295 * display. The display-specified events won't be affected.
3296 */
3297void InputDispatcher::setFocusedDisplay(int32_t displayId) {
3298#if DEBUG_FOCUS
3299 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
3300#endif
3301 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003302 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08003303
3304 if (mFocusedDisplayId != displayId) {
3305 sp<InputWindowHandle> oldFocusedWindowHandle =
3306 getValueByKey(mFocusedWindowHandlesByDisplay, mFocusedDisplayId);
3307 if (oldFocusedWindowHandle != nullptr) {
Robert Carr5c8a0262018-10-03 16:30:44 -07003308 sp<InputChannel> inputChannel =
3309 getInputChannelLocked(oldFocusedWindowHandle->getToken());
Tiger Huang721e26f2018-07-24 22:26:19 +08003310 if (inputChannel != nullptr) {
3311 CancelationOptions options(
3312 CancelationOptions::CANCEL_DISPLAY_UNSPECIFIED_EVENTS,
3313 "The display which contains this window no longer has focus.");
3314 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
3315 }
3316 }
3317 mFocusedDisplayId = displayId;
3318
3319 // Sanity check
3320 sp<InputWindowHandle> newFocusedWindowHandle =
3321 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
chaviw0c06c6e2019-01-09 13:27:07 -08003322 onFocusChangedLocked(oldFocusedWindowHandle, newFocusedWindowHandle);
Robert Carrf759f162018-11-13 12:57:11 -08003323
Tiger Huang721e26f2018-07-24 22:26:19 +08003324 if (newFocusedWindowHandle == nullptr) {
3325 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
3326 if (!mFocusedWindowHandlesByDisplay.empty()) {
3327 ALOGE("But another display has a focused window:");
3328 for (auto& it : mFocusedWindowHandlesByDisplay) {
3329 const int32_t displayId = it.first;
3330 const sp<InputWindowHandle>& windowHandle = it.second;
3331 ALOGE("Display #%" PRId32 " has focused window: '%s'\n",
3332 displayId, windowHandle->getName().c_str());
3333 }
3334 }
3335 }
3336 }
3337
3338#if DEBUG_FOCUS
3339 logDispatchStateLocked();
3340#endif
3341 } // release lock
3342
3343 // Wake up poll loop since it may need to make new input dispatching choices.
3344 mLooper->wake();
3345}
3346
Michael Wrightd02c5b62014-02-10 15:10:22 -08003347void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
3348#if DEBUG_FOCUS
3349 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
3350#endif
3351
3352 bool changed;
3353 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003354 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003355
3356 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
3357 if (mDispatchFrozen && !frozen) {
3358 resetANRTimeoutsLocked();
3359 }
3360
3361 if (mDispatchEnabled && !enabled) {
3362 resetAndDropEverythingLocked("dispatcher is being disabled");
3363 }
3364
3365 mDispatchEnabled = enabled;
3366 mDispatchFrozen = frozen;
3367 changed = true;
3368 } else {
3369 changed = false;
3370 }
3371
3372#if DEBUG_FOCUS
Tiger Huang721e26f2018-07-24 22:26:19 +08003373 logDispatchStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003374#endif
3375 } // release lock
3376
3377 if (changed) {
3378 // Wake up poll loop since it may need to make new input dispatching choices.
3379 mLooper->wake();
3380 }
3381}
3382
3383void InputDispatcher::setInputFilterEnabled(bool enabled) {
3384#if DEBUG_FOCUS
3385 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
3386#endif
3387
3388 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003389 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003390
3391 if (mInputFilterEnabled == enabled) {
3392 return;
3393 }
3394
3395 mInputFilterEnabled = enabled;
3396 resetAndDropEverythingLocked("input filter is being enabled or disabled");
3397 } // release lock
3398
3399 // Wake up poll loop since there might be work to do to drop everything.
3400 mLooper->wake();
3401}
3402
chaviwfbe5d9c2018-12-26 12:23:37 -08003403bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken) {
3404 if (fromToken == toToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003405#if DEBUG_FOCUS
chaviwfbe5d9c2018-12-26 12:23:37 -08003406 ALOGD("Trivial transfer to same window.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003407#endif
chaviwfbe5d9c2018-12-26 12:23:37 -08003408 return true;
3409 }
3410
Michael Wrightd02c5b62014-02-10 15:10:22 -08003411 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003412 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003413
chaviwfbe5d9c2018-12-26 12:23:37 -08003414 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromToken);
3415 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toToken);
Yi Kong9b14ac62018-07-17 13:48:38 -07003416 if (fromWindowHandle == nullptr || toWindowHandle == nullptr) {
chaviwfbe5d9c2018-12-26 12:23:37 -08003417 ALOGW("Cannot transfer focus because from or to window not found.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003418 return false;
3419 }
chaviw4f2dd402018-12-26 15:30:27 -08003420#if DEBUG_FOCUS
3421 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
3422 fromWindowHandle->getName().c_str(), toWindowHandle->getName().c_str());
3423#endif
Michael Wrightd02c5b62014-02-10 15:10:22 -08003424 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
3425#if DEBUG_FOCUS
3426 ALOGD("Cannot transfer focus because windows are on different displays.");
3427#endif
3428 return false;
3429 }
3430
3431 bool found = false;
Jeff Brownf086ddb2014-02-11 14:28:48 -08003432 for (size_t d = 0; d < mTouchStatesByDisplay.size(); d++) {
3433 TouchState& state = mTouchStatesByDisplay.editValueAt(d);
3434 for (size_t i = 0; i < state.windows.size(); i++) {
3435 const TouchedWindow& touchedWindow = state.windows[i];
3436 if (touchedWindow.windowHandle == fromWindowHandle) {
3437 int32_t oldTargetFlags = touchedWindow.targetFlags;
3438 BitSet32 pointerIds = touchedWindow.pointerIds;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003439
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003440 state.windows.erase(state.windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003441
Jeff Brownf086ddb2014-02-11 14:28:48 -08003442 int32_t newTargetFlags = oldTargetFlags
3443 & (InputTarget::FLAG_FOREGROUND
3444 | InputTarget::FLAG_SPLIT | InputTarget::FLAG_DISPATCH_AS_IS);
3445 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003446
Jeff Brownf086ddb2014-02-11 14:28:48 -08003447 found = true;
3448 goto Found;
3449 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003450 }
3451 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08003452Found:
Michael Wrightd02c5b62014-02-10 15:10:22 -08003453
3454 if (! found) {
3455#if DEBUG_FOCUS
3456 ALOGD("Focus transfer failed because from window did not have focus.");
3457#endif
3458 return false;
3459 }
3460
chaviwfbe5d9c2018-12-26 12:23:37 -08003461
3462 sp<InputChannel> fromChannel = getInputChannelLocked(fromToken);
3463 sp<InputChannel> toChannel = getInputChannelLocked(toToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003464 ssize_t fromConnectionIndex = getConnectionIndexLocked(fromChannel);
3465 ssize_t toConnectionIndex = getConnectionIndexLocked(toChannel);
3466 if (fromConnectionIndex >= 0 && toConnectionIndex >= 0) {
3467 sp<Connection> fromConnection = mConnectionsByFd.valueAt(fromConnectionIndex);
3468 sp<Connection> toConnection = mConnectionsByFd.valueAt(toConnectionIndex);
3469
3470 fromConnection->inputState.copyPointerStateTo(toConnection->inputState);
3471 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
3472 "transferring touch focus from this window to another window");
3473 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
3474 }
3475
3476#if DEBUG_FOCUS
3477 logDispatchStateLocked();
3478#endif
3479 } // release lock
3480
3481 // Wake up poll loop since it may need to make new input dispatching choices.
3482 mLooper->wake();
3483 return true;
3484}
3485
3486void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
3487#if DEBUG_FOCUS
3488 ALOGD("Resetting and dropping all events (%s).", reason);
3489#endif
3490
3491 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
3492 synthesizeCancelationEventsForAllConnectionsLocked(options);
3493
3494 resetKeyRepeatLocked();
3495 releasePendingEventLocked();
3496 drainInboundQueueLocked();
3497 resetANRTimeoutsLocked();
3498
Jeff Brownf086ddb2014-02-11 14:28:48 -08003499 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003500 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07003501 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003502}
3503
3504void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003505 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003506 dumpDispatchStateLocked(dump);
3507
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003508 std::istringstream stream(dump);
3509 std::string line;
3510
3511 while (std::getline(stream, line, '\n')) {
3512 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003513 }
3514}
3515
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003516void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
3517 dump += StringPrintf(INDENT "DispatchEnabled: %d\n", mDispatchEnabled);
3518 dump += StringPrintf(INDENT "DispatchFrozen: %d\n", mDispatchFrozen);
Tiger Huang721e26f2018-07-24 22:26:19 +08003519 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003520
Tiger Huang721e26f2018-07-24 22:26:19 +08003521 if (!mFocusedApplicationHandlesByDisplay.empty()) {
3522 dump += StringPrintf(INDENT "FocusedApplications:\n");
3523 for (auto& it : mFocusedApplicationHandlesByDisplay) {
3524 const int32_t displayId = it.first;
3525 const sp<InputApplicationHandle>& applicationHandle = it.second;
3526 dump += StringPrintf(
3527 INDENT2 "displayId=%" PRId32 ", name='%s', dispatchingTimeout=%0.3fms\n",
3528 displayId,
3529 applicationHandle->getName().c_str(),
3530 applicationHandle->getDispatchingTimeout(
3531 DEFAULT_INPUT_DISPATCHING_TIMEOUT) / 1000000.0);
3532 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003533 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08003534 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003535 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003536
3537 if (!mFocusedWindowHandlesByDisplay.empty()) {
3538 dump += StringPrintf(INDENT "FocusedWindows:\n");
3539 for (auto& it : mFocusedWindowHandlesByDisplay) {
3540 const int32_t displayId = it.first;
3541 const sp<InputWindowHandle>& windowHandle = it.second;
3542 dump += StringPrintf(INDENT2 "displayId=%" PRId32 ", name='%s'\n",
3543 displayId, windowHandle->getName().c_str());
3544 }
3545 } else {
3546 dump += StringPrintf(INDENT "FocusedWindows: <none>\n");
3547 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003548
Jeff Brownf086ddb2014-02-11 14:28:48 -08003549 if (!mTouchStatesByDisplay.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003550 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Jeff Brownf086ddb2014-02-11 14:28:48 -08003551 for (size_t i = 0; i < mTouchStatesByDisplay.size(); i++) {
3552 const TouchState& state = mTouchStatesByDisplay.valueAt(i);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003553 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Jeff Brownf086ddb2014-02-11 14:28:48 -08003554 state.displayId, toString(state.down), toString(state.split),
3555 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003556 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003557 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08003558 for (size_t i = 0; i < state.windows.size(); i++) {
3559 const TouchedWindow& touchedWindow = state.windows[i];
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003560 dump += StringPrintf(INDENT4 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
3561 i, touchedWindow.windowHandle->getName().c_str(),
Jeff Brownf086ddb2014-02-11 14:28:48 -08003562 touchedWindow.pointerIds.value,
3563 touchedWindow.targetFlags);
3564 }
3565 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003566 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08003567 }
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003568 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08003569 dump += INDENT3 "Portal windows:\n";
3570 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003571 const sp<InputWindowHandle> portalWindowHandle = state.portalWindows[i];
Tiger Huang85b8c5e2019-01-17 18:34:54 +08003572 dump += StringPrintf(INDENT4 "%zu: name='%s'\n",
3573 i, portalWindowHandle->getName().c_str());
3574 }
3575 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003576 }
3577 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003578 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003579 }
3580
Arthur Hungb92218b2018-08-14 12:00:21 +08003581 if (!mWindowHandlesByDisplay.empty()) {
3582 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003583 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08003584 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", it.first);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003585 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003586 dump += INDENT2 "Windows:\n";
3587 for (size_t i = 0; i < windowHandles.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003588 const sp<InputWindowHandle>& windowHandle = windowHandles[i];
Arthur Hungb92218b2018-08-14 12:00:21 +08003589 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003590
Arthur Hungb92218b2018-08-14 12:00:21 +08003591 dump += StringPrintf(INDENT3 "%zu: name='%s', displayId=%d, "
Tiger Huang85b8c5e2019-01-17 18:34:54 +08003592 "portalToDisplayId=%d, paused=%s, hasFocus=%s, hasWallpaper=%s, "
Arthur Hungb92218b2018-08-14 12:00:21 +08003593 "visible=%s, canReceiveKeys=%s, flags=0x%08x, type=0x%08x, layer=%d, "
Riddle Hsu39d4aa52018-11-30 20:46:53 +08003594 "frame=[%d,%d][%d,%d], globalScale=%f, windowScale=(%f,%f), "
Arthur Hungb92218b2018-08-14 12:00:21 +08003595 "touchableRegion=",
3596 i, windowInfo->name.c_str(), windowInfo->displayId,
Tiger Huang85b8c5e2019-01-17 18:34:54 +08003597 windowInfo->portalToDisplayId,
Arthur Hungb92218b2018-08-14 12:00:21 +08003598 toString(windowInfo->paused),
3599 toString(windowInfo->hasFocus),
3600 toString(windowInfo->hasWallpaper),
3601 toString(windowInfo->visible),
3602 toString(windowInfo->canReceiveKeys),
3603 windowInfo->layoutParamsFlags, windowInfo->layoutParamsType,
3604 windowInfo->layer,
3605 windowInfo->frameLeft, windowInfo->frameTop,
3606 windowInfo->frameRight, windowInfo->frameBottom,
Robert Carre07e1032018-11-26 12:55:53 -08003607 windowInfo->globalScaleFactor,
3608 windowInfo->windowXScale, windowInfo->windowYScale);
Arthur Hungb92218b2018-08-14 12:00:21 +08003609 dumpRegion(dump, windowInfo->touchableRegion);
3610 dump += StringPrintf(", inputFeatures=0x%08x", windowInfo->inputFeatures);
3611 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%0.3fms\n",
3612 windowInfo->ownerPid, windowInfo->ownerUid,
3613 windowInfo->dispatchingTimeout / 1000000.0);
3614 }
3615 } else {
3616 dump += INDENT2 "Windows: <none>\n";
3617 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003618 }
3619 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08003620 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003621 }
3622
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003623 if (!mMonitoringChannelsByDisplay.empty()) {
3624 for (auto& it : mMonitoringChannelsByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003625 const std::vector<sp<InputChannel>>& monitoringChannels = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08003626 dump += StringPrintf(INDENT "MonitoringChannels in display %" PRId32 ":\n", it.first);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003627 const size_t numChannels = monitoringChannels.size();
3628 for (size_t i = 0; i < numChannels; i++) {
3629 const sp<InputChannel>& channel = monitoringChannels[i];
3630 dump += StringPrintf(INDENT2 "%zu: '%s'\n", i, channel->getName().c_str());
3631 }
3632 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003633 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003634 dump += INDENT "MonitoringChannels: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003635 }
3636
3637 nsecs_t currentTime = now();
3638
3639 // Dump recently dispatched or dropped events from oldest to newest.
3640 if (!mRecentQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003641 dump += StringPrintf(INDENT "RecentQueue: length=%u\n", mRecentQueue.count());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003642 for (EventEntry* entry = mRecentQueue.head; entry; entry = entry->next) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003643 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003644 entry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003645 dump += StringPrintf(", age=%0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003646 (currentTime - entry->eventTime) * 0.000001f);
3647 }
3648 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003649 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003650 }
3651
3652 // Dump event currently being dispatched.
3653 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003654 dump += INDENT "PendingEvent:\n";
3655 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003656 mPendingEvent->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003657 dump += StringPrintf(", age=%0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003658 (currentTime - mPendingEvent->eventTime) * 0.000001f);
3659 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003660 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003661 }
3662
3663 // Dump inbound events from oldest to newest.
3664 if (!mInboundQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003665 dump += StringPrintf(INDENT "InboundQueue: length=%u\n", mInboundQueue.count());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003666 for (EventEntry* entry = mInboundQueue.head; entry; entry = entry->next) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003667 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003668 entry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003669 dump += StringPrintf(", age=%0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003670 (currentTime - entry->eventTime) * 0.000001f);
3671 }
3672 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003673 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003674 }
3675
Michael Wright78f24442014-08-06 15:55:28 -07003676 if (!mReplacedKeys.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003677 dump += INDENT "ReplacedKeys:\n";
Michael Wright78f24442014-08-06 15:55:28 -07003678 for (size_t i = 0; i < mReplacedKeys.size(); i++) {
3679 const KeyReplacement& replacement = mReplacedKeys.keyAt(i);
3680 int32_t newKeyCode = mReplacedKeys.valueAt(i);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003681 dump += StringPrintf(INDENT2 "%zu: originalKeyCode=%d, deviceId=%d, newKeyCode=%d\n",
Michael Wright78f24442014-08-06 15:55:28 -07003682 i, replacement.keyCode, replacement.deviceId, newKeyCode);
3683 }
3684 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003685 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07003686 }
3687
Michael Wrightd02c5b62014-02-10 15:10:22 -08003688 if (!mConnectionsByFd.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003689 dump += INDENT "Connections:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003690 for (size_t i = 0; i < mConnectionsByFd.size(); i++) {
3691 const sp<Connection>& connection = mConnectionsByFd.valueAt(i);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003692 dump += StringPrintf(INDENT2 "%zu: channelName='%s', windowName='%s', "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003693 "status=%s, monitor=%s, inputPublisherBlocked=%s\n",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08003694 i, connection->getInputChannelName().c_str(),
3695 connection->getWindowName().c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08003696 connection->getStatusLabel(), toString(connection->monitor),
3697 toString(connection->inputPublisherBlocked));
3698
3699 if (!connection->outboundQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003700 dump += StringPrintf(INDENT3 "OutboundQueue: length=%u\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003701 connection->outboundQueue.count());
3702 for (DispatchEntry* entry = connection->outboundQueue.head; entry;
3703 entry = entry->next) {
3704 dump.append(INDENT4);
3705 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003706 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, age=%0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003707 entry->targetFlags, entry->resolvedAction,
3708 (currentTime - entry->eventEntry->eventTime) * 0.000001f);
3709 }
3710 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003711 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003712 }
3713
3714 if (!connection->waitQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003715 dump += StringPrintf(INDENT3 "WaitQueue: length=%u\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003716 connection->waitQueue.count());
3717 for (DispatchEntry* entry = connection->waitQueue.head; entry;
3718 entry = entry->next) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003719 dump += INDENT4;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003720 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003721 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003722 "age=%0.1fms, wait=%0.1fms\n",
3723 entry->targetFlags, entry->resolvedAction,
3724 (currentTime - entry->eventEntry->eventTime) * 0.000001f,
3725 (currentTime - entry->deliveryTime) * 0.000001f);
3726 }
3727 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003728 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003729 }
3730 }
3731 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003732 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003733 }
3734
3735 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003736 dump += StringPrintf(INDENT "AppSwitch: pending, due in %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003737 (mAppSwitchDueTime - now()) / 1000000.0);
3738 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003739 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003740 }
3741
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003742 dump += INDENT "Configuration:\n";
3743 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003744 mConfig.keyRepeatDelay * 0.000001f);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003745 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003746 mConfig.keyRepeatTimeout * 0.000001f);
3747}
3748
Robert Carr803535b2018-08-02 16:38:15 -07003749status_t InputDispatcher::registerInputChannel(const sp<InputChannel>& inputChannel, int32_t displayId) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003750#if DEBUG_REGISTRATION
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003751 ALOGD("channel '%s' ~ registerInputChannel - displayId=%" PRId32,
3752 inputChannel->getName().c_str(), displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003753#endif
3754
3755 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003756 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003757
Robert Carr4e670e52018-08-15 13:26:12 -07003758 // If InputWindowHandle is null and displayId is not ADISPLAY_ID_NONE,
3759 // treat inputChannel as monitor channel for displayId.
3760 bool monitor = inputChannel->getToken() == nullptr && displayId != ADISPLAY_ID_NONE;
3761 if (monitor) {
3762 inputChannel->setToken(new BBinder());
3763 }
3764
Michael Wrightd02c5b62014-02-10 15:10:22 -08003765 if (getConnectionIndexLocked(inputChannel) >= 0) {
3766 ALOGW("Attempted to register already registered input channel '%s'",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003767 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003768 return BAD_VALUE;
3769 }
3770
Robert Carr803535b2018-08-02 16:38:15 -07003771 sp<Connection> connection = new Connection(inputChannel, monitor);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003772
3773 int fd = inputChannel->getFd();
3774 mConnectionsByFd.add(fd, connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07003775 mInputChannelsByToken[inputChannel->getToken()] = inputChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003776
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003777 // Store monitor channel by displayId.
Michael Wrightd02c5b62014-02-10 15:10:22 -08003778 if (monitor) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003779 std::vector<sp<InputChannel>>& monitoringChannels =
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003780 mMonitoringChannelsByDisplay[displayId];
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003781 monitoringChannels.push_back(inputChannel);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003782 }
3783
3784 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
3785 } // release lock
3786
3787 // Wake the looper because some connections have changed.
3788 mLooper->wake();
3789 return OK;
3790}
3791
3792status_t InputDispatcher::unregisterInputChannel(const sp<InputChannel>& inputChannel) {
3793#if DEBUG_REGISTRATION
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003794 ALOGD("channel '%s' ~ unregisterInputChannel", inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003795#endif
3796
3797 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003798 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003799
3800 status_t status = unregisterInputChannelLocked(inputChannel, false /*notify*/);
3801 if (status) {
3802 return status;
3803 }
3804 } // release lock
3805
3806 // Wake the poll loop because removing the connection may have changed the current
3807 // synchronization state.
3808 mLooper->wake();
3809 return OK;
3810}
3811
3812status_t InputDispatcher::unregisterInputChannelLocked(const sp<InputChannel>& inputChannel,
3813 bool notify) {
3814 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
3815 if (connectionIndex < 0) {
3816 ALOGW("Attempted to unregister already unregistered input channel '%s'",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003817 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003818 return BAD_VALUE;
3819 }
3820
3821 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
3822 mConnectionsByFd.removeItemsAt(connectionIndex);
3823
Robert Carr5c8a0262018-10-03 16:30:44 -07003824 mInputChannelsByToken.erase(inputChannel->getToken());
3825
Michael Wrightd02c5b62014-02-10 15:10:22 -08003826 if (connection->monitor) {
3827 removeMonitorChannelLocked(inputChannel);
3828 }
3829
3830 mLooper->removeFd(inputChannel->getFd());
3831
3832 nsecs_t currentTime = now();
3833 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
3834
3835 connection->status = Connection::STATUS_ZOMBIE;
3836 return OK;
3837}
3838
3839void InputDispatcher::removeMonitorChannelLocked(const sp<InputChannel>& inputChannel) {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003840 for (auto it = mMonitoringChannelsByDisplay.begin();
3841 it != mMonitoringChannelsByDisplay.end(); ) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003842 std::vector<sp<InputChannel>>& monitoringChannels = it->second;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003843 const size_t numChannels = monitoringChannels.size();
3844 for (size_t i = 0; i < numChannels; i++) {
3845 if (monitoringChannels[i] == inputChannel) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003846 monitoringChannels.erase(monitoringChannels.begin() + i);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003847 break;
3848 }
3849 }
3850 if (monitoringChannels.empty()) {
3851 it = mMonitoringChannelsByDisplay.erase(it);
3852 } else {
3853 ++it;
3854 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003855 }
3856}
3857
3858ssize_t InputDispatcher::getConnectionIndexLocked(const sp<InputChannel>& inputChannel) {
Robert Carr4e670e52018-08-15 13:26:12 -07003859 if (inputChannel == nullptr) {
Arthur Hung3b413f22018-10-26 18:05:34 +08003860 return -1;
3861 }
3862
Robert Carr4e670e52018-08-15 13:26:12 -07003863 for (size_t i = 0; i < mConnectionsByFd.size(); i++) {
3864 sp<Connection> connection = mConnectionsByFd.valueAt(i);
3865 if (connection->inputChannel->getToken() == inputChannel->getToken()) {
3866 return i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003867 }
3868 }
Robert Carr4e670e52018-08-15 13:26:12 -07003869
Michael Wrightd02c5b62014-02-10 15:10:22 -08003870 return -1;
3871}
3872
3873void InputDispatcher::onDispatchCycleFinishedLocked(
3874 nsecs_t currentTime, const sp<Connection>& connection, uint32_t seq, bool handled) {
3875 CommandEntry* commandEntry = postCommandLocked(
3876 & InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
3877 commandEntry->connection = connection;
3878 commandEntry->eventTime = currentTime;
3879 commandEntry->seq = seq;
3880 commandEntry->handled = handled;
3881}
3882
3883void InputDispatcher::onDispatchCycleBrokenLocked(
3884 nsecs_t currentTime, const sp<Connection>& connection) {
3885 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08003886 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003887
3888 CommandEntry* commandEntry = postCommandLocked(
3889 & InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
3890 commandEntry->connection = connection;
3891}
3892
chaviw0c06c6e2019-01-09 13:27:07 -08003893void InputDispatcher::onFocusChangedLocked(const sp<InputWindowHandle>& oldFocus,
3894 const sp<InputWindowHandle>& newFocus) {
3895 sp<IBinder> oldToken = oldFocus != nullptr ? oldFocus->getToken() : nullptr;
3896 sp<IBinder> newToken = newFocus != nullptr ? newFocus->getToken() : nullptr;
Robert Carrf759f162018-11-13 12:57:11 -08003897 CommandEntry* commandEntry = postCommandLocked(
3898 & InputDispatcher::doNotifyFocusChangedLockedInterruptible);
chaviw0c06c6e2019-01-09 13:27:07 -08003899 commandEntry->oldToken = oldToken;
3900 commandEntry->newToken = newToken;
Robert Carrf759f162018-11-13 12:57:11 -08003901}
3902
Michael Wrightd02c5b62014-02-10 15:10:22 -08003903void InputDispatcher::onANRLocked(
3904 nsecs_t currentTime, const sp<InputApplicationHandle>& applicationHandle,
3905 const sp<InputWindowHandle>& windowHandle,
3906 nsecs_t eventTime, nsecs_t waitStartTime, const char* reason) {
3907 float dispatchLatency = (currentTime - eventTime) * 0.000001f;
3908 float waitDuration = (currentTime - waitStartTime) * 0.000001f;
3909 ALOGI("Application is not responding: %s. "
3910 "It has been %0.1fms since event, %0.1fms since wait started. Reason: %s",
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003911 getApplicationWindowLabel(applicationHandle, windowHandle).c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08003912 dispatchLatency, waitDuration, reason);
3913
3914 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07003915 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003916 struct tm tm;
3917 localtime_r(&t, &tm);
3918 char timestr[64];
3919 strftime(timestr, sizeof(timestr), "%F %T", &tm);
3920 mLastANRState.clear();
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003921 mLastANRState += INDENT "ANR:\n";
3922 mLastANRState += StringPrintf(INDENT2 "Time: %s\n", timestr);
3923 mLastANRState += StringPrintf(INDENT2 "Window: %s\n",
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003924 getApplicationWindowLabel(applicationHandle, windowHandle).c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003925 mLastANRState += StringPrintf(INDENT2 "DispatchLatency: %0.1fms\n", dispatchLatency);
3926 mLastANRState += StringPrintf(INDENT2 "WaitDuration: %0.1fms\n", waitDuration);
3927 mLastANRState += StringPrintf(INDENT2 "Reason: %s\n", reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003928 dumpDispatchStateLocked(mLastANRState);
3929
3930 CommandEntry* commandEntry = postCommandLocked(
3931 & InputDispatcher::doNotifyANRLockedInterruptible);
3932 commandEntry->inputApplicationHandle = applicationHandle;
Robert Carr5c8a0262018-10-03 16:30:44 -07003933 commandEntry->inputChannel = windowHandle != nullptr ?
3934 getInputChannelLocked(windowHandle->getToken()) : nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003935 commandEntry->reason = reason;
3936}
3937
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003938void InputDispatcher::doNotifyConfigurationChangedLockedInterruptible (
Michael Wrightd02c5b62014-02-10 15:10:22 -08003939 CommandEntry* commandEntry) {
3940 mLock.unlock();
3941
3942 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
3943
3944 mLock.lock();
3945}
3946
3947void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(
3948 CommandEntry* commandEntry) {
3949 sp<Connection> connection = commandEntry->connection;
3950
3951 if (connection->status != Connection::STATUS_ZOMBIE) {
3952 mLock.unlock();
3953
Robert Carr803535b2018-08-02 16:38:15 -07003954 mPolicy->notifyInputChannelBroken(connection->inputChannel->getToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003955
3956 mLock.lock();
3957 }
3958}
3959
Robert Carrf759f162018-11-13 12:57:11 -08003960void InputDispatcher::doNotifyFocusChangedLockedInterruptible(
3961 CommandEntry* commandEntry) {
chaviw0c06c6e2019-01-09 13:27:07 -08003962 sp<IBinder> oldToken = commandEntry->oldToken;
3963 sp<IBinder> newToken = commandEntry->newToken;
Robert Carrf759f162018-11-13 12:57:11 -08003964 mLock.unlock();
chaviw0c06c6e2019-01-09 13:27:07 -08003965 mPolicy->notifyFocusChanged(oldToken, newToken);
Robert Carrf759f162018-11-13 12:57:11 -08003966 mLock.lock();
3967}
3968
Michael Wrightd02c5b62014-02-10 15:10:22 -08003969void InputDispatcher::doNotifyANRLockedInterruptible(
3970 CommandEntry* commandEntry) {
3971 mLock.unlock();
3972
3973 nsecs_t newTimeout = mPolicy->notifyANR(
Robert Carr803535b2018-08-02 16:38:15 -07003974 commandEntry->inputApplicationHandle,
3975 commandEntry->inputChannel ? commandEntry->inputChannel->getToken() : nullptr,
Michael Wrightd02c5b62014-02-10 15:10:22 -08003976 commandEntry->reason);
3977
3978 mLock.lock();
3979
3980 resumeAfterTargetsNotReadyTimeoutLocked(newTimeout,
Robert Carr803535b2018-08-02 16:38:15 -07003981 commandEntry->inputChannel);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003982}
3983
3984void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
3985 CommandEntry* commandEntry) {
3986 KeyEntry* entry = commandEntry->keyEntry;
3987
3988 KeyEvent event;
3989 initializeKeyEvent(&event, entry);
3990
3991 mLock.unlock();
3992
Michael Wright2b3c3302018-03-02 17:19:13 +00003993 android::base::Timer t;
Robert Carr803535b2018-08-02 16:38:15 -07003994 sp<IBinder> token = commandEntry->inputChannel != nullptr ?
3995 commandEntry->inputChannel->getToken() : nullptr;
3996 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(token,
Michael Wrightd02c5b62014-02-10 15:10:22 -08003997 &event, entry->policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003998 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3999 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
4000 std::to_string(t.duration().count()).c_str());
4001 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004002
4003 mLock.lock();
4004
4005 if (delay < 0) {
4006 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
4007 } else if (!delay) {
4008 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
4009 } else {
4010 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
4011 entry->interceptKeyWakeupTime = now() + delay;
4012 }
4013 entry->release();
4014}
4015
4016void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(
4017 CommandEntry* commandEntry) {
4018 sp<Connection> connection = commandEntry->connection;
4019 nsecs_t finishTime = commandEntry->eventTime;
4020 uint32_t seq = commandEntry->seq;
4021 bool handled = commandEntry->handled;
4022
4023 // Handle post-event policy actions.
4024 DispatchEntry* dispatchEntry = connection->findWaitQueueEntry(seq);
4025 if (dispatchEntry) {
4026 nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
4027 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004028 std::string msg =
4029 StringPrintf("Window '%s' spent %0.1fms processing the last input event: ",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004030 connection->getWindowName().c_str(), eventDuration * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004031 dispatchEntry->eventEntry->appendDescription(msg);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004032 ALOGI("%s", msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004033 }
4034
4035 bool restartEvent;
4036 if (dispatchEntry->eventEntry->type == EventEntry::TYPE_KEY) {
4037 KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry);
4038 restartEvent = afterKeyEventLockedInterruptible(connection,
4039 dispatchEntry, keyEntry, handled);
4040 } else if (dispatchEntry->eventEntry->type == EventEntry::TYPE_MOTION) {
4041 MotionEntry* motionEntry = static_cast<MotionEntry*>(dispatchEntry->eventEntry);
4042 restartEvent = afterMotionEventLockedInterruptible(connection,
4043 dispatchEntry, motionEntry, handled);
4044 } else {
4045 restartEvent = false;
4046 }
4047
4048 // Dequeue the event and start the next cycle.
4049 // Note that because the lock might have been released, it is possible that the
4050 // contents of the wait queue to have been drained, so we need to double-check
4051 // a few things.
4052 if (dispatchEntry == connection->findWaitQueueEntry(seq)) {
4053 connection->waitQueue.dequeue(dispatchEntry);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08004054 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004055 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
4056 connection->outboundQueue.enqueueAtHead(dispatchEntry);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08004057 traceOutboundQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004058 } else {
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08004059 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004060 }
4061 }
4062
4063 // Start the next dispatch cycle for this connection.
4064 startDispatchCycleLocked(now(), connection);
4065 }
4066}
4067
4068bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
4069 DispatchEntry* dispatchEntry, KeyEntry* keyEntry, bool handled) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004070 if (keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004071 if (!handled) {
4072 // Report the key as unhandled, since the fallback was not handled.
4073 mReporter->reportUnhandledKey(keyEntry->sequenceNum);
4074 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004075 return false;
4076 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004077
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004078 // Get the fallback key state.
4079 // Clear it out after dispatching the UP.
4080 int32_t originalKeyCode = keyEntry->keyCode;
4081 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
4082 if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
4083 connection->inputState.removeFallbackKey(originalKeyCode);
4084 }
4085
4086 if (handled || !dispatchEntry->hasForegroundTarget()) {
4087 // If the application handles the original key for which we previously
4088 // generated a fallback or if the window is not a foreground window,
4089 // then cancel the associated fallback key, if any.
4090 if (fallbackKeyCode != -1) {
4091 // Dispatch the unhandled key to the policy with the cancel flag.
Michael Wrightd02c5b62014-02-10 15:10:22 -08004092#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004093 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
Michael Wrightd02c5b62014-02-10 15:10:22 -08004094 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4095 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
4096 keyEntry->policyFlags);
4097#endif
4098 KeyEvent event;
4099 initializeKeyEvent(&event, keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004100 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004101
4102 mLock.unlock();
4103
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004104 mPolicy->dispatchUnhandledKey(connection->inputChannel->getToken(),
4105 &event, keyEntry->policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004106
4107 mLock.lock();
4108
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004109 // Cancel the fallback key.
4110 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004111 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004112 "application handled the original non-fallback key "
4113 "or is no longer a foreground target, "
4114 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004115 options.keyCode = fallbackKeyCode;
4116 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004117 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004118 connection->inputState.removeFallbackKey(originalKeyCode);
4119 }
4120 } else {
4121 // If the application did not handle a non-fallback key, first check
4122 // that we are in a good state to perform unhandled key event processing
4123 // Then ask the policy what to do with it.
4124 bool initialDown = keyEntry->action == AKEY_EVENT_ACTION_DOWN
4125 && keyEntry->repeatCount == 0;
4126 if (fallbackKeyCode == -1 && !initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004127#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004128 ALOGD("Unhandled key event: Skipping unhandled key event processing "
4129 "since this is not an initial down. "
4130 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4131 originalKeyCode, keyEntry->action, keyEntry->repeatCount,
4132 keyEntry->policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004133#endif
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004134 return false;
4135 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004136
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004137 // Dispatch the unhandled key to the policy.
4138#if DEBUG_OUTBOUND_EVENT_DETAILS
4139 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
4140 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4141 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
4142 keyEntry->policyFlags);
4143#endif
4144 KeyEvent event;
4145 initializeKeyEvent(&event, keyEntry);
4146
4147 mLock.unlock();
4148
4149 bool fallback = mPolicy->dispatchUnhandledKey(connection->inputChannel->getToken(),
4150 &event, keyEntry->policyFlags, &event);
4151
4152 mLock.lock();
4153
4154 if (connection->status != Connection::STATUS_NORMAL) {
4155 connection->inputState.removeFallbackKey(originalKeyCode);
4156 return false;
4157 }
4158
4159 // Latch the fallback keycode for this key on an initial down.
4160 // The fallback keycode cannot change at any other point in the lifecycle.
4161 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004162 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004163 fallbackKeyCode = event.getKeyCode();
4164 } else {
4165 fallbackKeyCode = AKEYCODE_UNKNOWN;
4166 }
4167 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
4168 }
4169
4170 ALOG_ASSERT(fallbackKeyCode != -1);
4171
4172 // Cancel the fallback key if the policy decides not to send it anymore.
4173 // We will continue to dispatch the key to the policy but we will no
4174 // longer dispatch a fallback key to the application.
4175 if (fallbackKeyCode != AKEYCODE_UNKNOWN
4176 && (!fallback || fallbackKeyCode != event.getKeyCode())) {
4177#if DEBUG_OUTBOUND_EVENT_DETAILS
4178 if (fallback) {
4179 ALOGD("Unhandled key event: Policy requested to send key %d"
4180 "as a fallback for %d, but on the DOWN it had requested "
4181 "to send %d instead. Fallback canceled.",
4182 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
4183 } else {
4184 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
4185 "but on the DOWN it had requested to send %d. "
4186 "Fallback canceled.",
4187 originalKeyCode, fallbackKeyCode);
4188 }
4189#endif
4190
4191 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
4192 "canceling fallback, policy no longer desires it");
4193 options.keyCode = fallbackKeyCode;
4194 synthesizeCancelationEventsForConnectionLocked(connection, options);
4195
4196 fallback = false;
4197 fallbackKeyCode = AKEYCODE_UNKNOWN;
4198 if (keyEntry->action != AKEY_EVENT_ACTION_UP) {
4199 connection->inputState.setFallbackKey(originalKeyCode,
4200 fallbackKeyCode);
4201 }
4202 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004203
4204#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004205 {
4206 std::string msg;
4207 const KeyedVector<int32_t, int32_t>& fallbackKeys =
4208 connection->inputState.getFallbackKeys();
4209 for (size_t i = 0; i < fallbackKeys.size(); i++) {
4210 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i),
4211 fallbackKeys.valueAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004212 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004213 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
4214 fallbackKeys.size(), msg.c_str());
4215 }
4216#endif
4217
4218 if (fallback) {
4219 // Restart the dispatch cycle using the fallback key.
4220 keyEntry->eventTime = event.getEventTime();
4221 keyEntry->deviceId = event.getDeviceId();
4222 keyEntry->source = event.getSource();
4223 keyEntry->displayId = event.getDisplayId();
4224 keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
4225 keyEntry->keyCode = fallbackKeyCode;
4226 keyEntry->scanCode = event.getScanCode();
4227 keyEntry->metaState = event.getMetaState();
4228 keyEntry->repeatCount = event.getRepeatCount();
4229 keyEntry->downTime = event.getDownTime();
4230 keyEntry->syntheticRepeat = false;
4231
4232#if DEBUG_OUTBOUND_EVENT_DETAILS
4233 ALOGD("Unhandled key event: Dispatching fallback key. "
4234 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
4235 originalKeyCode, fallbackKeyCode, keyEntry->metaState);
4236#endif
4237 return true; // restart the event
4238 } else {
4239#if DEBUG_OUTBOUND_EVENT_DETAILS
4240 ALOGD("Unhandled key event: No fallback key.");
4241#endif
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004242
4243 // Report the key as unhandled, since there is no fallback key.
4244 mReporter->reportUnhandledKey(keyEntry->sequenceNum);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004245 }
4246 }
4247 return false;
4248}
4249
4250bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
4251 DispatchEntry* dispatchEntry, MotionEntry* motionEntry, bool handled) {
4252 return false;
4253}
4254
4255void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
4256 mLock.unlock();
4257
4258 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
4259
4260 mLock.lock();
4261}
4262
4263void InputDispatcher::initializeKeyEvent(KeyEvent* event, const KeyEntry* entry) {
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004264 event->initialize(entry->deviceId, entry->source, entry->displayId, entry->action, entry->flags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004265 entry->keyCode, entry->scanCode, entry->metaState, entry->repeatCount,
4266 entry->downTime, entry->eventTime);
4267}
4268
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08004269void InputDispatcher::updateDispatchStatistics(nsecs_t currentTime, const EventEntry* entry,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004270 int32_t injectionResult, nsecs_t timeSpentWaitingForApplication) {
4271 // TODO Write some statistics about how long we spend waiting.
4272}
4273
4274void InputDispatcher::traceInboundQueueLengthLocked() {
4275 if (ATRACE_ENABLED()) {
4276 ATRACE_INT("iq", mInboundQueue.count());
4277 }
4278}
4279
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08004280void InputDispatcher::traceOutboundQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004281 if (ATRACE_ENABLED()) {
4282 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004283 snprintf(counterName, sizeof(counterName), "oq:%s", connection->getWindowName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004284 ATRACE_INT(counterName, connection->outboundQueue.count());
4285 }
4286}
4287
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08004288void InputDispatcher::traceWaitQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004289 if (ATRACE_ENABLED()) {
4290 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004291 snprintf(counterName, sizeof(counterName), "wq:%s", connection->getWindowName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004292 ATRACE_INT(counterName, connection->waitQueue.count());
4293 }
4294}
4295
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004296void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004297 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004298
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004299 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004300 dumpDispatchStateLocked(dump);
4301
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004302 if (!mLastANRState.empty()) {
4303 dump += "\nInput Dispatcher State at time of last ANR:\n";
4304 dump += mLastANRState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004305 }
4306}
4307
4308void InputDispatcher::monitor() {
4309 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004310 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004311 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004312 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004313}
4314
4315
Michael Wrightd02c5b62014-02-10 15:10:22 -08004316// --- InputDispatcher::InjectionState ---
4317
4318InputDispatcher::InjectionState::InjectionState(int32_t injectorPid, int32_t injectorUid) :
4319 refCount(1),
4320 injectorPid(injectorPid), injectorUid(injectorUid),
4321 injectionResult(INPUT_EVENT_INJECTION_PENDING), injectionIsAsync(false),
4322 pendingForegroundDispatches(0) {
4323}
4324
4325InputDispatcher::InjectionState::~InjectionState() {
4326}
4327
4328void InputDispatcher::InjectionState::release() {
4329 refCount -= 1;
4330 if (refCount == 0) {
4331 delete this;
4332 } else {
4333 ALOG_ASSERT(refCount > 0);
4334 }
4335}
4336
4337
4338// --- InputDispatcher::EventEntry ---
4339
Prabir Pradhan42611e02018-11-27 14:04:02 -08004340InputDispatcher::EventEntry::EventEntry(uint32_t sequenceNum, int32_t type,
4341 nsecs_t eventTime, uint32_t policyFlags) :
4342 sequenceNum(sequenceNum), refCount(1), type(type), eventTime(eventTime),
4343 policyFlags(policyFlags), injectionState(nullptr), dispatchInProgress(false) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004344}
4345
4346InputDispatcher::EventEntry::~EventEntry() {
4347 releaseInjectionState();
4348}
4349
4350void InputDispatcher::EventEntry::release() {
4351 refCount -= 1;
4352 if (refCount == 0) {
4353 delete this;
4354 } else {
4355 ALOG_ASSERT(refCount > 0);
4356 }
4357}
4358
4359void InputDispatcher::EventEntry::releaseInjectionState() {
4360 if (injectionState) {
4361 injectionState->release();
Yi Kong9b14ac62018-07-17 13:48:38 -07004362 injectionState = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004363 }
4364}
4365
4366
4367// --- InputDispatcher::ConfigurationChangedEntry ---
4368
Prabir Pradhan42611e02018-11-27 14:04:02 -08004369InputDispatcher::ConfigurationChangedEntry::ConfigurationChangedEntry(
4370 uint32_t sequenceNum, nsecs_t eventTime) :
4371 EventEntry(sequenceNum, TYPE_CONFIGURATION_CHANGED, eventTime, 0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004372}
4373
4374InputDispatcher::ConfigurationChangedEntry::~ConfigurationChangedEntry() {
4375}
4376
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004377void InputDispatcher::ConfigurationChangedEntry::appendDescription(std::string& msg) const {
4378 msg += StringPrintf("ConfigurationChangedEvent(), policyFlags=0x%08x", policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004379}
4380
4381
4382// --- InputDispatcher::DeviceResetEntry ---
4383
Prabir Pradhan42611e02018-11-27 14:04:02 -08004384InputDispatcher::DeviceResetEntry::DeviceResetEntry(
4385 uint32_t sequenceNum, nsecs_t eventTime, int32_t deviceId) :
4386 EventEntry(sequenceNum, TYPE_DEVICE_RESET, eventTime, 0),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004387 deviceId(deviceId) {
4388}
4389
4390InputDispatcher::DeviceResetEntry::~DeviceResetEntry() {
4391}
4392
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004393void InputDispatcher::DeviceResetEntry::appendDescription(std::string& msg) const {
4394 msg += StringPrintf("DeviceResetEvent(deviceId=%d), policyFlags=0x%08x",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004395 deviceId, policyFlags);
4396}
4397
4398
4399// --- InputDispatcher::KeyEntry ---
4400
Prabir Pradhan42611e02018-11-27 14:04:02 -08004401InputDispatcher::KeyEntry::KeyEntry(uint32_t sequenceNum, nsecs_t eventTime,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004402 int32_t deviceId, uint32_t source, int32_t displayId, uint32_t policyFlags, int32_t action,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004403 int32_t flags, int32_t keyCode, int32_t scanCode, int32_t metaState,
4404 int32_t repeatCount, nsecs_t downTime) :
Prabir Pradhan42611e02018-11-27 14:04:02 -08004405 EventEntry(sequenceNum, TYPE_KEY, eventTime, policyFlags),
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004406 deviceId(deviceId), source(source), displayId(displayId), action(action), flags(flags),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004407 keyCode(keyCode), scanCode(scanCode), metaState(metaState),
4408 repeatCount(repeatCount), downTime(downTime),
4409 syntheticRepeat(false), interceptKeyResult(KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN),
4410 interceptKeyWakeupTime(0) {
4411}
4412
4413InputDispatcher::KeyEntry::~KeyEntry() {
4414}
4415
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004416void InputDispatcher::KeyEntry::appendDescription(std::string& msg) const {
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004417 msg += StringPrintf("KeyEvent(deviceId=%d, source=0x%08x, displayId=%" PRId32 ", action=%s, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08004418 "flags=0x%08x, keyCode=%d, scanCode=%d, metaState=0x%08x, "
4419 "repeatCount=%d), policyFlags=0x%08x",
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004420 deviceId, source, displayId, keyActionToString(action).c_str(), flags, keyCode,
Siarhei Vishniakoub48188a2018-03-01 20:55:47 -08004421 scanCode, metaState, repeatCount, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004422}
4423
4424void InputDispatcher::KeyEntry::recycle() {
4425 releaseInjectionState();
4426
4427 dispatchInProgress = false;
4428 syntheticRepeat = false;
4429 interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
4430 interceptKeyWakeupTime = 0;
4431}
4432
4433
4434// --- InputDispatcher::MotionEntry ---
4435
Prabir Pradhan42611e02018-11-27 14:04:02 -08004436InputDispatcher::MotionEntry::MotionEntry(uint32_t sequenceNum, nsecs_t eventTime, int32_t deviceId,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004437 uint32_t source, int32_t displayId, uint32_t policyFlags, int32_t action,
4438 int32_t actionButton,
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08004439 int32_t flags, int32_t metaState, int32_t buttonState, MotionClassification classification,
4440 int32_t edgeFlags, float xPrecision, float yPrecision, nsecs_t downTime,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004441 uint32_t pointerCount,
Jeff Brownf086ddb2014-02-11 14:28:48 -08004442 const PointerProperties* pointerProperties, const PointerCoords* pointerCoords,
4443 float xOffset, float yOffset) :
Prabir Pradhan42611e02018-11-27 14:04:02 -08004444 EventEntry(sequenceNum, TYPE_MOTION, eventTime, policyFlags),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004445 eventTime(eventTime),
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004446 deviceId(deviceId), source(source), displayId(displayId), action(action),
4447 actionButton(actionButton), flags(flags), metaState(metaState), buttonState(buttonState),
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08004448 classification(classification), edgeFlags(edgeFlags),
4449 xPrecision(xPrecision), yPrecision(yPrecision),
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004450 downTime(downTime), pointerCount(pointerCount) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004451 for (uint32_t i = 0; i < pointerCount; i++) {
4452 this->pointerProperties[i].copyFrom(pointerProperties[i]);
4453 this->pointerCoords[i].copyFrom(pointerCoords[i]);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004454 if (xOffset || yOffset) {
4455 this->pointerCoords[i].applyOffset(xOffset, yOffset);
4456 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004457 }
4458}
4459
4460InputDispatcher::MotionEntry::~MotionEntry() {
4461}
4462
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004463void InputDispatcher::MotionEntry::appendDescription(std::string& msg) const {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004464 msg += StringPrintf("MotionEvent(deviceId=%d, source=0x%08x, displayId=%" PRId32
Siarhei Vishniakoub48188a2018-03-01 20:55:47 -08004465 ", action=%s, actionButton=0x%08x, flags=0x%08x, metaState=0x%08x, buttonState=0x%08x, "
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08004466 "classification=%s, edgeFlags=0x%08x, xPrecision=%.1f, yPrecision=%.1f, pointers=[",
Siarhei Vishniakoub48188a2018-03-01 20:55:47 -08004467 deviceId, source, displayId, motionActionToString(action).c_str(), actionButton, flags,
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08004468 metaState, buttonState, motionClassificationToString(classification), edgeFlags,
4469 xPrecision, yPrecision);
Siarhei Vishniakoub48188a2018-03-01 20:55:47 -08004470
Michael Wrightd02c5b62014-02-10 15:10:22 -08004471 for (uint32_t i = 0; i < pointerCount; i++) {
4472 if (i) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004473 msg += ", ";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004474 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004475 msg += StringPrintf("%d: (%.1f, %.1f)", pointerProperties[i].id,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004476 pointerCoords[i].getX(), pointerCoords[i].getY());
4477 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004478 msg += StringPrintf("]), policyFlags=0x%08x", policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004479}
4480
4481
4482// --- InputDispatcher::DispatchEntry ---
4483
4484volatile int32_t InputDispatcher::DispatchEntry::sNextSeqAtomic;
4485
4486InputDispatcher::DispatchEntry::DispatchEntry(EventEntry* eventEntry,
Robert Carre07e1032018-11-26 12:55:53 -08004487 int32_t targetFlags, float xOffset, float yOffset, float globalScaleFactor,
4488 float windowXScale, float windowYScale) :
Michael Wrightd02c5b62014-02-10 15:10:22 -08004489 seq(nextSeq()),
4490 eventEntry(eventEntry), targetFlags(targetFlags),
Robert Carre07e1032018-11-26 12:55:53 -08004491 xOffset(xOffset), yOffset(yOffset), globalScaleFactor(globalScaleFactor),
4492 windowXScale(windowXScale), windowYScale(windowYScale),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004493 deliveryTime(0), resolvedAction(0), resolvedFlags(0) {
4494 eventEntry->refCount += 1;
4495}
4496
4497InputDispatcher::DispatchEntry::~DispatchEntry() {
4498 eventEntry->release();
4499}
4500
4501uint32_t InputDispatcher::DispatchEntry::nextSeq() {
4502 // Sequence number 0 is reserved and will never be returned.
4503 uint32_t seq;
4504 do {
4505 seq = android_atomic_inc(&sNextSeqAtomic);
4506 } while (!seq);
4507 return seq;
4508}
4509
4510
4511// --- InputDispatcher::InputState ---
4512
4513InputDispatcher::InputState::InputState() {
4514}
4515
4516InputDispatcher::InputState::~InputState() {
4517}
4518
4519bool InputDispatcher::InputState::isNeutral() const {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004520 return mKeyMementos.empty() && mMotionMementos.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004521}
4522
4523bool InputDispatcher::InputState::isHovering(int32_t deviceId, uint32_t source,
4524 int32_t displayId) const {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004525 for (const MotionMemento& memento : mMotionMementos) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004526 if (memento.deviceId == deviceId
4527 && memento.source == source
4528 && memento.displayId == displayId
4529 && memento.hovering) {
4530 return true;
4531 }
4532 }
4533 return false;
4534}
4535
4536bool InputDispatcher::InputState::trackKey(const KeyEntry* entry,
4537 int32_t action, int32_t flags) {
4538 switch (action) {
4539 case AKEY_EVENT_ACTION_UP: {
4540 if (entry->flags & AKEY_EVENT_FLAG_FALLBACK) {
4541 for (size_t i = 0; i < mFallbackKeys.size(); ) {
4542 if (mFallbackKeys.valueAt(i) == entry->keyCode) {
4543 mFallbackKeys.removeItemsAt(i);
4544 } else {
4545 i += 1;
4546 }
4547 }
4548 }
4549 ssize_t index = findKeyMemento(entry);
4550 if (index >= 0) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004551 mKeyMementos.erase(mKeyMementos.begin() + index);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004552 return true;
4553 }
4554 /* FIXME: We can't just drop the key up event because that prevents creating
4555 * popup windows that are automatically shown when a key is held and then
4556 * dismissed when the key is released. The problem is that the popup will
4557 * not have received the original key down, so the key up will be considered
4558 * to be inconsistent with its observed state. We could perhaps handle this
4559 * by synthesizing a key down but that will cause other problems.
4560 *
4561 * So for now, allow inconsistent key up events to be dispatched.
4562 *
4563#if DEBUG_OUTBOUND_EVENT_DETAILS
4564 ALOGD("Dropping inconsistent key up event: deviceId=%d, source=%08x, "
4565 "keyCode=%d, scanCode=%d",
4566 entry->deviceId, entry->source, entry->keyCode, entry->scanCode);
4567#endif
4568 return false;
4569 */
4570 return true;
4571 }
4572
4573 case AKEY_EVENT_ACTION_DOWN: {
4574 ssize_t index = findKeyMemento(entry);
4575 if (index >= 0) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004576 mKeyMementos.erase(mKeyMementos.begin() + index);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004577 }
4578 addKeyMemento(entry, flags);
4579 return true;
4580 }
4581
4582 default:
4583 return true;
4584 }
4585}
4586
4587bool InputDispatcher::InputState::trackMotion(const MotionEntry* entry,
4588 int32_t action, int32_t flags) {
4589 int32_t actionMasked = action & AMOTION_EVENT_ACTION_MASK;
4590 switch (actionMasked) {
4591 case AMOTION_EVENT_ACTION_UP:
4592 case AMOTION_EVENT_ACTION_CANCEL: {
4593 ssize_t index = findMotionMemento(entry, false /*hovering*/);
4594 if (index >= 0) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004595 mMotionMementos.erase(mMotionMementos.begin() + index);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004596 return true;
4597 }
4598#if DEBUG_OUTBOUND_EVENT_DETAILS
4599 ALOGD("Dropping inconsistent motion up or cancel event: deviceId=%d, source=%08x, "
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004600 "displayId=%" PRId32 ", actionMasked=%d",
4601 entry->deviceId, entry->source, entry->displayId, actionMasked);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004602#endif
4603 return false;
4604 }
4605
4606 case AMOTION_EVENT_ACTION_DOWN: {
4607 ssize_t index = findMotionMemento(entry, false /*hovering*/);
4608 if (index >= 0) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004609 mMotionMementos.erase(mMotionMementos.begin() + index);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004610 }
4611 addMotionMemento(entry, flags, false /*hovering*/);
4612 return true;
4613 }
4614
4615 case AMOTION_EVENT_ACTION_POINTER_UP:
4616 case AMOTION_EVENT_ACTION_POINTER_DOWN:
4617 case AMOTION_EVENT_ACTION_MOVE: {
Michael Wright38dcdff2014-03-19 12:06:10 -07004618 if (entry->source & AINPUT_SOURCE_CLASS_NAVIGATION) {
4619 // Trackballs can send MOVE events with a corresponding DOWN or UP. There's no need to
4620 // generate cancellation events for these since they're based in relative rather than
4621 // absolute units.
4622 return true;
4623 }
4624
Michael Wrightd02c5b62014-02-10 15:10:22 -08004625 ssize_t index = findMotionMemento(entry, false /*hovering*/);
Michael Wright38dcdff2014-03-19 12:06:10 -07004626
4627 if (entry->source & AINPUT_SOURCE_CLASS_JOYSTICK) {
4628 // Joysticks can send MOVE events without a corresponding DOWN or UP. Since all
4629 // joystick axes are normalized to [-1, 1] we can trust that 0 means it's neutral. Any
4630 // other value and we need to track the motion so we can send cancellation events for
4631 // anything generating fallback events (e.g. DPad keys for joystick movements).
4632 if (index >= 0) {
4633 if (entry->pointerCoords[0].isEmpty()) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004634 mMotionMementos.erase(mMotionMementos.begin() + index);
Michael Wright38dcdff2014-03-19 12:06:10 -07004635 } else {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004636 MotionMemento& memento = mMotionMementos[index];
Michael Wright38dcdff2014-03-19 12:06:10 -07004637 memento.setPointers(entry);
4638 }
4639 } else if (!entry->pointerCoords[0].isEmpty()) {
4640 addMotionMemento(entry, flags, false /*hovering*/);
4641 }
4642
4643 // Joysticks and trackballs can send MOVE events without corresponding DOWN or UP.
4644 return true;
4645 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004646 if (index >= 0) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004647 MotionMemento& memento = mMotionMementos[index];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004648 memento.setPointers(entry);
4649 return true;
4650 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004651#if DEBUG_OUTBOUND_EVENT_DETAILS
4652 ALOGD("Dropping inconsistent motion pointer up/down or move event: "
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004653 "deviceId=%d, source=%08x, displayId=%" PRId32 ", actionMasked=%d",
4654 entry->deviceId, entry->source, entry->displayId, actionMasked);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004655#endif
4656 return false;
4657 }
4658
4659 case AMOTION_EVENT_ACTION_HOVER_EXIT: {
4660 ssize_t index = findMotionMemento(entry, true /*hovering*/);
4661 if (index >= 0) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004662 mMotionMementos.erase(mMotionMementos.begin() + index);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004663 return true;
4664 }
4665#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004666 ALOGD("Dropping inconsistent motion hover exit event: deviceId=%d, source=%08x, "
4667 "displayId=%" PRId32,
4668 entry->deviceId, entry->source, entry->displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004669#endif
4670 return false;
4671 }
4672
4673 case AMOTION_EVENT_ACTION_HOVER_ENTER:
4674 case AMOTION_EVENT_ACTION_HOVER_MOVE: {
4675 ssize_t index = findMotionMemento(entry, true /*hovering*/);
4676 if (index >= 0) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004677 mMotionMementos.erase(mMotionMementos.begin() + index);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004678 }
4679 addMotionMemento(entry, flags, true /*hovering*/);
4680 return true;
4681 }
4682
4683 default:
4684 return true;
4685 }
4686}
4687
4688ssize_t InputDispatcher::InputState::findKeyMemento(const KeyEntry* entry) const {
4689 for (size_t i = 0; i < mKeyMementos.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004690 const KeyMemento& memento = mKeyMementos[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004691 if (memento.deviceId == entry->deviceId
4692 && memento.source == entry->source
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004693 && memento.displayId == entry->displayId
Michael Wrightd02c5b62014-02-10 15:10:22 -08004694 && memento.keyCode == entry->keyCode
4695 && memento.scanCode == entry->scanCode) {
4696 return i;
4697 }
4698 }
4699 return -1;
4700}
4701
4702ssize_t InputDispatcher::InputState::findMotionMemento(const MotionEntry* entry,
4703 bool hovering) const {
4704 for (size_t i = 0; i < mMotionMementos.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004705 const MotionMemento& memento = mMotionMementos[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004706 if (memento.deviceId == entry->deviceId
4707 && memento.source == entry->source
4708 && memento.displayId == entry->displayId
4709 && memento.hovering == hovering) {
4710 return i;
4711 }
4712 }
4713 return -1;
4714}
4715
4716void InputDispatcher::InputState::addKeyMemento(const KeyEntry* entry, int32_t flags) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004717 KeyMemento memento;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004718 memento.deviceId = entry->deviceId;
4719 memento.source = entry->source;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004720 memento.displayId = entry->displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004721 memento.keyCode = entry->keyCode;
4722 memento.scanCode = entry->scanCode;
4723 memento.metaState = entry->metaState;
4724 memento.flags = flags;
4725 memento.downTime = entry->downTime;
4726 memento.policyFlags = entry->policyFlags;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004727 mKeyMementos.push_back(memento);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004728}
4729
4730void InputDispatcher::InputState::addMotionMemento(const MotionEntry* entry,
4731 int32_t flags, bool hovering) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004732 MotionMemento memento;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004733 memento.deviceId = entry->deviceId;
4734 memento.source = entry->source;
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004735 memento.displayId = entry->displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004736 memento.flags = flags;
4737 memento.xPrecision = entry->xPrecision;
4738 memento.yPrecision = entry->yPrecision;
4739 memento.downTime = entry->downTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004740 memento.setPointers(entry);
4741 memento.hovering = hovering;
4742 memento.policyFlags = entry->policyFlags;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004743 mMotionMementos.push_back(memento);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004744}
4745
4746void InputDispatcher::InputState::MotionMemento::setPointers(const MotionEntry* entry) {
4747 pointerCount = entry->pointerCount;
4748 for (uint32_t i = 0; i < entry->pointerCount; i++) {
4749 pointerProperties[i].copyFrom(entry->pointerProperties[i]);
4750 pointerCoords[i].copyFrom(entry->pointerCoords[i]);
4751 }
4752}
4753
4754void InputDispatcher::InputState::synthesizeCancelationEvents(nsecs_t currentTime,
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004755 std::vector<EventEntry*>& outEvents, const CancelationOptions& options) {
4756 for (KeyMemento& memento : mKeyMementos) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004757 if (shouldCancelKey(memento, options)) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004758 outEvents.push_back(new KeyEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, currentTime,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004759 memento.deviceId, memento.source, memento.displayId, memento.policyFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004760 AKEY_EVENT_ACTION_UP, memento.flags | AKEY_EVENT_FLAG_CANCELED,
4761 memento.keyCode, memento.scanCode, memento.metaState, 0, memento.downTime));
4762 }
4763 }
4764
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004765 for (const MotionMemento& memento : mMotionMementos) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004766 if (shouldCancelMotion(memento, options)) {
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08004767 const int32_t action = memento.hovering ?
4768 AMOTION_EVENT_ACTION_HOVER_EXIT : AMOTION_EVENT_ACTION_CANCEL;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004769 outEvents.push_back(new MotionEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, currentTime,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004770 memento.deviceId, memento.source, memento.displayId, memento.policyFlags,
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08004771 action, 0 /*actionButton*/, memento.flags, AMETA_NONE, 0 /*buttonState*/,
4772 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004773 memento.xPrecision, memento.yPrecision, memento.downTime,
Jeff Brownf086ddb2014-02-11 14:28:48 -08004774 memento.pointerCount, memento.pointerProperties, memento.pointerCoords,
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08004775 0 /*xOffset*/, 0 /*yOffset*/));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004776 }
4777 }
4778}
4779
4780void InputDispatcher::InputState::clear() {
4781 mKeyMementos.clear();
4782 mMotionMementos.clear();
4783 mFallbackKeys.clear();
4784}
4785
4786void InputDispatcher::InputState::copyPointerStateTo(InputState& other) const {
4787 for (size_t i = 0; i < mMotionMementos.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004788 const MotionMemento& memento = mMotionMementos[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004789 if (memento.source & AINPUT_SOURCE_CLASS_POINTER) {
4790 for (size_t j = 0; j < other.mMotionMementos.size(); ) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004791 const MotionMemento& otherMemento = other.mMotionMementos[j];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004792 if (memento.deviceId == otherMemento.deviceId
4793 && memento.source == otherMemento.source
4794 && memento.displayId == otherMemento.displayId) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004795 other.mMotionMementos.erase(other.mMotionMementos.begin() + j);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004796 } else {
4797 j += 1;
4798 }
4799 }
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004800 other.mMotionMementos.push_back(memento);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004801 }
4802 }
4803}
4804
4805int32_t InputDispatcher::InputState::getFallbackKey(int32_t originalKeyCode) {
4806 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
4807 return index >= 0 ? mFallbackKeys.valueAt(index) : -1;
4808}
4809
4810void InputDispatcher::InputState::setFallbackKey(int32_t originalKeyCode,
4811 int32_t fallbackKeyCode) {
4812 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
4813 if (index >= 0) {
4814 mFallbackKeys.replaceValueAt(index, fallbackKeyCode);
4815 } else {
4816 mFallbackKeys.add(originalKeyCode, fallbackKeyCode);
4817 }
4818}
4819
4820void InputDispatcher::InputState::removeFallbackKey(int32_t originalKeyCode) {
4821 mFallbackKeys.removeItem(originalKeyCode);
4822}
4823
4824bool InputDispatcher::InputState::shouldCancelKey(const KeyMemento& memento,
4825 const CancelationOptions& options) {
4826 if (options.keyCode != -1 && memento.keyCode != options.keyCode) {
4827 return false;
4828 }
4829
4830 if (options.deviceId != -1 && memento.deviceId != options.deviceId) {
4831 return false;
4832 }
4833
4834 switch (options.mode) {
4835 case CancelationOptions::CANCEL_ALL_EVENTS:
4836 case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
4837 return true;
4838 case CancelationOptions::CANCEL_FALLBACK_EVENTS:
4839 return memento.flags & AKEY_EVENT_FLAG_FALLBACK;
Tiger Huang721e26f2018-07-24 22:26:19 +08004840 case CancelationOptions::CANCEL_DISPLAY_UNSPECIFIED_EVENTS:
4841 return memento.displayId == ADISPLAY_ID_NONE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004842 default:
4843 return false;
4844 }
4845}
4846
4847bool InputDispatcher::InputState::shouldCancelMotion(const MotionMemento& memento,
4848 const CancelationOptions& options) {
4849 if (options.deviceId != -1 && memento.deviceId != options.deviceId) {
4850 return false;
4851 }
4852
4853 switch (options.mode) {
4854 case CancelationOptions::CANCEL_ALL_EVENTS:
4855 return true;
4856 case CancelationOptions::CANCEL_POINTER_EVENTS:
4857 return memento.source & AINPUT_SOURCE_CLASS_POINTER;
4858 case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
4859 return !(memento.source & AINPUT_SOURCE_CLASS_POINTER);
Tiger Huang721e26f2018-07-24 22:26:19 +08004860 case CancelationOptions::CANCEL_DISPLAY_UNSPECIFIED_EVENTS:
4861 return memento.displayId == ADISPLAY_ID_NONE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004862 default:
4863 return false;
4864 }
4865}
4866
4867
4868// --- InputDispatcher::Connection ---
4869
Robert Carr803535b2018-08-02 16:38:15 -07004870InputDispatcher::Connection::Connection(const sp<InputChannel>& inputChannel, bool monitor) :
4871 status(STATUS_NORMAL), inputChannel(inputChannel),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004872 monitor(monitor),
4873 inputPublisher(inputChannel), inputPublisherBlocked(false) {
4874}
4875
4876InputDispatcher::Connection::~Connection() {
4877}
4878
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004879const std::string InputDispatcher::Connection::getWindowName() const {
Robert Carr803535b2018-08-02 16:38:15 -07004880 if (inputChannel != nullptr) {
4881 return inputChannel->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004882 }
4883 if (monitor) {
4884 return "monitor";
4885 }
4886 return "?";
4887}
4888
4889const char* InputDispatcher::Connection::getStatusLabel() const {
4890 switch (status) {
4891 case STATUS_NORMAL:
4892 return "NORMAL";
4893
4894 case STATUS_BROKEN:
4895 return "BROKEN";
4896
4897 case STATUS_ZOMBIE:
4898 return "ZOMBIE";
4899
4900 default:
4901 return "UNKNOWN";
4902 }
4903}
4904
4905InputDispatcher::DispatchEntry* InputDispatcher::Connection::findWaitQueueEntry(uint32_t seq) {
Yi Kong9b14ac62018-07-17 13:48:38 -07004906 for (DispatchEntry* entry = waitQueue.head; entry != nullptr; entry = entry->next) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004907 if (entry->seq == seq) {
4908 return entry;
4909 }
4910 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004911 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004912}
4913
4914
4915// --- InputDispatcher::CommandEntry ---
4916
4917InputDispatcher::CommandEntry::CommandEntry(Command command) :
Yi Kong9b14ac62018-07-17 13:48:38 -07004918 command(command), eventTime(0), keyEntry(nullptr), userActivityEventType(0),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004919 seq(0), handled(false) {
4920}
4921
4922InputDispatcher::CommandEntry::~CommandEntry() {
4923}
4924
4925
4926// --- InputDispatcher::TouchState ---
4927
4928InputDispatcher::TouchState::TouchState() :
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004929 down(false), split(false), deviceId(-1), source(0), displayId(ADISPLAY_ID_NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004930}
4931
4932InputDispatcher::TouchState::~TouchState() {
4933}
4934
4935void InputDispatcher::TouchState::reset() {
4936 down = false;
4937 split = false;
4938 deviceId = -1;
4939 source = 0;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004940 displayId = ADISPLAY_ID_NONE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004941 windows.clear();
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004942 portalWindows.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004943}
4944
4945void InputDispatcher::TouchState::copyFrom(const TouchState& other) {
4946 down = other.down;
4947 split = other.split;
4948 deviceId = other.deviceId;
4949 source = other.source;
4950 displayId = other.displayId;
4951 windows = other.windows;
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004952 portalWindows = other.portalWindows;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004953}
4954
4955void InputDispatcher::TouchState::addOrUpdateWindow(const sp<InputWindowHandle>& windowHandle,
4956 int32_t targetFlags, BitSet32 pointerIds) {
4957 if (targetFlags & InputTarget::FLAG_SPLIT) {
4958 split = true;
4959 }
4960
4961 for (size_t i = 0; i < windows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004962 TouchedWindow& touchedWindow = windows[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004963 if (touchedWindow.windowHandle == windowHandle) {
4964 touchedWindow.targetFlags |= targetFlags;
4965 if (targetFlags & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
4966 touchedWindow.targetFlags &= ~InputTarget::FLAG_DISPATCH_AS_IS;
4967 }
4968 touchedWindow.pointerIds.value |= pointerIds.value;
4969 return;
4970 }
4971 }
4972
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004973 TouchedWindow touchedWindow;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004974 touchedWindow.windowHandle = windowHandle;
4975 touchedWindow.targetFlags = targetFlags;
4976 touchedWindow.pointerIds = pointerIds;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004977 windows.push_back(touchedWindow);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004978}
4979
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004980void InputDispatcher::TouchState::addPortalWindow(const sp<InputWindowHandle>& windowHandle) {
4981 size_t numWindows = portalWindows.size();
4982 for (size_t i = 0; i < numWindows; i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004983 if (portalWindows[i] == windowHandle) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004984 return;
4985 }
4986 }
4987 portalWindows.push_back(windowHandle);
4988}
4989
Michael Wrightd02c5b62014-02-10 15:10:22 -08004990void InputDispatcher::TouchState::removeWindow(const sp<InputWindowHandle>& windowHandle) {
4991 for (size_t i = 0; i < windows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004992 if (windows[i].windowHandle == windowHandle) {
4993 windows.erase(windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004994 return;
4995 }
4996 }
4997}
4998
Robert Carr803535b2018-08-02 16:38:15 -07004999void InputDispatcher::TouchState::removeWindowByToken(const sp<IBinder>& token) {
5000 for (size_t i = 0; i < windows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005001 if (windows[i].windowHandle->getToken() == token) {
5002 windows.erase(windows.begin() + i);
Robert Carr803535b2018-08-02 16:38:15 -07005003 return;
5004 }
5005 }
5006}
5007
Michael Wrightd02c5b62014-02-10 15:10:22 -08005008void InputDispatcher::TouchState::filterNonAsIsTouchWindows() {
5009 for (size_t i = 0 ; i < windows.size(); ) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005010 TouchedWindow& window = windows[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08005011 if (window.targetFlags & (InputTarget::FLAG_DISPATCH_AS_IS
5012 | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER)) {
5013 window.targetFlags &= ~InputTarget::FLAG_DISPATCH_MASK;
5014 window.targetFlags |= InputTarget::FLAG_DISPATCH_AS_IS;
5015 i += 1;
5016 } else {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005017 windows.erase(windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005018 }
5019 }
5020}
5021
5022sp<InputWindowHandle> InputDispatcher::TouchState::getFirstForegroundWindowHandle() const {
5023 for (size_t i = 0; i < windows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005024 const TouchedWindow& window = windows[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08005025 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
5026 return window.windowHandle;
5027 }
5028 }
Yi Kong9b14ac62018-07-17 13:48:38 -07005029 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005030}
5031
5032bool InputDispatcher::TouchState::isSlippery() const {
5033 // Must have exactly one foreground window.
5034 bool haveSlipperyForegroundWindow = false;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005035 for (const TouchedWindow& window : windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005036 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
5037 if (haveSlipperyForegroundWindow
5038 || !(window.windowHandle->getInfo()->layoutParamsFlags
5039 & InputWindowInfo::FLAG_SLIPPERY)) {
5040 return false;
5041 }
5042 haveSlipperyForegroundWindow = true;
5043 }
5044 }
5045 return haveSlipperyForegroundWindow;
5046}
5047
5048
5049// --- InputDispatcherThread ---
5050
5051InputDispatcherThread::InputDispatcherThread(const sp<InputDispatcherInterface>& dispatcher) :
5052 Thread(/*canCallJava*/ true), mDispatcher(dispatcher) {
5053}
5054
5055InputDispatcherThread::~InputDispatcherThread() {
5056}
5057
5058bool InputDispatcherThread::threadLoop() {
5059 mDispatcher->dispatchOnce();
5060 return true;
5061}
5062
5063} // namespace android