blob: ada9d9e8f0e7d0d11ccbee2768873e684973b5fe [file] [log] [blame]
Jeff Brownb4ff35d2011-01-02 16:37:43 -08001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Jeff Brown46b9ac02010-04-22 18:58:52 -070017#define LOG_TAG "InputDispatcher"
Jeff Brown481c1572012-03-09 14:41:15 -080018#define ATRACE_TAG ATRACE_TAG_INPUT
Jeff Brown46b9ac02010-04-22 18:58:52 -070019
20//#define LOG_NDEBUG 0
21
22// Log detailed debug messages about each inbound event notification to the dispatcher.
Jeff Brown349703e2010-06-22 01:27:15 -070023#define DEBUG_INBOUND_EVENT_DETAILS 0
Jeff Brown46b9ac02010-04-22 18:58:52 -070024
25// Log detailed debug messages about each outbound event processed by the dispatcher.
Jeff Brown349703e2010-06-22 01:27:15 -070026#define DEBUG_OUTBOUND_EVENT_DETAILS 0
Jeff Brown46b9ac02010-04-22 18:58:52 -070027
Jeff Brown46b9ac02010-04-22 18:58:52 -070028// Log debug messages about the dispatch cycle.
Jeff Brown349703e2010-06-22 01:27:15 -070029#define DEBUG_DISPATCH_CYCLE 0
Jeff Brown46b9ac02010-04-22 18:58:52 -070030
Jeff Brown9c3cda02010-06-15 01:31:58 -070031// Log debug messages about registrations.
Jeff Brown349703e2010-06-22 01:27:15 -070032#define DEBUG_REGISTRATION 0
Jeff Brown9c3cda02010-06-15 01:31:58 -070033
Jeff Brown7fbdc842010-06-17 20:52:56 -070034// Log debug messages about input event injection.
Jeff Brown349703e2010-06-22 01:27:15 -070035#define DEBUG_INJECTION 0
Jeff Brown7fbdc842010-06-17 20:52:56 -070036
Jeff Brownb88102f2010-09-08 11:49:43 -070037// Log debug messages about input focus tracking.
38#define DEBUG_FOCUS 0
39
40// Log debug messages about the app switch latency optimization.
41#define DEBUG_APP_SWITCH 0
42
Jeff Browna032cc02011-03-07 16:56:21 -080043// Log debug messages about hover events.
44#define DEBUG_HOVER 0
45
Jeff Brownb4ff35d2011-01-02 16:37:43 -080046#include "InputDispatcher.h"
47
Jeff Brown481c1572012-03-09 14:41:15 -080048#include <utils/Trace.h>
Jeff Brown46b9ac02010-04-22 18:58:52 -070049#include <cutils/log.h>
Mathias Agopianb93a03f82012-02-17 15:34:57 -080050#include <androidfw/PowerManager.h>
Jeff Brown46b9ac02010-04-22 18:58:52 -070051
52#include <stddef.h>
53#include <unistd.h>
Jeff Brown46b9ac02010-04-22 18:58:52 -070054#include <errno.h>
55#include <limits.h>
Jeff Brown46b9ac02010-04-22 18:58:52 -070056
Jeff Brownf2f48712010-10-01 17:46:21 -070057#define INDENT " "
58#define INDENT2 " "
59
Jeff Brown46b9ac02010-04-22 18:58:52 -070060namespace android {
61
Jeff Brownb88102f2010-09-08 11:49:43 -070062// Default input dispatching timeout if there is no focused application or paused window
63// from which to determine an appropriate dispatching timeout.
64const nsecs_t DEFAULT_INPUT_DISPATCHING_TIMEOUT = 5000 * 1000000LL; // 5 sec
65
66// Amount of time to allow for all pending events to be processed when an app switch
67// key is on the way. This is used to preempt input dispatch and drop input events
68// when an application takes too long to respond and the user has pressed an app switch key.
69const nsecs_t APP_SWITCH_TIMEOUT = 500 * 1000000LL; // 0.5sec
70
Jeff Brown928e0542011-01-10 11:17:36 -080071// Amount of time to allow for an event to be dispatched (measured since its eventTime)
72// before considering it stale and dropping it.
73const nsecs_t STALE_EVENT_TIMEOUT = 10000 * 1000000LL; // 10sec
74
Jeff Brownd1c48a02012-02-06 19:12:47 -080075// Amount of time to allow touch events to be streamed out to a connection before requiring
76// that the first event be finished. This value extends the ANR timeout by the specified
77// amount. For example, if streaming is allowed to get ahead by one second relative to the
78// queue of waiting unfinished events, then ANRs will similarly be delayed by one second.
79const nsecs_t STREAM_AHEAD_EVENT_TIMEOUT = 500 * 1000000LL; // 0.5sec
80
Jeff Brown46b9ac02010-04-22 18:58:52 -070081
Jeff Brown7fbdc842010-06-17 20:52:56 -070082static inline nsecs_t now() {
83 return systemTime(SYSTEM_TIME_MONOTONIC);
84}
85
Jeff Brownb88102f2010-09-08 11:49:43 -070086static inline const char* toString(bool value) {
87 return value ? "true" : "false";
88}
89
Jeff Brown01ce2e92010-09-26 22:20:12 -070090static inline int32_t getMotionEventActionPointerIndex(int32_t action) {
91 return (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK)
92 >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
93}
94
95static bool isValidKeyAction(int32_t action) {
96 switch (action) {
97 case AKEY_EVENT_ACTION_DOWN:
98 case AKEY_EVENT_ACTION_UP:
99 return true;
100 default:
101 return false;
102 }
103}
104
105static bool validateKeyEvent(int32_t action) {
106 if (! isValidKeyAction(action)) {
Steve Block3762c312012-01-06 19:20:56 +0000107 ALOGE("Key event has invalid action code 0x%x", action);
Jeff Brown01ce2e92010-09-26 22:20:12 -0700108 return false;
109 }
110 return true;
111}
112
Jeff Brownb6997262010-10-08 22:31:17 -0700113static bool isValidMotionAction(int32_t action, size_t pointerCount) {
Jeff Brown01ce2e92010-09-26 22:20:12 -0700114 switch (action & AMOTION_EVENT_ACTION_MASK) {
115 case AMOTION_EVENT_ACTION_DOWN:
116 case AMOTION_EVENT_ACTION_UP:
117 case AMOTION_EVENT_ACTION_CANCEL:
118 case AMOTION_EVENT_ACTION_MOVE:
Jeff Brown01ce2e92010-09-26 22:20:12 -0700119 case AMOTION_EVENT_ACTION_OUTSIDE:
Jeff Browna032cc02011-03-07 16:56:21 -0800120 case AMOTION_EVENT_ACTION_HOVER_ENTER:
Jeff Browncc0c1592011-02-19 05:07:28 -0800121 case AMOTION_EVENT_ACTION_HOVER_MOVE:
Jeff Browna032cc02011-03-07 16:56:21 -0800122 case AMOTION_EVENT_ACTION_HOVER_EXIT:
Jeff Brown33bbfd22011-02-24 20:55:35 -0800123 case AMOTION_EVENT_ACTION_SCROLL:
Jeff Brown01ce2e92010-09-26 22:20:12 -0700124 return true;
Jeff Brownb6997262010-10-08 22:31:17 -0700125 case AMOTION_EVENT_ACTION_POINTER_DOWN:
126 case AMOTION_EVENT_ACTION_POINTER_UP: {
127 int32_t index = getMotionEventActionPointerIndex(action);
128 return index >= 0 && size_t(index) < pointerCount;
129 }
Jeff Brown01ce2e92010-09-26 22:20:12 -0700130 default:
131 return false;
132 }
133}
134
135static bool validateMotionEvent(int32_t action, size_t pointerCount,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700136 const PointerProperties* pointerProperties) {
Jeff Brownb6997262010-10-08 22:31:17 -0700137 if (! isValidMotionAction(action, pointerCount)) {
Steve Block3762c312012-01-06 19:20:56 +0000138 ALOGE("Motion event has invalid action code 0x%x", action);
Jeff Brown01ce2e92010-09-26 22:20:12 -0700139 return false;
140 }
141 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Steve Block3762c312012-01-06 19:20:56 +0000142 ALOGE("Motion event has invalid pointer count %d; value must be between 1 and %d.",
Jeff Brown01ce2e92010-09-26 22:20:12 -0700143 pointerCount, MAX_POINTERS);
144 return false;
145 }
Jeff Brownc3db8582010-10-20 15:33:38 -0700146 BitSet32 pointerIdBits;
Jeff Brown01ce2e92010-09-26 22:20:12 -0700147 for (size_t i = 0; i < pointerCount; i++) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700148 int32_t id = pointerProperties[i].id;
Jeff Brownc3db8582010-10-20 15:33:38 -0700149 if (id < 0 || id > MAX_POINTER_ID) {
Steve Block3762c312012-01-06 19:20:56 +0000150 ALOGE("Motion event has invalid pointer id %d; value must be between 0 and %d",
Jeff Brownc3db8582010-10-20 15:33:38 -0700151 id, MAX_POINTER_ID);
Jeff Brown01ce2e92010-09-26 22:20:12 -0700152 return false;
153 }
Jeff Brownc3db8582010-10-20 15:33:38 -0700154 if (pointerIdBits.hasBit(id)) {
Steve Block3762c312012-01-06 19:20:56 +0000155 ALOGE("Motion event has duplicate pointer id %d", id);
Jeff Brownc3db8582010-10-20 15:33:38 -0700156 return false;
157 }
158 pointerIdBits.markBit(id);
Jeff Brown01ce2e92010-09-26 22:20:12 -0700159 }
160 return true;
161}
162
Jeff Brownfbf09772011-01-16 14:06:57 -0800163static void dumpRegion(String8& dump, const SkRegion& region) {
164 if (region.isEmpty()) {
165 dump.append("<empty>");
166 return;
167 }
168
169 bool first = true;
170 for (SkRegion::Iterator it(region); !it.done(); it.next()) {
171 if (first) {
172 first = false;
173 } else {
174 dump.append("|");
175 }
176 const SkIRect& rect = it.rect();
177 dump.appendFormat("[%d,%d][%d,%d]", rect.fLeft, rect.fTop, rect.fRight, rect.fBottom);
178 }
179}
180
Jeff Brownb88102f2010-09-08 11:49:43 -0700181
Jeff Brown46b9ac02010-04-22 18:58:52 -0700182// --- InputDispatcher ---
183
Jeff Brown9c3cda02010-06-15 01:31:58 -0700184InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy) :
Jeff Brownb88102f2010-09-08 11:49:43 -0700185 mPolicy(policy),
Jeff Brown928e0542011-01-10 11:17:36 -0800186 mPendingEvent(NULL), mAppSwitchSawKeyDown(false), mAppSwitchDueTime(LONG_LONG_MAX),
187 mNextUnblockedEvent(NULL),
Jeff Brownc042ee22012-05-08 13:03:42 -0700188 mDispatchEnabled(false), mDispatchFrozen(false), mInputFilterEnabled(false),
Jeff Brown9302c872011-07-13 22:51:29 -0700189 mInputTargetWaitCause(INPUT_TARGET_WAIT_CAUSE_NONE) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -0700190 mLooper = new Looper(false);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700191
Jeff Brown46b9ac02010-04-22 18:58:52 -0700192 mKeyRepeatState.lastKeyEntry = NULL;
Jeff Brown9c3cda02010-06-15 01:31:58 -0700193
Jeff Brown214eaf42011-05-26 19:17:02 -0700194 policy->getDispatcherConfiguration(&mConfig);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700195}
196
197InputDispatcher::~InputDispatcher() {
Jeff Brownb88102f2010-09-08 11:49:43 -0700198 { // acquire lock
199 AutoMutex _l(mLock);
200
201 resetKeyRepeatLocked();
Jeff Brown54a18252010-09-16 14:07:33 -0700202 releasePendingEventLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -0700203 drainInboundQueueLocked();
204 }
Jeff Brown46b9ac02010-04-22 18:58:52 -0700205
Jeff Browncbee6d62012-02-03 20:11:27 -0800206 while (mConnectionsByFd.size() != 0) {
207 unregisterInputChannel(mConnectionsByFd.valueAt(0)->inputChannel);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700208 }
Jeff Brown46b9ac02010-04-22 18:58:52 -0700209}
210
211void InputDispatcher::dispatchOnce() {
Jeff Brown46b9ac02010-04-22 18:58:52 -0700212 nsecs_t nextWakeupTime = LONG_LONG_MAX;
213 { // acquire lock
214 AutoMutex _l(mLock);
Jeff Brown112b5f52012-01-27 17:32:06 -0800215 mDispatcherIsAliveCondition.broadcast();
216
Jeff Brown214eaf42011-05-26 19:17:02 -0700217 dispatchOnceInnerLocked(&nextWakeupTime);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700218
Jeff Brownb88102f2010-09-08 11:49:43 -0700219 if (runCommandsLockedInterruptible()) {
220 nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
Jeff Brown46b9ac02010-04-22 18:58:52 -0700221 }
Jeff Brown46b9ac02010-04-22 18:58:52 -0700222 } // release lock
223
Jeff Brownb88102f2010-09-08 11:49:43 -0700224 // Wait for callback or timeout or wake. (make sure we round up, not down)
225 nsecs_t currentTime = now();
Jeff Brownaa3855d2011-03-17 01:34:19 -0700226 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
Jeff Brown4fe6c3e2010-09-13 23:17:30 -0700227 mLooper->pollOnce(timeoutMillis);
Jeff Brownb88102f2010-09-08 11:49:43 -0700228}
229
Jeff Brown214eaf42011-05-26 19:17:02 -0700230void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700231 nsecs_t currentTime = now();
232
233 // Reset the key repeat timer whenever we disallow key events, even if the next event
234 // is not a key. This is to ensure that we abort a key repeat if the device is just coming
235 // out of sleep.
Jeff Brown214eaf42011-05-26 19:17:02 -0700236 if (!mPolicy->isKeyRepeatEnabled()) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700237 resetKeyRepeatLocked();
238 }
239
Jeff Brownb88102f2010-09-08 11:49:43 -0700240 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
241 if (mDispatchFrozen) {
242#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +0000243 ALOGD("Dispatch frozen. Waiting some more.");
Jeff Brownb88102f2010-09-08 11:49:43 -0700244#endif
245 return;
246 }
247
248 // Optimize latency of app switches.
249 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
250 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
251 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
252 if (mAppSwitchDueTime < *nextWakeupTime) {
253 *nextWakeupTime = mAppSwitchDueTime;
254 }
255
Jeff Brownb88102f2010-09-08 11:49:43 -0700256 // Ready to start a new event.
257 // If we don't already have a pending event, go grab one.
258 if (! mPendingEvent) {
259 if (mInboundQueue.isEmpty()) {
260 if (isAppSwitchDue) {
261 // The inbound queue is empty so the app switch key we were waiting
262 // for will never arrive. Stop waiting for it.
263 resetPendingAppSwitchLocked(false);
264 isAppSwitchDue = false;
265 }
266
267 // Synthesize a key repeat if appropriate.
268 if (mKeyRepeatState.lastKeyEntry) {
269 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
Jeff Brown214eaf42011-05-26 19:17:02 -0700270 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700271 } else {
272 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
273 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
274 }
275 }
276 }
Jeff Browncc4f7db2011-08-30 20:34:48 -0700277
278 // Nothing to do if there is no pending event.
Jeff Browne9bb9be2012-02-06 15:47:55 -0800279 if (!mPendingEvent) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700280 return;
281 }
282 } else {
283 // Inbound queue has at least one entry.
Jeff Browne9bb9be2012-02-06 15:47:55 -0800284 mPendingEvent = mInboundQueue.dequeueAtHead();
Jeff Brown481c1572012-03-09 14:41:15 -0800285 traceInboundQueueLengthLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -0700286 }
Jeff Browne2fe69e2010-10-18 13:21:23 -0700287
288 // Poke user activity for this event.
289 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
290 pokeUserActivityLocked(mPendingEvent);
291 }
Jeff Browne9bb9be2012-02-06 15:47:55 -0800292
293 // Get ready to dispatch the event.
294 resetANRTimeoutsLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -0700295 }
296
297 // Now we have an event to dispatch.
Jeff Brown928e0542011-01-10 11:17:36 -0800298 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Steve Blockec193de2012-01-09 18:35:44 +0000299 ALOG_ASSERT(mPendingEvent != NULL);
Jeff Brown54a18252010-09-16 14:07:33 -0700300 bool done = false;
Jeff Brownb6997262010-10-08 22:31:17 -0700301 DropReason dropReason = DROP_REASON_NOT_DROPPED;
302 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
303 dropReason = DROP_REASON_POLICY;
304 } else if (!mDispatchEnabled) {
305 dropReason = DROP_REASON_DISABLED;
306 }
Jeff Brown928e0542011-01-10 11:17:36 -0800307
308 if (mNextUnblockedEvent == mPendingEvent) {
309 mNextUnblockedEvent = NULL;
310 }
311
Jeff Brownb88102f2010-09-08 11:49:43 -0700312 switch (mPendingEvent->type) {
313 case EventEntry::TYPE_CONFIGURATION_CHANGED: {
314 ConfigurationChangedEntry* typedEntry =
315 static_cast<ConfigurationChangedEntry*>(mPendingEvent);
Jeff Brown54a18252010-09-16 14:07:33 -0700316 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Jeff Brownb6997262010-10-08 22:31:17 -0700317 dropReason = DROP_REASON_NOT_DROPPED; // configuration changes are never dropped
Jeff Brownb88102f2010-09-08 11:49:43 -0700318 break;
319 }
320
Jeff Brown65fd2512011-08-18 11:20:58 -0700321 case EventEntry::TYPE_DEVICE_RESET: {
322 DeviceResetEntry* typedEntry =
323 static_cast<DeviceResetEntry*>(mPendingEvent);
324 done = dispatchDeviceResetLocked(currentTime, typedEntry);
325 dropReason = DROP_REASON_NOT_DROPPED; // device resets are never dropped
326 break;
327 }
328
Jeff Brownb88102f2010-09-08 11:49:43 -0700329 case EventEntry::TYPE_KEY: {
330 KeyEntry* typedEntry = static_cast<KeyEntry*>(mPendingEvent);
Jeff Brownb6997262010-10-08 22:31:17 -0700331 if (isAppSwitchDue) {
332 if (isAppSwitchKeyEventLocked(typedEntry)) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700333 resetPendingAppSwitchLocked(true);
Jeff Brownb6997262010-10-08 22:31:17 -0700334 isAppSwitchDue = false;
335 } else if (dropReason == DROP_REASON_NOT_DROPPED) {
336 dropReason = DROP_REASON_APP_SWITCH;
Jeff Brownb88102f2010-09-08 11:49:43 -0700337 }
338 }
Jeff Brown928e0542011-01-10 11:17:36 -0800339 if (dropReason == DROP_REASON_NOT_DROPPED
340 && isStaleEventLocked(currentTime, typedEntry)) {
341 dropReason = DROP_REASON_STALE;
342 }
343 if (dropReason == DROP_REASON_NOT_DROPPED && mNextUnblockedEvent) {
344 dropReason = DROP_REASON_BLOCKED;
345 }
Jeff Brown214eaf42011-05-26 19:17:02 -0700346 done = dispatchKeyLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700347 break;
348 }
349
350 case EventEntry::TYPE_MOTION: {
351 MotionEntry* typedEntry = static_cast<MotionEntry*>(mPendingEvent);
Jeff Brownb6997262010-10-08 22:31:17 -0700352 if (dropReason == DROP_REASON_NOT_DROPPED && isAppSwitchDue) {
353 dropReason = DROP_REASON_APP_SWITCH;
Jeff Brownb88102f2010-09-08 11:49:43 -0700354 }
Jeff Brown928e0542011-01-10 11:17:36 -0800355 if (dropReason == DROP_REASON_NOT_DROPPED
356 && isStaleEventLocked(currentTime, typedEntry)) {
357 dropReason = DROP_REASON_STALE;
358 }
359 if (dropReason == DROP_REASON_NOT_DROPPED && mNextUnblockedEvent) {
360 dropReason = DROP_REASON_BLOCKED;
361 }
Jeff Brownb6997262010-10-08 22:31:17 -0700362 done = dispatchMotionLocked(currentTime, typedEntry,
Jeff Browne20c9e02010-10-11 14:20:19 -0700363 &dropReason, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700364 break;
365 }
366
367 default:
Steve Blockec193de2012-01-09 18:35:44 +0000368 ALOG_ASSERT(false);
Jeff Brownb88102f2010-09-08 11:49:43 -0700369 break;
370 }
371
Jeff Brown54a18252010-09-16 14:07:33 -0700372 if (done) {
Jeff Brownb6997262010-10-08 22:31:17 -0700373 if (dropReason != DROP_REASON_NOT_DROPPED) {
374 dropInboundEventLocked(mPendingEvent, dropReason);
375 }
376
Jeff Brown54a18252010-09-16 14:07:33 -0700377 releasePendingEventLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -0700378 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
379 }
380}
381
382bool InputDispatcher::enqueueInboundEventLocked(EventEntry* entry) {
383 bool needWake = mInboundQueue.isEmpty();
384 mInboundQueue.enqueueAtTail(entry);
Jeff Brown481c1572012-03-09 14:41:15 -0800385 traceInboundQueueLengthLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -0700386
387 switch (entry->type) {
Jeff Brownb6997262010-10-08 22:31:17 -0700388 case EventEntry::TYPE_KEY: {
Jeff Brown928e0542011-01-10 11:17:36 -0800389 // Optimize app switch latency.
390 // If the application takes too long to catch up then we drop all events preceding
391 // the app switch key.
Jeff Brownb6997262010-10-08 22:31:17 -0700392 KeyEntry* keyEntry = static_cast<KeyEntry*>(entry);
393 if (isAppSwitchKeyEventLocked(keyEntry)) {
394 if (keyEntry->action == AKEY_EVENT_ACTION_DOWN) {
395 mAppSwitchSawKeyDown = true;
396 } else if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
397 if (mAppSwitchSawKeyDown) {
398#if DEBUG_APP_SWITCH
Steve Block5baa3a62011-12-20 16:23:08 +0000399 ALOGD("App switch is pending!");
Jeff Brownb6997262010-10-08 22:31:17 -0700400#endif
401 mAppSwitchDueTime = keyEntry->eventTime + APP_SWITCH_TIMEOUT;
402 mAppSwitchSawKeyDown = false;
403 needWake = true;
404 }
405 }
406 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700407 break;
408 }
Jeff Brown928e0542011-01-10 11:17:36 -0800409
410 case EventEntry::TYPE_MOTION: {
411 // Optimize case where the current application is unresponsive and the user
412 // decides to touch a window in a different application.
413 // If the application takes too long to catch up then we drop all events preceding
414 // the touch into the other window.
415 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
Jeff Brown33bbfd22011-02-24 20:55:35 -0800416 if (motionEntry->action == AMOTION_EVENT_ACTION_DOWN
Jeff Brown928e0542011-01-10 11:17:36 -0800417 && (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER)
418 && mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY
Jeff Brown9302c872011-07-13 22:51:29 -0700419 && mInputTargetWaitApplicationHandle != NULL) {
Jeff Brown3241b6b2012-02-03 15:08:02 -0800420 int32_t x = int32_t(motionEntry->pointerCoords[0].
Jeff Brownebbd5d12011-02-17 13:01:34 -0800421 getAxisValue(AMOTION_EVENT_AXIS_X));
Jeff Brown3241b6b2012-02-03 15:08:02 -0800422 int32_t y = int32_t(motionEntry->pointerCoords[0].
Jeff Brownebbd5d12011-02-17 13:01:34 -0800423 getAxisValue(AMOTION_EVENT_AXIS_Y));
Jeff Brown9302c872011-07-13 22:51:29 -0700424 sp<InputWindowHandle> touchedWindowHandle = findTouchedWindowAtLocked(x, y);
425 if (touchedWindowHandle != NULL
426 && touchedWindowHandle->inputApplicationHandle
427 != mInputTargetWaitApplicationHandle) {
Jeff Brown928e0542011-01-10 11:17:36 -0800428 // User touched a different application than the one we are waiting on.
429 // Flag the event, and start pruning the input queue.
430 mNextUnblockedEvent = motionEntry;
431 needWake = true;
432 }
433 }
434 break;
435 }
Jeff Brownb6997262010-10-08 22:31:17 -0700436 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700437
438 return needWake;
439}
440
Jeff Brown9302c872011-07-13 22:51:29 -0700441sp<InputWindowHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t x, int32_t y) {
Jeff Brown928e0542011-01-10 11:17:36 -0800442 // Traverse windows from front to back to find touched window.
Jeff Brown9302c872011-07-13 22:51:29 -0700443 size_t numWindows = mWindowHandles.size();
Jeff Brown928e0542011-01-10 11:17:36 -0800444 for (size_t i = 0; i < numWindows; i++) {
Jeff Brown9302c872011-07-13 22:51:29 -0700445 sp<InputWindowHandle> windowHandle = mWindowHandles.itemAt(i);
Jeff Browncc4f7db2011-08-30 20:34:48 -0700446 const InputWindowInfo* windowInfo = windowHandle->getInfo();
447 int32_t flags = windowInfo->layoutParamsFlags;
Jeff Brown928e0542011-01-10 11:17:36 -0800448
Jeff Browncc4f7db2011-08-30 20:34:48 -0700449 if (windowInfo->visible) {
450 if (!(flags & InputWindowInfo::FLAG_NOT_TOUCHABLE)) {
451 bool isTouchModal = (flags & (InputWindowInfo::FLAG_NOT_FOCUSABLE
452 | InputWindowInfo::FLAG_NOT_TOUCH_MODAL)) == 0;
453 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
Jeff Brown928e0542011-01-10 11:17:36 -0800454 // Found window.
Jeff Brown9302c872011-07-13 22:51:29 -0700455 return windowHandle;
Jeff Brown928e0542011-01-10 11:17:36 -0800456 }
457 }
458 }
459
Jeff Browncc4f7db2011-08-30 20:34:48 -0700460 if (flags & InputWindowInfo::FLAG_SYSTEM_ERROR) {
Jeff Brown928e0542011-01-10 11:17:36 -0800461 // Error window is on top but not visible, so touch is dropped.
462 return NULL;
463 }
464 }
465 return NULL;
466}
467
Jeff Brownb6997262010-10-08 22:31:17 -0700468void InputDispatcher::dropInboundEventLocked(EventEntry* entry, DropReason dropReason) {
469 const char* reason;
470 switch (dropReason) {
471 case DROP_REASON_POLICY:
Jeff Browne20c9e02010-10-11 14:20:19 -0700472#if DEBUG_INBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +0000473 ALOGD("Dropped event because policy consumed it.");
Jeff Browne20c9e02010-10-11 14:20:19 -0700474#endif
Jeff Brown3122e442010-10-11 23:32:49 -0700475 reason = "inbound event was dropped because the policy consumed it";
Jeff Brownb6997262010-10-08 22:31:17 -0700476 break;
477 case DROP_REASON_DISABLED:
Steve Block6215d3f2012-01-04 20:05:49 +0000478 ALOGI("Dropped event because input dispatch is disabled.");
Jeff Brownb6997262010-10-08 22:31:17 -0700479 reason = "inbound event was dropped because input dispatch is disabled";
480 break;
481 case DROP_REASON_APP_SWITCH:
Steve Block6215d3f2012-01-04 20:05:49 +0000482 ALOGI("Dropped event because of pending overdue app switch.");
Jeff Brownb6997262010-10-08 22:31:17 -0700483 reason = "inbound event was dropped because of pending overdue app switch";
484 break;
Jeff Brown928e0542011-01-10 11:17:36 -0800485 case DROP_REASON_BLOCKED:
Steve Block6215d3f2012-01-04 20:05:49 +0000486 ALOGI("Dropped event because the current application is not responding and the user "
Jeff Brown81346812011-06-28 20:08:48 -0700487 "has started interacting with a different application.");
Jeff Brown928e0542011-01-10 11:17:36 -0800488 reason = "inbound event was dropped because the current application is not responding "
Jeff Brown81346812011-06-28 20:08:48 -0700489 "and the user has started interacting with a different application";
Jeff Brown928e0542011-01-10 11:17:36 -0800490 break;
491 case DROP_REASON_STALE:
Steve Block6215d3f2012-01-04 20:05:49 +0000492 ALOGI("Dropped event because it is stale.");
Jeff Brown928e0542011-01-10 11:17:36 -0800493 reason = "inbound event was dropped because it is stale";
494 break;
Jeff Brownb6997262010-10-08 22:31:17 -0700495 default:
Steve Blockec193de2012-01-09 18:35:44 +0000496 ALOG_ASSERT(false);
Jeff Brownb6997262010-10-08 22:31:17 -0700497 return;
498 }
499
500 switch (entry->type) {
Jeff Brownda3d5a92011-03-29 15:11:34 -0700501 case EventEntry::TYPE_KEY: {
502 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
503 synthesizeCancelationEventsForAllConnectionsLocked(options);
Jeff Brownb6997262010-10-08 22:31:17 -0700504 break;
Jeff Brownda3d5a92011-03-29 15:11:34 -0700505 }
Jeff Brownb6997262010-10-08 22:31:17 -0700506 case EventEntry::TYPE_MOTION: {
507 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
508 if (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) {
Jeff Brownda3d5a92011-03-29 15:11:34 -0700509 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
510 synthesizeCancelationEventsForAllConnectionsLocked(options);
Jeff Brownb6997262010-10-08 22:31:17 -0700511 } else {
Jeff Brownda3d5a92011-03-29 15:11:34 -0700512 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
513 synthesizeCancelationEventsForAllConnectionsLocked(options);
Jeff Brownb6997262010-10-08 22:31:17 -0700514 }
515 break;
516 }
517 }
518}
519
520bool InputDispatcher::isAppSwitchKeyCode(int32_t keyCode) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700521 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL;
522}
523
Jeff Brownb6997262010-10-08 22:31:17 -0700524bool InputDispatcher::isAppSwitchKeyEventLocked(KeyEntry* keyEntry) {
525 return ! (keyEntry->flags & AKEY_EVENT_FLAG_CANCELED)
526 && isAppSwitchKeyCode(keyEntry->keyCode)
Jeff Browne20c9e02010-10-11 14:20:19 -0700527 && (keyEntry->policyFlags & POLICY_FLAG_TRUSTED)
Jeff Brownb6997262010-10-08 22:31:17 -0700528 && (keyEntry->policyFlags & POLICY_FLAG_PASS_TO_USER);
529}
530
Jeff Brownb88102f2010-09-08 11:49:43 -0700531bool InputDispatcher::isAppSwitchPendingLocked() {
532 return mAppSwitchDueTime != LONG_LONG_MAX;
533}
534
Jeff Brownb88102f2010-09-08 11:49:43 -0700535void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
536 mAppSwitchDueTime = LONG_LONG_MAX;
537
538#if DEBUG_APP_SWITCH
539 if (handled) {
Steve Block5baa3a62011-12-20 16:23:08 +0000540 ALOGD("App switch has arrived.");
Jeff Brownb88102f2010-09-08 11:49:43 -0700541 } else {
Steve Block5baa3a62011-12-20 16:23:08 +0000542 ALOGD("App switch was abandoned.");
Jeff Brownb88102f2010-09-08 11:49:43 -0700543 }
544#endif
Jeff Brown46b9ac02010-04-22 18:58:52 -0700545}
546
Jeff Brown928e0542011-01-10 11:17:36 -0800547bool InputDispatcher::isStaleEventLocked(nsecs_t currentTime, EventEntry* entry) {
548 return currentTime - entry->eventTime >= STALE_EVENT_TIMEOUT;
549}
550
Jeff Brown9c3cda02010-06-15 01:31:58 -0700551bool InputDispatcher::runCommandsLockedInterruptible() {
552 if (mCommandQueue.isEmpty()) {
553 return false;
554 }
Jeff Brown46b9ac02010-04-22 18:58:52 -0700555
Jeff Brown9c3cda02010-06-15 01:31:58 -0700556 do {
557 CommandEntry* commandEntry = mCommandQueue.dequeueAtHead();
558
559 Command command = commandEntry->command;
560 (this->*command)(commandEntry); // commands are implicitly 'LockedInterruptible'
561
Jeff Brown7fbdc842010-06-17 20:52:56 -0700562 commandEntry->connection.clear();
Jeff Brownac386072011-07-20 15:19:50 -0700563 delete commandEntry;
Jeff Brown9c3cda02010-06-15 01:31:58 -0700564 } while (! mCommandQueue.isEmpty());
565 return true;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700566}
567
Jeff Brown9c3cda02010-06-15 01:31:58 -0700568InputDispatcher::CommandEntry* InputDispatcher::postCommandLocked(Command command) {
Jeff Brownac386072011-07-20 15:19:50 -0700569 CommandEntry* commandEntry = new CommandEntry(command);
Jeff Brown9c3cda02010-06-15 01:31:58 -0700570 mCommandQueue.enqueueAtTail(commandEntry);
571 return commandEntry;
572}
573
Jeff Brownb88102f2010-09-08 11:49:43 -0700574void InputDispatcher::drainInboundQueueLocked() {
575 while (! mInboundQueue.isEmpty()) {
576 EventEntry* entry = mInboundQueue.dequeueAtHead();
Jeff Brown54a18252010-09-16 14:07:33 -0700577 releaseInboundEventLocked(entry);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700578 }
Jeff Brown481c1572012-03-09 14:41:15 -0800579 traceInboundQueueLengthLocked();
Jeff Brown46b9ac02010-04-22 18:58:52 -0700580}
581
Jeff Brown54a18252010-09-16 14:07:33 -0700582void InputDispatcher::releasePendingEventLocked() {
Jeff Brownb88102f2010-09-08 11:49:43 -0700583 if (mPendingEvent) {
Jeff Browne9bb9be2012-02-06 15:47:55 -0800584 resetANRTimeoutsLocked();
Jeff Brown54a18252010-09-16 14:07:33 -0700585 releaseInboundEventLocked(mPendingEvent);
Jeff Brownb88102f2010-09-08 11:49:43 -0700586 mPendingEvent = NULL;
587 }
588}
589
Jeff Brown54a18252010-09-16 14:07:33 -0700590void InputDispatcher::releaseInboundEventLocked(EventEntry* entry) {
Jeff Brown01ce2e92010-09-26 22:20:12 -0700591 InjectionState* injectionState = entry->injectionState;
592 if (injectionState && injectionState->injectionResult == INPUT_EVENT_INJECTION_PENDING) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700593#if DEBUG_DISPATCH_CYCLE
Steve Block5baa3a62011-12-20 16:23:08 +0000594 ALOGD("Injected inbound event was dropped.");
Jeff Brownb88102f2010-09-08 11:49:43 -0700595#endif
596 setInjectionResultLocked(entry, INPUT_EVENT_INJECTION_FAILED);
597 }
Jeff Brownabb4d442011-08-15 12:55:32 -0700598 if (entry == mNextUnblockedEvent) {
599 mNextUnblockedEvent = NULL;
600 }
Jeff Brownac386072011-07-20 15:19:50 -0700601 entry->release();
Jeff Brownb88102f2010-09-08 11:49:43 -0700602}
603
Jeff Brownb88102f2010-09-08 11:49:43 -0700604void InputDispatcher::resetKeyRepeatLocked() {
605 if (mKeyRepeatState.lastKeyEntry) {
Jeff Brownac386072011-07-20 15:19:50 -0700606 mKeyRepeatState.lastKeyEntry->release();
Jeff Brownb88102f2010-09-08 11:49:43 -0700607 mKeyRepeatState.lastKeyEntry = NULL;
608 }
609}
610
Jeff Brown214eaf42011-05-26 19:17:02 -0700611InputDispatcher::KeyEntry* InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
Jeff Brown349703e2010-06-22 01:27:15 -0700612 KeyEntry* entry = mKeyRepeatState.lastKeyEntry;
613
Jeff Brown349703e2010-06-22 01:27:15 -0700614 // Reuse the repeated key entry if it is otherwise unreferenced.
Jeff Browne20c9e02010-10-11 14:20:19 -0700615 uint32_t policyFlags = (entry->policyFlags & POLICY_FLAG_RAW_MASK)
616 | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700617 if (entry->refCount == 1) {
Jeff Brownac386072011-07-20 15:19:50 -0700618 entry->recycle();
Jeff Brown7fbdc842010-06-17 20:52:56 -0700619 entry->eventTime = currentTime;
Jeff Brown7fbdc842010-06-17 20:52:56 -0700620 entry->policyFlags = policyFlags;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700621 entry->repeatCount += 1;
622 } else {
Jeff Brownac386072011-07-20 15:19:50 -0700623 KeyEntry* newEntry = new KeyEntry(currentTime,
Jeff Brownc5ed5912010-07-14 18:48:53 -0700624 entry->deviceId, entry->source, policyFlags,
Jeff Brown7fbdc842010-06-17 20:52:56 -0700625 entry->action, entry->flags, entry->keyCode, entry->scanCode,
Jeff Brown00fa7bd2010-07-02 15:37:36 -0700626 entry->metaState, entry->repeatCount + 1, entry->downTime);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700627
628 mKeyRepeatState.lastKeyEntry = newEntry;
Jeff Brownac386072011-07-20 15:19:50 -0700629 entry->release();
Jeff Brown46b9ac02010-04-22 18:58:52 -0700630
631 entry = newEntry;
632 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700633 entry->syntheticRepeat = true;
634
635 // Increment reference count since we keep a reference to the event in
636 // mKeyRepeatState.lastKeyEntry in addition to the one we return.
637 entry->refCount += 1;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700638
Jeff Brown214eaf42011-05-26 19:17:02 -0700639 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Jeff Brownb88102f2010-09-08 11:49:43 -0700640 return entry;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700641}
642
Jeff Brownb88102f2010-09-08 11:49:43 -0700643bool InputDispatcher::dispatchConfigurationChangedLocked(
644 nsecs_t currentTime, ConfigurationChangedEntry* entry) {
Jeff Brown46b9ac02010-04-22 18:58:52 -0700645#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +0000646 ALOGD("dispatchConfigurationChanged - eventTime=%lld", entry->eventTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700647#endif
648
649 // Reset key repeating in case a keyboard device was added or removed or something.
650 resetKeyRepeatLocked();
651
652 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
653 CommandEntry* commandEntry = postCommandLocked(
654 & InputDispatcher::doNotifyConfigurationChangedInterruptible);
655 commandEntry->eventTime = entry->eventTime;
656 return true;
657}
658
Jeff Brown65fd2512011-08-18 11:20:58 -0700659bool InputDispatcher::dispatchDeviceResetLocked(
660 nsecs_t currentTime, DeviceResetEntry* entry) {
661#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +0000662 ALOGD("dispatchDeviceReset - eventTime=%lld, deviceId=%d", entry->eventTime, entry->deviceId);
Jeff Brown65fd2512011-08-18 11:20:58 -0700663#endif
664
665 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
666 "device was reset");
667 options.deviceId = entry->deviceId;
668 synthesizeCancelationEventsForAllConnectionsLocked(options);
669 return true;
670}
671
Jeff Brown214eaf42011-05-26 19:17:02 -0700672bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, KeyEntry* entry,
Jeff Browne20c9e02010-10-11 14:20:19 -0700673 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Jeff Browne46a0a42010-11-02 17:58:22 -0700674 // Preprocessing.
675 if (! entry->dispatchInProgress) {
676 if (entry->repeatCount == 0
677 && entry->action == AKEY_EVENT_ACTION_DOWN
678 && (entry->policyFlags & POLICY_FLAG_TRUSTED)
Jeff Brown0029c662011-03-30 02:25:18 -0700679 && (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
Jeff Browne46a0a42010-11-02 17:58:22 -0700680 if (mKeyRepeatState.lastKeyEntry
681 && mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode) {
682 // We have seen two identical key downs in a row which indicates that the device
683 // driver is automatically generating key repeats itself. We take note of the
684 // repeat here, but we disable our own next key repeat timer since it is clear that
685 // we will not need to synthesize key repeats ourselves.
686 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
687 resetKeyRepeatLocked();
688 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
689 } else {
690 // Not a repeat. Save key down state in case we do see a repeat later.
691 resetKeyRepeatLocked();
Jeff Brown214eaf42011-05-26 19:17:02 -0700692 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
Jeff Browne46a0a42010-11-02 17:58:22 -0700693 }
694 mKeyRepeatState.lastKeyEntry = entry;
695 entry->refCount += 1;
696 } else if (! entry->syntheticRepeat) {
697 resetKeyRepeatLocked();
698 }
699
Jeff Browne2e01262011-03-02 20:34:30 -0800700 if (entry->repeatCount == 1) {
701 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
702 } else {
703 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
704 }
705
Jeff Browne46a0a42010-11-02 17:58:22 -0700706 entry->dispatchInProgress = true;
Jeff Browne46a0a42010-11-02 17:58:22 -0700707
708 logOutboundKeyDetailsLocked("dispatchKey - ", entry);
709 }
710
Jeff Brown905805a2011-10-12 13:57:59 -0700711 // Handle case where the policy asked us to try again later last time.
712 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
713 if (currentTime < entry->interceptKeyWakeupTime) {
714 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
715 *nextWakeupTime = entry->interceptKeyWakeupTime;
716 }
717 return false; // wait until next wakeup
718 }
719 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
720 entry->interceptKeyWakeupTime = 0;
721 }
722
Jeff Brown54a18252010-09-16 14:07:33 -0700723 // Give the policy a chance to intercept the key.
724 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
Jeff Browne20c9e02010-10-11 14:20:19 -0700725 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Jeff Brown54a18252010-09-16 14:07:33 -0700726 CommandEntry* commandEntry = postCommandLocked(
727 & InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
Jeff Brown9302c872011-07-13 22:51:29 -0700728 if (mFocusedWindowHandle != NULL) {
729 commandEntry->inputWindowHandle = mFocusedWindowHandle;
Jeff Brown54a18252010-09-16 14:07:33 -0700730 }
731 commandEntry->keyEntry = entry;
732 entry->refCount += 1;
733 return false; // wait for the command to run
734 } else {
735 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
736 }
737 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Jeff Browne20c9e02010-10-11 14:20:19 -0700738 if (*dropReason == DROP_REASON_NOT_DROPPED) {
739 *dropReason = DROP_REASON_POLICY;
740 }
Jeff Brown54a18252010-09-16 14:07:33 -0700741 }
742
743 // Clean up if dropping the event.
Jeff Browne20c9e02010-10-11 14:20:19 -0700744 if (*dropReason != DROP_REASON_NOT_DROPPED) {
Jeff Brown3122e442010-10-11 23:32:49 -0700745 setInjectionResultLocked(entry, *dropReason == DROP_REASON_POLICY
746 ? INPUT_EVENT_INJECTION_SUCCEEDED : INPUT_EVENT_INJECTION_FAILED);
Jeff Brown54a18252010-09-16 14:07:33 -0700747 return true;
748 }
749
Jeff Brownb88102f2010-09-08 11:49:43 -0700750 // Identify targets.
Jeff Browne9bb9be2012-02-06 15:47:55 -0800751 Vector<InputTarget> inputTargets;
752 int32_t injectionResult = findFocusedWindowTargetsLocked(currentTime,
753 entry, inputTargets, nextWakeupTime);
754 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
755 return false;
Jeff Brownb88102f2010-09-08 11:49:43 -0700756 }
757
Jeff Browne9bb9be2012-02-06 15:47:55 -0800758 setInjectionResultLocked(entry, injectionResult);
759 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
760 return true;
761 }
762
763 addMonitoringTargetsLocked(inputTargets);
764
Jeff Brownb88102f2010-09-08 11:49:43 -0700765 // Dispatch the key.
Jeff Browne9bb9be2012-02-06 15:47:55 -0800766 dispatchEventLocked(currentTime, entry, inputTargets);
Jeff Brownb88102f2010-09-08 11:49:43 -0700767 return true;
768}
769
770void InputDispatcher::logOutboundKeyDetailsLocked(const char* prefix, const KeyEntry* entry) {
771#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +0000772 ALOGD("%seventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, "
Jeff Brownb88102f2010-09-08 11:49:43 -0700773 "action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, "
Jeff Browne46a0a42010-11-02 17:58:22 -0700774 "repeatCount=%d, downTime=%lld",
Jeff Brownb88102f2010-09-08 11:49:43 -0700775 prefix,
776 entry->eventTime, entry->deviceId, entry->source, entry->policyFlags,
777 entry->action, entry->flags, entry->keyCode, entry->scanCode, entry->metaState,
Jeff Browne46a0a42010-11-02 17:58:22 -0700778 entry->repeatCount, entry->downTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700779#endif
780}
781
782bool InputDispatcher::dispatchMotionLocked(
Jeff Browne20c9e02010-10-11 14:20:19 -0700783 nsecs_t currentTime, MotionEntry* entry, DropReason* dropReason, nsecs_t* nextWakeupTime) {
Jeff Browne46a0a42010-11-02 17:58:22 -0700784 // Preprocessing.
785 if (! entry->dispatchInProgress) {
786 entry->dispatchInProgress = true;
Jeff Browne46a0a42010-11-02 17:58:22 -0700787
788 logOutboundMotionDetailsLocked("dispatchMotion - ", entry);
789 }
790
Jeff Brown54a18252010-09-16 14:07:33 -0700791 // Clean up if dropping the event.
Jeff Browne20c9e02010-10-11 14:20:19 -0700792 if (*dropReason != DROP_REASON_NOT_DROPPED) {
Jeff Brown3122e442010-10-11 23:32:49 -0700793 setInjectionResultLocked(entry, *dropReason == DROP_REASON_POLICY
794 ? INPUT_EVENT_INJECTION_SUCCEEDED : INPUT_EVENT_INJECTION_FAILED);
Jeff Brown54a18252010-09-16 14:07:33 -0700795 return true;
796 }
797
Jeff Brownb88102f2010-09-08 11:49:43 -0700798 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
799
800 // Identify targets.
Jeff Browne9bb9be2012-02-06 15:47:55 -0800801 Vector<InputTarget> inputTargets;
802
Jeff Browncc0c1592011-02-19 05:07:28 -0800803 bool conflictingPointerActions = false;
Jeff Browne9bb9be2012-02-06 15:47:55 -0800804 int32_t injectionResult;
805 if (isPointerEvent) {
806 // Pointer event. (eg. touchscreen)
807 injectionResult = findTouchedWindowTargetsLocked(currentTime,
808 entry, inputTargets, nextWakeupTime, &conflictingPointerActions);
809 } else {
810 // Non touch event. (eg. trackball)
811 injectionResult = findFocusedWindowTargetsLocked(currentTime,
812 entry, inputTargets, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700813 }
Jeff Browne9bb9be2012-02-06 15:47:55 -0800814 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
815 return false;
816 }
817
818 setInjectionResultLocked(entry, injectionResult);
819 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
820 return true;
821 }
822
823 addMonitoringTargetsLocked(inputTargets);
Jeff Brownb88102f2010-09-08 11:49:43 -0700824
825 // Dispatch the motion.
Jeff Browncc0c1592011-02-19 05:07:28 -0800826 if (conflictingPointerActions) {
Jeff Brownda3d5a92011-03-29 15:11:34 -0700827 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
828 "conflicting pointer actions");
829 synthesizeCancelationEventsForAllConnectionsLocked(options);
Jeff Browncc0c1592011-02-19 05:07:28 -0800830 }
Jeff Browne9bb9be2012-02-06 15:47:55 -0800831 dispatchEventLocked(currentTime, entry, inputTargets);
Jeff Brownb88102f2010-09-08 11:49:43 -0700832 return true;
833}
834
835
836void InputDispatcher::logOutboundMotionDetailsLocked(const char* prefix, const MotionEntry* entry) {
837#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +0000838 ALOGD("%seventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, "
Jeff Brown85a31762010-09-01 17:01:00 -0700839 "action=0x%x, flags=0x%x, "
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700840 "metaState=0x%x, buttonState=0x%x, "
841 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%lld",
Jeff Brownb88102f2010-09-08 11:49:43 -0700842 prefix,
Jeff Brown85a31762010-09-01 17:01:00 -0700843 entry->eventTime, entry->deviceId, entry->source, entry->policyFlags,
844 entry->action, entry->flags,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700845 entry->metaState, entry->buttonState,
846 entry->edgeFlags, entry->xPrecision, entry->yPrecision,
Jeff Brown46b9ac02010-04-22 18:58:52 -0700847 entry->downTime);
848
Jeff Brown46b9ac02010-04-22 18:58:52 -0700849 for (uint32_t i = 0; i < entry->pointerCount; i++) {
Steve Block5baa3a62011-12-20 16:23:08 +0000850 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700851 "x=%f, y=%f, pressure=%f, size=%f, "
Jeff Brown85a31762010-09-01 17:01:00 -0700852 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
Jeff Brown8d608662010-08-30 03:02:23 -0700853 "orientation=%f",
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700854 i, entry->pointerProperties[i].id,
855 entry->pointerProperties[i].toolType,
Jeff Brown3241b6b2012-02-03 15:08:02 -0800856 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
857 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
858 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
859 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
860 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
861 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
862 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
863 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
864 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Jeff Brown46b9ac02010-04-22 18:58:52 -0700865 }
866#endif
Jeff Brown46b9ac02010-04-22 18:58:52 -0700867}
868
Jeff Browne9bb9be2012-02-06 15:47:55 -0800869void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
870 EventEntry* eventEntry, const Vector<InputTarget>& inputTargets) {
Jeff Brown46b9ac02010-04-22 18:58:52 -0700871#if DEBUG_DISPATCH_CYCLE
Jeff Brown3241b6b2012-02-03 15:08:02 -0800872 ALOGD("dispatchEventToCurrentInputTargets");
Jeff Brown46b9ac02010-04-22 18:58:52 -0700873#endif
874
Steve Blockec193de2012-01-09 18:35:44 +0000875 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
Jeff Brown9c3cda02010-06-15 01:31:58 -0700876
Jeff Browne2fe69e2010-10-18 13:21:23 -0700877 pokeUserActivityLocked(eventEntry);
878
Jeff Browne9bb9be2012-02-06 15:47:55 -0800879 for (size_t i = 0; i < inputTargets.size(); i++) {
880 const InputTarget& inputTarget = inputTargets.itemAt(i);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700881
Jeff Brown519e0242010-09-15 15:18:56 -0700882 ssize_t connectionIndex = getConnectionIndexLocked(inputTarget.inputChannel);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700883 if (connectionIndex >= 0) {
Jeff Browncbee6d62012-02-03 20:11:27 -0800884 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
Jeff Brown3241b6b2012-02-03 15:08:02 -0800885 prepareDispatchCycleLocked(currentTime, connection, eventEntry, &inputTarget);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700886 } else {
Jeff Brownb6997262010-10-08 22:31:17 -0700887#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +0000888 ALOGD("Dropping event delivery to target with channel '%s' because it "
Jeff Brownb6997262010-10-08 22:31:17 -0700889 "is no longer registered with the input dispatcher.",
Jeff Brown46b9ac02010-04-22 18:58:52 -0700890 inputTarget.inputChannel->getName().string());
Jeff Brownb6997262010-10-08 22:31:17 -0700891#endif
Jeff Brown46b9ac02010-04-22 18:58:52 -0700892 }
893 }
894}
895
Jeff Brownb88102f2010-09-08 11:49:43 -0700896int32_t InputDispatcher::handleTargetsNotReadyLocked(nsecs_t currentTime,
Jeff Brown9302c872011-07-13 22:51:29 -0700897 const EventEntry* entry,
898 const sp<InputApplicationHandle>& applicationHandle,
899 const sp<InputWindowHandle>& windowHandle,
Jeff Brownb88102f2010-09-08 11:49:43 -0700900 nsecs_t* nextWakeupTime) {
Jeff Brown9302c872011-07-13 22:51:29 -0700901 if (applicationHandle == NULL && windowHandle == NULL) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700902 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY) {
903#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +0000904 ALOGD("Waiting for system to become ready for input.");
Jeff Brownb88102f2010-09-08 11:49:43 -0700905#endif
906 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY;
907 mInputTargetWaitStartTime = currentTime;
908 mInputTargetWaitTimeoutTime = LONG_LONG_MAX;
909 mInputTargetWaitTimeoutExpired = false;
Jeff Brown9302c872011-07-13 22:51:29 -0700910 mInputTargetWaitApplicationHandle.clear();
Jeff Brownb88102f2010-09-08 11:49:43 -0700911 }
912 } else {
913 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
914#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +0000915 ALOGD("Waiting for application to become ready for input: %s",
Jeff Brown9302c872011-07-13 22:51:29 -0700916 getApplicationWindowLabelLocked(applicationHandle, windowHandle).string());
Jeff Brownb88102f2010-09-08 11:49:43 -0700917#endif
Jeff Browncc4f7db2011-08-30 20:34:48 -0700918 nsecs_t timeout;
919 if (windowHandle != NULL) {
920 timeout = windowHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
921 } else if (applicationHandle != NULL) {
922 timeout = applicationHandle->getDispatchingTimeout(
923 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
924 } else {
925 timeout = DEFAULT_INPUT_DISPATCHING_TIMEOUT;
926 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700927
928 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY;
929 mInputTargetWaitStartTime = currentTime;
930 mInputTargetWaitTimeoutTime = currentTime + timeout;
931 mInputTargetWaitTimeoutExpired = false;
Jeff Brown9302c872011-07-13 22:51:29 -0700932 mInputTargetWaitApplicationHandle.clear();
Jeff Brown928e0542011-01-10 11:17:36 -0800933
Jeff Brown9302c872011-07-13 22:51:29 -0700934 if (windowHandle != NULL) {
935 mInputTargetWaitApplicationHandle = windowHandle->inputApplicationHandle;
Jeff Brown928e0542011-01-10 11:17:36 -0800936 }
Jeff Brown9302c872011-07-13 22:51:29 -0700937 if (mInputTargetWaitApplicationHandle == NULL && applicationHandle != NULL) {
938 mInputTargetWaitApplicationHandle = applicationHandle;
Jeff Brown928e0542011-01-10 11:17:36 -0800939 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700940 }
941 }
942
943 if (mInputTargetWaitTimeoutExpired) {
944 return INPUT_EVENT_INJECTION_TIMED_OUT;
945 }
946
947 if (currentTime >= mInputTargetWaitTimeoutTime) {
Jeff Brown9302c872011-07-13 22:51:29 -0700948 onANRLocked(currentTime, applicationHandle, windowHandle,
949 entry->eventTime, mInputTargetWaitStartTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700950
951 // Force poll loop to wake up immediately on next iteration once we get the
952 // ANR response back from the policy.
953 *nextWakeupTime = LONG_LONG_MIN;
954 return INPUT_EVENT_INJECTION_PENDING;
955 } else {
956 // Force poll loop to wake up when timeout is due.
957 if (mInputTargetWaitTimeoutTime < *nextWakeupTime) {
958 *nextWakeupTime = mInputTargetWaitTimeoutTime;
959 }
960 return INPUT_EVENT_INJECTION_PENDING;
961 }
962}
963
Jeff Brown519e0242010-09-15 15:18:56 -0700964void InputDispatcher::resumeAfterTargetsNotReadyTimeoutLocked(nsecs_t newTimeout,
965 const sp<InputChannel>& inputChannel) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700966 if (newTimeout > 0) {
967 // Extend the timeout.
968 mInputTargetWaitTimeoutTime = now() + newTimeout;
969 } else {
970 // Give up.
971 mInputTargetWaitTimeoutExpired = true;
Jeff Brown519e0242010-09-15 15:18:56 -0700972
973 // Input state will not be realistic. Mark it out of sync.
Jeff Browndc3e0052010-09-16 11:02:16 -0700974 if (inputChannel.get()) {
975 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
976 if (connectionIndex >= 0) {
Jeff Browncbee6d62012-02-03 20:11:27 -0800977 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
Jeff Brownf44e3942012-04-20 11:33:27 -0700978 sp<InputWindowHandle> windowHandle = connection->inputWindowHandle;
979
980 if (windowHandle != NULL) {
981 mTouchState.removeWindow(windowHandle);
982 }
983
Jeff Brown00045a72010-12-09 18:10:30 -0800984 if (connection->status == Connection::STATUS_NORMAL) {
Jeff Brownda3d5a92011-03-29 15:11:34 -0700985 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
Jeff Brown00045a72010-12-09 18:10:30 -0800986 "application not responding");
Jeff Brownda3d5a92011-03-29 15:11:34 -0700987 synthesizeCancelationEventsForConnectionLocked(connection, options);
Jeff Brown00045a72010-12-09 18:10:30 -0800988 }
Jeff Browndc3e0052010-09-16 11:02:16 -0700989 }
Jeff Brown519e0242010-09-15 15:18:56 -0700990 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700991 }
992}
993
Jeff Brown519e0242010-09-15 15:18:56 -0700994nsecs_t InputDispatcher::getTimeSpentWaitingForApplicationLocked(
Jeff Brownb88102f2010-09-08 11:49:43 -0700995 nsecs_t currentTime) {
996 if (mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
997 return currentTime - mInputTargetWaitStartTime;
998 }
999 return 0;
1000}
1001
1002void InputDispatcher::resetANRTimeoutsLocked() {
1003#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001004 ALOGD("Resetting ANR timeouts.");
Jeff Brownb88102f2010-09-08 11:49:43 -07001005#endif
1006
Jeff Brownb88102f2010-09-08 11:49:43 -07001007 // Reset input target wait timeout.
1008 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_NONE;
Jeff Brown5ea29ab2011-07-27 11:50:51 -07001009 mInputTargetWaitApplicationHandle.clear();
Jeff Brownb88102f2010-09-08 11:49:43 -07001010}
1011
Jeff Brown01ce2e92010-09-26 22:20:12 -07001012int32_t InputDispatcher::findFocusedWindowTargetsLocked(nsecs_t currentTime,
Jeff Browne9bb9be2012-02-06 15:47:55 -08001013 const EventEntry* entry, Vector<InputTarget>& inputTargets, nsecs_t* nextWakeupTime) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001014 int32_t injectionResult;
1015
1016 // If there is no currently focused window and no focused application
1017 // then drop the event.
Jeff Brown9302c872011-07-13 22:51:29 -07001018 if (mFocusedWindowHandle == NULL) {
1019 if (mFocusedApplicationHandle != NULL) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001020#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001021 ALOGD("Waiting because there is no focused window but there is a "
Jeff Brown519e0242010-09-15 15:18:56 -07001022 "focused application that may eventually add a window: %s.",
Jeff Brown9302c872011-07-13 22:51:29 -07001023 getApplicationWindowLabelLocked(mFocusedApplicationHandle, NULL).string());
Jeff Brownb88102f2010-09-08 11:49:43 -07001024#endif
1025 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brown9302c872011-07-13 22:51:29 -07001026 mFocusedApplicationHandle, NULL, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -07001027 goto Unresponsive;
1028 }
1029
Steve Block6215d3f2012-01-04 20:05:49 +00001030 ALOGI("Dropping event because there is no focused window or focused application.");
Jeff Brownb88102f2010-09-08 11:49:43 -07001031 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1032 goto Failed;
1033 }
1034
1035 // Check permissions.
Jeff Brown9302c872011-07-13 22:51:29 -07001036 if (! checkInjectionPermission(mFocusedWindowHandle, entry->injectionState)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001037 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1038 goto Failed;
1039 }
1040
1041 // If the currently focused window is paused then keep waiting.
Jeff Browncc4f7db2011-08-30 20:34:48 -07001042 if (mFocusedWindowHandle->getInfo()->paused) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001043#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001044 ALOGD("Waiting because focused window is paused.");
Jeff Brownb88102f2010-09-08 11:49:43 -07001045#endif
1046 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brown9302c872011-07-13 22:51:29 -07001047 mFocusedApplicationHandle, mFocusedWindowHandle, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -07001048 goto Unresponsive;
1049 }
1050
Jeff Brown519e0242010-09-15 15:18:56 -07001051 // If the currently focused window is still working on previous events then keep waiting.
Jeff Brown0952c302012-02-13 13:48:59 -08001052 if (!isWindowReadyForMoreInputLocked(currentTime, mFocusedWindowHandle, entry)) {
Jeff Brown519e0242010-09-15 15:18:56 -07001053#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001054 ALOGD("Waiting because focused window still processing previous input.");
Jeff Brown519e0242010-09-15 15:18:56 -07001055#endif
1056 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brown9302c872011-07-13 22:51:29 -07001057 mFocusedApplicationHandle, mFocusedWindowHandle, nextWakeupTime);
Jeff Brown519e0242010-09-15 15:18:56 -07001058 goto Unresponsive;
1059 }
1060
Jeff Brownb88102f2010-09-08 11:49:43 -07001061 // Success! Output targets.
1062 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
Jeff Brown9302c872011-07-13 22:51:29 -07001063 addWindowTargetLocked(mFocusedWindowHandle,
Jeff Browne9bb9be2012-02-06 15:47:55 -08001064 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS, BitSet32(0),
1065 inputTargets);
Jeff Brownb88102f2010-09-08 11:49:43 -07001066
1067 // Done.
1068Failed:
1069Unresponsive:
Jeff Brown519e0242010-09-15 15:18:56 -07001070 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
1071 updateDispatchStatisticsLocked(currentTime, entry,
1072 injectionResult, timeSpentWaitingForApplication);
Jeff Brownb88102f2010-09-08 11:49:43 -07001073#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001074 ALOGD("findFocusedWindow finished: injectionResult=%d, "
Jeff Brown519e0242010-09-15 15:18:56 -07001075 "timeSpendWaitingForApplication=%0.1fms",
1076 injectionResult, timeSpentWaitingForApplication / 1000000.0);
Jeff Brownb88102f2010-09-08 11:49:43 -07001077#endif
1078 return injectionResult;
1079}
1080
Jeff Brown01ce2e92010-09-26 22:20:12 -07001081int32_t InputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime,
Jeff Browne9bb9be2012-02-06 15:47:55 -08001082 const MotionEntry* entry, Vector<InputTarget>& inputTargets, nsecs_t* nextWakeupTime,
1083 bool* outConflictingPointerActions) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001084 enum InjectionPermission {
1085 INJECTION_PERMISSION_UNKNOWN,
1086 INJECTION_PERMISSION_GRANTED,
1087 INJECTION_PERMISSION_DENIED
1088 };
1089
Jeff Brownb88102f2010-09-08 11:49:43 -07001090 nsecs_t startTime = now();
1091
1092 // For security reasons, we defer updating the touch state until we are sure that
1093 // event injection will be allowed.
1094 //
1095 // FIXME In the original code, screenWasOff could never be set to true.
1096 // The reason is that the POLICY_FLAG_WOKE_HERE
1097 // and POLICY_FLAG_BRIGHT_HERE flags were set only when preprocessing raw
1098 // EV_KEY, EV_REL and EV_ABS events. As it happens, the touch event was
1099 // actually enqueued using the policyFlags that appeared in the final EV_SYN
1100 // events upon which no preprocessing took place. So policyFlags was always 0.
1101 // In the new native input dispatcher we're a bit more careful about event
1102 // preprocessing so the touches we receive can actually have non-zero policyFlags.
1103 // Unfortunately we obtain undesirable behavior.
1104 //
1105 // Here's what happens:
1106 //
1107 // When the device dims in anticipation of going to sleep, touches
1108 // in windows which have FLAG_TOUCHABLE_WHEN_WAKING cause
1109 // the device to brighten and reset the user activity timer.
1110 // Touches on other windows (such as the launcher window)
1111 // are dropped. Then after a moment, the device goes to sleep. Oops.
1112 //
1113 // Also notice how screenWasOff was being initialized using POLICY_FLAG_BRIGHT_HERE
1114 // instead of POLICY_FLAG_WOKE_HERE...
1115 //
1116 bool screenWasOff = false; // original policy: policyFlags & POLICY_FLAG_BRIGHT_HERE;
1117
1118 int32_t action = entry->action;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001119 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Jeff Brownb88102f2010-09-08 11:49:43 -07001120
1121 // Update the touch state as needed based on the properties of the touch event.
Jeff Brown01ce2e92010-09-26 22:20:12 -07001122 int32_t injectionResult = INPUT_EVENT_INJECTION_PENDING;
1123 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
Jeff Brown9302c872011-07-13 22:51:29 -07001124 sp<InputWindowHandle> newHoverWindowHandle;
Jeff Browncc0c1592011-02-19 05:07:28 -08001125
1126 bool isSplit = mTouchState.split;
Jeff Brown2717eff2011-06-30 23:53:07 -07001127 bool switchedDevice = mTouchState.deviceId >= 0
1128 && (mTouchState.deviceId != entry->deviceId
1129 || mTouchState.source != entry->source);
Jeff Browna032cc02011-03-07 16:56:21 -08001130 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE
1131 || maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER
1132 || maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1133 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN
1134 || maskedAction == AMOTION_EVENT_ACTION_SCROLL
1135 || isHoverAction);
Jeff Brown81346812011-06-28 20:08:48 -07001136 bool wrongDevice = false;
Jeff Browna032cc02011-03-07 16:56:21 -08001137 if (newGesture) {
Jeff Browncc0c1592011-02-19 05:07:28 -08001138 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Jeff Brown81346812011-06-28 20:08:48 -07001139 if (switchedDevice && mTouchState.down && !down) {
1140#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001141 ALOGD("Dropping event because a pointer for a different device is already down.");
Jeff Brown81346812011-06-28 20:08:48 -07001142#endif
Jeff Browncc0c1592011-02-19 05:07:28 -08001143 mTempTouchState.copyFrom(mTouchState);
Jeff Brown81346812011-06-28 20:08:48 -07001144 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1145 switchedDevice = false;
1146 wrongDevice = true;
1147 goto Failed;
Jeff Browncc0c1592011-02-19 05:07:28 -08001148 }
Jeff Brown81346812011-06-28 20:08:48 -07001149 mTempTouchState.reset();
1150 mTempTouchState.down = down;
1151 mTempTouchState.deviceId = entry->deviceId;
1152 mTempTouchState.source = entry->source;
1153 isSplit = false;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001154 } else {
1155 mTempTouchState.copyFrom(mTouchState);
Jeff Browncc0c1592011-02-19 05:07:28 -08001156 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001157
Jeff Browna032cc02011-03-07 16:56:21 -08001158 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
Jeff Brown33bbfd22011-02-24 20:55:35 -08001159 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
Jeff Brownb88102f2010-09-08 11:49:43 -07001160
Jeff Brown01ce2e92010-09-26 22:20:12 -07001161 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Jeff Brown3241b6b2012-02-03 15:08:02 -08001162 int32_t x = int32_t(entry->pointerCoords[pointerIndex].
Jeff Brownebbd5d12011-02-17 13:01:34 -08001163 getAxisValue(AMOTION_EVENT_AXIS_X));
Jeff Brown3241b6b2012-02-03 15:08:02 -08001164 int32_t y = int32_t(entry->pointerCoords[pointerIndex].
Jeff Brownebbd5d12011-02-17 13:01:34 -08001165 getAxisValue(AMOTION_EVENT_AXIS_Y));
Jeff Brown9302c872011-07-13 22:51:29 -07001166 sp<InputWindowHandle> newTouchedWindowHandle;
1167 sp<InputWindowHandle> topErrorWindowHandle;
Jeff Browna032cc02011-03-07 16:56:21 -08001168 bool isTouchModal = false;
Jeff Brownb88102f2010-09-08 11:49:43 -07001169
1170 // Traverse windows from front to back to find touched window and outside targets.
Jeff Brown9302c872011-07-13 22:51:29 -07001171 size_t numWindows = mWindowHandles.size();
Jeff Brownb88102f2010-09-08 11:49:43 -07001172 for (size_t i = 0; i < numWindows; i++) {
Jeff Brown9302c872011-07-13 22:51:29 -07001173 sp<InputWindowHandle> windowHandle = mWindowHandles.itemAt(i);
Jeff Browncc4f7db2011-08-30 20:34:48 -07001174 const InputWindowInfo* windowInfo = windowHandle->getInfo();
1175 int32_t flags = windowInfo->layoutParamsFlags;
Jeff Brownb88102f2010-09-08 11:49:43 -07001176
Jeff Browncc4f7db2011-08-30 20:34:48 -07001177 if (flags & InputWindowInfo::FLAG_SYSTEM_ERROR) {
Jeff Brown9302c872011-07-13 22:51:29 -07001178 if (topErrorWindowHandle == NULL) {
1179 topErrorWindowHandle = windowHandle;
Jeff Brownb88102f2010-09-08 11:49:43 -07001180 }
1181 }
1182
Jeff Browncc4f7db2011-08-30 20:34:48 -07001183 if (windowInfo->visible) {
1184 if (! (flags & InputWindowInfo::FLAG_NOT_TOUCHABLE)) {
1185 isTouchModal = (flags & (InputWindowInfo::FLAG_NOT_FOCUSABLE
1186 | InputWindowInfo::FLAG_NOT_TOUCH_MODAL)) == 0;
1187 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
Jeff Brown9302c872011-07-13 22:51:29 -07001188 if (! screenWasOff
Jeff Browncc4f7db2011-08-30 20:34:48 -07001189 || (flags & InputWindowInfo::FLAG_TOUCHABLE_WHEN_WAKING)) {
Jeff Brown9302c872011-07-13 22:51:29 -07001190 newTouchedWindowHandle = windowHandle;
Jeff Brownb88102f2010-09-08 11:49:43 -07001191 }
1192 break; // found touched window, exit window loop
1193 }
1194 }
1195
Jeff Brown01ce2e92010-09-26 22:20:12 -07001196 if (maskedAction == AMOTION_EVENT_ACTION_DOWN
Jeff Browncc4f7db2011-08-30 20:34:48 -07001197 && (flags & InputWindowInfo::FLAG_WATCH_OUTSIDE_TOUCH)) {
Jeff Browna032cc02011-03-07 16:56:21 -08001198 int32_t outsideTargetFlags = InputTarget::FLAG_DISPATCH_AS_OUTSIDE;
Jeff Brown9302c872011-07-13 22:51:29 -07001199 if (isWindowObscuredAtPointLocked(windowHandle, x, y)) {
Jeff Brown19dfc832010-10-05 12:26:23 -07001200 outsideTargetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1201 }
1202
Jeff Brown9302c872011-07-13 22:51:29 -07001203 mTempTouchState.addOrUpdateWindow(
1204 windowHandle, outsideTargetFlags, BitSet32(0));
Jeff Brownb88102f2010-09-08 11:49:43 -07001205 }
1206 }
1207 }
1208
1209 // If there is an error window but it is not taking focus (typically because
1210 // it is invisible) then wait for it. Any other focused window may in
1211 // fact be in ANR state.
Jeff Brown9302c872011-07-13 22:51:29 -07001212 if (topErrorWindowHandle != NULL && newTouchedWindowHandle != topErrorWindowHandle) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001213#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001214 ALOGD("Waiting because system error window is pending.");
Jeff Brownb88102f2010-09-08 11:49:43 -07001215#endif
1216 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
1217 NULL, NULL, nextWakeupTime);
1218 injectionPermission = INJECTION_PERMISSION_UNKNOWN;
1219 goto Unresponsive;
1220 }
1221
Jeff Brown01ce2e92010-09-26 22:20:12 -07001222 // Figure out whether splitting will be allowed for this window.
Jeff Browncc4f7db2011-08-30 20:34:48 -07001223 if (newTouchedWindowHandle != NULL
1224 && newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001225 // New window supports splitting.
1226 isSplit = true;
1227 } else if (isSplit) {
1228 // New window does not support splitting but we have already split events.
1229 // Assign the pointer to the first foreground window we find.
1230 // (May be NULL which is why we put this code block before the next check.)
Jeff Brown9302c872011-07-13 22:51:29 -07001231 newTouchedWindowHandle = mTempTouchState.getFirstForegroundWindowHandle();
Jeff Brown01ce2e92010-09-26 22:20:12 -07001232 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001233
Jeff Brownb88102f2010-09-08 11:49:43 -07001234 // If we did not find a touched window then fail.
Jeff Brown9302c872011-07-13 22:51:29 -07001235 if (newTouchedWindowHandle == NULL) {
1236 if (mFocusedApplicationHandle != NULL) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001237#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001238 ALOGD("Waiting because there is no touched window but there is a "
Jeff Brown519e0242010-09-15 15:18:56 -07001239 "focused application that may eventually add a new window: %s.",
Jeff Brown9302c872011-07-13 22:51:29 -07001240 getApplicationWindowLabelLocked(mFocusedApplicationHandle, NULL).string());
Jeff Brownb88102f2010-09-08 11:49:43 -07001241#endif
1242 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brown9302c872011-07-13 22:51:29 -07001243 mFocusedApplicationHandle, NULL, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -07001244 goto Unresponsive;
1245 }
1246
Steve Block6215d3f2012-01-04 20:05:49 +00001247 ALOGI("Dropping event because there is no touched window or focused application.");
Jeff Brownb88102f2010-09-08 11:49:43 -07001248 injectionResult = INPUT_EVENT_INJECTION_FAILED;
Jeff Brownb88102f2010-09-08 11:49:43 -07001249 goto Failed;
1250 }
1251
Jeff Brown19dfc832010-10-05 12:26:23 -07001252 // Set target flags.
Jeff Browna032cc02011-03-07 16:56:21 -08001253 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
Jeff Brown19dfc832010-10-05 12:26:23 -07001254 if (isSplit) {
1255 targetFlags |= InputTarget::FLAG_SPLIT;
1256 }
Jeff Brown9302c872011-07-13 22:51:29 -07001257 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
Jeff Brown19dfc832010-10-05 12:26:23 -07001258 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1259 }
1260
Jeff Browna032cc02011-03-07 16:56:21 -08001261 // Update hover state.
1262 if (isHoverAction) {
Jeff Brown9302c872011-07-13 22:51:29 -07001263 newHoverWindowHandle = newTouchedWindowHandle;
Jeff Browna032cc02011-03-07 16:56:21 -08001264 } else if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
Jeff Brown9302c872011-07-13 22:51:29 -07001265 newHoverWindowHandle = mLastHoverWindowHandle;
Jeff Browna032cc02011-03-07 16:56:21 -08001266 }
1267
Jeff Brown01ce2e92010-09-26 22:20:12 -07001268 // Update the temporary touch state.
1269 BitSet32 pointerIds;
1270 if (isSplit) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07001271 uint32_t pointerId = entry->pointerProperties[pointerIndex].id;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001272 pointerIds.markBit(pointerId);
Jeff Brownb88102f2010-09-08 11:49:43 -07001273 }
Jeff Brown9302c872011-07-13 22:51:29 -07001274 mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Jeff Brownb88102f2010-09-08 11:49:43 -07001275 } else {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001276 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
Jeff Brownb88102f2010-09-08 11:49:43 -07001277
1278 // If the pointer is not currently down, then ignore the event.
Jeff Brown01ce2e92010-09-26 22:20:12 -07001279 if (! mTempTouchState.down) {
Jeff Browna2cc28d2011-03-25 11:58:46 -07001280#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001281 ALOGD("Dropping event because the pointer is not down or we previously "
Jeff Brown76860e32010-10-25 17:37:46 -07001282 "dropped the pointer down event.");
1283#endif
Jeff Brownb88102f2010-09-08 11:49:43 -07001284 injectionResult = INPUT_EVENT_INJECTION_FAILED;
Jeff Brownb88102f2010-09-08 11:49:43 -07001285 goto Failed;
1286 }
Jeff Brown98db5fa2011-06-08 15:37:10 -07001287
1288 // Check whether touches should slip outside of the current foreground window.
1289 if (maskedAction == AMOTION_EVENT_ACTION_MOVE
1290 && entry->pointerCount == 1
1291 && mTempTouchState.isSlippery()) {
Jeff Brown3241b6b2012-02-03 15:08:02 -08001292 int32_t x = int32_t(entry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
1293 int32_t y = int32_t(entry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Jeff Brown98db5fa2011-06-08 15:37:10 -07001294
Jeff Brown9302c872011-07-13 22:51:29 -07001295 sp<InputWindowHandle> oldTouchedWindowHandle =
1296 mTempTouchState.getFirstForegroundWindowHandle();
1297 sp<InputWindowHandle> newTouchedWindowHandle = findTouchedWindowAtLocked(x, y);
1298 if (oldTouchedWindowHandle != newTouchedWindowHandle
1299 && newTouchedWindowHandle != NULL) {
Jeff Brown98db5fa2011-06-08 15:37:10 -07001300#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001301 ALOGD("Touch is slipping out of window %s into window %s.",
Jeff Browncc4f7db2011-08-30 20:34:48 -07001302 oldTouchedWindowHandle->getName().string(),
1303 newTouchedWindowHandle->getName().string());
Jeff Brown98db5fa2011-06-08 15:37:10 -07001304#endif
1305 // Make a slippery exit from the old window.
Jeff Brown9302c872011-07-13 22:51:29 -07001306 mTempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
Jeff Brown98db5fa2011-06-08 15:37:10 -07001307 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT, BitSet32(0));
1308
1309 // Make a slippery entrance into the new window.
Jeff Browncc4f7db2011-08-30 20:34:48 -07001310 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Jeff Brown98db5fa2011-06-08 15:37:10 -07001311 isSplit = true;
1312 }
1313
1314 int32_t targetFlags = InputTarget::FLAG_FOREGROUND
1315 | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
1316 if (isSplit) {
1317 targetFlags |= InputTarget::FLAG_SPLIT;
1318 }
Jeff Brown9302c872011-07-13 22:51:29 -07001319 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
Jeff Brown98db5fa2011-06-08 15:37:10 -07001320 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1321 }
1322
1323 BitSet32 pointerIds;
1324 if (isSplit) {
1325 pointerIds.markBit(entry->pointerProperties[0].id);
1326 }
Jeff Brown9302c872011-07-13 22:51:29 -07001327 mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Jeff Brown98db5fa2011-06-08 15:37:10 -07001328 }
1329 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001330 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001331
Jeff Brown9302c872011-07-13 22:51:29 -07001332 if (newHoverWindowHandle != mLastHoverWindowHandle) {
Jeff Browna032cc02011-03-07 16:56:21 -08001333 // Let the previous window know that the hover sequence is over.
Jeff Brown9302c872011-07-13 22:51:29 -07001334 if (mLastHoverWindowHandle != NULL) {
Jeff Browna032cc02011-03-07 16:56:21 -08001335#if DEBUG_HOVER
Steve Block5baa3a62011-12-20 16:23:08 +00001336 ALOGD("Sending hover exit event to window %s.",
Jeff Browncc4f7db2011-08-30 20:34:48 -07001337 mLastHoverWindowHandle->getName().string());
Jeff Browna032cc02011-03-07 16:56:21 -08001338#endif
Jeff Brown9302c872011-07-13 22:51:29 -07001339 mTempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
Jeff Browna032cc02011-03-07 16:56:21 -08001340 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
1341 }
1342
1343 // Let the new window know that the hover sequence is starting.
Jeff Brown9302c872011-07-13 22:51:29 -07001344 if (newHoverWindowHandle != NULL) {
Jeff Browna032cc02011-03-07 16:56:21 -08001345#if DEBUG_HOVER
Steve Block5baa3a62011-12-20 16:23:08 +00001346 ALOGD("Sending hover enter event to window %s.",
Jeff Browncc4f7db2011-08-30 20:34:48 -07001347 newHoverWindowHandle->getName().string());
Jeff Browna032cc02011-03-07 16:56:21 -08001348#endif
Jeff Brown9302c872011-07-13 22:51:29 -07001349 mTempTouchState.addOrUpdateWindow(newHoverWindowHandle,
Jeff Browna032cc02011-03-07 16:56:21 -08001350 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER, BitSet32(0));
1351 }
1352 }
1353
Jeff Brown01ce2e92010-09-26 22:20:12 -07001354 // Check permission to inject into all touched foreground windows and ensure there
1355 // is at least one touched foreground window.
1356 {
1357 bool haveForegroundWindow = false;
1358 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1359 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1360 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1361 haveForegroundWindow = true;
Jeff Brown9302c872011-07-13 22:51:29 -07001362 if (! checkInjectionPermission(touchedWindow.windowHandle,
1363 entry->injectionState)) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001364 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1365 injectionPermission = INJECTION_PERMISSION_DENIED;
1366 goto Failed;
1367 }
1368 }
1369 }
1370 if (! haveForegroundWindow) {
Jeff Browna2cc28d2011-03-25 11:58:46 -07001371#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001372 ALOGD("Dropping event because there is no touched foreground window to receive it.");
Jeff Brownb88102f2010-09-08 11:49:43 -07001373#endif
1374 injectionResult = INPUT_EVENT_INJECTION_FAILED;
Jeff Brownb88102f2010-09-08 11:49:43 -07001375 goto Failed;
1376 }
1377
Jeff Brown01ce2e92010-09-26 22:20:12 -07001378 // Permission granted to injection into all touched foreground windows.
1379 injectionPermission = INJECTION_PERMISSION_GRANTED;
1380 }
Jeff Brown519e0242010-09-15 15:18:56 -07001381
Kenny Root7a9db182011-06-02 15:16:05 -07001382 // Check whether windows listening for outside touches are owned by the same UID. If it is
1383 // set the policy flag that we will not reveal coordinate information to this window.
1384 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
Jeff Brown9302c872011-07-13 22:51:29 -07001385 sp<InputWindowHandle> foregroundWindowHandle =
1386 mTempTouchState.getFirstForegroundWindowHandle();
Jeff Browncc4f7db2011-08-30 20:34:48 -07001387 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Kenny Root7a9db182011-06-02 15:16:05 -07001388 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1389 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1390 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
Jeff Brown9302c872011-07-13 22:51:29 -07001391 sp<InputWindowHandle> inputWindowHandle = touchedWindow.windowHandle;
Jeff Browncc4f7db2011-08-30 20:34:48 -07001392 if (inputWindowHandle->getInfo()->ownerUid != foregroundWindowUid) {
Jeff Brown9302c872011-07-13 22:51:29 -07001393 mTempTouchState.addOrUpdateWindow(inputWindowHandle,
Kenny Root7a9db182011-06-02 15:16:05 -07001394 InputTarget::FLAG_ZERO_COORDS, BitSet32(0));
1395 }
1396 }
1397 }
1398 }
1399
Jeff Brown01ce2e92010-09-26 22:20:12 -07001400 // Ensure all touched foreground windows are ready for new input.
1401 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1402 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1403 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1404 // If the touched window is paused then keep waiting.
Jeff Browncc4f7db2011-08-30 20:34:48 -07001405 if (touchedWindow.windowHandle->getInfo()->paused) {
Jeff Browna2cc28d2011-03-25 11:58:46 -07001406#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001407 ALOGD("Waiting because touched window is paused.");
Jeff Brown519e0242010-09-15 15:18:56 -07001408#endif
Jeff Brown01ce2e92010-09-26 22:20:12 -07001409 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brown9302c872011-07-13 22:51:29 -07001410 NULL, touchedWindow.windowHandle, nextWakeupTime);
Jeff Brown01ce2e92010-09-26 22:20:12 -07001411 goto Unresponsive;
1412 }
1413
1414 // If the touched window is still working on previous events then keep waiting.
Jeff Brown0952c302012-02-13 13:48:59 -08001415 if (!isWindowReadyForMoreInputLocked(currentTime, touchedWindow.windowHandle, entry)) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001416#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001417 ALOGD("Waiting because touched window still processing previous input.");
Jeff Brown01ce2e92010-09-26 22:20:12 -07001418#endif
1419 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brown9302c872011-07-13 22:51:29 -07001420 NULL, touchedWindow.windowHandle, nextWakeupTime);
Jeff Brown01ce2e92010-09-26 22:20:12 -07001421 goto Unresponsive;
1422 }
1423 }
1424 }
1425
1426 // If this is the first pointer going down and the touched window has a wallpaper
1427 // then also add the touched wallpaper windows so they are locked in for the duration
1428 // of the touch gesture.
Jeff Brown33bbfd22011-02-24 20:55:35 -08001429 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
1430 // engine only supports touch events. We would need to add a mechanism similar
1431 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
1432 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
Jeff Brown9302c872011-07-13 22:51:29 -07001433 sp<InputWindowHandle> foregroundWindowHandle =
1434 mTempTouchState.getFirstForegroundWindowHandle();
Jeff Browncc4f7db2011-08-30 20:34:48 -07001435 if (foregroundWindowHandle->getInfo()->hasWallpaper) {
Jeff Brown9302c872011-07-13 22:51:29 -07001436 for (size_t i = 0; i < mWindowHandles.size(); i++) {
1437 sp<InputWindowHandle> windowHandle = mWindowHandles.itemAt(i);
Jeff Browncc4f7db2011-08-30 20:34:48 -07001438 if (windowHandle->getInfo()->layoutParamsType
1439 == InputWindowInfo::TYPE_WALLPAPER) {
Jeff Brown9302c872011-07-13 22:51:29 -07001440 mTempTouchState.addOrUpdateWindow(windowHandle,
Jeff Browna032cc02011-03-07 16:56:21 -08001441 InputTarget::FLAG_WINDOW_IS_OBSCURED
1442 | InputTarget::FLAG_DISPATCH_AS_IS,
1443 BitSet32(0));
Jeff Brown01ce2e92010-09-26 22:20:12 -07001444 }
1445 }
1446 }
1447 }
1448
Jeff Brownb88102f2010-09-08 11:49:43 -07001449 // Success! Output targets.
1450 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
Jeff Brownb88102f2010-09-08 11:49:43 -07001451
Jeff Brown01ce2e92010-09-26 22:20:12 -07001452 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1453 const TouchedWindow& touchedWindow = mTempTouchState.windows.itemAt(i);
Jeff Brown9302c872011-07-13 22:51:29 -07001454 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Jeff Browne9bb9be2012-02-06 15:47:55 -08001455 touchedWindow.pointerIds, inputTargets);
Jeff Brownb88102f2010-09-08 11:49:43 -07001456 }
1457
Jeff Browna032cc02011-03-07 16:56:21 -08001458 // Drop the outside or hover touch windows since we will not care about them
1459 // in the next iteration.
1460 mTempTouchState.filterNonAsIsTouchWindows();
Jeff Brown01ce2e92010-09-26 22:20:12 -07001461
Jeff Brownb88102f2010-09-08 11:49:43 -07001462Failed:
1463 // Check injection permission once and for all.
1464 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001465 if (checkInjectionPermission(NULL, entry->injectionState)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001466 injectionPermission = INJECTION_PERMISSION_GRANTED;
1467 } else {
1468 injectionPermission = INJECTION_PERMISSION_DENIED;
1469 }
1470 }
1471
1472 // Update final pieces of touch state if the injector had permission.
1473 if (injectionPermission == INJECTION_PERMISSION_GRANTED) {
Jeff Brown95712852011-01-04 19:41:59 -08001474 if (!wrongDevice) {
Jeff Brown81346812011-06-28 20:08:48 -07001475 if (switchedDevice) {
1476#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001477 ALOGD("Conflicting pointer actions: Switched to a different device.");
Jeff Brown81346812011-06-28 20:08:48 -07001478#endif
1479 *outConflictingPointerActions = true;
1480 }
1481
1482 if (isHoverAction) {
1483 // Started hovering, therefore no longer down.
1484 if (mTouchState.down) {
1485#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001486 ALOGD("Conflicting pointer actions: Hover received while pointer was down.");
Jeff Brown81346812011-06-28 20:08:48 -07001487#endif
1488 *outConflictingPointerActions = true;
1489 }
1490 mTouchState.reset();
1491 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER
1492 || maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
1493 mTouchState.deviceId = entry->deviceId;
1494 mTouchState.source = entry->source;
1495 }
1496 } else if (maskedAction == AMOTION_EVENT_ACTION_UP
1497 || maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Jeff Brown95712852011-01-04 19:41:59 -08001498 // All pointers up or canceled.
Jeff Brown33bbfd22011-02-24 20:55:35 -08001499 mTouchState.reset();
Jeff Brown95712852011-01-04 19:41:59 -08001500 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1501 // First pointer went down.
1502 if (mTouchState.down) {
Jeff Brownb6997262010-10-08 22:31:17 -07001503#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001504 ALOGD("Conflicting pointer actions: Down received while already down.");
Jeff Brownb6997262010-10-08 22:31:17 -07001505#endif
Jeff Brown81346812011-06-28 20:08:48 -07001506 *outConflictingPointerActions = true;
Jeff Brown95712852011-01-04 19:41:59 -08001507 }
Jeff Brown33bbfd22011-02-24 20:55:35 -08001508 mTouchState.copyFrom(mTempTouchState);
Jeff Brown95712852011-01-04 19:41:59 -08001509 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
1510 // One pointer went up.
1511 if (isSplit) {
1512 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07001513 uint32_t pointerId = entry->pointerProperties[pointerIndex].id;
Jeff Brownb88102f2010-09-08 11:49:43 -07001514
Jeff Brown95712852011-01-04 19:41:59 -08001515 for (size_t i = 0; i < mTempTouchState.windows.size(); ) {
1516 TouchedWindow& touchedWindow = mTempTouchState.windows.editItemAt(i);
1517 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
1518 touchedWindow.pointerIds.clearBit(pointerId);
1519 if (touchedWindow.pointerIds.isEmpty()) {
1520 mTempTouchState.windows.removeAt(i);
1521 continue;
1522 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001523 }
Jeff Brown95712852011-01-04 19:41:59 -08001524 i += 1;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001525 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001526 }
Jeff Brown33bbfd22011-02-24 20:55:35 -08001527 mTouchState.copyFrom(mTempTouchState);
1528 } else if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
1529 // Discard temporary touch state since it was only valid for this action.
1530 } else {
1531 // Save changes to touch state as-is for all other actions.
1532 mTouchState.copyFrom(mTempTouchState);
Jeff Brownb88102f2010-09-08 11:49:43 -07001533 }
Jeff Browna032cc02011-03-07 16:56:21 -08001534
1535 // Update hover state.
Jeff Brown9302c872011-07-13 22:51:29 -07001536 mLastHoverWindowHandle = newHoverWindowHandle;
Jeff Brown95712852011-01-04 19:41:59 -08001537 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001538 } else {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001539#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001540 ALOGD("Not updating touch focus because injection was denied.");
Jeff Brown01ce2e92010-09-26 22:20:12 -07001541#endif
Jeff Brownb88102f2010-09-08 11:49:43 -07001542 }
1543
1544Unresponsive:
Jeff Brown120a4592010-10-27 18:43:51 -07001545 // Reset temporary touch state to ensure we release unnecessary references to input channels.
1546 mTempTouchState.reset();
1547
Jeff Brown519e0242010-09-15 15:18:56 -07001548 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
1549 updateDispatchStatisticsLocked(currentTime, entry,
1550 injectionResult, timeSpentWaitingForApplication);
Jeff Brownb88102f2010-09-08 11:49:43 -07001551#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001552 ALOGD("findTouchedWindow finished: injectionResult=%d, injectionPermission=%d, "
Jeff Brown01ce2e92010-09-26 22:20:12 -07001553 "timeSpentWaitingForApplication=%0.1fms",
Jeff Brown519e0242010-09-15 15:18:56 -07001554 injectionResult, injectionPermission, timeSpentWaitingForApplication / 1000000.0);
Jeff Brownb88102f2010-09-08 11:49:43 -07001555#endif
1556 return injectionResult;
1557}
1558
Jeff Brown9302c872011-07-13 22:51:29 -07001559void InputDispatcher::addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
Jeff Browne9bb9be2012-02-06 15:47:55 -08001560 int32_t targetFlags, BitSet32 pointerIds, Vector<InputTarget>& inputTargets) {
1561 inputTargets.push();
Jeff Brownb88102f2010-09-08 11:49:43 -07001562
Jeff Browncc4f7db2011-08-30 20:34:48 -07001563 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Jeff Browne9bb9be2012-02-06 15:47:55 -08001564 InputTarget& target = inputTargets.editTop();
Jeff Browncc4f7db2011-08-30 20:34:48 -07001565 target.inputChannel = windowInfo->inputChannel;
Jeff Brownb88102f2010-09-08 11:49:43 -07001566 target.flags = targetFlags;
Jeff Browncc4f7db2011-08-30 20:34:48 -07001567 target.xOffset = - windowInfo->frameLeft;
1568 target.yOffset = - windowInfo->frameTop;
1569 target.scaleFactor = windowInfo->scaleFactor;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001570 target.pointerIds = pointerIds;
Jeff Brownb88102f2010-09-08 11:49:43 -07001571}
1572
Jeff Browne9bb9be2012-02-06 15:47:55 -08001573void InputDispatcher::addMonitoringTargetsLocked(Vector<InputTarget>& inputTargets) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001574 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
Jeff Browne9bb9be2012-02-06 15:47:55 -08001575 inputTargets.push();
Jeff Brownb88102f2010-09-08 11:49:43 -07001576
Jeff Browne9bb9be2012-02-06 15:47:55 -08001577 InputTarget& target = inputTargets.editTop();
Jeff Brownb88102f2010-09-08 11:49:43 -07001578 target.inputChannel = mMonitoringChannels[i];
Jeff Brownb6110c22011-04-01 16:15:13 -07001579 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
Jeff Brownb88102f2010-09-08 11:49:43 -07001580 target.xOffset = 0;
1581 target.yOffset = 0;
Jeff Brownb6110c22011-04-01 16:15:13 -07001582 target.pointerIds.clear();
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001583 target.scaleFactor = 1.0f;
Jeff Brownb88102f2010-09-08 11:49:43 -07001584 }
1585}
1586
Jeff Brown9302c872011-07-13 22:51:29 -07001587bool InputDispatcher::checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
Jeff Brown01ce2e92010-09-26 22:20:12 -07001588 const InjectionState* injectionState) {
1589 if (injectionState
Jeff Browncc4f7db2011-08-30 20:34:48 -07001590 && (windowHandle == NULL
1591 || windowHandle->getInfo()->ownerUid != injectionState->injectorUid)
Jeff Brownb6997262010-10-08 22:31:17 -07001592 && !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Jeff Brown9302c872011-07-13 22:51:29 -07001593 if (windowHandle != NULL) {
Steve Block8564c8d2012-01-05 23:22:43 +00001594 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
Jeff Brown9302c872011-07-13 22:51:29 -07001595 "owned by uid %d",
Jeff Brownb6997262010-10-08 22:31:17 -07001596 injectionState->injectorPid, injectionState->injectorUid,
Jeff Browncc4f7db2011-08-30 20:34:48 -07001597 windowHandle->getName().string(),
1598 windowHandle->getInfo()->ownerUid);
Jeff Brownb6997262010-10-08 22:31:17 -07001599 } else {
Steve Block8564c8d2012-01-05 23:22:43 +00001600 ALOGW("Permission denied: injecting event from pid %d uid %d",
Jeff Brownb6997262010-10-08 22:31:17 -07001601 injectionState->injectorPid, injectionState->injectorUid);
Jeff Brownb88102f2010-09-08 11:49:43 -07001602 }
Jeff Brownb6997262010-10-08 22:31:17 -07001603 return false;
Jeff Brownb88102f2010-09-08 11:49:43 -07001604 }
1605 return true;
1606}
1607
Jeff Brown19dfc832010-10-05 12:26:23 -07001608bool InputDispatcher::isWindowObscuredAtPointLocked(
Jeff Brown9302c872011-07-13 22:51:29 -07001609 const sp<InputWindowHandle>& windowHandle, int32_t x, int32_t y) const {
1610 size_t numWindows = mWindowHandles.size();
Jeff Brownb88102f2010-09-08 11:49:43 -07001611 for (size_t i = 0; i < numWindows; i++) {
Jeff Brown9302c872011-07-13 22:51:29 -07001612 sp<InputWindowHandle> otherHandle = mWindowHandles.itemAt(i);
1613 if (otherHandle == windowHandle) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001614 break;
1615 }
Jeff Browncc4f7db2011-08-30 20:34:48 -07001616
1617 const InputWindowInfo* otherInfo = otherHandle->getInfo();
1618 if (otherInfo->visible && ! otherInfo->isTrustedOverlay()
1619 && otherInfo->frameContainsPoint(x, y)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001620 return true;
1621 }
1622 }
1623 return false;
1624}
1625
Jeff Brownd1c48a02012-02-06 19:12:47 -08001626bool InputDispatcher::isWindowReadyForMoreInputLocked(nsecs_t currentTime,
Jeff Brown0952c302012-02-13 13:48:59 -08001627 const sp<InputWindowHandle>& windowHandle, const EventEntry* eventEntry) {
Jeff Browncc4f7db2011-08-30 20:34:48 -07001628 ssize_t connectionIndex = getConnectionIndexLocked(windowHandle->getInputChannel());
Jeff Brown519e0242010-09-15 15:18:56 -07001629 if (connectionIndex >= 0) {
Jeff Browncbee6d62012-02-03 20:11:27 -08001630 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
Jeff Brownd1c48a02012-02-06 19:12:47 -08001631 if (connection->inputPublisherBlocked) {
1632 return false;
1633 }
Jeff Brown0952c302012-02-13 13:48:59 -08001634 if (eventEntry->type == EventEntry::TYPE_KEY) {
1635 // If the event is a key event, then we must wait for all previous events to
1636 // complete before delivering it because previous events may have the
1637 // side-effect of transferring focus to a different window and we want to
1638 // ensure that the following keys are sent to the new window.
1639 //
1640 // Suppose the user touches a button in a window then immediately presses "A".
1641 // If the button causes a pop-up window to appear then we want to ensure that
1642 // the "A" key is delivered to the new pop-up window. This is because users
1643 // often anticipate pending UI changes when typing on a keyboard.
1644 // To obtain this behavior, we must serialize key events with respect to all
1645 // prior input events.
Jeff Brownd1c48a02012-02-06 19:12:47 -08001646 return connection->outboundQueue.isEmpty()
1647 && connection->waitQueue.isEmpty();
1648 }
Jeff Brown0952c302012-02-13 13:48:59 -08001649 // Touch events can always be sent to a window immediately because the user intended
1650 // to touch whatever was visible at the time. Even if focus changes or a new
1651 // window appears moments later, the touch event was meant to be delivered to
1652 // whatever window happened to be on screen at the time.
1653 //
1654 // Generic motion events, such as trackball or joystick events are a little trickier.
1655 // Like key events, generic motion events are delivered to the focused window.
1656 // Unlike key events, generic motion events don't tend to transfer focus to other
1657 // windows and it is not important for them to be serialized. So we prefer to deliver
1658 // generic motion events as soon as possible to improve efficiency and reduce lag
1659 // through batching.
1660 //
1661 // The one case where we pause input event delivery is when the wait queue is piling
1662 // up with lots of events because the application is not responding.
1663 // This condition ensures that ANRs are detected reliably.
Jeff Brownd1c48a02012-02-06 19:12:47 -08001664 if (!connection->waitQueue.isEmpty()
1665 && currentTime >= connection->waitQueue.head->eventEntry->eventTime
1666 + STREAM_AHEAD_EVENT_TIMEOUT) {
1667 return false;
1668 }
Jeff Brown519e0242010-09-15 15:18:56 -07001669 }
Jeff Brownd1c48a02012-02-06 19:12:47 -08001670 return true;
Jeff Brown519e0242010-09-15 15:18:56 -07001671}
1672
Jeff Brown9302c872011-07-13 22:51:29 -07001673String8 InputDispatcher::getApplicationWindowLabelLocked(
1674 const sp<InputApplicationHandle>& applicationHandle,
1675 const sp<InputWindowHandle>& windowHandle) {
1676 if (applicationHandle != NULL) {
1677 if (windowHandle != NULL) {
Jeff Browncc4f7db2011-08-30 20:34:48 -07001678 String8 label(applicationHandle->getName());
Jeff Brown519e0242010-09-15 15:18:56 -07001679 label.append(" - ");
Jeff Browncc4f7db2011-08-30 20:34:48 -07001680 label.append(windowHandle->getName());
Jeff Brown519e0242010-09-15 15:18:56 -07001681 return label;
1682 } else {
Jeff Browncc4f7db2011-08-30 20:34:48 -07001683 return applicationHandle->getName();
Jeff Brown519e0242010-09-15 15:18:56 -07001684 }
Jeff Brown9302c872011-07-13 22:51:29 -07001685 } else if (windowHandle != NULL) {
Jeff Browncc4f7db2011-08-30 20:34:48 -07001686 return windowHandle->getName();
Jeff Brown519e0242010-09-15 15:18:56 -07001687 } else {
1688 return String8("<unknown application or window>");
1689 }
1690}
1691
Jeff Browne2fe69e2010-10-18 13:21:23 -07001692void InputDispatcher::pokeUserActivityLocked(const EventEntry* eventEntry) {
Jeff Brown56194eb2011-03-02 19:23:13 -08001693 int32_t eventType = POWER_MANAGER_OTHER_EVENT;
Jeff Brown4d396052010-10-29 21:50:21 -07001694 switch (eventEntry->type) {
1695 case EventEntry::TYPE_MOTION: {
Jeff Browne2fe69e2010-10-18 13:21:23 -07001696 const MotionEntry* motionEntry = static_cast<const MotionEntry*>(eventEntry);
Jeff Brown4d396052010-10-29 21:50:21 -07001697 if (motionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
1698 return;
1699 }
1700
Jeff Brown56194eb2011-03-02 19:23:13 -08001701 if (MotionEvent::isTouchEvent(motionEntry->source, motionEntry->action)) {
Joe Onorato1a542c72010-11-08 09:48:20 -08001702 eventType = POWER_MANAGER_TOUCH_EVENT;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001703 }
Jeff Brown4d396052010-10-29 21:50:21 -07001704 break;
1705 }
1706 case EventEntry::TYPE_KEY: {
1707 const KeyEntry* keyEntry = static_cast<const KeyEntry*>(eventEntry);
1708 if (keyEntry->flags & AKEY_EVENT_FLAG_CANCELED) {
1709 return;
1710 }
Jeff Brown56194eb2011-03-02 19:23:13 -08001711 eventType = POWER_MANAGER_BUTTON_EVENT;
Jeff Brown4d396052010-10-29 21:50:21 -07001712 break;
1713 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001714 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001715
Jeff Brownb88102f2010-09-08 11:49:43 -07001716 CommandEntry* commandEntry = postCommandLocked(
1717 & InputDispatcher::doPokeUserActivityLockedInterruptible);
Jeff Browne2fe69e2010-10-18 13:21:23 -07001718 commandEntry->eventTime = eventEntry->eventTime;
Jeff Brownb88102f2010-09-08 11:49:43 -07001719 commandEntry->userActivityEventType = eventType;
1720}
1721
Jeff Brown7fbdc842010-06-17 20:52:56 -07001722void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001723 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07001724#if DEBUG_DISPATCH_CYCLE
Steve Block5baa3a62011-12-20 16:23:08 +00001725 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
Jeff Brown9cc695c2011-08-23 18:35:04 -07001726 "xOffset=%f, yOffset=%f, scaleFactor=%f, "
Jeff Brown3241b6b2012-02-03 15:08:02 -08001727 "pointerIds=0x%x",
Jeff Brown519e0242010-09-15 15:18:56 -07001728 connection->getInputChannelName(), inputTarget->flags,
Jeff Brown46b9ac02010-04-22 18:58:52 -07001729 inputTarget->xOffset, inputTarget->yOffset,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001730 inputTarget->scaleFactor, inputTarget->pointerIds.value);
Jeff Brown46b9ac02010-04-22 18:58:52 -07001731#endif
1732
1733 // Skip this event if the connection status is not normal.
Jeff Brown519e0242010-09-15 15:18:56 -07001734 // We don't want to enqueue additional outbound events if the connection is broken.
Jeff Brown46b9ac02010-04-22 18:58:52 -07001735 if (connection->status != Connection::STATUS_NORMAL) {
Jeff Brownb6997262010-10-08 22:31:17 -07001736#if DEBUG_DISPATCH_CYCLE
Steve Block5baa3a62011-12-20 16:23:08 +00001737 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Jeff Brownb88102f2010-09-08 11:49:43 -07001738 connection->getInputChannelName(), connection->getStatusLabel());
Jeff Brownb6997262010-10-08 22:31:17 -07001739#endif
Jeff Brown46b9ac02010-04-22 18:58:52 -07001740 return;
1741 }
1742
Jeff Brown01ce2e92010-09-26 22:20:12 -07001743 // Split a motion event if needed.
Jeff Brown3241b6b2012-02-03 15:08:02 -08001744 if (inputTarget->flags & InputTarget::FLAG_SPLIT) {
Steve Blockec193de2012-01-09 18:35:44 +00001745 ALOG_ASSERT(eventEntry->type == EventEntry::TYPE_MOTION);
Jeff Brown01ce2e92010-09-26 22:20:12 -07001746
1747 MotionEntry* originalMotionEntry = static_cast<MotionEntry*>(eventEntry);
1748 if (inputTarget->pointerIds.count() != originalMotionEntry->pointerCount) {
1749 MotionEntry* splitMotionEntry = splitMotionEvent(
1750 originalMotionEntry, inputTarget->pointerIds);
Jeff Brown58a2da82011-01-25 16:02:22 -08001751 if (!splitMotionEntry) {
1752 return; // split event was dropped
1753 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001754#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001755 ALOGD("channel '%s' ~ Split motion event.",
Jeff Brown01ce2e92010-09-26 22:20:12 -07001756 connection->getInputChannelName());
1757 logOutboundMotionDetailsLocked(" ", splitMotionEntry);
1758#endif
Jeff Brownc0cb3dc2012-01-12 18:30:12 -08001759 enqueueDispatchEntriesLocked(currentTime, connection,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001760 splitMotionEntry, inputTarget);
Jeff Brownc0cb3dc2012-01-12 18:30:12 -08001761 splitMotionEntry->release();
1762 return;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001763 }
1764 }
1765
Jeff Brownc0cb3dc2012-01-12 18:30:12 -08001766 // Not splitting. Enqueue dispatch entries for the event as is.
Jeff Brown3241b6b2012-02-03 15:08:02 -08001767 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
Jeff Brownc0cb3dc2012-01-12 18:30:12 -08001768}
1769
1770void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001771 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07001772 bool wasEmpty = connection->outboundQueue.isEmpty();
1773
Jeff Browna032cc02011-03-07 16:56:21 -08001774 // Enqueue dispatch entries for the requested modes.
1775 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001776 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
Jeff Browna032cc02011-03-07 16:56:21 -08001777 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001778 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
Jeff Browna032cc02011-03-07 16:56:21 -08001779 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001780 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
Jeff Browna032cc02011-03-07 16:56:21 -08001781 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001782 InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brown98db5fa2011-06-08 15:37:10 -07001783 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001784 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
Jeff Brown98db5fa2011-06-08 15:37:10 -07001785 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001786 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Jeff Browna032cc02011-03-07 16:56:21 -08001787
1788 // If the outbound queue was previously empty, start the dispatch cycle going.
Jeff Brownb6110c22011-04-01 16:15:13 -07001789 if (wasEmpty && !connection->outboundQueue.isEmpty()) {
Jeff Browna032cc02011-03-07 16:56:21 -08001790 startDispatchCycleLocked(currentTime, connection);
1791 }
1792}
1793
1794void InputDispatcher::enqueueDispatchEntryLocked(
1795 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001796 int32_t dispatchMode) {
Jeff Browna032cc02011-03-07 16:56:21 -08001797 int32_t inputTargetFlags = inputTarget->flags;
1798 if (!(inputTargetFlags & dispatchMode)) {
1799 return;
1800 }
1801 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
1802
Jeff Brown46b9ac02010-04-22 18:58:52 -07001803 // This is a new event.
1804 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Jeff Brownac386072011-07-20 15:19:50 -07001805 DispatchEntry* dispatchEntry = new DispatchEntry(eventEntry, // increments ref
Dianne Hackbornaa9d84c2011-05-09 19:00:59 -07001806 inputTargetFlags, inputTarget->xOffset, inputTarget->yOffset,
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001807 inputTarget->scaleFactor);
Jeff Brown6ec402b2010-07-28 15:48:59 -07001808
Jeff Brown81346812011-06-28 20:08:48 -07001809 // Apply target flags and update the connection's input state.
1810 switch (eventEntry->type) {
1811 case EventEntry::TYPE_KEY: {
1812 KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
1813 dispatchEntry->resolvedAction = keyEntry->action;
1814 dispatchEntry->resolvedFlags = keyEntry->flags;
1815
1816 if (!connection->inputState.trackKey(keyEntry,
1817 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags)) {
1818#if DEBUG_DISPATCH_CYCLE
Steve Block5baa3a62011-12-20 16:23:08 +00001819 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
Jeff Brown81346812011-06-28 20:08:48 -07001820 connection->getInputChannelName());
1821#endif
Jeff Brownc0cb3dc2012-01-12 18:30:12 -08001822 delete dispatchEntry;
Jeff Brown81346812011-06-28 20:08:48 -07001823 return; // skip the inconsistent event
1824 }
1825 break;
1826 }
1827
1828 case EventEntry::TYPE_MOTION: {
1829 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
1830 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
1831 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
1832 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
1833 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
1834 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
1835 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
1836 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
1837 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
1838 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
1839 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
1840 } else {
1841 dispatchEntry->resolvedAction = motionEntry->action;
1842 }
1843 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE
1844 && !connection->inputState.isHovering(
1845 motionEntry->deviceId, motionEntry->source)) {
1846#if DEBUG_DISPATCH_CYCLE
Steve Block5baa3a62011-12-20 16:23:08 +00001847 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter event",
Jeff Brown81346812011-06-28 20:08:48 -07001848 connection->getInputChannelName());
1849#endif
1850 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
1851 }
1852
1853 dispatchEntry->resolvedFlags = motionEntry->flags;
1854 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
1855 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
1856 }
1857
1858 if (!connection->inputState.trackMotion(motionEntry,
1859 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags)) {
1860#if DEBUG_DISPATCH_CYCLE
Steve Block5baa3a62011-12-20 16:23:08 +00001861 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion event",
Jeff Brown81346812011-06-28 20:08:48 -07001862 connection->getInputChannelName());
1863#endif
Jeff Brownc0cb3dc2012-01-12 18:30:12 -08001864 delete dispatchEntry;
Jeff Brown81346812011-06-28 20:08:48 -07001865 return; // skip the inconsistent event
1866 }
1867 break;
1868 }
1869 }
1870
Jeff Brownc0cb3dc2012-01-12 18:30:12 -08001871 // Remember that we are waiting for this dispatch to complete.
1872 if (dispatchEntry->hasForegroundTarget()) {
1873 incrementPendingForegroundDispatchesLocked(eventEntry);
1874 }
1875
Jeff Brown46b9ac02010-04-22 18:58:52 -07001876 // Enqueue the dispatch entry.
1877 connection->outboundQueue.enqueueAtTail(dispatchEntry);
Jeff Brown481c1572012-03-09 14:41:15 -08001878 traceOutboundQueueLengthLocked(connection);
Jeff Brown46b9ac02010-04-22 18:58:52 -07001879}
1880
Jeff Brown7fbdc842010-06-17 20:52:56 -07001881void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Jeff Brown519e0242010-09-15 15:18:56 -07001882 const sp<Connection>& connection) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07001883#if DEBUG_DISPATCH_CYCLE
Steve Block5baa3a62011-12-20 16:23:08 +00001884 ALOGD("channel '%s' ~ startDispatchCycle",
Jeff Brown46b9ac02010-04-22 18:58:52 -07001885 connection->getInputChannelName());
1886#endif
1887
Jeff Brownd1c48a02012-02-06 19:12:47 -08001888 while (connection->status == Connection::STATUS_NORMAL
1889 && !connection->outboundQueue.isEmpty()) {
1890 DispatchEntry* dispatchEntry = connection->outboundQueue.head;
Jeff Brown46b9ac02010-04-22 18:58:52 -07001891
Jeff Brownd1c48a02012-02-06 19:12:47 -08001892 // Publish the event.
1893 status_t status;
1894 EventEntry* eventEntry = dispatchEntry->eventEntry;
1895 switch (eventEntry->type) {
1896 case EventEntry::TYPE_KEY: {
1897 KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
Jeff Brown46b9ac02010-04-22 18:58:52 -07001898
Jeff Brownd1c48a02012-02-06 19:12:47 -08001899 // Publish the key event.
Jeff Brown072ec962012-02-07 14:46:57 -08001900 status = connection->inputPublisher.publishKeyEvent(dispatchEntry->seq,
Jeff Brownd1c48a02012-02-06 19:12:47 -08001901 keyEntry->deviceId, keyEntry->source,
1902 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags,
1903 keyEntry->keyCode, keyEntry->scanCode,
1904 keyEntry->metaState, keyEntry->repeatCount, keyEntry->downTime,
1905 keyEntry->eventTime);
1906 break;
1907 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001908
Jeff Brownd1c48a02012-02-06 19:12:47 -08001909 case EventEntry::TYPE_MOTION: {
1910 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
Jeff Brown46b9ac02010-04-22 18:58:52 -07001911
Jeff Brownd1c48a02012-02-06 19:12:47 -08001912 PointerCoords scaledCoords[MAX_POINTERS];
1913 const PointerCoords* usingCoords = motionEntry->pointerCoords;
Jeff Brown46b9ac02010-04-22 18:58:52 -07001914
Jeff Brownd1c48a02012-02-06 19:12:47 -08001915 // Set the X and Y offset depending on the input source.
1916 float xOffset, yOffset, scaleFactor;
1917 if ((motionEntry->source & AINPUT_SOURCE_CLASS_POINTER)
1918 && !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
1919 scaleFactor = dispatchEntry->scaleFactor;
1920 xOffset = dispatchEntry->xOffset * scaleFactor;
1921 yOffset = dispatchEntry->yOffset * scaleFactor;
1922 if (scaleFactor != 1.0f) {
1923 for (size_t i = 0; i < motionEntry->pointerCount; i++) {
1924 scaledCoords[i] = motionEntry->pointerCoords[i];
1925 scaledCoords[i].scale(scaleFactor);
1926 }
1927 usingCoords = scaledCoords;
1928 }
1929 } else {
1930 xOffset = 0.0f;
1931 yOffset = 0.0f;
1932 scaleFactor = 1.0f;
1933
1934 // We don't want the dispatch target to know.
1935 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
1936 for (size_t i = 0; i < motionEntry->pointerCount; i++) {
1937 scaledCoords[i].clear();
1938 }
1939 usingCoords = scaledCoords;
1940 }
1941 }
1942
1943 // Publish the motion event.
Jeff Brown072ec962012-02-07 14:46:57 -08001944 status = connection->inputPublisher.publishMotionEvent(dispatchEntry->seq,
Jeff Brownd1c48a02012-02-06 19:12:47 -08001945 motionEntry->deviceId, motionEntry->source,
1946 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags,
1947 motionEntry->edgeFlags, motionEntry->metaState, motionEntry->buttonState,
1948 xOffset, yOffset,
1949 motionEntry->xPrecision, motionEntry->yPrecision,
1950 motionEntry->downTime, motionEntry->eventTime,
1951 motionEntry->pointerCount, motionEntry->pointerProperties,
1952 usingCoords);
1953 break;
1954 }
1955
1956 default:
1957 ALOG_ASSERT(false);
Jeff Brown46b9ac02010-04-22 18:58:52 -07001958 return;
1959 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07001960
Jeff Brownd1c48a02012-02-06 19:12:47 -08001961 // Check the result.
Jeff Brown46b9ac02010-04-22 18:58:52 -07001962 if (status) {
Jeff Brownd1c48a02012-02-06 19:12:47 -08001963 if (status == WOULD_BLOCK) {
1964 if (connection->waitQueue.isEmpty()) {
1965 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
1966 "This is unexpected because the wait queue is empty, so the pipe "
1967 "should be empty and we shouldn't have any problems writing an "
1968 "event to it, status=%d", connection->getInputChannelName(), status);
1969 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
1970 } else {
1971 // Pipe is full and we are waiting for the app to finish process some events
1972 // before sending more events to it.
1973#if DEBUG_DISPATCH_CYCLE
1974 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
1975 "waiting for the application to catch up",
1976 connection->getInputChannelName());
1977#endif
1978 connection->inputPublisherBlocked = true;
1979 }
1980 } else {
1981 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
1982 "status=%d", connection->getInputChannelName(), status);
1983 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
1984 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07001985 return;
1986 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07001987
Jeff Brownd1c48a02012-02-06 19:12:47 -08001988 // Re-enqueue the event on the wait queue.
1989 connection->outboundQueue.dequeue(dispatchEntry);
Jeff Brown481c1572012-03-09 14:41:15 -08001990 traceOutboundQueueLengthLocked(connection);
Jeff Brownd1c48a02012-02-06 19:12:47 -08001991 connection->waitQueue.enqueueAtTail(dispatchEntry);
Jeff Brown481c1572012-03-09 14:41:15 -08001992 traceWaitQueueLengthLocked(connection);
Jeff Brown46b9ac02010-04-22 18:58:52 -07001993 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07001994}
1995
Jeff Brown7fbdc842010-06-17 20:52:56 -07001996void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Jeff Brown072ec962012-02-07 14:46:57 -08001997 const sp<Connection>& connection, uint32_t seq, bool handled) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07001998#if DEBUG_DISPATCH_CYCLE
Jeff Brown072ec962012-02-07 14:46:57 -08001999 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
2000 connection->getInputChannelName(), seq, toString(handled));
Jeff Brown46b9ac02010-04-22 18:58:52 -07002001#endif
2002
Jeff Brownd1c48a02012-02-06 19:12:47 -08002003 connection->inputPublisherBlocked = false;
2004
Jeff Brown9c3cda02010-06-15 01:31:58 -07002005 if (connection->status == Connection::STATUS_BROKEN
2006 || connection->status == Connection::STATUS_ZOMBIE) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002007 return;
2008 }
2009
Jeff Brown3915bb82010-11-05 15:02:16 -07002010 // Notify other system components and prepare to start the next dispatch cycle.
Jeff Brown072ec962012-02-07 14:46:57 -08002011 onDispatchCycleFinishedLocked(currentTime, connection, seq, handled);
Jeff Brownb88102f2010-09-08 11:49:43 -07002012}
2013
Jeff Brownb6997262010-10-08 22:31:17 -07002014void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Jeff Browncc4f7db2011-08-30 20:34:48 -07002015 const sp<Connection>& connection, bool notify) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002016#if DEBUG_DISPATCH_CYCLE
Steve Block5baa3a62011-12-20 16:23:08 +00002017 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
Jeff Browncc4f7db2011-08-30 20:34:48 -07002018 connection->getInputChannelName(), toString(notify));
Jeff Brown46b9ac02010-04-22 18:58:52 -07002019#endif
2020
Jeff Brownd1c48a02012-02-06 19:12:47 -08002021 // Clear the dispatch queues.
2022 drainDispatchQueueLocked(&connection->outboundQueue);
Jeff Brown481c1572012-03-09 14:41:15 -08002023 traceOutboundQueueLengthLocked(connection);
Jeff Brownd1c48a02012-02-06 19:12:47 -08002024 drainDispatchQueueLocked(&connection->waitQueue);
Jeff Brown481c1572012-03-09 14:41:15 -08002025 traceWaitQueueLengthLocked(connection);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002026
Jeff Brownb6997262010-10-08 22:31:17 -07002027 // The connection appears to be unrecoverably broken.
Jeff Brown9c3cda02010-06-15 01:31:58 -07002028 // Ignore already broken or zombie connections.
Jeff Brownb6997262010-10-08 22:31:17 -07002029 if (connection->status == Connection::STATUS_NORMAL) {
2030 connection->status = Connection::STATUS_BROKEN;
Jeff Brown46b9ac02010-04-22 18:58:52 -07002031
Jeff Browncc4f7db2011-08-30 20:34:48 -07002032 if (notify) {
2033 // Notify other system components.
2034 onDispatchCycleBrokenLocked(currentTime, connection);
2035 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002036 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002037}
2038
Jeff Brownd1c48a02012-02-06 19:12:47 -08002039void InputDispatcher::drainDispatchQueueLocked(Queue<DispatchEntry>* queue) {
2040 while (!queue->isEmpty()) {
2041 DispatchEntry* dispatchEntry = queue->dequeueAtHead();
2042 releaseDispatchEntryLocked(dispatchEntry);
Jeff Brownb88102f2010-09-08 11:49:43 -07002043 }
Jeff Brownb88102f2010-09-08 11:49:43 -07002044}
2045
Jeff Brownd1c48a02012-02-06 19:12:47 -08002046void InputDispatcher::releaseDispatchEntryLocked(DispatchEntry* dispatchEntry) {
2047 if (dispatchEntry->hasForegroundTarget()) {
2048 decrementPendingForegroundDispatchesLocked(dispatchEntry->eventEntry);
2049 }
2050 delete dispatchEntry;
2051}
2052
Jeff Browncbee6d62012-02-03 20:11:27 -08002053int InputDispatcher::handleReceiveCallback(int fd, int events, void* data) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002054 InputDispatcher* d = static_cast<InputDispatcher*>(data);
2055
2056 { // acquire lock
2057 AutoMutex _l(d->mLock);
2058
Jeff Browncbee6d62012-02-03 20:11:27 -08002059 ssize_t connectionIndex = d->mConnectionsByFd.indexOfKey(fd);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002060 if (connectionIndex < 0) {
Steve Block3762c312012-01-06 19:20:56 +00002061 ALOGE("Received spurious receive callback for unknown input channel. "
Jeff Browncbee6d62012-02-03 20:11:27 -08002062 "fd=%d, events=0x%x", fd, events);
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002063 return 0; // remove the callback
Jeff Brown46b9ac02010-04-22 18:58:52 -07002064 }
2065
Jeff Browncc4f7db2011-08-30 20:34:48 -07002066 bool notify;
Jeff Browncbee6d62012-02-03 20:11:27 -08002067 sp<Connection> connection = d->mConnectionsByFd.valueAt(connectionIndex);
Jeff Browncc4f7db2011-08-30 20:34:48 -07002068 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
2069 if (!(events & ALOOPER_EVENT_INPUT)) {
Steve Block8564c8d2012-01-05 23:22:43 +00002070 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
Jeff Browncc4f7db2011-08-30 20:34:48 -07002071 "events=0x%x", connection->getInputChannelName(), events);
2072 return 1;
2073 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002074
Jeff Brown1adee112012-02-07 10:25:41 -08002075 nsecs_t currentTime = now();
2076 bool gotOne = false;
2077 status_t status;
2078 for (;;) {
Jeff Brown072ec962012-02-07 14:46:57 -08002079 uint32_t seq;
2080 bool handled;
2081 status = connection->inputPublisher.receiveFinishedSignal(&seq, &handled);
Jeff Brown1adee112012-02-07 10:25:41 -08002082 if (status) {
2083 break;
2084 }
Jeff Brown072ec962012-02-07 14:46:57 -08002085 d->finishDispatchCycleLocked(currentTime, connection, seq, handled);
Jeff Brown1adee112012-02-07 10:25:41 -08002086 gotOne = true;
2087 }
2088 if (gotOne) {
Jeff Browncc4f7db2011-08-30 20:34:48 -07002089 d->runCommandsLockedInterruptible();
Jeff Brown1adee112012-02-07 10:25:41 -08002090 if (status == WOULD_BLOCK) {
2091 return 1;
2092 }
Jeff Browncc4f7db2011-08-30 20:34:48 -07002093 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002094
Jeff Brown1adee112012-02-07 10:25:41 -08002095 notify = status != DEAD_OBJECT || !connection->monitor;
2096 if (notify) {
2097 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
2098 connection->getInputChannelName(), status);
2099 }
Jeff Browncc4f7db2011-08-30 20:34:48 -07002100 } else {
2101 // Monitor channels are never explicitly unregistered.
2102 // We do it automatically when the remote endpoint is closed so don't warn
2103 // about them.
2104 notify = !connection->monitor;
2105 if (notify) {
Steve Block8564c8d2012-01-05 23:22:43 +00002106 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. "
Jeff Browncc4f7db2011-08-30 20:34:48 -07002107 "events=0x%x", connection->getInputChannelName(), events);
2108 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002109 }
2110
Jeff Browncc4f7db2011-08-30 20:34:48 -07002111 // Unregister the channel.
2112 d->unregisterInputChannelLocked(connection->inputChannel, notify);
2113 return 0; // remove the callback
Jeff Brown46b9ac02010-04-22 18:58:52 -07002114 } // release lock
2115}
2116
Jeff Brownb6997262010-10-08 22:31:17 -07002117void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Jeff Brownda3d5a92011-03-29 15:11:34 -07002118 const CancelationOptions& options) {
Jeff Browncbee6d62012-02-03 20:11:27 -08002119 for (size_t i = 0; i < mConnectionsByFd.size(); i++) {
Jeff Brownb6997262010-10-08 22:31:17 -07002120 synthesizeCancelationEventsForConnectionLocked(
Jeff Browncbee6d62012-02-03 20:11:27 -08002121 mConnectionsByFd.valueAt(i), options);
Jeff Brownb6997262010-10-08 22:31:17 -07002122 }
2123}
2124
2125void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Jeff Brownda3d5a92011-03-29 15:11:34 -07002126 const sp<InputChannel>& channel, const CancelationOptions& options) {
Jeff Brownb6997262010-10-08 22:31:17 -07002127 ssize_t index = getConnectionIndexLocked(channel);
2128 if (index >= 0) {
2129 synthesizeCancelationEventsForConnectionLocked(
Jeff Browncbee6d62012-02-03 20:11:27 -08002130 mConnectionsByFd.valueAt(index), options);
Jeff Brownb6997262010-10-08 22:31:17 -07002131 }
2132}
2133
2134void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
Jeff Brownda3d5a92011-03-29 15:11:34 -07002135 const sp<Connection>& connection, const CancelationOptions& options) {
Jeff Brownc0cb3dc2012-01-12 18:30:12 -08002136 if (connection->status == Connection::STATUS_BROKEN) {
2137 return;
2138 }
2139
Jeff Brownb6997262010-10-08 22:31:17 -07002140 nsecs_t currentTime = now();
2141
Jeff Brown8b4be5602012-02-06 16:31:05 -08002142 Vector<EventEntry*> cancelationEvents;
Jeff Brownac386072011-07-20 15:19:50 -07002143 connection->inputState.synthesizeCancelationEvents(currentTime,
Jeff Brown8b4be5602012-02-06 16:31:05 -08002144 cancelationEvents, options);
Jeff Brownb6997262010-10-08 22:31:17 -07002145
Jeff Brown8b4be5602012-02-06 16:31:05 -08002146 if (!cancelationEvents.isEmpty()) {
Jeff Brownb6997262010-10-08 22:31:17 -07002147#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00002148 ALOGD("channel '%s' ~ Synthesized %d cancelation events to bring channel back in sync "
Jeff Brownda3d5a92011-03-29 15:11:34 -07002149 "with reality: %s, mode=%d.",
Jeff Brown8b4be5602012-02-06 16:31:05 -08002150 connection->getInputChannelName(), cancelationEvents.size(),
Jeff Brownda3d5a92011-03-29 15:11:34 -07002151 options.reason, options.mode);
Jeff Brownb6997262010-10-08 22:31:17 -07002152#endif
Jeff Brown8b4be5602012-02-06 16:31:05 -08002153 for (size_t i = 0; i < cancelationEvents.size(); i++) {
2154 EventEntry* cancelationEventEntry = cancelationEvents.itemAt(i);
Jeff Brownb6997262010-10-08 22:31:17 -07002155 switch (cancelationEventEntry->type) {
2156 case EventEntry::TYPE_KEY:
2157 logOutboundKeyDetailsLocked("cancel - ",
2158 static_cast<KeyEntry*>(cancelationEventEntry));
2159 break;
2160 case EventEntry::TYPE_MOTION:
2161 logOutboundMotionDetailsLocked("cancel - ",
2162 static_cast<MotionEntry*>(cancelationEventEntry));
2163 break;
2164 }
2165
Jeff Brown81346812011-06-28 20:08:48 -07002166 InputTarget target;
Jeff Brown9302c872011-07-13 22:51:29 -07002167 sp<InputWindowHandle> windowHandle = getWindowHandleLocked(connection->inputChannel);
2168 if (windowHandle != NULL) {
Jeff Browncc4f7db2011-08-30 20:34:48 -07002169 const InputWindowInfo* windowInfo = windowHandle->getInfo();
2170 target.xOffset = -windowInfo->frameLeft;
2171 target.yOffset = -windowInfo->frameTop;
2172 target.scaleFactor = windowInfo->scaleFactor;
Jeff Brownb6997262010-10-08 22:31:17 -07002173 } else {
Jeff Brown81346812011-06-28 20:08:48 -07002174 target.xOffset = 0;
2175 target.yOffset = 0;
2176 target.scaleFactor = 1.0f;
Jeff Brownb6997262010-10-08 22:31:17 -07002177 }
Jeff Brown81346812011-06-28 20:08:48 -07002178 target.inputChannel = connection->inputChannel;
2179 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
Jeff Brownb6997262010-10-08 22:31:17 -07002180
Jeff Brown81346812011-06-28 20:08:48 -07002181 enqueueDispatchEntryLocked(connection, cancelationEventEntry, // increments ref
Jeff Brown3241b6b2012-02-03 15:08:02 -08002182 &target, InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brownb6997262010-10-08 22:31:17 -07002183
Jeff Brownac386072011-07-20 15:19:50 -07002184 cancelationEventEntry->release();
Jeff Brownb6997262010-10-08 22:31:17 -07002185 }
2186
Jeff Brownd1c48a02012-02-06 19:12:47 -08002187 startDispatchCycleLocked(currentTime, connection);
Jeff Brownb6997262010-10-08 22:31:17 -07002188 }
2189}
2190
Jeff Brown01ce2e92010-09-26 22:20:12 -07002191InputDispatcher::MotionEntry*
2192InputDispatcher::splitMotionEvent(const MotionEntry* originalMotionEntry, BitSet32 pointerIds) {
Steve Blockec193de2012-01-09 18:35:44 +00002193 ALOG_ASSERT(pointerIds.value != 0);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002194
2195 uint32_t splitPointerIndexMap[MAX_POINTERS];
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002196 PointerProperties splitPointerProperties[MAX_POINTERS];
Jeff Brown01ce2e92010-09-26 22:20:12 -07002197 PointerCoords splitPointerCoords[MAX_POINTERS];
2198
2199 uint32_t originalPointerCount = originalMotionEntry->pointerCount;
2200 uint32_t splitPointerCount = 0;
2201
2202 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
2203 originalPointerIndex++) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002204 const PointerProperties& pointerProperties =
2205 originalMotionEntry->pointerProperties[originalPointerIndex];
2206 uint32_t pointerId = uint32_t(pointerProperties.id);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002207 if (pointerIds.hasBit(pointerId)) {
2208 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002209 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
Jeff Brownace13b12011-03-09 17:39:48 -08002210 splitPointerCoords[splitPointerCount].copyFrom(
Jeff Brown3241b6b2012-02-03 15:08:02 -08002211 originalMotionEntry->pointerCoords[originalPointerIndex]);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002212 splitPointerCount += 1;
2213 }
2214 }
Jeff Brown58a2da82011-01-25 16:02:22 -08002215
2216 if (splitPointerCount != pointerIds.count()) {
2217 // This is bad. We are missing some of the pointers that we expected to deliver.
2218 // Most likely this indicates that we received an ACTION_MOVE events that has
2219 // different pointer ids than we expected based on the previous ACTION_DOWN
2220 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
2221 // in this way.
Steve Block8564c8d2012-01-05 23:22:43 +00002222 ALOGW("Dropping split motion event because the pointer count is %d but "
Jeff Brown58a2da82011-01-25 16:02:22 -08002223 "we expected there to be %d pointers. This probably means we received "
2224 "a broken sequence of pointer ids from the input device.",
2225 splitPointerCount, pointerIds.count());
2226 return NULL;
2227 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07002228
2229 int32_t action = originalMotionEntry->action;
2230 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
2231 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
2232 || maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2233 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002234 const PointerProperties& pointerProperties =
2235 originalMotionEntry->pointerProperties[originalPointerIndex];
2236 uint32_t pointerId = uint32_t(pointerProperties.id);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002237 if (pointerIds.hasBit(pointerId)) {
2238 if (pointerIds.count() == 1) {
2239 // The first/last pointer went down/up.
2240 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
2241 ? AMOTION_EVENT_ACTION_DOWN : AMOTION_EVENT_ACTION_UP;
Jeff Brown9a01d052010-09-27 16:35:11 -07002242 } else {
2243 // A secondary pointer went down/up.
2244 uint32_t splitPointerIndex = 0;
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002245 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
Jeff Brown9a01d052010-09-27 16:35:11 -07002246 splitPointerIndex += 1;
2247 }
2248 action = maskedAction | (splitPointerIndex
2249 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002250 }
2251 } else {
2252 // An unrelated pointer changed.
2253 action = AMOTION_EVENT_ACTION_MOVE;
2254 }
2255 }
2256
Jeff Brownac386072011-07-20 15:19:50 -07002257 MotionEntry* splitMotionEntry = new MotionEntry(
Jeff Brown01ce2e92010-09-26 22:20:12 -07002258 originalMotionEntry->eventTime,
2259 originalMotionEntry->deviceId,
2260 originalMotionEntry->source,
2261 originalMotionEntry->policyFlags,
2262 action,
2263 originalMotionEntry->flags,
2264 originalMotionEntry->metaState,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002265 originalMotionEntry->buttonState,
Jeff Brown01ce2e92010-09-26 22:20:12 -07002266 originalMotionEntry->edgeFlags,
2267 originalMotionEntry->xPrecision,
2268 originalMotionEntry->yPrecision,
2269 originalMotionEntry->downTime,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002270 splitPointerCount, splitPointerProperties, splitPointerCoords);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002271
Jeff Browna032cc02011-03-07 16:56:21 -08002272 if (originalMotionEntry->injectionState) {
2273 splitMotionEntry->injectionState = originalMotionEntry->injectionState;
2274 splitMotionEntry->injectionState->refCount += 1;
2275 }
2276
Jeff Brown01ce2e92010-09-26 22:20:12 -07002277 return splitMotionEntry;
2278}
2279
Jeff Brownbe1aa822011-07-27 16:04:54 -07002280void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002281#if DEBUG_INBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00002282 ALOGD("notifyConfigurationChanged - eventTime=%lld", args->eventTime);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002283#endif
2284
Jeff Brownb88102f2010-09-08 11:49:43 -07002285 bool needWake;
Jeff Brown46b9ac02010-04-22 18:58:52 -07002286 { // acquire lock
2287 AutoMutex _l(mLock);
2288
Jeff Brownbe1aa822011-07-27 16:04:54 -07002289 ConfigurationChangedEntry* newEntry = new ConfigurationChangedEntry(args->eventTime);
Jeff Brownb88102f2010-09-08 11:49:43 -07002290 needWake = enqueueInboundEventLocked(newEntry);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002291 } // release lock
2292
Jeff Brownb88102f2010-09-08 11:49:43 -07002293 if (needWake) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002294 mLooper->wake();
Jeff Brown46b9ac02010-04-22 18:58:52 -07002295 }
2296}
2297
Jeff Brownbe1aa822011-07-27 16:04:54 -07002298void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002299#if DEBUG_INBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00002300 ALOGD("notifyKey - eventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, action=0x%x, "
Jeff Brown46b9ac02010-04-22 18:58:52 -07002301 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%lld",
Jeff Brownbe1aa822011-07-27 16:04:54 -07002302 args->eventTime, args->deviceId, args->source, args->policyFlags,
2303 args->action, args->flags, args->keyCode, args->scanCode,
2304 args->metaState, args->downTime);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002305#endif
Jeff Brownbe1aa822011-07-27 16:04:54 -07002306 if (!validateKeyEvent(args->action)) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002307 return;
2308 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002309
Jeff Brownbe1aa822011-07-27 16:04:54 -07002310 uint32_t policyFlags = args->policyFlags;
2311 int32_t flags = args->flags;
2312 int32_t metaState = args->metaState;
Jeff Brown1f245102010-11-18 20:53:46 -08002313 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
2314 policyFlags |= POLICY_FLAG_VIRTUAL;
2315 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
2316 }
Jeff Brown924c4d42011-03-07 16:40:47 -08002317 if (policyFlags & POLICY_FLAG_ALT) {
2318 metaState |= AMETA_ALT_ON | AMETA_ALT_LEFT_ON;
2319 }
2320 if (policyFlags & POLICY_FLAG_ALT_GR) {
2321 metaState |= AMETA_ALT_ON | AMETA_ALT_RIGHT_ON;
2322 }
2323 if (policyFlags & POLICY_FLAG_SHIFT) {
2324 metaState |= AMETA_SHIFT_ON | AMETA_SHIFT_LEFT_ON;
2325 }
2326 if (policyFlags & POLICY_FLAG_CAPS_LOCK) {
2327 metaState |= AMETA_CAPS_LOCK_ON;
2328 }
2329 if (policyFlags & POLICY_FLAG_FUNCTION) {
2330 metaState |= AMETA_FUNCTION_ON;
2331 }
Jeff Brown1f245102010-11-18 20:53:46 -08002332
Jeff Browne20c9e02010-10-11 14:20:19 -07002333 policyFlags |= POLICY_FLAG_TRUSTED;
Jeff Brown1f245102010-11-18 20:53:46 -08002334
2335 KeyEvent event;
Jeff Brownbe1aa822011-07-27 16:04:54 -07002336 event.initialize(args->deviceId, args->source, args->action,
2337 flags, args->keyCode, args->scanCode, metaState, 0,
2338 args->downTime, args->eventTime);
Jeff Brown1f245102010-11-18 20:53:46 -08002339
2340 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
2341
2342 if (policyFlags & POLICY_FLAG_WOKE_HERE) {
2343 flags |= AKEY_EVENT_FLAG_WOKE_HERE;
2344 }
Jeff Brownb6997262010-10-08 22:31:17 -07002345
Jeff Brownb88102f2010-09-08 11:49:43 -07002346 bool needWake;
Jeff Brown46b9ac02010-04-22 18:58:52 -07002347 { // acquire lock
Jeff Brown0029c662011-03-30 02:25:18 -07002348 mLock.lock();
2349
2350 if (mInputFilterEnabled) {
2351 mLock.unlock();
2352
2353 policyFlags |= POLICY_FLAG_FILTERED;
2354 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2355 return; // event was consumed by the filter
2356 }
2357
2358 mLock.lock();
2359 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002360
Jeff Brown7fbdc842010-06-17 20:52:56 -07002361 int32_t repeatCount = 0;
Jeff Brownbe1aa822011-07-27 16:04:54 -07002362 KeyEntry* newEntry = new KeyEntry(args->eventTime,
2363 args->deviceId, args->source, policyFlags,
2364 args->action, flags, args->keyCode, args->scanCode,
2365 metaState, repeatCount, args->downTime);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002366
Jeff Brownb88102f2010-09-08 11:49:43 -07002367 needWake = enqueueInboundEventLocked(newEntry);
Jeff Brown0029c662011-03-30 02:25:18 -07002368 mLock.unlock();
Jeff Brown46b9ac02010-04-22 18:58:52 -07002369 } // release lock
2370
Jeff Brownb88102f2010-09-08 11:49:43 -07002371 if (needWake) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002372 mLooper->wake();
Jeff Brown46b9ac02010-04-22 18:58:52 -07002373 }
2374}
2375
Jeff Brownbe1aa822011-07-27 16:04:54 -07002376void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002377#if DEBUG_INBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00002378 ALOGD("notifyMotion - eventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, "
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002379 "action=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, edgeFlags=0x%x, "
Jeff Brown85a31762010-09-01 17:01:00 -07002380 "xPrecision=%f, yPrecision=%f, downTime=%lld",
Jeff Brownbe1aa822011-07-27 16:04:54 -07002381 args->eventTime, args->deviceId, args->source, args->policyFlags,
2382 args->action, args->flags, args->metaState, args->buttonState,
2383 args->edgeFlags, args->xPrecision, args->yPrecision, args->downTime);
2384 for (uint32_t i = 0; i < args->pointerCount; i++) {
Steve Block5baa3a62011-12-20 16:23:08 +00002385 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002386 "x=%f, y=%f, pressure=%f, size=%f, "
Jeff Brown85a31762010-09-01 17:01:00 -07002387 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
Jeff Brown8d608662010-08-30 03:02:23 -07002388 "orientation=%f",
Jeff Brownbe1aa822011-07-27 16:04:54 -07002389 i, args->pointerProperties[i].id,
2390 args->pointerProperties[i].toolType,
2391 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
2392 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
2393 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
2394 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
2395 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
2396 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
2397 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
2398 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
2399 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Jeff Brown46b9ac02010-04-22 18:58:52 -07002400 }
2401#endif
Jeff Brownbe1aa822011-07-27 16:04:54 -07002402 if (!validateMotionEvent(args->action, args->pointerCount, args->pointerProperties)) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002403 return;
2404 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002405
Jeff Brownbe1aa822011-07-27 16:04:54 -07002406 uint32_t policyFlags = args->policyFlags;
Jeff Browne20c9e02010-10-11 14:20:19 -07002407 policyFlags |= POLICY_FLAG_TRUSTED;
Jeff Brownbe1aa822011-07-27 16:04:54 -07002408 mPolicy->interceptMotionBeforeQueueing(args->eventTime, /*byref*/ policyFlags);
Jeff Brownb6997262010-10-08 22:31:17 -07002409
Jeff Brownb88102f2010-09-08 11:49:43 -07002410 bool needWake;
Jeff Brown46b9ac02010-04-22 18:58:52 -07002411 { // acquire lock
Jeff Brown0029c662011-03-30 02:25:18 -07002412 mLock.lock();
2413
2414 if (mInputFilterEnabled) {
2415 mLock.unlock();
2416
2417 MotionEvent event;
Jeff Brownbe1aa822011-07-27 16:04:54 -07002418 event.initialize(args->deviceId, args->source, args->action, args->flags,
2419 args->edgeFlags, args->metaState, args->buttonState, 0, 0,
2420 args->xPrecision, args->yPrecision,
2421 args->downTime, args->eventTime,
2422 args->pointerCount, args->pointerProperties, args->pointerCoords);
Jeff Brown0029c662011-03-30 02:25:18 -07002423
2424 policyFlags |= POLICY_FLAG_FILTERED;
2425 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2426 return; // event was consumed by the filter
2427 }
2428
2429 mLock.lock();
2430 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002431
Jeff Brown46b9ac02010-04-22 18:58:52 -07002432 // Just enqueue a new motion event.
Jeff Brownbe1aa822011-07-27 16:04:54 -07002433 MotionEntry* newEntry = new MotionEntry(args->eventTime,
2434 args->deviceId, args->source, policyFlags,
2435 args->action, args->flags, args->metaState, args->buttonState,
2436 args->edgeFlags, args->xPrecision, args->yPrecision, args->downTime,
2437 args->pointerCount, args->pointerProperties, args->pointerCoords);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002438
Jeff Brownb88102f2010-09-08 11:49:43 -07002439 needWake = enqueueInboundEventLocked(newEntry);
Jeff Brown0029c662011-03-30 02:25:18 -07002440 mLock.unlock();
Jeff Brown46b9ac02010-04-22 18:58:52 -07002441 } // release lock
2442
Jeff Brownb88102f2010-09-08 11:49:43 -07002443 if (needWake) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002444 mLooper->wake();
Jeff Brown46b9ac02010-04-22 18:58:52 -07002445 }
2446}
2447
Jeff Brownbe1aa822011-07-27 16:04:54 -07002448void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
Jeff Brownb6997262010-10-08 22:31:17 -07002449#if DEBUG_INBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00002450 ALOGD("notifySwitch - eventTime=%lld, policyFlags=0x%x, switchCode=%d, switchValue=%d",
Jeff Brownbe1aa822011-07-27 16:04:54 -07002451 args->eventTime, args->policyFlags,
2452 args->switchCode, args->switchValue);
Jeff Brownb6997262010-10-08 22:31:17 -07002453#endif
2454
Jeff Brownbe1aa822011-07-27 16:04:54 -07002455 uint32_t policyFlags = args->policyFlags;
Jeff Browne20c9e02010-10-11 14:20:19 -07002456 policyFlags |= POLICY_FLAG_TRUSTED;
Jeff Brownbe1aa822011-07-27 16:04:54 -07002457 mPolicy->notifySwitch(args->eventTime,
2458 args->switchCode, args->switchValue, policyFlags);
Jeff Brownb6997262010-10-08 22:31:17 -07002459}
2460
Jeff Brown65fd2512011-08-18 11:20:58 -07002461void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
2462#if DEBUG_INBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00002463 ALOGD("notifyDeviceReset - eventTime=%lld, deviceId=%d",
Jeff Brown65fd2512011-08-18 11:20:58 -07002464 args->eventTime, args->deviceId);
2465#endif
2466
2467 bool needWake;
2468 { // acquire lock
2469 AutoMutex _l(mLock);
2470
2471 DeviceResetEntry* newEntry = new DeviceResetEntry(args->eventTime, args->deviceId);
2472 needWake = enqueueInboundEventLocked(newEntry);
2473 } // release lock
2474
2475 if (needWake) {
2476 mLooper->wake();
2477 }
2478}
2479
Jeff Brown7fbdc842010-06-17 20:52:56 -07002480int32_t InputDispatcher::injectInputEvent(const InputEvent* event,
Jeff Brown0029c662011-03-30 02:25:18 -07002481 int32_t injectorPid, int32_t injectorUid, int32_t syncMode, int32_t timeoutMillis,
2482 uint32_t policyFlags) {
Jeff Brown7fbdc842010-06-17 20:52:56 -07002483#if DEBUG_INBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00002484 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Jeff Brown0029c662011-03-30 02:25:18 -07002485 "syncMode=%d, timeoutMillis=%d, policyFlags=0x%08x",
2486 event->getType(), injectorPid, injectorUid, syncMode, timeoutMillis, policyFlags);
Jeff Brown7fbdc842010-06-17 20:52:56 -07002487#endif
2488
2489 nsecs_t endTime = now() + milliseconds_to_nanoseconds(timeoutMillis);
Jeff Browne20c9e02010-10-11 14:20:19 -07002490
Jeff Brown0029c662011-03-30 02:25:18 -07002491 policyFlags |= POLICY_FLAG_INJECTED;
Jeff Browne20c9e02010-10-11 14:20:19 -07002492 if (hasInjectionPermission(injectorPid, injectorUid)) {
2493 policyFlags |= POLICY_FLAG_TRUSTED;
2494 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07002495
Jeff Brown3241b6b2012-02-03 15:08:02 -08002496 EventEntry* firstInjectedEntry;
2497 EventEntry* lastInjectedEntry;
Jeff Brownb6997262010-10-08 22:31:17 -07002498 switch (event->getType()) {
2499 case AINPUT_EVENT_TYPE_KEY: {
2500 const KeyEvent* keyEvent = static_cast<const KeyEvent*>(event);
2501 int32_t action = keyEvent->getAction();
2502 if (! validateKeyEvent(action)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07002503 return INPUT_EVENT_INJECTION_FAILED;
2504 }
2505
Jeff Brownb6997262010-10-08 22:31:17 -07002506 int32_t flags = keyEvent->getFlags();
Jeff Brown1f245102010-11-18 20:53:46 -08002507 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
2508 policyFlags |= POLICY_FLAG_VIRTUAL;
2509 }
2510
Jeff Brown0029c662011-03-30 02:25:18 -07002511 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
2512 mPolicy->interceptKeyBeforeQueueing(keyEvent, /*byref*/ policyFlags);
2513 }
Jeff Brown1f245102010-11-18 20:53:46 -08002514
2515 if (policyFlags & POLICY_FLAG_WOKE_HERE) {
2516 flags |= AKEY_EVENT_FLAG_WOKE_HERE;
2517 }
Jeff Brown6ec402b2010-07-28 15:48:59 -07002518
Jeff Brownb6997262010-10-08 22:31:17 -07002519 mLock.lock();
Jeff Brown3241b6b2012-02-03 15:08:02 -08002520 firstInjectedEntry = new KeyEntry(keyEvent->getEventTime(),
Jeff Brown1f245102010-11-18 20:53:46 -08002521 keyEvent->getDeviceId(), keyEvent->getSource(),
2522 policyFlags, action, flags,
2523 keyEvent->getKeyCode(), keyEvent->getScanCode(), keyEvent->getMetaState(),
Jeff Brownb6997262010-10-08 22:31:17 -07002524 keyEvent->getRepeatCount(), keyEvent->getDownTime());
Jeff Brown3241b6b2012-02-03 15:08:02 -08002525 lastInjectedEntry = firstInjectedEntry;
Jeff Brownb6997262010-10-08 22:31:17 -07002526 break;
2527 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07002528
Jeff Brownb6997262010-10-08 22:31:17 -07002529 case AINPUT_EVENT_TYPE_MOTION: {
2530 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
2531 int32_t action = motionEvent->getAction();
2532 size_t pointerCount = motionEvent->getPointerCount();
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002533 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
2534 if (! validateMotionEvent(action, pointerCount, pointerProperties)) {
Jeff Brownb6997262010-10-08 22:31:17 -07002535 return INPUT_EVENT_INJECTION_FAILED;
2536 }
2537
Jeff Brown0029c662011-03-30 02:25:18 -07002538 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
2539 nsecs_t eventTime = motionEvent->getEventTime();
2540 mPolicy->interceptMotionBeforeQueueing(eventTime, /*byref*/ policyFlags);
2541 }
Jeff Brownb6997262010-10-08 22:31:17 -07002542
2543 mLock.lock();
2544 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
2545 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
Jeff Brown3241b6b2012-02-03 15:08:02 -08002546 firstInjectedEntry = new MotionEntry(*sampleEventTimes,
Jeff Brownb6997262010-10-08 22:31:17 -07002547 motionEvent->getDeviceId(), motionEvent->getSource(), policyFlags,
2548 action, motionEvent->getFlags(),
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002549 motionEvent->getMetaState(), motionEvent->getButtonState(),
2550 motionEvent->getEdgeFlags(),
Jeff Brownb6997262010-10-08 22:31:17 -07002551 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
2552 motionEvent->getDownTime(), uint32_t(pointerCount),
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002553 pointerProperties, samplePointerCoords);
Jeff Brown3241b6b2012-02-03 15:08:02 -08002554 lastInjectedEntry = firstInjectedEntry;
Jeff Brownb6997262010-10-08 22:31:17 -07002555 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
2556 sampleEventTimes += 1;
2557 samplePointerCoords += pointerCount;
Jeff Brown3241b6b2012-02-03 15:08:02 -08002558 MotionEntry* nextInjectedEntry = new MotionEntry(*sampleEventTimes,
2559 motionEvent->getDeviceId(), motionEvent->getSource(), policyFlags,
2560 action, motionEvent->getFlags(),
2561 motionEvent->getMetaState(), motionEvent->getButtonState(),
2562 motionEvent->getEdgeFlags(),
2563 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
2564 motionEvent->getDownTime(), uint32_t(pointerCount),
2565 pointerProperties, samplePointerCoords);
2566 lastInjectedEntry->next = nextInjectedEntry;
2567 lastInjectedEntry = nextInjectedEntry;
Jeff Brownb6997262010-10-08 22:31:17 -07002568 }
Jeff Brownb6997262010-10-08 22:31:17 -07002569 break;
2570 }
2571
2572 default:
Steve Block8564c8d2012-01-05 23:22:43 +00002573 ALOGW("Cannot inject event of type %d", event->getType());
Jeff Brownb6997262010-10-08 22:31:17 -07002574 return INPUT_EVENT_INJECTION_FAILED;
2575 }
2576
Jeff Brownac386072011-07-20 15:19:50 -07002577 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
Jeff Brownb6997262010-10-08 22:31:17 -07002578 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
2579 injectionState->injectionIsAsync = true;
2580 }
2581
2582 injectionState->refCount += 1;
Jeff Brown3241b6b2012-02-03 15:08:02 -08002583 lastInjectedEntry->injectionState = injectionState;
Jeff Brownb6997262010-10-08 22:31:17 -07002584
Jeff Brown3241b6b2012-02-03 15:08:02 -08002585 bool needWake = false;
2586 for (EventEntry* entry = firstInjectedEntry; entry != NULL; ) {
2587 EventEntry* nextEntry = entry->next;
2588 needWake |= enqueueInboundEventLocked(entry);
2589 entry = nextEntry;
2590 }
2591
Jeff Brownb6997262010-10-08 22:31:17 -07002592 mLock.unlock();
Jeff Brown7fbdc842010-06-17 20:52:56 -07002593
Jeff Brownb88102f2010-09-08 11:49:43 -07002594 if (needWake) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002595 mLooper->wake();
Jeff Brown7fbdc842010-06-17 20:52:56 -07002596 }
2597
2598 int32_t injectionResult;
2599 { // acquire lock
2600 AutoMutex _l(mLock);
2601
Jeff Brown6ec402b2010-07-28 15:48:59 -07002602 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
2603 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
2604 } else {
2605 for (;;) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002606 injectionResult = injectionState->injectionResult;
Jeff Brown6ec402b2010-07-28 15:48:59 -07002607 if (injectionResult != INPUT_EVENT_INJECTION_PENDING) {
2608 break;
2609 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07002610
Jeff Brown7fbdc842010-06-17 20:52:56 -07002611 nsecs_t remainingTimeout = endTime - now();
2612 if (remainingTimeout <= 0) {
Jeff Brown6ec402b2010-07-28 15:48:59 -07002613#if DEBUG_INJECTION
Steve Block5baa3a62011-12-20 16:23:08 +00002614 ALOGD("injectInputEvent - Timed out waiting for injection result "
Jeff Brown6ec402b2010-07-28 15:48:59 -07002615 "to become available.");
2616#endif
Jeff Brown7fbdc842010-06-17 20:52:56 -07002617 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
2618 break;
2619 }
2620
Jeff Brown6ec402b2010-07-28 15:48:59 -07002621 mInjectionResultAvailableCondition.waitRelative(mLock, remainingTimeout);
2622 }
2623
2624 if (injectionResult == INPUT_EVENT_INJECTION_SUCCEEDED
2625 && syncMode == INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002626 while (injectionState->pendingForegroundDispatches != 0) {
Jeff Brown6ec402b2010-07-28 15:48:59 -07002627#if DEBUG_INJECTION
Steve Block5baa3a62011-12-20 16:23:08 +00002628 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
Jeff Brown01ce2e92010-09-26 22:20:12 -07002629 injectionState->pendingForegroundDispatches);
Jeff Brown6ec402b2010-07-28 15:48:59 -07002630#endif
2631 nsecs_t remainingTimeout = endTime - now();
2632 if (remainingTimeout <= 0) {
2633#if DEBUG_INJECTION
Steve Block5baa3a62011-12-20 16:23:08 +00002634 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
Jeff Brown6ec402b2010-07-28 15:48:59 -07002635 "dispatches to finish.");
2636#endif
2637 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
2638 break;
2639 }
2640
2641 mInjectionSyncFinishedCondition.waitRelative(mLock, remainingTimeout);
2642 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07002643 }
2644 }
2645
Jeff Brownac386072011-07-20 15:19:50 -07002646 injectionState->release();
Jeff Brown7fbdc842010-06-17 20:52:56 -07002647 } // release lock
2648
Jeff Brown6ec402b2010-07-28 15:48:59 -07002649#if DEBUG_INJECTION
Steve Block5baa3a62011-12-20 16:23:08 +00002650 ALOGD("injectInputEvent - Finished with result %d. "
Jeff Brown6ec402b2010-07-28 15:48:59 -07002651 "injectorPid=%d, injectorUid=%d",
2652 injectionResult, injectorPid, injectorUid);
2653#endif
2654
Jeff Brown7fbdc842010-06-17 20:52:56 -07002655 return injectionResult;
2656}
2657
Jeff Brownb6997262010-10-08 22:31:17 -07002658bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
2659 return injectorUid == 0
2660 || mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
2661}
2662
Jeff Brown7fbdc842010-06-17 20:52:56 -07002663void InputDispatcher::setInjectionResultLocked(EventEntry* entry, int32_t injectionResult) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002664 InjectionState* injectionState = entry->injectionState;
2665 if (injectionState) {
Jeff Brown7fbdc842010-06-17 20:52:56 -07002666#if DEBUG_INJECTION
Steve Block5baa3a62011-12-20 16:23:08 +00002667 ALOGD("Setting input event injection result to %d. "
Jeff Brown7fbdc842010-06-17 20:52:56 -07002668 "injectorPid=%d, injectorUid=%d",
Jeff Brown01ce2e92010-09-26 22:20:12 -07002669 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
Jeff Brown7fbdc842010-06-17 20:52:56 -07002670#endif
2671
Jeff Brown0029c662011-03-30 02:25:18 -07002672 if (injectionState->injectionIsAsync
2673 && !(entry->policyFlags & POLICY_FLAG_FILTERED)) {
Jeff Brown6ec402b2010-07-28 15:48:59 -07002674 // Log the outcome since the injector did not wait for the injection result.
2675 switch (injectionResult) {
2676 case INPUT_EVENT_INJECTION_SUCCEEDED:
Steve Block71f2cf12011-10-20 11:56:00 +01002677 ALOGV("Asynchronous input event injection succeeded.");
Jeff Brown6ec402b2010-07-28 15:48:59 -07002678 break;
2679 case INPUT_EVENT_INJECTION_FAILED:
Steve Block8564c8d2012-01-05 23:22:43 +00002680 ALOGW("Asynchronous input event injection failed.");
Jeff Brown6ec402b2010-07-28 15:48:59 -07002681 break;
2682 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
Steve Block8564c8d2012-01-05 23:22:43 +00002683 ALOGW("Asynchronous input event injection permission denied.");
Jeff Brown6ec402b2010-07-28 15:48:59 -07002684 break;
2685 case INPUT_EVENT_INJECTION_TIMED_OUT:
Steve Block8564c8d2012-01-05 23:22:43 +00002686 ALOGW("Asynchronous input event injection timed out.");
Jeff Brown6ec402b2010-07-28 15:48:59 -07002687 break;
2688 }
2689 }
2690
Jeff Brown01ce2e92010-09-26 22:20:12 -07002691 injectionState->injectionResult = injectionResult;
Jeff Brown7fbdc842010-06-17 20:52:56 -07002692 mInjectionResultAvailableCondition.broadcast();
2693 }
2694}
2695
Jeff Brown01ce2e92010-09-26 22:20:12 -07002696void InputDispatcher::incrementPendingForegroundDispatchesLocked(EventEntry* entry) {
2697 InjectionState* injectionState = entry->injectionState;
2698 if (injectionState) {
2699 injectionState->pendingForegroundDispatches += 1;
2700 }
2701}
2702
Jeff Brown519e0242010-09-15 15:18:56 -07002703void InputDispatcher::decrementPendingForegroundDispatchesLocked(EventEntry* entry) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002704 InjectionState* injectionState = entry->injectionState;
2705 if (injectionState) {
2706 injectionState->pendingForegroundDispatches -= 1;
Jeff Brown6ec402b2010-07-28 15:48:59 -07002707
Jeff Brown01ce2e92010-09-26 22:20:12 -07002708 if (injectionState->pendingForegroundDispatches == 0) {
2709 mInjectionSyncFinishedCondition.broadcast();
2710 }
Jeff Brownb88102f2010-09-08 11:49:43 -07002711 }
2712}
2713
Jeff Brown9302c872011-07-13 22:51:29 -07002714sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
2715 const sp<InputChannel>& inputChannel) const {
2716 size_t numWindows = mWindowHandles.size();
2717 for (size_t i = 0; i < numWindows; i++) {
2718 const sp<InputWindowHandle>& windowHandle = mWindowHandles.itemAt(i);
Jeff Browncc4f7db2011-08-30 20:34:48 -07002719 if (windowHandle->getInputChannel() == inputChannel) {
Jeff Brown9302c872011-07-13 22:51:29 -07002720 return windowHandle;
Jeff Brown01ce2e92010-09-26 22:20:12 -07002721 }
2722 }
2723 return NULL;
2724}
2725
Jeff Brown9302c872011-07-13 22:51:29 -07002726bool InputDispatcher::hasWindowHandleLocked(
2727 const sp<InputWindowHandle>& windowHandle) const {
2728 size_t numWindows = mWindowHandles.size();
2729 for (size_t i = 0; i < numWindows; i++) {
2730 if (mWindowHandles.itemAt(i) == windowHandle) {
2731 return true;
2732 }
2733 }
2734 return false;
2735}
2736
2737void InputDispatcher::setInputWindows(const Vector<sp<InputWindowHandle> >& inputWindowHandles) {
Jeff Brownb88102f2010-09-08 11:49:43 -07002738#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002739 ALOGD("setInputWindows");
Jeff Brownb88102f2010-09-08 11:49:43 -07002740#endif
2741 { // acquire lock
2742 AutoMutex _l(mLock);
2743
Jeff Browncc4f7db2011-08-30 20:34:48 -07002744 Vector<sp<InputWindowHandle> > oldWindowHandles = mWindowHandles;
Jeff Brown9302c872011-07-13 22:51:29 -07002745 mWindowHandles = inputWindowHandles;
Jeff Brownb6997262010-10-08 22:31:17 -07002746
Jeff Brown9302c872011-07-13 22:51:29 -07002747 sp<InputWindowHandle> newFocusedWindowHandle;
2748 bool foundHoveredWindow = false;
2749 for (size_t i = 0; i < mWindowHandles.size(); i++) {
2750 const sp<InputWindowHandle>& windowHandle = mWindowHandles.itemAt(i);
Jeff Browncc4f7db2011-08-30 20:34:48 -07002751 if (!windowHandle->updateInfo() || windowHandle->getInputChannel() == NULL) {
Jeff Brown9302c872011-07-13 22:51:29 -07002752 mWindowHandles.removeAt(i--);
2753 continue;
2754 }
Jeff Browncc4f7db2011-08-30 20:34:48 -07002755 if (windowHandle->getInfo()->hasFocus) {
Jeff Brown9302c872011-07-13 22:51:29 -07002756 newFocusedWindowHandle = windowHandle;
2757 }
2758 if (windowHandle == mLastHoverWindowHandle) {
2759 foundHoveredWindow = true;
Jeff Brownb88102f2010-09-08 11:49:43 -07002760 }
2761 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07002762
Jeff Brown9302c872011-07-13 22:51:29 -07002763 if (!foundHoveredWindow) {
2764 mLastHoverWindowHandle = NULL;
2765 }
2766
2767 if (mFocusedWindowHandle != newFocusedWindowHandle) {
2768 if (mFocusedWindowHandle != NULL) {
Jeff Brownb6997262010-10-08 22:31:17 -07002769#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002770 ALOGD("Focus left window: %s",
Jeff Browncc4f7db2011-08-30 20:34:48 -07002771 mFocusedWindowHandle->getName().string());
Jeff Brownb6997262010-10-08 22:31:17 -07002772#endif
Jeff Browncc4f7db2011-08-30 20:34:48 -07002773 sp<InputChannel> focusedInputChannel = mFocusedWindowHandle->getInputChannel();
2774 if (focusedInputChannel != NULL) {
Christopher Tated9be36c2011-08-16 16:09:33 -07002775 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
2776 "focus left window");
2777 synthesizeCancelationEventsForInputChannelLocked(
Jeff Browncc4f7db2011-08-30 20:34:48 -07002778 focusedInputChannel, options);
Christopher Tated9be36c2011-08-16 16:09:33 -07002779 }
Jeff Brownb6997262010-10-08 22:31:17 -07002780 }
Jeff Brown9302c872011-07-13 22:51:29 -07002781 if (newFocusedWindowHandle != NULL) {
Jeff Brownb6997262010-10-08 22:31:17 -07002782#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002783 ALOGD("Focus entered window: %s",
Jeff Browncc4f7db2011-08-30 20:34:48 -07002784 newFocusedWindowHandle->getName().string());
Jeff Brownb6997262010-10-08 22:31:17 -07002785#endif
Jeff Brown9302c872011-07-13 22:51:29 -07002786 }
2787 mFocusedWindowHandle = newFocusedWindowHandle;
Jeff Brownb6997262010-10-08 22:31:17 -07002788 }
2789
Jeff Brown9302c872011-07-13 22:51:29 -07002790 for (size_t i = 0; i < mTouchState.windows.size(); i++) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002791 TouchedWindow& touchedWindow = mTouchState.windows.editItemAt(i);
Jeff Brown9302c872011-07-13 22:51:29 -07002792 if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
Jeff Brownb6997262010-10-08 22:31:17 -07002793#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002794 ALOGD("Touched window was removed: %s",
Jeff Browncc4f7db2011-08-30 20:34:48 -07002795 touchedWindow.windowHandle->getName().string());
Jeff Brownb6997262010-10-08 22:31:17 -07002796#endif
Jeff Browncc4f7db2011-08-30 20:34:48 -07002797 sp<InputChannel> touchedInputChannel =
2798 touchedWindow.windowHandle->getInputChannel();
2799 if (touchedInputChannel != NULL) {
Christopher Tated9be36c2011-08-16 16:09:33 -07002800 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
2801 "touched window was removed");
2802 synthesizeCancelationEventsForInputChannelLocked(
Jeff Browncc4f7db2011-08-30 20:34:48 -07002803 touchedInputChannel, options);
Christopher Tated9be36c2011-08-16 16:09:33 -07002804 }
Jeff Brown9302c872011-07-13 22:51:29 -07002805 mTouchState.windows.removeAt(i--);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002806 }
2807 }
Jeff Browncc4f7db2011-08-30 20:34:48 -07002808
2809 // Release information for windows that are no longer present.
2810 // This ensures that unused input channels are released promptly.
2811 // Otherwise, they might stick around until the window handle is destroyed
2812 // which might not happen until the next GC.
2813 for (size_t i = 0; i < oldWindowHandles.size(); i++) {
2814 const sp<InputWindowHandle>& oldWindowHandle = oldWindowHandles.itemAt(i);
2815 if (!hasWindowHandleLocked(oldWindowHandle)) {
2816#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002817 ALOGD("Window went away: %s", oldWindowHandle->getName().string());
Jeff Browncc4f7db2011-08-30 20:34:48 -07002818#endif
2819 oldWindowHandle->releaseInfo();
2820 }
2821 }
Jeff Brownb88102f2010-09-08 11:49:43 -07002822 } // release lock
2823
2824 // Wake up poll loop since it may need to make new input dispatching choices.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002825 mLooper->wake();
Jeff Brownb88102f2010-09-08 11:49:43 -07002826}
2827
Jeff Brown9302c872011-07-13 22:51:29 -07002828void InputDispatcher::setFocusedApplication(
2829 const sp<InputApplicationHandle>& inputApplicationHandle) {
Jeff Brownb88102f2010-09-08 11:49:43 -07002830#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002831 ALOGD("setFocusedApplication");
Jeff Brownb88102f2010-09-08 11:49:43 -07002832#endif
2833 { // acquire lock
2834 AutoMutex _l(mLock);
2835
Jeff Browncc4f7db2011-08-30 20:34:48 -07002836 if (inputApplicationHandle != NULL && inputApplicationHandle->updateInfo()) {
Jeff Brown5ea29ab2011-07-27 11:50:51 -07002837 if (mFocusedApplicationHandle != inputApplicationHandle) {
2838 if (mFocusedApplicationHandle != NULL) {
Jeff Browne9bb9be2012-02-06 15:47:55 -08002839 resetANRTimeoutsLocked();
Jeff Browncc4f7db2011-08-30 20:34:48 -07002840 mFocusedApplicationHandle->releaseInfo();
Jeff Brown5ea29ab2011-07-27 11:50:51 -07002841 }
2842 mFocusedApplicationHandle = inputApplicationHandle;
2843 }
2844 } else if (mFocusedApplicationHandle != NULL) {
Jeff Browne9bb9be2012-02-06 15:47:55 -08002845 resetANRTimeoutsLocked();
Jeff Browncc4f7db2011-08-30 20:34:48 -07002846 mFocusedApplicationHandle->releaseInfo();
Jeff Brown9302c872011-07-13 22:51:29 -07002847 mFocusedApplicationHandle.clear();
Jeff Brownb88102f2010-09-08 11:49:43 -07002848 }
2849
2850#if DEBUG_FOCUS
Jeff Brownb6997262010-10-08 22:31:17 -07002851 //logDispatchStateLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -07002852#endif
2853 } // release lock
2854
2855 // Wake up poll loop since it may need to make new input dispatching choices.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002856 mLooper->wake();
Jeff Brownb88102f2010-09-08 11:49:43 -07002857}
2858
Jeff Brownb88102f2010-09-08 11:49:43 -07002859void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
2860#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002861 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
Jeff Brownb88102f2010-09-08 11:49:43 -07002862#endif
2863
2864 bool changed;
2865 { // acquire lock
2866 AutoMutex _l(mLock);
2867
2868 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
Jeff Brown120a4592010-10-27 18:43:51 -07002869 if (mDispatchFrozen && !frozen) {
Jeff Brownb88102f2010-09-08 11:49:43 -07002870 resetANRTimeoutsLocked();
2871 }
2872
Jeff Brown120a4592010-10-27 18:43:51 -07002873 if (mDispatchEnabled && !enabled) {
2874 resetAndDropEverythingLocked("dispatcher is being disabled");
2875 }
2876
Jeff Brownb88102f2010-09-08 11:49:43 -07002877 mDispatchEnabled = enabled;
2878 mDispatchFrozen = frozen;
2879 changed = true;
2880 } else {
2881 changed = false;
2882 }
2883
2884#if DEBUG_FOCUS
Jeff Brownb6997262010-10-08 22:31:17 -07002885 //logDispatchStateLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -07002886#endif
2887 } // release lock
2888
2889 if (changed) {
2890 // Wake up poll loop since it may need to make new input dispatching choices.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002891 mLooper->wake();
Jeff Brown46b9ac02010-04-22 18:58:52 -07002892 }
2893}
2894
Jeff Brown0029c662011-03-30 02:25:18 -07002895void InputDispatcher::setInputFilterEnabled(bool enabled) {
2896#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002897 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
Jeff Brown0029c662011-03-30 02:25:18 -07002898#endif
2899
2900 { // acquire lock
2901 AutoMutex _l(mLock);
2902
2903 if (mInputFilterEnabled == enabled) {
2904 return;
2905 }
2906
2907 mInputFilterEnabled = enabled;
2908 resetAndDropEverythingLocked("input filter is being enabled or disabled");
2909 } // release lock
2910
2911 // Wake up poll loop since there might be work to do to drop everything.
2912 mLooper->wake();
2913}
2914
Jeff Browne6504122010-09-27 14:52:15 -07002915bool InputDispatcher::transferTouchFocus(const sp<InputChannel>& fromChannel,
2916 const sp<InputChannel>& toChannel) {
2917#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002918 ALOGD("transferTouchFocus: fromChannel=%s, toChannel=%s",
Jeff Browne6504122010-09-27 14:52:15 -07002919 fromChannel->getName().string(), toChannel->getName().string());
2920#endif
2921 { // acquire lock
2922 AutoMutex _l(mLock);
2923
Jeff Brown9302c872011-07-13 22:51:29 -07002924 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromChannel);
2925 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toChannel);
2926 if (fromWindowHandle == NULL || toWindowHandle == NULL) {
Jeff Browne6504122010-09-27 14:52:15 -07002927#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002928 ALOGD("Cannot transfer focus because from or to window not found.");
Jeff Browne6504122010-09-27 14:52:15 -07002929#endif
2930 return false;
2931 }
Jeff Brown9302c872011-07-13 22:51:29 -07002932 if (fromWindowHandle == toWindowHandle) {
Jeff Browne6504122010-09-27 14:52:15 -07002933#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002934 ALOGD("Trivial transfer to same window.");
Jeff Browne6504122010-09-27 14:52:15 -07002935#endif
2936 return true;
2937 }
2938
2939 bool found = false;
2940 for (size_t i = 0; i < mTouchState.windows.size(); i++) {
2941 const TouchedWindow& touchedWindow = mTouchState.windows[i];
Jeff Brown9302c872011-07-13 22:51:29 -07002942 if (touchedWindow.windowHandle == fromWindowHandle) {
Jeff Browne6504122010-09-27 14:52:15 -07002943 int32_t oldTargetFlags = touchedWindow.targetFlags;
2944 BitSet32 pointerIds = touchedWindow.pointerIds;
2945
2946 mTouchState.windows.removeAt(i);
2947
Jeff Brown46e75292010-11-10 16:53:45 -08002948 int32_t newTargetFlags = oldTargetFlags
Jeff Browna032cc02011-03-07 16:56:21 -08002949 & (InputTarget::FLAG_FOREGROUND
2950 | InputTarget::FLAG_SPLIT | InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brown9302c872011-07-13 22:51:29 -07002951 mTouchState.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Jeff Browne6504122010-09-27 14:52:15 -07002952
2953 found = true;
2954 break;
2955 }
2956 }
2957
2958 if (! found) {
2959#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002960 ALOGD("Focus transfer failed because from window did not have focus.");
Jeff Browne6504122010-09-27 14:52:15 -07002961#endif
2962 return false;
2963 }
2964
Jeff Brown9c9f1a32010-10-11 18:32:20 -07002965 ssize_t fromConnectionIndex = getConnectionIndexLocked(fromChannel);
2966 ssize_t toConnectionIndex = getConnectionIndexLocked(toChannel);
2967 if (fromConnectionIndex >= 0 && toConnectionIndex >= 0) {
Jeff Browncbee6d62012-02-03 20:11:27 -08002968 sp<Connection> fromConnection = mConnectionsByFd.valueAt(fromConnectionIndex);
2969 sp<Connection> toConnection = mConnectionsByFd.valueAt(toConnectionIndex);
Jeff Brown9c9f1a32010-10-11 18:32:20 -07002970
2971 fromConnection->inputState.copyPointerStateTo(toConnection->inputState);
Jeff Brownda3d5a92011-03-29 15:11:34 -07002972 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Jeff Brown9c9f1a32010-10-11 18:32:20 -07002973 "transferring touch focus from this window to another window");
Jeff Brownda3d5a92011-03-29 15:11:34 -07002974 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Jeff Brown9c9f1a32010-10-11 18:32:20 -07002975 }
2976
Jeff Browne6504122010-09-27 14:52:15 -07002977#if DEBUG_FOCUS
2978 logDispatchStateLocked();
2979#endif
2980 } // release lock
2981
2982 // Wake up poll loop since it may need to make new input dispatching choices.
2983 mLooper->wake();
2984 return true;
2985}
2986
Jeff Brown120a4592010-10-27 18:43:51 -07002987void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
2988#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002989 ALOGD("Resetting and dropping all events (%s).", reason);
Jeff Brown120a4592010-10-27 18:43:51 -07002990#endif
2991
Jeff Brownda3d5a92011-03-29 15:11:34 -07002992 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
2993 synthesizeCancelationEventsForAllConnectionsLocked(options);
Jeff Brown120a4592010-10-27 18:43:51 -07002994
2995 resetKeyRepeatLocked();
2996 releasePendingEventLocked();
2997 drainInboundQueueLocked();
Jeff Browne9bb9be2012-02-06 15:47:55 -08002998 resetANRTimeoutsLocked();
Jeff Brown120a4592010-10-27 18:43:51 -07002999
3000 mTouchState.reset();
Jeff Brown9302c872011-07-13 22:51:29 -07003001 mLastHoverWindowHandle.clear();
Jeff Brown120a4592010-10-27 18:43:51 -07003002}
3003
Jeff Brownb88102f2010-09-08 11:49:43 -07003004void InputDispatcher::logDispatchStateLocked() {
3005 String8 dump;
3006 dumpDispatchStateLocked(dump);
Jeff Brown2a95c2a2010-09-16 12:31:46 -07003007
3008 char* text = dump.lockBuffer(dump.size());
3009 char* start = text;
3010 while (*start != '\0') {
3011 char* end = strchr(start, '\n');
3012 if (*end == '\n') {
3013 *(end++) = '\0';
3014 }
Steve Block5baa3a62011-12-20 16:23:08 +00003015 ALOGD("%s", start);
Jeff Brown2a95c2a2010-09-16 12:31:46 -07003016 start = end;
3017 }
Jeff Brownb88102f2010-09-08 11:49:43 -07003018}
3019
3020void InputDispatcher::dumpDispatchStateLocked(String8& dump) {
Jeff Brownf2f48712010-10-01 17:46:21 -07003021 dump.appendFormat(INDENT "DispatchEnabled: %d\n", mDispatchEnabled);
3022 dump.appendFormat(INDENT "DispatchFrozen: %d\n", mDispatchFrozen);
Jeff Brownb88102f2010-09-08 11:49:43 -07003023
Jeff Brown9302c872011-07-13 22:51:29 -07003024 if (mFocusedApplicationHandle != NULL) {
Jeff Brownf2f48712010-10-01 17:46:21 -07003025 dump.appendFormat(INDENT "FocusedApplication: name='%s', dispatchingTimeout=%0.3fms\n",
Jeff Browncc4f7db2011-08-30 20:34:48 -07003026 mFocusedApplicationHandle->getName().string(),
3027 mFocusedApplicationHandle->getDispatchingTimeout(
3028 DEFAULT_INPUT_DISPATCHING_TIMEOUT) / 1000000.0);
Jeff Brownb88102f2010-09-08 11:49:43 -07003029 } else {
Jeff Brownf2f48712010-10-01 17:46:21 -07003030 dump.append(INDENT "FocusedApplication: <null>\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003031 }
Jeff Brownf2f48712010-10-01 17:46:21 -07003032 dump.appendFormat(INDENT "FocusedWindow: name='%s'\n",
Jeff Browncc4f7db2011-08-30 20:34:48 -07003033 mFocusedWindowHandle != NULL ? mFocusedWindowHandle->getName().string() : "<null>");
Jeff Brownf2f48712010-10-01 17:46:21 -07003034
3035 dump.appendFormat(INDENT "TouchDown: %s\n", toString(mTouchState.down));
3036 dump.appendFormat(INDENT "TouchSplit: %s\n", toString(mTouchState.split));
Jeff Brown95712852011-01-04 19:41:59 -08003037 dump.appendFormat(INDENT "TouchDeviceId: %d\n", mTouchState.deviceId);
Jeff Brown58a2da82011-01-25 16:02:22 -08003038 dump.appendFormat(INDENT "TouchSource: 0x%08x\n", mTouchState.source);
Jeff Brownf2f48712010-10-01 17:46:21 -07003039 if (!mTouchState.windows.isEmpty()) {
3040 dump.append(INDENT "TouchedWindows:\n");
3041 for (size_t i = 0; i < mTouchState.windows.size(); i++) {
3042 const TouchedWindow& touchedWindow = mTouchState.windows[i];
3043 dump.appendFormat(INDENT2 "%d: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
Jeff Browncc4f7db2011-08-30 20:34:48 -07003044 i, touchedWindow.windowHandle->getName().string(),
3045 touchedWindow.pointerIds.value,
Jeff Brownf2f48712010-10-01 17:46:21 -07003046 touchedWindow.targetFlags);
3047 }
3048 } else {
3049 dump.append(INDENT "TouchedWindows: <none>\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003050 }
3051
Jeff Brown9302c872011-07-13 22:51:29 -07003052 if (!mWindowHandles.isEmpty()) {
Jeff Brownf2f48712010-10-01 17:46:21 -07003053 dump.append(INDENT "Windows:\n");
Jeff Brown9302c872011-07-13 22:51:29 -07003054 for (size_t i = 0; i < mWindowHandles.size(); i++) {
3055 const sp<InputWindowHandle>& windowHandle = mWindowHandles.itemAt(i);
Jeff Browncc4f7db2011-08-30 20:34:48 -07003056 const InputWindowInfo* windowInfo = windowHandle->getInfo();
3057
Jeff Brownf2f48712010-10-01 17:46:21 -07003058 dump.appendFormat(INDENT2 "%d: name='%s', paused=%s, hasFocus=%s, hasWallpaper=%s, "
3059 "visible=%s, canReceiveKeys=%s, flags=0x%08x, type=0x%08x, layer=%d, "
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003060 "frame=[%d,%d][%d,%d], scale=%f, "
Jeff Brownfbf09772011-01-16 14:06:57 -08003061 "touchableRegion=",
Jeff Browncc4f7db2011-08-30 20:34:48 -07003062 i, windowInfo->name.string(),
3063 toString(windowInfo->paused),
3064 toString(windowInfo->hasFocus),
3065 toString(windowInfo->hasWallpaper),
3066 toString(windowInfo->visible),
3067 toString(windowInfo->canReceiveKeys),
3068 windowInfo->layoutParamsFlags, windowInfo->layoutParamsType,
3069 windowInfo->layer,
3070 windowInfo->frameLeft, windowInfo->frameTop,
3071 windowInfo->frameRight, windowInfo->frameBottom,
3072 windowInfo->scaleFactor);
3073 dumpRegion(dump, windowInfo->touchableRegion);
3074 dump.appendFormat(", inputFeatures=0x%08x", windowInfo->inputFeatures);
Jeff Brownfbf09772011-01-16 14:06:57 -08003075 dump.appendFormat(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%0.3fms\n",
Jeff Browncc4f7db2011-08-30 20:34:48 -07003076 windowInfo->ownerPid, windowInfo->ownerUid,
3077 windowInfo->dispatchingTimeout / 1000000.0);
Jeff Brownf2f48712010-10-01 17:46:21 -07003078 }
3079 } else {
3080 dump.append(INDENT "Windows: <none>\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003081 }
3082
Jeff Brownf2f48712010-10-01 17:46:21 -07003083 if (!mMonitoringChannels.isEmpty()) {
3084 dump.append(INDENT "MonitoringChannels:\n");
3085 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
3086 const sp<InputChannel>& channel = mMonitoringChannels[i];
3087 dump.appendFormat(INDENT2 "%d: '%s'\n", i, channel->getName().string());
3088 }
3089 } else {
3090 dump.append(INDENT "MonitoringChannels: <none>\n");
3091 }
Jeff Brown519e0242010-09-15 15:18:56 -07003092
Jeff Brownf2f48712010-10-01 17:46:21 -07003093 dump.appendFormat(INDENT "InboundQueue: length=%u\n", mInboundQueue.count());
3094
Jeff Brownb88102f2010-09-08 11:49:43 -07003095 if (isAppSwitchPendingLocked()) {
Jeff Brownf2f48712010-10-01 17:46:21 -07003096 dump.appendFormat(INDENT "AppSwitch: pending, due in %01.1fms\n",
Jeff Brownb88102f2010-09-08 11:49:43 -07003097 (mAppSwitchDueTime - now()) / 1000000.0);
3098 } else {
Jeff Brownf2f48712010-10-01 17:46:21 -07003099 dump.append(INDENT "AppSwitch: not pending\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003100 }
3101}
3102
Jeff Brown928e0542011-01-10 11:17:36 -08003103status_t InputDispatcher::registerInputChannel(const sp<InputChannel>& inputChannel,
3104 const sp<InputWindowHandle>& inputWindowHandle, bool monitor) {
Jeff Brown9c3cda02010-06-15 01:31:58 -07003105#if DEBUG_REGISTRATION
Steve Block5baa3a62011-12-20 16:23:08 +00003106 ALOGD("channel '%s' ~ registerInputChannel - monitor=%s", inputChannel->getName().string(),
Jeff Brownb88102f2010-09-08 11:49:43 -07003107 toString(monitor));
Jeff Brown9c3cda02010-06-15 01:31:58 -07003108#endif
3109
Jeff Brown46b9ac02010-04-22 18:58:52 -07003110 { // acquire lock
3111 AutoMutex _l(mLock);
3112
Jeff Brown519e0242010-09-15 15:18:56 -07003113 if (getConnectionIndexLocked(inputChannel) >= 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00003114 ALOGW("Attempted to register already registered input channel '%s'",
Jeff Brown46b9ac02010-04-22 18:58:52 -07003115 inputChannel->getName().string());
3116 return BAD_VALUE;
3117 }
3118
Jeff Browncc4f7db2011-08-30 20:34:48 -07003119 sp<Connection> connection = new Connection(inputChannel, inputWindowHandle, monitor);
Jeff Brown46b9ac02010-04-22 18:58:52 -07003120
Jeff Brown91e32892012-02-14 15:56:29 -08003121 int fd = inputChannel->getFd();
Jeff Browncbee6d62012-02-03 20:11:27 -08003122 mConnectionsByFd.add(fd, connection);
Jeff Brown9c3cda02010-06-15 01:31:58 -07003123
Jeff Brownb88102f2010-09-08 11:49:43 -07003124 if (monitor) {
3125 mMonitoringChannels.push(inputChannel);
3126 }
3127
Jeff Browncbee6d62012-02-03 20:11:27 -08003128 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
Jeff Brown2cbecea2010-08-17 15:59:26 -07003129
Jeff Brown9c3cda02010-06-15 01:31:58 -07003130 runCommandsLockedInterruptible();
Jeff Brown46b9ac02010-04-22 18:58:52 -07003131 } // release lock
Jeff Brown46b9ac02010-04-22 18:58:52 -07003132 return OK;
3133}
3134
3135status_t InputDispatcher::unregisterInputChannel(const sp<InputChannel>& inputChannel) {
Jeff Brown9c3cda02010-06-15 01:31:58 -07003136#if DEBUG_REGISTRATION
Steve Block5baa3a62011-12-20 16:23:08 +00003137 ALOGD("channel '%s' ~ unregisterInputChannel", inputChannel->getName().string());
Jeff Brown9c3cda02010-06-15 01:31:58 -07003138#endif
3139
Jeff Brown46b9ac02010-04-22 18:58:52 -07003140 { // acquire lock
3141 AutoMutex _l(mLock);
3142
Jeff Browncc4f7db2011-08-30 20:34:48 -07003143 status_t status = unregisterInputChannelLocked(inputChannel, false /*notify*/);
3144 if (status) {
3145 return status;
Jeff Brown46b9ac02010-04-22 18:58:52 -07003146 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07003147 } // release lock
3148
Jeff Brown46b9ac02010-04-22 18:58:52 -07003149 // Wake the poll loop because removing the connection may have changed the current
3150 // synchronization state.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07003151 mLooper->wake();
Jeff Brown46b9ac02010-04-22 18:58:52 -07003152 return OK;
3153}
3154
Jeff Browncc4f7db2011-08-30 20:34:48 -07003155status_t InputDispatcher::unregisterInputChannelLocked(const sp<InputChannel>& inputChannel,
3156 bool notify) {
3157 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
3158 if (connectionIndex < 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00003159 ALOGW("Attempted to unregister already unregistered input channel '%s'",
Jeff Browncc4f7db2011-08-30 20:34:48 -07003160 inputChannel->getName().string());
3161 return BAD_VALUE;
3162 }
3163
Jeff Browncbee6d62012-02-03 20:11:27 -08003164 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
3165 mConnectionsByFd.removeItemsAt(connectionIndex);
Jeff Browncc4f7db2011-08-30 20:34:48 -07003166
3167 if (connection->monitor) {
3168 removeMonitorChannelLocked(inputChannel);
3169 }
3170
Jeff Browncbee6d62012-02-03 20:11:27 -08003171 mLooper->removeFd(inputChannel->getFd());
Jeff Browncc4f7db2011-08-30 20:34:48 -07003172
3173 nsecs_t currentTime = now();
3174 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
3175
3176 runCommandsLockedInterruptible();
3177
3178 connection->status = Connection::STATUS_ZOMBIE;
3179 return OK;
3180}
3181
3182void InputDispatcher::removeMonitorChannelLocked(const sp<InputChannel>& inputChannel) {
3183 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
3184 if (mMonitoringChannels[i] == inputChannel) {
3185 mMonitoringChannels.removeAt(i);
3186 break;
3187 }
3188 }
3189}
3190
Jeff Brown519e0242010-09-15 15:18:56 -07003191ssize_t InputDispatcher::getConnectionIndexLocked(const sp<InputChannel>& inputChannel) {
Jeff Browncbee6d62012-02-03 20:11:27 -08003192 ssize_t connectionIndex = mConnectionsByFd.indexOfKey(inputChannel->getFd());
Jeff Brown2cbecea2010-08-17 15:59:26 -07003193 if (connectionIndex >= 0) {
Jeff Browncbee6d62012-02-03 20:11:27 -08003194 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
Jeff Brown2cbecea2010-08-17 15:59:26 -07003195 if (connection->inputChannel.get() == inputChannel.get()) {
3196 return connectionIndex;
3197 }
3198 }
3199
3200 return -1;
3201}
3202
Jeff Brown9c3cda02010-06-15 01:31:58 -07003203void InputDispatcher::onDispatchCycleFinishedLocked(
Jeff Brown072ec962012-02-07 14:46:57 -08003204 nsecs_t currentTime, const sp<Connection>& connection, uint32_t seq, bool handled) {
Jeff Brown3915bb82010-11-05 15:02:16 -07003205 CommandEntry* commandEntry = postCommandLocked(
3206 & InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
3207 commandEntry->connection = connection;
Jeff Brown072ec962012-02-07 14:46:57 -08003208 commandEntry->seq = seq;
Jeff Brown3915bb82010-11-05 15:02:16 -07003209 commandEntry->handled = handled;
Jeff Brown46b9ac02010-04-22 18:58:52 -07003210}
3211
Jeff Brown9c3cda02010-06-15 01:31:58 -07003212void InputDispatcher::onDispatchCycleBrokenLocked(
Jeff Brown7fbdc842010-06-17 20:52:56 -07003213 nsecs_t currentTime, const sp<Connection>& connection) {
Steve Block3762c312012-01-06 19:20:56 +00003214 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Jeff Brown46b9ac02010-04-22 18:58:52 -07003215 connection->getInputChannelName());
3216
Jeff Brown9c3cda02010-06-15 01:31:58 -07003217 CommandEntry* commandEntry = postCommandLocked(
3218 & InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
Jeff Brown7fbdc842010-06-17 20:52:56 -07003219 commandEntry->connection = connection;
Jeff Brown46b9ac02010-04-22 18:58:52 -07003220}
3221
Jeff Brown519e0242010-09-15 15:18:56 -07003222void InputDispatcher::onANRLocked(
Jeff Brown9302c872011-07-13 22:51:29 -07003223 nsecs_t currentTime, const sp<InputApplicationHandle>& applicationHandle,
3224 const sp<InputWindowHandle>& windowHandle,
Jeff Brown519e0242010-09-15 15:18:56 -07003225 nsecs_t eventTime, nsecs_t waitStartTime) {
Steve Block6215d3f2012-01-04 20:05:49 +00003226 ALOGI("Application is not responding: %s. "
Jeff Brown519e0242010-09-15 15:18:56 -07003227 "%01.1fms since event, %01.1fms since wait started",
Jeff Brown9302c872011-07-13 22:51:29 -07003228 getApplicationWindowLabelLocked(applicationHandle, windowHandle).string(),
Jeff Brown519e0242010-09-15 15:18:56 -07003229 (currentTime - eventTime) / 1000000.0,
3230 (currentTime - waitStartTime) / 1000000.0);
3231
3232 CommandEntry* commandEntry = postCommandLocked(
3233 & InputDispatcher::doNotifyANRLockedInterruptible);
Jeff Brown9302c872011-07-13 22:51:29 -07003234 commandEntry->inputApplicationHandle = applicationHandle;
3235 commandEntry->inputWindowHandle = windowHandle;
Jeff Brown519e0242010-09-15 15:18:56 -07003236}
3237
Jeff Brownb88102f2010-09-08 11:49:43 -07003238void InputDispatcher::doNotifyConfigurationChangedInterruptible(
3239 CommandEntry* commandEntry) {
3240 mLock.unlock();
3241
3242 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
3243
3244 mLock.lock();
3245}
3246
Jeff Brown9c3cda02010-06-15 01:31:58 -07003247void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(
3248 CommandEntry* commandEntry) {
Jeff Brown7fbdc842010-06-17 20:52:56 -07003249 sp<Connection> connection = commandEntry->connection;
Jeff Brown9c3cda02010-06-15 01:31:58 -07003250
Jeff Brown7fbdc842010-06-17 20:52:56 -07003251 if (connection->status != Connection::STATUS_ZOMBIE) {
3252 mLock.unlock();
Jeff Brown9c3cda02010-06-15 01:31:58 -07003253
Jeff Brown928e0542011-01-10 11:17:36 -08003254 mPolicy->notifyInputChannelBroken(connection->inputWindowHandle);
Jeff Brown7fbdc842010-06-17 20:52:56 -07003255
3256 mLock.lock();
3257 }
Jeff Brown9c3cda02010-06-15 01:31:58 -07003258}
3259
Jeff Brown519e0242010-09-15 15:18:56 -07003260void InputDispatcher::doNotifyANRLockedInterruptible(
Jeff Brown9c3cda02010-06-15 01:31:58 -07003261 CommandEntry* commandEntry) {
Jeff Brown519e0242010-09-15 15:18:56 -07003262 mLock.unlock();
Jeff Brown9c3cda02010-06-15 01:31:58 -07003263
Jeff Brown519e0242010-09-15 15:18:56 -07003264 nsecs_t newTimeout = mPolicy->notifyANR(
Jeff Brown928e0542011-01-10 11:17:36 -08003265 commandEntry->inputApplicationHandle, commandEntry->inputWindowHandle);
Jeff Brown9c3cda02010-06-15 01:31:58 -07003266
Jeff Brown519e0242010-09-15 15:18:56 -07003267 mLock.lock();
Jeff Brown7fbdc842010-06-17 20:52:56 -07003268
Jeff Brown9302c872011-07-13 22:51:29 -07003269 resumeAfterTargetsNotReadyTimeoutLocked(newTimeout,
3270 commandEntry->inputWindowHandle != NULL
Jeff Browncc4f7db2011-08-30 20:34:48 -07003271 ? commandEntry->inputWindowHandle->getInputChannel() : NULL);
Jeff Brown9c3cda02010-06-15 01:31:58 -07003272}
3273
Jeff Brownb88102f2010-09-08 11:49:43 -07003274void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
3275 CommandEntry* commandEntry) {
3276 KeyEntry* entry = commandEntry->keyEntry;
Jeff Brown1f245102010-11-18 20:53:46 -08003277
3278 KeyEvent event;
3279 initializeKeyEvent(&event, entry);
Jeff Brownb88102f2010-09-08 11:49:43 -07003280
3281 mLock.unlock();
3282
Jeff Brown905805a2011-10-12 13:57:59 -07003283 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(commandEntry->inputWindowHandle,
Jeff Brown1f245102010-11-18 20:53:46 -08003284 &event, entry->policyFlags);
Jeff Brownb88102f2010-09-08 11:49:43 -07003285
3286 mLock.lock();
3287
Jeff Brown905805a2011-10-12 13:57:59 -07003288 if (delay < 0) {
3289 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
3290 } else if (!delay) {
3291 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
3292 } else {
3293 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
3294 entry->interceptKeyWakeupTime = now() + delay;
3295 }
Jeff Brownac386072011-07-20 15:19:50 -07003296 entry->release();
Jeff Brownb88102f2010-09-08 11:49:43 -07003297}
3298
Jeff Brown3915bb82010-11-05 15:02:16 -07003299void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(
3300 CommandEntry* commandEntry) {
3301 sp<Connection> connection = commandEntry->connection;
Jeff Brown072ec962012-02-07 14:46:57 -08003302 uint32_t seq = commandEntry->seq;
Jeff Brown3915bb82010-11-05 15:02:16 -07003303 bool handled = commandEntry->handled;
3304
Jeff Brown072ec962012-02-07 14:46:57 -08003305 // Handle post-event policy actions.
3306 DispatchEntry* dispatchEntry = connection->findWaitQueueEntry(seq);
3307 if (dispatchEntry) {
Jeff Brownd1c48a02012-02-06 19:12:47 -08003308 bool restartEvent;
Jeff Brownd1c48a02012-02-06 19:12:47 -08003309 if (dispatchEntry->eventEntry->type == EventEntry::TYPE_KEY) {
3310 KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry);
3311 restartEvent = afterKeyEventLockedInterruptible(connection,
3312 dispatchEntry, keyEntry, handled);
3313 } else if (dispatchEntry->eventEntry->type == EventEntry::TYPE_MOTION) {
3314 MotionEntry* motionEntry = static_cast<MotionEntry*>(dispatchEntry->eventEntry);
3315 restartEvent = afterMotionEventLockedInterruptible(connection,
3316 dispatchEntry, motionEntry, handled);
3317 } else {
3318 restartEvent = false;
3319 }
3320
3321 // Dequeue the event and start the next cycle.
3322 // Note that because the lock might have been released, it is possible that the
3323 // contents of the wait queue to have been drained, so we need to double-check
3324 // a few things.
Jeff Brown072ec962012-02-07 14:46:57 -08003325 if (dispatchEntry == connection->findWaitQueueEntry(seq)) {
3326 connection->waitQueue.dequeue(dispatchEntry);
Jeff Brown481c1572012-03-09 14:41:15 -08003327 traceWaitQueueLengthLocked(connection);
Jeff Brownd1c48a02012-02-06 19:12:47 -08003328 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
3329 connection->outboundQueue.enqueueAtHead(dispatchEntry);
Jeff Brown481c1572012-03-09 14:41:15 -08003330 traceOutboundQueueLengthLocked(connection);
Jeff Brownd1c48a02012-02-06 19:12:47 -08003331 } else {
3332 releaseDispatchEntryLocked(dispatchEntry);
Jeff Brown49ed71d2010-12-06 17:13:33 -08003333 }
Jeff Brown3915bb82010-11-05 15:02:16 -07003334 }
Jeff Brown3915bb82010-11-05 15:02:16 -07003335
Jeff Brownd1c48a02012-02-06 19:12:47 -08003336 // Start the next dispatch cycle for this connection.
3337 startDispatchCycleLocked(now(), connection);
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003338 }
3339}
3340
3341bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
3342 DispatchEntry* dispatchEntry, KeyEntry* keyEntry, bool handled) {
3343 if (!(keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK)) {
3344 // Get the fallback key state.
3345 // Clear it out after dispatching the UP.
3346 int32_t originalKeyCode = keyEntry->keyCode;
3347 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
3348 if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
3349 connection->inputState.removeFallbackKey(originalKeyCode);
3350 }
3351
3352 if (handled || !dispatchEntry->hasForegroundTarget()) {
3353 // If the application handles the original key for which we previously
3354 // generated a fallback or if the window is not a foreground window,
3355 // then cancel the associated fallback key, if any.
3356 if (fallbackKeyCode != -1) {
3357 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
3358 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
3359 "application handled the original non-fallback key "
3360 "or is no longer a foreground target, "
3361 "canceling previously dispatched fallback key");
3362 options.keyCode = fallbackKeyCode;
3363 synthesizeCancelationEventsForConnectionLocked(connection, options);
3364 }
3365 connection->inputState.removeFallbackKey(originalKeyCode);
3366 }
3367 } else {
3368 // If the application did not handle a non-fallback key, first check
3369 // that we are in a good state to perform unhandled key event processing
3370 // Then ask the policy what to do with it.
3371 bool initialDown = keyEntry->action == AKEY_EVENT_ACTION_DOWN
3372 && keyEntry->repeatCount == 0;
3373 if (fallbackKeyCode == -1 && !initialDown) {
3374#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00003375 ALOGD("Unhandled key event: Skipping unhandled key event processing "
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003376 "since this is not an initial down. "
3377 "keyCode=%d, action=%d, repeatCount=%d",
3378 originalKeyCode, keyEntry->action, keyEntry->repeatCount);
3379#endif
3380 return false;
3381 }
3382
3383 // Dispatch the unhandled key to the policy.
3384#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00003385 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003386 "keyCode=%d, action=%d, repeatCount=%d",
3387 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount);
3388#endif
3389 KeyEvent event;
3390 initializeKeyEvent(&event, keyEntry);
3391
3392 mLock.unlock();
3393
3394 bool fallback = mPolicy->dispatchUnhandledKey(connection->inputWindowHandle,
3395 &event, keyEntry->policyFlags, &event);
3396
3397 mLock.lock();
3398
3399 if (connection->status != Connection::STATUS_NORMAL) {
3400 connection->inputState.removeFallbackKey(originalKeyCode);
Jeff Brownd1c48a02012-02-06 19:12:47 -08003401 return false;
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003402 }
3403
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003404 // Latch the fallback keycode for this key on an initial down.
3405 // The fallback keycode cannot change at any other point in the lifecycle.
3406 if (initialDown) {
3407 if (fallback) {
3408 fallbackKeyCode = event.getKeyCode();
3409 } else {
3410 fallbackKeyCode = AKEYCODE_UNKNOWN;
3411 }
3412 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
3413 }
3414
Steve Blockec193de2012-01-09 18:35:44 +00003415 ALOG_ASSERT(fallbackKeyCode != -1);
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003416
3417 // Cancel the fallback key if the policy decides not to send it anymore.
3418 // We will continue to dispatch the key to the policy but we will no
3419 // longer dispatch a fallback key to the application.
3420 if (fallbackKeyCode != AKEYCODE_UNKNOWN
3421 && (!fallback || fallbackKeyCode != event.getKeyCode())) {
3422#if DEBUG_OUTBOUND_EVENT_DETAILS
3423 if (fallback) {
Steve Block5baa3a62011-12-20 16:23:08 +00003424 ALOGD("Unhandled key event: Policy requested to send key %d"
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003425 "as a fallback for %d, but on the DOWN it had requested "
3426 "to send %d instead. Fallback canceled.",
3427 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
3428 } else {
Steve Block5baa3a62011-12-20 16:23:08 +00003429 ALOGD("Unhandled key event: Policy did not request fallback for %d,"
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003430 "but on the DOWN it had requested to send %d. "
3431 "Fallback canceled.",
3432 originalKeyCode, fallbackKeyCode);
3433 }
3434#endif
3435
3436 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
3437 "canceling fallback, policy no longer desires it");
3438 options.keyCode = fallbackKeyCode;
3439 synthesizeCancelationEventsForConnectionLocked(connection, options);
3440
3441 fallback = false;
3442 fallbackKeyCode = AKEYCODE_UNKNOWN;
3443 if (keyEntry->action != AKEY_EVENT_ACTION_UP) {
3444 connection->inputState.setFallbackKey(originalKeyCode,
3445 fallbackKeyCode);
3446 }
3447 }
3448
3449#if DEBUG_OUTBOUND_EVENT_DETAILS
3450 {
3451 String8 msg;
3452 const KeyedVector<int32_t, int32_t>& fallbackKeys =
3453 connection->inputState.getFallbackKeys();
3454 for (size_t i = 0; i < fallbackKeys.size(); i++) {
3455 msg.appendFormat(", %d->%d", fallbackKeys.keyAt(i),
3456 fallbackKeys.valueAt(i));
3457 }
Steve Block5baa3a62011-12-20 16:23:08 +00003458 ALOGD("Unhandled key event: %d currently tracked fallback keys%s.",
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003459 fallbackKeys.size(), msg.string());
3460 }
3461#endif
3462
3463 if (fallback) {
3464 // Restart the dispatch cycle using the fallback key.
3465 keyEntry->eventTime = event.getEventTime();
3466 keyEntry->deviceId = event.getDeviceId();
3467 keyEntry->source = event.getSource();
3468 keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
3469 keyEntry->keyCode = fallbackKeyCode;
3470 keyEntry->scanCode = event.getScanCode();
3471 keyEntry->metaState = event.getMetaState();
3472 keyEntry->repeatCount = event.getRepeatCount();
3473 keyEntry->downTime = event.getDownTime();
3474 keyEntry->syntheticRepeat = false;
3475
3476#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00003477 ALOGD("Unhandled key event: Dispatching fallback key. "
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003478 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
3479 originalKeyCode, fallbackKeyCode, keyEntry->metaState);
3480#endif
Jeff Brownd1c48a02012-02-06 19:12:47 -08003481 return true; // restart the event
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003482 } else {
3483#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00003484 ALOGD("Unhandled key event: No fallback key.");
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003485#endif
3486 }
3487 }
3488 }
3489 return false;
3490}
3491
3492bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
3493 DispatchEntry* dispatchEntry, MotionEntry* motionEntry, bool handled) {
3494 return false;
Jeff Brown3915bb82010-11-05 15:02:16 -07003495}
3496
Jeff Brownb88102f2010-09-08 11:49:43 -07003497void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
3498 mLock.unlock();
3499
Jeff Brown01ce2e92010-09-26 22:20:12 -07003500 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
Jeff Brownb88102f2010-09-08 11:49:43 -07003501
3502 mLock.lock();
3503}
3504
Jeff Brown3915bb82010-11-05 15:02:16 -07003505void InputDispatcher::initializeKeyEvent(KeyEvent* event, const KeyEntry* entry) {
3506 event->initialize(entry->deviceId, entry->source, entry->action, entry->flags,
3507 entry->keyCode, entry->scanCode, entry->metaState, entry->repeatCount,
3508 entry->downTime, entry->eventTime);
3509}
3510
Jeff Brown519e0242010-09-15 15:18:56 -07003511void InputDispatcher::updateDispatchStatisticsLocked(nsecs_t currentTime, const EventEntry* entry,
3512 int32_t injectionResult, nsecs_t timeSpentWaitingForApplication) {
3513 // TODO Write some statistics about how long we spend waiting.
Jeff Brownb88102f2010-09-08 11:49:43 -07003514}
3515
Jeff Brown481c1572012-03-09 14:41:15 -08003516void InputDispatcher::traceInboundQueueLengthLocked() {
3517 if (ATRACE_ENABLED()) {
3518 ATRACE_INT("iq", mInboundQueue.count());
3519 }
3520}
3521
3522void InputDispatcher::traceOutboundQueueLengthLocked(const sp<Connection>& connection) {
3523 if (ATRACE_ENABLED()) {
3524 char counterName[40];
3525 snprintf(counterName, sizeof(counterName), "oq:%s", connection->getWindowName());
3526 ATRACE_INT(counterName, connection->outboundQueue.count());
3527 }
3528}
3529
3530void InputDispatcher::traceWaitQueueLengthLocked(const sp<Connection>& connection) {
3531 if (ATRACE_ENABLED()) {
3532 char counterName[40];
3533 snprintf(counterName, sizeof(counterName), "wq:%s", connection->getWindowName());
3534 ATRACE_INT(counterName, connection->waitQueue.count());
3535 }
3536}
3537
Jeff Brownb88102f2010-09-08 11:49:43 -07003538void InputDispatcher::dump(String8& dump) {
Jeff Brown89ef0722011-08-10 16:25:21 -07003539 AutoMutex _l(mLock);
3540
Jeff Brownf2f48712010-10-01 17:46:21 -07003541 dump.append("Input Dispatcher State:\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003542 dumpDispatchStateLocked(dump);
Jeff Brown214eaf42011-05-26 19:17:02 -07003543
3544 dump.append(INDENT "Configuration:\n");
Jeff Brown214eaf42011-05-26 19:17:02 -07003545 dump.appendFormat(INDENT2 "KeyRepeatDelay: %0.1fms\n", mConfig.keyRepeatDelay * 0.000001f);
3546 dump.appendFormat(INDENT2 "KeyRepeatTimeout: %0.1fms\n", mConfig.keyRepeatTimeout * 0.000001f);
Jeff Brownb88102f2010-09-08 11:49:43 -07003547}
3548
Jeff Brown89ef0722011-08-10 16:25:21 -07003549void InputDispatcher::monitor() {
3550 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
3551 mLock.lock();
Jeff Brown112b5f52012-01-27 17:32:06 -08003552 mLooper->wake();
3553 mDispatcherIsAliveCondition.wait(mLock);
Jeff Brown89ef0722011-08-10 16:25:21 -07003554 mLock.unlock();
3555}
3556
Jeff Brown9c3cda02010-06-15 01:31:58 -07003557
Jeff Brown519e0242010-09-15 15:18:56 -07003558// --- InputDispatcher::Queue ---
3559
3560template <typename T>
3561uint32_t InputDispatcher::Queue<T>::count() const {
3562 uint32_t result = 0;
Jeff Brownac386072011-07-20 15:19:50 -07003563 for (const T* entry = head; entry; entry = entry->next) {
Jeff Brown519e0242010-09-15 15:18:56 -07003564 result += 1;
3565 }
3566 return result;
3567}
3568
3569
Jeff Brownac386072011-07-20 15:19:50 -07003570// --- InputDispatcher::InjectionState ---
Jeff Brown46b9ac02010-04-22 18:58:52 -07003571
Jeff Brownac386072011-07-20 15:19:50 -07003572InputDispatcher::InjectionState::InjectionState(int32_t injectorPid, int32_t injectorUid) :
3573 refCount(1),
3574 injectorPid(injectorPid), injectorUid(injectorUid),
3575 injectionResult(INPUT_EVENT_INJECTION_PENDING), injectionIsAsync(false),
3576 pendingForegroundDispatches(0) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07003577}
3578
Jeff Brownac386072011-07-20 15:19:50 -07003579InputDispatcher::InjectionState::~InjectionState() {
Jeff Brown01ce2e92010-09-26 22:20:12 -07003580}
3581
Jeff Brownac386072011-07-20 15:19:50 -07003582void InputDispatcher::InjectionState::release() {
3583 refCount -= 1;
3584 if (refCount == 0) {
3585 delete this;
3586 } else {
Steve Blockec193de2012-01-09 18:35:44 +00003587 ALOG_ASSERT(refCount > 0);
Jeff Brown01ce2e92010-09-26 22:20:12 -07003588 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07003589}
3590
Jeff Brownac386072011-07-20 15:19:50 -07003591
3592// --- InputDispatcher::EventEntry ---
3593
3594InputDispatcher::EventEntry::EventEntry(int32_t type, nsecs_t eventTime, uint32_t policyFlags) :
3595 refCount(1), type(type), eventTime(eventTime), policyFlags(policyFlags),
3596 injectionState(NULL), dispatchInProgress(false) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07003597}
3598
Jeff Brownac386072011-07-20 15:19:50 -07003599InputDispatcher::EventEntry::~EventEntry() {
3600 releaseInjectionState();
3601}
3602
3603void InputDispatcher::EventEntry::release() {
3604 refCount -= 1;
3605 if (refCount == 0) {
3606 delete this;
3607 } else {
Steve Blockec193de2012-01-09 18:35:44 +00003608 ALOG_ASSERT(refCount > 0);
Jeff Brownac386072011-07-20 15:19:50 -07003609 }
3610}
3611
3612void InputDispatcher::EventEntry::releaseInjectionState() {
3613 if (injectionState) {
3614 injectionState->release();
3615 injectionState = NULL;
3616 }
3617}
3618
3619
3620// --- InputDispatcher::ConfigurationChangedEntry ---
3621
3622InputDispatcher::ConfigurationChangedEntry::ConfigurationChangedEntry(nsecs_t eventTime) :
3623 EventEntry(TYPE_CONFIGURATION_CHANGED, eventTime, 0) {
3624}
3625
3626InputDispatcher::ConfigurationChangedEntry::~ConfigurationChangedEntry() {
3627}
3628
3629
Jeff Brown65fd2512011-08-18 11:20:58 -07003630// --- InputDispatcher::DeviceResetEntry ---
3631
3632InputDispatcher::DeviceResetEntry::DeviceResetEntry(nsecs_t eventTime, int32_t deviceId) :
3633 EventEntry(TYPE_DEVICE_RESET, eventTime, 0),
3634 deviceId(deviceId) {
3635}
3636
3637InputDispatcher::DeviceResetEntry::~DeviceResetEntry() {
3638}
3639
3640
Jeff Brownac386072011-07-20 15:19:50 -07003641// --- InputDispatcher::KeyEntry ---
3642
3643InputDispatcher::KeyEntry::KeyEntry(nsecs_t eventTime,
Jeff Brown58a2da82011-01-25 16:02:22 -08003644 int32_t deviceId, uint32_t source, uint32_t policyFlags, int32_t action,
Jeff Brown7fbdc842010-06-17 20:52:56 -07003645 int32_t flags, int32_t keyCode, int32_t scanCode, int32_t metaState,
Jeff Brownac386072011-07-20 15:19:50 -07003646 int32_t repeatCount, nsecs_t downTime) :
3647 EventEntry(TYPE_KEY, eventTime, policyFlags),
3648 deviceId(deviceId), source(source), action(action), flags(flags),
3649 keyCode(keyCode), scanCode(scanCode), metaState(metaState),
3650 repeatCount(repeatCount), downTime(downTime),
Jeff Brown905805a2011-10-12 13:57:59 -07003651 syntheticRepeat(false), interceptKeyResult(KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN),
3652 interceptKeyWakeupTime(0) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07003653}
3654
Jeff Brownac386072011-07-20 15:19:50 -07003655InputDispatcher::KeyEntry::~KeyEntry() {
3656}
Jeff Brown7fbdc842010-06-17 20:52:56 -07003657
Jeff Brownac386072011-07-20 15:19:50 -07003658void InputDispatcher::KeyEntry::recycle() {
3659 releaseInjectionState();
3660
3661 dispatchInProgress = false;
3662 syntheticRepeat = false;
3663 interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
Jeff Brown905805a2011-10-12 13:57:59 -07003664 interceptKeyWakeupTime = 0;
Jeff Brownac386072011-07-20 15:19:50 -07003665}
3666
3667
Jeff Brownae9fc032010-08-18 15:51:08 -07003668// --- InputDispatcher::MotionEntry ---
3669
Jeff Brownac386072011-07-20 15:19:50 -07003670InputDispatcher::MotionEntry::MotionEntry(nsecs_t eventTime,
3671 int32_t deviceId, uint32_t source, uint32_t policyFlags, int32_t action, int32_t flags,
3672 int32_t metaState, int32_t buttonState,
3673 int32_t edgeFlags, float xPrecision, float yPrecision,
3674 nsecs_t downTime, uint32_t pointerCount,
3675 const PointerProperties* pointerProperties, const PointerCoords* pointerCoords) :
3676 EventEntry(TYPE_MOTION, eventTime, policyFlags),
Jeff Brown3241b6b2012-02-03 15:08:02 -08003677 eventTime(eventTime),
Jeff Brownac386072011-07-20 15:19:50 -07003678 deviceId(deviceId), source(source), action(action), flags(flags),
3679 metaState(metaState), buttonState(buttonState), edgeFlags(edgeFlags),
3680 xPrecision(xPrecision), yPrecision(yPrecision),
Jeff Brown3241b6b2012-02-03 15:08:02 -08003681 downTime(downTime), pointerCount(pointerCount) {
Jeff Brownac386072011-07-20 15:19:50 -07003682 for (uint32_t i = 0; i < pointerCount; i++) {
3683 this->pointerProperties[i].copyFrom(pointerProperties[i]);
Jeff Brown3241b6b2012-02-03 15:08:02 -08003684 this->pointerCoords[i].copyFrom(pointerCoords[i]);
Jeff Brownac386072011-07-20 15:19:50 -07003685 }
3686}
3687
3688InputDispatcher::MotionEntry::~MotionEntry() {
Jeff Brownac386072011-07-20 15:19:50 -07003689}
3690
3691
3692// --- InputDispatcher::DispatchEntry ---
3693
Jeff Brown072ec962012-02-07 14:46:57 -08003694volatile int32_t InputDispatcher::DispatchEntry::sNextSeqAtomic;
3695
Jeff Brownac386072011-07-20 15:19:50 -07003696InputDispatcher::DispatchEntry::DispatchEntry(EventEntry* eventEntry,
3697 int32_t targetFlags, float xOffset, float yOffset, float scaleFactor) :
Jeff Brown072ec962012-02-07 14:46:57 -08003698 seq(nextSeq()),
Jeff Brownac386072011-07-20 15:19:50 -07003699 eventEntry(eventEntry), targetFlags(targetFlags),
3700 xOffset(xOffset), yOffset(yOffset), scaleFactor(scaleFactor),
Jeff Brown3241b6b2012-02-03 15:08:02 -08003701 resolvedAction(0), resolvedFlags(0) {
Jeff Brownac386072011-07-20 15:19:50 -07003702 eventEntry->refCount += 1;
3703}
3704
3705InputDispatcher::DispatchEntry::~DispatchEntry() {
3706 eventEntry->release();
3707}
3708
Jeff Brown072ec962012-02-07 14:46:57 -08003709uint32_t InputDispatcher::DispatchEntry::nextSeq() {
3710 // Sequence number 0 is reserved and will never be returned.
3711 uint32_t seq;
3712 do {
3713 seq = android_atomic_inc(&sNextSeqAtomic);
3714 } while (!seq);
3715 return seq;
3716}
3717
Jeff Brownb88102f2010-09-08 11:49:43 -07003718
3719// --- InputDispatcher::InputState ---
3720
Jeff Brownb6997262010-10-08 22:31:17 -07003721InputDispatcher::InputState::InputState() {
Jeff Brownb88102f2010-09-08 11:49:43 -07003722}
3723
3724InputDispatcher::InputState::~InputState() {
3725}
3726
3727bool InputDispatcher::InputState::isNeutral() const {
3728 return mKeyMementos.isEmpty() && mMotionMementos.isEmpty();
3729}
3730
Jeff Brown81346812011-06-28 20:08:48 -07003731bool InputDispatcher::InputState::isHovering(int32_t deviceId, uint32_t source) const {
3732 for (size_t i = 0; i < mMotionMementos.size(); i++) {
3733 const MotionMemento& memento = mMotionMementos.itemAt(i);
3734 if (memento.deviceId == deviceId
3735 && memento.source == source
3736 && memento.hovering) {
3737 return true;
3738 }
3739 }
3740 return false;
3741}
Jeff Brownb88102f2010-09-08 11:49:43 -07003742
Jeff Brown81346812011-06-28 20:08:48 -07003743bool InputDispatcher::InputState::trackKey(const KeyEntry* entry,
3744 int32_t action, int32_t flags) {
3745 switch (action) {
3746 case AKEY_EVENT_ACTION_UP: {
3747 if (entry->flags & AKEY_EVENT_FLAG_FALLBACK) {
3748 for (size_t i = 0; i < mFallbackKeys.size(); ) {
3749 if (mFallbackKeys.valueAt(i) == entry->keyCode) {
3750 mFallbackKeys.removeItemsAt(i);
3751 } else {
3752 i += 1;
3753 }
3754 }
3755 }
3756 ssize_t index = findKeyMemento(entry);
3757 if (index >= 0) {
3758 mKeyMementos.removeAt(index);
3759 return true;
3760 }
Jeff Brown68b909d2011-12-07 16:36:01 -08003761 /* FIXME: We can't just drop the key up event because that prevents creating
3762 * popup windows that are automatically shown when a key is held and then
3763 * dismissed when the key is released. The problem is that the popup will
3764 * not have received the original key down, so the key up will be considered
3765 * to be inconsistent with its observed state. We could perhaps handle this
3766 * by synthesizing a key down but that will cause other problems.
3767 *
3768 * So for now, allow inconsistent key up events to be dispatched.
3769 *
Jeff Brown81346812011-06-28 20:08:48 -07003770#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00003771 ALOGD("Dropping inconsistent key up event: deviceId=%d, source=%08x, "
Jeff Brown81346812011-06-28 20:08:48 -07003772 "keyCode=%d, scanCode=%d",
3773 entry->deviceId, entry->source, entry->keyCode, entry->scanCode);
3774#endif
3775 return false;
Jeff Brown68b909d2011-12-07 16:36:01 -08003776 */
3777 return true;
Jeff Brown81346812011-06-28 20:08:48 -07003778 }
3779
3780 case AKEY_EVENT_ACTION_DOWN: {
3781 ssize_t index = findKeyMemento(entry);
3782 if (index >= 0) {
3783 mKeyMementos.removeAt(index);
3784 }
3785 addKeyMemento(entry, flags);
3786 return true;
3787 }
3788
3789 default:
3790 return true;
Jeff Brownb88102f2010-09-08 11:49:43 -07003791 }
3792}
3793
Jeff Brown81346812011-06-28 20:08:48 -07003794bool InputDispatcher::InputState::trackMotion(const MotionEntry* entry,
3795 int32_t action, int32_t flags) {
3796 int32_t actionMasked = action & AMOTION_EVENT_ACTION_MASK;
3797 switch (actionMasked) {
3798 case AMOTION_EVENT_ACTION_UP:
3799 case AMOTION_EVENT_ACTION_CANCEL: {
3800 ssize_t index = findMotionMemento(entry, false /*hovering*/);
3801 if (index >= 0) {
3802 mMotionMementos.removeAt(index);
3803 return true;
Jeff Brownda3d5a92011-03-29 15:11:34 -07003804 }
Jeff Brown81346812011-06-28 20:08:48 -07003805#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00003806 ALOGD("Dropping inconsistent motion up or cancel event: deviceId=%d, source=%08x, "
Jeff Brown81346812011-06-28 20:08:48 -07003807 "actionMasked=%d",
3808 entry->deviceId, entry->source, actionMasked);
3809#endif
3810 return false;
Jeff Brownda3d5a92011-03-29 15:11:34 -07003811 }
3812
Jeff Brown81346812011-06-28 20:08:48 -07003813 case AMOTION_EVENT_ACTION_DOWN: {
3814 ssize_t index = findMotionMemento(entry, false /*hovering*/);
3815 if (index >= 0) {
3816 mMotionMementos.removeAt(index);
3817 }
3818 addMotionMemento(entry, flags, false /*hovering*/);
3819 return true;
3820 }
3821
3822 case AMOTION_EVENT_ACTION_POINTER_UP:
3823 case AMOTION_EVENT_ACTION_POINTER_DOWN:
3824 case AMOTION_EVENT_ACTION_MOVE: {
3825 ssize_t index = findMotionMemento(entry, false /*hovering*/);
3826 if (index >= 0) {
3827 MotionMemento& memento = mMotionMementos.editItemAt(index);
3828 memento.setPointers(entry);
3829 return true;
3830 }
Jeff Brown2e45fb62011-06-29 21:19:05 -07003831 if (actionMasked == AMOTION_EVENT_ACTION_MOVE
3832 && (entry->source & (AINPUT_SOURCE_CLASS_JOYSTICK
3833 | AINPUT_SOURCE_CLASS_NAVIGATION))) {
3834 // Joysticks and trackballs can send MOVE events without corresponding DOWN or UP.
3835 return true;
3836 }
Jeff Brown81346812011-06-28 20:08:48 -07003837#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00003838 ALOGD("Dropping inconsistent motion pointer up/down or move event: "
Jeff Brown81346812011-06-28 20:08:48 -07003839 "deviceId=%d, source=%08x, actionMasked=%d",
3840 entry->deviceId, entry->source, actionMasked);
3841#endif
3842 return false;
3843 }
3844
3845 case AMOTION_EVENT_ACTION_HOVER_EXIT: {
3846 ssize_t index = findMotionMemento(entry, true /*hovering*/);
3847 if (index >= 0) {
3848 mMotionMementos.removeAt(index);
3849 return true;
3850 }
3851#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00003852 ALOGD("Dropping inconsistent motion hover exit event: deviceId=%d, source=%08x",
Jeff Brown81346812011-06-28 20:08:48 -07003853 entry->deviceId, entry->source);
3854#endif
3855 return false;
3856 }
3857
3858 case AMOTION_EVENT_ACTION_HOVER_ENTER:
3859 case AMOTION_EVENT_ACTION_HOVER_MOVE: {
3860 ssize_t index = findMotionMemento(entry, true /*hovering*/);
3861 if (index >= 0) {
3862 mMotionMementos.removeAt(index);
3863 }
3864 addMotionMemento(entry, flags, true /*hovering*/);
3865 return true;
3866 }
3867
3868 default:
3869 return true;
3870 }
3871}
3872
3873ssize_t InputDispatcher::InputState::findKeyMemento(const KeyEntry* entry) const {
Jeff Brownb88102f2010-09-08 11:49:43 -07003874 for (size_t i = 0; i < mKeyMementos.size(); i++) {
Jeff Brown81346812011-06-28 20:08:48 -07003875 const KeyMemento& memento = mKeyMementos.itemAt(i);
Jeff Brownb88102f2010-09-08 11:49:43 -07003876 if (memento.deviceId == entry->deviceId
3877 && memento.source == entry->source
3878 && memento.keyCode == entry->keyCode
3879 && memento.scanCode == entry->scanCode) {
Jeff Brown81346812011-06-28 20:08:48 -07003880 return i;
Jeff Brownb88102f2010-09-08 11:49:43 -07003881 }
3882 }
Jeff Brown81346812011-06-28 20:08:48 -07003883 return -1;
Jeff Brownb88102f2010-09-08 11:49:43 -07003884}
3885
Jeff Brown81346812011-06-28 20:08:48 -07003886ssize_t InputDispatcher::InputState::findMotionMemento(const MotionEntry* entry,
3887 bool hovering) const {
Jeff Brownb88102f2010-09-08 11:49:43 -07003888 for (size_t i = 0; i < mMotionMementos.size(); i++) {
Jeff Brown81346812011-06-28 20:08:48 -07003889 const MotionMemento& memento = mMotionMementos.itemAt(i);
Jeff Brownb88102f2010-09-08 11:49:43 -07003890 if (memento.deviceId == entry->deviceId
Jeff Brown81346812011-06-28 20:08:48 -07003891 && memento.source == entry->source
3892 && memento.hovering == hovering) {
3893 return i;
Jeff Brownb88102f2010-09-08 11:49:43 -07003894 }
3895 }
Jeff Brown81346812011-06-28 20:08:48 -07003896 return -1;
3897}
Jeff Brownb88102f2010-09-08 11:49:43 -07003898
Jeff Brown81346812011-06-28 20:08:48 -07003899void InputDispatcher::InputState::addKeyMemento(const KeyEntry* entry, int32_t flags) {
3900 mKeyMementos.push();
3901 KeyMemento& memento = mKeyMementos.editTop();
3902 memento.deviceId = entry->deviceId;
3903 memento.source = entry->source;
3904 memento.keyCode = entry->keyCode;
3905 memento.scanCode = entry->scanCode;
3906 memento.flags = flags;
3907 memento.downTime = entry->downTime;
3908}
3909
3910void InputDispatcher::InputState::addMotionMemento(const MotionEntry* entry,
3911 int32_t flags, bool hovering) {
3912 mMotionMementos.push();
3913 MotionMemento& memento = mMotionMementos.editTop();
3914 memento.deviceId = entry->deviceId;
3915 memento.source = entry->source;
3916 memento.flags = flags;
3917 memento.xPrecision = entry->xPrecision;
3918 memento.yPrecision = entry->yPrecision;
3919 memento.downTime = entry->downTime;
3920 memento.setPointers(entry);
3921 memento.hovering = hovering;
Jeff Brownb88102f2010-09-08 11:49:43 -07003922}
3923
3924void InputDispatcher::InputState::MotionMemento::setPointers(const MotionEntry* entry) {
3925 pointerCount = entry->pointerCount;
3926 for (uint32_t i = 0; i < entry->pointerCount; i++) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003927 pointerProperties[i].copyFrom(entry->pointerProperties[i]);
Jeff Brown3241b6b2012-02-03 15:08:02 -08003928 pointerCoords[i].copyFrom(entry->pointerCoords[i]);
Jeff Brownb88102f2010-09-08 11:49:43 -07003929 }
3930}
3931
Jeff Brownb6997262010-10-08 22:31:17 -07003932void InputDispatcher::InputState::synthesizeCancelationEvents(nsecs_t currentTime,
Jeff Brownac386072011-07-20 15:19:50 -07003933 Vector<EventEntry*>& outEvents, const CancelationOptions& options) {
Jeff Brown81346812011-06-28 20:08:48 -07003934 for (size_t i = 0; i < mKeyMementos.size(); i++) {
Jeff Brownb88102f2010-09-08 11:49:43 -07003935 const KeyMemento& memento = mKeyMementos.itemAt(i);
Jeff Brown49ed71d2010-12-06 17:13:33 -08003936 if (shouldCancelKey(memento, options)) {
Jeff Brownac386072011-07-20 15:19:50 -07003937 outEvents.push(new KeyEntry(currentTime,
Jeff Brownb6997262010-10-08 22:31:17 -07003938 memento.deviceId, memento.source, 0,
Jeff Brown49ed71d2010-12-06 17:13:33 -08003939 AKEY_EVENT_ACTION_UP, memento.flags | AKEY_EVENT_FLAG_CANCELED,
Jeff Brownb6997262010-10-08 22:31:17 -07003940 memento.keyCode, memento.scanCode, 0, 0, memento.downTime));
Jeff Brownb6997262010-10-08 22:31:17 -07003941 }
Jeff Brownb88102f2010-09-08 11:49:43 -07003942 }
3943
Jeff Brown81346812011-06-28 20:08:48 -07003944 for (size_t i = 0; i < mMotionMementos.size(); i++) {
Jeff Brownb88102f2010-09-08 11:49:43 -07003945 const MotionMemento& memento = mMotionMementos.itemAt(i);
Jeff Brown49ed71d2010-12-06 17:13:33 -08003946 if (shouldCancelMotion(memento, options)) {
Jeff Brownac386072011-07-20 15:19:50 -07003947 outEvents.push(new MotionEntry(currentTime,
Jeff Brownb6997262010-10-08 22:31:17 -07003948 memento.deviceId, memento.source, 0,
Jeff Browna032cc02011-03-07 16:56:21 -08003949 memento.hovering
3950 ? AMOTION_EVENT_ACTION_HOVER_EXIT
3951 : AMOTION_EVENT_ACTION_CANCEL,
Jeff Brown81346812011-06-28 20:08:48 -07003952 memento.flags, 0, 0, 0,
Jeff Brownb6997262010-10-08 22:31:17 -07003953 memento.xPrecision, memento.yPrecision, memento.downTime,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003954 memento.pointerCount, memento.pointerProperties, memento.pointerCoords));
Jeff Brownb6997262010-10-08 22:31:17 -07003955 }
Jeff Brownb88102f2010-09-08 11:49:43 -07003956 }
3957}
3958
3959void InputDispatcher::InputState::clear() {
3960 mKeyMementos.clear();
3961 mMotionMementos.clear();
Jeff Brownda3d5a92011-03-29 15:11:34 -07003962 mFallbackKeys.clear();
Jeff Brownb6997262010-10-08 22:31:17 -07003963}
3964
Jeff Brown9c9f1a32010-10-11 18:32:20 -07003965void InputDispatcher::InputState::copyPointerStateTo(InputState& other) const {
3966 for (size_t i = 0; i < mMotionMementos.size(); i++) {
3967 const MotionMemento& memento = mMotionMementos.itemAt(i);
3968 if (memento.source & AINPUT_SOURCE_CLASS_POINTER) {
3969 for (size_t j = 0; j < other.mMotionMementos.size(); ) {
3970 const MotionMemento& otherMemento = other.mMotionMementos.itemAt(j);
3971 if (memento.deviceId == otherMemento.deviceId
3972 && memento.source == otherMemento.source) {
3973 other.mMotionMementos.removeAt(j);
3974 } else {
3975 j += 1;
3976 }
3977 }
3978 other.mMotionMementos.push(memento);
3979 }
3980 }
3981}
3982
Jeff Brownda3d5a92011-03-29 15:11:34 -07003983int32_t InputDispatcher::InputState::getFallbackKey(int32_t originalKeyCode) {
3984 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
3985 return index >= 0 ? mFallbackKeys.valueAt(index) : -1;
3986}
3987
3988void InputDispatcher::InputState::setFallbackKey(int32_t originalKeyCode,
3989 int32_t fallbackKeyCode) {
3990 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
3991 if (index >= 0) {
3992 mFallbackKeys.replaceValueAt(index, fallbackKeyCode);
3993 } else {
3994 mFallbackKeys.add(originalKeyCode, fallbackKeyCode);
3995 }
3996}
3997
3998void InputDispatcher::InputState::removeFallbackKey(int32_t originalKeyCode) {
3999 mFallbackKeys.removeItem(originalKeyCode);
4000}
4001
Jeff Brown49ed71d2010-12-06 17:13:33 -08004002bool InputDispatcher::InputState::shouldCancelKey(const KeyMemento& memento,
Jeff Brownda3d5a92011-03-29 15:11:34 -07004003 const CancelationOptions& options) {
4004 if (options.keyCode != -1 && memento.keyCode != options.keyCode) {
4005 return false;
4006 }
4007
Jeff Brown65fd2512011-08-18 11:20:58 -07004008 if (options.deviceId != -1 && memento.deviceId != options.deviceId) {
4009 return false;
4010 }
4011
Jeff Brownda3d5a92011-03-29 15:11:34 -07004012 switch (options.mode) {
4013 case CancelationOptions::CANCEL_ALL_EVENTS:
4014 case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
Jeff Brownb6997262010-10-08 22:31:17 -07004015 return true;
Jeff Brownda3d5a92011-03-29 15:11:34 -07004016 case CancelationOptions::CANCEL_FALLBACK_EVENTS:
Jeff Brown49ed71d2010-12-06 17:13:33 -08004017 return memento.flags & AKEY_EVENT_FLAG_FALLBACK;
4018 default:
4019 return false;
4020 }
4021}
4022
4023bool InputDispatcher::InputState::shouldCancelMotion(const MotionMemento& memento,
Jeff Brownda3d5a92011-03-29 15:11:34 -07004024 const CancelationOptions& options) {
Jeff Brown65fd2512011-08-18 11:20:58 -07004025 if (options.deviceId != -1 && memento.deviceId != options.deviceId) {
4026 return false;
4027 }
4028
Jeff Brownda3d5a92011-03-29 15:11:34 -07004029 switch (options.mode) {
4030 case CancelationOptions::CANCEL_ALL_EVENTS:
Jeff Brown49ed71d2010-12-06 17:13:33 -08004031 return true;
Jeff Brownda3d5a92011-03-29 15:11:34 -07004032 case CancelationOptions::CANCEL_POINTER_EVENTS:
Jeff Brown49ed71d2010-12-06 17:13:33 -08004033 return memento.source & AINPUT_SOURCE_CLASS_POINTER;
Jeff Brownda3d5a92011-03-29 15:11:34 -07004034 case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
Jeff Brown49ed71d2010-12-06 17:13:33 -08004035 return !(memento.source & AINPUT_SOURCE_CLASS_POINTER);
4036 default:
4037 return false;
Jeff Brownb6997262010-10-08 22:31:17 -07004038 }
Jeff Brownb88102f2010-09-08 11:49:43 -07004039}
4040
4041
Jeff Brown46b9ac02010-04-22 18:58:52 -07004042// --- InputDispatcher::Connection ---
4043
Jeff Brown928e0542011-01-10 11:17:36 -08004044InputDispatcher::Connection::Connection(const sp<InputChannel>& inputChannel,
Jeff Browncc4f7db2011-08-30 20:34:48 -07004045 const sp<InputWindowHandle>& inputWindowHandle, bool monitor) :
Jeff Brown928e0542011-01-10 11:17:36 -08004046 status(STATUS_NORMAL), inputChannel(inputChannel), inputWindowHandle(inputWindowHandle),
Jeff Browncc4f7db2011-08-30 20:34:48 -07004047 monitor(monitor),
Jeff Brownd1c48a02012-02-06 19:12:47 -08004048 inputPublisher(inputChannel), inputPublisherBlocked(false) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07004049}
4050
4051InputDispatcher::Connection::~Connection() {
4052}
4053
Jeff Brown481c1572012-03-09 14:41:15 -08004054const char* InputDispatcher::Connection::getWindowName() const {
4055 if (inputWindowHandle != NULL) {
4056 return inputWindowHandle->getName().string();
4057 }
4058 if (monitor) {
4059 return "monitor";
4060 }
4061 return "?";
4062}
4063
Jeff Brown9c3cda02010-06-15 01:31:58 -07004064const char* InputDispatcher::Connection::getStatusLabel() const {
4065 switch (status) {
4066 case STATUS_NORMAL:
4067 return "NORMAL";
4068
4069 case STATUS_BROKEN:
4070 return "BROKEN";
4071
Jeff Brown9c3cda02010-06-15 01:31:58 -07004072 case STATUS_ZOMBIE:
4073 return "ZOMBIE";
4074
4075 default:
4076 return "UNKNOWN";
4077 }
4078}
4079
Jeff Brown072ec962012-02-07 14:46:57 -08004080InputDispatcher::DispatchEntry* InputDispatcher::Connection::findWaitQueueEntry(uint32_t seq) {
4081 for (DispatchEntry* entry = waitQueue.head; entry != NULL; entry = entry->next) {
4082 if (entry->seq == seq) {
4083 return entry;
4084 }
4085 }
4086 return NULL;
4087}
4088
Jeff Brownb88102f2010-09-08 11:49:43 -07004089
Jeff Brown9c3cda02010-06-15 01:31:58 -07004090// --- InputDispatcher::CommandEntry ---
4091
Jeff Brownac386072011-07-20 15:19:50 -07004092InputDispatcher::CommandEntry::CommandEntry(Command command) :
Jeff Brown072ec962012-02-07 14:46:57 -08004093 command(command), eventTime(0), keyEntry(NULL), userActivityEventType(0),
4094 seq(0), handled(false) {
Jeff Brown9c3cda02010-06-15 01:31:58 -07004095}
4096
4097InputDispatcher::CommandEntry::~CommandEntry() {
4098}
4099
Jeff Brown46b9ac02010-04-22 18:58:52 -07004100
Jeff Brown01ce2e92010-09-26 22:20:12 -07004101// --- InputDispatcher::TouchState ---
4102
4103InputDispatcher::TouchState::TouchState() :
Jeff Brown58a2da82011-01-25 16:02:22 -08004104 down(false), split(false), deviceId(-1), source(0) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07004105}
4106
4107InputDispatcher::TouchState::~TouchState() {
4108}
4109
4110void InputDispatcher::TouchState::reset() {
4111 down = false;
4112 split = false;
Jeff Brown95712852011-01-04 19:41:59 -08004113 deviceId = -1;
Jeff Brown58a2da82011-01-25 16:02:22 -08004114 source = 0;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004115 windows.clear();
4116}
4117
4118void InputDispatcher::TouchState::copyFrom(const TouchState& other) {
4119 down = other.down;
4120 split = other.split;
Jeff Brown95712852011-01-04 19:41:59 -08004121 deviceId = other.deviceId;
Jeff Brown58a2da82011-01-25 16:02:22 -08004122 source = other.source;
Jeff Brown9302c872011-07-13 22:51:29 -07004123 windows = other.windows;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004124}
4125
Jeff Brown9302c872011-07-13 22:51:29 -07004126void InputDispatcher::TouchState::addOrUpdateWindow(const sp<InputWindowHandle>& windowHandle,
Jeff Brown01ce2e92010-09-26 22:20:12 -07004127 int32_t targetFlags, BitSet32 pointerIds) {
4128 if (targetFlags & InputTarget::FLAG_SPLIT) {
4129 split = true;
4130 }
4131
4132 for (size_t i = 0; i < windows.size(); i++) {
4133 TouchedWindow& touchedWindow = windows.editItemAt(i);
Jeff Brown9302c872011-07-13 22:51:29 -07004134 if (touchedWindow.windowHandle == windowHandle) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07004135 touchedWindow.targetFlags |= targetFlags;
Jeff Brown98db5fa2011-06-08 15:37:10 -07004136 if (targetFlags & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
4137 touchedWindow.targetFlags &= ~InputTarget::FLAG_DISPATCH_AS_IS;
4138 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07004139 touchedWindow.pointerIds.value |= pointerIds.value;
4140 return;
4141 }
4142 }
4143
4144 windows.push();
4145
4146 TouchedWindow& touchedWindow = windows.editTop();
Jeff Brown9302c872011-07-13 22:51:29 -07004147 touchedWindow.windowHandle = windowHandle;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004148 touchedWindow.targetFlags = targetFlags;
4149 touchedWindow.pointerIds = pointerIds;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004150}
4151
Jeff Brownf44e3942012-04-20 11:33:27 -07004152void InputDispatcher::TouchState::removeWindow(const sp<InputWindowHandle>& windowHandle) {
4153 for (size_t i = 0; i < windows.size(); i++) {
4154 if (windows.itemAt(i).windowHandle == windowHandle) {
4155 windows.removeAt(i);
4156 return;
4157 }
4158 }
4159}
4160
Jeff Browna032cc02011-03-07 16:56:21 -08004161void InputDispatcher::TouchState::filterNonAsIsTouchWindows() {
Jeff Brown01ce2e92010-09-26 22:20:12 -07004162 for (size_t i = 0 ; i < windows.size(); ) {
Jeff Browna032cc02011-03-07 16:56:21 -08004163 TouchedWindow& window = windows.editItemAt(i);
Jeff Brown98db5fa2011-06-08 15:37:10 -07004164 if (window.targetFlags & (InputTarget::FLAG_DISPATCH_AS_IS
4165 | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER)) {
Jeff Browna032cc02011-03-07 16:56:21 -08004166 window.targetFlags &= ~InputTarget::FLAG_DISPATCH_MASK;
4167 window.targetFlags |= InputTarget::FLAG_DISPATCH_AS_IS;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004168 i += 1;
Jeff Browna032cc02011-03-07 16:56:21 -08004169 } else {
4170 windows.removeAt(i);
Jeff Brown01ce2e92010-09-26 22:20:12 -07004171 }
4172 }
4173}
4174
Jeff Brown9302c872011-07-13 22:51:29 -07004175sp<InputWindowHandle> InputDispatcher::TouchState::getFirstForegroundWindowHandle() const {
Jeff Brown01ce2e92010-09-26 22:20:12 -07004176 for (size_t i = 0; i < windows.size(); i++) {
Jeff Brown98db5fa2011-06-08 15:37:10 -07004177 const TouchedWindow& window = windows.itemAt(i);
4178 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
Jeff Brown9302c872011-07-13 22:51:29 -07004179 return window.windowHandle;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004180 }
4181 }
4182 return NULL;
4183}
4184
Jeff Brown98db5fa2011-06-08 15:37:10 -07004185bool InputDispatcher::TouchState::isSlippery() const {
4186 // Must have exactly one foreground window.
4187 bool haveSlipperyForegroundWindow = false;
4188 for (size_t i = 0; i < windows.size(); i++) {
4189 const TouchedWindow& window = windows.itemAt(i);
4190 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
Jeff Browncc4f7db2011-08-30 20:34:48 -07004191 if (haveSlipperyForegroundWindow
4192 || !(window.windowHandle->getInfo()->layoutParamsFlags
4193 & InputWindowInfo::FLAG_SLIPPERY)) {
Jeff Brown98db5fa2011-06-08 15:37:10 -07004194 return false;
4195 }
4196 haveSlipperyForegroundWindow = true;
4197 }
4198 }
4199 return haveSlipperyForegroundWindow;
4200}
4201
Jeff Brown01ce2e92010-09-26 22:20:12 -07004202
Jeff Brown46b9ac02010-04-22 18:58:52 -07004203// --- InputDispatcherThread ---
4204
4205InputDispatcherThread::InputDispatcherThread(const sp<InputDispatcherInterface>& dispatcher) :
4206 Thread(/*canCallJava*/ true), mDispatcher(dispatcher) {
4207}
4208
4209InputDispatcherThread::~InputDispatcherThread() {
4210}
4211
4212bool InputDispatcherThread::threadLoop() {
4213 mDispatcher->dispatchOnce();
4214 return true;
4215}
4216
4217} // namespace android