blob: 57181c293cec49ea4703ccc38c661bf3a65e7a44 [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
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800218static void dumpRegion(std::string& dump, const Region& region) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800219 if (region.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800220 dump += "<empty>";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800221 return;
222 }
223
224 bool first = true;
225 Region::const_iterator cur = region.begin();
226 Region::const_iterator const tail = region.end();
227 while (cur != tail) {
228 if (first) {
229 first = false;
230 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800231 dump += "|";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800232 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800233 dump += StringPrintf("[%d,%d][%d,%d]", cur->left, cur->top, cur->right, cur->bottom);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800234 cur++;
235 }
236}
237
Tiger Huang721e26f2018-07-24 22:26:19 +0800238template<typename T, typename U>
239static T getValueByKey(std::unordered_map<U, T>& map, U key) {
240 typename std::unordered_map<U, T>::const_iterator it = map.find(key);
241 return it != map.end() ? it->second : T{};
242}
243
Michael Wrightd02c5b62014-02-10 15:10:22 -0800244
245// --- InputDispatcher ---
246
247InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy) :
248 mPolicy(policy),
Yi Kong9b14ac62018-07-17 13:48:38 -0700249 mPendingEvent(nullptr), mLastDropReason(DROP_REASON_NOT_DROPPED),
Michael Wright3a981722015-06-10 15:26:13 +0100250 mAppSwitchSawKeyDown(false), mAppSwitchDueTime(LONG_LONG_MAX),
Yi Kong9b14ac62018-07-17 13:48:38 -0700251 mNextUnblockedEvent(nullptr),
Michael Wrightd02c5b62014-02-10 15:10:22 -0800252 mDispatchEnabled(false), mDispatchFrozen(false), mInputFilterEnabled(false),
Tiger Huang721e26f2018-07-24 22:26:19 +0800253 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
Michael Wrightd02c5b62014-02-10 15:10:22 -0800254 mInputTargetWaitCause(INPUT_TARGET_WAIT_CAUSE_NONE) {
255 mLooper = new Looper(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800256 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800257
Yi Kong9b14ac62018-07-17 13:48:38 -0700258 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800259
260 policy->getDispatcherConfiguration(&mConfig);
261}
262
263InputDispatcher::~InputDispatcher() {
264 { // acquire lock
265 AutoMutex _l(mLock);
266
267 resetKeyRepeatLocked();
268 releasePendingEventLocked();
269 drainInboundQueueLocked();
270 }
271
272 while (mConnectionsByFd.size() != 0) {
273 unregisterInputChannel(mConnectionsByFd.valueAt(0)->inputChannel);
274 }
275}
276
277void InputDispatcher::dispatchOnce() {
278 nsecs_t nextWakeupTime = LONG_LONG_MAX;
279 { // acquire lock
280 AutoMutex _l(mLock);
281 mDispatcherIsAliveCondition.broadcast();
282
283 // Run a dispatch loop if there are no pending commands.
284 // The dispatch loop might enqueue commands to run afterwards.
285 if (!haveCommandsLocked()) {
286 dispatchOnceInnerLocked(&nextWakeupTime);
287 }
288
289 // Run all pending commands if there are any.
290 // If any commands were run then force the next poll to wake up immediately.
291 if (runCommandsLockedInterruptible()) {
292 nextWakeupTime = LONG_LONG_MIN;
293 }
294 } // release lock
295
296 // Wait for callback or timeout or wake. (make sure we round up, not down)
297 nsecs_t currentTime = now();
298 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
299 mLooper->pollOnce(timeoutMillis);
300}
301
302void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
303 nsecs_t currentTime = now();
304
Jeff Browndc5992e2014-04-11 01:27:26 -0700305 // Reset the key repeat timer whenever normal dispatch is suspended while the
306 // device is in a non-interactive state. This is to ensure that we abort a key
307 // repeat if the device is just coming out of sleep.
308 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800309 resetKeyRepeatLocked();
310 }
311
312 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
313 if (mDispatchFrozen) {
314#if DEBUG_FOCUS
315 ALOGD("Dispatch frozen. Waiting some more.");
316#endif
317 return;
318 }
319
320 // Optimize latency of app switches.
321 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
322 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
323 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
324 if (mAppSwitchDueTime < *nextWakeupTime) {
325 *nextWakeupTime = mAppSwitchDueTime;
326 }
327
328 // Ready to start a new event.
329 // If we don't already have a pending event, go grab one.
330 if (! mPendingEvent) {
331 if (mInboundQueue.isEmpty()) {
332 if (isAppSwitchDue) {
333 // The inbound queue is empty so the app switch key we were waiting
334 // for will never arrive. Stop waiting for it.
335 resetPendingAppSwitchLocked(false);
336 isAppSwitchDue = false;
337 }
338
339 // Synthesize a key repeat if appropriate.
340 if (mKeyRepeatState.lastKeyEntry) {
341 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
342 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
343 } else {
344 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
345 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
346 }
347 }
348 }
349
350 // Nothing to do if there is no pending event.
351 if (!mPendingEvent) {
352 return;
353 }
354 } else {
355 // Inbound queue has at least one entry.
356 mPendingEvent = mInboundQueue.dequeueAtHead();
357 traceInboundQueueLengthLocked();
358 }
359
360 // Poke user activity for this event.
361 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
362 pokeUserActivityLocked(mPendingEvent);
363 }
364
365 // Get ready to dispatch the event.
366 resetANRTimeoutsLocked();
367 }
368
369 // Now we have an event to dispatch.
370 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700371 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800372 bool done = false;
373 DropReason dropReason = DROP_REASON_NOT_DROPPED;
374 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
375 dropReason = DROP_REASON_POLICY;
376 } else if (!mDispatchEnabled) {
377 dropReason = DROP_REASON_DISABLED;
378 }
379
380 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700381 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800382 }
383
384 switch (mPendingEvent->type) {
385 case EventEntry::TYPE_CONFIGURATION_CHANGED: {
386 ConfigurationChangedEntry* typedEntry =
387 static_cast<ConfigurationChangedEntry*>(mPendingEvent);
388 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
389 dropReason = DROP_REASON_NOT_DROPPED; // configuration changes are never dropped
390 break;
391 }
392
393 case EventEntry::TYPE_DEVICE_RESET: {
394 DeviceResetEntry* typedEntry =
395 static_cast<DeviceResetEntry*>(mPendingEvent);
396 done = dispatchDeviceResetLocked(currentTime, typedEntry);
397 dropReason = DROP_REASON_NOT_DROPPED; // device resets are never dropped
398 break;
399 }
400
401 case EventEntry::TYPE_KEY: {
402 KeyEntry* typedEntry = static_cast<KeyEntry*>(mPendingEvent);
403 if (isAppSwitchDue) {
404 if (isAppSwitchKeyEventLocked(typedEntry)) {
405 resetPendingAppSwitchLocked(true);
406 isAppSwitchDue = false;
407 } else if (dropReason == DROP_REASON_NOT_DROPPED) {
408 dropReason = DROP_REASON_APP_SWITCH;
409 }
410 }
411 if (dropReason == DROP_REASON_NOT_DROPPED
412 && isStaleEventLocked(currentTime, typedEntry)) {
413 dropReason = DROP_REASON_STALE;
414 }
415 if (dropReason == DROP_REASON_NOT_DROPPED && mNextUnblockedEvent) {
416 dropReason = DROP_REASON_BLOCKED;
417 }
418 done = dispatchKeyLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
419 break;
420 }
421
422 case EventEntry::TYPE_MOTION: {
423 MotionEntry* typedEntry = static_cast<MotionEntry*>(mPendingEvent);
424 if (dropReason == DROP_REASON_NOT_DROPPED && isAppSwitchDue) {
425 dropReason = DROP_REASON_APP_SWITCH;
426 }
427 if (dropReason == DROP_REASON_NOT_DROPPED
428 && isStaleEventLocked(currentTime, typedEntry)) {
429 dropReason = DROP_REASON_STALE;
430 }
431 if (dropReason == DROP_REASON_NOT_DROPPED && mNextUnblockedEvent) {
432 dropReason = DROP_REASON_BLOCKED;
433 }
434 done = dispatchMotionLocked(currentTime, typedEntry,
435 &dropReason, nextWakeupTime);
436 break;
437 }
438
439 default:
440 ALOG_ASSERT(false);
441 break;
442 }
443
444 if (done) {
445 if (dropReason != DROP_REASON_NOT_DROPPED) {
446 dropInboundEventLocked(mPendingEvent, dropReason);
447 }
Michael Wright3a981722015-06-10 15:26:13 +0100448 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800449
450 releasePendingEventLocked();
451 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
452 }
453}
454
455bool InputDispatcher::enqueueInboundEventLocked(EventEntry* entry) {
456 bool needWake = mInboundQueue.isEmpty();
457 mInboundQueue.enqueueAtTail(entry);
458 traceInboundQueueLengthLocked();
459
460 switch (entry->type) {
461 case EventEntry::TYPE_KEY: {
462 // Optimize app switch latency.
463 // If the application takes too long to catch up then we drop all events preceding
464 // the app switch key.
465 KeyEntry* keyEntry = static_cast<KeyEntry*>(entry);
466 if (isAppSwitchKeyEventLocked(keyEntry)) {
467 if (keyEntry->action == AKEY_EVENT_ACTION_DOWN) {
468 mAppSwitchSawKeyDown = true;
469 } else if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
470 if (mAppSwitchSawKeyDown) {
471#if DEBUG_APP_SWITCH
472 ALOGD("App switch is pending!");
473#endif
474 mAppSwitchDueTime = keyEntry->eventTime + APP_SWITCH_TIMEOUT;
475 mAppSwitchSawKeyDown = false;
476 needWake = true;
477 }
478 }
479 }
480 break;
481 }
482
483 case EventEntry::TYPE_MOTION: {
484 // Optimize case where the current application is unresponsive and the user
485 // decides to touch a window in a different application.
486 // If the application takes too long to catch up then we drop all events preceding
487 // the touch into the other window.
488 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
489 if (motionEntry->action == AMOTION_EVENT_ACTION_DOWN
490 && (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER)
491 && mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY
Robert Carr740167f2018-10-11 19:03:41 -0700492 && mInputTargetWaitApplicationToken != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800493 int32_t displayId = motionEntry->displayId;
494 int32_t x = int32_t(motionEntry->pointerCoords[0].
495 getAxisValue(AMOTION_EVENT_AXIS_X));
496 int32_t y = int32_t(motionEntry->pointerCoords[0].
497 getAxisValue(AMOTION_EVENT_AXIS_Y));
498 sp<InputWindowHandle> touchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y);
Yi Kong9b14ac62018-07-17 13:48:38 -0700499 if (touchedWindowHandle != nullptr
Robert Carr740167f2018-10-11 19:03:41 -0700500 && touchedWindowHandle->getApplicationToken()
501 != mInputTargetWaitApplicationToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800502 // User touched a different application than the one we are waiting on.
503 // Flag the event, and start pruning the input queue.
504 mNextUnblockedEvent = motionEntry;
505 needWake = true;
506 }
507 }
508 break;
509 }
510 }
511
512 return needWake;
513}
514
515void InputDispatcher::addRecentEventLocked(EventEntry* entry) {
516 entry->refCount += 1;
517 mRecentQueue.enqueueAtTail(entry);
518 if (mRecentQueue.count() > RECENT_QUEUE_MAX_SIZE) {
519 mRecentQueue.dequeueAtHead()->release();
520 }
521}
522
523sp<InputWindowHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId,
524 int32_t x, int32_t y) {
525 // Traverse windows from front to back to find touched window.
Arthur Hungb92218b2018-08-14 12:00:21 +0800526 const Vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
527 size_t numWindows = windowHandles.size();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800528 for (size_t i = 0; i < numWindows; i++) {
Arthur Hungb92218b2018-08-14 12:00:21 +0800529 sp<InputWindowHandle> windowHandle = windowHandles.itemAt(i);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800530 const InputWindowInfo* windowInfo = windowHandle->getInfo();
531 if (windowInfo->displayId == displayId) {
532 int32_t flags = windowInfo->layoutParamsFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800533
534 if (windowInfo->visible) {
535 if (!(flags & InputWindowInfo::FLAG_NOT_TOUCHABLE)) {
536 bool isTouchModal = (flags & (InputWindowInfo::FLAG_NOT_FOCUSABLE
537 | InputWindowInfo::FLAG_NOT_TOUCH_MODAL)) == 0;
538 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
539 // Found window.
540 return windowHandle;
541 }
542 }
543 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800544 }
545 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700546 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800547}
548
549void InputDispatcher::dropInboundEventLocked(EventEntry* entry, DropReason dropReason) {
550 const char* reason;
551 switch (dropReason) {
552 case DROP_REASON_POLICY:
553#if DEBUG_INBOUND_EVENT_DETAILS
554 ALOGD("Dropped event because policy consumed it.");
555#endif
556 reason = "inbound event was dropped because the policy consumed it";
557 break;
558 case DROP_REASON_DISABLED:
Michael Wright3a981722015-06-10 15:26:13 +0100559 if (mLastDropReason != DROP_REASON_DISABLED) {
560 ALOGI("Dropped event because input dispatch is disabled.");
561 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800562 reason = "inbound event was dropped because input dispatch is disabled";
563 break;
564 case DROP_REASON_APP_SWITCH:
565 ALOGI("Dropped event because of pending overdue app switch.");
566 reason = "inbound event was dropped because of pending overdue app switch";
567 break;
568 case DROP_REASON_BLOCKED:
569 ALOGI("Dropped event because the current application is not responding and the user "
570 "has started interacting with a different application.");
571 reason = "inbound event was dropped because the current application is not responding "
572 "and the user has started interacting with a different application";
573 break;
574 case DROP_REASON_STALE:
575 ALOGI("Dropped event because it is stale.");
576 reason = "inbound event was dropped because it is stale";
577 break;
578 default:
579 ALOG_ASSERT(false);
580 return;
581 }
582
583 switch (entry->type) {
584 case EventEntry::TYPE_KEY: {
585 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
586 synthesizeCancelationEventsForAllConnectionsLocked(options);
587 break;
588 }
589 case EventEntry::TYPE_MOTION: {
590 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
591 if (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) {
592 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
593 synthesizeCancelationEventsForAllConnectionsLocked(options);
594 } else {
595 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
596 synthesizeCancelationEventsForAllConnectionsLocked(options);
597 }
598 break;
599 }
600 }
601}
602
603bool InputDispatcher::isAppSwitchKeyCode(int32_t keyCode) {
604 return keyCode == AKEYCODE_HOME
605 || keyCode == AKEYCODE_ENDCALL
606 || keyCode == AKEYCODE_APP_SWITCH;
607}
608
609bool InputDispatcher::isAppSwitchKeyEventLocked(KeyEntry* keyEntry) {
610 return ! (keyEntry->flags & AKEY_EVENT_FLAG_CANCELED)
611 && isAppSwitchKeyCode(keyEntry->keyCode)
612 && (keyEntry->policyFlags & POLICY_FLAG_TRUSTED)
613 && (keyEntry->policyFlags & POLICY_FLAG_PASS_TO_USER);
614}
615
616bool InputDispatcher::isAppSwitchPendingLocked() {
617 return mAppSwitchDueTime != LONG_LONG_MAX;
618}
619
620void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
621 mAppSwitchDueTime = LONG_LONG_MAX;
622
623#if DEBUG_APP_SWITCH
624 if (handled) {
625 ALOGD("App switch has arrived.");
626 } else {
627 ALOGD("App switch was abandoned.");
628 }
629#endif
630}
631
632bool InputDispatcher::isStaleEventLocked(nsecs_t currentTime, EventEntry* entry) {
633 return currentTime - entry->eventTime >= STALE_EVENT_TIMEOUT;
634}
635
636bool InputDispatcher::haveCommandsLocked() const {
637 return !mCommandQueue.isEmpty();
638}
639
640bool InputDispatcher::runCommandsLockedInterruptible() {
641 if (mCommandQueue.isEmpty()) {
642 return false;
643 }
644
645 do {
646 CommandEntry* commandEntry = mCommandQueue.dequeueAtHead();
647
648 Command command = commandEntry->command;
649 (this->*command)(commandEntry); // commands are implicitly 'LockedInterruptible'
650
651 commandEntry->connection.clear();
652 delete commandEntry;
653 } while (! mCommandQueue.isEmpty());
654 return true;
655}
656
657InputDispatcher::CommandEntry* InputDispatcher::postCommandLocked(Command command) {
658 CommandEntry* commandEntry = new CommandEntry(command);
659 mCommandQueue.enqueueAtTail(commandEntry);
660 return commandEntry;
661}
662
663void InputDispatcher::drainInboundQueueLocked() {
664 while (! mInboundQueue.isEmpty()) {
665 EventEntry* entry = mInboundQueue.dequeueAtHead();
666 releaseInboundEventLocked(entry);
667 }
668 traceInboundQueueLengthLocked();
669}
670
671void InputDispatcher::releasePendingEventLocked() {
672 if (mPendingEvent) {
673 resetANRTimeoutsLocked();
674 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -0700675 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800676 }
677}
678
679void InputDispatcher::releaseInboundEventLocked(EventEntry* entry) {
680 InjectionState* injectionState = entry->injectionState;
681 if (injectionState && injectionState->injectionResult == INPUT_EVENT_INJECTION_PENDING) {
682#if DEBUG_DISPATCH_CYCLE
683 ALOGD("Injected inbound event was dropped.");
684#endif
685 setInjectionResultLocked(entry, INPUT_EVENT_INJECTION_FAILED);
686 }
687 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700688 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800689 }
690 addRecentEventLocked(entry);
691 entry->release();
692}
693
694void InputDispatcher::resetKeyRepeatLocked() {
695 if (mKeyRepeatState.lastKeyEntry) {
696 mKeyRepeatState.lastKeyEntry->release();
Yi Kong9b14ac62018-07-17 13:48:38 -0700697 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800698 }
699}
700
701InputDispatcher::KeyEntry* InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
702 KeyEntry* entry = mKeyRepeatState.lastKeyEntry;
703
704 // Reuse the repeated key entry if it is otherwise unreferenced.
Michael Wright2e732952014-09-24 13:26:59 -0700705 uint32_t policyFlags = entry->policyFlags &
706 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800707 if (entry->refCount == 1) {
708 entry->recycle();
709 entry->eventTime = currentTime;
710 entry->policyFlags = policyFlags;
711 entry->repeatCount += 1;
712 } else {
Prabir Pradhan42611e02018-11-27 14:04:02 -0800713 KeyEntry* newEntry = new KeyEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, currentTime,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100714 entry->deviceId, entry->source, entry->displayId, policyFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800715 entry->action, entry->flags, entry->keyCode, entry->scanCode,
716 entry->metaState, entry->repeatCount + 1, entry->downTime);
717
718 mKeyRepeatState.lastKeyEntry = newEntry;
719 entry->release();
720
721 entry = newEntry;
722 }
723 entry->syntheticRepeat = true;
724
725 // Increment reference count since we keep a reference to the event in
726 // mKeyRepeatState.lastKeyEntry in addition to the one we return.
727 entry->refCount += 1;
728
729 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
730 return entry;
731}
732
733bool InputDispatcher::dispatchConfigurationChangedLocked(
734 nsecs_t currentTime, ConfigurationChangedEntry* entry) {
735#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700736 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800737#endif
738
739 // Reset key repeating in case a keyboard device was added or removed or something.
740 resetKeyRepeatLocked();
741
742 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
743 CommandEntry* commandEntry = postCommandLocked(
744 & InputDispatcher::doNotifyConfigurationChangedInterruptible);
745 commandEntry->eventTime = entry->eventTime;
746 return true;
747}
748
749bool InputDispatcher::dispatchDeviceResetLocked(
750 nsecs_t currentTime, DeviceResetEntry* entry) {
751#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700752 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry->eventTime,
753 entry->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800754#endif
755
756 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
757 "device was reset");
758 options.deviceId = entry->deviceId;
759 synthesizeCancelationEventsForAllConnectionsLocked(options);
760 return true;
761}
762
763bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, KeyEntry* entry,
764 DropReason* dropReason, nsecs_t* nextWakeupTime) {
765 // Preprocessing.
766 if (! entry->dispatchInProgress) {
767 if (entry->repeatCount == 0
768 && entry->action == AKEY_EVENT_ACTION_DOWN
769 && (entry->policyFlags & POLICY_FLAG_TRUSTED)
770 && (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
771 if (mKeyRepeatState.lastKeyEntry
772 && mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode) {
773 // We have seen two identical key downs in a row which indicates that the device
774 // driver is automatically generating key repeats itself. We take note of the
775 // repeat here, but we disable our own next key repeat timer since it is clear that
776 // we will not need to synthesize key repeats ourselves.
777 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
778 resetKeyRepeatLocked();
779 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
780 } else {
781 // Not a repeat. Save key down state in case we do see a repeat later.
782 resetKeyRepeatLocked();
783 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
784 }
785 mKeyRepeatState.lastKeyEntry = entry;
786 entry->refCount += 1;
787 } else if (! entry->syntheticRepeat) {
788 resetKeyRepeatLocked();
789 }
790
791 if (entry->repeatCount == 1) {
792 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
793 } else {
794 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
795 }
796
797 entry->dispatchInProgress = true;
798
799 logOutboundKeyDetailsLocked("dispatchKey - ", entry);
800 }
801
802 // Handle case where the policy asked us to try again later last time.
803 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
804 if (currentTime < entry->interceptKeyWakeupTime) {
805 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
806 *nextWakeupTime = entry->interceptKeyWakeupTime;
807 }
808 return false; // wait until next wakeup
809 }
810 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
811 entry->interceptKeyWakeupTime = 0;
812 }
813
814 // Give the policy a chance to intercept the key.
815 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
816 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
817 CommandEntry* commandEntry = postCommandLocked(
818 & InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
Tiger Huang721e26f2018-07-24 22:26:19 +0800819 sp<InputWindowHandle> focusedWindowHandle =
820 getValueByKey(mFocusedWindowHandlesByDisplay, getTargetDisplayId(entry));
821 if (focusedWindowHandle != nullptr) {
Robert Carr740167f2018-10-11 19:03:41 -0700822 commandEntry->inputChannel =
823 getInputChannelLocked(focusedWindowHandle->getToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800824 }
825 commandEntry->keyEntry = entry;
826 entry->refCount += 1;
827 return false; // wait for the command to run
828 } else {
829 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
830 }
831 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
832 if (*dropReason == DROP_REASON_NOT_DROPPED) {
833 *dropReason = DROP_REASON_POLICY;
834 }
835 }
836
837 // Clean up if dropping the event.
838 if (*dropReason != DROP_REASON_NOT_DROPPED) {
839 setInjectionResultLocked(entry, *dropReason == DROP_REASON_POLICY
840 ? INPUT_EVENT_INJECTION_SUCCEEDED : INPUT_EVENT_INJECTION_FAILED);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800841 mReporter->reportDroppedKey(entry->sequenceNum);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800842 return true;
843 }
844
845 // Identify targets.
846 Vector<InputTarget> inputTargets;
847 int32_t injectionResult = findFocusedWindowTargetsLocked(currentTime,
848 entry, inputTargets, nextWakeupTime);
849 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
850 return false;
851 }
852
853 setInjectionResultLocked(entry, injectionResult);
854 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
855 return true;
856 }
857
Arthur Hung2fbf37f2018-09-13 18:16:41 +0800858 // Add monitor channels from event's or focused display.
859 addMonitoringTargetsLocked(inputTargets, getTargetDisplayId(entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800860
861 // Dispatch the key.
862 dispatchEventLocked(currentTime, entry, inputTargets);
863 return true;
864}
865
866void InputDispatcher::logOutboundKeyDetailsLocked(const char* prefix, const KeyEntry* entry) {
867#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100868 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
869 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
Arthur Hung82a4cad2018-11-15 12:10:30 +0800870 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800871 prefix,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100872 entry->eventTime, entry->deviceId, entry->source, entry->displayId, entry->policyFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800873 entry->action, entry->flags, entry->keyCode, entry->scanCode, entry->metaState,
Arthur Hung82a4cad2018-11-15 12:10:30 +0800874 entry->repeatCount, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800875#endif
876}
877
878bool InputDispatcher::dispatchMotionLocked(
879 nsecs_t currentTime, MotionEntry* entry, DropReason* dropReason, nsecs_t* nextWakeupTime) {
880 // Preprocessing.
881 if (! entry->dispatchInProgress) {
882 entry->dispatchInProgress = true;
883
884 logOutboundMotionDetailsLocked("dispatchMotion - ", entry);
885 }
886
887 // Clean up if dropping the event.
888 if (*dropReason != DROP_REASON_NOT_DROPPED) {
889 setInjectionResultLocked(entry, *dropReason == DROP_REASON_POLICY
890 ? INPUT_EVENT_INJECTION_SUCCEEDED : INPUT_EVENT_INJECTION_FAILED);
891 return true;
892 }
893
894 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
895
896 // Identify targets.
897 Vector<InputTarget> inputTargets;
898
899 bool conflictingPointerActions = false;
900 int32_t injectionResult;
901 if (isPointerEvent) {
902 // Pointer event. (eg. touchscreen)
903 injectionResult = findTouchedWindowTargetsLocked(currentTime,
904 entry, inputTargets, nextWakeupTime, &conflictingPointerActions);
905 } else {
906 // Non touch event. (eg. trackball)
907 injectionResult = findFocusedWindowTargetsLocked(currentTime,
908 entry, inputTargets, nextWakeupTime);
909 }
910 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
911 return false;
912 }
913
914 setInjectionResultLocked(entry, injectionResult);
915 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
Michael Wrightfa13dcf2015-06-12 13:25:11 +0100916 if (injectionResult != INPUT_EVENT_INJECTION_PERMISSION_DENIED) {
917 CancelationOptions::Mode mode(isPointerEvent ?
918 CancelationOptions::CANCEL_POINTER_EVENTS :
919 CancelationOptions::CANCEL_NON_POINTER_EVENTS);
920 CancelationOptions options(mode, "input event injection failed");
921 synthesizeCancelationEventsForMonitorsLocked(options);
922 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800923 return true;
924 }
925
Arthur Hung2fbf37f2018-09-13 18:16:41 +0800926 // Add monitor channels from event's or focused display.
927 addMonitoringTargetsLocked(inputTargets, getTargetDisplayId(entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800928
929 // Dispatch the motion.
930 if (conflictingPointerActions) {
931 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
932 "conflicting pointer actions");
933 synthesizeCancelationEventsForAllConnectionsLocked(options);
934 }
935 dispatchEventLocked(currentTime, entry, inputTargets);
936 return true;
937}
938
939
940void InputDispatcher::logOutboundMotionDetailsLocked(const char* prefix, const MotionEntry* entry) {
941#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800942 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
943 ", policyFlags=0x%x, "
Michael Wright7b159c92015-05-14 14:48:03 +0100944 "action=0x%x, actionButton=0x%x, flags=0x%x, "
945 "metaState=0x%x, buttonState=0x%x,"
Arthur Hung82a4cad2018-11-15 12:10:30 +0800946 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800947 prefix,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800948 entry->eventTime, entry->deviceId, entry->source, entry->displayId, entry->policyFlags,
Michael Wrightfa13dcf2015-06-12 13:25:11 +0100949 entry->action, entry->actionButton, entry->flags,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800950 entry->metaState, entry->buttonState,
951 entry->edgeFlags, entry->xPrecision, entry->yPrecision,
Arthur Hung82a4cad2018-11-15 12:10:30 +0800952 entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800953
954 for (uint32_t i = 0; i < entry->pointerCount; i++) {
955 ALOGD(" Pointer %d: id=%d, toolType=%d, "
956 "x=%f, y=%f, pressure=%f, size=%f, "
957 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -0800958 "orientation=%f",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800959 i, entry->pointerProperties[i].id,
960 entry->pointerProperties[i].toolType,
961 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
962 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
963 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
964 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
965 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
966 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
967 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
968 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -0800969 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800970 }
971#endif
972}
973
974void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
975 EventEntry* eventEntry, const Vector<InputTarget>& inputTargets) {
976#if DEBUG_DISPATCH_CYCLE
977 ALOGD("dispatchEventToCurrentInputTargets");
978#endif
979
980 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
981
982 pokeUserActivityLocked(eventEntry);
983
984 for (size_t i = 0; i < inputTargets.size(); i++) {
985 const InputTarget& inputTarget = inputTargets.itemAt(i);
986
987 ssize_t connectionIndex = getConnectionIndexLocked(inputTarget.inputChannel);
988 if (connectionIndex >= 0) {
989 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
990 prepareDispatchCycleLocked(currentTime, connection, eventEntry, &inputTarget);
991 } else {
992#if DEBUG_FOCUS
993 ALOGD("Dropping event delivery to target with channel '%s' because it "
994 "is no longer registered with the input dispatcher.",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800995 inputTarget.inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800996#endif
997 }
998 }
999}
1000
1001int32_t InputDispatcher::handleTargetsNotReadyLocked(nsecs_t currentTime,
1002 const EventEntry* entry,
1003 const sp<InputApplicationHandle>& applicationHandle,
1004 const sp<InputWindowHandle>& windowHandle,
1005 nsecs_t* nextWakeupTime, const char* reason) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001006 if (applicationHandle == nullptr && windowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001007 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY) {
1008#if DEBUG_FOCUS
1009 ALOGD("Waiting for system to become ready for input. Reason: %s", reason);
1010#endif
1011 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY;
1012 mInputTargetWaitStartTime = currentTime;
1013 mInputTargetWaitTimeoutTime = LONG_LONG_MAX;
1014 mInputTargetWaitTimeoutExpired = false;
Robert Carr740167f2018-10-11 19:03:41 -07001015 mInputTargetWaitApplicationToken.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001016 }
1017 } else {
1018 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
1019#if DEBUG_FOCUS
1020 ALOGD("Waiting for application to become ready for input: %s. Reason: %s",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001021 getApplicationWindowLabelLocked(applicationHandle, windowHandle).c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08001022 reason);
1023#endif
1024 nsecs_t timeout;
Yi Kong9b14ac62018-07-17 13:48:38 -07001025 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001026 timeout = windowHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Yi Kong9b14ac62018-07-17 13:48:38 -07001027 } else if (applicationHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001028 timeout = applicationHandle->getDispatchingTimeout(
1029 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
1030 } else {
1031 timeout = DEFAULT_INPUT_DISPATCHING_TIMEOUT;
1032 }
1033
1034 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY;
1035 mInputTargetWaitStartTime = currentTime;
1036 mInputTargetWaitTimeoutTime = currentTime + timeout;
1037 mInputTargetWaitTimeoutExpired = false;
Robert Carr740167f2018-10-11 19:03:41 -07001038 mInputTargetWaitApplicationToken.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001039
Yi Kong9b14ac62018-07-17 13:48:38 -07001040 if (windowHandle != nullptr) {
Robert Carr740167f2018-10-11 19:03:41 -07001041 mInputTargetWaitApplicationToken = windowHandle->getApplicationToken();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001042 }
Robert Carr740167f2018-10-11 19:03:41 -07001043 if (mInputTargetWaitApplicationToken == nullptr && applicationHandle != nullptr) {
1044 mInputTargetWaitApplicationToken = applicationHandle->getApplicationToken();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001045 }
1046 }
1047 }
1048
1049 if (mInputTargetWaitTimeoutExpired) {
1050 return INPUT_EVENT_INJECTION_TIMED_OUT;
1051 }
1052
1053 if (currentTime >= mInputTargetWaitTimeoutTime) {
1054 onANRLocked(currentTime, applicationHandle, windowHandle,
1055 entry->eventTime, mInputTargetWaitStartTime, reason);
1056
1057 // Force poll loop to wake up immediately on next iteration once we get the
1058 // ANR response back from the policy.
1059 *nextWakeupTime = LONG_LONG_MIN;
1060 return INPUT_EVENT_INJECTION_PENDING;
1061 } else {
1062 // Force poll loop to wake up when timeout is due.
1063 if (mInputTargetWaitTimeoutTime < *nextWakeupTime) {
1064 *nextWakeupTime = mInputTargetWaitTimeoutTime;
1065 }
1066 return INPUT_EVENT_INJECTION_PENDING;
1067 }
1068}
1069
Robert Carr803535b2018-08-02 16:38:15 -07001070void InputDispatcher::removeWindowByTokenLocked(const sp<IBinder>& token) {
1071 for (size_t d = 0; d < mTouchStatesByDisplay.size(); d++) {
1072 TouchState& state = mTouchStatesByDisplay.editValueAt(d);
1073 state.removeWindowByToken(token);
1074 }
1075}
1076
Michael Wrightd02c5b62014-02-10 15:10:22 -08001077void InputDispatcher::resumeAfterTargetsNotReadyTimeoutLocked(nsecs_t newTimeout,
1078 const sp<InputChannel>& inputChannel) {
1079 if (newTimeout > 0) {
1080 // Extend the timeout.
1081 mInputTargetWaitTimeoutTime = now() + newTimeout;
1082 } else {
1083 // Give up.
1084 mInputTargetWaitTimeoutExpired = true;
1085
1086 // Input state will not be realistic. Mark it out of sync.
1087 if (inputChannel.get()) {
1088 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
1089 if (connectionIndex >= 0) {
1090 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
Robert Carr803535b2018-08-02 16:38:15 -07001091 sp<IBinder> token = connection->inputChannel->getToken();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001092
Robert Carr803535b2018-08-02 16:38:15 -07001093 if (token != nullptr) {
1094 removeWindowByTokenLocked(token);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001095 }
1096
1097 if (connection->status == Connection::STATUS_NORMAL) {
1098 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1099 "application not responding");
1100 synthesizeCancelationEventsForConnectionLocked(connection, options);
1101 }
1102 }
1103 }
1104 }
1105}
1106
1107nsecs_t InputDispatcher::getTimeSpentWaitingForApplicationLocked(
1108 nsecs_t currentTime) {
1109 if (mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
1110 return currentTime - mInputTargetWaitStartTime;
1111 }
1112 return 0;
1113}
1114
1115void InputDispatcher::resetANRTimeoutsLocked() {
1116#if DEBUG_FOCUS
1117 ALOGD("Resetting ANR timeouts.");
1118#endif
1119
1120 // Reset input target wait timeout.
1121 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_NONE;
Robert Carr740167f2018-10-11 19:03:41 -07001122 mInputTargetWaitApplicationToken.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001123}
1124
Tiger Huang721e26f2018-07-24 22:26:19 +08001125/**
1126 * Get the display id that the given event should go to. If this event specifies a valid display id,
1127 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1128 * Focused display is the display that the user most recently interacted with.
1129 */
1130int32_t InputDispatcher::getTargetDisplayId(const EventEntry* entry) {
1131 int32_t displayId;
1132 switch (entry->type) {
1133 case EventEntry::TYPE_KEY: {
1134 const KeyEntry* typedEntry = static_cast<const KeyEntry*>(entry);
1135 displayId = typedEntry->displayId;
1136 break;
1137 }
1138 case EventEntry::TYPE_MOTION: {
1139 const MotionEntry* typedEntry = static_cast<const MotionEntry*>(entry);
1140 displayId = typedEntry->displayId;
1141 break;
1142 }
1143 default: {
1144 ALOGE("Unsupported event type '%" PRId32 "' for target display.", entry->type);
1145 return ADISPLAY_ID_NONE;
1146 }
1147 }
1148 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1149}
1150
Michael Wrightd02c5b62014-02-10 15:10:22 -08001151int32_t InputDispatcher::findFocusedWindowTargetsLocked(nsecs_t currentTime,
1152 const EventEntry* entry, Vector<InputTarget>& inputTargets, nsecs_t* nextWakeupTime) {
1153 int32_t injectionResult;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001154 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001155
Tiger Huang721e26f2018-07-24 22:26:19 +08001156 int32_t displayId = getTargetDisplayId(entry);
1157 sp<InputWindowHandle> focusedWindowHandle =
1158 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
1159 sp<InputApplicationHandle> focusedApplicationHandle =
1160 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1161
Michael Wrightd02c5b62014-02-10 15:10:22 -08001162 // If there is no currently focused window and no focused application
1163 // then drop the event.
Tiger Huang721e26f2018-07-24 22:26:19 +08001164 if (focusedWindowHandle == nullptr) {
1165 if (focusedApplicationHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001166 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Tiger Huang721e26f2018-07-24 22:26:19 +08001167 focusedApplicationHandle, nullptr, nextWakeupTime,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001168 "Waiting because no window has focus but there is a "
1169 "focused application that may eventually add a window "
1170 "when it finishes starting up.");
1171 goto Unresponsive;
1172 }
1173
Arthur Hung3b413f22018-10-26 18:05:34 +08001174 ALOGI("Dropping event because there is no focused window or focused application in display "
1175 "%" PRId32 ".", displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001176 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1177 goto Failed;
1178 }
1179
1180 // Check permissions.
Tiger Huang721e26f2018-07-24 22:26:19 +08001181 if (!checkInjectionPermission(focusedWindowHandle, entry->injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001182 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1183 goto Failed;
1184 }
1185
Jeff Brownffb49772014-10-10 19:01:34 -07001186 // Check whether the window is ready for more input.
1187 reason = checkWindowReadyForMoreInputLocked(currentTime,
Tiger Huang721e26f2018-07-24 22:26:19 +08001188 focusedWindowHandle, entry, "focused");
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001189 if (!reason.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001190 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Tiger Huang721e26f2018-07-24 22:26:19 +08001191 focusedApplicationHandle, focusedWindowHandle, nextWakeupTime, reason.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001192 goto Unresponsive;
1193 }
1194
1195 // Success! Output targets.
1196 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
Tiger Huang721e26f2018-07-24 22:26:19 +08001197 addWindowTargetLocked(focusedWindowHandle,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001198 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS, BitSet32(0),
1199 inputTargets);
1200
1201 // Done.
1202Failed:
1203Unresponsive:
1204 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
1205 updateDispatchStatisticsLocked(currentTime, entry,
1206 injectionResult, timeSpentWaitingForApplication);
1207#if DEBUG_FOCUS
1208 ALOGD("findFocusedWindow finished: injectionResult=%d, "
1209 "timeSpentWaitingForApplication=%0.1fms",
1210 injectionResult, timeSpentWaitingForApplication / 1000000.0);
1211#endif
1212 return injectionResult;
1213}
1214
1215int32_t InputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime,
1216 const MotionEntry* entry, Vector<InputTarget>& inputTargets, nsecs_t* nextWakeupTime,
1217 bool* outConflictingPointerActions) {
1218 enum InjectionPermission {
1219 INJECTION_PERMISSION_UNKNOWN,
1220 INJECTION_PERMISSION_GRANTED,
1221 INJECTION_PERMISSION_DENIED
1222 };
1223
Michael Wrightd02c5b62014-02-10 15:10:22 -08001224 // For security reasons, we defer updating the touch state until we are sure that
1225 // event injection will be allowed.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001226 int32_t displayId = entry->displayId;
1227 int32_t action = entry->action;
1228 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
1229
1230 // Update the touch state as needed based on the properties of the touch event.
1231 int32_t injectionResult = INPUT_EVENT_INJECTION_PENDING;
1232 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
1233 sp<InputWindowHandle> newHoverWindowHandle;
1234
Jeff Brownf086ddb2014-02-11 14:28:48 -08001235 // Copy current touch state into mTempTouchState.
1236 // This state is always reset at the end of this function, so if we don't find state
1237 // for the specified display then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07001238 const TouchState* oldState = nullptr;
Jeff Brownf086ddb2014-02-11 14:28:48 -08001239 ssize_t oldStateIndex = mTouchStatesByDisplay.indexOfKey(displayId);
1240 if (oldStateIndex >= 0) {
1241 oldState = &mTouchStatesByDisplay.valueAt(oldStateIndex);
1242 mTempTouchState.copyFrom(*oldState);
1243 }
1244
1245 bool isSplit = mTempTouchState.split;
1246 bool switchedDevice = mTempTouchState.deviceId >= 0 && mTempTouchState.displayId >= 0
1247 && (mTempTouchState.deviceId != entry->deviceId
1248 || mTempTouchState.source != entry->source
1249 || mTempTouchState.displayId != displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001250 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE
1251 || maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER
1252 || maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1253 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN
1254 || maskedAction == AMOTION_EVENT_ACTION_SCROLL
1255 || isHoverAction);
1256 bool wrongDevice = false;
1257 if (newGesture) {
1258 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001259 if (switchedDevice && mTempTouchState.down && !down && !isHoverAction) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001260#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08001261 ALOGD("Dropping event because a pointer for a different device is already down "
1262 "in display %" PRId32, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001263#endif
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001264 // TODO: test multiple simultaneous input streams.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001265 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1266 switchedDevice = false;
1267 wrongDevice = true;
1268 goto Failed;
1269 }
1270 mTempTouchState.reset();
1271 mTempTouchState.down = down;
1272 mTempTouchState.deviceId = entry->deviceId;
1273 mTempTouchState.source = entry->source;
1274 mTempTouchState.displayId = displayId;
1275 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001276 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
1277#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08001278 ALOGI("Dropping move event because a pointer for a different device is already active "
1279 "in display %" PRId32, displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001280#endif
1281 // TODO: test multiple simultaneous input streams.
1282 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1283 switchedDevice = false;
1284 wrongDevice = true;
1285 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001286 }
1287
1288 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
1289 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
1290
1291 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
1292 int32_t x = int32_t(entry->pointerCoords[pointerIndex].
1293 getAxisValue(AMOTION_EVENT_AXIS_X));
1294 int32_t y = int32_t(entry->pointerCoords[pointerIndex].
1295 getAxisValue(AMOTION_EVENT_AXIS_Y));
1296 sp<InputWindowHandle> newTouchedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001297 bool isTouchModal = false;
1298
1299 // Traverse windows from front to back to find touched window and outside targets.
Arthur Hungb92218b2018-08-14 12:00:21 +08001300 const Vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
1301 size_t numWindows = windowHandles.size();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001302 for (size_t i = 0; i < numWindows; i++) {
Arthur Hungb92218b2018-08-14 12:00:21 +08001303 sp<InputWindowHandle> windowHandle = windowHandles.itemAt(i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001304 const InputWindowInfo* windowInfo = windowHandle->getInfo();
1305 if (windowInfo->displayId != displayId) {
1306 continue; // wrong display
1307 }
1308
Michael Wrightd02c5b62014-02-10 15:10:22 -08001309 int32_t flags = windowInfo->layoutParamsFlags;
1310 if (windowInfo->visible) {
1311 if (! (flags & InputWindowInfo::FLAG_NOT_TOUCHABLE)) {
1312 isTouchModal = (flags & (InputWindowInfo::FLAG_NOT_FOCUSABLE
1313 | InputWindowInfo::FLAG_NOT_TOUCH_MODAL)) == 0;
1314 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
Jeff Browndc5992e2014-04-11 01:27:26 -07001315 newTouchedWindowHandle = windowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001316 break; // found touched window, exit window loop
1317 }
1318 }
1319
1320 if (maskedAction == AMOTION_EVENT_ACTION_DOWN
1321 && (flags & InputWindowInfo::FLAG_WATCH_OUTSIDE_TOUCH)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001322 mTempTouchState.addOrUpdateWindow(
Michael Wright3b106102017-01-16 21:05:07 +00001323 windowHandle, InputTarget::FLAG_DISPATCH_AS_OUTSIDE, BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001324 }
1325 }
1326 }
1327
Michael Wrightd02c5b62014-02-10 15:10:22 -08001328 // Figure out whether splitting will be allowed for this window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001329 if (newTouchedWindowHandle != nullptr
Michael Wrightd02c5b62014-02-10 15:10:22 -08001330 && newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
1331 // New window supports splitting.
1332 isSplit = true;
1333 } else if (isSplit) {
1334 // New window does not support splitting but we have already split events.
1335 // Ignore the new window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001336 newTouchedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001337 }
1338
1339 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001340 if (newTouchedWindowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001341 // Try to assign the pointer to the first foreground window we find, if there is one.
1342 newTouchedWindowHandle = mTempTouchState.getFirstForegroundWindowHandle();
Yi Kong9b14ac62018-07-17 13:48:38 -07001343 if (newTouchedWindowHandle == nullptr) {
Arthur Hung3b413f22018-10-26 18:05:34 +08001344 ALOGI("Dropping event because there is no touchable window at (%d, %d) in display "
1345 "%" PRId32 ".", x, y, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001346 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1347 goto Failed;
1348 }
1349 }
1350
1351 // Set target flags.
1352 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
1353 if (isSplit) {
1354 targetFlags |= InputTarget::FLAG_SPLIT;
1355 }
1356 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1357 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001358 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
1359 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001360 }
1361
1362 // Update hover state.
1363 if (isHoverAction) {
1364 newHoverWindowHandle = newTouchedWindowHandle;
1365 } else if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
1366 newHoverWindowHandle = mLastHoverWindowHandle;
1367 }
1368
1369 // Update the temporary touch state.
1370 BitSet32 pointerIds;
1371 if (isSplit) {
1372 uint32_t pointerId = entry->pointerProperties[pointerIndex].id;
1373 pointerIds.markBit(pointerId);
1374 }
1375 mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
1376 } else {
1377 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
1378
1379 // If the pointer is not currently down, then ignore the event.
1380 if (! mTempTouchState.down) {
1381#if DEBUG_FOCUS
1382 ALOGD("Dropping event because the pointer is not down or we previously "
Arthur Hung3b413f22018-10-26 18:05:34 +08001383 "dropped the pointer down event in display %" PRId32, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001384#endif
1385 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1386 goto Failed;
1387 }
1388
1389 // Check whether touches should slip outside of the current foreground window.
1390 if (maskedAction == AMOTION_EVENT_ACTION_MOVE
1391 && entry->pointerCount == 1
1392 && mTempTouchState.isSlippery()) {
1393 int32_t x = int32_t(entry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
1394 int32_t y = int32_t(entry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
1395
1396 sp<InputWindowHandle> oldTouchedWindowHandle =
1397 mTempTouchState.getFirstForegroundWindowHandle();
1398 sp<InputWindowHandle> newTouchedWindowHandle =
1399 findTouchedWindowAtLocked(displayId, x, y);
1400 if (oldTouchedWindowHandle != newTouchedWindowHandle
Yi Kong9b14ac62018-07-17 13:48:38 -07001401 && newTouchedWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001402#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08001403 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001404 oldTouchedWindowHandle->getName().c_str(),
Arthur Hung3b413f22018-10-26 18:05:34 +08001405 newTouchedWindowHandle->getName().c_str(),
1406 displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001407#endif
1408 // Make a slippery exit from the old window.
1409 mTempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
1410 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT, BitSet32(0));
1411
1412 // Make a slippery entrance into the new window.
1413 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
1414 isSplit = true;
1415 }
1416
1417 int32_t targetFlags = InputTarget::FLAG_FOREGROUND
1418 | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
1419 if (isSplit) {
1420 targetFlags |= InputTarget::FLAG_SPLIT;
1421 }
1422 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1423 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1424 }
1425
1426 BitSet32 pointerIds;
1427 if (isSplit) {
1428 pointerIds.markBit(entry->pointerProperties[0].id);
1429 }
1430 mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
1431 }
1432 }
1433 }
1434
1435 if (newHoverWindowHandle != mLastHoverWindowHandle) {
1436 // Let the previous window know that the hover sequence is over.
Yi Kong9b14ac62018-07-17 13:48:38 -07001437 if (mLastHoverWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001438#if DEBUG_HOVER
1439 ALOGD("Sending hover exit event to window %s.",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001440 mLastHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001441#endif
1442 mTempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
1443 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
1444 }
1445
1446 // Let the new window know that the hover sequence is starting.
Yi Kong9b14ac62018-07-17 13:48:38 -07001447 if (newHoverWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001448#if DEBUG_HOVER
1449 ALOGD("Sending hover enter event to window %s.",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001450 newHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001451#endif
1452 mTempTouchState.addOrUpdateWindow(newHoverWindowHandle,
1453 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER, BitSet32(0));
1454 }
1455 }
1456
1457 // Check permission to inject into all touched foreground windows and ensure there
1458 // is at least one touched foreground window.
1459 {
1460 bool haveForegroundWindow = false;
1461 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1462 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1463 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1464 haveForegroundWindow = true;
1465 if (! checkInjectionPermission(touchedWindow.windowHandle,
1466 entry->injectionState)) {
1467 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1468 injectionPermission = INJECTION_PERMISSION_DENIED;
1469 goto Failed;
1470 }
1471 }
1472 }
1473 if (! haveForegroundWindow) {
1474#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08001475 ALOGD("Dropping event because there is no touched foreground window in display %" PRId32
1476 " to receive it.", displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001477#endif
1478 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1479 goto Failed;
1480 }
1481
1482 // Permission granted to injection into all touched foreground windows.
1483 injectionPermission = INJECTION_PERMISSION_GRANTED;
1484 }
1485
1486 // Check whether windows listening for outside touches are owned by the same UID. If it is
1487 // set the policy flag that we will not reveal coordinate information to this window.
1488 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1489 sp<InputWindowHandle> foregroundWindowHandle =
1490 mTempTouchState.getFirstForegroundWindowHandle();
1491 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
1492 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1493 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1494 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
1495 sp<InputWindowHandle> inputWindowHandle = touchedWindow.windowHandle;
1496 if (inputWindowHandle->getInfo()->ownerUid != foregroundWindowUid) {
1497 mTempTouchState.addOrUpdateWindow(inputWindowHandle,
1498 InputTarget::FLAG_ZERO_COORDS, BitSet32(0));
1499 }
1500 }
1501 }
1502 }
1503
1504 // Ensure all touched foreground windows are ready for new input.
1505 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1506 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1507 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
Jeff Brownffb49772014-10-10 19:01:34 -07001508 // Check whether the window is ready for more input.
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001509 std::string reason = checkWindowReadyForMoreInputLocked(currentTime,
Jeff Brownffb49772014-10-10 19:01:34 -07001510 touchedWindow.windowHandle, entry, "touched");
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001511 if (!reason.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001512 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Yi Kong9b14ac62018-07-17 13:48:38 -07001513 nullptr, touchedWindow.windowHandle, nextWakeupTime, reason.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001514 goto Unresponsive;
1515 }
1516 }
1517 }
1518
1519 // If this is the first pointer going down and the touched window has a wallpaper
1520 // then also add the touched wallpaper windows so they are locked in for the duration
1521 // of the touch gesture.
1522 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
1523 // engine only supports touch events. We would need to add a mechanism similar
1524 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
1525 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1526 sp<InputWindowHandle> foregroundWindowHandle =
1527 mTempTouchState.getFirstForegroundWindowHandle();
1528 if (foregroundWindowHandle->getInfo()->hasWallpaper) {
Arthur Hungb92218b2018-08-14 12:00:21 +08001529 const Vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
1530 size_t numWindows = windowHandles.size();
1531 for (size_t i = 0; i < numWindows; i++) {
1532 sp<InputWindowHandle> windowHandle = windowHandles.itemAt(i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001533 const InputWindowInfo* info = windowHandle->getInfo();
1534 if (info->displayId == displayId
1535 && windowHandle->getInfo()->layoutParamsType
1536 == InputWindowInfo::TYPE_WALLPAPER) {
1537 mTempTouchState.addOrUpdateWindow(windowHandle,
1538 InputTarget::FLAG_WINDOW_IS_OBSCURED
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001539 | InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED
Michael Wrightd02c5b62014-02-10 15:10:22 -08001540 | InputTarget::FLAG_DISPATCH_AS_IS,
1541 BitSet32(0));
1542 }
1543 }
1544 }
1545 }
1546
1547 // Success! Output targets.
1548 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
1549
1550 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1551 const TouchedWindow& touchedWindow = mTempTouchState.windows.itemAt(i);
1552 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
1553 touchedWindow.pointerIds, inputTargets);
1554 }
1555
1556 // Drop the outside or hover touch windows since we will not care about them
1557 // in the next iteration.
1558 mTempTouchState.filterNonAsIsTouchWindows();
1559
1560Failed:
1561 // Check injection permission once and for all.
1562 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001563 if (checkInjectionPermission(nullptr, entry->injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001564 injectionPermission = INJECTION_PERMISSION_GRANTED;
1565 } else {
1566 injectionPermission = INJECTION_PERMISSION_DENIED;
1567 }
1568 }
1569
1570 // Update final pieces of touch state if the injector had permission.
1571 if (injectionPermission == INJECTION_PERMISSION_GRANTED) {
1572 if (!wrongDevice) {
1573 if (switchedDevice) {
1574#if DEBUG_FOCUS
1575 ALOGD("Conflicting pointer actions: Switched to a different device.");
1576#endif
1577 *outConflictingPointerActions = true;
1578 }
1579
1580 if (isHoverAction) {
1581 // Started hovering, therefore no longer down.
Jeff Brownf086ddb2014-02-11 14:28:48 -08001582 if (oldState && oldState->down) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001583#if DEBUG_FOCUS
1584 ALOGD("Conflicting pointer actions: Hover received while pointer was down.");
1585#endif
1586 *outConflictingPointerActions = true;
1587 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08001588 mTempTouchState.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001589 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER
1590 || maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Jeff Brownf086ddb2014-02-11 14:28:48 -08001591 mTempTouchState.deviceId = entry->deviceId;
1592 mTempTouchState.source = entry->source;
1593 mTempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001594 }
1595 } else if (maskedAction == AMOTION_EVENT_ACTION_UP
1596 || maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
1597 // All pointers up or canceled.
Jeff Brownf086ddb2014-02-11 14:28:48 -08001598 mTempTouchState.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001599 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1600 // First pointer went down.
Jeff Brownf086ddb2014-02-11 14:28:48 -08001601 if (oldState && oldState->down) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001602#if DEBUG_FOCUS
1603 ALOGD("Conflicting pointer actions: Down received while already down.");
1604#endif
1605 *outConflictingPointerActions = true;
1606 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001607 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
1608 // One pointer went up.
1609 if (isSplit) {
1610 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
1611 uint32_t pointerId = entry->pointerProperties[pointerIndex].id;
1612
1613 for (size_t i = 0; i < mTempTouchState.windows.size(); ) {
1614 TouchedWindow& touchedWindow = mTempTouchState.windows.editItemAt(i);
1615 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
1616 touchedWindow.pointerIds.clearBit(pointerId);
1617 if (touchedWindow.pointerIds.isEmpty()) {
1618 mTempTouchState.windows.removeAt(i);
1619 continue;
1620 }
1621 }
1622 i += 1;
1623 }
1624 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08001625 }
1626
1627 // Save changes unless the action was scroll in which case the temporary touch
1628 // state was only valid for this one action.
1629 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
1630 if (mTempTouchState.displayId >= 0) {
1631 if (oldStateIndex >= 0) {
1632 mTouchStatesByDisplay.editValueAt(oldStateIndex).copyFrom(mTempTouchState);
1633 } else {
1634 mTouchStatesByDisplay.add(displayId, mTempTouchState);
1635 }
1636 } else if (oldStateIndex >= 0) {
1637 mTouchStatesByDisplay.removeItemsAt(oldStateIndex);
1638 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001639 }
1640
1641 // Update hover state.
1642 mLastHoverWindowHandle = newHoverWindowHandle;
1643 }
1644 } else {
1645#if DEBUG_FOCUS
1646 ALOGD("Not updating touch focus because injection was denied.");
1647#endif
1648 }
1649
1650Unresponsive:
1651 // Reset temporary touch state to ensure we release unnecessary references to input channels.
1652 mTempTouchState.reset();
1653
1654 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
1655 updateDispatchStatisticsLocked(currentTime, entry,
1656 injectionResult, timeSpentWaitingForApplication);
1657#if DEBUG_FOCUS
1658 ALOGD("findTouchedWindow finished: injectionResult=%d, injectionPermission=%d, "
1659 "timeSpentWaitingForApplication=%0.1fms",
1660 injectionResult, injectionPermission, timeSpentWaitingForApplication / 1000000.0);
1661#endif
1662 return injectionResult;
1663}
1664
1665void InputDispatcher::addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
1666 int32_t targetFlags, BitSet32 pointerIds, Vector<InputTarget>& inputTargets) {
Arthur Hungceeb5d72018-12-05 16:14:18 +08001667 sp<InputChannel> inputChannel = getInputChannelLocked(windowHandle->getToken());
1668 if (inputChannel == nullptr) {
1669 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
1670 return;
1671 }
1672
Michael Wrightd02c5b62014-02-10 15:10:22 -08001673 inputTargets.push();
1674
1675 const InputWindowInfo* windowInfo = windowHandle->getInfo();
1676 InputTarget& target = inputTargets.editTop();
Arthur Hungceeb5d72018-12-05 16:14:18 +08001677 target.inputChannel = inputChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001678 target.flags = targetFlags;
1679 target.xOffset = - windowInfo->frameLeft;
1680 target.yOffset = - windowInfo->frameTop;
Robert Carre07e1032018-11-26 12:55:53 -08001681 target.globalScaleFactor = windowInfo->globalScaleFactor;
1682 target.windowXScale = windowInfo->windowXScale;
1683 target.windowYScale = windowInfo->windowYScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001684 target.pointerIds = pointerIds;
1685}
1686
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001687void InputDispatcher::addMonitoringTargetsLocked(Vector<InputTarget>& inputTargets,
1688 int32_t displayId) {
1689 std::unordered_map<int32_t, Vector<sp<InputChannel>>>::const_iterator it =
1690 mMonitoringChannelsByDisplay.find(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001691
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001692 if (it != mMonitoringChannelsByDisplay.end()) {
1693 const Vector<sp<InputChannel>>& monitoringChannels = it->second;
1694 const size_t numChannels = monitoringChannels.size();
1695 for (size_t i = 0; i < numChannels; i++) {
1696 inputTargets.push();
1697
1698 InputTarget& target = inputTargets.editTop();
1699 target.inputChannel = monitoringChannels[i];
1700 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1701 target.xOffset = 0;
1702 target.yOffset = 0;
1703 target.pointerIds.clear();
Robert Carre07e1032018-11-26 12:55:53 -08001704 target.globalScaleFactor = 1.0f;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001705 }
1706 } else {
1707 // If there is no monitor channel registered or all monitor channel unregistered,
1708 // the display can't detect the extra system gesture by a copy of input events.
Arthur Hung3b413f22018-10-26 18:05:34 +08001709 ALOGW("There is no monitor channel found in display %" PRId32, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001710 }
1711}
1712
1713bool InputDispatcher::checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
1714 const InjectionState* injectionState) {
1715 if (injectionState
Yi Kong9b14ac62018-07-17 13:48:38 -07001716 && (windowHandle == nullptr
Michael Wrightd02c5b62014-02-10 15:10:22 -08001717 || windowHandle->getInfo()->ownerUid != injectionState->injectorUid)
1718 && !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001719 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001720 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
1721 "owned by uid %d",
1722 injectionState->injectorPid, injectionState->injectorUid,
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001723 windowHandle->getName().c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08001724 windowHandle->getInfo()->ownerUid);
1725 } else {
1726 ALOGW("Permission denied: injecting event from pid %d uid %d",
1727 injectionState->injectorPid, injectionState->injectorUid);
1728 }
1729 return false;
1730 }
1731 return true;
1732}
1733
1734bool InputDispatcher::isWindowObscuredAtPointLocked(
1735 const sp<InputWindowHandle>& windowHandle, int32_t x, int32_t y) const {
1736 int32_t displayId = windowHandle->getInfo()->displayId;
Arthur Hungb92218b2018-08-14 12:00:21 +08001737 const Vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
1738 size_t numWindows = windowHandles.size();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001739 for (size_t i = 0; i < numWindows; i++) {
Arthur Hungb92218b2018-08-14 12:00:21 +08001740 sp<InputWindowHandle> otherHandle = windowHandles.itemAt(i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001741 if (otherHandle == windowHandle) {
1742 break;
1743 }
1744
1745 const InputWindowInfo* otherInfo = otherHandle->getInfo();
1746 if (otherInfo->displayId == displayId
1747 && otherInfo->visible && !otherInfo->isTrustedOverlay()
1748 && otherInfo->frameContainsPoint(x, y)) {
1749 return true;
1750 }
1751 }
1752 return false;
1753}
1754
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001755
1756bool InputDispatcher::isWindowObscuredLocked(const sp<InputWindowHandle>& windowHandle) const {
1757 int32_t displayId = windowHandle->getInfo()->displayId;
Arthur Hungb92218b2018-08-14 12:00:21 +08001758 const Vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001759 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Arthur Hungb92218b2018-08-14 12:00:21 +08001760 size_t numWindows = windowHandles.size();
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001761 for (size_t i = 0; i < numWindows; i++) {
Arthur Hungb92218b2018-08-14 12:00:21 +08001762 sp<InputWindowHandle> otherHandle = windowHandles.itemAt(i);
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001763 if (otherHandle == windowHandle) {
1764 break;
1765 }
1766
1767 const InputWindowInfo* otherInfo = otherHandle->getInfo();
1768 if (otherInfo->displayId == displayId
1769 && otherInfo->visible && !otherInfo->isTrustedOverlay()
1770 && otherInfo->overlaps(windowInfo)) {
1771 return true;
1772 }
1773 }
1774 return false;
1775}
1776
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001777std::string InputDispatcher::checkWindowReadyForMoreInputLocked(nsecs_t currentTime,
Jeff Brownffb49772014-10-10 19:01:34 -07001778 const sp<InputWindowHandle>& windowHandle, const EventEntry* eventEntry,
1779 const char* targetType) {
1780 // If the window is paused then keep waiting.
1781 if (windowHandle->getInfo()->paused) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001782 return StringPrintf("Waiting because the %s window is paused.", targetType);
Jeff Brownffb49772014-10-10 19:01:34 -07001783 }
1784
1785 // If the window's connection is not registered then keep waiting.
Robert Carr5c8a0262018-10-03 16:30:44 -07001786 ssize_t connectionIndex = getConnectionIndexLocked(
1787 getInputChannelLocked(windowHandle->getToken()));
Jeff Brownffb49772014-10-10 19:01:34 -07001788 if (connectionIndex < 0) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001789 return StringPrintf("Waiting because the %s window's input channel is not "
Jeff Brownffb49772014-10-10 19:01:34 -07001790 "registered with the input dispatcher. The window may be in the process "
1791 "of being removed.", targetType);
1792 }
1793
1794 // If the connection is dead then keep waiting.
1795 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
1796 if (connection->status != Connection::STATUS_NORMAL) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001797 return StringPrintf("Waiting because the %s window's input connection is %s."
Jeff Brownffb49772014-10-10 19:01:34 -07001798 "The window may be in the process of being removed.", targetType,
1799 connection->getStatusLabel());
1800 }
1801
1802 // If the connection is backed up then keep waiting.
1803 if (connection->inputPublisherBlocked) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001804 return StringPrintf("Waiting because the %s window's input channel is full. "
Jeff Brownffb49772014-10-10 19:01:34 -07001805 "Outbound queue length: %d. Wait queue length: %d.",
1806 targetType, connection->outboundQueue.count(), connection->waitQueue.count());
1807 }
1808
1809 // Ensure that the dispatch queues aren't too far backed up for this event.
1810 if (eventEntry->type == EventEntry::TYPE_KEY) {
1811 // If the event is a key event, then we must wait for all previous events to
1812 // complete before delivering it because previous events may have the
1813 // side-effect of transferring focus to a different window and we want to
1814 // ensure that the following keys are sent to the new window.
1815 //
1816 // Suppose the user touches a button in a window then immediately presses "A".
1817 // If the button causes a pop-up window to appear then we want to ensure that
1818 // the "A" key is delivered to the new pop-up window. This is because users
1819 // often anticipate pending UI changes when typing on a keyboard.
1820 // To obtain this behavior, we must serialize key events with respect to all
1821 // prior input events.
1822 if (!connection->outboundQueue.isEmpty() || !connection->waitQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001823 return StringPrintf("Waiting to send key event because the %s window has not "
Jeff Brownffb49772014-10-10 19:01:34 -07001824 "finished processing all of the input events that were previously "
1825 "delivered to it. Outbound queue length: %d. Wait queue length: %d.",
1826 targetType, connection->outboundQueue.count(), connection->waitQueue.count());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001827 }
Jeff Brownffb49772014-10-10 19:01:34 -07001828 } else {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001829 // Touch events can always be sent to a window immediately because the user intended
1830 // to touch whatever was visible at the time. Even if focus changes or a new
1831 // window appears moments later, the touch event was meant to be delivered to
1832 // whatever window happened to be on screen at the time.
1833 //
1834 // Generic motion events, such as trackball or joystick events are a little trickier.
1835 // Like key events, generic motion events are delivered to the focused window.
1836 // Unlike key events, generic motion events don't tend to transfer focus to other
1837 // windows and it is not important for them to be serialized. So we prefer to deliver
1838 // generic motion events as soon as possible to improve efficiency and reduce lag
1839 // through batching.
1840 //
1841 // The one case where we pause input event delivery is when the wait queue is piling
1842 // up with lots of events because the application is not responding.
1843 // This condition ensures that ANRs are detected reliably.
1844 if (!connection->waitQueue.isEmpty()
1845 && currentTime >= connection->waitQueue.head->deliveryTime
1846 + STREAM_AHEAD_EVENT_TIMEOUT) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001847 return StringPrintf("Waiting to send non-key event because the %s window has not "
Jeff Brownffb49772014-10-10 19:01:34 -07001848 "finished processing certain input events that were delivered to it over "
1849 "%0.1fms ago. Wait queue length: %d. Wait queue head age: %0.1fms.",
1850 targetType, STREAM_AHEAD_EVENT_TIMEOUT * 0.000001f,
1851 connection->waitQueue.count(),
1852 (currentTime - connection->waitQueue.head->deliveryTime) * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001853 }
1854 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001855 return "";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001856}
1857
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001858std::string InputDispatcher::getApplicationWindowLabelLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08001859 const sp<InputApplicationHandle>& applicationHandle,
1860 const sp<InputWindowHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001861 if (applicationHandle != nullptr) {
1862 if (windowHandle != nullptr) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001863 std::string label(applicationHandle->getName());
1864 label += " - ";
1865 label += windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001866 return label;
1867 } else {
1868 return applicationHandle->getName();
1869 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001870 } else if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001871 return windowHandle->getName();
1872 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001873 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001874 }
1875}
1876
1877void InputDispatcher::pokeUserActivityLocked(const EventEntry* eventEntry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001878 int32_t displayId = getTargetDisplayId(eventEntry);
1879 sp<InputWindowHandle> focusedWindowHandle =
1880 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
1881 if (focusedWindowHandle != nullptr) {
1882 const InputWindowInfo* info = focusedWindowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001883 if (info->inputFeatures & InputWindowInfo::INPUT_FEATURE_DISABLE_USER_ACTIVITY) {
1884#if DEBUG_DISPATCH_CYCLE
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001885 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001886#endif
1887 return;
1888 }
1889 }
1890
1891 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
1892 switch (eventEntry->type) {
1893 case EventEntry::TYPE_MOTION: {
1894 const MotionEntry* motionEntry = static_cast<const MotionEntry*>(eventEntry);
1895 if (motionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
1896 return;
1897 }
1898
1899 if (MotionEvent::isTouchEvent(motionEntry->source, motionEntry->action)) {
1900 eventType = USER_ACTIVITY_EVENT_TOUCH;
1901 }
1902 break;
1903 }
1904 case EventEntry::TYPE_KEY: {
1905 const KeyEntry* keyEntry = static_cast<const KeyEntry*>(eventEntry);
1906 if (keyEntry->flags & AKEY_EVENT_FLAG_CANCELED) {
1907 return;
1908 }
1909 eventType = USER_ACTIVITY_EVENT_BUTTON;
1910 break;
1911 }
1912 }
1913
1914 CommandEntry* commandEntry = postCommandLocked(
1915 & InputDispatcher::doPokeUserActivityLockedInterruptible);
1916 commandEntry->eventTime = eventEntry->eventTime;
1917 commandEntry->userActivityEventType = eventType;
1918}
1919
1920void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
1921 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget) {
1922#if DEBUG_DISPATCH_CYCLE
1923 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
Robert Carre07e1032018-11-26 12:55:53 -08001924 "xOffset=%f, yOffset=%f, globalScaleFactor=%f, "
1925 "windowScaleFactor=(%f, %f), pointerIds=0x%x",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08001926 connection->getInputChannelName().c_str(), inputTarget->flags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001927 inputTarget->xOffset, inputTarget->yOffset,
Robert Carre07e1032018-11-26 12:55:53 -08001928 inputTarget->globalScaleFactor,
1929 inputTarget->windowXScale, inputTarget->windowYScale,
1930 inputTarget->pointerIds.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001931#endif
1932
1933 // Skip this event if the connection status is not normal.
1934 // We don't want to enqueue additional outbound events if the connection is broken.
1935 if (connection->status != Connection::STATUS_NORMAL) {
1936#if DEBUG_DISPATCH_CYCLE
1937 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08001938 connection->getInputChannelName().c_str(), connection->getStatusLabel());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001939#endif
1940 return;
1941 }
1942
1943 // Split a motion event if needed.
1944 if (inputTarget->flags & InputTarget::FLAG_SPLIT) {
1945 ALOG_ASSERT(eventEntry->type == EventEntry::TYPE_MOTION);
1946
1947 MotionEntry* originalMotionEntry = static_cast<MotionEntry*>(eventEntry);
1948 if (inputTarget->pointerIds.count() != originalMotionEntry->pointerCount) {
1949 MotionEntry* splitMotionEntry = splitMotionEvent(
1950 originalMotionEntry, inputTarget->pointerIds);
1951 if (!splitMotionEntry) {
1952 return; // split event was dropped
1953 }
1954#if DEBUG_FOCUS
1955 ALOGD("channel '%s' ~ Split motion event.",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08001956 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001957 logOutboundMotionDetailsLocked(" ", splitMotionEntry);
1958#endif
1959 enqueueDispatchEntriesLocked(currentTime, connection,
1960 splitMotionEntry, inputTarget);
1961 splitMotionEntry->release();
1962 return;
1963 }
1964 }
1965
1966 // Not splitting. Enqueue dispatch entries for the event as is.
1967 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
1968}
1969
1970void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
1971 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget) {
1972 bool wasEmpty = connection->outboundQueue.isEmpty();
1973
1974 // Enqueue dispatch entries for the requested modes.
1975 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1976 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
1977 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1978 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
1979 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1980 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
1981 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1982 InputTarget::FLAG_DISPATCH_AS_IS);
1983 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1984 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
1985 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1986 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
1987
1988 // If the outbound queue was previously empty, start the dispatch cycle going.
1989 if (wasEmpty && !connection->outboundQueue.isEmpty()) {
1990 startDispatchCycleLocked(currentTime, connection);
1991 }
1992}
1993
1994void InputDispatcher::enqueueDispatchEntryLocked(
1995 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget,
1996 int32_t dispatchMode) {
1997 int32_t inputTargetFlags = inputTarget->flags;
1998 if (!(inputTargetFlags & dispatchMode)) {
1999 return;
2000 }
2001 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
2002
2003 // This is a new event.
2004 // Enqueue a new dispatch entry onto the outbound queue for this connection.
2005 DispatchEntry* dispatchEntry = new DispatchEntry(eventEntry, // increments ref
2006 inputTargetFlags, inputTarget->xOffset, inputTarget->yOffset,
Robert Carre07e1032018-11-26 12:55:53 -08002007 inputTarget->globalScaleFactor, inputTarget->windowXScale,
2008 inputTarget->windowYScale);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002009
2010 // Apply target flags and update the connection's input state.
2011 switch (eventEntry->type) {
2012 case EventEntry::TYPE_KEY: {
2013 KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
2014 dispatchEntry->resolvedAction = keyEntry->action;
2015 dispatchEntry->resolvedFlags = keyEntry->flags;
2016
2017 if (!connection->inputState.trackKey(keyEntry,
2018 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags)) {
2019#if DEBUG_DISPATCH_CYCLE
2020 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002021 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002022#endif
2023 delete dispatchEntry;
2024 return; // skip the inconsistent event
2025 }
2026 break;
2027 }
2028
2029 case EventEntry::TYPE_MOTION: {
2030 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
2031 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2032 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
2033 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
2034 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
2035 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
2036 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2037 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
2038 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
2039 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
2040 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
2041 } else {
2042 dispatchEntry->resolvedAction = motionEntry->action;
2043 }
2044 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE
2045 && !connection->inputState.isHovering(
2046 motionEntry->deviceId, motionEntry->source, motionEntry->displayId)) {
2047#if DEBUG_DISPATCH_CYCLE
2048 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter event",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002049 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002050#endif
2051 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2052 }
2053
2054 dispatchEntry->resolvedFlags = motionEntry->flags;
2055 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
2056 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
2057 }
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002058 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
2059 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2060 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002061
2062 if (!connection->inputState.trackMotion(motionEntry,
2063 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags)) {
2064#if DEBUG_DISPATCH_CYCLE
2065 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion event",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002066 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002067#endif
2068 delete dispatchEntry;
2069 return; // skip the inconsistent event
2070 }
2071 break;
2072 }
2073 }
2074
2075 // Remember that we are waiting for this dispatch to complete.
2076 if (dispatchEntry->hasForegroundTarget()) {
2077 incrementPendingForegroundDispatchesLocked(eventEntry);
2078 }
2079
2080 // Enqueue the dispatch entry.
2081 connection->outboundQueue.enqueueAtTail(dispatchEntry);
2082 traceOutboundQueueLengthLocked(connection);
2083}
2084
2085void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
2086 const sp<Connection>& connection) {
2087#if DEBUG_DISPATCH_CYCLE
2088 ALOGD("channel '%s' ~ startDispatchCycle",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002089 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002090#endif
2091
2092 while (connection->status == Connection::STATUS_NORMAL
2093 && !connection->outboundQueue.isEmpty()) {
2094 DispatchEntry* dispatchEntry = connection->outboundQueue.head;
2095 dispatchEntry->deliveryTime = currentTime;
2096
2097 // Publish the event.
2098 status_t status;
2099 EventEntry* eventEntry = dispatchEntry->eventEntry;
2100 switch (eventEntry->type) {
2101 case EventEntry::TYPE_KEY: {
2102 KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
2103
2104 // Publish the key event.
2105 status = connection->inputPublisher.publishKeyEvent(dispatchEntry->seq,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002106 keyEntry->deviceId, keyEntry->source, keyEntry->displayId,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002107 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags,
2108 keyEntry->keyCode, keyEntry->scanCode,
2109 keyEntry->metaState, keyEntry->repeatCount, keyEntry->downTime,
2110 keyEntry->eventTime);
2111 break;
2112 }
2113
2114 case EventEntry::TYPE_MOTION: {
2115 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
2116
2117 PointerCoords scaledCoords[MAX_POINTERS];
2118 const PointerCoords* usingCoords = motionEntry->pointerCoords;
2119
2120 // Set the X and Y offset depending on the input source.
Siarhei Vishniakou635cb712017-11-01 16:32:14 -07002121 float xOffset, yOffset;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002122 if ((motionEntry->source & AINPUT_SOURCE_CLASS_POINTER)
2123 && !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
Robert Carre07e1032018-11-26 12:55:53 -08002124 float globalScaleFactor = dispatchEntry->globalScaleFactor;
2125 float wxs = dispatchEntry->windowXScale;
2126 float wys = dispatchEntry->windowYScale;
2127 xOffset = dispatchEntry->xOffset * wxs;
2128 yOffset = dispatchEntry->yOffset * wys;
2129 if (wxs != 1.0f || wys != 1.0f || globalScaleFactor != 1.0f) {
Narayan Kamathbc6001b2014-05-02 17:53:33 +01002130 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002131 scaledCoords[i] = motionEntry->pointerCoords[i];
Robert Carre07e1032018-11-26 12:55:53 -08002132 scaledCoords[i].scale(globalScaleFactor, wxs, wys);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002133 }
2134 usingCoords = scaledCoords;
2135 }
2136 } else {
2137 xOffset = 0.0f;
2138 yOffset = 0.0f;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002139
2140 // We don't want the dispatch target to know.
2141 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
Narayan Kamathbc6001b2014-05-02 17:53:33 +01002142 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002143 scaledCoords[i].clear();
2144 }
2145 usingCoords = scaledCoords;
2146 }
2147 }
2148
2149 // Publish the motion event.
2150 status = connection->inputPublisher.publishMotionEvent(dispatchEntry->seq,
Tarandeep Singh58641502017-07-31 10:51:54 -07002151 motionEntry->deviceId, motionEntry->source, motionEntry->displayId,
Michael Wright7b159c92015-05-14 14:48:03 +01002152 dispatchEntry->resolvedAction, motionEntry->actionButton,
2153 dispatchEntry->resolvedFlags, motionEntry->edgeFlags,
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08002154 motionEntry->metaState, motionEntry->buttonState, motionEntry->classification,
Michael Wright7b159c92015-05-14 14:48:03 +01002155 xOffset, yOffset, motionEntry->xPrecision, motionEntry->yPrecision,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002156 motionEntry->downTime, motionEntry->eventTime,
2157 motionEntry->pointerCount, motionEntry->pointerProperties,
2158 usingCoords);
2159 break;
2160 }
2161
2162 default:
2163 ALOG_ASSERT(false);
2164 return;
2165 }
2166
2167 // Check the result.
2168 if (status) {
2169 if (status == WOULD_BLOCK) {
2170 if (connection->waitQueue.isEmpty()) {
2171 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
2172 "This is unexpected because the wait queue is empty, so the pipe "
2173 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002174 "event to it, status=%d", connection->getInputChannelName().c_str(),
2175 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002176 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2177 } else {
2178 // Pipe is full and we are waiting for the app to finish process some events
2179 // before sending more events to it.
2180#if DEBUG_DISPATCH_CYCLE
2181 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
2182 "waiting for the application to catch up",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002183 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002184#endif
2185 connection->inputPublisherBlocked = true;
2186 }
2187 } else {
2188 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002189 "status=%d", connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002190 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2191 }
2192 return;
2193 }
2194
2195 // Re-enqueue the event on the wait queue.
2196 connection->outboundQueue.dequeue(dispatchEntry);
2197 traceOutboundQueueLengthLocked(connection);
2198 connection->waitQueue.enqueueAtTail(dispatchEntry);
2199 traceWaitQueueLengthLocked(connection);
2200 }
2201}
2202
2203void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
2204 const sp<Connection>& connection, uint32_t seq, bool handled) {
2205#if DEBUG_DISPATCH_CYCLE
2206 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002207 connection->getInputChannelName().c_str(), seq, toString(handled));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002208#endif
2209
2210 connection->inputPublisherBlocked = false;
2211
2212 if (connection->status == Connection::STATUS_BROKEN
2213 || connection->status == Connection::STATUS_ZOMBIE) {
2214 return;
2215 }
2216
2217 // Notify other system components and prepare to start the next dispatch cycle.
2218 onDispatchCycleFinishedLocked(currentTime, connection, seq, handled);
2219}
2220
2221void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
2222 const sp<Connection>& connection, bool notify) {
2223#if DEBUG_DISPATCH_CYCLE
2224 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002225 connection->getInputChannelName().c_str(), toString(notify));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002226#endif
2227
2228 // Clear the dispatch queues.
2229 drainDispatchQueueLocked(&connection->outboundQueue);
2230 traceOutboundQueueLengthLocked(connection);
2231 drainDispatchQueueLocked(&connection->waitQueue);
2232 traceWaitQueueLengthLocked(connection);
2233
2234 // The connection appears to be unrecoverably broken.
2235 // Ignore already broken or zombie connections.
2236 if (connection->status == Connection::STATUS_NORMAL) {
2237 connection->status = Connection::STATUS_BROKEN;
2238
2239 if (notify) {
2240 // Notify other system components.
2241 onDispatchCycleBrokenLocked(currentTime, connection);
2242 }
2243 }
2244}
2245
2246void InputDispatcher::drainDispatchQueueLocked(Queue<DispatchEntry>* queue) {
2247 while (!queue->isEmpty()) {
2248 DispatchEntry* dispatchEntry = queue->dequeueAtHead();
2249 releaseDispatchEntryLocked(dispatchEntry);
2250 }
2251}
2252
2253void InputDispatcher::releaseDispatchEntryLocked(DispatchEntry* dispatchEntry) {
2254 if (dispatchEntry->hasForegroundTarget()) {
2255 decrementPendingForegroundDispatchesLocked(dispatchEntry->eventEntry);
2256 }
2257 delete dispatchEntry;
2258}
2259
2260int InputDispatcher::handleReceiveCallback(int fd, int events, void* data) {
2261 InputDispatcher* d = static_cast<InputDispatcher*>(data);
2262
2263 { // acquire lock
2264 AutoMutex _l(d->mLock);
2265
2266 ssize_t connectionIndex = d->mConnectionsByFd.indexOfKey(fd);
2267 if (connectionIndex < 0) {
2268 ALOGE("Received spurious receive callback for unknown input channel. "
2269 "fd=%d, events=0x%x", fd, events);
2270 return 0; // remove the callback
2271 }
2272
2273 bool notify;
2274 sp<Connection> connection = d->mConnectionsByFd.valueAt(connectionIndex);
2275 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
2276 if (!(events & ALOOPER_EVENT_INPUT)) {
2277 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002278 "events=0x%x", connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002279 return 1;
2280 }
2281
2282 nsecs_t currentTime = now();
2283 bool gotOne = false;
2284 status_t status;
2285 for (;;) {
2286 uint32_t seq;
2287 bool handled;
2288 status = connection->inputPublisher.receiveFinishedSignal(&seq, &handled);
2289 if (status) {
2290 break;
2291 }
2292 d->finishDispatchCycleLocked(currentTime, connection, seq, handled);
2293 gotOne = true;
2294 }
2295 if (gotOne) {
2296 d->runCommandsLockedInterruptible();
2297 if (status == WOULD_BLOCK) {
2298 return 1;
2299 }
2300 }
2301
2302 notify = status != DEAD_OBJECT || !connection->monitor;
2303 if (notify) {
2304 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002305 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002306 }
2307 } else {
2308 // Monitor channels are never explicitly unregistered.
2309 // We do it automatically when the remote endpoint is closed so don't warn
2310 // about them.
2311 notify = !connection->monitor;
2312 if (notify) {
2313 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. "
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002314 "events=0x%x", connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002315 }
2316 }
2317
2318 // Unregister the channel.
2319 d->unregisterInputChannelLocked(connection->inputChannel, notify);
2320 return 0; // remove the callback
2321 } // release lock
2322}
2323
2324void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
2325 const CancelationOptions& options) {
2326 for (size_t i = 0; i < mConnectionsByFd.size(); i++) {
2327 synthesizeCancelationEventsForConnectionLocked(
2328 mConnectionsByFd.valueAt(i), options);
2329 }
2330}
2331
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002332void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
2333 const CancelationOptions& options) {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002334 for (auto& it : mMonitoringChannelsByDisplay) {
2335 const Vector<sp<InputChannel>>& monitoringChannels = it.second;
2336 const size_t numChannels = monitoringChannels.size();
2337 for (size_t i = 0; i < numChannels; i++) {
2338 synthesizeCancelationEventsForInputChannelLocked(monitoringChannels[i], options);
2339 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002340 }
2341}
2342
Michael Wrightd02c5b62014-02-10 15:10:22 -08002343void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
2344 const sp<InputChannel>& channel, const CancelationOptions& options) {
2345 ssize_t index = getConnectionIndexLocked(channel);
2346 if (index >= 0) {
2347 synthesizeCancelationEventsForConnectionLocked(
2348 mConnectionsByFd.valueAt(index), options);
2349 }
2350}
2351
2352void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
2353 const sp<Connection>& connection, const CancelationOptions& options) {
2354 if (connection->status == Connection::STATUS_BROKEN) {
2355 return;
2356 }
2357
2358 nsecs_t currentTime = now();
2359
2360 Vector<EventEntry*> cancelationEvents;
2361 connection->inputState.synthesizeCancelationEvents(currentTime,
2362 cancelationEvents, options);
2363
2364 if (!cancelationEvents.isEmpty()) {
2365#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002366 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
Michael Wrightd02c5b62014-02-10 15:10:22 -08002367 "with reality: %s, mode=%d.",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002368 connection->getInputChannelName().c_str(), cancelationEvents.size(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002369 options.reason, options.mode);
2370#endif
2371 for (size_t i = 0; i < cancelationEvents.size(); i++) {
2372 EventEntry* cancelationEventEntry = cancelationEvents.itemAt(i);
2373 switch (cancelationEventEntry->type) {
2374 case EventEntry::TYPE_KEY:
2375 logOutboundKeyDetailsLocked("cancel - ",
2376 static_cast<KeyEntry*>(cancelationEventEntry));
2377 break;
2378 case EventEntry::TYPE_MOTION:
2379 logOutboundMotionDetailsLocked("cancel - ",
2380 static_cast<MotionEntry*>(cancelationEventEntry));
2381 break;
2382 }
2383
2384 InputTarget target;
chaviwfbe5d9c2018-12-26 12:23:37 -08002385 sp<InputWindowHandle> windowHandle = getWindowHandleLocked(
2386 connection->inputChannel->getToken());
Yi Kong9b14ac62018-07-17 13:48:38 -07002387 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002388 const InputWindowInfo* windowInfo = windowHandle->getInfo();
2389 target.xOffset = -windowInfo->frameLeft;
2390 target.yOffset = -windowInfo->frameTop;
Robert Carre07e1032018-11-26 12:55:53 -08002391 target.globalScaleFactor = windowInfo->globalScaleFactor;
2392 target.windowXScale = windowInfo->windowXScale;
2393 target.windowYScale = windowInfo->windowYScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002394 } else {
2395 target.xOffset = 0;
2396 target.yOffset = 0;
Robert Carre07e1032018-11-26 12:55:53 -08002397 target.globalScaleFactor = 1.0f;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002398 }
2399 target.inputChannel = connection->inputChannel;
2400 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
2401
2402 enqueueDispatchEntryLocked(connection, cancelationEventEntry, // increments ref
2403 &target, InputTarget::FLAG_DISPATCH_AS_IS);
2404
2405 cancelationEventEntry->release();
2406 }
2407
2408 startDispatchCycleLocked(currentTime, connection);
2409 }
2410}
2411
2412InputDispatcher::MotionEntry*
2413InputDispatcher::splitMotionEvent(const MotionEntry* originalMotionEntry, BitSet32 pointerIds) {
2414 ALOG_ASSERT(pointerIds.value != 0);
2415
2416 uint32_t splitPointerIndexMap[MAX_POINTERS];
2417 PointerProperties splitPointerProperties[MAX_POINTERS];
2418 PointerCoords splitPointerCoords[MAX_POINTERS];
2419
2420 uint32_t originalPointerCount = originalMotionEntry->pointerCount;
2421 uint32_t splitPointerCount = 0;
2422
2423 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
2424 originalPointerIndex++) {
2425 const PointerProperties& pointerProperties =
2426 originalMotionEntry->pointerProperties[originalPointerIndex];
2427 uint32_t pointerId = uint32_t(pointerProperties.id);
2428 if (pointerIds.hasBit(pointerId)) {
2429 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
2430 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
2431 splitPointerCoords[splitPointerCount].copyFrom(
2432 originalMotionEntry->pointerCoords[originalPointerIndex]);
2433 splitPointerCount += 1;
2434 }
2435 }
2436
2437 if (splitPointerCount != pointerIds.count()) {
2438 // This is bad. We are missing some of the pointers that we expected to deliver.
2439 // Most likely this indicates that we received an ACTION_MOVE events that has
2440 // different pointer ids than we expected based on the previous ACTION_DOWN
2441 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
2442 // in this way.
2443 ALOGW("Dropping split motion event because the pointer count is %d but "
2444 "we expected there to be %d pointers. This probably means we received "
2445 "a broken sequence of pointer ids from the input device.",
2446 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07002447 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002448 }
2449
2450 int32_t action = originalMotionEntry->action;
2451 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
2452 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
2453 || maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2454 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
2455 const PointerProperties& pointerProperties =
2456 originalMotionEntry->pointerProperties[originalPointerIndex];
2457 uint32_t pointerId = uint32_t(pointerProperties.id);
2458 if (pointerIds.hasBit(pointerId)) {
2459 if (pointerIds.count() == 1) {
2460 // The first/last pointer went down/up.
2461 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
2462 ? AMOTION_EVENT_ACTION_DOWN : AMOTION_EVENT_ACTION_UP;
2463 } else {
2464 // A secondary pointer went down/up.
2465 uint32_t splitPointerIndex = 0;
2466 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
2467 splitPointerIndex += 1;
2468 }
2469 action = maskedAction | (splitPointerIndex
2470 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
2471 }
2472 } else {
2473 // An unrelated pointer changed.
2474 action = AMOTION_EVENT_ACTION_MOVE;
2475 }
2476 }
2477
2478 MotionEntry* splitMotionEntry = new MotionEntry(
Prabir Pradhan42611e02018-11-27 14:04:02 -08002479 originalMotionEntry->sequenceNum,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002480 originalMotionEntry->eventTime,
2481 originalMotionEntry->deviceId,
2482 originalMotionEntry->source,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002483 originalMotionEntry->displayId,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002484 originalMotionEntry->policyFlags,
2485 action,
Michael Wright7b159c92015-05-14 14:48:03 +01002486 originalMotionEntry->actionButton,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002487 originalMotionEntry->flags,
2488 originalMotionEntry->metaState,
2489 originalMotionEntry->buttonState,
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08002490 originalMotionEntry->classification,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002491 originalMotionEntry->edgeFlags,
2492 originalMotionEntry->xPrecision,
2493 originalMotionEntry->yPrecision,
2494 originalMotionEntry->downTime,
Jeff Brownf086ddb2014-02-11 14:28:48 -08002495 splitPointerCount, splitPointerProperties, splitPointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002496
2497 if (originalMotionEntry->injectionState) {
2498 splitMotionEntry->injectionState = originalMotionEntry->injectionState;
2499 splitMotionEntry->injectionState->refCount += 1;
2500 }
2501
2502 return splitMotionEntry;
2503}
2504
2505void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
2506#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002507 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002508#endif
2509
2510 bool needWake;
2511 { // acquire lock
2512 AutoMutex _l(mLock);
2513
Prabir Pradhan42611e02018-11-27 14:04:02 -08002514 ConfigurationChangedEntry* newEntry =
2515 new ConfigurationChangedEntry(args->sequenceNum, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002516 needWake = enqueueInboundEventLocked(newEntry);
2517 } // release lock
2518
2519 if (needWake) {
2520 mLooper->wake();
2521 }
2522}
2523
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002524/**
2525 * If one of the meta shortcuts is detected, process them here:
2526 * Meta + Backspace -> generate BACK
2527 * Meta + Enter -> generate HOME
2528 * This will potentially overwrite keyCode and metaState.
2529 */
2530void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
2531 int32_t& keyCode, int32_t& metaState) {
2532 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
2533 int32_t newKeyCode = AKEYCODE_UNKNOWN;
2534 if (keyCode == AKEYCODE_DEL) {
2535 newKeyCode = AKEYCODE_BACK;
2536 } else if (keyCode == AKEYCODE_ENTER) {
2537 newKeyCode = AKEYCODE_HOME;
2538 }
2539 if (newKeyCode != AKEYCODE_UNKNOWN) {
2540 AutoMutex _l(mLock);
2541 struct KeyReplacement replacement = {keyCode, deviceId};
2542 mReplacedKeys.add(replacement, newKeyCode);
2543 keyCode = newKeyCode;
2544 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
2545 }
2546 } else if (action == AKEY_EVENT_ACTION_UP) {
2547 // In order to maintain a consistent stream of up and down events, check to see if the key
2548 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
2549 // even if the modifier was released between the down and the up events.
2550 AutoMutex _l(mLock);
2551 struct KeyReplacement replacement = {keyCode, deviceId};
2552 ssize_t index = mReplacedKeys.indexOfKey(replacement);
2553 if (index >= 0) {
2554 keyCode = mReplacedKeys.valueAt(index);
2555 mReplacedKeys.removeItemsAt(index);
2556 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
2557 }
2558 }
2559}
2560
Michael Wrightd02c5b62014-02-10 15:10:22 -08002561void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
2562#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002563 ALOGD("notifyKey - eventTime=%" PRId64
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002564 ", deviceId=%d, source=0x%x, displayId=%" PRId32 "policyFlags=0x%x, action=0x%x, "
Arthur Hung82a4cad2018-11-15 12:10:30 +08002565 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002566 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002567 args->action, args->flags, args->keyCode, args->scanCode,
Arthur Hung82a4cad2018-11-15 12:10:30 +08002568 args->metaState, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002569#endif
2570 if (!validateKeyEvent(args->action)) {
2571 return;
2572 }
2573
2574 uint32_t policyFlags = args->policyFlags;
2575 int32_t flags = args->flags;
2576 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07002577 // InputDispatcher tracks and generates key repeats on behalf of
2578 // whatever notifies it, so repeatCount should always be set to 0
2579 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002580 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
2581 policyFlags |= POLICY_FLAG_VIRTUAL;
2582 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
2583 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002584 if (policyFlags & POLICY_FLAG_FUNCTION) {
2585 metaState |= AMETA_FUNCTION_ON;
2586 }
2587
2588 policyFlags |= POLICY_FLAG_TRUSTED;
2589
Michael Wright78f24442014-08-06 15:55:28 -07002590 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002591 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07002592
Michael Wrightd02c5b62014-02-10 15:10:22 -08002593 KeyEvent event;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002594 event.initialize(args->deviceId, args->source, args->displayId, args->action,
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07002595 flags, keyCode, args->scanCode, metaState, repeatCount,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002596 args->downTime, args->eventTime);
2597
Michael Wright2b3c3302018-03-02 17:19:13 +00002598 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002599 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002600 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2601 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
2602 std::to_string(t.duration().count()).c_str());
2603 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002604
Michael Wrightd02c5b62014-02-10 15:10:22 -08002605 bool needWake;
2606 { // acquire lock
2607 mLock.lock();
2608
2609 if (shouldSendKeyToInputFilterLocked(args)) {
2610 mLock.unlock();
2611
2612 policyFlags |= POLICY_FLAG_FILTERED;
2613 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2614 return; // event was consumed by the filter
2615 }
2616
2617 mLock.lock();
2618 }
2619
Prabir Pradhan42611e02018-11-27 14:04:02 -08002620 KeyEntry* newEntry = new KeyEntry(args->sequenceNum, args->eventTime,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002621 args->deviceId, args->source, args->displayId, policyFlags,
Michael Wright78f24442014-08-06 15:55:28 -07002622 args->action, flags, keyCode, args->scanCode,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002623 metaState, repeatCount, args->downTime);
2624
2625 needWake = enqueueInboundEventLocked(newEntry);
2626 mLock.unlock();
2627 } // release lock
2628
2629 if (needWake) {
2630 mLooper->wake();
2631 }
2632}
2633
2634bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
2635 return mInputFilterEnabled;
2636}
2637
2638void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
2639#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002640 ALOGD("notifyMotion - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
2641 ", policyFlags=0x%x, "
Michael Wright7b159c92015-05-14 14:48:03 +01002642 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x,"
Arthur Hung82a4cad2018-11-15 12:10:30 +08002643 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
2644 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002645 args->action, args->actionButton, args->flags, args->metaState, args->buttonState,
Arthur Hung82a4cad2018-11-15 12:10:30 +08002646 args->edgeFlags, args->xPrecision, args->yPrecision, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002647 for (uint32_t i = 0; i < args->pointerCount; i++) {
2648 ALOGD(" Pointer %d: id=%d, toolType=%d, "
2649 "x=%f, y=%f, pressure=%f, size=%f, "
2650 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
2651 "orientation=%f",
2652 i, args->pointerProperties[i].id,
2653 args->pointerProperties[i].toolType,
2654 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
2655 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
2656 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
2657 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
2658 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
2659 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
2660 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
2661 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
2662 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
2663 }
2664#endif
Michael Wright7b159c92015-05-14 14:48:03 +01002665 if (!validateMotionEvent(args->action, args->actionButton,
2666 args->pointerCount, args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002667 return;
2668 }
2669
2670 uint32_t policyFlags = args->policyFlags;
2671 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00002672
2673 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002674 mPolicy->interceptMotionBeforeQueueing(args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002675 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2676 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
2677 std::to_string(t.duration().count()).c_str());
2678 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002679
2680 bool needWake;
2681 { // acquire lock
2682 mLock.lock();
2683
2684 if (shouldSendMotionToInputFilterLocked(args)) {
2685 mLock.unlock();
2686
2687 MotionEvent event;
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002688 event.initialize(args->deviceId, args->source, args->displayId,
2689 args->action, args->actionButton,
Michael Wright7b159c92015-05-14 14:48:03 +01002690 args->flags, args->edgeFlags, args->metaState, args->buttonState,
Siarhei Vishniakouae478d32019-01-03 14:45:18 -08002691 args->classification, 0, 0, args->xPrecision, args->yPrecision,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002692 args->downTime, args->eventTime,
2693 args->pointerCount, args->pointerProperties, args->pointerCoords);
2694
2695 policyFlags |= POLICY_FLAG_FILTERED;
2696 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2697 return; // event was consumed by the filter
2698 }
2699
2700 mLock.lock();
2701 }
2702
2703 // Just enqueue a new motion event.
Prabir Pradhan42611e02018-11-27 14:04:02 -08002704 MotionEntry* newEntry = new MotionEntry(args->sequenceNum, args->eventTime,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002705 args->deviceId, args->source, args->displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002706 args->action, args->actionButton, args->flags,
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08002707 args->metaState, args->buttonState, args->classification,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002708 args->edgeFlags, args->xPrecision, args->yPrecision, args->downTime,
Jeff Brownf086ddb2014-02-11 14:28:48 -08002709 args->pointerCount, args->pointerProperties, args->pointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002710
2711 needWake = enqueueInboundEventLocked(newEntry);
2712 mLock.unlock();
2713 } // release lock
2714
2715 if (needWake) {
2716 mLooper->wake();
2717 }
2718}
2719
2720bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08002721 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002722}
2723
2724void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
2725#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002726 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
2727 "switchMask=0x%08x",
2728 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002729#endif
2730
2731 uint32_t policyFlags = args->policyFlags;
2732 policyFlags |= POLICY_FLAG_TRUSTED;
2733 mPolicy->notifySwitch(args->eventTime,
2734 args->switchValues, args->switchMask, policyFlags);
2735}
2736
2737void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
2738#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002739 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002740 args->eventTime, args->deviceId);
2741#endif
2742
2743 bool needWake;
2744 { // acquire lock
2745 AutoMutex _l(mLock);
2746
Prabir Pradhan42611e02018-11-27 14:04:02 -08002747 DeviceResetEntry* newEntry =
2748 new DeviceResetEntry(args->sequenceNum, args->eventTime, args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002749 needWake = enqueueInboundEventLocked(newEntry);
2750 } // release lock
2751
2752 if (needWake) {
2753 mLooper->wake();
2754 }
2755}
2756
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002757int32_t InputDispatcher::injectInputEvent(const InputEvent* event,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002758 int32_t injectorPid, int32_t injectorUid, int32_t syncMode, int32_t timeoutMillis,
2759 uint32_t policyFlags) {
2760#if DEBUG_INBOUND_EVENT_DETAILS
2761 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002762 "syncMode=%d, timeoutMillis=%d, policyFlags=0x%08x",
2763 event->getType(), injectorPid, injectorUid, syncMode, timeoutMillis, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002764#endif
2765
2766 nsecs_t endTime = now() + milliseconds_to_nanoseconds(timeoutMillis);
2767
2768 policyFlags |= POLICY_FLAG_INJECTED;
2769 if (hasInjectionPermission(injectorPid, injectorUid)) {
2770 policyFlags |= POLICY_FLAG_TRUSTED;
2771 }
2772
2773 EventEntry* firstInjectedEntry;
2774 EventEntry* lastInjectedEntry;
2775 switch (event->getType()) {
2776 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002777 KeyEvent keyEvent;
2778 keyEvent.initialize(*static_cast<const KeyEvent*>(event));
2779 int32_t action = keyEvent.getAction();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002780 if (! validateKeyEvent(action)) {
2781 return INPUT_EVENT_INJECTION_FAILED;
2782 }
2783
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002784 int32_t flags = keyEvent.getFlags();
2785 int32_t keyCode = keyEvent.getKeyCode();
2786 int32_t metaState = keyEvent.getMetaState();
2787 accelerateMetaShortcuts(keyEvent.getDeviceId(), action,
2788 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002789 keyEvent.initialize(keyEvent.getDeviceId(), keyEvent.getSource(), keyEvent.getDisplayId(),
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07002790 action, flags, keyCode, keyEvent.getScanCode(), metaState, keyEvent.getRepeatCount(),
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002791 keyEvent.getDownTime(), keyEvent.getEventTime());
2792
Michael Wrightd02c5b62014-02-10 15:10:22 -08002793 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
2794 policyFlags |= POLICY_FLAG_VIRTUAL;
2795 }
2796
2797 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wright2b3c3302018-03-02 17:19:13 +00002798 android::base::Timer t;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002799 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002800 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2801 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
2802 std::to_string(t.duration().count()).c_str());
2803 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002804 }
2805
Michael Wrightd02c5b62014-02-10 15:10:22 -08002806 mLock.lock();
Prabir Pradhan42611e02018-11-27 14:04:02 -08002807 firstInjectedEntry = new KeyEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, keyEvent.getEventTime(),
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002808 keyEvent.getDeviceId(), keyEvent.getSource(), keyEvent.getDisplayId(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002809 policyFlags, action, flags,
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002810 keyEvent.getKeyCode(), keyEvent.getScanCode(), keyEvent.getMetaState(),
2811 keyEvent.getRepeatCount(), keyEvent.getDownTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002812 lastInjectedEntry = firstInjectedEntry;
2813 break;
2814 }
2815
2816 case AINPUT_EVENT_TYPE_MOTION: {
2817 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002818 int32_t action = motionEvent->getAction();
2819 size_t pointerCount = motionEvent->getPointerCount();
2820 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
Michael Wright7b159c92015-05-14 14:48:03 +01002821 int32_t actionButton = motionEvent->getActionButton();
2822 if (! validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002823 return INPUT_EVENT_INJECTION_FAILED;
2824 }
2825
2826 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
2827 nsecs_t eventTime = motionEvent->getEventTime();
Michael Wright2b3c3302018-03-02 17:19:13 +00002828 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002829 mPolicy->interceptMotionBeforeQueueing(eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002830 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2831 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
2832 std::to_string(t.duration().count()).c_str());
2833 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002834 }
2835
2836 mLock.lock();
2837 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
2838 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
Prabir Pradhan42611e02018-11-27 14:04:02 -08002839 firstInjectedEntry = new MotionEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, *sampleEventTimes,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002840 motionEvent->getDeviceId(), motionEvent->getSource(), motionEvent->getDisplayId(),
2841 policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002842 action, actionButton, motionEvent->getFlags(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002843 motionEvent->getMetaState(), motionEvent->getButtonState(),
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08002844 motionEvent->getClassification(), motionEvent->getEdgeFlags(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002845 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002846 motionEvent->getDownTime(),
Jeff Brownf086ddb2014-02-11 14:28:48 -08002847 uint32_t(pointerCount), pointerProperties, samplePointerCoords,
2848 motionEvent->getXOffset(), motionEvent->getYOffset());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002849 lastInjectedEntry = firstInjectedEntry;
2850 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
2851 sampleEventTimes += 1;
2852 samplePointerCoords += pointerCount;
Prabir Pradhan42611e02018-11-27 14:04:02 -08002853 MotionEntry* nextInjectedEntry = new MotionEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM,
2854 *sampleEventTimes,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002855 motionEvent->getDeviceId(), motionEvent->getSource(),
2856 motionEvent->getDisplayId(), policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002857 action, actionButton, motionEvent->getFlags(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002858 motionEvent->getMetaState(), motionEvent->getButtonState(),
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08002859 motionEvent->getClassification(), motionEvent->getEdgeFlags(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002860 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002861 motionEvent->getDownTime(),
Jeff Brownf086ddb2014-02-11 14:28:48 -08002862 uint32_t(pointerCount), pointerProperties, samplePointerCoords,
2863 motionEvent->getXOffset(), motionEvent->getYOffset());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002864 lastInjectedEntry->next = nextInjectedEntry;
2865 lastInjectedEntry = nextInjectedEntry;
2866 }
2867 break;
2868 }
2869
2870 default:
2871 ALOGW("Cannot inject event of type %d", event->getType());
2872 return INPUT_EVENT_INJECTION_FAILED;
2873 }
2874
2875 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
2876 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
2877 injectionState->injectionIsAsync = true;
2878 }
2879
2880 injectionState->refCount += 1;
2881 lastInjectedEntry->injectionState = injectionState;
2882
2883 bool needWake = false;
Yi Kong9b14ac62018-07-17 13:48:38 -07002884 for (EventEntry* entry = firstInjectedEntry; entry != nullptr; ) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002885 EventEntry* nextEntry = entry->next;
2886 needWake |= enqueueInboundEventLocked(entry);
2887 entry = nextEntry;
2888 }
2889
2890 mLock.unlock();
2891
2892 if (needWake) {
2893 mLooper->wake();
2894 }
2895
2896 int32_t injectionResult;
2897 { // acquire lock
2898 AutoMutex _l(mLock);
2899
2900 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
2901 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
2902 } else {
2903 for (;;) {
2904 injectionResult = injectionState->injectionResult;
2905 if (injectionResult != INPUT_EVENT_INJECTION_PENDING) {
2906 break;
2907 }
2908
2909 nsecs_t remainingTimeout = endTime - now();
2910 if (remainingTimeout <= 0) {
2911#if DEBUG_INJECTION
2912 ALOGD("injectInputEvent - Timed out waiting for injection result "
2913 "to become available.");
2914#endif
2915 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
2916 break;
2917 }
2918
2919 mInjectionResultAvailableCondition.waitRelative(mLock, remainingTimeout);
2920 }
2921
2922 if (injectionResult == INPUT_EVENT_INJECTION_SUCCEEDED
2923 && syncMode == INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED) {
2924 while (injectionState->pendingForegroundDispatches != 0) {
2925#if DEBUG_INJECTION
2926 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
2927 injectionState->pendingForegroundDispatches);
2928#endif
2929 nsecs_t remainingTimeout = endTime - now();
2930 if (remainingTimeout <= 0) {
2931#if DEBUG_INJECTION
2932 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
2933 "dispatches to finish.");
2934#endif
2935 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
2936 break;
2937 }
2938
2939 mInjectionSyncFinishedCondition.waitRelative(mLock, remainingTimeout);
2940 }
2941 }
2942 }
2943
2944 injectionState->release();
2945 } // release lock
2946
2947#if DEBUG_INJECTION
2948 ALOGD("injectInputEvent - Finished with result %d. "
2949 "injectorPid=%d, injectorUid=%d",
2950 injectionResult, injectorPid, injectorUid);
2951#endif
2952
2953 return injectionResult;
2954}
2955
2956bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
2957 return injectorUid == 0
2958 || mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
2959}
2960
2961void InputDispatcher::setInjectionResultLocked(EventEntry* entry, int32_t injectionResult) {
2962 InjectionState* injectionState = entry->injectionState;
2963 if (injectionState) {
2964#if DEBUG_INJECTION
2965 ALOGD("Setting input event injection result to %d. "
2966 "injectorPid=%d, injectorUid=%d",
2967 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
2968#endif
2969
2970 if (injectionState->injectionIsAsync
2971 && !(entry->policyFlags & POLICY_FLAG_FILTERED)) {
2972 // Log the outcome since the injector did not wait for the injection result.
2973 switch (injectionResult) {
2974 case INPUT_EVENT_INJECTION_SUCCEEDED:
2975 ALOGV("Asynchronous input event injection succeeded.");
2976 break;
2977 case INPUT_EVENT_INJECTION_FAILED:
2978 ALOGW("Asynchronous input event injection failed.");
2979 break;
2980 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
2981 ALOGW("Asynchronous input event injection permission denied.");
2982 break;
2983 case INPUT_EVENT_INJECTION_TIMED_OUT:
2984 ALOGW("Asynchronous input event injection timed out.");
2985 break;
2986 }
2987 }
2988
2989 injectionState->injectionResult = injectionResult;
2990 mInjectionResultAvailableCondition.broadcast();
2991 }
2992}
2993
2994void InputDispatcher::incrementPendingForegroundDispatchesLocked(EventEntry* entry) {
2995 InjectionState* injectionState = entry->injectionState;
2996 if (injectionState) {
2997 injectionState->pendingForegroundDispatches += 1;
2998 }
2999}
3000
3001void InputDispatcher::decrementPendingForegroundDispatchesLocked(EventEntry* entry) {
3002 InjectionState* injectionState = entry->injectionState;
3003 if (injectionState) {
3004 injectionState->pendingForegroundDispatches -= 1;
3005
3006 if (injectionState->pendingForegroundDispatches == 0) {
3007 mInjectionSyncFinishedCondition.broadcast();
3008 }
3009 }
3010}
3011
Arthur Hungb92218b2018-08-14 12:00:21 +08003012Vector<sp<InputWindowHandle>> InputDispatcher::getWindowHandlesLocked(int32_t displayId) const {
3013 std::unordered_map<int32_t, Vector<sp<InputWindowHandle>>>::const_iterator it =
3014 mWindowHandlesByDisplay.find(displayId);
3015 if(it != mWindowHandlesByDisplay.end()) {
3016 return it->second;
3017 }
3018
3019 // Return an empty one if nothing found.
3020 return Vector<sp<InputWindowHandle>>();
3021}
3022
Michael Wrightd02c5b62014-02-10 15:10:22 -08003023sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08003024 const sp<IBinder>& windowHandleToken) const {
Arthur Hungb92218b2018-08-14 12:00:21 +08003025 for (auto& it : mWindowHandlesByDisplay) {
3026 const Vector<sp<InputWindowHandle>> windowHandles = it.second;
3027 size_t numWindows = windowHandles.size();
3028 for (size_t i = 0; i < numWindows; i++) {
3029 const sp<InputWindowHandle>& windowHandle = windowHandles.itemAt(i);
chaviwfbe5d9c2018-12-26 12:23:37 -08003030 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003031 return windowHandle;
3032 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003033 }
3034 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003035 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003036}
3037
3038bool InputDispatcher::hasWindowHandleLocked(
Siarhei Vishniakou9224fba2018-08-13 18:55:08 +00003039 const sp<InputWindowHandle>& windowHandle) const {
Arthur Hungb92218b2018-08-14 12:00:21 +08003040 for (auto& it : mWindowHandlesByDisplay) {
3041 const Vector<sp<InputWindowHandle>> windowHandles = it.second;
3042 size_t numWindows = windowHandles.size();
3043 for (size_t i = 0; i < numWindows; i++) {
Robert Carr5c8a0262018-10-03 16:30:44 -07003044 if (windowHandles.itemAt(i)->getToken()
3045 == windowHandle->getToken()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003046 if (windowHandle->getInfo()->displayId != it.first) {
Arthur Hung3b413f22018-10-26 18:05:34 +08003047 ALOGE("Found window %s in display %" PRId32
3048 ", but it should belong to display %" PRId32,
3049 windowHandle->getName().c_str(), it.first,
3050 windowHandle->getInfo()->displayId);
Arthur Hungb92218b2018-08-14 12:00:21 +08003051 }
3052 return true;
3053 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003054 }
3055 }
3056 return false;
3057}
3058
Robert Carr5c8a0262018-10-03 16:30:44 -07003059sp<InputChannel> InputDispatcher::getInputChannelLocked(const sp<IBinder>& token) const {
3060 size_t count = mInputChannelsByToken.count(token);
3061 if (count == 0) {
3062 return nullptr;
3063 }
3064 return mInputChannelsByToken.at(token);
3065}
3066
Arthur Hungb92218b2018-08-14 12:00:21 +08003067/**
3068 * Called from InputManagerService, update window handle list by displayId that can receive input.
3069 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
3070 * If set an empty list, remove all handles from the specific display.
3071 * For focused handle, check if need to change and send a cancel event to previous one.
3072 * For removed handle, check if need to send a cancel event if already in touch.
3073 */
3074void InputDispatcher::setInputWindows(const Vector<sp<InputWindowHandle>>& inputWindowHandles,
3075 int32_t displayId) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003076#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003077 ALOGD("setInputWindows displayId=%" PRId32, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003078#endif
3079 { // acquire lock
3080 AutoMutex _l(mLock);
3081
Arthur Hungb92218b2018-08-14 12:00:21 +08003082 // Copy old handles for release if they are no longer present.
3083 const Vector<sp<InputWindowHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003084
Tiger Huang721e26f2018-07-24 22:26:19 +08003085 sp<InputWindowHandle> newFocusedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003086 bool foundHoveredWindow = false;
Arthur Hungb92218b2018-08-14 12:00:21 +08003087
3088 if (inputWindowHandles.isEmpty()) {
3089 // Remove all handles on a display if there are no windows left.
3090 mWindowHandlesByDisplay.erase(displayId);
3091 } else {
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003092 // Since we compare the pointer of input window handles across window updates, we need
3093 // to make sure the handle object for the same window stays unchanged across updates.
3094 const Vector<sp<InputWindowHandle>>& oldHandles = mWindowHandlesByDisplay[displayId];
3095 std::unordered_map<sp<IBinder>, sp<InputWindowHandle>, IBinderHash> oldHandlesByTokens;
3096 for (size_t i = 0; i < oldHandles.size(); i++) {
3097 const sp<InputWindowHandle>& handle = oldHandles.itemAt(i);
3098 oldHandlesByTokens[handle->getToken()] = handle;
3099 }
3100
3101 const size_t numWindows = inputWindowHandles.size();
3102 Vector<sp<InputWindowHandle>> newHandles;
Arthur Hungb92218b2018-08-14 12:00:21 +08003103 for (size_t i = 0; i < numWindows; i++) {
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003104 const sp<InputWindowHandle>& handle = inputWindowHandles.itemAt(i);
3105 if (!handle->updateInfo() || getInputChannelLocked(handle->getToken()) == nullptr) {
Robert Carr5c8a0262018-10-03 16:30:44 -07003106 ALOGE("Window handle %s has no registered input channel",
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003107 handle->getName().c_str());
Arthur Hungb92218b2018-08-14 12:00:21 +08003108 continue;
3109 }
3110
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003111 if (handle->getInfo()->displayId != displayId) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003112 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003113 handle->getName().c_str(), displayId,
3114 handle->getInfo()->displayId);
Arthur Hungb92218b2018-08-14 12:00:21 +08003115 continue;
3116 }
3117
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003118 if (oldHandlesByTokens.find(handle->getToken()) != oldHandlesByTokens.end()) {
3119 const sp<InputWindowHandle> oldHandle =
3120 oldHandlesByTokens.at(handle->getToken());
3121 oldHandle->updateFrom(handle);
3122 newHandles.push_back(oldHandle);
3123 } else {
3124 newHandles.push_back(handle);
3125 }
3126 }
3127
3128 for (size_t i = 0; i < newHandles.size(); i++) {
3129 const sp<InputWindowHandle>& windowHandle = newHandles.itemAt(i);
Arthur Hung7ab76b12019-01-09 19:17:20 +08003130 // Set newFocusedWindowHandle to the top most focused window instead of the last one
3131 if (!newFocusedWindowHandle && windowHandle->getInfo()->hasFocus
3132 && windowHandle->getInfo()->visible) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003133 newFocusedWindowHandle = windowHandle;
3134 }
3135 if (windowHandle == mLastHoverWindowHandle) {
3136 foundHoveredWindow = true;
3137 }
Siarhei Vishniakou9224fba2018-08-13 18:55:08 +00003138 }
Arthur Hungb92218b2018-08-14 12:00:21 +08003139
3140 // Insert or replace
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003141 mWindowHandlesByDisplay[displayId] = newHandles;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003142 }
3143
3144 if (!foundHoveredWindow) {
Yi Kong9b14ac62018-07-17 13:48:38 -07003145 mLastHoverWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003146 }
3147
Tiger Huang721e26f2018-07-24 22:26:19 +08003148 sp<InputWindowHandle> oldFocusedWindowHandle =
3149 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
3150
3151 if (oldFocusedWindowHandle != newFocusedWindowHandle) {
3152 if (oldFocusedWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003153#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003154 ALOGD("Focus left window: %s in display %" PRId32,
3155 oldFocusedWindowHandle->getName().c_str(), displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003156#endif
Robert Carr5c8a0262018-10-03 16:30:44 -07003157 sp<InputChannel> focusedInputChannel = getInputChannelLocked(
3158 oldFocusedWindowHandle->getToken());
Yi Kong9b14ac62018-07-17 13:48:38 -07003159 if (focusedInputChannel != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003160 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
3161 "focus left window");
3162 synthesizeCancelationEventsForInputChannelLocked(
3163 focusedInputChannel, options);
3164 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003165 mFocusedWindowHandlesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003166 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003167 if (newFocusedWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003168#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003169 ALOGD("Focus entered window: %s in display %" PRId32,
3170 newFocusedWindowHandle->getName().c_str(), displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003171#endif
Tiger Huang721e26f2018-07-24 22:26:19 +08003172 mFocusedWindowHandlesByDisplay[displayId] = newFocusedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003173 }
Robert Carrf759f162018-11-13 12:57:11 -08003174
3175 if (mFocusedDisplayId == displayId) {
chaviw0c06c6e2019-01-09 13:27:07 -08003176 onFocusChangedLocked(oldFocusedWindowHandle, newFocusedWindowHandle);
Robert Carrf759f162018-11-13 12:57:11 -08003177 }
3178
Michael Wrightd02c5b62014-02-10 15:10:22 -08003179 }
3180
Arthur Hungb92218b2018-08-14 12:00:21 +08003181 ssize_t stateIndex = mTouchStatesByDisplay.indexOfKey(displayId);
3182 if (stateIndex >= 0) {
3183 TouchState& state = mTouchStatesByDisplay.editValueAt(stateIndex);
Ivan Lozano96f12992017-11-09 14:45:38 -08003184 for (size_t i = 0; i < state.windows.size(); ) {
Jeff Brownf086ddb2014-02-11 14:28:48 -08003185 TouchedWindow& touchedWindow = state.windows.editItemAt(i);
Siarhei Vishniakou9224fba2018-08-13 18:55:08 +00003186 if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003187#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003188 ALOGD("Touched window was removed: %s in display %" PRId32,
3189 touchedWindow.windowHandle->getName().c_str(), displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003190#endif
Jeff Brownf086ddb2014-02-11 14:28:48 -08003191 sp<InputChannel> touchedInputChannel =
Robert Carr5c8a0262018-10-03 16:30:44 -07003192 getInputChannelLocked(touchedWindow.windowHandle->getToken());
Yi Kong9b14ac62018-07-17 13:48:38 -07003193 if (touchedInputChannel != nullptr) {
Jeff Brownf086ddb2014-02-11 14:28:48 -08003194 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
3195 "touched window was removed");
3196 synthesizeCancelationEventsForInputChannelLocked(
3197 touchedInputChannel, options);
3198 }
Ivan Lozano96f12992017-11-09 14:45:38 -08003199 state.windows.removeAt(i);
3200 } else {
3201 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003202 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003203 }
3204 }
3205
3206 // Release information for windows that are no longer present.
3207 // This ensures that unused input channels are released promptly.
3208 // Otherwise, they might stick around until the window handle is destroyed
3209 // which might not happen until the next GC.
Arthur Hungb92218b2018-08-14 12:00:21 +08003210 size_t numWindows = oldWindowHandles.size();
3211 for (size_t i = 0; i < numWindows; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003212 const sp<InputWindowHandle>& oldWindowHandle = oldWindowHandles.itemAt(i);
Siarhei Vishniakou9224fba2018-08-13 18:55:08 +00003213 if (!hasWindowHandleLocked(oldWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003214#if DEBUG_FOCUS
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003215 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003216#endif
Arthur Hung3b413f22018-10-26 18:05:34 +08003217 oldWindowHandle->releaseChannel();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003218 }
3219 }
3220 } // release lock
3221
3222 // Wake up poll loop since it may need to make new input dispatching choices.
3223 mLooper->wake();
3224}
3225
3226void InputDispatcher::setFocusedApplication(
Tiger Huang721e26f2018-07-24 22:26:19 +08003227 int32_t displayId, const sp<InputApplicationHandle>& inputApplicationHandle) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003228#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003229 ALOGD("setFocusedApplication displayId=%" PRId32, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003230#endif
3231 { // acquire lock
3232 AutoMutex _l(mLock);
3233
Tiger Huang721e26f2018-07-24 22:26:19 +08003234 sp<InputApplicationHandle> oldFocusedApplicationHandle =
3235 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
Yi Kong9b14ac62018-07-17 13:48:38 -07003236 if (inputApplicationHandle != nullptr && inputApplicationHandle->updateInfo()) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003237 if (oldFocusedApplicationHandle != inputApplicationHandle) {
3238 if (oldFocusedApplicationHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003239 resetANRTimeoutsLocked();
Tiger Huang721e26f2018-07-24 22:26:19 +08003240 oldFocusedApplicationHandle->releaseInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003241 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003242 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003243 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003244 } else if (oldFocusedApplicationHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003245 resetANRTimeoutsLocked();
Tiger Huang721e26f2018-07-24 22:26:19 +08003246 oldFocusedApplicationHandle->releaseInfo();
3247 oldFocusedApplicationHandle.clear();
3248 mFocusedApplicationHandlesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003249 }
3250
3251#if DEBUG_FOCUS
3252 //logDispatchStateLocked();
3253#endif
3254 } // release lock
3255
3256 // Wake up poll loop since it may need to make new input dispatching choices.
3257 mLooper->wake();
3258}
3259
Tiger Huang721e26f2018-07-24 22:26:19 +08003260/**
3261 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
3262 * the display not specified.
3263 *
3264 * We track any unreleased events for each window. If a window loses the ability to receive the
3265 * released event, we will send a cancel event to it. So when the focused display is changed, we
3266 * cancel all the unreleased display-unspecified events for the focused window on the old focused
3267 * display. The display-specified events won't be affected.
3268 */
3269void InputDispatcher::setFocusedDisplay(int32_t displayId) {
3270#if DEBUG_FOCUS
3271 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
3272#endif
3273 { // acquire lock
3274 AutoMutex _l(mLock);
3275
3276 if (mFocusedDisplayId != displayId) {
3277 sp<InputWindowHandle> oldFocusedWindowHandle =
3278 getValueByKey(mFocusedWindowHandlesByDisplay, mFocusedDisplayId);
3279 if (oldFocusedWindowHandle != nullptr) {
Robert Carr5c8a0262018-10-03 16:30:44 -07003280 sp<InputChannel> inputChannel =
3281 getInputChannelLocked(oldFocusedWindowHandle->getToken());
Tiger Huang721e26f2018-07-24 22:26:19 +08003282 if (inputChannel != nullptr) {
3283 CancelationOptions options(
3284 CancelationOptions::CANCEL_DISPLAY_UNSPECIFIED_EVENTS,
3285 "The display which contains this window no longer has focus.");
3286 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
3287 }
3288 }
3289 mFocusedDisplayId = displayId;
3290
3291 // Sanity check
3292 sp<InputWindowHandle> newFocusedWindowHandle =
3293 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
chaviw0c06c6e2019-01-09 13:27:07 -08003294 onFocusChangedLocked(oldFocusedWindowHandle, newFocusedWindowHandle);
Robert Carrf759f162018-11-13 12:57:11 -08003295
Tiger Huang721e26f2018-07-24 22:26:19 +08003296 if (newFocusedWindowHandle == nullptr) {
3297 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
3298 if (!mFocusedWindowHandlesByDisplay.empty()) {
3299 ALOGE("But another display has a focused window:");
3300 for (auto& it : mFocusedWindowHandlesByDisplay) {
3301 const int32_t displayId = it.first;
3302 const sp<InputWindowHandle>& windowHandle = it.second;
3303 ALOGE("Display #%" PRId32 " has focused window: '%s'\n",
3304 displayId, windowHandle->getName().c_str());
3305 }
3306 }
3307 }
3308 }
3309
3310#if DEBUG_FOCUS
3311 logDispatchStateLocked();
3312#endif
3313 } // release lock
3314
3315 // Wake up poll loop since it may need to make new input dispatching choices.
3316 mLooper->wake();
3317}
3318
Michael Wrightd02c5b62014-02-10 15:10:22 -08003319void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
3320#if DEBUG_FOCUS
3321 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
3322#endif
3323
3324 bool changed;
3325 { // acquire lock
3326 AutoMutex _l(mLock);
3327
3328 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
3329 if (mDispatchFrozen && !frozen) {
3330 resetANRTimeoutsLocked();
3331 }
3332
3333 if (mDispatchEnabled && !enabled) {
3334 resetAndDropEverythingLocked("dispatcher is being disabled");
3335 }
3336
3337 mDispatchEnabled = enabled;
3338 mDispatchFrozen = frozen;
3339 changed = true;
3340 } else {
3341 changed = false;
3342 }
3343
3344#if DEBUG_FOCUS
Tiger Huang721e26f2018-07-24 22:26:19 +08003345 logDispatchStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003346#endif
3347 } // release lock
3348
3349 if (changed) {
3350 // Wake up poll loop since it may need to make new input dispatching choices.
3351 mLooper->wake();
3352 }
3353}
3354
3355void InputDispatcher::setInputFilterEnabled(bool enabled) {
3356#if DEBUG_FOCUS
3357 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
3358#endif
3359
3360 { // acquire lock
3361 AutoMutex _l(mLock);
3362
3363 if (mInputFilterEnabled == enabled) {
3364 return;
3365 }
3366
3367 mInputFilterEnabled = enabled;
3368 resetAndDropEverythingLocked("input filter is being enabled or disabled");
3369 } // release lock
3370
3371 // Wake up poll loop since there might be work to do to drop everything.
3372 mLooper->wake();
3373}
3374
chaviwfbe5d9c2018-12-26 12:23:37 -08003375bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken) {
3376 if (fromToken == toToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003377#if DEBUG_FOCUS
chaviwfbe5d9c2018-12-26 12:23:37 -08003378 ALOGD("Trivial transfer to same window.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003379#endif
chaviwfbe5d9c2018-12-26 12:23:37 -08003380 return true;
3381 }
3382
Michael Wrightd02c5b62014-02-10 15:10:22 -08003383 { // acquire lock
3384 AutoMutex _l(mLock);
3385
chaviwfbe5d9c2018-12-26 12:23:37 -08003386 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromToken);
3387 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toToken);
Yi Kong9b14ac62018-07-17 13:48:38 -07003388 if (fromWindowHandle == nullptr || toWindowHandle == nullptr) {
chaviwfbe5d9c2018-12-26 12:23:37 -08003389 ALOGW("Cannot transfer focus because from or to window not found.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003390 return false;
3391 }
chaviw4f2dd402018-12-26 15:30:27 -08003392#if DEBUG_FOCUS
3393 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
3394 fromWindowHandle->getName().c_str(), toWindowHandle->getName().c_str());
3395#endif
Michael Wrightd02c5b62014-02-10 15:10:22 -08003396 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
3397#if DEBUG_FOCUS
3398 ALOGD("Cannot transfer focus because windows are on different displays.");
3399#endif
3400 return false;
3401 }
3402
3403 bool found = false;
Jeff Brownf086ddb2014-02-11 14:28:48 -08003404 for (size_t d = 0; d < mTouchStatesByDisplay.size(); d++) {
3405 TouchState& state = mTouchStatesByDisplay.editValueAt(d);
3406 for (size_t i = 0; i < state.windows.size(); i++) {
3407 const TouchedWindow& touchedWindow = state.windows[i];
3408 if (touchedWindow.windowHandle == fromWindowHandle) {
3409 int32_t oldTargetFlags = touchedWindow.targetFlags;
3410 BitSet32 pointerIds = touchedWindow.pointerIds;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003411
Jeff Brownf086ddb2014-02-11 14:28:48 -08003412 state.windows.removeAt(i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003413
Jeff Brownf086ddb2014-02-11 14:28:48 -08003414 int32_t newTargetFlags = oldTargetFlags
3415 & (InputTarget::FLAG_FOREGROUND
3416 | InputTarget::FLAG_SPLIT | InputTarget::FLAG_DISPATCH_AS_IS);
3417 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003418
Jeff Brownf086ddb2014-02-11 14:28:48 -08003419 found = true;
3420 goto Found;
3421 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003422 }
3423 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08003424Found:
Michael Wrightd02c5b62014-02-10 15:10:22 -08003425
3426 if (! found) {
3427#if DEBUG_FOCUS
3428 ALOGD("Focus transfer failed because from window did not have focus.");
3429#endif
3430 return false;
3431 }
3432
chaviwfbe5d9c2018-12-26 12:23:37 -08003433
3434 sp<InputChannel> fromChannel = getInputChannelLocked(fromToken);
3435 sp<InputChannel> toChannel = getInputChannelLocked(toToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003436 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
chaviw0c06c6e2019-01-09 13:27:07 -08003856void InputDispatcher::onFocusChangedLocked(const sp<InputWindowHandle>& oldFocus,
3857 const sp<InputWindowHandle>& newFocus) {
3858 sp<IBinder> oldToken = oldFocus != nullptr ? oldFocus->getToken() : nullptr;
3859 sp<IBinder> newToken = newFocus != nullptr ? newFocus->getToken() : nullptr;
Robert Carrf759f162018-11-13 12:57:11 -08003860 CommandEntry* commandEntry = postCommandLocked(
3861 & InputDispatcher::doNotifyFocusChangedLockedInterruptible);
chaviw0c06c6e2019-01-09 13:27:07 -08003862 commandEntry->oldToken = oldToken;
3863 commandEntry->newToken = newToken;
Robert Carrf759f162018-11-13 12:57:11 -08003864}
3865
Michael Wrightd02c5b62014-02-10 15:10:22 -08003866void InputDispatcher::onANRLocked(
3867 nsecs_t currentTime, const sp<InputApplicationHandle>& applicationHandle,
3868 const sp<InputWindowHandle>& windowHandle,
3869 nsecs_t eventTime, nsecs_t waitStartTime, const char* reason) {
3870 float dispatchLatency = (currentTime - eventTime) * 0.000001f;
3871 float waitDuration = (currentTime - waitStartTime) * 0.000001f;
3872 ALOGI("Application is not responding: %s. "
3873 "It has been %0.1fms since event, %0.1fms since wait started. Reason: %s",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003874 getApplicationWindowLabelLocked(applicationHandle, windowHandle).c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08003875 dispatchLatency, waitDuration, reason);
3876
3877 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07003878 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003879 struct tm tm;
3880 localtime_r(&t, &tm);
3881 char timestr[64];
3882 strftime(timestr, sizeof(timestr), "%F %T", &tm);
3883 mLastANRState.clear();
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003884 mLastANRState += INDENT "ANR:\n";
3885 mLastANRState += StringPrintf(INDENT2 "Time: %s\n", timestr);
3886 mLastANRState += StringPrintf(INDENT2 "Window: %s\n",
3887 getApplicationWindowLabelLocked(applicationHandle, windowHandle).c_str());
3888 mLastANRState += StringPrintf(INDENT2 "DispatchLatency: %0.1fms\n", dispatchLatency);
3889 mLastANRState += StringPrintf(INDENT2 "WaitDuration: %0.1fms\n", waitDuration);
3890 mLastANRState += StringPrintf(INDENT2 "Reason: %s\n", reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003891 dumpDispatchStateLocked(mLastANRState);
3892
3893 CommandEntry* commandEntry = postCommandLocked(
3894 & InputDispatcher::doNotifyANRLockedInterruptible);
3895 commandEntry->inputApplicationHandle = applicationHandle;
Robert Carr5c8a0262018-10-03 16:30:44 -07003896 commandEntry->inputChannel = windowHandle != nullptr ?
3897 getInputChannelLocked(windowHandle->getToken()) : nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003898 commandEntry->reason = reason;
3899}
3900
3901void InputDispatcher::doNotifyConfigurationChangedInterruptible(
3902 CommandEntry* commandEntry) {
3903 mLock.unlock();
3904
3905 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
3906
3907 mLock.lock();
3908}
3909
3910void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(
3911 CommandEntry* commandEntry) {
3912 sp<Connection> connection = commandEntry->connection;
3913
3914 if (connection->status != Connection::STATUS_ZOMBIE) {
3915 mLock.unlock();
3916
Robert Carr803535b2018-08-02 16:38:15 -07003917 mPolicy->notifyInputChannelBroken(connection->inputChannel->getToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003918
3919 mLock.lock();
3920 }
3921}
3922
Robert Carrf759f162018-11-13 12:57:11 -08003923void InputDispatcher::doNotifyFocusChangedLockedInterruptible(
3924 CommandEntry* commandEntry) {
chaviw0c06c6e2019-01-09 13:27:07 -08003925 sp<IBinder> oldToken = commandEntry->oldToken;
3926 sp<IBinder> newToken = commandEntry->newToken;
Robert Carrf759f162018-11-13 12:57:11 -08003927 mLock.unlock();
chaviw0c06c6e2019-01-09 13:27:07 -08003928 mPolicy->notifyFocusChanged(oldToken, newToken);
Robert Carrf759f162018-11-13 12:57:11 -08003929 mLock.lock();
3930}
3931
Michael Wrightd02c5b62014-02-10 15:10:22 -08003932void InputDispatcher::doNotifyANRLockedInterruptible(
3933 CommandEntry* commandEntry) {
3934 mLock.unlock();
3935
3936 nsecs_t newTimeout = mPolicy->notifyANR(
Robert Carr803535b2018-08-02 16:38:15 -07003937 commandEntry->inputApplicationHandle,
3938 commandEntry->inputChannel ? commandEntry->inputChannel->getToken() : nullptr,
Michael Wrightd02c5b62014-02-10 15:10:22 -08003939 commandEntry->reason);
3940
3941 mLock.lock();
3942
3943 resumeAfterTargetsNotReadyTimeoutLocked(newTimeout,
Robert Carr803535b2018-08-02 16:38:15 -07003944 commandEntry->inputChannel);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003945}
3946
3947void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
3948 CommandEntry* commandEntry) {
3949 KeyEntry* entry = commandEntry->keyEntry;
3950
3951 KeyEvent event;
3952 initializeKeyEvent(&event, entry);
3953
3954 mLock.unlock();
3955
Michael Wright2b3c3302018-03-02 17:19:13 +00003956 android::base::Timer t;
Robert Carr803535b2018-08-02 16:38:15 -07003957 sp<IBinder> token = commandEntry->inputChannel != nullptr ?
3958 commandEntry->inputChannel->getToken() : nullptr;
3959 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(token,
Michael Wrightd02c5b62014-02-10 15:10:22 -08003960 &event, entry->policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003961 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3962 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
3963 std::to_string(t.duration().count()).c_str());
3964 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003965
3966 mLock.lock();
3967
3968 if (delay < 0) {
3969 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
3970 } else if (!delay) {
3971 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
3972 } else {
3973 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
3974 entry->interceptKeyWakeupTime = now() + delay;
3975 }
3976 entry->release();
3977}
3978
3979void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(
3980 CommandEntry* commandEntry) {
3981 sp<Connection> connection = commandEntry->connection;
3982 nsecs_t finishTime = commandEntry->eventTime;
3983 uint32_t seq = commandEntry->seq;
3984 bool handled = commandEntry->handled;
3985
3986 // Handle post-event policy actions.
3987 DispatchEntry* dispatchEntry = connection->findWaitQueueEntry(seq);
3988 if (dispatchEntry) {
3989 nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
3990 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003991 std::string msg =
3992 StringPrintf("Window '%s' spent %0.1fms processing the last input event: ",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08003993 connection->getWindowName().c_str(), eventDuration * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003994 dispatchEntry->eventEntry->appendDescription(msg);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003995 ALOGI("%s", msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003996 }
3997
3998 bool restartEvent;
3999 if (dispatchEntry->eventEntry->type == EventEntry::TYPE_KEY) {
4000 KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry);
4001 restartEvent = afterKeyEventLockedInterruptible(connection,
4002 dispatchEntry, keyEntry, handled);
4003 } else if (dispatchEntry->eventEntry->type == EventEntry::TYPE_MOTION) {
4004 MotionEntry* motionEntry = static_cast<MotionEntry*>(dispatchEntry->eventEntry);
4005 restartEvent = afterMotionEventLockedInterruptible(connection,
4006 dispatchEntry, motionEntry, handled);
4007 } else {
4008 restartEvent = false;
4009 }
4010
4011 // Dequeue the event and start the next cycle.
4012 // Note that because the lock might have been released, it is possible that the
4013 // contents of the wait queue to have been drained, so we need to double-check
4014 // a few things.
4015 if (dispatchEntry == connection->findWaitQueueEntry(seq)) {
4016 connection->waitQueue.dequeue(dispatchEntry);
4017 traceWaitQueueLengthLocked(connection);
4018 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
4019 connection->outboundQueue.enqueueAtHead(dispatchEntry);
4020 traceOutboundQueueLengthLocked(connection);
4021 } else {
4022 releaseDispatchEntryLocked(dispatchEntry);
4023 }
4024 }
4025
4026 // Start the next dispatch cycle for this connection.
4027 startDispatchCycleLocked(now(), connection);
4028 }
4029}
4030
4031bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
4032 DispatchEntry* dispatchEntry, KeyEntry* keyEntry, bool handled) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004033 if (keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004034 if (!handled) {
4035 // Report the key as unhandled, since the fallback was not handled.
4036 mReporter->reportUnhandledKey(keyEntry->sequenceNum);
4037 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004038 return false;
4039 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004040
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004041 // Get the fallback key state.
4042 // Clear it out after dispatching the UP.
4043 int32_t originalKeyCode = keyEntry->keyCode;
4044 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
4045 if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
4046 connection->inputState.removeFallbackKey(originalKeyCode);
4047 }
4048
4049 if (handled || !dispatchEntry->hasForegroundTarget()) {
4050 // If the application handles the original key for which we previously
4051 // generated a fallback or if the window is not a foreground window,
4052 // then cancel the associated fallback key, if any.
4053 if (fallbackKeyCode != -1) {
4054 // Dispatch the unhandled key to the policy with the cancel flag.
Michael Wrightd02c5b62014-02-10 15:10:22 -08004055#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004056 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
Michael Wrightd02c5b62014-02-10 15:10:22 -08004057 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4058 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
4059 keyEntry->policyFlags);
4060#endif
4061 KeyEvent event;
4062 initializeKeyEvent(&event, keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004063 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004064
4065 mLock.unlock();
4066
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004067 mPolicy->dispatchUnhandledKey(connection->inputChannel->getToken(),
4068 &event, keyEntry->policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004069
4070 mLock.lock();
4071
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004072 // Cancel the fallback key.
4073 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004074 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004075 "application handled the original non-fallback key "
4076 "or is no longer a foreground target, "
4077 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004078 options.keyCode = fallbackKeyCode;
4079 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004080 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004081 connection->inputState.removeFallbackKey(originalKeyCode);
4082 }
4083 } else {
4084 // If the application did not handle a non-fallback key, first check
4085 // that we are in a good state to perform unhandled key event processing
4086 // Then ask the policy what to do with it.
4087 bool initialDown = keyEntry->action == AKEY_EVENT_ACTION_DOWN
4088 && keyEntry->repeatCount == 0;
4089 if (fallbackKeyCode == -1 && !initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004090#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004091 ALOGD("Unhandled key event: Skipping unhandled key event processing "
4092 "since this is not an initial down. "
4093 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4094 originalKeyCode, keyEntry->action, keyEntry->repeatCount,
4095 keyEntry->policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004096#endif
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004097 return false;
4098 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004099
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004100 // Dispatch the unhandled key to the policy.
4101#if DEBUG_OUTBOUND_EVENT_DETAILS
4102 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
4103 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4104 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
4105 keyEntry->policyFlags);
4106#endif
4107 KeyEvent event;
4108 initializeKeyEvent(&event, keyEntry);
4109
4110 mLock.unlock();
4111
4112 bool fallback = mPolicy->dispatchUnhandledKey(connection->inputChannel->getToken(),
4113 &event, keyEntry->policyFlags, &event);
4114
4115 mLock.lock();
4116
4117 if (connection->status != Connection::STATUS_NORMAL) {
4118 connection->inputState.removeFallbackKey(originalKeyCode);
4119 return false;
4120 }
4121
4122 // Latch the fallback keycode for this key on an initial down.
4123 // The fallback keycode cannot change at any other point in the lifecycle.
4124 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004125 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004126 fallbackKeyCode = event.getKeyCode();
4127 } else {
4128 fallbackKeyCode = AKEYCODE_UNKNOWN;
4129 }
4130 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
4131 }
4132
4133 ALOG_ASSERT(fallbackKeyCode != -1);
4134
4135 // Cancel the fallback key if the policy decides not to send it anymore.
4136 // We will continue to dispatch the key to the policy but we will no
4137 // longer dispatch a fallback key to the application.
4138 if (fallbackKeyCode != AKEYCODE_UNKNOWN
4139 && (!fallback || fallbackKeyCode != event.getKeyCode())) {
4140#if DEBUG_OUTBOUND_EVENT_DETAILS
4141 if (fallback) {
4142 ALOGD("Unhandled key event: Policy requested to send key %d"
4143 "as a fallback for %d, but on the DOWN it had requested "
4144 "to send %d instead. Fallback canceled.",
4145 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
4146 } else {
4147 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
4148 "but on the DOWN it had requested to send %d. "
4149 "Fallback canceled.",
4150 originalKeyCode, fallbackKeyCode);
4151 }
4152#endif
4153
4154 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
4155 "canceling fallback, policy no longer desires it");
4156 options.keyCode = fallbackKeyCode;
4157 synthesizeCancelationEventsForConnectionLocked(connection, options);
4158
4159 fallback = false;
4160 fallbackKeyCode = AKEYCODE_UNKNOWN;
4161 if (keyEntry->action != AKEY_EVENT_ACTION_UP) {
4162 connection->inputState.setFallbackKey(originalKeyCode,
4163 fallbackKeyCode);
4164 }
4165 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004166
4167#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004168 {
4169 std::string msg;
4170 const KeyedVector<int32_t, int32_t>& fallbackKeys =
4171 connection->inputState.getFallbackKeys();
4172 for (size_t i = 0; i < fallbackKeys.size(); i++) {
4173 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i),
4174 fallbackKeys.valueAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004175 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004176 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
4177 fallbackKeys.size(), msg.c_str());
4178 }
4179#endif
4180
4181 if (fallback) {
4182 // Restart the dispatch cycle using the fallback key.
4183 keyEntry->eventTime = event.getEventTime();
4184 keyEntry->deviceId = event.getDeviceId();
4185 keyEntry->source = event.getSource();
4186 keyEntry->displayId = event.getDisplayId();
4187 keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
4188 keyEntry->keyCode = fallbackKeyCode;
4189 keyEntry->scanCode = event.getScanCode();
4190 keyEntry->metaState = event.getMetaState();
4191 keyEntry->repeatCount = event.getRepeatCount();
4192 keyEntry->downTime = event.getDownTime();
4193 keyEntry->syntheticRepeat = false;
4194
4195#if DEBUG_OUTBOUND_EVENT_DETAILS
4196 ALOGD("Unhandled key event: Dispatching fallback key. "
4197 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
4198 originalKeyCode, fallbackKeyCode, keyEntry->metaState);
4199#endif
4200 return true; // restart the event
4201 } else {
4202#if DEBUG_OUTBOUND_EVENT_DETAILS
4203 ALOGD("Unhandled key event: No fallback key.");
4204#endif
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004205
4206 // Report the key as unhandled, since there is no fallback key.
4207 mReporter->reportUnhandledKey(keyEntry->sequenceNum);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004208 }
4209 }
4210 return false;
4211}
4212
4213bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
4214 DispatchEntry* dispatchEntry, MotionEntry* motionEntry, bool handled) {
4215 return false;
4216}
4217
4218void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
4219 mLock.unlock();
4220
4221 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
4222
4223 mLock.lock();
4224}
4225
4226void InputDispatcher::initializeKeyEvent(KeyEvent* event, const KeyEntry* entry) {
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004227 event->initialize(entry->deviceId, entry->source, entry->displayId, entry->action, entry->flags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004228 entry->keyCode, entry->scanCode, entry->metaState, entry->repeatCount,
4229 entry->downTime, entry->eventTime);
4230}
4231
4232void InputDispatcher::updateDispatchStatisticsLocked(nsecs_t currentTime, const EventEntry* entry,
4233 int32_t injectionResult, nsecs_t timeSpentWaitingForApplication) {
4234 // TODO Write some statistics about how long we spend waiting.
4235}
4236
4237void InputDispatcher::traceInboundQueueLengthLocked() {
4238 if (ATRACE_ENABLED()) {
4239 ATRACE_INT("iq", mInboundQueue.count());
4240 }
4241}
4242
4243void InputDispatcher::traceOutboundQueueLengthLocked(const sp<Connection>& connection) {
4244 if (ATRACE_ENABLED()) {
4245 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004246 snprintf(counterName, sizeof(counterName), "oq:%s", connection->getWindowName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004247 ATRACE_INT(counterName, connection->outboundQueue.count());
4248 }
4249}
4250
4251void InputDispatcher::traceWaitQueueLengthLocked(const sp<Connection>& connection) {
4252 if (ATRACE_ENABLED()) {
4253 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004254 snprintf(counterName, sizeof(counterName), "wq:%s", connection->getWindowName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004255 ATRACE_INT(counterName, connection->waitQueue.count());
4256 }
4257}
4258
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004259void InputDispatcher::dump(std::string& dump) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004260 AutoMutex _l(mLock);
4261
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004262 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004263 dumpDispatchStateLocked(dump);
4264
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004265 if (!mLastANRState.empty()) {
4266 dump += "\nInput Dispatcher State at time of last ANR:\n";
4267 dump += mLastANRState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004268 }
4269}
4270
4271void InputDispatcher::monitor() {
4272 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
4273 mLock.lock();
4274 mLooper->wake();
4275 mDispatcherIsAliveCondition.wait(mLock);
4276 mLock.unlock();
4277}
4278
4279
Michael Wrightd02c5b62014-02-10 15:10:22 -08004280// --- InputDispatcher::InjectionState ---
4281
4282InputDispatcher::InjectionState::InjectionState(int32_t injectorPid, int32_t injectorUid) :
4283 refCount(1),
4284 injectorPid(injectorPid), injectorUid(injectorUid),
4285 injectionResult(INPUT_EVENT_INJECTION_PENDING), injectionIsAsync(false),
4286 pendingForegroundDispatches(0) {
4287}
4288
4289InputDispatcher::InjectionState::~InjectionState() {
4290}
4291
4292void InputDispatcher::InjectionState::release() {
4293 refCount -= 1;
4294 if (refCount == 0) {
4295 delete this;
4296 } else {
4297 ALOG_ASSERT(refCount > 0);
4298 }
4299}
4300
4301
4302// --- InputDispatcher::EventEntry ---
4303
Prabir Pradhan42611e02018-11-27 14:04:02 -08004304InputDispatcher::EventEntry::EventEntry(uint32_t sequenceNum, int32_t type,
4305 nsecs_t eventTime, uint32_t policyFlags) :
4306 sequenceNum(sequenceNum), refCount(1), type(type), eventTime(eventTime),
4307 policyFlags(policyFlags), injectionState(nullptr), dispatchInProgress(false) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004308}
4309
4310InputDispatcher::EventEntry::~EventEntry() {
4311 releaseInjectionState();
4312}
4313
4314void InputDispatcher::EventEntry::release() {
4315 refCount -= 1;
4316 if (refCount == 0) {
4317 delete this;
4318 } else {
4319 ALOG_ASSERT(refCount > 0);
4320 }
4321}
4322
4323void InputDispatcher::EventEntry::releaseInjectionState() {
4324 if (injectionState) {
4325 injectionState->release();
Yi Kong9b14ac62018-07-17 13:48:38 -07004326 injectionState = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004327 }
4328}
4329
4330
4331// --- InputDispatcher::ConfigurationChangedEntry ---
4332
Prabir Pradhan42611e02018-11-27 14:04:02 -08004333InputDispatcher::ConfigurationChangedEntry::ConfigurationChangedEntry(
4334 uint32_t sequenceNum, nsecs_t eventTime) :
4335 EventEntry(sequenceNum, TYPE_CONFIGURATION_CHANGED, eventTime, 0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004336}
4337
4338InputDispatcher::ConfigurationChangedEntry::~ConfigurationChangedEntry() {
4339}
4340
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004341void InputDispatcher::ConfigurationChangedEntry::appendDescription(std::string& msg) const {
4342 msg += StringPrintf("ConfigurationChangedEvent(), policyFlags=0x%08x", policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004343}
4344
4345
4346// --- InputDispatcher::DeviceResetEntry ---
4347
Prabir Pradhan42611e02018-11-27 14:04:02 -08004348InputDispatcher::DeviceResetEntry::DeviceResetEntry(
4349 uint32_t sequenceNum, nsecs_t eventTime, int32_t deviceId) :
4350 EventEntry(sequenceNum, TYPE_DEVICE_RESET, eventTime, 0),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004351 deviceId(deviceId) {
4352}
4353
4354InputDispatcher::DeviceResetEntry::~DeviceResetEntry() {
4355}
4356
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004357void InputDispatcher::DeviceResetEntry::appendDescription(std::string& msg) const {
4358 msg += StringPrintf("DeviceResetEvent(deviceId=%d), policyFlags=0x%08x",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004359 deviceId, policyFlags);
4360}
4361
4362
4363// --- InputDispatcher::KeyEntry ---
4364
Prabir Pradhan42611e02018-11-27 14:04:02 -08004365InputDispatcher::KeyEntry::KeyEntry(uint32_t sequenceNum, nsecs_t eventTime,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004366 int32_t deviceId, uint32_t source, int32_t displayId, uint32_t policyFlags, int32_t action,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004367 int32_t flags, int32_t keyCode, int32_t scanCode, int32_t metaState,
4368 int32_t repeatCount, nsecs_t downTime) :
Prabir Pradhan42611e02018-11-27 14:04:02 -08004369 EventEntry(sequenceNum, TYPE_KEY, eventTime, policyFlags),
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004370 deviceId(deviceId), source(source), displayId(displayId), action(action), flags(flags),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004371 keyCode(keyCode), scanCode(scanCode), metaState(metaState),
4372 repeatCount(repeatCount), downTime(downTime),
4373 syntheticRepeat(false), interceptKeyResult(KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN),
4374 interceptKeyWakeupTime(0) {
4375}
4376
4377InputDispatcher::KeyEntry::~KeyEntry() {
4378}
4379
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004380void InputDispatcher::KeyEntry::appendDescription(std::string& msg) const {
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004381 msg += StringPrintf("KeyEvent(deviceId=%d, source=0x%08x, displayId=%" PRId32 ", action=%s, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08004382 "flags=0x%08x, keyCode=%d, scanCode=%d, metaState=0x%08x, "
4383 "repeatCount=%d), policyFlags=0x%08x",
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004384 deviceId, source, displayId, keyActionToString(action).c_str(), flags, keyCode,
Siarhei Vishniakoub48188a2018-03-01 20:55:47 -08004385 scanCode, metaState, repeatCount, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004386}
4387
4388void InputDispatcher::KeyEntry::recycle() {
4389 releaseInjectionState();
4390
4391 dispatchInProgress = false;
4392 syntheticRepeat = false;
4393 interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
4394 interceptKeyWakeupTime = 0;
4395}
4396
4397
4398// --- InputDispatcher::MotionEntry ---
4399
Prabir Pradhan42611e02018-11-27 14:04:02 -08004400InputDispatcher::MotionEntry::MotionEntry(uint32_t sequenceNum, nsecs_t eventTime, int32_t deviceId,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004401 uint32_t source, int32_t displayId, uint32_t policyFlags, int32_t action,
4402 int32_t actionButton,
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08004403 int32_t flags, int32_t metaState, int32_t buttonState, MotionClassification classification,
4404 int32_t edgeFlags, float xPrecision, float yPrecision, nsecs_t downTime,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004405 uint32_t pointerCount,
Jeff Brownf086ddb2014-02-11 14:28:48 -08004406 const PointerProperties* pointerProperties, const PointerCoords* pointerCoords,
4407 float xOffset, float yOffset) :
Prabir Pradhan42611e02018-11-27 14:04:02 -08004408 EventEntry(sequenceNum, TYPE_MOTION, eventTime, policyFlags),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004409 eventTime(eventTime),
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004410 deviceId(deviceId), source(source), displayId(displayId), action(action),
4411 actionButton(actionButton), flags(flags), metaState(metaState), buttonState(buttonState),
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08004412 classification(classification), edgeFlags(edgeFlags),
4413 xPrecision(xPrecision), yPrecision(yPrecision),
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004414 downTime(downTime), pointerCount(pointerCount) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004415 for (uint32_t i = 0; i < pointerCount; i++) {
4416 this->pointerProperties[i].copyFrom(pointerProperties[i]);
4417 this->pointerCoords[i].copyFrom(pointerCoords[i]);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004418 if (xOffset || yOffset) {
4419 this->pointerCoords[i].applyOffset(xOffset, yOffset);
4420 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004421 }
4422}
4423
4424InputDispatcher::MotionEntry::~MotionEntry() {
4425}
4426
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004427void InputDispatcher::MotionEntry::appendDescription(std::string& msg) const {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004428 msg += StringPrintf("MotionEvent(deviceId=%d, source=0x%08x, displayId=%" PRId32
Siarhei Vishniakoub48188a2018-03-01 20:55:47 -08004429 ", action=%s, actionButton=0x%08x, flags=0x%08x, metaState=0x%08x, buttonState=0x%08x, "
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08004430 "classification=%s, edgeFlags=0x%08x, xPrecision=%.1f, yPrecision=%.1f, pointers=[",
Siarhei Vishniakoub48188a2018-03-01 20:55:47 -08004431 deviceId, source, displayId, motionActionToString(action).c_str(), actionButton, flags,
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08004432 metaState, buttonState, motionClassificationToString(classification), edgeFlags,
4433 xPrecision, yPrecision);
Siarhei Vishniakoub48188a2018-03-01 20:55:47 -08004434
Michael Wrightd02c5b62014-02-10 15:10:22 -08004435 for (uint32_t i = 0; i < pointerCount; i++) {
4436 if (i) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004437 msg += ", ";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004438 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004439 msg += StringPrintf("%d: (%.1f, %.1f)", pointerProperties[i].id,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004440 pointerCoords[i].getX(), pointerCoords[i].getY());
4441 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004442 msg += StringPrintf("]), policyFlags=0x%08x", policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004443}
4444
4445
4446// --- InputDispatcher::DispatchEntry ---
4447
4448volatile int32_t InputDispatcher::DispatchEntry::sNextSeqAtomic;
4449
4450InputDispatcher::DispatchEntry::DispatchEntry(EventEntry* eventEntry,
Robert Carre07e1032018-11-26 12:55:53 -08004451 int32_t targetFlags, float xOffset, float yOffset, float globalScaleFactor,
4452 float windowXScale, float windowYScale) :
Michael Wrightd02c5b62014-02-10 15:10:22 -08004453 seq(nextSeq()),
4454 eventEntry(eventEntry), targetFlags(targetFlags),
Robert Carre07e1032018-11-26 12:55:53 -08004455 xOffset(xOffset), yOffset(yOffset), globalScaleFactor(globalScaleFactor),
4456 windowXScale(windowXScale), windowYScale(windowYScale),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004457 deliveryTime(0), resolvedAction(0), resolvedFlags(0) {
4458 eventEntry->refCount += 1;
4459}
4460
4461InputDispatcher::DispatchEntry::~DispatchEntry() {
4462 eventEntry->release();
4463}
4464
4465uint32_t InputDispatcher::DispatchEntry::nextSeq() {
4466 // Sequence number 0 is reserved and will never be returned.
4467 uint32_t seq;
4468 do {
4469 seq = android_atomic_inc(&sNextSeqAtomic);
4470 } while (!seq);
4471 return seq;
4472}
4473
4474
4475// --- InputDispatcher::InputState ---
4476
4477InputDispatcher::InputState::InputState() {
4478}
4479
4480InputDispatcher::InputState::~InputState() {
4481}
4482
4483bool InputDispatcher::InputState::isNeutral() const {
4484 return mKeyMementos.isEmpty() && mMotionMementos.isEmpty();
4485}
4486
4487bool InputDispatcher::InputState::isHovering(int32_t deviceId, uint32_t source,
4488 int32_t displayId) const {
4489 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4490 const MotionMemento& memento = mMotionMementos.itemAt(i);
4491 if (memento.deviceId == deviceId
4492 && memento.source == source
4493 && memento.displayId == displayId
4494 && memento.hovering) {
4495 return true;
4496 }
4497 }
4498 return false;
4499}
4500
4501bool InputDispatcher::InputState::trackKey(const KeyEntry* entry,
4502 int32_t action, int32_t flags) {
4503 switch (action) {
4504 case AKEY_EVENT_ACTION_UP: {
4505 if (entry->flags & AKEY_EVENT_FLAG_FALLBACK) {
4506 for (size_t i = 0; i < mFallbackKeys.size(); ) {
4507 if (mFallbackKeys.valueAt(i) == entry->keyCode) {
4508 mFallbackKeys.removeItemsAt(i);
4509 } else {
4510 i += 1;
4511 }
4512 }
4513 }
4514 ssize_t index = findKeyMemento(entry);
4515 if (index >= 0) {
4516 mKeyMementos.removeAt(index);
4517 return true;
4518 }
4519 /* FIXME: We can't just drop the key up event because that prevents creating
4520 * popup windows that are automatically shown when a key is held and then
4521 * dismissed when the key is released. The problem is that the popup will
4522 * not have received the original key down, so the key up will be considered
4523 * to be inconsistent with its observed state. We could perhaps handle this
4524 * by synthesizing a key down but that will cause other problems.
4525 *
4526 * So for now, allow inconsistent key up events to be dispatched.
4527 *
4528#if DEBUG_OUTBOUND_EVENT_DETAILS
4529 ALOGD("Dropping inconsistent key up event: deviceId=%d, source=%08x, "
4530 "keyCode=%d, scanCode=%d",
4531 entry->deviceId, entry->source, entry->keyCode, entry->scanCode);
4532#endif
4533 return false;
4534 */
4535 return true;
4536 }
4537
4538 case AKEY_EVENT_ACTION_DOWN: {
4539 ssize_t index = findKeyMemento(entry);
4540 if (index >= 0) {
4541 mKeyMementos.removeAt(index);
4542 }
4543 addKeyMemento(entry, flags);
4544 return true;
4545 }
4546
4547 default:
4548 return true;
4549 }
4550}
4551
4552bool InputDispatcher::InputState::trackMotion(const MotionEntry* entry,
4553 int32_t action, int32_t flags) {
4554 int32_t actionMasked = action & AMOTION_EVENT_ACTION_MASK;
4555 switch (actionMasked) {
4556 case AMOTION_EVENT_ACTION_UP:
4557 case AMOTION_EVENT_ACTION_CANCEL: {
4558 ssize_t index = findMotionMemento(entry, false /*hovering*/);
4559 if (index >= 0) {
4560 mMotionMementos.removeAt(index);
4561 return true;
4562 }
4563#if DEBUG_OUTBOUND_EVENT_DETAILS
4564 ALOGD("Dropping inconsistent motion up or cancel event: deviceId=%d, source=%08x, "
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004565 "displayId=%" PRId32 ", actionMasked=%d",
4566 entry->deviceId, entry->source, entry->displayId, actionMasked);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004567#endif
4568 return false;
4569 }
4570
4571 case AMOTION_EVENT_ACTION_DOWN: {
4572 ssize_t index = findMotionMemento(entry, false /*hovering*/);
4573 if (index >= 0) {
4574 mMotionMementos.removeAt(index);
4575 }
4576 addMotionMemento(entry, flags, false /*hovering*/);
4577 return true;
4578 }
4579
4580 case AMOTION_EVENT_ACTION_POINTER_UP:
4581 case AMOTION_EVENT_ACTION_POINTER_DOWN:
4582 case AMOTION_EVENT_ACTION_MOVE: {
Michael Wright38dcdff2014-03-19 12:06:10 -07004583 if (entry->source & AINPUT_SOURCE_CLASS_NAVIGATION) {
4584 // Trackballs can send MOVE events with a corresponding DOWN or UP. There's no need to
4585 // generate cancellation events for these since they're based in relative rather than
4586 // absolute units.
4587 return true;
4588 }
4589
Michael Wrightd02c5b62014-02-10 15:10:22 -08004590 ssize_t index = findMotionMemento(entry, false /*hovering*/);
Michael Wright38dcdff2014-03-19 12:06:10 -07004591
4592 if (entry->source & AINPUT_SOURCE_CLASS_JOYSTICK) {
4593 // Joysticks can send MOVE events without a corresponding DOWN or UP. Since all
4594 // joystick axes are normalized to [-1, 1] we can trust that 0 means it's neutral. Any
4595 // other value and we need to track the motion so we can send cancellation events for
4596 // anything generating fallback events (e.g. DPad keys for joystick movements).
4597 if (index >= 0) {
4598 if (entry->pointerCoords[0].isEmpty()) {
4599 mMotionMementos.removeAt(index);
4600 } else {
4601 MotionMemento& memento = mMotionMementos.editItemAt(index);
4602 memento.setPointers(entry);
4603 }
4604 } else if (!entry->pointerCoords[0].isEmpty()) {
4605 addMotionMemento(entry, flags, false /*hovering*/);
4606 }
4607
4608 // Joysticks and trackballs can send MOVE events without corresponding DOWN or UP.
4609 return true;
4610 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004611 if (index >= 0) {
4612 MotionMemento& memento = mMotionMementos.editItemAt(index);
4613 memento.setPointers(entry);
4614 return true;
4615 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004616#if DEBUG_OUTBOUND_EVENT_DETAILS
4617 ALOGD("Dropping inconsistent motion pointer up/down or move event: "
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004618 "deviceId=%d, source=%08x, displayId=%" PRId32 ", actionMasked=%d",
4619 entry->deviceId, entry->source, entry->displayId, actionMasked);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004620#endif
4621 return false;
4622 }
4623
4624 case AMOTION_EVENT_ACTION_HOVER_EXIT: {
4625 ssize_t index = findMotionMemento(entry, true /*hovering*/);
4626 if (index >= 0) {
4627 mMotionMementos.removeAt(index);
4628 return true;
4629 }
4630#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004631 ALOGD("Dropping inconsistent motion hover exit event: deviceId=%d, source=%08x, "
4632 "displayId=%" PRId32,
4633 entry->deviceId, entry->source, entry->displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004634#endif
4635 return false;
4636 }
4637
4638 case AMOTION_EVENT_ACTION_HOVER_ENTER:
4639 case AMOTION_EVENT_ACTION_HOVER_MOVE: {
4640 ssize_t index = findMotionMemento(entry, true /*hovering*/);
4641 if (index >= 0) {
4642 mMotionMementos.removeAt(index);
4643 }
4644 addMotionMemento(entry, flags, true /*hovering*/);
4645 return true;
4646 }
4647
4648 default:
4649 return true;
4650 }
4651}
4652
4653ssize_t InputDispatcher::InputState::findKeyMemento(const KeyEntry* entry) const {
4654 for (size_t i = 0; i < mKeyMementos.size(); i++) {
4655 const KeyMemento& memento = mKeyMementos.itemAt(i);
4656 if (memento.deviceId == entry->deviceId
4657 && memento.source == entry->source
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004658 && memento.displayId == entry->displayId
Michael Wrightd02c5b62014-02-10 15:10:22 -08004659 && memento.keyCode == entry->keyCode
4660 && memento.scanCode == entry->scanCode) {
4661 return i;
4662 }
4663 }
4664 return -1;
4665}
4666
4667ssize_t InputDispatcher::InputState::findMotionMemento(const MotionEntry* entry,
4668 bool hovering) const {
4669 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4670 const MotionMemento& memento = mMotionMementos.itemAt(i);
4671 if (memento.deviceId == entry->deviceId
4672 && memento.source == entry->source
4673 && memento.displayId == entry->displayId
4674 && memento.hovering == hovering) {
4675 return i;
4676 }
4677 }
4678 return -1;
4679}
4680
4681void InputDispatcher::InputState::addKeyMemento(const KeyEntry* entry, int32_t flags) {
4682 mKeyMementos.push();
4683 KeyMemento& memento = mKeyMementos.editTop();
4684 memento.deviceId = entry->deviceId;
4685 memento.source = entry->source;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004686 memento.displayId = entry->displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004687 memento.keyCode = entry->keyCode;
4688 memento.scanCode = entry->scanCode;
4689 memento.metaState = entry->metaState;
4690 memento.flags = flags;
4691 memento.downTime = entry->downTime;
4692 memento.policyFlags = entry->policyFlags;
4693}
4694
4695void InputDispatcher::InputState::addMotionMemento(const MotionEntry* entry,
4696 int32_t flags, bool hovering) {
4697 mMotionMementos.push();
4698 MotionMemento& memento = mMotionMementos.editTop();
4699 memento.deviceId = entry->deviceId;
4700 memento.source = entry->source;
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004701 memento.displayId = entry->displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004702 memento.flags = flags;
4703 memento.xPrecision = entry->xPrecision;
4704 memento.yPrecision = entry->yPrecision;
4705 memento.downTime = entry->downTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004706 memento.setPointers(entry);
4707 memento.hovering = hovering;
4708 memento.policyFlags = entry->policyFlags;
4709}
4710
4711void InputDispatcher::InputState::MotionMemento::setPointers(const MotionEntry* entry) {
4712 pointerCount = entry->pointerCount;
4713 for (uint32_t i = 0; i < entry->pointerCount; i++) {
4714 pointerProperties[i].copyFrom(entry->pointerProperties[i]);
4715 pointerCoords[i].copyFrom(entry->pointerCoords[i]);
4716 }
4717}
4718
4719void InputDispatcher::InputState::synthesizeCancelationEvents(nsecs_t currentTime,
4720 Vector<EventEntry*>& outEvents, const CancelationOptions& options) {
4721 for (size_t i = 0; i < mKeyMementos.size(); i++) {
4722 const KeyMemento& memento = mKeyMementos.itemAt(i);
4723 if (shouldCancelKey(memento, options)) {
Prabir Pradhan42611e02018-11-27 14:04:02 -08004724 outEvents.push(new KeyEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, currentTime,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004725 memento.deviceId, memento.source, memento.displayId, memento.policyFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004726 AKEY_EVENT_ACTION_UP, memento.flags | AKEY_EVENT_FLAG_CANCELED,
4727 memento.keyCode, memento.scanCode, memento.metaState, 0, memento.downTime));
4728 }
4729 }
4730
4731 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4732 const MotionMemento& memento = mMotionMementos.itemAt(i);
4733 if (shouldCancelMotion(memento, options)) {
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08004734 const int32_t action = memento.hovering ?
4735 AMOTION_EVENT_ACTION_HOVER_EXIT : AMOTION_EVENT_ACTION_CANCEL;
Prabir Pradhan42611e02018-11-27 14:04:02 -08004736 outEvents.push(new MotionEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, currentTime,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004737 memento.deviceId, memento.source, memento.displayId, memento.policyFlags,
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08004738 action, 0 /*actionButton*/, memento.flags, AMETA_NONE, 0 /*buttonState*/,
4739 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004740 memento.xPrecision, memento.yPrecision, memento.downTime,
Jeff Brownf086ddb2014-02-11 14:28:48 -08004741 memento.pointerCount, memento.pointerProperties, memento.pointerCoords,
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08004742 0 /*xOffset*/, 0 /*yOffset*/));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004743 }
4744 }
4745}
4746
4747void InputDispatcher::InputState::clear() {
4748 mKeyMementos.clear();
4749 mMotionMementos.clear();
4750 mFallbackKeys.clear();
4751}
4752
4753void InputDispatcher::InputState::copyPointerStateTo(InputState& other) const {
4754 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4755 const MotionMemento& memento = mMotionMementos.itemAt(i);
4756 if (memento.source & AINPUT_SOURCE_CLASS_POINTER) {
4757 for (size_t j = 0; j < other.mMotionMementos.size(); ) {
4758 const MotionMemento& otherMemento = other.mMotionMementos.itemAt(j);
4759 if (memento.deviceId == otherMemento.deviceId
4760 && memento.source == otherMemento.source
4761 && memento.displayId == otherMemento.displayId) {
4762 other.mMotionMementos.removeAt(j);
4763 } else {
4764 j += 1;
4765 }
4766 }
4767 other.mMotionMementos.push(memento);
4768 }
4769 }
4770}
4771
4772int32_t InputDispatcher::InputState::getFallbackKey(int32_t originalKeyCode) {
4773 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
4774 return index >= 0 ? mFallbackKeys.valueAt(index) : -1;
4775}
4776
4777void InputDispatcher::InputState::setFallbackKey(int32_t originalKeyCode,
4778 int32_t fallbackKeyCode) {
4779 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
4780 if (index >= 0) {
4781 mFallbackKeys.replaceValueAt(index, fallbackKeyCode);
4782 } else {
4783 mFallbackKeys.add(originalKeyCode, fallbackKeyCode);
4784 }
4785}
4786
4787void InputDispatcher::InputState::removeFallbackKey(int32_t originalKeyCode) {
4788 mFallbackKeys.removeItem(originalKeyCode);
4789}
4790
4791bool InputDispatcher::InputState::shouldCancelKey(const KeyMemento& memento,
4792 const CancelationOptions& options) {
4793 if (options.keyCode != -1 && memento.keyCode != options.keyCode) {
4794 return false;
4795 }
4796
4797 if (options.deviceId != -1 && memento.deviceId != options.deviceId) {
4798 return false;
4799 }
4800
4801 switch (options.mode) {
4802 case CancelationOptions::CANCEL_ALL_EVENTS:
4803 case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
4804 return true;
4805 case CancelationOptions::CANCEL_FALLBACK_EVENTS:
4806 return memento.flags & AKEY_EVENT_FLAG_FALLBACK;
Tiger Huang721e26f2018-07-24 22:26:19 +08004807 case CancelationOptions::CANCEL_DISPLAY_UNSPECIFIED_EVENTS:
4808 return memento.displayId == ADISPLAY_ID_NONE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004809 default:
4810 return false;
4811 }
4812}
4813
4814bool InputDispatcher::InputState::shouldCancelMotion(const MotionMemento& memento,
4815 const CancelationOptions& options) {
4816 if (options.deviceId != -1 && memento.deviceId != options.deviceId) {
4817 return false;
4818 }
4819
4820 switch (options.mode) {
4821 case CancelationOptions::CANCEL_ALL_EVENTS:
4822 return true;
4823 case CancelationOptions::CANCEL_POINTER_EVENTS:
4824 return memento.source & AINPUT_SOURCE_CLASS_POINTER;
4825 case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
4826 return !(memento.source & AINPUT_SOURCE_CLASS_POINTER);
Tiger Huang721e26f2018-07-24 22:26:19 +08004827 case CancelationOptions::CANCEL_DISPLAY_UNSPECIFIED_EVENTS:
4828 return memento.displayId == ADISPLAY_ID_NONE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004829 default:
4830 return false;
4831 }
4832}
4833
4834
4835// --- InputDispatcher::Connection ---
4836
Robert Carr803535b2018-08-02 16:38:15 -07004837InputDispatcher::Connection::Connection(const sp<InputChannel>& inputChannel, bool monitor) :
4838 status(STATUS_NORMAL), inputChannel(inputChannel),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004839 monitor(monitor),
4840 inputPublisher(inputChannel), inputPublisherBlocked(false) {
4841}
4842
4843InputDispatcher::Connection::~Connection() {
4844}
4845
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004846const std::string InputDispatcher::Connection::getWindowName() const {
Robert Carr803535b2018-08-02 16:38:15 -07004847 if (inputChannel != nullptr) {
4848 return inputChannel->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004849 }
4850 if (monitor) {
4851 return "monitor";
4852 }
4853 return "?";
4854}
4855
4856const char* InputDispatcher::Connection::getStatusLabel() const {
4857 switch (status) {
4858 case STATUS_NORMAL:
4859 return "NORMAL";
4860
4861 case STATUS_BROKEN:
4862 return "BROKEN";
4863
4864 case STATUS_ZOMBIE:
4865 return "ZOMBIE";
4866
4867 default:
4868 return "UNKNOWN";
4869 }
4870}
4871
4872InputDispatcher::DispatchEntry* InputDispatcher::Connection::findWaitQueueEntry(uint32_t seq) {
Yi Kong9b14ac62018-07-17 13:48:38 -07004873 for (DispatchEntry* entry = waitQueue.head; entry != nullptr; entry = entry->next) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004874 if (entry->seq == seq) {
4875 return entry;
4876 }
4877 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004878 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004879}
4880
4881
4882// --- InputDispatcher::CommandEntry ---
4883
4884InputDispatcher::CommandEntry::CommandEntry(Command command) :
Yi Kong9b14ac62018-07-17 13:48:38 -07004885 command(command), eventTime(0), keyEntry(nullptr), userActivityEventType(0),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004886 seq(0), handled(false) {
4887}
4888
4889InputDispatcher::CommandEntry::~CommandEntry() {
4890}
4891
4892
4893// --- InputDispatcher::TouchState ---
4894
4895InputDispatcher::TouchState::TouchState() :
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004896 down(false), split(false), deviceId(-1), source(0), displayId(ADISPLAY_ID_NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004897}
4898
4899InputDispatcher::TouchState::~TouchState() {
4900}
4901
4902void InputDispatcher::TouchState::reset() {
4903 down = false;
4904 split = false;
4905 deviceId = -1;
4906 source = 0;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004907 displayId = ADISPLAY_ID_NONE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004908 windows.clear();
4909}
4910
4911void InputDispatcher::TouchState::copyFrom(const TouchState& other) {
4912 down = other.down;
4913 split = other.split;
4914 deviceId = other.deviceId;
4915 source = other.source;
4916 displayId = other.displayId;
4917 windows = other.windows;
4918}
4919
4920void InputDispatcher::TouchState::addOrUpdateWindow(const sp<InputWindowHandle>& windowHandle,
4921 int32_t targetFlags, BitSet32 pointerIds) {
4922 if (targetFlags & InputTarget::FLAG_SPLIT) {
4923 split = true;
4924 }
4925
4926 for (size_t i = 0; i < windows.size(); i++) {
4927 TouchedWindow& touchedWindow = windows.editItemAt(i);
4928 if (touchedWindow.windowHandle == windowHandle) {
4929 touchedWindow.targetFlags |= targetFlags;
4930 if (targetFlags & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
4931 touchedWindow.targetFlags &= ~InputTarget::FLAG_DISPATCH_AS_IS;
4932 }
4933 touchedWindow.pointerIds.value |= pointerIds.value;
4934 return;
4935 }
4936 }
4937
4938 windows.push();
4939
4940 TouchedWindow& touchedWindow = windows.editTop();
4941 touchedWindow.windowHandle = windowHandle;
4942 touchedWindow.targetFlags = targetFlags;
4943 touchedWindow.pointerIds = pointerIds;
4944}
4945
4946void InputDispatcher::TouchState::removeWindow(const sp<InputWindowHandle>& windowHandle) {
4947 for (size_t i = 0; i < windows.size(); i++) {
4948 if (windows.itemAt(i).windowHandle == windowHandle) {
4949 windows.removeAt(i);
4950 return;
4951 }
4952 }
4953}
4954
Robert Carr803535b2018-08-02 16:38:15 -07004955void InputDispatcher::TouchState::removeWindowByToken(const sp<IBinder>& token) {
4956 for (size_t i = 0; i < windows.size(); i++) {
Robert Carr5c8a0262018-10-03 16:30:44 -07004957 if (windows.itemAt(i).windowHandle->getToken() == token) {
Robert Carr803535b2018-08-02 16:38:15 -07004958 windows.removeAt(i);
4959 return;
4960 }
4961 }
4962}
4963
Michael Wrightd02c5b62014-02-10 15:10:22 -08004964void InputDispatcher::TouchState::filterNonAsIsTouchWindows() {
4965 for (size_t i = 0 ; i < windows.size(); ) {
4966 TouchedWindow& window = windows.editItemAt(i);
4967 if (window.targetFlags & (InputTarget::FLAG_DISPATCH_AS_IS
4968 | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER)) {
4969 window.targetFlags &= ~InputTarget::FLAG_DISPATCH_MASK;
4970 window.targetFlags |= InputTarget::FLAG_DISPATCH_AS_IS;
4971 i += 1;
4972 } else {
4973 windows.removeAt(i);
4974 }
4975 }
4976}
4977
4978sp<InputWindowHandle> InputDispatcher::TouchState::getFirstForegroundWindowHandle() const {
4979 for (size_t i = 0; i < windows.size(); i++) {
4980 const TouchedWindow& window = windows.itemAt(i);
4981 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
4982 return window.windowHandle;
4983 }
4984 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004985 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004986}
4987
4988bool InputDispatcher::TouchState::isSlippery() const {
4989 // Must have exactly one foreground window.
4990 bool haveSlipperyForegroundWindow = false;
4991 for (size_t i = 0; i < windows.size(); i++) {
4992 const TouchedWindow& window = windows.itemAt(i);
4993 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
4994 if (haveSlipperyForegroundWindow
4995 || !(window.windowHandle->getInfo()->layoutParamsFlags
4996 & InputWindowInfo::FLAG_SLIPPERY)) {
4997 return false;
4998 }
4999 haveSlipperyForegroundWindow = true;
5000 }
5001 }
5002 return haveSlipperyForegroundWindow;
5003}
5004
5005
5006// --- InputDispatcherThread ---
5007
5008InputDispatcherThread::InputDispatcherThread(const sp<InputDispatcherInterface>& dispatcher) :
5009 Thread(/*canCallJava*/ true), mDispatcher(dispatcher) {
5010}
5011
5012InputDispatcherThread::~InputDispatcherThread() {
5013}
5014
5015bool InputDispatcherThread::threadLoop() {
5016 mDispatcher->dispatchOnce();
5017 return true;
5018}
5019
5020} // namespace android