blob: 795ab4740a78f3bb7e59e539809d96da87c48833 [file] [log] [blame]
Jeff Brownb4ff35d2011-01-02 16:37:43 -08001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070017#define LOG_TAG "InputDispatcher"
Jeff Brown481c1572012-03-09 14:41:15 -080018#define ATRACE_TAG ATRACE_TAG_INPUT
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070019
20//#define LOG_NDEBUG 0
21
22// Log detailed debug messages about each inbound event notification to the dispatcher.
Jeff Brown349703e2010-06-22 01:27:15 -070023#define DEBUG_INBOUND_EVENT_DETAILS 0
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070024
25// Log detailed debug messages about each outbound event processed by the dispatcher.
Jeff Brown349703e2010-06-22 01:27:15 -070026#define DEBUG_OUTBOUND_EVENT_DETAILS 0
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070027
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070028// Log debug messages about the dispatch cycle.
Jeff Brown349703e2010-06-22 01:27:15 -070029#define DEBUG_DISPATCH_CYCLE 0
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070030
Jeff Brown9c3cda02010-06-15 01:31:58 -070031// Log debug messages about registrations.
Jeff Brown349703e2010-06-22 01:27:15 -070032#define DEBUG_REGISTRATION 0
Jeff Brown9c3cda02010-06-15 01:31:58 -070033
Jeff Brown7fbdc842010-06-17 20:52:56 -070034// Log debug messages about input event injection.
Jeff Brown349703e2010-06-22 01:27:15 -070035#define DEBUG_INJECTION 0
Jeff Brown7fbdc842010-06-17 20:52:56 -070036
Jeff Brownb88102f2010-09-08 11:49:43 -070037// Log debug messages about input focus tracking.
38#define DEBUG_FOCUS 0
39
40// Log debug messages about the app switch latency optimization.
41#define DEBUG_APP_SWITCH 0
42
Jeff Browna032cc02011-03-07 16:56:21 -080043// Log debug messages about hover events.
44#define DEBUG_HOVER 0
45
Jeff Brownb4ff35d2011-01-02 16:37:43 -080046#include "InputDispatcher.h"
47
Jeff Brown481c1572012-03-09 14:41:15 -080048#include <utils/Trace.h>
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070049#include <cutils/log.h>
Mathias Agopianb93a03f82012-02-17 15:34:57 -080050#include <androidfw/PowerManager.h>
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070051
52#include <stddef.h>
53#include <unistd.h>
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070054#include <errno.h>
55#include <limits.h>
Jeff Brown22aa5122012-06-17 12:01:06 -070056#include <time.h>
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070057
Jeff Brownf2f487182010-10-01 17:46:21 -070058#define INDENT " "
59#define INDENT2 " "
Jeff Brown265f1cc2012-06-11 18:01:06 -070060#define INDENT3 " "
61#define INDENT4 " "
Jeff Brownf2f487182010-10-01 17:46:21 -070062
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070063namespace android {
64
Jeff Brownb88102f2010-09-08 11:49:43 -070065// Default input dispatching timeout if there is no focused application or paused window
66// from which to determine an appropriate dispatching timeout.
67const nsecs_t DEFAULT_INPUT_DISPATCHING_TIMEOUT = 5000 * 1000000LL; // 5 sec
68
69// Amount of time to allow for all pending events to be processed when an app switch
70// key is on the way. This is used to preempt input dispatch and drop input events
71// when an application takes too long to respond and the user has pressed an app switch key.
72const nsecs_t APP_SWITCH_TIMEOUT = 500 * 1000000LL; // 0.5sec
73
Jeff Brown928e0542011-01-10 11:17:36 -080074// Amount of time to allow for an event to be dispatched (measured since its eventTime)
75// before considering it stale and dropping it.
76const nsecs_t STALE_EVENT_TIMEOUT = 10000 * 1000000LL; // 10sec
77
Jeff Brownd1c48a02012-02-06 19:12:47 -080078// Amount of time to allow touch events to be streamed out to a connection before requiring
79// that the first event be finished. This value extends the ANR timeout by the specified
80// amount. For example, if streaming is allowed to get ahead by one second relative to the
81// queue of waiting unfinished events, then ANRs will similarly be delayed by one second.
82const nsecs_t STREAM_AHEAD_EVENT_TIMEOUT = 500 * 1000000LL; // 0.5sec
83
Jeff Brown265f1cc2012-06-11 18:01:06 -070084// Log a warning when an event takes longer than this to process, even if an ANR does not occur.
85const nsecs_t SLOW_EVENT_PROCESSING_WARNING_TIMEOUT = 2000 * 1000000LL; // 2sec
86
Jeff Brown6876f322013-08-07 16:46:50 -070087// Number of recent events to keep for debugging purposes.
88const size_t RECENT_QUEUE_MAX_SIZE = 10;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070089
Jeff Brown7fbdc842010-06-17 20:52:56 -070090static inline nsecs_t now() {
91 return systemTime(SYSTEM_TIME_MONOTONIC);
92}
93
Jeff Brownb88102f2010-09-08 11:49:43 -070094static inline const char* toString(bool value) {
95 return value ? "true" : "false";
96}
97
Jeff Brown01ce2e92010-09-26 22:20:12 -070098static inline int32_t getMotionEventActionPointerIndex(int32_t action) {
99 return (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK)
100 >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
101}
102
103static bool isValidKeyAction(int32_t action) {
104 switch (action) {
105 case AKEY_EVENT_ACTION_DOWN:
106 case AKEY_EVENT_ACTION_UP:
107 return true;
108 default:
109 return false;
110 }
111}
112
113static bool validateKeyEvent(int32_t action) {
114 if (! isValidKeyAction(action)) {
Steve Block3762c312012-01-06 19:20:56 +0000115 ALOGE("Key event has invalid action code 0x%x", action);
Jeff Brown01ce2e92010-09-26 22:20:12 -0700116 return false;
117 }
118 return true;
119}
120
Jeff Brownb6997262010-10-08 22:31:17 -0700121static bool isValidMotionAction(int32_t action, size_t pointerCount) {
Jeff Brown01ce2e92010-09-26 22:20:12 -0700122 switch (action & AMOTION_EVENT_ACTION_MASK) {
123 case AMOTION_EVENT_ACTION_DOWN:
124 case AMOTION_EVENT_ACTION_UP:
125 case AMOTION_EVENT_ACTION_CANCEL:
126 case AMOTION_EVENT_ACTION_MOVE:
Jeff Brown01ce2e92010-09-26 22:20:12 -0700127 case AMOTION_EVENT_ACTION_OUTSIDE:
Jeff Browna032cc02011-03-07 16:56:21 -0800128 case AMOTION_EVENT_ACTION_HOVER_ENTER:
Jeff Browncc0c1592011-02-19 05:07:28 -0800129 case AMOTION_EVENT_ACTION_HOVER_MOVE:
Jeff Browna032cc02011-03-07 16:56:21 -0800130 case AMOTION_EVENT_ACTION_HOVER_EXIT:
Jeff Brown33bbfd22011-02-24 20:55:35 -0800131 case AMOTION_EVENT_ACTION_SCROLL:
Jeff Brown01ce2e92010-09-26 22:20:12 -0700132 return true;
Jeff Brownb6997262010-10-08 22:31:17 -0700133 case AMOTION_EVENT_ACTION_POINTER_DOWN:
134 case AMOTION_EVENT_ACTION_POINTER_UP: {
135 int32_t index = getMotionEventActionPointerIndex(action);
136 return index >= 0 && size_t(index) < pointerCount;
137 }
Jeff Brown01ce2e92010-09-26 22:20:12 -0700138 default:
139 return false;
140 }
141}
142
143static bool validateMotionEvent(int32_t action, size_t pointerCount,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700144 const PointerProperties* pointerProperties) {
Jeff Brownb6997262010-10-08 22:31:17 -0700145 if (! isValidMotionAction(action, pointerCount)) {
Steve Block3762c312012-01-06 19:20:56 +0000146 ALOGE("Motion event has invalid action code 0x%x", action);
Jeff Brown01ce2e92010-09-26 22:20:12 -0700147 return false;
148 }
149 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Steve Block3762c312012-01-06 19:20:56 +0000150 ALOGE("Motion event has invalid pointer count %d; value must be between 1 and %d.",
Jeff Brown01ce2e92010-09-26 22:20:12 -0700151 pointerCount, MAX_POINTERS);
152 return false;
153 }
Jeff Brownc3db8582010-10-20 15:33:38 -0700154 BitSet32 pointerIdBits;
Jeff Brown01ce2e92010-09-26 22:20:12 -0700155 for (size_t i = 0; i < pointerCount; i++) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700156 int32_t id = pointerProperties[i].id;
Jeff Brownc3db8582010-10-20 15:33:38 -0700157 if (id < 0 || id > MAX_POINTER_ID) {
Steve Block3762c312012-01-06 19:20:56 +0000158 ALOGE("Motion event has invalid pointer id %d; value must be between 0 and %d",
Jeff Brownc3db8582010-10-20 15:33:38 -0700159 id, MAX_POINTER_ID);
Jeff Brown01ce2e92010-09-26 22:20:12 -0700160 return false;
161 }
Jeff Brownc3db8582010-10-20 15:33:38 -0700162 if (pointerIdBits.hasBit(id)) {
Steve Block3762c312012-01-06 19:20:56 +0000163 ALOGE("Motion event has duplicate pointer id %d", id);
Jeff Brownc3db8582010-10-20 15:33:38 -0700164 return false;
165 }
166 pointerIdBits.markBit(id);
Jeff Brown01ce2e92010-09-26 22:20:12 -0700167 }
168 return true;
169}
170
Jeff Brown83d616a2012-09-09 20:33:43 -0700171static bool isMainDisplay(int32_t displayId) {
172 return displayId == ADISPLAY_ID_DEFAULT || displayId == ADISPLAY_ID_NONE;
173}
174
Jeff Brownfbf09772011-01-16 14:06:57 -0800175static void dumpRegion(String8& dump, const SkRegion& region) {
176 if (region.isEmpty()) {
177 dump.append("<empty>");
178 return;
179 }
180
181 bool first = true;
182 for (SkRegion::Iterator it(region); !it.done(); it.next()) {
183 if (first) {
184 first = false;
185 } else {
186 dump.append("|");
187 }
188 const SkIRect& rect = it.rect();
189 dump.appendFormat("[%d,%d][%d,%d]", rect.fLeft, rect.fTop, rect.fRight, rect.fBottom);
190 }
191}
192
Jeff Brownb88102f2010-09-08 11:49:43 -0700193
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700194// --- InputDispatcher ---
195
Jeff Brown9c3cda02010-06-15 01:31:58 -0700196InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy) :
Jeff Brownb88102f2010-09-08 11:49:43 -0700197 mPolicy(policy),
Jeff Brown928e0542011-01-10 11:17:36 -0800198 mPendingEvent(NULL), mAppSwitchSawKeyDown(false), mAppSwitchDueTime(LONG_LONG_MAX),
199 mNextUnblockedEvent(NULL),
Jeff Brownc042ee22012-05-08 13:03:42 -0700200 mDispatchEnabled(false), mDispatchFrozen(false), mInputFilterEnabled(false),
Jeff Brown9302c872011-07-13 22:51:29 -0700201 mInputTargetWaitCause(INPUT_TARGET_WAIT_CAUSE_NONE) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -0700202 mLooper = new Looper(false);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700203
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700204 mKeyRepeatState.lastKeyEntry = NULL;
Jeff Brown9c3cda02010-06-15 01:31:58 -0700205
Jeff Brown214eaf42011-05-26 19:17:02 -0700206 policy->getDispatcherConfiguration(&mConfig);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700207}
208
209InputDispatcher::~InputDispatcher() {
Jeff Brownb88102f2010-09-08 11:49:43 -0700210 { // acquire lock
211 AutoMutex _l(mLock);
212
213 resetKeyRepeatLocked();
Jeff Brown54a18252010-09-16 14:07:33 -0700214 releasePendingEventLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -0700215 drainInboundQueueLocked();
216 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700217
Jeff Browncbee6d62012-02-03 20:11:27 -0800218 while (mConnectionsByFd.size() != 0) {
219 unregisterInputChannel(mConnectionsByFd.valueAt(0)->inputChannel);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700220 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700221}
222
223void InputDispatcher::dispatchOnce() {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700224 nsecs_t nextWakeupTime = LONG_LONG_MAX;
225 { // acquire lock
226 AutoMutex _l(mLock);
Jeff Brown112b5f52012-01-27 17:32:06 -0800227 mDispatcherIsAliveCondition.broadcast();
228
Jeff Brown074b8b72012-10-31 19:01:31 -0700229 // Run a dispatch loop if there are no pending commands.
230 // The dispatch loop might enqueue commands to run afterwards.
231 if (!haveCommandsLocked()) {
232 dispatchOnceInnerLocked(&nextWakeupTime);
233 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700234
Jeff Brown074b8b72012-10-31 19:01:31 -0700235 // Run all pending commands if there are any.
236 // If any commands were run then force the next poll to wake up immediately.
Jeff Brownb88102f2010-09-08 11:49:43 -0700237 if (runCommandsLockedInterruptible()) {
Jeff Brown074b8b72012-10-31 19:01:31 -0700238 nextWakeupTime = LONG_LONG_MIN;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700239 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700240 } // release lock
241
Jeff Brownb88102f2010-09-08 11:49:43 -0700242 // Wait for callback or timeout or wake. (make sure we round up, not down)
243 nsecs_t currentTime = now();
Jeff Brownaa3855d2011-03-17 01:34:19 -0700244 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
Jeff Brown4fe6c3e2010-09-13 23:17:30 -0700245 mLooper->pollOnce(timeoutMillis);
Jeff Brownb88102f2010-09-08 11:49:43 -0700246}
247
Jeff Brown214eaf42011-05-26 19:17:02 -0700248void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700249 nsecs_t currentTime = now();
250
251 // Reset the key repeat timer whenever we disallow key events, even if the next event
252 // is not a key. This is to ensure that we abort a key repeat if the device is just coming
253 // out of sleep.
Jeff Brown214eaf42011-05-26 19:17:02 -0700254 if (!mPolicy->isKeyRepeatEnabled()) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700255 resetKeyRepeatLocked();
256 }
257
Jeff Brownb88102f2010-09-08 11:49:43 -0700258 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
259 if (mDispatchFrozen) {
260#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +0000261 ALOGD("Dispatch frozen. Waiting some more.");
Jeff Brownb88102f2010-09-08 11:49:43 -0700262#endif
263 return;
264 }
265
266 // Optimize latency of app switches.
267 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
268 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
269 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
270 if (mAppSwitchDueTime < *nextWakeupTime) {
271 *nextWakeupTime = mAppSwitchDueTime;
272 }
273
Jeff Brownb88102f2010-09-08 11:49:43 -0700274 // Ready to start a new event.
275 // If we don't already have a pending event, go grab one.
276 if (! mPendingEvent) {
277 if (mInboundQueue.isEmpty()) {
278 if (isAppSwitchDue) {
279 // The inbound queue is empty so the app switch key we were waiting
280 // for will never arrive. Stop waiting for it.
281 resetPendingAppSwitchLocked(false);
282 isAppSwitchDue = false;
283 }
284
285 // Synthesize a key repeat if appropriate.
286 if (mKeyRepeatState.lastKeyEntry) {
287 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
Jeff Brown214eaf42011-05-26 19:17:02 -0700288 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700289 } else {
290 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
291 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
292 }
293 }
294 }
Jeff Browncc4f7db2011-08-30 20:34:48 -0700295
296 // Nothing to do if there is no pending event.
Jeff Browne9bb9be2012-02-06 15:47:55 -0800297 if (!mPendingEvent) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700298 return;
299 }
300 } else {
301 // Inbound queue has at least one entry.
Jeff Browne9bb9be2012-02-06 15:47:55 -0800302 mPendingEvent = mInboundQueue.dequeueAtHead();
Jeff Brown481c1572012-03-09 14:41:15 -0800303 traceInboundQueueLengthLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -0700304 }
Jeff Browne2fe69e2010-10-18 13:21:23 -0700305
306 // Poke user activity for this event.
307 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
308 pokeUserActivityLocked(mPendingEvent);
309 }
Jeff Browne9bb9be2012-02-06 15:47:55 -0800310
311 // Get ready to dispatch the event.
312 resetANRTimeoutsLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -0700313 }
314
315 // Now we have an event to dispatch.
Jeff Brown928e0542011-01-10 11:17:36 -0800316 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Steve Blockec193de2012-01-09 18:35:44 +0000317 ALOG_ASSERT(mPendingEvent != NULL);
Jeff Brown54a18252010-09-16 14:07:33 -0700318 bool done = false;
Jeff Brownb6997262010-10-08 22:31:17 -0700319 DropReason dropReason = DROP_REASON_NOT_DROPPED;
320 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
321 dropReason = DROP_REASON_POLICY;
322 } else if (!mDispatchEnabled) {
323 dropReason = DROP_REASON_DISABLED;
324 }
Jeff Brown928e0542011-01-10 11:17:36 -0800325
326 if (mNextUnblockedEvent == mPendingEvent) {
327 mNextUnblockedEvent = NULL;
328 }
329
Jeff Brownb88102f2010-09-08 11:49:43 -0700330 switch (mPendingEvent->type) {
331 case EventEntry::TYPE_CONFIGURATION_CHANGED: {
332 ConfigurationChangedEntry* typedEntry =
333 static_cast<ConfigurationChangedEntry*>(mPendingEvent);
Jeff Brown54a18252010-09-16 14:07:33 -0700334 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Jeff Brownb6997262010-10-08 22:31:17 -0700335 dropReason = DROP_REASON_NOT_DROPPED; // configuration changes are never dropped
Jeff Brownb88102f2010-09-08 11:49:43 -0700336 break;
337 }
338
Jeff Brown65fd2512011-08-18 11:20:58 -0700339 case EventEntry::TYPE_DEVICE_RESET: {
340 DeviceResetEntry* typedEntry =
341 static_cast<DeviceResetEntry*>(mPendingEvent);
342 done = dispatchDeviceResetLocked(currentTime, typedEntry);
343 dropReason = DROP_REASON_NOT_DROPPED; // device resets are never dropped
344 break;
345 }
346
Jeff Brownb88102f2010-09-08 11:49:43 -0700347 case EventEntry::TYPE_KEY: {
348 KeyEntry* typedEntry = static_cast<KeyEntry*>(mPendingEvent);
Jeff Brownb6997262010-10-08 22:31:17 -0700349 if (isAppSwitchDue) {
350 if (isAppSwitchKeyEventLocked(typedEntry)) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700351 resetPendingAppSwitchLocked(true);
Jeff Brownb6997262010-10-08 22:31:17 -0700352 isAppSwitchDue = false;
353 } else if (dropReason == DROP_REASON_NOT_DROPPED) {
354 dropReason = DROP_REASON_APP_SWITCH;
Jeff Brownb88102f2010-09-08 11:49:43 -0700355 }
356 }
Jeff Brown928e0542011-01-10 11:17:36 -0800357 if (dropReason == DROP_REASON_NOT_DROPPED
358 && isStaleEventLocked(currentTime, typedEntry)) {
359 dropReason = DROP_REASON_STALE;
360 }
361 if (dropReason == DROP_REASON_NOT_DROPPED && mNextUnblockedEvent) {
362 dropReason = DROP_REASON_BLOCKED;
363 }
Jeff Brown214eaf42011-05-26 19:17:02 -0700364 done = dispatchKeyLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700365 break;
366 }
367
368 case EventEntry::TYPE_MOTION: {
369 MotionEntry* typedEntry = static_cast<MotionEntry*>(mPendingEvent);
Jeff Brownb6997262010-10-08 22:31:17 -0700370 if (dropReason == DROP_REASON_NOT_DROPPED && isAppSwitchDue) {
371 dropReason = DROP_REASON_APP_SWITCH;
Jeff Brownb88102f2010-09-08 11:49:43 -0700372 }
Jeff Brown928e0542011-01-10 11:17:36 -0800373 if (dropReason == DROP_REASON_NOT_DROPPED
374 && isStaleEventLocked(currentTime, typedEntry)) {
375 dropReason = DROP_REASON_STALE;
376 }
377 if (dropReason == DROP_REASON_NOT_DROPPED && mNextUnblockedEvent) {
378 dropReason = DROP_REASON_BLOCKED;
379 }
Jeff Brownb6997262010-10-08 22:31:17 -0700380 done = dispatchMotionLocked(currentTime, typedEntry,
Jeff Browne20c9e02010-10-11 14:20:19 -0700381 &dropReason, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700382 break;
383 }
384
385 default:
Steve Blockec193de2012-01-09 18:35:44 +0000386 ALOG_ASSERT(false);
Jeff Brownb88102f2010-09-08 11:49:43 -0700387 break;
388 }
389
Jeff Brown54a18252010-09-16 14:07:33 -0700390 if (done) {
Jeff Brownb6997262010-10-08 22:31:17 -0700391 if (dropReason != DROP_REASON_NOT_DROPPED) {
392 dropInboundEventLocked(mPendingEvent, dropReason);
393 }
394
Jeff Brown54a18252010-09-16 14:07:33 -0700395 releasePendingEventLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -0700396 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
397 }
398}
399
400bool InputDispatcher::enqueueInboundEventLocked(EventEntry* entry) {
401 bool needWake = mInboundQueue.isEmpty();
402 mInboundQueue.enqueueAtTail(entry);
Jeff Brown481c1572012-03-09 14:41:15 -0800403 traceInboundQueueLengthLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -0700404
405 switch (entry->type) {
Jeff Brownb6997262010-10-08 22:31:17 -0700406 case EventEntry::TYPE_KEY: {
Jeff Brown928e0542011-01-10 11:17:36 -0800407 // Optimize app switch latency.
408 // If the application takes too long to catch up then we drop all events preceding
409 // the app switch key.
Jeff Brownb6997262010-10-08 22:31:17 -0700410 KeyEntry* keyEntry = static_cast<KeyEntry*>(entry);
411 if (isAppSwitchKeyEventLocked(keyEntry)) {
412 if (keyEntry->action == AKEY_EVENT_ACTION_DOWN) {
413 mAppSwitchSawKeyDown = true;
414 } else if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
415 if (mAppSwitchSawKeyDown) {
416#if DEBUG_APP_SWITCH
Steve Block5baa3a62011-12-20 16:23:08 +0000417 ALOGD("App switch is pending!");
Jeff Brownb6997262010-10-08 22:31:17 -0700418#endif
419 mAppSwitchDueTime = keyEntry->eventTime + APP_SWITCH_TIMEOUT;
420 mAppSwitchSawKeyDown = false;
421 needWake = true;
422 }
423 }
424 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700425 break;
426 }
Jeff Brown928e0542011-01-10 11:17:36 -0800427
428 case EventEntry::TYPE_MOTION: {
429 // Optimize case where the current application is unresponsive and the user
430 // decides to touch a window in a different application.
431 // If the application takes too long to catch up then we drop all events preceding
432 // the touch into the other window.
433 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
Jeff Brown33bbfd22011-02-24 20:55:35 -0800434 if (motionEntry->action == AMOTION_EVENT_ACTION_DOWN
Jeff Brown928e0542011-01-10 11:17:36 -0800435 && (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER)
436 && mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY
Jeff Brown9302c872011-07-13 22:51:29 -0700437 && mInputTargetWaitApplicationHandle != NULL) {
Jeff Brown83d616a2012-09-09 20:33:43 -0700438 int32_t displayId = motionEntry->displayId;
Jeff Brown3241b6b2012-02-03 15:08:02 -0800439 int32_t x = int32_t(motionEntry->pointerCoords[0].
Jeff Brownebbd5d12011-02-17 13:01:34 -0800440 getAxisValue(AMOTION_EVENT_AXIS_X));
Jeff Brown3241b6b2012-02-03 15:08:02 -0800441 int32_t y = int32_t(motionEntry->pointerCoords[0].
Jeff Brownebbd5d12011-02-17 13:01:34 -0800442 getAxisValue(AMOTION_EVENT_AXIS_Y));
Jeff Brown83d616a2012-09-09 20:33:43 -0700443 sp<InputWindowHandle> touchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y);
Jeff Brown9302c872011-07-13 22:51:29 -0700444 if (touchedWindowHandle != NULL
445 && touchedWindowHandle->inputApplicationHandle
446 != mInputTargetWaitApplicationHandle) {
Jeff Brown928e0542011-01-10 11:17:36 -0800447 // User touched a different application than the one we are waiting on.
448 // Flag the event, and start pruning the input queue.
449 mNextUnblockedEvent = motionEntry;
450 needWake = true;
451 }
452 }
453 break;
454 }
Jeff Brownb6997262010-10-08 22:31:17 -0700455 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700456
457 return needWake;
458}
459
Jeff Brown6876f322013-08-07 16:46:50 -0700460void InputDispatcher::addRecentEventLocked(EventEntry* entry) {
461 entry->refCount += 1;
462 mRecentQueue.enqueueAtTail(entry);
463 if (mRecentQueue.count() > RECENT_QUEUE_MAX_SIZE) {
464 mRecentQueue.dequeueAtHead()->release();
465 }
466}
467
Jeff Brown83d616a2012-09-09 20:33:43 -0700468sp<InputWindowHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId,
469 int32_t x, int32_t y) {
Jeff Brown928e0542011-01-10 11:17:36 -0800470 // Traverse windows from front to back to find touched window.
Jeff Brown9302c872011-07-13 22:51:29 -0700471 size_t numWindows = mWindowHandles.size();
Jeff Brown928e0542011-01-10 11:17:36 -0800472 for (size_t i = 0; i < numWindows; i++) {
Jeff Brown9302c872011-07-13 22:51:29 -0700473 sp<InputWindowHandle> windowHandle = mWindowHandles.itemAt(i);
Jeff Browncc4f7db2011-08-30 20:34:48 -0700474 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Jeff Brown83d616a2012-09-09 20:33:43 -0700475 if (windowInfo->displayId == displayId) {
476 int32_t flags = windowInfo->layoutParamsFlags;
Jeff Brown928e0542011-01-10 11:17:36 -0800477
Jeff Brown83d616a2012-09-09 20:33:43 -0700478 if (windowInfo->visible) {
479 if (!(flags & InputWindowInfo::FLAG_NOT_TOUCHABLE)) {
480 bool isTouchModal = (flags & (InputWindowInfo::FLAG_NOT_FOCUSABLE
481 | InputWindowInfo::FLAG_NOT_TOUCH_MODAL)) == 0;
482 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
483 // Found window.
484 return windowHandle;
485 }
Jeff Brown928e0542011-01-10 11:17:36 -0800486 }
487 }
Jeff Brown928e0542011-01-10 11:17:36 -0800488
Jeff Brown83d616a2012-09-09 20:33:43 -0700489 if (flags & InputWindowInfo::FLAG_SYSTEM_ERROR) {
490 // Error window is on top but not visible, so touch is dropped.
491 return NULL;
492 }
Jeff Brown928e0542011-01-10 11:17:36 -0800493 }
494 }
495 return NULL;
496}
497
Jeff Brownb6997262010-10-08 22:31:17 -0700498void InputDispatcher::dropInboundEventLocked(EventEntry* entry, DropReason dropReason) {
499 const char* reason;
500 switch (dropReason) {
501 case DROP_REASON_POLICY:
Jeff Browne20c9e02010-10-11 14:20:19 -0700502#if DEBUG_INBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +0000503 ALOGD("Dropped event because policy consumed it.");
Jeff Browne20c9e02010-10-11 14:20:19 -0700504#endif
Jeff Brown3122e442010-10-11 23:32:49 -0700505 reason = "inbound event was dropped because the policy consumed it";
Jeff Brownb6997262010-10-08 22:31:17 -0700506 break;
507 case DROP_REASON_DISABLED:
Steve Block6215d3f2012-01-04 20:05:49 +0000508 ALOGI("Dropped event because input dispatch is disabled.");
Jeff Brownb6997262010-10-08 22:31:17 -0700509 reason = "inbound event was dropped because input dispatch is disabled";
510 break;
511 case DROP_REASON_APP_SWITCH:
Steve Block6215d3f2012-01-04 20:05:49 +0000512 ALOGI("Dropped event because of pending overdue app switch.");
Jeff Brownb6997262010-10-08 22:31:17 -0700513 reason = "inbound event was dropped because of pending overdue app switch";
514 break;
Jeff Brown928e0542011-01-10 11:17:36 -0800515 case DROP_REASON_BLOCKED:
Steve Block6215d3f2012-01-04 20:05:49 +0000516 ALOGI("Dropped event because the current application is not responding and the user "
Jeff Brown81346812011-06-28 20:08:48 -0700517 "has started interacting with a different application.");
Jeff Brown928e0542011-01-10 11:17:36 -0800518 reason = "inbound event was dropped because the current application is not responding "
Jeff Brown81346812011-06-28 20:08:48 -0700519 "and the user has started interacting with a different application";
Jeff Brown928e0542011-01-10 11:17:36 -0800520 break;
521 case DROP_REASON_STALE:
Steve Block6215d3f2012-01-04 20:05:49 +0000522 ALOGI("Dropped event because it is stale.");
Jeff Brown928e0542011-01-10 11:17:36 -0800523 reason = "inbound event was dropped because it is stale";
524 break;
Jeff Brownb6997262010-10-08 22:31:17 -0700525 default:
Steve Blockec193de2012-01-09 18:35:44 +0000526 ALOG_ASSERT(false);
Jeff Brownb6997262010-10-08 22:31:17 -0700527 return;
528 }
529
530 switch (entry->type) {
Jeff Brownda3d5a92011-03-29 15:11:34 -0700531 case EventEntry::TYPE_KEY: {
532 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
533 synthesizeCancelationEventsForAllConnectionsLocked(options);
Jeff Brownb6997262010-10-08 22:31:17 -0700534 break;
Jeff Brownda3d5a92011-03-29 15:11:34 -0700535 }
Jeff Brownb6997262010-10-08 22:31:17 -0700536 case EventEntry::TYPE_MOTION: {
537 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
538 if (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) {
Jeff Brownda3d5a92011-03-29 15:11:34 -0700539 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
540 synthesizeCancelationEventsForAllConnectionsLocked(options);
Jeff Brownb6997262010-10-08 22:31:17 -0700541 } else {
Jeff Brownda3d5a92011-03-29 15:11:34 -0700542 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
543 synthesizeCancelationEventsForAllConnectionsLocked(options);
Jeff Brownb6997262010-10-08 22:31:17 -0700544 }
545 break;
546 }
547 }
548}
549
550bool InputDispatcher::isAppSwitchKeyCode(int32_t keyCode) {
Michael Wright75ebb37f2013-03-15 16:27:29 -0700551 return keyCode == AKEYCODE_HOME
552 || keyCode == AKEYCODE_ENDCALL
553 || keyCode == AKEYCODE_APP_SWITCH;
Jeff Brownb88102f2010-09-08 11:49:43 -0700554}
555
Jeff Brownb6997262010-10-08 22:31:17 -0700556bool InputDispatcher::isAppSwitchKeyEventLocked(KeyEntry* keyEntry) {
557 return ! (keyEntry->flags & AKEY_EVENT_FLAG_CANCELED)
558 && isAppSwitchKeyCode(keyEntry->keyCode)
Jeff Browne20c9e02010-10-11 14:20:19 -0700559 && (keyEntry->policyFlags & POLICY_FLAG_TRUSTED)
Jeff Brownb6997262010-10-08 22:31:17 -0700560 && (keyEntry->policyFlags & POLICY_FLAG_PASS_TO_USER);
561}
562
Jeff Brownb88102f2010-09-08 11:49:43 -0700563bool InputDispatcher::isAppSwitchPendingLocked() {
564 return mAppSwitchDueTime != LONG_LONG_MAX;
565}
566
Jeff Brownb88102f2010-09-08 11:49:43 -0700567void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
568 mAppSwitchDueTime = LONG_LONG_MAX;
569
570#if DEBUG_APP_SWITCH
571 if (handled) {
Steve Block5baa3a62011-12-20 16:23:08 +0000572 ALOGD("App switch has arrived.");
Jeff Brownb88102f2010-09-08 11:49:43 -0700573 } else {
Steve Block5baa3a62011-12-20 16:23:08 +0000574 ALOGD("App switch was abandoned.");
Jeff Brownb88102f2010-09-08 11:49:43 -0700575 }
576#endif
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700577}
578
Jeff Brown928e0542011-01-10 11:17:36 -0800579bool InputDispatcher::isStaleEventLocked(nsecs_t currentTime, EventEntry* entry) {
580 return currentTime - entry->eventTime >= STALE_EVENT_TIMEOUT;
581}
582
Jeff Brown074b8b72012-10-31 19:01:31 -0700583bool InputDispatcher::haveCommandsLocked() const {
584 return !mCommandQueue.isEmpty();
585}
586
Jeff Brown9c3cda02010-06-15 01:31:58 -0700587bool InputDispatcher::runCommandsLockedInterruptible() {
588 if (mCommandQueue.isEmpty()) {
589 return false;
590 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700591
Jeff Brown9c3cda02010-06-15 01:31:58 -0700592 do {
593 CommandEntry* commandEntry = mCommandQueue.dequeueAtHead();
594
595 Command command = commandEntry->command;
596 (this->*command)(commandEntry); // commands are implicitly 'LockedInterruptible'
597
Jeff Brown7fbdc842010-06-17 20:52:56 -0700598 commandEntry->connection.clear();
Jeff Brownac386072011-07-20 15:19:50 -0700599 delete commandEntry;
Jeff Brown9c3cda02010-06-15 01:31:58 -0700600 } while (! mCommandQueue.isEmpty());
601 return true;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700602}
603
Jeff Brown9c3cda02010-06-15 01:31:58 -0700604InputDispatcher::CommandEntry* InputDispatcher::postCommandLocked(Command command) {
Jeff Brownac386072011-07-20 15:19:50 -0700605 CommandEntry* commandEntry = new CommandEntry(command);
Jeff Brown9c3cda02010-06-15 01:31:58 -0700606 mCommandQueue.enqueueAtTail(commandEntry);
607 return commandEntry;
608}
609
Jeff Brownb88102f2010-09-08 11:49:43 -0700610void InputDispatcher::drainInboundQueueLocked() {
611 while (! mInboundQueue.isEmpty()) {
612 EventEntry* entry = mInboundQueue.dequeueAtHead();
Jeff Brown54a18252010-09-16 14:07:33 -0700613 releaseInboundEventLocked(entry);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700614 }
Jeff Brown481c1572012-03-09 14:41:15 -0800615 traceInboundQueueLengthLocked();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700616}
617
Jeff Brown54a18252010-09-16 14:07:33 -0700618void InputDispatcher::releasePendingEventLocked() {
Jeff Brownb88102f2010-09-08 11:49:43 -0700619 if (mPendingEvent) {
Jeff Browne9bb9be2012-02-06 15:47:55 -0800620 resetANRTimeoutsLocked();
Jeff Brown54a18252010-09-16 14:07:33 -0700621 releaseInboundEventLocked(mPendingEvent);
Jeff Brownb88102f2010-09-08 11:49:43 -0700622 mPendingEvent = NULL;
623 }
624}
625
Jeff Brown54a18252010-09-16 14:07:33 -0700626void InputDispatcher::releaseInboundEventLocked(EventEntry* entry) {
Jeff Brown01ce2e92010-09-26 22:20:12 -0700627 InjectionState* injectionState = entry->injectionState;
628 if (injectionState && injectionState->injectionResult == INPUT_EVENT_INJECTION_PENDING) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700629#if DEBUG_DISPATCH_CYCLE
Steve Block5baa3a62011-12-20 16:23:08 +0000630 ALOGD("Injected inbound event was dropped.");
Jeff Brownb88102f2010-09-08 11:49:43 -0700631#endif
632 setInjectionResultLocked(entry, INPUT_EVENT_INJECTION_FAILED);
633 }
Jeff Brownabb4d442011-08-15 12:55:32 -0700634 if (entry == mNextUnblockedEvent) {
635 mNextUnblockedEvent = NULL;
636 }
Jeff Brown6876f322013-08-07 16:46:50 -0700637 addRecentEventLocked(entry);
Jeff Brownac386072011-07-20 15:19:50 -0700638 entry->release();
Jeff Brownb88102f2010-09-08 11:49:43 -0700639}
640
Jeff Brownb88102f2010-09-08 11:49:43 -0700641void InputDispatcher::resetKeyRepeatLocked() {
642 if (mKeyRepeatState.lastKeyEntry) {
Jeff Brownac386072011-07-20 15:19:50 -0700643 mKeyRepeatState.lastKeyEntry->release();
Jeff Brownb88102f2010-09-08 11:49:43 -0700644 mKeyRepeatState.lastKeyEntry = NULL;
645 }
646}
647
Jeff Brown214eaf42011-05-26 19:17:02 -0700648InputDispatcher::KeyEntry* InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
Jeff Brown349703e2010-06-22 01:27:15 -0700649 KeyEntry* entry = mKeyRepeatState.lastKeyEntry;
650
Jeff Brown349703e2010-06-22 01:27:15 -0700651 // Reuse the repeated key entry if it is otherwise unreferenced.
Jeff Browne20c9e02010-10-11 14:20:19 -0700652 uint32_t policyFlags = (entry->policyFlags & POLICY_FLAG_RAW_MASK)
653 | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700654 if (entry->refCount == 1) {
Jeff Brownac386072011-07-20 15:19:50 -0700655 entry->recycle();
Jeff Brown7fbdc842010-06-17 20:52:56 -0700656 entry->eventTime = currentTime;
Jeff Brown7fbdc842010-06-17 20:52:56 -0700657 entry->policyFlags = policyFlags;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700658 entry->repeatCount += 1;
659 } else {
Jeff Brownac386072011-07-20 15:19:50 -0700660 KeyEntry* newEntry = new KeyEntry(currentTime,
Jeff Brownc5ed5912010-07-14 18:48:53 -0700661 entry->deviceId, entry->source, policyFlags,
Jeff Brown7fbdc842010-06-17 20:52:56 -0700662 entry->action, entry->flags, entry->keyCode, entry->scanCode,
Jeff Brown00fa7bd2010-07-02 15:37:36 -0700663 entry->metaState, entry->repeatCount + 1, entry->downTime);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700664
665 mKeyRepeatState.lastKeyEntry = newEntry;
Jeff Brownac386072011-07-20 15:19:50 -0700666 entry->release();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700667
668 entry = newEntry;
669 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700670 entry->syntheticRepeat = true;
671
672 // Increment reference count since we keep a reference to the event in
673 // mKeyRepeatState.lastKeyEntry in addition to the one we return.
674 entry->refCount += 1;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700675
Jeff Brown214eaf42011-05-26 19:17:02 -0700676 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Jeff Brownb88102f2010-09-08 11:49:43 -0700677 return entry;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700678}
679
Jeff Brownb88102f2010-09-08 11:49:43 -0700680bool InputDispatcher::dispatchConfigurationChangedLocked(
681 nsecs_t currentTime, ConfigurationChangedEntry* entry) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700682#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +0000683 ALOGD("dispatchConfigurationChanged - eventTime=%lld", entry->eventTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700684#endif
685
686 // Reset key repeating in case a keyboard device was added or removed or something.
687 resetKeyRepeatLocked();
688
689 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
690 CommandEntry* commandEntry = postCommandLocked(
691 & InputDispatcher::doNotifyConfigurationChangedInterruptible);
692 commandEntry->eventTime = entry->eventTime;
693 return true;
694}
695
Jeff Brown65fd2512011-08-18 11:20:58 -0700696bool InputDispatcher::dispatchDeviceResetLocked(
697 nsecs_t currentTime, DeviceResetEntry* entry) {
698#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +0000699 ALOGD("dispatchDeviceReset - eventTime=%lld, deviceId=%d", entry->eventTime, entry->deviceId);
Jeff Brown65fd2512011-08-18 11:20:58 -0700700#endif
701
702 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
703 "device was reset");
704 options.deviceId = entry->deviceId;
705 synthesizeCancelationEventsForAllConnectionsLocked(options);
706 return true;
707}
708
Jeff Brown214eaf42011-05-26 19:17:02 -0700709bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, KeyEntry* entry,
Jeff Browne20c9e02010-10-11 14:20:19 -0700710 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Jeff Browne46a0a42010-11-02 17:58:22 -0700711 // Preprocessing.
712 if (! entry->dispatchInProgress) {
713 if (entry->repeatCount == 0
714 && entry->action == AKEY_EVENT_ACTION_DOWN
715 && (entry->policyFlags & POLICY_FLAG_TRUSTED)
Jeff Brown0029c662011-03-30 02:25:18 -0700716 && (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
Jeff Browne46a0a42010-11-02 17:58:22 -0700717 if (mKeyRepeatState.lastKeyEntry
718 && mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode) {
719 // We have seen two identical key downs in a row which indicates that the device
720 // driver is automatically generating key repeats itself. We take note of the
721 // repeat here, but we disable our own next key repeat timer since it is clear that
722 // we will not need to synthesize key repeats ourselves.
723 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
724 resetKeyRepeatLocked();
725 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
726 } else {
727 // Not a repeat. Save key down state in case we do see a repeat later.
728 resetKeyRepeatLocked();
Jeff Brown214eaf42011-05-26 19:17:02 -0700729 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
Jeff Browne46a0a42010-11-02 17:58:22 -0700730 }
731 mKeyRepeatState.lastKeyEntry = entry;
732 entry->refCount += 1;
733 } else if (! entry->syntheticRepeat) {
734 resetKeyRepeatLocked();
735 }
736
Jeff Browne2e01262011-03-02 20:34:30 -0800737 if (entry->repeatCount == 1) {
738 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
739 } else {
740 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
741 }
742
Jeff Browne46a0a42010-11-02 17:58:22 -0700743 entry->dispatchInProgress = true;
Jeff Browne46a0a42010-11-02 17:58:22 -0700744
745 logOutboundKeyDetailsLocked("dispatchKey - ", entry);
746 }
747
Jeff Brown905805a2011-10-12 13:57:59 -0700748 // Handle case where the policy asked us to try again later last time.
749 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
750 if (currentTime < entry->interceptKeyWakeupTime) {
751 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
752 *nextWakeupTime = entry->interceptKeyWakeupTime;
753 }
754 return false; // wait until next wakeup
755 }
756 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
757 entry->interceptKeyWakeupTime = 0;
758 }
759
Jeff Brown54a18252010-09-16 14:07:33 -0700760 // Give the policy a chance to intercept the key.
761 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
Jeff Browne20c9e02010-10-11 14:20:19 -0700762 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Jeff Brown54a18252010-09-16 14:07:33 -0700763 CommandEntry* commandEntry = postCommandLocked(
764 & InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
Jeff Brown9302c872011-07-13 22:51:29 -0700765 if (mFocusedWindowHandle != NULL) {
766 commandEntry->inputWindowHandle = mFocusedWindowHandle;
Jeff Brown54a18252010-09-16 14:07:33 -0700767 }
768 commandEntry->keyEntry = entry;
769 entry->refCount += 1;
770 return false; // wait for the command to run
771 } else {
772 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
773 }
774 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Jeff Browne20c9e02010-10-11 14:20:19 -0700775 if (*dropReason == DROP_REASON_NOT_DROPPED) {
776 *dropReason = DROP_REASON_POLICY;
777 }
Jeff Brown54a18252010-09-16 14:07:33 -0700778 }
779
780 // Clean up if dropping the event.
Jeff Browne20c9e02010-10-11 14:20:19 -0700781 if (*dropReason != DROP_REASON_NOT_DROPPED) {
Jeff Brown3122e442010-10-11 23:32:49 -0700782 setInjectionResultLocked(entry, *dropReason == DROP_REASON_POLICY
783 ? INPUT_EVENT_INJECTION_SUCCEEDED : INPUT_EVENT_INJECTION_FAILED);
Jeff Brown54a18252010-09-16 14:07:33 -0700784 return true;
785 }
786
Jeff Brownb88102f2010-09-08 11:49:43 -0700787 // Identify targets.
Jeff Browne9bb9be2012-02-06 15:47:55 -0800788 Vector<InputTarget> inputTargets;
789 int32_t injectionResult = findFocusedWindowTargetsLocked(currentTime,
790 entry, inputTargets, nextWakeupTime);
791 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
792 return false;
Jeff Brownb88102f2010-09-08 11:49:43 -0700793 }
794
Jeff Browne9bb9be2012-02-06 15:47:55 -0800795 setInjectionResultLocked(entry, injectionResult);
796 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
797 return true;
798 }
799
800 addMonitoringTargetsLocked(inputTargets);
801
Jeff Brownb88102f2010-09-08 11:49:43 -0700802 // Dispatch the key.
Jeff Browne9bb9be2012-02-06 15:47:55 -0800803 dispatchEventLocked(currentTime, entry, inputTargets);
Jeff Brownb88102f2010-09-08 11:49:43 -0700804 return true;
805}
806
807void InputDispatcher::logOutboundKeyDetailsLocked(const char* prefix, const KeyEntry* entry) {
808#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +0000809 ALOGD("%seventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, "
Jeff Brownb88102f2010-09-08 11:49:43 -0700810 "action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, "
Jeff Browne46a0a42010-11-02 17:58:22 -0700811 "repeatCount=%d, downTime=%lld",
Jeff Brownb88102f2010-09-08 11:49:43 -0700812 prefix,
813 entry->eventTime, entry->deviceId, entry->source, entry->policyFlags,
814 entry->action, entry->flags, entry->keyCode, entry->scanCode, entry->metaState,
Jeff Browne46a0a42010-11-02 17:58:22 -0700815 entry->repeatCount, entry->downTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700816#endif
817}
818
819bool InputDispatcher::dispatchMotionLocked(
Jeff Browne20c9e02010-10-11 14:20:19 -0700820 nsecs_t currentTime, MotionEntry* entry, DropReason* dropReason, nsecs_t* nextWakeupTime) {
Jeff Browne46a0a42010-11-02 17:58:22 -0700821 // Preprocessing.
822 if (! entry->dispatchInProgress) {
823 entry->dispatchInProgress = true;
Jeff Browne46a0a42010-11-02 17:58:22 -0700824
825 logOutboundMotionDetailsLocked("dispatchMotion - ", entry);
826 }
827
Jeff Brown54a18252010-09-16 14:07:33 -0700828 // Clean up if dropping the event.
Jeff Browne20c9e02010-10-11 14:20:19 -0700829 if (*dropReason != DROP_REASON_NOT_DROPPED) {
Jeff Brown3122e442010-10-11 23:32:49 -0700830 setInjectionResultLocked(entry, *dropReason == DROP_REASON_POLICY
831 ? INPUT_EVENT_INJECTION_SUCCEEDED : INPUT_EVENT_INJECTION_FAILED);
Jeff Brown54a18252010-09-16 14:07:33 -0700832 return true;
833 }
834
Jeff Brownb88102f2010-09-08 11:49:43 -0700835 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
836
837 // Identify targets.
Jeff Browne9bb9be2012-02-06 15:47:55 -0800838 Vector<InputTarget> inputTargets;
839
Jeff Browncc0c1592011-02-19 05:07:28 -0800840 bool conflictingPointerActions = false;
Jeff Browne9bb9be2012-02-06 15:47:55 -0800841 int32_t injectionResult;
842 if (isPointerEvent) {
843 // Pointer event. (eg. touchscreen)
844 injectionResult = findTouchedWindowTargetsLocked(currentTime,
845 entry, inputTargets, nextWakeupTime, &conflictingPointerActions);
846 } else {
847 // Non touch event. (eg. trackball)
848 injectionResult = findFocusedWindowTargetsLocked(currentTime,
849 entry, inputTargets, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700850 }
Jeff Browne9bb9be2012-02-06 15:47:55 -0800851 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
852 return false;
853 }
854
855 setInjectionResultLocked(entry, injectionResult);
856 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
857 return true;
858 }
859
Jeff Brown83d616a2012-09-09 20:33:43 -0700860 // TODO: support sending secondary display events to input monitors
861 if (isMainDisplay(entry->displayId)) {
862 addMonitoringTargetsLocked(inputTargets);
863 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700864
865 // Dispatch the motion.
Jeff Browncc0c1592011-02-19 05:07:28 -0800866 if (conflictingPointerActions) {
Jeff Brownda3d5a92011-03-29 15:11:34 -0700867 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
868 "conflicting pointer actions");
869 synthesizeCancelationEventsForAllConnectionsLocked(options);
Jeff Browncc0c1592011-02-19 05:07:28 -0800870 }
Jeff Browne9bb9be2012-02-06 15:47:55 -0800871 dispatchEventLocked(currentTime, entry, inputTargets);
Jeff Brownb88102f2010-09-08 11:49:43 -0700872 return true;
873}
874
875
876void InputDispatcher::logOutboundMotionDetailsLocked(const char* prefix, const MotionEntry* entry) {
877#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +0000878 ALOGD("%seventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, "
Jeff Brown85a31762010-09-01 17:01:00 -0700879 "action=0x%x, flags=0x%x, "
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700880 "metaState=0x%x, buttonState=0x%x, "
881 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%lld",
Jeff Brownb88102f2010-09-08 11:49:43 -0700882 prefix,
Jeff Brown85a31762010-09-01 17:01:00 -0700883 entry->eventTime, entry->deviceId, entry->source, entry->policyFlags,
884 entry->action, entry->flags,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700885 entry->metaState, entry->buttonState,
886 entry->edgeFlags, entry->xPrecision, entry->yPrecision,
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700887 entry->downTime);
888
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700889 for (uint32_t i = 0; i < entry->pointerCount; i++) {
Steve Block5baa3a62011-12-20 16:23:08 +0000890 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700891 "x=%f, y=%f, pressure=%f, size=%f, "
Jeff Brown85a31762010-09-01 17:01:00 -0700892 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
Jeff Brown8d608662010-08-30 03:02:23 -0700893 "orientation=%f",
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700894 i, entry->pointerProperties[i].id,
895 entry->pointerProperties[i].toolType,
Jeff Brown3241b6b2012-02-03 15:08:02 -0800896 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
897 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
898 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
899 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
900 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
901 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
902 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
903 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
904 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700905 }
906#endif
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700907}
908
Jeff Browne9bb9be2012-02-06 15:47:55 -0800909void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
910 EventEntry* eventEntry, const Vector<InputTarget>& inputTargets) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700911#if DEBUG_DISPATCH_CYCLE
Jeff Brown3241b6b2012-02-03 15:08:02 -0800912 ALOGD("dispatchEventToCurrentInputTargets");
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700913#endif
914
Steve Blockec193de2012-01-09 18:35:44 +0000915 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
Jeff Brown9c3cda02010-06-15 01:31:58 -0700916
Jeff Browne2fe69e2010-10-18 13:21:23 -0700917 pokeUserActivityLocked(eventEntry);
918
Jeff Browne9bb9be2012-02-06 15:47:55 -0800919 for (size_t i = 0; i < inputTargets.size(); i++) {
920 const InputTarget& inputTarget = inputTargets.itemAt(i);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700921
Jeff Brown519e0242010-09-15 15:18:56 -0700922 ssize_t connectionIndex = getConnectionIndexLocked(inputTarget.inputChannel);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700923 if (connectionIndex >= 0) {
Jeff Browncbee6d62012-02-03 20:11:27 -0800924 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
Jeff Brown3241b6b2012-02-03 15:08:02 -0800925 prepareDispatchCycleLocked(currentTime, connection, eventEntry, &inputTarget);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700926 } else {
Jeff Brownb6997262010-10-08 22:31:17 -0700927#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +0000928 ALOGD("Dropping event delivery to target with channel '%s' because it "
Jeff Brownb6997262010-10-08 22:31:17 -0700929 "is no longer registered with the input dispatcher.",
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700930 inputTarget.inputChannel->getName().string());
Jeff Brownb6997262010-10-08 22:31:17 -0700931#endif
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700932 }
933 }
934}
935
Jeff Brownb88102f2010-09-08 11:49:43 -0700936int32_t InputDispatcher::handleTargetsNotReadyLocked(nsecs_t currentTime,
Jeff Brown9302c872011-07-13 22:51:29 -0700937 const EventEntry* entry,
938 const sp<InputApplicationHandle>& applicationHandle,
939 const sp<InputWindowHandle>& windowHandle,
Jeff Brown265f1cc2012-06-11 18:01:06 -0700940 nsecs_t* nextWakeupTime, const char* reason) {
Jeff Brown9302c872011-07-13 22:51:29 -0700941 if (applicationHandle == NULL && windowHandle == NULL) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700942 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY) {
943#if DEBUG_FOCUS
Jeff Brown265f1cc2012-06-11 18:01:06 -0700944 ALOGD("Waiting for system to become ready for input. Reason: %s", reason);
Jeff Brownb88102f2010-09-08 11:49:43 -0700945#endif
946 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY;
947 mInputTargetWaitStartTime = currentTime;
948 mInputTargetWaitTimeoutTime = LONG_LONG_MAX;
949 mInputTargetWaitTimeoutExpired = false;
Jeff Brown9302c872011-07-13 22:51:29 -0700950 mInputTargetWaitApplicationHandle.clear();
Jeff Brownb88102f2010-09-08 11:49:43 -0700951 }
952 } else {
953 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
954#if DEBUG_FOCUS
Jeff Brown265f1cc2012-06-11 18:01:06 -0700955 ALOGD("Waiting for application to become ready for input: %s. Reason: %s",
956 getApplicationWindowLabelLocked(applicationHandle, windowHandle).string(),
957 reason);
Jeff Brownb88102f2010-09-08 11:49:43 -0700958#endif
Jeff Browncc4f7db2011-08-30 20:34:48 -0700959 nsecs_t timeout;
960 if (windowHandle != NULL) {
961 timeout = windowHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
962 } else if (applicationHandle != NULL) {
963 timeout = applicationHandle->getDispatchingTimeout(
964 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
965 } else {
966 timeout = DEFAULT_INPUT_DISPATCHING_TIMEOUT;
967 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700968
969 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY;
970 mInputTargetWaitStartTime = currentTime;
971 mInputTargetWaitTimeoutTime = currentTime + timeout;
972 mInputTargetWaitTimeoutExpired = false;
Jeff Brown9302c872011-07-13 22:51:29 -0700973 mInputTargetWaitApplicationHandle.clear();
Jeff Brown928e0542011-01-10 11:17:36 -0800974
Jeff Brown9302c872011-07-13 22:51:29 -0700975 if (windowHandle != NULL) {
976 mInputTargetWaitApplicationHandle = windowHandle->inputApplicationHandle;
Jeff Brown928e0542011-01-10 11:17:36 -0800977 }
Jeff Brown9302c872011-07-13 22:51:29 -0700978 if (mInputTargetWaitApplicationHandle == NULL && applicationHandle != NULL) {
979 mInputTargetWaitApplicationHandle = applicationHandle;
Jeff Brown928e0542011-01-10 11:17:36 -0800980 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700981 }
982 }
983
984 if (mInputTargetWaitTimeoutExpired) {
985 return INPUT_EVENT_INJECTION_TIMED_OUT;
986 }
987
988 if (currentTime >= mInputTargetWaitTimeoutTime) {
Jeff Brown9302c872011-07-13 22:51:29 -0700989 onANRLocked(currentTime, applicationHandle, windowHandle,
Jeff Brown265f1cc2012-06-11 18:01:06 -0700990 entry->eventTime, mInputTargetWaitStartTime, reason);
Jeff Brownb88102f2010-09-08 11:49:43 -0700991
992 // Force poll loop to wake up immediately on next iteration once we get the
993 // ANR response back from the policy.
994 *nextWakeupTime = LONG_LONG_MIN;
995 return INPUT_EVENT_INJECTION_PENDING;
996 } else {
997 // Force poll loop to wake up when timeout is due.
998 if (mInputTargetWaitTimeoutTime < *nextWakeupTime) {
999 *nextWakeupTime = mInputTargetWaitTimeoutTime;
1000 }
1001 return INPUT_EVENT_INJECTION_PENDING;
1002 }
1003}
1004
Jeff Brown519e0242010-09-15 15:18:56 -07001005void InputDispatcher::resumeAfterTargetsNotReadyTimeoutLocked(nsecs_t newTimeout,
1006 const sp<InputChannel>& inputChannel) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001007 if (newTimeout > 0) {
1008 // Extend the timeout.
1009 mInputTargetWaitTimeoutTime = now() + newTimeout;
1010 } else {
1011 // Give up.
1012 mInputTargetWaitTimeoutExpired = true;
Jeff Brown519e0242010-09-15 15:18:56 -07001013
1014 // Input state will not be realistic. Mark it out of sync.
Jeff Browndc3e0052010-09-16 11:02:16 -07001015 if (inputChannel.get()) {
1016 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
1017 if (connectionIndex >= 0) {
Jeff Browncbee6d62012-02-03 20:11:27 -08001018 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
Jeff Brownf44e3942012-04-20 11:33:27 -07001019 sp<InputWindowHandle> windowHandle = connection->inputWindowHandle;
1020
1021 if (windowHandle != NULL) {
1022 mTouchState.removeWindow(windowHandle);
1023 }
1024
Jeff Brown00045a72010-12-09 18:10:30 -08001025 if (connection->status == Connection::STATUS_NORMAL) {
Jeff Brownda3d5a92011-03-29 15:11:34 -07001026 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
Jeff Brown00045a72010-12-09 18:10:30 -08001027 "application not responding");
Jeff Brownda3d5a92011-03-29 15:11:34 -07001028 synthesizeCancelationEventsForConnectionLocked(connection, options);
Jeff Brown00045a72010-12-09 18:10:30 -08001029 }
Jeff Browndc3e0052010-09-16 11:02:16 -07001030 }
Jeff Brown519e0242010-09-15 15:18:56 -07001031 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001032 }
1033}
1034
Jeff Brown519e0242010-09-15 15:18:56 -07001035nsecs_t InputDispatcher::getTimeSpentWaitingForApplicationLocked(
Jeff Brownb88102f2010-09-08 11:49:43 -07001036 nsecs_t currentTime) {
1037 if (mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
1038 return currentTime - mInputTargetWaitStartTime;
1039 }
1040 return 0;
1041}
1042
1043void InputDispatcher::resetANRTimeoutsLocked() {
1044#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001045 ALOGD("Resetting ANR timeouts.");
Jeff Brownb88102f2010-09-08 11:49:43 -07001046#endif
1047
Jeff Brownb88102f2010-09-08 11:49:43 -07001048 // Reset input target wait timeout.
1049 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_NONE;
Jeff Brown5ea29ab2011-07-27 11:50:51 -07001050 mInputTargetWaitApplicationHandle.clear();
Jeff Brownb88102f2010-09-08 11:49:43 -07001051}
1052
Jeff Brown01ce2e92010-09-26 22:20:12 -07001053int32_t InputDispatcher::findFocusedWindowTargetsLocked(nsecs_t currentTime,
Jeff Browne9bb9be2012-02-06 15:47:55 -08001054 const EventEntry* entry, Vector<InputTarget>& inputTargets, nsecs_t* nextWakeupTime) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001055 int32_t injectionResult;
1056
1057 // If there is no currently focused window and no focused application
1058 // then drop the event.
Jeff Brown9302c872011-07-13 22:51:29 -07001059 if (mFocusedWindowHandle == NULL) {
1060 if (mFocusedApplicationHandle != NULL) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001061 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brown265f1cc2012-06-11 18:01:06 -07001062 mFocusedApplicationHandle, NULL, nextWakeupTime,
1063 "Waiting because no window has focus but there is a "
1064 "focused application that may eventually add a window "
1065 "when it finishes starting up.");
Jeff Brownb88102f2010-09-08 11:49:43 -07001066 goto Unresponsive;
1067 }
1068
Steve Block6215d3f2012-01-04 20:05:49 +00001069 ALOGI("Dropping event because there is no focused window or focused application.");
Jeff Brownb88102f2010-09-08 11:49:43 -07001070 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1071 goto Failed;
1072 }
1073
1074 // Check permissions.
Jeff Brown9302c872011-07-13 22:51:29 -07001075 if (! checkInjectionPermission(mFocusedWindowHandle, entry->injectionState)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001076 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1077 goto Failed;
1078 }
1079
1080 // If the currently focused window is paused then keep waiting.
Jeff Browncc4f7db2011-08-30 20:34:48 -07001081 if (mFocusedWindowHandle->getInfo()->paused) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001082 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brown265f1cc2012-06-11 18:01:06 -07001083 mFocusedApplicationHandle, mFocusedWindowHandle, nextWakeupTime,
1084 "Waiting because the focused window is paused.");
Jeff Brownb88102f2010-09-08 11:49:43 -07001085 goto Unresponsive;
1086 }
1087
Jeff Brown519e0242010-09-15 15:18:56 -07001088 // If the currently focused window is still working on previous events then keep waiting.
Jeff Brown0952c302012-02-13 13:48:59 -08001089 if (!isWindowReadyForMoreInputLocked(currentTime, mFocusedWindowHandle, entry)) {
Jeff Brown519e0242010-09-15 15:18:56 -07001090 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brown265f1cc2012-06-11 18:01:06 -07001091 mFocusedApplicationHandle, mFocusedWindowHandle, nextWakeupTime,
1092 "Waiting because the focused window has not finished "
1093 "processing the input events that were previously delivered to it.");
Jeff Brown519e0242010-09-15 15:18:56 -07001094 goto Unresponsive;
1095 }
1096
Jeff Brownb88102f2010-09-08 11:49:43 -07001097 // Success! Output targets.
1098 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
Jeff Brown9302c872011-07-13 22:51:29 -07001099 addWindowTargetLocked(mFocusedWindowHandle,
Jeff Browne9bb9be2012-02-06 15:47:55 -08001100 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS, BitSet32(0),
1101 inputTargets);
Jeff Brownb88102f2010-09-08 11:49:43 -07001102
1103 // Done.
1104Failed:
1105Unresponsive:
Jeff Brown519e0242010-09-15 15:18:56 -07001106 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
1107 updateDispatchStatisticsLocked(currentTime, entry,
1108 injectionResult, timeSpentWaitingForApplication);
Jeff Brownb88102f2010-09-08 11:49:43 -07001109#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001110 ALOGD("findFocusedWindow finished: injectionResult=%d, "
Jeff Brown22aa5122012-06-17 12:01:06 -07001111 "timeSpentWaitingForApplication=%0.1fms",
Jeff Brown519e0242010-09-15 15:18:56 -07001112 injectionResult, timeSpentWaitingForApplication / 1000000.0);
Jeff Brownb88102f2010-09-08 11:49:43 -07001113#endif
1114 return injectionResult;
1115}
1116
Jeff Brown01ce2e92010-09-26 22:20:12 -07001117int32_t InputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime,
Jeff Browne9bb9be2012-02-06 15:47:55 -08001118 const MotionEntry* entry, Vector<InputTarget>& inputTargets, nsecs_t* nextWakeupTime,
1119 bool* outConflictingPointerActions) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001120 enum InjectionPermission {
1121 INJECTION_PERMISSION_UNKNOWN,
1122 INJECTION_PERMISSION_GRANTED,
1123 INJECTION_PERMISSION_DENIED
1124 };
1125
Jeff Brownb88102f2010-09-08 11:49:43 -07001126 nsecs_t startTime = now();
1127
1128 // For security reasons, we defer updating the touch state until we are sure that
1129 // event injection will be allowed.
1130 //
1131 // FIXME In the original code, screenWasOff could never be set to true.
1132 // The reason is that the POLICY_FLAG_WOKE_HERE
1133 // and POLICY_FLAG_BRIGHT_HERE flags were set only when preprocessing raw
1134 // EV_KEY, EV_REL and EV_ABS events. As it happens, the touch event was
1135 // actually enqueued using the policyFlags that appeared in the final EV_SYN
1136 // events upon which no preprocessing took place. So policyFlags was always 0.
1137 // In the new native input dispatcher we're a bit more careful about event
1138 // preprocessing so the touches we receive can actually have non-zero policyFlags.
1139 // Unfortunately we obtain undesirable behavior.
1140 //
1141 // Here's what happens:
1142 //
1143 // When the device dims in anticipation of going to sleep, touches
1144 // in windows which have FLAG_TOUCHABLE_WHEN_WAKING cause
1145 // the device to brighten and reset the user activity timer.
1146 // Touches on other windows (such as the launcher window)
1147 // are dropped. Then after a moment, the device goes to sleep. Oops.
1148 //
1149 // Also notice how screenWasOff was being initialized using POLICY_FLAG_BRIGHT_HERE
1150 // instead of POLICY_FLAG_WOKE_HERE...
1151 //
1152 bool screenWasOff = false; // original policy: policyFlags & POLICY_FLAG_BRIGHT_HERE;
1153
Jeff Brown83d616a2012-09-09 20:33:43 -07001154 int32_t displayId = entry->displayId;
Jeff Brownb88102f2010-09-08 11:49:43 -07001155 int32_t action = entry->action;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001156 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Jeff Brownb88102f2010-09-08 11:49:43 -07001157
1158 // Update the touch state as needed based on the properties of the touch event.
Jeff Brown01ce2e92010-09-26 22:20:12 -07001159 int32_t injectionResult = INPUT_EVENT_INJECTION_PENDING;
1160 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
Jeff Brown9302c872011-07-13 22:51:29 -07001161 sp<InputWindowHandle> newHoverWindowHandle;
Jeff Browncc0c1592011-02-19 05:07:28 -08001162
1163 bool isSplit = mTouchState.split;
Jeff Brown83d616a2012-09-09 20:33:43 -07001164 bool switchedDevice = mTouchState.deviceId >= 0 && mTouchState.displayId >= 0
Jeff Brown2717eff2011-06-30 23:53:07 -07001165 && (mTouchState.deviceId != entry->deviceId
Jeff Brown83d616a2012-09-09 20:33:43 -07001166 || mTouchState.source != entry->source
1167 || mTouchState.displayId != displayId);
Jeff Browna032cc02011-03-07 16:56:21 -08001168 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE
1169 || maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER
1170 || maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1171 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN
1172 || maskedAction == AMOTION_EVENT_ACTION_SCROLL
1173 || isHoverAction);
Jeff Brown81346812011-06-28 20:08:48 -07001174 bool wrongDevice = false;
Jeff Browna032cc02011-03-07 16:56:21 -08001175 if (newGesture) {
Jeff Browncc0c1592011-02-19 05:07:28 -08001176 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Jeff Brown81346812011-06-28 20:08:48 -07001177 if (switchedDevice && mTouchState.down && !down) {
1178#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001179 ALOGD("Dropping event because a pointer for a different device is already down.");
Jeff Brown81346812011-06-28 20:08:48 -07001180#endif
Jeff Browncc0c1592011-02-19 05:07:28 -08001181 mTempTouchState.copyFrom(mTouchState);
Jeff Brown81346812011-06-28 20:08:48 -07001182 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1183 switchedDevice = false;
1184 wrongDevice = true;
1185 goto Failed;
Jeff Browncc0c1592011-02-19 05:07:28 -08001186 }
Jeff Brown81346812011-06-28 20:08:48 -07001187 mTempTouchState.reset();
1188 mTempTouchState.down = down;
1189 mTempTouchState.deviceId = entry->deviceId;
1190 mTempTouchState.source = entry->source;
Jeff Brown83d616a2012-09-09 20:33:43 -07001191 mTempTouchState.displayId = displayId;
Jeff Brown81346812011-06-28 20:08:48 -07001192 isSplit = false;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001193 } else {
1194 mTempTouchState.copyFrom(mTouchState);
Jeff Browncc0c1592011-02-19 05:07:28 -08001195 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001196
Jeff Browna032cc02011-03-07 16:56:21 -08001197 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
Jeff Brown33bbfd22011-02-24 20:55:35 -08001198 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
Jeff Brownb88102f2010-09-08 11:49:43 -07001199
Jeff Brown01ce2e92010-09-26 22:20:12 -07001200 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Jeff Brown3241b6b2012-02-03 15:08:02 -08001201 int32_t x = int32_t(entry->pointerCoords[pointerIndex].
Jeff Brownebbd5d12011-02-17 13:01:34 -08001202 getAxisValue(AMOTION_EVENT_AXIS_X));
Jeff Brown3241b6b2012-02-03 15:08:02 -08001203 int32_t y = int32_t(entry->pointerCoords[pointerIndex].
Jeff Brownebbd5d12011-02-17 13:01:34 -08001204 getAxisValue(AMOTION_EVENT_AXIS_Y));
Jeff Brown9302c872011-07-13 22:51:29 -07001205 sp<InputWindowHandle> newTouchedWindowHandle;
1206 sp<InputWindowHandle> topErrorWindowHandle;
Jeff Browna032cc02011-03-07 16:56:21 -08001207 bool isTouchModal = false;
Jeff Brownb88102f2010-09-08 11:49:43 -07001208
1209 // Traverse windows from front to back to find touched window and outside targets.
Jeff Brown9302c872011-07-13 22:51:29 -07001210 size_t numWindows = mWindowHandles.size();
Jeff Brownb88102f2010-09-08 11:49:43 -07001211 for (size_t i = 0; i < numWindows; i++) {
Jeff Brown9302c872011-07-13 22:51:29 -07001212 sp<InputWindowHandle> windowHandle = mWindowHandles.itemAt(i);
Jeff Browncc4f7db2011-08-30 20:34:48 -07001213 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Jeff Brown83d616a2012-09-09 20:33:43 -07001214 if (windowInfo->displayId != displayId) {
1215 continue; // wrong display
1216 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001217
Jeff Brown83d616a2012-09-09 20:33:43 -07001218 int32_t flags = windowInfo->layoutParamsFlags;
Jeff Browncc4f7db2011-08-30 20:34:48 -07001219 if (flags & InputWindowInfo::FLAG_SYSTEM_ERROR) {
Jeff Brown9302c872011-07-13 22:51:29 -07001220 if (topErrorWindowHandle == NULL) {
1221 topErrorWindowHandle = windowHandle;
Jeff Brownb88102f2010-09-08 11:49:43 -07001222 }
1223 }
1224
Jeff Browncc4f7db2011-08-30 20:34:48 -07001225 if (windowInfo->visible) {
1226 if (! (flags & InputWindowInfo::FLAG_NOT_TOUCHABLE)) {
1227 isTouchModal = (flags & (InputWindowInfo::FLAG_NOT_FOCUSABLE
1228 | InputWindowInfo::FLAG_NOT_TOUCH_MODAL)) == 0;
1229 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
Jeff Brown9302c872011-07-13 22:51:29 -07001230 if (! screenWasOff
Jeff Browncc4f7db2011-08-30 20:34:48 -07001231 || (flags & InputWindowInfo::FLAG_TOUCHABLE_WHEN_WAKING)) {
Jeff Brown9302c872011-07-13 22:51:29 -07001232 newTouchedWindowHandle = windowHandle;
Jeff Brownb88102f2010-09-08 11:49:43 -07001233 }
1234 break; // found touched window, exit window loop
1235 }
1236 }
1237
Jeff Brown01ce2e92010-09-26 22:20:12 -07001238 if (maskedAction == AMOTION_EVENT_ACTION_DOWN
Jeff Browncc4f7db2011-08-30 20:34:48 -07001239 && (flags & InputWindowInfo::FLAG_WATCH_OUTSIDE_TOUCH)) {
Jeff Browna032cc02011-03-07 16:56:21 -08001240 int32_t outsideTargetFlags = InputTarget::FLAG_DISPATCH_AS_OUTSIDE;
Jeff Brown9302c872011-07-13 22:51:29 -07001241 if (isWindowObscuredAtPointLocked(windowHandle, x, y)) {
Jeff Brown19dfc832010-10-05 12:26:23 -07001242 outsideTargetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1243 }
1244
Jeff Brown9302c872011-07-13 22:51:29 -07001245 mTempTouchState.addOrUpdateWindow(
1246 windowHandle, outsideTargetFlags, BitSet32(0));
Jeff Brownb88102f2010-09-08 11:49:43 -07001247 }
1248 }
1249 }
1250
1251 // If there is an error window but it is not taking focus (typically because
1252 // it is invisible) then wait for it. Any other focused window may in
1253 // fact be in ANR state.
Jeff Brown9302c872011-07-13 22:51:29 -07001254 if (topErrorWindowHandle != NULL && newTouchedWindowHandle != topErrorWindowHandle) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001255 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brown265f1cc2012-06-11 18:01:06 -07001256 NULL, NULL, nextWakeupTime,
1257 "Waiting because a system error window is about to be displayed.");
Jeff Brownb88102f2010-09-08 11:49:43 -07001258 injectionPermission = INJECTION_PERMISSION_UNKNOWN;
1259 goto Unresponsive;
1260 }
1261
Jeff Brown01ce2e92010-09-26 22:20:12 -07001262 // Figure out whether splitting will be allowed for this window.
Jeff Browncc4f7db2011-08-30 20:34:48 -07001263 if (newTouchedWindowHandle != NULL
1264 && newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001265 // New window supports splitting.
1266 isSplit = true;
1267 } else if (isSplit) {
1268 // New window does not support splitting but we have already split events.
Jeff Brown8249fc62012-05-24 18:57:32 -07001269 // Ignore the new window.
1270 newTouchedWindowHandle = NULL;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001271 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001272
Jeff Brown8249fc62012-05-24 18:57:32 -07001273 // Handle the case where we did not find a window.
Jeff Brown9302c872011-07-13 22:51:29 -07001274 if (newTouchedWindowHandle == NULL) {
Jeff Brown8249fc62012-05-24 18:57:32 -07001275 // Try to assign the pointer to the first foreground window we find, if there is one.
1276 newTouchedWindowHandle = mTempTouchState.getFirstForegroundWindowHandle();
1277 if (newTouchedWindowHandle == NULL) {
Jeff Brown0b31d812013-08-22 19:41:29 -07001278 ALOGI("Dropping event because there is no touchable window at (%d, %d).", x, y);
Jeff Brown8249fc62012-05-24 18:57:32 -07001279 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1280 goto Failed;
1281 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001282 }
1283
Jeff Brown19dfc832010-10-05 12:26:23 -07001284 // Set target flags.
Jeff Browna032cc02011-03-07 16:56:21 -08001285 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
Jeff Brown19dfc832010-10-05 12:26:23 -07001286 if (isSplit) {
1287 targetFlags |= InputTarget::FLAG_SPLIT;
1288 }
Jeff Brown9302c872011-07-13 22:51:29 -07001289 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
Jeff Brown19dfc832010-10-05 12:26:23 -07001290 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1291 }
1292
Jeff Browna032cc02011-03-07 16:56:21 -08001293 // Update hover state.
1294 if (isHoverAction) {
Jeff Brown9302c872011-07-13 22:51:29 -07001295 newHoverWindowHandle = newTouchedWindowHandle;
Jeff Browna032cc02011-03-07 16:56:21 -08001296 } else if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
Jeff Brown9302c872011-07-13 22:51:29 -07001297 newHoverWindowHandle = mLastHoverWindowHandle;
Jeff Browna032cc02011-03-07 16:56:21 -08001298 }
1299
Jeff Brown01ce2e92010-09-26 22:20:12 -07001300 // Update the temporary touch state.
1301 BitSet32 pointerIds;
1302 if (isSplit) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07001303 uint32_t pointerId = entry->pointerProperties[pointerIndex].id;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001304 pointerIds.markBit(pointerId);
Jeff Brownb88102f2010-09-08 11:49:43 -07001305 }
Jeff Brown9302c872011-07-13 22:51:29 -07001306 mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Jeff Brownb88102f2010-09-08 11:49:43 -07001307 } else {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001308 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
Jeff Brownb88102f2010-09-08 11:49:43 -07001309
1310 // If the pointer is not currently down, then ignore the event.
Jeff Brown01ce2e92010-09-26 22:20:12 -07001311 if (! mTempTouchState.down) {
Jeff Browna2cc28d2011-03-25 11:58:46 -07001312#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001313 ALOGD("Dropping event because the pointer is not down or we previously "
Jeff Brown76860e32010-10-25 17:37:46 -07001314 "dropped the pointer down event.");
1315#endif
Jeff Brownb88102f2010-09-08 11:49:43 -07001316 injectionResult = INPUT_EVENT_INJECTION_FAILED;
Jeff Brownb88102f2010-09-08 11:49:43 -07001317 goto Failed;
1318 }
Jeff Brown98db5fa2011-06-08 15:37:10 -07001319
1320 // Check whether touches should slip outside of the current foreground window.
1321 if (maskedAction == AMOTION_EVENT_ACTION_MOVE
1322 && entry->pointerCount == 1
1323 && mTempTouchState.isSlippery()) {
Jeff Brown3241b6b2012-02-03 15:08:02 -08001324 int32_t x = int32_t(entry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
1325 int32_t y = int32_t(entry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Jeff Brown98db5fa2011-06-08 15:37:10 -07001326
Jeff Brown9302c872011-07-13 22:51:29 -07001327 sp<InputWindowHandle> oldTouchedWindowHandle =
1328 mTempTouchState.getFirstForegroundWindowHandle();
Jeff Brown83d616a2012-09-09 20:33:43 -07001329 sp<InputWindowHandle> newTouchedWindowHandle =
1330 findTouchedWindowAtLocked(displayId, x, y);
Jeff Brown9302c872011-07-13 22:51:29 -07001331 if (oldTouchedWindowHandle != newTouchedWindowHandle
1332 && newTouchedWindowHandle != NULL) {
Jeff Brown98db5fa2011-06-08 15:37:10 -07001333#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001334 ALOGD("Touch is slipping out of window %s into window %s.",
Jeff Browncc4f7db2011-08-30 20:34:48 -07001335 oldTouchedWindowHandle->getName().string(),
1336 newTouchedWindowHandle->getName().string());
Jeff Brown98db5fa2011-06-08 15:37:10 -07001337#endif
1338 // Make a slippery exit from the old window.
Jeff Brown9302c872011-07-13 22:51:29 -07001339 mTempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
Jeff Brown98db5fa2011-06-08 15:37:10 -07001340 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT, BitSet32(0));
1341
1342 // Make a slippery entrance into the new window.
Jeff Browncc4f7db2011-08-30 20:34:48 -07001343 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Jeff Brown98db5fa2011-06-08 15:37:10 -07001344 isSplit = true;
1345 }
1346
1347 int32_t targetFlags = InputTarget::FLAG_FOREGROUND
1348 | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
1349 if (isSplit) {
1350 targetFlags |= InputTarget::FLAG_SPLIT;
1351 }
Jeff Brown9302c872011-07-13 22:51:29 -07001352 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
Jeff Brown98db5fa2011-06-08 15:37:10 -07001353 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1354 }
1355
1356 BitSet32 pointerIds;
1357 if (isSplit) {
1358 pointerIds.markBit(entry->pointerProperties[0].id);
1359 }
Jeff Brown9302c872011-07-13 22:51:29 -07001360 mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Jeff Brown98db5fa2011-06-08 15:37:10 -07001361 }
1362 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001363 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001364
Jeff Brown9302c872011-07-13 22:51:29 -07001365 if (newHoverWindowHandle != mLastHoverWindowHandle) {
Jeff Browna032cc02011-03-07 16:56:21 -08001366 // Let the previous window know that the hover sequence is over.
Jeff Brown9302c872011-07-13 22:51:29 -07001367 if (mLastHoverWindowHandle != NULL) {
Jeff Browna032cc02011-03-07 16:56:21 -08001368#if DEBUG_HOVER
Steve Block5baa3a62011-12-20 16:23:08 +00001369 ALOGD("Sending hover exit event to window %s.",
Jeff Browncc4f7db2011-08-30 20:34:48 -07001370 mLastHoverWindowHandle->getName().string());
Jeff Browna032cc02011-03-07 16:56:21 -08001371#endif
Jeff Brown9302c872011-07-13 22:51:29 -07001372 mTempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
Jeff Browna032cc02011-03-07 16:56:21 -08001373 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
1374 }
1375
1376 // Let the new window know that the hover sequence is starting.
Jeff Brown9302c872011-07-13 22:51:29 -07001377 if (newHoverWindowHandle != NULL) {
Jeff Browna032cc02011-03-07 16:56:21 -08001378#if DEBUG_HOVER
Steve Block5baa3a62011-12-20 16:23:08 +00001379 ALOGD("Sending hover enter event to window %s.",
Jeff Browncc4f7db2011-08-30 20:34:48 -07001380 newHoverWindowHandle->getName().string());
Jeff Browna032cc02011-03-07 16:56:21 -08001381#endif
Jeff Brown9302c872011-07-13 22:51:29 -07001382 mTempTouchState.addOrUpdateWindow(newHoverWindowHandle,
Jeff Browna032cc02011-03-07 16:56:21 -08001383 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER, BitSet32(0));
1384 }
1385 }
1386
Jeff Brown01ce2e92010-09-26 22:20:12 -07001387 // Check permission to inject into all touched foreground windows and ensure there
1388 // is at least one touched foreground window.
1389 {
1390 bool haveForegroundWindow = false;
1391 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1392 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1393 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1394 haveForegroundWindow = true;
Jeff Brown9302c872011-07-13 22:51:29 -07001395 if (! checkInjectionPermission(touchedWindow.windowHandle,
1396 entry->injectionState)) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001397 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1398 injectionPermission = INJECTION_PERMISSION_DENIED;
1399 goto Failed;
1400 }
1401 }
1402 }
1403 if (! haveForegroundWindow) {
Jeff Browna2cc28d2011-03-25 11:58:46 -07001404#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001405 ALOGD("Dropping event because there is no touched foreground window to receive it.");
Jeff Brownb88102f2010-09-08 11:49:43 -07001406#endif
1407 injectionResult = INPUT_EVENT_INJECTION_FAILED;
Jeff Brownb88102f2010-09-08 11:49:43 -07001408 goto Failed;
1409 }
1410
Jeff Brown01ce2e92010-09-26 22:20:12 -07001411 // Permission granted to injection into all touched foreground windows.
1412 injectionPermission = INJECTION_PERMISSION_GRANTED;
1413 }
Jeff Brown519e0242010-09-15 15:18:56 -07001414
Kenny Root7a9db182011-06-02 15:16:05 -07001415 // Check whether windows listening for outside touches are owned by the same UID. If it is
1416 // set the policy flag that we will not reveal coordinate information to this window.
1417 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
Jeff Brown9302c872011-07-13 22:51:29 -07001418 sp<InputWindowHandle> foregroundWindowHandle =
1419 mTempTouchState.getFirstForegroundWindowHandle();
Jeff Browncc4f7db2011-08-30 20:34:48 -07001420 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Kenny Root7a9db182011-06-02 15:16:05 -07001421 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1422 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1423 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
Jeff Brown9302c872011-07-13 22:51:29 -07001424 sp<InputWindowHandle> inputWindowHandle = touchedWindow.windowHandle;
Jeff Browncc4f7db2011-08-30 20:34:48 -07001425 if (inputWindowHandle->getInfo()->ownerUid != foregroundWindowUid) {
Jeff Brown9302c872011-07-13 22:51:29 -07001426 mTempTouchState.addOrUpdateWindow(inputWindowHandle,
Kenny Root7a9db182011-06-02 15:16:05 -07001427 InputTarget::FLAG_ZERO_COORDS, BitSet32(0));
1428 }
1429 }
1430 }
1431 }
1432
Jeff Brown01ce2e92010-09-26 22:20:12 -07001433 // Ensure all touched foreground windows are ready for new input.
1434 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1435 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1436 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1437 // If the touched window is paused then keep waiting.
Jeff Browncc4f7db2011-08-30 20:34:48 -07001438 if (touchedWindow.windowHandle->getInfo()->paused) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001439 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brown265f1cc2012-06-11 18:01:06 -07001440 NULL, touchedWindow.windowHandle, nextWakeupTime,
1441 "Waiting because the touched window is paused.");
Jeff Brown01ce2e92010-09-26 22:20:12 -07001442 goto Unresponsive;
1443 }
1444
1445 // If the touched window is still working on previous events then keep waiting.
Jeff Brown0952c302012-02-13 13:48:59 -08001446 if (!isWindowReadyForMoreInputLocked(currentTime, touchedWindow.windowHandle, entry)) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001447 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brown265f1cc2012-06-11 18:01:06 -07001448 NULL, touchedWindow.windowHandle, nextWakeupTime,
1449 "Waiting because the touched window has not finished "
1450 "processing the input events that were previously delivered to it.");
Jeff Brown01ce2e92010-09-26 22:20:12 -07001451 goto Unresponsive;
1452 }
1453 }
1454 }
1455
1456 // If this is the first pointer going down and the touched window has a wallpaper
1457 // then also add the touched wallpaper windows so they are locked in for the duration
1458 // of the touch gesture.
Jeff Brown33bbfd22011-02-24 20:55:35 -08001459 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
1460 // engine only supports touch events. We would need to add a mechanism similar
1461 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
1462 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
Jeff Brown9302c872011-07-13 22:51:29 -07001463 sp<InputWindowHandle> foregroundWindowHandle =
1464 mTempTouchState.getFirstForegroundWindowHandle();
Jeff Browncc4f7db2011-08-30 20:34:48 -07001465 if (foregroundWindowHandle->getInfo()->hasWallpaper) {
Jeff Brown9302c872011-07-13 22:51:29 -07001466 for (size_t i = 0; i < mWindowHandles.size(); i++) {
1467 sp<InputWindowHandle> windowHandle = mWindowHandles.itemAt(i);
Jeff Brown83d616a2012-09-09 20:33:43 -07001468 const InputWindowInfo* info = windowHandle->getInfo();
1469 if (info->displayId == displayId
1470 && windowHandle->getInfo()->layoutParamsType
1471 == InputWindowInfo::TYPE_WALLPAPER) {
Jeff Brown9302c872011-07-13 22:51:29 -07001472 mTempTouchState.addOrUpdateWindow(windowHandle,
Jeff Browna032cc02011-03-07 16:56:21 -08001473 InputTarget::FLAG_WINDOW_IS_OBSCURED
1474 | InputTarget::FLAG_DISPATCH_AS_IS,
1475 BitSet32(0));
Jeff Brown01ce2e92010-09-26 22:20:12 -07001476 }
1477 }
1478 }
1479 }
1480
Jeff Brownb88102f2010-09-08 11:49:43 -07001481 // Success! Output targets.
1482 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
Jeff Brownb88102f2010-09-08 11:49:43 -07001483
Jeff Brown01ce2e92010-09-26 22:20:12 -07001484 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1485 const TouchedWindow& touchedWindow = mTempTouchState.windows.itemAt(i);
Jeff Brown9302c872011-07-13 22:51:29 -07001486 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Jeff Browne9bb9be2012-02-06 15:47:55 -08001487 touchedWindow.pointerIds, inputTargets);
Jeff Brownb88102f2010-09-08 11:49:43 -07001488 }
1489
Jeff Browna032cc02011-03-07 16:56:21 -08001490 // Drop the outside or hover touch windows since we will not care about them
1491 // in the next iteration.
1492 mTempTouchState.filterNonAsIsTouchWindows();
Jeff Brown01ce2e92010-09-26 22:20:12 -07001493
Jeff Brownb88102f2010-09-08 11:49:43 -07001494Failed:
1495 // Check injection permission once and for all.
1496 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001497 if (checkInjectionPermission(NULL, entry->injectionState)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001498 injectionPermission = INJECTION_PERMISSION_GRANTED;
1499 } else {
1500 injectionPermission = INJECTION_PERMISSION_DENIED;
1501 }
1502 }
1503
1504 // Update final pieces of touch state if the injector had permission.
1505 if (injectionPermission == INJECTION_PERMISSION_GRANTED) {
Jeff Brown95712852011-01-04 19:41:59 -08001506 if (!wrongDevice) {
Jeff Brown81346812011-06-28 20:08:48 -07001507 if (switchedDevice) {
1508#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001509 ALOGD("Conflicting pointer actions: Switched to a different device.");
Jeff Brown81346812011-06-28 20:08:48 -07001510#endif
1511 *outConflictingPointerActions = true;
1512 }
1513
1514 if (isHoverAction) {
1515 // Started hovering, therefore no longer down.
1516 if (mTouchState.down) {
1517#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001518 ALOGD("Conflicting pointer actions: Hover received while pointer was down.");
Jeff Brown81346812011-06-28 20:08:48 -07001519#endif
1520 *outConflictingPointerActions = true;
1521 }
1522 mTouchState.reset();
1523 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER
1524 || maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
1525 mTouchState.deviceId = entry->deviceId;
1526 mTouchState.source = entry->source;
Jeff Brown83d616a2012-09-09 20:33:43 -07001527 mTouchState.displayId = displayId;
Jeff Brown81346812011-06-28 20:08:48 -07001528 }
1529 } else if (maskedAction == AMOTION_EVENT_ACTION_UP
1530 || maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Jeff Brown95712852011-01-04 19:41:59 -08001531 // All pointers up or canceled.
Jeff Brown33bbfd22011-02-24 20:55:35 -08001532 mTouchState.reset();
Jeff Brown95712852011-01-04 19:41:59 -08001533 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1534 // First pointer went down.
1535 if (mTouchState.down) {
Jeff Brownb6997262010-10-08 22:31:17 -07001536#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001537 ALOGD("Conflicting pointer actions: Down received while already down.");
Jeff Brownb6997262010-10-08 22:31:17 -07001538#endif
Jeff Brown81346812011-06-28 20:08:48 -07001539 *outConflictingPointerActions = true;
Jeff Brown95712852011-01-04 19:41:59 -08001540 }
Jeff Brown33bbfd22011-02-24 20:55:35 -08001541 mTouchState.copyFrom(mTempTouchState);
Jeff Brown95712852011-01-04 19:41:59 -08001542 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
1543 // One pointer went up.
1544 if (isSplit) {
1545 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07001546 uint32_t pointerId = entry->pointerProperties[pointerIndex].id;
Jeff Brownb88102f2010-09-08 11:49:43 -07001547
Jeff Brown95712852011-01-04 19:41:59 -08001548 for (size_t i = 0; i < mTempTouchState.windows.size(); ) {
1549 TouchedWindow& touchedWindow = mTempTouchState.windows.editItemAt(i);
1550 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
1551 touchedWindow.pointerIds.clearBit(pointerId);
1552 if (touchedWindow.pointerIds.isEmpty()) {
1553 mTempTouchState.windows.removeAt(i);
1554 continue;
1555 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001556 }
Jeff Brown95712852011-01-04 19:41:59 -08001557 i += 1;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001558 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001559 }
Jeff Brown33bbfd22011-02-24 20:55:35 -08001560 mTouchState.copyFrom(mTempTouchState);
1561 } else if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
1562 // Discard temporary touch state since it was only valid for this action.
1563 } else {
1564 // Save changes to touch state as-is for all other actions.
1565 mTouchState.copyFrom(mTempTouchState);
Jeff Brownb88102f2010-09-08 11:49:43 -07001566 }
Jeff Browna032cc02011-03-07 16:56:21 -08001567
1568 // Update hover state.
Jeff Brown9302c872011-07-13 22:51:29 -07001569 mLastHoverWindowHandle = newHoverWindowHandle;
Jeff Brown95712852011-01-04 19:41:59 -08001570 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001571 } else {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001572#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001573 ALOGD("Not updating touch focus because injection was denied.");
Jeff Brown01ce2e92010-09-26 22:20:12 -07001574#endif
Jeff Brownb88102f2010-09-08 11:49:43 -07001575 }
1576
1577Unresponsive:
Jeff Brown120a4592010-10-27 18:43:51 -07001578 // Reset temporary touch state to ensure we release unnecessary references to input channels.
1579 mTempTouchState.reset();
1580
Jeff Brown519e0242010-09-15 15:18:56 -07001581 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
1582 updateDispatchStatisticsLocked(currentTime, entry,
1583 injectionResult, timeSpentWaitingForApplication);
Jeff Brownb88102f2010-09-08 11:49:43 -07001584#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001585 ALOGD("findTouchedWindow finished: injectionResult=%d, injectionPermission=%d, "
Jeff Brown01ce2e92010-09-26 22:20:12 -07001586 "timeSpentWaitingForApplication=%0.1fms",
Jeff Brown519e0242010-09-15 15:18:56 -07001587 injectionResult, injectionPermission, timeSpentWaitingForApplication / 1000000.0);
Jeff Brownb88102f2010-09-08 11:49:43 -07001588#endif
1589 return injectionResult;
1590}
1591
Jeff Brown9302c872011-07-13 22:51:29 -07001592void InputDispatcher::addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
Jeff Browne9bb9be2012-02-06 15:47:55 -08001593 int32_t targetFlags, BitSet32 pointerIds, Vector<InputTarget>& inputTargets) {
1594 inputTargets.push();
Jeff Brownb88102f2010-09-08 11:49:43 -07001595
Jeff Browncc4f7db2011-08-30 20:34:48 -07001596 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Jeff Browne9bb9be2012-02-06 15:47:55 -08001597 InputTarget& target = inputTargets.editTop();
Jeff Browncc4f7db2011-08-30 20:34:48 -07001598 target.inputChannel = windowInfo->inputChannel;
Jeff Brownb88102f2010-09-08 11:49:43 -07001599 target.flags = targetFlags;
Jeff Browncc4f7db2011-08-30 20:34:48 -07001600 target.xOffset = - windowInfo->frameLeft;
1601 target.yOffset = - windowInfo->frameTop;
1602 target.scaleFactor = windowInfo->scaleFactor;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001603 target.pointerIds = pointerIds;
Jeff Brownb88102f2010-09-08 11:49:43 -07001604}
1605
Jeff Browne9bb9be2012-02-06 15:47:55 -08001606void InputDispatcher::addMonitoringTargetsLocked(Vector<InputTarget>& inputTargets) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001607 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
Jeff Browne9bb9be2012-02-06 15:47:55 -08001608 inputTargets.push();
Jeff Brownb88102f2010-09-08 11:49:43 -07001609
Jeff Browne9bb9be2012-02-06 15:47:55 -08001610 InputTarget& target = inputTargets.editTop();
Jeff Brownb88102f2010-09-08 11:49:43 -07001611 target.inputChannel = mMonitoringChannels[i];
Jeff Brownb6110c22011-04-01 16:15:13 -07001612 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
Jeff Brownb88102f2010-09-08 11:49:43 -07001613 target.xOffset = 0;
1614 target.yOffset = 0;
Jeff Brownb6110c22011-04-01 16:15:13 -07001615 target.pointerIds.clear();
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001616 target.scaleFactor = 1.0f;
Jeff Brownb88102f2010-09-08 11:49:43 -07001617 }
1618}
1619
Jeff Brown9302c872011-07-13 22:51:29 -07001620bool InputDispatcher::checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
Jeff Brown01ce2e92010-09-26 22:20:12 -07001621 const InjectionState* injectionState) {
1622 if (injectionState
Jeff Browncc4f7db2011-08-30 20:34:48 -07001623 && (windowHandle == NULL
1624 || windowHandle->getInfo()->ownerUid != injectionState->injectorUid)
Jeff Brownb6997262010-10-08 22:31:17 -07001625 && !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Jeff Brown9302c872011-07-13 22:51:29 -07001626 if (windowHandle != NULL) {
Steve Block8564c8d2012-01-05 23:22:43 +00001627 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
Jeff Brown9302c872011-07-13 22:51:29 -07001628 "owned by uid %d",
Jeff Brownb6997262010-10-08 22:31:17 -07001629 injectionState->injectorPid, injectionState->injectorUid,
Jeff Browncc4f7db2011-08-30 20:34:48 -07001630 windowHandle->getName().string(),
1631 windowHandle->getInfo()->ownerUid);
Jeff Brownb6997262010-10-08 22:31:17 -07001632 } else {
Steve Block8564c8d2012-01-05 23:22:43 +00001633 ALOGW("Permission denied: injecting event from pid %d uid %d",
Jeff Brownb6997262010-10-08 22:31:17 -07001634 injectionState->injectorPid, injectionState->injectorUid);
Jeff Brownb88102f2010-09-08 11:49:43 -07001635 }
Jeff Brownb6997262010-10-08 22:31:17 -07001636 return false;
Jeff Brownb88102f2010-09-08 11:49:43 -07001637 }
1638 return true;
1639}
1640
Jeff Brown19dfc832010-10-05 12:26:23 -07001641bool InputDispatcher::isWindowObscuredAtPointLocked(
Jeff Brown9302c872011-07-13 22:51:29 -07001642 const sp<InputWindowHandle>& windowHandle, int32_t x, int32_t y) const {
Jeff Brown83d616a2012-09-09 20:33:43 -07001643 int32_t displayId = windowHandle->getInfo()->displayId;
Jeff Brown9302c872011-07-13 22:51:29 -07001644 size_t numWindows = mWindowHandles.size();
Jeff Brownb88102f2010-09-08 11:49:43 -07001645 for (size_t i = 0; i < numWindows; i++) {
Jeff Brown9302c872011-07-13 22:51:29 -07001646 sp<InputWindowHandle> otherHandle = mWindowHandles.itemAt(i);
1647 if (otherHandle == windowHandle) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001648 break;
1649 }
Jeff Browncc4f7db2011-08-30 20:34:48 -07001650
1651 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Jeff Brown83d616a2012-09-09 20:33:43 -07001652 if (otherInfo->displayId == displayId
1653 && otherInfo->visible && !otherInfo->isTrustedOverlay()
Jeff Browncc4f7db2011-08-30 20:34:48 -07001654 && otherInfo->frameContainsPoint(x, y)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001655 return true;
1656 }
1657 }
1658 return false;
1659}
1660
Jeff Brownd1c48a02012-02-06 19:12:47 -08001661bool InputDispatcher::isWindowReadyForMoreInputLocked(nsecs_t currentTime,
Jeff Brown0952c302012-02-13 13:48:59 -08001662 const sp<InputWindowHandle>& windowHandle, const EventEntry* eventEntry) {
Jeff Browncc4f7db2011-08-30 20:34:48 -07001663 ssize_t connectionIndex = getConnectionIndexLocked(windowHandle->getInputChannel());
Jeff Brown519e0242010-09-15 15:18:56 -07001664 if (connectionIndex >= 0) {
Jeff Browncbee6d62012-02-03 20:11:27 -08001665 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
Jeff Brownd1c48a02012-02-06 19:12:47 -08001666 if (connection->inputPublisherBlocked) {
1667 return false;
1668 }
Jeff Brown0952c302012-02-13 13:48:59 -08001669 if (eventEntry->type == EventEntry::TYPE_KEY) {
1670 // If the event is a key event, then we must wait for all previous events to
1671 // complete before delivering it because previous events may have the
1672 // side-effect of transferring focus to a different window and we want to
1673 // ensure that the following keys are sent to the new window.
1674 //
1675 // Suppose the user touches a button in a window then immediately presses "A".
1676 // If the button causes a pop-up window to appear then we want to ensure that
1677 // the "A" key is delivered to the new pop-up window. This is because users
1678 // often anticipate pending UI changes when typing on a keyboard.
1679 // To obtain this behavior, we must serialize key events with respect to all
1680 // prior input events.
Jeff Brownd1c48a02012-02-06 19:12:47 -08001681 return connection->outboundQueue.isEmpty()
1682 && connection->waitQueue.isEmpty();
1683 }
Jeff Brown0952c302012-02-13 13:48:59 -08001684 // Touch events can always be sent to a window immediately because the user intended
1685 // to touch whatever was visible at the time. Even if focus changes or a new
1686 // window appears moments later, the touch event was meant to be delivered to
1687 // whatever window happened to be on screen at the time.
1688 //
1689 // Generic motion events, such as trackball or joystick events are a little trickier.
1690 // Like key events, generic motion events are delivered to the focused window.
1691 // Unlike key events, generic motion events don't tend to transfer focus to other
1692 // windows and it is not important for them to be serialized. So we prefer to deliver
1693 // generic motion events as soon as possible to improve efficiency and reduce lag
1694 // through batching.
1695 //
1696 // The one case where we pause input event delivery is when the wait queue is piling
1697 // up with lots of events because the application is not responding.
1698 // This condition ensures that ANRs are detected reliably.
Jeff Brownd1c48a02012-02-06 19:12:47 -08001699 if (!connection->waitQueue.isEmpty()
1700 && currentTime >= connection->waitQueue.head->eventEntry->eventTime
1701 + STREAM_AHEAD_EVENT_TIMEOUT) {
1702 return false;
1703 }
Jeff Brown519e0242010-09-15 15:18:56 -07001704 }
Jeff Brownd1c48a02012-02-06 19:12:47 -08001705 return true;
Jeff Brown519e0242010-09-15 15:18:56 -07001706}
1707
Jeff Brown9302c872011-07-13 22:51:29 -07001708String8 InputDispatcher::getApplicationWindowLabelLocked(
1709 const sp<InputApplicationHandle>& applicationHandle,
1710 const sp<InputWindowHandle>& windowHandle) {
1711 if (applicationHandle != NULL) {
1712 if (windowHandle != NULL) {
Jeff Browncc4f7db2011-08-30 20:34:48 -07001713 String8 label(applicationHandle->getName());
Jeff Brown519e0242010-09-15 15:18:56 -07001714 label.append(" - ");
Jeff Browncc4f7db2011-08-30 20:34:48 -07001715 label.append(windowHandle->getName());
Jeff Brown519e0242010-09-15 15:18:56 -07001716 return label;
1717 } else {
Jeff Browncc4f7db2011-08-30 20:34:48 -07001718 return applicationHandle->getName();
Jeff Brown519e0242010-09-15 15:18:56 -07001719 }
Jeff Brown9302c872011-07-13 22:51:29 -07001720 } else if (windowHandle != NULL) {
Jeff Browncc4f7db2011-08-30 20:34:48 -07001721 return windowHandle->getName();
Jeff Brown519e0242010-09-15 15:18:56 -07001722 } else {
1723 return String8("<unknown application or window>");
1724 }
1725}
1726
Jeff Browne2fe69e2010-10-18 13:21:23 -07001727void InputDispatcher::pokeUserActivityLocked(const EventEntry* eventEntry) {
Jeff Brown1e3b98d2012-09-30 18:58:59 -07001728 if (mFocusedWindowHandle != NULL) {
1729 const InputWindowInfo* info = mFocusedWindowHandle->getInfo();
1730 if (info->inputFeatures & InputWindowInfo::INPUT_FEATURE_DISABLE_USER_ACTIVITY) {
1731#if DEBUG_DISPATCH_CYCLE
1732 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.string());
1733#endif
1734 return;
1735 }
1736 }
1737
Jeff Brownb696de52012-07-27 15:38:50 -07001738 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Jeff Brown4d396052010-10-29 21:50:21 -07001739 switch (eventEntry->type) {
1740 case EventEntry::TYPE_MOTION: {
Jeff Browne2fe69e2010-10-18 13:21:23 -07001741 const MotionEntry* motionEntry = static_cast<const MotionEntry*>(eventEntry);
Jeff Brown4d396052010-10-29 21:50:21 -07001742 if (motionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
1743 return;
1744 }
1745
Jeff Brown56194eb2011-03-02 19:23:13 -08001746 if (MotionEvent::isTouchEvent(motionEntry->source, motionEntry->action)) {
Jeff Brownb696de52012-07-27 15:38:50 -07001747 eventType = USER_ACTIVITY_EVENT_TOUCH;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001748 }
Jeff Brown4d396052010-10-29 21:50:21 -07001749 break;
1750 }
1751 case EventEntry::TYPE_KEY: {
1752 const KeyEntry* keyEntry = static_cast<const KeyEntry*>(eventEntry);
1753 if (keyEntry->flags & AKEY_EVENT_FLAG_CANCELED) {
1754 return;
1755 }
Jeff Brownb696de52012-07-27 15:38:50 -07001756 eventType = USER_ACTIVITY_EVENT_BUTTON;
Jeff Brown4d396052010-10-29 21:50:21 -07001757 break;
1758 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001759 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001760
Jeff Brownb88102f2010-09-08 11:49:43 -07001761 CommandEntry* commandEntry = postCommandLocked(
1762 & InputDispatcher::doPokeUserActivityLockedInterruptible);
Jeff Browne2fe69e2010-10-18 13:21:23 -07001763 commandEntry->eventTime = eventEntry->eventTime;
Jeff Brownb88102f2010-09-08 11:49:43 -07001764 commandEntry->userActivityEventType = eventType;
1765}
1766
Jeff Brown7fbdc842010-06-17 20:52:56 -07001767void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001768 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001769#if DEBUG_DISPATCH_CYCLE
Steve Block5baa3a62011-12-20 16:23:08 +00001770 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
Jeff Brown9cc695c2011-08-23 18:35:04 -07001771 "xOffset=%f, yOffset=%f, scaleFactor=%f, "
Jeff Brown3241b6b2012-02-03 15:08:02 -08001772 "pointerIds=0x%x",
Jeff Brown519e0242010-09-15 15:18:56 -07001773 connection->getInputChannelName(), inputTarget->flags,
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001774 inputTarget->xOffset, inputTarget->yOffset,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001775 inputTarget->scaleFactor, inputTarget->pointerIds.value);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001776#endif
1777
1778 // Skip this event if the connection status is not normal.
Jeff Brown519e0242010-09-15 15:18:56 -07001779 // We don't want to enqueue additional outbound events if the connection is broken.
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001780 if (connection->status != Connection::STATUS_NORMAL) {
Jeff Brownb6997262010-10-08 22:31:17 -07001781#if DEBUG_DISPATCH_CYCLE
Steve Block5baa3a62011-12-20 16:23:08 +00001782 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Jeff Brownb88102f2010-09-08 11:49:43 -07001783 connection->getInputChannelName(), connection->getStatusLabel());
Jeff Brownb6997262010-10-08 22:31:17 -07001784#endif
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001785 return;
1786 }
1787
Jeff Brown01ce2e92010-09-26 22:20:12 -07001788 // Split a motion event if needed.
Jeff Brown3241b6b2012-02-03 15:08:02 -08001789 if (inputTarget->flags & InputTarget::FLAG_SPLIT) {
Steve Blockec193de2012-01-09 18:35:44 +00001790 ALOG_ASSERT(eventEntry->type == EventEntry::TYPE_MOTION);
Jeff Brown01ce2e92010-09-26 22:20:12 -07001791
1792 MotionEntry* originalMotionEntry = static_cast<MotionEntry*>(eventEntry);
1793 if (inputTarget->pointerIds.count() != originalMotionEntry->pointerCount) {
1794 MotionEntry* splitMotionEntry = splitMotionEvent(
1795 originalMotionEntry, inputTarget->pointerIds);
Jeff Brown58a2da82011-01-25 16:02:22 -08001796 if (!splitMotionEntry) {
1797 return; // split event was dropped
1798 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001799#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001800 ALOGD("channel '%s' ~ Split motion event.",
Jeff Brown01ce2e92010-09-26 22:20:12 -07001801 connection->getInputChannelName());
1802 logOutboundMotionDetailsLocked(" ", splitMotionEntry);
1803#endif
Jeff Brownc0cb3dc2012-01-12 18:30:12 -08001804 enqueueDispatchEntriesLocked(currentTime, connection,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001805 splitMotionEntry, inputTarget);
Jeff Brownc0cb3dc2012-01-12 18:30:12 -08001806 splitMotionEntry->release();
1807 return;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001808 }
1809 }
1810
Jeff Brownc0cb3dc2012-01-12 18:30:12 -08001811 // Not splitting. Enqueue dispatch entries for the event as is.
Jeff Brown3241b6b2012-02-03 15:08:02 -08001812 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
Jeff Brownc0cb3dc2012-01-12 18:30:12 -08001813}
1814
1815void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001816 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001817 bool wasEmpty = connection->outboundQueue.isEmpty();
1818
Jeff Browna032cc02011-03-07 16:56:21 -08001819 // Enqueue dispatch entries for the requested modes.
1820 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001821 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
Jeff Browna032cc02011-03-07 16:56:21 -08001822 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001823 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
Jeff Browna032cc02011-03-07 16:56:21 -08001824 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001825 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
Jeff Browna032cc02011-03-07 16:56:21 -08001826 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001827 InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brown98db5fa2011-06-08 15:37:10 -07001828 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001829 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
Jeff Brown98db5fa2011-06-08 15:37:10 -07001830 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001831 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Jeff Browna032cc02011-03-07 16:56:21 -08001832
1833 // If the outbound queue was previously empty, start the dispatch cycle going.
Jeff Brownb6110c22011-04-01 16:15:13 -07001834 if (wasEmpty && !connection->outboundQueue.isEmpty()) {
Jeff Browna032cc02011-03-07 16:56:21 -08001835 startDispatchCycleLocked(currentTime, connection);
1836 }
1837}
1838
1839void InputDispatcher::enqueueDispatchEntryLocked(
1840 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001841 int32_t dispatchMode) {
Jeff Browna032cc02011-03-07 16:56:21 -08001842 int32_t inputTargetFlags = inputTarget->flags;
1843 if (!(inputTargetFlags & dispatchMode)) {
1844 return;
1845 }
1846 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
1847
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001848 // This is a new event.
1849 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Jeff Brownac386072011-07-20 15:19:50 -07001850 DispatchEntry* dispatchEntry = new DispatchEntry(eventEntry, // increments ref
Dianne Hackbornaa9d84c2011-05-09 19:00:59 -07001851 inputTargetFlags, inputTarget->xOffset, inputTarget->yOffset,
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001852 inputTarget->scaleFactor);
Jeff Brown6ec402b2010-07-28 15:48:59 -07001853
Jeff Brown81346812011-06-28 20:08:48 -07001854 // Apply target flags and update the connection's input state.
1855 switch (eventEntry->type) {
1856 case EventEntry::TYPE_KEY: {
1857 KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
1858 dispatchEntry->resolvedAction = keyEntry->action;
1859 dispatchEntry->resolvedFlags = keyEntry->flags;
1860
1861 if (!connection->inputState.trackKey(keyEntry,
1862 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags)) {
1863#if DEBUG_DISPATCH_CYCLE
Steve Block5baa3a62011-12-20 16:23:08 +00001864 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key 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 case EventEntry::TYPE_MOTION: {
1874 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
1875 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
1876 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
1877 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
1878 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
1879 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
1880 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
1881 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
1882 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
1883 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
1884 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
1885 } else {
1886 dispatchEntry->resolvedAction = motionEntry->action;
1887 }
1888 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE
1889 && !connection->inputState.isHovering(
Jeff Brown83d616a2012-09-09 20:33:43 -07001890 motionEntry->deviceId, motionEntry->source, motionEntry->displayId)) {
Jeff Brown81346812011-06-28 20:08:48 -07001891#if DEBUG_DISPATCH_CYCLE
Steve Block5baa3a62011-12-20 16:23:08 +00001892 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter event",
Jeff Brown81346812011-06-28 20:08:48 -07001893 connection->getInputChannelName());
1894#endif
1895 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
1896 }
1897
1898 dispatchEntry->resolvedFlags = motionEntry->flags;
1899 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
1900 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
1901 }
1902
1903 if (!connection->inputState.trackMotion(motionEntry,
1904 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags)) {
1905#if DEBUG_DISPATCH_CYCLE
Steve Block5baa3a62011-12-20 16:23:08 +00001906 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion event",
Jeff Brown81346812011-06-28 20:08:48 -07001907 connection->getInputChannelName());
1908#endif
Jeff Brownc0cb3dc2012-01-12 18:30:12 -08001909 delete dispatchEntry;
Jeff Brown81346812011-06-28 20:08:48 -07001910 return; // skip the inconsistent event
1911 }
1912 break;
1913 }
1914 }
1915
Jeff Brownc0cb3dc2012-01-12 18:30:12 -08001916 // Remember that we are waiting for this dispatch to complete.
1917 if (dispatchEntry->hasForegroundTarget()) {
1918 incrementPendingForegroundDispatchesLocked(eventEntry);
1919 }
1920
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001921 // Enqueue the dispatch entry.
1922 connection->outboundQueue.enqueueAtTail(dispatchEntry);
Jeff Brown481c1572012-03-09 14:41:15 -08001923 traceOutboundQueueLengthLocked(connection);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001924}
1925
Jeff Brown7fbdc842010-06-17 20:52:56 -07001926void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Jeff Brown519e0242010-09-15 15:18:56 -07001927 const sp<Connection>& connection) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001928#if DEBUG_DISPATCH_CYCLE
Steve Block5baa3a62011-12-20 16:23:08 +00001929 ALOGD("channel '%s' ~ startDispatchCycle",
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001930 connection->getInputChannelName());
1931#endif
1932
Jeff Brownd1c48a02012-02-06 19:12:47 -08001933 while (connection->status == Connection::STATUS_NORMAL
1934 && !connection->outboundQueue.isEmpty()) {
1935 DispatchEntry* dispatchEntry = connection->outboundQueue.head;
Jeff Brown265f1cc2012-06-11 18:01:06 -07001936 dispatchEntry->deliveryTime = currentTime;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001937
Jeff Brownd1c48a02012-02-06 19:12:47 -08001938 // Publish the event.
1939 status_t status;
1940 EventEntry* eventEntry = dispatchEntry->eventEntry;
1941 switch (eventEntry->type) {
1942 case EventEntry::TYPE_KEY: {
1943 KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001944
Jeff Brownd1c48a02012-02-06 19:12:47 -08001945 // Publish the key event.
Jeff Brown072ec962012-02-07 14:46:57 -08001946 status = connection->inputPublisher.publishKeyEvent(dispatchEntry->seq,
Jeff Brownd1c48a02012-02-06 19:12:47 -08001947 keyEntry->deviceId, keyEntry->source,
1948 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags,
1949 keyEntry->keyCode, keyEntry->scanCode,
1950 keyEntry->metaState, keyEntry->repeatCount, keyEntry->downTime,
1951 keyEntry->eventTime);
1952 break;
1953 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001954
Jeff Brownd1c48a02012-02-06 19:12:47 -08001955 case EventEntry::TYPE_MOTION: {
1956 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001957
Jeff Brownd1c48a02012-02-06 19:12:47 -08001958 PointerCoords scaledCoords[MAX_POINTERS];
1959 const PointerCoords* usingCoords = motionEntry->pointerCoords;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001960
Jeff Brownd1c48a02012-02-06 19:12:47 -08001961 // Set the X and Y offset depending on the input source.
1962 float xOffset, yOffset, scaleFactor;
1963 if ((motionEntry->source & AINPUT_SOURCE_CLASS_POINTER)
1964 && !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
1965 scaleFactor = dispatchEntry->scaleFactor;
1966 xOffset = dispatchEntry->xOffset * scaleFactor;
1967 yOffset = dispatchEntry->yOffset * scaleFactor;
1968 if (scaleFactor != 1.0f) {
1969 for (size_t i = 0; i < motionEntry->pointerCount; i++) {
1970 scaledCoords[i] = motionEntry->pointerCoords[i];
1971 scaledCoords[i].scale(scaleFactor);
1972 }
1973 usingCoords = scaledCoords;
1974 }
1975 } else {
1976 xOffset = 0.0f;
1977 yOffset = 0.0f;
1978 scaleFactor = 1.0f;
1979
1980 // We don't want the dispatch target to know.
1981 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
1982 for (size_t i = 0; i < motionEntry->pointerCount; i++) {
1983 scaledCoords[i].clear();
1984 }
1985 usingCoords = scaledCoords;
1986 }
1987 }
1988
1989 // Publish the motion event.
Jeff Brown072ec962012-02-07 14:46:57 -08001990 status = connection->inputPublisher.publishMotionEvent(dispatchEntry->seq,
Jeff Brownd1c48a02012-02-06 19:12:47 -08001991 motionEntry->deviceId, motionEntry->source,
1992 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags,
1993 motionEntry->edgeFlags, motionEntry->metaState, motionEntry->buttonState,
1994 xOffset, yOffset,
1995 motionEntry->xPrecision, motionEntry->yPrecision,
1996 motionEntry->downTime, motionEntry->eventTime,
1997 motionEntry->pointerCount, motionEntry->pointerProperties,
1998 usingCoords);
1999 break;
2000 }
2001
2002 default:
2003 ALOG_ASSERT(false);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002004 return;
2005 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002006
Jeff Brownd1c48a02012-02-06 19:12:47 -08002007 // Check the result.
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002008 if (status) {
Jeff Brownd1c48a02012-02-06 19:12:47 -08002009 if (status == WOULD_BLOCK) {
2010 if (connection->waitQueue.isEmpty()) {
2011 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
2012 "This is unexpected because the wait queue is empty, so the pipe "
2013 "should be empty and we shouldn't have any problems writing an "
2014 "event to it, status=%d", connection->getInputChannelName(), status);
2015 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2016 } else {
2017 // Pipe is full and we are waiting for the app to finish process some events
2018 // before sending more events to it.
2019#if DEBUG_DISPATCH_CYCLE
2020 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
2021 "waiting for the application to catch up",
2022 connection->getInputChannelName());
2023#endif
2024 connection->inputPublisherBlocked = true;
2025 }
2026 } else {
2027 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
2028 "status=%d", connection->getInputChannelName(), status);
2029 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2030 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002031 return;
2032 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002033
Jeff Brownd1c48a02012-02-06 19:12:47 -08002034 // Re-enqueue the event on the wait queue.
2035 connection->outboundQueue.dequeue(dispatchEntry);
Jeff Brown481c1572012-03-09 14:41:15 -08002036 traceOutboundQueueLengthLocked(connection);
Jeff Brownd1c48a02012-02-06 19:12:47 -08002037 connection->waitQueue.enqueueAtTail(dispatchEntry);
Jeff Brown481c1572012-03-09 14:41:15 -08002038 traceWaitQueueLengthLocked(connection);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002039 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002040}
2041
Jeff Brown7fbdc842010-06-17 20:52:56 -07002042void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Jeff Brown072ec962012-02-07 14:46:57 -08002043 const sp<Connection>& connection, uint32_t seq, bool handled) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002044#if DEBUG_DISPATCH_CYCLE
Jeff Brown072ec962012-02-07 14:46:57 -08002045 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
2046 connection->getInputChannelName(), seq, toString(handled));
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002047#endif
2048
Jeff Brownd1c48a02012-02-06 19:12:47 -08002049 connection->inputPublisherBlocked = false;
2050
Jeff Brown9c3cda02010-06-15 01:31:58 -07002051 if (connection->status == Connection::STATUS_BROKEN
2052 || connection->status == Connection::STATUS_ZOMBIE) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002053 return;
2054 }
2055
Jeff Brown3915bb82010-11-05 15:02:16 -07002056 // Notify other system components and prepare to start the next dispatch cycle.
Jeff Brown072ec962012-02-07 14:46:57 -08002057 onDispatchCycleFinishedLocked(currentTime, connection, seq, handled);
Jeff Brownb88102f2010-09-08 11:49:43 -07002058}
2059
Jeff Brownb6997262010-10-08 22:31:17 -07002060void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Jeff Browncc4f7db2011-08-30 20:34:48 -07002061 const sp<Connection>& connection, bool notify) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002062#if DEBUG_DISPATCH_CYCLE
Steve Block5baa3a62011-12-20 16:23:08 +00002063 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
Jeff Browncc4f7db2011-08-30 20:34:48 -07002064 connection->getInputChannelName(), toString(notify));
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002065#endif
2066
Jeff Brownd1c48a02012-02-06 19:12:47 -08002067 // Clear the dispatch queues.
2068 drainDispatchQueueLocked(&connection->outboundQueue);
Jeff Brown481c1572012-03-09 14:41:15 -08002069 traceOutboundQueueLengthLocked(connection);
Jeff Brownd1c48a02012-02-06 19:12:47 -08002070 drainDispatchQueueLocked(&connection->waitQueue);
Jeff Brown481c1572012-03-09 14:41:15 -08002071 traceWaitQueueLengthLocked(connection);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002072
Jeff Brownb6997262010-10-08 22:31:17 -07002073 // The connection appears to be unrecoverably broken.
Jeff Brown9c3cda02010-06-15 01:31:58 -07002074 // Ignore already broken or zombie connections.
Jeff Brownb6997262010-10-08 22:31:17 -07002075 if (connection->status == Connection::STATUS_NORMAL) {
2076 connection->status = Connection::STATUS_BROKEN;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002077
Jeff Browncc4f7db2011-08-30 20:34:48 -07002078 if (notify) {
2079 // Notify other system components.
2080 onDispatchCycleBrokenLocked(currentTime, connection);
2081 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002082 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002083}
2084
Jeff Brownd1c48a02012-02-06 19:12:47 -08002085void InputDispatcher::drainDispatchQueueLocked(Queue<DispatchEntry>* queue) {
2086 while (!queue->isEmpty()) {
2087 DispatchEntry* dispatchEntry = queue->dequeueAtHead();
2088 releaseDispatchEntryLocked(dispatchEntry);
Jeff Brownb88102f2010-09-08 11:49:43 -07002089 }
Jeff Brownb88102f2010-09-08 11:49:43 -07002090}
2091
Jeff Brownd1c48a02012-02-06 19:12:47 -08002092void InputDispatcher::releaseDispatchEntryLocked(DispatchEntry* dispatchEntry) {
2093 if (dispatchEntry->hasForegroundTarget()) {
2094 decrementPendingForegroundDispatchesLocked(dispatchEntry->eventEntry);
2095 }
2096 delete dispatchEntry;
2097}
2098
Jeff Browncbee6d62012-02-03 20:11:27 -08002099int InputDispatcher::handleReceiveCallback(int fd, int events, void* data) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002100 InputDispatcher* d = static_cast<InputDispatcher*>(data);
2101
2102 { // acquire lock
2103 AutoMutex _l(d->mLock);
2104
Jeff Browncbee6d62012-02-03 20:11:27 -08002105 ssize_t connectionIndex = d->mConnectionsByFd.indexOfKey(fd);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002106 if (connectionIndex < 0) {
Steve Block3762c312012-01-06 19:20:56 +00002107 ALOGE("Received spurious receive callback for unknown input channel. "
Jeff Browncbee6d62012-02-03 20:11:27 -08002108 "fd=%d, events=0x%x", fd, events);
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002109 return 0; // remove the callback
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002110 }
2111
Jeff Browncc4f7db2011-08-30 20:34:48 -07002112 bool notify;
Jeff Browncbee6d62012-02-03 20:11:27 -08002113 sp<Connection> connection = d->mConnectionsByFd.valueAt(connectionIndex);
Jeff Browncc4f7db2011-08-30 20:34:48 -07002114 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
2115 if (!(events & ALOOPER_EVENT_INPUT)) {
Steve Block8564c8d2012-01-05 23:22:43 +00002116 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
Jeff Browncc4f7db2011-08-30 20:34:48 -07002117 "events=0x%x", connection->getInputChannelName(), events);
2118 return 1;
2119 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002120
Jeff Brown1adee112012-02-07 10:25:41 -08002121 nsecs_t currentTime = now();
2122 bool gotOne = false;
2123 status_t status;
2124 for (;;) {
Jeff Brown072ec962012-02-07 14:46:57 -08002125 uint32_t seq;
2126 bool handled;
2127 status = connection->inputPublisher.receiveFinishedSignal(&seq, &handled);
Jeff Brown1adee112012-02-07 10:25:41 -08002128 if (status) {
2129 break;
2130 }
Jeff Brown072ec962012-02-07 14:46:57 -08002131 d->finishDispatchCycleLocked(currentTime, connection, seq, handled);
Jeff Brown1adee112012-02-07 10:25:41 -08002132 gotOne = true;
2133 }
2134 if (gotOne) {
Jeff Browncc4f7db2011-08-30 20:34:48 -07002135 d->runCommandsLockedInterruptible();
Jeff Brown1adee112012-02-07 10:25:41 -08002136 if (status == WOULD_BLOCK) {
2137 return 1;
2138 }
Jeff Browncc4f7db2011-08-30 20:34:48 -07002139 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002140
Jeff Brown1adee112012-02-07 10:25:41 -08002141 notify = status != DEAD_OBJECT || !connection->monitor;
2142 if (notify) {
2143 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
2144 connection->getInputChannelName(), status);
2145 }
Jeff Browncc4f7db2011-08-30 20:34:48 -07002146 } else {
2147 // Monitor channels are never explicitly unregistered.
2148 // We do it automatically when the remote endpoint is closed so don't warn
2149 // about them.
2150 notify = !connection->monitor;
2151 if (notify) {
Steve Block8564c8d2012-01-05 23:22:43 +00002152 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. "
Jeff Browncc4f7db2011-08-30 20:34:48 -07002153 "events=0x%x", connection->getInputChannelName(), events);
2154 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002155 }
2156
Jeff Browncc4f7db2011-08-30 20:34:48 -07002157 // Unregister the channel.
2158 d->unregisterInputChannelLocked(connection->inputChannel, notify);
2159 return 0; // remove the callback
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002160 } // release lock
2161}
2162
Jeff Brownb6997262010-10-08 22:31:17 -07002163void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Jeff Brownda3d5a92011-03-29 15:11:34 -07002164 const CancelationOptions& options) {
Jeff Browncbee6d62012-02-03 20:11:27 -08002165 for (size_t i = 0; i < mConnectionsByFd.size(); i++) {
Jeff Brownb6997262010-10-08 22:31:17 -07002166 synthesizeCancelationEventsForConnectionLocked(
Jeff Browncbee6d62012-02-03 20:11:27 -08002167 mConnectionsByFd.valueAt(i), options);
Jeff Brownb6997262010-10-08 22:31:17 -07002168 }
2169}
2170
2171void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Jeff Brownda3d5a92011-03-29 15:11:34 -07002172 const sp<InputChannel>& channel, const CancelationOptions& options) {
Jeff Brownb6997262010-10-08 22:31:17 -07002173 ssize_t index = getConnectionIndexLocked(channel);
2174 if (index >= 0) {
2175 synthesizeCancelationEventsForConnectionLocked(
Jeff Browncbee6d62012-02-03 20:11:27 -08002176 mConnectionsByFd.valueAt(index), options);
Jeff Brownb6997262010-10-08 22:31:17 -07002177 }
2178}
2179
2180void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
Jeff Brownda3d5a92011-03-29 15:11:34 -07002181 const sp<Connection>& connection, const CancelationOptions& options) {
Jeff Brownc0cb3dc2012-01-12 18:30:12 -08002182 if (connection->status == Connection::STATUS_BROKEN) {
2183 return;
2184 }
2185
Jeff Brownb6997262010-10-08 22:31:17 -07002186 nsecs_t currentTime = now();
2187
Jeff Brown8b4be5602012-02-06 16:31:05 -08002188 Vector<EventEntry*> cancelationEvents;
Jeff Brownac386072011-07-20 15:19:50 -07002189 connection->inputState.synthesizeCancelationEvents(currentTime,
Jeff Brown8b4be5602012-02-06 16:31:05 -08002190 cancelationEvents, options);
Jeff Brownb6997262010-10-08 22:31:17 -07002191
Jeff Brown8b4be5602012-02-06 16:31:05 -08002192 if (!cancelationEvents.isEmpty()) {
Jeff Brownb6997262010-10-08 22:31:17 -07002193#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00002194 ALOGD("channel '%s' ~ Synthesized %d cancelation events to bring channel back in sync "
Jeff Brownda3d5a92011-03-29 15:11:34 -07002195 "with reality: %s, mode=%d.",
Jeff Brown8b4be5602012-02-06 16:31:05 -08002196 connection->getInputChannelName(), cancelationEvents.size(),
Jeff Brownda3d5a92011-03-29 15:11:34 -07002197 options.reason, options.mode);
Jeff Brownb6997262010-10-08 22:31:17 -07002198#endif
Jeff Brown8b4be5602012-02-06 16:31:05 -08002199 for (size_t i = 0; i < cancelationEvents.size(); i++) {
2200 EventEntry* cancelationEventEntry = cancelationEvents.itemAt(i);
Jeff Brownb6997262010-10-08 22:31:17 -07002201 switch (cancelationEventEntry->type) {
2202 case EventEntry::TYPE_KEY:
2203 logOutboundKeyDetailsLocked("cancel - ",
2204 static_cast<KeyEntry*>(cancelationEventEntry));
2205 break;
2206 case EventEntry::TYPE_MOTION:
2207 logOutboundMotionDetailsLocked("cancel - ",
2208 static_cast<MotionEntry*>(cancelationEventEntry));
2209 break;
2210 }
2211
Jeff Brown81346812011-06-28 20:08:48 -07002212 InputTarget target;
Jeff Brown9302c872011-07-13 22:51:29 -07002213 sp<InputWindowHandle> windowHandle = getWindowHandleLocked(connection->inputChannel);
2214 if (windowHandle != NULL) {
Jeff Browncc4f7db2011-08-30 20:34:48 -07002215 const InputWindowInfo* windowInfo = windowHandle->getInfo();
2216 target.xOffset = -windowInfo->frameLeft;
2217 target.yOffset = -windowInfo->frameTop;
2218 target.scaleFactor = windowInfo->scaleFactor;
Jeff Brownb6997262010-10-08 22:31:17 -07002219 } else {
Jeff Brown81346812011-06-28 20:08:48 -07002220 target.xOffset = 0;
2221 target.yOffset = 0;
2222 target.scaleFactor = 1.0f;
Jeff Brownb6997262010-10-08 22:31:17 -07002223 }
Jeff Brown81346812011-06-28 20:08:48 -07002224 target.inputChannel = connection->inputChannel;
2225 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
Jeff Brownb6997262010-10-08 22:31:17 -07002226
Jeff Brown81346812011-06-28 20:08:48 -07002227 enqueueDispatchEntryLocked(connection, cancelationEventEntry, // increments ref
Jeff Brown3241b6b2012-02-03 15:08:02 -08002228 &target, InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brownb6997262010-10-08 22:31:17 -07002229
Jeff Brownac386072011-07-20 15:19:50 -07002230 cancelationEventEntry->release();
Jeff Brownb6997262010-10-08 22:31:17 -07002231 }
2232
Jeff Brownd1c48a02012-02-06 19:12:47 -08002233 startDispatchCycleLocked(currentTime, connection);
Jeff Brownb6997262010-10-08 22:31:17 -07002234 }
2235}
2236
Jeff Brown01ce2e92010-09-26 22:20:12 -07002237InputDispatcher::MotionEntry*
2238InputDispatcher::splitMotionEvent(const MotionEntry* originalMotionEntry, BitSet32 pointerIds) {
Steve Blockec193de2012-01-09 18:35:44 +00002239 ALOG_ASSERT(pointerIds.value != 0);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002240
2241 uint32_t splitPointerIndexMap[MAX_POINTERS];
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002242 PointerProperties splitPointerProperties[MAX_POINTERS];
Jeff Brown01ce2e92010-09-26 22:20:12 -07002243 PointerCoords splitPointerCoords[MAX_POINTERS];
2244
2245 uint32_t originalPointerCount = originalMotionEntry->pointerCount;
2246 uint32_t splitPointerCount = 0;
2247
2248 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
2249 originalPointerIndex++) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002250 const PointerProperties& pointerProperties =
2251 originalMotionEntry->pointerProperties[originalPointerIndex];
2252 uint32_t pointerId = uint32_t(pointerProperties.id);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002253 if (pointerIds.hasBit(pointerId)) {
2254 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002255 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
Jeff Brownace13b12011-03-09 17:39:48 -08002256 splitPointerCoords[splitPointerCount].copyFrom(
Jeff Brown3241b6b2012-02-03 15:08:02 -08002257 originalMotionEntry->pointerCoords[originalPointerIndex]);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002258 splitPointerCount += 1;
2259 }
2260 }
Jeff Brown58a2da82011-01-25 16:02:22 -08002261
2262 if (splitPointerCount != pointerIds.count()) {
2263 // This is bad. We are missing some of the pointers that we expected to deliver.
2264 // Most likely this indicates that we received an ACTION_MOVE events that has
2265 // different pointer ids than we expected based on the previous ACTION_DOWN
2266 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
2267 // in this way.
Steve Block8564c8d2012-01-05 23:22:43 +00002268 ALOGW("Dropping split motion event because the pointer count is %d but "
Jeff Brown58a2da82011-01-25 16:02:22 -08002269 "we expected there to be %d pointers. This probably means we received "
2270 "a broken sequence of pointer ids from the input device.",
2271 splitPointerCount, pointerIds.count());
2272 return NULL;
2273 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07002274
2275 int32_t action = originalMotionEntry->action;
2276 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
2277 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
2278 || maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2279 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002280 const PointerProperties& pointerProperties =
2281 originalMotionEntry->pointerProperties[originalPointerIndex];
2282 uint32_t pointerId = uint32_t(pointerProperties.id);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002283 if (pointerIds.hasBit(pointerId)) {
2284 if (pointerIds.count() == 1) {
2285 // The first/last pointer went down/up.
2286 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
2287 ? AMOTION_EVENT_ACTION_DOWN : AMOTION_EVENT_ACTION_UP;
Jeff Brown9a01d052010-09-27 16:35:11 -07002288 } else {
2289 // A secondary pointer went down/up.
2290 uint32_t splitPointerIndex = 0;
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002291 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
Jeff Brown9a01d052010-09-27 16:35:11 -07002292 splitPointerIndex += 1;
2293 }
2294 action = maskedAction | (splitPointerIndex
2295 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002296 }
2297 } else {
2298 // An unrelated pointer changed.
2299 action = AMOTION_EVENT_ACTION_MOVE;
2300 }
2301 }
2302
Jeff Brownac386072011-07-20 15:19:50 -07002303 MotionEntry* splitMotionEntry = new MotionEntry(
Jeff Brown01ce2e92010-09-26 22:20:12 -07002304 originalMotionEntry->eventTime,
2305 originalMotionEntry->deviceId,
2306 originalMotionEntry->source,
2307 originalMotionEntry->policyFlags,
2308 action,
2309 originalMotionEntry->flags,
2310 originalMotionEntry->metaState,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002311 originalMotionEntry->buttonState,
Jeff Brown01ce2e92010-09-26 22:20:12 -07002312 originalMotionEntry->edgeFlags,
2313 originalMotionEntry->xPrecision,
2314 originalMotionEntry->yPrecision,
2315 originalMotionEntry->downTime,
Jeff Brown83d616a2012-09-09 20:33:43 -07002316 originalMotionEntry->displayId,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002317 splitPointerCount, splitPointerProperties, splitPointerCoords);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002318
Jeff Browna032cc02011-03-07 16:56:21 -08002319 if (originalMotionEntry->injectionState) {
2320 splitMotionEntry->injectionState = originalMotionEntry->injectionState;
2321 splitMotionEntry->injectionState->refCount += 1;
2322 }
2323
Jeff Brown01ce2e92010-09-26 22:20:12 -07002324 return splitMotionEntry;
2325}
2326
Jeff Brownbe1aa822011-07-27 16:04:54 -07002327void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002328#if DEBUG_INBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00002329 ALOGD("notifyConfigurationChanged - eventTime=%lld", args->eventTime);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002330#endif
2331
Jeff Brownb88102f2010-09-08 11:49:43 -07002332 bool needWake;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002333 { // acquire lock
2334 AutoMutex _l(mLock);
2335
Jeff Brownbe1aa822011-07-27 16:04:54 -07002336 ConfigurationChangedEntry* newEntry = new ConfigurationChangedEntry(args->eventTime);
Jeff Brownb88102f2010-09-08 11:49:43 -07002337 needWake = enqueueInboundEventLocked(newEntry);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002338 } // release lock
2339
Jeff Brownb88102f2010-09-08 11:49:43 -07002340 if (needWake) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002341 mLooper->wake();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002342 }
2343}
2344
Jeff Brownbe1aa822011-07-27 16:04:54 -07002345void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002346#if DEBUG_INBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00002347 ALOGD("notifyKey - eventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, action=0x%x, "
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002348 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%lld",
Jeff Brownbe1aa822011-07-27 16:04:54 -07002349 args->eventTime, args->deviceId, args->source, args->policyFlags,
2350 args->action, args->flags, args->keyCode, args->scanCode,
2351 args->metaState, args->downTime);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002352#endif
Jeff Brownbe1aa822011-07-27 16:04:54 -07002353 if (!validateKeyEvent(args->action)) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002354 return;
2355 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002356
Jeff Brownbe1aa822011-07-27 16:04:54 -07002357 uint32_t policyFlags = args->policyFlags;
2358 int32_t flags = args->flags;
2359 int32_t metaState = args->metaState;
Jeff Brown1f245102010-11-18 20:53:46 -08002360 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
2361 policyFlags |= POLICY_FLAG_VIRTUAL;
2362 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
2363 }
Jeff Brown924c4d42011-03-07 16:40:47 -08002364 if (policyFlags & POLICY_FLAG_ALT) {
2365 metaState |= AMETA_ALT_ON | AMETA_ALT_LEFT_ON;
2366 }
2367 if (policyFlags & POLICY_FLAG_ALT_GR) {
2368 metaState |= AMETA_ALT_ON | AMETA_ALT_RIGHT_ON;
2369 }
2370 if (policyFlags & POLICY_FLAG_SHIFT) {
2371 metaState |= AMETA_SHIFT_ON | AMETA_SHIFT_LEFT_ON;
2372 }
2373 if (policyFlags & POLICY_FLAG_CAPS_LOCK) {
2374 metaState |= AMETA_CAPS_LOCK_ON;
2375 }
2376 if (policyFlags & POLICY_FLAG_FUNCTION) {
2377 metaState |= AMETA_FUNCTION_ON;
2378 }
Jeff Brown1f245102010-11-18 20:53:46 -08002379
Jeff Browne20c9e02010-10-11 14:20:19 -07002380 policyFlags |= POLICY_FLAG_TRUSTED;
Jeff Brown1f245102010-11-18 20:53:46 -08002381
2382 KeyEvent event;
Jeff Brownbe1aa822011-07-27 16:04:54 -07002383 event.initialize(args->deviceId, args->source, args->action,
2384 flags, args->keyCode, args->scanCode, metaState, 0,
2385 args->downTime, args->eventTime);
Jeff Brown1f245102010-11-18 20:53:46 -08002386
2387 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
2388
2389 if (policyFlags & POLICY_FLAG_WOKE_HERE) {
2390 flags |= AKEY_EVENT_FLAG_WOKE_HERE;
2391 }
Jeff Brownb6997262010-10-08 22:31:17 -07002392
Jeff Brownb88102f2010-09-08 11:49:43 -07002393 bool needWake;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002394 { // acquire lock
Jeff Brown0029c662011-03-30 02:25:18 -07002395 mLock.lock();
2396
Jeff Brown83d616a2012-09-09 20:33:43 -07002397 if (shouldSendKeyToInputFilterLocked(args)) {
Jeff Brown0029c662011-03-30 02:25:18 -07002398 mLock.unlock();
2399
2400 policyFlags |= POLICY_FLAG_FILTERED;
2401 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2402 return; // event was consumed by the filter
2403 }
2404
2405 mLock.lock();
2406 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002407
Jeff Brown7fbdc842010-06-17 20:52:56 -07002408 int32_t repeatCount = 0;
Jeff Brownbe1aa822011-07-27 16:04:54 -07002409 KeyEntry* newEntry = new KeyEntry(args->eventTime,
2410 args->deviceId, args->source, policyFlags,
2411 args->action, flags, args->keyCode, args->scanCode,
2412 metaState, repeatCount, args->downTime);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002413
Jeff Brownb88102f2010-09-08 11:49:43 -07002414 needWake = enqueueInboundEventLocked(newEntry);
Jeff Brown0029c662011-03-30 02:25:18 -07002415 mLock.unlock();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002416 } // release lock
2417
Jeff Brownb88102f2010-09-08 11:49:43 -07002418 if (needWake) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002419 mLooper->wake();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002420 }
2421}
2422
Jeff Brown83d616a2012-09-09 20:33:43 -07002423bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
2424 return mInputFilterEnabled;
2425}
2426
Jeff Brownbe1aa822011-07-27 16:04:54 -07002427void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002428#if DEBUG_INBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00002429 ALOGD("notifyMotion - eventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, "
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002430 "action=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, edgeFlags=0x%x, "
Jeff Brown85a31762010-09-01 17:01:00 -07002431 "xPrecision=%f, yPrecision=%f, downTime=%lld",
Jeff Brownbe1aa822011-07-27 16:04:54 -07002432 args->eventTime, args->deviceId, args->source, args->policyFlags,
2433 args->action, args->flags, args->metaState, args->buttonState,
2434 args->edgeFlags, args->xPrecision, args->yPrecision, args->downTime);
2435 for (uint32_t i = 0; i < args->pointerCount; i++) {
Steve Block5baa3a62011-12-20 16:23:08 +00002436 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002437 "x=%f, y=%f, pressure=%f, size=%f, "
Jeff Brown85a31762010-09-01 17:01:00 -07002438 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
Jeff Brown8d608662010-08-30 03:02:23 -07002439 "orientation=%f",
Jeff Brownbe1aa822011-07-27 16:04:54 -07002440 i, args->pointerProperties[i].id,
2441 args->pointerProperties[i].toolType,
2442 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
2443 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
2444 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
2445 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
2446 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
2447 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
2448 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
2449 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
2450 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002451 }
2452#endif
Jeff Brownbe1aa822011-07-27 16:04:54 -07002453 if (!validateMotionEvent(args->action, args->pointerCount, args->pointerProperties)) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002454 return;
2455 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002456
Jeff Brownbe1aa822011-07-27 16:04:54 -07002457 uint32_t policyFlags = args->policyFlags;
Jeff Browne20c9e02010-10-11 14:20:19 -07002458 policyFlags |= POLICY_FLAG_TRUSTED;
Jeff Brownbe1aa822011-07-27 16:04:54 -07002459 mPolicy->interceptMotionBeforeQueueing(args->eventTime, /*byref*/ policyFlags);
Jeff Brownb6997262010-10-08 22:31:17 -07002460
Jeff Brownb88102f2010-09-08 11:49:43 -07002461 bool needWake;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002462 { // acquire lock
Jeff Brown0029c662011-03-30 02:25:18 -07002463 mLock.lock();
2464
Jeff Brown83d616a2012-09-09 20:33:43 -07002465 if (shouldSendMotionToInputFilterLocked(args)) {
Jeff Brown0029c662011-03-30 02:25:18 -07002466 mLock.unlock();
2467
2468 MotionEvent event;
Jeff Brownbe1aa822011-07-27 16:04:54 -07002469 event.initialize(args->deviceId, args->source, args->action, args->flags,
2470 args->edgeFlags, args->metaState, args->buttonState, 0, 0,
2471 args->xPrecision, args->yPrecision,
2472 args->downTime, args->eventTime,
2473 args->pointerCount, args->pointerProperties, args->pointerCoords);
Jeff Brown0029c662011-03-30 02:25:18 -07002474
2475 policyFlags |= POLICY_FLAG_FILTERED;
2476 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2477 return; // event was consumed by the filter
2478 }
2479
2480 mLock.lock();
2481 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002482
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002483 // Just enqueue a new motion event.
Jeff Brownbe1aa822011-07-27 16:04:54 -07002484 MotionEntry* newEntry = new MotionEntry(args->eventTime,
2485 args->deviceId, args->source, policyFlags,
2486 args->action, args->flags, args->metaState, args->buttonState,
2487 args->edgeFlags, args->xPrecision, args->yPrecision, args->downTime,
Jeff Brown83d616a2012-09-09 20:33:43 -07002488 args->displayId,
Jeff Brownbe1aa822011-07-27 16:04:54 -07002489 args->pointerCount, args->pointerProperties, args->pointerCoords);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002490
Jeff Brownb88102f2010-09-08 11:49:43 -07002491 needWake = enqueueInboundEventLocked(newEntry);
Jeff Brown0029c662011-03-30 02:25:18 -07002492 mLock.unlock();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002493 } // release lock
2494
Jeff Brownb88102f2010-09-08 11:49:43 -07002495 if (needWake) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002496 mLooper->wake();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002497 }
2498}
2499
Jeff Brown83d616a2012-09-09 20:33:43 -07002500bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
2501 // TODO: support sending secondary display events to input filter
2502 return mInputFilterEnabled && isMainDisplay(args->displayId);
2503}
2504
Jeff Brownbe1aa822011-07-27 16:04:54 -07002505void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
Jeff Brownb6997262010-10-08 22:31:17 -07002506#if DEBUG_INBOUND_EVENT_DETAILS
Jeff Brownbcc046a2012-09-27 20:46:43 -07002507 ALOGD("notifySwitch - eventTime=%lld, policyFlags=0x%x, switchValues=0x%08x, switchMask=0x%08x",
Jeff Brownbe1aa822011-07-27 16:04:54 -07002508 args->eventTime, args->policyFlags,
Jeff Brownbcc046a2012-09-27 20:46:43 -07002509 args->switchValues, args->switchMask);
Jeff Brownb6997262010-10-08 22:31:17 -07002510#endif
2511
Jeff Brownbe1aa822011-07-27 16:04:54 -07002512 uint32_t policyFlags = args->policyFlags;
Jeff Browne20c9e02010-10-11 14:20:19 -07002513 policyFlags |= POLICY_FLAG_TRUSTED;
Jeff Brownbe1aa822011-07-27 16:04:54 -07002514 mPolicy->notifySwitch(args->eventTime,
Jeff Brownbcc046a2012-09-27 20:46:43 -07002515 args->switchValues, args->switchMask, policyFlags);
Jeff Brownb6997262010-10-08 22:31:17 -07002516}
2517
Jeff Brown65fd2512011-08-18 11:20:58 -07002518void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
2519#if DEBUG_INBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00002520 ALOGD("notifyDeviceReset - eventTime=%lld, deviceId=%d",
Jeff Brown65fd2512011-08-18 11:20:58 -07002521 args->eventTime, args->deviceId);
2522#endif
2523
2524 bool needWake;
2525 { // acquire lock
2526 AutoMutex _l(mLock);
2527
2528 DeviceResetEntry* newEntry = new DeviceResetEntry(args->eventTime, args->deviceId);
2529 needWake = enqueueInboundEventLocked(newEntry);
2530 } // release lock
2531
2532 if (needWake) {
2533 mLooper->wake();
2534 }
2535}
2536
Jeff Brown7fbdc842010-06-17 20:52:56 -07002537int32_t InputDispatcher::injectInputEvent(const InputEvent* event,
Jeff Brown0029c662011-03-30 02:25:18 -07002538 int32_t injectorPid, int32_t injectorUid, int32_t syncMode, int32_t timeoutMillis,
2539 uint32_t policyFlags) {
Jeff Brown7fbdc842010-06-17 20:52:56 -07002540#if DEBUG_INBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00002541 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Jeff Brown0029c662011-03-30 02:25:18 -07002542 "syncMode=%d, timeoutMillis=%d, policyFlags=0x%08x",
2543 event->getType(), injectorPid, injectorUid, syncMode, timeoutMillis, policyFlags);
Jeff Brown7fbdc842010-06-17 20:52:56 -07002544#endif
2545
2546 nsecs_t endTime = now() + milliseconds_to_nanoseconds(timeoutMillis);
Jeff Browne20c9e02010-10-11 14:20:19 -07002547
Jeff Brown0029c662011-03-30 02:25:18 -07002548 policyFlags |= POLICY_FLAG_INJECTED;
Jeff Browne20c9e02010-10-11 14:20:19 -07002549 if (hasInjectionPermission(injectorPid, injectorUid)) {
2550 policyFlags |= POLICY_FLAG_TRUSTED;
2551 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07002552
Jeff Brown3241b6b2012-02-03 15:08:02 -08002553 EventEntry* firstInjectedEntry;
2554 EventEntry* lastInjectedEntry;
Jeff Brownb6997262010-10-08 22:31:17 -07002555 switch (event->getType()) {
2556 case AINPUT_EVENT_TYPE_KEY: {
2557 const KeyEvent* keyEvent = static_cast<const KeyEvent*>(event);
2558 int32_t action = keyEvent->getAction();
2559 if (! validateKeyEvent(action)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07002560 return INPUT_EVENT_INJECTION_FAILED;
2561 }
2562
Jeff Brownb6997262010-10-08 22:31:17 -07002563 int32_t flags = keyEvent->getFlags();
Jeff Brown1f245102010-11-18 20:53:46 -08002564 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
2565 policyFlags |= POLICY_FLAG_VIRTUAL;
2566 }
2567
Jeff Brown0029c662011-03-30 02:25:18 -07002568 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
2569 mPolicy->interceptKeyBeforeQueueing(keyEvent, /*byref*/ policyFlags);
2570 }
Jeff Brown1f245102010-11-18 20:53:46 -08002571
2572 if (policyFlags & POLICY_FLAG_WOKE_HERE) {
2573 flags |= AKEY_EVENT_FLAG_WOKE_HERE;
2574 }
Jeff Brown6ec402b2010-07-28 15:48:59 -07002575
Jeff Brownb6997262010-10-08 22:31:17 -07002576 mLock.lock();
Jeff Brown3241b6b2012-02-03 15:08:02 -08002577 firstInjectedEntry = new KeyEntry(keyEvent->getEventTime(),
Jeff Brown1f245102010-11-18 20:53:46 -08002578 keyEvent->getDeviceId(), keyEvent->getSource(),
2579 policyFlags, action, flags,
2580 keyEvent->getKeyCode(), keyEvent->getScanCode(), keyEvent->getMetaState(),
Jeff Brownb6997262010-10-08 22:31:17 -07002581 keyEvent->getRepeatCount(), keyEvent->getDownTime());
Jeff Brown3241b6b2012-02-03 15:08:02 -08002582 lastInjectedEntry = firstInjectedEntry;
Jeff Brownb6997262010-10-08 22:31:17 -07002583 break;
2584 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07002585
Jeff Brownb6997262010-10-08 22:31:17 -07002586 case AINPUT_EVENT_TYPE_MOTION: {
2587 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
Jeff Brown83d616a2012-09-09 20:33:43 -07002588 int32_t displayId = ADISPLAY_ID_DEFAULT;
Jeff Brownb6997262010-10-08 22:31:17 -07002589 int32_t action = motionEvent->getAction();
2590 size_t pointerCount = motionEvent->getPointerCount();
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002591 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
2592 if (! validateMotionEvent(action, pointerCount, pointerProperties)) {
Jeff Brownb6997262010-10-08 22:31:17 -07002593 return INPUT_EVENT_INJECTION_FAILED;
2594 }
2595
Jeff Brown0029c662011-03-30 02:25:18 -07002596 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
2597 nsecs_t eventTime = motionEvent->getEventTime();
2598 mPolicy->interceptMotionBeforeQueueing(eventTime, /*byref*/ policyFlags);
2599 }
Jeff Brownb6997262010-10-08 22:31:17 -07002600
2601 mLock.lock();
2602 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
2603 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
Jeff Brown3241b6b2012-02-03 15:08:02 -08002604 firstInjectedEntry = new MotionEntry(*sampleEventTimes,
Jeff Brownb6997262010-10-08 22:31:17 -07002605 motionEvent->getDeviceId(), motionEvent->getSource(), policyFlags,
2606 action, motionEvent->getFlags(),
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002607 motionEvent->getMetaState(), motionEvent->getButtonState(),
2608 motionEvent->getEdgeFlags(),
Jeff Brownb6997262010-10-08 22:31:17 -07002609 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
Jeff Brown83d616a2012-09-09 20:33:43 -07002610 motionEvent->getDownTime(), displayId,
2611 uint32_t(pointerCount), pointerProperties, samplePointerCoords);
Jeff Brown3241b6b2012-02-03 15:08:02 -08002612 lastInjectedEntry = firstInjectedEntry;
Jeff Brownb6997262010-10-08 22:31:17 -07002613 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
2614 sampleEventTimes += 1;
2615 samplePointerCoords += pointerCount;
Jeff Brown3241b6b2012-02-03 15:08:02 -08002616 MotionEntry* nextInjectedEntry = new MotionEntry(*sampleEventTimes,
2617 motionEvent->getDeviceId(), motionEvent->getSource(), policyFlags,
2618 action, motionEvent->getFlags(),
2619 motionEvent->getMetaState(), motionEvent->getButtonState(),
2620 motionEvent->getEdgeFlags(),
2621 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
Jeff Brown83d616a2012-09-09 20:33:43 -07002622 motionEvent->getDownTime(), displayId,
2623 uint32_t(pointerCount), pointerProperties, samplePointerCoords);
Jeff Brown3241b6b2012-02-03 15:08:02 -08002624 lastInjectedEntry->next = nextInjectedEntry;
2625 lastInjectedEntry = nextInjectedEntry;
Jeff Brownb6997262010-10-08 22:31:17 -07002626 }
Jeff Brownb6997262010-10-08 22:31:17 -07002627 break;
2628 }
2629
2630 default:
Steve Block8564c8d2012-01-05 23:22:43 +00002631 ALOGW("Cannot inject event of type %d", event->getType());
Jeff Brownb6997262010-10-08 22:31:17 -07002632 return INPUT_EVENT_INJECTION_FAILED;
2633 }
2634
Jeff Brownac386072011-07-20 15:19:50 -07002635 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
Jeff Brownb6997262010-10-08 22:31:17 -07002636 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
2637 injectionState->injectionIsAsync = true;
2638 }
2639
2640 injectionState->refCount += 1;
Jeff Brown3241b6b2012-02-03 15:08:02 -08002641 lastInjectedEntry->injectionState = injectionState;
Jeff Brownb6997262010-10-08 22:31:17 -07002642
Jeff Brown3241b6b2012-02-03 15:08:02 -08002643 bool needWake = false;
2644 for (EventEntry* entry = firstInjectedEntry; entry != NULL; ) {
2645 EventEntry* nextEntry = entry->next;
2646 needWake |= enqueueInboundEventLocked(entry);
2647 entry = nextEntry;
2648 }
2649
Jeff Brownb6997262010-10-08 22:31:17 -07002650 mLock.unlock();
Jeff Brown7fbdc842010-06-17 20:52:56 -07002651
Jeff Brownb88102f2010-09-08 11:49:43 -07002652 if (needWake) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002653 mLooper->wake();
Jeff Brown7fbdc842010-06-17 20:52:56 -07002654 }
2655
2656 int32_t injectionResult;
2657 { // acquire lock
2658 AutoMutex _l(mLock);
2659
Jeff Brown6ec402b2010-07-28 15:48:59 -07002660 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
2661 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
2662 } else {
2663 for (;;) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002664 injectionResult = injectionState->injectionResult;
Jeff Brown6ec402b2010-07-28 15:48:59 -07002665 if (injectionResult != INPUT_EVENT_INJECTION_PENDING) {
2666 break;
2667 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07002668
Jeff Brown7fbdc842010-06-17 20:52:56 -07002669 nsecs_t remainingTimeout = endTime - now();
2670 if (remainingTimeout <= 0) {
Jeff Brown6ec402b2010-07-28 15:48:59 -07002671#if DEBUG_INJECTION
Steve Block5baa3a62011-12-20 16:23:08 +00002672 ALOGD("injectInputEvent - Timed out waiting for injection result "
Jeff Brown6ec402b2010-07-28 15:48:59 -07002673 "to become available.");
2674#endif
Jeff Brown7fbdc842010-06-17 20:52:56 -07002675 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
2676 break;
2677 }
2678
Jeff Brown6ec402b2010-07-28 15:48:59 -07002679 mInjectionResultAvailableCondition.waitRelative(mLock, remainingTimeout);
2680 }
2681
2682 if (injectionResult == INPUT_EVENT_INJECTION_SUCCEEDED
2683 && syncMode == INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002684 while (injectionState->pendingForegroundDispatches != 0) {
Jeff Brown6ec402b2010-07-28 15:48:59 -07002685#if DEBUG_INJECTION
Steve Block5baa3a62011-12-20 16:23:08 +00002686 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
Jeff Brown01ce2e92010-09-26 22:20:12 -07002687 injectionState->pendingForegroundDispatches);
Jeff Brown6ec402b2010-07-28 15:48:59 -07002688#endif
2689 nsecs_t remainingTimeout = endTime - now();
2690 if (remainingTimeout <= 0) {
2691#if DEBUG_INJECTION
Steve Block5baa3a62011-12-20 16:23:08 +00002692 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
Jeff Brown6ec402b2010-07-28 15:48:59 -07002693 "dispatches to finish.");
2694#endif
2695 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
2696 break;
2697 }
2698
2699 mInjectionSyncFinishedCondition.waitRelative(mLock, remainingTimeout);
2700 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07002701 }
2702 }
2703
Jeff Brownac386072011-07-20 15:19:50 -07002704 injectionState->release();
Jeff Brown7fbdc842010-06-17 20:52:56 -07002705 } // release lock
2706
Jeff Brown6ec402b2010-07-28 15:48:59 -07002707#if DEBUG_INJECTION
Steve Block5baa3a62011-12-20 16:23:08 +00002708 ALOGD("injectInputEvent - Finished with result %d. "
Jeff Brown6ec402b2010-07-28 15:48:59 -07002709 "injectorPid=%d, injectorUid=%d",
2710 injectionResult, injectorPid, injectorUid);
2711#endif
2712
Jeff Brown7fbdc842010-06-17 20:52:56 -07002713 return injectionResult;
2714}
2715
Jeff Brownb6997262010-10-08 22:31:17 -07002716bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
2717 return injectorUid == 0
2718 || mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
2719}
2720
Jeff Brown7fbdc842010-06-17 20:52:56 -07002721void InputDispatcher::setInjectionResultLocked(EventEntry* entry, int32_t injectionResult) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002722 InjectionState* injectionState = entry->injectionState;
2723 if (injectionState) {
Jeff Brown7fbdc842010-06-17 20:52:56 -07002724#if DEBUG_INJECTION
Steve Block5baa3a62011-12-20 16:23:08 +00002725 ALOGD("Setting input event injection result to %d. "
Jeff Brown7fbdc842010-06-17 20:52:56 -07002726 "injectorPid=%d, injectorUid=%d",
Jeff Brown01ce2e92010-09-26 22:20:12 -07002727 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
Jeff Brown7fbdc842010-06-17 20:52:56 -07002728#endif
2729
Jeff Brown0029c662011-03-30 02:25:18 -07002730 if (injectionState->injectionIsAsync
2731 && !(entry->policyFlags & POLICY_FLAG_FILTERED)) {
Jeff Brown6ec402b2010-07-28 15:48:59 -07002732 // Log the outcome since the injector did not wait for the injection result.
2733 switch (injectionResult) {
2734 case INPUT_EVENT_INJECTION_SUCCEEDED:
Steve Block71f2cf12011-10-20 11:56:00 +01002735 ALOGV("Asynchronous input event injection succeeded.");
Jeff Brown6ec402b2010-07-28 15:48:59 -07002736 break;
2737 case INPUT_EVENT_INJECTION_FAILED:
Steve Block8564c8d2012-01-05 23:22:43 +00002738 ALOGW("Asynchronous input event injection failed.");
Jeff Brown6ec402b2010-07-28 15:48:59 -07002739 break;
2740 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
Steve Block8564c8d2012-01-05 23:22:43 +00002741 ALOGW("Asynchronous input event injection permission denied.");
Jeff Brown6ec402b2010-07-28 15:48:59 -07002742 break;
2743 case INPUT_EVENT_INJECTION_TIMED_OUT:
Steve Block8564c8d2012-01-05 23:22:43 +00002744 ALOGW("Asynchronous input event injection timed out.");
Jeff Brown6ec402b2010-07-28 15:48:59 -07002745 break;
2746 }
2747 }
2748
Jeff Brown01ce2e92010-09-26 22:20:12 -07002749 injectionState->injectionResult = injectionResult;
Jeff Brown7fbdc842010-06-17 20:52:56 -07002750 mInjectionResultAvailableCondition.broadcast();
2751 }
2752}
2753
Jeff Brown01ce2e92010-09-26 22:20:12 -07002754void InputDispatcher::incrementPendingForegroundDispatchesLocked(EventEntry* entry) {
2755 InjectionState* injectionState = entry->injectionState;
2756 if (injectionState) {
2757 injectionState->pendingForegroundDispatches += 1;
2758 }
2759}
2760
Jeff Brown519e0242010-09-15 15:18:56 -07002761void InputDispatcher::decrementPendingForegroundDispatchesLocked(EventEntry* entry) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002762 InjectionState* injectionState = entry->injectionState;
2763 if (injectionState) {
2764 injectionState->pendingForegroundDispatches -= 1;
Jeff Brown6ec402b2010-07-28 15:48:59 -07002765
Jeff Brown01ce2e92010-09-26 22:20:12 -07002766 if (injectionState->pendingForegroundDispatches == 0) {
2767 mInjectionSyncFinishedCondition.broadcast();
2768 }
Jeff Brownb88102f2010-09-08 11:49:43 -07002769 }
2770}
2771
Jeff Brown9302c872011-07-13 22:51:29 -07002772sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
2773 const sp<InputChannel>& inputChannel) const {
2774 size_t numWindows = mWindowHandles.size();
2775 for (size_t i = 0; i < numWindows; i++) {
2776 const sp<InputWindowHandle>& windowHandle = mWindowHandles.itemAt(i);
Jeff Browncc4f7db2011-08-30 20:34:48 -07002777 if (windowHandle->getInputChannel() == inputChannel) {
Jeff Brown9302c872011-07-13 22:51:29 -07002778 return windowHandle;
Jeff Brown01ce2e92010-09-26 22:20:12 -07002779 }
2780 }
2781 return NULL;
2782}
2783
Jeff Brown9302c872011-07-13 22:51:29 -07002784bool InputDispatcher::hasWindowHandleLocked(
2785 const sp<InputWindowHandle>& windowHandle) const {
2786 size_t numWindows = mWindowHandles.size();
2787 for (size_t i = 0; i < numWindows; i++) {
2788 if (mWindowHandles.itemAt(i) == windowHandle) {
2789 return true;
2790 }
2791 }
2792 return false;
2793}
2794
2795void InputDispatcher::setInputWindows(const Vector<sp<InputWindowHandle> >& inputWindowHandles) {
Jeff Brownb88102f2010-09-08 11:49:43 -07002796#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002797 ALOGD("setInputWindows");
Jeff Brownb88102f2010-09-08 11:49:43 -07002798#endif
2799 { // acquire lock
2800 AutoMutex _l(mLock);
2801
Jeff Browncc4f7db2011-08-30 20:34:48 -07002802 Vector<sp<InputWindowHandle> > oldWindowHandles = mWindowHandles;
Jeff Brown9302c872011-07-13 22:51:29 -07002803 mWindowHandles = inputWindowHandles;
Jeff Brownb6997262010-10-08 22:31:17 -07002804
Jeff Brown9302c872011-07-13 22:51:29 -07002805 sp<InputWindowHandle> newFocusedWindowHandle;
2806 bool foundHoveredWindow = false;
2807 for (size_t i = 0; i < mWindowHandles.size(); i++) {
2808 const sp<InputWindowHandle>& windowHandle = mWindowHandles.itemAt(i);
Jeff Browncc4f7db2011-08-30 20:34:48 -07002809 if (!windowHandle->updateInfo() || windowHandle->getInputChannel() == NULL) {
Jeff Brown9302c872011-07-13 22:51:29 -07002810 mWindowHandles.removeAt(i--);
2811 continue;
2812 }
Jeff Browncc4f7db2011-08-30 20:34:48 -07002813 if (windowHandle->getInfo()->hasFocus) {
Jeff Brown9302c872011-07-13 22:51:29 -07002814 newFocusedWindowHandle = windowHandle;
2815 }
2816 if (windowHandle == mLastHoverWindowHandle) {
2817 foundHoveredWindow = true;
Jeff Brownb88102f2010-09-08 11:49:43 -07002818 }
2819 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07002820
Jeff Brown9302c872011-07-13 22:51:29 -07002821 if (!foundHoveredWindow) {
2822 mLastHoverWindowHandle = NULL;
2823 }
2824
2825 if (mFocusedWindowHandle != newFocusedWindowHandle) {
2826 if (mFocusedWindowHandle != NULL) {
Jeff Brownb6997262010-10-08 22:31:17 -07002827#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002828 ALOGD("Focus left window: %s",
Jeff Browncc4f7db2011-08-30 20:34:48 -07002829 mFocusedWindowHandle->getName().string());
Jeff Brownb6997262010-10-08 22:31:17 -07002830#endif
Jeff Browncc4f7db2011-08-30 20:34:48 -07002831 sp<InputChannel> focusedInputChannel = mFocusedWindowHandle->getInputChannel();
2832 if (focusedInputChannel != NULL) {
Christopher Tated9be36c2011-08-16 16:09:33 -07002833 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
2834 "focus left window");
2835 synthesizeCancelationEventsForInputChannelLocked(
Jeff Browncc4f7db2011-08-30 20:34:48 -07002836 focusedInputChannel, options);
Christopher Tated9be36c2011-08-16 16:09:33 -07002837 }
Jeff Brownb6997262010-10-08 22:31:17 -07002838 }
Jeff Brown9302c872011-07-13 22:51:29 -07002839 if (newFocusedWindowHandle != NULL) {
Jeff Brownb6997262010-10-08 22:31:17 -07002840#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002841 ALOGD("Focus entered window: %s",
Jeff Browncc4f7db2011-08-30 20:34:48 -07002842 newFocusedWindowHandle->getName().string());
Jeff Brownb6997262010-10-08 22:31:17 -07002843#endif
Jeff Brown9302c872011-07-13 22:51:29 -07002844 }
2845 mFocusedWindowHandle = newFocusedWindowHandle;
Jeff Brownb6997262010-10-08 22:31:17 -07002846 }
2847
Jeff Brown9302c872011-07-13 22:51:29 -07002848 for (size_t i = 0; i < mTouchState.windows.size(); i++) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002849 TouchedWindow& touchedWindow = mTouchState.windows.editItemAt(i);
Jeff Brown9302c872011-07-13 22:51:29 -07002850 if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
Jeff Brownb6997262010-10-08 22:31:17 -07002851#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002852 ALOGD("Touched window was removed: %s",
Jeff Browncc4f7db2011-08-30 20:34:48 -07002853 touchedWindow.windowHandle->getName().string());
Jeff Brownb6997262010-10-08 22:31:17 -07002854#endif
Jeff Browncc4f7db2011-08-30 20:34:48 -07002855 sp<InputChannel> touchedInputChannel =
2856 touchedWindow.windowHandle->getInputChannel();
2857 if (touchedInputChannel != NULL) {
Christopher Tated9be36c2011-08-16 16:09:33 -07002858 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
2859 "touched window was removed");
2860 synthesizeCancelationEventsForInputChannelLocked(
Jeff Browncc4f7db2011-08-30 20:34:48 -07002861 touchedInputChannel, options);
Christopher Tated9be36c2011-08-16 16:09:33 -07002862 }
Jeff Brown9302c872011-07-13 22:51:29 -07002863 mTouchState.windows.removeAt(i--);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002864 }
2865 }
Jeff Browncc4f7db2011-08-30 20:34:48 -07002866
2867 // Release information for windows that are no longer present.
2868 // This ensures that unused input channels are released promptly.
2869 // Otherwise, they might stick around until the window handle is destroyed
2870 // which might not happen until the next GC.
2871 for (size_t i = 0; i < oldWindowHandles.size(); i++) {
2872 const sp<InputWindowHandle>& oldWindowHandle = oldWindowHandles.itemAt(i);
2873 if (!hasWindowHandleLocked(oldWindowHandle)) {
2874#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002875 ALOGD("Window went away: %s", oldWindowHandle->getName().string());
Jeff Browncc4f7db2011-08-30 20:34:48 -07002876#endif
2877 oldWindowHandle->releaseInfo();
2878 }
2879 }
Jeff Brownb88102f2010-09-08 11:49:43 -07002880 } // release lock
2881
2882 // Wake up poll loop since it may need to make new input dispatching choices.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002883 mLooper->wake();
Jeff Brownb88102f2010-09-08 11:49:43 -07002884}
2885
Jeff Brown9302c872011-07-13 22:51:29 -07002886void InputDispatcher::setFocusedApplication(
2887 const sp<InputApplicationHandle>& inputApplicationHandle) {
Jeff Brownb88102f2010-09-08 11:49:43 -07002888#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002889 ALOGD("setFocusedApplication");
Jeff Brownb88102f2010-09-08 11:49:43 -07002890#endif
2891 { // acquire lock
2892 AutoMutex _l(mLock);
2893
Jeff Browncc4f7db2011-08-30 20:34:48 -07002894 if (inputApplicationHandle != NULL && inputApplicationHandle->updateInfo()) {
Jeff Brown5ea29ab2011-07-27 11:50:51 -07002895 if (mFocusedApplicationHandle != inputApplicationHandle) {
2896 if (mFocusedApplicationHandle != NULL) {
Jeff Browne9bb9be2012-02-06 15:47:55 -08002897 resetANRTimeoutsLocked();
Jeff Browncc4f7db2011-08-30 20:34:48 -07002898 mFocusedApplicationHandle->releaseInfo();
Jeff Brown5ea29ab2011-07-27 11:50:51 -07002899 }
2900 mFocusedApplicationHandle = inputApplicationHandle;
2901 }
2902 } else if (mFocusedApplicationHandle != NULL) {
Jeff Browne9bb9be2012-02-06 15:47:55 -08002903 resetANRTimeoutsLocked();
Jeff Browncc4f7db2011-08-30 20:34:48 -07002904 mFocusedApplicationHandle->releaseInfo();
Jeff Brown9302c872011-07-13 22:51:29 -07002905 mFocusedApplicationHandle.clear();
Jeff Brownb88102f2010-09-08 11:49:43 -07002906 }
2907
2908#if DEBUG_FOCUS
Jeff Brownb6997262010-10-08 22:31:17 -07002909 //logDispatchStateLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -07002910#endif
2911 } // release lock
2912
2913 // Wake up poll loop since it may need to make new input dispatching choices.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002914 mLooper->wake();
Jeff Brownb88102f2010-09-08 11:49:43 -07002915}
2916
Jeff Brownb88102f2010-09-08 11:49:43 -07002917void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
2918#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002919 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
Jeff Brownb88102f2010-09-08 11:49:43 -07002920#endif
2921
2922 bool changed;
2923 { // acquire lock
2924 AutoMutex _l(mLock);
2925
2926 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
Jeff Brown120a4592010-10-27 18:43:51 -07002927 if (mDispatchFrozen && !frozen) {
Jeff Brownb88102f2010-09-08 11:49:43 -07002928 resetANRTimeoutsLocked();
2929 }
2930
Jeff Brown120a4592010-10-27 18:43:51 -07002931 if (mDispatchEnabled && !enabled) {
2932 resetAndDropEverythingLocked("dispatcher is being disabled");
2933 }
2934
Jeff Brownb88102f2010-09-08 11:49:43 -07002935 mDispatchEnabled = enabled;
2936 mDispatchFrozen = frozen;
2937 changed = true;
2938 } else {
2939 changed = false;
2940 }
2941
2942#if DEBUG_FOCUS
Jeff Brownb6997262010-10-08 22:31:17 -07002943 //logDispatchStateLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -07002944#endif
2945 } // release lock
2946
2947 if (changed) {
2948 // Wake up poll loop since it may need to make new input dispatching choices.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002949 mLooper->wake();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002950 }
2951}
2952
Jeff Brown0029c662011-03-30 02:25:18 -07002953void InputDispatcher::setInputFilterEnabled(bool enabled) {
2954#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002955 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
Jeff Brown0029c662011-03-30 02:25:18 -07002956#endif
2957
2958 { // acquire lock
2959 AutoMutex _l(mLock);
2960
2961 if (mInputFilterEnabled == enabled) {
2962 return;
2963 }
2964
2965 mInputFilterEnabled = enabled;
2966 resetAndDropEverythingLocked("input filter is being enabled or disabled");
2967 } // release lock
2968
2969 // Wake up poll loop since there might be work to do to drop everything.
2970 mLooper->wake();
2971}
2972
Jeff Browne6504122010-09-27 14:52:15 -07002973bool InputDispatcher::transferTouchFocus(const sp<InputChannel>& fromChannel,
2974 const sp<InputChannel>& toChannel) {
2975#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002976 ALOGD("transferTouchFocus: fromChannel=%s, toChannel=%s",
Jeff Browne6504122010-09-27 14:52:15 -07002977 fromChannel->getName().string(), toChannel->getName().string());
2978#endif
2979 { // acquire lock
2980 AutoMutex _l(mLock);
2981
Jeff Brown9302c872011-07-13 22:51:29 -07002982 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromChannel);
2983 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toChannel);
2984 if (fromWindowHandle == NULL || toWindowHandle == NULL) {
Jeff Browne6504122010-09-27 14:52:15 -07002985#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002986 ALOGD("Cannot transfer focus because from or to window not found.");
Jeff Browne6504122010-09-27 14:52:15 -07002987#endif
2988 return false;
2989 }
Jeff Brown9302c872011-07-13 22:51:29 -07002990 if (fromWindowHandle == toWindowHandle) {
Jeff Browne6504122010-09-27 14:52:15 -07002991#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002992 ALOGD("Trivial transfer to same window.");
Jeff Browne6504122010-09-27 14:52:15 -07002993#endif
2994 return true;
2995 }
Jeff Brown83d616a2012-09-09 20:33:43 -07002996 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
2997#if DEBUG_FOCUS
2998 ALOGD("Cannot transfer focus because windows are on different displays.");
2999#endif
3000 return false;
3001 }
Jeff Browne6504122010-09-27 14:52:15 -07003002
3003 bool found = false;
3004 for (size_t i = 0; i < mTouchState.windows.size(); i++) {
3005 const TouchedWindow& touchedWindow = mTouchState.windows[i];
Jeff Brown9302c872011-07-13 22:51:29 -07003006 if (touchedWindow.windowHandle == fromWindowHandle) {
Jeff Browne6504122010-09-27 14:52:15 -07003007 int32_t oldTargetFlags = touchedWindow.targetFlags;
3008 BitSet32 pointerIds = touchedWindow.pointerIds;
3009
3010 mTouchState.windows.removeAt(i);
3011
Jeff Brown46e75292010-11-10 16:53:45 -08003012 int32_t newTargetFlags = oldTargetFlags
Jeff Browna032cc02011-03-07 16:56:21 -08003013 & (InputTarget::FLAG_FOREGROUND
3014 | InputTarget::FLAG_SPLIT | InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brown9302c872011-07-13 22:51:29 -07003015 mTouchState.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Jeff Browne6504122010-09-27 14:52:15 -07003016
3017 found = true;
3018 break;
3019 }
3020 }
3021
3022 if (! found) {
3023#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00003024 ALOGD("Focus transfer failed because from window did not have focus.");
Jeff Browne6504122010-09-27 14:52:15 -07003025#endif
3026 return false;
3027 }
3028
Jeff Brown9c9f1a32010-10-11 18:32:20 -07003029 ssize_t fromConnectionIndex = getConnectionIndexLocked(fromChannel);
3030 ssize_t toConnectionIndex = getConnectionIndexLocked(toChannel);
3031 if (fromConnectionIndex >= 0 && toConnectionIndex >= 0) {
Jeff Browncbee6d62012-02-03 20:11:27 -08003032 sp<Connection> fromConnection = mConnectionsByFd.valueAt(fromConnectionIndex);
3033 sp<Connection> toConnection = mConnectionsByFd.valueAt(toConnectionIndex);
Jeff Brown9c9f1a32010-10-11 18:32:20 -07003034
3035 fromConnection->inputState.copyPointerStateTo(toConnection->inputState);
Jeff Brownda3d5a92011-03-29 15:11:34 -07003036 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Jeff Brown9c9f1a32010-10-11 18:32:20 -07003037 "transferring touch focus from this window to another window");
Jeff Brownda3d5a92011-03-29 15:11:34 -07003038 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Jeff Brown9c9f1a32010-10-11 18:32:20 -07003039 }
3040
Jeff Browne6504122010-09-27 14:52:15 -07003041#if DEBUG_FOCUS
3042 logDispatchStateLocked();
3043#endif
3044 } // release lock
3045
3046 // Wake up poll loop since it may need to make new input dispatching choices.
3047 mLooper->wake();
3048 return true;
3049}
3050
Jeff Brown120a4592010-10-27 18:43:51 -07003051void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
3052#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00003053 ALOGD("Resetting and dropping all events (%s).", reason);
Jeff Brown120a4592010-10-27 18:43:51 -07003054#endif
3055
Jeff Brownda3d5a92011-03-29 15:11:34 -07003056 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
3057 synthesizeCancelationEventsForAllConnectionsLocked(options);
Jeff Brown120a4592010-10-27 18:43:51 -07003058
3059 resetKeyRepeatLocked();
3060 releasePendingEventLocked();
3061 drainInboundQueueLocked();
Jeff Browne9bb9be2012-02-06 15:47:55 -08003062 resetANRTimeoutsLocked();
Jeff Brown120a4592010-10-27 18:43:51 -07003063
3064 mTouchState.reset();
Jeff Brown9302c872011-07-13 22:51:29 -07003065 mLastHoverWindowHandle.clear();
Jeff Brown120a4592010-10-27 18:43:51 -07003066}
3067
Jeff Brownb88102f2010-09-08 11:49:43 -07003068void InputDispatcher::logDispatchStateLocked() {
3069 String8 dump;
3070 dumpDispatchStateLocked(dump);
Jeff Brown2a95c2a2010-09-16 12:31:46 -07003071
3072 char* text = dump.lockBuffer(dump.size());
3073 char* start = text;
3074 while (*start != '\0') {
3075 char* end = strchr(start, '\n');
3076 if (*end == '\n') {
3077 *(end++) = '\0';
3078 }
Steve Block5baa3a62011-12-20 16:23:08 +00003079 ALOGD("%s", start);
Jeff Brown2a95c2a2010-09-16 12:31:46 -07003080 start = end;
3081 }
Jeff Brownb88102f2010-09-08 11:49:43 -07003082}
3083
3084void InputDispatcher::dumpDispatchStateLocked(String8& dump) {
Jeff Brownf2f487182010-10-01 17:46:21 -07003085 dump.appendFormat(INDENT "DispatchEnabled: %d\n", mDispatchEnabled);
3086 dump.appendFormat(INDENT "DispatchFrozen: %d\n", mDispatchFrozen);
Jeff Brownb88102f2010-09-08 11:49:43 -07003087
Jeff Brown9302c872011-07-13 22:51:29 -07003088 if (mFocusedApplicationHandle != NULL) {
Jeff Brownf2f487182010-10-01 17:46:21 -07003089 dump.appendFormat(INDENT "FocusedApplication: name='%s', dispatchingTimeout=%0.3fms\n",
Jeff Browncc4f7db2011-08-30 20:34:48 -07003090 mFocusedApplicationHandle->getName().string(),
3091 mFocusedApplicationHandle->getDispatchingTimeout(
3092 DEFAULT_INPUT_DISPATCHING_TIMEOUT) / 1000000.0);
Jeff Brownb88102f2010-09-08 11:49:43 -07003093 } else {
Jeff Brownf2f487182010-10-01 17:46:21 -07003094 dump.append(INDENT "FocusedApplication: <null>\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003095 }
Jeff Brownf2f487182010-10-01 17:46:21 -07003096 dump.appendFormat(INDENT "FocusedWindow: name='%s'\n",
Jeff Browncc4f7db2011-08-30 20:34:48 -07003097 mFocusedWindowHandle != NULL ? mFocusedWindowHandle->getName().string() : "<null>");
Jeff Brownf2f487182010-10-01 17:46:21 -07003098
3099 dump.appendFormat(INDENT "TouchDown: %s\n", toString(mTouchState.down));
3100 dump.appendFormat(INDENT "TouchSplit: %s\n", toString(mTouchState.split));
Jeff Brown95712852011-01-04 19:41:59 -08003101 dump.appendFormat(INDENT "TouchDeviceId: %d\n", mTouchState.deviceId);
Jeff Brown58a2da82011-01-25 16:02:22 -08003102 dump.appendFormat(INDENT "TouchSource: 0x%08x\n", mTouchState.source);
Jeff Brown83d616a2012-09-09 20:33:43 -07003103 dump.appendFormat(INDENT "TouchDisplayId: %d\n", mTouchState.displayId);
Jeff Brownf2f487182010-10-01 17:46:21 -07003104 if (!mTouchState.windows.isEmpty()) {
3105 dump.append(INDENT "TouchedWindows:\n");
3106 for (size_t i = 0; i < mTouchState.windows.size(); i++) {
3107 const TouchedWindow& touchedWindow = mTouchState.windows[i];
3108 dump.appendFormat(INDENT2 "%d: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
Jeff Browncc4f7db2011-08-30 20:34:48 -07003109 i, touchedWindow.windowHandle->getName().string(),
3110 touchedWindow.pointerIds.value,
Jeff Brownf2f487182010-10-01 17:46:21 -07003111 touchedWindow.targetFlags);
3112 }
3113 } else {
3114 dump.append(INDENT "TouchedWindows: <none>\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003115 }
3116
Jeff Brown9302c872011-07-13 22:51:29 -07003117 if (!mWindowHandles.isEmpty()) {
Jeff Brownf2f487182010-10-01 17:46:21 -07003118 dump.append(INDENT "Windows:\n");
Jeff Brown9302c872011-07-13 22:51:29 -07003119 for (size_t i = 0; i < mWindowHandles.size(); i++) {
3120 const sp<InputWindowHandle>& windowHandle = mWindowHandles.itemAt(i);
Jeff Browncc4f7db2011-08-30 20:34:48 -07003121 const InputWindowInfo* windowInfo = windowHandle->getInfo();
3122
Jeff Brown83d616a2012-09-09 20:33:43 -07003123 dump.appendFormat(INDENT2 "%d: name='%s', displayId=%d, "
3124 "paused=%s, hasFocus=%s, hasWallpaper=%s, "
Jeff Brownf2f487182010-10-01 17:46:21 -07003125 "visible=%s, canReceiveKeys=%s, flags=0x%08x, type=0x%08x, layer=%d, "
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003126 "frame=[%d,%d][%d,%d], scale=%f, "
Jeff Brownfbf09772011-01-16 14:06:57 -08003127 "touchableRegion=",
Jeff Brown83d616a2012-09-09 20:33:43 -07003128 i, windowInfo->name.string(), windowInfo->displayId,
Jeff Browncc4f7db2011-08-30 20:34:48 -07003129 toString(windowInfo->paused),
3130 toString(windowInfo->hasFocus),
3131 toString(windowInfo->hasWallpaper),
3132 toString(windowInfo->visible),
3133 toString(windowInfo->canReceiveKeys),
3134 windowInfo->layoutParamsFlags, windowInfo->layoutParamsType,
3135 windowInfo->layer,
3136 windowInfo->frameLeft, windowInfo->frameTop,
3137 windowInfo->frameRight, windowInfo->frameBottom,
3138 windowInfo->scaleFactor);
3139 dumpRegion(dump, windowInfo->touchableRegion);
3140 dump.appendFormat(", inputFeatures=0x%08x", windowInfo->inputFeatures);
Jeff Brownfbf09772011-01-16 14:06:57 -08003141 dump.appendFormat(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%0.3fms\n",
Jeff Browncc4f7db2011-08-30 20:34:48 -07003142 windowInfo->ownerPid, windowInfo->ownerUid,
3143 windowInfo->dispatchingTimeout / 1000000.0);
Jeff Brownf2f487182010-10-01 17:46:21 -07003144 }
3145 } else {
3146 dump.append(INDENT "Windows: <none>\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003147 }
3148
Jeff Brownf2f487182010-10-01 17:46:21 -07003149 if (!mMonitoringChannels.isEmpty()) {
3150 dump.append(INDENT "MonitoringChannels:\n");
3151 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
3152 const sp<InputChannel>& channel = mMonitoringChannels[i];
3153 dump.appendFormat(INDENT2 "%d: '%s'\n", i, channel->getName().string());
3154 }
3155 } else {
3156 dump.append(INDENT "MonitoringChannels: <none>\n");
3157 }
Jeff Brown519e0242010-09-15 15:18:56 -07003158
Jeff Brown265f1cc2012-06-11 18:01:06 -07003159 nsecs_t currentTime = now();
3160
Jeff Brown6876f322013-08-07 16:46:50 -07003161 // Dump recently dispatched or dropped events from oldest to newest.
3162 if (!mRecentQueue.isEmpty()) {
3163 dump.appendFormat(INDENT "RecentQueue: length=%u\n", mRecentQueue.count());
3164 for (EventEntry* entry = mRecentQueue.head; entry; entry = entry->next) {
3165 dump.append(INDENT2);
3166 entry->appendDescription(dump);
3167 dump.appendFormat(", age=%0.1fms\n",
3168 (currentTime - entry->eventTime) * 0.000001f);
3169 }
3170 } else {
3171 dump.append(INDENT "RecentQueue: <empty>\n");
3172 }
3173
3174 // Dump event currently being dispatched.
3175 if (mPendingEvent) {
3176 dump.append(INDENT "PendingEvent:\n");
3177 dump.append(INDENT2);
3178 mPendingEvent->appendDescription(dump);
3179 dump.appendFormat(", age=%0.1fms\n",
3180 (currentTime - mPendingEvent->eventTime) * 0.000001f);
3181 } else {
3182 dump.append(INDENT "PendingEvent: <none>\n");
3183 }
3184
3185 // Dump inbound events from oldest to newest.
Jeff Brown265f1cc2012-06-11 18:01:06 -07003186 if (!mInboundQueue.isEmpty()) {
3187 dump.appendFormat(INDENT "InboundQueue: length=%u\n", mInboundQueue.count());
3188 for (EventEntry* entry = mInboundQueue.head; entry; entry = entry->next) {
3189 dump.append(INDENT2);
3190 entry->appendDescription(dump);
Jeff Brown22aa5122012-06-17 12:01:06 -07003191 dump.appendFormat(", age=%0.1fms\n",
Jeff Brown265f1cc2012-06-11 18:01:06 -07003192 (currentTime - entry->eventTime) * 0.000001f);
3193 }
3194 } else {
3195 dump.append(INDENT "InboundQueue: <empty>\n");
3196 }
3197
3198 if (!mConnectionsByFd.isEmpty()) {
3199 dump.append(INDENT "Connections:\n");
3200 for (size_t i = 0; i < mConnectionsByFd.size(); i++) {
3201 const sp<Connection>& connection = mConnectionsByFd.valueAt(i);
3202 dump.appendFormat(INDENT2 "%d: channelName='%s', windowName='%s', "
3203 "status=%s, monitor=%s, inputPublisherBlocked=%s\n",
3204 i, connection->getInputChannelName(), connection->getWindowName(),
3205 connection->getStatusLabel(), toString(connection->monitor),
3206 toString(connection->inputPublisherBlocked));
3207
3208 if (!connection->outboundQueue.isEmpty()) {
3209 dump.appendFormat(INDENT3 "OutboundQueue: length=%u\n",
3210 connection->outboundQueue.count());
3211 for (DispatchEntry* entry = connection->outboundQueue.head; entry;
3212 entry = entry->next) {
3213 dump.append(INDENT4);
3214 entry->eventEntry->appendDescription(dump);
Jeff Brown22aa5122012-06-17 12:01:06 -07003215 dump.appendFormat(", targetFlags=0x%08x, resolvedAction=%d, age=%0.1fms\n",
Jeff Brown265f1cc2012-06-11 18:01:06 -07003216 entry->targetFlags, entry->resolvedAction,
3217 (currentTime - entry->eventEntry->eventTime) * 0.000001f);
3218 }
3219 } else {
3220 dump.append(INDENT3 "OutboundQueue: <empty>\n");
3221 }
3222
3223 if (!connection->waitQueue.isEmpty()) {
3224 dump.appendFormat(INDENT3 "WaitQueue: length=%u\n",
3225 connection->waitQueue.count());
3226 for (DispatchEntry* entry = connection->waitQueue.head; entry;
3227 entry = entry->next) {
3228 dump.append(INDENT4);
3229 entry->eventEntry->appendDescription(dump);
3230 dump.appendFormat(", targetFlags=0x%08x, resolvedAction=%d, "
Jeff Brown22aa5122012-06-17 12:01:06 -07003231 "age=%0.1fms, wait=%0.1fms\n",
Jeff Brown265f1cc2012-06-11 18:01:06 -07003232 entry->targetFlags, entry->resolvedAction,
3233 (currentTime - entry->eventEntry->eventTime) * 0.000001f,
3234 (currentTime - entry->deliveryTime) * 0.000001f);
3235 }
3236 } else {
3237 dump.append(INDENT3 "WaitQueue: <empty>\n");
3238 }
3239 }
3240 } else {
3241 dump.append(INDENT "Connections: <none>\n");
3242 }
Jeff Brownf2f487182010-10-01 17:46:21 -07003243
Jeff Brownb88102f2010-09-08 11:49:43 -07003244 if (isAppSwitchPendingLocked()) {
Jeff Brown22aa5122012-06-17 12:01:06 -07003245 dump.appendFormat(INDENT "AppSwitch: pending, due in %0.1fms\n",
Jeff Brownb88102f2010-09-08 11:49:43 -07003246 (mAppSwitchDueTime - now()) / 1000000.0);
3247 } else {
Jeff Brownf2f487182010-10-01 17:46:21 -07003248 dump.append(INDENT "AppSwitch: not pending\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003249 }
Jeff Brown22aa5122012-06-17 12:01:06 -07003250
3251 dump.append(INDENT "Configuration:\n");
3252 dump.appendFormat(INDENT2 "KeyRepeatDelay: %0.1fms\n",
3253 mConfig.keyRepeatDelay * 0.000001f);
3254 dump.appendFormat(INDENT2 "KeyRepeatTimeout: %0.1fms\n",
3255 mConfig.keyRepeatTimeout * 0.000001f);
Jeff Brownb88102f2010-09-08 11:49:43 -07003256}
3257
Jeff Brown928e0542011-01-10 11:17:36 -08003258status_t InputDispatcher::registerInputChannel(const sp<InputChannel>& inputChannel,
3259 const sp<InputWindowHandle>& inputWindowHandle, bool monitor) {
Jeff Brown9c3cda02010-06-15 01:31:58 -07003260#if DEBUG_REGISTRATION
Steve Block5baa3a62011-12-20 16:23:08 +00003261 ALOGD("channel '%s' ~ registerInputChannel - monitor=%s", inputChannel->getName().string(),
Jeff Brownb88102f2010-09-08 11:49:43 -07003262 toString(monitor));
Jeff Brown9c3cda02010-06-15 01:31:58 -07003263#endif
3264
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003265 { // acquire lock
3266 AutoMutex _l(mLock);
3267
Jeff Brown519e0242010-09-15 15:18:56 -07003268 if (getConnectionIndexLocked(inputChannel) >= 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00003269 ALOGW("Attempted to register already registered input channel '%s'",
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003270 inputChannel->getName().string());
3271 return BAD_VALUE;
3272 }
3273
Jeff Browncc4f7db2011-08-30 20:34:48 -07003274 sp<Connection> connection = new Connection(inputChannel, inputWindowHandle, monitor);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003275
Jeff Brown91e32892012-02-14 15:56:29 -08003276 int fd = inputChannel->getFd();
Jeff Browncbee6d62012-02-03 20:11:27 -08003277 mConnectionsByFd.add(fd, connection);
Jeff Brown9c3cda02010-06-15 01:31:58 -07003278
Jeff Brownb88102f2010-09-08 11:49:43 -07003279 if (monitor) {
3280 mMonitoringChannels.push(inputChannel);
3281 }
3282
Jeff Browncbee6d62012-02-03 20:11:27 -08003283 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003284 } // release lock
Jeff Brown074b8b72012-10-31 19:01:31 -07003285
3286 // Wake the looper because some connections have changed.
3287 mLooper->wake();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003288 return OK;
3289}
3290
3291status_t InputDispatcher::unregisterInputChannel(const sp<InputChannel>& inputChannel) {
Jeff Brown9c3cda02010-06-15 01:31:58 -07003292#if DEBUG_REGISTRATION
Steve Block5baa3a62011-12-20 16:23:08 +00003293 ALOGD("channel '%s' ~ unregisterInputChannel", inputChannel->getName().string());
Jeff Brown9c3cda02010-06-15 01:31:58 -07003294#endif
3295
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003296 { // acquire lock
3297 AutoMutex _l(mLock);
3298
Jeff Browncc4f7db2011-08-30 20:34:48 -07003299 status_t status = unregisterInputChannelLocked(inputChannel, false /*notify*/);
3300 if (status) {
3301 return status;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003302 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003303 } // release lock
3304
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003305 // Wake the poll loop because removing the connection may have changed the current
3306 // synchronization state.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07003307 mLooper->wake();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003308 return OK;
3309}
3310
Jeff Browncc4f7db2011-08-30 20:34:48 -07003311status_t InputDispatcher::unregisterInputChannelLocked(const sp<InputChannel>& inputChannel,
3312 bool notify) {
3313 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
3314 if (connectionIndex < 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00003315 ALOGW("Attempted to unregister already unregistered input channel '%s'",
Jeff Browncc4f7db2011-08-30 20:34:48 -07003316 inputChannel->getName().string());
3317 return BAD_VALUE;
3318 }
3319
Jeff Browncbee6d62012-02-03 20:11:27 -08003320 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
3321 mConnectionsByFd.removeItemsAt(connectionIndex);
Jeff Browncc4f7db2011-08-30 20:34:48 -07003322
3323 if (connection->monitor) {
3324 removeMonitorChannelLocked(inputChannel);
3325 }
3326
Jeff Browncbee6d62012-02-03 20:11:27 -08003327 mLooper->removeFd(inputChannel->getFd());
Jeff Browncc4f7db2011-08-30 20:34:48 -07003328
3329 nsecs_t currentTime = now();
3330 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
3331
Jeff Browncc4f7db2011-08-30 20:34:48 -07003332 connection->status = Connection::STATUS_ZOMBIE;
3333 return OK;
3334}
3335
3336void InputDispatcher::removeMonitorChannelLocked(const sp<InputChannel>& inputChannel) {
3337 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
3338 if (mMonitoringChannels[i] == inputChannel) {
3339 mMonitoringChannels.removeAt(i);
3340 break;
3341 }
3342 }
3343}
3344
Jeff Brown519e0242010-09-15 15:18:56 -07003345ssize_t InputDispatcher::getConnectionIndexLocked(const sp<InputChannel>& inputChannel) {
Jeff Browncbee6d62012-02-03 20:11:27 -08003346 ssize_t connectionIndex = mConnectionsByFd.indexOfKey(inputChannel->getFd());
Jeff Brown2cbecea2010-08-17 15:59:26 -07003347 if (connectionIndex >= 0) {
Jeff Browncbee6d62012-02-03 20:11:27 -08003348 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
Jeff Brown2cbecea2010-08-17 15:59:26 -07003349 if (connection->inputChannel.get() == inputChannel.get()) {
3350 return connectionIndex;
3351 }
3352 }
3353
3354 return -1;
3355}
3356
Jeff Brown9c3cda02010-06-15 01:31:58 -07003357void InputDispatcher::onDispatchCycleFinishedLocked(
Jeff Brown072ec962012-02-07 14:46:57 -08003358 nsecs_t currentTime, const sp<Connection>& connection, uint32_t seq, bool handled) {
Jeff Brown3915bb82010-11-05 15:02:16 -07003359 CommandEntry* commandEntry = postCommandLocked(
3360 & InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
3361 commandEntry->connection = connection;
Jeff Brown265f1cc2012-06-11 18:01:06 -07003362 commandEntry->eventTime = currentTime;
Jeff Brown072ec962012-02-07 14:46:57 -08003363 commandEntry->seq = seq;
Jeff Brown3915bb82010-11-05 15:02:16 -07003364 commandEntry->handled = handled;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003365}
3366
Jeff Brown9c3cda02010-06-15 01:31:58 -07003367void InputDispatcher::onDispatchCycleBrokenLocked(
Jeff Brown7fbdc842010-06-17 20:52:56 -07003368 nsecs_t currentTime, const sp<Connection>& connection) {
Steve Block3762c312012-01-06 19:20:56 +00003369 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003370 connection->getInputChannelName());
3371
Jeff Brown9c3cda02010-06-15 01:31:58 -07003372 CommandEntry* commandEntry = postCommandLocked(
3373 & InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
Jeff Brown7fbdc842010-06-17 20:52:56 -07003374 commandEntry->connection = connection;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003375}
3376
Jeff Brown519e0242010-09-15 15:18:56 -07003377void InputDispatcher::onANRLocked(
Jeff Brown9302c872011-07-13 22:51:29 -07003378 nsecs_t currentTime, const sp<InputApplicationHandle>& applicationHandle,
3379 const sp<InputWindowHandle>& windowHandle,
Jeff Brown265f1cc2012-06-11 18:01:06 -07003380 nsecs_t eventTime, nsecs_t waitStartTime, const char* reason) {
Jeff Brown22aa5122012-06-17 12:01:06 -07003381 float dispatchLatency = (currentTime - eventTime) * 0.000001f;
3382 float waitDuration = (currentTime - waitStartTime) * 0.000001f;
Steve Block6215d3f2012-01-04 20:05:49 +00003383 ALOGI("Application is not responding: %s. "
Jeff Brown22aa5122012-06-17 12:01:06 -07003384 "It has been %0.1fms since event, %0.1fms since wait started. Reason: %s",
Jeff Brown9302c872011-07-13 22:51:29 -07003385 getApplicationWindowLabelLocked(applicationHandle, windowHandle).string(),
Jeff Brown22aa5122012-06-17 12:01:06 -07003386 dispatchLatency, waitDuration, reason);
3387
3388 // Capture a record of the InputDispatcher state at the time of the ANR.
3389 time_t t = time(NULL);
3390 struct tm tm;
3391 localtime_r(&t, &tm);
3392 char timestr[64];
3393 strftime(timestr, sizeof(timestr), "%F %T", &tm);
3394 mLastANRState.clear();
3395 mLastANRState.append(INDENT "ANR:\n");
3396 mLastANRState.appendFormat(INDENT2 "Time: %s\n", timestr);
3397 mLastANRState.appendFormat(INDENT2 "Window: %s\n",
3398 getApplicationWindowLabelLocked(applicationHandle, windowHandle).string());
3399 mLastANRState.appendFormat(INDENT2 "DispatchLatency: %0.1fms\n", dispatchLatency);
3400 mLastANRState.appendFormat(INDENT2 "WaitDuration: %0.1fms\n", waitDuration);
3401 mLastANRState.appendFormat(INDENT2 "Reason: %s\n", reason);
3402 dumpDispatchStateLocked(mLastANRState);
Jeff Brown519e0242010-09-15 15:18:56 -07003403
3404 CommandEntry* commandEntry = postCommandLocked(
3405 & InputDispatcher::doNotifyANRLockedInterruptible);
Jeff Brown9302c872011-07-13 22:51:29 -07003406 commandEntry->inputApplicationHandle = applicationHandle;
3407 commandEntry->inputWindowHandle = windowHandle;
Jeff Brown519e0242010-09-15 15:18:56 -07003408}
3409
Jeff Brownb88102f2010-09-08 11:49:43 -07003410void InputDispatcher::doNotifyConfigurationChangedInterruptible(
3411 CommandEntry* commandEntry) {
3412 mLock.unlock();
3413
3414 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
3415
3416 mLock.lock();
3417}
3418
Jeff Brown9c3cda02010-06-15 01:31:58 -07003419void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(
3420 CommandEntry* commandEntry) {
Jeff Brown7fbdc842010-06-17 20:52:56 -07003421 sp<Connection> connection = commandEntry->connection;
Jeff Brown9c3cda02010-06-15 01:31:58 -07003422
Jeff Brown7fbdc842010-06-17 20:52:56 -07003423 if (connection->status != Connection::STATUS_ZOMBIE) {
3424 mLock.unlock();
Jeff Brown9c3cda02010-06-15 01:31:58 -07003425
Jeff Brown928e0542011-01-10 11:17:36 -08003426 mPolicy->notifyInputChannelBroken(connection->inputWindowHandle);
Jeff Brown7fbdc842010-06-17 20:52:56 -07003427
3428 mLock.lock();
3429 }
Jeff Brown9c3cda02010-06-15 01:31:58 -07003430}
3431
Jeff Brown519e0242010-09-15 15:18:56 -07003432void InputDispatcher::doNotifyANRLockedInterruptible(
Jeff Brown9c3cda02010-06-15 01:31:58 -07003433 CommandEntry* commandEntry) {
Jeff Brown519e0242010-09-15 15:18:56 -07003434 mLock.unlock();
Jeff Brown9c3cda02010-06-15 01:31:58 -07003435
Jeff Brown519e0242010-09-15 15:18:56 -07003436 nsecs_t newTimeout = mPolicy->notifyANR(
Jeff Brown928e0542011-01-10 11:17:36 -08003437 commandEntry->inputApplicationHandle, commandEntry->inputWindowHandle);
Jeff Brown9c3cda02010-06-15 01:31:58 -07003438
Jeff Brown519e0242010-09-15 15:18:56 -07003439 mLock.lock();
Jeff Brown7fbdc842010-06-17 20:52:56 -07003440
Jeff Brown9302c872011-07-13 22:51:29 -07003441 resumeAfterTargetsNotReadyTimeoutLocked(newTimeout,
3442 commandEntry->inputWindowHandle != NULL
Jeff Browncc4f7db2011-08-30 20:34:48 -07003443 ? commandEntry->inputWindowHandle->getInputChannel() : NULL);
Jeff Brown9c3cda02010-06-15 01:31:58 -07003444}
3445
Jeff Brownb88102f2010-09-08 11:49:43 -07003446void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
3447 CommandEntry* commandEntry) {
3448 KeyEntry* entry = commandEntry->keyEntry;
Jeff Brown1f245102010-11-18 20:53:46 -08003449
3450 KeyEvent event;
3451 initializeKeyEvent(&event, entry);
Jeff Brownb88102f2010-09-08 11:49:43 -07003452
3453 mLock.unlock();
3454
Jeff Brown905805a2011-10-12 13:57:59 -07003455 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(commandEntry->inputWindowHandle,
Jeff Brown1f245102010-11-18 20:53:46 -08003456 &event, entry->policyFlags);
Jeff Brownb88102f2010-09-08 11:49:43 -07003457
3458 mLock.lock();
3459
Jeff Brown905805a2011-10-12 13:57:59 -07003460 if (delay < 0) {
3461 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
3462 } else if (!delay) {
3463 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
3464 } else {
3465 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
3466 entry->interceptKeyWakeupTime = now() + delay;
3467 }
Jeff Brownac386072011-07-20 15:19:50 -07003468 entry->release();
Jeff Brownb88102f2010-09-08 11:49:43 -07003469}
3470
Jeff Brown3915bb82010-11-05 15:02:16 -07003471void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(
3472 CommandEntry* commandEntry) {
3473 sp<Connection> connection = commandEntry->connection;
Jeff Brown265f1cc2012-06-11 18:01:06 -07003474 nsecs_t finishTime = commandEntry->eventTime;
Jeff Brown072ec962012-02-07 14:46:57 -08003475 uint32_t seq = commandEntry->seq;
Jeff Brown3915bb82010-11-05 15:02:16 -07003476 bool handled = commandEntry->handled;
3477
Jeff Brown072ec962012-02-07 14:46:57 -08003478 // Handle post-event policy actions.
3479 DispatchEntry* dispatchEntry = connection->findWaitQueueEntry(seq);
3480 if (dispatchEntry) {
Jeff Brown265f1cc2012-06-11 18:01:06 -07003481 nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
3482 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
3483 String8 msg;
Jeff Brown22aa5122012-06-17 12:01:06 -07003484 msg.appendFormat("Window '%s' spent %0.1fms processing the last input event: ",
Jeff Brown265f1cc2012-06-11 18:01:06 -07003485 connection->getWindowName(), eventDuration * 0.000001f);
3486 dispatchEntry->eventEntry->appendDescription(msg);
3487 ALOGI("%s", msg.string());
3488 }
3489
Jeff Brownd1c48a02012-02-06 19:12:47 -08003490 bool restartEvent;
Jeff Brownd1c48a02012-02-06 19:12:47 -08003491 if (dispatchEntry->eventEntry->type == EventEntry::TYPE_KEY) {
3492 KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry);
3493 restartEvent = afterKeyEventLockedInterruptible(connection,
3494 dispatchEntry, keyEntry, handled);
3495 } else if (dispatchEntry->eventEntry->type == EventEntry::TYPE_MOTION) {
3496 MotionEntry* motionEntry = static_cast<MotionEntry*>(dispatchEntry->eventEntry);
3497 restartEvent = afterMotionEventLockedInterruptible(connection,
3498 dispatchEntry, motionEntry, handled);
3499 } else {
3500 restartEvent = false;
3501 }
3502
3503 // Dequeue the event and start the next cycle.
3504 // Note that because the lock might have been released, it is possible that the
3505 // contents of the wait queue to have been drained, so we need to double-check
3506 // a few things.
Jeff Brown072ec962012-02-07 14:46:57 -08003507 if (dispatchEntry == connection->findWaitQueueEntry(seq)) {
3508 connection->waitQueue.dequeue(dispatchEntry);
Jeff Brown481c1572012-03-09 14:41:15 -08003509 traceWaitQueueLengthLocked(connection);
Jeff Brownd1c48a02012-02-06 19:12:47 -08003510 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
3511 connection->outboundQueue.enqueueAtHead(dispatchEntry);
Jeff Brown481c1572012-03-09 14:41:15 -08003512 traceOutboundQueueLengthLocked(connection);
Jeff Brownd1c48a02012-02-06 19:12:47 -08003513 } else {
3514 releaseDispatchEntryLocked(dispatchEntry);
Jeff Brown49ed71d2010-12-06 17:13:33 -08003515 }
Jeff Brown3915bb82010-11-05 15:02:16 -07003516 }
Jeff Brown3915bb82010-11-05 15:02:16 -07003517
Jeff Brownd1c48a02012-02-06 19:12:47 -08003518 // Start the next dispatch cycle for this connection.
3519 startDispatchCycleLocked(now(), connection);
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003520 }
3521}
3522
3523bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
3524 DispatchEntry* dispatchEntry, KeyEntry* keyEntry, bool handled) {
3525 if (!(keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK)) {
3526 // Get the fallback key state.
3527 // Clear it out after dispatching the UP.
3528 int32_t originalKeyCode = keyEntry->keyCode;
3529 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
3530 if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
3531 connection->inputState.removeFallbackKey(originalKeyCode);
3532 }
3533
3534 if (handled || !dispatchEntry->hasForegroundTarget()) {
3535 // If the application handles the original key for which we previously
3536 // generated a fallback or if the window is not a foreground window,
3537 // then cancel the associated fallback key, if any.
3538 if (fallbackKeyCode != -1) {
Jeff Brownfd23e3e2012-05-09 13:34:28 -07003539 // Dispatch the unhandled key to the policy with the cancel flag.
3540#if DEBUG_OUTBOUND_EVENT_DETAILS
3541 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
3542 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
3543 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
3544 keyEntry->policyFlags);
3545#endif
3546 KeyEvent event;
3547 initializeKeyEvent(&event, keyEntry);
3548 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
3549
3550 mLock.unlock();
3551
3552 mPolicy->dispatchUnhandledKey(connection->inputWindowHandle,
3553 &event, keyEntry->policyFlags, &event);
3554
3555 mLock.lock();
3556
3557 // Cancel the fallback key.
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003558 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
3559 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
3560 "application handled the original non-fallback key "
3561 "or is no longer a foreground target, "
3562 "canceling previously dispatched fallback key");
3563 options.keyCode = fallbackKeyCode;
3564 synthesizeCancelationEventsForConnectionLocked(connection, options);
3565 }
3566 connection->inputState.removeFallbackKey(originalKeyCode);
3567 }
3568 } else {
3569 // If the application did not handle a non-fallback key, first check
3570 // that we are in a good state to perform unhandled key event processing
3571 // Then ask the policy what to do with it.
3572 bool initialDown = keyEntry->action == AKEY_EVENT_ACTION_DOWN
3573 && keyEntry->repeatCount == 0;
3574 if (fallbackKeyCode == -1 && !initialDown) {
3575#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00003576 ALOGD("Unhandled key event: Skipping unhandled key event processing "
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003577 "since this is not an initial down. "
Jeff Brownfd23e3e2012-05-09 13:34:28 -07003578 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
3579 originalKeyCode, keyEntry->action, keyEntry->repeatCount,
3580 keyEntry->policyFlags);
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003581#endif
3582 return false;
3583 }
3584
3585 // Dispatch the unhandled key to the policy.
3586#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00003587 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
Jeff Brownfd23e3e2012-05-09 13:34:28 -07003588 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
3589 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
3590 keyEntry->policyFlags);
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003591#endif
3592 KeyEvent event;
3593 initializeKeyEvent(&event, keyEntry);
3594
3595 mLock.unlock();
3596
3597 bool fallback = mPolicy->dispatchUnhandledKey(connection->inputWindowHandle,
3598 &event, keyEntry->policyFlags, &event);
3599
3600 mLock.lock();
3601
3602 if (connection->status != Connection::STATUS_NORMAL) {
3603 connection->inputState.removeFallbackKey(originalKeyCode);
Jeff Brownd1c48a02012-02-06 19:12:47 -08003604 return false;
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003605 }
3606
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003607 // Latch the fallback keycode for this key on an initial down.
3608 // The fallback keycode cannot change at any other point in the lifecycle.
3609 if (initialDown) {
3610 if (fallback) {
3611 fallbackKeyCode = event.getKeyCode();
3612 } else {
3613 fallbackKeyCode = AKEYCODE_UNKNOWN;
3614 }
3615 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
3616 }
3617
Steve Blockec193de2012-01-09 18:35:44 +00003618 ALOG_ASSERT(fallbackKeyCode != -1);
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003619
3620 // Cancel the fallback key if the policy decides not to send it anymore.
3621 // We will continue to dispatch the key to the policy but we will no
3622 // longer dispatch a fallback key to the application.
3623 if (fallbackKeyCode != AKEYCODE_UNKNOWN
3624 && (!fallback || fallbackKeyCode != event.getKeyCode())) {
3625#if DEBUG_OUTBOUND_EVENT_DETAILS
3626 if (fallback) {
Steve Block5baa3a62011-12-20 16:23:08 +00003627 ALOGD("Unhandled key event: Policy requested to send key %d"
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003628 "as a fallback for %d, but on the DOWN it had requested "
3629 "to send %d instead. Fallback canceled.",
3630 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
3631 } else {
Jeff Brownfd23e3e2012-05-09 13:34:28 -07003632 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003633 "but on the DOWN it had requested to send %d. "
3634 "Fallback canceled.",
3635 originalKeyCode, fallbackKeyCode);
3636 }
3637#endif
3638
3639 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
3640 "canceling fallback, policy no longer desires it");
3641 options.keyCode = fallbackKeyCode;
3642 synthesizeCancelationEventsForConnectionLocked(connection, options);
3643
3644 fallback = false;
3645 fallbackKeyCode = AKEYCODE_UNKNOWN;
3646 if (keyEntry->action != AKEY_EVENT_ACTION_UP) {
3647 connection->inputState.setFallbackKey(originalKeyCode,
3648 fallbackKeyCode);
3649 }
3650 }
3651
3652#if DEBUG_OUTBOUND_EVENT_DETAILS
3653 {
3654 String8 msg;
3655 const KeyedVector<int32_t, int32_t>& fallbackKeys =
3656 connection->inputState.getFallbackKeys();
3657 for (size_t i = 0; i < fallbackKeys.size(); i++) {
3658 msg.appendFormat(", %d->%d", fallbackKeys.keyAt(i),
3659 fallbackKeys.valueAt(i));
3660 }
Steve Block5baa3a62011-12-20 16:23:08 +00003661 ALOGD("Unhandled key event: %d currently tracked fallback keys%s.",
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003662 fallbackKeys.size(), msg.string());
3663 }
3664#endif
3665
3666 if (fallback) {
3667 // Restart the dispatch cycle using the fallback key.
3668 keyEntry->eventTime = event.getEventTime();
3669 keyEntry->deviceId = event.getDeviceId();
3670 keyEntry->source = event.getSource();
3671 keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
3672 keyEntry->keyCode = fallbackKeyCode;
3673 keyEntry->scanCode = event.getScanCode();
3674 keyEntry->metaState = event.getMetaState();
3675 keyEntry->repeatCount = event.getRepeatCount();
3676 keyEntry->downTime = event.getDownTime();
3677 keyEntry->syntheticRepeat = false;
3678
3679#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00003680 ALOGD("Unhandled key event: Dispatching fallback key. "
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003681 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
3682 originalKeyCode, fallbackKeyCode, keyEntry->metaState);
3683#endif
Jeff Brownd1c48a02012-02-06 19:12:47 -08003684 return true; // restart the event
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003685 } else {
3686#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00003687 ALOGD("Unhandled key event: No fallback key.");
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003688#endif
3689 }
3690 }
3691 }
3692 return false;
3693}
3694
3695bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
3696 DispatchEntry* dispatchEntry, MotionEntry* motionEntry, bool handled) {
3697 return false;
Jeff Brown3915bb82010-11-05 15:02:16 -07003698}
3699
Jeff Brownb88102f2010-09-08 11:49:43 -07003700void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
3701 mLock.unlock();
3702
Jeff Brown01ce2e92010-09-26 22:20:12 -07003703 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
Jeff Brownb88102f2010-09-08 11:49:43 -07003704
3705 mLock.lock();
3706}
3707
Jeff Brown3915bb82010-11-05 15:02:16 -07003708void InputDispatcher::initializeKeyEvent(KeyEvent* event, const KeyEntry* entry) {
3709 event->initialize(entry->deviceId, entry->source, entry->action, entry->flags,
3710 entry->keyCode, entry->scanCode, entry->metaState, entry->repeatCount,
3711 entry->downTime, entry->eventTime);
3712}
3713
Jeff Brown519e0242010-09-15 15:18:56 -07003714void InputDispatcher::updateDispatchStatisticsLocked(nsecs_t currentTime, const EventEntry* entry,
3715 int32_t injectionResult, nsecs_t timeSpentWaitingForApplication) {
3716 // TODO Write some statistics about how long we spend waiting.
Jeff Brownb88102f2010-09-08 11:49:43 -07003717}
3718
Jeff Brown481c1572012-03-09 14:41:15 -08003719void InputDispatcher::traceInboundQueueLengthLocked() {
3720 if (ATRACE_ENABLED()) {
3721 ATRACE_INT("iq", mInboundQueue.count());
3722 }
3723}
3724
3725void InputDispatcher::traceOutboundQueueLengthLocked(const sp<Connection>& connection) {
3726 if (ATRACE_ENABLED()) {
3727 char counterName[40];
3728 snprintf(counterName, sizeof(counterName), "oq:%s", connection->getWindowName());
3729 ATRACE_INT(counterName, connection->outboundQueue.count());
3730 }
3731}
3732
3733void InputDispatcher::traceWaitQueueLengthLocked(const sp<Connection>& connection) {
3734 if (ATRACE_ENABLED()) {
3735 char counterName[40];
3736 snprintf(counterName, sizeof(counterName), "wq:%s", connection->getWindowName());
3737 ATRACE_INT(counterName, connection->waitQueue.count());
3738 }
3739}
3740
Jeff Brownb88102f2010-09-08 11:49:43 -07003741void InputDispatcher::dump(String8& dump) {
Jeff Brown89ef0722011-08-10 16:25:21 -07003742 AutoMutex _l(mLock);
3743
Jeff Brownf2f487182010-10-01 17:46:21 -07003744 dump.append("Input Dispatcher State:\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003745 dumpDispatchStateLocked(dump);
Jeff Brown214eaf42011-05-26 19:17:02 -07003746
Jeff Brown22aa5122012-06-17 12:01:06 -07003747 if (!mLastANRState.isEmpty()) {
3748 dump.append("\nInput Dispatcher State at time of last ANR:\n");
3749 dump.append(mLastANRState);
3750 }
Jeff Brownb88102f2010-09-08 11:49:43 -07003751}
3752
Jeff Brown89ef0722011-08-10 16:25:21 -07003753void InputDispatcher::monitor() {
3754 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
3755 mLock.lock();
Jeff Brown112b5f52012-01-27 17:32:06 -08003756 mLooper->wake();
3757 mDispatcherIsAliveCondition.wait(mLock);
Jeff Brown89ef0722011-08-10 16:25:21 -07003758 mLock.unlock();
3759}
3760
Jeff Brown9c3cda02010-06-15 01:31:58 -07003761
Jeff Brown519e0242010-09-15 15:18:56 -07003762// --- InputDispatcher::Queue ---
3763
3764template <typename T>
3765uint32_t InputDispatcher::Queue<T>::count() const {
3766 uint32_t result = 0;
Jeff Brownac386072011-07-20 15:19:50 -07003767 for (const T* entry = head; entry; entry = entry->next) {
Jeff Brown519e0242010-09-15 15:18:56 -07003768 result += 1;
3769 }
3770 return result;
3771}
3772
3773
Jeff Brownac386072011-07-20 15:19:50 -07003774// --- InputDispatcher::InjectionState ---
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003775
Jeff Brownac386072011-07-20 15:19:50 -07003776InputDispatcher::InjectionState::InjectionState(int32_t injectorPid, int32_t injectorUid) :
3777 refCount(1),
3778 injectorPid(injectorPid), injectorUid(injectorUid),
3779 injectionResult(INPUT_EVENT_INJECTION_PENDING), injectionIsAsync(false),
3780 pendingForegroundDispatches(0) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003781}
3782
Jeff Brownac386072011-07-20 15:19:50 -07003783InputDispatcher::InjectionState::~InjectionState() {
Jeff Brown01ce2e92010-09-26 22:20:12 -07003784}
3785
Jeff Brownac386072011-07-20 15:19:50 -07003786void InputDispatcher::InjectionState::release() {
3787 refCount -= 1;
3788 if (refCount == 0) {
3789 delete this;
3790 } else {
Steve Blockec193de2012-01-09 18:35:44 +00003791 ALOG_ASSERT(refCount > 0);
Jeff Brown01ce2e92010-09-26 22:20:12 -07003792 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07003793}
3794
Jeff Brownac386072011-07-20 15:19:50 -07003795
3796// --- InputDispatcher::EventEntry ---
3797
3798InputDispatcher::EventEntry::EventEntry(int32_t type, nsecs_t eventTime, uint32_t policyFlags) :
3799 refCount(1), type(type), eventTime(eventTime), policyFlags(policyFlags),
3800 injectionState(NULL), dispatchInProgress(false) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003801}
3802
Jeff Brownac386072011-07-20 15:19:50 -07003803InputDispatcher::EventEntry::~EventEntry() {
3804 releaseInjectionState();
3805}
3806
3807void InputDispatcher::EventEntry::release() {
3808 refCount -= 1;
3809 if (refCount == 0) {
3810 delete this;
3811 } else {
Steve Blockec193de2012-01-09 18:35:44 +00003812 ALOG_ASSERT(refCount > 0);
Jeff Brownac386072011-07-20 15:19:50 -07003813 }
3814}
3815
3816void InputDispatcher::EventEntry::releaseInjectionState() {
3817 if (injectionState) {
3818 injectionState->release();
3819 injectionState = NULL;
3820 }
3821}
3822
3823
3824// --- InputDispatcher::ConfigurationChangedEntry ---
3825
3826InputDispatcher::ConfigurationChangedEntry::ConfigurationChangedEntry(nsecs_t eventTime) :
3827 EventEntry(TYPE_CONFIGURATION_CHANGED, eventTime, 0) {
3828}
3829
3830InputDispatcher::ConfigurationChangedEntry::~ConfigurationChangedEntry() {
3831}
3832
Jeff Brown265f1cc2012-06-11 18:01:06 -07003833void InputDispatcher::ConfigurationChangedEntry::appendDescription(String8& msg) const {
Jeff Brown6876f322013-08-07 16:46:50 -07003834 msg.append("ConfigurationChangedEvent(), policyFlags=0x%08x",
3835 policyFlags);
Jeff Brown265f1cc2012-06-11 18:01:06 -07003836}
3837
Jeff Brownac386072011-07-20 15:19:50 -07003838
Jeff Brown65fd2512011-08-18 11:20:58 -07003839// --- InputDispatcher::DeviceResetEntry ---
3840
3841InputDispatcher::DeviceResetEntry::DeviceResetEntry(nsecs_t eventTime, int32_t deviceId) :
3842 EventEntry(TYPE_DEVICE_RESET, eventTime, 0),
3843 deviceId(deviceId) {
3844}
3845
3846InputDispatcher::DeviceResetEntry::~DeviceResetEntry() {
3847}
3848
Jeff Brown265f1cc2012-06-11 18:01:06 -07003849void InputDispatcher::DeviceResetEntry::appendDescription(String8& msg) const {
Jeff Brown6876f322013-08-07 16:46:50 -07003850 msg.appendFormat("DeviceResetEvent(deviceId=%d), policyFlags=0x%08x",
3851 deviceId, policyFlags);
Jeff Brown265f1cc2012-06-11 18:01:06 -07003852}
3853
Jeff Brown65fd2512011-08-18 11:20:58 -07003854
Jeff Brownac386072011-07-20 15:19:50 -07003855// --- InputDispatcher::KeyEntry ---
3856
3857InputDispatcher::KeyEntry::KeyEntry(nsecs_t eventTime,
Jeff Brown58a2da82011-01-25 16:02:22 -08003858 int32_t deviceId, uint32_t source, uint32_t policyFlags, int32_t action,
Jeff Brown7fbdc842010-06-17 20:52:56 -07003859 int32_t flags, int32_t keyCode, int32_t scanCode, int32_t metaState,
Jeff Brownac386072011-07-20 15:19:50 -07003860 int32_t repeatCount, nsecs_t downTime) :
3861 EventEntry(TYPE_KEY, eventTime, policyFlags),
3862 deviceId(deviceId), source(source), action(action), flags(flags),
3863 keyCode(keyCode), scanCode(scanCode), metaState(metaState),
3864 repeatCount(repeatCount), downTime(downTime),
Jeff Brown905805a2011-10-12 13:57:59 -07003865 syntheticRepeat(false), interceptKeyResult(KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN),
3866 interceptKeyWakeupTime(0) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003867}
3868
Jeff Brownac386072011-07-20 15:19:50 -07003869InputDispatcher::KeyEntry::~KeyEntry() {
3870}
Jeff Brown7fbdc842010-06-17 20:52:56 -07003871
Jeff Brown265f1cc2012-06-11 18:01:06 -07003872void InputDispatcher::KeyEntry::appendDescription(String8& msg) const {
Jeff Brown6876f322013-08-07 16:46:50 -07003873 msg.appendFormat("KeyEvent(deviceId=%d, source=0x%08x, action=%d, "
3874 "flags=0x%08x, keyCode=%d, scanCode=%d, metaState=0x%08x, "
3875 "repeatCount=%d), policyFlags=0x%08x",
3876 deviceId, source, action, flags, keyCode, scanCode, metaState,
3877 repeatCount, policyFlags);
Jeff Brown265f1cc2012-06-11 18:01:06 -07003878}
3879
Jeff Brownac386072011-07-20 15:19:50 -07003880void InputDispatcher::KeyEntry::recycle() {
3881 releaseInjectionState();
3882
3883 dispatchInProgress = false;
3884 syntheticRepeat = false;
3885 interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
Jeff Brown905805a2011-10-12 13:57:59 -07003886 interceptKeyWakeupTime = 0;
Jeff Brownac386072011-07-20 15:19:50 -07003887}
3888
3889
Jeff Brownae9fc032010-08-18 15:51:08 -07003890// --- InputDispatcher::MotionEntry ---
3891
Jeff Brownac386072011-07-20 15:19:50 -07003892InputDispatcher::MotionEntry::MotionEntry(nsecs_t eventTime,
3893 int32_t deviceId, uint32_t source, uint32_t policyFlags, int32_t action, int32_t flags,
3894 int32_t metaState, int32_t buttonState,
3895 int32_t edgeFlags, float xPrecision, float yPrecision,
Jeff Brown83d616a2012-09-09 20:33:43 -07003896 nsecs_t downTime, int32_t displayId, uint32_t pointerCount,
Jeff Brownac386072011-07-20 15:19:50 -07003897 const PointerProperties* pointerProperties, const PointerCoords* pointerCoords) :
3898 EventEntry(TYPE_MOTION, eventTime, policyFlags),
Jeff Brown3241b6b2012-02-03 15:08:02 -08003899 eventTime(eventTime),
Jeff Brownac386072011-07-20 15:19:50 -07003900 deviceId(deviceId), source(source), action(action), flags(flags),
3901 metaState(metaState), buttonState(buttonState), edgeFlags(edgeFlags),
3902 xPrecision(xPrecision), yPrecision(yPrecision),
Jeff Brown83d616a2012-09-09 20:33:43 -07003903 downTime(downTime), displayId(displayId), pointerCount(pointerCount) {
Jeff Brownac386072011-07-20 15:19:50 -07003904 for (uint32_t i = 0; i < pointerCount; i++) {
3905 this->pointerProperties[i].copyFrom(pointerProperties[i]);
Jeff Brown3241b6b2012-02-03 15:08:02 -08003906 this->pointerCoords[i].copyFrom(pointerCoords[i]);
Jeff Brownac386072011-07-20 15:19:50 -07003907 }
3908}
3909
3910InputDispatcher::MotionEntry::~MotionEntry() {
Jeff Brownac386072011-07-20 15:19:50 -07003911}
3912
Jeff Brown265f1cc2012-06-11 18:01:06 -07003913void InputDispatcher::MotionEntry::appendDescription(String8& msg) const {
Jeff Brown6876f322013-08-07 16:46:50 -07003914 msg.appendFormat("MotionEvent(deviceId=%d, source=0x%08x, action=%d, "
3915 "flags=0x%08x, metaState=0x%08x, buttonState=0x%08x, edgeFlags=0x%08x, "
3916 "xPrecision=%.1f, yPrecision=%.1f, displayId=%d, pointers=[",
3917 deviceId, source, action, flags, metaState, buttonState, edgeFlags,
3918 xPrecision, yPrecision, displayId);
3919 for (uint32_t i = 0; i < pointerCount; i++) {
3920 if (i) {
3921 msg.append(", ");
3922 }
3923 msg.appendFormat("%d: (%.1f, %.1f)", pointerProperties[i].id,
3924 pointerCoords[i].getX(), pointerCoords[i].getY());
3925 }
3926 msg.appendFormat("]), policyFlags=0x%08x", policyFlags);
Jeff Brown265f1cc2012-06-11 18:01:06 -07003927}
3928
Jeff Brownac386072011-07-20 15:19:50 -07003929
3930// --- InputDispatcher::DispatchEntry ---
3931
Jeff Brown072ec962012-02-07 14:46:57 -08003932volatile int32_t InputDispatcher::DispatchEntry::sNextSeqAtomic;
3933
Jeff Brownac386072011-07-20 15:19:50 -07003934InputDispatcher::DispatchEntry::DispatchEntry(EventEntry* eventEntry,
3935 int32_t targetFlags, float xOffset, float yOffset, float scaleFactor) :
Jeff Brown072ec962012-02-07 14:46:57 -08003936 seq(nextSeq()),
Jeff Brownac386072011-07-20 15:19:50 -07003937 eventEntry(eventEntry), targetFlags(targetFlags),
3938 xOffset(xOffset), yOffset(yOffset), scaleFactor(scaleFactor),
Jeff Brown265f1cc2012-06-11 18:01:06 -07003939 deliveryTime(0), resolvedAction(0), resolvedFlags(0) {
Jeff Brownac386072011-07-20 15:19:50 -07003940 eventEntry->refCount += 1;
3941}
3942
3943InputDispatcher::DispatchEntry::~DispatchEntry() {
3944 eventEntry->release();
3945}
3946
Jeff Brown072ec962012-02-07 14:46:57 -08003947uint32_t InputDispatcher::DispatchEntry::nextSeq() {
3948 // Sequence number 0 is reserved and will never be returned.
3949 uint32_t seq;
3950 do {
3951 seq = android_atomic_inc(&sNextSeqAtomic);
3952 } while (!seq);
3953 return seq;
3954}
3955
Jeff Brownb88102f2010-09-08 11:49:43 -07003956
3957// --- InputDispatcher::InputState ---
3958
Jeff Brownb6997262010-10-08 22:31:17 -07003959InputDispatcher::InputState::InputState() {
Jeff Brownb88102f2010-09-08 11:49:43 -07003960}
3961
3962InputDispatcher::InputState::~InputState() {
3963}
3964
3965bool InputDispatcher::InputState::isNeutral() const {
3966 return mKeyMementos.isEmpty() && mMotionMementos.isEmpty();
3967}
3968
Jeff Brown83d616a2012-09-09 20:33:43 -07003969bool InputDispatcher::InputState::isHovering(int32_t deviceId, uint32_t source,
3970 int32_t displayId) const {
Jeff Brown81346812011-06-28 20:08:48 -07003971 for (size_t i = 0; i < mMotionMementos.size(); i++) {
3972 const MotionMemento& memento = mMotionMementos.itemAt(i);
3973 if (memento.deviceId == deviceId
3974 && memento.source == source
Jeff Brown83d616a2012-09-09 20:33:43 -07003975 && memento.displayId == displayId
Jeff Brown81346812011-06-28 20:08:48 -07003976 && memento.hovering) {
3977 return true;
3978 }
3979 }
3980 return false;
3981}
Jeff Brownb88102f2010-09-08 11:49:43 -07003982
Jeff Brown81346812011-06-28 20:08:48 -07003983bool InputDispatcher::InputState::trackKey(const KeyEntry* entry,
3984 int32_t action, int32_t flags) {
3985 switch (action) {
3986 case AKEY_EVENT_ACTION_UP: {
3987 if (entry->flags & AKEY_EVENT_FLAG_FALLBACK) {
3988 for (size_t i = 0; i < mFallbackKeys.size(); ) {
3989 if (mFallbackKeys.valueAt(i) == entry->keyCode) {
3990 mFallbackKeys.removeItemsAt(i);
3991 } else {
3992 i += 1;
3993 }
3994 }
3995 }
3996 ssize_t index = findKeyMemento(entry);
3997 if (index >= 0) {
3998 mKeyMementos.removeAt(index);
3999 return true;
4000 }
Jeff Brown68b909d2011-12-07 16:36:01 -08004001 /* FIXME: We can't just drop the key up event because that prevents creating
4002 * popup windows that are automatically shown when a key is held and then
4003 * dismissed when the key is released. The problem is that the popup will
4004 * not have received the original key down, so the key up will be considered
4005 * to be inconsistent with its observed state. We could perhaps handle this
4006 * by synthesizing a key down but that will cause other problems.
4007 *
4008 * So for now, allow inconsistent key up events to be dispatched.
4009 *
Jeff Brown81346812011-06-28 20:08:48 -07004010#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00004011 ALOGD("Dropping inconsistent key up event: deviceId=%d, source=%08x, "
Jeff Brown81346812011-06-28 20:08:48 -07004012 "keyCode=%d, scanCode=%d",
4013 entry->deviceId, entry->source, entry->keyCode, entry->scanCode);
4014#endif
4015 return false;
Jeff Brown68b909d2011-12-07 16:36:01 -08004016 */
4017 return true;
Jeff Brown81346812011-06-28 20:08:48 -07004018 }
4019
4020 case AKEY_EVENT_ACTION_DOWN: {
4021 ssize_t index = findKeyMemento(entry);
4022 if (index >= 0) {
4023 mKeyMementos.removeAt(index);
4024 }
4025 addKeyMemento(entry, flags);
4026 return true;
4027 }
4028
4029 default:
4030 return true;
Jeff Brownb88102f2010-09-08 11:49:43 -07004031 }
4032}
4033
Jeff Brown81346812011-06-28 20:08:48 -07004034bool InputDispatcher::InputState::trackMotion(const MotionEntry* entry,
4035 int32_t action, int32_t flags) {
4036 int32_t actionMasked = action & AMOTION_EVENT_ACTION_MASK;
4037 switch (actionMasked) {
4038 case AMOTION_EVENT_ACTION_UP:
4039 case AMOTION_EVENT_ACTION_CANCEL: {
4040 ssize_t index = findMotionMemento(entry, false /*hovering*/);
4041 if (index >= 0) {
4042 mMotionMementos.removeAt(index);
4043 return true;
Jeff Brownda3d5a92011-03-29 15:11:34 -07004044 }
Jeff Brown81346812011-06-28 20:08:48 -07004045#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00004046 ALOGD("Dropping inconsistent motion up or cancel event: deviceId=%d, source=%08x, "
Jeff Brown81346812011-06-28 20:08:48 -07004047 "actionMasked=%d",
4048 entry->deviceId, entry->source, actionMasked);
4049#endif
4050 return false;
Jeff Brownda3d5a92011-03-29 15:11:34 -07004051 }
4052
Jeff Brown81346812011-06-28 20:08:48 -07004053 case AMOTION_EVENT_ACTION_DOWN: {
4054 ssize_t index = findMotionMemento(entry, false /*hovering*/);
4055 if (index >= 0) {
4056 mMotionMementos.removeAt(index);
4057 }
4058 addMotionMemento(entry, flags, false /*hovering*/);
4059 return true;
4060 }
4061
4062 case AMOTION_EVENT_ACTION_POINTER_UP:
4063 case AMOTION_EVENT_ACTION_POINTER_DOWN:
4064 case AMOTION_EVENT_ACTION_MOVE: {
4065 ssize_t index = findMotionMemento(entry, false /*hovering*/);
4066 if (index >= 0) {
4067 MotionMemento& memento = mMotionMementos.editItemAt(index);
4068 memento.setPointers(entry);
4069 return true;
4070 }
Jeff Brown2e45fb62011-06-29 21:19:05 -07004071 if (actionMasked == AMOTION_EVENT_ACTION_MOVE
4072 && (entry->source & (AINPUT_SOURCE_CLASS_JOYSTICK
4073 | AINPUT_SOURCE_CLASS_NAVIGATION))) {
4074 // Joysticks and trackballs can send MOVE events without corresponding DOWN or UP.
4075 return true;
4076 }
Jeff Brown81346812011-06-28 20:08:48 -07004077#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00004078 ALOGD("Dropping inconsistent motion pointer up/down or move event: "
Jeff Brown81346812011-06-28 20:08:48 -07004079 "deviceId=%d, source=%08x, actionMasked=%d",
4080 entry->deviceId, entry->source, actionMasked);
4081#endif
4082 return false;
4083 }
4084
4085 case AMOTION_EVENT_ACTION_HOVER_EXIT: {
4086 ssize_t index = findMotionMemento(entry, true /*hovering*/);
4087 if (index >= 0) {
4088 mMotionMementos.removeAt(index);
4089 return true;
4090 }
4091#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00004092 ALOGD("Dropping inconsistent motion hover exit event: deviceId=%d, source=%08x",
Jeff Brown81346812011-06-28 20:08:48 -07004093 entry->deviceId, entry->source);
4094#endif
4095 return false;
4096 }
4097
4098 case AMOTION_EVENT_ACTION_HOVER_ENTER:
4099 case AMOTION_EVENT_ACTION_HOVER_MOVE: {
4100 ssize_t index = findMotionMemento(entry, true /*hovering*/);
4101 if (index >= 0) {
4102 mMotionMementos.removeAt(index);
4103 }
4104 addMotionMemento(entry, flags, true /*hovering*/);
4105 return true;
4106 }
4107
4108 default:
4109 return true;
4110 }
4111}
4112
4113ssize_t InputDispatcher::InputState::findKeyMemento(const KeyEntry* entry) const {
Jeff Brownb88102f2010-09-08 11:49:43 -07004114 for (size_t i = 0; i < mKeyMementos.size(); i++) {
Jeff Brown81346812011-06-28 20:08:48 -07004115 const KeyMemento& memento = mKeyMementos.itemAt(i);
Jeff Brownb88102f2010-09-08 11:49:43 -07004116 if (memento.deviceId == entry->deviceId
4117 && memento.source == entry->source
4118 && memento.keyCode == entry->keyCode
4119 && memento.scanCode == entry->scanCode) {
Jeff Brown81346812011-06-28 20:08:48 -07004120 return i;
Jeff Brownb88102f2010-09-08 11:49:43 -07004121 }
4122 }
Jeff Brown81346812011-06-28 20:08:48 -07004123 return -1;
Jeff Brownb88102f2010-09-08 11:49:43 -07004124}
4125
Jeff Brown81346812011-06-28 20:08:48 -07004126ssize_t InputDispatcher::InputState::findMotionMemento(const MotionEntry* entry,
4127 bool hovering) const {
Jeff Brownb88102f2010-09-08 11:49:43 -07004128 for (size_t i = 0; i < mMotionMementos.size(); i++) {
Jeff Brown81346812011-06-28 20:08:48 -07004129 const MotionMemento& memento = mMotionMementos.itemAt(i);
Jeff Brownb88102f2010-09-08 11:49:43 -07004130 if (memento.deviceId == entry->deviceId
Jeff Brown81346812011-06-28 20:08:48 -07004131 && memento.source == entry->source
Jeff Brown83d616a2012-09-09 20:33:43 -07004132 && memento.displayId == entry->displayId
Jeff Brown81346812011-06-28 20:08:48 -07004133 && memento.hovering == hovering) {
4134 return i;
Jeff Brownb88102f2010-09-08 11:49:43 -07004135 }
4136 }
Jeff Brown81346812011-06-28 20:08:48 -07004137 return -1;
4138}
Jeff Brownb88102f2010-09-08 11:49:43 -07004139
Jeff Brown81346812011-06-28 20:08:48 -07004140void InputDispatcher::InputState::addKeyMemento(const KeyEntry* entry, int32_t flags) {
4141 mKeyMementos.push();
4142 KeyMemento& memento = mKeyMementos.editTop();
4143 memento.deviceId = entry->deviceId;
4144 memento.source = entry->source;
4145 memento.keyCode = entry->keyCode;
4146 memento.scanCode = entry->scanCode;
Jeff Brownfd23e3e2012-05-09 13:34:28 -07004147 memento.metaState = entry->metaState;
Jeff Brown81346812011-06-28 20:08:48 -07004148 memento.flags = flags;
4149 memento.downTime = entry->downTime;
Jeff Brownfd23e3e2012-05-09 13:34:28 -07004150 memento.policyFlags = entry->policyFlags;
Jeff Brown81346812011-06-28 20:08:48 -07004151}
4152
4153void InputDispatcher::InputState::addMotionMemento(const MotionEntry* entry,
4154 int32_t flags, bool hovering) {
4155 mMotionMementos.push();
4156 MotionMemento& memento = mMotionMementos.editTop();
4157 memento.deviceId = entry->deviceId;
4158 memento.source = entry->source;
4159 memento.flags = flags;
4160 memento.xPrecision = entry->xPrecision;
4161 memento.yPrecision = entry->yPrecision;
4162 memento.downTime = entry->downTime;
Jeff Brown83d616a2012-09-09 20:33:43 -07004163 memento.displayId = entry->displayId;
Jeff Brown81346812011-06-28 20:08:48 -07004164 memento.setPointers(entry);
4165 memento.hovering = hovering;
Jeff Brownfd23e3e2012-05-09 13:34:28 -07004166 memento.policyFlags = entry->policyFlags;
Jeff Brownb88102f2010-09-08 11:49:43 -07004167}
4168
4169void InputDispatcher::InputState::MotionMemento::setPointers(const MotionEntry* entry) {
4170 pointerCount = entry->pointerCount;
4171 for (uint32_t i = 0; i < entry->pointerCount; i++) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07004172 pointerProperties[i].copyFrom(entry->pointerProperties[i]);
Jeff Brown3241b6b2012-02-03 15:08:02 -08004173 pointerCoords[i].copyFrom(entry->pointerCoords[i]);
Jeff Brownb88102f2010-09-08 11:49:43 -07004174 }
4175}
4176
Jeff Brownb6997262010-10-08 22:31:17 -07004177void InputDispatcher::InputState::synthesizeCancelationEvents(nsecs_t currentTime,
Jeff Brownac386072011-07-20 15:19:50 -07004178 Vector<EventEntry*>& outEvents, const CancelationOptions& options) {
Jeff Brown81346812011-06-28 20:08:48 -07004179 for (size_t i = 0; i < mKeyMementos.size(); i++) {
Jeff Brownb88102f2010-09-08 11:49:43 -07004180 const KeyMemento& memento = mKeyMementos.itemAt(i);
Jeff Brown49ed71d2010-12-06 17:13:33 -08004181 if (shouldCancelKey(memento, options)) {
Jeff Brownac386072011-07-20 15:19:50 -07004182 outEvents.push(new KeyEntry(currentTime,
Jeff Brownfd23e3e2012-05-09 13:34:28 -07004183 memento.deviceId, memento.source, memento.policyFlags,
Jeff Brown49ed71d2010-12-06 17:13:33 -08004184 AKEY_EVENT_ACTION_UP, memento.flags | AKEY_EVENT_FLAG_CANCELED,
Jeff Brownfd23e3e2012-05-09 13:34:28 -07004185 memento.keyCode, memento.scanCode, memento.metaState, 0, memento.downTime));
Jeff Brownb6997262010-10-08 22:31:17 -07004186 }
Jeff Brownb88102f2010-09-08 11:49:43 -07004187 }
4188
Jeff Brown81346812011-06-28 20:08:48 -07004189 for (size_t i = 0; i < mMotionMementos.size(); i++) {
Jeff Brownb88102f2010-09-08 11:49:43 -07004190 const MotionMemento& memento = mMotionMementos.itemAt(i);
Jeff Brown49ed71d2010-12-06 17:13:33 -08004191 if (shouldCancelMotion(memento, options)) {
Jeff Brownac386072011-07-20 15:19:50 -07004192 outEvents.push(new MotionEntry(currentTime,
Jeff Brownfd23e3e2012-05-09 13:34:28 -07004193 memento.deviceId, memento.source, memento.policyFlags,
Jeff Browna032cc02011-03-07 16:56:21 -08004194 memento.hovering
4195 ? AMOTION_EVENT_ACTION_HOVER_EXIT
4196 : AMOTION_EVENT_ACTION_CANCEL,
Jeff Brown81346812011-06-28 20:08:48 -07004197 memento.flags, 0, 0, 0,
Jeff Brownb6997262010-10-08 22:31:17 -07004198 memento.xPrecision, memento.yPrecision, memento.downTime,
Jeff Brown83d616a2012-09-09 20:33:43 -07004199 memento.displayId,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07004200 memento.pointerCount, memento.pointerProperties, memento.pointerCoords));
Jeff Brownb6997262010-10-08 22:31:17 -07004201 }
Jeff Brownb88102f2010-09-08 11:49:43 -07004202 }
4203}
4204
4205void InputDispatcher::InputState::clear() {
4206 mKeyMementos.clear();
4207 mMotionMementos.clear();
Jeff Brownda3d5a92011-03-29 15:11:34 -07004208 mFallbackKeys.clear();
Jeff Brownb6997262010-10-08 22:31:17 -07004209}
4210
Jeff Brown9c9f1a32010-10-11 18:32:20 -07004211void InputDispatcher::InputState::copyPointerStateTo(InputState& other) const {
4212 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4213 const MotionMemento& memento = mMotionMementos.itemAt(i);
4214 if (memento.source & AINPUT_SOURCE_CLASS_POINTER) {
4215 for (size_t j = 0; j < other.mMotionMementos.size(); ) {
4216 const MotionMemento& otherMemento = other.mMotionMementos.itemAt(j);
4217 if (memento.deviceId == otherMemento.deviceId
Jeff Brown83d616a2012-09-09 20:33:43 -07004218 && memento.source == otherMemento.source
4219 && memento.displayId == otherMemento.displayId) {
Jeff Brown9c9f1a32010-10-11 18:32:20 -07004220 other.mMotionMementos.removeAt(j);
4221 } else {
4222 j += 1;
4223 }
4224 }
4225 other.mMotionMementos.push(memento);
4226 }
4227 }
4228}
4229
Jeff Brownda3d5a92011-03-29 15:11:34 -07004230int32_t InputDispatcher::InputState::getFallbackKey(int32_t originalKeyCode) {
4231 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
4232 return index >= 0 ? mFallbackKeys.valueAt(index) : -1;
4233}
4234
4235void InputDispatcher::InputState::setFallbackKey(int32_t originalKeyCode,
4236 int32_t fallbackKeyCode) {
4237 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
4238 if (index >= 0) {
4239 mFallbackKeys.replaceValueAt(index, fallbackKeyCode);
4240 } else {
4241 mFallbackKeys.add(originalKeyCode, fallbackKeyCode);
4242 }
4243}
4244
4245void InputDispatcher::InputState::removeFallbackKey(int32_t originalKeyCode) {
4246 mFallbackKeys.removeItem(originalKeyCode);
4247}
4248
Jeff Brown49ed71d2010-12-06 17:13:33 -08004249bool InputDispatcher::InputState::shouldCancelKey(const KeyMemento& memento,
Jeff Brownda3d5a92011-03-29 15:11:34 -07004250 const CancelationOptions& options) {
4251 if (options.keyCode != -1 && memento.keyCode != options.keyCode) {
4252 return false;
4253 }
4254
Jeff Brown65fd2512011-08-18 11:20:58 -07004255 if (options.deviceId != -1 && memento.deviceId != options.deviceId) {
4256 return false;
4257 }
4258
Jeff Brownda3d5a92011-03-29 15:11:34 -07004259 switch (options.mode) {
4260 case CancelationOptions::CANCEL_ALL_EVENTS:
4261 case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
Jeff Brownb6997262010-10-08 22:31:17 -07004262 return true;
Jeff Brownda3d5a92011-03-29 15:11:34 -07004263 case CancelationOptions::CANCEL_FALLBACK_EVENTS:
Jeff Brown49ed71d2010-12-06 17:13:33 -08004264 return memento.flags & AKEY_EVENT_FLAG_FALLBACK;
4265 default:
4266 return false;
4267 }
4268}
4269
4270bool InputDispatcher::InputState::shouldCancelMotion(const MotionMemento& memento,
Jeff Brownda3d5a92011-03-29 15:11:34 -07004271 const CancelationOptions& options) {
Jeff Brown65fd2512011-08-18 11:20:58 -07004272 if (options.deviceId != -1 && memento.deviceId != options.deviceId) {
4273 return false;
4274 }
4275
Jeff Brownda3d5a92011-03-29 15:11:34 -07004276 switch (options.mode) {
4277 case CancelationOptions::CANCEL_ALL_EVENTS:
Jeff Brown49ed71d2010-12-06 17:13:33 -08004278 return true;
Jeff Brownda3d5a92011-03-29 15:11:34 -07004279 case CancelationOptions::CANCEL_POINTER_EVENTS:
Jeff Brown49ed71d2010-12-06 17:13:33 -08004280 return memento.source & AINPUT_SOURCE_CLASS_POINTER;
Jeff Brownda3d5a92011-03-29 15:11:34 -07004281 case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
Jeff Brown49ed71d2010-12-06 17:13:33 -08004282 return !(memento.source & AINPUT_SOURCE_CLASS_POINTER);
4283 default:
4284 return false;
Jeff Brownb6997262010-10-08 22:31:17 -07004285 }
Jeff Brownb88102f2010-09-08 11:49:43 -07004286}
4287
4288
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004289// --- InputDispatcher::Connection ---
4290
Jeff Brown928e0542011-01-10 11:17:36 -08004291InputDispatcher::Connection::Connection(const sp<InputChannel>& inputChannel,
Jeff Browncc4f7db2011-08-30 20:34:48 -07004292 const sp<InputWindowHandle>& inputWindowHandle, bool monitor) :
Jeff Brown928e0542011-01-10 11:17:36 -08004293 status(STATUS_NORMAL), inputChannel(inputChannel), inputWindowHandle(inputWindowHandle),
Jeff Browncc4f7db2011-08-30 20:34:48 -07004294 monitor(monitor),
Jeff Brownd1c48a02012-02-06 19:12:47 -08004295 inputPublisher(inputChannel), inputPublisherBlocked(false) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004296}
4297
4298InputDispatcher::Connection::~Connection() {
4299}
4300
Jeff Brown481c1572012-03-09 14:41:15 -08004301const char* InputDispatcher::Connection::getWindowName() const {
4302 if (inputWindowHandle != NULL) {
4303 return inputWindowHandle->getName().string();
4304 }
4305 if (monitor) {
4306 return "monitor";
4307 }
4308 return "?";
4309}
4310
Jeff Brown9c3cda02010-06-15 01:31:58 -07004311const char* InputDispatcher::Connection::getStatusLabel() const {
4312 switch (status) {
4313 case STATUS_NORMAL:
4314 return "NORMAL";
4315
4316 case STATUS_BROKEN:
4317 return "BROKEN";
4318
Jeff Brown9c3cda02010-06-15 01:31:58 -07004319 case STATUS_ZOMBIE:
4320 return "ZOMBIE";
4321
4322 default:
4323 return "UNKNOWN";
4324 }
4325}
4326
Jeff Brown072ec962012-02-07 14:46:57 -08004327InputDispatcher::DispatchEntry* InputDispatcher::Connection::findWaitQueueEntry(uint32_t seq) {
4328 for (DispatchEntry* entry = waitQueue.head; entry != NULL; entry = entry->next) {
4329 if (entry->seq == seq) {
4330 return entry;
4331 }
4332 }
4333 return NULL;
4334}
4335
Jeff Brownb88102f2010-09-08 11:49:43 -07004336
Jeff Brown9c3cda02010-06-15 01:31:58 -07004337// --- InputDispatcher::CommandEntry ---
4338
Jeff Brownac386072011-07-20 15:19:50 -07004339InputDispatcher::CommandEntry::CommandEntry(Command command) :
Jeff Brown072ec962012-02-07 14:46:57 -08004340 command(command), eventTime(0), keyEntry(NULL), userActivityEventType(0),
4341 seq(0), handled(false) {
Jeff Brown9c3cda02010-06-15 01:31:58 -07004342}
4343
4344InputDispatcher::CommandEntry::~CommandEntry() {
4345}
4346
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004347
Jeff Brown01ce2e92010-09-26 22:20:12 -07004348// --- InputDispatcher::TouchState ---
4349
4350InputDispatcher::TouchState::TouchState() :
Jeff Brown83d616a2012-09-09 20:33:43 -07004351 down(false), split(false), deviceId(-1), source(0), displayId(-1) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07004352}
4353
4354InputDispatcher::TouchState::~TouchState() {
4355}
4356
4357void InputDispatcher::TouchState::reset() {
4358 down = false;
4359 split = false;
Jeff Brown95712852011-01-04 19:41:59 -08004360 deviceId = -1;
Jeff Brown58a2da82011-01-25 16:02:22 -08004361 source = 0;
Jeff Brown83d616a2012-09-09 20:33:43 -07004362 displayId = -1;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004363 windows.clear();
4364}
4365
4366void InputDispatcher::TouchState::copyFrom(const TouchState& other) {
4367 down = other.down;
4368 split = other.split;
Jeff Brown95712852011-01-04 19:41:59 -08004369 deviceId = other.deviceId;
Jeff Brown58a2da82011-01-25 16:02:22 -08004370 source = other.source;
Jeff Brown83d616a2012-09-09 20:33:43 -07004371 displayId = other.displayId;
Jeff Brown9302c872011-07-13 22:51:29 -07004372 windows = other.windows;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004373}
4374
Jeff Brown9302c872011-07-13 22:51:29 -07004375void InputDispatcher::TouchState::addOrUpdateWindow(const sp<InputWindowHandle>& windowHandle,
Jeff Brown01ce2e92010-09-26 22:20:12 -07004376 int32_t targetFlags, BitSet32 pointerIds) {
4377 if (targetFlags & InputTarget::FLAG_SPLIT) {
4378 split = true;
4379 }
4380
4381 for (size_t i = 0; i < windows.size(); i++) {
4382 TouchedWindow& touchedWindow = windows.editItemAt(i);
Jeff Brown9302c872011-07-13 22:51:29 -07004383 if (touchedWindow.windowHandle == windowHandle) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07004384 touchedWindow.targetFlags |= targetFlags;
Jeff Brown98db5fa2011-06-08 15:37:10 -07004385 if (targetFlags & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
4386 touchedWindow.targetFlags &= ~InputTarget::FLAG_DISPATCH_AS_IS;
4387 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07004388 touchedWindow.pointerIds.value |= pointerIds.value;
4389 return;
4390 }
4391 }
4392
4393 windows.push();
4394
4395 TouchedWindow& touchedWindow = windows.editTop();
Jeff Brown9302c872011-07-13 22:51:29 -07004396 touchedWindow.windowHandle = windowHandle;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004397 touchedWindow.targetFlags = targetFlags;
4398 touchedWindow.pointerIds = pointerIds;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004399}
4400
Jeff Brownf44e3942012-04-20 11:33:27 -07004401void InputDispatcher::TouchState::removeWindow(const sp<InputWindowHandle>& windowHandle) {
4402 for (size_t i = 0; i < windows.size(); i++) {
4403 if (windows.itemAt(i).windowHandle == windowHandle) {
4404 windows.removeAt(i);
4405 return;
4406 }
4407 }
4408}
4409
Jeff Browna032cc02011-03-07 16:56:21 -08004410void InputDispatcher::TouchState::filterNonAsIsTouchWindows() {
Jeff Brown01ce2e92010-09-26 22:20:12 -07004411 for (size_t i = 0 ; i < windows.size(); ) {
Jeff Browna032cc02011-03-07 16:56:21 -08004412 TouchedWindow& window = windows.editItemAt(i);
Jeff Brown98db5fa2011-06-08 15:37:10 -07004413 if (window.targetFlags & (InputTarget::FLAG_DISPATCH_AS_IS
4414 | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER)) {
Jeff Browna032cc02011-03-07 16:56:21 -08004415 window.targetFlags &= ~InputTarget::FLAG_DISPATCH_MASK;
4416 window.targetFlags |= InputTarget::FLAG_DISPATCH_AS_IS;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004417 i += 1;
Jeff Browna032cc02011-03-07 16:56:21 -08004418 } else {
4419 windows.removeAt(i);
Jeff Brown01ce2e92010-09-26 22:20:12 -07004420 }
4421 }
4422}
4423
Jeff Brown9302c872011-07-13 22:51:29 -07004424sp<InputWindowHandle> InputDispatcher::TouchState::getFirstForegroundWindowHandle() const {
Jeff Brown01ce2e92010-09-26 22:20:12 -07004425 for (size_t i = 0; i < windows.size(); i++) {
Jeff Brown98db5fa2011-06-08 15:37:10 -07004426 const TouchedWindow& window = windows.itemAt(i);
4427 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
Jeff Brown9302c872011-07-13 22:51:29 -07004428 return window.windowHandle;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004429 }
4430 }
4431 return NULL;
4432}
4433
Jeff Brown98db5fa2011-06-08 15:37:10 -07004434bool InputDispatcher::TouchState::isSlippery() const {
4435 // Must have exactly one foreground window.
4436 bool haveSlipperyForegroundWindow = false;
4437 for (size_t i = 0; i < windows.size(); i++) {
4438 const TouchedWindow& window = windows.itemAt(i);
4439 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
Jeff Browncc4f7db2011-08-30 20:34:48 -07004440 if (haveSlipperyForegroundWindow
4441 || !(window.windowHandle->getInfo()->layoutParamsFlags
4442 & InputWindowInfo::FLAG_SLIPPERY)) {
Jeff Brown98db5fa2011-06-08 15:37:10 -07004443 return false;
4444 }
4445 haveSlipperyForegroundWindow = true;
4446 }
4447 }
4448 return haveSlipperyForegroundWindow;
4449}
4450
Jeff Brown01ce2e92010-09-26 22:20:12 -07004451
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004452// --- InputDispatcherThread ---
4453
4454InputDispatcherThread::InputDispatcherThread(const sp<InputDispatcherInterface>& dispatcher) :
4455 Thread(/*canCallJava*/ true), mDispatcher(dispatcher) {
4456}
4457
4458InputDispatcherThread::~InputDispatcherThread() {
4459}
4460
4461bool InputDispatcherThread::threadLoop() {
4462 mDispatcher->dispatchOnce();
4463 return true;
4464}
4465
4466} // namespace android