• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
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 
48 #include <errno.h>
49 #include <limits.h>
50 #include <sstream>
51 #include <stddef.h>
52 #include <time.h>
53 #include <unistd.h>
54 
55 #include <android-base/chrono_utils.h>
56 #include <android-base/stringprintf.h>
57 #include <log/log.h>
58 #include <utils/Trace.h>
59 #include <powermanager/PowerManager.h>
60 #include <ui/Region.h>
61 
62 #define INDENT "  "
63 #define INDENT2 "    "
64 #define INDENT3 "      "
65 #define INDENT4 "        "
66 
67 using android::base::StringPrintf;
68 
69 namespace android {
70 
71 // Default input dispatching timeout if there is no focused application or paused window
72 // from which to determine an appropriate dispatching timeout.
73 constexpr nsecs_t DEFAULT_INPUT_DISPATCHING_TIMEOUT = 5000 * 1000000LL; // 5 sec
74 
75 // Amount of time to allow for all pending events to be processed when an app switch
76 // key is on the way.  This is used to preempt input dispatch and drop input events
77 // when an application takes too long to respond and the user has pressed an app switch key.
78 constexpr nsecs_t APP_SWITCH_TIMEOUT = 500 * 1000000LL; // 0.5sec
79 
80 // Amount of time to allow for an event to be dispatched (measured since its eventTime)
81 // before considering it stale and dropping it.
82 constexpr nsecs_t STALE_EVENT_TIMEOUT = 10000 * 1000000LL; // 10sec
83 
84 // Amount of time to allow touch events to be streamed out to a connection before requiring
85 // that the first event be finished.  This value extends the ANR timeout by the specified
86 // amount.  For example, if streaming is allowed to get ahead by one second relative to the
87 // queue of waiting unfinished events, then ANRs will similarly be delayed by one second.
88 constexpr nsecs_t STREAM_AHEAD_EVENT_TIMEOUT = 500 * 1000000LL; // 0.5sec
89 
90 // Log a warning when an event takes longer than this to process, even if an ANR does not occur.
91 constexpr nsecs_t SLOW_EVENT_PROCESSING_WARNING_TIMEOUT = 2000 * 1000000LL; // 2sec
92 
93 // Log a warning when an interception call takes longer than this to process.
94 constexpr std::chrono::milliseconds SLOW_INTERCEPTION_THRESHOLD = 50ms;
95 
96 // Number of recent events to keep for debugging purposes.
97 constexpr size_t RECENT_QUEUE_MAX_SIZE = 10;
98 
99 
now()100 static inline nsecs_t now() {
101     return systemTime(SYSTEM_TIME_MONOTONIC);
102 }
103 
toString(bool value)104 static inline const char* toString(bool value) {
105     return value ? "true" : "false";
106 }
107 
getMotionEventActionPointerIndex(int32_t action)108 static inline int32_t getMotionEventActionPointerIndex(int32_t action) {
109     return (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK)
110             >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
111 }
112 
isValidKeyAction(int32_t action)113 static bool isValidKeyAction(int32_t action) {
114     switch (action) {
115     case AKEY_EVENT_ACTION_DOWN:
116     case AKEY_EVENT_ACTION_UP:
117         return true;
118     default:
119         return false;
120     }
121 }
122 
validateKeyEvent(int32_t action)123 static bool validateKeyEvent(int32_t action) {
124     if (! isValidKeyAction(action)) {
125         ALOGE("Key event has invalid action code 0x%x", action);
126         return false;
127     }
128     return true;
129 }
130 
isValidMotionAction(int32_t action,int32_t actionButton,int32_t pointerCount)131 static bool isValidMotionAction(int32_t action, int32_t actionButton, int32_t pointerCount) {
132     switch (action & AMOTION_EVENT_ACTION_MASK) {
133     case AMOTION_EVENT_ACTION_DOWN:
134     case AMOTION_EVENT_ACTION_UP:
135     case AMOTION_EVENT_ACTION_CANCEL:
136     case AMOTION_EVENT_ACTION_MOVE:
137     case AMOTION_EVENT_ACTION_OUTSIDE:
138     case AMOTION_EVENT_ACTION_HOVER_ENTER:
139     case AMOTION_EVENT_ACTION_HOVER_MOVE:
140     case AMOTION_EVENT_ACTION_HOVER_EXIT:
141     case AMOTION_EVENT_ACTION_SCROLL:
142         return true;
143     case AMOTION_EVENT_ACTION_POINTER_DOWN:
144     case AMOTION_EVENT_ACTION_POINTER_UP: {
145         int32_t index = getMotionEventActionPointerIndex(action);
146         return index >= 0 && index < pointerCount;
147     }
148     case AMOTION_EVENT_ACTION_BUTTON_PRESS:
149     case AMOTION_EVENT_ACTION_BUTTON_RELEASE:
150         return actionButton != 0;
151     default:
152         return false;
153     }
154 }
155 
validateMotionEvent(int32_t action,int32_t actionButton,size_t pointerCount,const PointerProperties * pointerProperties)156 static bool validateMotionEvent(int32_t action, int32_t actionButton, size_t pointerCount,
157         const PointerProperties* pointerProperties) {
158     if (! isValidMotionAction(action, actionButton, pointerCount)) {
159         ALOGE("Motion event has invalid action code 0x%x", action);
160         return false;
161     }
162     if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
163         ALOGE("Motion event has invalid pointer count %zu; value must be between 1 and %d.",
164                 pointerCount, MAX_POINTERS);
165         return false;
166     }
167     BitSet32 pointerIdBits;
168     for (size_t i = 0; i < pointerCount; i++) {
169         int32_t id = pointerProperties[i].id;
170         if (id < 0 || id > MAX_POINTER_ID) {
171             ALOGE("Motion event has invalid pointer id %d; value must be between 0 and %d",
172                     id, MAX_POINTER_ID);
173             return false;
174         }
175         if (pointerIdBits.hasBit(id)) {
176             ALOGE("Motion event has duplicate pointer id %d", id);
177             return false;
178         }
179         pointerIdBits.markBit(id);
180     }
181     return true;
182 }
183 
isMainDisplay(int32_t displayId)184 static bool isMainDisplay(int32_t displayId) {
185     return displayId == ADISPLAY_ID_DEFAULT || displayId == ADISPLAY_ID_NONE;
186 }
187 
dumpRegion(std::string & dump,const Region & region)188 static void dumpRegion(std::string& dump, const Region& region) {
189     if (region.isEmpty()) {
190         dump += "<empty>";
191         return;
192     }
193 
194     bool first = true;
195     Region::const_iterator cur = region.begin();
196     Region::const_iterator const tail = region.end();
197     while (cur != tail) {
198         if (first) {
199             first = false;
200         } else {
201             dump += "|";
202         }
203         dump += StringPrintf("[%d,%d][%d,%d]", cur->left, cur->top, cur->right, cur->bottom);
204         cur++;
205     }
206 }
207 
208 
209 // --- InputDispatcher ---
210 
InputDispatcher(const sp<InputDispatcherPolicyInterface> & policy)211 InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy) :
212     mPolicy(policy),
213     mPendingEvent(NULL), mLastDropReason(DROP_REASON_NOT_DROPPED),
214     mAppSwitchSawKeyDown(false), mAppSwitchDueTime(LONG_LONG_MAX),
215     mNextUnblockedEvent(NULL),
216     mDispatchEnabled(false), mDispatchFrozen(false), mInputFilterEnabled(false),
217     mInputTargetWaitCause(INPUT_TARGET_WAIT_CAUSE_NONE) {
218     mLooper = new Looper(false);
219 
220     mKeyRepeatState.lastKeyEntry = NULL;
221 
222     policy->getDispatcherConfiguration(&mConfig);
223 }
224 
~InputDispatcher()225 InputDispatcher::~InputDispatcher() {
226     { // acquire lock
227         AutoMutex _l(mLock);
228 
229         resetKeyRepeatLocked();
230         releasePendingEventLocked();
231         drainInboundQueueLocked();
232     }
233 
234     while (mConnectionsByFd.size() != 0) {
235         unregisterInputChannel(mConnectionsByFd.valueAt(0)->inputChannel);
236     }
237 }
238 
dispatchOnce()239 void InputDispatcher::dispatchOnce() {
240     nsecs_t nextWakeupTime = LONG_LONG_MAX;
241     { // acquire lock
242         AutoMutex _l(mLock);
243         mDispatcherIsAliveCondition.broadcast();
244 
245         // Run a dispatch loop if there are no pending commands.
246         // The dispatch loop might enqueue commands to run afterwards.
247         if (!haveCommandsLocked()) {
248             dispatchOnceInnerLocked(&nextWakeupTime);
249         }
250 
251         // Run all pending commands if there are any.
252         // If any commands were run then force the next poll to wake up immediately.
253         if (runCommandsLockedInterruptible()) {
254             nextWakeupTime = LONG_LONG_MIN;
255         }
256     } // release lock
257 
258     // Wait for callback or timeout or wake.  (make sure we round up, not down)
259     nsecs_t currentTime = now();
260     int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
261     mLooper->pollOnce(timeoutMillis);
262 }
263 
dispatchOnceInnerLocked(nsecs_t * nextWakeupTime)264 void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
265     nsecs_t currentTime = now();
266 
267     // Reset the key repeat timer whenever normal dispatch is suspended while the
268     // device is in a non-interactive state.  This is to ensure that we abort a key
269     // repeat if the device is just coming out of sleep.
270     if (!mDispatchEnabled) {
271         resetKeyRepeatLocked();
272     }
273 
274     // If dispatching is frozen, do not process timeouts or try to deliver any new events.
275     if (mDispatchFrozen) {
276 #if DEBUG_FOCUS
277         ALOGD("Dispatch frozen.  Waiting some more.");
278 #endif
279         return;
280     }
281 
282     // Optimize latency of app switches.
283     // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
284     // been pressed.  When it expires, we preempt dispatch and drop all other pending events.
285     bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
286     if (mAppSwitchDueTime < *nextWakeupTime) {
287         *nextWakeupTime = mAppSwitchDueTime;
288     }
289 
290     // Ready to start a new event.
291     // If we don't already have a pending event, go grab one.
292     if (! mPendingEvent) {
293         if (mInboundQueue.isEmpty()) {
294             if (isAppSwitchDue) {
295                 // The inbound queue is empty so the app switch key we were waiting
296                 // for will never arrive.  Stop waiting for it.
297                 resetPendingAppSwitchLocked(false);
298                 isAppSwitchDue = false;
299             }
300 
301             // Synthesize a key repeat if appropriate.
302             if (mKeyRepeatState.lastKeyEntry) {
303                 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
304                     mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
305                 } else {
306                     if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
307                         *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
308                     }
309                 }
310             }
311 
312             // Nothing to do if there is no pending event.
313             if (!mPendingEvent) {
314                 return;
315             }
316         } else {
317             // Inbound queue has at least one entry.
318             mPendingEvent = mInboundQueue.dequeueAtHead();
319             traceInboundQueueLengthLocked();
320         }
321 
322         // Poke user activity for this event.
323         if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
324             pokeUserActivityLocked(mPendingEvent);
325         }
326 
327         // Get ready to dispatch the event.
328         resetANRTimeoutsLocked();
329     }
330 
331     // Now we have an event to dispatch.
332     // All events are eventually dequeued and processed this way, even if we intend to drop them.
333     ALOG_ASSERT(mPendingEvent != NULL);
334     bool done = false;
335     DropReason dropReason = DROP_REASON_NOT_DROPPED;
336     if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
337         dropReason = DROP_REASON_POLICY;
338     } else if (!mDispatchEnabled) {
339         dropReason = DROP_REASON_DISABLED;
340     }
341 
342     if (mNextUnblockedEvent == mPendingEvent) {
343         mNextUnblockedEvent = NULL;
344     }
345 
346     switch (mPendingEvent->type) {
347     case EventEntry::TYPE_CONFIGURATION_CHANGED: {
348         ConfigurationChangedEntry* typedEntry =
349                 static_cast<ConfigurationChangedEntry*>(mPendingEvent);
350         done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
351         dropReason = DROP_REASON_NOT_DROPPED; // configuration changes are never dropped
352         break;
353     }
354 
355     case EventEntry::TYPE_DEVICE_RESET: {
356         DeviceResetEntry* typedEntry =
357                 static_cast<DeviceResetEntry*>(mPendingEvent);
358         done = dispatchDeviceResetLocked(currentTime, typedEntry);
359         dropReason = DROP_REASON_NOT_DROPPED; // device resets are never dropped
360         break;
361     }
362 
363     case EventEntry::TYPE_KEY: {
364         KeyEntry* typedEntry = static_cast<KeyEntry*>(mPendingEvent);
365         if (isAppSwitchDue) {
366             if (isAppSwitchKeyEventLocked(typedEntry)) {
367                 resetPendingAppSwitchLocked(true);
368                 isAppSwitchDue = false;
369             } else if (dropReason == DROP_REASON_NOT_DROPPED) {
370                 dropReason = DROP_REASON_APP_SWITCH;
371             }
372         }
373         if (dropReason == DROP_REASON_NOT_DROPPED
374                 && isStaleEventLocked(currentTime, typedEntry)) {
375             dropReason = DROP_REASON_STALE;
376         }
377         if (dropReason == DROP_REASON_NOT_DROPPED && mNextUnblockedEvent) {
378             dropReason = DROP_REASON_BLOCKED;
379         }
380         done = dispatchKeyLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
381         break;
382     }
383 
384     case EventEntry::TYPE_MOTION: {
385         MotionEntry* typedEntry = static_cast<MotionEntry*>(mPendingEvent);
386         if (dropReason == DROP_REASON_NOT_DROPPED && isAppSwitchDue) {
387             dropReason = DROP_REASON_APP_SWITCH;
388         }
389         if (dropReason == DROP_REASON_NOT_DROPPED
390                 && isStaleEventLocked(currentTime, typedEntry)) {
391             dropReason = DROP_REASON_STALE;
392         }
393         if (dropReason == DROP_REASON_NOT_DROPPED && mNextUnblockedEvent) {
394             dropReason = DROP_REASON_BLOCKED;
395         }
396         done = dispatchMotionLocked(currentTime, typedEntry,
397                 &dropReason, nextWakeupTime);
398         break;
399     }
400 
401     default:
402         ALOG_ASSERT(false);
403         break;
404     }
405 
406     if (done) {
407         if (dropReason != DROP_REASON_NOT_DROPPED) {
408             dropInboundEventLocked(mPendingEvent, dropReason);
409         }
410         mLastDropReason = dropReason;
411 
412         releasePendingEventLocked();
413         *nextWakeupTime = LONG_LONG_MIN;  // force next poll to wake up immediately
414     }
415 }
416 
enqueueInboundEventLocked(EventEntry * entry)417 bool InputDispatcher::enqueueInboundEventLocked(EventEntry* entry) {
418     bool needWake = mInboundQueue.isEmpty();
419     mInboundQueue.enqueueAtTail(entry);
420     traceInboundQueueLengthLocked();
421 
422     switch (entry->type) {
423     case EventEntry::TYPE_KEY: {
424         // Optimize app switch latency.
425         // If the application takes too long to catch up then we drop all events preceding
426         // the app switch key.
427         KeyEntry* keyEntry = static_cast<KeyEntry*>(entry);
428         if (isAppSwitchKeyEventLocked(keyEntry)) {
429             if (keyEntry->action == AKEY_EVENT_ACTION_DOWN) {
430                 mAppSwitchSawKeyDown = true;
431             } else if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
432                 if (mAppSwitchSawKeyDown) {
433 #if DEBUG_APP_SWITCH
434                     ALOGD("App switch is pending!");
435 #endif
436                     mAppSwitchDueTime = keyEntry->eventTime + APP_SWITCH_TIMEOUT;
437                     mAppSwitchSawKeyDown = false;
438                     needWake = true;
439                 }
440             }
441         }
442         break;
443     }
444 
445     case EventEntry::TYPE_MOTION: {
446         // Optimize case where the current application is unresponsive and the user
447         // decides to touch a window in a different application.
448         // If the application takes too long to catch up then we drop all events preceding
449         // the touch into the other window.
450         MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
451         if (motionEntry->action == AMOTION_EVENT_ACTION_DOWN
452                 && (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER)
453                 && mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY
454                 && mInputTargetWaitApplicationHandle != NULL) {
455             int32_t displayId = motionEntry->displayId;
456             int32_t x = int32_t(motionEntry->pointerCoords[0].
457                     getAxisValue(AMOTION_EVENT_AXIS_X));
458             int32_t y = int32_t(motionEntry->pointerCoords[0].
459                     getAxisValue(AMOTION_EVENT_AXIS_Y));
460             sp<InputWindowHandle> touchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y);
461             if (touchedWindowHandle != NULL
462                     && touchedWindowHandle->inputApplicationHandle
463                             != mInputTargetWaitApplicationHandle) {
464                 // User touched a different application than the one we are waiting on.
465                 // Flag the event, and start pruning the input queue.
466                 mNextUnblockedEvent = motionEntry;
467                 needWake = true;
468             }
469         }
470         break;
471     }
472     }
473 
474     return needWake;
475 }
476 
addRecentEventLocked(EventEntry * entry)477 void InputDispatcher::addRecentEventLocked(EventEntry* entry) {
478     entry->refCount += 1;
479     mRecentQueue.enqueueAtTail(entry);
480     if (mRecentQueue.count() > RECENT_QUEUE_MAX_SIZE) {
481         mRecentQueue.dequeueAtHead()->release();
482     }
483 }
484 
findTouchedWindowAtLocked(int32_t displayId,int32_t x,int32_t y)485 sp<InputWindowHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId,
486         int32_t x, int32_t y) {
487     // Traverse windows from front to back to find touched window.
488     size_t numWindows = mWindowHandles.size();
489     for (size_t i = 0; i < numWindows; i++) {
490         sp<InputWindowHandle> windowHandle = mWindowHandles.itemAt(i);
491         const InputWindowInfo* windowInfo = windowHandle->getInfo();
492         if (windowInfo->displayId == displayId) {
493             int32_t flags = windowInfo->layoutParamsFlags;
494 
495             if (windowInfo->visible) {
496                 if (!(flags & InputWindowInfo::FLAG_NOT_TOUCHABLE)) {
497                     bool isTouchModal = (flags & (InputWindowInfo::FLAG_NOT_FOCUSABLE
498                             | InputWindowInfo::FLAG_NOT_TOUCH_MODAL)) == 0;
499                     if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
500                         // Found window.
501                         return windowHandle;
502                     }
503                 }
504             }
505         }
506     }
507     return NULL;
508 }
509 
dropInboundEventLocked(EventEntry * entry,DropReason dropReason)510 void InputDispatcher::dropInboundEventLocked(EventEntry* entry, DropReason dropReason) {
511     const char* reason;
512     switch (dropReason) {
513     case DROP_REASON_POLICY:
514 #if DEBUG_INBOUND_EVENT_DETAILS
515         ALOGD("Dropped event because policy consumed it.");
516 #endif
517         reason = "inbound event was dropped because the policy consumed it";
518         break;
519     case DROP_REASON_DISABLED:
520         if (mLastDropReason != DROP_REASON_DISABLED) {
521             ALOGI("Dropped event because input dispatch is disabled.");
522         }
523         reason = "inbound event was dropped because input dispatch is disabled";
524         break;
525     case DROP_REASON_APP_SWITCH:
526         ALOGI("Dropped event because of pending overdue app switch.");
527         reason = "inbound event was dropped because of pending overdue app switch";
528         break;
529     case DROP_REASON_BLOCKED:
530         ALOGI("Dropped event because the current application is not responding and the user "
531                 "has started interacting with a different application.");
532         reason = "inbound event was dropped because the current application is not responding "
533                 "and the user has started interacting with a different application";
534         break;
535     case DROP_REASON_STALE:
536         ALOGI("Dropped event because it is stale.");
537         reason = "inbound event was dropped because it is stale";
538         break;
539     default:
540         ALOG_ASSERT(false);
541         return;
542     }
543 
544     switch (entry->type) {
545     case EventEntry::TYPE_KEY: {
546         CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
547         synthesizeCancelationEventsForAllConnectionsLocked(options);
548         break;
549     }
550     case EventEntry::TYPE_MOTION: {
551         MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
552         if (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) {
553             CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
554             synthesizeCancelationEventsForAllConnectionsLocked(options);
555         } else {
556             CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
557             synthesizeCancelationEventsForAllConnectionsLocked(options);
558         }
559         break;
560     }
561     }
562 }
563 
isAppSwitchKeyCode(int32_t keyCode)564 bool InputDispatcher::isAppSwitchKeyCode(int32_t keyCode) {
565     return keyCode == AKEYCODE_HOME
566             || keyCode == AKEYCODE_ENDCALL
567             || keyCode == AKEYCODE_APP_SWITCH;
568 }
569 
isAppSwitchKeyEventLocked(KeyEntry * keyEntry)570 bool InputDispatcher::isAppSwitchKeyEventLocked(KeyEntry* keyEntry) {
571     return ! (keyEntry->flags & AKEY_EVENT_FLAG_CANCELED)
572             && isAppSwitchKeyCode(keyEntry->keyCode)
573             && (keyEntry->policyFlags & POLICY_FLAG_TRUSTED)
574             && (keyEntry->policyFlags & POLICY_FLAG_PASS_TO_USER);
575 }
576 
isAppSwitchPendingLocked()577 bool InputDispatcher::isAppSwitchPendingLocked() {
578     return mAppSwitchDueTime != LONG_LONG_MAX;
579 }
580 
resetPendingAppSwitchLocked(bool handled)581 void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
582     mAppSwitchDueTime = LONG_LONG_MAX;
583 
584 #if DEBUG_APP_SWITCH
585     if (handled) {
586         ALOGD("App switch has arrived.");
587     } else {
588         ALOGD("App switch was abandoned.");
589     }
590 #endif
591 }
592 
isStaleEventLocked(nsecs_t currentTime,EventEntry * entry)593 bool InputDispatcher::isStaleEventLocked(nsecs_t currentTime, EventEntry* entry) {
594     return currentTime - entry->eventTime >= STALE_EVENT_TIMEOUT;
595 }
596 
haveCommandsLocked() const597 bool InputDispatcher::haveCommandsLocked() const {
598     return !mCommandQueue.isEmpty();
599 }
600 
runCommandsLockedInterruptible()601 bool InputDispatcher::runCommandsLockedInterruptible() {
602     if (mCommandQueue.isEmpty()) {
603         return false;
604     }
605 
606     do {
607         CommandEntry* commandEntry = mCommandQueue.dequeueAtHead();
608 
609         Command command = commandEntry->command;
610         (this->*command)(commandEntry); // commands are implicitly 'LockedInterruptible'
611 
612         commandEntry->connection.clear();
613         delete commandEntry;
614     } while (! mCommandQueue.isEmpty());
615     return true;
616 }
617 
postCommandLocked(Command command)618 InputDispatcher::CommandEntry* InputDispatcher::postCommandLocked(Command command) {
619     CommandEntry* commandEntry = new CommandEntry(command);
620     mCommandQueue.enqueueAtTail(commandEntry);
621     return commandEntry;
622 }
623 
drainInboundQueueLocked()624 void InputDispatcher::drainInboundQueueLocked() {
625     while (! mInboundQueue.isEmpty()) {
626         EventEntry* entry = mInboundQueue.dequeueAtHead();
627         releaseInboundEventLocked(entry);
628     }
629     traceInboundQueueLengthLocked();
630 }
631 
releasePendingEventLocked()632 void InputDispatcher::releasePendingEventLocked() {
633     if (mPendingEvent) {
634         resetANRTimeoutsLocked();
635         releaseInboundEventLocked(mPendingEvent);
636         mPendingEvent = NULL;
637     }
638 }
639 
releaseInboundEventLocked(EventEntry * entry)640 void InputDispatcher::releaseInboundEventLocked(EventEntry* entry) {
641     InjectionState* injectionState = entry->injectionState;
642     if (injectionState && injectionState->injectionResult == INPUT_EVENT_INJECTION_PENDING) {
643 #if DEBUG_DISPATCH_CYCLE
644         ALOGD("Injected inbound event was dropped.");
645 #endif
646         setInjectionResultLocked(entry, INPUT_EVENT_INJECTION_FAILED);
647     }
648     if (entry == mNextUnblockedEvent) {
649         mNextUnblockedEvent = NULL;
650     }
651     addRecentEventLocked(entry);
652     entry->release();
653 }
654 
resetKeyRepeatLocked()655 void InputDispatcher::resetKeyRepeatLocked() {
656     if (mKeyRepeatState.lastKeyEntry) {
657         mKeyRepeatState.lastKeyEntry->release();
658         mKeyRepeatState.lastKeyEntry = NULL;
659     }
660 }
661 
synthesizeKeyRepeatLocked(nsecs_t currentTime)662 InputDispatcher::KeyEntry* InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
663     KeyEntry* entry = mKeyRepeatState.lastKeyEntry;
664 
665     // Reuse the repeated key entry if it is otherwise unreferenced.
666     uint32_t policyFlags = entry->policyFlags &
667             (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
668     if (entry->refCount == 1) {
669         entry->recycle();
670         entry->eventTime = currentTime;
671         entry->policyFlags = policyFlags;
672         entry->repeatCount += 1;
673     } else {
674         KeyEntry* newEntry = new KeyEntry(currentTime,
675                 entry->deviceId, entry->source, policyFlags,
676                 entry->action, entry->flags, entry->keyCode, entry->scanCode,
677                 entry->metaState, entry->repeatCount + 1, entry->downTime);
678 
679         mKeyRepeatState.lastKeyEntry = newEntry;
680         entry->release();
681 
682         entry = newEntry;
683     }
684     entry->syntheticRepeat = true;
685 
686     // Increment reference count since we keep a reference to the event in
687     // mKeyRepeatState.lastKeyEntry in addition to the one we return.
688     entry->refCount += 1;
689 
690     mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
691     return entry;
692 }
693 
dispatchConfigurationChangedLocked(nsecs_t currentTime,ConfigurationChangedEntry * entry)694 bool InputDispatcher::dispatchConfigurationChangedLocked(
695         nsecs_t currentTime, ConfigurationChangedEntry* entry) {
696 #if DEBUG_OUTBOUND_EVENT_DETAILS
697     ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry->eventTime);
698 #endif
699 
700     // Reset key repeating in case a keyboard device was added or removed or something.
701     resetKeyRepeatLocked();
702 
703     // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
704     CommandEntry* commandEntry = postCommandLocked(
705             & InputDispatcher::doNotifyConfigurationChangedInterruptible);
706     commandEntry->eventTime = entry->eventTime;
707     return true;
708 }
709 
dispatchDeviceResetLocked(nsecs_t currentTime,DeviceResetEntry * entry)710 bool InputDispatcher::dispatchDeviceResetLocked(
711         nsecs_t currentTime, DeviceResetEntry* entry) {
712 #if DEBUG_OUTBOUND_EVENT_DETAILS
713     ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry->eventTime,
714             entry->deviceId);
715 #endif
716 
717     CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
718             "device was reset");
719     options.deviceId = entry->deviceId;
720     synthesizeCancelationEventsForAllConnectionsLocked(options);
721     return true;
722 }
723 
dispatchKeyLocked(nsecs_t currentTime,KeyEntry * entry,DropReason * dropReason,nsecs_t * nextWakeupTime)724 bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, KeyEntry* entry,
725         DropReason* dropReason, nsecs_t* nextWakeupTime) {
726     // Preprocessing.
727     if (! entry->dispatchInProgress) {
728         if (entry->repeatCount == 0
729                 && entry->action == AKEY_EVENT_ACTION_DOWN
730                 && (entry->policyFlags & POLICY_FLAG_TRUSTED)
731                 && (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
732             if (mKeyRepeatState.lastKeyEntry
733                     && mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode) {
734                 // We have seen two identical key downs in a row which indicates that the device
735                 // driver is automatically generating key repeats itself.  We take note of the
736                 // repeat here, but we disable our own next key repeat timer since it is clear that
737                 // we will not need to synthesize key repeats ourselves.
738                 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
739                 resetKeyRepeatLocked();
740                 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
741             } else {
742                 // Not a repeat.  Save key down state in case we do see a repeat later.
743                 resetKeyRepeatLocked();
744                 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
745             }
746             mKeyRepeatState.lastKeyEntry = entry;
747             entry->refCount += 1;
748         } else if (! entry->syntheticRepeat) {
749             resetKeyRepeatLocked();
750         }
751 
752         if (entry->repeatCount == 1) {
753             entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
754         } else {
755             entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
756         }
757 
758         entry->dispatchInProgress = true;
759 
760         logOutboundKeyDetailsLocked("dispatchKey - ", entry);
761     }
762 
763     // Handle case where the policy asked us to try again later last time.
764     if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
765         if (currentTime < entry->interceptKeyWakeupTime) {
766             if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
767                 *nextWakeupTime = entry->interceptKeyWakeupTime;
768             }
769             return false; // wait until next wakeup
770         }
771         entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
772         entry->interceptKeyWakeupTime = 0;
773     }
774 
775     // Give the policy a chance to intercept the key.
776     if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
777         if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
778             CommandEntry* commandEntry = postCommandLocked(
779                     & InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
780             if (mFocusedWindowHandle != NULL) {
781                 commandEntry->inputWindowHandle = mFocusedWindowHandle;
782             }
783             commandEntry->keyEntry = entry;
784             entry->refCount += 1;
785             return false; // wait for the command to run
786         } else {
787             entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
788         }
789     } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
790         if (*dropReason == DROP_REASON_NOT_DROPPED) {
791             *dropReason = DROP_REASON_POLICY;
792         }
793     }
794 
795     // Clean up if dropping the event.
796     if (*dropReason != DROP_REASON_NOT_DROPPED) {
797         setInjectionResultLocked(entry, *dropReason == DROP_REASON_POLICY
798                 ? INPUT_EVENT_INJECTION_SUCCEEDED : INPUT_EVENT_INJECTION_FAILED);
799         return true;
800     }
801 
802     // Identify targets.
803     Vector<InputTarget> inputTargets;
804     int32_t injectionResult = findFocusedWindowTargetsLocked(currentTime,
805             entry, inputTargets, nextWakeupTime);
806     if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
807         return false;
808     }
809 
810     setInjectionResultLocked(entry, injectionResult);
811     if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
812         return true;
813     }
814 
815     addMonitoringTargetsLocked(inputTargets);
816 
817     // Dispatch the key.
818     dispatchEventLocked(currentTime, entry, inputTargets);
819     return true;
820 }
821 
logOutboundKeyDetailsLocked(const char * prefix,const KeyEntry * entry)822 void InputDispatcher::logOutboundKeyDetailsLocked(const char* prefix, const KeyEntry* entry) {
823 #if DEBUG_OUTBOUND_EVENT_DETAILS
824     ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, policyFlags=0x%x, "
825             "action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, "
826             "repeatCount=%d, downTime=%" PRId64,
827             prefix,
828             entry->eventTime, entry->deviceId, entry->source, entry->policyFlags,
829             entry->action, entry->flags, entry->keyCode, entry->scanCode, entry->metaState,
830             entry->repeatCount, entry->downTime);
831 #endif
832 }
833 
dispatchMotionLocked(nsecs_t currentTime,MotionEntry * entry,DropReason * dropReason,nsecs_t * nextWakeupTime)834 bool InputDispatcher::dispatchMotionLocked(
835         nsecs_t currentTime, MotionEntry* entry, DropReason* dropReason, nsecs_t* nextWakeupTime) {
836     // Preprocessing.
837     if (! entry->dispatchInProgress) {
838         entry->dispatchInProgress = true;
839 
840         logOutboundMotionDetailsLocked("dispatchMotion - ", entry);
841     }
842 
843     // Clean up if dropping the event.
844     if (*dropReason != DROP_REASON_NOT_DROPPED) {
845         setInjectionResultLocked(entry, *dropReason == DROP_REASON_POLICY
846                 ? INPUT_EVENT_INJECTION_SUCCEEDED : INPUT_EVENT_INJECTION_FAILED);
847         return true;
848     }
849 
850     bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
851 
852     // Identify targets.
853     Vector<InputTarget> inputTargets;
854 
855     bool conflictingPointerActions = false;
856     int32_t injectionResult;
857     if (isPointerEvent) {
858         // Pointer event.  (eg. touchscreen)
859         injectionResult = findTouchedWindowTargetsLocked(currentTime,
860                 entry, inputTargets, nextWakeupTime, &conflictingPointerActions);
861     } else {
862         // Non touch event.  (eg. trackball)
863         injectionResult = findFocusedWindowTargetsLocked(currentTime,
864                 entry, inputTargets, nextWakeupTime);
865     }
866     if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
867         return false;
868     }
869 
870     setInjectionResultLocked(entry, injectionResult);
871     if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
872         if (injectionResult != INPUT_EVENT_INJECTION_PERMISSION_DENIED) {
873             CancelationOptions::Mode mode(isPointerEvent ?
874                     CancelationOptions::CANCEL_POINTER_EVENTS :
875                     CancelationOptions::CANCEL_NON_POINTER_EVENTS);
876             CancelationOptions options(mode, "input event injection failed");
877             synthesizeCancelationEventsForMonitorsLocked(options);
878         }
879         return true;
880     }
881 
882     addMonitoringTargetsLocked(inputTargets);
883 
884     // Dispatch the motion.
885     if (conflictingPointerActions) {
886         CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
887                 "conflicting pointer actions");
888         synthesizeCancelationEventsForAllConnectionsLocked(options);
889     }
890     dispatchEventLocked(currentTime, entry, inputTargets);
891     return true;
892 }
893 
894 
logOutboundMotionDetailsLocked(const char * prefix,const MotionEntry * entry)895 void InputDispatcher::logOutboundMotionDetailsLocked(const char* prefix, const MotionEntry* entry) {
896 #if DEBUG_OUTBOUND_EVENT_DETAILS
897     ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, policyFlags=0x%x, "
898             "action=0x%x, actionButton=0x%x, flags=0x%x, "
899             "metaState=0x%x, buttonState=0x%x,"
900             "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
901             prefix,
902             entry->eventTime, entry->deviceId, entry->source, entry->policyFlags,
903             entry->action, entry->actionButton, entry->flags,
904             entry->metaState, entry->buttonState,
905             entry->edgeFlags, entry->xPrecision, entry->yPrecision,
906             entry->downTime);
907 
908     for (uint32_t i = 0; i < entry->pointerCount; i++) {
909         ALOGD("  Pointer %d: id=%d, toolType=%d, "
910                 "x=%f, y=%f, pressure=%f, size=%f, "
911                 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
912                 "orientation=%f",
913                 i, entry->pointerProperties[i].id,
914                 entry->pointerProperties[i].toolType,
915                 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
916                 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
917                 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
918                 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
919                 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
920                 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
921                 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
922                 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
923                 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
924     }
925 #endif
926 }
927 
dispatchEventLocked(nsecs_t currentTime,EventEntry * eventEntry,const Vector<InputTarget> & inputTargets)928 void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
929         EventEntry* eventEntry, const Vector<InputTarget>& inputTargets) {
930 #if DEBUG_DISPATCH_CYCLE
931     ALOGD("dispatchEventToCurrentInputTargets");
932 #endif
933 
934     ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
935 
936     pokeUserActivityLocked(eventEntry);
937 
938     for (size_t i = 0; i < inputTargets.size(); i++) {
939         const InputTarget& inputTarget = inputTargets.itemAt(i);
940 
941         ssize_t connectionIndex = getConnectionIndexLocked(inputTarget.inputChannel);
942         if (connectionIndex >= 0) {
943             sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
944             prepareDispatchCycleLocked(currentTime, connection, eventEntry, &inputTarget);
945         } else {
946 #if DEBUG_FOCUS
947             ALOGD("Dropping event delivery to target with channel '%s' because it "
948                     "is no longer registered with the input dispatcher.",
949                     inputTarget.inputChannel->getName().c_str());
950 #endif
951         }
952     }
953 }
954 
handleTargetsNotReadyLocked(nsecs_t currentTime,const EventEntry * entry,const sp<InputApplicationHandle> & applicationHandle,const sp<InputWindowHandle> & windowHandle,nsecs_t * nextWakeupTime,const char * reason)955 int32_t InputDispatcher::handleTargetsNotReadyLocked(nsecs_t currentTime,
956         const EventEntry* entry,
957         const sp<InputApplicationHandle>& applicationHandle,
958         const sp<InputWindowHandle>& windowHandle,
959         nsecs_t* nextWakeupTime, const char* reason) {
960     if (applicationHandle == NULL && windowHandle == NULL) {
961         if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY) {
962 #if DEBUG_FOCUS
963             ALOGD("Waiting for system to become ready for input.  Reason: %s", reason);
964 #endif
965             mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY;
966             mInputTargetWaitStartTime = currentTime;
967             mInputTargetWaitTimeoutTime = LONG_LONG_MAX;
968             mInputTargetWaitTimeoutExpired = false;
969             mInputTargetWaitApplicationHandle.clear();
970         }
971     } else {
972         if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
973 #if DEBUG_FOCUS
974             ALOGD("Waiting for application to become ready for input: %s.  Reason: %s",
975                     getApplicationWindowLabelLocked(applicationHandle, windowHandle).c_str(),
976                     reason);
977 #endif
978             nsecs_t timeout;
979             if (windowHandle != NULL) {
980                 timeout = windowHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
981             } else if (applicationHandle != NULL) {
982                 timeout = applicationHandle->getDispatchingTimeout(
983                         DEFAULT_INPUT_DISPATCHING_TIMEOUT);
984             } else {
985                 timeout = DEFAULT_INPUT_DISPATCHING_TIMEOUT;
986             }
987 
988             mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY;
989             mInputTargetWaitStartTime = currentTime;
990             mInputTargetWaitTimeoutTime = currentTime + timeout;
991             mInputTargetWaitTimeoutExpired = false;
992             mInputTargetWaitApplicationHandle.clear();
993 
994             if (windowHandle != NULL) {
995                 mInputTargetWaitApplicationHandle = windowHandle->inputApplicationHandle;
996             }
997             if (mInputTargetWaitApplicationHandle == NULL && applicationHandle != NULL) {
998                 mInputTargetWaitApplicationHandle = applicationHandle;
999             }
1000         }
1001     }
1002 
1003     if (mInputTargetWaitTimeoutExpired) {
1004         return INPUT_EVENT_INJECTION_TIMED_OUT;
1005     }
1006 
1007     if (currentTime >= mInputTargetWaitTimeoutTime) {
1008         onANRLocked(currentTime, applicationHandle, windowHandle,
1009                 entry->eventTime, mInputTargetWaitStartTime, reason);
1010 
1011         // Force poll loop to wake up immediately on next iteration once we get the
1012         // ANR response back from the policy.
1013         *nextWakeupTime = LONG_LONG_MIN;
1014         return INPUT_EVENT_INJECTION_PENDING;
1015     } else {
1016         // Force poll loop to wake up when timeout is due.
1017         if (mInputTargetWaitTimeoutTime < *nextWakeupTime) {
1018             *nextWakeupTime = mInputTargetWaitTimeoutTime;
1019         }
1020         return INPUT_EVENT_INJECTION_PENDING;
1021     }
1022 }
1023 
resumeAfterTargetsNotReadyTimeoutLocked(nsecs_t newTimeout,const sp<InputChannel> & inputChannel)1024 void InputDispatcher::resumeAfterTargetsNotReadyTimeoutLocked(nsecs_t newTimeout,
1025         const sp<InputChannel>& inputChannel) {
1026     if (newTimeout > 0) {
1027         // Extend the timeout.
1028         mInputTargetWaitTimeoutTime = now() + newTimeout;
1029     } else {
1030         // Give up.
1031         mInputTargetWaitTimeoutExpired = true;
1032 
1033         // Input state will not be realistic.  Mark it out of sync.
1034         if (inputChannel.get()) {
1035             ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
1036             if (connectionIndex >= 0) {
1037                 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
1038                 sp<InputWindowHandle> windowHandle = connection->inputWindowHandle;
1039 
1040                 if (windowHandle != NULL) {
1041                     const InputWindowInfo* info = windowHandle->getInfo();
1042                     if (info) {
1043                         ssize_t stateIndex = mTouchStatesByDisplay.indexOfKey(info->displayId);
1044                         if (stateIndex >= 0) {
1045                             mTouchStatesByDisplay.editValueAt(stateIndex).removeWindow(
1046                                     windowHandle);
1047                         }
1048                     }
1049                 }
1050 
1051                 if (connection->status == Connection::STATUS_NORMAL) {
1052                     CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1053                             "application not responding");
1054                     synthesizeCancelationEventsForConnectionLocked(connection, options);
1055                 }
1056             }
1057         }
1058     }
1059 }
1060 
getTimeSpentWaitingForApplicationLocked(nsecs_t currentTime)1061 nsecs_t InputDispatcher::getTimeSpentWaitingForApplicationLocked(
1062         nsecs_t currentTime) {
1063     if (mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
1064         return currentTime - mInputTargetWaitStartTime;
1065     }
1066     return 0;
1067 }
1068 
resetANRTimeoutsLocked()1069 void InputDispatcher::resetANRTimeoutsLocked() {
1070 #if DEBUG_FOCUS
1071         ALOGD("Resetting ANR timeouts.");
1072 #endif
1073 
1074     // Reset input target wait timeout.
1075     mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_NONE;
1076     mInputTargetWaitApplicationHandle.clear();
1077 }
1078 
findFocusedWindowTargetsLocked(nsecs_t currentTime,const EventEntry * entry,Vector<InputTarget> & inputTargets,nsecs_t * nextWakeupTime)1079 int32_t InputDispatcher::findFocusedWindowTargetsLocked(nsecs_t currentTime,
1080         const EventEntry* entry, Vector<InputTarget>& inputTargets, nsecs_t* nextWakeupTime) {
1081     int32_t injectionResult;
1082     std::string reason;
1083 
1084     // If there is no currently focused window and no focused application
1085     // then drop the event.
1086     if (mFocusedWindowHandle == NULL) {
1087         if (mFocusedApplicationHandle != NULL) {
1088             injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
1089                     mFocusedApplicationHandle, NULL, nextWakeupTime,
1090                     "Waiting because no window has focus but there is a "
1091                     "focused application that may eventually add a window "
1092                     "when it finishes starting up.");
1093             goto Unresponsive;
1094         }
1095 
1096         ALOGI("Dropping event because there is no focused window or focused application.");
1097         injectionResult = INPUT_EVENT_INJECTION_FAILED;
1098         goto Failed;
1099     }
1100 
1101     // Check permissions.
1102     if (! checkInjectionPermission(mFocusedWindowHandle, entry->injectionState)) {
1103         injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1104         goto Failed;
1105     }
1106 
1107     // Check whether the window is ready for more input.
1108     reason = checkWindowReadyForMoreInputLocked(currentTime,
1109             mFocusedWindowHandle, entry, "focused");
1110     if (!reason.empty()) {
1111         injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
1112                 mFocusedApplicationHandle, mFocusedWindowHandle, nextWakeupTime, reason.c_str());
1113         goto Unresponsive;
1114     }
1115 
1116     // Success!  Output targets.
1117     injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
1118     addWindowTargetLocked(mFocusedWindowHandle,
1119             InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS, BitSet32(0),
1120             inputTargets);
1121 
1122     // Done.
1123 Failed:
1124 Unresponsive:
1125     nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
1126     updateDispatchStatisticsLocked(currentTime, entry,
1127             injectionResult, timeSpentWaitingForApplication);
1128 #if DEBUG_FOCUS
1129     ALOGD("findFocusedWindow finished: injectionResult=%d, "
1130             "timeSpentWaitingForApplication=%0.1fms",
1131             injectionResult, timeSpentWaitingForApplication / 1000000.0);
1132 #endif
1133     return injectionResult;
1134 }
1135 
findTouchedWindowTargetsLocked(nsecs_t currentTime,const MotionEntry * entry,Vector<InputTarget> & inputTargets,nsecs_t * nextWakeupTime,bool * outConflictingPointerActions)1136 int32_t InputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime,
1137         const MotionEntry* entry, Vector<InputTarget>& inputTargets, nsecs_t* nextWakeupTime,
1138         bool* outConflictingPointerActions) {
1139     enum InjectionPermission {
1140         INJECTION_PERMISSION_UNKNOWN,
1141         INJECTION_PERMISSION_GRANTED,
1142         INJECTION_PERMISSION_DENIED
1143     };
1144 
1145     // For security reasons, we defer updating the touch state until we are sure that
1146     // event injection will be allowed.
1147     int32_t displayId = entry->displayId;
1148     int32_t action = entry->action;
1149     int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
1150 
1151     // Update the touch state as needed based on the properties of the touch event.
1152     int32_t injectionResult = INPUT_EVENT_INJECTION_PENDING;
1153     InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
1154     sp<InputWindowHandle> newHoverWindowHandle;
1155 
1156     // Copy current touch state into mTempTouchState.
1157     // This state is always reset at the end of this function, so if we don't find state
1158     // for the specified display then our initial state will be empty.
1159     const TouchState* oldState = NULL;
1160     ssize_t oldStateIndex = mTouchStatesByDisplay.indexOfKey(displayId);
1161     if (oldStateIndex >= 0) {
1162         oldState = &mTouchStatesByDisplay.valueAt(oldStateIndex);
1163         mTempTouchState.copyFrom(*oldState);
1164     }
1165 
1166     bool isSplit = mTempTouchState.split;
1167     bool switchedDevice = mTempTouchState.deviceId >= 0 && mTempTouchState.displayId >= 0
1168             && (mTempTouchState.deviceId != entry->deviceId
1169                     || mTempTouchState.source != entry->source
1170                     || mTempTouchState.displayId != displayId);
1171     bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE
1172             || maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER
1173             || maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1174     bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN
1175             || maskedAction == AMOTION_EVENT_ACTION_SCROLL
1176             || isHoverAction);
1177     bool wrongDevice = false;
1178     if (newGesture) {
1179         bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
1180         if (switchedDevice && mTempTouchState.down && !down && !isHoverAction) {
1181 #if DEBUG_FOCUS
1182             ALOGD("Dropping event because a pointer for a different device is already down.");
1183 #endif
1184             // TODO: test multiple simultaneous input streams.
1185             injectionResult = INPUT_EVENT_INJECTION_FAILED;
1186             switchedDevice = false;
1187             wrongDevice = true;
1188             goto Failed;
1189         }
1190         mTempTouchState.reset();
1191         mTempTouchState.down = down;
1192         mTempTouchState.deviceId = entry->deviceId;
1193         mTempTouchState.source = entry->source;
1194         mTempTouchState.displayId = displayId;
1195         isSplit = false;
1196     } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
1197 #if DEBUG_FOCUS
1198         ALOGI("Dropping move event because a pointer for a different device is already active.");
1199 #endif
1200         // TODO: test multiple simultaneous input streams.
1201         injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1202         switchedDevice = false;
1203         wrongDevice = true;
1204         goto Failed;
1205     }
1206 
1207     if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
1208         /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
1209 
1210         int32_t pointerIndex = getMotionEventActionPointerIndex(action);
1211         int32_t x = int32_t(entry->pointerCoords[pointerIndex].
1212                 getAxisValue(AMOTION_EVENT_AXIS_X));
1213         int32_t y = int32_t(entry->pointerCoords[pointerIndex].
1214                 getAxisValue(AMOTION_EVENT_AXIS_Y));
1215         sp<InputWindowHandle> newTouchedWindowHandle;
1216         bool isTouchModal = false;
1217 
1218         // Traverse windows from front to back to find touched window and outside targets.
1219         size_t numWindows = mWindowHandles.size();
1220         for (size_t i = 0; i < numWindows; i++) {
1221             sp<InputWindowHandle> windowHandle = mWindowHandles.itemAt(i);
1222             const InputWindowInfo* windowInfo = windowHandle->getInfo();
1223             if (windowInfo->displayId != displayId) {
1224                 continue; // wrong display
1225             }
1226 
1227             int32_t flags = windowInfo->layoutParamsFlags;
1228             if (windowInfo->visible) {
1229                 if (! (flags & InputWindowInfo::FLAG_NOT_TOUCHABLE)) {
1230                     isTouchModal = (flags & (InputWindowInfo::FLAG_NOT_FOCUSABLE
1231                             | InputWindowInfo::FLAG_NOT_TOUCH_MODAL)) == 0;
1232                     if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
1233                         newTouchedWindowHandle = windowHandle;
1234                         break; // found touched window, exit window loop
1235                     }
1236                 }
1237 
1238                 if (maskedAction == AMOTION_EVENT_ACTION_DOWN
1239                         && (flags & InputWindowInfo::FLAG_WATCH_OUTSIDE_TOUCH)) {
1240                     mTempTouchState.addOrUpdateWindow(
1241                             windowHandle, InputTarget::FLAG_DISPATCH_AS_OUTSIDE, BitSet32(0));
1242                 }
1243             }
1244         }
1245 
1246         // Figure out whether splitting will be allowed for this window.
1247         if (newTouchedWindowHandle != NULL
1248                 && newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
1249             // New window supports splitting.
1250             isSplit = true;
1251         } else if (isSplit) {
1252             // New window does not support splitting but we have already split events.
1253             // Ignore the new window.
1254             newTouchedWindowHandle = NULL;
1255         }
1256 
1257         // Handle the case where we did not find a window.
1258         if (newTouchedWindowHandle == NULL) {
1259             // Try to assign the pointer to the first foreground window we find, if there is one.
1260             newTouchedWindowHandle = mTempTouchState.getFirstForegroundWindowHandle();
1261             if (newTouchedWindowHandle == NULL) {
1262                 ALOGI("Dropping event because there is no touchable window at (%d, %d).", x, y);
1263                 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1264                 goto Failed;
1265             }
1266         }
1267 
1268         // Set target flags.
1269         int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
1270         if (isSplit) {
1271             targetFlags |= InputTarget::FLAG_SPLIT;
1272         }
1273         if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1274             targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1275         } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
1276             targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1277         }
1278 
1279         // Update hover state.
1280         if (isHoverAction) {
1281             newHoverWindowHandle = newTouchedWindowHandle;
1282         } else if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
1283             newHoverWindowHandle = mLastHoverWindowHandle;
1284         }
1285 
1286         // Update the temporary touch state.
1287         BitSet32 pointerIds;
1288         if (isSplit) {
1289             uint32_t pointerId = entry->pointerProperties[pointerIndex].id;
1290             pointerIds.markBit(pointerId);
1291         }
1292         mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
1293     } else {
1294         /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
1295 
1296         // If the pointer is not currently down, then ignore the event.
1297         if (! mTempTouchState.down) {
1298 #if DEBUG_FOCUS
1299             ALOGD("Dropping event because the pointer is not down or we previously "
1300                     "dropped the pointer down event.");
1301 #endif
1302             injectionResult = INPUT_EVENT_INJECTION_FAILED;
1303             goto Failed;
1304         }
1305 
1306         // Check whether touches should slip outside of the current foreground window.
1307         if (maskedAction == AMOTION_EVENT_ACTION_MOVE
1308                 && entry->pointerCount == 1
1309                 && mTempTouchState.isSlippery()) {
1310             int32_t x = int32_t(entry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
1311             int32_t y = int32_t(entry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
1312 
1313             sp<InputWindowHandle> oldTouchedWindowHandle =
1314                     mTempTouchState.getFirstForegroundWindowHandle();
1315             sp<InputWindowHandle> newTouchedWindowHandle =
1316                     findTouchedWindowAtLocked(displayId, x, y);
1317             if (oldTouchedWindowHandle != newTouchedWindowHandle
1318                     && newTouchedWindowHandle != NULL) {
1319 #if DEBUG_FOCUS
1320                 ALOGD("Touch is slipping out of window %s into window %s.",
1321                         oldTouchedWindowHandle->getName().c_str(),
1322                         newTouchedWindowHandle->getName().c_str());
1323 #endif
1324                 // Make a slippery exit from the old window.
1325                 mTempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
1326                         InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT, BitSet32(0));
1327 
1328                 // Make a slippery entrance into the new window.
1329                 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
1330                     isSplit = true;
1331                 }
1332 
1333                 int32_t targetFlags = InputTarget::FLAG_FOREGROUND
1334                         | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
1335                 if (isSplit) {
1336                     targetFlags |= InputTarget::FLAG_SPLIT;
1337                 }
1338                 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1339                     targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1340                 }
1341 
1342                 BitSet32 pointerIds;
1343                 if (isSplit) {
1344                     pointerIds.markBit(entry->pointerProperties[0].id);
1345                 }
1346                 mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
1347             }
1348         }
1349     }
1350 
1351     if (newHoverWindowHandle != mLastHoverWindowHandle) {
1352         // Let the previous window know that the hover sequence is over.
1353         if (mLastHoverWindowHandle != NULL) {
1354 #if DEBUG_HOVER
1355             ALOGD("Sending hover exit event to window %s.",
1356                     mLastHoverWindowHandle->getName().c_str());
1357 #endif
1358             mTempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
1359                     InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
1360         }
1361 
1362         // Let the new window know that the hover sequence is starting.
1363         if (newHoverWindowHandle != NULL) {
1364 #if DEBUG_HOVER
1365             ALOGD("Sending hover enter event to window %s.",
1366                     newHoverWindowHandle->getName().c_str());
1367 #endif
1368             mTempTouchState.addOrUpdateWindow(newHoverWindowHandle,
1369                     InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER, BitSet32(0));
1370         }
1371     }
1372 
1373     // Check permission to inject into all touched foreground windows and ensure there
1374     // is at least one touched foreground window.
1375     {
1376         bool haveForegroundWindow = false;
1377         for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1378             const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1379             if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1380                 haveForegroundWindow = true;
1381                 if (! checkInjectionPermission(touchedWindow.windowHandle,
1382                         entry->injectionState)) {
1383                     injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1384                     injectionPermission = INJECTION_PERMISSION_DENIED;
1385                     goto Failed;
1386                 }
1387             }
1388         }
1389         if (! haveForegroundWindow) {
1390 #if DEBUG_FOCUS
1391             ALOGD("Dropping event because there is no touched foreground window to receive it.");
1392 #endif
1393             injectionResult = INPUT_EVENT_INJECTION_FAILED;
1394             goto Failed;
1395         }
1396 
1397         // Permission granted to injection into all touched foreground windows.
1398         injectionPermission = INJECTION_PERMISSION_GRANTED;
1399     }
1400 
1401     // Check whether windows listening for outside touches are owned by the same UID. If it is
1402     // set the policy flag that we will not reveal coordinate information to this window.
1403     if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1404         sp<InputWindowHandle> foregroundWindowHandle =
1405                 mTempTouchState.getFirstForegroundWindowHandle();
1406         const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
1407         for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1408             const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1409             if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
1410                 sp<InputWindowHandle> inputWindowHandle = touchedWindow.windowHandle;
1411                 if (inputWindowHandle->getInfo()->ownerUid != foregroundWindowUid) {
1412                     mTempTouchState.addOrUpdateWindow(inputWindowHandle,
1413                             InputTarget::FLAG_ZERO_COORDS, BitSet32(0));
1414                 }
1415             }
1416         }
1417     }
1418 
1419     // Ensure all touched foreground windows are ready for new input.
1420     for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1421         const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1422         if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1423             // Check whether the window is ready for more input.
1424             std::string reason = checkWindowReadyForMoreInputLocked(currentTime,
1425                     touchedWindow.windowHandle, entry, "touched");
1426             if (!reason.empty()) {
1427                 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
1428                         NULL, touchedWindow.windowHandle, nextWakeupTime, reason.c_str());
1429                 goto Unresponsive;
1430             }
1431         }
1432     }
1433 
1434     // If this is the first pointer going down and the touched window has a wallpaper
1435     // then also add the touched wallpaper windows so they are locked in for the duration
1436     // of the touch gesture.
1437     // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
1438     // engine only supports touch events.  We would need to add a mechanism similar
1439     // to View.onGenericMotionEvent to enable wallpapers to handle these events.
1440     if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1441         sp<InputWindowHandle> foregroundWindowHandle =
1442                 mTempTouchState.getFirstForegroundWindowHandle();
1443         if (foregroundWindowHandle->getInfo()->hasWallpaper) {
1444             for (size_t i = 0; i < mWindowHandles.size(); i++) {
1445                 sp<InputWindowHandle> windowHandle = mWindowHandles.itemAt(i);
1446                 const InputWindowInfo* info = windowHandle->getInfo();
1447                 if (info->displayId == displayId
1448                         && windowHandle->getInfo()->layoutParamsType
1449                                 == InputWindowInfo::TYPE_WALLPAPER) {
1450                     mTempTouchState.addOrUpdateWindow(windowHandle,
1451                             InputTarget::FLAG_WINDOW_IS_OBSCURED
1452                                     | InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED
1453                                     | InputTarget::FLAG_DISPATCH_AS_IS,
1454                             BitSet32(0));
1455                 }
1456             }
1457         }
1458     }
1459 
1460     // Success!  Output targets.
1461     injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
1462 
1463     for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1464         const TouchedWindow& touchedWindow = mTempTouchState.windows.itemAt(i);
1465         addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
1466                 touchedWindow.pointerIds, inputTargets);
1467     }
1468 
1469     // Drop the outside or hover touch windows since we will not care about them
1470     // in the next iteration.
1471     mTempTouchState.filterNonAsIsTouchWindows();
1472 
1473 Failed:
1474     // Check injection permission once and for all.
1475     if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
1476         if (checkInjectionPermission(NULL, entry->injectionState)) {
1477             injectionPermission = INJECTION_PERMISSION_GRANTED;
1478         } else {
1479             injectionPermission = INJECTION_PERMISSION_DENIED;
1480         }
1481     }
1482 
1483     // Update final pieces of touch state if the injector had permission.
1484     if (injectionPermission == INJECTION_PERMISSION_GRANTED) {
1485         if (!wrongDevice) {
1486             if (switchedDevice) {
1487 #if DEBUG_FOCUS
1488                 ALOGD("Conflicting pointer actions: Switched to a different device.");
1489 #endif
1490                 *outConflictingPointerActions = true;
1491             }
1492 
1493             if (isHoverAction) {
1494                 // Started hovering, therefore no longer down.
1495                 if (oldState && oldState->down) {
1496 #if DEBUG_FOCUS
1497                     ALOGD("Conflicting pointer actions: Hover received while pointer was down.");
1498 #endif
1499                     *outConflictingPointerActions = true;
1500                 }
1501                 mTempTouchState.reset();
1502                 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER
1503                         || maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
1504                     mTempTouchState.deviceId = entry->deviceId;
1505                     mTempTouchState.source = entry->source;
1506                     mTempTouchState.displayId = displayId;
1507                 }
1508             } else if (maskedAction == AMOTION_EVENT_ACTION_UP
1509                     || maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
1510                 // All pointers up or canceled.
1511                 mTempTouchState.reset();
1512             } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1513                 // First pointer went down.
1514                 if (oldState && oldState->down) {
1515 #if DEBUG_FOCUS
1516                     ALOGD("Conflicting pointer actions: Down received while already down.");
1517 #endif
1518                     *outConflictingPointerActions = true;
1519                 }
1520             } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
1521                 // One pointer went up.
1522                 if (isSplit) {
1523                     int32_t pointerIndex = getMotionEventActionPointerIndex(action);
1524                     uint32_t pointerId = entry->pointerProperties[pointerIndex].id;
1525 
1526                     for (size_t i = 0; i < mTempTouchState.windows.size(); ) {
1527                         TouchedWindow& touchedWindow = mTempTouchState.windows.editItemAt(i);
1528                         if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
1529                             touchedWindow.pointerIds.clearBit(pointerId);
1530                             if (touchedWindow.pointerIds.isEmpty()) {
1531                                 mTempTouchState.windows.removeAt(i);
1532                                 continue;
1533                             }
1534                         }
1535                         i += 1;
1536                     }
1537                 }
1538             }
1539 
1540             // Save changes unless the action was scroll in which case the temporary touch
1541             // state was only valid for this one action.
1542             if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
1543                 if (mTempTouchState.displayId >= 0) {
1544                     if (oldStateIndex >= 0) {
1545                         mTouchStatesByDisplay.editValueAt(oldStateIndex).copyFrom(mTempTouchState);
1546                     } else {
1547                         mTouchStatesByDisplay.add(displayId, mTempTouchState);
1548                     }
1549                 } else if (oldStateIndex >= 0) {
1550                     mTouchStatesByDisplay.removeItemsAt(oldStateIndex);
1551                 }
1552             }
1553 
1554             // Update hover state.
1555             mLastHoverWindowHandle = newHoverWindowHandle;
1556         }
1557     } else {
1558 #if DEBUG_FOCUS
1559         ALOGD("Not updating touch focus because injection was denied.");
1560 #endif
1561     }
1562 
1563 Unresponsive:
1564     // Reset temporary touch state to ensure we release unnecessary references to input channels.
1565     mTempTouchState.reset();
1566 
1567     nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
1568     updateDispatchStatisticsLocked(currentTime, entry,
1569             injectionResult, timeSpentWaitingForApplication);
1570 #if DEBUG_FOCUS
1571     ALOGD("findTouchedWindow finished: injectionResult=%d, injectionPermission=%d, "
1572             "timeSpentWaitingForApplication=%0.1fms",
1573             injectionResult, injectionPermission, timeSpentWaitingForApplication / 1000000.0);
1574 #endif
1575     return injectionResult;
1576 }
1577 
addWindowTargetLocked(const sp<InputWindowHandle> & windowHandle,int32_t targetFlags,BitSet32 pointerIds,Vector<InputTarget> & inputTargets)1578 void InputDispatcher::addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
1579         int32_t targetFlags, BitSet32 pointerIds, Vector<InputTarget>& inputTargets) {
1580     inputTargets.push();
1581 
1582     const InputWindowInfo* windowInfo = windowHandle->getInfo();
1583     InputTarget& target = inputTargets.editTop();
1584     target.inputChannel = windowInfo->inputChannel;
1585     target.flags = targetFlags;
1586     target.xOffset = - windowInfo->frameLeft;
1587     target.yOffset = - windowInfo->frameTop;
1588     target.scaleFactor = windowInfo->scaleFactor;
1589     target.pointerIds = pointerIds;
1590 }
1591 
addMonitoringTargetsLocked(Vector<InputTarget> & inputTargets)1592 void InputDispatcher::addMonitoringTargetsLocked(Vector<InputTarget>& inputTargets) {
1593     for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
1594         inputTargets.push();
1595 
1596         InputTarget& target = inputTargets.editTop();
1597         target.inputChannel = mMonitoringChannels[i];
1598         target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1599         target.xOffset = 0;
1600         target.yOffset = 0;
1601         target.pointerIds.clear();
1602         target.scaleFactor = 1.0f;
1603     }
1604 }
1605 
checkInjectionPermission(const sp<InputWindowHandle> & windowHandle,const InjectionState * injectionState)1606 bool InputDispatcher::checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
1607         const InjectionState* injectionState) {
1608     if (injectionState
1609             && (windowHandle == NULL
1610                     || windowHandle->getInfo()->ownerUid != injectionState->injectorUid)
1611             && !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
1612         if (windowHandle != NULL) {
1613             ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
1614                     "owned by uid %d",
1615                     injectionState->injectorPid, injectionState->injectorUid,
1616                     windowHandle->getName().c_str(),
1617                     windowHandle->getInfo()->ownerUid);
1618         } else {
1619             ALOGW("Permission denied: injecting event from pid %d uid %d",
1620                     injectionState->injectorPid, injectionState->injectorUid);
1621         }
1622         return false;
1623     }
1624     return true;
1625 }
1626 
isWindowObscuredAtPointLocked(const sp<InputWindowHandle> & windowHandle,int32_t x,int32_t y) const1627 bool InputDispatcher::isWindowObscuredAtPointLocked(
1628         const sp<InputWindowHandle>& windowHandle, int32_t x, int32_t y) const {
1629     int32_t displayId = windowHandle->getInfo()->displayId;
1630     size_t numWindows = mWindowHandles.size();
1631     for (size_t i = 0; i < numWindows; i++) {
1632         sp<InputWindowHandle> otherHandle = mWindowHandles.itemAt(i);
1633         if (otherHandle == windowHandle) {
1634             break;
1635         }
1636 
1637         const InputWindowInfo* otherInfo = otherHandle->getInfo();
1638         if (otherInfo->displayId == displayId
1639                 && otherInfo->visible && !otherInfo->isTrustedOverlay()
1640                 && otherInfo->frameContainsPoint(x, y)) {
1641             return true;
1642         }
1643     }
1644     return false;
1645 }
1646 
1647 
isWindowObscuredLocked(const sp<InputWindowHandle> & windowHandle) const1648 bool InputDispatcher::isWindowObscuredLocked(const sp<InputWindowHandle>& windowHandle) const {
1649     int32_t displayId = windowHandle->getInfo()->displayId;
1650     const InputWindowInfo* windowInfo = windowHandle->getInfo();
1651     size_t numWindows = mWindowHandles.size();
1652     for (size_t i = 0; i < numWindows; i++) {
1653         sp<InputWindowHandle> otherHandle = mWindowHandles.itemAt(i);
1654         if (otherHandle == windowHandle) {
1655             break;
1656         }
1657 
1658         const InputWindowInfo* otherInfo = otherHandle->getInfo();
1659         if (otherInfo->displayId == displayId
1660                 && otherInfo->visible && !otherInfo->isTrustedOverlay()
1661                 && otherInfo->overlaps(windowInfo)) {
1662             return true;
1663         }
1664     }
1665     return false;
1666 }
1667 
checkWindowReadyForMoreInputLocked(nsecs_t currentTime,const sp<InputWindowHandle> & windowHandle,const EventEntry * eventEntry,const char * targetType)1668 std::string InputDispatcher::checkWindowReadyForMoreInputLocked(nsecs_t currentTime,
1669         const sp<InputWindowHandle>& windowHandle, const EventEntry* eventEntry,
1670         const char* targetType) {
1671     // If the window is paused then keep waiting.
1672     if (windowHandle->getInfo()->paused) {
1673         return StringPrintf("Waiting because the %s window is paused.", targetType);
1674     }
1675 
1676     // If the window's connection is not registered then keep waiting.
1677     ssize_t connectionIndex = getConnectionIndexLocked(windowHandle->getInputChannel());
1678     if (connectionIndex < 0) {
1679         return StringPrintf("Waiting because the %s window's input channel is not "
1680                 "registered with the input dispatcher.  The window may be in the process "
1681                 "of being removed.", targetType);
1682     }
1683 
1684     // If the connection is dead then keep waiting.
1685     sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
1686     if (connection->status != Connection::STATUS_NORMAL) {
1687         return StringPrintf("Waiting because the %s window's input connection is %s."
1688                 "The window may be in the process of being removed.", targetType,
1689                 connection->getStatusLabel());
1690     }
1691 
1692     // If the connection is backed up then keep waiting.
1693     if (connection->inputPublisherBlocked) {
1694         return StringPrintf("Waiting because the %s window's input channel is full.  "
1695                 "Outbound queue length: %d.  Wait queue length: %d.",
1696                 targetType, connection->outboundQueue.count(), connection->waitQueue.count());
1697     }
1698 
1699     // Ensure that the dispatch queues aren't too far backed up for this event.
1700     if (eventEntry->type == EventEntry::TYPE_KEY) {
1701         // If the event is a key event, then we must wait for all previous events to
1702         // complete before delivering it because previous events may have the
1703         // side-effect of transferring focus to a different window and we want to
1704         // ensure that the following keys are sent to the new window.
1705         //
1706         // Suppose the user touches a button in a window then immediately presses "A".
1707         // If the button causes a pop-up window to appear then we want to ensure that
1708         // the "A" key is delivered to the new pop-up window.  This is because users
1709         // often anticipate pending UI changes when typing on a keyboard.
1710         // To obtain this behavior, we must serialize key events with respect to all
1711         // prior input events.
1712         if (!connection->outboundQueue.isEmpty() || !connection->waitQueue.isEmpty()) {
1713             return StringPrintf("Waiting to send key event because the %s window has not "
1714                     "finished processing all of the input events that were previously "
1715                     "delivered to it.  Outbound queue length: %d.  Wait queue length: %d.",
1716                     targetType, connection->outboundQueue.count(), connection->waitQueue.count());
1717         }
1718     } else {
1719         // Touch events can always be sent to a window immediately because the user intended
1720         // to touch whatever was visible at the time.  Even if focus changes or a new
1721         // window appears moments later, the touch event was meant to be delivered to
1722         // whatever window happened to be on screen at the time.
1723         //
1724         // Generic motion events, such as trackball or joystick events are a little trickier.
1725         // Like key events, generic motion events are delivered to the focused window.
1726         // Unlike key events, generic motion events don't tend to transfer focus to other
1727         // windows and it is not important for them to be serialized.  So we prefer to deliver
1728         // generic motion events as soon as possible to improve efficiency and reduce lag
1729         // through batching.
1730         //
1731         // The one case where we pause input event delivery is when the wait queue is piling
1732         // up with lots of events because the application is not responding.
1733         // This condition ensures that ANRs are detected reliably.
1734         if (!connection->waitQueue.isEmpty()
1735                 && currentTime >= connection->waitQueue.head->deliveryTime
1736                         + STREAM_AHEAD_EVENT_TIMEOUT) {
1737             return StringPrintf("Waiting to send non-key event because the %s window has not "
1738                     "finished processing certain input events that were delivered to it over "
1739                     "%0.1fms ago.  Wait queue length: %d.  Wait queue head age: %0.1fms.",
1740                     targetType, STREAM_AHEAD_EVENT_TIMEOUT * 0.000001f,
1741                     connection->waitQueue.count(),
1742                     (currentTime - connection->waitQueue.head->deliveryTime) * 0.000001f);
1743         }
1744     }
1745     return "";
1746 }
1747 
getApplicationWindowLabelLocked(const sp<InputApplicationHandle> & applicationHandle,const sp<InputWindowHandle> & windowHandle)1748 std::string InputDispatcher::getApplicationWindowLabelLocked(
1749         const sp<InputApplicationHandle>& applicationHandle,
1750         const sp<InputWindowHandle>& windowHandle) {
1751     if (applicationHandle != NULL) {
1752         if (windowHandle != NULL) {
1753             std::string label(applicationHandle->getName());
1754             label += " - ";
1755             label += windowHandle->getName();
1756             return label;
1757         } else {
1758             return applicationHandle->getName();
1759         }
1760     } else if (windowHandle != NULL) {
1761         return windowHandle->getName();
1762     } else {
1763         return "<unknown application or window>";
1764     }
1765 }
1766 
pokeUserActivityLocked(const EventEntry * eventEntry)1767 void InputDispatcher::pokeUserActivityLocked(const EventEntry* eventEntry) {
1768     if (mFocusedWindowHandle != NULL) {
1769         const InputWindowInfo* info = mFocusedWindowHandle->getInfo();
1770         if (info->inputFeatures & InputWindowInfo::INPUT_FEATURE_DISABLE_USER_ACTIVITY) {
1771 #if DEBUG_DISPATCH_CYCLE
1772             ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
1773 #endif
1774             return;
1775         }
1776     }
1777 
1778     int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
1779     switch (eventEntry->type) {
1780     case EventEntry::TYPE_MOTION: {
1781         const MotionEntry* motionEntry = static_cast<const MotionEntry*>(eventEntry);
1782         if (motionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
1783             return;
1784         }
1785 
1786         if (MotionEvent::isTouchEvent(motionEntry->source, motionEntry->action)) {
1787             eventType = USER_ACTIVITY_EVENT_TOUCH;
1788         }
1789         break;
1790     }
1791     case EventEntry::TYPE_KEY: {
1792         const KeyEntry* keyEntry = static_cast<const KeyEntry*>(eventEntry);
1793         if (keyEntry->flags & AKEY_EVENT_FLAG_CANCELED) {
1794             return;
1795         }
1796         eventType = USER_ACTIVITY_EVENT_BUTTON;
1797         break;
1798     }
1799     }
1800 
1801     CommandEntry* commandEntry = postCommandLocked(
1802             & InputDispatcher::doPokeUserActivityLockedInterruptible);
1803     commandEntry->eventTime = eventEntry->eventTime;
1804     commandEntry->userActivityEventType = eventType;
1805 }
1806 
prepareDispatchCycleLocked(nsecs_t currentTime,const sp<Connection> & connection,EventEntry * eventEntry,const InputTarget * inputTarget)1807 void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
1808         const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget) {
1809 #if DEBUG_DISPATCH_CYCLE
1810     ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
1811             "xOffset=%f, yOffset=%f, scaleFactor=%f, "
1812             "pointerIds=0x%x",
1813             connection->getInputChannelName().c_str(), inputTarget->flags,
1814             inputTarget->xOffset, inputTarget->yOffset,
1815             inputTarget->scaleFactor, inputTarget->pointerIds.value);
1816 #endif
1817 
1818     // Skip this event if the connection status is not normal.
1819     // We don't want to enqueue additional outbound events if the connection is broken.
1820     if (connection->status != Connection::STATUS_NORMAL) {
1821 #if DEBUG_DISPATCH_CYCLE
1822         ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
1823                 connection->getInputChannelName().c_str(), connection->getStatusLabel());
1824 #endif
1825         return;
1826     }
1827 
1828     // Split a motion event if needed.
1829     if (inputTarget->flags & InputTarget::FLAG_SPLIT) {
1830         ALOG_ASSERT(eventEntry->type == EventEntry::TYPE_MOTION);
1831 
1832         MotionEntry* originalMotionEntry = static_cast<MotionEntry*>(eventEntry);
1833         if (inputTarget->pointerIds.count() != originalMotionEntry->pointerCount) {
1834             MotionEntry* splitMotionEntry = splitMotionEvent(
1835                     originalMotionEntry, inputTarget->pointerIds);
1836             if (!splitMotionEntry) {
1837                 return; // split event was dropped
1838             }
1839 #if DEBUG_FOCUS
1840             ALOGD("channel '%s' ~ Split motion event.",
1841                     connection->getInputChannelName().c_str());
1842             logOutboundMotionDetailsLocked("  ", splitMotionEntry);
1843 #endif
1844             enqueueDispatchEntriesLocked(currentTime, connection,
1845                     splitMotionEntry, inputTarget);
1846             splitMotionEntry->release();
1847             return;
1848         }
1849     }
1850 
1851     // Not splitting.  Enqueue dispatch entries for the event as is.
1852     enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
1853 }
1854 
enqueueDispatchEntriesLocked(nsecs_t currentTime,const sp<Connection> & connection,EventEntry * eventEntry,const InputTarget * inputTarget)1855 void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
1856         const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget) {
1857     bool wasEmpty = connection->outboundQueue.isEmpty();
1858 
1859     // Enqueue dispatch entries for the requested modes.
1860     enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1861             InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
1862     enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1863             InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
1864     enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1865             InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
1866     enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1867             InputTarget::FLAG_DISPATCH_AS_IS);
1868     enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1869             InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
1870     enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1871             InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
1872 
1873     // If the outbound queue was previously empty, start the dispatch cycle going.
1874     if (wasEmpty && !connection->outboundQueue.isEmpty()) {
1875         startDispatchCycleLocked(currentTime, connection);
1876     }
1877 }
1878 
enqueueDispatchEntryLocked(const sp<Connection> & connection,EventEntry * eventEntry,const InputTarget * inputTarget,int32_t dispatchMode)1879 void InputDispatcher::enqueueDispatchEntryLocked(
1880         const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget,
1881         int32_t dispatchMode) {
1882     int32_t inputTargetFlags = inputTarget->flags;
1883     if (!(inputTargetFlags & dispatchMode)) {
1884         return;
1885     }
1886     inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
1887 
1888     // This is a new event.
1889     // Enqueue a new dispatch entry onto the outbound queue for this connection.
1890     DispatchEntry* dispatchEntry = new DispatchEntry(eventEntry, // increments ref
1891             inputTargetFlags, inputTarget->xOffset, inputTarget->yOffset,
1892             inputTarget->scaleFactor);
1893 
1894     // Apply target flags and update the connection's input state.
1895     switch (eventEntry->type) {
1896     case EventEntry::TYPE_KEY: {
1897         KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
1898         dispatchEntry->resolvedAction = keyEntry->action;
1899         dispatchEntry->resolvedFlags = keyEntry->flags;
1900 
1901         if (!connection->inputState.trackKey(keyEntry,
1902                 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags)) {
1903 #if DEBUG_DISPATCH_CYCLE
1904             ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
1905                     connection->getInputChannelName().c_str());
1906 #endif
1907             delete dispatchEntry;
1908             return; // skip the inconsistent event
1909         }
1910         break;
1911     }
1912 
1913     case EventEntry::TYPE_MOTION: {
1914         MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
1915         if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
1916             dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
1917         } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
1918             dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
1919         } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
1920             dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
1921         } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
1922             dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
1923         } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
1924             dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
1925         } else {
1926             dispatchEntry->resolvedAction = motionEntry->action;
1927         }
1928         if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE
1929                 && !connection->inputState.isHovering(
1930                         motionEntry->deviceId, motionEntry->source, motionEntry->displayId)) {
1931 #if DEBUG_DISPATCH_CYCLE
1932         ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter event",
1933                 connection->getInputChannelName().c_str());
1934 #endif
1935             dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
1936         }
1937 
1938         dispatchEntry->resolvedFlags = motionEntry->flags;
1939         if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
1940             dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
1941         }
1942         if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
1943             dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1944         }
1945 
1946         if (!connection->inputState.trackMotion(motionEntry,
1947                 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags)) {
1948 #if DEBUG_DISPATCH_CYCLE
1949             ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion event",
1950                     connection->getInputChannelName().c_str());
1951 #endif
1952             delete dispatchEntry;
1953             return; // skip the inconsistent event
1954         }
1955         break;
1956     }
1957     }
1958 
1959     // Remember that we are waiting for this dispatch to complete.
1960     if (dispatchEntry->hasForegroundTarget()) {
1961         incrementPendingForegroundDispatchesLocked(eventEntry);
1962     }
1963 
1964     // Enqueue the dispatch entry.
1965     connection->outboundQueue.enqueueAtTail(dispatchEntry);
1966     traceOutboundQueueLengthLocked(connection);
1967 }
1968 
startDispatchCycleLocked(nsecs_t currentTime,const sp<Connection> & connection)1969 void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
1970         const sp<Connection>& connection) {
1971 #if DEBUG_DISPATCH_CYCLE
1972     ALOGD("channel '%s' ~ startDispatchCycle",
1973             connection->getInputChannelName().c_str());
1974 #endif
1975 
1976     while (connection->status == Connection::STATUS_NORMAL
1977             && !connection->outboundQueue.isEmpty()) {
1978         DispatchEntry* dispatchEntry = connection->outboundQueue.head;
1979         dispatchEntry->deliveryTime = currentTime;
1980 
1981         // Publish the event.
1982         status_t status;
1983         EventEntry* eventEntry = dispatchEntry->eventEntry;
1984         switch (eventEntry->type) {
1985         case EventEntry::TYPE_KEY: {
1986             KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
1987 
1988             // Publish the key event.
1989             status = connection->inputPublisher.publishKeyEvent(dispatchEntry->seq,
1990                     keyEntry->deviceId, keyEntry->source,
1991                     dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags,
1992                     keyEntry->keyCode, keyEntry->scanCode,
1993                     keyEntry->metaState, keyEntry->repeatCount, keyEntry->downTime,
1994                     keyEntry->eventTime);
1995             break;
1996         }
1997 
1998         case EventEntry::TYPE_MOTION: {
1999             MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
2000 
2001             PointerCoords scaledCoords[MAX_POINTERS];
2002             const PointerCoords* usingCoords = motionEntry->pointerCoords;
2003 
2004             // Set the X and Y offset depending on the input source.
2005             float xOffset, yOffset;
2006             if ((motionEntry->source & AINPUT_SOURCE_CLASS_POINTER)
2007                     && !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
2008                 float scaleFactor = dispatchEntry->scaleFactor;
2009                 xOffset = dispatchEntry->xOffset * scaleFactor;
2010                 yOffset = dispatchEntry->yOffset * scaleFactor;
2011                 if (scaleFactor != 1.0f) {
2012                     for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
2013                         scaledCoords[i] = motionEntry->pointerCoords[i];
2014                         scaledCoords[i].scale(scaleFactor);
2015                     }
2016                     usingCoords = scaledCoords;
2017                 }
2018             } else {
2019                 xOffset = 0.0f;
2020                 yOffset = 0.0f;
2021 
2022                 // We don't want the dispatch target to know.
2023                 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
2024                     for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
2025                         scaledCoords[i].clear();
2026                     }
2027                     usingCoords = scaledCoords;
2028                 }
2029             }
2030 
2031             // Publish the motion event.
2032             status = connection->inputPublisher.publishMotionEvent(dispatchEntry->seq,
2033                     motionEntry->deviceId, motionEntry->source, motionEntry->displayId,
2034                     dispatchEntry->resolvedAction, motionEntry->actionButton,
2035                     dispatchEntry->resolvedFlags, motionEntry->edgeFlags,
2036                     motionEntry->metaState, motionEntry->buttonState,
2037                     xOffset, yOffset, motionEntry->xPrecision, motionEntry->yPrecision,
2038                     motionEntry->downTime, motionEntry->eventTime,
2039                     motionEntry->pointerCount, motionEntry->pointerProperties,
2040                     usingCoords);
2041             break;
2042         }
2043 
2044         default:
2045             ALOG_ASSERT(false);
2046             return;
2047         }
2048 
2049         // Check the result.
2050         if (status) {
2051             if (status == WOULD_BLOCK) {
2052                 if (connection->waitQueue.isEmpty()) {
2053                     ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
2054                             "This is unexpected because the wait queue is empty, so the pipe "
2055                             "should be empty and we shouldn't have any problems writing an "
2056                             "event to it, status=%d", connection->getInputChannelName().c_str(),
2057                             status);
2058                     abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2059                 } else {
2060                     // Pipe is full and we are waiting for the app to finish process some events
2061                     // before sending more events to it.
2062 #if DEBUG_DISPATCH_CYCLE
2063                     ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
2064                             "waiting for the application to catch up",
2065                             connection->getInputChannelName().c_str());
2066 #endif
2067                     connection->inputPublisherBlocked = true;
2068                 }
2069             } else {
2070                 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
2071                         "status=%d", connection->getInputChannelName().c_str(), status);
2072                 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2073             }
2074             return;
2075         }
2076 
2077         // Re-enqueue the event on the wait queue.
2078         connection->outboundQueue.dequeue(dispatchEntry);
2079         traceOutboundQueueLengthLocked(connection);
2080         connection->waitQueue.enqueueAtTail(dispatchEntry);
2081         traceWaitQueueLengthLocked(connection);
2082     }
2083 }
2084 
finishDispatchCycleLocked(nsecs_t currentTime,const sp<Connection> & connection,uint32_t seq,bool handled)2085 void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
2086         const sp<Connection>& connection, uint32_t seq, bool handled) {
2087 #if DEBUG_DISPATCH_CYCLE
2088     ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
2089             connection->getInputChannelName().c_str(), seq, toString(handled));
2090 #endif
2091 
2092     connection->inputPublisherBlocked = false;
2093 
2094     if (connection->status == Connection::STATUS_BROKEN
2095             || connection->status == Connection::STATUS_ZOMBIE) {
2096         return;
2097     }
2098 
2099     // Notify other system components and prepare to start the next dispatch cycle.
2100     onDispatchCycleFinishedLocked(currentTime, connection, seq, handled);
2101 }
2102 
abortBrokenDispatchCycleLocked(nsecs_t currentTime,const sp<Connection> & connection,bool notify)2103 void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
2104         const sp<Connection>& connection, bool notify) {
2105 #if DEBUG_DISPATCH_CYCLE
2106     ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
2107             connection->getInputChannelName().c_str(), toString(notify));
2108 #endif
2109 
2110     // Clear the dispatch queues.
2111     drainDispatchQueueLocked(&connection->outboundQueue);
2112     traceOutboundQueueLengthLocked(connection);
2113     drainDispatchQueueLocked(&connection->waitQueue);
2114     traceWaitQueueLengthLocked(connection);
2115 
2116     // The connection appears to be unrecoverably broken.
2117     // Ignore already broken or zombie connections.
2118     if (connection->status == Connection::STATUS_NORMAL) {
2119         connection->status = Connection::STATUS_BROKEN;
2120 
2121         if (notify) {
2122             // Notify other system components.
2123             onDispatchCycleBrokenLocked(currentTime, connection);
2124         }
2125     }
2126 }
2127 
drainDispatchQueueLocked(Queue<DispatchEntry> * queue)2128 void InputDispatcher::drainDispatchQueueLocked(Queue<DispatchEntry>* queue) {
2129     while (!queue->isEmpty()) {
2130         DispatchEntry* dispatchEntry = queue->dequeueAtHead();
2131         releaseDispatchEntryLocked(dispatchEntry);
2132     }
2133 }
2134 
releaseDispatchEntryLocked(DispatchEntry * dispatchEntry)2135 void InputDispatcher::releaseDispatchEntryLocked(DispatchEntry* dispatchEntry) {
2136     if (dispatchEntry->hasForegroundTarget()) {
2137         decrementPendingForegroundDispatchesLocked(dispatchEntry->eventEntry);
2138     }
2139     delete dispatchEntry;
2140 }
2141 
handleReceiveCallback(int fd,int events,void * data)2142 int InputDispatcher::handleReceiveCallback(int fd, int events, void* data) {
2143     InputDispatcher* d = static_cast<InputDispatcher*>(data);
2144 
2145     { // acquire lock
2146         AutoMutex _l(d->mLock);
2147 
2148         ssize_t connectionIndex = d->mConnectionsByFd.indexOfKey(fd);
2149         if (connectionIndex < 0) {
2150             ALOGE("Received spurious receive callback for unknown input channel.  "
2151                     "fd=%d, events=0x%x", fd, events);
2152             return 0; // remove the callback
2153         }
2154 
2155         bool notify;
2156         sp<Connection> connection = d->mConnectionsByFd.valueAt(connectionIndex);
2157         if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
2158             if (!(events & ALOOPER_EVENT_INPUT)) {
2159                 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event.  "
2160                         "events=0x%x", connection->getInputChannelName().c_str(), events);
2161                 return 1;
2162             }
2163 
2164             nsecs_t currentTime = now();
2165             bool gotOne = false;
2166             status_t status;
2167             for (;;) {
2168                 uint32_t seq;
2169                 bool handled;
2170                 status = connection->inputPublisher.receiveFinishedSignal(&seq, &handled);
2171                 if (status) {
2172                     break;
2173                 }
2174                 d->finishDispatchCycleLocked(currentTime, connection, seq, handled);
2175                 gotOne = true;
2176             }
2177             if (gotOne) {
2178                 d->runCommandsLockedInterruptible();
2179                 if (status == WOULD_BLOCK) {
2180                     return 1;
2181                 }
2182             }
2183 
2184             notify = status != DEAD_OBJECT || !connection->monitor;
2185             if (notify) {
2186                 ALOGE("channel '%s' ~ Failed to receive finished signal.  status=%d",
2187                         connection->getInputChannelName().c_str(), status);
2188             }
2189         } else {
2190             // Monitor channels are never explicitly unregistered.
2191             // We do it automatically when the remote endpoint is closed so don't warn
2192             // about them.
2193             notify = !connection->monitor;
2194             if (notify) {
2195                 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred.  "
2196                         "events=0x%x", connection->getInputChannelName().c_str(), events);
2197             }
2198         }
2199 
2200         // Unregister the channel.
2201         d->unregisterInputChannelLocked(connection->inputChannel, notify);
2202         return 0; // remove the callback
2203     } // release lock
2204 }
2205 
synthesizeCancelationEventsForAllConnectionsLocked(const CancelationOptions & options)2206 void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
2207         const CancelationOptions& options) {
2208     for (size_t i = 0; i < mConnectionsByFd.size(); i++) {
2209         synthesizeCancelationEventsForConnectionLocked(
2210                 mConnectionsByFd.valueAt(i), options);
2211     }
2212 }
2213 
synthesizeCancelationEventsForMonitorsLocked(const CancelationOptions & options)2214 void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
2215         const CancelationOptions& options) {
2216     for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
2217         synthesizeCancelationEventsForInputChannelLocked(mMonitoringChannels[i], options);
2218     }
2219 }
2220 
synthesizeCancelationEventsForInputChannelLocked(const sp<InputChannel> & channel,const CancelationOptions & options)2221 void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
2222         const sp<InputChannel>& channel, const CancelationOptions& options) {
2223     ssize_t index = getConnectionIndexLocked(channel);
2224     if (index >= 0) {
2225         synthesizeCancelationEventsForConnectionLocked(
2226                 mConnectionsByFd.valueAt(index), options);
2227     }
2228 }
2229 
synthesizeCancelationEventsForConnectionLocked(const sp<Connection> & connection,const CancelationOptions & options)2230 void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
2231         const sp<Connection>& connection, const CancelationOptions& options) {
2232     if (connection->status == Connection::STATUS_BROKEN) {
2233         return;
2234     }
2235 
2236     nsecs_t currentTime = now();
2237 
2238     Vector<EventEntry*> cancelationEvents;
2239     connection->inputState.synthesizeCancelationEvents(currentTime,
2240             cancelationEvents, options);
2241 
2242     if (!cancelationEvents.isEmpty()) {
2243 #if DEBUG_OUTBOUND_EVENT_DETAILS
2244         ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
2245                 "with reality: %s, mode=%d.",
2246                 connection->getInputChannelName().c_str(), cancelationEvents.size(),
2247                 options.reason, options.mode);
2248 #endif
2249         for (size_t i = 0; i < cancelationEvents.size(); i++) {
2250             EventEntry* cancelationEventEntry = cancelationEvents.itemAt(i);
2251             switch (cancelationEventEntry->type) {
2252             case EventEntry::TYPE_KEY:
2253                 logOutboundKeyDetailsLocked("cancel - ",
2254                         static_cast<KeyEntry*>(cancelationEventEntry));
2255                 break;
2256             case EventEntry::TYPE_MOTION:
2257                 logOutboundMotionDetailsLocked("cancel - ",
2258                         static_cast<MotionEntry*>(cancelationEventEntry));
2259                 break;
2260             }
2261 
2262             InputTarget target;
2263             sp<InputWindowHandle> windowHandle = getWindowHandleLocked(connection->inputChannel);
2264             if (windowHandle != NULL) {
2265                 const InputWindowInfo* windowInfo = windowHandle->getInfo();
2266                 target.xOffset = -windowInfo->frameLeft;
2267                 target.yOffset = -windowInfo->frameTop;
2268                 target.scaleFactor = windowInfo->scaleFactor;
2269             } else {
2270                 target.xOffset = 0;
2271                 target.yOffset = 0;
2272                 target.scaleFactor = 1.0f;
2273             }
2274             target.inputChannel = connection->inputChannel;
2275             target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
2276 
2277             enqueueDispatchEntryLocked(connection, cancelationEventEntry, // increments ref
2278                     &target, InputTarget::FLAG_DISPATCH_AS_IS);
2279 
2280             cancelationEventEntry->release();
2281         }
2282 
2283         startDispatchCycleLocked(currentTime, connection);
2284     }
2285 }
2286 
2287 InputDispatcher::MotionEntry*
splitMotionEvent(const MotionEntry * originalMotionEntry,BitSet32 pointerIds)2288 InputDispatcher::splitMotionEvent(const MotionEntry* originalMotionEntry, BitSet32 pointerIds) {
2289     ALOG_ASSERT(pointerIds.value != 0);
2290 
2291     uint32_t splitPointerIndexMap[MAX_POINTERS];
2292     PointerProperties splitPointerProperties[MAX_POINTERS];
2293     PointerCoords splitPointerCoords[MAX_POINTERS];
2294 
2295     uint32_t originalPointerCount = originalMotionEntry->pointerCount;
2296     uint32_t splitPointerCount = 0;
2297 
2298     for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
2299             originalPointerIndex++) {
2300         const PointerProperties& pointerProperties =
2301                 originalMotionEntry->pointerProperties[originalPointerIndex];
2302         uint32_t pointerId = uint32_t(pointerProperties.id);
2303         if (pointerIds.hasBit(pointerId)) {
2304             splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
2305             splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
2306             splitPointerCoords[splitPointerCount].copyFrom(
2307                     originalMotionEntry->pointerCoords[originalPointerIndex]);
2308             splitPointerCount += 1;
2309         }
2310     }
2311 
2312     if (splitPointerCount != pointerIds.count()) {
2313         // This is bad.  We are missing some of the pointers that we expected to deliver.
2314         // Most likely this indicates that we received an ACTION_MOVE events that has
2315         // different pointer ids than we expected based on the previous ACTION_DOWN
2316         // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
2317         // in this way.
2318         ALOGW("Dropping split motion event because the pointer count is %d but "
2319                 "we expected there to be %d pointers.  This probably means we received "
2320                 "a broken sequence of pointer ids from the input device.",
2321                 splitPointerCount, pointerIds.count());
2322         return NULL;
2323     }
2324 
2325     int32_t action = originalMotionEntry->action;
2326     int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
2327     if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
2328             || maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2329         int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
2330         const PointerProperties& pointerProperties =
2331                 originalMotionEntry->pointerProperties[originalPointerIndex];
2332         uint32_t pointerId = uint32_t(pointerProperties.id);
2333         if (pointerIds.hasBit(pointerId)) {
2334             if (pointerIds.count() == 1) {
2335                 // The first/last pointer went down/up.
2336                 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
2337                         ? AMOTION_EVENT_ACTION_DOWN : AMOTION_EVENT_ACTION_UP;
2338             } else {
2339                 // A secondary pointer went down/up.
2340                 uint32_t splitPointerIndex = 0;
2341                 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
2342                     splitPointerIndex += 1;
2343                 }
2344                 action = maskedAction | (splitPointerIndex
2345                         << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
2346             }
2347         } else {
2348             // An unrelated pointer changed.
2349             action = AMOTION_EVENT_ACTION_MOVE;
2350         }
2351     }
2352 
2353     MotionEntry* splitMotionEntry = new MotionEntry(
2354             originalMotionEntry->eventTime,
2355             originalMotionEntry->deviceId,
2356             originalMotionEntry->source,
2357             originalMotionEntry->policyFlags,
2358             action,
2359             originalMotionEntry->actionButton,
2360             originalMotionEntry->flags,
2361             originalMotionEntry->metaState,
2362             originalMotionEntry->buttonState,
2363             originalMotionEntry->edgeFlags,
2364             originalMotionEntry->xPrecision,
2365             originalMotionEntry->yPrecision,
2366             originalMotionEntry->downTime,
2367             originalMotionEntry->displayId,
2368             splitPointerCount, splitPointerProperties, splitPointerCoords, 0, 0);
2369 
2370     if (originalMotionEntry->injectionState) {
2371         splitMotionEntry->injectionState = originalMotionEntry->injectionState;
2372         splitMotionEntry->injectionState->refCount += 1;
2373     }
2374 
2375     return splitMotionEntry;
2376 }
2377 
notifyConfigurationChanged(const NotifyConfigurationChangedArgs * args)2378 void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
2379 #if DEBUG_INBOUND_EVENT_DETAILS
2380     ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
2381 #endif
2382 
2383     bool needWake;
2384     { // acquire lock
2385         AutoMutex _l(mLock);
2386 
2387         ConfigurationChangedEntry* newEntry = new ConfigurationChangedEntry(args->eventTime);
2388         needWake = enqueueInboundEventLocked(newEntry);
2389     } // release lock
2390 
2391     if (needWake) {
2392         mLooper->wake();
2393     }
2394 }
2395 
notifyKey(const NotifyKeyArgs * args)2396 void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
2397 #if DEBUG_INBOUND_EVENT_DETAILS
2398     ALOGD("notifyKey - eventTime=%" PRId64
2399             ", deviceId=%d, source=0x%x, policyFlags=0x%x, action=0x%x, "
2400             "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
2401             args->eventTime, args->deviceId, args->source, args->policyFlags,
2402             args->action, args->flags, args->keyCode, args->scanCode,
2403             args->metaState, args->downTime);
2404 #endif
2405     if (!validateKeyEvent(args->action)) {
2406         return;
2407     }
2408 
2409     uint32_t policyFlags = args->policyFlags;
2410     int32_t flags = args->flags;
2411     int32_t metaState = args->metaState;
2412     if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
2413         policyFlags |= POLICY_FLAG_VIRTUAL;
2414         flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
2415     }
2416     if (policyFlags & POLICY_FLAG_FUNCTION) {
2417         metaState |= AMETA_FUNCTION_ON;
2418     }
2419 
2420     policyFlags |= POLICY_FLAG_TRUSTED;
2421 
2422     int32_t keyCode = args->keyCode;
2423     if (metaState & AMETA_META_ON && args->action == AKEY_EVENT_ACTION_DOWN) {
2424         int32_t newKeyCode = AKEYCODE_UNKNOWN;
2425         if (keyCode == AKEYCODE_DEL) {
2426             newKeyCode = AKEYCODE_BACK;
2427         } else if (keyCode == AKEYCODE_ENTER) {
2428             newKeyCode = AKEYCODE_HOME;
2429         }
2430         if (newKeyCode != AKEYCODE_UNKNOWN) {
2431             AutoMutex _l(mLock);
2432             struct KeyReplacement replacement = {keyCode, args->deviceId};
2433             mReplacedKeys.add(replacement, newKeyCode);
2434             keyCode = newKeyCode;
2435             metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
2436         }
2437     } else if (args->action == AKEY_EVENT_ACTION_UP) {
2438         // In order to maintain a consistent stream of up and down events, check to see if the key
2439         // going up is one we've replaced in a down event and haven't yet replaced in an up event,
2440         // even if the modifier was released between the down and the up events.
2441         AutoMutex _l(mLock);
2442         struct KeyReplacement replacement = {keyCode, args->deviceId};
2443         ssize_t index = mReplacedKeys.indexOfKey(replacement);
2444         if (index >= 0) {
2445             keyCode = mReplacedKeys.valueAt(index);
2446             mReplacedKeys.removeItemsAt(index);
2447             metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
2448         }
2449     }
2450 
2451     KeyEvent event;
2452     event.initialize(args->deviceId, args->source, args->action,
2453             flags, keyCode, args->scanCode, metaState, 0,
2454             args->downTime, args->eventTime);
2455 
2456     android::base::Timer t;
2457     mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
2458     if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2459         ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
2460                 std::to_string(t.duration().count()).c_str());
2461     }
2462 
2463     bool needWake;
2464     { // acquire lock
2465         mLock.lock();
2466 
2467         if (shouldSendKeyToInputFilterLocked(args)) {
2468             mLock.unlock();
2469 
2470             policyFlags |= POLICY_FLAG_FILTERED;
2471             if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2472                 return; // event was consumed by the filter
2473             }
2474 
2475             mLock.lock();
2476         }
2477 
2478         int32_t repeatCount = 0;
2479         KeyEntry* newEntry = new KeyEntry(args->eventTime,
2480                 args->deviceId, args->source, policyFlags,
2481                 args->action, flags, keyCode, args->scanCode,
2482                 metaState, repeatCount, args->downTime);
2483 
2484         needWake = enqueueInboundEventLocked(newEntry);
2485         mLock.unlock();
2486     } // release lock
2487 
2488     if (needWake) {
2489         mLooper->wake();
2490     }
2491 }
2492 
shouldSendKeyToInputFilterLocked(const NotifyKeyArgs * args)2493 bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
2494     return mInputFilterEnabled;
2495 }
2496 
notifyMotion(const NotifyMotionArgs * args)2497 void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
2498 #if DEBUG_INBOUND_EVENT_DETAILS
2499     ALOGD("notifyMotion - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, policyFlags=0x%x, "
2500             "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x,"
2501             "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
2502             args->eventTime, args->deviceId, args->source, args->policyFlags,
2503             args->action, args->actionButton, args->flags, args->metaState, args->buttonState,
2504             args->edgeFlags, args->xPrecision, args->yPrecision, args->downTime);
2505     for (uint32_t i = 0; i < args->pointerCount; i++) {
2506         ALOGD("  Pointer %d: id=%d, toolType=%d, "
2507                 "x=%f, y=%f, pressure=%f, size=%f, "
2508                 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
2509                 "orientation=%f",
2510                 i, args->pointerProperties[i].id,
2511                 args->pointerProperties[i].toolType,
2512                 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
2513                 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
2514                 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
2515                 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
2516                 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
2517                 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
2518                 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
2519                 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
2520                 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
2521     }
2522 #endif
2523     if (!validateMotionEvent(args->action, args->actionButton,
2524                 args->pointerCount, args->pointerProperties)) {
2525         return;
2526     }
2527 
2528     uint32_t policyFlags = args->policyFlags;
2529     policyFlags |= POLICY_FLAG_TRUSTED;
2530 
2531     android::base::Timer t;
2532     mPolicy->interceptMotionBeforeQueueing(args->eventTime, /*byref*/ policyFlags);
2533     if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2534         ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
2535                 std::to_string(t.duration().count()).c_str());
2536     }
2537 
2538     bool needWake;
2539     { // acquire lock
2540         mLock.lock();
2541 
2542         if (shouldSendMotionToInputFilterLocked(args)) {
2543             mLock.unlock();
2544 
2545             MotionEvent event;
2546             event.initialize(args->deviceId, args->source, args->action, args->actionButton,
2547                     args->flags, args->edgeFlags, args->metaState, args->buttonState,
2548                     0, 0, args->xPrecision, args->yPrecision,
2549                     args->downTime, args->eventTime,
2550                     args->pointerCount, args->pointerProperties, args->pointerCoords);
2551 
2552             policyFlags |= POLICY_FLAG_FILTERED;
2553             if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2554                 return; // event was consumed by the filter
2555             }
2556 
2557             mLock.lock();
2558         }
2559 
2560         // Just enqueue a new motion event.
2561         MotionEntry* newEntry = new MotionEntry(args->eventTime,
2562                 args->deviceId, args->source, policyFlags,
2563                 args->action, args->actionButton, args->flags,
2564                 args->metaState, args->buttonState,
2565                 args->edgeFlags, args->xPrecision, args->yPrecision, args->downTime,
2566                 args->displayId,
2567                 args->pointerCount, args->pointerProperties, args->pointerCoords, 0, 0);
2568 
2569         needWake = enqueueInboundEventLocked(newEntry);
2570         mLock.unlock();
2571     } // release lock
2572 
2573     if (needWake) {
2574         mLooper->wake();
2575     }
2576 }
2577 
shouldSendMotionToInputFilterLocked(const NotifyMotionArgs * args)2578 bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
2579     // TODO: support sending secondary display events to input filter
2580     return mInputFilterEnabled && isMainDisplay(args->displayId);
2581 }
2582 
notifySwitch(const NotifySwitchArgs * args)2583 void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
2584 #if DEBUG_INBOUND_EVENT_DETAILS
2585     ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
2586             "switchMask=0x%08x",
2587             args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
2588 #endif
2589 
2590     uint32_t policyFlags = args->policyFlags;
2591     policyFlags |= POLICY_FLAG_TRUSTED;
2592     mPolicy->notifySwitch(args->eventTime,
2593             args->switchValues, args->switchMask, policyFlags);
2594 }
2595 
notifyDeviceReset(const NotifyDeviceResetArgs * args)2596 void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
2597 #if DEBUG_INBOUND_EVENT_DETAILS
2598     ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d",
2599             args->eventTime, args->deviceId);
2600 #endif
2601 
2602     bool needWake;
2603     { // acquire lock
2604         AutoMutex _l(mLock);
2605 
2606         DeviceResetEntry* newEntry = new DeviceResetEntry(args->eventTime, args->deviceId);
2607         needWake = enqueueInboundEventLocked(newEntry);
2608     } // release lock
2609 
2610     if (needWake) {
2611         mLooper->wake();
2612     }
2613 }
2614 
injectInputEvent(const InputEvent * event,int32_t displayId,int32_t injectorPid,int32_t injectorUid,int32_t syncMode,int32_t timeoutMillis,uint32_t policyFlags)2615 int32_t InputDispatcher::injectInputEvent(const InputEvent* event, int32_t displayId,
2616         int32_t injectorPid, int32_t injectorUid, int32_t syncMode, int32_t timeoutMillis,
2617         uint32_t policyFlags) {
2618 #if DEBUG_INBOUND_EVENT_DETAILS
2619     ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
2620             "syncMode=%d, timeoutMillis=%d, policyFlags=0x%08x, displayId=%d",
2621             event->getType(), injectorPid, injectorUid, syncMode, timeoutMillis, policyFlags,
2622             displayId);
2623 #endif
2624 
2625     nsecs_t endTime = now() + milliseconds_to_nanoseconds(timeoutMillis);
2626 
2627     policyFlags |= POLICY_FLAG_INJECTED;
2628     if (hasInjectionPermission(injectorPid, injectorUid)) {
2629         policyFlags |= POLICY_FLAG_TRUSTED;
2630     }
2631 
2632     EventEntry* firstInjectedEntry;
2633     EventEntry* lastInjectedEntry;
2634     switch (event->getType()) {
2635     case AINPUT_EVENT_TYPE_KEY: {
2636         const KeyEvent* keyEvent = static_cast<const KeyEvent*>(event);
2637         int32_t action = keyEvent->getAction();
2638         if (! validateKeyEvent(action)) {
2639             return INPUT_EVENT_INJECTION_FAILED;
2640         }
2641 
2642         int32_t flags = keyEvent->getFlags();
2643         if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
2644             policyFlags |= POLICY_FLAG_VIRTUAL;
2645         }
2646 
2647         if (!(policyFlags & POLICY_FLAG_FILTERED)) {
2648             android::base::Timer t;
2649             mPolicy->interceptKeyBeforeQueueing(keyEvent, /*byref*/ policyFlags);
2650             if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2651                 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
2652                         std::to_string(t.duration().count()).c_str());
2653             }
2654         }
2655 
2656         mLock.lock();
2657         firstInjectedEntry = new KeyEntry(keyEvent->getEventTime(),
2658                 keyEvent->getDeviceId(), keyEvent->getSource(),
2659                 policyFlags, action, flags,
2660                 keyEvent->getKeyCode(), keyEvent->getScanCode(), keyEvent->getMetaState(),
2661                 keyEvent->getRepeatCount(), keyEvent->getDownTime());
2662         lastInjectedEntry = firstInjectedEntry;
2663         break;
2664     }
2665 
2666     case AINPUT_EVENT_TYPE_MOTION: {
2667         const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
2668         int32_t action = motionEvent->getAction();
2669         size_t pointerCount = motionEvent->getPointerCount();
2670         const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
2671         int32_t actionButton = motionEvent->getActionButton();
2672         if (! validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
2673             return INPUT_EVENT_INJECTION_FAILED;
2674         }
2675 
2676         if (!(policyFlags & POLICY_FLAG_FILTERED)) {
2677             nsecs_t eventTime = motionEvent->getEventTime();
2678             android::base::Timer t;
2679             mPolicy->interceptMotionBeforeQueueing(eventTime, /*byref*/ policyFlags);
2680             if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2681                 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
2682                         std::to_string(t.duration().count()).c_str());
2683             }
2684         }
2685 
2686         mLock.lock();
2687         const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
2688         const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
2689         firstInjectedEntry = new MotionEntry(*sampleEventTimes,
2690                 motionEvent->getDeviceId(), motionEvent->getSource(), policyFlags,
2691                 action, actionButton, motionEvent->getFlags(),
2692                 motionEvent->getMetaState(), motionEvent->getButtonState(),
2693                 motionEvent->getEdgeFlags(),
2694                 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
2695                 motionEvent->getDownTime(), displayId,
2696                 uint32_t(pointerCount), pointerProperties, samplePointerCoords,
2697                 motionEvent->getXOffset(), motionEvent->getYOffset());
2698         lastInjectedEntry = firstInjectedEntry;
2699         for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
2700             sampleEventTimes += 1;
2701             samplePointerCoords += pointerCount;
2702             MotionEntry* nextInjectedEntry = new MotionEntry(*sampleEventTimes,
2703                     motionEvent->getDeviceId(), motionEvent->getSource(), policyFlags,
2704                     action, actionButton, motionEvent->getFlags(),
2705                     motionEvent->getMetaState(), motionEvent->getButtonState(),
2706                     motionEvent->getEdgeFlags(),
2707                     motionEvent->getXPrecision(), motionEvent->getYPrecision(),
2708                     motionEvent->getDownTime(), displayId,
2709                     uint32_t(pointerCount), pointerProperties, samplePointerCoords,
2710                     motionEvent->getXOffset(), motionEvent->getYOffset());
2711             lastInjectedEntry->next = nextInjectedEntry;
2712             lastInjectedEntry = nextInjectedEntry;
2713         }
2714         break;
2715     }
2716 
2717     default:
2718         ALOGW("Cannot inject event of type %d", event->getType());
2719         return INPUT_EVENT_INJECTION_FAILED;
2720     }
2721 
2722     InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
2723     if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
2724         injectionState->injectionIsAsync = true;
2725     }
2726 
2727     injectionState->refCount += 1;
2728     lastInjectedEntry->injectionState = injectionState;
2729 
2730     bool needWake = false;
2731     for (EventEntry* entry = firstInjectedEntry; entry != NULL; ) {
2732         EventEntry* nextEntry = entry->next;
2733         needWake |= enqueueInboundEventLocked(entry);
2734         entry = nextEntry;
2735     }
2736 
2737     mLock.unlock();
2738 
2739     if (needWake) {
2740         mLooper->wake();
2741     }
2742 
2743     int32_t injectionResult;
2744     { // acquire lock
2745         AutoMutex _l(mLock);
2746 
2747         if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
2748             injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
2749         } else {
2750             for (;;) {
2751                 injectionResult = injectionState->injectionResult;
2752                 if (injectionResult != INPUT_EVENT_INJECTION_PENDING) {
2753                     break;
2754                 }
2755 
2756                 nsecs_t remainingTimeout = endTime - now();
2757                 if (remainingTimeout <= 0) {
2758 #if DEBUG_INJECTION
2759                     ALOGD("injectInputEvent - Timed out waiting for injection result "
2760                             "to become available.");
2761 #endif
2762                     injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
2763                     break;
2764                 }
2765 
2766                 mInjectionResultAvailableCondition.waitRelative(mLock, remainingTimeout);
2767             }
2768 
2769             if (injectionResult == INPUT_EVENT_INJECTION_SUCCEEDED
2770                     && syncMode == INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED) {
2771                 while (injectionState->pendingForegroundDispatches != 0) {
2772 #if DEBUG_INJECTION
2773                     ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
2774                             injectionState->pendingForegroundDispatches);
2775 #endif
2776                     nsecs_t remainingTimeout = endTime - now();
2777                     if (remainingTimeout <= 0) {
2778 #if DEBUG_INJECTION
2779                     ALOGD("injectInputEvent - Timed out waiting for pending foreground "
2780                             "dispatches to finish.");
2781 #endif
2782                         injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
2783                         break;
2784                     }
2785 
2786                     mInjectionSyncFinishedCondition.waitRelative(mLock, remainingTimeout);
2787                 }
2788             }
2789         }
2790 
2791         injectionState->release();
2792     } // release lock
2793 
2794 #if DEBUG_INJECTION
2795     ALOGD("injectInputEvent - Finished with result %d.  "
2796             "injectorPid=%d, injectorUid=%d",
2797             injectionResult, injectorPid, injectorUid);
2798 #endif
2799 
2800     return injectionResult;
2801 }
2802 
hasInjectionPermission(int32_t injectorPid,int32_t injectorUid)2803 bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
2804     return injectorUid == 0
2805             || mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
2806 }
2807 
setInjectionResultLocked(EventEntry * entry,int32_t injectionResult)2808 void InputDispatcher::setInjectionResultLocked(EventEntry* entry, int32_t injectionResult) {
2809     InjectionState* injectionState = entry->injectionState;
2810     if (injectionState) {
2811 #if DEBUG_INJECTION
2812         ALOGD("Setting input event injection result to %d.  "
2813                 "injectorPid=%d, injectorUid=%d",
2814                  injectionResult, injectionState->injectorPid, injectionState->injectorUid);
2815 #endif
2816 
2817         if (injectionState->injectionIsAsync
2818                 && !(entry->policyFlags & POLICY_FLAG_FILTERED)) {
2819             // Log the outcome since the injector did not wait for the injection result.
2820             switch (injectionResult) {
2821             case INPUT_EVENT_INJECTION_SUCCEEDED:
2822                 ALOGV("Asynchronous input event injection succeeded.");
2823                 break;
2824             case INPUT_EVENT_INJECTION_FAILED:
2825                 ALOGW("Asynchronous input event injection failed.");
2826                 break;
2827             case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
2828                 ALOGW("Asynchronous input event injection permission denied.");
2829                 break;
2830             case INPUT_EVENT_INJECTION_TIMED_OUT:
2831                 ALOGW("Asynchronous input event injection timed out.");
2832                 break;
2833             }
2834         }
2835 
2836         injectionState->injectionResult = injectionResult;
2837         mInjectionResultAvailableCondition.broadcast();
2838     }
2839 }
2840 
incrementPendingForegroundDispatchesLocked(EventEntry * entry)2841 void InputDispatcher::incrementPendingForegroundDispatchesLocked(EventEntry* entry) {
2842     InjectionState* injectionState = entry->injectionState;
2843     if (injectionState) {
2844         injectionState->pendingForegroundDispatches += 1;
2845     }
2846 }
2847 
decrementPendingForegroundDispatchesLocked(EventEntry * entry)2848 void InputDispatcher::decrementPendingForegroundDispatchesLocked(EventEntry* entry) {
2849     InjectionState* injectionState = entry->injectionState;
2850     if (injectionState) {
2851         injectionState->pendingForegroundDispatches -= 1;
2852 
2853         if (injectionState->pendingForegroundDispatches == 0) {
2854             mInjectionSyncFinishedCondition.broadcast();
2855         }
2856     }
2857 }
2858 
getWindowHandleLocked(const sp<InputChannel> & inputChannel) const2859 sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
2860         const sp<InputChannel>& inputChannel) const {
2861     size_t numWindows = mWindowHandles.size();
2862     for (size_t i = 0; i < numWindows; i++) {
2863         const sp<InputWindowHandle>& windowHandle = mWindowHandles.itemAt(i);
2864         if (windowHandle->getInputChannel() == inputChannel) {
2865             return windowHandle;
2866         }
2867     }
2868     return NULL;
2869 }
2870 
hasWindowHandleLocked(const sp<InputWindowHandle> & windowHandle) const2871 bool InputDispatcher::hasWindowHandleLocked(
2872         const sp<InputWindowHandle>& windowHandle) const {
2873     size_t numWindows = mWindowHandles.size();
2874     for (size_t i = 0; i < numWindows; i++) {
2875         if (mWindowHandles.itemAt(i) == windowHandle) {
2876             return true;
2877         }
2878     }
2879     return false;
2880 }
2881 
setInputWindows(const Vector<sp<InputWindowHandle>> & inputWindowHandles)2882 void InputDispatcher::setInputWindows(const Vector<sp<InputWindowHandle> >& inputWindowHandles) {
2883 #if DEBUG_FOCUS
2884     ALOGD("setInputWindows");
2885 #endif
2886     { // acquire lock
2887         AutoMutex _l(mLock);
2888 
2889         Vector<sp<InputWindowHandle> > oldWindowHandles = mWindowHandles;
2890         mWindowHandles = inputWindowHandles;
2891 
2892         sp<InputWindowHandle> newFocusedWindowHandle;
2893         bool foundHoveredWindow = false;
2894         for (size_t i = 0; i < mWindowHandles.size(); i++) {
2895             const sp<InputWindowHandle>& windowHandle = mWindowHandles.itemAt(i);
2896             if (!windowHandle->updateInfo() || windowHandle->getInputChannel() == NULL) {
2897                 mWindowHandles.removeAt(i--);
2898                 continue;
2899             }
2900             if (windowHandle->getInfo()->hasFocus) {
2901                 newFocusedWindowHandle = windowHandle;
2902             }
2903             if (windowHandle == mLastHoverWindowHandle) {
2904                 foundHoveredWindow = true;
2905             }
2906         }
2907 
2908         if (!foundHoveredWindow) {
2909             mLastHoverWindowHandle = NULL;
2910         }
2911 
2912         if (mFocusedWindowHandle != newFocusedWindowHandle) {
2913             if (mFocusedWindowHandle != NULL) {
2914 #if DEBUG_FOCUS
2915                 ALOGD("Focus left window: %s",
2916                         mFocusedWindowHandle->getName().c_str());
2917 #endif
2918                 sp<InputChannel> focusedInputChannel = mFocusedWindowHandle->getInputChannel();
2919                 if (focusedInputChannel != NULL) {
2920                     CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
2921                             "focus left window");
2922                     synthesizeCancelationEventsForInputChannelLocked(
2923                             focusedInputChannel, options);
2924                 }
2925             }
2926             if (newFocusedWindowHandle != NULL) {
2927 #if DEBUG_FOCUS
2928                 ALOGD("Focus entered window: %s",
2929                         newFocusedWindowHandle->getName().c_str());
2930 #endif
2931             }
2932             mFocusedWindowHandle = newFocusedWindowHandle;
2933         }
2934 
2935         for (size_t d = 0; d < mTouchStatesByDisplay.size(); d++) {
2936             TouchState& state = mTouchStatesByDisplay.editValueAt(d);
2937             for (size_t i = 0; i < state.windows.size(); ) {
2938                 TouchedWindow& touchedWindow = state.windows.editItemAt(i);
2939                 if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
2940 #if DEBUG_FOCUS
2941                     ALOGD("Touched window was removed: %s",
2942                             touchedWindow.windowHandle->getName().c_str());
2943 #endif
2944                     sp<InputChannel> touchedInputChannel =
2945                             touchedWindow.windowHandle->getInputChannel();
2946                     if (touchedInputChannel != NULL) {
2947                         CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
2948                                 "touched window was removed");
2949                         synthesizeCancelationEventsForInputChannelLocked(
2950                                 touchedInputChannel, options);
2951                     }
2952                     state.windows.removeAt(i);
2953                 } else {
2954                   ++i;
2955                 }
2956             }
2957         }
2958 
2959         // Release information for windows that are no longer present.
2960         // This ensures that unused input channels are released promptly.
2961         // Otherwise, they might stick around until the window handle is destroyed
2962         // which might not happen until the next GC.
2963         for (size_t i = 0; i < oldWindowHandles.size(); i++) {
2964             const sp<InputWindowHandle>& oldWindowHandle = oldWindowHandles.itemAt(i);
2965             if (!hasWindowHandleLocked(oldWindowHandle)) {
2966 #if DEBUG_FOCUS
2967                 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
2968 #endif
2969                 oldWindowHandle->releaseInfo();
2970             }
2971         }
2972     } // release lock
2973 
2974     // Wake up poll loop since it may need to make new input dispatching choices.
2975     mLooper->wake();
2976 }
2977 
setFocusedApplication(const sp<InputApplicationHandle> & inputApplicationHandle)2978 void InputDispatcher::setFocusedApplication(
2979         const sp<InputApplicationHandle>& inputApplicationHandle) {
2980 #if DEBUG_FOCUS
2981     ALOGD("setFocusedApplication");
2982 #endif
2983     { // acquire lock
2984         AutoMutex _l(mLock);
2985 
2986         if (inputApplicationHandle != NULL && inputApplicationHandle->updateInfo()) {
2987             if (mFocusedApplicationHandle != inputApplicationHandle) {
2988                 if (mFocusedApplicationHandle != NULL) {
2989                     resetANRTimeoutsLocked();
2990                     mFocusedApplicationHandle->releaseInfo();
2991                 }
2992                 mFocusedApplicationHandle = inputApplicationHandle;
2993             }
2994         } else if (mFocusedApplicationHandle != NULL) {
2995             resetANRTimeoutsLocked();
2996             mFocusedApplicationHandle->releaseInfo();
2997             mFocusedApplicationHandle.clear();
2998         }
2999 
3000 #if DEBUG_FOCUS
3001         //logDispatchStateLocked();
3002 #endif
3003     } // release lock
3004 
3005     // Wake up poll loop since it may need to make new input dispatching choices.
3006     mLooper->wake();
3007 }
3008 
setInputDispatchMode(bool enabled,bool frozen)3009 void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
3010 #if DEBUG_FOCUS
3011     ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
3012 #endif
3013 
3014     bool changed;
3015     { // acquire lock
3016         AutoMutex _l(mLock);
3017 
3018         if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
3019             if (mDispatchFrozen && !frozen) {
3020                 resetANRTimeoutsLocked();
3021             }
3022 
3023             if (mDispatchEnabled && !enabled) {
3024                 resetAndDropEverythingLocked("dispatcher is being disabled");
3025             }
3026 
3027             mDispatchEnabled = enabled;
3028             mDispatchFrozen = frozen;
3029             changed = true;
3030         } else {
3031             changed = false;
3032         }
3033 
3034 #if DEBUG_FOCUS
3035         //logDispatchStateLocked();
3036 #endif
3037     } // release lock
3038 
3039     if (changed) {
3040         // Wake up poll loop since it may need to make new input dispatching choices.
3041         mLooper->wake();
3042     }
3043 }
3044 
setInputFilterEnabled(bool enabled)3045 void InputDispatcher::setInputFilterEnabled(bool enabled) {
3046 #if DEBUG_FOCUS
3047     ALOGD("setInputFilterEnabled: enabled=%d", enabled);
3048 #endif
3049 
3050     { // acquire lock
3051         AutoMutex _l(mLock);
3052 
3053         if (mInputFilterEnabled == enabled) {
3054             return;
3055         }
3056 
3057         mInputFilterEnabled = enabled;
3058         resetAndDropEverythingLocked("input filter is being enabled or disabled");
3059     } // release lock
3060 
3061     // Wake up poll loop since there might be work to do to drop everything.
3062     mLooper->wake();
3063 }
3064 
transferTouchFocus(const sp<InputChannel> & fromChannel,const sp<InputChannel> & toChannel)3065 bool InputDispatcher::transferTouchFocus(const sp<InputChannel>& fromChannel,
3066         const sp<InputChannel>& toChannel) {
3067 #if DEBUG_FOCUS
3068     ALOGD("transferTouchFocus: fromChannel=%s, toChannel=%s",
3069             fromChannel->getName().c_str(), toChannel->getName().c_str());
3070 #endif
3071     { // acquire lock
3072         AutoMutex _l(mLock);
3073 
3074         sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromChannel);
3075         sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toChannel);
3076         if (fromWindowHandle == NULL || toWindowHandle == NULL) {
3077 #if DEBUG_FOCUS
3078             ALOGD("Cannot transfer focus because from or to window not found.");
3079 #endif
3080             return false;
3081         }
3082         if (fromWindowHandle == toWindowHandle) {
3083 #if DEBUG_FOCUS
3084             ALOGD("Trivial transfer to same window.");
3085 #endif
3086             return true;
3087         }
3088         if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
3089 #if DEBUG_FOCUS
3090             ALOGD("Cannot transfer focus because windows are on different displays.");
3091 #endif
3092             return false;
3093         }
3094 
3095         bool found = false;
3096         for (size_t d = 0; d < mTouchStatesByDisplay.size(); d++) {
3097             TouchState& state = mTouchStatesByDisplay.editValueAt(d);
3098             for (size_t i = 0; i < state.windows.size(); i++) {
3099                 const TouchedWindow& touchedWindow = state.windows[i];
3100                 if (touchedWindow.windowHandle == fromWindowHandle) {
3101                     int32_t oldTargetFlags = touchedWindow.targetFlags;
3102                     BitSet32 pointerIds = touchedWindow.pointerIds;
3103 
3104                     state.windows.removeAt(i);
3105 
3106                     int32_t newTargetFlags = oldTargetFlags
3107                             & (InputTarget::FLAG_FOREGROUND
3108                                     | InputTarget::FLAG_SPLIT | InputTarget::FLAG_DISPATCH_AS_IS);
3109                     state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
3110 
3111                     found = true;
3112                     goto Found;
3113                 }
3114             }
3115         }
3116 Found:
3117 
3118         if (! found) {
3119 #if DEBUG_FOCUS
3120             ALOGD("Focus transfer failed because from window did not have focus.");
3121 #endif
3122             return false;
3123         }
3124 
3125         ssize_t fromConnectionIndex = getConnectionIndexLocked(fromChannel);
3126         ssize_t toConnectionIndex = getConnectionIndexLocked(toChannel);
3127         if (fromConnectionIndex >= 0 && toConnectionIndex >= 0) {
3128             sp<Connection> fromConnection = mConnectionsByFd.valueAt(fromConnectionIndex);
3129             sp<Connection> toConnection = mConnectionsByFd.valueAt(toConnectionIndex);
3130 
3131             fromConnection->inputState.copyPointerStateTo(toConnection->inputState);
3132             CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
3133                     "transferring touch focus from this window to another window");
3134             synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
3135         }
3136 
3137 #if DEBUG_FOCUS
3138         logDispatchStateLocked();
3139 #endif
3140     } // release lock
3141 
3142     // Wake up poll loop since it may need to make new input dispatching choices.
3143     mLooper->wake();
3144     return true;
3145 }
3146 
resetAndDropEverythingLocked(const char * reason)3147 void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
3148 #if DEBUG_FOCUS
3149     ALOGD("Resetting and dropping all events (%s).", reason);
3150 #endif
3151 
3152     CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
3153     synthesizeCancelationEventsForAllConnectionsLocked(options);
3154 
3155     resetKeyRepeatLocked();
3156     releasePendingEventLocked();
3157     drainInboundQueueLocked();
3158     resetANRTimeoutsLocked();
3159 
3160     mTouchStatesByDisplay.clear();
3161     mLastHoverWindowHandle.clear();
3162     mReplacedKeys.clear();
3163 }
3164 
logDispatchStateLocked()3165 void InputDispatcher::logDispatchStateLocked() {
3166     std::string dump;
3167     dumpDispatchStateLocked(dump);
3168 
3169     std::istringstream stream(dump);
3170     std::string line;
3171 
3172     while (std::getline(stream, line, '\n')) {
3173         ALOGD("%s", line.c_str());
3174     }
3175 }
3176 
dumpDispatchStateLocked(std::string & dump)3177 void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
3178     dump += StringPrintf(INDENT "DispatchEnabled: %d\n", mDispatchEnabled);
3179     dump += StringPrintf(INDENT "DispatchFrozen: %d\n", mDispatchFrozen);
3180 
3181     if (mFocusedApplicationHandle != NULL) {
3182         dump += StringPrintf(INDENT "FocusedApplication: name='%s', dispatchingTimeout=%0.3fms\n",
3183                 mFocusedApplicationHandle->getName().c_str(),
3184                 mFocusedApplicationHandle->getDispatchingTimeout(
3185                         DEFAULT_INPUT_DISPATCHING_TIMEOUT) / 1000000.0);
3186     } else {
3187         dump += StringPrintf(INDENT "FocusedApplication: <null>\n");
3188     }
3189     dump += StringPrintf(INDENT "FocusedWindow: name='%s'\n",
3190             mFocusedWindowHandle != NULL ? mFocusedWindowHandle->getName().c_str() : "<null>");
3191 
3192     if (!mTouchStatesByDisplay.isEmpty()) {
3193         dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
3194         for (size_t i = 0; i < mTouchStatesByDisplay.size(); i++) {
3195             const TouchState& state = mTouchStatesByDisplay.valueAt(i);
3196             dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
3197                     state.displayId, toString(state.down), toString(state.split),
3198                     state.deviceId, state.source);
3199             if (!state.windows.isEmpty()) {
3200                 dump += INDENT3 "Windows:\n";
3201                 for (size_t i = 0; i < state.windows.size(); i++) {
3202                     const TouchedWindow& touchedWindow = state.windows[i];
3203                     dump += StringPrintf(INDENT4 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
3204                             i, touchedWindow.windowHandle->getName().c_str(),
3205                             touchedWindow.pointerIds.value,
3206                             touchedWindow.targetFlags);
3207                 }
3208             } else {
3209                 dump += INDENT3 "Windows: <none>\n";
3210             }
3211         }
3212     } else {
3213         dump += INDENT "TouchStates: <no displays touched>\n";
3214     }
3215 
3216     if (!mWindowHandles.isEmpty()) {
3217         dump += INDENT "Windows:\n";
3218         for (size_t i = 0; i < mWindowHandles.size(); i++) {
3219             const sp<InputWindowHandle>& windowHandle = mWindowHandles.itemAt(i);
3220             const InputWindowInfo* windowInfo = windowHandle->getInfo();
3221 
3222             dump += StringPrintf(INDENT2 "%zu: name='%s', displayId=%d, "
3223                     "paused=%s, hasFocus=%s, hasWallpaper=%s, "
3224                     "visible=%s, canReceiveKeys=%s, flags=0x%08x, type=0x%08x, layer=%d, "
3225                     "frame=[%d,%d][%d,%d], scale=%f, "
3226                     "touchableRegion=",
3227                     i, windowInfo->name.c_str(), windowInfo->displayId,
3228                     toString(windowInfo->paused),
3229                     toString(windowInfo->hasFocus),
3230                     toString(windowInfo->hasWallpaper),
3231                     toString(windowInfo->visible),
3232                     toString(windowInfo->canReceiveKeys),
3233                     windowInfo->layoutParamsFlags, windowInfo->layoutParamsType,
3234                     windowInfo->layer,
3235                     windowInfo->frameLeft, windowInfo->frameTop,
3236                     windowInfo->frameRight, windowInfo->frameBottom,
3237                     windowInfo->scaleFactor);
3238             dumpRegion(dump, windowInfo->touchableRegion);
3239             dump += StringPrintf(", inputFeatures=0x%08x", windowInfo->inputFeatures);
3240             dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%0.3fms\n",
3241                     windowInfo->ownerPid, windowInfo->ownerUid,
3242                     windowInfo->dispatchingTimeout / 1000000.0);
3243         }
3244     } else {
3245         dump += INDENT "Windows: <none>\n";
3246     }
3247 
3248     if (!mMonitoringChannels.isEmpty()) {
3249         dump += INDENT "MonitoringChannels:\n";
3250         for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
3251             const sp<InputChannel>& channel = mMonitoringChannels[i];
3252             dump += StringPrintf(INDENT2 "%zu: '%s'\n", i, channel->getName().c_str());
3253         }
3254     } else {
3255         dump += INDENT "MonitoringChannels: <none>\n";
3256     }
3257 
3258     nsecs_t currentTime = now();
3259 
3260     // Dump recently dispatched or dropped events from oldest to newest.
3261     if (!mRecentQueue.isEmpty()) {
3262         dump += StringPrintf(INDENT "RecentQueue: length=%u\n", mRecentQueue.count());
3263         for (EventEntry* entry = mRecentQueue.head; entry; entry = entry->next) {
3264             dump += INDENT2;
3265             entry->appendDescription(dump);
3266             dump += StringPrintf(", age=%0.1fms\n",
3267                     (currentTime - entry->eventTime) * 0.000001f);
3268         }
3269     } else {
3270         dump += INDENT "RecentQueue: <empty>\n";
3271     }
3272 
3273     // Dump event currently being dispatched.
3274     if (mPendingEvent) {
3275         dump += INDENT "PendingEvent:\n";
3276         dump += INDENT2;
3277         mPendingEvent->appendDescription(dump);
3278         dump += StringPrintf(", age=%0.1fms\n",
3279                 (currentTime - mPendingEvent->eventTime) * 0.000001f);
3280     } else {
3281         dump += INDENT "PendingEvent: <none>\n";
3282     }
3283 
3284     // Dump inbound events from oldest to newest.
3285     if (!mInboundQueue.isEmpty()) {
3286         dump += StringPrintf(INDENT "InboundQueue: length=%u\n", mInboundQueue.count());
3287         for (EventEntry* entry = mInboundQueue.head; entry; entry = entry->next) {
3288             dump += INDENT2;
3289             entry->appendDescription(dump);
3290             dump += StringPrintf(", age=%0.1fms\n",
3291                     (currentTime - entry->eventTime) * 0.000001f);
3292         }
3293     } else {
3294         dump += INDENT "InboundQueue: <empty>\n";
3295     }
3296 
3297     if (!mReplacedKeys.isEmpty()) {
3298         dump += INDENT "ReplacedKeys:\n";
3299         for (size_t i = 0; i < mReplacedKeys.size(); i++) {
3300             const KeyReplacement& replacement = mReplacedKeys.keyAt(i);
3301             int32_t newKeyCode = mReplacedKeys.valueAt(i);
3302             dump += StringPrintf(INDENT2 "%zu: originalKeyCode=%d, deviceId=%d, newKeyCode=%d\n",
3303                     i, replacement.keyCode, replacement.deviceId, newKeyCode);
3304         }
3305     } else {
3306         dump += INDENT "ReplacedKeys: <empty>\n";
3307     }
3308 
3309     if (!mConnectionsByFd.isEmpty()) {
3310         dump += INDENT "Connections:\n";
3311         for (size_t i = 0; i < mConnectionsByFd.size(); i++) {
3312             const sp<Connection>& connection = mConnectionsByFd.valueAt(i);
3313             dump += StringPrintf(INDENT2 "%zu: channelName='%s', windowName='%s', "
3314                     "status=%s, monitor=%s, inputPublisherBlocked=%s\n",
3315                     i, connection->getInputChannelName().c_str(),
3316                     connection->getWindowName().c_str(),
3317                     connection->getStatusLabel(), toString(connection->monitor),
3318                     toString(connection->inputPublisherBlocked));
3319 
3320             if (!connection->outboundQueue.isEmpty()) {
3321                 dump += StringPrintf(INDENT3 "OutboundQueue: length=%u\n",
3322                         connection->outboundQueue.count());
3323                 for (DispatchEntry* entry = connection->outboundQueue.head; entry;
3324                         entry = entry->next) {
3325                     dump.append(INDENT4);
3326                     entry->eventEntry->appendDescription(dump);
3327                     dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, age=%0.1fms\n",
3328                             entry->targetFlags, entry->resolvedAction,
3329                             (currentTime - entry->eventEntry->eventTime) * 0.000001f);
3330                 }
3331             } else {
3332                 dump += INDENT3 "OutboundQueue: <empty>\n";
3333             }
3334 
3335             if (!connection->waitQueue.isEmpty()) {
3336                 dump += StringPrintf(INDENT3 "WaitQueue: length=%u\n",
3337                         connection->waitQueue.count());
3338                 for (DispatchEntry* entry = connection->waitQueue.head; entry;
3339                         entry = entry->next) {
3340                     dump += INDENT4;
3341                     entry->eventEntry->appendDescription(dump);
3342                     dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, "
3343                             "age=%0.1fms, wait=%0.1fms\n",
3344                             entry->targetFlags, entry->resolvedAction,
3345                             (currentTime - entry->eventEntry->eventTime) * 0.000001f,
3346                             (currentTime - entry->deliveryTime) * 0.000001f);
3347                 }
3348             } else {
3349                 dump += INDENT3 "WaitQueue: <empty>\n";
3350             }
3351         }
3352     } else {
3353         dump += INDENT "Connections: <none>\n";
3354     }
3355 
3356     if (isAppSwitchPendingLocked()) {
3357         dump += StringPrintf(INDENT "AppSwitch: pending, due in %0.1fms\n",
3358                 (mAppSwitchDueTime - now()) / 1000000.0);
3359     } else {
3360         dump += INDENT "AppSwitch: not pending\n";
3361     }
3362 
3363     dump += INDENT "Configuration:\n";
3364     dump += StringPrintf(INDENT2 "KeyRepeatDelay: %0.1fms\n",
3365             mConfig.keyRepeatDelay * 0.000001f);
3366     dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %0.1fms\n",
3367             mConfig.keyRepeatTimeout * 0.000001f);
3368 }
3369 
registerInputChannel(const sp<InputChannel> & inputChannel,const sp<InputWindowHandle> & inputWindowHandle,bool monitor)3370 status_t InputDispatcher::registerInputChannel(const sp<InputChannel>& inputChannel,
3371         const sp<InputWindowHandle>& inputWindowHandle, bool monitor) {
3372 #if DEBUG_REGISTRATION
3373     ALOGD("channel '%s' ~ registerInputChannel - monitor=%s", inputChannel->getName().c_str(),
3374             toString(monitor));
3375 #endif
3376 
3377     { // acquire lock
3378         AutoMutex _l(mLock);
3379 
3380         if (getConnectionIndexLocked(inputChannel) >= 0) {
3381             ALOGW("Attempted to register already registered input channel '%s'",
3382                     inputChannel->getName().c_str());
3383             return BAD_VALUE;
3384         }
3385 
3386         sp<Connection> connection = new Connection(inputChannel, inputWindowHandle, monitor);
3387 
3388         int fd = inputChannel->getFd();
3389         mConnectionsByFd.add(fd, connection);
3390 
3391         if (monitor) {
3392             mMonitoringChannels.push(inputChannel);
3393         }
3394 
3395         mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
3396     } // release lock
3397 
3398     // Wake the looper because some connections have changed.
3399     mLooper->wake();
3400     return OK;
3401 }
3402 
unregisterInputChannel(const sp<InputChannel> & inputChannel)3403 status_t InputDispatcher::unregisterInputChannel(const sp<InputChannel>& inputChannel) {
3404 #if DEBUG_REGISTRATION
3405     ALOGD("channel '%s' ~ unregisterInputChannel", inputChannel->getName().c_str());
3406 #endif
3407 
3408     { // acquire lock
3409         AutoMutex _l(mLock);
3410 
3411         status_t status = unregisterInputChannelLocked(inputChannel, false /*notify*/);
3412         if (status) {
3413             return status;
3414         }
3415     } // release lock
3416 
3417     // Wake the poll loop because removing the connection may have changed the current
3418     // synchronization state.
3419     mLooper->wake();
3420     return OK;
3421 }
3422 
unregisterInputChannelLocked(const sp<InputChannel> & inputChannel,bool notify)3423 status_t InputDispatcher::unregisterInputChannelLocked(const sp<InputChannel>& inputChannel,
3424         bool notify) {
3425     ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
3426     if (connectionIndex < 0) {
3427         ALOGW("Attempted to unregister already unregistered input channel '%s'",
3428                 inputChannel->getName().c_str());
3429         return BAD_VALUE;
3430     }
3431 
3432     sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
3433     mConnectionsByFd.removeItemsAt(connectionIndex);
3434 
3435     if (connection->monitor) {
3436         removeMonitorChannelLocked(inputChannel);
3437     }
3438 
3439     mLooper->removeFd(inputChannel->getFd());
3440 
3441     nsecs_t currentTime = now();
3442     abortBrokenDispatchCycleLocked(currentTime, connection, notify);
3443 
3444     connection->status = Connection::STATUS_ZOMBIE;
3445     return OK;
3446 }
3447 
removeMonitorChannelLocked(const sp<InputChannel> & inputChannel)3448 void InputDispatcher::removeMonitorChannelLocked(const sp<InputChannel>& inputChannel) {
3449     for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
3450          if (mMonitoringChannels[i] == inputChannel) {
3451              mMonitoringChannels.removeAt(i);
3452              break;
3453          }
3454     }
3455 }
3456 
getConnectionIndexLocked(const sp<InputChannel> & inputChannel)3457 ssize_t InputDispatcher::getConnectionIndexLocked(const sp<InputChannel>& inputChannel) {
3458     ssize_t connectionIndex = mConnectionsByFd.indexOfKey(inputChannel->getFd());
3459     if (connectionIndex >= 0) {
3460         sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
3461         if (connection->inputChannel.get() == inputChannel.get()) {
3462             return connectionIndex;
3463         }
3464     }
3465 
3466     return -1;
3467 }
3468 
onDispatchCycleFinishedLocked(nsecs_t currentTime,const sp<Connection> & connection,uint32_t seq,bool handled)3469 void InputDispatcher::onDispatchCycleFinishedLocked(
3470         nsecs_t currentTime, const sp<Connection>& connection, uint32_t seq, bool handled) {
3471     CommandEntry* commandEntry = postCommandLocked(
3472             & InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
3473     commandEntry->connection = connection;
3474     commandEntry->eventTime = currentTime;
3475     commandEntry->seq = seq;
3476     commandEntry->handled = handled;
3477 }
3478 
onDispatchCycleBrokenLocked(nsecs_t currentTime,const sp<Connection> & connection)3479 void InputDispatcher::onDispatchCycleBrokenLocked(
3480         nsecs_t currentTime, const sp<Connection>& connection) {
3481     ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
3482             connection->getInputChannelName().c_str());
3483 
3484     CommandEntry* commandEntry = postCommandLocked(
3485             & InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
3486     commandEntry->connection = connection;
3487 }
3488 
onANRLocked(nsecs_t currentTime,const sp<InputApplicationHandle> & applicationHandle,const sp<InputWindowHandle> & windowHandle,nsecs_t eventTime,nsecs_t waitStartTime,const char * reason)3489 void InputDispatcher::onANRLocked(
3490         nsecs_t currentTime, const sp<InputApplicationHandle>& applicationHandle,
3491         const sp<InputWindowHandle>& windowHandle,
3492         nsecs_t eventTime, nsecs_t waitStartTime, const char* reason) {
3493     float dispatchLatency = (currentTime - eventTime) * 0.000001f;
3494     float waitDuration = (currentTime - waitStartTime) * 0.000001f;
3495     ALOGI("Application is not responding: %s.  "
3496             "It has been %0.1fms since event, %0.1fms since wait started.  Reason: %s",
3497             getApplicationWindowLabelLocked(applicationHandle, windowHandle).c_str(),
3498             dispatchLatency, waitDuration, reason);
3499 
3500     // Capture a record of the InputDispatcher state at the time of the ANR.
3501     time_t t = time(NULL);
3502     struct tm tm;
3503     localtime_r(&t, &tm);
3504     char timestr[64];
3505     strftime(timestr, sizeof(timestr), "%F %T", &tm);
3506     mLastANRState.clear();
3507     mLastANRState += INDENT "ANR:\n";
3508     mLastANRState += StringPrintf(INDENT2 "Time: %s\n", timestr);
3509     mLastANRState += StringPrintf(INDENT2 "Window: %s\n",
3510             getApplicationWindowLabelLocked(applicationHandle, windowHandle).c_str());
3511     mLastANRState += StringPrintf(INDENT2 "DispatchLatency: %0.1fms\n", dispatchLatency);
3512     mLastANRState += StringPrintf(INDENT2 "WaitDuration: %0.1fms\n", waitDuration);
3513     mLastANRState += StringPrintf(INDENT2 "Reason: %s\n", reason);
3514     dumpDispatchStateLocked(mLastANRState);
3515 
3516     CommandEntry* commandEntry = postCommandLocked(
3517             & InputDispatcher::doNotifyANRLockedInterruptible);
3518     commandEntry->inputApplicationHandle = applicationHandle;
3519     commandEntry->inputWindowHandle = windowHandle;
3520     commandEntry->reason = reason;
3521 }
3522 
doNotifyConfigurationChangedInterruptible(CommandEntry * commandEntry)3523 void InputDispatcher::doNotifyConfigurationChangedInterruptible(
3524         CommandEntry* commandEntry) {
3525     mLock.unlock();
3526 
3527     mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
3528 
3529     mLock.lock();
3530 }
3531 
doNotifyInputChannelBrokenLockedInterruptible(CommandEntry * commandEntry)3532 void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(
3533         CommandEntry* commandEntry) {
3534     sp<Connection> connection = commandEntry->connection;
3535 
3536     if (connection->status != Connection::STATUS_ZOMBIE) {
3537         mLock.unlock();
3538 
3539         mPolicy->notifyInputChannelBroken(connection->inputWindowHandle);
3540 
3541         mLock.lock();
3542     }
3543 }
3544 
doNotifyANRLockedInterruptible(CommandEntry * commandEntry)3545 void InputDispatcher::doNotifyANRLockedInterruptible(
3546         CommandEntry* commandEntry) {
3547     mLock.unlock();
3548 
3549     nsecs_t newTimeout = mPolicy->notifyANR(
3550             commandEntry->inputApplicationHandle, commandEntry->inputWindowHandle,
3551             commandEntry->reason);
3552 
3553     mLock.lock();
3554 
3555     resumeAfterTargetsNotReadyTimeoutLocked(newTimeout,
3556             commandEntry->inputWindowHandle != NULL
3557                     ? commandEntry->inputWindowHandle->getInputChannel() : NULL);
3558 }
3559 
doInterceptKeyBeforeDispatchingLockedInterruptible(CommandEntry * commandEntry)3560 void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
3561         CommandEntry* commandEntry) {
3562     KeyEntry* entry = commandEntry->keyEntry;
3563 
3564     KeyEvent event;
3565     initializeKeyEvent(&event, entry);
3566 
3567     mLock.unlock();
3568 
3569     android::base::Timer t;
3570     nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(commandEntry->inputWindowHandle,
3571             &event, entry->policyFlags);
3572     if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3573         ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
3574                 std::to_string(t.duration().count()).c_str());
3575     }
3576 
3577     mLock.lock();
3578 
3579     if (delay < 0) {
3580         entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
3581     } else if (!delay) {
3582         entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
3583     } else {
3584         entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
3585         entry->interceptKeyWakeupTime = now() + delay;
3586     }
3587     entry->release();
3588 }
3589 
doDispatchCycleFinishedLockedInterruptible(CommandEntry * commandEntry)3590 void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(
3591         CommandEntry* commandEntry) {
3592     sp<Connection> connection = commandEntry->connection;
3593     nsecs_t finishTime = commandEntry->eventTime;
3594     uint32_t seq = commandEntry->seq;
3595     bool handled = commandEntry->handled;
3596 
3597     // Handle post-event policy actions.
3598     DispatchEntry* dispatchEntry = connection->findWaitQueueEntry(seq);
3599     if (dispatchEntry) {
3600         nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
3601         if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
3602             std::string msg =
3603                     StringPrintf("Window '%s' spent %0.1fms processing the last input event: ",
3604                     connection->getWindowName().c_str(), eventDuration * 0.000001f);
3605             dispatchEntry->eventEntry->appendDescription(msg);
3606             ALOGI("%s", msg.c_str());
3607         }
3608 
3609         bool restartEvent;
3610         if (dispatchEntry->eventEntry->type == EventEntry::TYPE_KEY) {
3611             KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry);
3612             restartEvent = afterKeyEventLockedInterruptible(connection,
3613                     dispatchEntry, keyEntry, handled);
3614         } else if (dispatchEntry->eventEntry->type == EventEntry::TYPE_MOTION) {
3615             MotionEntry* motionEntry = static_cast<MotionEntry*>(dispatchEntry->eventEntry);
3616             restartEvent = afterMotionEventLockedInterruptible(connection,
3617                     dispatchEntry, motionEntry, handled);
3618         } else {
3619             restartEvent = false;
3620         }
3621 
3622         // Dequeue the event and start the next cycle.
3623         // Note that because the lock might have been released, it is possible that the
3624         // contents of the wait queue to have been drained, so we need to double-check
3625         // a few things.
3626         if (dispatchEntry == connection->findWaitQueueEntry(seq)) {
3627             connection->waitQueue.dequeue(dispatchEntry);
3628             traceWaitQueueLengthLocked(connection);
3629             if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
3630                 connection->outboundQueue.enqueueAtHead(dispatchEntry);
3631                 traceOutboundQueueLengthLocked(connection);
3632             } else {
3633                 releaseDispatchEntryLocked(dispatchEntry);
3634             }
3635         }
3636 
3637         // Start the next dispatch cycle for this connection.
3638         startDispatchCycleLocked(now(), connection);
3639     }
3640 }
3641 
afterKeyEventLockedInterruptible(const sp<Connection> & connection,DispatchEntry * dispatchEntry,KeyEntry * keyEntry,bool handled)3642 bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
3643         DispatchEntry* dispatchEntry, KeyEntry* keyEntry, bool handled) {
3644     if (!(keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK)) {
3645         // Get the fallback key state.
3646         // Clear it out after dispatching the UP.
3647         int32_t originalKeyCode = keyEntry->keyCode;
3648         int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
3649         if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
3650             connection->inputState.removeFallbackKey(originalKeyCode);
3651         }
3652 
3653         if (handled || !dispatchEntry->hasForegroundTarget()) {
3654             // If the application handles the original key for which we previously
3655             // generated a fallback or if the window is not a foreground window,
3656             // then cancel the associated fallback key, if any.
3657             if (fallbackKeyCode != -1) {
3658                 // Dispatch the unhandled key to the policy with the cancel flag.
3659 #if DEBUG_OUTBOUND_EVENT_DETAILS
3660                 ALOGD("Unhandled key event: Asking policy to cancel fallback action.  "
3661                         "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
3662                         keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
3663                         keyEntry->policyFlags);
3664 #endif
3665                 KeyEvent event;
3666                 initializeKeyEvent(&event, keyEntry);
3667                 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
3668 
3669                 mLock.unlock();
3670 
3671                 mPolicy->dispatchUnhandledKey(connection->inputWindowHandle,
3672                         &event, keyEntry->policyFlags, &event);
3673 
3674                 mLock.lock();
3675 
3676                 // Cancel the fallback key.
3677                 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
3678                     CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
3679                             "application handled the original non-fallback key "
3680                             "or is no longer a foreground target, "
3681                             "canceling previously dispatched fallback key");
3682                     options.keyCode = fallbackKeyCode;
3683                     synthesizeCancelationEventsForConnectionLocked(connection, options);
3684                 }
3685                 connection->inputState.removeFallbackKey(originalKeyCode);
3686             }
3687         } else {
3688             // If the application did not handle a non-fallback key, first check
3689             // that we are in a good state to perform unhandled key event processing
3690             // Then ask the policy what to do with it.
3691             bool initialDown = keyEntry->action == AKEY_EVENT_ACTION_DOWN
3692                     && keyEntry->repeatCount == 0;
3693             if (fallbackKeyCode == -1 && !initialDown) {
3694 #if DEBUG_OUTBOUND_EVENT_DETAILS
3695                 ALOGD("Unhandled key event: Skipping unhandled key event processing "
3696                         "since this is not an initial down.  "
3697                         "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
3698                         originalKeyCode, keyEntry->action, keyEntry->repeatCount,
3699                         keyEntry->policyFlags);
3700 #endif
3701                 return false;
3702             }
3703 
3704             // Dispatch the unhandled key to the policy.
3705 #if DEBUG_OUTBOUND_EVENT_DETAILS
3706             ALOGD("Unhandled key event: Asking policy to perform fallback action.  "
3707                     "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
3708                     keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
3709                     keyEntry->policyFlags);
3710 #endif
3711             KeyEvent event;
3712             initializeKeyEvent(&event, keyEntry);
3713 
3714             mLock.unlock();
3715 
3716             bool fallback = mPolicy->dispatchUnhandledKey(connection->inputWindowHandle,
3717                     &event, keyEntry->policyFlags, &event);
3718 
3719             mLock.lock();
3720 
3721             if (connection->status != Connection::STATUS_NORMAL) {
3722                 connection->inputState.removeFallbackKey(originalKeyCode);
3723                 return false;
3724             }
3725 
3726             // Latch the fallback keycode for this key on an initial down.
3727             // The fallback keycode cannot change at any other point in the lifecycle.
3728             if (initialDown) {
3729                 if (fallback) {
3730                     fallbackKeyCode = event.getKeyCode();
3731                 } else {
3732                     fallbackKeyCode = AKEYCODE_UNKNOWN;
3733                 }
3734                 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
3735             }
3736 
3737             ALOG_ASSERT(fallbackKeyCode != -1);
3738 
3739             // Cancel the fallback key if the policy decides not to send it anymore.
3740             // We will continue to dispatch the key to the policy but we will no
3741             // longer dispatch a fallback key to the application.
3742             if (fallbackKeyCode != AKEYCODE_UNKNOWN
3743                     && (!fallback || fallbackKeyCode != event.getKeyCode())) {
3744 #if DEBUG_OUTBOUND_EVENT_DETAILS
3745                 if (fallback) {
3746                     ALOGD("Unhandled key event: Policy requested to send key %d"
3747                             "as a fallback for %d, but on the DOWN it had requested "
3748                             "to send %d instead.  Fallback canceled.",
3749                             event.getKeyCode(), originalKeyCode, fallbackKeyCode);
3750                 } else {
3751                     ALOGD("Unhandled key event: Policy did not request fallback for %d, "
3752                             "but on the DOWN it had requested to send %d.  "
3753                             "Fallback canceled.",
3754                             originalKeyCode, fallbackKeyCode);
3755                 }
3756 #endif
3757 
3758                 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
3759                         "canceling fallback, policy no longer desires it");
3760                 options.keyCode = fallbackKeyCode;
3761                 synthesizeCancelationEventsForConnectionLocked(connection, options);
3762 
3763                 fallback = false;
3764                 fallbackKeyCode = AKEYCODE_UNKNOWN;
3765                 if (keyEntry->action != AKEY_EVENT_ACTION_UP) {
3766                     connection->inputState.setFallbackKey(originalKeyCode,
3767                             fallbackKeyCode);
3768                 }
3769             }
3770 
3771 #if DEBUG_OUTBOUND_EVENT_DETAILS
3772             {
3773                 std::string msg;
3774                 const KeyedVector<int32_t, int32_t>& fallbackKeys =
3775                         connection->inputState.getFallbackKeys();
3776                 for (size_t i = 0; i < fallbackKeys.size(); i++) {
3777                     msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i),
3778                             fallbackKeys.valueAt(i));
3779                 }
3780                 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
3781                         fallbackKeys.size(), msg.c_str());
3782             }
3783 #endif
3784 
3785             if (fallback) {
3786                 // Restart the dispatch cycle using the fallback key.
3787                 keyEntry->eventTime = event.getEventTime();
3788                 keyEntry->deviceId = event.getDeviceId();
3789                 keyEntry->source = event.getSource();
3790                 keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
3791                 keyEntry->keyCode = fallbackKeyCode;
3792                 keyEntry->scanCode = event.getScanCode();
3793                 keyEntry->metaState = event.getMetaState();
3794                 keyEntry->repeatCount = event.getRepeatCount();
3795                 keyEntry->downTime = event.getDownTime();
3796                 keyEntry->syntheticRepeat = false;
3797 
3798 #if DEBUG_OUTBOUND_EVENT_DETAILS
3799                 ALOGD("Unhandled key event: Dispatching fallback key.  "
3800                         "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
3801                         originalKeyCode, fallbackKeyCode, keyEntry->metaState);
3802 #endif
3803                 return true; // restart the event
3804             } else {
3805 #if DEBUG_OUTBOUND_EVENT_DETAILS
3806                 ALOGD("Unhandled key event: No fallback key.");
3807 #endif
3808             }
3809         }
3810     }
3811     return false;
3812 }
3813 
afterMotionEventLockedInterruptible(const sp<Connection> & connection,DispatchEntry * dispatchEntry,MotionEntry * motionEntry,bool handled)3814 bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
3815         DispatchEntry* dispatchEntry, MotionEntry* motionEntry, bool handled) {
3816     return false;
3817 }
3818 
doPokeUserActivityLockedInterruptible(CommandEntry * commandEntry)3819 void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
3820     mLock.unlock();
3821 
3822     mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
3823 
3824     mLock.lock();
3825 }
3826 
initializeKeyEvent(KeyEvent * event,const KeyEntry * entry)3827 void InputDispatcher::initializeKeyEvent(KeyEvent* event, const KeyEntry* entry) {
3828     event->initialize(entry->deviceId, entry->source, entry->action, entry->flags,
3829             entry->keyCode, entry->scanCode, entry->metaState, entry->repeatCount,
3830             entry->downTime, entry->eventTime);
3831 }
3832 
updateDispatchStatisticsLocked(nsecs_t currentTime,const EventEntry * entry,int32_t injectionResult,nsecs_t timeSpentWaitingForApplication)3833 void InputDispatcher::updateDispatchStatisticsLocked(nsecs_t currentTime, const EventEntry* entry,
3834         int32_t injectionResult, nsecs_t timeSpentWaitingForApplication) {
3835     // TODO Write some statistics about how long we spend waiting.
3836 }
3837 
traceInboundQueueLengthLocked()3838 void InputDispatcher::traceInboundQueueLengthLocked() {
3839     if (ATRACE_ENABLED()) {
3840         ATRACE_INT("iq", mInboundQueue.count());
3841     }
3842 }
3843 
traceOutboundQueueLengthLocked(const sp<Connection> & connection)3844 void InputDispatcher::traceOutboundQueueLengthLocked(const sp<Connection>& connection) {
3845     if (ATRACE_ENABLED()) {
3846         char counterName[40];
3847         snprintf(counterName, sizeof(counterName), "oq:%s", connection->getWindowName().c_str());
3848         ATRACE_INT(counterName, connection->outboundQueue.count());
3849     }
3850 }
3851 
traceWaitQueueLengthLocked(const sp<Connection> & connection)3852 void InputDispatcher::traceWaitQueueLengthLocked(const sp<Connection>& connection) {
3853     if (ATRACE_ENABLED()) {
3854         char counterName[40];
3855         snprintf(counterName, sizeof(counterName), "wq:%s", connection->getWindowName().c_str());
3856         ATRACE_INT(counterName, connection->waitQueue.count());
3857     }
3858 }
3859 
dump(std::string & dump)3860 void InputDispatcher::dump(std::string& dump) {
3861     AutoMutex _l(mLock);
3862 
3863     dump += "Input Dispatcher State:\n";
3864     dumpDispatchStateLocked(dump);
3865 
3866     if (!mLastANRState.empty()) {
3867         dump += "\nInput Dispatcher State at time of last ANR:\n";
3868         dump += mLastANRState;
3869     }
3870 }
3871 
monitor()3872 void InputDispatcher::monitor() {
3873     // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
3874     mLock.lock();
3875     mLooper->wake();
3876     mDispatcherIsAliveCondition.wait(mLock);
3877     mLock.unlock();
3878 }
3879 
3880 
3881 // --- InputDispatcher::InjectionState ---
3882 
InjectionState(int32_t injectorPid,int32_t injectorUid)3883 InputDispatcher::InjectionState::InjectionState(int32_t injectorPid, int32_t injectorUid) :
3884         refCount(1),
3885         injectorPid(injectorPid), injectorUid(injectorUid),
3886         injectionResult(INPUT_EVENT_INJECTION_PENDING), injectionIsAsync(false),
3887         pendingForegroundDispatches(0) {
3888 }
3889 
~InjectionState()3890 InputDispatcher::InjectionState::~InjectionState() {
3891 }
3892 
release()3893 void InputDispatcher::InjectionState::release() {
3894     refCount -= 1;
3895     if (refCount == 0) {
3896         delete this;
3897     } else {
3898         ALOG_ASSERT(refCount > 0);
3899     }
3900 }
3901 
3902 
3903 // --- InputDispatcher::EventEntry ---
3904 
EventEntry(int32_t type,nsecs_t eventTime,uint32_t policyFlags)3905 InputDispatcher::EventEntry::EventEntry(int32_t type, nsecs_t eventTime, uint32_t policyFlags) :
3906         refCount(1), type(type), eventTime(eventTime), policyFlags(policyFlags),
3907         injectionState(NULL), dispatchInProgress(false) {
3908 }
3909 
~EventEntry()3910 InputDispatcher::EventEntry::~EventEntry() {
3911     releaseInjectionState();
3912 }
3913 
release()3914 void InputDispatcher::EventEntry::release() {
3915     refCount -= 1;
3916     if (refCount == 0) {
3917         delete this;
3918     } else {
3919         ALOG_ASSERT(refCount > 0);
3920     }
3921 }
3922 
releaseInjectionState()3923 void InputDispatcher::EventEntry::releaseInjectionState() {
3924     if (injectionState) {
3925         injectionState->release();
3926         injectionState = NULL;
3927     }
3928 }
3929 
3930 
3931 // --- InputDispatcher::ConfigurationChangedEntry ---
3932 
ConfigurationChangedEntry(nsecs_t eventTime)3933 InputDispatcher::ConfigurationChangedEntry::ConfigurationChangedEntry(nsecs_t eventTime) :
3934         EventEntry(TYPE_CONFIGURATION_CHANGED, eventTime, 0) {
3935 }
3936 
~ConfigurationChangedEntry()3937 InputDispatcher::ConfigurationChangedEntry::~ConfigurationChangedEntry() {
3938 }
3939 
appendDescription(std::string & msg) const3940 void InputDispatcher::ConfigurationChangedEntry::appendDescription(std::string& msg) const {
3941     msg += StringPrintf("ConfigurationChangedEvent(), policyFlags=0x%08x", policyFlags);
3942 }
3943 
3944 
3945 // --- InputDispatcher::DeviceResetEntry ---
3946 
DeviceResetEntry(nsecs_t eventTime,int32_t deviceId)3947 InputDispatcher::DeviceResetEntry::DeviceResetEntry(nsecs_t eventTime, int32_t deviceId) :
3948         EventEntry(TYPE_DEVICE_RESET, eventTime, 0),
3949         deviceId(deviceId) {
3950 }
3951 
~DeviceResetEntry()3952 InputDispatcher::DeviceResetEntry::~DeviceResetEntry() {
3953 }
3954 
appendDescription(std::string & msg) const3955 void InputDispatcher::DeviceResetEntry::appendDescription(std::string& msg) const {
3956     msg += StringPrintf("DeviceResetEvent(deviceId=%d), policyFlags=0x%08x",
3957             deviceId, policyFlags);
3958 }
3959 
3960 
3961 // --- InputDispatcher::KeyEntry ---
3962 
KeyEntry(nsecs_t eventTime,int32_t deviceId,uint32_t source,uint32_t policyFlags,int32_t action,int32_t flags,int32_t keyCode,int32_t scanCode,int32_t metaState,int32_t repeatCount,nsecs_t downTime)3963 InputDispatcher::KeyEntry::KeyEntry(nsecs_t eventTime,
3964         int32_t deviceId, uint32_t source, uint32_t policyFlags, int32_t action,
3965         int32_t flags, int32_t keyCode, int32_t scanCode, int32_t metaState,
3966         int32_t repeatCount, nsecs_t downTime) :
3967         EventEntry(TYPE_KEY, eventTime, policyFlags),
3968         deviceId(deviceId), source(source), action(action), flags(flags),
3969         keyCode(keyCode), scanCode(scanCode), metaState(metaState),
3970         repeatCount(repeatCount), downTime(downTime),
3971         syntheticRepeat(false), interceptKeyResult(KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN),
3972         interceptKeyWakeupTime(0) {
3973 }
3974 
~KeyEntry()3975 InputDispatcher::KeyEntry::~KeyEntry() {
3976 }
3977 
appendDescription(std::string & msg) const3978 void InputDispatcher::KeyEntry::appendDescription(std::string& msg) const {
3979     msg += StringPrintf("KeyEvent");
3980 }
3981 
recycle()3982 void InputDispatcher::KeyEntry::recycle() {
3983     releaseInjectionState();
3984 
3985     dispatchInProgress = false;
3986     syntheticRepeat = false;
3987     interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
3988     interceptKeyWakeupTime = 0;
3989 }
3990 
3991 
3992 // --- InputDispatcher::MotionEntry ---
3993 
MotionEntry(nsecs_t eventTime,int32_t deviceId,uint32_t source,uint32_t policyFlags,int32_t action,int32_t actionButton,int32_t flags,int32_t metaState,int32_t buttonState,int32_t edgeFlags,float xPrecision,float yPrecision,nsecs_t downTime,int32_t displayId,uint32_t pointerCount,const PointerProperties * pointerProperties,const PointerCoords * pointerCoords,float xOffset,float yOffset)3994 InputDispatcher::MotionEntry::MotionEntry(nsecs_t eventTime, int32_t deviceId,
3995         uint32_t source, uint32_t policyFlags, int32_t action, int32_t actionButton,
3996         int32_t flags, int32_t metaState, int32_t buttonState, int32_t edgeFlags,
3997         float xPrecision, float yPrecision, nsecs_t downTime,
3998         int32_t displayId, uint32_t pointerCount,
3999         const PointerProperties* pointerProperties, const PointerCoords* pointerCoords,
4000         float xOffset, float yOffset) :
4001         EventEntry(TYPE_MOTION, eventTime, policyFlags),
4002         eventTime(eventTime),
4003         deviceId(deviceId), source(source), action(action), actionButton(actionButton),
4004         flags(flags), metaState(metaState), buttonState(buttonState),
4005         edgeFlags(edgeFlags), xPrecision(xPrecision), yPrecision(yPrecision),
4006         downTime(downTime), displayId(displayId), pointerCount(pointerCount) {
4007     for (uint32_t i = 0; i < pointerCount; i++) {
4008         this->pointerProperties[i].copyFrom(pointerProperties[i]);
4009         this->pointerCoords[i].copyFrom(pointerCoords[i]);
4010         if (xOffset || yOffset) {
4011             this->pointerCoords[i].applyOffset(xOffset, yOffset);
4012         }
4013     }
4014 }
4015 
~MotionEntry()4016 InputDispatcher::MotionEntry::~MotionEntry() {
4017 }
4018 
appendDescription(std::string & msg) const4019 void InputDispatcher::MotionEntry::appendDescription(std::string& msg) const {
4020     msg += StringPrintf("MotionEvent");
4021 }
4022 
4023 
4024 // --- InputDispatcher::DispatchEntry ---
4025 
4026 volatile int32_t InputDispatcher::DispatchEntry::sNextSeqAtomic;
4027 
DispatchEntry(EventEntry * eventEntry,int32_t targetFlags,float xOffset,float yOffset,float scaleFactor)4028 InputDispatcher::DispatchEntry::DispatchEntry(EventEntry* eventEntry,
4029         int32_t targetFlags, float xOffset, float yOffset, float scaleFactor) :
4030         seq(nextSeq()),
4031         eventEntry(eventEntry), targetFlags(targetFlags),
4032         xOffset(xOffset), yOffset(yOffset), scaleFactor(scaleFactor),
4033         deliveryTime(0), resolvedAction(0), resolvedFlags(0) {
4034     eventEntry->refCount += 1;
4035 }
4036 
~DispatchEntry()4037 InputDispatcher::DispatchEntry::~DispatchEntry() {
4038     eventEntry->release();
4039 }
4040 
nextSeq()4041 uint32_t InputDispatcher::DispatchEntry::nextSeq() {
4042     // Sequence number 0 is reserved and will never be returned.
4043     uint32_t seq;
4044     do {
4045         seq = android_atomic_inc(&sNextSeqAtomic);
4046     } while (!seq);
4047     return seq;
4048 }
4049 
4050 
4051 // --- InputDispatcher::InputState ---
4052 
InputState()4053 InputDispatcher::InputState::InputState() {
4054 }
4055 
~InputState()4056 InputDispatcher::InputState::~InputState() {
4057 }
4058 
isNeutral() const4059 bool InputDispatcher::InputState::isNeutral() const {
4060     return mKeyMementos.isEmpty() && mMotionMementos.isEmpty();
4061 }
4062 
isHovering(int32_t deviceId,uint32_t source,int32_t displayId) const4063 bool InputDispatcher::InputState::isHovering(int32_t deviceId, uint32_t source,
4064         int32_t displayId) const {
4065     for (size_t i = 0; i < mMotionMementos.size(); i++) {
4066         const MotionMemento& memento = mMotionMementos.itemAt(i);
4067         if (memento.deviceId == deviceId
4068                 && memento.source == source
4069                 && memento.displayId == displayId
4070                 && memento.hovering) {
4071             return true;
4072         }
4073     }
4074     return false;
4075 }
4076 
trackKey(const KeyEntry * entry,int32_t action,int32_t flags)4077 bool InputDispatcher::InputState::trackKey(const KeyEntry* entry,
4078         int32_t action, int32_t flags) {
4079     switch (action) {
4080     case AKEY_EVENT_ACTION_UP: {
4081         if (entry->flags & AKEY_EVENT_FLAG_FALLBACK) {
4082             for (size_t i = 0; i < mFallbackKeys.size(); ) {
4083                 if (mFallbackKeys.valueAt(i) == entry->keyCode) {
4084                     mFallbackKeys.removeItemsAt(i);
4085                 } else {
4086                     i += 1;
4087                 }
4088             }
4089         }
4090         ssize_t index = findKeyMemento(entry);
4091         if (index >= 0) {
4092             mKeyMementos.removeAt(index);
4093             return true;
4094         }
4095         /* FIXME: We can't just drop the key up event because that prevents creating
4096          * popup windows that are automatically shown when a key is held and then
4097          * dismissed when the key is released.  The problem is that the popup will
4098          * not have received the original key down, so the key up will be considered
4099          * to be inconsistent with its observed state.  We could perhaps handle this
4100          * by synthesizing a key down but that will cause other problems.
4101          *
4102          * So for now, allow inconsistent key up events to be dispatched.
4103          *
4104 #if DEBUG_OUTBOUND_EVENT_DETAILS
4105         ALOGD("Dropping inconsistent key up event: deviceId=%d, source=%08x, "
4106                 "keyCode=%d, scanCode=%d",
4107                 entry->deviceId, entry->source, entry->keyCode, entry->scanCode);
4108 #endif
4109         return false;
4110         */
4111         return true;
4112     }
4113 
4114     case AKEY_EVENT_ACTION_DOWN: {
4115         ssize_t index = findKeyMemento(entry);
4116         if (index >= 0) {
4117             mKeyMementos.removeAt(index);
4118         }
4119         addKeyMemento(entry, flags);
4120         return true;
4121     }
4122 
4123     default:
4124         return true;
4125     }
4126 }
4127 
trackMotion(const MotionEntry * entry,int32_t action,int32_t flags)4128 bool InputDispatcher::InputState::trackMotion(const MotionEntry* entry,
4129         int32_t action, int32_t flags) {
4130     int32_t actionMasked = action & AMOTION_EVENT_ACTION_MASK;
4131     switch (actionMasked) {
4132     case AMOTION_EVENT_ACTION_UP:
4133     case AMOTION_EVENT_ACTION_CANCEL: {
4134         ssize_t index = findMotionMemento(entry, false /*hovering*/);
4135         if (index >= 0) {
4136             mMotionMementos.removeAt(index);
4137             return true;
4138         }
4139 #if DEBUG_OUTBOUND_EVENT_DETAILS
4140         ALOGD("Dropping inconsistent motion up or cancel event: deviceId=%d, source=%08x, "
4141                 "actionMasked=%d",
4142                 entry->deviceId, entry->source, actionMasked);
4143 #endif
4144         return false;
4145     }
4146 
4147     case AMOTION_EVENT_ACTION_DOWN: {
4148         ssize_t index = findMotionMemento(entry, false /*hovering*/);
4149         if (index >= 0) {
4150             mMotionMementos.removeAt(index);
4151         }
4152         addMotionMemento(entry, flags, false /*hovering*/);
4153         return true;
4154     }
4155 
4156     case AMOTION_EVENT_ACTION_POINTER_UP:
4157     case AMOTION_EVENT_ACTION_POINTER_DOWN:
4158     case AMOTION_EVENT_ACTION_MOVE: {
4159         if (entry->source & AINPUT_SOURCE_CLASS_NAVIGATION) {
4160             // Trackballs can send MOVE events with a corresponding DOWN or UP. There's no need to
4161             // generate cancellation events for these since they're based in relative rather than
4162             // absolute units.
4163             return true;
4164         }
4165 
4166         ssize_t index = findMotionMemento(entry, false /*hovering*/);
4167 
4168         if (entry->source & AINPUT_SOURCE_CLASS_JOYSTICK) {
4169             // Joysticks can send MOVE events without a corresponding DOWN or UP. Since all
4170             // joystick axes are normalized to [-1, 1] we can trust that 0 means it's neutral. Any
4171             // other value and we need to track the motion so we can send cancellation events for
4172             // anything generating fallback events (e.g. DPad keys for joystick movements).
4173             if (index >= 0) {
4174                 if (entry->pointerCoords[0].isEmpty()) {
4175                     mMotionMementos.removeAt(index);
4176                 } else {
4177                     MotionMemento& memento = mMotionMementos.editItemAt(index);
4178                     memento.setPointers(entry);
4179                 }
4180             } else if (!entry->pointerCoords[0].isEmpty()) {
4181                 addMotionMemento(entry, flags, false /*hovering*/);
4182             }
4183 
4184             // Joysticks and trackballs can send MOVE events without corresponding DOWN or UP.
4185             return true;
4186         }
4187         if (index >= 0) {
4188             MotionMemento& memento = mMotionMementos.editItemAt(index);
4189             memento.setPointers(entry);
4190             return true;
4191         }
4192 #if DEBUG_OUTBOUND_EVENT_DETAILS
4193         ALOGD("Dropping inconsistent motion pointer up/down or move event: "
4194                 "deviceId=%d, source=%08x, actionMasked=%d",
4195                 entry->deviceId, entry->source, actionMasked);
4196 #endif
4197         return false;
4198     }
4199 
4200     case AMOTION_EVENT_ACTION_HOVER_EXIT: {
4201         ssize_t index = findMotionMemento(entry, true /*hovering*/);
4202         if (index >= 0) {
4203             mMotionMementos.removeAt(index);
4204             return true;
4205         }
4206 #if DEBUG_OUTBOUND_EVENT_DETAILS
4207         ALOGD("Dropping inconsistent motion hover exit event: deviceId=%d, source=%08x",
4208                 entry->deviceId, entry->source);
4209 #endif
4210         return false;
4211     }
4212 
4213     case AMOTION_EVENT_ACTION_HOVER_ENTER:
4214     case AMOTION_EVENT_ACTION_HOVER_MOVE: {
4215         ssize_t index = findMotionMemento(entry, true /*hovering*/);
4216         if (index >= 0) {
4217             mMotionMementos.removeAt(index);
4218         }
4219         addMotionMemento(entry, flags, true /*hovering*/);
4220         return true;
4221     }
4222 
4223     default:
4224         return true;
4225     }
4226 }
4227 
findKeyMemento(const KeyEntry * entry) const4228 ssize_t InputDispatcher::InputState::findKeyMemento(const KeyEntry* entry) const {
4229     for (size_t i = 0; i < mKeyMementos.size(); i++) {
4230         const KeyMemento& memento = mKeyMementos.itemAt(i);
4231         if (memento.deviceId == entry->deviceId
4232                 && memento.source == entry->source
4233                 && memento.keyCode == entry->keyCode
4234                 && memento.scanCode == entry->scanCode) {
4235             return i;
4236         }
4237     }
4238     return -1;
4239 }
4240 
findMotionMemento(const MotionEntry * entry,bool hovering) const4241 ssize_t InputDispatcher::InputState::findMotionMemento(const MotionEntry* entry,
4242         bool hovering) const {
4243     for (size_t i = 0; i < mMotionMementos.size(); i++) {
4244         const MotionMemento& memento = mMotionMementos.itemAt(i);
4245         if (memento.deviceId == entry->deviceId
4246                 && memento.source == entry->source
4247                 && memento.displayId == entry->displayId
4248                 && memento.hovering == hovering) {
4249             return i;
4250         }
4251     }
4252     return -1;
4253 }
4254 
addKeyMemento(const KeyEntry * entry,int32_t flags)4255 void InputDispatcher::InputState::addKeyMemento(const KeyEntry* entry, int32_t flags) {
4256     mKeyMementos.push();
4257     KeyMemento& memento = mKeyMementos.editTop();
4258     memento.deviceId = entry->deviceId;
4259     memento.source = entry->source;
4260     memento.keyCode = entry->keyCode;
4261     memento.scanCode = entry->scanCode;
4262     memento.metaState = entry->metaState;
4263     memento.flags = flags;
4264     memento.downTime = entry->downTime;
4265     memento.policyFlags = entry->policyFlags;
4266 }
4267 
addMotionMemento(const MotionEntry * entry,int32_t flags,bool hovering)4268 void InputDispatcher::InputState::addMotionMemento(const MotionEntry* entry,
4269         int32_t flags, bool hovering) {
4270     mMotionMementos.push();
4271     MotionMemento& memento = mMotionMementos.editTop();
4272     memento.deviceId = entry->deviceId;
4273     memento.source = entry->source;
4274     memento.flags = flags;
4275     memento.xPrecision = entry->xPrecision;
4276     memento.yPrecision = entry->yPrecision;
4277     memento.downTime = entry->downTime;
4278     memento.displayId = entry->displayId;
4279     memento.setPointers(entry);
4280     memento.hovering = hovering;
4281     memento.policyFlags = entry->policyFlags;
4282 }
4283 
setPointers(const MotionEntry * entry)4284 void InputDispatcher::InputState::MotionMemento::setPointers(const MotionEntry* entry) {
4285     pointerCount = entry->pointerCount;
4286     for (uint32_t i = 0; i < entry->pointerCount; i++) {
4287         pointerProperties[i].copyFrom(entry->pointerProperties[i]);
4288         pointerCoords[i].copyFrom(entry->pointerCoords[i]);
4289     }
4290 }
4291 
synthesizeCancelationEvents(nsecs_t currentTime,Vector<EventEntry * > & outEvents,const CancelationOptions & options)4292 void InputDispatcher::InputState::synthesizeCancelationEvents(nsecs_t currentTime,
4293         Vector<EventEntry*>& outEvents, const CancelationOptions& options) {
4294     for (size_t i = 0; i < mKeyMementos.size(); i++) {
4295         const KeyMemento& memento = mKeyMementos.itemAt(i);
4296         if (shouldCancelKey(memento, options)) {
4297             outEvents.push(new KeyEntry(currentTime,
4298                     memento.deviceId, memento.source, memento.policyFlags,
4299                     AKEY_EVENT_ACTION_UP, memento.flags | AKEY_EVENT_FLAG_CANCELED,
4300                     memento.keyCode, memento.scanCode, memento.metaState, 0, memento.downTime));
4301         }
4302     }
4303 
4304     for (size_t i = 0; i < mMotionMementos.size(); i++) {
4305         const MotionMemento& memento = mMotionMementos.itemAt(i);
4306         if (shouldCancelMotion(memento, options)) {
4307             outEvents.push(new MotionEntry(currentTime,
4308                     memento.deviceId, memento.source, memento.policyFlags,
4309                     memento.hovering
4310                             ? AMOTION_EVENT_ACTION_HOVER_EXIT
4311                             : AMOTION_EVENT_ACTION_CANCEL,
4312                     memento.flags, 0, 0, 0, 0,
4313                     memento.xPrecision, memento.yPrecision, memento.downTime,
4314                     memento.displayId,
4315                     memento.pointerCount, memento.pointerProperties, memento.pointerCoords,
4316                     0, 0));
4317         }
4318     }
4319 }
4320 
clear()4321 void InputDispatcher::InputState::clear() {
4322     mKeyMementos.clear();
4323     mMotionMementos.clear();
4324     mFallbackKeys.clear();
4325 }
4326 
copyPointerStateTo(InputState & other) const4327 void InputDispatcher::InputState::copyPointerStateTo(InputState& other) const {
4328     for (size_t i = 0; i < mMotionMementos.size(); i++) {
4329         const MotionMemento& memento = mMotionMementos.itemAt(i);
4330         if (memento.source & AINPUT_SOURCE_CLASS_POINTER) {
4331             for (size_t j = 0; j < other.mMotionMementos.size(); ) {
4332                 const MotionMemento& otherMemento = other.mMotionMementos.itemAt(j);
4333                 if (memento.deviceId == otherMemento.deviceId
4334                         && memento.source == otherMemento.source
4335                         && memento.displayId == otherMemento.displayId) {
4336                     other.mMotionMementos.removeAt(j);
4337                 } else {
4338                     j += 1;
4339                 }
4340             }
4341             other.mMotionMementos.push(memento);
4342         }
4343     }
4344 }
4345 
getFallbackKey(int32_t originalKeyCode)4346 int32_t InputDispatcher::InputState::getFallbackKey(int32_t originalKeyCode) {
4347     ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
4348     return index >= 0 ? mFallbackKeys.valueAt(index) : -1;
4349 }
4350 
setFallbackKey(int32_t originalKeyCode,int32_t fallbackKeyCode)4351 void InputDispatcher::InputState::setFallbackKey(int32_t originalKeyCode,
4352         int32_t fallbackKeyCode) {
4353     ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
4354     if (index >= 0) {
4355         mFallbackKeys.replaceValueAt(index, fallbackKeyCode);
4356     } else {
4357         mFallbackKeys.add(originalKeyCode, fallbackKeyCode);
4358     }
4359 }
4360 
removeFallbackKey(int32_t originalKeyCode)4361 void InputDispatcher::InputState::removeFallbackKey(int32_t originalKeyCode) {
4362     mFallbackKeys.removeItem(originalKeyCode);
4363 }
4364 
shouldCancelKey(const KeyMemento & memento,const CancelationOptions & options)4365 bool InputDispatcher::InputState::shouldCancelKey(const KeyMemento& memento,
4366         const CancelationOptions& options) {
4367     if (options.keyCode != -1 && memento.keyCode != options.keyCode) {
4368         return false;
4369     }
4370 
4371     if (options.deviceId != -1 && memento.deviceId != options.deviceId) {
4372         return false;
4373     }
4374 
4375     switch (options.mode) {
4376     case CancelationOptions::CANCEL_ALL_EVENTS:
4377     case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
4378         return true;
4379     case CancelationOptions::CANCEL_FALLBACK_EVENTS:
4380         return memento.flags & AKEY_EVENT_FLAG_FALLBACK;
4381     default:
4382         return false;
4383     }
4384 }
4385 
shouldCancelMotion(const MotionMemento & memento,const CancelationOptions & options)4386 bool InputDispatcher::InputState::shouldCancelMotion(const MotionMemento& memento,
4387         const CancelationOptions& options) {
4388     if (options.deviceId != -1 && memento.deviceId != options.deviceId) {
4389         return false;
4390     }
4391 
4392     switch (options.mode) {
4393     case CancelationOptions::CANCEL_ALL_EVENTS:
4394         return true;
4395     case CancelationOptions::CANCEL_POINTER_EVENTS:
4396         return memento.source & AINPUT_SOURCE_CLASS_POINTER;
4397     case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
4398         return !(memento.source & AINPUT_SOURCE_CLASS_POINTER);
4399     default:
4400         return false;
4401     }
4402 }
4403 
4404 
4405 // --- InputDispatcher::Connection ---
4406 
Connection(const sp<InputChannel> & inputChannel,const sp<InputWindowHandle> & inputWindowHandle,bool monitor)4407 InputDispatcher::Connection::Connection(const sp<InputChannel>& inputChannel,
4408         const sp<InputWindowHandle>& inputWindowHandle, bool monitor) :
4409         status(STATUS_NORMAL), inputChannel(inputChannel), inputWindowHandle(inputWindowHandle),
4410         monitor(monitor),
4411         inputPublisher(inputChannel), inputPublisherBlocked(false) {
4412 }
4413 
~Connection()4414 InputDispatcher::Connection::~Connection() {
4415 }
4416 
getWindowName() const4417 const std::string InputDispatcher::Connection::getWindowName() const {
4418     if (inputWindowHandle != NULL) {
4419         return inputWindowHandle->getName();
4420     }
4421     if (monitor) {
4422         return "monitor";
4423     }
4424     return "?";
4425 }
4426 
getStatusLabel() const4427 const char* InputDispatcher::Connection::getStatusLabel() const {
4428     switch (status) {
4429     case STATUS_NORMAL:
4430         return "NORMAL";
4431 
4432     case STATUS_BROKEN:
4433         return "BROKEN";
4434 
4435     case STATUS_ZOMBIE:
4436         return "ZOMBIE";
4437 
4438     default:
4439         return "UNKNOWN";
4440     }
4441 }
4442 
findWaitQueueEntry(uint32_t seq)4443 InputDispatcher::DispatchEntry* InputDispatcher::Connection::findWaitQueueEntry(uint32_t seq) {
4444     for (DispatchEntry* entry = waitQueue.head; entry != NULL; entry = entry->next) {
4445         if (entry->seq == seq) {
4446             return entry;
4447         }
4448     }
4449     return NULL;
4450 }
4451 
4452 
4453 // --- InputDispatcher::CommandEntry ---
4454 
CommandEntry(Command command)4455 InputDispatcher::CommandEntry::CommandEntry(Command command) :
4456     command(command), eventTime(0), keyEntry(NULL), userActivityEventType(0),
4457     seq(0), handled(false) {
4458 }
4459 
~CommandEntry()4460 InputDispatcher::CommandEntry::~CommandEntry() {
4461 }
4462 
4463 
4464 // --- InputDispatcher::TouchState ---
4465 
TouchState()4466 InputDispatcher::TouchState::TouchState() :
4467     down(false), split(false), deviceId(-1), source(0), displayId(-1) {
4468 }
4469 
~TouchState()4470 InputDispatcher::TouchState::~TouchState() {
4471 }
4472 
reset()4473 void InputDispatcher::TouchState::reset() {
4474     down = false;
4475     split = false;
4476     deviceId = -1;
4477     source = 0;
4478     displayId = -1;
4479     windows.clear();
4480 }
4481 
copyFrom(const TouchState & other)4482 void InputDispatcher::TouchState::copyFrom(const TouchState& other) {
4483     down = other.down;
4484     split = other.split;
4485     deviceId = other.deviceId;
4486     source = other.source;
4487     displayId = other.displayId;
4488     windows = other.windows;
4489 }
4490 
addOrUpdateWindow(const sp<InputWindowHandle> & windowHandle,int32_t targetFlags,BitSet32 pointerIds)4491 void InputDispatcher::TouchState::addOrUpdateWindow(const sp<InputWindowHandle>& windowHandle,
4492         int32_t targetFlags, BitSet32 pointerIds) {
4493     if (targetFlags & InputTarget::FLAG_SPLIT) {
4494         split = true;
4495     }
4496 
4497     for (size_t i = 0; i < windows.size(); i++) {
4498         TouchedWindow& touchedWindow = windows.editItemAt(i);
4499         if (touchedWindow.windowHandle == windowHandle) {
4500             touchedWindow.targetFlags |= targetFlags;
4501             if (targetFlags & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
4502                 touchedWindow.targetFlags &= ~InputTarget::FLAG_DISPATCH_AS_IS;
4503             }
4504             touchedWindow.pointerIds.value |= pointerIds.value;
4505             return;
4506         }
4507     }
4508 
4509     windows.push();
4510 
4511     TouchedWindow& touchedWindow = windows.editTop();
4512     touchedWindow.windowHandle = windowHandle;
4513     touchedWindow.targetFlags = targetFlags;
4514     touchedWindow.pointerIds = pointerIds;
4515 }
4516 
removeWindow(const sp<InputWindowHandle> & windowHandle)4517 void InputDispatcher::TouchState::removeWindow(const sp<InputWindowHandle>& windowHandle) {
4518     for (size_t i = 0; i < windows.size(); i++) {
4519         if (windows.itemAt(i).windowHandle == windowHandle) {
4520             windows.removeAt(i);
4521             return;
4522         }
4523     }
4524 }
4525 
filterNonAsIsTouchWindows()4526 void InputDispatcher::TouchState::filterNonAsIsTouchWindows() {
4527     for (size_t i = 0 ; i < windows.size(); ) {
4528         TouchedWindow& window = windows.editItemAt(i);
4529         if (window.targetFlags & (InputTarget::FLAG_DISPATCH_AS_IS
4530                 | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER)) {
4531             window.targetFlags &= ~InputTarget::FLAG_DISPATCH_MASK;
4532             window.targetFlags |= InputTarget::FLAG_DISPATCH_AS_IS;
4533             i += 1;
4534         } else {
4535             windows.removeAt(i);
4536         }
4537     }
4538 }
4539 
getFirstForegroundWindowHandle() const4540 sp<InputWindowHandle> InputDispatcher::TouchState::getFirstForegroundWindowHandle() const {
4541     for (size_t i = 0; i < windows.size(); i++) {
4542         const TouchedWindow& window = windows.itemAt(i);
4543         if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
4544             return window.windowHandle;
4545         }
4546     }
4547     return NULL;
4548 }
4549 
isSlippery() const4550 bool InputDispatcher::TouchState::isSlippery() const {
4551     // Must have exactly one foreground window.
4552     bool haveSlipperyForegroundWindow = false;
4553     for (size_t i = 0; i < windows.size(); i++) {
4554         const TouchedWindow& window = windows.itemAt(i);
4555         if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
4556             if (haveSlipperyForegroundWindow
4557                     || !(window.windowHandle->getInfo()->layoutParamsFlags
4558                             & InputWindowInfo::FLAG_SLIPPERY)) {
4559                 return false;
4560             }
4561             haveSlipperyForegroundWindow = true;
4562         }
4563     }
4564     return haveSlipperyForegroundWindow;
4565 }
4566 
4567 
4568 // --- InputDispatcherThread ---
4569 
InputDispatcherThread(const sp<InputDispatcherInterface> & dispatcher)4570 InputDispatcherThread::InputDispatcherThread(const sp<InputDispatcherInterface>& dispatcher) :
4571         Thread(/*canCallJava*/ true), mDispatcher(dispatcher) {
4572 }
4573 
~InputDispatcherThread()4574 InputDispatcherThread::~InputDispatcherThread() {
4575 }
4576 
threadLoop()4577 bool InputDispatcherThread::threadLoop() {
4578     mDispatcher->dispatchOnce();
4579     return true;
4580 }
4581 
4582 } // namespace android
4583