blob: da3548f07e286413322e4db4324b8b4221b0a483 [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 Brownf2f487182010-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 Brown0029c662011-03-30 02:25:18 -0700188 mDispatchEnabled(true), 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
Jeff Brown01ce2e92010-09-26 22:20:12 -0700973 // Release the touch targets.
974 mTouchState.reset();
Jeff Brown2a95c2a2010-09-16 12:31:46 -0700975
Jeff Brown519e0242010-09-15 15:18:56 -0700976 // Input state will not be realistic. Mark it out of sync.
Jeff Browndc3e0052010-09-16 11:02:16 -0700977 if (inputChannel.get()) {
978 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
979 if (connectionIndex >= 0) {
Jeff Browncbee6d62012-02-03 20:11:27 -0800980 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
Jeff Brown00045a72010-12-09 18:10:30 -0800981 if (connection->status == Connection::STATUS_NORMAL) {
Jeff Brownda3d5a92011-03-29 15:11:34 -0700982 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
Jeff Brown00045a72010-12-09 18:10:30 -0800983 "application not responding");
Jeff Brownda3d5a92011-03-29 15:11:34 -0700984 synthesizeCancelationEventsForConnectionLocked(connection, options);
Jeff Brown00045a72010-12-09 18:10:30 -0800985 }
Jeff Browndc3e0052010-09-16 11:02:16 -0700986 }
Jeff Brown519e0242010-09-15 15:18:56 -0700987 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700988 }
989}
990
Jeff Brown519e0242010-09-15 15:18:56 -0700991nsecs_t InputDispatcher::getTimeSpentWaitingForApplicationLocked(
Jeff Brownb88102f2010-09-08 11:49:43 -0700992 nsecs_t currentTime) {
993 if (mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
994 return currentTime - mInputTargetWaitStartTime;
995 }
996 return 0;
997}
998
999void InputDispatcher::resetANRTimeoutsLocked() {
1000#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001001 ALOGD("Resetting ANR timeouts.");
Jeff Brownb88102f2010-09-08 11:49:43 -07001002#endif
1003
Jeff Brownb88102f2010-09-08 11:49:43 -07001004 // Reset input target wait timeout.
1005 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_NONE;
Jeff Brown5ea29ab2011-07-27 11:50:51 -07001006 mInputTargetWaitApplicationHandle.clear();
Jeff Brownb88102f2010-09-08 11:49:43 -07001007}
1008
Jeff Brown01ce2e92010-09-26 22:20:12 -07001009int32_t InputDispatcher::findFocusedWindowTargetsLocked(nsecs_t currentTime,
Jeff Browne9bb9be2012-02-06 15:47:55 -08001010 const EventEntry* entry, Vector<InputTarget>& inputTargets, nsecs_t* nextWakeupTime) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001011 int32_t injectionResult;
1012
1013 // If there is no currently focused window and no focused application
1014 // then drop the event.
Jeff Brown9302c872011-07-13 22:51:29 -07001015 if (mFocusedWindowHandle == NULL) {
1016 if (mFocusedApplicationHandle != NULL) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001017#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001018 ALOGD("Waiting because there is no focused window but there is a "
Jeff Brown519e0242010-09-15 15:18:56 -07001019 "focused application that may eventually add a window: %s.",
Jeff Brown9302c872011-07-13 22:51:29 -07001020 getApplicationWindowLabelLocked(mFocusedApplicationHandle, NULL).string());
Jeff Brownb88102f2010-09-08 11:49:43 -07001021#endif
1022 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brown9302c872011-07-13 22:51:29 -07001023 mFocusedApplicationHandle, NULL, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -07001024 goto Unresponsive;
1025 }
1026
Steve Block6215d3f2012-01-04 20:05:49 +00001027 ALOGI("Dropping event because there is no focused window or focused application.");
Jeff Brownb88102f2010-09-08 11:49:43 -07001028 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1029 goto Failed;
1030 }
1031
1032 // Check permissions.
Jeff Brown9302c872011-07-13 22:51:29 -07001033 if (! checkInjectionPermission(mFocusedWindowHandle, entry->injectionState)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001034 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1035 goto Failed;
1036 }
1037
1038 // If the currently focused window is paused then keep waiting.
Jeff Browncc4f7db2011-08-30 20:34:48 -07001039 if (mFocusedWindowHandle->getInfo()->paused) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001040#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001041 ALOGD("Waiting because focused window is paused.");
Jeff Brownb88102f2010-09-08 11:49:43 -07001042#endif
1043 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brown9302c872011-07-13 22:51:29 -07001044 mFocusedApplicationHandle, mFocusedWindowHandle, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -07001045 goto Unresponsive;
1046 }
1047
Jeff Brown519e0242010-09-15 15:18:56 -07001048 // If the currently focused window is still working on previous events then keep waiting.
Jeff Brown0952c302012-02-13 13:48:59 -08001049 if (!isWindowReadyForMoreInputLocked(currentTime, mFocusedWindowHandle, entry)) {
Jeff Brown519e0242010-09-15 15:18:56 -07001050#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001051 ALOGD("Waiting because focused window still processing previous input.");
Jeff Brown519e0242010-09-15 15:18:56 -07001052#endif
1053 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brown9302c872011-07-13 22:51:29 -07001054 mFocusedApplicationHandle, mFocusedWindowHandle, nextWakeupTime);
Jeff Brown519e0242010-09-15 15:18:56 -07001055 goto Unresponsive;
1056 }
1057
Jeff Brownb88102f2010-09-08 11:49:43 -07001058 // Success! Output targets.
1059 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
Jeff Brown9302c872011-07-13 22:51:29 -07001060 addWindowTargetLocked(mFocusedWindowHandle,
Jeff Browne9bb9be2012-02-06 15:47:55 -08001061 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS, BitSet32(0),
1062 inputTargets);
Jeff Brownb88102f2010-09-08 11:49:43 -07001063
1064 // Done.
1065Failed:
1066Unresponsive:
Jeff Brown519e0242010-09-15 15:18:56 -07001067 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
1068 updateDispatchStatisticsLocked(currentTime, entry,
1069 injectionResult, timeSpentWaitingForApplication);
Jeff Brownb88102f2010-09-08 11:49:43 -07001070#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001071 ALOGD("findFocusedWindow finished: injectionResult=%d, "
Jeff Brown519e0242010-09-15 15:18:56 -07001072 "timeSpendWaitingForApplication=%0.1fms",
1073 injectionResult, timeSpentWaitingForApplication / 1000000.0);
Jeff Brownb88102f2010-09-08 11:49:43 -07001074#endif
1075 return injectionResult;
1076}
1077
Jeff Brown01ce2e92010-09-26 22:20:12 -07001078int32_t InputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime,
Jeff Browne9bb9be2012-02-06 15:47:55 -08001079 const MotionEntry* entry, Vector<InputTarget>& inputTargets, nsecs_t* nextWakeupTime,
1080 bool* outConflictingPointerActions) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001081 enum InjectionPermission {
1082 INJECTION_PERMISSION_UNKNOWN,
1083 INJECTION_PERMISSION_GRANTED,
1084 INJECTION_PERMISSION_DENIED
1085 };
1086
Jeff Brownb88102f2010-09-08 11:49:43 -07001087 nsecs_t startTime = now();
1088
1089 // For security reasons, we defer updating the touch state until we are sure that
1090 // event injection will be allowed.
1091 //
1092 // FIXME In the original code, screenWasOff could never be set to true.
1093 // The reason is that the POLICY_FLAG_WOKE_HERE
1094 // and POLICY_FLAG_BRIGHT_HERE flags were set only when preprocessing raw
1095 // EV_KEY, EV_REL and EV_ABS events. As it happens, the touch event was
1096 // actually enqueued using the policyFlags that appeared in the final EV_SYN
1097 // events upon which no preprocessing took place. So policyFlags was always 0.
1098 // In the new native input dispatcher we're a bit more careful about event
1099 // preprocessing so the touches we receive can actually have non-zero policyFlags.
1100 // Unfortunately we obtain undesirable behavior.
1101 //
1102 // Here's what happens:
1103 //
1104 // When the device dims in anticipation of going to sleep, touches
1105 // in windows which have FLAG_TOUCHABLE_WHEN_WAKING cause
1106 // the device to brighten and reset the user activity timer.
1107 // Touches on other windows (such as the launcher window)
1108 // are dropped. Then after a moment, the device goes to sleep. Oops.
1109 //
1110 // Also notice how screenWasOff was being initialized using POLICY_FLAG_BRIGHT_HERE
1111 // instead of POLICY_FLAG_WOKE_HERE...
1112 //
1113 bool screenWasOff = false; // original policy: policyFlags & POLICY_FLAG_BRIGHT_HERE;
1114
1115 int32_t action = entry->action;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001116 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Jeff Brownb88102f2010-09-08 11:49:43 -07001117
1118 // Update the touch state as needed based on the properties of the touch event.
Jeff Brown01ce2e92010-09-26 22:20:12 -07001119 int32_t injectionResult = INPUT_EVENT_INJECTION_PENDING;
1120 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
Jeff Brown9302c872011-07-13 22:51:29 -07001121 sp<InputWindowHandle> newHoverWindowHandle;
Jeff Browncc0c1592011-02-19 05:07:28 -08001122
1123 bool isSplit = mTouchState.split;
Jeff Brown2717eff2011-06-30 23:53:07 -07001124 bool switchedDevice = mTouchState.deviceId >= 0
1125 && (mTouchState.deviceId != entry->deviceId
1126 || mTouchState.source != entry->source);
Jeff Browna032cc02011-03-07 16:56:21 -08001127 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE
1128 || maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER
1129 || maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1130 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN
1131 || maskedAction == AMOTION_EVENT_ACTION_SCROLL
1132 || isHoverAction);
Jeff Brown81346812011-06-28 20:08:48 -07001133 bool wrongDevice = false;
Jeff Browna032cc02011-03-07 16:56:21 -08001134 if (newGesture) {
Jeff Browncc0c1592011-02-19 05:07:28 -08001135 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Jeff Brown81346812011-06-28 20:08:48 -07001136 if (switchedDevice && mTouchState.down && !down) {
1137#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001138 ALOGD("Dropping event because a pointer for a different device is already down.");
Jeff Brown81346812011-06-28 20:08:48 -07001139#endif
Jeff Browncc0c1592011-02-19 05:07:28 -08001140 mTempTouchState.copyFrom(mTouchState);
Jeff Brown81346812011-06-28 20:08:48 -07001141 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1142 switchedDevice = false;
1143 wrongDevice = true;
1144 goto Failed;
Jeff Browncc0c1592011-02-19 05:07:28 -08001145 }
Jeff Brown81346812011-06-28 20:08:48 -07001146 mTempTouchState.reset();
1147 mTempTouchState.down = down;
1148 mTempTouchState.deviceId = entry->deviceId;
1149 mTempTouchState.source = entry->source;
1150 isSplit = false;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001151 } else {
1152 mTempTouchState.copyFrom(mTouchState);
Jeff Browncc0c1592011-02-19 05:07:28 -08001153 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001154
Jeff Browna032cc02011-03-07 16:56:21 -08001155 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
Jeff Brown33bbfd22011-02-24 20:55:35 -08001156 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
Jeff Brownb88102f2010-09-08 11:49:43 -07001157
Jeff Brown01ce2e92010-09-26 22:20:12 -07001158 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Jeff Brown3241b6b2012-02-03 15:08:02 -08001159 int32_t x = int32_t(entry->pointerCoords[pointerIndex].
Jeff Brownebbd5d12011-02-17 13:01:34 -08001160 getAxisValue(AMOTION_EVENT_AXIS_X));
Jeff Brown3241b6b2012-02-03 15:08:02 -08001161 int32_t y = int32_t(entry->pointerCoords[pointerIndex].
Jeff Brownebbd5d12011-02-17 13:01:34 -08001162 getAxisValue(AMOTION_EVENT_AXIS_Y));
Jeff Brown9302c872011-07-13 22:51:29 -07001163 sp<InputWindowHandle> newTouchedWindowHandle;
1164 sp<InputWindowHandle> topErrorWindowHandle;
Jeff Browna032cc02011-03-07 16:56:21 -08001165 bool isTouchModal = false;
Jeff Brownb88102f2010-09-08 11:49:43 -07001166
1167 // Traverse windows from front to back to find touched window and outside targets.
Jeff Brown9302c872011-07-13 22:51:29 -07001168 size_t numWindows = mWindowHandles.size();
Jeff Brownb88102f2010-09-08 11:49:43 -07001169 for (size_t i = 0; i < numWindows; i++) {
Jeff Brown9302c872011-07-13 22:51:29 -07001170 sp<InputWindowHandle> windowHandle = mWindowHandles.itemAt(i);
Jeff Browncc4f7db2011-08-30 20:34:48 -07001171 const InputWindowInfo* windowInfo = windowHandle->getInfo();
1172 int32_t flags = windowInfo->layoutParamsFlags;
Jeff Brownb88102f2010-09-08 11:49:43 -07001173
Jeff Browncc4f7db2011-08-30 20:34:48 -07001174 if (flags & InputWindowInfo::FLAG_SYSTEM_ERROR) {
Jeff Brown9302c872011-07-13 22:51:29 -07001175 if (topErrorWindowHandle == NULL) {
1176 topErrorWindowHandle = windowHandle;
Jeff Brownb88102f2010-09-08 11:49:43 -07001177 }
1178 }
1179
Jeff Browncc4f7db2011-08-30 20:34:48 -07001180 if (windowInfo->visible) {
1181 if (! (flags & InputWindowInfo::FLAG_NOT_TOUCHABLE)) {
1182 isTouchModal = (flags & (InputWindowInfo::FLAG_NOT_FOCUSABLE
1183 | InputWindowInfo::FLAG_NOT_TOUCH_MODAL)) == 0;
1184 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
Jeff Brown9302c872011-07-13 22:51:29 -07001185 if (! screenWasOff
Jeff Browncc4f7db2011-08-30 20:34:48 -07001186 || (flags & InputWindowInfo::FLAG_TOUCHABLE_WHEN_WAKING)) {
Jeff Brown9302c872011-07-13 22:51:29 -07001187 newTouchedWindowHandle = windowHandle;
Jeff Brownb88102f2010-09-08 11:49:43 -07001188 }
1189 break; // found touched window, exit window loop
1190 }
1191 }
1192
Jeff Brown01ce2e92010-09-26 22:20:12 -07001193 if (maskedAction == AMOTION_EVENT_ACTION_DOWN
Jeff Browncc4f7db2011-08-30 20:34:48 -07001194 && (flags & InputWindowInfo::FLAG_WATCH_OUTSIDE_TOUCH)) {
Jeff Browna032cc02011-03-07 16:56:21 -08001195 int32_t outsideTargetFlags = InputTarget::FLAG_DISPATCH_AS_OUTSIDE;
Jeff Brown9302c872011-07-13 22:51:29 -07001196 if (isWindowObscuredAtPointLocked(windowHandle, x, y)) {
Jeff Brown19dfc832010-10-05 12:26:23 -07001197 outsideTargetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1198 }
1199
Jeff Brown9302c872011-07-13 22:51:29 -07001200 mTempTouchState.addOrUpdateWindow(
1201 windowHandle, outsideTargetFlags, BitSet32(0));
Jeff Brownb88102f2010-09-08 11:49:43 -07001202 }
1203 }
1204 }
1205
1206 // If there is an error window but it is not taking focus (typically because
1207 // it is invisible) then wait for it. Any other focused window may in
1208 // fact be in ANR state.
Jeff Brown9302c872011-07-13 22:51:29 -07001209 if (topErrorWindowHandle != NULL && newTouchedWindowHandle != topErrorWindowHandle) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001210#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001211 ALOGD("Waiting because system error window is pending.");
Jeff Brownb88102f2010-09-08 11:49:43 -07001212#endif
1213 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
1214 NULL, NULL, nextWakeupTime);
1215 injectionPermission = INJECTION_PERMISSION_UNKNOWN;
1216 goto Unresponsive;
1217 }
1218
Jeff Brown01ce2e92010-09-26 22:20:12 -07001219 // Figure out whether splitting will be allowed for this window.
Jeff Browncc4f7db2011-08-30 20:34:48 -07001220 if (newTouchedWindowHandle != NULL
1221 && newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001222 // New window supports splitting.
1223 isSplit = true;
1224 } else if (isSplit) {
1225 // New window does not support splitting but we have already split events.
1226 // Assign the pointer to the first foreground window we find.
1227 // (May be NULL which is why we put this code block before the next check.)
Jeff Brown9302c872011-07-13 22:51:29 -07001228 newTouchedWindowHandle = mTempTouchState.getFirstForegroundWindowHandle();
Jeff Brown01ce2e92010-09-26 22:20:12 -07001229 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001230
Jeff Brownb88102f2010-09-08 11:49:43 -07001231 // If we did not find a touched window then fail.
Jeff Brown9302c872011-07-13 22:51:29 -07001232 if (newTouchedWindowHandle == NULL) {
1233 if (mFocusedApplicationHandle != NULL) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001234#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001235 ALOGD("Waiting because there is no touched window but there is a "
Jeff Brown519e0242010-09-15 15:18:56 -07001236 "focused application that may eventually add a new window: %s.",
Jeff Brown9302c872011-07-13 22:51:29 -07001237 getApplicationWindowLabelLocked(mFocusedApplicationHandle, NULL).string());
Jeff Brownb88102f2010-09-08 11:49:43 -07001238#endif
1239 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brown9302c872011-07-13 22:51:29 -07001240 mFocusedApplicationHandle, NULL, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -07001241 goto Unresponsive;
1242 }
1243
Steve Block6215d3f2012-01-04 20:05:49 +00001244 ALOGI("Dropping event because there is no touched window or focused application.");
Jeff Brownb88102f2010-09-08 11:49:43 -07001245 injectionResult = INPUT_EVENT_INJECTION_FAILED;
Jeff Brownb88102f2010-09-08 11:49:43 -07001246 goto Failed;
1247 }
1248
Jeff Brown19dfc832010-10-05 12:26:23 -07001249 // Set target flags.
Jeff Browna032cc02011-03-07 16:56:21 -08001250 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
Jeff Brown19dfc832010-10-05 12:26:23 -07001251 if (isSplit) {
1252 targetFlags |= InputTarget::FLAG_SPLIT;
1253 }
Jeff Brown9302c872011-07-13 22:51:29 -07001254 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
Jeff Brown19dfc832010-10-05 12:26:23 -07001255 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1256 }
1257
Jeff Browna032cc02011-03-07 16:56:21 -08001258 // Update hover state.
1259 if (isHoverAction) {
Jeff Brown9302c872011-07-13 22:51:29 -07001260 newHoverWindowHandle = newTouchedWindowHandle;
Jeff Browna032cc02011-03-07 16:56:21 -08001261 } else if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
Jeff Brown9302c872011-07-13 22:51:29 -07001262 newHoverWindowHandle = mLastHoverWindowHandle;
Jeff Browna032cc02011-03-07 16:56:21 -08001263 }
1264
Jeff Brown01ce2e92010-09-26 22:20:12 -07001265 // Update the temporary touch state.
1266 BitSet32 pointerIds;
1267 if (isSplit) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07001268 uint32_t pointerId = entry->pointerProperties[pointerIndex].id;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001269 pointerIds.markBit(pointerId);
Jeff Brownb88102f2010-09-08 11:49:43 -07001270 }
Jeff Brown9302c872011-07-13 22:51:29 -07001271 mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Jeff Brownb88102f2010-09-08 11:49:43 -07001272 } else {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001273 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
Jeff Brownb88102f2010-09-08 11:49:43 -07001274
1275 // If the pointer is not currently down, then ignore the event.
Jeff Brown01ce2e92010-09-26 22:20:12 -07001276 if (! mTempTouchState.down) {
Jeff Browna2cc28d2011-03-25 11:58:46 -07001277#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001278 ALOGD("Dropping event because the pointer is not down or we previously "
Jeff Brown76860e32010-10-25 17:37:46 -07001279 "dropped the pointer down event.");
1280#endif
Jeff Brownb88102f2010-09-08 11:49:43 -07001281 injectionResult = INPUT_EVENT_INJECTION_FAILED;
Jeff Brownb88102f2010-09-08 11:49:43 -07001282 goto Failed;
1283 }
Jeff Brown98db5fa2011-06-08 15:37:10 -07001284
1285 // Check whether touches should slip outside of the current foreground window.
1286 if (maskedAction == AMOTION_EVENT_ACTION_MOVE
1287 && entry->pointerCount == 1
1288 && mTempTouchState.isSlippery()) {
Jeff Brown3241b6b2012-02-03 15:08:02 -08001289 int32_t x = int32_t(entry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
1290 int32_t y = int32_t(entry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Jeff Brown98db5fa2011-06-08 15:37:10 -07001291
Jeff Brown9302c872011-07-13 22:51:29 -07001292 sp<InputWindowHandle> oldTouchedWindowHandle =
1293 mTempTouchState.getFirstForegroundWindowHandle();
1294 sp<InputWindowHandle> newTouchedWindowHandle = findTouchedWindowAtLocked(x, y);
1295 if (oldTouchedWindowHandle != newTouchedWindowHandle
1296 && newTouchedWindowHandle != NULL) {
Jeff Brown98db5fa2011-06-08 15:37:10 -07001297#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001298 ALOGD("Touch is slipping out of window %s into window %s.",
Jeff Browncc4f7db2011-08-30 20:34:48 -07001299 oldTouchedWindowHandle->getName().string(),
1300 newTouchedWindowHandle->getName().string());
Jeff Brown98db5fa2011-06-08 15:37:10 -07001301#endif
1302 // Make a slippery exit from the old window.
Jeff Brown9302c872011-07-13 22:51:29 -07001303 mTempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
Jeff Brown98db5fa2011-06-08 15:37:10 -07001304 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT, BitSet32(0));
1305
1306 // Make a slippery entrance into the new window.
Jeff Browncc4f7db2011-08-30 20:34:48 -07001307 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Jeff Brown98db5fa2011-06-08 15:37:10 -07001308 isSplit = true;
1309 }
1310
1311 int32_t targetFlags = InputTarget::FLAG_FOREGROUND
1312 | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
1313 if (isSplit) {
1314 targetFlags |= InputTarget::FLAG_SPLIT;
1315 }
Jeff Brown9302c872011-07-13 22:51:29 -07001316 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
Jeff Brown98db5fa2011-06-08 15:37:10 -07001317 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1318 }
1319
1320 BitSet32 pointerIds;
1321 if (isSplit) {
1322 pointerIds.markBit(entry->pointerProperties[0].id);
1323 }
Jeff Brown9302c872011-07-13 22:51:29 -07001324 mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Jeff Brown98db5fa2011-06-08 15:37:10 -07001325 }
1326 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001327 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001328
Jeff Brown9302c872011-07-13 22:51:29 -07001329 if (newHoverWindowHandle != mLastHoverWindowHandle) {
Jeff Browna032cc02011-03-07 16:56:21 -08001330 // Let the previous window know that the hover sequence is over.
Jeff Brown9302c872011-07-13 22:51:29 -07001331 if (mLastHoverWindowHandle != NULL) {
Jeff Browna032cc02011-03-07 16:56:21 -08001332#if DEBUG_HOVER
Steve Block5baa3a62011-12-20 16:23:08 +00001333 ALOGD("Sending hover exit event to window %s.",
Jeff Browncc4f7db2011-08-30 20:34:48 -07001334 mLastHoverWindowHandle->getName().string());
Jeff Browna032cc02011-03-07 16:56:21 -08001335#endif
Jeff Brown9302c872011-07-13 22:51:29 -07001336 mTempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
Jeff Browna032cc02011-03-07 16:56:21 -08001337 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
1338 }
1339
1340 // Let the new window know that the hover sequence is starting.
Jeff Brown9302c872011-07-13 22:51:29 -07001341 if (newHoverWindowHandle != NULL) {
Jeff Browna032cc02011-03-07 16:56:21 -08001342#if DEBUG_HOVER
Steve Block5baa3a62011-12-20 16:23:08 +00001343 ALOGD("Sending hover enter event to window %s.",
Jeff Browncc4f7db2011-08-30 20:34:48 -07001344 newHoverWindowHandle->getName().string());
Jeff Browna032cc02011-03-07 16:56:21 -08001345#endif
Jeff Brown9302c872011-07-13 22:51:29 -07001346 mTempTouchState.addOrUpdateWindow(newHoverWindowHandle,
Jeff Browna032cc02011-03-07 16:56:21 -08001347 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER, BitSet32(0));
1348 }
1349 }
1350
Jeff Brown01ce2e92010-09-26 22:20:12 -07001351 // Check permission to inject into all touched foreground windows and ensure there
1352 // is at least one touched foreground window.
1353 {
1354 bool haveForegroundWindow = false;
1355 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1356 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1357 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1358 haveForegroundWindow = true;
Jeff Brown9302c872011-07-13 22:51:29 -07001359 if (! checkInjectionPermission(touchedWindow.windowHandle,
1360 entry->injectionState)) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001361 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1362 injectionPermission = INJECTION_PERMISSION_DENIED;
1363 goto Failed;
1364 }
1365 }
1366 }
1367 if (! haveForegroundWindow) {
Jeff Browna2cc28d2011-03-25 11:58:46 -07001368#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001369 ALOGD("Dropping event because there is no touched foreground window to receive it.");
Jeff Brownb88102f2010-09-08 11:49:43 -07001370#endif
1371 injectionResult = INPUT_EVENT_INJECTION_FAILED;
Jeff Brownb88102f2010-09-08 11:49:43 -07001372 goto Failed;
1373 }
1374
Jeff Brown01ce2e92010-09-26 22:20:12 -07001375 // Permission granted to injection into all touched foreground windows.
1376 injectionPermission = INJECTION_PERMISSION_GRANTED;
1377 }
Jeff Brown519e0242010-09-15 15:18:56 -07001378
Kenny Root7a9db182011-06-02 15:16:05 -07001379 // Check whether windows listening for outside touches are owned by the same UID. If it is
1380 // set the policy flag that we will not reveal coordinate information to this window.
1381 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
Jeff Brown9302c872011-07-13 22:51:29 -07001382 sp<InputWindowHandle> foregroundWindowHandle =
1383 mTempTouchState.getFirstForegroundWindowHandle();
Jeff Browncc4f7db2011-08-30 20:34:48 -07001384 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Kenny Root7a9db182011-06-02 15:16:05 -07001385 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1386 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1387 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
Jeff Brown9302c872011-07-13 22:51:29 -07001388 sp<InputWindowHandle> inputWindowHandle = touchedWindow.windowHandle;
Jeff Browncc4f7db2011-08-30 20:34:48 -07001389 if (inputWindowHandle->getInfo()->ownerUid != foregroundWindowUid) {
Jeff Brown9302c872011-07-13 22:51:29 -07001390 mTempTouchState.addOrUpdateWindow(inputWindowHandle,
Kenny Root7a9db182011-06-02 15:16:05 -07001391 InputTarget::FLAG_ZERO_COORDS, BitSet32(0));
1392 }
1393 }
1394 }
1395 }
1396
Jeff Brown01ce2e92010-09-26 22:20:12 -07001397 // Ensure all touched foreground windows are ready for new input.
1398 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1399 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1400 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1401 // If the touched window is paused then keep waiting.
Jeff Browncc4f7db2011-08-30 20:34:48 -07001402 if (touchedWindow.windowHandle->getInfo()->paused) {
Jeff Browna2cc28d2011-03-25 11:58:46 -07001403#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001404 ALOGD("Waiting because touched window is paused.");
Jeff Brown519e0242010-09-15 15:18:56 -07001405#endif
Jeff Brown01ce2e92010-09-26 22:20:12 -07001406 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brown9302c872011-07-13 22:51:29 -07001407 NULL, touchedWindow.windowHandle, nextWakeupTime);
Jeff Brown01ce2e92010-09-26 22:20:12 -07001408 goto Unresponsive;
1409 }
1410
1411 // If the touched window is still working on previous events then keep waiting.
Jeff Brown0952c302012-02-13 13:48:59 -08001412 if (!isWindowReadyForMoreInputLocked(currentTime, touchedWindow.windowHandle, entry)) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001413#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001414 ALOGD("Waiting because touched window still processing previous input.");
Jeff Brown01ce2e92010-09-26 22:20:12 -07001415#endif
1416 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brown9302c872011-07-13 22:51:29 -07001417 NULL, touchedWindow.windowHandle, nextWakeupTime);
Jeff Brown01ce2e92010-09-26 22:20:12 -07001418 goto Unresponsive;
1419 }
1420 }
1421 }
1422
1423 // If this is the first pointer going down and the touched window has a wallpaper
1424 // then also add the touched wallpaper windows so they are locked in for the duration
1425 // of the touch gesture.
Jeff Brown33bbfd22011-02-24 20:55:35 -08001426 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
1427 // engine only supports touch events. We would need to add a mechanism similar
1428 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
1429 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
Jeff Brown9302c872011-07-13 22:51:29 -07001430 sp<InputWindowHandle> foregroundWindowHandle =
1431 mTempTouchState.getFirstForegroundWindowHandle();
Jeff Browncc4f7db2011-08-30 20:34:48 -07001432 if (foregroundWindowHandle->getInfo()->hasWallpaper) {
Jeff Brown9302c872011-07-13 22:51:29 -07001433 for (size_t i = 0; i < mWindowHandles.size(); i++) {
1434 sp<InputWindowHandle> windowHandle = mWindowHandles.itemAt(i);
Jeff Browncc4f7db2011-08-30 20:34:48 -07001435 if (windowHandle->getInfo()->layoutParamsType
1436 == InputWindowInfo::TYPE_WALLPAPER) {
Jeff Brown9302c872011-07-13 22:51:29 -07001437 mTempTouchState.addOrUpdateWindow(windowHandle,
Jeff Browna032cc02011-03-07 16:56:21 -08001438 InputTarget::FLAG_WINDOW_IS_OBSCURED
1439 | InputTarget::FLAG_DISPATCH_AS_IS,
1440 BitSet32(0));
Jeff Brown01ce2e92010-09-26 22:20:12 -07001441 }
1442 }
1443 }
1444 }
1445
Jeff Brownb88102f2010-09-08 11:49:43 -07001446 // Success! Output targets.
1447 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
Jeff Brownb88102f2010-09-08 11:49:43 -07001448
Jeff Brown01ce2e92010-09-26 22:20:12 -07001449 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1450 const TouchedWindow& touchedWindow = mTempTouchState.windows.itemAt(i);
Jeff Brown9302c872011-07-13 22:51:29 -07001451 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Jeff Browne9bb9be2012-02-06 15:47:55 -08001452 touchedWindow.pointerIds, inputTargets);
Jeff Brownb88102f2010-09-08 11:49:43 -07001453 }
1454
Jeff Browna032cc02011-03-07 16:56:21 -08001455 // Drop the outside or hover touch windows since we will not care about them
1456 // in the next iteration.
1457 mTempTouchState.filterNonAsIsTouchWindows();
Jeff Brown01ce2e92010-09-26 22:20:12 -07001458
Jeff Brownb88102f2010-09-08 11:49:43 -07001459Failed:
1460 // Check injection permission once and for all.
1461 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001462 if (checkInjectionPermission(NULL, entry->injectionState)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001463 injectionPermission = INJECTION_PERMISSION_GRANTED;
1464 } else {
1465 injectionPermission = INJECTION_PERMISSION_DENIED;
1466 }
1467 }
1468
1469 // Update final pieces of touch state if the injector had permission.
1470 if (injectionPermission == INJECTION_PERMISSION_GRANTED) {
Jeff Brown95712852011-01-04 19:41:59 -08001471 if (!wrongDevice) {
Jeff Brown81346812011-06-28 20:08:48 -07001472 if (switchedDevice) {
1473#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001474 ALOGD("Conflicting pointer actions: Switched to a different device.");
Jeff Brown81346812011-06-28 20:08:48 -07001475#endif
1476 *outConflictingPointerActions = true;
1477 }
1478
1479 if (isHoverAction) {
1480 // Started hovering, therefore no longer down.
1481 if (mTouchState.down) {
1482#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001483 ALOGD("Conflicting pointer actions: Hover received while pointer was down.");
Jeff Brown81346812011-06-28 20:08:48 -07001484#endif
1485 *outConflictingPointerActions = true;
1486 }
1487 mTouchState.reset();
1488 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER
1489 || maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
1490 mTouchState.deviceId = entry->deviceId;
1491 mTouchState.source = entry->source;
1492 }
1493 } else if (maskedAction == AMOTION_EVENT_ACTION_UP
1494 || maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Jeff Brown95712852011-01-04 19:41:59 -08001495 // All pointers up or canceled.
Jeff Brown33bbfd22011-02-24 20:55:35 -08001496 mTouchState.reset();
Jeff Brown95712852011-01-04 19:41:59 -08001497 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1498 // First pointer went down.
1499 if (mTouchState.down) {
Jeff Brownb6997262010-10-08 22:31:17 -07001500#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001501 ALOGD("Conflicting pointer actions: Down received while already down.");
Jeff Brownb6997262010-10-08 22:31:17 -07001502#endif
Jeff Brown81346812011-06-28 20:08:48 -07001503 *outConflictingPointerActions = true;
Jeff Brown95712852011-01-04 19:41:59 -08001504 }
Jeff Brown33bbfd22011-02-24 20:55:35 -08001505 mTouchState.copyFrom(mTempTouchState);
Jeff Brown95712852011-01-04 19:41:59 -08001506 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
1507 // One pointer went up.
1508 if (isSplit) {
1509 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07001510 uint32_t pointerId = entry->pointerProperties[pointerIndex].id;
Jeff Brownb88102f2010-09-08 11:49:43 -07001511
Jeff Brown95712852011-01-04 19:41:59 -08001512 for (size_t i = 0; i < mTempTouchState.windows.size(); ) {
1513 TouchedWindow& touchedWindow = mTempTouchState.windows.editItemAt(i);
1514 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
1515 touchedWindow.pointerIds.clearBit(pointerId);
1516 if (touchedWindow.pointerIds.isEmpty()) {
1517 mTempTouchState.windows.removeAt(i);
1518 continue;
1519 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001520 }
Jeff Brown95712852011-01-04 19:41:59 -08001521 i += 1;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001522 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001523 }
Jeff Brown33bbfd22011-02-24 20:55:35 -08001524 mTouchState.copyFrom(mTempTouchState);
1525 } else if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
1526 // Discard temporary touch state since it was only valid for this action.
1527 } else {
1528 // Save changes to touch state as-is for all other actions.
1529 mTouchState.copyFrom(mTempTouchState);
Jeff Brownb88102f2010-09-08 11:49:43 -07001530 }
Jeff Browna032cc02011-03-07 16:56:21 -08001531
1532 // Update hover state.
Jeff Brown9302c872011-07-13 22:51:29 -07001533 mLastHoverWindowHandle = newHoverWindowHandle;
Jeff Brown95712852011-01-04 19:41:59 -08001534 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001535 } else {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001536#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001537 ALOGD("Not updating touch focus because injection was denied.");
Jeff Brown01ce2e92010-09-26 22:20:12 -07001538#endif
Jeff Brownb88102f2010-09-08 11:49:43 -07001539 }
1540
1541Unresponsive:
Jeff Brown120a4592010-10-27 18:43:51 -07001542 // Reset temporary touch state to ensure we release unnecessary references to input channels.
1543 mTempTouchState.reset();
1544
Jeff Brown519e0242010-09-15 15:18:56 -07001545 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
1546 updateDispatchStatisticsLocked(currentTime, entry,
1547 injectionResult, timeSpentWaitingForApplication);
Jeff Brownb88102f2010-09-08 11:49:43 -07001548#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001549 ALOGD("findTouchedWindow finished: injectionResult=%d, injectionPermission=%d, "
Jeff Brown01ce2e92010-09-26 22:20:12 -07001550 "timeSpentWaitingForApplication=%0.1fms",
Jeff Brown519e0242010-09-15 15:18:56 -07001551 injectionResult, injectionPermission, timeSpentWaitingForApplication / 1000000.0);
Jeff Brownb88102f2010-09-08 11:49:43 -07001552#endif
1553 return injectionResult;
1554}
1555
Jeff Brown9302c872011-07-13 22:51:29 -07001556void InputDispatcher::addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
Jeff Browne9bb9be2012-02-06 15:47:55 -08001557 int32_t targetFlags, BitSet32 pointerIds, Vector<InputTarget>& inputTargets) {
1558 inputTargets.push();
Jeff Brownb88102f2010-09-08 11:49:43 -07001559
Jeff Browncc4f7db2011-08-30 20:34:48 -07001560 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Jeff Browne9bb9be2012-02-06 15:47:55 -08001561 InputTarget& target = inputTargets.editTop();
Jeff Browncc4f7db2011-08-30 20:34:48 -07001562 target.inputChannel = windowInfo->inputChannel;
Jeff Brownb88102f2010-09-08 11:49:43 -07001563 target.flags = targetFlags;
Jeff Browncc4f7db2011-08-30 20:34:48 -07001564 target.xOffset = - windowInfo->frameLeft;
1565 target.yOffset = - windowInfo->frameTop;
1566 target.scaleFactor = windowInfo->scaleFactor;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001567 target.pointerIds = pointerIds;
Jeff Brownb88102f2010-09-08 11:49:43 -07001568}
1569
Jeff Browne9bb9be2012-02-06 15:47:55 -08001570void InputDispatcher::addMonitoringTargetsLocked(Vector<InputTarget>& inputTargets) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001571 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
Jeff Browne9bb9be2012-02-06 15:47:55 -08001572 inputTargets.push();
Jeff Brownb88102f2010-09-08 11:49:43 -07001573
Jeff Browne9bb9be2012-02-06 15:47:55 -08001574 InputTarget& target = inputTargets.editTop();
Jeff Brownb88102f2010-09-08 11:49:43 -07001575 target.inputChannel = mMonitoringChannels[i];
Jeff Brownb6110c22011-04-01 16:15:13 -07001576 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
Jeff Brownb88102f2010-09-08 11:49:43 -07001577 target.xOffset = 0;
1578 target.yOffset = 0;
Jeff Brownb6110c22011-04-01 16:15:13 -07001579 target.pointerIds.clear();
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001580 target.scaleFactor = 1.0f;
Jeff Brownb88102f2010-09-08 11:49:43 -07001581 }
1582}
1583
Jeff Brown9302c872011-07-13 22:51:29 -07001584bool InputDispatcher::checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
Jeff Brown01ce2e92010-09-26 22:20:12 -07001585 const InjectionState* injectionState) {
1586 if (injectionState
Jeff Browncc4f7db2011-08-30 20:34:48 -07001587 && (windowHandle == NULL
1588 || windowHandle->getInfo()->ownerUid != injectionState->injectorUid)
Jeff Brownb6997262010-10-08 22:31:17 -07001589 && !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Jeff Brown9302c872011-07-13 22:51:29 -07001590 if (windowHandle != NULL) {
Steve Block8564c8d2012-01-05 23:22:43 +00001591 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
Jeff Brown9302c872011-07-13 22:51:29 -07001592 "owned by uid %d",
Jeff Brownb6997262010-10-08 22:31:17 -07001593 injectionState->injectorPid, injectionState->injectorUid,
Jeff Browncc4f7db2011-08-30 20:34:48 -07001594 windowHandle->getName().string(),
1595 windowHandle->getInfo()->ownerUid);
Jeff Brownb6997262010-10-08 22:31:17 -07001596 } else {
Steve Block8564c8d2012-01-05 23:22:43 +00001597 ALOGW("Permission denied: injecting event from pid %d uid %d",
Jeff Brownb6997262010-10-08 22:31:17 -07001598 injectionState->injectorPid, injectionState->injectorUid);
Jeff Brownb88102f2010-09-08 11:49:43 -07001599 }
Jeff Brownb6997262010-10-08 22:31:17 -07001600 return false;
Jeff Brownb88102f2010-09-08 11:49:43 -07001601 }
1602 return true;
1603}
1604
Jeff Brown19dfc832010-10-05 12:26:23 -07001605bool InputDispatcher::isWindowObscuredAtPointLocked(
Jeff Brown9302c872011-07-13 22:51:29 -07001606 const sp<InputWindowHandle>& windowHandle, int32_t x, int32_t y) const {
1607 size_t numWindows = mWindowHandles.size();
Jeff Brownb88102f2010-09-08 11:49:43 -07001608 for (size_t i = 0; i < numWindows; i++) {
Jeff Brown9302c872011-07-13 22:51:29 -07001609 sp<InputWindowHandle> otherHandle = mWindowHandles.itemAt(i);
1610 if (otherHandle == windowHandle) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001611 break;
1612 }
Jeff Browncc4f7db2011-08-30 20:34:48 -07001613
1614 const InputWindowInfo* otherInfo = otherHandle->getInfo();
1615 if (otherInfo->visible && ! otherInfo->isTrustedOverlay()
1616 && otherInfo->frameContainsPoint(x, y)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001617 return true;
1618 }
1619 }
1620 return false;
1621}
1622
Jeff Brownd1c48a02012-02-06 19:12:47 -08001623bool InputDispatcher::isWindowReadyForMoreInputLocked(nsecs_t currentTime,
Jeff Brown0952c302012-02-13 13:48:59 -08001624 const sp<InputWindowHandle>& windowHandle, const EventEntry* eventEntry) {
Jeff Browncc4f7db2011-08-30 20:34:48 -07001625 ssize_t connectionIndex = getConnectionIndexLocked(windowHandle->getInputChannel());
Jeff Brown519e0242010-09-15 15:18:56 -07001626 if (connectionIndex >= 0) {
Jeff Browncbee6d62012-02-03 20:11:27 -08001627 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
Jeff Brownd1c48a02012-02-06 19:12:47 -08001628 if (connection->inputPublisherBlocked) {
1629 return false;
1630 }
Jeff Brown0952c302012-02-13 13:48:59 -08001631 if (eventEntry->type == EventEntry::TYPE_KEY) {
1632 // If the event is a key event, then we must wait for all previous events to
1633 // complete before delivering it because previous events may have the
1634 // side-effect of transferring focus to a different window and we want to
1635 // ensure that the following keys are sent to the new window.
1636 //
1637 // Suppose the user touches a button in a window then immediately presses "A".
1638 // If the button causes a pop-up window to appear then we want to ensure that
1639 // the "A" key is delivered to the new pop-up window. This is because users
1640 // often anticipate pending UI changes when typing on a keyboard.
1641 // To obtain this behavior, we must serialize key events with respect to all
1642 // prior input events.
Jeff Brownd1c48a02012-02-06 19:12:47 -08001643 return connection->outboundQueue.isEmpty()
1644 && connection->waitQueue.isEmpty();
1645 }
Jeff Brown0952c302012-02-13 13:48:59 -08001646 // Touch events can always be sent to a window immediately because the user intended
1647 // to touch whatever was visible at the time. Even if focus changes or a new
1648 // window appears moments later, the touch event was meant to be delivered to
1649 // whatever window happened to be on screen at the time.
1650 //
1651 // Generic motion events, such as trackball or joystick events are a little trickier.
1652 // Like key events, generic motion events are delivered to the focused window.
1653 // Unlike key events, generic motion events don't tend to transfer focus to other
1654 // windows and it is not important for them to be serialized. So we prefer to deliver
1655 // generic motion events as soon as possible to improve efficiency and reduce lag
1656 // through batching.
1657 //
1658 // The one case where we pause input event delivery is when the wait queue is piling
1659 // up with lots of events because the application is not responding.
1660 // This condition ensures that ANRs are detected reliably.
Jeff Brownd1c48a02012-02-06 19:12:47 -08001661 if (!connection->waitQueue.isEmpty()
1662 && currentTime >= connection->waitQueue.head->eventEntry->eventTime
1663 + STREAM_AHEAD_EVENT_TIMEOUT) {
1664 return false;
1665 }
Jeff Brown519e0242010-09-15 15:18:56 -07001666 }
Jeff Brownd1c48a02012-02-06 19:12:47 -08001667 return true;
Jeff Brown519e0242010-09-15 15:18:56 -07001668}
1669
Jeff Brown9302c872011-07-13 22:51:29 -07001670String8 InputDispatcher::getApplicationWindowLabelLocked(
1671 const sp<InputApplicationHandle>& applicationHandle,
1672 const sp<InputWindowHandle>& windowHandle) {
1673 if (applicationHandle != NULL) {
1674 if (windowHandle != NULL) {
Jeff Browncc4f7db2011-08-30 20:34:48 -07001675 String8 label(applicationHandle->getName());
Jeff Brown519e0242010-09-15 15:18:56 -07001676 label.append(" - ");
Jeff Browncc4f7db2011-08-30 20:34:48 -07001677 label.append(windowHandle->getName());
Jeff Brown519e0242010-09-15 15:18:56 -07001678 return label;
1679 } else {
Jeff Browncc4f7db2011-08-30 20:34:48 -07001680 return applicationHandle->getName();
Jeff Brown519e0242010-09-15 15:18:56 -07001681 }
Jeff Brown9302c872011-07-13 22:51:29 -07001682 } else if (windowHandle != NULL) {
Jeff Browncc4f7db2011-08-30 20:34:48 -07001683 return windowHandle->getName();
Jeff Brown519e0242010-09-15 15:18:56 -07001684 } else {
1685 return String8("<unknown application or window>");
1686 }
1687}
1688
Jeff Browne2fe69e2010-10-18 13:21:23 -07001689void InputDispatcher::pokeUserActivityLocked(const EventEntry* eventEntry) {
Jeff Brown56194eb2011-03-02 19:23:13 -08001690 int32_t eventType = POWER_MANAGER_OTHER_EVENT;
Jeff Brown4d396052010-10-29 21:50:21 -07001691 switch (eventEntry->type) {
1692 case EventEntry::TYPE_MOTION: {
Jeff Browne2fe69e2010-10-18 13:21:23 -07001693 const MotionEntry* motionEntry = static_cast<const MotionEntry*>(eventEntry);
Jeff Brown4d396052010-10-29 21:50:21 -07001694 if (motionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
1695 return;
1696 }
1697
Jeff Brown56194eb2011-03-02 19:23:13 -08001698 if (MotionEvent::isTouchEvent(motionEntry->source, motionEntry->action)) {
Joe Onorato1a542c72010-11-08 09:48:20 -08001699 eventType = POWER_MANAGER_TOUCH_EVENT;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001700 }
Jeff Brown4d396052010-10-29 21:50:21 -07001701 break;
1702 }
1703 case EventEntry::TYPE_KEY: {
1704 const KeyEntry* keyEntry = static_cast<const KeyEntry*>(eventEntry);
1705 if (keyEntry->flags & AKEY_EVENT_FLAG_CANCELED) {
1706 return;
1707 }
Jeff Brown56194eb2011-03-02 19:23:13 -08001708 eventType = POWER_MANAGER_BUTTON_EVENT;
Jeff Brown4d396052010-10-29 21:50:21 -07001709 break;
1710 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001711 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001712
Jeff Brownb88102f2010-09-08 11:49:43 -07001713 CommandEntry* commandEntry = postCommandLocked(
1714 & InputDispatcher::doPokeUserActivityLockedInterruptible);
Jeff Browne2fe69e2010-10-18 13:21:23 -07001715 commandEntry->eventTime = eventEntry->eventTime;
Jeff Brownb88102f2010-09-08 11:49:43 -07001716 commandEntry->userActivityEventType = eventType;
1717}
1718
Jeff Brown7fbdc842010-06-17 20:52:56 -07001719void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001720 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07001721#if DEBUG_DISPATCH_CYCLE
Steve Block5baa3a62011-12-20 16:23:08 +00001722 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
Jeff Brown9cc695c2011-08-23 18:35:04 -07001723 "xOffset=%f, yOffset=%f, scaleFactor=%f, "
Jeff Brown3241b6b2012-02-03 15:08:02 -08001724 "pointerIds=0x%x",
Jeff Brown519e0242010-09-15 15:18:56 -07001725 connection->getInputChannelName(), inputTarget->flags,
Jeff Brown46b9ac02010-04-22 18:58:52 -07001726 inputTarget->xOffset, inputTarget->yOffset,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001727 inputTarget->scaleFactor, inputTarget->pointerIds.value);
Jeff Brown46b9ac02010-04-22 18:58:52 -07001728#endif
1729
1730 // Skip this event if the connection status is not normal.
Jeff Brown519e0242010-09-15 15:18:56 -07001731 // We don't want to enqueue additional outbound events if the connection is broken.
Jeff Brown46b9ac02010-04-22 18:58:52 -07001732 if (connection->status != Connection::STATUS_NORMAL) {
Jeff Brownb6997262010-10-08 22:31:17 -07001733#if DEBUG_DISPATCH_CYCLE
Steve Block5baa3a62011-12-20 16:23:08 +00001734 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Jeff Brownb88102f2010-09-08 11:49:43 -07001735 connection->getInputChannelName(), connection->getStatusLabel());
Jeff Brownb6997262010-10-08 22:31:17 -07001736#endif
Jeff Brown46b9ac02010-04-22 18:58:52 -07001737 return;
1738 }
1739
Jeff Brown01ce2e92010-09-26 22:20:12 -07001740 // Split a motion event if needed.
Jeff Brown3241b6b2012-02-03 15:08:02 -08001741 if (inputTarget->flags & InputTarget::FLAG_SPLIT) {
Steve Blockec193de2012-01-09 18:35:44 +00001742 ALOG_ASSERT(eventEntry->type == EventEntry::TYPE_MOTION);
Jeff Brown01ce2e92010-09-26 22:20:12 -07001743
1744 MotionEntry* originalMotionEntry = static_cast<MotionEntry*>(eventEntry);
1745 if (inputTarget->pointerIds.count() != originalMotionEntry->pointerCount) {
1746 MotionEntry* splitMotionEntry = splitMotionEvent(
1747 originalMotionEntry, inputTarget->pointerIds);
Jeff Brown58a2da82011-01-25 16:02:22 -08001748 if (!splitMotionEntry) {
1749 return; // split event was dropped
1750 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001751#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001752 ALOGD("channel '%s' ~ Split motion event.",
Jeff Brown01ce2e92010-09-26 22:20:12 -07001753 connection->getInputChannelName());
1754 logOutboundMotionDetailsLocked(" ", splitMotionEntry);
1755#endif
Jeff Brownc0cb3dc2012-01-12 18:30:12 -08001756 enqueueDispatchEntriesLocked(currentTime, connection,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001757 splitMotionEntry, inputTarget);
Jeff Brownc0cb3dc2012-01-12 18:30:12 -08001758 splitMotionEntry->release();
1759 return;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001760 }
1761 }
1762
Jeff Brownc0cb3dc2012-01-12 18:30:12 -08001763 // Not splitting. Enqueue dispatch entries for the event as is.
Jeff Brown3241b6b2012-02-03 15:08:02 -08001764 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
Jeff Brownc0cb3dc2012-01-12 18:30:12 -08001765}
1766
1767void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001768 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07001769 bool wasEmpty = connection->outboundQueue.isEmpty();
1770
Jeff Browna032cc02011-03-07 16:56:21 -08001771 // Enqueue dispatch entries for the requested modes.
1772 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001773 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
Jeff Browna032cc02011-03-07 16:56:21 -08001774 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001775 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
Jeff Browna032cc02011-03-07 16:56:21 -08001776 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001777 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
Jeff Browna032cc02011-03-07 16:56:21 -08001778 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001779 InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brown98db5fa2011-06-08 15:37:10 -07001780 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001781 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
Jeff Brown98db5fa2011-06-08 15:37:10 -07001782 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001783 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Jeff Browna032cc02011-03-07 16:56:21 -08001784
1785 // If the outbound queue was previously empty, start the dispatch cycle going.
Jeff Brownb6110c22011-04-01 16:15:13 -07001786 if (wasEmpty && !connection->outboundQueue.isEmpty()) {
Jeff Browna032cc02011-03-07 16:56:21 -08001787 startDispatchCycleLocked(currentTime, connection);
1788 }
1789}
1790
1791void InputDispatcher::enqueueDispatchEntryLocked(
1792 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001793 int32_t dispatchMode) {
Jeff Browna032cc02011-03-07 16:56:21 -08001794 int32_t inputTargetFlags = inputTarget->flags;
1795 if (!(inputTargetFlags & dispatchMode)) {
1796 return;
1797 }
1798 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
1799
Jeff Brown46b9ac02010-04-22 18:58:52 -07001800 // This is a new event.
1801 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Jeff Brownac386072011-07-20 15:19:50 -07001802 DispatchEntry* dispatchEntry = new DispatchEntry(eventEntry, // increments ref
Dianne Hackbornaa9d84c2011-05-09 19:00:59 -07001803 inputTargetFlags, inputTarget->xOffset, inputTarget->yOffset,
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001804 inputTarget->scaleFactor);
Jeff Brown6ec402b2010-07-28 15:48:59 -07001805
Jeff Brown81346812011-06-28 20:08:48 -07001806 // Apply target flags and update the connection's input state.
1807 switch (eventEntry->type) {
1808 case EventEntry::TYPE_KEY: {
1809 KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
1810 dispatchEntry->resolvedAction = keyEntry->action;
1811 dispatchEntry->resolvedFlags = keyEntry->flags;
1812
1813 if (!connection->inputState.trackKey(keyEntry,
1814 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags)) {
1815#if DEBUG_DISPATCH_CYCLE
Steve Block5baa3a62011-12-20 16:23:08 +00001816 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
Jeff Brown81346812011-06-28 20:08:48 -07001817 connection->getInputChannelName());
1818#endif
Jeff Brownc0cb3dc2012-01-12 18:30:12 -08001819 delete dispatchEntry;
Jeff Brown81346812011-06-28 20:08:48 -07001820 return; // skip the inconsistent event
1821 }
1822 break;
1823 }
1824
1825 case EventEntry::TYPE_MOTION: {
1826 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
1827 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
1828 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
1829 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
1830 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
1831 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
1832 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
1833 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
1834 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
1835 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
1836 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
1837 } else {
1838 dispatchEntry->resolvedAction = motionEntry->action;
1839 }
1840 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE
1841 && !connection->inputState.isHovering(
1842 motionEntry->deviceId, motionEntry->source)) {
1843#if DEBUG_DISPATCH_CYCLE
Steve Block5baa3a62011-12-20 16:23:08 +00001844 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter event",
Jeff Brown81346812011-06-28 20:08:48 -07001845 connection->getInputChannelName());
1846#endif
1847 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
1848 }
1849
1850 dispatchEntry->resolvedFlags = motionEntry->flags;
1851 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
1852 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
1853 }
1854
1855 if (!connection->inputState.trackMotion(motionEntry,
1856 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags)) {
1857#if DEBUG_DISPATCH_CYCLE
Steve Block5baa3a62011-12-20 16:23:08 +00001858 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion event",
Jeff Brown81346812011-06-28 20:08:48 -07001859 connection->getInputChannelName());
1860#endif
Jeff Brownc0cb3dc2012-01-12 18:30:12 -08001861 delete dispatchEntry;
Jeff Brown81346812011-06-28 20:08:48 -07001862 return; // skip the inconsistent event
1863 }
1864 break;
1865 }
1866 }
1867
Jeff Brownc0cb3dc2012-01-12 18:30:12 -08001868 // Remember that we are waiting for this dispatch to complete.
1869 if (dispatchEntry->hasForegroundTarget()) {
1870 incrementPendingForegroundDispatchesLocked(eventEntry);
1871 }
1872
Jeff Brown46b9ac02010-04-22 18:58:52 -07001873 // Enqueue the dispatch entry.
1874 connection->outboundQueue.enqueueAtTail(dispatchEntry);
Jeff Brown481c1572012-03-09 14:41:15 -08001875 traceOutboundQueueLengthLocked(connection);
Jeff Brown46b9ac02010-04-22 18:58:52 -07001876}
1877
Jeff Brown7fbdc842010-06-17 20:52:56 -07001878void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Jeff Brown519e0242010-09-15 15:18:56 -07001879 const sp<Connection>& connection) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07001880#if DEBUG_DISPATCH_CYCLE
Steve Block5baa3a62011-12-20 16:23:08 +00001881 ALOGD("channel '%s' ~ startDispatchCycle",
Jeff Brown46b9ac02010-04-22 18:58:52 -07001882 connection->getInputChannelName());
1883#endif
1884
Jeff Brownd1c48a02012-02-06 19:12:47 -08001885 while (connection->status == Connection::STATUS_NORMAL
1886 && !connection->outboundQueue.isEmpty()) {
1887 DispatchEntry* dispatchEntry = connection->outboundQueue.head;
Jeff Brown46b9ac02010-04-22 18:58:52 -07001888
Jeff Brownd1c48a02012-02-06 19:12:47 -08001889 // Publish the event.
1890 status_t status;
1891 EventEntry* eventEntry = dispatchEntry->eventEntry;
1892 switch (eventEntry->type) {
1893 case EventEntry::TYPE_KEY: {
1894 KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
Jeff Brown46b9ac02010-04-22 18:58:52 -07001895
Jeff Brownd1c48a02012-02-06 19:12:47 -08001896 // Publish the key event.
Jeff Brown072ec962012-02-07 14:46:57 -08001897 status = connection->inputPublisher.publishKeyEvent(dispatchEntry->seq,
Jeff Brownd1c48a02012-02-06 19:12:47 -08001898 keyEntry->deviceId, keyEntry->source,
1899 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags,
1900 keyEntry->keyCode, keyEntry->scanCode,
1901 keyEntry->metaState, keyEntry->repeatCount, keyEntry->downTime,
1902 keyEntry->eventTime);
1903 break;
1904 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001905
Jeff Brownd1c48a02012-02-06 19:12:47 -08001906 case EventEntry::TYPE_MOTION: {
1907 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
Jeff Brown46b9ac02010-04-22 18:58:52 -07001908
Jeff Brownd1c48a02012-02-06 19:12:47 -08001909 PointerCoords scaledCoords[MAX_POINTERS];
1910 const PointerCoords* usingCoords = motionEntry->pointerCoords;
Jeff Brown46b9ac02010-04-22 18:58:52 -07001911
Jeff Brownd1c48a02012-02-06 19:12:47 -08001912 // Set the X and Y offset depending on the input source.
1913 float xOffset, yOffset, scaleFactor;
1914 if ((motionEntry->source & AINPUT_SOURCE_CLASS_POINTER)
1915 && !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
1916 scaleFactor = dispatchEntry->scaleFactor;
1917 xOffset = dispatchEntry->xOffset * scaleFactor;
1918 yOffset = dispatchEntry->yOffset * scaleFactor;
1919 if (scaleFactor != 1.0f) {
1920 for (size_t i = 0; i < motionEntry->pointerCount; i++) {
1921 scaledCoords[i] = motionEntry->pointerCoords[i];
1922 scaledCoords[i].scale(scaleFactor);
1923 }
1924 usingCoords = scaledCoords;
1925 }
1926 } else {
1927 xOffset = 0.0f;
1928 yOffset = 0.0f;
1929 scaleFactor = 1.0f;
1930
1931 // We don't want the dispatch target to know.
1932 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
1933 for (size_t i = 0; i < motionEntry->pointerCount; i++) {
1934 scaledCoords[i].clear();
1935 }
1936 usingCoords = scaledCoords;
1937 }
1938 }
1939
1940 // Publish the motion event.
Jeff Brown072ec962012-02-07 14:46:57 -08001941 status = connection->inputPublisher.publishMotionEvent(dispatchEntry->seq,
Jeff Brownd1c48a02012-02-06 19:12:47 -08001942 motionEntry->deviceId, motionEntry->source,
1943 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags,
1944 motionEntry->edgeFlags, motionEntry->metaState, motionEntry->buttonState,
1945 xOffset, yOffset,
1946 motionEntry->xPrecision, motionEntry->yPrecision,
1947 motionEntry->downTime, motionEntry->eventTime,
1948 motionEntry->pointerCount, motionEntry->pointerProperties,
1949 usingCoords);
1950 break;
1951 }
1952
1953 default:
1954 ALOG_ASSERT(false);
Jeff Brown46b9ac02010-04-22 18:58:52 -07001955 return;
1956 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07001957
Jeff Brownd1c48a02012-02-06 19:12:47 -08001958 // Check the result.
Jeff Brown46b9ac02010-04-22 18:58:52 -07001959 if (status) {
Jeff Brownd1c48a02012-02-06 19:12:47 -08001960 if (status == WOULD_BLOCK) {
1961 if (connection->waitQueue.isEmpty()) {
1962 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
1963 "This is unexpected because the wait queue is empty, so the pipe "
1964 "should be empty and we shouldn't have any problems writing an "
1965 "event to it, status=%d", connection->getInputChannelName(), status);
1966 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
1967 } else {
1968 // Pipe is full and we are waiting for the app to finish process some events
1969 // before sending more events to it.
1970#if DEBUG_DISPATCH_CYCLE
1971 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
1972 "waiting for the application to catch up",
1973 connection->getInputChannelName());
1974#endif
1975 connection->inputPublisherBlocked = true;
1976 }
1977 } else {
1978 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
1979 "status=%d", connection->getInputChannelName(), status);
1980 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
1981 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07001982 return;
1983 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07001984
Jeff Brownd1c48a02012-02-06 19:12:47 -08001985 // Re-enqueue the event on the wait queue.
1986 connection->outboundQueue.dequeue(dispatchEntry);
Jeff Brown481c1572012-03-09 14:41:15 -08001987 traceOutboundQueueLengthLocked(connection);
Jeff Brownd1c48a02012-02-06 19:12:47 -08001988 connection->waitQueue.enqueueAtTail(dispatchEntry);
Jeff Brown481c1572012-03-09 14:41:15 -08001989 traceWaitQueueLengthLocked(connection);
Jeff Brown46b9ac02010-04-22 18:58:52 -07001990 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07001991}
1992
Jeff Brown7fbdc842010-06-17 20:52:56 -07001993void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Jeff Brown072ec962012-02-07 14:46:57 -08001994 const sp<Connection>& connection, uint32_t seq, bool handled) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07001995#if DEBUG_DISPATCH_CYCLE
Jeff Brown072ec962012-02-07 14:46:57 -08001996 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
1997 connection->getInputChannelName(), seq, toString(handled));
Jeff Brown46b9ac02010-04-22 18:58:52 -07001998#endif
1999
Jeff Brownd1c48a02012-02-06 19:12:47 -08002000 connection->inputPublisherBlocked = false;
2001
Jeff Brown9c3cda02010-06-15 01:31:58 -07002002 if (connection->status == Connection::STATUS_BROKEN
2003 || connection->status == Connection::STATUS_ZOMBIE) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002004 return;
2005 }
2006
Jeff Brown3915bb82010-11-05 15:02:16 -07002007 // Notify other system components and prepare to start the next dispatch cycle.
Jeff Brown072ec962012-02-07 14:46:57 -08002008 onDispatchCycleFinishedLocked(currentTime, connection, seq, handled);
Jeff Brownb88102f2010-09-08 11:49:43 -07002009}
2010
Jeff Brownb6997262010-10-08 22:31:17 -07002011void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Jeff Browncc4f7db2011-08-30 20:34:48 -07002012 const sp<Connection>& connection, bool notify) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002013#if DEBUG_DISPATCH_CYCLE
Steve Block5baa3a62011-12-20 16:23:08 +00002014 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
Jeff Browncc4f7db2011-08-30 20:34:48 -07002015 connection->getInputChannelName(), toString(notify));
Jeff Brown46b9ac02010-04-22 18:58:52 -07002016#endif
2017
Jeff Brownd1c48a02012-02-06 19:12:47 -08002018 // Clear the dispatch queues.
2019 drainDispatchQueueLocked(&connection->outboundQueue);
Jeff Brown481c1572012-03-09 14:41:15 -08002020 traceOutboundQueueLengthLocked(connection);
Jeff Brownd1c48a02012-02-06 19:12:47 -08002021 drainDispatchQueueLocked(&connection->waitQueue);
Jeff Brown481c1572012-03-09 14:41:15 -08002022 traceWaitQueueLengthLocked(connection);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002023
Jeff Brownb6997262010-10-08 22:31:17 -07002024 // The connection appears to be unrecoverably broken.
Jeff Brown9c3cda02010-06-15 01:31:58 -07002025 // Ignore already broken or zombie connections.
Jeff Brownb6997262010-10-08 22:31:17 -07002026 if (connection->status == Connection::STATUS_NORMAL) {
2027 connection->status = Connection::STATUS_BROKEN;
Jeff Brown46b9ac02010-04-22 18:58:52 -07002028
Jeff Browncc4f7db2011-08-30 20:34:48 -07002029 if (notify) {
2030 // Notify other system components.
2031 onDispatchCycleBrokenLocked(currentTime, connection);
2032 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002033 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002034}
2035
Jeff Brownd1c48a02012-02-06 19:12:47 -08002036void InputDispatcher::drainDispatchQueueLocked(Queue<DispatchEntry>* queue) {
2037 while (!queue->isEmpty()) {
2038 DispatchEntry* dispatchEntry = queue->dequeueAtHead();
2039 releaseDispatchEntryLocked(dispatchEntry);
Jeff Brownb88102f2010-09-08 11:49:43 -07002040 }
Jeff Brownb88102f2010-09-08 11:49:43 -07002041}
2042
Jeff Brownd1c48a02012-02-06 19:12:47 -08002043void InputDispatcher::releaseDispatchEntryLocked(DispatchEntry* dispatchEntry) {
2044 if (dispatchEntry->hasForegroundTarget()) {
2045 decrementPendingForegroundDispatchesLocked(dispatchEntry->eventEntry);
2046 }
2047 delete dispatchEntry;
2048}
2049
Jeff Browncbee6d62012-02-03 20:11:27 -08002050int InputDispatcher::handleReceiveCallback(int fd, int events, void* data) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002051 InputDispatcher* d = static_cast<InputDispatcher*>(data);
2052
2053 { // acquire lock
2054 AutoMutex _l(d->mLock);
2055
Jeff Browncbee6d62012-02-03 20:11:27 -08002056 ssize_t connectionIndex = d->mConnectionsByFd.indexOfKey(fd);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002057 if (connectionIndex < 0) {
Steve Block3762c312012-01-06 19:20:56 +00002058 ALOGE("Received spurious receive callback for unknown input channel. "
Jeff Browncbee6d62012-02-03 20:11:27 -08002059 "fd=%d, events=0x%x", fd, events);
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002060 return 0; // remove the callback
Jeff Brown46b9ac02010-04-22 18:58:52 -07002061 }
2062
Jeff Browncc4f7db2011-08-30 20:34:48 -07002063 bool notify;
Jeff Browncbee6d62012-02-03 20:11:27 -08002064 sp<Connection> connection = d->mConnectionsByFd.valueAt(connectionIndex);
Jeff Browncc4f7db2011-08-30 20:34:48 -07002065 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
2066 if (!(events & ALOOPER_EVENT_INPUT)) {
Steve Block8564c8d2012-01-05 23:22:43 +00002067 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
Jeff Browncc4f7db2011-08-30 20:34:48 -07002068 "events=0x%x", connection->getInputChannelName(), events);
2069 return 1;
2070 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002071
Jeff Brown1adee112012-02-07 10:25:41 -08002072 nsecs_t currentTime = now();
2073 bool gotOne = false;
2074 status_t status;
2075 for (;;) {
Jeff Brown072ec962012-02-07 14:46:57 -08002076 uint32_t seq;
2077 bool handled;
2078 status = connection->inputPublisher.receiveFinishedSignal(&seq, &handled);
Jeff Brown1adee112012-02-07 10:25:41 -08002079 if (status) {
2080 break;
2081 }
Jeff Brown072ec962012-02-07 14:46:57 -08002082 d->finishDispatchCycleLocked(currentTime, connection, seq, handled);
Jeff Brown1adee112012-02-07 10:25:41 -08002083 gotOne = true;
2084 }
2085 if (gotOne) {
Jeff Browncc4f7db2011-08-30 20:34:48 -07002086 d->runCommandsLockedInterruptible();
Jeff Brown1adee112012-02-07 10:25:41 -08002087 if (status == WOULD_BLOCK) {
2088 return 1;
2089 }
Jeff Browncc4f7db2011-08-30 20:34:48 -07002090 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002091
Jeff Brown1adee112012-02-07 10:25:41 -08002092 notify = status != DEAD_OBJECT || !connection->monitor;
2093 if (notify) {
2094 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
2095 connection->getInputChannelName(), status);
2096 }
Jeff Browncc4f7db2011-08-30 20:34:48 -07002097 } else {
2098 // Monitor channels are never explicitly unregistered.
2099 // We do it automatically when the remote endpoint is closed so don't warn
2100 // about them.
2101 notify = !connection->monitor;
2102 if (notify) {
Steve Block8564c8d2012-01-05 23:22:43 +00002103 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. "
Jeff Browncc4f7db2011-08-30 20:34:48 -07002104 "events=0x%x", connection->getInputChannelName(), events);
2105 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002106 }
2107
Jeff Browncc4f7db2011-08-30 20:34:48 -07002108 // Unregister the channel.
2109 d->unregisterInputChannelLocked(connection->inputChannel, notify);
2110 return 0; // remove the callback
Jeff Brown46b9ac02010-04-22 18:58:52 -07002111 } // release lock
2112}
2113
Jeff Brownb6997262010-10-08 22:31:17 -07002114void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Jeff Brownda3d5a92011-03-29 15:11:34 -07002115 const CancelationOptions& options) {
Jeff Browncbee6d62012-02-03 20:11:27 -08002116 for (size_t i = 0; i < mConnectionsByFd.size(); i++) {
Jeff Brownb6997262010-10-08 22:31:17 -07002117 synthesizeCancelationEventsForConnectionLocked(
Jeff Browncbee6d62012-02-03 20:11:27 -08002118 mConnectionsByFd.valueAt(i), options);
Jeff Brownb6997262010-10-08 22:31:17 -07002119 }
2120}
2121
2122void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Jeff Brownda3d5a92011-03-29 15:11:34 -07002123 const sp<InputChannel>& channel, const CancelationOptions& options) {
Jeff Brownb6997262010-10-08 22:31:17 -07002124 ssize_t index = getConnectionIndexLocked(channel);
2125 if (index >= 0) {
2126 synthesizeCancelationEventsForConnectionLocked(
Jeff Browncbee6d62012-02-03 20:11:27 -08002127 mConnectionsByFd.valueAt(index), options);
Jeff Brownb6997262010-10-08 22:31:17 -07002128 }
2129}
2130
2131void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
Jeff Brownda3d5a92011-03-29 15:11:34 -07002132 const sp<Connection>& connection, const CancelationOptions& options) {
Jeff Brownc0cb3dc2012-01-12 18:30:12 -08002133 if (connection->status == Connection::STATUS_BROKEN) {
2134 return;
2135 }
2136
Jeff Brownb6997262010-10-08 22:31:17 -07002137 nsecs_t currentTime = now();
2138
Jeff Brown8b4be5602012-02-06 16:31:05 -08002139 Vector<EventEntry*> cancelationEvents;
Jeff Brownac386072011-07-20 15:19:50 -07002140 connection->inputState.synthesizeCancelationEvents(currentTime,
Jeff Brown8b4be5602012-02-06 16:31:05 -08002141 cancelationEvents, options);
Jeff Brownb6997262010-10-08 22:31:17 -07002142
Jeff Brown8b4be5602012-02-06 16:31:05 -08002143 if (!cancelationEvents.isEmpty()) {
Jeff Brownb6997262010-10-08 22:31:17 -07002144#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00002145 ALOGD("channel '%s' ~ Synthesized %d cancelation events to bring channel back in sync "
Jeff Brownda3d5a92011-03-29 15:11:34 -07002146 "with reality: %s, mode=%d.",
Jeff Brown8b4be5602012-02-06 16:31:05 -08002147 connection->getInputChannelName(), cancelationEvents.size(),
Jeff Brownda3d5a92011-03-29 15:11:34 -07002148 options.reason, options.mode);
Jeff Brownb6997262010-10-08 22:31:17 -07002149#endif
Jeff Brown8b4be5602012-02-06 16:31:05 -08002150 for (size_t i = 0; i < cancelationEvents.size(); i++) {
2151 EventEntry* cancelationEventEntry = cancelationEvents.itemAt(i);
Jeff Brownb6997262010-10-08 22:31:17 -07002152 switch (cancelationEventEntry->type) {
2153 case EventEntry::TYPE_KEY:
2154 logOutboundKeyDetailsLocked("cancel - ",
2155 static_cast<KeyEntry*>(cancelationEventEntry));
2156 break;
2157 case EventEntry::TYPE_MOTION:
2158 logOutboundMotionDetailsLocked("cancel - ",
2159 static_cast<MotionEntry*>(cancelationEventEntry));
2160 break;
2161 }
2162
Jeff Brown81346812011-06-28 20:08:48 -07002163 InputTarget target;
Jeff Brown9302c872011-07-13 22:51:29 -07002164 sp<InputWindowHandle> windowHandle = getWindowHandleLocked(connection->inputChannel);
2165 if (windowHandle != NULL) {
Jeff Browncc4f7db2011-08-30 20:34:48 -07002166 const InputWindowInfo* windowInfo = windowHandle->getInfo();
2167 target.xOffset = -windowInfo->frameLeft;
2168 target.yOffset = -windowInfo->frameTop;
2169 target.scaleFactor = windowInfo->scaleFactor;
Jeff Brownb6997262010-10-08 22:31:17 -07002170 } else {
Jeff Brown81346812011-06-28 20:08:48 -07002171 target.xOffset = 0;
2172 target.yOffset = 0;
2173 target.scaleFactor = 1.0f;
Jeff Brownb6997262010-10-08 22:31:17 -07002174 }
Jeff Brown81346812011-06-28 20:08:48 -07002175 target.inputChannel = connection->inputChannel;
2176 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
Jeff Brownb6997262010-10-08 22:31:17 -07002177
Jeff Brown81346812011-06-28 20:08:48 -07002178 enqueueDispatchEntryLocked(connection, cancelationEventEntry, // increments ref
Jeff Brown3241b6b2012-02-03 15:08:02 -08002179 &target, InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brownb6997262010-10-08 22:31:17 -07002180
Jeff Brownac386072011-07-20 15:19:50 -07002181 cancelationEventEntry->release();
Jeff Brownb6997262010-10-08 22:31:17 -07002182 }
2183
Jeff Brownd1c48a02012-02-06 19:12:47 -08002184 startDispatchCycleLocked(currentTime, connection);
Jeff Brownb6997262010-10-08 22:31:17 -07002185 }
2186}
2187
Jeff Brown01ce2e92010-09-26 22:20:12 -07002188InputDispatcher::MotionEntry*
2189InputDispatcher::splitMotionEvent(const MotionEntry* originalMotionEntry, BitSet32 pointerIds) {
Steve Blockec193de2012-01-09 18:35:44 +00002190 ALOG_ASSERT(pointerIds.value != 0);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002191
2192 uint32_t splitPointerIndexMap[MAX_POINTERS];
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002193 PointerProperties splitPointerProperties[MAX_POINTERS];
Jeff Brown01ce2e92010-09-26 22:20:12 -07002194 PointerCoords splitPointerCoords[MAX_POINTERS];
2195
2196 uint32_t originalPointerCount = originalMotionEntry->pointerCount;
2197 uint32_t splitPointerCount = 0;
2198
2199 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
2200 originalPointerIndex++) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002201 const PointerProperties& pointerProperties =
2202 originalMotionEntry->pointerProperties[originalPointerIndex];
2203 uint32_t pointerId = uint32_t(pointerProperties.id);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002204 if (pointerIds.hasBit(pointerId)) {
2205 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002206 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
Jeff Brownace13b12011-03-09 17:39:48 -08002207 splitPointerCoords[splitPointerCount].copyFrom(
Jeff Brown3241b6b2012-02-03 15:08:02 -08002208 originalMotionEntry->pointerCoords[originalPointerIndex]);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002209 splitPointerCount += 1;
2210 }
2211 }
Jeff Brown58a2da82011-01-25 16:02:22 -08002212
2213 if (splitPointerCount != pointerIds.count()) {
2214 // This is bad. We are missing some of the pointers that we expected to deliver.
2215 // Most likely this indicates that we received an ACTION_MOVE events that has
2216 // different pointer ids than we expected based on the previous ACTION_DOWN
2217 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
2218 // in this way.
Steve Block8564c8d2012-01-05 23:22:43 +00002219 ALOGW("Dropping split motion event because the pointer count is %d but "
Jeff Brown58a2da82011-01-25 16:02:22 -08002220 "we expected there to be %d pointers. This probably means we received "
2221 "a broken sequence of pointer ids from the input device.",
2222 splitPointerCount, pointerIds.count());
2223 return NULL;
2224 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07002225
2226 int32_t action = originalMotionEntry->action;
2227 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
2228 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
2229 || maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2230 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002231 const PointerProperties& pointerProperties =
2232 originalMotionEntry->pointerProperties[originalPointerIndex];
2233 uint32_t pointerId = uint32_t(pointerProperties.id);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002234 if (pointerIds.hasBit(pointerId)) {
2235 if (pointerIds.count() == 1) {
2236 // The first/last pointer went down/up.
2237 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
2238 ? AMOTION_EVENT_ACTION_DOWN : AMOTION_EVENT_ACTION_UP;
Jeff Brown9a01d052010-09-27 16:35:11 -07002239 } else {
2240 // A secondary pointer went down/up.
2241 uint32_t splitPointerIndex = 0;
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002242 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
Jeff Brown9a01d052010-09-27 16:35:11 -07002243 splitPointerIndex += 1;
2244 }
2245 action = maskedAction | (splitPointerIndex
2246 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002247 }
2248 } else {
2249 // An unrelated pointer changed.
2250 action = AMOTION_EVENT_ACTION_MOVE;
2251 }
2252 }
2253
Jeff Brownac386072011-07-20 15:19:50 -07002254 MotionEntry* splitMotionEntry = new MotionEntry(
Jeff Brown01ce2e92010-09-26 22:20:12 -07002255 originalMotionEntry->eventTime,
2256 originalMotionEntry->deviceId,
2257 originalMotionEntry->source,
2258 originalMotionEntry->policyFlags,
2259 action,
2260 originalMotionEntry->flags,
2261 originalMotionEntry->metaState,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002262 originalMotionEntry->buttonState,
Jeff Brown01ce2e92010-09-26 22:20:12 -07002263 originalMotionEntry->edgeFlags,
2264 originalMotionEntry->xPrecision,
2265 originalMotionEntry->yPrecision,
2266 originalMotionEntry->downTime,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002267 splitPointerCount, splitPointerProperties, splitPointerCoords);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002268
Jeff Browna032cc02011-03-07 16:56:21 -08002269 if (originalMotionEntry->injectionState) {
2270 splitMotionEntry->injectionState = originalMotionEntry->injectionState;
2271 splitMotionEntry->injectionState->refCount += 1;
2272 }
2273
Jeff Brown01ce2e92010-09-26 22:20:12 -07002274 return splitMotionEntry;
2275}
2276
Jeff Brownbe1aa822011-07-27 16:04:54 -07002277void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002278#if DEBUG_INBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00002279 ALOGD("notifyConfigurationChanged - eventTime=%lld", args->eventTime);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002280#endif
2281
Jeff Brownb88102f2010-09-08 11:49:43 -07002282 bool needWake;
Jeff Brown46b9ac02010-04-22 18:58:52 -07002283 { // acquire lock
2284 AutoMutex _l(mLock);
2285
Jeff Brownbe1aa822011-07-27 16:04:54 -07002286 ConfigurationChangedEntry* newEntry = new ConfigurationChangedEntry(args->eventTime);
Jeff Brownb88102f2010-09-08 11:49:43 -07002287 needWake = enqueueInboundEventLocked(newEntry);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002288 } // release lock
2289
Jeff Brownb88102f2010-09-08 11:49:43 -07002290 if (needWake) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002291 mLooper->wake();
Jeff Brown46b9ac02010-04-22 18:58:52 -07002292 }
2293}
2294
Jeff Brownbe1aa822011-07-27 16:04:54 -07002295void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002296#if DEBUG_INBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00002297 ALOGD("notifyKey - eventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, action=0x%x, "
Jeff Brown46b9ac02010-04-22 18:58:52 -07002298 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%lld",
Jeff Brownbe1aa822011-07-27 16:04:54 -07002299 args->eventTime, args->deviceId, args->source, args->policyFlags,
2300 args->action, args->flags, args->keyCode, args->scanCode,
2301 args->metaState, args->downTime);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002302#endif
Jeff Brownbe1aa822011-07-27 16:04:54 -07002303 if (!validateKeyEvent(args->action)) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002304 return;
2305 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002306
Jeff Brownbe1aa822011-07-27 16:04:54 -07002307 uint32_t policyFlags = args->policyFlags;
2308 int32_t flags = args->flags;
2309 int32_t metaState = args->metaState;
Jeff Brown1f245102010-11-18 20:53:46 -08002310 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
2311 policyFlags |= POLICY_FLAG_VIRTUAL;
2312 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
2313 }
Jeff Brown924c4d42011-03-07 16:40:47 -08002314 if (policyFlags & POLICY_FLAG_ALT) {
2315 metaState |= AMETA_ALT_ON | AMETA_ALT_LEFT_ON;
2316 }
2317 if (policyFlags & POLICY_FLAG_ALT_GR) {
2318 metaState |= AMETA_ALT_ON | AMETA_ALT_RIGHT_ON;
2319 }
2320 if (policyFlags & POLICY_FLAG_SHIFT) {
2321 metaState |= AMETA_SHIFT_ON | AMETA_SHIFT_LEFT_ON;
2322 }
2323 if (policyFlags & POLICY_FLAG_CAPS_LOCK) {
2324 metaState |= AMETA_CAPS_LOCK_ON;
2325 }
2326 if (policyFlags & POLICY_FLAG_FUNCTION) {
2327 metaState |= AMETA_FUNCTION_ON;
2328 }
Jeff Brown1f245102010-11-18 20:53:46 -08002329
Jeff Browne20c9e02010-10-11 14:20:19 -07002330 policyFlags |= POLICY_FLAG_TRUSTED;
Jeff Brown1f245102010-11-18 20:53:46 -08002331
2332 KeyEvent event;
Jeff Brownbe1aa822011-07-27 16:04:54 -07002333 event.initialize(args->deviceId, args->source, args->action,
2334 flags, args->keyCode, args->scanCode, metaState, 0,
2335 args->downTime, args->eventTime);
Jeff Brown1f245102010-11-18 20:53:46 -08002336
2337 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
2338
2339 if (policyFlags & POLICY_FLAG_WOKE_HERE) {
2340 flags |= AKEY_EVENT_FLAG_WOKE_HERE;
2341 }
Jeff Brownb6997262010-10-08 22:31:17 -07002342
Jeff Brownb88102f2010-09-08 11:49:43 -07002343 bool needWake;
Jeff Brown46b9ac02010-04-22 18:58:52 -07002344 { // acquire lock
Jeff Brown0029c662011-03-30 02:25:18 -07002345 mLock.lock();
2346
2347 if (mInputFilterEnabled) {
2348 mLock.unlock();
2349
2350 policyFlags |= POLICY_FLAG_FILTERED;
2351 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2352 return; // event was consumed by the filter
2353 }
2354
2355 mLock.lock();
2356 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002357
Jeff Brown7fbdc842010-06-17 20:52:56 -07002358 int32_t repeatCount = 0;
Jeff Brownbe1aa822011-07-27 16:04:54 -07002359 KeyEntry* newEntry = new KeyEntry(args->eventTime,
2360 args->deviceId, args->source, policyFlags,
2361 args->action, flags, args->keyCode, args->scanCode,
2362 metaState, repeatCount, args->downTime);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002363
Jeff Brownb88102f2010-09-08 11:49:43 -07002364 needWake = enqueueInboundEventLocked(newEntry);
Jeff Brown0029c662011-03-30 02:25:18 -07002365 mLock.unlock();
Jeff Brown46b9ac02010-04-22 18:58:52 -07002366 } // release lock
2367
Jeff Brownb88102f2010-09-08 11:49:43 -07002368 if (needWake) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002369 mLooper->wake();
Jeff Brown46b9ac02010-04-22 18:58:52 -07002370 }
2371}
2372
Jeff Brownbe1aa822011-07-27 16:04:54 -07002373void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002374#if DEBUG_INBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00002375 ALOGD("notifyMotion - eventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, "
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002376 "action=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, edgeFlags=0x%x, "
Jeff Brown85a31762010-09-01 17:01:00 -07002377 "xPrecision=%f, yPrecision=%f, downTime=%lld",
Jeff Brownbe1aa822011-07-27 16:04:54 -07002378 args->eventTime, args->deviceId, args->source, args->policyFlags,
2379 args->action, args->flags, args->metaState, args->buttonState,
2380 args->edgeFlags, args->xPrecision, args->yPrecision, args->downTime);
2381 for (uint32_t i = 0; i < args->pointerCount; i++) {
Steve Block5baa3a62011-12-20 16:23:08 +00002382 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002383 "x=%f, y=%f, pressure=%f, size=%f, "
Jeff Brown85a31762010-09-01 17:01:00 -07002384 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
Jeff Brown8d608662010-08-30 03:02:23 -07002385 "orientation=%f",
Jeff Brownbe1aa822011-07-27 16:04:54 -07002386 i, args->pointerProperties[i].id,
2387 args->pointerProperties[i].toolType,
2388 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
2389 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
2390 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
2391 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
2392 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
2393 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
2394 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
2395 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
2396 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Jeff Brown46b9ac02010-04-22 18:58:52 -07002397 }
2398#endif
Jeff Brownbe1aa822011-07-27 16:04:54 -07002399 if (!validateMotionEvent(args->action, args->pointerCount, args->pointerProperties)) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002400 return;
2401 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002402
Jeff Brownbe1aa822011-07-27 16:04:54 -07002403 uint32_t policyFlags = args->policyFlags;
Jeff Browne20c9e02010-10-11 14:20:19 -07002404 policyFlags |= POLICY_FLAG_TRUSTED;
Jeff Brownbe1aa822011-07-27 16:04:54 -07002405 mPolicy->interceptMotionBeforeQueueing(args->eventTime, /*byref*/ policyFlags);
Jeff Brownb6997262010-10-08 22:31:17 -07002406
Jeff Brownb88102f2010-09-08 11:49:43 -07002407 bool needWake;
Jeff Brown46b9ac02010-04-22 18:58:52 -07002408 { // acquire lock
Jeff Brown0029c662011-03-30 02:25:18 -07002409 mLock.lock();
2410
2411 if (mInputFilterEnabled) {
2412 mLock.unlock();
2413
2414 MotionEvent event;
Jeff Brownbe1aa822011-07-27 16:04:54 -07002415 event.initialize(args->deviceId, args->source, args->action, args->flags,
2416 args->edgeFlags, args->metaState, args->buttonState, 0, 0,
2417 args->xPrecision, args->yPrecision,
2418 args->downTime, args->eventTime,
2419 args->pointerCount, args->pointerProperties, args->pointerCoords);
Jeff Brown0029c662011-03-30 02:25:18 -07002420
2421 policyFlags |= POLICY_FLAG_FILTERED;
2422 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2423 return; // event was consumed by the filter
2424 }
2425
2426 mLock.lock();
2427 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002428
Jeff Brown46b9ac02010-04-22 18:58:52 -07002429 // Just enqueue a new motion event.
Jeff Brownbe1aa822011-07-27 16:04:54 -07002430 MotionEntry* newEntry = new MotionEntry(args->eventTime,
2431 args->deviceId, args->source, policyFlags,
2432 args->action, args->flags, args->metaState, args->buttonState,
2433 args->edgeFlags, args->xPrecision, args->yPrecision, args->downTime,
2434 args->pointerCount, args->pointerProperties, args->pointerCoords);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002435
Jeff Brownb88102f2010-09-08 11:49:43 -07002436 needWake = enqueueInboundEventLocked(newEntry);
Jeff Brown0029c662011-03-30 02:25:18 -07002437 mLock.unlock();
Jeff Brown46b9ac02010-04-22 18:58:52 -07002438 } // release lock
2439
Jeff Brownb88102f2010-09-08 11:49:43 -07002440 if (needWake) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002441 mLooper->wake();
Jeff Brown46b9ac02010-04-22 18:58:52 -07002442 }
2443}
2444
Jeff Brownbe1aa822011-07-27 16:04:54 -07002445void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
Jeff Brownb6997262010-10-08 22:31:17 -07002446#if DEBUG_INBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00002447 ALOGD("notifySwitch - eventTime=%lld, policyFlags=0x%x, switchCode=%d, switchValue=%d",
Jeff Brownbe1aa822011-07-27 16:04:54 -07002448 args->eventTime, args->policyFlags,
2449 args->switchCode, args->switchValue);
Jeff Brownb6997262010-10-08 22:31:17 -07002450#endif
2451
Jeff Brownbe1aa822011-07-27 16:04:54 -07002452 uint32_t policyFlags = args->policyFlags;
Jeff Browne20c9e02010-10-11 14:20:19 -07002453 policyFlags |= POLICY_FLAG_TRUSTED;
Jeff Brownbe1aa822011-07-27 16:04:54 -07002454 mPolicy->notifySwitch(args->eventTime,
2455 args->switchCode, args->switchValue, policyFlags);
Jeff Brownb6997262010-10-08 22:31:17 -07002456}
2457
Jeff Brown65fd2512011-08-18 11:20:58 -07002458void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
2459#if DEBUG_INBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00002460 ALOGD("notifyDeviceReset - eventTime=%lld, deviceId=%d",
Jeff Brown65fd2512011-08-18 11:20:58 -07002461 args->eventTime, args->deviceId);
2462#endif
2463
2464 bool needWake;
2465 { // acquire lock
2466 AutoMutex _l(mLock);
2467
2468 DeviceResetEntry* newEntry = new DeviceResetEntry(args->eventTime, args->deviceId);
2469 needWake = enqueueInboundEventLocked(newEntry);
2470 } // release lock
2471
2472 if (needWake) {
2473 mLooper->wake();
2474 }
2475}
2476
Jeff Brown7fbdc842010-06-17 20:52:56 -07002477int32_t InputDispatcher::injectInputEvent(const InputEvent* event,
Jeff Brown0029c662011-03-30 02:25:18 -07002478 int32_t injectorPid, int32_t injectorUid, int32_t syncMode, int32_t timeoutMillis,
2479 uint32_t policyFlags) {
Jeff Brown7fbdc842010-06-17 20:52:56 -07002480#if DEBUG_INBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00002481 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Jeff Brown0029c662011-03-30 02:25:18 -07002482 "syncMode=%d, timeoutMillis=%d, policyFlags=0x%08x",
2483 event->getType(), injectorPid, injectorUid, syncMode, timeoutMillis, policyFlags);
Jeff Brown7fbdc842010-06-17 20:52:56 -07002484#endif
2485
2486 nsecs_t endTime = now() + milliseconds_to_nanoseconds(timeoutMillis);
Jeff Browne20c9e02010-10-11 14:20:19 -07002487
Jeff Brown0029c662011-03-30 02:25:18 -07002488 policyFlags |= POLICY_FLAG_INJECTED;
Jeff Browne20c9e02010-10-11 14:20:19 -07002489 if (hasInjectionPermission(injectorPid, injectorUid)) {
2490 policyFlags |= POLICY_FLAG_TRUSTED;
2491 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07002492
Jeff Brown3241b6b2012-02-03 15:08:02 -08002493 EventEntry* firstInjectedEntry;
2494 EventEntry* lastInjectedEntry;
Jeff Brownb6997262010-10-08 22:31:17 -07002495 switch (event->getType()) {
2496 case AINPUT_EVENT_TYPE_KEY: {
2497 const KeyEvent* keyEvent = static_cast<const KeyEvent*>(event);
2498 int32_t action = keyEvent->getAction();
2499 if (! validateKeyEvent(action)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07002500 return INPUT_EVENT_INJECTION_FAILED;
2501 }
2502
Jeff Brownb6997262010-10-08 22:31:17 -07002503 int32_t flags = keyEvent->getFlags();
Jeff Brown1f245102010-11-18 20:53:46 -08002504 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
2505 policyFlags |= POLICY_FLAG_VIRTUAL;
2506 }
2507
Jeff Brown0029c662011-03-30 02:25:18 -07002508 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
2509 mPolicy->interceptKeyBeforeQueueing(keyEvent, /*byref*/ policyFlags);
2510 }
Jeff Brown1f245102010-11-18 20:53:46 -08002511
2512 if (policyFlags & POLICY_FLAG_WOKE_HERE) {
2513 flags |= AKEY_EVENT_FLAG_WOKE_HERE;
2514 }
Jeff Brown6ec402b2010-07-28 15:48:59 -07002515
Jeff Brownb6997262010-10-08 22:31:17 -07002516 mLock.lock();
Jeff Brown3241b6b2012-02-03 15:08:02 -08002517 firstInjectedEntry = new KeyEntry(keyEvent->getEventTime(),
Jeff Brown1f245102010-11-18 20:53:46 -08002518 keyEvent->getDeviceId(), keyEvent->getSource(),
2519 policyFlags, action, flags,
2520 keyEvent->getKeyCode(), keyEvent->getScanCode(), keyEvent->getMetaState(),
Jeff Brownb6997262010-10-08 22:31:17 -07002521 keyEvent->getRepeatCount(), keyEvent->getDownTime());
Jeff Brown3241b6b2012-02-03 15:08:02 -08002522 lastInjectedEntry = firstInjectedEntry;
Jeff Brownb6997262010-10-08 22:31:17 -07002523 break;
2524 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07002525
Jeff Brownb6997262010-10-08 22:31:17 -07002526 case AINPUT_EVENT_TYPE_MOTION: {
2527 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
2528 int32_t action = motionEvent->getAction();
2529 size_t pointerCount = motionEvent->getPointerCount();
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002530 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
2531 if (! validateMotionEvent(action, pointerCount, pointerProperties)) {
Jeff Brownb6997262010-10-08 22:31:17 -07002532 return INPUT_EVENT_INJECTION_FAILED;
2533 }
2534
Jeff Brown0029c662011-03-30 02:25:18 -07002535 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
2536 nsecs_t eventTime = motionEvent->getEventTime();
2537 mPolicy->interceptMotionBeforeQueueing(eventTime, /*byref*/ policyFlags);
2538 }
Jeff Brownb6997262010-10-08 22:31:17 -07002539
2540 mLock.lock();
2541 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
2542 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
Jeff Brown3241b6b2012-02-03 15:08:02 -08002543 firstInjectedEntry = new MotionEntry(*sampleEventTimes,
Jeff Brownb6997262010-10-08 22:31:17 -07002544 motionEvent->getDeviceId(), motionEvent->getSource(), policyFlags,
2545 action, motionEvent->getFlags(),
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002546 motionEvent->getMetaState(), motionEvent->getButtonState(),
2547 motionEvent->getEdgeFlags(),
Jeff Brownb6997262010-10-08 22:31:17 -07002548 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
2549 motionEvent->getDownTime(), uint32_t(pointerCount),
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002550 pointerProperties, samplePointerCoords);
Jeff Brown3241b6b2012-02-03 15:08:02 -08002551 lastInjectedEntry = firstInjectedEntry;
Jeff Brownb6997262010-10-08 22:31:17 -07002552 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
2553 sampleEventTimes += 1;
2554 samplePointerCoords += pointerCount;
Jeff Brown3241b6b2012-02-03 15:08:02 -08002555 MotionEntry* nextInjectedEntry = new MotionEntry(*sampleEventTimes,
2556 motionEvent->getDeviceId(), motionEvent->getSource(), policyFlags,
2557 action, motionEvent->getFlags(),
2558 motionEvent->getMetaState(), motionEvent->getButtonState(),
2559 motionEvent->getEdgeFlags(),
2560 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
2561 motionEvent->getDownTime(), uint32_t(pointerCount),
2562 pointerProperties, samplePointerCoords);
2563 lastInjectedEntry->next = nextInjectedEntry;
2564 lastInjectedEntry = nextInjectedEntry;
Jeff Brownb6997262010-10-08 22:31:17 -07002565 }
Jeff Brownb6997262010-10-08 22:31:17 -07002566 break;
2567 }
2568
2569 default:
Steve Block8564c8d2012-01-05 23:22:43 +00002570 ALOGW("Cannot inject event of type %d", event->getType());
Jeff Brownb6997262010-10-08 22:31:17 -07002571 return INPUT_EVENT_INJECTION_FAILED;
2572 }
2573
Jeff Brownac386072011-07-20 15:19:50 -07002574 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
Jeff Brownb6997262010-10-08 22:31:17 -07002575 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
2576 injectionState->injectionIsAsync = true;
2577 }
2578
2579 injectionState->refCount += 1;
Jeff Brown3241b6b2012-02-03 15:08:02 -08002580 lastInjectedEntry->injectionState = injectionState;
Jeff Brownb6997262010-10-08 22:31:17 -07002581
Jeff Brown3241b6b2012-02-03 15:08:02 -08002582 bool needWake = false;
2583 for (EventEntry* entry = firstInjectedEntry; entry != NULL; ) {
2584 EventEntry* nextEntry = entry->next;
2585 needWake |= enqueueInboundEventLocked(entry);
2586 entry = nextEntry;
2587 }
2588
Jeff Brownb6997262010-10-08 22:31:17 -07002589 mLock.unlock();
Jeff Brown7fbdc842010-06-17 20:52:56 -07002590
Jeff Brownb88102f2010-09-08 11:49:43 -07002591 if (needWake) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002592 mLooper->wake();
Jeff Brown7fbdc842010-06-17 20:52:56 -07002593 }
2594
2595 int32_t injectionResult;
2596 { // acquire lock
2597 AutoMutex _l(mLock);
2598
Jeff Brown6ec402b2010-07-28 15:48:59 -07002599 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
2600 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
2601 } else {
2602 for (;;) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002603 injectionResult = injectionState->injectionResult;
Jeff Brown6ec402b2010-07-28 15:48:59 -07002604 if (injectionResult != INPUT_EVENT_INJECTION_PENDING) {
2605 break;
2606 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07002607
Jeff Brown7fbdc842010-06-17 20:52:56 -07002608 nsecs_t remainingTimeout = endTime - now();
2609 if (remainingTimeout <= 0) {
Jeff Brown6ec402b2010-07-28 15:48:59 -07002610#if DEBUG_INJECTION
Steve Block5baa3a62011-12-20 16:23:08 +00002611 ALOGD("injectInputEvent - Timed out waiting for injection result "
Jeff Brown6ec402b2010-07-28 15:48:59 -07002612 "to become available.");
2613#endif
Jeff Brown7fbdc842010-06-17 20:52:56 -07002614 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
2615 break;
2616 }
2617
Jeff Brown6ec402b2010-07-28 15:48:59 -07002618 mInjectionResultAvailableCondition.waitRelative(mLock, remainingTimeout);
2619 }
2620
2621 if (injectionResult == INPUT_EVENT_INJECTION_SUCCEEDED
2622 && syncMode == INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002623 while (injectionState->pendingForegroundDispatches != 0) {
Jeff Brown6ec402b2010-07-28 15:48:59 -07002624#if DEBUG_INJECTION
Steve Block5baa3a62011-12-20 16:23:08 +00002625 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
Jeff Brown01ce2e92010-09-26 22:20:12 -07002626 injectionState->pendingForegroundDispatches);
Jeff Brown6ec402b2010-07-28 15:48:59 -07002627#endif
2628 nsecs_t remainingTimeout = endTime - now();
2629 if (remainingTimeout <= 0) {
2630#if DEBUG_INJECTION
Steve Block5baa3a62011-12-20 16:23:08 +00002631 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
Jeff Brown6ec402b2010-07-28 15:48:59 -07002632 "dispatches to finish.");
2633#endif
2634 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
2635 break;
2636 }
2637
2638 mInjectionSyncFinishedCondition.waitRelative(mLock, remainingTimeout);
2639 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07002640 }
2641 }
2642
Jeff Brownac386072011-07-20 15:19:50 -07002643 injectionState->release();
Jeff Brown7fbdc842010-06-17 20:52:56 -07002644 } // release lock
2645
Jeff Brown6ec402b2010-07-28 15:48:59 -07002646#if DEBUG_INJECTION
Steve Block5baa3a62011-12-20 16:23:08 +00002647 ALOGD("injectInputEvent - Finished with result %d. "
Jeff Brown6ec402b2010-07-28 15:48:59 -07002648 "injectorPid=%d, injectorUid=%d",
2649 injectionResult, injectorPid, injectorUid);
2650#endif
2651
Jeff Brown7fbdc842010-06-17 20:52:56 -07002652 return injectionResult;
2653}
2654
Jeff Brownb6997262010-10-08 22:31:17 -07002655bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
2656 return injectorUid == 0
2657 || mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
2658}
2659
Jeff Brown7fbdc842010-06-17 20:52:56 -07002660void InputDispatcher::setInjectionResultLocked(EventEntry* entry, int32_t injectionResult) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002661 InjectionState* injectionState = entry->injectionState;
2662 if (injectionState) {
Jeff Brown7fbdc842010-06-17 20:52:56 -07002663#if DEBUG_INJECTION
Steve Block5baa3a62011-12-20 16:23:08 +00002664 ALOGD("Setting input event injection result to %d. "
Jeff Brown7fbdc842010-06-17 20:52:56 -07002665 "injectorPid=%d, injectorUid=%d",
Jeff Brown01ce2e92010-09-26 22:20:12 -07002666 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
Jeff Brown7fbdc842010-06-17 20:52:56 -07002667#endif
2668
Jeff Brown0029c662011-03-30 02:25:18 -07002669 if (injectionState->injectionIsAsync
2670 && !(entry->policyFlags & POLICY_FLAG_FILTERED)) {
Jeff Brown6ec402b2010-07-28 15:48:59 -07002671 // Log the outcome since the injector did not wait for the injection result.
2672 switch (injectionResult) {
2673 case INPUT_EVENT_INJECTION_SUCCEEDED:
Steve Block71f2cf12011-10-20 11:56:00 +01002674 ALOGV("Asynchronous input event injection succeeded.");
Jeff Brown6ec402b2010-07-28 15:48:59 -07002675 break;
2676 case INPUT_EVENT_INJECTION_FAILED:
Steve Block8564c8d2012-01-05 23:22:43 +00002677 ALOGW("Asynchronous input event injection failed.");
Jeff Brown6ec402b2010-07-28 15:48:59 -07002678 break;
2679 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
Steve Block8564c8d2012-01-05 23:22:43 +00002680 ALOGW("Asynchronous input event injection permission denied.");
Jeff Brown6ec402b2010-07-28 15:48:59 -07002681 break;
2682 case INPUT_EVENT_INJECTION_TIMED_OUT:
Steve Block8564c8d2012-01-05 23:22:43 +00002683 ALOGW("Asynchronous input event injection timed out.");
Jeff Brown6ec402b2010-07-28 15:48:59 -07002684 break;
2685 }
2686 }
2687
Jeff Brown01ce2e92010-09-26 22:20:12 -07002688 injectionState->injectionResult = injectionResult;
Jeff Brown7fbdc842010-06-17 20:52:56 -07002689 mInjectionResultAvailableCondition.broadcast();
2690 }
2691}
2692
Jeff Brown01ce2e92010-09-26 22:20:12 -07002693void InputDispatcher::incrementPendingForegroundDispatchesLocked(EventEntry* entry) {
2694 InjectionState* injectionState = entry->injectionState;
2695 if (injectionState) {
2696 injectionState->pendingForegroundDispatches += 1;
2697 }
2698}
2699
Jeff Brown519e0242010-09-15 15:18:56 -07002700void InputDispatcher::decrementPendingForegroundDispatchesLocked(EventEntry* entry) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002701 InjectionState* injectionState = entry->injectionState;
2702 if (injectionState) {
2703 injectionState->pendingForegroundDispatches -= 1;
Jeff Brown6ec402b2010-07-28 15:48:59 -07002704
Jeff Brown01ce2e92010-09-26 22:20:12 -07002705 if (injectionState->pendingForegroundDispatches == 0) {
2706 mInjectionSyncFinishedCondition.broadcast();
2707 }
Jeff Brownb88102f2010-09-08 11:49:43 -07002708 }
2709}
2710
Jeff Brown9302c872011-07-13 22:51:29 -07002711sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
2712 const sp<InputChannel>& inputChannel) const {
2713 size_t numWindows = mWindowHandles.size();
2714 for (size_t i = 0; i < numWindows; i++) {
2715 const sp<InputWindowHandle>& windowHandle = mWindowHandles.itemAt(i);
Jeff Browncc4f7db2011-08-30 20:34:48 -07002716 if (windowHandle->getInputChannel() == inputChannel) {
Jeff Brown9302c872011-07-13 22:51:29 -07002717 return windowHandle;
Jeff Brown01ce2e92010-09-26 22:20:12 -07002718 }
2719 }
2720 return NULL;
2721}
2722
Jeff Brown9302c872011-07-13 22:51:29 -07002723bool InputDispatcher::hasWindowHandleLocked(
2724 const sp<InputWindowHandle>& windowHandle) const {
2725 size_t numWindows = mWindowHandles.size();
2726 for (size_t i = 0; i < numWindows; i++) {
2727 if (mWindowHandles.itemAt(i) == windowHandle) {
2728 return true;
2729 }
2730 }
2731 return false;
2732}
2733
2734void InputDispatcher::setInputWindows(const Vector<sp<InputWindowHandle> >& inputWindowHandles) {
Jeff Brownb88102f2010-09-08 11:49:43 -07002735#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002736 ALOGD("setInputWindows");
Jeff Brownb88102f2010-09-08 11:49:43 -07002737#endif
2738 { // acquire lock
2739 AutoMutex _l(mLock);
2740
Jeff Browncc4f7db2011-08-30 20:34:48 -07002741 Vector<sp<InputWindowHandle> > oldWindowHandles = mWindowHandles;
Jeff Brown9302c872011-07-13 22:51:29 -07002742 mWindowHandles = inputWindowHandles;
Jeff Brownb6997262010-10-08 22:31:17 -07002743
Jeff Brown9302c872011-07-13 22:51:29 -07002744 sp<InputWindowHandle> newFocusedWindowHandle;
2745 bool foundHoveredWindow = false;
2746 for (size_t i = 0; i < mWindowHandles.size(); i++) {
2747 const sp<InputWindowHandle>& windowHandle = mWindowHandles.itemAt(i);
Jeff Browncc4f7db2011-08-30 20:34:48 -07002748 if (!windowHandle->updateInfo() || windowHandle->getInputChannel() == NULL) {
Jeff Brown9302c872011-07-13 22:51:29 -07002749 mWindowHandles.removeAt(i--);
2750 continue;
2751 }
Jeff Browncc4f7db2011-08-30 20:34:48 -07002752 if (windowHandle->getInfo()->hasFocus) {
Jeff Brown9302c872011-07-13 22:51:29 -07002753 newFocusedWindowHandle = windowHandle;
2754 }
2755 if (windowHandle == mLastHoverWindowHandle) {
2756 foundHoveredWindow = true;
Jeff Brownb88102f2010-09-08 11:49:43 -07002757 }
2758 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07002759
Jeff Brown9302c872011-07-13 22:51:29 -07002760 if (!foundHoveredWindow) {
2761 mLastHoverWindowHandle = NULL;
2762 }
2763
2764 if (mFocusedWindowHandle != newFocusedWindowHandle) {
2765 if (mFocusedWindowHandle != NULL) {
Jeff Brownb6997262010-10-08 22:31:17 -07002766#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002767 ALOGD("Focus left window: %s",
Jeff Browncc4f7db2011-08-30 20:34:48 -07002768 mFocusedWindowHandle->getName().string());
Jeff Brownb6997262010-10-08 22:31:17 -07002769#endif
Jeff Browncc4f7db2011-08-30 20:34:48 -07002770 sp<InputChannel> focusedInputChannel = mFocusedWindowHandle->getInputChannel();
2771 if (focusedInputChannel != NULL) {
Christopher Tated9be36c2011-08-16 16:09:33 -07002772 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
2773 "focus left window");
2774 synthesizeCancelationEventsForInputChannelLocked(
Jeff Browncc4f7db2011-08-30 20:34:48 -07002775 focusedInputChannel, options);
Christopher Tated9be36c2011-08-16 16:09:33 -07002776 }
Jeff Brownb6997262010-10-08 22:31:17 -07002777 }
Jeff Brown9302c872011-07-13 22:51:29 -07002778 if (newFocusedWindowHandle != NULL) {
Jeff Brownb6997262010-10-08 22:31:17 -07002779#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002780 ALOGD("Focus entered window: %s",
Jeff Browncc4f7db2011-08-30 20:34:48 -07002781 newFocusedWindowHandle->getName().string());
Jeff Brownb6997262010-10-08 22:31:17 -07002782#endif
Jeff Brown9302c872011-07-13 22:51:29 -07002783 }
2784 mFocusedWindowHandle = newFocusedWindowHandle;
Jeff Brownb6997262010-10-08 22:31:17 -07002785 }
2786
Jeff Brown9302c872011-07-13 22:51:29 -07002787 for (size_t i = 0; i < mTouchState.windows.size(); i++) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002788 TouchedWindow& touchedWindow = mTouchState.windows.editItemAt(i);
Jeff Brown9302c872011-07-13 22:51:29 -07002789 if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
Jeff Brownb6997262010-10-08 22:31:17 -07002790#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002791 ALOGD("Touched window was removed: %s",
Jeff Browncc4f7db2011-08-30 20:34:48 -07002792 touchedWindow.windowHandle->getName().string());
Jeff Brownb6997262010-10-08 22:31:17 -07002793#endif
Jeff Browncc4f7db2011-08-30 20:34:48 -07002794 sp<InputChannel> touchedInputChannel =
2795 touchedWindow.windowHandle->getInputChannel();
2796 if (touchedInputChannel != NULL) {
Christopher Tated9be36c2011-08-16 16:09:33 -07002797 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
2798 "touched window was removed");
2799 synthesizeCancelationEventsForInputChannelLocked(
Jeff Browncc4f7db2011-08-30 20:34:48 -07002800 touchedInputChannel, options);
Christopher Tated9be36c2011-08-16 16:09:33 -07002801 }
Jeff Brown9302c872011-07-13 22:51:29 -07002802 mTouchState.windows.removeAt(i--);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002803 }
2804 }
Jeff Browncc4f7db2011-08-30 20:34:48 -07002805
2806 // Release information for windows that are no longer present.
2807 // This ensures that unused input channels are released promptly.
2808 // Otherwise, they might stick around until the window handle is destroyed
2809 // which might not happen until the next GC.
2810 for (size_t i = 0; i < oldWindowHandles.size(); i++) {
2811 const sp<InputWindowHandle>& oldWindowHandle = oldWindowHandles.itemAt(i);
2812 if (!hasWindowHandleLocked(oldWindowHandle)) {
2813#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002814 ALOGD("Window went away: %s", oldWindowHandle->getName().string());
Jeff Browncc4f7db2011-08-30 20:34:48 -07002815#endif
2816 oldWindowHandle->releaseInfo();
2817 }
2818 }
Jeff Brownb88102f2010-09-08 11:49:43 -07002819 } // release lock
2820
2821 // Wake up poll loop since it may need to make new input dispatching choices.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002822 mLooper->wake();
Jeff Brownb88102f2010-09-08 11:49:43 -07002823}
2824
Jeff Brown9302c872011-07-13 22:51:29 -07002825void InputDispatcher::setFocusedApplication(
2826 const sp<InputApplicationHandle>& inputApplicationHandle) {
Jeff Brownb88102f2010-09-08 11:49:43 -07002827#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002828 ALOGD("setFocusedApplication");
Jeff Brownb88102f2010-09-08 11:49:43 -07002829#endif
2830 { // acquire lock
2831 AutoMutex _l(mLock);
2832
Jeff Browncc4f7db2011-08-30 20:34:48 -07002833 if (inputApplicationHandle != NULL && inputApplicationHandle->updateInfo()) {
Jeff Brown5ea29ab2011-07-27 11:50:51 -07002834 if (mFocusedApplicationHandle != inputApplicationHandle) {
2835 if (mFocusedApplicationHandle != NULL) {
Jeff Browne9bb9be2012-02-06 15:47:55 -08002836 resetANRTimeoutsLocked();
Jeff Browncc4f7db2011-08-30 20:34:48 -07002837 mFocusedApplicationHandle->releaseInfo();
Jeff Brown5ea29ab2011-07-27 11:50:51 -07002838 }
2839 mFocusedApplicationHandle = inputApplicationHandle;
2840 }
2841 } else if (mFocusedApplicationHandle != NULL) {
Jeff Browne9bb9be2012-02-06 15:47:55 -08002842 resetANRTimeoutsLocked();
Jeff Browncc4f7db2011-08-30 20:34:48 -07002843 mFocusedApplicationHandle->releaseInfo();
Jeff Brown9302c872011-07-13 22:51:29 -07002844 mFocusedApplicationHandle.clear();
Jeff Brownb88102f2010-09-08 11:49:43 -07002845 }
2846
2847#if DEBUG_FOCUS
Jeff Brownb6997262010-10-08 22:31:17 -07002848 //logDispatchStateLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -07002849#endif
2850 } // release lock
2851
2852 // Wake up poll loop since it may need to make new input dispatching choices.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002853 mLooper->wake();
Jeff Brownb88102f2010-09-08 11:49:43 -07002854}
2855
Jeff Brownb88102f2010-09-08 11:49:43 -07002856void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
2857#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002858 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
Jeff Brownb88102f2010-09-08 11:49:43 -07002859#endif
2860
2861 bool changed;
2862 { // acquire lock
2863 AutoMutex _l(mLock);
2864
2865 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
Jeff Brown120a4592010-10-27 18:43:51 -07002866 if (mDispatchFrozen && !frozen) {
Jeff Brownb88102f2010-09-08 11:49:43 -07002867 resetANRTimeoutsLocked();
2868 }
2869
Jeff Brown120a4592010-10-27 18:43:51 -07002870 if (mDispatchEnabled && !enabled) {
2871 resetAndDropEverythingLocked("dispatcher is being disabled");
2872 }
2873
Jeff Brownb88102f2010-09-08 11:49:43 -07002874 mDispatchEnabled = enabled;
2875 mDispatchFrozen = frozen;
2876 changed = true;
2877 } else {
2878 changed = false;
2879 }
2880
2881#if DEBUG_FOCUS
Jeff Brownb6997262010-10-08 22:31:17 -07002882 //logDispatchStateLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -07002883#endif
2884 } // release lock
2885
2886 if (changed) {
2887 // Wake up poll loop since it may need to make new input dispatching choices.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002888 mLooper->wake();
Jeff Brown46b9ac02010-04-22 18:58:52 -07002889 }
2890}
2891
Jeff Brown0029c662011-03-30 02:25:18 -07002892void InputDispatcher::setInputFilterEnabled(bool enabled) {
2893#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002894 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
Jeff Brown0029c662011-03-30 02:25:18 -07002895#endif
2896
2897 { // acquire lock
2898 AutoMutex _l(mLock);
2899
2900 if (mInputFilterEnabled == enabled) {
2901 return;
2902 }
2903
2904 mInputFilterEnabled = enabled;
2905 resetAndDropEverythingLocked("input filter is being enabled or disabled");
2906 } // release lock
2907
2908 // Wake up poll loop since there might be work to do to drop everything.
2909 mLooper->wake();
2910}
2911
Jeff Browne6504122010-09-27 14:52:15 -07002912bool InputDispatcher::transferTouchFocus(const sp<InputChannel>& fromChannel,
2913 const sp<InputChannel>& toChannel) {
2914#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002915 ALOGD("transferTouchFocus: fromChannel=%s, toChannel=%s",
Jeff Browne6504122010-09-27 14:52:15 -07002916 fromChannel->getName().string(), toChannel->getName().string());
2917#endif
2918 { // acquire lock
2919 AutoMutex _l(mLock);
2920
Jeff Brown9302c872011-07-13 22:51:29 -07002921 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromChannel);
2922 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toChannel);
2923 if (fromWindowHandle == NULL || toWindowHandle == NULL) {
Jeff Browne6504122010-09-27 14:52:15 -07002924#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002925 ALOGD("Cannot transfer focus because from or to window not found.");
Jeff Browne6504122010-09-27 14:52:15 -07002926#endif
2927 return false;
2928 }
Jeff Brown9302c872011-07-13 22:51:29 -07002929 if (fromWindowHandle == toWindowHandle) {
Jeff Browne6504122010-09-27 14:52:15 -07002930#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002931 ALOGD("Trivial transfer to same window.");
Jeff Browne6504122010-09-27 14:52:15 -07002932#endif
2933 return true;
2934 }
2935
2936 bool found = false;
2937 for (size_t i = 0; i < mTouchState.windows.size(); i++) {
2938 const TouchedWindow& touchedWindow = mTouchState.windows[i];
Jeff Brown9302c872011-07-13 22:51:29 -07002939 if (touchedWindow.windowHandle == fromWindowHandle) {
Jeff Browne6504122010-09-27 14:52:15 -07002940 int32_t oldTargetFlags = touchedWindow.targetFlags;
2941 BitSet32 pointerIds = touchedWindow.pointerIds;
2942
2943 mTouchState.windows.removeAt(i);
2944
Jeff Brown46e75292010-11-10 16:53:45 -08002945 int32_t newTargetFlags = oldTargetFlags
Jeff Browna032cc02011-03-07 16:56:21 -08002946 & (InputTarget::FLAG_FOREGROUND
2947 | InputTarget::FLAG_SPLIT | InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brown9302c872011-07-13 22:51:29 -07002948 mTouchState.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Jeff Browne6504122010-09-27 14:52:15 -07002949
2950 found = true;
2951 break;
2952 }
2953 }
2954
2955 if (! found) {
2956#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002957 ALOGD("Focus transfer failed because from window did not have focus.");
Jeff Browne6504122010-09-27 14:52:15 -07002958#endif
2959 return false;
2960 }
2961
Jeff Brown9c9f1a32010-10-11 18:32:20 -07002962 ssize_t fromConnectionIndex = getConnectionIndexLocked(fromChannel);
2963 ssize_t toConnectionIndex = getConnectionIndexLocked(toChannel);
2964 if (fromConnectionIndex >= 0 && toConnectionIndex >= 0) {
Jeff Browncbee6d62012-02-03 20:11:27 -08002965 sp<Connection> fromConnection = mConnectionsByFd.valueAt(fromConnectionIndex);
2966 sp<Connection> toConnection = mConnectionsByFd.valueAt(toConnectionIndex);
Jeff Brown9c9f1a32010-10-11 18:32:20 -07002967
2968 fromConnection->inputState.copyPointerStateTo(toConnection->inputState);
Jeff Brownda3d5a92011-03-29 15:11:34 -07002969 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Jeff Brown9c9f1a32010-10-11 18:32:20 -07002970 "transferring touch focus from this window to another window");
Jeff Brownda3d5a92011-03-29 15:11:34 -07002971 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Jeff Brown9c9f1a32010-10-11 18:32:20 -07002972 }
2973
Jeff Browne6504122010-09-27 14:52:15 -07002974#if DEBUG_FOCUS
2975 logDispatchStateLocked();
2976#endif
2977 } // release lock
2978
2979 // Wake up poll loop since it may need to make new input dispatching choices.
2980 mLooper->wake();
2981 return true;
2982}
2983
Jeff Brown120a4592010-10-27 18:43:51 -07002984void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
2985#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002986 ALOGD("Resetting and dropping all events (%s).", reason);
Jeff Brown120a4592010-10-27 18:43:51 -07002987#endif
2988
Jeff Brownda3d5a92011-03-29 15:11:34 -07002989 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
2990 synthesizeCancelationEventsForAllConnectionsLocked(options);
Jeff Brown120a4592010-10-27 18:43:51 -07002991
2992 resetKeyRepeatLocked();
2993 releasePendingEventLocked();
2994 drainInboundQueueLocked();
Jeff Browne9bb9be2012-02-06 15:47:55 -08002995 resetANRTimeoutsLocked();
Jeff Brown120a4592010-10-27 18:43:51 -07002996
2997 mTouchState.reset();
Jeff Brown9302c872011-07-13 22:51:29 -07002998 mLastHoverWindowHandle.clear();
Jeff Brown120a4592010-10-27 18:43:51 -07002999}
3000
Jeff Brownb88102f2010-09-08 11:49:43 -07003001void InputDispatcher::logDispatchStateLocked() {
3002 String8 dump;
3003 dumpDispatchStateLocked(dump);
Jeff Brown2a95c2a2010-09-16 12:31:46 -07003004
3005 char* text = dump.lockBuffer(dump.size());
3006 char* start = text;
3007 while (*start != '\0') {
3008 char* end = strchr(start, '\n');
3009 if (*end == '\n') {
3010 *(end++) = '\0';
3011 }
Steve Block5baa3a62011-12-20 16:23:08 +00003012 ALOGD("%s", start);
Jeff Brown2a95c2a2010-09-16 12:31:46 -07003013 start = end;
3014 }
Jeff Brownb88102f2010-09-08 11:49:43 -07003015}
3016
3017void InputDispatcher::dumpDispatchStateLocked(String8& dump) {
Jeff Brownf2f487182010-10-01 17:46:21 -07003018 dump.appendFormat(INDENT "DispatchEnabled: %d\n", mDispatchEnabled);
3019 dump.appendFormat(INDENT "DispatchFrozen: %d\n", mDispatchFrozen);
Jeff Brownb88102f2010-09-08 11:49:43 -07003020
Jeff Brown9302c872011-07-13 22:51:29 -07003021 if (mFocusedApplicationHandle != NULL) {
Jeff Brownf2f487182010-10-01 17:46:21 -07003022 dump.appendFormat(INDENT "FocusedApplication: name='%s', dispatchingTimeout=%0.3fms\n",
Jeff Browncc4f7db2011-08-30 20:34:48 -07003023 mFocusedApplicationHandle->getName().string(),
3024 mFocusedApplicationHandle->getDispatchingTimeout(
3025 DEFAULT_INPUT_DISPATCHING_TIMEOUT) / 1000000.0);
Jeff Brownb88102f2010-09-08 11:49:43 -07003026 } else {
Jeff Brownf2f487182010-10-01 17:46:21 -07003027 dump.append(INDENT "FocusedApplication: <null>\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003028 }
Jeff Brownf2f487182010-10-01 17:46:21 -07003029 dump.appendFormat(INDENT "FocusedWindow: name='%s'\n",
Jeff Browncc4f7db2011-08-30 20:34:48 -07003030 mFocusedWindowHandle != NULL ? mFocusedWindowHandle->getName().string() : "<null>");
Jeff Brownf2f487182010-10-01 17:46:21 -07003031
3032 dump.appendFormat(INDENT "TouchDown: %s\n", toString(mTouchState.down));
3033 dump.appendFormat(INDENT "TouchSplit: %s\n", toString(mTouchState.split));
Jeff Brown95712852011-01-04 19:41:59 -08003034 dump.appendFormat(INDENT "TouchDeviceId: %d\n", mTouchState.deviceId);
Jeff Brown58a2da82011-01-25 16:02:22 -08003035 dump.appendFormat(INDENT "TouchSource: 0x%08x\n", mTouchState.source);
Jeff Brownf2f487182010-10-01 17:46:21 -07003036 if (!mTouchState.windows.isEmpty()) {
3037 dump.append(INDENT "TouchedWindows:\n");
3038 for (size_t i = 0; i < mTouchState.windows.size(); i++) {
3039 const TouchedWindow& touchedWindow = mTouchState.windows[i];
3040 dump.appendFormat(INDENT2 "%d: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
Jeff Browncc4f7db2011-08-30 20:34:48 -07003041 i, touchedWindow.windowHandle->getName().string(),
3042 touchedWindow.pointerIds.value,
Jeff Brownf2f487182010-10-01 17:46:21 -07003043 touchedWindow.targetFlags);
3044 }
3045 } else {
3046 dump.append(INDENT "TouchedWindows: <none>\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003047 }
3048
Jeff Brown9302c872011-07-13 22:51:29 -07003049 if (!mWindowHandles.isEmpty()) {
Jeff Brownf2f487182010-10-01 17:46:21 -07003050 dump.append(INDENT "Windows:\n");
Jeff Brown9302c872011-07-13 22:51:29 -07003051 for (size_t i = 0; i < mWindowHandles.size(); i++) {
3052 const sp<InputWindowHandle>& windowHandle = mWindowHandles.itemAt(i);
Jeff Browncc4f7db2011-08-30 20:34:48 -07003053 const InputWindowInfo* windowInfo = windowHandle->getInfo();
3054
Jeff Brownf2f487182010-10-01 17:46:21 -07003055 dump.appendFormat(INDENT2 "%d: name='%s', paused=%s, hasFocus=%s, hasWallpaper=%s, "
3056 "visible=%s, canReceiveKeys=%s, flags=0x%08x, type=0x%08x, layer=%d, "
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003057 "frame=[%d,%d][%d,%d], scale=%f, "
Jeff Brownfbf09772011-01-16 14:06:57 -08003058 "touchableRegion=",
Jeff Browncc4f7db2011-08-30 20:34:48 -07003059 i, windowInfo->name.string(),
3060 toString(windowInfo->paused),
3061 toString(windowInfo->hasFocus),
3062 toString(windowInfo->hasWallpaper),
3063 toString(windowInfo->visible),
3064 toString(windowInfo->canReceiveKeys),
3065 windowInfo->layoutParamsFlags, windowInfo->layoutParamsType,
3066 windowInfo->layer,
3067 windowInfo->frameLeft, windowInfo->frameTop,
3068 windowInfo->frameRight, windowInfo->frameBottom,
3069 windowInfo->scaleFactor);
3070 dumpRegion(dump, windowInfo->touchableRegion);
3071 dump.appendFormat(", inputFeatures=0x%08x", windowInfo->inputFeatures);
Jeff Brownfbf09772011-01-16 14:06:57 -08003072 dump.appendFormat(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%0.3fms\n",
Jeff Browncc4f7db2011-08-30 20:34:48 -07003073 windowInfo->ownerPid, windowInfo->ownerUid,
3074 windowInfo->dispatchingTimeout / 1000000.0);
Jeff Brownf2f487182010-10-01 17:46:21 -07003075 }
3076 } else {
3077 dump.append(INDENT "Windows: <none>\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003078 }
3079
Jeff Brownf2f487182010-10-01 17:46:21 -07003080 if (!mMonitoringChannels.isEmpty()) {
3081 dump.append(INDENT "MonitoringChannels:\n");
3082 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
3083 const sp<InputChannel>& channel = mMonitoringChannels[i];
3084 dump.appendFormat(INDENT2 "%d: '%s'\n", i, channel->getName().string());
3085 }
3086 } else {
3087 dump.append(INDENT "MonitoringChannels: <none>\n");
3088 }
Jeff Brown519e0242010-09-15 15:18:56 -07003089
Jeff Brownf2f487182010-10-01 17:46:21 -07003090 dump.appendFormat(INDENT "InboundQueue: length=%u\n", mInboundQueue.count());
3091
Jeff Brownb88102f2010-09-08 11:49:43 -07003092 if (isAppSwitchPendingLocked()) {
Jeff Brownf2f487182010-10-01 17:46:21 -07003093 dump.appendFormat(INDENT "AppSwitch: pending, due in %01.1fms\n",
Jeff Brownb88102f2010-09-08 11:49:43 -07003094 (mAppSwitchDueTime - now()) / 1000000.0);
3095 } else {
Jeff Brownf2f487182010-10-01 17:46:21 -07003096 dump.append(INDENT "AppSwitch: not pending\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003097 }
3098}
3099
Jeff Brown928e0542011-01-10 11:17:36 -08003100status_t InputDispatcher::registerInputChannel(const sp<InputChannel>& inputChannel,
3101 const sp<InputWindowHandle>& inputWindowHandle, bool monitor) {
Jeff Brown9c3cda02010-06-15 01:31:58 -07003102#if DEBUG_REGISTRATION
Steve Block5baa3a62011-12-20 16:23:08 +00003103 ALOGD("channel '%s' ~ registerInputChannel - monitor=%s", inputChannel->getName().string(),
Jeff Brownb88102f2010-09-08 11:49:43 -07003104 toString(monitor));
Jeff Brown9c3cda02010-06-15 01:31:58 -07003105#endif
3106
Jeff Brown46b9ac02010-04-22 18:58:52 -07003107 { // acquire lock
3108 AutoMutex _l(mLock);
3109
Jeff Brown519e0242010-09-15 15:18:56 -07003110 if (getConnectionIndexLocked(inputChannel) >= 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00003111 ALOGW("Attempted to register already registered input channel '%s'",
Jeff Brown46b9ac02010-04-22 18:58:52 -07003112 inputChannel->getName().string());
3113 return BAD_VALUE;
3114 }
3115
Jeff Browncc4f7db2011-08-30 20:34:48 -07003116 sp<Connection> connection = new Connection(inputChannel, inputWindowHandle, monitor);
Jeff Brown46b9ac02010-04-22 18:58:52 -07003117
Jeff Brown91e32892012-02-14 15:56:29 -08003118 int fd = inputChannel->getFd();
Jeff Browncbee6d62012-02-03 20:11:27 -08003119 mConnectionsByFd.add(fd, connection);
Jeff Brown9c3cda02010-06-15 01:31:58 -07003120
Jeff Brownb88102f2010-09-08 11:49:43 -07003121 if (monitor) {
3122 mMonitoringChannels.push(inputChannel);
3123 }
3124
Jeff Browncbee6d62012-02-03 20:11:27 -08003125 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
Jeff Brown2cbecea2010-08-17 15:59:26 -07003126
Jeff Brown9c3cda02010-06-15 01:31:58 -07003127 runCommandsLockedInterruptible();
Jeff Brown46b9ac02010-04-22 18:58:52 -07003128 } // release lock
Jeff Brown46b9ac02010-04-22 18:58:52 -07003129 return OK;
3130}
3131
3132status_t InputDispatcher::unregisterInputChannel(const sp<InputChannel>& inputChannel) {
Jeff Brown9c3cda02010-06-15 01:31:58 -07003133#if DEBUG_REGISTRATION
Steve Block5baa3a62011-12-20 16:23:08 +00003134 ALOGD("channel '%s' ~ unregisterInputChannel", inputChannel->getName().string());
Jeff Brown9c3cda02010-06-15 01:31:58 -07003135#endif
3136
Jeff Brown46b9ac02010-04-22 18:58:52 -07003137 { // acquire lock
3138 AutoMutex _l(mLock);
3139
Jeff Browncc4f7db2011-08-30 20:34:48 -07003140 status_t status = unregisterInputChannelLocked(inputChannel, false /*notify*/);
3141 if (status) {
3142 return status;
Jeff Brown46b9ac02010-04-22 18:58:52 -07003143 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07003144 } // release lock
3145
Jeff Brown46b9ac02010-04-22 18:58:52 -07003146 // Wake the poll loop because removing the connection may have changed the current
3147 // synchronization state.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07003148 mLooper->wake();
Jeff Brown46b9ac02010-04-22 18:58:52 -07003149 return OK;
3150}
3151
Jeff Browncc4f7db2011-08-30 20:34:48 -07003152status_t InputDispatcher::unregisterInputChannelLocked(const sp<InputChannel>& inputChannel,
3153 bool notify) {
3154 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
3155 if (connectionIndex < 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00003156 ALOGW("Attempted to unregister already unregistered input channel '%s'",
Jeff Browncc4f7db2011-08-30 20:34:48 -07003157 inputChannel->getName().string());
3158 return BAD_VALUE;
3159 }
3160
Jeff Browncbee6d62012-02-03 20:11:27 -08003161 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
3162 mConnectionsByFd.removeItemsAt(connectionIndex);
Jeff Browncc4f7db2011-08-30 20:34:48 -07003163
3164 if (connection->monitor) {
3165 removeMonitorChannelLocked(inputChannel);
3166 }
3167
Jeff Browncbee6d62012-02-03 20:11:27 -08003168 mLooper->removeFd(inputChannel->getFd());
Jeff Browncc4f7db2011-08-30 20:34:48 -07003169
3170 nsecs_t currentTime = now();
3171 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
3172
3173 runCommandsLockedInterruptible();
3174
3175 connection->status = Connection::STATUS_ZOMBIE;
3176 return OK;
3177}
3178
3179void InputDispatcher::removeMonitorChannelLocked(const sp<InputChannel>& inputChannel) {
3180 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
3181 if (mMonitoringChannels[i] == inputChannel) {
3182 mMonitoringChannels.removeAt(i);
3183 break;
3184 }
3185 }
3186}
3187
Jeff Brown519e0242010-09-15 15:18:56 -07003188ssize_t InputDispatcher::getConnectionIndexLocked(const sp<InputChannel>& inputChannel) {
Jeff Browncbee6d62012-02-03 20:11:27 -08003189 ssize_t connectionIndex = mConnectionsByFd.indexOfKey(inputChannel->getFd());
Jeff Brown2cbecea2010-08-17 15:59:26 -07003190 if (connectionIndex >= 0) {
Jeff Browncbee6d62012-02-03 20:11:27 -08003191 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
Jeff Brown2cbecea2010-08-17 15:59:26 -07003192 if (connection->inputChannel.get() == inputChannel.get()) {
3193 return connectionIndex;
3194 }
3195 }
3196
3197 return -1;
3198}
3199
Jeff Brown9c3cda02010-06-15 01:31:58 -07003200void InputDispatcher::onDispatchCycleFinishedLocked(
Jeff Brown072ec962012-02-07 14:46:57 -08003201 nsecs_t currentTime, const sp<Connection>& connection, uint32_t seq, bool handled) {
Jeff Brown3915bb82010-11-05 15:02:16 -07003202 CommandEntry* commandEntry = postCommandLocked(
3203 & InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
3204 commandEntry->connection = connection;
Jeff Brown072ec962012-02-07 14:46:57 -08003205 commandEntry->seq = seq;
Jeff Brown3915bb82010-11-05 15:02:16 -07003206 commandEntry->handled = handled;
Jeff Brown46b9ac02010-04-22 18:58:52 -07003207}
3208
Jeff Brown9c3cda02010-06-15 01:31:58 -07003209void InputDispatcher::onDispatchCycleBrokenLocked(
Jeff Brown7fbdc842010-06-17 20:52:56 -07003210 nsecs_t currentTime, const sp<Connection>& connection) {
Steve Block3762c312012-01-06 19:20:56 +00003211 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Jeff Brown46b9ac02010-04-22 18:58:52 -07003212 connection->getInputChannelName());
3213
Jeff Brown9c3cda02010-06-15 01:31:58 -07003214 CommandEntry* commandEntry = postCommandLocked(
3215 & InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
Jeff Brown7fbdc842010-06-17 20:52:56 -07003216 commandEntry->connection = connection;
Jeff Brown46b9ac02010-04-22 18:58:52 -07003217}
3218
Jeff Brown519e0242010-09-15 15:18:56 -07003219void InputDispatcher::onANRLocked(
Jeff Brown9302c872011-07-13 22:51:29 -07003220 nsecs_t currentTime, const sp<InputApplicationHandle>& applicationHandle,
3221 const sp<InputWindowHandle>& windowHandle,
Jeff Brown519e0242010-09-15 15:18:56 -07003222 nsecs_t eventTime, nsecs_t waitStartTime) {
Steve Block6215d3f2012-01-04 20:05:49 +00003223 ALOGI("Application is not responding: %s. "
Jeff Brown519e0242010-09-15 15:18:56 -07003224 "%01.1fms since event, %01.1fms since wait started",
Jeff Brown9302c872011-07-13 22:51:29 -07003225 getApplicationWindowLabelLocked(applicationHandle, windowHandle).string(),
Jeff Brown519e0242010-09-15 15:18:56 -07003226 (currentTime - eventTime) / 1000000.0,
3227 (currentTime - waitStartTime) / 1000000.0);
3228
3229 CommandEntry* commandEntry = postCommandLocked(
3230 & InputDispatcher::doNotifyANRLockedInterruptible);
Jeff Brown9302c872011-07-13 22:51:29 -07003231 commandEntry->inputApplicationHandle = applicationHandle;
3232 commandEntry->inputWindowHandle = windowHandle;
Jeff Brown519e0242010-09-15 15:18:56 -07003233}
3234
Jeff Brownb88102f2010-09-08 11:49:43 -07003235void InputDispatcher::doNotifyConfigurationChangedInterruptible(
3236 CommandEntry* commandEntry) {
3237 mLock.unlock();
3238
3239 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
3240
3241 mLock.lock();
3242}
3243
Jeff Brown9c3cda02010-06-15 01:31:58 -07003244void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(
3245 CommandEntry* commandEntry) {
Jeff Brown7fbdc842010-06-17 20:52:56 -07003246 sp<Connection> connection = commandEntry->connection;
Jeff Brown9c3cda02010-06-15 01:31:58 -07003247
Jeff Brown7fbdc842010-06-17 20:52:56 -07003248 if (connection->status != Connection::STATUS_ZOMBIE) {
3249 mLock.unlock();
Jeff Brown9c3cda02010-06-15 01:31:58 -07003250
Jeff Brown928e0542011-01-10 11:17:36 -08003251 mPolicy->notifyInputChannelBroken(connection->inputWindowHandle);
Jeff Brown7fbdc842010-06-17 20:52:56 -07003252
3253 mLock.lock();
3254 }
Jeff Brown9c3cda02010-06-15 01:31:58 -07003255}
3256
Jeff Brown519e0242010-09-15 15:18:56 -07003257void InputDispatcher::doNotifyANRLockedInterruptible(
Jeff Brown9c3cda02010-06-15 01:31:58 -07003258 CommandEntry* commandEntry) {
Jeff Brown519e0242010-09-15 15:18:56 -07003259 mLock.unlock();
Jeff Brown9c3cda02010-06-15 01:31:58 -07003260
Jeff Brown519e0242010-09-15 15:18:56 -07003261 nsecs_t newTimeout = mPolicy->notifyANR(
Jeff Brown928e0542011-01-10 11:17:36 -08003262 commandEntry->inputApplicationHandle, commandEntry->inputWindowHandle);
Jeff Brown9c3cda02010-06-15 01:31:58 -07003263
Jeff Brown519e0242010-09-15 15:18:56 -07003264 mLock.lock();
Jeff Brown7fbdc842010-06-17 20:52:56 -07003265
Jeff Brown9302c872011-07-13 22:51:29 -07003266 resumeAfterTargetsNotReadyTimeoutLocked(newTimeout,
3267 commandEntry->inputWindowHandle != NULL
Jeff Browncc4f7db2011-08-30 20:34:48 -07003268 ? commandEntry->inputWindowHandle->getInputChannel() : NULL);
Jeff Brown9c3cda02010-06-15 01:31:58 -07003269}
3270
Jeff Brownb88102f2010-09-08 11:49:43 -07003271void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
3272 CommandEntry* commandEntry) {
3273 KeyEntry* entry = commandEntry->keyEntry;
Jeff Brown1f245102010-11-18 20:53:46 -08003274
3275 KeyEvent event;
3276 initializeKeyEvent(&event, entry);
Jeff Brownb88102f2010-09-08 11:49:43 -07003277
3278 mLock.unlock();
3279
Jeff Brown905805a2011-10-12 13:57:59 -07003280 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(commandEntry->inputWindowHandle,
Jeff Brown1f245102010-11-18 20:53:46 -08003281 &event, entry->policyFlags);
Jeff Brownb88102f2010-09-08 11:49:43 -07003282
3283 mLock.lock();
3284
Jeff Brown905805a2011-10-12 13:57:59 -07003285 if (delay < 0) {
3286 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
3287 } else if (!delay) {
3288 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
3289 } else {
3290 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
3291 entry->interceptKeyWakeupTime = now() + delay;
3292 }
Jeff Brownac386072011-07-20 15:19:50 -07003293 entry->release();
Jeff Brownb88102f2010-09-08 11:49:43 -07003294}
3295
Jeff Brown3915bb82010-11-05 15:02:16 -07003296void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(
3297 CommandEntry* commandEntry) {
3298 sp<Connection> connection = commandEntry->connection;
Jeff Brown072ec962012-02-07 14:46:57 -08003299 uint32_t seq = commandEntry->seq;
Jeff Brown3915bb82010-11-05 15:02:16 -07003300 bool handled = commandEntry->handled;
3301
Jeff Brown072ec962012-02-07 14:46:57 -08003302 // Handle post-event policy actions.
3303 DispatchEntry* dispatchEntry = connection->findWaitQueueEntry(seq);
3304 if (dispatchEntry) {
Jeff Brownd1c48a02012-02-06 19:12:47 -08003305 bool restartEvent;
Jeff Brownd1c48a02012-02-06 19:12:47 -08003306 if (dispatchEntry->eventEntry->type == EventEntry::TYPE_KEY) {
3307 KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry);
3308 restartEvent = afterKeyEventLockedInterruptible(connection,
3309 dispatchEntry, keyEntry, handled);
3310 } else if (dispatchEntry->eventEntry->type == EventEntry::TYPE_MOTION) {
3311 MotionEntry* motionEntry = static_cast<MotionEntry*>(dispatchEntry->eventEntry);
3312 restartEvent = afterMotionEventLockedInterruptible(connection,
3313 dispatchEntry, motionEntry, handled);
3314 } else {
3315 restartEvent = false;
3316 }
3317
3318 // Dequeue the event and start the next cycle.
3319 // Note that because the lock might have been released, it is possible that the
3320 // contents of the wait queue to have been drained, so we need to double-check
3321 // a few things.
Jeff Brown072ec962012-02-07 14:46:57 -08003322 if (dispatchEntry == connection->findWaitQueueEntry(seq)) {
3323 connection->waitQueue.dequeue(dispatchEntry);
Jeff Brown481c1572012-03-09 14:41:15 -08003324 traceWaitQueueLengthLocked(connection);
Jeff Brownd1c48a02012-02-06 19:12:47 -08003325 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
3326 connection->outboundQueue.enqueueAtHead(dispatchEntry);
Jeff Brown481c1572012-03-09 14:41:15 -08003327 traceOutboundQueueLengthLocked(connection);
Jeff Brownd1c48a02012-02-06 19:12:47 -08003328 } else {
3329 releaseDispatchEntryLocked(dispatchEntry);
Jeff Brown49ed71d2010-12-06 17:13:33 -08003330 }
Jeff Brown3915bb82010-11-05 15:02:16 -07003331 }
Jeff Brown3915bb82010-11-05 15:02:16 -07003332
Jeff Brownd1c48a02012-02-06 19:12:47 -08003333 // Start the next dispatch cycle for this connection.
3334 startDispatchCycleLocked(now(), connection);
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003335 }
3336}
3337
3338bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
3339 DispatchEntry* dispatchEntry, KeyEntry* keyEntry, bool handled) {
3340 if (!(keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK)) {
3341 // Get the fallback key state.
3342 // Clear it out after dispatching the UP.
3343 int32_t originalKeyCode = keyEntry->keyCode;
3344 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
3345 if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
3346 connection->inputState.removeFallbackKey(originalKeyCode);
3347 }
3348
3349 if (handled || !dispatchEntry->hasForegroundTarget()) {
3350 // If the application handles the original key for which we previously
3351 // generated a fallback or if the window is not a foreground window,
3352 // then cancel the associated fallback key, if any.
3353 if (fallbackKeyCode != -1) {
3354 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
3355 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
3356 "application handled the original non-fallback key "
3357 "or is no longer a foreground target, "
3358 "canceling previously dispatched fallback key");
3359 options.keyCode = fallbackKeyCode;
3360 synthesizeCancelationEventsForConnectionLocked(connection, options);
3361 }
3362 connection->inputState.removeFallbackKey(originalKeyCode);
3363 }
3364 } else {
3365 // If the application did not handle a non-fallback key, first check
3366 // that we are in a good state to perform unhandled key event processing
3367 // Then ask the policy what to do with it.
3368 bool initialDown = keyEntry->action == AKEY_EVENT_ACTION_DOWN
3369 && keyEntry->repeatCount == 0;
3370 if (fallbackKeyCode == -1 && !initialDown) {
3371#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00003372 ALOGD("Unhandled key event: Skipping unhandled key event processing "
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003373 "since this is not an initial down. "
3374 "keyCode=%d, action=%d, repeatCount=%d",
3375 originalKeyCode, keyEntry->action, keyEntry->repeatCount);
3376#endif
3377 return false;
3378 }
3379
3380 // Dispatch the unhandled key to the policy.
3381#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00003382 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003383 "keyCode=%d, action=%d, repeatCount=%d",
3384 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount);
3385#endif
3386 KeyEvent event;
3387 initializeKeyEvent(&event, keyEntry);
3388
3389 mLock.unlock();
3390
3391 bool fallback = mPolicy->dispatchUnhandledKey(connection->inputWindowHandle,
3392 &event, keyEntry->policyFlags, &event);
3393
3394 mLock.lock();
3395
3396 if (connection->status != Connection::STATUS_NORMAL) {
3397 connection->inputState.removeFallbackKey(originalKeyCode);
Jeff Brownd1c48a02012-02-06 19:12:47 -08003398 return false;
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003399 }
3400
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003401 // Latch the fallback keycode for this key on an initial down.
3402 // The fallback keycode cannot change at any other point in the lifecycle.
3403 if (initialDown) {
3404 if (fallback) {
3405 fallbackKeyCode = event.getKeyCode();
3406 } else {
3407 fallbackKeyCode = AKEYCODE_UNKNOWN;
3408 }
3409 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
3410 }
3411
Steve Blockec193de2012-01-09 18:35:44 +00003412 ALOG_ASSERT(fallbackKeyCode != -1);
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003413
3414 // Cancel the fallback key if the policy decides not to send it anymore.
3415 // We will continue to dispatch the key to the policy but we will no
3416 // longer dispatch a fallback key to the application.
3417 if (fallbackKeyCode != AKEYCODE_UNKNOWN
3418 && (!fallback || fallbackKeyCode != event.getKeyCode())) {
3419#if DEBUG_OUTBOUND_EVENT_DETAILS
3420 if (fallback) {
Steve Block5baa3a62011-12-20 16:23:08 +00003421 ALOGD("Unhandled key event: Policy requested to send key %d"
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003422 "as a fallback for %d, but on the DOWN it had requested "
3423 "to send %d instead. Fallback canceled.",
3424 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
3425 } else {
Steve Block5baa3a62011-12-20 16:23:08 +00003426 ALOGD("Unhandled key event: Policy did not request fallback for %d,"
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003427 "but on the DOWN it had requested to send %d. "
3428 "Fallback canceled.",
3429 originalKeyCode, fallbackKeyCode);
3430 }
3431#endif
3432
3433 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
3434 "canceling fallback, policy no longer desires it");
3435 options.keyCode = fallbackKeyCode;
3436 synthesizeCancelationEventsForConnectionLocked(connection, options);
3437
3438 fallback = false;
3439 fallbackKeyCode = AKEYCODE_UNKNOWN;
3440 if (keyEntry->action != AKEY_EVENT_ACTION_UP) {
3441 connection->inputState.setFallbackKey(originalKeyCode,
3442 fallbackKeyCode);
3443 }
3444 }
3445
3446#if DEBUG_OUTBOUND_EVENT_DETAILS
3447 {
3448 String8 msg;
3449 const KeyedVector<int32_t, int32_t>& fallbackKeys =
3450 connection->inputState.getFallbackKeys();
3451 for (size_t i = 0; i < fallbackKeys.size(); i++) {
3452 msg.appendFormat(", %d->%d", fallbackKeys.keyAt(i),
3453 fallbackKeys.valueAt(i));
3454 }
Steve Block5baa3a62011-12-20 16:23:08 +00003455 ALOGD("Unhandled key event: %d currently tracked fallback keys%s.",
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003456 fallbackKeys.size(), msg.string());
3457 }
3458#endif
3459
3460 if (fallback) {
3461 // Restart the dispatch cycle using the fallback key.
3462 keyEntry->eventTime = event.getEventTime();
3463 keyEntry->deviceId = event.getDeviceId();
3464 keyEntry->source = event.getSource();
3465 keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
3466 keyEntry->keyCode = fallbackKeyCode;
3467 keyEntry->scanCode = event.getScanCode();
3468 keyEntry->metaState = event.getMetaState();
3469 keyEntry->repeatCount = event.getRepeatCount();
3470 keyEntry->downTime = event.getDownTime();
3471 keyEntry->syntheticRepeat = false;
3472
3473#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00003474 ALOGD("Unhandled key event: Dispatching fallback key. "
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003475 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
3476 originalKeyCode, fallbackKeyCode, keyEntry->metaState);
3477#endif
Jeff Brownd1c48a02012-02-06 19:12:47 -08003478 return true; // restart the event
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003479 } else {
3480#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00003481 ALOGD("Unhandled key event: No fallback key.");
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003482#endif
3483 }
3484 }
3485 }
3486 return false;
3487}
3488
3489bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
3490 DispatchEntry* dispatchEntry, MotionEntry* motionEntry, bool handled) {
3491 return false;
Jeff Brown3915bb82010-11-05 15:02:16 -07003492}
3493
Jeff Brownb88102f2010-09-08 11:49:43 -07003494void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
3495 mLock.unlock();
3496
Jeff Brown01ce2e92010-09-26 22:20:12 -07003497 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
Jeff Brownb88102f2010-09-08 11:49:43 -07003498
3499 mLock.lock();
3500}
3501
Jeff Brown3915bb82010-11-05 15:02:16 -07003502void InputDispatcher::initializeKeyEvent(KeyEvent* event, const KeyEntry* entry) {
3503 event->initialize(entry->deviceId, entry->source, entry->action, entry->flags,
3504 entry->keyCode, entry->scanCode, entry->metaState, entry->repeatCount,
3505 entry->downTime, entry->eventTime);
3506}
3507
Jeff Brown519e0242010-09-15 15:18:56 -07003508void InputDispatcher::updateDispatchStatisticsLocked(nsecs_t currentTime, const EventEntry* entry,
3509 int32_t injectionResult, nsecs_t timeSpentWaitingForApplication) {
3510 // TODO Write some statistics about how long we spend waiting.
Jeff Brownb88102f2010-09-08 11:49:43 -07003511}
3512
Jeff Brown481c1572012-03-09 14:41:15 -08003513void InputDispatcher::traceInboundQueueLengthLocked() {
3514 if (ATRACE_ENABLED()) {
3515 ATRACE_INT("iq", mInboundQueue.count());
3516 }
3517}
3518
3519void InputDispatcher::traceOutboundQueueLengthLocked(const sp<Connection>& connection) {
3520 if (ATRACE_ENABLED()) {
3521 char counterName[40];
3522 snprintf(counterName, sizeof(counterName), "oq:%s", connection->getWindowName());
3523 ATRACE_INT(counterName, connection->outboundQueue.count());
3524 }
3525}
3526
3527void InputDispatcher::traceWaitQueueLengthLocked(const sp<Connection>& connection) {
3528 if (ATRACE_ENABLED()) {
3529 char counterName[40];
3530 snprintf(counterName, sizeof(counterName), "wq:%s", connection->getWindowName());
3531 ATRACE_INT(counterName, connection->waitQueue.count());
3532 }
3533}
3534
Jeff Brownb88102f2010-09-08 11:49:43 -07003535void InputDispatcher::dump(String8& dump) {
Jeff Brown89ef0722011-08-10 16:25:21 -07003536 AutoMutex _l(mLock);
3537
Jeff Brownf2f487182010-10-01 17:46:21 -07003538 dump.append("Input Dispatcher State:\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003539 dumpDispatchStateLocked(dump);
Jeff Brown214eaf42011-05-26 19:17:02 -07003540
3541 dump.append(INDENT "Configuration:\n");
Jeff Brown214eaf42011-05-26 19:17:02 -07003542 dump.appendFormat(INDENT2 "KeyRepeatDelay: %0.1fms\n", mConfig.keyRepeatDelay * 0.000001f);
3543 dump.appendFormat(INDENT2 "KeyRepeatTimeout: %0.1fms\n", mConfig.keyRepeatTimeout * 0.000001f);
Jeff Brownb88102f2010-09-08 11:49:43 -07003544}
3545
Jeff Brown89ef0722011-08-10 16:25:21 -07003546void InputDispatcher::monitor() {
3547 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
3548 mLock.lock();
Jeff Brown112b5f52012-01-27 17:32:06 -08003549 mLooper->wake();
3550 mDispatcherIsAliveCondition.wait(mLock);
Jeff Brown89ef0722011-08-10 16:25:21 -07003551 mLock.unlock();
3552}
3553
Jeff Brown9c3cda02010-06-15 01:31:58 -07003554
Jeff Brown519e0242010-09-15 15:18:56 -07003555// --- InputDispatcher::Queue ---
3556
3557template <typename T>
3558uint32_t InputDispatcher::Queue<T>::count() const {
3559 uint32_t result = 0;
Jeff Brownac386072011-07-20 15:19:50 -07003560 for (const T* entry = head; entry; entry = entry->next) {
Jeff Brown519e0242010-09-15 15:18:56 -07003561 result += 1;
3562 }
3563 return result;
3564}
3565
3566
Jeff Brownac386072011-07-20 15:19:50 -07003567// --- InputDispatcher::InjectionState ---
Jeff Brown46b9ac02010-04-22 18:58:52 -07003568
Jeff Brownac386072011-07-20 15:19:50 -07003569InputDispatcher::InjectionState::InjectionState(int32_t injectorPid, int32_t injectorUid) :
3570 refCount(1),
3571 injectorPid(injectorPid), injectorUid(injectorUid),
3572 injectionResult(INPUT_EVENT_INJECTION_PENDING), injectionIsAsync(false),
3573 pendingForegroundDispatches(0) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07003574}
3575
Jeff Brownac386072011-07-20 15:19:50 -07003576InputDispatcher::InjectionState::~InjectionState() {
Jeff Brown01ce2e92010-09-26 22:20:12 -07003577}
3578
Jeff Brownac386072011-07-20 15:19:50 -07003579void InputDispatcher::InjectionState::release() {
3580 refCount -= 1;
3581 if (refCount == 0) {
3582 delete this;
3583 } else {
Steve Blockec193de2012-01-09 18:35:44 +00003584 ALOG_ASSERT(refCount > 0);
Jeff Brown01ce2e92010-09-26 22:20:12 -07003585 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07003586}
3587
Jeff Brownac386072011-07-20 15:19:50 -07003588
3589// --- InputDispatcher::EventEntry ---
3590
3591InputDispatcher::EventEntry::EventEntry(int32_t type, nsecs_t eventTime, uint32_t policyFlags) :
3592 refCount(1), type(type), eventTime(eventTime), policyFlags(policyFlags),
3593 injectionState(NULL), dispatchInProgress(false) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07003594}
3595
Jeff Brownac386072011-07-20 15:19:50 -07003596InputDispatcher::EventEntry::~EventEntry() {
3597 releaseInjectionState();
3598}
3599
3600void InputDispatcher::EventEntry::release() {
3601 refCount -= 1;
3602 if (refCount == 0) {
3603 delete this;
3604 } else {
Steve Blockec193de2012-01-09 18:35:44 +00003605 ALOG_ASSERT(refCount > 0);
Jeff Brownac386072011-07-20 15:19:50 -07003606 }
3607}
3608
3609void InputDispatcher::EventEntry::releaseInjectionState() {
3610 if (injectionState) {
3611 injectionState->release();
3612 injectionState = NULL;
3613 }
3614}
3615
3616
3617// --- InputDispatcher::ConfigurationChangedEntry ---
3618
3619InputDispatcher::ConfigurationChangedEntry::ConfigurationChangedEntry(nsecs_t eventTime) :
3620 EventEntry(TYPE_CONFIGURATION_CHANGED, eventTime, 0) {
3621}
3622
3623InputDispatcher::ConfigurationChangedEntry::~ConfigurationChangedEntry() {
3624}
3625
3626
Jeff Brown65fd2512011-08-18 11:20:58 -07003627// --- InputDispatcher::DeviceResetEntry ---
3628
3629InputDispatcher::DeviceResetEntry::DeviceResetEntry(nsecs_t eventTime, int32_t deviceId) :
3630 EventEntry(TYPE_DEVICE_RESET, eventTime, 0),
3631 deviceId(deviceId) {
3632}
3633
3634InputDispatcher::DeviceResetEntry::~DeviceResetEntry() {
3635}
3636
3637
Jeff Brownac386072011-07-20 15:19:50 -07003638// --- InputDispatcher::KeyEntry ---
3639
3640InputDispatcher::KeyEntry::KeyEntry(nsecs_t eventTime,
Jeff Brown58a2da82011-01-25 16:02:22 -08003641 int32_t deviceId, uint32_t source, uint32_t policyFlags, int32_t action,
Jeff Brown7fbdc842010-06-17 20:52:56 -07003642 int32_t flags, int32_t keyCode, int32_t scanCode, int32_t metaState,
Jeff Brownac386072011-07-20 15:19:50 -07003643 int32_t repeatCount, nsecs_t downTime) :
3644 EventEntry(TYPE_KEY, eventTime, policyFlags),
3645 deviceId(deviceId), source(source), action(action), flags(flags),
3646 keyCode(keyCode), scanCode(scanCode), metaState(metaState),
3647 repeatCount(repeatCount), downTime(downTime),
Jeff Brown905805a2011-10-12 13:57:59 -07003648 syntheticRepeat(false), interceptKeyResult(KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN),
3649 interceptKeyWakeupTime(0) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07003650}
3651
Jeff Brownac386072011-07-20 15:19:50 -07003652InputDispatcher::KeyEntry::~KeyEntry() {
3653}
Jeff Brown7fbdc842010-06-17 20:52:56 -07003654
Jeff Brownac386072011-07-20 15:19:50 -07003655void InputDispatcher::KeyEntry::recycle() {
3656 releaseInjectionState();
3657
3658 dispatchInProgress = false;
3659 syntheticRepeat = false;
3660 interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
Jeff Brown905805a2011-10-12 13:57:59 -07003661 interceptKeyWakeupTime = 0;
Jeff Brownac386072011-07-20 15:19:50 -07003662}
3663
3664
Jeff Brownae9fc032010-08-18 15:51:08 -07003665// --- InputDispatcher::MotionEntry ---
3666
Jeff Brownac386072011-07-20 15:19:50 -07003667InputDispatcher::MotionEntry::MotionEntry(nsecs_t eventTime,
3668 int32_t deviceId, uint32_t source, uint32_t policyFlags, int32_t action, int32_t flags,
3669 int32_t metaState, int32_t buttonState,
3670 int32_t edgeFlags, float xPrecision, float yPrecision,
3671 nsecs_t downTime, uint32_t pointerCount,
3672 const PointerProperties* pointerProperties, const PointerCoords* pointerCoords) :
3673 EventEntry(TYPE_MOTION, eventTime, policyFlags),
Jeff Brown3241b6b2012-02-03 15:08:02 -08003674 eventTime(eventTime),
Jeff Brownac386072011-07-20 15:19:50 -07003675 deviceId(deviceId), source(source), action(action), flags(flags),
3676 metaState(metaState), buttonState(buttonState), edgeFlags(edgeFlags),
3677 xPrecision(xPrecision), yPrecision(yPrecision),
Jeff Brown3241b6b2012-02-03 15:08:02 -08003678 downTime(downTime), pointerCount(pointerCount) {
Jeff Brownac386072011-07-20 15:19:50 -07003679 for (uint32_t i = 0; i < pointerCount; i++) {
3680 this->pointerProperties[i].copyFrom(pointerProperties[i]);
Jeff Brown3241b6b2012-02-03 15:08:02 -08003681 this->pointerCoords[i].copyFrom(pointerCoords[i]);
Jeff Brownac386072011-07-20 15:19:50 -07003682 }
3683}
3684
3685InputDispatcher::MotionEntry::~MotionEntry() {
Jeff Brownac386072011-07-20 15:19:50 -07003686}
3687
3688
3689// --- InputDispatcher::DispatchEntry ---
3690
Jeff Brown072ec962012-02-07 14:46:57 -08003691volatile int32_t InputDispatcher::DispatchEntry::sNextSeqAtomic;
3692
Jeff Brownac386072011-07-20 15:19:50 -07003693InputDispatcher::DispatchEntry::DispatchEntry(EventEntry* eventEntry,
3694 int32_t targetFlags, float xOffset, float yOffset, float scaleFactor) :
Jeff Brown072ec962012-02-07 14:46:57 -08003695 seq(nextSeq()),
Jeff Brownac386072011-07-20 15:19:50 -07003696 eventEntry(eventEntry), targetFlags(targetFlags),
3697 xOffset(xOffset), yOffset(yOffset), scaleFactor(scaleFactor),
Jeff Brown3241b6b2012-02-03 15:08:02 -08003698 resolvedAction(0), resolvedFlags(0) {
Jeff Brownac386072011-07-20 15:19:50 -07003699 eventEntry->refCount += 1;
3700}
3701
3702InputDispatcher::DispatchEntry::~DispatchEntry() {
3703 eventEntry->release();
3704}
3705
Jeff Brown072ec962012-02-07 14:46:57 -08003706uint32_t InputDispatcher::DispatchEntry::nextSeq() {
3707 // Sequence number 0 is reserved and will never be returned.
3708 uint32_t seq;
3709 do {
3710 seq = android_atomic_inc(&sNextSeqAtomic);
3711 } while (!seq);
3712 return seq;
3713}
3714
Jeff Brownb88102f2010-09-08 11:49:43 -07003715
3716// --- InputDispatcher::InputState ---
3717
Jeff Brownb6997262010-10-08 22:31:17 -07003718InputDispatcher::InputState::InputState() {
Jeff Brownb88102f2010-09-08 11:49:43 -07003719}
3720
3721InputDispatcher::InputState::~InputState() {
3722}
3723
3724bool InputDispatcher::InputState::isNeutral() const {
3725 return mKeyMementos.isEmpty() && mMotionMementos.isEmpty();
3726}
3727
Jeff Brown81346812011-06-28 20:08:48 -07003728bool InputDispatcher::InputState::isHovering(int32_t deviceId, uint32_t source) const {
3729 for (size_t i = 0; i < mMotionMementos.size(); i++) {
3730 const MotionMemento& memento = mMotionMementos.itemAt(i);
3731 if (memento.deviceId == deviceId
3732 && memento.source == source
3733 && memento.hovering) {
3734 return true;
3735 }
3736 }
3737 return false;
3738}
Jeff Brownb88102f2010-09-08 11:49:43 -07003739
Jeff Brown81346812011-06-28 20:08:48 -07003740bool InputDispatcher::InputState::trackKey(const KeyEntry* entry,
3741 int32_t action, int32_t flags) {
3742 switch (action) {
3743 case AKEY_EVENT_ACTION_UP: {
3744 if (entry->flags & AKEY_EVENT_FLAG_FALLBACK) {
3745 for (size_t i = 0; i < mFallbackKeys.size(); ) {
3746 if (mFallbackKeys.valueAt(i) == entry->keyCode) {
3747 mFallbackKeys.removeItemsAt(i);
3748 } else {
3749 i += 1;
3750 }
3751 }
3752 }
3753 ssize_t index = findKeyMemento(entry);
3754 if (index >= 0) {
3755 mKeyMementos.removeAt(index);
3756 return true;
3757 }
Jeff Brown68b909d2011-12-07 16:36:01 -08003758 /* FIXME: We can't just drop the key up event because that prevents creating
3759 * popup windows that are automatically shown when a key is held and then
3760 * dismissed when the key is released. The problem is that the popup will
3761 * not have received the original key down, so the key up will be considered
3762 * to be inconsistent with its observed state. We could perhaps handle this
3763 * by synthesizing a key down but that will cause other problems.
3764 *
3765 * So for now, allow inconsistent key up events to be dispatched.
3766 *
Jeff Brown81346812011-06-28 20:08:48 -07003767#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00003768 ALOGD("Dropping inconsistent key up event: deviceId=%d, source=%08x, "
Jeff Brown81346812011-06-28 20:08:48 -07003769 "keyCode=%d, scanCode=%d",
3770 entry->deviceId, entry->source, entry->keyCode, entry->scanCode);
3771#endif
3772 return false;
Jeff Brown68b909d2011-12-07 16:36:01 -08003773 */
3774 return true;
Jeff Brown81346812011-06-28 20:08:48 -07003775 }
3776
3777 case AKEY_EVENT_ACTION_DOWN: {
3778 ssize_t index = findKeyMemento(entry);
3779 if (index >= 0) {
3780 mKeyMementos.removeAt(index);
3781 }
3782 addKeyMemento(entry, flags);
3783 return true;
3784 }
3785
3786 default:
3787 return true;
Jeff Brownb88102f2010-09-08 11:49:43 -07003788 }
3789}
3790
Jeff Brown81346812011-06-28 20:08:48 -07003791bool InputDispatcher::InputState::trackMotion(const MotionEntry* entry,
3792 int32_t action, int32_t flags) {
3793 int32_t actionMasked = action & AMOTION_EVENT_ACTION_MASK;
3794 switch (actionMasked) {
3795 case AMOTION_EVENT_ACTION_UP:
3796 case AMOTION_EVENT_ACTION_CANCEL: {
3797 ssize_t index = findMotionMemento(entry, false /*hovering*/);
3798 if (index >= 0) {
3799 mMotionMementos.removeAt(index);
3800 return true;
Jeff Brownda3d5a92011-03-29 15:11:34 -07003801 }
Jeff Brown81346812011-06-28 20:08:48 -07003802#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00003803 ALOGD("Dropping inconsistent motion up or cancel event: deviceId=%d, source=%08x, "
Jeff Brown81346812011-06-28 20:08:48 -07003804 "actionMasked=%d",
3805 entry->deviceId, entry->source, actionMasked);
3806#endif
3807 return false;
Jeff Brownda3d5a92011-03-29 15:11:34 -07003808 }
3809
Jeff Brown81346812011-06-28 20:08:48 -07003810 case AMOTION_EVENT_ACTION_DOWN: {
3811 ssize_t index = findMotionMemento(entry, false /*hovering*/);
3812 if (index >= 0) {
3813 mMotionMementos.removeAt(index);
3814 }
3815 addMotionMemento(entry, flags, false /*hovering*/);
3816 return true;
3817 }
3818
3819 case AMOTION_EVENT_ACTION_POINTER_UP:
3820 case AMOTION_EVENT_ACTION_POINTER_DOWN:
3821 case AMOTION_EVENT_ACTION_MOVE: {
3822 ssize_t index = findMotionMemento(entry, false /*hovering*/);
3823 if (index >= 0) {
3824 MotionMemento& memento = mMotionMementos.editItemAt(index);
3825 memento.setPointers(entry);
3826 return true;
3827 }
Jeff Brown2e45fb62011-06-29 21:19:05 -07003828 if (actionMasked == AMOTION_EVENT_ACTION_MOVE
3829 && (entry->source & (AINPUT_SOURCE_CLASS_JOYSTICK
3830 | AINPUT_SOURCE_CLASS_NAVIGATION))) {
3831 // Joysticks and trackballs can send MOVE events without corresponding DOWN or UP.
3832 return true;
3833 }
Jeff Brown81346812011-06-28 20:08:48 -07003834#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00003835 ALOGD("Dropping inconsistent motion pointer up/down or move event: "
Jeff Brown81346812011-06-28 20:08:48 -07003836 "deviceId=%d, source=%08x, actionMasked=%d",
3837 entry->deviceId, entry->source, actionMasked);
3838#endif
3839 return false;
3840 }
3841
3842 case AMOTION_EVENT_ACTION_HOVER_EXIT: {
3843 ssize_t index = findMotionMemento(entry, true /*hovering*/);
3844 if (index >= 0) {
3845 mMotionMementos.removeAt(index);
3846 return true;
3847 }
3848#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00003849 ALOGD("Dropping inconsistent motion hover exit event: deviceId=%d, source=%08x",
Jeff Brown81346812011-06-28 20:08:48 -07003850 entry->deviceId, entry->source);
3851#endif
3852 return false;
3853 }
3854
3855 case AMOTION_EVENT_ACTION_HOVER_ENTER:
3856 case AMOTION_EVENT_ACTION_HOVER_MOVE: {
3857 ssize_t index = findMotionMemento(entry, true /*hovering*/);
3858 if (index >= 0) {
3859 mMotionMementos.removeAt(index);
3860 }
3861 addMotionMemento(entry, flags, true /*hovering*/);
3862 return true;
3863 }
3864
3865 default:
3866 return true;
3867 }
3868}
3869
3870ssize_t InputDispatcher::InputState::findKeyMemento(const KeyEntry* entry) const {
Jeff Brownb88102f2010-09-08 11:49:43 -07003871 for (size_t i = 0; i < mKeyMementos.size(); i++) {
Jeff Brown81346812011-06-28 20:08:48 -07003872 const KeyMemento& memento = mKeyMementos.itemAt(i);
Jeff Brownb88102f2010-09-08 11:49:43 -07003873 if (memento.deviceId == entry->deviceId
3874 && memento.source == entry->source
3875 && memento.keyCode == entry->keyCode
3876 && memento.scanCode == entry->scanCode) {
Jeff Brown81346812011-06-28 20:08:48 -07003877 return i;
Jeff Brownb88102f2010-09-08 11:49:43 -07003878 }
3879 }
Jeff Brown81346812011-06-28 20:08:48 -07003880 return -1;
Jeff Brownb88102f2010-09-08 11:49:43 -07003881}
3882
Jeff Brown81346812011-06-28 20:08:48 -07003883ssize_t InputDispatcher::InputState::findMotionMemento(const MotionEntry* entry,
3884 bool hovering) const {
Jeff Brownb88102f2010-09-08 11:49:43 -07003885 for (size_t i = 0; i < mMotionMementos.size(); i++) {
Jeff Brown81346812011-06-28 20:08:48 -07003886 const MotionMemento& memento = mMotionMementos.itemAt(i);
Jeff Brownb88102f2010-09-08 11:49:43 -07003887 if (memento.deviceId == entry->deviceId
Jeff Brown81346812011-06-28 20:08:48 -07003888 && memento.source == entry->source
3889 && memento.hovering == hovering) {
3890 return i;
Jeff Brownb88102f2010-09-08 11:49:43 -07003891 }
3892 }
Jeff Brown81346812011-06-28 20:08:48 -07003893 return -1;
3894}
Jeff Brownb88102f2010-09-08 11:49:43 -07003895
Jeff Brown81346812011-06-28 20:08:48 -07003896void InputDispatcher::InputState::addKeyMemento(const KeyEntry* entry, int32_t flags) {
3897 mKeyMementos.push();
3898 KeyMemento& memento = mKeyMementos.editTop();
3899 memento.deviceId = entry->deviceId;
3900 memento.source = entry->source;
3901 memento.keyCode = entry->keyCode;
3902 memento.scanCode = entry->scanCode;
3903 memento.flags = flags;
3904 memento.downTime = entry->downTime;
3905}
3906
3907void InputDispatcher::InputState::addMotionMemento(const MotionEntry* entry,
3908 int32_t flags, bool hovering) {
3909 mMotionMementos.push();
3910 MotionMemento& memento = mMotionMementos.editTop();
3911 memento.deviceId = entry->deviceId;
3912 memento.source = entry->source;
3913 memento.flags = flags;
3914 memento.xPrecision = entry->xPrecision;
3915 memento.yPrecision = entry->yPrecision;
3916 memento.downTime = entry->downTime;
3917 memento.setPointers(entry);
3918 memento.hovering = hovering;
Jeff Brownb88102f2010-09-08 11:49:43 -07003919}
3920
3921void InputDispatcher::InputState::MotionMemento::setPointers(const MotionEntry* entry) {
3922 pointerCount = entry->pointerCount;
3923 for (uint32_t i = 0; i < entry->pointerCount; i++) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003924 pointerProperties[i].copyFrom(entry->pointerProperties[i]);
Jeff Brown3241b6b2012-02-03 15:08:02 -08003925 pointerCoords[i].copyFrom(entry->pointerCoords[i]);
Jeff Brownb88102f2010-09-08 11:49:43 -07003926 }
3927}
3928
Jeff Brownb6997262010-10-08 22:31:17 -07003929void InputDispatcher::InputState::synthesizeCancelationEvents(nsecs_t currentTime,
Jeff Brownac386072011-07-20 15:19:50 -07003930 Vector<EventEntry*>& outEvents, const CancelationOptions& options) {
Jeff Brown81346812011-06-28 20:08:48 -07003931 for (size_t i = 0; i < mKeyMementos.size(); i++) {
Jeff Brownb88102f2010-09-08 11:49:43 -07003932 const KeyMemento& memento = mKeyMementos.itemAt(i);
Jeff Brown49ed71d2010-12-06 17:13:33 -08003933 if (shouldCancelKey(memento, options)) {
Jeff Brownac386072011-07-20 15:19:50 -07003934 outEvents.push(new KeyEntry(currentTime,
Jeff Brownb6997262010-10-08 22:31:17 -07003935 memento.deviceId, memento.source, 0,
Jeff Brown49ed71d2010-12-06 17:13:33 -08003936 AKEY_EVENT_ACTION_UP, memento.flags | AKEY_EVENT_FLAG_CANCELED,
Jeff Brownb6997262010-10-08 22:31:17 -07003937 memento.keyCode, memento.scanCode, 0, 0, memento.downTime));
Jeff Brownb6997262010-10-08 22:31:17 -07003938 }
Jeff Brownb88102f2010-09-08 11:49:43 -07003939 }
3940
Jeff Brown81346812011-06-28 20:08:48 -07003941 for (size_t i = 0; i < mMotionMementos.size(); i++) {
Jeff Brownb88102f2010-09-08 11:49:43 -07003942 const MotionMemento& memento = mMotionMementos.itemAt(i);
Jeff Brown49ed71d2010-12-06 17:13:33 -08003943 if (shouldCancelMotion(memento, options)) {
Jeff Brownac386072011-07-20 15:19:50 -07003944 outEvents.push(new MotionEntry(currentTime,
Jeff Brownb6997262010-10-08 22:31:17 -07003945 memento.deviceId, memento.source, 0,
Jeff Browna032cc02011-03-07 16:56:21 -08003946 memento.hovering
3947 ? AMOTION_EVENT_ACTION_HOVER_EXIT
3948 : AMOTION_EVENT_ACTION_CANCEL,
Jeff Brown81346812011-06-28 20:08:48 -07003949 memento.flags, 0, 0, 0,
Jeff Brownb6997262010-10-08 22:31:17 -07003950 memento.xPrecision, memento.yPrecision, memento.downTime,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003951 memento.pointerCount, memento.pointerProperties, memento.pointerCoords));
Jeff Brownb6997262010-10-08 22:31:17 -07003952 }
Jeff Brownb88102f2010-09-08 11:49:43 -07003953 }
3954}
3955
3956void InputDispatcher::InputState::clear() {
3957 mKeyMementos.clear();
3958 mMotionMementos.clear();
Jeff Brownda3d5a92011-03-29 15:11:34 -07003959 mFallbackKeys.clear();
Jeff Brownb6997262010-10-08 22:31:17 -07003960}
3961
Jeff Brown9c9f1a32010-10-11 18:32:20 -07003962void InputDispatcher::InputState::copyPointerStateTo(InputState& other) const {
3963 for (size_t i = 0; i < mMotionMementos.size(); i++) {
3964 const MotionMemento& memento = mMotionMementos.itemAt(i);
3965 if (memento.source & AINPUT_SOURCE_CLASS_POINTER) {
3966 for (size_t j = 0; j < other.mMotionMementos.size(); ) {
3967 const MotionMemento& otherMemento = other.mMotionMementos.itemAt(j);
3968 if (memento.deviceId == otherMemento.deviceId
3969 && memento.source == otherMemento.source) {
3970 other.mMotionMementos.removeAt(j);
3971 } else {
3972 j += 1;
3973 }
3974 }
3975 other.mMotionMementos.push(memento);
3976 }
3977 }
3978}
3979
Jeff Brownda3d5a92011-03-29 15:11:34 -07003980int32_t InputDispatcher::InputState::getFallbackKey(int32_t originalKeyCode) {
3981 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
3982 return index >= 0 ? mFallbackKeys.valueAt(index) : -1;
3983}
3984
3985void InputDispatcher::InputState::setFallbackKey(int32_t originalKeyCode,
3986 int32_t fallbackKeyCode) {
3987 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
3988 if (index >= 0) {
3989 mFallbackKeys.replaceValueAt(index, fallbackKeyCode);
3990 } else {
3991 mFallbackKeys.add(originalKeyCode, fallbackKeyCode);
3992 }
3993}
3994
3995void InputDispatcher::InputState::removeFallbackKey(int32_t originalKeyCode) {
3996 mFallbackKeys.removeItem(originalKeyCode);
3997}
3998
Jeff Brown49ed71d2010-12-06 17:13:33 -08003999bool InputDispatcher::InputState::shouldCancelKey(const KeyMemento& memento,
Jeff Brownda3d5a92011-03-29 15:11:34 -07004000 const CancelationOptions& options) {
4001 if (options.keyCode != -1 && memento.keyCode != options.keyCode) {
4002 return false;
4003 }
4004
Jeff Brown65fd2512011-08-18 11:20:58 -07004005 if (options.deviceId != -1 && memento.deviceId != options.deviceId) {
4006 return false;
4007 }
4008
Jeff Brownda3d5a92011-03-29 15:11:34 -07004009 switch (options.mode) {
4010 case CancelationOptions::CANCEL_ALL_EVENTS:
4011 case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
Jeff Brownb6997262010-10-08 22:31:17 -07004012 return true;
Jeff Brownda3d5a92011-03-29 15:11:34 -07004013 case CancelationOptions::CANCEL_FALLBACK_EVENTS:
Jeff Brown49ed71d2010-12-06 17:13:33 -08004014 return memento.flags & AKEY_EVENT_FLAG_FALLBACK;
4015 default:
4016 return false;
4017 }
4018}
4019
4020bool InputDispatcher::InputState::shouldCancelMotion(const MotionMemento& memento,
Jeff Brownda3d5a92011-03-29 15:11:34 -07004021 const CancelationOptions& options) {
Jeff Brown65fd2512011-08-18 11:20:58 -07004022 if (options.deviceId != -1 && memento.deviceId != options.deviceId) {
4023 return false;
4024 }
4025
Jeff Brownda3d5a92011-03-29 15:11:34 -07004026 switch (options.mode) {
4027 case CancelationOptions::CANCEL_ALL_EVENTS:
Jeff Brown49ed71d2010-12-06 17:13:33 -08004028 return true;
Jeff Brownda3d5a92011-03-29 15:11:34 -07004029 case CancelationOptions::CANCEL_POINTER_EVENTS:
Jeff Brown49ed71d2010-12-06 17:13:33 -08004030 return memento.source & AINPUT_SOURCE_CLASS_POINTER;
Jeff Brownda3d5a92011-03-29 15:11:34 -07004031 case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
Jeff Brown49ed71d2010-12-06 17:13:33 -08004032 return !(memento.source & AINPUT_SOURCE_CLASS_POINTER);
4033 default:
4034 return false;
Jeff Brownb6997262010-10-08 22:31:17 -07004035 }
Jeff Brownb88102f2010-09-08 11:49:43 -07004036}
4037
4038
Jeff Brown46b9ac02010-04-22 18:58:52 -07004039// --- InputDispatcher::Connection ---
4040
Jeff Brown928e0542011-01-10 11:17:36 -08004041InputDispatcher::Connection::Connection(const sp<InputChannel>& inputChannel,
Jeff Browncc4f7db2011-08-30 20:34:48 -07004042 const sp<InputWindowHandle>& inputWindowHandle, bool monitor) :
Jeff Brown928e0542011-01-10 11:17:36 -08004043 status(STATUS_NORMAL), inputChannel(inputChannel), inputWindowHandle(inputWindowHandle),
Jeff Browncc4f7db2011-08-30 20:34:48 -07004044 monitor(monitor),
Jeff Brownd1c48a02012-02-06 19:12:47 -08004045 inputPublisher(inputChannel), inputPublisherBlocked(false) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07004046}
4047
4048InputDispatcher::Connection::~Connection() {
4049}
4050
Jeff Brown481c1572012-03-09 14:41:15 -08004051const char* InputDispatcher::Connection::getWindowName() const {
4052 if (inputWindowHandle != NULL) {
4053 return inputWindowHandle->getName().string();
4054 }
4055 if (monitor) {
4056 return "monitor";
4057 }
4058 return "?";
4059}
4060
Jeff Brown9c3cda02010-06-15 01:31:58 -07004061const char* InputDispatcher::Connection::getStatusLabel() const {
4062 switch (status) {
4063 case STATUS_NORMAL:
4064 return "NORMAL";
4065
4066 case STATUS_BROKEN:
4067 return "BROKEN";
4068
Jeff Brown9c3cda02010-06-15 01:31:58 -07004069 case STATUS_ZOMBIE:
4070 return "ZOMBIE";
4071
4072 default:
4073 return "UNKNOWN";
4074 }
4075}
4076
Jeff Brown072ec962012-02-07 14:46:57 -08004077InputDispatcher::DispatchEntry* InputDispatcher::Connection::findWaitQueueEntry(uint32_t seq) {
4078 for (DispatchEntry* entry = waitQueue.head; entry != NULL; entry = entry->next) {
4079 if (entry->seq == seq) {
4080 return entry;
4081 }
4082 }
4083 return NULL;
4084}
4085
Jeff Brownb88102f2010-09-08 11:49:43 -07004086
Jeff Brown9c3cda02010-06-15 01:31:58 -07004087// --- InputDispatcher::CommandEntry ---
4088
Jeff Brownac386072011-07-20 15:19:50 -07004089InputDispatcher::CommandEntry::CommandEntry(Command command) :
Jeff Brown072ec962012-02-07 14:46:57 -08004090 command(command), eventTime(0), keyEntry(NULL), userActivityEventType(0),
4091 seq(0), handled(false) {
Jeff Brown9c3cda02010-06-15 01:31:58 -07004092}
4093
4094InputDispatcher::CommandEntry::~CommandEntry() {
4095}
4096
Jeff Brown46b9ac02010-04-22 18:58:52 -07004097
Jeff Brown01ce2e92010-09-26 22:20:12 -07004098// --- InputDispatcher::TouchState ---
4099
4100InputDispatcher::TouchState::TouchState() :
Jeff Brown58a2da82011-01-25 16:02:22 -08004101 down(false), split(false), deviceId(-1), source(0) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07004102}
4103
4104InputDispatcher::TouchState::~TouchState() {
4105}
4106
4107void InputDispatcher::TouchState::reset() {
4108 down = false;
4109 split = false;
Jeff Brown95712852011-01-04 19:41:59 -08004110 deviceId = -1;
Jeff Brown58a2da82011-01-25 16:02:22 -08004111 source = 0;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004112 windows.clear();
4113}
4114
4115void InputDispatcher::TouchState::copyFrom(const TouchState& other) {
4116 down = other.down;
4117 split = other.split;
Jeff Brown95712852011-01-04 19:41:59 -08004118 deviceId = other.deviceId;
Jeff Brown58a2da82011-01-25 16:02:22 -08004119 source = other.source;
Jeff Brown9302c872011-07-13 22:51:29 -07004120 windows = other.windows;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004121}
4122
Jeff Brown9302c872011-07-13 22:51:29 -07004123void InputDispatcher::TouchState::addOrUpdateWindow(const sp<InputWindowHandle>& windowHandle,
Jeff Brown01ce2e92010-09-26 22:20:12 -07004124 int32_t targetFlags, BitSet32 pointerIds) {
4125 if (targetFlags & InputTarget::FLAG_SPLIT) {
4126 split = true;
4127 }
4128
4129 for (size_t i = 0; i < windows.size(); i++) {
4130 TouchedWindow& touchedWindow = windows.editItemAt(i);
Jeff Brown9302c872011-07-13 22:51:29 -07004131 if (touchedWindow.windowHandle == windowHandle) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07004132 touchedWindow.targetFlags |= targetFlags;
Jeff Brown98db5fa2011-06-08 15:37:10 -07004133 if (targetFlags & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
4134 touchedWindow.targetFlags &= ~InputTarget::FLAG_DISPATCH_AS_IS;
4135 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07004136 touchedWindow.pointerIds.value |= pointerIds.value;
4137 return;
4138 }
4139 }
4140
4141 windows.push();
4142
4143 TouchedWindow& touchedWindow = windows.editTop();
Jeff Brown9302c872011-07-13 22:51:29 -07004144 touchedWindow.windowHandle = windowHandle;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004145 touchedWindow.targetFlags = targetFlags;
4146 touchedWindow.pointerIds = pointerIds;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004147}
4148
Jeff Browna032cc02011-03-07 16:56:21 -08004149void InputDispatcher::TouchState::filterNonAsIsTouchWindows() {
Jeff Brown01ce2e92010-09-26 22:20:12 -07004150 for (size_t i = 0 ; i < windows.size(); ) {
Jeff Browna032cc02011-03-07 16:56:21 -08004151 TouchedWindow& window = windows.editItemAt(i);
Jeff Brown98db5fa2011-06-08 15:37:10 -07004152 if (window.targetFlags & (InputTarget::FLAG_DISPATCH_AS_IS
4153 | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER)) {
Jeff Browna032cc02011-03-07 16:56:21 -08004154 window.targetFlags &= ~InputTarget::FLAG_DISPATCH_MASK;
4155 window.targetFlags |= InputTarget::FLAG_DISPATCH_AS_IS;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004156 i += 1;
Jeff Browna032cc02011-03-07 16:56:21 -08004157 } else {
4158 windows.removeAt(i);
Jeff Brown01ce2e92010-09-26 22:20:12 -07004159 }
4160 }
4161}
4162
Jeff Brown9302c872011-07-13 22:51:29 -07004163sp<InputWindowHandle> InputDispatcher::TouchState::getFirstForegroundWindowHandle() const {
Jeff Brown01ce2e92010-09-26 22:20:12 -07004164 for (size_t i = 0; i < windows.size(); i++) {
Jeff Brown98db5fa2011-06-08 15:37:10 -07004165 const TouchedWindow& window = windows.itemAt(i);
4166 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
Jeff Brown9302c872011-07-13 22:51:29 -07004167 return window.windowHandle;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004168 }
4169 }
4170 return NULL;
4171}
4172
Jeff Brown98db5fa2011-06-08 15:37:10 -07004173bool InputDispatcher::TouchState::isSlippery() const {
4174 // Must have exactly one foreground window.
4175 bool haveSlipperyForegroundWindow = false;
4176 for (size_t i = 0; i < windows.size(); i++) {
4177 const TouchedWindow& window = windows.itemAt(i);
4178 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
Jeff Browncc4f7db2011-08-30 20:34:48 -07004179 if (haveSlipperyForegroundWindow
4180 || !(window.windowHandle->getInfo()->layoutParamsFlags
4181 & InputWindowInfo::FLAG_SLIPPERY)) {
Jeff Brown98db5fa2011-06-08 15:37:10 -07004182 return false;
4183 }
4184 haveSlipperyForegroundWindow = true;
4185 }
4186 }
4187 return haveSlipperyForegroundWindow;
4188}
4189
Jeff Brown01ce2e92010-09-26 22:20:12 -07004190
Jeff Brown46b9ac02010-04-22 18:58:52 -07004191// --- InputDispatcherThread ---
4192
4193InputDispatcherThread::InputDispatcherThread(const sp<InputDispatcherInterface>& dispatcher) :
4194 Thread(/*canCallJava*/ true), mDispatcher(dispatcher) {
4195}
4196
4197InputDispatcherThread::~InputDispatcherThread() {
4198}
4199
4200bool InputDispatcherThread::threadLoop() {
4201 mDispatcher->dispatchOnce();
4202 return true;
4203}
4204
4205} // namespace android