blob: 87a6c1bab8db62f5cd3f76215087d585e0fc1bf2 [file] [log] [blame]
Jeff Brownb4ff35d2011-01-02 16:37:43 -08001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070017#define LOG_TAG "InputDispatcher"
Jeff Brown481c1572012-03-09 14:41:15 -080018#define ATRACE_TAG ATRACE_TAG_INPUT
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070019
20//#define LOG_NDEBUG 0
21
22// Log detailed debug messages about each inbound event notification to the dispatcher.
Jeff Brown349703e2010-06-22 01:27:15 -070023#define DEBUG_INBOUND_EVENT_DETAILS 0
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070024
25// Log detailed debug messages about each outbound event processed by the dispatcher.
Jeff Brown349703e2010-06-22 01:27:15 -070026#define DEBUG_OUTBOUND_EVENT_DETAILS 0
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070027
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070028// Log debug messages about the dispatch cycle.
Jeff Brown349703e2010-06-22 01:27:15 -070029#define DEBUG_DISPATCH_CYCLE 0
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070030
Jeff Brown9c3cda02010-06-15 01:31:58 -070031// Log debug messages about registrations.
Jeff Brown349703e2010-06-22 01:27:15 -070032#define DEBUG_REGISTRATION 0
Jeff Brown9c3cda02010-06-15 01:31:58 -070033
Jeff Brown7fbdc842010-06-17 20:52:56 -070034// Log debug messages about input event injection.
Jeff Brown349703e2010-06-22 01:27:15 -070035#define DEBUG_INJECTION 0
Jeff Brown7fbdc842010-06-17 20:52:56 -070036
Jeff Brownb88102f2010-09-08 11:49:43 -070037// 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
Jeff Browna032cc02011-03-07 16:56:21 -080043// Log debug messages about hover events.
44#define DEBUG_HOVER 0
45
Jeff Brownb4ff35d2011-01-02 16:37:43 -080046#include "InputDispatcher.h"
47
Jeff Brown481c1572012-03-09 14:41:15 -080048#include <utils/Trace.h>
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070049#include <cutils/log.h>
Mathias Agopianb93a03f82012-02-17 15:34:57 -080050#include <androidfw/PowerManager.h>
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070051
52#include <stddef.h>
53#include <unistd.h>
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070054#include <errno.h>
55#include <limits.h>
Jeff Brown22aa5122012-06-17 12:01:06 -070056#include <time.h>
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070057
Jeff Brownf2f487182010-10-01 17:46:21 -070058#define INDENT " "
59#define INDENT2 " "
Jeff Brown265f1cc2012-06-11 18:01:06 -070060#define INDENT3 " "
61#define INDENT4 " "
Jeff Brownf2f487182010-10-01 17:46:21 -070062
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070063namespace android {
64
Jeff Brownb88102f2010-09-08 11:49:43 -070065// Default input dispatching timeout if there is no focused application or paused window
66// from which to determine an appropriate dispatching timeout.
67const 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.
72const nsecs_t APP_SWITCH_TIMEOUT = 500 * 1000000LL; // 0.5sec
73
Jeff Brown928e0542011-01-10 11:17:36 -080074// Amount of time to allow for an event to be dispatched (measured since its eventTime)
75// before considering it stale and dropping it.
76const nsecs_t STALE_EVENT_TIMEOUT = 10000 * 1000000LL; // 10sec
77
Jeff Brownd1c48a02012-02-06 19:12:47 -080078// 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.
82const nsecs_t STREAM_AHEAD_EVENT_TIMEOUT = 500 * 1000000LL; // 0.5sec
83
Jeff Brown265f1cc2012-06-11 18:01:06 -070084// Log a warning when an event takes longer than this to process, even if an ANR does not occur.
85const nsecs_t SLOW_EVENT_PROCESSING_WARNING_TIMEOUT = 2000 * 1000000LL; // 2sec
86
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070087
Jeff Brown7fbdc842010-06-17 20:52:56 -070088static inline nsecs_t now() {
89 return systemTime(SYSTEM_TIME_MONOTONIC);
90}
91
Jeff Brownb88102f2010-09-08 11:49:43 -070092static inline const char* toString(bool value) {
93 return value ? "true" : "false";
94}
95
Jeff Brown01ce2e92010-09-26 22:20:12 -070096static inline int32_t getMotionEventActionPointerIndex(int32_t action) {
97 return (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK)
98 >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
99}
100
101static bool isValidKeyAction(int32_t action) {
102 switch (action) {
103 case AKEY_EVENT_ACTION_DOWN:
104 case AKEY_EVENT_ACTION_UP:
105 return true;
106 default:
107 return false;
108 }
109}
110
111static bool validateKeyEvent(int32_t action) {
112 if (! isValidKeyAction(action)) {
Steve Block3762c312012-01-06 19:20:56 +0000113 ALOGE("Key event has invalid action code 0x%x", action);
Jeff Brown01ce2e92010-09-26 22:20:12 -0700114 return false;
115 }
116 return true;
117}
118
Jeff Brownb6997262010-10-08 22:31:17 -0700119static bool isValidMotionAction(int32_t action, size_t pointerCount) {
Jeff Brown01ce2e92010-09-26 22:20:12 -0700120 switch (action & AMOTION_EVENT_ACTION_MASK) {
121 case AMOTION_EVENT_ACTION_DOWN:
122 case AMOTION_EVENT_ACTION_UP:
123 case AMOTION_EVENT_ACTION_CANCEL:
124 case AMOTION_EVENT_ACTION_MOVE:
Jeff Brown01ce2e92010-09-26 22:20:12 -0700125 case AMOTION_EVENT_ACTION_OUTSIDE:
Jeff Browna032cc02011-03-07 16:56:21 -0800126 case AMOTION_EVENT_ACTION_HOVER_ENTER:
Jeff Browncc0c1592011-02-19 05:07:28 -0800127 case AMOTION_EVENT_ACTION_HOVER_MOVE:
Jeff Browna032cc02011-03-07 16:56:21 -0800128 case AMOTION_EVENT_ACTION_HOVER_EXIT:
Jeff Brown33bbfd22011-02-24 20:55:35 -0800129 case AMOTION_EVENT_ACTION_SCROLL:
Jeff Brown01ce2e92010-09-26 22:20:12 -0700130 return true;
Jeff Brownb6997262010-10-08 22:31:17 -0700131 case AMOTION_EVENT_ACTION_POINTER_DOWN:
132 case AMOTION_EVENT_ACTION_POINTER_UP: {
133 int32_t index = getMotionEventActionPointerIndex(action);
134 return index >= 0 && size_t(index) < pointerCount;
135 }
Jeff Brown01ce2e92010-09-26 22:20:12 -0700136 default:
137 return false;
138 }
139}
140
141static bool validateMotionEvent(int32_t action, size_t pointerCount,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700142 const PointerProperties* pointerProperties) {
Jeff Brownb6997262010-10-08 22:31:17 -0700143 if (! isValidMotionAction(action, pointerCount)) {
Steve Block3762c312012-01-06 19:20:56 +0000144 ALOGE("Motion event has invalid action code 0x%x", action);
Jeff Brown01ce2e92010-09-26 22:20:12 -0700145 return false;
146 }
147 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Steve Block3762c312012-01-06 19:20:56 +0000148 ALOGE("Motion event has invalid pointer count %d; value must be between 1 and %d.",
Jeff Brown01ce2e92010-09-26 22:20:12 -0700149 pointerCount, MAX_POINTERS);
150 return false;
151 }
Jeff Brownc3db8582010-10-20 15:33:38 -0700152 BitSet32 pointerIdBits;
Jeff Brown01ce2e92010-09-26 22:20:12 -0700153 for (size_t i = 0; i < pointerCount; i++) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700154 int32_t id = pointerProperties[i].id;
Jeff Brownc3db8582010-10-20 15:33:38 -0700155 if (id < 0 || id > MAX_POINTER_ID) {
Steve Block3762c312012-01-06 19:20:56 +0000156 ALOGE("Motion event has invalid pointer id %d; value must be between 0 and %d",
Jeff Brownc3db8582010-10-20 15:33:38 -0700157 id, MAX_POINTER_ID);
Jeff Brown01ce2e92010-09-26 22:20:12 -0700158 return false;
159 }
Jeff Brownc3db8582010-10-20 15:33:38 -0700160 if (pointerIdBits.hasBit(id)) {
Steve Block3762c312012-01-06 19:20:56 +0000161 ALOGE("Motion event has duplicate pointer id %d", id);
Jeff Brownc3db8582010-10-20 15:33:38 -0700162 return false;
163 }
164 pointerIdBits.markBit(id);
Jeff Brown01ce2e92010-09-26 22:20:12 -0700165 }
166 return true;
167}
168
Jeff Brown83d616a2012-09-09 20:33:43 -0700169static bool isMainDisplay(int32_t displayId) {
170 return displayId == ADISPLAY_ID_DEFAULT || displayId == ADISPLAY_ID_NONE;
171}
172
Jeff Brownfbf09772011-01-16 14:06:57 -0800173static void dumpRegion(String8& dump, const SkRegion& region) {
174 if (region.isEmpty()) {
175 dump.append("<empty>");
176 return;
177 }
178
179 bool first = true;
180 for (SkRegion::Iterator it(region); !it.done(); it.next()) {
181 if (first) {
182 first = false;
183 } else {
184 dump.append("|");
185 }
186 const SkIRect& rect = it.rect();
187 dump.appendFormat("[%d,%d][%d,%d]", rect.fLeft, rect.fTop, rect.fRight, rect.fBottom);
188 }
189}
190
Jeff Brownb88102f2010-09-08 11:49:43 -0700191
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700192// --- InputDispatcher ---
193
Jeff Brown9c3cda02010-06-15 01:31:58 -0700194InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy) :
Jeff Brownb88102f2010-09-08 11:49:43 -0700195 mPolicy(policy),
Jeff Brown928e0542011-01-10 11:17:36 -0800196 mPendingEvent(NULL), mAppSwitchSawKeyDown(false), mAppSwitchDueTime(LONG_LONG_MAX),
197 mNextUnblockedEvent(NULL),
Jeff Brownc042ee22012-05-08 13:03:42 -0700198 mDispatchEnabled(false), mDispatchFrozen(false), mInputFilterEnabled(false),
Jeff Brown9302c872011-07-13 22:51:29 -0700199 mInputTargetWaitCause(INPUT_TARGET_WAIT_CAUSE_NONE) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -0700200 mLooper = new Looper(false);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700201
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700202 mKeyRepeatState.lastKeyEntry = NULL;
Jeff Brown9c3cda02010-06-15 01:31:58 -0700203
Jeff Brown214eaf42011-05-26 19:17:02 -0700204 policy->getDispatcherConfiguration(&mConfig);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700205}
206
207InputDispatcher::~InputDispatcher() {
Jeff Brownb88102f2010-09-08 11:49:43 -0700208 { // acquire lock
209 AutoMutex _l(mLock);
210
211 resetKeyRepeatLocked();
Jeff Brown54a18252010-09-16 14:07:33 -0700212 releasePendingEventLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -0700213 drainInboundQueueLocked();
214 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700215
Jeff Browncbee6d62012-02-03 20:11:27 -0800216 while (mConnectionsByFd.size() != 0) {
217 unregisterInputChannel(mConnectionsByFd.valueAt(0)->inputChannel);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700218 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700219}
220
221void InputDispatcher::dispatchOnce() {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700222 nsecs_t nextWakeupTime = LONG_LONG_MAX;
223 { // acquire lock
224 AutoMutex _l(mLock);
Jeff Brown112b5f52012-01-27 17:32:06 -0800225 mDispatcherIsAliveCondition.broadcast();
226
Jeff Brown214eaf42011-05-26 19:17:02 -0700227 dispatchOnceInnerLocked(&nextWakeupTime);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700228
Jeff Brownb88102f2010-09-08 11:49:43 -0700229 if (runCommandsLockedInterruptible()) {
230 nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700231 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700232 } // release lock
233
Jeff Brownb88102f2010-09-08 11:49:43 -0700234 // Wait for callback or timeout or wake. (make sure we round up, not down)
235 nsecs_t currentTime = now();
Jeff Brownaa3855d2011-03-17 01:34:19 -0700236 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
Jeff Brown4fe6c3e2010-09-13 23:17:30 -0700237 mLooper->pollOnce(timeoutMillis);
Jeff Brownb88102f2010-09-08 11:49:43 -0700238}
239
Jeff Brown214eaf42011-05-26 19:17:02 -0700240void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700241 nsecs_t currentTime = now();
242
243 // Reset the key repeat timer whenever we disallow key events, even if the next event
244 // is not a key. This is to ensure that we abort a key repeat if the device is just coming
245 // out of sleep.
Jeff Brown214eaf42011-05-26 19:17:02 -0700246 if (!mPolicy->isKeyRepeatEnabled()) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700247 resetKeyRepeatLocked();
248 }
249
Jeff Brownb88102f2010-09-08 11:49:43 -0700250 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
251 if (mDispatchFrozen) {
252#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +0000253 ALOGD("Dispatch frozen. Waiting some more.");
Jeff Brownb88102f2010-09-08 11:49:43 -0700254#endif
255 return;
256 }
257
258 // Optimize latency of app switches.
259 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
260 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
261 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
262 if (mAppSwitchDueTime < *nextWakeupTime) {
263 *nextWakeupTime = mAppSwitchDueTime;
264 }
265
Jeff Brownb88102f2010-09-08 11:49:43 -0700266 // Ready to start a new event.
267 // If we don't already have a pending event, go grab one.
268 if (! mPendingEvent) {
269 if (mInboundQueue.isEmpty()) {
270 if (isAppSwitchDue) {
271 // The inbound queue is empty so the app switch key we were waiting
272 // for will never arrive. Stop waiting for it.
273 resetPendingAppSwitchLocked(false);
274 isAppSwitchDue = false;
275 }
276
277 // Synthesize a key repeat if appropriate.
278 if (mKeyRepeatState.lastKeyEntry) {
279 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
Jeff Brown214eaf42011-05-26 19:17:02 -0700280 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700281 } else {
282 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
283 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
284 }
285 }
286 }
Jeff Browncc4f7db2011-08-30 20:34:48 -0700287
288 // Nothing to do if there is no pending event.
Jeff Browne9bb9be2012-02-06 15:47:55 -0800289 if (!mPendingEvent) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700290 return;
291 }
292 } else {
293 // Inbound queue has at least one entry.
Jeff Browne9bb9be2012-02-06 15:47:55 -0800294 mPendingEvent = mInboundQueue.dequeueAtHead();
Jeff Brown481c1572012-03-09 14:41:15 -0800295 traceInboundQueueLengthLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -0700296 }
Jeff Browne2fe69e2010-10-18 13:21:23 -0700297
298 // Poke user activity for this event.
299 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
300 pokeUserActivityLocked(mPendingEvent);
301 }
Jeff Browne9bb9be2012-02-06 15:47:55 -0800302
303 // Get ready to dispatch the event.
304 resetANRTimeoutsLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -0700305 }
306
307 // Now we have an event to dispatch.
Jeff Brown928e0542011-01-10 11:17:36 -0800308 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Steve Blockec193de2012-01-09 18:35:44 +0000309 ALOG_ASSERT(mPendingEvent != NULL);
Jeff Brown54a18252010-09-16 14:07:33 -0700310 bool done = false;
Jeff Brownb6997262010-10-08 22:31:17 -0700311 DropReason dropReason = DROP_REASON_NOT_DROPPED;
312 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
313 dropReason = DROP_REASON_POLICY;
314 } else if (!mDispatchEnabled) {
315 dropReason = DROP_REASON_DISABLED;
316 }
Jeff Brown928e0542011-01-10 11:17:36 -0800317
318 if (mNextUnblockedEvent == mPendingEvent) {
319 mNextUnblockedEvent = NULL;
320 }
321
Jeff Brownb88102f2010-09-08 11:49:43 -0700322 switch (mPendingEvent->type) {
323 case EventEntry::TYPE_CONFIGURATION_CHANGED: {
324 ConfigurationChangedEntry* typedEntry =
325 static_cast<ConfigurationChangedEntry*>(mPendingEvent);
Jeff Brown54a18252010-09-16 14:07:33 -0700326 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Jeff Brownb6997262010-10-08 22:31:17 -0700327 dropReason = DROP_REASON_NOT_DROPPED; // configuration changes are never dropped
Jeff Brownb88102f2010-09-08 11:49:43 -0700328 break;
329 }
330
Jeff Brown65fd2512011-08-18 11:20:58 -0700331 case EventEntry::TYPE_DEVICE_RESET: {
332 DeviceResetEntry* typedEntry =
333 static_cast<DeviceResetEntry*>(mPendingEvent);
334 done = dispatchDeviceResetLocked(currentTime, typedEntry);
335 dropReason = DROP_REASON_NOT_DROPPED; // device resets are never dropped
336 break;
337 }
338
Jeff Brownb88102f2010-09-08 11:49:43 -0700339 case EventEntry::TYPE_KEY: {
340 KeyEntry* typedEntry = static_cast<KeyEntry*>(mPendingEvent);
Jeff Brownb6997262010-10-08 22:31:17 -0700341 if (isAppSwitchDue) {
342 if (isAppSwitchKeyEventLocked(typedEntry)) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700343 resetPendingAppSwitchLocked(true);
Jeff Brownb6997262010-10-08 22:31:17 -0700344 isAppSwitchDue = false;
345 } else if (dropReason == DROP_REASON_NOT_DROPPED) {
346 dropReason = DROP_REASON_APP_SWITCH;
Jeff Brownb88102f2010-09-08 11:49:43 -0700347 }
348 }
Jeff Brown928e0542011-01-10 11:17:36 -0800349 if (dropReason == DROP_REASON_NOT_DROPPED
350 && isStaleEventLocked(currentTime, typedEntry)) {
351 dropReason = DROP_REASON_STALE;
352 }
353 if (dropReason == DROP_REASON_NOT_DROPPED && mNextUnblockedEvent) {
354 dropReason = DROP_REASON_BLOCKED;
355 }
Jeff Brown214eaf42011-05-26 19:17:02 -0700356 done = dispatchKeyLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700357 break;
358 }
359
360 case EventEntry::TYPE_MOTION: {
361 MotionEntry* typedEntry = static_cast<MotionEntry*>(mPendingEvent);
Jeff Brownb6997262010-10-08 22:31:17 -0700362 if (dropReason == DROP_REASON_NOT_DROPPED && isAppSwitchDue) {
363 dropReason = DROP_REASON_APP_SWITCH;
Jeff Brownb88102f2010-09-08 11:49:43 -0700364 }
Jeff Brown928e0542011-01-10 11:17:36 -0800365 if (dropReason == DROP_REASON_NOT_DROPPED
366 && isStaleEventLocked(currentTime, typedEntry)) {
367 dropReason = DROP_REASON_STALE;
368 }
369 if (dropReason == DROP_REASON_NOT_DROPPED && mNextUnblockedEvent) {
370 dropReason = DROP_REASON_BLOCKED;
371 }
Jeff Brownb6997262010-10-08 22:31:17 -0700372 done = dispatchMotionLocked(currentTime, typedEntry,
Jeff Browne20c9e02010-10-11 14:20:19 -0700373 &dropReason, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700374 break;
375 }
376
377 default:
Steve Blockec193de2012-01-09 18:35:44 +0000378 ALOG_ASSERT(false);
Jeff Brownb88102f2010-09-08 11:49:43 -0700379 break;
380 }
381
Jeff Brown54a18252010-09-16 14:07:33 -0700382 if (done) {
Jeff Brownb6997262010-10-08 22:31:17 -0700383 if (dropReason != DROP_REASON_NOT_DROPPED) {
384 dropInboundEventLocked(mPendingEvent, dropReason);
385 }
386
Jeff Brown54a18252010-09-16 14:07:33 -0700387 releasePendingEventLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -0700388 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
389 }
390}
391
392bool InputDispatcher::enqueueInboundEventLocked(EventEntry* entry) {
393 bool needWake = mInboundQueue.isEmpty();
394 mInboundQueue.enqueueAtTail(entry);
Jeff Brown481c1572012-03-09 14:41:15 -0800395 traceInboundQueueLengthLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -0700396
397 switch (entry->type) {
Jeff Brownb6997262010-10-08 22:31:17 -0700398 case EventEntry::TYPE_KEY: {
Jeff Brown928e0542011-01-10 11:17:36 -0800399 // Optimize app switch latency.
400 // If the application takes too long to catch up then we drop all events preceding
401 // the app switch key.
Jeff Brownb6997262010-10-08 22:31:17 -0700402 KeyEntry* keyEntry = static_cast<KeyEntry*>(entry);
403 if (isAppSwitchKeyEventLocked(keyEntry)) {
404 if (keyEntry->action == AKEY_EVENT_ACTION_DOWN) {
405 mAppSwitchSawKeyDown = true;
406 } else if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
407 if (mAppSwitchSawKeyDown) {
408#if DEBUG_APP_SWITCH
Steve Block5baa3a62011-12-20 16:23:08 +0000409 ALOGD("App switch is pending!");
Jeff Brownb6997262010-10-08 22:31:17 -0700410#endif
411 mAppSwitchDueTime = keyEntry->eventTime + APP_SWITCH_TIMEOUT;
412 mAppSwitchSawKeyDown = false;
413 needWake = true;
414 }
415 }
416 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700417 break;
418 }
Jeff Brown928e0542011-01-10 11:17:36 -0800419
420 case EventEntry::TYPE_MOTION: {
421 // Optimize case where the current application is unresponsive and the user
422 // decides to touch a window in a different application.
423 // If the application takes too long to catch up then we drop all events preceding
424 // the touch into the other window.
425 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
Jeff Brown33bbfd22011-02-24 20:55:35 -0800426 if (motionEntry->action == AMOTION_EVENT_ACTION_DOWN
Jeff Brown928e0542011-01-10 11:17:36 -0800427 && (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER)
428 && mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY
Jeff Brown9302c872011-07-13 22:51:29 -0700429 && mInputTargetWaitApplicationHandle != NULL) {
Jeff Brown83d616a2012-09-09 20:33:43 -0700430 int32_t displayId = motionEntry->displayId;
Jeff Brown3241b6b2012-02-03 15:08:02 -0800431 int32_t x = int32_t(motionEntry->pointerCoords[0].
Jeff Brownebbd5d12011-02-17 13:01:34 -0800432 getAxisValue(AMOTION_EVENT_AXIS_X));
Jeff Brown3241b6b2012-02-03 15:08:02 -0800433 int32_t y = int32_t(motionEntry->pointerCoords[0].
Jeff Brownebbd5d12011-02-17 13:01:34 -0800434 getAxisValue(AMOTION_EVENT_AXIS_Y));
Jeff Brown83d616a2012-09-09 20:33:43 -0700435 sp<InputWindowHandle> touchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y);
Jeff Brown9302c872011-07-13 22:51:29 -0700436 if (touchedWindowHandle != NULL
437 && touchedWindowHandle->inputApplicationHandle
438 != mInputTargetWaitApplicationHandle) {
Jeff Brown928e0542011-01-10 11:17:36 -0800439 // User touched a different application than the one we are waiting on.
440 // Flag the event, and start pruning the input queue.
441 mNextUnblockedEvent = motionEntry;
442 needWake = true;
443 }
444 }
445 break;
446 }
Jeff Brownb6997262010-10-08 22:31:17 -0700447 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700448
449 return needWake;
450}
451
Jeff Brown83d616a2012-09-09 20:33:43 -0700452sp<InputWindowHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId,
453 int32_t x, int32_t y) {
Jeff Brown928e0542011-01-10 11:17:36 -0800454 // Traverse windows from front to back to find touched window.
Jeff Brown9302c872011-07-13 22:51:29 -0700455 size_t numWindows = mWindowHandles.size();
Jeff Brown928e0542011-01-10 11:17:36 -0800456 for (size_t i = 0; i < numWindows; i++) {
Jeff Brown9302c872011-07-13 22:51:29 -0700457 sp<InputWindowHandle> windowHandle = mWindowHandles.itemAt(i);
Jeff Browncc4f7db2011-08-30 20:34:48 -0700458 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Jeff Brown83d616a2012-09-09 20:33:43 -0700459 if (windowInfo->displayId == displayId) {
460 int32_t flags = windowInfo->layoutParamsFlags;
Jeff Brown928e0542011-01-10 11:17:36 -0800461
Jeff Brown83d616a2012-09-09 20:33:43 -0700462 if (windowInfo->visible) {
463 if (!(flags & InputWindowInfo::FLAG_NOT_TOUCHABLE)) {
464 bool isTouchModal = (flags & (InputWindowInfo::FLAG_NOT_FOCUSABLE
465 | InputWindowInfo::FLAG_NOT_TOUCH_MODAL)) == 0;
466 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
467 // Found window.
468 return windowHandle;
469 }
Jeff Brown928e0542011-01-10 11:17:36 -0800470 }
471 }
Jeff Brown928e0542011-01-10 11:17:36 -0800472
Jeff Brown83d616a2012-09-09 20:33:43 -0700473 if (flags & InputWindowInfo::FLAG_SYSTEM_ERROR) {
474 // Error window is on top but not visible, so touch is dropped.
475 return NULL;
476 }
Jeff Brown928e0542011-01-10 11:17:36 -0800477 }
478 }
479 return NULL;
480}
481
Jeff Brownb6997262010-10-08 22:31:17 -0700482void InputDispatcher::dropInboundEventLocked(EventEntry* entry, DropReason dropReason) {
483 const char* reason;
484 switch (dropReason) {
485 case DROP_REASON_POLICY:
Jeff Browne20c9e02010-10-11 14:20:19 -0700486#if DEBUG_INBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +0000487 ALOGD("Dropped event because policy consumed it.");
Jeff Browne20c9e02010-10-11 14:20:19 -0700488#endif
Jeff Brown3122e442010-10-11 23:32:49 -0700489 reason = "inbound event was dropped because the policy consumed it";
Jeff Brownb6997262010-10-08 22:31:17 -0700490 break;
491 case DROP_REASON_DISABLED:
Steve Block6215d3f2012-01-04 20:05:49 +0000492 ALOGI("Dropped event because input dispatch is disabled.");
Jeff Brownb6997262010-10-08 22:31:17 -0700493 reason = "inbound event was dropped because input dispatch is disabled";
494 break;
495 case DROP_REASON_APP_SWITCH:
Steve Block6215d3f2012-01-04 20:05:49 +0000496 ALOGI("Dropped event because of pending overdue app switch.");
Jeff Brownb6997262010-10-08 22:31:17 -0700497 reason = "inbound event was dropped because of pending overdue app switch";
498 break;
Jeff Brown928e0542011-01-10 11:17:36 -0800499 case DROP_REASON_BLOCKED:
Steve Block6215d3f2012-01-04 20:05:49 +0000500 ALOGI("Dropped event because the current application is not responding and the user "
Jeff Brown81346812011-06-28 20:08:48 -0700501 "has started interacting with a different application.");
Jeff Brown928e0542011-01-10 11:17:36 -0800502 reason = "inbound event was dropped because the current application is not responding "
Jeff Brown81346812011-06-28 20:08:48 -0700503 "and the user has started interacting with a different application";
Jeff Brown928e0542011-01-10 11:17:36 -0800504 break;
505 case DROP_REASON_STALE:
Steve Block6215d3f2012-01-04 20:05:49 +0000506 ALOGI("Dropped event because it is stale.");
Jeff Brown928e0542011-01-10 11:17:36 -0800507 reason = "inbound event was dropped because it is stale";
508 break;
Jeff Brownb6997262010-10-08 22:31:17 -0700509 default:
Steve Blockec193de2012-01-09 18:35:44 +0000510 ALOG_ASSERT(false);
Jeff Brownb6997262010-10-08 22:31:17 -0700511 return;
512 }
513
514 switch (entry->type) {
Jeff Brownda3d5a92011-03-29 15:11:34 -0700515 case EventEntry::TYPE_KEY: {
516 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
517 synthesizeCancelationEventsForAllConnectionsLocked(options);
Jeff Brownb6997262010-10-08 22:31:17 -0700518 break;
Jeff Brownda3d5a92011-03-29 15:11:34 -0700519 }
Jeff Brownb6997262010-10-08 22:31:17 -0700520 case EventEntry::TYPE_MOTION: {
521 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
522 if (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) {
Jeff Brownda3d5a92011-03-29 15:11:34 -0700523 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
524 synthesizeCancelationEventsForAllConnectionsLocked(options);
Jeff Brownb6997262010-10-08 22:31:17 -0700525 } else {
Jeff Brownda3d5a92011-03-29 15:11:34 -0700526 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
527 synthesizeCancelationEventsForAllConnectionsLocked(options);
Jeff Brownb6997262010-10-08 22:31:17 -0700528 }
529 break;
530 }
531 }
532}
533
534bool InputDispatcher::isAppSwitchKeyCode(int32_t keyCode) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700535 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL;
536}
537
Jeff Brownb6997262010-10-08 22:31:17 -0700538bool InputDispatcher::isAppSwitchKeyEventLocked(KeyEntry* keyEntry) {
539 return ! (keyEntry->flags & AKEY_EVENT_FLAG_CANCELED)
540 && isAppSwitchKeyCode(keyEntry->keyCode)
Jeff Browne20c9e02010-10-11 14:20:19 -0700541 && (keyEntry->policyFlags & POLICY_FLAG_TRUSTED)
Jeff Brownb6997262010-10-08 22:31:17 -0700542 && (keyEntry->policyFlags & POLICY_FLAG_PASS_TO_USER);
543}
544
Jeff Brownb88102f2010-09-08 11:49:43 -0700545bool InputDispatcher::isAppSwitchPendingLocked() {
546 return mAppSwitchDueTime != LONG_LONG_MAX;
547}
548
Jeff Brownb88102f2010-09-08 11:49:43 -0700549void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
550 mAppSwitchDueTime = LONG_LONG_MAX;
551
552#if DEBUG_APP_SWITCH
553 if (handled) {
Steve Block5baa3a62011-12-20 16:23:08 +0000554 ALOGD("App switch has arrived.");
Jeff Brownb88102f2010-09-08 11:49:43 -0700555 } else {
Steve Block5baa3a62011-12-20 16:23:08 +0000556 ALOGD("App switch was abandoned.");
Jeff Brownb88102f2010-09-08 11:49:43 -0700557 }
558#endif
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700559}
560
Jeff Brown928e0542011-01-10 11:17:36 -0800561bool InputDispatcher::isStaleEventLocked(nsecs_t currentTime, EventEntry* entry) {
562 return currentTime - entry->eventTime >= STALE_EVENT_TIMEOUT;
563}
564
Jeff Brown9c3cda02010-06-15 01:31:58 -0700565bool InputDispatcher::runCommandsLockedInterruptible() {
566 if (mCommandQueue.isEmpty()) {
567 return false;
568 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700569
Jeff Brown9c3cda02010-06-15 01:31:58 -0700570 do {
571 CommandEntry* commandEntry = mCommandQueue.dequeueAtHead();
572
573 Command command = commandEntry->command;
574 (this->*command)(commandEntry); // commands are implicitly 'LockedInterruptible'
575
Jeff Brown7fbdc842010-06-17 20:52:56 -0700576 commandEntry->connection.clear();
Jeff Brownac386072011-07-20 15:19:50 -0700577 delete commandEntry;
Jeff Brown9c3cda02010-06-15 01:31:58 -0700578 } while (! mCommandQueue.isEmpty());
579 return true;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700580}
581
Jeff Brown9c3cda02010-06-15 01:31:58 -0700582InputDispatcher::CommandEntry* InputDispatcher::postCommandLocked(Command command) {
Jeff Brownac386072011-07-20 15:19:50 -0700583 CommandEntry* commandEntry = new CommandEntry(command);
Jeff Brown9c3cda02010-06-15 01:31:58 -0700584 mCommandQueue.enqueueAtTail(commandEntry);
585 return commandEntry;
586}
587
Jeff Brownb88102f2010-09-08 11:49:43 -0700588void InputDispatcher::drainInboundQueueLocked() {
589 while (! mInboundQueue.isEmpty()) {
590 EventEntry* entry = mInboundQueue.dequeueAtHead();
Jeff Brown54a18252010-09-16 14:07:33 -0700591 releaseInboundEventLocked(entry);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700592 }
Jeff Brown481c1572012-03-09 14:41:15 -0800593 traceInboundQueueLengthLocked();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700594}
595
Jeff Brown54a18252010-09-16 14:07:33 -0700596void InputDispatcher::releasePendingEventLocked() {
Jeff Brownb88102f2010-09-08 11:49:43 -0700597 if (mPendingEvent) {
Jeff Browne9bb9be2012-02-06 15:47:55 -0800598 resetANRTimeoutsLocked();
Jeff Brown54a18252010-09-16 14:07:33 -0700599 releaseInboundEventLocked(mPendingEvent);
Jeff Brownb88102f2010-09-08 11:49:43 -0700600 mPendingEvent = NULL;
601 }
602}
603
Jeff Brown54a18252010-09-16 14:07:33 -0700604void InputDispatcher::releaseInboundEventLocked(EventEntry* entry) {
Jeff Brown01ce2e92010-09-26 22:20:12 -0700605 InjectionState* injectionState = entry->injectionState;
606 if (injectionState && injectionState->injectionResult == INPUT_EVENT_INJECTION_PENDING) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700607#if DEBUG_DISPATCH_CYCLE
Steve Block5baa3a62011-12-20 16:23:08 +0000608 ALOGD("Injected inbound event was dropped.");
Jeff Brownb88102f2010-09-08 11:49:43 -0700609#endif
610 setInjectionResultLocked(entry, INPUT_EVENT_INJECTION_FAILED);
611 }
Jeff Brownabb4d442011-08-15 12:55:32 -0700612 if (entry == mNextUnblockedEvent) {
613 mNextUnblockedEvent = NULL;
614 }
Jeff Brownac386072011-07-20 15:19:50 -0700615 entry->release();
Jeff Brownb88102f2010-09-08 11:49:43 -0700616}
617
Jeff Brownb88102f2010-09-08 11:49:43 -0700618void InputDispatcher::resetKeyRepeatLocked() {
619 if (mKeyRepeatState.lastKeyEntry) {
Jeff Brownac386072011-07-20 15:19:50 -0700620 mKeyRepeatState.lastKeyEntry->release();
Jeff Brownb88102f2010-09-08 11:49:43 -0700621 mKeyRepeatState.lastKeyEntry = NULL;
622 }
623}
624
Jeff Brown214eaf42011-05-26 19:17:02 -0700625InputDispatcher::KeyEntry* InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
Jeff Brown349703e2010-06-22 01:27:15 -0700626 KeyEntry* entry = mKeyRepeatState.lastKeyEntry;
627
Jeff Brown349703e2010-06-22 01:27:15 -0700628 // Reuse the repeated key entry if it is otherwise unreferenced.
Jeff Browne20c9e02010-10-11 14:20:19 -0700629 uint32_t policyFlags = (entry->policyFlags & POLICY_FLAG_RAW_MASK)
630 | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700631 if (entry->refCount == 1) {
Jeff Brownac386072011-07-20 15:19:50 -0700632 entry->recycle();
Jeff Brown7fbdc842010-06-17 20:52:56 -0700633 entry->eventTime = currentTime;
Jeff Brown7fbdc842010-06-17 20:52:56 -0700634 entry->policyFlags = policyFlags;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700635 entry->repeatCount += 1;
636 } else {
Jeff Brownac386072011-07-20 15:19:50 -0700637 KeyEntry* newEntry = new KeyEntry(currentTime,
Jeff Brownc5ed5912010-07-14 18:48:53 -0700638 entry->deviceId, entry->source, policyFlags,
Jeff Brown7fbdc842010-06-17 20:52:56 -0700639 entry->action, entry->flags, entry->keyCode, entry->scanCode,
Jeff Brown00fa7bd2010-07-02 15:37:36 -0700640 entry->metaState, entry->repeatCount + 1, entry->downTime);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700641
642 mKeyRepeatState.lastKeyEntry = newEntry;
Jeff Brownac386072011-07-20 15:19:50 -0700643 entry->release();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700644
645 entry = newEntry;
646 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700647 entry->syntheticRepeat = true;
648
649 // Increment reference count since we keep a reference to the event in
650 // mKeyRepeatState.lastKeyEntry in addition to the one we return.
651 entry->refCount += 1;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700652
Jeff Brown214eaf42011-05-26 19:17:02 -0700653 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Jeff Brownb88102f2010-09-08 11:49:43 -0700654 return entry;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700655}
656
Jeff Brownb88102f2010-09-08 11:49:43 -0700657bool InputDispatcher::dispatchConfigurationChangedLocked(
658 nsecs_t currentTime, ConfigurationChangedEntry* entry) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700659#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +0000660 ALOGD("dispatchConfigurationChanged - eventTime=%lld", entry->eventTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700661#endif
662
663 // Reset key repeating in case a keyboard device was added or removed or something.
664 resetKeyRepeatLocked();
665
666 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
667 CommandEntry* commandEntry = postCommandLocked(
668 & InputDispatcher::doNotifyConfigurationChangedInterruptible);
669 commandEntry->eventTime = entry->eventTime;
670 return true;
671}
672
Jeff Brown65fd2512011-08-18 11:20:58 -0700673bool InputDispatcher::dispatchDeviceResetLocked(
674 nsecs_t currentTime, DeviceResetEntry* entry) {
675#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +0000676 ALOGD("dispatchDeviceReset - eventTime=%lld, deviceId=%d", entry->eventTime, entry->deviceId);
Jeff Brown65fd2512011-08-18 11:20:58 -0700677#endif
678
679 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
680 "device was reset");
681 options.deviceId = entry->deviceId;
682 synthesizeCancelationEventsForAllConnectionsLocked(options);
683 return true;
684}
685
Jeff Brown214eaf42011-05-26 19:17:02 -0700686bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, KeyEntry* entry,
Jeff Browne20c9e02010-10-11 14:20:19 -0700687 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Jeff Browne46a0a42010-11-02 17:58:22 -0700688 // Preprocessing.
689 if (! entry->dispatchInProgress) {
690 if (entry->repeatCount == 0
691 && entry->action == AKEY_EVENT_ACTION_DOWN
692 && (entry->policyFlags & POLICY_FLAG_TRUSTED)
Jeff Brown0029c662011-03-30 02:25:18 -0700693 && (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
Jeff Browne46a0a42010-11-02 17:58:22 -0700694 if (mKeyRepeatState.lastKeyEntry
695 && mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode) {
696 // We have seen two identical key downs in a row which indicates that the device
697 // driver is automatically generating key repeats itself. We take note of the
698 // repeat here, but we disable our own next key repeat timer since it is clear that
699 // we will not need to synthesize key repeats ourselves.
700 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
701 resetKeyRepeatLocked();
702 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
703 } else {
704 // Not a repeat. Save key down state in case we do see a repeat later.
705 resetKeyRepeatLocked();
Jeff Brown214eaf42011-05-26 19:17:02 -0700706 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
Jeff Browne46a0a42010-11-02 17:58:22 -0700707 }
708 mKeyRepeatState.lastKeyEntry = entry;
709 entry->refCount += 1;
710 } else if (! entry->syntheticRepeat) {
711 resetKeyRepeatLocked();
712 }
713
Jeff Browne2e01262011-03-02 20:34:30 -0800714 if (entry->repeatCount == 1) {
715 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
716 } else {
717 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
718 }
719
Jeff Browne46a0a42010-11-02 17:58:22 -0700720 entry->dispatchInProgress = true;
Jeff Browne46a0a42010-11-02 17:58:22 -0700721
722 logOutboundKeyDetailsLocked("dispatchKey - ", entry);
723 }
724
Jeff Brown905805a2011-10-12 13:57:59 -0700725 // Handle case where the policy asked us to try again later last time.
726 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
727 if (currentTime < entry->interceptKeyWakeupTime) {
728 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
729 *nextWakeupTime = entry->interceptKeyWakeupTime;
730 }
731 return false; // wait until next wakeup
732 }
733 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
734 entry->interceptKeyWakeupTime = 0;
735 }
736
Jeff Brown54a18252010-09-16 14:07:33 -0700737 // Give the policy a chance to intercept the key.
738 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
Jeff Browne20c9e02010-10-11 14:20:19 -0700739 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Jeff Brown54a18252010-09-16 14:07:33 -0700740 CommandEntry* commandEntry = postCommandLocked(
741 & InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
Jeff Brown9302c872011-07-13 22:51:29 -0700742 if (mFocusedWindowHandle != NULL) {
743 commandEntry->inputWindowHandle = mFocusedWindowHandle;
Jeff Brown54a18252010-09-16 14:07:33 -0700744 }
745 commandEntry->keyEntry = entry;
746 entry->refCount += 1;
747 return false; // wait for the command to run
748 } else {
749 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
750 }
751 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Jeff Browne20c9e02010-10-11 14:20:19 -0700752 if (*dropReason == DROP_REASON_NOT_DROPPED) {
753 *dropReason = DROP_REASON_POLICY;
754 }
Jeff Brown54a18252010-09-16 14:07:33 -0700755 }
756
757 // Clean up if dropping the event.
Jeff Browne20c9e02010-10-11 14:20:19 -0700758 if (*dropReason != DROP_REASON_NOT_DROPPED) {
Jeff Brown3122e442010-10-11 23:32:49 -0700759 setInjectionResultLocked(entry, *dropReason == DROP_REASON_POLICY
760 ? INPUT_EVENT_INJECTION_SUCCEEDED : INPUT_EVENT_INJECTION_FAILED);
Jeff Brown54a18252010-09-16 14:07:33 -0700761 return true;
762 }
763
Jeff Brownb88102f2010-09-08 11:49:43 -0700764 // Identify targets.
Jeff Browne9bb9be2012-02-06 15:47:55 -0800765 Vector<InputTarget> inputTargets;
766 int32_t injectionResult = findFocusedWindowTargetsLocked(currentTime,
767 entry, inputTargets, nextWakeupTime);
768 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
769 return false;
Jeff Brownb88102f2010-09-08 11:49:43 -0700770 }
771
Jeff Browne9bb9be2012-02-06 15:47:55 -0800772 setInjectionResultLocked(entry, injectionResult);
773 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
774 return true;
775 }
776
777 addMonitoringTargetsLocked(inputTargets);
778
Jeff Brownb88102f2010-09-08 11:49:43 -0700779 // Dispatch the key.
Jeff Browne9bb9be2012-02-06 15:47:55 -0800780 dispatchEventLocked(currentTime, entry, inputTargets);
Jeff Brownb88102f2010-09-08 11:49:43 -0700781 return true;
782}
783
784void InputDispatcher::logOutboundKeyDetailsLocked(const char* prefix, const KeyEntry* entry) {
785#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +0000786 ALOGD("%seventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, "
Jeff Brownb88102f2010-09-08 11:49:43 -0700787 "action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, "
Jeff Browne46a0a42010-11-02 17:58:22 -0700788 "repeatCount=%d, downTime=%lld",
Jeff Brownb88102f2010-09-08 11:49:43 -0700789 prefix,
790 entry->eventTime, entry->deviceId, entry->source, entry->policyFlags,
791 entry->action, entry->flags, entry->keyCode, entry->scanCode, entry->metaState,
Jeff Browne46a0a42010-11-02 17:58:22 -0700792 entry->repeatCount, entry->downTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700793#endif
794}
795
796bool InputDispatcher::dispatchMotionLocked(
Jeff Browne20c9e02010-10-11 14:20:19 -0700797 nsecs_t currentTime, MotionEntry* entry, DropReason* dropReason, nsecs_t* nextWakeupTime) {
Jeff Browne46a0a42010-11-02 17:58:22 -0700798 // Preprocessing.
799 if (! entry->dispatchInProgress) {
800 entry->dispatchInProgress = true;
Jeff Browne46a0a42010-11-02 17:58:22 -0700801
802 logOutboundMotionDetailsLocked("dispatchMotion - ", entry);
803 }
804
Jeff Brown54a18252010-09-16 14:07:33 -0700805 // Clean up if dropping the event.
Jeff Browne20c9e02010-10-11 14:20:19 -0700806 if (*dropReason != DROP_REASON_NOT_DROPPED) {
Jeff Brown3122e442010-10-11 23:32:49 -0700807 setInjectionResultLocked(entry, *dropReason == DROP_REASON_POLICY
808 ? INPUT_EVENT_INJECTION_SUCCEEDED : INPUT_EVENT_INJECTION_FAILED);
Jeff Brown54a18252010-09-16 14:07:33 -0700809 return true;
810 }
811
Jeff Brownb88102f2010-09-08 11:49:43 -0700812 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
813
814 // Identify targets.
Jeff Browne9bb9be2012-02-06 15:47:55 -0800815 Vector<InputTarget> inputTargets;
816
Jeff Browncc0c1592011-02-19 05:07:28 -0800817 bool conflictingPointerActions = false;
Jeff Browne9bb9be2012-02-06 15:47:55 -0800818 int32_t injectionResult;
819 if (isPointerEvent) {
820 // Pointer event. (eg. touchscreen)
821 injectionResult = findTouchedWindowTargetsLocked(currentTime,
822 entry, inputTargets, nextWakeupTime, &conflictingPointerActions);
823 } else {
824 // Non touch event. (eg. trackball)
825 injectionResult = findFocusedWindowTargetsLocked(currentTime,
826 entry, inputTargets, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700827 }
Jeff Browne9bb9be2012-02-06 15:47:55 -0800828 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
829 return false;
830 }
831
832 setInjectionResultLocked(entry, injectionResult);
833 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
834 return true;
835 }
836
Jeff Brown83d616a2012-09-09 20:33:43 -0700837 // TODO: support sending secondary display events to input monitors
838 if (isMainDisplay(entry->displayId)) {
839 addMonitoringTargetsLocked(inputTargets);
840 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700841
842 // Dispatch the motion.
Jeff Browncc0c1592011-02-19 05:07:28 -0800843 if (conflictingPointerActions) {
Jeff Brownda3d5a92011-03-29 15:11:34 -0700844 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
845 "conflicting pointer actions");
846 synthesizeCancelationEventsForAllConnectionsLocked(options);
Jeff Browncc0c1592011-02-19 05:07:28 -0800847 }
Jeff Browne9bb9be2012-02-06 15:47:55 -0800848 dispatchEventLocked(currentTime, entry, inputTargets);
Jeff Brownb88102f2010-09-08 11:49:43 -0700849 return true;
850}
851
852
853void InputDispatcher::logOutboundMotionDetailsLocked(const char* prefix, const MotionEntry* entry) {
854#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +0000855 ALOGD("%seventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, "
Jeff Brown85a31762010-09-01 17:01:00 -0700856 "action=0x%x, flags=0x%x, "
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700857 "metaState=0x%x, buttonState=0x%x, "
858 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%lld",
Jeff Brownb88102f2010-09-08 11:49:43 -0700859 prefix,
Jeff Brown85a31762010-09-01 17:01:00 -0700860 entry->eventTime, entry->deviceId, entry->source, entry->policyFlags,
861 entry->action, entry->flags,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700862 entry->metaState, entry->buttonState,
863 entry->edgeFlags, entry->xPrecision, entry->yPrecision,
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700864 entry->downTime);
865
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700866 for (uint32_t i = 0; i < entry->pointerCount; i++) {
Steve Block5baa3a62011-12-20 16:23:08 +0000867 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700868 "x=%f, y=%f, pressure=%f, size=%f, "
Jeff Brown85a31762010-09-01 17:01:00 -0700869 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
Jeff Brown8d608662010-08-30 03:02:23 -0700870 "orientation=%f",
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700871 i, entry->pointerProperties[i].id,
872 entry->pointerProperties[i].toolType,
Jeff Brown3241b6b2012-02-03 15:08:02 -0800873 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
874 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
875 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
876 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
877 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
878 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
879 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
880 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
881 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700882 }
883#endif
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700884}
885
Jeff Browne9bb9be2012-02-06 15:47:55 -0800886void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
887 EventEntry* eventEntry, const Vector<InputTarget>& inputTargets) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700888#if DEBUG_DISPATCH_CYCLE
Jeff Brown3241b6b2012-02-03 15:08:02 -0800889 ALOGD("dispatchEventToCurrentInputTargets");
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700890#endif
891
Steve Blockec193de2012-01-09 18:35:44 +0000892 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
Jeff Brown9c3cda02010-06-15 01:31:58 -0700893
Jeff Browne2fe69e2010-10-18 13:21:23 -0700894 pokeUserActivityLocked(eventEntry);
895
Jeff Browne9bb9be2012-02-06 15:47:55 -0800896 for (size_t i = 0; i < inputTargets.size(); i++) {
897 const InputTarget& inputTarget = inputTargets.itemAt(i);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700898
Jeff Brown519e0242010-09-15 15:18:56 -0700899 ssize_t connectionIndex = getConnectionIndexLocked(inputTarget.inputChannel);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700900 if (connectionIndex >= 0) {
Jeff Browncbee6d62012-02-03 20:11:27 -0800901 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
Jeff Brown3241b6b2012-02-03 15:08:02 -0800902 prepareDispatchCycleLocked(currentTime, connection, eventEntry, &inputTarget);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700903 } else {
Jeff Brownb6997262010-10-08 22:31:17 -0700904#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +0000905 ALOGD("Dropping event delivery to target with channel '%s' because it "
Jeff Brownb6997262010-10-08 22:31:17 -0700906 "is no longer registered with the input dispatcher.",
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700907 inputTarget.inputChannel->getName().string());
Jeff Brownb6997262010-10-08 22:31:17 -0700908#endif
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700909 }
910 }
911}
912
Jeff Brownb88102f2010-09-08 11:49:43 -0700913int32_t InputDispatcher::handleTargetsNotReadyLocked(nsecs_t currentTime,
Jeff Brown9302c872011-07-13 22:51:29 -0700914 const EventEntry* entry,
915 const sp<InputApplicationHandle>& applicationHandle,
916 const sp<InputWindowHandle>& windowHandle,
Jeff Brown265f1cc2012-06-11 18:01:06 -0700917 nsecs_t* nextWakeupTime, const char* reason) {
Jeff Brown9302c872011-07-13 22:51:29 -0700918 if (applicationHandle == NULL && windowHandle == NULL) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700919 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY) {
920#if DEBUG_FOCUS
Jeff Brown265f1cc2012-06-11 18:01:06 -0700921 ALOGD("Waiting for system to become ready for input. Reason: %s", reason);
Jeff Brownb88102f2010-09-08 11:49:43 -0700922#endif
923 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY;
924 mInputTargetWaitStartTime = currentTime;
925 mInputTargetWaitTimeoutTime = LONG_LONG_MAX;
926 mInputTargetWaitTimeoutExpired = false;
Jeff Brown9302c872011-07-13 22:51:29 -0700927 mInputTargetWaitApplicationHandle.clear();
Jeff Brownb88102f2010-09-08 11:49:43 -0700928 }
929 } else {
930 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
931#if DEBUG_FOCUS
Jeff Brown265f1cc2012-06-11 18:01:06 -0700932 ALOGD("Waiting for application to become ready for input: %s. Reason: %s",
933 getApplicationWindowLabelLocked(applicationHandle, windowHandle).string(),
934 reason);
Jeff Brownb88102f2010-09-08 11:49:43 -0700935#endif
Jeff Browncc4f7db2011-08-30 20:34:48 -0700936 nsecs_t timeout;
937 if (windowHandle != NULL) {
938 timeout = windowHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
939 } else if (applicationHandle != NULL) {
940 timeout = applicationHandle->getDispatchingTimeout(
941 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
942 } else {
943 timeout = DEFAULT_INPUT_DISPATCHING_TIMEOUT;
944 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700945
946 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY;
947 mInputTargetWaitStartTime = currentTime;
948 mInputTargetWaitTimeoutTime = currentTime + timeout;
949 mInputTargetWaitTimeoutExpired = false;
Jeff Brown9302c872011-07-13 22:51:29 -0700950 mInputTargetWaitApplicationHandle.clear();
Jeff Brown928e0542011-01-10 11:17:36 -0800951
Jeff Brown9302c872011-07-13 22:51:29 -0700952 if (windowHandle != NULL) {
953 mInputTargetWaitApplicationHandle = windowHandle->inputApplicationHandle;
Jeff Brown928e0542011-01-10 11:17:36 -0800954 }
Jeff Brown9302c872011-07-13 22:51:29 -0700955 if (mInputTargetWaitApplicationHandle == NULL && applicationHandle != NULL) {
956 mInputTargetWaitApplicationHandle = applicationHandle;
Jeff Brown928e0542011-01-10 11:17:36 -0800957 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700958 }
959 }
960
961 if (mInputTargetWaitTimeoutExpired) {
962 return INPUT_EVENT_INJECTION_TIMED_OUT;
963 }
964
965 if (currentTime >= mInputTargetWaitTimeoutTime) {
Jeff Brown9302c872011-07-13 22:51:29 -0700966 onANRLocked(currentTime, applicationHandle, windowHandle,
Jeff Brown265f1cc2012-06-11 18:01:06 -0700967 entry->eventTime, mInputTargetWaitStartTime, reason);
Jeff Brownb88102f2010-09-08 11:49:43 -0700968
969 // Force poll loop to wake up immediately on next iteration once we get the
970 // ANR response back from the policy.
971 *nextWakeupTime = LONG_LONG_MIN;
972 return INPUT_EVENT_INJECTION_PENDING;
973 } else {
974 // Force poll loop to wake up when timeout is due.
975 if (mInputTargetWaitTimeoutTime < *nextWakeupTime) {
976 *nextWakeupTime = mInputTargetWaitTimeoutTime;
977 }
978 return INPUT_EVENT_INJECTION_PENDING;
979 }
980}
981
Jeff Brown519e0242010-09-15 15:18:56 -0700982void InputDispatcher::resumeAfterTargetsNotReadyTimeoutLocked(nsecs_t newTimeout,
983 const sp<InputChannel>& inputChannel) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700984 if (newTimeout > 0) {
985 // Extend the timeout.
986 mInputTargetWaitTimeoutTime = now() + newTimeout;
987 } else {
988 // Give up.
989 mInputTargetWaitTimeoutExpired = true;
Jeff Brown519e0242010-09-15 15:18:56 -0700990
991 // Input state will not be realistic. Mark it out of sync.
Jeff Browndc3e0052010-09-16 11:02:16 -0700992 if (inputChannel.get()) {
993 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
994 if (connectionIndex >= 0) {
Jeff Browncbee6d62012-02-03 20:11:27 -0800995 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
Jeff Brownf44e3942012-04-20 11:33:27 -0700996 sp<InputWindowHandle> windowHandle = connection->inputWindowHandle;
997
998 if (windowHandle != NULL) {
999 mTouchState.removeWindow(windowHandle);
1000 }
1001
Jeff Brown00045a72010-12-09 18:10:30 -08001002 if (connection->status == Connection::STATUS_NORMAL) {
Jeff Brownda3d5a92011-03-29 15:11:34 -07001003 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
Jeff Brown00045a72010-12-09 18:10:30 -08001004 "application not responding");
Jeff Brownda3d5a92011-03-29 15:11:34 -07001005 synthesizeCancelationEventsForConnectionLocked(connection, options);
Jeff Brown00045a72010-12-09 18:10:30 -08001006 }
Jeff Browndc3e0052010-09-16 11:02:16 -07001007 }
Jeff Brown519e0242010-09-15 15:18:56 -07001008 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001009 }
1010}
1011
Jeff Brown519e0242010-09-15 15:18:56 -07001012nsecs_t InputDispatcher::getTimeSpentWaitingForApplicationLocked(
Jeff Brownb88102f2010-09-08 11:49:43 -07001013 nsecs_t currentTime) {
1014 if (mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
1015 return currentTime - mInputTargetWaitStartTime;
1016 }
1017 return 0;
1018}
1019
1020void InputDispatcher::resetANRTimeoutsLocked() {
1021#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001022 ALOGD("Resetting ANR timeouts.");
Jeff Brownb88102f2010-09-08 11:49:43 -07001023#endif
1024
Jeff Brownb88102f2010-09-08 11:49:43 -07001025 // Reset input target wait timeout.
1026 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_NONE;
Jeff Brown5ea29ab2011-07-27 11:50:51 -07001027 mInputTargetWaitApplicationHandle.clear();
Jeff Brownb88102f2010-09-08 11:49:43 -07001028}
1029
Jeff Brown01ce2e92010-09-26 22:20:12 -07001030int32_t InputDispatcher::findFocusedWindowTargetsLocked(nsecs_t currentTime,
Jeff Browne9bb9be2012-02-06 15:47:55 -08001031 const EventEntry* entry, Vector<InputTarget>& inputTargets, nsecs_t* nextWakeupTime) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001032 int32_t injectionResult;
1033
1034 // If there is no currently focused window and no focused application
1035 // then drop the event.
Jeff Brown9302c872011-07-13 22:51:29 -07001036 if (mFocusedWindowHandle == NULL) {
1037 if (mFocusedApplicationHandle != NULL) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001038 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brown265f1cc2012-06-11 18:01:06 -07001039 mFocusedApplicationHandle, NULL, nextWakeupTime,
1040 "Waiting because no window has focus but there is a "
1041 "focused application that may eventually add a window "
1042 "when it finishes starting up.");
Jeff Brownb88102f2010-09-08 11:49:43 -07001043 goto Unresponsive;
1044 }
1045
Steve Block6215d3f2012-01-04 20:05:49 +00001046 ALOGI("Dropping event because there is no focused window or focused application.");
Jeff Brownb88102f2010-09-08 11:49:43 -07001047 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1048 goto Failed;
1049 }
1050
1051 // Check permissions.
Jeff Brown9302c872011-07-13 22:51:29 -07001052 if (! checkInjectionPermission(mFocusedWindowHandle, entry->injectionState)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001053 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1054 goto Failed;
1055 }
1056
1057 // If the currently focused window is paused then keep waiting.
Jeff Browncc4f7db2011-08-30 20:34:48 -07001058 if (mFocusedWindowHandle->getInfo()->paused) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001059 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brown265f1cc2012-06-11 18:01:06 -07001060 mFocusedApplicationHandle, mFocusedWindowHandle, nextWakeupTime,
1061 "Waiting because the focused window is paused.");
Jeff Brownb88102f2010-09-08 11:49:43 -07001062 goto Unresponsive;
1063 }
1064
Jeff Brown519e0242010-09-15 15:18:56 -07001065 // If the currently focused window is still working on previous events then keep waiting.
Jeff Brown0952c302012-02-13 13:48:59 -08001066 if (!isWindowReadyForMoreInputLocked(currentTime, mFocusedWindowHandle, entry)) {
Jeff Brown519e0242010-09-15 15:18:56 -07001067 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brown265f1cc2012-06-11 18:01:06 -07001068 mFocusedApplicationHandle, mFocusedWindowHandle, nextWakeupTime,
1069 "Waiting because the focused window has not finished "
1070 "processing the input events that were previously delivered to it.");
Jeff Brown519e0242010-09-15 15:18:56 -07001071 goto Unresponsive;
1072 }
1073
Jeff Brownb88102f2010-09-08 11:49:43 -07001074 // Success! Output targets.
1075 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
Jeff Brown9302c872011-07-13 22:51:29 -07001076 addWindowTargetLocked(mFocusedWindowHandle,
Jeff Browne9bb9be2012-02-06 15:47:55 -08001077 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS, BitSet32(0),
1078 inputTargets);
Jeff Brownb88102f2010-09-08 11:49:43 -07001079
1080 // Done.
1081Failed:
1082Unresponsive:
Jeff Brown519e0242010-09-15 15:18:56 -07001083 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
1084 updateDispatchStatisticsLocked(currentTime, entry,
1085 injectionResult, timeSpentWaitingForApplication);
Jeff Brownb88102f2010-09-08 11:49:43 -07001086#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001087 ALOGD("findFocusedWindow finished: injectionResult=%d, "
Jeff Brown22aa5122012-06-17 12:01:06 -07001088 "timeSpentWaitingForApplication=%0.1fms",
Jeff Brown519e0242010-09-15 15:18:56 -07001089 injectionResult, timeSpentWaitingForApplication / 1000000.0);
Jeff Brownb88102f2010-09-08 11:49:43 -07001090#endif
1091 return injectionResult;
1092}
1093
Jeff Brown01ce2e92010-09-26 22:20:12 -07001094int32_t InputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime,
Jeff Browne9bb9be2012-02-06 15:47:55 -08001095 const MotionEntry* entry, Vector<InputTarget>& inputTargets, nsecs_t* nextWakeupTime,
1096 bool* outConflictingPointerActions) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001097 enum InjectionPermission {
1098 INJECTION_PERMISSION_UNKNOWN,
1099 INJECTION_PERMISSION_GRANTED,
1100 INJECTION_PERMISSION_DENIED
1101 };
1102
Jeff Brownb88102f2010-09-08 11:49:43 -07001103 nsecs_t startTime = now();
1104
1105 // For security reasons, we defer updating the touch state until we are sure that
1106 // event injection will be allowed.
1107 //
1108 // FIXME In the original code, screenWasOff could never be set to true.
1109 // The reason is that the POLICY_FLAG_WOKE_HERE
1110 // and POLICY_FLAG_BRIGHT_HERE flags were set only when preprocessing raw
1111 // EV_KEY, EV_REL and EV_ABS events. As it happens, the touch event was
1112 // actually enqueued using the policyFlags that appeared in the final EV_SYN
1113 // events upon which no preprocessing took place. So policyFlags was always 0.
1114 // In the new native input dispatcher we're a bit more careful about event
1115 // preprocessing so the touches we receive can actually have non-zero policyFlags.
1116 // Unfortunately we obtain undesirable behavior.
1117 //
1118 // Here's what happens:
1119 //
1120 // When the device dims in anticipation of going to sleep, touches
1121 // in windows which have FLAG_TOUCHABLE_WHEN_WAKING cause
1122 // the device to brighten and reset the user activity timer.
1123 // Touches on other windows (such as the launcher window)
1124 // are dropped. Then after a moment, the device goes to sleep. Oops.
1125 //
1126 // Also notice how screenWasOff was being initialized using POLICY_FLAG_BRIGHT_HERE
1127 // instead of POLICY_FLAG_WOKE_HERE...
1128 //
1129 bool screenWasOff = false; // original policy: policyFlags & POLICY_FLAG_BRIGHT_HERE;
1130
Jeff Brown83d616a2012-09-09 20:33:43 -07001131 int32_t displayId = entry->displayId;
Jeff Brownb88102f2010-09-08 11:49:43 -07001132 int32_t action = entry->action;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001133 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Jeff Brownb88102f2010-09-08 11:49:43 -07001134
1135 // Update the touch state as needed based on the properties of the touch event.
Jeff Brown01ce2e92010-09-26 22:20:12 -07001136 int32_t injectionResult = INPUT_EVENT_INJECTION_PENDING;
1137 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
Jeff Brown9302c872011-07-13 22:51:29 -07001138 sp<InputWindowHandle> newHoverWindowHandle;
Jeff Browncc0c1592011-02-19 05:07:28 -08001139
1140 bool isSplit = mTouchState.split;
Jeff Brown83d616a2012-09-09 20:33:43 -07001141 bool switchedDevice = mTouchState.deviceId >= 0 && mTouchState.displayId >= 0
Jeff Brown2717eff2011-06-30 23:53:07 -07001142 && (mTouchState.deviceId != entry->deviceId
Jeff Brown83d616a2012-09-09 20:33:43 -07001143 || mTouchState.source != entry->source
1144 || mTouchState.displayId != displayId);
Jeff Browna032cc02011-03-07 16:56:21 -08001145 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE
1146 || maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER
1147 || maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1148 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN
1149 || maskedAction == AMOTION_EVENT_ACTION_SCROLL
1150 || isHoverAction);
Jeff Brown81346812011-06-28 20:08:48 -07001151 bool wrongDevice = false;
Jeff Browna032cc02011-03-07 16:56:21 -08001152 if (newGesture) {
Jeff Browncc0c1592011-02-19 05:07:28 -08001153 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Jeff Brown81346812011-06-28 20:08:48 -07001154 if (switchedDevice && mTouchState.down && !down) {
1155#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001156 ALOGD("Dropping event because a pointer for a different device is already down.");
Jeff Brown81346812011-06-28 20:08:48 -07001157#endif
Jeff Browncc0c1592011-02-19 05:07:28 -08001158 mTempTouchState.copyFrom(mTouchState);
Jeff Brown81346812011-06-28 20:08:48 -07001159 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1160 switchedDevice = false;
1161 wrongDevice = true;
1162 goto Failed;
Jeff Browncc0c1592011-02-19 05:07:28 -08001163 }
Jeff Brown81346812011-06-28 20:08:48 -07001164 mTempTouchState.reset();
1165 mTempTouchState.down = down;
1166 mTempTouchState.deviceId = entry->deviceId;
1167 mTempTouchState.source = entry->source;
Jeff Brown83d616a2012-09-09 20:33:43 -07001168 mTempTouchState.displayId = displayId;
Jeff Brown81346812011-06-28 20:08:48 -07001169 isSplit = false;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001170 } else {
1171 mTempTouchState.copyFrom(mTouchState);
Jeff Browncc0c1592011-02-19 05:07:28 -08001172 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001173
Jeff Browna032cc02011-03-07 16:56:21 -08001174 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
Jeff Brown33bbfd22011-02-24 20:55:35 -08001175 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
Jeff Brownb88102f2010-09-08 11:49:43 -07001176
Jeff Brown01ce2e92010-09-26 22:20:12 -07001177 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Jeff Brown3241b6b2012-02-03 15:08:02 -08001178 int32_t x = int32_t(entry->pointerCoords[pointerIndex].
Jeff Brownebbd5d12011-02-17 13:01:34 -08001179 getAxisValue(AMOTION_EVENT_AXIS_X));
Jeff Brown3241b6b2012-02-03 15:08:02 -08001180 int32_t y = int32_t(entry->pointerCoords[pointerIndex].
Jeff Brownebbd5d12011-02-17 13:01:34 -08001181 getAxisValue(AMOTION_EVENT_AXIS_Y));
Jeff Brown9302c872011-07-13 22:51:29 -07001182 sp<InputWindowHandle> newTouchedWindowHandle;
1183 sp<InputWindowHandle> topErrorWindowHandle;
Jeff Browna032cc02011-03-07 16:56:21 -08001184 bool isTouchModal = false;
Jeff Brownb88102f2010-09-08 11:49:43 -07001185
1186 // Traverse windows from front to back to find touched window and outside targets.
Jeff Brown9302c872011-07-13 22:51:29 -07001187 size_t numWindows = mWindowHandles.size();
Jeff Brownb88102f2010-09-08 11:49:43 -07001188 for (size_t i = 0; i < numWindows; i++) {
Jeff Brown9302c872011-07-13 22:51:29 -07001189 sp<InputWindowHandle> windowHandle = mWindowHandles.itemAt(i);
Jeff Browncc4f7db2011-08-30 20:34:48 -07001190 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Jeff Brown83d616a2012-09-09 20:33:43 -07001191 if (windowInfo->displayId != displayId) {
1192 continue; // wrong display
1193 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001194
Jeff Brown83d616a2012-09-09 20:33:43 -07001195 int32_t flags = windowInfo->layoutParamsFlags;
Jeff Browncc4f7db2011-08-30 20:34:48 -07001196 if (flags & InputWindowInfo::FLAG_SYSTEM_ERROR) {
Jeff Brown9302c872011-07-13 22:51:29 -07001197 if (topErrorWindowHandle == NULL) {
1198 topErrorWindowHandle = windowHandle;
Jeff Brownb88102f2010-09-08 11:49:43 -07001199 }
1200 }
1201
Jeff Browncc4f7db2011-08-30 20:34:48 -07001202 if (windowInfo->visible) {
1203 if (! (flags & InputWindowInfo::FLAG_NOT_TOUCHABLE)) {
1204 isTouchModal = (flags & (InputWindowInfo::FLAG_NOT_FOCUSABLE
1205 | InputWindowInfo::FLAG_NOT_TOUCH_MODAL)) == 0;
1206 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
Jeff Brown9302c872011-07-13 22:51:29 -07001207 if (! screenWasOff
Jeff Browncc4f7db2011-08-30 20:34:48 -07001208 || (flags & InputWindowInfo::FLAG_TOUCHABLE_WHEN_WAKING)) {
Jeff Brown9302c872011-07-13 22:51:29 -07001209 newTouchedWindowHandle = windowHandle;
Jeff Brownb88102f2010-09-08 11:49:43 -07001210 }
1211 break; // found touched window, exit window loop
1212 }
1213 }
1214
Jeff Brown01ce2e92010-09-26 22:20:12 -07001215 if (maskedAction == AMOTION_EVENT_ACTION_DOWN
Jeff Browncc4f7db2011-08-30 20:34:48 -07001216 && (flags & InputWindowInfo::FLAG_WATCH_OUTSIDE_TOUCH)) {
Jeff Browna032cc02011-03-07 16:56:21 -08001217 int32_t outsideTargetFlags = InputTarget::FLAG_DISPATCH_AS_OUTSIDE;
Jeff Brown9302c872011-07-13 22:51:29 -07001218 if (isWindowObscuredAtPointLocked(windowHandle, x, y)) {
Jeff Brown19dfc832010-10-05 12:26:23 -07001219 outsideTargetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1220 }
1221
Jeff Brown9302c872011-07-13 22:51:29 -07001222 mTempTouchState.addOrUpdateWindow(
1223 windowHandle, outsideTargetFlags, BitSet32(0));
Jeff Brownb88102f2010-09-08 11:49:43 -07001224 }
1225 }
1226 }
1227
1228 // If there is an error window but it is not taking focus (typically because
1229 // it is invisible) then wait for it. Any other focused window may in
1230 // fact be in ANR state.
Jeff Brown9302c872011-07-13 22:51:29 -07001231 if (topErrorWindowHandle != NULL && newTouchedWindowHandle != topErrorWindowHandle) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001232 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brown265f1cc2012-06-11 18:01:06 -07001233 NULL, NULL, nextWakeupTime,
1234 "Waiting because a system error window is about to be displayed.");
Jeff Brownb88102f2010-09-08 11:49:43 -07001235 injectionPermission = INJECTION_PERMISSION_UNKNOWN;
1236 goto Unresponsive;
1237 }
1238
Jeff Brown01ce2e92010-09-26 22:20:12 -07001239 // Figure out whether splitting will be allowed for this window.
Jeff Browncc4f7db2011-08-30 20:34:48 -07001240 if (newTouchedWindowHandle != NULL
1241 && newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001242 // New window supports splitting.
1243 isSplit = true;
1244 } else if (isSplit) {
1245 // New window does not support splitting but we have already split events.
Jeff Brown8249fc62012-05-24 18:57:32 -07001246 // Ignore the new window.
1247 newTouchedWindowHandle = NULL;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001248 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001249
Jeff Brown8249fc62012-05-24 18:57:32 -07001250 // Handle the case where we did not find a window.
Jeff Brown9302c872011-07-13 22:51:29 -07001251 if (newTouchedWindowHandle == NULL) {
Jeff Brown8249fc62012-05-24 18:57:32 -07001252 // Try to assign the pointer to the first foreground window we find, if there is one.
1253 newTouchedWindowHandle = mTempTouchState.getFirstForegroundWindowHandle();
1254 if (newTouchedWindowHandle == NULL) {
1255 // There is no touched window. If this is an initial down event
1256 // then wait for a window to appear that will handle the touch. This is
1257 // to ensure that we report an ANR in the case where an application has started
1258 // but not yet put up a window and the user is starting to get impatient.
1259 if (maskedAction == AMOTION_EVENT_ACTION_DOWN
1260 && mFocusedApplicationHandle != NULL) {
Jeff Brown8249fc62012-05-24 18:57:32 -07001261 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brown265f1cc2012-06-11 18:01:06 -07001262 mFocusedApplicationHandle, NULL, nextWakeupTime,
1263 "Waiting because there is no touchable window that can "
1264 "handle the event but there is focused application that may "
1265 "eventually add a new window when it finishes starting up.");
Jeff Brown8249fc62012-05-24 18:57:32 -07001266 goto Unresponsive;
1267 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001268
Jeff Brown8249fc62012-05-24 18:57:32 -07001269 ALOGI("Dropping event because there is no touched window.");
1270 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1271 goto Failed;
1272 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001273 }
1274
Jeff Brown19dfc832010-10-05 12:26:23 -07001275 // Set target flags.
Jeff Browna032cc02011-03-07 16:56:21 -08001276 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
Jeff Brown19dfc832010-10-05 12:26:23 -07001277 if (isSplit) {
1278 targetFlags |= InputTarget::FLAG_SPLIT;
1279 }
Jeff Brown9302c872011-07-13 22:51:29 -07001280 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
Jeff Brown19dfc832010-10-05 12:26:23 -07001281 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1282 }
1283
Jeff Browna032cc02011-03-07 16:56:21 -08001284 // Update hover state.
1285 if (isHoverAction) {
Jeff Brown9302c872011-07-13 22:51:29 -07001286 newHoverWindowHandle = newTouchedWindowHandle;
Jeff Browna032cc02011-03-07 16:56:21 -08001287 } else if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
Jeff Brown9302c872011-07-13 22:51:29 -07001288 newHoverWindowHandle = mLastHoverWindowHandle;
Jeff Browna032cc02011-03-07 16:56:21 -08001289 }
1290
Jeff Brown01ce2e92010-09-26 22:20:12 -07001291 // Update the temporary touch state.
1292 BitSet32 pointerIds;
1293 if (isSplit) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07001294 uint32_t pointerId = entry->pointerProperties[pointerIndex].id;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001295 pointerIds.markBit(pointerId);
Jeff Brownb88102f2010-09-08 11:49:43 -07001296 }
Jeff Brown9302c872011-07-13 22:51:29 -07001297 mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Jeff Brownb88102f2010-09-08 11:49:43 -07001298 } else {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001299 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
Jeff Brownb88102f2010-09-08 11:49:43 -07001300
1301 // If the pointer is not currently down, then ignore the event.
Jeff Brown01ce2e92010-09-26 22:20:12 -07001302 if (! mTempTouchState.down) {
Jeff Browna2cc28d2011-03-25 11:58:46 -07001303#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001304 ALOGD("Dropping event because the pointer is not down or we previously "
Jeff Brown76860e32010-10-25 17:37:46 -07001305 "dropped the pointer down event.");
1306#endif
Jeff Brownb88102f2010-09-08 11:49:43 -07001307 injectionResult = INPUT_EVENT_INJECTION_FAILED;
Jeff Brownb88102f2010-09-08 11:49:43 -07001308 goto Failed;
1309 }
Jeff Brown98db5fa2011-06-08 15:37:10 -07001310
1311 // Check whether touches should slip outside of the current foreground window.
1312 if (maskedAction == AMOTION_EVENT_ACTION_MOVE
1313 && entry->pointerCount == 1
1314 && mTempTouchState.isSlippery()) {
Jeff Brown3241b6b2012-02-03 15:08:02 -08001315 int32_t x = int32_t(entry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
1316 int32_t y = int32_t(entry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Jeff Brown98db5fa2011-06-08 15:37:10 -07001317
Jeff Brown9302c872011-07-13 22:51:29 -07001318 sp<InputWindowHandle> oldTouchedWindowHandle =
1319 mTempTouchState.getFirstForegroundWindowHandle();
Jeff Brown83d616a2012-09-09 20:33:43 -07001320 sp<InputWindowHandle> newTouchedWindowHandle =
1321 findTouchedWindowAtLocked(displayId, x, y);
Jeff Brown9302c872011-07-13 22:51:29 -07001322 if (oldTouchedWindowHandle != newTouchedWindowHandle
1323 && newTouchedWindowHandle != NULL) {
Jeff Brown98db5fa2011-06-08 15:37:10 -07001324#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001325 ALOGD("Touch is slipping out of window %s into window %s.",
Jeff Browncc4f7db2011-08-30 20:34:48 -07001326 oldTouchedWindowHandle->getName().string(),
1327 newTouchedWindowHandle->getName().string());
Jeff Brown98db5fa2011-06-08 15:37:10 -07001328#endif
1329 // Make a slippery exit from the old window.
Jeff Brown9302c872011-07-13 22:51:29 -07001330 mTempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
Jeff Brown98db5fa2011-06-08 15:37:10 -07001331 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT, BitSet32(0));
1332
1333 // Make a slippery entrance into the new window.
Jeff Browncc4f7db2011-08-30 20:34:48 -07001334 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Jeff Brown98db5fa2011-06-08 15:37:10 -07001335 isSplit = true;
1336 }
1337
1338 int32_t targetFlags = InputTarget::FLAG_FOREGROUND
1339 | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
1340 if (isSplit) {
1341 targetFlags |= InputTarget::FLAG_SPLIT;
1342 }
Jeff Brown9302c872011-07-13 22:51:29 -07001343 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
Jeff Brown98db5fa2011-06-08 15:37:10 -07001344 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1345 }
1346
1347 BitSet32 pointerIds;
1348 if (isSplit) {
1349 pointerIds.markBit(entry->pointerProperties[0].id);
1350 }
Jeff Brown9302c872011-07-13 22:51:29 -07001351 mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Jeff Brown98db5fa2011-06-08 15:37:10 -07001352 }
1353 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001354 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001355
Jeff Brown9302c872011-07-13 22:51:29 -07001356 if (newHoverWindowHandle != mLastHoverWindowHandle) {
Jeff Browna032cc02011-03-07 16:56:21 -08001357 // Let the previous window know that the hover sequence is over.
Jeff Brown9302c872011-07-13 22:51:29 -07001358 if (mLastHoverWindowHandle != NULL) {
Jeff Browna032cc02011-03-07 16:56:21 -08001359#if DEBUG_HOVER
Steve Block5baa3a62011-12-20 16:23:08 +00001360 ALOGD("Sending hover exit event to window %s.",
Jeff Browncc4f7db2011-08-30 20:34:48 -07001361 mLastHoverWindowHandle->getName().string());
Jeff Browna032cc02011-03-07 16:56:21 -08001362#endif
Jeff Brown9302c872011-07-13 22:51:29 -07001363 mTempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
Jeff Browna032cc02011-03-07 16:56:21 -08001364 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
1365 }
1366
1367 // Let the new window know that the hover sequence is starting.
Jeff Brown9302c872011-07-13 22:51:29 -07001368 if (newHoverWindowHandle != NULL) {
Jeff Browna032cc02011-03-07 16:56:21 -08001369#if DEBUG_HOVER
Steve Block5baa3a62011-12-20 16:23:08 +00001370 ALOGD("Sending hover enter event to window %s.",
Jeff Browncc4f7db2011-08-30 20:34:48 -07001371 newHoverWindowHandle->getName().string());
Jeff Browna032cc02011-03-07 16:56:21 -08001372#endif
Jeff Brown9302c872011-07-13 22:51:29 -07001373 mTempTouchState.addOrUpdateWindow(newHoverWindowHandle,
Jeff Browna032cc02011-03-07 16:56:21 -08001374 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER, BitSet32(0));
1375 }
1376 }
1377
Jeff Brown01ce2e92010-09-26 22:20:12 -07001378 // Check permission to inject into all touched foreground windows and ensure there
1379 // is at least one touched foreground window.
1380 {
1381 bool haveForegroundWindow = false;
1382 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1383 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1384 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1385 haveForegroundWindow = true;
Jeff Brown9302c872011-07-13 22:51:29 -07001386 if (! checkInjectionPermission(touchedWindow.windowHandle,
1387 entry->injectionState)) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001388 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1389 injectionPermission = INJECTION_PERMISSION_DENIED;
1390 goto Failed;
1391 }
1392 }
1393 }
1394 if (! haveForegroundWindow) {
Jeff Browna2cc28d2011-03-25 11:58:46 -07001395#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001396 ALOGD("Dropping event because there is no touched foreground window to receive it.");
Jeff Brownb88102f2010-09-08 11:49:43 -07001397#endif
1398 injectionResult = INPUT_EVENT_INJECTION_FAILED;
Jeff Brownb88102f2010-09-08 11:49:43 -07001399 goto Failed;
1400 }
1401
Jeff Brown01ce2e92010-09-26 22:20:12 -07001402 // Permission granted to injection into all touched foreground windows.
1403 injectionPermission = INJECTION_PERMISSION_GRANTED;
1404 }
Jeff Brown519e0242010-09-15 15:18:56 -07001405
Kenny Root7a9db182011-06-02 15:16:05 -07001406 // Check whether windows listening for outside touches are owned by the same UID. If it is
1407 // set the policy flag that we will not reveal coordinate information to this window.
1408 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
Jeff Brown9302c872011-07-13 22:51:29 -07001409 sp<InputWindowHandle> foregroundWindowHandle =
1410 mTempTouchState.getFirstForegroundWindowHandle();
Jeff Browncc4f7db2011-08-30 20:34:48 -07001411 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Kenny Root7a9db182011-06-02 15:16:05 -07001412 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1413 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1414 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
Jeff Brown9302c872011-07-13 22:51:29 -07001415 sp<InputWindowHandle> inputWindowHandle = touchedWindow.windowHandle;
Jeff Browncc4f7db2011-08-30 20:34:48 -07001416 if (inputWindowHandle->getInfo()->ownerUid != foregroundWindowUid) {
Jeff Brown9302c872011-07-13 22:51:29 -07001417 mTempTouchState.addOrUpdateWindow(inputWindowHandle,
Kenny Root7a9db182011-06-02 15:16:05 -07001418 InputTarget::FLAG_ZERO_COORDS, BitSet32(0));
1419 }
1420 }
1421 }
1422 }
1423
Jeff Brown01ce2e92010-09-26 22:20:12 -07001424 // Ensure all touched foreground windows are ready for new input.
1425 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1426 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1427 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1428 // If the touched window is paused then keep waiting.
Jeff Browncc4f7db2011-08-30 20:34:48 -07001429 if (touchedWindow.windowHandle->getInfo()->paused) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001430 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brown265f1cc2012-06-11 18:01:06 -07001431 NULL, touchedWindow.windowHandle, nextWakeupTime,
1432 "Waiting because the touched window is paused.");
Jeff Brown01ce2e92010-09-26 22:20:12 -07001433 goto Unresponsive;
1434 }
1435
1436 // If the touched window is still working on previous events then keep waiting.
Jeff Brown0952c302012-02-13 13:48:59 -08001437 if (!isWindowReadyForMoreInputLocked(currentTime, touchedWindow.windowHandle, entry)) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001438 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brown265f1cc2012-06-11 18:01:06 -07001439 NULL, touchedWindow.windowHandle, nextWakeupTime,
1440 "Waiting because the touched window has not finished "
1441 "processing the input events that were previously delivered to it.");
Jeff Brown01ce2e92010-09-26 22:20:12 -07001442 goto Unresponsive;
1443 }
1444 }
1445 }
1446
1447 // If this is the first pointer going down and the touched window has a wallpaper
1448 // then also add the touched wallpaper windows so they are locked in for the duration
1449 // of the touch gesture.
Jeff Brown33bbfd22011-02-24 20:55:35 -08001450 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
1451 // engine only supports touch events. We would need to add a mechanism similar
1452 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
1453 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
Jeff Brown9302c872011-07-13 22:51:29 -07001454 sp<InputWindowHandle> foregroundWindowHandle =
1455 mTempTouchState.getFirstForegroundWindowHandle();
Jeff Browncc4f7db2011-08-30 20:34:48 -07001456 if (foregroundWindowHandle->getInfo()->hasWallpaper) {
Jeff Brown9302c872011-07-13 22:51:29 -07001457 for (size_t i = 0; i < mWindowHandles.size(); i++) {
1458 sp<InputWindowHandle> windowHandle = mWindowHandles.itemAt(i);
Jeff Brown83d616a2012-09-09 20:33:43 -07001459 const InputWindowInfo* info = windowHandle->getInfo();
1460 if (info->displayId == displayId
1461 && windowHandle->getInfo()->layoutParamsType
1462 == InputWindowInfo::TYPE_WALLPAPER) {
Jeff Brown9302c872011-07-13 22:51:29 -07001463 mTempTouchState.addOrUpdateWindow(windowHandle,
Jeff Browna032cc02011-03-07 16:56:21 -08001464 InputTarget::FLAG_WINDOW_IS_OBSCURED
1465 | InputTarget::FLAG_DISPATCH_AS_IS,
1466 BitSet32(0));
Jeff Brown01ce2e92010-09-26 22:20:12 -07001467 }
1468 }
1469 }
1470 }
1471
Jeff Brownb88102f2010-09-08 11:49:43 -07001472 // Success! Output targets.
1473 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
Jeff Brownb88102f2010-09-08 11:49:43 -07001474
Jeff Brown01ce2e92010-09-26 22:20:12 -07001475 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1476 const TouchedWindow& touchedWindow = mTempTouchState.windows.itemAt(i);
Jeff Brown9302c872011-07-13 22:51:29 -07001477 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Jeff Browne9bb9be2012-02-06 15:47:55 -08001478 touchedWindow.pointerIds, inputTargets);
Jeff Brownb88102f2010-09-08 11:49:43 -07001479 }
1480
Jeff Browna032cc02011-03-07 16:56:21 -08001481 // Drop the outside or hover touch windows since we will not care about them
1482 // in the next iteration.
1483 mTempTouchState.filterNonAsIsTouchWindows();
Jeff Brown01ce2e92010-09-26 22:20:12 -07001484
Jeff Brownb88102f2010-09-08 11:49:43 -07001485Failed:
1486 // Check injection permission once and for all.
1487 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001488 if (checkInjectionPermission(NULL, entry->injectionState)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001489 injectionPermission = INJECTION_PERMISSION_GRANTED;
1490 } else {
1491 injectionPermission = INJECTION_PERMISSION_DENIED;
1492 }
1493 }
1494
1495 // Update final pieces of touch state if the injector had permission.
1496 if (injectionPermission == INJECTION_PERMISSION_GRANTED) {
Jeff Brown95712852011-01-04 19:41:59 -08001497 if (!wrongDevice) {
Jeff Brown81346812011-06-28 20:08:48 -07001498 if (switchedDevice) {
1499#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001500 ALOGD("Conflicting pointer actions: Switched to a different device.");
Jeff Brown81346812011-06-28 20:08:48 -07001501#endif
1502 *outConflictingPointerActions = true;
1503 }
1504
1505 if (isHoverAction) {
1506 // Started hovering, therefore no longer down.
1507 if (mTouchState.down) {
1508#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001509 ALOGD("Conflicting pointer actions: Hover received while pointer was down.");
Jeff Brown81346812011-06-28 20:08:48 -07001510#endif
1511 *outConflictingPointerActions = true;
1512 }
1513 mTouchState.reset();
1514 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER
1515 || maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
1516 mTouchState.deviceId = entry->deviceId;
1517 mTouchState.source = entry->source;
Jeff Brown83d616a2012-09-09 20:33:43 -07001518 mTouchState.displayId = displayId;
Jeff Brown81346812011-06-28 20:08:48 -07001519 }
1520 } else if (maskedAction == AMOTION_EVENT_ACTION_UP
1521 || maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Jeff Brown95712852011-01-04 19:41:59 -08001522 // All pointers up or canceled.
Jeff Brown33bbfd22011-02-24 20:55:35 -08001523 mTouchState.reset();
Jeff Brown95712852011-01-04 19:41:59 -08001524 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1525 // First pointer went down.
1526 if (mTouchState.down) {
Jeff Brownb6997262010-10-08 22:31:17 -07001527#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001528 ALOGD("Conflicting pointer actions: Down received while already down.");
Jeff Brownb6997262010-10-08 22:31:17 -07001529#endif
Jeff Brown81346812011-06-28 20:08:48 -07001530 *outConflictingPointerActions = true;
Jeff Brown95712852011-01-04 19:41:59 -08001531 }
Jeff Brown33bbfd22011-02-24 20:55:35 -08001532 mTouchState.copyFrom(mTempTouchState);
Jeff Brown95712852011-01-04 19:41:59 -08001533 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
1534 // One pointer went up.
1535 if (isSplit) {
1536 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07001537 uint32_t pointerId = entry->pointerProperties[pointerIndex].id;
Jeff Brownb88102f2010-09-08 11:49:43 -07001538
Jeff Brown95712852011-01-04 19:41:59 -08001539 for (size_t i = 0; i < mTempTouchState.windows.size(); ) {
1540 TouchedWindow& touchedWindow = mTempTouchState.windows.editItemAt(i);
1541 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
1542 touchedWindow.pointerIds.clearBit(pointerId);
1543 if (touchedWindow.pointerIds.isEmpty()) {
1544 mTempTouchState.windows.removeAt(i);
1545 continue;
1546 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001547 }
Jeff Brown95712852011-01-04 19:41:59 -08001548 i += 1;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001549 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001550 }
Jeff Brown33bbfd22011-02-24 20:55:35 -08001551 mTouchState.copyFrom(mTempTouchState);
1552 } else if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
1553 // Discard temporary touch state since it was only valid for this action.
1554 } else {
1555 // Save changes to touch state as-is for all other actions.
1556 mTouchState.copyFrom(mTempTouchState);
Jeff Brownb88102f2010-09-08 11:49:43 -07001557 }
Jeff Browna032cc02011-03-07 16:56:21 -08001558
1559 // Update hover state.
Jeff Brown9302c872011-07-13 22:51:29 -07001560 mLastHoverWindowHandle = newHoverWindowHandle;
Jeff Brown95712852011-01-04 19:41:59 -08001561 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001562 } else {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001563#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001564 ALOGD("Not updating touch focus because injection was denied.");
Jeff Brown01ce2e92010-09-26 22:20:12 -07001565#endif
Jeff Brownb88102f2010-09-08 11:49:43 -07001566 }
1567
1568Unresponsive:
Jeff Brown120a4592010-10-27 18:43:51 -07001569 // Reset temporary touch state to ensure we release unnecessary references to input channels.
1570 mTempTouchState.reset();
1571
Jeff Brown519e0242010-09-15 15:18:56 -07001572 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
1573 updateDispatchStatisticsLocked(currentTime, entry,
1574 injectionResult, timeSpentWaitingForApplication);
Jeff Brownb88102f2010-09-08 11:49:43 -07001575#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001576 ALOGD("findTouchedWindow finished: injectionResult=%d, injectionPermission=%d, "
Jeff Brown01ce2e92010-09-26 22:20:12 -07001577 "timeSpentWaitingForApplication=%0.1fms",
Jeff Brown519e0242010-09-15 15:18:56 -07001578 injectionResult, injectionPermission, timeSpentWaitingForApplication / 1000000.0);
Jeff Brownb88102f2010-09-08 11:49:43 -07001579#endif
1580 return injectionResult;
1581}
1582
Jeff Brown9302c872011-07-13 22:51:29 -07001583void InputDispatcher::addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
Jeff Browne9bb9be2012-02-06 15:47:55 -08001584 int32_t targetFlags, BitSet32 pointerIds, Vector<InputTarget>& inputTargets) {
1585 inputTargets.push();
Jeff Brownb88102f2010-09-08 11:49:43 -07001586
Jeff Browncc4f7db2011-08-30 20:34:48 -07001587 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Jeff Browne9bb9be2012-02-06 15:47:55 -08001588 InputTarget& target = inputTargets.editTop();
Jeff Browncc4f7db2011-08-30 20:34:48 -07001589 target.inputChannel = windowInfo->inputChannel;
Jeff Brownb88102f2010-09-08 11:49:43 -07001590 target.flags = targetFlags;
Jeff Browncc4f7db2011-08-30 20:34:48 -07001591 target.xOffset = - windowInfo->frameLeft;
1592 target.yOffset = - windowInfo->frameTop;
1593 target.scaleFactor = windowInfo->scaleFactor;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001594 target.pointerIds = pointerIds;
Jeff Brownb88102f2010-09-08 11:49:43 -07001595}
1596
Jeff Browne9bb9be2012-02-06 15:47:55 -08001597void InputDispatcher::addMonitoringTargetsLocked(Vector<InputTarget>& inputTargets) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001598 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
Jeff Browne9bb9be2012-02-06 15:47:55 -08001599 inputTargets.push();
Jeff Brownb88102f2010-09-08 11:49:43 -07001600
Jeff Browne9bb9be2012-02-06 15:47:55 -08001601 InputTarget& target = inputTargets.editTop();
Jeff Brownb88102f2010-09-08 11:49:43 -07001602 target.inputChannel = mMonitoringChannels[i];
Jeff Brownb6110c22011-04-01 16:15:13 -07001603 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
Jeff Brownb88102f2010-09-08 11:49:43 -07001604 target.xOffset = 0;
1605 target.yOffset = 0;
Jeff Brownb6110c22011-04-01 16:15:13 -07001606 target.pointerIds.clear();
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001607 target.scaleFactor = 1.0f;
Jeff Brownb88102f2010-09-08 11:49:43 -07001608 }
1609}
1610
Jeff Brown9302c872011-07-13 22:51:29 -07001611bool InputDispatcher::checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
Jeff Brown01ce2e92010-09-26 22:20:12 -07001612 const InjectionState* injectionState) {
1613 if (injectionState
Jeff Browncc4f7db2011-08-30 20:34:48 -07001614 && (windowHandle == NULL
1615 || windowHandle->getInfo()->ownerUid != injectionState->injectorUid)
Jeff Brownb6997262010-10-08 22:31:17 -07001616 && !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Jeff Brown9302c872011-07-13 22:51:29 -07001617 if (windowHandle != NULL) {
Steve Block8564c8d2012-01-05 23:22:43 +00001618 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
Jeff Brown9302c872011-07-13 22:51:29 -07001619 "owned by uid %d",
Jeff Brownb6997262010-10-08 22:31:17 -07001620 injectionState->injectorPid, injectionState->injectorUid,
Jeff Browncc4f7db2011-08-30 20:34:48 -07001621 windowHandle->getName().string(),
1622 windowHandle->getInfo()->ownerUid);
Jeff Brownb6997262010-10-08 22:31:17 -07001623 } else {
Steve Block8564c8d2012-01-05 23:22:43 +00001624 ALOGW("Permission denied: injecting event from pid %d uid %d",
Jeff Brownb6997262010-10-08 22:31:17 -07001625 injectionState->injectorPid, injectionState->injectorUid);
Jeff Brownb88102f2010-09-08 11:49:43 -07001626 }
Jeff Brownb6997262010-10-08 22:31:17 -07001627 return false;
Jeff Brownb88102f2010-09-08 11:49:43 -07001628 }
1629 return true;
1630}
1631
Jeff Brown19dfc832010-10-05 12:26:23 -07001632bool InputDispatcher::isWindowObscuredAtPointLocked(
Jeff Brown9302c872011-07-13 22:51:29 -07001633 const sp<InputWindowHandle>& windowHandle, int32_t x, int32_t y) const {
Jeff Brown83d616a2012-09-09 20:33:43 -07001634 int32_t displayId = windowHandle->getInfo()->displayId;
Jeff Brown9302c872011-07-13 22:51:29 -07001635 size_t numWindows = mWindowHandles.size();
Jeff Brownb88102f2010-09-08 11:49:43 -07001636 for (size_t i = 0; i < numWindows; i++) {
Jeff Brown9302c872011-07-13 22:51:29 -07001637 sp<InputWindowHandle> otherHandle = mWindowHandles.itemAt(i);
1638 if (otherHandle == windowHandle) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001639 break;
1640 }
Jeff Browncc4f7db2011-08-30 20:34:48 -07001641
1642 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Jeff Brown83d616a2012-09-09 20:33:43 -07001643 if (otherInfo->displayId == displayId
1644 && otherInfo->visible && !otherInfo->isTrustedOverlay()
Jeff Browncc4f7db2011-08-30 20:34:48 -07001645 && otherInfo->frameContainsPoint(x, y)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001646 return true;
1647 }
1648 }
1649 return false;
1650}
1651
Jeff Brownd1c48a02012-02-06 19:12:47 -08001652bool InputDispatcher::isWindowReadyForMoreInputLocked(nsecs_t currentTime,
Jeff Brown0952c302012-02-13 13:48:59 -08001653 const sp<InputWindowHandle>& windowHandle, const EventEntry* eventEntry) {
Jeff Browncc4f7db2011-08-30 20:34:48 -07001654 ssize_t connectionIndex = getConnectionIndexLocked(windowHandle->getInputChannel());
Jeff Brown519e0242010-09-15 15:18:56 -07001655 if (connectionIndex >= 0) {
Jeff Browncbee6d62012-02-03 20:11:27 -08001656 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
Jeff Brownd1c48a02012-02-06 19:12:47 -08001657 if (connection->inputPublisherBlocked) {
1658 return false;
1659 }
Jeff Brown0952c302012-02-13 13:48:59 -08001660 if (eventEntry->type == EventEntry::TYPE_KEY) {
1661 // If the event is a key event, then we must wait for all previous events to
1662 // complete before delivering it because previous events may have the
1663 // side-effect of transferring focus to a different window and we want to
1664 // ensure that the following keys are sent to the new window.
1665 //
1666 // Suppose the user touches a button in a window then immediately presses "A".
1667 // If the button causes a pop-up window to appear then we want to ensure that
1668 // the "A" key is delivered to the new pop-up window. This is because users
1669 // often anticipate pending UI changes when typing on a keyboard.
1670 // To obtain this behavior, we must serialize key events with respect to all
1671 // prior input events.
Jeff Brownd1c48a02012-02-06 19:12:47 -08001672 return connection->outboundQueue.isEmpty()
1673 && connection->waitQueue.isEmpty();
1674 }
Jeff Brown0952c302012-02-13 13:48:59 -08001675 // Touch events can always be sent to a window immediately because the user intended
1676 // to touch whatever was visible at the time. Even if focus changes or a new
1677 // window appears moments later, the touch event was meant to be delivered to
1678 // whatever window happened to be on screen at the time.
1679 //
1680 // Generic motion events, such as trackball or joystick events are a little trickier.
1681 // Like key events, generic motion events are delivered to the focused window.
1682 // Unlike key events, generic motion events don't tend to transfer focus to other
1683 // windows and it is not important for them to be serialized. So we prefer to deliver
1684 // generic motion events as soon as possible to improve efficiency and reduce lag
1685 // through batching.
1686 //
1687 // The one case where we pause input event delivery is when the wait queue is piling
1688 // up with lots of events because the application is not responding.
1689 // This condition ensures that ANRs are detected reliably.
Jeff Brownd1c48a02012-02-06 19:12:47 -08001690 if (!connection->waitQueue.isEmpty()
1691 && currentTime >= connection->waitQueue.head->eventEntry->eventTime
1692 + STREAM_AHEAD_EVENT_TIMEOUT) {
1693 return false;
1694 }
Jeff Brown519e0242010-09-15 15:18:56 -07001695 }
Jeff Brownd1c48a02012-02-06 19:12:47 -08001696 return true;
Jeff Brown519e0242010-09-15 15:18:56 -07001697}
1698
Jeff Brown9302c872011-07-13 22:51:29 -07001699String8 InputDispatcher::getApplicationWindowLabelLocked(
1700 const sp<InputApplicationHandle>& applicationHandle,
1701 const sp<InputWindowHandle>& windowHandle) {
1702 if (applicationHandle != NULL) {
1703 if (windowHandle != NULL) {
Jeff Browncc4f7db2011-08-30 20:34:48 -07001704 String8 label(applicationHandle->getName());
Jeff Brown519e0242010-09-15 15:18:56 -07001705 label.append(" - ");
Jeff Browncc4f7db2011-08-30 20:34:48 -07001706 label.append(windowHandle->getName());
Jeff Brown519e0242010-09-15 15:18:56 -07001707 return label;
1708 } else {
Jeff Browncc4f7db2011-08-30 20:34:48 -07001709 return applicationHandle->getName();
Jeff Brown519e0242010-09-15 15:18:56 -07001710 }
Jeff Brown9302c872011-07-13 22:51:29 -07001711 } else if (windowHandle != NULL) {
Jeff Browncc4f7db2011-08-30 20:34:48 -07001712 return windowHandle->getName();
Jeff Brown519e0242010-09-15 15:18:56 -07001713 } else {
1714 return String8("<unknown application or window>");
1715 }
1716}
1717
Jeff Browne2fe69e2010-10-18 13:21:23 -07001718void InputDispatcher::pokeUserActivityLocked(const EventEntry* eventEntry) {
Jeff Brownb696de52012-07-27 15:38:50 -07001719 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Jeff Brown4d396052010-10-29 21:50:21 -07001720 switch (eventEntry->type) {
1721 case EventEntry::TYPE_MOTION: {
Jeff Browne2fe69e2010-10-18 13:21:23 -07001722 const MotionEntry* motionEntry = static_cast<const MotionEntry*>(eventEntry);
Jeff Brown4d396052010-10-29 21:50:21 -07001723 if (motionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
1724 return;
1725 }
1726
Jeff Brown56194eb2011-03-02 19:23:13 -08001727 if (MotionEvent::isTouchEvent(motionEntry->source, motionEntry->action)) {
Jeff Brownb696de52012-07-27 15:38:50 -07001728 eventType = USER_ACTIVITY_EVENT_TOUCH;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001729 }
Jeff Brown4d396052010-10-29 21:50:21 -07001730 break;
1731 }
1732 case EventEntry::TYPE_KEY: {
1733 const KeyEntry* keyEntry = static_cast<const KeyEntry*>(eventEntry);
1734 if (keyEntry->flags & AKEY_EVENT_FLAG_CANCELED) {
1735 return;
1736 }
Jeff Brownb696de52012-07-27 15:38:50 -07001737 eventType = USER_ACTIVITY_EVENT_BUTTON;
Jeff Brown4d396052010-10-29 21:50:21 -07001738 break;
1739 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001740 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001741
Jeff Brownb88102f2010-09-08 11:49:43 -07001742 CommandEntry* commandEntry = postCommandLocked(
1743 & InputDispatcher::doPokeUserActivityLockedInterruptible);
Jeff Browne2fe69e2010-10-18 13:21:23 -07001744 commandEntry->eventTime = eventEntry->eventTime;
Jeff Brownb88102f2010-09-08 11:49:43 -07001745 commandEntry->userActivityEventType = eventType;
1746}
1747
Jeff Brown7fbdc842010-06-17 20:52:56 -07001748void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001749 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001750#if DEBUG_DISPATCH_CYCLE
Steve Block5baa3a62011-12-20 16:23:08 +00001751 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
Jeff Brown9cc695c2011-08-23 18:35:04 -07001752 "xOffset=%f, yOffset=%f, scaleFactor=%f, "
Jeff Brown3241b6b2012-02-03 15:08:02 -08001753 "pointerIds=0x%x",
Jeff Brown519e0242010-09-15 15:18:56 -07001754 connection->getInputChannelName(), inputTarget->flags,
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001755 inputTarget->xOffset, inputTarget->yOffset,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001756 inputTarget->scaleFactor, inputTarget->pointerIds.value);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001757#endif
1758
1759 // Skip this event if the connection status is not normal.
Jeff Brown519e0242010-09-15 15:18:56 -07001760 // We don't want to enqueue additional outbound events if the connection is broken.
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001761 if (connection->status != Connection::STATUS_NORMAL) {
Jeff Brownb6997262010-10-08 22:31:17 -07001762#if DEBUG_DISPATCH_CYCLE
Steve Block5baa3a62011-12-20 16:23:08 +00001763 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Jeff Brownb88102f2010-09-08 11:49:43 -07001764 connection->getInputChannelName(), connection->getStatusLabel());
Jeff Brownb6997262010-10-08 22:31:17 -07001765#endif
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001766 return;
1767 }
1768
Jeff Brown01ce2e92010-09-26 22:20:12 -07001769 // Split a motion event if needed.
Jeff Brown3241b6b2012-02-03 15:08:02 -08001770 if (inputTarget->flags & InputTarget::FLAG_SPLIT) {
Steve Blockec193de2012-01-09 18:35:44 +00001771 ALOG_ASSERT(eventEntry->type == EventEntry::TYPE_MOTION);
Jeff Brown01ce2e92010-09-26 22:20:12 -07001772
1773 MotionEntry* originalMotionEntry = static_cast<MotionEntry*>(eventEntry);
1774 if (inputTarget->pointerIds.count() != originalMotionEntry->pointerCount) {
1775 MotionEntry* splitMotionEntry = splitMotionEvent(
1776 originalMotionEntry, inputTarget->pointerIds);
Jeff Brown58a2da82011-01-25 16:02:22 -08001777 if (!splitMotionEntry) {
1778 return; // split event was dropped
1779 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001780#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001781 ALOGD("channel '%s' ~ Split motion event.",
Jeff Brown01ce2e92010-09-26 22:20:12 -07001782 connection->getInputChannelName());
1783 logOutboundMotionDetailsLocked(" ", splitMotionEntry);
1784#endif
Jeff Brownc0cb3dc2012-01-12 18:30:12 -08001785 enqueueDispatchEntriesLocked(currentTime, connection,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001786 splitMotionEntry, inputTarget);
Jeff Brownc0cb3dc2012-01-12 18:30:12 -08001787 splitMotionEntry->release();
1788 return;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001789 }
1790 }
1791
Jeff Brownc0cb3dc2012-01-12 18:30:12 -08001792 // Not splitting. Enqueue dispatch entries for the event as is.
Jeff Brown3241b6b2012-02-03 15:08:02 -08001793 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
Jeff Brownc0cb3dc2012-01-12 18:30:12 -08001794}
1795
1796void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001797 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001798 bool wasEmpty = connection->outboundQueue.isEmpty();
1799
Jeff Browna032cc02011-03-07 16:56:21 -08001800 // Enqueue dispatch entries for the requested modes.
1801 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001802 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
Jeff Browna032cc02011-03-07 16:56:21 -08001803 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001804 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
Jeff Browna032cc02011-03-07 16:56:21 -08001805 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001806 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
Jeff Browna032cc02011-03-07 16:56:21 -08001807 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001808 InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brown98db5fa2011-06-08 15:37:10 -07001809 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001810 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
Jeff Brown98db5fa2011-06-08 15:37:10 -07001811 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001812 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Jeff Browna032cc02011-03-07 16:56:21 -08001813
1814 // If the outbound queue was previously empty, start the dispatch cycle going.
Jeff Brownb6110c22011-04-01 16:15:13 -07001815 if (wasEmpty && !connection->outboundQueue.isEmpty()) {
Jeff Browna032cc02011-03-07 16:56:21 -08001816 startDispatchCycleLocked(currentTime, connection);
1817 }
1818}
1819
1820void InputDispatcher::enqueueDispatchEntryLocked(
1821 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001822 int32_t dispatchMode) {
Jeff Browna032cc02011-03-07 16:56:21 -08001823 int32_t inputTargetFlags = inputTarget->flags;
1824 if (!(inputTargetFlags & dispatchMode)) {
1825 return;
1826 }
1827 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
1828
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001829 // This is a new event.
1830 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Jeff Brownac386072011-07-20 15:19:50 -07001831 DispatchEntry* dispatchEntry = new DispatchEntry(eventEntry, // increments ref
Dianne Hackbornaa9d84c2011-05-09 19:00:59 -07001832 inputTargetFlags, inputTarget->xOffset, inputTarget->yOffset,
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001833 inputTarget->scaleFactor);
Jeff Brown6ec402b2010-07-28 15:48:59 -07001834
Jeff Brown81346812011-06-28 20:08:48 -07001835 // Apply target flags and update the connection's input state.
1836 switch (eventEntry->type) {
1837 case EventEntry::TYPE_KEY: {
1838 KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
1839 dispatchEntry->resolvedAction = keyEntry->action;
1840 dispatchEntry->resolvedFlags = keyEntry->flags;
1841
1842 if (!connection->inputState.trackKey(keyEntry,
1843 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags)) {
1844#if DEBUG_DISPATCH_CYCLE
Steve Block5baa3a62011-12-20 16:23:08 +00001845 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
Jeff Brown81346812011-06-28 20:08:48 -07001846 connection->getInputChannelName());
1847#endif
Jeff Brownc0cb3dc2012-01-12 18:30:12 -08001848 delete dispatchEntry;
Jeff Brown81346812011-06-28 20:08:48 -07001849 return; // skip the inconsistent event
1850 }
1851 break;
1852 }
1853
1854 case EventEntry::TYPE_MOTION: {
1855 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
1856 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
1857 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
1858 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
1859 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
1860 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
1861 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
1862 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
1863 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
1864 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
1865 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
1866 } else {
1867 dispatchEntry->resolvedAction = motionEntry->action;
1868 }
1869 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE
1870 && !connection->inputState.isHovering(
Jeff Brown83d616a2012-09-09 20:33:43 -07001871 motionEntry->deviceId, motionEntry->source, motionEntry->displayId)) {
Jeff Brown81346812011-06-28 20:08:48 -07001872#if DEBUG_DISPATCH_CYCLE
Steve Block5baa3a62011-12-20 16:23:08 +00001873 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter event",
Jeff Brown81346812011-06-28 20:08:48 -07001874 connection->getInputChannelName());
1875#endif
1876 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
1877 }
1878
1879 dispatchEntry->resolvedFlags = motionEntry->flags;
1880 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
1881 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
1882 }
1883
1884 if (!connection->inputState.trackMotion(motionEntry,
1885 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags)) {
1886#if DEBUG_DISPATCH_CYCLE
Steve Block5baa3a62011-12-20 16:23:08 +00001887 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion event",
Jeff Brown81346812011-06-28 20:08:48 -07001888 connection->getInputChannelName());
1889#endif
Jeff Brownc0cb3dc2012-01-12 18:30:12 -08001890 delete dispatchEntry;
Jeff Brown81346812011-06-28 20:08:48 -07001891 return; // skip the inconsistent event
1892 }
1893 break;
1894 }
1895 }
1896
Jeff Brownc0cb3dc2012-01-12 18:30:12 -08001897 // Remember that we are waiting for this dispatch to complete.
1898 if (dispatchEntry->hasForegroundTarget()) {
1899 incrementPendingForegroundDispatchesLocked(eventEntry);
1900 }
1901
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001902 // Enqueue the dispatch entry.
1903 connection->outboundQueue.enqueueAtTail(dispatchEntry);
Jeff Brown481c1572012-03-09 14:41:15 -08001904 traceOutboundQueueLengthLocked(connection);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001905}
1906
Jeff Brown7fbdc842010-06-17 20:52:56 -07001907void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Jeff Brown519e0242010-09-15 15:18:56 -07001908 const sp<Connection>& connection) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001909#if DEBUG_DISPATCH_CYCLE
Steve Block5baa3a62011-12-20 16:23:08 +00001910 ALOGD("channel '%s' ~ startDispatchCycle",
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001911 connection->getInputChannelName());
1912#endif
1913
Jeff Brownd1c48a02012-02-06 19:12:47 -08001914 while (connection->status == Connection::STATUS_NORMAL
1915 && !connection->outboundQueue.isEmpty()) {
1916 DispatchEntry* dispatchEntry = connection->outboundQueue.head;
Jeff Brown265f1cc2012-06-11 18:01:06 -07001917 dispatchEntry->deliveryTime = currentTime;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001918
Jeff Brownd1c48a02012-02-06 19:12:47 -08001919 // Publish the event.
1920 status_t status;
1921 EventEntry* eventEntry = dispatchEntry->eventEntry;
1922 switch (eventEntry->type) {
1923 case EventEntry::TYPE_KEY: {
1924 KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001925
Jeff Brownd1c48a02012-02-06 19:12:47 -08001926 // Publish the key event.
Jeff Brown072ec962012-02-07 14:46:57 -08001927 status = connection->inputPublisher.publishKeyEvent(dispatchEntry->seq,
Jeff Brownd1c48a02012-02-06 19:12:47 -08001928 keyEntry->deviceId, keyEntry->source,
1929 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags,
1930 keyEntry->keyCode, keyEntry->scanCode,
1931 keyEntry->metaState, keyEntry->repeatCount, keyEntry->downTime,
1932 keyEntry->eventTime);
1933 break;
1934 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001935
Jeff Brownd1c48a02012-02-06 19:12:47 -08001936 case EventEntry::TYPE_MOTION: {
1937 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001938
Jeff Brownd1c48a02012-02-06 19:12:47 -08001939 PointerCoords scaledCoords[MAX_POINTERS];
1940 const PointerCoords* usingCoords = motionEntry->pointerCoords;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001941
Jeff Brownd1c48a02012-02-06 19:12:47 -08001942 // Set the X and Y offset depending on the input source.
1943 float xOffset, yOffset, scaleFactor;
1944 if ((motionEntry->source & AINPUT_SOURCE_CLASS_POINTER)
1945 && !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
1946 scaleFactor = dispatchEntry->scaleFactor;
1947 xOffset = dispatchEntry->xOffset * scaleFactor;
1948 yOffset = dispatchEntry->yOffset * scaleFactor;
1949 if (scaleFactor != 1.0f) {
1950 for (size_t i = 0; i < motionEntry->pointerCount; i++) {
1951 scaledCoords[i] = motionEntry->pointerCoords[i];
1952 scaledCoords[i].scale(scaleFactor);
1953 }
1954 usingCoords = scaledCoords;
1955 }
1956 } else {
1957 xOffset = 0.0f;
1958 yOffset = 0.0f;
1959 scaleFactor = 1.0f;
1960
1961 // We don't want the dispatch target to know.
1962 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
1963 for (size_t i = 0; i < motionEntry->pointerCount; i++) {
1964 scaledCoords[i].clear();
1965 }
1966 usingCoords = scaledCoords;
1967 }
1968 }
1969
1970 // Publish the motion event.
Jeff Brown072ec962012-02-07 14:46:57 -08001971 status = connection->inputPublisher.publishMotionEvent(dispatchEntry->seq,
Jeff Brownd1c48a02012-02-06 19:12:47 -08001972 motionEntry->deviceId, motionEntry->source,
1973 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags,
1974 motionEntry->edgeFlags, motionEntry->metaState, motionEntry->buttonState,
1975 xOffset, yOffset,
1976 motionEntry->xPrecision, motionEntry->yPrecision,
1977 motionEntry->downTime, motionEntry->eventTime,
1978 motionEntry->pointerCount, motionEntry->pointerProperties,
1979 usingCoords);
1980 break;
1981 }
1982
1983 default:
1984 ALOG_ASSERT(false);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001985 return;
1986 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001987
Jeff Brownd1c48a02012-02-06 19:12:47 -08001988 // Check the result.
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001989 if (status) {
Jeff Brownd1c48a02012-02-06 19:12:47 -08001990 if (status == WOULD_BLOCK) {
1991 if (connection->waitQueue.isEmpty()) {
1992 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
1993 "This is unexpected because the wait queue is empty, so the pipe "
1994 "should be empty and we shouldn't have any problems writing an "
1995 "event to it, status=%d", connection->getInputChannelName(), status);
1996 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
1997 } else {
1998 // Pipe is full and we are waiting for the app to finish process some events
1999 // before sending more events to it.
2000#if DEBUG_DISPATCH_CYCLE
2001 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
2002 "waiting for the application to catch up",
2003 connection->getInputChannelName());
2004#endif
2005 connection->inputPublisherBlocked = true;
2006 }
2007 } else {
2008 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
2009 "status=%d", connection->getInputChannelName(), status);
2010 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2011 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002012 return;
2013 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002014
Jeff Brownd1c48a02012-02-06 19:12:47 -08002015 // Re-enqueue the event on the wait queue.
2016 connection->outboundQueue.dequeue(dispatchEntry);
Jeff Brown481c1572012-03-09 14:41:15 -08002017 traceOutboundQueueLengthLocked(connection);
Jeff Brownd1c48a02012-02-06 19:12:47 -08002018 connection->waitQueue.enqueueAtTail(dispatchEntry);
Jeff Brown481c1572012-03-09 14:41:15 -08002019 traceWaitQueueLengthLocked(connection);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002020 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002021}
2022
Jeff Brown7fbdc842010-06-17 20:52:56 -07002023void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Jeff Brown072ec962012-02-07 14:46:57 -08002024 const sp<Connection>& connection, uint32_t seq, bool handled) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002025#if DEBUG_DISPATCH_CYCLE
Jeff Brown072ec962012-02-07 14:46:57 -08002026 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
2027 connection->getInputChannelName(), seq, toString(handled));
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002028#endif
2029
Jeff Brownd1c48a02012-02-06 19:12:47 -08002030 connection->inputPublisherBlocked = false;
2031
Jeff Brown9c3cda02010-06-15 01:31:58 -07002032 if (connection->status == Connection::STATUS_BROKEN
2033 || connection->status == Connection::STATUS_ZOMBIE) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002034 return;
2035 }
2036
Jeff Brown3915bb82010-11-05 15:02:16 -07002037 // Notify other system components and prepare to start the next dispatch cycle.
Jeff Brown072ec962012-02-07 14:46:57 -08002038 onDispatchCycleFinishedLocked(currentTime, connection, seq, handled);
Jeff Brownb88102f2010-09-08 11:49:43 -07002039}
2040
Jeff Brownb6997262010-10-08 22:31:17 -07002041void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Jeff Browncc4f7db2011-08-30 20:34:48 -07002042 const sp<Connection>& connection, bool notify) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002043#if DEBUG_DISPATCH_CYCLE
Steve Block5baa3a62011-12-20 16:23:08 +00002044 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
Jeff Browncc4f7db2011-08-30 20:34:48 -07002045 connection->getInputChannelName(), toString(notify));
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002046#endif
2047
Jeff Brownd1c48a02012-02-06 19:12:47 -08002048 // Clear the dispatch queues.
2049 drainDispatchQueueLocked(&connection->outboundQueue);
Jeff Brown481c1572012-03-09 14:41:15 -08002050 traceOutboundQueueLengthLocked(connection);
Jeff Brownd1c48a02012-02-06 19:12:47 -08002051 drainDispatchQueueLocked(&connection->waitQueue);
Jeff Brown481c1572012-03-09 14:41:15 -08002052 traceWaitQueueLengthLocked(connection);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002053
Jeff Brownb6997262010-10-08 22:31:17 -07002054 // The connection appears to be unrecoverably broken.
Jeff Brown9c3cda02010-06-15 01:31:58 -07002055 // Ignore already broken or zombie connections.
Jeff Brownb6997262010-10-08 22:31:17 -07002056 if (connection->status == Connection::STATUS_NORMAL) {
2057 connection->status = Connection::STATUS_BROKEN;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002058
Jeff Browncc4f7db2011-08-30 20:34:48 -07002059 if (notify) {
2060 // Notify other system components.
2061 onDispatchCycleBrokenLocked(currentTime, connection);
2062 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002063 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002064}
2065
Jeff Brownd1c48a02012-02-06 19:12:47 -08002066void InputDispatcher::drainDispatchQueueLocked(Queue<DispatchEntry>* queue) {
2067 while (!queue->isEmpty()) {
2068 DispatchEntry* dispatchEntry = queue->dequeueAtHead();
2069 releaseDispatchEntryLocked(dispatchEntry);
Jeff Brownb88102f2010-09-08 11:49:43 -07002070 }
Jeff Brownb88102f2010-09-08 11:49:43 -07002071}
2072
Jeff Brownd1c48a02012-02-06 19:12:47 -08002073void InputDispatcher::releaseDispatchEntryLocked(DispatchEntry* dispatchEntry) {
2074 if (dispatchEntry->hasForegroundTarget()) {
2075 decrementPendingForegroundDispatchesLocked(dispatchEntry->eventEntry);
2076 }
2077 delete dispatchEntry;
2078}
2079
Jeff Browncbee6d62012-02-03 20:11:27 -08002080int InputDispatcher::handleReceiveCallback(int fd, int events, void* data) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002081 InputDispatcher* d = static_cast<InputDispatcher*>(data);
2082
2083 { // acquire lock
2084 AutoMutex _l(d->mLock);
2085
Jeff Browncbee6d62012-02-03 20:11:27 -08002086 ssize_t connectionIndex = d->mConnectionsByFd.indexOfKey(fd);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002087 if (connectionIndex < 0) {
Steve Block3762c312012-01-06 19:20:56 +00002088 ALOGE("Received spurious receive callback for unknown input channel. "
Jeff Browncbee6d62012-02-03 20:11:27 -08002089 "fd=%d, events=0x%x", fd, events);
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002090 return 0; // remove the callback
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002091 }
2092
Jeff Browncc4f7db2011-08-30 20:34:48 -07002093 bool notify;
Jeff Browncbee6d62012-02-03 20:11:27 -08002094 sp<Connection> connection = d->mConnectionsByFd.valueAt(connectionIndex);
Jeff Browncc4f7db2011-08-30 20:34:48 -07002095 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
2096 if (!(events & ALOOPER_EVENT_INPUT)) {
Steve Block8564c8d2012-01-05 23:22:43 +00002097 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
Jeff Browncc4f7db2011-08-30 20:34:48 -07002098 "events=0x%x", connection->getInputChannelName(), events);
2099 return 1;
2100 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002101
Jeff Brown1adee112012-02-07 10:25:41 -08002102 nsecs_t currentTime = now();
2103 bool gotOne = false;
2104 status_t status;
2105 for (;;) {
Jeff Brown072ec962012-02-07 14:46:57 -08002106 uint32_t seq;
2107 bool handled;
2108 status = connection->inputPublisher.receiveFinishedSignal(&seq, &handled);
Jeff Brown1adee112012-02-07 10:25:41 -08002109 if (status) {
2110 break;
2111 }
Jeff Brown072ec962012-02-07 14:46:57 -08002112 d->finishDispatchCycleLocked(currentTime, connection, seq, handled);
Jeff Brown1adee112012-02-07 10:25:41 -08002113 gotOne = true;
2114 }
2115 if (gotOne) {
Jeff Browncc4f7db2011-08-30 20:34:48 -07002116 d->runCommandsLockedInterruptible();
Jeff Brown1adee112012-02-07 10:25:41 -08002117 if (status == WOULD_BLOCK) {
2118 return 1;
2119 }
Jeff Browncc4f7db2011-08-30 20:34:48 -07002120 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002121
Jeff Brown1adee112012-02-07 10:25:41 -08002122 notify = status != DEAD_OBJECT || !connection->monitor;
2123 if (notify) {
2124 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
2125 connection->getInputChannelName(), status);
2126 }
Jeff Browncc4f7db2011-08-30 20:34:48 -07002127 } else {
2128 // Monitor channels are never explicitly unregistered.
2129 // We do it automatically when the remote endpoint is closed so don't warn
2130 // about them.
2131 notify = !connection->monitor;
2132 if (notify) {
Steve Block8564c8d2012-01-05 23:22:43 +00002133 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. "
Jeff Browncc4f7db2011-08-30 20:34:48 -07002134 "events=0x%x", connection->getInputChannelName(), events);
2135 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002136 }
2137
Jeff Browncc4f7db2011-08-30 20:34:48 -07002138 // Unregister the channel.
2139 d->unregisterInputChannelLocked(connection->inputChannel, notify);
2140 return 0; // remove the callback
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002141 } // release lock
2142}
2143
Jeff Brownb6997262010-10-08 22:31:17 -07002144void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Jeff Brownda3d5a92011-03-29 15:11:34 -07002145 const CancelationOptions& options) {
Jeff Browncbee6d62012-02-03 20:11:27 -08002146 for (size_t i = 0; i < mConnectionsByFd.size(); i++) {
Jeff Brownb6997262010-10-08 22:31:17 -07002147 synthesizeCancelationEventsForConnectionLocked(
Jeff Browncbee6d62012-02-03 20:11:27 -08002148 mConnectionsByFd.valueAt(i), options);
Jeff Brownb6997262010-10-08 22:31:17 -07002149 }
2150}
2151
2152void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Jeff Brownda3d5a92011-03-29 15:11:34 -07002153 const sp<InputChannel>& channel, const CancelationOptions& options) {
Jeff Brownb6997262010-10-08 22:31:17 -07002154 ssize_t index = getConnectionIndexLocked(channel);
2155 if (index >= 0) {
2156 synthesizeCancelationEventsForConnectionLocked(
Jeff Browncbee6d62012-02-03 20:11:27 -08002157 mConnectionsByFd.valueAt(index), options);
Jeff Brownb6997262010-10-08 22:31:17 -07002158 }
2159}
2160
2161void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
Jeff Brownda3d5a92011-03-29 15:11:34 -07002162 const sp<Connection>& connection, const CancelationOptions& options) {
Jeff Brownc0cb3dc2012-01-12 18:30:12 -08002163 if (connection->status == Connection::STATUS_BROKEN) {
2164 return;
2165 }
2166
Jeff Brownb6997262010-10-08 22:31:17 -07002167 nsecs_t currentTime = now();
2168
Jeff Brown8b4be5602012-02-06 16:31:05 -08002169 Vector<EventEntry*> cancelationEvents;
Jeff Brownac386072011-07-20 15:19:50 -07002170 connection->inputState.synthesizeCancelationEvents(currentTime,
Jeff Brown8b4be5602012-02-06 16:31:05 -08002171 cancelationEvents, options);
Jeff Brownb6997262010-10-08 22:31:17 -07002172
Jeff Brown8b4be5602012-02-06 16:31:05 -08002173 if (!cancelationEvents.isEmpty()) {
Jeff Brownb6997262010-10-08 22:31:17 -07002174#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00002175 ALOGD("channel '%s' ~ Synthesized %d cancelation events to bring channel back in sync "
Jeff Brownda3d5a92011-03-29 15:11:34 -07002176 "with reality: %s, mode=%d.",
Jeff Brown8b4be5602012-02-06 16:31:05 -08002177 connection->getInputChannelName(), cancelationEvents.size(),
Jeff Brownda3d5a92011-03-29 15:11:34 -07002178 options.reason, options.mode);
Jeff Brownb6997262010-10-08 22:31:17 -07002179#endif
Jeff Brown8b4be5602012-02-06 16:31:05 -08002180 for (size_t i = 0; i < cancelationEvents.size(); i++) {
2181 EventEntry* cancelationEventEntry = cancelationEvents.itemAt(i);
Jeff Brownb6997262010-10-08 22:31:17 -07002182 switch (cancelationEventEntry->type) {
2183 case EventEntry::TYPE_KEY:
2184 logOutboundKeyDetailsLocked("cancel - ",
2185 static_cast<KeyEntry*>(cancelationEventEntry));
2186 break;
2187 case EventEntry::TYPE_MOTION:
2188 logOutboundMotionDetailsLocked("cancel - ",
2189 static_cast<MotionEntry*>(cancelationEventEntry));
2190 break;
2191 }
2192
Jeff Brown81346812011-06-28 20:08:48 -07002193 InputTarget target;
Jeff Brown9302c872011-07-13 22:51:29 -07002194 sp<InputWindowHandle> windowHandle = getWindowHandleLocked(connection->inputChannel);
2195 if (windowHandle != NULL) {
Jeff Browncc4f7db2011-08-30 20:34:48 -07002196 const InputWindowInfo* windowInfo = windowHandle->getInfo();
2197 target.xOffset = -windowInfo->frameLeft;
2198 target.yOffset = -windowInfo->frameTop;
2199 target.scaleFactor = windowInfo->scaleFactor;
Jeff Brownb6997262010-10-08 22:31:17 -07002200 } else {
Jeff Brown81346812011-06-28 20:08:48 -07002201 target.xOffset = 0;
2202 target.yOffset = 0;
2203 target.scaleFactor = 1.0f;
Jeff Brownb6997262010-10-08 22:31:17 -07002204 }
Jeff Brown81346812011-06-28 20:08:48 -07002205 target.inputChannel = connection->inputChannel;
2206 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
Jeff Brownb6997262010-10-08 22:31:17 -07002207
Jeff Brown81346812011-06-28 20:08:48 -07002208 enqueueDispatchEntryLocked(connection, cancelationEventEntry, // increments ref
Jeff Brown3241b6b2012-02-03 15:08:02 -08002209 &target, InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brownb6997262010-10-08 22:31:17 -07002210
Jeff Brownac386072011-07-20 15:19:50 -07002211 cancelationEventEntry->release();
Jeff Brownb6997262010-10-08 22:31:17 -07002212 }
2213
Jeff Brownd1c48a02012-02-06 19:12:47 -08002214 startDispatchCycleLocked(currentTime, connection);
Jeff Brownb6997262010-10-08 22:31:17 -07002215 }
2216}
2217
Jeff Brown01ce2e92010-09-26 22:20:12 -07002218InputDispatcher::MotionEntry*
2219InputDispatcher::splitMotionEvent(const MotionEntry* originalMotionEntry, BitSet32 pointerIds) {
Steve Blockec193de2012-01-09 18:35:44 +00002220 ALOG_ASSERT(pointerIds.value != 0);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002221
2222 uint32_t splitPointerIndexMap[MAX_POINTERS];
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002223 PointerProperties splitPointerProperties[MAX_POINTERS];
Jeff Brown01ce2e92010-09-26 22:20:12 -07002224 PointerCoords splitPointerCoords[MAX_POINTERS];
2225
2226 uint32_t originalPointerCount = originalMotionEntry->pointerCount;
2227 uint32_t splitPointerCount = 0;
2228
2229 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
2230 originalPointerIndex++) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002231 const PointerProperties& pointerProperties =
2232 originalMotionEntry->pointerProperties[originalPointerIndex];
2233 uint32_t pointerId = uint32_t(pointerProperties.id);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002234 if (pointerIds.hasBit(pointerId)) {
2235 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002236 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
Jeff Brownace13b12011-03-09 17:39:48 -08002237 splitPointerCoords[splitPointerCount].copyFrom(
Jeff Brown3241b6b2012-02-03 15:08:02 -08002238 originalMotionEntry->pointerCoords[originalPointerIndex]);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002239 splitPointerCount += 1;
2240 }
2241 }
Jeff Brown58a2da82011-01-25 16:02:22 -08002242
2243 if (splitPointerCount != pointerIds.count()) {
2244 // This is bad. We are missing some of the pointers that we expected to deliver.
2245 // Most likely this indicates that we received an ACTION_MOVE events that has
2246 // different pointer ids than we expected based on the previous ACTION_DOWN
2247 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
2248 // in this way.
Steve Block8564c8d2012-01-05 23:22:43 +00002249 ALOGW("Dropping split motion event because the pointer count is %d but "
Jeff Brown58a2da82011-01-25 16:02:22 -08002250 "we expected there to be %d pointers. This probably means we received "
2251 "a broken sequence of pointer ids from the input device.",
2252 splitPointerCount, pointerIds.count());
2253 return NULL;
2254 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07002255
2256 int32_t action = originalMotionEntry->action;
2257 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
2258 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
2259 || maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2260 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002261 const PointerProperties& pointerProperties =
2262 originalMotionEntry->pointerProperties[originalPointerIndex];
2263 uint32_t pointerId = uint32_t(pointerProperties.id);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002264 if (pointerIds.hasBit(pointerId)) {
2265 if (pointerIds.count() == 1) {
2266 // The first/last pointer went down/up.
2267 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
2268 ? AMOTION_EVENT_ACTION_DOWN : AMOTION_EVENT_ACTION_UP;
Jeff Brown9a01d052010-09-27 16:35:11 -07002269 } else {
2270 // A secondary pointer went down/up.
2271 uint32_t splitPointerIndex = 0;
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002272 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
Jeff Brown9a01d052010-09-27 16:35:11 -07002273 splitPointerIndex += 1;
2274 }
2275 action = maskedAction | (splitPointerIndex
2276 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002277 }
2278 } else {
2279 // An unrelated pointer changed.
2280 action = AMOTION_EVENT_ACTION_MOVE;
2281 }
2282 }
2283
Jeff Brownac386072011-07-20 15:19:50 -07002284 MotionEntry* splitMotionEntry = new MotionEntry(
Jeff Brown01ce2e92010-09-26 22:20:12 -07002285 originalMotionEntry->eventTime,
2286 originalMotionEntry->deviceId,
2287 originalMotionEntry->source,
2288 originalMotionEntry->policyFlags,
2289 action,
2290 originalMotionEntry->flags,
2291 originalMotionEntry->metaState,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002292 originalMotionEntry->buttonState,
Jeff Brown01ce2e92010-09-26 22:20:12 -07002293 originalMotionEntry->edgeFlags,
2294 originalMotionEntry->xPrecision,
2295 originalMotionEntry->yPrecision,
2296 originalMotionEntry->downTime,
Jeff Brown83d616a2012-09-09 20:33:43 -07002297 originalMotionEntry->displayId,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002298 splitPointerCount, splitPointerProperties, splitPointerCoords);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002299
Jeff Browna032cc02011-03-07 16:56:21 -08002300 if (originalMotionEntry->injectionState) {
2301 splitMotionEntry->injectionState = originalMotionEntry->injectionState;
2302 splitMotionEntry->injectionState->refCount += 1;
2303 }
2304
Jeff Brown01ce2e92010-09-26 22:20:12 -07002305 return splitMotionEntry;
2306}
2307
Jeff Brownbe1aa822011-07-27 16:04:54 -07002308void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002309#if DEBUG_INBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00002310 ALOGD("notifyConfigurationChanged - eventTime=%lld", args->eventTime);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002311#endif
2312
Jeff Brownb88102f2010-09-08 11:49:43 -07002313 bool needWake;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002314 { // acquire lock
2315 AutoMutex _l(mLock);
2316
Jeff Brownbe1aa822011-07-27 16:04:54 -07002317 ConfigurationChangedEntry* newEntry = new ConfigurationChangedEntry(args->eventTime);
Jeff Brownb88102f2010-09-08 11:49:43 -07002318 needWake = enqueueInboundEventLocked(newEntry);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002319 } // release lock
2320
Jeff Brownb88102f2010-09-08 11:49:43 -07002321 if (needWake) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002322 mLooper->wake();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002323 }
2324}
2325
Jeff Brownbe1aa822011-07-27 16:04:54 -07002326void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002327#if DEBUG_INBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00002328 ALOGD("notifyKey - eventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, action=0x%x, "
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002329 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%lld",
Jeff Brownbe1aa822011-07-27 16:04:54 -07002330 args->eventTime, args->deviceId, args->source, args->policyFlags,
2331 args->action, args->flags, args->keyCode, args->scanCode,
2332 args->metaState, args->downTime);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002333#endif
Jeff Brownbe1aa822011-07-27 16:04:54 -07002334 if (!validateKeyEvent(args->action)) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002335 return;
2336 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002337
Jeff Brownbe1aa822011-07-27 16:04:54 -07002338 uint32_t policyFlags = args->policyFlags;
2339 int32_t flags = args->flags;
2340 int32_t metaState = args->metaState;
Jeff Brown1f245102010-11-18 20:53:46 -08002341 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
2342 policyFlags |= POLICY_FLAG_VIRTUAL;
2343 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
2344 }
Jeff Brown924c4d42011-03-07 16:40:47 -08002345 if (policyFlags & POLICY_FLAG_ALT) {
2346 metaState |= AMETA_ALT_ON | AMETA_ALT_LEFT_ON;
2347 }
2348 if (policyFlags & POLICY_FLAG_ALT_GR) {
2349 metaState |= AMETA_ALT_ON | AMETA_ALT_RIGHT_ON;
2350 }
2351 if (policyFlags & POLICY_FLAG_SHIFT) {
2352 metaState |= AMETA_SHIFT_ON | AMETA_SHIFT_LEFT_ON;
2353 }
2354 if (policyFlags & POLICY_FLAG_CAPS_LOCK) {
2355 metaState |= AMETA_CAPS_LOCK_ON;
2356 }
2357 if (policyFlags & POLICY_FLAG_FUNCTION) {
2358 metaState |= AMETA_FUNCTION_ON;
2359 }
Jeff Brown1f245102010-11-18 20:53:46 -08002360
Jeff Browne20c9e02010-10-11 14:20:19 -07002361 policyFlags |= POLICY_FLAG_TRUSTED;
Jeff Brown1f245102010-11-18 20:53:46 -08002362
2363 KeyEvent event;
Jeff Brownbe1aa822011-07-27 16:04:54 -07002364 event.initialize(args->deviceId, args->source, args->action,
2365 flags, args->keyCode, args->scanCode, metaState, 0,
2366 args->downTime, args->eventTime);
Jeff Brown1f245102010-11-18 20:53:46 -08002367
2368 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
2369
2370 if (policyFlags & POLICY_FLAG_WOKE_HERE) {
2371 flags |= AKEY_EVENT_FLAG_WOKE_HERE;
2372 }
Jeff Brownb6997262010-10-08 22:31:17 -07002373
Jeff Brownb88102f2010-09-08 11:49:43 -07002374 bool needWake;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002375 { // acquire lock
Jeff Brown0029c662011-03-30 02:25:18 -07002376 mLock.lock();
2377
Jeff Brown83d616a2012-09-09 20:33:43 -07002378 if (shouldSendKeyToInputFilterLocked(args)) {
Jeff Brown0029c662011-03-30 02:25:18 -07002379 mLock.unlock();
2380
2381 policyFlags |= POLICY_FLAG_FILTERED;
2382 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2383 return; // event was consumed by the filter
2384 }
2385
2386 mLock.lock();
2387 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002388
Jeff Brown7fbdc842010-06-17 20:52:56 -07002389 int32_t repeatCount = 0;
Jeff Brownbe1aa822011-07-27 16:04:54 -07002390 KeyEntry* newEntry = new KeyEntry(args->eventTime,
2391 args->deviceId, args->source, policyFlags,
2392 args->action, flags, args->keyCode, args->scanCode,
2393 metaState, repeatCount, args->downTime);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002394
Jeff Brownb88102f2010-09-08 11:49:43 -07002395 needWake = enqueueInboundEventLocked(newEntry);
Jeff Brown0029c662011-03-30 02:25:18 -07002396 mLock.unlock();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002397 } // release lock
2398
Jeff Brownb88102f2010-09-08 11:49:43 -07002399 if (needWake) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002400 mLooper->wake();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002401 }
2402}
2403
Jeff Brown83d616a2012-09-09 20:33:43 -07002404bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
2405 return mInputFilterEnabled;
2406}
2407
Jeff Brownbe1aa822011-07-27 16:04:54 -07002408void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002409#if DEBUG_INBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00002410 ALOGD("notifyMotion - eventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, "
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002411 "action=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, edgeFlags=0x%x, "
Jeff Brown85a31762010-09-01 17:01:00 -07002412 "xPrecision=%f, yPrecision=%f, downTime=%lld",
Jeff Brownbe1aa822011-07-27 16:04:54 -07002413 args->eventTime, args->deviceId, args->source, args->policyFlags,
2414 args->action, args->flags, args->metaState, args->buttonState,
2415 args->edgeFlags, args->xPrecision, args->yPrecision, args->downTime);
2416 for (uint32_t i = 0; i < args->pointerCount; i++) {
Steve Block5baa3a62011-12-20 16:23:08 +00002417 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002418 "x=%f, y=%f, pressure=%f, size=%f, "
Jeff Brown85a31762010-09-01 17:01:00 -07002419 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
Jeff Brown8d608662010-08-30 03:02:23 -07002420 "orientation=%f",
Jeff Brownbe1aa822011-07-27 16:04:54 -07002421 i, args->pointerProperties[i].id,
2422 args->pointerProperties[i].toolType,
2423 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
2424 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
2425 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
2426 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
2427 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
2428 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
2429 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
2430 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
2431 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002432 }
2433#endif
Jeff Brownbe1aa822011-07-27 16:04:54 -07002434 if (!validateMotionEvent(args->action, args->pointerCount, args->pointerProperties)) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002435 return;
2436 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002437
Jeff Brownbe1aa822011-07-27 16:04:54 -07002438 uint32_t policyFlags = args->policyFlags;
Jeff Browne20c9e02010-10-11 14:20:19 -07002439 policyFlags |= POLICY_FLAG_TRUSTED;
Jeff Brownbe1aa822011-07-27 16:04:54 -07002440 mPolicy->interceptMotionBeforeQueueing(args->eventTime, /*byref*/ policyFlags);
Jeff Brownb6997262010-10-08 22:31:17 -07002441
Jeff Brownb88102f2010-09-08 11:49:43 -07002442 bool needWake;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002443 { // acquire lock
Jeff Brown0029c662011-03-30 02:25:18 -07002444 mLock.lock();
2445
Jeff Brown83d616a2012-09-09 20:33:43 -07002446 if (shouldSendMotionToInputFilterLocked(args)) {
Jeff Brown0029c662011-03-30 02:25:18 -07002447 mLock.unlock();
2448
2449 MotionEvent event;
Jeff Brownbe1aa822011-07-27 16:04:54 -07002450 event.initialize(args->deviceId, args->source, args->action, args->flags,
2451 args->edgeFlags, args->metaState, args->buttonState, 0, 0,
2452 args->xPrecision, args->yPrecision,
2453 args->downTime, args->eventTime,
2454 args->pointerCount, args->pointerProperties, args->pointerCoords);
Jeff Brown0029c662011-03-30 02:25:18 -07002455
2456 policyFlags |= POLICY_FLAG_FILTERED;
2457 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2458 return; // event was consumed by the filter
2459 }
2460
2461 mLock.lock();
2462 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002463
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002464 // Just enqueue a new motion event.
Jeff Brownbe1aa822011-07-27 16:04:54 -07002465 MotionEntry* newEntry = new MotionEntry(args->eventTime,
2466 args->deviceId, args->source, policyFlags,
2467 args->action, args->flags, args->metaState, args->buttonState,
2468 args->edgeFlags, args->xPrecision, args->yPrecision, args->downTime,
Jeff Brown83d616a2012-09-09 20:33:43 -07002469 args->displayId,
Jeff Brownbe1aa822011-07-27 16:04:54 -07002470 args->pointerCount, args->pointerProperties, args->pointerCoords);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002471
Jeff Brownb88102f2010-09-08 11:49:43 -07002472 needWake = enqueueInboundEventLocked(newEntry);
Jeff Brown0029c662011-03-30 02:25:18 -07002473 mLock.unlock();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002474 } // release lock
2475
Jeff Brownb88102f2010-09-08 11:49:43 -07002476 if (needWake) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002477 mLooper->wake();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002478 }
2479}
2480
Jeff Brown83d616a2012-09-09 20:33:43 -07002481bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
2482 // TODO: support sending secondary display events to input filter
2483 return mInputFilterEnabled && isMainDisplay(args->displayId);
2484}
2485
Jeff Brownbe1aa822011-07-27 16:04:54 -07002486void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
Jeff Brownb6997262010-10-08 22:31:17 -07002487#if DEBUG_INBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00002488 ALOGD("notifySwitch - eventTime=%lld, policyFlags=0x%x, switchCode=%d, switchValue=%d",
Jeff Brownbe1aa822011-07-27 16:04:54 -07002489 args->eventTime, args->policyFlags,
2490 args->switchCode, args->switchValue);
Jeff Brownb6997262010-10-08 22:31:17 -07002491#endif
2492
Jeff Brownbe1aa822011-07-27 16:04:54 -07002493 uint32_t policyFlags = args->policyFlags;
Jeff Browne20c9e02010-10-11 14:20:19 -07002494 policyFlags |= POLICY_FLAG_TRUSTED;
Jeff Brownbe1aa822011-07-27 16:04:54 -07002495 mPolicy->notifySwitch(args->eventTime,
2496 args->switchCode, args->switchValue, policyFlags);
Jeff Brownb6997262010-10-08 22:31:17 -07002497}
2498
Jeff Brown65fd2512011-08-18 11:20:58 -07002499void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
2500#if DEBUG_INBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00002501 ALOGD("notifyDeviceReset - eventTime=%lld, deviceId=%d",
Jeff Brown65fd2512011-08-18 11:20:58 -07002502 args->eventTime, args->deviceId);
2503#endif
2504
2505 bool needWake;
2506 { // acquire lock
2507 AutoMutex _l(mLock);
2508
2509 DeviceResetEntry* newEntry = new DeviceResetEntry(args->eventTime, args->deviceId);
2510 needWake = enqueueInboundEventLocked(newEntry);
2511 } // release lock
2512
2513 if (needWake) {
2514 mLooper->wake();
2515 }
2516}
2517
Jeff Brown7fbdc842010-06-17 20:52:56 -07002518int32_t InputDispatcher::injectInputEvent(const InputEvent* event,
Jeff Brown0029c662011-03-30 02:25:18 -07002519 int32_t injectorPid, int32_t injectorUid, int32_t syncMode, int32_t timeoutMillis,
2520 uint32_t policyFlags) {
Jeff Brown7fbdc842010-06-17 20:52:56 -07002521#if DEBUG_INBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00002522 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Jeff Brown0029c662011-03-30 02:25:18 -07002523 "syncMode=%d, timeoutMillis=%d, policyFlags=0x%08x",
2524 event->getType(), injectorPid, injectorUid, syncMode, timeoutMillis, policyFlags);
Jeff Brown7fbdc842010-06-17 20:52:56 -07002525#endif
2526
2527 nsecs_t endTime = now() + milliseconds_to_nanoseconds(timeoutMillis);
Jeff Browne20c9e02010-10-11 14:20:19 -07002528
Jeff Brown0029c662011-03-30 02:25:18 -07002529 policyFlags |= POLICY_FLAG_INJECTED;
Jeff Browne20c9e02010-10-11 14:20:19 -07002530 if (hasInjectionPermission(injectorPid, injectorUid)) {
2531 policyFlags |= POLICY_FLAG_TRUSTED;
2532 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07002533
Jeff Brown3241b6b2012-02-03 15:08:02 -08002534 EventEntry* firstInjectedEntry;
2535 EventEntry* lastInjectedEntry;
Jeff Brownb6997262010-10-08 22:31:17 -07002536 switch (event->getType()) {
2537 case AINPUT_EVENT_TYPE_KEY: {
2538 const KeyEvent* keyEvent = static_cast<const KeyEvent*>(event);
2539 int32_t action = keyEvent->getAction();
2540 if (! validateKeyEvent(action)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07002541 return INPUT_EVENT_INJECTION_FAILED;
2542 }
2543
Jeff Brownb6997262010-10-08 22:31:17 -07002544 int32_t flags = keyEvent->getFlags();
Jeff Brown1f245102010-11-18 20:53:46 -08002545 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
2546 policyFlags |= POLICY_FLAG_VIRTUAL;
2547 }
2548
Jeff Brown0029c662011-03-30 02:25:18 -07002549 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
2550 mPolicy->interceptKeyBeforeQueueing(keyEvent, /*byref*/ policyFlags);
2551 }
Jeff Brown1f245102010-11-18 20:53:46 -08002552
2553 if (policyFlags & POLICY_FLAG_WOKE_HERE) {
2554 flags |= AKEY_EVENT_FLAG_WOKE_HERE;
2555 }
Jeff Brown6ec402b2010-07-28 15:48:59 -07002556
Jeff Brownb6997262010-10-08 22:31:17 -07002557 mLock.lock();
Jeff Brown3241b6b2012-02-03 15:08:02 -08002558 firstInjectedEntry = new KeyEntry(keyEvent->getEventTime(),
Jeff Brown1f245102010-11-18 20:53:46 -08002559 keyEvent->getDeviceId(), keyEvent->getSource(),
2560 policyFlags, action, flags,
2561 keyEvent->getKeyCode(), keyEvent->getScanCode(), keyEvent->getMetaState(),
Jeff Brownb6997262010-10-08 22:31:17 -07002562 keyEvent->getRepeatCount(), keyEvent->getDownTime());
Jeff Brown3241b6b2012-02-03 15:08:02 -08002563 lastInjectedEntry = firstInjectedEntry;
Jeff Brownb6997262010-10-08 22:31:17 -07002564 break;
2565 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07002566
Jeff Brownb6997262010-10-08 22:31:17 -07002567 case AINPUT_EVENT_TYPE_MOTION: {
2568 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
Jeff Brown83d616a2012-09-09 20:33:43 -07002569 int32_t displayId = ADISPLAY_ID_DEFAULT;
Jeff Brownb6997262010-10-08 22:31:17 -07002570 int32_t action = motionEvent->getAction();
2571 size_t pointerCount = motionEvent->getPointerCount();
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002572 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
2573 if (! validateMotionEvent(action, pointerCount, pointerProperties)) {
Jeff Brownb6997262010-10-08 22:31:17 -07002574 return INPUT_EVENT_INJECTION_FAILED;
2575 }
2576
Jeff Brown0029c662011-03-30 02:25:18 -07002577 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
2578 nsecs_t eventTime = motionEvent->getEventTime();
2579 mPolicy->interceptMotionBeforeQueueing(eventTime, /*byref*/ policyFlags);
2580 }
Jeff Brownb6997262010-10-08 22:31:17 -07002581
2582 mLock.lock();
2583 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
2584 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
Jeff Brown3241b6b2012-02-03 15:08:02 -08002585 firstInjectedEntry = new MotionEntry(*sampleEventTimes,
Jeff Brownb6997262010-10-08 22:31:17 -07002586 motionEvent->getDeviceId(), motionEvent->getSource(), policyFlags,
2587 action, motionEvent->getFlags(),
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002588 motionEvent->getMetaState(), motionEvent->getButtonState(),
2589 motionEvent->getEdgeFlags(),
Jeff Brownb6997262010-10-08 22:31:17 -07002590 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
Jeff Brown83d616a2012-09-09 20:33:43 -07002591 motionEvent->getDownTime(), displayId,
2592 uint32_t(pointerCount), pointerProperties, samplePointerCoords);
Jeff Brown3241b6b2012-02-03 15:08:02 -08002593 lastInjectedEntry = firstInjectedEntry;
Jeff Brownb6997262010-10-08 22:31:17 -07002594 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
2595 sampleEventTimes += 1;
2596 samplePointerCoords += pointerCount;
Jeff Brown3241b6b2012-02-03 15:08:02 -08002597 MotionEntry* nextInjectedEntry = new MotionEntry(*sampleEventTimes,
2598 motionEvent->getDeviceId(), motionEvent->getSource(), policyFlags,
2599 action, motionEvent->getFlags(),
2600 motionEvent->getMetaState(), motionEvent->getButtonState(),
2601 motionEvent->getEdgeFlags(),
2602 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
Jeff Brown83d616a2012-09-09 20:33:43 -07002603 motionEvent->getDownTime(), displayId,
2604 uint32_t(pointerCount), pointerProperties, samplePointerCoords);
Jeff Brown3241b6b2012-02-03 15:08:02 -08002605 lastInjectedEntry->next = nextInjectedEntry;
2606 lastInjectedEntry = nextInjectedEntry;
Jeff Brownb6997262010-10-08 22:31:17 -07002607 }
Jeff Brownb6997262010-10-08 22:31:17 -07002608 break;
2609 }
2610
2611 default:
Steve Block8564c8d2012-01-05 23:22:43 +00002612 ALOGW("Cannot inject event of type %d", event->getType());
Jeff Brownb6997262010-10-08 22:31:17 -07002613 return INPUT_EVENT_INJECTION_FAILED;
2614 }
2615
Jeff Brownac386072011-07-20 15:19:50 -07002616 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
Jeff Brownb6997262010-10-08 22:31:17 -07002617 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
2618 injectionState->injectionIsAsync = true;
2619 }
2620
2621 injectionState->refCount += 1;
Jeff Brown3241b6b2012-02-03 15:08:02 -08002622 lastInjectedEntry->injectionState = injectionState;
Jeff Brownb6997262010-10-08 22:31:17 -07002623
Jeff Brown3241b6b2012-02-03 15:08:02 -08002624 bool needWake = false;
2625 for (EventEntry* entry = firstInjectedEntry; entry != NULL; ) {
2626 EventEntry* nextEntry = entry->next;
2627 needWake |= enqueueInboundEventLocked(entry);
2628 entry = nextEntry;
2629 }
2630
Jeff Brownb6997262010-10-08 22:31:17 -07002631 mLock.unlock();
Jeff Brown7fbdc842010-06-17 20:52:56 -07002632
Jeff Brownb88102f2010-09-08 11:49:43 -07002633 if (needWake) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002634 mLooper->wake();
Jeff Brown7fbdc842010-06-17 20:52:56 -07002635 }
2636
2637 int32_t injectionResult;
2638 { // acquire lock
2639 AutoMutex _l(mLock);
2640
Jeff Brown6ec402b2010-07-28 15:48:59 -07002641 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
2642 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
2643 } else {
2644 for (;;) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002645 injectionResult = injectionState->injectionResult;
Jeff Brown6ec402b2010-07-28 15:48:59 -07002646 if (injectionResult != INPUT_EVENT_INJECTION_PENDING) {
2647 break;
2648 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07002649
Jeff Brown7fbdc842010-06-17 20:52:56 -07002650 nsecs_t remainingTimeout = endTime - now();
2651 if (remainingTimeout <= 0) {
Jeff Brown6ec402b2010-07-28 15:48:59 -07002652#if DEBUG_INJECTION
Steve Block5baa3a62011-12-20 16:23:08 +00002653 ALOGD("injectInputEvent - Timed out waiting for injection result "
Jeff Brown6ec402b2010-07-28 15:48:59 -07002654 "to become available.");
2655#endif
Jeff Brown7fbdc842010-06-17 20:52:56 -07002656 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
2657 break;
2658 }
2659
Jeff Brown6ec402b2010-07-28 15:48:59 -07002660 mInjectionResultAvailableCondition.waitRelative(mLock, remainingTimeout);
2661 }
2662
2663 if (injectionResult == INPUT_EVENT_INJECTION_SUCCEEDED
2664 && syncMode == INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002665 while (injectionState->pendingForegroundDispatches != 0) {
Jeff Brown6ec402b2010-07-28 15:48:59 -07002666#if DEBUG_INJECTION
Steve Block5baa3a62011-12-20 16:23:08 +00002667 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
Jeff Brown01ce2e92010-09-26 22:20:12 -07002668 injectionState->pendingForegroundDispatches);
Jeff Brown6ec402b2010-07-28 15:48:59 -07002669#endif
2670 nsecs_t remainingTimeout = endTime - now();
2671 if (remainingTimeout <= 0) {
2672#if DEBUG_INJECTION
Steve Block5baa3a62011-12-20 16:23:08 +00002673 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
Jeff Brown6ec402b2010-07-28 15:48:59 -07002674 "dispatches to finish.");
2675#endif
2676 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
2677 break;
2678 }
2679
2680 mInjectionSyncFinishedCondition.waitRelative(mLock, remainingTimeout);
2681 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07002682 }
2683 }
2684
Jeff Brownac386072011-07-20 15:19:50 -07002685 injectionState->release();
Jeff Brown7fbdc842010-06-17 20:52:56 -07002686 } // release lock
2687
Jeff Brown6ec402b2010-07-28 15:48:59 -07002688#if DEBUG_INJECTION
Steve Block5baa3a62011-12-20 16:23:08 +00002689 ALOGD("injectInputEvent - Finished with result %d. "
Jeff Brown6ec402b2010-07-28 15:48:59 -07002690 "injectorPid=%d, injectorUid=%d",
2691 injectionResult, injectorPid, injectorUid);
2692#endif
2693
Jeff Brown7fbdc842010-06-17 20:52:56 -07002694 return injectionResult;
2695}
2696
Jeff Brownb6997262010-10-08 22:31:17 -07002697bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
2698 return injectorUid == 0
2699 || mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
2700}
2701
Jeff Brown7fbdc842010-06-17 20:52:56 -07002702void InputDispatcher::setInjectionResultLocked(EventEntry* entry, int32_t injectionResult) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002703 InjectionState* injectionState = entry->injectionState;
2704 if (injectionState) {
Jeff Brown7fbdc842010-06-17 20:52:56 -07002705#if DEBUG_INJECTION
Steve Block5baa3a62011-12-20 16:23:08 +00002706 ALOGD("Setting input event injection result to %d. "
Jeff Brown7fbdc842010-06-17 20:52:56 -07002707 "injectorPid=%d, injectorUid=%d",
Jeff Brown01ce2e92010-09-26 22:20:12 -07002708 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
Jeff Brown7fbdc842010-06-17 20:52:56 -07002709#endif
2710
Jeff Brown0029c662011-03-30 02:25:18 -07002711 if (injectionState->injectionIsAsync
2712 && !(entry->policyFlags & POLICY_FLAG_FILTERED)) {
Jeff Brown6ec402b2010-07-28 15:48:59 -07002713 // Log the outcome since the injector did not wait for the injection result.
2714 switch (injectionResult) {
2715 case INPUT_EVENT_INJECTION_SUCCEEDED:
Steve Block71f2cf12011-10-20 11:56:00 +01002716 ALOGV("Asynchronous input event injection succeeded.");
Jeff Brown6ec402b2010-07-28 15:48:59 -07002717 break;
2718 case INPUT_EVENT_INJECTION_FAILED:
Steve Block8564c8d2012-01-05 23:22:43 +00002719 ALOGW("Asynchronous input event injection failed.");
Jeff Brown6ec402b2010-07-28 15:48:59 -07002720 break;
2721 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
Steve Block8564c8d2012-01-05 23:22:43 +00002722 ALOGW("Asynchronous input event injection permission denied.");
Jeff Brown6ec402b2010-07-28 15:48:59 -07002723 break;
2724 case INPUT_EVENT_INJECTION_TIMED_OUT:
Steve Block8564c8d2012-01-05 23:22:43 +00002725 ALOGW("Asynchronous input event injection timed out.");
Jeff Brown6ec402b2010-07-28 15:48:59 -07002726 break;
2727 }
2728 }
2729
Jeff Brown01ce2e92010-09-26 22:20:12 -07002730 injectionState->injectionResult = injectionResult;
Jeff Brown7fbdc842010-06-17 20:52:56 -07002731 mInjectionResultAvailableCondition.broadcast();
2732 }
2733}
2734
Jeff Brown01ce2e92010-09-26 22:20:12 -07002735void InputDispatcher::incrementPendingForegroundDispatchesLocked(EventEntry* entry) {
2736 InjectionState* injectionState = entry->injectionState;
2737 if (injectionState) {
2738 injectionState->pendingForegroundDispatches += 1;
2739 }
2740}
2741
Jeff Brown519e0242010-09-15 15:18:56 -07002742void InputDispatcher::decrementPendingForegroundDispatchesLocked(EventEntry* entry) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002743 InjectionState* injectionState = entry->injectionState;
2744 if (injectionState) {
2745 injectionState->pendingForegroundDispatches -= 1;
Jeff Brown6ec402b2010-07-28 15:48:59 -07002746
Jeff Brown01ce2e92010-09-26 22:20:12 -07002747 if (injectionState->pendingForegroundDispatches == 0) {
2748 mInjectionSyncFinishedCondition.broadcast();
2749 }
Jeff Brownb88102f2010-09-08 11:49:43 -07002750 }
2751}
2752
Jeff Brown9302c872011-07-13 22:51:29 -07002753sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
2754 const sp<InputChannel>& inputChannel) const {
2755 size_t numWindows = mWindowHandles.size();
2756 for (size_t i = 0; i < numWindows; i++) {
2757 const sp<InputWindowHandle>& windowHandle = mWindowHandles.itemAt(i);
Jeff Browncc4f7db2011-08-30 20:34:48 -07002758 if (windowHandle->getInputChannel() == inputChannel) {
Jeff Brown9302c872011-07-13 22:51:29 -07002759 return windowHandle;
Jeff Brown01ce2e92010-09-26 22:20:12 -07002760 }
2761 }
2762 return NULL;
2763}
2764
Jeff Brown9302c872011-07-13 22:51:29 -07002765bool InputDispatcher::hasWindowHandleLocked(
2766 const sp<InputWindowHandle>& windowHandle) const {
2767 size_t numWindows = mWindowHandles.size();
2768 for (size_t i = 0; i < numWindows; i++) {
2769 if (mWindowHandles.itemAt(i) == windowHandle) {
2770 return true;
2771 }
2772 }
2773 return false;
2774}
2775
2776void InputDispatcher::setInputWindows(const Vector<sp<InputWindowHandle> >& inputWindowHandles) {
Jeff Brownb88102f2010-09-08 11:49:43 -07002777#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002778 ALOGD("setInputWindows");
Jeff Brownb88102f2010-09-08 11:49:43 -07002779#endif
2780 { // acquire lock
2781 AutoMutex _l(mLock);
2782
Jeff Browncc4f7db2011-08-30 20:34:48 -07002783 Vector<sp<InputWindowHandle> > oldWindowHandles = mWindowHandles;
Jeff Brown9302c872011-07-13 22:51:29 -07002784 mWindowHandles = inputWindowHandles;
Jeff Brownb6997262010-10-08 22:31:17 -07002785
Jeff Brown9302c872011-07-13 22:51:29 -07002786 sp<InputWindowHandle> newFocusedWindowHandle;
2787 bool foundHoveredWindow = false;
2788 for (size_t i = 0; i < mWindowHandles.size(); i++) {
2789 const sp<InputWindowHandle>& windowHandle = mWindowHandles.itemAt(i);
Jeff Browncc4f7db2011-08-30 20:34:48 -07002790 if (!windowHandle->updateInfo() || windowHandle->getInputChannel() == NULL) {
Jeff Brown9302c872011-07-13 22:51:29 -07002791 mWindowHandles.removeAt(i--);
2792 continue;
2793 }
Jeff Browncc4f7db2011-08-30 20:34:48 -07002794 if (windowHandle->getInfo()->hasFocus) {
Jeff Brown9302c872011-07-13 22:51:29 -07002795 newFocusedWindowHandle = windowHandle;
2796 }
2797 if (windowHandle == mLastHoverWindowHandle) {
2798 foundHoveredWindow = true;
Jeff Brownb88102f2010-09-08 11:49:43 -07002799 }
2800 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07002801
Jeff Brown9302c872011-07-13 22:51:29 -07002802 if (!foundHoveredWindow) {
2803 mLastHoverWindowHandle = NULL;
2804 }
2805
2806 if (mFocusedWindowHandle != newFocusedWindowHandle) {
2807 if (mFocusedWindowHandle != NULL) {
Jeff Brownb6997262010-10-08 22:31:17 -07002808#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002809 ALOGD("Focus left window: %s",
Jeff Browncc4f7db2011-08-30 20:34:48 -07002810 mFocusedWindowHandle->getName().string());
Jeff Brownb6997262010-10-08 22:31:17 -07002811#endif
Jeff Browncc4f7db2011-08-30 20:34:48 -07002812 sp<InputChannel> focusedInputChannel = mFocusedWindowHandle->getInputChannel();
2813 if (focusedInputChannel != NULL) {
Christopher Tated9be36c2011-08-16 16:09:33 -07002814 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
2815 "focus left window");
2816 synthesizeCancelationEventsForInputChannelLocked(
Jeff Browncc4f7db2011-08-30 20:34:48 -07002817 focusedInputChannel, options);
Christopher Tated9be36c2011-08-16 16:09:33 -07002818 }
Jeff Brownb6997262010-10-08 22:31:17 -07002819 }
Jeff Brown9302c872011-07-13 22:51:29 -07002820 if (newFocusedWindowHandle != NULL) {
Jeff Brownb6997262010-10-08 22:31:17 -07002821#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002822 ALOGD("Focus entered window: %s",
Jeff Browncc4f7db2011-08-30 20:34:48 -07002823 newFocusedWindowHandle->getName().string());
Jeff Brownb6997262010-10-08 22:31:17 -07002824#endif
Jeff Brown9302c872011-07-13 22:51:29 -07002825 }
2826 mFocusedWindowHandle = newFocusedWindowHandle;
Jeff Brownb6997262010-10-08 22:31:17 -07002827 }
2828
Jeff Brown9302c872011-07-13 22:51:29 -07002829 for (size_t i = 0; i < mTouchState.windows.size(); i++) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002830 TouchedWindow& touchedWindow = mTouchState.windows.editItemAt(i);
Jeff Brown9302c872011-07-13 22:51:29 -07002831 if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
Jeff Brownb6997262010-10-08 22:31:17 -07002832#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002833 ALOGD("Touched window was removed: %s",
Jeff Browncc4f7db2011-08-30 20:34:48 -07002834 touchedWindow.windowHandle->getName().string());
Jeff Brownb6997262010-10-08 22:31:17 -07002835#endif
Jeff Browncc4f7db2011-08-30 20:34:48 -07002836 sp<InputChannel> touchedInputChannel =
2837 touchedWindow.windowHandle->getInputChannel();
2838 if (touchedInputChannel != NULL) {
Christopher Tated9be36c2011-08-16 16:09:33 -07002839 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
2840 "touched window was removed");
2841 synthesizeCancelationEventsForInputChannelLocked(
Jeff Browncc4f7db2011-08-30 20:34:48 -07002842 touchedInputChannel, options);
Christopher Tated9be36c2011-08-16 16:09:33 -07002843 }
Jeff Brown9302c872011-07-13 22:51:29 -07002844 mTouchState.windows.removeAt(i--);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002845 }
2846 }
Jeff Browncc4f7db2011-08-30 20:34:48 -07002847
2848 // Release information for windows that are no longer present.
2849 // This ensures that unused input channels are released promptly.
2850 // Otherwise, they might stick around until the window handle is destroyed
2851 // which might not happen until the next GC.
2852 for (size_t i = 0; i < oldWindowHandles.size(); i++) {
2853 const sp<InputWindowHandle>& oldWindowHandle = oldWindowHandles.itemAt(i);
2854 if (!hasWindowHandleLocked(oldWindowHandle)) {
2855#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002856 ALOGD("Window went away: %s", oldWindowHandle->getName().string());
Jeff Browncc4f7db2011-08-30 20:34:48 -07002857#endif
2858 oldWindowHandle->releaseInfo();
2859 }
2860 }
Jeff Brownb88102f2010-09-08 11:49:43 -07002861 } // release lock
2862
2863 // Wake up poll loop since it may need to make new input dispatching choices.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002864 mLooper->wake();
Jeff Brownb88102f2010-09-08 11:49:43 -07002865}
2866
Jeff Brown9302c872011-07-13 22:51:29 -07002867void InputDispatcher::setFocusedApplication(
2868 const sp<InputApplicationHandle>& inputApplicationHandle) {
Jeff Brownb88102f2010-09-08 11:49:43 -07002869#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002870 ALOGD("setFocusedApplication");
Jeff Brownb88102f2010-09-08 11:49:43 -07002871#endif
2872 { // acquire lock
2873 AutoMutex _l(mLock);
2874
Jeff Browncc4f7db2011-08-30 20:34:48 -07002875 if (inputApplicationHandle != NULL && inputApplicationHandle->updateInfo()) {
Jeff Brown5ea29ab2011-07-27 11:50:51 -07002876 if (mFocusedApplicationHandle != inputApplicationHandle) {
2877 if (mFocusedApplicationHandle != NULL) {
Jeff Browne9bb9be2012-02-06 15:47:55 -08002878 resetANRTimeoutsLocked();
Jeff Browncc4f7db2011-08-30 20:34:48 -07002879 mFocusedApplicationHandle->releaseInfo();
Jeff Brown5ea29ab2011-07-27 11:50:51 -07002880 }
2881 mFocusedApplicationHandle = inputApplicationHandle;
2882 }
2883 } else if (mFocusedApplicationHandle != NULL) {
Jeff Browne9bb9be2012-02-06 15:47:55 -08002884 resetANRTimeoutsLocked();
Jeff Browncc4f7db2011-08-30 20:34:48 -07002885 mFocusedApplicationHandle->releaseInfo();
Jeff Brown9302c872011-07-13 22:51:29 -07002886 mFocusedApplicationHandle.clear();
Jeff Brownb88102f2010-09-08 11:49:43 -07002887 }
2888
2889#if DEBUG_FOCUS
Jeff Brownb6997262010-10-08 22:31:17 -07002890 //logDispatchStateLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -07002891#endif
2892 } // release lock
2893
2894 // Wake up poll loop since it may need to make new input dispatching choices.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002895 mLooper->wake();
Jeff Brownb88102f2010-09-08 11:49:43 -07002896}
2897
Jeff Brownb88102f2010-09-08 11:49:43 -07002898void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
2899#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002900 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
Jeff Brownb88102f2010-09-08 11:49:43 -07002901#endif
2902
2903 bool changed;
2904 { // acquire lock
2905 AutoMutex _l(mLock);
2906
2907 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
Jeff Brown120a4592010-10-27 18:43:51 -07002908 if (mDispatchFrozen && !frozen) {
Jeff Brownb88102f2010-09-08 11:49:43 -07002909 resetANRTimeoutsLocked();
2910 }
2911
Jeff Brown120a4592010-10-27 18:43:51 -07002912 if (mDispatchEnabled && !enabled) {
2913 resetAndDropEverythingLocked("dispatcher is being disabled");
2914 }
2915
Jeff Brownb88102f2010-09-08 11:49:43 -07002916 mDispatchEnabled = enabled;
2917 mDispatchFrozen = frozen;
2918 changed = true;
2919 } else {
2920 changed = false;
2921 }
2922
2923#if DEBUG_FOCUS
Jeff Brownb6997262010-10-08 22:31:17 -07002924 //logDispatchStateLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -07002925#endif
2926 } // release lock
2927
2928 if (changed) {
2929 // Wake up poll loop since it may need to make new input dispatching choices.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002930 mLooper->wake();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002931 }
2932}
2933
Jeff Brown0029c662011-03-30 02:25:18 -07002934void InputDispatcher::setInputFilterEnabled(bool enabled) {
2935#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002936 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
Jeff Brown0029c662011-03-30 02:25:18 -07002937#endif
2938
2939 { // acquire lock
2940 AutoMutex _l(mLock);
2941
2942 if (mInputFilterEnabled == enabled) {
2943 return;
2944 }
2945
2946 mInputFilterEnabled = enabled;
2947 resetAndDropEverythingLocked("input filter is being enabled or disabled");
2948 } // release lock
2949
2950 // Wake up poll loop since there might be work to do to drop everything.
2951 mLooper->wake();
2952}
2953
Jeff Browne6504122010-09-27 14:52:15 -07002954bool InputDispatcher::transferTouchFocus(const sp<InputChannel>& fromChannel,
2955 const sp<InputChannel>& toChannel) {
2956#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002957 ALOGD("transferTouchFocus: fromChannel=%s, toChannel=%s",
Jeff Browne6504122010-09-27 14:52:15 -07002958 fromChannel->getName().string(), toChannel->getName().string());
2959#endif
2960 { // acquire lock
2961 AutoMutex _l(mLock);
2962
Jeff Brown9302c872011-07-13 22:51:29 -07002963 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromChannel);
2964 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toChannel);
2965 if (fromWindowHandle == NULL || toWindowHandle == NULL) {
Jeff Browne6504122010-09-27 14:52:15 -07002966#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002967 ALOGD("Cannot transfer focus because from or to window not found.");
Jeff Browne6504122010-09-27 14:52:15 -07002968#endif
2969 return false;
2970 }
Jeff Brown9302c872011-07-13 22:51:29 -07002971 if (fromWindowHandle == toWindowHandle) {
Jeff Browne6504122010-09-27 14:52:15 -07002972#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002973 ALOGD("Trivial transfer to same window.");
Jeff Browne6504122010-09-27 14:52:15 -07002974#endif
2975 return true;
2976 }
Jeff Brown83d616a2012-09-09 20:33:43 -07002977 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
2978#if DEBUG_FOCUS
2979 ALOGD("Cannot transfer focus because windows are on different displays.");
2980#endif
2981 return false;
2982 }
Jeff Browne6504122010-09-27 14:52:15 -07002983
2984 bool found = false;
2985 for (size_t i = 0; i < mTouchState.windows.size(); i++) {
2986 const TouchedWindow& touchedWindow = mTouchState.windows[i];
Jeff Brown9302c872011-07-13 22:51:29 -07002987 if (touchedWindow.windowHandle == fromWindowHandle) {
Jeff Browne6504122010-09-27 14:52:15 -07002988 int32_t oldTargetFlags = touchedWindow.targetFlags;
2989 BitSet32 pointerIds = touchedWindow.pointerIds;
2990
2991 mTouchState.windows.removeAt(i);
2992
Jeff Brown46e75292010-11-10 16:53:45 -08002993 int32_t newTargetFlags = oldTargetFlags
Jeff Browna032cc02011-03-07 16:56:21 -08002994 & (InputTarget::FLAG_FOREGROUND
2995 | InputTarget::FLAG_SPLIT | InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brown9302c872011-07-13 22:51:29 -07002996 mTouchState.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Jeff Browne6504122010-09-27 14:52:15 -07002997
2998 found = true;
2999 break;
3000 }
3001 }
3002
3003 if (! found) {
3004#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00003005 ALOGD("Focus transfer failed because from window did not have focus.");
Jeff Browne6504122010-09-27 14:52:15 -07003006#endif
3007 return false;
3008 }
3009
Jeff Brown9c9f1a32010-10-11 18:32:20 -07003010 ssize_t fromConnectionIndex = getConnectionIndexLocked(fromChannel);
3011 ssize_t toConnectionIndex = getConnectionIndexLocked(toChannel);
3012 if (fromConnectionIndex >= 0 && toConnectionIndex >= 0) {
Jeff Browncbee6d62012-02-03 20:11:27 -08003013 sp<Connection> fromConnection = mConnectionsByFd.valueAt(fromConnectionIndex);
3014 sp<Connection> toConnection = mConnectionsByFd.valueAt(toConnectionIndex);
Jeff Brown9c9f1a32010-10-11 18:32:20 -07003015
3016 fromConnection->inputState.copyPointerStateTo(toConnection->inputState);
Jeff Brownda3d5a92011-03-29 15:11:34 -07003017 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Jeff Brown9c9f1a32010-10-11 18:32:20 -07003018 "transferring touch focus from this window to another window");
Jeff Brownda3d5a92011-03-29 15:11:34 -07003019 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Jeff Brown9c9f1a32010-10-11 18:32:20 -07003020 }
3021
Jeff Browne6504122010-09-27 14:52:15 -07003022#if DEBUG_FOCUS
3023 logDispatchStateLocked();
3024#endif
3025 } // release lock
3026
3027 // Wake up poll loop since it may need to make new input dispatching choices.
3028 mLooper->wake();
3029 return true;
3030}
3031
Jeff Brown120a4592010-10-27 18:43:51 -07003032void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
3033#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00003034 ALOGD("Resetting and dropping all events (%s).", reason);
Jeff Brown120a4592010-10-27 18:43:51 -07003035#endif
3036
Jeff Brownda3d5a92011-03-29 15:11:34 -07003037 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
3038 synthesizeCancelationEventsForAllConnectionsLocked(options);
Jeff Brown120a4592010-10-27 18:43:51 -07003039
3040 resetKeyRepeatLocked();
3041 releasePendingEventLocked();
3042 drainInboundQueueLocked();
Jeff Browne9bb9be2012-02-06 15:47:55 -08003043 resetANRTimeoutsLocked();
Jeff Brown120a4592010-10-27 18:43:51 -07003044
3045 mTouchState.reset();
Jeff Brown9302c872011-07-13 22:51:29 -07003046 mLastHoverWindowHandle.clear();
Jeff Brown120a4592010-10-27 18:43:51 -07003047}
3048
Jeff Brownb88102f2010-09-08 11:49:43 -07003049void InputDispatcher::logDispatchStateLocked() {
3050 String8 dump;
3051 dumpDispatchStateLocked(dump);
Jeff Brown2a95c2a2010-09-16 12:31:46 -07003052
3053 char* text = dump.lockBuffer(dump.size());
3054 char* start = text;
3055 while (*start != '\0') {
3056 char* end = strchr(start, '\n');
3057 if (*end == '\n') {
3058 *(end++) = '\0';
3059 }
Steve Block5baa3a62011-12-20 16:23:08 +00003060 ALOGD("%s", start);
Jeff Brown2a95c2a2010-09-16 12:31:46 -07003061 start = end;
3062 }
Jeff Brownb88102f2010-09-08 11:49:43 -07003063}
3064
3065void InputDispatcher::dumpDispatchStateLocked(String8& dump) {
Jeff Brownf2f487182010-10-01 17:46:21 -07003066 dump.appendFormat(INDENT "DispatchEnabled: %d\n", mDispatchEnabled);
3067 dump.appendFormat(INDENT "DispatchFrozen: %d\n", mDispatchFrozen);
Jeff Brownb88102f2010-09-08 11:49:43 -07003068
Jeff Brown9302c872011-07-13 22:51:29 -07003069 if (mFocusedApplicationHandle != NULL) {
Jeff Brownf2f487182010-10-01 17:46:21 -07003070 dump.appendFormat(INDENT "FocusedApplication: name='%s', dispatchingTimeout=%0.3fms\n",
Jeff Browncc4f7db2011-08-30 20:34:48 -07003071 mFocusedApplicationHandle->getName().string(),
3072 mFocusedApplicationHandle->getDispatchingTimeout(
3073 DEFAULT_INPUT_DISPATCHING_TIMEOUT) / 1000000.0);
Jeff Brownb88102f2010-09-08 11:49:43 -07003074 } else {
Jeff Brownf2f487182010-10-01 17:46:21 -07003075 dump.append(INDENT "FocusedApplication: <null>\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003076 }
Jeff Brownf2f487182010-10-01 17:46:21 -07003077 dump.appendFormat(INDENT "FocusedWindow: name='%s'\n",
Jeff Browncc4f7db2011-08-30 20:34:48 -07003078 mFocusedWindowHandle != NULL ? mFocusedWindowHandle->getName().string() : "<null>");
Jeff Brownf2f487182010-10-01 17:46:21 -07003079
3080 dump.appendFormat(INDENT "TouchDown: %s\n", toString(mTouchState.down));
3081 dump.appendFormat(INDENT "TouchSplit: %s\n", toString(mTouchState.split));
Jeff Brown95712852011-01-04 19:41:59 -08003082 dump.appendFormat(INDENT "TouchDeviceId: %d\n", mTouchState.deviceId);
Jeff Brown58a2da82011-01-25 16:02:22 -08003083 dump.appendFormat(INDENT "TouchSource: 0x%08x\n", mTouchState.source);
Jeff Brown83d616a2012-09-09 20:33:43 -07003084 dump.appendFormat(INDENT "TouchDisplayId: %d\n", mTouchState.displayId);
Jeff Brownf2f487182010-10-01 17:46:21 -07003085 if (!mTouchState.windows.isEmpty()) {
3086 dump.append(INDENT "TouchedWindows:\n");
3087 for (size_t i = 0; i < mTouchState.windows.size(); i++) {
3088 const TouchedWindow& touchedWindow = mTouchState.windows[i];
3089 dump.appendFormat(INDENT2 "%d: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
Jeff Browncc4f7db2011-08-30 20:34:48 -07003090 i, touchedWindow.windowHandle->getName().string(),
3091 touchedWindow.pointerIds.value,
Jeff Brownf2f487182010-10-01 17:46:21 -07003092 touchedWindow.targetFlags);
3093 }
3094 } else {
3095 dump.append(INDENT "TouchedWindows: <none>\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003096 }
3097
Jeff Brown9302c872011-07-13 22:51:29 -07003098 if (!mWindowHandles.isEmpty()) {
Jeff Brownf2f487182010-10-01 17:46:21 -07003099 dump.append(INDENT "Windows:\n");
Jeff Brown9302c872011-07-13 22:51:29 -07003100 for (size_t i = 0; i < mWindowHandles.size(); i++) {
3101 const sp<InputWindowHandle>& windowHandle = mWindowHandles.itemAt(i);
Jeff Browncc4f7db2011-08-30 20:34:48 -07003102 const InputWindowInfo* windowInfo = windowHandle->getInfo();
3103
Jeff Brown83d616a2012-09-09 20:33:43 -07003104 dump.appendFormat(INDENT2 "%d: name='%s', displayId=%d, "
3105 "paused=%s, hasFocus=%s, hasWallpaper=%s, "
Jeff Brownf2f487182010-10-01 17:46:21 -07003106 "visible=%s, canReceiveKeys=%s, flags=0x%08x, type=0x%08x, layer=%d, "
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003107 "frame=[%d,%d][%d,%d], scale=%f, "
Jeff Brownfbf09772011-01-16 14:06:57 -08003108 "touchableRegion=",
Jeff Brown83d616a2012-09-09 20:33:43 -07003109 i, windowInfo->name.string(), windowInfo->displayId,
Jeff Browncc4f7db2011-08-30 20:34:48 -07003110 toString(windowInfo->paused),
3111 toString(windowInfo->hasFocus),
3112 toString(windowInfo->hasWallpaper),
3113 toString(windowInfo->visible),
3114 toString(windowInfo->canReceiveKeys),
3115 windowInfo->layoutParamsFlags, windowInfo->layoutParamsType,
3116 windowInfo->layer,
3117 windowInfo->frameLeft, windowInfo->frameTop,
3118 windowInfo->frameRight, windowInfo->frameBottom,
3119 windowInfo->scaleFactor);
3120 dumpRegion(dump, windowInfo->touchableRegion);
3121 dump.appendFormat(", inputFeatures=0x%08x", windowInfo->inputFeatures);
Jeff Brownfbf09772011-01-16 14:06:57 -08003122 dump.appendFormat(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%0.3fms\n",
Jeff Browncc4f7db2011-08-30 20:34:48 -07003123 windowInfo->ownerPid, windowInfo->ownerUid,
3124 windowInfo->dispatchingTimeout / 1000000.0);
Jeff Brownf2f487182010-10-01 17:46:21 -07003125 }
3126 } else {
3127 dump.append(INDENT "Windows: <none>\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003128 }
3129
Jeff Brownf2f487182010-10-01 17:46:21 -07003130 if (!mMonitoringChannels.isEmpty()) {
3131 dump.append(INDENT "MonitoringChannels:\n");
3132 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
3133 const sp<InputChannel>& channel = mMonitoringChannels[i];
3134 dump.appendFormat(INDENT2 "%d: '%s'\n", i, channel->getName().string());
3135 }
3136 } else {
3137 dump.append(INDENT "MonitoringChannels: <none>\n");
3138 }
Jeff Brown519e0242010-09-15 15:18:56 -07003139
Jeff Brown265f1cc2012-06-11 18:01:06 -07003140 nsecs_t currentTime = now();
3141
3142 if (!mInboundQueue.isEmpty()) {
3143 dump.appendFormat(INDENT "InboundQueue: length=%u\n", mInboundQueue.count());
3144 for (EventEntry* entry = mInboundQueue.head; entry; entry = entry->next) {
3145 dump.append(INDENT2);
3146 entry->appendDescription(dump);
Jeff Brown22aa5122012-06-17 12:01:06 -07003147 dump.appendFormat(", age=%0.1fms\n",
Jeff Brown265f1cc2012-06-11 18:01:06 -07003148 (currentTime - entry->eventTime) * 0.000001f);
3149 }
3150 } else {
3151 dump.append(INDENT "InboundQueue: <empty>\n");
3152 }
3153
3154 if (!mConnectionsByFd.isEmpty()) {
3155 dump.append(INDENT "Connections:\n");
3156 for (size_t i = 0; i < mConnectionsByFd.size(); i++) {
3157 const sp<Connection>& connection = mConnectionsByFd.valueAt(i);
3158 dump.appendFormat(INDENT2 "%d: channelName='%s', windowName='%s', "
3159 "status=%s, monitor=%s, inputPublisherBlocked=%s\n",
3160 i, connection->getInputChannelName(), connection->getWindowName(),
3161 connection->getStatusLabel(), toString(connection->monitor),
3162 toString(connection->inputPublisherBlocked));
3163
3164 if (!connection->outboundQueue.isEmpty()) {
3165 dump.appendFormat(INDENT3 "OutboundQueue: length=%u\n",
3166 connection->outboundQueue.count());
3167 for (DispatchEntry* entry = connection->outboundQueue.head; entry;
3168 entry = entry->next) {
3169 dump.append(INDENT4);
3170 entry->eventEntry->appendDescription(dump);
Jeff Brown22aa5122012-06-17 12:01:06 -07003171 dump.appendFormat(", targetFlags=0x%08x, resolvedAction=%d, age=%0.1fms\n",
Jeff Brown265f1cc2012-06-11 18:01:06 -07003172 entry->targetFlags, entry->resolvedAction,
3173 (currentTime - entry->eventEntry->eventTime) * 0.000001f);
3174 }
3175 } else {
3176 dump.append(INDENT3 "OutboundQueue: <empty>\n");
3177 }
3178
3179 if (!connection->waitQueue.isEmpty()) {
3180 dump.appendFormat(INDENT3 "WaitQueue: length=%u\n",
3181 connection->waitQueue.count());
3182 for (DispatchEntry* entry = connection->waitQueue.head; entry;
3183 entry = entry->next) {
3184 dump.append(INDENT4);
3185 entry->eventEntry->appendDescription(dump);
3186 dump.appendFormat(", targetFlags=0x%08x, resolvedAction=%d, "
Jeff Brown22aa5122012-06-17 12:01:06 -07003187 "age=%0.1fms, wait=%0.1fms\n",
Jeff Brown265f1cc2012-06-11 18:01:06 -07003188 entry->targetFlags, entry->resolvedAction,
3189 (currentTime - entry->eventEntry->eventTime) * 0.000001f,
3190 (currentTime - entry->deliveryTime) * 0.000001f);
3191 }
3192 } else {
3193 dump.append(INDENT3 "WaitQueue: <empty>\n");
3194 }
3195 }
3196 } else {
3197 dump.append(INDENT "Connections: <none>\n");
3198 }
Jeff Brownf2f487182010-10-01 17:46:21 -07003199
Jeff Brownb88102f2010-09-08 11:49:43 -07003200 if (isAppSwitchPendingLocked()) {
Jeff Brown22aa5122012-06-17 12:01:06 -07003201 dump.appendFormat(INDENT "AppSwitch: pending, due in %0.1fms\n",
Jeff Brownb88102f2010-09-08 11:49:43 -07003202 (mAppSwitchDueTime - now()) / 1000000.0);
3203 } else {
Jeff Brownf2f487182010-10-01 17:46:21 -07003204 dump.append(INDENT "AppSwitch: not pending\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003205 }
Jeff Brown22aa5122012-06-17 12:01:06 -07003206
3207 dump.append(INDENT "Configuration:\n");
3208 dump.appendFormat(INDENT2 "KeyRepeatDelay: %0.1fms\n",
3209 mConfig.keyRepeatDelay * 0.000001f);
3210 dump.appendFormat(INDENT2 "KeyRepeatTimeout: %0.1fms\n",
3211 mConfig.keyRepeatTimeout * 0.000001f);
Jeff Brownb88102f2010-09-08 11:49:43 -07003212}
3213
Jeff Brown928e0542011-01-10 11:17:36 -08003214status_t InputDispatcher::registerInputChannel(const sp<InputChannel>& inputChannel,
3215 const sp<InputWindowHandle>& inputWindowHandle, bool monitor) {
Jeff Brown9c3cda02010-06-15 01:31:58 -07003216#if DEBUG_REGISTRATION
Steve Block5baa3a62011-12-20 16:23:08 +00003217 ALOGD("channel '%s' ~ registerInputChannel - monitor=%s", inputChannel->getName().string(),
Jeff Brownb88102f2010-09-08 11:49:43 -07003218 toString(monitor));
Jeff Brown9c3cda02010-06-15 01:31:58 -07003219#endif
3220
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003221 { // acquire lock
3222 AutoMutex _l(mLock);
3223
Jeff Brown519e0242010-09-15 15:18:56 -07003224 if (getConnectionIndexLocked(inputChannel) >= 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00003225 ALOGW("Attempted to register already registered input channel '%s'",
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003226 inputChannel->getName().string());
3227 return BAD_VALUE;
3228 }
3229
Jeff Browncc4f7db2011-08-30 20:34:48 -07003230 sp<Connection> connection = new Connection(inputChannel, inputWindowHandle, monitor);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003231
Jeff Brown91e32892012-02-14 15:56:29 -08003232 int fd = inputChannel->getFd();
Jeff Browncbee6d62012-02-03 20:11:27 -08003233 mConnectionsByFd.add(fd, connection);
Jeff Brown9c3cda02010-06-15 01:31:58 -07003234
Jeff Brownb88102f2010-09-08 11:49:43 -07003235 if (monitor) {
3236 mMonitoringChannels.push(inputChannel);
3237 }
3238
Jeff Browncbee6d62012-02-03 20:11:27 -08003239 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
Jeff Brown2cbecea2010-08-17 15:59:26 -07003240
Jeff Brown9c3cda02010-06-15 01:31:58 -07003241 runCommandsLockedInterruptible();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003242 } // release lock
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003243 return OK;
3244}
3245
3246status_t InputDispatcher::unregisterInputChannel(const sp<InputChannel>& inputChannel) {
Jeff Brown9c3cda02010-06-15 01:31:58 -07003247#if DEBUG_REGISTRATION
Steve Block5baa3a62011-12-20 16:23:08 +00003248 ALOGD("channel '%s' ~ unregisterInputChannel", inputChannel->getName().string());
Jeff Brown9c3cda02010-06-15 01:31:58 -07003249#endif
3250
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003251 { // acquire lock
3252 AutoMutex _l(mLock);
3253
Jeff Browncc4f7db2011-08-30 20:34:48 -07003254 status_t status = unregisterInputChannelLocked(inputChannel, false /*notify*/);
3255 if (status) {
3256 return status;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003257 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003258 } // release lock
3259
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003260 // Wake the poll loop because removing the connection may have changed the current
3261 // synchronization state.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07003262 mLooper->wake();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003263 return OK;
3264}
3265
Jeff Browncc4f7db2011-08-30 20:34:48 -07003266status_t InputDispatcher::unregisterInputChannelLocked(const sp<InputChannel>& inputChannel,
3267 bool notify) {
3268 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
3269 if (connectionIndex < 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00003270 ALOGW("Attempted to unregister already unregistered input channel '%s'",
Jeff Browncc4f7db2011-08-30 20:34:48 -07003271 inputChannel->getName().string());
3272 return BAD_VALUE;
3273 }
3274
Jeff Browncbee6d62012-02-03 20:11:27 -08003275 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
3276 mConnectionsByFd.removeItemsAt(connectionIndex);
Jeff Browncc4f7db2011-08-30 20:34:48 -07003277
3278 if (connection->monitor) {
3279 removeMonitorChannelLocked(inputChannel);
3280 }
3281
Jeff Browncbee6d62012-02-03 20:11:27 -08003282 mLooper->removeFd(inputChannel->getFd());
Jeff Browncc4f7db2011-08-30 20:34:48 -07003283
3284 nsecs_t currentTime = now();
3285 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
3286
3287 runCommandsLockedInterruptible();
3288
3289 connection->status = Connection::STATUS_ZOMBIE;
3290 return OK;
3291}
3292
3293void InputDispatcher::removeMonitorChannelLocked(const sp<InputChannel>& inputChannel) {
3294 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
3295 if (mMonitoringChannels[i] == inputChannel) {
3296 mMonitoringChannels.removeAt(i);
3297 break;
3298 }
3299 }
3300}
3301
Jeff Brown519e0242010-09-15 15:18:56 -07003302ssize_t InputDispatcher::getConnectionIndexLocked(const sp<InputChannel>& inputChannel) {
Jeff Browncbee6d62012-02-03 20:11:27 -08003303 ssize_t connectionIndex = mConnectionsByFd.indexOfKey(inputChannel->getFd());
Jeff Brown2cbecea2010-08-17 15:59:26 -07003304 if (connectionIndex >= 0) {
Jeff Browncbee6d62012-02-03 20:11:27 -08003305 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
Jeff Brown2cbecea2010-08-17 15:59:26 -07003306 if (connection->inputChannel.get() == inputChannel.get()) {
3307 return connectionIndex;
3308 }
3309 }
3310
3311 return -1;
3312}
3313
Jeff Brown9c3cda02010-06-15 01:31:58 -07003314void InputDispatcher::onDispatchCycleFinishedLocked(
Jeff Brown072ec962012-02-07 14:46:57 -08003315 nsecs_t currentTime, const sp<Connection>& connection, uint32_t seq, bool handled) {
Jeff Brown3915bb82010-11-05 15:02:16 -07003316 CommandEntry* commandEntry = postCommandLocked(
3317 & InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
3318 commandEntry->connection = connection;
Jeff Brown265f1cc2012-06-11 18:01:06 -07003319 commandEntry->eventTime = currentTime;
Jeff Brown072ec962012-02-07 14:46:57 -08003320 commandEntry->seq = seq;
Jeff Brown3915bb82010-11-05 15:02:16 -07003321 commandEntry->handled = handled;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003322}
3323
Jeff Brown9c3cda02010-06-15 01:31:58 -07003324void InputDispatcher::onDispatchCycleBrokenLocked(
Jeff Brown7fbdc842010-06-17 20:52:56 -07003325 nsecs_t currentTime, const sp<Connection>& connection) {
Steve Block3762c312012-01-06 19:20:56 +00003326 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003327 connection->getInputChannelName());
3328
Jeff Brown9c3cda02010-06-15 01:31:58 -07003329 CommandEntry* commandEntry = postCommandLocked(
3330 & InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
Jeff Brown7fbdc842010-06-17 20:52:56 -07003331 commandEntry->connection = connection;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003332}
3333
Jeff Brown519e0242010-09-15 15:18:56 -07003334void InputDispatcher::onANRLocked(
Jeff Brown9302c872011-07-13 22:51:29 -07003335 nsecs_t currentTime, const sp<InputApplicationHandle>& applicationHandle,
3336 const sp<InputWindowHandle>& windowHandle,
Jeff Brown265f1cc2012-06-11 18:01:06 -07003337 nsecs_t eventTime, nsecs_t waitStartTime, const char* reason) {
Jeff Brown22aa5122012-06-17 12:01:06 -07003338 float dispatchLatency = (currentTime - eventTime) * 0.000001f;
3339 float waitDuration = (currentTime - waitStartTime) * 0.000001f;
Steve Block6215d3f2012-01-04 20:05:49 +00003340 ALOGI("Application is not responding: %s. "
Jeff Brown22aa5122012-06-17 12:01:06 -07003341 "It has been %0.1fms since event, %0.1fms since wait started. Reason: %s",
Jeff Brown9302c872011-07-13 22:51:29 -07003342 getApplicationWindowLabelLocked(applicationHandle, windowHandle).string(),
Jeff Brown22aa5122012-06-17 12:01:06 -07003343 dispatchLatency, waitDuration, reason);
3344
3345 // Capture a record of the InputDispatcher state at the time of the ANR.
3346 time_t t = time(NULL);
3347 struct tm tm;
3348 localtime_r(&t, &tm);
3349 char timestr[64];
3350 strftime(timestr, sizeof(timestr), "%F %T", &tm);
3351 mLastANRState.clear();
3352 mLastANRState.append(INDENT "ANR:\n");
3353 mLastANRState.appendFormat(INDENT2 "Time: %s\n", timestr);
3354 mLastANRState.appendFormat(INDENT2 "Window: %s\n",
3355 getApplicationWindowLabelLocked(applicationHandle, windowHandle).string());
3356 mLastANRState.appendFormat(INDENT2 "DispatchLatency: %0.1fms\n", dispatchLatency);
3357 mLastANRState.appendFormat(INDENT2 "WaitDuration: %0.1fms\n", waitDuration);
3358 mLastANRState.appendFormat(INDENT2 "Reason: %s\n", reason);
3359 dumpDispatchStateLocked(mLastANRState);
Jeff Brown519e0242010-09-15 15:18:56 -07003360
3361 CommandEntry* commandEntry = postCommandLocked(
3362 & InputDispatcher::doNotifyANRLockedInterruptible);
Jeff Brown9302c872011-07-13 22:51:29 -07003363 commandEntry->inputApplicationHandle = applicationHandle;
3364 commandEntry->inputWindowHandle = windowHandle;
Jeff Brown519e0242010-09-15 15:18:56 -07003365}
3366
Jeff Brownb88102f2010-09-08 11:49:43 -07003367void InputDispatcher::doNotifyConfigurationChangedInterruptible(
3368 CommandEntry* commandEntry) {
3369 mLock.unlock();
3370
3371 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
3372
3373 mLock.lock();
3374}
3375
Jeff Brown9c3cda02010-06-15 01:31:58 -07003376void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(
3377 CommandEntry* commandEntry) {
Jeff Brown7fbdc842010-06-17 20:52:56 -07003378 sp<Connection> connection = commandEntry->connection;
Jeff Brown9c3cda02010-06-15 01:31:58 -07003379
Jeff Brown7fbdc842010-06-17 20:52:56 -07003380 if (connection->status != Connection::STATUS_ZOMBIE) {
3381 mLock.unlock();
Jeff Brown9c3cda02010-06-15 01:31:58 -07003382
Jeff Brown928e0542011-01-10 11:17:36 -08003383 mPolicy->notifyInputChannelBroken(connection->inputWindowHandle);
Jeff Brown7fbdc842010-06-17 20:52:56 -07003384
3385 mLock.lock();
3386 }
Jeff Brown9c3cda02010-06-15 01:31:58 -07003387}
3388
Jeff Brown519e0242010-09-15 15:18:56 -07003389void InputDispatcher::doNotifyANRLockedInterruptible(
Jeff Brown9c3cda02010-06-15 01:31:58 -07003390 CommandEntry* commandEntry) {
Jeff Brown519e0242010-09-15 15:18:56 -07003391 mLock.unlock();
Jeff Brown9c3cda02010-06-15 01:31:58 -07003392
Jeff Brown519e0242010-09-15 15:18:56 -07003393 nsecs_t newTimeout = mPolicy->notifyANR(
Jeff Brown928e0542011-01-10 11:17:36 -08003394 commandEntry->inputApplicationHandle, commandEntry->inputWindowHandle);
Jeff Brown9c3cda02010-06-15 01:31:58 -07003395
Jeff Brown519e0242010-09-15 15:18:56 -07003396 mLock.lock();
Jeff Brown7fbdc842010-06-17 20:52:56 -07003397
Jeff Brown9302c872011-07-13 22:51:29 -07003398 resumeAfterTargetsNotReadyTimeoutLocked(newTimeout,
3399 commandEntry->inputWindowHandle != NULL
Jeff Browncc4f7db2011-08-30 20:34:48 -07003400 ? commandEntry->inputWindowHandle->getInputChannel() : NULL);
Jeff Brown9c3cda02010-06-15 01:31:58 -07003401}
3402
Jeff Brownb88102f2010-09-08 11:49:43 -07003403void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
3404 CommandEntry* commandEntry) {
3405 KeyEntry* entry = commandEntry->keyEntry;
Jeff Brown1f245102010-11-18 20:53:46 -08003406
3407 KeyEvent event;
3408 initializeKeyEvent(&event, entry);
Jeff Brownb88102f2010-09-08 11:49:43 -07003409
3410 mLock.unlock();
3411
Jeff Brown905805a2011-10-12 13:57:59 -07003412 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(commandEntry->inputWindowHandle,
Jeff Brown1f245102010-11-18 20:53:46 -08003413 &event, entry->policyFlags);
Jeff Brownb88102f2010-09-08 11:49:43 -07003414
3415 mLock.lock();
3416
Jeff Brown905805a2011-10-12 13:57:59 -07003417 if (delay < 0) {
3418 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
3419 } else if (!delay) {
3420 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
3421 } else {
3422 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
3423 entry->interceptKeyWakeupTime = now() + delay;
3424 }
Jeff Brownac386072011-07-20 15:19:50 -07003425 entry->release();
Jeff Brownb88102f2010-09-08 11:49:43 -07003426}
3427
Jeff Brown3915bb82010-11-05 15:02:16 -07003428void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(
3429 CommandEntry* commandEntry) {
3430 sp<Connection> connection = commandEntry->connection;
Jeff Brown265f1cc2012-06-11 18:01:06 -07003431 nsecs_t finishTime = commandEntry->eventTime;
Jeff Brown072ec962012-02-07 14:46:57 -08003432 uint32_t seq = commandEntry->seq;
Jeff Brown3915bb82010-11-05 15:02:16 -07003433 bool handled = commandEntry->handled;
3434
Jeff Brown072ec962012-02-07 14:46:57 -08003435 // Handle post-event policy actions.
3436 DispatchEntry* dispatchEntry = connection->findWaitQueueEntry(seq);
3437 if (dispatchEntry) {
Jeff Brown265f1cc2012-06-11 18:01:06 -07003438 nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
3439 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
3440 String8 msg;
Jeff Brown22aa5122012-06-17 12:01:06 -07003441 msg.appendFormat("Window '%s' spent %0.1fms processing the last input event: ",
Jeff Brown265f1cc2012-06-11 18:01:06 -07003442 connection->getWindowName(), eventDuration * 0.000001f);
3443 dispatchEntry->eventEntry->appendDescription(msg);
3444 ALOGI("%s", msg.string());
3445 }
3446
Jeff Brownd1c48a02012-02-06 19:12:47 -08003447 bool restartEvent;
Jeff Brownd1c48a02012-02-06 19:12:47 -08003448 if (dispatchEntry->eventEntry->type == EventEntry::TYPE_KEY) {
3449 KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry);
3450 restartEvent = afterKeyEventLockedInterruptible(connection,
3451 dispatchEntry, keyEntry, handled);
3452 } else if (dispatchEntry->eventEntry->type == EventEntry::TYPE_MOTION) {
3453 MotionEntry* motionEntry = static_cast<MotionEntry*>(dispatchEntry->eventEntry);
3454 restartEvent = afterMotionEventLockedInterruptible(connection,
3455 dispatchEntry, motionEntry, handled);
3456 } else {
3457 restartEvent = false;
3458 }
3459
3460 // Dequeue the event and start the next cycle.
3461 // Note that because the lock might have been released, it is possible that the
3462 // contents of the wait queue to have been drained, so we need to double-check
3463 // a few things.
Jeff Brown072ec962012-02-07 14:46:57 -08003464 if (dispatchEntry == connection->findWaitQueueEntry(seq)) {
3465 connection->waitQueue.dequeue(dispatchEntry);
Jeff Brown481c1572012-03-09 14:41:15 -08003466 traceWaitQueueLengthLocked(connection);
Jeff Brownd1c48a02012-02-06 19:12:47 -08003467 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
3468 connection->outboundQueue.enqueueAtHead(dispatchEntry);
Jeff Brown481c1572012-03-09 14:41:15 -08003469 traceOutboundQueueLengthLocked(connection);
Jeff Brownd1c48a02012-02-06 19:12:47 -08003470 } else {
3471 releaseDispatchEntryLocked(dispatchEntry);
Jeff Brown49ed71d2010-12-06 17:13:33 -08003472 }
Jeff Brown3915bb82010-11-05 15:02:16 -07003473 }
Jeff Brown3915bb82010-11-05 15:02:16 -07003474
Jeff Brownd1c48a02012-02-06 19:12:47 -08003475 // Start the next dispatch cycle for this connection.
3476 startDispatchCycleLocked(now(), connection);
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003477 }
3478}
3479
3480bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
3481 DispatchEntry* dispatchEntry, KeyEntry* keyEntry, bool handled) {
3482 if (!(keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK)) {
3483 // Get the fallback key state.
3484 // Clear it out after dispatching the UP.
3485 int32_t originalKeyCode = keyEntry->keyCode;
3486 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
3487 if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
3488 connection->inputState.removeFallbackKey(originalKeyCode);
3489 }
3490
3491 if (handled || !dispatchEntry->hasForegroundTarget()) {
3492 // If the application handles the original key for which we previously
3493 // generated a fallback or if the window is not a foreground window,
3494 // then cancel the associated fallback key, if any.
3495 if (fallbackKeyCode != -1) {
Jeff Brownfd23e3e2012-05-09 13:34:28 -07003496 // Dispatch the unhandled key to the policy with the cancel flag.
3497#if DEBUG_OUTBOUND_EVENT_DETAILS
3498 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
3499 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
3500 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
3501 keyEntry->policyFlags);
3502#endif
3503 KeyEvent event;
3504 initializeKeyEvent(&event, keyEntry);
3505 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
3506
3507 mLock.unlock();
3508
3509 mPolicy->dispatchUnhandledKey(connection->inputWindowHandle,
3510 &event, keyEntry->policyFlags, &event);
3511
3512 mLock.lock();
3513
3514 // Cancel the fallback key.
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003515 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
3516 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
3517 "application handled the original non-fallback key "
3518 "or is no longer a foreground target, "
3519 "canceling previously dispatched fallback key");
3520 options.keyCode = fallbackKeyCode;
3521 synthesizeCancelationEventsForConnectionLocked(connection, options);
3522 }
3523 connection->inputState.removeFallbackKey(originalKeyCode);
3524 }
3525 } else {
3526 // If the application did not handle a non-fallback key, first check
3527 // that we are in a good state to perform unhandled key event processing
3528 // Then ask the policy what to do with it.
3529 bool initialDown = keyEntry->action == AKEY_EVENT_ACTION_DOWN
3530 && keyEntry->repeatCount == 0;
3531 if (fallbackKeyCode == -1 && !initialDown) {
3532#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00003533 ALOGD("Unhandled key event: Skipping unhandled key event processing "
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003534 "since this is not an initial down. "
Jeff Brownfd23e3e2012-05-09 13:34:28 -07003535 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
3536 originalKeyCode, keyEntry->action, keyEntry->repeatCount,
3537 keyEntry->policyFlags);
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003538#endif
3539 return false;
3540 }
3541
3542 // Dispatch the unhandled key to the policy.
3543#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00003544 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
Jeff Brownfd23e3e2012-05-09 13:34:28 -07003545 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
3546 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
3547 keyEntry->policyFlags);
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003548#endif
3549 KeyEvent event;
3550 initializeKeyEvent(&event, keyEntry);
3551
3552 mLock.unlock();
3553
3554 bool fallback = mPolicy->dispatchUnhandledKey(connection->inputWindowHandle,
3555 &event, keyEntry->policyFlags, &event);
3556
3557 mLock.lock();
3558
3559 if (connection->status != Connection::STATUS_NORMAL) {
3560 connection->inputState.removeFallbackKey(originalKeyCode);
Jeff Brownd1c48a02012-02-06 19:12:47 -08003561 return false;
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003562 }
3563
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003564 // Latch the fallback keycode for this key on an initial down.
3565 // The fallback keycode cannot change at any other point in the lifecycle.
3566 if (initialDown) {
3567 if (fallback) {
3568 fallbackKeyCode = event.getKeyCode();
3569 } else {
3570 fallbackKeyCode = AKEYCODE_UNKNOWN;
3571 }
3572 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
3573 }
3574
Steve Blockec193de2012-01-09 18:35:44 +00003575 ALOG_ASSERT(fallbackKeyCode != -1);
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003576
3577 // Cancel the fallback key if the policy decides not to send it anymore.
3578 // We will continue to dispatch the key to the policy but we will no
3579 // longer dispatch a fallback key to the application.
3580 if (fallbackKeyCode != AKEYCODE_UNKNOWN
3581 && (!fallback || fallbackKeyCode != event.getKeyCode())) {
3582#if DEBUG_OUTBOUND_EVENT_DETAILS
3583 if (fallback) {
Steve Block5baa3a62011-12-20 16:23:08 +00003584 ALOGD("Unhandled key event: Policy requested to send key %d"
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003585 "as a fallback for %d, but on the DOWN it had requested "
3586 "to send %d instead. Fallback canceled.",
3587 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
3588 } else {
Jeff Brownfd23e3e2012-05-09 13:34:28 -07003589 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003590 "but on the DOWN it had requested to send %d. "
3591 "Fallback canceled.",
3592 originalKeyCode, fallbackKeyCode);
3593 }
3594#endif
3595
3596 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
3597 "canceling fallback, policy no longer desires it");
3598 options.keyCode = fallbackKeyCode;
3599 synthesizeCancelationEventsForConnectionLocked(connection, options);
3600
3601 fallback = false;
3602 fallbackKeyCode = AKEYCODE_UNKNOWN;
3603 if (keyEntry->action != AKEY_EVENT_ACTION_UP) {
3604 connection->inputState.setFallbackKey(originalKeyCode,
3605 fallbackKeyCode);
3606 }
3607 }
3608
3609#if DEBUG_OUTBOUND_EVENT_DETAILS
3610 {
3611 String8 msg;
3612 const KeyedVector<int32_t, int32_t>& fallbackKeys =
3613 connection->inputState.getFallbackKeys();
3614 for (size_t i = 0; i < fallbackKeys.size(); i++) {
3615 msg.appendFormat(", %d->%d", fallbackKeys.keyAt(i),
3616 fallbackKeys.valueAt(i));
3617 }
Steve Block5baa3a62011-12-20 16:23:08 +00003618 ALOGD("Unhandled key event: %d currently tracked fallback keys%s.",
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003619 fallbackKeys.size(), msg.string());
3620 }
3621#endif
3622
3623 if (fallback) {
3624 // Restart the dispatch cycle using the fallback key.
3625 keyEntry->eventTime = event.getEventTime();
3626 keyEntry->deviceId = event.getDeviceId();
3627 keyEntry->source = event.getSource();
3628 keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
3629 keyEntry->keyCode = fallbackKeyCode;
3630 keyEntry->scanCode = event.getScanCode();
3631 keyEntry->metaState = event.getMetaState();
3632 keyEntry->repeatCount = event.getRepeatCount();
3633 keyEntry->downTime = event.getDownTime();
3634 keyEntry->syntheticRepeat = false;
3635
3636#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00003637 ALOGD("Unhandled key event: Dispatching fallback key. "
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003638 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
3639 originalKeyCode, fallbackKeyCode, keyEntry->metaState);
3640#endif
Jeff Brownd1c48a02012-02-06 19:12:47 -08003641 return true; // restart the event
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003642 } else {
3643#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00003644 ALOGD("Unhandled key event: No fallback key.");
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003645#endif
3646 }
3647 }
3648 }
3649 return false;
3650}
3651
3652bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
3653 DispatchEntry* dispatchEntry, MotionEntry* motionEntry, bool handled) {
3654 return false;
Jeff Brown3915bb82010-11-05 15:02:16 -07003655}
3656
Jeff Brownb88102f2010-09-08 11:49:43 -07003657void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
3658 mLock.unlock();
3659
Jeff Brown01ce2e92010-09-26 22:20:12 -07003660 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
Jeff Brownb88102f2010-09-08 11:49:43 -07003661
3662 mLock.lock();
3663}
3664
Jeff Brown3915bb82010-11-05 15:02:16 -07003665void InputDispatcher::initializeKeyEvent(KeyEvent* event, const KeyEntry* entry) {
3666 event->initialize(entry->deviceId, entry->source, entry->action, entry->flags,
3667 entry->keyCode, entry->scanCode, entry->metaState, entry->repeatCount,
3668 entry->downTime, entry->eventTime);
3669}
3670
Jeff Brown519e0242010-09-15 15:18:56 -07003671void InputDispatcher::updateDispatchStatisticsLocked(nsecs_t currentTime, const EventEntry* entry,
3672 int32_t injectionResult, nsecs_t timeSpentWaitingForApplication) {
3673 // TODO Write some statistics about how long we spend waiting.
Jeff Brownb88102f2010-09-08 11:49:43 -07003674}
3675
Jeff Brown481c1572012-03-09 14:41:15 -08003676void InputDispatcher::traceInboundQueueLengthLocked() {
3677 if (ATRACE_ENABLED()) {
3678 ATRACE_INT("iq", mInboundQueue.count());
3679 }
3680}
3681
3682void InputDispatcher::traceOutboundQueueLengthLocked(const sp<Connection>& connection) {
3683 if (ATRACE_ENABLED()) {
3684 char counterName[40];
3685 snprintf(counterName, sizeof(counterName), "oq:%s", connection->getWindowName());
3686 ATRACE_INT(counterName, connection->outboundQueue.count());
3687 }
3688}
3689
3690void InputDispatcher::traceWaitQueueLengthLocked(const sp<Connection>& connection) {
3691 if (ATRACE_ENABLED()) {
3692 char counterName[40];
3693 snprintf(counterName, sizeof(counterName), "wq:%s", connection->getWindowName());
3694 ATRACE_INT(counterName, connection->waitQueue.count());
3695 }
3696}
3697
Jeff Brownb88102f2010-09-08 11:49:43 -07003698void InputDispatcher::dump(String8& dump) {
Jeff Brown89ef0722011-08-10 16:25:21 -07003699 AutoMutex _l(mLock);
3700
Jeff Brownf2f487182010-10-01 17:46:21 -07003701 dump.append("Input Dispatcher State:\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003702 dumpDispatchStateLocked(dump);
Jeff Brown214eaf42011-05-26 19:17:02 -07003703
Jeff Brown22aa5122012-06-17 12:01:06 -07003704 if (!mLastANRState.isEmpty()) {
3705 dump.append("\nInput Dispatcher State at time of last ANR:\n");
3706 dump.append(mLastANRState);
3707 }
Jeff Brownb88102f2010-09-08 11:49:43 -07003708}
3709
Jeff Brown89ef0722011-08-10 16:25:21 -07003710void InputDispatcher::monitor() {
3711 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
3712 mLock.lock();
Jeff Brown112b5f52012-01-27 17:32:06 -08003713 mLooper->wake();
3714 mDispatcherIsAliveCondition.wait(mLock);
Jeff Brown89ef0722011-08-10 16:25:21 -07003715 mLock.unlock();
3716}
3717
Jeff Brown9c3cda02010-06-15 01:31:58 -07003718
Jeff Brown519e0242010-09-15 15:18:56 -07003719// --- InputDispatcher::Queue ---
3720
3721template <typename T>
3722uint32_t InputDispatcher::Queue<T>::count() const {
3723 uint32_t result = 0;
Jeff Brownac386072011-07-20 15:19:50 -07003724 for (const T* entry = head; entry; entry = entry->next) {
Jeff Brown519e0242010-09-15 15:18:56 -07003725 result += 1;
3726 }
3727 return result;
3728}
3729
3730
Jeff Brownac386072011-07-20 15:19:50 -07003731// --- InputDispatcher::InjectionState ---
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003732
Jeff Brownac386072011-07-20 15:19:50 -07003733InputDispatcher::InjectionState::InjectionState(int32_t injectorPid, int32_t injectorUid) :
3734 refCount(1),
3735 injectorPid(injectorPid), injectorUid(injectorUid),
3736 injectionResult(INPUT_EVENT_INJECTION_PENDING), injectionIsAsync(false),
3737 pendingForegroundDispatches(0) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003738}
3739
Jeff Brownac386072011-07-20 15:19:50 -07003740InputDispatcher::InjectionState::~InjectionState() {
Jeff Brown01ce2e92010-09-26 22:20:12 -07003741}
3742
Jeff Brownac386072011-07-20 15:19:50 -07003743void InputDispatcher::InjectionState::release() {
3744 refCount -= 1;
3745 if (refCount == 0) {
3746 delete this;
3747 } else {
Steve Blockec193de2012-01-09 18:35:44 +00003748 ALOG_ASSERT(refCount > 0);
Jeff Brown01ce2e92010-09-26 22:20:12 -07003749 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07003750}
3751
Jeff Brownac386072011-07-20 15:19:50 -07003752
3753// --- InputDispatcher::EventEntry ---
3754
3755InputDispatcher::EventEntry::EventEntry(int32_t type, nsecs_t eventTime, uint32_t policyFlags) :
3756 refCount(1), type(type), eventTime(eventTime), policyFlags(policyFlags),
3757 injectionState(NULL), dispatchInProgress(false) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003758}
3759
Jeff Brownac386072011-07-20 15:19:50 -07003760InputDispatcher::EventEntry::~EventEntry() {
3761 releaseInjectionState();
3762}
3763
3764void InputDispatcher::EventEntry::release() {
3765 refCount -= 1;
3766 if (refCount == 0) {
3767 delete this;
3768 } else {
Steve Blockec193de2012-01-09 18:35:44 +00003769 ALOG_ASSERT(refCount > 0);
Jeff Brownac386072011-07-20 15:19:50 -07003770 }
3771}
3772
3773void InputDispatcher::EventEntry::releaseInjectionState() {
3774 if (injectionState) {
3775 injectionState->release();
3776 injectionState = NULL;
3777 }
3778}
3779
3780
3781// --- InputDispatcher::ConfigurationChangedEntry ---
3782
3783InputDispatcher::ConfigurationChangedEntry::ConfigurationChangedEntry(nsecs_t eventTime) :
3784 EventEntry(TYPE_CONFIGURATION_CHANGED, eventTime, 0) {
3785}
3786
3787InputDispatcher::ConfigurationChangedEntry::~ConfigurationChangedEntry() {
3788}
3789
Jeff Brown265f1cc2012-06-11 18:01:06 -07003790void InputDispatcher::ConfigurationChangedEntry::appendDescription(String8& msg) const {
3791 msg.append("ConfigurationChangedEvent()");
3792}
3793
Jeff Brownac386072011-07-20 15:19:50 -07003794
Jeff Brown65fd2512011-08-18 11:20:58 -07003795// --- InputDispatcher::DeviceResetEntry ---
3796
3797InputDispatcher::DeviceResetEntry::DeviceResetEntry(nsecs_t eventTime, int32_t deviceId) :
3798 EventEntry(TYPE_DEVICE_RESET, eventTime, 0),
3799 deviceId(deviceId) {
3800}
3801
3802InputDispatcher::DeviceResetEntry::~DeviceResetEntry() {
3803}
3804
Jeff Brown265f1cc2012-06-11 18:01:06 -07003805void InputDispatcher::DeviceResetEntry::appendDescription(String8& msg) const {
3806 msg.appendFormat("DeviceResetEvent(deviceId=%d)", deviceId);
3807}
3808
Jeff Brown65fd2512011-08-18 11:20:58 -07003809
Jeff Brownac386072011-07-20 15:19:50 -07003810// --- InputDispatcher::KeyEntry ---
3811
3812InputDispatcher::KeyEntry::KeyEntry(nsecs_t eventTime,
Jeff Brown58a2da82011-01-25 16:02:22 -08003813 int32_t deviceId, uint32_t source, uint32_t policyFlags, int32_t action,
Jeff Brown7fbdc842010-06-17 20:52:56 -07003814 int32_t flags, int32_t keyCode, int32_t scanCode, int32_t metaState,
Jeff Brownac386072011-07-20 15:19:50 -07003815 int32_t repeatCount, nsecs_t downTime) :
3816 EventEntry(TYPE_KEY, eventTime, policyFlags),
3817 deviceId(deviceId), source(source), action(action), flags(flags),
3818 keyCode(keyCode), scanCode(scanCode), metaState(metaState),
3819 repeatCount(repeatCount), downTime(downTime),
Jeff Brown905805a2011-10-12 13:57:59 -07003820 syntheticRepeat(false), interceptKeyResult(KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN),
3821 interceptKeyWakeupTime(0) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003822}
3823
Jeff Brownac386072011-07-20 15:19:50 -07003824InputDispatcher::KeyEntry::~KeyEntry() {
3825}
Jeff Brown7fbdc842010-06-17 20:52:56 -07003826
Jeff Brown265f1cc2012-06-11 18:01:06 -07003827void InputDispatcher::KeyEntry::appendDescription(String8& msg) const {
3828 msg.appendFormat("KeyEvent(action=%d, deviceId=%d, source=0x%08x)",
3829 action, deviceId, source);
3830}
3831
Jeff Brownac386072011-07-20 15:19:50 -07003832void InputDispatcher::KeyEntry::recycle() {
3833 releaseInjectionState();
3834
3835 dispatchInProgress = false;
3836 syntheticRepeat = false;
3837 interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
Jeff Brown905805a2011-10-12 13:57:59 -07003838 interceptKeyWakeupTime = 0;
Jeff Brownac386072011-07-20 15:19:50 -07003839}
3840
3841
Jeff Brownae9fc032010-08-18 15:51:08 -07003842// --- InputDispatcher::MotionEntry ---
3843
Jeff Brownac386072011-07-20 15:19:50 -07003844InputDispatcher::MotionEntry::MotionEntry(nsecs_t eventTime,
3845 int32_t deviceId, uint32_t source, uint32_t policyFlags, int32_t action, int32_t flags,
3846 int32_t metaState, int32_t buttonState,
3847 int32_t edgeFlags, float xPrecision, float yPrecision,
Jeff Brown83d616a2012-09-09 20:33:43 -07003848 nsecs_t downTime, int32_t displayId, uint32_t pointerCount,
Jeff Brownac386072011-07-20 15:19:50 -07003849 const PointerProperties* pointerProperties, const PointerCoords* pointerCoords) :
3850 EventEntry(TYPE_MOTION, eventTime, policyFlags),
Jeff Brown3241b6b2012-02-03 15:08:02 -08003851 eventTime(eventTime),
Jeff Brownac386072011-07-20 15:19:50 -07003852 deviceId(deviceId), source(source), action(action), flags(flags),
3853 metaState(metaState), buttonState(buttonState), edgeFlags(edgeFlags),
3854 xPrecision(xPrecision), yPrecision(yPrecision),
Jeff Brown83d616a2012-09-09 20:33:43 -07003855 downTime(downTime), displayId(displayId), pointerCount(pointerCount) {
Jeff Brownac386072011-07-20 15:19:50 -07003856 for (uint32_t i = 0; i < pointerCount; i++) {
3857 this->pointerProperties[i].copyFrom(pointerProperties[i]);
Jeff Brown3241b6b2012-02-03 15:08:02 -08003858 this->pointerCoords[i].copyFrom(pointerCoords[i]);
Jeff Brownac386072011-07-20 15:19:50 -07003859 }
3860}
3861
3862InputDispatcher::MotionEntry::~MotionEntry() {
Jeff Brownac386072011-07-20 15:19:50 -07003863}
3864
Jeff Brown265f1cc2012-06-11 18:01:06 -07003865void InputDispatcher::MotionEntry::appendDescription(String8& msg) const {
Jeff Brown83d616a2012-09-09 20:33:43 -07003866 msg.appendFormat("MotionEvent(action=%d, deviceId=%d, source=0x%08x, displayId=%d)",
3867 action, deviceId, source, displayId);
Jeff Brown265f1cc2012-06-11 18:01:06 -07003868}
3869
Jeff Brownac386072011-07-20 15:19:50 -07003870
3871// --- InputDispatcher::DispatchEntry ---
3872
Jeff Brown072ec962012-02-07 14:46:57 -08003873volatile int32_t InputDispatcher::DispatchEntry::sNextSeqAtomic;
3874
Jeff Brownac386072011-07-20 15:19:50 -07003875InputDispatcher::DispatchEntry::DispatchEntry(EventEntry* eventEntry,
3876 int32_t targetFlags, float xOffset, float yOffset, float scaleFactor) :
Jeff Brown072ec962012-02-07 14:46:57 -08003877 seq(nextSeq()),
Jeff Brownac386072011-07-20 15:19:50 -07003878 eventEntry(eventEntry), targetFlags(targetFlags),
3879 xOffset(xOffset), yOffset(yOffset), scaleFactor(scaleFactor),
Jeff Brown265f1cc2012-06-11 18:01:06 -07003880 deliveryTime(0), resolvedAction(0), resolvedFlags(0) {
Jeff Brownac386072011-07-20 15:19:50 -07003881 eventEntry->refCount += 1;
3882}
3883
3884InputDispatcher::DispatchEntry::~DispatchEntry() {
3885 eventEntry->release();
3886}
3887
Jeff Brown072ec962012-02-07 14:46:57 -08003888uint32_t InputDispatcher::DispatchEntry::nextSeq() {
3889 // Sequence number 0 is reserved and will never be returned.
3890 uint32_t seq;
3891 do {
3892 seq = android_atomic_inc(&sNextSeqAtomic);
3893 } while (!seq);
3894 return seq;
3895}
3896
Jeff Brownb88102f2010-09-08 11:49:43 -07003897
3898// --- InputDispatcher::InputState ---
3899
Jeff Brownb6997262010-10-08 22:31:17 -07003900InputDispatcher::InputState::InputState() {
Jeff Brownb88102f2010-09-08 11:49:43 -07003901}
3902
3903InputDispatcher::InputState::~InputState() {
3904}
3905
3906bool InputDispatcher::InputState::isNeutral() const {
3907 return mKeyMementos.isEmpty() && mMotionMementos.isEmpty();
3908}
3909
Jeff Brown83d616a2012-09-09 20:33:43 -07003910bool InputDispatcher::InputState::isHovering(int32_t deviceId, uint32_t source,
3911 int32_t displayId) const {
Jeff Brown81346812011-06-28 20:08:48 -07003912 for (size_t i = 0; i < mMotionMementos.size(); i++) {
3913 const MotionMemento& memento = mMotionMementos.itemAt(i);
3914 if (memento.deviceId == deviceId
3915 && memento.source == source
Jeff Brown83d616a2012-09-09 20:33:43 -07003916 && memento.displayId == displayId
Jeff Brown81346812011-06-28 20:08:48 -07003917 && memento.hovering) {
3918 return true;
3919 }
3920 }
3921 return false;
3922}
Jeff Brownb88102f2010-09-08 11:49:43 -07003923
Jeff Brown81346812011-06-28 20:08:48 -07003924bool InputDispatcher::InputState::trackKey(const KeyEntry* entry,
3925 int32_t action, int32_t flags) {
3926 switch (action) {
3927 case AKEY_EVENT_ACTION_UP: {
3928 if (entry->flags & AKEY_EVENT_FLAG_FALLBACK) {
3929 for (size_t i = 0; i < mFallbackKeys.size(); ) {
3930 if (mFallbackKeys.valueAt(i) == entry->keyCode) {
3931 mFallbackKeys.removeItemsAt(i);
3932 } else {
3933 i += 1;
3934 }
3935 }
3936 }
3937 ssize_t index = findKeyMemento(entry);
3938 if (index >= 0) {
3939 mKeyMementos.removeAt(index);
3940 return true;
3941 }
Jeff Brown68b909d2011-12-07 16:36:01 -08003942 /* FIXME: We can't just drop the key up event because that prevents creating
3943 * popup windows that are automatically shown when a key is held and then
3944 * dismissed when the key is released. The problem is that the popup will
3945 * not have received the original key down, so the key up will be considered
3946 * to be inconsistent with its observed state. We could perhaps handle this
3947 * by synthesizing a key down but that will cause other problems.
3948 *
3949 * So for now, allow inconsistent key up events to be dispatched.
3950 *
Jeff Brown81346812011-06-28 20:08:48 -07003951#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00003952 ALOGD("Dropping inconsistent key up event: deviceId=%d, source=%08x, "
Jeff Brown81346812011-06-28 20:08:48 -07003953 "keyCode=%d, scanCode=%d",
3954 entry->deviceId, entry->source, entry->keyCode, entry->scanCode);
3955#endif
3956 return false;
Jeff Brown68b909d2011-12-07 16:36:01 -08003957 */
3958 return true;
Jeff Brown81346812011-06-28 20:08:48 -07003959 }
3960
3961 case AKEY_EVENT_ACTION_DOWN: {
3962 ssize_t index = findKeyMemento(entry);
3963 if (index >= 0) {
3964 mKeyMementos.removeAt(index);
3965 }
3966 addKeyMemento(entry, flags);
3967 return true;
3968 }
3969
3970 default:
3971 return true;
Jeff Brownb88102f2010-09-08 11:49:43 -07003972 }
3973}
3974
Jeff Brown81346812011-06-28 20:08:48 -07003975bool InputDispatcher::InputState::trackMotion(const MotionEntry* entry,
3976 int32_t action, int32_t flags) {
3977 int32_t actionMasked = action & AMOTION_EVENT_ACTION_MASK;
3978 switch (actionMasked) {
3979 case AMOTION_EVENT_ACTION_UP:
3980 case AMOTION_EVENT_ACTION_CANCEL: {
3981 ssize_t index = findMotionMemento(entry, false /*hovering*/);
3982 if (index >= 0) {
3983 mMotionMementos.removeAt(index);
3984 return true;
Jeff Brownda3d5a92011-03-29 15:11:34 -07003985 }
Jeff Brown81346812011-06-28 20:08:48 -07003986#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00003987 ALOGD("Dropping inconsistent motion up or cancel event: deviceId=%d, source=%08x, "
Jeff Brown81346812011-06-28 20:08:48 -07003988 "actionMasked=%d",
3989 entry->deviceId, entry->source, actionMasked);
3990#endif
3991 return false;
Jeff Brownda3d5a92011-03-29 15:11:34 -07003992 }
3993
Jeff Brown81346812011-06-28 20:08:48 -07003994 case AMOTION_EVENT_ACTION_DOWN: {
3995 ssize_t index = findMotionMemento(entry, false /*hovering*/);
3996 if (index >= 0) {
3997 mMotionMementos.removeAt(index);
3998 }
3999 addMotionMemento(entry, flags, false /*hovering*/);
4000 return true;
4001 }
4002
4003 case AMOTION_EVENT_ACTION_POINTER_UP:
4004 case AMOTION_EVENT_ACTION_POINTER_DOWN:
4005 case AMOTION_EVENT_ACTION_MOVE: {
4006 ssize_t index = findMotionMemento(entry, false /*hovering*/);
4007 if (index >= 0) {
4008 MotionMemento& memento = mMotionMementos.editItemAt(index);
4009 memento.setPointers(entry);
4010 return true;
4011 }
Jeff Brown2e45fb62011-06-29 21:19:05 -07004012 if (actionMasked == AMOTION_EVENT_ACTION_MOVE
4013 && (entry->source & (AINPUT_SOURCE_CLASS_JOYSTICK
4014 | AINPUT_SOURCE_CLASS_NAVIGATION))) {
4015 // Joysticks and trackballs can send MOVE events without corresponding DOWN or UP.
4016 return true;
4017 }
Jeff Brown81346812011-06-28 20:08:48 -07004018#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00004019 ALOGD("Dropping inconsistent motion pointer up/down or move event: "
Jeff Brown81346812011-06-28 20:08:48 -07004020 "deviceId=%d, source=%08x, actionMasked=%d",
4021 entry->deviceId, entry->source, actionMasked);
4022#endif
4023 return false;
4024 }
4025
4026 case AMOTION_EVENT_ACTION_HOVER_EXIT: {
4027 ssize_t index = findMotionMemento(entry, true /*hovering*/);
4028 if (index >= 0) {
4029 mMotionMementos.removeAt(index);
4030 return true;
4031 }
4032#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00004033 ALOGD("Dropping inconsistent motion hover exit event: deviceId=%d, source=%08x",
Jeff Brown81346812011-06-28 20:08:48 -07004034 entry->deviceId, entry->source);
4035#endif
4036 return false;
4037 }
4038
4039 case AMOTION_EVENT_ACTION_HOVER_ENTER:
4040 case AMOTION_EVENT_ACTION_HOVER_MOVE: {
4041 ssize_t index = findMotionMemento(entry, true /*hovering*/);
4042 if (index >= 0) {
4043 mMotionMementos.removeAt(index);
4044 }
4045 addMotionMemento(entry, flags, true /*hovering*/);
4046 return true;
4047 }
4048
4049 default:
4050 return true;
4051 }
4052}
4053
4054ssize_t InputDispatcher::InputState::findKeyMemento(const KeyEntry* entry) const {
Jeff Brownb88102f2010-09-08 11:49:43 -07004055 for (size_t i = 0; i < mKeyMementos.size(); i++) {
Jeff Brown81346812011-06-28 20:08:48 -07004056 const KeyMemento& memento = mKeyMementos.itemAt(i);
Jeff Brownb88102f2010-09-08 11:49:43 -07004057 if (memento.deviceId == entry->deviceId
4058 && memento.source == entry->source
4059 && memento.keyCode == entry->keyCode
4060 && memento.scanCode == entry->scanCode) {
Jeff Brown81346812011-06-28 20:08:48 -07004061 return i;
Jeff Brownb88102f2010-09-08 11:49:43 -07004062 }
4063 }
Jeff Brown81346812011-06-28 20:08:48 -07004064 return -1;
Jeff Brownb88102f2010-09-08 11:49:43 -07004065}
4066
Jeff Brown81346812011-06-28 20:08:48 -07004067ssize_t InputDispatcher::InputState::findMotionMemento(const MotionEntry* entry,
4068 bool hovering) const {
Jeff Brownb88102f2010-09-08 11:49:43 -07004069 for (size_t i = 0; i < mMotionMementos.size(); i++) {
Jeff Brown81346812011-06-28 20:08:48 -07004070 const MotionMemento& memento = mMotionMementos.itemAt(i);
Jeff Brownb88102f2010-09-08 11:49:43 -07004071 if (memento.deviceId == entry->deviceId
Jeff Brown81346812011-06-28 20:08:48 -07004072 && memento.source == entry->source
Jeff Brown83d616a2012-09-09 20:33:43 -07004073 && memento.displayId == entry->displayId
Jeff Brown81346812011-06-28 20:08:48 -07004074 && memento.hovering == hovering) {
4075 return i;
Jeff Brownb88102f2010-09-08 11:49:43 -07004076 }
4077 }
Jeff Brown81346812011-06-28 20:08:48 -07004078 return -1;
4079}
Jeff Brownb88102f2010-09-08 11:49:43 -07004080
Jeff Brown81346812011-06-28 20:08:48 -07004081void InputDispatcher::InputState::addKeyMemento(const KeyEntry* entry, int32_t flags) {
4082 mKeyMementos.push();
4083 KeyMemento& memento = mKeyMementos.editTop();
4084 memento.deviceId = entry->deviceId;
4085 memento.source = entry->source;
4086 memento.keyCode = entry->keyCode;
4087 memento.scanCode = entry->scanCode;
Jeff Brownfd23e3e2012-05-09 13:34:28 -07004088 memento.metaState = entry->metaState;
Jeff Brown81346812011-06-28 20:08:48 -07004089 memento.flags = flags;
4090 memento.downTime = entry->downTime;
Jeff Brownfd23e3e2012-05-09 13:34:28 -07004091 memento.policyFlags = entry->policyFlags;
Jeff Brown81346812011-06-28 20:08:48 -07004092}
4093
4094void InputDispatcher::InputState::addMotionMemento(const MotionEntry* entry,
4095 int32_t flags, bool hovering) {
4096 mMotionMementos.push();
4097 MotionMemento& memento = mMotionMementos.editTop();
4098 memento.deviceId = entry->deviceId;
4099 memento.source = entry->source;
4100 memento.flags = flags;
4101 memento.xPrecision = entry->xPrecision;
4102 memento.yPrecision = entry->yPrecision;
4103 memento.downTime = entry->downTime;
Jeff Brown83d616a2012-09-09 20:33:43 -07004104 memento.displayId = entry->displayId;
Jeff Brown81346812011-06-28 20:08:48 -07004105 memento.setPointers(entry);
4106 memento.hovering = hovering;
Jeff Brownfd23e3e2012-05-09 13:34:28 -07004107 memento.policyFlags = entry->policyFlags;
Jeff Brownb88102f2010-09-08 11:49:43 -07004108}
4109
4110void InputDispatcher::InputState::MotionMemento::setPointers(const MotionEntry* entry) {
4111 pointerCount = entry->pointerCount;
4112 for (uint32_t i = 0; i < entry->pointerCount; i++) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07004113 pointerProperties[i].copyFrom(entry->pointerProperties[i]);
Jeff Brown3241b6b2012-02-03 15:08:02 -08004114 pointerCoords[i].copyFrom(entry->pointerCoords[i]);
Jeff Brownb88102f2010-09-08 11:49:43 -07004115 }
4116}
4117
Jeff Brownb6997262010-10-08 22:31:17 -07004118void InputDispatcher::InputState::synthesizeCancelationEvents(nsecs_t currentTime,
Jeff Brownac386072011-07-20 15:19:50 -07004119 Vector<EventEntry*>& outEvents, const CancelationOptions& options) {
Jeff Brown81346812011-06-28 20:08:48 -07004120 for (size_t i = 0; i < mKeyMementos.size(); i++) {
Jeff Brownb88102f2010-09-08 11:49:43 -07004121 const KeyMemento& memento = mKeyMementos.itemAt(i);
Jeff Brown49ed71d2010-12-06 17:13:33 -08004122 if (shouldCancelKey(memento, options)) {
Jeff Brownac386072011-07-20 15:19:50 -07004123 outEvents.push(new KeyEntry(currentTime,
Jeff Brownfd23e3e2012-05-09 13:34:28 -07004124 memento.deviceId, memento.source, memento.policyFlags,
Jeff Brown49ed71d2010-12-06 17:13:33 -08004125 AKEY_EVENT_ACTION_UP, memento.flags | AKEY_EVENT_FLAG_CANCELED,
Jeff Brownfd23e3e2012-05-09 13:34:28 -07004126 memento.keyCode, memento.scanCode, memento.metaState, 0, memento.downTime));
Jeff Brownb6997262010-10-08 22:31:17 -07004127 }
Jeff Brownb88102f2010-09-08 11:49:43 -07004128 }
4129
Jeff Brown81346812011-06-28 20:08:48 -07004130 for (size_t i = 0; i < mMotionMementos.size(); i++) {
Jeff Brownb88102f2010-09-08 11:49:43 -07004131 const MotionMemento& memento = mMotionMementos.itemAt(i);
Jeff Brown49ed71d2010-12-06 17:13:33 -08004132 if (shouldCancelMotion(memento, options)) {
Jeff Brownac386072011-07-20 15:19:50 -07004133 outEvents.push(new MotionEntry(currentTime,
Jeff Brownfd23e3e2012-05-09 13:34:28 -07004134 memento.deviceId, memento.source, memento.policyFlags,
Jeff Browna032cc02011-03-07 16:56:21 -08004135 memento.hovering
4136 ? AMOTION_EVENT_ACTION_HOVER_EXIT
4137 : AMOTION_EVENT_ACTION_CANCEL,
Jeff Brown81346812011-06-28 20:08:48 -07004138 memento.flags, 0, 0, 0,
Jeff Brownb6997262010-10-08 22:31:17 -07004139 memento.xPrecision, memento.yPrecision, memento.downTime,
Jeff Brown83d616a2012-09-09 20:33:43 -07004140 memento.displayId,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07004141 memento.pointerCount, memento.pointerProperties, memento.pointerCoords));
Jeff Brownb6997262010-10-08 22:31:17 -07004142 }
Jeff Brownb88102f2010-09-08 11:49:43 -07004143 }
4144}
4145
4146void InputDispatcher::InputState::clear() {
4147 mKeyMementos.clear();
4148 mMotionMementos.clear();
Jeff Brownda3d5a92011-03-29 15:11:34 -07004149 mFallbackKeys.clear();
Jeff Brownb6997262010-10-08 22:31:17 -07004150}
4151
Jeff Brown9c9f1a32010-10-11 18:32:20 -07004152void InputDispatcher::InputState::copyPointerStateTo(InputState& other) const {
4153 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4154 const MotionMemento& memento = mMotionMementos.itemAt(i);
4155 if (memento.source & AINPUT_SOURCE_CLASS_POINTER) {
4156 for (size_t j = 0; j < other.mMotionMementos.size(); ) {
4157 const MotionMemento& otherMemento = other.mMotionMementos.itemAt(j);
4158 if (memento.deviceId == otherMemento.deviceId
Jeff Brown83d616a2012-09-09 20:33:43 -07004159 && memento.source == otherMemento.source
4160 && memento.displayId == otherMemento.displayId) {
Jeff Brown9c9f1a32010-10-11 18:32:20 -07004161 other.mMotionMementos.removeAt(j);
4162 } else {
4163 j += 1;
4164 }
4165 }
4166 other.mMotionMementos.push(memento);
4167 }
4168 }
4169}
4170
Jeff Brownda3d5a92011-03-29 15:11:34 -07004171int32_t InputDispatcher::InputState::getFallbackKey(int32_t originalKeyCode) {
4172 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
4173 return index >= 0 ? mFallbackKeys.valueAt(index) : -1;
4174}
4175
4176void InputDispatcher::InputState::setFallbackKey(int32_t originalKeyCode,
4177 int32_t fallbackKeyCode) {
4178 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
4179 if (index >= 0) {
4180 mFallbackKeys.replaceValueAt(index, fallbackKeyCode);
4181 } else {
4182 mFallbackKeys.add(originalKeyCode, fallbackKeyCode);
4183 }
4184}
4185
4186void InputDispatcher::InputState::removeFallbackKey(int32_t originalKeyCode) {
4187 mFallbackKeys.removeItem(originalKeyCode);
4188}
4189
Jeff Brown49ed71d2010-12-06 17:13:33 -08004190bool InputDispatcher::InputState::shouldCancelKey(const KeyMemento& memento,
Jeff Brownda3d5a92011-03-29 15:11:34 -07004191 const CancelationOptions& options) {
4192 if (options.keyCode != -1 && memento.keyCode != options.keyCode) {
4193 return false;
4194 }
4195
Jeff Brown65fd2512011-08-18 11:20:58 -07004196 if (options.deviceId != -1 && memento.deviceId != options.deviceId) {
4197 return false;
4198 }
4199
Jeff Brownda3d5a92011-03-29 15:11:34 -07004200 switch (options.mode) {
4201 case CancelationOptions::CANCEL_ALL_EVENTS:
4202 case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
Jeff Brownb6997262010-10-08 22:31:17 -07004203 return true;
Jeff Brownda3d5a92011-03-29 15:11:34 -07004204 case CancelationOptions::CANCEL_FALLBACK_EVENTS:
Jeff Brown49ed71d2010-12-06 17:13:33 -08004205 return memento.flags & AKEY_EVENT_FLAG_FALLBACK;
4206 default:
4207 return false;
4208 }
4209}
4210
4211bool InputDispatcher::InputState::shouldCancelMotion(const MotionMemento& memento,
Jeff Brownda3d5a92011-03-29 15:11:34 -07004212 const CancelationOptions& options) {
Jeff Brown65fd2512011-08-18 11:20:58 -07004213 if (options.deviceId != -1 && memento.deviceId != options.deviceId) {
4214 return false;
4215 }
4216
Jeff Brownda3d5a92011-03-29 15:11:34 -07004217 switch (options.mode) {
4218 case CancelationOptions::CANCEL_ALL_EVENTS:
Jeff Brown49ed71d2010-12-06 17:13:33 -08004219 return true;
Jeff Brownda3d5a92011-03-29 15:11:34 -07004220 case CancelationOptions::CANCEL_POINTER_EVENTS:
Jeff Brown49ed71d2010-12-06 17:13:33 -08004221 return memento.source & AINPUT_SOURCE_CLASS_POINTER;
Jeff Brownda3d5a92011-03-29 15:11:34 -07004222 case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
Jeff Brown49ed71d2010-12-06 17:13:33 -08004223 return !(memento.source & AINPUT_SOURCE_CLASS_POINTER);
4224 default:
4225 return false;
Jeff Brownb6997262010-10-08 22:31:17 -07004226 }
Jeff Brownb88102f2010-09-08 11:49:43 -07004227}
4228
4229
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004230// --- InputDispatcher::Connection ---
4231
Jeff Brown928e0542011-01-10 11:17:36 -08004232InputDispatcher::Connection::Connection(const sp<InputChannel>& inputChannel,
Jeff Browncc4f7db2011-08-30 20:34:48 -07004233 const sp<InputWindowHandle>& inputWindowHandle, bool monitor) :
Jeff Brown928e0542011-01-10 11:17:36 -08004234 status(STATUS_NORMAL), inputChannel(inputChannel), inputWindowHandle(inputWindowHandle),
Jeff Browncc4f7db2011-08-30 20:34:48 -07004235 monitor(monitor),
Jeff Brownd1c48a02012-02-06 19:12:47 -08004236 inputPublisher(inputChannel), inputPublisherBlocked(false) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004237}
4238
4239InputDispatcher::Connection::~Connection() {
4240}
4241
Jeff Brown481c1572012-03-09 14:41:15 -08004242const char* InputDispatcher::Connection::getWindowName() const {
4243 if (inputWindowHandle != NULL) {
4244 return inputWindowHandle->getName().string();
4245 }
4246 if (monitor) {
4247 return "monitor";
4248 }
4249 return "?";
4250}
4251
Jeff Brown9c3cda02010-06-15 01:31:58 -07004252const char* InputDispatcher::Connection::getStatusLabel() const {
4253 switch (status) {
4254 case STATUS_NORMAL:
4255 return "NORMAL";
4256
4257 case STATUS_BROKEN:
4258 return "BROKEN";
4259
Jeff Brown9c3cda02010-06-15 01:31:58 -07004260 case STATUS_ZOMBIE:
4261 return "ZOMBIE";
4262
4263 default:
4264 return "UNKNOWN";
4265 }
4266}
4267
Jeff Brown072ec962012-02-07 14:46:57 -08004268InputDispatcher::DispatchEntry* InputDispatcher::Connection::findWaitQueueEntry(uint32_t seq) {
4269 for (DispatchEntry* entry = waitQueue.head; entry != NULL; entry = entry->next) {
4270 if (entry->seq == seq) {
4271 return entry;
4272 }
4273 }
4274 return NULL;
4275}
4276
Jeff Brownb88102f2010-09-08 11:49:43 -07004277
Jeff Brown9c3cda02010-06-15 01:31:58 -07004278// --- InputDispatcher::CommandEntry ---
4279
Jeff Brownac386072011-07-20 15:19:50 -07004280InputDispatcher::CommandEntry::CommandEntry(Command command) :
Jeff Brown072ec962012-02-07 14:46:57 -08004281 command(command), eventTime(0), keyEntry(NULL), userActivityEventType(0),
4282 seq(0), handled(false) {
Jeff Brown9c3cda02010-06-15 01:31:58 -07004283}
4284
4285InputDispatcher::CommandEntry::~CommandEntry() {
4286}
4287
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004288
Jeff Brown01ce2e92010-09-26 22:20:12 -07004289// --- InputDispatcher::TouchState ---
4290
4291InputDispatcher::TouchState::TouchState() :
Jeff Brown83d616a2012-09-09 20:33:43 -07004292 down(false), split(false), deviceId(-1), source(0), displayId(-1) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07004293}
4294
4295InputDispatcher::TouchState::~TouchState() {
4296}
4297
4298void InputDispatcher::TouchState::reset() {
4299 down = false;
4300 split = false;
Jeff Brown95712852011-01-04 19:41:59 -08004301 deviceId = -1;
Jeff Brown58a2da82011-01-25 16:02:22 -08004302 source = 0;
Jeff Brown83d616a2012-09-09 20:33:43 -07004303 displayId = -1;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004304 windows.clear();
4305}
4306
4307void InputDispatcher::TouchState::copyFrom(const TouchState& other) {
4308 down = other.down;
4309 split = other.split;
Jeff Brown95712852011-01-04 19:41:59 -08004310 deviceId = other.deviceId;
Jeff Brown58a2da82011-01-25 16:02:22 -08004311 source = other.source;
Jeff Brown83d616a2012-09-09 20:33:43 -07004312 displayId = other.displayId;
Jeff Brown9302c872011-07-13 22:51:29 -07004313 windows = other.windows;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004314}
4315
Jeff Brown9302c872011-07-13 22:51:29 -07004316void InputDispatcher::TouchState::addOrUpdateWindow(const sp<InputWindowHandle>& windowHandle,
Jeff Brown01ce2e92010-09-26 22:20:12 -07004317 int32_t targetFlags, BitSet32 pointerIds) {
4318 if (targetFlags & InputTarget::FLAG_SPLIT) {
4319 split = true;
4320 }
4321
4322 for (size_t i = 0; i < windows.size(); i++) {
4323 TouchedWindow& touchedWindow = windows.editItemAt(i);
Jeff Brown9302c872011-07-13 22:51:29 -07004324 if (touchedWindow.windowHandle == windowHandle) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07004325 touchedWindow.targetFlags |= targetFlags;
Jeff Brown98db5fa2011-06-08 15:37:10 -07004326 if (targetFlags & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
4327 touchedWindow.targetFlags &= ~InputTarget::FLAG_DISPATCH_AS_IS;
4328 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07004329 touchedWindow.pointerIds.value |= pointerIds.value;
4330 return;
4331 }
4332 }
4333
4334 windows.push();
4335
4336 TouchedWindow& touchedWindow = windows.editTop();
Jeff Brown9302c872011-07-13 22:51:29 -07004337 touchedWindow.windowHandle = windowHandle;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004338 touchedWindow.targetFlags = targetFlags;
4339 touchedWindow.pointerIds = pointerIds;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004340}
4341
Jeff Brownf44e3942012-04-20 11:33:27 -07004342void InputDispatcher::TouchState::removeWindow(const sp<InputWindowHandle>& windowHandle) {
4343 for (size_t i = 0; i < windows.size(); i++) {
4344 if (windows.itemAt(i).windowHandle == windowHandle) {
4345 windows.removeAt(i);
4346 return;
4347 }
4348 }
4349}
4350
Jeff Browna032cc02011-03-07 16:56:21 -08004351void InputDispatcher::TouchState::filterNonAsIsTouchWindows() {
Jeff Brown01ce2e92010-09-26 22:20:12 -07004352 for (size_t i = 0 ; i < windows.size(); ) {
Jeff Browna032cc02011-03-07 16:56:21 -08004353 TouchedWindow& window = windows.editItemAt(i);
Jeff Brown98db5fa2011-06-08 15:37:10 -07004354 if (window.targetFlags & (InputTarget::FLAG_DISPATCH_AS_IS
4355 | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER)) {
Jeff Browna032cc02011-03-07 16:56:21 -08004356 window.targetFlags &= ~InputTarget::FLAG_DISPATCH_MASK;
4357 window.targetFlags |= InputTarget::FLAG_DISPATCH_AS_IS;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004358 i += 1;
Jeff Browna032cc02011-03-07 16:56:21 -08004359 } else {
4360 windows.removeAt(i);
Jeff Brown01ce2e92010-09-26 22:20:12 -07004361 }
4362 }
4363}
4364
Jeff Brown9302c872011-07-13 22:51:29 -07004365sp<InputWindowHandle> InputDispatcher::TouchState::getFirstForegroundWindowHandle() const {
Jeff Brown01ce2e92010-09-26 22:20:12 -07004366 for (size_t i = 0; i < windows.size(); i++) {
Jeff Brown98db5fa2011-06-08 15:37:10 -07004367 const TouchedWindow& window = windows.itemAt(i);
4368 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
Jeff Brown9302c872011-07-13 22:51:29 -07004369 return window.windowHandle;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004370 }
4371 }
4372 return NULL;
4373}
4374
Jeff Brown98db5fa2011-06-08 15:37:10 -07004375bool InputDispatcher::TouchState::isSlippery() const {
4376 // Must have exactly one foreground window.
4377 bool haveSlipperyForegroundWindow = false;
4378 for (size_t i = 0; i < windows.size(); i++) {
4379 const TouchedWindow& window = windows.itemAt(i);
4380 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
Jeff Browncc4f7db2011-08-30 20:34:48 -07004381 if (haveSlipperyForegroundWindow
4382 || !(window.windowHandle->getInfo()->layoutParamsFlags
4383 & InputWindowInfo::FLAG_SLIPPERY)) {
Jeff Brown98db5fa2011-06-08 15:37:10 -07004384 return false;
4385 }
4386 haveSlipperyForegroundWindow = true;
4387 }
4388 }
4389 return haveSlipperyForegroundWindow;
4390}
4391
Jeff Brown01ce2e92010-09-26 22:20:12 -07004392
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004393// --- InputDispatcherThread ---
4394
4395InputDispatcherThread::InputDispatcherThread(const sp<InputDispatcherInterface>& dispatcher) :
4396 Thread(/*canCallJava*/ true), mDispatcher(dispatcher) {
4397}
4398
4399InputDispatcherThread::~InputDispatcherThread() {
4400}
4401
4402bool InputDispatcherThread::threadLoop() {
4403 mDispatcher->dispatchOnce();
4404 return true;
4405}
4406
4407} // namespace android