OSDN Git Service

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