blob: 7862e172ea90fd045dc4cb91d3b0d7a80cb0bf06 [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 Brownf2f487182010-10-01 17:46:21 -070058#define INDENT " "
59#define INDENT2 " "
Jeff Brown265f1cc2012-06-11 18:01:06 -070060#define INDENT3 " "
61#define INDENT4 " "
Jeff Brownf2f487182010-10-01 17:46:21 -070062
Jeff 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 Brown214eaf42011-05-26 19:17:02 -0700227 dispatchOnceInnerLocked(&nextWakeupTime);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700228
Jeff Brownb88102f2010-09-08 11:49:43 -0700229 if (runCommandsLockedInterruptible()) {
230 nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
Jeff Brown46b9ac02010-04-22 18:58:52 -0700231 }
Jeff Brown46b9ac02010-04-22 18:58:52 -0700232 } // release lock
233
Jeff Brownb88102f2010-09-08 11:49:43 -0700234 // Wait for callback or timeout or wake. (make sure we round up, not down)
235 nsecs_t currentTime = now();
Jeff Brownaa3855d2011-03-17 01:34:19 -0700236 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
Jeff Brown4fe6c3e2010-09-13 23:17:30 -0700237 mLooper->pollOnce(timeoutMillis);
Jeff Brownb88102f2010-09-08 11:49:43 -0700238}
239
Jeff Brown214eaf42011-05-26 19:17:02 -0700240void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700241 nsecs_t currentTime = now();
242
243 // Reset the key repeat timer whenever we disallow key events, even if the next event
244 // is not a key. This is to ensure that we abort a key repeat if the device is just coming
245 // out of sleep.
Jeff Brown214eaf42011-05-26 19:17:02 -0700246 if (!mPolicy->isKeyRepeatEnabled()) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700247 resetKeyRepeatLocked();
248 }
249
Jeff Brownb88102f2010-09-08 11:49:43 -0700250 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
251 if (mDispatchFrozen) {
252#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +0000253 ALOGD("Dispatch frozen. Waiting some more.");
Jeff Brownb88102f2010-09-08 11:49:43 -0700254#endif
255 return;
256 }
257
258 // Optimize latency of app switches.
259 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
260 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
261 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
262 if (mAppSwitchDueTime < *nextWakeupTime) {
263 *nextWakeupTime = mAppSwitchDueTime;
264 }
265
Jeff Brownb88102f2010-09-08 11:49:43 -0700266 // Ready to start a new event.
267 // If we don't already have a pending event, go grab one.
268 if (! mPendingEvent) {
269 if (mInboundQueue.isEmpty()) {
270 if (isAppSwitchDue) {
271 // The inbound queue is empty so the app switch key we were waiting
272 // for will never arrive. Stop waiting for it.
273 resetPendingAppSwitchLocked(false);
274 isAppSwitchDue = false;
275 }
276
277 // Synthesize a key repeat if appropriate.
278 if (mKeyRepeatState.lastKeyEntry) {
279 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
Jeff Brown214eaf42011-05-26 19:17:02 -0700280 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700281 } else {
282 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
283 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
284 }
285 }
286 }
Jeff Browncc4f7db2011-08-30 20:34:48 -0700287
288 // Nothing to do if there is no pending event.
Jeff Browne9bb9be2012-02-06 15:47:55 -0800289 if (!mPendingEvent) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700290 return;
291 }
292 } else {
293 // Inbound queue has at least one entry.
Jeff Browne9bb9be2012-02-06 15:47:55 -0800294 mPendingEvent = mInboundQueue.dequeueAtHead();
Jeff Brown481c1572012-03-09 14:41:15 -0800295 traceInboundQueueLengthLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -0700296 }
Jeff Browne2fe69e2010-10-18 13:21:23 -0700297
298 // Poke user activity for this event.
299 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
300 pokeUserActivityLocked(mPendingEvent);
301 }
Jeff Browne9bb9be2012-02-06 15:47:55 -0800302
303 // Get ready to dispatch the event.
304 resetANRTimeoutsLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -0700305 }
306
307 // Now we have an event to dispatch.
Jeff Brown928e0542011-01-10 11:17:36 -0800308 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Steve Blockec193de2012-01-09 18:35:44 +0000309 ALOG_ASSERT(mPendingEvent != NULL);
Jeff Brown54a18252010-09-16 14:07:33 -0700310 bool done = false;
Jeff Brownb6997262010-10-08 22:31:17 -0700311 DropReason dropReason = DROP_REASON_NOT_DROPPED;
312 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
313 dropReason = DROP_REASON_POLICY;
314 } else if (!mDispatchEnabled) {
315 dropReason = DROP_REASON_DISABLED;
316 }
Jeff Brown928e0542011-01-10 11:17:36 -0800317
318 if (mNextUnblockedEvent == mPendingEvent) {
319 mNextUnblockedEvent = NULL;
320 }
321
Jeff Brownb88102f2010-09-08 11:49:43 -0700322 switch (mPendingEvent->type) {
323 case EventEntry::TYPE_CONFIGURATION_CHANGED: {
324 ConfigurationChangedEntry* typedEntry =
325 static_cast<ConfigurationChangedEntry*>(mPendingEvent);
Jeff Brown54a18252010-09-16 14:07:33 -0700326 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Jeff Brownb6997262010-10-08 22:31:17 -0700327 dropReason = DROP_REASON_NOT_DROPPED; // configuration changes are never dropped
Jeff Brownb88102f2010-09-08 11:49:43 -0700328 break;
329 }
330
Jeff Brown65fd2512011-08-18 11:20:58 -0700331 case EventEntry::TYPE_DEVICE_RESET: {
332 DeviceResetEntry* typedEntry =
333 static_cast<DeviceResetEntry*>(mPendingEvent);
334 done = dispatchDeviceResetLocked(currentTime, typedEntry);
335 dropReason = DROP_REASON_NOT_DROPPED; // device resets are never dropped
336 break;
337 }
338
Jeff Brownb88102f2010-09-08 11:49:43 -0700339 case EventEntry::TYPE_KEY: {
340 KeyEntry* typedEntry = static_cast<KeyEntry*>(mPendingEvent);
Jeff Brownb6997262010-10-08 22:31:17 -0700341 if (isAppSwitchDue) {
342 if (isAppSwitchKeyEventLocked(typedEntry)) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700343 resetPendingAppSwitchLocked(true);
Jeff Brownb6997262010-10-08 22:31:17 -0700344 isAppSwitchDue = false;
345 } else if (dropReason == DROP_REASON_NOT_DROPPED) {
346 dropReason = DROP_REASON_APP_SWITCH;
Jeff Brownb88102f2010-09-08 11:49:43 -0700347 }
348 }
Jeff Brown928e0542011-01-10 11:17:36 -0800349 if (dropReason == DROP_REASON_NOT_DROPPED
350 && isStaleEventLocked(currentTime, typedEntry)) {
351 dropReason = DROP_REASON_STALE;
352 }
353 if (dropReason == DROP_REASON_NOT_DROPPED && mNextUnblockedEvent) {
354 dropReason = DROP_REASON_BLOCKED;
355 }
Jeff Brown214eaf42011-05-26 19:17:02 -0700356 done = dispatchKeyLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700357 break;
358 }
359
360 case EventEntry::TYPE_MOTION: {
361 MotionEntry* typedEntry = static_cast<MotionEntry*>(mPendingEvent);
Jeff Brownb6997262010-10-08 22:31:17 -0700362 if (dropReason == DROP_REASON_NOT_DROPPED && isAppSwitchDue) {
363 dropReason = DROP_REASON_APP_SWITCH;
Jeff Brownb88102f2010-09-08 11:49:43 -0700364 }
Jeff Brown928e0542011-01-10 11:17:36 -0800365 if (dropReason == DROP_REASON_NOT_DROPPED
366 && isStaleEventLocked(currentTime, typedEntry)) {
367 dropReason = DROP_REASON_STALE;
368 }
369 if (dropReason == DROP_REASON_NOT_DROPPED && mNextUnblockedEvent) {
370 dropReason = DROP_REASON_BLOCKED;
371 }
Jeff Brownb6997262010-10-08 22:31:17 -0700372 done = dispatchMotionLocked(currentTime, typedEntry,
Jeff Browne20c9e02010-10-11 14:20:19 -0700373 &dropReason, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700374 break;
375 }
376
377 default:
Steve Blockec193de2012-01-09 18:35:44 +0000378 ALOG_ASSERT(false);
Jeff Brownb88102f2010-09-08 11:49:43 -0700379 break;
380 }
381
Jeff Brown54a18252010-09-16 14:07:33 -0700382 if (done) {
Jeff Brownb6997262010-10-08 22:31:17 -0700383 if (dropReason != DROP_REASON_NOT_DROPPED) {
384 dropInboundEventLocked(mPendingEvent, dropReason);
385 }
386
Jeff Brown54a18252010-09-16 14:07:33 -0700387 releasePendingEventLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -0700388 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
389 }
390}
391
392bool InputDispatcher::enqueueInboundEventLocked(EventEntry* entry) {
393 bool needWake = mInboundQueue.isEmpty();
394 mInboundQueue.enqueueAtTail(entry);
Jeff Brown481c1572012-03-09 14:41:15 -0800395 traceInboundQueueLengthLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -0700396
397 switch (entry->type) {
Jeff Brownb6997262010-10-08 22:31:17 -0700398 case EventEntry::TYPE_KEY: {
Jeff Brown928e0542011-01-10 11:17:36 -0800399 // Optimize app switch latency.
400 // If the application takes too long to catch up then we drop all events preceding
401 // the app switch key.
Jeff Brownb6997262010-10-08 22:31:17 -0700402 KeyEntry* keyEntry = static_cast<KeyEntry*>(entry);
403 if (isAppSwitchKeyEventLocked(keyEntry)) {
404 if (keyEntry->action == AKEY_EVENT_ACTION_DOWN) {
405 mAppSwitchSawKeyDown = true;
406 } else if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
407 if (mAppSwitchSawKeyDown) {
408#if DEBUG_APP_SWITCH
Steve Block5baa3a62011-12-20 16:23:08 +0000409 ALOGD("App switch is pending!");
Jeff Brownb6997262010-10-08 22:31:17 -0700410#endif
411 mAppSwitchDueTime = keyEntry->eventTime + APP_SWITCH_TIMEOUT;
412 mAppSwitchSawKeyDown = false;
413 needWake = true;
414 }
415 }
416 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700417 break;
418 }
Jeff Brown928e0542011-01-10 11:17:36 -0800419
420 case EventEntry::TYPE_MOTION: {
421 // Optimize case where the current application is unresponsive and the user
422 // decides to touch a window in a different application.
423 // If the application takes too long to catch up then we drop all events preceding
424 // the touch into the other window.
425 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
Jeff Brown33bbfd22011-02-24 20:55:35 -0800426 if (motionEntry->action == AMOTION_EVENT_ACTION_DOWN
Jeff Brown928e0542011-01-10 11:17:36 -0800427 && (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER)
428 && mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY
Jeff Brown9302c872011-07-13 22:51:29 -0700429 && mInputTargetWaitApplicationHandle != NULL) {
Jeff Brown83d616a2012-09-09 20:33:43 -0700430 int32_t displayId = motionEntry->displayId;
Jeff Brown3241b6b2012-02-03 15:08:02 -0800431 int32_t x = int32_t(motionEntry->pointerCoords[0].
Jeff Brownebbd5d12011-02-17 13:01:34 -0800432 getAxisValue(AMOTION_EVENT_AXIS_X));
Jeff Brown3241b6b2012-02-03 15:08:02 -0800433 int32_t y = int32_t(motionEntry->pointerCoords[0].
Jeff Brownebbd5d12011-02-17 13:01:34 -0800434 getAxisValue(AMOTION_EVENT_AXIS_Y));
Jeff Brown83d616a2012-09-09 20:33:43 -0700435 sp<InputWindowHandle> touchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y);
Jeff Brown9302c872011-07-13 22:51:29 -0700436 if (touchedWindowHandle != NULL
437 && touchedWindowHandle->inputApplicationHandle
438 != mInputTargetWaitApplicationHandle) {
Jeff Brown928e0542011-01-10 11:17:36 -0800439 // User touched a different application than the one we are waiting on.
440 // Flag the event, and start pruning the input queue.
441 mNextUnblockedEvent = motionEntry;
442 needWake = true;
443 }
444 }
445 break;
446 }
Jeff Brownb6997262010-10-08 22:31:17 -0700447 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700448
449 return needWake;
450}
451
Jeff Brown83d616a2012-09-09 20:33:43 -0700452sp<InputWindowHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId,
453 int32_t x, int32_t y) {
Jeff Brown928e0542011-01-10 11:17:36 -0800454 // Traverse windows from front to back to find touched window.
Jeff Brown9302c872011-07-13 22:51:29 -0700455 size_t numWindows = mWindowHandles.size();
Jeff Brown928e0542011-01-10 11:17:36 -0800456 for (size_t i = 0; i < numWindows; i++) {
Jeff Brown9302c872011-07-13 22:51:29 -0700457 sp<InputWindowHandle> windowHandle = mWindowHandles.itemAt(i);
Jeff Browncc4f7db2011-08-30 20:34:48 -0700458 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Jeff Brown83d616a2012-09-09 20:33:43 -0700459 if (windowInfo->displayId == displayId) {
460 int32_t flags = windowInfo->layoutParamsFlags;
Jeff Brown928e0542011-01-10 11:17:36 -0800461
Jeff Brown83d616a2012-09-09 20:33:43 -0700462 if (windowInfo->visible) {
463 if (!(flags & InputWindowInfo::FLAG_NOT_TOUCHABLE)) {
464 bool isTouchModal = (flags & (InputWindowInfo::FLAG_NOT_FOCUSABLE
465 | InputWindowInfo::FLAG_NOT_TOUCH_MODAL)) == 0;
466 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
467 // Found window.
468 return windowHandle;
469 }
Jeff Brown928e0542011-01-10 11:17:36 -0800470 }
471 }
Jeff Brown928e0542011-01-10 11:17:36 -0800472
Jeff Brown83d616a2012-09-09 20:33:43 -0700473 if (flags & InputWindowInfo::FLAG_SYSTEM_ERROR) {
474 // Error window is on top but not visible, so touch is dropped.
475 return NULL;
476 }
Jeff Brown928e0542011-01-10 11:17:36 -0800477 }
478 }
479 return NULL;
480}
481
Jeff Brownb6997262010-10-08 22:31:17 -0700482void InputDispatcher::dropInboundEventLocked(EventEntry* entry, DropReason dropReason) {
483 const char* reason;
484 switch (dropReason) {
485 case DROP_REASON_POLICY:
Jeff Browne20c9e02010-10-11 14:20:19 -0700486#if DEBUG_INBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +0000487 ALOGD("Dropped event because policy consumed it.");
Jeff Browne20c9e02010-10-11 14:20:19 -0700488#endif
Jeff Brown3122e442010-10-11 23:32:49 -0700489 reason = "inbound event was dropped because the policy consumed it";
Jeff Brownb6997262010-10-08 22:31:17 -0700490 break;
491 case DROP_REASON_DISABLED:
Steve Block6215d3f2012-01-04 20:05:49 +0000492 ALOGI("Dropped event because input dispatch is disabled.");
Jeff Brownb6997262010-10-08 22:31:17 -0700493 reason = "inbound event was dropped because input dispatch is disabled";
494 break;
495 case DROP_REASON_APP_SWITCH:
Steve Block6215d3f2012-01-04 20:05:49 +0000496 ALOGI("Dropped event because of pending overdue app switch.");
Jeff Brownb6997262010-10-08 22:31:17 -0700497 reason = "inbound event was dropped because of pending overdue app switch";
498 break;
Jeff Brown928e0542011-01-10 11:17:36 -0800499 case DROP_REASON_BLOCKED:
Steve Block6215d3f2012-01-04 20:05:49 +0000500 ALOGI("Dropped event because the current application is not responding and the user "
Jeff Brown81346812011-06-28 20:08:48 -0700501 "has started interacting with a different application.");
Jeff Brown928e0542011-01-10 11:17:36 -0800502 reason = "inbound event was dropped because the current application is not responding "
Jeff Brown81346812011-06-28 20:08:48 -0700503 "and the user has started interacting with a different application";
Jeff Brown928e0542011-01-10 11:17:36 -0800504 break;
505 case DROP_REASON_STALE:
Steve Block6215d3f2012-01-04 20:05:49 +0000506 ALOGI("Dropped event because it is stale.");
Jeff Brown928e0542011-01-10 11:17:36 -0800507 reason = "inbound event was dropped because it is stale";
508 break;
Jeff Brownb6997262010-10-08 22:31:17 -0700509 default:
Steve Blockec193de2012-01-09 18:35:44 +0000510 ALOG_ASSERT(false);
Jeff Brownb6997262010-10-08 22:31:17 -0700511 return;
512 }
513
514 switch (entry->type) {
Jeff Brownda3d5a92011-03-29 15:11:34 -0700515 case EventEntry::TYPE_KEY: {
516 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
517 synthesizeCancelationEventsForAllConnectionsLocked(options);
Jeff Brownb6997262010-10-08 22:31:17 -0700518 break;
Jeff Brownda3d5a92011-03-29 15:11:34 -0700519 }
Jeff Brownb6997262010-10-08 22:31:17 -0700520 case EventEntry::TYPE_MOTION: {
521 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
522 if (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) {
Jeff Brownda3d5a92011-03-29 15:11:34 -0700523 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
524 synthesizeCancelationEventsForAllConnectionsLocked(options);
Jeff Brownb6997262010-10-08 22:31:17 -0700525 } else {
Jeff Brownda3d5a92011-03-29 15:11:34 -0700526 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
527 synthesizeCancelationEventsForAllConnectionsLocked(options);
Jeff Brownb6997262010-10-08 22:31:17 -0700528 }
529 break;
530 }
531 }
532}
533
534bool InputDispatcher::isAppSwitchKeyCode(int32_t keyCode) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700535 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL;
536}
537
Jeff Brownb6997262010-10-08 22:31:17 -0700538bool InputDispatcher::isAppSwitchKeyEventLocked(KeyEntry* keyEntry) {
539 return ! (keyEntry->flags & AKEY_EVENT_FLAG_CANCELED)
540 && isAppSwitchKeyCode(keyEntry->keyCode)
Jeff Browne20c9e02010-10-11 14:20:19 -0700541 && (keyEntry->policyFlags & POLICY_FLAG_TRUSTED)
Jeff Brownb6997262010-10-08 22:31:17 -0700542 && (keyEntry->policyFlags & POLICY_FLAG_PASS_TO_USER);
543}
544
Jeff Brownb88102f2010-09-08 11:49:43 -0700545bool InputDispatcher::isAppSwitchPendingLocked() {
546 return mAppSwitchDueTime != LONG_LONG_MAX;
547}
548
Jeff Brownb88102f2010-09-08 11:49:43 -0700549void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
550 mAppSwitchDueTime = LONG_LONG_MAX;
551
552#if DEBUG_APP_SWITCH
553 if (handled) {
Steve Block5baa3a62011-12-20 16:23:08 +0000554 ALOGD("App switch has arrived.");
Jeff Brownb88102f2010-09-08 11:49:43 -0700555 } else {
Steve Block5baa3a62011-12-20 16:23:08 +0000556 ALOGD("App switch was abandoned.");
Jeff Brownb88102f2010-09-08 11:49:43 -0700557 }
558#endif
Jeff Brown46b9ac02010-04-22 18:58:52 -0700559}
560
Jeff Brown928e0542011-01-10 11:17:36 -0800561bool InputDispatcher::isStaleEventLocked(nsecs_t currentTime, EventEntry* entry) {
562 return currentTime - entry->eventTime >= STALE_EVENT_TIMEOUT;
563}
564
Jeff Brown9c3cda02010-06-15 01:31:58 -0700565bool InputDispatcher::runCommandsLockedInterruptible() {
566 if (mCommandQueue.isEmpty()) {
567 return false;
568 }
Jeff Brown46b9ac02010-04-22 18:58:52 -0700569
Jeff Brown9c3cda02010-06-15 01:31:58 -0700570 do {
571 CommandEntry* commandEntry = mCommandQueue.dequeueAtHead();
572
573 Command command = commandEntry->command;
574 (this->*command)(commandEntry); // commands are implicitly 'LockedInterruptible'
575
Jeff Brown7fbdc842010-06-17 20:52:56 -0700576 commandEntry->connection.clear();
Jeff Brownac386072011-07-20 15:19:50 -0700577 delete commandEntry;
Jeff Brown9c3cda02010-06-15 01:31:58 -0700578 } while (! mCommandQueue.isEmpty());
579 return true;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700580}
581
Jeff Brown9c3cda02010-06-15 01:31:58 -0700582InputDispatcher::CommandEntry* InputDispatcher::postCommandLocked(Command command) {
Jeff Brownac386072011-07-20 15:19:50 -0700583 CommandEntry* commandEntry = new CommandEntry(command);
Jeff Brown9c3cda02010-06-15 01:31:58 -0700584 mCommandQueue.enqueueAtTail(commandEntry);
585 return commandEntry;
586}
587
Jeff Brownb88102f2010-09-08 11:49:43 -0700588void InputDispatcher::drainInboundQueueLocked() {
589 while (! mInboundQueue.isEmpty()) {
590 EventEntry* entry = mInboundQueue.dequeueAtHead();
Jeff Brown54a18252010-09-16 14:07:33 -0700591 releaseInboundEventLocked(entry);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700592 }
Jeff Brown481c1572012-03-09 14:41:15 -0800593 traceInboundQueueLengthLocked();
Jeff Brown46b9ac02010-04-22 18:58:52 -0700594}
595
Jeff Brown54a18252010-09-16 14:07:33 -0700596void InputDispatcher::releasePendingEventLocked() {
Jeff Brownb88102f2010-09-08 11:49:43 -0700597 if (mPendingEvent) {
Jeff Browne9bb9be2012-02-06 15:47:55 -0800598 resetANRTimeoutsLocked();
Jeff Brown54a18252010-09-16 14:07:33 -0700599 releaseInboundEventLocked(mPendingEvent);
Jeff Brownb88102f2010-09-08 11:49:43 -0700600 mPendingEvent = NULL;
601 }
602}
603
Jeff Brown54a18252010-09-16 14:07:33 -0700604void InputDispatcher::releaseInboundEventLocked(EventEntry* entry) {
Jeff Brown01ce2e92010-09-26 22:20:12 -0700605 InjectionState* injectionState = entry->injectionState;
606 if (injectionState && injectionState->injectionResult == INPUT_EVENT_INJECTION_PENDING) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700607#if DEBUG_DISPATCH_CYCLE
Steve Block5baa3a62011-12-20 16:23:08 +0000608 ALOGD("Injected inbound event was dropped.");
Jeff Brownb88102f2010-09-08 11:49:43 -0700609#endif
610 setInjectionResultLocked(entry, INPUT_EVENT_INJECTION_FAILED);
611 }
Jeff Brownabb4d442011-08-15 12:55:32 -0700612 if (entry == mNextUnblockedEvent) {
613 mNextUnblockedEvent = NULL;
614 }
Jeff Brownac386072011-07-20 15:19:50 -0700615 entry->release();
Jeff Brownb88102f2010-09-08 11:49:43 -0700616}
617
Jeff Brownb88102f2010-09-08 11:49:43 -0700618void InputDispatcher::resetKeyRepeatLocked() {
619 if (mKeyRepeatState.lastKeyEntry) {
Jeff Brownac386072011-07-20 15:19:50 -0700620 mKeyRepeatState.lastKeyEntry->release();
Jeff Brownb88102f2010-09-08 11:49:43 -0700621 mKeyRepeatState.lastKeyEntry = NULL;
622 }
623}
624
Jeff Brown214eaf42011-05-26 19:17:02 -0700625InputDispatcher::KeyEntry* InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
Jeff Brown349703e2010-06-22 01:27:15 -0700626 KeyEntry* entry = mKeyRepeatState.lastKeyEntry;
627
Jeff Brown349703e2010-06-22 01:27:15 -0700628 // Reuse the repeated key entry if it is otherwise unreferenced.
Jeff Browne20c9e02010-10-11 14:20:19 -0700629 uint32_t policyFlags = (entry->policyFlags & POLICY_FLAG_RAW_MASK)
630 | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700631 if (entry->refCount == 1) {
Jeff Brownac386072011-07-20 15:19:50 -0700632 entry->recycle();
Jeff Brown7fbdc842010-06-17 20:52:56 -0700633 entry->eventTime = currentTime;
Jeff Brown7fbdc842010-06-17 20:52:56 -0700634 entry->policyFlags = policyFlags;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700635 entry->repeatCount += 1;
636 } else {
Jeff Brownac386072011-07-20 15:19:50 -0700637 KeyEntry* newEntry = new KeyEntry(currentTime,
Jeff Brownc5ed5912010-07-14 18:48:53 -0700638 entry->deviceId, entry->source, policyFlags,
Jeff Brown7fbdc842010-06-17 20:52:56 -0700639 entry->action, entry->flags, entry->keyCode, entry->scanCode,
Jeff Brown00fa7bd2010-07-02 15:37:36 -0700640 entry->metaState, entry->repeatCount + 1, entry->downTime);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700641
642 mKeyRepeatState.lastKeyEntry = newEntry;
Jeff Brownac386072011-07-20 15:19:50 -0700643 entry->release();
Jeff Brown46b9ac02010-04-22 18:58:52 -0700644
645 entry = newEntry;
646 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700647 entry->syntheticRepeat = true;
648
649 // Increment reference count since we keep a reference to the event in
650 // mKeyRepeatState.lastKeyEntry in addition to the one we return.
651 entry->refCount += 1;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700652
Jeff Brown214eaf42011-05-26 19:17:02 -0700653 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Jeff Brownb88102f2010-09-08 11:49:43 -0700654 return entry;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700655}
656
Jeff Brownb88102f2010-09-08 11:49:43 -0700657bool InputDispatcher::dispatchConfigurationChangedLocked(
658 nsecs_t currentTime, ConfigurationChangedEntry* entry) {
Jeff Brown46b9ac02010-04-22 18:58:52 -0700659#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +0000660 ALOGD("dispatchConfigurationChanged - eventTime=%lld", entry->eventTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700661#endif
662
663 // Reset key repeating in case a keyboard device was added or removed or something.
664 resetKeyRepeatLocked();
665
666 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
667 CommandEntry* commandEntry = postCommandLocked(
668 & InputDispatcher::doNotifyConfigurationChangedInterruptible);
669 commandEntry->eventTime = entry->eventTime;
670 return true;
671}
672
Jeff Brown65fd2512011-08-18 11:20:58 -0700673bool InputDispatcher::dispatchDeviceResetLocked(
674 nsecs_t currentTime, DeviceResetEntry* entry) {
675#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +0000676 ALOGD("dispatchDeviceReset - eventTime=%lld, deviceId=%d", entry->eventTime, entry->deviceId);
Jeff Brown65fd2512011-08-18 11:20:58 -0700677#endif
678
679 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
680 "device was reset");
681 options.deviceId = entry->deviceId;
682 synthesizeCancelationEventsForAllConnectionsLocked(options);
683 return true;
684}
685
Jeff Brown214eaf42011-05-26 19:17:02 -0700686bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, KeyEntry* entry,
Jeff Browne20c9e02010-10-11 14:20:19 -0700687 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Jeff Browne46a0a42010-11-02 17:58:22 -0700688 // Preprocessing.
689 if (! entry->dispatchInProgress) {
690 if (entry->repeatCount == 0
691 && entry->action == AKEY_EVENT_ACTION_DOWN
692 && (entry->policyFlags & POLICY_FLAG_TRUSTED)
Jeff Brown0029c662011-03-30 02:25:18 -0700693 && (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
Jeff Browne46a0a42010-11-02 17:58:22 -0700694 if (mKeyRepeatState.lastKeyEntry
695 && mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode) {
696 // We have seen two identical key downs in a row which indicates that the device
697 // driver is automatically generating key repeats itself. We take note of the
698 // repeat here, but we disable our own next key repeat timer since it is clear that
699 // we will not need to synthesize key repeats ourselves.
700 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
701 resetKeyRepeatLocked();
702 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
703 } else {
704 // Not a repeat. Save key down state in case we do see a repeat later.
705 resetKeyRepeatLocked();
Jeff Brown214eaf42011-05-26 19:17:02 -0700706 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
Jeff Browne46a0a42010-11-02 17:58:22 -0700707 }
708 mKeyRepeatState.lastKeyEntry = entry;
709 entry->refCount += 1;
710 } else if (! entry->syntheticRepeat) {
711 resetKeyRepeatLocked();
712 }
713
Jeff Browne2e01262011-03-02 20:34:30 -0800714 if (entry->repeatCount == 1) {
715 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
716 } else {
717 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
718 }
719
Jeff Browne46a0a42010-11-02 17:58:22 -0700720 entry->dispatchInProgress = true;
Jeff Browne46a0a42010-11-02 17:58:22 -0700721
722 logOutboundKeyDetailsLocked("dispatchKey - ", entry);
723 }
724
Jeff Brown905805a2011-10-12 13:57:59 -0700725 // Handle case where the policy asked us to try again later last time.
726 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
727 if (currentTime < entry->interceptKeyWakeupTime) {
728 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
729 *nextWakeupTime = entry->interceptKeyWakeupTime;
730 }
731 return false; // wait until next wakeup
732 }
733 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
734 entry->interceptKeyWakeupTime = 0;
735 }
736
Jeff Brown54a18252010-09-16 14:07:33 -0700737 // Give the policy a chance to intercept the key.
738 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
Jeff Browne20c9e02010-10-11 14:20:19 -0700739 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Jeff Brown54a18252010-09-16 14:07:33 -0700740 CommandEntry* commandEntry = postCommandLocked(
741 & InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
Jeff Brown9302c872011-07-13 22:51:29 -0700742 if (mFocusedWindowHandle != NULL) {
743 commandEntry->inputWindowHandle = mFocusedWindowHandle;
Jeff Brown54a18252010-09-16 14:07:33 -0700744 }
745 commandEntry->keyEntry = entry;
746 entry->refCount += 1;
747 return false; // wait for the command to run
748 } else {
749 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
750 }
751 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Jeff Browne20c9e02010-10-11 14:20:19 -0700752 if (*dropReason == DROP_REASON_NOT_DROPPED) {
753 *dropReason = DROP_REASON_POLICY;
754 }
Jeff Brown54a18252010-09-16 14:07:33 -0700755 }
756
757 // Clean up if dropping the event.
Jeff Browne20c9e02010-10-11 14:20:19 -0700758 if (*dropReason != DROP_REASON_NOT_DROPPED) {
Jeff Brown3122e442010-10-11 23:32:49 -0700759 setInjectionResultLocked(entry, *dropReason == DROP_REASON_POLICY
760 ? INPUT_EVENT_INJECTION_SUCCEEDED : INPUT_EVENT_INJECTION_FAILED);
Jeff Brown54a18252010-09-16 14:07:33 -0700761 return true;
762 }
763
Jeff Brownb88102f2010-09-08 11:49:43 -0700764 // Identify targets.
Jeff Browne9bb9be2012-02-06 15:47:55 -0800765 Vector<InputTarget> inputTargets;
766 int32_t injectionResult = findFocusedWindowTargetsLocked(currentTime,
767 entry, inputTargets, nextWakeupTime);
768 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
769 return false;
Jeff Brownb88102f2010-09-08 11:49:43 -0700770 }
771
Jeff Browne9bb9be2012-02-06 15:47:55 -0800772 setInjectionResultLocked(entry, injectionResult);
773 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
774 return true;
775 }
776
777 addMonitoringTargetsLocked(inputTargets);
778
Jeff Brownb88102f2010-09-08 11:49:43 -0700779 // Dispatch the key.
Jeff Browne9bb9be2012-02-06 15:47:55 -0800780 dispatchEventLocked(currentTime, entry, inputTargets);
Jeff Brownb88102f2010-09-08 11:49:43 -0700781 return true;
782}
783
784void InputDispatcher::logOutboundKeyDetailsLocked(const char* prefix, const KeyEntry* entry) {
785#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +0000786 ALOGD("%seventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, "
Jeff Brownb88102f2010-09-08 11:49:43 -0700787 "action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, "
Jeff Browne46a0a42010-11-02 17:58:22 -0700788 "repeatCount=%d, downTime=%lld",
Jeff Brownb88102f2010-09-08 11:49:43 -0700789 prefix,
790 entry->eventTime, entry->deviceId, entry->source, entry->policyFlags,
791 entry->action, entry->flags, entry->keyCode, entry->scanCode, entry->metaState,
Jeff Browne46a0a42010-11-02 17:58:22 -0700792 entry->repeatCount, entry->downTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700793#endif
794}
795
796bool InputDispatcher::dispatchMotionLocked(
Jeff Browne20c9e02010-10-11 14:20:19 -0700797 nsecs_t currentTime, MotionEntry* entry, DropReason* dropReason, nsecs_t* nextWakeupTime) {
Jeff Browne46a0a42010-11-02 17:58:22 -0700798 // Preprocessing.
799 if (! entry->dispatchInProgress) {
800 entry->dispatchInProgress = true;
Jeff Browne46a0a42010-11-02 17:58:22 -0700801
802 logOutboundMotionDetailsLocked("dispatchMotion - ", entry);
803 }
804
Jeff Brown54a18252010-09-16 14:07:33 -0700805 // Clean up if dropping the event.
Jeff Browne20c9e02010-10-11 14:20:19 -0700806 if (*dropReason != DROP_REASON_NOT_DROPPED) {
Jeff Brown3122e442010-10-11 23:32:49 -0700807 setInjectionResultLocked(entry, *dropReason == DROP_REASON_POLICY
808 ? INPUT_EVENT_INJECTION_SUCCEEDED : INPUT_EVENT_INJECTION_FAILED);
Jeff Brown54a18252010-09-16 14:07:33 -0700809 return true;
810 }
811
Jeff Brownb88102f2010-09-08 11:49:43 -0700812 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
813
814 // Identify targets.
Jeff Browne9bb9be2012-02-06 15:47:55 -0800815 Vector<InputTarget> inputTargets;
816
Jeff Browncc0c1592011-02-19 05:07:28 -0800817 bool conflictingPointerActions = false;
Jeff Browne9bb9be2012-02-06 15:47:55 -0800818 int32_t injectionResult;
819 if (isPointerEvent) {
820 // Pointer event. (eg. touchscreen)
821 injectionResult = findTouchedWindowTargetsLocked(currentTime,
822 entry, inputTargets, nextWakeupTime, &conflictingPointerActions);
823 } else {
824 // Non touch event. (eg. trackball)
825 injectionResult = findFocusedWindowTargetsLocked(currentTime,
826 entry, inputTargets, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700827 }
Jeff Browne9bb9be2012-02-06 15:47:55 -0800828 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
829 return false;
830 }
831
832 setInjectionResultLocked(entry, injectionResult);
833 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
834 return true;
835 }
836
Jeff Brown83d616a2012-09-09 20:33:43 -0700837 // TODO: support sending secondary display events to input monitors
838 if (isMainDisplay(entry->displayId)) {
839 addMonitoringTargetsLocked(inputTargets);
840 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700841
842 // Dispatch the motion.
Jeff Browncc0c1592011-02-19 05:07:28 -0800843 if (conflictingPointerActions) {
Jeff Brownda3d5a92011-03-29 15:11:34 -0700844 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
845 "conflicting pointer actions");
846 synthesizeCancelationEventsForAllConnectionsLocked(options);
Jeff Browncc0c1592011-02-19 05:07:28 -0800847 }
Jeff Browne9bb9be2012-02-06 15:47:55 -0800848 dispatchEventLocked(currentTime, entry, inputTargets);
Jeff Brownb88102f2010-09-08 11:49:43 -0700849 return true;
850}
851
852
853void InputDispatcher::logOutboundMotionDetailsLocked(const char* prefix, const MotionEntry* entry) {
854#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +0000855 ALOGD("%seventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, "
Jeff Brown85a31762010-09-01 17:01:00 -0700856 "action=0x%x, flags=0x%x, "
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700857 "metaState=0x%x, buttonState=0x%x, "
858 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%lld",
Jeff Brownb88102f2010-09-08 11:49:43 -0700859 prefix,
Jeff Brown85a31762010-09-01 17:01:00 -0700860 entry->eventTime, entry->deviceId, entry->source, entry->policyFlags,
861 entry->action, entry->flags,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700862 entry->metaState, entry->buttonState,
863 entry->edgeFlags, entry->xPrecision, entry->yPrecision,
Jeff Brown46b9ac02010-04-22 18:58:52 -0700864 entry->downTime);
865
Jeff Brown46b9ac02010-04-22 18:58:52 -0700866 for (uint32_t i = 0; i < entry->pointerCount; i++) {
Steve Block5baa3a62011-12-20 16:23:08 +0000867 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700868 "x=%f, y=%f, pressure=%f, size=%f, "
Jeff Brown85a31762010-09-01 17:01:00 -0700869 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
Jeff Brown8d608662010-08-30 03:02:23 -0700870 "orientation=%f",
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700871 i, entry->pointerProperties[i].id,
872 entry->pointerProperties[i].toolType,
Jeff Brown3241b6b2012-02-03 15:08:02 -0800873 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
874 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
875 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
876 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
877 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
878 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
879 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
880 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
881 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Jeff Brown46b9ac02010-04-22 18:58:52 -0700882 }
883#endif
Jeff Brown46b9ac02010-04-22 18:58:52 -0700884}
885
Jeff Browne9bb9be2012-02-06 15:47:55 -0800886void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
887 EventEntry* eventEntry, const Vector<InputTarget>& inputTargets) {
Jeff Brown46b9ac02010-04-22 18:58:52 -0700888#if DEBUG_DISPATCH_CYCLE
Jeff Brown3241b6b2012-02-03 15:08:02 -0800889 ALOGD("dispatchEventToCurrentInputTargets");
Jeff Brown46b9ac02010-04-22 18:58:52 -0700890#endif
891
Steve Blockec193de2012-01-09 18:35:44 +0000892 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
Jeff Brown9c3cda02010-06-15 01:31:58 -0700893
Jeff Browne2fe69e2010-10-18 13:21:23 -0700894 pokeUserActivityLocked(eventEntry);
895
Jeff Browne9bb9be2012-02-06 15:47:55 -0800896 for (size_t i = 0; i < inputTargets.size(); i++) {
897 const InputTarget& inputTarget = inputTargets.itemAt(i);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700898
Jeff Brown519e0242010-09-15 15:18:56 -0700899 ssize_t connectionIndex = getConnectionIndexLocked(inputTarget.inputChannel);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700900 if (connectionIndex >= 0) {
Jeff Browncbee6d62012-02-03 20:11:27 -0800901 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
Jeff Brown3241b6b2012-02-03 15:08:02 -0800902 prepareDispatchCycleLocked(currentTime, connection, eventEntry, &inputTarget);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700903 } else {
Jeff Brownb6997262010-10-08 22:31:17 -0700904#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +0000905 ALOGD("Dropping event delivery to target with channel '%s' because it "
Jeff Brownb6997262010-10-08 22:31:17 -0700906 "is no longer registered with the input dispatcher.",
Jeff Brown46b9ac02010-04-22 18:58:52 -0700907 inputTarget.inputChannel->getName().string());
Jeff Brownb6997262010-10-08 22:31:17 -0700908#endif
Jeff Brown46b9ac02010-04-22 18:58:52 -0700909 }
910 }
911}
912
Jeff Brownb88102f2010-09-08 11:49:43 -0700913int32_t InputDispatcher::handleTargetsNotReadyLocked(nsecs_t currentTime,
Jeff Brown9302c872011-07-13 22:51:29 -0700914 const EventEntry* entry,
915 const sp<InputApplicationHandle>& applicationHandle,
916 const sp<InputWindowHandle>& windowHandle,
Jeff Brown265f1cc2012-06-11 18:01:06 -0700917 nsecs_t* nextWakeupTime, const char* reason) {
Jeff Brown9302c872011-07-13 22:51:29 -0700918 if (applicationHandle == NULL && windowHandle == NULL) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700919 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY) {
920#if DEBUG_FOCUS
Jeff Brown265f1cc2012-06-11 18:01:06 -0700921 ALOGD("Waiting for system to become ready for input. Reason: %s", reason);
Jeff Brownb88102f2010-09-08 11:49:43 -0700922#endif
923 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY;
924 mInputTargetWaitStartTime = currentTime;
925 mInputTargetWaitTimeoutTime = LONG_LONG_MAX;
926 mInputTargetWaitTimeoutExpired = false;
Jeff Brown9302c872011-07-13 22:51:29 -0700927 mInputTargetWaitApplicationHandle.clear();
Jeff Brownb88102f2010-09-08 11:49:43 -0700928 }
929 } else {
930 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
931#if DEBUG_FOCUS
Jeff Brown265f1cc2012-06-11 18:01:06 -0700932 ALOGD("Waiting for application to become ready for input: %s. Reason: %s",
933 getApplicationWindowLabelLocked(applicationHandle, windowHandle).string(),
934 reason);
Jeff Brownb88102f2010-09-08 11:49:43 -0700935#endif
Jeff Browncc4f7db2011-08-30 20:34:48 -0700936 nsecs_t timeout;
937 if (windowHandle != NULL) {
938 timeout = windowHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
939 } else if (applicationHandle != NULL) {
940 timeout = applicationHandle->getDispatchingTimeout(
941 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
942 } else {
943 timeout = DEFAULT_INPUT_DISPATCHING_TIMEOUT;
944 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700945
946 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY;
947 mInputTargetWaitStartTime = currentTime;
948 mInputTargetWaitTimeoutTime = currentTime + timeout;
949 mInputTargetWaitTimeoutExpired = false;
Jeff Brown9302c872011-07-13 22:51:29 -0700950 mInputTargetWaitApplicationHandle.clear();
Jeff Brown928e0542011-01-10 11:17:36 -0800951
Jeff Brown9302c872011-07-13 22:51:29 -0700952 if (windowHandle != NULL) {
953 mInputTargetWaitApplicationHandle = windowHandle->inputApplicationHandle;
Jeff Brown928e0542011-01-10 11:17:36 -0800954 }
Jeff Brown9302c872011-07-13 22:51:29 -0700955 if (mInputTargetWaitApplicationHandle == NULL && applicationHandle != NULL) {
956 mInputTargetWaitApplicationHandle = applicationHandle;
Jeff Brown928e0542011-01-10 11:17:36 -0800957 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700958 }
959 }
960
961 if (mInputTargetWaitTimeoutExpired) {
962 return INPUT_EVENT_INJECTION_TIMED_OUT;
963 }
964
965 if (currentTime >= mInputTargetWaitTimeoutTime) {
Jeff Brown9302c872011-07-13 22:51:29 -0700966 onANRLocked(currentTime, applicationHandle, windowHandle,
Jeff Brown265f1cc2012-06-11 18:01:06 -0700967 entry->eventTime, mInputTargetWaitStartTime, reason);
Jeff Brownb88102f2010-09-08 11:49:43 -0700968
969 // Force poll loop to wake up immediately on next iteration once we get the
970 // ANR response back from the policy.
971 *nextWakeupTime = LONG_LONG_MIN;
972 return INPUT_EVENT_INJECTION_PENDING;
973 } else {
974 // Force poll loop to wake up when timeout is due.
975 if (mInputTargetWaitTimeoutTime < *nextWakeupTime) {
976 *nextWakeupTime = mInputTargetWaitTimeoutTime;
977 }
978 return INPUT_EVENT_INJECTION_PENDING;
979 }
980}
981
Jeff Brown519e0242010-09-15 15:18:56 -0700982void InputDispatcher::resumeAfterTargetsNotReadyTimeoutLocked(nsecs_t newTimeout,
983 const sp<InputChannel>& inputChannel) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700984 if (newTimeout > 0) {
985 // Extend the timeout.
986 mInputTargetWaitTimeoutTime = now() + newTimeout;
987 } else {
988 // Give up.
989 mInputTargetWaitTimeoutExpired = true;
Jeff Brown519e0242010-09-15 15:18:56 -0700990
991 // Input state will not be realistic. Mark it out of sync.
Jeff Browndc3e0052010-09-16 11:02:16 -0700992 if (inputChannel.get()) {
993 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
994 if (connectionIndex >= 0) {
Jeff Browncbee6d62012-02-03 20:11:27 -0800995 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
Jeff Brownf44e3942012-04-20 11:33:27 -0700996 sp<InputWindowHandle> windowHandle = connection->inputWindowHandle;
997
998 if (windowHandle != NULL) {
999 mTouchState.removeWindow(windowHandle);
1000 }
1001
Jeff Brown00045a72010-12-09 18:10:30 -08001002 if (connection->status == Connection::STATUS_NORMAL) {
Jeff Brownda3d5a92011-03-29 15:11:34 -07001003 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
Jeff Brown00045a72010-12-09 18:10:30 -08001004 "application not responding");
Jeff Brownda3d5a92011-03-29 15:11:34 -07001005 synthesizeCancelationEventsForConnectionLocked(connection, options);
Jeff Brown00045a72010-12-09 18:10:30 -08001006 }
Jeff Browndc3e0052010-09-16 11:02:16 -07001007 }
Jeff Brown519e0242010-09-15 15:18:56 -07001008 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001009 }
1010}
1011
Jeff Brown519e0242010-09-15 15:18:56 -07001012nsecs_t InputDispatcher::getTimeSpentWaitingForApplicationLocked(
Jeff Brownb88102f2010-09-08 11:49:43 -07001013 nsecs_t currentTime) {
1014 if (mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
1015 return currentTime - mInputTargetWaitStartTime;
1016 }
1017 return 0;
1018}
1019
1020void InputDispatcher::resetANRTimeoutsLocked() {
1021#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001022 ALOGD("Resetting ANR timeouts.");
Jeff Brownb88102f2010-09-08 11:49:43 -07001023#endif
1024
Jeff Brownb88102f2010-09-08 11:49:43 -07001025 // Reset input target wait timeout.
1026 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_NONE;
Jeff Brown5ea29ab2011-07-27 11:50:51 -07001027 mInputTargetWaitApplicationHandle.clear();
Jeff Brownb88102f2010-09-08 11:49:43 -07001028}
1029
Jeff Brown01ce2e92010-09-26 22:20:12 -07001030int32_t InputDispatcher::findFocusedWindowTargetsLocked(nsecs_t currentTime,
Jeff Browne9bb9be2012-02-06 15:47:55 -08001031 const EventEntry* entry, Vector<InputTarget>& inputTargets, nsecs_t* nextWakeupTime) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001032 int32_t injectionResult;
1033
1034 // If there is no currently focused window and no focused application
1035 // then drop the event.
Jeff Brown9302c872011-07-13 22:51:29 -07001036 if (mFocusedWindowHandle == NULL) {
1037 if (mFocusedApplicationHandle != NULL) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001038 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brown265f1cc2012-06-11 18:01:06 -07001039 mFocusedApplicationHandle, NULL, nextWakeupTime,
1040 "Waiting because no window has focus but there is a "
1041 "focused application that may eventually add a window "
1042 "when it finishes starting up.");
Jeff Brownb88102f2010-09-08 11:49:43 -07001043 goto Unresponsive;
1044 }
1045
Steve Block6215d3f2012-01-04 20:05:49 +00001046 ALOGI("Dropping event because there is no focused window or focused application.");
Jeff Brownb88102f2010-09-08 11:49:43 -07001047 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1048 goto Failed;
1049 }
1050
1051 // Check permissions.
Jeff Brown9302c872011-07-13 22:51:29 -07001052 if (! checkInjectionPermission(mFocusedWindowHandle, entry->injectionState)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001053 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1054 goto Failed;
1055 }
1056
1057 // If the currently focused window is paused then keep waiting.
Jeff Browncc4f7db2011-08-30 20:34:48 -07001058 if (mFocusedWindowHandle->getInfo()->paused) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001059 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brown265f1cc2012-06-11 18:01:06 -07001060 mFocusedApplicationHandle, mFocusedWindowHandle, nextWakeupTime,
1061 "Waiting because the focused window is paused.");
Jeff Brownb88102f2010-09-08 11:49:43 -07001062 goto Unresponsive;
1063 }
1064
Jeff Brown519e0242010-09-15 15:18:56 -07001065 // If the currently focused window is still working on previous events then keep waiting.
Jeff Brown0952c302012-02-13 13:48:59 -08001066 if (!isWindowReadyForMoreInputLocked(currentTime, mFocusedWindowHandle, entry)) {
Jeff Brown519e0242010-09-15 15:18:56 -07001067 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brown265f1cc2012-06-11 18:01:06 -07001068 mFocusedApplicationHandle, mFocusedWindowHandle, nextWakeupTime,
1069 "Waiting because the focused window has not finished "
1070 "processing the input events that were previously delivered to it.");
Jeff Brown519e0242010-09-15 15:18:56 -07001071 goto Unresponsive;
1072 }
1073
Jeff Brownb88102f2010-09-08 11:49:43 -07001074 // Success! Output targets.
1075 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
Jeff Brown9302c872011-07-13 22:51:29 -07001076 addWindowTargetLocked(mFocusedWindowHandle,
Jeff Browne9bb9be2012-02-06 15:47:55 -08001077 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS, BitSet32(0),
1078 inputTargets);
Jeff Brownb88102f2010-09-08 11:49:43 -07001079
1080 // Done.
1081Failed:
1082Unresponsive:
Jeff Brown519e0242010-09-15 15:18:56 -07001083 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
1084 updateDispatchStatisticsLocked(currentTime, entry,
1085 injectionResult, timeSpentWaitingForApplication);
Jeff Brownb88102f2010-09-08 11:49:43 -07001086#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001087 ALOGD("findFocusedWindow finished: injectionResult=%d, "
Jeff Brown22aa5122012-06-17 12:01:06 -07001088 "timeSpentWaitingForApplication=%0.1fms",
Jeff Brown519e0242010-09-15 15:18:56 -07001089 injectionResult, timeSpentWaitingForApplication / 1000000.0);
Jeff Brownb88102f2010-09-08 11:49:43 -07001090#endif
1091 return injectionResult;
1092}
1093
Jeff Brown01ce2e92010-09-26 22:20:12 -07001094int32_t InputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime,
Jeff Browne9bb9be2012-02-06 15:47:55 -08001095 const MotionEntry* entry, Vector<InputTarget>& inputTargets, nsecs_t* nextWakeupTime,
1096 bool* outConflictingPointerActions) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001097 enum InjectionPermission {
1098 INJECTION_PERMISSION_UNKNOWN,
1099 INJECTION_PERMISSION_GRANTED,
1100 INJECTION_PERMISSION_DENIED
1101 };
1102
Jeff Brownb88102f2010-09-08 11:49:43 -07001103 nsecs_t startTime = now();
1104
1105 // For security reasons, we defer updating the touch state until we are sure that
1106 // event injection will be allowed.
1107 //
1108 // FIXME In the original code, screenWasOff could never be set to true.
1109 // The reason is that the POLICY_FLAG_WOKE_HERE
1110 // and POLICY_FLAG_BRIGHT_HERE flags were set only when preprocessing raw
1111 // EV_KEY, EV_REL and EV_ABS events. As it happens, the touch event was
1112 // actually enqueued using the policyFlags that appeared in the final EV_SYN
1113 // events upon which no preprocessing took place. So policyFlags was always 0.
1114 // In the new native input dispatcher we're a bit more careful about event
1115 // preprocessing so the touches we receive can actually have non-zero policyFlags.
1116 // Unfortunately we obtain undesirable behavior.
1117 //
1118 // Here's what happens:
1119 //
1120 // When the device dims in anticipation of going to sleep, touches
1121 // in windows which have FLAG_TOUCHABLE_WHEN_WAKING cause
1122 // the device to brighten and reset the user activity timer.
1123 // Touches on other windows (such as the launcher window)
1124 // are dropped. Then after a moment, the device goes to sleep. Oops.
1125 //
1126 // Also notice how screenWasOff was being initialized using POLICY_FLAG_BRIGHT_HERE
1127 // instead of POLICY_FLAG_WOKE_HERE...
1128 //
1129 bool screenWasOff = false; // original policy: policyFlags & POLICY_FLAG_BRIGHT_HERE;
1130
Jeff Brown83d616a2012-09-09 20:33:43 -07001131 int32_t displayId = entry->displayId;
Jeff Brownb88102f2010-09-08 11:49:43 -07001132 int32_t action = entry->action;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001133 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Jeff Brownb88102f2010-09-08 11:49:43 -07001134
1135 // Update the touch state as needed based on the properties of the touch event.
Jeff Brown01ce2e92010-09-26 22:20:12 -07001136 int32_t injectionResult = INPUT_EVENT_INJECTION_PENDING;
1137 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
Jeff Brown9302c872011-07-13 22:51:29 -07001138 sp<InputWindowHandle> newHoverWindowHandle;
Jeff Browncc0c1592011-02-19 05:07:28 -08001139
1140 bool isSplit = mTouchState.split;
Jeff Brown83d616a2012-09-09 20:33:43 -07001141 bool switchedDevice = mTouchState.deviceId >= 0 && mTouchState.displayId >= 0
Jeff Brown2717eff2011-06-30 23:53:07 -07001142 && (mTouchState.deviceId != entry->deviceId
Jeff Brown83d616a2012-09-09 20:33:43 -07001143 || mTouchState.source != entry->source
1144 || mTouchState.displayId != displayId);
Jeff Browna032cc02011-03-07 16:56:21 -08001145 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE
1146 || maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER
1147 || maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1148 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN
1149 || maskedAction == AMOTION_EVENT_ACTION_SCROLL
1150 || isHoverAction);
Jeff Brown81346812011-06-28 20:08:48 -07001151 bool wrongDevice = false;
Jeff Browna032cc02011-03-07 16:56:21 -08001152 if (newGesture) {
Jeff Browncc0c1592011-02-19 05:07:28 -08001153 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Jeff Brown81346812011-06-28 20:08:48 -07001154 if (switchedDevice && mTouchState.down && !down) {
1155#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001156 ALOGD("Dropping event because a pointer for a different device is already down.");
Jeff Brown81346812011-06-28 20:08:48 -07001157#endif
Jeff Browncc0c1592011-02-19 05:07:28 -08001158 mTempTouchState.copyFrom(mTouchState);
Jeff Brown81346812011-06-28 20:08:48 -07001159 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1160 switchedDevice = false;
1161 wrongDevice = true;
1162 goto Failed;
Jeff Browncc0c1592011-02-19 05:07:28 -08001163 }
Jeff Brown81346812011-06-28 20:08:48 -07001164 mTempTouchState.reset();
1165 mTempTouchState.down = down;
1166 mTempTouchState.deviceId = entry->deviceId;
1167 mTempTouchState.source = entry->source;
Jeff Brown83d616a2012-09-09 20:33:43 -07001168 mTempTouchState.displayId = displayId;
Jeff Brown81346812011-06-28 20:08:48 -07001169 isSplit = false;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001170 } else {
1171 mTempTouchState.copyFrom(mTouchState);
Jeff Browncc0c1592011-02-19 05:07:28 -08001172 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001173
Jeff Browna032cc02011-03-07 16:56:21 -08001174 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
Jeff Brown33bbfd22011-02-24 20:55:35 -08001175 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
Jeff Brownb88102f2010-09-08 11:49:43 -07001176
Jeff Brown01ce2e92010-09-26 22:20:12 -07001177 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Jeff Brown3241b6b2012-02-03 15:08:02 -08001178 int32_t x = int32_t(entry->pointerCoords[pointerIndex].
Jeff Brownebbd5d12011-02-17 13:01:34 -08001179 getAxisValue(AMOTION_EVENT_AXIS_X));
Jeff Brown3241b6b2012-02-03 15:08:02 -08001180 int32_t y = int32_t(entry->pointerCoords[pointerIndex].
Jeff Brownebbd5d12011-02-17 13:01:34 -08001181 getAxisValue(AMOTION_EVENT_AXIS_Y));
Jeff Brown9302c872011-07-13 22:51:29 -07001182 sp<InputWindowHandle> newTouchedWindowHandle;
1183 sp<InputWindowHandle> topErrorWindowHandle;
Jeff Browna032cc02011-03-07 16:56:21 -08001184 bool isTouchModal = false;
Jeff Brownb88102f2010-09-08 11:49:43 -07001185
1186 // Traverse windows from front to back to find touched window and outside targets.
Jeff Brown9302c872011-07-13 22:51:29 -07001187 size_t numWindows = mWindowHandles.size();
Jeff Brownb88102f2010-09-08 11:49:43 -07001188 for (size_t i = 0; i < numWindows; i++) {
Jeff Brown9302c872011-07-13 22:51:29 -07001189 sp<InputWindowHandle> windowHandle = mWindowHandles.itemAt(i);
Jeff Browncc4f7db2011-08-30 20:34:48 -07001190 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Jeff Brown83d616a2012-09-09 20:33:43 -07001191 if (windowInfo->displayId != displayId) {
1192 continue; // wrong display
1193 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001194
Jeff Brown83d616a2012-09-09 20:33:43 -07001195 int32_t flags = windowInfo->layoutParamsFlags;
Jeff Browncc4f7db2011-08-30 20:34:48 -07001196 if (flags & InputWindowInfo::FLAG_SYSTEM_ERROR) {
Jeff Brown9302c872011-07-13 22:51:29 -07001197 if (topErrorWindowHandle == NULL) {
1198 topErrorWindowHandle = windowHandle;
Jeff Brownb88102f2010-09-08 11:49:43 -07001199 }
1200 }
1201
Jeff Browncc4f7db2011-08-30 20:34:48 -07001202 if (windowInfo->visible) {
1203 if (! (flags & InputWindowInfo::FLAG_NOT_TOUCHABLE)) {
1204 isTouchModal = (flags & (InputWindowInfo::FLAG_NOT_FOCUSABLE
1205 | InputWindowInfo::FLAG_NOT_TOUCH_MODAL)) == 0;
1206 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
Jeff Brown9302c872011-07-13 22:51:29 -07001207 if (! screenWasOff
Jeff Browncc4f7db2011-08-30 20:34:48 -07001208 || (flags & InputWindowInfo::FLAG_TOUCHABLE_WHEN_WAKING)) {
Jeff Brown9302c872011-07-13 22:51:29 -07001209 newTouchedWindowHandle = windowHandle;
Jeff Brownb88102f2010-09-08 11:49:43 -07001210 }
1211 break; // found touched window, exit window loop
1212 }
1213 }
1214
Jeff Brown01ce2e92010-09-26 22:20:12 -07001215 if (maskedAction == AMOTION_EVENT_ACTION_DOWN
Jeff Browncc4f7db2011-08-30 20:34:48 -07001216 && (flags & InputWindowInfo::FLAG_WATCH_OUTSIDE_TOUCH)) {
Jeff Browna032cc02011-03-07 16:56:21 -08001217 int32_t outsideTargetFlags = InputTarget::FLAG_DISPATCH_AS_OUTSIDE;
Jeff Brown9302c872011-07-13 22:51:29 -07001218 if (isWindowObscuredAtPointLocked(windowHandle, x, y)) {
Jeff Brown19dfc832010-10-05 12:26:23 -07001219 outsideTargetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1220 }
1221
Jeff Brown9302c872011-07-13 22:51:29 -07001222 mTempTouchState.addOrUpdateWindow(
1223 windowHandle, outsideTargetFlags, BitSet32(0));
Jeff Brownb88102f2010-09-08 11:49:43 -07001224 }
1225 }
1226 }
1227
1228 // If there is an error window but it is not taking focus (typically because
1229 // it is invisible) then wait for it. Any other focused window may in
1230 // fact be in ANR state.
Jeff Brown9302c872011-07-13 22:51:29 -07001231 if (topErrorWindowHandle != NULL && newTouchedWindowHandle != topErrorWindowHandle) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001232 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brown265f1cc2012-06-11 18:01:06 -07001233 NULL, NULL, nextWakeupTime,
1234 "Waiting because a system error window is about to be displayed.");
Jeff Brownb88102f2010-09-08 11:49:43 -07001235 injectionPermission = INJECTION_PERMISSION_UNKNOWN;
1236 goto Unresponsive;
1237 }
1238
Jeff Brown01ce2e92010-09-26 22:20:12 -07001239 // Figure out whether splitting will be allowed for this window.
Jeff Browncc4f7db2011-08-30 20:34:48 -07001240 if (newTouchedWindowHandle != NULL
1241 && newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001242 // New window supports splitting.
1243 isSplit = true;
1244 } else if (isSplit) {
1245 // New window does not support splitting but we have already split events.
Jeff Brown8249fc62012-05-24 18:57:32 -07001246 // Ignore the new window.
1247 newTouchedWindowHandle = NULL;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001248 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001249
Jeff Brown8249fc62012-05-24 18:57:32 -07001250 // Handle the case where we did not find a window.
Jeff Brown9302c872011-07-13 22:51:29 -07001251 if (newTouchedWindowHandle == NULL) {
Jeff Brown8249fc62012-05-24 18:57:32 -07001252 // Try to assign the pointer to the first foreground window we find, if there is one.
1253 newTouchedWindowHandle = mTempTouchState.getFirstForegroundWindowHandle();
1254 if (newTouchedWindowHandle == NULL) {
1255 // There is no touched window. If this is an initial down event
1256 // then wait for a window to appear that will handle the touch. This is
1257 // to ensure that we report an ANR in the case where an application has started
1258 // but not yet put up a window and the user is starting to get impatient.
1259 if (maskedAction == AMOTION_EVENT_ACTION_DOWN
1260 && mFocusedApplicationHandle != NULL) {
Jeff Brown8249fc62012-05-24 18:57:32 -07001261 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brown265f1cc2012-06-11 18:01:06 -07001262 mFocusedApplicationHandle, NULL, nextWakeupTime,
1263 "Waiting because there is no touchable window that can "
1264 "handle the event but there is focused application that may "
1265 "eventually add a new window when it finishes starting up.");
Jeff Brown8249fc62012-05-24 18:57:32 -07001266 goto Unresponsive;
1267 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001268
Jeff Brown8249fc62012-05-24 18:57:32 -07001269 ALOGI("Dropping event because there is no touched window.");
1270 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1271 goto Failed;
1272 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001273 }
1274
Jeff Brown19dfc832010-10-05 12:26:23 -07001275 // Set target flags.
Jeff Browna032cc02011-03-07 16:56:21 -08001276 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
Jeff Brown19dfc832010-10-05 12:26:23 -07001277 if (isSplit) {
1278 targetFlags |= InputTarget::FLAG_SPLIT;
1279 }
Jeff Brown9302c872011-07-13 22:51:29 -07001280 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
Jeff Brown19dfc832010-10-05 12:26:23 -07001281 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1282 }
1283
Jeff Browna032cc02011-03-07 16:56:21 -08001284 // Update hover state.
1285 if (isHoverAction) {
Jeff Brown9302c872011-07-13 22:51:29 -07001286 newHoverWindowHandle = newTouchedWindowHandle;
Jeff Browna032cc02011-03-07 16:56:21 -08001287 } else if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
Jeff Brown9302c872011-07-13 22:51:29 -07001288 newHoverWindowHandle = mLastHoverWindowHandle;
Jeff Browna032cc02011-03-07 16:56:21 -08001289 }
1290
Jeff Brown01ce2e92010-09-26 22:20:12 -07001291 // Update the temporary touch state.
1292 BitSet32 pointerIds;
1293 if (isSplit) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07001294 uint32_t pointerId = entry->pointerProperties[pointerIndex].id;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001295 pointerIds.markBit(pointerId);
Jeff Brownb88102f2010-09-08 11:49:43 -07001296 }
Jeff Brown9302c872011-07-13 22:51:29 -07001297 mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Jeff Brownb88102f2010-09-08 11:49:43 -07001298 } else {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001299 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
Jeff Brownb88102f2010-09-08 11:49:43 -07001300
1301 // If the pointer is not currently down, then ignore the event.
Jeff Brown01ce2e92010-09-26 22:20:12 -07001302 if (! mTempTouchState.down) {
Jeff Browna2cc28d2011-03-25 11:58:46 -07001303#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001304 ALOGD("Dropping event because the pointer is not down or we previously "
Jeff Brown76860e32010-10-25 17:37:46 -07001305 "dropped the pointer down event.");
1306#endif
Jeff Brownb88102f2010-09-08 11:49:43 -07001307 injectionResult = INPUT_EVENT_INJECTION_FAILED;
Jeff Brownb88102f2010-09-08 11:49:43 -07001308 goto Failed;
1309 }
Jeff Brown98db5fa2011-06-08 15:37:10 -07001310
1311 // Check whether touches should slip outside of the current foreground window.
1312 if (maskedAction == AMOTION_EVENT_ACTION_MOVE
1313 && entry->pointerCount == 1
1314 && mTempTouchState.isSlippery()) {
Jeff Brown3241b6b2012-02-03 15:08:02 -08001315 int32_t x = int32_t(entry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
1316 int32_t y = int32_t(entry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Jeff Brown98db5fa2011-06-08 15:37:10 -07001317
Jeff Brown9302c872011-07-13 22:51:29 -07001318 sp<InputWindowHandle> oldTouchedWindowHandle =
1319 mTempTouchState.getFirstForegroundWindowHandle();
Jeff Brown83d616a2012-09-09 20:33:43 -07001320 sp<InputWindowHandle> newTouchedWindowHandle =
1321 findTouchedWindowAtLocked(displayId, x, y);
Jeff Brown9302c872011-07-13 22:51:29 -07001322 if (oldTouchedWindowHandle != newTouchedWindowHandle
1323 && newTouchedWindowHandle != NULL) {
Jeff Brown98db5fa2011-06-08 15:37:10 -07001324#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001325 ALOGD("Touch is slipping out of window %s into window %s.",
Jeff Browncc4f7db2011-08-30 20:34:48 -07001326 oldTouchedWindowHandle->getName().string(),
1327 newTouchedWindowHandle->getName().string());
Jeff Brown98db5fa2011-06-08 15:37:10 -07001328#endif
1329 // Make a slippery exit from the old window.
Jeff Brown9302c872011-07-13 22:51:29 -07001330 mTempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
Jeff Brown98db5fa2011-06-08 15:37:10 -07001331 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT, BitSet32(0));
1332
1333 // Make a slippery entrance into the new window.
Jeff Browncc4f7db2011-08-30 20:34:48 -07001334 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Jeff Brown98db5fa2011-06-08 15:37:10 -07001335 isSplit = true;
1336 }
1337
1338 int32_t targetFlags = InputTarget::FLAG_FOREGROUND
1339 | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
1340 if (isSplit) {
1341 targetFlags |= InputTarget::FLAG_SPLIT;
1342 }
Jeff Brown9302c872011-07-13 22:51:29 -07001343 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
Jeff Brown98db5fa2011-06-08 15:37:10 -07001344 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1345 }
1346
1347 BitSet32 pointerIds;
1348 if (isSplit) {
1349 pointerIds.markBit(entry->pointerProperties[0].id);
1350 }
Jeff Brown9302c872011-07-13 22:51:29 -07001351 mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Jeff Brown98db5fa2011-06-08 15:37:10 -07001352 }
1353 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001354 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001355
Jeff Brown9302c872011-07-13 22:51:29 -07001356 if (newHoverWindowHandle != mLastHoverWindowHandle) {
Jeff Browna032cc02011-03-07 16:56:21 -08001357 // Let the previous window know that the hover sequence is over.
Jeff Brown9302c872011-07-13 22:51:29 -07001358 if (mLastHoverWindowHandle != NULL) {
Jeff Browna032cc02011-03-07 16:56:21 -08001359#if DEBUG_HOVER
Steve Block5baa3a62011-12-20 16:23:08 +00001360 ALOGD("Sending hover exit event to window %s.",
Jeff Browncc4f7db2011-08-30 20:34:48 -07001361 mLastHoverWindowHandle->getName().string());
Jeff Browna032cc02011-03-07 16:56:21 -08001362#endif
Jeff Brown9302c872011-07-13 22:51:29 -07001363 mTempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
Jeff Browna032cc02011-03-07 16:56:21 -08001364 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
1365 }
1366
1367 // Let the new window know that the hover sequence is starting.
Jeff Brown9302c872011-07-13 22:51:29 -07001368 if (newHoverWindowHandle != NULL) {
Jeff Browna032cc02011-03-07 16:56:21 -08001369#if DEBUG_HOVER
Steve Block5baa3a62011-12-20 16:23:08 +00001370 ALOGD("Sending hover enter event to window %s.",
Jeff Browncc4f7db2011-08-30 20:34:48 -07001371 newHoverWindowHandle->getName().string());
Jeff Browna032cc02011-03-07 16:56:21 -08001372#endif
Jeff Brown9302c872011-07-13 22:51:29 -07001373 mTempTouchState.addOrUpdateWindow(newHoverWindowHandle,
Jeff Browna032cc02011-03-07 16:56:21 -08001374 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER, BitSet32(0));
1375 }
1376 }
1377
Jeff Brown01ce2e92010-09-26 22:20:12 -07001378 // Check permission to inject into all touched foreground windows and ensure there
1379 // is at least one touched foreground window.
1380 {
1381 bool haveForegroundWindow = false;
1382 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1383 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1384 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1385 haveForegroundWindow = true;
Jeff Brown9302c872011-07-13 22:51:29 -07001386 if (! checkInjectionPermission(touchedWindow.windowHandle,
1387 entry->injectionState)) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001388 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1389 injectionPermission = INJECTION_PERMISSION_DENIED;
1390 goto Failed;
1391 }
1392 }
1393 }
1394 if (! haveForegroundWindow) {
Jeff Browna2cc28d2011-03-25 11:58:46 -07001395#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001396 ALOGD("Dropping event because there is no touched foreground window to receive it.");
Jeff Brownb88102f2010-09-08 11:49:43 -07001397#endif
1398 injectionResult = INPUT_EVENT_INJECTION_FAILED;
Jeff Brownb88102f2010-09-08 11:49:43 -07001399 goto Failed;
1400 }
1401
Jeff Brown01ce2e92010-09-26 22:20:12 -07001402 // Permission granted to injection into all touched foreground windows.
1403 injectionPermission = INJECTION_PERMISSION_GRANTED;
1404 }
Jeff Brown519e0242010-09-15 15:18:56 -07001405
Kenny Root7a9db182011-06-02 15:16:05 -07001406 // Check whether windows listening for outside touches are owned by the same UID. If it is
1407 // set the policy flag that we will not reveal coordinate information to this window.
1408 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
Jeff Brown9302c872011-07-13 22:51:29 -07001409 sp<InputWindowHandle> foregroundWindowHandle =
1410 mTempTouchState.getFirstForegroundWindowHandle();
Jeff Browncc4f7db2011-08-30 20:34:48 -07001411 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Kenny Root7a9db182011-06-02 15:16:05 -07001412 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1413 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1414 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
Jeff Brown9302c872011-07-13 22:51:29 -07001415 sp<InputWindowHandle> inputWindowHandle = touchedWindow.windowHandle;
Jeff Browncc4f7db2011-08-30 20:34:48 -07001416 if (inputWindowHandle->getInfo()->ownerUid != foregroundWindowUid) {
Jeff Brown9302c872011-07-13 22:51:29 -07001417 mTempTouchState.addOrUpdateWindow(inputWindowHandle,
Kenny Root7a9db182011-06-02 15:16:05 -07001418 InputTarget::FLAG_ZERO_COORDS, BitSet32(0));
1419 }
1420 }
1421 }
1422 }
1423
Jeff Brown01ce2e92010-09-26 22:20:12 -07001424 // Ensure all touched foreground windows are ready for new input.
1425 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1426 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1427 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1428 // If the touched window is paused then keep waiting.
Jeff Browncc4f7db2011-08-30 20:34:48 -07001429 if (touchedWindow.windowHandle->getInfo()->paused) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001430 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brown265f1cc2012-06-11 18:01:06 -07001431 NULL, touchedWindow.windowHandle, nextWakeupTime,
1432 "Waiting because the touched window is paused.");
Jeff Brown01ce2e92010-09-26 22:20:12 -07001433 goto Unresponsive;
1434 }
1435
1436 // If the touched window is still working on previous events then keep waiting.
Jeff Brown0952c302012-02-13 13:48:59 -08001437 if (!isWindowReadyForMoreInputLocked(currentTime, touchedWindow.windowHandle, entry)) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001438 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brown265f1cc2012-06-11 18:01:06 -07001439 NULL, touchedWindow.windowHandle, nextWakeupTime,
1440 "Waiting because the touched window has not finished "
1441 "processing the input events that were previously delivered to it.");
Jeff Brown01ce2e92010-09-26 22:20:12 -07001442 goto Unresponsive;
1443 }
1444 }
1445 }
1446
1447 // If this is the first pointer going down and the touched window has a wallpaper
1448 // then also add the touched wallpaper windows so they are locked in for the duration
1449 // of the touch gesture.
Jeff Brown33bbfd22011-02-24 20:55:35 -08001450 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
1451 // engine only supports touch events. We would need to add a mechanism similar
1452 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
1453 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
Jeff Brown9302c872011-07-13 22:51:29 -07001454 sp<InputWindowHandle> foregroundWindowHandle =
1455 mTempTouchState.getFirstForegroundWindowHandle();
Jeff Browncc4f7db2011-08-30 20:34:48 -07001456 if (foregroundWindowHandle->getInfo()->hasWallpaper) {
Jeff Brown9302c872011-07-13 22:51:29 -07001457 for (size_t i = 0; i < mWindowHandles.size(); i++) {
1458 sp<InputWindowHandle> windowHandle = mWindowHandles.itemAt(i);
Jeff Brown83d616a2012-09-09 20:33:43 -07001459 const InputWindowInfo* info = windowHandle->getInfo();
1460 if (info->displayId == displayId
1461 && windowHandle->getInfo()->layoutParamsType
1462 == InputWindowInfo::TYPE_WALLPAPER) {
Jeff Brown9302c872011-07-13 22:51:29 -07001463 mTempTouchState.addOrUpdateWindow(windowHandle,
Jeff Browna032cc02011-03-07 16:56:21 -08001464 InputTarget::FLAG_WINDOW_IS_OBSCURED
1465 | InputTarget::FLAG_DISPATCH_AS_IS,
1466 BitSet32(0));
Jeff Brown01ce2e92010-09-26 22:20:12 -07001467 }
1468 }
1469 }
1470 }
1471
Jeff Brownb88102f2010-09-08 11:49:43 -07001472 // Success! Output targets.
1473 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
Jeff Brownb88102f2010-09-08 11:49:43 -07001474
Jeff Brown01ce2e92010-09-26 22:20:12 -07001475 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1476 const TouchedWindow& touchedWindow = mTempTouchState.windows.itemAt(i);
Jeff Brown9302c872011-07-13 22:51:29 -07001477 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Jeff Browne9bb9be2012-02-06 15:47:55 -08001478 touchedWindow.pointerIds, inputTargets);
Jeff Brownb88102f2010-09-08 11:49:43 -07001479 }
1480
Jeff Browna032cc02011-03-07 16:56:21 -08001481 // Drop the outside or hover touch windows since we will not care about them
1482 // in the next iteration.
1483 mTempTouchState.filterNonAsIsTouchWindows();
Jeff Brown01ce2e92010-09-26 22:20:12 -07001484
Jeff Brownb88102f2010-09-08 11:49:43 -07001485Failed:
1486 // Check injection permission once and for all.
1487 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001488 if (checkInjectionPermission(NULL, entry->injectionState)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001489 injectionPermission = INJECTION_PERMISSION_GRANTED;
1490 } else {
1491 injectionPermission = INJECTION_PERMISSION_DENIED;
1492 }
1493 }
1494
1495 // Update final pieces of touch state if the injector had permission.
1496 if (injectionPermission == INJECTION_PERMISSION_GRANTED) {
Jeff Brown95712852011-01-04 19:41:59 -08001497 if (!wrongDevice) {
Jeff Brown81346812011-06-28 20:08:48 -07001498 if (switchedDevice) {
1499#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001500 ALOGD("Conflicting pointer actions: Switched to a different device.");
Jeff Brown81346812011-06-28 20:08:48 -07001501#endif
1502 *outConflictingPointerActions = true;
1503 }
1504
1505 if (isHoverAction) {
1506 // Started hovering, therefore no longer down.
1507 if (mTouchState.down) {
1508#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001509 ALOGD("Conflicting pointer actions: Hover received while pointer was down.");
Jeff Brown81346812011-06-28 20:08:48 -07001510#endif
1511 *outConflictingPointerActions = true;
1512 }
1513 mTouchState.reset();
1514 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER
1515 || maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
1516 mTouchState.deviceId = entry->deviceId;
1517 mTouchState.source = entry->source;
Jeff Brown83d616a2012-09-09 20:33:43 -07001518 mTouchState.displayId = displayId;
Jeff Brown81346812011-06-28 20:08:48 -07001519 }
1520 } else if (maskedAction == AMOTION_EVENT_ACTION_UP
1521 || maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Jeff Brown95712852011-01-04 19:41:59 -08001522 // All pointers up or canceled.
Jeff Brown33bbfd22011-02-24 20:55:35 -08001523 mTouchState.reset();
Jeff Brown95712852011-01-04 19:41:59 -08001524 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1525 // First pointer went down.
1526 if (mTouchState.down) {
Jeff Brownb6997262010-10-08 22:31:17 -07001527#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001528 ALOGD("Conflicting pointer actions: Down received while already down.");
Jeff Brownb6997262010-10-08 22:31:17 -07001529#endif
Jeff Brown81346812011-06-28 20:08:48 -07001530 *outConflictingPointerActions = true;
Jeff Brown95712852011-01-04 19:41:59 -08001531 }
Jeff Brown33bbfd22011-02-24 20:55:35 -08001532 mTouchState.copyFrom(mTempTouchState);
Jeff Brown95712852011-01-04 19:41:59 -08001533 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
1534 // One pointer went up.
1535 if (isSplit) {
1536 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07001537 uint32_t pointerId = entry->pointerProperties[pointerIndex].id;
Jeff Brownb88102f2010-09-08 11:49:43 -07001538
Jeff Brown95712852011-01-04 19:41:59 -08001539 for (size_t i = 0; i < mTempTouchState.windows.size(); ) {
1540 TouchedWindow& touchedWindow = mTempTouchState.windows.editItemAt(i);
1541 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
1542 touchedWindow.pointerIds.clearBit(pointerId);
1543 if (touchedWindow.pointerIds.isEmpty()) {
1544 mTempTouchState.windows.removeAt(i);
1545 continue;
1546 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001547 }
Jeff Brown95712852011-01-04 19:41:59 -08001548 i += 1;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001549 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001550 }
Jeff Brown33bbfd22011-02-24 20:55:35 -08001551 mTouchState.copyFrom(mTempTouchState);
1552 } else if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
1553 // Discard temporary touch state since it was only valid for this action.
1554 } else {
1555 // Save changes to touch state as-is for all other actions.
1556 mTouchState.copyFrom(mTempTouchState);
Jeff Brownb88102f2010-09-08 11:49:43 -07001557 }
Jeff Browna032cc02011-03-07 16:56:21 -08001558
1559 // Update hover state.
Jeff Brown9302c872011-07-13 22:51:29 -07001560 mLastHoverWindowHandle = newHoverWindowHandle;
Jeff Brown95712852011-01-04 19:41:59 -08001561 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001562 } else {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001563#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001564 ALOGD("Not updating touch focus because injection was denied.");
Jeff Brown01ce2e92010-09-26 22:20:12 -07001565#endif
Jeff Brownb88102f2010-09-08 11:49:43 -07001566 }
1567
1568Unresponsive:
Jeff Brown120a4592010-10-27 18:43:51 -07001569 // Reset temporary touch state to ensure we release unnecessary references to input channels.
1570 mTempTouchState.reset();
1571
Jeff Brown519e0242010-09-15 15:18:56 -07001572 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
1573 updateDispatchStatisticsLocked(currentTime, entry,
1574 injectionResult, timeSpentWaitingForApplication);
Jeff Brownb88102f2010-09-08 11:49:43 -07001575#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001576 ALOGD("findTouchedWindow finished: injectionResult=%d, injectionPermission=%d, "
Jeff Brown01ce2e92010-09-26 22:20:12 -07001577 "timeSpentWaitingForApplication=%0.1fms",
Jeff Brown519e0242010-09-15 15:18:56 -07001578 injectionResult, injectionPermission, timeSpentWaitingForApplication / 1000000.0);
Jeff Brownb88102f2010-09-08 11:49:43 -07001579#endif
1580 return injectionResult;
1581}
1582
Jeff Brown9302c872011-07-13 22:51:29 -07001583void InputDispatcher::addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
Jeff Browne9bb9be2012-02-06 15:47:55 -08001584 int32_t targetFlags, BitSet32 pointerIds, Vector<InputTarget>& inputTargets) {
1585 inputTargets.push();
Jeff Brownb88102f2010-09-08 11:49:43 -07001586
Jeff Browncc4f7db2011-08-30 20:34:48 -07001587 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Jeff Browne9bb9be2012-02-06 15:47:55 -08001588 InputTarget& target = inputTargets.editTop();
Jeff Browncc4f7db2011-08-30 20:34:48 -07001589 target.inputChannel = windowInfo->inputChannel;
Jeff Brownb88102f2010-09-08 11:49:43 -07001590 target.flags = targetFlags;
Jeff Browncc4f7db2011-08-30 20:34:48 -07001591 target.xOffset = - windowInfo->frameLeft;
1592 target.yOffset = - windowInfo->frameTop;
1593 target.scaleFactor = windowInfo->scaleFactor;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001594 target.pointerIds = pointerIds;
Jeff Brownb88102f2010-09-08 11:49:43 -07001595}
1596
Jeff Browne9bb9be2012-02-06 15:47:55 -08001597void InputDispatcher::addMonitoringTargetsLocked(Vector<InputTarget>& inputTargets) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001598 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
Jeff Browne9bb9be2012-02-06 15:47:55 -08001599 inputTargets.push();
Jeff Brownb88102f2010-09-08 11:49:43 -07001600
Jeff Browne9bb9be2012-02-06 15:47:55 -08001601 InputTarget& target = inputTargets.editTop();
Jeff Brownb88102f2010-09-08 11:49:43 -07001602 target.inputChannel = mMonitoringChannels[i];
Jeff Brownb6110c22011-04-01 16:15:13 -07001603 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
Jeff Brownb88102f2010-09-08 11:49:43 -07001604 target.xOffset = 0;
1605 target.yOffset = 0;
Jeff Brownb6110c22011-04-01 16:15:13 -07001606 target.pointerIds.clear();
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001607 target.scaleFactor = 1.0f;
Jeff Brownb88102f2010-09-08 11:49:43 -07001608 }
1609}
1610
Jeff Brown9302c872011-07-13 22:51:29 -07001611bool InputDispatcher::checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
Jeff Brown01ce2e92010-09-26 22:20:12 -07001612 const InjectionState* injectionState) {
1613 if (injectionState
Jeff Browncc4f7db2011-08-30 20:34:48 -07001614 && (windowHandle == NULL
1615 || windowHandle->getInfo()->ownerUid != injectionState->injectorUid)
Jeff Brownb6997262010-10-08 22:31:17 -07001616 && !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Jeff Brown9302c872011-07-13 22:51:29 -07001617 if (windowHandle != NULL) {
Steve Block8564c8d2012-01-05 23:22:43 +00001618 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
Jeff Brown9302c872011-07-13 22:51:29 -07001619 "owned by uid %d",
Jeff Brownb6997262010-10-08 22:31:17 -07001620 injectionState->injectorPid, injectionState->injectorUid,
Jeff Browncc4f7db2011-08-30 20:34:48 -07001621 windowHandle->getName().string(),
1622 windowHandle->getInfo()->ownerUid);
Jeff Brownb6997262010-10-08 22:31:17 -07001623 } else {
Steve Block8564c8d2012-01-05 23:22:43 +00001624 ALOGW("Permission denied: injecting event from pid %d uid %d",
Jeff Brownb6997262010-10-08 22:31:17 -07001625 injectionState->injectorPid, injectionState->injectorUid);
Jeff Brownb88102f2010-09-08 11:49:43 -07001626 }
Jeff Brownb6997262010-10-08 22:31:17 -07001627 return false;
Jeff Brownb88102f2010-09-08 11:49:43 -07001628 }
1629 return true;
1630}
1631
Jeff Brown19dfc832010-10-05 12:26:23 -07001632bool InputDispatcher::isWindowObscuredAtPointLocked(
Jeff Brown9302c872011-07-13 22:51:29 -07001633 const sp<InputWindowHandle>& windowHandle, int32_t x, int32_t y) const {
Jeff Brown83d616a2012-09-09 20:33:43 -07001634 int32_t displayId = windowHandle->getInfo()->displayId;
Jeff Brown9302c872011-07-13 22:51:29 -07001635 size_t numWindows = mWindowHandles.size();
Jeff Brownb88102f2010-09-08 11:49:43 -07001636 for (size_t i = 0; i < numWindows; i++) {
Jeff Brown9302c872011-07-13 22:51:29 -07001637 sp<InputWindowHandle> otherHandle = mWindowHandles.itemAt(i);
1638 if (otherHandle == windowHandle) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001639 break;
1640 }
Jeff Browncc4f7db2011-08-30 20:34:48 -07001641
1642 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Jeff Brown83d616a2012-09-09 20:33:43 -07001643 if (otherInfo->displayId == displayId
1644 && otherInfo->visible && !otherInfo->isTrustedOverlay()
Jeff Browncc4f7db2011-08-30 20:34:48 -07001645 && otherInfo->frameContainsPoint(x, y)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001646 return true;
1647 }
1648 }
1649 return false;
1650}
1651
Jeff Brownd1c48a02012-02-06 19:12:47 -08001652bool InputDispatcher::isWindowReadyForMoreInputLocked(nsecs_t currentTime,
Jeff Brown0952c302012-02-13 13:48:59 -08001653 const sp<InputWindowHandle>& windowHandle, const EventEntry* eventEntry) {
Jeff Browncc4f7db2011-08-30 20:34:48 -07001654 ssize_t connectionIndex = getConnectionIndexLocked(windowHandle->getInputChannel());
Jeff Brown519e0242010-09-15 15:18:56 -07001655 if (connectionIndex >= 0) {
Jeff Browncbee6d62012-02-03 20:11:27 -08001656 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
Jeff Brownd1c48a02012-02-06 19:12:47 -08001657 if (connection->inputPublisherBlocked) {
1658 return false;
1659 }
Jeff Brown0952c302012-02-13 13:48:59 -08001660 if (eventEntry->type == EventEntry::TYPE_KEY) {
1661 // If the event is a key event, then we must wait for all previous events to
1662 // complete before delivering it because previous events may have the
1663 // side-effect of transferring focus to a different window and we want to
1664 // ensure that the following keys are sent to the new window.
1665 //
1666 // Suppose the user touches a button in a window then immediately presses "A".
1667 // If the button causes a pop-up window to appear then we want to ensure that
1668 // the "A" key is delivered to the new pop-up window. This is because users
1669 // often anticipate pending UI changes when typing on a keyboard.
1670 // To obtain this behavior, we must serialize key events with respect to all
1671 // prior input events.
Jeff Brownd1c48a02012-02-06 19:12:47 -08001672 return connection->outboundQueue.isEmpty()
1673 && connection->waitQueue.isEmpty();
1674 }
Jeff Brown0952c302012-02-13 13:48:59 -08001675 // Touch events can always be sent to a window immediately because the user intended
1676 // to touch whatever was visible at the time. Even if focus changes or a new
1677 // window appears moments later, the touch event was meant to be delivered to
1678 // whatever window happened to be on screen at the time.
1679 //
1680 // Generic motion events, such as trackball or joystick events are a little trickier.
1681 // Like key events, generic motion events are delivered to the focused window.
1682 // Unlike key events, generic motion events don't tend to transfer focus to other
1683 // windows and it is not important for them to be serialized. So we prefer to deliver
1684 // generic motion events as soon as possible to improve efficiency and reduce lag
1685 // through batching.
1686 //
1687 // The one case where we pause input event delivery is when the wait queue is piling
1688 // up with lots of events because the application is not responding.
1689 // This condition ensures that ANRs are detected reliably.
Jeff Brownd1c48a02012-02-06 19:12:47 -08001690 if (!connection->waitQueue.isEmpty()
1691 && currentTime >= connection->waitQueue.head->eventEntry->eventTime
1692 + STREAM_AHEAD_EVENT_TIMEOUT) {
1693 return false;
1694 }
Jeff Brown519e0242010-09-15 15:18:56 -07001695 }
Jeff Brownd1c48a02012-02-06 19:12:47 -08001696 return true;
Jeff Brown519e0242010-09-15 15:18:56 -07001697}
1698
Jeff Brown9302c872011-07-13 22:51:29 -07001699String8 InputDispatcher::getApplicationWindowLabelLocked(
1700 const sp<InputApplicationHandle>& applicationHandle,
1701 const sp<InputWindowHandle>& windowHandle) {
1702 if (applicationHandle != NULL) {
1703 if (windowHandle != NULL) {
Jeff Browncc4f7db2011-08-30 20:34:48 -07001704 String8 label(applicationHandle->getName());
Jeff Brown519e0242010-09-15 15:18:56 -07001705 label.append(" - ");
Jeff Browncc4f7db2011-08-30 20:34:48 -07001706 label.append(windowHandle->getName());
Jeff Brown519e0242010-09-15 15:18:56 -07001707 return label;
1708 } else {
Jeff Browncc4f7db2011-08-30 20:34:48 -07001709 return applicationHandle->getName();
Jeff Brown519e0242010-09-15 15:18:56 -07001710 }
Jeff Brown9302c872011-07-13 22:51:29 -07001711 } else if (windowHandle != NULL) {
Jeff Browncc4f7db2011-08-30 20:34:48 -07001712 return windowHandle->getName();
Jeff Brown519e0242010-09-15 15:18:56 -07001713 } else {
1714 return String8("<unknown application or window>");
1715 }
1716}
1717
Jeff Browne2fe69e2010-10-18 13:21:23 -07001718void InputDispatcher::pokeUserActivityLocked(const EventEntry* eventEntry) {
Jeff Brown1e3b98d2012-09-30 18:58:59 -07001719 if (mFocusedWindowHandle != NULL) {
1720 const InputWindowInfo* info = mFocusedWindowHandle->getInfo();
1721 if (info->inputFeatures & InputWindowInfo::INPUT_FEATURE_DISABLE_USER_ACTIVITY) {
1722#if DEBUG_DISPATCH_CYCLE
1723 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.string());
1724#endif
1725 return;
1726 }
1727 }
1728
Jeff Brownb696de52012-07-27 15:38:50 -07001729 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Jeff Brown4d396052010-10-29 21:50:21 -07001730 switch (eventEntry->type) {
1731 case EventEntry::TYPE_MOTION: {
Jeff Browne2fe69e2010-10-18 13:21:23 -07001732 const MotionEntry* motionEntry = static_cast<const MotionEntry*>(eventEntry);
Jeff Brown4d396052010-10-29 21:50:21 -07001733 if (motionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
1734 return;
1735 }
1736
Jeff Brown56194eb2011-03-02 19:23:13 -08001737 if (MotionEvent::isTouchEvent(motionEntry->source, motionEntry->action)) {
Jeff Brownb696de52012-07-27 15:38:50 -07001738 eventType = USER_ACTIVITY_EVENT_TOUCH;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001739 }
Jeff Brown4d396052010-10-29 21:50:21 -07001740 break;
1741 }
1742 case EventEntry::TYPE_KEY: {
1743 const KeyEntry* keyEntry = static_cast<const KeyEntry*>(eventEntry);
1744 if (keyEntry->flags & AKEY_EVENT_FLAG_CANCELED) {
1745 return;
1746 }
Jeff Brownb696de52012-07-27 15:38:50 -07001747 eventType = USER_ACTIVITY_EVENT_BUTTON;
Jeff Brown4d396052010-10-29 21:50:21 -07001748 break;
1749 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001750 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001751
Jeff Brownb88102f2010-09-08 11:49:43 -07001752 CommandEntry* commandEntry = postCommandLocked(
1753 & InputDispatcher::doPokeUserActivityLockedInterruptible);
Jeff Browne2fe69e2010-10-18 13:21:23 -07001754 commandEntry->eventTime = eventEntry->eventTime;
Jeff Brownb88102f2010-09-08 11:49:43 -07001755 commandEntry->userActivityEventType = eventType;
1756}
1757
Jeff Brown7fbdc842010-06-17 20:52:56 -07001758void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001759 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07001760#if DEBUG_DISPATCH_CYCLE
Steve Block5baa3a62011-12-20 16:23:08 +00001761 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
Jeff Brown9cc695c2011-08-23 18:35:04 -07001762 "xOffset=%f, yOffset=%f, scaleFactor=%f, "
Jeff Brown3241b6b2012-02-03 15:08:02 -08001763 "pointerIds=0x%x",
Jeff Brown519e0242010-09-15 15:18:56 -07001764 connection->getInputChannelName(), inputTarget->flags,
Jeff Brown46b9ac02010-04-22 18:58:52 -07001765 inputTarget->xOffset, inputTarget->yOffset,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001766 inputTarget->scaleFactor, inputTarget->pointerIds.value);
Jeff Brown46b9ac02010-04-22 18:58:52 -07001767#endif
1768
1769 // Skip this event if the connection status is not normal.
Jeff Brown519e0242010-09-15 15:18:56 -07001770 // We don't want to enqueue additional outbound events if the connection is broken.
Jeff Brown46b9ac02010-04-22 18:58:52 -07001771 if (connection->status != Connection::STATUS_NORMAL) {
Jeff Brownb6997262010-10-08 22:31:17 -07001772#if DEBUG_DISPATCH_CYCLE
Steve Block5baa3a62011-12-20 16:23:08 +00001773 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Jeff Brownb88102f2010-09-08 11:49:43 -07001774 connection->getInputChannelName(), connection->getStatusLabel());
Jeff Brownb6997262010-10-08 22:31:17 -07001775#endif
Jeff Brown46b9ac02010-04-22 18:58:52 -07001776 return;
1777 }
1778
Jeff Brown01ce2e92010-09-26 22:20:12 -07001779 // Split a motion event if needed.
Jeff Brown3241b6b2012-02-03 15:08:02 -08001780 if (inputTarget->flags & InputTarget::FLAG_SPLIT) {
Steve Blockec193de2012-01-09 18:35:44 +00001781 ALOG_ASSERT(eventEntry->type == EventEntry::TYPE_MOTION);
Jeff Brown01ce2e92010-09-26 22:20:12 -07001782
1783 MotionEntry* originalMotionEntry = static_cast<MotionEntry*>(eventEntry);
1784 if (inputTarget->pointerIds.count() != originalMotionEntry->pointerCount) {
1785 MotionEntry* splitMotionEntry = splitMotionEvent(
1786 originalMotionEntry, inputTarget->pointerIds);
Jeff Brown58a2da82011-01-25 16:02:22 -08001787 if (!splitMotionEntry) {
1788 return; // split event was dropped
1789 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001790#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001791 ALOGD("channel '%s' ~ Split motion event.",
Jeff Brown01ce2e92010-09-26 22:20:12 -07001792 connection->getInputChannelName());
1793 logOutboundMotionDetailsLocked(" ", splitMotionEntry);
1794#endif
Jeff Brownc0cb3dc2012-01-12 18:30:12 -08001795 enqueueDispatchEntriesLocked(currentTime, connection,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001796 splitMotionEntry, inputTarget);
Jeff Brownc0cb3dc2012-01-12 18:30:12 -08001797 splitMotionEntry->release();
1798 return;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001799 }
1800 }
1801
Jeff Brownc0cb3dc2012-01-12 18:30:12 -08001802 // Not splitting. Enqueue dispatch entries for the event as is.
Jeff Brown3241b6b2012-02-03 15:08:02 -08001803 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
Jeff Brownc0cb3dc2012-01-12 18:30:12 -08001804}
1805
1806void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001807 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07001808 bool wasEmpty = connection->outboundQueue.isEmpty();
1809
Jeff Browna032cc02011-03-07 16:56:21 -08001810 // Enqueue dispatch entries for the requested modes.
1811 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001812 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
Jeff Browna032cc02011-03-07 16:56:21 -08001813 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001814 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
Jeff Browna032cc02011-03-07 16:56:21 -08001815 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001816 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
Jeff Browna032cc02011-03-07 16:56:21 -08001817 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001818 InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brown98db5fa2011-06-08 15:37:10 -07001819 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001820 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
Jeff Brown98db5fa2011-06-08 15:37:10 -07001821 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001822 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Jeff Browna032cc02011-03-07 16:56:21 -08001823
1824 // If the outbound queue was previously empty, start the dispatch cycle going.
Jeff Brownb6110c22011-04-01 16:15:13 -07001825 if (wasEmpty && !connection->outboundQueue.isEmpty()) {
Jeff Browna032cc02011-03-07 16:56:21 -08001826 startDispatchCycleLocked(currentTime, connection);
1827 }
1828}
1829
1830void InputDispatcher::enqueueDispatchEntryLocked(
1831 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001832 int32_t dispatchMode) {
Jeff Browna032cc02011-03-07 16:56:21 -08001833 int32_t inputTargetFlags = inputTarget->flags;
1834 if (!(inputTargetFlags & dispatchMode)) {
1835 return;
1836 }
1837 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
1838
Jeff Brown46b9ac02010-04-22 18:58:52 -07001839 // This is a new event.
1840 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Jeff Brownac386072011-07-20 15:19:50 -07001841 DispatchEntry* dispatchEntry = new DispatchEntry(eventEntry, // increments ref
Dianne Hackbornaa9d84c2011-05-09 19:00:59 -07001842 inputTargetFlags, inputTarget->xOffset, inputTarget->yOffset,
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001843 inputTarget->scaleFactor);
Jeff Brown6ec402b2010-07-28 15:48:59 -07001844
Jeff Brown81346812011-06-28 20:08:48 -07001845 // Apply target flags and update the connection's input state.
1846 switch (eventEntry->type) {
1847 case EventEntry::TYPE_KEY: {
1848 KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
1849 dispatchEntry->resolvedAction = keyEntry->action;
1850 dispatchEntry->resolvedFlags = keyEntry->flags;
1851
1852 if (!connection->inputState.trackKey(keyEntry,
1853 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags)) {
1854#if DEBUG_DISPATCH_CYCLE
Steve Block5baa3a62011-12-20 16:23:08 +00001855 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
Jeff Brown81346812011-06-28 20:08:48 -07001856 connection->getInputChannelName());
1857#endif
Jeff Brownc0cb3dc2012-01-12 18:30:12 -08001858 delete dispatchEntry;
Jeff Brown81346812011-06-28 20:08:48 -07001859 return; // skip the inconsistent event
1860 }
1861 break;
1862 }
1863
1864 case EventEntry::TYPE_MOTION: {
1865 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
1866 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
1867 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
1868 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
1869 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
1870 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
1871 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
1872 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
1873 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
1874 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
1875 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
1876 } else {
1877 dispatchEntry->resolvedAction = motionEntry->action;
1878 }
1879 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE
1880 && !connection->inputState.isHovering(
Jeff Brown83d616a2012-09-09 20:33:43 -07001881 motionEntry->deviceId, motionEntry->source, motionEntry->displayId)) {
Jeff Brown81346812011-06-28 20:08:48 -07001882#if DEBUG_DISPATCH_CYCLE
Steve Block5baa3a62011-12-20 16:23:08 +00001883 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter event",
Jeff Brown81346812011-06-28 20:08:48 -07001884 connection->getInputChannelName());
1885#endif
1886 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
1887 }
1888
1889 dispatchEntry->resolvedFlags = motionEntry->flags;
1890 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
1891 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
1892 }
1893
1894 if (!connection->inputState.trackMotion(motionEntry,
1895 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags)) {
1896#if DEBUG_DISPATCH_CYCLE
Steve Block5baa3a62011-12-20 16:23:08 +00001897 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion event",
Jeff Brown81346812011-06-28 20:08:48 -07001898 connection->getInputChannelName());
1899#endif
Jeff Brownc0cb3dc2012-01-12 18:30:12 -08001900 delete dispatchEntry;
Jeff Brown81346812011-06-28 20:08:48 -07001901 return; // skip the inconsistent event
1902 }
1903 break;
1904 }
1905 }
1906
Jeff Brownc0cb3dc2012-01-12 18:30:12 -08001907 // Remember that we are waiting for this dispatch to complete.
1908 if (dispatchEntry->hasForegroundTarget()) {
1909 incrementPendingForegroundDispatchesLocked(eventEntry);
1910 }
1911
Jeff Brown46b9ac02010-04-22 18:58:52 -07001912 // Enqueue the dispatch entry.
1913 connection->outboundQueue.enqueueAtTail(dispatchEntry);
Jeff Brown481c1572012-03-09 14:41:15 -08001914 traceOutboundQueueLengthLocked(connection);
Jeff Brown46b9ac02010-04-22 18:58:52 -07001915}
1916
Jeff Brown7fbdc842010-06-17 20:52:56 -07001917void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Jeff Brown519e0242010-09-15 15:18:56 -07001918 const sp<Connection>& connection) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07001919#if DEBUG_DISPATCH_CYCLE
Steve Block5baa3a62011-12-20 16:23:08 +00001920 ALOGD("channel '%s' ~ startDispatchCycle",
Jeff Brown46b9ac02010-04-22 18:58:52 -07001921 connection->getInputChannelName());
1922#endif
1923
Jeff Brownd1c48a02012-02-06 19:12:47 -08001924 while (connection->status == Connection::STATUS_NORMAL
1925 && !connection->outboundQueue.isEmpty()) {
1926 DispatchEntry* dispatchEntry = connection->outboundQueue.head;
Jeff Brown265f1cc2012-06-11 18:01:06 -07001927 dispatchEntry->deliveryTime = currentTime;
Jeff Brown46b9ac02010-04-22 18:58:52 -07001928
Jeff Brownd1c48a02012-02-06 19:12:47 -08001929 // Publish the event.
1930 status_t status;
1931 EventEntry* eventEntry = dispatchEntry->eventEntry;
1932 switch (eventEntry->type) {
1933 case EventEntry::TYPE_KEY: {
1934 KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
Jeff Brown46b9ac02010-04-22 18:58:52 -07001935
Jeff Brownd1c48a02012-02-06 19:12:47 -08001936 // Publish the key event.
Jeff Brown072ec962012-02-07 14:46:57 -08001937 status = connection->inputPublisher.publishKeyEvent(dispatchEntry->seq,
Jeff Brownd1c48a02012-02-06 19:12:47 -08001938 keyEntry->deviceId, keyEntry->source,
1939 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags,
1940 keyEntry->keyCode, keyEntry->scanCode,
1941 keyEntry->metaState, keyEntry->repeatCount, keyEntry->downTime,
1942 keyEntry->eventTime);
1943 break;
1944 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001945
Jeff Brownd1c48a02012-02-06 19:12:47 -08001946 case EventEntry::TYPE_MOTION: {
1947 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
Jeff Brown46b9ac02010-04-22 18:58:52 -07001948
Jeff Brownd1c48a02012-02-06 19:12:47 -08001949 PointerCoords scaledCoords[MAX_POINTERS];
1950 const PointerCoords* usingCoords = motionEntry->pointerCoords;
Jeff Brown46b9ac02010-04-22 18:58:52 -07001951
Jeff Brownd1c48a02012-02-06 19:12:47 -08001952 // Set the X and Y offset depending on the input source.
1953 float xOffset, yOffset, scaleFactor;
1954 if ((motionEntry->source & AINPUT_SOURCE_CLASS_POINTER)
1955 && !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
1956 scaleFactor = dispatchEntry->scaleFactor;
1957 xOffset = dispatchEntry->xOffset * scaleFactor;
1958 yOffset = dispatchEntry->yOffset * scaleFactor;
1959 if (scaleFactor != 1.0f) {
1960 for (size_t i = 0; i < motionEntry->pointerCount; i++) {
1961 scaledCoords[i] = motionEntry->pointerCoords[i];
1962 scaledCoords[i].scale(scaleFactor);
1963 }
1964 usingCoords = scaledCoords;
1965 }
1966 } else {
1967 xOffset = 0.0f;
1968 yOffset = 0.0f;
1969 scaleFactor = 1.0f;
1970
1971 // We don't want the dispatch target to know.
1972 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
1973 for (size_t i = 0; i < motionEntry->pointerCount; i++) {
1974 scaledCoords[i].clear();
1975 }
1976 usingCoords = scaledCoords;
1977 }
1978 }
1979
1980 // Publish the motion event.
Jeff Brown072ec962012-02-07 14:46:57 -08001981 status = connection->inputPublisher.publishMotionEvent(dispatchEntry->seq,
Jeff Brownd1c48a02012-02-06 19:12:47 -08001982 motionEntry->deviceId, motionEntry->source,
1983 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags,
1984 motionEntry->edgeFlags, motionEntry->metaState, motionEntry->buttonState,
1985 xOffset, yOffset,
1986 motionEntry->xPrecision, motionEntry->yPrecision,
1987 motionEntry->downTime, motionEntry->eventTime,
1988 motionEntry->pointerCount, motionEntry->pointerProperties,
1989 usingCoords);
1990 break;
1991 }
1992
1993 default:
1994 ALOG_ASSERT(false);
Jeff Brown46b9ac02010-04-22 18:58:52 -07001995 return;
1996 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07001997
Jeff Brownd1c48a02012-02-06 19:12:47 -08001998 // Check the result.
Jeff Brown46b9ac02010-04-22 18:58:52 -07001999 if (status) {
Jeff Brownd1c48a02012-02-06 19:12:47 -08002000 if (status == WOULD_BLOCK) {
2001 if (connection->waitQueue.isEmpty()) {
2002 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
2003 "This is unexpected because the wait queue is empty, so the pipe "
2004 "should be empty and we shouldn't have any problems writing an "
2005 "event to it, status=%d", connection->getInputChannelName(), status);
2006 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2007 } else {
2008 // Pipe is full and we are waiting for the app to finish process some events
2009 // before sending more events to it.
2010#if DEBUG_DISPATCH_CYCLE
2011 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
2012 "waiting for the application to catch up",
2013 connection->getInputChannelName());
2014#endif
2015 connection->inputPublisherBlocked = true;
2016 }
2017 } else {
2018 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
2019 "status=%d", connection->getInputChannelName(), status);
2020 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2021 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002022 return;
2023 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002024
Jeff Brownd1c48a02012-02-06 19:12:47 -08002025 // Re-enqueue the event on the wait queue.
2026 connection->outboundQueue.dequeue(dispatchEntry);
Jeff Brown481c1572012-03-09 14:41:15 -08002027 traceOutboundQueueLengthLocked(connection);
Jeff Brownd1c48a02012-02-06 19:12:47 -08002028 connection->waitQueue.enqueueAtTail(dispatchEntry);
Jeff Brown481c1572012-03-09 14:41:15 -08002029 traceWaitQueueLengthLocked(connection);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002030 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002031}
2032
Jeff Brown7fbdc842010-06-17 20:52:56 -07002033void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Jeff Brown072ec962012-02-07 14:46:57 -08002034 const sp<Connection>& connection, uint32_t seq, bool handled) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002035#if DEBUG_DISPATCH_CYCLE
Jeff Brown072ec962012-02-07 14:46:57 -08002036 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
2037 connection->getInputChannelName(), seq, toString(handled));
Jeff Brown46b9ac02010-04-22 18:58:52 -07002038#endif
2039
Jeff Brownd1c48a02012-02-06 19:12:47 -08002040 connection->inputPublisherBlocked = false;
2041
Jeff Brown9c3cda02010-06-15 01:31:58 -07002042 if (connection->status == Connection::STATUS_BROKEN
2043 || connection->status == Connection::STATUS_ZOMBIE) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002044 return;
2045 }
2046
Jeff Brown3915bb82010-11-05 15:02:16 -07002047 // Notify other system components and prepare to start the next dispatch cycle.
Jeff Brown072ec962012-02-07 14:46:57 -08002048 onDispatchCycleFinishedLocked(currentTime, connection, seq, handled);
Jeff Brownb88102f2010-09-08 11:49:43 -07002049}
2050
Jeff Brownb6997262010-10-08 22:31:17 -07002051void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Jeff Browncc4f7db2011-08-30 20:34:48 -07002052 const sp<Connection>& connection, bool notify) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002053#if DEBUG_DISPATCH_CYCLE
Steve Block5baa3a62011-12-20 16:23:08 +00002054 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
Jeff Browncc4f7db2011-08-30 20:34:48 -07002055 connection->getInputChannelName(), toString(notify));
Jeff Brown46b9ac02010-04-22 18:58:52 -07002056#endif
2057
Jeff Brownd1c48a02012-02-06 19:12:47 -08002058 // Clear the dispatch queues.
2059 drainDispatchQueueLocked(&connection->outboundQueue);
Jeff Brown481c1572012-03-09 14:41:15 -08002060 traceOutboundQueueLengthLocked(connection);
Jeff Brownd1c48a02012-02-06 19:12:47 -08002061 drainDispatchQueueLocked(&connection->waitQueue);
Jeff Brown481c1572012-03-09 14:41:15 -08002062 traceWaitQueueLengthLocked(connection);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002063
Jeff Brownb6997262010-10-08 22:31:17 -07002064 // The connection appears to be unrecoverably broken.
Jeff Brown9c3cda02010-06-15 01:31:58 -07002065 // Ignore already broken or zombie connections.
Jeff Brownb6997262010-10-08 22:31:17 -07002066 if (connection->status == Connection::STATUS_NORMAL) {
2067 connection->status = Connection::STATUS_BROKEN;
Jeff Brown46b9ac02010-04-22 18:58:52 -07002068
Jeff Browncc4f7db2011-08-30 20:34:48 -07002069 if (notify) {
2070 // Notify other system components.
2071 onDispatchCycleBrokenLocked(currentTime, connection);
2072 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002073 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002074}
2075
Jeff Brownd1c48a02012-02-06 19:12:47 -08002076void InputDispatcher::drainDispatchQueueLocked(Queue<DispatchEntry>* queue) {
2077 while (!queue->isEmpty()) {
2078 DispatchEntry* dispatchEntry = queue->dequeueAtHead();
2079 releaseDispatchEntryLocked(dispatchEntry);
Jeff Brownb88102f2010-09-08 11:49:43 -07002080 }
Jeff Brownb88102f2010-09-08 11:49:43 -07002081}
2082
Jeff Brownd1c48a02012-02-06 19:12:47 -08002083void InputDispatcher::releaseDispatchEntryLocked(DispatchEntry* dispatchEntry) {
2084 if (dispatchEntry->hasForegroundTarget()) {
2085 decrementPendingForegroundDispatchesLocked(dispatchEntry->eventEntry);
2086 }
2087 delete dispatchEntry;
2088}
2089
Jeff Browncbee6d62012-02-03 20:11:27 -08002090int InputDispatcher::handleReceiveCallback(int fd, int events, void* data) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002091 InputDispatcher* d = static_cast<InputDispatcher*>(data);
2092
2093 { // acquire lock
2094 AutoMutex _l(d->mLock);
2095
Jeff Browncbee6d62012-02-03 20:11:27 -08002096 ssize_t connectionIndex = d->mConnectionsByFd.indexOfKey(fd);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002097 if (connectionIndex < 0) {
Steve Block3762c312012-01-06 19:20:56 +00002098 ALOGE("Received spurious receive callback for unknown input channel. "
Jeff Browncbee6d62012-02-03 20:11:27 -08002099 "fd=%d, events=0x%x", fd, events);
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002100 return 0; // remove the callback
Jeff Brown46b9ac02010-04-22 18:58:52 -07002101 }
2102
Jeff Browncc4f7db2011-08-30 20:34:48 -07002103 bool notify;
Jeff Browncbee6d62012-02-03 20:11:27 -08002104 sp<Connection> connection = d->mConnectionsByFd.valueAt(connectionIndex);
Jeff Browncc4f7db2011-08-30 20:34:48 -07002105 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
2106 if (!(events & ALOOPER_EVENT_INPUT)) {
Steve Block8564c8d2012-01-05 23:22:43 +00002107 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
Jeff Browncc4f7db2011-08-30 20:34:48 -07002108 "events=0x%x", connection->getInputChannelName(), events);
2109 return 1;
2110 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002111
Jeff Brown1adee112012-02-07 10:25:41 -08002112 nsecs_t currentTime = now();
2113 bool gotOne = false;
2114 status_t status;
2115 for (;;) {
Jeff Brown072ec962012-02-07 14:46:57 -08002116 uint32_t seq;
2117 bool handled;
2118 status = connection->inputPublisher.receiveFinishedSignal(&seq, &handled);
Jeff Brown1adee112012-02-07 10:25:41 -08002119 if (status) {
2120 break;
2121 }
Jeff Brown072ec962012-02-07 14:46:57 -08002122 d->finishDispatchCycleLocked(currentTime, connection, seq, handled);
Jeff Brown1adee112012-02-07 10:25:41 -08002123 gotOne = true;
2124 }
2125 if (gotOne) {
Jeff Browncc4f7db2011-08-30 20:34:48 -07002126 d->runCommandsLockedInterruptible();
Jeff Brown1adee112012-02-07 10:25:41 -08002127 if (status == WOULD_BLOCK) {
2128 return 1;
2129 }
Jeff Browncc4f7db2011-08-30 20:34:48 -07002130 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002131
Jeff Brown1adee112012-02-07 10:25:41 -08002132 notify = status != DEAD_OBJECT || !connection->monitor;
2133 if (notify) {
2134 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
2135 connection->getInputChannelName(), status);
2136 }
Jeff Browncc4f7db2011-08-30 20:34:48 -07002137 } else {
2138 // Monitor channels are never explicitly unregistered.
2139 // We do it automatically when the remote endpoint is closed so don't warn
2140 // about them.
2141 notify = !connection->monitor;
2142 if (notify) {
Steve Block8564c8d2012-01-05 23:22:43 +00002143 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. "
Jeff Browncc4f7db2011-08-30 20:34:48 -07002144 "events=0x%x", connection->getInputChannelName(), events);
2145 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002146 }
2147
Jeff Browncc4f7db2011-08-30 20:34:48 -07002148 // Unregister the channel.
2149 d->unregisterInputChannelLocked(connection->inputChannel, notify);
2150 return 0; // remove the callback
Jeff Brown46b9ac02010-04-22 18:58:52 -07002151 } // release lock
2152}
2153
Jeff Brownb6997262010-10-08 22:31:17 -07002154void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Jeff Brownda3d5a92011-03-29 15:11:34 -07002155 const CancelationOptions& options) {
Jeff Browncbee6d62012-02-03 20:11:27 -08002156 for (size_t i = 0; i < mConnectionsByFd.size(); i++) {
Jeff Brownb6997262010-10-08 22:31:17 -07002157 synthesizeCancelationEventsForConnectionLocked(
Jeff Browncbee6d62012-02-03 20:11:27 -08002158 mConnectionsByFd.valueAt(i), options);
Jeff Brownb6997262010-10-08 22:31:17 -07002159 }
2160}
2161
2162void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Jeff Brownda3d5a92011-03-29 15:11:34 -07002163 const sp<InputChannel>& channel, const CancelationOptions& options) {
Jeff Brownb6997262010-10-08 22:31:17 -07002164 ssize_t index = getConnectionIndexLocked(channel);
2165 if (index >= 0) {
2166 synthesizeCancelationEventsForConnectionLocked(
Jeff Browncbee6d62012-02-03 20:11:27 -08002167 mConnectionsByFd.valueAt(index), options);
Jeff Brownb6997262010-10-08 22:31:17 -07002168 }
2169}
2170
2171void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
Jeff Brownda3d5a92011-03-29 15:11:34 -07002172 const sp<Connection>& connection, const CancelationOptions& options) {
Jeff Brownc0cb3dc2012-01-12 18:30:12 -08002173 if (connection->status == Connection::STATUS_BROKEN) {
2174 return;
2175 }
2176
Jeff Brownb6997262010-10-08 22:31:17 -07002177 nsecs_t currentTime = now();
2178
Jeff Brown8b4be5602012-02-06 16:31:05 -08002179 Vector<EventEntry*> cancelationEvents;
Jeff Brownac386072011-07-20 15:19:50 -07002180 connection->inputState.synthesizeCancelationEvents(currentTime,
Jeff Brown8b4be5602012-02-06 16:31:05 -08002181 cancelationEvents, options);
Jeff Brownb6997262010-10-08 22:31:17 -07002182
Jeff Brown8b4be5602012-02-06 16:31:05 -08002183 if (!cancelationEvents.isEmpty()) {
Jeff Brownb6997262010-10-08 22:31:17 -07002184#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00002185 ALOGD("channel '%s' ~ Synthesized %d cancelation events to bring channel back in sync "
Jeff Brownda3d5a92011-03-29 15:11:34 -07002186 "with reality: %s, mode=%d.",
Jeff Brown8b4be5602012-02-06 16:31:05 -08002187 connection->getInputChannelName(), cancelationEvents.size(),
Jeff Brownda3d5a92011-03-29 15:11:34 -07002188 options.reason, options.mode);
Jeff Brownb6997262010-10-08 22:31:17 -07002189#endif
Jeff Brown8b4be5602012-02-06 16:31:05 -08002190 for (size_t i = 0; i < cancelationEvents.size(); i++) {
2191 EventEntry* cancelationEventEntry = cancelationEvents.itemAt(i);
Jeff Brownb6997262010-10-08 22:31:17 -07002192 switch (cancelationEventEntry->type) {
2193 case EventEntry::TYPE_KEY:
2194 logOutboundKeyDetailsLocked("cancel - ",
2195 static_cast<KeyEntry*>(cancelationEventEntry));
2196 break;
2197 case EventEntry::TYPE_MOTION:
2198 logOutboundMotionDetailsLocked("cancel - ",
2199 static_cast<MotionEntry*>(cancelationEventEntry));
2200 break;
2201 }
2202
Jeff Brown81346812011-06-28 20:08:48 -07002203 InputTarget target;
Jeff Brown9302c872011-07-13 22:51:29 -07002204 sp<InputWindowHandle> windowHandle = getWindowHandleLocked(connection->inputChannel);
2205 if (windowHandle != NULL) {
Jeff Browncc4f7db2011-08-30 20:34:48 -07002206 const InputWindowInfo* windowInfo = windowHandle->getInfo();
2207 target.xOffset = -windowInfo->frameLeft;
2208 target.yOffset = -windowInfo->frameTop;
2209 target.scaleFactor = windowInfo->scaleFactor;
Jeff Brownb6997262010-10-08 22:31:17 -07002210 } else {
Jeff Brown81346812011-06-28 20:08:48 -07002211 target.xOffset = 0;
2212 target.yOffset = 0;
2213 target.scaleFactor = 1.0f;
Jeff Brownb6997262010-10-08 22:31:17 -07002214 }
Jeff Brown81346812011-06-28 20:08:48 -07002215 target.inputChannel = connection->inputChannel;
2216 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
Jeff Brownb6997262010-10-08 22:31:17 -07002217
Jeff Brown81346812011-06-28 20:08:48 -07002218 enqueueDispatchEntryLocked(connection, cancelationEventEntry, // increments ref
Jeff Brown3241b6b2012-02-03 15:08:02 -08002219 &target, InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brownb6997262010-10-08 22:31:17 -07002220
Jeff Brownac386072011-07-20 15:19:50 -07002221 cancelationEventEntry->release();
Jeff Brownb6997262010-10-08 22:31:17 -07002222 }
2223
Jeff Brownd1c48a02012-02-06 19:12:47 -08002224 startDispatchCycleLocked(currentTime, connection);
Jeff Brownb6997262010-10-08 22:31:17 -07002225 }
2226}
2227
Jeff Brown01ce2e92010-09-26 22:20:12 -07002228InputDispatcher::MotionEntry*
2229InputDispatcher::splitMotionEvent(const MotionEntry* originalMotionEntry, BitSet32 pointerIds) {
Steve Blockec193de2012-01-09 18:35:44 +00002230 ALOG_ASSERT(pointerIds.value != 0);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002231
2232 uint32_t splitPointerIndexMap[MAX_POINTERS];
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002233 PointerProperties splitPointerProperties[MAX_POINTERS];
Jeff Brown01ce2e92010-09-26 22:20:12 -07002234 PointerCoords splitPointerCoords[MAX_POINTERS];
2235
2236 uint32_t originalPointerCount = originalMotionEntry->pointerCount;
2237 uint32_t splitPointerCount = 0;
2238
2239 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
2240 originalPointerIndex++) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002241 const PointerProperties& pointerProperties =
2242 originalMotionEntry->pointerProperties[originalPointerIndex];
2243 uint32_t pointerId = uint32_t(pointerProperties.id);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002244 if (pointerIds.hasBit(pointerId)) {
2245 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002246 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
Jeff Brownace13b12011-03-09 17:39:48 -08002247 splitPointerCoords[splitPointerCount].copyFrom(
Jeff Brown3241b6b2012-02-03 15:08:02 -08002248 originalMotionEntry->pointerCoords[originalPointerIndex]);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002249 splitPointerCount += 1;
2250 }
2251 }
Jeff Brown58a2da82011-01-25 16:02:22 -08002252
2253 if (splitPointerCount != pointerIds.count()) {
2254 // This is bad. We are missing some of the pointers that we expected to deliver.
2255 // Most likely this indicates that we received an ACTION_MOVE events that has
2256 // different pointer ids than we expected based on the previous ACTION_DOWN
2257 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
2258 // in this way.
Steve Block8564c8d2012-01-05 23:22:43 +00002259 ALOGW("Dropping split motion event because the pointer count is %d but "
Jeff Brown58a2da82011-01-25 16:02:22 -08002260 "we expected there to be %d pointers. This probably means we received "
2261 "a broken sequence of pointer ids from the input device.",
2262 splitPointerCount, pointerIds.count());
2263 return NULL;
2264 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07002265
2266 int32_t action = originalMotionEntry->action;
2267 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
2268 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
2269 || maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2270 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002271 const PointerProperties& pointerProperties =
2272 originalMotionEntry->pointerProperties[originalPointerIndex];
2273 uint32_t pointerId = uint32_t(pointerProperties.id);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002274 if (pointerIds.hasBit(pointerId)) {
2275 if (pointerIds.count() == 1) {
2276 // The first/last pointer went down/up.
2277 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
2278 ? AMOTION_EVENT_ACTION_DOWN : AMOTION_EVENT_ACTION_UP;
Jeff Brown9a01d052010-09-27 16:35:11 -07002279 } else {
2280 // A secondary pointer went down/up.
2281 uint32_t splitPointerIndex = 0;
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002282 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
Jeff Brown9a01d052010-09-27 16:35:11 -07002283 splitPointerIndex += 1;
2284 }
2285 action = maskedAction | (splitPointerIndex
2286 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002287 }
2288 } else {
2289 // An unrelated pointer changed.
2290 action = AMOTION_EVENT_ACTION_MOVE;
2291 }
2292 }
2293
Jeff Brownac386072011-07-20 15:19:50 -07002294 MotionEntry* splitMotionEntry = new MotionEntry(
Jeff Brown01ce2e92010-09-26 22:20:12 -07002295 originalMotionEntry->eventTime,
2296 originalMotionEntry->deviceId,
2297 originalMotionEntry->source,
2298 originalMotionEntry->policyFlags,
2299 action,
2300 originalMotionEntry->flags,
2301 originalMotionEntry->metaState,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002302 originalMotionEntry->buttonState,
Jeff Brown01ce2e92010-09-26 22:20:12 -07002303 originalMotionEntry->edgeFlags,
2304 originalMotionEntry->xPrecision,
2305 originalMotionEntry->yPrecision,
2306 originalMotionEntry->downTime,
Jeff Brown83d616a2012-09-09 20:33:43 -07002307 originalMotionEntry->displayId,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002308 splitPointerCount, splitPointerProperties, splitPointerCoords);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002309
Jeff Browna032cc02011-03-07 16:56:21 -08002310 if (originalMotionEntry->injectionState) {
2311 splitMotionEntry->injectionState = originalMotionEntry->injectionState;
2312 splitMotionEntry->injectionState->refCount += 1;
2313 }
2314
Jeff Brown01ce2e92010-09-26 22:20:12 -07002315 return splitMotionEntry;
2316}
2317
Jeff Brownbe1aa822011-07-27 16:04:54 -07002318void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002319#if DEBUG_INBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00002320 ALOGD("notifyConfigurationChanged - eventTime=%lld", args->eventTime);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002321#endif
2322
Jeff Brownb88102f2010-09-08 11:49:43 -07002323 bool needWake;
Jeff Brown46b9ac02010-04-22 18:58:52 -07002324 { // acquire lock
2325 AutoMutex _l(mLock);
2326
Jeff Brownbe1aa822011-07-27 16:04:54 -07002327 ConfigurationChangedEntry* newEntry = new ConfigurationChangedEntry(args->eventTime);
Jeff Brownb88102f2010-09-08 11:49:43 -07002328 needWake = enqueueInboundEventLocked(newEntry);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002329 } // release lock
2330
Jeff Brownb88102f2010-09-08 11:49:43 -07002331 if (needWake) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002332 mLooper->wake();
Jeff Brown46b9ac02010-04-22 18:58:52 -07002333 }
2334}
2335
Jeff Brownbe1aa822011-07-27 16:04:54 -07002336void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002337#if DEBUG_INBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00002338 ALOGD("notifyKey - eventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, action=0x%x, "
Jeff Brown46b9ac02010-04-22 18:58:52 -07002339 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%lld",
Jeff Brownbe1aa822011-07-27 16:04:54 -07002340 args->eventTime, args->deviceId, args->source, args->policyFlags,
2341 args->action, args->flags, args->keyCode, args->scanCode,
2342 args->metaState, args->downTime);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002343#endif
Jeff Brownbe1aa822011-07-27 16:04:54 -07002344 if (!validateKeyEvent(args->action)) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002345 return;
2346 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002347
Jeff Brownbe1aa822011-07-27 16:04:54 -07002348 uint32_t policyFlags = args->policyFlags;
2349 int32_t flags = args->flags;
2350 int32_t metaState = args->metaState;
Jeff Brown1f245102010-11-18 20:53:46 -08002351 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
2352 policyFlags |= POLICY_FLAG_VIRTUAL;
2353 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
2354 }
Jeff Brown924c4d42011-03-07 16:40:47 -08002355 if (policyFlags & POLICY_FLAG_ALT) {
2356 metaState |= AMETA_ALT_ON | AMETA_ALT_LEFT_ON;
2357 }
2358 if (policyFlags & POLICY_FLAG_ALT_GR) {
2359 metaState |= AMETA_ALT_ON | AMETA_ALT_RIGHT_ON;
2360 }
2361 if (policyFlags & POLICY_FLAG_SHIFT) {
2362 metaState |= AMETA_SHIFT_ON | AMETA_SHIFT_LEFT_ON;
2363 }
2364 if (policyFlags & POLICY_FLAG_CAPS_LOCK) {
2365 metaState |= AMETA_CAPS_LOCK_ON;
2366 }
2367 if (policyFlags & POLICY_FLAG_FUNCTION) {
2368 metaState |= AMETA_FUNCTION_ON;
2369 }
Jeff Brown1f245102010-11-18 20:53:46 -08002370
Jeff Browne20c9e02010-10-11 14:20:19 -07002371 policyFlags |= POLICY_FLAG_TRUSTED;
Jeff Brown1f245102010-11-18 20:53:46 -08002372
2373 KeyEvent event;
Jeff Brownbe1aa822011-07-27 16:04:54 -07002374 event.initialize(args->deviceId, args->source, args->action,
2375 flags, args->keyCode, args->scanCode, metaState, 0,
2376 args->downTime, args->eventTime);
Jeff Brown1f245102010-11-18 20:53:46 -08002377
2378 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
2379
2380 if (policyFlags & POLICY_FLAG_WOKE_HERE) {
2381 flags |= AKEY_EVENT_FLAG_WOKE_HERE;
2382 }
Jeff Brownb6997262010-10-08 22:31:17 -07002383
Jeff Brownb88102f2010-09-08 11:49:43 -07002384 bool needWake;
Jeff Brown46b9ac02010-04-22 18:58:52 -07002385 { // acquire lock
Jeff Brown0029c662011-03-30 02:25:18 -07002386 mLock.lock();
2387
Jeff Brown83d616a2012-09-09 20:33:43 -07002388 if (shouldSendKeyToInputFilterLocked(args)) {
Jeff Brown0029c662011-03-30 02:25:18 -07002389 mLock.unlock();
2390
2391 policyFlags |= POLICY_FLAG_FILTERED;
2392 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2393 return; // event was consumed by the filter
2394 }
2395
2396 mLock.lock();
2397 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002398
Jeff Brown7fbdc842010-06-17 20:52:56 -07002399 int32_t repeatCount = 0;
Jeff Brownbe1aa822011-07-27 16:04:54 -07002400 KeyEntry* newEntry = new KeyEntry(args->eventTime,
2401 args->deviceId, args->source, policyFlags,
2402 args->action, flags, args->keyCode, args->scanCode,
2403 metaState, repeatCount, args->downTime);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002404
Jeff Brownb88102f2010-09-08 11:49:43 -07002405 needWake = enqueueInboundEventLocked(newEntry);
Jeff Brown0029c662011-03-30 02:25:18 -07002406 mLock.unlock();
Jeff Brown46b9ac02010-04-22 18:58:52 -07002407 } // release lock
2408
Jeff Brownb88102f2010-09-08 11:49:43 -07002409 if (needWake) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002410 mLooper->wake();
Jeff Brown46b9ac02010-04-22 18:58:52 -07002411 }
2412}
2413
Jeff Brown83d616a2012-09-09 20:33:43 -07002414bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
2415 return mInputFilterEnabled;
2416}
2417
Jeff Brownbe1aa822011-07-27 16:04:54 -07002418void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002419#if DEBUG_INBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00002420 ALOGD("notifyMotion - eventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, "
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002421 "action=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, edgeFlags=0x%x, "
Jeff Brown85a31762010-09-01 17:01:00 -07002422 "xPrecision=%f, yPrecision=%f, downTime=%lld",
Jeff Brownbe1aa822011-07-27 16:04:54 -07002423 args->eventTime, args->deviceId, args->source, args->policyFlags,
2424 args->action, args->flags, args->metaState, args->buttonState,
2425 args->edgeFlags, args->xPrecision, args->yPrecision, args->downTime);
2426 for (uint32_t i = 0; i < args->pointerCount; i++) {
Steve Block5baa3a62011-12-20 16:23:08 +00002427 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002428 "x=%f, y=%f, pressure=%f, size=%f, "
Jeff Brown85a31762010-09-01 17:01:00 -07002429 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
Jeff Brown8d608662010-08-30 03:02:23 -07002430 "orientation=%f",
Jeff Brownbe1aa822011-07-27 16:04:54 -07002431 i, args->pointerProperties[i].id,
2432 args->pointerProperties[i].toolType,
2433 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
2434 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
2435 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
2436 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
2437 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
2438 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
2439 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
2440 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
2441 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Jeff Brown46b9ac02010-04-22 18:58:52 -07002442 }
2443#endif
Jeff Brownbe1aa822011-07-27 16:04:54 -07002444 if (!validateMotionEvent(args->action, args->pointerCount, args->pointerProperties)) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002445 return;
2446 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002447
Jeff Brownbe1aa822011-07-27 16:04:54 -07002448 uint32_t policyFlags = args->policyFlags;
Jeff Browne20c9e02010-10-11 14:20:19 -07002449 policyFlags |= POLICY_FLAG_TRUSTED;
Jeff Brownbe1aa822011-07-27 16:04:54 -07002450 mPolicy->interceptMotionBeforeQueueing(args->eventTime, /*byref*/ policyFlags);
Jeff Brownb6997262010-10-08 22:31:17 -07002451
Jeff Brownb88102f2010-09-08 11:49:43 -07002452 bool needWake;
Jeff Brown46b9ac02010-04-22 18:58:52 -07002453 { // acquire lock
Jeff Brown0029c662011-03-30 02:25:18 -07002454 mLock.lock();
2455
Jeff Brown83d616a2012-09-09 20:33:43 -07002456 if (shouldSendMotionToInputFilterLocked(args)) {
Jeff Brown0029c662011-03-30 02:25:18 -07002457 mLock.unlock();
2458
2459 MotionEvent event;
Jeff Brownbe1aa822011-07-27 16:04:54 -07002460 event.initialize(args->deviceId, args->source, args->action, args->flags,
2461 args->edgeFlags, args->metaState, args->buttonState, 0, 0,
2462 args->xPrecision, args->yPrecision,
2463 args->downTime, args->eventTime,
2464 args->pointerCount, args->pointerProperties, args->pointerCoords);
Jeff Brown0029c662011-03-30 02:25:18 -07002465
2466 policyFlags |= POLICY_FLAG_FILTERED;
2467 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2468 return; // event was consumed by the filter
2469 }
2470
2471 mLock.lock();
2472 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002473
Jeff Brown46b9ac02010-04-22 18:58:52 -07002474 // Just enqueue a new motion event.
Jeff Brownbe1aa822011-07-27 16:04:54 -07002475 MotionEntry* newEntry = new MotionEntry(args->eventTime,
2476 args->deviceId, args->source, policyFlags,
2477 args->action, args->flags, args->metaState, args->buttonState,
2478 args->edgeFlags, args->xPrecision, args->yPrecision, args->downTime,
Jeff Brown83d616a2012-09-09 20:33:43 -07002479 args->displayId,
Jeff Brownbe1aa822011-07-27 16:04:54 -07002480 args->pointerCount, args->pointerProperties, args->pointerCoords);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002481
Jeff Brownb88102f2010-09-08 11:49:43 -07002482 needWake = enqueueInboundEventLocked(newEntry);
Jeff Brown0029c662011-03-30 02:25:18 -07002483 mLock.unlock();
Jeff Brown46b9ac02010-04-22 18:58:52 -07002484 } // release lock
2485
Jeff Brownb88102f2010-09-08 11:49:43 -07002486 if (needWake) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002487 mLooper->wake();
Jeff Brown46b9ac02010-04-22 18:58:52 -07002488 }
2489}
2490
Jeff Brown83d616a2012-09-09 20:33:43 -07002491bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
2492 // TODO: support sending secondary display events to input filter
2493 return mInputFilterEnabled && isMainDisplay(args->displayId);
2494}
2495
Jeff Brownbe1aa822011-07-27 16:04:54 -07002496void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
Jeff Brownb6997262010-10-08 22:31:17 -07002497#if DEBUG_INBOUND_EVENT_DETAILS
Jeff Brownbcc046a2012-09-27 20:46:43 -07002498 ALOGD("notifySwitch - eventTime=%lld, policyFlags=0x%x, switchValues=0x%08x, switchMask=0x%08x",
Jeff Brownbe1aa822011-07-27 16:04:54 -07002499 args->eventTime, args->policyFlags,
Jeff Brownbcc046a2012-09-27 20:46:43 -07002500 args->switchValues, args->switchMask);
Jeff Brownb6997262010-10-08 22:31:17 -07002501#endif
2502
Jeff Brownbe1aa822011-07-27 16:04:54 -07002503 uint32_t policyFlags = args->policyFlags;
Jeff Browne20c9e02010-10-11 14:20:19 -07002504 policyFlags |= POLICY_FLAG_TRUSTED;
Jeff Brownbe1aa822011-07-27 16:04:54 -07002505 mPolicy->notifySwitch(args->eventTime,
Jeff Brownbcc046a2012-09-27 20:46:43 -07002506 args->switchValues, args->switchMask, policyFlags);
Jeff Brownb6997262010-10-08 22:31:17 -07002507}
2508
Jeff Brown65fd2512011-08-18 11:20:58 -07002509void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
2510#if DEBUG_INBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00002511 ALOGD("notifyDeviceReset - eventTime=%lld, deviceId=%d",
Jeff Brown65fd2512011-08-18 11:20:58 -07002512 args->eventTime, args->deviceId);
2513#endif
2514
2515 bool needWake;
2516 { // acquire lock
2517 AutoMutex _l(mLock);
2518
2519 DeviceResetEntry* newEntry = new DeviceResetEntry(args->eventTime, args->deviceId);
2520 needWake = enqueueInboundEventLocked(newEntry);
2521 } // release lock
2522
2523 if (needWake) {
2524 mLooper->wake();
2525 }
2526}
2527
Jeff Brown7fbdc842010-06-17 20:52:56 -07002528int32_t InputDispatcher::injectInputEvent(const InputEvent* event,
Jeff Brown0029c662011-03-30 02:25:18 -07002529 int32_t injectorPid, int32_t injectorUid, int32_t syncMode, int32_t timeoutMillis,
2530 uint32_t policyFlags) {
Jeff Brown7fbdc842010-06-17 20:52:56 -07002531#if DEBUG_INBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00002532 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Jeff Brown0029c662011-03-30 02:25:18 -07002533 "syncMode=%d, timeoutMillis=%d, policyFlags=0x%08x",
2534 event->getType(), injectorPid, injectorUid, syncMode, timeoutMillis, policyFlags);
Jeff Brown7fbdc842010-06-17 20:52:56 -07002535#endif
2536
2537 nsecs_t endTime = now() + milliseconds_to_nanoseconds(timeoutMillis);
Jeff Browne20c9e02010-10-11 14:20:19 -07002538
Jeff Brown0029c662011-03-30 02:25:18 -07002539 policyFlags |= POLICY_FLAG_INJECTED;
Jeff Browne20c9e02010-10-11 14:20:19 -07002540 if (hasInjectionPermission(injectorPid, injectorUid)) {
2541 policyFlags |= POLICY_FLAG_TRUSTED;
2542 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07002543
Jeff Brown3241b6b2012-02-03 15:08:02 -08002544 EventEntry* firstInjectedEntry;
2545 EventEntry* lastInjectedEntry;
Jeff Brownb6997262010-10-08 22:31:17 -07002546 switch (event->getType()) {
2547 case AINPUT_EVENT_TYPE_KEY: {
2548 const KeyEvent* keyEvent = static_cast<const KeyEvent*>(event);
2549 int32_t action = keyEvent->getAction();
2550 if (! validateKeyEvent(action)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07002551 return INPUT_EVENT_INJECTION_FAILED;
2552 }
2553
Jeff Brownb6997262010-10-08 22:31:17 -07002554 int32_t flags = keyEvent->getFlags();
Jeff Brown1f245102010-11-18 20:53:46 -08002555 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
2556 policyFlags |= POLICY_FLAG_VIRTUAL;
2557 }
2558
Jeff Brown0029c662011-03-30 02:25:18 -07002559 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
2560 mPolicy->interceptKeyBeforeQueueing(keyEvent, /*byref*/ policyFlags);
2561 }
Jeff Brown1f245102010-11-18 20:53:46 -08002562
2563 if (policyFlags & POLICY_FLAG_WOKE_HERE) {
2564 flags |= AKEY_EVENT_FLAG_WOKE_HERE;
2565 }
Jeff Brown6ec402b2010-07-28 15:48:59 -07002566
Jeff Brownb6997262010-10-08 22:31:17 -07002567 mLock.lock();
Jeff Brown3241b6b2012-02-03 15:08:02 -08002568 firstInjectedEntry = new KeyEntry(keyEvent->getEventTime(),
Jeff Brown1f245102010-11-18 20:53:46 -08002569 keyEvent->getDeviceId(), keyEvent->getSource(),
2570 policyFlags, action, flags,
2571 keyEvent->getKeyCode(), keyEvent->getScanCode(), keyEvent->getMetaState(),
Jeff Brownb6997262010-10-08 22:31:17 -07002572 keyEvent->getRepeatCount(), keyEvent->getDownTime());
Jeff Brown3241b6b2012-02-03 15:08:02 -08002573 lastInjectedEntry = firstInjectedEntry;
Jeff Brownb6997262010-10-08 22:31:17 -07002574 break;
2575 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07002576
Jeff Brownb6997262010-10-08 22:31:17 -07002577 case AINPUT_EVENT_TYPE_MOTION: {
2578 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
Jeff Brown83d616a2012-09-09 20:33:43 -07002579 int32_t displayId = ADISPLAY_ID_DEFAULT;
Jeff Brownb6997262010-10-08 22:31:17 -07002580 int32_t action = motionEvent->getAction();
2581 size_t pointerCount = motionEvent->getPointerCount();
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002582 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
2583 if (! validateMotionEvent(action, pointerCount, pointerProperties)) {
Jeff Brownb6997262010-10-08 22:31:17 -07002584 return INPUT_EVENT_INJECTION_FAILED;
2585 }
2586
Jeff Brown0029c662011-03-30 02:25:18 -07002587 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
2588 nsecs_t eventTime = motionEvent->getEventTime();
2589 mPolicy->interceptMotionBeforeQueueing(eventTime, /*byref*/ policyFlags);
2590 }
Jeff Brownb6997262010-10-08 22:31:17 -07002591
2592 mLock.lock();
2593 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
2594 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
Jeff Brown3241b6b2012-02-03 15:08:02 -08002595 firstInjectedEntry = new MotionEntry(*sampleEventTimes,
Jeff Brownb6997262010-10-08 22:31:17 -07002596 motionEvent->getDeviceId(), motionEvent->getSource(), policyFlags,
2597 action, motionEvent->getFlags(),
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002598 motionEvent->getMetaState(), motionEvent->getButtonState(),
2599 motionEvent->getEdgeFlags(),
Jeff Brownb6997262010-10-08 22:31:17 -07002600 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
Jeff Brown83d616a2012-09-09 20:33:43 -07002601 motionEvent->getDownTime(), displayId,
2602 uint32_t(pointerCount), pointerProperties, samplePointerCoords);
Jeff Brown3241b6b2012-02-03 15:08:02 -08002603 lastInjectedEntry = firstInjectedEntry;
Jeff Brownb6997262010-10-08 22:31:17 -07002604 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
2605 sampleEventTimes += 1;
2606 samplePointerCoords += pointerCount;
Jeff Brown3241b6b2012-02-03 15:08:02 -08002607 MotionEntry* nextInjectedEntry = new MotionEntry(*sampleEventTimes,
2608 motionEvent->getDeviceId(), motionEvent->getSource(), policyFlags,
2609 action, motionEvent->getFlags(),
2610 motionEvent->getMetaState(), motionEvent->getButtonState(),
2611 motionEvent->getEdgeFlags(),
2612 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
Jeff Brown83d616a2012-09-09 20:33:43 -07002613 motionEvent->getDownTime(), displayId,
2614 uint32_t(pointerCount), pointerProperties, samplePointerCoords);
Jeff Brown3241b6b2012-02-03 15:08:02 -08002615 lastInjectedEntry->next = nextInjectedEntry;
2616 lastInjectedEntry = nextInjectedEntry;
Jeff Brownb6997262010-10-08 22:31:17 -07002617 }
Jeff Brownb6997262010-10-08 22:31:17 -07002618 break;
2619 }
2620
2621 default:
Steve Block8564c8d2012-01-05 23:22:43 +00002622 ALOGW("Cannot inject event of type %d", event->getType());
Jeff Brownb6997262010-10-08 22:31:17 -07002623 return INPUT_EVENT_INJECTION_FAILED;
2624 }
2625
Jeff Brownac386072011-07-20 15:19:50 -07002626 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
Jeff Brownb6997262010-10-08 22:31:17 -07002627 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
2628 injectionState->injectionIsAsync = true;
2629 }
2630
2631 injectionState->refCount += 1;
Jeff Brown3241b6b2012-02-03 15:08:02 -08002632 lastInjectedEntry->injectionState = injectionState;
Jeff Brownb6997262010-10-08 22:31:17 -07002633
Jeff Brown3241b6b2012-02-03 15:08:02 -08002634 bool needWake = false;
2635 for (EventEntry* entry = firstInjectedEntry; entry != NULL; ) {
2636 EventEntry* nextEntry = entry->next;
2637 needWake |= enqueueInboundEventLocked(entry);
2638 entry = nextEntry;
2639 }
2640
Jeff Brownb6997262010-10-08 22:31:17 -07002641 mLock.unlock();
Jeff Brown7fbdc842010-06-17 20:52:56 -07002642
Jeff Brownb88102f2010-09-08 11:49:43 -07002643 if (needWake) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002644 mLooper->wake();
Jeff Brown7fbdc842010-06-17 20:52:56 -07002645 }
2646
2647 int32_t injectionResult;
2648 { // acquire lock
2649 AutoMutex _l(mLock);
2650
Jeff Brown6ec402b2010-07-28 15:48:59 -07002651 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
2652 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
2653 } else {
2654 for (;;) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002655 injectionResult = injectionState->injectionResult;
Jeff Brown6ec402b2010-07-28 15:48:59 -07002656 if (injectionResult != INPUT_EVENT_INJECTION_PENDING) {
2657 break;
2658 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07002659
Jeff Brown7fbdc842010-06-17 20:52:56 -07002660 nsecs_t remainingTimeout = endTime - now();
2661 if (remainingTimeout <= 0) {
Jeff Brown6ec402b2010-07-28 15:48:59 -07002662#if DEBUG_INJECTION
Steve Block5baa3a62011-12-20 16:23:08 +00002663 ALOGD("injectInputEvent - Timed out waiting for injection result "
Jeff Brown6ec402b2010-07-28 15:48:59 -07002664 "to become available.");
2665#endif
Jeff Brown7fbdc842010-06-17 20:52:56 -07002666 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
2667 break;
2668 }
2669
Jeff Brown6ec402b2010-07-28 15:48:59 -07002670 mInjectionResultAvailableCondition.waitRelative(mLock, remainingTimeout);
2671 }
2672
2673 if (injectionResult == INPUT_EVENT_INJECTION_SUCCEEDED
2674 && syncMode == INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002675 while (injectionState->pendingForegroundDispatches != 0) {
Jeff Brown6ec402b2010-07-28 15:48:59 -07002676#if DEBUG_INJECTION
Steve Block5baa3a62011-12-20 16:23:08 +00002677 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
Jeff Brown01ce2e92010-09-26 22:20:12 -07002678 injectionState->pendingForegroundDispatches);
Jeff Brown6ec402b2010-07-28 15:48:59 -07002679#endif
2680 nsecs_t remainingTimeout = endTime - now();
2681 if (remainingTimeout <= 0) {
2682#if DEBUG_INJECTION
Steve Block5baa3a62011-12-20 16:23:08 +00002683 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
Jeff Brown6ec402b2010-07-28 15:48:59 -07002684 "dispatches to finish.");
2685#endif
2686 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
2687 break;
2688 }
2689
2690 mInjectionSyncFinishedCondition.waitRelative(mLock, remainingTimeout);
2691 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07002692 }
2693 }
2694
Jeff Brownac386072011-07-20 15:19:50 -07002695 injectionState->release();
Jeff Brown7fbdc842010-06-17 20:52:56 -07002696 } // release lock
2697
Jeff Brown6ec402b2010-07-28 15:48:59 -07002698#if DEBUG_INJECTION
Steve Block5baa3a62011-12-20 16:23:08 +00002699 ALOGD("injectInputEvent - Finished with result %d. "
Jeff Brown6ec402b2010-07-28 15:48:59 -07002700 "injectorPid=%d, injectorUid=%d",
2701 injectionResult, injectorPid, injectorUid);
2702#endif
2703
Jeff Brown7fbdc842010-06-17 20:52:56 -07002704 return injectionResult;
2705}
2706
Jeff Brownb6997262010-10-08 22:31:17 -07002707bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
2708 return injectorUid == 0
2709 || mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
2710}
2711
Jeff Brown7fbdc842010-06-17 20:52:56 -07002712void InputDispatcher::setInjectionResultLocked(EventEntry* entry, int32_t injectionResult) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002713 InjectionState* injectionState = entry->injectionState;
2714 if (injectionState) {
Jeff Brown7fbdc842010-06-17 20:52:56 -07002715#if DEBUG_INJECTION
Steve Block5baa3a62011-12-20 16:23:08 +00002716 ALOGD("Setting input event injection result to %d. "
Jeff Brown7fbdc842010-06-17 20:52:56 -07002717 "injectorPid=%d, injectorUid=%d",
Jeff Brown01ce2e92010-09-26 22:20:12 -07002718 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
Jeff Brown7fbdc842010-06-17 20:52:56 -07002719#endif
2720
Jeff Brown0029c662011-03-30 02:25:18 -07002721 if (injectionState->injectionIsAsync
2722 && !(entry->policyFlags & POLICY_FLAG_FILTERED)) {
Jeff Brown6ec402b2010-07-28 15:48:59 -07002723 // Log the outcome since the injector did not wait for the injection result.
2724 switch (injectionResult) {
2725 case INPUT_EVENT_INJECTION_SUCCEEDED:
Steve Block71f2cf12011-10-20 11:56:00 +01002726 ALOGV("Asynchronous input event injection succeeded.");
Jeff Brown6ec402b2010-07-28 15:48:59 -07002727 break;
2728 case INPUT_EVENT_INJECTION_FAILED:
Steve Block8564c8d2012-01-05 23:22:43 +00002729 ALOGW("Asynchronous input event injection failed.");
Jeff Brown6ec402b2010-07-28 15:48:59 -07002730 break;
2731 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
Steve Block8564c8d2012-01-05 23:22:43 +00002732 ALOGW("Asynchronous input event injection permission denied.");
Jeff Brown6ec402b2010-07-28 15:48:59 -07002733 break;
2734 case INPUT_EVENT_INJECTION_TIMED_OUT:
Steve Block8564c8d2012-01-05 23:22:43 +00002735 ALOGW("Asynchronous input event injection timed out.");
Jeff Brown6ec402b2010-07-28 15:48:59 -07002736 break;
2737 }
2738 }
2739
Jeff Brown01ce2e92010-09-26 22:20:12 -07002740 injectionState->injectionResult = injectionResult;
Jeff Brown7fbdc842010-06-17 20:52:56 -07002741 mInjectionResultAvailableCondition.broadcast();
2742 }
2743}
2744
Jeff Brown01ce2e92010-09-26 22:20:12 -07002745void InputDispatcher::incrementPendingForegroundDispatchesLocked(EventEntry* entry) {
2746 InjectionState* injectionState = entry->injectionState;
2747 if (injectionState) {
2748 injectionState->pendingForegroundDispatches += 1;
2749 }
2750}
2751
Jeff Brown519e0242010-09-15 15:18:56 -07002752void InputDispatcher::decrementPendingForegroundDispatchesLocked(EventEntry* entry) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002753 InjectionState* injectionState = entry->injectionState;
2754 if (injectionState) {
2755 injectionState->pendingForegroundDispatches -= 1;
Jeff Brown6ec402b2010-07-28 15:48:59 -07002756
Jeff Brown01ce2e92010-09-26 22:20:12 -07002757 if (injectionState->pendingForegroundDispatches == 0) {
2758 mInjectionSyncFinishedCondition.broadcast();
2759 }
Jeff Brownb88102f2010-09-08 11:49:43 -07002760 }
2761}
2762
Jeff Brown9302c872011-07-13 22:51:29 -07002763sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
2764 const sp<InputChannel>& inputChannel) const {
2765 size_t numWindows = mWindowHandles.size();
2766 for (size_t i = 0; i < numWindows; i++) {
2767 const sp<InputWindowHandle>& windowHandle = mWindowHandles.itemAt(i);
Jeff Browncc4f7db2011-08-30 20:34:48 -07002768 if (windowHandle->getInputChannel() == inputChannel) {
Jeff Brown9302c872011-07-13 22:51:29 -07002769 return windowHandle;
Jeff Brown01ce2e92010-09-26 22:20:12 -07002770 }
2771 }
2772 return NULL;
2773}
2774
Jeff Brown9302c872011-07-13 22:51:29 -07002775bool InputDispatcher::hasWindowHandleLocked(
2776 const sp<InputWindowHandle>& windowHandle) const {
2777 size_t numWindows = mWindowHandles.size();
2778 for (size_t i = 0; i < numWindows; i++) {
2779 if (mWindowHandles.itemAt(i) == windowHandle) {
2780 return true;
2781 }
2782 }
2783 return false;
2784}
2785
2786void InputDispatcher::setInputWindows(const Vector<sp<InputWindowHandle> >& inputWindowHandles) {
Jeff Brownb88102f2010-09-08 11:49:43 -07002787#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002788 ALOGD("setInputWindows");
Jeff Brownb88102f2010-09-08 11:49:43 -07002789#endif
2790 { // acquire lock
2791 AutoMutex _l(mLock);
2792
Jeff Browncc4f7db2011-08-30 20:34:48 -07002793 Vector<sp<InputWindowHandle> > oldWindowHandles = mWindowHandles;
Jeff Brown9302c872011-07-13 22:51:29 -07002794 mWindowHandles = inputWindowHandles;
Jeff Brownb6997262010-10-08 22:31:17 -07002795
Jeff Brown9302c872011-07-13 22:51:29 -07002796 sp<InputWindowHandle> newFocusedWindowHandle;
2797 bool foundHoveredWindow = false;
2798 for (size_t i = 0; i < mWindowHandles.size(); i++) {
2799 const sp<InputWindowHandle>& windowHandle = mWindowHandles.itemAt(i);
Jeff Browncc4f7db2011-08-30 20:34:48 -07002800 if (!windowHandle->updateInfo() || windowHandle->getInputChannel() == NULL) {
Jeff Brown9302c872011-07-13 22:51:29 -07002801 mWindowHandles.removeAt(i--);
2802 continue;
2803 }
Jeff Browncc4f7db2011-08-30 20:34:48 -07002804 if (windowHandle->getInfo()->hasFocus) {
Jeff Brown9302c872011-07-13 22:51:29 -07002805 newFocusedWindowHandle = windowHandle;
2806 }
2807 if (windowHandle == mLastHoverWindowHandle) {
2808 foundHoveredWindow = true;
Jeff Brownb88102f2010-09-08 11:49:43 -07002809 }
2810 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07002811
Jeff Brown9302c872011-07-13 22:51:29 -07002812 if (!foundHoveredWindow) {
2813 mLastHoverWindowHandle = NULL;
2814 }
2815
2816 if (mFocusedWindowHandle != newFocusedWindowHandle) {
2817 if (mFocusedWindowHandle != NULL) {
Jeff Brownb6997262010-10-08 22:31:17 -07002818#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002819 ALOGD("Focus left window: %s",
Jeff Browncc4f7db2011-08-30 20:34:48 -07002820 mFocusedWindowHandle->getName().string());
Jeff Brownb6997262010-10-08 22:31:17 -07002821#endif
Jeff Browncc4f7db2011-08-30 20:34:48 -07002822 sp<InputChannel> focusedInputChannel = mFocusedWindowHandle->getInputChannel();
2823 if (focusedInputChannel != NULL) {
Christopher Tated9be36c2011-08-16 16:09:33 -07002824 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
2825 "focus left window");
2826 synthesizeCancelationEventsForInputChannelLocked(
Jeff Browncc4f7db2011-08-30 20:34:48 -07002827 focusedInputChannel, options);
Christopher Tated9be36c2011-08-16 16:09:33 -07002828 }
Jeff Brownb6997262010-10-08 22:31:17 -07002829 }
Jeff Brown9302c872011-07-13 22:51:29 -07002830 if (newFocusedWindowHandle != NULL) {
Jeff Brownb6997262010-10-08 22:31:17 -07002831#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002832 ALOGD("Focus entered window: %s",
Jeff Browncc4f7db2011-08-30 20:34:48 -07002833 newFocusedWindowHandle->getName().string());
Jeff Brownb6997262010-10-08 22:31:17 -07002834#endif
Jeff Brown9302c872011-07-13 22:51:29 -07002835 }
2836 mFocusedWindowHandle = newFocusedWindowHandle;
Jeff Brownb6997262010-10-08 22:31:17 -07002837 }
2838
Jeff Brown9302c872011-07-13 22:51:29 -07002839 for (size_t i = 0; i < mTouchState.windows.size(); i++) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002840 TouchedWindow& touchedWindow = mTouchState.windows.editItemAt(i);
Jeff Brown9302c872011-07-13 22:51:29 -07002841 if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
Jeff Brownb6997262010-10-08 22:31:17 -07002842#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002843 ALOGD("Touched window was removed: %s",
Jeff Browncc4f7db2011-08-30 20:34:48 -07002844 touchedWindow.windowHandle->getName().string());
Jeff Brownb6997262010-10-08 22:31:17 -07002845#endif
Jeff Browncc4f7db2011-08-30 20:34:48 -07002846 sp<InputChannel> touchedInputChannel =
2847 touchedWindow.windowHandle->getInputChannel();
2848 if (touchedInputChannel != NULL) {
Christopher Tated9be36c2011-08-16 16:09:33 -07002849 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
2850 "touched window was removed");
2851 synthesizeCancelationEventsForInputChannelLocked(
Jeff Browncc4f7db2011-08-30 20:34:48 -07002852 touchedInputChannel, options);
Christopher Tated9be36c2011-08-16 16:09:33 -07002853 }
Jeff Brown9302c872011-07-13 22:51:29 -07002854 mTouchState.windows.removeAt(i--);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002855 }
2856 }
Jeff Browncc4f7db2011-08-30 20:34:48 -07002857
2858 // Release information for windows that are no longer present.
2859 // This ensures that unused input channels are released promptly.
2860 // Otherwise, they might stick around until the window handle is destroyed
2861 // which might not happen until the next GC.
2862 for (size_t i = 0; i < oldWindowHandles.size(); i++) {
2863 const sp<InputWindowHandle>& oldWindowHandle = oldWindowHandles.itemAt(i);
2864 if (!hasWindowHandleLocked(oldWindowHandle)) {
2865#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002866 ALOGD("Window went away: %s", oldWindowHandle->getName().string());
Jeff Browncc4f7db2011-08-30 20:34:48 -07002867#endif
2868 oldWindowHandle->releaseInfo();
2869 }
2870 }
Jeff Brownb88102f2010-09-08 11:49:43 -07002871 } // release lock
2872
2873 // Wake up poll loop since it may need to make new input dispatching choices.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002874 mLooper->wake();
Jeff Brownb88102f2010-09-08 11:49:43 -07002875}
2876
Jeff Brown9302c872011-07-13 22:51:29 -07002877void InputDispatcher::setFocusedApplication(
2878 const sp<InputApplicationHandle>& inputApplicationHandle) {
Jeff Brownb88102f2010-09-08 11:49:43 -07002879#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002880 ALOGD("setFocusedApplication");
Jeff Brownb88102f2010-09-08 11:49:43 -07002881#endif
2882 { // acquire lock
2883 AutoMutex _l(mLock);
2884
Jeff Browncc4f7db2011-08-30 20:34:48 -07002885 if (inputApplicationHandle != NULL && inputApplicationHandle->updateInfo()) {
Jeff Brown5ea29ab2011-07-27 11:50:51 -07002886 if (mFocusedApplicationHandle != inputApplicationHandle) {
2887 if (mFocusedApplicationHandle != NULL) {
Jeff Browne9bb9be2012-02-06 15:47:55 -08002888 resetANRTimeoutsLocked();
Jeff Browncc4f7db2011-08-30 20:34:48 -07002889 mFocusedApplicationHandle->releaseInfo();
Jeff Brown5ea29ab2011-07-27 11:50:51 -07002890 }
2891 mFocusedApplicationHandle = inputApplicationHandle;
2892 }
2893 } else if (mFocusedApplicationHandle != NULL) {
Jeff Browne9bb9be2012-02-06 15:47:55 -08002894 resetANRTimeoutsLocked();
Jeff Browncc4f7db2011-08-30 20:34:48 -07002895 mFocusedApplicationHandle->releaseInfo();
Jeff Brown9302c872011-07-13 22:51:29 -07002896 mFocusedApplicationHandle.clear();
Jeff Brownb88102f2010-09-08 11:49:43 -07002897 }
2898
2899#if DEBUG_FOCUS
Jeff Brownb6997262010-10-08 22:31:17 -07002900 //logDispatchStateLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -07002901#endif
2902 } // release lock
2903
2904 // Wake up poll loop since it may need to make new input dispatching choices.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002905 mLooper->wake();
Jeff Brownb88102f2010-09-08 11:49:43 -07002906}
2907
Jeff Brownb88102f2010-09-08 11:49:43 -07002908void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
2909#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002910 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
Jeff Brownb88102f2010-09-08 11:49:43 -07002911#endif
2912
2913 bool changed;
2914 { // acquire lock
2915 AutoMutex _l(mLock);
2916
2917 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
Jeff Brown120a4592010-10-27 18:43:51 -07002918 if (mDispatchFrozen && !frozen) {
Jeff Brownb88102f2010-09-08 11:49:43 -07002919 resetANRTimeoutsLocked();
2920 }
2921
Jeff Brown120a4592010-10-27 18:43:51 -07002922 if (mDispatchEnabled && !enabled) {
2923 resetAndDropEverythingLocked("dispatcher is being disabled");
2924 }
2925
Jeff Brownb88102f2010-09-08 11:49:43 -07002926 mDispatchEnabled = enabled;
2927 mDispatchFrozen = frozen;
2928 changed = true;
2929 } else {
2930 changed = false;
2931 }
2932
2933#if DEBUG_FOCUS
Jeff Brownb6997262010-10-08 22:31:17 -07002934 //logDispatchStateLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -07002935#endif
2936 } // release lock
2937
2938 if (changed) {
2939 // Wake up poll loop since it may need to make new input dispatching choices.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002940 mLooper->wake();
Jeff Brown46b9ac02010-04-22 18:58:52 -07002941 }
2942}
2943
Jeff Brown0029c662011-03-30 02:25:18 -07002944void InputDispatcher::setInputFilterEnabled(bool enabled) {
2945#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002946 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
Jeff Brown0029c662011-03-30 02:25:18 -07002947#endif
2948
2949 { // acquire lock
2950 AutoMutex _l(mLock);
2951
2952 if (mInputFilterEnabled == enabled) {
2953 return;
2954 }
2955
2956 mInputFilterEnabled = enabled;
2957 resetAndDropEverythingLocked("input filter is being enabled or disabled");
2958 } // release lock
2959
2960 // Wake up poll loop since there might be work to do to drop everything.
2961 mLooper->wake();
2962}
2963
Jeff Browne6504122010-09-27 14:52:15 -07002964bool InputDispatcher::transferTouchFocus(const sp<InputChannel>& fromChannel,
2965 const sp<InputChannel>& toChannel) {
2966#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002967 ALOGD("transferTouchFocus: fromChannel=%s, toChannel=%s",
Jeff Browne6504122010-09-27 14:52:15 -07002968 fromChannel->getName().string(), toChannel->getName().string());
2969#endif
2970 { // acquire lock
2971 AutoMutex _l(mLock);
2972
Jeff Brown9302c872011-07-13 22:51:29 -07002973 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromChannel);
2974 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toChannel);
2975 if (fromWindowHandle == NULL || toWindowHandle == NULL) {
Jeff Browne6504122010-09-27 14:52:15 -07002976#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002977 ALOGD("Cannot transfer focus because from or to window not found.");
Jeff Browne6504122010-09-27 14:52:15 -07002978#endif
2979 return false;
2980 }
Jeff Brown9302c872011-07-13 22:51:29 -07002981 if (fromWindowHandle == toWindowHandle) {
Jeff Browne6504122010-09-27 14:52:15 -07002982#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002983 ALOGD("Trivial transfer to same window.");
Jeff Browne6504122010-09-27 14:52:15 -07002984#endif
2985 return true;
2986 }
Jeff Brown83d616a2012-09-09 20:33:43 -07002987 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
2988#if DEBUG_FOCUS
2989 ALOGD("Cannot transfer focus because windows are on different displays.");
2990#endif
2991 return false;
2992 }
Jeff Browne6504122010-09-27 14:52:15 -07002993
2994 bool found = false;
2995 for (size_t i = 0; i < mTouchState.windows.size(); i++) {
2996 const TouchedWindow& touchedWindow = mTouchState.windows[i];
Jeff Brown9302c872011-07-13 22:51:29 -07002997 if (touchedWindow.windowHandle == fromWindowHandle) {
Jeff Browne6504122010-09-27 14:52:15 -07002998 int32_t oldTargetFlags = touchedWindow.targetFlags;
2999 BitSet32 pointerIds = touchedWindow.pointerIds;
3000
3001 mTouchState.windows.removeAt(i);
3002
Jeff Brown46e75292010-11-10 16:53:45 -08003003 int32_t newTargetFlags = oldTargetFlags
Jeff Browna032cc02011-03-07 16:56:21 -08003004 & (InputTarget::FLAG_FOREGROUND
3005 | InputTarget::FLAG_SPLIT | InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brown9302c872011-07-13 22:51:29 -07003006 mTouchState.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Jeff Browne6504122010-09-27 14:52:15 -07003007
3008 found = true;
3009 break;
3010 }
3011 }
3012
3013 if (! found) {
3014#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00003015 ALOGD("Focus transfer failed because from window did not have focus.");
Jeff Browne6504122010-09-27 14:52:15 -07003016#endif
3017 return false;
3018 }
3019
Jeff Brown9c9f1a32010-10-11 18:32:20 -07003020 ssize_t fromConnectionIndex = getConnectionIndexLocked(fromChannel);
3021 ssize_t toConnectionIndex = getConnectionIndexLocked(toChannel);
3022 if (fromConnectionIndex >= 0 && toConnectionIndex >= 0) {
Jeff Browncbee6d62012-02-03 20:11:27 -08003023 sp<Connection> fromConnection = mConnectionsByFd.valueAt(fromConnectionIndex);
3024 sp<Connection> toConnection = mConnectionsByFd.valueAt(toConnectionIndex);
Jeff Brown9c9f1a32010-10-11 18:32:20 -07003025
3026 fromConnection->inputState.copyPointerStateTo(toConnection->inputState);
Jeff Brownda3d5a92011-03-29 15:11:34 -07003027 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Jeff Brown9c9f1a32010-10-11 18:32:20 -07003028 "transferring touch focus from this window to another window");
Jeff Brownda3d5a92011-03-29 15:11:34 -07003029 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Jeff Brown9c9f1a32010-10-11 18:32:20 -07003030 }
3031
Jeff Browne6504122010-09-27 14:52:15 -07003032#if DEBUG_FOCUS
3033 logDispatchStateLocked();
3034#endif
3035 } // release lock
3036
3037 // Wake up poll loop since it may need to make new input dispatching choices.
3038 mLooper->wake();
3039 return true;
3040}
3041
Jeff Brown120a4592010-10-27 18:43:51 -07003042void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
3043#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00003044 ALOGD("Resetting and dropping all events (%s).", reason);
Jeff Brown120a4592010-10-27 18:43:51 -07003045#endif
3046
Jeff Brownda3d5a92011-03-29 15:11:34 -07003047 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
3048 synthesizeCancelationEventsForAllConnectionsLocked(options);
Jeff Brown120a4592010-10-27 18:43:51 -07003049
3050 resetKeyRepeatLocked();
3051 releasePendingEventLocked();
3052 drainInboundQueueLocked();
Jeff Browne9bb9be2012-02-06 15:47:55 -08003053 resetANRTimeoutsLocked();
Jeff Brown120a4592010-10-27 18:43:51 -07003054
3055 mTouchState.reset();
Jeff Brown9302c872011-07-13 22:51:29 -07003056 mLastHoverWindowHandle.clear();
Jeff Brown120a4592010-10-27 18:43:51 -07003057}
3058
Jeff Brownb88102f2010-09-08 11:49:43 -07003059void InputDispatcher::logDispatchStateLocked() {
3060 String8 dump;
3061 dumpDispatchStateLocked(dump);
Jeff Brown2a95c2a2010-09-16 12:31:46 -07003062
3063 char* text = dump.lockBuffer(dump.size());
3064 char* start = text;
3065 while (*start != '\0') {
3066 char* end = strchr(start, '\n');
3067 if (*end == '\n') {
3068 *(end++) = '\0';
3069 }
Steve Block5baa3a62011-12-20 16:23:08 +00003070 ALOGD("%s", start);
Jeff Brown2a95c2a2010-09-16 12:31:46 -07003071 start = end;
3072 }
Jeff Brownb88102f2010-09-08 11:49:43 -07003073}
3074
3075void InputDispatcher::dumpDispatchStateLocked(String8& dump) {
Jeff Brownf2f487182010-10-01 17:46:21 -07003076 dump.appendFormat(INDENT "DispatchEnabled: %d\n", mDispatchEnabled);
3077 dump.appendFormat(INDENT "DispatchFrozen: %d\n", mDispatchFrozen);
Jeff Brownb88102f2010-09-08 11:49:43 -07003078
Jeff Brown9302c872011-07-13 22:51:29 -07003079 if (mFocusedApplicationHandle != NULL) {
Jeff Brownf2f487182010-10-01 17:46:21 -07003080 dump.appendFormat(INDENT "FocusedApplication: name='%s', dispatchingTimeout=%0.3fms\n",
Jeff Browncc4f7db2011-08-30 20:34:48 -07003081 mFocusedApplicationHandle->getName().string(),
3082 mFocusedApplicationHandle->getDispatchingTimeout(
3083 DEFAULT_INPUT_DISPATCHING_TIMEOUT) / 1000000.0);
Jeff Brownb88102f2010-09-08 11:49:43 -07003084 } else {
Jeff Brownf2f487182010-10-01 17:46:21 -07003085 dump.append(INDENT "FocusedApplication: <null>\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003086 }
Jeff Brownf2f487182010-10-01 17:46:21 -07003087 dump.appendFormat(INDENT "FocusedWindow: name='%s'\n",
Jeff Browncc4f7db2011-08-30 20:34:48 -07003088 mFocusedWindowHandle != NULL ? mFocusedWindowHandle->getName().string() : "<null>");
Jeff Brownf2f487182010-10-01 17:46:21 -07003089
3090 dump.appendFormat(INDENT "TouchDown: %s\n", toString(mTouchState.down));
3091 dump.appendFormat(INDENT "TouchSplit: %s\n", toString(mTouchState.split));
Jeff Brown95712852011-01-04 19:41:59 -08003092 dump.appendFormat(INDENT "TouchDeviceId: %d\n", mTouchState.deviceId);
Jeff Brown58a2da82011-01-25 16:02:22 -08003093 dump.appendFormat(INDENT "TouchSource: 0x%08x\n", mTouchState.source);
Jeff Brown83d616a2012-09-09 20:33:43 -07003094 dump.appendFormat(INDENT "TouchDisplayId: %d\n", mTouchState.displayId);
Jeff Brownf2f487182010-10-01 17:46:21 -07003095 if (!mTouchState.windows.isEmpty()) {
3096 dump.append(INDENT "TouchedWindows:\n");
3097 for (size_t i = 0; i < mTouchState.windows.size(); i++) {
3098 const TouchedWindow& touchedWindow = mTouchState.windows[i];
3099 dump.appendFormat(INDENT2 "%d: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
Jeff Browncc4f7db2011-08-30 20:34:48 -07003100 i, touchedWindow.windowHandle->getName().string(),
3101 touchedWindow.pointerIds.value,
Jeff Brownf2f487182010-10-01 17:46:21 -07003102 touchedWindow.targetFlags);
3103 }
3104 } else {
3105 dump.append(INDENT "TouchedWindows: <none>\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003106 }
3107
Jeff Brown9302c872011-07-13 22:51:29 -07003108 if (!mWindowHandles.isEmpty()) {
Jeff Brownf2f487182010-10-01 17:46:21 -07003109 dump.append(INDENT "Windows:\n");
Jeff Brown9302c872011-07-13 22:51:29 -07003110 for (size_t i = 0; i < mWindowHandles.size(); i++) {
3111 const sp<InputWindowHandle>& windowHandle = mWindowHandles.itemAt(i);
Jeff Browncc4f7db2011-08-30 20:34:48 -07003112 const InputWindowInfo* windowInfo = windowHandle->getInfo();
3113
Jeff Brown83d616a2012-09-09 20:33:43 -07003114 dump.appendFormat(INDENT2 "%d: name='%s', displayId=%d, "
3115 "paused=%s, hasFocus=%s, hasWallpaper=%s, "
Jeff Brownf2f487182010-10-01 17:46:21 -07003116 "visible=%s, canReceiveKeys=%s, flags=0x%08x, type=0x%08x, layer=%d, "
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003117 "frame=[%d,%d][%d,%d], scale=%f, "
Jeff Brownfbf09772011-01-16 14:06:57 -08003118 "touchableRegion=",
Jeff Brown83d616a2012-09-09 20:33:43 -07003119 i, windowInfo->name.string(), windowInfo->displayId,
Jeff Browncc4f7db2011-08-30 20:34:48 -07003120 toString(windowInfo->paused),
3121 toString(windowInfo->hasFocus),
3122 toString(windowInfo->hasWallpaper),
3123 toString(windowInfo->visible),
3124 toString(windowInfo->canReceiveKeys),
3125 windowInfo->layoutParamsFlags, windowInfo->layoutParamsType,
3126 windowInfo->layer,
3127 windowInfo->frameLeft, windowInfo->frameTop,
3128 windowInfo->frameRight, windowInfo->frameBottom,
3129 windowInfo->scaleFactor);
3130 dumpRegion(dump, windowInfo->touchableRegion);
3131 dump.appendFormat(", inputFeatures=0x%08x", windowInfo->inputFeatures);
Jeff Brownfbf09772011-01-16 14:06:57 -08003132 dump.appendFormat(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%0.3fms\n",
Jeff Browncc4f7db2011-08-30 20:34:48 -07003133 windowInfo->ownerPid, windowInfo->ownerUid,
3134 windowInfo->dispatchingTimeout / 1000000.0);
Jeff Brownf2f487182010-10-01 17:46:21 -07003135 }
3136 } else {
3137 dump.append(INDENT "Windows: <none>\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003138 }
3139
Jeff Brownf2f487182010-10-01 17:46:21 -07003140 if (!mMonitoringChannels.isEmpty()) {
3141 dump.append(INDENT "MonitoringChannels:\n");
3142 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
3143 const sp<InputChannel>& channel = mMonitoringChannels[i];
3144 dump.appendFormat(INDENT2 "%d: '%s'\n", i, channel->getName().string());
3145 }
3146 } else {
3147 dump.append(INDENT "MonitoringChannels: <none>\n");
3148 }
Jeff Brown519e0242010-09-15 15:18:56 -07003149
Jeff Brown265f1cc2012-06-11 18:01:06 -07003150 nsecs_t currentTime = now();
3151
3152 if (!mInboundQueue.isEmpty()) {
3153 dump.appendFormat(INDENT "InboundQueue: length=%u\n", mInboundQueue.count());
3154 for (EventEntry* entry = mInboundQueue.head; entry; entry = entry->next) {
3155 dump.append(INDENT2);
3156 entry->appendDescription(dump);
Jeff Brown22aa5122012-06-17 12:01:06 -07003157 dump.appendFormat(", age=%0.1fms\n",
Jeff Brown265f1cc2012-06-11 18:01:06 -07003158 (currentTime - entry->eventTime) * 0.000001f);
3159 }
3160 } else {
3161 dump.append(INDENT "InboundQueue: <empty>\n");
3162 }
3163
3164 if (!mConnectionsByFd.isEmpty()) {
3165 dump.append(INDENT "Connections:\n");
3166 for (size_t i = 0; i < mConnectionsByFd.size(); i++) {
3167 const sp<Connection>& connection = mConnectionsByFd.valueAt(i);
3168 dump.appendFormat(INDENT2 "%d: channelName='%s', windowName='%s', "
3169 "status=%s, monitor=%s, inputPublisherBlocked=%s\n",
3170 i, connection->getInputChannelName(), connection->getWindowName(),
3171 connection->getStatusLabel(), toString(connection->monitor),
3172 toString(connection->inputPublisherBlocked));
3173
3174 if (!connection->outboundQueue.isEmpty()) {
3175 dump.appendFormat(INDENT3 "OutboundQueue: length=%u\n",
3176 connection->outboundQueue.count());
3177 for (DispatchEntry* entry = connection->outboundQueue.head; entry;
3178 entry = entry->next) {
3179 dump.append(INDENT4);
3180 entry->eventEntry->appendDescription(dump);
Jeff Brown22aa5122012-06-17 12:01:06 -07003181 dump.appendFormat(", targetFlags=0x%08x, resolvedAction=%d, age=%0.1fms\n",
Jeff Brown265f1cc2012-06-11 18:01:06 -07003182 entry->targetFlags, entry->resolvedAction,
3183 (currentTime - entry->eventEntry->eventTime) * 0.000001f);
3184 }
3185 } else {
3186 dump.append(INDENT3 "OutboundQueue: <empty>\n");
3187 }
3188
3189 if (!connection->waitQueue.isEmpty()) {
3190 dump.appendFormat(INDENT3 "WaitQueue: length=%u\n",
3191 connection->waitQueue.count());
3192 for (DispatchEntry* entry = connection->waitQueue.head; entry;
3193 entry = entry->next) {
3194 dump.append(INDENT4);
3195 entry->eventEntry->appendDescription(dump);
3196 dump.appendFormat(", targetFlags=0x%08x, resolvedAction=%d, "
Jeff Brown22aa5122012-06-17 12:01:06 -07003197 "age=%0.1fms, wait=%0.1fms\n",
Jeff Brown265f1cc2012-06-11 18:01:06 -07003198 entry->targetFlags, entry->resolvedAction,
3199 (currentTime - entry->eventEntry->eventTime) * 0.000001f,
3200 (currentTime - entry->deliveryTime) * 0.000001f);
3201 }
3202 } else {
3203 dump.append(INDENT3 "WaitQueue: <empty>\n");
3204 }
3205 }
3206 } else {
3207 dump.append(INDENT "Connections: <none>\n");
3208 }
Jeff Brownf2f487182010-10-01 17:46:21 -07003209
Jeff Brownb88102f2010-09-08 11:49:43 -07003210 if (isAppSwitchPendingLocked()) {
Jeff Brown22aa5122012-06-17 12:01:06 -07003211 dump.appendFormat(INDENT "AppSwitch: pending, due in %0.1fms\n",
Jeff Brownb88102f2010-09-08 11:49:43 -07003212 (mAppSwitchDueTime - now()) / 1000000.0);
3213 } else {
Jeff Brownf2f487182010-10-01 17:46:21 -07003214 dump.append(INDENT "AppSwitch: not pending\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003215 }
Jeff Brown22aa5122012-06-17 12:01:06 -07003216
3217 dump.append(INDENT "Configuration:\n");
3218 dump.appendFormat(INDENT2 "KeyRepeatDelay: %0.1fms\n",
3219 mConfig.keyRepeatDelay * 0.000001f);
3220 dump.appendFormat(INDENT2 "KeyRepeatTimeout: %0.1fms\n",
3221 mConfig.keyRepeatTimeout * 0.000001f);
Jeff Brownb88102f2010-09-08 11:49:43 -07003222}
3223
Jeff Brown928e0542011-01-10 11:17:36 -08003224status_t InputDispatcher::registerInputChannel(const sp<InputChannel>& inputChannel,
3225 const sp<InputWindowHandle>& inputWindowHandle, bool monitor) {
Jeff Brown9c3cda02010-06-15 01:31:58 -07003226#if DEBUG_REGISTRATION
Steve Block5baa3a62011-12-20 16:23:08 +00003227 ALOGD("channel '%s' ~ registerInputChannel - monitor=%s", inputChannel->getName().string(),
Jeff Brownb88102f2010-09-08 11:49:43 -07003228 toString(monitor));
Jeff Brown9c3cda02010-06-15 01:31:58 -07003229#endif
3230
Jeff Brown46b9ac02010-04-22 18:58:52 -07003231 { // acquire lock
3232 AutoMutex _l(mLock);
3233
Jeff Brown519e0242010-09-15 15:18:56 -07003234 if (getConnectionIndexLocked(inputChannel) >= 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00003235 ALOGW("Attempted to register already registered input channel '%s'",
Jeff Brown46b9ac02010-04-22 18:58:52 -07003236 inputChannel->getName().string());
3237 return BAD_VALUE;
3238 }
3239
Jeff Browncc4f7db2011-08-30 20:34:48 -07003240 sp<Connection> connection = new Connection(inputChannel, inputWindowHandle, monitor);
Jeff Brown46b9ac02010-04-22 18:58:52 -07003241
Jeff Brown91e32892012-02-14 15:56:29 -08003242 int fd = inputChannel->getFd();
Jeff Browncbee6d62012-02-03 20:11:27 -08003243 mConnectionsByFd.add(fd, connection);
Jeff Brown9c3cda02010-06-15 01:31:58 -07003244
Jeff Brownb88102f2010-09-08 11:49:43 -07003245 if (monitor) {
3246 mMonitoringChannels.push(inputChannel);
3247 }
3248
Jeff Browncbee6d62012-02-03 20:11:27 -08003249 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
Jeff Brown2cbecea2010-08-17 15:59:26 -07003250
Jeff Brown9c3cda02010-06-15 01:31:58 -07003251 runCommandsLockedInterruptible();
Jeff Brown46b9ac02010-04-22 18:58:52 -07003252 } // release lock
Jeff Brown46b9ac02010-04-22 18:58:52 -07003253 return OK;
3254}
3255
3256status_t InputDispatcher::unregisterInputChannel(const sp<InputChannel>& inputChannel) {
Jeff Brown9c3cda02010-06-15 01:31:58 -07003257#if DEBUG_REGISTRATION
Steve Block5baa3a62011-12-20 16:23:08 +00003258 ALOGD("channel '%s' ~ unregisterInputChannel", inputChannel->getName().string());
Jeff Brown9c3cda02010-06-15 01:31:58 -07003259#endif
3260
Jeff Brown46b9ac02010-04-22 18:58:52 -07003261 { // acquire lock
3262 AutoMutex _l(mLock);
3263
Jeff Browncc4f7db2011-08-30 20:34:48 -07003264 status_t status = unregisterInputChannelLocked(inputChannel, false /*notify*/);
3265 if (status) {
3266 return status;
Jeff Brown46b9ac02010-04-22 18:58:52 -07003267 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07003268 } // release lock
3269
Jeff Brown46b9ac02010-04-22 18:58:52 -07003270 // Wake the poll loop because removing the connection may have changed the current
3271 // synchronization state.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07003272 mLooper->wake();
Jeff Brown46b9ac02010-04-22 18:58:52 -07003273 return OK;
3274}
3275
Jeff Browncc4f7db2011-08-30 20:34:48 -07003276status_t InputDispatcher::unregisterInputChannelLocked(const sp<InputChannel>& inputChannel,
3277 bool notify) {
3278 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
3279 if (connectionIndex < 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00003280 ALOGW("Attempted to unregister already unregistered input channel '%s'",
Jeff Browncc4f7db2011-08-30 20:34:48 -07003281 inputChannel->getName().string());
3282 return BAD_VALUE;
3283 }
3284
Jeff Browncbee6d62012-02-03 20:11:27 -08003285 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
3286 mConnectionsByFd.removeItemsAt(connectionIndex);
Jeff Browncc4f7db2011-08-30 20:34:48 -07003287
3288 if (connection->monitor) {
3289 removeMonitorChannelLocked(inputChannel);
3290 }
3291
Jeff Browncbee6d62012-02-03 20:11:27 -08003292 mLooper->removeFd(inputChannel->getFd());
Jeff Browncc4f7db2011-08-30 20:34:48 -07003293
3294 nsecs_t currentTime = now();
3295 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
3296
3297 runCommandsLockedInterruptible();
3298
3299 connection->status = Connection::STATUS_ZOMBIE;
3300 return OK;
3301}
3302
3303void InputDispatcher::removeMonitorChannelLocked(const sp<InputChannel>& inputChannel) {
3304 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
3305 if (mMonitoringChannels[i] == inputChannel) {
3306 mMonitoringChannels.removeAt(i);
3307 break;
3308 }
3309 }
3310}
3311
Jeff Brown519e0242010-09-15 15:18:56 -07003312ssize_t InputDispatcher::getConnectionIndexLocked(const sp<InputChannel>& inputChannel) {
Jeff Browncbee6d62012-02-03 20:11:27 -08003313 ssize_t connectionIndex = mConnectionsByFd.indexOfKey(inputChannel->getFd());
Jeff Brown2cbecea2010-08-17 15:59:26 -07003314 if (connectionIndex >= 0) {
Jeff Browncbee6d62012-02-03 20:11:27 -08003315 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
Jeff Brown2cbecea2010-08-17 15:59:26 -07003316 if (connection->inputChannel.get() == inputChannel.get()) {
3317 return connectionIndex;
3318 }
3319 }
3320
3321 return -1;
3322}
3323
Jeff Brown9c3cda02010-06-15 01:31:58 -07003324void InputDispatcher::onDispatchCycleFinishedLocked(
Jeff Brown072ec962012-02-07 14:46:57 -08003325 nsecs_t currentTime, const sp<Connection>& connection, uint32_t seq, bool handled) {
Jeff Brown3915bb82010-11-05 15:02:16 -07003326 CommandEntry* commandEntry = postCommandLocked(
3327 & InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
3328 commandEntry->connection = connection;
Jeff Brown265f1cc2012-06-11 18:01:06 -07003329 commandEntry->eventTime = currentTime;
Jeff Brown072ec962012-02-07 14:46:57 -08003330 commandEntry->seq = seq;
Jeff Brown3915bb82010-11-05 15:02:16 -07003331 commandEntry->handled = handled;
Jeff Brown46b9ac02010-04-22 18:58:52 -07003332}
3333
Jeff Brown9c3cda02010-06-15 01:31:58 -07003334void InputDispatcher::onDispatchCycleBrokenLocked(
Jeff Brown7fbdc842010-06-17 20:52:56 -07003335 nsecs_t currentTime, const sp<Connection>& connection) {
Steve Block3762c312012-01-06 19:20:56 +00003336 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Jeff Brown46b9ac02010-04-22 18:58:52 -07003337 connection->getInputChannelName());
3338
Jeff Brown9c3cda02010-06-15 01:31:58 -07003339 CommandEntry* commandEntry = postCommandLocked(
3340 & InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
Jeff Brown7fbdc842010-06-17 20:52:56 -07003341 commandEntry->connection = connection;
Jeff Brown46b9ac02010-04-22 18:58:52 -07003342}
3343
Jeff Brown519e0242010-09-15 15:18:56 -07003344void InputDispatcher::onANRLocked(
Jeff Brown9302c872011-07-13 22:51:29 -07003345 nsecs_t currentTime, const sp<InputApplicationHandle>& applicationHandle,
3346 const sp<InputWindowHandle>& windowHandle,
Jeff Brown265f1cc2012-06-11 18:01:06 -07003347 nsecs_t eventTime, nsecs_t waitStartTime, const char* reason) {
Jeff Brown22aa5122012-06-17 12:01:06 -07003348 float dispatchLatency = (currentTime - eventTime) * 0.000001f;
3349 float waitDuration = (currentTime - waitStartTime) * 0.000001f;
Steve Block6215d3f2012-01-04 20:05:49 +00003350 ALOGI("Application is not responding: %s. "
Jeff Brown22aa5122012-06-17 12:01:06 -07003351 "It has been %0.1fms since event, %0.1fms since wait started. Reason: %s",
Jeff Brown9302c872011-07-13 22:51:29 -07003352 getApplicationWindowLabelLocked(applicationHandle, windowHandle).string(),
Jeff Brown22aa5122012-06-17 12:01:06 -07003353 dispatchLatency, waitDuration, reason);
3354
3355 // Capture a record of the InputDispatcher state at the time of the ANR.
3356 time_t t = time(NULL);
3357 struct tm tm;
3358 localtime_r(&t, &tm);
3359 char timestr[64];
3360 strftime(timestr, sizeof(timestr), "%F %T", &tm);
3361 mLastANRState.clear();
3362 mLastANRState.append(INDENT "ANR:\n");
3363 mLastANRState.appendFormat(INDENT2 "Time: %s\n", timestr);
3364 mLastANRState.appendFormat(INDENT2 "Window: %s\n",
3365 getApplicationWindowLabelLocked(applicationHandle, windowHandle).string());
3366 mLastANRState.appendFormat(INDENT2 "DispatchLatency: %0.1fms\n", dispatchLatency);
3367 mLastANRState.appendFormat(INDENT2 "WaitDuration: %0.1fms\n", waitDuration);
3368 mLastANRState.appendFormat(INDENT2 "Reason: %s\n", reason);
3369 dumpDispatchStateLocked(mLastANRState);
Jeff Brown519e0242010-09-15 15:18:56 -07003370
3371 CommandEntry* commandEntry = postCommandLocked(
3372 & InputDispatcher::doNotifyANRLockedInterruptible);
Jeff Brown9302c872011-07-13 22:51:29 -07003373 commandEntry->inputApplicationHandle = applicationHandle;
3374 commandEntry->inputWindowHandle = windowHandle;
Jeff Brown519e0242010-09-15 15:18:56 -07003375}
3376
Jeff Brownb88102f2010-09-08 11:49:43 -07003377void InputDispatcher::doNotifyConfigurationChangedInterruptible(
3378 CommandEntry* commandEntry) {
3379 mLock.unlock();
3380
3381 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
3382
3383 mLock.lock();
3384}
3385
Jeff Brown9c3cda02010-06-15 01:31:58 -07003386void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(
3387 CommandEntry* commandEntry) {
Jeff Brown7fbdc842010-06-17 20:52:56 -07003388 sp<Connection> connection = commandEntry->connection;
Jeff Brown9c3cda02010-06-15 01:31:58 -07003389
Jeff Brown7fbdc842010-06-17 20:52:56 -07003390 if (connection->status != Connection::STATUS_ZOMBIE) {
3391 mLock.unlock();
Jeff Brown9c3cda02010-06-15 01:31:58 -07003392
Jeff Brown928e0542011-01-10 11:17:36 -08003393 mPolicy->notifyInputChannelBroken(connection->inputWindowHandle);
Jeff Brown7fbdc842010-06-17 20:52:56 -07003394
3395 mLock.lock();
3396 }
Jeff Brown9c3cda02010-06-15 01:31:58 -07003397}
3398
Jeff Brown519e0242010-09-15 15:18:56 -07003399void InputDispatcher::doNotifyANRLockedInterruptible(
Jeff Brown9c3cda02010-06-15 01:31:58 -07003400 CommandEntry* commandEntry) {
Jeff Brown519e0242010-09-15 15:18:56 -07003401 mLock.unlock();
Jeff Brown9c3cda02010-06-15 01:31:58 -07003402
Jeff Brown519e0242010-09-15 15:18:56 -07003403 nsecs_t newTimeout = mPolicy->notifyANR(
Jeff Brown928e0542011-01-10 11:17:36 -08003404 commandEntry->inputApplicationHandle, commandEntry->inputWindowHandle);
Jeff Brown9c3cda02010-06-15 01:31:58 -07003405
Jeff Brown519e0242010-09-15 15:18:56 -07003406 mLock.lock();
Jeff Brown7fbdc842010-06-17 20:52:56 -07003407
Jeff Brown9302c872011-07-13 22:51:29 -07003408 resumeAfterTargetsNotReadyTimeoutLocked(newTimeout,
3409 commandEntry->inputWindowHandle != NULL
Jeff Browncc4f7db2011-08-30 20:34:48 -07003410 ? commandEntry->inputWindowHandle->getInputChannel() : NULL);
Jeff Brown9c3cda02010-06-15 01:31:58 -07003411}
3412
Jeff Brownb88102f2010-09-08 11:49:43 -07003413void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
3414 CommandEntry* commandEntry) {
3415 KeyEntry* entry = commandEntry->keyEntry;
Jeff Brown1f245102010-11-18 20:53:46 -08003416
3417 KeyEvent event;
3418 initializeKeyEvent(&event, entry);
Jeff Brownb88102f2010-09-08 11:49:43 -07003419
3420 mLock.unlock();
3421
Jeff Brown905805a2011-10-12 13:57:59 -07003422 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(commandEntry->inputWindowHandle,
Jeff Brown1f245102010-11-18 20:53:46 -08003423 &event, entry->policyFlags);
Jeff Brownb88102f2010-09-08 11:49:43 -07003424
3425 mLock.lock();
3426
Jeff Brown905805a2011-10-12 13:57:59 -07003427 if (delay < 0) {
3428 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
3429 } else if (!delay) {
3430 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
3431 } else {
3432 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
3433 entry->interceptKeyWakeupTime = now() + delay;
3434 }
Jeff Brownac386072011-07-20 15:19:50 -07003435 entry->release();
Jeff Brownb88102f2010-09-08 11:49:43 -07003436}
3437
Jeff Brown3915bb82010-11-05 15:02:16 -07003438void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(
3439 CommandEntry* commandEntry) {
3440 sp<Connection> connection = commandEntry->connection;
Jeff Brown265f1cc2012-06-11 18:01:06 -07003441 nsecs_t finishTime = commandEntry->eventTime;
Jeff Brown072ec962012-02-07 14:46:57 -08003442 uint32_t seq = commandEntry->seq;
Jeff Brown3915bb82010-11-05 15:02:16 -07003443 bool handled = commandEntry->handled;
3444
Jeff Brown072ec962012-02-07 14:46:57 -08003445 // Handle post-event policy actions.
3446 DispatchEntry* dispatchEntry = connection->findWaitQueueEntry(seq);
3447 if (dispatchEntry) {
Jeff Brown265f1cc2012-06-11 18:01:06 -07003448 nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
3449 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
3450 String8 msg;
Jeff Brown22aa5122012-06-17 12:01:06 -07003451 msg.appendFormat("Window '%s' spent %0.1fms processing the last input event: ",
Jeff Brown265f1cc2012-06-11 18:01:06 -07003452 connection->getWindowName(), eventDuration * 0.000001f);
3453 dispatchEntry->eventEntry->appendDescription(msg);
3454 ALOGI("%s", msg.string());
3455 }
3456
Jeff Brownd1c48a02012-02-06 19:12:47 -08003457 bool restartEvent;
Jeff Brownd1c48a02012-02-06 19:12:47 -08003458 if (dispatchEntry->eventEntry->type == EventEntry::TYPE_KEY) {
3459 KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry);
3460 restartEvent = afterKeyEventLockedInterruptible(connection,
3461 dispatchEntry, keyEntry, handled);
3462 } else if (dispatchEntry->eventEntry->type == EventEntry::TYPE_MOTION) {
3463 MotionEntry* motionEntry = static_cast<MotionEntry*>(dispatchEntry->eventEntry);
3464 restartEvent = afterMotionEventLockedInterruptible(connection,
3465 dispatchEntry, motionEntry, handled);
3466 } else {
3467 restartEvent = false;
3468 }
3469
3470 // Dequeue the event and start the next cycle.
3471 // Note that because the lock might have been released, it is possible that the
3472 // contents of the wait queue to have been drained, so we need to double-check
3473 // a few things.
Jeff Brown072ec962012-02-07 14:46:57 -08003474 if (dispatchEntry == connection->findWaitQueueEntry(seq)) {
3475 connection->waitQueue.dequeue(dispatchEntry);
Jeff Brown481c1572012-03-09 14:41:15 -08003476 traceWaitQueueLengthLocked(connection);
Jeff Brownd1c48a02012-02-06 19:12:47 -08003477 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
3478 connection->outboundQueue.enqueueAtHead(dispatchEntry);
Jeff Brown481c1572012-03-09 14:41:15 -08003479 traceOutboundQueueLengthLocked(connection);
Jeff Brownd1c48a02012-02-06 19:12:47 -08003480 } else {
3481 releaseDispatchEntryLocked(dispatchEntry);
Jeff Brown49ed71d2010-12-06 17:13:33 -08003482 }
Jeff Brown3915bb82010-11-05 15:02:16 -07003483 }
Jeff Brown3915bb82010-11-05 15:02:16 -07003484
Jeff Brownd1c48a02012-02-06 19:12:47 -08003485 // Start the next dispatch cycle for this connection.
3486 startDispatchCycleLocked(now(), connection);
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003487 }
3488}
3489
3490bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
3491 DispatchEntry* dispatchEntry, KeyEntry* keyEntry, bool handled) {
3492 if (!(keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK)) {
3493 // Get the fallback key state.
3494 // Clear it out after dispatching the UP.
3495 int32_t originalKeyCode = keyEntry->keyCode;
3496 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
3497 if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
3498 connection->inputState.removeFallbackKey(originalKeyCode);
3499 }
3500
3501 if (handled || !dispatchEntry->hasForegroundTarget()) {
3502 // If the application handles the original key for which we previously
3503 // generated a fallback or if the window is not a foreground window,
3504 // then cancel the associated fallback key, if any.
3505 if (fallbackKeyCode != -1) {
Jeff Brownfd23e3e2012-05-09 13:34:28 -07003506 // Dispatch the unhandled key to the policy with the cancel flag.
3507#if DEBUG_OUTBOUND_EVENT_DETAILS
3508 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
3509 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
3510 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
3511 keyEntry->policyFlags);
3512#endif
3513 KeyEvent event;
3514 initializeKeyEvent(&event, keyEntry);
3515 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
3516
3517 mLock.unlock();
3518
3519 mPolicy->dispatchUnhandledKey(connection->inputWindowHandle,
3520 &event, keyEntry->policyFlags, &event);
3521
3522 mLock.lock();
3523
3524 // Cancel the fallback key.
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003525 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
3526 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
3527 "application handled the original non-fallback key "
3528 "or is no longer a foreground target, "
3529 "canceling previously dispatched fallback key");
3530 options.keyCode = fallbackKeyCode;
3531 synthesizeCancelationEventsForConnectionLocked(connection, options);
3532 }
3533 connection->inputState.removeFallbackKey(originalKeyCode);
3534 }
3535 } else {
3536 // If the application did not handle a non-fallback key, first check
3537 // that we are in a good state to perform unhandled key event processing
3538 // Then ask the policy what to do with it.
3539 bool initialDown = keyEntry->action == AKEY_EVENT_ACTION_DOWN
3540 && keyEntry->repeatCount == 0;
3541 if (fallbackKeyCode == -1 && !initialDown) {
3542#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00003543 ALOGD("Unhandled key event: Skipping unhandled key event processing "
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003544 "since this is not an initial down. "
Jeff Brownfd23e3e2012-05-09 13:34:28 -07003545 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
3546 originalKeyCode, keyEntry->action, keyEntry->repeatCount,
3547 keyEntry->policyFlags);
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003548#endif
3549 return false;
3550 }
3551
3552 // Dispatch the unhandled key to the policy.
3553#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00003554 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
Jeff Brownfd23e3e2012-05-09 13:34:28 -07003555 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
3556 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
3557 keyEntry->policyFlags);
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003558#endif
3559 KeyEvent event;
3560 initializeKeyEvent(&event, keyEntry);
3561
3562 mLock.unlock();
3563
3564 bool fallback = mPolicy->dispatchUnhandledKey(connection->inputWindowHandle,
3565 &event, keyEntry->policyFlags, &event);
3566
3567 mLock.lock();
3568
3569 if (connection->status != Connection::STATUS_NORMAL) {
3570 connection->inputState.removeFallbackKey(originalKeyCode);
Jeff Brownd1c48a02012-02-06 19:12:47 -08003571 return false;
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003572 }
3573
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003574 // Latch the fallback keycode for this key on an initial down.
3575 // The fallback keycode cannot change at any other point in the lifecycle.
3576 if (initialDown) {
3577 if (fallback) {
3578 fallbackKeyCode = event.getKeyCode();
3579 } else {
3580 fallbackKeyCode = AKEYCODE_UNKNOWN;
3581 }
3582 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
3583 }
3584
Steve Blockec193de2012-01-09 18:35:44 +00003585 ALOG_ASSERT(fallbackKeyCode != -1);
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003586
3587 // Cancel the fallback key if the policy decides not to send it anymore.
3588 // We will continue to dispatch the key to the policy but we will no
3589 // longer dispatch a fallback key to the application.
3590 if (fallbackKeyCode != AKEYCODE_UNKNOWN
3591 && (!fallback || fallbackKeyCode != event.getKeyCode())) {
3592#if DEBUG_OUTBOUND_EVENT_DETAILS
3593 if (fallback) {
Steve Block5baa3a62011-12-20 16:23:08 +00003594 ALOGD("Unhandled key event: Policy requested to send key %d"
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003595 "as a fallback for %d, but on the DOWN it had requested "
3596 "to send %d instead. Fallback canceled.",
3597 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
3598 } else {
Jeff Brownfd23e3e2012-05-09 13:34:28 -07003599 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003600 "but on the DOWN it had requested to send %d. "
3601 "Fallback canceled.",
3602 originalKeyCode, fallbackKeyCode);
3603 }
3604#endif
3605
3606 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
3607 "canceling fallback, policy no longer desires it");
3608 options.keyCode = fallbackKeyCode;
3609 synthesizeCancelationEventsForConnectionLocked(connection, options);
3610
3611 fallback = false;
3612 fallbackKeyCode = AKEYCODE_UNKNOWN;
3613 if (keyEntry->action != AKEY_EVENT_ACTION_UP) {
3614 connection->inputState.setFallbackKey(originalKeyCode,
3615 fallbackKeyCode);
3616 }
3617 }
3618
3619#if DEBUG_OUTBOUND_EVENT_DETAILS
3620 {
3621 String8 msg;
3622 const KeyedVector<int32_t, int32_t>& fallbackKeys =
3623 connection->inputState.getFallbackKeys();
3624 for (size_t i = 0; i < fallbackKeys.size(); i++) {
3625 msg.appendFormat(", %d->%d", fallbackKeys.keyAt(i),
3626 fallbackKeys.valueAt(i));
3627 }
Steve Block5baa3a62011-12-20 16:23:08 +00003628 ALOGD("Unhandled key event: %d currently tracked fallback keys%s.",
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003629 fallbackKeys.size(), msg.string());
3630 }
3631#endif
3632
3633 if (fallback) {
3634 // Restart the dispatch cycle using the fallback key.
3635 keyEntry->eventTime = event.getEventTime();
3636 keyEntry->deviceId = event.getDeviceId();
3637 keyEntry->source = event.getSource();
3638 keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
3639 keyEntry->keyCode = fallbackKeyCode;
3640 keyEntry->scanCode = event.getScanCode();
3641 keyEntry->metaState = event.getMetaState();
3642 keyEntry->repeatCount = event.getRepeatCount();
3643 keyEntry->downTime = event.getDownTime();
3644 keyEntry->syntheticRepeat = false;
3645
3646#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00003647 ALOGD("Unhandled key event: Dispatching fallback key. "
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003648 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
3649 originalKeyCode, fallbackKeyCode, keyEntry->metaState);
3650#endif
Jeff Brownd1c48a02012-02-06 19:12:47 -08003651 return true; // restart the event
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003652 } else {
3653#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00003654 ALOGD("Unhandled key event: No fallback key.");
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003655#endif
3656 }
3657 }
3658 }
3659 return false;
3660}
3661
3662bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
3663 DispatchEntry* dispatchEntry, MotionEntry* motionEntry, bool handled) {
3664 return false;
Jeff Brown3915bb82010-11-05 15:02:16 -07003665}
3666
Jeff Brownb88102f2010-09-08 11:49:43 -07003667void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
3668 mLock.unlock();
3669
Jeff Brown01ce2e92010-09-26 22:20:12 -07003670 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
Jeff Brownb88102f2010-09-08 11:49:43 -07003671
3672 mLock.lock();
3673}
3674
Jeff Brown3915bb82010-11-05 15:02:16 -07003675void InputDispatcher::initializeKeyEvent(KeyEvent* event, const KeyEntry* entry) {
3676 event->initialize(entry->deviceId, entry->source, entry->action, entry->flags,
3677 entry->keyCode, entry->scanCode, entry->metaState, entry->repeatCount,
3678 entry->downTime, entry->eventTime);
3679}
3680
Jeff Brown519e0242010-09-15 15:18:56 -07003681void InputDispatcher::updateDispatchStatisticsLocked(nsecs_t currentTime, const EventEntry* entry,
3682 int32_t injectionResult, nsecs_t timeSpentWaitingForApplication) {
3683 // TODO Write some statistics about how long we spend waiting.
Jeff Brownb88102f2010-09-08 11:49:43 -07003684}
3685
Jeff Brown481c1572012-03-09 14:41:15 -08003686void InputDispatcher::traceInboundQueueLengthLocked() {
3687 if (ATRACE_ENABLED()) {
3688 ATRACE_INT("iq", mInboundQueue.count());
3689 }
3690}
3691
3692void InputDispatcher::traceOutboundQueueLengthLocked(const sp<Connection>& connection) {
3693 if (ATRACE_ENABLED()) {
3694 char counterName[40];
3695 snprintf(counterName, sizeof(counterName), "oq:%s", connection->getWindowName());
3696 ATRACE_INT(counterName, connection->outboundQueue.count());
3697 }
3698}
3699
3700void InputDispatcher::traceWaitQueueLengthLocked(const sp<Connection>& connection) {
3701 if (ATRACE_ENABLED()) {
3702 char counterName[40];
3703 snprintf(counterName, sizeof(counterName), "wq:%s", connection->getWindowName());
3704 ATRACE_INT(counterName, connection->waitQueue.count());
3705 }
3706}
3707
Jeff Brownb88102f2010-09-08 11:49:43 -07003708void InputDispatcher::dump(String8& dump) {
Jeff Brown89ef0722011-08-10 16:25:21 -07003709 AutoMutex _l(mLock);
3710
Jeff Brownf2f487182010-10-01 17:46:21 -07003711 dump.append("Input Dispatcher State:\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003712 dumpDispatchStateLocked(dump);
Jeff Brown214eaf42011-05-26 19:17:02 -07003713
Jeff Brown22aa5122012-06-17 12:01:06 -07003714 if (!mLastANRState.isEmpty()) {
3715 dump.append("\nInput Dispatcher State at time of last ANR:\n");
3716 dump.append(mLastANRState);
3717 }
Jeff Brownb88102f2010-09-08 11:49:43 -07003718}
3719
Jeff Brown89ef0722011-08-10 16:25:21 -07003720void InputDispatcher::monitor() {
3721 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
3722 mLock.lock();
Jeff Brown112b5f52012-01-27 17:32:06 -08003723 mLooper->wake();
3724 mDispatcherIsAliveCondition.wait(mLock);
Jeff Brown89ef0722011-08-10 16:25:21 -07003725 mLock.unlock();
3726}
3727
Jeff Brown9c3cda02010-06-15 01:31:58 -07003728
Jeff Brown519e0242010-09-15 15:18:56 -07003729// --- InputDispatcher::Queue ---
3730
3731template <typename T>
3732uint32_t InputDispatcher::Queue<T>::count() const {
3733 uint32_t result = 0;
Jeff Brownac386072011-07-20 15:19:50 -07003734 for (const T* entry = head; entry; entry = entry->next) {
Jeff Brown519e0242010-09-15 15:18:56 -07003735 result += 1;
3736 }
3737 return result;
3738}
3739
3740
Jeff Brownac386072011-07-20 15:19:50 -07003741// --- InputDispatcher::InjectionState ---
Jeff Brown46b9ac02010-04-22 18:58:52 -07003742
Jeff Brownac386072011-07-20 15:19:50 -07003743InputDispatcher::InjectionState::InjectionState(int32_t injectorPid, int32_t injectorUid) :
3744 refCount(1),
3745 injectorPid(injectorPid), injectorUid(injectorUid),
3746 injectionResult(INPUT_EVENT_INJECTION_PENDING), injectionIsAsync(false),
3747 pendingForegroundDispatches(0) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07003748}
3749
Jeff Brownac386072011-07-20 15:19:50 -07003750InputDispatcher::InjectionState::~InjectionState() {
Jeff Brown01ce2e92010-09-26 22:20:12 -07003751}
3752
Jeff Brownac386072011-07-20 15:19:50 -07003753void InputDispatcher::InjectionState::release() {
3754 refCount -= 1;
3755 if (refCount == 0) {
3756 delete this;
3757 } else {
Steve Blockec193de2012-01-09 18:35:44 +00003758 ALOG_ASSERT(refCount > 0);
Jeff Brown01ce2e92010-09-26 22:20:12 -07003759 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07003760}
3761
Jeff Brownac386072011-07-20 15:19:50 -07003762
3763// --- InputDispatcher::EventEntry ---
3764
3765InputDispatcher::EventEntry::EventEntry(int32_t type, nsecs_t eventTime, uint32_t policyFlags) :
3766 refCount(1), type(type), eventTime(eventTime), policyFlags(policyFlags),
3767 injectionState(NULL), dispatchInProgress(false) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07003768}
3769
Jeff Brownac386072011-07-20 15:19:50 -07003770InputDispatcher::EventEntry::~EventEntry() {
3771 releaseInjectionState();
3772}
3773
3774void InputDispatcher::EventEntry::release() {
3775 refCount -= 1;
3776 if (refCount == 0) {
3777 delete this;
3778 } else {
Steve Blockec193de2012-01-09 18:35:44 +00003779 ALOG_ASSERT(refCount > 0);
Jeff Brownac386072011-07-20 15:19:50 -07003780 }
3781}
3782
3783void InputDispatcher::EventEntry::releaseInjectionState() {
3784 if (injectionState) {
3785 injectionState->release();
3786 injectionState = NULL;
3787 }
3788}
3789
3790
3791// --- InputDispatcher::ConfigurationChangedEntry ---
3792
3793InputDispatcher::ConfigurationChangedEntry::ConfigurationChangedEntry(nsecs_t eventTime) :
3794 EventEntry(TYPE_CONFIGURATION_CHANGED, eventTime, 0) {
3795}
3796
3797InputDispatcher::ConfigurationChangedEntry::~ConfigurationChangedEntry() {
3798}
3799
Jeff Brown265f1cc2012-06-11 18:01:06 -07003800void InputDispatcher::ConfigurationChangedEntry::appendDescription(String8& msg) const {
3801 msg.append("ConfigurationChangedEvent()");
3802}
3803
Jeff Brownac386072011-07-20 15:19:50 -07003804
Jeff Brown65fd2512011-08-18 11:20:58 -07003805// --- InputDispatcher::DeviceResetEntry ---
3806
3807InputDispatcher::DeviceResetEntry::DeviceResetEntry(nsecs_t eventTime, int32_t deviceId) :
3808 EventEntry(TYPE_DEVICE_RESET, eventTime, 0),
3809 deviceId(deviceId) {
3810}
3811
3812InputDispatcher::DeviceResetEntry::~DeviceResetEntry() {
3813}
3814
Jeff Brown265f1cc2012-06-11 18:01:06 -07003815void InputDispatcher::DeviceResetEntry::appendDescription(String8& msg) const {
3816 msg.appendFormat("DeviceResetEvent(deviceId=%d)", deviceId);
3817}
3818
Jeff Brown65fd2512011-08-18 11:20:58 -07003819
Jeff Brownac386072011-07-20 15:19:50 -07003820// --- InputDispatcher::KeyEntry ---
3821
3822InputDispatcher::KeyEntry::KeyEntry(nsecs_t eventTime,
Jeff Brown58a2da82011-01-25 16:02:22 -08003823 int32_t deviceId, uint32_t source, uint32_t policyFlags, int32_t action,
Jeff Brown7fbdc842010-06-17 20:52:56 -07003824 int32_t flags, int32_t keyCode, int32_t scanCode, int32_t metaState,
Jeff Brownac386072011-07-20 15:19:50 -07003825 int32_t repeatCount, nsecs_t downTime) :
3826 EventEntry(TYPE_KEY, eventTime, policyFlags),
3827 deviceId(deviceId), source(source), action(action), flags(flags),
3828 keyCode(keyCode), scanCode(scanCode), metaState(metaState),
3829 repeatCount(repeatCount), downTime(downTime),
Jeff Brown905805a2011-10-12 13:57:59 -07003830 syntheticRepeat(false), interceptKeyResult(KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN),
3831 interceptKeyWakeupTime(0) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07003832}
3833
Jeff Brownac386072011-07-20 15:19:50 -07003834InputDispatcher::KeyEntry::~KeyEntry() {
3835}
Jeff Brown7fbdc842010-06-17 20:52:56 -07003836
Jeff Brown265f1cc2012-06-11 18:01:06 -07003837void InputDispatcher::KeyEntry::appendDescription(String8& msg) const {
3838 msg.appendFormat("KeyEvent(action=%d, deviceId=%d, source=0x%08x)",
3839 action, deviceId, source);
3840}
3841
Jeff Brownac386072011-07-20 15:19:50 -07003842void InputDispatcher::KeyEntry::recycle() {
3843 releaseInjectionState();
3844
3845 dispatchInProgress = false;
3846 syntheticRepeat = false;
3847 interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
Jeff Brown905805a2011-10-12 13:57:59 -07003848 interceptKeyWakeupTime = 0;
Jeff Brownac386072011-07-20 15:19:50 -07003849}
3850
3851
Jeff Brownae9fc032010-08-18 15:51:08 -07003852// --- InputDispatcher::MotionEntry ---
3853
Jeff Brownac386072011-07-20 15:19:50 -07003854InputDispatcher::MotionEntry::MotionEntry(nsecs_t eventTime,
3855 int32_t deviceId, uint32_t source, uint32_t policyFlags, int32_t action, int32_t flags,
3856 int32_t metaState, int32_t buttonState,
3857 int32_t edgeFlags, float xPrecision, float yPrecision,
Jeff Brown83d616a2012-09-09 20:33:43 -07003858 nsecs_t downTime, int32_t displayId, uint32_t pointerCount,
Jeff Brownac386072011-07-20 15:19:50 -07003859 const PointerProperties* pointerProperties, const PointerCoords* pointerCoords) :
3860 EventEntry(TYPE_MOTION, eventTime, policyFlags),
Jeff Brown3241b6b2012-02-03 15:08:02 -08003861 eventTime(eventTime),
Jeff Brownac386072011-07-20 15:19:50 -07003862 deviceId(deviceId), source(source), action(action), flags(flags),
3863 metaState(metaState), buttonState(buttonState), edgeFlags(edgeFlags),
3864 xPrecision(xPrecision), yPrecision(yPrecision),
Jeff Brown83d616a2012-09-09 20:33:43 -07003865 downTime(downTime), displayId(displayId), pointerCount(pointerCount) {
Jeff Brownac386072011-07-20 15:19:50 -07003866 for (uint32_t i = 0; i < pointerCount; i++) {
3867 this->pointerProperties[i].copyFrom(pointerProperties[i]);
Jeff Brown3241b6b2012-02-03 15:08:02 -08003868 this->pointerCoords[i].copyFrom(pointerCoords[i]);
Jeff Brownac386072011-07-20 15:19:50 -07003869 }
3870}
3871
3872InputDispatcher::MotionEntry::~MotionEntry() {
Jeff Brownac386072011-07-20 15:19:50 -07003873}
3874
Jeff Brown265f1cc2012-06-11 18:01:06 -07003875void InputDispatcher::MotionEntry::appendDescription(String8& msg) const {
Jeff Brown83d616a2012-09-09 20:33:43 -07003876 msg.appendFormat("MotionEvent(action=%d, deviceId=%d, source=0x%08x, displayId=%d)",
3877 action, deviceId, source, displayId);
Jeff Brown265f1cc2012-06-11 18:01:06 -07003878}
3879
Jeff Brownac386072011-07-20 15:19:50 -07003880
3881// --- InputDispatcher::DispatchEntry ---
3882
Jeff Brown072ec962012-02-07 14:46:57 -08003883volatile int32_t InputDispatcher::DispatchEntry::sNextSeqAtomic;
3884
Jeff Brownac386072011-07-20 15:19:50 -07003885InputDispatcher::DispatchEntry::DispatchEntry(EventEntry* eventEntry,
3886 int32_t targetFlags, float xOffset, float yOffset, float scaleFactor) :
Jeff Brown072ec962012-02-07 14:46:57 -08003887 seq(nextSeq()),
Jeff Brownac386072011-07-20 15:19:50 -07003888 eventEntry(eventEntry), targetFlags(targetFlags),
3889 xOffset(xOffset), yOffset(yOffset), scaleFactor(scaleFactor),
Jeff Brown265f1cc2012-06-11 18:01:06 -07003890 deliveryTime(0), resolvedAction(0), resolvedFlags(0) {
Jeff Brownac386072011-07-20 15:19:50 -07003891 eventEntry->refCount += 1;
3892}
3893
3894InputDispatcher::DispatchEntry::~DispatchEntry() {
3895 eventEntry->release();
3896}
3897
Jeff Brown072ec962012-02-07 14:46:57 -08003898uint32_t InputDispatcher::DispatchEntry::nextSeq() {
3899 // Sequence number 0 is reserved and will never be returned.
3900 uint32_t seq;
3901 do {
3902 seq = android_atomic_inc(&sNextSeqAtomic);
3903 } while (!seq);
3904 return seq;
3905}
3906
Jeff Brownb88102f2010-09-08 11:49:43 -07003907
3908// --- InputDispatcher::InputState ---
3909
Jeff Brownb6997262010-10-08 22:31:17 -07003910InputDispatcher::InputState::InputState() {
Jeff Brownb88102f2010-09-08 11:49:43 -07003911}
3912
3913InputDispatcher::InputState::~InputState() {
3914}
3915
3916bool InputDispatcher::InputState::isNeutral() const {
3917 return mKeyMementos.isEmpty() && mMotionMementos.isEmpty();
3918}
3919
Jeff Brown83d616a2012-09-09 20:33:43 -07003920bool InputDispatcher::InputState::isHovering(int32_t deviceId, uint32_t source,
3921 int32_t displayId) const {
Jeff Brown81346812011-06-28 20:08:48 -07003922 for (size_t i = 0; i < mMotionMementos.size(); i++) {
3923 const MotionMemento& memento = mMotionMementos.itemAt(i);
3924 if (memento.deviceId == deviceId
3925 && memento.source == source
Jeff Brown83d616a2012-09-09 20:33:43 -07003926 && memento.displayId == displayId
Jeff Brown81346812011-06-28 20:08:48 -07003927 && memento.hovering) {
3928 return true;
3929 }
3930 }
3931 return false;
3932}
Jeff Brownb88102f2010-09-08 11:49:43 -07003933
Jeff Brown81346812011-06-28 20:08:48 -07003934bool InputDispatcher::InputState::trackKey(const KeyEntry* entry,
3935 int32_t action, int32_t flags) {
3936 switch (action) {
3937 case AKEY_EVENT_ACTION_UP: {
3938 if (entry->flags & AKEY_EVENT_FLAG_FALLBACK) {
3939 for (size_t i = 0; i < mFallbackKeys.size(); ) {
3940 if (mFallbackKeys.valueAt(i) == entry->keyCode) {
3941 mFallbackKeys.removeItemsAt(i);
3942 } else {
3943 i += 1;
3944 }
3945 }
3946 }
3947 ssize_t index = findKeyMemento(entry);
3948 if (index >= 0) {
3949 mKeyMementos.removeAt(index);
3950 return true;
3951 }
Jeff Brown68b909d2011-12-07 16:36:01 -08003952 /* FIXME: We can't just drop the key up event because that prevents creating
3953 * popup windows that are automatically shown when a key is held and then
3954 * dismissed when the key is released. The problem is that the popup will
3955 * not have received the original key down, so the key up will be considered
3956 * to be inconsistent with its observed state. We could perhaps handle this
3957 * by synthesizing a key down but that will cause other problems.
3958 *
3959 * So for now, allow inconsistent key up events to be dispatched.
3960 *
Jeff Brown81346812011-06-28 20:08:48 -07003961#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00003962 ALOGD("Dropping inconsistent key up event: deviceId=%d, source=%08x, "
Jeff Brown81346812011-06-28 20:08:48 -07003963 "keyCode=%d, scanCode=%d",
3964 entry->deviceId, entry->source, entry->keyCode, entry->scanCode);
3965#endif
3966 return false;
Jeff Brown68b909d2011-12-07 16:36:01 -08003967 */
3968 return true;
Jeff Brown81346812011-06-28 20:08:48 -07003969 }
3970
3971 case AKEY_EVENT_ACTION_DOWN: {
3972 ssize_t index = findKeyMemento(entry);
3973 if (index >= 0) {
3974 mKeyMementos.removeAt(index);
3975 }
3976 addKeyMemento(entry, flags);
3977 return true;
3978 }
3979
3980 default:
3981 return true;
Jeff Brownb88102f2010-09-08 11:49:43 -07003982 }
3983}
3984
Jeff Brown81346812011-06-28 20:08:48 -07003985bool InputDispatcher::InputState::trackMotion(const MotionEntry* entry,
3986 int32_t action, int32_t flags) {
3987 int32_t actionMasked = action & AMOTION_EVENT_ACTION_MASK;
3988 switch (actionMasked) {
3989 case AMOTION_EVENT_ACTION_UP:
3990 case AMOTION_EVENT_ACTION_CANCEL: {
3991 ssize_t index = findMotionMemento(entry, false /*hovering*/);
3992 if (index >= 0) {
3993 mMotionMementos.removeAt(index);
3994 return true;
Jeff Brownda3d5a92011-03-29 15:11:34 -07003995 }
Jeff Brown81346812011-06-28 20:08:48 -07003996#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00003997 ALOGD("Dropping inconsistent motion up or cancel event: deviceId=%d, source=%08x, "
Jeff Brown81346812011-06-28 20:08:48 -07003998 "actionMasked=%d",
3999 entry->deviceId, entry->source, actionMasked);
4000#endif
4001 return false;
Jeff Brownda3d5a92011-03-29 15:11:34 -07004002 }
4003
Jeff Brown81346812011-06-28 20:08:48 -07004004 case AMOTION_EVENT_ACTION_DOWN: {
4005 ssize_t index = findMotionMemento(entry, false /*hovering*/);
4006 if (index >= 0) {
4007 mMotionMementos.removeAt(index);
4008 }
4009 addMotionMemento(entry, flags, false /*hovering*/);
4010 return true;
4011 }
4012
4013 case AMOTION_EVENT_ACTION_POINTER_UP:
4014 case AMOTION_EVENT_ACTION_POINTER_DOWN:
4015 case AMOTION_EVENT_ACTION_MOVE: {
4016 ssize_t index = findMotionMemento(entry, false /*hovering*/);
4017 if (index >= 0) {
4018 MotionMemento& memento = mMotionMementos.editItemAt(index);
4019 memento.setPointers(entry);
4020 return true;
4021 }
Jeff Brown2e45fb62011-06-29 21:19:05 -07004022 if (actionMasked == AMOTION_EVENT_ACTION_MOVE
4023 && (entry->source & (AINPUT_SOURCE_CLASS_JOYSTICK
4024 | AINPUT_SOURCE_CLASS_NAVIGATION))) {
4025 // Joysticks and trackballs can send MOVE events without corresponding DOWN or UP.
4026 return true;
4027 }
Jeff Brown81346812011-06-28 20:08:48 -07004028#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00004029 ALOGD("Dropping inconsistent motion pointer up/down or move event: "
Jeff Brown81346812011-06-28 20:08:48 -07004030 "deviceId=%d, source=%08x, actionMasked=%d",
4031 entry->deviceId, entry->source, actionMasked);
4032#endif
4033 return false;
4034 }
4035
4036 case AMOTION_EVENT_ACTION_HOVER_EXIT: {
4037 ssize_t index = findMotionMemento(entry, true /*hovering*/);
4038 if (index >= 0) {
4039 mMotionMementos.removeAt(index);
4040 return true;
4041 }
4042#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00004043 ALOGD("Dropping inconsistent motion hover exit event: deviceId=%d, source=%08x",
Jeff Brown81346812011-06-28 20:08:48 -07004044 entry->deviceId, entry->source);
4045#endif
4046 return false;
4047 }
4048
4049 case AMOTION_EVENT_ACTION_HOVER_ENTER:
4050 case AMOTION_EVENT_ACTION_HOVER_MOVE: {
4051 ssize_t index = findMotionMemento(entry, true /*hovering*/);
4052 if (index >= 0) {
4053 mMotionMementos.removeAt(index);
4054 }
4055 addMotionMemento(entry, flags, true /*hovering*/);
4056 return true;
4057 }
4058
4059 default:
4060 return true;
4061 }
4062}
4063
4064ssize_t InputDispatcher::InputState::findKeyMemento(const KeyEntry* entry) const {
Jeff Brownb88102f2010-09-08 11:49:43 -07004065 for (size_t i = 0; i < mKeyMementos.size(); i++) {
Jeff Brown81346812011-06-28 20:08:48 -07004066 const KeyMemento& memento = mKeyMementos.itemAt(i);
Jeff Brownb88102f2010-09-08 11:49:43 -07004067 if (memento.deviceId == entry->deviceId
4068 && memento.source == entry->source
4069 && memento.keyCode == entry->keyCode
4070 && memento.scanCode == entry->scanCode) {
Jeff Brown81346812011-06-28 20:08:48 -07004071 return i;
Jeff Brownb88102f2010-09-08 11:49:43 -07004072 }
4073 }
Jeff Brown81346812011-06-28 20:08:48 -07004074 return -1;
Jeff Brownb88102f2010-09-08 11:49:43 -07004075}
4076
Jeff Brown81346812011-06-28 20:08:48 -07004077ssize_t InputDispatcher::InputState::findMotionMemento(const MotionEntry* entry,
4078 bool hovering) const {
Jeff Brownb88102f2010-09-08 11:49:43 -07004079 for (size_t i = 0; i < mMotionMementos.size(); i++) {
Jeff Brown81346812011-06-28 20:08:48 -07004080 const MotionMemento& memento = mMotionMementos.itemAt(i);
Jeff Brownb88102f2010-09-08 11:49:43 -07004081 if (memento.deviceId == entry->deviceId
Jeff Brown81346812011-06-28 20:08:48 -07004082 && memento.source == entry->source
Jeff Brown83d616a2012-09-09 20:33:43 -07004083 && memento.displayId == entry->displayId
Jeff Brown81346812011-06-28 20:08:48 -07004084 && memento.hovering == hovering) {
4085 return i;
Jeff Brownb88102f2010-09-08 11:49:43 -07004086 }
4087 }
Jeff Brown81346812011-06-28 20:08:48 -07004088 return -1;
4089}
Jeff Brownb88102f2010-09-08 11:49:43 -07004090
Jeff Brown81346812011-06-28 20:08:48 -07004091void InputDispatcher::InputState::addKeyMemento(const KeyEntry* entry, int32_t flags) {
4092 mKeyMementos.push();
4093 KeyMemento& memento = mKeyMementos.editTop();
4094 memento.deviceId = entry->deviceId;
4095 memento.source = entry->source;
4096 memento.keyCode = entry->keyCode;
4097 memento.scanCode = entry->scanCode;
Jeff Brownfd23e3e2012-05-09 13:34:28 -07004098 memento.metaState = entry->metaState;
Jeff Brown81346812011-06-28 20:08:48 -07004099 memento.flags = flags;
4100 memento.downTime = entry->downTime;
Jeff Brownfd23e3e2012-05-09 13:34:28 -07004101 memento.policyFlags = entry->policyFlags;
Jeff Brown81346812011-06-28 20:08:48 -07004102}
4103
4104void InputDispatcher::InputState::addMotionMemento(const MotionEntry* entry,
4105 int32_t flags, bool hovering) {
4106 mMotionMementos.push();
4107 MotionMemento& memento = mMotionMementos.editTop();
4108 memento.deviceId = entry->deviceId;
4109 memento.source = entry->source;
4110 memento.flags = flags;
4111 memento.xPrecision = entry->xPrecision;
4112 memento.yPrecision = entry->yPrecision;
4113 memento.downTime = entry->downTime;
Jeff Brown83d616a2012-09-09 20:33:43 -07004114 memento.displayId = entry->displayId;
Jeff Brown81346812011-06-28 20:08:48 -07004115 memento.setPointers(entry);
4116 memento.hovering = hovering;
Jeff Brownfd23e3e2012-05-09 13:34:28 -07004117 memento.policyFlags = entry->policyFlags;
Jeff Brownb88102f2010-09-08 11:49:43 -07004118}
4119
4120void InputDispatcher::InputState::MotionMemento::setPointers(const MotionEntry* entry) {
4121 pointerCount = entry->pointerCount;
4122 for (uint32_t i = 0; i < entry->pointerCount; i++) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07004123 pointerProperties[i].copyFrom(entry->pointerProperties[i]);
Jeff Brown3241b6b2012-02-03 15:08:02 -08004124 pointerCoords[i].copyFrom(entry->pointerCoords[i]);
Jeff Brownb88102f2010-09-08 11:49:43 -07004125 }
4126}
4127
Jeff Brownb6997262010-10-08 22:31:17 -07004128void InputDispatcher::InputState::synthesizeCancelationEvents(nsecs_t currentTime,
Jeff Brownac386072011-07-20 15:19:50 -07004129 Vector<EventEntry*>& outEvents, const CancelationOptions& options) {
Jeff Brown81346812011-06-28 20:08:48 -07004130 for (size_t i = 0; i < mKeyMementos.size(); i++) {
Jeff Brownb88102f2010-09-08 11:49:43 -07004131 const KeyMemento& memento = mKeyMementos.itemAt(i);
Jeff Brown49ed71d2010-12-06 17:13:33 -08004132 if (shouldCancelKey(memento, options)) {
Jeff Brownac386072011-07-20 15:19:50 -07004133 outEvents.push(new KeyEntry(currentTime,
Jeff Brownfd23e3e2012-05-09 13:34:28 -07004134 memento.deviceId, memento.source, memento.policyFlags,
Jeff Brown49ed71d2010-12-06 17:13:33 -08004135 AKEY_EVENT_ACTION_UP, memento.flags | AKEY_EVENT_FLAG_CANCELED,
Jeff Brownfd23e3e2012-05-09 13:34:28 -07004136 memento.keyCode, memento.scanCode, memento.metaState, 0, memento.downTime));
Jeff Brownb6997262010-10-08 22:31:17 -07004137 }
Jeff Brownb88102f2010-09-08 11:49:43 -07004138 }
4139
Jeff Brown81346812011-06-28 20:08:48 -07004140 for (size_t i = 0; i < mMotionMementos.size(); i++) {
Jeff Brownb88102f2010-09-08 11:49:43 -07004141 const MotionMemento& memento = mMotionMementos.itemAt(i);
Jeff Brown49ed71d2010-12-06 17:13:33 -08004142 if (shouldCancelMotion(memento, options)) {
Jeff Brownac386072011-07-20 15:19:50 -07004143 outEvents.push(new MotionEntry(currentTime,
Jeff Brownfd23e3e2012-05-09 13:34:28 -07004144 memento.deviceId, memento.source, memento.policyFlags,
Jeff Browna032cc02011-03-07 16:56:21 -08004145 memento.hovering
4146 ? AMOTION_EVENT_ACTION_HOVER_EXIT
4147 : AMOTION_EVENT_ACTION_CANCEL,
Jeff Brown81346812011-06-28 20:08:48 -07004148 memento.flags, 0, 0, 0,
Jeff Brownb6997262010-10-08 22:31:17 -07004149 memento.xPrecision, memento.yPrecision, memento.downTime,
Jeff Brown83d616a2012-09-09 20:33:43 -07004150 memento.displayId,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07004151 memento.pointerCount, memento.pointerProperties, memento.pointerCoords));
Jeff Brownb6997262010-10-08 22:31:17 -07004152 }
Jeff Brownb88102f2010-09-08 11:49:43 -07004153 }
4154}
4155
4156void InputDispatcher::InputState::clear() {
4157 mKeyMementos.clear();
4158 mMotionMementos.clear();
Jeff Brownda3d5a92011-03-29 15:11:34 -07004159 mFallbackKeys.clear();
Jeff Brownb6997262010-10-08 22:31:17 -07004160}
4161
Jeff Brown9c9f1a32010-10-11 18:32:20 -07004162void InputDispatcher::InputState::copyPointerStateTo(InputState& other) const {
4163 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4164 const MotionMemento& memento = mMotionMementos.itemAt(i);
4165 if (memento.source & AINPUT_SOURCE_CLASS_POINTER) {
4166 for (size_t j = 0; j < other.mMotionMementos.size(); ) {
4167 const MotionMemento& otherMemento = other.mMotionMementos.itemAt(j);
4168 if (memento.deviceId == otherMemento.deviceId
Jeff Brown83d616a2012-09-09 20:33:43 -07004169 && memento.source == otherMemento.source
4170 && memento.displayId == otherMemento.displayId) {
Jeff Brown9c9f1a32010-10-11 18:32:20 -07004171 other.mMotionMementos.removeAt(j);
4172 } else {
4173 j += 1;
4174 }
4175 }
4176 other.mMotionMementos.push(memento);
4177 }
4178 }
4179}
4180
Jeff Brownda3d5a92011-03-29 15:11:34 -07004181int32_t InputDispatcher::InputState::getFallbackKey(int32_t originalKeyCode) {
4182 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
4183 return index >= 0 ? mFallbackKeys.valueAt(index) : -1;
4184}
4185
4186void InputDispatcher::InputState::setFallbackKey(int32_t originalKeyCode,
4187 int32_t fallbackKeyCode) {
4188 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
4189 if (index >= 0) {
4190 mFallbackKeys.replaceValueAt(index, fallbackKeyCode);
4191 } else {
4192 mFallbackKeys.add(originalKeyCode, fallbackKeyCode);
4193 }
4194}
4195
4196void InputDispatcher::InputState::removeFallbackKey(int32_t originalKeyCode) {
4197 mFallbackKeys.removeItem(originalKeyCode);
4198}
4199
Jeff Brown49ed71d2010-12-06 17:13:33 -08004200bool InputDispatcher::InputState::shouldCancelKey(const KeyMemento& memento,
Jeff Brownda3d5a92011-03-29 15:11:34 -07004201 const CancelationOptions& options) {
4202 if (options.keyCode != -1 && memento.keyCode != options.keyCode) {
4203 return false;
4204 }
4205
Jeff Brown65fd2512011-08-18 11:20:58 -07004206 if (options.deviceId != -1 && memento.deviceId != options.deviceId) {
4207 return false;
4208 }
4209
Jeff Brownda3d5a92011-03-29 15:11:34 -07004210 switch (options.mode) {
4211 case CancelationOptions::CANCEL_ALL_EVENTS:
4212 case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
Jeff Brownb6997262010-10-08 22:31:17 -07004213 return true;
Jeff Brownda3d5a92011-03-29 15:11:34 -07004214 case CancelationOptions::CANCEL_FALLBACK_EVENTS:
Jeff Brown49ed71d2010-12-06 17:13:33 -08004215 return memento.flags & AKEY_EVENT_FLAG_FALLBACK;
4216 default:
4217 return false;
4218 }
4219}
4220
4221bool InputDispatcher::InputState::shouldCancelMotion(const MotionMemento& memento,
Jeff Brownda3d5a92011-03-29 15:11:34 -07004222 const CancelationOptions& options) {
Jeff Brown65fd2512011-08-18 11:20:58 -07004223 if (options.deviceId != -1 && memento.deviceId != options.deviceId) {
4224 return false;
4225 }
4226
Jeff Brownda3d5a92011-03-29 15:11:34 -07004227 switch (options.mode) {
4228 case CancelationOptions::CANCEL_ALL_EVENTS:
Jeff Brown49ed71d2010-12-06 17:13:33 -08004229 return true;
Jeff Brownda3d5a92011-03-29 15:11:34 -07004230 case CancelationOptions::CANCEL_POINTER_EVENTS:
Jeff Brown49ed71d2010-12-06 17:13:33 -08004231 return memento.source & AINPUT_SOURCE_CLASS_POINTER;
Jeff Brownda3d5a92011-03-29 15:11:34 -07004232 case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
Jeff Brown49ed71d2010-12-06 17:13:33 -08004233 return !(memento.source & AINPUT_SOURCE_CLASS_POINTER);
4234 default:
4235 return false;
Jeff Brownb6997262010-10-08 22:31:17 -07004236 }
Jeff Brownb88102f2010-09-08 11:49:43 -07004237}
4238
4239
Jeff Brown46b9ac02010-04-22 18:58:52 -07004240// --- InputDispatcher::Connection ---
4241
Jeff Brown928e0542011-01-10 11:17:36 -08004242InputDispatcher::Connection::Connection(const sp<InputChannel>& inputChannel,
Jeff Browncc4f7db2011-08-30 20:34:48 -07004243 const sp<InputWindowHandle>& inputWindowHandle, bool monitor) :
Jeff Brown928e0542011-01-10 11:17:36 -08004244 status(STATUS_NORMAL), inputChannel(inputChannel), inputWindowHandle(inputWindowHandle),
Jeff Browncc4f7db2011-08-30 20:34:48 -07004245 monitor(monitor),
Jeff Brownd1c48a02012-02-06 19:12:47 -08004246 inputPublisher(inputChannel), inputPublisherBlocked(false) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07004247}
4248
4249InputDispatcher::Connection::~Connection() {
4250}
4251
Jeff Brown481c1572012-03-09 14:41:15 -08004252const char* InputDispatcher::Connection::getWindowName() const {
4253 if (inputWindowHandle != NULL) {
4254 return inputWindowHandle->getName().string();
4255 }
4256 if (monitor) {
4257 return "monitor";
4258 }
4259 return "?";
4260}
4261
Jeff Brown9c3cda02010-06-15 01:31:58 -07004262const char* InputDispatcher::Connection::getStatusLabel() const {
4263 switch (status) {
4264 case STATUS_NORMAL:
4265 return "NORMAL";
4266
4267 case STATUS_BROKEN:
4268 return "BROKEN";
4269
Jeff Brown9c3cda02010-06-15 01:31:58 -07004270 case STATUS_ZOMBIE:
4271 return "ZOMBIE";
4272
4273 default:
4274 return "UNKNOWN";
4275 }
4276}
4277
Jeff Brown072ec962012-02-07 14:46:57 -08004278InputDispatcher::DispatchEntry* InputDispatcher::Connection::findWaitQueueEntry(uint32_t seq) {
4279 for (DispatchEntry* entry = waitQueue.head; entry != NULL; entry = entry->next) {
4280 if (entry->seq == seq) {
4281 return entry;
4282 }
4283 }
4284 return NULL;
4285}
4286
Jeff Brownb88102f2010-09-08 11:49:43 -07004287
Jeff Brown9c3cda02010-06-15 01:31:58 -07004288// --- InputDispatcher::CommandEntry ---
4289
Jeff Brownac386072011-07-20 15:19:50 -07004290InputDispatcher::CommandEntry::CommandEntry(Command command) :
Jeff Brown072ec962012-02-07 14:46:57 -08004291 command(command), eventTime(0), keyEntry(NULL), userActivityEventType(0),
4292 seq(0), handled(false) {
Jeff Brown9c3cda02010-06-15 01:31:58 -07004293}
4294
4295InputDispatcher::CommandEntry::~CommandEntry() {
4296}
4297
Jeff Brown46b9ac02010-04-22 18:58:52 -07004298
Jeff Brown01ce2e92010-09-26 22:20:12 -07004299// --- InputDispatcher::TouchState ---
4300
4301InputDispatcher::TouchState::TouchState() :
Jeff Brown83d616a2012-09-09 20:33:43 -07004302 down(false), split(false), deviceId(-1), source(0), displayId(-1) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07004303}
4304
4305InputDispatcher::TouchState::~TouchState() {
4306}
4307
4308void InputDispatcher::TouchState::reset() {
4309 down = false;
4310 split = false;
Jeff Brown95712852011-01-04 19:41:59 -08004311 deviceId = -1;
Jeff Brown58a2da82011-01-25 16:02:22 -08004312 source = 0;
Jeff Brown83d616a2012-09-09 20:33:43 -07004313 displayId = -1;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004314 windows.clear();
4315}
4316
4317void InputDispatcher::TouchState::copyFrom(const TouchState& other) {
4318 down = other.down;
4319 split = other.split;
Jeff Brown95712852011-01-04 19:41:59 -08004320 deviceId = other.deviceId;
Jeff Brown58a2da82011-01-25 16:02:22 -08004321 source = other.source;
Jeff Brown83d616a2012-09-09 20:33:43 -07004322 displayId = other.displayId;
Jeff Brown9302c872011-07-13 22:51:29 -07004323 windows = other.windows;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004324}
4325
Jeff Brown9302c872011-07-13 22:51:29 -07004326void InputDispatcher::TouchState::addOrUpdateWindow(const sp<InputWindowHandle>& windowHandle,
Jeff Brown01ce2e92010-09-26 22:20:12 -07004327 int32_t targetFlags, BitSet32 pointerIds) {
4328 if (targetFlags & InputTarget::FLAG_SPLIT) {
4329 split = true;
4330 }
4331
4332 for (size_t i = 0; i < windows.size(); i++) {
4333 TouchedWindow& touchedWindow = windows.editItemAt(i);
Jeff Brown9302c872011-07-13 22:51:29 -07004334 if (touchedWindow.windowHandle == windowHandle) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07004335 touchedWindow.targetFlags |= targetFlags;
Jeff Brown98db5fa2011-06-08 15:37:10 -07004336 if (targetFlags & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
4337 touchedWindow.targetFlags &= ~InputTarget::FLAG_DISPATCH_AS_IS;
4338 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07004339 touchedWindow.pointerIds.value |= pointerIds.value;
4340 return;
4341 }
4342 }
4343
4344 windows.push();
4345
4346 TouchedWindow& touchedWindow = windows.editTop();
Jeff Brown9302c872011-07-13 22:51:29 -07004347 touchedWindow.windowHandle = windowHandle;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004348 touchedWindow.targetFlags = targetFlags;
4349 touchedWindow.pointerIds = pointerIds;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004350}
4351
Jeff Brownf44e3942012-04-20 11:33:27 -07004352void InputDispatcher::TouchState::removeWindow(const sp<InputWindowHandle>& windowHandle) {
4353 for (size_t i = 0; i < windows.size(); i++) {
4354 if (windows.itemAt(i).windowHandle == windowHandle) {
4355 windows.removeAt(i);
4356 return;
4357 }
4358 }
4359}
4360
Jeff Browna032cc02011-03-07 16:56:21 -08004361void InputDispatcher::TouchState::filterNonAsIsTouchWindows() {
Jeff Brown01ce2e92010-09-26 22:20:12 -07004362 for (size_t i = 0 ; i < windows.size(); ) {
Jeff Browna032cc02011-03-07 16:56:21 -08004363 TouchedWindow& window = windows.editItemAt(i);
Jeff Brown98db5fa2011-06-08 15:37:10 -07004364 if (window.targetFlags & (InputTarget::FLAG_DISPATCH_AS_IS
4365 | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER)) {
Jeff Browna032cc02011-03-07 16:56:21 -08004366 window.targetFlags &= ~InputTarget::FLAG_DISPATCH_MASK;
4367 window.targetFlags |= InputTarget::FLAG_DISPATCH_AS_IS;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004368 i += 1;
Jeff Browna032cc02011-03-07 16:56:21 -08004369 } else {
4370 windows.removeAt(i);
Jeff Brown01ce2e92010-09-26 22:20:12 -07004371 }
4372 }
4373}
4374
Jeff Brown9302c872011-07-13 22:51:29 -07004375sp<InputWindowHandle> InputDispatcher::TouchState::getFirstForegroundWindowHandle() const {
Jeff Brown01ce2e92010-09-26 22:20:12 -07004376 for (size_t i = 0; i < windows.size(); i++) {
Jeff Brown98db5fa2011-06-08 15:37:10 -07004377 const TouchedWindow& window = windows.itemAt(i);
4378 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
Jeff Brown9302c872011-07-13 22:51:29 -07004379 return window.windowHandle;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004380 }
4381 }
4382 return NULL;
4383}
4384
Jeff Brown98db5fa2011-06-08 15:37:10 -07004385bool InputDispatcher::TouchState::isSlippery() const {
4386 // Must have exactly one foreground window.
4387 bool haveSlipperyForegroundWindow = false;
4388 for (size_t i = 0; i < windows.size(); i++) {
4389 const TouchedWindow& window = windows.itemAt(i);
4390 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
Jeff Browncc4f7db2011-08-30 20:34:48 -07004391 if (haveSlipperyForegroundWindow
4392 || !(window.windowHandle->getInfo()->layoutParamsFlags
4393 & InputWindowInfo::FLAG_SLIPPERY)) {
Jeff Brown98db5fa2011-06-08 15:37:10 -07004394 return false;
4395 }
4396 haveSlipperyForegroundWindow = true;
4397 }
4398 }
4399 return haveSlipperyForegroundWindow;
4400}
4401
Jeff Brown01ce2e92010-09-26 22:20:12 -07004402
Jeff Brown46b9ac02010-04-22 18:58:52 -07004403// --- InputDispatcherThread ---
4404
4405InputDispatcherThread::InputDispatcherThread(const sp<InputDispatcherInterface>& dispatcher) :
4406 Thread(/*canCallJava*/ true), mDispatcher(dispatcher) {
4407}
4408
4409InputDispatcherThread::~InputDispatcherThread() {
4410}
4411
4412bool InputDispatcherThread::threadLoop() {
4413 mDispatcher->dispatchOnce();
4414 return true;
4415}
4416
4417} // namespace android