blob: 9d924353235a8d89da9d3023898eeafbc15b169b [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>
49#include <limits.h>
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080050#include <sstream>
Mark Salyzyna5e161b2016-09-29 08:08:05 -070051#include <stddef.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080052#include <time.h>
Mark Salyzyna5e161b2016-09-29 08:08:05 -070053#include <unistd.h>
54
Michael Wright2b3c3302018-03-02 17:19:13 +000055#include <android-base/chrono_utils.h>
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080056#include <android-base/stringprintf.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070057#include <log/log.h>
Mark Salyzyna5e161b2016-09-29 08:08:05 -070058#include <utils/Trace.h>
59#include <powermanager/PowerManager.h>
60#include <ui/Region.h>
Robert Carr4e670e52018-08-15 13:26:12 -070061#include <binder/Binder.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080062
63#define INDENT " "
64#define INDENT2 " "
65#define INDENT3 " "
66#define INDENT4 " "
67
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080068using android::base::StringPrintf;
69
Michael Wrightd02c5b62014-02-10 15:10:22 -080070namespace android {
71
72// Default input dispatching timeout if there is no focused application or paused window
73// from which to determine an appropriate dispatching timeout.
Michael Wright2b3c3302018-03-02 17:19:13 +000074constexpr nsecs_t DEFAULT_INPUT_DISPATCHING_TIMEOUT = 5000 * 1000000LL; // 5 sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080075
76// Amount of time to allow for all pending events to be processed when an app switch
77// key is on the way. This is used to preempt input dispatch and drop input events
78// when an application takes too long to respond and the user has pressed an app switch key.
Michael Wright2b3c3302018-03-02 17:19:13 +000079constexpr nsecs_t APP_SWITCH_TIMEOUT = 500 * 1000000LL; // 0.5sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080080
81// Amount of time to allow for an event to be dispatched (measured since its eventTime)
82// before considering it stale and dropping it.
Michael Wright2b3c3302018-03-02 17:19:13 +000083constexpr nsecs_t STALE_EVENT_TIMEOUT = 10000 * 1000000LL; // 10sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080084
85// Amount of time to allow touch events to be streamed out to a connection before requiring
86// that the first event be finished. This value extends the ANR timeout by the specified
87// amount. For example, if streaming is allowed to get ahead by one second relative to the
88// queue of waiting unfinished events, then ANRs will similarly be delayed by one second.
Michael Wright2b3c3302018-03-02 17:19:13 +000089constexpr nsecs_t STREAM_AHEAD_EVENT_TIMEOUT = 500 * 1000000LL; // 0.5sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080090
91// 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 +000092constexpr nsecs_t SLOW_EVENT_PROCESSING_WARNING_TIMEOUT = 2000 * 1000000LL; // 2sec
93
94// Log a warning when an interception call takes longer than this to process.
95constexpr std::chrono::milliseconds SLOW_INTERCEPTION_THRESHOLD = 50ms;
Michael Wrightd02c5b62014-02-10 15:10:22 -080096
97// Number of recent events to keep for debugging purposes.
Michael Wright2b3c3302018-03-02 17:19:13 +000098constexpr size_t RECENT_QUEUE_MAX_SIZE = 10;
99
Prabir Pradhan42611e02018-11-27 14:04:02 -0800100// Sequence number for synthesized or injected events.
101constexpr uint32_t SYNTHESIZED_EVENT_SEQUENCE_NUM = 0;
102
Michael Wrightd02c5b62014-02-10 15:10:22 -0800103
104static inline nsecs_t now() {
105 return systemTime(SYSTEM_TIME_MONOTONIC);
106}
107
108static inline const char* toString(bool value) {
109 return value ? "true" : "false";
110}
111
Siarhei Vishniakoub48188a2018-03-01 20:55:47 -0800112static std::string motionActionToString(int32_t action) {
113 // Convert MotionEvent action to string
114 switch(action & AMOTION_EVENT_ACTION_MASK) {
115 case AMOTION_EVENT_ACTION_DOWN:
116 return "DOWN";
117 case AMOTION_EVENT_ACTION_MOVE:
118 return "MOVE";
119 case AMOTION_EVENT_ACTION_UP:
120 return "UP";
121 case AMOTION_EVENT_ACTION_POINTER_DOWN:
122 return "POINTER_DOWN";
123 case AMOTION_EVENT_ACTION_POINTER_UP:
124 return "POINTER_UP";
125 }
126 return StringPrintf("%" PRId32, action);
127}
128
129static std::string keyActionToString(int32_t action) {
130 // Convert KeyEvent action to string
131 switch(action) {
132 case AKEY_EVENT_ACTION_DOWN:
133 return "DOWN";
134 case AKEY_EVENT_ACTION_UP:
135 return "UP";
136 case AKEY_EVENT_ACTION_MULTIPLE:
137 return "MULTIPLE";
138 }
139 return StringPrintf("%" PRId32, action);
140}
141
Michael Wrightd02c5b62014-02-10 15:10:22 -0800142static inline int32_t getMotionEventActionPointerIndex(int32_t action) {
143 return (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK)
144 >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
145}
146
147static bool isValidKeyAction(int32_t action) {
148 switch (action) {
149 case AKEY_EVENT_ACTION_DOWN:
150 case AKEY_EVENT_ACTION_UP:
151 return true;
152 default:
153 return false;
154 }
155}
156
157static bool validateKeyEvent(int32_t action) {
158 if (! isValidKeyAction(action)) {
159 ALOGE("Key event has invalid action code 0x%x", action);
160 return false;
161 }
162 return true;
163}
164
Michael Wright7b159c92015-05-14 14:48:03 +0100165static bool isValidMotionAction(int32_t action, int32_t actionButton, int32_t pointerCount) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800166 switch (action & AMOTION_EVENT_ACTION_MASK) {
167 case AMOTION_EVENT_ACTION_DOWN:
168 case AMOTION_EVENT_ACTION_UP:
169 case AMOTION_EVENT_ACTION_CANCEL:
170 case AMOTION_EVENT_ACTION_MOVE:
171 case AMOTION_EVENT_ACTION_OUTSIDE:
172 case AMOTION_EVENT_ACTION_HOVER_ENTER:
173 case AMOTION_EVENT_ACTION_HOVER_MOVE:
174 case AMOTION_EVENT_ACTION_HOVER_EXIT:
175 case AMOTION_EVENT_ACTION_SCROLL:
176 return true;
177 case AMOTION_EVENT_ACTION_POINTER_DOWN:
178 case AMOTION_EVENT_ACTION_POINTER_UP: {
179 int32_t index = getMotionEventActionPointerIndex(action);
Dan Albert1bd2fc02016-02-02 15:11:57 -0800180 return index >= 0 && index < pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800181 }
Michael Wright7b159c92015-05-14 14:48:03 +0100182 case AMOTION_EVENT_ACTION_BUTTON_PRESS:
183 case AMOTION_EVENT_ACTION_BUTTON_RELEASE:
184 return actionButton != 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800185 default:
186 return false;
187 }
188}
189
Michael Wright7b159c92015-05-14 14:48:03 +0100190static bool validateMotionEvent(int32_t action, int32_t actionButton, size_t pointerCount,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800191 const PointerProperties* pointerProperties) {
Michael Wright7b159c92015-05-14 14:48:03 +0100192 if (! isValidMotionAction(action, actionButton, pointerCount)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800193 ALOGE("Motion event has invalid action code 0x%x", action);
194 return false;
195 }
196 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Narayan Kamath37764c72014-03-27 14:21:09 +0000197 ALOGE("Motion event has invalid pointer count %zu; value must be between 1 and %d.",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800198 pointerCount, MAX_POINTERS);
199 return false;
200 }
201 BitSet32 pointerIdBits;
202 for (size_t i = 0; i < pointerCount; i++) {
203 int32_t id = pointerProperties[i].id;
204 if (id < 0 || id > MAX_POINTER_ID) {
205 ALOGE("Motion event has invalid pointer id %d; value must be between 0 and %d",
206 id, MAX_POINTER_ID);
207 return false;
208 }
209 if (pointerIdBits.hasBit(id)) {
210 ALOGE("Motion event has duplicate pointer id %d", id);
211 return false;
212 }
213 pointerIdBits.markBit(id);
214 }
215 return true;
216}
217
218static bool isMainDisplay(int32_t displayId) {
219 return displayId == ADISPLAY_ID_DEFAULT || displayId == ADISPLAY_ID_NONE;
220}
221
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800222static void dumpRegion(std::string& dump, const Region& region) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800223 if (region.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800224 dump += "<empty>";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800225 return;
226 }
227
228 bool first = true;
229 Region::const_iterator cur = region.begin();
230 Region::const_iterator const tail = region.end();
231 while (cur != tail) {
232 if (first) {
233 first = false;
234 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800235 dump += "|";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800236 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800237 dump += StringPrintf("[%d,%d][%d,%d]", cur->left, cur->top, cur->right, cur->bottom);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800238 cur++;
239 }
240}
241
Tiger Huang721e26f2018-07-24 22:26:19 +0800242template<typename T, typename U>
243static T getValueByKey(std::unordered_map<U, T>& map, U key) {
244 typename std::unordered_map<U, T>::const_iterator it = map.find(key);
245 return it != map.end() ? it->second : T{};
246}
247
Michael Wrightd02c5b62014-02-10 15:10:22 -0800248
249// --- InputDispatcher ---
250
251InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy) :
252 mPolicy(policy),
Yi Kong9b14ac62018-07-17 13:48:38 -0700253 mPendingEvent(nullptr), mLastDropReason(DROP_REASON_NOT_DROPPED),
Michael Wright3a981722015-06-10 15:26:13 +0100254 mAppSwitchSawKeyDown(false), mAppSwitchDueTime(LONG_LONG_MAX),
Yi Kong9b14ac62018-07-17 13:48:38 -0700255 mNextUnblockedEvent(nullptr),
Michael Wrightd02c5b62014-02-10 15:10:22 -0800256 mDispatchEnabled(false), mDispatchFrozen(false), mInputFilterEnabled(false),
Tiger Huang721e26f2018-07-24 22:26:19 +0800257 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
Michael Wrightd02c5b62014-02-10 15:10:22 -0800258 mInputTargetWaitCause(INPUT_TARGET_WAIT_CAUSE_NONE) {
259 mLooper = new Looper(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800260 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800261
Yi Kong9b14ac62018-07-17 13:48:38 -0700262 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800263
264 policy->getDispatcherConfiguration(&mConfig);
265}
266
267InputDispatcher::~InputDispatcher() {
268 { // acquire lock
269 AutoMutex _l(mLock);
270
271 resetKeyRepeatLocked();
272 releasePendingEventLocked();
273 drainInboundQueueLocked();
274 }
275
276 while (mConnectionsByFd.size() != 0) {
277 unregisterInputChannel(mConnectionsByFd.valueAt(0)->inputChannel);
278 }
279}
280
281void InputDispatcher::dispatchOnce() {
282 nsecs_t nextWakeupTime = LONG_LONG_MAX;
283 { // acquire lock
284 AutoMutex _l(mLock);
285 mDispatcherIsAliveCondition.broadcast();
286
287 // Run a dispatch loop if there are no pending commands.
288 // The dispatch loop might enqueue commands to run afterwards.
289 if (!haveCommandsLocked()) {
290 dispatchOnceInnerLocked(&nextWakeupTime);
291 }
292
293 // Run all pending commands if there are any.
294 // If any commands were run then force the next poll to wake up immediately.
295 if (runCommandsLockedInterruptible()) {
296 nextWakeupTime = LONG_LONG_MIN;
297 }
298 } // release lock
299
300 // Wait for callback or timeout or wake. (make sure we round up, not down)
301 nsecs_t currentTime = now();
302 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
303 mLooper->pollOnce(timeoutMillis);
304}
305
306void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
307 nsecs_t currentTime = now();
308
Jeff Browndc5992e2014-04-11 01:27:26 -0700309 // Reset the key repeat timer whenever normal dispatch is suspended while the
310 // device is in a non-interactive state. This is to ensure that we abort a key
311 // repeat if the device is just coming out of sleep.
312 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800313 resetKeyRepeatLocked();
314 }
315
316 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
317 if (mDispatchFrozen) {
318#if DEBUG_FOCUS
319 ALOGD("Dispatch frozen. Waiting some more.");
320#endif
321 return;
322 }
323
324 // Optimize latency of app switches.
325 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
326 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
327 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
328 if (mAppSwitchDueTime < *nextWakeupTime) {
329 *nextWakeupTime = mAppSwitchDueTime;
330 }
331
332 // Ready to start a new event.
333 // If we don't already have a pending event, go grab one.
334 if (! mPendingEvent) {
335 if (mInboundQueue.isEmpty()) {
336 if (isAppSwitchDue) {
337 // The inbound queue is empty so the app switch key we were waiting
338 // for will never arrive. Stop waiting for it.
339 resetPendingAppSwitchLocked(false);
340 isAppSwitchDue = false;
341 }
342
343 // Synthesize a key repeat if appropriate.
344 if (mKeyRepeatState.lastKeyEntry) {
345 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
346 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
347 } else {
348 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
349 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
350 }
351 }
352 }
353
354 // Nothing to do if there is no pending event.
355 if (!mPendingEvent) {
356 return;
357 }
358 } else {
359 // Inbound queue has at least one entry.
360 mPendingEvent = mInboundQueue.dequeueAtHead();
361 traceInboundQueueLengthLocked();
362 }
363
364 // Poke user activity for this event.
365 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
366 pokeUserActivityLocked(mPendingEvent);
367 }
368
369 // Get ready to dispatch the event.
370 resetANRTimeoutsLocked();
371 }
372
373 // Now we have an event to dispatch.
374 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700375 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800376 bool done = false;
377 DropReason dropReason = DROP_REASON_NOT_DROPPED;
378 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
379 dropReason = DROP_REASON_POLICY;
380 } else if (!mDispatchEnabled) {
381 dropReason = DROP_REASON_DISABLED;
382 }
383
384 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700385 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800386 }
387
388 switch (mPendingEvent->type) {
389 case EventEntry::TYPE_CONFIGURATION_CHANGED: {
390 ConfigurationChangedEntry* typedEntry =
391 static_cast<ConfigurationChangedEntry*>(mPendingEvent);
392 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
393 dropReason = DROP_REASON_NOT_DROPPED; // configuration changes are never dropped
394 break;
395 }
396
397 case EventEntry::TYPE_DEVICE_RESET: {
398 DeviceResetEntry* typedEntry =
399 static_cast<DeviceResetEntry*>(mPendingEvent);
400 done = dispatchDeviceResetLocked(currentTime, typedEntry);
401 dropReason = DROP_REASON_NOT_DROPPED; // device resets are never dropped
402 break;
403 }
404
405 case EventEntry::TYPE_KEY: {
406 KeyEntry* typedEntry = static_cast<KeyEntry*>(mPendingEvent);
407 if (isAppSwitchDue) {
408 if (isAppSwitchKeyEventLocked(typedEntry)) {
409 resetPendingAppSwitchLocked(true);
410 isAppSwitchDue = false;
411 } else if (dropReason == DROP_REASON_NOT_DROPPED) {
412 dropReason = DROP_REASON_APP_SWITCH;
413 }
414 }
415 if (dropReason == DROP_REASON_NOT_DROPPED
416 && isStaleEventLocked(currentTime, typedEntry)) {
417 dropReason = DROP_REASON_STALE;
418 }
419 if (dropReason == DROP_REASON_NOT_DROPPED && mNextUnblockedEvent) {
420 dropReason = DROP_REASON_BLOCKED;
421 }
422 done = dispatchKeyLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
423 break;
424 }
425
426 case EventEntry::TYPE_MOTION: {
427 MotionEntry* typedEntry = static_cast<MotionEntry*>(mPendingEvent);
428 if (dropReason == DROP_REASON_NOT_DROPPED && isAppSwitchDue) {
429 dropReason = DROP_REASON_APP_SWITCH;
430 }
431 if (dropReason == DROP_REASON_NOT_DROPPED
432 && isStaleEventLocked(currentTime, typedEntry)) {
433 dropReason = DROP_REASON_STALE;
434 }
435 if (dropReason == DROP_REASON_NOT_DROPPED && mNextUnblockedEvent) {
436 dropReason = DROP_REASON_BLOCKED;
437 }
438 done = dispatchMotionLocked(currentTime, typedEntry,
439 &dropReason, nextWakeupTime);
440 break;
441 }
442
443 default:
444 ALOG_ASSERT(false);
445 break;
446 }
447
448 if (done) {
449 if (dropReason != DROP_REASON_NOT_DROPPED) {
450 dropInboundEventLocked(mPendingEvent, dropReason);
451 }
Michael Wright3a981722015-06-10 15:26:13 +0100452 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800453
454 releasePendingEventLocked();
455 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
456 }
457}
458
459bool InputDispatcher::enqueueInboundEventLocked(EventEntry* entry) {
460 bool needWake = mInboundQueue.isEmpty();
461 mInboundQueue.enqueueAtTail(entry);
462 traceInboundQueueLengthLocked();
463
464 switch (entry->type) {
465 case EventEntry::TYPE_KEY: {
466 // Optimize app switch latency.
467 // If the application takes too long to catch up then we drop all events preceding
468 // the app switch key.
469 KeyEntry* keyEntry = static_cast<KeyEntry*>(entry);
470 if (isAppSwitchKeyEventLocked(keyEntry)) {
471 if (keyEntry->action == AKEY_EVENT_ACTION_DOWN) {
472 mAppSwitchSawKeyDown = true;
473 } else if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
474 if (mAppSwitchSawKeyDown) {
475#if DEBUG_APP_SWITCH
476 ALOGD("App switch is pending!");
477#endif
478 mAppSwitchDueTime = keyEntry->eventTime + APP_SWITCH_TIMEOUT;
479 mAppSwitchSawKeyDown = false;
480 needWake = true;
481 }
482 }
483 }
484 break;
485 }
486
487 case EventEntry::TYPE_MOTION: {
488 // Optimize case where the current application is unresponsive and the user
489 // decides to touch a window in a different application.
490 // If the application takes too long to catch up then we drop all events preceding
491 // the touch into the other window.
492 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
493 if (motionEntry->action == AMOTION_EVENT_ACTION_DOWN
494 && (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER)
495 && mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY
Robert Carr740167f2018-10-11 19:03:41 -0700496 && mInputTargetWaitApplicationToken != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800497 int32_t displayId = motionEntry->displayId;
498 int32_t x = int32_t(motionEntry->pointerCoords[0].
499 getAxisValue(AMOTION_EVENT_AXIS_X));
500 int32_t y = int32_t(motionEntry->pointerCoords[0].
501 getAxisValue(AMOTION_EVENT_AXIS_Y));
502 sp<InputWindowHandle> touchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y);
Yi Kong9b14ac62018-07-17 13:48:38 -0700503 if (touchedWindowHandle != nullptr
Robert Carr740167f2018-10-11 19:03:41 -0700504 && touchedWindowHandle->getApplicationToken()
505 != mInputTargetWaitApplicationToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800506 // User touched a different application than the one we are waiting on.
507 // Flag the event, and start pruning the input queue.
508 mNextUnblockedEvent = motionEntry;
509 needWake = true;
510 }
511 }
512 break;
513 }
514 }
515
516 return needWake;
517}
518
519void InputDispatcher::addRecentEventLocked(EventEntry* entry) {
520 entry->refCount += 1;
521 mRecentQueue.enqueueAtTail(entry);
522 if (mRecentQueue.count() > RECENT_QUEUE_MAX_SIZE) {
523 mRecentQueue.dequeueAtHead()->release();
524 }
525}
526
527sp<InputWindowHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId,
528 int32_t x, int32_t y) {
529 // Traverse windows from front to back to find touched window.
Arthur Hungb92218b2018-08-14 12:00:21 +0800530 const Vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
531 size_t numWindows = windowHandles.size();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800532 for (size_t i = 0; i < numWindows; i++) {
Arthur Hungb92218b2018-08-14 12:00:21 +0800533 sp<InputWindowHandle> windowHandle = windowHandles.itemAt(i);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800534 const InputWindowInfo* windowInfo = windowHandle->getInfo();
535 if (windowInfo->displayId == displayId) {
536 int32_t flags = windowInfo->layoutParamsFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800537
538 if (windowInfo->visible) {
539 if (!(flags & InputWindowInfo::FLAG_NOT_TOUCHABLE)) {
540 bool isTouchModal = (flags & (InputWindowInfo::FLAG_NOT_FOCUSABLE
541 | InputWindowInfo::FLAG_NOT_TOUCH_MODAL)) == 0;
542 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
543 // Found window.
544 return windowHandle;
545 }
546 }
547 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800548 }
549 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700550 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800551}
552
553void InputDispatcher::dropInboundEventLocked(EventEntry* entry, DropReason dropReason) {
554 const char* reason;
555 switch (dropReason) {
556 case DROP_REASON_POLICY:
557#if DEBUG_INBOUND_EVENT_DETAILS
558 ALOGD("Dropped event because policy consumed it.");
559#endif
560 reason = "inbound event was dropped because the policy consumed it";
561 break;
562 case DROP_REASON_DISABLED:
Michael Wright3a981722015-06-10 15:26:13 +0100563 if (mLastDropReason != DROP_REASON_DISABLED) {
564 ALOGI("Dropped event because input dispatch is disabled.");
565 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800566 reason = "inbound event was dropped because input dispatch is disabled";
567 break;
568 case DROP_REASON_APP_SWITCH:
569 ALOGI("Dropped event because of pending overdue app switch.");
570 reason = "inbound event was dropped because of pending overdue app switch";
571 break;
572 case DROP_REASON_BLOCKED:
573 ALOGI("Dropped event because the current application is not responding and the user "
574 "has started interacting with a different application.");
575 reason = "inbound event was dropped because the current application is not responding "
576 "and the user has started interacting with a different application";
577 break;
578 case DROP_REASON_STALE:
579 ALOGI("Dropped event because it is stale.");
580 reason = "inbound event was dropped because it is stale";
581 break;
582 default:
583 ALOG_ASSERT(false);
584 return;
585 }
586
587 switch (entry->type) {
588 case EventEntry::TYPE_KEY: {
589 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
590 synthesizeCancelationEventsForAllConnectionsLocked(options);
591 break;
592 }
593 case EventEntry::TYPE_MOTION: {
594 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
595 if (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) {
596 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
597 synthesizeCancelationEventsForAllConnectionsLocked(options);
598 } else {
599 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
600 synthesizeCancelationEventsForAllConnectionsLocked(options);
601 }
602 break;
603 }
604 }
605}
606
607bool InputDispatcher::isAppSwitchKeyCode(int32_t keyCode) {
608 return keyCode == AKEYCODE_HOME
609 || keyCode == AKEYCODE_ENDCALL
610 || keyCode == AKEYCODE_APP_SWITCH;
611}
612
613bool InputDispatcher::isAppSwitchKeyEventLocked(KeyEntry* keyEntry) {
614 return ! (keyEntry->flags & AKEY_EVENT_FLAG_CANCELED)
615 && isAppSwitchKeyCode(keyEntry->keyCode)
616 && (keyEntry->policyFlags & POLICY_FLAG_TRUSTED)
617 && (keyEntry->policyFlags & POLICY_FLAG_PASS_TO_USER);
618}
619
620bool InputDispatcher::isAppSwitchPendingLocked() {
621 return mAppSwitchDueTime != LONG_LONG_MAX;
622}
623
624void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
625 mAppSwitchDueTime = LONG_LONG_MAX;
626
627#if DEBUG_APP_SWITCH
628 if (handled) {
629 ALOGD("App switch has arrived.");
630 } else {
631 ALOGD("App switch was abandoned.");
632 }
633#endif
634}
635
636bool InputDispatcher::isStaleEventLocked(nsecs_t currentTime, EventEntry* entry) {
637 return currentTime - entry->eventTime >= STALE_EVENT_TIMEOUT;
638}
639
640bool InputDispatcher::haveCommandsLocked() const {
641 return !mCommandQueue.isEmpty();
642}
643
644bool InputDispatcher::runCommandsLockedInterruptible() {
645 if (mCommandQueue.isEmpty()) {
646 return false;
647 }
648
649 do {
650 CommandEntry* commandEntry = mCommandQueue.dequeueAtHead();
651
652 Command command = commandEntry->command;
653 (this->*command)(commandEntry); // commands are implicitly 'LockedInterruptible'
654
655 commandEntry->connection.clear();
656 delete commandEntry;
657 } while (! mCommandQueue.isEmpty());
658 return true;
659}
660
661InputDispatcher::CommandEntry* InputDispatcher::postCommandLocked(Command command) {
662 CommandEntry* commandEntry = new CommandEntry(command);
663 mCommandQueue.enqueueAtTail(commandEntry);
664 return commandEntry;
665}
666
667void InputDispatcher::drainInboundQueueLocked() {
668 while (! mInboundQueue.isEmpty()) {
669 EventEntry* entry = mInboundQueue.dequeueAtHead();
670 releaseInboundEventLocked(entry);
671 }
672 traceInboundQueueLengthLocked();
673}
674
675void InputDispatcher::releasePendingEventLocked() {
676 if (mPendingEvent) {
677 resetANRTimeoutsLocked();
678 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -0700679 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800680 }
681}
682
683void InputDispatcher::releaseInboundEventLocked(EventEntry* entry) {
684 InjectionState* injectionState = entry->injectionState;
685 if (injectionState && injectionState->injectionResult == INPUT_EVENT_INJECTION_PENDING) {
686#if DEBUG_DISPATCH_CYCLE
687 ALOGD("Injected inbound event was dropped.");
688#endif
689 setInjectionResultLocked(entry, INPUT_EVENT_INJECTION_FAILED);
690 }
691 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700692 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800693 }
694 addRecentEventLocked(entry);
695 entry->release();
696}
697
698void InputDispatcher::resetKeyRepeatLocked() {
699 if (mKeyRepeatState.lastKeyEntry) {
700 mKeyRepeatState.lastKeyEntry->release();
Yi Kong9b14ac62018-07-17 13:48:38 -0700701 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800702 }
703}
704
705InputDispatcher::KeyEntry* InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
706 KeyEntry* entry = mKeyRepeatState.lastKeyEntry;
707
708 // Reuse the repeated key entry if it is otherwise unreferenced.
Michael Wright2e732952014-09-24 13:26:59 -0700709 uint32_t policyFlags = entry->policyFlags &
710 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800711 if (entry->refCount == 1) {
712 entry->recycle();
713 entry->eventTime = currentTime;
714 entry->policyFlags = policyFlags;
715 entry->repeatCount += 1;
716 } else {
Prabir Pradhan42611e02018-11-27 14:04:02 -0800717 KeyEntry* newEntry = new KeyEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, currentTime,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100718 entry->deviceId, entry->source, entry->displayId, policyFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800719 entry->action, entry->flags, entry->keyCode, entry->scanCode,
720 entry->metaState, entry->repeatCount + 1, entry->downTime);
721
722 mKeyRepeatState.lastKeyEntry = newEntry;
723 entry->release();
724
725 entry = newEntry;
726 }
727 entry->syntheticRepeat = true;
728
729 // Increment reference count since we keep a reference to the event in
730 // mKeyRepeatState.lastKeyEntry in addition to the one we return.
731 entry->refCount += 1;
732
733 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
734 return entry;
735}
736
737bool InputDispatcher::dispatchConfigurationChangedLocked(
738 nsecs_t currentTime, ConfigurationChangedEntry* entry) {
739#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700740 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800741#endif
742
743 // Reset key repeating in case a keyboard device was added or removed or something.
744 resetKeyRepeatLocked();
745
746 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
747 CommandEntry* commandEntry = postCommandLocked(
748 & InputDispatcher::doNotifyConfigurationChangedInterruptible);
749 commandEntry->eventTime = entry->eventTime;
750 return true;
751}
752
753bool InputDispatcher::dispatchDeviceResetLocked(
754 nsecs_t currentTime, DeviceResetEntry* entry) {
755#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700756 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry->eventTime,
757 entry->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800758#endif
759
760 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
761 "device was reset");
762 options.deviceId = entry->deviceId;
763 synthesizeCancelationEventsForAllConnectionsLocked(options);
764 return true;
765}
766
767bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, KeyEntry* entry,
768 DropReason* dropReason, nsecs_t* nextWakeupTime) {
769 // Preprocessing.
770 if (! entry->dispatchInProgress) {
771 if (entry->repeatCount == 0
772 && entry->action == AKEY_EVENT_ACTION_DOWN
773 && (entry->policyFlags & POLICY_FLAG_TRUSTED)
774 && (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
775 if (mKeyRepeatState.lastKeyEntry
776 && mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode) {
777 // We have seen two identical key downs in a row which indicates that the device
778 // driver is automatically generating key repeats itself. We take note of the
779 // repeat here, but we disable our own next key repeat timer since it is clear that
780 // we will not need to synthesize key repeats ourselves.
781 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
782 resetKeyRepeatLocked();
783 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
784 } else {
785 // Not a repeat. Save key down state in case we do see a repeat later.
786 resetKeyRepeatLocked();
787 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
788 }
789 mKeyRepeatState.lastKeyEntry = entry;
790 entry->refCount += 1;
791 } else if (! entry->syntheticRepeat) {
792 resetKeyRepeatLocked();
793 }
794
795 if (entry->repeatCount == 1) {
796 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
797 } else {
798 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
799 }
800
801 entry->dispatchInProgress = true;
802
803 logOutboundKeyDetailsLocked("dispatchKey - ", entry);
804 }
805
806 // Handle case where the policy asked us to try again later last time.
807 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
808 if (currentTime < entry->interceptKeyWakeupTime) {
809 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
810 *nextWakeupTime = entry->interceptKeyWakeupTime;
811 }
812 return false; // wait until next wakeup
813 }
814 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
815 entry->interceptKeyWakeupTime = 0;
816 }
817
818 // Give the policy a chance to intercept the key.
819 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
820 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
821 CommandEntry* commandEntry = postCommandLocked(
822 & InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
Tiger Huang721e26f2018-07-24 22:26:19 +0800823 sp<InputWindowHandle> focusedWindowHandle =
824 getValueByKey(mFocusedWindowHandlesByDisplay, getTargetDisplayId(entry));
825 if (focusedWindowHandle != nullptr) {
Robert Carr740167f2018-10-11 19:03:41 -0700826 commandEntry->inputChannel =
827 getInputChannelLocked(focusedWindowHandle->getToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800828 }
829 commandEntry->keyEntry = entry;
830 entry->refCount += 1;
831 return false; // wait for the command to run
832 } else {
833 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
834 }
835 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
836 if (*dropReason == DROP_REASON_NOT_DROPPED) {
837 *dropReason = DROP_REASON_POLICY;
838 }
839 }
840
841 // Clean up if dropping the event.
842 if (*dropReason != DROP_REASON_NOT_DROPPED) {
843 setInjectionResultLocked(entry, *dropReason == DROP_REASON_POLICY
844 ? INPUT_EVENT_INJECTION_SUCCEEDED : INPUT_EVENT_INJECTION_FAILED);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800845 mReporter->reportDroppedKey(entry->sequenceNum);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800846 return true;
847 }
848
849 // Identify targets.
850 Vector<InputTarget> inputTargets;
851 int32_t injectionResult = findFocusedWindowTargetsLocked(currentTime,
852 entry, inputTargets, nextWakeupTime);
853 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
854 return false;
855 }
856
857 setInjectionResultLocked(entry, injectionResult);
858 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
859 return true;
860 }
861
Arthur Hung2fbf37f2018-09-13 18:16:41 +0800862 // Add monitor channels from event's or focused display.
863 addMonitoringTargetsLocked(inputTargets, getTargetDisplayId(entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800864
865 // Dispatch the key.
866 dispatchEventLocked(currentTime, entry, inputTargets);
867 return true;
868}
869
870void InputDispatcher::logOutboundKeyDetailsLocked(const char* prefix, const KeyEntry* entry) {
871#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100872 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
873 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
Arthur Hung82a4cad2018-11-15 12:10:30 +0800874 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800875 prefix,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100876 entry->eventTime, entry->deviceId, entry->source, entry->displayId, entry->policyFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800877 entry->action, entry->flags, entry->keyCode, entry->scanCode, entry->metaState,
Arthur Hung82a4cad2018-11-15 12:10:30 +0800878 entry->repeatCount, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800879#endif
880}
881
882bool InputDispatcher::dispatchMotionLocked(
883 nsecs_t currentTime, MotionEntry* entry, DropReason* dropReason, nsecs_t* nextWakeupTime) {
884 // Preprocessing.
885 if (! entry->dispatchInProgress) {
886 entry->dispatchInProgress = true;
887
888 logOutboundMotionDetailsLocked("dispatchMotion - ", entry);
889 }
890
891 // Clean up if dropping the event.
892 if (*dropReason != DROP_REASON_NOT_DROPPED) {
893 setInjectionResultLocked(entry, *dropReason == DROP_REASON_POLICY
894 ? INPUT_EVENT_INJECTION_SUCCEEDED : INPUT_EVENT_INJECTION_FAILED);
895 return true;
896 }
897
898 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
899
900 // Identify targets.
901 Vector<InputTarget> inputTargets;
902
903 bool conflictingPointerActions = false;
904 int32_t injectionResult;
905 if (isPointerEvent) {
906 // Pointer event. (eg. touchscreen)
907 injectionResult = findTouchedWindowTargetsLocked(currentTime,
908 entry, inputTargets, nextWakeupTime, &conflictingPointerActions);
909 } else {
910 // Non touch event. (eg. trackball)
911 injectionResult = findFocusedWindowTargetsLocked(currentTime,
912 entry, inputTargets, nextWakeupTime);
913 }
914 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
915 return false;
916 }
917
918 setInjectionResultLocked(entry, injectionResult);
919 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
Michael Wrightfa13dcf2015-06-12 13:25:11 +0100920 if (injectionResult != INPUT_EVENT_INJECTION_PERMISSION_DENIED) {
921 CancelationOptions::Mode mode(isPointerEvent ?
922 CancelationOptions::CANCEL_POINTER_EVENTS :
923 CancelationOptions::CANCEL_NON_POINTER_EVENTS);
924 CancelationOptions options(mode, "input event injection failed");
925 synthesizeCancelationEventsForMonitorsLocked(options);
926 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800927 return true;
928 }
929
Arthur Hung2fbf37f2018-09-13 18:16:41 +0800930 // Add monitor channels from event's or focused display.
931 addMonitoringTargetsLocked(inputTargets, getTargetDisplayId(entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800932
933 // Dispatch the motion.
934 if (conflictingPointerActions) {
935 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
936 "conflicting pointer actions");
937 synthesizeCancelationEventsForAllConnectionsLocked(options);
938 }
939 dispatchEventLocked(currentTime, entry, inputTargets);
940 return true;
941}
942
943
944void InputDispatcher::logOutboundMotionDetailsLocked(const char* prefix, const MotionEntry* entry) {
945#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800946 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
947 ", policyFlags=0x%x, "
Michael Wright7b159c92015-05-14 14:48:03 +0100948 "action=0x%x, actionButton=0x%x, flags=0x%x, "
949 "metaState=0x%x, buttonState=0x%x,"
Arthur Hung82a4cad2018-11-15 12:10:30 +0800950 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800951 prefix,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800952 entry->eventTime, entry->deviceId, entry->source, entry->displayId, entry->policyFlags,
Michael Wrightfa13dcf2015-06-12 13:25:11 +0100953 entry->action, entry->actionButton, entry->flags,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800954 entry->metaState, entry->buttonState,
955 entry->edgeFlags, entry->xPrecision, entry->yPrecision,
Arthur Hung82a4cad2018-11-15 12:10:30 +0800956 entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800957
958 for (uint32_t i = 0; i < entry->pointerCount; i++) {
959 ALOGD(" Pointer %d: id=%d, toolType=%d, "
960 "x=%f, y=%f, pressure=%f, size=%f, "
961 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -0800962 "orientation=%f",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800963 i, entry->pointerProperties[i].id,
964 entry->pointerProperties[i].toolType,
965 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
966 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
967 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
968 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
969 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
970 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
971 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
972 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -0800973 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800974 }
975#endif
976}
977
978void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
979 EventEntry* eventEntry, const Vector<InputTarget>& inputTargets) {
980#if DEBUG_DISPATCH_CYCLE
981 ALOGD("dispatchEventToCurrentInputTargets");
982#endif
983
984 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
985
986 pokeUserActivityLocked(eventEntry);
987
988 for (size_t i = 0; i < inputTargets.size(); i++) {
989 const InputTarget& inputTarget = inputTargets.itemAt(i);
990
991 ssize_t connectionIndex = getConnectionIndexLocked(inputTarget.inputChannel);
992 if (connectionIndex >= 0) {
993 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
994 prepareDispatchCycleLocked(currentTime, connection, eventEntry, &inputTarget);
995 } else {
996#if DEBUG_FOCUS
997 ALOGD("Dropping event delivery to target with channel '%s' because it "
998 "is no longer registered with the input dispatcher.",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800999 inputTarget.inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001000#endif
1001 }
1002 }
1003}
1004
1005int32_t InputDispatcher::handleTargetsNotReadyLocked(nsecs_t currentTime,
1006 const EventEntry* entry,
1007 const sp<InputApplicationHandle>& applicationHandle,
1008 const sp<InputWindowHandle>& windowHandle,
1009 nsecs_t* nextWakeupTime, const char* reason) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001010 if (applicationHandle == nullptr && windowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001011 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY) {
1012#if DEBUG_FOCUS
1013 ALOGD("Waiting for system to become ready for input. Reason: %s", reason);
1014#endif
1015 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY;
1016 mInputTargetWaitStartTime = currentTime;
1017 mInputTargetWaitTimeoutTime = LONG_LONG_MAX;
1018 mInputTargetWaitTimeoutExpired = false;
Robert Carr740167f2018-10-11 19:03:41 -07001019 mInputTargetWaitApplicationToken.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001020 }
1021 } else {
1022 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
1023#if DEBUG_FOCUS
1024 ALOGD("Waiting for application to become ready for input: %s. Reason: %s",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001025 getApplicationWindowLabelLocked(applicationHandle, windowHandle).c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08001026 reason);
1027#endif
1028 nsecs_t timeout;
Yi Kong9b14ac62018-07-17 13:48:38 -07001029 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001030 timeout = windowHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Yi Kong9b14ac62018-07-17 13:48:38 -07001031 } else if (applicationHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001032 timeout = applicationHandle->getDispatchingTimeout(
1033 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
1034 } else {
1035 timeout = DEFAULT_INPUT_DISPATCHING_TIMEOUT;
1036 }
1037
1038 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY;
1039 mInputTargetWaitStartTime = currentTime;
1040 mInputTargetWaitTimeoutTime = currentTime + timeout;
1041 mInputTargetWaitTimeoutExpired = false;
Robert Carr740167f2018-10-11 19:03:41 -07001042 mInputTargetWaitApplicationToken.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001043
Yi Kong9b14ac62018-07-17 13:48:38 -07001044 if (windowHandle != nullptr) {
Robert Carr740167f2018-10-11 19:03:41 -07001045 mInputTargetWaitApplicationToken = windowHandle->getApplicationToken();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001046 }
Robert Carr740167f2018-10-11 19:03:41 -07001047 if (mInputTargetWaitApplicationToken == nullptr && applicationHandle != nullptr) {
1048 mInputTargetWaitApplicationToken = applicationHandle->getApplicationToken();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001049 }
1050 }
1051 }
1052
1053 if (mInputTargetWaitTimeoutExpired) {
1054 return INPUT_EVENT_INJECTION_TIMED_OUT;
1055 }
1056
1057 if (currentTime >= mInputTargetWaitTimeoutTime) {
1058 onANRLocked(currentTime, applicationHandle, windowHandle,
1059 entry->eventTime, mInputTargetWaitStartTime, reason);
1060
1061 // Force poll loop to wake up immediately on next iteration once we get the
1062 // ANR response back from the policy.
1063 *nextWakeupTime = LONG_LONG_MIN;
1064 return INPUT_EVENT_INJECTION_PENDING;
1065 } else {
1066 // Force poll loop to wake up when timeout is due.
1067 if (mInputTargetWaitTimeoutTime < *nextWakeupTime) {
1068 *nextWakeupTime = mInputTargetWaitTimeoutTime;
1069 }
1070 return INPUT_EVENT_INJECTION_PENDING;
1071 }
1072}
1073
Robert Carr803535b2018-08-02 16:38:15 -07001074void InputDispatcher::removeWindowByTokenLocked(const sp<IBinder>& token) {
1075 for (size_t d = 0; d < mTouchStatesByDisplay.size(); d++) {
1076 TouchState& state = mTouchStatesByDisplay.editValueAt(d);
1077 state.removeWindowByToken(token);
1078 }
1079}
1080
Michael Wrightd02c5b62014-02-10 15:10:22 -08001081void InputDispatcher::resumeAfterTargetsNotReadyTimeoutLocked(nsecs_t newTimeout,
1082 const sp<InputChannel>& inputChannel) {
1083 if (newTimeout > 0) {
1084 // Extend the timeout.
1085 mInputTargetWaitTimeoutTime = now() + newTimeout;
1086 } else {
1087 // Give up.
1088 mInputTargetWaitTimeoutExpired = true;
1089
1090 // Input state will not be realistic. Mark it out of sync.
1091 if (inputChannel.get()) {
1092 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
1093 if (connectionIndex >= 0) {
1094 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
Robert Carr803535b2018-08-02 16:38:15 -07001095 sp<IBinder> token = connection->inputChannel->getToken();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001096
Robert Carr803535b2018-08-02 16:38:15 -07001097 if (token != nullptr) {
1098 removeWindowByTokenLocked(token);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001099 }
1100
1101 if (connection->status == Connection::STATUS_NORMAL) {
1102 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1103 "application not responding");
1104 synthesizeCancelationEventsForConnectionLocked(connection, options);
1105 }
1106 }
1107 }
1108 }
1109}
1110
1111nsecs_t InputDispatcher::getTimeSpentWaitingForApplicationLocked(
1112 nsecs_t currentTime) {
1113 if (mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
1114 return currentTime - mInputTargetWaitStartTime;
1115 }
1116 return 0;
1117}
1118
1119void InputDispatcher::resetANRTimeoutsLocked() {
1120#if DEBUG_FOCUS
1121 ALOGD("Resetting ANR timeouts.");
1122#endif
1123
1124 // Reset input target wait timeout.
1125 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_NONE;
Robert Carr740167f2018-10-11 19:03:41 -07001126 mInputTargetWaitApplicationToken.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001127}
1128
Tiger Huang721e26f2018-07-24 22:26:19 +08001129/**
1130 * Get the display id that the given event should go to. If this event specifies a valid display id,
1131 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1132 * Focused display is the display that the user most recently interacted with.
1133 */
1134int32_t InputDispatcher::getTargetDisplayId(const EventEntry* entry) {
1135 int32_t displayId;
1136 switch (entry->type) {
1137 case EventEntry::TYPE_KEY: {
1138 const KeyEntry* typedEntry = static_cast<const KeyEntry*>(entry);
1139 displayId = typedEntry->displayId;
1140 break;
1141 }
1142 case EventEntry::TYPE_MOTION: {
1143 const MotionEntry* typedEntry = static_cast<const MotionEntry*>(entry);
1144 displayId = typedEntry->displayId;
1145 break;
1146 }
1147 default: {
1148 ALOGE("Unsupported event type '%" PRId32 "' for target display.", entry->type);
1149 return ADISPLAY_ID_NONE;
1150 }
1151 }
1152 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1153}
1154
Michael Wrightd02c5b62014-02-10 15:10:22 -08001155int32_t InputDispatcher::findFocusedWindowTargetsLocked(nsecs_t currentTime,
1156 const EventEntry* entry, Vector<InputTarget>& inputTargets, nsecs_t* nextWakeupTime) {
1157 int32_t injectionResult;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001158 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001159
Tiger Huang721e26f2018-07-24 22:26:19 +08001160 int32_t displayId = getTargetDisplayId(entry);
1161 sp<InputWindowHandle> focusedWindowHandle =
1162 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
1163 sp<InputApplicationHandle> focusedApplicationHandle =
1164 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1165
Michael Wrightd02c5b62014-02-10 15:10:22 -08001166 // If there is no currently focused window and no focused application
1167 // then drop the event.
Tiger Huang721e26f2018-07-24 22:26:19 +08001168 if (focusedWindowHandle == nullptr) {
1169 if (focusedApplicationHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001170 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Tiger Huang721e26f2018-07-24 22:26:19 +08001171 focusedApplicationHandle, nullptr, nextWakeupTime,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001172 "Waiting because no window has focus but there is a "
1173 "focused application that may eventually add a window "
1174 "when it finishes starting up.");
1175 goto Unresponsive;
1176 }
1177
Arthur Hung3b413f22018-10-26 18:05:34 +08001178 ALOGI("Dropping event because there is no focused window or focused application in display "
1179 "%" PRId32 ".", displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001180 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1181 goto Failed;
1182 }
1183
1184 // Check permissions.
Tiger Huang721e26f2018-07-24 22:26:19 +08001185 if (!checkInjectionPermission(focusedWindowHandle, entry->injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001186 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1187 goto Failed;
1188 }
1189
Jeff Brownffb49772014-10-10 19:01:34 -07001190 // Check whether the window is ready for more input.
1191 reason = checkWindowReadyForMoreInputLocked(currentTime,
Tiger Huang721e26f2018-07-24 22:26:19 +08001192 focusedWindowHandle, entry, "focused");
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001193 if (!reason.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001194 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Tiger Huang721e26f2018-07-24 22:26:19 +08001195 focusedApplicationHandle, focusedWindowHandle, nextWakeupTime, reason.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001196 goto Unresponsive;
1197 }
1198
1199 // Success! Output targets.
1200 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
Tiger Huang721e26f2018-07-24 22:26:19 +08001201 addWindowTargetLocked(focusedWindowHandle,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001202 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS, BitSet32(0),
1203 inputTargets);
1204
1205 // Done.
1206Failed:
1207Unresponsive:
1208 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
1209 updateDispatchStatisticsLocked(currentTime, entry,
1210 injectionResult, timeSpentWaitingForApplication);
1211#if DEBUG_FOCUS
1212 ALOGD("findFocusedWindow finished: injectionResult=%d, "
1213 "timeSpentWaitingForApplication=%0.1fms",
1214 injectionResult, timeSpentWaitingForApplication / 1000000.0);
1215#endif
1216 return injectionResult;
1217}
1218
1219int32_t InputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime,
1220 const MotionEntry* entry, Vector<InputTarget>& inputTargets, nsecs_t* nextWakeupTime,
1221 bool* outConflictingPointerActions) {
1222 enum InjectionPermission {
1223 INJECTION_PERMISSION_UNKNOWN,
1224 INJECTION_PERMISSION_GRANTED,
1225 INJECTION_PERMISSION_DENIED
1226 };
1227
Michael Wrightd02c5b62014-02-10 15:10:22 -08001228 // For security reasons, we defer updating the touch state until we are sure that
1229 // event injection will be allowed.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001230 int32_t displayId = entry->displayId;
1231 int32_t action = entry->action;
1232 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
1233
1234 // Update the touch state as needed based on the properties of the touch event.
1235 int32_t injectionResult = INPUT_EVENT_INJECTION_PENDING;
1236 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
1237 sp<InputWindowHandle> newHoverWindowHandle;
1238
Jeff Brownf086ddb2014-02-11 14:28:48 -08001239 // Copy current touch state into mTempTouchState.
1240 // This state is always reset at the end of this function, so if we don't find state
1241 // for the specified display then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07001242 const TouchState* oldState = nullptr;
Jeff Brownf086ddb2014-02-11 14:28:48 -08001243 ssize_t oldStateIndex = mTouchStatesByDisplay.indexOfKey(displayId);
1244 if (oldStateIndex >= 0) {
1245 oldState = &mTouchStatesByDisplay.valueAt(oldStateIndex);
1246 mTempTouchState.copyFrom(*oldState);
1247 }
1248
1249 bool isSplit = mTempTouchState.split;
1250 bool switchedDevice = mTempTouchState.deviceId >= 0 && mTempTouchState.displayId >= 0
1251 && (mTempTouchState.deviceId != entry->deviceId
1252 || mTempTouchState.source != entry->source
1253 || mTempTouchState.displayId != displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001254 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE
1255 || maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER
1256 || maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1257 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN
1258 || maskedAction == AMOTION_EVENT_ACTION_SCROLL
1259 || isHoverAction);
1260 bool wrongDevice = false;
1261 if (newGesture) {
1262 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001263 if (switchedDevice && mTempTouchState.down && !down && !isHoverAction) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001264#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08001265 ALOGD("Dropping event because a pointer for a different device is already down "
1266 "in display %" PRId32, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001267#endif
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001268 // TODO: test multiple simultaneous input streams.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001269 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1270 switchedDevice = false;
1271 wrongDevice = true;
1272 goto Failed;
1273 }
1274 mTempTouchState.reset();
1275 mTempTouchState.down = down;
1276 mTempTouchState.deviceId = entry->deviceId;
1277 mTempTouchState.source = entry->source;
1278 mTempTouchState.displayId = displayId;
1279 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001280 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
1281#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08001282 ALOGI("Dropping move event because a pointer for a different device is already active "
1283 "in display %" PRId32, displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001284#endif
1285 // TODO: test multiple simultaneous input streams.
1286 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1287 switchedDevice = false;
1288 wrongDevice = true;
1289 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001290 }
1291
1292 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
1293 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
1294
1295 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
1296 int32_t x = int32_t(entry->pointerCoords[pointerIndex].
1297 getAxisValue(AMOTION_EVENT_AXIS_X));
1298 int32_t y = int32_t(entry->pointerCoords[pointerIndex].
1299 getAxisValue(AMOTION_EVENT_AXIS_Y));
1300 sp<InputWindowHandle> newTouchedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001301 bool isTouchModal = false;
1302
1303 // Traverse windows from front to back to find touched window and outside targets.
Arthur Hungb92218b2018-08-14 12:00:21 +08001304 const Vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
1305 size_t numWindows = windowHandles.size();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001306 for (size_t i = 0; i < numWindows; i++) {
Arthur Hungb92218b2018-08-14 12:00:21 +08001307 sp<InputWindowHandle> windowHandle = windowHandles.itemAt(i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001308 const InputWindowInfo* windowInfo = windowHandle->getInfo();
1309 if (windowInfo->displayId != displayId) {
1310 continue; // wrong display
1311 }
1312
Michael Wrightd02c5b62014-02-10 15:10:22 -08001313 int32_t flags = windowInfo->layoutParamsFlags;
1314 if (windowInfo->visible) {
1315 if (! (flags & InputWindowInfo::FLAG_NOT_TOUCHABLE)) {
1316 isTouchModal = (flags & (InputWindowInfo::FLAG_NOT_FOCUSABLE
1317 | InputWindowInfo::FLAG_NOT_TOUCH_MODAL)) == 0;
1318 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
Jeff Browndc5992e2014-04-11 01:27:26 -07001319 newTouchedWindowHandle = windowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001320 break; // found touched window, exit window loop
1321 }
1322 }
1323
1324 if (maskedAction == AMOTION_EVENT_ACTION_DOWN
1325 && (flags & InputWindowInfo::FLAG_WATCH_OUTSIDE_TOUCH)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001326 mTempTouchState.addOrUpdateWindow(
Michael Wright3b106102017-01-16 21:05:07 +00001327 windowHandle, InputTarget::FLAG_DISPATCH_AS_OUTSIDE, BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001328 }
1329 }
1330 }
1331
Michael Wrightd02c5b62014-02-10 15:10:22 -08001332 // Figure out whether splitting will be allowed for this window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001333 if (newTouchedWindowHandle != nullptr
Michael Wrightd02c5b62014-02-10 15:10:22 -08001334 && newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
1335 // New window supports splitting.
1336 isSplit = true;
1337 } else if (isSplit) {
1338 // New window does not support splitting but we have already split events.
1339 // Ignore the new window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001340 newTouchedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001341 }
1342
1343 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001344 if (newTouchedWindowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001345 // Try to assign the pointer to the first foreground window we find, if there is one.
1346 newTouchedWindowHandle = mTempTouchState.getFirstForegroundWindowHandle();
Yi Kong9b14ac62018-07-17 13:48:38 -07001347 if (newTouchedWindowHandle == nullptr) {
Arthur Hung3b413f22018-10-26 18:05:34 +08001348 ALOGI("Dropping event because there is no touchable window at (%d, %d) in display "
1349 "%" PRId32 ".", x, y, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001350 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1351 goto Failed;
1352 }
1353 }
1354
1355 // Set target flags.
1356 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
1357 if (isSplit) {
1358 targetFlags |= InputTarget::FLAG_SPLIT;
1359 }
1360 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1361 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001362 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
1363 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001364 }
1365
1366 // Update hover state.
1367 if (isHoverAction) {
1368 newHoverWindowHandle = newTouchedWindowHandle;
1369 } else if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
1370 newHoverWindowHandle = mLastHoverWindowHandle;
1371 }
1372
1373 // Update the temporary touch state.
1374 BitSet32 pointerIds;
1375 if (isSplit) {
1376 uint32_t pointerId = entry->pointerProperties[pointerIndex].id;
1377 pointerIds.markBit(pointerId);
1378 }
1379 mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
1380 } else {
1381 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
1382
1383 // If the pointer is not currently down, then ignore the event.
1384 if (! mTempTouchState.down) {
1385#if DEBUG_FOCUS
1386 ALOGD("Dropping event because the pointer is not down or we previously "
Arthur Hung3b413f22018-10-26 18:05:34 +08001387 "dropped the pointer down event in display %" PRId32, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001388#endif
1389 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1390 goto Failed;
1391 }
1392
1393 // Check whether touches should slip outside of the current foreground window.
1394 if (maskedAction == AMOTION_EVENT_ACTION_MOVE
1395 && entry->pointerCount == 1
1396 && mTempTouchState.isSlippery()) {
1397 int32_t x = int32_t(entry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
1398 int32_t y = int32_t(entry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
1399
1400 sp<InputWindowHandle> oldTouchedWindowHandle =
1401 mTempTouchState.getFirstForegroundWindowHandle();
1402 sp<InputWindowHandle> newTouchedWindowHandle =
1403 findTouchedWindowAtLocked(displayId, x, y);
1404 if (oldTouchedWindowHandle != newTouchedWindowHandle
Yi Kong9b14ac62018-07-17 13:48:38 -07001405 && newTouchedWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001406#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08001407 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001408 oldTouchedWindowHandle->getName().c_str(),
Arthur Hung3b413f22018-10-26 18:05:34 +08001409 newTouchedWindowHandle->getName().c_str(),
1410 displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001411#endif
1412 // Make a slippery exit from the old window.
1413 mTempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
1414 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT, BitSet32(0));
1415
1416 // Make a slippery entrance into the new window.
1417 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
1418 isSplit = true;
1419 }
1420
1421 int32_t targetFlags = InputTarget::FLAG_FOREGROUND
1422 | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
1423 if (isSplit) {
1424 targetFlags |= InputTarget::FLAG_SPLIT;
1425 }
1426 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1427 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1428 }
1429
1430 BitSet32 pointerIds;
1431 if (isSplit) {
1432 pointerIds.markBit(entry->pointerProperties[0].id);
1433 }
1434 mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
1435 }
1436 }
1437 }
1438
1439 if (newHoverWindowHandle != mLastHoverWindowHandle) {
1440 // Let the previous window know that the hover sequence is over.
Yi Kong9b14ac62018-07-17 13:48:38 -07001441 if (mLastHoverWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001442#if DEBUG_HOVER
1443 ALOGD("Sending hover exit event to window %s.",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001444 mLastHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001445#endif
1446 mTempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
1447 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
1448 }
1449
1450 // Let the new window know that the hover sequence is starting.
Yi Kong9b14ac62018-07-17 13:48:38 -07001451 if (newHoverWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001452#if DEBUG_HOVER
1453 ALOGD("Sending hover enter event to window %s.",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001454 newHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001455#endif
1456 mTempTouchState.addOrUpdateWindow(newHoverWindowHandle,
1457 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER, BitSet32(0));
1458 }
1459 }
1460
1461 // Check permission to inject into all touched foreground windows and ensure there
1462 // is at least one touched foreground window.
1463 {
1464 bool haveForegroundWindow = false;
1465 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1466 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1467 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1468 haveForegroundWindow = true;
1469 if (! checkInjectionPermission(touchedWindow.windowHandle,
1470 entry->injectionState)) {
1471 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1472 injectionPermission = INJECTION_PERMISSION_DENIED;
1473 goto Failed;
1474 }
1475 }
1476 }
1477 if (! haveForegroundWindow) {
1478#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08001479 ALOGD("Dropping event because there is no touched foreground window in display %" PRId32
1480 " to receive it.", displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001481#endif
1482 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1483 goto Failed;
1484 }
1485
1486 // Permission granted to injection into all touched foreground windows.
1487 injectionPermission = INJECTION_PERMISSION_GRANTED;
1488 }
1489
1490 // Check whether windows listening for outside touches are owned by the same UID. If it is
1491 // set the policy flag that we will not reveal coordinate information to this window.
1492 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1493 sp<InputWindowHandle> foregroundWindowHandle =
1494 mTempTouchState.getFirstForegroundWindowHandle();
1495 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
1496 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1497 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1498 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.
1509 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1510 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1511 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
Jeff Brownffb49772014-10-10 19:01:34 -07001512 // Check whether the window is ready for more input.
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001513 std::string reason = checkWindowReadyForMoreInputLocked(currentTime,
Jeff Brownffb49772014-10-10 19:01:34 -07001514 touchedWindow.windowHandle, entry, "touched");
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001515 if (!reason.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001516 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Yi Kong9b14ac62018-07-17 13:48:38 -07001517 nullptr, touchedWindow.windowHandle, nextWakeupTime, reason.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001518 goto Unresponsive;
1519 }
1520 }
1521 }
1522
1523 // If this is the first pointer going down and the touched window has a wallpaper
1524 // then also add the touched wallpaper windows so they are locked in for the duration
1525 // of the touch gesture.
1526 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
1527 // engine only supports touch events. We would need to add a mechanism similar
1528 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
1529 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1530 sp<InputWindowHandle> foregroundWindowHandle =
1531 mTempTouchState.getFirstForegroundWindowHandle();
1532 if (foregroundWindowHandle->getInfo()->hasWallpaper) {
Arthur Hungb92218b2018-08-14 12:00:21 +08001533 const Vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
1534 size_t numWindows = windowHandles.size();
1535 for (size_t i = 0; i < numWindows; i++) {
1536 sp<InputWindowHandle> windowHandle = windowHandles.itemAt(i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001537 const InputWindowInfo* info = windowHandle->getInfo();
1538 if (info->displayId == displayId
1539 && windowHandle->getInfo()->layoutParamsType
1540 == InputWindowInfo::TYPE_WALLPAPER) {
1541 mTempTouchState.addOrUpdateWindow(windowHandle,
1542 InputTarget::FLAG_WINDOW_IS_OBSCURED
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001543 | InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED
Michael Wrightd02c5b62014-02-10 15:10:22 -08001544 | InputTarget::FLAG_DISPATCH_AS_IS,
1545 BitSet32(0));
1546 }
1547 }
1548 }
1549 }
1550
1551 // Success! Output targets.
1552 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
1553
1554 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1555 const TouchedWindow& touchedWindow = mTempTouchState.windows.itemAt(i);
1556 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
1557 touchedWindow.pointerIds, inputTargets);
1558 }
1559
1560 // Drop the outside or hover touch windows since we will not care about them
1561 // in the next iteration.
1562 mTempTouchState.filterNonAsIsTouchWindows();
1563
1564Failed:
1565 // Check injection permission once and for all.
1566 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001567 if (checkInjectionPermission(nullptr, entry->injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001568 injectionPermission = INJECTION_PERMISSION_GRANTED;
1569 } else {
1570 injectionPermission = INJECTION_PERMISSION_DENIED;
1571 }
1572 }
1573
1574 // Update final pieces of touch state if the injector had permission.
1575 if (injectionPermission == INJECTION_PERMISSION_GRANTED) {
1576 if (!wrongDevice) {
1577 if (switchedDevice) {
1578#if DEBUG_FOCUS
1579 ALOGD("Conflicting pointer actions: Switched to a different device.");
1580#endif
1581 *outConflictingPointerActions = true;
1582 }
1583
1584 if (isHoverAction) {
1585 // Started hovering, therefore no longer down.
Jeff Brownf086ddb2014-02-11 14:28:48 -08001586 if (oldState && oldState->down) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001587#if DEBUG_FOCUS
1588 ALOGD("Conflicting pointer actions: Hover received while pointer was down.");
1589#endif
1590 *outConflictingPointerActions = true;
1591 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08001592 mTempTouchState.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001593 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER
1594 || maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Jeff Brownf086ddb2014-02-11 14:28:48 -08001595 mTempTouchState.deviceId = entry->deviceId;
1596 mTempTouchState.source = entry->source;
1597 mTempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001598 }
1599 } else if (maskedAction == AMOTION_EVENT_ACTION_UP
1600 || maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
1601 // All pointers up or canceled.
Jeff Brownf086ddb2014-02-11 14:28:48 -08001602 mTempTouchState.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001603 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1604 // First pointer went down.
Jeff Brownf086ddb2014-02-11 14:28:48 -08001605 if (oldState && oldState->down) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001606#if DEBUG_FOCUS
1607 ALOGD("Conflicting pointer actions: Down received while already down.");
1608#endif
1609 *outConflictingPointerActions = true;
1610 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001611 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
1612 // One pointer went up.
1613 if (isSplit) {
1614 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
1615 uint32_t pointerId = entry->pointerProperties[pointerIndex].id;
1616
1617 for (size_t i = 0; i < mTempTouchState.windows.size(); ) {
1618 TouchedWindow& touchedWindow = mTempTouchState.windows.editItemAt(i);
1619 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
1620 touchedWindow.pointerIds.clearBit(pointerId);
1621 if (touchedWindow.pointerIds.isEmpty()) {
1622 mTempTouchState.windows.removeAt(i);
1623 continue;
1624 }
1625 }
1626 i += 1;
1627 }
1628 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08001629 }
1630
1631 // Save changes unless the action was scroll in which case the temporary touch
1632 // state was only valid for this one action.
1633 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
1634 if (mTempTouchState.displayId >= 0) {
1635 if (oldStateIndex >= 0) {
1636 mTouchStatesByDisplay.editValueAt(oldStateIndex).copyFrom(mTempTouchState);
1637 } else {
1638 mTouchStatesByDisplay.add(displayId, mTempTouchState);
1639 }
1640 } else if (oldStateIndex >= 0) {
1641 mTouchStatesByDisplay.removeItemsAt(oldStateIndex);
1642 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001643 }
1644
1645 // Update hover state.
1646 mLastHoverWindowHandle = newHoverWindowHandle;
1647 }
1648 } else {
1649#if DEBUG_FOCUS
1650 ALOGD("Not updating touch focus because injection was denied.");
1651#endif
1652 }
1653
1654Unresponsive:
1655 // Reset temporary touch state to ensure we release unnecessary references to input channels.
1656 mTempTouchState.reset();
1657
1658 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
1659 updateDispatchStatisticsLocked(currentTime, entry,
1660 injectionResult, timeSpentWaitingForApplication);
1661#if DEBUG_FOCUS
1662 ALOGD("findTouchedWindow finished: injectionResult=%d, injectionPermission=%d, "
1663 "timeSpentWaitingForApplication=%0.1fms",
1664 injectionResult, injectionPermission, timeSpentWaitingForApplication / 1000000.0);
1665#endif
1666 return injectionResult;
1667}
1668
1669void InputDispatcher::addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
1670 int32_t targetFlags, BitSet32 pointerIds, Vector<InputTarget>& inputTargets) {
Arthur Hungceeb5d72018-12-05 16:14:18 +08001671 sp<InputChannel> inputChannel = getInputChannelLocked(windowHandle->getToken());
1672 if (inputChannel == nullptr) {
1673 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
1674 return;
1675 }
1676
Michael Wrightd02c5b62014-02-10 15:10:22 -08001677 inputTargets.push();
1678
1679 const InputWindowInfo* windowInfo = windowHandle->getInfo();
1680 InputTarget& target = inputTargets.editTop();
Arthur Hungceeb5d72018-12-05 16:14:18 +08001681 target.inputChannel = inputChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001682 target.flags = targetFlags;
1683 target.xOffset = - windowInfo->frameLeft;
1684 target.yOffset = - windowInfo->frameTop;
Robert Carre07e1032018-11-26 12:55:53 -08001685 target.globalScaleFactor = windowInfo->globalScaleFactor;
1686 target.windowXScale = windowInfo->windowXScale;
1687 target.windowYScale = windowInfo->windowYScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001688 target.pointerIds = pointerIds;
1689}
1690
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001691void InputDispatcher::addMonitoringTargetsLocked(Vector<InputTarget>& inputTargets,
1692 int32_t displayId) {
1693 std::unordered_map<int32_t, Vector<sp<InputChannel>>>::const_iterator it =
1694 mMonitoringChannelsByDisplay.find(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001695
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001696 if (it != mMonitoringChannelsByDisplay.end()) {
1697 const Vector<sp<InputChannel>>& monitoringChannels = it->second;
1698 const size_t numChannels = monitoringChannels.size();
1699 for (size_t i = 0; i < numChannels; i++) {
1700 inputTargets.push();
1701
1702 InputTarget& target = inputTargets.editTop();
1703 target.inputChannel = monitoringChannels[i];
1704 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1705 target.xOffset = 0;
1706 target.yOffset = 0;
1707 target.pointerIds.clear();
Robert Carre07e1032018-11-26 12:55:53 -08001708 target.globalScaleFactor = 1.0f;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001709 }
1710 } else {
1711 // If there is no monitor channel registered or all monitor channel unregistered,
1712 // the display can't detect the extra system gesture by a copy of input events.
Arthur Hung3b413f22018-10-26 18:05:34 +08001713 ALOGW("There is no monitor channel found in display %" PRId32, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001714 }
1715}
1716
1717bool InputDispatcher::checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
1718 const InjectionState* injectionState) {
1719 if (injectionState
Yi Kong9b14ac62018-07-17 13:48:38 -07001720 && (windowHandle == nullptr
Michael Wrightd02c5b62014-02-10 15:10:22 -08001721 || windowHandle->getInfo()->ownerUid != injectionState->injectorUid)
1722 && !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001723 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001724 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
1725 "owned by uid %d",
1726 injectionState->injectorPid, injectionState->injectorUid,
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001727 windowHandle->getName().c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08001728 windowHandle->getInfo()->ownerUid);
1729 } else {
1730 ALOGW("Permission denied: injecting event from pid %d uid %d",
1731 injectionState->injectorPid, injectionState->injectorUid);
1732 }
1733 return false;
1734 }
1735 return true;
1736}
1737
1738bool InputDispatcher::isWindowObscuredAtPointLocked(
1739 const sp<InputWindowHandle>& windowHandle, int32_t x, int32_t y) const {
1740 int32_t displayId = windowHandle->getInfo()->displayId;
Arthur Hungb92218b2018-08-14 12:00:21 +08001741 const Vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
1742 size_t numWindows = windowHandles.size();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001743 for (size_t i = 0; i < numWindows; i++) {
Arthur Hungb92218b2018-08-14 12:00:21 +08001744 sp<InputWindowHandle> otherHandle = windowHandles.itemAt(i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001745 if (otherHandle == windowHandle) {
1746 break;
1747 }
1748
1749 const InputWindowInfo* otherInfo = otherHandle->getInfo();
1750 if (otherInfo->displayId == displayId
1751 && otherInfo->visible && !otherInfo->isTrustedOverlay()
1752 && otherInfo->frameContainsPoint(x, y)) {
1753 return true;
1754 }
1755 }
1756 return false;
1757}
1758
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001759
1760bool InputDispatcher::isWindowObscuredLocked(const sp<InputWindowHandle>& windowHandle) const {
1761 int32_t displayId = windowHandle->getInfo()->displayId;
Arthur Hungb92218b2018-08-14 12:00:21 +08001762 const Vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001763 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Arthur Hungb92218b2018-08-14 12:00:21 +08001764 size_t numWindows = windowHandles.size();
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001765 for (size_t i = 0; i < numWindows; i++) {
Arthur Hungb92218b2018-08-14 12:00:21 +08001766 sp<InputWindowHandle> otherHandle = windowHandles.itemAt(i);
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001767 if (otherHandle == windowHandle) {
1768 break;
1769 }
1770
1771 const InputWindowInfo* otherInfo = otherHandle->getInfo();
1772 if (otherInfo->displayId == displayId
1773 && otherInfo->visible && !otherInfo->isTrustedOverlay()
1774 && otherInfo->overlaps(windowInfo)) {
1775 return true;
1776 }
1777 }
1778 return false;
1779}
1780
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001781std::string InputDispatcher::checkWindowReadyForMoreInputLocked(nsecs_t currentTime,
Jeff Brownffb49772014-10-10 19:01:34 -07001782 const sp<InputWindowHandle>& windowHandle, const EventEntry* eventEntry,
1783 const char* targetType) {
1784 // If the window is paused then keep waiting.
1785 if (windowHandle->getInfo()->paused) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001786 return StringPrintf("Waiting because the %s window is paused.", targetType);
Jeff Brownffb49772014-10-10 19:01:34 -07001787 }
1788
1789 // If the window's connection is not registered then keep waiting.
Robert Carr5c8a0262018-10-03 16:30:44 -07001790 ssize_t connectionIndex = getConnectionIndexLocked(
1791 getInputChannelLocked(windowHandle->getToken()));
Jeff Brownffb49772014-10-10 19:01:34 -07001792 if (connectionIndex < 0) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001793 return StringPrintf("Waiting because the %s window's input channel is not "
Jeff Brownffb49772014-10-10 19:01:34 -07001794 "registered with the input dispatcher. The window may be in the process "
1795 "of being removed.", targetType);
1796 }
1797
1798 // If the connection is dead then keep waiting.
1799 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
1800 if (connection->status != Connection::STATUS_NORMAL) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001801 return StringPrintf("Waiting because the %s window's input connection is %s."
Jeff Brownffb49772014-10-10 19:01:34 -07001802 "The window may be in the process of being removed.", targetType,
1803 connection->getStatusLabel());
1804 }
1805
1806 // If the connection is backed up then keep waiting.
1807 if (connection->inputPublisherBlocked) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001808 return StringPrintf("Waiting because the %s window's input channel is full. "
Jeff Brownffb49772014-10-10 19:01:34 -07001809 "Outbound queue length: %d. Wait queue length: %d.",
1810 targetType, connection->outboundQueue.count(), connection->waitQueue.count());
1811 }
1812
1813 // Ensure that the dispatch queues aren't too far backed up for this event.
1814 if (eventEntry->type == EventEntry::TYPE_KEY) {
1815 // If the event is a key event, then we must wait for all previous events to
1816 // complete before delivering it because previous events may have the
1817 // side-effect of transferring focus to a different window and we want to
1818 // ensure that the following keys are sent to the new window.
1819 //
1820 // Suppose the user touches a button in a window then immediately presses "A".
1821 // If the button causes a pop-up window to appear then we want to ensure that
1822 // the "A" key is delivered to the new pop-up window. This is because users
1823 // often anticipate pending UI changes when typing on a keyboard.
1824 // To obtain this behavior, we must serialize key events with respect to all
1825 // prior input events.
1826 if (!connection->outboundQueue.isEmpty() || !connection->waitQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001827 return StringPrintf("Waiting to send key event because the %s window has not "
Jeff Brownffb49772014-10-10 19:01:34 -07001828 "finished processing all of the input events that were previously "
1829 "delivered to it. Outbound queue length: %d. Wait queue length: %d.",
1830 targetType, connection->outboundQueue.count(), connection->waitQueue.count());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001831 }
Jeff Brownffb49772014-10-10 19:01:34 -07001832 } else {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001833 // Touch events can always be sent to a window immediately because the user intended
1834 // to touch whatever was visible at the time. Even if focus changes or a new
1835 // window appears moments later, the touch event was meant to be delivered to
1836 // whatever window happened to be on screen at the time.
1837 //
1838 // Generic motion events, such as trackball or joystick events are a little trickier.
1839 // Like key events, generic motion events are delivered to the focused window.
1840 // Unlike key events, generic motion events don't tend to transfer focus to other
1841 // windows and it is not important for them to be serialized. So we prefer to deliver
1842 // generic motion events as soon as possible to improve efficiency and reduce lag
1843 // through batching.
1844 //
1845 // The one case where we pause input event delivery is when the wait queue is piling
1846 // up with lots of events because the application is not responding.
1847 // This condition ensures that ANRs are detected reliably.
1848 if (!connection->waitQueue.isEmpty()
1849 && currentTime >= connection->waitQueue.head->deliveryTime
1850 + STREAM_AHEAD_EVENT_TIMEOUT) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001851 return StringPrintf("Waiting to send non-key event because the %s window has not "
Jeff Brownffb49772014-10-10 19:01:34 -07001852 "finished processing certain input events that were delivered to it over "
1853 "%0.1fms ago. Wait queue length: %d. Wait queue head age: %0.1fms.",
1854 targetType, STREAM_AHEAD_EVENT_TIMEOUT * 0.000001f,
1855 connection->waitQueue.count(),
1856 (currentTime - connection->waitQueue.head->deliveryTime) * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001857 }
1858 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001859 return "";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001860}
1861
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001862std::string InputDispatcher::getApplicationWindowLabelLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08001863 const sp<InputApplicationHandle>& applicationHandle,
1864 const sp<InputWindowHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001865 if (applicationHandle != nullptr) {
1866 if (windowHandle != nullptr) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001867 std::string label(applicationHandle->getName());
1868 label += " - ";
1869 label += windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001870 return label;
1871 } else {
1872 return applicationHandle->getName();
1873 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001874 } else if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001875 return windowHandle->getName();
1876 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001877 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001878 }
1879}
1880
1881void InputDispatcher::pokeUserActivityLocked(const EventEntry* eventEntry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001882 int32_t displayId = getTargetDisplayId(eventEntry);
1883 sp<InputWindowHandle> focusedWindowHandle =
1884 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
1885 if (focusedWindowHandle != nullptr) {
1886 const InputWindowInfo* info = focusedWindowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001887 if (info->inputFeatures & InputWindowInfo::INPUT_FEATURE_DISABLE_USER_ACTIVITY) {
1888#if DEBUG_DISPATCH_CYCLE
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001889 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001890#endif
1891 return;
1892 }
1893 }
1894
1895 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
1896 switch (eventEntry->type) {
1897 case EventEntry::TYPE_MOTION: {
1898 const MotionEntry* motionEntry = static_cast<const MotionEntry*>(eventEntry);
1899 if (motionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
1900 return;
1901 }
1902
1903 if (MotionEvent::isTouchEvent(motionEntry->source, motionEntry->action)) {
1904 eventType = USER_ACTIVITY_EVENT_TOUCH;
1905 }
1906 break;
1907 }
1908 case EventEntry::TYPE_KEY: {
1909 const KeyEntry* keyEntry = static_cast<const KeyEntry*>(eventEntry);
1910 if (keyEntry->flags & AKEY_EVENT_FLAG_CANCELED) {
1911 return;
1912 }
1913 eventType = USER_ACTIVITY_EVENT_BUTTON;
1914 break;
1915 }
1916 }
1917
1918 CommandEntry* commandEntry = postCommandLocked(
1919 & InputDispatcher::doPokeUserActivityLockedInterruptible);
1920 commandEntry->eventTime = eventEntry->eventTime;
1921 commandEntry->userActivityEventType = eventType;
1922}
1923
1924void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
1925 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget) {
1926#if DEBUG_DISPATCH_CYCLE
1927 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
Robert Carre07e1032018-11-26 12:55:53 -08001928 "xOffset=%f, yOffset=%f, globalScaleFactor=%f, "
1929 "windowScaleFactor=(%f, %f), pointerIds=0x%x",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08001930 connection->getInputChannelName().c_str(), inputTarget->flags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001931 inputTarget->xOffset, inputTarget->yOffset,
Robert Carre07e1032018-11-26 12:55:53 -08001932 inputTarget->globalScaleFactor,
1933 inputTarget->windowXScale, inputTarget->windowYScale,
1934 inputTarget->pointerIds.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001935#endif
1936
1937 // Skip this event if the connection status is not normal.
1938 // We don't want to enqueue additional outbound events if the connection is broken.
1939 if (connection->status != Connection::STATUS_NORMAL) {
1940#if DEBUG_DISPATCH_CYCLE
1941 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08001942 connection->getInputChannelName().c_str(), connection->getStatusLabel());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001943#endif
1944 return;
1945 }
1946
1947 // Split a motion event if needed.
1948 if (inputTarget->flags & InputTarget::FLAG_SPLIT) {
1949 ALOG_ASSERT(eventEntry->type == EventEntry::TYPE_MOTION);
1950
1951 MotionEntry* originalMotionEntry = static_cast<MotionEntry*>(eventEntry);
1952 if (inputTarget->pointerIds.count() != originalMotionEntry->pointerCount) {
1953 MotionEntry* splitMotionEntry = splitMotionEvent(
1954 originalMotionEntry, inputTarget->pointerIds);
1955 if (!splitMotionEntry) {
1956 return; // split event was dropped
1957 }
1958#if DEBUG_FOCUS
1959 ALOGD("channel '%s' ~ Split motion event.",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08001960 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001961 logOutboundMotionDetailsLocked(" ", splitMotionEntry);
1962#endif
1963 enqueueDispatchEntriesLocked(currentTime, connection,
1964 splitMotionEntry, inputTarget);
1965 splitMotionEntry->release();
1966 return;
1967 }
1968 }
1969
1970 // Not splitting. Enqueue dispatch entries for the event as is.
1971 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
1972}
1973
1974void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
1975 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget) {
1976 bool wasEmpty = connection->outboundQueue.isEmpty();
1977
1978 // Enqueue dispatch entries for the requested modes.
1979 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1980 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
1981 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1982 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
1983 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1984 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
1985 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1986 InputTarget::FLAG_DISPATCH_AS_IS);
1987 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1988 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
1989 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1990 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
1991
1992 // If the outbound queue was previously empty, start the dispatch cycle going.
1993 if (wasEmpty && !connection->outboundQueue.isEmpty()) {
1994 startDispatchCycleLocked(currentTime, connection);
1995 }
1996}
1997
1998void InputDispatcher::enqueueDispatchEntryLocked(
1999 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget,
2000 int32_t dispatchMode) {
2001 int32_t inputTargetFlags = inputTarget->flags;
2002 if (!(inputTargetFlags & dispatchMode)) {
2003 return;
2004 }
2005 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
2006
2007 // This is a new event.
2008 // Enqueue a new dispatch entry onto the outbound queue for this connection.
2009 DispatchEntry* dispatchEntry = new DispatchEntry(eventEntry, // increments ref
2010 inputTargetFlags, inputTarget->xOffset, inputTarget->yOffset,
Robert Carre07e1032018-11-26 12:55:53 -08002011 inputTarget->globalScaleFactor, inputTarget->windowXScale,
2012 inputTarget->windowYScale);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002013
2014 // Apply target flags and update the connection's input state.
2015 switch (eventEntry->type) {
2016 case EventEntry::TYPE_KEY: {
2017 KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
2018 dispatchEntry->resolvedAction = keyEntry->action;
2019 dispatchEntry->resolvedFlags = keyEntry->flags;
2020
2021 if (!connection->inputState.trackKey(keyEntry,
2022 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags)) {
2023#if DEBUG_DISPATCH_CYCLE
2024 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002025 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002026#endif
2027 delete dispatchEntry;
2028 return; // skip the inconsistent event
2029 }
2030 break;
2031 }
2032
2033 case EventEntry::TYPE_MOTION: {
2034 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
2035 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2036 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
2037 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
2038 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
2039 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
2040 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2041 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
2042 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
2043 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
2044 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
2045 } else {
2046 dispatchEntry->resolvedAction = motionEntry->action;
2047 }
2048 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE
2049 && !connection->inputState.isHovering(
2050 motionEntry->deviceId, motionEntry->source, motionEntry->displayId)) {
2051#if DEBUG_DISPATCH_CYCLE
2052 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter event",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002053 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002054#endif
2055 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2056 }
2057
2058 dispatchEntry->resolvedFlags = motionEntry->flags;
2059 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
2060 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
2061 }
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002062 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
2063 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2064 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002065
2066 if (!connection->inputState.trackMotion(motionEntry,
2067 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags)) {
2068#if DEBUG_DISPATCH_CYCLE
2069 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion event",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002070 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002071#endif
2072 delete dispatchEntry;
2073 return; // skip the inconsistent event
2074 }
2075 break;
2076 }
2077 }
2078
2079 // Remember that we are waiting for this dispatch to complete.
2080 if (dispatchEntry->hasForegroundTarget()) {
2081 incrementPendingForegroundDispatchesLocked(eventEntry);
2082 }
2083
2084 // Enqueue the dispatch entry.
2085 connection->outboundQueue.enqueueAtTail(dispatchEntry);
2086 traceOutboundQueueLengthLocked(connection);
2087}
2088
2089void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
2090 const sp<Connection>& connection) {
2091#if DEBUG_DISPATCH_CYCLE
2092 ALOGD("channel '%s' ~ startDispatchCycle",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002093 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002094#endif
2095
2096 while (connection->status == Connection::STATUS_NORMAL
2097 && !connection->outboundQueue.isEmpty()) {
2098 DispatchEntry* dispatchEntry = connection->outboundQueue.head;
2099 dispatchEntry->deliveryTime = currentTime;
2100
2101 // Publish the event.
2102 status_t status;
2103 EventEntry* eventEntry = dispatchEntry->eventEntry;
2104 switch (eventEntry->type) {
2105 case EventEntry::TYPE_KEY: {
2106 KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
2107
2108 // Publish the key event.
2109 status = connection->inputPublisher.publishKeyEvent(dispatchEntry->seq,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002110 keyEntry->deviceId, keyEntry->source, keyEntry->displayId,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002111 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags,
2112 keyEntry->keyCode, keyEntry->scanCode,
2113 keyEntry->metaState, keyEntry->repeatCount, keyEntry->downTime,
2114 keyEntry->eventTime);
2115 break;
2116 }
2117
2118 case EventEntry::TYPE_MOTION: {
2119 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
2120
2121 PointerCoords scaledCoords[MAX_POINTERS];
2122 const PointerCoords* usingCoords = motionEntry->pointerCoords;
2123
2124 // Set the X and Y offset depending on the input source.
Siarhei Vishniakou635cb712017-11-01 16:32:14 -07002125 float xOffset, yOffset;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002126 if ((motionEntry->source & AINPUT_SOURCE_CLASS_POINTER)
2127 && !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
Robert Carre07e1032018-11-26 12:55:53 -08002128 float globalScaleFactor = dispatchEntry->globalScaleFactor;
2129 float wxs = dispatchEntry->windowXScale;
2130 float wys = dispatchEntry->windowYScale;
2131 xOffset = dispatchEntry->xOffset * wxs;
2132 yOffset = dispatchEntry->yOffset * wys;
2133 if (wxs != 1.0f || wys != 1.0f || globalScaleFactor != 1.0f) {
Narayan Kamathbc6001b2014-05-02 17:53:33 +01002134 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002135 scaledCoords[i] = motionEntry->pointerCoords[i];
Robert Carre07e1032018-11-26 12:55:53 -08002136 scaledCoords[i].scale(globalScaleFactor, wxs, wys);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002137 }
2138 usingCoords = scaledCoords;
2139 }
2140 } else {
2141 xOffset = 0.0f;
2142 yOffset = 0.0f;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002143
2144 // We don't want the dispatch target to know.
2145 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
Narayan Kamathbc6001b2014-05-02 17:53:33 +01002146 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002147 scaledCoords[i].clear();
2148 }
2149 usingCoords = scaledCoords;
2150 }
2151 }
2152
2153 // Publish the motion event.
2154 status = connection->inputPublisher.publishMotionEvent(dispatchEntry->seq,
Tarandeep Singh58641502017-07-31 10:51:54 -07002155 motionEntry->deviceId, motionEntry->source, motionEntry->displayId,
Michael Wright7b159c92015-05-14 14:48:03 +01002156 dispatchEntry->resolvedAction, motionEntry->actionButton,
2157 dispatchEntry->resolvedFlags, motionEntry->edgeFlags,
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08002158 motionEntry->metaState, motionEntry->buttonState, motionEntry->classification,
Michael Wright7b159c92015-05-14 14:48:03 +01002159 xOffset, yOffset, motionEntry->xPrecision, motionEntry->yPrecision,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002160 motionEntry->downTime, motionEntry->eventTime,
2161 motionEntry->pointerCount, motionEntry->pointerProperties,
2162 usingCoords);
2163 break;
2164 }
2165
2166 default:
2167 ALOG_ASSERT(false);
2168 return;
2169 }
2170
2171 // Check the result.
2172 if (status) {
2173 if (status == WOULD_BLOCK) {
2174 if (connection->waitQueue.isEmpty()) {
2175 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
2176 "This is unexpected because the wait queue is empty, so the pipe "
2177 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002178 "event to it, status=%d", connection->getInputChannelName().c_str(),
2179 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002180 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2181 } else {
2182 // Pipe is full and we are waiting for the app to finish process some events
2183 // before sending more events to it.
2184#if DEBUG_DISPATCH_CYCLE
2185 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
2186 "waiting for the application to catch up",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002187 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002188#endif
2189 connection->inputPublisherBlocked = true;
2190 }
2191 } else {
2192 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002193 "status=%d", connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002194 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2195 }
2196 return;
2197 }
2198
2199 // Re-enqueue the event on the wait queue.
2200 connection->outboundQueue.dequeue(dispatchEntry);
2201 traceOutboundQueueLengthLocked(connection);
2202 connection->waitQueue.enqueueAtTail(dispatchEntry);
2203 traceWaitQueueLengthLocked(connection);
2204 }
2205}
2206
2207void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
2208 const sp<Connection>& connection, uint32_t seq, bool handled) {
2209#if DEBUG_DISPATCH_CYCLE
2210 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002211 connection->getInputChannelName().c_str(), seq, toString(handled));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002212#endif
2213
2214 connection->inputPublisherBlocked = false;
2215
2216 if (connection->status == Connection::STATUS_BROKEN
2217 || connection->status == Connection::STATUS_ZOMBIE) {
2218 return;
2219 }
2220
2221 // Notify other system components and prepare to start the next dispatch cycle.
2222 onDispatchCycleFinishedLocked(currentTime, connection, seq, handled);
2223}
2224
2225void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
2226 const sp<Connection>& connection, bool notify) {
2227#if DEBUG_DISPATCH_CYCLE
2228 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002229 connection->getInputChannelName().c_str(), toString(notify));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002230#endif
2231
2232 // Clear the dispatch queues.
2233 drainDispatchQueueLocked(&connection->outboundQueue);
2234 traceOutboundQueueLengthLocked(connection);
2235 drainDispatchQueueLocked(&connection->waitQueue);
2236 traceWaitQueueLengthLocked(connection);
2237
2238 // The connection appears to be unrecoverably broken.
2239 // Ignore already broken or zombie connections.
2240 if (connection->status == Connection::STATUS_NORMAL) {
2241 connection->status = Connection::STATUS_BROKEN;
2242
2243 if (notify) {
2244 // Notify other system components.
2245 onDispatchCycleBrokenLocked(currentTime, connection);
2246 }
2247 }
2248}
2249
2250void InputDispatcher::drainDispatchQueueLocked(Queue<DispatchEntry>* queue) {
2251 while (!queue->isEmpty()) {
2252 DispatchEntry* dispatchEntry = queue->dequeueAtHead();
2253 releaseDispatchEntryLocked(dispatchEntry);
2254 }
2255}
2256
2257void InputDispatcher::releaseDispatchEntryLocked(DispatchEntry* dispatchEntry) {
2258 if (dispatchEntry->hasForegroundTarget()) {
2259 decrementPendingForegroundDispatchesLocked(dispatchEntry->eventEntry);
2260 }
2261 delete dispatchEntry;
2262}
2263
2264int InputDispatcher::handleReceiveCallback(int fd, int events, void* data) {
2265 InputDispatcher* d = static_cast<InputDispatcher*>(data);
2266
2267 { // acquire lock
2268 AutoMutex _l(d->mLock);
2269
2270 ssize_t connectionIndex = d->mConnectionsByFd.indexOfKey(fd);
2271 if (connectionIndex < 0) {
2272 ALOGE("Received spurious receive callback for unknown input channel. "
2273 "fd=%d, events=0x%x", fd, events);
2274 return 0; // remove the callback
2275 }
2276
2277 bool notify;
2278 sp<Connection> connection = d->mConnectionsByFd.valueAt(connectionIndex);
2279 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
2280 if (!(events & ALOOPER_EVENT_INPUT)) {
2281 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002282 "events=0x%x", connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002283 return 1;
2284 }
2285
2286 nsecs_t currentTime = now();
2287 bool gotOne = false;
2288 status_t status;
2289 for (;;) {
2290 uint32_t seq;
2291 bool handled;
2292 status = connection->inputPublisher.receiveFinishedSignal(&seq, &handled);
2293 if (status) {
2294 break;
2295 }
2296 d->finishDispatchCycleLocked(currentTime, connection, seq, handled);
2297 gotOne = true;
2298 }
2299 if (gotOne) {
2300 d->runCommandsLockedInterruptible();
2301 if (status == WOULD_BLOCK) {
2302 return 1;
2303 }
2304 }
2305
2306 notify = status != DEAD_OBJECT || !connection->monitor;
2307 if (notify) {
2308 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002309 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002310 }
2311 } else {
2312 // Monitor channels are never explicitly unregistered.
2313 // We do it automatically when the remote endpoint is closed so don't warn
2314 // about them.
2315 notify = !connection->monitor;
2316 if (notify) {
2317 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. "
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002318 "events=0x%x", connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002319 }
2320 }
2321
2322 // Unregister the channel.
2323 d->unregisterInputChannelLocked(connection->inputChannel, notify);
2324 return 0; // remove the callback
2325 } // release lock
2326}
2327
2328void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
2329 const CancelationOptions& options) {
2330 for (size_t i = 0; i < mConnectionsByFd.size(); i++) {
2331 synthesizeCancelationEventsForConnectionLocked(
2332 mConnectionsByFd.valueAt(i), options);
2333 }
2334}
2335
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002336void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
2337 const CancelationOptions& options) {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002338 for (auto& it : mMonitoringChannelsByDisplay) {
2339 const Vector<sp<InputChannel>>& monitoringChannels = it.second;
2340 const size_t numChannels = monitoringChannels.size();
2341 for (size_t i = 0; i < numChannels; i++) {
2342 synthesizeCancelationEventsForInputChannelLocked(monitoringChannels[i], options);
2343 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002344 }
2345}
2346
Michael Wrightd02c5b62014-02-10 15:10:22 -08002347void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
2348 const sp<InputChannel>& channel, const CancelationOptions& options) {
2349 ssize_t index = getConnectionIndexLocked(channel);
2350 if (index >= 0) {
2351 synthesizeCancelationEventsForConnectionLocked(
2352 mConnectionsByFd.valueAt(index), options);
2353 }
2354}
2355
2356void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
2357 const sp<Connection>& connection, const CancelationOptions& options) {
2358 if (connection->status == Connection::STATUS_BROKEN) {
2359 return;
2360 }
2361
2362 nsecs_t currentTime = now();
2363
2364 Vector<EventEntry*> cancelationEvents;
2365 connection->inputState.synthesizeCancelationEvents(currentTime,
2366 cancelationEvents, options);
2367
2368 if (!cancelationEvents.isEmpty()) {
2369#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002370 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
Michael Wrightd02c5b62014-02-10 15:10:22 -08002371 "with reality: %s, mode=%d.",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002372 connection->getInputChannelName().c_str(), cancelationEvents.size(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002373 options.reason, options.mode);
2374#endif
2375 for (size_t i = 0; i < cancelationEvents.size(); i++) {
2376 EventEntry* cancelationEventEntry = cancelationEvents.itemAt(i);
2377 switch (cancelationEventEntry->type) {
2378 case EventEntry::TYPE_KEY:
2379 logOutboundKeyDetailsLocked("cancel - ",
2380 static_cast<KeyEntry*>(cancelationEventEntry));
2381 break;
2382 case EventEntry::TYPE_MOTION:
2383 logOutboundMotionDetailsLocked("cancel - ",
2384 static_cast<MotionEntry*>(cancelationEventEntry));
2385 break;
2386 }
2387
2388 InputTarget target;
chaviwfbe5d9c2018-12-26 12:23:37 -08002389 sp<InputWindowHandle> windowHandle = getWindowHandleLocked(
2390 connection->inputChannel->getToken());
Yi Kong9b14ac62018-07-17 13:48:38 -07002391 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002392 const InputWindowInfo* windowInfo = windowHandle->getInfo();
2393 target.xOffset = -windowInfo->frameLeft;
2394 target.yOffset = -windowInfo->frameTop;
Robert Carre07e1032018-11-26 12:55:53 -08002395 target.globalScaleFactor = windowInfo->globalScaleFactor;
2396 target.windowXScale = windowInfo->windowXScale;
2397 target.windowYScale = windowInfo->windowYScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002398 } else {
2399 target.xOffset = 0;
2400 target.yOffset = 0;
Robert Carre07e1032018-11-26 12:55:53 -08002401 target.globalScaleFactor = 1.0f;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002402 }
2403 target.inputChannel = connection->inputChannel;
2404 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
2405
2406 enqueueDispatchEntryLocked(connection, cancelationEventEntry, // increments ref
2407 &target, InputTarget::FLAG_DISPATCH_AS_IS);
2408
2409 cancelationEventEntry->release();
2410 }
2411
2412 startDispatchCycleLocked(currentTime, connection);
2413 }
2414}
2415
2416InputDispatcher::MotionEntry*
2417InputDispatcher::splitMotionEvent(const MotionEntry* originalMotionEntry, BitSet32 pointerIds) {
2418 ALOG_ASSERT(pointerIds.value != 0);
2419
2420 uint32_t splitPointerIndexMap[MAX_POINTERS];
2421 PointerProperties splitPointerProperties[MAX_POINTERS];
2422 PointerCoords splitPointerCoords[MAX_POINTERS];
2423
2424 uint32_t originalPointerCount = originalMotionEntry->pointerCount;
2425 uint32_t splitPointerCount = 0;
2426
2427 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
2428 originalPointerIndex++) {
2429 const PointerProperties& pointerProperties =
2430 originalMotionEntry->pointerProperties[originalPointerIndex];
2431 uint32_t pointerId = uint32_t(pointerProperties.id);
2432 if (pointerIds.hasBit(pointerId)) {
2433 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
2434 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
2435 splitPointerCoords[splitPointerCount].copyFrom(
2436 originalMotionEntry->pointerCoords[originalPointerIndex]);
2437 splitPointerCount += 1;
2438 }
2439 }
2440
2441 if (splitPointerCount != pointerIds.count()) {
2442 // This is bad. We are missing some of the pointers that we expected to deliver.
2443 // Most likely this indicates that we received an ACTION_MOVE events that has
2444 // different pointer ids than we expected based on the previous ACTION_DOWN
2445 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
2446 // in this way.
2447 ALOGW("Dropping split motion event because the pointer count is %d but "
2448 "we expected there to be %d pointers. This probably means we received "
2449 "a broken sequence of pointer ids from the input device.",
2450 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07002451 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002452 }
2453
2454 int32_t action = originalMotionEntry->action;
2455 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
2456 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
2457 || maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2458 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
2459 const PointerProperties& pointerProperties =
2460 originalMotionEntry->pointerProperties[originalPointerIndex];
2461 uint32_t pointerId = uint32_t(pointerProperties.id);
2462 if (pointerIds.hasBit(pointerId)) {
2463 if (pointerIds.count() == 1) {
2464 // The first/last pointer went down/up.
2465 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
2466 ? AMOTION_EVENT_ACTION_DOWN : AMOTION_EVENT_ACTION_UP;
2467 } else {
2468 // A secondary pointer went down/up.
2469 uint32_t splitPointerIndex = 0;
2470 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
2471 splitPointerIndex += 1;
2472 }
2473 action = maskedAction | (splitPointerIndex
2474 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
2475 }
2476 } else {
2477 // An unrelated pointer changed.
2478 action = AMOTION_EVENT_ACTION_MOVE;
2479 }
2480 }
2481
2482 MotionEntry* splitMotionEntry = new MotionEntry(
Prabir Pradhan42611e02018-11-27 14:04:02 -08002483 originalMotionEntry->sequenceNum,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002484 originalMotionEntry->eventTime,
2485 originalMotionEntry->deviceId,
2486 originalMotionEntry->source,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002487 originalMotionEntry->displayId,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002488 originalMotionEntry->policyFlags,
2489 action,
Michael Wright7b159c92015-05-14 14:48:03 +01002490 originalMotionEntry->actionButton,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002491 originalMotionEntry->flags,
2492 originalMotionEntry->metaState,
2493 originalMotionEntry->buttonState,
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08002494 originalMotionEntry->classification,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002495 originalMotionEntry->edgeFlags,
2496 originalMotionEntry->xPrecision,
2497 originalMotionEntry->yPrecision,
2498 originalMotionEntry->downTime,
Jeff Brownf086ddb2014-02-11 14:28:48 -08002499 splitPointerCount, splitPointerProperties, splitPointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002500
2501 if (originalMotionEntry->injectionState) {
2502 splitMotionEntry->injectionState = originalMotionEntry->injectionState;
2503 splitMotionEntry->injectionState->refCount += 1;
2504 }
2505
2506 return splitMotionEntry;
2507}
2508
2509void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
2510#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002511 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002512#endif
2513
2514 bool needWake;
2515 { // acquire lock
2516 AutoMutex _l(mLock);
2517
Prabir Pradhan42611e02018-11-27 14:04:02 -08002518 ConfigurationChangedEntry* newEntry =
2519 new ConfigurationChangedEntry(args->sequenceNum, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002520 needWake = enqueueInboundEventLocked(newEntry);
2521 } // release lock
2522
2523 if (needWake) {
2524 mLooper->wake();
2525 }
2526}
2527
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002528/**
2529 * If one of the meta shortcuts is detected, process them here:
2530 * Meta + Backspace -> generate BACK
2531 * Meta + Enter -> generate HOME
2532 * This will potentially overwrite keyCode and metaState.
2533 */
2534void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
2535 int32_t& keyCode, int32_t& metaState) {
2536 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
2537 int32_t newKeyCode = AKEYCODE_UNKNOWN;
2538 if (keyCode == AKEYCODE_DEL) {
2539 newKeyCode = AKEYCODE_BACK;
2540 } else if (keyCode == AKEYCODE_ENTER) {
2541 newKeyCode = AKEYCODE_HOME;
2542 }
2543 if (newKeyCode != AKEYCODE_UNKNOWN) {
2544 AutoMutex _l(mLock);
2545 struct KeyReplacement replacement = {keyCode, deviceId};
2546 mReplacedKeys.add(replacement, newKeyCode);
2547 keyCode = newKeyCode;
2548 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
2549 }
2550 } else if (action == AKEY_EVENT_ACTION_UP) {
2551 // In order to maintain a consistent stream of up and down events, check to see if the key
2552 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
2553 // even if the modifier was released between the down and the up events.
2554 AutoMutex _l(mLock);
2555 struct KeyReplacement replacement = {keyCode, deviceId};
2556 ssize_t index = mReplacedKeys.indexOfKey(replacement);
2557 if (index >= 0) {
2558 keyCode = mReplacedKeys.valueAt(index);
2559 mReplacedKeys.removeItemsAt(index);
2560 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
2561 }
2562 }
2563}
2564
Michael Wrightd02c5b62014-02-10 15:10:22 -08002565void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
2566#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002567 ALOGD("notifyKey - eventTime=%" PRId64
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002568 ", deviceId=%d, source=0x%x, displayId=%" PRId32 "policyFlags=0x%x, action=0x%x, "
Arthur Hung82a4cad2018-11-15 12:10:30 +08002569 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002570 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002571 args->action, args->flags, args->keyCode, args->scanCode,
Arthur Hung82a4cad2018-11-15 12:10:30 +08002572 args->metaState, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002573#endif
2574 if (!validateKeyEvent(args->action)) {
2575 return;
2576 }
2577
2578 uint32_t policyFlags = args->policyFlags;
2579 int32_t flags = args->flags;
2580 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07002581 // InputDispatcher tracks and generates key repeats on behalf of
2582 // whatever notifies it, so repeatCount should always be set to 0
2583 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002584 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
2585 policyFlags |= POLICY_FLAG_VIRTUAL;
2586 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
2587 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002588 if (policyFlags & POLICY_FLAG_FUNCTION) {
2589 metaState |= AMETA_FUNCTION_ON;
2590 }
2591
2592 policyFlags |= POLICY_FLAG_TRUSTED;
2593
Michael Wright78f24442014-08-06 15:55:28 -07002594 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002595 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07002596
Michael Wrightd02c5b62014-02-10 15:10:22 -08002597 KeyEvent event;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002598 event.initialize(args->deviceId, args->source, args->displayId, args->action,
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07002599 flags, keyCode, args->scanCode, metaState, repeatCount,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002600 args->downTime, args->eventTime);
2601
Michael Wright2b3c3302018-03-02 17:19:13 +00002602 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002603 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002604 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2605 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
2606 std::to_string(t.duration().count()).c_str());
2607 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002608
Michael Wrightd02c5b62014-02-10 15:10:22 -08002609 bool needWake;
2610 { // acquire lock
2611 mLock.lock();
2612
2613 if (shouldSendKeyToInputFilterLocked(args)) {
2614 mLock.unlock();
2615
2616 policyFlags |= POLICY_FLAG_FILTERED;
2617 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2618 return; // event was consumed by the filter
2619 }
2620
2621 mLock.lock();
2622 }
2623
Prabir Pradhan42611e02018-11-27 14:04:02 -08002624 KeyEntry* newEntry = new KeyEntry(args->sequenceNum, args->eventTime,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002625 args->deviceId, args->source, args->displayId, policyFlags,
Michael Wright78f24442014-08-06 15:55:28 -07002626 args->action, flags, keyCode, args->scanCode,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002627 metaState, repeatCount, args->downTime);
2628
2629 needWake = enqueueInboundEventLocked(newEntry);
2630 mLock.unlock();
2631 } // release lock
2632
2633 if (needWake) {
2634 mLooper->wake();
2635 }
2636}
2637
2638bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
2639 return mInputFilterEnabled;
2640}
2641
2642void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
2643#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002644 ALOGD("notifyMotion - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
2645 ", policyFlags=0x%x, "
Michael Wright7b159c92015-05-14 14:48:03 +01002646 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x,"
Arthur Hung82a4cad2018-11-15 12:10:30 +08002647 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
2648 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002649 args->action, args->actionButton, args->flags, args->metaState, args->buttonState,
Arthur Hung82a4cad2018-11-15 12:10:30 +08002650 args->edgeFlags, args->xPrecision, args->yPrecision, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002651 for (uint32_t i = 0; i < args->pointerCount; i++) {
2652 ALOGD(" Pointer %d: id=%d, toolType=%d, "
2653 "x=%f, y=%f, pressure=%f, size=%f, "
2654 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
2655 "orientation=%f",
2656 i, args->pointerProperties[i].id,
2657 args->pointerProperties[i].toolType,
2658 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
2659 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
2660 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
2661 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
2662 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
2663 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
2664 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
2665 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
2666 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
2667 }
2668#endif
Michael Wright7b159c92015-05-14 14:48:03 +01002669 if (!validateMotionEvent(args->action, args->actionButton,
2670 args->pointerCount, args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002671 return;
2672 }
2673
2674 uint32_t policyFlags = args->policyFlags;
2675 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00002676
2677 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002678 mPolicy->interceptMotionBeforeQueueing(args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002679 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2680 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
2681 std::to_string(t.duration().count()).c_str());
2682 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002683
2684 bool needWake;
2685 { // acquire lock
2686 mLock.lock();
2687
2688 if (shouldSendMotionToInputFilterLocked(args)) {
2689 mLock.unlock();
2690
2691 MotionEvent event;
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002692 event.initialize(args->deviceId, args->source, args->displayId,
2693 args->action, args->actionButton,
Michael Wright7b159c92015-05-14 14:48:03 +01002694 args->flags, args->edgeFlags, args->metaState, args->buttonState,
Siarhei Vishniakouae478d32019-01-03 14:45:18 -08002695 args->classification, 0, 0, args->xPrecision, args->yPrecision,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002696 args->downTime, args->eventTime,
2697 args->pointerCount, args->pointerProperties, args->pointerCoords);
2698
2699 policyFlags |= POLICY_FLAG_FILTERED;
2700 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2701 return; // event was consumed by the filter
2702 }
2703
2704 mLock.lock();
2705 }
2706
2707 // Just enqueue a new motion event.
Prabir Pradhan42611e02018-11-27 14:04:02 -08002708 MotionEntry* newEntry = new MotionEntry(args->sequenceNum, args->eventTime,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002709 args->deviceId, args->source, args->displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002710 args->action, args->actionButton, args->flags,
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08002711 args->metaState, args->buttonState, args->classification,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002712 args->edgeFlags, args->xPrecision, args->yPrecision, args->downTime,
Jeff Brownf086ddb2014-02-11 14:28:48 -08002713 args->pointerCount, args->pointerProperties, args->pointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002714
2715 needWake = enqueueInboundEventLocked(newEntry);
2716 mLock.unlock();
2717 } // release lock
2718
2719 if (needWake) {
2720 mLooper->wake();
2721 }
2722}
2723
2724bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
2725 // TODO: support sending secondary display events to input filter
2726 return mInputFilterEnabled && isMainDisplay(args->displayId);
2727}
2728
2729void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
2730#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002731 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
2732 "switchMask=0x%08x",
2733 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002734#endif
2735
2736 uint32_t policyFlags = args->policyFlags;
2737 policyFlags |= POLICY_FLAG_TRUSTED;
2738 mPolicy->notifySwitch(args->eventTime,
2739 args->switchValues, args->switchMask, policyFlags);
2740}
2741
2742void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
2743#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002744 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002745 args->eventTime, args->deviceId);
2746#endif
2747
2748 bool needWake;
2749 { // acquire lock
2750 AutoMutex _l(mLock);
2751
Prabir Pradhan42611e02018-11-27 14:04:02 -08002752 DeviceResetEntry* newEntry =
2753 new DeviceResetEntry(args->sequenceNum, args->eventTime, args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002754 needWake = enqueueInboundEventLocked(newEntry);
2755 } // release lock
2756
2757 if (needWake) {
2758 mLooper->wake();
2759 }
2760}
2761
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002762int32_t InputDispatcher::injectInputEvent(const InputEvent* event,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002763 int32_t injectorPid, int32_t injectorUid, int32_t syncMode, int32_t timeoutMillis,
2764 uint32_t policyFlags) {
2765#if DEBUG_INBOUND_EVENT_DETAILS
2766 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002767 "syncMode=%d, timeoutMillis=%d, policyFlags=0x%08x",
2768 event->getType(), injectorPid, injectorUid, syncMode, timeoutMillis, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002769#endif
2770
2771 nsecs_t endTime = now() + milliseconds_to_nanoseconds(timeoutMillis);
2772
2773 policyFlags |= POLICY_FLAG_INJECTED;
2774 if (hasInjectionPermission(injectorPid, injectorUid)) {
2775 policyFlags |= POLICY_FLAG_TRUSTED;
2776 }
2777
2778 EventEntry* firstInjectedEntry;
2779 EventEntry* lastInjectedEntry;
2780 switch (event->getType()) {
2781 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002782 KeyEvent keyEvent;
2783 keyEvent.initialize(*static_cast<const KeyEvent*>(event));
2784 int32_t action = keyEvent.getAction();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002785 if (! validateKeyEvent(action)) {
2786 return INPUT_EVENT_INJECTION_FAILED;
2787 }
2788
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002789 int32_t flags = keyEvent.getFlags();
2790 int32_t keyCode = keyEvent.getKeyCode();
2791 int32_t metaState = keyEvent.getMetaState();
2792 accelerateMetaShortcuts(keyEvent.getDeviceId(), action,
2793 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002794 keyEvent.initialize(keyEvent.getDeviceId(), keyEvent.getSource(), keyEvent.getDisplayId(),
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07002795 action, flags, keyCode, keyEvent.getScanCode(), metaState, keyEvent.getRepeatCount(),
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002796 keyEvent.getDownTime(), keyEvent.getEventTime());
2797
Michael Wrightd02c5b62014-02-10 15:10:22 -08002798 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
2799 policyFlags |= POLICY_FLAG_VIRTUAL;
2800 }
2801
2802 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wright2b3c3302018-03-02 17:19:13 +00002803 android::base::Timer t;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002804 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002805 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2806 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
2807 std::to_string(t.duration().count()).c_str());
2808 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002809 }
2810
Michael Wrightd02c5b62014-02-10 15:10:22 -08002811 mLock.lock();
Prabir Pradhan42611e02018-11-27 14:04:02 -08002812 firstInjectedEntry = new KeyEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, keyEvent.getEventTime(),
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002813 keyEvent.getDeviceId(), keyEvent.getSource(), keyEvent.getDisplayId(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002814 policyFlags, action, flags,
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002815 keyEvent.getKeyCode(), keyEvent.getScanCode(), keyEvent.getMetaState(),
2816 keyEvent.getRepeatCount(), keyEvent.getDownTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002817 lastInjectedEntry = firstInjectedEntry;
2818 break;
2819 }
2820
2821 case AINPUT_EVENT_TYPE_MOTION: {
2822 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002823 int32_t action = motionEvent->getAction();
2824 size_t pointerCount = motionEvent->getPointerCount();
2825 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
Michael Wright7b159c92015-05-14 14:48:03 +01002826 int32_t actionButton = motionEvent->getActionButton();
2827 if (! validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002828 return INPUT_EVENT_INJECTION_FAILED;
2829 }
2830
2831 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
2832 nsecs_t eventTime = motionEvent->getEventTime();
Michael Wright2b3c3302018-03-02 17:19:13 +00002833 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002834 mPolicy->interceptMotionBeforeQueueing(eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002835 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2836 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
2837 std::to_string(t.duration().count()).c_str());
2838 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002839 }
2840
2841 mLock.lock();
2842 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
2843 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
Prabir Pradhan42611e02018-11-27 14:04:02 -08002844 firstInjectedEntry = new MotionEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, *sampleEventTimes,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002845 motionEvent->getDeviceId(), motionEvent->getSource(), motionEvent->getDisplayId(),
2846 policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002847 action, actionButton, motionEvent->getFlags(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002848 motionEvent->getMetaState(), motionEvent->getButtonState(),
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08002849 motionEvent->getClassification(), motionEvent->getEdgeFlags(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002850 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002851 motionEvent->getDownTime(),
Jeff Brownf086ddb2014-02-11 14:28:48 -08002852 uint32_t(pointerCount), pointerProperties, samplePointerCoords,
2853 motionEvent->getXOffset(), motionEvent->getYOffset());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002854 lastInjectedEntry = firstInjectedEntry;
2855 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
2856 sampleEventTimes += 1;
2857 samplePointerCoords += pointerCount;
Prabir Pradhan42611e02018-11-27 14:04:02 -08002858 MotionEntry* nextInjectedEntry = new MotionEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM,
2859 *sampleEventTimes,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002860 motionEvent->getDeviceId(), motionEvent->getSource(),
2861 motionEvent->getDisplayId(), policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002862 action, actionButton, motionEvent->getFlags(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002863 motionEvent->getMetaState(), motionEvent->getButtonState(),
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08002864 motionEvent->getClassification(), motionEvent->getEdgeFlags(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002865 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002866 motionEvent->getDownTime(),
Jeff Brownf086ddb2014-02-11 14:28:48 -08002867 uint32_t(pointerCount), pointerProperties, samplePointerCoords,
2868 motionEvent->getXOffset(), motionEvent->getYOffset());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002869 lastInjectedEntry->next = nextInjectedEntry;
2870 lastInjectedEntry = nextInjectedEntry;
2871 }
2872 break;
2873 }
2874
2875 default:
2876 ALOGW("Cannot inject event of type %d", event->getType());
2877 return INPUT_EVENT_INJECTION_FAILED;
2878 }
2879
2880 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
2881 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
2882 injectionState->injectionIsAsync = true;
2883 }
2884
2885 injectionState->refCount += 1;
2886 lastInjectedEntry->injectionState = injectionState;
2887
2888 bool needWake = false;
Yi Kong9b14ac62018-07-17 13:48:38 -07002889 for (EventEntry* entry = firstInjectedEntry; entry != nullptr; ) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002890 EventEntry* nextEntry = entry->next;
2891 needWake |= enqueueInboundEventLocked(entry);
2892 entry = nextEntry;
2893 }
2894
2895 mLock.unlock();
2896
2897 if (needWake) {
2898 mLooper->wake();
2899 }
2900
2901 int32_t injectionResult;
2902 { // acquire lock
2903 AutoMutex _l(mLock);
2904
2905 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
2906 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
2907 } else {
2908 for (;;) {
2909 injectionResult = injectionState->injectionResult;
2910 if (injectionResult != INPUT_EVENT_INJECTION_PENDING) {
2911 break;
2912 }
2913
2914 nsecs_t remainingTimeout = endTime - now();
2915 if (remainingTimeout <= 0) {
2916#if DEBUG_INJECTION
2917 ALOGD("injectInputEvent - Timed out waiting for injection result "
2918 "to become available.");
2919#endif
2920 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
2921 break;
2922 }
2923
2924 mInjectionResultAvailableCondition.waitRelative(mLock, remainingTimeout);
2925 }
2926
2927 if (injectionResult == INPUT_EVENT_INJECTION_SUCCEEDED
2928 && syncMode == INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED) {
2929 while (injectionState->pendingForegroundDispatches != 0) {
2930#if DEBUG_INJECTION
2931 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
2932 injectionState->pendingForegroundDispatches);
2933#endif
2934 nsecs_t remainingTimeout = endTime - now();
2935 if (remainingTimeout <= 0) {
2936#if DEBUG_INJECTION
2937 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
2938 "dispatches to finish.");
2939#endif
2940 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
2941 break;
2942 }
2943
2944 mInjectionSyncFinishedCondition.waitRelative(mLock, remainingTimeout);
2945 }
2946 }
2947 }
2948
2949 injectionState->release();
2950 } // release lock
2951
2952#if DEBUG_INJECTION
2953 ALOGD("injectInputEvent - Finished with result %d. "
2954 "injectorPid=%d, injectorUid=%d",
2955 injectionResult, injectorPid, injectorUid);
2956#endif
2957
2958 return injectionResult;
2959}
2960
2961bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
2962 return injectorUid == 0
2963 || mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
2964}
2965
2966void InputDispatcher::setInjectionResultLocked(EventEntry* entry, int32_t injectionResult) {
2967 InjectionState* injectionState = entry->injectionState;
2968 if (injectionState) {
2969#if DEBUG_INJECTION
2970 ALOGD("Setting input event injection result to %d. "
2971 "injectorPid=%d, injectorUid=%d",
2972 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
2973#endif
2974
2975 if (injectionState->injectionIsAsync
2976 && !(entry->policyFlags & POLICY_FLAG_FILTERED)) {
2977 // Log the outcome since the injector did not wait for the injection result.
2978 switch (injectionResult) {
2979 case INPUT_EVENT_INJECTION_SUCCEEDED:
2980 ALOGV("Asynchronous input event injection succeeded.");
2981 break;
2982 case INPUT_EVENT_INJECTION_FAILED:
2983 ALOGW("Asynchronous input event injection failed.");
2984 break;
2985 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
2986 ALOGW("Asynchronous input event injection permission denied.");
2987 break;
2988 case INPUT_EVENT_INJECTION_TIMED_OUT:
2989 ALOGW("Asynchronous input event injection timed out.");
2990 break;
2991 }
2992 }
2993
2994 injectionState->injectionResult = injectionResult;
2995 mInjectionResultAvailableCondition.broadcast();
2996 }
2997}
2998
2999void InputDispatcher::incrementPendingForegroundDispatchesLocked(EventEntry* entry) {
3000 InjectionState* injectionState = entry->injectionState;
3001 if (injectionState) {
3002 injectionState->pendingForegroundDispatches += 1;
3003 }
3004}
3005
3006void InputDispatcher::decrementPendingForegroundDispatchesLocked(EventEntry* entry) {
3007 InjectionState* injectionState = entry->injectionState;
3008 if (injectionState) {
3009 injectionState->pendingForegroundDispatches -= 1;
3010
3011 if (injectionState->pendingForegroundDispatches == 0) {
3012 mInjectionSyncFinishedCondition.broadcast();
3013 }
3014 }
3015}
3016
Arthur Hungb92218b2018-08-14 12:00:21 +08003017Vector<sp<InputWindowHandle>> InputDispatcher::getWindowHandlesLocked(int32_t displayId) const {
3018 std::unordered_map<int32_t, Vector<sp<InputWindowHandle>>>::const_iterator it =
3019 mWindowHandlesByDisplay.find(displayId);
3020 if(it != mWindowHandlesByDisplay.end()) {
3021 return it->second;
3022 }
3023
3024 // Return an empty one if nothing found.
3025 return Vector<sp<InputWindowHandle>>();
3026}
3027
Michael Wrightd02c5b62014-02-10 15:10:22 -08003028sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08003029 const sp<IBinder>& windowHandleToken) const {
Arthur Hungb92218b2018-08-14 12:00:21 +08003030 for (auto& it : mWindowHandlesByDisplay) {
3031 const Vector<sp<InputWindowHandle>> windowHandles = it.second;
3032 size_t numWindows = windowHandles.size();
3033 for (size_t i = 0; i < numWindows; i++) {
3034 const sp<InputWindowHandle>& windowHandle = windowHandles.itemAt(i);
chaviwfbe5d9c2018-12-26 12:23:37 -08003035 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003036 return windowHandle;
3037 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003038 }
3039 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003040 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003041}
3042
3043bool InputDispatcher::hasWindowHandleLocked(
Siarhei Vishniakou9224fba2018-08-13 18:55:08 +00003044 const sp<InputWindowHandle>& windowHandle) const {
Arthur Hungb92218b2018-08-14 12:00:21 +08003045 for (auto& it : mWindowHandlesByDisplay) {
3046 const Vector<sp<InputWindowHandle>> windowHandles = it.second;
3047 size_t numWindows = windowHandles.size();
3048 for (size_t i = 0; i < numWindows; i++) {
Robert Carr5c8a0262018-10-03 16:30:44 -07003049 if (windowHandles.itemAt(i)->getToken()
3050 == windowHandle->getToken()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003051 if (windowHandle->getInfo()->displayId != it.first) {
Arthur Hung3b413f22018-10-26 18:05:34 +08003052 ALOGE("Found window %s in display %" PRId32
3053 ", but it should belong to display %" PRId32,
3054 windowHandle->getName().c_str(), it.first,
3055 windowHandle->getInfo()->displayId);
Arthur Hungb92218b2018-08-14 12:00:21 +08003056 }
3057 return true;
3058 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003059 }
3060 }
3061 return false;
3062}
3063
Robert Carr5c8a0262018-10-03 16:30:44 -07003064sp<InputChannel> InputDispatcher::getInputChannelLocked(const sp<IBinder>& token) const {
3065 size_t count = mInputChannelsByToken.count(token);
3066 if (count == 0) {
3067 return nullptr;
3068 }
3069 return mInputChannelsByToken.at(token);
3070}
3071
Arthur Hungb92218b2018-08-14 12:00:21 +08003072/**
3073 * Called from InputManagerService, update window handle list by displayId that can receive input.
3074 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
3075 * If set an empty list, remove all handles from the specific display.
3076 * For focused handle, check if need to change and send a cancel event to previous one.
3077 * For removed handle, check if need to send a cancel event if already in touch.
3078 */
3079void InputDispatcher::setInputWindows(const Vector<sp<InputWindowHandle>>& inputWindowHandles,
3080 int32_t displayId) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003081#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003082 ALOGD("setInputWindows displayId=%" PRId32, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003083#endif
3084 { // acquire lock
3085 AutoMutex _l(mLock);
3086
Arthur Hungb92218b2018-08-14 12:00:21 +08003087 // Copy old handles for release if they are no longer present.
3088 const Vector<sp<InputWindowHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003089
Tiger Huang721e26f2018-07-24 22:26:19 +08003090 sp<InputWindowHandle> newFocusedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003091 bool foundHoveredWindow = false;
Arthur Hungb92218b2018-08-14 12:00:21 +08003092
3093 if (inputWindowHandles.isEmpty()) {
3094 // Remove all handles on a display if there are no windows left.
3095 mWindowHandlesByDisplay.erase(displayId);
3096 } else {
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003097 // Since we compare the pointer of input window handles across window updates, we need
3098 // to make sure the handle object for the same window stays unchanged across updates.
3099 const Vector<sp<InputWindowHandle>>& oldHandles = mWindowHandlesByDisplay[displayId];
3100 std::unordered_map<sp<IBinder>, sp<InputWindowHandle>, IBinderHash> oldHandlesByTokens;
3101 for (size_t i = 0; i < oldHandles.size(); i++) {
3102 const sp<InputWindowHandle>& handle = oldHandles.itemAt(i);
3103 oldHandlesByTokens[handle->getToken()] = handle;
3104 }
3105
3106 const size_t numWindows = inputWindowHandles.size();
3107 Vector<sp<InputWindowHandle>> newHandles;
Arthur Hungb92218b2018-08-14 12:00:21 +08003108 for (size_t i = 0; i < numWindows; i++) {
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003109 const sp<InputWindowHandle>& handle = inputWindowHandles.itemAt(i);
3110 if (!handle->updateInfo() || getInputChannelLocked(handle->getToken()) == nullptr) {
Robert Carr5c8a0262018-10-03 16:30:44 -07003111 ALOGE("Window handle %s has no registered input channel",
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003112 handle->getName().c_str());
Arthur Hungb92218b2018-08-14 12:00:21 +08003113 continue;
3114 }
3115
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003116 if (handle->getInfo()->displayId != displayId) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003117 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003118 handle->getName().c_str(), displayId,
3119 handle->getInfo()->displayId);
Arthur Hungb92218b2018-08-14 12:00:21 +08003120 continue;
3121 }
3122
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003123 if (oldHandlesByTokens.find(handle->getToken()) != oldHandlesByTokens.end()) {
3124 const sp<InputWindowHandle> oldHandle =
3125 oldHandlesByTokens.at(handle->getToken());
3126 oldHandle->updateFrom(handle);
3127 newHandles.push_back(oldHandle);
3128 } else {
3129 newHandles.push_back(handle);
3130 }
3131 }
3132
3133 for (size_t i = 0; i < newHandles.size(); i++) {
3134 const sp<InputWindowHandle>& windowHandle = newHandles.itemAt(i);
Arthur Hung7ab76b12019-01-09 19:17:20 +08003135 // Set newFocusedWindowHandle to the top most focused window instead of the last one
3136 if (!newFocusedWindowHandle && windowHandle->getInfo()->hasFocus
3137 && windowHandle->getInfo()->visible) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003138 newFocusedWindowHandle = windowHandle;
3139 }
3140 if (windowHandle == mLastHoverWindowHandle) {
3141 foundHoveredWindow = true;
3142 }
Siarhei Vishniakou9224fba2018-08-13 18:55:08 +00003143 }
Arthur Hungb92218b2018-08-14 12:00:21 +08003144
3145 // Insert or replace
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003146 mWindowHandlesByDisplay[displayId] = newHandles;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003147 }
3148
3149 if (!foundHoveredWindow) {
Yi Kong9b14ac62018-07-17 13:48:38 -07003150 mLastHoverWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003151 }
3152
Tiger Huang721e26f2018-07-24 22:26:19 +08003153 sp<InputWindowHandle> oldFocusedWindowHandle =
3154 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
3155
3156 if (oldFocusedWindowHandle != newFocusedWindowHandle) {
3157 if (oldFocusedWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003158#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003159 ALOGD("Focus left window: %s in display %" PRId32,
3160 oldFocusedWindowHandle->getName().c_str(), displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003161#endif
Robert Carr5c8a0262018-10-03 16:30:44 -07003162 sp<InputChannel> focusedInputChannel = getInputChannelLocked(
3163 oldFocusedWindowHandle->getToken());
Yi Kong9b14ac62018-07-17 13:48:38 -07003164 if (focusedInputChannel != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003165 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
3166 "focus left window");
3167 synthesizeCancelationEventsForInputChannelLocked(
3168 focusedInputChannel, options);
3169 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003170 mFocusedWindowHandlesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003171 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003172 if (newFocusedWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003173#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003174 ALOGD("Focus entered window: %s in display %" PRId32,
3175 newFocusedWindowHandle->getName().c_str(), displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003176#endif
Tiger Huang721e26f2018-07-24 22:26:19 +08003177 mFocusedWindowHandlesByDisplay[displayId] = newFocusedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003178 }
Robert Carrf759f162018-11-13 12:57:11 -08003179
3180 if (mFocusedDisplayId == displayId) {
chaviw0c06c6e2019-01-09 13:27:07 -08003181 onFocusChangedLocked(oldFocusedWindowHandle, newFocusedWindowHandle);
Robert Carrf759f162018-11-13 12:57:11 -08003182 }
3183
Michael Wrightd02c5b62014-02-10 15:10:22 -08003184 }
3185
Arthur Hungb92218b2018-08-14 12:00:21 +08003186 ssize_t stateIndex = mTouchStatesByDisplay.indexOfKey(displayId);
3187 if (stateIndex >= 0) {
3188 TouchState& state = mTouchStatesByDisplay.editValueAt(stateIndex);
Ivan Lozano96f12992017-11-09 14:45:38 -08003189 for (size_t i = 0; i < state.windows.size(); ) {
Jeff Brownf086ddb2014-02-11 14:28:48 -08003190 TouchedWindow& touchedWindow = state.windows.editItemAt(i);
Siarhei Vishniakou9224fba2018-08-13 18:55:08 +00003191 if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003192#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003193 ALOGD("Touched window was removed: %s in display %" PRId32,
3194 touchedWindow.windowHandle->getName().c_str(), displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003195#endif
Jeff Brownf086ddb2014-02-11 14:28:48 -08003196 sp<InputChannel> touchedInputChannel =
Robert Carr5c8a0262018-10-03 16:30:44 -07003197 getInputChannelLocked(touchedWindow.windowHandle->getToken());
Yi Kong9b14ac62018-07-17 13:48:38 -07003198 if (touchedInputChannel != nullptr) {
Jeff Brownf086ddb2014-02-11 14:28:48 -08003199 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
3200 "touched window was removed");
3201 synthesizeCancelationEventsForInputChannelLocked(
3202 touchedInputChannel, options);
3203 }
Ivan Lozano96f12992017-11-09 14:45:38 -08003204 state.windows.removeAt(i);
3205 } else {
3206 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003207 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003208 }
3209 }
3210
3211 // Release information for windows that are no longer present.
3212 // This ensures that unused input channels are released promptly.
3213 // Otherwise, they might stick around until the window handle is destroyed
3214 // which might not happen until the next GC.
Arthur Hungb92218b2018-08-14 12:00:21 +08003215 size_t numWindows = oldWindowHandles.size();
3216 for (size_t i = 0; i < numWindows; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003217 const sp<InputWindowHandle>& oldWindowHandle = oldWindowHandles.itemAt(i);
Siarhei Vishniakou9224fba2018-08-13 18:55:08 +00003218 if (!hasWindowHandleLocked(oldWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003219#if DEBUG_FOCUS
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003220 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003221#endif
Arthur Hung3b413f22018-10-26 18:05:34 +08003222 oldWindowHandle->releaseChannel();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003223 }
3224 }
3225 } // release lock
3226
3227 // Wake up poll loop since it may need to make new input dispatching choices.
3228 mLooper->wake();
3229}
3230
3231void InputDispatcher::setFocusedApplication(
Tiger Huang721e26f2018-07-24 22:26:19 +08003232 int32_t displayId, const sp<InputApplicationHandle>& inputApplicationHandle) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003233#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003234 ALOGD("setFocusedApplication displayId=%" PRId32, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003235#endif
3236 { // acquire lock
3237 AutoMutex _l(mLock);
3238
Tiger Huang721e26f2018-07-24 22:26:19 +08003239 sp<InputApplicationHandle> oldFocusedApplicationHandle =
3240 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
Yi Kong9b14ac62018-07-17 13:48:38 -07003241 if (inputApplicationHandle != nullptr && inputApplicationHandle->updateInfo()) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003242 if (oldFocusedApplicationHandle != inputApplicationHandle) {
3243 if (oldFocusedApplicationHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003244 resetANRTimeoutsLocked();
Tiger Huang721e26f2018-07-24 22:26:19 +08003245 oldFocusedApplicationHandle->releaseInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003246 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003247 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003248 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003249 } else if (oldFocusedApplicationHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003250 resetANRTimeoutsLocked();
Tiger Huang721e26f2018-07-24 22:26:19 +08003251 oldFocusedApplicationHandle->releaseInfo();
3252 oldFocusedApplicationHandle.clear();
3253 mFocusedApplicationHandlesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003254 }
3255
3256#if DEBUG_FOCUS
3257 //logDispatchStateLocked();
3258#endif
3259 } // release lock
3260
3261 // Wake up poll loop since it may need to make new input dispatching choices.
3262 mLooper->wake();
3263}
3264
Tiger Huang721e26f2018-07-24 22:26:19 +08003265/**
3266 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
3267 * the display not specified.
3268 *
3269 * We track any unreleased events for each window. If a window loses the ability to receive the
3270 * released event, we will send a cancel event to it. So when the focused display is changed, we
3271 * cancel all the unreleased display-unspecified events for the focused window on the old focused
3272 * display. The display-specified events won't be affected.
3273 */
3274void InputDispatcher::setFocusedDisplay(int32_t displayId) {
3275#if DEBUG_FOCUS
3276 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
3277#endif
3278 { // acquire lock
3279 AutoMutex _l(mLock);
3280
3281 if (mFocusedDisplayId != displayId) {
3282 sp<InputWindowHandle> oldFocusedWindowHandle =
3283 getValueByKey(mFocusedWindowHandlesByDisplay, mFocusedDisplayId);
3284 if (oldFocusedWindowHandle != nullptr) {
Robert Carr5c8a0262018-10-03 16:30:44 -07003285 sp<InputChannel> inputChannel =
3286 getInputChannelLocked(oldFocusedWindowHandle->getToken());
Tiger Huang721e26f2018-07-24 22:26:19 +08003287 if (inputChannel != nullptr) {
3288 CancelationOptions options(
3289 CancelationOptions::CANCEL_DISPLAY_UNSPECIFIED_EVENTS,
3290 "The display which contains this window no longer has focus.");
3291 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
3292 }
3293 }
3294 mFocusedDisplayId = displayId;
3295
3296 // Sanity check
3297 sp<InputWindowHandle> newFocusedWindowHandle =
3298 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
chaviw0c06c6e2019-01-09 13:27:07 -08003299 onFocusChangedLocked(oldFocusedWindowHandle, newFocusedWindowHandle);
Robert Carrf759f162018-11-13 12:57:11 -08003300
Tiger Huang721e26f2018-07-24 22:26:19 +08003301 if (newFocusedWindowHandle == nullptr) {
3302 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
3303 if (!mFocusedWindowHandlesByDisplay.empty()) {
3304 ALOGE("But another display has a focused window:");
3305 for (auto& it : mFocusedWindowHandlesByDisplay) {
3306 const int32_t displayId = it.first;
3307 const sp<InputWindowHandle>& windowHandle = it.second;
3308 ALOGE("Display #%" PRId32 " has focused window: '%s'\n",
3309 displayId, windowHandle->getName().c_str());
3310 }
3311 }
3312 }
3313 }
3314
3315#if DEBUG_FOCUS
3316 logDispatchStateLocked();
3317#endif
3318 } // release lock
3319
3320 // Wake up poll loop since it may need to make new input dispatching choices.
3321 mLooper->wake();
3322}
3323
Michael Wrightd02c5b62014-02-10 15:10:22 -08003324void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
3325#if DEBUG_FOCUS
3326 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
3327#endif
3328
3329 bool changed;
3330 { // acquire lock
3331 AutoMutex _l(mLock);
3332
3333 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
3334 if (mDispatchFrozen && !frozen) {
3335 resetANRTimeoutsLocked();
3336 }
3337
3338 if (mDispatchEnabled && !enabled) {
3339 resetAndDropEverythingLocked("dispatcher is being disabled");
3340 }
3341
3342 mDispatchEnabled = enabled;
3343 mDispatchFrozen = frozen;
3344 changed = true;
3345 } else {
3346 changed = false;
3347 }
3348
3349#if DEBUG_FOCUS
Tiger Huang721e26f2018-07-24 22:26:19 +08003350 logDispatchStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003351#endif
3352 } // release lock
3353
3354 if (changed) {
3355 // Wake up poll loop since it may need to make new input dispatching choices.
3356 mLooper->wake();
3357 }
3358}
3359
3360void InputDispatcher::setInputFilterEnabled(bool enabled) {
3361#if DEBUG_FOCUS
3362 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
3363#endif
3364
3365 { // acquire lock
3366 AutoMutex _l(mLock);
3367
3368 if (mInputFilterEnabled == enabled) {
3369 return;
3370 }
3371
3372 mInputFilterEnabled = enabled;
3373 resetAndDropEverythingLocked("input filter is being enabled or disabled");
3374 } // release lock
3375
3376 // Wake up poll loop since there might be work to do to drop everything.
3377 mLooper->wake();
3378}
3379
chaviwfbe5d9c2018-12-26 12:23:37 -08003380bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken) {
3381 if (fromToken == toToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003382#if DEBUG_FOCUS
chaviwfbe5d9c2018-12-26 12:23:37 -08003383 ALOGD("Trivial transfer to same window.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003384#endif
chaviwfbe5d9c2018-12-26 12:23:37 -08003385 return true;
3386 }
3387
Michael Wrightd02c5b62014-02-10 15:10:22 -08003388 { // acquire lock
3389 AutoMutex _l(mLock);
3390
chaviwfbe5d9c2018-12-26 12:23:37 -08003391 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromToken);
3392 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toToken);
Yi Kong9b14ac62018-07-17 13:48:38 -07003393 if (fromWindowHandle == nullptr || toWindowHandle == nullptr) {
chaviwfbe5d9c2018-12-26 12:23:37 -08003394 ALOGW("Cannot transfer focus because from or to window not found.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003395 return false;
3396 }
chaviw4f2dd402018-12-26 15:30:27 -08003397#if DEBUG_FOCUS
3398 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
3399 fromWindowHandle->getName().c_str(), toWindowHandle->getName().c_str());
3400#endif
Michael Wrightd02c5b62014-02-10 15:10:22 -08003401 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
3402#if DEBUG_FOCUS
3403 ALOGD("Cannot transfer focus because windows are on different displays.");
3404#endif
3405 return false;
3406 }
3407
3408 bool found = false;
Jeff Brownf086ddb2014-02-11 14:28:48 -08003409 for (size_t d = 0; d < mTouchStatesByDisplay.size(); d++) {
3410 TouchState& state = mTouchStatesByDisplay.editValueAt(d);
3411 for (size_t i = 0; i < state.windows.size(); i++) {
3412 const TouchedWindow& touchedWindow = state.windows[i];
3413 if (touchedWindow.windowHandle == fromWindowHandle) {
3414 int32_t oldTargetFlags = touchedWindow.targetFlags;
3415 BitSet32 pointerIds = touchedWindow.pointerIds;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003416
Jeff Brownf086ddb2014-02-11 14:28:48 -08003417 state.windows.removeAt(i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003418
Jeff Brownf086ddb2014-02-11 14:28:48 -08003419 int32_t newTargetFlags = oldTargetFlags
3420 & (InputTarget::FLAG_FOREGROUND
3421 | InputTarget::FLAG_SPLIT | InputTarget::FLAG_DISPATCH_AS_IS);
3422 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003423
Jeff Brownf086ddb2014-02-11 14:28:48 -08003424 found = true;
3425 goto Found;
3426 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003427 }
3428 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08003429Found:
Michael Wrightd02c5b62014-02-10 15:10:22 -08003430
3431 if (! found) {
3432#if DEBUG_FOCUS
3433 ALOGD("Focus transfer failed because from window did not have focus.");
3434#endif
3435 return false;
3436 }
3437
chaviwfbe5d9c2018-12-26 12:23:37 -08003438
3439 sp<InputChannel> fromChannel = getInputChannelLocked(fromToken);
3440 sp<InputChannel> toChannel = getInputChannelLocked(toToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003441 ssize_t fromConnectionIndex = getConnectionIndexLocked(fromChannel);
3442 ssize_t toConnectionIndex = getConnectionIndexLocked(toChannel);
3443 if (fromConnectionIndex >= 0 && toConnectionIndex >= 0) {
3444 sp<Connection> fromConnection = mConnectionsByFd.valueAt(fromConnectionIndex);
3445 sp<Connection> toConnection = mConnectionsByFd.valueAt(toConnectionIndex);
3446
3447 fromConnection->inputState.copyPointerStateTo(toConnection->inputState);
3448 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
3449 "transferring touch focus from this window to another window");
3450 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
3451 }
3452
3453#if DEBUG_FOCUS
3454 logDispatchStateLocked();
3455#endif
3456 } // release lock
3457
3458 // Wake up poll loop since it may need to make new input dispatching choices.
3459 mLooper->wake();
3460 return true;
3461}
3462
3463void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
3464#if DEBUG_FOCUS
3465 ALOGD("Resetting and dropping all events (%s).", reason);
3466#endif
3467
3468 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
3469 synthesizeCancelationEventsForAllConnectionsLocked(options);
3470
3471 resetKeyRepeatLocked();
3472 releasePendingEventLocked();
3473 drainInboundQueueLocked();
3474 resetANRTimeoutsLocked();
3475
Jeff Brownf086ddb2014-02-11 14:28:48 -08003476 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003477 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07003478 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003479}
3480
3481void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003482 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003483 dumpDispatchStateLocked(dump);
3484
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003485 std::istringstream stream(dump);
3486 std::string line;
3487
3488 while (std::getline(stream, line, '\n')) {
3489 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003490 }
3491}
3492
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003493void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
3494 dump += StringPrintf(INDENT "DispatchEnabled: %d\n", mDispatchEnabled);
3495 dump += StringPrintf(INDENT "DispatchFrozen: %d\n", mDispatchFrozen);
Tiger Huang721e26f2018-07-24 22:26:19 +08003496 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003497
Tiger Huang721e26f2018-07-24 22:26:19 +08003498 if (!mFocusedApplicationHandlesByDisplay.empty()) {
3499 dump += StringPrintf(INDENT "FocusedApplications:\n");
3500 for (auto& it : mFocusedApplicationHandlesByDisplay) {
3501 const int32_t displayId = it.first;
3502 const sp<InputApplicationHandle>& applicationHandle = it.second;
3503 dump += StringPrintf(
3504 INDENT2 "displayId=%" PRId32 ", name='%s', dispatchingTimeout=%0.3fms\n",
3505 displayId,
3506 applicationHandle->getName().c_str(),
3507 applicationHandle->getDispatchingTimeout(
3508 DEFAULT_INPUT_DISPATCHING_TIMEOUT) / 1000000.0);
3509 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003510 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08003511 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003512 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003513
3514 if (!mFocusedWindowHandlesByDisplay.empty()) {
3515 dump += StringPrintf(INDENT "FocusedWindows:\n");
3516 for (auto& it : mFocusedWindowHandlesByDisplay) {
3517 const int32_t displayId = it.first;
3518 const sp<InputWindowHandle>& windowHandle = it.second;
3519 dump += StringPrintf(INDENT2 "displayId=%" PRId32 ", name='%s'\n",
3520 displayId, windowHandle->getName().c_str());
3521 }
3522 } else {
3523 dump += StringPrintf(INDENT "FocusedWindows: <none>\n");
3524 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003525
Jeff Brownf086ddb2014-02-11 14:28:48 -08003526 if (!mTouchStatesByDisplay.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003527 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Jeff Brownf086ddb2014-02-11 14:28:48 -08003528 for (size_t i = 0; i < mTouchStatesByDisplay.size(); i++) {
3529 const TouchState& state = mTouchStatesByDisplay.valueAt(i);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003530 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Jeff Brownf086ddb2014-02-11 14:28:48 -08003531 state.displayId, toString(state.down), toString(state.split),
3532 state.deviceId, state.source);
3533 if (!state.windows.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003534 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08003535 for (size_t i = 0; i < state.windows.size(); i++) {
3536 const TouchedWindow& touchedWindow = state.windows[i];
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003537 dump += StringPrintf(INDENT4 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
3538 i, touchedWindow.windowHandle->getName().c_str(),
Jeff Brownf086ddb2014-02-11 14:28:48 -08003539 touchedWindow.pointerIds.value,
3540 touchedWindow.targetFlags);
3541 }
3542 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003543 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08003544 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003545 }
3546 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003547 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003548 }
3549
Arthur Hungb92218b2018-08-14 12:00:21 +08003550 if (!mWindowHandlesByDisplay.empty()) {
3551 for (auto& it : mWindowHandlesByDisplay) {
3552 const Vector<sp<InputWindowHandle>> windowHandles = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08003553 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", it.first);
Arthur Hungb92218b2018-08-14 12:00:21 +08003554 if (!windowHandles.isEmpty()) {
3555 dump += INDENT2 "Windows:\n";
3556 for (size_t i = 0; i < windowHandles.size(); i++) {
3557 const sp<InputWindowHandle>& windowHandle = windowHandles.itemAt(i);
3558 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003559
Arthur Hungb92218b2018-08-14 12:00:21 +08003560 dump += StringPrintf(INDENT3 "%zu: name='%s', displayId=%d, "
3561 "paused=%s, hasFocus=%s, hasWallpaper=%s, "
3562 "visible=%s, canReceiveKeys=%s, flags=0x%08x, type=0x%08x, layer=%d, "
Riddle Hsu39d4aa52018-11-30 20:46:53 +08003563 "frame=[%d,%d][%d,%d], globalScale=%f, windowScale=(%f,%f), "
Arthur Hungb92218b2018-08-14 12:00:21 +08003564 "touchableRegion=",
3565 i, windowInfo->name.c_str(), windowInfo->displayId,
3566 toString(windowInfo->paused),
3567 toString(windowInfo->hasFocus),
3568 toString(windowInfo->hasWallpaper),
3569 toString(windowInfo->visible),
3570 toString(windowInfo->canReceiveKeys),
3571 windowInfo->layoutParamsFlags, windowInfo->layoutParamsType,
3572 windowInfo->layer,
3573 windowInfo->frameLeft, windowInfo->frameTop,
3574 windowInfo->frameRight, windowInfo->frameBottom,
Robert Carre07e1032018-11-26 12:55:53 -08003575 windowInfo->globalScaleFactor,
3576 windowInfo->windowXScale, windowInfo->windowYScale);
Arthur Hungb92218b2018-08-14 12:00:21 +08003577 dumpRegion(dump, windowInfo->touchableRegion);
3578 dump += StringPrintf(", inputFeatures=0x%08x", windowInfo->inputFeatures);
3579 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%0.3fms\n",
3580 windowInfo->ownerPid, windowInfo->ownerUid,
3581 windowInfo->dispatchingTimeout / 1000000.0);
3582 }
3583 } else {
3584 dump += INDENT2 "Windows: <none>\n";
3585 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003586 }
3587 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08003588 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003589 }
3590
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003591 if (!mMonitoringChannelsByDisplay.empty()) {
3592 for (auto& it : mMonitoringChannelsByDisplay) {
3593 const Vector<sp<InputChannel>>& monitoringChannels = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08003594 dump += StringPrintf(INDENT "MonitoringChannels in display %" PRId32 ":\n", it.first);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003595 const size_t numChannels = monitoringChannels.size();
3596 for (size_t i = 0; i < numChannels; i++) {
3597 const sp<InputChannel>& channel = monitoringChannels[i];
3598 dump += StringPrintf(INDENT2 "%zu: '%s'\n", i, channel->getName().c_str());
3599 }
3600 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003601 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003602 dump += INDENT "MonitoringChannels: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003603 }
3604
3605 nsecs_t currentTime = now();
3606
3607 // Dump recently dispatched or dropped events from oldest to newest.
3608 if (!mRecentQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003609 dump += StringPrintf(INDENT "RecentQueue: length=%u\n", mRecentQueue.count());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003610 for (EventEntry* entry = mRecentQueue.head; entry; entry = entry->next) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003611 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003612 entry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003613 dump += StringPrintf(", age=%0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003614 (currentTime - entry->eventTime) * 0.000001f);
3615 }
3616 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003617 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003618 }
3619
3620 // Dump event currently being dispatched.
3621 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003622 dump += INDENT "PendingEvent:\n";
3623 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003624 mPendingEvent->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003625 dump += StringPrintf(", age=%0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003626 (currentTime - mPendingEvent->eventTime) * 0.000001f);
3627 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003628 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003629 }
3630
3631 // Dump inbound events from oldest to newest.
3632 if (!mInboundQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003633 dump += StringPrintf(INDENT "InboundQueue: length=%u\n", mInboundQueue.count());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003634 for (EventEntry* entry = mInboundQueue.head; entry; entry = entry->next) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003635 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003636 entry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003637 dump += StringPrintf(", age=%0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003638 (currentTime - entry->eventTime) * 0.000001f);
3639 }
3640 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003641 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003642 }
3643
Michael Wright78f24442014-08-06 15:55:28 -07003644 if (!mReplacedKeys.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003645 dump += INDENT "ReplacedKeys:\n";
Michael Wright78f24442014-08-06 15:55:28 -07003646 for (size_t i = 0; i < mReplacedKeys.size(); i++) {
3647 const KeyReplacement& replacement = mReplacedKeys.keyAt(i);
3648 int32_t newKeyCode = mReplacedKeys.valueAt(i);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003649 dump += StringPrintf(INDENT2 "%zu: originalKeyCode=%d, deviceId=%d, newKeyCode=%d\n",
Michael Wright78f24442014-08-06 15:55:28 -07003650 i, replacement.keyCode, replacement.deviceId, newKeyCode);
3651 }
3652 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003653 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07003654 }
3655
Michael Wrightd02c5b62014-02-10 15:10:22 -08003656 if (!mConnectionsByFd.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003657 dump += INDENT "Connections:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003658 for (size_t i = 0; i < mConnectionsByFd.size(); i++) {
3659 const sp<Connection>& connection = mConnectionsByFd.valueAt(i);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003660 dump += StringPrintf(INDENT2 "%zu: channelName='%s', windowName='%s', "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003661 "status=%s, monitor=%s, inputPublisherBlocked=%s\n",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08003662 i, connection->getInputChannelName().c_str(),
3663 connection->getWindowName().c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08003664 connection->getStatusLabel(), toString(connection->monitor),
3665 toString(connection->inputPublisherBlocked));
3666
3667 if (!connection->outboundQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003668 dump += StringPrintf(INDENT3 "OutboundQueue: length=%u\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003669 connection->outboundQueue.count());
3670 for (DispatchEntry* entry = connection->outboundQueue.head; entry;
3671 entry = entry->next) {
3672 dump.append(INDENT4);
3673 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003674 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, age=%0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003675 entry->targetFlags, entry->resolvedAction,
3676 (currentTime - entry->eventEntry->eventTime) * 0.000001f);
3677 }
3678 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003679 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003680 }
3681
3682 if (!connection->waitQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003683 dump += StringPrintf(INDENT3 "WaitQueue: length=%u\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003684 connection->waitQueue.count());
3685 for (DispatchEntry* entry = connection->waitQueue.head; entry;
3686 entry = entry->next) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003687 dump += INDENT4;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003688 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003689 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003690 "age=%0.1fms, wait=%0.1fms\n",
3691 entry->targetFlags, entry->resolvedAction,
3692 (currentTime - entry->eventEntry->eventTime) * 0.000001f,
3693 (currentTime - entry->deliveryTime) * 0.000001f);
3694 }
3695 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003696 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003697 }
3698 }
3699 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003700 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003701 }
3702
3703 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003704 dump += StringPrintf(INDENT "AppSwitch: pending, due in %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003705 (mAppSwitchDueTime - now()) / 1000000.0);
3706 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003707 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003708 }
3709
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003710 dump += INDENT "Configuration:\n";
3711 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003712 mConfig.keyRepeatDelay * 0.000001f);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003713 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003714 mConfig.keyRepeatTimeout * 0.000001f);
3715}
3716
Robert Carr803535b2018-08-02 16:38:15 -07003717status_t InputDispatcher::registerInputChannel(const sp<InputChannel>& inputChannel, int32_t displayId) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003718#if DEBUG_REGISTRATION
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003719 ALOGD("channel '%s' ~ registerInputChannel - displayId=%" PRId32,
3720 inputChannel->getName().c_str(), displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003721#endif
3722
3723 { // acquire lock
3724 AutoMutex _l(mLock);
3725
Robert Carr4e670e52018-08-15 13:26:12 -07003726 // If InputWindowHandle is null and displayId is not ADISPLAY_ID_NONE,
3727 // treat inputChannel as monitor channel for displayId.
3728 bool monitor = inputChannel->getToken() == nullptr && displayId != ADISPLAY_ID_NONE;
3729 if (monitor) {
3730 inputChannel->setToken(new BBinder());
3731 }
3732
Michael Wrightd02c5b62014-02-10 15:10:22 -08003733 if (getConnectionIndexLocked(inputChannel) >= 0) {
3734 ALOGW("Attempted to register already registered input channel '%s'",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003735 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003736 return BAD_VALUE;
3737 }
3738
Robert Carr803535b2018-08-02 16:38:15 -07003739 sp<Connection> connection = new Connection(inputChannel, monitor);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003740
3741 int fd = inputChannel->getFd();
3742 mConnectionsByFd.add(fd, connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07003743 mInputChannelsByToken[inputChannel->getToken()] = inputChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003744
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003745 // Store monitor channel by displayId.
Michael Wrightd02c5b62014-02-10 15:10:22 -08003746 if (monitor) {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003747 Vector<sp<InputChannel>>& monitoringChannels =
3748 mMonitoringChannelsByDisplay[displayId];
3749 monitoringChannels.push(inputChannel);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003750 }
3751
3752 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
3753 } // release lock
3754
3755 // Wake the looper because some connections have changed.
3756 mLooper->wake();
3757 return OK;
3758}
3759
3760status_t InputDispatcher::unregisterInputChannel(const sp<InputChannel>& inputChannel) {
3761#if DEBUG_REGISTRATION
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003762 ALOGD("channel '%s' ~ unregisterInputChannel", inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003763#endif
3764
3765 { // acquire lock
3766 AutoMutex _l(mLock);
3767
3768 status_t status = unregisterInputChannelLocked(inputChannel, false /*notify*/);
3769 if (status) {
3770 return status;
3771 }
3772 } // release lock
3773
3774 // Wake the poll loop because removing the connection may have changed the current
3775 // synchronization state.
3776 mLooper->wake();
3777 return OK;
3778}
3779
3780status_t InputDispatcher::unregisterInputChannelLocked(const sp<InputChannel>& inputChannel,
3781 bool notify) {
3782 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
3783 if (connectionIndex < 0) {
3784 ALOGW("Attempted to unregister already unregistered input channel '%s'",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003785 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003786 return BAD_VALUE;
3787 }
3788
3789 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
3790 mConnectionsByFd.removeItemsAt(connectionIndex);
3791
Robert Carr5c8a0262018-10-03 16:30:44 -07003792 mInputChannelsByToken.erase(inputChannel->getToken());
3793
Michael Wrightd02c5b62014-02-10 15:10:22 -08003794 if (connection->monitor) {
3795 removeMonitorChannelLocked(inputChannel);
3796 }
3797
3798 mLooper->removeFd(inputChannel->getFd());
3799
3800 nsecs_t currentTime = now();
3801 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
3802
3803 connection->status = Connection::STATUS_ZOMBIE;
3804 return OK;
3805}
3806
3807void InputDispatcher::removeMonitorChannelLocked(const sp<InputChannel>& inputChannel) {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003808 for (auto it = mMonitoringChannelsByDisplay.begin();
3809 it != mMonitoringChannelsByDisplay.end(); ) {
3810 Vector<sp<InputChannel>>& monitoringChannels = it->second;
3811 const size_t numChannels = monitoringChannels.size();
3812 for (size_t i = 0; i < numChannels; i++) {
3813 if (monitoringChannels[i] == inputChannel) {
3814 monitoringChannels.removeAt(i);
3815 break;
3816 }
3817 }
3818 if (monitoringChannels.empty()) {
3819 it = mMonitoringChannelsByDisplay.erase(it);
3820 } else {
3821 ++it;
3822 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003823 }
3824}
3825
3826ssize_t InputDispatcher::getConnectionIndexLocked(const sp<InputChannel>& inputChannel) {
Robert Carr4e670e52018-08-15 13:26:12 -07003827 if (inputChannel == nullptr) {
Arthur Hung3b413f22018-10-26 18:05:34 +08003828 return -1;
3829 }
3830
Robert Carr4e670e52018-08-15 13:26:12 -07003831 for (size_t i = 0; i < mConnectionsByFd.size(); i++) {
3832 sp<Connection> connection = mConnectionsByFd.valueAt(i);
3833 if (connection->inputChannel->getToken() == inputChannel->getToken()) {
3834 return i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003835 }
3836 }
Robert Carr4e670e52018-08-15 13:26:12 -07003837
Michael Wrightd02c5b62014-02-10 15:10:22 -08003838 return -1;
3839}
3840
3841void InputDispatcher::onDispatchCycleFinishedLocked(
3842 nsecs_t currentTime, const sp<Connection>& connection, uint32_t seq, bool handled) {
3843 CommandEntry* commandEntry = postCommandLocked(
3844 & InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
3845 commandEntry->connection = connection;
3846 commandEntry->eventTime = currentTime;
3847 commandEntry->seq = seq;
3848 commandEntry->handled = handled;
3849}
3850
3851void InputDispatcher::onDispatchCycleBrokenLocked(
3852 nsecs_t currentTime, const sp<Connection>& connection) {
3853 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08003854 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003855
3856 CommandEntry* commandEntry = postCommandLocked(
3857 & InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
3858 commandEntry->connection = connection;
3859}
3860
chaviw0c06c6e2019-01-09 13:27:07 -08003861void InputDispatcher::onFocusChangedLocked(const sp<InputWindowHandle>& oldFocus,
3862 const sp<InputWindowHandle>& newFocus) {
3863 sp<IBinder> oldToken = oldFocus != nullptr ? oldFocus->getToken() : nullptr;
3864 sp<IBinder> newToken = newFocus != nullptr ? newFocus->getToken() : nullptr;
Robert Carrf759f162018-11-13 12:57:11 -08003865 CommandEntry* commandEntry = postCommandLocked(
3866 & InputDispatcher::doNotifyFocusChangedLockedInterruptible);
chaviw0c06c6e2019-01-09 13:27:07 -08003867 commandEntry->oldToken = oldToken;
3868 commandEntry->newToken = newToken;
Robert Carrf759f162018-11-13 12:57:11 -08003869}
3870
Michael Wrightd02c5b62014-02-10 15:10:22 -08003871void InputDispatcher::onANRLocked(
3872 nsecs_t currentTime, const sp<InputApplicationHandle>& applicationHandle,
3873 const sp<InputWindowHandle>& windowHandle,
3874 nsecs_t eventTime, nsecs_t waitStartTime, const char* reason) {
3875 float dispatchLatency = (currentTime - eventTime) * 0.000001f;
3876 float waitDuration = (currentTime - waitStartTime) * 0.000001f;
3877 ALOGI("Application is not responding: %s. "
3878 "It has been %0.1fms since event, %0.1fms since wait started. Reason: %s",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003879 getApplicationWindowLabelLocked(applicationHandle, windowHandle).c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08003880 dispatchLatency, waitDuration, reason);
3881
3882 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07003883 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003884 struct tm tm;
3885 localtime_r(&t, &tm);
3886 char timestr[64];
3887 strftime(timestr, sizeof(timestr), "%F %T", &tm);
3888 mLastANRState.clear();
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003889 mLastANRState += INDENT "ANR:\n";
3890 mLastANRState += StringPrintf(INDENT2 "Time: %s\n", timestr);
3891 mLastANRState += StringPrintf(INDENT2 "Window: %s\n",
3892 getApplicationWindowLabelLocked(applicationHandle, windowHandle).c_str());
3893 mLastANRState += StringPrintf(INDENT2 "DispatchLatency: %0.1fms\n", dispatchLatency);
3894 mLastANRState += StringPrintf(INDENT2 "WaitDuration: %0.1fms\n", waitDuration);
3895 mLastANRState += StringPrintf(INDENT2 "Reason: %s\n", reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003896 dumpDispatchStateLocked(mLastANRState);
3897
3898 CommandEntry* commandEntry = postCommandLocked(
3899 & InputDispatcher::doNotifyANRLockedInterruptible);
3900 commandEntry->inputApplicationHandle = applicationHandle;
Robert Carr5c8a0262018-10-03 16:30:44 -07003901 commandEntry->inputChannel = windowHandle != nullptr ?
3902 getInputChannelLocked(windowHandle->getToken()) : nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003903 commandEntry->reason = reason;
3904}
3905
3906void InputDispatcher::doNotifyConfigurationChangedInterruptible(
3907 CommandEntry* commandEntry) {
3908 mLock.unlock();
3909
3910 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
3911
3912 mLock.lock();
3913}
3914
3915void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(
3916 CommandEntry* commandEntry) {
3917 sp<Connection> connection = commandEntry->connection;
3918
3919 if (connection->status != Connection::STATUS_ZOMBIE) {
3920 mLock.unlock();
3921
Robert Carr803535b2018-08-02 16:38:15 -07003922 mPolicy->notifyInputChannelBroken(connection->inputChannel->getToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003923
3924 mLock.lock();
3925 }
3926}
3927
Robert Carrf759f162018-11-13 12:57:11 -08003928void InputDispatcher::doNotifyFocusChangedLockedInterruptible(
3929 CommandEntry* commandEntry) {
chaviw0c06c6e2019-01-09 13:27:07 -08003930 sp<IBinder> oldToken = commandEntry->oldToken;
3931 sp<IBinder> newToken = commandEntry->newToken;
Robert Carrf759f162018-11-13 12:57:11 -08003932 mLock.unlock();
chaviw0c06c6e2019-01-09 13:27:07 -08003933 mPolicy->notifyFocusChanged(oldToken, newToken);
Robert Carrf759f162018-11-13 12:57:11 -08003934 mLock.lock();
3935}
3936
Michael Wrightd02c5b62014-02-10 15:10:22 -08003937void InputDispatcher::doNotifyANRLockedInterruptible(
3938 CommandEntry* commandEntry) {
3939 mLock.unlock();
3940
3941 nsecs_t newTimeout = mPolicy->notifyANR(
Robert Carr803535b2018-08-02 16:38:15 -07003942 commandEntry->inputApplicationHandle,
3943 commandEntry->inputChannel ? commandEntry->inputChannel->getToken() : nullptr,
Michael Wrightd02c5b62014-02-10 15:10:22 -08003944 commandEntry->reason);
3945
3946 mLock.lock();
3947
3948 resumeAfterTargetsNotReadyTimeoutLocked(newTimeout,
Robert Carr803535b2018-08-02 16:38:15 -07003949 commandEntry->inputChannel);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003950}
3951
3952void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
3953 CommandEntry* commandEntry) {
3954 KeyEntry* entry = commandEntry->keyEntry;
3955
3956 KeyEvent event;
3957 initializeKeyEvent(&event, entry);
3958
3959 mLock.unlock();
3960
Michael Wright2b3c3302018-03-02 17:19:13 +00003961 android::base::Timer t;
Robert Carr803535b2018-08-02 16:38:15 -07003962 sp<IBinder> token = commandEntry->inputChannel != nullptr ?
3963 commandEntry->inputChannel->getToken() : nullptr;
3964 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(token,
Michael Wrightd02c5b62014-02-10 15:10:22 -08003965 &event, entry->policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003966 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3967 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
3968 std::to_string(t.duration().count()).c_str());
3969 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003970
3971 mLock.lock();
3972
3973 if (delay < 0) {
3974 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
3975 } else if (!delay) {
3976 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
3977 } else {
3978 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
3979 entry->interceptKeyWakeupTime = now() + delay;
3980 }
3981 entry->release();
3982}
3983
3984void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(
3985 CommandEntry* commandEntry) {
3986 sp<Connection> connection = commandEntry->connection;
3987 nsecs_t finishTime = commandEntry->eventTime;
3988 uint32_t seq = commandEntry->seq;
3989 bool handled = commandEntry->handled;
3990
3991 // Handle post-event policy actions.
3992 DispatchEntry* dispatchEntry = connection->findWaitQueueEntry(seq);
3993 if (dispatchEntry) {
3994 nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
3995 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003996 std::string msg =
3997 StringPrintf("Window '%s' spent %0.1fms processing the last input event: ",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08003998 connection->getWindowName().c_str(), eventDuration * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003999 dispatchEntry->eventEntry->appendDescription(msg);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004000 ALOGI("%s", msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004001 }
4002
4003 bool restartEvent;
4004 if (dispatchEntry->eventEntry->type == EventEntry::TYPE_KEY) {
4005 KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry);
4006 restartEvent = afterKeyEventLockedInterruptible(connection,
4007 dispatchEntry, keyEntry, handled);
4008 } else if (dispatchEntry->eventEntry->type == EventEntry::TYPE_MOTION) {
4009 MotionEntry* motionEntry = static_cast<MotionEntry*>(dispatchEntry->eventEntry);
4010 restartEvent = afterMotionEventLockedInterruptible(connection,
4011 dispatchEntry, motionEntry, handled);
4012 } else {
4013 restartEvent = false;
4014 }
4015
4016 // Dequeue the event and start the next cycle.
4017 // Note that because the lock might have been released, it is possible that the
4018 // contents of the wait queue to have been drained, so we need to double-check
4019 // a few things.
4020 if (dispatchEntry == connection->findWaitQueueEntry(seq)) {
4021 connection->waitQueue.dequeue(dispatchEntry);
4022 traceWaitQueueLengthLocked(connection);
4023 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
4024 connection->outboundQueue.enqueueAtHead(dispatchEntry);
4025 traceOutboundQueueLengthLocked(connection);
4026 } else {
4027 releaseDispatchEntryLocked(dispatchEntry);
4028 }
4029 }
4030
4031 // Start the next dispatch cycle for this connection.
4032 startDispatchCycleLocked(now(), connection);
4033 }
4034}
4035
4036bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
4037 DispatchEntry* dispatchEntry, KeyEntry* keyEntry, bool handled) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004038 if (keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004039 if (!handled) {
4040 // Report the key as unhandled, since the fallback was not handled.
4041 mReporter->reportUnhandledKey(keyEntry->sequenceNum);
4042 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004043 return false;
4044 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004045
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004046 // Get the fallback key state.
4047 // Clear it out after dispatching the UP.
4048 int32_t originalKeyCode = keyEntry->keyCode;
4049 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
4050 if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
4051 connection->inputState.removeFallbackKey(originalKeyCode);
4052 }
4053
4054 if (handled || !dispatchEntry->hasForegroundTarget()) {
4055 // If the application handles the original key for which we previously
4056 // generated a fallback or if the window is not a foreground window,
4057 // then cancel the associated fallback key, if any.
4058 if (fallbackKeyCode != -1) {
4059 // Dispatch the unhandled key to the policy with the cancel flag.
Michael Wrightd02c5b62014-02-10 15:10:22 -08004060#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004061 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
Michael Wrightd02c5b62014-02-10 15:10:22 -08004062 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4063 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
4064 keyEntry->policyFlags);
4065#endif
4066 KeyEvent event;
4067 initializeKeyEvent(&event, keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004068 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004069
4070 mLock.unlock();
4071
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004072 mPolicy->dispatchUnhandledKey(connection->inputChannel->getToken(),
4073 &event, keyEntry->policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004074
4075 mLock.lock();
4076
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004077 // Cancel the fallback key.
4078 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004079 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004080 "application handled the original non-fallback key "
4081 "or is no longer a foreground target, "
4082 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004083 options.keyCode = fallbackKeyCode;
4084 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004085 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004086 connection->inputState.removeFallbackKey(originalKeyCode);
4087 }
4088 } else {
4089 // If the application did not handle a non-fallback key, first check
4090 // that we are in a good state to perform unhandled key event processing
4091 // Then ask the policy what to do with it.
4092 bool initialDown = keyEntry->action == AKEY_EVENT_ACTION_DOWN
4093 && keyEntry->repeatCount == 0;
4094 if (fallbackKeyCode == -1 && !initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004095#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004096 ALOGD("Unhandled key event: Skipping unhandled key event processing "
4097 "since this is not an initial down. "
4098 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4099 originalKeyCode, keyEntry->action, keyEntry->repeatCount,
4100 keyEntry->policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004101#endif
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004102 return false;
4103 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004104
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004105 // Dispatch the unhandled key to the policy.
4106#if DEBUG_OUTBOUND_EVENT_DETAILS
4107 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
4108 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4109 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
4110 keyEntry->policyFlags);
4111#endif
4112 KeyEvent event;
4113 initializeKeyEvent(&event, keyEntry);
4114
4115 mLock.unlock();
4116
4117 bool fallback = mPolicy->dispatchUnhandledKey(connection->inputChannel->getToken(),
4118 &event, keyEntry->policyFlags, &event);
4119
4120 mLock.lock();
4121
4122 if (connection->status != Connection::STATUS_NORMAL) {
4123 connection->inputState.removeFallbackKey(originalKeyCode);
4124 return false;
4125 }
4126
4127 // Latch the fallback keycode for this key on an initial down.
4128 // The fallback keycode cannot change at any other point in the lifecycle.
4129 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004130 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004131 fallbackKeyCode = event.getKeyCode();
4132 } else {
4133 fallbackKeyCode = AKEYCODE_UNKNOWN;
4134 }
4135 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
4136 }
4137
4138 ALOG_ASSERT(fallbackKeyCode != -1);
4139
4140 // Cancel the fallback key if the policy decides not to send it anymore.
4141 // We will continue to dispatch the key to the policy but we will no
4142 // longer dispatch a fallback key to the application.
4143 if (fallbackKeyCode != AKEYCODE_UNKNOWN
4144 && (!fallback || fallbackKeyCode != event.getKeyCode())) {
4145#if DEBUG_OUTBOUND_EVENT_DETAILS
4146 if (fallback) {
4147 ALOGD("Unhandled key event: Policy requested to send key %d"
4148 "as a fallback for %d, but on the DOWN it had requested "
4149 "to send %d instead. Fallback canceled.",
4150 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
4151 } else {
4152 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
4153 "but on the DOWN it had requested to send %d. "
4154 "Fallback canceled.",
4155 originalKeyCode, fallbackKeyCode);
4156 }
4157#endif
4158
4159 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
4160 "canceling fallback, policy no longer desires it");
4161 options.keyCode = fallbackKeyCode;
4162 synthesizeCancelationEventsForConnectionLocked(connection, options);
4163
4164 fallback = false;
4165 fallbackKeyCode = AKEYCODE_UNKNOWN;
4166 if (keyEntry->action != AKEY_EVENT_ACTION_UP) {
4167 connection->inputState.setFallbackKey(originalKeyCode,
4168 fallbackKeyCode);
4169 }
4170 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004171
4172#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004173 {
4174 std::string msg;
4175 const KeyedVector<int32_t, int32_t>& fallbackKeys =
4176 connection->inputState.getFallbackKeys();
4177 for (size_t i = 0; i < fallbackKeys.size(); i++) {
4178 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i),
4179 fallbackKeys.valueAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004180 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004181 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
4182 fallbackKeys.size(), msg.c_str());
4183 }
4184#endif
4185
4186 if (fallback) {
4187 // Restart the dispatch cycle using the fallback key.
4188 keyEntry->eventTime = event.getEventTime();
4189 keyEntry->deviceId = event.getDeviceId();
4190 keyEntry->source = event.getSource();
4191 keyEntry->displayId = event.getDisplayId();
4192 keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
4193 keyEntry->keyCode = fallbackKeyCode;
4194 keyEntry->scanCode = event.getScanCode();
4195 keyEntry->metaState = event.getMetaState();
4196 keyEntry->repeatCount = event.getRepeatCount();
4197 keyEntry->downTime = event.getDownTime();
4198 keyEntry->syntheticRepeat = false;
4199
4200#if DEBUG_OUTBOUND_EVENT_DETAILS
4201 ALOGD("Unhandled key event: Dispatching fallback key. "
4202 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
4203 originalKeyCode, fallbackKeyCode, keyEntry->metaState);
4204#endif
4205 return true; // restart the event
4206 } else {
4207#if DEBUG_OUTBOUND_EVENT_DETAILS
4208 ALOGD("Unhandled key event: No fallback key.");
4209#endif
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004210
4211 // Report the key as unhandled, since there is no fallback key.
4212 mReporter->reportUnhandledKey(keyEntry->sequenceNum);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004213 }
4214 }
4215 return false;
4216}
4217
4218bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
4219 DispatchEntry* dispatchEntry, MotionEntry* motionEntry, bool handled) {
4220 return false;
4221}
4222
4223void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
4224 mLock.unlock();
4225
4226 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
4227
4228 mLock.lock();
4229}
4230
4231void InputDispatcher::initializeKeyEvent(KeyEvent* event, const KeyEntry* entry) {
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004232 event->initialize(entry->deviceId, entry->source, entry->displayId, entry->action, entry->flags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004233 entry->keyCode, entry->scanCode, entry->metaState, entry->repeatCount,
4234 entry->downTime, entry->eventTime);
4235}
4236
4237void InputDispatcher::updateDispatchStatisticsLocked(nsecs_t currentTime, const EventEntry* entry,
4238 int32_t injectionResult, nsecs_t timeSpentWaitingForApplication) {
4239 // TODO Write some statistics about how long we spend waiting.
4240}
4241
4242void InputDispatcher::traceInboundQueueLengthLocked() {
4243 if (ATRACE_ENABLED()) {
4244 ATRACE_INT("iq", mInboundQueue.count());
4245 }
4246}
4247
4248void InputDispatcher::traceOutboundQueueLengthLocked(const sp<Connection>& connection) {
4249 if (ATRACE_ENABLED()) {
4250 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004251 snprintf(counterName, sizeof(counterName), "oq:%s", connection->getWindowName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004252 ATRACE_INT(counterName, connection->outboundQueue.count());
4253 }
4254}
4255
4256void InputDispatcher::traceWaitQueueLengthLocked(const sp<Connection>& connection) {
4257 if (ATRACE_ENABLED()) {
4258 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004259 snprintf(counterName, sizeof(counterName), "wq:%s", connection->getWindowName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004260 ATRACE_INT(counterName, connection->waitQueue.count());
4261 }
4262}
4263
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004264void InputDispatcher::dump(std::string& dump) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004265 AutoMutex _l(mLock);
4266
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004267 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004268 dumpDispatchStateLocked(dump);
4269
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004270 if (!mLastANRState.empty()) {
4271 dump += "\nInput Dispatcher State at time of last ANR:\n";
4272 dump += mLastANRState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004273 }
4274}
4275
4276void InputDispatcher::monitor() {
4277 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
4278 mLock.lock();
4279 mLooper->wake();
4280 mDispatcherIsAliveCondition.wait(mLock);
4281 mLock.unlock();
4282}
4283
4284
Michael Wrightd02c5b62014-02-10 15:10:22 -08004285// --- InputDispatcher::InjectionState ---
4286
4287InputDispatcher::InjectionState::InjectionState(int32_t injectorPid, int32_t injectorUid) :
4288 refCount(1),
4289 injectorPid(injectorPid), injectorUid(injectorUid),
4290 injectionResult(INPUT_EVENT_INJECTION_PENDING), injectionIsAsync(false),
4291 pendingForegroundDispatches(0) {
4292}
4293
4294InputDispatcher::InjectionState::~InjectionState() {
4295}
4296
4297void InputDispatcher::InjectionState::release() {
4298 refCount -= 1;
4299 if (refCount == 0) {
4300 delete this;
4301 } else {
4302 ALOG_ASSERT(refCount > 0);
4303 }
4304}
4305
4306
4307// --- InputDispatcher::EventEntry ---
4308
Prabir Pradhan42611e02018-11-27 14:04:02 -08004309InputDispatcher::EventEntry::EventEntry(uint32_t sequenceNum, int32_t type,
4310 nsecs_t eventTime, uint32_t policyFlags) :
4311 sequenceNum(sequenceNum), refCount(1), type(type), eventTime(eventTime),
4312 policyFlags(policyFlags), injectionState(nullptr), dispatchInProgress(false) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004313}
4314
4315InputDispatcher::EventEntry::~EventEntry() {
4316 releaseInjectionState();
4317}
4318
4319void InputDispatcher::EventEntry::release() {
4320 refCount -= 1;
4321 if (refCount == 0) {
4322 delete this;
4323 } else {
4324 ALOG_ASSERT(refCount > 0);
4325 }
4326}
4327
4328void InputDispatcher::EventEntry::releaseInjectionState() {
4329 if (injectionState) {
4330 injectionState->release();
Yi Kong9b14ac62018-07-17 13:48:38 -07004331 injectionState = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004332 }
4333}
4334
4335
4336// --- InputDispatcher::ConfigurationChangedEntry ---
4337
Prabir Pradhan42611e02018-11-27 14:04:02 -08004338InputDispatcher::ConfigurationChangedEntry::ConfigurationChangedEntry(
4339 uint32_t sequenceNum, nsecs_t eventTime) :
4340 EventEntry(sequenceNum, TYPE_CONFIGURATION_CHANGED, eventTime, 0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004341}
4342
4343InputDispatcher::ConfigurationChangedEntry::~ConfigurationChangedEntry() {
4344}
4345
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004346void InputDispatcher::ConfigurationChangedEntry::appendDescription(std::string& msg) const {
4347 msg += StringPrintf("ConfigurationChangedEvent(), policyFlags=0x%08x", policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004348}
4349
4350
4351// --- InputDispatcher::DeviceResetEntry ---
4352
Prabir Pradhan42611e02018-11-27 14:04:02 -08004353InputDispatcher::DeviceResetEntry::DeviceResetEntry(
4354 uint32_t sequenceNum, nsecs_t eventTime, int32_t deviceId) :
4355 EventEntry(sequenceNum, TYPE_DEVICE_RESET, eventTime, 0),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004356 deviceId(deviceId) {
4357}
4358
4359InputDispatcher::DeviceResetEntry::~DeviceResetEntry() {
4360}
4361
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004362void InputDispatcher::DeviceResetEntry::appendDescription(std::string& msg) const {
4363 msg += StringPrintf("DeviceResetEvent(deviceId=%d), policyFlags=0x%08x",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004364 deviceId, policyFlags);
4365}
4366
4367
4368// --- InputDispatcher::KeyEntry ---
4369
Prabir Pradhan42611e02018-11-27 14:04:02 -08004370InputDispatcher::KeyEntry::KeyEntry(uint32_t sequenceNum, nsecs_t eventTime,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004371 int32_t deviceId, uint32_t source, int32_t displayId, uint32_t policyFlags, int32_t action,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004372 int32_t flags, int32_t keyCode, int32_t scanCode, int32_t metaState,
4373 int32_t repeatCount, nsecs_t downTime) :
Prabir Pradhan42611e02018-11-27 14:04:02 -08004374 EventEntry(sequenceNum, TYPE_KEY, eventTime, policyFlags),
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004375 deviceId(deviceId), source(source), displayId(displayId), action(action), flags(flags),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004376 keyCode(keyCode), scanCode(scanCode), metaState(metaState),
4377 repeatCount(repeatCount), downTime(downTime),
4378 syntheticRepeat(false), interceptKeyResult(KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN),
4379 interceptKeyWakeupTime(0) {
4380}
4381
4382InputDispatcher::KeyEntry::~KeyEntry() {
4383}
4384
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004385void InputDispatcher::KeyEntry::appendDescription(std::string& msg) const {
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004386 msg += StringPrintf("KeyEvent(deviceId=%d, source=0x%08x, displayId=%" PRId32 ", action=%s, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08004387 "flags=0x%08x, keyCode=%d, scanCode=%d, metaState=0x%08x, "
4388 "repeatCount=%d), policyFlags=0x%08x",
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004389 deviceId, source, displayId, keyActionToString(action).c_str(), flags, keyCode,
Siarhei Vishniakoub48188a2018-03-01 20:55:47 -08004390 scanCode, metaState, repeatCount, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004391}
4392
4393void InputDispatcher::KeyEntry::recycle() {
4394 releaseInjectionState();
4395
4396 dispatchInProgress = false;
4397 syntheticRepeat = false;
4398 interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
4399 interceptKeyWakeupTime = 0;
4400}
4401
4402
4403// --- InputDispatcher::MotionEntry ---
4404
Prabir Pradhan42611e02018-11-27 14:04:02 -08004405InputDispatcher::MotionEntry::MotionEntry(uint32_t sequenceNum, nsecs_t eventTime, int32_t deviceId,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004406 uint32_t source, int32_t displayId, uint32_t policyFlags, int32_t action,
4407 int32_t actionButton,
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08004408 int32_t flags, int32_t metaState, int32_t buttonState, MotionClassification classification,
4409 int32_t edgeFlags, float xPrecision, float yPrecision, nsecs_t downTime,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004410 uint32_t pointerCount,
Jeff Brownf086ddb2014-02-11 14:28:48 -08004411 const PointerProperties* pointerProperties, const PointerCoords* pointerCoords,
4412 float xOffset, float yOffset) :
Prabir Pradhan42611e02018-11-27 14:04:02 -08004413 EventEntry(sequenceNum, TYPE_MOTION, eventTime, policyFlags),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004414 eventTime(eventTime),
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004415 deviceId(deviceId), source(source), displayId(displayId), action(action),
4416 actionButton(actionButton), flags(flags), metaState(metaState), buttonState(buttonState),
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08004417 classification(classification), edgeFlags(edgeFlags),
4418 xPrecision(xPrecision), yPrecision(yPrecision),
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004419 downTime(downTime), pointerCount(pointerCount) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004420 for (uint32_t i = 0; i < pointerCount; i++) {
4421 this->pointerProperties[i].copyFrom(pointerProperties[i]);
4422 this->pointerCoords[i].copyFrom(pointerCoords[i]);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004423 if (xOffset || yOffset) {
4424 this->pointerCoords[i].applyOffset(xOffset, yOffset);
4425 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004426 }
4427}
4428
4429InputDispatcher::MotionEntry::~MotionEntry() {
4430}
4431
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004432void InputDispatcher::MotionEntry::appendDescription(std::string& msg) const {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004433 msg += StringPrintf("MotionEvent(deviceId=%d, source=0x%08x, displayId=%" PRId32
Siarhei Vishniakoub48188a2018-03-01 20:55:47 -08004434 ", action=%s, actionButton=0x%08x, flags=0x%08x, metaState=0x%08x, buttonState=0x%08x, "
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08004435 "classification=%s, edgeFlags=0x%08x, xPrecision=%.1f, yPrecision=%.1f, pointers=[",
Siarhei Vishniakoub48188a2018-03-01 20:55:47 -08004436 deviceId, source, displayId, motionActionToString(action).c_str(), actionButton, flags,
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08004437 metaState, buttonState, motionClassificationToString(classification), edgeFlags,
4438 xPrecision, yPrecision);
Siarhei Vishniakoub48188a2018-03-01 20:55:47 -08004439
Michael Wrightd02c5b62014-02-10 15:10:22 -08004440 for (uint32_t i = 0; i < pointerCount; i++) {
4441 if (i) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004442 msg += ", ";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004443 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004444 msg += StringPrintf("%d: (%.1f, %.1f)", pointerProperties[i].id,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004445 pointerCoords[i].getX(), pointerCoords[i].getY());
4446 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004447 msg += StringPrintf("]), policyFlags=0x%08x", policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004448}
4449
4450
4451// --- InputDispatcher::DispatchEntry ---
4452
4453volatile int32_t InputDispatcher::DispatchEntry::sNextSeqAtomic;
4454
4455InputDispatcher::DispatchEntry::DispatchEntry(EventEntry* eventEntry,
Robert Carre07e1032018-11-26 12:55:53 -08004456 int32_t targetFlags, float xOffset, float yOffset, float globalScaleFactor,
4457 float windowXScale, float windowYScale) :
Michael Wrightd02c5b62014-02-10 15:10:22 -08004458 seq(nextSeq()),
4459 eventEntry(eventEntry), targetFlags(targetFlags),
Robert Carre07e1032018-11-26 12:55:53 -08004460 xOffset(xOffset), yOffset(yOffset), globalScaleFactor(globalScaleFactor),
4461 windowXScale(windowXScale), windowYScale(windowYScale),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004462 deliveryTime(0), resolvedAction(0), resolvedFlags(0) {
4463 eventEntry->refCount += 1;
4464}
4465
4466InputDispatcher::DispatchEntry::~DispatchEntry() {
4467 eventEntry->release();
4468}
4469
4470uint32_t InputDispatcher::DispatchEntry::nextSeq() {
4471 // Sequence number 0 is reserved and will never be returned.
4472 uint32_t seq;
4473 do {
4474 seq = android_atomic_inc(&sNextSeqAtomic);
4475 } while (!seq);
4476 return seq;
4477}
4478
4479
4480// --- InputDispatcher::InputState ---
4481
4482InputDispatcher::InputState::InputState() {
4483}
4484
4485InputDispatcher::InputState::~InputState() {
4486}
4487
4488bool InputDispatcher::InputState::isNeutral() const {
4489 return mKeyMementos.isEmpty() && mMotionMementos.isEmpty();
4490}
4491
4492bool InputDispatcher::InputState::isHovering(int32_t deviceId, uint32_t source,
4493 int32_t displayId) const {
4494 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4495 const MotionMemento& memento = mMotionMementos.itemAt(i);
4496 if (memento.deviceId == deviceId
4497 && memento.source == source
4498 && memento.displayId == displayId
4499 && memento.hovering) {
4500 return true;
4501 }
4502 }
4503 return false;
4504}
4505
4506bool InputDispatcher::InputState::trackKey(const KeyEntry* entry,
4507 int32_t action, int32_t flags) {
4508 switch (action) {
4509 case AKEY_EVENT_ACTION_UP: {
4510 if (entry->flags & AKEY_EVENT_FLAG_FALLBACK) {
4511 for (size_t i = 0; i < mFallbackKeys.size(); ) {
4512 if (mFallbackKeys.valueAt(i) == entry->keyCode) {
4513 mFallbackKeys.removeItemsAt(i);
4514 } else {
4515 i += 1;
4516 }
4517 }
4518 }
4519 ssize_t index = findKeyMemento(entry);
4520 if (index >= 0) {
4521 mKeyMementos.removeAt(index);
4522 return true;
4523 }
4524 /* FIXME: We can't just drop the key up event because that prevents creating
4525 * popup windows that are automatically shown when a key is held and then
4526 * dismissed when the key is released. The problem is that the popup will
4527 * not have received the original key down, so the key up will be considered
4528 * to be inconsistent with its observed state. We could perhaps handle this
4529 * by synthesizing a key down but that will cause other problems.
4530 *
4531 * So for now, allow inconsistent key up events to be dispatched.
4532 *
4533#if DEBUG_OUTBOUND_EVENT_DETAILS
4534 ALOGD("Dropping inconsistent key up event: deviceId=%d, source=%08x, "
4535 "keyCode=%d, scanCode=%d",
4536 entry->deviceId, entry->source, entry->keyCode, entry->scanCode);
4537#endif
4538 return false;
4539 */
4540 return true;
4541 }
4542
4543 case AKEY_EVENT_ACTION_DOWN: {
4544 ssize_t index = findKeyMemento(entry);
4545 if (index >= 0) {
4546 mKeyMementos.removeAt(index);
4547 }
4548 addKeyMemento(entry, flags);
4549 return true;
4550 }
4551
4552 default:
4553 return true;
4554 }
4555}
4556
4557bool InputDispatcher::InputState::trackMotion(const MotionEntry* entry,
4558 int32_t action, int32_t flags) {
4559 int32_t actionMasked = action & AMOTION_EVENT_ACTION_MASK;
4560 switch (actionMasked) {
4561 case AMOTION_EVENT_ACTION_UP:
4562 case AMOTION_EVENT_ACTION_CANCEL: {
4563 ssize_t index = findMotionMemento(entry, false /*hovering*/);
4564 if (index >= 0) {
4565 mMotionMementos.removeAt(index);
4566 return true;
4567 }
4568#if DEBUG_OUTBOUND_EVENT_DETAILS
4569 ALOGD("Dropping inconsistent motion up or cancel event: deviceId=%d, source=%08x, "
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004570 "displayId=%" PRId32 ", actionMasked=%d",
4571 entry->deviceId, entry->source, entry->displayId, actionMasked);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004572#endif
4573 return false;
4574 }
4575
4576 case AMOTION_EVENT_ACTION_DOWN: {
4577 ssize_t index = findMotionMemento(entry, false /*hovering*/);
4578 if (index >= 0) {
4579 mMotionMementos.removeAt(index);
4580 }
4581 addMotionMemento(entry, flags, false /*hovering*/);
4582 return true;
4583 }
4584
4585 case AMOTION_EVENT_ACTION_POINTER_UP:
4586 case AMOTION_EVENT_ACTION_POINTER_DOWN:
4587 case AMOTION_EVENT_ACTION_MOVE: {
Michael Wright38dcdff2014-03-19 12:06:10 -07004588 if (entry->source & AINPUT_SOURCE_CLASS_NAVIGATION) {
4589 // Trackballs can send MOVE events with a corresponding DOWN or UP. There's no need to
4590 // generate cancellation events for these since they're based in relative rather than
4591 // absolute units.
4592 return true;
4593 }
4594
Michael Wrightd02c5b62014-02-10 15:10:22 -08004595 ssize_t index = findMotionMemento(entry, false /*hovering*/);
Michael Wright38dcdff2014-03-19 12:06:10 -07004596
4597 if (entry->source & AINPUT_SOURCE_CLASS_JOYSTICK) {
4598 // Joysticks can send MOVE events without a corresponding DOWN or UP. Since all
4599 // joystick axes are normalized to [-1, 1] we can trust that 0 means it's neutral. Any
4600 // other value and we need to track the motion so we can send cancellation events for
4601 // anything generating fallback events (e.g. DPad keys for joystick movements).
4602 if (index >= 0) {
4603 if (entry->pointerCoords[0].isEmpty()) {
4604 mMotionMementos.removeAt(index);
4605 } else {
4606 MotionMemento& memento = mMotionMementos.editItemAt(index);
4607 memento.setPointers(entry);
4608 }
4609 } else if (!entry->pointerCoords[0].isEmpty()) {
4610 addMotionMemento(entry, flags, false /*hovering*/);
4611 }
4612
4613 // Joysticks and trackballs can send MOVE events without corresponding DOWN or UP.
4614 return true;
4615 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004616 if (index >= 0) {
4617 MotionMemento& memento = mMotionMementos.editItemAt(index);
4618 memento.setPointers(entry);
4619 return true;
4620 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004621#if DEBUG_OUTBOUND_EVENT_DETAILS
4622 ALOGD("Dropping inconsistent motion pointer up/down or move event: "
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004623 "deviceId=%d, source=%08x, displayId=%" PRId32 ", actionMasked=%d",
4624 entry->deviceId, entry->source, entry->displayId, actionMasked);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004625#endif
4626 return false;
4627 }
4628
4629 case AMOTION_EVENT_ACTION_HOVER_EXIT: {
4630 ssize_t index = findMotionMemento(entry, true /*hovering*/);
4631 if (index >= 0) {
4632 mMotionMementos.removeAt(index);
4633 return true;
4634 }
4635#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004636 ALOGD("Dropping inconsistent motion hover exit event: deviceId=%d, source=%08x, "
4637 "displayId=%" PRId32,
4638 entry->deviceId, entry->source, entry->displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004639#endif
4640 return false;
4641 }
4642
4643 case AMOTION_EVENT_ACTION_HOVER_ENTER:
4644 case AMOTION_EVENT_ACTION_HOVER_MOVE: {
4645 ssize_t index = findMotionMemento(entry, true /*hovering*/);
4646 if (index >= 0) {
4647 mMotionMementos.removeAt(index);
4648 }
4649 addMotionMemento(entry, flags, true /*hovering*/);
4650 return true;
4651 }
4652
4653 default:
4654 return true;
4655 }
4656}
4657
4658ssize_t InputDispatcher::InputState::findKeyMemento(const KeyEntry* entry) const {
4659 for (size_t i = 0; i < mKeyMementos.size(); i++) {
4660 const KeyMemento& memento = mKeyMementos.itemAt(i);
4661 if (memento.deviceId == entry->deviceId
4662 && memento.source == entry->source
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004663 && memento.displayId == entry->displayId
Michael Wrightd02c5b62014-02-10 15:10:22 -08004664 && memento.keyCode == entry->keyCode
4665 && memento.scanCode == entry->scanCode) {
4666 return i;
4667 }
4668 }
4669 return -1;
4670}
4671
4672ssize_t InputDispatcher::InputState::findMotionMemento(const MotionEntry* entry,
4673 bool hovering) const {
4674 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4675 const MotionMemento& memento = mMotionMementos.itemAt(i);
4676 if (memento.deviceId == entry->deviceId
4677 && memento.source == entry->source
4678 && memento.displayId == entry->displayId
4679 && memento.hovering == hovering) {
4680 return i;
4681 }
4682 }
4683 return -1;
4684}
4685
4686void InputDispatcher::InputState::addKeyMemento(const KeyEntry* entry, int32_t flags) {
4687 mKeyMementos.push();
4688 KeyMemento& memento = mKeyMementos.editTop();
4689 memento.deviceId = entry->deviceId;
4690 memento.source = entry->source;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004691 memento.displayId = entry->displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004692 memento.keyCode = entry->keyCode;
4693 memento.scanCode = entry->scanCode;
4694 memento.metaState = entry->metaState;
4695 memento.flags = flags;
4696 memento.downTime = entry->downTime;
4697 memento.policyFlags = entry->policyFlags;
4698}
4699
4700void InputDispatcher::InputState::addMotionMemento(const MotionEntry* entry,
4701 int32_t flags, bool hovering) {
4702 mMotionMementos.push();
4703 MotionMemento& memento = mMotionMementos.editTop();
4704 memento.deviceId = entry->deviceId;
4705 memento.source = entry->source;
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004706 memento.displayId = entry->displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004707 memento.flags = flags;
4708 memento.xPrecision = entry->xPrecision;
4709 memento.yPrecision = entry->yPrecision;
4710 memento.downTime = entry->downTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004711 memento.setPointers(entry);
4712 memento.hovering = hovering;
4713 memento.policyFlags = entry->policyFlags;
4714}
4715
4716void InputDispatcher::InputState::MotionMemento::setPointers(const MotionEntry* entry) {
4717 pointerCount = entry->pointerCount;
4718 for (uint32_t i = 0; i < entry->pointerCount; i++) {
4719 pointerProperties[i].copyFrom(entry->pointerProperties[i]);
4720 pointerCoords[i].copyFrom(entry->pointerCoords[i]);
4721 }
4722}
4723
4724void InputDispatcher::InputState::synthesizeCancelationEvents(nsecs_t currentTime,
4725 Vector<EventEntry*>& outEvents, const CancelationOptions& options) {
4726 for (size_t i = 0; i < mKeyMementos.size(); i++) {
4727 const KeyMemento& memento = mKeyMementos.itemAt(i);
4728 if (shouldCancelKey(memento, options)) {
Prabir Pradhan42611e02018-11-27 14:04:02 -08004729 outEvents.push(new KeyEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, currentTime,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004730 memento.deviceId, memento.source, memento.displayId, memento.policyFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004731 AKEY_EVENT_ACTION_UP, memento.flags | AKEY_EVENT_FLAG_CANCELED,
4732 memento.keyCode, memento.scanCode, memento.metaState, 0, memento.downTime));
4733 }
4734 }
4735
4736 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4737 const MotionMemento& memento = mMotionMementos.itemAt(i);
4738 if (shouldCancelMotion(memento, options)) {
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08004739 const int32_t action = memento.hovering ?
4740 AMOTION_EVENT_ACTION_HOVER_EXIT : AMOTION_EVENT_ACTION_CANCEL;
Prabir Pradhan42611e02018-11-27 14:04:02 -08004741 outEvents.push(new MotionEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, currentTime,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004742 memento.deviceId, memento.source, memento.displayId, memento.policyFlags,
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08004743 action, 0 /*actionButton*/, memento.flags, AMETA_NONE, 0 /*buttonState*/,
4744 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004745 memento.xPrecision, memento.yPrecision, memento.downTime,
Jeff Brownf086ddb2014-02-11 14:28:48 -08004746 memento.pointerCount, memento.pointerProperties, memento.pointerCoords,
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08004747 0 /*xOffset*/, 0 /*yOffset*/));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004748 }
4749 }
4750}
4751
4752void InputDispatcher::InputState::clear() {
4753 mKeyMementos.clear();
4754 mMotionMementos.clear();
4755 mFallbackKeys.clear();
4756}
4757
4758void InputDispatcher::InputState::copyPointerStateTo(InputState& other) const {
4759 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4760 const MotionMemento& memento = mMotionMementos.itemAt(i);
4761 if (memento.source & AINPUT_SOURCE_CLASS_POINTER) {
4762 for (size_t j = 0; j < other.mMotionMementos.size(); ) {
4763 const MotionMemento& otherMemento = other.mMotionMementos.itemAt(j);
4764 if (memento.deviceId == otherMemento.deviceId
4765 && memento.source == otherMemento.source
4766 && memento.displayId == otherMemento.displayId) {
4767 other.mMotionMementos.removeAt(j);
4768 } else {
4769 j += 1;
4770 }
4771 }
4772 other.mMotionMementos.push(memento);
4773 }
4774 }
4775}
4776
4777int32_t InputDispatcher::InputState::getFallbackKey(int32_t originalKeyCode) {
4778 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
4779 return index >= 0 ? mFallbackKeys.valueAt(index) : -1;
4780}
4781
4782void InputDispatcher::InputState::setFallbackKey(int32_t originalKeyCode,
4783 int32_t fallbackKeyCode) {
4784 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
4785 if (index >= 0) {
4786 mFallbackKeys.replaceValueAt(index, fallbackKeyCode);
4787 } else {
4788 mFallbackKeys.add(originalKeyCode, fallbackKeyCode);
4789 }
4790}
4791
4792void InputDispatcher::InputState::removeFallbackKey(int32_t originalKeyCode) {
4793 mFallbackKeys.removeItem(originalKeyCode);
4794}
4795
4796bool InputDispatcher::InputState::shouldCancelKey(const KeyMemento& memento,
4797 const CancelationOptions& options) {
4798 if (options.keyCode != -1 && memento.keyCode != options.keyCode) {
4799 return false;
4800 }
4801
4802 if (options.deviceId != -1 && memento.deviceId != options.deviceId) {
4803 return false;
4804 }
4805
4806 switch (options.mode) {
4807 case CancelationOptions::CANCEL_ALL_EVENTS:
4808 case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
4809 return true;
4810 case CancelationOptions::CANCEL_FALLBACK_EVENTS:
4811 return memento.flags & AKEY_EVENT_FLAG_FALLBACK;
Tiger Huang721e26f2018-07-24 22:26:19 +08004812 case CancelationOptions::CANCEL_DISPLAY_UNSPECIFIED_EVENTS:
4813 return memento.displayId == ADISPLAY_ID_NONE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004814 default:
4815 return false;
4816 }
4817}
4818
4819bool InputDispatcher::InputState::shouldCancelMotion(const MotionMemento& memento,
4820 const CancelationOptions& options) {
4821 if (options.deviceId != -1 && memento.deviceId != options.deviceId) {
4822 return false;
4823 }
4824
4825 switch (options.mode) {
4826 case CancelationOptions::CANCEL_ALL_EVENTS:
4827 return true;
4828 case CancelationOptions::CANCEL_POINTER_EVENTS:
4829 return memento.source & AINPUT_SOURCE_CLASS_POINTER;
4830 case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
4831 return !(memento.source & AINPUT_SOURCE_CLASS_POINTER);
Tiger Huang721e26f2018-07-24 22:26:19 +08004832 case CancelationOptions::CANCEL_DISPLAY_UNSPECIFIED_EVENTS:
4833 return memento.displayId == ADISPLAY_ID_NONE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004834 default:
4835 return false;
4836 }
4837}
4838
4839
4840// --- InputDispatcher::Connection ---
4841
Robert Carr803535b2018-08-02 16:38:15 -07004842InputDispatcher::Connection::Connection(const sp<InputChannel>& inputChannel, bool monitor) :
4843 status(STATUS_NORMAL), inputChannel(inputChannel),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004844 monitor(monitor),
4845 inputPublisher(inputChannel), inputPublisherBlocked(false) {
4846}
4847
4848InputDispatcher::Connection::~Connection() {
4849}
4850
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004851const std::string InputDispatcher::Connection::getWindowName() const {
Robert Carr803535b2018-08-02 16:38:15 -07004852 if (inputChannel != nullptr) {
4853 return inputChannel->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004854 }
4855 if (monitor) {
4856 return "monitor";
4857 }
4858 return "?";
4859}
4860
4861const char* InputDispatcher::Connection::getStatusLabel() const {
4862 switch (status) {
4863 case STATUS_NORMAL:
4864 return "NORMAL";
4865
4866 case STATUS_BROKEN:
4867 return "BROKEN";
4868
4869 case STATUS_ZOMBIE:
4870 return "ZOMBIE";
4871
4872 default:
4873 return "UNKNOWN";
4874 }
4875}
4876
4877InputDispatcher::DispatchEntry* InputDispatcher::Connection::findWaitQueueEntry(uint32_t seq) {
Yi Kong9b14ac62018-07-17 13:48:38 -07004878 for (DispatchEntry* entry = waitQueue.head; entry != nullptr; entry = entry->next) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004879 if (entry->seq == seq) {
4880 return entry;
4881 }
4882 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004883 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004884}
4885
4886
4887// --- InputDispatcher::CommandEntry ---
4888
4889InputDispatcher::CommandEntry::CommandEntry(Command command) :
Yi Kong9b14ac62018-07-17 13:48:38 -07004890 command(command), eventTime(0), keyEntry(nullptr), userActivityEventType(0),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004891 seq(0), handled(false) {
4892}
4893
4894InputDispatcher::CommandEntry::~CommandEntry() {
4895}
4896
4897
4898// --- InputDispatcher::TouchState ---
4899
4900InputDispatcher::TouchState::TouchState() :
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004901 down(false), split(false), deviceId(-1), source(0), displayId(ADISPLAY_ID_NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004902}
4903
4904InputDispatcher::TouchState::~TouchState() {
4905}
4906
4907void InputDispatcher::TouchState::reset() {
4908 down = false;
4909 split = false;
4910 deviceId = -1;
4911 source = 0;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004912 displayId = ADISPLAY_ID_NONE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004913 windows.clear();
4914}
4915
4916void InputDispatcher::TouchState::copyFrom(const TouchState& other) {
4917 down = other.down;
4918 split = other.split;
4919 deviceId = other.deviceId;
4920 source = other.source;
4921 displayId = other.displayId;
4922 windows = other.windows;
4923}
4924
4925void InputDispatcher::TouchState::addOrUpdateWindow(const sp<InputWindowHandle>& windowHandle,
4926 int32_t targetFlags, BitSet32 pointerIds) {
4927 if (targetFlags & InputTarget::FLAG_SPLIT) {
4928 split = true;
4929 }
4930
4931 for (size_t i = 0; i < windows.size(); i++) {
4932 TouchedWindow& touchedWindow = windows.editItemAt(i);
4933 if (touchedWindow.windowHandle == windowHandle) {
4934 touchedWindow.targetFlags |= targetFlags;
4935 if (targetFlags & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
4936 touchedWindow.targetFlags &= ~InputTarget::FLAG_DISPATCH_AS_IS;
4937 }
4938 touchedWindow.pointerIds.value |= pointerIds.value;
4939 return;
4940 }
4941 }
4942
4943 windows.push();
4944
4945 TouchedWindow& touchedWindow = windows.editTop();
4946 touchedWindow.windowHandle = windowHandle;
4947 touchedWindow.targetFlags = targetFlags;
4948 touchedWindow.pointerIds = pointerIds;
4949}
4950
4951void InputDispatcher::TouchState::removeWindow(const sp<InputWindowHandle>& windowHandle) {
4952 for (size_t i = 0; i < windows.size(); i++) {
4953 if (windows.itemAt(i).windowHandle == windowHandle) {
4954 windows.removeAt(i);
4955 return;
4956 }
4957 }
4958}
4959
Robert Carr803535b2018-08-02 16:38:15 -07004960void InputDispatcher::TouchState::removeWindowByToken(const sp<IBinder>& token) {
4961 for (size_t i = 0; i < windows.size(); i++) {
Robert Carr5c8a0262018-10-03 16:30:44 -07004962 if (windows.itemAt(i).windowHandle->getToken() == token) {
Robert Carr803535b2018-08-02 16:38:15 -07004963 windows.removeAt(i);
4964 return;
4965 }
4966 }
4967}
4968
Michael Wrightd02c5b62014-02-10 15:10:22 -08004969void InputDispatcher::TouchState::filterNonAsIsTouchWindows() {
4970 for (size_t i = 0 ; i < windows.size(); ) {
4971 TouchedWindow& window = windows.editItemAt(i);
4972 if (window.targetFlags & (InputTarget::FLAG_DISPATCH_AS_IS
4973 | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER)) {
4974 window.targetFlags &= ~InputTarget::FLAG_DISPATCH_MASK;
4975 window.targetFlags |= InputTarget::FLAG_DISPATCH_AS_IS;
4976 i += 1;
4977 } else {
4978 windows.removeAt(i);
4979 }
4980 }
4981}
4982
4983sp<InputWindowHandle> InputDispatcher::TouchState::getFirstForegroundWindowHandle() const {
4984 for (size_t i = 0; i < windows.size(); i++) {
4985 const TouchedWindow& window = windows.itemAt(i);
4986 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
4987 return window.windowHandle;
4988 }
4989 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004990 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004991}
4992
4993bool InputDispatcher::TouchState::isSlippery() const {
4994 // Must have exactly one foreground window.
4995 bool haveSlipperyForegroundWindow = false;
4996 for (size_t i = 0; i < windows.size(); i++) {
4997 const TouchedWindow& window = windows.itemAt(i);
4998 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
4999 if (haveSlipperyForegroundWindow
5000 || !(window.windowHandle->getInfo()->layoutParamsFlags
5001 & InputWindowInfo::FLAG_SLIPPERY)) {
5002 return false;
5003 }
5004 haveSlipperyForegroundWindow = true;
5005 }
5006 }
5007 return haveSlipperyForegroundWindow;
5008}
5009
5010
5011// --- InputDispatcherThread ---
5012
5013InputDispatcherThread::InputDispatcherThread(const sp<InputDispatcherInterface>& dispatcher) :
5014 Thread(/*canCallJava*/ true), mDispatcher(dispatcher) {
5015}
5016
5017InputDispatcherThread::~InputDispatcherThread() {
5018}
5019
5020bool InputDispatcherThread::threadLoop() {
5021 mDispatcher->dispatchOnce();
5022 return true;
5023}
5024
5025} // namespace android