blob: 8e3aa5fd2f55fa6b0c3e335387fc8057e8d8e017 [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,
2158 motionEntry->metaState, motionEntry->buttonState,
2159 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,
2494 originalMotionEntry->edgeFlags,
2495 originalMotionEntry->xPrecision,
2496 originalMotionEntry->yPrecision,
2497 originalMotionEntry->downTime,
Jeff Brownf086ddb2014-02-11 14:28:48 -08002498 splitPointerCount, splitPointerProperties, splitPointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002499
2500 if (originalMotionEntry->injectionState) {
2501 splitMotionEntry->injectionState = originalMotionEntry->injectionState;
2502 splitMotionEntry->injectionState->refCount += 1;
2503 }
2504
2505 return splitMotionEntry;
2506}
2507
2508void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
2509#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002510 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002511#endif
2512
2513 bool needWake;
2514 { // acquire lock
2515 AutoMutex _l(mLock);
2516
Prabir Pradhan42611e02018-11-27 14:04:02 -08002517 ConfigurationChangedEntry* newEntry =
2518 new ConfigurationChangedEntry(args->sequenceNum, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002519 needWake = enqueueInboundEventLocked(newEntry);
2520 } // release lock
2521
2522 if (needWake) {
2523 mLooper->wake();
2524 }
2525}
2526
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002527/**
2528 * If one of the meta shortcuts is detected, process them here:
2529 * Meta + Backspace -> generate BACK
2530 * Meta + Enter -> generate HOME
2531 * This will potentially overwrite keyCode and metaState.
2532 */
2533void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
2534 int32_t& keyCode, int32_t& metaState) {
2535 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
2536 int32_t newKeyCode = AKEYCODE_UNKNOWN;
2537 if (keyCode == AKEYCODE_DEL) {
2538 newKeyCode = AKEYCODE_BACK;
2539 } else if (keyCode == AKEYCODE_ENTER) {
2540 newKeyCode = AKEYCODE_HOME;
2541 }
2542 if (newKeyCode != AKEYCODE_UNKNOWN) {
2543 AutoMutex _l(mLock);
2544 struct KeyReplacement replacement = {keyCode, deviceId};
2545 mReplacedKeys.add(replacement, newKeyCode);
2546 keyCode = newKeyCode;
2547 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
2548 }
2549 } else if (action == AKEY_EVENT_ACTION_UP) {
2550 // In order to maintain a consistent stream of up and down events, check to see if the key
2551 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
2552 // even if the modifier was released between the down and the up events.
2553 AutoMutex _l(mLock);
2554 struct KeyReplacement replacement = {keyCode, deviceId};
2555 ssize_t index = mReplacedKeys.indexOfKey(replacement);
2556 if (index >= 0) {
2557 keyCode = mReplacedKeys.valueAt(index);
2558 mReplacedKeys.removeItemsAt(index);
2559 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
2560 }
2561 }
2562}
2563
Michael Wrightd02c5b62014-02-10 15:10:22 -08002564void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
2565#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002566 ALOGD("notifyKey - eventTime=%" PRId64
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002567 ", deviceId=%d, source=0x%x, displayId=%" PRId32 "policyFlags=0x%x, action=0x%x, "
Arthur Hung82a4cad2018-11-15 12:10:30 +08002568 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002569 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002570 args->action, args->flags, args->keyCode, args->scanCode,
Arthur Hung82a4cad2018-11-15 12:10:30 +08002571 args->metaState, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002572#endif
2573 if (!validateKeyEvent(args->action)) {
2574 return;
2575 }
2576
2577 uint32_t policyFlags = args->policyFlags;
2578 int32_t flags = args->flags;
2579 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07002580 // InputDispatcher tracks and generates key repeats on behalf of
2581 // whatever notifies it, so repeatCount should always be set to 0
2582 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002583 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
2584 policyFlags |= POLICY_FLAG_VIRTUAL;
2585 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
2586 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002587 if (policyFlags & POLICY_FLAG_FUNCTION) {
2588 metaState |= AMETA_FUNCTION_ON;
2589 }
2590
2591 policyFlags |= POLICY_FLAG_TRUSTED;
2592
Michael Wright78f24442014-08-06 15:55:28 -07002593 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002594 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07002595
Michael Wrightd02c5b62014-02-10 15:10:22 -08002596 KeyEvent event;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002597 event.initialize(args->deviceId, args->source, args->displayId, args->action,
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07002598 flags, keyCode, args->scanCode, metaState, repeatCount,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002599 args->downTime, args->eventTime);
2600
Michael Wright2b3c3302018-03-02 17:19:13 +00002601 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002602 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002603 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2604 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
2605 std::to_string(t.duration().count()).c_str());
2606 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002607
Michael Wrightd02c5b62014-02-10 15:10:22 -08002608 bool needWake;
2609 { // acquire lock
2610 mLock.lock();
2611
2612 if (shouldSendKeyToInputFilterLocked(args)) {
2613 mLock.unlock();
2614
2615 policyFlags |= POLICY_FLAG_FILTERED;
2616 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2617 return; // event was consumed by the filter
2618 }
2619
2620 mLock.lock();
2621 }
2622
Prabir Pradhan42611e02018-11-27 14:04:02 -08002623 KeyEntry* newEntry = new KeyEntry(args->sequenceNum, args->eventTime,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002624 args->deviceId, args->source, args->displayId, policyFlags,
Michael Wright78f24442014-08-06 15:55:28 -07002625 args->action, flags, keyCode, args->scanCode,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002626 metaState, repeatCount, args->downTime);
2627
2628 needWake = enqueueInboundEventLocked(newEntry);
2629 mLock.unlock();
2630 } // release lock
2631
2632 if (needWake) {
2633 mLooper->wake();
2634 }
2635}
2636
2637bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
2638 return mInputFilterEnabled;
2639}
2640
2641void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
2642#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002643 ALOGD("notifyMotion - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
2644 ", policyFlags=0x%x, "
Michael Wright7b159c92015-05-14 14:48:03 +01002645 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x,"
Arthur Hung82a4cad2018-11-15 12:10:30 +08002646 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
2647 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002648 args->action, args->actionButton, args->flags, args->metaState, args->buttonState,
Arthur Hung82a4cad2018-11-15 12:10:30 +08002649 args->edgeFlags, args->xPrecision, args->yPrecision, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002650 for (uint32_t i = 0; i < args->pointerCount; i++) {
2651 ALOGD(" Pointer %d: id=%d, toolType=%d, "
2652 "x=%f, y=%f, pressure=%f, size=%f, "
2653 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
2654 "orientation=%f",
2655 i, args->pointerProperties[i].id,
2656 args->pointerProperties[i].toolType,
2657 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
2658 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
2659 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
2660 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
2661 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
2662 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
2663 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
2664 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
2665 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
2666 }
2667#endif
Michael Wright7b159c92015-05-14 14:48:03 +01002668 if (!validateMotionEvent(args->action, args->actionButton,
2669 args->pointerCount, args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002670 return;
2671 }
2672
2673 uint32_t policyFlags = args->policyFlags;
2674 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00002675
2676 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002677 mPolicy->interceptMotionBeforeQueueing(args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002678 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2679 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
2680 std::to_string(t.duration().count()).c_str());
2681 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002682
2683 bool needWake;
2684 { // acquire lock
2685 mLock.lock();
2686
2687 if (shouldSendMotionToInputFilterLocked(args)) {
2688 mLock.unlock();
2689
2690 MotionEvent event;
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002691 event.initialize(args->deviceId, args->source, args->displayId,
2692 args->action, args->actionButton,
Michael Wright7b159c92015-05-14 14:48:03 +01002693 args->flags, args->edgeFlags, args->metaState, args->buttonState,
2694 0, 0, args->xPrecision, args->yPrecision,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002695 args->downTime, args->eventTime,
2696 args->pointerCount, args->pointerProperties, args->pointerCoords);
2697
2698 policyFlags |= POLICY_FLAG_FILTERED;
2699 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2700 return; // event was consumed by the filter
2701 }
2702
2703 mLock.lock();
2704 }
2705
2706 // Just enqueue a new motion event.
Prabir Pradhan42611e02018-11-27 14:04:02 -08002707 MotionEntry* newEntry = new MotionEntry(args->sequenceNum, args->eventTime,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002708 args->deviceId, args->source, args->displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002709 args->action, args->actionButton, args->flags,
2710 args->metaState, args->buttonState,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002711 args->edgeFlags, args->xPrecision, args->yPrecision, args->downTime,
Jeff Brownf086ddb2014-02-11 14:28:48 -08002712 args->pointerCount, args->pointerProperties, args->pointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002713
2714 needWake = enqueueInboundEventLocked(newEntry);
2715 mLock.unlock();
2716 } // release lock
2717
2718 if (needWake) {
2719 mLooper->wake();
2720 }
2721}
2722
2723bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
2724 // TODO: support sending secondary display events to input filter
2725 return mInputFilterEnabled && isMainDisplay(args->displayId);
2726}
2727
2728void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
2729#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002730 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
2731 "switchMask=0x%08x",
2732 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002733#endif
2734
2735 uint32_t policyFlags = args->policyFlags;
2736 policyFlags |= POLICY_FLAG_TRUSTED;
2737 mPolicy->notifySwitch(args->eventTime,
2738 args->switchValues, args->switchMask, policyFlags);
2739}
2740
2741void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
2742#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002743 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002744 args->eventTime, args->deviceId);
2745#endif
2746
2747 bool needWake;
2748 { // acquire lock
2749 AutoMutex _l(mLock);
2750
Prabir Pradhan42611e02018-11-27 14:04:02 -08002751 DeviceResetEntry* newEntry =
2752 new DeviceResetEntry(args->sequenceNum, args->eventTime, args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002753 needWake = enqueueInboundEventLocked(newEntry);
2754 } // release lock
2755
2756 if (needWake) {
2757 mLooper->wake();
2758 }
2759}
2760
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002761int32_t InputDispatcher::injectInputEvent(const InputEvent* event,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002762 int32_t injectorPid, int32_t injectorUid, int32_t syncMode, int32_t timeoutMillis,
2763 uint32_t policyFlags) {
2764#if DEBUG_INBOUND_EVENT_DETAILS
2765 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002766 "syncMode=%d, timeoutMillis=%d, policyFlags=0x%08x",
2767 event->getType(), injectorPid, injectorUid, syncMode, timeoutMillis, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002768#endif
2769
2770 nsecs_t endTime = now() + milliseconds_to_nanoseconds(timeoutMillis);
2771
2772 policyFlags |= POLICY_FLAG_INJECTED;
2773 if (hasInjectionPermission(injectorPid, injectorUid)) {
2774 policyFlags |= POLICY_FLAG_TRUSTED;
2775 }
2776
2777 EventEntry* firstInjectedEntry;
2778 EventEntry* lastInjectedEntry;
2779 switch (event->getType()) {
2780 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002781 KeyEvent keyEvent;
2782 keyEvent.initialize(*static_cast<const KeyEvent*>(event));
2783 int32_t action = keyEvent.getAction();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002784 if (! validateKeyEvent(action)) {
2785 return INPUT_EVENT_INJECTION_FAILED;
2786 }
2787
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002788 int32_t flags = keyEvent.getFlags();
2789 int32_t keyCode = keyEvent.getKeyCode();
2790 int32_t metaState = keyEvent.getMetaState();
2791 accelerateMetaShortcuts(keyEvent.getDeviceId(), action,
2792 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002793 keyEvent.initialize(keyEvent.getDeviceId(), keyEvent.getSource(), keyEvent.getDisplayId(),
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07002794 action, flags, keyCode, keyEvent.getScanCode(), metaState, keyEvent.getRepeatCount(),
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002795 keyEvent.getDownTime(), keyEvent.getEventTime());
2796
Michael Wrightd02c5b62014-02-10 15:10:22 -08002797 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
2798 policyFlags |= POLICY_FLAG_VIRTUAL;
2799 }
2800
2801 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wright2b3c3302018-03-02 17:19:13 +00002802 android::base::Timer t;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002803 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002804 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2805 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
2806 std::to_string(t.duration().count()).c_str());
2807 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002808 }
2809
Michael Wrightd02c5b62014-02-10 15:10:22 -08002810 mLock.lock();
Prabir Pradhan42611e02018-11-27 14:04:02 -08002811 firstInjectedEntry = new KeyEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, keyEvent.getEventTime(),
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002812 keyEvent.getDeviceId(), keyEvent.getSource(), keyEvent.getDisplayId(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002813 policyFlags, action, flags,
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002814 keyEvent.getKeyCode(), keyEvent.getScanCode(), keyEvent.getMetaState(),
2815 keyEvent.getRepeatCount(), keyEvent.getDownTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002816 lastInjectedEntry = firstInjectedEntry;
2817 break;
2818 }
2819
2820 case AINPUT_EVENT_TYPE_MOTION: {
2821 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002822 int32_t action = motionEvent->getAction();
2823 size_t pointerCount = motionEvent->getPointerCount();
2824 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
Michael Wright7b159c92015-05-14 14:48:03 +01002825 int32_t actionButton = motionEvent->getActionButton();
2826 if (! validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002827 return INPUT_EVENT_INJECTION_FAILED;
2828 }
2829
2830 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
2831 nsecs_t eventTime = motionEvent->getEventTime();
Michael Wright2b3c3302018-03-02 17:19:13 +00002832 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002833 mPolicy->interceptMotionBeforeQueueing(eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002834 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2835 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
2836 std::to_string(t.duration().count()).c_str());
2837 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002838 }
2839
2840 mLock.lock();
2841 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
2842 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
Prabir Pradhan42611e02018-11-27 14:04:02 -08002843 firstInjectedEntry = new MotionEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, *sampleEventTimes,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002844 motionEvent->getDeviceId(), motionEvent->getSource(), motionEvent->getDisplayId(),
2845 policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002846 action, actionButton, motionEvent->getFlags(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002847 motionEvent->getMetaState(), motionEvent->getButtonState(),
2848 motionEvent->getEdgeFlags(),
2849 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002850 motionEvent->getDownTime(),
Jeff Brownf086ddb2014-02-11 14:28:48 -08002851 uint32_t(pointerCount), pointerProperties, samplePointerCoords,
2852 motionEvent->getXOffset(), motionEvent->getYOffset());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002853 lastInjectedEntry = firstInjectedEntry;
2854 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
2855 sampleEventTimes += 1;
2856 samplePointerCoords += pointerCount;
Prabir Pradhan42611e02018-11-27 14:04:02 -08002857 MotionEntry* nextInjectedEntry = new MotionEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM,
2858 *sampleEventTimes,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002859 motionEvent->getDeviceId(), motionEvent->getSource(),
2860 motionEvent->getDisplayId(), policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002861 action, actionButton, motionEvent->getFlags(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002862 motionEvent->getMetaState(), motionEvent->getButtonState(),
2863 motionEvent->getEdgeFlags(),
2864 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002865 motionEvent->getDownTime(),
Jeff Brownf086ddb2014-02-11 14:28:48 -08002866 uint32_t(pointerCount), pointerProperties, samplePointerCoords,
2867 motionEvent->getXOffset(), motionEvent->getYOffset());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002868 lastInjectedEntry->next = nextInjectedEntry;
2869 lastInjectedEntry = nextInjectedEntry;
2870 }
2871 break;
2872 }
2873
2874 default:
2875 ALOGW("Cannot inject event of type %d", event->getType());
2876 return INPUT_EVENT_INJECTION_FAILED;
2877 }
2878
2879 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
2880 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
2881 injectionState->injectionIsAsync = true;
2882 }
2883
2884 injectionState->refCount += 1;
2885 lastInjectedEntry->injectionState = injectionState;
2886
2887 bool needWake = false;
Yi Kong9b14ac62018-07-17 13:48:38 -07002888 for (EventEntry* entry = firstInjectedEntry; entry != nullptr; ) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002889 EventEntry* nextEntry = entry->next;
2890 needWake |= enqueueInboundEventLocked(entry);
2891 entry = nextEntry;
2892 }
2893
2894 mLock.unlock();
2895
2896 if (needWake) {
2897 mLooper->wake();
2898 }
2899
2900 int32_t injectionResult;
2901 { // acquire lock
2902 AutoMutex _l(mLock);
2903
2904 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
2905 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
2906 } else {
2907 for (;;) {
2908 injectionResult = injectionState->injectionResult;
2909 if (injectionResult != INPUT_EVENT_INJECTION_PENDING) {
2910 break;
2911 }
2912
2913 nsecs_t remainingTimeout = endTime - now();
2914 if (remainingTimeout <= 0) {
2915#if DEBUG_INJECTION
2916 ALOGD("injectInputEvent - Timed out waiting for injection result "
2917 "to become available.");
2918#endif
2919 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
2920 break;
2921 }
2922
2923 mInjectionResultAvailableCondition.waitRelative(mLock, remainingTimeout);
2924 }
2925
2926 if (injectionResult == INPUT_EVENT_INJECTION_SUCCEEDED
2927 && syncMode == INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED) {
2928 while (injectionState->pendingForegroundDispatches != 0) {
2929#if DEBUG_INJECTION
2930 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
2931 injectionState->pendingForegroundDispatches);
2932#endif
2933 nsecs_t remainingTimeout = endTime - now();
2934 if (remainingTimeout <= 0) {
2935#if DEBUG_INJECTION
2936 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
2937 "dispatches to finish.");
2938#endif
2939 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
2940 break;
2941 }
2942
2943 mInjectionSyncFinishedCondition.waitRelative(mLock, remainingTimeout);
2944 }
2945 }
2946 }
2947
2948 injectionState->release();
2949 } // release lock
2950
2951#if DEBUG_INJECTION
2952 ALOGD("injectInputEvent - Finished with result %d. "
2953 "injectorPid=%d, injectorUid=%d",
2954 injectionResult, injectorPid, injectorUid);
2955#endif
2956
2957 return injectionResult;
2958}
2959
2960bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
2961 return injectorUid == 0
2962 || mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
2963}
2964
2965void InputDispatcher::setInjectionResultLocked(EventEntry* entry, int32_t injectionResult) {
2966 InjectionState* injectionState = entry->injectionState;
2967 if (injectionState) {
2968#if DEBUG_INJECTION
2969 ALOGD("Setting input event injection result to %d. "
2970 "injectorPid=%d, injectorUid=%d",
2971 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
2972#endif
2973
2974 if (injectionState->injectionIsAsync
2975 && !(entry->policyFlags & POLICY_FLAG_FILTERED)) {
2976 // Log the outcome since the injector did not wait for the injection result.
2977 switch (injectionResult) {
2978 case INPUT_EVENT_INJECTION_SUCCEEDED:
2979 ALOGV("Asynchronous input event injection succeeded.");
2980 break;
2981 case INPUT_EVENT_INJECTION_FAILED:
2982 ALOGW("Asynchronous input event injection failed.");
2983 break;
2984 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
2985 ALOGW("Asynchronous input event injection permission denied.");
2986 break;
2987 case INPUT_EVENT_INJECTION_TIMED_OUT:
2988 ALOGW("Asynchronous input event injection timed out.");
2989 break;
2990 }
2991 }
2992
2993 injectionState->injectionResult = injectionResult;
2994 mInjectionResultAvailableCondition.broadcast();
2995 }
2996}
2997
2998void InputDispatcher::incrementPendingForegroundDispatchesLocked(EventEntry* entry) {
2999 InjectionState* injectionState = entry->injectionState;
3000 if (injectionState) {
3001 injectionState->pendingForegroundDispatches += 1;
3002 }
3003}
3004
3005void InputDispatcher::decrementPendingForegroundDispatchesLocked(EventEntry* entry) {
3006 InjectionState* injectionState = entry->injectionState;
3007 if (injectionState) {
3008 injectionState->pendingForegroundDispatches -= 1;
3009
3010 if (injectionState->pendingForegroundDispatches == 0) {
3011 mInjectionSyncFinishedCondition.broadcast();
3012 }
3013 }
3014}
3015
Arthur Hungb92218b2018-08-14 12:00:21 +08003016Vector<sp<InputWindowHandle>> InputDispatcher::getWindowHandlesLocked(int32_t displayId) const {
3017 std::unordered_map<int32_t, Vector<sp<InputWindowHandle>>>::const_iterator it =
3018 mWindowHandlesByDisplay.find(displayId);
3019 if(it != mWindowHandlesByDisplay.end()) {
3020 return it->second;
3021 }
3022
3023 // Return an empty one if nothing found.
3024 return Vector<sp<InputWindowHandle>>();
3025}
3026
Michael Wrightd02c5b62014-02-10 15:10:22 -08003027sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08003028 const sp<IBinder>& windowHandleToken) const {
Arthur Hungb92218b2018-08-14 12:00:21 +08003029 for (auto& it : mWindowHandlesByDisplay) {
3030 const Vector<sp<InputWindowHandle>> windowHandles = it.second;
3031 size_t numWindows = windowHandles.size();
3032 for (size_t i = 0; i < numWindows; i++) {
3033 const sp<InputWindowHandle>& windowHandle = windowHandles.itemAt(i);
chaviwfbe5d9c2018-12-26 12:23:37 -08003034 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003035 return windowHandle;
3036 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003037 }
3038 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003039 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003040}
3041
3042bool InputDispatcher::hasWindowHandleLocked(
Siarhei Vishniakou9224fba2018-08-13 18:55:08 +00003043 const sp<InputWindowHandle>& windowHandle) const {
Arthur Hungb92218b2018-08-14 12:00:21 +08003044 for (auto& it : mWindowHandlesByDisplay) {
3045 const Vector<sp<InputWindowHandle>> windowHandles = it.second;
3046 size_t numWindows = windowHandles.size();
3047 for (size_t i = 0; i < numWindows; i++) {
Robert Carr5c8a0262018-10-03 16:30:44 -07003048 if (windowHandles.itemAt(i)->getToken()
3049 == windowHandle->getToken()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003050 if (windowHandle->getInfo()->displayId != it.first) {
Arthur Hung3b413f22018-10-26 18:05:34 +08003051 ALOGE("Found window %s in display %" PRId32
3052 ", but it should belong to display %" PRId32,
3053 windowHandle->getName().c_str(), it.first,
3054 windowHandle->getInfo()->displayId);
Arthur Hungb92218b2018-08-14 12:00:21 +08003055 }
3056 return true;
3057 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003058 }
3059 }
3060 return false;
3061}
3062
Robert Carr5c8a0262018-10-03 16:30:44 -07003063sp<InputChannel> InputDispatcher::getInputChannelLocked(const sp<IBinder>& token) const {
3064 size_t count = mInputChannelsByToken.count(token);
3065 if (count == 0) {
3066 return nullptr;
3067 }
3068 return mInputChannelsByToken.at(token);
3069}
3070
Arthur Hungb92218b2018-08-14 12:00:21 +08003071/**
3072 * Called from InputManagerService, update window handle list by displayId that can receive input.
3073 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
3074 * If set an empty list, remove all handles from the specific display.
3075 * For focused handle, check if need to change and send a cancel event to previous one.
3076 * For removed handle, check if need to send a cancel event if already in touch.
3077 */
3078void InputDispatcher::setInputWindows(const Vector<sp<InputWindowHandle>>& inputWindowHandles,
3079 int32_t displayId) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003080#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003081 ALOGD("setInputWindows displayId=%" PRId32, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003082#endif
3083 { // acquire lock
3084 AutoMutex _l(mLock);
3085
Arthur Hungb92218b2018-08-14 12:00:21 +08003086 // Copy old handles for release if they are no longer present.
3087 const Vector<sp<InputWindowHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003088
Tiger Huang721e26f2018-07-24 22:26:19 +08003089 sp<InputWindowHandle> newFocusedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003090 bool foundHoveredWindow = false;
Arthur Hungb92218b2018-08-14 12:00:21 +08003091
3092 if (inputWindowHandles.isEmpty()) {
3093 // Remove all handles on a display if there are no windows left.
3094 mWindowHandlesByDisplay.erase(displayId);
3095 } else {
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003096 // Since we compare the pointer of input window handles across window updates, we need
3097 // to make sure the handle object for the same window stays unchanged across updates.
3098 const Vector<sp<InputWindowHandle>>& oldHandles = mWindowHandlesByDisplay[displayId];
3099 std::unordered_map<sp<IBinder>, sp<InputWindowHandle>, IBinderHash> oldHandlesByTokens;
3100 for (size_t i = 0; i < oldHandles.size(); i++) {
3101 const sp<InputWindowHandle>& handle = oldHandles.itemAt(i);
3102 oldHandlesByTokens[handle->getToken()] = handle;
3103 }
3104
3105 const size_t numWindows = inputWindowHandles.size();
3106 Vector<sp<InputWindowHandle>> newHandles;
Arthur Hungb92218b2018-08-14 12:00:21 +08003107 for (size_t i = 0; i < numWindows; i++) {
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003108 const sp<InputWindowHandle>& handle = inputWindowHandles.itemAt(i);
3109 if (!handle->updateInfo() || getInputChannelLocked(handle->getToken()) == nullptr) {
Robert Carr5c8a0262018-10-03 16:30:44 -07003110 ALOGE("Window handle %s has no registered input channel",
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003111 handle->getName().c_str());
Arthur Hungb92218b2018-08-14 12:00:21 +08003112 continue;
3113 }
3114
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003115 if (handle->getInfo()->displayId != displayId) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003116 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003117 handle->getName().c_str(), displayId,
3118 handle->getInfo()->displayId);
Arthur Hungb92218b2018-08-14 12:00:21 +08003119 continue;
3120 }
3121
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003122 if (oldHandlesByTokens.find(handle->getToken()) != oldHandlesByTokens.end()) {
3123 const sp<InputWindowHandle> oldHandle =
3124 oldHandlesByTokens.at(handle->getToken());
3125 oldHandle->updateFrom(handle);
3126 newHandles.push_back(oldHandle);
3127 } else {
3128 newHandles.push_back(handle);
3129 }
3130 }
3131
3132 for (size_t i = 0; i < newHandles.size(); i++) {
3133 const sp<InputWindowHandle>& windowHandle = newHandles.itemAt(i);
Siarhei Vishniakou49ee3232018-12-03 15:10:36 -06003134 if (windowHandle->getInfo()->hasFocus && windowHandle->getInfo()->visible) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003135 newFocusedWindowHandle = windowHandle;
3136 }
3137 if (windowHandle == mLastHoverWindowHandle) {
3138 foundHoveredWindow = true;
3139 }
Siarhei Vishniakou9224fba2018-08-13 18:55:08 +00003140 }
Arthur Hungb92218b2018-08-14 12:00:21 +08003141
3142 // Insert or replace
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003143 mWindowHandlesByDisplay[displayId] = newHandles;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003144 }
3145
3146 if (!foundHoveredWindow) {
Yi Kong9b14ac62018-07-17 13:48:38 -07003147 mLastHoverWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003148 }
3149
Tiger Huang721e26f2018-07-24 22:26:19 +08003150 sp<InputWindowHandle> oldFocusedWindowHandle =
3151 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
3152
3153 if (oldFocusedWindowHandle != newFocusedWindowHandle) {
3154 if (oldFocusedWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003155#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003156 ALOGD("Focus left window: %s in display %" PRId32,
3157 oldFocusedWindowHandle->getName().c_str(), displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003158#endif
Robert Carr5c8a0262018-10-03 16:30:44 -07003159 sp<InputChannel> focusedInputChannel = getInputChannelLocked(
3160 oldFocusedWindowHandle->getToken());
Yi Kong9b14ac62018-07-17 13:48:38 -07003161 if (focusedInputChannel != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003162 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
3163 "focus left window");
3164 synthesizeCancelationEventsForInputChannelLocked(
3165 focusedInputChannel, options);
3166 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003167 mFocusedWindowHandlesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003168 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003169 if (newFocusedWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003170#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003171 ALOGD("Focus entered window: %s in display %" PRId32,
3172 newFocusedWindowHandle->getName().c_str(), displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003173#endif
Tiger Huang721e26f2018-07-24 22:26:19 +08003174 mFocusedWindowHandlesByDisplay[displayId] = newFocusedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003175 }
Robert Carrf759f162018-11-13 12:57:11 -08003176
3177 if (mFocusedDisplayId == displayId) {
3178 onFocusChangedLocked(newFocusedWindowHandle);
3179 }
3180
Michael Wrightd02c5b62014-02-10 15:10:22 -08003181 }
3182
Arthur Hungb92218b2018-08-14 12:00:21 +08003183 ssize_t stateIndex = mTouchStatesByDisplay.indexOfKey(displayId);
3184 if (stateIndex >= 0) {
3185 TouchState& state = mTouchStatesByDisplay.editValueAt(stateIndex);
Ivan Lozano96f12992017-11-09 14:45:38 -08003186 for (size_t i = 0; i < state.windows.size(); ) {
Jeff Brownf086ddb2014-02-11 14:28:48 -08003187 TouchedWindow& touchedWindow = state.windows.editItemAt(i);
Siarhei Vishniakou9224fba2018-08-13 18:55:08 +00003188 if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003189#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003190 ALOGD("Touched window was removed: %s in display %" PRId32,
3191 touchedWindow.windowHandle->getName().c_str(), displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003192#endif
Jeff Brownf086ddb2014-02-11 14:28:48 -08003193 sp<InputChannel> touchedInputChannel =
Robert Carr5c8a0262018-10-03 16:30:44 -07003194 getInputChannelLocked(touchedWindow.windowHandle->getToken());
Yi Kong9b14ac62018-07-17 13:48:38 -07003195 if (touchedInputChannel != nullptr) {
Jeff Brownf086ddb2014-02-11 14:28:48 -08003196 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
3197 "touched window was removed");
3198 synthesizeCancelationEventsForInputChannelLocked(
3199 touchedInputChannel, options);
3200 }
Ivan Lozano96f12992017-11-09 14:45:38 -08003201 state.windows.removeAt(i);
3202 } else {
3203 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003204 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003205 }
3206 }
3207
3208 // Release information for windows that are no longer present.
3209 // This ensures that unused input channels are released promptly.
3210 // Otherwise, they might stick around until the window handle is destroyed
3211 // which might not happen until the next GC.
Arthur Hungb92218b2018-08-14 12:00:21 +08003212 size_t numWindows = oldWindowHandles.size();
3213 for (size_t i = 0; i < numWindows; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003214 const sp<InputWindowHandle>& oldWindowHandle = oldWindowHandles.itemAt(i);
Siarhei Vishniakou9224fba2018-08-13 18:55:08 +00003215 if (!hasWindowHandleLocked(oldWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003216#if DEBUG_FOCUS
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003217 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003218#endif
Arthur Hung3b413f22018-10-26 18:05:34 +08003219 oldWindowHandle->releaseChannel();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003220 }
3221 }
3222 } // release lock
3223
3224 // Wake up poll loop since it may need to make new input dispatching choices.
3225 mLooper->wake();
3226}
3227
3228void InputDispatcher::setFocusedApplication(
Tiger Huang721e26f2018-07-24 22:26:19 +08003229 int32_t displayId, const sp<InputApplicationHandle>& inputApplicationHandle) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003230#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003231 ALOGD("setFocusedApplication displayId=%" PRId32, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003232#endif
3233 { // acquire lock
3234 AutoMutex _l(mLock);
3235
Tiger Huang721e26f2018-07-24 22:26:19 +08003236 sp<InputApplicationHandle> oldFocusedApplicationHandle =
3237 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
Yi Kong9b14ac62018-07-17 13:48:38 -07003238 if (inputApplicationHandle != nullptr && inputApplicationHandle->updateInfo()) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003239 if (oldFocusedApplicationHandle != inputApplicationHandle) {
3240 if (oldFocusedApplicationHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003241 resetANRTimeoutsLocked();
Tiger Huang721e26f2018-07-24 22:26:19 +08003242 oldFocusedApplicationHandle->releaseInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003243 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003244 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003245 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003246 } else if (oldFocusedApplicationHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003247 resetANRTimeoutsLocked();
Tiger Huang721e26f2018-07-24 22:26:19 +08003248 oldFocusedApplicationHandle->releaseInfo();
3249 oldFocusedApplicationHandle.clear();
3250 mFocusedApplicationHandlesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003251 }
3252
3253#if DEBUG_FOCUS
3254 //logDispatchStateLocked();
3255#endif
3256 } // release lock
3257
3258 // Wake up poll loop since it may need to make new input dispatching choices.
3259 mLooper->wake();
3260}
3261
Tiger Huang721e26f2018-07-24 22:26:19 +08003262/**
3263 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
3264 * the display not specified.
3265 *
3266 * We track any unreleased events for each window. If a window loses the ability to receive the
3267 * released event, we will send a cancel event to it. So when the focused display is changed, we
3268 * cancel all the unreleased display-unspecified events for the focused window on the old focused
3269 * display. The display-specified events won't be affected.
3270 */
3271void InputDispatcher::setFocusedDisplay(int32_t displayId) {
3272#if DEBUG_FOCUS
3273 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
3274#endif
3275 { // acquire lock
3276 AutoMutex _l(mLock);
3277
3278 if (mFocusedDisplayId != displayId) {
3279 sp<InputWindowHandle> oldFocusedWindowHandle =
3280 getValueByKey(mFocusedWindowHandlesByDisplay, mFocusedDisplayId);
3281 if (oldFocusedWindowHandle != nullptr) {
Robert Carr5c8a0262018-10-03 16:30:44 -07003282 sp<InputChannel> inputChannel =
3283 getInputChannelLocked(oldFocusedWindowHandle->getToken());
Tiger Huang721e26f2018-07-24 22:26:19 +08003284 if (inputChannel != nullptr) {
3285 CancelationOptions options(
3286 CancelationOptions::CANCEL_DISPLAY_UNSPECIFIED_EVENTS,
3287 "The display which contains this window no longer has focus.");
3288 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
3289 }
3290 }
3291 mFocusedDisplayId = displayId;
3292
3293 // Sanity check
3294 sp<InputWindowHandle> newFocusedWindowHandle =
3295 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
Robert Carrf759f162018-11-13 12:57:11 -08003296 onFocusChangedLocked(newFocusedWindowHandle);
3297
Tiger Huang721e26f2018-07-24 22:26:19 +08003298 if (newFocusedWindowHandle == nullptr) {
3299 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
3300 if (!mFocusedWindowHandlesByDisplay.empty()) {
3301 ALOGE("But another display has a focused window:");
3302 for (auto& it : mFocusedWindowHandlesByDisplay) {
3303 const int32_t displayId = it.first;
3304 const sp<InputWindowHandle>& windowHandle = it.second;
3305 ALOGE("Display #%" PRId32 " has focused window: '%s'\n",
3306 displayId, windowHandle->getName().c_str());
3307 }
3308 }
3309 }
3310 }
3311
3312#if DEBUG_FOCUS
3313 logDispatchStateLocked();
3314#endif
3315 } // release lock
3316
3317 // Wake up poll loop since it may need to make new input dispatching choices.
3318 mLooper->wake();
3319}
3320
Michael Wrightd02c5b62014-02-10 15:10:22 -08003321void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
3322#if DEBUG_FOCUS
3323 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
3324#endif
3325
3326 bool changed;
3327 { // acquire lock
3328 AutoMutex _l(mLock);
3329
3330 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
3331 if (mDispatchFrozen && !frozen) {
3332 resetANRTimeoutsLocked();
3333 }
3334
3335 if (mDispatchEnabled && !enabled) {
3336 resetAndDropEverythingLocked("dispatcher is being disabled");
3337 }
3338
3339 mDispatchEnabled = enabled;
3340 mDispatchFrozen = frozen;
3341 changed = true;
3342 } else {
3343 changed = false;
3344 }
3345
3346#if DEBUG_FOCUS
Tiger Huang721e26f2018-07-24 22:26:19 +08003347 logDispatchStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003348#endif
3349 } // release lock
3350
3351 if (changed) {
3352 // Wake up poll loop since it may need to make new input dispatching choices.
3353 mLooper->wake();
3354 }
3355}
3356
3357void InputDispatcher::setInputFilterEnabled(bool enabled) {
3358#if DEBUG_FOCUS
3359 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
3360#endif
3361
3362 { // acquire lock
3363 AutoMutex _l(mLock);
3364
3365 if (mInputFilterEnabled == enabled) {
3366 return;
3367 }
3368
3369 mInputFilterEnabled = enabled;
3370 resetAndDropEverythingLocked("input filter is being enabled or disabled");
3371 } // release lock
3372
3373 // Wake up poll loop since there might be work to do to drop everything.
3374 mLooper->wake();
3375}
3376
chaviwfbe5d9c2018-12-26 12:23:37 -08003377bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken) {
3378 if (fromToken == toToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003379#if DEBUG_FOCUS
chaviwfbe5d9c2018-12-26 12:23:37 -08003380 ALOGD("Trivial transfer to same window.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003381#endif
chaviwfbe5d9c2018-12-26 12:23:37 -08003382 return true;
3383 }
3384
Michael Wrightd02c5b62014-02-10 15:10:22 -08003385 { // acquire lock
3386 AutoMutex _l(mLock);
3387
chaviwfbe5d9c2018-12-26 12:23:37 -08003388 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromToken);
3389 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toToken);
Yi Kong9b14ac62018-07-17 13:48:38 -07003390 if (fromWindowHandle == nullptr || toWindowHandle == nullptr) {
chaviwfbe5d9c2018-12-26 12:23:37 -08003391 ALOGW("Cannot transfer focus because from or to window not found.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003392 return false;
3393 }
chaviw4f2dd402018-12-26 15:30:27 -08003394#if DEBUG_FOCUS
3395 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
3396 fromWindowHandle->getName().c_str(), toWindowHandle->getName().c_str());
3397#endif
Michael Wrightd02c5b62014-02-10 15:10:22 -08003398 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
3399#if DEBUG_FOCUS
3400 ALOGD("Cannot transfer focus because windows are on different displays.");
3401#endif
3402 return false;
3403 }
3404
3405 bool found = false;
Jeff Brownf086ddb2014-02-11 14:28:48 -08003406 for (size_t d = 0; d < mTouchStatesByDisplay.size(); d++) {
3407 TouchState& state = mTouchStatesByDisplay.editValueAt(d);
3408 for (size_t i = 0; i < state.windows.size(); i++) {
3409 const TouchedWindow& touchedWindow = state.windows[i];
3410 if (touchedWindow.windowHandle == fromWindowHandle) {
3411 int32_t oldTargetFlags = touchedWindow.targetFlags;
3412 BitSet32 pointerIds = touchedWindow.pointerIds;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003413
Jeff Brownf086ddb2014-02-11 14:28:48 -08003414 state.windows.removeAt(i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003415
Jeff Brownf086ddb2014-02-11 14:28:48 -08003416 int32_t newTargetFlags = oldTargetFlags
3417 & (InputTarget::FLAG_FOREGROUND
3418 | InputTarget::FLAG_SPLIT | InputTarget::FLAG_DISPATCH_AS_IS);
3419 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003420
Jeff Brownf086ddb2014-02-11 14:28:48 -08003421 found = true;
3422 goto Found;
3423 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003424 }
3425 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08003426Found:
Michael Wrightd02c5b62014-02-10 15:10:22 -08003427
3428 if (! found) {
3429#if DEBUG_FOCUS
3430 ALOGD("Focus transfer failed because from window did not have focus.");
3431#endif
3432 return false;
3433 }
3434
chaviwfbe5d9c2018-12-26 12:23:37 -08003435
3436 sp<InputChannel> fromChannel = getInputChannelLocked(fromToken);
3437 sp<InputChannel> toChannel = getInputChannelLocked(toToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003438 ssize_t fromConnectionIndex = getConnectionIndexLocked(fromChannel);
3439 ssize_t toConnectionIndex = getConnectionIndexLocked(toChannel);
3440 if (fromConnectionIndex >= 0 && toConnectionIndex >= 0) {
3441 sp<Connection> fromConnection = mConnectionsByFd.valueAt(fromConnectionIndex);
3442 sp<Connection> toConnection = mConnectionsByFd.valueAt(toConnectionIndex);
3443
3444 fromConnection->inputState.copyPointerStateTo(toConnection->inputState);
3445 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
3446 "transferring touch focus from this window to another window");
3447 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
3448 }
3449
3450#if DEBUG_FOCUS
3451 logDispatchStateLocked();
3452#endif
3453 } // release lock
3454
3455 // Wake up poll loop since it may need to make new input dispatching choices.
3456 mLooper->wake();
3457 return true;
3458}
3459
3460void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
3461#if DEBUG_FOCUS
3462 ALOGD("Resetting and dropping all events (%s).", reason);
3463#endif
3464
3465 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
3466 synthesizeCancelationEventsForAllConnectionsLocked(options);
3467
3468 resetKeyRepeatLocked();
3469 releasePendingEventLocked();
3470 drainInboundQueueLocked();
3471 resetANRTimeoutsLocked();
3472
Jeff Brownf086ddb2014-02-11 14:28:48 -08003473 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003474 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07003475 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003476}
3477
3478void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003479 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003480 dumpDispatchStateLocked(dump);
3481
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003482 std::istringstream stream(dump);
3483 std::string line;
3484
3485 while (std::getline(stream, line, '\n')) {
3486 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003487 }
3488}
3489
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003490void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
3491 dump += StringPrintf(INDENT "DispatchEnabled: %d\n", mDispatchEnabled);
3492 dump += StringPrintf(INDENT "DispatchFrozen: %d\n", mDispatchFrozen);
Tiger Huang721e26f2018-07-24 22:26:19 +08003493 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003494
Tiger Huang721e26f2018-07-24 22:26:19 +08003495 if (!mFocusedApplicationHandlesByDisplay.empty()) {
3496 dump += StringPrintf(INDENT "FocusedApplications:\n");
3497 for (auto& it : mFocusedApplicationHandlesByDisplay) {
3498 const int32_t displayId = it.first;
3499 const sp<InputApplicationHandle>& applicationHandle = it.second;
3500 dump += StringPrintf(
3501 INDENT2 "displayId=%" PRId32 ", name='%s', dispatchingTimeout=%0.3fms\n",
3502 displayId,
3503 applicationHandle->getName().c_str(),
3504 applicationHandle->getDispatchingTimeout(
3505 DEFAULT_INPUT_DISPATCHING_TIMEOUT) / 1000000.0);
3506 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003507 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08003508 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003509 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003510
3511 if (!mFocusedWindowHandlesByDisplay.empty()) {
3512 dump += StringPrintf(INDENT "FocusedWindows:\n");
3513 for (auto& it : mFocusedWindowHandlesByDisplay) {
3514 const int32_t displayId = it.first;
3515 const sp<InputWindowHandle>& windowHandle = it.second;
3516 dump += StringPrintf(INDENT2 "displayId=%" PRId32 ", name='%s'\n",
3517 displayId, windowHandle->getName().c_str());
3518 }
3519 } else {
3520 dump += StringPrintf(INDENT "FocusedWindows: <none>\n");
3521 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003522
Jeff Brownf086ddb2014-02-11 14:28:48 -08003523 if (!mTouchStatesByDisplay.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003524 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Jeff Brownf086ddb2014-02-11 14:28:48 -08003525 for (size_t i = 0; i < mTouchStatesByDisplay.size(); i++) {
3526 const TouchState& state = mTouchStatesByDisplay.valueAt(i);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003527 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Jeff Brownf086ddb2014-02-11 14:28:48 -08003528 state.displayId, toString(state.down), toString(state.split),
3529 state.deviceId, state.source);
3530 if (!state.windows.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003531 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08003532 for (size_t i = 0; i < state.windows.size(); i++) {
3533 const TouchedWindow& touchedWindow = state.windows[i];
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003534 dump += StringPrintf(INDENT4 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
3535 i, touchedWindow.windowHandle->getName().c_str(),
Jeff Brownf086ddb2014-02-11 14:28:48 -08003536 touchedWindow.pointerIds.value,
3537 touchedWindow.targetFlags);
3538 }
3539 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003540 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08003541 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003542 }
3543 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003544 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003545 }
3546
Arthur Hungb92218b2018-08-14 12:00:21 +08003547 if (!mWindowHandlesByDisplay.empty()) {
3548 for (auto& it : mWindowHandlesByDisplay) {
3549 const Vector<sp<InputWindowHandle>> windowHandles = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08003550 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", it.first);
Arthur Hungb92218b2018-08-14 12:00:21 +08003551 if (!windowHandles.isEmpty()) {
3552 dump += INDENT2 "Windows:\n";
3553 for (size_t i = 0; i < windowHandles.size(); i++) {
3554 const sp<InputWindowHandle>& windowHandle = windowHandles.itemAt(i);
3555 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003556
Arthur Hungb92218b2018-08-14 12:00:21 +08003557 dump += StringPrintf(INDENT3 "%zu: name='%s', displayId=%d, "
3558 "paused=%s, hasFocus=%s, hasWallpaper=%s, "
3559 "visible=%s, canReceiveKeys=%s, flags=0x%08x, type=0x%08x, layer=%d, "
Riddle Hsu39d4aa52018-11-30 20:46:53 +08003560 "frame=[%d,%d][%d,%d], globalScale=%f, windowScale=(%f,%f), "
Arthur Hungb92218b2018-08-14 12:00:21 +08003561 "touchableRegion=",
3562 i, windowInfo->name.c_str(), windowInfo->displayId,
3563 toString(windowInfo->paused),
3564 toString(windowInfo->hasFocus),
3565 toString(windowInfo->hasWallpaper),
3566 toString(windowInfo->visible),
3567 toString(windowInfo->canReceiveKeys),
3568 windowInfo->layoutParamsFlags, windowInfo->layoutParamsType,
3569 windowInfo->layer,
3570 windowInfo->frameLeft, windowInfo->frameTop,
3571 windowInfo->frameRight, windowInfo->frameBottom,
Robert Carre07e1032018-11-26 12:55:53 -08003572 windowInfo->globalScaleFactor,
3573 windowInfo->windowXScale, windowInfo->windowYScale);
Arthur Hungb92218b2018-08-14 12:00:21 +08003574 dumpRegion(dump, windowInfo->touchableRegion);
3575 dump += StringPrintf(", inputFeatures=0x%08x", windowInfo->inputFeatures);
3576 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%0.3fms\n",
3577 windowInfo->ownerPid, windowInfo->ownerUid,
3578 windowInfo->dispatchingTimeout / 1000000.0);
3579 }
3580 } else {
3581 dump += INDENT2 "Windows: <none>\n";
3582 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003583 }
3584 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08003585 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003586 }
3587
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003588 if (!mMonitoringChannelsByDisplay.empty()) {
3589 for (auto& it : mMonitoringChannelsByDisplay) {
3590 const Vector<sp<InputChannel>>& monitoringChannels = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08003591 dump += StringPrintf(INDENT "MonitoringChannels in display %" PRId32 ":\n", it.first);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003592 const size_t numChannels = monitoringChannels.size();
3593 for (size_t i = 0; i < numChannels; i++) {
3594 const sp<InputChannel>& channel = monitoringChannels[i];
3595 dump += StringPrintf(INDENT2 "%zu: '%s'\n", i, channel->getName().c_str());
3596 }
3597 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003598 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003599 dump += INDENT "MonitoringChannels: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003600 }
3601
3602 nsecs_t currentTime = now();
3603
3604 // Dump recently dispatched or dropped events from oldest to newest.
3605 if (!mRecentQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003606 dump += StringPrintf(INDENT "RecentQueue: length=%u\n", mRecentQueue.count());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003607 for (EventEntry* entry = mRecentQueue.head; entry; entry = entry->next) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003608 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003609 entry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003610 dump += StringPrintf(", age=%0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003611 (currentTime - entry->eventTime) * 0.000001f);
3612 }
3613 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003614 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003615 }
3616
3617 // Dump event currently being dispatched.
3618 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003619 dump += INDENT "PendingEvent:\n";
3620 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003621 mPendingEvent->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003622 dump += StringPrintf(", age=%0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003623 (currentTime - mPendingEvent->eventTime) * 0.000001f);
3624 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003625 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003626 }
3627
3628 // Dump inbound events from oldest to newest.
3629 if (!mInboundQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003630 dump += StringPrintf(INDENT "InboundQueue: length=%u\n", mInboundQueue.count());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003631 for (EventEntry* entry = mInboundQueue.head; entry; entry = entry->next) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003632 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003633 entry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003634 dump += StringPrintf(", age=%0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003635 (currentTime - entry->eventTime) * 0.000001f);
3636 }
3637 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003638 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003639 }
3640
Michael Wright78f24442014-08-06 15:55:28 -07003641 if (!mReplacedKeys.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003642 dump += INDENT "ReplacedKeys:\n";
Michael Wright78f24442014-08-06 15:55:28 -07003643 for (size_t i = 0; i < mReplacedKeys.size(); i++) {
3644 const KeyReplacement& replacement = mReplacedKeys.keyAt(i);
3645 int32_t newKeyCode = mReplacedKeys.valueAt(i);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003646 dump += StringPrintf(INDENT2 "%zu: originalKeyCode=%d, deviceId=%d, newKeyCode=%d\n",
Michael Wright78f24442014-08-06 15:55:28 -07003647 i, replacement.keyCode, replacement.deviceId, newKeyCode);
3648 }
3649 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003650 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07003651 }
3652
Michael Wrightd02c5b62014-02-10 15:10:22 -08003653 if (!mConnectionsByFd.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003654 dump += INDENT "Connections:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003655 for (size_t i = 0; i < mConnectionsByFd.size(); i++) {
3656 const sp<Connection>& connection = mConnectionsByFd.valueAt(i);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003657 dump += StringPrintf(INDENT2 "%zu: channelName='%s', windowName='%s', "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003658 "status=%s, monitor=%s, inputPublisherBlocked=%s\n",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08003659 i, connection->getInputChannelName().c_str(),
3660 connection->getWindowName().c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08003661 connection->getStatusLabel(), toString(connection->monitor),
3662 toString(connection->inputPublisherBlocked));
3663
3664 if (!connection->outboundQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003665 dump += StringPrintf(INDENT3 "OutboundQueue: length=%u\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003666 connection->outboundQueue.count());
3667 for (DispatchEntry* entry = connection->outboundQueue.head; entry;
3668 entry = entry->next) {
3669 dump.append(INDENT4);
3670 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003671 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, age=%0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003672 entry->targetFlags, entry->resolvedAction,
3673 (currentTime - entry->eventEntry->eventTime) * 0.000001f);
3674 }
3675 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003676 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003677 }
3678
3679 if (!connection->waitQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003680 dump += StringPrintf(INDENT3 "WaitQueue: length=%u\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003681 connection->waitQueue.count());
3682 for (DispatchEntry* entry = connection->waitQueue.head; entry;
3683 entry = entry->next) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003684 dump += INDENT4;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003685 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003686 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003687 "age=%0.1fms, wait=%0.1fms\n",
3688 entry->targetFlags, entry->resolvedAction,
3689 (currentTime - entry->eventEntry->eventTime) * 0.000001f,
3690 (currentTime - entry->deliveryTime) * 0.000001f);
3691 }
3692 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003693 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003694 }
3695 }
3696 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003697 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003698 }
3699
3700 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003701 dump += StringPrintf(INDENT "AppSwitch: pending, due in %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003702 (mAppSwitchDueTime - now()) / 1000000.0);
3703 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003704 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003705 }
3706
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003707 dump += INDENT "Configuration:\n";
3708 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003709 mConfig.keyRepeatDelay * 0.000001f);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003710 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003711 mConfig.keyRepeatTimeout * 0.000001f);
3712}
3713
Robert Carr803535b2018-08-02 16:38:15 -07003714status_t InputDispatcher::registerInputChannel(const sp<InputChannel>& inputChannel, int32_t displayId) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003715#if DEBUG_REGISTRATION
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003716 ALOGD("channel '%s' ~ registerInputChannel - displayId=%" PRId32,
3717 inputChannel->getName().c_str(), displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003718#endif
3719
3720 { // acquire lock
3721 AutoMutex _l(mLock);
3722
Robert Carr4e670e52018-08-15 13:26:12 -07003723 // If InputWindowHandle is null and displayId is not ADISPLAY_ID_NONE,
3724 // treat inputChannel as monitor channel for displayId.
3725 bool monitor = inputChannel->getToken() == nullptr && displayId != ADISPLAY_ID_NONE;
3726 if (monitor) {
3727 inputChannel->setToken(new BBinder());
3728 }
3729
Michael Wrightd02c5b62014-02-10 15:10:22 -08003730 if (getConnectionIndexLocked(inputChannel) >= 0) {
3731 ALOGW("Attempted to register already registered input channel '%s'",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003732 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003733 return BAD_VALUE;
3734 }
3735
Robert Carr803535b2018-08-02 16:38:15 -07003736 sp<Connection> connection = new Connection(inputChannel, monitor);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003737
3738 int fd = inputChannel->getFd();
3739 mConnectionsByFd.add(fd, connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07003740 mInputChannelsByToken[inputChannel->getToken()] = inputChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003741
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003742 // Store monitor channel by displayId.
Michael Wrightd02c5b62014-02-10 15:10:22 -08003743 if (monitor) {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003744 Vector<sp<InputChannel>>& monitoringChannels =
3745 mMonitoringChannelsByDisplay[displayId];
3746 monitoringChannels.push(inputChannel);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003747 }
3748
3749 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
3750 } // release lock
3751
3752 // Wake the looper because some connections have changed.
3753 mLooper->wake();
3754 return OK;
3755}
3756
3757status_t InputDispatcher::unregisterInputChannel(const sp<InputChannel>& inputChannel) {
3758#if DEBUG_REGISTRATION
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003759 ALOGD("channel '%s' ~ unregisterInputChannel", inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003760#endif
3761
3762 { // acquire lock
3763 AutoMutex _l(mLock);
3764
3765 status_t status = unregisterInputChannelLocked(inputChannel, false /*notify*/);
3766 if (status) {
3767 return status;
3768 }
3769 } // release lock
3770
3771 // Wake the poll loop because removing the connection may have changed the current
3772 // synchronization state.
3773 mLooper->wake();
3774 return OK;
3775}
3776
3777status_t InputDispatcher::unregisterInputChannelLocked(const sp<InputChannel>& inputChannel,
3778 bool notify) {
3779 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
3780 if (connectionIndex < 0) {
3781 ALOGW("Attempted to unregister already unregistered input channel '%s'",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003782 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003783 return BAD_VALUE;
3784 }
3785
3786 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
3787 mConnectionsByFd.removeItemsAt(connectionIndex);
3788
Robert Carr5c8a0262018-10-03 16:30:44 -07003789 mInputChannelsByToken.erase(inputChannel->getToken());
3790
Michael Wrightd02c5b62014-02-10 15:10:22 -08003791 if (connection->monitor) {
3792 removeMonitorChannelLocked(inputChannel);
3793 }
3794
3795 mLooper->removeFd(inputChannel->getFd());
3796
3797 nsecs_t currentTime = now();
3798 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
3799
3800 connection->status = Connection::STATUS_ZOMBIE;
3801 return OK;
3802}
3803
3804void InputDispatcher::removeMonitorChannelLocked(const sp<InputChannel>& inputChannel) {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003805 for (auto it = mMonitoringChannelsByDisplay.begin();
3806 it != mMonitoringChannelsByDisplay.end(); ) {
3807 Vector<sp<InputChannel>>& monitoringChannels = it->second;
3808 const size_t numChannels = monitoringChannels.size();
3809 for (size_t i = 0; i < numChannels; i++) {
3810 if (monitoringChannels[i] == inputChannel) {
3811 monitoringChannels.removeAt(i);
3812 break;
3813 }
3814 }
3815 if (monitoringChannels.empty()) {
3816 it = mMonitoringChannelsByDisplay.erase(it);
3817 } else {
3818 ++it;
3819 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003820 }
3821}
3822
3823ssize_t InputDispatcher::getConnectionIndexLocked(const sp<InputChannel>& inputChannel) {
Robert Carr4e670e52018-08-15 13:26:12 -07003824 if (inputChannel == nullptr) {
Arthur Hung3b413f22018-10-26 18:05:34 +08003825 return -1;
3826 }
3827
Robert Carr4e670e52018-08-15 13:26:12 -07003828 for (size_t i = 0; i < mConnectionsByFd.size(); i++) {
3829 sp<Connection> connection = mConnectionsByFd.valueAt(i);
3830 if (connection->inputChannel->getToken() == inputChannel->getToken()) {
3831 return i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003832 }
3833 }
Robert Carr4e670e52018-08-15 13:26:12 -07003834
Michael Wrightd02c5b62014-02-10 15:10:22 -08003835 return -1;
3836}
3837
3838void InputDispatcher::onDispatchCycleFinishedLocked(
3839 nsecs_t currentTime, const sp<Connection>& connection, uint32_t seq, bool handled) {
3840 CommandEntry* commandEntry = postCommandLocked(
3841 & InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
3842 commandEntry->connection = connection;
3843 commandEntry->eventTime = currentTime;
3844 commandEntry->seq = seq;
3845 commandEntry->handled = handled;
3846}
3847
3848void InputDispatcher::onDispatchCycleBrokenLocked(
3849 nsecs_t currentTime, const sp<Connection>& connection) {
3850 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08003851 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003852
3853 CommandEntry* commandEntry = postCommandLocked(
3854 & InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
3855 commandEntry->connection = connection;
3856}
3857
Robert Carrf759f162018-11-13 12:57:11 -08003858void InputDispatcher::onFocusChangedLocked(const sp<InputWindowHandle>& newFocus) {
3859 sp<IBinder> token = newFocus != nullptr ? newFocus->getToken() : nullptr;
3860 CommandEntry* commandEntry = postCommandLocked(
3861 & InputDispatcher::doNotifyFocusChangedLockedInterruptible);
3862 commandEntry->token = token;
3863}
3864
Michael Wrightd02c5b62014-02-10 15:10:22 -08003865void InputDispatcher::onANRLocked(
3866 nsecs_t currentTime, const sp<InputApplicationHandle>& applicationHandle,
3867 const sp<InputWindowHandle>& windowHandle,
3868 nsecs_t eventTime, nsecs_t waitStartTime, const char* reason) {
3869 float dispatchLatency = (currentTime - eventTime) * 0.000001f;
3870 float waitDuration = (currentTime - waitStartTime) * 0.000001f;
3871 ALOGI("Application is not responding: %s. "
3872 "It has been %0.1fms since event, %0.1fms since wait started. Reason: %s",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003873 getApplicationWindowLabelLocked(applicationHandle, windowHandle).c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08003874 dispatchLatency, waitDuration, reason);
3875
3876 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07003877 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003878 struct tm tm;
3879 localtime_r(&t, &tm);
3880 char timestr[64];
3881 strftime(timestr, sizeof(timestr), "%F %T", &tm);
3882 mLastANRState.clear();
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003883 mLastANRState += INDENT "ANR:\n";
3884 mLastANRState += StringPrintf(INDENT2 "Time: %s\n", timestr);
3885 mLastANRState += StringPrintf(INDENT2 "Window: %s\n",
3886 getApplicationWindowLabelLocked(applicationHandle, windowHandle).c_str());
3887 mLastANRState += StringPrintf(INDENT2 "DispatchLatency: %0.1fms\n", dispatchLatency);
3888 mLastANRState += StringPrintf(INDENT2 "WaitDuration: %0.1fms\n", waitDuration);
3889 mLastANRState += StringPrintf(INDENT2 "Reason: %s\n", reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003890 dumpDispatchStateLocked(mLastANRState);
3891
3892 CommandEntry* commandEntry = postCommandLocked(
3893 & InputDispatcher::doNotifyANRLockedInterruptible);
3894 commandEntry->inputApplicationHandle = applicationHandle;
Robert Carr5c8a0262018-10-03 16:30:44 -07003895 commandEntry->inputChannel = windowHandle != nullptr ?
3896 getInputChannelLocked(windowHandle->getToken()) : nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003897 commandEntry->reason = reason;
3898}
3899
3900void InputDispatcher::doNotifyConfigurationChangedInterruptible(
3901 CommandEntry* commandEntry) {
3902 mLock.unlock();
3903
3904 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
3905
3906 mLock.lock();
3907}
3908
3909void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(
3910 CommandEntry* commandEntry) {
3911 sp<Connection> connection = commandEntry->connection;
3912
3913 if (connection->status != Connection::STATUS_ZOMBIE) {
3914 mLock.unlock();
3915
Robert Carr803535b2018-08-02 16:38:15 -07003916 mPolicy->notifyInputChannelBroken(connection->inputChannel->getToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003917
3918 mLock.lock();
3919 }
3920}
3921
Robert Carrf759f162018-11-13 12:57:11 -08003922void InputDispatcher::doNotifyFocusChangedLockedInterruptible(
3923 CommandEntry* commandEntry) {
3924 sp<IBinder> token = commandEntry->token;
3925 mLock.unlock();
3926 mPolicy->notifyFocusChanged(token);
3927 mLock.lock();
3928}
3929
Michael Wrightd02c5b62014-02-10 15:10:22 -08003930void InputDispatcher::doNotifyANRLockedInterruptible(
3931 CommandEntry* commandEntry) {
3932 mLock.unlock();
3933
3934 nsecs_t newTimeout = mPolicy->notifyANR(
Robert Carr803535b2018-08-02 16:38:15 -07003935 commandEntry->inputApplicationHandle,
3936 commandEntry->inputChannel ? commandEntry->inputChannel->getToken() : nullptr,
Michael Wrightd02c5b62014-02-10 15:10:22 -08003937 commandEntry->reason);
3938
3939 mLock.lock();
3940
3941 resumeAfterTargetsNotReadyTimeoutLocked(newTimeout,
Robert Carr803535b2018-08-02 16:38:15 -07003942 commandEntry->inputChannel);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003943}
3944
3945void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
3946 CommandEntry* commandEntry) {
3947 KeyEntry* entry = commandEntry->keyEntry;
3948
3949 KeyEvent event;
3950 initializeKeyEvent(&event, entry);
3951
3952 mLock.unlock();
3953
Michael Wright2b3c3302018-03-02 17:19:13 +00003954 android::base::Timer t;
Robert Carr803535b2018-08-02 16:38:15 -07003955 sp<IBinder> token = commandEntry->inputChannel != nullptr ?
3956 commandEntry->inputChannel->getToken() : nullptr;
3957 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(token,
Michael Wrightd02c5b62014-02-10 15:10:22 -08003958 &event, entry->policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003959 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3960 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
3961 std::to_string(t.duration().count()).c_str());
3962 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003963
3964 mLock.lock();
3965
3966 if (delay < 0) {
3967 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
3968 } else if (!delay) {
3969 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
3970 } else {
3971 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
3972 entry->interceptKeyWakeupTime = now() + delay;
3973 }
3974 entry->release();
3975}
3976
3977void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(
3978 CommandEntry* commandEntry) {
3979 sp<Connection> connection = commandEntry->connection;
3980 nsecs_t finishTime = commandEntry->eventTime;
3981 uint32_t seq = commandEntry->seq;
3982 bool handled = commandEntry->handled;
3983
3984 // Handle post-event policy actions.
3985 DispatchEntry* dispatchEntry = connection->findWaitQueueEntry(seq);
3986 if (dispatchEntry) {
3987 nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
3988 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003989 std::string msg =
3990 StringPrintf("Window '%s' spent %0.1fms processing the last input event: ",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08003991 connection->getWindowName().c_str(), eventDuration * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003992 dispatchEntry->eventEntry->appendDescription(msg);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003993 ALOGI("%s", msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003994 }
3995
3996 bool restartEvent;
3997 if (dispatchEntry->eventEntry->type == EventEntry::TYPE_KEY) {
3998 KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry);
3999 restartEvent = afterKeyEventLockedInterruptible(connection,
4000 dispatchEntry, keyEntry, handled);
4001 } else if (dispatchEntry->eventEntry->type == EventEntry::TYPE_MOTION) {
4002 MotionEntry* motionEntry = static_cast<MotionEntry*>(dispatchEntry->eventEntry);
4003 restartEvent = afterMotionEventLockedInterruptible(connection,
4004 dispatchEntry, motionEntry, handled);
4005 } else {
4006 restartEvent = false;
4007 }
4008
4009 // Dequeue the event and start the next cycle.
4010 // Note that because the lock might have been released, it is possible that the
4011 // contents of the wait queue to have been drained, so we need to double-check
4012 // a few things.
4013 if (dispatchEntry == connection->findWaitQueueEntry(seq)) {
4014 connection->waitQueue.dequeue(dispatchEntry);
4015 traceWaitQueueLengthLocked(connection);
4016 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
4017 connection->outboundQueue.enqueueAtHead(dispatchEntry);
4018 traceOutboundQueueLengthLocked(connection);
4019 } else {
4020 releaseDispatchEntryLocked(dispatchEntry);
4021 }
4022 }
4023
4024 // Start the next dispatch cycle for this connection.
4025 startDispatchCycleLocked(now(), connection);
4026 }
4027}
4028
4029bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
4030 DispatchEntry* dispatchEntry, KeyEntry* keyEntry, bool handled) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004031 if (keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004032 if (!handled) {
4033 // Report the key as unhandled, since the fallback was not handled.
4034 mReporter->reportUnhandledKey(keyEntry->sequenceNum);
4035 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004036 return false;
4037 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004038
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004039 // Get the fallback key state.
4040 // Clear it out after dispatching the UP.
4041 int32_t originalKeyCode = keyEntry->keyCode;
4042 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
4043 if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
4044 connection->inputState.removeFallbackKey(originalKeyCode);
4045 }
4046
4047 if (handled || !dispatchEntry->hasForegroundTarget()) {
4048 // If the application handles the original key for which we previously
4049 // generated a fallback or if the window is not a foreground window,
4050 // then cancel the associated fallback key, if any.
4051 if (fallbackKeyCode != -1) {
4052 // Dispatch the unhandled key to the policy with the cancel flag.
Michael Wrightd02c5b62014-02-10 15:10:22 -08004053#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004054 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
Michael Wrightd02c5b62014-02-10 15:10:22 -08004055 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4056 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
4057 keyEntry->policyFlags);
4058#endif
4059 KeyEvent event;
4060 initializeKeyEvent(&event, keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004061 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004062
4063 mLock.unlock();
4064
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004065 mPolicy->dispatchUnhandledKey(connection->inputChannel->getToken(),
4066 &event, keyEntry->policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004067
4068 mLock.lock();
4069
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004070 // Cancel the fallback key.
4071 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004072 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004073 "application handled the original non-fallback key "
4074 "or is no longer a foreground target, "
4075 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004076 options.keyCode = fallbackKeyCode;
4077 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004078 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004079 connection->inputState.removeFallbackKey(originalKeyCode);
4080 }
4081 } else {
4082 // If the application did not handle a non-fallback key, first check
4083 // that we are in a good state to perform unhandled key event processing
4084 // Then ask the policy what to do with it.
4085 bool initialDown = keyEntry->action == AKEY_EVENT_ACTION_DOWN
4086 && keyEntry->repeatCount == 0;
4087 if (fallbackKeyCode == -1 && !initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004088#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004089 ALOGD("Unhandled key event: Skipping unhandled key event processing "
4090 "since this is not an initial down. "
4091 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4092 originalKeyCode, keyEntry->action, keyEntry->repeatCount,
4093 keyEntry->policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004094#endif
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004095 return false;
4096 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004097
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004098 // Dispatch the unhandled key to the policy.
4099#if DEBUG_OUTBOUND_EVENT_DETAILS
4100 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
4101 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4102 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
4103 keyEntry->policyFlags);
4104#endif
4105 KeyEvent event;
4106 initializeKeyEvent(&event, keyEntry);
4107
4108 mLock.unlock();
4109
4110 bool fallback = mPolicy->dispatchUnhandledKey(connection->inputChannel->getToken(),
4111 &event, keyEntry->policyFlags, &event);
4112
4113 mLock.lock();
4114
4115 if (connection->status != Connection::STATUS_NORMAL) {
4116 connection->inputState.removeFallbackKey(originalKeyCode);
4117 return false;
4118 }
4119
4120 // Latch the fallback keycode for this key on an initial down.
4121 // The fallback keycode cannot change at any other point in the lifecycle.
4122 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004123 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004124 fallbackKeyCode = event.getKeyCode();
4125 } else {
4126 fallbackKeyCode = AKEYCODE_UNKNOWN;
4127 }
4128 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
4129 }
4130
4131 ALOG_ASSERT(fallbackKeyCode != -1);
4132
4133 // Cancel the fallback key if the policy decides not to send it anymore.
4134 // We will continue to dispatch the key to the policy but we will no
4135 // longer dispatch a fallback key to the application.
4136 if (fallbackKeyCode != AKEYCODE_UNKNOWN
4137 && (!fallback || fallbackKeyCode != event.getKeyCode())) {
4138#if DEBUG_OUTBOUND_EVENT_DETAILS
4139 if (fallback) {
4140 ALOGD("Unhandled key event: Policy requested to send key %d"
4141 "as a fallback for %d, but on the DOWN it had requested "
4142 "to send %d instead. Fallback canceled.",
4143 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
4144 } else {
4145 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
4146 "but on the DOWN it had requested to send %d. "
4147 "Fallback canceled.",
4148 originalKeyCode, fallbackKeyCode);
4149 }
4150#endif
4151
4152 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
4153 "canceling fallback, policy no longer desires it");
4154 options.keyCode = fallbackKeyCode;
4155 synthesizeCancelationEventsForConnectionLocked(connection, options);
4156
4157 fallback = false;
4158 fallbackKeyCode = AKEYCODE_UNKNOWN;
4159 if (keyEntry->action != AKEY_EVENT_ACTION_UP) {
4160 connection->inputState.setFallbackKey(originalKeyCode,
4161 fallbackKeyCode);
4162 }
4163 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004164
4165#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004166 {
4167 std::string msg;
4168 const KeyedVector<int32_t, int32_t>& fallbackKeys =
4169 connection->inputState.getFallbackKeys();
4170 for (size_t i = 0; i < fallbackKeys.size(); i++) {
4171 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i),
4172 fallbackKeys.valueAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004173 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004174 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
4175 fallbackKeys.size(), msg.c_str());
4176 }
4177#endif
4178
4179 if (fallback) {
4180 // Restart the dispatch cycle using the fallback key.
4181 keyEntry->eventTime = event.getEventTime();
4182 keyEntry->deviceId = event.getDeviceId();
4183 keyEntry->source = event.getSource();
4184 keyEntry->displayId = event.getDisplayId();
4185 keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
4186 keyEntry->keyCode = fallbackKeyCode;
4187 keyEntry->scanCode = event.getScanCode();
4188 keyEntry->metaState = event.getMetaState();
4189 keyEntry->repeatCount = event.getRepeatCount();
4190 keyEntry->downTime = event.getDownTime();
4191 keyEntry->syntheticRepeat = false;
4192
4193#if DEBUG_OUTBOUND_EVENT_DETAILS
4194 ALOGD("Unhandled key event: Dispatching fallback key. "
4195 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
4196 originalKeyCode, fallbackKeyCode, keyEntry->metaState);
4197#endif
4198 return true; // restart the event
4199 } else {
4200#if DEBUG_OUTBOUND_EVENT_DETAILS
4201 ALOGD("Unhandled key event: No fallback key.");
4202#endif
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004203
4204 // Report the key as unhandled, since there is no fallback key.
4205 mReporter->reportUnhandledKey(keyEntry->sequenceNum);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004206 }
4207 }
4208 return false;
4209}
4210
4211bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
4212 DispatchEntry* dispatchEntry, MotionEntry* motionEntry, bool handled) {
4213 return false;
4214}
4215
4216void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
4217 mLock.unlock();
4218
4219 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
4220
4221 mLock.lock();
4222}
4223
4224void InputDispatcher::initializeKeyEvent(KeyEvent* event, const KeyEntry* entry) {
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004225 event->initialize(entry->deviceId, entry->source, entry->displayId, entry->action, entry->flags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004226 entry->keyCode, entry->scanCode, entry->metaState, entry->repeatCount,
4227 entry->downTime, entry->eventTime);
4228}
4229
4230void InputDispatcher::updateDispatchStatisticsLocked(nsecs_t currentTime, const EventEntry* entry,
4231 int32_t injectionResult, nsecs_t timeSpentWaitingForApplication) {
4232 // TODO Write some statistics about how long we spend waiting.
4233}
4234
4235void InputDispatcher::traceInboundQueueLengthLocked() {
4236 if (ATRACE_ENABLED()) {
4237 ATRACE_INT("iq", mInboundQueue.count());
4238 }
4239}
4240
4241void InputDispatcher::traceOutboundQueueLengthLocked(const sp<Connection>& connection) {
4242 if (ATRACE_ENABLED()) {
4243 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004244 snprintf(counterName, sizeof(counterName), "oq:%s", connection->getWindowName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004245 ATRACE_INT(counterName, connection->outboundQueue.count());
4246 }
4247}
4248
4249void InputDispatcher::traceWaitQueueLengthLocked(const sp<Connection>& connection) {
4250 if (ATRACE_ENABLED()) {
4251 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004252 snprintf(counterName, sizeof(counterName), "wq:%s", connection->getWindowName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004253 ATRACE_INT(counterName, connection->waitQueue.count());
4254 }
4255}
4256
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004257void InputDispatcher::dump(std::string& dump) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004258 AutoMutex _l(mLock);
4259
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004260 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004261 dumpDispatchStateLocked(dump);
4262
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004263 if (!mLastANRState.empty()) {
4264 dump += "\nInput Dispatcher State at time of last ANR:\n";
4265 dump += mLastANRState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004266 }
4267}
4268
4269void InputDispatcher::monitor() {
4270 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
4271 mLock.lock();
4272 mLooper->wake();
4273 mDispatcherIsAliveCondition.wait(mLock);
4274 mLock.unlock();
4275}
4276
4277
Michael Wrightd02c5b62014-02-10 15:10:22 -08004278// --- InputDispatcher::InjectionState ---
4279
4280InputDispatcher::InjectionState::InjectionState(int32_t injectorPid, int32_t injectorUid) :
4281 refCount(1),
4282 injectorPid(injectorPid), injectorUid(injectorUid),
4283 injectionResult(INPUT_EVENT_INJECTION_PENDING), injectionIsAsync(false),
4284 pendingForegroundDispatches(0) {
4285}
4286
4287InputDispatcher::InjectionState::~InjectionState() {
4288}
4289
4290void InputDispatcher::InjectionState::release() {
4291 refCount -= 1;
4292 if (refCount == 0) {
4293 delete this;
4294 } else {
4295 ALOG_ASSERT(refCount > 0);
4296 }
4297}
4298
4299
4300// --- InputDispatcher::EventEntry ---
4301
Prabir Pradhan42611e02018-11-27 14:04:02 -08004302InputDispatcher::EventEntry::EventEntry(uint32_t sequenceNum, int32_t type,
4303 nsecs_t eventTime, uint32_t policyFlags) :
4304 sequenceNum(sequenceNum), refCount(1), type(type), eventTime(eventTime),
4305 policyFlags(policyFlags), injectionState(nullptr), dispatchInProgress(false) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004306}
4307
4308InputDispatcher::EventEntry::~EventEntry() {
4309 releaseInjectionState();
4310}
4311
4312void InputDispatcher::EventEntry::release() {
4313 refCount -= 1;
4314 if (refCount == 0) {
4315 delete this;
4316 } else {
4317 ALOG_ASSERT(refCount > 0);
4318 }
4319}
4320
4321void InputDispatcher::EventEntry::releaseInjectionState() {
4322 if (injectionState) {
4323 injectionState->release();
Yi Kong9b14ac62018-07-17 13:48:38 -07004324 injectionState = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004325 }
4326}
4327
4328
4329// --- InputDispatcher::ConfigurationChangedEntry ---
4330
Prabir Pradhan42611e02018-11-27 14:04:02 -08004331InputDispatcher::ConfigurationChangedEntry::ConfigurationChangedEntry(
4332 uint32_t sequenceNum, nsecs_t eventTime) :
4333 EventEntry(sequenceNum, TYPE_CONFIGURATION_CHANGED, eventTime, 0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004334}
4335
4336InputDispatcher::ConfigurationChangedEntry::~ConfigurationChangedEntry() {
4337}
4338
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004339void InputDispatcher::ConfigurationChangedEntry::appendDescription(std::string& msg) const {
4340 msg += StringPrintf("ConfigurationChangedEvent(), policyFlags=0x%08x", policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004341}
4342
4343
4344// --- InputDispatcher::DeviceResetEntry ---
4345
Prabir Pradhan42611e02018-11-27 14:04:02 -08004346InputDispatcher::DeviceResetEntry::DeviceResetEntry(
4347 uint32_t sequenceNum, nsecs_t eventTime, int32_t deviceId) :
4348 EventEntry(sequenceNum, TYPE_DEVICE_RESET, eventTime, 0),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004349 deviceId(deviceId) {
4350}
4351
4352InputDispatcher::DeviceResetEntry::~DeviceResetEntry() {
4353}
4354
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004355void InputDispatcher::DeviceResetEntry::appendDescription(std::string& msg) const {
4356 msg += StringPrintf("DeviceResetEvent(deviceId=%d), policyFlags=0x%08x",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004357 deviceId, policyFlags);
4358}
4359
4360
4361// --- InputDispatcher::KeyEntry ---
4362
Prabir Pradhan42611e02018-11-27 14:04:02 -08004363InputDispatcher::KeyEntry::KeyEntry(uint32_t sequenceNum, nsecs_t eventTime,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004364 int32_t deviceId, uint32_t source, int32_t displayId, uint32_t policyFlags, int32_t action,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004365 int32_t flags, int32_t keyCode, int32_t scanCode, int32_t metaState,
4366 int32_t repeatCount, nsecs_t downTime) :
Prabir Pradhan42611e02018-11-27 14:04:02 -08004367 EventEntry(sequenceNum, TYPE_KEY, eventTime, policyFlags),
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004368 deviceId(deviceId), source(source), displayId(displayId), action(action), flags(flags),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004369 keyCode(keyCode), scanCode(scanCode), metaState(metaState),
4370 repeatCount(repeatCount), downTime(downTime),
4371 syntheticRepeat(false), interceptKeyResult(KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN),
4372 interceptKeyWakeupTime(0) {
4373}
4374
4375InputDispatcher::KeyEntry::~KeyEntry() {
4376}
4377
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004378void InputDispatcher::KeyEntry::appendDescription(std::string& msg) const {
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004379 msg += StringPrintf("KeyEvent(deviceId=%d, source=0x%08x, displayId=%" PRId32 ", action=%s, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08004380 "flags=0x%08x, keyCode=%d, scanCode=%d, metaState=0x%08x, "
4381 "repeatCount=%d), policyFlags=0x%08x",
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004382 deviceId, source, displayId, keyActionToString(action).c_str(), flags, keyCode,
Siarhei Vishniakoub48188a2018-03-01 20:55:47 -08004383 scanCode, metaState, repeatCount, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004384}
4385
4386void InputDispatcher::KeyEntry::recycle() {
4387 releaseInjectionState();
4388
4389 dispatchInProgress = false;
4390 syntheticRepeat = false;
4391 interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
4392 interceptKeyWakeupTime = 0;
4393}
4394
4395
4396// --- InputDispatcher::MotionEntry ---
4397
Prabir Pradhan42611e02018-11-27 14:04:02 -08004398InputDispatcher::MotionEntry::MotionEntry(uint32_t sequenceNum, nsecs_t eventTime, int32_t deviceId,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004399 uint32_t source, int32_t displayId, uint32_t policyFlags, int32_t action,
4400 int32_t actionButton,
Michael Wright7b159c92015-05-14 14:48:03 +01004401 int32_t flags, int32_t metaState, int32_t buttonState, int32_t edgeFlags,
4402 float xPrecision, float yPrecision, nsecs_t downTime,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004403 uint32_t pointerCount,
Jeff Brownf086ddb2014-02-11 14:28:48 -08004404 const PointerProperties* pointerProperties, const PointerCoords* pointerCoords,
4405 float xOffset, float yOffset) :
Prabir Pradhan42611e02018-11-27 14:04:02 -08004406 EventEntry(sequenceNum, TYPE_MOTION, eventTime, policyFlags),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004407 eventTime(eventTime),
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004408 deviceId(deviceId), source(source), displayId(displayId), action(action),
4409 actionButton(actionButton), flags(flags), metaState(metaState), buttonState(buttonState),
Michael Wright7b159c92015-05-14 14:48:03 +01004410 edgeFlags(edgeFlags), xPrecision(xPrecision), yPrecision(yPrecision),
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004411 downTime(downTime), pointerCount(pointerCount) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004412 for (uint32_t i = 0; i < pointerCount; i++) {
4413 this->pointerProperties[i].copyFrom(pointerProperties[i]);
4414 this->pointerCoords[i].copyFrom(pointerCoords[i]);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004415 if (xOffset || yOffset) {
4416 this->pointerCoords[i].applyOffset(xOffset, yOffset);
4417 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004418 }
4419}
4420
4421InputDispatcher::MotionEntry::~MotionEntry() {
4422}
4423
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004424void InputDispatcher::MotionEntry::appendDescription(std::string& msg) const {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004425 msg += StringPrintf("MotionEvent(deviceId=%d, source=0x%08x, displayId=%" PRId32
Siarhei Vishniakoub48188a2018-03-01 20:55:47 -08004426 ", action=%s, actionButton=0x%08x, flags=0x%08x, metaState=0x%08x, buttonState=0x%08x, "
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004427 "edgeFlags=0x%08x, xPrecision=%.1f, yPrecision=%.1f, pointers=[",
Siarhei Vishniakoub48188a2018-03-01 20:55:47 -08004428 deviceId, source, displayId, motionActionToString(action).c_str(), actionButton, flags,
4429 metaState, buttonState, edgeFlags, xPrecision, yPrecision);
4430
Michael Wrightd02c5b62014-02-10 15:10:22 -08004431 for (uint32_t i = 0; i < pointerCount; i++) {
4432 if (i) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004433 msg += ", ";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004434 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004435 msg += StringPrintf("%d: (%.1f, %.1f)", pointerProperties[i].id,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004436 pointerCoords[i].getX(), pointerCoords[i].getY());
4437 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004438 msg += StringPrintf("]), policyFlags=0x%08x", policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004439}
4440
4441
4442// --- InputDispatcher::DispatchEntry ---
4443
4444volatile int32_t InputDispatcher::DispatchEntry::sNextSeqAtomic;
4445
4446InputDispatcher::DispatchEntry::DispatchEntry(EventEntry* eventEntry,
Robert Carre07e1032018-11-26 12:55:53 -08004447 int32_t targetFlags, float xOffset, float yOffset, float globalScaleFactor,
4448 float windowXScale, float windowYScale) :
Michael Wrightd02c5b62014-02-10 15:10:22 -08004449 seq(nextSeq()),
4450 eventEntry(eventEntry), targetFlags(targetFlags),
Robert Carre07e1032018-11-26 12:55:53 -08004451 xOffset(xOffset), yOffset(yOffset), globalScaleFactor(globalScaleFactor),
4452 windowXScale(windowXScale), windowYScale(windowYScale),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004453 deliveryTime(0), resolvedAction(0), resolvedFlags(0) {
4454 eventEntry->refCount += 1;
4455}
4456
4457InputDispatcher::DispatchEntry::~DispatchEntry() {
4458 eventEntry->release();
4459}
4460
4461uint32_t InputDispatcher::DispatchEntry::nextSeq() {
4462 // Sequence number 0 is reserved and will never be returned.
4463 uint32_t seq;
4464 do {
4465 seq = android_atomic_inc(&sNextSeqAtomic);
4466 } while (!seq);
4467 return seq;
4468}
4469
4470
4471// --- InputDispatcher::InputState ---
4472
4473InputDispatcher::InputState::InputState() {
4474}
4475
4476InputDispatcher::InputState::~InputState() {
4477}
4478
4479bool InputDispatcher::InputState::isNeutral() const {
4480 return mKeyMementos.isEmpty() && mMotionMementos.isEmpty();
4481}
4482
4483bool InputDispatcher::InputState::isHovering(int32_t deviceId, uint32_t source,
4484 int32_t displayId) const {
4485 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4486 const MotionMemento& memento = mMotionMementos.itemAt(i);
4487 if (memento.deviceId == deviceId
4488 && memento.source == source
4489 && memento.displayId == displayId
4490 && memento.hovering) {
4491 return true;
4492 }
4493 }
4494 return false;
4495}
4496
4497bool InputDispatcher::InputState::trackKey(const KeyEntry* entry,
4498 int32_t action, int32_t flags) {
4499 switch (action) {
4500 case AKEY_EVENT_ACTION_UP: {
4501 if (entry->flags & AKEY_EVENT_FLAG_FALLBACK) {
4502 for (size_t i = 0; i < mFallbackKeys.size(); ) {
4503 if (mFallbackKeys.valueAt(i) == entry->keyCode) {
4504 mFallbackKeys.removeItemsAt(i);
4505 } else {
4506 i += 1;
4507 }
4508 }
4509 }
4510 ssize_t index = findKeyMemento(entry);
4511 if (index >= 0) {
4512 mKeyMementos.removeAt(index);
4513 return true;
4514 }
4515 /* FIXME: We can't just drop the key up event because that prevents creating
4516 * popup windows that are automatically shown when a key is held and then
4517 * dismissed when the key is released. The problem is that the popup will
4518 * not have received the original key down, so the key up will be considered
4519 * to be inconsistent with its observed state. We could perhaps handle this
4520 * by synthesizing a key down but that will cause other problems.
4521 *
4522 * So for now, allow inconsistent key up events to be dispatched.
4523 *
4524#if DEBUG_OUTBOUND_EVENT_DETAILS
4525 ALOGD("Dropping inconsistent key up event: deviceId=%d, source=%08x, "
4526 "keyCode=%d, scanCode=%d",
4527 entry->deviceId, entry->source, entry->keyCode, entry->scanCode);
4528#endif
4529 return false;
4530 */
4531 return true;
4532 }
4533
4534 case AKEY_EVENT_ACTION_DOWN: {
4535 ssize_t index = findKeyMemento(entry);
4536 if (index >= 0) {
4537 mKeyMementos.removeAt(index);
4538 }
4539 addKeyMemento(entry, flags);
4540 return true;
4541 }
4542
4543 default:
4544 return true;
4545 }
4546}
4547
4548bool InputDispatcher::InputState::trackMotion(const MotionEntry* entry,
4549 int32_t action, int32_t flags) {
4550 int32_t actionMasked = action & AMOTION_EVENT_ACTION_MASK;
4551 switch (actionMasked) {
4552 case AMOTION_EVENT_ACTION_UP:
4553 case AMOTION_EVENT_ACTION_CANCEL: {
4554 ssize_t index = findMotionMemento(entry, false /*hovering*/);
4555 if (index >= 0) {
4556 mMotionMementos.removeAt(index);
4557 return true;
4558 }
4559#if DEBUG_OUTBOUND_EVENT_DETAILS
4560 ALOGD("Dropping inconsistent motion up or cancel event: deviceId=%d, source=%08x, "
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004561 "displayId=%" PRId32 ", actionMasked=%d",
4562 entry->deviceId, entry->source, entry->displayId, actionMasked);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004563#endif
4564 return false;
4565 }
4566
4567 case AMOTION_EVENT_ACTION_DOWN: {
4568 ssize_t index = findMotionMemento(entry, false /*hovering*/);
4569 if (index >= 0) {
4570 mMotionMementos.removeAt(index);
4571 }
4572 addMotionMemento(entry, flags, false /*hovering*/);
4573 return true;
4574 }
4575
4576 case AMOTION_EVENT_ACTION_POINTER_UP:
4577 case AMOTION_EVENT_ACTION_POINTER_DOWN:
4578 case AMOTION_EVENT_ACTION_MOVE: {
Michael Wright38dcdff2014-03-19 12:06:10 -07004579 if (entry->source & AINPUT_SOURCE_CLASS_NAVIGATION) {
4580 // Trackballs can send MOVE events with a corresponding DOWN or UP. There's no need to
4581 // generate cancellation events for these since they're based in relative rather than
4582 // absolute units.
4583 return true;
4584 }
4585
Michael Wrightd02c5b62014-02-10 15:10:22 -08004586 ssize_t index = findMotionMemento(entry, false /*hovering*/);
Michael Wright38dcdff2014-03-19 12:06:10 -07004587
4588 if (entry->source & AINPUT_SOURCE_CLASS_JOYSTICK) {
4589 // Joysticks can send MOVE events without a corresponding DOWN or UP. Since all
4590 // joystick axes are normalized to [-1, 1] we can trust that 0 means it's neutral. Any
4591 // other value and we need to track the motion so we can send cancellation events for
4592 // anything generating fallback events (e.g. DPad keys for joystick movements).
4593 if (index >= 0) {
4594 if (entry->pointerCoords[0].isEmpty()) {
4595 mMotionMementos.removeAt(index);
4596 } else {
4597 MotionMemento& memento = mMotionMementos.editItemAt(index);
4598 memento.setPointers(entry);
4599 }
4600 } else if (!entry->pointerCoords[0].isEmpty()) {
4601 addMotionMemento(entry, flags, false /*hovering*/);
4602 }
4603
4604 // Joysticks and trackballs can send MOVE events without corresponding DOWN or UP.
4605 return true;
4606 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004607 if (index >= 0) {
4608 MotionMemento& memento = mMotionMementos.editItemAt(index);
4609 memento.setPointers(entry);
4610 return true;
4611 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004612#if DEBUG_OUTBOUND_EVENT_DETAILS
4613 ALOGD("Dropping inconsistent motion pointer up/down or move event: "
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004614 "deviceId=%d, source=%08x, displayId=%" PRId32 ", actionMasked=%d",
4615 entry->deviceId, entry->source, entry->displayId, actionMasked);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004616#endif
4617 return false;
4618 }
4619
4620 case AMOTION_EVENT_ACTION_HOVER_EXIT: {
4621 ssize_t index = findMotionMemento(entry, true /*hovering*/);
4622 if (index >= 0) {
4623 mMotionMementos.removeAt(index);
4624 return true;
4625 }
4626#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004627 ALOGD("Dropping inconsistent motion hover exit event: deviceId=%d, source=%08x, "
4628 "displayId=%" PRId32,
4629 entry->deviceId, entry->source, entry->displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004630#endif
4631 return false;
4632 }
4633
4634 case AMOTION_EVENT_ACTION_HOVER_ENTER:
4635 case AMOTION_EVENT_ACTION_HOVER_MOVE: {
4636 ssize_t index = findMotionMemento(entry, true /*hovering*/);
4637 if (index >= 0) {
4638 mMotionMementos.removeAt(index);
4639 }
4640 addMotionMemento(entry, flags, true /*hovering*/);
4641 return true;
4642 }
4643
4644 default:
4645 return true;
4646 }
4647}
4648
4649ssize_t InputDispatcher::InputState::findKeyMemento(const KeyEntry* entry) const {
4650 for (size_t i = 0; i < mKeyMementos.size(); i++) {
4651 const KeyMemento& memento = mKeyMementos.itemAt(i);
4652 if (memento.deviceId == entry->deviceId
4653 && memento.source == entry->source
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004654 && memento.displayId == entry->displayId
Michael Wrightd02c5b62014-02-10 15:10:22 -08004655 && memento.keyCode == entry->keyCode
4656 && memento.scanCode == entry->scanCode) {
4657 return i;
4658 }
4659 }
4660 return -1;
4661}
4662
4663ssize_t InputDispatcher::InputState::findMotionMemento(const MotionEntry* entry,
4664 bool hovering) const {
4665 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4666 const MotionMemento& memento = mMotionMementos.itemAt(i);
4667 if (memento.deviceId == entry->deviceId
4668 && memento.source == entry->source
4669 && memento.displayId == entry->displayId
4670 && memento.hovering == hovering) {
4671 return i;
4672 }
4673 }
4674 return -1;
4675}
4676
4677void InputDispatcher::InputState::addKeyMemento(const KeyEntry* entry, int32_t flags) {
4678 mKeyMementos.push();
4679 KeyMemento& memento = mKeyMementos.editTop();
4680 memento.deviceId = entry->deviceId;
4681 memento.source = entry->source;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004682 memento.displayId = entry->displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004683 memento.keyCode = entry->keyCode;
4684 memento.scanCode = entry->scanCode;
4685 memento.metaState = entry->metaState;
4686 memento.flags = flags;
4687 memento.downTime = entry->downTime;
4688 memento.policyFlags = entry->policyFlags;
4689}
4690
4691void InputDispatcher::InputState::addMotionMemento(const MotionEntry* entry,
4692 int32_t flags, bool hovering) {
4693 mMotionMementos.push();
4694 MotionMemento& memento = mMotionMementos.editTop();
4695 memento.deviceId = entry->deviceId;
4696 memento.source = entry->source;
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004697 memento.displayId = entry->displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004698 memento.flags = flags;
4699 memento.xPrecision = entry->xPrecision;
4700 memento.yPrecision = entry->yPrecision;
4701 memento.downTime = entry->downTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004702 memento.setPointers(entry);
4703 memento.hovering = hovering;
4704 memento.policyFlags = entry->policyFlags;
4705}
4706
4707void InputDispatcher::InputState::MotionMemento::setPointers(const MotionEntry* entry) {
4708 pointerCount = entry->pointerCount;
4709 for (uint32_t i = 0; i < entry->pointerCount; i++) {
4710 pointerProperties[i].copyFrom(entry->pointerProperties[i]);
4711 pointerCoords[i].copyFrom(entry->pointerCoords[i]);
4712 }
4713}
4714
4715void InputDispatcher::InputState::synthesizeCancelationEvents(nsecs_t currentTime,
4716 Vector<EventEntry*>& outEvents, const CancelationOptions& options) {
4717 for (size_t i = 0; i < mKeyMementos.size(); i++) {
4718 const KeyMemento& memento = mKeyMementos.itemAt(i);
4719 if (shouldCancelKey(memento, options)) {
Prabir Pradhan42611e02018-11-27 14:04:02 -08004720 outEvents.push(new KeyEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, currentTime,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004721 memento.deviceId, memento.source, memento.displayId, memento.policyFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004722 AKEY_EVENT_ACTION_UP, memento.flags | AKEY_EVENT_FLAG_CANCELED,
4723 memento.keyCode, memento.scanCode, memento.metaState, 0, memento.downTime));
4724 }
4725 }
4726
4727 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4728 const MotionMemento& memento = mMotionMementos.itemAt(i);
4729 if (shouldCancelMotion(memento, options)) {
Prabir Pradhan42611e02018-11-27 14:04:02 -08004730 outEvents.push(new MotionEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, currentTime,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004731 memento.deviceId, memento.source, memento.displayId, memento.policyFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004732 memento.hovering
4733 ? AMOTION_EVENT_ACTION_HOVER_EXIT
4734 : AMOTION_EVENT_ACTION_CANCEL,
Michael Wright7b159c92015-05-14 14:48:03 +01004735 memento.flags, 0, 0, 0, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004736 memento.xPrecision, memento.yPrecision, memento.downTime,
Jeff Brownf086ddb2014-02-11 14:28:48 -08004737 memento.pointerCount, memento.pointerProperties, memento.pointerCoords,
4738 0, 0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004739 }
4740 }
4741}
4742
4743void InputDispatcher::InputState::clear() {
4744 mKeyMementos.clear();
4745 mMotionMementos.clear();
4746 mFallbackKeys.clear();
4747}
4748
4749void InputDispatcher::InputState::copyPointerStateTo(InputState& other) const {
4750 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4751 const MotionMemento& memento = mMotionMementos.itemAt(i);
4752 if (memento.source & AINPUT_SOURCE_CLASS_POINTER) {
4753 for (size_t j = 0; j < other.mMotionMementos.size(); ) {
4754 const MotionMemento& otherMemento = other.mMotionMementos.itemAt(j);
4755 if (memento.deviceId == otherMemento.deviceId
4756 && memento.source == otherMemento.source
4757 && memento.displayId == otherMemento.displayId) {
4758 other.mMotionMementos.removeAt(j);
4759 } else {
4760 j += 1;
4761 }
4762 }
4763 other.mMotionMementos.push(memento);
4764 }
4765 }
4766}
4767
4768int32_t InputDispatcher::InputState::getFallbackKey(int32_t originalKeyCode) {
4769 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
4770 return index >= 0 ? mFallbackKeys.valueAt(index) : -1;
4771}
4772
4773void InputDispatcher::InputState::setFallbackKey(int32_t originalKeyCode,
4774 int32_t fallbackKeyCode) {
4775 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
4776 if (index >= 0) {
4777 mFallbackKeys.replaceValueAt(index, fallbackKeyCode);
4778 } else {
4779 mFallbackKeys.add(originalKeyCode, fallbackKeyCode);
4780 }
4781}
4782
4783void InputDispatcher::InputState::removeFallbackKey(int32_t originalKeyCode) {
4784 mFallbackKeys.removeItem(originalKeyCode);
4785}
4786
4787bool InputDispatcher::InputState::shouldCancelKey(const KeyMemento& memento,
4788 const CancelationOptions& options) {
4789 if (options.keyCode != -1 && memento.keyCode != options.keyCode) {
4790 return false;
4791 }
4792
4793 if (options.deviceId != -1 && memento.deviceId != options.deviceId) {
4794 return false;
4795 }
4796
4797 switch (options.mode) {
4798 case CancelationOptions::CANCEL_ALL_EVENTS:
4799 case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
4800 return true;
4801 case CancelationOptions::CANCEL_FALLBACK_EVENTS:
4802 return memento.flags & AKEY_EVENT_FLAG_FALLBACK;
Tiger Huang721e26f2018-07-24 22:26:19 +08004803 case CancelationOptions::CANCEL_DISPLAY_UNSPECIFIED_EVENTS:
4804 return memento.displayId == ADISPLAY_ID_NONE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004805 default:
4806 return false;
4807 }
4808}
4809
4810bool InputDispatcher::InputState::shouldCancelMotion(const MotionMemento& memento,
4811 const CancelationOptions& options) {
4812 if (options.deviceId != -1 && memento.deviceId != options.deviceId) {
4813 return false;
4814 }
4815
4816 switch (options.mode) {
4817 case CancelationOptions::CANCEL_ALL_EVENTS:
4818 return true;
4819 case CancelationOptions::CANCEL_POINTER_EVENTS:
4820 return memento.source & AINPUT_SOURCE_CLASS_POINTER;
4821 case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
4822 return !(memento.source & AINPUT_SOURCE_CLASS_POINTER);
Tiger Huang721e26f2018-07-24 22:26:19 +08004823 case CancelationOptions::CANCEL_DISPLAY_UNSPECIFIED_EVENTS:
4824 return memento.displayId == ADISPLAY_ID_NONE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004825 default:
4826 return false;
4827 }
4828}
4829
4830
4831// --- InputDispatcher::Connection ---
4832
Robert Carr803535b2018-08-02 16:38:15 -07004833InputDispatcher::Connection::Connection(const sp<InputChannel>& inputChannel, bool monitor) :
4834 status(STATUS_NORMAL), inputChannel(inputChannel),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004835 monitor(monitor),
4836 inputPublisher(inputChannel), inputPublisherBlocked(false) {
4837}
4838
4839InputDispatcher::Connection::~Connection() {
4840}
4841
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004842const std::string InputDispatcher::Connection::getWindowName() const {
Robert Carr803535b2018-08-02 16:38:15 -07004843 if (inputChannel != nullptr) {
4844 return inputChannel->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004845 }
4846 if (monitor) {
4847 return "monitor";
4848 }
4849 return "?";
4850}
4851
4852const char* InputDispatcher::Connection::getStatusLabel() const {
4853 switch (status) {
4854 case STATUS_NORMAL:
4855 return "NORMAL";
4856
4857 case STATUS_BROKEN:
4858 return "BROKEN";
4859
4860 case STATUS_ZOMBIE:
4861 return "ZOMBIE";
4862
4863 default:
4864 return "UNKNOWN";
4865 }
4866}
4867
4868InputDispatcher::DispatchEntry* InputDispatcher::Connection::findWaitQueueEntry(uint32_t seq) {
Yi Kong9b14ac62018-07-17 13:48:38 -07004869 for (DispatchEntry* entry = waitQueue.head; entry != nullptr; entry = entry->next) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004870 if (entry->seq == seq) {
4871 return entry;
4872 }
4873 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004874 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004875}
4876
4877
4878// --- InputDispatcher::CommandEntry ---
4879
4880InputDispatcher::CommandEntry::CommandEntry(Command command) :
Yi Kong9b14ac62018-07-17 13:48:38 -07004881 command(command), eventTime(0), keyEntry(nullptr), userActivityEventType(0),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004882 seq(0), handled(false) {
4883}
4884
4885InputDispatcher::CommandEntry::~CommandEntry() {
4886}
4887
4888
4889// --- InputDispatcher::TouchState ---
4890
4891InputDispatcher::TouchState::TouchState() :
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004892 down(false), split(false), deviceId(-1), source(0), displayId(ADISPLAY_ID_NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004893}
4894
4895InputDispatcher::TouchState::~TouchState() {
4896}
4897
4898void InputDispatcher::TouchState::reset() {
4899 down = false;
4900 split = false;
4901 deviceId = -1;
4902 source = 0;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004903 displayId = ADISPLAY_ID_NONE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004904 windows.clear();
4905}
4906
4907void InputDispatcher::TouchState::copyFrom(const TouchState& other) {
4908 down = other.down;
4909 split = other.split;
4910 deviceId = other.deviceId;
4911 source = other.source;
4912 displayId = other.displayId;
4913 windows = other.windows;
4914}
4915
4916void InputDispatcher::TouchState::addOrUpdateWindow(const sp<InputWindowHandle>& windowHandle,
4917 int32_t targetFlags, BitSet32 pointerIds) {
4918 if (targetFlags & InputTarget::FLAG_SPLIT) {
4919 split = true;
4920 }
4921
4922 for (size_t i = 0; i < windows.size(); i++) {
4923 TouchedWindow& touchedWindow = windows.editItemAt(i);
4924 if (touchedWindow.windowHandle == windowHandle) {
4925 touchedWindow.targetFlags |= targetFlags;
4926 if (targetFlags & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
4927 touchedWindow.targetFlags &= ~InputTarget::FLAG_DISPATCH_AS_IS;
4928 }
4929 touchedWindow.pointerIds.value |= pointerIds.value;
4930 return;
4931 }
4932 }
4933
4934 windows.push();
4935
4936 TouchedWindow& touchedWindow = windows.editTop();
4937 touchedWindow.windowHandle = windowHandle;
4938 touchedWindow.targetFlags = targetFlags;
4939 touchedWindow.pointerIds = pointerIds;
4940}
4941
4942void InputDispatcher::TouchState::removeWindow(const sp<InputWindowHandle>& windowHandle) {
4943 for (size_t i = 0; i < windows.size(); i++) {
4944 if (windows.itemAt(i).windowHandle == windowHandle) {
4945 windows.removeAt(i);
4946 return;
4947 }
4948 }
4949}
4950
Robert Carr803535b2018-08-02 16:38:15 -07004951void InputDispatcher::TouchState::removeWindowByToken(const sp<IBinder>& token) {
4952 for (size_t i = 0; i < windows.size(); i++) {
Robert Carr5c8a0262018-10-03 16:30:44 -07004953 if (windows.itemAt(i).windowHandle->getToken() == token) {
Robert Carr803535b2018-08-02 16:38:15 -07004954 windows.removeAt(i);
4955 return;
4956 }
4957 }
4958}
4959
Michael Wrightd02c5b62014-02-10 15:10:22 -08004960void InputDispatcher::TouchState::filterNonAsIsTouchWindows() {
4961 for (size_t i = 0 ; i < windows.size(); ) {
4962 TouchedWindow& window = windows.editItemAt(i);
4963 if (window.targetFlags & (InputTarget::FLAG_DISPATCH_AS_IS
4964 | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER)) {
4965 window.targetFlags &= ~InputTarget::FLAG_DISPATCH_MASK;
4966 window.targetFlags |= InputTarget::FLAG_DISPATCH_AS_IS;
4967 i += 1;
4968 } else {
4969 windows.removeAt(i);
4970 }
4971 }
4972}
4973
4974sp<InputWindowHandle> InputDispatcher::TouchState::getFirstForegroundWindowHandle() const {
4975 for (size_t i = 0; i < windows.size(); i++) {
4976 const TouchedWindow& window = windows.itemAt(i);
4977 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
4978 return window.windowHandle;
4979 }
4980 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004981 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004982}
4983
4984bool InputDispatcher::TouchState::isSlippery() const {
4985 // Must have exactly one foreground window.
4986 bool haveSlipperyForegroundWindow = false;
4987 for (size_t i = 0; i < windows.size(); i++) {
4988 const TouchedWindow& window = windows.itemAt(i);
4989 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
4990 if (haveSlipperyForegroundWindow
4991 || !(window.windowHandle->getInfo()->layoutParamsFlags
4992 & InputWindowInfo::FLAG_SLIPPERY)) {
4993 return false;
4994 }
4995 haveSlipperyForegroundWindow = true;
4996 }
4997 }
4998 return haveSlipperyForegroundWindow;
4999}
5000
5001
5002// --- InputDispatcherThread ---
5003
5004InputDispatcherThread::InputDispatcherThread(const sp<InputDispatcherInterface>& dispatcher) :
5005 Thread(/*canCallJava*/ true), mDispatcher(dispatcher) {
5006}
5007
5008InputDispatcherThread::~InputDispatcherThread() {
5009}
5010
5011bool InputDispatcherThread::threadLoop() {
5012 mDispatcher->dispatchOnce();
5013 return true;
5014}
5015
5016} // namespace android