blob: 23a846b7ce953f47dbaa297c452d92a12283819f [file] [log] [blame]
Jeff Brownb4ff35d2011-01-02 16:37:43 -08001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Jeff Brown46b9ac02010-04-22 18:58:52 -070017#define LOG_TAG "InputDispatcher"
Jeff Brown481c1572012-03-09 14:41:15 -080018#define ATRACE_TAG ATRACE_TAG_INPUT
Jeff Brown46b9ac02010-04-22 18:58:52 -070019
20//#define LOG_NDEBUG 0
21
22// Log detailed debug messages about each inbound event notification to the dispatcher.
Jeff Brown349703e2010-06-22 01:27:15 -070023#define DEBUG_INBOUND_EVENT_DETAILS 0
Jeff Brown46b9ac02010-04-22 18:58:52 -070024
25// Log detailed debug messages about each outbound event processed by the dispatcher.
Jeff Brown349703e2010-06-22 01:27:15 -070026#define DEBUG_OUTBOUND_EVENT_DETAILS 0
Jeff Brown46b9ac02010-04-22 18:58:52 -070027
Jeff Brown46b9ac02010-04-22 18:58:52 -070028// Log debug messages about the dispatch cycle.
Jeff Brown349703e2010-06-22 01:27:15 -070029#define DEBUG_DISPATCH_CYCLE 0
Jeff Brown46b9ac02010-04-22 18:58:52 -070030
Jeff Brown9c3cda02010-06-15 01:31:58 -070031// Log debug messages about registrations.
Jeff Brown349703e2010-06-22 01:27:15 -070032#define DEBUG_REGISTRATION 0
Jeff Brown9c3cda02010-06-15 01:31:58 -070033
Jeff Brown7fbdc842010-06-17 20:52:56 -070034// Log debug messages about input event injection.
Jeff Brown349703e2010-06-22 01:27:15 -070035#define DEBUG_INJECTION 0
Jeff Brown7fbdc842010-06-17 20:52:56 -070036
Jeff Brownb88102f2010-09-08 11:49:43 -070037// Log debug messages about input focus tracking.
38#define DEBUG_FOCUS 0
39
40// Log debug messages about the app switch latency optimization.
41#define DEBUG_APP_SWITCH 0
42
Jeff Browna032cc02011-03-07 16:56:21 -080043// Log debug messages about hover events.
44#define DEBUG_HOVER 0
45
Jeff Brownb4ff35d2011-01-02 16:37:43 -080046#include "InputDispatcher.h"
47
Jeff Brown481c1572012-03-09 14:41:15 -080048#include <utils/Trace.h>
Jeff Brown46b9ac02010-04-22 18:58:52 -070049#include <cutils/log.h>
Mathias Agopianb93a03f82012-02-17 15:34:57 -080050#include <androidfw/PowerManager.h>
Jeff Brown46b9ac02010-04-22 18:58:52 -070051
52#include <stddef.h>
53#include <unistd.h>
Jeff Brown46b9ac02010-04-22 18:58:52 -070054#include <errno.h>
55#include <limits.h>
Jeff Brown22aa5122012-06-17 12:01:06 -070056#include <time.h>
Jeff Brown46b9ac02010-04-22 18:58:52 -070057
Jeff Brownf2f48712010-10-01 17:46:21 -070058#define INDENT " "
59#define INDENT2 " "
Jeff Brown265f1cc2012-06-11 18:01:06 -070060#define INDENT3 " "
61#define INDENT4 " "
Jeff Brownf2f48712010-10-01 17:46:21 -070062
Jeff Brown46b9ac02010-04-22 18:58:52 -070063namespace android {
64
Jeff Brownb88102f2010-09-08 11:49:43 -070065// Default input dispatching timeout if there is no focused application or paused window
66// from which to determine an appropriate dispatching timeout.
67const nsecs_t DEFAULT_INPUT_DISPATCHING_TIMEOUT = 5000 * 1000000LL; // 5 sec
68
69// Amount of time to allow for all pending events to be processed when an app switch
70// key is on the way. This is used to preempt input dispatch and drop input events
71// when an application takes too long to respond and the user has pressed an app switch key.
72const nsecs_t APP_SWITCH_TIMEOUT = 500 * 1000000LL; // 0.5sec
73
Jeff Brown928e0542011-01-10 11:17:36 -080074// Amount of time to allow for an event to be dispatched (measured since its eventTime)
75// before considering it stale and dropping it.
76const nsecs_t STALE_EVENT_TIMEOUT = 10000 * 1000000LL; // 10sec
77
Jeff Brownd1c48a02012-02-06 19:12:47 -080078// Amount of time to allow touch events to be streamed out to a connection before requiring
79// that the first event be finished. This value extends the ANR timeout by the specified
80// amount. For example, if streaming is allowed to get ahead by one second relative to the
81// queue of waiting unfinished events, then ANRs will similarly be delayed by one second.
82const nsecs_t STREAM_AHEAD_EVENT_TIMEOUT = 500 * 1000000LL; // 0.5sec
83
Jeff Brown265f1cc2012-06-11 18:01:06 -070084// Log a warning when an event takes longer than this to process, even if an ANR does not occur.
85const nsecs_t SLOW_EVENT_PROCESSING_WARNING_TIMEOUT = 2000 * 1000000LL; // 2sec
86
Jeff Brown46b9ac02010-04-22 18:58:52 -070087
Jeff Brown7fbdc842010-06-17 20:52:56 -070088static inline nsecs_t now() {
89 return systemTime(SYSTEM_TIME_MONOTONIC);
90}
91
Jeff Brownb88102f2010-09-08 11:49:43 -070092static inline const char* toString(bool value) {
93 return value ? "true" : "false";
94}
95
Jeff Brown01ce2e92010-09-26 22:20:12 -070096static inline int32_t getMotionEventActionPointerIndex(int32_t action) {
97 return (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK)
98 >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
99}
100
101static bool isValidKeyAction(int32_t action) {
102 switch (action) {
103 case AKEY_EVENT_ACTION_DOWN:
104 case AKEY_EVENT_ACTION_UP:
105 return true;
106 default:
107 return false;
108 }
109}
110
111static bool validateKeyEvent(int32_t action) {
112 if (! isValidKeyAction(action)) {
Steve Block3762c312012-01-06 19:20:56 +0000113 ALOGE("Key event has invalid action code 0x%x", action);
Jeff Brown01ce2e92010-09-26 22:20:12 -0700114 return false;
115 }
116 return true;
117}
118
Jeff Brownb6997262010-10-08 22:31:17 -0700119static bool isValidMotionAction(int32_t action, size_t pointerCount) {
Jeff Brown01ce2e92010-09-26 22:20:12 -0700120 switch (action & AMOTION_EVENT_ACTION_MASK) {
121 case AMOTION_EVENT_ACTION_DOWN:
122 case AMOTION_EVENT_ACTION_UP:
123 case AMOTION_EVENT_ACTION_CANCEL:
124 case AMOTION_EVENT_ACTION_MOVE:
Jeff Brown01ce2e92010-09-26 22:20:12 -0700125 case AMOTION_EVENT_ACTION_OUTSIDE:
Jeff Browna032cc02011-03-07 16:56:21 -0800126 case AMOTION_EVENT_ACTION_HOVER_ENTER:
Jeff Browncc0c1592011-02-19 05:07:28 -0800127 case AMOTION_EVENT_ACTION_HOVER_MOVE:
Jeff Browna032cc02011-03-07 16:56:21 -0800128 case AMOTION_EVENT_ACTION_HOVER_EXIT:
Jeff Brown33bbfd22011-02-24 20:55:35 -0800129 case AMOTION_EVENT_ACTION_SCROLL:
Jeff Brown01ce2e92010-09-26 22:20:12 -0700130 return true;
Jeff Brownb6997262010-10-08 22:31:17 -0700131 case AMOTION_EVENT_ACTION_POINTER_DOWN:
132 case AMOTION_EVENT_ACTION_POINTER_UP: {
133 int32_t index = getMotionEventActionPointerIndex(action);
134 return index >= 0 && size_t(index) < pointerCount;
135 }
Jeff Brown01ce2e92010-09-26 22:20:12 -0700136 default:
137 return false;
138 }
139}
140
141static bool validateMotionEvent(int32_t action, size_t pointerCount,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700142 const PointerProperties* pointerProperties) {
Jeff Brownb6997262010-10-08 22:31:17 -0700143 if (! isValidMotionAction(action, pointerCount)) {
Steve Block3762c312012-01-06 19:20:56 +0000144 ALOGE("Motion event has invalid action code 0x%x", action);
Jeff Brown01ce2e92010-09-26 22:20:12 -0700145 return false;
146 }
147 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Steve Block3762c312012-01-06 19:20:56 +0000148 ALOGE("Motion event has invalid pointer count %d; value must be between 1 and %d.",
Jeff Brown01ce2e92010-09-26 22:20:12 -0700149 pointerCount, MAX_POINTERS);
150 return false;
151 }
Jeff Brownc3db8582010-10-20 15:33:38 -0700152 BitSet32 pointerIdBits;
Jeff Brown01ce2e92010-09-26 22:20:12 -0700153 for (size_t i = 0; i < pointerCount; i++) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700154 int32_t id = pointerProperties[i].id;
Jeff Brownc3db8582010-10-20 15:33:38 -0700155 if (id < 0 || id > MAX_POINTER_ID) {
Steve Block3762c312012-01-06 19:20:56 +0000156 ALOGE("Motion event has invalid pointer id %d; value must be between 0 and %d",
Jeff Brownc3db8582010-10-20 15:33:38 -0700157 id, MAX_POINTER_ID);
Jeff Brown01ce2e92010-09-26 22:20:12 -0700158 return false;
159 }
Jeff Brownc3db8582010-10-20 15:33:38 -0700160 if (pointerIdBits.hasBit(id)) {
Steve Block3762c312012-01-06 19:20:56 +0000161 ALOGE("Motion event has duplicate pointer id %d", id);
Jeff Brownc3db8582010-10-20 15:33:38 -0700162 return false;
163 }
164 pointerIdBits.markBit(id);
Jeff Brown01ce2e92010-09-26 22:20:12 -0700165 }
166 return true;
167}
168
Jeff Brown83d616a2012-09-09 20:33:43 -0700169static bool isMainDisplay(int32_t displayId) {
170 return displayId == ADISPLAY_ID_DEFAULT || displayId == ADISPLAY_ID_NONE;
171}
172
Jeff Brownfbf09772011-01-16 14:06:57 -0800173static void dumpRegion(String8& dump, const SkRegion& region) {
174 if (region.isEmpty()) {
175 dump.append("<empty>");
176 return;
177 }
178
179 bool first = true;
180 for (SkRegion::Iterator it(region); !it.done(); it.next()) {
181 if (first) {
182 first = false;
183 } else {
184 dump.append("|");
185 }
186 const SkIRect& rect = it.rect();
187 dump.appendFormat("[%d,%d][%d,%d]", rect.fLeft, rect.fTop, rect.fRight, rect.fBottom);
188 }
189}
190
Jeff Brownb88102f2010-09-08 11:49:43 -0700191
Jeff Brown46b9ac02010-04-22 18:58:52 -0700192// --- InputDispatcher ---
193
Jeff Brown9c3cda02010-06-15 01:31:58 -0700194InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy) :
Jeff Brownb88102f2010-09-08 11:49:43 -0700195 mPolicy(policy),
Jeff Brown928e0542011-01-10 11:17:36 -0800196 mPendingEvent(NULL), mAppSwitchSawKeyDown(false), mAppSwitchDueTime(LONG_LONG_MAX),
197 mNextUnblockedEvent(NULL),
Jeff Brownc042ee22012-05-08 13:03:42 -0700198 mDispatchEnabled(false), mDispatchFrozen(false), mInputFilterEnabled(false),
Jeff Brown9302c872011-07-13 22:51:29 -0700199 mInputTargetWaitCause(INPUT_TARGET_WAIT_CAUSE_NONE) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -0700200 mLooper = new Looper(false);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700201
Jeff Brown46b9ac02010-04-22 18:58:52 -0700202 mKeyRepeatState.lastKeyEntry = NULL;
Jeff Brown9c3cda02010-06-15 01:31:58 -0700203
Jeff Brown214eaf42011-05-26 19:17:02 -0700204 policy->getDispatcherConfiguration(&mConfig);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700205}
206
207InputDispatcher::~InputDispatcher() {
Jeff Brownb88102f2010-09-08 11:49:43 -0700208 { // acquire lock
209 AutoMutex _l(mLock);
210
211 resetKeyRepeatLocked();
Jeff Brown54a18252010-09-16 14:07:33 -0700212 releasePendingEventLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -0700213 drainInboundQueueLocked();
214 }
Jeff Brown46b9ac02010-04-22 18:58:52 -0700215
Jeff Browncbee6d62012-02-03 20:11:27 -0800216 while (mConnectionsByFd.size() != 0) {
217 unregisterInputChannel(mConnectionsByFd.valueAt(0)->inputChannel);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700218 }
Jeff Brown46b9ac02010-04-22 18:58:52 -0700219}
220
221void InputDispatcher::dispatchOnce() {
Jeff Brown46b9ac02010-04-22 18:58:52 -0700222 nsecs_t nextWakeupTime = LONG_LONG_MAX;
223 { // acquire lock
224 AutoMutex _l(mLock);
Jeff Brown112b5f52012-01-27 17:32:06 -0800225 mDispatcherIsAliveCondition.broadcast();
226
Jeff Brown074b8b72012-10-31 19:01:31 -0700227 // Run a dispatch loop if there are no pending commands.
228 // The dispatch loop might enqueue commands to run afterwards.
229 if (!haveCommandsLocked()) {
230 dispatchOnceInnerLocked(&nextWakeupTime);
231 }
Jeff Brown46b9ac02010-04-22 18:58:52 -0700232
Jeff Brown074b8b72012-10-31 19:01:31 -0700233 // Run all pending commands if there are any.
234 // If any commands were run then force the next poll to wake up immediately.
Jeff Brownb88102f2010-09-08 11:49:43 -0700235 if (runCommandsLockedInterruptible()) {
Jeff Brown074b8b72012-10-31 19:01:31 -0700236 nextWakeupTime = LONG_LONG_MIN;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700237 }
Jeff Brown46b9ac02010-04-22 18:58:52 -0700238 } // release lock
239
Jeff Brownb88102f2010-09-08 11:49:43 -0700240 // Wait for callback or timeout or wake. (make sure we round up, not down)
241 nsecs_t currentTime = now();
Jeff Brownaa3855d2011-03-17 01:34:19 -0700242 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
Jeff Brown4fe6c3e2010-09-13 23:17:30 -0700243 mLooper->pollOnce(timeoutMillis);
Jeff Brownb88102f2010-09-08 11:49:43 -0700244}
245
Jeff Brown214eaf42011-05-26 19:17:02 -0700246void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700247 nsecs_t currentTime = now();
248
249 // Reset the key repeat timer whenever we disallow key events, even if the next event
250 // is not a key. This is to ensure that we abort a key repeat if the device is just coming
251 // out of sleep.
Jeff Brown214eaf42011-05-26 19:17:02 -0700252 if (!mPolicy->isKeyRepeatEnabled()) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700253 resetKeyRepeatLocked();
254 }
255
Jeff Brownb88102f2010-09-08 11:49:43 -0700256 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
257 if (mDispatchFrozen) {
258#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +0000259 ALOGD("Dispatch frozen. Waiting some more.");
Jeff Brownb88102f2010-09-08 11:49:43 -0700260#endif
261 return;
262 }
263
264 // Optimize latency of app switches.
265 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
266 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
267 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
268 if (mAppSwitchDueTime < *nextWakeupTime) {
269 *nextWakeupTime = mAppSwitchDueTime;
270 }
271
Jeff Brownb88102f2010-09-08 11:49:43 -0700272 // Ready to start a new event.
273 // If we don't already have a pending event, go grab one.
274 if (! mPendingEvent) {
275 if (mInboundQueue.isEmpty()) {
276 if (isAppSwitchDue) {
277 // The inbound queue is empty so the app switch key we were waiting
278 // for will never arrive. Stop waiting for it.
279 resetPendingAppSwitchLocked(false);
280 isAppSwitchDue = false;
281 }
282
283 // Synthesize a key repeat if appropriate.
284 if (mKeyRepeatState.lastKeyEntry) {
285 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
Jeff Brown214eaf42011-05-26 19:17:02 -0700286 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700287 } else {
288 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
289 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
290 }
291 }
292 }
Jeff Browncc4f7db2011-08-30 20:34:48 -0700293
294 // Nothing to do if there is no pending event.
Jeff Browne9bb9be2012-02-06 15:47:55 -0800295 if (!mPendingEvent) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700296 return;
297 }
298 } else {
299 // Inbound queue has at least one entry.
Jeff Browne9bb9be2012-02-06 15:47:55 -0800300 mPendingEvent = mInboundQueue.dequeueAtHead();
Jeff Brown481c1572012-03-09 14:41:15 -0800301 traceInboundQueueLengthLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -0700302 }
Jeff Browne2fe69e2010-10-18 13:21:23 -0700303
304 // Poke user activity for this event.
305 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
306 pokeUserActivityLocked(mPendingEvent);
307 }
Jeff Browne9bb9be2012-02-06 15:47:55 -0800308
309 // Get ready to dispatch the event.
310 resetANRTimeoutsLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -0700311 }
312
313 // Now we have an event to dispatch.
Jeff Brown928e0542011-01-10 11:17:36 -0800314 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Steve Blockec193de2012-01-09 18:35:44 +0000315 ALOG_ASSERT(mPendingEvent != NULL);
Jeff Brown54a18252010-09-16 14:07:33 -0700316 bool done = false;
Jeff Brownb6997262010-10-08 22:31:17 -0700317 DropReason dropReason = DROP_REASON_NOT_DROPPED;
318 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
319 dropReason = DROP_REASON_POLICY;
320 } else if (!mDispatchEnabled) {
321 dropReason = DROP_REASON_DISABLED;
322 }
Jeff Brown928e0542011-01-10 11:17:36 -0800323
324 if (mNextUnblockedEvent == mPendingEvent) {
325 mNextUnblockedEvent = NULL;
326 }
327
Jeff Brownb88102f2010-09-08 11:49:43 -0700328 switch (mPendingEvent->type) {
329 case EventEntry::TYPE_CONFIGURATION_CHANGED: {
330 ConfigurationChangedEntry* typedEntry =
331 static_cast<ConfigurationChangedEntry*>(mPendingEvent);
Jeff Brown54a18252010-09-16 14:07:33 -0700332 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Jeff Brownb6997262010-10-08 22:31:17 -0700333 dropReason = DROP_REASON_NOT_DROPPED; // configuration changes are never dropped
Jeff Brownb88102f2010-09-08 11:49:43 -0700334 break;
335 }
336
Jeff Brown65fd2512011-08-18 11:20:58 -0700337 case EventEntry::TYPE_DEVICE_RESET: {
338 DeviceResetEntry* typedEntry =
339 static_cast<DeviceResetEntry*>(mPendingEvent);
340 done = dispatchDeviceResetLocked(currentTime, typedEntry);
341 dropReason = DROP_REASON_NOT_DROPPED; // device resets are never dropped
342 break;
343 }
344
Jeff Brownb88102f2010-09-08 11:49:43 -0700345 case EventEntry::TYPE_KEY: {
346 KeyEntry* typedEntry = static_cast<KeyEntry*>(mPendingEvent);
Jeff Brownb6997262010-10-08 22:31:17 -0700347 if (isAppSwitchDue) {
348 if (isAppSwitchKeyEventLocked(typedEntry)) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700349 resetPendingAppSwitchLocked(true);
Jeff Brownb6997262010-10-08 22:31:17 -0700350 isAppSwitchDue = false;
351 } else if (dropReason == DROP_REASON_NOT_DROPPED) {
352 dropReason = DROP_REASON_APP_SWITCH;
Jeff Brownb88102f2010-09-08 11:49:43 -0700353 }
354 }
Jeff Brown928e0542011-01-10 11:17:36 -0800355 if (dropReason == DROP_REASON_NOT_DROPPED
356 && isStaleEventLocked(currentTime, typedEntry)) {
357 dropReason = DROP_REASON_STALE;
358 }
359 if (dropReason == DROP_REASON_NOT_DROPPED && mNextUnblockedEvent) {
360 dropReason = DROP_REASON_BLOCKED;
361 }
Jeff Brown214eaf42011-05-26 19:17:02 -0700362 done = dispatchKeyLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700363 break;
364 }
365
366 case EventEntry::TYPE_MOTION: {
367 MotionEntry* typedEntry = static_cast<MotionEntry*>(mPendingEvent);
Jeff Brownb6997262010-10-08 22:31:17 -0700368 if (dropReason == DROP_REASON_NOT_DROPPED && isAppSwitchDue) {
369 dropReason = DROP_REASON_APP_SWITCH;
Jeff Brownb88102f2010-09-08 11:49:43 -0700370 }
Jeff Brown928e0542011-01-10 11:17:36 -0800371 if (dropReason == DROP_REASON_NOT_DROPPED
372 && isStaleEventLocked(currentTime, typedEntry)) {
373 dropReason = DROP_REASON_STALE;
374 }
375 if (dropReason == DROP_REASON_NOT_DROPPED && mNextUnblockedEvent) {
376 dropReason = DROP_REASON_BLOCKED;
377 }
Jeff Brownb6997262010-10-08 22:31:17 -0700378 done = dispatchMotionLocked(currentTime, typedEntry,
Jeff Browne20c9e02010-10-11 14:20:19 -0700379 &dropReason, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700380 break;
381 }
382
383 default:
Steve Blockec193de2012-01-09 18:35:44 +0000384 ALOG_ASSERT(false);
Jeff Brownb88102f2010-09-08 11:49:43 -0700385 break;
386 }
387
Jeff Brown54a18252010-09-16 14:07:33 -0700388 if (done) {
Jeff Brownb6997262010-10-08 22:31:17 -0700389 if (dropReason != DROP_REASON_NOT_DROPPED) {
390 dropInboundEventLocked(mPendingEvent, dropReason);
391 }
392
Jeff Brown54a18252010-09-16 14:07:33 -0700393 releasePendingEventLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -0700394 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
395 }
396}
397
398bool InputDispatcher::enqueueInboundEventLocked(EventEntry* entry) {
399 bool needWake = mInboundQueue.isEmpty();
400 mInboundQueue.enqueueAtTail(entry);
Jeff Brown481c1572012-03-09 14:41:15 -0800401 traceInboundQueueLengthLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -0700402
403 switch (entry->type) {
Jeff Brownb6997262010-10-08 22:31:17 -0700404 case EventEntry::TYPE_KEY: {
Jeff Brown928e0542011-01-10 11:17:36 -0800405 // Optimize app switch latency.
406 // If the application takes too long to catch up then we drop all events preceding
407 // the app switch key.
Jeff Brownb6997262010-10-08 22:31:17 -0700408 KeyEntry* keyEntry = static_cast<KeyEntry*>(entry);
409 if (isAppSwitchKeyEventLocked(keyEntry)) {
410 if (keyEntry->action == AKEY_EVENT_ACTION_DOWN) {
411 mAppSwitchSawKeyDown = true;
412 } else if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
413 if (mAppSwitchSawKeyDown) {
414#if DEBUG_APP_SWITCH
Steve Block5baa3a62011-12-20 16:23:08 +0000415 ALOGD("App switch is pending!");
Jeff Brownb6997262010-10-08 22:31:17 -0700416#endif
417 mAppSwitchDueTime = keyEntry->eventTime + APP_SWITCH_TIMEOUT;
418 mAppSwitchSawKeyDown = false;
419 needWake = true;
420 }
421 }
422 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700423 break;
424 }
Jeff Brown928e0542011-01-10 11:17:36 -0800425
426 case EventEntry::TYPE_MOTION: {
427 // Optimize case where the current application is unresponsive and the user
428 // decides to touch a window in a different application.
429 // If the application takes too long to catch up then we drop all events preceding
430 // the touch into the other window.
431 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
Jeff Brown33bbfd22011-02-24 20:55:35 -0800432 if (motionEntry->action == AMOTION_EVENT_ACTION_DOWN
Jeff Brown928e0542011-01-10 11:17:36 -0800433 && (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER)
434 && mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY
Jeff Brown9302c872011-07-13 22:51:29 -0700435 && mInputTargetWaitApplicationHandle != NULL) {
Jeff Brown83d616a2012-09-09 20:33:43 -0700436 int32_t displayId = motionEntry->displayId;
Jeff Brown3241b6b2012-02-03 15:08:02 -0800437 int32_t x = int32_t(motionEntry->pointerCoords[0].
Jeff Brownebbd5d12011-02-17 13:01:34 -0800438 getAxisValue(AMOTION_EVENT_AXIS_X));
Jeff Brown3241b6b2012-02-03 15:08:02 -0800439 int32_t y = int32_t(motionEntry->pointerCoords[0].
Jeff Brownebbd5d12011-02-17 13:01:34 -0800440 getAxisValue(AMOTION_EVENT_AXIS_Y));
Jeff Brown83d616a2012-09-09 20:33:43 -0700441 sp<InputWindowHandle> touchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y);
Jeff Brown9302c872011-07-13 22:51:29 -0700442 if (touchedWindowHandle != NULL
443 && touchedWindowHandle->inputApplicationHandle
444 != mInputTargetWaitApplicationHandle) {
Jeff Brown928e0542011-01-10 11:17:36 -0800445 // User touched a different application than the one we are waiting on.
446 // Flag the event, and start pruning the input queue.
447 mNextUnblockedEvent = motionEntry;
448 needWake = true;
449 }
450 }
451 break;
452 }
Jeff Brownb6997262010-10-08 22:31:17 -0700453 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700454
455 return needWake;
456}
457
Jeff Brown83d616a2012-09-09 20:33:43 -0700458sp<InputWindowHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId,
459 int32_t x, int32_t y) {
Jeff Brown928e0542011-01-10 11:17:36 -0800460 // Traverse windows from front to back to find touched window.
Jeff Brown9302c872011-07-13 22:51:29 -0700461 size_t numWindows = mWindowHandles.size();
Jeff Brown928e0542011-01-10 11:17:36 -0800462 for (size_t i = 0; i < numWindows; i++) {
Jeff Brown9302c872011-07-13 22:51:29 -0700463 sp<InputWindowHandle> windowHandle = mWindowHandles.itemAt(i);
Jeff Browncc4f7db2011-08-30 20:34:48 -0700464 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Jeff Brown83d616a2012-09-09 20:33:43 -0700465 if (windowInfo->displayId == displayId) {
466 int32_t flags = windowInfo->layoutParamsFlags;
Jeff Brown928e0542011-01-10 11:17:36 -0800467
Jeff Brown83d616a2012-09-09 20:33:43 -0700468 if (windowInfo->visible) {
469 if (!(flags & InputWindowInfo::FLAG_NOT_TOUCHABLE)) {
470 bool isTouchModal = (flags & (InputWindowInfo::FLAG_NOT_FOCUSABLE
471 | InputWindowInfo::FLAG_NOT_TOUCH_MODAL)) == 0;
472 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
473 // Found window.
474 return windowHandle;
475 }
Jeff Brown928e0542011-01-10 11:17:36 -0800476 }
477 }
Jeff Brown928e0542011-01-10 11:17:36 -0800478
Jeff Brown83d616a2012-09-09 20:33:43 -0700479 if (flags & InputWindowInfo::FLAG_SYSTEM_ERROR) {
480 // Error window is on top but not visible, so touch is dropped.
481 return NULL;
482 }
Jeff Brown928e0542011-01-10 11:17:36 -0800483 }
484 }
485 return NULL;
486}
487
Jeff Brownb6997262010-10-08 22:31:17 -0700488void InputDispatcher::dropInboundEventLocked(EventEntry* entry, DropReason dropReason) {
489 const char* reason;
490 switch (dropReason) {
491 case DROP_REASON_POLICY:
Jeff Browne20c9e02010-10-11 14:20:19 -0700492#if DEBUG_INBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +0000493 ALOGD("Dropped event because policy consumed it.");
Jeff Browne20c9e02010-10-11 14:20:19 -0700494#endif
Jeff Brown3122e442010-10-11 23:32:49 -0700495 reason = "inbound event was dropped because the policy consumed it";
Jeff Brownb6997262010-10-08 22:31:17 -0700496 break;
497 case DROP_REASON_DISABLED:
Steve Block6215d3f2012-01-04 20:05:49 +0000498 ALOGI("Dropped event because input dispatch is disabled.");
Jeff Brownb6997262010-10-08 22:31:17 -0700499 reason = "inbound event was dropped because input dispatch is disabled";
500 break;
501 case DROP_REASON_APP_SWITCH:
Steve Block6215d3f2012-01-04 20:05:49 +0000502 ALOGI("Dropped event because of pending overdue app switch.");
Jeff Brownb6997262010-10-08 22:31:17 -0700503 reason = "inbound event was dropped because of pending overdue app switch";
504 break;
Jeff Brown928e0542011-01-10 11:17:36 -0800505 case DROP_REASON_BLOCKED:
Steve Block6215d3f2012-01-04 20:05:49 +0000506 ALOGI("Dropped event because the current application is not responding and the user "
Jeff Brown81346812011-06-28 20:08:48 -0700507 "has started interacting with a different application.");
Jeff Brown928e0542011-01-10 11:17:36 -0800508 reason = "inbound event was dropped because the current application is not responding "
Jeff Brown81346812011-06-28 20:08:48 -0700509 "and the user has started interacting with a different application";
Jeff Brown928e0542011-01-10 11:17:36 -0800510 break;
511 case DROP_REASON_STALE:
Steve Block6215d3f2012-01-04 20:05:49 +0000512 ALOGI("Dropped event because it is stale.");
Jeff Brown928e0542011-01-10 11:17:36 -0800513 reason = "inbound event was dropped because it is stale";
514 break;
Jeff Brownb6997262010-10-08 22:31:17 -0700515 default:
Steve Blockec193de2012-01-09 18:35:44 +0000516 ALOG_ASSERT(false);
Jeff Brownb6997262010-10-08 22:31:17 -0700517 return;
518 }
519
520 switch (entry->type) {
Jeff Brownda3d5a92011-03-29 15:11:34 -0700521 case EventEntry::TYPE_KEY: {
522 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
523 synthesizeCancelationEventsForAllConnectionsLocked(options);
Jeff Brownb6997262010-10-08 22:31:17 -0700524 break;
Jeff Brownda3d5a92011-03-29 15:11:34 -0700525 }
Jeff Brownb6997262010-10-08 22:31:17 -0700526 case EventEntry::TYPE_MOTION: {
527 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
528 if (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) {
Jeff Brownda3d5a92011-03-29 15:11:34 -0700529 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
530 synthesizeCancelationEventsForAllConnectionsLocked(options);
Jeff Brownb6997262010-10-08 22:31:17 -0700531 } else {
Jeff Brownda3d5a92011-03-29 15:11:34 -0700532 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
533 synthesizeCancelationEventsForAllConnectionsLocked(options);
Jeff Brownb6997262010-10-08 22:31:17 -0700534 }
535 break;
536 }
537 }
538}
539
540bool InputDispatcher::isAppSwitchKeyCode(int32_t keyCode) {
Michael Wright75ebb37f2013-03-15 16:27:29 -0700541 return keyCode == AKEYCODE_HOME
542 || keyCode == AKEYCODE_ENDCALL
543 || keyCode == AKEYCODE_APP_SWITCH;
Jeff Brownb88102f2010-09-08 11:49:43 -0700544}
545
Jeff Brownb6997262010-10-08 22:31:17 -0700546bool InputDispatcher::isAppSwitchKeyEventLocked(KeyEntry* keyEntry) {
547 return ! (keyEntry->flags & AKEY_EVENT_FLAG_CANCELED)
548 && isAppSwitchKeyCode(keyEntry->keyCode)
Jeff Browne20c9e02010-10-11 14:20:19 -0700549 && (keyEntry->policyFlags & POLICY_FLAG_TRUSTED)
Jeff Brownb6997262010-10-08 22:31:17 -0700550 && (keyEntry->policyFlags & POLICY_FLAG_PASS_TO_USER);
551}
552
Jeff Brownb88102f2010-09-08 11:49:43 -0700553bool InputDispatcher::isAppSwitchPendingLocked() {
554 return mAppSwitchDueTime != LONG_LONG_MAX;
555}
556
Jeff Brownb88102f2010-09-08 11:49:43 -0700557void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
558 mAppSwitchDueTime = LONG_LONG_MAX;
559
560#if DEBUG_APP_SWITCH
561 if (handled) {
Steve Block5baa3a62011-12-20 16:23:08 +0000562 ALOGD("App switch has arrived.");
Jeff Brownb88102f2010-09-08 11:49:43 -0700563 } else {
Steve Block5baa3a62011-12-20 16:23:08 +0000564 ALOGD("App switch was abandoned.");
Jeff Brownb88102f2010-09-08 11:49:43 -0700565 }
566#endif
Jeff Brown46b9ac02010-04-22 18:58:52 -0700567}
568
Jeff Brown928e0542011-01-10 11:17:36 -0800569bool InputDispatcher::isStaleEventLocked(nsecs_t currentTime, EventEntry* entry) {
570 return currentTime - entry->eventTime >= STALE_EVENT_TIMEOUT;
571}
572
Jeff Brown074b8b72012-10-31 19:01:31 -0700573bool InputDispatcher::haveCommandsLocked() const {
574 return !mCommandQueue.isEmpty();
575}
576
Jeff Brown9c3cda02010-06-15 01:31:58 -0700577bool InputDispatcher::runCommandsLockedInterruptible() {
578 if (mCommandQueue.isEmpty()) {
579 return false;
580 }
Jeff Brown46b9ac02010-04-22 18:58:52 -0700581
Jeff Brown9c3cda02010-06-15 01:31:58 -0700582 do {
583 CommandEntry* commandEntry = mCommandQueue.dequeueAtHead();
584
585 Command command = commandEntry->command;
586 (this->*command)(commandEntry); // commands are implicitly 'LockedInterruptible'
587
Jeff Brown7fbdc842010-06-17 20:52:56 -0700588 commandEntry->connection.clear();
Jeff Brownac386072011-07-20 15:19:50 -0700589 delete commandEntry;
Jeff Brown9c3cda02010-06-15 01:31:58 -0700590 } while (! mCommandQueue.isEmpty());
591 return true;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700592}
593
Jeff Brown9c3cda02010-06-15 01:31:58 -0700594InputDispatcher::CommandEntry* InputDispatcher::postCommandLocked(Command command) {
Jeff Brownac386072011-07-20 15:19:50 -0700595 CommandEntry* commandEntry = new CommandEntry(command);
Jeff Brown9c3cda02010-06-15 01:31:58 -0700596 mCommandQueue.enqueueAtTail(commandEntry);
597 return commandEntry;
598}
599
Jeff Brownb88102f2010-09-08 11:49:43 -0700600void InputDispatcher::drainInboundQueueLocked() {
601 while (! mInboundQueue.isEmpty()) {
602 EventEntry* entry = mInboundQueue.dequeueAtHead();
Jeff Brown54a18252010-09-16 14:07:33 -0700603 releaseInboundEventLocked(entry);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700604 }
Jeff Brown481c1572012-03-09 14:41:15 -0800605 traceInboundQueueLengthLocked();
Jeff Brown46b9ac02010-04-22 18:58:52 -0700606}
607
Jeff Brown54a18252010-09-16 14:07:33 -0700608void InputDispatcher::releasePendingEventLocked() {
Jeff Brownb88102f2010-09-08 11:49:43 -0700609 if (mPendingEvent) {
Jeff Browne9bb9be2012-02-06 15:47:55 -0800610 resetANRTimeoutsLocked();
Jeff Brown54a18252010-09-16 14:07:33 -0700611 releaseInboundEventLocked(mPendingEvent);
Jeff Brownb88102f2010-09-08 11:49:43 -0700612 mPendingEvent = NULL;
613 }
614}
615
Jeff Brown54a18252010-09-16 14:07:33 -0700616void InputDispatcher::releaseInboundEventLocked(EventEntry* entry) {
Jeff Brown01ce2e92010-09-26 22:20:12 -0700617 InjectionState* injectionState = entry->injectionState;
618 if (injectionState && injectionState->injectionResult == INPUT_EVENT_INJECTION_PENDING) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700619#if DEBUG_DISPATCH_CYCLE
Steve Block5baa3a62011-12-20 16:23:08 +0000620 ALOGD("Injected inbound event was dropped.");
Jeff Brownb88102f2010-09-08 11:49:43 -0700621#endif
622 setInjectionResultLocked(entry, INPUT_EVENT_INJECTION_FAILED);
623 }
Jeff Brownabb4d442011-08-15 12:55:32 -0700624 if (entry == mNextUnblockedEvent) {
625 mNextUnblockedEvent = NULL;
626 }
Jeff Brownac386072011-07-20 15:19:50 -0700627 entry->release();
Jeff Brownb88102f2010-09-08 11:49:43 -0700628}
629
Jeff Brownb88102f2010-09-08 11:49:43 -0700630void InputDispatcher::resetKeyRepeatLocked() {
631 if (mKeyRepeatState.lastKeyEntry) {
Jeff Brownac386072011-07-20 15:19:50 -0700632 mKeyRepeatState.lastKeyEntry->release();
Jeff Brownb88102f2010-09-08 11:49:43 -0700633 mKeyRepeatState.lastKeyEntry = NULL;
634 }
635}
636
Jeff Brown214eaf42011-05-26 19:17:02 -0700637InputDispatcher::KeyEntry* InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
Jeff Brown349703e2010-06-22 01:27:15 -0700638 KeyEntry* entry = mKeyRepeatState.lastKeyEntry;
639
Jeff Brown349703e2010-06-22 01:27:15 -0700640 // Reuse the repeated key entry if it is otherwise unreferenced.
Jeff Browne20c9e02010-10-11 14:20:19 -0700641 uint32_t policyFlags = (entry->policyFlags & POLICY_FLAG_RAW_MASK)
642 | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700643 if (entry->refCount == 1) {
Jeff Brownac386072011-07-20 15:19:50 -0700644 entry->recycle();
Jeff Brown7fbdc842010-06-17 20:52:56 -0700645 entry->eventTime = currentTime;
Jeff Brown7fbdc842010-06-17 20:52:56 -0700646 entry->policyFlags = policyFlags;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700647 entry->repeatCount += 1;
648 } else {
Jeff Brownac386072011-07-20 15:19:50 -0700649 KeyEntry* newEntry = new KeyEntry(currentTime,
Jeff Brownc5ed5912010-07-14 18:48:53 -0700650 entry->deviceId, entry->source, policyFlags,
Jeff Brown7fbdc842010-06-17 20:52:56 -0700651 entry->action, entry->flags, entry->keyCode, entry->scanCode,
Jeff Brown00fa7bd2010-07-02 15:37:36 -0700652 entry->metaState, entry->repeatCount + 1, entry->downTime);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700653
654 mKeyRepeatState.lastKeyEntry = newEntry;
Jeff Brownac386072011-07-20 15:19:50 -0700655 entry->release();
Jeff Brown46b9ac02010-04-22 18:58:52 -0700656
657 entry = newEntry;
658 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700659 entry->syntheticRepeat = true;
660
661 // Increment reference count since we keep a reference to the event in
662 // mKeyRepeatState.lastKeyEntry in addition to the one we return.
663 entry->refCount += 1;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700664
Jeff Brown214eaf42011-05-26 19:17:02 -0700665 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Jeff Brownb88102f2010-09-08 11:49:43 -0700666 return entry;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700667}
668
Jeff Brownb88102f2010-09-08 11:49:43 -0700669bool InputDispatcher::dispatchConfigurationChangedLocked(
670 nsecs_t currentTime, ConfigurationChangedEntry* entry) {
Jeff Brown46b9ac02010-04-22 18:58:52 -0700671#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +0000672 ALOGD("dispatchConfigurationChanged - eventTime=%lld", entry->eventTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700673#endif
674
675 // Reset key repeating in case a keyboard device was added or removed or something.
676 resetKeyRepeatLocked();
677
678 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
679 CommandEntry* commandEntry = postCommandLocked(
680 & InputDispatcher::doNotifyConfigurationChangedInterruptible);
681 commandEntry->eventTime = entry->eventTime;
682 return true;
683}
684
Jeff Brown65fd2512011-08-18 11:20:58 -0700685bool InputDispatcher::dispatchDeviceResetLocked(
686 nsecs_t currentTime, DeviceResetEntry* entry) {
687#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +0000688 ALOGD("dispatchDeviceReset - eventTime=%lld, deviceId=%d", entry->eventTime, entry->deviceId);
Jeff Brown65fd2512011-08-18 11:20:58 -0700689#endif
690
691 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
692 "device was reset");
693 options.deviceId = entry->deviceId;
694 synthesizeCancelationEventsForAllConnectionsLocked(options);
695 return true;
696}
697
Jeff Brown214eaf42011-05-26 19:17:02 -0700698bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, KeyEntry* entry,
Jeff Browne20c9e02010-10-11 14:20:19 -0700699 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Jeff Browne46a0a42010-11-02 17:58:22 -0700700 // Preprocessing.
701 if (! entry->dispatchInProgress) {
702 if (entry->repeatCount == 0
703 && entry->action == AKEY_EVENT_ACTION_DOWN
704 && (entry->policyFlags & POLICY_FLAG_TRUSTED)
Jeff Brown0029c662011-03-30 02:25:18 -0700705 && (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
Jeff Browne46a0a42010-11-02 17:58:22 -0700706 if (mKeyRepeatState.lastKeyEntry
707 && mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode) {
708 // We have seen two identical key downs in a row which indicates that the device
709 // driver is automatically generating key repeats itself. We take note of the
710 // repeat here, but we disable our own next key repeat timer since it is clear that
711 // we will not need to synthesize key repeats ourselves.
712 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
713 resetKeyRepeatLocked();
714 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
715 } else {
716 // Not a repeat. Save key down state in case we do see a repeat later.
717 resetKeyRepeatLocked();
Jeff Brown214eaf42011-05-26 19:17:02 -0700718 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
Jeff Browne46a0a42010-11-02 17:58:22 -0700719 }
720 mKeyRepeatState.lastKeyEntry = entry;
721 entry->refCount += 1;
722 } else if (! entry->syntheticRepeat) {
723 resetKeyRepeatLocked();
724 }
725
Jeff Browne2e01262011-03-02 20:34:30 -0800726 if (entry->repeatCount == 1) {
727 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
728 } else {
729 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
730 }
731
Jeff Browne46a0a42010-11-02 17:58:22 -0700732 entry->dispatchInProgress = true;
Jeff Browne46a0a42010-11-02 17:58:22 -0700733
734 logOutboundKeyDetailsLocked("dispatchKey - ", entry);
735 }
736
Jeff Brown905805a2011-10-12 13:57:59 -0700737 // Handle case where the policy asked us to try again later last time.
738 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
739 if (currentTime < entry->interceptKeyWakeupTime) {
740 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
741 *nextWakeupTime = entry->interceptKeyWakeupTime;
742 }
743 return false; // wait until next wakeup
744 }
745 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
746 entry->interceptKeyWakeupTime = 0;
747 }
748
Jeff Brown54a18252010-09-16 14:07:33 -0700749 // Give the policy a chance to intercept the key.
750 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
Jeff Browne20c9e02010-10-11 14:20:19 -0700751 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Jeff Brown54a18252010-09-16 14:07:33 -0700752 CommandEntry* commandEntry = postCommandLocked(
753 & InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
Jeff Brown9302c872011-07-13 22:51:29 -0700754 if (mFocusedWindowHandle != NULL) {
755 commandEntry->inputWindowHandle = mFocusedWindowHandle;
Jeff Brown54a18252010-09-16 14:07:33 -0700756 }
757 commandEntry->keyEntry = entry;
758 entry->refCount += 1;
759 return false; // wait for the command to run
760 } else {
761 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
762 }
763 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Jeff Browne20c9e02010-10-11 14:20:19 -0700764 if (*dropReason == DROP_REASON_NOT_DROPPED) {
765 *dropReason = DROP_REASON_POLICY;
766 }
Jeff Brown54a18252010-09-16 14:07:33 -0700767 }
768
769 // Clean up if dropping the event.
Jeff Browne20c9e02010-10-11 14:20:19 -0700770 if (*dropReason != DROP_REASON_NOT_DROPPED) {
Jeff Brown3122e442010-10-11 23:32:49 -0700771 setInjectionResultLocked(entry, *dropReason == DROP_REASON_POLICY
772 ? INPUT_EVENT_INJECTION_SUCCEEDED : INPUT_EVENT_INJECTION_FAILED);
Jeff Brown54a18252010-09-16 14:07:33 -0700773 return true;
774 }
775
Jeff Brownb88102f2010-09-08 11:49:43 -0700776 // Identify targets.
Jeff Browne9bb9be2012-02-06 15:47:55 -0800777 Vector<InputTarget> inputTargets;
778 int32_t injectionResult = findFocusedWindowTargetsLocked(currentTime,
779 entry, inputTargets, nextWakeupTime);
780 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
781 return false;
Jeff Brownb88102f2010-09-08 11:49:43 -0700782 }
783
Jeff Browne9bb9be2012-02-06 15:47:55 -0800784 setInjectionResultLocked(entry, injectionResult);
785 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
786 return true;
787 }
788
789 addMonitoringTargetsLocked(inputTargets);
790
Jeff Brownb88102f2010-09-08 11:49:43 -0700791 // Dispatch the key.
Jeff Browne9bb9be2012-02-06 15:47:55 -0800792 dispatchEventLocked(currentTime, entry, inputTargets);
Jeff Brownb88102f2010-09-08 11:49:43 -0700793 return true;
794}
795
796void InputDispatcher::logOutboundKeyDetailsLocked(const char* prefix, const KeyEntry* entry) {
797#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +0000798 ALOGD("%seventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, "
Jeff Brownb88102f2010-09-08 11:49:43 -0700799 "action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, "
Jeff Browne46a0a42010-11-02 17:58:22 -0700800 "repeatCount=%d, downTime=%lld",
Jeff Brownb88102f2010-09-08 11:49:43 -0700801 prefix,
802 entry->eventTime, entry->deviceId, entry->source, entry->policyFlags,
803 entry->action, entry->flags, entry->keyCode, entry->scanCode, entry->metaState,
Jeff Browne46a0a42010-11-02 17:58:22 -0700804 entry->repeatCount, entry->downTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700805#endif
806}
807
808bool InputDispatcher::dispatchMotionLocked(
Jeff Browne20c9e02010-10-11 14:20:19 -0700809 nsecs_t currentTime, MotionEntry* entry, DropReason* dropReason, nsecs_t* nextWakeupTime) {
Jeff Browne46a0a42010-11-02 17:58:22 -0700810 // Preprocessing.
811 if (! entry->dispatchInProgress) {
812 entry->dispatchInProgress = true;
Jeff Browne46a0a42010-11-02 17:58:22 -0700813
814 logOutboundMotionDetailsLocked("dispatchMotion - ", entry);
815 }
816
Jeff Brown54a18252010-09-16 14:07:33 -0700817 // Clean up if dropping the event.
Jeff Browne20c9e02010-10-11 14:20:19 -0700818 if (*dropReason != DROP_REASON_NOT_DROPPED) {
Jeff Brown3122e442010-10-11 23:32:49 -0700819 setInjectionResultLocked(entry, *dropReason == DROP_REASON_POLICY
820 ? INPUT_EVENT_INJECTION_SUCCEEDED : INPUT_EVENT_INJECTION_FAILED);
Jeff Brown54a18252010-09-16 14:07:33 -0700821 return true;
822 }
823
Jeff Brownb88102f2010-09-08 11:49:43 -0700824 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
825
826 // Identify targets.
Jeff Browne9bb9be2012-02-06 15:47:55 -0800827 Vector<InputTarget> inputTargets;
828
Jeff Browncc0c1592011-02-19 05:07:28 -0800829 bool conflictingPointerActions = false;
Jeff Browne9bb9be2012-02-06 15:47:55 -0800830 int32_t injectionResult;
831 if (isPointerEvent) {
832 // Pointer event. (eg. touchscreen)
833 injectionResult = findTouchedWindowTargetsLocked(currentTime,
834 entry, inputTargets, nextWakeupTime, &conflictingPointerActions);
835 } else {
836 // Non touch event. (eg. trackball)
837 injectionResult = findFocusedWindowTargetsLocked(currentTime,
838 entry, inputTargets, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700839 }
Jeff Browne9bb9be2012-02-06 15:47:55 -0800840 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
841 return false;
842 }
843
844 setInjectionResultLocked(entry, injectionResult);
845 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
846 return true;
847 }
848
Jeff Brown83d616a2012-09-09 20:33:43 -0700849 // TODO: support sending secondary display events to input monitors
850 if (isMainDisplay(entry->displayId)) {
851 addMonitoringTargetsLocked(inputTargets);
852 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700853
854 // Dispatch the motion.
Jeff Browncc0c1592011-02-19 05:07:28 -0800855 if (conflictingPointerActions) {
Jeff Brownda3d5a92011-03-29 15:11:34 -0700856 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
857 "conflicting pointer actions");
858 synthesizeCancelationEventsForAllConnectionsLocked(options);
Jeff Browncc0c1592011-02-19 05:07:28 -0800859 }
Jeff Browne9bb9be2012-02-06 15:47:55 -0800860 dispatchEventLocked(currentTime, entry, inputTargets);
Jeff Brownb88102f2010-09-08 11:49:43 -0700861 return true;
862}
863
864
865void InputDispatcher::logOutboundMotionDetailsLocked(const char* prefix, const MotionEntry* entry) {
866#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +0000867 ALOGD("%seventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, "
Jeff Brown85a31762010-09-01 17:01:00 -0700868 "action=0x%x, flags=0x%x, "
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700869 "metaState=0x%x, buttonState=0x%x, "
870 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%lld",
Jeff Brownb88102f2010-09-08 11:49:43 -0700871 prefix,
Jeff Brown85a31762010-09-01 17:01:00 -0700872 entry->eventTime, entry->deviceId, entry->source, entry->policyFlags,
873 entry->action, entry->flags,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700874 entry->metaState, entry->buttonState,
875 entry->edgeFlags, entry->xPrecision, entry->yPrecision,
Jeff Brown46b9ac02010-04-22 18:58:52 -0700876 entry->downTime);
877
Jeff Brown46b9ac02010-04-22 18:58:52 -0700878 for (uint32_t i = 0; i < entry->pointerCount; i++) {
Steve Block5baa3a62011-12-20 16:23:08 +0000879 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700880 "x=%f, y=%f, pressure=%f, size=%f, "
Jeff Brown85a31762010-09-01 17:01:00 -0700881 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
Jeff Brown8d608662010-08-30 03:02:23 -0700882 "orientation=%f",
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700883 i, entry->pointerProperties[i].id,
884 entry->pointerProperties[i].toolType,
Jeff Brown3241b6b2012-02-03 15:08:02 -0800885 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
886 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
887 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
888 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
889 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
890 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
891 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
892 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
893 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Jeff Brown46b9ac02010-04-22 18:58:52 -0700894 }
895#endif
Jeff Brown46b9ac02010-04-22 18:58:52 -0700896}
897
Jeff Browne9bb9be2012-02-06 15:47:55 -0800898void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
899 EventEntry* eventEntry, const Vector<InputTarget>& inputTargets) {
Jeff Brown46b9ac02010-04-22 18:58:52 -0700900#if DEBUG_DISPATCH_CYCLE
Jeff Brown3241b6b2012-02-03 15:08:02 -0800901 ALOGD("dispatchEventToCurrentInputTargets");
Jeff Brown46b9ac02010-04-22 18:58:52 -0700902#endif
903
Steve Blockec193de2012-01-09 18:35:44 +0000904 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
Jeff Brown9c3cda02010-06-15 01:31:58 -0700905
Jeff Browne2fe69e2010-10-18 13:21:23 -0700906 pokeUserActivityLocked(eventEntry);
907
Jeff Browne9bb9be2012-02-06 15:47:55 -0800908 for (size_t i = 0; i < inputTargets.size(); i++) {
909 const InputTarget& inputTarget = inputTargets.itemAt(i);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700910
Jeff Brown519e0242010-09-15 15:18:56 -0700911 ssize_t connectionIndex = getConnectionIndexLocked(inputTarget.inputChannel);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700912 if (connectionIndex >= 0) {
Jeff Browncbee6d62012-02-03 20:11:27 -0800913 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
Jeff Brown3241b6b2012-02-03 15:08:02 -0800914 prepareDispatchCycleLocked(currentTime, connection, eventEntry, &inputTarget);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700915 } else {
Jeff Brownb6997262010-10-08 22:31:17 -0700916#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +0000917 ALOGD("Dropping event delivery to target with channel '%s' because it "
Jeff Brownb6997262010-10-08 22:31:17 -0700918 "is no longer registered with the input dispatcher.",
Jeff Brown46b9ac02010-04-22 18:58:52 -0700919 inputTarget.inputChannel->getName().string());
Jeff Brownb6997262010-10-08 22:31:17 -0700920#endif
Jeff Brown46b9ac02010-04-22 18:58:52 -0700921 }
922 }
923}
924
Jeff Brownb88102f2010-09-08 11:49:43 -0700925int32_t InputDispatcher::handleTargetsNotReadyLocked(nsecs_t currentTime,
Jeff Brown9302c872011-07-13 22:51:29 -0700926 const EventEntry* entry,
927 const sp<InputApplicationHandle>& applicationHandle,
928 const sp<InputWindowHandle>& windowHandle,
Jeff Brown265f1cc2012-06-11 18:01:06 -0700929 nsecs_t* nextWakeupTime, const char* reason) {
Jeff Brown9302c872011-07-13 22:51:29 -0700930 if (applicationHandle == NULL && windowHandle == NULL) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700931 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY) {
932#if DEBUG_FOCUS
Jeff Brown265f1cc2012-06-11 18:01:06 -0700933 ALOGD("Waiting for system to become ready for input. Reason: %s", reason);
Jeff Brownb88102f2010-09-08 11:49:43 -0700934#endif
935 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY;
936 mInputTargetWaitStartTime = currentTime;
937 mInputTargetWaitTimeoutTime = LONG_LONG_MAX;
938 mInputTargetWaitTimeoutExpired = false;
Jeff Brown9302c872011-07-13 22:51:29 -0700939 mInputTargetWaitApplicationHandle.clear();
Jeff Brownb88102f2010-09-08 11:49:43 -0700940 }
941 } else {
942 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
943#if DEBUG_FOCUS
Jeff Brown265f1cc2012-06-11 18:01:06 -0700944 ALOGD("Waiting for application to become ready for input: %s. Reason: %s",
945 getApplicationWindowLabelLocked(applicationHandle, windowHandle).string(),
946 reason);
Jeff Brownb88102f2010-09-08 11:49:43 -0700947#endif
Jeff Browncc4f7db2011-08-30 20:34:48 -0700948 nsecs_t timeout;
949 if (windowHandle != NULL) {
950 timeout = windowHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
951 } else if (applicationHandle != NULL) {
952 timeout = applicationHandle->getDispatchingTimeout(
953 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
954 } else {
955 timeout = DEFAULT_INPUT_DISPATCHING_TIMEOUT;
956 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700957
958 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY;
959 mInputTargetWaitStartTime = currentTime;
960 mInputTargetWaitTimeoutTime = currentTime + timeout;
961 mInputTargetWaitTimeoutExpired = false;
Jeff Brown9302c872011-07-13 22:51:29 -0700962 mInputTargetWaitApplicationHandle.clear();
Jeff Brown928e0542011-01-10 11:17:36 -0800963
Jeff Brown9302c872011-07-13 22:51:29 -0700964 if (windowHandle != NULL) {
965 mInputTargetWaitApplicationHandle = windowHandle->inputApplicationHandle;
Jeff Brown928e0542011-01-10 11:17:36 -0800966 }
Jeff Brown9302c872011-07-13 22:51:29 -0700967 if (mInputTargetWaitApplicationHandle == NULL && applicationHandle != NULL) {
968 mInputTargetWaitApplicationHandle = applicationHandle;
Jeff Brown928e0542011-01-10 11:17:36 -0800969 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700970 }
971 }
972
973 if (mInputTargetWaitTimeoutExpired) {
974 return INPUT_EVENT_INJECTION_TIMED_OUT;
975 }
976
977 if (currentTime >= mInputTargetWaitTimeoutTime) {
Jeff Brown9302c872011-07-13 22:51:29 -0700978 onANRLocked(currentTime, applicationHandle, windowHandle,
Jeff Brown265f1cc2012-06-11 18:01:06 -0700979 entry->eventTime, mInputTargetWaitStartTime, reason);
Jeff Brownb88102f2010-09-08 11:49:43 -0700980
981 // Force poll loop to wake up immediately on next iteration once we get the
982 // ANR response back from the policy.
983 *nextWakeupTime = LONG_LONG_MIN;
984 return INPUT_EVENT_INJECTION_PENDING;
985 } else {
986 // Force poll loop to wake up when timeout is due.
987 if (mInputTargetWaitTimeoutTime < *nextWakeupTime) {
988 *nextWakeupTime = mInputTargetWaitTimeoutTime;
989 }
990 return INPUT_EVENT_INJECTION_PENDING;
991 }
992}
993
Jeff Brown519e0242010-09-15 15:18:56 -0700994void InputDispatcher::resumeAfterTargetsNotReadyTimeoutLocked(nsecs_t newTimeout,
995 const sp<InputChannel>& inputChannel) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700996 if (newTimeout > 0) {
997 // Extend the timeout.
998 mInputTargetWaitTimeoutTime = now() + newTimeout;
999 } else {
1000 // Give up.
1001 mInputTargetWaitTimeoutExpired = true;
Jeff Brown519e0242010-09-15 15:18:56 -07001002
1003 // Input state will not be realistic. Mark it out of sync.
Jeff Browndc3e0052010-09-16 11:02:16 -07001004 if (inputChannel.get()) {
1005 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
1006 if (connectionIndex >= 0) {
Jeff Browncbee6d62012-02-03 20:11:27 -08001007 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
Jeff Brownf44e3942012-04-20 11:33:27 -07001008 sp<InputWindowHandle> windowHandle = connection->inputWindowHandle;
1009
1010 if (windowHandle != NULL) {
1011 mTouchState.removeWindow(windowHandle);
1012 }
1013
Jeff Brown00045a72010-12-09 18:10:30 -08001014 if (connection->status == Connection::STATUS_NORMAL) {
Jeff Brownda3d5a92011-03-29 15:11:34 -07001015 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
Jeff Brown00045a72010-12-09 18:10:30 -08001016 "application not responding");
Jeff Brownda3d5a92011-03-29 15:11:34 -07001017 synthesizeCancelationEventsForConnectionLocked(connection, options);
Jeff Brown00045a72010-12-09 18:10:30 -08001018 }
Jeff Browndc3e0052010-09-16 11:02:16 -07001019 }
Jeff Brown519e0242010-09-15 15:18:56 -07001020 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001021 }
1022}
1023
Jeff Brown519e0242010-09-15 15:18:56 -07001024nsecs_t InputDispatcher::getTimeSpentWaitingForApplicationLocked(
Jeff Brownb88102f2010-09-08 11:49:43 -07001025 nsecs_t currentTime) {
1026 if (mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
1027 return currentTime - mInputTargetWaitStartTime;
1028 }
1029 return 0;
1030}
1031
1032void InputDispatcher::resetANRTimeoutsLocked() {
1033#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001034 ALOGD("Resetting ANR timeouts.");
Jeff Brownb88102f2010-09-08 11:49:43 -07001035#endif
1036
Jeff Brownb88102f2010-09-08 11:49:43 -07001037 // Reset input target wait timeout.
1038 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_NONE;
Jeff Brown5ea29ab2011-07-27 11:50:51 -07001039 mInputTargetWaitApplicationHandle.clear();
Jeff Brownb88102f2010-09-08 11:49:43 -07001040}
1041
Jeff Brown01ce2e92010-09-26 22:20:12 -07001042int32_t InputDispatcher::findFocusedWindowTargetsLocked(nsecs_t currentTime,
Jeff Browne9bb9be2012-02-06 15:47:55 -08001043 const EventEntry* entry, Vector<InputTarget>& inputTargets, nsecs_t* nextWakeupTime) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001044 int32_t injectionResult;
1045
1046 // If there is no currently focused window and no focused application
1047 // then drop the event.
Jeff Brown9302c872011-07-13 22:51:29 -07001048 if (mFocusedWindowHandle == NULL) {
1049 if (mFocusedApplicationHandle != NULL) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001050 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brown265f1cc2012-06-11 18:01:06 -07001051 mFocusedApplicationHandle, NULL, nextWakeupTime,
1052 "Waiting because no window has focus but there is a "
1053 "focused application that may eventually add a window "
1054 "when it finishes starting up.");
Jeff Brownb88102f2010-09-08 11:49:43 -07001055 goto Unresponsive;
1056 }
1057
Steve Block6215d3f2012-01-04 20:05:49 +00001058 ALOGI("Dropping event because there is no focused window or focused application.");
Jeff Brownb88102f2010-09-08 11:49:43 -07001059 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1060 goto Failed;
1061 }
1062
1063 // Check permissions.
Jeff Brown9302c872011-07-13 22:51:29 -07001064 if (! checkInjectionPermission(mFocusedWindowHandle, entry->injectionState)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001065 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1066 goto Failed;
1067 }
1068
1069 // If the currently focused window is paused then keep waiting.
Jeff Browncc4f7db2011-08-30 20:34:48 -07001070 if (mFocusedWindowHandle->getInfo()->paused) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001071 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brown265f1cc2012-06-11 18:01:06 -07001072 mFocusedApplicationHandle, mFocusedWindowHandle, nextWakeupTime,
1073 "Waiting because the focused window is paused.");
Jeff Brownb88102f2010-09-08 11:49:43 -07001074 goto Unresponsive;
1075 }
1076
Jeff Brown519e0242010-09-15 15:18:56 -07001077 // If the currently focused window is still working on previous events then keep waiting.
Jeff Brown0952c302012-02-13 13:48:59 -08001078 if (!isWindowReadyForMoreInputLocked(currentTime, mFocusedWindowHandle, entry)) {
Jeff Brown519e0242010-09-15 15:18:56 -07001079 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brown265f1cc2012-06-11 18:01:06 -07001080 mFocusedApplicationHandle, mFocusedWindowHandle, nextWakeupTime,
1081 "Waiting because the focused window has not finished "
1082 "processing the input events that were previously delivered to it.");
Jeff Brown519e0242010-09-15 15:18:56 -07001083 goto Unresponsive;
1084 }
1085
Jeff Brownb88102f2010-09-08 11:49:43 -07001086 // Success! Output targets.
1087 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
Jeff Brown9302c872011-07-13 22:51:29 -07001088 addWindowTargetLocked(mFocusedWindowHandle,
Jeff Browne9bb9be2012-02-06 15:47:55 -08001089 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS, BitSet32(0),
1090 inputTargets);
Jeff Brownb88102f2010-09-08 11:49:43 -07001091
1092 // Done.
1093Failed:
1094Unresponsive:
Jeff Brown519e0242010-09-15 15:18:56 -07001095 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
1096 updateDispatchStatisticsLocked(currentTime, entry,
1097 injectionResult, timeSpentWaitingForApplication);
Jeff Brownb88102f2010-09-08 11:49:43 -07001098#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001099 ALOGD("findFocusedWindow finished: injectionResult=%d, "
Jeff Brown22aa5122012-06-17 12:01:06 -07001100 "timeSpentWaitingForApplication=%0.1fms",
Jeff Brown519e0242010-09-15 15:18:56 -07001101 injectionResult, timeSpentWaitingForApplication / 1000000.0);
Jeff Brownb88102f2010-09-08 11:49:43 -07001102#endif
1103 return injectionResult;
1104}
1105
Jeff Brown01ce2e92010-09-26 22:20:12 -07001106int32_t InputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime,
Jeff Browne9bb9be2012-02-06 15:47:55 -08001107 const MotionEntry* entry, Vector<InputTarget>& inputTargets, nsecs_t* nextWakeupTime,
1108 bool* outConflictingPointerActions) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001109 enum InjectionPermission {
1110 INJECTION_PERMISSION_UNKNOWN,
1111 INJECTION_PERMISSION_GRANTED,
1112 INJECTION_PERMISSION_DENIED
1113 };
1114
Jeff Brownb88102f2010-09-08 11:49:43 -07001115 nsecs_t startTime = now();
1116
1117 // For security reasons, we defer updating the touch state until we are sure that
1118 // event injection will be allowed.
1119 //
1120 // FIXME In the original code, screenWasOff could never be set to true.
1121 // The reason is that the POLICY_FLAG_WOKE_HERE
1122 // and POLICY_FLAG_BRIGHT_HERE flags were set only when preprocessing raw
1123 // EV_KEY, EV_REL and EV_ABS events. As it happens, the touch event was
1124 // actually enqueued using the policyFlags that appeared in the final EV_SYN
1125 // events upon which no preprocessing took place. So policyFlags was always 0.
1126 // In the new native input dispatcher we're a bit more careful about event
1127 // preprocessing so the touches we receive can actually have non-zero policyFlags.
1128 // Unfortunately we obtain undesirable behavior.
1129 //
1130 // Here's what happens:
1131 //
1132 // When the device dims in anticipation of going to sleep, touches
1133 // in windows which have FLAG_TOUCHABLE_WHEN_WAKING cause
1134 // the device to brighten and reset the user activity timer.
1135 // Touches on other windows (such as the launcher window)
1136 // are dropped. Then after a moment, the device goes to sleep. Oops.
1137 //
1138 // Also notice how screenWasOff was being initialized using POLICY_FLAG_BRIGHT_HERE
1139 // instead of POLICY_FLAG_WOKE_HERE...
1140 //
1141 bool screenWasOff = false; // original policy: policyFlags & POLICY_FLAG_BRIGHT_HERE;
1142
Jeff Brown83d616a2012-09-09 20:33:43 -07001143 int32_t displayId = entry->displayId;
Jeff Brownb88102f2010-09-08 11:49:43 -07001144 int32_t action = entry->action;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001145 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Jeff Brownb88102f2010-09-08 11:49:43 -07001146
1147 // Update the touch state as needed based on the properties of the touch event.
Jeff Brown01ce2e92010-09-26 22:20:12 -07001148 int32_t injectionResult = INPUT_EVENT_INJECTION_PENDING;
1149 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
Jeff Brown9302c872011-07-13 22:51:29 -07001150 sp<InputWindowHandle> newHoverWindowHandle;
Jeff Browncc0c1592011-02-19 05:07:28 -08001151
1152 bool isSplit = mTouchState.split;
Jeff Brown83d616a2012-09-09 20:33:43 -07001153 bool switchedDevice = mTouchState.deviceId >= 0 && mTouchState.displayId >= 0
Jeff Brown2717eff2011-06-30 23:53:07 -07001154 && (mTouchState.deviceId != entry->deviceId
Jeff Brown83d616a2012-09-09 20:33:43 -07001155 || mTouchState.source != entry->source
1156 || mTouchState.displayId != displayId);
Jeff Browna032cc02011-03-07 16:56:21 -08001157 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE
1158 || maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER
1159 || maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1160 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN
1161 || maskedAction == AMOTION_EVENT_ACTION_SCROLL
1162 || isHoverAction);
Jeff Brown81346812011-06-28 20:08:48 -07001163 bool wrongDevice = false;
Jeff Browna032cc02011-03-07 16:56:21 -08001164 if (newGesture) {
Jeff Browncc0c1592011-02-19 05:07:28 -08001165 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Jeff Brown81346812011-06-28 20:08:48 -07001166 if (switchedDevice && mTouchState.down && !down) {
1167#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001168 ALOGD("Dropping event because a pointer for a different device is already down.");
Jeff Brown81346812011-06-28 20:08:48 -07001169#endif
Jeff Browncc0c1592011-02-19 05:07:28 -08001170 mTempTouchState.copyFrom(mTouchState);
Jeff Brown81346812011-06-28 20:08:48 -07001171 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1172 switchedDevice = false;
1173 wrongDevice = true;
1174 goto Failed;
Jeff Browncc0c1592011-02-19 05:07:28 -08001175 }
Jeff Brown81346812011-06-28 20:08:48 -07001176 mTempTouchState.reset();
1177 mTempTouchState.down = down;
1178 mTempTouchState.deviceId = entry->deviceId;
1179 mTempTouchState.source = entry->source;
Jeff Brown83d616a2012-09-09 20:33:43 -07001180 mTempTouchState.displayId = displayId;
Jeff Brown81346812011-06-28 20:08:48 -07001181 isSplit = false;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001182 } else {
1183 mTempTouchState.copyFrom(mTouchState);
Jeff Browncc0c1592011-02-19 05:07:28 -08001184 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001185
Jeff Browna032cc02011-03-07 16:56:21 -08001186 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
Jeff Brown33bbfd22011-02-24 20:55:35 -08001187 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
Jeff Brownb88102f2010-09-08 11:49:43 -07001188
Jeff Brown01ce2e92010-09-26 22:20:12 -07001189 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Jeff Brown3241b6b2012-02-03 15:08:02 -08001190 int32_t x = int32_t(entry->pointerCoords[pointerIndex].
Jeff Brownebbd5d12011-02-17 13:01:34 -08001191 getAxisValue(AMOTION_EVENT_AXIS_X));
Jeff Brown3241b6b2012-02-03 15:08:02 -08001192 int32_t y = int32_t(entry->pointerCoords[pointerIndex].
Jeff Brownebbd5d12011-02-17 13:01:34 -08001193 getAxisValue(AMOTION_EVENT_AXIS_Y));
Jeff Brown9302c872011-07-13 22:51:29 -07001194 sp<InputWindowHandle> newTouchedWindowHandle;
1195 sp<InputWindowHandle> topErrorWindowHandle;
Jeff Browna032cc02011-03-07 16:56:21 -08001196 bool isTouchModal = false;
Jeff Brownb88102f2010-09-08 11:49:43 -07001197
1198 // Traverse windows from front to back to find touched window and outside targets.
Jeff Brown9302c872011-07-13 22:51:29 -07001199 size_t numWindows = mWindowHandles.size();
Jeff Brownb88102f2010-09-08 11:49:43 -07001200 for (size_t i = 0; i < numWindows; i++) {
Jeff Brown9302c872011-07-13 22:51:29 -07001201 sp<InputWindowHandle> windowHandle = mWindowHandles.itemAt(i);
Jeff Browncc4f7db2011-08-30 20:34:48 -07001202 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Jeff Brown83d616a2012-09-09 20:33:43 -07001203 if (windowInfo->displayId != displayId) {
1204 continue; // wrong display
1205 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001206
Jeff Brown83d616a2012-09-09 20:33:43 -07001207 int32_t flags = windowInfo->layoutParamsFlags;
Jeff Browncc4f7db2011-08-30 20:34:48 -07001208 if (flags & InputWindowInfo::FLAG_SYSTEM_ERROR) {
Jeff Brown9302c872011-07-13 22:51:29 -07001209 if (topErrorWindowHandle == NULL) {
1210 topErrorWindowHandle = windowHandle;
Jeff Brownb88102f2010-09-08 11:49:43 -07001211 }
1212 }
1213
Jeff Browncc4f7db2011-08-30 20:34:48 -07001214 if (windowInfo->visible) {
1215 if (! (flags & InputWindowInfo::FLAG_NOT_TOUCHABLE)) {
1216 isTouchModal = (flags & (InputWindowInfo::FLAG_NOT_FOCUSABLE
1217 | InputWindowInfo::FLAG_NOT_TOUCH_MODAL)) == 0;
1218 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
Jeff Brown9302c872011-07-13 22:51:29 -07001219 if (! screenWasOff
Jeff Browncc4f7db2011-08-30 20:34:48 -07001220 || (flags & InputWindowInfo::FLAG_TOUCHABLE_WHEN_WAKING)) {
Jeff Brown9302c872011-07-13 22:51:29 -07001221 newTouchedWindowHandle = windowHandle;
Jeff Brownb88102f2010-09-08 11:49:43 -07001222 }
1223 break; // found touched window, exit window loop
1224 }
1225 }
1226
Jeff Brown01ce2e92010-09-26 22:20:12 -07001227 if (maskedAction == AMOTION_EVENT_ACTION_DOWN
Jeff Browncc4f7db2011-08-30 20:34:48 -07001228 && (flags & InputWindowInfo::FLAG_WATCH_OUTSIDE_TOUCH)) {
Jeff Browna032cc02011-03-07 16:56:21 -08001229 int32_t outsideTargetFlags = InputTarget::FLAG_DISPATCH_AS_OUTSIDE;
Jeff Brown9302c872011-07-13 22:51:29 -07001230 if (isWindowObscuredAtPointLocked(windowHandle, x, y)) {
Jeff Brown19dfc832010-10-05 12:26:23 -07001231 outsideTargetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1232 }
1233
Jeff Brown9302c872011-07-13 22:51:29 -07001234 mTempTouchState.addOrUpdateWindow(
1235 windowHandle, outsideTargetFlags, BitSet32(0));
Jeff Brownb88102f2010-09-08 11:49:43 -07001236 }
1237 }
1238 }
1239
1240 // If there is an error window but it is not taking focus (typically because
1241 // it is invisible) then wait for it. Any other focused window may in
1242 // fact be in ANR state.
Jeff Brown9302c872011-07-13 22:51:29 -07001243 if (topErrorWindowHandle != NULL && newTouchedWindowHandle != topErrorWindowHandle) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001244 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brown265f1cc2012-06-11 18:01:06 -07001245 NULL, NULL, nextWakeupTime,
1246 "Waiting because a system error window is about to be displayed.");
Jeff Brownb88102f2010-09-08 11:49:43 -07001247 injectionPermission = INJECTION_PERMISSION_UNKNOWN;
1248 goto Unresponsive;
1249 }
1250
Jeff Brown01ce2e92010-09-26 22:20:12 -07001251 // Figure out whether splitting will be allowed for this window.
Jeff Browncc4f7db2011-08-30 20:34:48 -07001252 if (newTouchedWindowHandle != NULL
1253 && newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001254 // New window supports splitting.
1255 isSplit = true;
1256 } else if (isSplit) {
1257 // New window does not support splitting but we have already split events.
Jeff Brown8249fc62012-05-24 18:57:32 -07001258 // Ignore the new window.
1259 newTouchedWindowHandle = NULL;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001260 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001261
Jeff Brown8249fc62012-05-24 18:57:32 -07001262 // Handle the case where we did not find a window.
Jeff Brown9302c872011-07-13 22:51:29 -07001263 if (newTouchedWindowHandle == NULL) {
Jeff Brown8249fc62012-05-24 18:57:32 -07001264 // Try to assign the pointer to the first foreground window we find, if there is one.
1265 newTouchedWindowHandle = mTempTouchState.getFirstForegroundWindowHandle();
1266 if (newTouchedWindowHandle == NULL) {
1267 // There is no touched window. If this is an initial down event
1268 // then wait for a window to appear that will handle the touch. This is
1269 // to ensure that we report an ANR in the case where an application has started
1270 // but not yet put up a window and the user is starting to get impatient.
1271 if (maskedAction == AMOTION_EVENT_ACTION_DOWN
1272 && mFocusedApplicationHandle != NULL) {
Jeff Brown8249fc62012-05-24 18:57:32 -07001273 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brown265f1cc2012-06-11 18:01:06 -07001274 mFocusedApplicationHandle, NULL, nextWakeupTime,
1275 "Waiting because there is no touchable window that can "
1276 "handle the event but there is focused application that may "
1277 "eventually add a new window when it finishes starting up.");
Jeff Brown8249fc62012-05-24 18:57:32 -07001278 goto Unresponsive;
1279 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001280
Jeff Brown8249fc62012-05-24 18:57:32 -07001281 ALOGI("Dropping event because there is no touched window.");
1282 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1283 goto Failed;
1284 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001285 }
1286
Jeff Brown19dfc832010-10-05 12:26:23 -07001287 // Set target flags.
Jeff Browna032cc02011-03-07 16:56:21 -08001288 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
Jeff Brown19dfc832010-10-05 12:26:23 -07001289 if (isSplit) {
1290 targetFlags |= InputTarget::FLAG_SPLIT;
1291 }
Jeff Brown9302c872011-07-13 22:51:29 -07001292 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
Jeff Brown19dfc832010-10-05 12:26:23 -07001293 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1294 }
1295
Jeff Browna032cc02011-03-07 16:56:21 -08001296 // Update hover state.
1297 if (isHoverAction) {
Jeff Brown9302c872011-07-13 22:51:29 -07001298 newHoverWindowHandle = newTouchedWindowHandle;
Jeff Browna032cc02011-03-07 16:56:21 -08001299 } else if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
Jeff Brown9302c872011-07-13 22:51:29 -07001300 newHoverWindowHandle = mLastHoverWindowHandle;
Jeff Browna032cc02011-03-07 16:56:21 -08001301 }
1302
Jeff Brown01ce2e92010-09-26 22:20:12 -07001303 // Update the temporary touch state.
1304 BitSet32 pointerIds;
1305 if (isSplit) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07001306 uint32_t pointerId = entry->pointerProperties[pointerIndex].id;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001307 pointerIds.markBit(pointerId);
Jeff Brownb88102f2010-09-08 11:49:43 -07001308 }
Jeff Brown9302c872011-07-13 22:51:29 -07001309 mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Jeff Brownb88102f2010-09-08 11:49:43 -07001310 } else {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001311 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
Jeff Brownb88102f2010-09-08 11:49:43 -07001312
1313 // If the pointer is not currently down, then ignore the event.
Jeff Brown01ce2e92010-09-26 22:20:12 -07001314 if (! mTempTouchState.down) {
Jeff Browna2cc28d2011-03-25 11:58:46 -07001315#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001316 ALOGD("Dropping event because the pointer is not down or we previously "
Jeff Brown76860e32010-10-25 17:37:46 -07001317 "dropped the pointer down event.");
1318#endif
Jeff Brownb88102f2010-09-08 11:49:43 -07001319 injectionResult = INPUT_EVENT_INJECTION_FAILED;
Jeff Brownb88102f2010-09-08 11:49:43 -07001320 goto Failed;
1321 }
Jeff Brown98db5fa2011-06-08 15:37:10 -07001322
1323 // Check whether touches should slip outside of the current foreground window.
1324 if (maskedAction == AMOTION_EVENT_ACTION_MOVE
1325 && entry->pointerCount == 1
1326 && mTempTouchState.isSlippery()) {
Jeff Brown3241b6b2012-02-03 15:08:02 -08001327 int32_t x = int32_t(entry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
1328 int32_t y = int32_t(entry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Jeff Brown98db5fa2011-06-08 15:37:10 -07001329
Jeff Brown9302c872011-07-13 22:51:29 -07001330 sp<InputWindowHandle> oldTouchedWindowHandle =
1331 mTempTouchState.getFirstForegroundWindowHandle();
Jeff Brown83d616a2012-09-09 20:33:43 -07001332 sp<InputWindowHandle> newTouchedWindowHandle =
1333 findTouchedWindowAtLocked(displayId, x, y);
Jeff Brown9302c872011-07-13 22:51:29 -07001334 if (oldTouchedWindowHandle != newTouchedWindowHandle
1335 && newTouchedWindowHandle != NULL) {
Jeff Brown98db5fa2011-06-08 15:37:10 -07001336#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001337 ALOGD("Touch is slipping out of window %s into window %s.",
Jeff Browncc4f7db2011-08-30 20:34:48 -07001338 oldTouchedWindowHandle->getName().string(),
1339 newTouchedWindowHandle->getName().string());
Jeff Brown98db5fa2011-06-08 15:37:10 -07001340#endif
1341 // Make a slippery exit from the old window.
Jeff Brown9302c872011-07-13 22:51:29 -07001342 mTempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
Jeff Brown98db5fa2011-06-08 15:37:10 -07001343 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT, BitSet32(0));
1344
1345 // Make a slippery entrance into the new window.
Jeff Browncc4f7db2011-08-30 20:34:48 -07001346 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Jeff Brown98db5fa2011-06-08 15:37:10 -07001347 isSplit = true;
1348 }
1349
1350 int32_t targetFlags = InputTarget::FLAG_FOREGROUND
1351 | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
1352 if (isSplit) {
1353 targetFlags |= InputTarget::FLAG_SPLIT;
1354 }
Jeff Brown9302c872011-07-13 22:51:29 -07001355 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
Jeff Brown98db5fa2011-06-08 15:37:10 -07001356 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1357 }
1358
1359 BitSet32 pointerIds;
1360 if (isSplit) {
1361 pointerIds.markBit(entry->pointerProperties[0].id);
1362 }
Jeff Brown9302c872011-07-13 22:51:29 -07001363 mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Jeff Brown98db5fa2011-06-08 15:37:10 -07001364 }
1365 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001366 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001367
Jeff Brown9302c872011-07-13 22:51:29 -07001368 if (newHoverWindowHandle != mLastHoverWindowHandle) {
Jeff Browna032cc02011-03-07 16:56:21 -08001369 // Let the previous window know that the hover sequence is over.
Jeff Brown9302c872011-07-13 22:51:29 -07001370 if (mLastHoverWindowHandle != NULL) {
Jeff Browna032cc02011-03-07 16:56:21 -08001371#if DEBUG_HOVER
Steve Block5baa3a62011-12-20 16:23:08 +00001372 ALOGD("Sending hover exit event to window %s.",
Jeff Browncc4f7db2011-08-30 20:34:48 -07001373 mLastHoverWindowHandle->getName().string());
Jeff Browna032cc02011-03-07 16:56:21 -08001374#endif
Jeff Brown9302c872011-07-13 22:51:29 -07001375 mTempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
Jeff Browna032cc02011-03-07 16:56:21 -08001376 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
1377 }
1378
1379 // Let the new window know that the hover sequence is starting.
Jeff Brown9302c872011-07-13 22:51:29 -07001380 if (newHoverWindowHandle != NULL) {
Jeff Browna032cc02011-03-07 16:56:21 -08001381#if DEBUG_HOVER
Steve Block5baa3a62011-12-20 16:23:08 +00001382 ALOGD("Sending hover enter event to window %s.",
Jeff Browncc4f7db2011-08-30 20:34:48 -07001383 newHoverWindowHandle->getName().string());
Jeff Browna032cc02011-03-07 16:56:21 -08001384#endif
Jeff Brown9302c872011-07-13 22:51:29 -07001385 mTempTouchState.addOrUpdateWindow(newHoverWindowHandle,
Jeff Browna032cc02011-03-07 16:56:21 -08001386 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER, BitSet32(0));
1387 }
1388 }
1389
Jeff Brown01ce2e92010-09-26 22:20:12 -07001390 // Check permission to inject into all touched foreground windows and ensure there
1391 // is at least one touched foreground window.
1392 {
1393 bool haveForegroundWindow = false;
1394 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1395 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1396 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1397 haveForegroundWindow = true;
Jeff Brown9302c872011-07-13 22:51:29 -07001398 if (! checkInjectionPermission(touchedWindow.windowHandle,
1399 entry->injectionState)) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001400 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1401 injectionPermission = INJECTION_PERMISSION_DENIED;
1402 goto Failed;
1403 }
1404 }
1405 }
1406 if (! haveForegroundWindow) {
Jeff Browna2cc28d2011-03-25 11:58:46 -07001407#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001408 ALOGD("Dropping event because there is no touched foreground window to receive it.");
Jeff Brownb88102f2010-09-08 11:49:43 -07001409#endif
1410 injectionResult = INPUT_EVENT_INJECTION_FAILED;
Jeff Brownb88102f2010-09-08 11:49:43 -07001411 goto Failed;
1412 }
1413
Jeff Brown01ce2e92010-09-26 22:20:12 -07001414 // Permission granted to injection into all touched foreground windows.
1415 injectionPermission = INJECTION_PERMISSION_GRANTED;
1416 }
Jeff Brown519e0242010-09-15 15:18:56 -07001417
Kenny Root7a9db182011-06-02 15:16:05 -07001418 // Check whether windows listening for outside touches are owned by the same UID. If it is
1419 // set the policy flag that we will not reveal coordinate information to this window.
1420 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
Jeff Brown9302c872011-07-13 22:51:29 -07001421 sp<InputWindowHandle> foregroundWindowHandle =
1422 mTempTouchState.getFirstForegroundWindowHandle();
Jeff Browncc4f7db2011-08-30 20:34:48 -07001423 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Kenny Root7a9db182011-06-02 15:16:05 -07001424 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1425 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1426 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
Jeff Brown9302c872011-07-13 22:51:29 -07001427 sp<InputWindowHandle> inputWindowHandle = touchedWindow.windowHandle;
Jeff Browncc4f7db2011-08-30 20:34:48 -07001428 if (inputWindowHandle->getInfo()->ownerUid != foregroundWindowUid) {
Jeff Brown9302c872011-07-13 22:51:29 -07001429 mTempTouchState.addOrUpdateWindow(inputWindowHandle,
Kenny Root7a9db182011-06-02 15:16:05 -07001430 InputTarget::FLAG_ZERO_COORDS, BitSet32(0));
1431 }
1432 }
1433 }
1434 }
1435
Jeff Brown01ce2e92010-09-26 22:20:12 -07001436 // Ensure all touched foreground windows are ready for new input.
1437 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1438 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1439 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1440 // If the touched window is paused then keep waiting.
Jeff Browncc4f7db2011-08-30 20:34:48 -07001441 if (touchedWindow.windowHandle->getInfo()->paused) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001442 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brown265f1cc2012-06-11 18:01:06 -07001443 NULL, touchedWindow.windowHandle, nextWakeupTime,
1444 "Waiting because the touched window is paused.");
Jeff Brown01ce2e92010-09-26 22:20:12 -07001445 goto Unresponsive;
1446 }
1447
1448 // If the touched window is still working on previous events then keep waiting.
Jeff Brown0952c302012-02-13 13:48:59 -08001449 if (!isWindowReadyForMoreInputLocked(currentTime, touchedWindow.windowHandle, entry)) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001450 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brown265f1cc2012-06-11 18:01:06 -07001451 NULL, touchedWindow.windowHandle, nextWakeupTime,
1452 "Waiting because the touched window has not finished "
1453 "processing the input events that were previously delivered to it.");
Jeff Brown01ce2e92010-09-26 22:20:12 -07001454 goto Unresponsive;
1455 }
1456 }
1457 }
1458
1459 // If this is the first pointer going down and the touched window has a wallpaper
1460 // then also add the touched wallpaper windows so they are locked in for the duration
1461 // of the touch gesture.
Jeff Brown33bbfd22011-02-24 20:55:35 -08001462 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
1463 // engine only supports touch events. We would need to add a mechanism similar
1464 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
1465 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
Jeff Brown9302c872011-07-13 22:51:29 -07001466 sp<InputWindowHandle> foregroundWindowHandle =
1467 mTempTouchState.getFirstForegroundWindowHandle();
Jeff Browncc4f7db2011-08-30 20:34:48 -07001468 if (foregroundWindowHandle->getInfo()->hasWallpaper) {
Jeff Brown9302c872011-07-13 22:51:29 -07001469 for (size_t i = 0; i < mWindowHandles.size(); i++) {
1470 sp<InputWindowHandle> windowHandle = mWindowHandles.itemAt(i);
Jeff Brown83d616a2012-09-09 20:33:43 -07001471 const InputWindowInfo* info = windowHandle->getInfo();
1472 if (info->displayId == displayId
1473 && windowHandle->getInfo()->layoutParamsType
1474 == InputWindowInfo::TYPE_WALLPAPER) {
Jeff Brown9302c872011-07-13 22:51:29 -07001475 mTempTouchState.addOrUpdateWindow(windowHandle,
Jeff Browna032cc02011-03-07 16:56:21 -08001476 InputTarget::FLAG_WINDOW_IS_OBSCURED
1477 | InputTarget::FLAG_DISPATCH_AS_IS,
1478 BitSet32(0));
Jeff Brown01ce2e92010-09-26 22:20:12 -07001479 }
1480 }
1481 }
1482 }
1483
Jeff Brownb88102f2010-09-08 11:49:43 -07001484 // Success! Output targets.
1485 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
Jeff Brownb88102f2010-09-08 11:49:43 -07001486
Jeff Brown01ce2e92010-09-26 22:20:12 -07001487 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1488 const TouchedWindow& touchedWindow = mTempTouchState.windows.itemAt(i);
Jeff Brown9302c872011-07-13 22:51:29 -07001489 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Jeff Browne9bb9be2012-02-06 15:47:55 -08001490 touchedWindow.pointerIds, inputTargets);
Jeff Brownb88102f2010-09-08 11:49:43 -07001491 }
1492
Jeff Browna032cc02011-03-07 16:56:21 -08001493 // Drop the outside or hover touch windows since we will not care about them
1494 // in the next iteration.
1495 mTempTouchState.filterNonAsIsTouchWindows();
Jeff Brown01ce2e92010-09-26 22:20:12 -07001496
Jeff Brownb88102f2010-09-08 11:49:43 -07001497Failed:
1498 // Check injection permission once and for all.
1499 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001500 if (checkInjectionPermission(NULL, entry->injectionState)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001501 injectionPermission = INJECTION_PERMISSION_GRANTED;
1502 } else {
1503 injectionPermission = INJECTION_PERMISSION_DENIED;
1504 }
1505 }
1506
1507 // Update final pieces of touch state if the injector had permission.
1508 if (injectionPermission == INJECTION_PERMISSION_GRANTED) {
Jeff Brown95712852011-01-04 19:41:59 -08001509 if (!wrongDevice) {
Jeff Brown81346812011-06-28 20:08:48 -07001510 if (switchedDevice) {
1511#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001512 ALOGD("Conflicting pointer actions: Switched to a different device.");
Jeff Brown81346812011-06-28 20:08:48 -07001513#endif
1514 *outConflictingPointerActions = true;
1515 }
1516
1517 if (isHoverAction) {
1518 // Started hovering, therefore no longer down.
1519 if (mTouchState.down) {
1520#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001521 ALOGD("Conflicting pointer actions: Hover received while pointer was down.");
Jeff Brown81346812011-06-28 20:08:48 -07001522#endif
1523 *outConflictingPointerActions = true;
1524 }
1525 mTouchState.reset();
1526 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER
1527 || maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
1528 mTouchState.deviceId = entry->deviceId;
1529 mTouchState.source = entry->source;
Jeff Brown83d616a2012-09-09 20:33:43 -07001530 mTouchState.displayId = displayId;
Jeff Brown81346812011-06-28 20:08:48 -07001531 }
1532 } else if (maskedAction == AMOTION_EVENT_ACTION_UP
1533 || maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Jeff Brown95712852011-01-04 19:41:59 -08001534 // All pointers up or canceled.
Jeff Brown33bbfd22011-02-24 20:55:35 -08001535 mTouchState.reset();
Jeff Brown95712852011-01-04 19:41:59 -08001536 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1537 // First pointer went down.
1538 if (mTouchState.down) {
Jeff Brownb6997262010-10-08 22:31:17 -07001539#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001540 ALOGD("Conflicting pointer actions: Down received while already down.");
Jeff Brownb6997262010-10-08 22:31:17 -07001541#endif
Jeff Brown81346812011-06-28 20:08:48 -07001542 *outConflictingPointerActions = true;
Jeff Brown95712852011-01-04 19:41:59 -08001543 }
Jeff Brown33bbfd22011-02-24 20:55:35 -08001544 mTouchState.copyFrom(mTempTouchState);
Jeff Brown95712852011-01-04 19:41:59 -08001545 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
1546 // One pointer went up.
1547 if (isSplit) {
1548 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07001549 uint32_t pointerId = entry->pointerProperties[pointerIndex].id;
Jeff Brownb88102f2010-09-08 11:49:43 -07001550
Jeff Brown95712852011-01-04 19:41:59 -08001551 for (size_t i = 0; i < mTempTouchState.windows.size(); ) {
1552 TouchedWindow& touchedWindow = mTempTouchState.windows.editItemAt(i);
1553 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
1554 touchedWindow.pointerIds.clearBit(pointerId);
1555 if (touchedWindow.pointerIds.isEmpty()) {
1556 mTempTouchState.windows.removeAt(i);
1557 continue;
1558 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001559 }
Jeff Brown95712852011-01-04 19:41:59 -08001560 i += 1;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001561 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001562 }
Jeff Brown33bbfd22011-02-24 20:55:35 -08001563 mTouchState.copyFrom(mTempTouchState);
1564 } else if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
1565 // Discard temporary touch state since it was only valid for this action.
1566 } else {
1567 // Save changes to touch state as-is for all other actions.
1568 mTouchState.copyFrom(mTempTouchState);
Jeff Brownb88102f2010-09-08 11:49:43 -07001569 }
Jeff Browna032cc02011-03-07 16:56:21 -08001570
1571 // Update hover state.
Jeff Brown9302c872011-07-13 22:51:29 -07001572 mLastHoverWindowHandle = newHoverWindowHandle;
Jeff Brown95712852011-01-04 19:41:59 -08001573 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001574 } else {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001575#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001576 ALOGD("Not updating touch focus because injection was denied.");
Jeff Brown01ce2e92010-09-26 22:20:12 -07001577#endif
Jeff Brownb88102f2010-09-08 11:49:43 -07001578 }
1579
1580Unresponsive:
Jeff Brown120a4592010-10-27 18:43:51 -07001581 // Reset temporary touch state to ensure we release unnecessary references to input channels.
1582 mTempTouchState.reset();
1583
Jeff Brown519e0242010-09-15 15:18:56 -07001584 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
1585 updateDispatchStatisticsLocked(currentTime, entry,
1586 injectionResult, timeSpentWaitingForApplication);
Jeff Brownb88102f2010-09-08 11:49:43 -07001587#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001588 ALOGD("findTouchedWindow finished: injectionResult=%d, injectionPermission=%d, "
Jeff Brown01ce2e92010-09-26 22:20:12 -07001589 "timeSpentWaitingForApplication=%0.1fms",
Jeff Brown519e0242010-09-15 15:18:56 -07001590 injectionResult, injectionPermission, timeSpentWaitingForApplication / 1000000.0);
Jeff Brownb88102f2010-09-08 11:49:43 -07001591#endif
1592 return injectionResult;
1593}
1594
Jeff Brown9302c872011-07-13 22:51:29 -07001595void InputDispatcher::addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
Jeff Browne9bb9be2012-02-06 15:47:55 -08001596 int32_t targetFlags, BitSet32 pointerIds, Vector<InputTarget>& inputTargets) {
1597 inputTargets.push();
Jeff Brownb88102f2010-09-08 11:49:43 -07001598
Jeff Browncc4f7db2011-08-30 20:34:48 -07001599 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Jeff Browne9bb9be2012-02-06 15:47:55 -08001600 InputTarget& target = inputTargets.editTop();
Jeff Browncc4f7db2011-08-30 20:34:48 -07001601 target.inputChannel = windowInfo->inputChannel;
Jeff Brownb88102f2010-09-08 11:49:43 -07001602 target.flags = targetFlags;
Jeff Browncc4f7db2011-08-30 20:34:48 -07001603 target.xOffset = - windowInfo->frameLeft;
1604 target.yOffset = - windowInfo->frameTop;
1605 target.scaleFactor = windowInfo->scaleFactor;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001606 target.pointerIds = pointerIds;
Jeff Brownb88102f2010-09-08 11:49:43 -07001607}
1608
Jeff Browne9bb9be2012-02-06 15:47:55 -08001609void InputDispatcher::addMonitoringTargetsLocked(Vector<InputTarget>& inputTargets) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001610 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
Jeff Browne9bb9be2012-02-06 15:47:55 -08001611 inputTargets.push();
Jeff Brownb88102f2010-09-08 11:49:43 -07001612
Jeff Browne9bb9be2012-02-06 15:47:55 -08001613 InputTarget& target = inputTargets.editTop();
Jeff Brownb88102f2010-09-08 11:49:43 -07001614 target.inputChannel = mMonitoringChannels[i];
Jeff Brownb6110c22011-04-01 16:15:13 -07001615 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
Jeff Brownb88102f2010-09-08 11:49:43 -07001616 target.xOffset = 0;
1617 target.yOffset = 0;
Jeff Brownb6110c22011-04-01 16:15:13 -07001618 target.pointerIds.clear();
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001619 target.scaleFactor = 1.0f;
Jeff Brownb88102f2010-09-08 11:49:43 -07001620 }
1621}
1622
Jeff Brown9302c872011-07-13 22:51:29 -07001623bool InputDispatcher::checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
Jeff Brown01ce2e92010-09-26 22:20:12 -07001624 const InjectionState* injectionState) {
1625 if (injectionState
Jeff Browncc4f7db2011-08-30 20:34:48 -07001626 && (windowHandle == NULL
1627 || windowHandle->getInfo()->ownerUid != injectionState->injectorUid)
Jeff Brownb6997262010-10-08 22:31:17 -07001628 && !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Jeff Brown9302c872011-07-13 22:51:29 -07001629 if (windowHandle != NULL) {
Steve Block8564c8d2012-01-05 23:22:43 +00001630 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
Jeff Brown9302c872011-07-13 22:51:29 -07001631 "owned by uid %d",
Jeff Brownb6997262010-10-08 22:31:17 -07001632 injectionState->injectorPid, injectionState->injectorUid,
Jeff Browncc4f7db2011-08-30 20:34:48 -07001633 windowHandle->getName().string(),
1634 windowHandle->getInfo()->ownerUid);
Jeff Brownb6997262010-10-08 22:31:17 -07001635 } else {
Steve Block8564c8d2012-01-05 23:22:43 +00001636 ALOGW("Permission denied: injecting event from pid %d uid %d",
Jeff Brownb6997262010-10-08 22:31:17 -07001637 injectionState->injectorPid, injectionState->injectorUid);
Jeff Brownb88102f2010-09-08 11:49:43 -07001638 }
Jeff Brownb6997262010-10-08 22:31:17 -07001639 return false;
Jeff Brownb88102f2010-09-08 11:49:43 -07001640 }
1641 return true;
1642}
1643
Jeff Brown19dfc832010-10-05 12:26:23 -07001644bool InputDispatcher::isWindowObscuredAtPointLocked(
Jeff Brown9302c872011-07-13 22:51:29 -07001645 const sp<InputWindowHandle>& windowHandle, int32_t x, int32_t y) const {
Jeff Brown83d616a2012-09-09 20:33:43 -07001646 int32_t displayId = windowHandle->getInfo()->displayId;
Jeff Brown9302c872011-07-13 22:51:29 -07001647 size_t numWindows = mWindowHandles.size();
Jeff Brownb88102f2010-09-08 11:49:43 -07001648 for (size_t i = 0; i < numWindows; i++) {
Jeff Brown9302c872011-07-13 22:51:29 -07001649 sp<InputWindowHandle> otherHandle = mWindowHandles.itemAt(i);
1650 if (otherHandle == windowHandle) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001651 break;
1652 }
Jeff Browncc4f7db2011-08-30 20:34:48 -07001653
1654 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Jeff Brown83d616a2012-09-09 20:33:43 -07001655 if (otherInfo->displayId == displayId
1656 && otherInfo->visible && !otherInfo->isTrustedOverlay()
Jeff Browncc4f7db2011-08-30 20:34:48 -07001657 && otherInfo->frameContainsPoint(x, y)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001658 return true;
1659 }
1660 }
1661 return false;
1662}
1663
Jeff Brownd1c48a02012-02-06 19:12:47 -08001664bool InputDispatcher::isWindowReadyForMoreInputLocked(nsecs_t currentTime,
Jeff Brown0952c302012-02-13 13:48:59 -08001665 const sp<InputWindowHandle>& windowHandle, const EventEntry* eventEntry) {
Jeff Browncc4f7db2011-08-30 20:34:48 -07001666 ssize_t connectionIndex = getConnectionIndexLocked(windowHandle->getInputChannel());
Jeff Brown519e0242010-09-15 15:18:56 -07001667 if (connectionIndex >= 0) {
Jeff Browncbee6d62012-02-03 20:11:27 -08001668 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
Jeff Brownd1c48a02012-02-06 19:12:47 -08001669 if (connection->inputPublisherBlocked) {
1670 return false;
1671 }
Jeff Brown0952c302012-02-13 13:48:59 -08001672 if (eventEntry->type == EventEntry::TYPE_KEY) {
1673 // If the event is a key event, then we must wait for all previous events to
1674 // complete before delivering it because previous events may have the
1675 // side-effect of transferring focus to a different window and we want to
1676 // ensure that the following keys are sent to the new window.
1677 //
1678 // Suppose the user touches a button in a window then immediately presses "A".
1679 // If the button causes a pop-up window to appear then we want to ensure that
1680 // the "A" key is delivered to the new pop-up window. This is because users
1681 // often anticipate pending UI changes when typing on a keyboard.
1682 // To obtain this behavior, we must serialize key events with respect to all
1683 // prior input events.
Jeff Brownd1c48a02012-02-06 19:12:47 -08001684 return connection->outboundQueue.isEmpty()
1685 && connection->waitQueue.isEmpty();
1686 }
Jeff Brown0952c302012-02-13 13:48:59 -08001687 // Touch events can always be sent to a window immediately because the user intended
1688 // to touch whatever was visible at the time. Even if focus changes or a new
1689 // window appears moments later, the touch event was meant to be delivered to
1690 // whatever window happened to be on screen at the time.
1691 //
1692 // Generic motion events, such as trackball or joystick events are a little trickier.
1693 // Like key events, generic motion events are delivered to the focused window.
1694 // Unlike key events, generic motion events don't tend to transfer focus to other
1695 // windows and it is not important for them to be serialized. So we prefer to deliver
1696 // generic motion events as soon as possible to improve efficiency and reduce lag
1697 // through batching.
1698 //
1699 // The one case where we pause input event delivery is when the wait queue is piling
1700 // up with lots of events because the application is not responding.
1701 // This condition ensures that ANRs are detected reliably.
Jeff Brownd1c48a02012-02-06 19:12:47 -08001702 if (!connection->waitQueue.isEmpty()
1703 && currentTime >= connection->waitQueue.head->eventEntry->eventTime
1704 + STREAM_AHEAD_EVENT_TIMEOUT) {
1705 return false;
1706 }
Jeff Brown519e0242010-09-15 15:18:56 -07001707 }
Jeff Brownd1c48a02012-02-06 19:12:47 -08001708 return true;
Jeff Brown519e0242010-09-15 15:18:56 -07001709}
1710
Jeff Brown9302c872011-07-13 22:51:29 -07001711String8 InputDispatcher::getApplicationWindowLabelLocked(
1712 const sp<InputApplicationHandle>& applicationHandle,
1713 const sp<InputWindowHandle>& windowHandle) {
1714 if (applicationHandle != NULL) {
1715 if (windowHandle != NULL) {
Jeff Browncc4f7db2011-08-30 20:34:48 -07001716 String8 label(applicationHandle->getName());
Jeff Brown519e0242010-09-15 15:18:56 -07001717 label.append(" - ");
Jeff Browncc4f7db2011-08-30 20:34:48 -07001718 label.append(windowHandle->getName());
Jeff Brown519e0242010-09-15 15:18:56 -07001719 return label;
1720 } else {
Jeff Browncc4f7db2011-08-30 20:34:48 -07001721 return applicationHandle->getName();
Jeff Brown519e0242010-09-15 15:18:56 -07001722 }
Jeff Brown9302c872011-07-13 22:51:29 -07001723 } else if (windowHandle != NULL) {
Jeff Browncc4f7db2011-08-30 20:34:48 -07001724 return windowHandle->getName();
Jeff Brown519e0242010-09-15 15:18:56 -07001725 } else {
1726 return String8("<unknown application or window>");
1727 }
1728}
1729
Jeff Browne2fe69e2010-10-18 13:21:23 -07001730void InputDispatcher::pokeUserActivityLocked(const EventEntry* eventEntry) {
Jeff Brown1e3b98d2012-09-30 18:58:59 -07001731 if (mFocusedWindowHandle != NULL) {
1732 const InputWindowInfo* info = mFocusedWindowHandle->getInfo();
1733 if (info->inputFeatures & InputWindowInfo::INPUT_FEATURE_DISABLE_USER_ACTIVITY) {
1734#if DEBUG_DISPATCH_CYCLE
1735 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.string());
1736#endif
1737 return;
1738 }
1739 }
1740
Jeff Brownb696de52012-07-27 15:38:50 -07001741 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Jeff Brown4d396052010-10-29 21:50:21 -07001742 switch (eventEntry->type) {
1743 case EventEntry::TYPE_MOTION: {
Jeff Browne2fe69e2010-10-18 13:21:23 -07001744 const MotionEntry* motionEntry = static_cast<const MotionEntry*>(eventEntry);
Jeff Brown4d396052010-10-29 21:50:21 -07001745 if (motionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
1746 return;
1747 }
1748
Jeff Brown56194eb2011-03-02 19:23:13 -08001749 if (MotionEvent::isTouchEvent(motionEntry->source, motionEntry->action)) {
Jeff Brownb696de52012-07-27 15:38:50 -07001750 eventType = USER_ACTIVITY_EVENT_TOUCH;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001751 }
Jeff Brown4d396052010-10-29 21:50:21 -07001752 break;
1753 }
1754 case EventEntry::TYPE_KEY: {
1755 const KeyEntry* keyEntry = static_cast<const KeyEntry*>(eventEntry);
1756 if (keyEntry->flags & AKEY_EVENT_FLAG_CANCELED) {
1757 return;
1758 }
Jeff Brownb696de52012-07-27 15:38:50 -07001759 eventType = USER_ACTIVITY_EVENT_BUTTON;
Jeff Brown4d396052010-10-29 21:50:21 -07001760 break;
1761 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001762 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001763
Jeff Brownb88102f2010-09-08 11:49:43 -07001764 CommandEntry* commandEntry = postCommandLocked(
1765 & InputDispatcher::doPokeUserActivityLockedInterruptible);
Jeff Browne2fe69e2010-10-18 13:21:23 -07001766 commandEntry->eventTime = eventEntry->eventTime;
Jeff Brownb88102f2010-09-08 11:49:43 -07001767 commandEntry->userActivityEventType = eventType;
1768}
1769
Jeff Brown7fbdc842010-06-17 20:52:56 -07001770void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001771 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07001772#if DEBUG_DISPATCH_CYCLE
Steve Block5baa3a62011-12-20 16:23:08 +00001773 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
Jeff Brown9cc695c2011-08-23 18:35:04 -07001774 "xOffset=%f, yOffset=%f, scaleFactor=%f, "
Jeff Brown3241b6b2012-02-03 15:08:02 -08001775 "pointerIds=0x%x",
Jeff Brown519e0242010-09-15 15:18:56 -07001776 connection->getInputChannelName(), inputTarget->flags,
Jeff Brown46b9ac02010-04-22 18:58:52 -07001777 inputTarget->xOffset, inputTarget->yOffset,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001778 inputTarget->scaleFactor, inputTarget->pointerIds.value);
Jeff Brown46b9ac02010-04-22 18:58:52 -07001779#endif
1780
1781 // Skip this event if the connection status is not normal.
Jeff Brown519e0242010-09-15 15:18:56 -07001782 // We don't want to enqueue additional outbound events if the connection is broken.
Jeff Brown46b9ac02010-04-22 18:58:52 -07001783 if (connection->status != Connection::STATUS_NORMAL) {
Jeff Brownb6997262010-10-08 22:31:17 -07001784#if DEBUG_DISPATCH_CYCLE
Steve Block5baa3a62011-12-20 16:23:08 +00001785 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Jeff Brownb88102f2010-09-08 11:49:43 -07001786 connection->getInputChannelName(), connection->getStatusLabel());
Jeff Brownb6997262010-10-08 22:31:17 -07001787#endif
Jeff Brown46b9ac02010-04-22 18:58:52 -07001788 return;
1789 }
1790
Jeff Brown01ce2e92010-09-26 22:20:12 -07001791 // Split a motion event if needed.
Jeff Brown3241b6b2012-02-03 15:08:02 -08001792 if (inputTarget->flags & InputTarget::FLAG_SPLIT) {
Steve Blockec193de2012-01-09 18:35:44 +00001793 ALOG_ASSERT(eventEntry->type == EventEntry::TYPE_MOTION);
Jeff Brown01ce2e92010-09-26 22:20:12 -07001794
1795 MotionEntry* originalMotionEntry = static_cast<MotionEntry*>(eventEntry);
1796 if (inputTarget->pointerIds.count() != originalMotionEntry->pointerCount) {
1797 MotionEntry* splitMotionEntry = splitMotionEvent(
1798 originalMotionEntry, inputTarget->pointerIds);
Jeff Brown58a2da82011-01-25 16:02:22 -08001799 if (!splitMotionEntry) {
1800 return; // split event was dropped
1801 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001802#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001803 ALOGD("channel '%s' ~ Split motion event.",
Jeff Brown01ce2e92010-09-26 22:20:12 -07001804 connection->getInputChannelName());
1805 logOutboundMotionDetailsLocked(" ", splitMotionEntry);
1806#endif
Jeff Brownc0cb3dc2012-01-12 18:30:12 -08001807 enqueueDispatchEntriesLocked(currentTime, connection,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001808 splitMotionEntry, inputTarget);
Jeff Brownc0cb3dc2012-01-12 18:30:12 -08001809 splitMotionEntry->release();
1810 return;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001811 }
1812 }
1813
Jeff Brownc0cb3dc2012-01-12 18:30:12 -08001814 // Not splitting. Enqueue dispatch entries for the event as is.
Jeff Brown3241b6b2012-02-03 15:08:02 -08001815 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
Jeff Brownc0cb3dc2012-01-12 18:30:12 -08001816}
1817
1818void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001819 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07001820 bool wasEmpty = connection->outboundQueue.isEmpty();
1821
Jeff Browna032cc02011-03-07 16:56:21 -08001822 // Enqueue dispatch entries for the requested modes.
1823 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001824 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
Jeff Browna032cc02011-03-07 16:56:21 -08001825 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001826 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
Jeff Browna032cc02011-03-07 16:56:21 -08001827 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001828 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
Jeff Browna032cc02011-03-07 16:56:21 -08001829 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001830 InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brown98db5fa2011-06-08 15:37:10 -07001831 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001832 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
Jeff Brown98db5fa2011-06-08 15:37:10 -07001833 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001834 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Jeff Browna032cc02011-03-07 16:56:21 -08001835
1836 // If the outbound queue was previously empty, start the dispatch cycle going.
Jeff Brownb6110c22011-04-01 16:15:13 -07001837 if (wasEmpty && !connection->outboundQueue.isEmpty()) {
Jeff Browna032cc02011-03-07 16:56:21 -08001838 startDispatchCycleLocked(currentTime, connection);
1839 }
1840}
1841
1842void InputDispatcher::enqueueDispatchEntryLocked(
1843 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001844 int32_t dispatchMode) {
Jeff Browna032cc02011-03-07 16:56:21 -08001845 int32_t inputTargetFlags = inputTarget->flags;
1846 if (!(inputTargetFlags & dispatchMode)) {
1847 return;
1848 }
1849 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
1850
Jeff Brown46b9ac02010-04-22 18:58:52 -07001851 // This is a new event.
1852 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Jeff Brownac386072011-07-20 15:19:50 -07001853 DispatchEntry* dispatchEntry = new DispatchEntry(eventEntry, // increments ref
Dianne Hackbornaa9d84c2011-05-09 19:00:59 -07001854 inputTargetFlags, inputTarget->xOffset, inputTarget->yOffset,
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001855 inputTarget->scaleFactor);
Jeff Brown6ec402b2010-07-28 15:48:59 -07001856
Jeff Brown81346812011-06-28 20:08:48 -07001857 // Apply target flags and update the connection's input state.
1858 switch (eventEntry->type) {
1859 case EventEntry::TYPE_KEY: {
1860 KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
1861 dispatchEntry->resolvedAction = keyEntry->action;
1862 dispatchEntry->resolvedFlags = keyEntry->flags;
1863
1864 if (!connection->inputState.trackKey(keyEntry,
1865 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags)) {
1866#if DEBUG_DISPATCH_CYCLE
Steve Block5baa3a62011-12-20 16:23:08 +00001867 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
Jeff Brown81346812011-06-28 20:08:48 -07001868 connection->getInputChannelName());
1869#endif
Jeff Brownc0cb3dc2012-01-12 18:30:12 -08001870 delete dispatchEntry;
Jeff Brown81346812011-06-28 20:08:48 -07001871 return; // skip the inconsistent event
1872 }
1873 break;
1874 }
1875
1876 case EventEntry::TYPE_MOTION: {
1877 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
1878 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
1879 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
1880 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
1881 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
1882 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
1883 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
1884 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
1885 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
1886 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
1887 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
1888 } else {
1889 dispatchEntry->resolvedAction = motionEntry->action;
1890 }
1891 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE
1892 && !connection->inputState.isHovering(
Jeff Brown83d616a2012-09-09 20:33:43 -07001893 motionEntry->deviceId, motionEntry->source, motionEntry->displayId)) {
Jeff Brown81346812011-06-28 20:08:48 -07001894#if DEBUG_DISPATCH_CYCLE
Steve Block5baa3a62011-12-20 16:23:08 +00001895 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter event",
Jeff Brown81346812011-06-28 20:08:48 -07001896 connection->getInputChannelName());
1897#endif
1898 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
1899 }
1900
1901 dispatchEntry->resolvedFlags = motionEntry->flags;
1902 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
1903 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
1904 }
1905
1906 if (!connection->inputState.trackMotion(motionEntry,
1907 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags)) {
1908#if DEBUG_DISPATCH_CYCLE
Steve Block5baa3a62011-12-20 16:23:08 +00001909 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion event",
Jeff Brown81346812011-06-28 20:08:48 -07001910 connection->getInputChannelName());
1911#endif
Jeff Brownc0cb3dc2012-01-12 18:30:12 -08001912 delete dispatchEntry;
Jeff Brown81346812011-06-28 20:08:48 -07001913 return; // skip the inconsistent event
1914 }
1915 break;
1916 }
1917 }
1918
Jeff Brownc0cb3dc2012-01-12 18:30:12 -08001919 // Remember that we are waiting for this dispatch to complete.
1920 if (dispatchEntry->hasForegroundTarget()) {
1921 incrementPendingForegroundDispatchesLocked(eventEntry);
1922 }
1923
Jeff Brown46b9ac02010-04-22 18:58:52 -07001924 // Enqueue the dispatch entry.
1925 connection->outboundQueue.enqueueAtTail(dispatchEntry);
Jeff Brown481c1572012-03-09 14:41:15 -08001926 traceOutboundQueueLengthLocked(connection);
Jeff Brown46b9ac02010-04-22 18:58:52 -07001927}
1928
Jeff Brown7fbdc842010-06-17 20:52:56 -07001929void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Jeff Brown519e0242010-09-15 15:18:56 -07001930 const sp<Connection>& connection) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07001931#if DEBUG_DISPATCH_CYCLE
Steve Block5baa3a62011-12-20 16:23:08 +00001932 ALOGD("channel '%s' ~ startDispatchCycle",
Jeff Brown46b9ac02010-04-22 18:58:52 -07001933 connection->getInputChannelName());
1934#endif
1935
Jeff Brownd1c48a02012-02-06 19:12:47 -08001936 while (connection->status == Connection::STATUS_NORMAL
1937 && !connection->outboundQueue.isEmpty()) {
1938 DispatchEntry* dispatchEntry = connection->outboundQueue.head;
Jeff Brown265f1cc2012-06-11 18:01:06 -07001939 dispatchEntry->deliveryTime = currentTime;
Jeff Brown46b9ac02010-04-22 18:58:52 -07001940
Jeff Brownd1c48a02012-02-06 19:12:47 -08001941 // Publish the event.
1942 status_t status;
1943 EventEntry* eventEntry = dispatchEntry->eventEntry;
1944 switch (eventEntry->type) {
1945 case EventEntry::TYPE_KEY: {
1946 KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
Jeff Brown46b9ac02010-04-22 18:58:52 -07001947
Jeff Brownd1c48a02012-02-06 19:12:47 -08001948 // Publish the key event.
Jeff Brown072ec962012-02-07 14:46:57 -08001949 status = connection->inputPublisher.publishKeyEvent(dispatchEntry->seq,
Jeff Brownd1c48a02012-02-06 19:12:47 -08001950 keyEntry->deviceId, keyEntry->source,
1951 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags,
1952 keyEntry->keyCode, keyEntry->scanCode,
1953 keyEntry->metaState, keyEntry->repeatCount, keyEntry->downTime,
1954 keyEntry->eventTime);
1955 break;
1956 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001957
Jeff Brownd1c48a02012-02-06 19:12:47 -08001958 case EventEntry::TYPE_MOTION: {
1959 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
Jeff Brown46b9ac02010-04-22 18:58:52 -07001960
Jeff Brownd1c48a02012-02-06 19:12:47 -08001961 PointerCoords scaledCoords[MAX_POINTERS];
1962 const PointerCoords* usingCoords = motionEntry->pointerCoords;
Jeff Brown46b9ac02010-04-22 18:58:52 -07001963
Jeff Brownd1c48a02012-02-06 19:12:47 -08001964 // Set the X and Y offset depending on the input source.
1965 float xOffset, yOffset, scaleFactor;
1966 if ((motionEntry->source & AINPUT_SOURCE_CLASS_POINTER)
1967 && !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
1968 scaleFactor = dispatchEntry->scaleFactor;
1969 xOffset = dispatchEntry->xOffset * scaleFactor;
1970 yOffset = dispatchEntry->yOffset * scaleFactor;
1971 if (scaleFactor != 1.0f) {
1972 for (size_t i = 0; i < motionEntry->pointerCount; i++) {
1973 scaledCoords[i] = motionEntry->pointerCoords[i];
1974 scaledCoords[i].scale(scaleFactor);
1975 }
1976 usingCoords = scaledCoords;
1977 }
1978 } else {
1979 xOffset = 0.0f;
1980 yOffset = 0.0f;
1981 scaleFactor = 1.0f;
1982
1983 // We don't want the dispatch target to know.
1984 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
1985 for (size_t i = 0; i < motionEntry->pointerCount; i++) {
1986 scaledCoords[i].clear();
1987 }
1988 usingCoords = scaledCoords;
1989 }
1990 }
1991
1992 // Publish the motion event.
Jeff Brown072ec962012-02-07 14:46:57 -08001993 status = connection->inputPublisher.publishMotionEvent(dispatchEntry->seq,
Jeff Brownd1c48a02012-02-06 19:12:47 -08001994 motionEntry->deviceId, motionEntry->source,
1995 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags,
1996 motionEntry->edgeFlags, motionEntry->metaState, motionEntry->buttonState,
1997 xOffset, yOffset,
1998 motionEntry->xPrecision, motionEntry->yPrecision,
1999 motionEntry->downTime, motionEntry->eventTime,
2000 motionEntry->pointerCount, motionEntry->pointerProperties,
2001 usingCoords);
2002 break;
2003 }
2004
2005 default:
2006 ALOG_ASSERT(false);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002007 return;
2008 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002009
Jeff Brownd1c48a02012-02-06 19:12:47 -08002010 // Check the result.
Jeff Brown46b9ac02010-04-22 18:58:52 -07002011 if (status) {
Jeff Brownd1c48a02012-02-06 19:12:47 -08002012 if (status == WOULD_BLOCK) {
2013 if (connection->waitQueue.isEmpty()) {
2014 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
2015 "This is unexpected because the wait queue is empty, so the pipe "
2016 "should be empty and we shouldn't have any problems writing an "
2017 "event to it, status=%d", connection->getInputChannelName(), status);
2018 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2019 } else {
2020 // Pipe is full and we are waiting for the app to finish process some events
2021 // before sending more events to it.
2022#if DEBUG_DISPATCH_CYCLE
2023 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
2024 "waiting for the application to catch up",
2025 connection->getInputChannelName());
2026#endif
2027 connection->inputPublisherBlocked = true;
2028 }
2029 } else {
2030 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
2031 "status=%d", connection->getInputChannelName(), status);
2032 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2033 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002034 return;
2035 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002036
Jeff Brownd1c48a02012-02-06 19:12:47 -08002037 // Re-enqueue the event on the wait queue.
2038 connection->outboundQueue.dequeue(dispatchEntry);
Jeff Brown481c1572012-03-09 14:41:15 -08002039 traceOutboundQueueLengthLocked(connection);
Jeff Brownd1c48a02012-02-06 19:12:47 -08002040 connection->waitQueue.enqueueAtTail(dispatchEntry);
Jeff Brown481c1572012-03-09 14:41:15 -08002041 traceWaitQueueLengthLocked(connection);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002042 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002043}
2044
Jeff Brown7fbdc842010-06-17 20:52:56 -07002045void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Jeff Brown072ec962012-02-07 14:46:57 -08002046 const sp<Connection>& connection, uint32_t seq, bool handled) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002047#if DEBUG_DISPATCH_CYCLE
Jeff Brown072ec962012-02-07 14:46:57 -08002048 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
2049 connection->getInputChannelName(), seq, toString(handled));
Jeff Brown46b9ac02010-04-22 18:58:52 -07002050#endif
2051
Jeff Brownd1c48a02012-02-06 19:12:47 -08002052 connection->inputPublisherBlocked = false;
2053
Jeff Brown9c3cda02010-06-15 01:31:58 -07002054 if (connection->status == Connection::STATUS_BROKEN
2055 || connection->status == Connection::STATUS_ZOMBIE) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002056 return;
2057 }
2058
Jeff Brown3915bb82010-11-05 15:02:16 -07002059 // Notify other system components and prepare to start the next dispatch cycle.
Jeff Brown072ec962012-02-07 14:46:57 -08002060 onDispatchCycleFinishedLocked(currentTime, connection, seq, handled);
Jeff Brownb88102f2010-09-08 11:49:43 -07002061}
2062
Jeff Brownb6997262010-10-08 22:31:17 -07002063void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Jeff Browncc4f7db2011-08-30 20:34:48 -07002064 const sp<Connection>& connection, bool notify) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002065#if DEBUG_DISPATCH_CYCLE
Steve Block5baa3a62011-12-20 16:23:08 +00002066 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
Jeff Browncc4f7db2011-08-30 20:34:48 -07002067 connection->getInputChannelName(), toString(notify));
Jeff Brown46b9ac02010-04-22 18:58:52 -07002068#endif
2069
Jeff Brownd1c48a02012-02-06 19:12:47 -08002070 // Clear the dispatch queues.
2071 drainDispatchQueueLocked(&connection->outboundQueue);
Jeff Brown481c1572012-03-09 14:41:15 -08002072 traceOutboundQueueLengthLocked(connection);
Jeff Brownd1c48a02012-02-06 19:12:47 -08002073 drainDispatchQueueLocked(&connection->waitQueue);
Jeff Brown481c1572012-03-09 14:41:15 -08002074 traceWaitQueueLengthLocked(connection);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002075
Jeff Brownb6997262010-10-08 22:31:17 -07002076 // The connection appears to be unrecoverably broken.
Jeff Brown9c3cda02010-06-15 01:31:58 -07002077 // Ignore already broken or zombie connections.
Jeff Brownb6997262010-10-08 22:31:17 -07002078 if (connection->status == Connection::STATUS_NORMAL) {
2079 connection->status = Connection::STATUS_BROKEN;
Jeff Brown46b9ac02010-04-22 18:58:52 -07002080
Jeff Browncc4f7db2011-08-30 20:34:48 -07002081 if (notify) {
2082 // Notify other system components.
2083 onDispatchCycleBrokenLocked(currentTime, connection);
2084 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002085 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002086}
2087
Jeff Brownd1c48a02012-02-06 19:12:47 -08002088void InputDispatcher::drainDispatchQueueLocked(Queue<DispatchEntry>* queue) {
2089 while (!queue->isEmpty()) {
2090 DispatchEntry* dispatchEntry = queue->dequeueAtHead();
2091 releaseDispatchEntryLocked(dispatchEntry);
Jeff Brownb88102f2010-09-08 11:49:43 -07002092 }
Jeff Brownb88102f2010-09-08 11:49:43 -07002093}
2094
Jeff Brownd1c48a02012-02-06 19:12:47 -08002095void InputDispatcher::releaseDispatchEntryLocked(DispatchEntry* dispatchEntry) {
2096 if (dispatchEntry->hasForegroundTarget()) {
2097 decrementPendingForegroundDispatchesLocked(dispatchEntry->eventEntry);
2098 }
2099 delete dispatchEntry;
2100}
2101
Jeff Browncbee6d62012-02-03 20:11:27 -08002102int InputDispatcher::handleReceiveCallback(int fd, int events, void* data) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002103 InputDispatcher* d = static_cast<InputDispatcher*>(data);
2104
2105 { // acquire lock
2106 AutoMutex _l(d->mLock);
2107
Jeff Browncbee6d62012-02-03 20:11:27 -08002108 ssize_t connectionIndex = d->mConnectionsByFd.indexOfKey(fd);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002109 if (connectionIndex < 0) {
Steve Block3762c312012-01-06 19:20:56 +00002110 ALOGE("Received spurious receive callback for unknown input channel. "
Jeff Browncbee6d62012-02-03 20:11:27 -08002111 "fd=%d, events=0x%x", fd, events);
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002112 return 0; // remove the callback
Jeff Brown46b9ac02010-04-22 18:58:52 -07002113 }
2114
Jeff Browncc4f7db2011-08-30 20:34:48 -07002115 bool notify;
Jeff Browncbee6d62012-02-03 20:11:27 -08002116 sp<Connection> connection = d->mConnectionsByFd.valueAt(connectionIndex);
Jeff Browncc4f7db2011-08-30 20:34:48 -07002117 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
2118 if (!(events & ALOOPER_EVENT_INPUT)) {
Steve Block8564c8d2012-01-05 23:22:43 +00002119 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
Jeff Browncc4f7db2011-08-30 20:34:48 -07002120 "events=0x%x", connection->getInputChannelName(), events);
2121 return 1;
2122 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002123
Jeff Brown1adee112012-02-07 10:25:41 -08002124 nsecs_t currentTime = now();
2125 bool gotOne = false;
2126 status_t status;
2127 for (;;) {
Jeff Brown072ec962012-02-07 14:46:57 -08002128 uint32_t seq;
2129 bool handled;
2130 status = connection->inputPublisher.receiveFinishedSignal(&seq, &handled);
Jeff Brown1adee112012-02-07 10:25:41 -08002131 if (status) {
2132 break;
2133 }
Jeff Brown072ec962012-02-07 14:46:57 -08002134 d->finishDispatchCycleLocked(currentTime, connection, seq, handled);
Jeff Brown1adee112012-02-07 10:25:41 -08002135 gotOne = true;
2136 }
2137 if (gotOne) {
Jeff Browncc4f7db2011-08-30 20:34:48 -07002138 d->runCommandsLockedInterruptible();
Jeff Brown1adee112012-02-07 10:25:41 -08002139 if (status == WOULD_BLOCK) {
2140 return 1;
2141 }
Jeff Browncc4f7db2011-08-30 20:34:48 -07002142 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002143
Jeff Brown1adee112012-02-07 10:25:41 -08002144 notify = status != DEAD_OBJECT || !connection->monitor;
2145 if (notify) {
2146 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
2147 connection->getInputChannelName(), status);
2148 }
Jeff Browncc4f7db2011-08-30 20:34:48 -07002149 } else {
2150 // Monitor channels are never explicitly unregistered.
2151 // We do it automatically when the remote endpoint is closed so don't warn
2152 // about them.
2153 notify = !connection->monitor;
2154 if (notify) {
Steve Block8564c8d2012-01-05 23:22:43 +00002155 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. "
Jeff Browncc4f7db2011-08-30 20:34:48 -07002156 "events=0x%x", connection->getInputChannelName(), events);
2157 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002158 }
2159
Jeff Browncc4f7db2011-08-30 20:34:48 -07002160 // Unregister the channel.
2161 d->unregisterInputChannelLocked(connection->inputChannel, notify);
2162 return 0; // remove the callback
Jeff Brown46b9ac02010-04-22 18:58:52 -07002163 } // release lock
2164}
2165
Jeff Brownb6997262010-10-08 22:31:17 -07002166void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Jeff Brownda3d5a92011-03-29 15:11:34 -07002167 const CancelationOptions& options) {
Jeff Browncbee6d62012-02-03 20:11:27 -08002168 for (size_t i = 0; i < mConnectionsByFd.size(); i++) {
Jeff Brownb6997262010-10-08 22:31:17 -07002169 synthesizeCancelationEventsForConnectionLocked(
Jeff Browncbee6d62012-02-03 20:11:27 -08002170 mConnectionsByFd.valueAt(i), options);
Jeff Brownb6997262010-10-08 22:31:17 -07002171 }
2172}
2173
2174void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Jeff Brownda3d5a92011-03-29 15:11:34 -07002175 const sp<InputChannel>& channel, const CancelationOptions& options) {
Jeff Brownb6997262010-10-08 22:31:17 -07002176 ssize_t index = getConnectionIndexLocked(channel);
2177 if (index >= 0) {
2178 synthesizeCancelationEventsForConnectionLocked(
Jeff Browncbee6d62012-02-03 20:11:27 -08002179 mConnectionsByFd.valueAt(index), options);
Jeff Brownb6997262010-10-08 22:31:17 -07002180 }
2181}
2182
2183void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
Jeff Brownda3d5a92011-03-29 15:11:34 -07002184 const sp<Connection>& connection, const CancelationOptions& options) {
Jeff Brownc0cb3dc2012-01-12 18:30:12 -08002185 if (connection->status == Connection::STATUS_BROKEN) {
2186 return;
2187 }
2188
Jeff Brownb6997262010-10-08 22:31:17 -07002189 nsecs_t currentTime = now();
2190
Jeff Brown8b4be5602012-02-06 16:31:05 -08002191 Vector<EventEntry*> cancelationEvents;
Jeff Brownac386072011-07-20 15:19:50 -07002192 connection->inputState.synthesizeCancelationEvents(currentTime,
Jeff Brown8b4be5602012-02-06 16:31:05 -08002193 cancelationEvents, options);
Jeff Brownb6997262010-10-08 22:31:17 -07002194
Jeff Brown8b4be5602012-02-06 16:31:05 -08002195 if (!cancelationEvents.isEmpty()) {
Jeff Brownb6997262010-10-08 22:31:17 -07002196#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00002197 ALOGD("channel '%s' ~ Synthesized %d cancelation events to bring channel back in sync "
Jeff Brownda3d5a92011-03-29 15:11:34 -07002198 "with reality: %s, mode=%d.",
Jeff Brown8b4be5602012-02-06 16:31:05 -08002199 connection->getInputChannelName(), cancelationEvents.size(),
Jeff Brownda3d5a92011-03-29 15:11:34 -07002200 options.reason, options.mode);
Jeff Brownb6997262010-10-08 22:31:17 -07002201#endif
Jeff Brown8b4be5602012-02-06 16:31:05 -08002202 for (size_t i = 0; i < cancelationEvents.size(); i++) {
2203 EventEntry* cancelationEventEntry = cancelationEvents.itemAt(i);
Jeff Brownb6997262010-10-08 22:31:17 -07002204 switch (cancelationEventEntry->type) {
2205 case EventEntry::TYPE_KEY:
2206 logOutboundKeyDetailsLocked("cancel - ",
2207 static_cast<KeyEntry*>(cancelationEventEntry));
2208 break;
2209 case EventEntry::TYPE_MOTION:
2210 logOutboundMotionDetailsLocked("cancel - ",
2211 static_cast<MotionEntry*>(cancelationEventEntry));
2212 break;
2213 }
2214
Jeff Brown81346812011-06-28 20:08:48 -07002215 InputTarget target;
Jeff Brown9302c872011-07-13 22:51:29 -07002216 sp<InputWindowHandle> windowHandle = getWindowHandleLocked(connection->inputChannel);
2217 if (windowHandle != NULL) {
Jeff Browncc4f7db2011-08-30 20:34:48 -07002218 const InputWindowInfo* windowInfo = windowHandle->getInfo();
2219 target.xOffset = -windowInfo->frameLeft;
2220 target.yOffset = -windowInfo->frameTop;
2221 target.scaleFactor = windowInfo->scaleFactor;
Jeff Brownb6997262010-10-08 22:31:17 -07002222 } else {
Jeff Brown81346812011-06-28 20:08:48 -07002223 target.xOffset = 0;
2224 target.yOffset = 0;
2225 target.scaleFactor = 1.0f;
Jeff Brownb6997262010-10-08 22:31:17 -07002226 }
Jeff Brown81346812011-06-28 20:08:48 -07002227 target.inputChannel = connection->inputChannel;
2228 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
Jeff Brownb6997262010-10-08 22:31:17 -07002229
Jeff Brown81346812011-06-28 20:08:48 -07002230 enqueueDispatchEntryLocked(connection, cancelationEventEntry, // increments ref
Jeff Brown3241b6b2012-02-03 15:08:02 -08002231 &target, InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brownb6997262010-10-08 22:31:17 -07002232
Jeff Brownac386072011-07-20 15:19:50 -07002233 cancelationEventEntry->release();
Jeff Brownb6997262010-10-08 22:31:17 -07002234 }
2235
Jeff Brownd1c48a02012-02-06 19:12:47 -08002236 startDispatchCycleLocked(currentTime, connection);
Jeff Brownb6997262010-10-08 22:31:17 -07002237 }
2238}
2239
Jeff Brown01ce2e92010-09-26 22:20:12 -07002240InputDispatcher::MotionEntry*
2241InputDispatcher::splitMotionEvent(const MotionEntry* originalMotionEntry, BitSet32 pointerIds) {
Steve Blockec193de2012-01-09 18:35:44 +00002242 ALOG_ASSERT(pointerIds.value != 0);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002243
2244 uint32_t splitPointerIndexMap[MAX_POINTERS];
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002245 PointerProperties splitPointerProperties[MAX_POINTERS];
Jeff Brown01ce2e92010-09-26 22:20:12 -07002246 PointerCoords splitPointerCoords[MAX_POINTERS];
2247
2248 uint32_t originalPointerCount = originalMotionEntry->pointerCount;
2249 uint32_t splitPointerCount = 0;
2250
2251 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
2252 originalPointerIndex++) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002253 const PointerProperties& pointerProperties =
2254 originalMotionEntry->pointerProperties[originalPointerIndex];
2255 uint32_t pointerId = uint32_t(pointerProperties.id);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002256 if (pointerIds.hasBit(pointerId)) {
2257 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002258 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
Jeff Brownace13b12011-03-09 17:39:48 -08002259 splitPointerCoords[splitPointerCount].copyFrom(
Jeff Brown3241b6b2012-02-03 15:08:02 -08002260 originalMotionEntry->pointerCoords[originalPointerIndex]);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002261 splitPointerCount += 1;
2262 }
2263 }
Jeff Brown58a2da82011-01-25 16:02:22 -08002264
2265 if (splitPointerCount != pointerIds.count()) {
2266 // This is bad. We are missing some of the pointers that we expected to deliver.
2267 // Most likely this indicates that we received an ACTION_MOVE events that has
2268 // different pointer ids than we expected based on the previous ACTION_DOWN
2269 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
2270 // in this way.
Steve Block8564c8d2012-01-05 23:22:43 +00002271 ALOGW("Dropping split motion event because the pointer count is %d but "
Jeff Brown58a2da82011-01-25 16:02:22 -08002272 "we expected there to be %d pointers. This probably means we received "
2273 "a broken sequence of pointer ids from the input device.",
2274 splitPointerCount, pointerIds.count());
2275 return NULL;
2276 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07002277
2278 int32_t action = originalMotionEntry->action;
2279 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
2280 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
2281 || maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2282 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002283 const PointerProperties& pointerProperties =
2284 originalMotionEntry->pointerProperties[originalPointerIndex];
2285 uint32_t pointerId = uint32_t(pointerProperties.id);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002286 if (pointerIds.hasBit(pointerId)) {
2287 if (pointerIds.count() == 1) {
2288 // The first/last pointer went down/up.
2289 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
2290 ? AMOTION_EVENT_ACTION_DOWN : AMOTION_EVENT_ACTION_UP;
Jeff Brown9a01d052010-09-27 16:35:11 -07002291 } else {
2292 // A secondary pointer went down/up.
2293 uint32_t splitPointerIndex = 0;
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002294 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
Jeff Brown9a01d052010-09-27 16:35:11 -07002295 splitPointerIndex += 1;
2296 }
2297 action = maskedAction | (splitPointerIndex
2298 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002299 }
2300 } else {
2301 // An unrelated pointer changed.
2302 action = AMOTION_EVENT_ACTION_MOVE;
2303 }
2304 }
2305
Jeff Brownac386072011-07-20 15:19:50 -07002306 MotionEntry* splitMotionEntry = new MotionEntry(
Jeff Brown01ce2e92010-09-26 22:20:12 -07002307 originalMotionEntry->eventTime,
2308 originalMotionEntry->deviceId,
2309 originalMotionEntry->source,
2310 originalMotionEntry->policyFlags,
2311 action,
2312 originalMotionEntry->flags,
2313 originalMotionEntry->metaState,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002314 originalMotionEntry->buttonState,
Jeff Brown01ce2e92010-09-26 22:20:12 -07002315 originalMotionEntry->edgeFlags,
2316 originalMotionEntry->xPrecision,
2317 originalMotionEntry->yPrecision,
2318 originalMotionEntry->downTime,
Jeff Brown83d616a2012-09-09 20:33:43 -07002319 originalMotionEntry->displayId,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002320 splitPointerCount, splitPointerProperties, splitPointerCoords);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002321
Jeff Browna032cc02011-03-07 16:56:21 -08002322 if (originalMotionEntry->injectionState) {
2323 splitMotionEntry->injectionState = originalMotionEntry->injectionState;
2324 splitMotionEntry->injectionState->refCount += 1;
2325 }
2326
Jeff Brown01ce2e92010-09-26 22:20:12 -07002327 return splitMotionEntry;
2328}
2329
Jeff Brownbe1aa822011-07-27 16:04:54 -07002330void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002331#if DEBUG_INBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00002332 ALOGD("notifyConfigurationChanged - eventTime=%lld", args->eventTime);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002333#endif
2334
Jeff Brownb88102f2010-09-08 11:49:43 -07002335 bool needWake;
Jeff Brown46b9ac02010-04-22 18:58:52 -07002336 { // acquire lock
2337 AutoMutex _l(mLock);
2338
Jeff Brownbe1aa822011-07-27 16:04:54 -07002339 ConfigurationChangedEntry* newEntry = new ConfigurationChangedEntry(args->eventTime);
Jeff Brownb88102f2010-09-08 11:49:43 -07002340 needWake = enqueueInboundEventLocked(newEntry);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002341 } // release lock
2342
Jeff Brownb88102f2010-09-08 11:49:43 -07002343 if (needWake) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002344 mLooper->wake();
Jeff Brown46b9ac02010-04-22 18:58:52 -07002345 }
2346}
2347
Jeff Brownbe1aa822011-07-27 16:04:54 -07002348void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002349#if DEBUG_INBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00002350 ALOGD("notifyKey - eventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, action=0x%x, "
Jeff Brown46b9ac02010-04-22 18:58:52 -07002351 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%lld",
Jeff Brownbe1aa822011-07-27 16:04:54 -07002352 args->eventTime, args->deviceId, args->source, args->policyFlags,
2353 args->action, args->flags, args->keyCode, args->scanCode,
2354 args->metaState, args->downTime);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002355#endif
Jeff Brownbe1aa822011-07-27 16:04:54 -07002356 if (!validateKeyEvent(args->action)) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002357 return;
2358 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002359
Jeff Brownbe1aa822011-07-27 16:04:54 -07002360 uint32_t policyFlags = args->policyFlags;
2361 int32_t flags = args->flags;
2362 int32_t metaState = args->metaState;
Jeff Brown1f245102010-11-18 20:53:46 -08002363 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
2364 policyFlags |= POLICY_FLAG_VIRTUAL;
2365 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
2366 }
Jeff Brown924c4d42011-03-07 16:40:47 -08002367 if (policyFlags & POLICY_FLAG_ALT) {
2368 metaState |= AMETA_ALT_ON | AMETA_ALT_LEFT_ON;
2369 }
2370 if (policyFlags & POLICY_FLAG_ALT_GR) {
2371 metaState |= AMETA_ALT_ON | AMETA_ALT_RIGHT_ON;
2372 }
2373 if (policyFlags & POLICY_FLAG_SHIFT) {
2374 metaState |= AMETA_SHIFT_ON | AMETA_SHIFT_LEFT_ON;
2375 }
2376 if (policyFlags & POLICY_FLAG_CAPS_LOCK) {
2377 metaState |= AMETA_CAPS_LOCK_ON;
2378 }
2379 if (policyFlags & POLICY_FLAG_FUNCTION) {
2380 metaState |= AMETA_FUNCTION_ON;
2381 }
Jeff Brown1f245102010-11-18 20:53:46 -08002382
Jeff Browne20c9e02010-10-11 14:20:19 -07002383 policyFlags |= POLICY_FLAG_TRUSTED;
Jeff Brown1f245102010-11-18 20:53:46 -08002384
2385 KeyEvent event;
Jeff Brownbe1aa822011-07-27 16:04:54 -07002386 event.initialize(args->deviceId, args->source, args->action,
2387 flags, args->keyCode, args->scanCode, metaState, 0,
2388 args->downTime, args->eventTime);
Jeff Brown1f245102010-11-18 20:53:46 -08002389
2390 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
2391
2392 if (policyFlags & POLICY_FLAG_WOKE_HERE) {
2393 flags |= AKEY_EVENT_FLAG_WOKE_HERE;
2394 }
Jeff Brownb6997262010-10-08 22:31:17 -07002395
Jeff Brownb88102f2010-09-08 11:49:43 -07002396 bool needWake;
Jeff Brown46b9ac02010-04-22 18:58:52 -07002397 { // acquire lock
Jeff Brown0029c662011-03-30 02:25:18 -07002398 mLock.lock();
2399
Jeff Brown83d616a2012-09-09 20:33:43 -07002400 if (shouldSendKeyToInputFilterLocked(args)) {
Jeff Brown0029c662011-03-30 02:25:18 -07002401 mLock.unlock();
2402
2403 policyFlags |= POLICY_FLAG_FILTERED;
2404 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2405 return; // event was consumed by the filter
2406 }
2407
2408 mLock.lock();
2409 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002410
Jeff Brown7fbdc842010-06-17 20:52:56 -07002411 int32_t repeatCount = 0;
Jeff Brownbe1aa822011-07-27 16:04:54 -07002412 KeyEntry* newEntry = new KeyEntry(args->eventTime,
2413 args->deviceId, args->source, policyFlags,
2414 args->action, flags, args->keyCode, args->scanCode,
2415 metaState, repeatCount, args->downTime);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002416
Jeff Brownb88102f2010-09-08 11:49:43 -07002417 needWake = enqueueInboundEventLocked(newEntry);
Jeff Brown0029c662011-03-30 02:25:18 -07002418 mLock.unlock();
Jeff Brown46b9ac02010-04-22 18:58:52 -07002419 } // release lock
2420
Jeff Brownb88102f2010-09-08 11:49:43 -07002421 if (needWake) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002422 mLooper->wake();
Jeff Brown46b9ac02010-04-22 18:58:52 -07002423 }
2424}
2425
Jeff Brown83d616a2012-09-09 20:33:43 -07002426bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
2427 return mInputFilterEnabled;
2428}
2429
Jeff Brownbe1aa822011-07-27 16:04:54 -07002430void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002431#if DEBUG_INBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00002432 ALOGD("notifyMotion - eventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, "
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002433 "action=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, edgeFlags=0x%x, "
Jeff Brown85a31762010-09-01 17:01:00 -07002434 "xPrecision=%f, yPrecision=%f, downTime=%lld",
Jeff Brownbe1aa822011-07-27 16:04:54 -07002435 args->eventTime, args->deviceId, args->source, args->policyFlags,
2436 args->action, args->flags, args->metaState, args->buttonState,
2437 args->edgeFlags, args->xPrecision, args->yPrecision, args->downTime);
2438 for (uint32_t i = 0; i < args->pointerCount; i++) {
Steve Block5baa3a62011-12-20 16:23:08 +00002439 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002440 "x=%f, y=%f, pressure=%f, size=%f, "
Jeff Brown85a31762010-09-01 17:01:00 -07002441 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
Jeff Brown8d608662010-08-30 03:02:23 -07002442 "orientation=%f",
Jeff Brownbe1aa822011-07-27 16:04:54 -07002443 i, args->pointerProperties[i].id,
2444 args->pointerProperties[i].toolType,
2445 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
2446 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
2447 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
2448 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
2449 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
2450 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
2451 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
2452 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
2453 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Jeff Brown46b9ac02010-04-22 18:58:52 -07002454 }
2455#endif
Jeff Brownbe1aa822011-07-27 16:04:54 -07002456 if (!validateMotionEvent(args->action, args->pointerCount, args->pointerProperties)) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002457 return;
2458 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002459
Jeff Brownbe1aa822011-07-27 16:04:54 -07002460 uint32_t policyFlags = args->policyFlags;
Jeff Browne20c9e02010-10-11 14:20:19 -07002461 policyFlags |= POLICY_FLAG_TRUSTED;
Jeff Brownbe1aa822011-07-27 16:04:54 -07002462 mPolicy->interceptMotionBeforeQueueing(args->eventTime, /*byref*/ policyFlags);
Jeff Brownb6997262010-10-08 22:31:17 -07002463
Jeff Brownb88102f2010-09-08 11:49:43 -07002464 bool needWake;
Jeff Brown46b9ac02010-04-22 18:58:52 -07002465 { // acquire lock
Jeff Brown0029c662011-03-30 02:25:18 -07002466 mLock.lock();
2467
Jeff Brown83d616a2012-09-09 20:33:43 -07002468 if (shouldSendMotionToInputFilterLocked(args)) {
Jeff Brown0029c662011-03-30 02:25:18 -07002469 mLock.unlock();
2470
2471 MotionEvent event;
Jeff Brownbe1aa822011-07-27 16:04:54 -07002472 event.initialize(args->deviceId, args->source, args->action, args->flags,
2473 args->edgeFlags, args->metaState, args->buttonState, 0, 0,
2474 args->xPrecision, args->yPrecision,
2475 args->downTime, args->eventTime,
2476 args->pointerCount, args->pointerProperties, args->pointerCoords);
Jeff Brown0029c662011-03-30 02:25:18 -07002477
2478 policyFlags |= POLICY_FLAG_FILTERED;
2479 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2480 return; // event was consumed by the filter
2481 }
2482
2483 mLock.lock();
2484 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002485
Jeff Brown46b9ac02010-04-22 18:58:52 -07002486 // Just enqueue a new motion event.
Jeff Brownbe1aa822011-07-27 16:04:54 -07002487 MotionEntry* newEntry = new MotionEntry(args->eventTime,
2488 args->deviceId, args->source, policyFlags,
2489 args->action, args->flags, args->metaState, args->buttonState,
2490 args->edgeFlags, args->xPrecision, args->yPrecision, args->downTime,
Jeff Brown83d616a2012-09-09 20:33:43 -07002491 args->displayId,
Jeff Brownbe1aa822011-07-27 16:04:54 -07002492 args->pointerCount, args->pointerProperties, args->pointerCoords);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002493
Jeff Brownb88102f2010-09-08 11:49:43 -07002494 needWake = enqueueInboundEventLocked(newEntry);
Jeff Brown0029c662011-03-30 02:25:18 -07002495 mLock.unlock();
Jeff Brown46b9ac02010-04-22 18:58:52 -07002496 } // release lock
2497
Jeff Brownb88102f2010-09-08 11:49:43 -07002498 if (needWake) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002499 mLooper->wake();
Jeff Brown46b9ac02010-04-22 18:58:52 -07002500 }
2501}
2502
Jeff Brown83d616a2012-09-09 20:33:43 -07002503bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
2504 // TODO: support sending secondary display events to input filter
2505 return mInputFilterEnabled && isMainDisplay(args->displayId);
2506}
2507
Jeff Brownbe1aa822011-07-27 16:04:54 -07002508void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
Jeff Brownb6997262010-10-08 22:31:17 -07002509#if DEBUG_INBOUND_EVENT_DETAILS
Jeff Brownbcc046a2012-09-27 20:46:43 -07002510 ALOGD("notifySwitch - eventTime=%lld, policyFlags=0x%x, switchValues=0x%08x, switchMask=0x%08x",
Jeff Brownbe1aa822011-07-27 16:04:54 -07002511 args->eventTime, args->policyFlags,
Jeff Brownbcc046a2012-09-27 20:46:43 -07002512 args->switchValues, args->switchMask);
Jeff Brownb6997262010-10-08 22:31:17 -07002513#endif
2514
Jeff Brownbe1aa822011-07-27 16:04:54 -07002515 uint32_t policyFlags = args->policyFlags;
Jeff Browne20c9e02010-10-11 14:20:19 -07002516 policyFlags |= POLICY_FLAG_TRUSTED;
Jeff Brownbe1aa822011-07-27 16:04:54 -07002517 mPolicy->notifySwitch(args->eventTime,
Jeff Brownbcc046a2012-09-27 20:46:43 -07002518 args->switchValues, args->switchMask, policyFlags);
Jeff Brownb6997262010-10-08 22:31:17 -07002519}
2520
Jeff Brown65fd2512011-08-18 11:20:58 -07002521void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
2522#if DEBUG_INBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00002523 ALOGD("notifyDeviceReset - eventTime=%lld, deviceId=%d",
Jeff Brown65fd2512011-08-18 11:20:58 -07002524 args->eventTime, args->deviceId);
2525#endif
2526
2527 bool needWake;
2528 { // acquire lock
2529 AutoMutex _l(mLock);
2530
2531 DeviceResetEntry* newEntry = new DeviceResetEntry(args->eventTime, args->deviceId);
2532 needWake = enqueueInboundEventLocked(newEntry);
2533 } // release lock
2534
2535 if (needWake) {
2536 mLooper->wake();
2537 }
2538}
2539
Jeff Brown7fbdc842010-06-17 20:52:56 -07002540int32_t InputDispatcher::injectInputEvent(const InputEvent* event,
Jeff Brown0029c662011-03-30 02:25:18 -07002541 int32_t injectorPid, int32_t injectorUid, int32_t syncMode, int32_t timeoutMillis,
2542 uint32_t policyFlags) {
Jeff Brown7fbdc842010-06-17 20:52:56 -07002543#if DEBUG_INBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00002544 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Jeff Brown0029c662011-03-30 02:25:18 -07002545 "syncMode=%d, timeoutMillis=%d, policyFlags=0x%08x",
2546 event->getType(), injectorPid, injectorUid, syncMode, timeoutMillis, policyFlags);
Jeff Brown7fbdc842010-06-17 20:52:56 -07002547#endif
2548
2549 nsecs_t endTime = now() + milliseconds_to_nanoseconds(timeoutMillis);
Jeff Browne20c9e02010-10-11 14:20:19 -07002550
Jeff Brown0029c662011-03-30 02:25:18 -07002551 policyFlags |= POLICY_FLAG_INJECTED;
Jeff Browne20c9e02010-10-11 14:20:19 -07002552 if (hasInjectionPermission(injectorPid, injectorUid)) {
2553 policyFlags |= POLICY_FLAG_TRUSTED;
2554 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07002555
Jeff Brown3241b6b2012-02-03 15:08:02 -08002556 EventEntry* firstInjectedEntry;
2557 EventEntry* lastInjectedEntry;
Jeff Brownb6997262010-10-08 22:31:17 -07002558 switch (event->getType()) {
2559 case AINPUT_EVENT_TYPE_KEY: {
2560 const KeyEvent* keyEvent = static_cast<const KeyEvent*>(event);
2561 int32_t action = keyEvent->getAction();
2562 if (! validateKeyEvent(action)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07002563 return INPUT_EVENT_INJECTION_FAILED;
2564 }
2565
Jeff Brownb6997262010-10-08 22:31:17 -07002566 int32_t flags = keyEvent->getFlags();
Jeff Brown1f245102010-11-18 20:53:46 -08002567 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
2568 policyFlags |= POLICY_FLAG_VIRTUAL;
2569 }
2570
Jeff Brown0029c662011-03-30 02:25:18 -07002571 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
2572 mPolicy->interceptKeyBeforeQueueing(keyEvent, /*byref*/ policyFlags);
2573 }
Jeff Brown1f245102010-11-18 20:53:46 -08002574
2575 if (policyFlags & POLICY_FLAG_WOKE_HERE) {
2576 flags |= AKEY_EVENT_FLAG_WOKE_HERE;
2577 }
Jeff Brown6ec402b2010-07-28 15:48:59 -07002578
Jeff Brownb6997262010-10-08 22:31:17 -07002579 mLock.lock();
Jeff Brown3241b6b2012-02-03 15:08:02 -08002580 firstInjectedEntry = new KeyEntry(keyEvent->getEventTime(),
Jeff Brown1f245102010-11-18 20:53:46 -08002581 keyEvent->getDeviceId(), keyEvent->getSource(),
2582 policyFlags, action, flags,
2583 keyEvent->getKeyCode(), keyEvent->getScanCode(), keyEvent->getMetaState(),
Jeff Brownb6997262010-10-08 22:31:17 -07002584 keyEvent->getRepeatCount(), keyEvent->getDownTime());
Jeff Brown3241b6b2012-02-03 15:08:02 -08002585 lastInjectedEntry = firstInjectedEntry;
Jeff Brownb6997262010-10-08 22:31:17 -07002586 break;
2587 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07002588
Jeff Brownb6997262010-10-08 22:31:17 -07002589 case AINPUT_EVENT_TYPE_MOTION: {
2590 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
Jeff Brown83d616a2012-09-09 20:33:43 -07002591 int32_t displayId = ADISPLAY_ID_DEFAULT;
Jeff Brownb6997262010-10-08 22:31:17 -07002592 int32_t action = motionEvent->getAction();
2593 size_t pointerCount = motionEvent->getPointerCount();
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002594 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
2595 if (! validateMotionEvent(action, pointerCount, pointerProperties)) {
Jeff Brownb6997262010-10-08 22:31:17 -07002596 return INPUT_EVENT_INJECTION_FAILED;
2597 }
2598
Jeff Brown0029c662011-03-30 02:25:18 -07002599 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
2600 nsecs_t eventTime = motionEvent->getEventTime();
2601 mPolicy->interceptMotionBeforeQueueing(eventTime, /*byref*/ policyFlags);
2602 }
Jeff Brownb6997262010-10-08 22:31:17 -07002603
2604 mLock.lock();
2605 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
2606 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
Jeff Brown3241b6b2012-02-03 15:08:02 -08002607 firstInjectedEntry = new MotionEntry(*sampleEventTimes,
Jeff Brownb6997262010-10-08 22:31:17 -07002608 motionEvent->getDeviceId(), motionEvent->getSource(), policyFlags,
2609 action, motionEvent->getFlags(),
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002610 motionEvent->getMetaState(), motionEvent->getButtonState(),
2611 motionEvent->getEdgeFlags(),
Jeff Brownb6997262010-10-08 22:31:17 -07002612 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
Jeff Brown83d616a2012-09-09 20:33:43 -07002613 motionEvent->getDownTime(), displayId,
2614 uint32_t(pointerCount), pointerProperties, samplePointerCoords);
Jeff Brown3241b6b2012-02-03 15:08:02 -08002615 lastInjectedEntry = firstInjectedEntry;
Jeff Brownb6997262010-10-08 22:31:17 -07002616 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
2617 sampleEventTimes += 1;
2618 samplePointerCoords += pointerCount;
Jeff Brown3241b6b2012-02-03 15:08:02 -08002619 MotionEntry* nextInjectedEntry = new MotionEntry(*sampleEventTimes,
2620 motionEvent->getDeviceId(), motionEvent->getSource(), policyFlags,
2621 action, motionEvent->getFlags(),
2622 motionEvent->getMetaState(), motionEvent->getButtonState(),
2623 motionEvent->getEdgeFlags(),
2624 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
Jeff Brown83d616a2012-09-09 20:33:43 -07002625 motionEvent->getDownTime(), displayId,
2626 uint32_t(pointerCount), pointerProperties, samplePointerCoords);
Jeff Brown3241b6b2012-02-03 15:08:02 -08002627 lastInjectedEntry->next = nextInjectedEntry;
2628 lastInjectedEntry = nextInjectedEntry;
Jeff Brownb6997262010-10-08 22:31:17 -07002629 }
Jeff Brownb6997262010-10-08 22:31:17 -07002630 break;
2631 }
2632
2633 default:
Steve Block8564c8d2012-01-05 23:22:43 +00002634 ALOGW("Cannot inject event of type %d", event->getType());
Jeff Brownb6997262010-10-08 22:31:17 -07002635 return INPUT_EVENT_INJECTION_FAILED;
2636 }
2637
Jeff Brownac386072011-07-20 15:19:50 -07002638 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
Jeff Brownb6997262010-10-08 22:31:17 -07002639 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
2640 injectionState->injectionIsAsync = true;
2641 }
2642
2643 injectionState->refCount += 1;
Jeff Brown3241b6b2012-02-03 15:08:02 -08002644 lastInjectedEntry->injectionState = injectionState;
Jeff Brownb6997262010-10-08 22:31:17 -07002645
Jeff Brown3241b6b2012-02-03 15:08:02 -08002646 bool needWake = false;
2647 for (EventEntry* entry = firstInjectedEntry; entry != NULL; ) {
2648 EventEntry* nextEntry = entry->next;
2649 needWake |= enqueueInboundEventLocked(entry);
2650 entry = nextEntry;
2651 }
2652
Jeff Brownb6997262010-10-08 22:31:17 -07002653 mLock.unlock();
Jeff Brown7fbdc842010-06-17 20:52:56 -07002654
Jeff Brownb88102f2010-09-08 11:49:43 -07002655 if (needWake) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002656 mLooper->wake();
Jeff Brown7fbdc842010-06-17 20:52:56 -07002657 }
2658
2659 int32_t injectionResult;
2660 { // acquire lock
2661 AutoMutex _l(mLock);
2662
Jeff Brown6ec402b2010-07-28 15:48:59 -07002663 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
2664 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
2665 } else {
2666 for (;;) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002667 injectionResult = injectionState->injectionResult;
Jeff Brown6ec402b2010-07-28 15:48:59 -07002668 if (injectionResult != INPUT_EVENT_INJECTION_PENDING) {
2669 break;
2670 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07002671
Jeff Brown7fbdc842010-06-17 20:52:56 -07002672 nsecs_t remainingTimeout = endTime - now();
2673 if (remainingTimeout <= 0) {
Jeff Brown6ec402b2010-07-28 15:48:59 -07002674#if DEBUG_INJECTION
Steve Block5baa3a62011-12-20 16:23:08 +00002675 ALOGD("injectInputEvent - Timed out waiting for injection result "
Jeff Brown6ec402b2010-07-28 15:48:59 -07002676 "to become available.");
2677#endif
Jeff Brown7fbdc842010-06-17 20:52:56 -07002678 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
2679 break;
2680 }
2681
Jeff Brown6ec402b2010-07-28 15:48:59 -07002682 mInjectionResultAvailableCondition.waitRelative(mLock, remainingTimeout);
2683 }
2684
2685 if (injectionResult == INPUT_EVENT_INJECTION_SUCCEEDED
2686 && syncMode == INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002687 while (injectionState->pendingForegroundDispatches != 0) {
Jeff Brown6ec402b2010-07-28 15:48:59 -07002688#if DEBUG_INJECTION
Steve Block5baa3a62011-12-20 16:23:08 +00002689 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
Jeff Brown01ce2e92010-09-26 22:20:12 -07002690 injectionState->pendingForegroundDispatches);
Jeff Brown6ec402b2010-07-28 15:48:59 -07002691#endif
2692 nsecs_t remainingTimeout = endTime - now();
2693 if (remainingTimeout <= 0) {
2694#if DEBUG_INJECTION
Steve Block5baa3a62011-12-20 16:23:08 +00002695 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
Jeff Brown6ec402b2010-07-28 15:48:59 -07002696 "dispatches to finish.");
2697#endif
2698 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
2699 break;
2700 }
2701
2702 mInjectionSyncFinishedCondition.waitRelative(mLock, remainingTimeout);
2703 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07002704 }
2705 }
2706
Jeff Brownac386072011-07-20 15:19:50 -07002707 injectionState->release();
Jeff Brown7fbdc842010-06-17 20:52:56 -07002708 } // release lock
2709
Jeff Brown6ec402b2010-07-28 15:48:59 -07002710#if DEBUG_INJECTION
Steve Block5baa3a62011-12-20 16:23:08 +00002711 ALOGD("injectInputEvent - Finished with result %d. "
Jeff Brown6ec402b2010-07-28 15:48:59 -07002712 "injectorPid=%d, injectorUid=%d",
2713 injectionResult, injectorPid, injectorUid);
2714#endif
2715
Jeff Brown7fbdc842010-06-17 20:52:56 -07002716 return injectionResult;
2717}
2718
Jeff Brownb6997262010-10-08 22:31:17 -07002719bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
2720 return injectorUid == 0
2721 || mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
2722}
2723
Jeff Brown7fbdc842010-06-17 20:52:56 -07002724void InputDispatcher::setInjectionResultLocked(EventEntry* entry, int32_t injectionResult) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002725 InjectionState* injectionState = entry->injectionState;
2726 if (injectionState) {
Jeff Brown7fbdc842010-06-17 20:52:56 -07002727#if DEBUG_INJECTION
Steve Block5baa3a62011-12-20 16:23:08 +00002728 ALOGD("Setting input event injection result to %d. "
Jeff Brown7fbdc842010-06-17 20:52:56 -07002729 "injectorPid=%d, injectorUid=%d",
Jeff Brown01ce2e92010-09-26 22:20:12 -07002730 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
Jeff Brown7fbdc842010-06-17 20:52:56 -07002731#endif
2732
Jeff Brown0029c662011-03-30 02:25:18 -07002733 if (injectionState->injectionIsAsync
2734 && !(entry->policyFlags & POLICY_FLAG_FILTERED)) {
Jeff Brown6ec402b2010-07-28 15:48:59 -07002735 // Log the outcome since the injector did not wait for the injection result.
2736 switch (injectionResult) {
2737 case INPUT_EVENT_INJECTION_SUCCEEDED:
Steve Block71f2cf12011-10-20 11:56:00 +01002738 ALOGV("Asynchronous input event injection succeeded.");
Jeff Brown6ec402b2010-07-28 15:48:59 -07002739 break;
2740 case INPUT_EVENT_INJECTION_FAILED:
Steve Block8564c8d2012-01-05 23:22:43 +00002741 ALOGW("Asynchronous input event injection failed.");
Jeff Brown6ec402b2010-07-28 15:48:59 -07002742 break;
2743 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
Steve Block8564c8d2012-01-05 23:22:43 +00002744 ALOGW("Asynchronous input event injection permission denied.");
Jeff Brown6ec402b2010-07-28 15:48:59 -07002745 break;
2746 case INPUT_EVENT_INJECTION_TIMED_OUT:
Steve Block8564c8d2012-01-05 23:22:43 +00002747 ALOGW("Asynchronous input event injection timed out.");
Jeff Brown6ec402b2010-07-28 15:48:59 -07002748 break;
2749 }
2750 }
2751
Jeff Brown01ce2e92010-09-26 22:20:12 -07002752 injectionState->injectionResult = injectionResult;
Jeff Brown7fbdc842010-06-17 20:52:56 -07002753 mInjectionResultAvailableCondition.broadcast();
2754 }
2755}
2756
Jeff Brown01ce2e92010-09-26 22:20:12 -07002757void InputDispatcher::incrementPendingForegroundDispatchesLocked(EventEntry* entry) {
2758 InjectionState* injectionState = entry->injectionState;
2759 if (injectionState) {
2760 injectionState->pendingForegroundDispatches += 1;
2761 }
2762}
2763
Jeff Brown519e0242010-09-15 15:18:56 -07002764void InputDispatcher::decrementPendingForegroundDispatchesLocked(EventEntry* entry) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002765 InjectionState* injectionState = entry->injectionState;
2766 if (injectionState) {
2767 injectionState->pendingForegroundDispatches -= 1;
Jeff Brown6ec402b2010-07-28 15:48:59 -07002768
Jeff Brown01ce2e92010-09-26 22:20:12 -07002769 if (injectionState->pendingForegroundDispatches == 0) {
2770 mInjectionSyncFinishedCondition.broadcast();
2771 }
Jeff Brownb88102f2010-09-08 11:49:43 -07002772 }
2773}
2774
Jeff Brown9302c872011-07-13 22:51:29 -07002775sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
2776 const sp<InputChannel>& inputChannel) const {
2777 size_t numWindows = mWindowHandles.size();
2778 for (size_t i = 0; i < numWindows; i++) {
2779 const sp<InputWindowHandle>& windowHandle = mWindowHandles.itemAt(i);
Jeff Browncc4f7db2011-08-30 20:34:48 -07002780 if (windowHandle->getInputChannel() == inputChannel) {
Jeff Brown9302c872011-07-13 22:51:29 -07002781 return windowHandle;
Jeff Brown01ce2e92010-09-26 22:20:12 -07002782 }
2783 }
2784 return NULL;
2785}
2786
Jeff Brown9302c872011-07-13 22:51:29 -07002787bool InputDispatcher::hasWindowHandleLocked(
2788 const sp<InputWindowHandle>& windowHandle) const {
2789 size_t numWindows = mWindowHandles.size();
2790 for (size_t i = 0; i < numWindows; i++) {
2791 if (mWindowHandles.itemAt(i) == windowHandle) {
2792 return true;
2793 }
2794 }
2795 return false;
2796}
2797
2798void InputDispatcher::setInputWindows(const Vector<sp<InputWindowHandle> >& inputWindowHandles) {
Jeff Brownb88102f2010-09-08 11:49:43 -07002799#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002800 ALOGD("setInputWindows");
Jeff Brownb88102f2010-09-08 11:49:43 -07002801#endif
2802 { // acquire lock
2803 AutoMutex _l(mLock);
2804
Jeff Browncc4f7db2011-08-30 20:34:48 -07002805 Vector<sp<InputWindowHandle> > oldWindowHandles = mWindowHandles;
Jeff Brown9302c872011-07-13 22:51:29 -07002806 mWindowHandles = inputWindowHandles;
Jeff Brownb6997262010-10-08 22:31:17 -07002807
Jeff Brown9302c872011-07-13 22:51:29 -07002808 sp<InputWindowHandle> newFocusedWindowHandle;
2809 bool foundHoveredWindow = false;
2810 for (size_t i = 0; i < mWindowHandles.size(); i++) {
2811 const sp<InputWindowHandle>& windowHandle = mWindowHandles.itemAt(i);
Jeff Browncc4f7db2011-08-30 20:34:48 -07002812 if (!windowHandle->updateInfo() || windowHandle->getInputChannel() == NULL) {
Jeff Brown9302c872011-07-13 22:51:29 -07002813 mWindowHandles.removeAt(i--);
2814 continue;
2815 }
Jeff Browncc4f7db2011-08-30 20:34:48 -07002816 if (windowHandle->getInfo()->hasFocus) {
Jeff Brown9302c872011-07-13 22:51:29 -07002817 newFocusedWindowHandle = windowHandle;
2818 }
2819 if (windowHandle == mLastHoverWindowHandle) {
2820 foundHoveredWindow = true;
Jeff Brownb88102f2010-09-08 11:49:43 -07002821 }
2822 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07002823
Jeff Brown9302c872011-07-13 22:51:29 -07002824 if (!foundHoveredWindow) {
2825 mLastHoverWindowHandle = NULL;
2826 }
2827
2828 if (mFocusedWindowHandle != newFocusedWindowHandle) {
2829 if (mFocusedWindowHandle != NULL) {
Jeff Brownb6997262010-10-08 22:31:17 -07002830#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002831 ALOGD("Focus left window: %s",
Jeff Browncc4f7db2011-08-30 20:34:48 -07002832 mFocusedWindowHandle->getName().string());
Jeff Brownb6997262010-10-08 22:31:17 -07002833#endif
Jeff Browncc4f7db2011-08-30 20:34:48 -07002834 sp<InputChannel> focusedInputChannel = mFocusedWindowHandle->getInputChannel();
2835 if (focusedInputChannel != NULL) {
Christopher Tated9be36c2011-08-16 16:09:33 -07002836 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
2837 "focus left window");
2838 synthesizeCancelationEventsForInputChannelLocked(
Jeff Browncc4f7db2011-08-30 20:34:48 -07002839 focusedInputChannel, options);
Christopher Tated9be36c2011-08-16 16:09:33 -07002840 }
Jeff Brownb6997262010-10-08 22:31:17 -07002841 }
Jeff Brown9302c872011-07-13 22:51:29 -07002842 if (newFocusedWindowHandle != NULL) {
Jeff Brownb6997262010-10-08 22:31:17 -07002843#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002844 ALOGD("Focus entered window: %s",
Jeff Browncc4f7db2011-08-30 20:34:48 -07002845 newFocusedWindowHandle->getName().string());
Jeff Brownb6997262010-10-08 22:31:17 -07002846#endif
Jeff Brown9302c872011-07-13 22:51:29 -07002847 }
2848 mFocusedWindowHandle = newFocusedWindowHandle;
Jeff Brownb6997262010-10-08 22:31:17 -07002849 }
2850
Jeff Brown9302c872011-07-13 22:51:29 -07002851 for (size_t i = 0; i < mTouchState.windows.size(); i++) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002852 TouchedWindow& touchedWindow = mTouchState.windows.editItemAt(i);
Jeff Brown9302c872011-07-13 22:51:29 -07002853 if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
Jeff Brownb6997262010-10-08 22:31:17 -07002854#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002855 ALOGD("Touched window was removed: %s",
Jeff Browncc4f7db2011-08-30 20:34:48 -07002856 touchedWindow.windowHandle->getName().string());
Jeff Brownb6997262010-10-08 22:31:17 -07002857#endif
Jeff Browncc4f7db2011-08-30 20:34:48 -07002858 sp<InputChannel> touchedInputChannel =
2859 touchedWindow.windowHandle->getInputChannel();
2860 if (touchedInputChannel != NULL) {
Christopher Tated9be36c2011-08-16 16:09:33 -07002861 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
2862 "touched window was removed");
2863 synthesizeCancelationEventsForInputChannelLocked(
Jeff Browncc4f7db2011-08-30 20:34:48 -07002864 touchedInputChannel, options);
Christopher Tated9be36c2011-08-16 16:09:33 -07002865 }
Jeff Brown9302c872011-07-13 22:51:29 -07002866 mTouchState.windows.removeAt(i--);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002867 }
2868 }
Jeff Browncc4f7db2011-08-30 20:34:48 -07002869
2870 // Release information for windows that are no longer present.
2871 // This ensures that unused input channels are released promptly.
2872 // Otherwise, they might stick around until the window handle is destroyed
2873 // which might not happen until the next GC.
2874 for (size_t i = 0; i < oldWindowHandles.size(); i++) {
2875 const sp<InputWindowHandle>& oldWindowHandle = oldWindowHandles.itemAt(i);
2876 if (!hasWindowHandleLocked(oldWindowHandle)) {
2877#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002878 ALOGD("Window went away: %s", oldWindowHandle->getName().string());
Jeff Browncc4f7db2011-08-30 20:34:48 -07002879#endif
2880 oldWindowHandle->releaseInfo();
2881 }
2882 }
Jeff Brownb88102f2010-09-08 11:49:43 -07002883 } // release lock
2884
2885 // Wake up poll loop since it may need to make new input dispatching choices.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002886 mLooper->wake();
Jeff Brownb88102f2010-09-08 11:49:43 -07002887}
2888
Jeff Brown9302c872011-07-13 22:51:29 -07002889void InputDispatcher::setFocusedApplication(
2890 const sp<InputApplicationHandle>& inputApplicationHandle) {
Jeff Brownb88102f2010-09-08 11:49:43 -07002891#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002892 ALOGD("setFocusedApplication");
Jeff Brownb88102f2010-09-08 11:49:43 -07002893#endif
2894 { // acquire lock
2895 AutoMutex _l(mLock);
2896
Jeff Browncc4f7db2011-08-30 20:34:48 -07002897 if (inputApplicationHandle != NULL && inputApplicationHandle->updateInfo()) {
Jeff Brown5ea29ab2011-07-27 11:50:51 -07002898 if (mFocusedApplicationHandle != inputApplicationHandle) {
2899 if (mFocusedApplicationHandle != NULL) {
Jeff Browne9bb9be2012-02-06 15:47:55 -08002900 resetANRTimeoutsLocked();
Jeff Browncc4f7db2011-08-30 20:34:48 -07002901 mFocusedApplicationHandle->releaseInfo();
Jeff Brown5ea29ab2011-07-27 11:50:51 -07002902 }
2903 mFocusedApplicationHandle = inputApplicationHandle;
2904 }
2905 } else if (mFocusedApplicationHandle != NULL) {
Jeff Browne9bb9be2012-02-06 15:47:55 -08002906 resetANRTimeoutsLocked();
Jeff Browncc4f7db2011-08-30 20:34:48 -07002907 mFocusedApplicationHandle->releaseInfo();
Jeff Brown9302c872011-07-13 22:51:29 -07002908 mFocusedApplicationHandle.clear();
Jeff Brownb88102f2010-09-08 11:49:43 -07002909 }
2910
2911#if DEBUG_FOCUS
Jeff Brownb6997262010-10-08 22:31:17 -07002912 //logDispatchStateLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -07002913#endif
2914 } // release lock
2915
2916 // Wake up poll loop since it may need to make new input dispatching choices.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002917 mLooper->wake();
Jeff Brownb88102f2010-09-08 11:49:43 -07002918}
2919
Jeff Brownb88102f2010-09-08 11:49:43 -07002920void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
2921#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002922 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
Jeff Brownb88102f2010-09-08 11:49:43 -07002923#endif
2924
2925 bool changed;
2926 { // acquire lock
2927 AutoMutex _l(mLock);
2928
2929 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
Jeff Brown120a4592010-10-27 18:43:51 -07002930 if (mDispatchFrozen && !frozen) {
Jeff Brownb88102f2010-09-08 11:49:43 -07002931 resetANRTimeoutsLocked();
2932 }
2933
Jeff Brown120a4592010-10-27 18:43:51 -07002934 if (mDispatchEnabled && !enabled) {
2935 resetAndDropEverythingLocked("dispatcher is being disabled");
2936 }
2937
Jeff Brownb88102f2010-09-08 11:49:43 -07002938 mDispatchEnabled = enabled;
2939 mDispatchFrozen = frozen;
2940 changed = true;
2941 } else {
2942 changed = false;
2943 }
2944
2945#if DEBUG_FOCUS
Jeff Brownb6997262010-10-08 22:31:17 -07002946 //logDispatchStateLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -07002947#endif
2948 } // release lock
2949
2950 if (changed) {
2951 // Wake up poll loop since it may need to make new input dispatching choices.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002952 mLooper->wake();
Jeff Brown46b9ac02010-04-22 18:58:52 -07002953 }
2954}
2955
Jeff Brown0029c662011-03-30 02:25:18 -07002956void InputDispatcher::setInputFilterEnabled(bool enabled) {
2957#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002958 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
Jeff Brown0029c662011-03-30 02:25:18 -07002959#endif
2960
2961 { // acquire lock
2962 AutoMutex _l(mLock);
2963
2964 if (mInputFilterEnabled == enabled) {
2965 return;
2966 }
2967
2968 mInputFilterEnabled = enabled;
2969 resetAndDropEverythingLocked("input filter is being enabled or disabled");
2970 } // release lock
2971
2972 // Wake up poll loop since there might be work to do to drop everything.
2973 mLooper->wake();
2974}
2975
Jeff Browne6504122010-09-27 14:52:15 -07002976bool InputDispatcher::transferTouchFocus(const sp<InputChannel>& fromChannel,
2977 const sp<InputChannel>& toChannel) {
2978#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002979 ALOGD("transferTouchFocus: fromChannel=%s, toChannel=%s",
Jeff Browne6504122010-09-27 14:52:15 -07002980 fromChannel->getName().string(), toChannel->getName().string());
2981#endif
2982 { // acquire lock
2983 AutoMutex _l(mLock);
2984
Jeff Brown9302c872011-07-13 22:51:29 -07002985 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromChannel);
2986 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toChannel);
2987 if (fromWindowHandle == NULL || toWindowHandle == NULL) {
Jeff Browne6504122010-09-27 14:52:15 -07002988#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002989 ALOGD("Cannot transfer focus because from or to window not found.");
Jeff Browne6504122010-09-27 14:52:15 -07002990#endif
2991 return false;
2992 }
Jeff Brown9302c872011-07-13 22:51:29 -07002993 if (fromWindowHandle == toWindowHandle) {
Jeff Browne6504122010-09-27 14:52:15 -07002994#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002995 ALOGD("Trivial transfer to same window.");
Jeff Browne6504122010-09-27 14:52:15 -07002996#endif
2997 return true;
2998 }
Jeff Brown83d616a2012-09-09 20:33:43 -07002999 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
3000#if DEBUG_FOCUS
3001 ALOGD("Cannot transfer focus because windows are on different displays.");
3002#endif
3003 return false;
3004 }
Jeff Browne6504122010-09-27 14:52:15 -07003005
3006 bool found = false;
3007 for (size_t i = 0; i < mTouchState.windows.size(); i++) {
3008 const TouchedWindow& touchedWindow = mTouchState.windows[i];
Jeff Brown9302c872011-07-13 22:51:29 -07003009 if (touchedWindow.windowHandle == fromWindowHandle) {
Jeff Browne6504122010-09-27 14:52:15 -07003010 int32_t oldTargetFlags = touchedWindow.targetFlags;
3011 BitSet32 pointerIds = touchedWindow.pointerIds;
3012
3013 mTouchState.windows.removeAt(i);
3014
Jeff Brown46e75292010-11-10 16:53:45 -08003015 int32_t newTargetFlags = oldTargetFlags
Jeff Browna032cc02011-03-07 16:56:21 -08003016 & (InputTarget::FLAG_FOREGROUND
3017 | InputTarget::FLAG_SPLIT | InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brown9302c872011-07-13 22:51:29 -07003018 mTouchState.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Jeff Browne6504122010-09-27 14:52:15 -07003019
3020 found = true;
3021 break;
3022 }
3023 }
3024
3025 if (! found) {
3026#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00003027 ALOGD("Focus transfer failed because from window did not have focus.");
Jeff Browne6504122010-09-27 14:52:15 -07003028#endif
3029 return false;
3030 }
3031
Jeff Brown9c9f1a32010-10-11 18:32:20 -07003032 ssize_t fromConnectionIndex = getConnectionIndexLocked(fromChannel);
3033 ssize_t toConnectionIndex = getConnectionIndexLocked(toChannel);
3034 if (fromConnectionIndex >= 0 && toConnectionIndex >= 0) {
Jeff Browncbee6d62012-02-03 20:11:27 -08003035 sp<Connection> fromConnection = mConnectionsByFd.valueAt(fromConnectionIndex);
3036 sp<Connection> toConnection = mConnectionsByFd.valueAt(toConnectionIndex);
Jeff Brown9c9f1a32010-10-11 18:32:20 -07003037
3038 fromConnection->inputState.copyPointerStateTo(toConnection->inputState);
Jeff Brownda3d5a92011-03-29 15:11:34 -07003039 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Jeff Brown9c9f1a32010-10-11 18:32:20 -07003040 "transferring touch focus from this window to another window");
Jeff Brownda3d5a92011-03-29 15:11:34 -07003041 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Jeff Brown9c9f1a32010-10-11 18:32:20 -07003042 }
3043
Jeff Browne6504122010-09-27 14:52:15 -07003044#if DEBUG_FOCUS
3045 logDispatchStateLocked();
3046#endif
3047 } // release lock
3048
3049 // Wake up poll loop since it may need to make new input dispatching choices.
3050 mLooper->wake();
3051 return true;
3052}
3053
Jeff Brown120a4592010-10-27 18:43:51 -07003054void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
3055#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00003056 ALOGD("Resetting and dropping all events (%s).", reason);
Jeff Brown120a4592010-10-27 18:43:51 -07003057#endif
3058
Jeff Brownda3d5a92011-03-29 15:11:34 -07003059 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
3060 synthesizeCancelationEventsForAllConnectionsLocked(options);
Jeff Brown120a4592010-10-27 18:43:51 -07003061
3062 resetKeyRepeatLocked();
3063 releasePendingEventLocked();
3064 drainInboundQueueLocked();
Jeff Browne9bb9be2012-02-06 15:47:55 -08003065 resetANRTimeoutsLocked();
Jeff Brown120a4592010-10-27 18:43:51 -07003066
3067 mTouchState.reset();
Jeff Brown9302c872011-07-13 22:51:29 -07003068 mLastHoverWindowHandle.clear();
Jeff Brown120a4592010-10-27 18:43:51 -07003069}
3070
Jeff Brownb88102f2010-09-08 11:49:43 -07003071void InputDispatcher::logDispatchStateLocked() {
3072 String8 dump;
3073 dumpDispatchStateLocked(dump);
Jeff Brown2a95c2a2010-09-16 12:31:46 -07003074
3075 char* text = dump.lockBuffer(dump.size());
3076 char* start = text;
3077 while (*start != '\0') {
3078 char* end = strchr(start, '\n');
3079 if (*end == '\n') {
3080 *(end++) = '\0';
3081 }
Steve Block5baa3a62011-12-20 16:23:08 +00003082 ALOGD("%s", start);
Jeff Brown2a95c2a2010-09-16 12:31:46 -07003083 start = end;
3084 }
Jeff Brownb88102f2010-09-08 11:49:43 -07003085}
3086
3087void InputDispatcher::dumpDispatchStateLocked(String8& dump) {
Jeff Brownf2f48712010-10-01 17:46:21 -07003088 dump.appendFormat(INDENT "DispatchEnabled: %d\n", mDispatchEnabled);
3089 dump.appendFormat(INDENT "DispatchFrozen: %d\n", mDispatchFrozen);
Jeff Brownb88102f2010-09-08 11:49:43 -07003090
Jeff Brown9302c872011-07-13 22:51:29 -07003091 if (mFocusedApplicationHandle != NULL) {
Jeff Brownf2f48712010-10-01 17:46:21 -07003092 dump.appendFormat(INDENT "FocusedApplication: name='%s', dispatchingTimeout=%0.3fms\n",
Jeff Browncc4f7db2011-08-30 20:34:48 -07003093 mFocusedApplicationHandle->getName().string(),
3094 mFocusedApplicationHandle->getDispatchingTimeout(
3095 DEFAULT_INPUT_DISPATCHING_TIMEOUT) / 1000000.0);
Jeff Brownb88102f2010-09-08 11:49:43 -07003096 } else {
Jeff Brownf2f48712010-10-01 17:46:21 -07003097 dump.append(INDENT "FocusedApplication: <null>\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003098 }
Jeff Brownf2f48712010-10-01 17:46:21 -07003099 dump.appendFormat(INDENT "FocusedWindow: name='%s'\n",
Jeff Browncc4f7db2011-08-30 20:34:48 -07003100 mFocusedWindowHandle != NULL ? mFocusedWindowHandle->getName().string() : "<null>");
Jeff Brownf2f48712010-10-01 17:46:21 -07003101
3102 dump.appendFormat(INDENT "TouchDown: %s\n", toString(mTouchState.down));
3103 dump.appendFormat(INDENT "TouchSplit: %s\n", toString(mTouchState.split));
Jeff Brown95712852011-01-04 19:41:59 -08003104 dump.appendFormat(INDENT "TouchDeviceId: %d\n", mTouchState.deviceId);
Jeff Brown58a2da82011-01-25 16:02:22 -08003105 dump.appendFormat(INDENT "TouchSource: 0x%08x\n", mTouchState.source);
Jeff Brown83d616a2012-09-09 20:33:43 -07003106 dump.appendFormat(INDENT "TouchDisplayId: %d\n", mTouchState.displayId);
Jeff Brownf2f48712010-10-01 17:46:21 -07003107 if (!mTouchState.windows.isEmpty()) {
3108 dump.append(INDENT "TouchedWindows:\n");
3109 for (size_t i = 0; i < mTouchState.windows.size(); i++) {
3110 const TouchedWindow& touchedWindow = mTouchState.windows[i];
3111 dump.appendFormat(INDENT2 "%d: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
Jeff Browncc4f7db2011-08-30 20:34:48 -07003112 i, touchedWindow.windowHandle->getName().string(),
3113 touchedWindow.pointerIds.value,
Jeff Brownf2f48712010-10-01 17:46:21 -07003114 touchedWindow.targetFlags);
3115 }
3116 } else {
3117 dump.append(INDENT "TouchedWindows: <none>\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003118 }
3119
Jeff Brown9302c872011-07-13 22:51:29 -07003120 if (!mWindowHandles.isEmpty()) {
Jeff Brownf2f48712010-10-01 17:46:21 -07003121 dump.append(INDENT "Windows:\n");
Jeff Brown9302c872011-07-13 22:51:29 -07003122 for (size_t i = 0; i < mWindowHandles.size(); i++) {
3123 const sp<InputWindowHandle>& windowHandle = mWindowHandles.itemAt(i);
Jeff Browncc4f7db2011-08-30 20:34:48 -07003124 const InputWindowInfo* windowInfo = windowHandle->getInfo();
3125
Jeff Brown83d616a2012-09-09 20:33:43 -07003126 dump.appendFormat(INDENT2 "%d: name='%s', displayId=%d, "
3127 "paused=%s, hasFocus=%s, hasWallpaper=%s, "
Jeff Brownf2f48712010-10-01 17:46:21 -07003128 "visible=%s, canReceiveKeys=%s, flags=0x%08x, type=0x%08x, layer=%d, "
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003129 "frame=[%d,%d][%d,%d], scale=%f, "
Jeff Brownfbf09772011-01-16 14:06:57 -08003130 "touchableRegion=",
Jeff Brown83d616a2012-09-09 20:33:43 -07003131 i, windowInfo->name.string(), windowInfo->displayId,
Jeff Browncc4f7db2011-08-30 20:34:48 -07003132 toString(windowInfo->paused),
3133 toString(windowInfo->hasFocus),
3134 toString(windowInfo->hasWallpaper),
3135 toString(windowInfo->visible),
3136 toString(windowInfo->canReceiveKeys),
3137 windowInfo->layoutParamsFlags, windowInfo->layoutParamsType,
3138 windowInfo->layer,
3139 windowInfo->frameLeft, windowInfo->frameTop,
3140 windowInfo->frameRight, windowInfo->frameBottom,
3141 windowInfo->scaleFactor);
3142 dumpRegion(dump, windowInfo->touchableRegion);
3143 dump.appendFormat(", inputFeatures=0x%08x", windowInfo->inputFeatures);
Jeff Brownfbf09772011-01-16 14:06:57 -08003144 dump.appendFormat(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%0.3fms\n",
Jeff Browncc4f7db2011-08-30 20:34:48 -07003145 windowInfo->ownerPid, windowInfo->ownerUid,
3146 windowInfo->dispatchingTimeout / 1000000.0);
Jeff Brownf2f48712010-10-01 17:46:21 -07003147 }
3148 } else {
3149 dump.append(INDENT "Windows: <none>\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003150 }
3151
Jeff Brownf2f48712010-10-01 17:46:21 -07003152 if (!mMonitoringChannels.isEmpty()) {
3153 dump.append(INDENT "MonitoringChannels:\n");
3154 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
3155 const sp<InputChannel>& channel = mMonitoringChannels[i];
3156 dump.appendFormat(INDENT2 "%d: '%s'\n", i, channel->getName().string());
3157 }
3158 } else {
3159 dump.append(INDENT "MonitoringChannels: <none>\n");
3160 }
Jeff Brown519e0242010-09-15 15:18:56 -07003161
Jeff Brown265f1cc2012-06-11 18:01:06 -07003162 nsecs_t currentTime = now();
3163
3164 if (!mInboundQueue.isEmpty()) {
3165 dump.appendFormat(INDENT "InboundQueue: length=%u\n", mInboundQueue.count());
3166 for (EventEntry* entry = mInboundQueue.head; entry; entry = entry->next) {
3167 dump.append(INDENT2);
3168 entry->appendDescription(dump);
Jeff Brown22aa5122012-06-17 12:01:06 -07003169 dump.appendFormat(", age=%0.1fms\n",
Jeff Brown265f1cc2012-06-11 18:01:06 -07003170 (currentTime - entry->eventTime) * 0.000001f);
3171 }
3172 } else {
3173 dump.append(INDENT "InboundQueue: <empty>\n");
3174 }
3175
3176 if (!mConnectionsByFd.isEmpty()) {
3177 dump.append(INDENT "Connections:\n");
3178 for (size_t i = 0; i < mConnectionsByFd.size(); i++) {
3179 const sp<Connection>& connection = mConnectionsByFd.valueAt(i);
3180 dump.appendFormat(INDENT2 "%d: channelName='%s', windowName='%s', "
3181 "status=%s, monitor=%s, inputPublisherBlocked=%s\n",
3182 i, connection->getInputChannelName(), connection->getWindowName(),
3183 connection->getStatusLabel(), toString(connection->monitor),
3184 toString(connection->inputPublisherBlocked));
3185
3186 if (!connection->outboundQueue.isEmpty()) {
3187 dump.appendFormat(INDENT3 "OutboundQueue: length=%u\n",
3188 connection->outboundQueue.count());
3189 for (DispatchEntry* entry = connection->outboundQueue.head; entry;
3190 entry = entry->next) {
3191 dump.append(INDENT4);
3192 entry->eventEntry->appendDescription(dump);
Jeff Brown22aa5122012-06-17 12:01:06 -07003193 dump.appendFormat(", targetFlags=0x%08x, resolvedAction=%d, age=%0.1fms\n",
Jeff Brown265f1cc2012-06-11 18:01:06 -07003194 entry->targetFlags, entry->resolvedAction,
3195 (currentTime - entry->eventEntry->eventTime) * 0.000001f);
3196 }
3197 } else {
3198 dump.append(INDENT3 "OutboundQueue: <empty>\n");
3199 }
3200
3201 if (!connection->waitQueue.isEmpty()) {
3202 dump.appendFormat(INDENT3 "WaitQueue: length=%u\n",
3203 connection->waitQueue.count());
3204 for (DispatchEntry* entry = connection->waitQueue.head; entry;
3205 entry = entry->next) {
3206 dump.append(INDENT4);
3207 entry->eventEntry->appendDescription(dump);
3208 dump.appendFormat(", targetFlags=0x%08x, resolvedAction=%d, "
Jeff Brown22aa5122012-06-17 12:01:06 -07003209 "age=%0.1fms, wait=%0.1fms\n",
Jeff Brown265f1cc2012-06-11 18:01:06 -07003210 entry->targetFlags, entry->resolvedAction,
3211 (currentTime - entry->eventEntry->eventTime) * 0.000001f,
3212 (currentTime - entry->deliveryTime) * 0.000001f);
3213 }
3214 } else {
3215 dump.append(INDENT3 "WaitQueue: <empty>\n");
3216 }
3217 }
3218 } else {
3219 dump.append(INDENT "Connections: <none>\n");
3220 }
Jeff Brownf2f48712010-10-01 17:46:21 -07003221
Jeff Brownb88102f2010-09-08 11:49:43 -07003222 if (isAppSwitchPendingLocked()) {
Jeff Brown22aa5122012-06-17 12:01:06 -07003223 dump.appendFormat(INDENT "AppSwitch: pending, due in %0.1fms\n",
Jeff Brownb88102f2010-09-08 11:49:43 -07003224 (mAppSwitchDueTime - now()) / 1000000.0);
3225 } else {
Jeff Brownf2f48712010-10-01 17:46:21 -07003226 dump.append(INDENT "AppSwitch: not pending\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003227 }
Jeff Brown22aa5122012-06-17 12:01:06 -07003228
3229 dump.append(INDENT "Configuration:\n");
3230 dump.appendFormat(INDENT2 "KeyRepeatDelay: %0.1fms\n",
3231 mConfig.keyRepeatDelay * 0.000001f);
3232 dump.appendFormat(INDENT2 "KeyRepeatTimeout: %0.1fms\n",
3233 mConfig.keyRepeatTimeout * 0.000001f);
Jeff Brownb88102f2010-09-08 11:49:43 -07003234}
3235
Jeff Brown928e0542011-01-10 11:17:36 -08003236status_t InputDispatcher::registerInputChannel(const sp<InputChannel>& inputChannel,
3237 const sp<InputWindowHandle>& inputWindowHandle, bool monitor) {
Jeff Brown9c3cda02010-06-15 01:31:58 -07003238#if DEBUG_REGISTRATION
Steve Block5baa3a62011-12-20 16:23:08 +00003239 ALOGD("channel '%s' ~ registerInputChannel - monitor=%s", inputChannel->getName().string(),
Jeff Brownb88102f2010-09-08 11:49:43 -07003240 toString(monitor));
Jeff Brown9c3cda02010-06-15 01:31:58 -07003241#endif
3242
Jeff Brown46b9ac02010-04-22 18:58:52 -07003243 { // acquire lock
3244 AutoMutex _l(mLock);
3245
Jeff Brown519e0242010-09-15 15:18:56 -07003246 if (getConnectionIndexLocked(inputChannel) >= 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00003247 ALOGW("Attempted to register already registered input channel '%s'",
Jeff Brown46b9ac02010-04-22 18:58:52 -07003248 inputChannel->getName().string());
3249 return BAD_VALUE;
3250 }
3251
Jeff Browncc4f7db2011-08-30 20:34:48 -07003252 sp<Connection> connection = new Connection(inputChannel, inputWindowHandle, monitor);
Jeff Brown46b9ac02010-04-22 18:58:52 -07003253
Jeff Brown91e32892012-02-14 15:56:29 -08003254 int fd = inputChannel->getFd();
Jeff Browncbee6d62012-02-03 20:11:27 -08003255 mConnectionsByFd.add(fd, connection);
Jeff Brown9c3cda02010-06-15 01:31:58 -07003256
Jeff Brownb88102f2010-09-08 11:49:43 -07003257 if (monitor) {
3258 mMonitoringChannels.push(inputChannel);
3259 }
3260
Jeff Browncbee6d62012-02-03 20:11:27 -08003261 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
Jeff Brown46b9ac02010-04-22 18:58:52 -07003262 } // release lock
Jeff Brown074b8b72012-10-31 19:01:31 -07003263
3264 // Wake the looper because some connections have changed.
3265 mLooper->wake();
Jeff Brown46b9ac02010-04-22 18:58:52 -07003266 return OK;
3267}
3268
3269status_t InputDispatcher::unregisterInputChannel(const sp<InputChannel>& inputChannel) {
Jeff Brown9c3cda02010-06-15 01:31:58 -07003270#if DEBUG_REGISTRATION
Steve Block5baa3a62011-12-20 16:23:08 +00003271 ALOGD("channel '%s' ~ unregisterInputChannel", inputChannel->getName().string());
Jeff Brown9c3cda02010-06-15 01:31:58 -07003272#endif
3273
Jeff Brown46b9ac02010-04-22 18:58:52 -07003274 { // acquire lock
3275 AutoMutex _l(mLock);
3276
Jeff Browncc4f7db2011-08-30 20:34:48 -07003277 status_t status = unregisterInputChannelLocked(inputChannel, false /*notify*/);
3278 if (status) {
3279 return status;
Jeff Brown46b9ac02010-04-22 18:58:52 -07003280 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07003281 } // release lock
3282
Jeff Brown46b9ac02010-04-22 18:58:52 -07003283 // Wake the poll loop because removing the connection may have changed the current
3284 // synchronization state.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07003285 mLooper->wake();
Jeff Brown46b9ac02010-04-22 18:58:52 -07003286 return OK;
3287}
3288
Jeff Browncc4f7db2011-08-30 20:34:48 -07003289status_t InputDispatcher::unregisterInputChannelLocked(const sp<InputChannel>& inputChannel,
3290 bool notify) {
3291 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
3292 if (connectionIndex < 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00003293 ALOGW("Attempted to unregister already unregistered input channel '%s'",
Jeff Browncc4f7db2011-08-30 20:34:48 -07003294 inputChannel->getName().string());
3295 return BAD_VALUE;
3296 }
3297
Jeff Browncbee6d62012-02-03 20:11:27 -08003298 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
3299 mConnectionsByFd.removeItemsAt(connectionIndex);
Jeff Browncc4f7db2011-08-30 20:34:48 -07003300
3301 if (connection->monitor) {
3302 removeMonitorChannelLocked(inputChannel);
3303 }
3304
Jeff Browncbee6d62012-02-03 20:11:27 -08003305 mLooper->removeFd(inputChannel->getFd());
Jeff Browncc4f7db2011-08-30 20:34:48 -07003306
3307 nsecs_t currentTime = now();
3308 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
3309
Jeff Browncc4f7db2011-08-30 20:34:48 -07003310 connection->status = Connection::STATUS_ZOMBIE;
3311 return OK;
3312}
3313
3314void InputDispatcher::removeMonitorChannelLocked(const sp<InputChannel>& inputChannel) {
3315 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
3316 if (mMonitoringChannels[i] == inputChannel) {
3317 mMonitoringChannels.removeAt(i);
3318 break;
3319 }
3320 }
3321}
3322
Jeff Brown519e0242010-09-15 15:18:56 -07003323ssize_t InputDispatcher::getConnectionIndexLocked(const sp<InputChannel>& inputChannel) {
Jeff Browncbee6d62012-02-03 20:11:27 -08003324 ssize_t connectionIndex = mConnectionsByFd.indexOfKey(inputChannel->getFd());
Jeff Brown2cbecea2010-08-17 15:59:26 -07003325 if (connectionIndex >= 0) {
Jeff Browncbee6d62012-02-03 20:11:27 -08003326 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
Jeff Brown2cbecea2010-08-17 15:59:26 -07003327 if (connection->inputChannel.get() == inputChannel.get()) {
3328 return connectionIndex;
3329 }
3330 }
3331
3332 return -1;
3333}
3334
Jeff Brown9c3cda02010-06-15 01:31:58 -07003335void InputDispatcher::onDispatchCycleFinishedLocked(
Jeff Brown072ec962012-02-07 14:46:57 -08003336 nsecs_t currentTime, const sp<Connection>& connection, uint32_t seq, bool handled) {
Jeff Brown3915bb82010-11-05 15:02:16 -07003337 CommandEntry* commandEntry = postCommandLocked(
3338 & InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
3339 commandEntry->connection = connection;
Jeff Brown265f1cc2012-06-11 18:01:06 -07003340 commandEntry->eventTime = currentTime;
Jeff Brown072ec962012-02-07 14:46:57 -08003341 commandEntry->seq = seq;
Jeff Brown3915bb82010-11-05 15:02:16 -07003342 commandEntry->handled = handled;
Jeff Brown46b9ac02010-04-22 18:58:52 -07003343}
3344
Jeff Brown9c3cda02010-06-15 01:31:58 -07003345void InputDispatcher::onDispatchCycleBrokenLocked(
Jeff Brown7fbdc842010-06-17 20:52:56 -07003346 nsecs_t currentTime, const sp<Connection>& connection) {
Steve Block3762c312012-01-06 19:20:56 +00003347 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Jeff Brown46b9ac02010-04-22 18:58:52 -07003348 connection->getInputChannelName());
3349
Jeff Brown9c3cda02010-06-15 01:31:58 -07003350 CommandEntry* commandEntry = postCommandLocked(
3351 & InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
Jeff Brown7fbdc842010-06-17 20:52:56 -07003352 commandEntry->connection = connection;
Jeff Brown46b9ac02010-04-22 18:58:52 -07003353}
3354
Jeff Brown519e0242010-09-15 15:18:56 -07003355void InputDispatcher::onANRLocked(
Jeff Brown9302c872011-07-13 22:51:29 -07003356 nsecs_t currentTime, const sp<InputApplicationHandle>& applicationHandle,
3357 const sp<InputWindowHandle>& windowHandle,
Jeff Brown265f1cc2012-06-11 18:01:06 -07003358 nsecs_t eventTime, nsecs_t waitStartTime, const char* reason) {
Jeff Brown22aa5122012-06-17 12:01:06 -07003359 float dispatchLatency = (currentTime - eventTime) * 0.000001f;
3360 float waitDuration = (currentTime - waitStartTime) * 0.000001f;
Steve Block6215d3f2012-01-04 20:05:49 +00003361 ALOGI("Application is not responding: %s. "
Jeff Brown22aa5122012-06-17 12:01:06 -07003362 "It has been %0.1fms since event, %0.1fms since wait started. Reason: %s",
Jeff Brown9302c872011-07-13 22:51:29 -07003363 getApplicationWindowLabelLocked(applicationHandle, windowHandle).string(),
Jeff Brown22aa5122012-06-17 12:01:06 -07003364 dispatchLatency, waitDuration, reason);
3365
3366 // Capture a record of the InputDispatcher state at the time of the ANR.
3367 time_t t = time(NULL);
3368 struct tm tm;
3369 localtime_r(&t, &tm);
3370 char timestr[64];
3371 strftime(timestr, sizeof(timestr), "%F %T", &tm);
3372 mLastANRState.clear();
3373 mLastANRState.append(INDENT "ANR:\n");
3374 mLastANRState.appendFormat(INDENT2 "Time: %s\n", timestr);
3375 mLastANRState.appendFormat(INDENT2 "Window: %s\n",
3376 getApplicationWindowLabelLocked(applicationHandle, windowHandle).string());
3377 mLastANRState.appendFormat(INDENT2 "DispatchLatency: %0.1fms\n", dispatchLatency);
3378 mLastANRState.appendFormat(INDENT2 "WaitDuration: %0.1fms\n", waitDuration);
3379 mLastANRState.appendFormat(INDENT2 "Reason: %s\n", reason);
3380 dumpDispatchStateLocked(mLastANRState);
Jeff Brown519e0242010-09-15 15:18:56 -07003381
3382 CommandEntry* commandEntry = postCommandLocked(
3383 & InputDispatcher::doNotifyANRLockedInterruptible);
Jeff Brown9302c872011-07-13 22:51:29 -07003384 commandEntry->inputApplicationHandle = applicationHandle;
3385 commandEntry->inputWindowHandle = windowHandle;
Jeff Brown519e0242010-09-15 15:18:56 -07003386}
3387
Jeff Brownb88102f2010-09-08 11:49:43 -07003388void InputDispatcher::doNotifyConfigurationChangedInterruptible(
3389 CommandEntry* commandEntry) {
3390 mLock.unlock();
3391
3392 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
3393
3394 mLock.lock();
3395}
3396
Jeff Brown9c3cda02010-06-15 01:31:58 -07003397void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(
3398 CommandEntry* commandEntry) {
Jeff Brown7fbdc842010-06-17 20:52:56 -07003399 sp<Connection> connection = commandEntry->connection;
Jeff Brown9c3cda02010-06-15 01:31:58 -07003400
Jeff Brown7fbdc842010-06-17 20:52:56 -07003401 if (connection->status != Connection::STATUS_ZOMBIE) {
3402 mLock.unlock();
Jeff Brown9c3cda02010-06-15 01:31:58 -07003403
Jeff Brown928e0542011-01-10 11:17:36 -08003404 mPolicy->notifyInputChannelBroken(connection->inputWindowHandle);
Jeff Brown7fbdc842010-06-17 20:52:56 -07003405
3406 mLock.lock();
3407 }
Jeff Brown9c3cda02010-06-15 01:31:58 -07003408}
3409
Jeff Brown519e0242010-09-15 15:18:56 -07003410void InputDispatcher::doNotifyANRLockedInterruptible(
Jeff Brown9c3cda02010-06-15 01:31:58 -07003411 CommandEntry* commandEntry) {
Jeff Brown519e0242010-09-15 15:18:56 -07003412 mLock.unlock();
Jeff Brown9c3cda02010-06-15 01:31:58 -07003413
Jeff Brown519e0242010-09-15 15:18:56 -07003414 nsecs_t newTimeout = mPolicy->notifyANR(
Jeff Brown928e0542011-01-10 11:17:36 -08003415 commandEntry->inputApplicationHandle, commandEntry->inputWindowHandle);
Jeff Brown9c3cda02010-06-15 01:31:58 -07003416
Jeff Brown519e0242010-09-15 15:18:56 -07003417 mLock.lock();
Jeff Brown7fbdc842010-06-17 20:52:56 -07003418
Jeff Brown9302c872011-07-13 22:51:29 -07003419 resumeAfterTargetsNotReadyTimeoutLocked(newTimeout,
3420 commandEntry->inputWindowHandle != NULL
Jeff Browncc4f7db2011-08-30 20:34:48 -07003421 ? commandEntry->inputWindowHandle->getInputChannel() : NULL);
Jeff Brown9c3cda02010-06-15 01:31:58 -07003422}
3423
Jeff Brownb88102f2010-09-08 11:49:43 -07003424void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
3425 CommandEntry* commandEntry) {
3426 KeyEntry* entry = commandEntry->keyEntry;
Jeff Brown1f245102010-11-18 20:53:46 -08003427
3428 KeyEvent event;
3429 initializeKeyEvent(&event, entry);
Jeff Brownb88102f2010-09-08 11:49:43 -07003430
3431 mLock.unlock();
3432
Jeff Brown905805a2011-10-12 13:57:59 -07003433 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(commandEntry->inputWindowHandle,
Jeff Brown1f245102010-11-18 20:53:46 -08003434 &event, entry->policyFlags);
Jeff Brownb88102f2010-09-08 11:49:43 -07003435
3436 mLock.lock();
3437
Jeff Brown905805a2011-10-12 13:57:59 -07003438 if (delay < 0) {
3439 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
3440 } else if (!delay) {
3441 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
3442 } else {
3443 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
3444 entry->interceptKeyWakeupTime = now() + delay;
3445 }
Jeff Brownac386072011-07-20 15:19:50 -07003446 entry->release();
Jeff Brownb88102f2010-09-08 11:49:43 -07003447}
3448
Jeff Brown3915bb82010-11-05 15:02:16 -07003449void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(
3450 CommandEntry* commandEntry) {
3451 sp<Connection> connection = commandEntry->connection;
Jeff Brown265f1cc2012-06-11 18:01:06 -07003452 nsecs_t finishTime = commandEntry->eventTime;
Jeff Brown072ec962012-02-07 14:46:57 -08003453 uint32_t seq = commandEntry->seq;
Jeff Brown3915bb82010-11-05 15:02:16 -07003454 bool handled = commandEntry->handled;
3455
Jeff Brown072ec962012-02-07 14:46:57 -08003456 // Handle post-event policy actions.
3457 DispatchEntry* dispatchEntry = connection->findWaitQueueEntry(seq);
3458 if (dispatchEntry) {
Jeff Brown265f1cc2012-06-11 18:01:06 -07003459 nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
3460 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
3461 String8 msg;
Jeff Brown22aa5122012-06-17 12:01:06 -07003462 msg.appendFormat("Window '%s' spent %0.1fms processing the last input event: ",
Jeff Brown265f1cc2012-06-11 18:01:06 -07003463 connection->getWindowName(), eventDuration * 0.000001f);
3464 dispatchEntry->eventEntry->appendDescription(msg);
3465 ALOGI("%s", msg.string());
3466 }
3467
Jeff Brownd1c48a02012-02-06 19:12:47 -08003468 bool restartEvent;
Jeff Brownd1c48a02012-02-06 19:12:47 -08003469 if (dispatchEntry->eventEntry->type == EventEntry::TYPE_KEY) {
3470 KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry);
3471 restartEvent = afterKeyEventLockedInterruptible(connection,
3472 dispatchEntry, keyEntry, handled);
3473 } else if (dispatchEntry->eventEntry->type == EventEntry::TYPE_MOTION) {
3474 MotionEntry* motionEntry = static_cast<MotionEntry*>(dispatchEntry->eventEntry);
3475 restartEvent = afterMotionEventLockedInterruptible(connection,
3476 dispatchEntry, motionEntry, handled);
3477 } else {
3478 restartEvent = false;
3479 }
3480
3481 // Dequeue the event and start the next cycle.
3482 // Note that because the lock might have been released, it is possible that the
3483 // contents of the wait queue to have been drained, so we need to double-check
3484 // a few things.
Jeff Brown072ec962012-02-07 14:46:57 -08003485 if (dispatchEntry == connection->findWaitQueueEntry(seq)) {
3486 connection->waitQueue.dequeue(dispatchEntry);
Jeff Brown481c1572012-03-09 14:41:15 -08003487 traceWaitQueueLengthLocked(connection);
Jeff Brownd1c48a02012-02-06 19:12:47 -08003488 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
3489 connection->outboundQueue.enqueueAtHead(dispatchEntry);
Jeff Brown481c1572012-03-09 14:41:15 -08003490 traceOutboundQueueLengthLocked(connection);
Jeff Brownd1c48a02012-02-06 19:12:47 -08003491 } else {
3492 releaseDispatchEntryLocked(dispatchEntry);
Jeff Brown49ed71d2010-12-06 17:13:33 -08003493 }
Jeff Brown3915bb82010-11-05 15:02:16 -07003494 }
Jeff Brown3915bb82010-11-05 15:02:16 -07003495
Jeff Brownd1c48a02012-02-06 19:12:47 -08003496 // Start the next dispatch cycle for this connection.
3497 startDispatchCycleLocked(now(), connection);
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003498 }
3499}
3500
3501bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
3502 DispatchEntry* dispatchEntry, KeyEntry* keyEntry, bool handled) {
3503 if (!(keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK)) {
3504 // Get the fallback key state.
3505 // Clear it out after dispatching the UP.
3506 int32_t originalKeyCode = keyEntry->keyCode;
3507 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
3508 if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
3509 connection->inputState.removeFallbackKey(originalKeyCode);
3510 }
3511
3512 if (handled || !dispatchEntry->hasForegroundTarget()) {
3513 // If the application handles the original key for which we previously
3514 // generated a fallback or if the window is not a foreground window,
3515 // then cancel the associated fallback key, if any.
3516 if (fallbackKeyCode != -1) {
Jeff Brownfd23e3e2012-05-09 13:34:28 -07003517 // Dispatch the unhandled key to the policy with the cancel flag.
3518#if DEBUG_OUTBOUND_EVENT_DETAILS
3519 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
3520 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
3521 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
3522 keyEntry->policyFlags);
3523#endif
3524 KeyEvent event;
3525 initializeKeyEvent(&event, keyEntry);
3526 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
3527
3528 mLock.unlock();
3529
3530 mPolicy->dispatchUnhandledKey(connection->inputWindowHandle,
3531 &event, keyEntry->policyFlags, &event);
3532
3533 mLock.lock();
3534
3535 // Cancel the fallback key.
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003536 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
3537 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
3538 "application handled the original non-fallback key "
3539 "or is no longer a foreground target, "
3540 "canceling previously dispatched fallback key");
3541 options.keyCode = fallbackKeyCode;
3542 synthesizeCancelationEventsForConnectionLocked(connection, options);
3543 }
3544 connection->inputState.removeFallbackKey(originalKeyCode);
3545 }
3546 } else {
3547 // If the application did not handle a non-fallback key, first check
3548 // that we are in a good state to perform unhandled key event processing
3549 // Then ask the policy what to do with it.
3550 bool initialDown = keyEntry->action == AKEY_EVENT_ACTION_DOWN
3551 && keyEntry->repeatCount == 0;
3552 if (fallbackKeyCode == -1 && !initialDown) {
3553#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00003554 ALOGD("Unhandled key event: Skipping unhandled key event processing "
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003555 "since this is not an initial down. "
Jeff Brownfd23e3e2012-05-09 13:34:28 -07003556 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
3557 originalKeyCode, keyEntry->action, keyEntry->repeatCount,
3558 keyEntry->policyFlags);
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003559#endif
3560 return false;
3561 }
3562
3563 // Dispatch the unhandled key to the policy.
3564#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00003565 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
Jeff Brownfd23e3e2012-05-09 13:34:28 -07003566 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
3567 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
3568 keyEntry->policyFlags);
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003569#endif
3570 KeyEvent event;
3571 initializeKeyEvent(&event, keyEntry);
3572
3573 mLock.unlock();
3574
3575 bool fallback = mPolicy->dispatchUnhandledKey(connection->inputWindowHandle,
3576 &event, keyEntry->policyFlags, &event);
3577
3578 mLock.lock();
3579
3580 if (connection->status != Connection::STATUS_NORMAL) {
3581 connection->inputState.removeFallbackKey(originalKeyCode);
Jeff Brownd1c48a02012-02-06 19:12:47 -08003582 return false;
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003583 }
3584
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003585 // Latch the fallback keycode for this key on an initial down.
3586 // The fallback keycode cannot change at any other point in the lifecycle.
3587 if (initialDown) {
3588 if (fallback) {
3589 fallbackKeyCode = event.getKeyCode();
3590 } else {
3591 fallbackKeyCode = AKEYCODE_UNKNOWN;
3592 }
3593 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
3594 }
3595
Steve Blockec193de2012-01-09 18:35:44 +00003596 ALOG_ASSERT(fallbackKeyCode != -1);
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003597
3598 // Cancel the fallback key if the policy decides not to send it anymore.
3599 // We will continue to dispatch the key to the policy but we will no
3600 // longer dispatch a fallback key to the application.
3601 if (fallbackKeyCode != AKEYCODE_UNKNOWN
3602 && (!fallback || fallbackKeyCode != event.getKeyCode())) {
3603#if DEBUG_OUTBOUND_EVENT_DETAILS
3604 if (fallback) {
Steve Block5baa3a62011-12-20 16:23:08 +00003605 ALOGD("Unhandled key event: Policy requested to send key %d"
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003606 "as a fallback for %d, but on the DOWN it had requested "
3607 "to send %d instead. Fallback canceled.",
3608 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
3609 } else {
Jeff Brownfd23e3e2012-05-09 13:34:28 -07003610 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003611 "but on the DOWN it had requested to send %d. "
3612 "Fallback canceled.",
3613 originalKeyCode, fallbackKeyCode);
3614 }
3615#endif
3616
3617 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
3618 "canceling fallback, policy no longer desires it");
3619 options.keyCode = fallbackKeyCode;
3620 synthesizeCancelationEventsForConnectionLocked(connection, options);
3621
3622 fallback = false;
3623 fallbackKeyCode = AKEYCODE_UNKNOWN;
3624 if (keyEntry->action != AKEY_EVENT_ACTION_UP) {
3625 connection->inputState.setFallbackKey(originalKeyCode,
3626 fallbackKeyCode);
3627 }
3628 }
3629
3630#if DEBUG_OUTBOUND_EVENT_DETAILS
3631 {
3632 String8 msg;
3633 const KeyedVector<int32_t, int32_t>& fallbackKeys =
3634 connection->inputState.getFallbackKeys();
3635 for (size_t i = 0; i < fallbackKeys.size(); i++) {
3636 msg.appendFormat(", %d->%d", fallbackKeys.keyAt(i),
3637 fallbackKeys.valueAt(i));
3638 }
Steve Block5baa3a62011-12-20 16:23:08 +00003639 ALOGD("Unhandled key event: %d currently tracked fallback keys%s.",
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003640 fallbackKeys.size(), msg.string());
3641 }
3642#endif
3643
3644 if (fallback) {
3645 // Restart the dispatch cycle using the fallback key.
3646 keyEntry->eventTime = event.getEventTime();
3647 keyEntry->deviceId = event.getDeviceId();
3648 keyEntry->source = event.getSource();
3649 keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
3650 keyEntry->keyCode = fallbackKeyCode;
3651 keyEntry->scanCode = event.getScanCode();
3652 keyEntry->metaState = event.getMetaState();
3653 keyEntry->repeatCount = event.getRepeatCount();
3654 keyEntry->downTime = event.getDownTime();
3655 keyEntry->syntheticRepeat = false;
3656
3657#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00003658 ALOGD("Unhandled key event: Dispatching fallback key. "
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003659 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
3660 originalKeyCode, fallbackKeyCode, keyEntry->metaState);
3661#endif
Jeff Brownd1c48a02012-02-06 19:12:47 -08003662 return true; // restart the event
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003663 } else {
3664#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00003665 ALOGD("Unhandled key event: No fallback key.");
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003666#endif
3667 }
3668 }
3669 }
3670 return false;
3671}
3672
3673bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
3674 DispatchEntry* dispatchEntry, MotionEntry* motionEntry, bool handled) {
3675 return false;
Jeff Brown3915bb82010-11-05 15:02:16 -07003676}
3677
Jeff Brownb88102f2010-09-08 11:49:43 -07003678void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
3679 mLock.unlock();
3680
Jeff Brown01ce2e92010-09-26 22:20:12 -07003681 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
Jeff Brownb88102f2010-09-08 11:49:43 -07003682
3683 mLock.lock();
3684}
3685
Jeff Brown3915bb82010-11-05 15:02:16 -07003686void InputDispatcher::initializeKeyEvent(KeyEvent* event, const KeyEntry* entry) {
3687 event->initialize(entry->deviceId, entry->source, entry->action, entry->flags,
3688 entry->keyCode, entry->scanCode, entry->metaState, entry->repeatCount,
3689 entry->downTime, entry->eventTime);
3690}
3691
Jeff Brown519e0242010-09-15 15:18:56 -07003692void InputDispatcher::updateDispatchStatisticsLocked(nsecs_t currentTime, const EventEntry* entry,
3693 int32_t injectionResult, nsecs_t timeSpentWaitingForApplication) {
3694 // TODO Write some statistics about how long we spend waiting.
Jeff Brownb88102f2010-09-08 11:49:43 -07003695}
3696
Jeff Brown481c1572012-03-09 14:41:15 -08003697void InputDispatcher::traceInboundQueueLengthLocked() {
3698 if (ATRACE_ENABLED()) {
3699 ATRACE_INT("iq", mInboundQueue.count());
3700 }
3701}
3702
3703void InputDispatcher::traceOutboundQueueLengthLocked(const sp<Connection>& connection) {
3704 if (ATRACE_ENABLED()) {
3705 char counterName[40];
3706 snprintf(counterName, sizeof(counterName), "oq:%s", connection->getWindowName());
3707 ATRACE_INT(counterName, connection->outboundQueue.count());
3708 }
3709}
3710
3711void InputDispatcher::traceWaitQueueLengthLocked(const sp<Connection>& connection) {
3712 if (ATRACE_ENABLED()) {
3713 char counterName[40];
3714 snprintf(counterName, sizeof(counterName), "wq:%s", connection->getWindowName());
3715 ATRACE_INT(counterName, connection->waitQueue.count());
3716 }
3717}
3718
Jeff Brownb88102f2010-09-08 11:49:43 -07003719void InputDispatcher::dump(String8& dump) {
Jeff Brown89ef0722011-08-10 16:25:21 -07003720 AutoMutex _l(mLock);
3721
Jeff Brownf2f48712010-10-01 17:46:21 -07003722 dump.append("Input Dispatcher State:\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003723 dumpDispatchStateLocked(dump);
Jeff Brown214eaf42011-05-26 19:17:02 -07003724
Jeff Brown22aa5122012-06-17 12:01:06 -07003725 if (!mLastANRState.isEmpty()) {
3726 dump.append("\nInput Dispatcher State at time of last ANR:\n");
3727 dump.append(mLastANRState);
3728 }
Jeff Brownb88102f2010-09-08 11:49:43 -07003729}
3730
Jeff Brown89ef0722011-08-10 16:25:21 -07003731void InputDispatcher::monitor() {
3732 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
3733 mLock.lock();
Jeff Brown112b5f52012-01-27 17:32:06 -08003734 mLooper->wake();
3735 mDispatcherIsAliveCondition.wait(mLock);
Jeff Brown89ef0722011-08-10 16:25:21 -07003736 mLock.unlock();
3737}
3738
Jeff Brown9c3cda02010-06-15 01:31:58 -07003739
Jeff Brown519e0242010-09-15 15:18:56 -07003740// --- InputDispatcher::Queue ---
3741
3742template <typename T>
3743uint32_t InputDispatcher::Queue<T>::count() const {
3744 uint32_t result = 0;
Jeff Brownac386072011-07-20 15:19:50 -07003745 for (const T* entry = head; entry; entry = entry->next) {
Jeff Brown519e0242010-09-15 15:18:56 -07003746 result += 1;
3747 }
3748 return result;
3749}
3750
3751
Jeff Brownac386072011-07-20 15:19:50 -07003752// --- InputDispatcher::InjectionState ---
Jeff Brown46b9ac02010-04-22 18:58:52 -07003753
Jeff Brownac386072011-07-20 15:19:50 -07003754InputDispatcher::InjectionState::InjectionState(int32_t injectorPid, int32_t injectorUid) :
3755 refCount(1),
3756 injectorPid(injectorPid), injectorUid(injectorUid),
3757 injectionResult(INPUT_EVENT_INJECTION_PENDING), injectionIsAsync(false),
3758 pendingForegroundDispatches(0) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07003759}
3760
Jeff Brownac386072011-07-20 15:19:50 -07003761InputDispatcher::InjectionState::~InjectionState() {
Jeff Brown01ce2e92010-09-26 22:20:12 -07003762}
3763
Jeff Brownac386072011-07-20 15:19:50 -07003764void InputDispatcher::InjectionState::release() {
3765 refCount -= 1;
3766 if (refCount == 0) {
3767 delete this;
3768 } else {
Steve Blockec193de2012-01-09 18:35:44 +00003769 ALOG_ASSERT(refCount > 0);
Jeff Brown01ce2e92010-09-26 22:20:12 -07003770 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07003771}
3772
Jeff Brownac386072011-07-20 15:19:50 -07003773
3774// --- InputDispatcher::EventEntry ---
3775
3776InputDispatcher::EventEntry::EventEntry(int32_t type, nsecs_t eventTime, uint32_t policyFlags) :
3777 refCount(1), type(type), eventTime(eventTime), policyFlags(policyFlags),
3778 injectionState(NULL), dispatchInProgress(false) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07003779}
3780
Jeff Brownac386072011-07-20 15:19:50 -07003781InputDispatcher::EventEntry::~EventEntry() {
3782 releaseInjectionState();
3783}
3784
3785void InputDispatcher::EventEntry::release() {
3786 refCount -= 1;
3787 if (refCount == 0) {
3788 delete this;
3789 } else {
Steve Blockec193de2012-01-09 18:35:44 +00003790 ALOG_ASSERT(refCount > 0);
Jeff Brownac386072011-07-20 15:19:50 -07003791 }
3792}
3793
3794void InputDispatcher::EventEntry::releaseInjectionState() {
3795 if (injectionState) {
3796 injectionState->release();
3797 injectionState = NULL;
3798 }
3799}
3800
3801
3802// --- InputDispatcher::ConfigurationChangedEntry ---
3803
3804InputDispatcher::ConfigurationChangedEntry::ConfigurationChangedEntry(nsecs_t eventTime) :
3805 EventEntry(TYPE_CONFIGURATION_CHANGED, eventTime, 0) {
3806}
3807
3808InputDispatcher::ConfigurationChangedEntry::~ConfigurationChangedEntry() {
3809}
3810
Jeff Brown265f1cc2012-06-11 18:01:06 -07003811void InputDispatcher::ConfigurationChangedEntry::appendDescription(String8& msg) const {
3812 msg.append("ConfigurationChangedEvent()");
3813}
3814
Jeff Brownac386072011-07-20 15:19:50 -07003815
Jeff Brown65fd2512011-08-18 11:20:58 -07003816// --- InputDispatcher::DeviceResetEntry ---
3817
3818InputDispatcher::DeviceResetEntry::DeviceResetEntry(nsecs_t eventTime, int32_t deviceId) :
3819 EventEntry(TYPE_DEVICE_RESET, eventTime, 0),
3820 deviceId(deviceId) {
3821}
3822
3823InputDispatcher::DeviceResetEntry::~DeviceResetEntry() {
3824}
3825
Jeff Brown265f1cc2012-06-11 18:01:06 -07003826void InputDispatcher::DeviceResetEntry::appendDescription(String8& msg) const {
3827 msg.appendFormat("DeviceResetEvent(deviceId=%d)", deviceId);
3828}
3829
Jeff Brown65fd2512011-08-18 11:20:58 -07003830
Jeff Brownac386072011-07-20 15:19:50 -07003831// --- InputDispatcher::KeyEntry ---
3832
3833InputDispatcher::KeyEntry::KeyEntry(nsecs_t eventTime,
Jeff Brown58a2da82011-01-25 16:02:22 -08003834 int32_t deviceId, uint32_t source, uint32_t policyFlags, int32_t action,
Jeff Brown7fbdc842010-06-17 20:52:56 -07003835 int32_t flags, int32_t keyCode, int32_t scanCode, int32_t metaState,
Jeff Brownac386072011-07-20 15:19:50 -07003836 int32_t repeatCount, nsecs_t downTime) :
3837 EventEntry(TYPE_KEY, eventTime, policyFlags),
3838 deviceId(deviceId), source(source), action(action), flags(flags),
3839 keyCode(keyCode), scanCode(scanCode), metaState(metaState),
3840 repeatCount(repeatCount), downTime(downTime),
Jeff Brown905805a2011-10-12 13:57:59 -07003841 syntheticRepeat(false), interceptKeyResult(KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN),
3842 interceptKeyWakeupTime(0) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07003843}
3844
Jeff Brownac386072011-07-20 15:19:50 -07003845InputDispatcher::KeyEntry::~KeyEntry() {
3846}
Jeff Brown7fbdc842010-06-17 20:52:56 -07003847
Jeff Brown265f1cc2012-06-11 18:01:06 -07003848void InputDispatcher::KeyEntry::appendDescription(String8& msg) const {
3849 msg.appendFormat("KeyEvent(action=%d, deviceId=%d, source=0x%08x)",
3850 action, deviceId, source);
3851}
3852
Jeff Brownac386072011-07-20 15:19:50 -07003853void InputDispatcher::KeyEntry::recycle() {
3854 releaseInjectionState();
3855
3856 dispatchInProgress = false;
3857 syntheticRepeat = false;
3858 interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
Jeff Brown905805a2011-10-12 13:57:59 -07003859 interceptKeyWakeupTime = 0;
Jeff Brownac386072011-07-20 15:19:50 -07003860}
3861
3862
Jeff Brownae9fc032010-08-18 15:51:08 -07003863// --- InputDispatcher::MotionEntry ---
3864
Jeff Brownac386072011-07-20 15:19:50 -07003865InputDispatcher::MotionEntry::MotionEntry(nsecs_t eventTime,
3866 int32_t deviceId, uint32_t source, uint32_t policyFlags, int32_t action, int32_t flags,
3867 int32_t metaState, int32_t buttonState,
3868 int32_t edgeFlags, float xPrecision, float yPrecision,
Jeff Brown83d616a2012-09-09 20:33:43 -07003869 nsecs_t downTime, int32_t displayId, uint32_t pointerCount,
Jeff Brownac386072011-07-20 15:19:50 -07003870 const PointerProperties* pointerProperties, const PointerCoords* pointerCoords) :
3871 EventEntry(TYPE_MOTION, eventTime, policyFlags),
Jeff Brown3241b6b2012-02-03 15:08:02 -08003872 eventTime(eventTime),
Jeff Brownac386072011-07-20 15:19:50 -07003873 deviceId(deviceId), source(source), action(action), flags(flags),
3874 metaState(metaState), buttonState(buttonState), edgeFlags(edgeFlags),
3875 xPrecision(xPrecision), yPrecision(yPrecision),
Jeff Brown83d616a2012-09-09 20:33:43 -07003876 downTime(downTime), displayId(displayId), pointerCount(pointerCount) {
Jeff Brownac386072011-07-20 15:19:50 -07003877 for (uint32_t i = 0; i < pointerCount; i++) {
3878 this->pointerProperties[i].copyFrom(pointerProperties[i]);
Jeff Brown3241b6b2012-02-03 15:08:02 -08003879 this->pointerCoords[i].copyFrom(pointerCoords[i]);
Jeff Brownac386072011-07-20 15:19:50 -07003880 }
3881}
3882
3883InputDispatcher::MotionEntry::~MotionEntry() {
Jeff Brownac386072011-07-20 15:19:50 -07003884}
3885
Jeff Brown265f1cc2012-06-11 18:01:06 -07003886void InputDispatcher::MotionEntry::appendDescription(String8& msg) const {
Jeff Brown83d616a2012-09-09 20:33:43 -07003887 msg.appendFormat("MotionEvent(action=%d, deviceId=%d, source=0x%08x, displayId=%d)",
3888 action, deviceId, source, displayId);
Jeff Brown265f1cc2012-06-11 18:01:06 -07003889}
3890
Jeff Brownac386072011-07-20 15:19:50 -07003891
3892// --- InputDispatcher::DispatchEntry ---
3893
Jeff Brown072ec962012-02-07 14:46:57 -08003894volatile int32_t InputDispatcher::DispatchEntry::sNextSeqAtomic;
3895
Jeff Brownac386072011-07-20 15:19:50 -07003896InputDispatcher::DispatchEntry::DispatchEntry(EventEntry* eventEntry,
3897 int32_t targetFlags, float xOffset, float yOffset, float scaleFactor) :
Jeff Brown072ec962012-02-07 14:46:57 -08003898 seq(nextSeq()),
Jeff Brownac386072011-07-20 15:19:50 -07003899 eventEntry(eventEntry), targetFlags(targetFlags),
3900 xOffset(xOffset), yOffset(yOffset), scaleFactor(scaleFactor),
Jeff Brown265f1cc2012-06-11 18:01:06 -07003901 deliveryTime(0), resolvedAction(0), resolvedFlags(0) {
Jeff Brownac386072011-07-20 15:19:50 -07003902 eventEntry->refCount += 1;
3903}
3904
3905InputDispatcher::DispatchEntry::~DispatchEntry() {
3906 eventEntry->release();
3907}
3908
Jeff Brown072ec962012-02-07 14:46:57 -08003909uint32_t InputDispatcher::DispatchEntry::nextSeq() {
3910 // Sequence number 0 is reserved and will never be returned.
3911 uint32_t seq;
3912 do {
3913 seq = android_atomic_inc(&sNextSeqAtomic);
3914 } while (!seq);
3915 return seq;
3916}
3917
Jeff Brownb88102f2010-09-08 11:49:43 -07003918
3919// --- InputDispatcher::InputState ---
3920
Jeff Brownb6997262010-10-08 22:31:17 -07003921InputDispatcher::InputState::InputState() {
Jeff Brownb88102f2010-09-08 11:49:43 -07003922}
3923
3924InputDispatcher::InputState::~InputState() {
3925}
3926
3927bool InputDispatcher::InputState::isNeutral() const {
3928 return mKeyMementos.isEmpty() && mMotionMementos.isEmpty();
3929}
3930
Jeff Brown83d616a2012-09-09 20:33:43 -07003931bool InputDispatcher::InputState::isHovering(int32_t deviceId, uint32_t source,
3932 int32_t displayId) const {
Jeff Brown81346812011-06-28 20:08:48 -07003933 for (size_t i = 0; i < mMotionMementos.size(); i++) {
3934 const MotionMemento& memento = mMotionMementos.itemAt(i);
3935 if (memento.deviceId == deviceId
3936 && memento.source == source
Jeff Brown83d616a2012-09-09 20:33:43 -07003937 && memento.displayId == displayId
Jeff Brown81346812011-06-28 20:08:48 -07003938 && memento.hovering) {
3939 return true;
3940 }
3941 }
3942 return false;
3943}
Jeff Brownb88102f2010-09-08 11:49:43 -07003944
Jeff Brown81346812011-06-28 20:08:48 -07003945bool InputDispatcher::InputState::trackKey(const KeyEntry* entry,
3946 int32_t action, int32_t flags) {
3947 switch (action) {
3948 case AKEY_EVENT_ACTION_UP: {
3949 if (entry->flags & AKEY_EVENT_FLAG_FALLBACK) {
3950 for (size_t i = 0; i < mFallbackKeys.size(); ) {
3951 if (mFallbackKeys.valueAt(i) == entry->keyCode) {
3952 mFallbackKeys.removeItemsAt(i);
3953 } else {
3954 i += 1;
3955 }
3956 }
3957 }
3958 ssize_t index = findKeyMemento(entry);
3959 if (index >= 0) {
3960 mKeyMementos.removeAt(index);
3961 return true;
3962 }
Jeff Brown68b909d2011-12-07 16:36:01 -08003963 /* FIXME: We can't just drop the key up event because that prevents creating
3964 * popup windows that are automatically shown when a key is held and then
3965 * dismissed when the key is released. The problem is that the popup will
3966 * not have received the original key down, so the key up will be considered
3967 * to be inconsistent with its observed state. We could perhaps handle this
3968 * by synthesizing a key down but that will cause other problems.
3969 *
3970 * So for now, allow inconsistent key up events to be dispatched.
3971 *
Jeff Brown81346812011-06-28 20:08:48 -07003972#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00003973 ALOGD("Dropping inconsistent key up event: deviceId=%d, source=%08x, "
Jeff Brown81346812011-06-28 20:08:48 -07003974 "keyCode=%d, scanCode=%d",
3975 entry->deviceId, entry->source, entry->keyCode, entry->scanCode);
3976#endif
3977 return false;
Jeff Brown68b909d2011-12-07 16:36:01 -08003978 */
3979 return true;
Jeff Brown81346812011-06-28 20:08:48 -07003980 }
3981
3982 case AKEY_EVENT_ACTION_DOWN: {
3983 ssize_t index = findKeyMemento(entry);
3984 if (index >= 0) {
3985 mKeyMementos.removeAt(index);
3986 }
3987 addKeyMemento(entry, flags);
3988 return true;
3989 }
3990
3991 default:
3992 return true;
Jeff Brownb88102f2010-09-08 11:49:43 -07003993 }
3994}
3995
Jeff Brown81346812011-06-28 20:08:48 -07003996bool InputDispatcher::InputState::trackMotion(const MotionEntry* entry,
3997 int32_t action, int32_t flags) {
3998 int32_t actionMasked = action & AMOTION_EVENT_ACTION_MASK;
3999 switch (actionMasked) {
4000 case AMOTION_EVENT_ACTION_UP:
4001 case AMOTION_EVENT_ACTION_CANCEL: {
4002 ssize_t index = findMotionMemento(entry, false /*hovering*/);
4003 if (index >= 0) {
4004 mMotionMementos.removeAt(index);
4005 return true;
Jeff Brownda3d5a92011-03-29 15:11:34 -07004006 }
Jeff Brown81346812011-06-28 20:08:48 -07004007#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00004008 ALOGD("Dropping inconsistent motion up or cancel event: deviceId=%d, source=%08x, "
Jeff Brown81346812011-06-28 20:08:48 -07004009 "actionMasked=%d",
4010 entry->deviceId, entry->source, actionMasked);
4011#endif
4012 return false;
Jeff Brownda3d5a92011-03-29 15:11:34 -07004013 }
4014
Jeff Brown81346812011-06-28 20:08:48 -07004015 case AMOTION_EVENT_ACTION_DOWN: {
4016 ssize_t index = findMotionMemento(entry, false /*hovering*/);
4017 if (index >= 0) {
4018 mMotionMementos.removeAt(index);
4019 }
4020 addMotionMemento(entry, flags, false /*hovering*/);
4021 return true;
4022 }
4023
4024 case AMOTION_EVENT_ACTION_POINTER_UP:
4025 case AMOTION_EVENT_ACTION_POINTER_DOWN:
4026 case AMOTION_EVENT_ACTION_MOVE: {
4027 ssize_t index = findMotionMemento(entry, false /*hovering*/);
4028 if (index >= 0) {
4029 MotionMemento& memento = mMotionMementos.editItemAt(index);
4030 memento.setPointers(entry);
4031 return true;
4032 }
Jeff Brown2e45fb62011-06-29 21:19:05 -07004033 if (actionMasked == AMOTION_EVENT_ACTION_MOVE
4034 && (entry->source & (AINPUT_SOURCE_CLASS_JOYSTICK
4035 | AINPUT_SOURCE_CLASS_NAVIGATION))) {
4036 // Joysticks and trackballs can send MOVE events without corresponding DOWN or UP.
4037 return true;
4038 }
Jeff Brown81346812011-06-28 20:08:48 -07004039#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00004040 ALOGD("Dropping inconsistent motion pointer up/down or move event: "
Jeff Brown81346812011-06-28 20:08:48 -07004041 "deviceId=%d, source=%08x, actionMasked=%d",
4042 entry->deviceId, entry->source, actionMasked);
4043#endif
4044 return false;
4045 }
4046
4047 case AMOTION_EVENT_ACTION_HOVER_EXIT: {
4048 ssize_t index = findMotionMemento(entry, true /*hovering*/);
4049 if (index >= 0) {
4050 mMotionMementos.removeAt(index);
4051 return true;
4052 }
4053#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00004054 ALOGD("Dropping inconsistent motion hover exit event: deviceId=%d, source=%08x",
Jeff Brown81346812011-06-28 20:08:48 -07004055 entry->deviceId, entry->source);
4056#endif
4057 return false;
4058 }
4059
4060 case AMOTION_EVENT_ACTION_HOVER_ENTER:
4061 case AMOTION_EVENT_ACTION_HOVER_MOVE: {
4062 ssize_t index = findMotionMemento(entry, true /*hovering*/);
4063 if (index >= 0) {
4064 mMotionMementos.removeAt(index);
4065 }
4066 addMotionMemento(entry, flags, true /*hovering*/);
4067 return true;
4068 }
4069
4070 default:
4071 return true;
4072 }
4073}
4074
4075ssize_t InputDispatcher::InputState::findKeyMemento(const KeyEntry* entry) const {
Jeff Brownb88102f2010-09-08 11:49:43 -07004076 for (size_t i = 0; i < mKeyMementos.size(); i++) {
Jeff Brown81346812011-06-28 20:08:48 -07004077 const KeyMemento& memento = mKeyMementos.itemAt(i);
Jeff Brownb88102f2010-09-08 11:49:43 -07004078 if (memento.deviceId == entry->deviceId
4079 && memento.source == entry->source
4080 && memento.keyCode == entry->keyCode
4081 && memento.scanCode == entry->scanCode) {
Jeff Brown81346812011-06-28 20:08:48 -07004082 return i;
Jeff Brownb88102f2010-09-08 11:49:43 -07004083 }
4084 }
Jeff Brown81346812011-06-28 20:08:48 -07004085 return -1;
Jeff Brownb88102f2010-09-08 11:49:43 -07004086}
4087
Jeff Brown81346812011-06-28 20:08:48 -07004088ssize_t InputDispatcher::InputState::findMotionMemento(const MotionEntry* entry,
4089 bool hovering) const {
Jeff Brownb88102f2010-09-08 11:49:43 -07004090 for (size_t i = 0; i < mMotionMementos.size(); i++) {
Jeff Brown81346812011-06-28 20:08:48 -07004091 const MotionMemento& memento = mMotionMementos.itemAt(i);
Jeff Brownb88102f2010-09-08 11:49:43 -07004092 if (memento.deviceId == entry->deviceId
Jeff Brown81346812011-06-28 20:08:48 -07004093 && memento.source == entry->source
Jeff Brown83d616a2012-09-09 20:33:43 -07004094 && memento.displayId == entry->displayId
Jeff Brown81346812011-06-28 20:08:48 -07004095 && memento.hovering == hovering) {
4096 return i;
Jeff Brownb88102f2010-09-08 11:49:43 -07004097 }
4098 }
Jeff Brown81346812011-06-28 20:08:48 -07004099 return -1;
4100}
Jeff Brownb88102f2010-09-08 11:49:43 -07004101
Jeff Brown81346812011-06-28 20:08:48 -07004102void InputDispatcher::InputState::addKeyMemento(const KeyEntry* entry, int32_t flags) {
4103 mKeyMementos.push();
4104 KeyMemento& memento = mKeyMementos.editTop();
4105 memento.deviceId = entry->deviceId;
4106 memento.source = entry->source;
4107 memento.keyCode = entry->keyCode;
4108 memento.scanCode = entry->scanCode;
Jeff Brownfd23e3e2012-05-09 13:34:28 -07004109 memento.metaState = entry->metaState;
Jeff Brown81346812011-06-28 20:08:48 -07004110 memento.flags = flags;
4111 memento.downTime = entry->downTime;
Jeff Brownfd23e3e2012-05-09 13:34:28 -07004112 memento.policyFlags = entry->policyFlags;
Jeff Brown81346812011-06-28 20:08:48 -07004113}
4114
4115void InputDispatcher::InputState::addMotionMemento(const MotionEntry* entry,
4116 int32_t flags, bool hovering) {
4117 mMotionMementos.push();
4118 MotionMemento& memento = mMotionMementos.editTop();
4119 memento.deviceId = entry->deviceId;
4120 memento.source = entry->source;
4121 memento.flags = flags;
4122 memento.xPrecision = entry->xPrecision;
4123 memento.yPrecision = entry->yPrecision;
4124 memento.downTime = entry->downTime;
Jeff Brown83d616a2012-09-09 20:33:43 -07004125 memento.displayId = entry->displayId;
Jeff Brown81346812011-06-28 20:08:48 -07004126 memento.setPointers(entry);
4127 memento.hovering = hovering;
Jeff Brownfd23e3e2012-05-09 13:34:28 -07004128 memento.policyFlags = entry->policyFlags;
Jeff Brownb88102f2010-09-08 11:49:43 -07004129}
4130
4131void InputDispatcher::InputState::MotionMemento::setPointers(const MotionEntry* entry) {
4132 pointerCount = entry->pointerCount;
4133 for (uint32_t i = 0; i < entry->pointerCount; i++) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07004134 pointerProperties[i].copyFrom(entry->pointerProperties[i]);
Jeff Brown3241b6b2012-02-03 15:08:02 -08004135 pointerCoords[i].copyFrom(entry->pointerCoords[i]);
Jeff Brownb88102f2010-09-08 11:49:43 -07004136 }
4137}
4138
Jeff Brownb6997262010-10-08 22:31:17 -07004139void InputDispatcher::InputState::synthesizeCancelationEvents(nsecs_t currentTime,
Jeff Brownac386072011-07-20 15:19:50 -07004140 Vector<EventEntry*>& outEvents, const CancelationOptions& options) {
Jeff Brown81346812011-06-28 20:08:48 -07004141 for (size_t i = 0; i < mKeyMementos.size(); i++) {
Jeff Brownb88102f2010-09-08 11:49:43 -07004142 const KeyMemento& memento = mKeyMementos.itemAt(i);
Jeff Brown49ed71d2010-12-06 17:13:33 -08004143 if (shouldCancelKey(memento, options)) {
Jeff Brownac386072011-07-20 15:19:50 -07004144 outEvents.push(new KeyEntry(currentTime,
Jeff Brownfd23e3e2012-05-09 13:34:28 -07004145 memento.deviceId, memento.source, memento.policyFlags,
Jeff Brown49ed71d2010-12-06 17:13:33 -08004146 AKEY_EVENT_ACTION_UP, memento.flags | AKEY_EVENT_FLAG_CANCELED,
Jeff Brownfd23e3e2012-05-09 13:34:28 -07004147 memento.keyCode, memento.scanCode, memento.metaState, 0, memento.downTime));
Jeff Brownb6997262010-10-08 22:31:17 -07004148 }
Jeff Brownb88102f2010-09-08 11:49:43 -07004149 }
4150
Jeff Brown81346812011-06-28 20:08:48 -07004151 for (size_t i = 0; i < mMotionMementos.size(); i++) {
Jeff Brownb88102f2010-09-08 11:49:43 -07004152 const MotionMemento& memento = mMotionMementos.itemAt(i);
Jeff Brown49ed71d2010-12-06 17:13:33 -08004153 if (shouldCancelMotion(memento, options)) {
Jeff Brownac386072011-07-20 15:19:50 -07004154 outEvents.push(new MotionEntry(currentTime,
Jeff Brownfd23e3e2012-05-09 13:34:28 -07004155 memento.deviceId, memento.source, memento.policyFlags,
Jeff Browna032cc02011-03-07 16:56:21 -08004156 memento.hovering
4157 ? AMOTION_EVENT_ACTION_HOVER_EXIT
4158 : AMOTION_EVENT_ACTION_CANCEL,
Jeff Brown81346812011-06-28 20:08:48 -07004159 memento.flags, 0, 0, 0,
Jeff Brownb6997262010-10-08 22:31:17 -07004160 memento.xPrecision, memento.yPrecision, memento.downTime,
Jeff Brown83d616a2012-09-09 20:33:43 -07004161 memento.displayId,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07004162 memento.pointerCount, memento.pointerProperties, memento.pointerCoords));
Jeff Brownb6997262010-10-08 22:31:17 -07004163 }
Jeff Brownb88102f2010-09-08 11:49:43 -07004164 }
4165}
4166
4167void InputDispatcher::InputState::clear() {
4168 mKeyMementos.clear();
4169 mMotionMementos.clear();
Jeff Brownda3d5a92011-03-29 15:11:34 -07004170 mFallbackKeys.clear();
Jeff Brownb6997262010-10-08 22:31:17 -07004171}
4172
Jeff Brown9c9f1a32010-10-11 18:32:20 -07004173void InputDispatcher::InputState::copyPointerStateTo(InputState& other) const {
4174 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4175 const MotionMemento& memento = mMotionMementos.itemAt(i);
4176 if (memento.source & AINPUT_SOURCE_CLASS_POINTER) {
4177 for (size_t j = 0; j < other.mMotionMementos.size(); ) {
4178 const MotionMemento& otherMemento = other.mMotionMementos.itemAt(j);
4179 if (memento.deviceId == otherMemento.deviceId
Jeff Brown83d616a2012-09-09 20:33:43 -07004180 && memento.source == otherMemento.source
4181 && memento.displayId == otherMemento.displayId) {
Jeff Brown9c9f1a32010-10-11 18:32:20 -07004182 other.mMotionMementos.removeAt(j);
4183 } else {
4184 j += 1;
4185 }
4186 }
4187 other.mMotionMementos.push(memento);
4188 }
4189 }
4190}
4191
Jeff Brownda3d5a92011-03-29 15:11:34 -07004192int32_t InputDispatcher::InputState::getFallbackKey(int32_t originalKeyCode) {
4193 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
4194 return index >= 0 ? mFallbackKeys.valueAt(index) : -1;
4195}
4196
4197void InputDispatcher::InputState::setFallbackKey(int32_t originalKeyCode,
4198 int32_t fallbackKeyCode) {
4199 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
4200 if (index >= 0) {
4201 mFallbackKeys.replaceValueAt(index, fallbackKeyCode);
4202 } else {
4203 mFallbackKeys.add(originalKeyCode, fallbackKeyCode);
4204 }
4205}
4206
4207void InputDispatcher::InputState::removeFallbackKey(int32_t originalKeyCode) {
4208 mFallbackKeys.removeItem(originalKeyCode);
4209}
4210
Jeff Brown49ed71d2010-12-06 17:13:33 -08004211bool InputDispatcher::InputState::shouldCancelKey(const KeyMemento& memento,
Jeff Brownda3d5a92011-03-29 15:11:34 -07004212 const CancelationOptions& options) {
4213 if (options.keyCode != -1 && memento.keyCode != options.keyCode) {
4214 return false;
4215 }
4216
Jeff Brown65fd2512011-08-18 11:20:58 -07004217 if (options.deviceId != -1 && memento.deviceId != options.deviceId) {
4218 return false;
4219 }
4220
Jeff Brownda3d5a92011-03-29 15:11:34 -07004221 switch (options.mode) {
4222 case CancelationOptions::CANCEL_ALL_EVENTS:
4223 case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
Jeff Brownb6997262010-10-08 22:31:17 -07004224 return true;
Jeff Brownda3d5a92011-03-29 15:11:34 -07004225 case CancelationOptions::CANCEL_FALLBACK_EVENTS:
Jeff Brown49ed71d2010-12-06 17:13:33 -08004226 return memento.flags & AKEY_EVENT_FLAG_FALLBACK;
4227 default:
4228 return false;
4229 }
4230}
4231
4232bool InputDispatcher::InputState::shouldCancelMotion(const MotionMemento& memento,
Jeff Brownda3d5a92011-03-29 15:11:34 -07004233 const CancelationOptions& options) {
Jeff Brown65fd2512011-08-18 11:20:58 -07004234 if (options.deviceId != -1 && memento.deviceId != options.deviceId) {
4235 return false;
4236 }
4237
Jeff Brownda3d5a92011-03-29 15:11:34 -07004238 switch (options.mode) {
4239 case CancelationOptions::CANCEL_ALL_EVENTS:
Jeff Brown49ed71d2010-12-06 17:13:33 -08004240 return true;
Jeff Brownda3d5a92011-03-29 15:11:34 -07004241 case CancelationOptions::CANCEL_POINTER_EVENTS:
Jeff Brown49ed71d2010-12-06 17:13:33 -08004242 return memento.source & AINPUT_SOURCE_CLASS_POINTER;
Jeff Brownda3d5a92011-03-29 15:11:34 -07004243 case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
Jeff Brown49ed71d2010-12-06 17:13:33 -08004244 return !(memento.source & AINPUT_SOURCE_CLASS_POINTER);
4245 default:
4246 return false;
Jeff Brownb6997262010-10-08 22:31:17 -07004247 }
Jeff Brownb88102f2010-09-08 11:49:43 -07004248}
4249
4250
Jeff Brown46b9ac02010-04-22 18:58:52 -07004251// --- InputDispatcher::Connection ---
4252
Jeff Brown928e0542011-01-10 11:17:36 -08004253InputDispatcher::Connection::Connection(const sp<InputChannel>& inputChannel,
Jeff Browncc4f7db2011-08-30 20:34:48 -07004254 const sp<InputWindowHandle>& inputWindowHandle, bool monitor) :
Jeff Brown928e0542011-01-10 11:17:36 -08004255 status(STATUS_NORMAL), inputChannel(inputChannel), inputWindowHandle(inputWindowHandle),
Jeff Browncc4f7db2011-08-30 20:34:48 -07004256 monitor(monitor),
Jeff Brownd1c48a02012-02-06 19:12:47 -08004257 inputPublisher(inputChannel), inputPublisherBlocked(false) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07004258}
4259
4260InputDispatcher::Connection::~Connection() {
4261}
4262
Jeff Brown481c1572012-03-09 14:41:15 -08004263const char* InputDispatcher::Connection::getWindowName() const {
4264 if (inputWindowHandle != NULL) {
4265 return inputWindowHandle->getName().string();
4266 }
4267 if (monitor) {
4268 return "monitor";
4269 }
4270 return "?";
4271}
4272
Jeff Brown9c3cda02010-06-15 01:31:58 -07004273const char* InputDispatcher::Connection::getStatusLabel() const {
4274 switch (status) {
4275 case STATUS_NORMAL:
4276 return "NORMAL";
4277
4278 case STATUS_BROKEN:
4279 return "BROKEN";
4280
Jeff Brown9c3cda02010-06-15 01:31:58 -07004281 case STATUS_ZOMBIE:
4282 return "ZOMBIE";
4283
4284 default:
4285 return "UNKNOWN";
4286 }
4287}
4288
Jeff Brown072ec962012-02-07 14:46:57 -08004289InputDispatcher::DispatchEntry* InputDispatcher::Connection::findWaitQueueEntry(uint32_t seq) {
4290 for (DispatchEntry* entry = waitQueue.head; entry != NULL; entry = entry->next) {
4291 if (entry->seq == seq) {
4292 return entry;
4293 }
4294 }
4295 return NULL;
4296}
4297
Jeff Brownb88102f2010-09-08 11:49:43 -07004298
Jeff Brown9c3cda02010-06-15 01:31:58 -07004299// --- InputDispatcher::CommandEntry ---
4300
Jeff Brownac386072011-07-20 15:19:50 -07004301InputDispatcher::CommandEntry::CommandEntry(Command command) :
Jeff Brown072ec962012-02-07 14:46:57 -08004302 command(command), eventTime(0), keyEntry(NULL), userActivityEventType(0),
4303 seq(0), handled(false) {
Jeff Brown9c3cda02010-06-15 01:31:58 -07004304}
4305
4306InputDispatcher::CommandEntry::~CommandEntry() {
4307}
4308
Jeff Brown46b9ac02010-04-22 18:58:52 -07004309
Jeff Brown01ce2e92010-09-26 22:20:12 -07004310// --- InputDispatcher::TouchState ---
4311
4312InputDispatcher::TouchState::TouchState() :
Jeff Brown83d616a2012-09-09 20:33:43 -07004313 down(false), split(false), deviceId(-1), source(0), displayId(-1) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07004314}
4315
4316InputDispatcher::TouchState::~TouchState() {
4317}
4318
4319void InputDispatcher::TouchState::reset() {
4320 down = false;
4321 split = false;
Jeff Brown95712852011-01-04 19:41:59 -08004322 deviceId = -1;
Jeff Brown58a2da82011-01-25 16:02:22 -08004323 source = 0;
Jeff Brown83d616a2012-09-09 20:33:43 -07004324 displayId = -1;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004325 windows.clear();
4326}
4327
4328void InputDispatcher::TouchState::copyFrom(const TouchState& other) {
4329 down = other.down;
4330 split = other.split;
Jeff Brown95712852011-01-04 19:41:59 -08004331 deviceId = other.deviceId;
Jeff Brown58a2da82011-01-25 16:02:22 -08004332 source = other.source;
Jeff Brown83d616a2012-09-09 20:33:43 -07004333 displayId = other.displayId;
Jeff Brown9302c872011-07-13 22:51:29 -07004334 windows = other.windows;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004335}
4336
Jeff Brown9302c872011-07-13 22:51:29 -07004337void InputDispatcher::TouchState::addOrUpdateWindow(const sp<InputWindowHandle>& windowHandle,
Jeff Brown01ce2e92010-09-26 22:20:12 -07004338 int32_t targetFlags, BitSet32 pointerIds) {
4339 if (targetFlags & InputTarget::FLAG_SPLIT) {
4340 split = true;
4341 }
4342
4343 for (size_t i = 0; i < windows.size(); i++) {
4344 TouchedWindow& touchedWindow = windows.editItemAt(i);
Jeff Brown9302c872011-07-13 22:51:29 -07004345 if (touchedWindow.windowHandle == windowHandle) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07004346 touchedWindow.targetFlags |= targetFlags;
Jeff Brown98db5fa2011-06-08 15:37:10 -07004347 if (targetFlags & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
4348 touchedWindow.targetFlags &= ~InputTarget::FLAG_DISPATCH_AS_IS;
4349 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07004350 touchedWindow.pointerIds.value |= pointerIds.value;
4351 return;
4352 }
4353 }
4354
4355 windows.push();
4356
4357 TouchedWindow& touchedWindow = windows.editTop();
Jeff Brown9302c872011-07-13 22:51:29 -07004358 touchedWindow.windowHandle = windowHandle;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004359 touchedWindow.targetFlags = targetFlags;
4360 touchedWindow.pointerIds = pointerIds;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004361}
4362
Jeff Brownf44e3942012-04-20 11:33:27 -07004363void InputDispatcher::TouchState::removeWindow(const sp<InputWindowHandle>& windowHandle) {
4364 for (size_t i = 0; i < windows.size(); i++) {
4365 if (windows.itemAt(i).windowHandle == windowHandle) {
4366 windows.removeAt(i);
4367 return;
4368 }
4369 }
4370}
4371
Jeff Browna032cc02011-03-07 16:56:21 -08004372void InputDispatcher::TouchState::filterNonAsIsTouchWindows() {
Jeff Brown01ce2e92010-09-26 22:20:12 -07004373 for (size_t i = 0 ; i < windows.size(); ) {
Jeff Browna032cc02011-03-07 16:56:21 -08004374 TouchedWindow& window = windows.editItemAt(i);
Jeff Brown98db5fa2011-06-08 15:37:10 -07004375 if (window.targetFlags & (InputTarget::FLAG_DISPATCH_AS_IS
4376 | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER)) {
Jeff Browna032cc02011-03-07 16:56:21 -08004377 window.targetFlags &= ~InputTarget::FLAG_DISPATCH_MASK;
4378 window.targetFlags |= InputTarget::FLAG_DISPATCH_AS_IS;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004379 i += 1;
Jeff Browna032cc02011-03-07 16:56:21 -08004380 } else {
4381 windows.removeAt(i);
Jeff Brown01ce2e92010-09-26 22:20:12 -07004382 }
4383 }
4384}
4385
Jeff Brown9302c872011-07-13 22:51:29 -07004386sp<InputWindowHandle> InputDispatcher::TouchState::getFirstForegroundWindowHandle() const {
Jeff Brown01ce2e92010-09-26 22:20:12 -07004387 for (size_t i = 0; i < windows.size(); i++) {
Jeff Brown98db5fa2011-06-08 15:37:10 -07004388 const TouchedWindow& window = windows.itemAt(i);
4389 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
Jeff Brown9302c872011-07-13 22:51:29 -07004390 return window.windowHandle;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004391 }
4392 }
4393 return NULL;
4394}
4395
Jeff Brown98db5fa2011-06-08 15:37:10 -07004396bool InputDispatcher::TouchState::isSlippery() const {
4397 // Must have exactly one foreground window.
4398 bool haveSlipperyForegroundWindow = false;
4399 for (size_t i = 0; i < windows.size(); i++) {
4400 const TouchedWindow& window = windows.itemAt(i);
4401 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
Jeff Browncc4f7db2011-08-30 20:34:48 -07004402 if (haveSlipperyForegroundWindow
4403 || !(window.windowHandle->getInfo()->layoutParamsFlags
4404 & InputWindowInfo::FLAG_SLIPPERY)) {
Jeff Brown98db5fa2011-06-08 15:37:10 -07004405 return false;
4406 }
4407 haveSlipperyForegroundWindow = true;
4408 }
4409 }
4410 return haveSlipperyForegroundWindow;
4411}
4412
Jeff Brown01ce2e92010-09-26 22:20:12 -07004413
Jeff Brown46b9ac02010-04-22 18:58:52 -07004414// --- InputDispatcherThread ---
4415
4416InputDispatcherThread::InputDispatcherThread(const sp<InputDispatcherInterface>& dispatcher) :
4417 Thread(/*canCallJava*/ true), mDispatcher(dispatcher) {
4418}
4419
4420InputDispatcherThread::~InputDispatcherThread() {
4421}
4422
4423bool InputDispatcherThread::threadLoop() {
4424 mDispatcher->dispatchOnce();
4425 return true;
4426}
4427
4428} // namespace android