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