blob: e63da05d8dfe45f4974b37e1b25f959736bfa5d6 [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 Brown22aa5122012-06-17 12:01:06 -070056#include <time.h>
Jeff Brown46b9ac02010-04-22 18:58:52 -070057
Jeff Brownf2f48712010-10-01 17:46:21 -070058#define INDENT " "
59#define INDENT2 " "
Jeff Brown265f1cc2012-06-11 18:01:06 -070060#define INDENT3 " "
61#define INDENT4 " "
Jeff Brownf2f48712010-10-01 17:46:21 -070062
Jeff Brown46b9ac02010-04-22 18:58:52 -070063namespace android {
64
Jeff Brownb88102f2010-09-08 11:49:43 -070065// Default input dispatching timeout if there is no focused application or paused window
66// from which to determine an appropriate dispatching timeout.
67const nsecs_t DEFAULT_INPUT_DISPATCHING_TIMEOUT = 5000 * 1000000LL; // 5 sec
68
69// Amount of time to allow for all pending events to be processed when an app switch
70// key is on the way. This is used to preempt input dispatch and drop input events
71// when an application takes too long to respond and the user has pressed an app switch key.
72const nsecs_t APP_SWITCH_TIMEOUT = 500 * 1000000LL; // 0.5sec
73
Jeff Brown928e0542011-01-10 11:17:36 -080074// Amount of time to allow for an event to be dispatched (measured since its eventTime)
75// before considering it stale and dropping it.
76const nsecs_t STALE_EVENT_TIMEOUT = 10000 * 1000000LL; // 10sec
77
Jeff Brownd1c48a02012-02-06 19:12:47 -080078// Amount of time to allow touch events to be streamed out to a connection before requiring
79// that the first event be finished. This value extends the ANR timeout by the specified
80// amount. For example, if streaming is allowed to get ahead by one second relative to the
81// queue of waiting unfinished events, then ANRs will similarly be delayed by one second.
82const nsecs_t STREAM_AHEAD_EVENT_TIMEOUT = 500 * 1000000LL; // 0.5sec
83
Jeff Brown265f1cc2012-06-11 18:01:06 -070084// Log a warning when an event takes longer than this to process, even if an ANR does not occur.
85const nsecs_t SLOW_EVENT_PROCESSING_WARNING_TIMEOUT = 2000 * 1000000LL; // 2sec
86
Jeff Brown46b9ac02010-04-22 18:58:52 -070087
Jeff Brown7fbdc842010-06-17 20:52:56 -070088static inline nsecs_t now() {
89 return systemTime(SYSTEM_TIME_MONOTONIC);
90}
91
Jeff Brownb88102f2010-09-08 11:49:43 -070092static inline const char* toString(bool value) {
93 return value ? "true" : "false";
94}
95
Jeff Brown01ce2e92010-09-26 22:20:12 -070096static inline int32_t getMotionEventActionPointerIndex(int32_t action) {
97 return (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK)
98 >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
99}
100
101static bool isValidKeyAction(int32_t action) {
102 switch (action) {
103 case AKEY_EVENT_ACTION_DOWN:
104 case AKEY_EVENT_ACTION_UP:
105 return true;
106 default:
107 return false;
108 }
109}
110
111static bool validateKeyEvent(int32_t action) {
112 if (! isValidKeyAction(action)) {
Steve Block3762c312012-01-06 19:20:56 +0000113 ALOGE("Key event has invalid action code 0x%x", action);
Jeff Brown01ce2e92010-09-26 22:20:12 -0700114 return false;
115 }
116 return true;
117}
118
Jeff Brownb6997262010-10-08 22:31:17 -0700119static bool isValidMotionAction(int32_t action, size_t pointerCount) {
Jeff Brown01ce2e92010-09-26 22:20:12 -0700120 switch (action & AMOTION_EVENT_ACTION_MASK) {
121 case AMOTION_EVENT_ACTION_DOWN:
122 case AMOTION_EVENT_ACTION_UP:
123 case AMOTION_EVENT_ACTION_CANCEL:
124 case AMOTION_EVENT_ACTION_MOVE:
Jeff Brown01ce2e92010-09-26 22:20:12 -0700125 case AMOTION_EVENT_ACTION_OUTSIDE:
Jeff Browna032cc02011-03-07 16:56:21 -0800126 case AMOTION_EVENT_ACTION_HOVER_ENTER:
Jeff Browncc0c1592011-02-19 05:07:28 -0800127 case AMOTION_EVENT_ACTION_HOVER_MOVE:
Jeff Browna032cc02011-03-07 16:56:21 -0800128 case AMOTION_EVENT_ACTION_HOVER_EXIT:
Jeff Brown33bbfd22011-02-24 20:55:35 -0800129 case AMOTION_EVENT_ACTION_SCROLL:
Jeff Brown01ce2e92010-09-26 22:20:12 -0700130 return true;
Jeff Brownb6997262010-10-08 22:31:17 -0700131 case AMOTION_EVENT_ACTION_POINTER_DOWN:
132 case AMOTION_EVENT_ACTION_POINTER_UP: {
133 int32_t index = getMotionEventActionPointerIndex(action);
134 return index >= 0 && size_t(index) < pointerCount;
135 }
Jeff Brown01ce2e92010-09-26 22:20:12 -0700136 default:
137 return false;
138 }
139}
140
141static bool validateMotionEvent(int32_t action, size_t pointerCount,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700142 const PointerProperties* pointerProperties) {
Jeff Brownb6997262010-10-08 22:31:17 -0700143 if (! isValidMotionAction(action, pointerCount)) {
Steve Block3762c312012-01-06 19:20:56 +0000144 ALOGE("Motion event has invalid action code 0x%x", action);
Jeff Brown01ce2e92010-09-26 22:20:12 -0700145 return false;
146 }
147 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Steve Block3762c312012-01-06 19:20:56 +0000148 ALOGE("Motion event has invalid pointer count %d; value must be between 1 and %d.",
Jeff Brown01ce2e92010-09-26 22:20:12 -0700149 pointerCount, MAX_POINTERS);
150 return false;
151 }
Jeff Brownc3db8582010-10-20 15:33:38 -0700152 BitSet32 pointerIdBits;
Jeff Brown01ce2e92010-09-26 22:20:12 -0700153 for (size_t i = 0; i < pointerCount; i++) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700154 int32_t id = pointerProperties[i].id;
Jeff Brownc3db8582010-10-20 15:33:38 -0700155 if (id < 0 || id > MAX_POINTER_ID) {
Steve Block3762c312012-01-06 19:20:56 +0000156 ALOGE("Motion event has invalid pointer id %d; value must be between 0 and %d",
Jeff Brownc3db8582010-10-20 15:33:38 -0700157 id, MAX_POINTER_ID);
Jeff Brown01ce2e92010-09-26 22:20:12 -0700158 return false;
159 }
Jeff Brownc3db8582010-10-20 15:33:38 -0700160 if (pointerIdBits.hasBit(id)) {
Steve Block3762c312012-01-06 19:20:56 +0000161 ALOGE("Motion event has duplicate pointer id %d", id);
Jeff Brownc3db8582010-10-20 15:33:38 -0700162 return false;
163 }
164 pointerIdBits.markBit(id);
Jeff Brown01ce2e92010-09-26 22:20:12 -0700165 }
166 return true;
167}
168
Jeff Brownfbf09772011-01-16 14:06:57 -0800169static void dumpRegion(String8& dump, const SkRegion& region) {
170 if (region.isEmpty()) {
171 dump.append("<empty>");
172 return;
173 }
174
175 bool first = true;
176 for (SkRegion::Iterator it(region); !it.done(); it.next()) {
177 if (first) {
178 first = false;
179 } else {
180 dump.append("|");
181 }
182 const SkIRect& rect = it.rect();
183 dump.appendFormat("[%d,%d][%d,%d]", rect.fLeft, rect.fTop, rect.fRight, rect.fBottom);
184 }
185}
186
Jeff Brownb88102f2010-09-08 11:49:43 -0700187
Jeff Brown46b9ac02010-04-22 18:58:52 -0700188// --- InputDispatcher ---
189
Jeff Brown9c3cda02010-06-15 01:31:58 -0700190InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy) :
Jeff Brownb88102f2010-09-08 11:49:43 -0700191 mPolicy(policy),
Jeff Brown928e0542011-01-10 11:17:36 -0800192 mPendingEvent(NULL), mAppSwitchSawKeyDown(false), mAppSwitchDueTime(LONG_LONG_MAX),
193 mNextUnblockedEvent(NULL),
Jeff Brownc042ee22012-05-08 13:03:42 -0700194 mDispatchEnabled(false), mDispatchFrozen(false), mInputFilterEnabled(false),
Jeff Brown9302c872011-07-13 22:51:29 -0700195 mInputTargetWaitCause(INPUT_TARGET_WAIT_CAUSE_NONE) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -0700196 mLooper = new Looper(false);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700197
Jeff Brown46b9ac02010-04-22 18:58:52 -0700198 mKeyRepeatState.lastKeyEntry = NULL;
Jeff Brown9c3cda02010-06-15 01:31:58 -0700199
Jeff Brown214eaf42011-05-26 19:17:02 -0700200 policy->getDispatcherConfiguration(&mConfig);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700201}
202
203InputDispatcher::~InputDispatcher() {
Jeff Brownb88102f2010-09-08 11:49:43 -0700204 { // acquire lock
205 AutoMutex _l(mLock);
206
207 resetKeyRepeatLocked();
Jeff Brown54a18252010-09-16 14:07:33 -0700208 releasePendingEventLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -0700209 drainInboundQueueLocked();
210 }
Jeff Brown46b9ac02010-04-22 18:58:52 -0700211
Jeff Browncbee6d62012-02-03 20:11:27 -0800212 while (mConnectionsByFd.size() != 0) {
213 unregisterInputChannel(mConnectionsByFd.valueAt(0)->inputChannel);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700214 }
Jeff Brown46b9ac02010-04-22 18:58:52 -0700215}
216
217void InputDispatcher::dispatchOnce() {
Jeff Brown46b9ac02010-04-22 18:58:52 -0700218 nsecs_t nextWakeupTime = LONG_LONG_MAX;
219 { // acquire lock
220 AutoMutex _l(mLock);
Jeff Brown112b5f52012-01-27 17:32:06 -0800221 mDispatcherIsAliveCondition.broadcast();
222
Jeff Brown214eaf42011-05-26 19:17:02 -0700223 dispatchOnceInnerLocked(&nextWakeupTime);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700224
Jeff Brownb88102f2010-09-08 11:49:43 -0700225 if (runCommandsLockedInterruptible()) {
226 nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
Jeff Brown46b9ac02010-04-22 18:58:52 -0700227 }
Jeff Brown46b9ac02010-04-22 18:58:52 -0700228 } // release lock
229
Jeff Brownb88102f2010-09-08 11:49:43 -0700230 // Wait for callback or timeout or wake. (make sure we round up, not down)
231 nsecs_t currentTime = now();
Jeff Brownaa3855d2011-03-17 01:34:19 -0700232 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
Jeff Brown4fe6c3e2010-09-13 23:17:30 -0700233 mLooper->pollOnce(timeoutMillis);
Jeff Brownb88102f2010-09-08 11:49:43 -0700234}
235
Jeff Brown214eaf42011-05-26 19:17:02 -0700236void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700237 nsecs_t currentTime = now();
238
239 // Reset the key repeat timer whenever we disallow key events, even if the next event
240 // is not a key. This is to ensure that we abort a key repeat if the device is just coming
241 // out of sleep.
Jeff Brown214eaf42011-05-26 19:17:02 -0700242 if (!mPolicy->isKeyRepeatEnabled()) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700243 resetKeyRepeatLocked();
244 }
245
Jeff Brownb88102f2010-09-08 11:49:43 -0700246 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
247 if (mDispatchFrozen) {
248#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +0000249 ALOGD("Dispatch frozen. Waiting some more.");
Jeff Brownb88102f2010-09-08 11:49:43 -0700250#endif
251 return;
252 }
253
254 // Optimize latency of app switches.
255 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
256 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
257 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
258 if (mAppSwitchDueTime < *nextWakeupTime) {
259 *nextWakeupTime = mAppSwitchDueTime;
260 }
261
Jeff Brownb88102f2010-09-08 11:49:43 -0700262 // Ready to start a new event.
263 // If we don't already have a pending event, go grab one.
264 if (! mPendingEvent) {
265 if (mInboundQueue.isEmpty()) {
266 if (isAppSwitchDue) {
267 // The inbound queue is empty so the app switch key we were waiting
268 // for will never arrive. Stop waiting for it.
269 resetPendingAppSwitchLocked(false);
270 isAppSwitchDue = false;
271 }
272
273 // Synthesize a key repeat if appropriate.
274 if (mKeyRepeatState.lastKeyEntry) {
275 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
Jeff Brown214eaf42011-05-26 19:17:02 -0700276 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700277 } else {
278 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
279 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
280 }
281 }
282 }
Jeff Browncc4f7db2011-08-30 20:34:48 -0700283
284 // Nothing to do if there is no pending event.
Jeff Browne9bb9be2012-02-06 15:47:55 -0800285 if (!mPendingEvent) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700286 return;
287 }
288 } else {
289 // Inbound queue has at least one entry.
Jeff Browne9bb9be2012-02-06 15:47:55 -0800290 mPendingEvent = mInboundQueue.dequeueAtHead();
Jeff Brown481c1572012-03-09 14:41:15 -0800291 traceInboundQueueLengthLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -0700292 }
Jeff Browne2fe69e2010-10-18 13:21:23 -0700293
294 // Poke user activity for this event.
295 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
296 pokeUserActivityLocked(mPendingEvent);
297 }
Jeff Browne9bb9be2012-02-06 15:47:55 -0800298
299 // Get ready to dispatch the event.
300 resetANRTimeoutsLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -0700301 }
302
303 // Now we have an event to dispatch.
Jeff Brown928e0542011-01-10 11:17:36 -0800304 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Steve Blockec193de2012-01-09 18:35:44 +0000305 ALOG_ASSERT(mPendingEvent != NULL);
Jeff Brown54a18252010-09-16 14:07:33 -0700306 bool done = false;
Jeff Brownb6997262010-10-08 22:31:17 -0700307 DropReason dropReason = DROP_REASON_NOT_DROPPED;
308 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
309 dropReason = DROP_REASON_POLICY;
310 } else if (!mDispatchEnabled) {
311 dropReason = DROP_REASON_DISABLED;
312 }
Jeff Brown928e0542011-01-10 11:17:36 -0800313
314 if (mNextUnblockedEvent == mPendingEvent) {
315 mNextUnblockedEvent = NULL;
316 }
317
Jeff Brownb88102f2010-09-08 11:49:43 -0700318 switch (mPendingEvent->type) {
319 case EventEntry::TYPE_CONFIGURATION_CHANGED: {
320 ConfigurationChangedEntry* typedEntry =
321 static_cast<ConfigurationChangedEntry*>(mPendingEvent);
Jeff Brown54a18252010-09-16 14:07:33 -0700322 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Jeff Brownb6997262010-10-08 22:31:17 -0700323 dropReason = DROP_REASON_NOT_DROPPED; // configuration changes are never dropped
Jeff Brownb88102f2010-09-08 11:49:43 -0700324 break;
325 }
326
Jeff Brown65fd2512011-08-18 11:20:58 -0700327 case EventEntry::TYPE_DEVICE_RESET: {
328 DeviceResetEntry* typedEntry =
329 static_cast<DeviceResetEntry*>(mPendingEvent);
330 done = dispatchDeviceResetLocked(currentTime, typedEntry);
331 dropReason = DROP_REASON_NOT_DROPPED; // device resets are never dropped
332 break;
333 }
334
Jeff Brownb88102f2010-09-08 11:49:43 -0700335 case EventEntry::TYPE_KEY: {
336 KeyEntry* typedEntry = static_cast<KeyEntry*>(mPendingEvent);
Jeff Brownb6997262010-10-08 22:31:17 -0700337 if (isAppSwitchDue) {
338 if (isAppSwitchKeyEventLocked(typedEntry)) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700339 resetPendingAppSwitchLocked(true);
Jeff Brownb6997262010-10-08 22:31:17 -0700340 isAppSwitchDue = false;
341 } else if (dropReason == DROP_REASON_NOT_DROPPED) {
342 dropReason = DROP_REASON_APP_SWITCH;
Jeff Brownb88102f2010-09-08 11:49:43 -0700343 }
344 }
Jeff Brown928e0542011-01-10 11:17:36 -0800345 if (dropReason == DROP_REASON_NOT_DROPPED
346 && isStaleEventLocked(currentTime, typedEntry)) {
347 dropReason = DROP_REASON_STALE;
348 }
349 if (dropReason == DROP_REASON_NOT_DROPPED && mNextUnblockedEvent) {
350 dropReason = DROP_REASON_BLOCKED;
351 }
Jeff Brown214eaf42011-05-26 19:17:02 -0700352 done = dispatchKeyLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700353 break;
354 }
355
356 case EventEntry::TYPE_MOTION: {
357 MotionEntry* typedEntry = static_cast<MotionEntry*>(mPendingEvent);
Jeff Brownb6997262010-10-08 22:31:17 -0700358 if (dropReason == DROP_REASON_NOT_DROPPED && isAppSwitchDue) {
359 dropReason = DROP_REASON_APP_SWITCH;
Jeff Brownb88102f2010-09-08 11:49:43 -0700360 }
Jeff Brown928e0542011-01-10 11:17:36 -0800361 if (dropReason == DROP_REASON_NOT_DROPPED
362 && isStaleEventLocked(currentTime, typedEntry)) {
363 dropReason = DROP_REASON_STALE;
364 }
365 if (dropReason == DROP_REASON_NOT_DROPPED && mNextUnblockedEvent) {
366 dropReason = DROP_REASON_BLOCKED;
367 }
Jeff Brownb6997262010-10-08 22:31:17 -0700368 done = dispatchMotionLocked(currentTime, typedEntry,
Jeff Browne20c9e02010-10-11 14:20:19 -0700369 &dropReason, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700370 break;
371 }
372
373 default:
Steve Blockec193de2012-01-09 18:35:44 +0000374 ALOG_ASSERT(false);
Jeff Brownb88102f2010-09-08 11:49:43 -0700375 break;
376 }
377
Jeff Brown54a18252010-09-16 14:07:33 -0700378 if (done) {
Jeff Brownb6997262010-10-08 22:31:17 -0700379 if (dropReason != DROP_REASON_NOT_DROPPED) {
380 dropInboundEventLocked(mPendingEvent, dropReason);
381 }
382
Jeff Brown54a18252010-09-16 14:07:33 -0700383 releasePendingEventLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -0700384 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
385 }
386}
387
388bool InputDispatcher::enqueueInboundEventLocked(EventEntry* entry) {
389 bool needWake = mInboundQueue.isEmpty();
390 mInboundQueue.enqueueAtTail(entry);
Jeff Brown481c1572012-03-09 14:41:15 -0800391 traceInboundQueueLengthLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -0700392
393 switch (entry->type) {
Jeff Brownb6997262010-10-08 22:31:17 -0700394 case EventEntry::TYPE_KEY: {
Jeff Brown928e0542011-01-10 11:17:36 -0800395 // Optimize app switch latency.
396 // If the application takes too long to catch up then we drop all events preceding
397 // the app switch key.
Jeff Brownb6997262010-10-08 22:31:17 -0700398 KeyEntry* keyEntry = static_cast<KeyEntry*>(entry);
399 if (isAppSwitchKeyEventLocked(keyEntry)) {
400 if (keyEntry->action == AKEY_EVENT_ACTION_DOWN) {
401 mAppSwitchSawKeyDown = true;
402 } else if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
403 if (mAppSwitchSawKeyDown) {
404#if DEBUG_APP_SWITCH
Steve Block5baa3a62011-12-20 16:23:08 +0000405 ALOGD("App switch is pending!");
Jeff Brownb6997262010-10-08 22:31:17 -0700406#endif
407 mAppSwitchDueTime = keyEntry->eventTime + APP_SWITCH_TIMEOUT;
408 mAppSwitchSawKeyDown = false;
409 needWake = true;
410 }
411 }
412 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700413 break;
414 }
Jeff Brown928e0542011-01-10 11:17:36 -0800415
416 case EventEntry::TYPE_MOTION: {
417 // Optimize case where the current application is unresponsive and the user
418 // decides to touch a window in a different application.
419 // If the application takes too long to catch up then we drop all events preceding
420 // the touch into the other window.
421 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
Jeff Brown33bbfd22011-02-24 20:55:35 -0800422 if (motionEntry->action == AMOTION_EVENT_ACTION_DOWN
Jeff Brown928e0542011-01-10 11:17:36 -0800423 && (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER)
424 && mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY
Jeff Brown9302c872011-07-13 22:51:29 -0700425 && mInputTargetWaitApplicationHandle != NULL) {
Jeff Brown3241b6b2012-02-03 15:08:02 -0800426 int32_t x = int32_t(motionEntry->pointerCoords[0].
Jeff Brownebbd5d12011-02-17 13:01:34 -0800427 getAxisValue(AMOTION_EVENT_AXIS_X));
Jeff Brown3241b6b2012-02-03 15:08:02 -0800428 int32_t y = int32_t(motionEntry->pointerCoords[0].
Jeff Brownebbd5d12011-02-17 13:01:34 -0800429 getAxisValue(AMOTION_EVENT_AXIS_Y));
Jeff Brown9302c872011-07-13 22:51:29 -0700430 sp<InputWindowHandle> touchedWindowHandle = findTouchedWindowAtLocked(x, y);
431 if (touchedWindowHandle != NULL
432 && touchedWindowHandle->inputApplicationHandle
433 != mInputTargetWaitApplicationHandle) {
Jeff Brown928e0542011-01-10 11:17:36 -0800434 // User touched a different application than the one we are waiting on.
435 // Flag the event, and start pruning the input queue.
436 mNextUnblockedEvent = motionEntry;
437 needWake = true;
438 }
439 }
440 break;
441 }
Jeff Brownb6997262010-10-08 22:31:17 -0700442 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700443
444 return needWake;
445}
446
Jeff Brown9302c872011-07-13 22:51:29 -0700447sp<InputWindowHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t x, int32_t y) {
Jeff Brown928e0542011-01-10 11:17:36 -0800448 // Traverse windows from front to back to find touched window.
Jeff Brown9302c872011-07-13 22:51:29 -0700449 size_t numWindows = mWindowHandles.size();
Jeff Brown928e0542011-01-10 11:17:36 -0800450 for (size_t i = 0; i < numWindows; i++) {
Jeff Brown9302c872011-07-13 22:51:29 -0700451 sp<InputWindowHandle> windowHandle = mWindowHandles.itemAt(i);
Jeff Browncc4f7db2011-08-30 20:34:48 -0700452 const InputWindowInfo* windowInfo = windowHandle->getInfo();
453 int32_t flags = windowInfo->layoutParamsFlags;
Jeff Brown928e0542011-01-10 11:17:36 -0800454
Jeff Browncc4f7db2011-08-30 20:34:48 -0700455 if (windowInfo->visible) {
456 if (!(flags & InputWindowInfo::FLAG_NOT_TOUCHABLE)) {
457 bool isTouchModal = (flags & (InputWindowInfo::FLAG_NOT_FOCUSABLE
458 | InputWindowInfo::FLAG_NOT_TOUCH_MODAL)) == 0;
459 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
Jeff Brown928e0542011-01-10 11:17:36 -0800460 // Found window.
Jeff Brown9302c872011-07-13 22:51:29 -0700461 return windowHandle;
Jeff Brown928e0542011-01-10 11:17:36 -0800462 }
463 }
464 }
465
Jeff Browncc4f7db2011-08-30 20:34:48 -0700466 if (flags & InputWindowInfo::FLAG_SYSTEM_ERROR) {
Jeff Brown928e0542011-01-10 11:17:36 -0800467 // Error window is on top but not visible, so touch is dropped.
468 return NULL;
469 }
470 }
471 return NULL;
472}
473
Jeff Brownb6997262010-10-08 22:31:17 -0700474void InputDispatcher::dropInboundEventLocked(EventEntry* entry, DropReason dropReason) {
475 const char* reason;
476 switch (dropReason) {
477 case DROP_REASON_POLICY:
Jeff Browne20c9e02010-10-11 14:20:19 -0700478#if DEBUG_INBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +0000479 ALOGD("Dropped event because policy consumed it.");
Jeff Browne20c9e02010-10-11 14:20:19 -0700480#endif
Jeff Brown3122e442010-10-11 23:32:49 -0700481 reason = "inbound event was dropped because the policy consumed it";
Jeff Brownb6997262010-10-08 22:31:17 -0700482 break;
483 case DROP_REASON_DISABLED:
Steve Block6215d3f2012-01-04 20:05:49 +0000484 ALOGI("Dropped event because input dispatch is disabled.");
Jeff Brownb6997262010-10-08 22:31:17 -0700485 reason = "inbound event was dropped because input dispatch is disabled";
486 break;
487 case DROP_REASON_APP_SWITCH:
Steve Block6215d3f2012-01-04 20:05:49 +0000488 ALOGI("Dropped event because of pending overdue app switch.");
Jeff Brownb6997262010-10-08 22:31:17 -0700489 reason = "inbound event was dropped because of pending overdue app switch";
490 break;
Jeff Brown928e0542011-01-10 11:17:36 -0800491 case DROP_REASON_BLOCKED:
Steve Block6215d3f2012-01-04 20:05:49 +0000492 ALOGI("Dropped event because the current application is not responding and the user "
Jeff Brown81346812011-06-28 20:08:48 -0700493 "has started interacting with a different application.");
Jeff Brown928e0542011-01-10 11:17:36 -0800494 reason = "inbound event was dropped because the current application is not responding "
Jeff Brown81346812011-06-28 20:08:48 -0700495 "and the user has started interacting with a different application";
Jeff Brown928e0542011-01-10 11:17:36 -0800496 break;
497 case DROP_REASON_STALE:
Steve Block6215d3f2012-01-04 20:05:49 +0000498 ALOGI("Dropped event because it is stale.");
Jeff Brown928e0542011-01-10 11:17:36 -0800499 reason = "inbound event was dropped because it is stale";
500 break;
Jeff Brownb6997262010-10-08 22:31:17 -0700501 default:
Steve Blockec193de2012-01-09 18:35:44 +0000502 ALOG_ASSERT(false);
Jeff Brownb6997262010-10-08 22:31:17 -0700503 return;
504 }
505
506 switch (entry->type) {
Jeff Brownda3d5a92011-03-29 15:11:34 -0700507 case EventEntry::TYPE_KEY: {
508 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
509 synthesizeCancelationEventsForAllConnectionsLocked(options);
Jeff Brownb6997262010-10-08 22:31:17 -0700510 break;
Jeff Brownda3d5a92011-03-29 15:11:34 -0700511 }
Jeff Brownb6997262010-10-08 22:31:17 -0700512 case EventEntry::TYPE_MOTION: {
513 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
514 if (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) {
Jeff Brownda3d5a92011-03-29 15:11:34 -0700515 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
516 synthesizeCancelationEventsForAllConnectionsLocked(options);
Jeff Brownb6997262010-10-08 22:31:17 -0700517 } else {
Jeff Brownda3d5a92011-03-29 15:11:34 -0700518 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
519 synthesizeCancelationEventsForAllConnectionsLocked(options);
Jeff Brownb6997262010-10-08 22:31:17 -0700520 }
521 break;
522 }
523 }
524}
525
526bool InputDispatcher::isAppSwitchKeyCode(int32_t keyCode) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700527 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL;
528}
529
Jeff Brownb6997262010-10-08 22:31:17 -0700530bool InputDispatcher::isAppSwitchKeyEventLocked(KeyEntry* keyEntry) {
531 return ! (keyEntry->flags & AKEY_EVENT_FLAG_CANCELED)
532 && isAppSwitchKeyCode(keyEntry->keyCode)
Jeff Browne20c9e02010-10-11 14:20:19 -0700533 && (keyEntry->policyFlags & POLICY_FLAG_TRUSTED)
Jeff Brownb6997262010-10-08 22:31:17 -0700534 && (keyEntry->policyFlags & POLICY_FLAG_PASS_TO_USER);
535}
536
Jeff Brownb88102f2010-09-08 11:49:43 -0700537bool InputDispatcher::isAppSwitchPendingLocked() {
538 return mAppSwitchDueTime != LONG_LONG_MAX;
539}
540
Jeff Brownb88102f2010-09-08 11:49:43 -0700541void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
542 mAppSwitchDueTime = LONG_LONG_MAX;
543
544#if DEBUG_APP_SWITCH
545 if (handled) {
Steve Block5baa3a62011-12-20 16:23:08 +0000546 ALOGD("App switch has arrived.");
Jeff Brownb88102f2010-09-08 11:49:43 -0700547 } else {
Steve Block5baa3a62011-12-20 16:23:08 +0000548 ALOGD("App switch was abandoned.");
Jeff Brownb88102f2010-09-08 11:49:43 -0700549 }
550#endif
Jeff Brown46b9ac02010-04-22 18:58:52 -0700551}
552
Jeff Brown928e0542011-01-10 11:17:36 -0800553bool InputDispatcher::isStaleEventLocked(nsecs_t currentTime, EventEntry* entry) {
554 return currentTime - entry->eventTime >= STALE_EVENT_TIMEOUT;
555}
556
Jeff Brown9c3cda02010-06-15 01:31:58 -0700557bool InputDispatcher::runCommandsLockedInterruptible() {
558 if (mCommandQueue.isEmpty()) {
559 return false;
560 }
Jeff Brown46b9ac02010-04-22 18:58:52 -0700561
Jeff Brown9c3cda02010-06-15 01:31:58 -0700562 do {
563 CommandEntry* commandEntry = mCommandQueue.dequeueAtHead();
564
565 Command command = commandEntry->command;
566 (this->*command)(commandEntry); // commands are implicitly 'LockedInterruptible'
567
Jeff Brown7fbdc842010-06-17 20:52:56 -0700568 commandEntry->connection.clear();
Jeff Brownac386072011-07-20 15:19:50 -0700569 delete commandEntry;
Jeff Brown9c3cda02010-06-15 01:31:58 -0700570 } while (! mCommandQueue.isEmpty());
571 return true;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700572}
573
Jeff Brown9c3cda02010-06-15 01:31:58 -0700574InputDispatcher::CommandEntry* InputDispatcher::postCommandLocked(Command command) {
Jeff Brownac386072011-07-20 15:19:50 -0700575 CommandEntry* commandEntry = new CommandEntry(command);
Jeff Brown9c3cda02010-06-15 01:31:58 -0700576 mCommandQueue.enqueueAtTail(commandEntry);
577 return commandEntry;
578}
579
Jeff Brownb88102f2010-09-08 11:49:43 -0700580void InputDispatcher::drainInboundQueueLocked() {
581 while (! mInboundQueue.isEmpty()) {
582 EventEntry* entry = mInboundQueue.dequeueAtHead();
Jeff Brown54a18252010-09-16 14:07:33 -0700583 releaseInboundEventLocked(entry);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700584 }
Jeff Brown481c1572012-03-09 14:41:15 -0800585 traceInboundQueueLengthLocked();
Jeff Brown46b9ac02010-04-22 18:58:52 -0700586}
587
Jeff Brown54a18252010-09-16 14:07:33 -0700588void InputDispatcher::releasePendingEventLocked() {
Jeff Brownb88102f2010-09-08 11:49:43 -0700589 if (mPendingEvent) {
Jeff Browne9bb9be2012-02-06 15:47:55 -0800590 resetANRTimeoutsLocked();
Jeff Brown54a18252010-09-16 14:07:33 -0700591 releaseInboundEventLocked(mPendingEvent);
Jeff Brownb88102f2010-09-08 11:49:43 -0700592 mPendingEvent = NULL;
593 }
594}
595
Jeff Brown54a18252010-09-16 14:07:33 -0700596void InputDispatcher::releaseInboundEventLocked(EventEntry* entry) {
Jeff Brown01ce2e92010-09-26 22:20:12 -0700597 InjectionState* injectionState = entry->injectionState;
598 if (injectionState && injectionState->injectionResult == INPUT_EVENT_INJECTION_PENDING) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700599#if DEBUG_DISPATCH_CYCLE
Steve Block5baa3a62011-12-20 16:23:08 +0000600 ALOGD("Injected inbound event was dropped.");
Jeff Brownb88102f2010-09-08 11:49:43 -0700601#endif
602 setInjectionResultLocked(entry, INPUT_EVENT_INJECTION_FAILED);
603 }
Jeff Brownabb4d442011-08-15 12:55:32 -0700604 if (entry == mNextUnblockedEvent) {
605 mNextUnblockedEvent = NULL;
606 }
Jeff Brownac386072011-07-20 15:19:50 -0700607 entry->release();
Jeff Brownb88102f2010-09-08 11:49:43 -0700608}
609
Jeff Brownb88102f2010-09-08 11:49:43 -0700610void InputDispatcher::resetKeyRepeatLocked() {
611 if (mKeyRepeatState.lastKeyEntry) {
Jeff Brownac386072011-07-20 15:19:50 -0700612 mKeyRepeatState.lastKeyEntry->release();
Jeff Brownb88102f2010-09-08 11:49:43 -0700613 mKeyRepeatState.lastKeyEntry = NULL;
614 }
615}
616
Jeff Brown214eaf42011-05-26 19:17:02 -0700617InputDispatcher::KeyEntry* InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
Jeff Brown349703e2010-06-22 01:27:15 -0700618 KeyEntry* entry = mKeyRepeatState.lastKeyEntry;
619
Jeff Brown349703e2010-06-22 01:27:15 -0700620 // Reuse the repeated key entry if it is otherwise unreferenced.
Jeff Browne20c9e02010-10-11 14:20:19 -0700621 uint32_t policyFlags = (entry->policyFlags & POLICY_FLAG_RAW_MASK)
622 | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700623 if (entry->refCount == 1) {
Jeff Brownac386072011-07-20 15:19:50 -0700624 entry->recycle();
Jeff Brown7fbdc842010-06-17 20:52:56 -0700625 entry->eventTime = currentTime;
Jeff Brown7fbdc842010-06-17 20:52:56 -0700626 entry->policyFlags = policyFlags;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700627 entry->repeatCount += 1;
628 } else {
Jeff Brownac386072011-07-20 15:19:50 -0700629 KeyEntry* newEntry = new KeyEntry(currentTime,
Jeff Brownc5ed5912010-07-14 18:48:53 -0700630 entry->deviceId, entry->source, policyFlags,
Jeff Brown7fbdc842010-06-17 20:52:56 -0700631 entry->action, entry->flags, entry->keyCode, entry->scanCode,
Jeff Brown00fa7bd2010-07-02 15:37:36 -0700632 entry->metaState, entry->repeatCount + 1, entry->downTime);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700633
634 mKeyRepeatState.lastKeyEntry = newEntry;
Jeff Brownac386072011-07-20 15:19:50 -0700635 entry->release();
Jeff Brown46b9ac02010-04-22 18:58:52 -0700636
637 entry = newEntry;
638 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700639 entry->syntheticRepeat = true;
640
641 // Increment reference count since we keep a reference to the event in
642 // mKeyRepeatState.lastKeyEntry in addition to the one we return.
643 entry->refCount += 1;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700644
Jeff Brown214eaf42011-05-26 19:17:02 -0700645 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Jeff Brownb88102f2010-09-08 11:49:43 -0700646 return entry;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700647}
648
Jeff Brownb88102f2010-09-08 11:49:43 -0700649bool InputDispatcher::dispatchConfigurationChangedLocked(
650 nsecs_t currentTime, ConfigurationChangedEntry* entry) {
Jeff Brown46b9ac02010-04-22 18:58:52 -0700651#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +0000652 ALOGD("dispatchConfigurationChanged - eventTime=%lld", entry->eventTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700653#endif
654
655 // Reset key repeating in case a keyboard device was added or removed or something.
656 resetKeyRepeatLocked();
657
658 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
659 CommandEntry* commandEntry = postCommandLocked(
660 & InputDispatcher::doNotifyConfigurationChangedInterruptible);
661 commandEntry->eventTime = entry->eventTime;
662 return true;
663}
664
Jeff Brown65fd2512011-08-18 11:20:58 -0700665bool InputDispatcher::dispatchDeviceResetLocked(
666 nsecs_t currentTime, DeviceResetEntry* entry) {
667#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +0000668 ALOGD("dispatchDeviceReset - eventTime=%lld, deviceId=%d", entry->eventTime, entry->deviceId);
Jeff Brown65fd2512011-08-18 11:20:58 -0700669#endif
670
671 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
672 "device was reset");
673 options.deviceId = entry->deviceId;
674 synthesizeCancelationEventsForAllConnectionsLocked(options);
675 return true;
676}
677
Jeff Brown214eaf42011-05-26 19:17:02 -0700678bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, KeyEntry* entry,
Jeff Browne20c9e02010-10-11 14:20:19 -0700679 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Jeff Browne46a0a42010-11-02 17:58:22 -0700680 // Preprocessing.
681 if (! entry->dispatchInProgress) {
682 if (entry->repeatCount == 0
683 && entry->action == AKEY_EVENT_ACTION_DOWN
684 && (entry->policyFlags & POLICY_FLAG_TRUSTED)
Jeff Brown0029c662011-03-30 02:25:18 -0700685 && (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
Jeff Browne46a0a42010-11-02 17:58:22 -0700686 if (mKeyRepeatState.lastKeyEntry
687 && mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode) {
688 // We have seen two identical key downs in a row which indicates that the device
689 // driver is automatically generating key repeats itself. We take note of the
690 // repeat here, but we disable our own next key repeat timer since it is clear that
691 // we will not need to synthesize key repeats ourselves.
692 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
693 resetKeyRepeatLocked();
694 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
695 } else {
696 // Not a repeat. Save key down state in case we do see a repeat later.
697 resetKeyRepeatLocked();
Jeff Brown214eaf42011-05-26 19:17:02 -0700698 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
Jeff Browne46a0a42010-11-02 17:58:22 -0700699 }
700 mKeyRepeatState.lastKeyEntry = entry;
701 entry->refCount += 1;
702 } else if (! entry->syntheticRepeat) {
703 resetKeyRepeatLocked();
704 }
705
Jeff Browne2e01262011-03-02 20:34:30 -0800706 if (entry->repeatCount == 1) {
707 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
708 } else {
709 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
710 }
711
Jeff Browne46a0a42010-11-02 17:58:22 -0700712 entry->dispatchInProgress = true;
Jeff Browne46a0a42010-11-02 17:58:22 -0700713
714 logOutboundKeyDetailsLocked("dispatchKey - ", entry);
715 }
716
Jeff Brown905805a2011-10-12 13:57:59 -0700717 // Handle case where the policy asked us to try again later last time.
718 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
719 if (currentTime < entry->interceptKeyWakeupTime) {
720 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
721 *nextWakeupTime = entry->interceptKeyWakeupTime;
722 }
723 return false; // wait until next wakeup
724 }
725 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
726 entry->interceptKeyWakeupTime = 0;
727 }
728
Jeff Brown54a18252010-09-16 14:07:33 -0700729 // Give the policy a chance to intercept the key.
730 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
Jeff Browne20c9e02010-10-11 14:20:19 -0700731 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Jeff Brown54a18252010-09-16 14:07:33 -0700732 CommandEntry* commandEntry = postCommandLocked(
733 & InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
Jeff Brown9302c872011-07-13 22:51:29 -0700734 if (mFocusedWindowHandle != NULL) {
735 commandEntry->inputWindowHandle = mFocusedWindowHandle;
Jeff Brown54a18252010-09-16 14:07:33 -0700736 }
737 commandEntry->keyEntry = entry;
738 entry->refCount += 1;
739 return false; // wait for the command to run
740 } else {
741 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
742 }
743 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Jeff Browne20c9e02010-10-11 14:20:19 -0700744 if (*dropReason == DROP_REASON_NOT_DROPPED) {
745 *dropReason = DROP_REASON_POLICY;
746 }
Jeff Brown54a18252010-09-16 14:07:33 -0700747 }
748
749 // Clean up if dropping the event.
Jeff Browne20c9e02010-10-11 14:20:19 -0700750 if (*dropReason != DROP_REASON_NOT_DROPPED) {
Jeff Brown3122e442010-10-11 23:32:49 -0700751 setInjectionResultLocked(entry, *dropReason == DROP_REASON_POLICY
752 ? INPUT_EVENT_INJECTION_SUCCEEDED : INPUT_EVENT_INJECTION_FAILED);
Jeff Brown54a18252010-09-16 14:07:33 -0700753 return true;
754 }
755
Jeff Brownb88102f2010-09-08 11:49:43 -0700756 // Identify targets.
Jeff Browne9bb9be2012-02-06 15:47:55 -0800757 Vector<InputTarget> inputTargets;
758 int32_t injectionResult = findFocusedWindowTargetsLocked(currentTime,
759 entry, inputTargets, nextWakeupTime);
760 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
761 return false;
Jeff Brownb88102f2010-09-08 11:49:43 -0700762 }
763
Jeff Browne9bb9be2012-02-06 15:47:55 -0800764 setInjectionResultLocked(entry, injectionResult);
765 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
766 return true;
767 }
768
769 addMonitoringTargetsLocked(inputTargets);
770
Jeff Brownb88102f2010-09-08 11:49:43 -0700771 // Dispatch the key.
Jeff Browne9bb9be2012-02-06 15:47:55 -0800772 dispatchEventLocked(currentTime, entry, inputTargets);
Jeff Brownb88102f2010-09-08 11:49:43 -0700773 return true;
774}
775
776void InputDispatcher::logOutboundKeyDetailsLocked(const char* prefix, const KeyEntry* entry) {
777#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +0000778 ALOGD("%seventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, "
Jeff Brownb88102f2010-09-08 11:49:43 -0700779 "action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, "
Jeff Browne46a0a42010-11-02 17:58:22 -0700780 "repeatCount=%d, downTime=%lld",
Jeff Brownb88102f2010-09-08 11:49:43 -0700781 prefix,
782 entry->eventTime, entry->deviceId, entry->source, entry->policyFlags,
783 entry->action, entry->flags, entry->keyCode, entry->scanCode, entry->metaState,
Jeff Browne46a0a42010-11-02 17:58:22 -0700784 entry->repeatCount, entry->downTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700785#endif
786}
787
788bool InputDispatcher::dispatchMotionLocked(
Jeff Browne20c9e02010-10-11 14:20:19 -0700789 nsecs_t currentTime, MotionEntry* entry, DropReason* dropReason, nsecs_t* nextWakeupTime) {
Jeff Browne46a0a42010-11-02 17:58:22 -0700790 // Preprocessing.
791 if (! entry->dispatchInProgress) {
792 entry->dispatchInProgress = true;
Jeff Browne46a0a42010-11-02 17:58:22 -0700793
794 logOutboundMotionDetailsLocked("dispatchMotion - ", entry);
795 }
796
Jeff Brown54a18252010-09-16 14:07:33 -0700797 // Clean up if dropping the event.
Jeff Browne20c9e02010-10-11 14:20:19 -0700798 if (*dropReason != DROP_REASON_NOT_DROPPED) {
Jeff Brown3122e442010-10-11 23:32:49 -0700799 setInjectionResultLocked(entry, *dropReason == DROP_REASON_POLICY
800 ? INPUT_EVENT_INJECTION_SUCCEEDED : INPUT_EVENT_INJECTION_FAILED);
Jeff Brown54a18252010-09-16 14:07:33 -0700801 return true;
802 }
803
Jeff Brownb88102f2010-09-08 11:49:43 -0700804 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
805
806 // Identify targets.
Jeff Browne9bb9be2012-02-06 15:47:55 -0800807 Vector<InputTarget> inputTargets;
808
Jeff Browncc0c1592011-02-19 05:07:28 -0800809 bool conflictingPointerActions = false;
Jeff Browne9bb9be2012-02-06 15:47:55 -0800810 int32_t injectionResult;
811 if (isPointerEvent) {
812 // Pointer event. (eg. touchscreen)
813 injectionResult = findTouchedWindowTargetsLocked(currentTime,
814 entry, inputTargets, nextWakeupTime, &conflictingPointerActions);
815 } else {
816 // Non touch event. (eg. trackball)
817 injectionResult = findFocusedWindowTargetsLocked(currentTime,
818 entry, inputTargets, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700819 }
Jeff Browne9bb9be2012-02-06 15:47:55 -0800820 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
821 return false;
822 }
823
824 setInjectionResultLocked(entry, injectionResult);
825 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
826 return true;
827 }
828
829 addMonitoringTargetsLocked(inputTargets);
Jeff Brownb88102f2010-09-08 11:49:43 -0700830
831 // Dispatch the motion.
Jeff Browncc0c1592011-02-19 05:07:28 -0800832 if (conflictingPointerActions) {
Jeff Brownda3d5a92011-03-29 15:11:34 -0700833 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
834 "conflicting pointer actions");
835 synthesizeCancelationEventsForAllConnectionsLocked(options);
Jeff Browncc0c1592011-02-19 05:07:28 -0800836 }
Jeff Browne9bb9be2012-02-06 15:47:55 -0800837 dispatchEventLocked(currentTime, entry, inputTargets);
Jeff Brownb88102f2010-09-08 11:49:43 -0700838 return true;
839}
840
841
842void InputDispatcher::logOutboundMotionDetailsLocked(const char* prefix, const MotionEntry* entry) {
843#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +0000844 ALOGD("%seventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, "
Jeff Brown85a31762010-09-01 17:01:00 -0700845 "action=0x%x, flags=0x%x, "
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700846 "metaState=0x%x, buttonState=0x%x, "
847 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%lld",
Jeff Brownb88102f2010-09-08 11:49:43 -0700848 prefix,
Jeff Brown85a31762010-09-01 17:01:00 -0700849 entry->eventTime, entry->deviceId, entry->source, entry->policyFlags,
850 entry->action, entry->flags,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700851 entry->metaState, entry->buttonState,
852 entry->edgeFlags, entry->xPrecision, entry->yPrecision,
Jeff Brown46b9ac02010-04-22 18:58:52 -0700853 entry->downTime);
854
Jeff Brown46b9ac02010-04-22 18:58:52 -0700855 for (uint32_t i = 0; i < entry->pointerCount; i++) {
Steve Block5baa3a62011-12-20 16:23:08 +0000856 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700857 "x=%f, y=%f, pressure=%f, size=%f, "
Jeff Brown85a31762010-09-01 17:01:00 -0700858 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
Jeff Brown8d608662010-08-30 03:02:23 -0700859 "orientation=%f",
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700860 i, entry->pointerProperties[i].id,
861 entry->pointerProperties[i].toolType,
Jeff Brown3241b6b2012-02-03 15:08:02 -0800862 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
863 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
864 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
865 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
866 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
867 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
868 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
869 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
870 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Jeff Brown46b9ac02010-04-22 18:58:52 -0700871 }
872#endif
Jeff Brown46b9ac02010-04-22 18:58:52 -0700873}
874
Jeff Browne9bb9be2012-02-06 15:47:55 -0800875void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
876 EventEntry* eventEntry, const Vector<InputTarget>& inputTargets) {
Jeff Brown46b9ac02010-04-22 18:58:52 -0700877#if DEBUG_DISPATCH_CYCLE
Jeff Brown3241b6b2012-02-03 15:08:02 -0800878 ALOGD("dispatchEventToCurrentInputTargets");
Jeff Brown46b9ac02010-04-22 18:58:52 -0700879#endif
880
Steve Blockec193de2012-01-09 18:35:44 +0000881 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
Jeff Brown9c3cda02010-06-15 01:31:58 -0700882
Jeff Browne2fe69e2010-10-18 13:21:23 -0700883 pokeUserActivityLocked(eventEntry);
884
Jeff Browne9bb9be2012-02-06 15:47:55 -0800885 for (size_t i = 0; i < inputTargets.size(); i++) {
886 const InputTarget& inputTarget = inputTargets.itemAt(i);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700887
Jeff Brown519e0242010-09-15 15:18:56 -0700888 ssize_t connectionIndex = getConnectionIndexLocked(inputTarget.inputChannel);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700889 if (connectionIndex >= 0) {
Jeff Browncbee6d62012-02-03 20:11:27 -0800890 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
Jeff Brown3241b6b2012-02-03 15:08:02 -0800891 prepareDispatchCycleLocked(currentTime, connection, eventEntry, &inputTarget);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700892 } else {
Jeff Brownb6997262010-10-08 22:31:17 -0700893#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +0000894 ALOGD("Dropping event delivery to target with channel '%s' because it "
Jeff Brownb6997262010-10-08 22:31:17 -0700895 "is no longer registered with the input dispatcher.",
Jeff Brown46b9ac02010-04-22 18:58:52 -0700896 inputTarget.inputChannel->getName().string());
Jeff Brownb6997262010-10-08 22:31:17 -0700897#endif
Jeff Brown46b9ac02010-04-22 18:58:52 -0700898 }
899 }
900}
901
Jeff Brownb88102f2010-09-08 11:49:43 -0700902int32_t InputDispatcher::handleTargetsNotReadyLocked(nsecs_t currentTime,
Jeff Brown9302c872011-07-13 22:51:29 -0700903 const EventEntry* entry,
904 const sp<InputApplicationHandle>& applicationHandle,
905 const sp<InputWindowHandle>& windowHandle,
Jeff Brown265f1cc2012-06-11 18:01:06 -0700906 nsecs_t* nextWakeupTime, const char* reason) {
Jeff Brown9302c872011-07-13 22:51:29 -0700907 if (applicationHandle == NULL && windowHandle == NULL) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700908 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY) {
909#if DEBUG_FOCUS
Jeff Brown265f1cc2012-06-11 18:01:06 -0700910 ALOGD("Waiting for system to become ready for input. Reason: %s", reason);
Jeff Brownb88102f2010-09-08 11:49:43 -0700911#endif
912 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY;
913 mInputTargetWaitStartTime = currentTime;
914 mInputTargetWaitTimeoutTime = LONG_LONG_MAX;
915 mInputTargetWaitTimeoutExpired = false;
Jeff Brown9302c872011-07-13 22:51:29 -0700916 mInputTargetWaitApplicationHandle.clear();
Jeff Brownb88102f2010-09-08 11:49:43 -0700917 }
918 } else {
919 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
920#if DEBUG_FOCUS
Jeff Brown265f1cc2012-06-11 18:01:06 -0700921 ALOGD("Waiting for application to become ready for input: %s. Reason: %s",
922 getApplicationWindowLabelLocked(applicationHandle, windowHandle).string(),
923 reason);
Jeff Brownb88102f2010-09-08 11:49:43 -0700924#endif
Jeff Browncc4f7db2011-08-30 20:34:48 -0700925 nsecs_t timeout;
926 if (windowHandle != NULL) {
927 timeout = windowHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
928 } else if (applicationHandle != NULL) {
929 timeout = applicationHandle->getDispatchingTimeout(
930 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
931 } else {
932 timeout = DEFAULT_INPUT_DISPATCHING_TIMEOUT;
933 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700934
935 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY;
936 mInputTargetWaitStartTime = currentTime;
937 mInputTargetWaitTimeoutTime = currentTime + timeout;
938 mInputTargetWaitTimeoutExpired = false;
Jeff Brown9302c872011-07-13 22:51:29 -0700939 mInputTargetWaitApplicationHandle.clear();
Jeff Brown928e0542011-01-10 11:17:36 -0800940
Jeff Brown9302c872011-07-13 22:51:29 -0700941 if (windowHandle != NULL) {
942 mInputTargetWaitApplicationHandle = windowHandle->inputApplicationHandle;
Jeff Brown928e0542011-01-10 11:17:36 -0800943 }
Jeff Brown9302c872011-07-13 22:51:29 -0700944 if (mInputTargetWaitApplicationHandle == NULL && applicationHandle != NULL) {
945 mInputTargetWaitApplicationHandle = applicationHandle;
Jeff Brown928e0542011-01-10 11:17:36 -0800946 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700947 }
948 }
949
950 if (mInputTargetWaitTimeoutExpired) {
951 return INPUT_EVENT_INJECTION_TIMED_OUT;
952 }
953
954 if (currentTime >= mInputTargetWaitTimeoutTime) {
Jeff Brown9302c872011-07-13 22:51:29 -0700955 onANRLocked(currentTime, applicationHandle, windowHandle,
Jeff Brown265f1cc2012-06-11 18:01:06 -0700956 entry->eventTime, mInputTargetWaitStartTime, reason);
Jeff Brownb88102f2010-09-08 11:49:43 -0700957
958 // Force poll loop to wake up immediately on next iteration once we get the
959 // ANR response back from the policy.
960 *nextWakeupTime = LONG_LONG_MIN;
961 return INPUT_EVENT_INJECTION_PENDING;
962 } else {
963 // Force poll loop to wake up when timeout is due.
964 if (mInputTargetWaitTimeoutTime < *nextWakeupTime) {
965 *nextWakeupTime = mInputTargetWaitTimeoutTime;
966 }
967 return INPUT_EVENT_INJECTION_PENDING;
968 }
969}
970
Jeff Brown519e0242010-09-15 15:18:56 -0700971void InputDispatcher::resumeAfterTargetsNotReadyTimeoutLocked(nsecs_t newTimeout,
972 const sp<InputChannel>& inputChannel) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700973 if (newTimeout > 0) {
974 // Extend the timeout.
975 mInputTargetWaitTimeoutTime = now() + newTimeout;
976 } else {
977 // Give up.
978 mInputTargetWaitTimeoutExpired = true;
Jeff Brown519e0242010-09-15 15:18:56 -0700979
980 // Input state will not be realistic. Mark it out of sync.
Jeff Browndc3e0052010-09-16 11:02:16 -0700981 if (inputChannel.get()) {
982 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
983 if (connectionIndex >= 0) {
Jeff Browncbee6d62012-02-03 20:11:27 -0800984 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
Jeff Brownf44e3942012-04-20 11:33:27 -0700985 sp<InputWindowHandle> windowHandle = connection->inputWindowHandle;
986
987 if (windowHandle != NULL) {
988 mTouchState.removeWindow(windowHandle);
989 }
990
Jeff Brown00045a72010-12-09 18:10:30 -0800991 if (connection->status == Connection::STATUS_NORMAL) {
Jeff Brownda3d5a92011-03-29 15:11:34 -0700992 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
Jeff Brown00045a72010-12-09 18:10:30 -0800993 "application not responding");
Jeff Brownda3d5a92011-03-29 15:11:34 -0700994 synthesizeCancelationEventsForConnectionLocked(connection, options);
Jeff Brown00045a72010-12-09 18:10:30 -0800995 }
Jeff Browndc3e0052010-09-16 11:02:16 -0700996 }
Jeff Brown519e0242010-09-15 15:18:56 -0700997 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700998 }
999}
1000
Jeff Brown519e0242010-09-15 15:18:56 -07001001nsecs_t InputDispatcher::getTimeSpentWaitingForApplicationLocked(
Jeff Brownb88102f2010-09-08 11:49:43 -07001002 nsecs_t currentTime) {
1003 if (mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
1004 return currentTime - mInputTargetWaitStartTime;
1005 }
1006 return 0;
1007}
1008
1009void InputDispatcher::resetANRTimeoutsLocked() {
1010#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001011 ALOGD("Resetting ANR timeouts.");
Jeff Brownb88102f2010-09-08 11:49:43 -07001012#endif
1013
Jeff Brownb88102f2010-09-08 11:49:43 -07001014 // Reset input target wait timeout.
1015 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_NONE;
Jeff Brown5ea29ab2011-07-27 11:50:51 -07001016 mInputTargetWaitApplicationHandle.clear();
Jeff Brownb88102f2010-09-08 11:49:43 -07001017}
1018
Jeff Brown01ce2e92010-09-26 22:20:12 -07001019int32_t InputDispatcher::findFocusedWindowTargetsLocked(nsecs_t currentTime,
Jeff Browne9bb9be2012-02-06 15:47:55 -08001020 const EventEntry* entry, Vector<InputTarget>& inputTargets, nsecs_t* nextWakeupTime) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001021 int32_t injectionResult;
1022
1023 // If there is no currently focused window and no focused application
1024 // then drop the event.
Jeff Brown9302c872011-07-13 22:51:29 -07001025 if (mFocusedWindowHandle == NULL) {
1026 if (mFocusedApplicationHandle != NULL) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001027 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brown265f1cc2012-06-11 18:01:06 -07001028 mFocusedApplicationHandle, NULL, nextWakeupTime,
1029 "Waiting because no window has focus but there is a "
1030 "focused application that may eventually add a window "
1031 "when it finishes starting up.");
Jeff Brownb88102f2010-09-08 11:49:43 -07001032 goto Unresponsive;
1033 }
1034
Steve Block6215d3f2012-01-04 20:05:49 +00001035 ALOGI("Dropping event because there is no focused window or focused application.");
Jeff Brownb88102f2010-09-08 11:49:43 -07001036 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1037 goto Failed;
1038 }
1039
1040 // Check permissions.
Jeff Brown9302c872011-07-13 22:51:29 -07001041 if (! checkInjectionPermission(mFocusedWindowHandle, entry->injectionState)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001042 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1043 goto Failed;
1044 }
1045
1046 // If the currently focused window is paused then keep waiting.
Jeff Browncc4f7db2011-08-30 20:34:48 -07001047 if (mFocusedWindowHandle->getInfo()->paused) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001048 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brown265f1cc2012-06-11 18:01:06 -07001049 mFocusedApplicationHandle, mFocusedWindowHandle, nextWakeupTime,
1050 "Waiting because the focused window is paused.");
Jeff Brownb88102f2010-09-08 11:49:43 -07001051 goto Unresponsive;
1052 }
1053
Jeff Brown519e0242010-09-15 15:18:56 -07001054 // If the currently focused window is still working on previous events then keep waiting.
Jeff Brown0952c302012-02-13 13:48:59 -08001055 if (!isWindowReadyForMoreInputLocked(currentTime, mFocusedWindowHandle, entry)) {
Jeff Brown519e0242010-09-15 15:18:56 -07001056 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brown265f1cc2012-06-11 18:01:06 -07001057 mFocusedApplicationHandle, mFocusedWindowHandle, nextWakeupTime,
1058 "Waiting because the focused window has not finished "
1059 "processing the input events that were previously delivered to it.");
Jeff Brown519e0242010-09-15 15:18:56 -07001060 goto Unresponsive;
1061 }
1062
Jeff Brownb88102f2010-09-08 11:49:43 -07001063 // Success! Output targets.
1064 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
Jeff Brown9302c872011-07-13 22:51:29 -07001065 addWindowTargetLocked(mFocusedWindowHandle,
Jeff Browne9bb9be2012-02-06 15:47:55 -08001066 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS, BitSet32(0),
1067 inputTargets);
Jeff Brownb88102f2010-09-08 11:49:43 -07001068
1069 // Done.
1070Failed:
1071Unresponsive:
Jeff Brown519e0242010-09-15 15:18:56 -07001072 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
1073 updateDispatchStatisticsLocked(currentTime, entry,
1074 injectionResult, timeSpentWaitingForApplication);
Jeff Brownb88102f2010-09-08 11:49:43 -07001075#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001076 ALOGD("findFocusedWindow finished: injectionResult=%d, "
Jeff Brown22aa5122012-06-17 12:01:06 -07001077 "timeSpentWaitingForApplication=%0.1fms",
Jeff Brown519e0242010-09-15 15:18:56 -07001078 injectionResult, timeSpentWaitingForApplication / 1000000.0);
Jeff Brownb88102f2010-09-08 11:49:43 -07001079#endif
1080 return injectionResult;
1081}
1082
Jeff Brown01ce2e92010-09-26 22:20:12 -07001083int32_t InputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime,
Jeff Browne9bb9be2012-02-06 15:47:55 -08001084 const MotionEntry* entry, Vector<InputTarget>& inputTargets, nsecs_t* nextWakeupTime,
1085 bool* outConflictingPointerActions) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001086 enum InjectionPermission {
1087 INJECTION_PERMISSION_UNKNOWN,
1088 INJECTION_PERMISSION_GRANTED,
1089 INJECTION_PERMISSION_DENIED
1090 };
1091
Jeff Brownb88102f2010-09-08 11:49:43 -07001092 nsecs_t startTime = now();
1093
1094 // For security reasons, we defer updating the touch state until we are sure that
1095 // event injection will be allowed.
1096 //
1097 // FIXME In the original code, screenWasOff could never be set to true.
1098 // The reason is that the POLICY_FLAG_WOKE_HERE
1099 // and POLICY_FLAG_BRIGHT_HERE flags were set only when preprocessing raw
1100 // EV_KEY, EV_REL and EV_ABS events. As it happens, the touch event was
1101 // actually enqueued using the policyFlags that appeared in the final EV_SYN
1102 // events upon which no preprocessing took place. So policyFlags was always 0.
1103 // In the new native input dispatcher we're a bit more careful about event
1104 // preprocessing so the touches we receive can actually have non-zero policyFlags.
1105 // Unfortunately we obtain undesirable behavior.
1106 //
1107 // Here's what happens:
1108 //
1109 // When the device dims in anticipation of going to sleep, touches
1110 // in windows which have FLAG_TOUCHABLE_WHEN_WAKING cause
1111 // the device to brighten and reset the user activity timer.
1112 // Touches on other windows (such as the launcher window)
1113 // are dropped. Then after a moment, the device goes to sleep. Oops.
1114 //
1115 // Also notice how screenWasOff was being initialized using POLICY_FLAG_BRIGHT_HERE
1116 // instead of POLICY_FLAG_WOKE_HERE...
1117 //
1118 bool screenWasOff = false; // original policy: policyFlags & POLICY_FLAG_BRIGHT_HERE;
1119
1120 int32_t action = entry->action;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001121 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Jeff Brownb88102f2010-09-08 11:49:43 -07001122
1123 // Update the touch state as needed based on the properties of the touch event.
Jeff Brown01ce2e92010-09-26 22:20:12 -07001124 int32_t injectionResult = INPUT_EVENT_INJECTION_PENDING;
1125 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
Jeff Brown9302c872011-07-13 22:51:29 -07001126 sp<InputWindowHandle> newHoverWindowHandle;
Jeff Browncc0c1592011-02-19 05:07:28 -08001127
1128 bool isSplit = mTouchState.split;
Jeff Brown2717eff2011-06-30 23:53:07 -07001129 bool switchedDevice = mTouchState.deviceId >= 0
1130 && (mTouchState.deviceId != entry->deviceId
1131 || mTouchState.source != entry->source);
Jeff Browna032cc02011-03-07 16:56:21 -08001132 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE
1133 || maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER
1134 || maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1135 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN
1136 || maskedAction == AMOTION_EVENT_ACTION_SCROLL
1137 || isHoverAction);
Jeff Brown81346812011-06-28 20:08:48 -07001138 bool wrongDevice = false;
Jeff Browna032cc02011-03-07 16:56:21 -08001139 if (newGesture) {
Jeff Browncc0c1592011-02-19 05:07:28 -08001140 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Jeff Brown81346812011-06-28 20:08:48 -07001141 if (switchedDevice && mTouchState.down && !down) {
1142#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001143 ALOGD("Dropping event because a pointer for a different device is already down.");
Jeff Brown81346812011-06-28 20:08:48 -07001144#endif
Jeff Browncc0c1592011-02-19 05:07:28 -08001145 mTempTouchState.copyFrom(mTouchState);
Jeff Brown81346812011-06-28 20:08:48 -07001146 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1147 switchedDevice = false;
1148 wrongDevice = true;
1149 goto Failed;
Jeff Browncc0c1592011-02-19 05:07:28 -08001150 }
Jeff Brown81346812011-06-28 20:08:48 -07001151 mTempTouchState.reset();
1152 mTempTouchState.down = down;
1153 mTempTouchState.deviceId = entry->deviceId;
1154 mTempTouchState.source = entry->source;
1155 isSplit = false;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001156 } else {
1157 mTempTouchState.copyFrom(mTouchState);
Jeff Browncc0c1592011-02-19 05:07:28 -08001158 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001159
Jeff Browna032cc02011-03-07 16:56:21 -08001160 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
Jeff Brown33bbfd22011-02-24 20:55:35 -08001161 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
Jeff Brownb88102f2010-09-08 11:49:43 -07001162
Jeff Brown01ce2e92010-09-26 22:20:12 -07001163 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Jeff Brown3241b6b2012-02-03 15:08:02 -08001164 int32_t x = int32_t(entry->pointerCoords[pointerIndex].
Jeff Brownebbd5d12011-02-17 13:01:34 -08001165 getAxisValue(AMOTION_EVENT_AXIS_X));
Jeff Brown3241b6b2012-02-03 15:08:02 -08001166 int32_t y = int32_t(entry->pointerCoords[pointerIndex].
Jeff Brownebbd5d12011-02-17 13:01:34 -08001167 getAxisValue(AMOTION_EVENT_AXIS_Y));
Jeff Brown9302c872011-07-13 22:51:29 -07001168 sp<InputWindowHandle> newTouchedWindowHandle;
1169 sp<InputWindowHandle> topErrorWindowHandle;
Jeff Browna032cc02011-03-07 16:56:21 -08001170 bool isTouchModal = false;
Jeff Brownb88102f2010-09-08 11:49:43 -07001171
1172 // Traverse windows from front to back to find touched window and outside targets.
Jeff Brown9302c872011-07-13 22:51:29 -07001173 size_t numWindows = mWindowHandles.size();
Jeff Brownb88102f2010-09-08 11:49:43 -07001174 for (size_t i = 0; i < numWindows; i++) {
Jeff Brown9302c872011-07-13 22:51:29 -07001175 sp<InputWindowHandle> windowHandle = mWindowHandles.itemAt(i);
Jeff Browncc4f7db2011-08-30 20:34:48 -07001176 const InputWindowInfo* windowInfo = windowHandle->getInfo();
1177 int32_t flags = windowInfo->layoutParamsFlags;
Jeff Brownb88102f2010-09-08 11:49:43 -07001178
Jeff Browncc4f7db2011-08-30 20:34:48 -07001179 if (flags & InputWindowInfo::FLAG_SYSTEM_ERROR) {
Jeff Brown9302c872011-07-13 22:51:29 -07001180 if (topErrorWindowHandle == NULL) {
1181 topErrorWindowHandle = windowHandle;
Jeff Brownb88102f2010-09-08 11:49:43 -07001182 }
1183 }
1184
Jeff Browncc4f7db2011-08-30 20:34:48 -07001185 if (windowInfo->visible) {
1186 if (! (flags & InputWindowInfo::FLAG_NOT_TOUCHABLE)) {
1187 isTouchModal = (flags & (InputWindowInfo::FLAG_NOT_FOCUSABLE
1188 | InputWindowInfo::FLAG_NOT_TOUCH_MODAL)) == 0;
1189 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
Jeff Brown9302c872011-07-13 22:51:29 -07001190 if (! screenWasOff
Jeff Browncc4f7db2011-08-30 20:34:48 -07001191 || (flags & InputWindowInfo::FLAG_TOUCHABLE_WHEN_WAKING)) {
Jeff Brown9302c872011-07-13 22:51:29 -07001192 newTouchedWindowHandle = windowHandle;
Jeff Brownb88102f2010-09-08 11:49:43 -07001193 }
1194 break; // found touched window, exit window loop
1195 }
1196 }
1197
Jeff Brown01ce2e92010-09-26 22:20:12 -07001198 if (maskedAction == AMOTION_EVENT_ACTION_DOWN
Jeff Browncc4f7db2011-08-30 20:34:48 -07001199 && (flags & InputWindowInfo::FLAG_WATCH_OUTSIDE_TOUCH)) {
Jeff Browna032cc02011-03-07 16:56:21 -08001200 int32_t outsideTargetFlags = InputTarget::FLAG_DISPATCH_AS_OUTSIDE;
Jeff Brown9302c872011-07-13 22:51:29 -07001201 if (isWindowObscuredAtPointLocked(windowHandle, x, y)) {
Jeff Brown19dfc832010-10-05 12:26:23 -07001202 outsideTargetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1203 }
1204
Jeff Brown9302c872011-07-13 22:51:29 -07001205 mTempTouchState.addOrUpdateWindow(
1206 windowHandle, outsideTargetFlags, BitSet32(0));
Jeff Brownb88102f2010-09-08 11:49:43 -07001207 }
1208 }
1209 }
1210
1211 // If there is an error window but it is not taking focus (typically because
1212 // it is invisible) then wait for it. Any other focused window may in
1213 // fact be in ANR state.
Jeff Brown9302c872011-07-13 22:51:29 -07001214 if (topErrorWindowHandle != NULL && newTouchedWindowHandle != topErrorWindowHandle) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001215 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brown265f1cc2012-06-11 18:01:06 -07001216 NULL, NULL, nextWakeupTime,
1217 "Waiting because a system error window is about to be displayed.");
Jeff Brownb88102f2010-09-08 11:49:43 -07001218 injectionPermission = INJECTION_PERMISSION_UNKNOWN;
1219 goto Unresponsive;
1220 }
1221
Jeff Brown01ce2e92010-09-26 22:20:12 -07001222 // Figure out whether splitting will be allowed for this window.
Jeff Browncc4f7db2011-08-30 20:34:48 -07001223 if (newTouchedWindowHandle != NULL
1224 && newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001225 // New window supports splitting.
1226 isSplit = true;
1227 } else if (isSplit) {
1228 // New window does not support splitting but we have already split events.
Jeff Brown8249fc62012-05-24 18:57:32 -07001229 // Ignore the new window.
1230 newTouchedWindowHandle = NULL;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001231 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001232
Jeff Brown8249fc62012-05-24 18:57:32 -07001233 // Handle the case where we did not find a window.
Jeff Brown9302c872011-07-13 22:51:29 -07001234 if (newTouchedWindowHandle == NULL) {
Jeff Brown8249fc62012-05-24 18:57:32 -07001235 // Try to assign the pointer to the first foreground window we find, if there is one.
1236 newTouchedWindowHandle = mTempTouchState.getFirstForegroundWindowHandle();
1237 if (newTouchedWindowHandle == NULL) {
1238 // There is no touched window. If this is an initial down event
1239 // then wait for a window to appear that will handle the touch. This is
1240 // to ensure that we report an ANR in the case where an application has started
1241 // but not yet put up a window and the user is starting to get impatient.
1242 if (maskedAction == AMOTION_EVENT_ACTION_DOWN
1243 && mFocusedApplicationHandle != NULL) {
Jeff Brown8249fc62012-05-24 18:57:32 -07001244 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brown265f1cc2012-06-11 18:01:06 -07001245 mFocusedApplicationHandle, NULL, nextWakeupTime,
1246 "Waiting because there is no touchable window that can "
1247 "handle the event but there is focused application that may "
1248 "eventually add a new window when it finishes starting up.");
Jeff Brown8249fc62012-05-24 18:57:32 -07001249 goto Unresponsive;
1250 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001251
Jeff Brown8249fc62012-05-24 18:57:32 -07001252 ALOGI("Dropping event because there is no touched window.");
1253 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1254 goto Failed;
1255 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001256 }
1257
Jeff Brown19dfc832010-10-05 12:26:23 -07001258 // Set target flags.
Jeff Browna032cc02011-03-07 16:56:21 -08001259 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
Jeff Brown19dfc832010-10-05 12:26:23 -07001260 if (isSplit) {
1261 targetFlags |= InputTarget::FLAG_SPLIT;
1262 }
Jeff Brown9302c872011-07-13 22:51:29 -07001263 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
Jeff Brown19dfc832010-10-05 12:26:23 -07001264 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1265 }
1266
Jeff Browna032cc02011-03-07 16:56:21 -08001267 // Update hover state.
1268 if (isHoverAction) {
Jeff Brown9302c872011-07-13 22:51:29 -07001269 newHoverWindowHandle = newTouchedWindowHandle;
Jeff Browna032cc02011-03-07 16:56:21 -08001270 } else if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
Jeff Brown9302c872011-07-13 22:51:29 -07001271 newHoverWindowHandle = mLastHoverWindowHandle;
Jeff Browna032cc02011-03-07 16:56:21 -08001272 }
1273
Jeff Brown01ce2e92010-09-26 22:20:12 -07001274 // Update the temporary touch state.
1275 BitSet32 pointerIds;
1276 if (isSplit) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07001277 uint32_t pointerId = entry->pointerProperties[pointerIndex].id;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001278 pointerIds.markBit(pointerId);
Jeff Brownb88102f2010-09-08 11:49:43 -07001279 }
Jeff Brown9302c872011-07-13 22:51:29 -07001280 mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Jeff Brownb88102f2010-09-08 11:49:43 -07001281 } else {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001282 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
Jeff Brownb88102f2010-09-08 11:49:43 -07001283
1284 // If the pointer is not currently down, then ignore the event.
Jeff Brown01ce2e92010-09-26 22:20:12 -07001285 if (! mTempTouchState.down) {
Jeff Browna2cc28d2011-03-25 11:58:46 -07001286#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001287 ALOGD("Dropping event because the pointer is not down or we previously "
Jeff Brown76860e32010-10-25 17:37:46 -07001288 "dropped the pointer down event.");
1289#endif
Jeff Brownb88102f2010-09-08 11:49:43 -07001290 injectionResult = INPUT_EVENT_INJECTION_FAILED;
Jeff Brownb88102f2010-09-08 11:49:43 -07001291 goto Failed;
1292 }
Jeff Brown98db5fa2011-06-08 15:37:10 -07001293
1294 // Check whether touches should slip outside of the current foreground window.
1295 if (maskedAction == AMOTION_EVENT_ACTION_MOVE
1296 && entry->pointerCount == 1
1297 && mTempTouchState.isSlippery()) {
Jeff Brown3241b6b2012-02-03 15:08:02 -08001298 int32_t x = int32_t(entry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
1299 int32_t y = int32_t(entry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Jeff Brown98db5fa2011-06-08 15:37:10 -07001300
Jeff Brown9302c872011-07-13 22:51:29 -07001301 sp<InputWindowHandle> oldTouchedWindowHandle =
1302 mTempTouchState.getFirstForegroundWindowHandle();
1303 sp<InputWindowHandle> newTouchedWindowHandle = findTouchedWindowAtLocked(x, y);
1304 if (oldTouchedWindowHandle != newTouchedWindowHandle
1305 && newTouchedWindowHandle != NULL) {
Jeff Brown98db5fa2011-06-08 15:37:10 -07001306#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001307 ALOGD("Touch is slipping out of window %s into window %s.",
Jeff Browncc4f7db2011-08-30 20:34:48 -07001308 oldTouchedWindowHandle->getName().string(),
1309 newTouchedWindowHandle->getName().string());
Jeff Brown98db5fa2011-06-08 15:37:10 -07001310#endif
1311 // Make a slippery exit from the old window.
Jeff Brown9302c872011-07-13 22:51:29 -07001312 mTempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
Jeff Brown98db5fa2011-06-08 15:37:10 -07001313 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT, BitSet32(0));
1314
1315 // Make a slippery entrance into the new window.
Jeff Browncc4f7db2011-08-30 20:34:48 -07001316 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Jeff Brown98db5fa2011-06-08 15:37:10 -07001317 isSplit = true;
1318 }
1319
1320 int32_t targetFlags = InputTarget::FLAG_FOREGROUND
1321 | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
1322 if (isSplit) {
1323 targetFlags |= InputTarget::FLAG_SPLIT;
1324 }
Jeff Brown9302c872011-07-13 22:51:29 -07001325 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
Jeff Brown98db5fa2011-06-08 15:37:10 -07001326 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1327 }
1328
1329 BitSet32 pointerIds;
1330 if (isSplit) {
1331 pointerIds.markBit(entry->pointerProperties[0].id);
1332 }
Jeff Brown9302c872011-07-13 22:51:29 -07001333 mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Jeff Brown98db5fa2011-06-08 15:37:10 -07001334 }
1335 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001336 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001337
Jeff Brown9302c872011-07-13 22:51:29 -07001338 if (newHoverWindowHandle != mLastHoverWindowHandle) {
Jeff Browna032cc02011-03-07 16:56:21 -08001339 // Let the previous window know that the hover sequence is over.
Jeff Brown9302c872011-07-13 22:51:29 -07001340 if (mLastHoverWindowHandle != NULL) {
Jeff Browna032cc02011-03-07 16:56:21 -08001341#if DEBUG_HOVER
Steve Block5baa3a62011-12-20 16:23:08 +00001342 ALOGD("Sending hover exit event to window %s.",
Jeff Browncc4f7db2011-08-30 20:34:48 -07001343 mLastHoverWindowHandle->getName().string());
Jeff Browna032cc02011-03-07 16:56:21 -08001344#endif
Jeff Brown9302c872011-07-13 22:51:29 -07001345 mTempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
Jeff Browna032cc02011-03-07 16:56:21 -08001346 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
1347 }
1348
1349 // Let the new window know that the hover sequence is starting.
Jeff Brown9302c872011-07-13 22:51:29 -07001350 if (newHoverWindowHandle != NULL) {
Jeff Browna032cc02011-03-07 16:56:21 -08001351#if DEBUG_HOVER
Steve Block5baa3a62011-12-20 16:23:08 +00001352 ALOGD("Sending hover enter event to window %s.",
Jeff Browncc4f7db2011-08-30 20:34:48 -07001353 newHoverWindowHandle->getName().string());
Jeff Browna032cc02011-03-07 16:56:21 -08001354#endif
Jeff Brown9302c872011-07-13 22:51:29 -07001355 mTempTouchState.addOrUpdateWindow(newHoverWindowHandle,
Jeff Browna032cc02011-03-07 16:56:21 -08001356 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER, BitSet32(0));
1357 }
1358 }
1359
Jeff Brown01ce2e92010-09-26 22:20:12 -07001360 // Check permission to inject into all touched foreground windows and ensure there
1361 // is at least one touched foreground window.
1362 {
1363 bool haveForegroundWindow = false;
1364 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1365 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1366 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1367 haveForegroundWindow = true;
Jeff Brown9302c872011-07-13 22:51:29 -07001368 if (! checkInjectionPermission(touchedWindow.windowHandle,
1369 entry->injectionState)) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001370 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1371 injectionPermission = INJECTION_PERMISSION_DENIED;
1372 goto Failed;
1373 }
1374 }
1375 }
1376 if (! haveForegroundWindow) {
Jeff Browna2cc28d2011-03-25 11:58:46 -07001377#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001378 ALOGD("Dropping event because there is no touched foreground window to receive it.");
Jeff Brownb88102f2010-09-08 11:49:43 -07001379#endif
1380 injectionResult = INPUT_EVENT_INJECTION_FAILED;
Jeff Brownb88102f2010-09-08 11:49:43 -07001381 goto Failed;
1382 }
1383
Jeff Brown01ce2e92010-09-26 22:20:12 -07001384 // Permission granted to injection into all touched foreground windows.
1385 injectionPermission = INJECTION_PERMISSION_GRANTED;
1386 }
Jeff Brown519e0242010-09-15 15:18:56 -07001387
Kenny Root7a9db182011-06-02 15:16:05 -07001388 // Check whether windows listening for outside touches are owned by the same UID. If it is
1389 // set the policy flag that we will not reveal coordinate information to this window.
1390 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
Jeff Brown9302c872011-07-13 22:51:29 -07001391 sp<InputWindowHandle> foregroundWindowHandle =
1392 mTempTouchState.getFirstForegroundWindowHandle();
Jeff Browncc4f7db2011-08-30 20:34:48 -07001393 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Kenny Root7a9db182011-06-02 15:16:05 -07001394 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1395 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1396 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
Jeff Brown9302c872011-07-13 22:51:29 -07001397 sp<InputWindowHandle> inputWindowHandle = touchedWindow.windowHandle;
Jeff Browncc4f7db2011-08-30 20:34:48 -07001398 if (inputWindowHandle->getInfo()->ownerUid != foregroundWindowUid) {
Jeff Brown9302c872011-07-13 22:51:29 -07001399 mTempTouchState.addOrUpdateWindow(inputWindowHandle,
Kenny Root7a9db182011-06-02 15:16:05 -07001400 InputTarget::FLAG_ZERO_COORDS, BitSet32(0));
1401 }
1402 }
1403 }
1404 }
1405
Jeff Brown01ce2e92010-09-26 22:20:12 -07001406 // Ensure all touched foreground windows are ready for new input.
1407 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1408 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1409 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1410 // If the touched window is paused then keep waiting.
Jeff Browncc4f7db2011-08-30 20:34:48 -07001411 if (touchedWindow.windowHandle->getInfo()->paused) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001412 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brown265f1cc2012-06-11 18:01:06 -07001413 NULL, touchedWindow.windowHandle, nextWakeupTime,
1414 "Waiting because the touched window is paused.");
Jeff Brown01ce2e92010-09-26 22:20:12 -07001415 goto Unresponsive;
1416 }
1417
1418 // If the touched window is still working on previous events then keep waiting.
Jeff Brown0952c302012-02-13 13:48:59 -08001419 if (!isWindowReadyForMoreInputLocked(currentTime, touchedWindow.windowHandle, entry)) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001420 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brown265f1cc2012-06-11 18:01:06 -07001421 NULL, touchedWindow.windowHandle, nextWakeupTime,
1422 "Waiting because the touched window has not finished "
1423 "processing the input events that were previously delivered to it.");
Jeff Brown01ce2e92010-09-26 22:20:12 -07001424 goto Unresponsive;
1425 }
1426 }
1427 }
1428
1429 // If this is the first pointer going down and the touched window has a wallpaper
1430 // then also add the touched wallpaper windows so they are locked in for the duration
1431 // of the touch gesture.
Jeff Brown33bbfd22011-02-24 20:55:35 -08001432 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
1433 // engine only supports touch events. We would need to add a mechanism similar
1434 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
1435 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
Jeff Brown9302c872011-07-13 22:51:29 -07001436 sp<InputWindowHandle> foregroundWindowHandle =
1437 mTempTouchState.getFirstForegroundWindowHandle();
Jeff Browncc4f7db2011-08-30 20:34:48 -07001438 if (foregroundWindowHandle->getInfo()->hasWallpaper) {
Jeff Brown9302c872011-07-13 22:51:29 -07001439 for (size_t i = 0; i < mWindowHandles.size(); i++) {
1440 sp<InputWindowHandle> windowHandle = mWindowHandles.itemAt(i);
Jeff Browncc4f7db2011-08-30 20:34:48 -07001441 if (windowHandle->getInfo()->layoutParamsType
1442 == InputWindowInfo::TYPE_WALLPAPER) {
Jeff Brown9302c872011-07-13 22:51:29 -07001443 mTempTouchState.addOrUpdateWindow(windowHandle,
Jeff Browna032cc02011-03-07 16:56:21 -08001444 InputTarget::FLAG_WINDOW_IS_OBSCURED
1445 | InputTarget::FLAG_DISPATCH_AS_IS,
1446 BitSet32(0));
Jeff Brown01ce2e92010-09-26 22:20:12 -07001447 }
1448 }
1449 }
1450 }
1451
Jeff Brownb88102f2010-09-08 11:49:43 -07001452 // Success! Output targets.
1453 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
Jeff Brownb88102f2010-09-08 11:49:43 -07001454
Jeff Brown01ce2e92010-09-26 22:20:12 -07001455 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1456 const TouchedWindow& touchedWindow = mTempTouchState.windows.itemAt(i);
Jeff Brown9302c872011-07-13 22:51:29 -07001457 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Jeff Browne9bb9be2012-02-06 15:47:55 -08001458 touchedWindow.pointerIds, inputTargets);
Jeff Brownb88102f2010-09-08 11:49:43 -07001459 }
1460
Jeff Browna032cc02011-03-07 16:56:21 -08001461 // Drop the outside or hover touch windows since we will not care about them
1462 // in the next iteration.
1463 mTempTouchState.filterNonAsIsTouchWindows();
Jeff Brown01ce2e92010-09-26 22:20:12 -07001464
Jeff Brownb88102f2010-09-08 11:49:43 -07001465Failed:
1466 // Check injection permission once and for all.
1467 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001468 if (checkInjectionPermission(NULL, entry->injectionState)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001469 injectionPermission = INJECTION_PERMISSION_GRANTED;
1470 } else {
1471 injectionPermission = INJECTION_PERMISSION_DENIED;
1472 }
1473 }
1474
1475 // Update final pieces of touch state if the injector had permission.
1476 if (injectionPermission == INJECTION_PERMISSION_GRANTED) {
Jeff Brown95712852011-01-04 19:41:59 -08001477 if (!wrongDevice) {
Jeff Brown81346812011-06-28 20:08:48 -07001478 if (switchedDevice) {
1479#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001480 ALOGD("Conflicting pointer actions: Switched to a different device.");
Jeff Brown81346812011-06-28 20:08:48 -07001481#endif
1482 *outConflictingPointerActions = true;
1483 }
1484
1485 if (isHoverAction) {
1486 // Started hovering, therefore no longer down.
1487 if (mTouchState.down) {
1488#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001489 ALOGD("Conflicting pointer actions: Hover received while pointer was down.");
Jeff Brown81346812011-06-28 20:08:48 -07001490#endif
1491 *outConflictingPointerActions = true;
1492 }
1493 mTouchState.reset();
1494 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER
1495 || maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
1496 mTouchState.deviceId = entry->deviceId;
1497 mTouchState.source = entry->source;
1498 }
1499 } else if (maskedAction == AMOTION_EVENT_ACTION_UP
1500 || maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Jeff Brown95712852011-01-04 19:41:59 -08001501 // All pointers up or canceled.
Jeff Brown33bbfd22011-02-24 20:55:35 -08001502 mTouchState.reset();
Jeff Brown95712852011-01-04 19:41:59 -08001503 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1504 // First pointer went down.
1505 if (mTouchState.down) {
Jeff Brownb6997262010-10-08 22:31:17 -07001506#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001507 ALOGD("Conflicting pointer actions: Down received while already down.");
Jeff Brownb6997262010-10-08 22:31:17 -07001508#endif
Jeff Brown81346812011-06-28 20:08:48 -07001509 *outConflictingPointerActions = true;
Jeff Brown95712852011-01-04 19:41:59 -08001510 }
Jeff Brown33bbfd22011-02-24 20:55:35 -08001511 mTouchState.copyFrom(mTempTouchState);
Jeff Brown95712852011-01-04 19:41:59 -08001512 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
1513 // One pointer went up.
1514 if (isSplit) {
1515 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07001516 uint32_t pointerId = entry->pointerProperties[pointerIndex].id;
Jeff Brownb88102f2010-09-08 11:49:43 -07001517
Jeff Brown95712852011-01-04 19:41:59 -08001518 for (size_t i = 0; i < mTempTouchState.windows.size(); ) {
1519 TouchedWindow& touchedWindow = mTempTouchState.windows.editItemAt(i);
1520 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
1521 touchedWindow.pointerIds.clearBit(pointerId);
1522 if (touchedWindow.pointerIds.isEmpty()) {
1523 mTempTouchState.windows.removeAt(i);
1524 continue;
1525 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001526 }
Jeff Brown95712852011-01-04 19:41:59 -08001527 i += 1;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001528 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001529 }
Jeff Brown33bbfd22011-02-24 20:55:35 -08001530 mTouchState.copyFrom(mTempTouchState);
1531 } else if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
1532 // Discard temporary touch state since it was only valid for this action.
1533 } else {
1534 // Save changes to touch state as-is for all other actions.
1535 mTouchState.copyFrom(mTempTouchState);
Jeff Brownb88102f2010-09-08 11:49:43 -07001536 }
Jeff Browna032cc02011-03-07 16:56:21 -08001537
1538 // Update hover state.
Jeff Brown9302c872011-07-13 22:51:29 -07001539 mLastHoverWindowHandle = newHoverWindowHandle;
Jeff Brown95712852011-01-04 19:41:59 -08001540 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001541 } else {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001542#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001543 ALOGD("Not updating touch focus because injection was denied.");
Jeff Brown01ce2e92010-09-26 22:20:12 -07001544#endif
Jeff Brownb88102f2010-09-08 11:49:43 -07001545 }
1546
1547Unresponsive:
Jeff Brown120a4592010-10-27 18:43:51 -07001548 // Reset temporary touch state to ensure we release unnecessary references to input channels.
1549 mTempTouchState.reset();
1550
Jeff Brown519e0242010-09-15 15:18:56 -07001551 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
1552 updateDispatchStatisticsLocked(currentTime, entry,
1553 injectionResult, timeSpentWaitingForApplication);
Jeff Brownb88102f2010-09-08 11:49:43 -07001554#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001555 ALOGD("findTouchedWindow finished: injectionResult=%d, injectionPermission=%d, "
Jeff Brown01ce2e92010-09-26 22:20:12 -07001556 "timeSpentWaitingForApplication=%0.1fms",
Jeff Brown519e0242010-09-15 15:18:56 -07001557 injectionResult, injectionPermission, timeSpentWaitingForApplication / 1000000.0);
Jeff Brownb88102f2010-09-08 11:49:43 -07001558#endif
1559 return injectionResult;
1560}
1561
Jeff Brown9302c872011-07-13 22:51:29 -07001562void InputDispatcher::addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
Jeff Browne9bb9be2012-02-06 15:47:55 -08001563 int32_t targetFlags, BitSet32 pointerIds, Vector<InputTarget>& inputTargets) {
1564 inputTargets.push();
Jeff Brownb88102f2010-09-08 11:49:43 -07001565
Jeff Browncc4f7db2011-08-30 20:34:48 -07001566 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Jeff Browne9bb9be2012-02-06 15:47:55 -08001567 InputTarget& target = inputTargets.editTop();
Jeff Browncc4f7db2011-08-30 20:34:48 -07001568 target.inputChannel = windowInfo->inputChannel;
Jeff Brownb88102f2010-09-08 11:49:43 -07001569 target.flags = targetFlags;
Jeff Browncc4f7db2011-08-30 20:34:48 -07001570 target.xOffset = - windowInfo->frameLeft;
1571 target.yOffset = - windowInfo->frameTop;
1572 target.scaleFactor = windowInfo->scaleFactor;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001573 target.pointerIds = pointerIds;
Jeff Brownb88102f2010-09-08 11:49:43 -07001574}
1575
Jeff Browne9bb9be2012-02-06 15:47:55 -08001576void InputDispatcher::addMonitoringTargetsLocked(Vector<InputTarget>& inputTargets) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001577 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
Jeff Browne9bb9be2012-02-06 15:47:55 -08001578 inputTargets.push();
Jeff Brownb88102f2010-09-08 11:49:43 -07001579
Jeff Browne9bb9be2012-02-06 15:47:55 -08001580 InputTarget& target = inputTargets.editTop();
Jeff Brownb88102f2010-09-08 11:49:43 -07001581 target.inputChannel = mMonitoringChannels[i];
Jeff Brownb6110c22011-04-01 16:15:13 -07001582 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
Jeff Brownb88102f2010-09-08 11:49:43 -07001583 target.xOffset = 0;
1584 target.yOffset = 0;
Jeff Brownb6110c22011-04-01 16:15:13 -07001585 target.pointerIds.clear();
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001586 target.scaleFactor = 1.0f;
Jeff Brownb88102f2010-09-08 11:49:43 -07001587 }
1588}
1589
Jeff Brown9302c872011-07-13 22:51:29 -07001590bool InputDispatcher::checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
Jeff Brown01ce2e92010-09-26 22:20:12 -07001591 const InjectionState* injectionState) {
1592 if (injectionState
Jeff Browncc4f7db2011-08-30 20:34:48 -07001593 && (windowHandle == NULL
1594 || windowHandle->getInfo()->ownerUid != injectionState->injectorUid)
Jeff Brownb6997262010-10-08 22:31:17 -07001595 && !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Jeff Brown9302c872011-07-13 22:51:29 -07001596 if (windowHandle != NULL) {
Steve Block8564c8d2012-01-05 23:22:43 +00001597 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
Jeff Brown9302c872011-07-13 22:51:29 -07001598 "owned by uid %d",
Jeff Brownb6997262010-10-08 22:31:17 -07001599 injectionState->injectorPid, injectionState->injectorUid,
Jeff Browncc4f7db2011-08-30 20:34:48 -07001600 windowHandle->getName().string(),
1601 windowHandle->getInfo()->ownerUid);
Jeff Brownb6997262010-10-08 22:31:17 -07001602 } else {
Steve Block8564c8d2012-01-05 23:22:43 +00001603 ALOGW("Permission denied: injecting event from pid %d uid %d",
Jeff Brownb6997262010-10-08 22:31:17 -07001604 injectionState->injectorPid, injectionState->injectorUid);
Jeff Brownb88102f2010-09-08 11:49:43 -07001605 }
Jeff Brownb6997262010-10-08 22:31:17 -07001606 return false;
Jeff Brownb88102f2010-09-08 11:49:43 -07001607 }
1608 return true;
1609}
1610
Jeff Brown19dfc832010-10-05 12:26:23 -07001611bool InputDispatcher::isWindowObscuredAtPointLocked(
Jeff Brown9302c872011-07-13 22:51:29 -07001612 const sp<InputWindowHandle>& windowHandle, int32_t x, int32_t y) const {
1613 size_t numWindows = mWindowHandles.size();
Jeff Brownb88102f2010-09-08 11:49:43 -07001614 for (size_t i = 0; i < numWindows; i++) {
Jeff Brown9302c872011-07-13 22:51:29 -07001615 sp<InputWindowHandle> otherHandle = mWindowHandles.itemAt(i);
1616 if (otherHandle == windowHandle) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001617 break;
1618 }
Jeff Browncc4f7db2011-08-30 20:34:48 -07001619
1620 const InputWindowInfo* otherInfo = otherHandle->getInfo();
1621 if (otherInfo->visible && ! otherInfo->isTrustedOverlay()
1622 && otherInfo->frameContainsPoint(x, y)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001623 return true;
1624 }
1625 }
1626 return false;
1627}
1628
Jeff Brownd1c48a02012-02-06 19:12:47 -08001629bool InputDispatcher::isWindowReadyForMoreInputLocked(nsecs_t currentTime,
Jeff Brown0952c302012-02-13 13:48:59 -08001630 const sp<InputWindowHandle>& windowHandle, const EventEntry* eventEntry) {
Jeff Browncc4f7db2011-08-30 20:34:48 -07001631 ssize_t connectionIndex = getConnectionIndexLocked(windowHandle->getInputChannel());
Jeff Brown519e0242010-09-15 15:18:56 -07001632 if (connectionIndex >= 0) {
Jeff Browncbee6d62012-02-03 20:11:27 -08001633 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
Jeff Brownd1c48a02012-02-06 19:12:47 -08001634 if (connection->inputPublisherBlocked) {
1635 return false;
1636 }
Jeff Brown0952c302012-02-13 13:48:59 -08001637 if (eventEntry->type == EventEntry::TYPE_KEY) {
1638 // If the event is a key event, then we must wait for all previous events to
1639 // complete before delivering it because previous events may have the
1640 // side-effect of transferring focus to a different window and we want to
1641 // ensure that the following keys are sent to the new window.
1642 //
1643 // Suppose the user touches a button in a window then immediately presses "A".
1644 // If the button causes a pop-up window to appear then we want to ensure that
1645 // the "A" key is delivered to the new pop-up window. This is because users
1646 // often anticipate pending UI changes when typing on a keyboard.
1647 // To obtain this behavior, we must serialize key events with respect to all
1648 // prior input events.
Jeff Brownd1c48a02012-02-06 19:12:47 -08001649 return connection->outboundQueue.isEmpty()
1650 && connection->waitQueue.isEmpty();
1651 }
Jeff Brown0952c302012-02-13 13:48:59 -08001652 // Touch events can always be sent to a window immediately because the user intended
1653 // to touch whatever was visible at the time. Even if focus changes or a new
1654 // window appears moments later, the touch event was meant to be delivered to
1655 // whatever window happened to be on screen at the time.
1656 //
1657 // Generic motion events, such as trackball or joystick events are a little trickier.
1658 // Like key events, generic motion events are delivered to the focused window.
1659 // Unlike key events, generic motion events don't tend to transfer focus to other
1660 // windows and it is not important for them to be serialized. So we prefer to deliver
1661 // generic motion events as soon as possible to improve efficiency and reduce lag
1662 // through batching.
1663 //
1664 // The one case where we pause input event delivery is when the wait queue is piling
1665 // up with lots of events because the application is not responding.
1666 // This condition ensures that ANRs are detected reliably.
Jeff Brownd1c48a02012-02-06 19:12:47 -08001667 if (!connection->waitQueue.isEmpty()
1668 && currentTime >= connection->waitQueue.head->eventEntry->eventTime
1669 + STREAM_AHEAD_EVENT_TIMEOUT) {
1670 return false;
1671 }
Jeff Brown519e0242010-09-15 15:18:56 -07001672 }
Jeff Brownd1c48a02012-02-06 19:12:47 -08001673 return true;
Jeff Brown519e0242010-09-15 15:18:56 -07001674}
1675
Jeff Brown9302c872011-07-13 22:51:29 -07001676String8 InputDispatcher::getApplicationWindowLabelLocked(
1677 const sp<InputApplicationHandle>& applicationHandle,
1678 const sp<InputWindowHandle>& windowHandle) {
1679 if (applicationHandle != NULL) {
1680 if (windowHandle != NULL) {
Jeff Browncc4f7db2011-08-30 20:34:48 -07001681 String8 label(applicationHandle->getName());
Jeff Brown519e0242010-09-15 15:18:56 -07001682 label.append(" - ");
Jeff Browncc4f7db2011-08-30 20:34:48 -07001683 label.append(windowHandle->getName());
Jeff Brown519e0242010-09-15 15:18:56 -07001684 return label;
1685 } else {
Jeff Browncc4f7db2011-08-30 20:34:48 -07001686 return applicationHandle->getName();
Jeff Brown519e0242010-09-15 15:18:56 -07001687 }
Jeff Brown9302c872011-07-13 22:51:29 -07001688 } else if (windowHandle != NULL) {
Jeff Browncc4f7db2011-08-30 20:34:48 -07001689 return windowHandle->getName();
Jeff Brown519e0242010-09-15 15:18:56 -07001690 } else {
1691 return String8("<unknown application or window>");
1692 }
1693}
1694
Jeff Browne2fe69e2010-10-18 13:21:23 -07001695void InputDispatcher::pokeUserActivityLocked(const EventEntry* eventEntry) {
Jeff Brown56194eb2011-03-02 19:23:13 -08001696 int32_t eventType = POWER_MANAGER_OTHER_EVENT;
Jeff Brown4d396052010-10-29 21:50:21 -07001697 switch (eventEntry->type) {
1698 case EventEntry::TYPE_MOTION: {
Jeff Browne2fe69e2010-10-18 13:21:23 -07001699 const MotionEntry* motionEntry = static_cast<const MotionEntry*>(eventEntry);
Jeff Brown4d396052010-10-29 21:50:21 -07001700 if (motionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
1701 return;
1702 }
1703
Jeff Brown56194eb2011-03-02 19:23:13 -08001704 if (MotionEvent::isTouchEvent(motionEntry->source, motionEntry->action)) {
Joe Onorato1a542c72010-11-08 09:48:20 -08001705 eventType = POWER_MANAGER_TOUCH_EVENT;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001706 }
Jeff Brown4d396052010-10-29 21:50:21 -07001707 break;
1708 }
1709 case EventEntry::TYPE_KEY: {
1710 const KeyEntry* keyEntry = static_cast<const KeyEntry*>(eventEntry);
1711 if (keyEntry->flags & AKEY_EVENT_FLAG_CANCELED) {
1712 return;
1713 }
Jeff Brown56194eb2011-03-02 19:23:13 -08001714 eventType = POWER_MANAGER_BUTTON_EVENT;
Jeff Brown4d396052010-10-29 21:50:21 -07001715 break;
1716 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001717 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001718
Jeff Brownb88102f2010-09-08 11:49:43 -07001719 CommandEntry* commandEntry = postCommandLocked(
1720 & InputDispatcher::doPokeUserActivityLockedInterruptible);
Jeff Browne2fe69e2010-10-18 13:21:23 -07001721 commandEntry->eventTime = eventEntry->eventTime;
Jeff Brownb88102f2010-09-08 11:49:43 -07001722 commandEntry->userActivityEventType = eventType;
1723}
1724
Jeff Brown7fbdc842010-06-17 20:52:56 -07001725void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001726 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07001727#if DEBUG_DISPATCH_CYCLE
Steve Block5baa3a62011-12-20 16:23:08 +00001728 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
Jeff Brown9cc695c2011-08-23 18:35:04 -07001729 "xOffset=%f, yOffset=%f, scaleFactor=%f, "
Jeff Brown3241b6b2012-02-03 15:08:02 -08001730 "pointerIds=0x%x",
Jeff Brown519e0242010-09-15 15:18:56 -07001731 connection->getInputChannelName(), inputTarget->flags,
Jeff Brown46b9ac02010-04-22 18:58:52 -07001732 inputTarget->xOffset, inputTarget->yOffset,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001733 inputTarget->scaleFactor, inputTarget->pointerIds.value);
Jeff Brown46b9ac02010-04-22 18:58:52 -07001734#endif
1735
1736 // Skip this event if the connection status is not normal.
Jeff Brown519e0242010-09-15 15:18:56 -07001737 // We don't want to enqueue additional outbound events if the connection is broken.
Jeff Brown46b9ac02010-04-22 18:58:52 -07001738 if (connection->status != Connection::STATUS_NORMAL) {
Jeff Brownb6997262010-10-08 22:31:17 -07001739#if DEBUG_DISPATCH_CYCLE
Steve Block5baa3a62011-12-20 16:23:08 +00001740 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Jeff Brownb88102f2010-09-08 11:49:43 -07001741 connection->getInputChannelName(), connection->getStatusLabel());
Jeff Brownb6997262010-10-08 22:31:17 -07001742#endif
Jeff Brown46b9ac02010-04-22 18:58:52 -07001743 return;
1744 }
1745
Jeff Brown01ce2e92010-09-26 22:20:12 -07001746 // Split a motion event if needed.
Jeff Brown3241b6b2012-02-03 15:08:02 -08001747 if (inputTarget->flags & InputTarget::FLAG_SPLIT) {
Steve Blockec193de2012-01-09 18:35:44 +00001748 ALOG_ASSERT(eventEntry->type == EventEntry::TYPE_MOTION);
Jeff Brown01ce2e92010-09-26 22:20:12 -07001749
1750 MotionEntry* originalMotionEntry = static_cast<MotionEntry*>(eventEntry);
1751 if (inputTarget->pointerIds.count() != originalMotionEntry->pointerCount) {
1752 MotionEntry* splitMotionEntry = splitMotionEvent(
1753 originalMotionEntry, inputTarget->pointerIds);
Jeff Brown58a2da82011-01-25 16:02:22 -08001754 if (!splitMotionEntry) {
1755 return; // split event was dropped
1756 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001757#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001758 ALOGD("channel '%s' ~ Split motion event.",
Jeff Brown01ce2e92010-09-26 22:20:12 -07001759 connection->getInputChannelName());
1760 logOutboundMotionDetailsLocked(" ", splitMotionEntry);
1761#endif
Jeff Brownc0cb3dc2012-01-12 18:30:12 -08001762 enqueueDispatchEntriesLocked(currentTime, connection,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001763 splitMotionEntry, inputTarget);
Jeff Brownc0cb3dc2012-01-12 18:30:12 -08001764 splitMotionEntry->release();
1765 return;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001766 }
1767 }
1768
Jeff Brownc0cb3dc2012-01-12 18:30:12 -08001769 // Not splitting. Enqueue dispatch entries for the event as is.
Jeff Brown3241b6b2012-02-03 15:08:02 -08001770 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
Jeff Brownc0cb3dc2012-01-12 18:30:12 -08001771}
1772
1773void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001774 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07001775 bool wasEmpty = connection->outboundQueue.isEmpty();
1776
Jeff Browna032cc02011-03-07 16:56:21 -08001777 // Enqueue dispatch entries for the requested modes.
1778 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001779 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
Jeff Browna032cc02011-03-07 16:56:21 -08001780 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001781 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
Jeff Browna032cc02011-03-07 16:56:21 -08001782 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001783 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
Jeff Browna032cc02011-03-07 16:56:21 -08001784 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001785 InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brown98db5fa2011-06-08 15:37:10 -07001786 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001787 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
Jeff Brown98db5fa2011-06-08 15:37:10 -07001788 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001789 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Jeff Browna032cc02011-03-07 16:56:21 -08001790
1791 // If the outbound queue was previously empty, start the dispatch cycle going.
Jeff Brownb6110c22011-04-01 16:15:13 -07001792 if (wasEmpty && !connection->outboundQueue.isEmpty()) {
Jeff Browna032cc02011-03-07 16:56:21 -08001793 startDispatchCycleLocked(currentTime, connection);
1794 }
1795}
1796
1797void InputDispatcher::enqueueDispatchEntryLocked(
1798 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001799 int32_t dispatchMode) {
Jeff Browna032cc02011-03-07 16:56:21 -08001800 int32_t inputTargetFlags = inputTarget->flags;
1801 if (!(inputTargetFlags & dispatchMode)) {
1802 return;
1803 }
1804 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
1805
Jeff Brown46b9ac02010-04-22 18:58:52 -07001806 // This is a new event.
1807 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Jeff Brownac386072011-07-20 15:19:50 -07001808 DispatchEntry* dispatchEntry = new DispatchEntry(eventEntry, // increments ref
Dianne Hackbornaa9d84c2011-05-09 19:00:59 -07001809 inputTargetFlags, inputTarget->xOffset, inputTarget->yOffset,
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001810 inputTarget->scaleFactor);
Jeff Brown6ec402b2010-07-28 15:48:59 -07001811
Jeff Brown81346812011-06-28 20:08:48 -07001812 // Apply target flags and update the connection's input state.
1813 switch (eventEntry->type) {
1814 case EventEntry::TYPE_KEY: {
1815 KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
1816 dispatchEntry->resolvedAction = keyEntry->action;
1817 dispatchEntry->resolvedFlags = keyEntry->flags;
1818
1819 if (!connection->inputState.trackKey(keyEntry,
1820 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags)) {
1821#if DEBUG_DISPATCH_CYCLE
Steve Block5baa3a62011-12-20 16:23:08 +00001822 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
Jeff Brown81346812011-06-28 20:08:48 -07001823 connection->getInputChannelName());
1824#endif
Jeff Brownc0cb3dc2012-01-12 18:30:12 -08001825 delete dispatchEntry;
Jeff Brown81346812011-06-28 20:08:48 -07001826 return; // skip the inconsistent event
1827 }
1828 break;
1829 }
1830
1831 case EventEntry::TYPE_MOTION: {
1832 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
1833 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
1834 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
1835 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
1836 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
1837 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
1838 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
1839 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
1840 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
1841 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
1842 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
1843 } else {
1844 dispatchEntry->resolvedAction = motionEntry->action;
1845 }
1846 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE
1847 && !connection->inputState.isHovering(
1848 motionEntry->deviceId, motionEntry->source)) {
1849#if DEBUG_DISPATCH_CYCLE
Steve Block5baa3a62011-12-20 16:23:08 +00001850 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter event",
Jeff Brown81346812011-06-28 20:08:48 -07001851 connection->getInputChannelName());
1852#endif
1853 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
1854 }
1855
1856 dispatchEntry->resolvedFlags = motionEntry->flags;
1857 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
1858 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
1859 }
1860
1861 if (!connection->inputState.trackMotion(motionEntry,
1862 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags)) {
1863#if DEBUG_DISPATCH_CYCLE
Steve Block5baa3a62011-12-20 16:23:08 +00001864 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion event",
Jeff Brown81346812011-06-28 20:08:48 -07001865 connection->getInputChannelName());
1866#endif
Jeff Brownc0cb3dc2012-01-12 18:30:12 -08001867 delete dispatchEntry;
Jeff Brown81346812011-06-28 20:08:48 -07001868 return; // skip the inconsistent event
1869 }
1870 break;
1871 }
1872 }
1873
Jeff Brownc0cb3dc2012-01-12 18:30:12 -08001874 // Remember that we are waiting for this dispatch to complete.
1875 if (dispatchEntry->hasForegroundTarget()) {
1876 incrementPendingForegroundDispatchesLocked(eventEntry);
1877 }
1878
Jeff Brown46b9ac02010-04-22 18:58:52 -07001879 // Enqueue the dispatch entry.
1880 connection->outboundQueue.enqueueAtTail(dispatchEntry);
Jeff Brown481c1572012-03-09 14:41:15 -08001881 traceOutboundQueueLengthLocked(connection);
Jeff Brown46b9ac02010-04-22 18:58:52 -07001882}
1883
Jeff Brown7fbdc842010-06-17 20:52:56 -07001884void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Jeff Brown519e0242010-09-15 15:18:56 -07001885 const sp<Connection>& connection) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07001886#if DEBUG_DISPATCH_CYCLE
Steve Block5baa3a62011-12-20 16:23:08 +00001887 ALOGD("channel '%s' ~ startDispatchCycle",
Jeff Brown46b9ac02010-04-22 18:58:52 -07001888 connection->getInputChannelName());
1889#endif
1890
Jeff Brownd1c48a02012-02-06 19:12:47 -08001891 while (connection->status == Connection::STATUS_NORMAL
1892 && !connection->outboundQueue.isEmpty()) {
1893 DispatchEntry* dispatchEntry = connection->outboundQueue.head;
Jeff Brown265f1cc2012-06-11 18:01:06 -07001894 dispatchEntry->deliveryTime = currentTime;
Jeff Brown46b9ac02010-04-22 18:58:52 -07001895
Jeff Brownd1c48a02012-02-06 19:12:47 -08001896 // Publish the event.
1897 status_t status;
1898 EventEntry* eventEntry = dispatchEntry->eventEntry;
1899 switch (eventEntry->type) {
1900 case EventEntry::TYPE_KEY: {
1901 KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
Jeff Brown46b9ac02010-04-22 18:58:52 -07001902
Jeff Brownd1c48a02012-02-06 19:12:47 -08001903 // Publish the key event.
Jeff Brown072ec962012-02-07 14:46:57 -08001904 status = connection->inputPublisher.publishKeyEvent(dispatchEntry->seq,
Jeff Brownd1c48a02012-02-06 19:12:47 -08001905 keyEntry->deviceId, keyEntry->source,
1906 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags,
1907 keyEntry->keyCode, keyEntry->scanCode,
1908 keyEntry->metaState, keyEntry->repeatCount, keyEntry->downTime,
1909 keyEntry->eventTime);
1910 break;
1911 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001912
Jeff Brownd1c48a02012-02-06 19:12:47 -08001913 case EventEntry::TYPE_MOTION: {
1914 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
Jeff Brown46b9ac02010-04-22 18:58:52 -07001915
Jeff Brownd1c48a02012-02-06 19:12:47 -08001916 PointerCoords scaledCoords[MAX_POINTERS];
1917 const PointerCoords* usingCoords = motionEntry->pointerCoords;
Jeff Brown46b9ac02010-04-22 18:58:52 -07001918
Jeff Brownd1c48a02012-02-06 19:12:47 -08001919 // Set the X and Y offset depending on the input source.
1920 float xOffset, yOffset, scaleFactor;
1921 if ((motionEntry->source & AINPUT_SOURCE_CLASS_POINTER)
1922 && !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
1923 scaleFactor = dispatchEntry->scaleFactor;
1924 xOffset = dispatchEntry->xOffset * scaleFactor;
1925 yOffset = dispatchEntry->yOffset * scaleFactor;
1926 if (scaleFactor != 1.0f) {
1927 for (size_t i = 0; i < motionEntry->pointerCount; i++) {
1928 scaledCoords[i] = motionEntry->pointerCoords[i];
1929 scaledCoords[i].scale(scaleFactor);
1930 }
1931 usingCoords = scaledCoords;
1932 }
1933 } else {
1934 xOffset = 0.0f;
1935 yOffset = 0.0f;
1936 scaleFactor = 1.0f;
1937
1938 // We don't want the dispatch target to know.
1939 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
1940 for (size_t i = 0; i < motionEntry->pointerCount; i++) {
1941 scaledCoords[i].clear();
1942 }
1943 usingCoords = scaledCoords;
1944 }
1945 }
1946
1947 // Publish the motion event.
Jeff Brown072ec962012-02-07 14:46:57 -08001948 status = connection->inputPublisher.publishMotionEvent(dispatchEntry->seq,
Jeff Brownd1c48a02012-02-06 19:12:47 -08001949 motionEntry->deviceId, motionEntry->source,
1950 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags,
1951 motionEntry->edgeFlags, motionEntry->metaState, motionEntry->buttonState,
1952 xOffset, yOffset,
1953 motionEntry->xPrecision, motionEntry->yPrecision,
1954 motionEntry->downTime, motionEntry->eventTime,
1955 motionEntry->pointerCount, motionEntry->pointerProperties,
1956 usingCoords);
1957 break;
1958 }
1959
1960 default:
1961 ALOG_ASSERT(false);
Jeff Brown46b9ac02010-04-22 18:58:52 -07001962 return;
1963 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07001964
Jeff Brownd1c48a02012-02-06 19:12:47 -08001965 // Check the result.
Jeff Brown46b9ac02010-04-22 18:58:52 -07001966 if (status) {
Jeff Brownd1c48a02012-02-06 19:12:47 -08001967 if (status == WOULD_BLOCK) {
1968 if (connection->waitQueue.isEmpty()) {
1969 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
1970 "This is unexpected because the wait queue is empty, so the pipe "
1971 "should be empty and we shouldn't have any problems writing an "
1972 "event to it, status=%d", connection->getInputChannelName(), status);
1973 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
1974 } else {
1975 // Pipe is full and we are waiting for the app to finish process some events
1976 // before sending more events to it.
1977#if DEBUG_DISPATCH_CYCLE
1978 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
1979 "waiting for the application to catch up",
1980 connection->getInputChannelName());
1981#endif
1982 connection->inputPublisherBlocked = true;
1983 }
1984 } else {
1985 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
1986 "status=%d", connection->getInputChannelName(), status);
1987 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
1988 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07001989 return;
1990 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07001991
Jeff Brownd1c48a02012-02-06 19:12:47 -08001992 // Re-enqueue the event on the wait queue.
1993 connection->outboundQueue.dequeue(dispatchEntry);
Jeff Brown481c1572012-03-09 14:41:15 -08001994 traceOutboundQueueLengthLocked(connection);
Jeff Brownd1c48a02012-02-06 19:12:47 -08001995 connection->waitQueue.enqueueAtTail(dispatchEntry);
Jeff Brown481c1572012-03-09 14:41:15 -08001996 traceWaitQueueLengthLocked(connection);
Jeff Brown46b9ac02010-04-22 18:58:52 -07001997 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07001998}
1999
Jeff Brown7fbdc842010-06-17 20:52:56 -07002000void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Jeff Brown072ec962012-02-07 14:46:57 -08002001 const sp<Connection>& connection, uint32_t seq, bool handled) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002002#if DEBUG_DISPATCH_CYCLE
Jeff Brown072ec962012-02-07 14:46:57 -08002003 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
2004 connection->getInputChannelName(), seq, toString(handled));
Jeff Brown46b9ac02010-04-22 18:58:52 -07002005#endif
2006
Jeff Brownd1c48a02012-02-06 19:12:47 -08002007 connection->inputPublisherBlocked = false;
2008
Jeff Brown9c3cda02010-06-15 01:31:58 -07002009 if (connection->status == Connection::STATUS_BROKEN
2010 || connection->status == Connection::STATUS_ZOMBIE) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002011 return;
2012 }
2013
Jeff Brown3915bb82010-11-05 15:02:16 -07002014 // Notify other system components and prepare to start the next dispatch cycle.
Jeff Brown072ec962012-02-07 14:46:57 -08002015 onDispatchCycleFinishedLocked(currentTime, connection, seq, handled);
Jeff Brownb88102f2010-09-08 11:49:43 -07002016}
2017
Jeff Brownb6997262010-10-08 22:31:17 -07002018void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Jeff Browncc4f7db2011-08-30 20:34:48 -07002019 const sp<Connection>& connection, bool notify) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002020#if DEBUG_DISPATCH_CYCLE
Steve Block5baa3a62011-12-20 16:23:08 +00002021 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
Jeff Browncc4f7db2011-08-30 20:34:48 -07002022 connection->getInputChannelName(), toString(notify));
Jeff Brown46b9ac02010-04-22 18:58:52 -07002023#endif
2024
Jeff Brownd1c48a02012-02-06 19:12:47 -08002025 // Clear the dispatch queues.
2026 drainDispatchQueueLocked(&connection->outboundQueue);
Jeff Brown481c1572012-03-09 14:41:15 -08002027 traceOutboundQueueLengthLocked(connection);
Jeff Brownd1c48a02012-02-06 19:12:47 -08002028 drainDispatchQueueLocked(&connection->waitQueue);
Jeff Brown481c1572012-03-09 14:41:15 -08002029 traceWaitQueueLengthLocked(connection);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002030
Jeff Brownb6997262010-10-08 22:31:17 -07002031 // The connection appears to be unrecoverably broken.
Jeff Brown9c3cda02010-06-15 01:31:58 -07002032 // Ignore already broken or zombie connections.
Jeff Brownb6997262010-10-08 22:31:17 -07002033 if (connection->status == Connection::STATUS_NORMAL) {
2034 connection->status = Connection::STATUS_BROKEN;
Jeff Brown46b9ac02010-04-22 18:58:52 -07002035
Jeff Browncc4f7db2011-08-30 20:34:48 -07002036 if (notify) {
2037 // Notify other system components.
2038 onDispatchCycleBrokenLocked(currentTime, connection);
2039 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002040 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002041}
2042
Jeff Brownd1c48a02012-02-06 19:12:47 -08002043void InputDispatcher::drainDispatchQueueLocked(Queue<DispatchEntry>* queue) {
2044 while (!queue->isEmpty()) {
2045 DispatchEntry* dispatchEntry = queue->dequeueAtHead();
2046 releaseDispatchEntryLocked(dispatchEntry);
Jeff Brownb88102f2010-09-08 11:49:43 -07002047 }
Jeff Brownb88102f2010-09-08 11:49:43 -07002048}
2049
Jeff Brownd1c48a02012-02-06 19:12:47 -08002050void InputDispatcher::releaseDispatchEntryLocked(DispatchEntry* dispatchEntry) {
2051 if (dispatchEntry->hasForegroundTarget()) {
2052 decrementPendingForegroundDispatchesLocked(dispatchEntry->eventEntry);
2053 }
2054 delete dispatchEntry;
2055}
2056
Jeff Browncbee6d62012-02-03 20:11:27 -08002057int InputDispatcher::handleReceiveCallback(int fd, int events, void* data) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002058 InputDispatcher* d = static_cast<InputDispatcher*>(data);
2059
2060 { // acquire lock
2061 AutoMutex _l(d->mLock);
2062
Jeff Browncbee6d62012-02-03 20:11:27 -08002063 ssize_t connectionIndex = d->mConnectionsByFd.indexOfKey(fd);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002064 if (connectionIndex < 0) {
Steve Block3762c312012-01-06 19:20:56 +00002065 ALOGE("Received spurious receive callback for unknown input channel. "
Jeff Browncbee6d62012-02-03 20:11:27 -08002066 "fd=%d, events=0x%x", fd, events);
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002067 return 0; // remove the callback
Jeff Brown46b9ac02010-04-22 18:58:52 -07002068 }
2069
Jeff Browncc4f7db2011-08-30 20:34:48 -07002070 bool notify;
Jeff Browncbee6d62012-02-03 20:11:27 -08002071 sp<Connection> connection = d->mConnectionsByFd.valueAt(connectionIndex);
Jeff Browncc4f7db2011-08-30 20:34:48 -07002072 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
2073 if (!(events & ALOOPER_EVENT_INPUT)) {
Steve Block8564c8d2012-01-05 23:22:43 +00002074 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
Jeff Browncc4f7db2011-08-30 20:34:48 -07002075 "events=0x%x", connection->getInputChannelName(), events);
2076 return 1;
2077 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002078
Jeff Brown1adee112012-02-07 10:25:41 -08002079 nsecs_t currentTime = now();
2080 bool gotOne = false;
2081 status_t status;
2082 for (;;) {
Jeff Brown072ec962012-02-07 14:46:57 -08002083 uint32_t seq;
2084 bool handled;
2085 status = connection->inputPublisher.receiveFinishedSignal(&seq, &handled);
Jeff Brown1adee112012-02-07 10:25:41 -08002086 if (status) {
2087 break;
2088 }
Jeff Brown072ec962012-02-07 14:46:57 -08002089 d->finishDispatchCycleLocked(currentTime, connection, seq, handled);
Jeff Brown1adee112012-02-07 10:25:41 -08002090 gotOne = true;
2091 }
2092 if (gotOne) {
Jeff Browncc4f7db2011-08-30 20:34:48 -07002093 d->runCommandsLockedInterruptible();
Jeff Brown1adee112012-02-07 10:25:41 -08002094 if (status == WOULD_BLOCK) {
2095 return 1;
2096 }
Jeff Browncc4f7db2011-08-30 20:34:48 -07002097 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002098
Jeff Brown1adee112012-02-07 10:25:41 -08002099 notify = status != DEAD_OBJECT || !connection->monitor;
2100 if (notify) {
2101 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
2102 connection->getInputChannelName(), status);
2103 }
Jeff Browncc4f7db2011-08-30 20:34:48 -07002104 } else {
2105 // Monitor channels are never explicitly unregistered.
2106 // We do it automatically when the remote endpoint is closed so don't warn
2107 // about them.
2108 notify = !connection->monitor;
2109 if (notify) {
Steve Block8564c8d2012-01-05 23:22:43 +00002110 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. "
Jeff Browncc4f7db2011-08-30 20:34:48 -07002111 "events=0x%x", connection->getInputChannelName(), events);
2112 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002113 }
2114
Jeff Browncc4f7db2011-08-30 20:34:48 -07002115 // Unregister the channel.
2116 d->unregisterInputChannelLocked(connection->inputChannel, notify);
2117 return 0; // remove the callback
Jeff Brown46b9ac02010-04-22 18:58:52 -07002118 } // release lock
2119}
2120
Jeff Brownb6997262010-10-08 22:31:17 -07002121void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Jeff Brownda3d5a92011-03-29 15:11:34 -07002122 const CancelationOptions& options) {
Jeff Browncbee6d62012-02-03 20:11:27 -08002123 for (size_t i = 0; i < mConnectionsByFd.size(); i++) {
Jeff Brownb6997262010-10-08 22:31:17 -07002124 synthesizeCancelationEventsForConnectionLocked(
Jeff Browncbee6d62012-02-03 20:11:27 -08002125 mConnectionsByFd.valueAt(i), options);
Jeff Brownb6997262010-10-08 22:31:17 -07002126 }
2127}
2128
2129void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Jeff Brownda3d5a92011-03-29 15:11:34 -07002130 const sp<InputChannel>& channel, const CancelationOptions& options) {
Jeff Brownb6997262010-10-08 22:31:17 -07002131 ssize_t index = getConnectionIndexLocked(channel);
2132 if (index >= 0) {
2133 synthesizeCancelationEventsForConnectionLocked(
Jeff Browncbee6d62012-02-03 20:11:27 -08002134 mConnectionsByFd.valueAt(index), options);
Jeff Brownb6997262010-10-08 22:31:17 -07002135 }
2136}
2137
2138void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
Jeff Brownda3d5a92011-03-29 15:11:34 -07002139 const sp<Connection>& connection, const CancelationOptions& options) {
Jeff Brownc0cb3dc2012-01-12 18:30:12 -08002140 if (connection->status == Connection::STATUS_BROKEN) {
2141 return;
2142 }
2143
Jeff Brownb6997262010-10-08 22:31:17 -07002144 nsecs_t currentTime = now();
2145
Jeff Brown8b4be5602012-02-06 16:31:05 -08002146 Vector<EventEntry*> cancelationEvents;
Jeff Brownac386072011-07-20 15:19:50 -07002147 connection->inputState.synthesizeCancelationEvents(currentTime,
Jeff Brown8b4be5602012-02-06 16:31:05 -08002148 cancelationEvents, options);
Jeff Brownb6997262010-10-08 22:31:17 -07002149
Jeff Brown8b4be5602012-02-06 16:31:05 -08002150 if (!cancelationEvents.isEmpty()) {
Jeff Brownb6997262010-10-08 22:31:17 -07002151#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00002152 ALOGD("channel '%s' ~ Synthesized %d cancelation events to bring channel back in sync "
Jeff Brownda3d5a92011-03-29 15:11:34 -07002153 "with reality: %s, mode=%d.",
Jeff Brown8b4be5602012-02-06 16:31:05 -08002154 connection->getInputChannelName(), cancelationEvents.size(),
Jeff Brownda3d5a92011-03-29 15:11:34 -07002155 options.reason, options.mode);
Jeff Brownb6997262010-10-08 22:31:17 -07002156#endif
Jeff Brown8b4be5602012-02-06 16:31:05 -08002157 for (size_t i = 0; i < cancelationEvents.size(); i++) {
2158 EventEntry* cancelationEventEntry = cancelationEvents.itemAt(i);
Jeff Brownb6997262010-10-08 22:31:17 -07002159 switch (cancelationEventEntry->type) {
2160 case EventEntry::TYPE_KEY:
2161 logOutboundKeyDetailsLocked("cancel - ",
2162 static_cast<KeyEntry*>(cancelationEventEntry));
2163 break;
2164 case EventEntry::TYPE_MOTION:
2165 logOutboundMotionDetailsLocked("cancel - ",
2166 static_cast<MotionEntry*>(cancelationEventEntry));
2167 break;
2168 }
2169
Jeff Brown81346812011-06-28 20:08:48 -07002170 InputTarget target;
Jeff Brown9302c872011-07-13 22:51:29 -07002171 sp<InputWindowHandle> windowHandle = getWindowHandleLocked(connection->inputChannel);
2172 if (windowHandle != NULL) {
Jeff Browncc4f7db2011-08-30 20:34:48 -07002173 const InputWindowInfo* windowInfo = windowHandle->getInfo();
2174 target.xOffset = -windowInfo->frameLeft;
2175 target.yOffset = -windowInfo->frameTop;
2176 target.scaleFactor = windowInfo->scaleFactor;
Jeff Brownb6997262010-10-08 22:31:17 -07002177 } else {
Jeff Brown81346812011-06-28 20:08:48 -07002178 target.xOffset = 0;
2179 target.yOffset = 0;
2180 target.scaleFactor = 1.0f;
Jeff Brownb6997262010-10-08 22:31:17 -07002181 }
Jeff Brown81346812011-06-28 20:08:48 -07002182 target.inputChannel = connection->inputChannel;
2183 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
Jeff Brownb6997262010-10-08 22:31:17 -07002184
Jeff Brown81346812011-06-28 20:08:48 -07002185 enqueueDispatchEntryLocked(connection, cancelationEventEntry, // increments ref
Jeff Brown3241b6b2012-02-03 15:08:02 -08002186 &target, InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brownb6997262010-10-08 22:31:17 -07002187
Jeff Brownac386072011-07-20 15:19:50 -07002188 cancelationEventEntry->release();
Jeff Brownb6997262010-10-08 22:31:17 -07002189 }
2190
Jeff Brownd1c48a02012-02-06 19:12:47 -08002191 startDispatchCycleLocked(currentTime, connection);
Jeff Brownb6997262010-10-08 22:31:17 -07002192 }
2193}
2194
Jeff Brown01ce2e92010-09-26 22:20:12 -07002195InputDispatcher::MotionEntry*
2196InputDispatcher::splitMotionEvent(const MotionEntry* originalMotionEntry, BitSet32 pointerIds) {
Steve Blockec193de2012-01-09 18:35:44 +00002197 ALOG_ASSERT(pointerIds.value != 0);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002198
2199 uint32_t splitPointerIndexMap[MAX_POINTERS];
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002200 PointerProperties splitPointerProperties[MAX_POINTERS];
Jeff Brown01ce2e92010-09-26 22:20:12 -07002201 PointerCoords splitPointerCoords[MAX_POINTERS];
2202
2203 uint32_t originalPointerCount = originalMotionEntry->pointerCount;
2204 uint32_t splitPointerCount = 0;
2205
2206 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
2207 originalPointerIndex++) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002208 const PointerProperties& pointerProperties =
2209 originalMotionEntry->pointerProperties[originalPointerIndex];
2210 uint32_t pointerId = uint32_t(pointerProperties.id);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002211 if (pointerIds.hasBit(pointerId)) {
2212 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002213 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
Jeff Brownace13b12011-03-09 17:39:48 -08002214 splitPointerCoords[splitPointerCount].copyFrom(
Jeff Brown3241b6b2012-02-03 15:08:02 -08002215 originalMotionEntry->pointerCoords[originalPointerIndex]);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002216 splitPointerCount += 1;
2217 }
2218 }
Jeff Brown58a2da82011-01-25 16:02:22 -08002219
2220 if (splitPointerCount != pointerIds.count()) {
2221 // This is bad. We are missing some of the pointers that we expected to deliver.
2222 // Most likely this indicates that we received an ACTION_MOVE events that has
2223 // different pointer ids than we expected based on the previous ACTION_DOWN
2224 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
2225 // in this way.
Steve Block8564c8d2012-01-05 23:22:43 +00002226 ALOGW("Dropping split motion event because the pointer count is %d but "
Jeff Brown58a2da82011-01-25 16:02:22 -08002227 "we expected there to be %d pointers. This probably means we received "
2228 "a broken sequence of pointer ids from the input device.",
2229 splitPointerCount, pointerIds.count());
2230 return NULL;
2231 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07002232
2233 int32_t action = originalMotionEntry->action;
2234 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
2235 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
2236 || maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2237 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002238 const PointerProperties& pointerProperties =
2239 originalMotionEntry->pointerProperties[originalPointerIndex];
2240 uint32_t pointerId = uint32_t(pointerProperties.id);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002241 if (pointerIds.hasBit(pointerId)) {
2242 if (pointerIds.count() == 1) {
2243 // The first/last pointer went down/up.
2244 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
2245 ? AMOTION_EVENT_ACTION_DOWN : AMOTION_EVENT_ACTION_UP;
Jeff Brown9a01d052010-09-27 16:35:11 -07002246 } else {
2247 // A secondary pointer went down/up.
2248 uint32_t splitPointerIndex = 0;
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002249 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
Jeff Brown9a01d052010-09-27 16:35:11 -07002250 splitPointerIndex += 1;
2251 }
2252 action = maskedAction | (splitPointerIndex
2253 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002254 }
2255 } else {
2256 // An unrelated pointer changed.
2257 action = AMOTION_EVENT_ACTION_MOVE;
2258 }
2259 }
2260
Jeff Brownac386072011-07-20 15:19:50 -07002261 MotionEntry* splitMotionEntry = new MotionEntry(
Jeff Brown01ce2e92010-09-26 22:20:12 -07002262 originalMotionEntry->eventTime,
2263 originalMotionEntry->deviceId,
2264 originalMotionEntry->source,
2265 originalMotionEntry->policyFlags,
2266 action,
2267 originalMotionEntry->flags,
2268 originalMotionEntry->metaState,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002269 originalMotionEntry->buttonState,
Jeff Brown01ce2e92010-09-26 22:20:12 -07002270 originalMotionEntry->edgeFlags,
2271 originalMotionEntry->xPrecision,
2272 originalMotionEntry->yPrecision,
2273 originalMotionEntry->downTime,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002274 splitPointerCount, splitPointerProperties, splitPointerCoords);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002275
Jeff Browna032cc02011-03-07 16:56:21 -08002276 if (originalMotionEntry->injectionState) {
2277 splitMotionEntry->injectionState = originalMotionEntry->injectionState;
2278 splitMotionEntry->injectionState->refCount += 1;
2279 }
2280
Jeff Brown01ce2e92010-09-26 22:20:12 -07002281 return splitMotionEntry;
2282}
2283
Jeff Brownbe1aa822011-07-27 16:04:54 -07002284void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002285#if DEBUG_INBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00002286 ALOGD("notifyConfigurationChanged - eventTime=%lld", args->eventTime);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002287#endif
2288
Jeff Brownb88102f2010-09-08 11:49:43 -07002289 bool needWake;
Jeff Brown46b9ac02010-04-22 18:58:52 -07002290 { // acquire lock
2291 AutoMutex _l(mLock);
2292
Jeff Brownbe1aa822011-07-27 16:04:54 -07002293 ConfigurationChangedEntry* newEntry = new ConfigurationChangedEntry(args->eventTime);
Jeff Brownb88102f2010-09-08 11:49:43 -07002294 needWake = enqueueInboundEventLocked(newEntry);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002295 } // release lock
2296
Jeff Brownb88102f2010-09-08 11:49:43 -07002297 if (needWake) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002298 mLooper->wake();
Jeff Brown46b9ac02010-04-22 18:58:52 -07002299 }
2300}
2301
Jeff Brownbe1aa822011-07-27 16:04:54 -07002302void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002303#if DEBUG_INBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00002304 ALOGD("notifyKey - eventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, action=0x%x, "
Jeff Brown46b9ac02010-04-22 18:58:52 -07002305 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%lld",
Jeff Brownbe1aa822011-07-27 16:04:54 -07002306 args->eventTime, args->deviceId, args->source, args->policyFlags,
2307 args->action, args->flags, args->keyCode, args->scanCode,
2308 args->metaState, args->downTime);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002309#endif
Jeff Brownbe1aa822011-07-27 16:04:54 -07002310 if (!validateKeyEvent(args->action)) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002311 return;
2312 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002313
Jeff Brownbe1aa822011-07-27 16:04:54 -07002314 uint32_t policyFlags = args->policyFlags;
2315 int32_t flags = args->flags;
2316 int32_t metaState = args->metaState;
Jeff Brown1f245102010-11-18 20:53:46 -08002317 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
2318 policyFlags |= POLICY_FLAG_VIRTUAL;
2319 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
2320 }
Jeff Brown924c4d42011-03-07 16:40:47 -08002321 if (policyFlags & POLICY_FLAG_ALT) {
2322 metaState |= AMETA_ALT_ON | AMETA_ALT_LEFT_ON;
2323 }
2324 if (policyFlags & POLICY_FLAG_ALT_GR) {
2325 metaState |= AMETA_ALT_ON | AMETA_ALT_RIGHT_ON;
2326 }
2327 if (policyFlags & POLICY_FLAG_SHIFT) {
2328 metaState |= AMETA_SHIFT_ON | AMETA_SHIFT_LEFT_ON;
2329 }
2330 if (policyFlags & POLICY_FLAG_CAPS_LOCK) {
2331 metaState |= AMETA_CAPS_LOCK_ON;
2332 }
2333 if (policyFlags & POLICY_FLAG_FUNCTION) {
2334 metaState |= AMETA_FUNCTION_ON;
2335 }
Jeff Brown1f245102010-11-18 20:53:46 -08002336
Jeff Browne20c9e02010-10-11 14:20:19 -07002337 policyFlags |= POLICY_FLAG_TRUSTED;
Jeff Brown1f245102010-11-18 20:53:46 -08002338
2339 KeyEvent event;
Jeff Brownbe1aa822011-07-27 16:04:54 -07002340 event.initialize(args->deviceId, args->source, args->action,
2341 flags, args->keyCode, args->scanCode, metaState, 0,
2342 args->downTime, args->eventTime);
Jeff Brown1f245102010-11-18 20:53:46 -08002343
2344 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
2345
2346 if (policyFlags & POLICY_FLAG_WOKE_HERE) {
2347 flags |= AKEY_EVENT_FLAG_WOKE_HERE;
2348 }
Jeff Brownb6997262010-10-08 22:31:17 -07002349
Jeff Brownb88102f2010-09-08 11:49:43 -07002350 bool needWake;
Jeff Brown46b9ac02010-04-22 18:58:52 -07002351 { // acquire lock
Jeff Brown0029c662011-03-30 02:25:18 -07002352 mLock.lock();
2353
2354 if (mInputFilterEnabled) {
2355 mLock.unlock();
2356
2357 policyFlags |= POLICY_FLAG_FILTERED;
2358 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2359 return; // event was consumed by the filter
2360 }
2361
2362 mLock.lock();
2363 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002364
Jeff Brown7fbdc842010-06-17 20:52:56 -07002365 int32_t repeatCount = 0;
Jeff Brownbe1aa822011-07-27 16:04:54 -07002366 KeyEntry* newEntry = new KeyEntry(args->eventTime,
2367 args->deviceId, args->source, policyFlags,
2368 args->action, flags, args->keyCode, args->scanCode,
2369 metaState, repeatCount, args->downTime);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002370
Jeff Brownb88102f2010-09-08 11:49:43 -07002371 needWake = enqueueInboundEventLocked(newEntry);
Jeff Brown0029c662011-03-30 02:25:18 -07002372 mLock.unlock();
Jeff Brown46b9ac02010-04-22 18:58:52 -07002373 } // release lock
2374
Jeff Brownb88102f2010-09-08 11:49:43 -07002375 if (needWake) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002376 mLooper->wake();
Jeff Brown46b9ac02010-04-22 18:58:52 -07002377 }
2378}
2379
Jeff Brownbe1aa822011-07-27 16:04:54 -07002380void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002381#if DEBUG_INBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00002382 ALOGD("notifyMotion - eventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, "
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002383 "action=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, edgeFlags=0x%x, "
Jeff Brown85a31762010-09-01 17:01:00 -07002384 "xPrecision=%f, yPrecision=%f, downTime=%lld",
Jeff Brownbe1aa822011-07-27 16:04:54 -07002385 args->eventTime, args->deviceId, args->source, args->policyFlags,
2386 args->action, args->flags, args->metaState, args->buttonState,
2387 args->edgeFlags, args->xPrecision, args->yPrecision, args->downTime);
2388 for (uint32_t i = 0; i < args->pointerCount; i++) {
Steve Block5baa3a62011-12-20 16:23:08 +00002389 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002390 "x=%f, y=%f, pressure=%f, size=%f, "
Jeff Brown85a31762010-09-01 17:01:00 -07002391 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
Jeff Brown8d608662010-08-30 03:02:23 -07002392 "orientation=%f",
Jeff Brownbe1aa822011-07-27 16:04:54 -07002393 i, args->pointerProperties[i].id,
2394 args->pointerProperties[i].toolType,
2395 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
2396 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
2397 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
2398 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
2399 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
2400 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
2401 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
2402 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
2403 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Jeff Brown46b9ac02010-04-22 18:58:52 -07002404 }
2405#endif
Jeff Brownbe1aa822011-07-27 16:04:54 -07002406 if (!validateMotionEvent(args->action, args->pointerCount, args->pointerProperties)) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002407 return;
2408 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002409
Jeff Brownbe1aa822011-07-27 16:04:54 -07002410 uint32_t policyFlags = args->policyFlags;
Jeff Browne20c9e02010-10-11 14:20:19 -07002411 policyFlags |= POLICY_FLAG_TRUSTED;
Jeff Brownbe1aa822011-07-27 16:04:54 -07002412 mPolicy->interceptMotionBeforeQueueing(args->eventTime, /*byref*/ policyFlags);
Jeff Brownb6997262010-10-08 22:31:17 -07002413
Jeff Brownb88102f2010-09-08 11:49:43 -07002414 bool needWake;
Jeff Brown46b9ac02010-04-22 18:58:52 -07002415 { // acquire lock
Jeff Brown0029c662011-03-30 02:25:18 -07002416 mLock.lock();
2417
2418 if (mInputFilterEnabled) {
2419 mLock.unlock();
2420
2421 MotionEvent event;
Jeff Brownbe1aa822011-07-27 16:04:54 -07002422 event.initialize(args->deviceId, args->source, args->action, args->flags,
2423 args->edgeFlags, args->metaState, args->buttonState, 0, 0,
2424 args->xPrecision, args->yPrecision,
2425 args->downTime, args->eventTime,
2426 args->pointerCount, args->pointerProperties, args->pointerCoords);
Jeff Brown0029c662011-03-30 02:25:18 -07002427
2428 policyFlags |= POLICY_FLAG_FILTERED;
2429 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2430 return; // event was consumed by the filter
2431 }
2432
2433 mLock.lock();
2434 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002435
Jeff Brown46b9ac02010-04-22 18:58:52 -07002436 // Just enqueue a new motion event.
Jeff Brownbe1aa822011-07-27 16:04:54 -07002437 MotionEntry* newEntry = new MotionEntry(args->eventTime,
2438 args->deviceId, args->source, policyFlags,
2439 args->action, args->flags, args->metaState, args->buttonState,
2440 args->edgeFlags, args->xPrecision, args->yPrecision, args->downTime,
2441 args->pointerCount, args->pointerProperties, args->pointerCoords);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002442
Jeff Brownb88102f2010-09-08 11:49:43 -07002443 needWake = enqueueInboundEventLocked(newEntry);
Jeff Brown0029c662011-03-30 02:25:18 -07002444 mLock.unlock();
Jeff Brown46b9ac02010-04-22 18:58:52 -07002445 } // release lock
2446
Jeff Brownb88102f2010-09-08 11:49:43 -07002447 if (needWake) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002448 mLooper->wake();
Jeff Brown46b9ac02010-04-22 18:58:52 -07002449 }
2450}
2451
Jeff Brownbe1aa822011-07-27 16:04:54 -07002452void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
Jeff Brownb6997262010-10-08 22:31:17 -07002453#if DEBUG_INBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00002454 ALOGD("notifySwitch - eventTime=%lld, policyFlags=0x%x, switchCode=%d, switchValue=%d",
Jeff Brownbe1aa822011-07-27 16:04:54 -07002455 args->eventTime, args->policyFlags,
2456 args->switchCode, args->switchValue);
Jeff Brownb6997262010-10-08 22:31:17 -07002457#endif
2458
Jeff Brownbe1aa822011-07-27 16:04:54 -07002459 uint32_t policyFlags = args->policyFlags;
Jeff Browne20c9e02010-10-11 14:20:19 -07002460 policyFlags |= POLICY_FLAG_TRUSTED;
Jeff Brownbe1aa822011-07-27 16:04:54 -07002461 mPolicy->notifySwitch(args->eventTime,
2462 args->switchCode, args->switchValue, policyFlags);
Jeff Brownb6997262010-10-08 22:31:17 -07002463}
2464
Jeff Brown65fd2512011-08-18 11:20:58 -07002465void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
2466#if DEBUG_INBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00002467 ALOGD("notifyDeviceReset - eventTime=%lld, deviceId=%d",
Jeff Brown65fd2512011-08-18 11:20:58 -07002468 args->eventTime, args->deviceId);
2469#endif
2470
2471 bool needWake;
2472 { // acquire lock
2473 AutoMutex _l(mLock);
2474
2475 DeviceResetEntry* newEntry = new DeviceResetEntry(args->eventTime, args->deviceId);
2476 needWake = enqueueInboundEventLocked(newEntry);
2477 } // release lock
2478
2479 if (needWake) {
2480 mLooper->wake();
2481 }
2482}
2483
Jeff Brown7fbdc842010-06-17 20:52:56 -07002484int32_t InputDispatcher::injectInputEvent(const InputEvent* event,
Jeff Brown0029c662011-03-30 02:25:18 -07002485 int32_t injectorPid, int32_t injectorUid, int32_t syncMode, int32_t timeoutMillis,
2486 uint32_t policyFlags) {
Jeff Brown7fbdc842010-06-17 20:52:56 -07002487#if DEBUG_INBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00002488 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Jeff Brown0029c662011-03-30 02:25:18 -07002489 "syncMode=%d, timeoutMillis=%d, policyFlags=0x%08x",
2490 event->getType(), injectorPid, injectorUid, syncMode, timeoutMillis, policyFlags);
Jeff Brown7fbdc842010-06-17 20:52:56 -07002491#endif
2492
2493 nsecs_t endTime = now() + milliseconds_to_nanoseconds(timeoutMillis);
Jeff Browne20c9e02010-10-11 14:20:19 -07002494
Jeff Brown0029c662011-03-30 02:25:18 -07002495 policyFlags |= POLICY_FLAG_INJECTED;
Jeff Browne20c9e02010-10-11 14:20:19 -07002496 if (hasInjectionPermission(injectorPid, injectorUid)) {
2497 policyFlags |= POLICY_FLAG_TRUSTED;
2498 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07002499
Jeff Brown3241b6b2012-02-03 15:08:02 -08002500 EventEntry* firstInjectedEntry;
2501 EventEntry* lastInjectedEntry;
Jeff Brownb6997262010-10-08 22:31:17 -07002502 switch (event->getType()) {
2503 case AINPUT_EVENT_TYPE_KEY: {
2504 const KeyEvent* keyEvent = static_cast<const KeyEvent*>(event);
2505 int32_t action = keyEvent->getAction();
2506 if (! validateKeyEvent(action)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07002507 return INPUT_EVENT_INJECTION_FAILED;
2508 }
2509
Jeff Brownb6997262010-10-08 22:31:17 -07002510 int32_t flags = keyEvent->getFlags();
Jeff Brown1f245102010-11-18 20:53:46 -08002511 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
2512 policyFlags |= POLICY_FLAG_VIRTUAL;
2513 }
2514
Jeff Brown0029c662011-03-30 02:25:18 -07002515 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
2516 mPolicy->interceptKeyBeforeQueueing(keyEvent, /*byref*/ policyFlags);
2517 }
Jeff Brown1f245102010-11-18 20:53:46 -08002518
2519 if (policyFlags & POLICY_FLAG_WOKE_HERE) {
2520 flags |= AKEY_EVENT_FLAG_WOKE_HERE;
2521 }
Jeff Brown6ec402b2010-07-28 15:48:59 -07002522
Jeff Brownb6997262010-10-08 22:31:17 -07002523 mLock.lock();
Jeff Brown3241b6b2012-02-03 15:08:02 -08002524 firstInjectedEntry = new KeyEntry(keyEvent->getEventTime(),
Jeff Brown1f245102010-11-18 20:53:46 -08002525 keyEvent->getDeviceId(), keyEvent->getSource(),
2526 policyFlags, action, flags,
2527 keyEvent->getKeyCode(), keyEvent->getScanCode(), keyEvent->getMetaState(),
Jeff Brownb6997262010-10-08 22:31:17 -07002528 keyEvent->getRepeatCount(), keyEvent->getDownTime());
Jeff Brown3241b6b2012-02-03 15:08:02 -08002529 lastInjectedEntry = firstInjectedEntry;
Jeff Brownb6997262010-10-08 22:31:17 -07002530 break;
2531 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07002532
Jeff Brownb6997262010-10-08 22:31:17 -07002533 case AINPUT_EVENT_TYPE_MOTION: {
2534 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
2535 int32_t action = motionEvent->getAction();
2536 size_t pointerCount = motionEvent->getPointerCount();
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002537 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
2538 if (! validateMotionEvent(action, pointerCount, pointerProperties)) {
Jeff Brownb6997262010-10-08 22:31:17 -07002539 return INPUT_EVENT_INJECTION_FAILED;
2540 }
2541
Jeff Brown0029c662011-03-30 02:25:18 -07002542 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
2543 nsecs_t eventTime = motionEvent->getEventTime();
2544 mPolicy->interceptMotionBeforeQueueing(eventTime, /*byref*/ policyFlags);
2545 }
Jeff Brownb6997262010-10-08 22:31:17 -07002546
2547 mLock.lock();
2548 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
2549 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
Jeff Brown3241b6b2012-02-03 15:08:02 -08002550 firstInjectedEntry = new MotionEntry(*sampleEventTimes,
Jeff Brownb6997262010-10-08 22:31:17 -07002551 motionEvent->getDeviceId(), motionEvent->getSource(), policyFlags,
2552 action, motionEvent->getFlags(),
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002553 motionEvent->getMetaState(), motionEvent->getButtonState(),
2554 motionEvent->getEdgeFlags(),
Jeff Brownb6997262010-10-08 22:31:17 -07002555 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
2556 motionEvent->getDownTime(), uint32_t(pointerCount),
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002557 pointerProperties, samplePointerCoords);
Jeff Brown3241b6b2012-02-03 15:08:02 -08002558 lastInjectedEntry = firstInjectedEntry;
Jeff Brownb6997262010-10-08 22:31:17 -07002559 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
2560 sampleEventTimes += 1;
2561 samplePointerCoords += pointerCount;
Jeff Brown3241b6b2012-02-03 15:08:02 -08002562 MotionEntry* nextInjectedEntry = new MotionEntry(*sampleEventTimes,
2563 motionEvent->getDeviceId(), motionEvent->getSource(), policyFlags,
2564 action, motionEvent->getFlags(),
2565 motionEvent->getMetaState(), motionEvent->getButtonState(),
2566 motionEvent->getEdgeFlags(),
2567 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
2568 motionEvent->getDownTime(), uint32_t(pointerCount),
2569 pointerProperties, samplePointerCoords);
2570 lastInjectedEntry->next = nextInjectedEntry;
2571 lastInjectedEntry = nextInjectedEntry;
Jeff Brownb6997262010-10-08 22:31:17 -07002572 }
Jeff Brownb6997262010-10-08 22:31:17 -07002573 break;
2574 }
2575
2576 default:
Steve Block8564c8d2012-01-05 23:22:43 +00002577 ALOGW("Cannot inject event of type %d", event->getType());
Jeff Brownb6997262010-10-08 22:31:17 -07002578 return INPUT_EVENT_INJECTION_FAILED;
2579 }
2580
Jeff Brownac386072011-07-20 15:19:50 -07002581 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
Jeff Brownb6997262010-10-08 22:31:17 -07002582 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
2583 injectionState->injectionIsAsync = true;
2584 }
2585
2586 injectionState->refCount += 1;
Jeff Brown3241b6b2012-02-03 15:08:02 -08002587 lastInjectedEntry->injectionState = injectionState;
Jeff Brownb6997262010-10-08 22:31:17 -07002588
Jeff Brown3241b6b2012-02-03 15:08:02 -08002589 bool needWake = false;
2590 for (EventEntry* entry = firstInjectedEntry; entry != NULL; ) {
2591 EventEntry* nextEntry = entry->next;
2592 needWake |= enqueueInboundEventLocked(entry);
2593 entry = nextEntry;
2594 }
2595
Jeff Brownb6997262010-10-08 22:31:17 -07002596 mLock.unlock();
Jeff Brown7fbdc842010-06-17 20:52:56 -07002597
Jeff Brownb88102f2010-09-08 11:49:43 -07002598 if (needWake) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002599 mLooper->wake();
Jeff Brown7fbdc842010-06-17 20:52:56 -07002600 }
2601
2602 int32_t injectionResult;
2603 { // acquire lock
2604 AutoMutex _l(mLock);
2605
Jeff Brown6ec402b2010-07-28 15:48:59 -07002606 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
2607 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
2608 } else {
2609 for (;;) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002610 injectionResult = injectionState->injectionResult;
Jeff Brown6ec402b2010-07-28 15:48:59 -07002611 if (injectionResult != INPUT_EVENT_INJECTION_PENDING) {
2612 break;
2613 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07002614
Jeff Brown7fbdc842010-06-17 20:52:56 -07002615 nsecs_t remainingTimeout = endTime - now();
2616 if (remainingTimeout <= 0) {
Jeff Brown6ec402b2010-07-28 15:48:59 -07002617#if DEBUG_INJECTION
Steve Block5baa3a62011-12-20 16:23:08 +00002618 ALOGD("injectInputEvent - Timed out waiting for injection result "
Jeff Brown6ec402b2010-07-28 15:48:59 -07002619 "to become available.");
2620#endif
Jeff Brown7fbdc842010-06-17 20:52:56 -07002621 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
2622 break;
2623 }
2624
Jeff Brown6ec402b2010-07-28 15:48:59 -07002625 mInjectionResultAvailableCondition.waitRelative(mLock, remainingTimeout);
2626 }
2627
2628 if (injectionResult == INPUT_EVENT_INJECTION_SUCCEEDED
2629 && syncMode == INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002630 while (injectionState->pendingForegroundDispatches != 0) {
Jeff Brown6ec402b2010-07-28 15:48:59 -07002631#if DEBUG_INJECTION
Steve Block5baa3a62011-12-20 16:23:08 +00002632 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
Jeff Brown01ce2e92010-09-26 22:20:12 -07002633 injectionState->pendingForegroundDispatches);
Jeff Brown6ec402b2010-07-28 15:48:59 -07002634#endif
2635 nsecs_t remainingTimeout = endTime - now();
2636 if (remainingTimeout <= 0) {
2637#if DEBUG_INJECTION
Steve Block5baa3a62011-12-20 16:23:08 +00002638 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
Jeff Brown6ec402b2010-07-28 15:48:59 -07002639 "dispatches to finish.");
2640#endif
2641 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
2642 break;
2643 }
2644
2645 mInjectionSyncFinishedCondition.waitRelative(mLock, remainingTimeout);
2646 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07002647 }
2648 }
2649
Jeff Brownac386072011-07-20 15:19:50 -07002650 injectionState->release();
Jeff Brown7fbdc842010-06-17 20:52:56 -07002651 } // release lock
2652
Jeff Brown6ec402b2010-07-28 15:48:59 -07002653#if DEBUG_INJECTION
Steve Block5baa3a62011-12-20 16:23:08 +00002654 ALOGD("injectInputEvent - Finished with result %d. "
Jeff Brown6ec402b2010-07-28 15:48:59 -07002655 "injectorPid=%d, injectorUid=%d",
2656 injectionResult, injectorPid, injectorUid);
2657#endif
2658
Jeff Brown7fbdc842010-06-17 20:52:56 -07002659 return injectionResult;
2660}
2661
Jeff Brownb6997262010-10-08 22:31:17 -07002662bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
2663 return injectorUid == 0
2664 || mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
2665}
2666
Jeff Brown7fbdc842010-06-17 20:52:56 -07002667void InputDispatcher::setInjectionResultLocked(EventEntry* entry, int32_t injectionResult) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002668 InjectionState* injectionState = entry->injectionState;
2669 if (injectionState) {
Jeff Brown7fbdc842010-06-17 20:52:56 -07002670#if DEBUG_INJECTION
Steve Block5baa3a62011-12-20 16:23:08 +00002671 ALOGD("Setting input event injection result to %d. "
Jeff Brown7fbdc842010-06-17 20:52:56 -07002672 "injectorPid=%d, injectorUid=%d",
Jeff Brown01ce2e92010-09-26 22:20:12 -07002673 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
Jeff Brown7fbdc842010-06-17 20:52:56 -07002674#endif
2675
Jeff Brown0029c662011-03-30 02:25:18 -07002676 if (injectionState->injectionIsAsync
2677 && !(entry->policyFlags & POLICY_FLAG_FILTERED)) {
Jeff Brown6ec402b2010-07-28 15:48:59 -07002678 // Log the outcome since the injector did not wait for the injection result.
2679 switch (injectionResult) {
2680 case INPUT_EVENT_INJECTION_SUCCEEDED:
Steve Block71f2cf12011-10-20 11:56:00 +01002681 ALOGV("Asynchronous input event injection succeeded.");
Jeff Brown6ec402b2010-07-28 15:48:59 -07002682 break;
2683 case INPUT_EVENT_INJECTION_FAILED:
Steve Block8564c8d2012-01-05 23:22:43 +00002684 ALOGW("Asynchronous input event injection failed.");
Jeff Brown6ec402b2010-07-28 15:48:59 -07002685 break;
2686 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
Steve Block8564c8d2012-01-05 23:22:43 +00002687 ALOGW("Asynchronous input event injection permission denied.");
Jeff Brown6ec402b2010-07-28 15:48:59 -07002688 break;
2689 case INPUT_EVENT_INJECTION_TIMED_OUT:
Steve Block8564c8d2012-01-05 23:22:43 +00002690 ALOGW("Asynchronous input event injection timed out.");
Jeff Brown6ec402b2010-07-28 15:48:59 -07002691 break;
2692 }
2693 }
2694
Jeff Brown01ce2e92010-09-26 22:20:12 -07002695 injectionState->injectionResult = injectionResult;
Jeff Brown7fbdc842010-06-17 20:52:56 -07002696 mInjectionResultAvailableCondition.broadcast();
2697 }
2698}
2699
Jeff Brown01ce2e92010-09-26 22:20:12 -07002700void InputDispatcher::incrementPendingForegroundDispatchesLocked(EventEntry* entry) {
2701 InjectionState* injectionState = entry->injectionState;
2702 if (injectionState) {
2703 injectionState->pendingForegroundDispatches += 1;
2704 }
2705}
2706
Jeff Brown519e0242010-09-15 15:18:56 -07002707void InputDispatcher::decrementPendingForegroundDispatchesLocked(EventEntry* entry) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002708 InjectionState* injectionState = entry->injectionState;
2709 if (injectionState) {
2710 injectionState->pendingForegroundDispatches -= 1;
Jeff Brown6ec402b2010-07-28 15:48:59 -07002711
Jeff Brown01ce2e92010-09-26 22:20:12 -07002712 if (injectionState->pendingForegroundDispatches == 0) {
2713 mInjectionSyncFinishedCondition.broadcast();
2714 }
Jeff Brownb88102f2010-09-08 11:49:43 -07002715 }
2716}
2717
Jeff Brown9302c872011-07-13 22:51:29 -07002718sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
2719 const sp<InputChannel>& inputChannel) const {
2720 size_t numWindows = mWindowHandles.size();
2721 for (size_t i = 0; i < numWindows; i++) {
2722 const sp<InputWindowHandle>& windowHandle = mWindowHandles.itemAt(i);
Jeff Browncc4f7db2011-08-30 20:34:48 -07002723 if (windowHandle->getInputChannel() == inputChannel) {
Jeff Brown9302c872011-07-13 22:51:29 -07002724 return windowHandle;
Jeff Brown01ce2e92010-09-26 22:20:12 -07002725 }
2726 }
2727 return NULL;
2728}
2729
Jeff Brown9302c872011-07-13 22:51:29 -07002730bool InputDispatcher::hasWindowHandleLocked(
2731 const sp<InputWindowHandle>& windowHandle) const {
2732 size_t numWindows = mWindowHandles.size();
2733 for (size_t i = 0; i < numWindows; i++) {
2734 if (mWindowHandles.itemAt(i) == windowHandle) {
2735 return true;
2736 }
2737 }
2738 return false;
2739}
2740
2741void InputDispatcher::setInputWindows(const Vector<sp<InputWindowHandle> >& inputWindowHandles) {
Jeff Brownb88102f2010-09-08 11:49:43 -07002742#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002743 ALOGD("setInputWindows");
Jeff Brownb88102f2010-09-08 11:49:43 -07002744#endif
2745 { // acquire lock
2746 AutoMutex _l(mLock);
2747
Jeff Browncc4f7db2011-08-30 20:34:48 -07002748 Vector<sp<InputWindowHandle> > oldWindowHandles = mWindowHandles;
Jeff Brown9302c872011-07-13 22:51:29 -07002749 mWindowHandles = inputWindowHandles;
Jeff Brownb6997262010-10-08 22:31:17 -07002750
Jeff Brown9302c872011-07-13 22:51:29 -07002751 sp<InputWindowHandle> newFocusedWindowHandle;
2752 bool foundHoveredWindow = false;
2753 for (size_t i = 0; i < mWindowHandles.size(); i++) {
2754 const sp<InputWindowHandle>& windowHandle = mWindowHandles.itemAt(i);
Jeff Browncc4f7db2011-08-30 20:34:48 -07002755 if (!windowHandle->updateInfo() || windowHandle->getInputChannel() == NULL) {
Jeff Brown9302c872011-07-13 22:51:29 -07002756 mWindowHandles.removeAt(i--);
2757 continue;
2758 }
Jeff Browncc4f7db2011-08-30 20:34:48 -07002759 if (windowHandle->getInfo()->hasFocus) {
Jeff Brown9302c872011-07-13 22:51:29 -07002760 newFocusedWindowHandle = windowHandle;
2761 }
2762 if (windowHandle == mLastHoverWindowHandle) {
2763 foundHoveredWindow = true;
Jeff Brownb88102f2010-09-08 11:49:43 -07002764 }
2765 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07002766
Jeff Brown9302c872011-07-13 22:51:29 -07002767 if (!foundHoveredWindow) {
2768 mLastHoverWindowHandle = NULL;
2769 }
2770
2771 if (mFocusedWindowHandle != newFocusedWindowHandle) {
2772 if (mFocusedWindowHandle != NULL) {
Jeff Brownb6997262010-10-08 22:31:17 -07002773#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002774 ALOGD("Focus left window: %s",
Jeff Browncc4f7db2011-08-30 20:34:48 -07002775 mFocusedWindowHandle->getName().string());
Jeff Brownb6997262010-10-08 22:31:17 -07002776#endif
Jeff Browncc4f7db2011-08-30 20:34:48 -07002777 sp<InputChannel> focusedInputChannel = mFocusedWindowHandle->getInputChannel();
2778 if (focusedInputChannel != NULL) {
Christopher Tated9be36c2011-08-16 16:09:33 -07002779 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
2780 "focus left window");
2781 synthesizeCancelationEventsForInputChannelLocked(
Jeff Browncc4f7db2011-08-30 20:34:48 -07002782 focusedInputChannel, options);
Christopher Tated9be36c2011-08-16 16:09:33 -07002783 }
Jeff Brownb6997262010-10-08 22:31:17 -07002784 }
Jeff Brown9302c872011-07-13 22:51:29 -07002785 if (newFocusedWindowHandle != NULL) {
Jeff Brownb6997262010-10-08 22:31:17 -07002786#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002787 ALOGD("Focus entered window: %s",
Jeff Browncc4f7db2011-08-30 20:34:48 -07002788 newFocusedWindowHandle->getName().string());
Jeff Brownb6997262010-10-08 22:31:17 -07002789#endif
Jeff Brown9302c872011-07-13 22:51:29 -07002790 }
2791 mFocusedWindowHandle = newFocusedWindowHandle;
Jeff Brownb6997262010-10-08 22:31:17 -07002792 }
2793
Jeff Brown9302c872011-07-13 22:51:29 -07002794 for (size_t i = 0; i < mTouchState.windows.size(); i++) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002795 TouchedWindow& touchedWindow = mTouchState.windows.editItemAt(i);
Jeff Brown9302c872011-07-13 22:51:29 -07002796 if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
Jeff Brownb6997262010-10-08 22:31:17 -07002797#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002798 ALOGD("Touched window was removed: %s",
Jeff Browncc4f7db2011-08-30 20:34:48 -07002799 touchedWindow.windowHandle->getName().string());
Jeff Brownb6997262010-10-08 22:31:17 -07002800#endif
Jeff Browncc4f7db2011-08-30 20:34:48 -07002801 sp<InputChannel> touchedInputChannel =
2802 touchedWindow.windowHandle->getInputChannel();
2803 if (touchedInputChannel != NULL) {
Christopher Tated9be36c2011-08-16 16:09:33 -07002804 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
2805 "touched window was removed");
2806 synthesizeCancelationEventsForInputChannelLocked(
Jeff Browncc4f7db2011-08-30 20:34:48 -07002807 touchedInputChannel, options);
Christopher Tated9be36c2011-08-16 16:09:33 -07002808 }
Jeff Brown9302c872011-07-13 22:51:29 -07002809 mTouchState.windows.removeAt(i--);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002810 }
2811 }
Jeff Browncc4f7db2011-08-30 20:34:48 -07002812
2813 // Release information for windows that are no longer present.
2814 // This ensures that unused input channels are released promptly.
2815 // Otherwise, they might stick around until the window handle is destroyed
2816 // which might not happen until the next GC.
2817 for (size_t i = 0; i < oldWindowHandles.size(); i++) {
2818 const sp<InputWindowHandle>& oldWindowHandle = oldWindowHandles.itemAt(i);
2819 if (!hasWindowHandleLocked(oldWindowHandle)) {
2820#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002821 ALOGD("Window went away: %s", oldWindowHandle->getName().string());
Jeff Browncc4f7db2011-08-30 20:34:48 -07002822#endif
2823 oldWindowHandle->releaseInfo();
2824 }
2825 }
Jeff Brownb88102f2010-09-08 11:49:43 -07002826 } // release lock
2827
2828 // Wake up poll loop since it may need to make new input dispatching choices.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002829 mLooper->wake();
Jeff Brownb88102f2010-09-08 11:49:43 -07002830}
2831
Jeff Brown9302c872011-07-13 22:51:29 -07002832void InputDispatcher::setFocusedApplication(
2833 const sp<InputApplicationHandle>& inputApplicationHandle) {
Jeff Brownb88102f2010-09-08 11:49:43 -07002834#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002835 ALOGD("setFocusedApplication");
Jeff Brownb88102f2010-09-08 11:49:43 -07002836#endif
2837 { // acquire lock
2838 AutoMutex _l(mLock);
2839
Jeff Browncc4f7db2011-08-30 20:34:48 -07002840 if (inputApplicationHandle != NULL && inputApplicationHandle->updateInfo()) {
Jeff Brown5ea29ab2011-07-27 11:50:51 -07002841 if (mFocusedApplicationHandle != inputApplicationHandle) {
2842 if (mFocusedApplicationHandle != NULL) {
Jeff Browne9bb9be2012-02-06 15:47:55 -08002843 resetANRTimeoutsLocked();
Jeff Browncc4f7db2011-08-30 20:34:48 -07002844 mFocusedApplicationHandle->releaseInfo();
Jeff Brown5ea29ab2011-07-27 11:50:51 -07002845 }
2846 mFocusedApplicationHandle = inputApplicationHandle;
2847 }
2848 } else if (mFocusedApplicationHandle != NULL) {
Jeff Browne9bb9be2012-02-06 15:47:55 -08002849 resetANRTimeoutsLocked();
Jeff Browncc4f7db2011-08-30 20:34:48 -07002850 mFocusedApplicationHandle->releaseInfo();
Jeff Brown9302c872011-07-13 22:51:29 -07002851 mFocusedApplicationHandle.clear();
Jeff Brownb88102f2010-09-08 11:49:43 -07002852 }
2853
2854#if DEBUG_FOCUS
Jeff Brownb6997262010-10-08 22:31:17 -07002855 //logDispatchStateLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -07002856#endif
2857 } // release lock
2858
2859 // Wake up poll loop since it may need to make new input dispatching choices.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002860 mLooper->wake();
Jeff Brownb88102f2010-09-08 11:49:43 -07002861}
2862
Jeff Brownb88102f2010-09-08 11:49:43 -07002863void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
2864#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002865 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
Jeff Brownb88102f2010-09-08 11:49:43 -07002866#endif
2867
2868 bool changed;
2869 { // acquire lock
2870 AutoMutex _l(mLock);
2871
2872 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
Jeff Brown120a4592010-10-27 18:43:51 -07002873 if (mDispatchFrozen && !frozen) {
Jeff Brownb88102f2010-09-08 11:49:43 -07002874 resetANRTimeoutsLocked();
2875 }
2876
Jeff Brown120a4592010-10-27 18:43:51 -07002877 if (mDispatchEnabled && !enabled) {
2878 resetAndDropEverythingLocked("dispatcher is being disabled");
2879 }
2880
Jeff Brownb88102f2010-09-08 11:49:43 -07002881 mDispatchEnabled = enabled;
2882 mDispatchFrozen = frozen;
2883 changed = true;
2884 } else {
2885 changed = false;
2886 }
2887
2888#if DEBUG_FOCUS
Jeff Brownb6997262010-10-08 22:31:17 -07002889 //logDispatchStateLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -07002890#endif
2891 } // release lock
2892
2893 if (changed) {
2894 // Wake up poll loop since it may need to make new input dispatching choices.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002895 mLooper->wake();
Jeff Brown46b9ac02010-04-22 18:58:52 -07002896 }
2897}
2898
Jeff Brown0029c662011-03-30 02:25:18 -07002899void InputDispatcher::setInputFilterEnabled(bool enabled) {
2900#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002901 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
Jeff Brown0029c662011-03-30 02:25:18 -07002902#endif
2903
2904 { // acquire lock
2905 AutoMutex _l(mLock);
2906
2907 if (mInputFilterEnabled == enabled) {
2908 return;
2909 }
2910
2911 mInputFilterEnabled = enabled;
2912 resetAndDropEverythingLocked("input filter is being enabled or disabled");
2913 } // release lock
2914
2915 // Wake up poll loop since there might be work to do to drop everything.
2916 mLooper->wake();
2917}
2918
Jeff Browne6504122010-09-27 14:52:15 -07002919bool InputDispatcher::transferTouchFocus(const sp<InputChannel>& fromChannel,
2920 const sp<InputChannel>& toChannel) {
2921#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002922 ALOGD("transferTouchFocus: fromChannel=%s, toChannel=%s",
Jeff Browne6504122010-09-27 14:52:15 -07002923 fromChannel->getName().string(), toChannel->getName().string());
2924#endif
2925 { // acquire lock
2926 AutoMutex _l(mLock);
2927
Jeff Brown9302c872011-07-13 22:51:29 -07002928 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromChannel);
2929 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toChannel);
2930 if (fromWindowHandle == NULL || toWindowHandle == NULL) {
Jeff Browne6504122010-09-27 14:52:15 -07002931#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002932 ALOGD("Cannot transfer focus because from or to window not found.");
Jeff Browne6504122010-09-27 14:52:15 -07002933#endif
2934 return false;
2935 }
Jeff Brown9302c872011-07-13 22:51:29 -07002936 if (fromWindowHandle == toWindowHandle) {
Jeff Browne6504122010-09-27 14:52:15 -07002937#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002938 ALOGD("Trivial transfer to same window.");
Jeff Browne6504122010-09-27 14:52:15 -07002939#endif
2940 return true;
2941 }
2942
2943 bool found = false;
2944 for (size_t i = 0; i < mTouchState.windows.size(); i++) {
2945 const TouchedWindow& touchedWindow = mTouchState.windows[i];
Jeff Brown9302c872011-07-13 22:51:29 -07002946 if (touchedWindow.windowHandle == fromWindowHandle) {
Jeff Browne6504122010-09-27 14:52:15 -07002947 int32_t oldTargetFlags = touchedWindow.targetFlags;
2948 BitSet32 pointerIds = touchedWindow.pointerIds;
2949
2950 mTouchState.windows.removeAt(i);
2951
Jeff Brown46e75292010-11-10 16:53:45 -08002952 int32_t newTargetFlags = oldTargetFlags
Jeff Browna032cc02011-03-07 16:56:21 -08002953 & (InputTarget::FLAG_FOREGROUND
2954 | InputTarget::FLAG_SPLIT | InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brown9302c872011-07-13 22:51:29 -07002955 mTouchState.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Jeff Browne6504122010-09-27 14:52:15 -07002956
2957 found = true;
2958 break;
2959 }
2960 }
2961
2962 if (! found) {
2963#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002964 ALOGD("Focus transfer failed because from window did not have focus.");
Jeff Browne6504122010-09-27 14:52:15 -07002965#endif
2966 return false;
2967 }
2968
Jeff Brown9c9f1a32010-10-11 18:32:20 -07002969 ssize_t fromConnectionIndex = getConnectionIndexLocked(fromChannel);
2970 ssize_t toConnectionIndex = getConnectionIndexLocked(toChannel);
2971 if (fromConnectionIndex >= 0 && toConnectionIndex >= 0) {
Jeff Browncbee6d62012-02-03 20:11:27 -08002972 sp<Connection> fromConnection = mConnectionsByFd.valueAt(fromConnectionIndex);
2973 sp<Connection> toConnection = mConnectionsByFd.valueAt(toConnectionIndex);
Jeff Brown9c9f1a32010-10-11 18:32:20 -07002974
2975 fromConnection->inputState.copyPointerStateTo(toConnection->inputState);
Jeff Brownda3d5a92011-03-29 15:11:34 -07002976 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Jeff Brown9c9f1a32010-10-11 18:32:20 -07002977 "transferring touch focus from this window to another window");
Jeff Brownda3d5a92011-03-29 15:11:34 -07002978 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Jeff Brown9c9f1a32010-10-11 18:32:20 -07002979 }
2980
Jeff Browne6504122010-09-27 14:52:15 -07002981#if DEBUG_FOCUS
2982 logDispatchStateLocked();
2983#endif
2984 } // release lock
2985
2986 // Wake up poll loop since it may need to make new input dispatching choices.
2987 mLooper->wake();
2988 return true;
2989}
2990
Jeff Brown120a4592010-10-27 18:43:51 -07002991void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
2992#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002993 ALOGD("Resetting and dropping all events (%s).", reason);
Jeff Brown120a4592010-10-27 18:43:51 -07002994#endif
2995
Jeff Brownda3d5a92011-03-29 15:11:34 -07002996 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
2997 synthesizeCancelationEventsForAllConnectionsLocked(options);
Jeff Brown120a4592010-10-27 18:43:51 -07002998
2999 resetKeyRepeatLocked();
3000 releasePendingEventLocked();
3001 drainInboundQueueLocked();
Jeff Browne9bb9be2012-02-06 15:47:55 -08003002 resetANRTimeoutsLocked();
Jeff Brown120a4592010-10-27 18:43:51 -07003003
3004 mTouchState.reset();
Jeff Brown9302c872011-07-13 22:51:29 -07003005 mLastHoverWindowHandle.clear();
Jeff Brown120a4592010-10-27 18:43:51 -07003006}
3007
Jeff Brownb88102f2010-09-08 11:49:43 -07003008void InputDispatcher::logDispatchStateLocked() {
3009 String8 dump;
3010 dumpDispatchStateLocked(dump);
Jeff Brown2a95c2a2010-09-16 12:31:46 -07003011
3012 char* text = dump.lockBuffer(dump.size());
3013 char* start = text;
3014 while (*start != '\0') {
3015 char* end = strchr(start, '\n');
3016 if (*end == '\n') {
3017 *(end++) = '\0';
3018 }
Steve Block5baa3a62011-12-20 16:23:08 +00003019 ALOGD("%s", start);
Jeff Brown2a95c2a2010-09-16 12:31:46 -07003020 start = end;
3021 }
Jeff Brownb88102f2010-09-08 11:49:43 -07003022}
3023
3024void InputDispatcher::dumpDispatchStateLocked(String8& dump) {
Jeff Brownf2f48712010-10-01 17:46:21 -07003025 dump.appendFormat(INDENT "DispatchEnabled: %d\n", mDispatchEnabled);
3026 dump.appendFormat(INDENT "DispatchFrozen: %d\n", mDispatchFrozen);
Jeff Brownb88102f2010-09-08 11:49:43 -07003027
Jeff Brown9302c872011-07-13 22:51:29 -07003028 if (mFocusedApplicationHandle != NULL) {
Jeff Brownf2f48712010-10-01 17:46:21 -07003029 dump.appendFormat(INDENT "FocusedApplication: name='%s', dispatchingTimeout=%0.3fms\n",
Jeff Browncc4f7db2011-08-30 20:34:48 -07003030 mFocusedApplicationHandle->getName().string(),
3031 mFocusedApplicationHandle->getDispatchingTimeout(
3032 DEFAULT_INPUT_DISPATCHING_TIMEOUT) / 1000000.0);
Jeff Brownb88102f2010-09-08 11:49:43 -07003033 } else {
Jeff Brownf2f48712010-10-01 17:46:21 -07003034 dump.append(INDENT "FocusedApplication: <null>\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003035 }
Jeff Brownf2f48712010-10-01 17:46:21 -07003036 dump.appendFormat(INDENT "FocusedWindow: name='%s'\n",
Jeff Browncc4f7db2011-08-30 20:34:48 -07003037 mFocusedWindowHandle != NULL ? mFocusedWindowHandle->getName().string() : "<null>");
Jeff Brownf2f48712010-10-01 17:46:21 -07003038
3039 dump.appendFormat(INDENT "TouchDown: %s\n", toString(mTouchState.down));
3040 dump.appendFormat(INDENT "TouchSplit: %s\n", toString(mTouchState.split));
Jeff Brown95712852011-01-04 19:41:59 -08003041 dump.appendFormat(INDENT "TouchDeviceId: %d\n", mTouchState.deviceId);
Jeff Brown58a2da82011-01-25 16:02:22 -08003042 dump.appendFormat(INDENT "TouchSource: 0x%08x\n", mTouchState.source);
Jeff Brownf2f48712010-10-01 17:46:21 -07003043 if (!mTouchState.windows.isEmpty()) {
3044 dump.append(INDENT "TouchedWindows:\n");
3045 for (size_t i = 0; i < mTouchState.windows.size(); i++) {
3046 const TouchedWindow& touchedWindow = mTouchState.windows[i];
3047 dump.appendFormat(INDENT2 "%d: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
Jeff Browncc4f7db2011-08-30 20:34:48 -07003048 i, touchedWindow.windowHandle->getName().string(),
3049 touchedWindow.pointerIds.value,
Jeff Brownf2f48712010-10-01 17:46:21 -07003050 touchedWindow.targetFlags);
3051 }
3052 } else {
3053 dump.append(INDENT "TouchedWindows: <none>\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003054 }
3055
Jeff Brown9302c872011-07-13 22:51:29 -07003056 if (!mWindowHandles.isEmpty()) {
Jeff Brownf2f48712010-10-01 17:46:21 -07003057 dump.append(INDENT "Windows:\n");
Jeff Brown9302c872011-07-13 22:51:29 -07003058 for (size_t i = 0; i < mWindowHandles.size(); i++) {
3059 const sp<InputWindowHandle>& windowHandle = mWindowHandles.itemAt(i);
Jeff Browncc4f7db2011-08-30 20:34:48 -07003060 const InputWindowInfo* windowInfo = windowHandle->getInfo();
3061
Jeff Brownf2f48712010-10-01 17:46:21 -07003062 dump.appendFormat(INDENT2 "%d: name='%s', paused=%s, hasFocus=%s, hasWallpaper=%s, "
3063 "visible=%s, canReceiveKeys=%s, flags=0x%08x, type=0x%08x, layer=%d, "
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003064 "frame=[%d,%d][%d,%d], scale=%f, "
Jeff Brownfbf09772011-01-16 14:06:57 -08003065 "touchableRegion=",
Jeff Browncc4f7db2011-08-30 20:34:48 -07003066 i, windowInfo->name.string(),
3067 toString(windowInfo->paused),
3068 toString(windowInfo->hasFocus),
3069 toString(windowInfo->hasWallpaper),
3070 toString(windowInfo->visible),
3071 toString(windowInfo->canReceiveKeys),
3072 windowInfo->layoutParamsFlags, windowInfo->layoutParamsType,
3073 windowInfo->layer,
3074 windowInfo->frameLeft, windowInfo->frameTop,
3075 windowInfo->frameRight, windowInfo->frameBottom,
3076 windowInfo->scaleFactor);
3077 dumpRegion(dump, windowInfo->touchableRegion);
3078 dump.appendFormat(", inputFeatures=0x%08x", windowInfo->inputFeatures);
Jeff Brownfbf09772011-01-16 14:06:57 -08003079 dump.appendFormat(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%0.3fms\n",
Jeff Browncc4f7db2011-08-30 20:34:48 -07003080 windowInfo->ownerPid, windowInfo->ownerUid,
3081 windowInfo->dispatchingTimeout / 1000000.0);
Jeff Brownf2f48712010-10-01 17:46:21 -07003082 }
3083 } else {
3084 dump.append(INDENT "Windows: <none>\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003085 }
3086
Jeff Brownf2f48712010-10-01 17:46:21 -07003087 if (!mMonitoringChannels.isEmpty()) {
3088 dump.append(INDENT "MonitoringChannels:\n");
3089 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
3090 const sp<InputChannel>& channel = mMonitoringChannels[i];
3091 dump.appendFormat(INDENT2 "%d: '%s'\n", i, channel->getName().string());
3092 }
3093 } else {
3094 dump.append(INDENT "MonitoringChannels: <none>\n");
3095 }
Jeff Brown519e0242010-09-15 15:18:56 -07003096
Jeff Brown265f1cc2012-06-11 18:01:06 -07003097 nsecs_t currentTime = now();
3098
3099 if (!mInboundQueue.isEmpty()) {
3100 dump.appendFormat(INDENT "InboundQueue: length=%u\n", mInboundQueue.count());
3101 for (EventEntry* entry = mInboundQueue.head; entry; entry = entry->next) {
3102 dump.append(INDENT2);
3103 entry->appendDescription(dump);
Jeff Brown22aa5122012-06-17 12:01:06 -07003104 dump.appendFormat(", age=%0.1fms\n",
Jeff Brown265f1cc2012-06-11 18:01:06 -07003105 (currentTime - entry->eventTime) * 0.000001f);
3106 }
3107 } else {
3108 dump.append(INDENT "InboundQueue: <empty>\n");
3109 }
3110
3111 if (!mConnectionsByFd.isEmpty()) {
3112 dump.append(INDENT "Connections:\n");
3113 for (size_t i = 0; i < mConnectionsByFd.size(); i++) {
3114 const sp<Connection>& connection = mConnectionsByFd.valueAt(i);
3115 dump.appendFormat(INDENT2 "%d: channelName='%s', windowName='%s', "
3116 "status=%s, monitor=%s, inputPublisherBlocked=%s\n",
3117 i, connection->getInputChannelName(), connection->getWindowName(),
3118 connection->getStatusLabel(), toString(connection->monitor),
3119 toString(connection->inputPublisherBlocked));
3120
3121 if (!connection->outboundQueue.isEmpty()) {
3122 dump.appendFormat(INDENT3 "OutboundQueue: length=%u\n",
3123 connection->outboundQueue.count());
3124 for (DispatchEntry* entry = connection->outboundQueue.head; entry;
3125 entry = entry->next) {
3126 dump.append(INDENT4);
3127 entry->eventEntry->appendDescription(dump);
Jeff Brown22aa5122012-06-17 12:01:06 -07003128 dump.appendFormat(", targetFlags=0x%08x, resolvedAction=%d, age=%0.1fms\n",
Jeff Brown265f1cc2012-06-11 18:01:06 -07003129 entry->targetFlags, entry->resolvedAction,
3130 (currentTime - entry->eventEntry->eventTime) * 0.000001f);
3131 }
3132 } else {
3133 dump.append(INDENT3 "OutboundQueue: <empty>\n");
3134 }
3135
3136 if (!connection->waitQueue.isEmpty()) {
3137 dump.appendFormat(INDENT3 "WaitQueue: length=%u\n",
3138 connection->waitQueue.count());
3139 for (DispatchEntry* entry = connection->waitQueue.head; entry;
3140 entry = entry->next) {
3141 dump.append(INDENT4);
3142 entry->eventEntry->appendDescription(dump);
3143 dump.appendFormat(", targetFlags=0x%08x, resolvedAction=%d, "
Jeff Brown22aa5122012-06-17 12:01:06 -07003144 "age=%0.1fms, wait=%0.1fms\n",
Jeff Brown265f1cc2012-06-11 18:01:06 -07003145 entry->targetFlags, entry->resolvedAction,
3146 (currentTime - entry->eventEntry->eventTime) * 0.000001f,
3147 (currentTime - entry->deliveryTime) * 0.000001f);
3148 }
3149 } else {
3150 dump.append(INDENT3 "WaitQueue: <empty>\n");
3151 }
3152 }
3153 } else {
3154 dump.append(INDENT "Connections: <none>\n");
3155 }
Jeff Brownf2f48712010-10-01 17:46:21 -07003156
Jeff Brownb88102f2010-09-08 11:49:43 -07003157 if (isAppSwitchPendingLocked()) {
Jeff Brown22aa5122012-06-17 12:01:06 -07003158 dump.appendFormat(INDENT "AppSwitch: pending, due in %0.1fms\n",
Jeff Brownb88102f2010-09-08 11:49:43 -07003159 (mAppSwitchDueTime - now()) / 1000000.0);
3160 } else {
Jeff Brownf2f48712010-10-01 17:46:21 -07003161 dump.append(INDENT "AppSwitch: not pending\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003162 }
Jeff Brown22aa5122012-06-17 12:01:06 -07003163
3164 dump.append(INDENT "Configuration:\n");
3165 dump.appendFormat(INDENT2 "KeyRepeatDelay: %0.1fms\n",
3166 mConfig.keyRepeatDelay * 0.000001f);
3167 dump.appendFormat(INDENT2 "KeyRepeatTimeout: %0.1fms\n",
3168 mConfig.keyRepeatTimeout * 0.000001f);
Jeff Brownb88102f2010-09-08 11:49:43 -07003169}
3170
Jeff Brown928e0542011-01-10 11:17:36 -08003171status_t InputDispatcher::registerInputChannel(const sp<InputChannel>& inputChannel,
3172 const sp<InputWindowHandle>& inputWindowHandle, bool monitor) {
Jeff Brown9c3cda02010-06-15 01:31:58 -07003173#if DEBUG_REGISTRATION
Steve Block5baa3a62011-12-20 16:23:08 +00003174 ALOGD("channel '%s' ~ registerInputChannel - monitor=%s", inputChannel->getName().string(),
Jeff Brownb88102f2010-09-08 11:49:43 -07003175 toString(monitor));
Jeff Brown9c3cda02010-06-15 01:31:58 -07003176#endif
3177
Jeff Brown46b9ac02010-04-22 18:58:52 -07003178 { // acquire lock
3179 AutoMutex _l(mLock);
3180
Jeff Brown519e0242010-09-15 15:18:56 -07003181 if (getConnectionIndexLocked(inputChannel) >= 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00003182 ALOGW("Attempted to register already registered input channel '%s'",
Jeff Brown46b9ac02010-04-22 18:58:52 -07003183 inputChannel->getName().string());
3184 return BAD_VALUE;
3185 }
3186
Jeff Browncc4f7db2011-08-30 20:34:48 -07003187 sp<Connection> connection = new Connection(inputChannel, inputWindowHandle, monitor);
Jeff Brown46b9ac02010-04-22 18:58:52 -07003188
Jeff Brown91e32892012-02-14 15:56:29 -08003189 int fd = inputChannel->getFd();
Jeff Browncbee6d62012-02-03 20:11:27 -08003190 mConnectionsByFd.add(fd, connection);
Jeff Brown9c3cda02010-06-15 01:31:58 -07003191
Jeff Brownb88102f2010-09-08 11:49:43 -07003192 if (monitor) {
3193 mMonitoringChannels.push(inputChannel);
3194 }
3195
Jeff Browncbee6d62012-02-03 20:11:27 -08003196 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
Jeff Brown2cbecea2010-08-17 15:59:26 -07003197
Jeff Brown9c3cda02010-06-15 01:31:58 -07003198 runCommandsLockedInterruptible();
Jeff Brown46b9ac02010-04-22 18:58:52 -07003199 } // release lock
Jeff Brown46b9ac02010-04-22 18:58:52 -07003200 return OK;
3201}
3202
3203status_t InputDispatcher::unregisterInputChannel(const sp<InputChannel>& inputChannel) {
Jeff Brown9c3cda02010-06-15 01:31:58 -07003204#if DEBUG_REGISTRATION
Steve Block5baa3a62011-12-20 16:23:08 +00003205 ALOGD("channel '%s' ~ unregisterInputChannel", inputChannel->getName().string());
Jeff Brown9c3cda02010-06-15 01:31:58 -07003206#endif
3207
Jeff Brown46b9ac02010-04-22 18:58:52 -07003208 { // acquire lock
3209 AutoMutex _l(mLock);
3210
Jeff Browncc4f7db2011-08-30 20:34:48 -07003211 status_t status = unregisterInputChannelLocked(inputChannel, false /*notify*/);
3212 if (status) {
3213 return status;
Jeff Brown46b9ac02010-04-22 18:58:52 -07003214 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07003215 } // release lock
3216
Jeff Brown46b9ac02010-04-22 18:58:52 -07003217 // Wake the poll loop because removing the connection may have changed the current
3218 // synchronization state.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07003219 mLooper->wake();
Jeff Brown46b9ac02010-04-22 18:58:52 -07003220 return OK;
3221}
3222
Jeff Browncc4f7db2011-08-30 20:34:48 -07003223status_t InputDispatcher::unregisterInputChannelLocked(const sp<InputChannel>& inputChannel,
3224 bool notify) {
3225 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
3226 if (connectionIndex < 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00003227 ALOGW("Attempted to unregister already unregistered input channel '%s'",
Jeff Browncc4f7db2011-08-30 20:34:48 -07003228 inputChannel->getName().string());
3229 return BAD_VALUE;
3230 }
3231
Jeff Browncbee6d62012-02-03 20:11:27 -08003232 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
3233 mConnectionsByFd.removeItemsAt(connectionIndex);
Jeff Browncc4f7db2011-08-30 20:34:48 -07003234
3235 if (connection->monitor) {
3236 removeMonitorChannelLocked(inputChannel);
3237 }
3238
Jeff Browncbee6d62012-02-03 20:11:27 -08003239 mLooper->removeFd(inputChannel->getFd());
Jeff Browncc4f7db2011-08-30 20:34:48 -07003240
3241 nsecs_t currentTime = now();
3242 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
3243
3244 runCommandsLockedInterruptible();
3245
3246 connection->status = Connection::STATUS_ZOMBIE;
3247 return OK;
3248}
3249
3250void InputDispatcher::removeMonitorChannelLocked(const sp<InputChannel>& inputChannel) {
3251 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
3252 if (mMonitoringChannels[i] == inputChannel) {
3253 mMonitoringChannels.removeAt(i);
3254 break;
3255 }
3256 }
3257}
3258
Jeff Brown519e0242010-09-15 15:18:56 -07003259ssize_t InputDispatcher::getConnectionIndexLocked(const sp<InputChannel>& inputChannel) {
Jeff Browncbee6d62012-02-03 20:11:27 -08003260 ssize_t connectionIndex = mConnectionsByFd.indexOfKey(inputChannel->getFd());
Jeff Brown2cbecea2010-08-17 15:59:26 -07003261 if (connectionIndex >= 0) {
Jeff Browncbee6d62012-02-03 20:11:27 -08003262 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
Jeff Brown2cbecea2010-08-17 15:59:26 -07003263 if (connection->inputChannel.get() == inputChannel.get()) {
3264 return connectionIndex;
3265 }
3266 }
3267
3268 return -1;
3269}
3270
Jeff Brown9c3cda02010-06-15 01:31:58 -07003271void InputDispatcher::onDispatchCycleFinishedLocked(
Jeff Brown072ec962012-02-07 14:46:57 -08003272 nsecs_t currentTime, const sp<Connection>& connection, uint32_t seq, bool handled) {
Jeff Brown3915bb82010-11-05 15:02:16 -07003273 CommandEntry* commandEntry = postCommandLocked(
3274 & InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
3275 commandEntry->connection = connection;
Jeff Brown265f1cc2012-06-11 18:01:06 -07003276 commandEntry->eventTime = currentTime;
Jeff Brown072ec962012-02-07 14:46:57 -08003277 commandEntry->seq = seq;
Jeff Brown3915bb82010-11-05 15:02:16 -07003278 commandEntry->handled = handled;
Jeff Brown46b9ac02010-04-22 18:58:52 -07003279}
3280
Jeff Brown9c3cda02010-06-15 01:31:58 -07003281void InputDispatcher::onDispatchCycleBrokenLocked(
Jeff Brown7fbdc842010-06-17 20:52:56 -07003282 nsecs_t currentTime, const sp<Connection>& connection) {
Steve Block3762c312012-01-06 19:20:56 +00003283 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Jeff Brown46b9ac02010-04-22 18:58:52 -07003284 connection->getInputChannelName());
3285
Jeff Brown9c3cda02010-06-15 01:31:58 -07003286 CommandEntry* commandEntry = postCommandLocked(
3287 & InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
Jeff Brown7fbdc842010-06-17 20:52:56 -07003288 commandEntry->connection = connection;
Jeff Brown46b9ac02010-04-22 18:58:52 -07003289}
3290
Jeff Brown519e0242010-09-15 15:18:56 -07003291void InputDispatcher::onANRLocked(
Jeff Brown9302c872011-07-13 22:51:29 -07003292 nsecs_t currentTime, const sp<InputApplicationHandle>& applicationHandle,
3293 const sp<InputWindowHandle>& windowHandle,
Jeff Brown265f1cc2012-06-11 18:01:06 -07003294 nsecs_t eventTime, nsecs_t waitStartTime, const char* reason) {
Jeff Brown22aa5122012-06-17 12:01:06 -07003295 float dispatchLatency = (currentTime - eventTime) * 0.000001f;
3296 float waitDuration = (currentTime - waitStartTime) * 0.000001f;
Steve Block6215d3f2012-01-04 20:05:49 +00003297 ALOGI("Application is not responding: %s. "
Jeff Brown22aa5122012-06-17 12:01:06 -07003298 "It has been %0.1fms since event, %0.1fms since wait started. Reason: %s",
Jeff Brown9302c872011-07-13 22:51:29 -07003299 getApplicationWindowLabelLocked(applicationHandle, windowHandle).string(),
Jeff Brown22aa5122012-06-17 12:01:06 -07003300 dispatchLatency, waitDuration, reason);
3301
3302 // Capture a record of the InputDispatcher state at the time of the ANR.
3303 time_t t = time(NULL);
3304 struct tm tm;
3305 localtime_r(&t, &tm);
3306 char timestr[64];
3307 strftime(timestr, sizeof(timestr), "%F %T", &tm);
3308 mLastANRState.clear();
3309 mLastANRState.append(INDENT "ANR:\n");
3310 mLastANRState.appendFormat(INDENT2 "Time: %s\n", timestr);
3311 mLastANRState.appendFormat(INDENT2 "Window: %s\n",
3312 getApplicationWindowLabelLocked(applicationHandle, windowHandle).string());
3313 mLastANRState.appendFormat(INDENT2 "DispatchLatency: %0.1fms\n", dispatchLatency);
3314 mLastANRState.appendFormat(INDENT2 "WaitDuration: %0.1fms\n", waitDuration);
3315 mLastANRState.appendFormat(INDENT2 "Reason: %s\n", reason);
3316 dumpDispatchStateLocked(mLastANRState);
Jeff Brown519e0242010-09-15 15:18:56 -07003317
3318 CommandEntry* commandEntry = postCommandLocked(
3319 & InputDispatcher::doNotifyANRLockedInterruptible);
Jeff Brown9302c872011-07-13 22:51:29 -07003320 commandEntry->inputApplicationHandle = applicationHandle;
3321 commandEntry->inputWindowHandle = windowHandle;
Jeff Brown519e0242010-09-15 15:18:56 -07003322}
3323
Jeff Brownb88102f2010-09-08 11:49:43 -07003324void InputDispatcher::doNotifyConfigurationChangedInterruptible(
3325 CommandEntry* commandEntry) {
3326 mLock.unlock();
3327
3328 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
3329
3330 mLock.lock();
3331}
3332
Jeff Brown9c3cda02010-06-15 01:31:58 -07003333void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(
3334 CommandEntry* commandEntry) {
Jeff Brown7fbdc842010-06-17 20:52:56 -07003335 sp<Connection> connection = commandEntry->connection;
Jeff Brown9c3cda02010-06-15 01:31:58 -07003336
Jeff Brown7fbdc842010-06-17 20:52:56 -07003337 if (connection->status != Connection::STATUS_ZOMBIE) {
3338 mLock.unlock();
Jeff Brown9c3cda02010-06-15 01:31:58 -07003339
Jeff Brown928e0542011-01-10 11:17:36 -08003340 mPolicy->notifyInputChannelBroken(connection->inputWindowHandle);
Jeff Brown7fbdc842010-06-17 20:52:56 -07003341
3342 mLock.lock();
3343 }
Jeff Brown9c3cda02010-06-15 01:31:58 -07003344}
3345
Jeff Brown519e0242010-09-15 15:18:56 -07003346void InputDispatcher::doNotifyANRLockedInterruptible(
Jeff Brown9c3cda02010-06-15 01:31:58 -07003347 CommandEntry* commandEntry) {
Jeff Brown519e0242010-09-15 15:18:56 -07003348 mLock.unlock();
Jeff Brown9c3cda02010-06-15 01:31:58 -07003349
Jeff Brown519e0242010-09-15 15:18:56 -07003350 nsecs_t newTimeout = mPolicy->notifyANR(
Jeff Brown928e0542011-01-10 11:17:36 -08003351 commandEntry->inputApplicationHandle, commandEntry->inputWindowHandle);
Jeff Brown9c3cda02010-06-15 01:31:58 -07003352
Jeff Brown519e0242010-09-15 15:18:56 -07003353 mLock.lock();
Jeff Brown7fbdc842010-06-17 20:52:56 -07003354
Jeff Brown9302c872011-07-13 22:51:29 -07003355 resumeAfterTargetsNotReadyTimeoutLocked(newTimeout,
3356 commandEntry->inputWindowHandle != NULL
Jeff Browncc4f7db2011-08-30 20:34:48 -07003357 ? commandEntry->inputWindowHandle->getInputChannel() : NULL);
Jeff Brown9c3cda02010-06-15 01:31:58 -07003358}
3359
Jeff Brownb88102f2010-09-08 11:49:43 -07003360void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
3361 CommandEntry* commandEntry) {
3362 KeyEntry* entry = commandEntry->keyEntry;
Jeff Brown1f245102010-11-18 20:53:46 -08003363
3364 KeyEvent event;
3365 initializeKeyEvent(&event, entry);
Jeff Brownb88102f2010-09-08 11:49:43 -07003366
3367 mLock.unlock();
3368
Jeff Brown905805a2011-10-12 13:57:59 -07003369 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(commandEntry->inputWindowHandle,
Jeff Brown1f245102010-11-18 20:53:46 -08003370 &event, entry->policyFlags);
Jeff Brownb88102f2010-09-08 11:49:43 -07003371
3372 mLock.lock();
3373
Jeff Brown905805a2011-10-12 13:57:59 -07003374 if (delay < 0) {
3375 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
3376 } else if (!delay) {
3377 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
3378 } else {
3379 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
3380 entry->interceptKeyWakeupTime = now() + delay;
3381 }
Jeff Brownac386072011-07-20 15:19:50 -07003382 entry->release();
Jeff Brownb88102f2010-09-08 11:49:43 -07003383}
3384
Jeff Brown3915bb82010-11-05 15:02:16 -07003385void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(
3386 CommandEntry* commandEntry) {
3387 sp<Connection> connection = commandEntry->connection;
Jeff Brown265f1cc2012-06-11 18:01:06 -07003388 nsecs_t finishTime = commandEntry->eventTime;
Jeff Brown072ec962012-02-07 14:46:57 -08003389 uint32_t seq = commandEntry->seq;
Jeff Brown3915bb82010-11-05 15:02:16 -07003390 bool handled = commandEntry->handled;
3391
Jeff Brown072ec962012-02-07 14:46:57 -08003392 // Handle post-event policy actions.
3393 DispatchEntry* dispatchEntry = connection->findWaitQueueEntry(seq);
3394 if (dispatchEntry) {
Jeff Brown265f1cc2012-06-11 18:01:06 -07003395 nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
3396 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
3397 String8 msg;
Jeff Brown22aa5122012-06-17 12:01:06 -07003398 msg.appendFormat("Window '%s' spent %0.1fms processing the last input event: ",
Jeff Brown265f1cc2012-06-11 18:01:06 -07003399 connection->getWindowName(), eventDuration * 0.000001f);
3400 dispatchEntry->eventEntry->appendDescription(msg);
3401 ALOGI("%s", msg.string());
3402 }
3403
Jeff Brownd1c48a02012-02-06 19:12:47 -08003404 bool restartEvent;
Jeff Brownd1c48a02012-02-06 19:12:47 -08003405 if (dispatchEntry->eventEntry->type == EventEntry::TYPE_KEY) {
3406 KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry);
3407 restartEvent = afterKeyEventLockedInterruptible(connection,
3408 dispatchEntry, keyEntry, handled);
3409 } else if (dispatchEntry->eventEntry->type == EventEntry::TYPE_MOTION) {
3410 MotionEntry* motionEntry = static_cast<MotionEntry*>(dispatchEntry->eventEntry);
3411 restartEvent = afterMotionEventLockedInterruptible(connection,
3412 dispatchEntry, motionEntry, handled);
3413 } else {
3414 restartEvent = false;
3415 }
3416
3417 // Dequeue the event and start the next cycle.
3418 // Note that because the lock might have been released, it is possible that the
3419 // contents of the wait queue to have been drained, so we need to double-check
3420 // a few things.
Jeff Brown072ec962012-02-07 14:46:57 -08003421 if (dispatchEntry == connection->findWaitQueueEntry(seq)) {
3422 connection->waitQueue.dequeue(dispatchEntry);
Jeff Brown481c1572012-03-09 14:41:15 -08003423 traceWaitQueueLengthLocked(connection);
Jeff Brownd1c48a02012-02-06 19:12:47 -08003424 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
3425 connection->outboundQueue.enqueueAtHead(dispatchEntry);
Jeff Brown481c1572012-03-09 14:41:15 -08003426 traceOutboundQueueLengthLocked(connection);
Jeff Brownd1c48a02012-02-06 19:12:47 -08003427 } else {
3428 releaseDispatchEntryLocked(dispatchEntry);
Jeff Brown49ed71d2010-12-06 17:13:33 -08003429 }
Jeff Brown3915bb82010-11-05 15:02:16 -07003430 }
Jeff Brown3915bb82010-11-05 15:02:16 -07003431
Jeff Brownd1c48a02012-02-06 19:12:47 -08003432 // Start the next dispatch cycle for this connection.
3433 startDispatchCycleLocked(now(), connection);
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003434 }
3435}
3436
3437bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
3438 DispatchEntry* dispatchEntry, KeyEntry* keyEntry, bool handled) {
3439 if (!(keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK)) {
3440 // Get the fallback key state.
3441 // Clear it out after dispatching the UP.
3442 int32_t originalKeyCode = keyEntry->keyCode;
3443 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
3444 if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
3445 connection->inputState.removeFallbackKey(originalKeyCode);
3446 }
3447
3448 if (handled || !dispatchEntry->hasForegroundTarget()) {
3449 // If the application handles the original key for which we previously
3450 // generated a fallback or if the window is not a foreground window,
3451 // then cancel the associated fallback key, if any.
3452 if (fallbackKeyCode != -1) {
Jeff Brownfd23e3e2012-05-09 13:34:28 -07003453 // Dispatch the unhandled key to the policy with the cancel flag.
3454#if DEBUG_OUTBOUND_EVENT_DETAILS
3455 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
3456 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
3457 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
3458 keyEntry->policyFlags);
3459#endif
3460 KeyEvent event;
3461 initializeKeyEvent(&event, keyEntry);
3462 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
3463
3464 mLock.unlock();
3465
3466 mPolicy->dispatchUnhandledKey(connection->inputWindowHandle,
3467 &event, keyEntry->policyFlags, &event);
3468
3469 mLock.lock();
3470
3471 // Cancel the fallback key.
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003472 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
3473 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
3474 "application handled the original non-fallback key "
3475 "or is no longer a foreground target, "
3476 "canceling previously dispatched fallback key");
3477 options.keyCode = fallbackKeyCode;
3478 synthesizeCancelationEventsForConnectionLocked(connection, options);
3479 }
3480 connection->inputState.removeFallbackKey(originalKeyCode);
3481 }
3482 } else {
3483 // If the application did not handle a non-fallback key, first check
3484 // that we are in a good state to perform unhandled key event processing
3485 // Then ask the policy what to do with it.
3486 bool initialDown = keyEntry->action == AKEY_EVENT_ACTION_DOWN
3487 && keyEntry->repeatCount == 0;
3488 if (fallbackKeyCode == -1 && !initialDown) {
3489#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00003490 ALOGD("Unhandled key event: Skipping unhandled key event processing "
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003491 "since this is not an initial down. "
Jeff Brownfd23e3e2012-05-09 13:34:28 -07003492 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
3493 originalKeyCode, keyEntry->action, keyEntry->repeatCount,
3494 keyEntry->policyFlags);
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003495#endif
3496 return false;
3497 }
3498
3499 // Dispatch the unhandled key to the policy.
3500#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00003501 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
Jeff Brownfd23e3e2012-05-09 13:34:28 -07003502 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
3503 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
3504 keyEntry->policyFlags);
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003505#endif
3506 KeyEvent event;
3507 initializeKeyEvent(&event, keyEntry);
3508
3509 mLock.unlock();
3510
3511 bool fallback = mPolicy->dispatchUnhandledKey(connection->inputWindowHandle,
3512 &event, keyEntry->policyFlags, &event);
3513
3514 mLock.lock();
3515
3516 if (connection->status != Connection::STATUS_NORMAL) {
3517 connection->inputState.removeFallbackKey(originalKeyCode);
Jeff Brownd1c48a02012-02-06 19:12:47 -08003518 return false;
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003519 }
3520
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003521 // Latch the fallback keycode for this key on an initial down.
3522 // The fallback keycode cannot change at any other point in the lifecycle.
3523 if (initialDown) {
3524 if (fallback) {
3525 fallbackKeyCode = event.getKeyCode();
3526 } else {
3527 fallbackKeyCode = AKEYCODE_UNKNOWN;
3528 }
3529 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
3530 }
3531
Steve Blockec193de2012-01-09 18:35:44 +00003532 ALOG_ASSERT(fallbackKeyCode != -1);
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003533
3534 // Cancel the fallback key if the policy decides not to send it anymore.
3535 // We will continue to dispatch the key to the policy but we will no
3536 // longer dispatch a fallback key to the application.
3537 if (fallbackKeyCode != AKEYCODE_UNKNOWN
3538 && (!fallback || fallbackKeyCode != event.getKeyCode())) {
3539#if DEBUG_OUTBOUND_EVENT_DETAILS
3540 if (fallback) {
Steve Block5baa3a62011-12-20 16:23:08 +00003541 ALOGD("Unhandled key event: Policy requested to send key %d"
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003542 "as a fallback for %d, but on the DOWN it had requested "
3543 "to send %d instead. Fallback canceled.",
3544 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
3545 } else {
Jeff Brownfd23e3e2012-05-09 13:34:28 -07003546 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003547 "but on the DOWN it had requested to send %d. "
3548 "Fallback canceled.",
3549 originalKeyCode, fallbackKeyCode);
3550 }
3551#endif
3552
3553 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
3554 "canceling fallback, policy no longer desires it");
3555 options.keyCode = fallbackKeyCode;
3556 synthesizeCancelationEventsForConnectionLocked(connection, options);
3557
3558 fallback = false;
3559 fallbackKeyCode = AKEYCODE_UNKNOWN;
3560 if (keyEntry->action != AKEY_EVENT_ACTION_UP) {
3561 connection->inputState.setFallbackKey(originalKeyCode,
3562 fallbackKeyCode);
3563 }
3564 }
3565
3566#if DEBUG_OUTBOUND_EVENT_DETAILS
3567 {
3568 String8 msg;
3569 const KeyedVector<int32_t, int32_t>& fallbackKeys =
3570 connection->inputState.getFallbackKeys();
3571 for (size_t i = 0; i < fallbackKeys.size(); i++) {
3572 msg.appendFormat(", %d->%d", fallbackKeys.keyAt(i),
3573 fallbackKeys.valueAt(i));
3574 }
Steve Block5baa3a62011-12-20 16:23:08 +00003575 ALOGD("Unhandled key event: %d currently tracked fallback keys%s.",
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003576 fallbackKeys.size(), msg.string());
3577 }
3578#endif
3579
3580 if (fallback) {
3581 // Restart the dispatch cycle using the fallback key.
3582 keyEntry->eventTime = event.getEventTime();
3583 keyEntry->deviceId = event.getDeviceId();
3584 keyEntry->source = event.getSource();
3585 keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
3586 keyEntry->keyCode = fallbackKeyCode;
3587 keyEntry->scanCode = event.getScanCode();
3588 keyEntry->metaState = event.getMetaState();
3589 keyEntry->repeatCount = event.getRepeatCount();
3590 keyEntry->downTime = event.getDownTime();
3591 keyEntry->syntheticRepeat = false;
3592
3593#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00003594 ALOGD("Unhandled key event: Dispatching fallback key. "
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003595 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
3596 originalKeyCode, fallbackKeyCode, keyEntry->metaState);
3597#endif
Jeff Brownd1c48a02012-02-06 19:12:47 -08003598 return true; // restart the event
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003599 } else {
3600#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00003601 ALOGD("Unhandled key event: No fallback key.");
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003602#endif
3603 }
3604 }
3605 }
3606 return false;
3607}
3608
3609bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
3610 DispatchEntry* dispatchEntry, MotionEntry* motionEntry, bool handled) {
3611 return false;
Jeff Brown3915bb82010-11-05 15:02:16 -07003612}
3613
Jeff Brownb88102f2010-09-08 11:49:43 -07003614void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
3615 mLock.unlock();
3616
Jeff Brown01ce2e92010-09-26 22:20:12 -07003617 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
Jeff Brownb88102f2010-09-08 11:49:43 -07003618
3619 mLock.lock();
3620}
3621
Jeff Brown3915bb82010-11-05 15:02:16 -07003622void InputDispatcher::initializeKeyEvent(KeyEvent* event, const KeyEntry* entry) {
3623 event->initialize(entry->deviceId, entry->source, entry->action, entry->flags,
3624 entry->keyCode, entry->scanCode, entry->metaState, entry->repeatCount,
3625 entry->downTime, entry->eventTime);
3626}
3627
Jeff Brown519e0242010-09-15 15:18:56 -07003628void InputDispatcher::updateDispatchStatisticsLocked(nsecs_t currentTime, const EventEntry* entry,
3629 int32_t injectionResult, nsecs_t timeSpentWaitingForApplication) {
3630 // TODO Write some statistics about how long we spend waiting.
Jeff Brownb88102f2010-09-08 11:49:43 -07003631}
3632
Jeff Brown481c1572012-03-09 14:41:15 -08003633void InputDispatcher::traceInboundQueueLengthLocked() {
3634 if (ATRACE_ENABLED()) {
3635 ATRACE_INT("iq", mInboundQueue.count());
3636 }
3637}
3638
3639void InputDispatcher::traceOutboundQueueLengthLocked(const sp<Connection>& connection) {
3640 if (ATRACE_ENABLED()) {
3641 char counterName[40];
3642 snprintf(counterName, sizeof(counterName), "oq:%s", connection->getWindowName());
3643 ATRACE_INT(counterName, connection->outboundQueue.count());
3644 }
3645}
3646
3647void InputDispatcher::traceWaitQueueLengthLocked(const sp<Connection>& connection) {
3648 if (ATRACE_ENABLED()) {
3649 char counterName[40];
3650 snprintf(counterName, sizeof(counterName), "wq:%s", connection->getWindowName());
3651 ATRACE_INT(counterName, connection->waitQueue.count());
3652 }
3653}
3654
Jeff Brownb88102f2010-09-08 11:49:43 -07003655void InputDispatcher::dump(String8& dump) {
Jeff Brown89ef0722011-08-10 16:25:21 -07003656 AutoMutex _l(mLock);
3657
Jeff Brownf2f48712010-10-01 17:46:21 -07003658 dump.append("Input Dispatcher State:\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003659 dumpDispatchStateLocked(dump);
Jeff Brown214eaf42011-05-26 19:17:02 -07003660
Jeff Brown22aa5122012-06-17 12:01:06 -07003661 if (!mLastANRState.isEmpty()) {
3662 dump.append("\nInput Dispatcher State at time of last ANR:\n");
3663 dump.append(mLastANRState);
3664 }
Jeff Brownb88102f2010-09-08 11:49:43 -07003665}
3666
Jeff Brown89ef0722011-08-10 16:25:21 -07003667void InputDispatcher::monitor() {
3668 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
3669 mLock.lock();
Jeff Brown112b5f52012-01-27 17:32:06 -08003670 mLooper->wake();
3671 mDispatcherIsAliveCondition.wait(mLock);
Jeff Brown89ef0722011-08-10 16:25:21 -07003672 mLock.unlock();
3673}
3674
Jeff Brown9c3cda02010-06-15 01:31:58 -07003675
Jeff Brown519e0242010-09-15 15:18:56 -07003676// --- InputDispatcher::Queue ---
3677
3678template <typename T>
3679uint32_t InputDispatcher::Queue<T>::count() const {
3680 uint32_t result = 0;
Jeff Brownac386072011-07-20 15:19:50 -07003681 for (const T* entry = head; entry; entry = entry->next) {
Jeff Brown519e0242010-09-15 15:18:56 -07003682 result += 1;
3683 }
3684 return result;
3685}
3686
3687
Jeff Brownac386072011-07-20 15:19:50 -07003688// --- InputDispatcher::InjectionState ---
Jeff Brown46b9ac02010-04-22 18:58:52 -07003689
Jeff Brownac386072011-07-20 15:19:50 -07003690InputDispatcher::InjectionState::InjectionState(int32_t injectorPid, int32_t injectorUid) :
3691 refCount(1),
3692 injectorPid(injectorPid), injectorUid(injectorUid),
3693 injectionResult(INPUT_EVENT_INJECTION_PENDING), injectionIsAsync(false),
3694 pendingForegroundDispatches(0) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07003695}
3696
Jeff Brownac386072011-07-20 15:19:50 -07003697InputDispatcher::InjectionState::~InjectionState() {
Jeff Brown01ce2e92010-09-26 22:20:12 -07003698}
3699
Jeff Brownac386072011-07-20 15:19:50 -07003700void InputDispatcher::InjectionState::release() {
3701 refCount -= 1;
3702 if (refCount == 0) {
3703 delete this;
3704 } else {
Steve Blockec193de2012-01-09 18:35:44 +00003705 ALOG_ASSERT(refCount > 0);
Jeff Brown01ce2e92010-09-26 22:20:12 -07003706 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07003707}
3708
Jeff Brownac386072011-07-20 15:19:50 -07003709
3710// --- InputDispatcher::EventEntry ---
3711
3712InputDispatcher::EventEntry::EventEntry(int32_t type, nsecs_t eventTime, uint32_t policyFlags) :
3713 refCount(1), type(type), eventTime(eventTime), policyFlags(policyFlags),
3714 injectionState(NULL), dispatchInProgress(false) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07003715}
3716
Jeff Brownac386072011-07-20 15:19:50 -07003717InputDispatcher::EventEntry::~EventEntry() {
3718 releaseInjectionState();
3719}
3720
3721void InputDispatcher::EventEntry::release() {
3722 refCount -= 1;
3723 if (refCount == 0) {
3724 delete this;
3725 } else {
Steve Blockec193de2012-01-09 18:35:44 +00003726 ALOG_ASSERT(refCount > 0);
Jeff Brownac386072011-07-20 15:19:50 -07003727 }
3728}
3729
3730void InputDispatcher::EventEntry::releaseInjectionState() {
3731 if (injectionState) {
3732 injectionState->release();
3733 injectionState = NULL;
3734 }
3735}
3736
3737
3738// --- InputDispatcher::ConfigurationChangedEntry ---
3739
3740InputDispatcher::ConfigurationChangedEntry::ConfigurationChangedEntry(nsecs_t eventTime) :
3741 EventEntry(TYPE_CONFIGURATION_CHANGED, eventTime, 0) {
3742}
3743
3744InputDispatcher::ConfigurationChangedEntry::~ConfigurationChangedEntry() {
3745}
3746
Jeff Brown265f1cc2012-06-11 18:01:06 -07003747void InputDispatcher::ConfigurationChangedEntry::appendDescription(String8& msg) const {
3748 msg.append("ConfigurationChangedEvent()");
3749}
3750
Jeff Brownac386072011-07-20 15:19:50 -07003751
Jeff Brown65fd2512011-08-18 11:20:58 -07003752// --- InputDispatcher::DeviceResetEntry ---
3753
3754InputDispatcher::DeviceResetEntry::DeviceResetEntry(nsecs_t eventTime, int32_t deviceId) :
3755 EventEntry(TYPE_DEVICE_RESET, eventTime, 0),
3756 deviceId(deviceId) {
3757}
3758
3759InputDispatcher::DeviceResetEntry::~DeviceResetEntry() {
3760}
3761
Jeff Brown265f1cc2012-06-11 18:01:06 -07003762void InputDispatcher::DeviceResetEntry::appendDescription(String8& msg) const {
3763 msg.appendFormat("DeviceResetEvent(deviceId=%d)", deviceId);
3764}
3765
Jeff Brown65fd2512011-08-18 11:20:58 -07003766
Jeff Brownac386072011-07-20 15:19:50 -07003767// --- InputDispatcher::KeyEntry ---
3768
3769InputDispatcher::KeyEntry::KeyEntry(nsecs_t eventTime,
Jeff Brown58a2da82011-01-25 16:02:22 -08003770 int32_t deviceId, uint32_t source, uint32_t policyFlags, int32_t action,
Jeff Brown7fbdc842010-06-17 20:52:56 -07003771 int32_t flags, int32_t keyCode, int32_t scanCode, int32_t metaState,
Jeff Brownac386072011-07-20 15:19:50 -07003772 int32_t repeatCount, nsecs_t downTime) :
3773 EventEntry(TYPE_KEY, eventTime, policyFlags),
3774 deviceId(deviceId), source(source), action(action), flags(flags),
3775 keyCode(keyCode), scanCode(scanCode), metaState(metaState),
3776 repeatCount(repeatCount), downTime(downTime),
Jeff Brown905805a2011-10-12 13:57:59 -07003777 syntheticRepeat(false), interceptKeyResult(KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN),
3778 interceptKeyWakeupTime(0) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07003779}
3780
Jeff Brownac386072011-07-20 15:19:50 -07003781InputDispatcher::KeyEntry::~KeyEntry() {
3782}
Jeff Brown7fbdc842010-06-17 20:52:56 -07003783
Jeff Brown265f1cc2012-06-11 18:01:06 -07003784void InputDispatcher::KeyEntry::appendDescription(String8& msg) const {
3785 msg.appendFormat("KeyEvent(action=%d, deviceId=%d, source=0x%08x)",
3786 action, deviceId, source);
3787}
3788
Jeff Brownac386072011-07-20 15:19:50 -07003789void InputDispatcher::KeyEntry::recycle() {
3790 releaseInjectionState();
3791
3792 dispatchInProgress = false;
3793 syntheticRepeat = false;
3794 interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
Jeff Brown905805a2011-10-12 13:57:59 -07003795 interceptKeyWakeupTime = 0;
Jeff Brownac386072011-07-20 15:19:50 -07003796}
3797
3798
Jeff Brownae9fc032010-08-18 15:51:08 -07003799// --- InputDispatcher::MotionEntry ---
3800
Jeff Brownac386072011-07-20 15:19:50 -07003801InputDispatcher::MotionEntry::MotionEntry(nsecs_t eventTime,
3802 int32_t deviceId, uint32_t source, uint32_t policyFlags, int32_t action, int32_t flags,
3803 int32_t metaState, int32_t buttonState,
3804 int32_t edgeFlags, float xPrecision, float yPrecision,
3805 nsecs_t downTime, uint32_t pointerCount,
3806 const PointerProperties* pointerProperties, const PointerCoords* pointerCoords) :
3807 EventEntry(TYPE_MOTION, eventTime, policyFlags),
Jeff Brown3241b6b2012-02-03 15:08:02 -08003808 eventTime(eventTime),
Jeff Brownac386072011-07-20 15:19:50 -07003809 deviceId(deviceId), source(source), action(action), flags(flags),
3810 metaState(metaState), buttonState(buttonState), edgeFlags(edgeFlags),
3811 xPrecision(xPrecision), yPrecision(yPrecision),
Jeff Brown3241b6b2012-02-03 15:08:02 -08003812 downTime(downTime), pointerCount(pointerCount) {
Jeff Brownac386072011-07-20 15:19:50 -07003813 for (uint32_t i = 0; i < pointerCount; i++) {
3814 this->pointerProperties[i].copyFrom(pointerProperties[i]);
Jeff Brown3241b6b2012-02-03 15:08:02 -08003815 this->pointerCoords[i].copyFrom(pointerCoords[i]);
Jeff Brownac386072011-07-20 15:19:50 -07003816 }
3817}
3818
3819InputDispatcher::MotionEntry::~MotionEntry() {
Jeff Brownac386072011-07-20 15:19:50 -07003820}
3821
Jeff Brown265f1cc2012-06-11 18:01:06 -07003822void InputDispatcher::MotionEntry::appendDescription(String8& msg) const {
3823 msg.appendFormat("MotionEvent(action=%d, deviceId=%d, source=0x%08x)",
3824 action, deviceId, source);
3825}
3826
Jeff Brownac386072011-07-20 15:19:50 -07003827
3828// --- InputDispatcher::DispatchEntry ---
3829
Jeff Brown072ec962012-02-07 14:46:57 -08003830volatile int32_t InputDispatcher::DispatchEntry::sNextSeqAtomic;
3831
Jeff Brownac386072011-07-20 15:19:50 -07003832InputDispatcher::DispatchEntry::DispatchEntry(EventEntry* eventEntry,
3833 int32_t targetFlags, float xOffset, float yOffset, float scaleFactor) :
Jeff Brown072ec962012-02-07 14:46:57 -08003834 seq(nextSeq()),
Jeff Brownac386072011-07-20 15:19:50 -07003835 eventEntry(eventEntry), targetFlags(targetFlags),
3836 xOffset(xOffset), yOffset(yOffset), scaleFactor(scaleFactor),
Jeff Brown265f1cc2012-06-11 18:01:06 -07003837 deliveryTime(0), resolvedAction(0), resolvedFlags(0) {
Jeff Brownac386072011-07-20 15:19:50 -07003838 eventEntry->refCount += 1;
3839}
3840
3841InputDispatcher::DispatchEntry::~DispatchEntry() {
3842 eventEntry->release();
3843}
3844
Jeff Brown072ec962012-02-07 14:46:57 -08003845uint32_t InputDispatcher::DispatchEntry::nextSeq() {
3846 // Sequence number 0 is reserved and will never be returned.
3847 uint32_t seq;
3848 do {
3849 seq = android_atomic_inc(&sNextSeqAtomic);
3850 } while (!seq);
3851 return seq;
3852}
3853
Jeff Brownb88102f2010-09-08 11:49:43 -07003854
3855// --- InputDispatcher::InputState ---
3856
Jeff Brownb6997262010-10-08 22:31:17 -07003857InputDispatcher::InputState::InputState() {
Jeff Brownb88102f2010-09-08 11:49:43 -07003858}
3859
3860InputDispatcher::InputState::~InputState() {
3861}
3862
3863bool InputDispatcher::InputState::isNeutral() const {
3864 return mKeyMementos.isEmpty() && mMotionMementos.isEmpty();
3865}
3866
Jeff Brown81346812011-06-28 20:08:48 -07003867bool InputDispatcher::InputState::isHovering(int32_t deviceId, uint32_t source) const {
3868 for (size_t i = 0; i < mMotionMementos.size(); i++) {
3869 const MotionMemento& memento = mMotionMementos.itemAt(i);
3870 if (memento.deviceId == deviceId
3871 && memento.source == source
3872 && memento.hovering) {
3873 return true;
3874 }
3875 }
3876 return false;
3877}
Jeff Brownb88102f2010-09-08 11:49:43 -07003878
Jeff Brown81346812011-06-28 20:08:48 -07003879bool InputDispatcher::InputState::trackKey(const KeyEntry* entry,
3880 int32_t action, int32_t flags) {
3881 switch (action) {
3882 case AKEY_EVENT_ACTION_UP: {
3883 if (entry->flags & AKEY_EVENT_FLAG_FALLBACK) {
3884 for (size_t i = 0; i < mFallbackKeys.size(); ) {
3885 if (mFallbackKeys.valueAt(i) == entry->keyCode) {
3886 mFallbackKeys.removeItemsAt(i);
3887 } else {
3888 i += 1;
3889 }
3890 }
3891 }
3892 ssize_t index = findKeyMemento(entry);
3893 if (index >= 0) {
3894 mKeyMementos.removeAt(index);
3895 return true;
3896 }
Jeff Brown68b909d2011-12-07 16:36:01 -08003897 /* FIXME: We can't just drop the key up event because that prevents creating
3898 * popup windows that are automatically shown when a key is held and then
3899 * dismissed when the key is released. The problem is that the popup will
3900 * not have received the original key down, so the key up will be considered
3901 * to be inconsistent with its observed state. We could perhaps handle this
3902 * by synthesizing a key down but that will cause other problems.
3903 *
3904 * So for now, allow inconsistent key up events to be dispatched.
3905 *
Jeff Brown81346812011-06-28 20:08:48 -07003906#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00003907 ALOGD("Dropping inconsistent key up event: deviceId=%d, source=%08x, "
Jeff Brown81346812011-06-28 20:08:48 -07003908 "keyCode=%d, scanCode=%d",
3909 entry->deviceId, entry->source, entry->keyCode, entry->scanCode);
3910#endif
3911 return false;
Jeff Brown68b909d2011-12-07 16:36:01 -08003912 */
3913 return true;
Jeff Brown81346812011-06-28 20:08:48 -07003914 }
3915
3916 case AKEY_EVENT_ACTION_DOWN: {
3917 ssize_t index = findKeyMemento(entry);
3918 if (index >= 0) {
3919 mKeyMementos.removeAt(index);
3920 }
3921 addKeyMemento(entry, flags);
3922 return true;
3923 }
3924
3925 default:
3926 return true;
Jeff Brownb88102f2010-09-08 11:49:43 -07003927 }
3928}
3929
Jeff Brown81346812011-06-28 20:08:48 -07003930bool InputDispatcher::InputState::trackMotion(const MotionEntry* entry,
3931 int32_t action, int32_t flags) {
3932 int32_t actionMasked = action & AMOTION_EVENT_ACTION_MASK;
3933 switch (actionMasked) {
3934 case AMOTION_EVENT_ACTION_UP:
3935 case AMOTION_EVENT_ACTION_CANCEL: {
3936 ssize_t index = findMotionMemento(entry, false /*hovering*/);
3937 if (index >= 0) {
3938 mMotionMementos.removeAt(index);
3939 return true;
Jeff Brownda3d5a92011-03-29 15:11:34 -07003940 }
Jeff Brown81346812011-06-28 20:08:48 -07003941#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00003942 ALOGD("Dropping inconsistent motion up or cancel event: deviceId=%d, source=%08x, "
Jeff Brown81346812011-06-28 20:08:48 -07003943 "actionMasked=%d",
3944 entry->deviceId, entry->source, actionMasked);
3945#endif
3946 return false;
Jeff Brownda3d5a92011-03-29 15:11:34 -07003947 }
3948
Jeff Brown81346812011-06-28 20:08:48 -07003949 case AMOTION_EVENT_ACTION_DOWN: {
3950 ssize_t index = findMotionMemento(entry, false /*hovering*/);
3951 if (index >= 0) {
3952 mMotionMementos.removeAt(index);
3953 }
3954 addMotionMemento(entry, flags, false /*hovering*/);
3955 return true;
3956 }
3957
3958 case AMOTION_EVENT_ACTION_POINTER_UP:
3959 case AMOTION_EVENT_ACTION_POINTER_DOWN:
3960 case AMOTION_EVENT_ACTION_MOVE: {
3961 ssize_t index = findMotionMemento(entry, false /*hovering*/);
3962 if (index >= 0) {
3963 MotionMemento& memento = mMotionMementos.editItemAt(index);
3964 memento.setPointers(entry);
3965 return true;
3966 }
Jeff Brown2e45fb62011-06-29 21:19:05 -07003967 if (actionMasked == AMOTION_EVENT_ACTION_MOVE
3968 && (entry->source & (AINPUT_SOURCE_CLASS_JOYSTICK
3969 | AINPUT_SOURCE_CLASS_NAVIGATION))) {
3970 // Joysticks and trackballs can send MOVE events without corresponding DOWN or UP.
3971 return true;
3972 }
Jeff Brown81346812011-06-28 20:08:48 -07003973#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00003974 ALOGD("Dropping inconsistent motion pointer up/down or move event: "
Jeff Brown81346812011-06-28 20:08:48 -07003975 "deviceId=%d, source=%08x, actionMasked=%d",
3976 entry->deviceId, entry->source, actionMasked);
3977#endif
3978 return false;
3979 }
3980
3981 case AMOTION_EVENT_ACTION_HOVER_EXIT: {
3982 ssize_t index = findMotionMemento(entry, true /*hovering*/);
3983 if (index >= 0) {
3984 mMotionMementos.removeAt(index);
3985 return true;
3986 }
3987#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00003988 ALOGD("Dropping inconsistent motion hover exit event: deviceId=%d, source=%08x",
Jeff Brown81346812011-06-28 20:08:48 -07003989 entry->deviceId, entry->source);
3990#endif
3991 return false;
3992 }
3993
3994 case AMOTION_EVENT_ACTION_HOVER_ENTER:
3995 case AMOTION_EVENT_ACTION_HOVER_MOVE: {
3996 ssize_t index = findMotionMemento(entry, true /*hovering*/);
3997 if (index >= 0) {
3998 mMotionMementos.removeAt(index);
3999 }
4000 addMotionMemento(entry, flags, true /*hovering*/);
4001 return true;
4002 }
4003
4004 default:
4005 return true;
4006 }
4007}
4008
4009ssize_t InputDispatcher::InputState::findKeyMemento(const KeyEntry* entry) const {
Jeff Brownb88102f2010-09-08 11:49:43 -07004010 for (size_t i = 0; i < mKeyMementos.size(); i++) {
Jeff Brown81346812011-06-28 20:08:48 -07004011 const KeyMemento& memento = mKeyMementos.itemAt(i);
Jeff Brownb88102f2010-09-08 11:49:43 -07004012 if (memento.deviceId == entry->deviceId
4013 && memento.source == entry->source
4014 && memento.keyCode == entry->keyCode
4015 && memento.scanCode == entry->scanCode) {
Jeff Brown81346812011-06-28 20:08:48 -07004016 return i;
Jeff Brownb88102f2010-09-08 11:49:43 -07004017 }
4018 }
Jeff Brown81346812011-06-28 20:08:48 -07004019 return -1;
Jeff Brownb88102f2010-09-08 11:49:43 -07004020}
4021
Jeff Brown81346812011-06-28 20:08:48 -07004022ssize_t InputDispatcher::InputState::findMotionMemento(const MotionEntry* entry,
4023 bool hovering) const {
Jeff Brownb88102f2010-09-08 11:49:43 -07004024 for (size_t i = 0; i < mMotionMementos.size(); i++) {
Jeff Brown81346812011-06-28 20:08:48 -07004025 const MotionMemento& memento = mMotionMementos.itemAt(i);
Jeff Brownb88102f2010-09-08 11:49:43 -07004026 if (memento.deviceId == entry->deviceId
Jeff Brown81346812011-06-28 20:08:48 -07004027 && memento.source == entry->source
4028 && memento.hovering == hovering) {
4029 return i;
Jeff Brownb88102f2010-09-08 11:49:43 -07004030 }
4031 }
Jeff Brown81346812011-06-28 20:08:48 -07004032 return -1;
4033}
Jeff Brownb88102f2010-09-08 11:49:43 -07004034
Jeff Brown81346812011-06-28 20:08:48 -07004035void InputDispatcher::InputState::addKeyMemento(const KeyEntry* entry, int32_t flags) {
4036 mKeyMementos.push();
4037 KeyMemento& memento = mKeyMementos.editTop();
4038 memento.deviceId = entry->deviceId;
4039 memento.source = entry->source;
4040 memento.keyCode = entry->keyCode;
4041 memento.scanCode = entry->scanCode;
Jeff Brownfd23e3e2012-05-09 13:34:28 -07004042 memento.metaState = entry->metaState;
Jeff Brown81346812011-06-28 20:08:48 -07004043 memento.flags = flags;
4044 memento.downTime = entry->downTime;
Jeff Brownfd23e3e2012-05-09 13:34:28 -07004045 memento.policyFlags = entry->policyFlags;
Jeff Brown81346812011-06-28 20:08:48 -07004046}
4047
4048void InputDispatcher::InputState::addMotionMemento(const MotionEntry* entry,
4049 int32_t flags, bool hovering) {
4050 mMotionMementos.push();
4051 MotionMemento& memento = mMotionMementos.editTop();
4052 memento.deviceId = entry->deviceId;
4053 memento.source = entry->source;
4054 memento.flags = flags;
4055 memento.xPrecision = entry->xPrecision;
4056 memento.yPrecision = entry->yPrecision;
4057 memento.downTime = entry->downTime;
4058 memento.setPointers(entry);
4059 memento.hovering = hovering;
Jeff Brownfd23e3e2012-05-09 13:34:28 -07004060 memento.policyFlags = entry->policyFlags;
Jeff Brownb88102f2010-09-08 11:49:43 -07004061}
4062
4063void InputDispatcher::InputState::MotionMemento::setPointers(const MotionEntry* entry) {
4064 pointerCount = entry->pointerCount;
4065 for (uint32_t i = 0; i < entry->pointerCount; i++) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07004066 pointerProperties[i].copyFrom(entry->pointerProperties[i]);
Jeff Brown3241b6b2012-02-03 15:08:02 -08004067 pointerCoords[i].copyFrom(entry->pointerCoords[i]);
Jeff Brownb88102f2010-09-08 11:49:43 -07004068 }
4069}
4070
Jeff Brownb6997262010-10-08 22:31:17 -07004071void InputDispatcher::InputState::synthesizeCancelationEvents(nsecs_t currentTime,
Jeff Brownac386072011-07-20 15:19:50 -07004072 Vector<EventEntry*>& outEvents, const CancelationOptions& options) {
Jeff Brown81346812011-06-28 20:08:48 -07004073 for (size_t i = 0; i < mKeyMementos.size(); i++) {
Jeff Brownb88102f2010-09-08 11:49:43 -07004074 const KeyMemento& memento = mKeyMementos.itemAt(i);
Jeff Brown49ed71d2010-12-06 17:13:33 -08004075 if (shouldCancelKey(memento, options)) {
Jeff Brownac386072011-07-20 15:19:50 -07004076 outEvents.push(new KeyEntry(currentTime,
Jeff Brownfd23e3e2012-05-09 13:34:28 -07004077 memento.deviceId, memento.source, memento.policyFlags,
Jeff Brown49ed71d2010-12-06 17:13:33 -08004078 AKEY_EVENT_ACTION_UP, memento.flags | AKEY_EVENT_FLAG_CANCELED,
Jeff Brownfd23e3e2012-05-09 13:34:28 -07004079 memento.keyCode, memento.scanCode, memento.metaState, 0, memento.downTime));
Jeff Brownb6997262010-10-08 22:31:17 -07004080 }
Jeff Brownb88102f2010-09-08 11:49:43 -07004081 }
4082
Jeff Brown81346812011-06-28 20:08:48 -07004083 for (size_t i = 0; i < mMotionMementos.size(); i++) {
Jeff Brownb88102f2010-09-08 11:49:43 -07004084 const MotionMemento& memento = mMotionMementos.itemAt(i);
Jeff Brown49ed71d2010-12-06 17:13:33 -08004085 if (shouldCancelMotion(memento, options)) {
Jeff Brownac386072011-07-20 15:19:50 -07004086 outEvents.push(new MotionEntry(currentTime,
Jeff Brownfd23e3e2012-05-09 13:34:28 -07004087 memento.deviceId, memento.source, memento.policyFlags,
Jeff Browna032cc02011-03-07 16:56:21 -08004088 memento.hovering
4089 ? AMOTION_EVENT_ACTION_HOVER_EXIT
4090 : AMOTION_EVENT_ACTION_CANCEL,
Jeff Brown81346812011-06-28 20:08:48 -07004091 memento.flags, 0, 0, 0,
Jeff Brownb6997262010-10-08 22:31:17 -07004092 memento.xPrecision, memento.yPrecision, memento.downTime,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07004093 memento.pointerCount, memento.pointerProperties, memento.pointerCoords));
Jeff Brownb6997262010-10-08 22:31:17 -07004094 }
Jeff Brownb88102f2010-09-08 11:49:43 -07004095 }
4096}
4097
4098void InputDispatcher::InputState::clear() {
4099 mKeyMementos.clear();
4100 mMotionMementos.clear();
Jeff Brownda3d5a92011-03-29 15:11:34 -07004101 mFallbackKeys.clear();
Jeff Brownb6997262010-10-08 22:31:17 -07004102}
4103
Jeff Brown9c9f1a32010-10-11 18:32:20 -07004104void InputDispatcher::InputState::copyPointerStateTo(InputState& other) const {
4105 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4106 const MotionMemento& memento = mMotionMementos.itemAt(i);
4107 if (memento.source & AINPUT_SOURCE_CLASS_POINTER) {
4108 for (size_t j = 0; j < other.mMotionMementos.size(); ) {
4109 const MotionMemento& otherMemento = other.mMotionMementos.itemAt(j);
4110 if (memento.deviceId == otherMemento.deviceId
4111 && memento.source == otherMemento.source) {
4112 other.mMotionMementos.removeAt(j);
4113 } else {
4114 j += 1;
4115 }
4116 }
4117 other.mMotionMementos.push(memento);
4118 }
4119 }
4120}
4121
Jeff Brownda3d5a92011-03-29 15:11:34 -07004122int32_t InputDispatcher::InputState::getFallbackKey(int32_t originalKeyCode) {
4123 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
4124 return index >= 0 ? mFallbackKeys.valueAt(index) : -1;
4125}
4126
4127void InputDispatcher::InputState::setFallbackKey(int32_t originalKeyCode,
4128 int32_t fallbackKeyCode) {
4129 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
4130 if (index >= 0) {
4131 mFallbackKeys.replaceValueAt(index, fallbackKeyCode);
4132 } else {
4133 mFallbackKeys.add(originalKeyCode, fallbackKeyCode);
4134 }
4135}
4136
4137void InputDispatcher::InputState::removeFallbackKey(int32_t originalKeyCode) {
4138 mFallbackKeys.removeItem(originalKeyCode);
4139}
4140
Jeff Brown49ed71d2010-12-06 17:13:33 -08004141bool InputDispatcher::InputState::shouldCancelKey(const KeyMemento& memento,
Jeff Brownda3d5a92011-03-29 15:11:34 -07004142 const CancelationOptions& options) {
4143 if (options.keyCode != -1 && memento.keyCode != options.keyCode) {
4144 return false;
4145 }
4146
Jeff Brown65fd2512011-08-18 11:20:58 -07004147 if (options.deviceId != -1 && memento.deviceId != options.deviceId) {
4148 return false;
4149 }
4150
Jeff Brownda3d5a92011-03-29 15:11:34 -07004151 switch (options.mode) {
4152 case CancelationOptions::CANCEL_ALL_EVENTS:
4153 case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
Jeff Brownb6997262010-10-08 22:31:17 -07004154 return true;
Jeff Brownda3d5a92011-03-29 15:11:34 -07004155 case CancelationOptions::CANCEL_FALLBACK_EVENTS:
Jeff Brown49ed71d2010-12-06 17:13:33 -08004156 return memento.flags & AKEY_EVENT_FLAG_FALLBACK;
4157 default:
4158 return false;
4159 }
4160}
4161
4162bool InputDispatcher::InputState::shouldCancelMotion(const MotionMemento& memento,
Jeff Brownda3d5a92011-03-29 15:11:34 -07004163 const CancelationOptions& options) {
Jeff Brown65fd2512011-08-18 11:20:58 -07004164 if (options.deviceId != -1 && memento.deviceId != options.deviceId) {
4165 return false;
4166 }
4167
Jeff Brownda3d5a92011-03-29 15:11:34 -07004168 switch (options.mode) {
4169 case CancelationOptions::CANCEL_ALL_EVENTS:
Jeff Brown49ed71d2010-12-06 17:13:33 -08004170 return true;
Jeff Brownda3d5a92011-03-29 15:11:34 -07004171 case CancelationOptions::CANCEL_POINTER_EVENTS:
Jeff Brown49ed71d2010-12-06 17:13:33 -08004172 return memento.source & AINPUT_SOURCE_CLASS_POINTER;
Jeff Brownda3d5a92011-03-29 15:11:34 -07004173 case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
Jeff Brown49ed71d2010-12-06 17:13:33 -08004174 return !(memento.source & AINPUT_SOURCE_CLASS_POINTER);
4175 default:
4176 return false;
Jeff Brownb6997262010-10-08 22:31:17 -07004177 }
Jeff Brownb88102f2010-09-08 11:49:43 -07004178}
4179
4180
Jeff Brown46b9ac02010-04-22 18:58:52 -07004181// --- InputDispatcher::Connection ---
4182
Jeff Brown928e0542011-01-10 11:17:36 -08004183InputDispatcher::Connection::Connection(const sp<InputChannel>& inputChannel,
Jeff Browncc4f7db2011-08-30 20:34:48 -07004184 const sp<InputWindowHandle>& inputWindowHandle, bool monitor) :
Jeff Brown928e0542011-01-10 11:17:36 -08004185 status(STATUS_NORMAL), inputChannel(inputChannel), inputWindowHandle(inputWindowHandle),
Jeff Browncc4f7db2011-08-30 20:34:48 -07004186 monitor(monitor),
Jeff Brownd1c48a02012-02-06 19:12:47 -08004187 inputPublisher(inputChannel), inputPublisherBlocked(false) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07004188}
4189
4190InputDispatcher::Connection::~Connection() {
4191}
4192
Jeff Brown481c1572012-03-09 14:41:15 -08004193const char* InputDispatcher::Connection::getWindowName() const {
4194 if (inputWindowHandle != NULL) {
4195 return inputWindowHandle->getName().string();
4196 }
4197 if (monitor) {
4198 return "monitor";
4199 }
4200 return "?";
4201}
4202
Jeff Brown9c3cda02010-06-15 01:31:58 -07004203const char* InputDispatcher::Connection::getStatusLabel() const {
4204 switch (status) {
4205 case STATUS_NORMAL:
4206 return "NORMAL";
4207
4208 case STATUS_BROKEN:
4209 return "BROKEN";
4210
Jeff Brown9c3cda02010-06-15 01:31:58 -07004211 case STATUS_ZOMBIE:
4212 return "ZOMBIE";
4213
4214 default:
4215 return "UNKNOWN";
4216 }
4217}
4218
Jeff Brown072ec962012-02-07 14:46:57 -08004219InputDispatcher::DispatchEntry* InputDispatcher::Connection::findWaitQueueEntry(uint32_t seq) {
4220 for (DispatchEntry* entry = waitQueue.head; entry != NULL; entry = entry->next) {
4221 if (entry->seq == seq) {
4222 return entry;
4223 }
4224 }
4225 return NULL;
4226}
4227
Jeff Brownb88102f2010-09-08 11:49:43 -07004228
Jeff Brown9c3cda02010-06-15 01:31:58 -07004229// --- InputDispatcher::CommandEntry ---
4230
Jeff Brownac386072011-07-20 15:19:50 -07004231InputDispatcher::CommandEntry::CommandEntry(Command command) :
Jeff Brown072ec962012-02-07 14:46:57 -08004232 command(command), eventTime(0), keyEntry(NULL), userActivityEventType(0),
4233 seq(0), handled(false) {
Jeff Brown9c3cda02010-06-15 01:31:58 -07004234}
4235
4236InputDispatcher::CommandEntry::~CommandEntry() {
4237}
4238
Jeff Brown46b9ac02010-04-22 18:58:52 -07004239
Jeff Brown01ce2e92010-09-26 22:20:12 -07004240// --- InputDispatcher::TouchState ---
4241
4242InputDispatcher::TouchState::TouchState() :
Jeff Brown58a2da82011-01-25 16:02:22 -08004243 down(false), split(false), deviceId(-1), source(0) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07004244}
4245
4246InputDispatcher::TouchState::~TouchState() {
4247}
4248
4249void InputDispatcher::TouchState::reset() {
4250 down = false;
4251 split = false;
Jeff Brown95712852011-01-04 19:41:59 -08004252 deviceId = -1;
Jeff Brown58a2da82011-01-25 16:02:22 -08004253 source = 0;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004254 windows.clear();
4255}
4256
4257void InputDispatcher::TouchState::copyFrom(const TouchState& other) {
4258 down = other.down;
4259 split = other.split;
Jeff Brown95712852011-01-04 19:41:59 -08004260 deviceId = other.deviceId;
Jeff Brown58a2da82011-01-25 16:02:22 -08004261 source = other.source;
Jeff Brown9302c872011-07-13 22:51:29 -07004262 windows = other.windows;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004263}
4264
Jeff Brown9302c872011-07-13 22:51:29 -07004265void InputDispatcher::TouchState::addOrUpdateWindow(const sp<InputWindowHandle>& windowHandle,
Jeff Brown01ce2e92010-09-26 22:20:12 -07004266 int32_t targetFlags, BitSet32 pointerIds) {
4267 if (targetFlags & InputTarget::FLAG_SPLIT) {
4268 split = true;
4269 }
4270
4271 for (size_t i = 0; i < windows.size(); i++) {
4272 TouchedWindow& touchedWindow = windows.editItemAt(i);
Jeff Brown9302c872011-07-13 22:51:29 -07004273 if (touchedWindow.windowHandle == windowHandle) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07004274 touchedWindow.targetFlags |= targetFlags;
Jeff Brown98db5fa2011-06-08 15:37:10 -07004275 if (targetFlags & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
4276 touchedWindow.targetFlags &= ~InputTarget::FLAG_DISPATCH_AS_IS;
4277 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07004278 touchedWindow.pointerIds.value |= pointerIds.value;
4279 return;
4280 }
4281 }
4282
4283 windows.push();
4284
4285 TouchedWindow& touchedWindow = windows.editTop();
Jeff Brown9302c872011-07-13 22:51:29 -07004286 touchedWindow.windowHandle = windowHandle;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004287 touchedWindow.targetFlags = targetFlags;
4288 touchedWindow.pointerIds = pointerIds;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004289}
4290
Jeff Brownf44e3942012-04-20 11:33:27 -07004291void InputDispatcher::TouchState::removeWindow(const sp<InputWindowHandle>& windowHandle) {
4292 for (size_t i = 0; i < windows.size(); i++) {
4293 if (windows.itemAt(i).windowHandle == windowHandle) {
4294 windows.removeAt(i);
4295 return;
4296 }
4297 }
4298}
4299
Jeff Browna032cc02011-03-07 16:56:21 -08004300void InputDispatcher::TouchState::filterNonAsIsTouchWindows() {
Jeff Brown01ce2e92010-09-26 22:20:12 -07004301 for (size_t i = 0 ; i < windows.size(); ) {
Jeff Browna032cc02011-03-07 16:56:21 -08004302 TouchedWindow& window = windows.editItemAt(i);
Jeff Brown98db5fa2011-06-08 15:37:10 -07004303 if (window.targetFlags & (InputTarget::FLAG_DISPATCH_AS_IS
4304 | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER)) {
Jeff Browna032cc02011-03-07 16:56:21 -08004305 window.targetFlags &= ~InputTarget::FLAG_DISPATCH_MASK;
4306 window.targetFlags |= InputTarget::FLAG_DISPATCH_AS_IS;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004307 i += 1;
Jeff Browna032cc02011-03-07 16:56:21 -08004308 } else {
4309 windows.removeAt(i);
Jeff Brown01ce2e92010-09-26 22:20:12 -07004310 }
4311 }
4312}
4313
Jeff Brown9302c872011-07-13 22:51:29 -07004314sp<InputWindowHandle> InputDispatcher::TouchState::getFirstForegroundWindowHandle() const {
Jeff Brown01ce2e92010-09-26 22:20:12 -07004315 for (size_t i = 0; i < windows.size(); i++) {
Jeff Brown98db5fa2011-06-08 15:37:10 -07004316 const TouchedWindow& window = windows.itemAt(i);
4317 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
Jeff Brown9302c872011-07-13 22:51:29 -07004318 return window.windowHandle;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004319 }
4320 }
4321 return NULL;
4322}
4323
Jeff Brown98db5fa2011-06-08 15:37:10 -07004324bool InputDispatcher::TouchState::isSlippery() const {
4325 // Must have exactly one foreground window.
4326 bool haveSlipperyForegroundWindow = false;
4327 for (size_t i = 0; i < windows.size(); i++) {
4328 const TouchedWindow& window = windows.itemAt(i);
4329 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
Jeff Browncc4f7db2011-08-30 20:34:48 -07004330 if (haveSlipperyForegroundWindow
4331 || !(window.windowHandle->getInfo()->layoutParamsFlags
4332 & InputWindowInfo::FLAG_SLIPPERY)) {
Jeff Brown98db5fa2011-06-08 15:37:10 -07004333 return false;
4334 }
4335 haveSlipperyForegroundWindow = true;
4336 }
4337 }
4338 return haveSlipperyForegroundWindow;
4339}
4340
Jeff Brown01ce2e92010-09-26 22:20:12 -07004341
Jeff Brown46b9ac02010-04-22 18:58:52 -07004342// --- InputDispatcherThread ---
4343
4344InputDispatcherThread::InputDispatcherThread(const sp<InputDispatcherInterface>& dispatcher) :
4345 Thread(/*canCallJava*/ true), mDispatcher(dispatcher) {
4346}
4347
4348InputDispatcherThread::~InputDispatcherThread() {
4349}
4350
4351bool InputDispatcherThread::threadLoop() {
4352 mDispatcher->dispatchOnce();
4353 return true;
4354}
4355
4356} // namespace android