blob: 6173452166739f81248eb354fcbbd8ef03a23825 [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;
2389 sp<InputWindowHandle> windowHandle = getWindowHandleLocked(connection->inputChannel);
Yi Kong9b14ac62018-07-17 13:48:38 -07002390 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002391 const InputWindowInfo* windowInfo = windowHandle->getInfo();
2392 target.xOffset = -windowInfo->frameLeft;
2393 target.yOffset = -windowInfo->frameTop;
Robert Carre07e1032018-11-26 12:55:53 -08002394 target.globalScaleFactor = windowInfo->globalScaleFactor;
2395 target.windowXScale = windowInfo->windowXScale;
2396 target.windowYScale = windowInfo->windowYScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002397 } else {
2398 target.xOffset = 0;
2399 target.yOffset = 0;
Robert Carre07e1032018-11-26 12:55:53 -08002400 target.globalScaleFactor = 1.0f;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002401 }
2402 target.inputChannel = connection->inputChannel;
2403 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
2404
2405 enqueueDispatchEntryLocked(connection, cancelationEventEntry, // increments ref
2406 &target, InputTarget::FLAG_DISPATCH_AS_IS);
2407
2408 cancelationEventEntry->release();
2409 }
2410
2411 startDispatchCycleLocked(currentTime, connection);
2412 }
2413}
2414
2415InputDispatcher::MotionEntry*
2416InputDispatcher::splitMotionEvent(const MotionEntry* originalMotionEntry, BitSet32 pointerIds) {
2417 ALOG_ASSERT(pointerIds.value != 0);
2418
2419 uint32_t splitPointerIndexMap[MAX_POINTERS];
2420 PointerProperties splitPointerProperties[MAX_POINTERS];
2421 PointerCoords splitPointerCoords[MAX_POINTERS];
2422
2423 uint32_t originalPointerCount = originalMotionEntry->pointerCount;
2424 uint32_t splitPointerCount = 0;
2425
2426 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
2427 originalPointerIndex++) {
2428 const PointerProperties& pointerProperties =
2429 originalMotionEntry->pointerProperties[originalPointerIndex];
2430 uint32_t pointerId = uint32_t(pointerProperties.id);
2431 if (pointerIds.hasBit(pointerId)) {
2432 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
2433 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
2434 splitPointerCoords[splitPointerCount].copyFrom(
2435 originalMotionEntry->pointerCoords[originalPointerIndex]);
2436 splitPointerCount += 1;
2437 }
2438 }
2439
2440 if (splitPointerCount != pointerIds.count()) {
2441 // This is bad. We are missing some of the pointers that we expected to deliver.
2442 // Most likely this indicates that we received an ACTION_MOVE events that has
2443 // different pointer ids than we expected based on the previous ACTION_DOWN
2444 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
2445 // in this way.
2446 ALOGW("Dropping split motion event because the pointer count is %d but "
2447 "we expected there to be %d pointers. This probably means we received "
2448 "a broken sequence of pointer ids from the input device.",
2449 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07002450 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002451 }
2452
2453 int32_t action = originalMotionEntry->action;
2454 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
2455 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
2456 || maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2457 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
2458 const PointerProperties& pointerProperties =
2459 originalMotionEntry->pointerProperties[originalPointerIndex];
2460 uint32_t pointerId = uint32_t(pointerProperties.id);
2461 if (pointerIds.hasBit(pointerId)) {
2462 if (pointerIds.count() == 1) {
2463 // The first/last pointer went down/up.
2464 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
2465 ? AMOTION_EVENT_ACTION_DOWN : AMOTION_EVENT_ACTION_UP;
2466 } else {
2467 // A secondary pointer went down/up.
2468 uint32_t splitPointerIndex = 0;
2469 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
2470 splitPointerIndex += 1;
2471 }
2472 action = maskedAction | (splitPointerIndex
2473 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
2474 }
2475 } else {
2476 // An unrelated pointer changed.
2477 action = AMOTION_EVENT_ACTION_MOVE;
2478 }
2479 }
2480
2481 MotionEntry* splitMotionEntry = new MotionEntry(
Prabir Pradhan42611e02018-11-27 14:04:02 -08002482 originalMotionEntry->sequenceNum,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002483 originalMotionEntry->eventTime,
2484 originalMotionEntry->deviceId,
2485 originalMotionEntry->source,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002486 originalMotionEntry->displayId,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002487 originalMotionEntry->policyFlags,
2488 action,
Michael Wright7b159c92015-05-14 14:48:03 +01002489 originalMotionEntry->actionButton,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002490 originalMotionEntry->flags,
2491 originalMotionEntry->metaState,
2492 originalMotionEntry->buttonState,
2493 originalMotionEntry->edgeFlags,
2494 originalMotionEntry->xPrecision,
2495 originalMotionEntry->yPrecision,
2496 originalMotionEntry->downTime,
Jeff Brownf086ddb2014-02-11 14:28:48 -08002497 splitPointerCount, splitPointerProperties, splitPointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002498
2499 if (originalMotionEntry->injectionState) {
2500 splitMotionEntry->injectionState = originalMotionEntry->injectionState;
2501 splitMotionEntry->injectionState->refCount += 1;
2502 }
2503
2504 return splitMotionEntry;
2505}
2506
2507void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
2508#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002509 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002510#endif
2511
2512 bool needWake;
2513 { // acquire lock
2514 AutoMutex _l(mLock);
2515
Prabir Pradhan42611e02018-11-27 14:04:02 -08002516 ConfigurationChangedEntry* newEntry =
2517 new ConfigurationChangedEntry(args->sequenceNum, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002518 needWake = enqueueInboundEventLocked(newEntry);
2519 } // release lock
2520
2521 if (needWake) {
2522 mLooper->wake();
2523 }
2524}
2525
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002526/**
2527 * If one of the meta shortcuts is detected, process them here:
2528 * Meta + Backspace -> generate BACK
2529 * Meta + Enter -> generate HOME
2530 * This will potentially overwrite keyCode and metaState.
2531 */
2532void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
2533 int32_t& keyCode, int32_t& metaState) {
2534 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
2535 int32_t newKeyCode = AKEYCODE_UNKNOWN;
2536 if (keyCode == AKEYCODE_DEL) {
2537 newKeyCode = AKEYCODE_BACK;
2538 } else if (keyCode == AKEYCODE_ENTER) {
2539 newKeyCode = AKEYCODE_HOME;
2540 }
2541 if (newKeyCode != AKEYCODE_UNKNOWN) {
2542 AutoMutex _l(mLock);
2543 struct KeyReplacement replacement = {keyCode, deviceId};
2544 mReplacedKeys.add(replacement, newKeyCode);
2545 keyCode = newKeyCode;
2546 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
2547 }
2548 } else if (action == AKEY_EVENT_ACTION_UP) {
2549 // In order to maintain a consistent stream of up and down events, check to see if the key
2550 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
2551 // even if the modifier was released between the down and the up events.
2552 AutoMutex _l(mLock);
2553 struct KeyReplacement replacement = {keyCode, deviceId};
2554 ssize_t index = mReplacedKeys.indexOfKey(replacement);
2555 if (index >= 0) {
2556 keyCode = mReplacedKeys.valueAt(index);
2557 mReplacedKeys.removeItemsAt(index);
2558 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
2559 }
2560 }
2561}
2562
Michael Wrightd02c5b62014-02-10 15:10:22 -08002563void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
2564#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002565 ALOGD("notifyKey - eventTime=%" PRId64
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002566 ", deviceId=%d, source=0x%x, displayId=%" PRId32 "policyFlags=0x%x, action=0x%x, "
Arthur Hung82a4cad2018-11-15 12:10:30 +08002567 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002568 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002569 args->action, args->flags, args->keyCode, args->scanCode,
Arthur Hung82a4cad2018-11-15 12:10:30 +08002570 args->metaState, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002571#endif
2572 if (!validateKeyEvent(args->action)) {
2573 return;
2574 }
2575
2576 uint32_t policyFlags = args->policyFlags;
2577 int32_t flags = args->flags;
2578 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07002579 // InputDispatcher tracks and generates key repeats on behalf of
2580 // whatever notifies it, so repeatCount should always be set to 0
2581 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002582 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
2583 policyFlags |= POLICY_FLAG_VIRTUAL;
2584 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
2585 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002586 if (policyFlags & POLICY_FLAG_FUNCTION) {
2587 metaState |= AMETA_FUNCTION_ON;
2588 }
2589
2590 policyFlags |= POLICY_FLAG_TRUSTED;
2591
Michael Wright78f24442014-08-06 15:55:28 -07002592 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002593 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07002594
Michael Wrightd02c5b62014-02-10 15:10:22 -08002595 KeyEvent event;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002596 event.initialize(args->deviceId, args->source, args->displayId, args->action,
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07002597 flags, keyCode, args->scanCode, metaState, repeatCount,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002598 args->downTime, args->eventTime);
2599
Michael Wright2b3c3302018-03-02 17:19:13 +00002600 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002601 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002602 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2603 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
2604 std::to_string(t.duration().count()).c_str());
2605 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002606
Michael Wrightd02c5b62014-02-10 15:10:22 -08002607 bool needWake;
2608 { // acquire lock
2609 mLock.lock();
2610
2611 if (shouldSendKeyToInputFilterLocked(args)) {
2612 mLock.unlock();
2613
2614 policyFlags |= POLICY_FLAG_FILTERED;
2615 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2616 return; // event was consumed by the filter
2617 }
2618
2619 mLock.lock();
2620 }
2621
Prabir Pradhan42611e02018-11-27 14:04:02 -08002622 KeyEntry* newEntry = new KeyEntry(args->sequenceNum, args->eventTime,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002623 args->deviceId, args->source, args->displayId, policyFlags,
Michael Wright78f24442014-08-06 15:55:28 -07002624 args->action, flags, keyCode, args->scanCode,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002625 metaState, repeatCount, args->downTime);
2626
2627 needWake = enqueueInboundEventLocked(newEntry);
2628 mLock.unlock();
2629 } // release lock
2630
2631 if (needWake) {
2632 mLooper->wake();
2633 }
2634}
2635
2636bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
2637 return mInputFilterEnabled;
2638}
2639
2640void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
2641#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002642 ALOGD("notifyMotion - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
2643 ", policyFlags=0x%x, "
Michael Wright7b159c92015-05-14 14:48:03 +01002644 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x,"
Arthur Hung82a4cad2018-11-15 12:10:30 +08002645 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
2646 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002647 args->action, args->actionButton, args->flags, args->metaState, args->buttonState,
Arthur Hung82a4cad2018-11-15 12:10:30 +08002648 args->edgeFlags, args->xPrecision, args->yPrecision, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002649 for (uint32_t i = 0; i < args->pointerCount; i++) {
2650 ALOGD(" Pointer %d: id=%d, toolType=%d, "
2651 "x=%f, y=%f, pressure=%f, size=%f, "
2652 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
2653 "orientation=%f",
2654 i, args->pointerProperties[i].id,
2655 args->pointerProperties[i].toolType,
2656 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
2657 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
2658 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
2659 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
2660 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
2661 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
2662 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
2663 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
2664 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
2665 }
2666#endif
Michael Wright7b159c92015-05-14 14:48:03 +01002667 if (!validateMotionEvent(args->action, args->actionButton,
2668 args->pointerCount, args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002669 return;
2670 }
2671
2672 uint32_t policyFlags = args->policyFlags;
2673 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00002674
2675 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002676 mPolicy->interceptMotionBeforeQueueing(args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002677 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2678 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
2679 std::to_string(t.duration().count()).c_str());
2680 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002681
2682 bool needWake;
2683 { // acquire lock
2684 mLock.lock();
2685
2686 if (shouldSendMotionToInputFilterLocked(args)) {
2687 mLock.unlock();
2688
2689 MotionEvent event;
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002690 event.initialize(args->deviceId, args->source, args->displayId,
2691 args->action, args->actionButton,
Michael Wright7b159c92015-05-14 14:48:03 +01002692 args->flags, args->edgeFlags, args->metaState, args->buttonState,
2693 0, 0, args->xPrecision, args->yPrecision,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002694 args->downTime, args->eventTime,
2695 args->pointerCount, args->pointerProperties, args->pointerCoords);
2696
2697 policyFlags |= POLICY_FLAG_FILTERED;
2698 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2699 return; // event was consumed by the filter
2700 }
2701
2702 mLock.lock();
2703 }
2704
2705 // Just enqueue a new motion event.
Prabir Pradhan42611e02018-11-27 14:04:02 -08002706 MotionEntry* newEntry = new MotionEntry(args->sequenceNum, args->eventTime,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002707 args->deviceId, args->source, args->displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002708 args->action, args->actionButton, args->flags,
2709 args->metaState, args->buttonState,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002710 args->edgeFlags, args->xPrecision, args->yPrecision, args->downTime,
Jeff Brownf086ddb2014-02-11 14:28:48 -08002711 args->pointerCount, args->pointerProperties, args->pointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002712
2713 needWake = enqueueInboundEventLocked(newEntry);
2714 mLock.unlock();
2715 } // release lock
2716
2717 if (needWake) {
2718 mLooper->wake();
2719 }
2720}
2721
2722bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
2723 // TODO: support sending secondary display events to input filter
2724 return mInputFilterEnabled && isMainDisplay(args->displayId);
2725}
2726
2727void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
2728#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002729 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
2730 "switchMask=0x%08x",
2731 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002732#endif
2733
2734 uint32_t policyFlags = args->policyFlags;
2735 policyFlags |= POLICY_FLAG_TRUSTED;
2736 mPolicy->notifySwitch(args->eventTime,
2737 args->switchValues, args->switchMask, policyFlags);
2738}
2739
2740void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
2741#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002742 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002743 args->eventTime, args->deviceId);
2744#endif
2745
2746 bool needWake;
2747 { // acquire lock
2748 AutoMutex _l(mLock);
2749
Prabir Pradhan42611e02018-11-27 14:04:02 -08002750 DeviceResetEntry* newEntry =
2751 new DeviceResetEntry(args->sequenceNum, args->eventTime, args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002752 needWake = enqueueInboundEventLocked(newEntry);
2753 } // release lock
2754
2755 if (needWake) {
2756 mLooper->wake();
2757 }
2758}
2759
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002760int32_t InputDispatcher::injectInputEvent(const InputEvent* event,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002761 int32_t injectorPid, int32_t injectorUid, int32_t syncMode, int32_t timeoutMillis,
2762 uint32_t policyFlags) {
2763#if DEBUG_INBOUND_EVENT_DETAILS
2764 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002765 "syncMode=%d, timeoutMillis=%d, policyFlags=0x%08x",
2766 event->getType(), injectorPid, injectorUid, syncMode, timeoutMillis, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002767#endif
2768
2769 nsecs_t endTime = now() + milliseconds_to_nanoseconds(timeoutMillis);
2770
2771 policyFlags |= POLICY_FLAG_INJECTED;
2772 if (hasInjectionPermission(injectorPid, injectorUid)) {
2773 policyFlags |= POLICY_FLAG_TRUSTED;
2774 }
2775
2776 EventEntry* firstInjectedEntry;
2777 EventEntry* lastInjectedEntry;
2778 switch (event->getType()) {
2779 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002780 KeyEvent keyEvent;
2781 keyEvent.initialize(*static_cast<const KeyEvent*>(event));
2782 int32_t action = keyEvent.getAction();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002783 if (! validateKeyEvent(action)) {
2784 return INPUT_EVENT_INJECTION_FAILED;
2785 }
2786
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002787 int32_t flags = keyEvent.getFlags();
2788 int32_t keyCode = keyEvent.getKeyCode();
2789 int32_t metaState = keyEvent.getMetaState();
2790 accelerateMetaShortcuts(keyEvent.getDeviceId(), action,
2791 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002792 keyEvent.initialize(keyEvent.getDeviceId(), keyEvent.getSource(), keyEvent.getDisplayId(),
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07002793 action, flags, keyCode, keyEvent.getScanCode(), metaState, keyEvent.getRepeatCount(),
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002794 keyEvent.getDownTime(), keyEvent.getEventTime());
2795
Michael Wrightd02c5b62014-02-10 15:10:22 -08002796 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
2797 policyFlags |= POLICY_FLAG_VIRTUAL;
2798 }
2799
2800 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wright2b3c3302018-03-02 17:19:13 +00002801 android::base::Timer t;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002802 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002803 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2804 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
2805 std::to_string(t.duration().count()).c_str());
2806 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002807 }
2808
Michael Wrightd02c5b62014-02-10 15:10:22 -08002809 mLock.lock();
Prabir Pradhan42611e02018-11-27 14:04:02 -08002810 firstInjectedEntry = new KeyEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, keyEvent.getEventTime(),
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002811 keyEvent.getDeviceId(), keyEvent.getSource(), keyEvent.getDisplayId(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002812 policyFlags, action, flags,
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002813 keyEvent.getKeyCode(), keyEvent.getScanCode(), keyEvent.getMetaState(),
2814 keyEvent.getRepeatCount(), keyEvent.getDownTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002815 lastInjectedEntry = firstInjectedEntry;
2816 break;
2817 }
2818
2819 case AINPUT_EVENT_TYPE_MOTION: {
2820 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002821 int32_t action = motionEvent->getAction();
2822 size_t pointerCount = motionEvent->getPointerCount();
2823 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
Michael Wright7b159c92015-05-14 14:48:03 +01002824 int32_t actionButton = motionEvent->getActionButton();
2825 if (! validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002826 return INPUT_EVENT_INJECTION_FAILED;
2827 }
2828
2829 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
2830 nsecs_t eventTime = motionEvent->getEventTime();
Michael Wright2b3c3302018-03-02 17:19:13 +00002831 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002832 mPolicy->interceptMotionBeforeQueueing(eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002833 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2834 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
2835 std::to_string(t.duration().count()).c_str());
2836 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002837 }
2838
2839 mLock.lock();
2840 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
2841 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
Prabir Pradhan42611e02018-11-27 14:04:02 -08002842 firstInjectedEntry = new MotionEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, *sampleEventTimes,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002843 motionEvent->getDeviceId(), motionEvent->getSource(), motionEvent->getDisplayId(),
2844 policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002845 action, actionButton, motionEvent->getFlags(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002846 motionEvent->getMetaState(), motionEvent->getButtonState(),
2847 motionEvent->getEdgeFlags(),
2848 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002849 motionEvent->getDownTime(),
Jeff Brownf086ddb2014-02-11 14:28:48 -08002850 uint32_t(pointerCount), pointerProperties, samplePointerCoords,
2851 motionEvent->getXOffset(), motionEvent->getYOffset());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002852 lastInjectedEntry = firstInjectedEntry;
2853 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
2854 sampleEventTimes += 1;
2855 samplePointerCoords += pointerCount;
Prabir Pradhan42611e02018-11-27 14:04:02 -08002856 MotionEntry* nextInjectedEntry = new MotionEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM,
2857 *sampleEventTimes,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002858 motionEvent->getDeviceId(), motionEvent->getSource(),
2859 motionEvent->getDisplayId(), policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002860 action, actionButton, motionEvent->getFlags(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002861 motionEvent->getMetaState(), motionEvent->getButtonState(),
2862 motionEvent->getEdgeFlags(),
2863 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002864 motionEvent->getDownTime(),
Jeff Brownf086ddb2014-02-11 14:28:48 -08002865 uint32_t(pointerCount), pointerProperties, samplePointerCoords,
2866 motionEvent->getXOffset(), motionEvent->getYOffset());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002867 lastInjectedEntry->next = nextInjectedEntry;
2868 lastInjectedEntry = nextInjectedEntry;
2869 }
2870 break;
2871 }
2872
2873 default:
2874 ALOGW("Cannot inject event of type %d", event->getType());
2875 return INPUT_EVENT_INJECTION_FAILED;
2876 }
2877
2878 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
2879 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
2880 injectionState->injectionIsAsync = true;
2881 }
2882
2883 injectionState->refCount += 1;
2884 lastInjectedEntry->injectionState = injectionState;
2885
2886 bool needWake = false;
Yi Kong9b14ac62018-07-17 13:48:38 -07002887 for (EventEntry* entry = firstInjectedEntry; entry != nullptr; ) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002888 EventEntry* nextEntry = entry->next;
2889 needWake |= enqueueInboundEventLocked(entry);
2890 entry = nextEntry;
2891 }
2892
2893 mLock.unlock();
2894
2895 if (needWake) {
2896 mLooper->wake();
2897 }
2898
2899 int32_t injectionResult;
2900 { // acquire lock
2901 AutoMutex _l(mLock);
2902
2903 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
2904 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
2905 } else {
2906 for (;;) {
2907 injectionResult = injectionState->injectionResult;
2908 if (injectionResult != INPUT_EVENT_INJECTION_PENDING) {
2909 break;
2910 }
2911
2912 nsecs_t remainingTimeout = endTime - now();
2913 if (remainingTimeout <= 0) {
2914#if DEBUG_INJECTION
2915 ALOGD("injectInputEvent - Timed out waiting for injection result "
2916 "to become available.");
2917#endif
2918 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
2919 break;
2920 }
2921
2922 mInjectionResultAvailableCondition.waitRelative(mLock, remainingTimeout);
2923 }
2924
2925 if (injectionResult == INPUT_EVENT_INJECTION_SUCCEEDED
2926 && syncMode == INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED) {
2927 while (injectionState->pendingForegroundDispatches != 0) {
2928#if DEBUG_INJECTION
2929 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
2930 injectionState->pendingForegroundDispatches);
2931#endif
2932 nsecs_t remainingTimeout = endTime - now();
2933 if (remainingTimeout <= 0) {
2934#if DEBUG_INJECTION
2935 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
2936 "dispatches to finish.");
2937#endif
2938 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
2939 break;
2940 }
2941
2942 mInjectionSyncFinishedCondition.waitRelative(mLock, remainingTimeout);
2943 }
2944 }
2945 }
2946
2947 injectionState->release();
2948 } // release lock
2949
2950#if DEBUG_INJECTION
2951 ALOGD("injectInputEvent - Finished with result %d. "
2952 "injectorPid=%d, injectorUid=%d",
2953 injectionResult, injectorPid, injectorUid);
2954#endif
2955
2956 return injectionResult;
2957}
2958
2959bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
2960 return injectorUid == 0
2961 || mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
2962}
2963
2964void InputDispatcher::setInjectionResultLocked(EventEntry* entry, int32_t injectionResult) {
2965 InjectionState* injectionState = entry->injectionState;
2966 if (injectionState) {
2967#if DEBUG_INJECTION
2968 ALOGD("Setting input event injection result to %d. "
2969 "injectorPid=%d, injectorUid=%d",
2970 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
2971#endif
2972
2973 if (injectionState->injectionIsAsync
2974 && !(entry->policyFlags & POLICY_FLAG_FILTERED)) {
2975 // Log the outcome since the injector did not wait for the injection result.
2976 switch (injectionResult) {
2977 case INPUT_EVENT_INJECTION_SUCCEEDED:
2978 ALOGV("Asynchronous input event injection succeeded.");
2979 break;
2980 case INPUT_EVENT_INJECTION_FAILED:
2981 ALOGW("Asynchronous input event injection failed.");
2982 break;
2983 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
2984 ALOGW("Asynchronous input event injection permission denied.");
2985 break;
2986 case INPUT_EVENT_INJECTION_TIMED_OUT:
2987 ALOGW("Asynchronous input event injection timed out.");
2988 break;
2989 }
2990 }
2991
2992 injectionState->injectionResult = injectionResult;
2993 mInjectionResultAvailableCondition.broadcast();
2994 }
2995}
2996
2997void InputDispatcher::incrementPendingForegroundDispatchesLocked(EventEntry* entry) {
2998 InjectionState* injectionState = entry->injectionState;
2999 if (injectionState) {
3000 injectionState->pendingForegroundDispatches += 1;
3001 }
3002}
3003
3004void InputDispatcher::decrementPendingForegroundDispatchesLocked(EventEntry* entry) {
3005 InjectionState* injectionState = entry->injectionState;
3006 if (injectionState) {
3007 injectionState->pendingForegroundDispatches -= 1;
3008
3009 if (injectionState->pendingForegroundDispatches == 0) {
3010 mInjectionSyncFinishedCondition.broadcast();
3011 }
3012 }
3013}
3014
Arthur Hungb92218b2018-08-14 12:00:21 +08003015Vector<sp<InputWindowHandle>> InputDispatcher::getWindowHandlesLocked(int32_t displayId) const {
3016 std::unordered_map<int32_t, Vector<sp<InputWindowHandle>>>::const_iterator it =
3017 mWindowHandlesByDisplay.find(displayId);
3018 if(it != mWindowHandlesByDisplay.end()) {
3019 return it->second;
3020 }
3021
3022 // Return an empty one if nothing found.
3023 return Vector<sp<InputWindowHandle>>();
3024}
3025
Michael Wrightd02c5b62014-02-10 15:10:22 -08003026sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
3027 const sp<InputChannel>& inputChannel) const {
Arthur Hungb92218b2018-08-14 12:00:21 +08003028 for (auto& it : mWindowHandlesByDisplay) {
3029 const Vector<sp<InputWindowHandle>> windowHandles = it.second;
3030 size_t numWindows = windowHandles.size();
3031 for (size_t i = 0; i < numWindows; i++) {
3032 const sp<InputWindowHandle>& windowHandle = windowHandles.itemAt(i);
Robert Carr5c8a0262018-10-03 16:30:44 -07003033 if (windowHandle->getToken() == inputChannel->getToken()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003034 return windowHandle;
3035 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003036 }
3037 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003038 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003039}
3040
3041bool InputDispatcher::hasWindowHandleLocked(
Siarhei Vishniakou9224fba2018-08-13 18:55:08 +00003042 const sp<InputWindowHandle>& windowHandle) const {
Arthur Hungb92218b2018-08-14 12:00:21 +08003043 for (auto& it : mWindowHandlesByDisplay) {
3044 const Vector<sp<InputWindowHandle>> windowHandles = it.second;
3045 size_t numWindows = windowHandles.size();
3046 for (size_t i = 0; i < numWindows; i++) {
Robert Carr5c8a0262018-10-03 16:30:44 -07003047 if (windowHandles.itemAt(i)->getToken()
3048 == windowHandle->getToken()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003049 if (windowHandle->getInfo()->displayId != it.first) {
Arthur Hung3b413f22018-10-26 18:05:34 +08003050 ALOGE("Found window %s in display %" PRId32
3051 ", but it should belong to display %" PRId32,
3052 windowHandle->getName().c_str(), it.first,
3053 windowHandle->getInfo()->displayId);
Arthur Hungb92218b2018-08-14 12:00:21 +08003054 }
3055 return true;
3056 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003057 }
3058 }
3059 return false;
3060}
3061
Robert Carr5c8a0262018-10-03 16:30:44 -07003062sp<InputChannel> InputDispatcher::getInputChannelLocked(const sp<IBinder>& token) const {
3063 size_t count = mInputChannelsByToken.count(token);
3064 if (count == 0) {
3065 return nullptr;
3066 }
3067 return mInputChannelsByToken.at(token);
3068}
3069
Arthur Hungb92218b2018-08-14 12:00:21 +08003070/**
3071 * Called from InputManagerService, update window handle list by displayId that can receive input.
3072 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
3073 * If set an empty list, remove all handles from the specific display.
3074 * For focused handle, check if need to change and send a cancel event to previous one.
3075 * For removed handle, check if need to send a cancel event if already in touch.
3076 */
3077void InputDispatcher::setInputWindows(const Vector<sp<InputWindowHandle>>& inputWindowHandles,
3078 int32_t displayId) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003079#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003080 ALOGD("setInputWindows displayId=%" PRId32, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003081#endif
3082 { // acquire lock
3083 AutoMutex _l(mLock);
3084
Arthur Hungb92218b2018-08-14 12:00:21 +08003085 // Copy old handles for release if they are no longer present.
3086 const Vector<sp<InputWindowHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003087
Tiger Huang721e26f2018-07-24 22:26:19 +08003088 sp<InputWindowHandle> newFocusedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003089 bool foundHoveredWindow = false;
Arthur Hungb92218b2018-08-14 12:00:21 +08003090
3091 if (inputWindowHandles.isEmpty()) {
3092 // Remove all handles on a display if there are no windows left.
3093 mWindowHandlesByDisplay.erase(displayId);
3094 } else {
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003095 // Since we compare the pointer of input window handles across window updates, we need
3096 // to make sure the handle object for the same window stays unchanged across updates.
3097 const Vector<sp<InputWindowHandle>>& oldHandles = mWindowHandlesByDisplay[displayId];
3098 std::unordered_map<sp<IBinder>, sp<InputWindowHandle>, IBinderHash> oldHandlesByTokens;
3099 for (size_t i = 0; i < oldHandles.size(); i++) {
3100 const sp<InputWindowHandle>& handle = oldHandles.itemAt(i);
3101 oldHandlesByTokens[handle->getToken()] = handle;
3102 }
3103
3104 const size_t numWindows = inputWindowHandles.size();
3105 Vector<sp<InputWindowHandle>> newHandles;
Arthur Hungb92218b2018-08-14 12:00:21 +08003106 for (size_t i = 0; i < numWindows; i++) {
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003107 const sp<InputWindowHandle>& handle = inputWindowHandles.itemAt(i);
3108 if (!handle->updateInfo() || getInputChannelLocked(handle->getToken()) == nullptr) {
Robert Carr5c8a0262018-10-03 16:30:44 -07003109 ALOGE("Window handle %s has no registered input channel",
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003110 handle->getName().c_str());
Arthur Hungb92218b2018-08-14 12:00:21 +08003111 continue;
3112 }
3113
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003114 if (handle->getInfo()->displayId != displayId) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003115 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003116 handle->getName().c_str(), displayId,
3117 handle->getInfo()->displayId);
Arthur Hungb92218b2018-08-14 12:00:21 +08003118 continue;
3119 }
3120
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003121 if (oldHandlesByTokens.find(handle->getToken()) != oldHandlesByTokens.end()) {
3122 const sp<InputWindowHandle> oldHandle =
3123 oldHandlesByTokens.at(handle->getToken());
3124 oldHandle->updateFrom(handle);
3125 newHandles.push_back(oldHandle);
3126 } else {
3127 newHandles.push_back(handle);
3128 }
3129 }
3130
3131 for (size_t i = 0; i < newHandles.size(); i++) {
3132 const sp<InputWindowHandle>& windowHandle = newHandles.itemAt(i);
Siarhei Vishniakou49ee3232018-12-03 15:10:36 -06003133 if (windowHandle->getInfo()->hasFocus && windowHandle->getInfo()->visible) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003134 newFocusedWindowHandle = windowHandle;
3135 }
3136 if (windowHandle == mLastHoverWindowHandle) {
3137 foundHoveredWindow = true;
3138 }
Siarhei Vishniakou9224fba2018-08-13 18:55:08 +00003139 }
Arthur Hungb92218b2018-08-14 12:00:21 +08003140
3141 // Insert or replace
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003142 mWindowHandlesByDisplay[displayId] = newHandles;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003143 }
3144
3145 if (!foundHoveredWindow) {
Yi Kong9b14ac62018-07-17 13:48:38 -07003146 mLastHoverWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003147 }
3148
Tiger Huang721e26f2018-07-24 22:26:19 +08003149 sp<InputWindowHandle> oldFocusedWindowHandle =
3150 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
3151
3152 if (oldFocusedWindowHandle != newFocusedWindowHandle) {
3153 if (oldFocusedWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003154#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003155 ALOGD("Focus left window: %s in display %" PRId32,
3156 oldFocusedWindowHandle->getName().c_str(), displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003157#endif
Robert Carr5c8a0262018-10-03 16:30:44 -07003158 sp<InputChannel> focusedInputChannel = getInputChannelLocked(
3159 oldFocusedWindowHandle->getToken());
Yi Kong9b14ac62018-07-17 13:48:38 -07003160 if (focusedInputChannel != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003161 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
3162 "focus left window");
3163 synthesizeCancelationEventsForInputChannelLocked(
3164 focusedInputChannel, options);
3165 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003166 mFocusedWindowHandlesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003167 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003168 if (newFocusedWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003169#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003170 ALOGD("Focus entered window: %s in display %" PRId32,
3171 newFocusedWindowHandle->getName().c_str(), displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003172#endif
Tiger Huang721e26f2018-07-24 22:26:19 +08003173 mFocusedWindowHandlesByDisplay[displayId] = newFocusedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003174 }
Robert Carrf759f162018-11-13 12:57:11 -08003175
3176 if (mFocusedDisplayId == displayId) {
3177 onFocusChangedLocked(newFocusedWindowHandle);
3178 }
3179
Michael Wrightd02c5b62014-02-10 15:10:22 -08003180 }
3181
Arthur Hungb92218b2018-08-14 12:00:21 +08003182 ssize_t stateIndex = mTouchStatesByDisplay.indexOfKey(displayId);
3183 if (stateIndex >= 0) {
3184 TouchState& state = mTouchStatesByDisplay.editValueAt(stateIndex);
Ivan Lozano96f12992017-11-09 14:45:38 -08003185 for (size_t i = 0; i < state.windows.size(); ) {
Jeff Brownf086ddb2014-02-11 14:28:48 -08003186 TouchedWindow& touchedWindow = state.windows.editItemAt(i);
Siarhei Vishniakou9224fba2018-08-13 18:55:08 +00003187 if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003188#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003189 ALOGD("Touched window was removed: %s in display %" PRId32,
3190 touchedWindow.windowHandle->getName().c_str(), displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003191#endif
Jeff Brownf086ddb2014-02-11 14:28:48 -08003192 sp<InputChannel> touchedInputChannel =
Robert Carr5c8a0262018-10-03 16:30:44 -07003193 getInputChannelLocked(touchedWindow.windowHandle->getToken());
Yi Kong9b14ac62018-07-17 13:48:38 -07003194 if (touchedInputChannel != nullptr) {
Jeff Brownf086ddb2014-02-11 14:28:48 -08003195 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
3196 "touched window was removed");
3197 synthesizeCancelationEventsForInputChannelLocked(
3198 touchedInputChannel, options);
3199 }
Ivan Lozano96f12992017-11-09 14:45:38 -08003200 state.windows.removeAt(i);
3201 } else {
3202 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003203 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003204 }
3205 }
3206
3207 // Release information for windows that are no longer present.
3208 // This ensures that unused input channels are released promptly.
3209 // Otherwise, they might stick around until the window handle is destroyed
3210 // which might not happen until the next GC.
Arthur Hungb92218b2018-08-14 12:00:21 +08003211 size_t numWindows = oldWindowHandles.size();
3212 for (size_t i = 0; i < numWindows; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003213 const sp<InputWindowHandle>& oldWindowHandle = oldWindowHandles.itemAt(i);
Siarhei Vishniakou9224fba2018-08-13 18:55:08 +00003214 if (!hasWindowHandleLocked(oldWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003215#if DEBUG_FOCUS
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003216 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003217#endif
Arthur Hung3b413f22018-10-26 18:05:34 +08003218 oldWindowHandle->releaseChannel();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003219 }
3220 }
3221 } // release lock
3222
3223 // Wake up poll loop since it may need to make new input dispatching choices.
3224 mLooper->wake();
3225}
3226
3227void InputDispatcher::setFocusedApplication(
Tiger Huang721e26f2018-07-24 22:26:19 +08003228 int32_t displayId, const sp<InputApplicationHandle>& inputApplicationHandle) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003229#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003230 ALOGD("setFocusedApplication displayId=%" PRId32, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003231#endif
3232 { // acquire lock
3233 AutoMutex _l(mLock);
3234
Tiger Huang721e26f2018-07-24 22:26:19 +08003235 sp<InputApplicationHandle> oldFocusedApplicationHandle =
3236 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
Yi Kong9b14ac62018-07-17 13:48:38 -07003237 if (inputApplicationHandle != nullptr && inputApplicationHandle->updateInfo()) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003238 if (oldFocusedApplicationHandle != inputApplicationHandle) {
3239 if (oldFocusedApplicationHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003240 resetANRTimeoutsLocked();
Tiger Huang721e26f2018-07-24 22:26:19 +08003241 oldFocusedApplicationHandle->releaseInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003242 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003243 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003244 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003245 } else if (oldFocusedApplicationHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003246 resetANRTimeoutsLocked();
Tiger Huang721e26f2018-07-24 22:26:19 +08003247 oldFocusedApplicationHandle->releaseInfo();
3248 oldFocusedApplicationHandle.clear();
3249 mFocusedApplicationHandlesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003250 }
3251
3252#if DEBUG_FOCUS
3253 //logDispatchStateLocked();
3254#endif
3255 } // release lock
3256
3257 // Wake up poll loop since it may need to make new input dispatching choices.
3258 mLooper->wake();
3259}
3260
Tiger Huang721e26f2018-07-24 22:26:19 +08003261/**
3262 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
3263 * the display not specified.
3264 *
3265 * We track any unreleased events for each window. If a window loses the ability to receive the
3266 * released event, we will send a cancel event to it. So when the focused display is changed, we
3267 * cancel all the unreleased display-unspecified events for the focused window on the old focused
3268 * display. The display-specified events won't be affected.
3269 */
3270void InputDispatcher::setFocusedDisplay(int32_t displayId) {
3271#if DEBUG_FOCUS
3272 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
3273#endif
3274 { // acquire lock
3275 AutoMutex _l(mLock);
3276
3277 if (mFocusedDisplayId != displayId) {
3278 sp<InputWindowHandle> oldFocusedWindowHandle =
3279 getValueByKey(mFocusedWindowHandlesByDisplay, mFocusedDisplayId);
3280 if (oldFocusedWindowHandle != nullptr) {
Robert Carr5c8a0262018-10-03 16:30:44 -07003281 sp<InputChannel> inputChannel =
3282 getInputChannelLocked(oldFocusedWindowHandle->getToken());
Tiger Huang721e26f2018-07-24 22:26:19 +08003283 if (inputChannel != nullptr) {
3284 CancelationOptions options(
3285 CancelationOptions::CANCEL_DISPLAY_UNSPECIFIED_EVENTS,
3286 "The display which contains this window no longer has focus.");
3287 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
3288 }
3289 }
3290 mFocusedDisplayId = displayId;
3291
3292 // Sanity check
3293 sp<InputWindowHandle> newFocusedWindowHandle =
3294 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
Robert Carrf759f162018-11-13 12:57:11 -08003295 onFocusChangedLocked(newFocusedWindowHandle);
3296
Tiger Huang721e26f2018-07-24 22:26:19 +08003297 if (newFocusedWindowHandle == nullptr) {
3298 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
3299 if (!mFocusedWindowHandlesByDisplay.empty()) {
3300 ALOGE("But another display has a focused window:");
3301 for (auto& it : mFocusedWindowHandlesByDisplay) {
3302 const int32_t displayId = it.first;
3303 const sp<InputWindowHandle>& windowHandle = it.second;
3304 ALOGE("Display #%" PRId32 " has focused window: '%s'\n",
3305 displayId, windowHandle->getName().c_str());
3306 }
3307 }
3308 }
3309 }
3310
3311#if DEBUG_FOCUS
3312 logDispatchStateLocked();
3313#endif
3314 } // release lock
3315
3316 // Wake up poll loop since it may need to make new input dispatching choices.
3317 mLooper->wake();
3318}
3319
Michael Wrightd02c5b62014-02-10 15:10:22 -08003320void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
3321#if DEBUG_FOCUS
3322 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
3323#endif
3324
3325 bool changed;
3326 { // acquire lock
3327 AutoMutex _l(mLock);
3328
3329 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
3330 if (mDispatchFrozen && !frozen) {
3331 resetANRTimeoutsLocked();
3332 }
3333
3334 if (mDispatchEnabled && !enabled) {
3335 resetAndDropEverythingLocked("dispatcher is being disabled");
3336 }
3337
3338 mDispatchEnabled = enabled;
3339 mDispatchFrozen = frozen;
3340 changed = true;
3341 } else {
3342 changed = false;
3343 }
3344
3345#if DEBUG_FOCUS
Tiger Huang721e26f2018-07-24 22:26:19 +08003346 logDispatchStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003347#endif
3348 } // release lock
3349
3350 if (changed) {
3351 // Wake up poll loop since it may need to make new input dispatching choices.
3352 mLooper->wake();
3353 }
3354}
3355
3356void InputDispatcher::setInputFilterEnabled(bool enabled) {
3357#if DEBUG_FOCUS
3358 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
3359#endif
3360
3361 { // acquire lock
3362 AutoMutex _l(mLock);
3363
3364 if (mInputFilterEnabled == enabled) {
3365 return;
3366 }
3367
3368 mInputFilterEnabled = enabled;
3369 resetAndDropEverythingLocked("input filter is being enabled or disabled");
3370 } // release lock
3371
3372 // Wake up poll loop since there might be work to do to drop everything.
3373 mLooper->wake();
3374}
3375
3376bool InputDispatcher::transferTouchFocus(const sp<InputChannel>& fromChannel,
3377 const sp<InputChannel>& toChannel) {
3378#if DEBUG_FOCUS
3379 ALOGD("transferTouchFocus: fromChannel=%s, toChannel=%s",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003380 fromChannel->getName().c_str(), toChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003381#endif
3382 { // acquire lock
3383 AutoMutex _l(mLock);
3384
3385 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromChannel);
3386 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toChannel);
Yi Kong9b14ac62018-07-17 13:48:38 -07003387 if (fromWindowHandle == nullptr || toWindowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003388#if DEBUG_FOCUS
3389 ALOGD("Cannot transfer focus because from or to window not found.");
3390#endif
3391 return false;
3392 }
3393 if (fromWindowHandle == toWindowHandle) {
3394#if DEBUG_FOCUS
3395 ALOGD("Trivial transfer to same window.");
3396#endif
3397 return true;
3398 }
3399 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
3400#if DEBUG_FOCUS
3401 ALOGD("Cannot transfer focus because windows are on different displays.");
3402#endif
3403 return false;
3404 }
3405
3406 bool found = false;
Jeff Brownf086ddb2014-02-11 14:28:48 -08003407 for (size_t d = 0; d < mTouchStatesByDisplay.size(); d++) {
3408 TouchState& state = mTouchStatesByDisplay.editValueAt(d);
3409 for (size_t i = 0; i < state.windows.size(); i++) {
3410 const TouchedWindow& touchedWindow = state.windows[i];
3411 if (touchedWindow.windowHandle == fromWindowHandle) {
3412 int32_t oldTargetFlags = touchedWindow.targetFlags;
3413 BitSet32 pointerIds = touchedWindow.pointerIds;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003414
Jeff Brownf086ddb2014-02-11 14:28:48 -08003415 state.windows.removeAt(i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003416
Jeff Brownf086ddb2014-02-11 14:28:48 -08003417 int32_t newTargetFlags = oldTargetFlags
3418 & (InputTarget::FLAG_FOREGROUND
3419 | InputTarget::FLAG_SPLIT | InputTarget::FLAG_DISPATCH_AS_IS);
3420 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003421
Jeff Brownf086ddb2014-02-11 14:28:48 -08003422 found = true;
3423 goto Found;
3424 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003425 }
3426 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08003427Found:
Michael Wrightd02c5b62014-02-10 15:10:22 -08003428
3429 if (! found) {
3430#if DEBUG_FOCUS
3431 ALOGD("Focus transfer failed because from window did not have focus.");
3432#endif
3433 return false;
3434 }
3435
3436 ssize_t fromConnectionIndex = getConnectionIndexLocked(fromChannel);
3437 ssize_t toConnectionIndex = getConnectionIndexLocked(toChannel);
3438 if (fromConnectionIndex >= 0 && toConnectionIndex >= 0) {
3439 sp<Connection> fromConnection = mConnectionsByFd.valueAt(fromConnectionIndex);
3440 sp<Connection> toConnection = mConnectionsByFd.valueAt(toConnectionIndex);
3441
3442 fromConnection->inputState.copyPointerStateTo(toConnection->inputState);
3443 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
3444 "transferring touch focus from this window to another window");
3445 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
3446 }
3447
3448#if DEBUG_FOCUS
3449 logDispatchStateLocked();
3450#endif
3451 } // release lock
3452
3453 // Wake up poll loop since it may need to make new input dispatching choices.
3454 mLooper->wake();
3455 return true;
3456}
3457
3458void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
3459#if DEBUG_FOCUS
3460 ALOGD("Resetting and dropping all events (%s).", reason);
3461#endif
3462
3463 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
3464 synthesizeCancelationEventsForAllConnectionsLocked(options);
3465
3466 resetKeyRepeatLocked();
3467 releasePendingEventLocked();
3468 drainInboundQueueLocked();
3469 resetANRTimeoutsLocked();
3470
Jeff Brownf086ddb2014-02-11 14:28:48 -08003471 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003472 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07003473 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003474}
3475
3476void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003477 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003478 dumpDispatchStateLocked(dump);
3479
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003480 std::istringstream stream(dump);
3481 std::string line;
3482
3483 while (std::getline(stream, line, '\n')) {
3484 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003485 }
3486}
3487
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003488void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
3489 dump += StringPrintf(INDENT "DispatchEnabled: %d\n", mDispatchEnabled);
3490 dump += StringPrintf(INDENT "DispatchFrozen: %d\n", mDispatchFrozen);
Tiger Huang721e26f2018-07-24 22:26:19 +08003491 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003492
Tiger Huang721e26f2018-07-24 22:26:19 +08003493 if (!mFocusedApplicationHandlesByDisplay.empty()) {
3494 dump += StringPrintf(INDENT "FocusedApplications:\n");
3495 for (auto& it : mFocusedApplicationHandlesByDisplay) {
3496 const int32_t displayId = it.first;
3497 const sp<InputApplicationHandle>& applicationHandle = it.second;
3498 dump += StringPrintf(
3499 INDENT2 "displayId=%" PRId32 ", name='%s', dispatchingTimeout=%0.3fms\n",
3500 displayId,
3501 applicationHandle->getName().c_str(),
3502 applicationHandle->getDispatchingTimeout(
3503 DEFAULT_INPUT_DISPATCHING_TIMEOUT) / 1000000.0);
3504 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003505 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08003506 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003507 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003508
3509 if (!mFocusedWindowHandlesByDisplay.empty()) {
3510 dump += StringPrintf(INDENT "FocusedWindows:\n");
3511 for (auto& it : mFocusedWindowHandlesByDisplay) {
3512 const int32_t displayId = it.first;
3513 const sp<InputWindowHandle>& windowHandle = it.second;
3514 dump += StringPrintf(INDENT2 "displayId=%" PRId32 ", name='%s'\n",
3515 displayId, windowHandle->getName().c_str());
3516 }
3517 } else {
3518 dump += StringPrintf(INDENT "FocusedWindows: <none>\n");
3519 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003520
Jeff Brownf086ddb2014-02-11 14:28:48 -08003521 if (!mTouchStatesByDisplay.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003522 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Jeff Brownf086ddb2014-02-11 14:28:48 -08003523 for (size_t i = 0; i < mTouchStatesByDisplay.size(); i++) {
3524 const TouchState& state = mTouchStatesByDisplay.valueAt(i);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003525 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Jeff Brownf086ddb2014-02-11 14:28:48 -08003526 state.displayId, toString(state.down), toString(state.split),
3527 state.deviceId, state.source);
3528 if (!state.windows.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003529 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08003530 for (size_t i = 0; i < state.windows.size(); i++) {
3531 const TouchedWindow& touchedWindow = state.windows[i];
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003532 dump += StringPrintf(INDENT4 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
3533 i, touchedWindow.windowHandle->getName().c_str(),
Jeff Brownf086ddb2014-02-11 14:28:48 -08003534 touchedWindow.pointerIds.value,
3535 touchedWindow.targetFlags);
3536 }
3537 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003538 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08003539 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003540 }
3541 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003542 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003543 }
3544
Arthur Hungb92218b2018-08-14 12:00:21 +08003545 if (!mWindowHandlesByDisplay.empty()) {
3546 for (auto& it : mWindowHandlesByDisplay) {
3547 const Vector<sp<InputWindowHandle>> windowHandles = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08003548 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", it.first);
Arthur Hungb92218b2018-08-14 12:00:21 +08003549 if (!windowHandles.isEmpty()) {
3550 dump += INDENT2 "Windows:\n";
3551 for (size_t i = 0; i < windowHandles.size(); i++) {
3552 const sp<InputWindowHandle>& windowHandle = windowHandles.itemAt(i);
3553 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003554
Arthur Hungb92218b2018-08-14 12:00:21 +08003555 dump += StringPrintf(INDENT3 "%zu: name='%s', displayId=%d, "
3556 "paused=%s, hasFocus=%s, hasWallpaper=%s, "
3557 "visible=%s, canReceiveKeys=%s, flags=0x%08x, type=0x%08x, layer=%d, "
Riddle Hsu39d4aa52018-11-30 20:46:53 +08003558 "frame=[%d,%d][%d,%d], globalScale=%f, windowScale=(%f,%f), "
Arthur Hungb92218b2018-08-14 12:00:21 +08003559 "touchableRegion=",
3560 i, windowInfo->name.c_str(), windowInfo->displayId,
3561 toString(windowInfo->paused),
3562 toString(windowInfo->hasFocus),
3563 toString(windowInfo->hasWallpaper),
3564 toString(windowInfo->visible),
3565 toString(windowInfo->canReceiveKeys),
3566 windowInfo->layoutParamsFlags, windowInfo->layoutParamsType,
3567 windowInfo->layer,
3568 windowInfo->frameLeft, windowInfo->frameTop,
3569 windowInfo->frameRight, windowInfo->frameBottom,
Robert Carre07e1032018-11-26 12:55:53 -08003570 windowInfo->globalScaleFactor,
3571 windowInfo->windowXScale, windowInfo->windowYScale);
Arthur Hungb92218b2018-08-14 12:00:21 +08003572 dumpRegion(dump, windowInfo->touchableRegion);
3573 dump += StringPrintf(", inputFeatures=0x%08x", windowInfo->inputFeatures);
3574 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%0.3fms\n",
3575 windowInfo->ownerPid, windowInfo->ownerUid,
3576 windowInfo->dispatchingTimeout / 1000000.0);
3577 }
3578 } else {
3579 dump += INDENT2 "Windows: <none>\n";
3580 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003581 }
3582 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08003583 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003584 }
3585
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003586 if (!mMonitoringChannelsByDisplay.empty()) {
3587 for (auto& it : mMonitoringChannelsByDisplay) {
3588 const Vector<sp<InputChannel>>& monitoringChannels = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08003589 dump += StringPrintf(INDENT "MonitoringChannels in display %" PRId32 ":\n", it.first);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003590 const size_t numChannels = monitoringChannels.size();
3591 for (size_t i = 0; i < numChannels; i++) {
3592 const sp<InputChannel>& channel = monitoringChannels[i];
3593 dump += StringPrintf(INDENT2 "%zu: '%s'\n", i, channel->getName().c_str());
3594 }
3595 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003596 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003597 dump += INDENT "MonitoringChannels: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003598 }
3599
3600 nsecs_t currentTime = now();
3601
3602 // Dump recently dispatched or dropped events from oldest to newest.
3603 if (!mRecentQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003604 dump += StringPrintf(INDENT "RecentQueue: length=%u\n", mRecentQueue.count());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003605 for (EventEntry* entry = mRecentQueue.head; entry; entry = entry->next) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003606 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003607 entry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003608 dump += StringPrintf(", age=%0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003609 (currentTime - entry->eventTime) * 0.000001f);
3610 }
3611 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003612 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003613 }
3614
3615 // Dump event currently being dispatched.
3616 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003617 dump += INDENT "PendingEvent:\n";
3618 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003619 mPendingEvent->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003620 dump += StringPrintf(", age=%0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003621 (currentTime - mPendingEvent->eventTime) * 0.000001f);
3622 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003623 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003624 }
3625
3626 // Dump inbound events from oldest to newest.
3627 if (!mInboundQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003628 dump += StringPrintf(INDENT "InboundQueue: length=%u\n", mInboundQueue.count());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003629 for (EventEntry* entry = mInboundQueue.head; entry; entry = entry->next) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003630 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003631 entry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003632 dump += StringPrintf(", age=%0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003633 (currentTime - entry->eventTime) * 0.000001f);
3634 }
3635 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003636 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003637 }
3638
Michael Wright78f24442014-08-06 15:55:28 -07003639 if (!mReplacedKeys.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003640 dump += INDENT "ReplacedKeys:\n";
Michael Wright78f24442014-08-06 15:55:28 -07003641 for (size_t i = 0; i < mReplacedKeys.size(); i++) {
3642 const KeyReplacement& replacement = mReplacedKeys.keyAt(i);
3643 int32_t newKeyCode = mReplacedKeys.valueAt(i);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003644 dump += StringPrintf(INDENT2 "%zu: originalKeyCode=%d, deviceId=%d, newKeyCode=%d\n",
Michael Wright78f24442014-08-06 15:55:28 -07003645 i, replacement.keyCode, replacement.deviceId, newKeyCode);
3646 }
3647 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003648 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07003649 }
3650
Michael Wrightd02c5b62014-02-10 15:10:22 -08003651 if (!mConnectionsByFd.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003652 dump += INDENT "Connections:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003653 for (size_t i = 0; i < mConnectionsByFd.size(); i++) {
3654 const sp<Connection>& connection = mConnectionsByFd.valueAt(i);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003655 dump += StringPrintf(INDENT2 "%zu: channelName='%s', windowName='%s', "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003656 "status=%s, monitor=%s, inputPublisherBlocked=%s\n",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08003657 i, connection->getInputChannelName().c_str(),
3658 connection->getWindowName().c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08003659 connection->getStatusLabel(), toString(connection->monitor),
3660 toString(connection->inputPublisherBlocked));
3661
3662 if (!connection->outboundQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003663 dump += StringPrintf(INDENT3 "OutboundQueue: length=%u\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003664 connection->outboundQueue.count());
3665 for (DispatchEntry* entry = connection->outboundQueue.head; entry;
3666 entry = entry->next) {
3667 dump.append(INDENT4);
3668 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003669 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, age=%0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003670 entry->targetFlags, entry->resolvedAction,
3671 (currentTime - entry->eventEntry->eventTime) * 0.000001f);
3672 }
3673 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003674 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003675 }
3676
3677 if (!connection->waitQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003678 dump += StringPrintf(INDENT3 "WaitQueue: length=%u\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003679 connection->waitQueue.count());
3680 for (DispatchEntry* entry = connection->waitQueue.head; entry;
3681 entry = entry->next) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003682 dump += INDENT4;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003683 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003684 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003685 "age=%0.1fms, wait=%0.1fms\n",
3686 entry->targetFlags, entry->resolvedAction,
3687 (currentTime - entry->eventEntry->eventTime) * 0.000001f,
3688 (currentTime - entry->deliveryTime) * 0.000001f);
3689 }
3690 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003691 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003692 }
3693 }
3694 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003695 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003696 }
3697
3698 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003699 dump += StringPrintf(INDENT "AppSwitch: pending, due in %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003700 (mAppSwitchDueTime - now()) / 1000000.0);
3701 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003702 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003703 }
3704
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003705 dump += INDENT "Configuration:\n";
3706 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003707 mConfig.keyRepeatDelay * 0.000001f);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003708 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003709 mConfig.keyRepeatTimeout * 0.000001f);
3710}
3711
Robert Carr803535b2018-08-02 16:38:15 -07003712status_t InputDispatcher::registerInputChannel(const sp<InputChannel>& inputChannel, int32_t displayId) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003713#if DEBUG_REGISTRATION
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003714 ALOGD("channel '%s' ~ registerInputChannel - displayId=%" PRId32,
3715 inputChannel->getName().c_str(), displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003716#endif
3717
3718 { // acquire lock
3719 AutoMutex _l(mLock);
3720
Robert Carr4e670e52018-08-15 13:26:12 -07003721 // If InputWindowHandle is null and displayId is not ADISPLAY_ID_NONE,
3722 // treat inputChannel as monitor channel for displayId.
3723 bool monitor = inputChannel->getToken() == nullptr && displayId != ADISPLAY_ID_NONE;
3724 if (monitor) {
3725 inputChannel->setToken(new BBinder());
3726 }
3727
Michael Wrightd02c5b62014-02-10 15:10:22 -08003728 if (getConnectionIndexLocked(inputChannel) >= 0) {
3729 ALOGW("Attempted to register already registered input channel '%s'",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003730 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003731 return BAD_VALUE;
3732 }
3733
Robert Carr803535b2018-08-02 16:38:15 -07003734 sp<Connection> connection = new Connection(inputChannel, monitor);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003735
3736 int fd = inputChannel->getFd();
3737 mConnectionsByFd.add(fd, connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07003738 mInputChannelsByToken[inputChannel->getToken()] = inputChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003739
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003740 // Store monitor channel by displayId.
Michael Wrightd02c5b62014-02-10 15:10:22 -08003741 if (monitor) {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003742 Vector<sp<InputChannel>>& monitoringChannels =
3743 mMonitoringChannelsByDisplay[displayId];
3744 monitoringChannels.push(inputChannel);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003745 }
3746
3747 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
3748 } // release lock
3749
3750 // Wake the looper because some connections have changed.
3751 mLooper->wake();
3752 return OK;
3753}
3754
3755status_t InputDispatcher::unregisterInputChannel(const sp<InputChannel>& inputChannel) {
3756#if DEBUG_REGISTRATION
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003757 ALOGD("channel '%s' ~ unregisterInputChannel", inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003758#endif
3759
3760 { // acquire lock
3761 AutoMutex _l(mLock);
3762
3763 status_t status = unregisterInputChannelLocked(inputChannel, false /*notify*/);
3764 if (status) {
3765 return status;
3766 }
3767 } // release lock
3768
3769 // Wake the poll loop because removing the connection may have changed the current
3770 // synchronization state.
3771 mLooper->wake();
3772 return OK;
3773}
3774
3775status_t InputDispatcher::unregisterInputChannelLocked(const sp<InputChannel>& inputChannel,
3776 bool notify) {
3777 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
3778 if (connectionIndex < 0) {
3779 ALOGW("Attempted to unregister already unregistered input channel '%s'",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003780 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003781 return BAD_VALUE;
3782 }
3783
3784 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
3785 mConnectionsByFd.removeItemsAt(connectionIndex);
3786
Robert Carr5c8a0262018-10-03 16:30:44 -07003787 mInputChannelsByToken.erase(inputChannel->getToken());
3788
Michael Wrightd02c5b62014-02-10 15:10:22 -08003789 if (connection->monitor) {
3790 removeMonitorChannelLocked(inputChannel);
3791 }
3792
3793 mLooper->removeFd(inputChannel->getFd());
3794
3795 nsecs_t currentTime = now();
3796 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
3797
3798 connection->status = Connection::STATUS_ZOMBIE;
3799 return OK;
3800}
3801
3802void InputDispatcher::removeMonitorChannelLocked(const sp<InputChannel>& inputChannel) {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003803 for (auto it = mMonitoringChannelsByDisplay.begin();
3804 it != mMonitoringChannelsByDisplay.end(); ) {
3805 Vector<sp<InputChannel>>& monitoringChannels = it->second;
3806 const size_t numChannels = monitoringChannels.size();
3807 for (size_t i = 0; i < numChannels; i++) {
3808 if (monitoringChannels[i] == inputChannel) {
3809 monitoringChannels.removeAt(i);
3810 break;
3811 }
3812 }
3813 if (monitoringChannels.empty()) {
3814 it = mMonitoringChannelsByDisplay.erase(it);
3815 } else {
3816 ++it;
3817 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003818 }
3819}
3820
3821ssize_t InputDispatcher::getConnectionIndexLocked(const sp<InputChannel>& inputChannel) {
Robert Carr4e670e52018-08-15 13:26:12 -07003822 if (inputChannel == nullptr) {
Arthur Hung3b413f22018-10-26 18:05:34 +08003823 return -1;
3824 }
3825
Robert Carr4e670e52018-08-15 13:26:12 -07003826 for (size_t i = 0; i < mConnectionsByFd.size(); i++) {
3827 sp<Connection> connection = mConnectionsByFd.valueAt(i);
3828 if (connection->inputChannel->getToken() == inputChannel->getToken()) {
3829 return i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003830 }
3831 }
Robert Carr4e670e52018-08-15 13:26:12 -07003832
Michael Wrightd02c5b62014-02-10 15:10:22 -08003833 return -1;
3834}
3835
3836void InputDispatcher::onDispatchCycleFinishedLocked(
3837 nsecs_t currentTime, const sp<Connection>& connection, uint32_t seq, bool handled) {
3838 CommandEntry* commandEntry = postCommandLocked(
3839 & InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
3840 commandEntry->connection = connection;
3841 commandEntry->eventTime = currentTime;
3842 commandEntry->seq = seq;
3843 commandEntry->handled = handled;
3844}
3845
3846void InputDispatcher::onDispatchCycleBrokenLocked(
3847 nsecs_t currentTime, const sp<Connection>& connection) {
3848 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08003849 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003850
3851 CommandEntry* commandEntry = postCommandLocked(
3852 & InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
3853 commandEntry->connection = connection;
3854}
3855
Robert Carrf759f162018-11-13 12:57:11 -08003856void InputDispatcher::onFocusChangedLocked(const sp<InputWindowHandle>& newFocus) {
3857 sp<IBinder> token = newFocus != nullptr ? newFocus->getToken() : nullptr;
3858 CommandEntry* commandEntry = postCommandLocked(
3859 & InputDispatcher::doNotifyFocusChangedLockedInterruptible);
3860 commandEntry->token = token;
3861}
3862
Michael Wrightd02c5b62014-02-10 15:10:22 -08003863void InputDispatcher::onANRLocked(
3864 nsecs_t currentTime, const sp<InputApplicationHandle>& applicationHandle,
3865 const sp<InputWindowHandle>& windowHandle,
3866 nsecs_t eventTime, nsecs_t waitStartTime, const char* reason) {
3867 float dispatchLatency = (currentTime - eventTime) * 0.000001f;
3868 float waitDuration = (currentTime - waitStartTime) * 0.000001f;
3869 ALOGI("Application is not responding: %s. "
3870 "It has been %0.1fms since event, %0.1fms since wait started. Reason: %s",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003871 getApplicationWindowLabelLocked(applicationHandle, windowHandle).c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08003872 dispatchLatency, waitDuration, reason);
3873
3874 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07003875 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003876 struct tm tm;
3877 localtime_r(&t, &tm);
3878 char timestr[64];
3879 strftime(timestr, sizeof(timestr), "%F %T", &tm);
3880 mLastANRState.clear();
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003881 mLastANRState += INDENT "ANR:\n";
3882 mLastANRState += StringPrintf(INDENT2 "Time: %s\n", timestr);
3883 mLastANRState += StringPrintf(INDENT2 "Window: %s\n",
3884 getApplicationWindowLabelLocked(applicationHandle, windowHandle).c_str());
3885 mLastANRState += StringPrintf(INDENT2 "DispatchLatency: %0.1fms\n", dispatchLatency);
3886 mLastANRState += StringPrintf(INDENT2 "WaitDuration: %0.1fms\n", waitDuration);
3887 mLastANRState += StringPrintf(INDENT2 "Reason: %s\n", reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003888 dumpDispatchStateLocked(mLastANRState);
3889
3890 CommandEntry* commandEntry = postCommandLocked(
3891 & InputDispatcher::doNotifyANRLockedInterruptible);
3892 commandEntry->inputApplicationHandle = applicationHandle;
Robert Carr5c8a0262018-10-03 16:30:44 -07003893 commandEntry->inputChannel = windowHandle != nullptr ?
3894 getInputChannelLocked(windowHandle->getToken()) : nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003895 commandEntry->reason = reason;
3896}
3897
3898void InputDispatcher::doNotifyConfigurationChangedInterruptible(
3899 CommandEntry* commandEntry) {
3900 mLock.unlock();
3901
3902 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
3903
3904 mLock.lock();
3905}
3906
3907void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(
3908 CommandEntry* commandEntry) {
3909 sp<Connection> connection = commandEntry->connection;
3910
3911 if (connection->status != Connection::STATUS_ZOMBIE) {
3912 mLock.unlock();
3913
Robert Carr803535b2018-08-02 16:38:15 -07003914 mPolicy->notifyInputChannelBroken(connection->inputChannel->getToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003915
3916 mLock.lock();
3917 }
3918}
3919
Robert Carrf759f162018-11-13 12:57:11 -08003920void InputDispatcher::doNotifyFocusChangedLockedInterruptible(
3921 CommandEntry* commandEntry) {
3922 sp<IBinder> token = commandEntry->token;
3923 mLock.unlock();
3924 mPolicy->notifyFocusChanged(token);
3925 mLock.lock();
3926}
3927
Michael Wrightd02c5b62014-02-10 15:10:22 -08003928void InputDispatcher::doNotifyANRLockedInterruptible(
3929 CommandEntry* commandEntry) {
3930 mLock.unlock();
3931
3932 nsecs_t newTimeout = mPolicy->notifyANR(
Robert Carr803535b2018-08-02 16:38:15 -07003933 commandEntry->inputApplicationHandle,
3934 commandEntry->inputChannel ? commandEntry->inputChannel->getToken() : nullptr,
Michael Wrightd02c5b62014-02-10 15:10:22 -08003935 commandEntry->reason);
3936
3937 mLock.lock();
3938
3939 resumeAfterTargetsNotReadyTimeoutLocked(newTimeout,
Robert Carr803535b2018-08-02 16:38:15 -07003940 commandEntry->inputChannel);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003941}
3942
3943void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
3944 CommandEntry* commandEntry) {
3945 KeyEntry* entry = commandEntry->keyEntry;
3946
3947 KeyEvent event;
3948 initializeKeyEvent(&event, entry);
3949
3950 mLock.unlock();
3951
Michael Wright2b3c3302018-03-02 17:19:13 +00003952 android::base::Timer t;
Robert Carr803535b2018-08-02 16:38:15 -07003953 sp<IBinder> token = commandEntry->inputChannel != nullptr ?
3954 commandEntry->inputChannel->getToken() : nullptr;
3955 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(token,
Michael Wrightd02c5b62014-02-10 15:10:22 -08003956 &event, entry->policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003957 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3958 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
3959 std::to_string(t.duration().count()).c_str());
3960 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003961
3962 mLock.lock();
3963
3964 if (delay < 0) {
3965 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
3966 } else if (!delay) {
3967 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
3968 } else {
3969 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
3970 entry->interceptKeyWakeupTime = now() + delay;
3971 }
3972 entry->release();
3973}
3974
3975void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(
3976 CommandEntry* commandEntry) {
3977 sp<Connection> connection = commandEntry->connection;
3978 nsecs_t finishTime = commandEntry->eventTime;
3979 uint32_t seq = commandEntry->seq;
3980 bool handled = commandEntry->handled;
3981
3982 // Handle post-event policy actions.
3983 DispatchEntry* dispatchEntry = connection->findWaitQueueEntry(seq);
3984 if (dispatchEntry) {
3985 nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
3986 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003987 std::string msg =
3988 StringPrintf("Window '%s' spent %0.1fms processing the last input event: ",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08003989 connection->getWindowName().c_str(), eventDuration * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003990 dispatchEntry->eventEntry->appendDescription(msg);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003991 ALOGI("%s", msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003992 }
3993
3994 bool restartEvent;
3995 if (dispatchEntry->eventEntry->type == EventEntry::TYPE_KEY) {
3996 KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry);
3997 restartEvent = afterKeyEventLockedInterruptible(connection,
3998 dispatchEntry, keyEntry, handled);
3999 } else if (dispatchEntry->eventEntry->type == EventEntry::TYPE_MOTION) {
4000 MotionEntry* motionEntry = static_cast<MotionEntry*>(dispatchEntry->eventEntry);
4001 restartEvent = afterMotionEventLockedInterruptible(connection,
4002 dispatchEntry, motionEntry, handled);
4003 } else {
4004 restartEvent = false;
4005 }
4006
4007 // Dequeue the event and start the next cycle.
4008 // Note that because the lock might have been released, it is possible that the
4009 // contents of the wait queue to have been drained, so we need to double-check
4010 // a few things.
4011 if (dispatchEntry == connection->findWaitQueueEntry(seq)) {
4012 connection->waitQueue.dequeue(dispatchEntry);
4013 traceWaitQueueLengthLocked(connection);
4014 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
4015 connection->outboundQueue.enqueueAtHead(dispatchEntry);
4016 traceOutboundQueueLengthLocked(connection);
4017 } else {
4018 releaseDispatchEntryLocked(dispatchEntry);
4019 }
4020 }
4021
4022 // Start the next dispatch cycle for this connection.
4023 startDispatchCycleLocked(now(), connection);
4024 }
4025}
4026
4027bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
4028 DispatchEntry* dispatchEntry, KeyEntry* keyEntry, bool handled) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004029 if (keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004030 if (!handled) {
4031 // Report the key as unhandled, since the fallback was not handled.
4032 mReporter->reportUnhandledKey(keyEntry->sequenceNum);
4033 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004034 return false;
4035 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004036
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004037 // Get the fallback key state.
4038 // Clear it out after dispatching the UP.
4039 int32_t originalKeyCode = keyEntry->keyCode;
4040 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
4041 if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
4042 connection->inputState.removeFallbackKey(originalKeyCode);
4043 }
4044
4045 if (handled || !dispatchEntry->hasForegroundTarget()) {
4046 // If the application handles the original key for which we previously
4047 // generated a fallback or if the window is not a foreground window,
4048 // then cancel the associated fallback key, if any.
4049 if (fallbackKeyCode != -1) {
4050 // Dispatch the unhandled key to the policy with the cancel flag.
Michael Wrightd02c5b62014-02-10 15:10:22 -08004051#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004052 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
Michael Wrightd02c5b62014-02-10 15:10:22 -08004053 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4054 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
4055 keyEntry->policyFlags);
4056#endif
4057 KeyEvent event;
4058 initializeKeyEvent(&event, keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004059 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004060
4061 mLock.unlock();
4062
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004063 mPolicy->dispatchUnhandledKey(connection->inputChannel->getToken(),
4064 &event, keyEntry->policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004065
4066 mLock.lock();
4067
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004068 // Cancel the fallback key.
4069 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004070 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004071 "application handled the original non-fallback key "
4072 "or is no longer a foreground target, "
4073 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004074 options.keyCode = fallbackKeyCode;
4075 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004076 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004077 connection->inputState.removeFallbackKey(originalKeyCode);
4078 }
4079 } else {
4080 // If the application did not handle a non-fallback key, first check
4081 // that we are in a good state to perform unhandled key event processing
4082 // Then ask the policy what to do with it.
4083 bool initialDown = keyEntry->action == AKEY_EVENT_ACTION_DOWN
4084 && keyEntry->repeatCount == 0;
4085 if (fallbackKeyCode == -1 && !initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004086#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004087 ALOGD("Unhandled key event: Skipping unhandled key event processing "
4088 "since this is not an initial down. "
4089 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4090 originalKeyCode, keyEntry->action, keyEntry->repeatCount,
4091 keyEntry->policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004092#endif
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004093 return false;
4094 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004095
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004096 // Dispatch the unhandled key to the policy.
4097#if DEBUG_OUTBOUND_EVENT_DETAILS
4098 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
4099 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4100 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
4101 keyEntry->policyFlags);
4102#endif
4103 KeyEvent event;
4104 initializeKeyEvent(&event, keyEntry);
4105
4106 mLock.unlock();
4107
4108 bool fallback = mPolicy->dispatchUnhandledKey(connection->inputChannel->getToken(),
4109 &event, keyEntry->policyFlags, &event);
4110
4111 mLock.lock();
4112
4113 if (connection->status != Connection::STATUS_NORMAL) {
4114 connection->inputState.removeFallbackKey(originalKeyCode);
4115 return false;
4116 }
4117
4118 // Latch the fallback keycode for this key on an initial down.
4119 // The fallback keycode cannot change at any other point in the lifecycle.
4120 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004121 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004122 fallbackKeyCode = event.getKeyCode();
4123 } else {
4124 fallbackKeyCode = AKEYCODE_UNKNOWN;
4125 }
4126 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
4127 }
4128
4129 ALOG_ASSERT(fallbackKeyCode != -1);
4130
4131 // Cancel the fallback key if the policy decides not to send it anymore.
4132 // We will continue to dispatch the key to the policy but we will no
4133 // longer dispatch a fallback key to the application.
4134 if (fallbackKeyCode != AKEYCODE_UNKNOWN
4135 && (!fallback || fallbackKeyCode != event.getKeyCode())) {
4136#if DEBUG_OUTBOUND_EVENT_DETAILS
4137 if (fallback) {
4138 ALOGD("Unhandled key event: Policy requested to send key %d"
4139 "as a fallback for %d, but on the DOWN it had requested "
4140 "to send %d instead. Fallback canceled.",
4141 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
4142 } else {
4143 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
4144 "but on the DOWN it had requested to send %d. "
4145 "Fallback canceled.",
4146 originalKeyCode, fallbackKeyCode);
4147 }
4148#endif
4149
4150 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
4151 "canceling fallback, policy no longer desires it");
4152 options.keyCode = fallbackKeyCode;
4153 synthesizeCancelationEventsForConnectionLocked(connection, options);
4154
4155 fallback = false;
4156 fallbackKeyCode = AKEYCODE_UNKNOWN;
4157 if (keyEntry->action != AKEY_EVENT_ACTION_UP) {
4158 connection->inputState.setFallbackKey(originalKeyCode,
4159 fallbackKeyCode);
4160 }
4161 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004162
4163#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004164 {
4165 std::string msg;
4166 const KeyedVector<int32_t, int32_t>& fallbackKeys =
4167 connection->inputState.getFallbackKeys();
4168 for (size_t i = 0; i < fallbackKeys.size(); i++) {
4169 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i),
4170 fallbackKeys.valueAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004171 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004172 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
4173 fallbackKeys.size(), msg.c_str());
4174 }
4175#endif
4176
4177 if (fallback) {
4178 // Restart the dispatch cycle using the fallback key.
4179 keyEntry->eventTime = event.getEventTime();
4180 keyEntry->deviceId = event.getDeviceId();
4181 keyEntry->source = event.getSource();
4182 keyEntry->displayId = event.getDisplayId();
4183 keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
4184 keyEntry->keyCode = fallbackKeyCode;
4185 keyEntry->scanCode = event.getScanCode();
4186 keyEntry->metaState = event.getMetaState();
4187 keyEntry->repeatCount = event.getRepeatCount();
4188 keyEntry->downTime = event.getDownTime();
4189 keyEntry->syntheticRepeat = false;
4190
4191#if DEBUG_OUTBOUND_EVENT_DETAILS
4192 ALOGD("Unhandled key event: Dispatching fallback key. "
4193 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
4194 originalKeyCode, fallbackKeyCode, keyEntry->metaState);
4195#endif
4196 return true; // restart the event
4197 } else {
4198#if DEBUG_OUTBOUND_EVENT_DETAILS
4199 ALOGD("Unhandled key event: No fallback key.");
4200#endif
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004201
4202 // Report the key as unhandled, since there is no fallback key.
4203 mReporter->reportUnhandledKey(keyEntry->sequenceNum);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004204 }
4205 }
4206 return false;
4207}
4208
4209bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
4210 DispatchEntry* dispatchEntry, MotionEntry* motionEntry, bool handled) {
4211 return false;
4212}
4213
4214void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
4215 mLock.unlock();
4216
4217 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
4218
4219 mLock.lock();
4220}
4221
4222void InputDispatcher::initializeKeyEvent(KeyEvent* event, const KeyEntry* entry) {
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004223 event->initialize(entry->deviceId, entry->source, entry->displayId, entry->action, entry->flags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004224 entry->keyCode, entry->scanCode, entry->metaState, entry->repeatCount,
4225 entry->downTime, entry->eventTime);
4226}
4227
4228void InputDispatcher::updateDispatchStatisticsLocked(nsecs_t currentTime, const EventEntry* entry,
4229 int32_t injectionResult, nsecs_t timeSpentWaitingForApplication) {
4230 // TODO Write some statistics about how long we spend waiting.
4231}
4232
4233void InputDispatcher::traceInboundQueueLengthLocked() {
4234 if (ATRACE_ENABLED()) {
4235 ATRACE_INT("iq", mInboundQueue.count());
4236 }
4237}
4238
4239void InputDispatcher::traceOutboundQueueLengthLocked(const sp<Connection>& connection) {
4240 if (ATRACE_ENABLED()) {
4241 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004242 snprintf(counterName, sizeof(counterName), "oq:%s", connection->getWindowName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004243 ATRACE_INT(counterName, connection->outboundQueue.count());
4244 }
4245}
4246
4247void InputDispatcher::traceWaitQueueLengthLocked(const sp<Connection>& connection) {
4248 if (ATRACE_ENABLED()) {
4249 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004250 snprintf(counterName, sizeof(counterName), "wq:%s", connection->getWindowName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004251 ATRACE_INT(counterName, connection->waitQueue.count());
4252 }
4253}
4254
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004255void InputDispatcher::dump(std::string& dump) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004256 AutoMutex _l(mLock);
4257
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004258 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004259 dumpDispatchStateLocked(dump);
4260
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004261 if (!mLastANRState.empty()) {
4262 dump += "\nInput Dispatcher State at time of last ANR:\n";
4263 dump += mLastANRState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004264 }
4265}
4266
4267void InputDispatcher::monitor() {
4268 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
4269 mLock.lock();
4270 mLooper->wake();
4271 mDispatcherIsAliveCondition.wait(mLock);
4272 mLock.unlock();
4273}
4274
4275
Michael Wrightd02c5b62014-02-10 15:10:22 -08004276// --- InputDispatcher::InjectionState ---
4277
4278InputDispatcher::InjectionState::InjectionState(int32_t injectorPid, int32_t injectorUid) :
4279 refCount(1),
4280 injectorPid(injectorPid), injectorUid(injectorUid),
4281 injectionResult(INPUT_EVENT_INJECTION_PENDING), injectionIsAsync(false),
4282 pendingForegroundDispatches(0) {
4283}
4284
4285InputDispatcher::InjectionState::~InjectionState() {
4286}
4287
4288void InputDispatcher::InjectionState::release() {
4289 refCount -= 1;
4290 if (refCount == 0) {
4291 delete this;
4292 } else {
4293 ALOG_ASSERT(refCount > 0);
4294 }
4295}
4296
4297
4298// --- InputDispatcher::EventEntry ---
4299
Prabir Pradhan42611e02018-11-27 14:04:02 -08004300InputDispatcher::EventEntry::EventEntry(uint32_t sequenceNum, int32_t type,
4301 nsecs_t eventTime, uint32_t policyFlags) :
4302 sequenceNum(sequenceNum), refCount(1), type(type), eventTime(eventTime),
4303 policyFlags(policyFlags), injectionState(nullptr), dispatchInProgress(false) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004304}
4305
4306InputDispatcher::EventEntry::~EventEntry() {
4307 releaseInjectionState();
4308}
4309
4310void InputDispatcher::EventEntry::release() {
4311 refCount -= 1;
4312 if (refCount == 0) {
4313 delete this;
4314 } else {
4315 ALOG_ASSERT(refCount > 0);
4316 }
4317}
4318
4319void InputDispatcher::EventEntry::releaseInjectionState() {
4320 if (injectionState) {
4321 injectionState->release();
Yi Kong9b14ac62018-07-17 13:48:38 -07004322 injectionState = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004323 }
4324}
4325
4326
4327// --- InputDispatcher::ConfigurationChangedEntry ---
4328
Prabir Pradhan42611e02018-11-27 14:04:02 -08004329InputDispatcher::ConfigurationChangedEntry::ConfigurationChangedEntry(
4330 uint32_t sequenceNum, nsecs_t eventTime) :
4331 EventEntry(sequenceNum, TYPE_CONFIGURATION_CHANGED, eventTime, 0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004332}
4333
4334InputDispatcher::ConfigurationChangedEntry::~ConfigurationChangedEntry() {
4335}
4336
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004337void InputDispatcher::ConfigurationChangedEntry::appendDescription(std::string& msg) const {
4338 msg += StringPrintf("ConfigurationChangedEvent(), policyFlags=0x%08x", policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004339}
4340
4341
4342// --- InputDispatcher::DeviceResetEntry ---
4343
Prabir Pradhan42611e02018-11-27 14:04:02 -08004344InputDispatcher::DeviceResetEntry::DeviceResetEntry(
4345 uint32_t sequenceNum, nsecs_t eventTime, int32_t deviceId) :
4346 EventEntry(sequenceNum, TYPE_DEVICE_RESET, eventTime, 0),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004347 deviceId(deviceId) {
4348}
4349
4350InputDispatcher::DeviceResetEntry::~DeviceResetEntry() {
4351}
4352
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004353void InputDispatcher::DeviceResetEntry::appendDescription(std::string& msg) const {
4354 msg += StringPrintf("DeviceResetEvent(deviceId=%d), policyFlags=0x%08x",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004355 deviceId, policyFlags);
4356}
4357
4358
4359// --- InputDispatcher::KeyEntry ---
4360
Prabir Pradhan42611e02018-11-27 14:04:02 -08004361InputDispatcher::KeyEntry::KeyEntry(uint32_t sequenceNum, nsecs_t eventTime,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004362 int32_t deviceId, uint32_t source, int32_t displayId, uint32_t policyFlags, int32_t action,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004363 int32_t flags, int32_t keyCode, int32_t scanCode, int32_t metaState,
4364 int32_t repeatCount, nsecs_t downTime) :
Prabir Pradhan42611e02018-11-27 14:04:02 -08004365 EventEntry(sequenceNum, TYPE_KEY, eventTime, policyFlags),
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004366 deviceId(deviceId), source(source), displayId(displayId), action(action), flags(flags),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004367 keyCode(keyCode), scanCode(scanCode), metaState(metaState),
4368 repeatCount(repeatCount), downTime(downTime),
4369 syntheticRepeat(false), interceptKeyResult(KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN),
4370 interceptKeyWakeupTime(0) {
4371}
4372
4373InputDispatcher::KeyEntry::~KeyEntry() {
4374}
4375
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004376void InputDispatcher::KeyEntry::appendDescription(std::string& msg) const {
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004377 msg += StringPrintf("KeyEvent(deviceId=%d, source=0x%08x, displayId=%" PRId32 ", action=%s, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08004378 "flags=0x%08x, keyCode=%d, scanCode=%d, metaState=0x%08x, "
4379 "repeatCount=%d), policyFlags=0x%08x",
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004380 deviceId, source, displayId, keyActionToString(action).c_str(), flags, keyCode,
Siarhei Vishniakoub48188a2018-03-01 20:55:47 -08004381 scanCode, metaState, repeatCount, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004382}
4383
4384void InputDispatcher::KeyEntry::recycle() {
4385 releaseInjectionState();
4386
4387 dispatchInProgress = false;
4388 syntheticRepeat = false;
4389 interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
4390 interceptKeyWakeupTime = 0;
4391}
4392
4393
4394// --- InputDispatcher::MotionEntry ---
4395
Prabir Pradhan42611e02018-11-27 14:04:02 -08004396InputDispatcher::MotionEntry::MotionEntry(uint32_t sequenceNum, nsecs_t eventTime, int32_t deviceId,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004397 uint32_t source, int32_t displayId, uint32_t policyFlags, int32_t action,
4398 int32_t actionButton,
Michael Wright7b159c92015-05-14 14:48:03 +01004399 int32_t flags, int32_t metaState, int32_t buttonState, int32_t edgeFlags,
4400 float xPrecision, float yPrecision, nsecs_t downTime,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004401 uint32_t pointerCount,
Jeff Brownf086ddb2014-02-11 14:28:48 -08004402 const PointerProperties* pointerProperties, const PointerCoords* pointerCoords,
4403 float xOffset, float yOffset) :
Prabir Pradhan42611e02018-11-27 14:04:02 -08004404 EventEntry(sequenceNum, TYPE_MOTION, eventTime, policyFlags),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004405 eventTime(eventTime),
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004406 deviceId(deviceId), source(source), displayId(displayId), action(action),
4407 actionButton(actionButton), flags(flags), metaState(metaState), buttonState(buttonState),
Michael Wright7b159c92015-05-14 14:48:03 +01004408 edgeFlags(edgeFlags), xPrecision(xPrecision), yPrecision(yPrecision),
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004409 downTime(downTime), pointerCount(pointerCount) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004410 for (uint32_t i = 0; i < pointerCount; i++) {
4411 this->pointerProperties[i].copyFrom(pointerProperties[i]);
4412 this->pointerCoords[i].copyFrom(pointerCoords[i]);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004413 if (xOffset || yOffset) {
4414 this->pointerCoords[i].applyOffset(xOffset, yOffset);
4415 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004416 }
4417}
4418
4419InputDispatcher::MotionEntry::~MotionEntry() {
4420}
4421
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004422void InputDispatcher::MotionEntry::appendDescription(std::string& msg) const {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004423 msg += StringPrintf("MotionEvent(deviceId=%d, source=0x%08x, displayId=%" PRId32
Siarhei Vishniakoub48188a2018-03-01 20:55:47 -08004424 ", action=%s, actionButton=0x%08x, flags=0x%08x, metaState=0x%08x, buttonState=0x%08x, "
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004425 "edgeFlags=0x%08x, xPrecision=%.1f, yPrecision=%.1f, pointers=[",
Siarhei Vishniakoub48188a2018-03-01 20:55:47 -08004426 deviceId, source, displayId, motionActionToString(action).c_str(), actionButton, flags,
4427 metaState, buttonState, edgeFlags, xPrecision, yPrecision);
4428
Michael Wrightd02c5b62014-02-10 15:10:22 -08004429 for (uint32_t i = 0; i < pointerCount; i++) {
4430 if (i) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004431 msg += ", ";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004432 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004433 msg += StringPrintf("%d: (%.1f, %.1f)", pointerProperties[i].id,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004434 pointerCoords[i].getX(), pointerCoords[i].getY());
4435 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004436 msg += StringPrintf("]), policyFlags=0x%08x", policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004437}
4438
4439
4440// --- InputDispatcher::DispatchEntry ---
4441
4442volatile int32_t InputDispatcher::DispatchEntry::sNextSeqAtomic;
4443
4444InputDispatcher::DispatchEntry::DispatchEntry(EventEntry* eventEntry,
Robert Carre07e1032018-11-26 12:55:53 -08004445 int32_t targetFlags, float xOffset, float yOffset, float globalScaleFactor,
4446 float windowXScale, float windowYScale) :
Michael Wrightd02c5b62014-02-10 15:10:22 -08004447 seq(nextSeq()),
4448 eventEntry(eventEntry), targetFlags(targetFlags),
Robert Carre07e1032018-11-26 12:55:53 -08004449 xOffset(xOffset), yOffset(yOffset), globalScaleFactor(globalScaleFactor),
4450 windowXScale(windowXScale), windowYScale(windowYScale),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004451 deliveryTime(0), resolvedAction(0), resolvedFlags(0) {
4452 eventEntry->refCount += 1;
4453}
4454
4455InputDispatcher::DispatchEntry::~DispatchEntry() {
4456 eventEntry->release();
4457}
4458
4459uint32_t InputDispatcher::DispatchEntry::nextSeq() {
4460 // Sequence number 0 is reserved and will never be returned.
4461 uint32_t seq;
4462 do {
4463 seq = android_atomic_inc(&sNextSeqAtomic);
4464 } while (!seq);
4465 return seq;
4466}
4467
4468
4469// --- InputDispatcher::InputState ---
4470
4471InputDispatcher::InputState::InputState() {
4472}
4473
4474InputDispatcher::InputState::~InputState() {
4475}
4476
4477bool InputDispatcher::InputState::isNeutral() const {
4478 return mKeyMementos.isEmpty() && mMotionMementos.isEmpty();
4479}
4480
4481bool InputDispatcher::InputState::isHovering(int32_t deviceId, uint32_t source,
4482 int32_t displayId) const {
4483 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4484 const MotionMemento& memento = mMotionMementos.itemAt(i);
4485 if (memento.deviceId == deviceId
4486 && memento.source == source
4487 && memento.displayId == displayId
4488 && memento.hovering) {
4489 return true;
4490 }
4491 }
4492 return false;
4493}
4494
4495bool InputDispatcher::InputState::trackKey(const KeyEntry* entry,
4496 int32_t action, int32_t flags) {
4497 switch (action) {
4498 case AKEY_EVENT_ACTION_UP: {
4499 if (entry->flags & AKEY_EVENT_FLAG_FALLBACK) {
4500 for (size_t i = 0; i < mFallbackKeys.size(); ) {
4501 if (mFallbackKeys.valueAt(i) == entry->keyCode) {
4502 mFallbackKeys.removeItemsAt(i);
4503 } else {
4504 i += 1;
4505 }
4506 }
4507 }
4508 ssize_t index = findKeyMemento(entry);
4509 if (index >= 0) {
4510 mKeyMementos.removeAt(index);
4511 return true;
4512 }
4513 /* FIXME: We can't just drop the key up event because that prevents creating
4514 * popup windows that are automatically shown when a key is held and then
4515 * dismissed when the key is released. The problem is that the popup will
4516 * not have received the original key down, so the key up will be considered
4517 * to be inconsistent with its observed state. We could perhaps handle this
4518 * by synthesizing a key down but that will cause other problems.
4519 *
4520 * So for now, allow inconsistent key up events to be dispatched.
4521 *
4522#if DEBUG_OUTBOUND_EVENT_DETAILS
4523 ALOGD("Dropping inconsistent key up event: deviceId=%d, source=%08x, "
4524 "keyCode=%d, scanCode=%d",
4525 entry->deviceId, entry->source, entry->keyCode, entry->scanCode);
4526#endif
4527 return false;
4528 */
4529 return true;
4530 }
4531
4532 case AKEY_EVENT_ACTION_DOWN: {
4533 ssize_t index = findKeyMemento(entry);
4534 if (index >= 0) {
4535 mKeyMementos.removeAt(index);
4536 }
4537 addKeyMemento(entry, flags);
4538 return true;
4539 }
4540
4541 default:
4542 return true;
4543 }
4544}
4545
4546bool InputDispatcher::InputState::trackMotion(const MotionEntry* entry,
4547 int32_t action, int32_t flags) {
4548 int32_t actionMasked = action & AMOTION_EVENT_ACTION_MASK;
4549 switch (actionMasked) {
4550 case AMOTION_EVENT_ACTION_UP:
4551 case AMOTION_EVENT_ACTION_CANCEL: {
4552 ssize_t index = findMotionMemento(entry, false /*hovering*/);
4553 if (index >= 0) {
4554 mMotionMementos.removeAt(index);
4555 return true;
4556 }
4557#if DEBUG_OUTBOUND_EVENT_DETAILS
4558 ALOGD("Dropping inconsistent motion up or cancel event: deviceId=%d, source=%08x, "
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004559 "displayId=%" PRId32 ", actionMasked=%d",
4560 entry->deviceId, entry->source, entry->displayId, actionMasked);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004561#endif
4562 return false;
4563 }
4564
4565 case AMOTION_EVENT_ACTION_DOWN: {
4566 ssize_t index = findMotionMemento(entry, false /*hovering*/);
4567 if (index >= 0) {
4568 mMotionMementos.removeAt(index);
4569 }
4570 addMotionMemento(entry, flags, false /*hovering*/);
4571 return true;
4572 }
4573
4574 case AMOTION_EVENT_ACTION_POINTER_UP:
4575 case AMOTION_EVENT_ACTION_POINTER_DOWN:
4576 case AMOTION_EVENT_ACTION_MOVE: {
Michael Wright38dcdff2014-03-19 12:06:10 -07004577 if (entry->source & AINPUT_SOURCE_CLASS_NAVIGATION) {
4578 // Trackballs can send MOVE events with a corresponding DOWN or UP. There's no need to
4579 // generate cancellation events for these since they're based in relative rather than
4580 // absolute units.
4581 return true;
4582 }
4583
Michael Wrightd02c5b62014-02-10 15:10:22 -08004584 ssize_t index = findMotionMemento(entry, false /*hovering*/);
Michael Wright38dcdff2014-03-19 12:06:10 -07004585
4586 if (entry->source & AINPUT_SOURCE_CLASS_JOYSTICK) {
4587 // Joysticks can send MOVE events without a corresponding DOWN or UP. Since all
4588 // joystick axes are normalized to [-1, 1] we can trust that 0 means it's neutral. Any
4589 // other value and we need to track the motion so we can send cancellation events for
4590 // anything generating fallback events (e.g. DPad keys for joystick movements).
4591 if (index >= 0) {
4592 if (entry->pointerCoords[0].isEmpty()) {
4593 mMotionMementos.removeAt(index);
4594 } else {
4595 MotionMemento& memento = mMotionMementos.editItemAt(index);
4596 memento.setPointers(entry);
4597 }
4598 } else if (!entry->pointerCoords[0].isEmpty()) {
4599 addMotionMemento(entry, flags, false /*hovering*/);
4600 }
4601
4602 // Joysticks and trackballs can send MOVE events without corresponding DOWN or UP.
4603 return true;
4604 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004605 if (index >= 0) {
4606 MotionMemento& memento = mMotionMementos.editItemAt(index);
4607 memento.setPointers(entry);
4608 return true;
4609 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004610#if DEBUG_OUTBOUND_EVENT_DETAILS
4611 ALOGD("Dropping inconsistent motion pointer up/down or move event: "
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004612 "deviceId=%d, source=%08x, displayId=%" PRId32 ", actionMasked=%d",
4613 entry->deviceId, entry->source, entry->displayId, actionMasked);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004614#endif
4615 return false;
4616 }
4617
4618 case AMOTION_EVENT_ACTION_HOVER_EXIT: {
4619 ssize_t index = findMotionMemento(entry, true /*hovering*/);
4620 if (index >= 0) {
4621 mMotionMementos.removeAt(index);
4622 return true;
4623 }
4624#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004625 ALOGD("Dropping inconsistent motion hover exit event: deviceId=%d, source=%08x, "
4626 "displayId=%" PRId32,
4627 entry->deviceId, entry->source, entry->displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004628#endif
4629 return false;
4630 }
4631
4632 case AMOTION_EVENT_ACTION_HOVER_ENTER:
4633 case AMOTION_EVENT_ACTION_HOVER_MOVE: {
4634 ssize_t index = findMotionMemento(entry, true /*hovering*/);
4635 if (index >= 0) {
4636 mMotionMementos.removeAt(index);
4637 }
4638 addMotionMemento(entry, flags, true /*hovering*/);
4639 return true;
4640 }
4641
4642 default:
4643 return true;
4644 }
4645}
4646
4647ssize_t InputDispatcher::InputState::findKeyMemento(const KeyEntry* entry) const {
4648 for (size_t i = 0; i < mKeyMementos.size(); i++) {
4649 const KeyMemento& memento = mKeyMementos.itemAt(i);
4650 if (memento.deviceId == entry->deviceId
4651 && memento.source == entry->source
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004652 && memento.displayId == entry->displayId
Michael Wrightd02c5b62014-02-10 15:10:22 -08004653 && memento.keyCode == entry->keyCode
4654 && memento.scanCode == entry->scanCode) {
4655 return i;
4656 }
4657 }
4658 return -1;
4659}
4660
4661ssize_t InputDispatcher::InputState::findMotionMemento(const MotionEntry* entry,
4662 bool hovering) const {
4663 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4664 const MotionMemento& memento = mMotionMementos.itemAt(i);
4665 if (memento.deviceId == entry->deviceId
4666 && memento.source == entry->source
4667 && memento.displayId == entry->displayId
4668 && memento.hovering == hovering) {
4669 return i;
4670 }
4671 }
4672 return -1;
4673}
4674
4675void InputDispatcher::InputState::addKeyMemento(const KeyEntry* entry, int32_t flags) {
4676 mKeyMementos.push();
4677 KeyMemento& memento = mKeyMementos.editTop();
4678 memento.deviceId = entry->deviceId;
4679 memento.source = entry->source;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004680 memento.displayId = entry->displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004681 memento.keyCode = entry->keyCode;
4682 memento.scanCode = entry->scanCode;
4683 memento.metaState = entry->metaState;
4684 memento.flags = flags;
4685 memento.downTime = entry->downTime;
4686 memento.policyFlags = entry->policyFlags;
4687}
4688
4689void InputDispatcher::InputState::addMotionMemento(const MotionEntry* entry,
4690 int32_t flags, bool hovering) {
4691 mMotionMementos.push();
4692 MotionMemento& memento = mMotionMementos.editTop();
4693 memento.deviceId = entry->deviceId;
4694 memento.source = entry->source;
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004695 memento.displayId = entry->displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004696 memento.flags = flags;
4697 memento.xPrecision = entry->xPrecision;
4698 memento.yPrecision = entry->yPrecision;
4699 memento.downTime = entry->downTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004700 memento.setPointers(entry);
4701 memento.hovering = hovering;
4702 memento.policyFlags = entry->policyFlags;
4703}
4704
4705void InputDispatcher::InputState::MotionMemento::setPointers(const MotionEntry* entry) {
4706 pointerCount = entry->pointerCount;
4707 for (uint32_t i = 0; i < entry->pointerCount; i++) {
4708 pointerProperties[i].copyFrom(entry->pointerProperties[i]);
4709 pointerCoords[i].copyFrom(entry->pointerCoords[i]);
4710 }
4711}
4712
4713void InputDispatcher::InputState::synthesizeCancelationEvents(nsecs_t currentTime,
4714 Vector<EventEntry*>& outEvents, const CancelationOptions& options) {
4715 for (size_t i = 0; i < mKeyMementos.size(); i++) {
4716 const KeyMemento& memento = mKeyMementos.itemAt(i);
4717 if (shouldCancelKey(memento, options)) {
Prabir Pradhan42611e02018-11-27 14:04:02 -08004718 outEvents.push(new KeyEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, currentTime,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004719 memento.deviceId, memento.source, memento.displayId, memento.policyFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004720 AKEY_EVENT_ACTION_UP, memento.flags | AKEY_EVENT_FLAG_CANCELED,
4721 memento.keyCode, memento.scanCode, memento.metaState, 0, memento.downTime));
4722 }
4723 }
4724
4725 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4726 const MotionMemento& memento = mMotionMementos.itemAt(i);
4727 if (shouldCancelMotion(memento, options)) {
Prabir Pradhan42611e02018-11-27 14:04:02 -08004728 outEvents.push(new MotionEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, currentTime,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004729 memento.deviceId, memento.source, memento.displayId, memento.policyFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004730 memento.hovering
4731 ? AMOTION_EVENT_ACTION_HOVER_EXIT
4732 : AMOTION_EVENT_ACTION_CANCEL,
Michael Wright7b159c92015-05-14 14:48:03 +01004733 memento.flags, 0, 0, 0, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004734 memento.xPrecision, memento.yPrecision, memento.downTime,
Jeff Brownf086ddb2014-02-11 14:28:48 -08004735 memento.pointerCount, memento.pointerProperties, memento.pointerCoords,
4736 0, 0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004737 }
4738 }
4739}
4740
4741void InputDispatcher::InputState::clear() {
4742 mKeyMementos.clear();
4743 mMotionMementos.clear();
4744 mFallbackKeys.clear();
4745}
4746
4747void InputDispatcher::InputState::copyPointerStateTo(InputState& other) const {
4748 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4749 const MotionMemento& memento = mMotionMementos.itemAt(i);
4750 if (memento.source & AINPUT_SOURCE_CLASS_POINTER) {
4751 for (size_t j = 0; j < other.mMotionMementos.size(); ) {
4752 const MotionMemento& otherMemento = other.mMotionMementos.itemAt(j);
4753 if (memento.deviceId == otherMemento.deviceId
4754 && memento.source == otherMemento.source
4755 && memento.displayId == otherMemento.displayId) {
4756 other.mMotionMementos.removeAt(j);
4757 } else {
4758 j += 1;
4759 }
4760 }
4761 other.mMotionMementos.push(memento);
4762 }
4763 }
4764}
4765
4766int32_t InputDispatcher::InputState::getFallbackKey(int32_t originalKeyCode) {
4767 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
4768 return index >= 0 ? mFallbackKeys.valueAt(index) : -1;
4769}
4770
4771void InputDispatcher::InputState::setFallbackKey(int32_t originalKeyCode,
4772 int32_t fallbackKeyCode) {
4773 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
4774 if (index >= 0) {
4775 mFallbackKeys.replaceValueAt(index, fallbackKeyCode);
4776 } else {
4777 mFallbackKeys.add(originalKeyCode, fallbackKeyCode);
4778 }
4779}
4780
4781void InputDispatcher::InputState::removeFallbackKey(int32_t originalKeyCode) {
4782 mFallbackKeys.removeItem(originalKeyCode);
4783}
4784
4785bool InputDispatcher::InputState::shouldCancelKey(const KeyMemento& memento,
4786 const CancelationOptions& options) {
4787 if (options.keyCode != -1 && memento.keyCode != options.keyCode) {
4788 return false;
4789 }
4790
4791 if (options.deviceId != -1 && memento.deviceId != options.deviceId) {
4792 return false;
4793 }
4794
4795 switch (options.mode) {
4796 case CancelationOptions::CANCEL_ALL_EVENTS:
4797 case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
4798 return true;
4799 case CancelationOptions::CANCEL_FALLBACK_EVENTS:
4800 return memento.flags & AKEY_EVENT_FLAG_FALLBACK;
Tiger Huang721e26f2018-07-24 22:26:19 +08004801 case CancelationOptions::CANCEL_DISPLAY_UNSPECIFIED_EVENTS:
4802 return memento.displayId == ADISPLAY_ID_NONE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004803 default:
4804 return false;
4805 }
4806}
4807
4808bool InputDispatcher::InputState::shouldCancelMotion(const MotionMemento& memento,
4809 const CancelationOptions& options) {
4810 if (options.deviceId != -1 && memento.deviceId != options.deviceId) {
4811 return false;
4812 }
4813
4814 switch (options.mode) {
4815 case CancelationOptions::CANCEL_ALL_EVENTS:
4816 return true;
4817 case CancelationOptions::CANCEL_POINTER_EVENTS:
4818 return memento.source & AINPUT_SOURCE_CLASS_POINTER;
4819 case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
4820 return !(memento.source & AINPUT_SOURCE_CLASS_POINTER);
Tiger Huang721e26f2018-07-24 22:26:19 +08004821 case CancelationOptions::CANCEL_DISPLAY_UNSPECIFIED_EVENTS:
4822 return memento.displayId == ADISPLAY_ID_NONE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004823 default:
4824 return false;
4825 }
4826}
4827
4828
4829// --- InputDispatcher::Connection ---
4830
Robert Carr803535b2018-08-02 16:38:15 -07004831InputDispatcher::Connection::Connection(const sp<InputChannel>& inputChannel, bool monitor) :
4832 status(STATUS_NORMAL), inputChannel(inputChannel),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004833 monitor(monitor),
4834 inputPublisher(inputChannel), inputPublisherBlocked(false) {
4835}
4836
4837InputDispatcher::Connection::~Connection() {
4838}
4839
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004840const std::string InputDispatcher::Connection::getWindowName() const {
Robert Carr803535b2018-08-02 16:38:15 -07004841 if (inputChannel != nullptr) {
4842 return inputChannel->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004843 }
4844 if (monitor) {
4845 return "monitor";
4846 }
4847 return "?";
4848}
4849
4850const char* InputDispatcher::Connection::getStatusLabel() const {
4851 switch (status) {
4852 case STATUS_NORMAL:
4853 return "NORMAL";
4854
4855 case STATUS_BROKEN:
4856 return "BROKEN";
4857
4858 case STATUS_ZOMBIE:
4859 return "ZOMBIE";
4860
4861 default:
4862 return "UNKNOWN";
4863 }
4864}
4865
4866InputDispatcher::DispatchEntry* InputDispatcher::Connection::findWaitQueueEntry(uint32_t seq) {
Yi Kong9b14ac62018-07-17 13:48:38 -07004867 for (DispatchEntry* entry = waitQueue.head; entry != nullptr; entry = entry->next) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004868 if (entry->seq == seq) {
4869 return entry;
4870 }
4871 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004872 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004873}
4874
4875
4876// --- InputDispatcher::CommandEntry ---
4877
4878InputDispatcher::CommandEntry::CommandEntry(Command command) :
Yi Kong9b14ac62018-07-17 13:48:38 -07004879 command(command), eventTime(0), keyEntry(nullptr), userActivityEventType(0),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004880 seq(0), handled(false) {
4881}
4882
4883InputDispatcher::CommandEntry::~CommandEntry() {
4884}
4885
4886
4887// --- InputDispatcher::TouchState ---
4888
4889InputDispatcher::TouchState::TouchState() :
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004890 down(false), split(false), deviceId(-1), source(0), displayId(ADISPLAY_ID_NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004891}
4892
4893InputDispatcher::TouchState::~TouchState() {
4894}
4895
4896void InputDispatcher::TouchState::reset() {
4897 down = false;
4898 split = false;
4899 deviceId = -1;
4900 source = 0;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004901 displayId = ADISPLAY_ID_NONE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004902 windows.clear();
4903}
4904
4905void InputDispatcher::TouchState::copyFrom(const TouchState& other) {
4906 down = other.down;
4907 split = other.split;
4908 deviceId = other.deviceId;
4909 source = other.source;
4910 displayId = other.displayId;
4911 windows = other.windows;
4912}
4913
4914void InputDispatcher::TouchState::addOrUpdateWindow(const sp<InputWindowHandle>& windowHandle,
4915 int32_t targetFlags, BitSet32 pointerIds) {
4916 if (targetFlags & InputTarget::FLAG_SPLIT) {
4917 split = true;
4918 }
4919
4920 for (size_t i = 0; i < windows.size(); i++) {
4921 TouchedWindow& touchedWindow = windows.editItemAt(i);
4922 if (touchedWindow.windowHandle == windowHandle) {
4923 touchedWindow.targetFlags |= targetFlags;
4924 if (targetFlags & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
4925 touchedWindow.targetFlags &= ~InputTarget::FLAG_DISPATCH_AS_IS;
4926 }
4927 touchedWindow.pointerIds.value |= pointerIds.value;
4928 return;
4929 }
4930 }
4931
4932 windows.push();
4933
4934 TouchedWindow& touchedWindow = windows.editTop();
4935 touchedWindow.windowHandle = windowHandle;
4936 touchedWindow.targetFlags = targetFlags;
4937 touchedWindow.pointerIds = pointerIds;
4938}
4939
4940void InputDispatcher::TouchState::removeWindow(const sp<InputWindowHandle>& windowHandle) {
4941 for (size_t i = 0; i < windows.size(); i++) {
4942 if (windows.itemAt(i).windowHandle == windowHandle) {
4943 windows.removeAt(i);
4944 return;
4945 }
4946 }
4947}
4948
Robert Carr803535b2018-08-02 16:38:15 -07004949void InputDispatcher::TouchState::removeWindowByToken(const sp<IBinder>& token) {
4950 for (size_t i = 0; i < windows.size(); i++) {
Robert Carr5c8a0262018-10-03 16:30:44 -07004951 if (windows.itemAt(i).windowHandle->getToken() == token) {
Robert Carr803535b2018-08-02 16:38:15 -07004952 windows.removeAt(i);
4953 return;
4954 }
4955 }
4956}
4957
Michael Wrightd02c5b62014-02-10 15:10:22 -08004958void InputDispatcher::TouchState::filterNonAsIsTouchWindows() {
4959 for (size_t i = 0 ; i < windows.size(); ) {
4960 TouchedWindow& window = windows.editItemAt(i);
4961 if (window.targetFlags & (InputTarget::FLAG_DISPATCH_AS_IS
4962 | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER)) {
4963 window.targetFlags &= ~InputTarget::FLAG_DISPATCH_MASK;
4964 window.targetFlags |= InputTarget::FLAG_DISPATCH_AS_IS;
4965 i += 1;
4966 } else {
4967 windows.removeAt(i);
4968 }
4969 }
4970}
4971
4972sp<InputWindowHandle> InputDispatcher::TouchState::getFirstForegroundWindowHandle() const {
4973 for (size_t i = 0; i < windows.size(); i++) {
4974 const TouchedWindow& window = windows.itemAt(i);
4975 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
4976 return window.windowHandle;
4977 }
4978 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004979 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004980}
4981
4982bool InputDispatcher::TouchState::isSlippery() const {
4983 // Must have exactly one foreground window.
4984 bool haveSlipperyForegroundWindow = false;
4985 for (size_t i = 0; i < windows.size(); i++) {
4986 const TouchedWindow& window = windows.itemAt(i);
4987 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
4988 if (haveSlipperyForegroundWindow
4989 || !(window.windowHandle->getInfo()->layoutParamsFlags
4990 & InputWindowInfo::FLAG_SLIPPERY)) {
4991 return false;
4992 }
4993 haveSlipperyForegroundWindow = true;
4994 }
4995 }
4996 return haveSlipperyForegroundWindow;
4997}
4998
4999
5000// --- InputDispatcherThread ---
5001
5002InputDispatcherThread::InputDispatcherThread(const sp<InputDispatcherInterface>& dispatcher) :
5003 Thread(/*canCallJava*/ true), mDispatcher(dispatcher) {
5004}
5005
5006InputDispatcherThread::~InputDispatcherThread() {
5007}
5008
5009bool InputDispatcherThread::threadLoop() {
5010 mDispatcher->dispatchOnce();
5011 return true;
5012}
5013
5014} // namespace android