OSDN Git Service

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