blob: 0465215a8e8cb17a050328c6083cbddf7cd3343b [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) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700541 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL;
542}
543
Jeff Brownb6997262010-10-08 22:31:17 -0700544bool InputDispatcher::isAppSwitchKeyEventLocked(KeyEntry* keyEntry) {
545 return ! (keyEntry->flags & AKEY_EVENT_FLAG_CANCELED)
546 && isAppSwitchKeyCode(keyEntry->keyCode)
Jeff Browne20c9e02010-10-11 14:20:19 -0700547 && (keyEntry->policyFlags & POLICY_FLAG_TRUSTED)
Jeff Brownb6997262010-10-08 22:31:17 -0700548 && (keyEntry->policyFlags & POLICY_FLAG_PASS_TO_USER);
549}
550
Jeff Brownb88102f2010-09-08 11:49:43 -0700551bool InputDispatcher::isAppSwitchPendingLocked() {
552 return mAppSwitchDueTime != LONG_LONG_MAX;
553}
554
Jeff Brownb88102f2010-09-08 11:49:43 -0700555void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
556 mAppSwitchDueTime = LONG_LONG_MAX;
557
558#if DEBUG_APP_SWITCH
559 if (handled) {
Steve Block5baa3a62011-12-20 16:23:08 +0000560 ALOGD("App switch has arrived.");
Jeff Brownb88102f2010-09-08 11:49:43 -0700561 } else {
Steve Block5baa3a62011-12-20 16:23:08 +0000562 ALOGD("App switch was abandoned.");
Jeff Brownb88102f2010-09-08 11:49:43 -0700563 }
564#endif
Jeff Brown46b9ac02010-04-22 18:58:52 -0700565}
566
Jeff Brown928e0542011-01-10 11:17:36 -0800567bool InputDispatcher::isStaleEventLocked(nsecs_t currentTime, EventEntry* entry) {
568 return currentTime - entry->eventTime >= STALE_EVENT_TIMEOUT;
569}
570
Jeff Brown074b8b72012-10-31 19:01:31 -0700571bool InputDispatcher::haveCommandsLocked() const {
572 return !mCommandQueue.isEmpty();
573}
574
Jeff Brown9c3cda02010-06-15 01:31:58 -0700575bool InputDispatcher::runCommandsLockedInterruptible() {
576 if (mCommandQueue.isEmpty()) {
577 return false;
578 }
Jeff Brown46b9ac02010-04-22 18:58:52 -0700579
Jeff Brown9c3cda02010-06-15 01:31:58 -0700580 do {
581 CommandEntry* commandEntry = mCommandQueue.dequeueAtHead();
582
583 Command command = commandEntry->command;
584 (this->*command)(commandEntry); // commands are implicitly 'LockedInterruptible'
585
Jeff Brown7fbdc842010-06-17 20:52:56 -0700586 commandEntry->connection.clear();
Jeff Brownac386072011-07-20 15:19:50 -0700587 delete commandEntry;
Jeff Brown9c3cda02010-06-15 01:31:58 -0700588 } while (! mCommandQueue.isEmpty());
589 return true;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700590}
591
Jeff Brown9c3cda02010-06-15 01:31:58 -0700592InputDispatcher::CommandEntry* InputDispatcher::postCommandLocked(Command command) {
Jeff Brownac386072011-07-20 15:19:50 -0700593 CommandEntry* commandEntry = new CommandEntry(command);
Jeff Brown9c3cda02010-06-15 01:31:58 -0700594 mCommandQueue.enqueueAtTail(commandEntry);
595 return commandEntry;
596}
597
Jeff Brownb88102f2010-09-08 11:49:43 -0700598void InputDispatcher::drainInboundQueueLocked() {
599 while (! mInboundQueue.isEmpty()) {
600 EventEntry* entry = mInboundQueue.dequeueAtHead();
Jeff Brown54a18252010-09-16 14:07:33 -0700601 releaseInboundEventLocked(entry);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700602 }
Jeff Brown481c1572012-03-09 14:41:15 -0800603 traceInboundQueueLengthLocked();
Jeff Brown46b9ac02010-04-22 18:58:52 -0700604}
605
Jeff Brown54a18252010-09-16 14:07:33 -0700606void InputDispatcher::releasePendingEventLocked() {
Jeff Brownb88102f2010-09-08 11:49:43 -0700607 if (mPendingEvent) {
Jeff Browne9bb9be2012-02-06 15:47:55 -0800608 resetANRTimeoutsLocked();
Jeff Brown54a18252010-09-16 14:07:33 -0700609 releaseInboundEventLocked(mPendingEvent);
Jeff Brownb88102f2010-09-08 11:49:43 -0700610 mPendingEvent = NULL;
611 }
612}
613
Jeff Brown54a18252010-09-16 14:07:33 -0700614void InputDispatcher::releaseInboundEventLocked(EventEntry* entry) {
Jeff Brown01ce2e92010-09-26 22:20:12 -0700615 InjectionState* injectionState = entry->injectionState;
616 if (injectionState && injectionState->injectionResult == INPUT_EVENT_INJECTION_PENDING) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700617#if DEBUG_DISPATCH_CYCLE
Steve Block5baa3a62011-12-20 16:23:08 +0000618 ALOGD("Injected inbound event was dropped.");
Jeff Brownb88102f2010-09-08 11:49:43 -0700619#endif
620 setInjectionResultLocked(entry, INPUT_EVENT_INJECTION_FAILED);
621 }
Jeff Brownabb4d442011-08-15 12:55:32 -0700622 if (entry == mNextUnblockedEvent) {
623 mNextUnblockedEvent = NULL;
624 }
Jeff Brownac386072011-07-20 15:19:50 -0700625 entry->release();
Jeff Brownb88102f2010-09-08 11:49:43 -0700626}
627
Jeff Brownb88102f2010-09-08 11:49:43 -0700628void InputDispatcher::resetKeyRepeatLocked() {
629 if (mKeyRepeatState.lastKeyEntry) {
Jeff Brownac386072011-07-20 15:19:50 -0700630 mKeyRepeatState.lastKeyEntry->release();
Jeff Brownb88102f2010-09-08 11:49:43 -0700631 mKeyRepeatState.lastKeyEntry = NULL;
632 }
633}
634
Jeff Brown214eaf42011-05-26 19:17:02 -0700635InputDispatcher::KeyEntry* InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
Jeff Brown349703e2010-06-22 01:27:15 -0700636 KeyEntry* entry = mKeyRepeatState.lastKeyEntry;
637
Jeff Brown349703e2010-06-22 01:27:15 -0700638 // Reuse the repeated key entry if it is otherwise unreferenced.
Jeff Browne20c9e02010-10-11 14:20:19 -0700639 uint32_t policyFlags = (entry->policyFlags & POLICY_FLAG_RAW_MASK)
640 | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700641 if (entry->refCount == 1) {
Jeff Brownac386072011-07-20 15:19:50 -0700642 entry->recycle();
Jeff Brown7fbdc842010-06-17 20:52:56 -0700643 entry->eventTime = currentTime;
Jeff Brown7fbdc842010-06-17 20:52:56 -0700644 entry->policyFlags = policyFlags;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700645 entry->repeatCount += 1;
646 } else {
Jeff Brownac386072011-07-20 15:19:50 -0700647 KeyEntry* newEntry = new KeyEntry(currentTime,
Jeff Brownc5ed5912010-07-14 18:48:53 -0700648 entry->deviceId, entry->source, policyFlags,
Jeff Brown7fbdc842010-06-17 20:52:56 -0700649 entry->action, entry->flags, entry->keyCode, entry->scanCode,
Jeff Brown00fa7bd2010-07-02 15:37:36 -0700650 entry->metaState, entry->repeatCount + 1, entry->downTime);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700651
652 mKeyRepeatState.lastKeyEntry = newEntry;
Jeff Brownac386072011-07-20 15:19:50 -0700653 entry->release();
Jeff Brown46b9ac02010-04-22 18:58:52 -0700654
655 entry = newEntry;
656 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700657 entry->syntheticRepeat = true;
658
659 // Increment reference count since we keep a reference to the event in
660 // mKeyRepeatState.lastKeyEntry in addition to the one we return.
661 entry->refCount += 1;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700662
Jeff Brown214eaf42011-05-26 19:17:02 -0700663 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Jeff Brownb88102f2010-09-08 11:49:43 -0700664 return entry;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700665}
666
Jeff Brownb88102f2010-09-08 11:49:43 -0700667bool InputDispatcher::dispatchConfigurationChangedLocked(
668 nsecs_t currentTime, ConfigurationChangedEntry* entry) {
Jeff Brown46b9ac02010-04-22 18:58:52 -0700669#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +0000670 ALOGD("dispatchConfigurationChanged - eventTime=%lld", entry->eventTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700671#endif
672
673 // Reset key repeating in case a keyboard device was added or removed or something.
674 resetKeyRepeatLocked();
675
676 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
677 CommandEntry* commandEntry = postCommandLocked(
678 & InputDispatcher::doNotifyConfigurationChangedInterruptible);
679 commandEntry->eventTime = entry->eventTime;
680 return true;
681}
682
Jeff Brown65fd2512011-08-18 11:20:58 -0700683bool InputDispatcher::dispatchDeviceResetLocked(
684 nsecs_t currentTime, DeviceResetEntry* entry) {
685#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +0000686 ALOGD("dispatchDeviceReset - eventTime=%lld, deviceId=%d", entry->eventTime, entry->deviceId);
Jeff Brown65fd2512011-08-18 11:20:58 -0700687#endif
688
689 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
690 "device was reset");
691 options.deviceId = entry->deviceId;
692 synthesizeCancelationEventsForAllConnectionsLocked(options);
693 return true;
694}
695
Jeff Brown214eaf42011-05-26 19:17:02 -0700696bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, KeyEntry* entry,
Jeff Browne20c9e02010-10-11 14:20:19 -0700697 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Jeff Browne46a0a42010-11-02 17:58:22 -0700698 // Preprocessing.
699 if (! entry->dispatchInProgress) {
700 if (entry->repeatCount == 0
701 && entry->action == AKEY_EVENT_ACTION_DOWN
702 && (entry->policyFlags & POLICY_FLAG_TRUSTED)
Jeff Brown0029c662011-03-30 02:25:18 -0700703 && (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
Jeff Browne46a0a42010-11-02 17:58:22 -0700704 if (mKeyRepeatState.lastKeyEntry
705 && mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode) {
706 // We have seen two identical key downs in a row which indicates that the device
707 // driver is automatically generating key repeats itself. We take note of the
708 // repeat here, but we disable our own next key repeat timer since it is clear that
709 // we will not need to synthesize key repeats ourselves.
710 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
711 resetKeyRepeatLocked();
712 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
713 } else {
714 // Not a repeat. Save key down state in case we do see a repeat later.
715 resetKeyRepeatLocked();
Jeff Brown214eaf42011-05-26 19:17:02 -0700716 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
Jeff Browne46a0a42010-11-02 17:58:22 -0700717 }
718 mKeyRepeatState.lastKeyEntry = entry;
719 entry->refCount += 1;
720 } else if (! entry->syntheticRepeat) {
721 resetKeyRepeatLocked();
722 }
723
Jeff Browne2e01262011-03-02 20:34:30 -0800724 if (entry->repeatCount == 1) {
725 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
726 } else {
727 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
728 }
729
Jeff Browne46a0a42010-11-02 17:58:22 -0700730 entry->dispatchInProgress = true;
Jeff Browne46a0a42010-11-02 17:58:22 -0700731
732 logOutboundKeyDetailsLocked("dispatchKey - ", entry);
733 }
734
Jeff Brown905805a2011-10-12 13:57:59 -0700735 // Handle case where the policy asked us to try again later last time.
736 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
737 if (currentTime < entry->interceptKeyWakeupTime) {
738 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
739 *nextWakeupTime = entry->interceptKeyWakeupTime;
740 }
741 return false; // wait until next wakeup
742 }
743 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
744 entry->interceptKeyWakeupTime = 0;
745 }
746
Jeff Brown54a18252010-09-16 14:07:33 -0700747 // Give the policy a chance to intercept the key.
748 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
Jeff Browne20c9e02010-10-11 14:20:19 -0700749 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Jeff Brown54a18252010-09-16 14:07:33 -0700750 CommandEntry* commandEntry = postCommandLocked(
751 & InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
Jeff Brown9302c872011-07-13 22:51:29 -0700752 if (mFocusedWindowHandle != NULL) {
753 commandEntry->inputWindowHandle = mFocusedWindowHandle;
Jeff Brown54a18252010-09-16 14:07:33 -0700754 }
755 commandEntry->keyEntry = entry;
756 entry->refCount += 1;
757 return false; // wait for the command to run
758 } else {
759 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
760 }
761 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Jeff Browne20c9e02010-10-11 14:20:19 -0700762 if (*dropReason == DROP_REASON_NOT_DROPPED) {
763 *dropReason = DROP_REASON_POLICY;
764 }
Jeff Brown54a18252010-09-16 14:07:33 -0700765 }
766
767 // Clean up if dropping the event.
Jeff Browne20c9e02010-10-11 14:20:19 -0700768 if (*dropReason != DROP_REASON_NOT_DROPPED) {
Jeff Brown3122e442010-10-11 23:32:49 -0700769 setInjectionResultLocked(entry, *dropReason == DROP_REASON_POLICY
770 ? INPUT_EVENT_INJECTION_SUCCEEDED : INPUT_EVENT_INJECTION_FAILED);
Jeff Brown54a18252010-09-16 14:07:33 -0700771 return true;
772 }
773
Jeff Brownb88102f2010-09-08 11:49:43 -0700774 // Identify targets.
Jeff Browne9bb9be2012-02-06 15:47:55 -0800775 Vector<InputTarget> inputTargets;
776 int32_t injectionResult = findFocusedWindowTargetsLocked(currentTime,
777 entry, inputTargets, nextWakeupTime);
778 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
779 return false;
Jeff Brownb88102f2010-09-08 11:49:43 -0700780 }
781
Jeff Browne9bb9be2012-02-06 15:47:55 -0800782 setInjectionResultLocked(entry, injectionResult);
783 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
784 return true;
785 }
786
787 addMonitoringTargetsLocked(inputTargets);
788
Jeff Brownb88102f2010-09-08 11:49:43 -0700789 // Dispatch the key.
Jeff Browne9bb9be2012-02-06 15:47:55 -0800790 dispatchEventLocked(currentTime, entry, inputTargets);
Jeff Brownb88102f2010-09-08 11:49:43 -0700791 return true;
792}
793
794void InputDispatcher::logOutboundKeyDetailsLocked(const char* prefix, const KeyEntry* entry) {
795#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +0000796 ALOGD("%seventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, "
Jeff Brownb88102f2010-09-08 11:49:43 -0700797 "action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, "
Jeff Browne46a0a42010-11-02 17:58:22 -0700798 "repeatCount=%d, downTime=%lld",
Jeff Brownb88102f2010-09-08 11:49:43 -0700799 prefix,
800 entry->eventTime, entry->deviceId, entry->source, entry->policyFlags,
801 entry->action, entry->flags, entry->keyCode, entry->scanCode, entry->metaState,
Jeff Browne46a0a42010-11-02 17:58:22 -0700802 entry->repeatCount, entry->downTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700803#endif
804}
805
806bool InputDispatcher::dispatchMotionLocked(
Jeff Browne20c9e02010-10-11 14:20:19 -0700807 nsecs_t currentTime, MotionEntry* entry, DropReason* dropReason, nsecs_t* nextWakeupTime) {
Jeff Browne46a0a42010-11-02 17:58:22 -0700808 // Preprocessing.
809 if (! entry->dispatchInProgress) {
810 entry->dispatchInProgress = true;
Jeff Browne46a0a42010-11-02 17:58:22 -0700811
812 logOutboundMotionDetailsLocked("dispatchMotion - ", entry);
813 }
814
Jeff Brown54a18252010-09-16 14:07:33 -0700815 // Clean up if dropping the event.
Jeff Browne20c9e02010-10-11 14:20:19 -0700816 if (*dropReason != DROP_REASON_NOT_DROPPED) {
Jeff Brown3122e442010-10-11 23:32:49 -0700817 setInjectionResultLocked(entry, *dropReason == DROP_REASON_POLICY
818 ? INPUT_EVENT_INJECTION_SUCCEEDED : INPUT_EVENT_INJECTION_FAILED);
Jeff Brown54a18252010-09-16 14:07:33 -0700819 return true;
820 }
821
Jeff Brownb88102f2010-09-08 11:49:43 -0700822 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
823
824 // Identify targets.
Jeff Browne9bb9be2012-02-06 15:47:55 -0800825 Vector<InputTarget> inputTargets;
826
Jeff Browncc0c1592011-02-19 05:07:28 -0800827 bool conflictingPointerActions = false;
Jeff Browne9bb9be2012-02-06 15:47:55 -0800828 int32_t injectionResult;
829 if (isPointerEvent) {
830 // Pointer event. (eg. touchscreen)
831 injectionResult = findTouchedWindowTargetsLocked(currentTime,
832 entry, inputTargets, nextWakeupTime, &conflictingPointerActions);
833 } else {
834 // Non touch event. (eg. trackball)
835 injectionResult = findFocusedWindowTargetsLocked(currentTime,
836 entry, inputTargets, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700837 }
Jeff Browne9bb9be2012-02-06 15:47:55 -0800838 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
839 return false;
840 }
841
842 setInjectionResultLocked(entry, injectionResult);
843 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
844 return true;
845 }
846
Jeff Brown83d616a2012-09-09 20:33:43 -0700847 // TODO: support sending secondary display events to input monitors
848 if (isMainDisplay(entry->displayId)) {
849 addMonitoringTargetsLocked(inputTargets);
850 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700851
852 // Dispatch the motion.
Jeff Browncc0c1592011-02-19 05:07:28 -0800853 if (conflictingPointerActions) {
Jeff Brownda3d5a92011-03-29 15:11:34 -0700854 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
855 "conflicting pointer actions");
856 synthesizeCancelationEventsForAllConnectionsLocked(options);
Jeff Browncc0c1592011-02-19 05:07:28 -0800857 }
Jeff Browne9bb9be2012-02-06 15:47:55 -0800858 dispatchEventLocked(currentTime, entry, inputTargets);
Jeff Brownb88102f2010-09-08 11:49:43 -0700859 return true;
860}
861
862
863void InputDispatcher::logOutboundMotionDetailsLocked(const char* prefix, const MotionEntry* entry) {
864#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +0000865 ALOGD("%seventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, "
Jeff Brown85a31762010-09-01 17:01:00 -0700866 "action=0x%x, flags=0x%x, "
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700867 "metaState=0x%x, buttonState=0x%x, "
868 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%lld",
Jeff Brownb88102f2010-09-08 11:49:43 -0700869 prefix,
Jeff Brown85a31762010-09-01 17:01:00 -0700870 entry->eventTime, entry->deviceId, entry->source, entry->policyFlags,
871 entry->action, entry->flags,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700872 entry->metaState, entry->buttonState,
873 entry->edgeFlags, entry->xPrecision, entry->yPrecision,
Jeff Brown46b9ac02010-04-22 18:58:52 -0700874 entry->downTime);
875
Jeff Brown46b9ac02010-04-22 18:58:52 -0700876 for (uint32_t i = 0; i < entry->pointerCount; i++) {
Steve Block5baa3a62011-12-20 16:23:08 +0000877 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700878 "x=%f, y=%f, pressure=%f, size=%f, "
Jeff Brown85a31762010-09-01 17:01:00 -0700879 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
Jeff Brown8d608662010-08-30 03:02:23 -0700880 "orientation=%f",
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700881 i, entry->pointerProperties[i].id,
882 entry->pointerProperties[i].toolType,
Jeff Brown3241b6b2012-02-03 15:08:02 -0800883 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
884 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
885 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
886 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
887 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
888 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
889 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
890 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
891 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Jeff Brown46b9ac02010-04-22 18:58:52 -0700892 }
893#endif
Jeff Brown46b9ac02010-04-22 18:58:52 -0700894}
895
Jeff Browne9bb9be2012-02-06 15:47:55 -0800896void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
897 EventEntry* eventEntry, const Vector<InputTarget>& inputTargets) {
Jeff Brown46b9ac02010-04-22 18:58:52 -0700898#if DEBUG_DISPATCH_CYCLE
Jeff Brown3241b6b2012-02-03 15:08:02 -0800899 ALOGD("dispatchEventToCurrentInputTargets");
Jeff Brown46b9ac02010-04-22 18:58:52 -0700900#endif
901
Steve Blockec193de2012-01-09 18:35:44 +0000902 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
Jeff Brown9c3cda02010-06-15 01:31:58 -0700903
Jeff Browne2fe69e2010-10-18 13:21:23 -0700904 pokeUserActivityLocked(eventEntry);
905
Jeff Browne9bb9be2012-02-06 15:47:55 -0800906 for (size_t i = 0; i < inputTargets.size(); i++) {
907 const InputTarget& inputTarget = inputTargets.itemAt(i);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700908
Jeff Brown519e0242010-09-15 15:18:56 -0700909 ssize_t connectionIndex = getConnectionIndexLocked(inputTarget.inputChannel);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700910 if (connectionIndex >= 0) {
Jeff Browncbee6d62012-02-03 20:11:27 -0800911 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
Jeff Brown3241b6b2012-02-03 15:08:02 -0800912 prepareDispatchCycleLocked(currentTime, connection, eventEntry, &inputTarget);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700913 } else {
Jeff Brownb6997262010-10-08 22:31:17 -0700914#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +0000915 ALOGD("Dropping event delivery to target with channel '%s' because it "
Jeff Brownb6997262010-10-08 22:31:17 -0700916 "is no longer registered with the input dispatcher.",
Jeff Brown46b9ac02010-04-22 18:58:52 -0700917 inputTarget.inputChannel->getName().string());
Jeff Brownb6997262010-10-08 22:31:17 -0700918#endif
Jeff Brown46b9ac02010-04-22 18:58:52 -0700919 }
920 }
921}
922
Jeff Brownb88102f2010-09-08 11:49:43 -0700923int32_t InputDispatcher::handleTargetsNotReadyLocked(nsecs_t currentTime,
Jeff Brown9302c872011-07-13 22:51:29 -0700924 const EventEntry* entry,
925 const sp<InputApplicationHandle>& applicationHandle,
926 const sp<InputWindowHandle>& windowHandle,
Jeff Brown265f1cc2012-06-11 18:01:06 -0700927 nsecs_t* nextWakeupTime, const char* reason) {
Jeff Brown9302c872011-07-13 22:51:29 -0700928 if (applicationHandle == NULL && windowHandle == NULL) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700929 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY) {
930#if DEBUG_FOCUS
Jeff Brown265f1cc2012-06-11 18:01:06 -0700931 ALOGD("Waiting for system to become ready for input. Reason: %s", reason);
Jeff Brownb88102f2010-09-08 11:49:43 -0700932#endif
933 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY;
934 mInputTargetWaitStartTime = currentTime;
935 mInputTargetWaitTimeoutTime = LONG_LONG_MAX;
936 mInputTargetWaitTimeoutExpired = false;
Jeff Brown9302c872011-07-13 22:51:29 -0700937 mInputTargetWaitApplicationHandle.clear();
Jeff Brownb88102f2010-09-08 11:49:43 -0700938 }
939 } else {
940 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
941#if DEBUG_FOCUS
Jeff Brown265f1cc2012-06-11 18:01:06 -0700942 ALOGD("Waiting for application to become ready for input: %s. Reason: %s",
943 getApplicationWindowLabelLocked(applicationHandle, windowHandle).string(),
944 reason);
Jeff Brownb88102f2010-09-08 11:49:43 -0700945#endif
Jeff Browncc4f7db2011-08-30 20:34:48 -0700946 nsecs_t timeout;
947 if (windowHandle != NULL) {
948 timeout = windowHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
949 } else if (applicationHandle != NULL) {
950 timeout = applicationHandle->getDispatchingTimeout(
951 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
952 } else {
953 timeout = DEFAULT_INPUT_DISPATCHING_TIMEOUT;
954 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700955
956 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY;
957 mInputTargetWaitStartTime = currentTime;
958 mInputTargetWaitTimeoutTime = currentTime + timeout;
959 mInputTargetWaitTimeoutExpired = false;
Jeff Brown9302c872011-07-13 22:51:29 -0700960 mInputTargetWaitApplicationHandle.clear();
Jeff Brown928e0542011-01-10 11:17:36 -0800961
Jeff Brown9302c872011-07-13 22:51:29 -0700962 if (windowHandle != NULL) {
963 mInputTargetWaitApplicationHandle = windowHandle->inputApplicationHandle;
Jeff Brown928e0542011-01-10 11:17:36 -0800964 }
Jeff Brown9302c872011-07-13 22:51:29 -0700965 if (mInputTargetWaitApplicationHandle == NULL && applicationHandle != NULL) {
966 mInputTargetWaitApplicationHandle = applicationHandle;
Jeff Brown928e0542011-01-10 11:17:36 -0800967 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700968 }
969 }
970
971 if (mInputTargetWaitTimeoutExpired) {
972 return INPUT_EVENT_INJECTION_TIMED_OUT;
973 }
974
975 if (currentTime >= mInputTargetWaitTimeoutTime) {
Jeff Brown9302c872011-07-13 22:51:29 -0700976 onANRLocked(currentTime, applicationHandle, windowHandle,
Jeff Brown265f1cc2012-06-11 18:01:06 -0700977 entry->eventTime, mInputTargetWaitStartTime, reason);
Jeff Brownb88102f2010-09-08 11:49:43 -0700978
979 // Force poll loop to wake up immediately on next iteration once we get the
980 // ANR response back from the policy.
981 *nextWakeupTime = LONG_LONG_MIN;
982 return INPUT_EVENT_INJECTION_PENDING;
983 } else {
984 // Force poll loop to wake up when timeout is due.
985 if (mInputTargetWaitTimeoutTime < *nextWakeupTime) {
986 *nextWakeupTime = mInputTargetWaitTimeoutTime;
987 }
988 return INPUT_EVENT_INJECTION_PENDING;
989 }
990}
991
Jeff Brown519e0242010-09-15 15:18:56 -0700992void InputDispatcher::resumeAfterTargetsNotReadyTimeoutLocked(nsecs_t newTimeout,
993 const sp<InputChannel>& inputChannel) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700994 if (newTimeout > 0) {
995 // Extend the timeout.
996 mInputTargetWaitTimeoutTime = now() + newTimeout;
997 } else {
998 // Give up.
999 mInputTargetWaitTimeoutExpired = true;
Jeff Brown519e0242010-09-15 15:18:56 -07001000
1001 // Input state will not be realistic. Mark it out of sync.
Jeff Browndc3e0052010-09-16 11:02:16 -07001002 if (inputChannel.get()) {
1003 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
1004 if (connectionIndex >= 0) {
Jeff Browncbee6d62012-02-03 20:11:27 -08001005 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
Jeff Brownf44e3942012-04-20 11:33:27 -07001006 sp<InputWindowHandle> windowHandle = connection->inputWindowHandle;
1007
1008 if (windowHandle != NULL) {
1009 mTouchState.removeWindow(windowHandle);
1010 }
1011
Jeff Brown00045a72010-12-09 18:10:30 -08001012 if (connection->status == Connection::STATUS_NORMAL) {
Jeff Brownda3d5a92011-03-29 15:11:34 -07001013 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
Jeff Brown00045a72010-12-09 18:10:30 -08001014 "application not responding");
Jeff Brownda3d5a92011-03-29 15:11:34 -07001015 synthesizeCancelationEventsForConnectionLocked(connection, options);
Jeff Brown00045a72010-12-09 18:10:30 -08001016 }
Jeff Browndc3e0052010-09-16 11:02:16 -07001017 }
Jeff Brown519e0242010-09-15 15:18:56 -07001018 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001019 }
1020}
1021
Jeff Brown519e0242010-09-15 15:18:56 -07001022nsecs_t InputDispatcher::getTimeSpentWaitingForApplicationLocked(
Jeff Brownb88102f2010-09-08 11:49:43 -07001023 nsecs_t currentTime) {
1024 if (mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
1025 return currentTime - mInputTargetWaitStartTime;
1026 }
1027 return 0;
1028}
1029
1030void InputDispatcher::resetANRTimeoutsLocked() {
1031#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001032 ALOGD("Resetting ANR timeouts.");
Jeff Brownb88102f2010-09-08 11:49:43 -07001033#endif
1034
Jeff Brownb88102f2010-09-08 11:49:43 -07001035 // Reset input target wait timeout.
1036 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_NONE;
Jeff Brown5ea29ab2011-07-27 11:50:51 -07001037 mInputTargetWaitApplicationHandle.clear();
Jeff Brownb88102f2010-09-08 11:49:43 -07001038}
1039
Jeff Brown01ce2e92010-09-26 22:20:12 -07001040int32_t InputDispatcher::findFocusedWindowTargetsLocked(nsecs_t currentTime,
Jeff Browne9bb9be2012-02-06 15:47:55 -08001041 const EventEntry* entry, Vector<InputTarget>& inputTargets, nsecs_t* nextWakeupTime) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001042 int32_t injectionResult;
1043
1044 // If there is no currently focused window and no focused application
1045 // then drop the event.
Jeff Brown9302c872011-07-13 22:51:29 -07001046 if (mFocusedWindowHandle == NULL) {
1047 if (mFocusedApplicationHandle != NULL) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001048 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brown265f1cc2012-06-11 18:01:06 -07001049 mFocusedApplicationHandle, NULL, nextWakeupTime,
1050 "Waiting because no window has focus but there is a "
1051 "focused application that may eventually add a window "
1052 "when it finishes starting up.");
Jeff Brownb88102f2010-09-08 11:49:43 -07001053 goto Unresponsive;
1054 }
1055
Steve Block6215d3f2012-01-04 20:05:49 +00001056 ALOGI("Dropping event because there is no focused window or focused application.");
Jeff Brownb88102f2010-09-08 11:49:43 -07001057 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1058 goto Failed;
1059 }
1060
1061 // Check permissions.
Jeff Brown9302c872011-07-13 22:51:29 -07001062 if (! checkInjectionPermission(mFocusedWindowHandle, entry->injectionState)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001063 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1064 goto Failed;
1065 }
1066
1067 // If the currently focused window is paused then keep waiting.
Jeff Browncc4f7db2011-08-30 20:34:48 -07001068 if (mFocusedWindowHandle->getInfo()->paused) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001069 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brown265f1cc2012-06-11 18:01:06 -07001070 mFocusedApplicationHandle, mFocusedWindowHandle, nextWakeupTime,
1071 "Waiting because the focused window is paused.");
Jeff Brownb88102f2010-09-08 11:49:43 -07001072 goto Unresponsive;
1073 }
1074
Jeff Brown519e0242010-09-15 15:18:56 -07001075 // If the currently focused window is still working on previous events then keep waiting.
Jeff Brown0952c302012-02-13 13:48:59 -08001076 if (!isWindowReadyForMoreInputLocked(currentTime, mFocusedWindowHandle, entry)) {
Jeff Brown519e0242010-09-15 15:18:56 -07001077 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brown265f1cc2012-06-11 18:01:06 -07001078 mFocusedApplicationHandle, mFocusedWindowHandle, nextWakeupTime,
1079 "Waiting because the focused window has not finished "
1080 "processing the input events that were previously delivered to it.");
Jeff Brown519e0242010-09-15 15:18:56 -07001081 goto Unresponsive;
1082 }
1083
Jeff Brownb88102f2010-09-08 11:49:43 -07001084 // Success! Output targets.
1085 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
Jeff Brown9302c872011-07-13 22:51:29 -07001086 addWindowTargetLocked(mFocusedWindowHandle,
Jeff Browne9bb9be2012-02-06 15:47:55 -08001087 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS, BitSet32(0),
1088 inputTargets);
Jeff Brownb88102f2010-09-08 11:49:43 -07001089
1090 // Done.
1091Failed:
1092Unresponsive:
Jeff Brown519e0242010-09-15 15:18:56 -07001093 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
1094 updateDispatchStatisticsLocked(currentTime, entry,
1095 injectionResult, timeSpentWaitingForApplication);
Jeff Brownb88102f2010-09-08 11:49:43 -07001096#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001097 ALOGD("findFocusedWindow finished: injectionResult=%d, "
Jeff Brown22aa5122012-06-17 12:01:06 -07001098 "timeSpentWaitingForApplication=%0.1fms",
Jeff Brown519e0242010-09-15 15:18:56 -07001099 injectionResult, timeSpentWaitingForApplication / 1000000.0);
Jeff Brownb88102f2010-09-08 11:49:43 -07001100#endif
1101 return injectionResult;
1102}
1103
Jeff Brown01ce2e92010-09-26 22:20:12 -07001104int32_t InputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime,
Jeff Browne9bb9be2012-02-06 15:47:55 -08001105 const MotionEntry* entry, Vector<InputTarget>& inputTargets, nsecs_t* nextWakeupTime,
1106 bool* outConflictingPointerActions) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001107 enum InjectionPermission {
1108 INJECTION_PERMISSION_UNKNOWN,
1109 INJECTION_PERMISSION_GRANTED,
1110 INJECTION_PERMISSION_DENIED
1111 };
1112
Jeff Brownb88102f2010-09-08 11:49:43 -07001113 nsecs_t startTime = now();
1114
1115 // For security reasons, we defer updating the touch state until we are sure that
1116 // event injection will be allowed.
1117 //
1118 // FIXME In the original code, screenWasOff could never be set to true.
1119 // The reason is that the POLICY_FLAG_WOKE_HERE
1120 // and POLICY_FLAG_BRIGHT_HERE flags were set only when preprocessing raw
1121 // EV_KEY, EV_REL and EV_ABS events. As it happens, the touch event was
1122 // actually enqueued using the policyFlags that appeared in the final EV_SYN
1123 // events upon which no preprocessing took place. So policyFlags was always 0.
1124 // In the new native input dispatcher we're a bit more careful about event
1125 // preprocessing so the touches we receive can actually have non-zero policyFlags.
1126 // Unfortunately we obtain undesirable behavior.
1127 //
1128 // Here's what happens:
1129 //
1130 // When the device dims in anticipation of going to sleep, touches
1131 // in windows which have FLAG_TOUCHABLE_WHEN_WAKING cause
1132 // the device to brighten and reset the user activity timer.
1133 // Touches on other windows (such as the launcher window)
1134 // are dropped. Then after a moment, the device goes to sleep. Oops.
1135 //
1136 // Also notice how screenWasOff was being initialized using POLICY_FLAG_BRIGHT_HERE
1137 // instead of POLICY_FLAG_WOKE_HERE...
1138 //
1139 bool screenWasOff = false; // original policy: policyFlags & POLICY_FLAG_BRIGHT_HERE;
1140
Jeff Brown83d616a2012-09-09 20:33:43 -07001141 int32_t displayId = entry->displayId;
Jeff Brownb88102f2010-09-08 11:49:43 -07001142 int32_t action = entry->action;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001143 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Jeff Brownb88102f2010-09-08 11:49:43 -07001144
1145 // Update the touch state as needed based on the properties of the touch event.
Jeff Brown01ce2e92010-09-26 22:20:12 -07001146 int32_t injectionResult = INPUT_EVENT_INJECTION_PENDING;
1147 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
Jeff Brown9302c872011-07-13 22:51:29 -07001148 sp<InputWindowHandle> newHoverWindowHandle;
Jeff Browncc0c1592011-02-19 05:07:28 -08001149
1150 bool isSplit = mTouchState.split;
Jeff Brown83d616a2012-09-09 20:33:43 -07001151 bool switchedDevice = mTouchState.deviceId >= 0 && mTouchState.displayId >= 0
Jeff Brown2717eff2011-06-30 23:53:07 -07001152 && (mTouchState.deviceId != entry->deviceId
Jeff Brown83d616a2012-09-09 20:33:43 -07001153 || mTouchState.source != entry->source
1154 || mTouchState.displayId != displayId);
Jeff Browna032cc02011-03-07 16:56:21 -08001155 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE
1156 || maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER
1157 || maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1158 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN
1159 || maskedAction == AMOTION_EVENT_ACTION_SCROLL
1160 || isHoverAction);
Jeff Brown81346812011-06-28 20:08:48 -07001161 bool wrongDevice = false;
Jeff Browna032cc02011-03-07 16:56:21 -08001162 if (newGesture) {
Jeff Browncc0c1592011-02-19 05:07:28 -08001163 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Jeff Brown81346812011-06-28 20:08:48 -07001164 if (switchedDevice && mTouchState.down && !down) {
1165#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001166 ALOGD("Dropping event because a pointer for a different device is already down.");
Jeff Brown81346812011-06-28 20:08:48 -07001167#endif
Jeff Browncc0c1592011-02-19 05:07:28 -08001168 mTempTouchState.copyFrom(mTouchState);
Jeff Brown81346812011-06-28 20:08:48 -07001169 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1170 switchedDevice = false;
1171 wrongDevice = true;
1172 goto Failed;
Jeff Browncc0c1592011-02-19 05:07:28 -08001173 }
Jeff Brown81346812011-06-28 20:08:48 -07001174 mTempTouchState.reset();
1175 mTempTouchState.down = down;
1176 mTempTouchState.deviceId = entry->deviceId;
1177 mTempTouchState.source = entry->source;
Jeff Brown83d616a2012-09-09 20:33:43 -07001178 mTempTouchState.displayId = displayId;
Jeff Brown81346812011-06-28 20:08:48 -07001179 isSplit = false;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001180 } else {
1181 mTempTouchState.copyFrom(mTouchState);
Jeff Browncc0c1592011-02-19 05:07:28 -08001182 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001183
Jeff Browna032cc02011-03-07 16:56:21 -08001184 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
Jeff Brown33bbfd22011-02-24 20:55:35 -08001185 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
Jeff Brownb88102f2010-09-08 11:49:43 -07001186
Jeff Brown01ce2e92010-09-26 22:20:12 -07001187 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Jeff Brown3241b6b2012-02-03 15:08:02 -08001188 int32_t x = int32_t(entry->pointerCoords[pointerIndex].
Jeff Brownebbd5d12011-02-17 13:01:34 -08001189 getAxisValue(AMOTION_EVENT_AXIS_X));
Jeff Brown3241b6b2012-02-03 15:08:02 -08001190 int32_t y = int32_t(entry->pointerCoords[pointerIndex].
Jeff Brownebbd5d12011-02-17 13:01:34 -08001191 getAxisValue(AMOTION_EVENT_AXIS_Y));
Jeff Brown9302c872011-07-13 22:51:29 -07001192 sp<InputWindowHandle> newTouchedWindowHandle;
1193 sp<InputWindowHandle> topErrorWindowHandle;
Jeff Browna032cc02011-03-07 16:56:21 -08001194 bool isTouchModal = false;
Jeff Brownb88102f2010-09-08 11:49:43 -07001195
1196 // Traverse windows from front to back to find touched window and outside targets.
Jeff Brown9302c872011-07-13 22:51:29 -07001197 size_t numWindows = mWindowHandles.size();
Jeff Brownb88102f2010-09-08 11:49:43 -07001198 for (size_t i = 0; i < numWindows; i++) {
Jeff Brown9302c872011-07-13 22:51:29 -07001199 sp<InputWindowHandle> windowHandle = mWindowHandles.itemAt(i);
Jeff Browncc4f7db2011-08-30 20:34:48 -07001200 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Jeff Brown83d616a2012-09-09 20:33:43 -07001201 if (windowInfo->displayId != displayId) {
1202 continue; // wrong display
1203 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001204
Jeff Brown83d616a2012-09-09 20:33:43 -07001205 int32_t flags = windowInfo->layoutParamsFlags;
Jeff Browncc4f7db2011-08-30 20:34:48 -07001206 if (flags & InputWindowInfo::FLAG_SYSTEM_ERROR) {
Jeff Brown9302c872011-07-13 22:51:29 -07001207 if (topErrorWindowHandle == NULL) {
1208 topErrorWindowHandle = windowHandle;
Jeff Brownb88102f2010-09-08 11:49:43 -07001209 }
1210 }
1211
Jeff Browncc4f7db2011-08-30 20:34:48 -07001212 if (windowInfo->visible) {
1213 if (! (flags & InputWindowInfo::FLAG_NOT_TOUCHABLE)) {
1214 isTouchModal = (flags & (InputWindowInfo::FLAG_NOT_FOCUSABLE
1215 | InputWindowInfo::FLAG_NOT_TOUCH_MODAL)) == 0;
1216 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
Jeff Brown9302c872011-07-13 22:51:29 -07001217 if (! screenWasOff
Jeff Browncc4f7db2011-08-30 20:34:48 -07001218 || (flags & InputWindowInfo::FLAG_TOUCHABLE_WHEN_WAKING)) {
Jeff Brown9302c872011-07-13 22:51:29 -07001219 newTouchedWindowHandle = windowHandle;
Jeff Brownb88102f2010-09-08 11:49:43 -07001220 }
1221 break; // found touched window, exit window loop
1222 }
1223 }
1224
Jeff Brown01ce2e92010-09-26 22:20:12 -07001225 if (maskedAction == AMOTION_EVENT_ACTION_DOWN
Jeff Browncc4f7db2011-08-30 20:34:48 -07001226 && (flags & InputWindowInfo::FLAG_WATCH_OUTSIDE_TOUCH)) {
Jeff Browna032cc02011-03-07 16:56:21 -08001227 int32_t outsideTargetFlags = InputTarget::FLAG_DISPATCH_AS_OUTSIDE;
Jeff Brown9302c872011-07-13 22:51:29 -07001228 if (isWindowObscuredAtPointLocked(windowHandle, x, y)) {
Jeff Brown19dfc832010-10-05 12:26:23 -07001229 outsideTargetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1230 }
1231
Jeff Brown9302c872011-07-13 22:51:29 -07001232 mTempTouchState.addOrUpdateWindow(
1233 windowHandle, outsideTargetFlags, BitSet32(0));
Jeff Brownb88102f2010-09-08 11:49:43 -07001234 }
1235 }
1236 }
1237
1238 // If there is an error window but it is not taking focus (typically because
1239 // it is invisible) then wait for it. Any other focused window may in
1240 // fact be in ANR state.
Jeff Brown9302c872011-07-13 22:51:29 -07001241 if (topErrorWindowHandle != NULL && newTouchedWindowHandle != topErrorWindowHandle) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001242 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brown265f1cc2012-06-11 18:01:06 -07001243 NULL, NULL, nextWakeupTime,
1244 "Waiting because a system error window is about to be displayed.");
Jeff Brownb88102f2010-09-08 11:49:43 -07001245 injectionPermission = INJECTION_PERMISSION_UNKNOWN;
1246 goto Unresponsive;
1247 }
1248
Jeff Brown01ce2e92010-09-26 22:20:12 -07001249 // Figure out whether splitting will be allowed for this window.
Jeff Browncc4f7db2011-08-30 20:34:48 -07001250 if (newTouchedWindowHandle != NULL
1251 && newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001252 // New window supports splitting.
1253 isSplit = true;
1254 } else if (isSplit) {
1255 // New window does not support splitting but we have already split events.
Jeff Brown8249fc62012-05-24 18:57:32 -07001256 // Ignore the new window.
1257 newTouchedWindowHandle = NULL;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001258 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001259
Jeff Brown8249fc62012-05-24 18:57:32 -07001260 // Handle the case where we did not find a window.
Jeff Brown9302c872011-07-13 22:51:29 -07001261 if (newTouchedWindowHandle == NULL) {
Jeff Brown8249fc62012-05-24 18:57:32 -07001262 // Try to assign the pointer to the first foreground window we find, if there is one.
1263 newTouchedWindowHandle = mTempTouchState.getFirstForegroundWindowHandle();
1264 if (newTouchedWindowHandle == NULL) {
1265 // There is no touched window. If this is an initial down event
1266 // then wait for a window to appear that will handle the touch. This is
1267 // to ensure that we report an ANR in the case where an application has started
1268 // but not yet put up a window and the user is starting to get impatient.
1269 if (maskedAction == AMOTION_EVENT_ACTION_DOWN
1270 && mFocusedApplicationHandle != NULL) {
Jeff Brown8249fc62012-05-24 18:57:32 -07001271 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brown265f1cc2012-06-11 18:01:06 -07001272 mFocusedApplicationHandle, NULL, nextWakeupTime,
1273 "Waiting because there is no touchable window that can "
1274 "handle the event but there is focused application that may "
1275 "eventually add a new window when it finishes starting up.");
Jeff Brown8249fc62012-05-24 18:57:32 -07001276 goto Unresponsive;
1277 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001278
Jeff Brown8249fc62012-05-24 18:57:32 -07001279 ALOGI("Dropping event because there is no touched window.");
1280 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1281 goto Failed;
1282 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001283 }
1284
Jeff Brown19dfc832010-10-05 12:26:23 -07001285 // Set target flags.
Jeff Browna032cc02011-03-07 16:56:21 -08001286 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
Jeff Brown19dfc832010-10-05 12:26:23 -07001287 if (isSplit) {
1288 targetFlags |= InputTarget::FLAG_SPLIT;
1289 }
Jeff Brown9302c872011-07-13 22:51:29 -07001290 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
Jeff Brown19dfc832010-10-05 12:26:23 -07001291 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1292 }
1293
Jeff Browna032cc02011-03-07 16:56:21 -08001294 // Update hover state.
1295 if (isHoverAction) {
Jeff Brown9302c872011-07-13 22:51:29 -07001296 newHoverWindowHandle = newTouchedWindowHandle;
Jeff Browna032cc02011-03-07 16:56:21 -08001297 } else if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
Jeff Brown9302c872011-07-13 22:51:29 -07001298 newHoverWindowHandle = mLastHoverWindowHandle;
Jeff Browna032cc02011-03-07 16:56:21 -08001299 }
1300
Jeff Brown01ce2e92010-09-26 22:20:12 -07001301 // Update the temporary touch state.
1302 BitSet32 pointerIds;
1303 if (isSplit) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07001304 uint32_t pointerId = entry->pointerProperties[pointerIndex].id;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001305 pointerIds.markBit(pointerId);
Jeff Brownb88102f2010-09-08 11:49:43 -07001306 }
Jeff Brown9302c872011-07-13 22:51:29 -07001307 mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Jeff Brownb88102f2010-09-08 11:49:43 -07001308 } else {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001309 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
Jeff Brownb88102f2010-09-08 11:49:43 -07001310
1311 // If the pointer is not currently down, then ignore the event.
Jeff Brown01ce2e92010-09-26 22:20:12 -07001312 if (! mTempTouchState.down) {
Jeff Browna2cc28d2011-03-25 11:58:46 -07001313#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001314 ALOGD("Dropping event because the pointer is not down or we previously "
Jeff Brown76860e32010-10-25 17:37:46 -07001315 "dropped the pointer down event.");
1316#endif
Jeff Brownb88102f2010-09-08 11:49:43 -07001317 injectionResult = INPUT_EVENT_INJECTION_FAILED;
Jeff Brownb88102f2010-09-08 11:49:43 -07001318 goto Failed;
1319 }
Jeff Brown98db5fa2011-06-08 15:37:10 -07001320
1321 // Check whether touches should slip outside of the current foreground window.
1322 if (maskedAction == AMOTION_EVENT_ACTION_MOVE
1323 && entry->pointerCount == 1
1324 && mTempTouchState.isSlippery()) {
Jeff Brown3241b6b2012-02-03 15:08:02 -08001325 int32_t x = int32_t(entry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
1326 int32_t y = int32_t(entry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Jeff Brown98db5fa2011-06-08 15:37:10 -07001327
Jeff Brown9302c872011-07-13 22:51:29 -07001328 sp<InputWindowHandle> oldTouchedWindowHandle =
1329 mTempTouchState.getFirstForegroundWindowHandle();
Jeff Brown83d616a2012-09-09 20:33:43 -07001330 sp<InputWindowHandle> newTouchedWindowHandle =
1331 findTouchedWindowAtLocked(displayId, x, y);
Jeff Brown9302c872011-07-13 22:51:29 -07001332 if (oldTouchedWindowHandle != newTouchedWindowHandle
1333 && newTouchedWindowHandle != NULL) {
Jeff Brown98db5fa2011-06-08 15:37:10 -07001334#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001335 ALOGD("Touch is slipping out of window %s into window %s.",
Jeff Browncc4f7db2011-08-30 20:34:48 -07001336 oldTouchedWindowHandle->getName().string(),
1337 newTouchedWindowHandle->getName().string());
Jeff Brown98db5fa2011-06-08 15:37:10 -07001338#endif
1339 // Make a slippery exit from the old window.
Jeff Brown9302c872011-07-13 22:51:29 -07001340 mTempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
Jeff Brown98db5fa2011-06-08 15:37:10 -07001341 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT, BitSet32(0));
1342
1343 // Make a slippery entrance into the new window.
Jeff Browncc4f7db2011-08-30 20:34:48 -07001344 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Jeff Brown98db5fa2011-06-08 15:37:10 -07001345 isSplit = true;
1346 }
1347
1348 int32_t targetFlags = InputTarget::FLAG_FOREGROUND
1349 | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
1350 if (isSplit) {
1351 targetFlags |= InputTarget::FLAG_SPLIT;
1352 }
Jeff Brown9302c872011-07-13 22:51:29 -07001353 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
Jeff Brown98db5fa2011-06-08 15:37:10 -07001354 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1355 }
1356
1357 BitSet32 pointerIds;
1358 if (isSplit) {
1359 pointerIds.markBit(entry->pointerProperties[0].id);
1360 }
Jeff Brown9302c872011-07-13 22:51:29 -07001361 mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Jeff Brown98db5fa2011-06-08 15:37:10 -07001362 }
1363 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001364 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001365
Jeff Brown9302c872011-07-13 22:51:29 -07001366 if (newHoverWindowHandle != mLastHoverWindowHandle) {
Jeff Browna032cc02011-03-07 16:56:21 -08001367 // Let the previous window know that the hover sequence is over.
Jeff Brown9302c872011-07-13 22:51:29 -07001368 if (mLastHoverWindowHandle != NULL) {
Jeff Browna032cc02011-03-07 16:56:21 -08001369#if DEBUG_HOVER
Steve Block5baa3a62011-12-20 16:23:08 +00001370 ALOGD("Sending hover exit event to window %s.",
Jeff Browncc4f7db2011-08-30 20:34:48 -07001371 mLastHoverWindowHandle->getName().string());
Jeff Browna032cc02011-03-07 16:56:21 -08001372#endif
Jeff Brown9302c872011-07-13 22:51:29 -07001373 mTempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
Jeff Browna032cc02011-03-07 16:56:21 -08001374 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
1375 }
1376
1377 // Let the new window know that the hover sequence is starting.
Jeff Brown9302c872011-07-13 22:51:29 -07001378 if (newHoverWindowHandle != NULL) {
Jeff Browna032cc02011-03-07 16:56:21 -08001379#if DEBUG_HOVER
Steve Block5baa3a62011-12-20 16:23:08 +00001380 ALOGD("Sending hover enter event to window %s.",
Jeff Browncc4f7db2011-08-30 20:34:48 -07001381 newHoverWindowHandle->getName().string());
Jeff Browna032cc02011-03-07 16:56:21 -08001382#endif
Jeff Brown9302c872011-07-13 22:51:29 -07001383 mTempTouchState.addOrUpdateWindow(newHoverWindowHandle,
Jeff Browna032cc02011-03-07 16:56:21 -08001384 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER, BitSet32(0));
1385 }
1386 }
1387
Jeff Brown01ce2e92010-09-26 22:20:12 -07001388 // Check permission to inject into all touched foreground windows and ensure there
1389 // is at least one touched foreground window.
1390 {
1391 bool haveForegroundWindow = false;
1392 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1393 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1394 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1395 haveForegroundWindow = true;
Jeff Brown9302c872011-07-13 22:51:29 -07001396 if (! checkInjectionPermission(touchedWindow.windowHandle,
1397 entry->injectionState)) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001398 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1399 injectionPermission = INJECTION_PERMISSION_DENIED;
1400 goto Failed;
1401 }
1402 }
1403 }
1404 if (! haveForegroundWindow) {
Jeff Browna2cc28d2011-03-25 11:58:46 -07001405#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001406 ALOGD("Dropping event because there is no touched foreground window to receive it.");
Jeff Brownb88102f2010-09-08 11:49:43 -07001407#endif
1408 injectionResult = INPUT_EVENT_INJECTION_FAILED;
Jeff Brownb88102f2010-09-08 11:49:43 -07001409 goto Failed;
1410 }
1411
Jeff Brown01ce2e92010-09-26 22:20:12 -07001412 // Permission granted to injection into all touched foreground windows.
1413 injectionPermission = INJECTION_PERMISSION_GRANTED;
1414 }
Jeff Brown519e0242010-09-15 15:18:56 -07001415
Kenny Root7a9db182011-06-02 15:16:05 -07001416 // Check whether windows listening for outside touches are owned by the same UID. If it is
1417 // set the policy flag that we will not reveal coordinate information to this window.
1418 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
Jeff Brown9302c872011-07-13 22:51:29 -07001419 sp<InputWindowHandle> foregroundWindowHandle =
1420 mTempTouchState.getFirstForegroundWindowHandle();
Jeff Browncc4f7db2011-08-30 20:34:48 -07001421 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Kenny Root7a9db182011-06-02 15:16:05 -07001422 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1423 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1424 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
Jeff Brown9302c872011-07-13 22:51:29 -07001425 sp<InputWindowHandle> inputWindowHandle = touchedWindow.windowHandle;
Jeff Browncc4f7db2011-08-30 20:34:48 -07001426 if (inputWindowHandle->getInfo()->ownerUid != foregroundWindowUid) {
Jeff Brown9302c872011-07-13 22:51:29 -07001427 mTempTouchState.addOrUpdateWindow(inputWindowHandle,
Kenny Root7a9db182011-06-02 15:16:05 -07001428 InputTarget::FLAG_ZERO_COORDS, BitSet32(0));
1429 }
1430 }
1431 }
1432 }
1433
Jeff Brown01ce2e92010-09-26 22:20:12 -07001434 // Ensure all touched foreground windows are ready for new input.
1435 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1436 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1437 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1438 // If the touched window is paused then keep waiting.
Jeff Browncc4f7db2011-08-30 20:34:48 -07001439 if (touchedWindow.windowHandle->getInfo()->paused) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001440 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brown265f1cc2012-06-11 18:01:06 -07001441 NULL, touchedWindow.windowHandle, nextWakeupTime,
1442 "Waiting because the touched window is paused.");
Jeff Brown01ce2e92010-09-26 22:20:12 -07001443 goto Unresponsive;
1444 }
1445
1446 // If the touched window is still working on previous events then keep waiting.
Jeff Brown0952c302012-02-13 13:48:59 -08001447 if (!isWindowReadyForMoreInputLocked(currentTime, touchedWindow.windowHandle, entry)) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001448 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brown265f1cc2012-06-11 18:01:06 -07001449 NULL, touchedWindow.windowHandle, nextWakeupTime,
1450 "Waiting because the touched window has not finished "
1451 "processing the input events that were previously delivered to it.");
Jeff Brown01ce2e92010-09-26 22:20:12 -07001452 goto Unresponsive;
1453 }
1454 }
1455 }
1456
1457 // If this is the first pointer going down and the touched window has a wallpaper
1458 // then also add the touched wallpaper windows so they are locked in for the duration
1459 // of the touch gesture.
Jeff Brown33bbfd22011-02-24 20:55:35 -08001460 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
1461 // engine only supports touch events. We would need to add a mechanism similar
1462 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
1463 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
Jeff Brown9302c872011-07-13 22:51:29 -07001464 sp<InputWindowHandle> foregroundWindowHandle =
1465 mTempTouchState.getFirstForegroundWindowHandle();
Jeff Browncc4f7db2011-08-30 20:34:48 -07001466 if (foregroundWindowHandle->getInfo()->hasWallpaper) {
Jeff Brown9302c872011-07-13 22:51:29 -07001467 for (size_t i = 0; i < mWindowHandles.size(); i++) {
1468 sp<InputWindowHandle> windowHandle = mWindowHandles.itemAt(i);
Jeff Brown83d616a2012-09-09 20:33:43 -07001469 const InputWindowInfo* info = windowHandle->getInfo();
1470 if (info->displayId == displayId
1471 && windowHandle->getInfo()->layoutParamsType
1472 == InputWindowInfo::TYPE_WALLPAPER) {
Jeff Brown9302c872011-07-13 22:51:29 -07001473 mTempTouchState.addOrUpdateWindow(windowHandle,
Jeff Browna032cc02011-03-07 16:56:21 -08001474 InputTarget::FLAG_WINDOW_IS_OBSCURED
1475 | InputTarget::FLAG_DISPATCH_AS_IS,
1476 BitSet32(0));
Jeff Brown01ce2e92010-09-26 22:20:12 -07001477 }
1478 }
1479 }
1480 }
1481
Jeff Brownb88102f2010-09-08 11:49:43 -07001482 // Success! Output targets.
1483 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
Jeff Brownb88102f2010-09-08 11:49:43 -07001484
Jeff Brown01ce2e92010-09-26 22:20:12 -07001485 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1486 const TouchedWindow& touchedWindow = mTempTouchState.windows.itemAt(i);
Jeff Brown9302c872011-07-13 22:51:29 -07001487 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Jeff Browne9bb9be2012-02-06 15:47:55 -08001488 touchedWindow.pointerIds, inputTargets);
Jeff Brownb88102f2010-09-08 11:49:43 -07001489 }
1490
Jeff Browna032cc02011-03-07 16:56:21 -08001491 // Drop the outside or hover touch windows since we will not care about them
1492 // in the next iteration.
1493 mTempTouchState.filterNonAsIsTouchWindows();
Jeff Brown01ce2e92010-09-26 22:20:12 -07001494
Jeff Brownb88102f2010-09-08 11:49:43 -07001495Failed:
1496 // Check injection permission once and for all.
1497 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001498 if (checkInjectionPermission(NULL, entry->injectionState)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001499 injectionPermission = INJECTION_PERMISSION_GRANTED;
1500 } else {
1501 injectionPermission = INJECTION_PERMISSION_DENIED;
1502 }
1503 }
1504
1505 // Update final pieces of touch state if the injector had permission.
1506 if (injectionPermission == INJECTION_PERMISSION_GRANTED) {
Jeff Brown95712852011-01-04 19:41:59 -08001507 if (!wrongDevice) {
Jeff Brown81346812011-06-28 20:08:48 -07001508 if (switchedDevice) {
1509#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001510 ALOGD("Conflicting pointer actions: Switched to a different device.");
Jeff Brown81346812011-06-28 20:08:48 -07001511#endif
1512 *outConflictingPointerActions = true;
1513 }
1514
1515 if (isHoverAction) {
1516 // Started hovering, therefore no longer down.
1517 if (mTouchState.down) {
1518#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001519 ALOGD("Conflicting pointer actions: Hover received while pointer was down.");
Jeff Brown81346812011-06-28 20:08:48 -07001520#endif
1521 *outConflictingPointerActions = true;
1522 }
1523 mTouchState.reset();
1524 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER
1525 || maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
1526 mTouchState.deviceId = entry->deviceId;
1527 mTouchState.source = entry->source;
Jeff Brown83d616a2012-09-09 20:33:43 -07001528 mTouchState.displayId = displayId;
Jeff Brown81346812011-06-28 20:08:48 -07001529 }
1530 } else if (maskedAction == AMOTION_EVENT_ACTION_UP
1531 || maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Jeff Brown95712852011-01-04 19:41:59 -08001532 // All pointers up or canceled.
Jeff Brown33bbfd22011-02-24 20:55:35 -08001533 mTouchState.reset();
Jeff Brown95712852011-01-04 19:41:59 -08001534 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1535 // First pointer went down.
1536 if (mTouchState.down) {
Jeff Brownb6997262010-10-08 22:31:17 -07001537#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001538 ALOGD("Conflicting pointer actions: Down received while already down.");
Jeff Brownb6997262010-10-08 22:31:17 -07001539#endif
Jeff Brown81346812011-06-28 20:08:48 -07001540 *outConflictingPointerActions = true;
Jeff Brown95712852011-01-04 19:41:59 -08001541 }
Jeff Brown33bbfd22011-02-24 20:55:35 -08001542 mTouchState.copyFrom(mTempTouchState);
Jeff Brown95712852011-01-04 19:41:59 -08001543 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
1544 // One pointer went up.
1545 if (isSplit) {
1546 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07001547 uint32_t pointerId = entry->pointerProperties[pointerIndex].id;
Jeff Brownb88102f2010-09-08 11:49:43 -07001548
Jeff Brown95712852011-01-04 19:41:59 -08001549 for (size_t i = 0; i < mTempTouchState.windows.size(); ) {
1550 TouchedWindow& touchedWindow = mTempTouchState.windows.editItemAt(i);
1551 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
1552 touchedWindow.pointerIds.clearBit(pointerId);
1553 if (touchedWindow.pointerIds.isEmpty()) {
1554 mTempTouchState.windows.removeAt(i);
1555 continue;
1556 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001557 }
Jeff Brown95712852011-01-04 19:41:59 -08001558 i += 1;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001559 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001560 }
Jeff Brown33bbfd22011-02-24 20:55:35 -08001561 mTouchState.copyFrom(mTempTouchState);
1562 } else if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
1563 // Discard temporary touch state since it was only valid for this action.
1564 } else {
1565 // Save changes to touch state as-is for all other actions.
1566 mTouchState.copyFrom(mTempTouchState);
Jeff Brownb88102f2010-09-08 11:49:43 -07001567 }
Jeff Browna032cc02011-03-07 16:56:21 -08001568
1569 // Update hover state.
Jeff Brown9302c872011-07-13 22:51:29 -07001570 mLastHoverWindowHandle = newHoverWindowHandle;
Jeff Brown95712852011-01-04 19:41:59 -08001571 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001572 } else {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001573#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001574 ALOGD("Not updating touch focus because injection was denied.");
Jeff Brown01ce2e92010-09-26 22:20:12 -07001575#endif
Jeff Brownb88102f2010-09-08 11:49:43 -07001576 }
1577
1578Unresponsive:
Jeff Brown120a4592010-10-27 18:43:51 -07001579 // Reset temporary touch state to ensure we release unnecessary references to input channels.
1580 mTempTouchState.reset();
1581
Jeff Brown519e0242010-09-15 15:18:56 -07001582 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
1583 updateDispatchStatisticsLocked(currentTime, entry,
1584 injectionResult, timeSpentWaitingForApplication);
Jeff Brownb88102f2010-09-08 11:49:43 -07001585#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001586 ALOGD("findTouchedWindow finished: injectionResult=%d, injectionPermission=%d, "
Jeff Brown01ce2e92010-09-26 22:20:12 -07001587 "timeSpentWaitingForApplication=%0.1fms",
Jeff Brown519e0242010-09-15 15:18:56 -07001588 injectionResult, injectionPermission, timeSpentWaitingForApplication / 1000000.0);
Jeff Brownb88102f2010-09-08 11:49:43 -07001589#endif
1590 return injectionResult;
1591}
1592
Jeff Brown9302c872011-07-13 22:51:29 -07001593void InputDispatcher::addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
Jeff Browne9bb9be2012-02-06 15:47:55 -08001594 int32_t targetFlags, BitSet32 pointerIds, Vector<InputTarget>& inputTargets) {
1595 inputTargets.push();
Jeff Brownb88102f2010-09-08 11:49:43 -07001596
Jeff Browncc4f7db2011-08-30 20:34:48 -07001597 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Jeff Browne9bb9be2012-02-06 15:47:55 -08001598 InputTarget& target = inputTargets.editTop();
Jeff Browncc4f7db2011-08-30 20:34:48 -07001599 target.inputChannel = windowInfo->inputChannel;
Jeff Brownb88102f2010-09-08 11:49:43 -07001600 target.flags = targetFlags;
Jeff Browncc4f7db2011-08-30 20:34:48 -07001601 target.xOffset = - windowInfo->frameLeft;
1602 target.yOffset = - windowInfo->frameTop;
1603 target.scaleFactor = windowInfo->scaleFactor;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001604 target.pointerIds = pointerIds;
Jeff Brownb88102f2010-09-08 11:49:43 -07001605}
1606
Jeff Browne9bb9be2012-02-06 15:47:55 -08001607void InputDispatcher::addMonitoringTargetsLocked(Vector<InputTarget>& inputTargets) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001608 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
Jeff Browne9bb9be2012-02-06 15:47:55 -08001609 inputTargets.push();
Jeff Brownb88102f2010-09-08 11:49:43 -07001610
Jeff Browne9bb9be2012-02-06 15:47:55 -08001611 InputTarget& target = inputTargets.editTop();
Jeff Brownb88102f2010-09-08 11:49:43 -07001612 target.inputChannel = mMonitoringChannels[i];
Jeff Brownb6110c22011-04-01 16:15:13 -07001613 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
Jeff Brownb88102f2010-09-08 11:49:43 -07001614 target.xOffset = 0;
1615 target.yOffset = 0;
Jeff Brownb6110c22011-04-01 16:15:13 -07001616 target.pointerIds.clear();
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001617 target.scaleFactor = 1.0f;
Jeff Brownb88102f2010-09-08 11:49:43 -07001618 }
1619}
1620
Jeff Brown9302c872011-07-13 22:51:29 -07001621bool InputDispatcher::checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
Jeff Brown01ce2e92010-09-26 22:20:12 -07001622 const InjectionState* injectionState) {
1623 if (injectionState
Jeff Browncc4f7db2011-08-30 20:34:48 -07001624 && (windowHandle == NULL
1625 || windowHandle->getInfo()->ownerUid != injectionState->injectorUid)
Jeff Brownb6997262010-10-08 22:31:17 -07001626 && !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Jeff Brown9302c872011-07-13 22:51:29 -07001627 if (windowHandle != NULL) {
Steve Block8564c8d2012-01-05 23:22:43 +00001628 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
Jeff Brown9302c872011-07-13 22:51:29 -07001629 "owned by uid %d",
Jeff Brownb6997262010-10-08 22:31:17 -07001630 injectionState->injectorPid, injectionState->injectorUid,
Jeff Browncc4f7db2011-08-30 20:34:48 -07001631 windowHandle->getName().string(),
1632 windowHandle->getInfo()->ownerUid);
Jeff Brownb6997262010-10-08 22:31:17 -07001633 } else {
Steve Block8564c8d2012-01-05 23:22:43 +00001634 ALOGW("Permission denied: injecting event from pid %d uid %d",
Jeff Brownb6997262010-10-08 22:31:17 -07001635 injectionState->injectorPid, injectionState->injectorUid);
Jeff Brownb88102f2010-09-08 11:49:43 -07001636 }
Jeff Brownb6997262010-10-08 22:31:17 -07001637 return false;
Jeff Brownb88102f2010-09-08 11:49:43 -07001638 }
1639 return true;
1640}
1641
Jeff Brown19dfc832010-10-05 12:26:23 -07001642bool InputDispatcher::isWindowObscuredAtPointLocked(
Jeff Brown9302c872011-07-13 22:51:29 -07001643 const sp<InputWindowHandle>& windowHandle, int32_t x, int32_t y) const {
Jeff Brown83d616a2012-09-09 20:33:43 -07001644 int32_t displayId = windowHandle->getInfo()->displayId;
Jeff Brown9302c872011-07-13 22:51:29 -07001645 size_t numWindows = mWindowHandles.size();
Jeff Brownb88102f2010-09-08 11:49:43 -07001646 for (size_t i = 0; i < numWindows; i++) {
Jeff Brown9302c872011-07-13 22:51:29 -07001647 sp<InputWindowHandle> otherHandle = mWindowHandles.itemAt(i);
1648 if (otherHandle == windowHandle) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001649 break;
1650 }
Jeff Browncc4f7db2011-08-30 20:34:48 -07001651
1652 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Jeff Brown83d616a2012-09-09 20:33:43 -07001653 if (otherInfo->displayId == displayId
1654 && otherInfo->visible && !otherInfo->isTrustedOverlay()
Jeff Browncc4f7db2011-08-30 20:34:48 -07001655 && otherInfo->frameContainsPoint(x, y)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001656 return true;
1657 }
1658 }
1659 return false;
1660}
1661
Jeff Brownd1c48a02012-02-06 19:12:47 -08001662bool InputDispatcher::isWindowReadyForMoreInputLocked(nsecs_t currentTime,
Jeff Brown0952c302012-02-13 13:48:59 -08001663 const sp<InputWindowHandle>& windowHandle, const EventEntry* eventEntry) {
Jeff Browncc4f7db2011-08-30 20:34:48 -07001664 ssize_t connectionIndex = getConnectionIndexLocked(windowHandle->getInputChannel());
Jeff Brown519e0242010-09-15 15:18:56 -07001665 if (connectionIndex >= 0) {
Jeff Browncbee6d62012-02-03 20:11:27 -08001666 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
Jeff Brownd1c48a02012-02-06 19:12:47 -08001667 if (connection->inputPublisherBlocked) {
1668 return false;
1669 }
Jeff Brown0952c302012-02-13 13:48:59 -08001670 if (eventEntry->type == EventEntry::TYPE_KEY) {
1671 // If the event is a key event, then we must wait for all previous events to
1672 // complete before delivering it because previous events may have the
1673 // side-effect of transferring focus to a different window and we want to
1674 // ensure that the following keys are sent to the new window.
1675 //
1676 // Suppose the user touches a button in a window then immediately presses "A".
1677 // If the button causes a pop-up window to appear then we want to ensure that
1678 // the "A" key is delivered to the new pop-up window. This is because users
1679 // often anticipate pending UI changes when typing on a keyboard.
1680 // To obtain this behavior, we must serialize key events with respect to all
1681 // prior input events.
Jeff Brownd1c48a02012-02-06 19:12:47 -08001682 return connection->outboundQueue.isEmpty()
1683 && connection->waitQueue.isEmpty();
1684 }
Jeff Brown0952c302012-02-13 13:48:59 -08001685 // Touch events can always be sent to a window immediately because the user intended
1686 // to touch whatever was visible at the time. Even if focus changes or a new
1687 // window appears moments later, the touch event was meant to be delivered to
1688 // whatever window happened to be on screen at the time.
1689 //
1690 // Generic motion events, such as trackball or joystick events are a little trickier.
1691 // Like key events, generic motion events are delivered to the focused window.
1692 // Unlike key events, generic motion events don't tend to transfer focus to other
1693 // windows and it is not important for them to be serialized. So we prefer to deliver
1694 // generic motion events as soon as possible to improve efficiency and reduce lag
1695 // through batching.
1696 //
1697 // The one case where we pause input event delivery is when the wait queue is piling
1698 // up with lots of events because the application is not responding.
1699 // This condition ensures that ANRs are detected reliably.
Jeff Brownd1c48a02012-02-06 19:12:47 -08001700 if (!connection->waitQueue.isEmpty()
1701 && currentTime >= connection->waitQueue.head->eventEntry->eventTime
1702 + STREAM_AHEAD_EVENT_TIMEOUT) {
1703 return false;
1704 }
Jeff Brown519e0242010-09-15 15:18:56 -07001705 }
Jeff Brownd1c48a02012-02-06 19:12:47 -08001706 return true;
Jeff Brown519e0242010-09-15 15:18:56 -07001707}
1708
Jeff Brown9302c872011-07-13 22:51:29 -07001709String8 InputDispatcher::getApplicationWindowLabelLocked(
1710 const sp<InputApplicationHandle>& applicationHandle,
1711 const sp<InputWindowHandle>& windowHandle) {
1712 if (applicationHandle != NULL) {
1713 if (windowHandle != NULL) {
Jeff Browncc4f7db2011-08-30 20:34:48 -07001714 String8 label(applicationHandle->getName());
Jeff Brown519e0242010-09-15 15:18:56 -07001715 label.append(" - ");
Jeff Browncc4f7db2011-08-30 20:34:48 -07001716 label.append(windowHandle->getName());
Jeff Brown519e0242010-09-15 15:18:56 -07001717 return label;
1718 } else {
Jeff Browncc4f7db2011-08-30 20:34:48 -07001719 return applicationHandle->getName();
Jeff Brown519e0242010-09-15 15:18:56 -07001720 }
Jeff Brown9302c872011-07-13 22:51:29 -07001721 } else if (windowHandle != NULL) {
Jeff Browncc4f7db2011-08-30 20:34:48 -07001722 return windowHandle->getName();
Jeff Brown519e0242010-09-15 15:18:56 -07001723 } else {
1724 return String8("<unknown application or window>");
1725 }
1726}
1727
Jeff Browne2fe69e2010-10-18 13:21:23 -07001728void InputDispatcher::pokeUserActivityLocked(const EventEntry* eventEntry) {
Jeff Brown1e3b98d2012-09-30 18:58:59 -07001729 if (mFocusedWindowHandle != NULL) {
1730 const InputWindowInfo* info = mFocusedWindowHandle->getInfo();
1731 if (info->inputFeatures & InputWindowInfo::INPUT_FEATURE_DISABLE_USER_ACTIVITY) {
1732#if DEBUG_DISPATCH_CYCLE
1733 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.string());
1734#endif
1735 return;
1736 }
1737 }
1738
Jeff Brownb696de52012-07-27 15:38:50 -07001739 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Jeff Brown4d396052010-10-29 21:50:21 -07001740 switch (eventEntry->type) {
1741 case EventEntry::TYPE_MOTION: {
Jeff Browne2fe69e2010-10-18 13:21:23 -07001742 const MotionEntry* motionEntry = static_cast<const MotionEntry*>(eventEntry);
Jeff Brown4d396052010-10-29 21:50:21 -07001743 if (motionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
1744 return;
1745 }
1746
Jeff Brown56194eb2011-03-02 19:23:13 -08001747 if (MotionEvent::isTouchEvent(motionEntry->source, motionEntry->action)) {
Jeff Brownb696de52012-07-27 15:38:50 -07001748 eventType = USER_ACTIVITY_EVENT_TOUCH;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001749 }
Jeff Brown4d396052010-10-29 21:50:21 -07001750 break;
1751 }
1752 case EventEntry::TYPE_KEY: {
1753 const KeyEntry* keyEntry = static_cast<const KeyEntry*>(eventEntry);
1754 if (keyEntry->flags & AKEY_EVENT_FLAG_CANCELED) {
1755 return;
1756 }
Jeff Brownb696de52012-07-27 15:38:50 -07001757 eventType = USER_ACTIVITY_EVENT_BUTTON;
Jeff Brown4d396052010-10-29 21:50:21 -07001758 break;
1759 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001760 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001761
Jeff Brownb88102f2010-09-08 11:49:43 -07001762 CommandEntry* commandEntry = postCommandLocked(
1763 & InputDispatcher::doPokeUserActivityLockedInterruptible);
Jeff Browne2fe69e2010-10-18 13:21:23 -07001764 commandEntry->eventTime = eventEntry->eventTime;
Jeff Brownb88102f2010-09-08 11:49:43 -07001765 commandEntry->userActivityEventType = eventType;
1766}
1767
Jeff Brown7fbdc842010-06-17 20:52:56 -07001768void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001769 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07001770#if DEBUG_DISPATCH_CYCLE
Steve Block5baa3a62011-12-20 16:23:08 +00001771 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
Jeff Brown9cc695c2011-08-23 18:35:04 -07001772 "xOffset=%f, yOffset=%f, scaleFactor=%f, "
Jeff Brown3241b6b2012-02-03 15:08:02 -08001773 "pointerIds=0x%x",
Jeff Brown519e0242010-09-15 15:18:56 -07001774 connection->getInputChannelName(), inputTarget->flags,
Jeff Brown46b9ac02010-04-22 18:58:52 -07001775 inputTarget->xOffset, inputTarget->yOffset,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001776 inputTarget->scaleFactor, inputTarget->pointerIds.value);
Jeff Brown46b9ac02010-04-22 18:58:52 -07001777#endif
1778
1779 // Skip this event if the connection status is not normal.
Jeff Brown519e0242010-09-15 15:18:56 -07001780 // We don't want to enqueue additional outbound events if the connection is broken.
Jeff Brown46b9ac02010-04-22 18:58:52 -07001781 if (connection->status != Connection::STATUS_NORMAL) {
Jeff Brownb6997262010-10-08 22:31:17 -07001782#if DEBUG_DISPATCH_CYCLE
Steve Block5baa3a62011-12-20 16:23:08 +00001783 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Jeff Brownb88102f2010-09-08 11:49:43 -07001784 connection->getInputChannelName(), connection->getStatusLabel());
Jeff Brownb6997262010-10-08 22:31:17 -07001785#endif
Jeff Brown46b9ac02010-04-22 18:58:52 -07001786 return;
1787 }
1788
Jeff Brown01ce2e92010-09-26 22:20:12 -07001789 // Split a motion event if needed.
Jeff Brown3241b6b2012-02-03 15:08:02 -08001790 if (inputTarget->flags & InputTarget::FLAG_SPLIT) {
Steve Blockec193de2012-01-09 18:35:44 +00001791 ALOG_ASSERT(eventEntry->type == EventEntry::TYPE_MOTION);
Jeff Brown01ce2e92010-09-26 22:20:12 -07001792
1793 MotionEntry* originalMotionEntry = static_cast<MotionEntry*>(eventEntry);
1794 if (inputTarget->pointerIds.count() != originalMotionEntry->pointerCount) {
1795 MotionEntry* splitMotionEntry = splitMotionEvent(
1796 originalMotionEntry, inputTarget->pointerIds);
Jeff Brown58a2da82011-01-25 16:02:22 -08001797 if (!splitMotionEntry) {
1798 return; // split event was dropped
1799 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001800#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001801 ALOGD("channel '%s' ~ Split motion event.",
Jeff Brown01ce2e92010-09-26 22:20:12 -07001802 connection->getInputChannelName());
1803 logOutboundMotionDetailsLocked(" ", splitMotionEntry);
1804#endif
Jeff Brownc0cb3dc2012-01-12 18:30:12 -08001805 enqueueDispatchEntriesLocked(currentTime, connection,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001806 splitMotionEntry, inputTarget);
Jeff Brownc0cb3dc2012-01-12 18:30:12 -08001807 splitMotionEntry->release();
1808 return;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001809 }
1810 }
1811
Jeff Brownc0cb3dc2012-01-12 18:30:12 -08001812 // Not splitting. Enqueue dispatch entries for the event as is.
Jeff Brown3241b6b2012-02-03 15:08:02 -08001813 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
Jeff Brownc0cb3dc2012-01-12 18:30:12 -08001814}
1815
1816void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001817 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07001818 bool wasEmpty = connection->outboundQueue.isEmpty();
1819
Jeff Browna032cc02011-03-07 16:56:21 -08001820 // Enqueue dispatch entries for the requested modes.
1821 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001822 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
Jeff Browna032cc02011-03-07 16:56:21 -08001823 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001824 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
Jeff Browna032cc02011-03-07 16:56:21 -08001825 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001826 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
Jeff Browna032cc02011-03-07 16:56:21 -08001827 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001828 InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brown98db5fa2011-06-08 15:37:10 -07001829 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001830 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
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_ENTER);
Jeff Browna032cc02011-03-07 16:56:21 -08001833
1834 // If the outbound queue was previously empty, start the dispatch cycle going.
Jeff Brownb6110c22011-04-01 16:15:13 -07001835 if (wasEmpty && !connection->outboundQueue.isEmpty()) {
Jeff Browna032cc02011-03-07 16:56:21 -08001836 startDispatchCycleLocked(currentTime, connection);
1837 }
1838}
1839
1840void InputDispatcher::enqueueDispatchEntryLocked(
1841 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001842 int32_t dispatchMode) {
Jeff Browna032cc02011-03-07 16:56:21 -08001843 int32_t inputTargetFlags = inputTarget->flags;
1844 if (!(inputTargetFlags & dispatchMode)) {
1845 return;
1846 }
1847 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
1848
Jeff Brown46b9ac02010-04-22 18:58:52 -07001849 // This is a new event.
1850 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Jeff Brownac386072011-07-20 15:19:50 -07001851 DispatchEntry* dispatchEntry = new DispatchEntry(eventEntry, // increments ref
Dianne Hackbornaa9d84c2011-05-09 19:00:59 -07001852 inputTargetFlags, inputTarget->xOffset, inputTarget->yOffset,
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001853 inputTarget->scaleFactor);
Jeff Brown6ec402b2010-07-28 15:48:59 -07001854
Jeff Brown81346812011-06-28 20:08:48 -07001855 // Apply target flags and update the connection's input state.
1856 switch (eventEntry->type) {
1857 case EventEntry::TYPE_KEY: {
1858 KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
1859 dispatchEntry->resolvedAction = keyEntry->action;
1860 dispatchEntry->resolvedFlags = keyEntry->flags;
1861
1862 if (!connection->inputState.trackKey(keyEntry,
1863 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags)) {
1864#if DEBUG_DISPATCH_CYCLE
Steve Block5baa3a62011-12-20 16:23:08 +00001865 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
Jeff Brown81346812011-06-28 20:08:48 -07001866 connection->getInputChannelName());
1867#endif
Jeff Brownc0cb3dc2012-01-12 18:30:12 -08001868 delete dispatchEntry;
Jeff Brown81346812011-06-28 20:08:48 -07001869 return; // skip the inconsistent event
1870 }
1871 break;
1872 }
1873
1874 case EventEntry::TYPE_MOTION: {
1875 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
1876 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
1877 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
1878 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
1879 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
1880 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
1881 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
1882 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
1883 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
1884 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
1885 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
1886 } else {
1887 dispatchEntry->resolvedAction = motionEntry->action;
1888 }
1889 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE
1890 && !connection->inputState.isHovering(
Jeff Brown83d616a2012-09-09 20:33:43 -07001891 motionEntry->deviceId, motionEntry->source, motionEntry->displayId)) {
Jeff Brown81346812011-06-28 20:08:48 -07001892#if DEBUG_DISPATCH_CYCLE
Steve Block5baa3a62011-12-20 16:23:08 +00001893 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter event",
Jeff Brown81346812011-06-28 20:08:48 -07001894 connection->getInputChannelName());
1895#endif
1896 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
1897 }
1898
1899 dispatchEntry->resolvedFlags = motionEntry->flags;
1900 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
1901 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
1902 }
1903
1904 if (!connection->inputState.trackMotion(motionEntry,
1905 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags)) {
1906#if DEBUG_DISPATCH_CYCLE
Steve Block5baa3a62011-12-20 16:23:08 +00001907 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion event",
Jeff Brown81346812011-06-28 20:08:48 -07001908 connection->getInputChannelName());
1909#endif
Jeff Brownc0cb3dc2012-01-12 18:30:12 -08001910 delete dispatchEntry;
Jeff Brown81346812011-06-28 20:08:48 -07001911 return; // skip the inconsistent event
1912 }
1913 break;
1914 }
1915 }
1916
Jeff Brownc0cb3dc2012-01-12 18:30:12 -08001917 // Remember that we are waiting for this dispatch to complete.
1918 if (dispatchEntry->hasForegroundTarget()) {
1919 incrementPendingForegroundDispatchesLocked(eventEntry);
1920 }
1921
Jeff Brown46b9ac02010-04-22 18:58:52 -07001922 // Enqueue the dispatch entry.
1923 connection->outboundQueue.enqueueAtTail(dispatchEntry);
Jeff Brown481c1572012-03-09 14:41:15 -08001924 traceOutboundQueueLengthLocked(connection);
Jeff Brown46b9ac02010-04-22 18:58:52 -07001925}
1926
Jeff Brown7fbdc842010-06-17 20:52:56 -07001927void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Jeff Brown519e0242010-09-15 15:18:56 -07001928 const sp<Connection>& connection) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07001929#if DEBUG_DISPATCH_CYCLE
Steve Block5baa3a62011-12-20 16:23:08 +00001930 ALOGD("channel '%s' ~ startDispatchCycle",
Jeff Brown46b9ac02010-04-22 18:58:52 -07001931 connection->getInputChannelName());
1932#endif
1933
Jeff Brownd1c48a02012-02-06 19:12:47 -08001934 while (connection->status == Connection::STATUS_NORMAL
1935 && !connection->outboundQueue.isEmpty()) {
1936 DispatchEntry* dispatchEntry = connection->outboundQueue.head;
Jeff Brown265f1cc2012-06-11 18:01:06 -07001937 dispatchEntry->deliveryTime = currentTime;
Jeff Brown46b9ac02010-04-22 18:58:52 -07001938
Jeff Brownd1c48a02012-02-06 19:12:47 -08001939 // Publish the event.
1940 status_t status;
1941 EventEntry* eventEntry = dispatchEntry->eventEntry;
1942 switch (eventEntry->type) {
1943 case EventEntry::TYPE_KEY: {
1944 KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
Jeff Brown46b9ac02010-04-22 18:58:52 -07001945
Jeff Brownd1c48a02012-02-06 19:12:47 -08001946 // Publish the key event.
Jeff Brown072ec962012-02-07 14:46:57 -08001947 status = connection->inputPublisher.publishKeyEvent(dispatchEntry->seq,
Jeff Brownd1c48a02012-02-06 19:12:47 -08001948 keyEntry->deviceId, keyEntry->source,
1949 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags,
1950 keyEntry->keyCode, keyEntry->scanCode,
1951 keyEntry->metaState, keyEntry->repeatCount, keyEntry->downTime,
1952 keyEntry->eventTime);
1953 break;
1954 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001955
Jeff Brownd1c48a02012-02-06 19:12:47 -08001956 case EventEntry::TYPE_MOTION: {
1957 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
Jeff Brown46b9ac02010-04-22 18:58:52 -07001958
Jeff Brownd1c48a02012-02-06 19:12:47 -08001959 PointerCoords scaledCoords[MAX_POINTERS];
1960 const PointerCoords* usingCoords = motionEntry->pointerCoords;
Jeff Brown46b9ac02010-04-22 18:58:52 -07001961
Jeff Brownd1c48a02012-02-06 19:12:47 -08001962 // Set the X and Y offset depending on the input source.
1963 float xOffset, yOffset, scaleFactor;
1964 if ((motionEntry->source & AINPUT_SOURCE_CLASS_POINTER)
1965 && !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
1966 scaleFactor = dispatchEntry->scaleFactor;
1967 xOffset = dispatchEntry->xOffset * scaleFactor;
1968 yOffset = dispatchEntry->yOffset * scaleFactor;
1969 if (scaleFactor != 1.0f) {
1970 for (size_t i = 0; i < motionEntry->pointerCount; i++) {
1971 scaledCoords[i] = motionEntry->pointerCoords[i];
1972 scaledCoords[i].scale(scaleFactor);
1973 }
1974 usingCoords = scaledCoords;
1975 }
1976 } else {
1977 xOffset = 0.0f;
1978 yOffset = 0.0f;
1979 scaleFactor = 1.0f;
1980
1981 // We don't want the dispatch target to know.
1982 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
1983 for (size_t i = 0; i < motionEntry->pointerCount; i++) {
1984 scaledCoords[i].clear();
1985 }
1986 usingCoords = scaledCoords;
1987 }
1988 }
1989
1990 // Publish the motion event.
Jeff Brown072ec962012-02-07 14:46:57 -08001991 status = connection->inputPublisher.publishMotionEvent(dispatchEntry->seq,
Jeff Brownd1c48a02012-02-06 19:12:47 -08001992 motionEntry->deviceId, motionEntry->source,
1993 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags,
1994 motionEntry->edgeFlags, motionEntry->metaState, motionEntry->buttonState,
1995 xOffset, yOffset,
1996 motionEntry->xPrecision, motionEntry->yPrecision,
1997 motionEntry->downTime, motionEntry->eventTime,
1998 motionEntry->pointerCount, motionEntry->pointerProperties,
1999 usingCoords);
2000 break;
2001 }
2002
2003 default:
2004 ALOG_ASSERT(false);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002005 return;
2006 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002007
Jeff Brownd1c48a02012-02-06 19:12:47 -08002008 // Check the result.
Jeff Brown46b9ac02010-04-22 18:58:52 -07002009 if (status) {
Jeff Brownd1c48a02012-02-06 19:12:47 -08002010 if (status == WOULD_BLOCK) {
2011 if (connection->waitQueue.isEmpty()) {
2012 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
2013 "This is unexpected because the wait queue is empty, so the pipe "
2014 "should be empty and we shouldn't have any problems writing an "
2015 "event to it, status=%d", connection->getInputChannelName(), status);
2016 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2017 } else {
2018 // Pipe is full and we are waiting for the app to finish process some events
2019 // before sending more events to it.
2020#if DEBUG_DISPATCH_CYCLE
2021 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
2022 "waiting for the application to catch up",
2023 connection->getInputChannelName());
2024#endif
2025 connection->inputPublisherBlocked = true;
2026 }
2027 } else {
2028 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
2029 "status=%d", connection->getInputChannelName(), status);
2030 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2031 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002032 return;
2033 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002034
Jeff Brownd1c48a02012-02-06 19:12:47 -08002035 // Re-enqueue the event on the wait queue.
2036 connection->outboundQueue.dequeue(dispatchEntry);
Jeff Brown481c1572012-03-09 14:41:15 -08002037 traceOutboundQueueLengthLocked(connection);
Jeff Brownd1c48a02012-02-06 19:12:47 -08002038 connection->waitQueue.enqueueAtTail(dispatchEntry);
Jeff Brown481c1572012-03-09 14:41:15 -08002039 traceWaitQueueLengthLocked(connection);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002040 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002041}
2042
Jeff Brown7fbdc842010-06-17 20:52:56 -07002043void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Jeff Brown072ec962012-02-07 14:46:57 -08002044 const sp<Connection>& connection, uint32_t seq, bool handled) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002045#if DEBUG_DISPATCH_CYCLE
Jeff Brown072ec962012-02-07 14:46:57 -08002046 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
2047 connection->getInputChannelName(), seq, toString(handled));
Jeff Brown46b9ac02010-04-22 18:58:52 -07002048#endif
2049
Jeff Brownd1c48a02012-02-06 19:12:47 -08002050 connection->inputPublisherBlocked = false;
2051
Jeff Brown9c3cda02010-06-15 01:31:58 -07002052 if (connection->status == Connection::STATUS_BROKEN
2053 || connection->status == Connection::STATUS_ZOMBIE) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002054 return;
2055 }
2056
Jeff Brown3915bb82010-11-05 15:02:16 -07002057 // Notify other system components and prepare to start the next dispatch cycle.
Jeff Brown072ec962012-02-07 14:46:57 -08002058 onDispatchCycleFinishedLocked(currentTime, connection, seq, handled);
Jeff Brownb88102f2010-09-08 11:49:43 -07002059}
2060
Jeff Brownb6997262010-10-08 22:31:17 -07002061void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Jeff Browncc4f7db2011-08-30 20:34:48 -07002062 const sp<Connection>& connection, bool notify) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002063#if DEBUG_DISPATCH_CYCLE
Steve Block5baa3a62011-12-20 16:23:08 +00002064 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
Jeff Browncc4f7db2011-08-30 20:34:48 -07002065 connection->getInputChannelName(), toString(notify));
Jeff Brown46b9ac02010-04-22 18:58:52 -07002066#endif
2067
Jeff Brownd1c48a02012-02-06 19:12:47 -08002068 // Clear the dispatch queues.
2069 drainDispatchQueueLocked(&connection->outboundQueue);
Jeff Brown481c1572012-03-09 14:41:15 -08002070 traceOutboundQueueLengthLocked(connection);
Jeff Brownd1c48a02012-02-06 19:12:47 -08002071 drainDispatchQueueLocked(&connection->waitQueue);
Jeff Brown481c1572012-03-09 14:41:15 -08002072 traceWaitQueueLengthLocked(connection);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002073
Jeff Brownb6997262010-10-08 22:31:17 -07002074 // The connection appears to be unrecoverably broken.
Jeff Brown9c3cda02010-06-15 01:31:58 -07002075 // Ignore already broken or zombie connections.
Jeff Brownb6997262010-10-08 22:31:17 -07002076 if (connection->status == Connection::STATUS_NORMAL) {
2077 connection->status = Connection::STATUS_BROKEN;
Jeff Brown46b9ac02010-04-22 18:58:52 -07002078
Jeff Browncc4f7db2011-08-30 20:34:48 -07002079 if (notify) {
2080 // Notify other system components.
2081 onDispatchCycleBrokenLocked(currentTime, connection);
2082 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002083 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002084}
2085
Jeff Brownd1c48a02012-02-06 19:12:47 -08002086void InputDispatcher::drainDispatchQueueLocked(Queue<DispatchEntry>* queue) {
2087 while (!queue->isEmpty()) {
2088 DispatchEntry* dispatchEntry = queue->dequeueAtHead();
2089 releaseDispatchEntryLocked(dispatchEntry);
Jeff Brownb88102f2010-09-08 11:49:43 -07002090 }
Jeff Brownb88102f2010-09-08 11:49:43 -07002091}
2092
Jeff Brownd1c48a02012-02-06 19:12:47 -08002093void InputDispatcher::releaseDispatchEntryLocked(DispatchEntry* dispatchEntry) {
2094 if (dispatchEntry->hasForegroundTarget()) {
2095 decrementPendingForegroundDispatchesLocked(dispatchEntry->eventEntry);
2096 }
2097 delete dispatchEntry;
2098}
2099
Jeff Browncbee6d62012-02-03 20:11:27 -08002100int InputDispatcher::handleReceiveCallback(int fd, int events, void* data) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002101 InputDispatcher* d = static_cast<InputDispatcher*>(data);
2102
2103 { // acquire lock
2104 AutoMutex _l(d->mLock);
2105
Jeff Browncbee6d62012-02-03 20:11:27 -08002106 ssize_t connectionIndex = d->mConnectionsByFd.indexOfKey(fd);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002107 if (connectionIndex < 0) {
Steve Block3762c312012-01-06 19:20:56 +00002108 ALOGE("Received spurious receive callback for unknown input channel. "
Jeff Browncbee6d62012-02-03 20:11:27 -08002109 "fd=%d, events=0x%x", fd, events);
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002110 return 0; // remove the callback
Jeff Brown46b9ac02010-04-22 18:58:52 -07002111 }
2112
Jeff Browncc4f7db2011-08-30 20:34:48 -07002113 bool notify;
Jeff Browncbee6d62012-02-03 20:11:27 -08002114 sp<Connection> connection = d->mConnectionsByFd.valueAt(connectionIndex);
Jeff Browncc4f7db2011-08-30 20:34:48 -07002115 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
2116 if (!(events & ALOOPER_EVENT_INPUT)) {
Steve Block8564c8d2012-01-05 23:22:43 +00002117 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
Jeff Browncc4f7db2011-08-30 20:34:48 -07002118 "events=0x%x", connection->getInputChannelName(), events);
2119 return 1;
2120 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002121
Jeff Brown1adee112012-02-07 10:25:41 -08002122 nsecs_t currentTime = now();
2123 bool gotOne = false;
2124 status_t status;
2125 for (;;) {
Jeff Brown072ec962012-02-07 14:46:57 -08002126 uint32_t seq;
2127 bool handled;
2128 status = connection->inputPublisher.receiveFinishedSignal(&seq, &handled);
Jeff Brown1adee112012-02-07 10:25:41 -08002129 if (status) {
2130 break;
2131 }
Jeff Brown072ec962012-02-07 14:46:57 -08002132 d->finishDispatchCycleLocked(currentTime, connection, seq, handled);
Jeff Brown1adee112012-02-07 10:25:41 -08002133 gotOne = true;
2134 }
2135 if (gotOne) {
Jeff Browncc4f7db2011-08-30 20:34:48 -07002136 d->runCommandsLockedInterruptible();
Jeff Brown1adee112012-02-07 10:25:41 -08002137 if (status == WOULD_BLOCK) {
2138 return 1;
2139 }
Jeff Browncc4f7db2011-08-30 20:34:48 -07002140 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002141
Jeff Brown1adee112012-02-07 10:25:41 -08002142 notify = status != DEAD_OBJECT || !connection->monitor;
2143 if (notify) {
2144 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
2145 connection->getInputChannelName(), status);
2146 }
Jeff Browncc4f7db2011-08-30 20:34:48 -07002147 } else {
2148 // Monitor channels are never explicitly unregistered.
2149 // We do it automatically when the remote endpoint is closed so don't warn
2150 // about them.
2151 notify = !connection->monitor;
2152 if (notify) {
Steve Block8564c8d2012-01-05 23:22:43 +00002153 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. "
Jeff Browncc4f7db2011-08-30 20:34:48 -07002154 "events=0x%x", connection->getInputChannelName(), events);
2155 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002156 }
2157
Jeff Browncc4f7db2011-08-30 20:34:48 -07002158 // Unregister the channel.
2159 d->unregisterInputChannelLocked(connection->inputChannel, notify);
2160 return 0; // remove the callback
Jeff Brown46b9ac02010-04-22 18:58:52 -07002161 } // release lock
2162}
2163
Jeff Brownb6997262010-10-08 22:31:17 -07002164void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Jeff Brownda3d5a92011-03-29 15:11:34 -07002165 const CancelationOptions& options) {
Jeff Browncbee6d62012-02-03 20:11:27 -08002166 for (size_t i = 0; i < mConnectionsByFd.size(); i++) {
Jeff Brownb6997262010-10-08 22:31:17 -07002167 synthesizeCancelationEventsForConnectionLocked(
Jeff Browncbee6d62012-02-03 20:11:27 -08002168 mConnectionsByFd.valueAt(i), options);
Jeff Brownb6997262010-10-08 22:31:17 -07002169 }
2170}
2171
2172void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Jeff Brownda3d5a92011-03-29 15:11:34 -07002173 const sp<InputChannel>& channel, const CancelationOptions& options) {
Jeff Brownb6997262010-10-08 22:31:17 -07002174 ssize_t index = getConnectionIndexLocked(channel);
2175 if (index >= 0) {
2176 synthesizeCancelationEventsForConnectionLocked(
Jeff Browncbee6d62012-02-03 20:11:27 -08002177 mConnectionsByFd.valueAt(index), options);
Jeff Brownb6997262010-10-08 22:31:17 -07002178 }
2179}
2180
2181void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
Jeff Brownda3d5a92011-03-29 15:11:34 -07002182 const sp<Connection>& connection, const CancelationOptions& options) {
Jeff Brownc0cb3dc2012-01-12 18:30:12 -08002183 if (connection->status == Connection::STATUS_BROKEN) {
2184 return;
2185 }
2186
Jeff Brownb6997262010-10-08 22:31:17 -07002187 nsecs_t currentTime = now();
2188
Jeff Brown8b4be5602012-02-06 16:31:05 -08002189 Vector<EventEntry*> cancelationEvents;
Jeff Brownac386072011-07-20 15:19:50 -07002190 connection->inputState.synthesizeCancelationEvents(currentTime,
Jeff Brown8b4be5602012-02-06 16:31:05 -08002191 cancelationEvents, options);
Jeff Brownb6997262010-10-08 22:31:17 -07002192
Jeff Brown8b4be5602012-02-06 16:31:05 -08002193 if (!cancelationEvents.isEmpty()) {
Jeff Brownb6997262010-10-08 22:31:17 -07002194#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00002195 ALOGD("channel '%s' ~ Synthesized %d cancelation events to bring channel back in sync "
Jeff Brownda3d5a92011-03-29 15:11:34 -07002196 "with reality: %s, mode=%d.",
Jeff Brown8b4be5602012-02-06 16:31:05 -08002197 connection->getInputChannelName(), cancelationEvents.size(),
Jeff Brownda3d5a92011-03-29 15:11:34 -07002198 options.reason, options.mode);
Jeff Brownb6997262010-10-08 22:31:17 -07002199#endif
Jeff Brown8b4be5602012-02-06 16:31:05 -08002200 for (size_t i = 0; i < cancelationEvents.size(); i++) {
2201 EventEntry* cancelationEventEntry = cancelationEvents.itemAt(i);
Jeff Brownb6997262010-10-08 22:31:17 -07002202 switch (cancelationEventEntry->type) {
2203 case EventEntry::TYPE_KEY:
2204 logOutboundKeyDetailsLocked("cancel - ",
2205 static_cast<KeyEntry*>(cancelationEventEntry));
2206 break;
2207 case EventEntry::TYPE_MOTION:
2208 logOutboundMotionDetailsLocked("cancel - ",
2209 static_cast<MotionEntry*>(cancelationEventEntry));
2210 break;
2211 }
2212
Jeff Brown81346812011-06-28 20:08:48 -07002213 InputTarget target;
Jeff Brown9302c872011-07-13 22:51:29 -07002214 sp<InputWindowHandle> windowHandle = getWindowHandleLocked(connection->inputChannel);
2215 if (windowHandle != NULL) {
Jeff Browncc4f7db2011-08-30 20:34:48 -07002216 const InputWindowInfo* windowInfo = windowHandle->getInfo();
2217 target.xOffset = -windowInfo->frameLeft;
2218 target.yOffset = -windowInfo->frameTop;
2219 target.scaleFactor = windowInfo->scaleFactor;
Jeff Brownb6997262010-10-08 22:31:17 -07002220 } else {
Jeff Brown81346812011-06-28 20:08:48 -07002221 target.xOffset = 0;
2222 target.yOffset = 0;
2223 target.scaleFactor = 1.0f;
Jeff Brownb6997262010-10-08 22:31:17 -07002224 }
Jeff Brown81346812011-06-28 20:08:48 -07002225 target.inputChannel = connection->inputChannel;
2226 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
Jeff Brownb6997262010-10-08 22:31:17 -07002227
Jeff Brown81346812011-06-28 20:08:48 -07002228 enqueueDispatchEntryLocked(connection, cancelationEventEntry, // increments ref
Jeff Brown3241b6b2012-02-03 15:08:02 -08002229 &target, InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brownb6997262010-10-08 22:31:17 -07002230
Jeff Brownac386072011-07-20 15:19:50 -07002231 cancelationEventEntry->release();
Jeff Brownb6997262010-10-08 22:31:17 -07002232 }
2233
Jeff Brownd1c48a02012-02-06 19:12:47 -08002234 startDispatchCycleLocked(currentTime, connection);
Jeff Brownb6997262010-10-08 22:31:17 -07002235 }
2236}
2237
Jeff Brown01ce2e92010-09-26 22:20:12 -07002238InputDispatcher::MotionEntry*
2239InputDispatcher::splitMotionEvent(const MotionEntry* originalMotionEntry, BitSet32 pointerIds) {
Steve Blockec193de2012-01-09 18:35:44 +00002240 ALOG_ASSERT(pointerIds.value != 0);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002241
2242 uint32_t splitPointerIndexMap[MAX_POINTERS];
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002243 PointerProperties splitPointerProperties[MAX_POINTERS];
Jeff Brown01ce2e92010-09-26 22:20:12 -07002244 PointerCoords splitPointerCoords[MAX_POINTERS];
2245
2246 uint32_t originalPointerCount = originalMotionEntry->pointerCount;
2247 uint32_t splitPointerCount = 0;
2248
2249 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
2250 originalPointerIndex++) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002251 const PointerProperties& pointerProperties =
2252 originalMotionEntry->pointerProperties[originalPointerIndex];
2253 uint32_t pointerId = uint32_t(pointerProperties.id);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002254 if (pointerIds.hasBit(pointerId)) {
2255 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002256 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
Jeff Brownace13b12011-03-09 17:39:48 -08002257 splitPointerCoords[splitPointerCount].copyFrom(
Jeff Brown3241b6b2012-02-03 15:08:02 -08002258 originalMotionEntry->pointerCoords[originalPointerIndex]);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002259 splitPointerCount += 1;
2260 }
2261 }
Jeff Brown58a2da82011-01-25 16:02:22 -08002262
2263 if (splitPointerCount != pointerIds.count()) {
2264 // This is bad. We are missing some of the pointers that we expected to deliver.
2265 // Most likely this indicates that we received an ACTION_MOVE events that has
2266 // different pointer ids than we expected based on the previous ACTION_DOWN
2267 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
2268 // in this way.
Steve Block8564c8d2012-01-05 23:22:43 +00002269 ALOGW("Dropping split motion event because the pointer count is %d but "
Jeff Brown58a2da82011-01-25 16:02:22 -08002270 "we expected there to be %d pointers. This probably means we received "
2271 "a broken sequence of pointer ids from the input device.",
2272 splitPointerCount, pointerIds.count());
2273 return NULL;
2274 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07002275
2276 int32_t action = originalMotionEntry->action;
2277 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
2278 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
2279 || maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2280 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002281 const PointerProperties& pointerProperties =
2282 originalMotionEntry->pointerProperties[originalPointerIndex];
2283 uint32_t pointerId = uint32_t(pointerProperties.id);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002284 if (pointerIds.hasBit(pointerId)) {
2285 if (pointerIds.count() == 1) {
2286 // The first/last pointer went down/up.
2287 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
2288 ? AMOTION_EVENT_ACTION_DOWN : AMOTION_EVENT_ACTION_UP;
Jeff Brown9a01d052010-09-27 16:35:11 -07002289 } else {
2290 // A secondary pointer went down/up.
2291 uint32_t splitPointerIndex = 0;
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002292 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
Jeff Brown9a01d052010-09-27 16:35:11 -07002293 splitPointerIndex += 1;
2294 }
2295 action = maskedAction | (splitPointerIndex
2296 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002297 }
2298 } else {
2299 // An unrelated pointer changed.
2300 action = AMOTION_EVENT_ACTION_MOVE;
2301 }
2302 }
2303
Jeff Brownac386072011-07-20 15:19:50 -07002304 MotionEntry* splitMotionEntry = new MotionEntry(
Jeff Brown01ce2e92010-09-26 22:20:12 -07002305 originalMotionEntry->eventTime,
2306 originalMotionEntry->deviceId,
2307 originalMotionEntry->source,
2308 originalMotionEntry->policyFlags,
2309 action,
2310 originalMotionEntry->flags,
2311 originalMotionEntry->metaState,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002312 originalMotionEntry->buttonState,
Jeff Brown01ce2e92010-09-26 22:20:12 -07002313 originalMotionEntry->edgeFlags,
2314 originalMotionEntry->xPrecision,
2315 originalMotionEntry->yPrecision,
2316 originalMotionEntry->downTime,
Jeff Brown83d616a2012-09-09 20:33:43 -07002317 originalMotionEntry->displayId,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002318 splitPointerCount, splitPointerProperties, splitPointerCoords);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002319
Jeff Browna032cc02011-03-07 16:56:21 -08002320 if (originalMotionEntry->injectionState) {
2321 splitMotionEntry->injectionState = originalMotionEntry->injectionState;
2322 splitMotionEntry->injectionState->refCount += 1;
2323 }
2324
Jeff Brown01ce2e92010-09-26 22:20:12 -07002325 return splitMotionEntry;
2326}
2327
Jeff Brownbe1aa822011-07-27 16:04:54 -07002328void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002329#if DEBUG_INBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00002330 ALOGD("notifyConfigurationChanged - eventTime=%lld", args->eventTime);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002331#endif
2332
Jeff Brownb88102f2010-09-08 11:49:43 -07002333 bool needWake;
Jeff Brown46b9ac02010-04-22 18:58:52 -07002334 { // acquire lock
2335 AutoMutex _l(mLock);
2336
Jeff Brownbe1aa822011-07-27 16:04:54 -07002337 ConfigurationChangedEntry* newEntry = new ConfigurationChangedEntry(args->eventTime);
Jeff Brownb88102f2010-09-08 11:49:43 -07002338 needWake = enqueueInboundEventLocked(newEntry);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002339 } // release lock
2340
Jeff Brownb88102f2010-09-08 11:49:43 -07002341 if (needWake) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002342 mLooper->wake();
Jeff Brown46b9ac02010-04-22 18:58:52 -07002343 }
2344}
2345
Jeff Brownbe1aa822011-07-27 16:04:54 -07002346void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002347#if DEBUG_INBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00002348 ALOGD("notifyKey - eventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, action=0x%x, "
Jeff Brown46b9ac02010-04-22 18:58:52 -07002349 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%lld",
Jeff Brownbe1aa822011-07-27 16:04:54 -07002350 args->eventTime, args->deviceId, args->source, args->policyFlags,
2351 args->action, args->flags, args->keyCode, args->scanCode,
2352 args->metaState, args->downTime);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002353#endif
Jeff Brownbe1aa822011-07-27 16:04:54 -07002354 if (!validateKeyEvent(args->action)) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002355 return;
2356 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002357
Jeff Brownbe1aa822011-07-27 16:04:54 -07002358 uint32_t policyFlags = args->policyFlags;
2359 int32_t flags = args->flags;
2360 int32_t metaState = args->metaState;
Jeff Brown1f245102010-11-18 20:53:46 -08002361 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
2362 policyFlags |= POLICY_FLAG_VIRTUAL;
2363 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
2364 }
Jeff Brown924c4d42011-03-07 16:40:47 -08002365 if (policyFlags & POLICY_FLAG_ALT) {
2366 metaState |= AMETA_ALT_ON | AMETA_ALT_LEFT_ON;
2367 }
2368 if (policyFlags & POLICY_FLAG_ALT_GR) {
2369 metaState |= AMETA_ALT_ON | AMETA_ALT_RIGHT_ON;
2370 }
2371 if (policyFlags & POLICY_FLAG_SHIFT) {
2372 metaState |= AMETA_SHIFT_ON | AMETA_SHIFT_LEFT_ON;
2373 }
2374 if (policyFlags & POLICY_FLAG_CAPS_LOCK) {
2375 metaState |= AMETA_CAPS_LOCK_ON;
2376 }
2377 if (policyFlags & POLICY_FLAG_FUNCTION) {
2378 metaState |= AMETA_FUNCTION_ON;
2379 }
Jeff Brown1f245102010-11-18 20:53:46 -08002380
Jeff Browne20c9e02010-10-11 14:20:19 -07002381 policyFlags |= POLICY_FLAG_TRUSTED;
Jeff Brown1f245102010-11-18 20:53:46 -08002382
2383 KeyEvent event;
Jeff Brownbe1aa822011-07-27 16:04:54 -07002384 event.initialize(args->deviceId, args->source, args->action,
2385 flags, args->keyCode, args->scanCode, metaState, 0,
2386 args->downTime, args->eventTime);
Jeff Brown1f245102010-11-18 20:53:46 -08002387
2388 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
2389
2390 if (policyFlags & POLICY_FLAG_WOKE_HERE) {
2391 flags |= AKEY_EVENT_FLAG_WOKE_HERE;
2392 }
Jeff Brownb6997262010-10-08 22:31:17 -07002393
Jeff Brownb88102f2010-09-08 11:49:43 -07002394 bool needWake;
Jeff Brown46b9ac02010-04-22 18:58:52 -07002395 { // acquire lock
Jeff Brown0029c662011-03-30 02:25:18 -07002396 mLock.lock();
2397
Jeff Brown83d616a2012-09-09 20:33:43 -07002398 if (shouldSendKeyToInputFilterLocked(args)) {
Jeff Brown0029c662011-03-30 02:25:18 -07002399 mLock.unlock();
2400
2401 policyFlags |= POLICY_FLAG_FILTERED;
2402 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2403 return; // event was consumed by the filter
2404 }
2405
2406 mLock.lock();
2407 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002408
Jeff Brown7fbdc842010-06-17 20:52:56 -07002409 int32_t repeatCount = 0;
Jeff Brownbe1aa822011-07-27 16:04:54 -07002410 KeyEntry* newEntry = new KeyEntry(args->eventTime,
2411 args->deviceId, args->source, policyFlags,
2412 args->action, flags, args->keyCode, args->scanCode,
2413 metaState, repeatCount, args->downTime);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002414
Jeff Brownb88102f2010-09-08 11:49:43 -07002415 needWake = enqueueInboundEventLocked(newEntry);
Jeff Brown0029c662011-03-30 02:25:18 -07002416 mLock.unlock();
Jeff Brown46b9ac02010-04-22 18:58:52 -07002417 } // release lock
2418
Jeff Brownb88102f2010-09-08 11:49:43 -07002419 if (needWake) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002420 mLooper->wake();
Jeff Brown46b9ac02010-04-22 18:58:52 -07002421 }
2422}
2423
Jeff Brown83d616a2012-09-09 20:33:43 -07002424bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
2425 return mInputFilterEnabled;
2426}
2427
Jeff Brownbe1aa822011-07-27 16:04:54 -07002428void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002429#if DEBUG_INBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00002430 ALOGD("notifyMotion - eventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, "
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002431 "action=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, edgeFlags=0x%x, "
Jeff Brown85a31762010-09-01 17:01:00 -07002432 "xPrecision=%f, yPrecision=%f, downTime=%lld",
Jeff Brownbe1aa822011-07-27 16:04:54 -07002433 args->eventTime, args->deviceId, args->source, args->policyFlags,
2434 args->action, args->flags, args->metaState, args->buttonState,
2435 args->edgeFlags, args->xPrecision, args->yPrecision, args->downTime);
2436 for (uint32_t i = 0; i < args->pointerCount; i++) {
Steve Block5baa3a62011-12-20 16:23:08 +00002437 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002438 "x=%f, y=%f, pressure=%f, size=%f, "
Jeff Brown85a31762010-09-01 17:01:00 -07002439 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
Jeff Brown8d608662010-08-30 03:02:23 -07002440 "orientation=%f",
Jeff Brownbe1aa822011-07-27 16:04:54 -07002441 i, args->pointerProperties[i].id,
2442 args->pointerProperties[i].toolType,
2443 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
2444 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
2445 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
2446 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
2447 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
2448 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
2449 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
2450 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
2451 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Jeff Brown46b9ac02010-04-22 18:58:52 -07002452 }
2453#endif
Jeff Brownbe1aa822011-07-27 16:04:54 -07002454 if (!validateMotionEvent(args->action, args->pointerCount, args->pointerProperties)) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002455 return;
2456 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002457
Jeff Brownbe1aa822011-07-27 16:04:54 -07002458 uint32_t policyFlags = args->policyFlags;
Jeff Browne20c9e02010-10-11 14:20:19 -07002459 policyFlags |= POLICY_FLAG_TRUSTED;
Jeff Brownbe1aa822011-07-27 16:04:54 -07002460 mPolicy->interceptMotionBeforeQueueing(args->eventTime, /*byref*/ policyFlags);
Jeff Brownb6997262010-10-08 22:31:17 -07002461
Jeff Brownb88102f2010-09-08 11:49:43 -07002462 bool needWake;
Jeff Brown46b9ac02010-04-22 18:58:52 -07002463 { // acquire lock
Jeff Brown0029c662011-03-30 02:25:18 -07002464 mLock.lock();
2465
Jeff Brown83d616a2012-09-09 20:33:43 -07002466 if (shouldSendMotionToInputFilterLocked(args)) {
Jeff Brown0029c662011-03-30 02:25:18 -07002467 mLock.unlock();
2468
2469 MotionEvent event;
Jeff Brownbe1aa822011-07-27 16:04:54 -07002470 event.initialize(args->deviceId, args->source, args->action, args->flags,
2471 args->edgeFlags, args->metaState, args->buttonState, 0, 0,
2472 args->xPrecision, args->yPrecision,
2473 args->downTime, args->eventTime,
2474 args->pointerCount, args->pointerProperties, args->pointerCoords);
Jeff Brown0029c662011-03-30 02:25:18 -07002475
2476 policyFlags |= POLICY_FLAG_FILTERED;
2477 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2478 return; // event was consumed by the filter
2479 }
2480
2481 mLock.lock();
2482 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002483
Jeff Brown46b9ac02010-04-22 18:58:52 -07002484 // Just enqueue a new motion event.
Jeff Brownbe1aa822011-07-27 16:04:54 -07002485 MotionEntry* newEntry = new MotionEntry(args->eventTime,
2486 args->deviceId, args->source, policyFlags,
2487 args->action, args->flags, args->metaState, args->buttonState,
2488 args->edgeFlags, args->xPrecision, args->yPrecision, args->downTime,
Jeff Brown83d616a2012-09-09 20:33:43 -07002489 args->displayId,
Jeff Brownbe1aa822011-07-27 16:04:54 -07002490 args->pointerCount, args->pointerProperties, args->pointerCoords);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002491
Jeff Brownb88102f2010-09-08 11:49:43 -07002492 needWake = enqueueInboundEventLocked(newEntry);
Jeff Brown0029c662011-03-30 02:25:18 -07002493 mLock.unlock();
Jeff Brown46b9ac02010-04-22 18:58:52 -07002494 } // release lock
2495
Jeff Brownb88102f2010-09-08 11:49:43 -07002496 if (needWake) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002497 mLooper->wake();
Jeff Brown46b9ac02010-04-22 18:58:52 -07002498 }
2499}
2500
Jeff Brown83d616a2012-09-09 20:33:43 -07002501bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
2502 // TODO: support sending secondary display events to input filter
2503 return mInputFilterEnabled && isMainDisplay(args->displayId);
2504}
2505
Jeff Brownbe1aa822011-07-27 16:04:54 -07002506void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
Jeff Brownb6997262010-10-08 22:31:17 -07002507#if DEBUG_INBOUND_EVENT_DETAILS
Jeff Brownbcc046a2012-09-27 20:46:43 -07002508 ALOGD("notifySwitch - eventTime=%lld, policyFlags=0x%x, switchValues=0x%08x, switchMask=0x%08x",
Jeff Brownbe1aa822011-07-27 16:04:54 -07002509 args->eventTime, args->policyFlags,
Jeff Brownbcc046a2012-09-27 20:46:43 -07002510 args->switchValues, args->switchMask);
Jeff Brownb6997262010-10-08 22:31:17 -07002511#endif
2512
Jeff Brownbe1aa822011-07-27 16:04:54 -07002513 uint32_t policyFlags = args->policyFlags;
Jeff Browne20c9e02010-10-11 14:20:19 -07002514 policyFlags |= POLICY_FLAG_TRUSTED;
Jeff Brownbe1aa822011-07-27 16:04:54 -07002515 mPolicy->notifySwitch(args->eventTime,
Jeff Brownbcc046a2012-09-27 20:46:43 -07002516 args->switchValues, args->switchMask, policyFlags);
Jeff Brownb6997262010-10-08 22:31:17 -07002517}
2518
Jeff Brown65fd2512011-08-18 11:20:58 -07002519void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
2520#if DEBUG_INBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00002521 ALOGD("notifyDeviceReset - eventTime=%lld, deviceId=%d",
Jeff Brown65fd2512011-08-18 11:20:58 -07002522 args->eventTime, args->deviceId);
2523#endif
2524
2525 bool needWake;
2526 { // acquire lock
2527 AutoMutex _l(mLock);
2528
2529 DeviceResetEntry* newEntry = new DeviceResetEntry(args->eventTime, args->deviceId);
2530 needWake = enqueueInboundEventLocked(newEntry);
2531 } // release lock
2532
2533 if (needWake) {
2534 mLooper->wake();
2535 }
2536}
2537
Jeff Brown7fbdc842010-06-17 20:52:56 -07002538int32_t InputDispatcher::injectInputEvent(const InputEvent* event,
Jeff Brown0029c662011-03-30 02:25:18 -07002539 int32_t injectorPid, int32_t injectorUid, int32_t syncMode, int32_t timeoutMillis,
2540 uint32_t policyFlags) {
Jeff Brown7fbdc842010-06-17 20:52:56 -07002541#if DEBUG_INBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00002542 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Jeff Brown0029c662011-03-30 02:25:18 -07002543 "syncMode=%d, timeoutMillis=%d, policyFlags=0x%08x",
2544 event->getType(), injectorPid, injectorUid, syncMode, timeoutMillis, policyFlags);
Jeff Brown7fbdc842010-06-17 20:52:56 -07002545#endif
2546
2547 nsecs_t endTime = now() + milliseconds_to_nanoseconds(timeoutMillis);
Jeff Browne20c9e02010-10-11 14:20:19 -07002548
Jeff Brown0029c662011-03-30 02:25:18 -07002549 policyFlags |= POLICY_FLAG_INJECTED;
Jeff Browne20c9e02010-10-11 14:20:19 -07002550 if (hasInjectionPermission(injectorPid, injectorUid)) {
2551 policyFlags |= POLICY_FLAG_TRUSTED;
2552 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07002553
Jeff Brown3241b6b2012-02-03 15:08:02 -08002554 EventEntry* firstInjectedEntry;
2555 EventEntry* lastInjectedEntry;
Jeff Brownb6997262010-10-08 22:31:17 -07002556 switch (event->getType()) {
2557 case AINPUT_EVENT_TYPE_KEY: {
2558 const KeyEvent* keyEvent = static_cast<const KeyEvent*>(event);
2559 int32_t action = keyEvent->getAction();
2560 if (! validateKeyEvent(action)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07002561 return INPUT_EVENT_INJECTION_FAILED;
2562 }
2563
Jeff Brownb6997262010-10-08 22:31:17 -07002564 int32_t flags = keyEvent->getFlags();
Jeff Brown1f245102010-11-18 20:53:46 -08002565 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
2566 policyFlags |= POLICY_FLAG_VIRTUAL;
2567 }
2568
Jeff Brown0029c662011-03-30 02:25:18 -07002569 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
2570 mPolicy->interceptKeyBeforeQueueing(keyEvent, /*byref*/ policyFlags);
2571 }
Jeff Brown1f245102010-11-18 20:53:46 -08002572
2573 if (policyFlags & POLICY_FLAG_WOKE_HERE) {
2574 flags |= AKEY_EVENT_FLAG_WOKE_HERE;
2575 }
Jeff Brown6ec402b2010-07-28 15:48:59 -07002576
Jeff Brownb6997262010-10-08 22:31:17 -07002577 mLock.lock();
Jeff Brown3241b6b2012-02-03 15:08:02 -08002578 firstInjectedEntry = new KeyEntry(keyEvent->getEventTime(),
Jeff Brown1f245102010-11-18 20:53:46 -08002579 keyEvent->getDeviceId(), keyEvent->getSource(),
2580 policyFlags, action, flags,
2581 keyEvent->getKeyCode(), keyEvent->getScanCode(), keyEvent->getMetaState(),
Jeff Brownb6997262010-10-08 22:31:17 -07002582 keyEvent->getRepeatCount(), keyEvent->getDownTime());
Jeff Brown3241b6b2012-02-03 15:08:02 -08002583 lastInjectedEntry = firstInjectedEntry;
Jeff Brownb6997262010-10-08 22:31:17 -07002584 break;
2585 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07002586
Jeff Brownb6997262010-10-08 22:31:17 -07002587 case AINPUT_EVENT_TYPE_MOTION: {
2588 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
Jeff Brown83d616a2012-09-09 20:33:43 -07002589 int32_t displayId = ADISPLAY_ID_DEFAULT;
Jeff Brownb6997262010-10-08 22:31:17 -07002590 int32_t action = motionEvent->getAction();
2591 size_t pointerCount = motionEvent->getPointerCount();
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002592 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
2593 if (! validateMotionEvent(action, pointerCount, pointerProperties)) {
Jeff Brownb6997262010-10-08 22:31:17 -07002594 return INPUT_EVENT_INJECTION_FAILED;
2595 }
2596
Jeff Brown0029c662011-03-30 02:25:18 -07002597 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
2598 nsecs_t eventTime = motionEvent->getEventTime();
2599 mPolicy->interceptMotionBeforeQueueing(eventTime, /*byref*/ policyFlags);
2600 }
Jeff Brownb6997262010-10-08 22:31:17 -07002601
2602 mLock.lock();
2603 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
2604 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
Jeff Brown3241b6b2012-02-03 15:08:02 -08002605 firstInjectedEntry = new MotionEntry(*sampleEventTimes,
Jeff Brownb6997262010-10-08 22:31:17 -07002606 motionEvent->getDeviceId(), motionEvent->getSource(), policyFlags,
2607 action, motionEvent->getFlags(),
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002608 motionEvent->getMetaState(), motionEvent->getButtonState(),
2609 motionEvent->getEdgeFlags(),
Jeff Brownb6997262010-10-08 22:31:17 -07002610 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
Jeff Brown83d616a2012-09-09 20:33:43 -07002611 motionEvent->getDownTime(), displayId,
2612 uint32_t(pointerCount), pointerProperties, samplePointerCoords);
Jeff Brown3241b6b2012-02-03 15:08:02 -08002613 lastInjectedEntry = firstInjectedEntry;
Jeff Brownb6997262010-10-08 22:31:17 -07002614 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
2615 sampleEventTimes += 1;
2616 samplePointerCoords += pointerCount;
Jeff Brown3241b6b2012-02-03 15:08:02 -08002617 MotionEntry* nextInjectedEntry = new MotionEntry(*sampleEventTimes,
2618 motionEvent->getDeviceId(), motionEvent->getSource(), policyFlags,
2619 action, motionEvent->getFlags(),
2620 motionEvent->getMetaState(), motionEvent->getButtonState(),
2621 motionEvent->getEdgeFlags(),
2622 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
Jeff Brown83d616a2012-09-09 20:33:43 -07002623 motionEvent->getDownTime(), displayId,
2624 uint32_t(pointerCount), pointerProperties, samplePointerCoords);
Jeff Brown3241b6b2012-02-03 15:08:02 -08002625 lastInjectedEntry->next = nextInjectedEntry;
2626 lastInjectedEntry = nextInjectedEntry;
Jeff Brownb6997262010-10-08 22:31:17 -07002627 }
Jeff Brownb6997262010-10-08 22:31:17 -07002628 break;
2629 }
2630
2631 default:
Steve Block8564c8d2012-01-05 23:22:43 +00002632 ALOGW("Cannot inject event of type %d", event->getType());
Jeff Brownb6997262010-10-08 22:31:17 -07002633 return INPUT_EVENT_INJECTION_FAILED;
2634 }
2635
Jeff Brownac386072011-07-20 15:19:50 -07002636 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
Jeff Brownb6997262010-10-08 22:31:17 -07002637 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
2638 injectionState->injectionIsAsync = true;
2639 }
2640
2641 injectionState->refCount += 1;
Jeff Brown3241b6b2012-02-03 15:08:02 -08002642 lastInjectedEntry->injectionState = injectionState;
Jeff Brownb6997262010-10-08 22:31:17 -07002643
Jeff Brown3241b6b2012-02-03 15:08:02 -08002644 bool needWake = false;
2645 for (EventEntry* entry = firstInjectedEntry; entry != NULL; ) {
2646 EventEntry* nextEntry = entry->next;
2647 needWake |= enqueueInboundEventLocked(entry);
2648 entry = nextEntry;
2649 }
2650
Jeff Brownb6997262010-10-08 22:31:17 -07002651 mLock.unlock();
Jeff Brown7fbdc842010-06-17 20:52:56 -07002652
Jeff Brownb88102f2010-09-08 11:49:43 -07002653 if (needWake) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002654 mLooper->wake();
Jeff Brown7fbdc842010-06-17 20:52:56 -07002655 }
2656
2657 int32_t injectionResult;
2658 { // acquire lock
2659 AutoMutex _l(mLock);
2660
Jeff Brown6ec402b2010-07-28 15:48:59 -07002661 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
2662 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
2663 } else {
2664 for (;;) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002665 injectionResult = injectionState->injectionResult;
Jeff Brown6ec402b2010-07-28 15:48:59 -07002666 if (injectionResult != INPUT_EVENT_INJECTION_PENDING) {
2667 break;
2668 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07002669
Jeff Brown7fbdc842010-06-17 20:52:56 -07002670 nsecs_t remainingTimeout = endTime - now();
2671 if (remainingTimeout <= 0) {
Jeff Brown6ec402b2010-07-28 15:48:59 -07002672#if DEBUG_INJECTION
Steve Block5baa3a62011-12-20 16:23:08 +00002673 ALOGD("injectInputEvent - Timed out waiting for injection result "
Jeff Brown6ec402b2010-07-28 15:48:59 -07002674 "to become available.");
2675#endif
Jeff Brown7fbdc842010-06-17 20:52:56 -07002676 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
2677 break;
2678 }
2679
Jeff Brown6ec402b2010-07-28 15:48:59 -07002680 mInjectionResultAvailableCondition.waitRelative(mLock, remainingTimeout);
2681 }
2682
2683 if (injectionResult == INPUT_EVENT_INJECTION_SUCCEEDED
2684 && syncMode == INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002685 while (injectionState->pendingForegroundDispatches != 0) {
Jeff Brown6ec402b2010-07-28 15:48:59 -07002686#if DEBUG_INJECTION
Steve Block5baa3a62011-12-20 16:23:08 +00002687 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
Jeff Brown01ce2e92010-09-26 22:20:12 -07002688 injectionState->pendingForegroundDispatches);
Jeff Brown6ec402b2010-07-28 15:48:59 -07002689#endif
2690 nsecs_t remainingTimeout = endTime - now();
2691 if (remainingTimeout <= 0) {
2692#if DEBUG_INJECTION
Steve Block5baa3a62011-12-20 16:23:08 +00002693 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
Jeff Brown6ec402b2010-07-28 15:48:59 -07002694 "dispatches to finish.");
2695#endif
2696 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
2697 break;
2698 }
2699
2700 mInjectionSyncFinishedCondition.waitRelative(mLock, remainingTimeout);
2701 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07002702 }
2703 }
2704
Jeff Brownac386072011-07-20 15:19:50 -07002705 injectionState->release();
Jeff Brown7fbdc842010-06-17 20:52:56 -07002706 } // release lock
2707
Jeff Brown6ec402b2010-07-28 15:48:59 -07002708#if DEBUG_INJECTION
Steve Block5baa3a62011-12-20 16:23:08 +00002709 ALOGD("injectInputEvent - Finished with result %d. "
Jeff Brown6ec402b2010-07-28 15:48:59 -07002710 "injectorPid=%d, injectorUid=%d",
2711 injectionResult, injectorPid, injectorUid);
2712#endif
2713
Jeff Brown7fbdc842010-06-17 20:52:56 -07002714 return injectionResult;
2715}
2716
Jeff Brownb6997262010-10-08 22:31:17 -07002717bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
2718 return injectorUid == 0
2719 || mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
2720}
2721
Jeff Brown7fbdc842010-06-17 20:52:56 -07002722void InputDispatcher::setInjectionResultLocked(EventEntry* entry, int32_t injectionResult) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002723 InjectionState* injectionState = entry->injectionState;
2724 if (injectionState) {
Jeff Brown7fbdc842010-06-17 20:52:56 -07002725#if DEBUG_INJECTION
Steve Block5baa3a62011-12-20 16:23:08 +00002726 ALOGD("Setting input event injection result to %d. "
Jeff Brown7fbdc842010-06-17 20:52:56 -07002727 "injectorPid=%d, injectorUid=%d",
Jeff Brown01ce2e92010-09-26 22:20:12 -07002728 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
Jeff Brown7fbdc842010-06-17 20:52:56 -07002729#endif
2730
Jeff Brown0029c662011-03-30 02:25:18 -07002731 if (injectionState->injectionIsAsync
2732 && !(entry->policyFlags & POLICY_FLAG_FILTERED)) {
Jeff Brown6ec402b2010-07-28 15:48:59 -07002733 // Log the outcome since the injector did not wait for the injection result.
2734 switch (injectionResult) {
2735 case INPUT_EVENT_INJECTION_SUCCEEDED:
Steve Block71f2cf12011-10-20 11:56:00 +01002736 ALOGV("Asynchronous input event injection succeeded.");
Jeff Brown6ec402b2010-07-28 15:48:59 -07002737 break;
2738 case INPUT_EVENT_INJECTION_FAILED:
Steve Block8564c8d2012-01-05 23:22:43 +00002739 ALOGW("Asynchronous input event injection failed.");
Jeff Brown6ec402b2010-07-28 15:48:59 -07002740 break;
2741 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
Steve Block8564c8d2012-01-05 23:22:43 +00002742 ALOGW("Asynchronous input event injection permission denied.");
Jeff Brown6ec402b2010-07-28 15:48:59 -07002743 break;
2744 case INPUT_EVENT_INJECTION_TIMED_OUT:
Steve Block8564c8d2012-01-05 23:22:43 +00002745 ALOGW("Asynchronous input event injection timed out.");
Jeff Brown6ec402b2010-07-28 15:48:59 -07002746 break;
2747 }
2748 }
2749
Jeff Brown01ce2e92010-09-26 22:20:12 -07002750 injectionState->injectionResult = injectionResult;
Jeff Brown7fbdc842010-06-17 20:52:56 -07002751 mInjectionResultAvailableCondition.broadcast();
2752 }
2753}
2754
Jeff Brown01ce2e92010-09-26 22:20:12 -07002755void InputDispatcher::incrementPendingForegroundDispatchesLocked(EventEntry* entry) {
2756 InjectionState* injectionState = entry->injectionState;
2757 if (injectionState) {
2758 injectionState->pendingForegroundDispatches += 1;
2759 }
2760}
2761
Jeff Brown519e0242010-09-15 15:18:56 -07002762void InputDispatcher::decrementPendingForegroundDispatchesLocked(EventEntry* entry) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002763 InjectionState* injectionState = entry->injectionState;
2764 if (injectionState) {
2765 injectionState->pendingForegroundDispatches -= 1;
Jeff Brown6ec402b2010-07-28 15:48:59 -07002766
Jeff Brown01ce2e92010-09-26 22:20:12 -07002767 if (injectionState->pendingForegroundDispatches == 0) {
2768 mInjectionSyncFinishedCondition.broadcast();
2769 }
Jeff Brownb88102f2010-09-08 11:49:43 -07002770 }
2771}
2772
Jeff Brown9302c872011-07-13 22:51:29 -07002773sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
2774 const sp<InputChannel>& inputChannel) const {
2775 size_t numWindows = mWindowHandles.size();
2776 for (size_t i = 0; i < numWindows; i++) {
2777 const sp<InputWindowHandle>& windowHandle = mWindowHandles.itemAt(i);
Jeff Browncc4f7db2011-08-30 20:34:48 -07002778 if (windowHandle->getInputChannel() == inputChannel) {
Jeff Brown9302c872011-07-13 22:51:29 -07002779 return windowHandle;
Jeff Brown01ce2e92010-09-26 22:20:12 -07002780 }
2781 }
2782 return NULL;
2783}
2784
Jeff Brown9302c872011-07-13 22:51:29 -07002785bool InputDispatcher::hasWindowHandleLocked(
2786 const sp<InputWindowHandle>& windowHandle) const {
2787 size_t numWindows = mWindowHandles.size();
2788 for (size_t i = 0; i < numWindows; i++) {
2789 if (mWindowHandles.itemAt(i) == windowHandle) {
2790 return true;
2791 }
2792 }
2793 return false;
2794}
2795
2796void InputDispatcher::setInputWindows(const Vector<sp<InputWindowHandle> >& inputWindowHandles) {
Jeff Brownb88102f2010-09-08 11:49:43 -07002797#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002798 ALOGD("setInputWindows");
Jeff Brownb88102f2010-09-08 11:49:43 -07002799#endif
2800 { // acquire lock
2801 AutoMutex _l(mLock);
2802
Jeff Browncc4f7db2011-08-30 20:34:48 -07002803 Vector<sp<InputWindowHandle> > oldWindowHandles = mWindowHandles;
Jeff Brown9302c872011-07-13 22:51:29 -07002804 mWindowHandles = inputWindowHandles;
Jeff Brownb6997262010-10-08 22:31:17 -07002805
Jeff Brown9302c872011-07-13 22:51:29 -07002806 sp<InputWindowHandle> newFocusedWindowHandle;
2807 bool foundHoveredWindow = false;
2808 for (size_t i = 0; i < mWindowHandles.size(); i++) {
2809 const sp<InputWindowHandle>& windowHandle = mWindowHandles.itemAt(i);
Jeff Browncc4f7db2011-08-30 20:34:48 -07002810 if (!windowHandle->updateInfo() || windowHandle->getInputChannel() == NULL) {
Jeff Brown9302c872011-07-13 22:51:29 -07002811 mWindowHandles.removeAt(i--);
2812 continue;
2813 }
Jeff Browncc4f7db2011-08-30 20:34:48 -07002814 if (windowHandle->getInfo()->hasFocus) {
Jeff Brown9302c872011-07-13 22:51:29 -07002815 newFocusedWindowHandle = windowHandle;
2816 }
2817 if (windowHandle == mLastHoverWindowHandle) {
2818 foundHoveredWindow = true;
Jeff Brownb88102f2010-09-08 11:49:43 -07002819 }
2820 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07002821
Jeff Brown9302c872011-07-13 22:51:29 -07002822 if (!foundHoveredWindow) {
2823 mLastHoverWindowHandle = NULL;
2824 }
2825
2826 if (mFocusedWindowHandle != newFocusedWindowHandle) {
2827 if (mFocusedWindowHandle != NULL) {
Jeff Brownb6997262010-10-08 22:31:17 -07002828#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002829 ALOGD("Focus left window: %s",
Jeff Browncc4f7db2011-08-30 20:34:48 -07002830 mFocusedWindowHandle->getName().string());
Jeff Brownb6997262010-10-08 22:31:17 -07002831#endif
Jeff Browncc4f7db2011-08-30 20:34:48 -07002832 sp<InputChannel> focusedInputChannel = mFocusedWindowHandle->getInputChannel();
2833 if (focusedInputChannel != NULL) {
Christopher Tated9be36c2011-08-16 16:09:33 -07002834 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
2835 "focus left window");
2836 synthesizeCancelationEventsForInputChannelLocked(
Jeff Browncc4f7db2011-08-30 20:34:48 -07002837 focusedInputChannel, options);
Christopher Tated9be36c2011-08-16 16:09:33 -07002838 }
Jeff Brownb6997262010-10-08 22:31:17 -07002839 }
Jeff Brown9302c872011-07-13 22:51:29 -07002840 if (newFocusedWindowHandle != NULL) {
Jeff Brownb6997262010-10-08 22:31:17 -07002841#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002842 ALOGD("Focus entered window: %s",
Jeff Browncc4f7db2011-08-30 20:34:48 -07002843 newFocusedWindowHandle->getName().string());
Jeff Brownb6997262010-10-08 22:31:17 -07002844#endif
Jeff Brown9302c872011-07-13 22:51:29 -07002845 }
2846 mFocusedWindowHandle = newFocusedWindowHandle;
Jeff Brownb6997262010-10-08 22:31:17 -07002847 }
2848
Jeff Brown9302c872011-07-13 22:51:29 -07002849 for (size_t i = 0; i < mTouchState.windows.size(); i++) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002850 TouchedWindow& touchedWindow = mTouchState.windows.editItemAt(i);
Jeff Brown9302c872011-07-13 22:51:29 -07002851 if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
Jeff Brownb6997262010-10-08 22:31:17 -07002852#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002853 ALOGD("Touched window was removed: %s",
Jeff Browncc4f7db2011-08-30 20:34:48 -07002854 touchedWindow.windowHandle->getName().string());
Jeff Brownb6997262010-10-08 22:31:17 -07002855#endif
Jeff Browncc4f7db2011-08-30 20:34:48 -07002856 sp<InputChannel> touchedInputChannel =
2857 touchedWindow.windowHandle->getInputChannel();
2858 if (touchedInputChannel != NULL) {
Christopher Tated9be36c2011-08-16 16:09:33 -07002859 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
2860 "touched window was removed");
2861 synthesizeCancelationEventsForInputChannelLocked(
Jeff Browncc4f7db2011-08-30 20:34:48 -07002862 touchedInputChannel, options);
Christopher Tated9be36c2011-08-16 16:09:33 -07002863 }
Jeff Brown9302c872011-07-13 22:51:29 -07002864 mTouchState.windows.removeAt(i--);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002865 }
2866 }
Jeff Browncc4f7db2011-08-30 20:34:48 -07002867
2868 // Release information for windows that are no longer present.
2869 // This ensures that unused input channels are released promptly.
2870 // Otherwise, they might stick around until the window handle is destroyed
2871 // which might not happen until the next GC.
2872 for (size_t i = 0; i < oldWindowHandles.size(); i++) {
2873 const sp<InputWindowHandle>& oldWindowHandle = oldWindowHandles.itemAt(i);
2874 if (!hasWindowHandleLocked(oldWindowHandle)) {
2875#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002876 ALOGD("Window went away: %s", oldWindowHandle->getName().string());
Jeff Browncc4f7db2011-08-30 20:34:48 -07002877#endif
2878 oldWindowHandle->releaseInfo();
2879 }
2880 }
Jeff Brownb88102f2010-09-08 11:49:43 -07002881 } // release lock
2882
2883 // Wake up poll loop since it may need to make new input dispatching choices.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002884 mLooper->wake();
Jeff Brownb88102f2010-09-08 11:49:43 -07002885}
2886
Jeff Brown9302c872011-07-13 22:51:29 -07002887void InputDispatcher::setFocusedApplication(
2888 const sp<InputApplicationHandle>& inputApplicationHandle) {
Jeff Brownb88102f2010-09-08 11:49:43 -07002889#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002890 ALOGD("setFocusedApplication");
Jeff Brownb88102f2010-09-08 11:49:43 -07002891#endif
2892 { // acquire lock
2893 AutoMutex _l(mLock);
2894
Jeff Browncc4f7db2011-08-30 20:34:48 -07002895 if (inputApplicationHandle != NULL && inputApplicationHandle->updateInfo()) {
Jeff Brown5ea29ab2011-07-27 11:50:51 -07002896 if (mFocusedApplicationHandle != inputApplicationHandle) {
2897 if (mFocusedApplicationHandle != NULL) {
Jeff Browne9bb9be2012-02-06 15:47:55 -08002898 resetANRTimeoutsLocked();
Jeff Browncc4f7db2011-08-30 20:34:48 -07002899 mFocusedApplicationHandle->releaseInfo();
Jeff Brown5ea29ab2011-07-27 11:50:51 -07002900 }
2901 mFocusedApplicationHandle = inputApplicationHandle;
2902 }
2903 } else if (mFocusedApplicationHandle != NULL) {
Jeff Browne9bb9be2012-02-06 15:47:55 -08002904 resetANRTimeoutsLocked();
Jeff Browncc4f7db2011-08-30 20:34:48 -07002905 mFocusedApplicationHandle->releaseInfo();
Jeff Brown9302c872011-07-13 22:51:29 -07002906 mFocusedApplicationHandle.clear();
Jeff Brownb88102f2010-09-08 11:49:43 -07002907 }
2908
2909#if DEBUG_FOCUS
Jeff Brownb6997262010-10-08 22:31:17 -07002910 //logDispatchStateLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -07002911#endif
2912 } // release lock
2913
2914 // Wake up poll loop since it may need to make new input dispatching choices.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002915 mLooper->wake();
Jeff Brownb88102f2010-09-08 11:49:43 -07002916}
2917
Jeff Brownb88102f2010-09-08 11:49:43 -07002918void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
2919#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002920 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
Jeff Brownb88102f2010-09-08 11:49:43 -07002921#endif
2922
2923 bool changed;
2924 { // acquire lock
2925 AutoMutex _l(mLock);
2926
2927 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
Jeff Brown120a4592010-10-27 18:43:51 -07002928 if (mDispatchFrozen && !frozen) {
Jeff Brownb88102f2010-09-08 11:49:43 -07002929 resetANRTimeoutsLocked();
2930 }
2931
Jeff Brown120a4592010-10-27 18:43:51 -07002932 if (mDispatchEnabled && !enabled) {
2933 resetAndDropEverythingLocked("dispatcher is being disabled");
2934 }
2935
Jeff Brownb88102f2010-09-08 11:49:43 -07002936 mDispatchEnabled = enabled;
2937 mDispatchFrozen = frozen;
2938 changed = true;
2939 } else {
2940 changed = false;
2941 }
2942
2943#if DEBUG_FOCUS
Jeff Brownb6997262010-10-08 22:31:17 -07002944 //logDispatchStateLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -07002945#endif
2946 } // release lock
2947
2948 if (changed) {
2949 // Wake up poll loop since it may need to make new input dispatching choices.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002950 mLooper->wake();
Jeff Brown46b9ac02010-04-22 18:58:52 -07002951 }
2952}
2953
Jeff Brown0029c662011-03-30 02:25:18 -07002954void InputDispatcher::setInputFilterEnabled(bool enabled) {
2955#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002956 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
Jeff Brown0029c662011-03-30 02:25:18 -07002957#endif
2958
2959 { // acquire lock
2960 AutoMutex _l(mLock);
2961
2962 if (mInputFilterEnabled == enabled) {
2963 return;
2964 }
2965
2966 mInputFilterEnabled = enabled;
2967 resetAndDropEverythingLocked("input filter is being enabled or disabled");
2968 } // release lock
2969
2970 // Wake up poll loop since there might be work to do to drop everything.
2971 mLooper->wake();
2972}
2973
Jeff Browne6504122010-09-27 14:52:15 -07002974bool InputDispatcher::transferTouchFocus(const sp<InputChannel>& fromChannel,
2975 const sp<InputChannel>& toChannel) {
2976#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002977 ALOGD("transferTouchFocus: fromChannel=%s, toChannel=%s",
Jeff Browne6504122010-09-27 14:52:15 -07002978 fromChannel->getName().string(), toChannel->getName().string());
2979#endif
2980 { // acquire lock
2981 AutoMutex _l(mLock);
2982
Jeff Brown9302c872011-07-13 22:51:29 -07002983 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromChannel);
2984 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toChannel);
2985 if (fromWindowHandle == NULL || toWindowHandle == NULL) {
Jeff Browne6504122010-09-27 14:52:15 -07002986#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002987 ALOGD("Cannot transfer focus because from or to window not found.");
Jeff Browne6504122010-09-27 14:52:15 -07002988#endif
2989 return false;
2990 }
Jeff Brown9302c872011-07-13 22:51:29 -07002991 if (fromWindowHandle == toWindowHandle) {
Jeff Browne6504122010-09-27 14:52:15 -07002992#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002993 ALOGD("Trivial transfer to same window.");
Jeff Browne6504122010-09-27 14:52:15 -07002994#endif
2995 return true;
2996 }
Jeff Brown83d616a2012-09-09 20:33:43 -07002997 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
2998#if DEBUG_FOCUS
2999 ALOGD("Cannot transfer focus because windows are on different displays.");
3000#endif
3001 return false;
3002 }
Jeff Browne6504122010-09-27 14:52:15 -07003003
3004 bool found = false;
3005 for (size_t i = 0; i < mTouchState.windows.size(); i++) {
3006 const TouchedWindow& touchedWindow = mTouchState.windows[i];
Jeff Brown9302c872011-07-13 22:51:29 -07003007 if (touchedWindow.windowHandle == fromWindowHandle) {
Jeff Browne6504122010-09-27 14:52:15 -07003008 int32_t oldTargetFlags = touchedWindow.targetFlags;
3009 BitSet32 pointerIds = touchedWindow.pointerIds;
3010
3011 mTouchState.windows.removeAt(i);
3012
Jeff Brown46e75292010-11-10 16:53:45 -08003013 int32_t newTargetFlags = oldTargetFlags
Jeff Browna032cc02011-03-07 16:56:21 -08003014 & (InputTarget::FLAG_FOREGROUND
3015 | InputTarget::FLAG_SPLIT | InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brown9302c872011-07-13 22:51:29 -07003016 mTouchState.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Jeff Browne6504122010-09-27 14:52:15 -07003017
3018 found = true;
3019 break;
3020 }
3021 }
3022
3023 if (! found) {
3024#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00003025 ALOGD("Focus transfer failed because from window did not have focus.");
Jeff Browne6504122010-09-27 14:52:15 -07003026#endif
3027 return false;
3028 }
3029
Jeff Brown9c9f1a32010-10-11 18:32:20 -07003030 ssize_t fromConnectionIndex = getConnectionIndexLocked(fromChannel);
3031 ssize_t toConnectionIndex = getConnectionIndexLocked(toChannel);
3032 if (fromConnectionIndex >= 0 && toConnectionIndex >= 0) {
Jeff Browncbee6d62012-02-03 20:11:27 -08003033 sp<Connection> fromConnection = mConnectionsByFd.valueAt(fromConnectionIndex);
3034 sp<Connection> toConnection = mConnectionsByFd.valueAt(toConnectionIndex);
Jeff Brown9c9f1a32010-10-11 18:32:20 -07003035
3036 fromConnection->inputState.copyPointerStateTo(toConnection->inputState);
Jeff Brownda3d5a92011-03-29 15:11:34 -07003037 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Jeff Brown9c9f1a32010-10-11 18:32:20 -07003038 "transferring touch focus from this window to another window");
Jeff Brownda3d5a92011-03-29 15:11:34 -07003039 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Jeff Brown9c9f1a32010-10-11 18:32:20 -07003040 }
3041
Jeff Browne6504122010-09-27 14:52:15 -07003042#if DEBUG_FOCUS
3043 logDispatchStateLocked();
3044#endif
3045 } // release lock
3046
3047 // Wake up poll loop since it may need to make new input dispatching choices.
3048 mLooper->wake();
3049 return true;
3050}
3051
Jeff Brown120a4592010-10-27 18:43:51 -07003052void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
3053#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00003054 ALOGD("Resetting and dropping all events (%s).", reason);
Jeff Brown120a4592010-10-27 18:43:51 -07003055#endif
3056
Jeff Brownda3d5a92011-03-29 15:11:34 -07003057 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
3058 synthesizeCancelationEventsForAllConnectionsLocked(options);
Jeff Brown120a4592010-10-27 18:43:51 -07003059
3060 resetKeyRepeatLocked();
3061 releasePendingEventLocked();
3062 drainInboundQueueLocked();
Jeff Browne9bb9be2012-02-06 15:47:55 -08003063 resetANRTimeoutsLocked();
Jeff Brown120a4592010-10-27 18:43:51 -07003064
3065 mTouchState.reset();
Jeff Brown9302c872011-07-13 22:51:29 -07003066 mLastHoverWindowHandle.clear();
Jeff Brown120a4592010-10-27 18:43:51 -07003067}
3068
Jeff Brownb88102f2010-09-08 11:49:43 -07003069void InputDispatcher::logDispatchStateLocked() {
3070 String8 dump;
3071 dumpDispatchStateLocked(dump);
Jeff Brown2a95c2a2010-09-16 12:31:46 -07003072
3073 char* text = dump.lockBuffer(dump.size());
3074 char* start = text;
3075 while (*start != '\0') {
3076 char* end = strchr(start, '\n');
3077 if (*end == '\n') {
3078 *(end++) = '\0';
3079 }
Steve Block5baa3a62011-12-20 16:23:08 +00003080 ALOGD("%s", start);
Jeff Brown2a95c2a2010-09-16 12:31:46 -07003081 start = end;
3082 }
Jeff Brownb88102f2010-09-08 11:49:43 -07003083}
3084
3085void InputDispatcher::dumpDispatchStateLocked(String8& dump) {
Jeff Brownf2f48712010-10-01 17:46:21 -07003086 dump.appendFormat(INDENT "DispatchEnabled: %d\n", mDispatchEnabled);
3087 dump.appendFormat(INDENT "DispatchFrozen: %d\n", mDispatchFrozen);
Jeff Brownb88102f2010-09-08 11:49:43 -07003088
Jeff Brown9302c872011-07-13 22:51:29 -07003089 if (mFocusedApplicationHandle != NULL) {
Jeff Brownf2f48712010-10-01 17:46:21 -07003090 dump.appendFormat(INDENT "FocusedApplication: name='%s', dispatchingTimeout=%0.3fms\n",
Jeff Browncc4f7db2011-08-30 20:34:48 -07003091 mFocusedApplicationHandle->getName().string(),
3092 mFocusedApplicationHandle->getDispatchingTimeout(
3093 DEFAULT_INPUT_DISPATCHING_TIMEOUT) / 1000000.0);
Jeff Brownb88102f2010-09-08 11:49:43 -07003094 } else {
Jeff Brownf2f48712010-10-01 17:46:21 -07003095 dump.append(INDENT "FocusedApplication: <null>\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003096 }
Jeff Brownf2f48712010-10-01 17:46:21 -07003097 dump.appendFormat(INDENT "FocusedWindow: name='%s'\n",
Jeff Browncc4f7db2011-08-30 20:34:48 -07003098 mFocusedWindowHandle != NULL ? mFocusedWindowHandle->getName().string() : "<null>");
Jeff Brownf2f48712010-10-01 17:46:21 -07003099
3100 dump.appendFormat(INDENT "TouchDown: %s\n", toString(mTouchState.down));
3101 dump.appendFormat(INDENT "TouchSplit: %s\n", toString(mTouchState.split));
Jeff Brown95712852011-01-04 19:41:59 -08003102 dump.appendFormat(INDENT "TouchDeviceId: %d\n", mTouchState.deviceId);
Jeff Brown58a2da82011-01-25 16:02:22 -08003103 dump.appendFormat(INDENT "TouchSource: 0x%08x\n", mTouchState.source);
Jeff Brown83d616a2012-09-09 20:33:43 -07003104 dump.appendFormat(INDENT "TouchDisplayId: %d\n", mTouchState.displayId);
Jeff Brownf2f48712010-10-01 17:46:21 -07003105 if (!mTouchState.windows.isEmpty()) {
3106 dump.append(INDENT "TouchedWindows:\n");
3107 for (size_t i = 0; i < mTouchState.windows.size(); i++) {
3108 const TouchedWindow& touchedWindow = mTouchState.windows[i];
3109 dump.appendFormat(INDENT2 "%d: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
Jeff Browncc4f7db2011-08-30 20:34:48 -07003110 i, touchedWindow.windowHandle->getName().string(),
3111 touchedWindow.pointerIds.value,
Jeff Brownf2f48712010-10-01 17:46:21 -07003112 touchedWindow.targetFlags);
3113 }
3114 } else {
3115 dump.append(INDENT "TouchedWindows: <none>\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003116 }
3117
Jeff Brown9302c872011-07-13 22:51:29 -07003118 if (!mWindowHandles.isEmpty()) {
Jeff Brownf2f48712010-10-01 17:46:21 -07003119 dump.append(INDENT "Windows:\n");
Jeff Brown9302c872011-07-13 22:51:29 -07003120 for (size_t i = 0; i < mWindowHandles.size(); i++) {
3121 const sp<InputWindowHandle>& windowHandle = mWindowHandles.itemAt(i);
Jeff Browncc4f7db2011-08-30 20:34:48 -07003122 const InputWindowInfo* windowInfo = windowHandle->getInfo();
3123
Jeff Brown83d616a2012-09-09 20:33:43 -07003124 dump.appendFormat(INDENT2 "%d: name='%s', displayId=%d, "
3125 "paused=%s, hasFocus=%s, hasWallpaper=%s, "
Jeff Brownf2f48712010-10-01 17:46:21 -07003126 "visible=%s, canReceiveKeys=%s, flags=0x%08x, type=0x%08x, layer=%d, "
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003127 "frame=[%d,%d][%d,%d], scale=%f, "
Jeff Brownfbf09772011-01-16 14:06:57 -08003128 "touchableRegion=",
Jeff Brown83d616a2012-09-09 20:33:43 -07003129 i, windowInfo->name.string(), windowInfo->displayId,
Jeff Browncc4f7db2011-08-30 20:34:48 -07003130 toString(windowInfo->paused),
3131 toString(windowInfo->hasFocus),
3132 toString(windowInfo->hasWallpaper),
3133 toString(windowInfo->visible),
3134 toString(windowInfo->canReceiveKeys),
3135 windowInfo->layoutParamsFlags, windowInfo->layoutParamsType,
3136 windowInfo->layer,
3137 windowInfo->frameLeft, windowInfo->frameTop,
3138 windowInfo->frameRight, windowInfo->frameBottom,
3139 windowInfo->scaleFactor);
3140 dumpRegion(dump, windowInfo->touchableRegion);
3141 dump.appendFormat(", inputFeatures=0x%08x", windowInfo->inputFeatures);
Jeff Brownfbf09772011-01-16 14:06:57 -08003142 dump.appendFormat(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%0.3fms\n",
Jeff Browncc4f7db2011-08-30 20:34:48 -07003143 windowInfo->ownerPid, windowInfo->ownerUid,
3144 windowInfo->dispatchingTimeout / 1000000.0);
Jeff Brownf2f48712010-10-01 17:46:21 -07003145 }
3146 } else {
3147 dump.append(INDENT "Windows: <none>\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003148 }
3149
Jeff Brownf2f48712010-10-01 17:46:21 -07003150 if (!mMonitoringChannels.isEmpty()) {
3151 dump.append(INDENT "MonitoringChannels:\n");
3152 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
3153 const sp<InputChannel>& channel = mMonitoringChannels[i];
3154 dump.appendFormat(INDENT2 "%d: '%s'\n", i, channel->getName().string());
3155 }
3156 } else {
3157 dump.append(INDENT "MonitoringChannels: <none>\n");
3158 }
Jeff Brown519e0242010-09-15 15:18:56 -07003159
Jeff Brown265f1cc2012-06-11 18:01:06 -07003160 nsecs_t currentTime = now();
3161
3162 if (!mInboundQueue.isEmpty()) {
3163 dump.appendFormat(INDENT "InboundQueue: length=%u\n", mInboundQueue.count());
3164 for (EventEntry* entry = mInboundQueue.head; entry; entry = entry->next) {
3165 dump.append(INDENT2);
3166 entry->appendDescription(dump);
Jeff Brown22aa5122012-06-17 12:01:06 -07003167 dump.appendFormat(", age=%0.1fms\n",
Jeff Brown265f1cc2012-06-11 18:01:06 -07003168 (currentTime - entry->eventTime) * 0.000001f);
3169 }
3170 } else {
3171 dump.append(INDENT "InboundQueue: <empty>\n");
3172 }
3173
3174 if (!mConnectionsByFd.isEmpty()) {
3175 dump.append(INDENT "Connections:\n");
3176 for (size_t i = 0; i < mConnectionsByFd.size(); i++) {
3177 const sp<Connection>& connection = mConnectionsByFd.valueAt(i);
3178 dump.appendFormat(INDENT2 "%d: channelName='%s', windowName='%s', "
3179 "status=%s, monitor=%s, inputPublisherBlocked=%s\n",
3180 i, connection->getInputChannelName(), connection->getWindowName(),
3181 connection->getStatusLabel(), toString(connection->monitor),
3182 toString(connection->inputPublisherBlocked));
3183
3184 if (!connection->outboundQueue.isEmpty()) {
3185 dump.appendFormat(INDENT3 "OutboundQueue: length=%u\n",
3186 connection->outboundQueue.count());
3187 for (DispatchEntry* entry = connection->outboundQueue.head; entry;
3188 entry = entry->next) {
3189 dump.append(INDENT4);
3190 entry->eventEntry->appendDescription(dump);
Jeff Brown22aa5122012-06-17 12:01:06 -07003191 dump.appendFormat(", targetFlags=0x%08x, resolvedAction=%d, age=%0.1fms\n",
Jeff Brown265f1cc2012-06-11 18:01:06 -07003192 entry->targetFlags, entry->resolvedAction,
3193 (currentTime - entry->eventEntry->eventTime) * 0.000001f);
3194 }
3195 } else {
3196 dump.append(INDENT3 "OutboundQueue: <empty>\n");
3197 }
3198
3199 if (!connection->waitQueue.isEmpty()) {
3200 dump.appendFormat(INDENT3 "WaitQueue: length=%u\n",
3201 connection->waitQueue.count());
3202 for (DispatchEntry* entry = connection->waitQueue.head; entry;
3203 entry = entry->next) {
3204 dump.append(INDENT4);
3205 entry->eventEntry->appendDescription(dump);
3206 dump.appendFormat(", targetFlags=0x%08x, resolvedAction=%d, "
Jeff Brown22aa5122012-06-17 12:01:06 -07003207 "age=%0.1fms, wait=%0.1fms\n",
Jeff Brown265f1cc2012-06-11 18:01:06 -07003208 entry->targetFlags, entry->resolvedAction,
3209 (currentTime - entry->eventEntry->eventTime) * 0.000001f,
3210 (currentTime - entry->deliveryTime) * 0.000001f);
3211 }
3212 } else {
3213 dump.append(INDENT3 "WaitQueue: <empty>\n");
3214 }
3215 }
3216 } else {
3217 dump.append(INDENT "Connections: <none>\n");
3218 }
Jeff Brownf2f48712010-10-01 17:46:21 -07003219
Jeff Brownb88102f2010-09-08 11:49:43 -07003220 if (isAppSwitchPendingLocked()) {
Jeff Brown22aa5122012-06-17 12:01:06 -07003221 dump.appendFormat(INDENT "AppSwitch: pending, due in %0.1fms\n",
Jeff Brownb88102f2010-09-08 11:49:43 -07003222 (mAppSwitchDueTime - now()) / 1000000.0);
3223 } else {
Jeff Brownf2f48712010-10-01 17:46:21 -07003224 dump.append(INDENT "AppSwitch: not pending\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003225 }
Jeff Brown22aa5122012-06-17 12:01:06 -07003226
3227 dump.append(INDENT "Configuration:\n");
3228 dump.appendFormat(INDENT2 "KeyRepeatDelay: %0.1fms\n",
3229 mConfig.keyRepeatDelay * 0.000001f);
3230 dump.appendFormat(INDENT2 "KeyRepeatTimeout: %0.1fms\n",
3231 mConfig.keyRepeatTimeout * 0.000001f);
Jeff Brownb88102f2010-09-08 11:49:43 -07003232}
3233
Jeff Brown928e0542011-01-10 11:17:36 -08003234status_t InputDispatcher::registerInputChannel(const sp<InputChannel>& inputChannel,
3235 const sp<InputWindowHandle>& inputWindowHandle, bool monitor) {
Jeff Brown9c3cda02010-06-15 01:31:58 -07003236#if DEBUG_REGISTRATION
Steve Block5baa3a62011-12-20 16:23:08 +00003237 ALOGD("channel '%s' ~ registerInputChannel - monitor=%s", inputChannel->getName().string(),
Jeff Brownb88102f2010-09-08 11:49:43 -07003238 toString(monitor));
Jeff Brown9c3cda02010-06-15 01:31:58 -07003239#endif
3240
Jeff Brown46b9ac02010-04-22 18:58:52 -07003241 { // acquire lock
3242 AutoMutex _l(mLock);
3243
Jeff Brown519e0242010-09-15 15:18:56 -07003244 if (getConnectionIndexLocked(inputChannel) >= 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00003245 ALOGW("Attempted to register already registered input channel '%s'",
Jeff Brown46b9ac02010-04-22 18:58:52 -07003246 inputChannel->getName().string());
3247 return BAD_VALUE;
3248 }
3249
Jeff Browncc4f7db2011-08-30 20:34:48 -07003250 sp<Connection> connection = new Connection(inputChannel, inputWindowHandle, monitor);
Jeff Brown46b9ac02010-04-22 18:58:52 -07003251
Jeff Brown91e32892012-02-14 15:56:29 -08003252 int fd = inputChannel->getFd();
Jeff Browncbee6d62012-02-03 20:11:27 -08003253 mConnectionsByFd.add(fd, connection);
Jeff Brown9c3cda02010-06-15 01:31:58 -07003254
Jeff Brownb88102f2010-09-08 11:49:43 -07003255 if (monitor) {
3256 mMonitoringChannels.push(inputChannel);
3257 }
3258
Jeff Browncbee6d62012-02-03 20:11:27 -08003259 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
Jeff Brown46b9ac02010-04-22 18:58:52 -07003260 } // release lock
Jeff Brown074b8b72012-10-31 19:01:31 -07003261
3262 // Wake the looper because some connections have changed.
3263 mLooper->wake();
Jeff Brown46b9ac02010-04-22 18:58:52 -07003264 return OK;
3265}
3266
3267status_t InputDispatcher::unregisterInputChannel(const sp<InputChannel>& inputChannel) {
Jeff Brown9c3cda02010-06-15 01:31:58 -07003268#if DEBUG_REGISTRATION
Steve Block5baa3a62011-12-20 16:23:08 +00003269 ALOGD("channel '%s' ~ unregisterInputChannel", inputChannel->getName().string());
Jeff Brown9c3cda02010-06-15 01:31:58 -07003270#endif
3271
Jeff Brown46b9ac02010-04-22 18:58:52 -07003272 { // acquire lock
3273 AutoMutex _l(mLock);
3274
Jeff Browncc4f7db2011-08-30 20:34:48 -07003275 status_t status = unregisterInputChannelLocked(inputChannel, false /*notify*/);
3276 if (status) {
3277 return status;
Jeff Brown46b9ac02010-04-22 18:58:52 -07003278 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07003279 } // release lock
3280
Jeff Brown46b9ac02010-04-22 18:58:52 -07003281 // Wake the poll loop because removing the connection may have changed the current
3282 // synchronization state.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07003283 mLooper->wake();
Jeff Brown46b9ac02010-04-22 18:58:52 -07003284 return OK;
3285}
3286
Jeff Browncc4f7db2011-08-30 20:34:48 -07003287status_t InputDispatcher::unregisterInputChannelLocked(const sp<InputChannel>& inputChannel,
3288 bool notify) {
3289 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
3290 if (connectionIndex < 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00003291 ALOGW("Attempted to unregister already unregistered input channel '%s'",
Jeff Browncc4f7db2011-08-30 20:34:48 -07003292 inputChannel->getName().string());
3293 return BAD_VALUE;
3294 }
3295
Jeff Browncbee6d62012-02-03 20:11:27 -08003296 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
3297 mConnectionsByFd.removeItemsAt(connectionIndex);
Jeff Browncc4f7db2011-08-30 20:34:48 -07003298
3299 if (connection->monitor) {
3300 removeMonitorChannelLocked(inputChannel);
3301 }
3302
Jeff Browncbee6d62012-02-03 20:11:27 -08003303 mLooper->removeFd(inputChannel->getFd());
Jeff Browncc4f7db2011-08-30 20:34:48 -07003304
3305 nsecs_t currentTime = now();
3306 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
3307
Jeff Browncc4f7db2011-08-30 20:34:48 -07003308 connection->status = Connection::STATUS_ZOMBIE;
3309 return OK;
3310}
3311
3312void InputDispatcher::removeMonitorChannelLocked(const sp<InputChannel>& inputChannel) {
3313 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
3314 if (mMonitoringChannels[i] == inputChannel) {
3315 mMonitoringChannels.removeAt(i);
3316 break;
3317 }
3318 }
3319}
3320
Jeff Brown519e0242010-09-15 15:18:56 -07003321ssize_t InputDispatcher::getConnectionIndexLocked(const sp<InputChannel>& inputChannel) {
Jeff Browncbee6d62012-02-03 20:11:27 -08003322 ssize_t connectionIndex = mConnectionsByFd.indexOfKey(inputChannel->getFd());
Jeff Brown2cbecea2010-08-17 15:59:26 -07003323 if (connectionIndex >= 0) {
Jeff Browncbee6d62012-02-03 20:11:27 -08003324 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
Jeff Brown2cbecea2010-08-17 15:59:26 -07003325 if (connection->inputChannel.get() == inputChannel.get()) {
3326 return connectionIndex;
3327 }
3328 }
3329
3330 return -1;
3331}
3332
Jeff Brown9c3cda02010-06-15 01:31:58 -07003333void InputDispatcher::onDispatchCycleFinishedLocked(
Jeff Brown072ec962012-02-07 14:46:57 -08003334 nsecs_t currentTime, const sp<Connection>& connection, uint32_t seq, bool handled) {
Jeff Brown3915bb82010-11-05 15:02:16 -07003335 CommandEntry* commandEntry = postCommandLocked(
3336 & InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
3337 commandEntry->connection = connection;
Jeff Brown265f1cc2012-06-11 18:01:06 -07003338 commandEntry->eventTime = currentTime;
Jeff Brown072ec962012-02-07 14:46:57 -08003339 commandEntry->seq = seq;
Jeff Brown3915bb82010-11-05 15:02:16 -07003340 commandEntry->handled = handled;
Jeff Brown46b9ac02010-04-22 18:58:52 -07003341}
3342
Jeff Brown9c3cda02010-06-15 01:31:58 -07003343void InputDispatcher::onDispatchCycleBrokenLocked(
Jeff Brown7fbdc842010-06-17 20:52:56 -07003344 nsecs_t currentTime, const sp<Connection>& connection) {
Steve Block3762c312012-01-06 19:20:56 +00003345 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Jeff Brown46b9ac02010-04-22 18:58:52 -07003346 connection->getInputChannelName());
3347
Jeff Brown9c3cda02010-06-15 01:31:58 -07003348 CommandEntry* commandEntry = postCommandLocked(
3349 & InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
Jeff Brown7fbdc842010-06-17 20:52:56 -07003350 commandEntry->connection = connection;
Jeff Brown46b9ac02010-04-22 18:58:52 -07003351}
3352
Jeff Brown519e0242010-09-15 15:18:56 -07003353void InputDispatcher::onANRLocked(
Jeff Brown9302c872011-07-13 22:51:29 -07003354 nsecs_t currentTime, const sp<InputApplicationHandle>& applicationHandle,
3355 const sp<InputWindowHandle>& windowHandle,
Jeff Brown265f1cc2012-06-11 18:01:06 -07003356 nsecs_t eventTime, nsecs_t waitStartTime, const char* reason) {
Jeff Brown22aa5122012-06-17 12:01:06 -07003357 float dispatchLatency = (currentTime - eventTime) * 0.000001f;
3358 float waitDuration = (currentTime - waitStartTime) * 0.000001f;
Steve Block6215d3f2012-01-04 20:05:49 +00003359 ALOGI("Application is not responding: %s. "
Jeff Brown22aa5122012-06-17 12:01:06 -07003360 "It has been %0.1fms since event, %0.1fms since wait started. Reason: %s",
Jeff Brown9302c872011-07-13 22:51:29 -07003361 getApplicationWindowLabelLocked(applicationHandle, windowHandle).string(),
Jeff Brown22aa5122012-06-17 12:01:06 -07003362 dispatchLatency, waitDuration, reason);
3363
3364 // Capture a record of the InputDispatcher state at the time of the ANR.
3365 time_t t = time(NULL);
3366 struct tm tm;
3367 localtime_r(&t, &tm);
3368 char timestr[64];
3369 strftime(timestr, sizeof(timestr), "%F %T", &tm);
3370 mLastANRState.clear();
3371 mLastANRState.append(INDENT "ANR:\n");
3372 mLastANRState.appendFormat(INDENT2 "Time: %s\n", timestr);
3373 mLastANRState.appendFormat(INDENT2 "Window: %s\n",
3374 getApplicationWindowLabelLocked(applicationHandle, windowHandle).string());
3375 mLastANRState.appendFormat(INDENT2 "DispatchLatency: %0.1fms\n", dispatchLatency);
3376 mLastANRState.appendFormat(INDENT2 "WaitDuration: %0.1fms\n", waitDuration);
3377 mLastANRState.appendFormat(INDENT2 "Reason: %s\n", reason);
3378 dumpDispatchStateLocked(mLastANRState);
Jeff Brown519e0242010-09-15 15:18:56 -07003379
3380 CommandEntry* commandEntry = postCommandLocked(
3381 & InputDispatcher::doNotifyANRLockedInterruptible);
Jeff Brown9302c872011-07-13 22:51:29 -07003382 commandEntry->inputApplicationHandle = applicationHandle;
3383 commandEntry->inputWindowHandle = windowHandle;
Jeff Brown519e0242010-09-15 15:18:56 -07003384}
3385
Jeff Brownb88102f2010-09-08 11:49:43 -07003386void InputDispatcher::doNotifyConfigurationChangedInterruptible(
3387 CommandEntry* commandEntry) {
3388 mLock.unlock();
3389
3390 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
3391
3392 mLock.lock();
3393}
3394
Jeff Brown9c3cda02010-06-15 01:31:58 -07003395void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(
3396 CommandEntry* commandEntry) {
Jeff Brown7fbdc842010-06-17 20:52:56 -07003397 sp<Connection> connection = commandEntry->connection;
Jeff Brown9c3cda02010-06-15 01:31:58 -07003398
Jeff Brown7fbdc842010-06-17 20:52:56 -07003399 if (connection->status != Connection::STATUS_ZOMBIE) {
3400 mLock.unlock();
Jeff Brown9c3cda02010-06-15 01:31:58 -07003401
Jeff Brown928e0542011-01-10 11:17:36 -08003402 mPolicy->notifyInputChannelBroken(connection->inputWindowHandle);
Jeff Brown7fbdc842010-06-17 20:52:56 -07003403
3404 mLock.lock();
3405 }
Jeff Brown9c3cda02010-06-15 01:31:58 -07003406}
3407
Jeff Brown519e0242010-09-15 15:18:56 -07003408void InputDispatcher::doNotifyANRLockedInterruptible(
Jeff Brown9c3cda02010-06-15 01:31:58 -07003409 CommandEntry* commandEntry) {
Jeff Brown519e0242010-09-15 15:18:56 -07003410 mLock.unlock();
Jeff Brown9c3cda02010-06-15 01:31:58 -07003411
Jeff Brown519e0242010-09-15 15:18:56 -07003412 nsecs_t newTimeout = mPolicy->notifyANR(
Jeff Brown928e0542011-01-10 11:17:36 -08003413 commandEntry->inputApplicationHandle, commandEntry->inputWindowHandle);
Jeff Brown9c3cda02010-06-15 01:31:58 -07003414
Jeff Brown519e0242010-09-15 15:18:56 -07003415 mLock.lock();
Jeff Brown7fbdc842010-06-17 20:52:56 -07003416
Jeff Brown9302c872011-07-13 22:51:29 -07003417 resumeAfterTargetsNotReadyTimeoutLocked(newTimeout,
3418 commandEntry->inputWindowHandle != NULL
Jeff Browncc4f7db2011-08-30 20:34:48 -07003419 ? commandEntry->inputWindowHandle->getInputChannel() : NULL);
Jeff Brown9c3cda02010-06-15 01:31:58 -07003420}
3421
Jeff Brownb88102f2010-09-08 11:49:43 -07003422void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
3423 CommandEntry* commandEntry) {
3424 KeyEntry* entry = commandEntry->keyEntry;
Jeff Brown1f245102010-11-18 20:53:46 -08003425
3426 KeyEvent event;
3427 initializeKeyEvent(&event, entry);
Jeff Brownb88102f2010-09-08 11:49:43 -07003428
3429 mLock.unlock();
3430
Jeff Brown905805a2011-10-12 13:57:59 -07003431 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(commandEntry->inputWindowHandle,
Jeff Brown1f245102010-11-18 20:53:46 -08003432 &event, entry->policyFlags);
Jeff Brownb88102f2010-09-08 11:49:43 -07003433
3434 mLock.lock();
3435
Jeff Brown905805a2011-10-12 13:57:59 -07003436 if (delay < 0) {
3437 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
3438 } else if (!delay) {
3439 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
3440 } else {
3441 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
3442 entry->interceptKeyWakeupTime = now() + delay;
3443 }
Jeff Brownac386072011-07-20 15:19:50 -07003444 entry->release();
Jeff Brownb88102f2010-09-08 11:49:43 -07003445}
3446
Jeff Brown3915bb82010-11-05 15:02:16 -07003447void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(
3448 CommandEntry* commandEntry) {
3449 sp<Connection> connection = commandEntry->connection;
Jeff Brown265f1cc2012-06-11 18:01:06 -07003450 nsecs_t finishTime = commandEntry->eventTime;
Jeff Brown072ec962012-02-07 14:46:57 -08003451 uint32_t seq = commandEntry->seq;
Jeff Brown3915bb82010-11-05 15:02:16 -07003452 bool handled = commandEntry->handled;
3453
Jeff Brown072ec962012-02-07 14:46:57 -08003454 // Handle post-event policy actions.
3455 DispatchEntry* dispatchEntry = connection->findWaitQueueEntry(seq);
3456 if (dispatchEntry) {
Jeff Brown265f1cc2012-06-11 18:01:06 -07003457 nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
3458 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
3459 String8 msg;
Jeff Brown22aa5122012-06-17 12:01:06 -07003460 msg.appendFormat("Window '%s' spent %0.1fms processing the last input event: ",
Jeff Brown265f1cc2012-06-11 18:01:06 -07003461 connection->getWindowName(), eventDuration * 0.000001f);
3462 dispatchEntry->eventEntry->appendDescription(msg);
3463 ALOGI("%s", msg.string());
3464 }
3465
Jeff Brownd1c48a02012-02-06 19:12:47 -08003466 bool restartEvent;
Jeff Brownd1c48a02012-02-06 19:12:47 -08003467 if (dispatchEntry->eventEntry->type == EventEntry::TYPE_KEY) {
3468 KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry);
3469 restartEvent = afterKeyEventLockedInterruptible(connection,
3470 dispatchEntry, keyEntry, handled);
3471 } else if (dispatchEntry->eventEntry->type == EventEntry::TYPE_MOTION) {
3472 MotionEntry* motionEntry = static_cast<MotionEntry*>(dispatchEntry->eventEntry);
3473 restartEvent = afterMotionEventLockedInterruptible(connection,
3474 dispatchEntry, motionEntry, handled);
3475 } else {
3476 restartEvent = false;
3477 }
3478
3479 // Dequeue the event and start the next cycle.
3480 // Note that because the lock might have been released, it is possible that the
3481 // contents of the wait queue to have been drained, so we need to double-check
3482 // a few things.
Jeff Brown072ec962012-02-07 14:46:57 -08003483 if (dispatchEntry == connection->findWaitQueueEntry(seq)) {
3484 connection->waitQueue.dequeue(dispatchEntry);
Jeff Brown481c1572012-03-09 14:41:15 -08003485 traceWaitQueueLengthLocked(connection);
Jeff Brownd1c48a02012-02-06 19:12:47 -08003486 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
3487 connection->outboundQueue.enqueueAtHead(dispatchEntry);
Jeff Brown481c1572012-03-09 14:41:15 -08003488 traceOutboundQueueLengthLocked(connection);
Jeff Brownd1c48a02012-02-06 19:12:47 -08003489 } else {
3490 releaseDispatchEntryLocked(dispatchEntry);
Jeff Brown49ed71d2010-12-06 17:13:33 -08003491 }
Jeff Brown3915bb82010-11-05 15:02:16 -07003492 }
Jeff Brown3915bb82010-11-05 15:02:16 -07003493
Jeff Brownd1c48a02012-02-06 19:12:47 -08003494 // Start the next dispatch cycle for this connection.
3495 startDispatchCycleLocked(now(), connection);
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003496 }
3497}
3498
3499bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
3500 DispatchEntry* dispatchEntry, KeyEntry* keyEntry, bool handled) {
3501 if (!(keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK)) {
3502 // Get the fallback key state.
3503 // Clear it out after dispatching the UP.
3504 int32_t originalKeyCode = keyEntry->keyCode;
3505 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
3506 if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
3507 connection->inputState.removeFallbackKey(originalKeyCode);
3508 }
3509
3510 if (handled || !dispatchEntry->hasForegroundTarget()) {
3511 // If the application handles the original key for which we previously
3512 // generated a fallback or if the window is not a foreground window,
3513 // then cancel the associated fallback key, if any.
3514 if (fallbackKeyCode != -1) {
Jeff Brownfd23e3e2012-05-09 13:34:28 -07003515 // Dispatch the unhandled key to the policy with the cancel flag.
3516#if DEBUG_OUTBOUND_EVENT_DETAILS
3517 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
3518 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
3519 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
3520 keyEntry->policyFlags);
3521#endif
3522 KeyEvent event;
3523 initializeKeyEvent(&event, keyEntry);
3524 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
3525
3526 mLock.unlock();
3527
3528 mPolicy->dispatchUnhandledKey(connection->inputWindowHandle,
3529 &event, keyEntry->policyFlags, &event);
3530
3531 mLock.lock();
3532
3533 // Cancel the fallback key.
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003534 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
3535 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
3536 "application handled the original non-fallback key "
3537 "or is no longer a foreground target, "
3538 "canceling previously dispatched fallback key");
3539 options.keyCode = fallbackKeyCode;
3540 synthesizeCancelationEventsForConnectionLocked(connection, options);
3541 }
3542 connection->inputState.removeFallbackKey(originalKeyCode);
3543 }
3544 } else {
3545 // If the application did not handle a non-fallback key, first check
3546 // that we are in a good state to perform unhandled key event processing
3547 // Then ask the policy what to do with it.
3548 bool initialDown = keyEntry->action == AKEY_EVENT_ACTION_DOWN
3549 && keyEntry->repeatCount == 0;
3550 if (fallbackKeyCode == -1 && !initialDown) {
3551#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00003552 ALOGD("Unhandled key event: Skipping unhandled key event processing "
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003553 "since this is not an initial down. "
Jeff Brownfd23e3e2012-05-09 13:34:28 -07003554 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
3555 originalKeyCode, keyEntry->action, keyEntry->repeatCount,
3556 keyEntry->policyFlags);
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003557#endif
3558 return false;
3559 }
3560
3561 // Dispatch the unhandled key to the policy.
3562#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00003563 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
Jeff Brownfd23e3e2012-05-09 13:34:28 -07003564 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
3565 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
3566 keyEntry->policyFlags);
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003567#endif
3568 KeyEvent event;
3569 initializeKeyEvent(&event, keyEntry);
3570
3571 mLock.unlock();
3572
3573 bool fallback = mPolicy->dispatchUnhandledKey(connection->inputWindowHandle,
3574 &event, keyEntry->policyFlags, &event);
3575
3576 mLock.lock();
3577
3578 if (connection->status != Connection::STATUS_NORMAL) {
3579 connection->inputState.removeFallbackKey(originalKeyCode);
Jeff Brownd1c48a02012-02-06 19:12:47 -08003580 return false;
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003581 }
3582
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003583 // Latch the fallback keycode for this key on an initial down.
3584 // The fallback keycode cannot change at any other point in the lifecycle.
3585 if (initialDown) {
3586 if (fallback) {
3587 fallbackKeyCode = event.getKeyCode();
3588 } else {
3589 fallbackKeyCode = AKEYCODE_UNKNOWN;
3590 }
3591 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
3592 }
3593
Steve Blockec193de2012-01-09 18:35:44 +00003594 ALOG_ASSERT(fallbackKeyCode != -1);
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003595
3596 // Cancel the fallback key if the policy decides not to send it anymore.
3597 // We will continue to dispatch the key to the policy but we will no
3598 // longer dispatch a fallback key to the application.
3599 if (fallbackKeyCode != AKEYCODE_UNKNOWN
3600 && (!fallback || fallbackKeyCode != event.getKeyCode())) {
3601#if DEBUG_OUTBOUND_EVENT_DETAILS
3602 if (fallback) {
Steve Block5baa3a62011-12-20 16:23:08 +00003603 ALOGD("Unhandled key event: Policy requested to send key %d"
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003604 "as a fallback for %d, but on the DOWN it had requested "
3605 "to send %d instead. Fallback canceled.",
3606 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
3607 } else {
Jeff Brownfd23e3e2012-05-09 13:34:28 -07003608 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003609 "but on the DOWN it had requested to send %d. "
3610 "Fallback canceled.",
3611 originalKeyCode, fallbackKeyCode);
3612 }
3613#endif
3614
3615 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
3616 "canceling fallback, policy no longer desires it");
3617 options.keyCode = fallbackKeyCode;
3618 synthesizeCancelationEventsForConnectionLocked(connection, options);
3619
3620 fallback = false;
3621 fallbackKeyCode = AKEYCODE_UNKNOWN;
3622 if (keyEntry->action != AKEY_EVENT_ACTION_UP) {
3623 connection->inputState.setFallbackKey(originalKeyCode,
3624 fallbackKeyCode);
3625 }
3626 }
3627
3628#if DEBUG_OUTBOUND_EVENT_DETAILS
3629 {
3630 String8 msg;
3631 const KeyedVector<int32_t, int32_t>& fallbackKeys =
3632 connection->inputState.getFallbackKeys();
3633 for (size_t i = 0; i < fallbackKeys.size(); i++) {
3634 msg.appendFormat(", %d->%d", fallbackKeys.keyAt(i),
3635 fallbackKeys.valueAt(i));
3636 }
Steve Block5baa3a62011-12-20 16:23:08 +00003637 ALOGD("Unhandled key event: %d currently tracked fallback keys%s.",
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003638 fallbackKeys.size(), msg.string());
3639 }
3640#endif
3641
3642 if (fallback) {
3643 // Restart the dispatch cycle using the fallback key.
3644 keyEntry->eventTime = event.getEventTime();
3645 keyEntry->deviceId = event.getDeviceId();
3646 keyEntry->source = event.getSource();
3647 keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
3648 keyEntry->keyCode = fallbackKeyCode;
3649 keyEntry->scanCode = event.getScanCode();
3650 keyEntry->metaState = event.getMetaState();
3651 keyEntry->repeatCount = event.getRepeatCount();
3652 keyEntry->downTime = event.getDownTime();
3653 keyEntry->syntheticRepeat = false;
3654
3655#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00003656 ALOGD("Unhandled key event: Dispatching fallback key. "
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003657 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
3658 originalKeyCode, fallbackKeyCode, keyEntry->metaState);
3659#endif
Jeff Brownd1c48a02012-02-06 19:12:47 -08003660 return true; // restart the event
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003661 } else {
3662#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00003663 ALOGD("Unhandled key event: No fallback key.");
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003664#endif
3665 }
3666 }
3667 }
3668 return false;
3669}
3670
3671bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
3672 DispatchEntry* dispatchEntry, MotionEntry* motionEntry, bool handled) {
3673 return false;
Jeff Brown3915bb82010-11-05 15:02:16 -07003674}
3675
Jeff Brownb88102f2010-09-08 11:49:43 -07003676void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
3677 mLock.unlock();
3678
Jeff Brown01ce2e92010-09-26 22:20:12 -07003679 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
Jeff Brownb88102f2010-09-08 11:49:43 -07003680
3681 mLock.lock();
3682}
3683
Jeff Brown3915bb82010-11-05 15:02:16 -07003684void InputDispatcher::initializeKeyEvent(KeyEvent* event, const KeyEntry* entry) {
3685 event->initialize(entry->deviceId, entry->source, entry->action, entry->flags,
3686 entry->keyCode, entry->scanCode, entry->metaState, entry->repeatCount,
3687 entry->downTime, entry->eventTime);
3688}
3689
Jeff Brown519e0242010-09-15 15:18:56 -07003690void InputDispatcher::updateDispatchStatisticsLocked(nsecs_t currentTime, const EventEntry* entry,
3691 int32_t injectionResult, nsecs_t timeSpentWaitingForApplication) {
3692 // TODO Write some statistics about how long we spend waiting.
Jeff Brownb88102f2010-09-08 11:49:43 -07003693}
3694
Jeff Brown481c1572012-03-09 14:41:15 -08003695void InputDispatcher::traceInboundQueueLengthLocked() {
3696 if (ATRACE_ENABLED()) {
3697 ATRACE_INT("iq", mInboundQueue.count());
3698 }
3699}
3700
3701void InputDispatcher::traceOutboundQueueLengthLocked(const sp<Connection>& connection) {
3702 if (ATRACE_ENABLED()) {
3703 char counterName[40];
3704 snprintf(counterName, sizeof(counterName), "oq:%s", connection->getWindowName());
3705 ATRACE_INT(counterName, connection->outboundQueue.count());
3706 }
3707}
3708
3709void InputDispatcher::traceWaitQueueLengthLocked(const sp<Connection>& connection) {
3710 if (ATRACE_ENABLED()) {
3711 char counterName[40];
3712 snprintf(counterName, sizeof(counterName), "wq:%s", connection->getWindowName());
3713 ATRACE_INT(counterName, connection->waitQueue.count());
3714 }
3715}
3716
Jeff Brownb88102f2010-09-08 11:49:43 -07003717void InputDispatcher::dump(String8& dump) {
Jeff Brown89ef0722011-08-10 16:25:21 -07003718 AutoMutex _l(mLock);
3719
Jeff Brownf2f48712010-10-01 17:46:21 -07003720 dump.append("Input Dispatcher State:\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003721 dumpDispatchStateLocked(dump);
Jeff Brown214eaf42011-05-26 19:17:02 -07003722
Jeff Brown22aa5122012-06-17 12:01:06 -07003723 if (!mLastANRState.isEmpty()) {
3724 dump.append("\nInput Dispatcher State at time of last ANR:\n");
3725 dump.append(mLastANRState);
3726 }
Jeff Brownb88102f2010-09-08 11:49:43 -07003727}
3728
Jeff Brown89ef0722011-08-10 16:25:21 -07003729void InputDispatcher::monitor() {
3730 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
3731 mLock.lock();
Jeff Brown112b5f52012-01-27 17:32:06 -08003732 mLooper->wake();
3733 mDispatcherIsAliveCondition.wait(mLock);
Jeff Brown89ef0722011-08-10 16:25:21 -07003734 mLock.unlock();
3735}
3736
Jeff Brown9c3cda02010-06-15 01:31:58 -07003737
Jeff Brown519e0242010-09-15 15:18:56 -07003738// --- InputDispatcher::Queue ---
3739
3740template <typename T>
3741uint32_t InputDispatcher::Queue<T>::count() const {
3742 uint32_t result = 0;
Jeff Brownac386072011-07-20 15:19:50 -07003743 for (const T* entry = head; entry; entry = entry->next) {
Jeff Brown519e0242010-09-15 15:18:56 -07003744 result += 1;
3745 }
3746 return result;
3747}
3748
3749
Jeff Brownac386072011-07-20 15:19:50 -07003750// --- InputDispatcher::InjectionState ---
Jeff Brown46b9ac02010-04-22 18:58:52 -07003751
Jeff Brownac386072011-07-20 15:19:50 -07003752InputDispatcher::InjectionState::InjectionState(int32_t injectorPid, int32_t injectorUid) :
3753 refCount(1),
3754 injectorPid(injectorPid), injectorUid(injectorUid),
3755 injectionResult(INPUT_EVENT_INJECTION_PENDING), injectionIsAsync(false),
3756 pendingForegroundDispatches(0) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07003757}
3758
Jeff Brownac386072011-07-20 15:19:50 -07003759InputDispatcher::InjectionState::~InjectionState() {
Jeff Brown01ce2e92010-09-26 22:20:12 -07003760}
3761
Jeff Brownac386072011-07-20 15:19:50 -07003762void InputDispatcher::InjectionState::release() {
3763 refCount -= 1;
3764 if (refCount == 0) {
3765 delete this;
3766 } else {
Steve Blockec193de2012-01-09 18:35:44 +00003767 ALOG_ASSERT(refCount > 0);
Jeff Brown01ce2e92010-09-26 22:20:12 -07003768 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07003769}
3770
Jeff Brownac386072011-07-20 15:19:50 -07003771
3772// --- InputDispatcher::EventEntry ---
3773
3774InputDispatcher::EventEntry::EventEntry(int32_t type, nsecs_t eventTime, uint32_t policyFlags) :
3775 refCount(1), type(type), eventTime(eventTime), policyFlags(policyFlags),
3776 injectionState(NULL), dispatchInProgress(false) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07003777}
3778
Jeff Brownac386072011-07-20 15:19:50 -07003779InputDispatcher::EventEntry::~EventEntry() {
3780 releaseInjectionState();
3781}
3782
3783void InputDispatcher::EventEntry::release() {
3784 refCount -= 1;
3785 if (refCount == 0) {
3786 delete this;
3787 } else {
Steve Blockec193de2012-01-09 18:35:44 +00003788 ALOG_ASSERT(refCount > 0);
Jeff Brownac386072011-07-20 15:19:50 -07003789 }
3790}
3791
3792void InputDispatcher::EventEntry::releaseInjectionState() {
3793 if (injectionState) {
3794 injectionState->release();
3795 injectionState = NULL;
3796 }
3797}
3798
3799
3800// --- InputDispatcher::ConfigurationChangedEntry ---
3801
3802InputDispatcher::ConfigurationChangedEntry::ConfigurationChangedEntry(nsecs_t eventTime) :
3803 EventEntry(TYPE_CONFIGURATION_CHANGED, eventTime, 0) {
3804}
3805
3806InputDispatcher::ConfigurationChangedEntry::~ConfigurationChangedEntry() {
3807}
3808
Jeff Brown265f1cc2012-06-11 18:01:06 -07003809void InputDispatcher::ConfigurationChangedEntry::appendDescription(String8& msg) const {
3810 msg.append("ConfigurationChangedEvent()");
3811}
3812
Jeff Brownac386072011-07-20 15:19:50 -07003813
Jeff Brown65fd2512011-08-18 11:20:58 -07003814// --- InputDispatcher::DeviceResetEntry ---
3815
3816InputDispatcher::DeviceResetEntry::DeviceResetEntry(nsecs_t eventTime, int32_t deviceId) :
3817 EventEntry(TYPE_DEVICE_RESET, eventTime, 0),
3818 deviceId(deviceId) {
3819}
3820
3821InputDispatcher::DeviceResetEntry::~DeviceResetEntry() {
3822}
3823
Jeff Brown265f1cc2012-06-11 18:01:06 -07003824void InputDispatcher::DeviceResetEntry::appendDescription(String8& msg) const {
3825 msg.appendFormat("DeviceResetEvent(deviceId=%d)", deviceId);
3826}
3827
Jeff Brown65fd2512011-08-18 11:20:58 -07003828
Jeff Brownac386072011-07-20 15:19:50 -07003829// --- InputDispatcher::KeyEntry ---
3830
3831InputDispatcher::KeyEntry::KeyEntry(nsecs_t eventTime,
Jeff Brown58a2da82011-01-25 16:02:22 -08003832 int32_t deviceId, uint32_t source, uint32_t policyFlags, int32_t action,
Jeff Brown7fbdc842010-06-17 20:52:56 -07003833 int32_t flags, int32_t keyCode, int32_t scanCode, int32_t metaState,
Jeff Brownac386072011-07-20 15:19:50 -07003834 int32_t repeatCount, nsecs_t downTime) :
3835 EventEntry(TYPE_KEY, eventTime, policyFlags),
3836 deviceId(deviceId), source(source), action(action), flags(flags),
3837 keyCode(keyCode), scanCode(scanCode), metaState(metaState),
3838 repeatCount(repeatCount), downTime(downTime),
Jeff Brown905805a2011-10-12 13:57:59 -07003839 syntheticRepeat(false), interceptKeyResult(KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN),
3840 interceptKeyWakeupTime(0) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07003841}
3842
Jeff Brownac386072011-07-20 15:19:50 -07003843InputDispatcher::KeyEntry::~KeyEntry() {
3844}
Jeff Brown7fbdc842010-06-17 20:52:56 -07003845
Jeff Brown265f1cc2012-06-11 18:01:06 -07003846void InputDispatcher::KeyEntry::appendDescription(String8& msg) const {
3847 msg.appendFormat("KeyEvent(action=%d, deviceId=%d, source=0x%08x)",
3848 action, deviceId, source);
3849}
3850
Jeff Brownac386072011-07-20 15:19:50 -07003851void InputDispatcher::KeyEntry::recycle() {
3852 releaseInjectionState();
3853
3854 dispatchInProgress = false;
3855 syntheticRepeat = false;
3856 interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
Jeff Brown905805a2011-10-12 13:57:59 -07003857 interceptKeyWakeupTime = 0;
Jeff Brownac386072011-07-20 15:19:50 -07003858}
3859
3860
Jeff Brownae9fc032010-08-18 15:51:08 -07003861// --- InputDispatcher::MotionEntry ---
3862
Jeff Brownac386072011-07-20 15:19:50 -07003863InputDispatcher::MotionEntry::MotionEntry(nsecs_t eventTime,
3864 int32_t deviceId, uint32_t source, uint32_t policyFlags, int32_t action, int32_t flags,
3865 int32_t metaState, int32_t buttonState,
3866 int32_t edgeFlags, float xPrecision, float yPrecision,
Jeff Brown83d616a2012-09-09 20:33:43 -07003867 nsecs_t downTime, int32_t displayId, uint32_t pointerCount,
Jeff Brownac386072011-07-20 15:19:50 -07003868 const PointerProperties* pointerProperties, const PointerCoords* pointerCoords) :
3869 EventEntry(TYPE_MOTION, eventTime, policyFlags),
Jeff Brown3241b6b2012-02-03 15:08:02 -08003870 eventTime(eventTime),
Jeff Brownac386072011-07-20 15:19:50 -07003871 deviceId(deviceId), source(source), action(action), flags(flags),
3872 metaState(metaState), buttonState(buttonState), edgeFlags(edgeFlags),
3873 xPrecision(xPrecision), yPrecision(yPrecision),
Jeff Brown83d616a2012-09-09 20:33:43 -07003874 downTime(downTime), displayId(displayId), pointerCount(pointerCount) {
Jeff Brownac386072011-07-20 15:19:50 -07003875 for (uint32_t i = 0; i < pointerCount; i++) {
3876 this->pointerProperties[i].copyFrom(pointerProperties[i]);
Jeff Brown3241b6b2012-02-03 15:08:02 -08003877 this->pointerCoords[i].copyFrom(pointerCoords[i]);
Jeff Brownac386072011-07-20 15:19:50 -07003878 }
3879}
3880
3881InputDispatcher::MotionEntry::~MotionEntry() {
Jeff Brownac386072011-07-20 15:19:50 -07003882}
3883
Jeff Brown265f1cc2012-06-11 18:01:06 -07003884void InputDispatcher::MotionEntry::appendDescription(String8& msg) const {
Jeff Brown83d616a2012-09-09 20:33:43 -07003885 msg.appendFormat("MotionEvent(action=%d, deviceId=%d, source=0x%08x, displayId=%d)",
3886 action, deviceId, source, displayId);
Jeff Brown265f1cc2012-06-11 18:01:06 -07003887}
3888
Jeff Brownac386072011-07-20 15:19:50 -07003889
3890// --- InputDispatcher::DispatchEntry ---
3891
Jeff Brown072ec962012-02-07 14:46:57 -08003892volatile int32_t InputDispatcher::DispatchEntry::sNextSeqAtomic;
3893
Jeff Brownac386072011-07-20 15:19:50 -07003894InputDispatcher::DispatchEntry::DispatchEntry(EventEntry* eventEntry,
3895 int32_t targetFlags, float xOffset, float yOffset, float scaleFactor) :
Jeff Brown072ec962012-02-07 14:46:57 -08003896 seq(nextSeq()),
Jeff Brownac386072011-07-20 15:19:50 -07003897 eventEntry(eventEntry), targetFlags(targetFlags),
3898 xOffset(xOffset), yOffset(yOffset), scaleFactor(scaleFactor),
Jeff Brown265f1cc2012-06-11 18:01:06 -07003899 deliveryTime(0), resolvedAction(0), resolvedFlags(0) {
Jeff Brownac386072011-07-20 15:19:50 -07003900 eventEntry->refCount += 1;
3901}
3902
3903InputDispatcher::DispatchEntry::~DispatchEntry() {
3904 eventEntry->release();
3905}
3906
Jeff Brown072ec962012-02-07 14:46:57 -08003907uint32_t InputDispatcher::DispatchEntry::nextSeq() {
3908 // Sequence number 0 is reserved and will never be returned.
3909 uint32_t seq;
3910 do {
3911 seq = android_atomic_inc(&sNextSeqAtomic);
3912 } while (!seq);
3913 return seq;
3914}
3915
Jeff Brownb88102f2010-09-08 11:49:43 -07003916
3917// --- InputDispatcher::InputState ---
3918
Jeff Brownb6997262010-10-08 22:31:17 -07003919InputDispatcher::InputState::InputState() {
Jeff Brownb88102f2010-09-08 11:49:43 -07003920}
3921
3922InputDispatcher::InputState::~InputState() {
3923}
3924
3925bool InputDispatcher::InputState::isNeutral() const {
3926 return mKeyMementos.isEmpty() && mMotionMementos.isEmpty();
3927}
3928
Jeff Brown83d616a2012-09-09 20:33:43 -07003929bool InputDispatcher::InputState::isHovering(int32_t deviceId, uint32_t source,
3930 int32_t displayId) const {
Jeff Brown81346812011-06-28 20:08:48 -07003931 for (size_t i = 0; i < mMotionMementos.size(); i++) {
3932 const MotionMemento& memento = mMotionMementos.itemAt(i);
3933 if (memento.deviceId == deviceId
3934 && memento.source == source
Jeff Brown83d616a2012-09-09 20:33:43 -07003935 && memento.displayId == displayId
Jeff Brown81346812011-06-28 20:08:48 -07003936 && memento.hovering) {
3937 return true;
3938 }
3939 }
3940 return false;
3941}
Jeff Brownb88102f2010-09-08 11:49:43 -07003942
Jeff Brown81346812011-06-28 20:08:48 -07003943bool InputDispatcher::InputState::trackKey(const KeyEntry* entry,
3944 int32_t action, int32_t flags) {
3945 switch (action) {
3946 case AKEY_EVENT_ACTION_UP: {
3947 if (entry->flags & AKEY_EVENT_FLAG_FALLBACK) {
3948 for (size_t i = 0; i < mFallbackKeys.size(); ) {
3949 if (mFallbackKeys.valueAt(i) == entry->keyCode) {
3950 mFallbackKeys.removeItemsAt(i);
3951 } else {
3952 i += 1;
3953 }
3954 }
3955 }
3956 ssize_t index = findKeyMemento(entry);
3957 if (index >= 0) {
3958 mKeyMementos.removeAt(index);
3959 return true;
3960 }
Jeff Brown68b909d2011-12-07 16:36:01 -08003961 /* FIXME: We can't just drop the key up event because that prevents creating
3962 * popup windows that are automatically shown when a key is held and then
3963 * dismissed when the key is released. The problem is that the popup will
3964 * not have received the original key down, so the key up will be considered
3965 * to be inconsistent with its observed state. We could perhaps handle this
3966 * by synthesizing a key down but that will cause other problems.
3967 *
3968 * So for now, allow inconsistent key up events to be dispatched.
3969 *
Jeff Brown81346812011-06-28 20:08:48 -07003970#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00003971 ALOGD("Dropping inconsistent key up event: deviceId=%d, source=%08x, "
Jeff Brown81346812011-06-28 20:08:48 -07003972 "keyCode=%d, scanCode=%d",
3973 entry->deviceId, entry->source, entry->keyCode, entry->scanCode);
3974#endif
3975 return false;
Jeff Brown68b909d2011-12-07 16:36:01 -08003976 */
3977 return true;
Jeff Brown81346812011-06-28 20:08:48 -07003978 }
3979
3980 case AKEY_EVENT_ACTION_DOWN: {
3981 ssize_t index = findKeyMemento(entry);
3982 if (index >= 0) {
3983 mKeyMementos.removeAt(index);
3984 }
3985 addKeyMemento(entry, flags);
3986 return true;
3987 }
3988
3989 default:
3990 return true;
Jeff Brownb88102f2010-09-08 11:49:43 -07003991 }
3992}
3993
Jeff Brown81346812011-06-28 20:08:48 -07003994bool InputDispatcher::InputState::trackMotion(const MotionEntry* entry,
3995 int32_t action, int32_t flags) {
3996 int32_t actionMasked = action & AMOTION_EVENT_ACTION_MASK;
3997 switch (actionMasked) {
3998 case AMOTION_EVENT_ACTION_UP:
3999 case AMOTION_EVENT_ACTION_CANCEL: {
4000 ssize_t index = findMotionMemento(entry, false /*hovering*/);
4001 if (index >= 0) {
4002 mMotionMementos.removeAt(index);
4003 return true;
Jeff Brownda3d5a92011-03-29 15:11:34 -07004004 }
Jeff Brown81346812011-06-28 20:08:48 -07004005#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00004006 ALOGD("Dropping inconsistent motion up or cancel event: deviceId=%d, source=%08x, "
Jeff Brown81346812011-06-28 20:08:48 -07004007 "actionMasked=%d",
4008 entry->deviceId, entry->source, actionMasked);
4009#endif
4010 return false;
Jeff Brownda3d5a92011-03-29 15:11:34 -07004011 }
4012
Jeff Brown81346812011-06-28 20:08:48 -07004013 case AMOTION_EVENT_ACTION_DOWN: {
4014 ssize_t index = findMotionMemento(entry, false /*hovering*/);
4015 if (index >= 0) {
4016 mMotionMementos.removeAt(index);
4017 }
4018 addMotionMemento(entry, flags, false /*hovering*/);
4019 return true;
4020 }
4021
4022 case AMOTION_EVENT_ACTION_POINTER_UP:
4023 case AMOTION_EVENT_ACTION_POINTER_DOWN:
4024 case AMOTION_EVENT_ACTION_MOVE: {
4025 ssize_t index = findMotionMemento(entry, false /*hovering*/);
4026 if (index >= 0) {
4027 MotionMemento& memento = mMotionMementos.editItemAt(index);
4028 memento.setPointers(entry);
4029 return true;
4030 }
Jeff Brown2e45fb62011-06-29 21:19:05 -07004031 if (actionMasked == AMOTION_EVENT_ACTION_MOVE
4032 && (entry->source & (AINPUT_SOURCE_CLASS_JOYSTICK
4033 | AINPUT_SOURCE_CLASS_NAVIGATION))) {
4034 // Joysticks and trackballs can send MOVE events without corresponding DOWN or UP.
4035 return true;
4036 }
Jeff Brown81346812011-06-28 20:08:48 -07004037#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00004038 ALOGD("Dropping inconsistent motion pointer up/down or move event: "
Jeff Brown81346812011-06-28 20:08:48 -07004039 "deviceId=%d, source=%08x, actionMasked=%d",
4040 entry->deviceId, entry->source, actionMasked);
4041#endif
4042 return false;
4043 }
4044
4045 case AMOTION_EVENT_ACTION_HOVER_EXIT: {
4046 ssize_t index = findMotionMemento(entry, true /*hovering*/);
4047 if (index >= 0) {
4048 mMotionMementos.removeAt(index);
4049 return true;
4050 }
4051#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00004052 ALOGD("Dropping inconsistent motion hover exit event: deviceId=%d, source=%08x",
Jeff Brown81346812011-06-28 20:08:48 -07004053 entry->deviceId, entry->source);
4054#endif
4055 return false;
4056 }
4057
4058 case AMOTION_EVENT_ACTION_HOVER_ENTER:
4059 case AMOTION_EVENT_ACTION_HOVER_MOVE: {
4060 ssize_t index = findMotionMemento(entry, true /*hovering*/);
4061 if (index >= 0) {
4062 mMotionMementos.removeAt(index);
4063 }
4064 addMotionMemento(entry, flags, true /*hovering*/);
4065 return true;
4066 }
4067
4068 default:
4069 return true;
4070 }
4071}
4072
4073ssize_t InputDispatcher::InputState::findKeyMemento(const KeyEntry* entry) const {
Jeff Brownb88102f2010-09-08 11:49:43 -07004074 for (size_t i = 0; i < mKeyMementos.size(); i++) {
Jeff Brown81346812011-06-28 20:08:48 -07004075 const KeyMemento& memento = mKeyMementos.itemAt(i);
Jeff Brownb88102f2010-09-08 11:49:43 -07004076 if (memento.deviceId == entry->deviceId
4077 && memento.source == entry->source
4078 && memento.keyCode == entry->keyCode
4079 && memento.scanCode == entry->scanCode) {
Jeff Brown81346812011-06-28 20:08:48 -07004080 return i;
Jeff Brownb88102f2010-09-08 11:49:43 -07004081 }
4082 }
Jeff Brown81346812011-06-28 20:08:48 -07004083 return -1;
Jeff Brownb88102f2010-09-08 11:49:43 -07004084}
4085
Jeff Brown81346812011-06-28 20:08:48 -07004086ssize_t InputDispatcher::InputState::findMotionMemento(const MotionEntry* entry,
4087 bool hovering) const {
Jeff Brownb88102f2010-09-08 11:49:43 -07004088 for (size_t i = 0; i < mMotionMementos.size(); i++) {
Jeff Brown81346812011-06-28 20:08:48 -07004089 const MotionMemento& memento = mMotionMementos.itemAt(i);
Jeff Brownb88102f2010-09-08 11:49:43 -07004090 if (memento.deviceId == entry->deviceId
Jeff Brown81346812011-06-28 20:08:48 -07004091 && memento.source == entry->source
Jeff Brown83d616a2012-09-09 20:33:43 -07004092 && memento.displayId == entry->displayId
Jeff Brown81346812011-06-28 20:08:48 -07004093 && memento.hovering == hovering) {
4094 return i;
Jeff Brownb88102f2010-09-08 11:49:43 -07004095 }
4096 }
Jeff Brown81346812011-06-28 20:08:48 -07004097 return -1;
4098}
Jeff Brownb88102f2010-09-08 11:49:43 -07004099
Jeff Brown81346812011-06-28 20:08:48 -07004100void InputDispatcher::InputState::addKeyMemento(const KeyEntry* entry, int32_t flags) {
4101 mKeyMementos.push();
4102 KeyMemento& memento = mKeyMementos.editTop();
4103 memento.deviceId = entry->deviceId;
4104 memento.source = entry->source;
4105 memento.keyCode = entry->keyCode;
4106 memento.scanCode = entry->scanCode;
Jeff Brownfd23e3e2012-05-09 13:34:28 -07004107 memento.metaState = entry->metaState;
Jeff Brown81346812011-06-28 20:08:48 -07004108 memento.flags = flags;
4109 memento.downTime = entry->downTime;
Jeff Brownfd23e3e2012-05-09 13:34:28 -07004110 memento.policyFlags = entry->policyFlags;
Jeff Brown81346812011-06-28 20:08:48 -07004111}
4112
4113void InputDispatcher::InputState::addMotionMemento(const MotionEntry* entry,
4114 int32_t flags, bool hovering) {
4115 mMotionMementos.push();
4116 MotionMemento& memento = mMotionMementos.editTop();
4117 memento.deviceId = entry->deviceId;
4118 memento.source = entry->source;
4119 memento.flags = flags;
4120 memento.xPrecision = entry->xPrecision;
4121 memento.yPrecision = entry->yPrecision;
4122 memento.downTime = entry->downTime;
Jeff Brown83d616a2012-09-09 20:33:43 -07004123 memento.displayId = entry->displayId;
Jeff Brown81346812011-06-28 20:08:48 -07004124 memento.setPointers(entry);
4125 memento.hovering = hovering;
Jeff Brownfd23e3e2012-05-09 13:34:28 -07004126 memento.policyFlags = entry->policyFlags;
Jeff Brownb88102f2010-09-08 11:49:43 -07004127}
4128
4129void InputDispatcher::InputState::MotionMemento::setPointers(const MotionEntry* entry) {
4130 pointerCount = entry->pointerCount;
4131 for (uint32_t i = 0; i < entry->pointerCount; i++) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07004132 pointerProperties[i].copyFrom(entry->pointerProperties[i]);
Jeff Brown3241b6b2012-02-03 15:08:02 -08004133 pointerCoords[i].copyFrom(entry->pointerCoords[i]);
Jeff Brownb88102f2010-09-08 11:49:43 -07004134 }
4135}
4136
Jeff Brownb6997262010-10-08 22:31:17 -07004137void InputDispatcher::InputState::synthesizeCancelationEvents(nsecs_t currentTime,
Jeff Brownac386072011-07-20 15:19:50 -07004138 Vector<EventEntry*>& outEvents, const CancelationOptions& options) {
Jeff Brown81346812011-06-28 20:08:48 -07004139 for (size_t i = 0; i < mKeyMementos.size(); i++) {
Jeff Brownb88102f2010-09-08 11:49:43 -07004140 const KeyMemento& memento = mKeyMementos.itemAt(i);
Jeff Brown49ed71d2010-12-06 17:13:33 -08004141 if (shouldCancelKey(memento, options)) {
Jeff Brownac386072011-07-20 15:19:50 -07004142 outEvents.push(new KeyEntry(currentTime,
Jeff Brownfd23e3e2012-05-09 13:34:28 -07004143 memento.deviceId, memento.source, memento.policyFlags,
Jeff Brown49ed71d2010-12-06 17:13:33 -08004144 AKEY_EVENT_ACTION_UP, memento.flags | AKEY_EVENT_FLAG_CANCELED,
Jeff Brownfd23e3e2012-05-09 13:34:28 -07004145 memento.keyCode, memento.scanCode, memento.metaState, 0, memento.downTime));
Jeff Brownb6997262010-10-08 22:31:17 -07004146 }
Jeff Brownb88102f2010-09-08 11:49:43 -07004147 }
4148
Jeff Brown81346812011-06-28 20:08:48 -07004149 for (size_t i = 0; i < mMotionMementos.size(); i++) {
Jeff Brownb88102f2010-09-08 11:49:43 -07004150 const MotionMemento& memento = mMotionMementos.itemAt(i);
Jeff Brown49ed71d2010-12-06 17:13:33 -08004151 if (shouldCancelMotion(memento, options)) {
Jeff Brownac386072011-07-20 15:19:50 -07004152 outEvents.push(new MotionEntry(currentTime,
Jeff Brownfd23e3e2012-05-09 13:34:28 -07004153 memento.deviceId, memento.source, memento.policyFlags,
Jeff Browna032cc02011-03-07 16:56:21 -08004154 memento.hovering
4155 ? AMOTION_EVENT_ACTION_HOVER_EXIT
4156 : AMOTION_EVENT_ACTION_CANCEL,
Jeff Brown81346812011-06-28 20:08:48 -07004157 memento.flags, 0, 0, 0,
Jeff Brownb6997262010-10-08 22:31:17 -07004158 memento.xPrecision, memento.yPrecision, memento.downTime,
Jeff Brown83d616a2012-09-09 20:33:43 -07004159 memento.displayId,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07004160 memento.pointerCount, memento.pointerProperties, memento.pointerCoords));
Jeff Brownb6997262010-10-08 22:31:17 -07004161 }
Jeff Brownb88102f2010-09-08 11:49:43 -07004162 }
4163}
4164
4165void InputDispatcher::InputState::clear() {
4166 mKeyMementos.clear();
4167 mMotionMementos.clear();
Jeff Brownda3d5a92011-03-29 15:11:34 -07004168 mFallbackKeys.clear();
Jeff Brownb6997262010-10-08 22:31:17 -07004169}
4170
Jeff Brown9c9f1a32010-10-11 18:32:20 -07004171void InputDispatcher::InputState::copyPointerStateTo(InputState& other) const {
4172 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4173 const MotionMemento& memento = mMotionMementos.itemAt(i);
4174 if (memento.source & AINPUT_SOURCE_CLASS_POINTER) {
4175 for (size_t j = 0; j < other.mMotionMementos.size(); ) {
4176 const MotionMemento& otherMemento = other.mMotionMementos.itemAt(j);
4177 if (memento.deviceId == otherMemento.deviceId
Jeff Brown83d616a2012-09-09 20:33:43 -07004178 && memento.source == otherMemento.source
4179 && memento.displayId == otherMemento.displayId) {
Jeff Brown9c9f1a32010-10-11 18:32:20 -07004180 other.mMotionMementos.removeAt(j);
4181 } else {
4182 j += 1;
4183 }
4184 }
4185 other.mMotionMementos.push(memento);
4186 }
4187 }
4188}
4189
Jeff Brownda3d5a92011-03-29 15:11:34 -07004190int32_t InputDispatcher::InputState::getFallbackKey(int32_t originalKeyCode) {
4191 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
4192 return index >= 0 ? mFallbackKeys.valueAt(index) : -1;
4193}
4194
4195void InputDispatcher::InputState::setFallbackKey(int32_t originalKeyCode,
4196 int32_t fallbackKeyCode) {
4197 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
4198 if (index >= 0) {
4199 mFallbackKeys.replaceValueAt(index, fallbackKeyCode);
4200 } else {
4201 mFallbackKeys.add(originalKeyCode, fallbackKeyCode);
4202 }
4203}
4204
4205void InputDispatcher::InputState::removeFallbackKey(int32_t originalKeyCode) {
4206 mFallbackKeys.removeItem(originalKeyCode);
4207}
4208
Jeff Brown49ed71d2010-12-06 17:13:33 -08004209bool InputDispatcher::InputState::shouldCancelKey(const KeyMemento& memento,
Jeff Brownda3d5a92011-03-29 15:11:34 -07004210 const CancelationOptions& options) {
4211 if (options.keyCode != -1 && memento.keyCode != options.keyCode) {
4212 return false;
4213 }
4214
Jeff Brown65fd2512011-08-18 11:20:58 -07004215 if (options.deviceId != -1 && memento.deviceId != options.deviceId) {
4216 return false;
4217 }
4218
Jeff Brownda3d5a92011-03-29 15:11:34 -07004219 switch (options.mode) {
4220 case CancelationOptions::CANCEL_ALL_EVENTS:
4221 case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
Jeff Brownb6997262010-10-08 22:31:17 -07004222 return true;
Jeff Brownda3d5a92011-03-29 15:11:34 -07004223 case CancelationOptions::CANCEL_FALLBACK_EVENTS:
Jeff Brown49ed71d2010-12-06 17:13:33 -08004224 return memento.flags & AKEY_EVENT_FLAG_FALLBACK;
4225 default:
4226 return false;
4227 }
4228}
4229
4230bool InputDispatcher::InputState::shouldCancelMotion(const MotionMemento& memento,
Jeff Brownda3d5a92011-03-29 15:11:34 -07004231 const CancelationOptions& options) {
Jeff Brown65fd2512011-08-18 11:20:58 -07004232 if (options.deviceId != -1 && memento.deviceId != options.deviceId) {
4233 return false;
4234 }
4235
Jeff Brownda3d5a92011-03-29 15:11:34 -07004236 switch (options.mode) {
4237 case CancelationOptions::CANCEL_ALL_EVENTS:
Jeff Brown49ed71d2010-12-06 17:13:33 -08004238 return true;
Jeff Brownda3d5a92011-03-29 15:11:34 -07004239 case CancelationOptions::CANCEL_POINTER_EVENTS:
Jeff Brown49ed71d2010-12-06 17:13:33 -08004240 return memento.source & AINPUT_SOURCE_CLASS_POINTER;
Jeff Brownda3d5a92011-03-29 15:11:34 -07004241 case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
Jeff Brown49ed71d2010-12-06 17:13:33 -08004242 return !(memento.source & AINPUT_SOURCE_CLASS_POINTER);
4243 default:
4244 return false;
Jeff Brownb6997262010-10-08 22:31:17 -07004245 }
Jeff Brownb88102f2010-09-08 11:49:43 -07004246}
4247
4248
Jeff Brown46b9ac02010-04-22 18:58:52 -07004249// --- InputDispatcher::Connection ---
4250
Jeff Brown928e0542011-01-10 11:17:36 -08004251InputDispatcher::Connection::Connection(const sp<InputChannel>& inputChannel,
Jeff Browncc4f7db2011-08-30 20:34:48 -07004252 const sp<InputWindowHandle>& inputWindowHandle, bool monitor) :
Jeff Brown928e0542011-01-10 11:17:36 -08004253 status(STATUS_NORMAL), inputChannel(inputChannel), inputWindowHandle(inputWindowHandle),
Jeff Browncc4f7db2011-08-30 20:34:48 -07004254 monitor(monitor),
Jeff Brownd1c48a02012-02-06 19:12:47 -08004255 inputPublisher(inputChannel), inputPublisherBlocked(false) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07004256}
4257
4258InputDispatcher::Connection::~Connection() {
4259}
4260
Jeff Brown481c1572012-03-09 14:41:15 -08004261const char* InputDispatcher::Connection::getWindowName() const {
4262 if (inputWindowHandle != NULL) {
4263 return inputWindowHandle->getName().string();
4264 }
4265 if (monitor) {
4266 return "monitor";
4267 }
4268 return "?";
4269}
4270
Jeff Brown9c3cda02010-06-15 01:31:58 -07004271const char* InputDispatcher::Connection::getStatusLabel() const {
4272 switch (status) {
4273 case STATUS_NORMAL:
4274 return "NORMAL";
4275
4276 case STATUS_BROKEN:
4277 return "BROKEN";
4278
Jeff Brown9c3cda02010-06-15 01:31:58 -07004279 case STATUS_ZOMBIE:
4280 return "ZOMBIE";
4281
4282 default:
4283 return "UNKNOWN";
4284 }
4285}
4286
Jeff Brown072ec962012-02-07 14:46:57 -08004287InputDispatcher::DispatchEntry* InputDispatcher::Connection::findWaitQueueEntry(uint32_t seq) {
4288 for (DispatchEntry* entry = waitQueue.head; entry != NULL; entry = entry->next) {
4289 if (entry->seq == seq) {
4290 return entry;
4291 }
4292 }
4293 return NULL;
4294}
4295
Jeff Brownb88102f2010-09-08 11:49:43 -07004296
Jeff Brown9c3cda02010-06-15 01:31:58 -07004297// --- InputDispatcher::CommandEntry ---
4298
Jeff Brownac386072011-07-20 15:19:50 -07004299InputDispatcher::CommandEntry::CommandEntry(Command command) :
Jeff Brown072ec962012-02-07 14:46:57 -08004300 command(command), eventTime(0), keyEntry(NULL), userActivityEventType(0),
4301 seq(0), handled(false) {
Jeff Brown9c3cda02010-06-15 01:31:58 -07004302}
4303
4304InputDispatcher::CommandEntry::~CommandEntry() {
4305}
4306
Jeff Brown46b9ac02010-04-22 18:58:52 -07004307
Jeff Brown01ce2e92010-09-26 22:20:12 -07004308// --- InputDispatcher::TouchState ---
4309
4310InputDispatcher::TouchState::TouchState() :
Jeff Brown83d616a2012-09-09 20:33:43 -07004311 down(false), split(false), deviceId(-1), source(0), displayId(-1) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07004312}
4313
4314InputDispatcher::TouchState::~TouchState() {
4315}
4316
4317void InputDispatcher::TouchState::reset() {
4318 down = false;
4319 split = false;
Jeff Brown95712852011-01-04 19:41:59 -08004320 deviceId = -1;
Jeff Brown58a2da82011-01-25 16:02:22 -08004321 source = 0;
Jeff Brown83d616a2012-09-09 20:33:43 -07004322 displayId = -1;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004323 windows.clear();
4324}
4325
4326void InputDispatcher::TouchState::copyFrom(const TouchState& other) {
4327 down = other.down;
4328 split = other.split;
Jeff Brown95712852011-01-04 19:41:59 -08004329 deviceId = other.deviceId;
Jeff Brown58a2da82011-01-25 16:02:22 -08004330 source = other.source;
Jeff Brown83d616a2012-09-09 20:33:43 -07004331 displayId = other.displayId;
Jeff Brown9302c872011-07-13 22:51:29 -07004332 windows = other.windows;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004333}
4334
Jeff Brown9302c872011-07-13 22:51:29 -07004335void InputDispatcher::TouchState::addOrUpdateWindow(const sp<InputWindowHandle>& windowHandle,
Jeff Brown01ce2e92010-09-26 22:20:12 -07004336 int32_t targetFlags, BitSet32 pointerIds) {
4337 if (targetFlags & InputTarget::FLAG_SPLIT) {
4338 split = true;
4339 }
4340
4341 for (size_t i = 0; i < windows.size(); i++) {
4342 TouchedWindow& touchedWindow = windows.editItemAt(i);
Jeff Brown9302c872011-07-13 22:51:29 -07004343 if (touchedWindow.windowHandle == windowHandle) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07004344 touchedWindow.targetFlags |= targetFlags;
Jeff Brown98db5fa2011-06-08 15:37:10 -07004345 if (targetFlags & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
4346 touchedWindow.targetFlags &= ~InputTarget::FLAG_DISPATCH_AS_IS;
4347 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07004348 touchedWindow.pointerIds.value |= pointerIds.value;
4349 return;
4350 }
4351 }
4352
4353 windows.push();
4354
4355 TouchedWindow& touchedWindow = windows.editTop();
Jeff Brown9302c872011-07-13 22:51:29 -07004356 touchedWindow.windowHandle = windowHandle;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004357 touchedWindow.targetFlags = targetFlags;
4358 touchedWindow.pointerIds = pointerIds;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004359}
4360
Jeff Brownf44e3942012-04-20 11:33:27 -07004361void InputDispatcher::TouchState::removeWindow(const sp<InputWindowHandle>& windowHandle) {
4362 for (size_t i = 0; i < windows.size(); i++) {
4363 if (windows.itemAt(i).windowHandle == windowHandle) {
4364 windows.removeAt(i);
4365 return;
4366 }
4367 }
4368}
4369
Jeff Browna032cc02011-03-07 16:56:21 -08004370void InputDispatcher::TouchState::filterNonAsIsTouchWindows() {
Jeff Brown01ce2e92010-09-26 22:20:12 -07004371 for (size_t i = 0 ; i < windows.size(); ) {
Jeff Browna032cc02011-03-07 16:56:21 -08004372 TouchedWindow& window = windows.editItemAt(i);
Jeff Brown98db5fa2011-06-08 15:37:10 -07004373 if (window.targetFlags & (InputTarget::FLAG_DISPATCH_AS_IS
4374 | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER)) {
Jeff Browna032cc02011-03-07 16:56:21 -08004375 window.targetFlags &= ~InputTarget::FLAG_DISPATCH_MASK;
4376 window.targetFlags |= InputTarget::FLAG_DISPATCH_AS_IS;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004377 i += 1;
Jeff Browna032cc02011-03-07 16:56:21 -08004378 } else {
4379 windows.removeAt(i);
Jeff Brown01ce2e92010-09-26 22:20:12 -07004380 }
4381 }
4382}
4383
Jeff Brown9302c872011-07-13 22:51:29 -07004384sp<InputWindowHandle> InputDispatcher::TouchState::getFirstForegroundWindowHandle() const {
Jeff Brown01ce2e92010-09-26 22:20:12 -07004385 for (size_t i = 0; i < windows.size(); i++) {
Jeff Brown98db5fa2011-06-08 15:37:10 -07004386 const TouchedWindow& window = windows.itemAt(i);
4387 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
Jeff Brown9302c872011-07-13 22:51:29 -07004388 return window.windowHandle;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004389 }
4390 }
4391 return NULL;
4392}
4393
Jeff Brown98db5fa2011-06-08 15:37:10 -07004394bool InputDispatcher::TouchState::isSlippery() const {
4395 // Must have exactly one foreground window.
4396 bool haveSlipperyForegroundWindow = false;
4397 for (size_t i = 0; i < windows.size(); i++) {
4398 const TouchedWindow& window = windows.itemAt(i);
4399 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
Jeff Browncc4f7db2011-08-30 20:34:48 -07004400 if (haveSlipperyForegroundWindow
4401 || !(window.windowHandle->getInfo()->layoutParamsFlags
4402 & InputWindowInfo::FLAG_SLIPPERY)) {
Jeff Brown98db5fa2011-06-08 15:37:10 -07004403 return false;
4404 }
4405 haveSlipperyForegroundWindow = true;
4406 }
4407 }
4408 return haveSlipperyForegroundWindow;
4409}
4410
Jeff Brown01ce2e92010-09-26 22:20:12 -07004411
Jeff Brown46b9ac02010-04-22 18:58:52 -07004412// --- InputDispatcherThread ---
4413
4414InputDispatcherThread::InputDispatcherThread(const sp<InputDispatcherInterface>& dispatcher) :
4415 Thread(/*canCallJava*/ true), mDispatcher(dispatcher) {
4416}
4417
4418InputDispatcherThread::~InputDispatcherThread() {
4419}
4420
4421bool InputDispatcherThread::threadLoop() {
4422 mDispatcher->dispatchOnce();
4423 return true;
4424}
4425
4426} // namespace android