blob: c8e11c22184383d323b21245331cb66bfbd6ac87 [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 Brown46b9ac02010-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 Brown46b9ac02010-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 Brown46b9ac02010-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 Brown46b9ac02010-04-22 18:58:52 -070027
Jeff Brown46b9ac02010-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 Brown46b9ac02010-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 Brown46b9ac02010-04-22 18:58:52 -070049#include <cutils/log.h>
Mathias Agopianb93a03f82012-02-17 15:34:57 -080050#include <androidfw/PowerManager.h>
Jeff Brown46b9ac02010-04-22 18:58:52 -070051
52#include <stddef.h>
53#include <unistd.h>
Jeff Brown46b9ac02010-04-22 18:58:52 -070054#include <errno.h>
55#include <limits.h>
Jeff Brown46b9ac02010-04-22 18:58:52 -070056
Jeff Brownf2f48712010-10-01 17:46:21 -070057#define INDENT " "
58#define INDENT2 " "
59
Jeff Brown46b9ac02010-04-22 18:58:52 -070060namespace android {
61
Jeff Brownb88102f2010-09-08 11:49:43 -070062// Default input dispatching timeout if there is no focused application or paused window
63// from which to determine an appropriate dispatching timeout.
64const nsecs_t DEFAULT_INPUT_DISPATCHING_TIMEOUT = 5000 * 1000000LL; // 5 sec
65
66// Amount of time to allow for all pending events to be processed when an app switch
67// key is on the way. This is used to preempt input dispatch and drop input events
68// when an application takes too long to respond and the user has pressed an app switch key.
69const nsecs_t APP_SWITCH_TIMEOUT = 500 * 1000000LL; // 0.5sec
70
Jeff Brown928e0542011-01-10 11:17:36 -080071// Amount of time to allow for an event to be dispatched (measured since its eventTime)
72// before considering it stale and dropping it.
73const nsecs_t STALE_EVENT_TIMEOUT = 10000 * 1000000LL; // 10sec
74
Jeff Brownd1c48a02012-02-06 19:12:47 -080075// Amount of time to allow touch events to be streamed out to a connection before requiring
76// that the first event be finished. This value extends the ANR timeout by the specified
77// amount. For example, if streaming is allowed to get ahead by one second relative to the
78// queue of waiting unfinished events, then ANRs will similarly be delayed by one second.
79const nsecs_t STREAM_AHEAD_EVENT_TIMEOUT = 500 * 1000000LL; // 0.5sec
80
Jeff Brown46b9ac02010-04-22 18:58:52 -070081
Jeff Brown7fbdc842010-06-17 20:52:56 -070082static inline nsecs_t now() {
83 return systemTime(SYSTEM_TIME_MONOTONIC);
84}
85
Jeff Brownb88102f2010-09-08 11:49:43 -070086static inline const char* toString(bool value) {
87 return value ? "true" : "false";
88}
89
Jeff Brown01ce2e92010-09-26 22:20:12 -070090static inline int32_t getMotionEventActionPointerIndex(int32_t action) {
91 return (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK)
92 >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
93}
94
95static bool isValidKeyAction(int32_t action) {
96 switch (action) {
97 case AKEY_EVENT_ACTION_DOWN:
98 case AKEY_EVENT_ACTION_UP:
99 return true;
100 default:
101 return false;
102 }
103}
104
105static bool validateKeyEvent(int32_t action) {
106 if (! isValidKeyAction(action)) {
Steve Block3762c312012-01-06 19:20:56 +0000107 ALOGE("Key event has invalid action code 0x%x", action);
Jeff Brown01ce2e92010-09-26 22:20:12 -0700108 return false;
109 }
110 return true;
111}
112
Jeff Brownb6997262010-10-08 22:31:17 -0700113static bool isValidMotionAction(int32_t action, size_t pointerCount) {
Jeff Brown01ce2e92010-09-26 22:20:12 -0700114 switch (action & AMOTION_EVENT_ACTION_MASK) {
115 case AMOTION_EVENT_ACTION_DOWN:
116 case AMOTION_EVENT_ACTION_UP:
117 case AMOTION_EVENT_ACTION_CANCEL:
118 case AMOTION_EVENT_ACTION_MOVE:
Jeff Brown01ce2e92010-09-26 22:20:12 -0700119 case AMOTION_EVENT_ACTION_OUTSIDE:
Jeff Browna032cc02011-03-07 16:56:21 -0800120 case AMOTION_EVENT_ACTION_HOVER_ENTER:
Jeff Browncc0c1592011-02-19 05:07:28 -0800121 case AMOTION_EVENT_ACTION_HOVER_MOVE:
Jeff Browna032cc02011-03-07 16:56:21 -0800122 case AMOTION_EVENT_ACTION_HOVER_EXIT:
Jeff Brown33bbfd22011-02-24 20:55:35 -0800123 case AMOTION_EVENT_ACTION_SCROLL:
Jeff Brown01ce2e92010-09-26 22:20:12 -0700124 return true;
Jeff Brownb6997262010-10-08 22:31:17 -0700125 case AMOTION_EVENT_ACTION_POINTER_DOWN:
126 case AMOTION_EVENT_ACTION_POINTER_UP: {
127 int32_t index = getMotionEventActionPointerIndex(action);
128 return index >= 0 && size_t(index) < pointerCount;
129 }
Jeff Brown01ce2e92010-09-26 22:20:12 -0700130 default:
131 return false;
132 }
133}
134
135static bool validateMotionEvent(int32_t action, size_t pointerCount,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700136 const PointerProperties* pointerProperties) {
Jeff Brownb6997262010-10-08 22:31:17 -0700137 if (! isValidMotionAction(action, pointerCount)) {
Steve Block3762c312012-01-06 19:20:56 +0000138 ALOGE("Motion event has invalid action code 0x%x", action);
Jeff Brown01ce2e92010-09-26 22:20:12 -0700139 return false;
140 }
141 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Steve Block3762c312012-01-06 19:20:56 +0000142 ALOGE("Motion event has invalid pointer count %d; value must be between 1 and %d.",
Jeff Brown01ce2e92010-09-26 22:20:12 -0700143 pointerCount, MAX_POINTERS);
144 return false;
145 }
Jeff Brownc3db8582010-10-20 15:33:38 -0700146 BitSet32 pointerIdBits;
Jeff Brown01ce2e92010-09-26 22:20:12 -0700147 for (size_t i = 0; i < pointerCount; i++) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700148 int32_t id = pointerProperties[i].id;
Jeff Brownc3db8582010-10-20 15:33:38 -0700149 if (id < 0 || id > MAX_POINTER_ID) {
Steve Block3762c312012-01-06 19:20:56 +0000150 ALOGE("Motion event has invalid pointer id %d; value must be between 0 and %d",
Jeff Brownc3db8582010-10-20 15:33:38 -0700151 id, MAX_POINTER_ID);
Jeff Brown01ce2e92010-09-26 22:20:12 -0700152 return false;
153 }
Jeff Brownc3db8582010-10-20 15:33:38 -0700154 if (pointerIdBits.hasBit(id)) {
Steve Block3762c312012-01-06 19:20:56 +0000155 ALOGE("Motion event has duplicate pointer id %d", id);
Jeff Brownc3db8582010-10-20 15:33:38 -0700156 return false;
157 }
158 pointerIdBits.markBit(id);
Jeff Brown01ce2e92010-09-26 22:20:12 -0700159 }
160 return true;
161}
162
Jeff Brownfbf09772011-01-16 14:06:57 -0800163static void dumpRegion(String8& dump, const SkRegion& region) {
164 if (region.isEmpty()) {
165 dump.append("<empty>");
166 return;
167 }
168
169 bool first = true;
170 for (SkRegion::Iterator it(region); !it.done(); it.next()) {
171 if (first) {
172 first = false;
173 } else {
174 dump.append("|");
175 }
176 const SkIRect& rect = it.rect();
177 dump.appendFormat("[%d,%d][%d,%d]", rect.fLeft, rect.fTop, rect.fRight, rect.fBottom);
178 }
179}
180
Jeff Brownb88102f2010-09-08 11:49:43 -0700181
Jeff Brown46b9ac02010-04-22 18:58:52 -0700182// --- InputDispatcher ---
183
Jeff Brown9c3cda02010-06-15 01:31:58 -0700184InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy) :
Jeff Brownb88102f2010-09-08 11:49:43 -0700185 mPolicy(policy),
Jeff Brown928e0542011-01-10 11:17:36 -0800186 mPendingEvent(NULL), mAppSwitchSawKeyDown(false), mAppSwitchDueTime(LONG_LONG_MAX),
187 mNextUnblockedEvent(NULL),
Jeff Brownc042ee22012-05-08 13:03:42 -0700188 mDispatchEnabled(false), mDispatchFrozen(false), mInputFilterEnabled(false),
Jeff Brown9302c872011-07-13 22:51:29 -0700189 mInputTargetWaitCause(INPUT_TARGET_WAIT_CAUSE_NONE) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -0700190 mLooper = new Looper(false);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700191
Jeff Brown46b9ac02010-04-22 18:58:52 -0700192 mKeyRepeatState.lastKeyEntry = NULL;
Jeff Brown9c3cda02010-06-15 01:31:58 -0700193
Jeff Brown214eaf42011-05-26 19:17:02 -0700194 policy->getDispatcherConfiguration(&mConfig);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700195}
196
197InputDispatcher::~InputDispatcher() {
Jeff Brownb88102f2010-09-08 11:49:43 -0700198 { // acquire lock
199 AutoMutex _l(mLock);
200
201 resetKeyRepeatLocked();
Jeff Brown54a18252010-09-16 14:07:33 -0700202 releasePendingEventLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -0700203 drainInboundQueueLocked();
204 }
Jeff Brown46b9ac02010-04-22 18:58:52 -0700205
Jeff Browncbee6d62012-02-03 20:11:27 -0800206 while (mConnectionsByFd.size() != 0) {
207 unregisterInputChannel(mConnectionsByFd.valueAt(0)->inputChannel);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700208 }
Jeff Brown46b9ac02010-04-22 18:58:52 -0700209}
210
211void InputDispatcher::dispatchOnce() {
Jeff Brown46b9ac02010-04-22 18:58:52 -0700212 nsecs_t nextWakeupTime = LONG_LONG_MAX;
213 { // acquire lock
214 AutoMutex _l(mLock);
Jeff Brown112b5f52012-01-27 17:32:06 -0800215 mDispatcherIsAliveCondition.broadcast();
216
Jeff Brown214eaf42011-05-26 19:17:02 -0700217 dispatchOnceInnerLocked(&nextWakeupTime);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700218
Jeff Brownb88102f2010-09-08 11:49:43 -0700219 if (runCommandsLockedInterruptible()) {
220 nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
Jeff Brown46b9ac02010-04-22 18:58:52 -0700221 }
Jeff Brown46b9ac02010-04-22 18:58:52 -0700222 } // release lock
223
Jeff Brownb88102f2010-09-08 11:49:43 -0700224 // Wait for callback or timeout or wake. (make sure we round up, not down)
225 nsecs_t currentTime = now();
Jeff Brownaa3855d2011-03-17 01:34:19 -0700226 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
Jeff Brown4fe6c3e2010-09-13 23:17:30 -0700227 mLooper->pollOnce(timeoutMillis);
Jeff Brownb88102f2010-09-08 11:49:43 -0700228}
229
Jeff Brown214eaf42011-05-26 19:17:02 -0700230void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700231 nsecs_t currentTime = now();
232
233 // Reset the key repeat timer whenever we disallow key events, even if the next event
234 // is not a key. This is to ensure that we abort a key repeat if the device is just coming
235 // out of sleep.
Jeff Brown214eaf42011-05-26 19:17:02 -0700236 if (!mPolicy->isKeyRepeatEnabled()) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700237 resetKeyRepeatLocked();
238 }
239
Jeff Brownb88102f2010-09-08 11:49:43 -0700240 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
241 if (mDispatchFrozen) {
242#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +0000243 ALOGD("Dispatch frozen. Waiting some more.");
Jeff Brownb88102f2010-09-08 11:49:43 -0700244#endif
245 return;
246 }
247
248 // Optimize latency of app switches.
249 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
250 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
251 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
252 if (mAppSwitchDueTime < *nextWakeupTime) {
253 *nextWakeupTime = mAppSwitchDueTime;
254 }
255
Jeff Brownb88102f2010-09-08 11:49:43 -0700256 // Ready to start a new event.
257 // If we don't already have a pending event, go grab one.
258 if (! mPendingEvent) {
259 if (mInboundQueue.isEmpty()) {
260 if (isAppSwitchDue) {
261 // The inbound queue is empty so the app switch key we were waiting
262 // for will never arrive. Stop waiting for it.
263 resetPendingAppSwitchLocked(false);
264 isAppSwitchDue = false;
265 }
266
267 // Synthesize a key repeat if appropriate.
268 if (mKeyRepeatState.lastKeyEntry) {
269 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
Jeff Brown214eaf42011-05-26 19:17:02 -0700270 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700271 } else {
272 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
273 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
274 }
275 }
276 }
Jeff Browncc4f7db2011-08-30 20:34:48 -0700277
278 // Nothing to do if there is no pending event.
Jeff Browne9bb9be2012-02-06 15:47:55 -0800279 if (!mPendingEvent) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700280 return;
281 }
282 } else {
283 // Inbound queue has at least one entry.
Jeff Browne9bb9be2012-02-06 15:47:55 -0800284 mPendingEvent = mInboundQueue.dequeueAtHead();
Jeff Brown481c1572012-03-09 14:41:15 -0800285 traceInboundQueueLengthLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -0700286 }
Jeff Browne2fe69e2010-10-18 13:21:23 -0700287
288 // Poke user activity for this event.
289 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
290 pokeUserActivityLocked(mPendingEvent);
291 }
Jeff Browne9bb9be2012-02-06 15:47:55 -0800292
293 // Get ready to dispatch the event.
294 resetANRTimeoutsLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -0700295 }
296
297 // Now we have an event to dispatch.
Jeff Brown928e0542011-01-10 11:17:36 -0800298 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Steve Blockec193de2012-01-09 18:35:44 +0000299 ALOG_ASSERT(mPendingEvent != NULL);
Jeff Brown54a18252010-09-16 14:07:33 -0700300 bool done = false;
Jeff Brownb6997262010-10-08 22:31:17 -0700301 DropReason dropReason = DROP_REASON_NOT_DROPPED;
302 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
303 dropReason = DROP_REASON_POLICY;
304 } else if (!mDispatchEnabled) {
305 dropReason = DROP_REASON_DISABLED;
306 }
Jeff Brown928e0542011-01-10 11:17:36 -0800307
308 if (mNextUnblockedEvent == mPendingEvent) {
309 mNextUnblockedEvent = NULL;
310 }
311
Jeff Brownb88102f2010-09-08 11:49:43 -0700312 switch (mPendingEvent->type) {
313 case EventEntry::TYPE_CONFIGURATION_CHANGED: {
314 ConfigurationChangedEntry* typedEntry =
315 static_cast<ConfigurationChangedEntry*>(mPendingEvent);
Jeff Brown54a18252010-09-16 14:07:33 -0700316 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Jeff Brownb6997262010-10-08 22:31:17 -0700317 dropReason = DROP_REASON_NOT_DROPPED; // configuration changes are never dropped
Jeff Brownb88102f2010-09-08 11:49:43 -0700318 break;
319 }
320
Jeff Brown65fd2512011-08-18 11:20:58 -0700321 case EventEntry::TYPE_DEVICE_RESET: {
322 DeviceResetEntry* typedEntry =
323 static_cast<DeviceResetEntry*>(mPendingEvent);
324 done = dispatchDeviceResetLocked(currentTime, typedEntry);
325 dropReason = DROP_REASON_NOT_DROPPED; // device resets are never dropped
326 break;
327 }
328
Jeff Brownb88102f2010-09-08 11:49:43 -0700329 case EventEntry::TYPE_KEY: {
330 KeyEntry* typedEntry = static_cast<KeyEntry*>(mPendingEvent);
Jeff Brownb6997262010-10-08 22:31:17 -0700331 if (isAppSwitchDue) {
332 if (isAppSwitchKeyEventLocked(typedEntry)) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700333 resetPendingAppSwitchLocked(true);
Jeff Brownb6997262010-10-08 22:31:17 -0700334 isAppSwitchDue = false;
335 } else if (dropReason == DROP_REASON_NOT_DROPPED) {
336 dropReason = DROP_REASON_APP_SWITCH;
Jeff Brownb88102f2010-09-08 11:49:43 -0700337 }
338 }
Jeff Brown928e0542011-01-10 11:17:36 -0800339 if (dropReason == DROP_REASON_NOT_DROPPED
340 && isStaleEventLocked(currentTime, typedEntry)) {
341 dropReason = DROP_REASON_STALE;
342 }
343 if (dropReason == DROP_REASON_NOT_DROPPED && mNextUnblockedEvent) {
344 dropReason = DROP_REASON_BLOCKED;
345 }
Jeff Brown214eaf42011-05-26 19:17:02 -0700346 done = dispatchKeyLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700347 break;
348 }
349
350 case EventEntry::TYPE_MOTION: {
351 MotionEntry* typedEntry = static_cast<MotionEntry*>(mPendingEvent);
Jeff Brownb6997262010-10-08 22:31:17 -0700352 if (dropReason == DROP_REASON_NOT_DROPPED && isAppSwitchDue) {
353 dropReason = DROP_REASON_APP_SWITCH;
Jeff Brownb88102f2010-09-08 11:49:43 -0700354 }
Jeff Brown928e0542011-01-10 11:17:36 -0800355 if (dropReason == DROP_REASON_NOT_DROPPED
356 && isStaleEventLocked(currentTime, typedEntry)) {
357 dropReason = DROP_REASON_STALE;
358 }
359 if (dropReason == DROP_REASON_NOT_DROPPED && mNextUnblockedEvent) {
360 dropReason = DROP_REASON_BLOCKED;
361 }
Jeff Brownb6997262010-10-08 22:31:17 -0700362 done = dispatchMotionLocked(currentTime, typedEntry,
Jeff Browne20c9e02010-10-11 14:20:19 -0700363 &dropReason, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700364 break;
365 }
366
367 default:
Steve Blockec193de2012-01-09 18:35:44 +0000368 ALOG_ASSERT(false);
Jeff Brownb88102f2010-09-08 11:49:43 -0700369 break;
370 }
371
Jeff Brown54a18252010-09-16 14:07:33 -0700372 if (done) {
Jeff Brownb6997262010-10-08 22:31:17 -0700373 if (dropReason != DROP_REASON_NOT_DROPPED) {
374 dropInboundEventLocked(mPendingEvent, dropReason);
375 }
376
Jeff Brown54a18252010-09-16 14:07:33 -0700377 releasePendingEventLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -0700378 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
379 }
380}
381
382bool InputDispatcher::enqueueInboundEventLocked(EventEntry* entry) {
383 bool needWake = mInboundQueue.isEmpty();
384 mInboundQueue.enqueueAtTail(entry);
Jeff Brown481c1572012-03-09 14:41:15 -0800385 traceInboundQueueLengthLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -0700386
387 switch (entry->type) {
Jeff Brownb6997262010-10-08 22:31:17 -0700388 case EventEntry::TYPE_KEY: {
Jeff Brown928e0542011-01-10 11:17:36 -0800389 // Optimize app switch latency.
390 // If the application takes too long to catch up then we drop all events preceding
391 // the app switch key.
Jeff Brownb6997262010-10-08 22:31:17 -0700392 KeyEntry* keyEntry = static_cast<KeyEntry*>(entry);
393 if (isAppSwitchKeyEventLocked(keyEntry)) {
394 if (keyEntry->action == AKEY_EVENT_ACTION_DOWN) {
395 mAppSwitchSawKeyDown = true;
396 } else if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
397 if (mAppSwitchSawKeyDown) {
398#if DEBUG_APP_SWITCH
Steve Block5baa3a62011-12-20 16:23:08 +0000399 ALOGD("App switch is pending!");
Jeff Brownb6997262010-10-08 22:31:17 -0700400#endif
401 mAppSwitchDueTime = keyEntry->eventTime + APP_SWITCH_TIMEOUT;
402 mAppSwitchSawKeyDown = false;
403 needWake = true;
404 }
405 }
406 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700407 break;
408 }
Jeff Brown928e0542011-01-10 11:17:36 -0800409
410 case EventEntry::TYPE_MOTION: {
411 // Optimize case where the current application is unresponsive and the user
412 // decides to touch a window in a different application.
413 // If the application takes too long to catch up then we drop all events preceding
414 // the touch into the other window.
415 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
Jeff Brown33bbfd22011-02-24 20:55:35 -0800416 if (motionEntry->action == AMOTION_EVENT_ACTION_DOWN
Jeff Brown928e0542011-01-10 11:17:36 -0800417 && (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER)
418 && mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY
Jeff Brown9302c872011-07-13 22:51:29 -0700419 && mInputTargetWaitApplicationHandle != NULL) {
Jeff Brown3241b6b2012-02-03 15:08:02 -0800420 int32_t x = int32_t(motionEntry->pointerCoords[0].
Jeff Brownebbd5d12011-02-17 13:01:34 -0800421 getAxisValue(AMOTION_EVENT_AXIS_X));
Jeff Brown3241b6b2012-02-03 15:08:02 -0800422 int32_t y = int32_t(motionEntry->pointerCoords[0].
Jeff Brownebbd5d12011-02-17 13:01:34 -0800423 getAxisValue(AMOTION_EVENT_AXIS_Y));
Jeff Brown9302c872011-07-13 22:51:29 -0700424 sp<InputWindowHandle> touchedWindowHandle = findTouchedWindowAtLocked(x, y);
425 if (touchedWindowHandle != NULL
426 && touchedWindowHandle->inputApplicationHandle
427 != mInputTargetWaitApplicationHandle) {
Jeff Brown928e0542011-01-10 11:17:36 -0800428 // User touched a different application than the one we are waiting on.
429 // Flag the event, and start pruning the input queue.
430 mNextUnblockedEvent = motionEntry;
431 needWake = true;
432 }
433 }
434 break;
435 }
Jeff Brownb6997262010-10-08 22:31:17 -0700436 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700437
438 return needWake;
439}
440
Jeff Brown9302c872011-07-13 22:51:29 -0700441sp<InputWindowHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t x, int32_t y) {
Jeff Brown928e0542011-01-10 11:17:36 -0800442 // Traverse windows from front to back to find touched window.
Jeff Brown9302c872011-07-13 22:51:29 -0700443 size_t numWindows = mWindowHandles.size();
Jeff Brown928e0542011-01-10 11:17:36 -0800444 for (size_t i = 0; i < numWindows; i++) {
Jeff Brown9302c872011-07-13 22:51:29 -0700445 sp<InputWindowHandle> windowHandle = mWindowHandles.itemAt(i);
Jeff Browncc4f7db2011-08-30 20:34:48 -0700446 const InputWindowInfo* windowInfo = windowHandle->getInfo();
447 int32_t flags = windowInfo->layoutParamsFlags;
Jeff Brown928e0542011-01-10 11:17:36 -0800448
Jeff Browncc4f7db2011-08-30 20:34:48 -0700449 if (windowInfo->visible) {
450 if (!(flags & InputWindowInfo::FLAG_NOT_TOUCHABLE)) {
451 bool isTouchModal = (flags & (InputWindowInfo::FLAG_NOT_FOCUSABLE
452 | InputWindowInfo::FLAG_NOT_TOUCH_MODAL)) == 0;
453 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
Jeff Brown928e0542011-01-10 11:17:36 -0800454 // Found window.
Jeff Brown9302c872011-07-13 22:51:29 -0700455 return windowHandle;
Jeff Brown928e0542011-01-10 11:17:36 -0800456 }
457 }
458 }
459
Jeff Browncc4f7db2011-08-30 20:34:48 -0700460 if (flags & InputWindowInfo::FLAG_SYSTEM_ERROR) {
Jeff Brown928e0542011-01-10 11:17:36 -0800461 // Error window is on top but not visible, so touch is dropped.
462 return NULL;
463 }
464 }
465 return NULL;
466}
467
Jeff Brownb6997262010-10-08 22:31:17 -0700468void InputDispatcher::dropInboundEventLocked(EventEntry* entry, DropReason dropReason) {
469 const char* reason;
470 switch (dropReason) {
471 case DROP_REASON_POLICY:
Jeff Browne20c9e02010-10-11 14:20:19 -0700472#if DEBUG_INBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +0000473 ALOGD("Dropped event because policy consumed it.");
Jeff Browne20c9e02010-10-11 14:20:19 -0700474#endif
Jeff Brown3122e442010-10-11 23:32:49 -0700475 reason = "inbound event was dropped because the policy consumed it";
Jeff Brownb6997262010-10-08 22:31:17 -0700476 break;
477 case DROP_REASON_DISABLED:
Steve Block6215d3f2012-01-04 20:05:49 +0000478 ALOGI("Dropped event because input dispatch is disabled.");
Jeff Brownb6997262010-10-08 22:31:17 -0700479 reason = "inbound event was dropped because input dispatch is disabled";
480 break;
481 case DROP_REASON_APP_SWITCH:
Steve Block6215d3f2012-01-04 20:05:49 +0000482 ALOGI("Dropped event because of pending overdue app switch.");
Jeff Brownb6997262010-10-08 22:31:17 -0700483 reason = "inbound event was dropped because of pending overdue app switch";
484 break;
Jeff Brown928e0542011-01-10 11:17:36 -0800485 case DROP_REASON_BLOCKED:
Steve Block6215d3f2012-01-04 20:05:49 +0000486 ALOGI("Dropped event because the current application is not responding and the user "
Jeff Brown81346812011-06-28 20:08:48 -0700487 "has started interacting with a different application.");
Jeff Brown928e0542011-01-10 11:17:36 -0800488 reason = "inbound event was dropped because the current application is not responding "
Jeff Brown81346812011-06-28 20:08:48 -0700489 "and the user has started interacting with a different application";
Jeff Brown928e0542011-01-10 11:17:36 -0800490 break;
491 case DROP_REASON_STALE:
Steve Block6215d3f2012-01-04 20:05:49 +0000492 ALOGI("Dropped event because it is stale.");
Jeff Brown928e0542011-01-10 11:17:36 -0800493 reason = "inbound event was dropped because it is stale";
494 break;
Jeff Brownb6997262010-10-08 22:31:17 -0700495 default:
Steve Blockec193de2012-01-09 18:35:44 +0000496 ALOG_ASSERT(false);
Jeff Brownb6997262010-10-08 22:31:17 -0700497 return;
498 }
499
500 switch (entry->type) {
Jeff Brownda3d5a92011-03-29 15:11:34 -0700501 case EventEntry::TYPE_KEY: {
502 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
503 synthesizeCancelationEventsForAllConnectionsLocked(options);
Jeff Brownb6997262010-10-08 22:31:17 -0700504 break;
Jeff Brownda3d5a92011-03-29 15:11:34 -0700505 }
Jeff Brownb6997262010-10-08 22:31:17 -0700506 case EventEntry::TYPE_MOTION: {
507 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
508 if (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) {
Jeff Brownda3d5a92011-03-29 15:11:34 -0700509 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
510 synthesizeCancelationEventsForAllConnectionsLocked(options);
Jeff Brownb6997262010-10-08 22:31:17 -0700511 } else {
Jeff Brownda3d5a92011-03-29 15:11:34 -0700512 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
513 synthesizeCancelationEventsForAllConnectionsLocked(options);
Jeff Brownb6997262010-10-08 22:31:17 -0700514 }
515 break;
516 }
517 }
518}
519
520bool InputDispatcher::isAppSwitchKeyCode(int32_t keyCode) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700521 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL;
522}
523
Jeff Brownb6997262010-10-08 22:31:17 -0700524bool InputDispatcher::isAppSwitchKeyEventLocked(KeyEntry* keyEntry) {
525 return ! (keyEntry->flags & AKEY_EVENT_FLAG_CANCELED)
526 && isAppSwitchKeyCode(keyEntry->keyCode)
Jeff Browne20c9e02010-10-11 14:20:19 -0700527 && (keyEntry->policyFlags & POLICY_FLAG_TRUSTED)
Jeff Brownb6997262010-10-08 22:31:17 -0700528 && (keyEntry->policyFlags & POLICY_FLAG_PASS_TO_USER);
529}
530
Jeff Brownb88102f2010-09-08 11:49:43 -0700531bool InputDispatcher::isAppSwitchPendingLocked() {
532 return mAppSwitchDueTime != LONG_LONG_MAX;
533}
534
Jeff Brownb88102f2010-09-08 11:49:43 -0700535void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
536 mAppSwitchDueTime = LONG_LONG_MAX;
537
538#if DEBUG_APP_SWITCH
539 if (handled) {
Steve Block5baa3a62011-12-20 16:23:08 +0000540 ALOGD("App switch has arrived.");
Jeff Brownb88102f2010-09-08 11:49:43 -0700541 } else {
Steve Block5baa3a62011-12-20 16:23:08 +0000542 ALOGD("App switch was abandoned.");
Jeff Brownb88102f2010-09-08 11:49:43 -0700543 }
544#endif
Jeff Brown46b9ac02010-04-22 18:58:52 -0700545}
546
Jeff Brown928e0542011-01-10 11:17:36 -0800547bool InputDispatcher::isStaleEventLocked(nsecs_t currentTime, EventEntry* entry) {
548 return currentTime - entry->eventTime >= STALE_EVENT_TIMEOUT;
549}
550
Jeff Brown9c3cda02010-06-15 01:31:58 -0700551bool InputDispatcher::runCommandsLockedInterruptible() {
552 if (mCommandQueue.isEmpty()) {
553 return false;
554 }
Jeff Brown46b9ac02010-04-22 18:58:52 -0700555
Jeff Brown9c3cda02010-06-15 01:31:58 -0700556 do {
557 CommandEntry* commandEntry = mCommandQueue.dequeueAtHead();
558
559 Command command = commandEntry->command;
560 (this->*command)(commandEntry); // commands are implicitly 'LockedInterruptible'
561
Jeff Brown7fbdc842010-06-17 20:52:56 -0700562 commandEntry->connection.clear();
Jeff Brownac386072011-07-20 15:19:50 -0700563 delete commandEntry;
Jeff Brown9c3cda02010-06-15 01:31:58 -0700564 } while (! mCommandQueue.isEmpty());
565 return true;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700566}
567
Jeff Brown9c3cda02010-06-15 01:31:58 -0700568InputDispatcher::CommandEntry* InputDispatcher::postCommandLocked(Command command) {
Jeff Brownac386072011-07-20 15:19:50 -0700569 CommandEntry* commandEntry = new CommandEntry(command);
Jeff Brown9c3cda02010-06-15 01:31:58 -0700570 mCommandQueue.enqueueAtTail(commandEntry);
571 return commandEntry;
572}
573
Jeff Brownb88102f2010-09-08 11:49:43 -0700574void InputDispatcher::drainInboundQueueLocked() {
575 while (! mInboundQueue.isEmpty()) {
576 EventEntry* entry = mInboundQueue.dequeueAtHead();
Jeff Brown54a18252010-09-16 14:07:33 -0700577 releaseInboundEventLocked(entry);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700578 }
Jeff Brown481c1572012-03-09 14:41:15 -0800579 traceInboundQueueLengthLocked();
Jeff Brown46b9ac02010-04-22 18:58:52 -0700580}
581
Jeff Brown54a18252010-09-16 14:07:33 -0700582void InputDispatcher::releasePendingEventLocked() {
Jeff Brownb88102f2010-09-08 11:49:43 -0700583 if (mPendingEvent) {
Jeff Browne9bb9be2012-02-06 15:47:55 -0800584 resetANRTimeoutsLocked();
Jeff Brown54a18252010-09-16 14:07:33 -0700585 releaseInboundEventLocked(mPendingEvent);
Jeff Brownb88102f2010-09-08 11:49:43 -0700586 mPendingEvent = NULL;
587 }
588}
589
Jeff Brown54a18252010-09-16 14:07:33 -0700590void InputDispatcher::releaseInboundEventLocked(EventEntry* entry) {
Jeff Brown01ce2e92010-09-26 22:20:12 -0700591 InjectionState* injectionState = entry->injectionState;
592 if (injectionState && injectionState->injectionResult == INPUT_EVENT_INJECTION_PENDING) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700593#if DEBUG_DISPATCH_CYCLE
Steve Block5baa3a62011-12-20 16:23:08 +0000594 ALOGD("Injected inbound event was dropped.");
Jeff Brownb88102f2010-09-08 11:49:43 -0700595#endif
596 setInjectionResultLocked(entry, INPUT_EVENT_INJECTION_FAILED);
597 }
Jeff Brownabb4d442011-08-15 12:55:32 -0700598 if (entry == mNextUnblockedEvent) {
599 mNextUnblockedEvent = NULL;
600 }
Jeff Brownac386072011-07-20 15:19:50 -0700601 entry->release();
Jeff Brownb88102f2010-09-08 11:49:43 -0700602}
603
Jeff Brownb88102f2010-09-08 11:49:43 -0700604void InputDispatcher::resetKeyRepeatLocked() {
605 if (mKeyRepeatState.lastKeyEntry) {
Jeff Brownac386072011-07-20 15:19:50 -0700606 mKeyRepeatState.lastKeyEntry->release();
Jeff Brownb88102f2010-09-08 11:49:43 -0700607 mKeyRepeatState.lastKeyEntry = NULL;
608 }
609}
610
Jeff Brown214eaf42011-05-26 19:17:02 -0700611InputDispatcher::KeyEntry* InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
Jeff Brown349703e2010-06-22 01:27:15 -0700612 KeyEntry* entry = mKeyRepeatState.lastKeyEntry;
613
Jeff Brown349703e2010-06-22 01:27:15 -0700614 // Reuse the repeated key entry if it is otherwise unreferenced.
Jeff Browne20c9e02010-10-11 14:20:19 -0700615 uint32_t policyFlags = (entry->policyFlags & POLICY_FLAG_RAW_MASK)
616 | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700617 if (entry->refCount == 1) {
Jeff Brownac386072011-07-20 15:19:50 -0700618 entry->recycle();
Jeff Brown7fbdc842010-06-17 20:52:56 -0700619 entry->eventTime = currentTime;
Jeff Brown7fbdc842010-06-17 20:52:56 -0700620 entry->policyFlags = policyFlags;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700621 entry->repeatCount += 1;
622 } else {
Jeff Brownac386072011-07-20 15:19:50 -0700623 KeyEntry* newEntry = new KeyEntry(currentTime,
Jeff Brownc5ed5912010-07-14 18:48:53 -0700624 entry->deviceId, entry->source, policyFlags,
Jeff Brown7fbdc842010-06-17 20:52:56 -0700625 entry->action, entry->flags, entry->keyCode, entry->scanCode,
Jeff Brown00fa7bd2010-07-02 15:37:36 -0700626 entry->metaState, entry->repeatCount + 1, entry->downTime);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700627
628 mKeyRepeatState.lastKeyEntry = newEntry;
Jeff Brownac386072011-07-20 15:19:50 -0700629 entry->release();
Jeff Brown46b9ac02010-04-22 18:58:52 -0700630
631 entry = newEntry;
632 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700633 entry->syntheticRepeat = true;
634
635 // Increment reference count since we keep a reference to the event in
636 // mKeyRepeatState.lastKeyEntry in addition to the one we return.
637 entry->refCount += 1;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700638
Jeff Brown214eaf42011-05-26 19:17:02 -0700639 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Jeff Brownb88102f2010-09-08 11:49:43 -0700640 return entry;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700641}
642
Jeff Brownb88102f2010-09-08 11:49:43 -0700643bool InputDispatcher::dispatchConfigurationChangedLocked(
644 nsecs_t currentTime, ConfigurationChangedEntry* entry) {
Jeff Brown46b9ac02010-04-22 18:58:52 -0700645#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +0000646 ALOGD("dispatchConfigurationChanged - eventTime=%lld", entry->eventTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700647#endif
648
649 // Reset key repeating in case a keyboard device was added or removed or something.
650 resetKeyRepeatLocked();
651
652 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
653 CommandEntry* commandEntry = postCommandLocked(
654 & InputDispatcher::doNotifyConfigurationChangedInterruptible);
655 commandEntry->eventTime = entry->eventTime;
656 return true;
657}
658
Jeff Brown65fd2512011-08-18 11:20:58 -0700659bool InputDispatcher::dispatchDeviceResetLocked(
660 nsecs_t currentTime, DeviceResetEntry* entry) {
661#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +0000662 ALOGD("dispatchDeviceReset - eventTime=%lld, deviceId=%d", entry->eventTime, entry->deviceId);
Jeff Brown65fd2512011-08-18 11:20:58 -0700663#endif
664
665 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
666 "device was reset");
667 options.deviceId = entry->deviceId;
668 synthesizeCancelationEventsForAllConnectionsLocked(options);
669 return true;
670}
671
Jeff Brown214eaf42011-05-26 19:17:02 -0700672bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, KeyEntry* entry,
Jeff Browne20c9e02010-10-11 14:20:19 -0700673 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Jeff Browne46a0a42010-11-02 17:58:22 -0700674 // Preprocessing.
675 if (! entry->dispatchInProgress) {
676 if (entry->repeatCount == 0
677 && entry->action == AKEY_EVENT_ACTION_DOWN
678 && (entry->policyFlags & POLICY_FLAG_TRUSTED)
Jeff Brown0029c662011-03-30 02:25:18 -0700679 && (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
Jeff Browne46a0a42010-11-02 17:58:22 -0700680 if (mKeyRepeatState.lastKeyEntry
681 && mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode) {
682 // We have seen two identical key downs in a row which indicates that the device
683 // driver is automatically generating key repeats itself. We take note of the
684 // repeat here, but we disable our own next key repeat timer since it is clear that
685 // we will not need to synthesize key repeats ourselves.
686 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
687 resetKeyRepeatLocked();
688 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
689 } else {
690 // Not a repeat. Save key down state in case we do see a repeat later.
691 resetKeyRepeatLocked();
Jeff Brown214eaf42011-05-26 19:17:02 -0700692 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
Jeff Browne46a0a42010-11-02 17:58:22 -0700693 }
694 mKeyRepeatState.lastKeyEntry = entry;
695 entry->refCount += 1;
696 } else if (! entry->syntheticRepeat) {
697 resetKeyRepeatLocked();
698 }
699
Jeff Browne2e01262011-03-02 20:34:30 -0800700 if (entry->repeatCount == 1) {
701 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
702 } else {
703 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
704 }
705
Jeff Browne46a0a42010-11-02 17:58:22 -0700706 entry->dispatchInProgress = true;
Jeff Browne46a0a42010-11-02 17:58:22 -0700707
708 logOutboundKeyDetailsLocked("dispatchKey - ", entry);
709 }
710
Jeff Brown905805a2011-10-12 13:57:59 -0700711 // Handle case where the policy asked us to try again later last time.
712 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
713 if (currentTime < entry->interceptKeyWakeupTime) {
714 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
715 *nextWakeupTime = entry->interceptKeyWakeupTime;
716 }
717 return false; // wait until next wakeup
718 }
719 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
720 entry->interceptKeyWakeupTime = 0;
721 }
722
Jeff Brown54a18252010-09-16 14:07:33 -0700723 // Give the policy a chance to intercept the key.
724 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
Jeff Browne20c9e02010-10-11 14:20:19 -0700725 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Jeff Brown54a18252010-09-16 14:07:33 -0700726 CommandEntry* commandEntry = postCommandLocked(
727 & InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
Jeff Brown9302c872011-07-13 22:51:29 -0700728 if (mFocusedWindowHandle != NULL) {
729 commandEntry->inputWindowHandle = mFocusedWindowHandle;
Jeff Brown54a18252010-09-16 14:07:33 -0700730 }
731 commandEntry->keyEntry = entry;
732 entry->refCount += 1;
733 return false; // wait for the command to run
734 } else {
735 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
736 }
737 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Jeff Browne20c9e02010-10-11 14:20:19 -0700738 if (*dropReason == DROP_REASON_NOT_DROPPED) {
739 *dropReason = DROP_REASON_POLICY;
740 }
Jeff Brown54a18252010-09-16 14:07:33 -0700741 }
742
743 // Clean up if dropping the event.
Jeff Browne20c9e02010-10-11 14:20:19 -0700744 if (*dropReason != DROP_REASON_NOT_DROPPED) {
Jeff Brown3122e442010-10-11 23:32:49 -0700745 setInjectionResultLocked(entry, *dropReason == DROP_REASON_POLICY
746 ? INPUT_EVENT_INJECTION_SUCCEEDED : INPUT_EVENT_INJECTION_FAILED);
Jeff Brown54a18252010-09-16 14:07:33 -0700747 return true;
748 }
749
Jeff Brownb88102f2010-09-08 11:49:43 -0700750 // Identify targets.
Jeff Browne9bb9be2012-02-06 15:47:55 -0800751 Vector<InputTarget> inputTargets;
752 int32_t injectionResult = findFocusedWindowTargetsLocked(currentTime,
753 entry, inputTargets, nextWakeupTime);
754 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
755 return false;
Jeff Brownb88102f2010-09-08 11:49:43 -0700756 }
757
Jeff Browne9bb9be2012-02-06 15:47:55 -0800758 setInjectionResultLocked(entry, injectionResult);
759 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
760 return true;
761 }
762
763 addMonitoringTargetsLocked(inputTargets);
764
Jeff Brownb88102f2010-09-08 11:49:43 -0700765 // Dispatch the key.
Jeff Browne9bb9be2012-02-06 15:47:55 -0800766 dispatchEventLocked(currentTime, entry, inputTargets);
Jeff Brownb88102f2010-09-08 11:49:43 -0700767 return true;
768}
769
770void InputDispatcher::logOutboundKeyDetailsLocked(const char* prefix, const KeyEntry* entry) {
771#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +0000772 ALOGD("%seventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, "
Jeff Brownb88102f2010-09-08 11:49:43 -0700773 "action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, "
Jeff Browne46a0a42010-11-02 17:58:22 -0700774 "repeatCount=%d, downTime=%lld",
Jeff Brownb88102f2010-09-08 11:49:43 -0700775 prefix,
776 entry->eventTime, entry->deviceId, entry->source, entry->policyFlags,
777 entry->action, entry->flags, entry->keyCode, entry->scanCode, entry->metaState,
Jeff Browne46a0a42010-11-02 17:58:22 -0700778 entry->repeatCount, entry->downTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700779#endif
780}
781
782bool InputDispatcher::dispatchMotionLocked(
Jeff Browne20c9e02010-10-11 14:20:19 -0700783 nsecs_t currentTime, MotionEntry* entry, DropReason* dropReason, nsecs_t* nextWakeupTime) {
Jeff Browne46a0a42010-11-02 17:58:22 -0700784 // Preprocessing.
785 if (! entry->dispatchInProgress) {
786 entry->dispatchInProgress = true;
Jeff Browne46a0a42010-11-02 17:58:22 -0700787
788 logOutboundMotionDetailsLocked("dispatchMotion - ", entry);
789 }
790
Jeff Brown54a18252010-09-16 14:07:33 -0700791 // Clean up if dropping the event.
Jeff Browne20c9e02010-10-11 14:20:19 -0700792 if (*dropReason != DROP_REASON_NOT_DROPPED) {
Jeff Brown3122e442010-10-11 23:32:49 -0700793 setInjectionResultLocked(entry, *dropReason == DROP_REASON_POLICY
794 ? INPUT_EVENT_INJECTION_SUCCEEDED : INPUT_EVENT_INJECTION_FAILED);
Jeff Brown54a18252010-09-16 14:07:33 -0700795 return true;
796 }
797
Jeff Brownb88102f2010-09-08 11:49:43 -0700798 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
799
800 // Identify targets.
Jeff Browne9bb9be2012-02-06 15:47:55 -0800801 Vector<InputTarget> inputTargets;
802
Jeff Browncc0c1592011-02-19 05:07:28 -0800803 bool conflictingPointerActions = false;
Jeff Browne9bb9be2012-02-06 15:47:55 -0800804 int32_t injectionResult;
805 if (isPointerEvent) {
806 // Pointer event. (eg. touchscreen)
807 injectionResult = findTouchedWindowTargetsLocked(currentTime,
808 entry, inputTargets, nextWakeupTime, &conflictingPointerActions);
809 } else {
810 // Non touch event. (eg. trackball)
811 injectionResult = findFocusedWindowTargetsLocked(currentTime,
812 entry, inputTargets, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700813 }
Jeff Browne9bb9be2012-02-06 15:47:55 -0800814 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
815 return false;
816 }
817
818 setInjectionResultLocked(entry, injectionResult);
819 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
820 return true;
821 }
822
823 addMonitoringTargetsLocked(inputTargets);
Jeff Brownb88102f2010-09-08 11:49:43 -0700824
825 // Dispatch the motion.
Jeff Browncc0c1592011-02-19 05:07:28 -0800826 if (conflictingPointerActions) {
Jeff Brownda3d5a92011-03-29 15:11:34 -0700827 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
828 "conflicting pointer actions");
829 synthesizeCancelationEventsForAllConnectionsLocked(options);
Jeff Browncc0c1592011-02-19 05:07:28 -0800830 }
Jeff Browne9bb9be2012-02-06 15:47:55 -0800831 dispatchEventLocked(currentTime, entry, inputTargets);
Jeff Brownb88102f2010-09-08 11:49:43 -0700832 return true;
833}
834
835
836void InputDispatcher::logOutboundMotionDetailsLocked(const char* prefix, const MotionEntry* entry) {
837#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +0000838 ALOGD("%seventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, "
Jeff Brown85a31762010-09-01 17:01:00 -0700839 "action=0x%x, flags=0x%x, "
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700840 "metaState=0x%x, buttonState=0x%x, "
841 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%lld",
Jeff Brownb88102f2010-09-08 11:49:43 -0700842 prefix,
Jeff Brown85a31762010-09-01 17:01:00 -0700843 entry->eventTime, entry->deviceId, entry->source, entry->policyFlags,
844 entry->action, entry->flags,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700845 entry->metaState, entry->buttonState,
846 entry->edgeFlags, entry->xPrecision, entry->yPrecision,
Jeff Brown46b9ac02010-04-22 18:58:52 -0700847 entry->downTime);
848
Jeff Brown46b9ac02010-04-22 18:58:52 -0700849 for (uint32_t i = 0; i < entry->pointerCount; i++) {
Steve Block5baa3a62011-12-20 16:23:08 +0000850 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700851 "x=%f, y=%f, pressure=%f, size=%f, "
Jeff Brown85a31762010-09-01 17:01:00 -0700852 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
Jeff Brown8d608662010-08-30 03:02:23 -0700853 "orientation=%f",
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700854 i, entry->pointerProperties[i].id,
855 entry->pointerProperties[i].toolType,
Jeff Brown3241b6b2012-02-03 15:08:02 -0800856 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
857 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
858 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
859 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
860 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
861 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
862 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
863 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
864 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Jeff Brown46b9ac02010-04-22 18:58:52 -0700865 }
866#endif
Jeff Brown46b9ac02010-04-22 18:58:52 -0700867}
868
Jeff Browne9bb9be2012-02-06 15:47:55 -0800869void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
870 EventEntry* eventEntry, const Vector<InputTarget>& inputTargets) {
Jeff Brown46b9ac02010-04-22 18:58:52 -0700871#if DEBUG_DISPATCH_CYCLE
Jeff Brown3241b6b2012-02-03 15:08:02 -0800872 ALOGD("dispatchEventToCurrentInputTargets");
Jeff Brown46b9ac02010-04-22 18:58:52 -0700873#endif
874
Steve Blockec193de2012-01-09 18:35:44 +0000875 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
Jeff Brown9c3cda02010-06-15 01:31:58 -0700876
Jeff Browne2fe69e2010-10-18 13:21:23 -0700877 pokeUserActivityLocked(eventEntry);
878
Jeff Browne9bb9be2012-02-06 15:47:55 -0800879 for (size_t i = 0; i < inputTargets.size(); i++) {
880 const InputTarget& inputTarget = inputTargets.itemAt(i);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700881
Jeff Brown519e0242010-09-15 15:18:56 -0700882 ssize_t connectionIndex = getConnectionIndexLocked(inputTarget.inputChannel);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700883 if (connectionIndex >= 0) {
Jeff Browncbee6d62012-02-03 20:11:27 -0800884 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
Jeff Brown3241b6b2012-02-03 15:08:02 -0800885 prepareDispatchCycleLocked(currentTime, connection, eventEntry, &inputTarget);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700886 } else {
Jeff Brownb6997262010-10-08 22:31:17 -0700887#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +0000888 ALOGD("Dropping event delivery to target with channel '%s' because it "
Jeff Brownb6997262010-10-08 22:31:17 -0700889 "is no longer registered with the input dispatcher.",
Jeff Brown46b9ac02010-04-22 18:58:52 -0700890 inputTarget.inputChannel->getName().string());
Jeff Brownb6997262010-10-08 22:31:17 -0700891#endif
Jeff Brown46b9ac02010-04-22 18:58:52 -0700892 }
893 }
894}
895
Jeff Brownb88102f2010-09-08 11:49:43 -0700896int32_t InputDispatcher::handleTargetsNotReadyLocked(nsecs_t currentTime,
Jeff Brown9302c872011-07-13 22:51:29 -0700897 const EventEntry* entry,
898 const sp<InputApplicationHandle>& applicationHandle,
899 const sp<InputWindowHandle>& windowHandle,
Jeff Brownb88102f2010-09-08 11:49:43 -0700900 nsecs_t* nextWakeupTime) {
Jeff Brown9302c872011-07-13 22:51:29 -0700901 if (applicationHandle == NULL && windowHandle == NULL) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700902 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY) {
903#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +0000904 ALOGD("Waiting for system to become ready for input.");
Jeff Brownb88102f2010-09-08 11:49:43 -0700905#endif
906 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY;
907 mInputTargetWaitStartTime = currentTime;
908 mInputTargetWaitTimeoutTime = LONG_LONG_MAX;
909 mInputTargetWaitTimeoutExpired = false;
Jeff Brown9302c872011-07-13 22:51:29 -0700910 mInputTargetWaitApplicationHandle.clear();
Jeff Brownb88102f2010-09-08 11:49:43 -0700911 }
912 } else {
913 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
914#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +0000915 ALOGD("Waiting for application to become ready for input: %s",
Jeff Brown9302c872011-07-13 22:51:29 -0700916 getApplicationWindowLabelLocked(applicationHandle, windowHandle).string());
Jeff Brownb88102f2010-09-08 11:49:43 -0700917#endif
Jeff Browncc4f7db2011-08-30 20:34:48 -0700918 nsecs_t timeout;
919 if (windowHandle != NULL) {
920 timeout = windowHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
921 } else if (applicationHandle != NULL) {
922 timeout = applicationHandle->getDispatchingTimeout(
923 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
924 } else {
925 timeout = DEFAULT_INPUT_DISPATCHING_TIMEOUT;
926 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700927
928 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY;
929 mInputTargetWaitStartTime = currentTime;
930 mInputTargetWaitTimeoutTime = currentTime + timeout;
931 mInputTargetWaitTimeoutExpired = false;
Jeff Brown9302c872011-07-13 22:51:29 -0700932 mInputTargetWaitApplicationHandle.clear();
Jeff Brown928e0542011-01-10 11:17:36 -0800933
Jeff Brown9302c872011-07-13 22:51:29 -0700934 if (windowHandle != NULL) {
935 mInputTargetWaitApplicationHandle = windowHandle->inputApplicationHandle;
Jeff Brown928e0542011-01-10 11:17:36 -0800936 }
Jeff Brown9302c872011-07-13 22:51:29 -0700937 if (mInputTargetWaitApplicationHandle == NULL && applicationHandle != NULL) {
938 mInputTargetWaitApplicationHandle = applicationHandle;
Jeff Brown928e0542011-01-10 11:17:36 -0800939 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700940 }
941 }
942
943 if (mInputTargetWaitTimeoutExpired) {
944 return INPUT_EVENT_INJECTION_TIMED_OUT;
945 }
946
947 if (currentTime >= mInputTargetWaitTimeoutTime) {
Jeff Brown9302c872011-07-13 22:51:29 -0700948 onANRLocked(currentTime, applicationHandle, windowHandle,
949 entry->eventTime, mInputTargetWaitStartTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700950
951 // Force poll loop to wake up immediately on next iteration once we get the
952 // ANR response back from the policy.
953 *nextWakeupTime = LONG_LONG_MIN;
954 return INPUT_EVENT_INJECTION_PENDING;
955 } else {
956 // Force poll loop to wake up when timeout is due.
957 if (mInputTargetWaitTimeoutTime < *nextWakeupTime) {
958 *nextWakeupTime = mInputTargetWaitTimeoutTime;
959 }
960 return INPUT_EVENT_INJECTION_PENDING;
961 }
962}
963
Jeff Brown519e0242010-09-15 15:18:56 -0700964void InputDispatcher::resumeAfterTargetsNotReadyTimeoutLocked(nsecs_t newTimeout,
965 const sp<InputChannel>& inputChannel) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700966 if (newTimeout > 0) {
967 // Extend the timeout.
968 mInputTargetWaitTimeoutTime = now() + newTimeout;
969 } else {
970 // Give up.
971 mInputTargetWaitTimeoutExpired = true;
Jeff Brown519e0242010-09-15 15:18:56 -0700972
973 // Input state will not be realistic. Mark it out of sync.
Jeff Browndc3e0052010-09-16 11:02:16 -0700974 if (inputChannel.get()) {
975 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
976 if (connectionIndex >= 0) {
Jeff Browncbee6d62012-02-03 20:11:27 -0800977 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
Jeff Brownf44e3942012-04-20 11:33:27 -0700978 sp<InputWindowHandle> windowHandle = connection->inputWindowHandle;
979
980 if (windowHandle != NULL) {
981 mTouchState.removeWindow(windowHandle);
982 }
983
Jeff Brown00045a72010-12-09 18:10:30 -0800984 if (connection->status == Connection::STATUS_NORMAL) {
Jeff Brownda3d5a92011-03-29 15:11:34 -0700985 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
Jeff Brown00045a72010-12-09 18:10:30 -0800986 "application not responding");
Jeff Brownda3d5a92011-03-29 15:11:34 -0700987 synthesizeCancelationEventsForConnectionLocked(connection, options);
Jeff Brown00045a72010-12-09 18:10:30 -0800988 }
Jeff Browndc3e0052010-09-16 11:02:16 -0700989 }
Jeff Brown519e0242010-09-15 15:18:56 -0700990 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700991 }
992}
993
Jeff Brown519e0242010-09-15 15:18:56 -0700994nsecs_t InputDispatcher::getTimeSpentWaitingForApplicationLocked(
Jeff Brownb88102f2010-09-08 11:49:43 -0700995 nsecs_t currentTime) {
996 if (mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
997 return currentTime - mInputTargetWaitStartTime;
998 }
999 return 0;
1000}
1001
1002void InputDispatcher::resetANRTimeoutsLocked() {
1003#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001004 ALOGD("Resetting ANR timeouts.");
Jeff Brownb88102f2010-09-08 11:49:43 -07001005#endif
1006
Jeff Brownb88102f2010-09-08 11:49:43 -07001007 // Reset input target wait timeout.
1008 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_NONE;
Jeff Brown5ea29ab2011-07-27 11:50:51 -07001009 mInputTargetWaitApplicationHandle.clear();
Jeff Brownb88102f2010-09-08 11:49:43 -07001010}
1011
Jeff Brown01ce2e92010-09-26 22:20:12 -07001012int32_t InputDispatcher::findFocusedWindowTargetsLocked(nsecs_t currentTime,
Jeff Browne9bb9be2012-02-06 15:47:55 -08001013 const EventEntry* entry, Vector<InputTarget>& inputTargets, nsecs_t* nextWakeupTime) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001014 int32_t injectionResult;
1015
1016 // If there is no currently focused window and no focused application
1017 // then drop the event.
Jeff Brown9302c872011-07-13 22:51:29 -07001018 if (mFocusedWindowHandle == NULL) {
1019 if (mFocusedApplicationHandle != NULL) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001020#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001021 ALOGD("Waiting because there is no focused window but there is a "
Jeff Brown519e0242010-09-15 15:18:56 -07001022 "focused application that may eventually add a window: %s.",
Jeff Brown9302c872011-07-13 22:51:29 -07001023 getApplicationWindowLabelLocked(mFocusedApplicationHandle, NULL).string());
Jeff Brownb88102f2010-09-08 11:49:43 -07001024#endif
1025 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brown9302c872011-07-13 22:51:29 -07001026 mFocusedApplicationHandle, NULL, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -07001027 goto Unresponsive;
1028 }
1029
Steve Block6215d3f2012-01-04 20:05:49 +00001030 ALOGI("Dropping event because there is no focused window or focused application.");
Jeff Brownb88102f2010-09-08 11:49:43 -07001031 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1032 goto Failed;
1033 }
1034
1035 // Check permissions.
Jeff Brown9302c872011-07-13 22:51:29 -07001036 if (! checkInjectionPermission(mFocusedWindowHandle, entry->injectionState)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001037 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1038 goto Failed;
1039 }
1040
1041 // If the currently focused window is paused then keep waiting.
Jeff Browncc4f7db2011-08-30 20:34:48 -07001042 if (mFocusedWindowHandle->getInfo()->paused) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001043#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001044 ALOGD("Waiting because focused window is paused.");
Jeff Brownb88102f2010-09-08 11:49:43 -07001045#endif
1046 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brown9302c872011-07-13 22:51:29 -07001047 mFocusedApplicationHandle, mFocusedWindowHandle, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -07001048 goto Unresponsive;
1049 }
1050
Jeff Brown519e0242010-09-15 15:18:56 -07001051 // If the currently focused window is still working on previous events then keep waiting.
Jeff Brown0952c302012-02-13 13:48:59 -08001052 if (!isWindowReadyForMoreInputLocked(currentTime, mFocusedWindowHandle, entry)) {
Jeff Brown519e0242010-09-15 15:18:56 -07001053#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001054 ALOGD("Waiting because focused window still processing previous input.");
Jeff Brown519e0242010-09-15 15:18:56 -07001055#endif
1056 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brown9302c872011-07-13 22:51:29 -07001057 mFocusedApplicationHandle, mFocusedWindowHandle, nextWakeupTime);
Jeff Brown519e0242010-09-15 15:18:56 -07001058 goto Unresponsive;
1059 }
1060
Jeff Brownb88102f2010-09-08 11:49:43 -07001061 // Success! Output targets.
1062 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
Jeff Brown9302c872011-07-13 22:51:29 -07001063 addWindowTargetLocked(mFocusedWindowHandle,
Jeff Browne9bb9be2012-02-06 15:47:55 -08001064 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS, BitSet32(0),
1065 inputTargets);
Jeff Brownb88102f2010-09-08 11:49:43 -07001066
1067 // Done.
1068Failed:
1069Unresponsive:
Jeff Brown519e0242010-09-15 15:18:56 -07001070 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
1071 updateDispatchStatisticsLocked(currentTime, entry,
1072 injectionResult, timeSpentWaitingForApplication);
Jeff Brownb88102f2010-09-08 11:49:43 -07001073#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001074 ALOGD("findFocusedWindow finished: injectionResult=%d, "
Jeff Brown519e0242010-09-15 15:18:56 -07001075 "timeSpendWaitingForApplication=%0.1fms",
1076 injectionResult, timeSpentWaitingForApplication / 1000000.0);
Jeff Brownb88102f2010-09-08 11:49:43 -07001077#endif
1078 return injectionResult;
1079}
1080
Jeff Brown01ce2e92010-09-26 22:20:12 -07001081int32_t InputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime,
Jeff Browne9bb9be2012-02-06 15:47:55 -08001082 const MotionEntry* entry, Vector<InputTarget>& inputTargets, nsecs_t* nextWakeupTime,
1083 bool* outConflictingPointerActions) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001084 enum InjectionPermission {
1085 INJECTION_PERMISSION_UNKNOWN,
1086 INJECTION_PERMISSION_GRANTED,
1087 INJECTION_PERMISSION_DENIED
1088 };
1089
Jeff Brownb88102f2010-09-08 11:49:43 -07001090 nsecs_t startTime = now();
1091
1092 // For security reasons, we defer updating the touch state until we are sure that
1093 // event injection will be allowed.
1094 //
1095 // FIXME In the original code, screenWasOff could never be set to true.
1096 // The reason is that the POLICY_FLAG_WOKE_HERE
1097 // and POLICY_FLAG_BRIGHT_HERE flags were set only when preprocessing raw
1098 // EV_KEY, EV_REL and EV_ABS events. As it happens, the touch event was
1099 // actually enqueued using the policyFlags that appeared in the final EV_SYN
1100 // events upon which no preprocessing took place. So policyFlags was always 0.
1101 // In the new native input dispatcher we're a bit more careful about event
1102 // preprocessing so the touches we receive can actually have non-zero policyFlags.
1103 // Unfortunately we obtain undesirable behavior.
1104 //
1105 // Here's what happens:
1106 //
1107 // When the device dims in anticipation of going to sleep, touches
1108 // in windows which have FLAG_TOUCHABLE_WHEN_WAKING cause
1109 // the device to brighten and reset the user activity timer.
1110 // Touches on other windows (such as the launcher window)
1111 // are dropped. Then after a moment, the device goes to sleep. Oops.
1112 //
1113 // Also notice how screenWasOff was being initialized using POLICY_FLAG_BRIGHT_HERE
1114 // instead of POLICY_FLAG_WOKE_HERE...
1115 //
1116 bool screenWasOff = false; // original policy: policyFlags & POLICY_FLAG_BRIGHT_HERE;
1117
1118 int32_t action = entry->action;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001119 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Jeff Brownb88102f2010-09-08 11:49:43 -07001120
1121 // Update the touch state as needed based on the properties of the touch event.
Jeff Brown01ce2e92010-09-26 22:20:12 -07001122 int32_t injectionResult = INPUT_EVENT_INJECTION_PENDING;
1123 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
Jeff Brown9302c872011-07-13 22:51:29 -07001124 sp<InputWindowHandle> newHoverWindowHandle;
Jeff Browncc0c1592011-02-19 05:07:28 -08001125
1126 bool isSplit = mTouchState.split;
Jeff Brown2717eff2011-06-30 23:53:07 -07001127 bool switchedDevice = mTouchState.deviceId >= 0
1128 && (mTouchState.deviceId != entry->deviceId
1129 || mTouchState.source != entry->source);
Jeff Browna032cc02011-03-07 16:56:21 -08001130 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE
1131 || maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER
1132 || maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1133 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN
1134 || maskedAction == AMOTION_EVENT_ACTION_SCROLL
1135 || isHoverAction);
Jeff Brown81346812011-06-28 20:08:48 -07001136 bool wrongDevice = false;
Jeff Browna032cc02011-03-07 16:56:21 -08001137 if (newGesture) {
Jeff Browncc0c1592011-02-19 05:07:28 -08001138 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Jeff Brown81346812011-06-28 20:08:48 -07001139 if (switchedDevice && mTouchState.down && !down) {
1140#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001141 ALOGD("Dropping event because a pointer for a different device is already down.");
Jeff Brown81346812011-06-28 20:08:48 -07001142#endif
Jeff Browncc0c1592011-02-19 05:07:28 -08001143 mTempTouchState.copyFrom(mTouchState);
Jeff Brown81346812011-06-28 20:08:48 -07001144 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1145 switchedDevice = false;
1146 wrongDevice = true;
1147 goto Failed;
Jeff Browncc0c1592011-02-19 05:07:28 -08001148 }
Jeff Brown81346812011-06-28 20:08:48 -07001149 mTempTouchState.reset();
1150 mTempTouchState.down = down;
1151 mTempTouchState.deviceId = entry->deviceId;
1152 mTempTouchState.source = entry->source;
1153 isSplit = false;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001154 } else {
1155 mTempTouchState.copyFrom(mTouchState);
Jeff Browncc0c1592011-02-19 05:07:28 -08001156 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001157
Jeff Browna032cc02011-03-07 16:56:21 -08001158 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
Jeff Brown33bbfd22011-02-24 20:55:35 -08001159 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
Jeff Brownb88102f2010-09-08 11:49:43 -07001160
Jeff Brown01ce2e92010-09-26 22:20:12 -07001161 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Jeff Brown3241b6b2012-02-03 15:08:02 -08001162 int32_t x = int32_t(entry->pointerCoords[pointerIndex].
Jeff Brownebbd5d12011-02-17 13:01:34 -08001163 getAxisValue(AMOTION_EVENT_AXIS_X));
Jeff Brown3241b6b2012-02-03 15:08:02 -08001164 int32_t y = int32_t(entry->pointerCoords[pointerIndex].
Jeff Brownebbd5d12011-02-17 13:01:34 -08001165 getAxisValue(AMOTION_EVENT_AXIS_Y));
Jeff Brown9302c872011-07-13 22:51:29 -07001166 sp<InputWindowHandle> newTouchedWindowHandle;
1167 sp<InputWindowHandle> topErrorWindowHandle;
Jeff Browna032cc02011-03-07 16:56:21 -08001168 bool isTouchModal = false;
Jeff Brownb88102f2010-09-08 11:49:43 -07001169
1170 // Traverse windows from front to back to find touched window and outside targets.
Jeff Brown9302c872011-07-13 22:51:29 -07001171 size_t numWindows = mWindowHandles.size();
Jeff Brownb88102f2010-09-08 11:49:43 -07001172 for (size_t i = 0; i < numWindows; i++) {
Jeff Brown9302c872011-07-13 22:51:29 -07001173 sp<InputWindowHandle> windowHandle = mWindowHandles.itemAt(i);
Jeff Browncc4f7db2011-08-30 20:34:48 -07001174 const InputWindowInfo* windowInfo = windowHandle->getInfo();
1175 int32_t flags = windowInfo->layoutParamsFlags;
Jeff Brownb88102f2010-09-08 11:49:43 -07001176
Jeff Browncc4f7db2011-08-30 20:34:48 -07001177 if (flags & InputWindowInfo::FLAG_SYSTEM_ERROR) {
Jeff Brown9302c872011-07-13 22:51:29 -07001178 if (topErrorWindowHandle == NULL) {
1179 topErrorWindowHandle = windowHandle;
Jeff Brownb88102f2010-09-08 11:49:43 -07001180 }
1181 }
1182
Jeff Browncc4f7db2011-08-30 20:34:48 -07001183 if (windowInfo->visible) {
1184 if (! (flags & InputWindowInfo::FLAG_NOT_TOUCHABLE)) {
1185 isTouchModal = (flags & (InputWindowInfo::FLAG_NOT_FOCUSABLE
1186 | InputWindowInfo::FLAG_NOT_TOUCH_MODAL)) == 0;
1187 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
Jeff Brown9302c872011-07-13 22:51:29 -07001188 if (! screenWasOff
Jeff Browncc4f7db2011-08-30 20:34:48 -07001189 || (flags & InputWindowInfo::FLAG_TOUCHABLE_WHEN_WAKING)) {
Jeff Brown9302c872011-07-13 22:51:29 -07001190 newTouchedWindowHandle = windowHandle;
Jeff Brownb88102f2010-09-08 11:49:43 -07001191 }
1192 break; // found touched window, exit window loop
1193 }
1194 }
1195
Jeff Brown01ce2e92010-09-26 22:20:12 -07001196 if (maskedAction == AMOTION_EVENT_ACTION_DOWN
Jeff Browncc4f7db2011-08-30 20:34:48 -07001197 && (flags & InputWindowInfo::FLAG_WATCH_OUTSIDE_TOUCH)) {
Jeff Browna032cc02011-03-07 16:56:21 -08001198 int32_t outsideTargetFlags = InputTarget::FLAG_DISPATCH_AS_OUTSIDE;
Jeff Brown9302c872011-07-13 22:51:29 -07001199 if (isWindowObscuredAtPointLocked(windowHandle, x, y)) {
Jeff Brown19dfc832010-10-05 12:26:23 -07001200 outsideTargetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1201 }
1202
Jeff Brown9302c872011-07-13 22:51:29 -07001203 mTempTouchState.addOrUpdateWindow(
1204 windowHandle, outsideTargetFlags, BitSet32(0));
Jeff Brownb88102f2010-09-08 11:49:43 -07001205 }
1206 }
1207 }
1208
1209 // If there is an error window but it is not taking focus (typically because
1210 // it is invisible) then wait for it. Any other focused window may in
1211 // fact be in ANR state.
Jeff Brown9302c872011-07-13 22:51:29 -07001212 if (topErrorWindowHandle != NULL && newTouchedWindowHandle != topErrorWindowHandle) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001213#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001214 ALOGD("Waiting because system error window is pending.");
Jeff Brownb88102f2010-09-08 11:49:43 -07001215#endif
1216 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
1217 NULL, NULL, nextWakeupTime);
1218 injectionPermission = INJECTION_PERMISSION_UNKNOWN;
1219 goto Unresponsive;
1220 }
1221
Jeff Brown01ce2e92010-09-26 22:20:12 -07001222 // Figure out whether splitting will be allowed for this window.
Jeff Browncc4f7db2011-08-30 20:34:48 -07001223 if (newTouchedWindowHandle != NULL
1224 && newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001225 // New window supports splitting.
1226 isSplit = true;
1227 } else if (isSplit) {
1228 // New window does not support splitting but we have already split events.
Jeff Brown8249fc62012-05-24 18:57:32 -07001229 // Ignore the new window.
1230 newTouchedWindowHandle = NULL;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001231 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001232
Jeff Brown8249fc62012-05-24 18:57:32 -07001233 // Handle the case where we did not find a window.
Jeff Brown9302c872011-07-13 22:51:29 -07001234 if (newTouchedWindowHandle == NULL) {
Jeff Brown8249fc62012-05-24 18:57:32 -07001235 // Try to assign the pointer to the first foreground window we find, if there is one.
1236 newTouchedWindowHandle = mTempTouchState.getFirstForegroundWindowHandle();
1237 if (newTouchedWindowHandle == NULL) {
1238 // There is no touched window. If this is an initial down event
1239 // then wait for a window to appear that will handle the touch. This is
1240 // to ensure that we report an ANR in the case where an application has started
1241 // but not yet put up a window and the user is starting to get impatient.
1242 if (maskedAction == AMOTION_EVENT_ACTION_DOWN
1243 && mFocusedApplicationHandle != NULL) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001244#if DEBUG_FOCUS
Jeff Brown8249fc62012-05-24 18:57:32 -07001245 ALOGD("Waiting because there is no touched window but there is a "
1246 "focused application that may eventually add a new window: %s.",
1247 getApplicationWindowLabelLocked(
1248 mFocusedApplicationHandle, NULL).string());
Jeff Brownb88102f2010-09-08 11:49:43 -07001249#endif
Jeff Brown8249fc62012-05-24 18:57:32 -07001250 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
1251 mFocusedApplicationHandle, NULL, nextWakeupTime);
1252 goto Unresponsive;
1253 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001254
Jeff Brown8249fc62012-05-24 18:57:32 -07001255 ALOGI("Dropping event because there is no touched window.");
1256 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1257 goto Failed;
1258 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001259 }
1260
Jeff Brown19dfc832010-10-05 12:26:23 -07001261 // Set target flags.
Jeff Browna032cc02011-03-07 16:56:21 -08001262 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
Jeff Brown19dfc832010-10-05 12:26:23 -07001263 if (isSplit) {
1264 targetFlags |= InputTarget::FLAG_SPLIT;
1265 }
Jeff Brown9302c872011-07-13 22:51:29 -07001266 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
Jeff Brown19dfc832010-10-05 12:26:23 -07001267 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1268 }
1269
Jeff Browna032cc02011-03-07 16:56:21 -08001270 // Update hover state.
1271 if (isHoverAction) {
Jeff Brown9302c872011-07-13 22:51:29 -07001272 newHoverWindowHandle = newTouchedWindowHandle;
Jeff Browna032cc02011-03-07 16:56:21 -08001273 } else if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
Jeff Brown9302c872011-07-13 22:51:29 -07001274 newHoverWindowHandle = mLastHoverWindowHandle;
Jeff Browna032cc02011-03-07 16:56:21 -08001275 }
1276
Jeff Brown01ce2e92010-09-26 22:20:12 -07001277 // Update the temporary touch state.
1278 BitSet32 pointerIds;
1279 if (isSplit) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07001280 uint32_t pointerId = entry->pointerProperties[pointerIndex].id;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001281 pointerIds.markBit(pointerId);
Jeff Brownb88102f2010-09-08 11:49:43 -07001282 }
Jeff Brown9302c872011-07-13 22:51:29 -07001283 mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Jeff Brownb88102f2010-09-08 11:49:43 -07001284 } else {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001285 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
Jeff Brownb88102f2010-09-08 11:49:43 -07001286
1287 // If the pointer is not currently down, then ignore the event.
Jeff Brown01ce2e92010-09-26 22:20:12 -07001288 if (! mTempTouchState.down) {
Jeff Browna2cc28d2011-03-25 11:58:46 -07001289#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001290 ALOGD("Dropping event because the pointer is not down or we previously "
Jeff Brown76860e32010-10-25 17:37:46 -07001291 "dropped the pointer down event.");
1292#endif
Jeff Brownb88102f2010-09-08 11:49:43 -07001293 injectionResult = INPUT_EVENT_INJECTION_FAILED;
Jeff Brownb88102f2010-09-08 11:49:43 -07001294 goto Failed;
1295 }
Jeff Brown98db5fa2011-06-08 15:37:10 -07001296
1297 // Check whether touches should slip outside of the current foreground window.
1298 if (maskedAction == AMOTION_EVENT_ACTION_MOVE
1299 && entry->pointerCount == 1
1300 && mTempTouchState.isSlippery()) {
Jeff Brown3241b6b2012-02-03 15:08:02 -08001301 int32_t x = int32_t(entry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
1302 int32_t y = int32_t(entry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Jeff Brown98db5fa2011-06-08 15:37:10 -07001303
Jeff Brown9302c872011-07-13 22:51:29 -07001304 sp<InputWindowHandle> oldTouchedWindowHandle =
1305 mTempTouchState.getFirstForegroundWindowHandle();
1306 sp<InputWindowHandle> newTouchedWindowHandle = findTouchedWindowAtLocked(x, y);
1307 if (oldTouchedWindowHandle != newTouchedWindowHandle
1308 && newTouchedWindowHandle != NULL) {
Jeff Brown98db5fa2011-06-08 15:37:10 -07001309#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001310 ALOGD("Touch is slipping out of window %s into window %s.",
Jeff Browncc4f7db2011-08-30 20:34:48 -07001311 oldTouchedWindowHandle->getName().string(),
1312 newTouchedWindowHandle->getName().string());
Jeff Brown98db5fa2011-06-08 15:37:10 -07001313#endif
1314 // Make a slippery exit from the old window.
Jeff Brown9302c872011-07-13 22:51:29 -07001315 mTempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
Jeff Brown98db5fa2011-06-08 15:37:10 -07001316 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT, BitSet32(0));
1317
1318 // Make a slippery entrance into the new window.
Jeff Browncc4f7db2011-08-30 20:34:48 -07001319 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Jeff Brown98db5fa2011-06-08 15:37:10 -07001320 isSplit = true;
1321 }
1322
1323 int32_t targetFlags = InputTarget::FLAG_FOREGROUND
1324 | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
1325 if (isSplit) {
1326 targetFlags |= InputTarget::FLAG_SPLIT;
1327 }
Jeff Brown9302c872011-07-13 22:51:29 -07001328 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
Jeff Brown98db5fa2011-06-08 15:37:10 -07001329 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1330 }
1331
1332 BitSet32 pointerIds;
1333 if (isSplit) {
1334 pointerIds.markBit(entry->pointerProperties[0].id);
1335 }
Jeff Brown9302c872011-07-13 22:51:29 -07001336 mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Jeff Brown98db5fa2011-06-08 15:37:10 -07001337 }
1338 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001339 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001340
Jeff Brown9302c872011-07-13 22:51:29 -07001341 if (newHoverWindowHandle != mLastHoverWindowHandle) {
Jeff Browna032cc02011-03-07 16:56:21 -08001342 // Let the previous window know that the hover sequence is over.
Jeff Brown9302c872011-07-13 22:51:29 -07001343 if (mLastHoverWindowHandle != NULL) {
Jeff Browna032cc02011-03-07 16:56:21 -08001344#if DEBUG_HOVER
Steve Block5baa3a62011-12-20 16:23:08 +00001345 ALOGD("Sending hover exit event to window %s.",
Jeff Browncc4f7db2011-08-30 20:34:48 -07001346 mLastHoverWindowHandle->getName().string());
Jeff Browna032cc02011-03-07 16:56:21 -08001347#endif
Jeff Brown9302c872011-07-13 22:51:29 -07001348 mTempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
Jeff Browna032cc02011-03-07 16:56:21 -08001349 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
1350 }
1351
1352 // Let the new window know that the hover sequence is starting.
Jeff Brown9302c872011-07-13 22:51:29 -07001353 if (newHoverWindowHandle != NULL) {
Jeff Browna032cc02011-03-07 16:56:21 -08001354#if DEBUG_HOVER
Steve Block5baa3a62011-12-20 16:23:08 +00001355 ALOGD("Sending hover enter event to window %s.",
Jeff Browncc4f7db2011-08-30 20:34:48 -07001356 newHoverWindowHandle->getName().string());
Jeff Browna032cc02011-03-07 16:56:21 -08001357#endif
Jeff Brown9302c872011-07-13 22:51:29 -07001358 mTempTouchState.addOrUpdateWindow(newHoverWindowHandle,
Jeff Browna032cc02011-03-07 16:56:21 -08001359 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER, BitSet32(0));
1360 }
1361 }
1362
Jeff Brown01ce2e92010-09-26 22:20:12 -07001363 // Check permission to inject into all touched foreground windows and ensure there
1364 // is at least one touched foreground window.
1365 {
1366 bool haveForegroundWindow = false;
1367 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1368 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1369 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1370 haveForegroundWindow = true;
Jeff Brown9302c872011-07-13 22:51:29 -07001371 if (! checkInjectionPermission(touchedWindow.windowHandle,
1372 entry->injectionState)) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001373 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1374 injectionPermission = INJECTION_PERMISSION_DENIED;
1375 goto Failed;
1376 }
1377 }
1378 }
1379 if (! haveForegroundWindow) {
Jeff Browna2cc28d2011-03-25 11:58:46 -07001380#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001381 ALOGD("Dropping event because there is no touched foreground window to receive it.");
Jeff Brownb88102f2010-09-08 11:49:43 -07001382#endif
1383 injectionResult = INPUT_EVENT_INJECTION_FAILED;
Jeff Brownb88102f2010-09-08 11:49:43 -07001384 goto Failed;
1385 }
1386
Jeff Brown01ce2e92010-09-26 22:20:12 -07001387 // Permission granted to injection into all touched foreground windows.
1388 injectionPermission = INJECTION_PERMISSION_GRANTED;
1389 }
Jeff Brown519e0242010-09-15 15:18:56 -07001390
Kenny Root7a9db182011-06-02 15:16:05 -07001391 // Check whether windows listening for outside touches are owned by the same UID. If it is
1392 // set the policy flag that we will not reveal coordinate information to this window.
1393 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
Jeff Brown9302c872011-07-13 22:51:29 -07001394 sp<InputWindowHandle> foregroundWindowHandle =
1395 mTempTouchState.getFirstForegroundWindowHandle();
Jeff Browncc4f7db2011-08-30 20:34:48 -07001396 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Kenny Root7a9db182011-06-02 15:16:05 -07001397 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1398 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1399 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
Jeff Brown9302c872011-07-13 22:51:29 -07001400 sp<InputWindowHandle> inputWindowHandle = touchedWindow.windowHandle;
Jeff Browncc4f7db2011-08-30 20:34:48 -07001401 if (inputWindowHandle->getInfo()->ownerUid != foregroundWindowUid) {
Jeff Brown9302c872011-07-13 22:51:29 -07001402 mTempTouchState.addOrUpdateWindow(inputWindowHandle,
Kenny Root7a9db182011-06-02 15:16:05 -07001403 InputTarget::FLAG_ZERO_COORDS, BitSet32(0));
1404 }
1405 }
1406 }
1407 }
1408
Jeff Brown01ce2e92010-09-26 22:20:12 -07001409 // Ensure all touched foreground windows are ready for new input.
1410 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1411 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1412 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1413 // If the touched window is paused then keep waiting.
Jeff Browncc4f7db2011-08-30 20:34:48 -07001414 if (touchedWindow.windowHandle->getInfo()->paused) {
Jeff Browna2cc28d2011-03-25 11:58:46 -07001415#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001416 ALOGD("Waiting because touched window is paused.");
Jeff Brown519e0242010-09-15 15:18:56 -07001417#endif
Jeff Brown01ce2e92010-09-26 22:20:12 -07001418 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brown9302c872011-07-13 22:51:29 -07001419 NULL, touchedWindow.windowHandle, nextWakeupTime);
Jeff Brown01ce2e92010-09-26 22:20:12 -07001420 goto Unresponsive;
1421 }
1422
1423 // If the touched window is still working on previous events then keep waiting.
Jeff Brown0952c302012-02-13 13:48:59 -08001424 if (!isWindowReadyForMoreInputLocked(currentTime, touchedWindow.windowHandle, entry)) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001425#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001426 ALOGD("Waiting because touched window still processing previous input.");
Jeff Brown01ce2e92010-09-26 22:20:12 -07001427#endif
1428 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brown9302c872011-07-13 22:51:29 -07001429 NULL, touchedWindow.windowHandle, nextWakeupTime);
Jeff Brown01ce2e92010-09-26 22:20:12 -07001430 goto Unresponsive;
1431 }
1432 }
1433 }
1434
1435 // If this is the first pointer going down and the touched window has a wallpaper
1436 // then also add the touched wallpaper windows so they are locked in for the duration
1437 // of the touch gesture.
Jeff Brown33bbfd22011-02-24 20:55:35 -08001438 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
1439 // engine only supports touch events. We would need to add a mechanism similar
1440 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
1441 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
Jeff Brown9302c872011-07-13 22:51:29 -07001442 sp<InputWindowHandle> foregroundWindowHandle =
1443 mTempTouchState.getFirstForegroundWindowHandle();
Jeff Browncc4f7db2011-08-30 20:34:48 -07001444 if (foregroundWindowHandle->getInfo()->hasWallpaper) {
Jeff Brown9302c872011-07-13 22:51:29 -07001445 for (size_t i = 0; i < mWindowHandles.size(); i++) {
1446 sp<InputWindowHandle> windowHandle = mWindowHandles.itemAt(i);
Jeff Browncc4f7db2011-08-30 20:34:48 -07001447 if (windowHandle->getInfo()->layoutParamsType
1448 == InputWindowInfo::TYPE_WALLPAPER) {
Jeff Brown9302c872011-07-13 22:51:29 -07001449 mTempTouchState.addOrUpdateWindow(windowHandle,
Jeff Browna032cc02011-03-07 16:56:21 -08001450 InputTarget::FLAG_WINDOW_IS_OBSCURED
1451 | InputTarget::FLAG_DISPATCH_AS_IS,
1452 BitSet32(0));
Jeff Brown01ce2e92010-09-26 22:20:12 -07001453 }
1454 }
1455 }
1456 }
1457
Jeff Brownb88102f2010-09-08 11:49:43 -07001458 // Success! Output targets.
1459 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
Jeff Brownb88102f2010-09-08 11:49:43 -07001460
Jeff Brown01ce2e92010-09-26 22:20:12 -07001461 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1462 const TouchedWindow& touchedWindow = mTempTouchState.windows.itemAt(i);
Jeff Brown9302c872011-07-13 22:51:29 -07001463 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Jeff Browne9bb9be2012-02-06 15:47:55 -08001464 touchedWindow.pointerIds, inputTargets);
Jeff Brownb88102f2010-09-08 11:49:43 -07001465 }
1466
Jeff Browna032cc02011-03-07 16:56:21 -08001467 // Drop the outside or hover touch windows since we will not care about them
1468 // in the next iteration.
1469 mTempTouchState.filterNonAsIsTouchWindows();
Jeff Brown01ce2e92010-09-26 22:20:12 -07001470
Jeff Brownb88102f2010-09-08 11:49:43 -07001471Failed:
1472 // Check injection permission once and for all.
1473 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001474 if (checkInjectionPermission(NULL, entry->injectionState)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001475 injectionPermission = INJECTION_PERMISSION_GRANTED;
1476 } else {
1477 injectionPermission = INJECTION_PERMISSION_DENIED;
1478 }
1479 }
1480
1481 // Update final pieces of touch state if the injector had permission.
1482 if (injectionPermission == INJECTION_PERMISSION_GRANTED) {
Jeff Brown95712852011-01-04 19:41:59 -08001483 if (!wrongDevice) {
Jeff Brown81346812011-06-28 20:08:48 -07001484 if (switchedDevice) {
1485#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001486 ALOGD("Conflicting pointer actions: Switched to a different device.");
Jeff Brown81346812011-06-28 20:08:48 -07001487#endif
1488 *outConflictingPointerActions = true;
1489 }
1490
1491 if (isHoverAction) {
1492 // Started hovering, therefore no longer down.
1493 if (mTouchState.down) {
1494#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001495 ALOGD("Conflicting pointer actions: Hover received while pointer was down.");
Jeff Brown81346812011-06-28 20:08:48 -07001496#endif
1497 *outConflictingPointerActions = true;
1498 }
1499 mTouchState.reset();
1500 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER
1501 || maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
1502 mTouchState.deviceId = entry->deviceId;
1503 mTouchState.source = entry->source;
1504 }
1505 } else if (maskedAction == AMOTION_EVENT_ACTION_UP
1506 || maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Jeff Brown95712852011-01-04 19:41:59 -08001507 // All pointers up or canceled.
Jeff Brown33bbfd22011-02-24 20:55:35 -08001508 mTouchState.reset();
Jeff Brown95712852011-01-04 19:41:59 -08001509 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1510 // First pointer went down.
1511 if (mTouchState.down) {
Jeff Brownb6997262010-10-08 22:31:17 -07001512#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001513 ALOGD("Conflicting pointer actions: Down received while already down.");
Jeff Brownb6997262010-10-08 22:31:17 -07001514#endif
Jeff Brown81346812011-06-28 20:08:48 -07001515 *outConflictingPointerActions = true;
Jeff Brown95712852011-01-04 19:41:59 -08001516 }
Jeff Brown33bbfd22011-02-24 20:55:35 -08001517 mTouchState.copyFrom(mTempTouchState);
Jeff Brown95712852011-01-04 19:41:59 -08001518 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
1519 // One pointer went up.
1520 if (isSplit) {
1521 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07001522 uint32_t pointerId = entry->pointerProperties[pointerIndex].id;
Jeff Brownb88102f2010-09-08 11:49:43 -07001523
Jeff Brown95712852011-01-04 19:41:59 -08001524 for (size_t i = 0; i < mTempTouchState.windows.size(); ) {
1525 TouchedWindow& touchedWindow = mTempTouchState.windows.editItemAt(i);
1526 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
1527 touchedWindow.pointerIds.clearBit(pointerId);
1528 if (touchedWindow.pointerIds.isEmpty()) {
1529 mTempTouchState.windows.removeAt(i);
1530 continue;
1531 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001532 }
Jeff Brown95712852011-01-04 19:41:59 -08001533 i += 1;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001534 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001535 }
Jeff Brown33bbfd22011-02-24 20:55:35 -08001536 mTouchState.copyFrom(mTempTouchState);
1537 } else if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
1538 // Discard temporary touch state since it was only valid for this action.
1539 } else {
1540 // Save changes to touch state as-is for all other actions.
1541 mTouchState.copyFrom(mTempTouchState);
Jeff Brownb88102f2010-09-08 11:49:43 -07001542 }
Jeff Browna032cc02011-03-07 16:56:21 -08001543
1544 // Update hover state.
Jeff Brown9302c872011-07-13 22:51:29 -07001545 mLastHoverWindowHandle = newHoverWindowHandle;
Jeff Brown95712852011-01-04 19:41:59 -08001546 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001547 } else {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001548#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001549 ALOGD("Not updating touch focus because injection was denied.");
Jeff Brown01ce2e92010-09-26 22:20:12 -07001550#endif
Jeff Brownb88102f2010-09-08 11:49:43 -07001551 }
1552
1553Unresponsive:
Jeff Brown120a4592010-10-27 18:43:51 -07001554 // Reset temporary touch state to ensure we release unnecessary references to input channels.
1555 mTempTouchState.reset();
1556
Jeff Brown519e0242010-09-15 15:18:56 -07001557 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
1558 updateDispatchStatisticsLocked(currentTime, entry,
1559 injectionResult, timeSpentWaitingForApplication);
Jeff Brownb88102f2010-09-08 11:49:43 -07001560#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001561 ALOGD("findTouchedWindow finished: injectionResult=%d, injectionPermission=%d, "
Jeff Brown01ce2e92010-09-26 22:20:12 -07001562 "timeSpentWaitingForApplication=%0.1fms",
Jeff Brown519e0242010-09-15 15:18:56 -07001563 injectionResult, injectionPermission, timeSpentWaitingForApplication / 1000000.0);
Jeff Brownb88102f2010-09-08 11:49:43 -07001564#endif
1565 return injectionResult;
1566}
1567
Jeff Brown9302c872011-07-13 22:51:29 -07001568void InputDispatcher::addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
Jeff Browne9bb9be2012-02-06 15:47:55 -08001569 int32_t targetFlags, BitSet32 pointerIds, Vector<InputTarget>& inputTargets) {
1570 inputTargets.push();
Jeff Brownb88102f2010-09-08 11:49:43 -07001571
Jeff Browncc4f7db2011-08-30 20:34:48 -07001572 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Jeff Browne9bb9be2012-02-06 15:47:55 -08001573 InputTarget& target = inputTargets.editTop();
Jeff Browncc4f7db2011-08-30 20:34:48 -07001574 target.inputChannel = windowInfo->inputChannel;
Jeff Brownb88102f2010-09-08 11:49:43 -07001575 target.flags = targetFlags;
Jeff Browncc4f7db2011-08-30 20:34:48 -07001576 target.xOffset = - windowInfo->frameLeft;
1577 target.yOffset = - windowInfo->frameTop;
1578 target.scaleFactor = windowInfo->scaleFactor;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001579 target.pointerIds = pointerIds;
Jeff Brownb88102f2010-09-08 11:49:43 -07001580}
1581
Jeff Browne9bb9be2012-02-06 15:47:55 -08001582void InputDispatcher::addMonitoringTargetsLocked(Vector<InputTarget>& inputTargets) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001583 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
Jeff Browne9bb9be2012-02-06 15:47:55 -08001584 inputTargets.push();
Jeff Brownb88102f2010-09-08 11:49:43 -07001585
Jeff Browne9bb9be2012-02-06 15:47:55 -08001586 InputTarget& target = inputTargets.editTop();
Jeff Brownb88102f2010-09-08 11:49:43 -07001587 target.inputChannel = mMonitoringChannels[i];
Jeff Brownb6110c22011-04-01 16:15:13 -07001588 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
Jeff Brownb88102f2010-09-08 11:49:43 -07001589 target.xOffset = 0;
1590 target.yOffset = 0;
Jeff Brownb6110c22011-04-01 16:15:13 -07001591 target.pointerIds.clear();
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001592 target.scaleFactor = 1.0f;
Jeff Brownb88102f2010-09-08 11:49:43 -07001593 }
1594}
1595
Jeff Brown9302c872011-07-13 22:51:29 -07001596bool InputDispatcher::checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
Jeff Brown01ce2e92010-09-26 22:20:12 -07001597 const InjectionState* injectionState) {
1598 if (injectionState
Jeff Browncc4f7db2011-08-30 20:34:48 -07001599 && (windowHandle == NULL
1600 || windowHandle->getInfo()->ownerUid != injectionState->injectorUid)
Jeff Brownb6997262010-10-08 22:31:17 -07001601 && !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Jeff Brown9302c872011-07-13 22:51:29 -07001602 if (windowHandle != NULL) {
Steve Block8564c8d2012-01-05 23:22:43 +00001603 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
Jeff Brown9302c872011-07-13 22:51:29 -07001604 "owned by uid %d",
Jeff Brownb6997262010-10-08 22:31:17 -07001605 injectionState->injectorPid, injectionState->injectorUid,
Jeff Browncc4f7db2011-08-30 20:34:48 -07001606 windowHandle->getName().string(),
1607 windowHandle->getInfo()->ownerUid);
Jeff Brownb6997262010-10-08 22:31:17 -07001608 } else {
Steve Block8564c8d2012-01-05 23:22:43 +00001609 ALOGW("Permission denied: injecting event from pid %d uid %d",
Jeff Brownb6997262010-10-08 22:31:17 -07001610 injectionState->injectorPid, injectionState->injectorUid);
Jeff Brownb88102f2010-09-08 11:49:43 -07001611 }
Jeff Brownb6997262010-10-08 22:31:17 -07001612 return false;
Jeff Brownb88102f2010-09-08 11:49:43 -07001613 }
1614 return true;
1615}
1616
Jeff Brown19dfc832010-10-05 12:26:23 -07001617bool InputDispatcher::isWindowObscuredAtPointLocked(
Jeff Brown9302c872011-07-13 22:51:29 -07001618 const sp<InputWindowHandle>& windowHandle, int32_t x, int32_t y) const {
1619 size_t numWindows = mWindowHandles.size();
Jeff Brownb88102f2010-09-08 11:49:43 -07001620 for (size_t i = 0; i < numWindows; i++) {
Jeff Brown9302c872011-07-13 22:51:29 -07001621 sp<InputWindowHandle> otherHandle = mWindowHandles.itemAt(i);
1622 if (otherHandle == windowHandle) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001623 break;
1624 }
Jeff Browncc4f7db2011-08-30 20:34:48 -07001625
1626 const InputWindowInfo* otherInfo = otherHandle->getInfo();
1627 if (otherInfo->visible && ! otherInfo->isTrustedOverlay()
1628 && otherInfo->frameContainsPoint(x, y)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001629 return true;
1630 }
1631 }
1632 return false;
1633}
1634
Jeff Brownd1c48a02012-02-06 19:12:47 -08001635bool InputDispatcher::isWindowReadyForMoreInputLocked(nsecs_t currentTime,
Jeff Brown0952c302012-02-13 13:48:59 -08001636 const sp<InputWindowHandle>& windowHandle, const EventEntry* eventEntry) {
Jeff Browncc4f7db2011-08-30 20:34:48 -07001637 ssize_t connectionIndex = getConnectionIndexLocked(windowHandle->getInputChannel());
Jeff Brown519e0242010-09-15 15:18:56 -07001638 if (connectionIndex >= 0) {
Jeff Browncbee6d62012-02-03 20:11:27 -08001639 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
Jeff Brownd1c48a02012-02-06 19:12:47 -08001640 if (connection->inputPublisherBlocked) {
1641 return false;
1642 }
Jeff Brown0952c302012-02-13 13:48:59 -08001643 if (eventEntry->type == EventEntry::TYPE_KEY) {
1644 // If the event is a key event, then we must wait for all previous events to
1645 // complete before delivering it because previous events may have the
1646 // side-effect of transferring focus to a different window and we want to
1647 // ensure that the following keys are sent to the new window.
1648 //
1649 // Suppose the user touches a button in a window then immediately presses "A".
1650 // If the button causes a pop-up window to appear then we want to ensure that
1651 // the "A" key is delivered to the new pop-up window. This is because users
1652 // often anticipate pending UI changes when typing on a keyboard.
1653 // To obtain this behavior, we must serialize key events with respect to all
1654 // prior input events.
Jeff Brownd1c48a02012-02-06 19:12:47 -08001655 return connection->outboundQueue.isEmpty()
1656 && connection->waitQueue.isEmpty();
1657 }
Jeff Brown0952c302012-02-13 13:48:59 -08001658 // Touch events can always be sent to a window immediately because the user intended
1659 // to touch whatever was visible at the time. Even if focus changes or a new
1660 // window appears moments later, the touch event was meant to be delivered to
1661 // whatever window happened to be on screen at the time.
1662 //
1663 // Generic motion events, such as trackball or joystick events are a little trickier.
1664 // Like key events, generic motion events are delivered to the focused window.
1665 // Unlike key events, generic motion events don't tend to transfer focus to other
1666 // windows and it is not important for them to be serialized. So we prefer to deliver
1667 // generic motion events as soon as possible to improve efficiency and reduce lag
1668 // through batching.
1669 //
1670 // The one case where we pause input event delivery is when the wait queue is piling
1671 // up with lots of events because the application is not responding.
1672 // This condition ensures that ANRs are detected reliably.
Jeff Brownd1c48a02012-02-06 19:12:47 -08001673 if (!connection->waitQueue.isEmpty()
1674 && currentTime >= connection->waitQueue.head->eventEntry->eventTime
1675 + STREAM_AHEAD_EVENT_TIMEOUT) {
1676 return false;
1677 }
Jeff Brown519e0242010-09-15 15:18:56 -07001678 }
Jeff Brownd1c48a02012-02-06 19:12:47 -08001679 return true;
Jeff Brown519e0242010-09-15 15:18:56 -07001680}
1681
Jeff Brown9302c872011-07-13 22:51:29 -07001682String8 InputDispatcher::getApplicationWindowLabelLocked(
1683 const sp<InputApplicationHandle>& applicationHandle,
1684 const sp<InputWindowHandle>& windowHandle) {
1685 if (applicationHandle != NULL) {
1686 if (windowHandle != NULL) {
Jeff Browncc4f7db2011-08-30 20:34:48 -07001687 String8 label(applicationHandle->getName());
Jeff Brown519e0242010-09-15 15:18:56 -07001688 label.append(" - ");
Jeff Browncc4f7db2011-08-30 20:34:48 -07001689 label.append(windowHandle->getName());
Jeff Brown519e0242010-09-15 15:18:56 -07001690 return label;
1691 } else {
Jeff Browncc4f7db2011-08-30 20:34:48 -07001692 return applicationHandle->getName();
Jeff Brown519e0242010-09-15 15:18:56 -07001693 }
Jeff Brown9302c872011-07-13 22:51:29 -07001694 } else if (windowHandle != NULL) {
Jeff Browncc4f7db2011-08-30 20:34:48 -07001695 return windowHandle->getName();
Jeff Brown519e0242010-09-15 15:18:56 -07001696 } else {
1697 return String8("<unknown application or window>");
1698 }
1699}
1700
Jeff Browne2fe69e2010-10-18 13:21:23 -07001701void InputDispatcher::pokeUserActivityLocked(const EventEntry* eventEntry) {
Jeff Brown56194eb2011-03-02 19:23:13 -08001702 int32_t eventType = POWER_MANAGER_OTHER_EVENT;
Jeff Brown4d396052010-10-29 21:50:21 -07001703 switch (eventEntry->type) {
1704 case EventEntry::TYPE_MOTION: {
Jeff Browne2fe69e2010-10-18 13:21:23 -07001705 const MotionEntry* motionEntry = static_cast<const MotionEntry*>(eventEntry);
Jeff Brown4d396052010-10-29 21:50:21 -07001706 if (motionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
1707 return;
1708 }
1709
Jeff Brown56194eb2011-03-02 19:23:13 -08001710 if (MotionEvent::isTouchEvent(motionEntry->source, motionEntry->action)) {
Joe Onorato1a542c72010-11-08 09:48:20 -08001711 eventType = POWER_MANAGER_TOUCH_EVENT;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001712 }
Jeff Brown4d396052010-10-29 21:50:21 -07001713 break;
1714 }
1715 case EventEntry::TYPE_KEY: {
1716 const KeyEntry* keyEntry = static_cast<const KeyEntry*>(eventEntry);
1717 if (keyEntry->flags & AKEY_EVENT_FLAG_CANCELED) {
1718 return;
1719 }
Jeff Brown56194eb2011-03-02 19:23:13 -08001720 eventType = POWER_MANAGER_BUTTON_EVENT;
Jeff Brown4d396052010-10-29 21:50:21 -07001721 break;
1722 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001723 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001724
Jeff Brownb88102f2010-09-08 11:49:43 -07001725 CommandEntry* commandEntry = postCommandLocked(
1726 & InputDispatcher::doPokeUserActivityLockedInterruptible);
Jeff Browne2fe69e2010-10-18 13:21:23 -07001727 commandEntry->eventTime = eventEntry->eventTime;
Jeff Brownb88102f2010-09-08 11:49:43 -07001728 commandEntry->userActivityEventType = eventType;
1729}
1730
Jeff Brown7fbdc842010-06-17 20:52:56 -07001731void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001732 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07001733#if DEBUG_DISPATCH_CYCLE
Steve Block5baa3a62011-12-20 16:23:08 +00001734 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
Jeff Brown9cc695c2011-08-23 18:35:04 -07001735 "xOffset=%f, yOffset=%f, scaleFactor=%f, "
Jeff Brown3241b6b2012-02-03 15:08:02 -08001736 "pointerIds=0x%x",
Jeff Brown519e0242010-09-15 15:18:56 -07001737 connection->getInputChannelName(), inputTarget->flags,
Jeff Brown46b9ac02010-04-22 18:58:52 -07001738 inputTarget->xOffset, inputTarget->yOffset,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001739 inputTarget->scaleFactor, inputTarget->pointerIds.value);
Jeff Brown46b9ac02010-04-22 18:58:52 -07001740#endif
1741
1742 // Skip this event if the connection status is not normal.
Jeff Brown519e0242010-09-15 15:18:56 -07001743 // We don't want to enqueue additional outbound events if the connection is broken.
Jeff Brown46b9ac02010-04-22 18:58:52 -07001744 if (connection->status != Connection::STATUS_NORMAL) {
Jeff Brownb6997262010-10-08 22:31:17 -07001745#if DEBUG_DISPATCH_CYCLE
Steve Block5baa3a62011-12-20 16:23:08 +00001746 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Jeff Brownb88102f2010-09-08 11:49:43 -07001747 connection->getInputChannelName(), connection->getStatusLabel());
Jeff Brownb6997262010-10-08 22:31:17 -07001748#endif
Jeff Brown46b9ac02010-04-22 18:58:52 -07001749 return;
1750 }
1751
Jeff Brown01ce2e92010-09-26 22:20:12 -07001752 // Split a motion event if needed.
Jeff Brown3241b6b2012-02-03 15:08:02 -08001753 if (inputTarget->flags & InputTarget::FLAG_SPLIT) {
Steve Blockec193de2012-01-09 18:35:44 +00001754 ALOG_ASSERT(eventEntry->type == EventEntry::TYPE_MOTION);
Jeff Brown01ce2e92010-09-26 22:20:12 -07001755
1756 MotionEntry* originalMotionEntry = static_cast<MotionEntry*>(eventEntry);
1757 if (inputTarget->pointerIds.count() != originalMotionEntry->pointerCount) {
1758 MotionEntry* splitMotionEntry = splitMotionEvent(
1759 originalMotionEntry, inputTarget->pointerIds);
Jeff Brown58a2da82011-01-25 16:02:22 -08001760 if (!splitMotionEntry) {
1761 return; // split event was dropped
1762 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001763#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001764 ALOGD("channel '%s' ~ Split motion event.",
Jeff Brown01ce2e92010-09-26 22:20:12 -07001765 connection->getInputChannelName());
1766 logOutboundMotionDetailsLocked(" ", splitMotionEntry);
1767#endif
Jeff Brownc0cb3dc2012-01-12 18:30:12 -08001768 enqueueDispatchEntriesLocked(currentTime, connection,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001769 splitMotionEntry, inputTarget);
Jeff Brownc0cb3dc2012-01-12 18:30:12 -08001770 splitMotionEntry->release();
1771 return;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001772 }
1773 }
1774
Jeff Brownc0cb3dc2012-01-12 18:30:12 -08001775 // Not splitting. Enqueue dispatch entries for the event as is.
Jeff Brown3241b6b2012-02-03 15:08:02 -08001776 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
Jeff Brownc0cb3dc2012-01-12 18:30:12 -08001777}
1778
1779void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001780 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07001781 bool wasEmpty = connection->outboundQueue.isEmpty();
1782
Jeff Browna032cc02011-03-07 16:56:21 -08001783 // Enqueue dispatch entries for the requested modes.
1784 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001785 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
Jeff Browna032cc02011-03-07 16:56:21 -08001786 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001787 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
Jeff Browna032cc02011-03-07 16:56:21 -08001788 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001789 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
Jeff Browna032cc02011-03-07 16:56:21 -08001790 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001791 InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brown98db5fa2011-06-08 15:37:10 -07001792 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001793 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
Jeff Brown98db5fa2011-06-08 15:37:10 -07001794 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001795 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Jeff Browna032cc02011-03-07 16:56:21 -08001796
1797 // If the outbound queue was previously empty, start the dispatch cycle going.
Jeff Brownb6110c22011-04-01 16:15:13 -07001798 if (wasEmpty && !connection->outboundQueue.isEmpty()) {
Jeff Browna032cc02011-03-07 16:56:21 -08001799 startDispatchCycleLocked(currentTime, connection);
1800 }
1801}
1802
1803void InputDispatcher::enqueueDispatchEntryLocked(
1804 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001805 int32_t dispatchMode) {
Jeff Browna032cc02011-03-07 16:56:21 -08001806 int32_t inputTargetFlags = inputTarget->flags;
1807 if (!(inputTargetFlags & dispatchMode)) {
1808 return;
1809 }
1810 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
1811
Jeff Brown46b9ac02010-04-22 18:58:52 -07001812 // This is a new event.
1813 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Jeff Brownac386072011-07-20 15:19:50 -07001814 DispatchEntry* dispatchEntry = new DispatchEntry(eventEntry, // increments ref
Dianne Hackbornaa9d84c2011-05-09 19:00:59 -07001815 inputTargetFlags, inputTarget->xOffset, inputTarget->yOffset,
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001816 inputTarget->scaleFactor);
Jeff Brown6ec402b2010-07-28 15:48:59 -07001817
Jeff Brown81346812011-06-28 20:08:48 -07001818 // Apply target flags and update the connection's input state.
1819 switch (eventEntry->type) {
1820 case EventEntry::TYPE_KEY: {
1821 KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
1822 dispatchEntry->resolvedAction = keyEntry->action;
1823 dispatchEntry->resolvedFlags = keyEntry->flags;
1824
1825 if (!connection->inputState.trackKey(keyEntry,
1826 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags)) {
1827#if DEBUG_DISPATCH_CYCLE
Steve Block5baa3a62011-12-20 16:23:08 +00001828 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
Jeff Brown81346812011-06-28 20:08:48 -07001829 connection->getInputChannelName());
1830#endif
Jeff Brownc0cb3dc2012-01-12 18:30:12 -08001831 delete dispatchEntry;
Jeff Brown81346812011-06-28 20:08:48 -07001832 return; // skip the inconsistent event
1833 }
1834 break;
1835 }
1836
1837 case EventEntry::TYPE_MOTION: {
1838 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
1839 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
1840 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
1841 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
1842 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
1843 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
1844 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
1845 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
1846 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
1847 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
1848 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
1849 } else {
1850 dispatchEntry->resolvedAction = motionEntry->action;
1851 }
1852 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE
1853 && !connection->inputState.isHovering(
1854 motionEntry->deviceId, motionEntry->source)) {
1855#if DEBUG_DISPATCH_CYCLE
Steve Block5baa3a62011-12-20 16:23:08 +00001856 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter event",
Jeff Brown81346812011-06-28 20:08:48 -07001857 connection->getInputChannelName());
1858#endif
1859 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
1860 }
1861
1862 dispatchEntry->resolvedFlags = motionEntry->flags;
1863 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
1864 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
1865 }
1866
1867 if (!connection->inputState.trackMotion(motionEntry,
1868 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags)) {
1869#if DEBUG_DISPATCH_CYCLE
Steve Block5baa3a62011-12-20 16:23:08 +00001870 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion event",
Jeff Brown81346812011-06-28 20:08:48 -07001871 connection->getInputChannelName());
1872#endif
Jeff Brownc0cb3dc2012-01-12 18:30:12 -08001873 delete dispatchEntry;
Jeff Brown81346812011-06-28 20:08:48 -07001874 return; // skip the inconsistent event
1875 }
1876 break;
1877 }
1878 }
1879
Jeff Brownc0cb3dc2012-01-12 18:30:12 -08001880 // Remember that we are waiting for this dispatch to complete.
1881 if (dispatchEntry->hasForegroundTarget()) {
1882 incrementPendingForegroundDispatchesLocked(eventEntry);
1883 }
1884
Jeff Brown46b9ac02010-04-22 18:58:52 -07001885 // Enqueue the dispatch entry.
1886 connection->outboundQueue.enqueueAtTail(dispatchEntry);
Jeff Brown481c1572012-03-09 14:41:15 -08001887 traceOutboundQueueLengthLocked(connection);
Jeff Brown46b9ac02010-04-22 18:58:52 -07001888}
1889
Jeff Brown7fbdc842010-06-17 20:52:56 -07001890void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Jeff Brown519e0242010-09-15 15:18:56 -07001891 const sp<Connection>& connection) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07001892#if DEBUG_DISPATCH_CYCLE
Steve Block5baa3a62011-12-20 16:23:08 +00001893 ALOGD("channel '%s' ~ startDispatchCycle",
Jeff Brown46b9ac02010-04-22 18:58:52 -07001894 connection->getInputChannelName());
1895#endif
1896
Jeff Brownd1c48a02012-02-06 19:12:47 -08001897 while (connection->status == Connection::STATUS_NORMAL
1898 && !connection->outboundQueue.isEmpty()) {
1899 DispatchEntry* dispatchEntry = connection->outboundQueue.head;
Jeff Brown46b9ac02010-04-22 18:58:52 -07001900
Jeff Brownd1c48a02012-02-06 19:12:47 -08001901 // Publish the event.
1902 status_t status;
1903 EventEntry* eventEntry = dispatchEntry->eventEntry;
1904 switch (eventEntry->type) {
1905 case EventEntry::TYPE_KEY: {
1906 KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
Jeff Brown46b9ac02010-04-22 18:58:52 -07001907
Jeff Brownd1c48a02012-02-06 19:12:47 -08001908 // Publish the key event.
Jeff Brown072ec962012-02-07 14:46:57 -08001909 status = connection->inputPublisher.publishKeyEvent(dispatchEntry->seq,
Jeff Brownd1c48a02012-02-06 19:12:47 -08001910 keyEntry->deviceId, keyEntry->source,
1911 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags,
1912 keyEntry->keyCode, keyEntry->scanCode,
1913 keyEntry->metaState, keyEntry->repeatCount, keyEntry->downTime,
1914 keyEntry->eventTime);
1915 break;
1916 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001917
Jeff Brownd1c48a02012-02-06 19:12:47 -08001918 case EventEntry::TYPE_MOTION: {
1919 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
Jeff Brown46b9ac02010-04-22 18:58:52 -07001920
Jeff Brownd1c48a02012-02-06 19:12:47 -08001921 PointerCoords scaledCoords[MAX_POINTERS];
1922 const PointerCoords* usingCoords = motionEntry->pointerCoords;
Jeff Brown46b9ac02010-04-22 18:58:52 -07001923
Jeff Brownd1c48a02012-02-06 19:12:47 -08001924 // Set the X and Y offset depending on the input source.
1925 float xOffset, yOffset, scaleFactor;
1926 if ((motionEntry->source & AINPUT_SOURCE_CLASS_POINTER)
1927 && !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
1928 scaleFactor = dispatchEntry->scaleFactor;
1929 xOffset = dispatchEntry->xOffset * scaleFactor;
1930 yOffset = dispatchEntry->yOffset * scaleFactor;
1931 if (scaleFactor != 1.0f) {
1932 for (size_t i = 0; i < motionEntry->pointerCount; i++) {
1933 scaledCoords[i] = motionEntry->pointerCoords[i];
1934 scaledCoords[i].scale(scaleFactor);
1935 }
1936 usingCoords = scaledCoords;
1937 }
1938 } else {
1939 xOffset = 0.0f;
1940 yOffset = 0.0f;
1941 scaleFactor = 1.0f;
1942
1943 // We don't want the dispatch target to know.
1944 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
1945 for (size_t i = 0; i < motionEntry->pointerCount; i++) {
1946 scaledCoords[i].clear();
1947 }
1948 usingCoords = scaledCoords;
1949 }
1950 }
1951
1952 // Publish the motion event.
Jeff Brown072ec962012-02-07 14:46:57 -08001953 status = connection->inputPublisher.publishMotionEvent(dispatchEntry->seq,
Jeff Brownd1c48a02012-02-06 19:12:47 -08001954 motionEntry->deviceId, motionEntry->source,
1955 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags,
1956 motionEntry->edgeFlags, motionEntry->metaState, motionEntry->buttonState,
1957 xOffset, yOffset,
1958 motionEntry->xPrecision, motionEntry->yPrecision,
1959 motionEntry->downTime, motionEntry->eventTime,
1960 motionEntry->pointerCount, motionEntry->pointerProperties,
1961 usingCoords);
1962 break;
1963 }
1964
1965 default:
1966 ALOG_ASSERT(false);
Jeff Brown46b9ac02010-04-22 18:58:52 -07001967 return;
1968 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07001969
Jeff Brownd1c48a02012-02-06 19:12:47 -08001970 // Check the result.
Jeff Brown46b9ac02010-04-22 18:58:52 -07001971 if (status) {
Jeff Brownd1c48a02012-02-06 19:12:47 -08001972 if (status == WOULD_BLOCK) {
1973 if (connection->waitQueue.isEmpty()) {
1974 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
1975 "This is unexpected because the wait queue is empty, so the pipe "
1976 "should be empty and we shouldn't have any problems writing an "
1977 "event to it, status=%d", connection->getInputChannelName(), status);
1978 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
1979 } else {
1980 // Pipe is full and we are waiting for the app to finish process some events
1981 // before sending more events to it.
1982#if DEBUG_DISPATCH_CYCLE
1983 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
1984 "waiting for the application to catch up",
1985 connection->getInputChannelName());
1986#endif
1987 connection->inputPublisherBlocked = true;
1988 }
1989 } else {
1990 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
1991 "status=%d", connection->getInputChannelName(), status);
1992 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
1993 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07001994 return;
1995 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07001996
Jeff Brownd1c48a02012-02-06 19:12:47 -08001997 // Re-enqueue the event on the wait queue.
1998 connection->outboundQueue.dequeue(dispatchEntry);
Jeff Brown481c1572012-03-09 14:41:15 -08001999 traceOutboundQueueLengthLocked(connection);
Jeff Brownd1c48a02012-02-06 19:12:47 -08002000 connection->waitQueue.enqueueAtTail(dispatchEntry);
Jeff Brown481c1572012-03-09 14:41:15 -08002001 traceWaitQueueLengthLocked(connection);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002002 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002003}
2004
Jeff Brown7fbdc842010-06-17 20:52:56 -07002005void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Jeff Brown072ec962012-02-07 14:46:57 -08002006 const sp<Connection>& connection, uint32_t seq, bool handled) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002007#if DEBUG_DISPATCH_CYCLE
Jeff Brown072ec962012-02-07 14:46:57 -08002008 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
2009 connection->getInputChannelName(), seq, toString(handled));
Jeff Brown46b9ac02010-04-22 18:58:52 -07002010#endif
2011
Jeff Brownd1c48a02012-02-06 19:12:47 -08002012 connection->inputPublisherBlocked = false;
2013
Jeff Brown9c3cda02010-06-15 01:31:58 -07002014 if (connection->status == Connection::STATUS_BROKEN
2015 || connection->status == Connection::STATUS_ZOMBIE) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002016 return;
2017 }
2018
Jeff Brown3915bb82010-11-05 15:02:16 -07002019 // Notify other system components and prepare to start the next dispatch cycle.
Jeff Brown072ec962012-02-07 14:46:57 -08002020 onDispatchCycleFinishedLocked(currentTime, connection, seq, handled);
Jeff Brownb88102f2010-09-08 11:49:43 -07002021}
2022
Jeff Brownb6997262010-10-08 22:31:17 -07002023void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Jeff Browncc4f7db2011-08-30 20:34:48 -07002024 const sp<Connection>& connection, bool notify) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002025#if DEBUG_DISPATCH_CYCLE
Steve Block5baa3a62011-12-20 16:23:08 +00002026 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
Jeff Browncc4f7db2011-08-30 20:34:48 -07002027 connection->getInputChannelName(), toString(notify));
Jeff Brown46b9ac02010-04-22 18:58:52 -07002028#endif
2029
Jeff Brownd1c48a02012-02-06 19:12:47 -08002030 // Clear the dispatch queues.
2031 drainDispatchQueueLocked(&connection->outboundQueue);
Jeff Brown481c1572012-03-09 14:41:15 -08002032 traceOutboundQueueLengthLocked(connection);
Jeff Brownd1c48a02012-02-06 19:12:47 -08002033 drainDispatchQueueLocked(&connection->waitQueue);
Jeff Brown481c1572012-03-09 14:41:15 -08002034 traceWaitQueueLengthLocked(connection);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002035
Jeff Brownb6997262010-10-08 22:31:17 -07002036 // The connection appears to be unrecoverably broken.
Jeff Brown9c3cda02010-06-15 01:31:58 -07002037 // Ignore already broken or zombie connections.
Jeff Brownb6997262010-10-08 22:31:17 -07002038 if (connection->status == Connection::STATUS_NORMAL) {
2039 connection->status = Connection::STATUS_BROKEN;
Jeff Brown46b9ac02010-04-22 18:58:52 -07002040
Jeff Browncc4f7db2011-08-30 20:34:48 -07002041 if (notify) {
2042 // Notify other system components.
2043 onDispatchCycleBrokenLocked(currentTime, connection);
2044 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002045 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002046}
2047
Jeff Brownd1c48a02012-02-06 19:12:47 -08002048void InputDispatcher::drainDispatchQueueLocked(Queue<DispatchEntry>* queue) {
2049 while (!queue->isEmpty()) {
2050 DispatchEntry* dispatchEntry = queue->dequeueAtHead();
2051 releaseDispatchEntryLocked(dispatchEntry);
Jeff Brownb88102f2010-09-08 11:49:43 -07002052 }
Jeff Brownb88102f2010-09-08 11:49:43 -07002053}
2054
Jeff Brownd1c48a02012-02-06 19:12:47 -08002055void InputDispatcher::releaseDispatchEntryLocked(DispatchEntry* dispatchEntry) {
2056 if (dispatchEntry->hasForegroundTarget()) {
2057 decrementPendingForegroundDispatchesLocked(dispatchEntry->eventEntry);
2058 }
2059 delete dispatchEntry;
2060}
2061
Jeff Browncbee6d62012-02-03 20:11:27 -08002062int InputDispatcher::handleReceiveCallback(int fd, int events, void* data) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002063 InputDispatcher* d = static_cast<InputDispatcher*>(data);
2064
2065 { // acquire lock
2066 AutoMutex _l(d->mLock);
2067
Jeff Browncbee6d62012-02-03 20:11:27 -08002068 ssize_t connectionIndex = d->mConnectionsByFd.indexOfKey(fd);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002069 if (connectionIndex < 0) {
Steve Block3762c312012-01-06 19:20:56 +00002070 ALOGE("Received spurious receive callback for unknown input channel. "
Jeff Browncbee6d62012-02-03 20:11:27 -08002071 "fd=%d, events=0x%x", fd, events);
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002072 return 0; // remove the callback
Jeff Brown46b9ac02010-04-22 18:58:52 -07002073 }
2074
Jeff Browncc4f7db2011-08-30 20:34:48 -07002075 bool notify;
Jeff Browncbee6d62012-02-03 20:11:27 -08002076 sp<Connection> connection = d->mConnectionsByFd.valueAt(connectionIndex);
Jeff Browncc4f7db2011-08-30 20:34:48 -07002077 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
2078 if (!(events & ALOOPER_EVENT_INPUT)) {
Steve Block8564c8d2012-01-05 23:22:43 +00002079 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
Jeff Browncc4f7db2011-08-30 20:34:48 -07002080 "events=0x%x", connection->getInputChannelName(), events);
2081 return 1;
2082 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002083
Jeff Brown1adee112012-02-07 10:25:41 -08002084 nsecs_t currentTime = now();
2085 bool gotOne = false;
2086 status_t status;
2087 for (;;) {
Jeff Brown072ec962012-02-07 14:46:57 -08002088 uint32_t seq;
2089 bool handled;
2090 status = connection->inputPublisher.receiveFinishedSignal(&seq, &handled);
Jeff Brown1adee112012-02-07 10:25:41 -08002091 if (status) {
2092 break;
2093 }
Jeff Brown072ec962012-02-07 14:46:57 -08002094 d->finishDispatchCycleLocked(currentTime, connection, seq, handled);
Jeff Brown1adee112012-02-07 10:25:41 -08002095 gotOne = true;
2096 }
2097 if (gotOne) {
Jeff Browncc4f7db2011-08-30 20:34:48 -07002098 d->runCommandsLockedInterruptible();
Jeff Brown1adee112012-02-07 10:25:41 -08002099 if (status == WOULD_BLOCK) {
2100 return 1;
2101 }
Jeff Browncc4f7db2011-08-30 20:34:48 -07002102 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002103
Jeff Brown1adee112012-02-07 10:25:41 -08002104 notify = status != DEAD_OBJECT || !connection->monitor;
2105 if (notify) {
2106 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
2107 connection->getInputChannelName(), status);
2108 }
Jeff Browncc4f7db2011-08-30 20:34:48 -07002109 } else {
2110 // Monitor channels are never explicitly unregistered.
2111 // We do it automatically when the remote endpoint is closed so don't warn
2112 // about them.
2113 notify = !connection->monitor;
2114 if (notify) {
Steve Block8564c8d2012-01-05 23:22:43 +00002115 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. "
Jeff Browncc4f7db2011-08-30 20:34:48 -07002116 "events=0x%x", connection->getInputChannelName(), events);
2117 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002118 }
2119
Jeff Browncc4f7db2011-08-30 20:34:48 -07002120 // Unregister the channel.
2121 d->unregisterInputChannelLocked(connection->inputChannel, notify);
2122 return 0; // remove the callback
Jeff Brown46b9ac02010-04-22 18:58:52 -07002123 } // release lock
2124}
2125
Jeff Brownb6997262010-10-08 22:31:17 -07002126void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Jeff Brownda3d5a92011-03-29 15:11:34 -07002127 const CancelationOptions& options) {
Jeff Browncbee6d62012-02-03 20:11:27 -08002128 for (size_t i = 0; i < mConnectionsByFd.size(); i++) {
Jeff Brownb6997262010-10-08 22:31:17 -07002129 synthesizeCancelationEventsForConnectionLocked(
Jeff Browncbee6d62012-02-03 20:11:27 -08002130 mConnectionsByFd.valueAt(i), options);
Jeff Brownb6997262010-10-08 22:31:17 -07002131 }
2132}
2133
2134void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Jeff Brownda3d5a92011-03-29 15:11:34 -07002135 const sp<InputChannel>& channel, const CancelationOptions& options) {
Jeff Brownb6997262010-10-08 22:31:17 -07002136 ssize_t index = getConnectionIndexLocked(channel);
2137 if (index >= 0) {
2138 synthesizeCancelationEventsForConnectionLocked(
Jeff Browncbee6d62012-02-03 20:11:27 -08002139 mConnectionsByFd.valueAt(index), options);
Jeff Brownb6997262010-10-08 22:31:17 -07002140 }
2141}
2142
2143void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
Jeff Brownda3d5a92011-03-29 15:11:34 -07002144 const sp<Connection>& connection, const CancelationOptions& options) {
Jeff Brownc0cb3dc2012-01-12 18:30:12 -08002145 if (connection->status == Connection::STATUS_BROKEN) {
2146 return;
2147 }
2148
Jeff Brownb6997262010-10-08 22:31:17 -07002149 nsecs_t currentTime = now();
2150
Jeff Brown8b4be5602012-02-06 16:31:05 -08002151 Vector<EventEntry*> cancelationEvents;
Jeff Brownac386072011-07-20 15:19:50 -07002152 connection->inputState.synthesizeCancelationEvents(currentTime,
Jeff Brown8b4be5602012-02-06 16:31:05 -08002153 cancelationEvents, options);
Jeff Brownb6997262010-10-08 22:31:17 -07002154
Jeff Brown8b4be5602012-02-06 16:31:05 -08002155 if (!cancelationEvents.isEmpty()) {
Jeff Brownb6997262010-10-08 22:31:17 -07002156#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00002157 ALOGD("channel '%s' ~ Synthesized %d cancelation events to bring channel back in sync "
Jeff Brownda3d5a92011-03-29 15:11:34 -07002158 "with reality: %s, mode=%d.",
Jeff Brown8b4be5602012-02-06 16:31:05 -08002159 connection->getInputChannelName(), cancelationEvents.size(),
Jeff Brownda3d5a92011-03-29 15:11:34 -07002160 options.reason, options.mode);
Jeff Brownb6997262010-10-08 22:31:17 -07002161#endif
Jeff Brown8b4be5602012-02-06 16:31:05 -08002162 for (size_t i = 0; i < cancelationEvents.size(); i++) {
2163 EventEntry* cancelationEventEntry = cancelationEvents.itemAt(i);
Jeff Brownb6997262010-10-08 22:31:17 -07002164 switch (cancelationEventEntry->type) {
2165 case EventEntry::TYPE_KEY:
2166 logOutboundKeyDetailsLocked("cancel - ",
2167 static_cast<KeyEntry*>(cancelationEventEntry));
2168 break;
2169 case EventEntry::TYPE_MOTION:
2170 logOutboundMotionDetailsLocked("cancel - ",
2171 static_cast<MotionEntry*>(cancelationEventEntry));
2172 break;
2173 }
2174
Jeff Brown81346812011-06-28 20:08:48 -07002175 InputTarget target;
Jeff Brown9302c872011-07-13 22:51:29 -07002176 sp<InputWindowHandle> windowHandle = getWindowHandleLocked(connection->inputChannel);
2177 if (windowHandle != NULL) {
Jeff Browncc4f7db2011-08-30 20:34:48 -07002178 const InputWindowInfo* windowInfo = windowHandle->getInfo();
2179 target.xOffset = -windowInfo->frameLeft;
2180 target.yOffset = -windowInfo->frameTop;
2181 target.scaleFactor = windowInfo->scaleFactor;
Jeff Brownb6997262010-10-08 22:31:17 -07002182 } else {
Jeff Brown81346812011-06-28 20:08:48 -07002183 target.xOffset = 0;
2184 target.yOffset = 0;
2185 target.scaleFactor = 1.0f;
Jeff Brownb6997262010-10-08 22:31:17 -07002186 }
Jeff Brown81346812011-06-28 20:08:48 -07002187 target.inputChannel = connection->inputChannel;
2188 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
Jeff Brownb6997262010-10-08 22:31:17 -07002189
Jeff Brown81346812011-06-28 20:08:48 -07002190 enqueueDispatchEntryLocked(connection, cancelationEventEntry, // increments ref
Jeff Brown3241b6b2012-02-03 15:08:02 -08002191 &target, InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brownb6997262010-10-08 22:31:17 -07002192
Jeff Brownac386072011-07-20 15:19:50 -07002193 cancelationEventEntry->release();
Jeff Brownb6997262010-10-08 22:31:17 -07002194 }
2195
Jeff Brownd1c48a02012-02-06 19:12:47 -08002196 startDispatchCycleLocked(currentTime, connection);
Jeff Brownb6997262010-10-08 22:31:17 -07002197 }
2198}
2199
Jeff Brown01ce2e92010-09-26 22:20:12 -07002200InputDispatcher::MotionEntry*
2201InputDispatcher::splitMotionEvent(const MotionEntry* originalMotionEntry, BitSet32 pointerIds) {
Steve Blockec193de2012-01-09 18:35:44 +00002202 ALOG_ASSERT(pointerIds.value != 0);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002203
2204 uint32_t splitPointerIndexMap[MAX_POINTERS];
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002205 PointerProperties splitPointerProperties[MAX_POINTERS];
Jeff Brown01ce2e92010-09-26 22:20:12 -07002206 PointerCoords splitPointerCoords[MAX_POINTERS];
2207
2208 uint32_t originalPointerCount = originalMotionEntry->pointerCount;
2209 uint32_t splitPointerCount = 0;
2210
2211 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
2212 originalPointerIndex++) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002213 const PointerProperties& pointerProperties =
2214 originalMotionEntry->pointerProperties[originalPointerIndex];
2215 uint32_t pointerId = uint32_t(pointerProperties.id);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002216 if (pointerIds.hasBit(pointerId)) {
2217 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002218 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
Jeff Brownace13b12011-03-09 17:39:48 -08002219 splitPointerCoords[splitPointerCount].copyFrom(
Jeff Brown3241b6b2012-02-03 15:08:02 -08002220 originalMotionEntry->pointerCoords[originalPointerIndex]);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002221 splitPointerCount += 1;
2222 }
2223 }
Jeff Brown58a2da82011-01-25 16:02:22 -08002224
2225 if (splitPointerCount != pointerIds.count()) {
2226 // This is bad. We are missing some of the pointers that we expected to deliver.
2227 // Most likely this indicates that we received an ACTION_MOVE events that has
2228 // different pointer ids than we expected based on the previous ACTION_DOWN
2229 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
2230 // in this way.
Steve Block8564c8d2012-01-05 23:22:43 +00002231 ALOGW("Dropping split motion event because the pointer count is %d but "
Jeff Brown58a2da82011-01-25 16:02:22 -08002232 "we expected there to be %d pointers. This probably means we received "
2233 "a broken sequence of pointer ids from the input device.",
2234 splitPointerCount, pointerIds.count());
2235 return NULL;
2236 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07002237
2238 int32_t action = originalMotionEntry->action;
2239 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
2240 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
2241 || maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2242 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002243 const PointerProperties& pointerProperties =
2244 originalMotionEntry->pointerProperties[originalPointerIndex];
2245 uint32_t pointerId = uint32_t(pointerProperties.id);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002246 if (pointerIds.hasBit(pointerId)) {
2247 if (pointerIds.count() == 1) {
2248 // The first/last pointer went down/up.
2249 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
2250 ? AMOTION_EVENT_ACTION_DOWN : AMOTION_EVENT_ACTION_UP;
Jeff Brown9a01d052010-09-27 16:35:11 -07002251 } else {
2252 // A secondary pointer went down/up.
2253 uint32_t splitPointerIndex = 0;
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002254 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
Jeff Brown9a01d052010-09-27 16:35:11 -07002255 splitPointerIndex += 1;
2256 }
2257 action = maskedAction | (splitPointerIndex
2258 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002259 }
2260 } else {
2261 // An unrelated pointer changed.
2262 action = AMOTION_EVENT_ACTION_MOVE;
2263 }
2264 }
2265
Jeff Brownac386072011-07-20 15:19:50 -07002266 MotionEntry* splitMotionEntry = new MotionEntry(
Jeff Brown01ce2e92010-09-26 22:20:12 -07002267 originalMotionEntry->eventTime,
2268 originalMotionEntry->deviceId,
2269 originalMotionEntry->source,
2270 originalMotionEntry->policyFlags,
2271 action,
2272 originalMotionEntry->flags,
2273 originalMotionEntry->metaState,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002274 originalMotionEntry->buttonState,
Jeff Brown01ce2e92010-09-26 22:20:12 -07002275 originalMotionEntry->edgeFlags,
2276 originalMotionEntry->xPrecision,
2277 originalMotionEntry->yPrecision,
2278 originalMotionEntry->downTime,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002279 splitPointerCount, splitPointerProperties, splitPointerCoords);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002280
Jeff Browna032cc02011-03-07 16:56:21 -08002281 if (originalMotionEntry->injectionState) {
2282 splitMotionEntry->injectionState = originalMotionEntry->injectionState;
2283 splitMotionEntry->injectionState->refCount += 1;
2284 }
2285
Jeff Brown01ce2e92010-09-26 22:20:12 -07002286 return splitMotionEntry;
2287}
2288
Jeff Brownbe1aa822011-07-27 16:04:54 -07002289void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002290#if DEBUG_INBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00002291 ALOGD("notifyConfigurationChanged - eventTime=%lld", args->eventTime);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002292#endif
2293
Jeff Brownb88102f2010-09-08 11:49:43 -07002294 bool needWake;
Jeff Brown46b9ac02010-04-22 18:58:52 -07002295 { // acquire lock
2296 AutoMutex _l(mLock);
2297
Jeff Brownbe1aa822011-07-27 16:04:54 -07002298 ConfigurationChangedEntry* newEntry = new ConfigurationChangedEntry(args->eventTime);
Jeff Brownb88102f2010-09-08 11:49:43 -07002299 needWake = enqueueInboundEventLocked(newEntry);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002300 } // release lock
2301
Jeff Brownb88102f2010-09-08 11:49:43 -07002302 if (needWake) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002303 mLooper->wake();
Jeff Brown46b9ac02010-04-22 18:58:52 -07002304 }
2305}
2306
Jeff Brownbe1aa822011-07-27 16:04:54 -07002307void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002308#if DEBUG_INBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00002309 ALOGD("notifyKey - eventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, action=0x%x, "
Jeff Brown46b9ac02010-04-22 18:58:52 -07002310 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%lld",
Jeff Brownbe1aa822011-07-27 16:04:54 -07002311 args->eventTime, args->deviceId, args->source, args->policyFlags,
2312 args->action, args->flags, args->keyCode, args->scanCode,
2313 args->metaState, args->downTime);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002314#endif
Jeff Brownbe1aa822011-07-27 16:04:54 -07002315 if (!validateKeyEvent(args->action)) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002316 return;
2317 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002318
Jeff Brownbe1aa822011-07-27 16:04:54 -07002319 uint32_t policyFlags = args->policyFlags;
2320 int32_t flags = args->flags;
2321 int32_t metaState = args->metaState;
Jeff Brown1f245102010-11-18 20:53:46 -08002322 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
2323 policyFlags |= POLICY_FLAG_VIRTUAL;
2324 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
2325 }
Jeff Brown924c4d42011-03-07 16:40:47 -08002326 if (policyFlags & POLICY_FLAG_ALT) {
2327 metaState |= AMETA_ALT_ON | AMETA_ALT_LEFT_ON;
2328 }
2329 if (policyFlags & POLICY_FLAG_ALT_GR) {
2330 metaState |= AMETA_ALT_ON | AMETA_ALT_RIGHT_ON;
2331 }
2332 if (policyFlags & POLICY_FLAG_SHIFT) {
2333 metaState |= AMETA_SHIFT_ON | AMETA_SHIFT_LEFT_ON;
2334 }
2335 if (policyFlags & POLICY_FLAG_CAPS_LOCK) {
2336 metaState |= AMETA_CAPS_LOCK_ON;
2337 }
2338 if (policyFlags & POLICY_FLAG_FUNCTION) {
2339 metaState |= AMETA_FUNCTION_ON;
2340 }
Jeff Brown1f245102010-11-18 20:53:46 -08002341
Jeff Browne20c9e02010-10-11 14:20:19 -07002342 policyFlags |= POLICY_FLAG_TRUSTED;
Jeff Brown1f245102010-11-18 20:53:46 -08002343
2344 KeyEvent event;
Jeff Brownbe1aa822011-07-27 16:04:54 -07002345 event.initialize(args->deviceId, args->source, args->action,
2346 flags, args->keyCode, args->scanCode, metaState, 0,
2347 args->downTime, args->eventTime);
Jeff Brown1f245102010-11-18 20:53:46 -08002348
2349 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
2350
2351 if (policyFlags & POLICY_FLAG_WOKE_HERE) {
2352 flags |= AKEY_EVENT_FLAG_WOKE_HERE;
2353 }
Jeff Brownb6997262010-10-08 22:31:17 -07002354
Jeff Brownb88102f2010-09-08 11:49:43 -07002355 bool needWake;
Jeff Brown46b9ac02010-04-22 18:58:52 -07002356 { // acquire lock
Jeff Brown0029c662011-03-30 02:25:18 -07002357 mLock.lock();
2358
2359 if (mInputFilterEnabled) {
2360 mLock.unlock();
2361
2362 policyFlags |= POLICY_FLAG_FILTERED;
2363 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2364 return; // event was consumed by the filter
2365 }
2366
2367 mLock.lock();
2368 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002369
Jeff Brown7fbdc842010-06-17 20:52:56 -07002370 int32_t repeatCount = 0;
Jeff Brownbe1aa822011-07-27 16:04:54 -07002371 KeyEntry* newEntry = new KeyEntry(args->eventTime,
2372 args->deviceId, args->source, policyFlags,
2373 args->action, flags, args->keyCode, args->scanCode,
2374 metaState, repeatCount, args->downTime);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002375
Jeff Brownb88102f2010-09-08 11:49:43 -07002376 needWake = enqueueInboundEventLocked(newEntry);
Jeff Brown0029c662011-03-30 02:25:18 -07002377 mLock.unlock();
Jeff Brown46b9ac02010-04-22 18:58:52 -07002378 } // release lock
2379
Jeff Brownb88102f2010-09-08 11:49:43 -07002380 if (needWake) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002381 mLooper->wake();
Jeff Brown46b9ac02010-04-22 18:58:52 -07002382 }
2383}
2384
Jeff Brownbe1aa822011-07-27 16:04:54 -07002385void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002386#if DEBUG_INBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00002387 ALOGD("notifyMotion - eventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, "
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002388 "action=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, edgeFlags=0x%x, "
Jeff Brown85a31762010-09-01 17:01:00 -07002389 "xPrecision=%f, yPrecision=%f, downTime=%lld",
Jeff Brownbe1aa822011-07-27 16:04:54 -07002390 args->eventTime, args->deviceId, args->source, args->policyFlags,
2391 args->action, args->flags, args->metaState, args->buttonState,
2392 args->edgeFlags, args->xPrecision, args->yPrecision, args->downTime);
2393 for (uint32_t i = 0; i < args->pointerCount; i++) {
Steve Block5baa3a62011-12-20 16:23:08 +00002394 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002395 "x=%f, y=%f, pressure=%f, size=%f, "
Jeff Brown85a31762010-09-01 17:01:00 -07002396 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
Jeff Brown8d608662010-08-30 03:02:23 -07002397 "orientation=%f",
Jeff Brownbe1aa822011-07-27 16:04:54 -07002398 i, args->pointerProperties[i].id,
2399 args->pointerProperties[i].toolType,
2400 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
2401 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
2402 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
2403 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
2404 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
2405 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
2406 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
2407 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
2408 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Jeff Brown46b9ac02010-04-22 18:58:52 -07002409 }
2410#endif
Jeff Brownbe1aa822011-07-27 16:04:54 -07002411 if (!validateMotionEvent(args->action, args->pointerCount, args->pointerProperties)) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002412 return;
2413 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002414
Jeff Brownbe1aa822011-07-27 16:04:54 -07002415 uint32_t policyFlags = args->policyFlags;
Jeff Browne20c9e02010-10-11 14:20:19 -07002416 policyFlags |= POLICY_FLAG_TRUSTED;
Jeff Brownbe1aa822011-07-27 16:04:54 -07002417 mPolicy->interceptMotionBeforeQueueing(args->eventTime, /*byref*/ policyFlags);
Jeff Brownb6997262010-10-08 22:31:17 -07002418
Jeff Brownb88102f2010-09-08 11:49:43 -07002419 bool needWake;
Jeff Brown46b9ac02010-04-22 18:58:52 -07002420 { // acquire lock
Jeff Brown0029c662011-03-30 02:25:18 -07002421 mLock.lock();
2422
2423 if (mInputFilterEnabled) {
2424 mLock.unlock();
2425
2426 MotionEvent event;
Jeff Brownbe1aa822011-07-27 16:04:54 -07002427 event.initialize(args->deviceId, args->source, args->action, args->flags,
2428 args->edgeFlags, args->metaState, args->buttonState, 0, 0,
2429 args->xPrecision, args->yPrecision,
2430 args->downTime, args->eventTime,
2431 args->pointerCount, args->pointerProperties, args->pointerCoords);
Jeff Brown0029c662011-03-30 02:25:18 -07002432
2433 policyFlags |= POLICY_FLAG_FILTERED;
2434 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2435 return; // event was consumed by the filter
2436 }
2437
2438 mLock.lock();
2439 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002440
Jeff Brown46b9ac02010-04-22 18:58:52 -07002441 // Just enqueue a new motion event.
Jeff Brownbe1aa822011-07-27 16:04:54 -07002442 MotionEntry* newEntry = new MotionEntry(args->eventTime,
2443 args->deviceId, args->source, policyFlags,
2444 args->action, args->flags, args->metaState, args->buttonState,
2445 args->edgeFlags, args->xPrecision, args->yPrecision, args->downTime,
2446 args->pointerCount, args->pointerProperties, args->pointerCoords);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002447
Jeff Brownb88102f2010-09-08 11:49:43 -07002448 needWake = enqueueInboundEventLocked(newEntry);
Jeff Brown0029c662011-03-30 02:25:18 -07002449 mLock.unlock();
Jeff Brown46b9ac02010-04-22 18:58:52 -07002450 } // release lock
2451
Jeff Brownb88102f2010-09-08 11:49:43 -07002452 if (needWake) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002453 mLooper->wake();
Jeff Brown46b9ac02010-04-22 18:58:52 -07002454 }
2455}
2456
Jeff Brownbe1aa822011-07-27 16:04:54 -07002457void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
Jeff Brownb6997262010-10-08 22:31:17 -07002458#if DEBUG_INBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00002459 ALOGD("notifySwitch - eventTime=%lld, policyFlags=0x%x, switchCode=%d, switchValue=%d",
Jeff Brownbe1aa822011-07-27 16:04:54 -07002460 args->eventTime, args->policyFlags,
2461 args->switchCode, args->switchValue);
Jeff Brownb6997262010-10-08 22:31:17 -07002462#endif
2463
Jeff Brownbe1aa822011-07-27 16:04:54 -07002464 uint32_t policyFlags = args->policyFlags;
Jeff Browne20c9e02010-10-11 14:20:19 -07002465 policyFlags |= POLICY_FLAG_TRUSTED;
Jeff Brownbe1aa822011-07-27 16:04:54 -07002466 mPolicy->notifySwitch(args->eventTime,
2467 args->switchCode, args->switchValue, policyFlags);
Jeff Brownb6997262010-10-08 22:31:17 -07002468}
2469
Jeff Brown65fd2512011-08-18 11:20:58 -07002470void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
2471#if DEBUG_INBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00002472 ALOGD("notifyDeviceReset - eventTime=%lld, deviceId=%d",
Jeff Brown65fd2512011-08-18 11:20:58 -07002473 args->eventTime, args->deviceId);
2474#endif
2475
2476 bool needWake;
2477 { // acquire lock
2478 AutoMutex _l(mLock);
2479
2480 DeviceResetEntry* newEntry = new DeviceResetEntry(args->eventTime, args->deviceId);
2481 needWake = enqueueInboundEventLocked(newEntry);
2482 } // release lock
2483
2484 if (needWake) {
2485 mLooper->wake();
2486 }
2487}
2488
Jeff Brown7fbdc842010-06-17 20:52:56 -07002489int32_t InputDispatcher::injectInputEvent(const InputEvent* event,
Jeff Brown0029c662011-03-30 02:25:18 -07002490 int32_t injectorPid, int32_t injectorUid, int32_t syncMode, int32_t timeoutMillis,
2491 uint32_t policyFlags) {
Jeff Brown7fbdc842010-06-17 20:52:56 -07002492#if DEBUG_INBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00002493 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Jeff Brown0029c662011-03-30 02:25:18 -07002494 "syncMode=%d, timeoutMillis=%d, policyFlags=0x%08x",
2495 event->getType(), injectorPid, injectorUid, syncMode, timeoutMillis, policyFlags);
Jeff Brown7fbdc842010-06-17 20:52:56 -07002496#endif
2497
2498 nsecs_t endTime = now() + milliseconds_to_nanoseconds(timeoutMillis);
Jeff Browne20c9e02010-10-11 14:20:19 -07002499
Jeff Brown0029c662011-03-30 02:25:18 -07002500 policyFlags |= POLICY_FLAG_INJECTED;
Jeff Browne20c9e02010-10-11 14:20:19 -07002501 if (hasInjectionPermission(injectorPid, injectorUid)) {
2502 policyFlags |= POLICY_FLAG_TRUSTED;
2503 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07002504
Jeff Brown3241b6b2012-02-03 15:08:02 -08002505 EventEntry* firstInjectedEntry;
2506 EventEntry* lastInjectedEntry;
Jeff Brownb6997262010-10-08 22:31:17 -07002507 switch (event->getType()) {
2508 case AINPUT_EVENT_TYPE_KEY: {
2509 const KeyEvent* keyEvent = static_cast<const KeyEvent*>(event);
2510 int32_t action = keyEvent->getAction();
2511 if (! validateKeyEvent(action)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07002512 return INPUT_EVENT_INJECTION_FAILED;
2513 }
2514
Jeff Brownb6997262010-10-08 22:31:17 -07002515 int32_t flags = keyEvent->getFlags();
Jeff Brown1f245102010-11-18 20:53:46 -08002516 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
2517 policyFlags |= POLICY_FLAG_VIRTUAL;
2518 }
2519
Jeff Brown0029c662011-03-30 02:25:18 -07002520 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
2521 mPolicy->interceptKeyBeforeQueueing(keyEvent, /*byref*/ policyFlags);
2522 }
Jeff Brown1f245102010-11-18 20:53:46 -08002523
2524 if (policyFlags & POLICY_FLAG_WOKE_HERE) {
2525 flags |= AKEY_EVENT_FLAG_WOKE_HERE;
2526 }
Jeff Brown6ec402b2010-07-28 15:48:59 -07002527
Jeff Brownb6997262010-10-08 22:31:17 -07002528 mLock.lock();
Jeff Brown3241b6b2012-02-03 15:08:02 -08002529 firstInjectedEntry = new KeyEntry(keyEvent->getEventTime(),
Jeff Brown1f245102010-11-18 20:53:46 -08002530 keyEvent->getDeviceId(), keyEvent->getSource(),
2531 policyFlags, action, flags,
2532 keyEvent->getKeyCode(), keyEvent->getScanCode(), keyEvent->getMetaState(),
Jeff Brownb6997262010-10-08 22:31:17 -07002533 keyEvent->getRepeatCount(), keyEvent->getDownTime());
Jeff Brown3241b6b2012-02-03 15:08:02 -08002534 lastInjectedEntry = firstInjectedEntry;
Jeff Brownb6997262010-10-08 22:31:17 -07002535 break;
2536 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07002537
Jeff Brownb6997262010-10-08 22:31:17 -07002538 case AINPUT_EVENT_TYPE_MOTION: {
2539 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
2540 int32_t action = motionEvent->getAction();
2541 size_t pointerCount = motionEvent->getPointerCount();
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002542 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
2543 if (! validateMotionEvent(action, pointerCount, pointerProperties)) {
Jeff Brownb6997262010-10-08 22:31:17 -07002544 return INPUT_EVENT_INJECTION_FAILED;
2545 }
2546
Jeff Brown0029c662011-03-30 02:25:18 -07002547 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
2548 nsecs_t eventTime = motionEvent->getEventTime();
2549 mPolicy->interceptMotionBeforeQueueing(eventTime, /*byref*/ policyFlags);
2550 }
Jeff Brownb6997262010-10-08 22:31:17 -07002551
2552 mLock.lock();
2553 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
2554 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
Jeff Brown3241b6b2012-02-03 15:08:02 -08002555 firstInjectedEntry = new MotionEntry(*sampleEventTimes,
Jeff Brownb6997262010-10-08 22:31:17 -07002556 motionEvent->getDeviceId(), motionEvent->getSource(), policyFlags,
2557 action, motionEvent->getFlags(),
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002558 motionEvent->getMetaState(), motionEvent->getButtonState(),
2559 motionEvent->getEdgeFlags(),
Jeff Brownb6997262010-10-08 22:31:17 -07002560 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
2561 motionEvent->getDownTime(), uint32_t(pointerCount),
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002562 pointerProperties, samplePointerCoords);
Jeff Brown3241b6b2012-02-03 15:08:02 -08002563 lastInjectedEntry = firstInjectedEntry;
Jeff Brownb6997262010-10-08 22:31:17 -07002564 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
2565 sampleEventTimes += 1;
2566 samplePointerCoords += pointerCount;
Jeff Brown3241b6b2012-02-03 15:08:02 -08002567 MotionEntry* nextInjectedEntry = new MotionEntry(*sampleEventTimes,
2568 motionEvent->getDeviceId(), motionEvent->getSource(), policyFlags,
2569 action, motionEvent->getFlags(),
2570 motionEvent->getMetaState(), motionEvent->getButtonState(),
2571 motionEvent->getEdgeFlags(),
2572 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
2573 motionEvent->getDownTime(), uint32_t(pointerCount),
2574 pointerProperties, samplePointerCoords);
2575 lastInjectedEntry->next = nextInjectedEntry;
2576 lastInjectedEntry = nextInjectedEntry;
Jeff Brownb6997262010-10-08 22:31:17 -07002577 }
Jeff Brownb6997262010-10-08 22:31:17 -07002578 break;
2579 }
2580
2581 default:
Steve Block8564c8d2012-01-05 23:22:43 +00002582 ALOGW("Cannot inject event of type %d", event->getType());
Jeff Brownb6997262010-10-08 22:31:17 -07002583 return INPUT_EVENT_INJECTION_FAILED;
2584 }
2585
Jeff Brownac386072011-07-20 15:19:50 -07002586 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
Jeff Brownb6997262010-10-08 22:31:17 -07002587 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
2588 injectionState->injectionIsAsync = true;
2589 }
2590
2591 injectionState->refCount += 1;
Jeff Brown3241b6b2012-02-03 15:08:02 -08002592 lastInjectedEntry->injectionState = injectionState;
Jeff Brownb6997262010-10-08 22:31:17 -07002593
Jeff Brown3241b6b2012-02-03 15:08:02 -08002594 bool needWake = false;
2595 for (EventEntry* entry = firstInjectedEntry; entry != NULL; ) {
2596 EventEntry* nextEntry = entry->next;
2597 needWake |= enqueueInboundEventLocked(entry);
2598 entry = nextEntry;
2599 }
2600
Jeff Brownb6997262010-10-08 22:31:17 -07002601 mLock.unlock();
Jeff Brown7fbdc842010-06-17 20:52:56 -07002602
Jeff Brownb88102f2010-09-08 11:49:43 -07002603 if (needWake) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002604 mLooper->wake();
Jeff Brown7fbdc842010-06-17 20:52:56 -07002605 }
2606
2607 int32_t injectionResult;
2608 { // acquire lock
2609 AutoMutex _l(mLock);
2610
Jeff Brown6ec402b2010-07-28 15:48:59 -07002611 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
2612 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
2613 } else {
2614 for (;;) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002615 injectionResult = injectionState->injectionResult;
Jeff Brown6ec402b2010-07-28 15:48:59 -07002616 if (injectionResult != INPUT_EVENT_INJECTION_PENDING) {
2617 break;
2618 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07002619
Jeff Brown7fbdc842010-06-17 20:52:56 -07002620 nsecs_t remainingTimeout = endTime - now();
2621 if (remainingTimeout <= 0) {
Jeff Brown6ec402b2010-07-28 15:48:59 -07002622#if DEBUG_INJECTION
Steve Block5baa3a62011-12-20 16:23:08 +00002623 ALOGD("injectInputEvent - Timed out waiting for injection result "
Jeff Brown6ec402b2010-07-28 15:48:59 -07002624 "to become available.");
2625#endif
Jeff Brown7fbdc842010-06-17 20:52:56 -07002626 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
2627 break;
2628 }
2629
Jeff Brown6ec402b2010-07-28 15:48:59 -07002630 mInjectionResultAvailableCondition.waitRelative(mLock, remainingTimeout);
2631 }
2632
2633 if (injectionResult == INPUT_EVENT_INJECTION_SUCCEEDED
2634 && syncMode == INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002635 while (injectionState->pendingForegroundDispatches != 0) {
Jeff Brown6ec402b2010-07-28 15:48:59 -07002636#if DEBUG_INJECTION
Steve Block5baa3a62011-12-20 16:23:08 +00002637 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
Jeff Brown01ce2e92010-09-26 22:20:12 -07002638 injectionState->pendingForegroundDispatches);
Jeff Brown6ec402b2010-07-28 15:48:59 -07002639#endif
2640 nsecs_t remainingTimeout = endTime - now();
2641 if (remainingTimeout <= 0) {
2642#if DEBUG_INJECTION
Steve Block5baa3a62011-12-20 16:23:08 +00002643 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
Jeff Brown6ec402b2010-07-28 15:48:59 -07002644 "dispatches to finish.");
2645#endif
2646 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
2647 break;
2648 }
2649
2650 mInjectionSyncFinishedCondition.waitRelative(mLock, remainingTimeout);
2651 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07002652 }
2653 }
2654
Jeff Brownac386072011-07-20 15:19:50 -07002655 injectionState->release();
Jeff Brown7fbdc842010-06-17 20:52:56 -07002656 } // release lock
2657
Jeff Brown6ec402b2010-07-28 15:48:59 -07002658#if DEBUG_INJECTION
Steve Block5baa3a62011-12-20 16:23:08 +00002659 ALOGD("injectInputEvent - Finished with result %d. "
Jeff Brown6ec402b2010-07-28 15:48:59 -07002660 "injectorPid=%d, injectorUid=%d",
2661 injectionResult, injectorPid, injectorUid);
2662#endif
2663
Jeff Brown7fbdc842010-06-17 20:52:56 -07002664 return injectionResult;
2665}
2666
Jeff Brownb6997262010-10-08 22:31:17 -07002667bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
2668 return injectorUid == 0
2669 || mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
2670}
2671
Jeff Brown7fbdc842010-06-17 20:52:56 -07002672void InputDispatcher::setInjectionResultLocked(EventEntry* entry, int32_t injectionResult) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002673 InjectionState* injectionState = entry->injectionState;
2674 if (injectionState) {
Jeff Brown7fbdc842010-06-17 20:52:56 -07002675#if DEBUG_INJECTION
Steve Block5baa3a62011-12-20 16:23:08 +00002676 ALOGD("Setting input event injection result to %d. "
Jeff Brown7fbdc842010-06-17 20:52:56 -07002677 "injectorPid=%d, injectorUid=%d",
Jeff Brown01ce2e92010-09-26 22:20:12 -07002678 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
Jeff Brown7fbdc842010-06-17 20:52:56 -07002679#endif
2680
Jeff Brown0029c662011-03-30 02:25:18 -07002681 if (injectionState->injectionIsAsync
2682 && !(entry->policyFlags & POLICY_FLAG_FILTERED)) {
Jeff Brown6ec402b2010-07-28 15:48:59 -07002683 // Log the outcome since the injector did not wait for the injection result.
2684 switch (injectionResult) {
2685 case INPUT_EVENT_INJECTION_SUCCEEDED:
Steve Block71f2cf12011-10-20 11:56:00 +01002686 ALOGV("Asynchronous input event injection succeeded.");
Jeff Brown6ec402b2010-07-28 15:48:59 -07002687 break;
2688 case INPUT_EVENT_INJECTION_FAILED:
Steve Block8564c8d2012-01-05 23:22:43 +00002689 ALOGW("Asynchronous input event injection failed.");
Jeff Brown6ec402b2010-07-28 15:48:59 -07002690 break;
2691 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
Steve Block8564c8d2012-01-05 23:22:43 +00002692 ALOGW("Asynchronous input event injection permission denied.");
Jeff Brown6ec402b2010-07-28 15:48:59 -07002693 break;
2694 case INPUT_EVENT_INJECTION_TIMED_OUT:
Steve Block8564c8d2012-01-05 23:22:43 +00002695 ALOGW("Asynchronous input event injection timed out.");
Jeff Brown6ec402b2010-07-28 15:48:59 -07002696 break;
2697 }
2698 }
2699
Jeff Brown01ce2e92010-09-26 22:20:12 -07002700 injectionState->injectionResult = injectionResult;
Jeff Brown7fbdc842010-06-17 20:52:56 -07002701 mInjectionResultAvailableCondition.broadcast();
2702 }
2703}
2704
Jeff Brown01ce2e92010-09-26 22:20:12 -07002705void InputDispatcher::incrementPendingForegroundDispatchesLocked(EventEntry* entry) {
2706 InjectionState* injectionState = entry->injectionState;
2707 if (injectionState) {
2708 injectionState->pendingForegroundDispatches += 1;
2709 }
2710}
2711
Jeff Brown519e0242010-09-15 15:18:56 -07002712void InputDispatcher::decrementPendingForegroundDispatchesLocked(EventEntry* entry) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002713 InjectionState* injectionState = entry->injectionState;
2714 if (injectionState) {
2715 injectionState->pendingForegroundDispatches -= 1;
Jeff Brown6ec402b2010-07-28 15:48:59 -07002716
Jeff Brown01ce2e92010-09-26 22:20:12 -07002717 if (injectionState->pendingForegroundDispatches == 0) {
2718 mInjectionSyncFinishedCondition.broadcast();
2719 }
Jeff Brownb88102f2010-09-08 11:49:43 -07002720 }
2721}
2722
Jeff Brown9302c872011-07-13 22:51:29 -07002723sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
2724 const sp<InputChannel>& inputChannel) const {
2725 size_t numWindows = mWindowHandles.size();
2726 for (size_t i = 0; i < numWindows; i++) {
2727 const sp<InputWindowHandle>& windowHandle = mWindowHandles.itemAt(i);
Jeff Browncc4f7db2011-08-30 20:34:48 -07002728 if (windowHandle->getInputChannel() == inputChannel) {
Jeff Brown9302c872011-07-13 22:51:29 -07002729 return windowHandle;
Jeff Brown01ce2e92010-09-26 22:20:12 -07002730 }
2731 }
2732 return NULL;
2733}
2734
Jeff Brown9302c872011-07-13 22:51:29 -07002735bool InputDispatcher::hasWindowHandleLocked(
2736 const sp<InputWindowHandle>& windowHandle) const {
2737 size_t numWindows = mWindowHandles.size();
2738 for (size_t i = 0; i < numWindows; i++) {
2739 if (mWindowHandles.itemAt(i) == windowHandle) {
2740 return true;
2741 }
2742 }
2743 return false;
2744}
2745
2746void InputDispatcher::setInputWindows(const Vector<sp<InputWindowHandle> >& inputWindowHandles) {
Jeff Brownb88102f2010-09-08 11:49:43 -07002747#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002748 ALOGD("setInputWindows");
Jeff Brownb88102f2010-09-08 11:49:43 -07002749#endif
2750 { // acquire lock
2751 AutoMutex _l(mLock);
2752
Jeff Browncc4f7db2011-08-30 20:34:48 -07002753 Vector<sp<InputWindowHandle> > oldWindowHandles = mWindowHandles;
Jeff Brown9302c872011-07-13 22:51:29 -07002754 mWindowHandles = inputWindowHandles;
Jeff Brownb6997262010-10-08 22:31:17 -07002755
Jeff Brown9302c872011-07-13 22:51:29 -07002756 sp<InputWindowHandle> newFocusedWindowHandle;
2757 bool foundHoveredWindow = false;
2758 for (size_t i = 0; i < mWindowHandles.size(); i++) {
2759 const sp<InputWindowHandle>& windowHandle = mWindowHandles.itemAt(i);
Jeff Browncc4f7db2011-08-30 20:34:48 -07002760 if (!windowHandle->updateInfo() || windowHandle->getInputChannel() == NULL) {
Jeff Brown9302c872011-07-13 22:51:29 -07002761 mWindowHandles.removeAt(i--);
2762 continue;
2763 }
Jeff Browncc4f7db2011-08-30 20:34:48 -07002764 if (windowHandle->getInfo()->hasFocus) {
Jeff Brown9302c872011-07-13 22:51:29 -07002765 newFocusedWindowHandle = windowHandle;
2766 }
2767 if (windowHandle == mLastHoverWindowHandle) {
2768 foundHoveredWindow = true;
Jeff Brownb88102f2010-09-08 11:49:43 -07002769 }
2770 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07002771
Jeff Brown9302c872011-07-13 22:51:29 -07002772 if (!foundHoveredWindow) {
2773 mLastHoverWindowHandle = NULL;
2774 }
2775
2776 if (mFocusedWindowHandle != newFocusedWindowHandle) {
2777 if (mFocusedWindowHandle != NULL) {
Jeff Brownb6997262010-10-08 22:31:17 -07002778#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002779 ALOGD("Focus left window: %s",
Jeff Browncc4f7db2011-08-30 20:34:48 -07002780 mFocusedWindowHandle->getName().string());
Jeff Brownb6997262010-10-08 22:31:17 -07002781#endif
Jeff Browncc4f7db2011-08-30 20:34:48 -07002782 sp<InputChannel> focusedInputChannel = mFocusedWindowHandle->getInputChannel();
2783 if (focusedInputChannel != NULL) {
Christopher Tated9be36c2011-08-16 16:09:33 -07002784 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
2785 "focus left window");
2786 synthesizeCancelationEventsForInputChannelLocked(
Jeff Browncc4f7db2011-08-30 20:34:48 -07002787 focusedInputChannel, options);
Christopher Tated9be36c2011-08-16 16:09:33 -07002788 }
Jeff Brownb6997262010-10-08 22:31:17 -07002789 }
Jeff Brown9302c872011-07-13 22:51:29 -07002790 if (newFocusedWindowHandle != NULL) {
Jeff Brownb6997262010-10-08 22:31:17 -07002791#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002792 ALOGD("Focus entered window: %s",
Jeff Browncc4f7db2011-08-30 20:34:48 -07002793 newFocusedWindowHandle->getName().string());
Jeff Brownb6997262010-10-08 22:31:17 -07002794#endif
Jeff Brown9302c872011-07-13 22:51:29 -07002795 }
2796 mFocusedWindowHandle = newFocusedWindowHandle;
Jeff Brownb6997262010-10-08 22:31:17 -07002797 }
2798
Jeff Brown9302c872011-07-13 22:51:29 -07002799 for (size_t i = 0; i < mTouchState.windows.size(); i++) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002800 TouchedWindow& touchedWindow = mTouchState.windows.editItemAt(i);
Jeff Brown9302c872011-07-13 22:51:29 -07002801 if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
Jeff Brownb6997262010-10-08 22:31:17 -07002802#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002803 ALOGD("Touched window was removed: %s",
Jeff Browncc4f7db2011-08-30 20:34:48 -07002804 touchedWindow.windowHandle->getName().string());
Jeff Brownb6997262010-10-08 22:31:17 -07002805#endif
Jeff Browncc4f7db2011-08-30 20:34:48 -07002806 sp<InputChannel> touchedInputChannel =
2807 touchedWindow.windowHandle->getInputChannel();
2808 if (touchedInputChannel != NULL) {
Christopher Tated9be36c2011-08-16 16:09:33 -07002809 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
2810 "touched window was removed");
2811 synthesizeCancelationEventsForInputChannelLocked(
Jeff Browncc4f7db2011-08-30 20:34:48 -07002812 touchedInputChannel, options);
Christopher Tated9be36c2011-08-16 16:09:33 -07002813 }
Jeff Brown9302c872011-07-13 22:51:29 -07002814 mTouchState.windows.removeAt(i--);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002815 }
2816 }
Jeff Browncc4f7db2011-08-30 20:34:48 -07002817
2818 // Release information for windows that are no longer present.
2819 // This ensures that unused input channels are released promptly.
2820 // Otherwise, they might stick around until the window handle is destroyed
2821 // which might not happen until the next GC.
2822 for (size_t i = 0; i < oldWindowHandles.size(); i++) {
2823 const sp<InputWindowHandle>& oldWindowHandle = oldWindowHandles.itemAt(i);
2824 if (!hasWindowHandleLocked(oldWindowHandle)) {
2825#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002826 ALOGD("Window went away: %s", oldWindowHandle->getName().string());
Jeff Browncc4f7db2011-08-30 20:34:48 -07002827#endif
2828 oldWindowHandle->releaseInfo();
2829 }
2830 }
Jeff Brownb88102f2010-09-08 11:49:43 -07002831 } // release lock
2832
2833 // Wake up poll loop since it may need to make new input dispatching choices.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002834 mLooper->wake();
Jeff Brownb88102f2010-09-08 11:49:43 -07002835}
2836
Jeff Brown9302c872011-07-13 22:51:29 -07002837void InputDispatcher::setFocusedApplication(
2838 const sp<InputApplicationHandle>& inputApplicationHandle) {
Jeff Brownb88102f2010-09-08 11:49:43 -07002839#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002840 ALOGD("setFocusedApplication");
Jeff Brownb88102f2010-09-08 11:49:43 -07002841#endif
2842 { // acquire lock
2843 AutoMutex _l(mLock);
2844
Jeff Browncc4f7db2011-08-30 20:34:48 -07002845 if (inputApplicationHandle != NULL && inputApplicationHandle->updateInfo()) {
Jeff Brown5ea29ab2011-07-27 11:50:51 -07002846 if (mFocusedApplicationHandle != inputApplicationHandle) {
2847 if (mFocusedApplicationHandle != NULL) {
Jeff Browne9bb9be2012-02-06 15:47:55 -08002848 resetANRTimeoutsLocked();
Jeff Browncc4f7db2011-08-30 20:34:48 -07002849 mFocusedApplicationHandle->releaseInfo();
Jeff Brown5ea29ab2011-07-27 11:50:51 -07002850 }
2851 mFocusedApplicationHandle = inputApplicationHandle;
2852 }
2853 } else if (mFocusedApplicationHandle != NULL) {
Jeff Browne9bb9be2012-02-06 15:47:55 -08002854 resetANRTimeoutsLocked();
Jeff Browncc4f7db2011-08-30 20:34:48 -07002855 mFocusedApplicationHandle->releaseInfo();
Jeff Brown9302c872011-07-13 22:51:29 -07002856 mFocusedApplicationHandle.clear();
Jeff Brownb88102f2010-09-08 11:49:43 -07002857 }
2858
2859#if DEBUG_FOCUS
Jeff Brownb6997262010-10-08 22:31:17 -07002860 //logDispatchStateLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -07002861#endif
2862 } // release lock
2863
2864 // Wake up poll loop since it may need to make new input dispatching choices.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002865 mLooper->wake();
Jeff Brownb88102f2010-09-08 11:49:43 -07002866}
2867
Jeff Brownb88102f2010-09-08 11:49:43 -07002868void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
2869#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002870 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
Jeff Brownb88102f2010-09-08 11:49:43 -07002871#endif
2872
2873 bool changed;
2874 { // acquire lock
2875 AutoMutex _l(mLock);
2876
2877 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
Jeff Brown120a4592010-10-27 18:43:51 -07002878 if (mDispatchFrozen && !frozen) {
Jeff Brownb88102f2010-09-08 11:49:43 -07002879 resetANRTimeoutsLocked();
2880 }
2881
Jeff Brown120a4592010-10-27 18:43:51 -07002882 if (mDispatchEnabled && !enabled) {
2883 resetAndDropEverythingLocked("dispatcher is being disabled");
2884 }
2885
Jeff Brownb88102f2010-09-08 11:49:43 -07002886 mDispatchEnabled = enabled;
2887 mDispatchFrozen = frozen;
2888 changed = true;
2889 } else {
2890 changed = false;
2891 }
2892
2893#if DEBUG_FOCUS
Jeff Brownb6997262010-10-08 22:31:17 -07002894 //logDispatchStateLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -07002895#endif
2896 } // release lock
2897
2898 if (changed) {
2899 // Wake up poll loop since it may need to make new input dispatching choices.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002900 mLooper->wake();
Jeff Brown46b9ac02010-04-22 18:58:52 -07002901 }
2902}
2903
Jeff Brown0029c662011-03-30 02:25:18 -07002904void InputDispatcher::setInputFilterEnabled(bool enabled) {
2905#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002906 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
Jeff Brown0029c662011-03-30 02:25:18 -07002907#endif
2908
2909 { // acquire lock
2910 AutoMutex _l(mLock);
2911
2912 if (mInputFilterEnabled == enabled) {
2913 return;
2914 }
2915
2916 mInputFilterEnabled = enabled;
2917 resetAndDropEverythingLocked("input filter is being enabled or disabled");
2918 } // release lock
2919
2920 // Wake up poll loop since there might be work to do to drop everything.
2921 mLooper->wake();
2922}
2923
Jeff Browne6504122010-09-27 14:52:15 -07002924bool InputDispatcher::transferTouchFocus(const sp<InputChannel>& fromChannel,
2925 const sp<InputChannel>& toChannel) {
2926#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002927 ALOGD("transferTouchFocus: fromChannel=%s, toChannel=%s",
Jeff Browne6504122010-09-27 14:52:15 -07002928 fromChannel->getName().string(), toChannel->getName().string());
2929#endif
2930 { // acquire lock
2931 AutoMutex _l(mLock);
2932
Jeff Brown9302c872011-07-13 22:51:29 -07002933 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromChannel);
2934 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toChannel);
2935 if (fromWindowHandle == NULL || toWindowHandle == NULL) {
Jeff Browne6504122010-09-27 14:52:15 -07002936#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002937 ALOGD("Cannot transfer focus because from or to window not found.");
Jeff Browne6504122010-09-27 14:52:15 -07002938#endif
2939 return false;
2940 }
Jeff Brown9302c872011-07-13 22:51:29 -07002941 if (fromWindowHandle == toWindowHandle) {
Jeff Browne6504122010-09-27 14:52:15 -07002942#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002943 ALOGD("Trivial transfer to same window.");
Jeff Browne6504122010-09-27 14:52:15 -07002944#endif
2945 return true;
2946 }
2947
2948 bool found = false;
2949 for (size_t i = 0; i < mTouchState.windows.size(); i++) {
2950 const TouchedWindow& touchedWindow = mTouchState.windows[i];
Jeff Brown9302c872011-07-13 22:51:29 -07002951 if (touchedWindow.windowHandle == fromWindowHandle) {
Jeff Browne6504122010-09-27 14:52:15 -07002952 int32_t oldTargetFlags = touchedWindow.targetFlags;
2953 BitSet32 pointerIds = touchedWindow.pointerIds;
2954
2955 mTouchState.windows.removeAt(i);
2956
Jeff Brown46e75292010-11-10 16:53:45 -08002957 int32_t newTargetFlags = oldTargetFlags
Jeff Browna032cc02011-03-07 16:56:21 -08002958 & (InputTarget::FLAG_FOREGROUND
2959 | InputTarget::FLAG_SPLIT | InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brown9302c872011-07-13 22:51:29 -07002960 mTouchState.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Jeff Browne6504122010-09-27 14:52:15 -07002961
2962 found = true;
2963 break;
2964 }
2965 }
2966
2967 if (! found) {
2968#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002969 ALOGD("Focus transfer failed because from window did not have focus.");
Jeff Browne6504122010-09-27 14:52:15 -07002970#endif
2971 return false;
2972 }
2973
Jeff Brown9c9f1a32010-10-11 18:32:20 -07002974 ssize_t fromConnectionIndex = getConnectionIndexLocked(fromChannel);
2975 ssize_t toConnectionIndex = getConnectionIndexLocked(toChannel);
2976 if (fromConnectionIndex >= 0 && toConnectionIndex >= 0) {
Jeff Browncbee6d62012-02-03 20:11:27 -08002977 sp<Connection> fromConnection = mConnectionsByFd.valueAt(fromConnectionIndex);
2978 sp<Connection> toConnection = mConnectionsByFd.valueAt(toConnectionIndex);
Jeff Brown9c9f1a32010-10-11 18:32:20 -07002979
2980 fromConnection->inputState.copyPointerStateTo(toConnection->inputState);
Jeff Brownda3d5a92011-03-29 15:11:34 -07002981 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Jeff Brown9c9f1a32010-10-11 18:32:20 -07002982 "transferring touch focus from this window to another window");
Jeff Brownda3d5a92011-03-29 15:11:34 -07002983 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Jeff Brown9c9f1a32010-10-11 18:32:20 -07002984 }
2985
Jeff Browne6504122010-09-27 14:52:15 -07002986#if DEBUG_FOCUS
2987 logDispatchStateLocked();
2988#endif
2989 } // release lock
2990
2991 // Wake up poll loop since it may need to make new input dispatching choices.
2992 mLooper->wake();
2993 return true;
2994}
2995
Jeff Brown120a4592010-10-27 18:43:51 -07002996void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
2997#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002998 ALOGD("Resetting and dropping all events (%s).", reason);
Jeff Brown120a4592010-10-27 18:43:51 -07002999#endif
3000
Jeff Brownda3d5a92011-03-29 15:11:34 -07003001 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
3002 synthesizeCancelationEventsForAllConnectionsLocked(options);
Jeff Brown120a4592010-10-27 18:43:51 -07003003
3004 resetKeyRepeatLocked();
3005 releasePendingEventLocked();
3006 drainInboundQueueLocked();
Jeff Browne9bb9be2012-02-06 15:47:55 -08003007 resetANRTimeoutsLocked();
Jeff Brown120a4592010-10-27 18:43:51 -07003008
3009 mTouchState.reset();
Jeff Brown9302c872011-07-13 22:51:29 -07003010 mLastHoverWindowHandle.clear();
Jeff Brown120a4592010-10-27 18:43:51 -07003011}
3012
Jeff Brownb88102f2010-09-08 11:49:43 -07003013void InputDispatcher::logDispatchStateLocked() {
3014 String8 dump;
3015 dumpDispatchStateLocked(dump);
Jeff Brown2a95c2a2010-09-16 12:31:46 -07003016
3017 char* text = dump.lockBuffer(dump.size());
3018 char* start = text;
3019 while (*start != '\0') {
3020 char* end = strchr(start, '\n');
3021 if (*end == '\n') {
3022 *(end++) = '\0';
3023 }
Steve Block5baa3a62011-12-20 16:23:08 +00003024 ALOGD("%s", start);
Jeff Brown2a95c2a2010-09-16 12:31:46 -07003025 start = end;
3026 }
Jeff Brownb88102f2010-09-08 11:49:43 -07003027}
3028
3029void InputDispatcher::dumpDispatchStateLocked(String8& dump) {
Jeff Brownf2f48712010-10-01 17:46:21 -07003030 dump.appendFormat(INDENT "DispatchEnabled: %d\n", mDispatchEnabled);
3031 dump.appendFormat(INDENT "DispatchFrozen: %d\n", mDispatchFrozen);
Jeff Brownb88102f2010-09-08 11:49:43 -07003032
Jeff Brown9302c872011-07-13 22:51:29 -07003033 if (mFocusedApplicationHandle != NULL) {
Jeff Brownf2f48712010-10-01 17:46:21 -07003034 dump.appendFormat(INDENT "FocusedApplication: name='%s', dispatchingTimeout=%0.3fms\n",
Jeff Browncc4f7db2011-08-30 20:34:48 -07003035 mFocusedApplicationHandle->getName().string(),
3036 mFocusedApplicationHandle->getDispatchingTimeout(
3037 DEFAULT_INPUT_DISPATCHING_TIMEOUT) / 1000000.0);
Jeff Brownb88102f2010-09-08 11:49:43 -07003038 } else {
Jeff Brownf2f48712010-10-01 17:46:21 -07003039 dump.append(INDENT "FocusedApplication: <null>\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003040 }
Jeff Brownf2f48712010-10-01 17:46:21 -07003041 dump.appendFormat(INDENT "FocusedWindow: name='%s'\n",
Jeff Browncc4f7db2011-08-30 20:34:48 -07003042 mFocusedWindowHandle != NULL ? mFocusedWindowHandle->getName().string() : "<null>");
Jeff Brownf2f48712010-10-01 17:46:21 -07003043
3044 dump.appendFormat(INDENT "TouchDown: %s\n", toString(mTouchState.down));
3045 dump.appendFormat(INDENT "TouchSplit: %s\n", toString(mTouchState.split));
Jeff Brown95712852011-01-04 19:41:59 -08003046 dump.appendFormat(INDENT "TouchDeviceId: %d\n", mTouchState.deviceId);
Jeff Brown58a2da82011-01-25 16:02:22 -08003047 dump.appendFormat(INDENT "TouchSource: 0x%08x\n", mTouchState.source);
Jeff Brownf2f48712010-10-01 17:46:21 -07003048 if (!mTouchState.windows.isEmpty()) {
3049 dump.append(INDENT "TouchedWindows:\n");
3050 for (size_t i = 0; i < mTouchState.windows.size(); i++) {
3051 const TouchedWindow& touchedWindow = mTouchState.windows[i];
3052 dump.appendFormat(INDENT2 "%d: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
Jeff Browncc4f7db2011-08-30 20:34:48 -07003053 i, touchedWindow.windowHandle->getName().string(),
3054 touchedWindow.pointerIds.value,
Jeff Brownf2f48712010-10-01 17:46:21 -07003055 touchedWindow.targetFlags);
3056 }
3057 } else {
3058 dump.append(INDENT "TouchedWindows: <none>\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003059 }
3060
Jeff Brown9302c872011-07-13 22:51:29 -07003061 if (!mWindowHandles.isEmpty()) {
Jeff Brownf2f48712010-10-01 17:46:21 -07003062 dump.append(INDENT "Windows:\n");
Jeff Brown9302c872011-07-13 22:51:29 -07003063 for (size_t i = 0; i < mWindowHandles.size(); i++) {
3064 const sp<InputWindowHandle>& windowHandle = mWindowHandles.itemAt(i);
Jeff Browncc4f7db2011-08-30 20:34:48 -07003065 const InputWindowInfo* windowInfo = windowHandle->getInfo();
3066
Jeff Brownf2f48712010-10-01 17:46:21 -07003067 dump.appendFormat(INDENT2 "%d: name='%s', paused=%s, hasFocus=%s, hasWallpaper=%s, "
3068 "visible=%s, canReceiveKeys=%s, flags=0x%08x, type=0x%08x, layer=%d, "
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003069 "frame=[%d,%d][%d,%d], scale=%f, "
Jeff Brownfbf09772011-01-16 14:06:57 -08003070 "touchableRegion=",
Jeff Browncc4f7db2011-08-30 20:34:48 -07003071 i, windowInfo->name.string(),
3072 toString(windowInfo->paused),
3073 toString(windowInfo->hasFocus),
3074 toString(windowInfo->hasWallpaper),
3075 toString(windowInfo->visible),
3076 toString(windowInfo->canReceiveKeys),
3077 windowInfo->layoutParamsFlags, windowInfo->layoutParamsType,
3078 windowInfo->layer,
3079 windowInfo->frameLeft, windowInfo->frameTop,
3080 windowInfo->frameRight, windowInfo->frameBottom,
3081 windowInfo->scaleFactor);
3082 dumpRegion(dump, windowInfo->touchableRegion);
3083 dump.appendFormat(", inputFeatures=0x%08x", windowInfo->inputFeatures);
Jeff Brownfbf09772011-01-16 14:06:57 -08003084 dump.appendFormat(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%0.3fms\n",
Jeff Browncc4f7db2011-08-30 20:34:48 -07003085 windowInfo->ownerPid, windowInfo->ownerUid,
3086 windowInfo->dispatchingTimeout / 1000000.0);
Jeff Brownf2f48712010-10-01 17:46:21 -07003087 }
3088 } else {
3089 dump.append(INDENT "Windows: <none>\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003090 }
3091
Jeff Brownf2f48712010-10-01 17:46:21 -07003092 if (!mMonitoringChannels.isEmpty()) {
3093 dump.append(INDENT "MonitoringChannels:\n");
3094 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
3095 const sp<InputChannel>& channel = mMonitoringChannels[i];
3096 dump.appendFormat(INDENT2 "%d: '%s'\n", i, channel->getName().string());
3097 }
3098 } else {
3099 dump.append(INDENT "MonitoringChannels: <none>\n");
3100 }
Jeff Brown519e0242010-09-15 15:18:56 -07003101
Jeff Brownf2f48712010-10-01 17:46:21 -07003102 dump.appendFormat(INDENT "InboundQueue: length=%u\n", mInboundQueue.count());
3103
Jeff Brownb88102f2010-09-08 11:49:43 -07003104 if (isAppSwitchPendingLocked()) {
Jeff Brownf2f48712010-10-01 17:46:21 -07003105 dump.appendFormat(INDENT "AppSwitch: pending, due in %01.1fms\n",
Jeff Brownb88102f2010-09-08 11:49:43 -07003106 (mAppSwitchDueTime - now()) / 1000000.0);
3107 } else {
Jeff Brownf2f48712010-10-01 17:46:21 -07003108 dump.append(INDENT "AppSwitch: not pending\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003109 }
3110}
3111
Jeff Brown928e0542011-01-10 11:17:36 -08003112status_t InputDispatcher::registerInputChannel(const sp<InputChannel>& inputChannel,
3113 const sp<InputWindowHandle>& inputWindowHandle, bool monitor) {
Jeff Brown9c3cda02010-06-15 01:31:58 -07003114#if DEBUG_REGISTRATION
Steve Block5baa3a62011-12-20 16:23:08 +00003115 ALOGD("channel '%s' ~ registerInputChannel - monitor=%s", inputChannel->getName().string(),
Jeff Brownb88102f2010-09-08 11:49:43 -07003116 toString(monitor));
Jeff Brown9c3cda02010-06-15 01:31:58 -07003117#endif
3118
Jeff Brown46b9ac02010-04-22 18:58:52 -07003119 { // acquire lock
3120 AutoMutex _l(mLock);
3121
Jeff Brown519e0242010-09-15 15:18:56 -07003122 if (getConnectionIndexLocked(inputChannel) >= 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00003123 ALOGW("Attempted to register already registered input channel '%s'",
Jeff Brown46b9ac02010-04-22 18:58:52 -07003124 inputChannel->getName().string());
3125 return BAD_VALUE;
3126 }
3127
Jeff Browncc4f7db2011-08-30 20:34:48 -07003128 sp<Connection> connection = new Connection(inputChannel, inputWindowHandle, monitor);
Jeff Brown46b9ac02010-04-22 18:58:52 -07003129
Jeff Brown91e32892012-02-14 15:56:29 -08003130 int fd = inputChannel->getFd();
Jeff Browncbee6d62012-02-03 20:11:27 -08003131 mConnectionsByFd.add(fd, connection);
Jeff Brown9c3cda02010-06-15 01:31:58 -07003132
Jeff Brownb88102f2010-09-08 11:49:43 -07003133 if (monitor) {
3134 mMonitoringChannels.push(inputChannel);
3135 }
3136
Jeff Browncbee6d62012-02-03 20:11:27 -08003137 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
Jeff Brown2cbecea2010-08-17 15:59:26 -07003138
Jeff Brown9c3cda02010-06-15 01:31:58 -07003139 runCommandsLockedInterruptible();
Jeff Brown46b9ac02010-04-22 18:58:52 -07003140 } // release lock
Jeff Brown46b9ac02010-04-22 18:58:52 -07003141 return OK;
3142}
3143
3144status_t InputDispatcher::unregisterInputChannel(const sp<InputChannel>& inputChannel) {
Jeff Brown9c3cda02010-06-15 01:31:58 -07003145#if DEBUG_REGISTRATION
Steve Block5baa3a62011-12-20 16:23:08 +00003146 ALOGD("channel '%s' ~ unregisterInputChannel", inputChannel->getName().string());
Jeff Brown9c3cda02010-06-15 01:31:58 -07003147#endif
3148
Jeff Brown46b9ac02010-04-22 18:58:52 -07003149 { // acquire lock
3150 AutoMutex _l(mLock);
3151
Jeff Browncc4f7db2011-08-30 20:34:48 -07003152 status_t status = unregisterInputChannelLocked(inputChannel, false /*notify*/);
3153 if (status) {
3154 return status;
Jeff Brown46b9ac02010-04-22 18:58:52 -07003155 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07003156 } // release lock
3157
Jeff Brown46b9ac02010-04-22 18:58:52 -07003158 // Wake the poll loop because removing the connection may have changed the current
3159 // synchronization state.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07003160 mLooper->wake();
Jeff Brown46b9ac02010-04-22 18:58:52 -07003161 return OK;
3162}
3163
Jeff Browncc4f7db2011-08-30 20:34:48 -07003164status_t InputDispatcher::unregisterInputChannelLocked(const sp<InputChannel>& inputChannel,
3165 bool notify) {
3166 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
3167 if (connectionIndex < 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00003168 ALOGW("Attempted to unregister already unregistered input channel '%s'",
Jeff Browncc4f7db2011-08-30 20:34:48 -07003169 inputChannel->getName().string());
3170 return BAD_VALUE;
3171 }
3172
Jeff Browncbee6d62012-02-03 20:11:27 -08003173 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
3174 mConnectionsByFd.removeItemsAt(connectionIndex);
Jeff Browncc4f7db2011-08-30 20:34:48 -07003175
3176 if (connection->monitor) {
3177 removeMonitorChannelLocked(inputChannel);
3178 }
3179
Jeff Browncbee6d62012-02-03 20:11:27 -08003180 mLooper->removeFd(inputChannel->getFd());
Jeff Browncc4f7db2011-08-30 20:34:48 -07003181
3182 nsecs_t currentTime = now();
3183 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
3184
3185 runCommandsLockedInterruptible();
3186
3187 connection->status = Connection::STATUS_ZOMBIE;
3188 return OK;
3189}
3190
3191void InputDispatcher::removeMonitorChannelLocked(const sp<InputChannel>& inputChannel) {
3192 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
3193 if (mMonitoringChannels[i] == inputChannel) {
3194 mMonitoringChannels.removeAt(i);
3195 break;
3196 }
3197 }
3198}
3199
Jeff Brown519e0242010-09-15 15:18:56 -07003200ssize_t InputDispatcher::getConnectionIndexLocked(const sp<InputChannel>& inputChannel) {
Jeff Browncbee6d62012-02-03 20:11:27 -08003201 ssize_t connectionIndex = mConnectionsByFd.indexOfKey(inputChannel->getFd());
Jeff Brown2cbecea2010-08-17 15:59:26 -07003202 if (connectionIndex >= 0) {
Jeff Browncbee6d62012-02-03 20:11:27 -08003203 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
Jeff Brown2cbecea2010-08-17 15:59:26 -07003204 if (connection->inputChannel.get() == inputChannel.get()) {
3205 return connectionIndex;
3206 }
3207 }
3208
3209 return -1;
3210}
3211
Jeff Brown9c3cda02010-06-15 01:31:58 -07003212void InputDispatcher::onDispatchCycleFinishedLocked(
Jeff Brown072ec962012-02-07 14:46:57 -08003213 nsecs_t currentTime, const sp<Connection>& connection, uint32_t seq, bool handled) {
Jeff Brown3915bb82010-11-05 15:02:16 -07003214 CommandEntry* commandEntry = postCommandLocked(
3215 & InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
3216 commandEntry->connection = connection;
Jeff Brown072ec962012-02-07 14:46:57 -08003217 commandEntry->seq = seq;
Jeff Brown3915bb82010-11-05 15:02:16 -07003218 commandEntry->handled = handled;
Jeff Brown46b9ac02010-04-22 18:58:52 -07003219}
3220
Jeff Brown9c3cda02010-06-15 01:31:58 -07003221void InputDispatcher::onDispatchCycleBrokenLocked(
Jeff Brown7fbdc842010-06-17 20:52:56 -07003222 nsecs_t currentTime, const sp<Connection>& connection) {
Steve Block3762c312012-01-06 19:20:56 +00003223 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Jeff Brown46b9ac02010-04-22 18:58:52 -07003224 connection->getInputChannelName());
3225
Jeff Brown9c3cda02010-06-15 01:31:58 -07003226 CommandEntry* commandEntry = postCommandLocked(
3227 & InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
Jeff Brown7fbdc842010-06-17 20:52:56 -07003228 commandEntry->connection = connection;
Jeff Brown46b9ac02010-04-22 18:58:52 -07003229}
3230
Jeff Brown519e0242010-09-15 15:18:56 -07003231void InputDispatcher::onANRLocked(
Jeff Brown9302c872011-07-13 22:51:29 -07003232 nsecs_t currentTime, const sp<InputApplicationHandle>& applicationHandle,
3233 const sp<InputWindowHandle>& windowHandle,
Jeff Brown519e0242010-09-15 15:18:56 -07003234 nsecs_t eventTime, nsecs_t waitStartTime) {
Steve Block6215d3f2012-01-04 20:05:49 +00003235 ALOGI("Application is not responding: %s. "
Jeff Brown519e0242010-09-15 15:18:56 -07003236 "%01.1fms since event, %01.1fms since wait started",
Jeff Brown9302c872011-07-13 22:51:29 -07003237 getApplicationWindowLabelLocked(applicationHandle, windowHandle).string(),
Jeff Brown519e0242010-09-15 15:18:56 -07003238 (currentTime - eventTime) / 1000000.0,
3239 (currentTime - waitStartTime) / 1000000.0);
3240
3241 CommandEntry* commandEntry = postCommandLocked(
3242 & InputDispatcher::doNotifyANRLockedInterruptible);
Jeff Brown9302c872011-07-13 22:51:29 -07003243 commandEntry->inputApplicationHandle = applicationHandle;
3244 commandEntry->inputWindowHandle = windowHandle;
Jeff Brown519e0242010-09-15 15:18:56 -07003245}
3246
Jeff Brownb88102f2010-09-08 11:49:43 -07003247void InputDispatcher::doNotifyConfigurationChangedInterruptible(
3248 CommandEntry* commandEntry) {
3249 mLock.unlock();
3250
3251 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
3252
3253 mLock.lock();
3254}
3255
Jeff Brown9c3cda02010-06-15 01:31:58 -07003256void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(
3257 CommandEntry* commandEntry) {
Jeff Brown7fbdc842010-06-17 20:52:56 -07003258 sp<Connection> connection = commandEntry->connection;
Jeff Brown9c3cda02010-06-15 01:31:58 -07003259
Jeff Brown7fbdc842010-06-17 20:52:56 -07003260 if (connection->status != Connection::STATUS_ZOMBIE) {
3261 mLock.unlock();
Jeff Brown9c3cda02010-06-15 01:31:58 -07003262
Jeff Brown928e0542011-01-10 11:17:36 -08003263 mPolicy->notifyInputChannelBroken(connection->inputWindowHandle);
Jeff Brown7fbdc842010-06-17 20:52:56 -07003264
3265 mLock.lock();
3266 }
Jeff Brown9c3cda02010-06-15 01:31:58 -07003267}
3268
Jeff Brown519e0242010-09-15 15:18:56 -07003269void InputDispatcher::doNotifyANRLockedInterruptible(
Jeff Brown9c3cda02010-06-15 01:31:58 -07003270 CommandEntry* commandEntry) {
Jeff Brown519e0242010-09-15 15:18:56 -07003271 mLock.unlock();
Jeff Brown9c3cda02010-06-15 01:31:58 -07003272
Jeff Brown519e0242010-09-15 15:18:56 -07003273 nsecs_t newTimeout = mPolicy->notifyANR(
Jeff Brown928e0542011-01-10 11:17:36 -08003274 commandEntry->inputApplicationHandle, commandEntry->inputWindowHandle);
Jeff Brown9c3cda02010-06-15 01:31:58 -07003275
Jeff Brown519e0242010-09-15 15:18:56 -07003276 mLock.lock();
Jeff Brown7fbdc842010-06-17 20:52:56 -07003277
Jeff Brown9302c872011-07-13 22:51:29 -07003278 resumeAfterTargetsNotReadyTimeoutLocked(newTimeout,
3279 commandEntry->inputWindowHandle != NULL
Jeff Browncc4f7db2011-08-30 20:34:48 -07003280 ? commandEntry->inputWindowHandle->getInputChannel() : NULL);
Jeff Brown9c3cda02010-06-15 01:31:58 -07003281}
3282
Jeff Brownb88102f2010-09-08 11:49:43 -07003283void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
3284 CommandEntry* commandEntry) {
3285 KeyEntry* entry = commandEntry->keyEntry;
Jeff Brown1f245102010-11-18 20:53:46 -08003286
3287 KeyEvent event;
3288 initializeKeyEvent(&event, entry);
Jeff Brownb88102f2010-09-08 11:49:43 -07003289
3290 mLock.unlock();
3291
Jeff Brown905805a2011-10-12 13:57:59 -07003292 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(commandEntry->inputWindowHandle,
Jeff Brown1f245102010-11-18 20:53:46 -08003293 &event, entry->policyFlags);
Jeff Brownb88102f2010-09-08 11:49:43 -07003294
3295 mLock.lock();
3296
Jeff Brown905805a2011-10-12 13:57:59 -07003297 if (delay < 0) {
3298 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
3299 } else if (!delay) {
3300 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
3301 } else {
3302 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
3303 entry->interceptKeyWakeupTime = now() + delay;
3304 }
Jeff Brownac386072011-07-20 15:19:50 -07003305 entry->release();
Jeff Brownb88102f2010-09-08 11:49:43 -07003306}
3307
Jeff Brown3915bb82010-11-05 15:02:16 -07003308void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(
3309 CommandEntry* commandEntry) {
3310 sp<Connection> connection = commandEntry->connection;
Jeff Brown072ec962012-02-07 14:46:57 -08003311 uint32_t seq = commandEntry->seq;
Jeff Brown3915bb82010-11-05 15:02:16 -07003312 bool handled = commandEntry->handled;
3313
Jeff Brown072ec962012-02-07 14:46:57 -08003314 // Handle post-event policy actions.
3315 DispatchEntry* dispatchEntry = connection->findWaitQueueEntry(seq);
3316 if (dispatchEntry) {
Jeff Brownd1c48a02012-02-06 19:12:47 -08003317 bool restartEvent;
Jeff Brownd1c48a02012-02-06 19:12:47 -08003318 if (dispatchEntry->eventEntry->type == EventEntry::TYPE_KEY) {
3319 KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry);
3320 restartEvent = afterKeyEventLockedInterruptible(connection,
3321 dispatchEntry, keyEntry, handled);
3322 } else if (dispatchEntry->eventEntry->type == EventEntry::TYPE_MOTION) {
3323 MotionEntry* motionEntry = static_cast<MotionEntry*>(dispatchEntry->eventEntry);
3324 restartEvent = afterMotionEventLockedInterruptible(connection,
3325 dispatchEntry, motionEntry, handled);
3326 } else {
3327 restartEvent = false;
3328 }
3329
3330 // Dequeue the event and start the next cycle.
3331 // Note that because the lock might have been released, it is possible that the
3332 // contents of the wait queue to have been drained, so we need to double-check
3333 // a few things.
Jeff Brown072ec962012-02-07 14:46:57 -08003334 if (dispatchEntry == connection->findWaitQueueEntry(seq)) {
3335 connection->waitQueue.dequeue(dispatchEntry);
Jeff Brown481c1572012-03-09 14:41:15 -08003336 traceWaitQueueLengthLocked(connection);
Jeff Brownd1c48a02012-02-06 19:12:47 -08003337 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
3338 connection->outboundQueue.enqueueAtHead(dispatchEntry);
Jeff Brown481c1572012-03-09 14:41:15 -08003339 traceOutboundQueueLengthLocked(connection);
Jeff Brownd1c48a02012-02-06 19:12:47 -08003340 } else {
3341 releaseDispatchEntryLocked(dispatchEntry);
Jeff Brown49ed71d2010-12-06 17:13:33 -08003342 }
Jeff Brown3915bb82010-11-05 15:02:16 -07003343 }
Jeff Brown3915bb82010-11-05 15:02:16 -07003344
Jeff Brownd1c48a02012-02-06 19:12:47 -08003345 // Start the next dispatch cycle for this connection.
3346 startDispatchCycleLocked(now(), connection);
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003347 }
3348}
3349
3350bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
3351 DispatchEntry* dispatchEntry, KeyEntry* keyEntry, bool handled) {
3352 if (!(keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK)) {
3353 // Get the fallback key state.
3354 // Clear it out after dispatching the UP.
3355 int32_t originalKeyCode = keyEntry->keyCode;
3356 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
3357 if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
3358 connection->inputState.removeFallbackKey(originalKeyCode);
3359 }
3360
3361 if (handled || !dispatchEntry->hasForegroundTarget()) {
3362 // If the application handles the original key for which we previously
3363 // generated a fallback or if the window is not a foreground window,
3364 // then cancel the associated fallback key, if any.
3365 if (fallbackKeyCode != -1) {
Jeff Brownfd23e3e2012-05-09 13:34:28 -07003366 // Dispatch the unhandled key to the policy with the cancel flag.
3367#if DEBUG_OUTBOUND_EVENT_DETAILS
3368 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
3369 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
3370 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
3371 keyEntry->policyFlags);
3372#endif
3373 KeyEvent event;
3374 initializeKeyEvent(&event, keyEntry);
3375 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
3376
3377 mLock.unlock();
3378
3379 mPolicy->dispatchUnhandledKey(connection->inputWindowHandle,
3380 &event, keyEntry->policyFlags, &event);
3381
3382 mLock.lock();
3383
3384 // Cancel the fallback key.
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003385 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
3386 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
3387 "application handled the original non-fallback key "
3388 "or is no longer a foreground target, "
3389 "canceling previously dispatched fallback key");
3390 options.keyCode = fallbackKeyCode;
3391 synthesizeCancelationEventsForConnectionLocked(connection, options);
3392 }
3393 connection->inputState.removeFallbackKey(originalKeyCode);
3394 }
3395 } else {
3396 // If the application did not handle a non-fallback key, first check
3397 // that we are in a good state to perform unhandled key event processing
3398 // Then ask the policy what to do with it.
3399 bool initialDown = keyEntry->action == AKEY_EVENT_ACTION_DOWN
3400 && keyEntry->repeatCount == 0;
3401 if (fallbackKeyCode == -1 && !initialDown) {
3402#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00003403 ALOGD("Unhandled key event: Skipping unhandled key event processing "
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003404 "since this is not an initial down. "
Jeff Brownfd23e3e2012-05-09 13:34:28 -07003405 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
3406 originalKeyCode, keyEntry->action, keyEntry->repeatCount,
3407 keyEntry->policyFlags);
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003408#endif
3409 return false;
3410 }
3411
3412 // Dispatch the unhandled key to the policy.
3413#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00003414 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
Jeff Brownfd23e3e2012-05-09 13:34:28 -07003415 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
3416 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
3417 keyEntry->policyFlags);
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003418#endif
3419 KeyEvent event;
3420 initializeKeyEvent(&event, keyEntry);
3421
3422 mLock.unlock();
3423
3424 bool fallback = mPolicy->dispatchUnhandledKey(connection->inputWindowHandle,
3425 &event, keyEntry->policyFlags, &event);
3426
3427 mLock.lock();
3428
3429 if (connection->status != Connection::STATUS_NORMAL) {
3430 connection->inputState.removeFallbackKey(originalKeyCode);
Jeff Brownd1c48a02012-02-06 19:12:47 -08003431 return false;
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003432 }
3433
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003434 // Latch the fallback keycode for this key on an initial down.
3435 // The fallback keycode cannot change at any other point in the lifecycle.
3436 if (initialDown) {
3437 if (fallback) {
3438 fallbackKeyCode = event.getKeyCode();
3439 } else {
3440 fallbackKeyCode = AKEYCODE_UNKNOWN;
3441 }
3442 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
3443 }
3444
Steve Blockec193de2012-01-09 18:35:44 +00003445 ALOG_ASSERT(fallbackKeyCode != -1);
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003446
3447 // Cancel the fallback key if the policy decides not to send it anymore.
3448 // We will continue to dispatch the key to the policy but we will no
3449 // longer dispatch a fallback key to the application.
3450 if (fallbackKeyCode != AKEYCODE_UNKNOWN
3451 && (!fallback || fallbackKeyCode != event.getKeyCode())) {
3452#if DEBUG_OUTBOUND_EVENT_DETAILS
3453 if (fallback) {
Steve Block5baa3a62011-12-20 16:23:08 +00003454 ALOGD("Unhandled key event: Policy requested to send key %d"
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003455 "as a fallback for %d, but on the DOWN it had requested "
3456 "to send %d instead. Fallback canceled.",
3457 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
3458 } else {
Jeff Brownfd23e3e2012-05-09 13:34:28 -07003459 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003460 "but on the DOWN it had requested to send %d. "
3461 "Fallback canceled.",
3462 originalKeyCode, fallbackKeyCode);
3463 }
3464#endif
3465
3466 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
3467 "canceling fallback, policy no longer desires it");
3468 options.keyCode = fallbackKeyCode;
3469 synthesizeCancelationEventsForConnectionLocked(connection, options);
3470
3471 fallback = false;
3472 fallbackKeyCode = AKEYCODE_UNKNOWN;
3473 if (keyEntry->action != AKEY_EVENT_ACTION_UP) {
3474 connection->inputState.setFallbackKey(originalKeyCode,
3475 fallbackKeyCode);
3476 }
3477 }
3478
3479#if DEBUG_OUTBOUND_EVENT_DETAILS
3480 {
3481 String8 msg;
3482 const KeyedVector<int32_t, int32_t>& fallbackKeys =
3483 connection->inputState.getFallbackKeys();
3484 for (size_t i = 0; i < fallbackKeys.size(); i++) {
3485 msg.appendFormat(", %d->%d", fallbackKeys.keyAt(i),
3486 fallbackKeys.valueAt(i));
3487 }
Steve Block5baa3a62011-12-20 16:23:08 +00003488 ALOGD("Unhandled key event: %d currently tracked fallback keys%s.",
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003489 fallbackKeys.size(), msg.string());
3490 }
3491#endif
3492
3493 if (fallback) {
3494 // Restart the dispatch cycle using the fallback key.
3495 keyEntry->eventTime = event.getEventTime();
3496 keyEntry->deviceId = event.getDeviceId();
3497 keyEntry->source = event.getSource();
3498 keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
3499 keyEntry->keyCode = fallbackKeyCode;
3500 keyEntry->scanCode = event.getScanCode();
3501 keyEntry->metaState = event.getMetaState();
3502 keyEntry->repeatCount = event.getRepeatCount();
3503 keyEntry->downTime = event.getDownTime();
3504 keyEntry->syntheticRepeat = false;
3505
3506#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00003507 ALOGD("Unhandled key event: Dispatching fallback key. "
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003508 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
3509 originalKeyCode, fallbackKeyCode, keyEntry->metaState);
3510#endif
Jeff Brownd1c48a02012-02-06 19:12:47 -08003511 return true; // restart the event
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003512 } else {
3513#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00003514 ALOGD("Unhandled key event: No fallback key.");
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003515#endif
3516 }
3517 }
3518 }
3519 return false;
3520}
3521
3522bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
3523 DispatchEntry* dispatchEntry, MotionEntry* motionEntry, bool handled) {
3524 return false;
Jeff Brown3915bb82010-11-05 15:02:16 -07003525}
3526
Jeff Brownb88102f2010-09-08 11:49:43 -07003527void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
3528 mLock.unlock();
3529
Jeff Brown01ce2e92010-09-26 22:20:12 -07003530 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
Jeff Brownb88102f2010-09-08 11:49:43 -07003531
3532 mLock.lock();
3533}
3534
Jeff Brown3915bb82010-11-05 15:02:16 -07003535void InputDispatcher::initializeKeyEvent(KeyEvent* event, const KeyEntry* entry) {
3536 event->initialize(entry->deviceId, entry->source, entry->action, entry->flags,
3537 entry->keyCode, entry->scanCode, entry->metaState, entry->repeatCount,
3538 entry->downTime, entry->eventTime);
3539}
3540
Jeff Brown519e0242010-09-15 15:18:56 -07003541void InputDispatcher::updateDispatchStatisticsLocked(nsecs_t currentTime, const EventEntry* entry,
3542 int32_t injectionResult, nsecs_t timeSpentWaitingForApplication) {
3543 // TODO Write some statistics about how long we spend waiting.
Jeff Brownb88102f2010-09-08 11:49:43 -07003544}
3545
Jeff Brown481c1572012-03-09 14:41:15 -08003546void InputDispatcher::traceInboundQueueLengthLocked() {
3547 if (ATRACE_ENABLED()) {
3548 ATRACE_INT("iq", mInboundQueue.count());
3549 }
3550}
3551
3552void InputDispatcher::traceOutboundQueueLengthLocked(const sp<Connection>& connection) {
3553 if (ATRACE_ENABLED()) {
3554 char counterName[40];
3555 snprintf(counterName, sizeof(counterName), "oq:%s", connection->getWindowName());
3556 ATRACE_INT(counterName, connection->outboundQueue.count());
3557 }
3558}
3559
3560void InputDispatcher::traceWaitQueueLengthLocked(const sp<Connection>& connection) {
3561 if (ATRACE_ENABLED()) {
3562 char counterName[40];
3563 snprintf(counterName, sizeof(counterName), "wq:%s", connection->getWindowName());
3564 ATRACE_INT(counterName, connection->waitQueue.count());
3565 }
3566}
3567
Jeff Brownb88102f2010-09-08 11:49:43 -07003568void InputDispatcher::dump(String8& dump) {
Jeff Brown89ef0722011-08-10 16:25:21 -07003569 AutoMutex _l(mLock);
3570
Jeff Brownf2f48712010-10-01 17:46:21 -07003571 dump.append("Input Dispatcher State:\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003572 dumpDispatchStateLocked(dump);
Jeff Brown214eaf42011-05-26 19:17:02 -07003573
3574 dump.append(INDENT "Configuration:\n");
Jeff Brown214eaf42011-05-26 19:17:02 -07003575 dump.appendFormat(INDENT2 "KeyRepeatDelay: %0.1fms\n", mConfig.keyRepeatDelay * 0.000001f);
3576 dump.appendFormat(INDENT2 "KeyRepeatTimeout: %0.1fms\n", mConfig.keyRepeatTimeout * 0.000001f);
Jeff Brownb88102f2010-09-08 11:49:43 -07003577}
3578
Jeff Brown89ef0722011-08-10 16:25:21 -07003579void InputDispatcher::monitor() {
3580 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
3581 mLock.lock();
Jeff Brown112b5f52012-01-27 17:32:06 -08003582 mLooper->wake();
3583 mDispatcherIsAliveCondition.wait(mLock);
Jeff Brown89ef0722011-08-10 16:25:21 -07003584 mLock.unlock();
3585}
3586
Jeff Brown9c3cda02010-06-15 01:31:58 -07003587
Jeff Brown519e0242010-09-15 15:18:56 -07003588// --- InputDispatcher::Queue ---
3589
3590template <typename T>
3591uint32_t InputDispatcher::Queue<T>::count() const {
3592 uint32_t result = 0;
Jeff Brownac386072011-07-20 15:19:50 -07003593 for (const T* entry = head; entry; entry = entry->next) {
Jeff Brown519e0242010-09-15 15:18:56 -07003594 result += 1;
3595 }
3596 return result;
3597}
3598
3599
Jeff Brownac386072011-07-20 15:19:50 -07003600// --- InputDispatcher::InjectionState ---
Jeff Brown46b9ac02010-04-22 18:58:52 -07003601
Jeff Brownac386072011-07-20 15:19:50 -07003602InputDispatcher::InjectionState::InjectionState(int32_t injectorPid, int32_t injectorUid) :
3603 refCount(1),
3604 injectorPid(injectorPid), injectorUid(injectorUid),
3605 injectionResult(INPUT_EVENT_INJECTION_PENDING), injectionIsAsync(false),
3606 pendingForegroundDispatches(0) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07003607}
3608
Jeff Brownac386072011-07-20 15:19:50 -07003609InputDispatcher::InjectionState::~InjectionState() {
Jeff Brown01ce2e92010-09-26 22:20:12 -07003610}
3611
Jeff Brownac386072011-07-20 15:19:50 -07003612void InputDispatcher::InjectionState::release() {
3613 refCount -= 1;
3614 if (refCount == 0) {
3615 delete this;
3616 } else {
Steve Blockec193de2012-01-09 18:35:44 +00003617 ALOG_ASSERT(refCount > 0);
Jeff Brown01ce2e92010-09-26 22:20:12 -07003618 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07003619}
3620
Jeff Brownac386072011-07-20 15:19:50 -07003621
3622// --- InputDispatcher::EventEntry ---
3623
3624InputDispatcher::EventEntry::EventEntry(int32_t type, nsecs_t eventTime, uint32_t policyFlags) :
3625 refCount(1), type(type), eventTime(eventTime), policyFlags(policyFlags),
3626 injectionState(NULL), dispatchInProgress(false) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07003627}
3628
Jeff Brownac386072011-07-20 15:19:50 -07003629InputDispatcher::EventEntry::~EventEntry() {
3630 releaseInjectionState();
3631}
3632
3633void InputDispatcher::EventEntry::release() {
3634 refCount -= 1;
3635 if (refCount == 0) {
3636 delete this;
3637 } else {
Steve Blockec193de2012-01-09 18:35:44 +00003638 ALOG_ASSERT(refCount > 0);
Jeff Brownac386072011-07-20 15:19:50 -07003639 }
3640}
3641
3642void InputDispatcher::EventEntry::releaseInjectionState() {
3643 if (injectionState) {
3644 injectionState->release();
3645 injectionState = NULL;
3646 }
3647}
3648
3649
3650// --- InputDispatcher::ConfigurationChangedEntry ---
3651
3652InputDispatcher::ConfigurationChangedEntry::ConfigurationChangedEntry(nsecs_t eventTime) :
3653 EventEntry(TYPE_CONFIGURATION_CHANGED, eventTime, 0) {
3654}
3655
3656InputDispatcher::ConfigurationChangedEntry::~ConfigurationChangedEntry() {
3657}
3658
3659
Jeff Brown65fd2512011-08-18 11:20:58 -07003660// --- InputDispatcher::DeviceResetEntry ---
3661
3662InputDispatcher::DeviceResetEntry::DeviceResetEntry(nsecs_t eventTime, int32_t deviceId) :
3663 EventEntry(TYPE_DEVICE_RESET, eventTime, 0),
3664 deviceId(deviceId) {
3665}
3666
3667InputDispatcher::DeviceResetEntry::~DeviceResetEntry() {
3668}
3669
3670
Jeff Brownac386072011-07-20 15:19:50 -07003671// --- InputDispatcher::KeyEntry ---
3672
3673InputDispatcher::KeyEntry::KeyEntry(nsecs_t eventTime,
Jeff Brown58a2da82011-01-25 16:02:22 -08003674 int32_t deviceId, uint32_t source, uint32_t policyFlags, int32_t action,
Jeff Brown7fbdc842010-06-17 20:52:56 -07003675 int32_t flags, int32_t keyCode, int32_t scanCode, int32_t metaState,
Jeff Brownac386072011-07-20 15:19:50 -07003676 int32_t repeatCount, nsecs_t downTime) :
3677 EventEntry(TYPE_KEY, eventTime, policyFlags),
3678 deviceId(deviceId), source(source), action(action), flags(flags),
3679 keyCode(keyCode), scanCode(scanCode), metaState(metaState),
3680 repeatCount(repeatCount), downTime(downTime),
Jeff Brown905805a2011-10-12 13:57:59 -07003681 syntheticRepeat(false), interceptKeyResult(KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN),
3682 interceptKeyWakeupTime(0) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07003683}
3684
Jeff Brownac386072011-07-20 15:19:50 -07003685InputDispatcher::KeyEntry::~KeyEntry() {
3686}
Jeff Brown7fbdc842010-06-17 20:52:56 -07003687
Jeff Brownac386072011-07-20 15:19:50 -07003688void InputDispatcher::KeyEntry::recycle() {
3689 releaseInjectionState();
3690
3691 dispatchInProgress = false;
3692 syntheticRepeat = false;
3693 interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
Jeff Brown905805a2011-10-12 13:57:59 -07003694 interceptKeyWakeupTime = 0;
Jeff Brownac386072011-07-20 15:19:50 -07003695}
3696
3697
Jeff Brownae9fc032010-08-18 15:51:08 -07003698// --- InputDispatcher::MotionEntry ---
3699
Jeff Brownac386072011-07-20 15:19:50 -07003700InputDispatcher::MotionEntry::MotionEntry(nsecs_t eventTime,
3701 int32_t deviceId, uint32_t source, uint32_t policyFlags, int32_t action, int32_t flags,
3702 int32_t metaState, int32_t buttonState,
3703 int32_t edgeFlags, float xPrecision, float yPrecision,
3704 nsecs_t downTime, uint32_t pointerCount,
3705 const PointerProperties* pointerProperties, const PointerCoords* pointerCoords) :
3706 EventEntry(TYPE_MOTION, eventTime, policyFlags),
Jeff Brown3241b6b2012-02-03 15:08:02 -08003707 eventTime(eventTime),
Jeff Brownac386072011-07-20 15:19:50 -07003708 deviceId(deviceId), source(source), action(action), flags(flags),
3709 metaState(metaState), buttonState(buttonState), edgeFlags(edgeFlags),
3710 xPrecision(xPrecision), yPrecision(yPrecision),
Jeff Brown3241b6b2012-02-03 15:08:02 -08003711 downTime(downTime), pointerCount(pointerCount) {
Jeff Brownac386072011-07-20 15:19:50 -07003712 for (uint32_t i = 0; i < pointerCount; i++) {
3713 this->pointerProperties[i].copyFrom(pointerProperties[i]);
Jeff Brown3241b6b2012-02-03 15:08:02 -08003714 this->pointerCoords[i].copyFrom(pointerCoords[i]);
Jeff Brownac386072011-07-20 15:19:50 -07003715 }
3716}
3717
3718InputDispatcher::MotionEntry::~MotionEntry() {
Jeff Brownac386072011-07-20 15:19:50 -07003719}
3720
3721
3722// --- InputDispatcher::DispatchEntry ---
3723
Jeff Brown072ec962012-02-07 14:46:57 -08003724volatile int32_t InputDispatcher::DispatchEntry::sNextSeqAtomic;
3725
Jeff Brownac386072011-07-20 15:19:50 -07003726InputDispatcher::DispatchEntry::DispatchEntry(EventEntry* eventEntry,
3727 int32_t targetFlags, float xOffset, float yOffset, float scaleFactor) :
Jeff Brown072ec962012-02-07 14:46:57 -08003728 seq(nextSeq()),
Jeff Brownac386072011-07-20 15:19:50 -07003729 eventEntry(eventEntry), targetFlags(targetFlags),
3730 xOffset(xOffset), yOffset(yOffset), scaleFactor(scaleFactor),
Jeff Brown3241b6b2012-02-03 15:08:02 -08003731 resolvedAction(0), resolvedFlags(0) {
Jeff Brownac386072011-07-20 15:19:50 -07003732 eventEntry->refCount += 1;
3733}
3734
3735InputDispatcher::DispatchEntry::~DispatchEntry() {
3736 eventEntry->release();
3737}
3738
Jeff Brown072ec962012-02-07 14:46:57 -08003739uint32_t InputDispatcher::DispatchEntry::nextSeq() {
3740 // Sequence number 0 is reserved and will never be returned.
3741 uint32_t seq;
3742 do {
3743 seq = android_atomic_inc(&sNextSeqAtomic);
3744 } while (!seq);
3745 return seq;
3746}
3747
Jeff Brownb88102f2010-09-08 11:49:43 -07003748
3749// --- InputDispatcher::InputState ---
3750
Jeff Brownb6997262010-10-08 22:31:17 -07003751InputDispatcher::InputState::InputState() {
Jeff Brownb88102f2010-09-08 11:49:43 -07003752}
3753
3754InputDispatcher::InputState::~InputState() {
3755}
3756
3757bool InputDispatcher::InputState::isNeutral() const {
3758 return mKeyMementos.isEmpty() && mMotionMementos.isEmpty();
3759}
3760
Jeff Brown81346812011-06-28 20:08:48 -07003761bool InputDispatcher::InputState::isHovering(int32_t deviceId, uint32_t source) const {
3762 for (size_t i = 0; i < mMotionMementos.size(); i++) {
3763 const MotionMemento& memento = mMotionMementos.itemAt(i);
3764 if (memento.deviceId == deviceId
3765 && memento.source == source
3766 && memento.hovering) {
3767 return true;
3768 }
3769 }
3770 return false;
3771}
Jeff Brownb88102f2010-09-08 11:49:43 -07003772
Jeff Brown81346812011-06-28 20:08:48 -07003773bool InputDispatcher::InputState::trackKey(const KeyEntry* entry,
3774 int32_t action, int32_t flags) {
3775 switch (action) {
3776 case AKEY_EVENT_ACTION_UP: {
3777 if (entry->flags & AKEY_EVENT_FLAG_FALLBACK) {
3778 for (size_t i = 0; i < mFallbackKeys.size(); ) {
3779 if (mFallbackKeys.valueAt(i) == entry->keyCode) {
3780 mFallbackKeys.removeItemsAt(i);
3781 } else {
3782 i += 1;
3783 }
3784 }
3785 }
3786 ssize_t index = findKeyMemento(entry);
3787 if (index >= 0) {
3788 mKeyMementos.removeAt(index);
3789 return true;
3790 }
Jeff Brown68b909d2011-12-07 16:36:01 -08003791 /* FIXME: We can't just drop the key up event because that prevents creating
3792 * popup windows that are automatically shown when a key is held and then
3793 * dismissed when the key is released. The problem is that the popup will
3794 * not have received the original key down, so the key up will be considered
3795 * to be inconsistent with its observed state. We could perhaps handle this
3796 * by synthesizing a key down but that will cause other problems.
3797 *
3798 * So for now, allow inconsistent key up events to be dispatched.
3799 *
Jeff Brown81346812011-06-28 20:08:48 -07003800#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00003801 ALOGD("Dropping inconsistent key up event: deviceId=%d, source=%08x, "
Jeff Brown81346812011-06-28 20:08:48 -07003802 "keyCode=%d, scanCode=%d",
3803 entry->deviceId, entry->source, entry->keyCode, entry->scanCode);
3804#endif
3805 return false;
Jeff Brown68b909d2011-12-07 16:36:01 -08003806 */
3807 return true;
Jeff Brown81346812011-06-28 20:08:48 -07003808 }
3809
3810 case AKEY_EVENT_ACTION_DOWN: {
3811 ssize_t index = findKeyMemento(entry);
3812 if (index >= 0) {
3813 mKeyMementos.removeAt(index);
3814 }
3815 addKeyMemento(entry, flags);
3816 return true;
3817 }
3818
3819 default:
3820 return true;
Jeff Brownb88102f2010-09-08 11:49:43 -07003821 }
3822}
3823
Jeff Brown81346812011-06-28 20:08:48 -07003824bool InputDispatcher::InputState::trackMotion(const MotionEntry* entry,
3825 int32_t action, int32_t flags) {
3826 int32_t actionMasked = action & AMOTION_EVENT_ACTION_MASK;
3827 switch (actionMasked) {
3828 case AMOTION_EVENT_ACTION_UP:
3829 case AMOTION_EVENT_ACTION_CANCEL: {
3830 ssize_t index = findMotionMemento(entry, false /*hovering*/);
3831 if (index >= 0) {
3832 mMotionMementos.removeAt(index);
3833 return true;
Jeff Brownda3d5a92011-03-29 15:11:34 -07003834 }
Jeff Brown81346812011-06-28 20:08:48 -07003835#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00003836 ALOGD("Dropping inconsistent motion up or cancel event: deviceId=%d, source=%08x, "
Jeff Brown81346812011-06-28 20:08:48 -07003837 "actionMasked=%d",
3838 entry->deviceId, entry->source, actionMasked);
3839#endif
3840 return false;
Jeff Brownda3d5a92011-03-29 15:11:34 -07003841 }
3842
Jeff Brown81346812011-06-28 20:08:48 -07003843 case AMOTION_EVENT_ACTION_DOWN: {
3844 ssize_t index = findMotionMemento(entry, false /*hovering*/);
3845 if (index >= 0) {
3846 mMotionMementos.removeAt(index);
3847 }
3848 addMotionMemento(entry, flags, false /*hovering*/);
3849 return true;
3850 }
3851
3852 case AMOTION_EVENT_ACTION_POINTER_UP:
3853 case AMOTION_EVENT_ACTION_POINTER_DOWN:
3854 case AMOTION_EVENT_ACTION_MOVE: {
3855 ssize_t index = findMotionMemento(entry, false /*hovering*/);
3856 if (index >= 0) {
3857 MotionMemento& memento = mMotionMementos.editItemAt(index);
3858 memento.setPointers(entry);
3859 return true;
3860 }
Jeff Brown2e45fb62011-06-29 21:19:05 -07003861 if (actionMasked == AMOTION_EVENT_ACTION_MOVE
3862 && (entry->source & (AINPUT_SOURCE_CLASS_JOYSTICK
3863 | AINPUT_SOURCE_CLASS_NAVIGATION))) {
3864 // Joysticks and trackballs can send MOVE events without corresponding DOWN or UP.
3865 return true;
3866 }
Jeff Brown81346812011-06-28 20:08:48 -07003867#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00003868 ALOGD("Dropping inconsistent motion pointer up/down or move event: "
Jeff Brown81346812011-06-28 20:08:48 -07003869 "deviceId=%d, source=%08x, actionMasked=%d",
3870 entry->deviceId, entry->source, actionMasked);
3871#endif
3872 return false;
3873 }
3874
3875 case AMOTION_EVENT_ACTION_HOVER_EXIT: {
3876 ssize_t index = findMotionMemento(entry, true /*hovering*/);
3877 if (index >= 0) {
3878 mMotionMementos.removeAt(index);
3879 return true;
3880 }
3881#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00003882 ALOGD("Dropping inconsistent motion hover exit event: deviceId=%d, source=%08x",
Jeff Brown81346812011-06-28 20:08:48 -07003883 entry->deviceId, entry->source);
3884#endif
3885 return false;
3886 }
3887
3888 case AMOTION_EVENT_ACTION_HOVER_ENTER:
3889 case AMOTION_EVENT_ACTION_HOVER_MOVE: {
3890 ssize_t index = findMotionMemento(entry, true /*hovering*/);
3891 if (index >= 0) {
3892 mMotionMementos.removeAt(index);
3893 }
3894 addMotionMemento(entry, flags, true /*hovering*/);
3895 return true;
3896 }
3897
3898 default:
3899 return true;
3900 }
3901}
3902
3903ssize_t InputDispatcher::InputState::findKeyMemento(const KeyEntry* entry) const {
Jeff Brownb88102f2010-09-08 11:49:43 -07003904 for (size_t i = 0; i < mKeyMementos.size(); i++) {
Jeff Brown81346812011-06-28 20:08:48 -07003905 const KeyMemento& memento = mKeyMementos.itemAt(i);
Jeff Brownb88102f2010-09-08 11:49:43 -07003906 if (memento.deviceId == entry->deviceId
3907 && memento.source == entry->source
3908 && memento.keyCode == entry->keyCode
3909 && memento.scanCode == entry->scanCode) {
Jeff Brown81346812011-06-28 20:08:48 -07003910 return i;
Jeff Brownb88102f2010-09-08 11:49:43 -07003911 }
3912 }
Jeff Brown81346812011-06-28 20:08:48 -07003913 return -1;
Jeff Brownb88102f2010-09-08 11:49:43 -07003914}
3915
Jeff Brown81346812011-06-28 20:08:48 -07003916ssize_t InputDispatcher::InputState::findMotionMemento(const MotionEntry* entry,
3917 bool hovering) const {
Jeff Brownb88102f2010-09-08 11:49:43 -07003918 for (size_t i = 0; i < mMotionMementos.size(); i++) {
Jeff Brown81346812011-06-28 20:08:48 -07003919 const MotionMemento& memento = mMotionMementos.itemAt(i);
Jeff Brownb88102f2010-09-08 11:49:43 -07003920 if (memento.deviceId == entry->deviceId
Jeff Brown81346812011-06-28 20:08:48 -07003921 && memento.source == entry->source
3922 && memento.hovering == hovering) {
3923 return i;
Jeff Brownb88102f2010-09-08 11:49:43 -07003924 }
3925 }
Jeff Brown81346812011-06-28 20:08:48 -07003926 return -1;
3927}
Jeff Brownb88102f2010-09-08 11:49:43 -07003928
Jeff Brown81346812011-06-28 20:08:48 -07003929void InputDispatcher::InputState::addKeyMemento(const KeyEntry* entry, int32_t flags) {
3930 mKeyMementos.push();
3931 KeyMemento& memento = mKeyMementos.editTop();
3932 memento.deviceId = entry->deviceId;
3933 memento.source = entry->source;
3934 memento.keyCode = entry->keyCode;
3935 memento.scanCode = entry->scanCode;
Jeff Brownfd23e3e2012-05-09 13:34:28 -07003936 memento.metaState = entry->metaState;
Jeff Brown81346812011-06-28 20:08:48 -07003937 memento.flags = flags;
3938 memento.downTime = entry->downTime;
Jeff Brownfd23e3e2012-05-09 13:34:28 -07003939 memento.policyFlags = entry->policyFlags;
Jeff Brown81346812011-06-28 20:08:48 -07003940}
3941
3942void InputDispatcher::InputState::addMotionMemento(const MotionEntry* entry,
3943 int32_t flags, bool hovering) {
3944 mMotionMementos.push();
3945 MotionMemento& memento = mMotionMementos.editTop();
3946 memento.deviceId = entry->deviceId;
3947 memento.source = entry->source;
3948 memento.flags = flags;
3949 memento.xPrecision = entry->xPrecision;
3950 memento.yPrecision = entry->yPrecision;
3951 memento.downTime = entry->downTime;
3952 memento.setPointers(entry);
3953 memento.hovering = hovering;
Jeff Brownfd23e3e2012-05-09 13:34:28 -07003954 memento.policyFlags = entry->policyFlags;
Jeff Brownb88102f2010-09-08 11:49:43 -07003955}
3956
3957void InputDispatcher::InputState::MotionMemento::setPointers(const MotionEntry* entry) {
3958 pointerCount = entry->pointerCount;
3959 for (uint32_t i = 0; i < entry->pointerCount; i++) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003960 pointerProperties[i].copyFrom(entry->pointerProperties[i]);
Jeff Brown3241b6b2012-02-03 15:08:02 -08003961 pointerCoords[i].copyFrom(entry->pointerCoords[i]);
Jeff Brownb88102f2010-09-08 11:49:43 -07003962 }
3963}
3964
Jeff Brownb6997262010-10-08 22:31:17 -07003965void InputDispatcher::InputState::synthesizeCancelationEvents(nsecs_t currentTime,
Jeff Brownac386072011-07-20 15:19:50 -07003966 Vector<EventEntry*>& outEvents, const CancelationOptions& options) {
Jeff Brown81346812011-06-28 20:08:48 -07003967 for (size_t i = 0; i < mKeyMementos.size(); i++) {
Jeff Brownb88102f2010-09-08 11:49:43 -07003968 const KeyMemento& memento = mKeyMementos.itemAt(i);
Jeff Brown49ed71d2010-12-06 17:13:33 -08003969 if (shouldCancelKey(memento, options)) {
Jeff Brownac386072011-07-20 15:19:50 -07003970 outEvents.push(new KeyEntry(currentTime,
Jeff Brownfd23e3e2012-05-09 13:34:28 -07003971 memento.deviceId, memento.source, memento.policyFlags,
Jeff Brown49ed71d2010-12-06 17:13:33 -08003972 AKEY_EVENT_ACTION_UP, memento.flags | AKEY_EVENT_FLAG_CANCELED,
Jeff Brownfd23e3e2012-05-09 13:34:28 -07003973 memento.keyCode, memento.scanCode, memento.metaState, 0, memento.downTime));
Jeff Brownb6997262010-10-08 22:31:17 -07003974 }
Jeff Brownb88102f2010-09-08 11:49:43 -07003975 }
3976
Jeff Brown81346812011-06-28 20:08:48 -07003977 for (size_t i = 0; i < mMotionMementos.size(); i++) {
Jeff Brownb88102f2010-09-08 11:49:43 -07003978 const MotionMemento& memento = mMotionMementos.itemAt(i);
Jeff Brown49ed71d2010-12-06 17:13:33 -08003979 if (shouldCancelMotion(memento, options)) {
Jeff Brownac386072011-07-20 15:19:50 -07003980 outEvents.push(new MotionEntry(currentTime,
Jeff Brownfd23e3e2012-05-09 13:34:28 -07003981 memento.deviceId, memento.source, memento.policyFlags,
Jeff Browna032cc02011-03-07 16:56:21 -08003982 memento.hovering
3983 ? AMOTION_EVENT_ACTION_HOVER_EXIT
3984 : AMOTION_EVENT_ACTION_CANCEL,
Jeff Brown81346812011-06-28 20:08:48 -07003985 memento.flags, 0, 0, 0,
Jeff Brownb6997262010-10-08 22:31:17 -07003986 memento.xPrecision, memento.yPrecision, memento.downTime,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003987 memento.pointerCount, memento.pointerProperties, memento.pointerCoords));
Jeff Brownb6997262010-10-08 22:31:17 -07003988 }
Jeff Brownb88102f2010-09-08 11:49:43 -07003989 }
3990}
3991
3992void InputDispatcher::InputState::clear() {
3993 mKeyMementos.clear();
3994 mMotionMementos.clear();
Jeff Brownda3d5a92011-03-29 15:11:34 -07003995 mFallbackKeys.clear();
Jeff Brownb6997262010-10-08 22:31:17 -07003996}
3997
Jeff Brown9c9f1a32010-10-11 18:32:20 -07003998void InputDispatcher::InputState::copyPointerStateTo(InputState& other) const {
3999 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4000 const MotionMemento& memento = mMotionMementos.itemAt(i);
4001 if (memento.source & AINPUT_SOURCE_CLASS_POINTER) {
4002 for (size_t j = 0; j < other.mMotionMementos.size(); ) {
4003 const MotionMemento& otherMemento = other.mMotionMementos.itemAt(j);
4004 if (memento.deviceId == otherMemento.deviceId
4005 && memento.source == otherMemento.source) {
4006 other.mMotionMementos.removeAt(j);
4007 } else {
4008 j += 1;
4009 }
4010 }
4011 other.mMotionMementos.push(memento);
4012 }
4013 }
4014}
4015
Jeff Brownda3d5a92011-03-29 15:11:34 -07004016int32_t InputDispatcher::InputState::getFallbackKey(int32_t originalKeyCode) {
4017 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
4018 return index >= 0 ? mFallbackKeys.valueAt(index) : -1;
4019}
4020
4021void InputDispatcher::InputState::setFallbackKey(int32_t originalKeyCode,
4022 int32_t fallbackKeyCode) {
4023 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
4024 if (index >= 0) {
4025 mFallbackKeys.replaceValueAt(index, fallbackKeyCode);
4026 } else {
4027 mFallbackKeys.add(originalKeyCode, fallbackKeyCode);
4028 }
4029}
4030
4031void InputDispatcher::InputState::removeFallbackKey(int32_t originalKeyCode) {
4032 mFallbackKeys.removeItem(originalKeyCode);
4033}
4034
Jeff Brown49ed71d2010-12-06 17:13:33 -08004035bool InputDispatcher::InputState::shouldCancelKey(const KeyMemento& memento,
Jeff Brownda3d5a92011-03-29 15:11:34 -07004036 const CancelationOptions& options) {
4037 if (options.keyCode != -1 && memento.keyCode != options.keyCode) {
4038 return false;
4039 }
4040
Jeff Brown65fd2512011-08-18 11:20:58 -07004041 if (options.deviceId != -1 && memento.deviceId != options.deviceId) {
4042 return false;
4043 }
4044
Jeff Brownda3d5a92011-03-29 15:11:34 -07004045 switch (options.mode) {
4046 case CancelationOptions::CANCEL_ALL_EVENTS:
4047 case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
Jeff Brownb6997262010-10-08 22:31:17 -07004048 return true;
Jeff Brownda3d5a92011-03-29 15:11:34 -07004049 case CancelationOptions::CANCEL_FALLBACK_EVENTS:
Jeff Brown49ed71d2010-12-06 17:13:33 -08004050 return memento.flags & AKEY_EVENT_FLAG_FALLBACK;
4051 default:
4052 return false;
4053 }
4054}
4055
4056bool InputDispatcher::InputState::shouldCancelMotion(const MotionMemento& memento,
Jeff Brownda3d5a92011-03-29 15:11:34 -07004057 const CancelationOptions& options) {
Jeff Brown65fd2512011-08-18 11:20:58 -07004058 if (options.deviceId != -1 && memento.deviceId != options.deviceId) {
4059 return false;
4060 }
4061
Jeff Brownda3d5a92011-03-29 15:11:34 -07004062 switch (options.mode) {
4063 case CancelationOptions::CANCEL_ALL_EVENTS:
Jeff Brown49ed71d2010-12-06 17:13:33 -08004064 return true;
Jeff Brownda3d5a92011-03-29 15:11:34 -07004065 case CancelationOptions::CANCEL_POINTER_EVENTS:
Jeff Brown49ed71d2010-12-06 17:13:33 -08004066 return memento.source & AINPUT_SOURCE_CLASS_POINTER;
Jeff Brownda3d5a92011-03-29 15:11:34 -07004067 case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
Jeff Brown49ed71d2010-12-06 17:13:33 -08004068 return !(memento.source & AINPUT_SOURCE_CLASS_POINTER);
4069 default:
4070 return false;
Jeff Brownb6997262010-10-08 22:31:17 -07004071 }
Jeff Brownb88102f2010-09-08 11:49:43 -07004072}
4073
4074
Jeff Brown46b9ac02010-04-22 18:58:52 -07004075// --- InputDispatcher::Connection ---
4076
Jeff Brown928e0542011-01-10 11:17:36 -08004077InputDispatcher::Connection::Connection(const sp<InputChannel>& inputChannel,
Jeff Browncc4f7db2011-08-30 20:34:48 -07004078 const sp<InputWindowHandle>& inputWindowHandle, bool monitor) :
Jeff Brown928e0542011-01-10 11:17:36 -08004079 status(STATUS_NORMAL), inputChannel(inputChannel), inputWindowHandle(inputWindowHandle),
Jeff Browncc4f7db2011-08-30 20:34:48 -07004080 monitor(monitor),
Jeff Brownd1c48a02012-02-06 19:12:47 -08004081 inputPublisher(inputChannel), inputPublisherBlocked(false) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07004082}
4083
4084InputDispatcher::Connection::~Connection() {
4085}
4086
Jeff Brown481c1572012-03-09 14:41:15 -08004087const char* InputDispatcher::Connection::getWindowName() const {
4088 if (inputWindowHandle != NULL) {
4089 return inputWindowHandle->getName().string();
4090 }
4091 if (monitor) {
4092 return "monitor";
4093 }
4094 return "?";
4095}
4096
Jeff Brown9c3cda02010-06-15 01:31:58 -07004097const char* InputDispatcher::Connection::getStatusLabel() const {
4098 switch (status) {
4099 case STATUS_NORMAL:
4100 return "NORMAL";
4101
4102 case STATUS_BROKEN:
4103 return "BROKEN";
4104
Jeff Brown9c3cda02010-06-15 01:31:58 -07004105 case STATUS_ZOMBIE:
4106 return "ZOMBIE";
4107
4108 default:
4109 return "UNKNOWN";
4110 }
4111}
4112
Jeff Brown072ec962012-02-07 14:46:57 -08004113InputDispatcher::DispatchEntry* InputDispatcher::Connection::findWaitQueueEntry(uint32_t seq) {
4114 for (DispatchEntry* entry = waitQueue.head; entry != NULL; entry = entry->next) {
4115 if (entry->seq == seq) {
4116 return entry;
4117 }
4118 }
4119 return NULL;
4120}
4121
Jeff Brownb88102f2010-09-08 11:49:43 -07004122
Jeff Brown9c3cda02010-06-15 01:31:58 -07004123// --- InputDispatcher::CommandEntry ---
4124
Jeff Brownac386072011-07-20 15:19:50 -07004125InputDispatcher::CommandEntry::CommandEntry(Command command) :
Jeff Brown072ec962012-02-07 14:46:57 -08004126 command(command), eventTime(0), keyEntry(NULL), userActivityEventType(0),
4127 seq(0), handled(false) {
Jeff Brown9c3cda02010-06-15 01:31:58 -07004128}
4129
4130InputDispatcher::CommandEntry::~CommandEntry() {
4131}
4132
Jeff Brown46b9ac02010-04-22 18:58:52 -07004133
Jeff Brown01ce2e92010-09-26 22:20:12 -07004134// --- InputDispatcher::TouchState ---
4135
4136InputDispatcher::TouchState::TouchState() :
Jeff Brown58a2da82011-01-25 16:02:22 -08004137 down(false), split(false), deviceId(-1), source(0) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07004138}
4139
4140InputDispatcher::TouchState::~TouchState() {
4141}
4142
4143void InputDispatcher::TouchState::reset() {
4144 down = false;
4145 split = false;
Jeff Brown95712852011-01-04 19:41:59 -08004146 deviceId = -1;
Jeff Brown58a2da82011-01-25 16:02:22 -08004147 source = 0;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004148 windows.clear();
4149}
4150
4151void InputDispatcher::TouchState::copyFrom(const TouchState& other) {
4152 down = other.down;
4153 split = other.split;
Jeff Brown95712852011-01-04 19:41:59 -08004154 deviceId = other.deviceId;
Jeff Brown58a2da82011-01-25 16:02:22 -08004155 source = other.source;
Jeff Brown9302c872011-07-13 22:51:29 -07004156 windows = other.windows;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004157}
4158
Jeff Brown9302c872011-07-13 22:51:29 -07004159void InputDispatcher::TouchState::addOrUpdateWindow(const sp<InputWindowHandle>& windowHandle,
Jeff Brown01ce2e92010-09-26 22:20:12 -07004160 int32_t targetFlags, BitSet32 pointerIds) {
4161 if (targetFlags & InputTarget::FLAG_SPLIT) {
4162 split = true;
4163 }
4164
4165 for (size_t i = 0; i < windows.size(); i++) {
4166 TouchedWindow& touchedWindow = windows.editItemAt(i);
Jeff Brown9302c872011-07-13 22:51:29 -07004167 if (touchedWindow.windowHandle == windowHandle) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07004168 touchedWindow.targetFlags |= targetFlags;
Jeff Brown98db5fa2011-06-08 15:37:10 -07004169 if (targetFlags & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
4170 touchedWindow.targetFlags &= ~InputTarget::FLAG_DISPATCH_AS_IS;
4171 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07004172 touchedWindow.pointerIds.value |= pointerIds.value;
4173 return;
4174 }
4175 }
4176
4177 windows.push();
4178
4179 TouchedWindow& touchedWindow = windows.editTop();
Jeff Brown9302c872011-07-13 22:51:29 -07004180 touchedWindow.windowHandle = windowHandle;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004181 touchedWindow.targetFlags = targetFlags;
4182 touchedWindow.pointerIds = pointerIds;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004183}
4184
Jeff Brownf44e3942012-04-20 11:33:27 -07004185void InputDispatcher::TouchState::removeWindow(const sp<InputWindowHandle>& windowHandle) {
4186 for (size_t i = 0; i < windows.size(); i++) {
4187 if (windows.itemAt(i).windowHandle == windowHandle) {
4188 windows.removeAt(i);
4189 return;
4190 }
4191 }
4192}
4193
Jeff Browna032cc02011-03-07 16:56:21 -08004194void InputDispatcher::TouchState::filterNonAsIsTouchWindows() {
Jeff Brown01ce2e92010-09-26 22:20:12 -07004195 for (size_t i = 0 ; i < windows.size(); ) {
Jeff Browna032cc02011-03-07 16:56:21 -08004196 TouchedWindow& window = windows.editItemAt(i);
Jeff Brown98db5fa2011-06-08 15:37:10 -07004197 if (window.targetFlags & (InputTarget::FLAG_DISPATCH_AS_IS
4198 | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER)) {
Jeff Browna032cc02011-03-07 16:56:21 -08004199 window.targetFlags &= ~InputTarget::FLAG_DISPATCH_MASK;
4200 window.targetFlags |= InputTarget::FLAG_DISPATCH_AS_IS;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004201 i += 1;
Jeff Browna032cc02011-03-07 16:56:21 -08004202 } else {
4203 windows.removeAt(i);
Jeff Brown01ce2e92010-09-26 22:20:12 -07004204 }
4205 }
4206}
4207
Jeff Brown9302c872011-07-13 22:51:29 -07004208sp<InputWindowHandle> InputDispatcher::TouchState::getFirstForegroundWindowHandle() const {
Jeff Brown01ce2e92010-09-26 22:20:12 -07004209 for (size_t i = 0; i < windows.size(); i++) {
Jeff Brown98db5fa2011-06-08 15:37:10 -07004210 const TouchedWindow& window = windows.itemAt(i);
4211 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
Jeff Brown9302c872011-07-13 22:51:29 -07004212 return window.windowHandle;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004213 }
4214 }
4215 return NULL;
4216}
4217
Jeff Brown98db5fa2011-06-08 15:37:10 -07004218bool InputDispatcher::TouchState::isSlippery() const {
4219 // Must have exactly one foreground window.
4220 bool haveSlipperyForegroundWindow = false;
4221 for (size_t i = 0; i < windows.size(); i++) {
4222 const TouchedWindow& window = windows.itemAt(i);
4223 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
Jeff Browncc4f7db2011-08-30 20:34:48 -07004224 if (haveSlipperyForegroundWindow
4225 || !(window.windowHandle->getInfo()->layoutParamsFlags
4226 & InputWindowInfo::FLAG_SLIPPERY)) {
Jeff Brown98db5fa2011-06-08 15:37:10 -07004227 return false;
4228 }
4229 haveSlipperyForegroundWindow = true;
4230 }
4231 }
4232 return haveSlipperyForegroundWindow;
4233}
4234
Jeff Brown01ce2e92010-09-26 22:20:12 -07004235
Jeff Brown46b9ac02010-04-22 18:58:52 -07004236// --- InputDispatcherThread ---
4237
4238InputDispatcherThread::InputDispatcherThread(const sp<InputDispatcherInterface>& dispatcher) :
4239 Thread(/*canCallJava*/ true), mDispatcher(dispatcher) {
4240}
4241
4242InputDispatcherThread::~InputDispatcherThread() {
4243}
4244
4245bool InputDispatcherThread::threadLoop() {
4246 mDispatcher->dispatchOnce();
4247 return true;
4248}
4249
4250} // namespace android