blob: e6e28df0dfb3688ffa266f27a50e600adc950d9e [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"
18
19//#define LOG_NDEBUG 0
20
21// Log detailed debug messages about each inbound event notification to the dispatcher.
Jeff Brown349703e2010-06-22 01:27:15 -070022#define DEBUG_INBOUND_EVENT_DETAILS 0
Jeff Brown46b9ac02010-04-22 18:58:52 -070023
24// Log detailed debug messages about each outbound event processed by the dispatcher.
Jeff Brown349703e2010-06-22 01:27:15 -070025#define DEBUG_OUTBOUND_EVENT_DETAILS 0
Jeff Brown46b9ac02010-04-22 18:58:52 -070026
Jeff Brown46b9ac02010-04-22 18:58:52 -070027// Log debug messages about the dispatch cycle.
Jeff Brown349703e2010-06-22 01:27:15 -070028#define DEBUG_DISPATCH_CYCLE 0
Jeff Brown46b9ac02010-04-22 18:58:52 -070029
Jeff Brown9c3cda02010-06-15 01:31:58 -070030// Log debug messages about registrations.
Jeff Brown349703e2010-06-22 01:27:15 -070031#define DEBUG_REGISTRATION 0
Jeff Brown9c3cda02010-06-15 01:31:58 -070032
Jeff Brown7fbdc842010-06-17 20:52:56 -070033// Log debug messages about input event injection.
Jeff Brown349703e2010-06-22 01:27:15 -070034#define DEBUG_INJECTION 0
Jeff Brown7fbdc842010-06-17 20:52:56 -070035
Jeff Brownb88102f2010-09-08 11:49:43 -070036// Log debug messages about input focus tracking.
37#define DEBUG_FOCUS 0
38
39// Log debug messages about the app switch latency optimization.
40#define DEBUG_APP_SWITCH 0
41
Jeff Browna032cc02011-03-07 16:56:21 -080042// Log debug messages about hover events.
43#define DEBUG_HOVER 0
44
Jeff Brownb4ff35d2011-01-02 16:37:43 -080045#include "InputDispatcher.h"
46
Jeff Brown46b9ac02010-04-22 18:58:52 -070047#include <cutils/log.h>
Jeff Brownb88102f2010-09-08 11:49:43 -070048#include <ui/PowerManager.h>
Jeff Brown46b9ac02010-04-22 18:58:52 -070049
50#include <stddef.h>
51#include <unistd.h>
Jeff Brown46b9ac02010-04-22 18:58:52 -070052#include <errno.h>
53#include <limits.h>
Jeff Brown46b9ac02010-04-22 18:58:52 -070054
Jeff Brownf2f48712010-10-01 17:46:21 -070055#define INDENT " "
56#define INDENT2 " "
57
Jeff Brown46b9ac02010-04-22 18:58:52 -070058namespace android {
59
Jeff Brownb88102f2010-09-08 11:49:43 -070060// Default input dispatching timeout if there is no focused application or paused window
61// from which to determine an appropriate dispatching timeout.
62const nsecs_t DEFAULT_INPUT_DISPATCHING_TIMEOUT = 5000 * 1000000LL; // 5 sec
63
64// Amount of time to allow for all pending events to be processed when an app switch
65// key is on the way. This is used to preempt input dispatch and drop input events
66// when an application takes too long to respond and the user has pressed an app switch key.
67const nsecs_t APP_SWITCH_TIMEOUT = 500 * 1000000LL; // 0.5sec
68
Jeff Brown928e0542011-01-10 11:17:36 -080069// Amount of time to allow for an event to be dispatched (measured since its eventTime)
70// before considering it stale and dropping it.
71const nsecs_t STALE_EVENT_TIMEOUT = 10000 * 1000000LL; // 10sec
72
Jeff Brownd1c48a02012-02-06 19:12:47 -080073// Amount of time to allow touch events to be streamed out to a connection before requiring
74// that the first event be finished. This value extends the ANR timeout by the specified
75// amount. For example, if streaming is allowed to get ahead by one second relative to the
76// queue of waiting unfinished events, then ANRs will similarly be delayed by one second.
77const nsecs_t STREAM_AHEAD_EVENT_TIMEOUT = 500 * 1000000LL; // 0.5sec
78
Jeff Brown46b9ac02010-04-22 18:58:52 -070079
Jeff Brown7fbdc842010-06-17 20:52:56 -070080static inline nsecs_t now() {
81 return systemTime(SYSTEM_TIME_MONOTONIC);
82}
83
Jeff Brownb88102f2010-09-08 11:49:43 -070084static inline const char* toString(bool value) {
85 return value ? "true" : "false";
86}
87
Jeff Brown01ce2e92010-09-26 22:20:12 -070088static inline int32_t getMotionEventActionPointerIndex(int32_t action) {
89 return (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK)
90 >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
91}
92
93static bool isValidKeyAction(int32_t action) {
94 switch (action) {
95 case AKEY_EVENT_ACTION_DOWN:
96 case AKEY_EVENT_ACTION_UP:
97 return true;
98 default:
99 return false;
100 }
101}
102
103static bool validateKeyEvent(int32_t action) {
104 if (! isValidKeyAction(action)) {
Steve Block3762c312012-01-06 19:20:56 +0000105 ALOGE("Key event has invalid action code 0x%x", action);
Jeff Brown01ce2e92010-09-26 22:20:12 -0700106 return false;
107 }
108 return true;
109}
110
Jeff Brownb6997262010-10-08 22:31:17 -0700111static bool isValidMotionAction(int32_t action, size_t pointerCount) {
Jeff Brown01ce2e92010-09-26 22:20:12 -0700112 switch (action & AMOTION_EVENT_ACTION_MASK) {
113 case AMOTION_EVENT_ACTION_DOWN:
114 case AMOTION_EVENT_ACTION_UP:
115 case AMOTION_EVENT_ACTION_CANCEL:
116 case AMOTION_EVENT_ACTION_MOVE:
Jeff Brown01ce2e92010-09-26 22:20:12 -0700117 case AMOTION_EVENT_ACTION_OUTSIDE:
Jeff Browna032cc02011-03-07 16:56:21 -0800118 case AMOTION_EVENT_ACTION_HOVER_ENTER:
Jeff Browncc0c1592011-02-19 05:07:28 -0800119 case AMOTION_EVENT_ACTION_HOVER_MOVE:
Jeff Browna032cc02011-03-07 16:56:21 -0800120 case AMOTION_EVENT_ACTION_HOVER_EXIT:
Jeff Brown33bbfd22011-02-24 20:55:35 -0800121 case AMOTION_EVENT_ACTION_SCROLL:
Jeff Brown01ce2e92010-09-26 22:20:12 -0700122 return true;
Jeff Brownb6997262010-10-08 22:31:17 -0700123 case AMOTION_EVENT_ACTION_POINTER_DOWN:
124 case AMOTION_EVENT_ACTION_POINTER_UP: {
125 int32_t index = getMotionEventActionPointerIndex(action);
126 return index >= 0 && size_t(index) < pointerCount;
127 }
Jeff Brown01ce2e92010-09-26 22:20:12 -0700128 default:
129 return false;
130 }
131}
132
133static bool validateMotionEvent(int32_t action, size_t pointerCount,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700134 const PointerProperties* pointerProperties) {
Jeff Brownb6997262010-10-08 22:31:17 -0700135 if (! isValidMotionAction(action, pointerCount)) {
Steve Block3762c312012-01-06 19:20:56 +0000136 ALOGE("Motion event has invalid action code 0x%x", action);
Jeff Brown01ce2e92010-09-26 22:20:12 -0700137 return false;
138 }
139 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Steve Block3762c312012-01-06 19:20:56 +0000140 ALOGE("Motion event has invalid pointer count %d; value must be between 1 and %d.",
Jeff Brown01ce2e92010-09-26 22:20:12 -0700141 pointerCount, MAX_POINTERS);
142 return false;
143 }
Jeff Brownc3db8582010-10-20 15:33:38 -0700144 BitSet32 pointerIdBits;
Jeff Brown01ce2e92010-09-26 22:20:12 -0700145 for (size_t i = 0; i < pointerCount; i++) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700146 int32_t id = pointerProperties[i].id;
Jeff Brownc3db8582010-10-20 15:33:38 -0700147 if (id < 0 || id > MAX_POINTER_ID) {
Steve Block3762c312012-01-06 19:20:56 +0000148 ALOGE("Motion event has invalid pointer id %d; value must be between 0 and %d",
Jeff Brownc3db8582010-10-20 15:33:38 -0700149 id, MAX_POINTER_ID);
Jeff Brown01ce2e92010-09-26 22:20:12 -0700150 return false;
151 }
Jeff Brownc3db8582010-10-20 15:33:38 -0700152 if (pointerIdBits.hasBit(id)) {
Steve Block3762c312012-01-06 19:20:56 +0000153 ALOGE("Motion event has duplicate pointer id %d", id);
Jeff Brownc3db8582010-10-20 15:33:38 -0700154 return false;
155 }
156 pointerIdBits.markBit(id);
Jeff Brown01ce2e92010-09-26 22:20:12 -0700157 }
158 return true;
159}
160
Jeff Brownfbf09772011-01-16 14:06:57 -0800161static void dumpRegion(String8& dump, const SkRegion& region) {
162 if (region.isEmpty()) {
163 dump.append("<empty>");
164 return;
165 }
166
167 bool first = true;
168 for (SkRegion::Iterator it(region); !it.done(); it.next()) {
169 if (first) {
170 first = false;
171 } else {
172 dump.append("|");
173 }
174 const SkIRect& rect = it.rect();
175 dump.appendFormat("[%d,%d][%d,%d]", rect.fLeft, rect.fTop, rect.fRight, rect.fBottom);
176 }
177}
178
Jeff Brownb88102f2010-09-08 11:49:43 -0700179
Jeff Brown46b9ac02010-04-22 18:58:52 -0700180// --- InputDispatcher ---
181
Jeff Brown9c3cda02010-06-15 01:31:58 -0700182InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy) :
Jeff Brownb88102f2010-09-08 11:49:43 -0700183 mPolicy(policy),
Jeff Brown928e0542011-01-10 11:17:36 -0800184 mPendingEvent(NULL), mAppSwitchSawKeyDown(false), mAppSwitchDueTime(LONG_LONG_MAX),
185 mNextUnblockedEvent(NULL),
Jeff Brown0029c662011-03-30 02:25:18 -0700186 mDispatchEnabled(true), mDispatchFrozen(false), mInputFilterEnabled(false),
Jeff Brown9302c872011-07-13 22:51:29 -0700187 mInputTargetWaitCause(INPUT_TARGET_WAIT_CAUSE_NONE) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -0700188 mLooper = new Looper(false);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700189
Jeff Brown46b9ac02010-04-22 18:58:52 -0700190 mKeyRepeatState.lastKeyEntry = NULL;
Jeff Brown9c3cda02010-06-15 01:31:58 -0700191
Jeff Brown214eaf42011-05-26 19:17:02 -0700192 policy->getDispatcherConfiguration(&mConfig);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700193}
194
195InputDispatcher::~InputDispatcher() {
Jeff Brownb88102f2010-09-08 11:49:43 -0700196 { // acquire lock
197 AutoMutex _l(mLock);
198
199 resetKeyRepeatLocked();
Jeff Brown54a18252010-09-16 14:07:33 -0700200 releasePendingEventLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -0700201 drainInboundQueueLocked();
202 }
Jeff Brown46b9ac02010-04-22 18:58:52 -0700203
Jeff Browncbee6d62012-02-03 20:11:27 -0800204 while (mConnectionsByFd.size() != 0) {
205 unregisterInputChannel(mConnectionsByFd.valueAt(0)->inputChannel);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700206 }
Jeff Brown46b9ac02010-04-22 18:58:52 -0700207}
208
209void InputDispatcher::dispatchOnce() {
Jeff Brown46b9ac02010-04-22 18:58:52 -0700210 nsecs_t nextWakeupTime = LONG_LONG_MAX;
211 { // acquire lock
212 AutoMutex _l(mLock);
Jeff Brown112b5f52012-01-27 17:32:06 -0800213 mDispatcherIsAliveCondition.broadcast();
214
Jeff Brown214eaf42011-05-26 19:17:02 -0700215 dispatchOnceInnerLocked(&nextWakeupTime);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700216
Jeff Brownb88102f2010-09-08 11:49:43 -0700217 if (runCommandsLockedInterruptible()) {
218 nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
Jeff Brown46b9ac02010-04-22 18:58:52 -0700219 }
Jeff Brown46b9ac02010-04-22 18:58:52 -0700220 } // release lock
221
Jeff Brownb88102f2010-09-08 11:49:43 -0700222 // Wait for callback or timeout or wake. (make sure we round up, not down)
223 nsecs_t currentTime = now();
Jeff Brownaa3855d2011-03-17 01:34:19 -0700224 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
Jeff Brown4fe6c3e2010-09-13 23:17:30 -0700225 mLooper->pollOnce(timeoutMillis);
Jeff Brownb88102f2010-09-08 11:49:43 -0700226}
227
Jeff Brown214eaf42011-05-26 19:17:02 -0700228void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700229 nsecs_t currentTime = now();
230
231 // Reset the key repeat timer whenever we disallow key events, even if the next event
232 // is not a key. This is to ensure that we abort a key repeat if the device is just coming
233 // out of sleep.
Jeff Brown214eaf42011-05-26 19:17:02 -0700234 if (!mPolicy->isKeyRepeatEnabled()) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700235 resetKeyRepeatLocked();
236 }
237
Jeff Brownb88102f2010-09-08 11:49:43 -0700238 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
239 if (mDispatchFrozen) {
240#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +0000241 ALOGD("Dispatch frozen. Waiting some more.");
Jeff Brownb88102f2010-09-08 11:49:43 -0700242#endif
243 return;
244 }
245
246 // Optimize latency of app switches.
247 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
248 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
249 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
250 if (mAppSwitchDueTime < *nextWakeupTime) {
251 *nextWakeupTime = mAppSwitchDueTime;
252 }
253
Jeff Brownb88102f2010-09-08 11:49:43 -0700254 // Ready to start a new event.
255 // If we don't already have a pending event, go grab one.
256 if (! mPendingEvent) {
257 if (mInboundQueue.isEmpty()) {
258 if (isAppSwitchDue) {
259 // The inbound queue is empty so the app switch key we were waiting
260 // for will never arrive. Stop waiting for it.
261 resetPendingAppSwitchLocked(false);
262 isAppSwitchDue = false;
263 }
264
265 // Synthesize a key repeat if appropriate.
266 if (mKeyRepeatState.lastKeyEntry) {
267 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
Jeff Brown214eaf42011-05-26 19:17:02 -0700268 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700269 } else {
270 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
271 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
272 }
273 }
274 }
Jeff Browncc4f7db2011-08-30 20:34:48 -0700275
276 // Nothing to do if there is no pending event.
Jeff Browne9bb9be2012-02-06 15:47:55 -0800277 if (!mPendingEvent) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700278 return;
279 }
280 } else {
281 // Inbound queue has at least one entry.
Jeff Browne9bb9be2012-02-06 15:47:55 -0800282 mPendingEvent = mInboundQueue.dequeueAtHead();
Jeff Brownb88102f2010-09-08 11:49:43 -0700283 }
Jeff Browne2fe69e2010-10-18 13:21:23 -0700284
285 // Poke user activity for this event.
286 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
287 pokeUserActivityLocked(mPendingEvent);
288 }
Jeff Browne9bb9be2012-02-06 15:47:55 -0800289
290 // Get ready to dispatch the event.
291 resetANRTimeoutsLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -0700292 }
293
294 // Now we have an event to dispatch.
Jeff Brown928e0542011-01-10 11:17:36 -0800295 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Steve Blockec193de2012-01-09 18:35:44 +0000296 ALOG_ASSERT(mPendingEvent != NULL);
Jeff Brown54a18252010-09-16 14:07:33 -0700297 bool done = false;
Jeff Brownb6997262010-10-08 22:31:17 -0700298 DropReason dropReason = DROP_REASON_NOT_DROPPED;
299 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
300 dropReason = DROP_REASON_POLICY;
301 } else if (!mDispatchEnabled) {
302 dropReason = DROP_REASON_DISABLED;
303 }
Jeff Brown928e0542011-01-10 11:17:36 -0800304
305 if (mNextUnblockedEvent == mPendingEvent) {
306 mNextUnblockedEvent = NULL;
307 }
308
Jeff Brownb88102f2010-09-08 11:49:43 -0700309 switch (mPendingEvent->type) {
310 case EventEntry::TYPE_CONFIGURATION_CHANGED: {
311 ConfigurationChangedEntry* typedEntry =
312 static_cast<ConfigurationChangedEntry*>(mPendingEvent);
Jeff Brown54a18252010-09-16 14:07:33 -0700313 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Jeff Brownb6997262010-10-08 22:31:17 -0700314 dropReason = DROP_REASON_NOT_DROPPED; // configuration changes are never dropped
Jeff Brownb88102f2010-09-08 11:49:43 -0700315 break;
316 }
317
Jeff Brown65fd2512011-08-18 11:20:58 -0700318 case EventEntry::TYPE_DEVICE_RESET: {
319 DeviceResetEntry* typedEntry =
320 static_cast<DeviceResetEntry*>(mPendingEvent);
321 done = dispatchDeviceResetLocked(currentTime, typedEntry);
322 dropReason = DROP_REASON_NOT_DROPPED; // device resets are never dropped
323 break;
324 }
325
Jeff Brownb88102f2010-09-08 11:49:43 -0700326 case EventEntry::TYPE_KEY: {
327 KeyEntry* typedEntry = static_cast<KeyEntry*>(mPendingEvent);
Jeff Brownb6997262010-10-08 22:31:17 -0700328 if (isAppSwitchDue) {
329 if (isAppSwitchKeyEventLocked(typedEntry)) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700330 resetPendingAppSwitchLocked(true);
Jeff Brownb6997262010-10-08 22:31:17 -0700331 isAppSwitchDue = false;
332 } else if (dropReason == DROP_REASON_NOT_DROPPED) {
333 dropReason = DROP_REASON_APP_SWITCH;
Jeff Brownb88102f2010-09-08 11:49:43 -0700334 }
335 }
Jeff Brown928e0542011-01-10 11:17:36 -0800336 if (dropReason == DROP_REASON_NOT_DROPPED
337 && isStaleEventLocked(currentTime, typedEntry)) {
338 dropReason = DROP_REASON_STALE;
339 }
340 if (dropReason == DROP_REASON_NOT_DROPPED && mNextUnblockedEvent) {
341 dropReason = DROP_REASON_BLOCKED;
342 }
Jeff Brown214eaf42011-05-26 19:17:02 -0700343 done = dispatchKeyLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700344 break;
345 }
346
347 case EventEntry::TYPE_MOTION: {
348 MotionEntry* typedEntry = static_cast<MotionEntry*>(mPendingEvent);
Jeff Brownb6997262010-10-08 22:31:17 -0700349 if (dropReason == DROP_REASON_NOT_DROPPED && isAppSwitchDue) {
350 dropReason = DROP_REASON_APP_SWITCH;
Jeff Brownb88102f2010-09-08 11:49:43 -0700351 }
Jeff Brown928e0542011-01-10 11:17:36 -0800352 if (dropReason == DROP_REASON_NOT_DROPPED
353 && isStaleEventLocked(currentTime, typedEntry)) {
354 dropReason = DROP_REASON_STALE;
355 }
356 if (dropReason == DROP_REASON_NOT_DROPPED && mNextUnblockedEvent) {
357 dropReason = DROP_REASON_BLOCKED;
358 }
Jeff Brownb6997262010-10-08 22:31:17 -0700359 done = dispatchMotionLocked(currentTime, typedEntry,
Jeff Browne20c9e02010-10-11 14:20:19 -0700360 &dropReason, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700361 break;
362 }
363
364 default:
Steve Blockec193de2012-01-09 18:35:44 +0000365 ALOG_ASSERT(false);
Jeff Brownb88102f2010-09-08 11:49:43 -0700366 break;
367 }
368
Jeff Brown54a18252010-09-16 14:07:33 -0700369 if (done) {
Jeff Brownb6997262010-10-08 22:31:17 -0700370 if (dropReason != DROP_REASON_NOT_DROPPED) {
371 dropInboundEventLocked(mPendingEvent, dropReason);
372 }
373
Jeff Brown54a18252010-09-16 14:07:33 -0700374 releasePendingEventLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -0700375 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
376 }
377}
378
379bool InputDispatcher::enqueueInboundEventLocked(EventEntry* entry) {
380 bool needWake = mInboundQueue.isEmpty();
381 mInboundQueue.enqueueAtTail(entry);
382
383 switch (entry->type) {
Jeff Brownb6997262010-10-08 22:31:17 -0700384 case EventEntry::TYPE_KEY: {
Jeff Brown928e0542011-01-10 11:17:36 -0800385 // Optimize app switch latency.
386 // If the application takes too long to catch up then we drop all events preceding
387 // the app switch key.
Jeff Brownb6997262010-10-08 22:31:17 -0700388 KeyEntry* keyEntry = static_cast<KeyEntry*>(entry);
389 if (isAppSwitchKeyEventLocked(keyEntry)) {
390 if (keyEntry->action == AKEY_EVENT_ACTION_DOWN) {
391 mAppSwitchSawKeyDown = true;
392 } else if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
393 if (mAppSwitchSawKeyDown) {
394#if DEBUG_APP_SWITCH
Steve Block5baa3a62011-12-20 16:23:08 +0000395 ALOGD("App switch is pending!");
Jeff Brownb6997262010-10-08 22:31:17 -0700396#endif
397 mAppSwitchDueTime = keyEntry->eventTime + APP_SWITCH_TIMEOUT;
398 mAppSwitchSawKeyDown = false;
399 needWake = true;
400 }
401 }
402 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700403 break;
404 }
Jeff Brown928e0542011-01-10 11:17:36 -0800405
406 case EventEntry::TYPE_MOTION: {
407 // Optimize case where the current application is unresponsive and the user
408 // decides to touch a window in a different application.
409 // If the application takes too long to catch up then we drop all events preceding
410 // the touch into the other window.
411 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
Jeff Brown33bbfd22011-02-24 20:55:35 -0800412 if (motionEntry->action == AMOTION_EVENT_ACTION_DOWN
Jeff Brown928e0542011-01-10 11:17:36 -0800413 && (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER)
414 && mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY
Jeff Brown9302c872011-07-13 22:51:29 -0700415 && mInputTargetWaitApplicationHandle != NULL) {
Jeff Brown3241b6b2012-02-03 15:08:02 -0800416 int32_t x = int32_t(motionEntry->pointerCoords[0].
Jeff Brownebbd5d12011-02-17 13:01:34 -0800417 getAxisValue(AMOTION_EVENT_AXIS_X));
Jeff Brown3241b6b2012-02-03 15:08:02 -0800418 int32_t y = int32_t(motionEntry->pointerCoords[0].
Jeff Brownebbd5d12011-02-17 13:01:34 -0800419 getAxisValue(AMOTION_EVENT_AXIS_Y));
Jeff Brown9302c872011-07-13 22:51:29 -0700420 sp<InputWindowHandle> touchedWindowHandle = findTouchedWindowAtLocked(x, y);
421 if (touchedWindowHandle != NULL
422 && touchedWindowHandle->inputApplicationHandle
423 != mInputTargetWaitApplicationHandle) {
Jeff Brown928e0542011-01-10 11:17:36 -0800424 // User touched a different application than the one we are waiting on.
425 // Flag the event, and start pruning the input queue.
426 mNextUnblockedEvent = motionEntry;
427 needWake = true;
428 }
429 }
430 break;
431 }
Jeff Brownb6997262010-10-08 22:31:17 -0700432 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700433
434 return needWake;
435}
436
Jeff Brown9302c872011-07-13 22:51:29 -0700437sp<InputWindowHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t x, int32_t y) {
Jeff Brown928e0542011-01-10 11:17:36 -0800438 // Traverse windows from front to back to find touched window.
Jeff Brown9302c872011-07-13 22:51:29 -0700439 size_t numWindows = mWindowHandles.size();
Jeff Brown928e0542011-01-10 11:17:36 -0800440 for (size_t i = 0; i < numWindows; i++) {
Jeff Brown9302c872011-07-13 22:51:29 -0700441 sp<InputWindowHandle> windowHandle = mWindowHandles.itemAt(i);
Jeff Browncc4f7db2011-08-30 20:34:48 -0700442 const InputWindowInfo* windowInfo = windowHandle->getInfo();
443 int32_t flags = windowInfo->layoutParamsFlags;
Jeff Brown928e0542011-01-10 11:17:36 -0800444
Jeff Browncc4f7db2011-08-30 20:34:48 -0700445 if (windowInfo->visible) {
446 if (!(flags & InputWindowInfo::FLAG_NOT_TOUCHABLE)) {
447 bool isTouchModal = (flags & (InputWindowInfo::FLAG_NOT_FOCUSABLE
448 | InputWindowInfo::FLAG_NOT_TOUCH_MODAL)) == 0;
449 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
Jeff Brown928e0542011-01-10 11:17:36 -0800450 // Found window.
Jeff Brown9302c872011-07-13 22:51:29 -0700451 return windowHandle;
Jeff Brown928e0542011-01-10 11:17:36 -0800452 }
453 }
454 }
455
Jeff Browncc4f7db2011-08-30 20:34:48 -0700456 if (flags & InputWindowInfo::FLAG_SYSTEM_ERROR) {
Jeff Brown928e0542011-01-10 11:17:36 -0800457 // Error window is on top but not visible, so touch is dropped.
458 return NULL;
459 }
460 }
461 return NULL;
462}
463
Jeff Brownb6997262010-10-08 22:31:17 -0700464void InputDispatcher::dropInboundEventLocked(EventEntry* entry, DropReason dropReason) {
465 const char* reason;
466 switch (dropReason) {
467 case DROP_REASON_POLICY:
Jeff Browne20c9e02010-10-11 14:20:19 -0700468#if DEBUG_INBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +0000469 ALOGD("Dropped event because policy consumed it.");
Jeff Browne20c9e02010-10-11 14:20:19 -0700470#endif
Jeff Brown3122e442010-10-11 23:32:49 -0700471 reason = "inbound event was dropped because the policy consumed it";
Jeff Brownb6997262010-10-08 22:31:17 -0700472 break;
473 case DROP_REASON_DISABLED:
Steve Block6215d3f2012-01-04 20:05:49 +0000474 ALOGI("Dropped event because input dispatch is disabled.");
Jeff Brownb6997262010-10-08 22:31:17 -0700475 reason = "inbound event was dropped because input dispatch is disabled";
476 break;
477 case DROP_REASON_APP_SWITCH:
Steve Block6215d3f2012-01-04 20:05:49 +0000478 ALOGI("Dropped event because of pending overdue app switch.");
Jeff Brownb6997262010-10-08 22:31:17 -0700479 reason = "inbound event was dropped because of pending overdue app switch";
480 break;
Jeff Brown928e0542011-01-10 11:17:36 -0800481 case DROP_REASON_BLOCKED:
Steve Block6215d3f2012-01-04 20:05:49 +0000482 ALOGI("Dropped event because the current application is not responding and the user "
Jeff Brown81346812011-06-28 20:08:48 -0700483 "has started interacting with a different application.");
Jeff Brown928e0542011-01-10 11:17:36 -0800484 reason = "inbound event was dropped because the current application is not responding "
Jeff Brown81346812011-06-28 20:08:48 -0700485 "and the user has started interacting with a different application";
Jeff Brown928e0542011-01-10 11:17:36 -0800486 break;
487 case DROP_REASON_STALE:
Steve Block6215d3f2012-01-04 20:05:49 +0000488 ALOGI("Dropped event because it is stale.");
Jeff Brown928e0542011-01-10 11:17:36 -0800489 reason = "inbound event was dropped because it is stale";
490 break;
Jeff Brownb6997262010-10-08 22:31:17 -0700491 default:
Steve Blockec193de2012-01-09 18:35:44 +0000492 ALOG_ASSERT(false);
Jeff Brownb6997262010-10-08 22:31:17 -0700493 return;
494 }
495
496 switch (entry->type) {
Jeff Brownda3d5a92011-03-29 15:11:34 -0700497 case EventEntry::TYPE_KEY: {
498 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
499 synthesizeCancelationEventsForAllConnectionsLocked(options);
Jeff Brownb6997262010-10-08 22:31:17 -0700500 break;
Jeff Brownda3d5a92011-03-29 15:11:34 -0700501 }
Jeff Brownb6997262010-10-08 22:31:17 -0700502 case EventEntry::TYPE_MOTION: {
503 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
504 if (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) {
Jeff Brownda3d5a92011-03-29 15:11:34 -0700505 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
506 synthesizeCancelationEventsForAllConnectionsLocked(options);
Jeff Brownb6997262010-10-08 22:31:17 -0700507 } else {
Jeff Brownda3d5a92011-03-29 15:11:34 -0700508 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
509 synthesizeCancelationEventsForAllConnectionsLocked(options);
Jeff Brownb6997262010-10-08 22:31:17 -0700510 }
511 break;
512 }
513 }
514}
515
516bool InputDispatcher::isAppSwitchKeyCode(int32_t keyCode) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700517 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL;
518}
519
Jeff Brownb6997262010-10-08 22:31:17 -0700520bool InputDispatcher::isAppSwitchKeyEventLocked(KeyEntry* keyEntry) {
521 return ! (keyEntry->flags & AKEY_EVENT_FLAG_CANCELED)
522 && isAppSwitchKeyCode(keyEntry->keyCode)
Jeff Browne20c9e02010-10-11 14:20:19 -0700523 && (keyEntry->policyFlags & POLICY_FLAG_TRUSTED)
Jeff Brownb6997262010-10-08 22:31:17 -0700524 && (keyEntry->policyFlags & POLICY_FLAG_PASS_TO_USER);
525}
526
Jeff Brownb88102f2010-09-08 11:49:43 -0700527bool InputDispatcher::isAppSwitchPendingLocked() {
528 return mAppSwitchDueTime != LONG_LONG_MAX;
529}
530
Jeff Brownb88102f2010-09-08 11:49:43 -0700531void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
532 mAppSwitchDueTime = LONG_LONG_MAX;
533
534#if DEBUG_APP_SWITCH
535 if (handled) {
Steve Block5baa3a62011-12-20 16:23:08 +0000536 ALOGD("App switch has arrived.");
Jeff Brownb88102f2010-09-08 11:49:43 -0700537 } else {
Steve Block5baa3a62011-12-20 16:23:08 +0000538 ALOGD("App switch was abandoned.");
Jeff Brownb88102f2010-09-08 11:49:43 -0700539 }
540#endif
Jeff Brown46b9ac02010-04-22 18:58:52 -0700541}
542
Jeff Brown928e0542011-01-10 11:17:36 -0800543bool InputDispatcher::isStaleEventLocked(nsecs_t currentTime, EventEntry* entry) {
544 return currentTime - entry->eventTime >= STALE_EVENT_TIMEOUT;
545}
546
Jeff Brown9c3cda02010-06-15 01:31:58 -0700547bool InputDispatcher::runCommandsLockedInterruptible() {
548 if (mCommandQueue.isEmpty()) {
549 return false;
550 }
Jeff Brown46b9ac02010-04-22 18:58:52 -0700551
Jeff Brown9c3cda02010-06-15 01:31:58 -0700552 do {
553 CommandEntry* commandEntry = mCommandQueue.dequeueAtHead();
554
555 Command command = commandEntry->command;
556 (this->*command)(commandEntry); // commands are implicitly 'LockedInterruptible'
557
Jeff Brown7fbdc842010-06-17 20:52:56 -0700558 commandEntry->connection.clear();
Jeff Brownac386072011-07-20 15:19:50 -0700559 delete commandEntry;
Jeff Brown9c3cda02010-06-15 01:31:58 -0700560 } while (! mCommandQueue.isEmpty());
561 return true;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700562}
563
Jeff Brown9c3cda02010-06-15 01:31:58 -0700564InputDispatcher::CommandEntry* InputDispatcher::postCommandLocked(Command command) {
Jeff Brownac386072011-07-20 15:19:50 -0700565 CommandEntry* commandEntry = new CommandEntry(command);
Jeff Brown9c3cda02010-06-15 01:31:58 -0700566 mCommandQueue.enqueueAtTail(commandEntry);
567 return commandEntry;
568}
569
Jeff Brownb88102f2010-09-08 11:49:43 -0700570void InputDispatcher::drainInboundQueueLocked() {
571 while (! mInboundQueue.isEmpty()) {
572 EventEntry* entry = mInboundQueue.dequeueAtHead();
Jeff Brown54a18252010-09-16 14:07:33 -0700573 releaseInboundEventLocked(entry);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700574 }
Jeff Brown46b9ac02010-04-22 18:58:52 -0700575}
576
Jeff Brown54a18252010-09-16 14:07:33 -0700577void InputDispatcher::releasePendingEventLocked() {
Jeff Brownb88102f2010-09-08 11:49:43 -0700578 if (mPendingEvent) {
Jeff Browne9bb9be2012-02-06 15:47:55 -0800579 resetANRTimeoutsLocked();
Jeff Brown54a18252010-09-16 14:07:33 -0700580 releaseInboundEventLocked(mPendingEvent);
Jeff Brownb88102f2010-09-08 11:49:43 -0700581 mPendingEvent = NULL;
582 }
583}
584
Jeff Brown54a18252010-09-16 14:07:33 -0700585void InputDispatcher::releaseInboundEventLocked(EventEntry* entry) {
Jeff Brown01ce2e92010-09-26 22:20:12 -0700586 InjectionState* injectionState = entry->injectionState;
587 if (injectionState && injectionState->injectionResult == INPUT_EVENT_INJECTION_PENDING) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700588#if DEBUG_DISPATCH_CYCLE
Steve Block5baa3a62011-12-20 16:23:08 +0000589 ALOGD("Injected inbound event was dropped.");
Jeff Brownb88102f2010-09-08 11:49:43 -0700590#endif
591 setInjectionResultLocked(entry, INPUT_EVENT_INJECTION_FAILED);
592 }
Jeff Brownabb4d442011-08-15 12:55:32 -0700593 if (entry == mNextUnblockedEvent) {
594 mNextUnblockedEvent = NULL;
595 }
Jeff Brownac386072011-07-20 15:19:50 -0700596 entry->release();
Jeff Brownb88102f2010-09-08 11:49:43 -0700597}
598
Jeff Brownb88102f2010-09-08 11:49:43 -0700599void InputDispatcher::resetKeyRepeatLocked() {
600 if (mKeyRepeatState.lastKeyEntry) {
Jeff Brownac386072011-07-20 15:19:50 -0700601 mKeyRepeatState.lastKeyEntry->release();
Jeff Brownb88102f2010-09-08 11:49:43 -0700602 mKeyRepeatState.lastKeyEntry = NULL;
603 }
604}
605
Jeff Brown214eaf42011-05-26 19:17:02 -0700606InputDispatcher::KeyEntry* InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
Jeff Brown349703e2010-06-22 01:27:15 -0700607 KeyEntry* entry = mKeyRepeatState.lastKeyEntry;
608
Jeff Brown349703e2010-06-22 01:27:15 -0700609 // Reuse the repeated key entry if it is otherwise unreferenced.
Jeff Browne20c9e02010-10-11 14:20:19 -0700610 uint32_t policyFlags = (entry->policyFlags & POLICY_FLAG_RAW_MASK)
611 | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700612 if (entry->refCount == 1) {
Jeff Brownac386072011-07-20 15:19:50 -0700613 entry->recycle();
Jeff Brown7fbdc842010-06-17 20:52:56 -0700614 entry->eventTime = currentTime;
Jeff Brown7fbdc842010-06-17 20:52:56 -0700615 entry->policyFlags = policyFlags;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700616 entry->repeatCount += 1;
617 } else {
Jeff Brownac386072011-07-20 15:19:50 -0700618 KeyEntry* newEntry = new KeyEntry(currentTime,
Jeff Brownc5ed5912010-07-14 18:48:53 -0700619 entry->deviceId, entry->source, policyFlags,
Jeff Brown7fbdc842010-06-17 20:52:56 -0700620 entry->action, entry->flags, entry->keyCode, entry->scanCode,
Jeff Brown00fa7bd2010-07-02 15:37:36 -0700621 entry->metaState, entry->repeatCount + 1, entry->downTime);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700622
623 mKeyRepeatState.lastKeyEntry = newEntry;
Jeff Brownac386072011-07-20 15:19:50 -0700624 entry->release();
Jeff Brown46b9ac02010-04-22 18:58:52 -0700625
626 entry = newEntry;
627 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700628 entry->syntheticRepeat = true;
629
630 // Increment reference count since we keep a reference to the event in
631 // mKeyRepeatState.lastKeyEntry in addition to the one we return.
632 entry->refCount += 1;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700633
Jeff Brown214eaf42011-05-26 19:17:02 -0700634 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Jeff Brownb88102f2010-09-08 11:49:43 -0700635 return entry;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700636}
637
Jeff Brownb88102f2010-09-08 11:49:43 -0700638bool InputDispatcher::dispatchConfigurationChangedLocked(
639 nsecs_t currentTime, ConfigurationChangedEntry* entry) {
Jeff Brown46b9ac02010-04-22 18:58:52 -0700640#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +0000641 ALOGD("dispatchConfigurationChanged - eventTime=%lld", entry->eventTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700642#endif
643
644 // Reset key repeating in case a keyboard device was added or removed or something.
645 resetKeyRepeatLocked();
646
647 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
648 CommandEntry* commandEntry = postCommandLocked(
649 & InputDispatcher::doNotifyConfigurationChangedInterruptible);
650 commandEntry->eventTime = entry->eventTime;
651 return true;
652}
653
Jeff Brown65fd2512011-08-18 11:20:58 -0700654bool InputDispatcher::dispatchDeviceResetLocked(
655 nsecs_t currentTime, DeviceResetEntry* entry) {
656#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +0000657 ALOGD("dispatchDeviceReset - eventTime=%lld, deviceId=%d", entry->eventTime, entry->deviceId);
Jeff Brown65fd2512011-08-18 11:20:58 -0700658#endif
659
660 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
661 "device was reset");
662 options.deviceId = entry->deviceId;
663 synthesizeCancelationEventsForAllConnectionsLocked(options);
664 return true;
665}
666
Jeff Brown214eaf42011-05-26 19:17:02 -0700667bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, KeyEntry* entry,
Jeff Browne20c9e02010-10-11 14:20:19 -0700668 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Jeff Browne46a0a42010-11-02 17:58:22 -0700669 // Preprocessing.
670 if (! entry->dispatchInProgress) {
671 if (entry->repeatCount == 0
672 && entry->action == AKEY_EVENT_ACTION_DOWN
673 && (entry->policyFlags & POLICY_FLAG_TRUSTED)
Jeff Brown0029c662011-03-30 02:25:18 -0700674 && (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
Jeff Browne46a0a42010-11-02 17:58:22 -0700675 if (mKeyRepeatState.lastKeyEntry
676 && mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode) {
677 // We have seen two identical key downs in a row which indicates that the device
678 // driver is automatically generating key repeats itself. We take note of the
679 // repeat here, but we disable our own next key repeat timer since it is clear that
680 // we will not need to synthesize key repeats ourselves.
681 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
682 resetKeyRepeatLocked();
683 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
684 } else {
685 // Not a repeat. Save key down state in case we do see a repeat later.
686 resetKeyRepeatLocked();
Jeff Brown214eaf42011-05-26 19:17:02 -0700687 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
Jeff Browne46a0a42010-11-02 17:58:22 -0700688 }
689 mKeyRepeatState.lastKeyEntry = entry;
690 entry->refCount += 1;
691 } else if (! entry->syntheticRepeat) {
692 resetKeyRepeatLocked();
693 }
694
Jeff Browne2e01262011-03-02 20:34:30 -0800695 if (entry->repeatCount == 1) {
696 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
697 } else {
698 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
699 }
700
Jeff Browne46a0a42010-11-02 17:58:22 -0700701 entry->dispatchInProgress = true;
Jeff Browne46a0a42010-11-02 17:58:22 -0700702
703 logOutboundKeyDetailsLocked("dispatchKey - ", entry);
704 }
705
Jeff Brown905805a2011-10-12 13:57:59 -0700706 // Handle case where the policy asked us to try again later last time.
707 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
708 if (currentTime < entry->interceptKeyWakeupTime) {
709 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
710 *nextWakeupTime = entry->interceptKeyWakeupTime;
711 }
712 return false; // wait until next wakeup
713 }
714 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
715 entry->interceptKeyWakeupTime = 0;
716 }
717
Jeff Brown54a18252010-09-16 14:07:33 -0700718 // Give the policy a chance to intercept the key.
719 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
Jeff Browne20c9e02010-10-11 14:20:19 -0700720 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Jeff Brown54a18252010-09-16 14:07:33 -0700721 CommandEntry* commandEntry = postCommandLocked(
722 & InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
Jeff Brown9302c872011-07-13 22:51:29 -0700723 if (mFocusedWindowHandle != NULL) {
724 commandEntry->inputWindowHandle = mFocusedWindowHandle;
Jeff Brown54a18252010-09-16 14:07:33 -0700725 }
726 commandEntry->keyEntry = entry;
727 entry->refCount += 1;
728 return false; // wait for the command to run
729 } else {
730 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
731 }
732 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Jeff Browne20c9e02010-10-11 14:20:19 -0700733 if (*dropReason == DROP_REASON_NOT_DROPPED) {
734 *dropReason = DROP_REASON_POLICY;
735 }
Jeff Brown54a18252010-09-16 14:07:33 -0700736 }
737
738 // Clean up if dropping the event.
Jeff Browne20c9e02010-10-11 14:20:19 -0700739 if (*dropReason != DROP_REASON_NOT_DROPPED) {
Jeff Brown3122e442010-10-11 23:32:49 -0700740 setInjectionResultLocked(entry, *dropReason == DROP_REASON_POLICY
741 ? INPUT_EVENT_INJECTION_SUCCEEDED : INPUT_EVENT_INJECTION_FAILED);
Jeff Brown54a18252010-09-16 14:07:33 -0700742 return true;
743 }
744
Jeff Brownb88102f2010-09-08 11:49:43 -0700745 // Identify targets.
Jeff Browne9bb9be2012-02-06 15:47:55 -0800746 Vector<InputTarget> inputTargets;
747 int32_t injectionResult = findFocusedWindowTargetsLocked(currentTime,
748 entry, inputTargets, nextWakeupTime);
749 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
750 return false;
Jeff Brownb88102f2010-09-08 11:49:43 -0700751 }
752
Jeff Browne9bb9be2012-02-06 15:47:55 -0800753 setInjectionResultLocked(entry, injectionResult);
754 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
755 return true;
756 }
757
758 addMonitoringTargetsLocked(inputTargets);
759
Jeff Brownb88102f2010-09-08 11:49:43 -0700760 // Dispatch the key.
Jeff Browne9bb9be2012-02-06 15:47:55 -0800761 dispatchEventLocked(currentTime, entry, inputTargets);
Jeff Brownb88102f2010-09-08 11:49:43 -0700762 return true;
763}
764
765void InputDispatcher::logOutboundKeyDetailsLocked(const char* prefix, const KeyEntry* entry) {
766#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +0000767 ALOGD("%seventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, "
Jeff Brownb88102f2010-09-08 11:49:43 -0700768 "action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, "
Jeff Browne46a0a42010-11-02 17:58:22 -0700769 "repeatCount=%d, downTime=%lld",
Jeff Brownb88102f2010-09-08 11:49:43 -0700770 prefix,
771 entry->eventTime, entry->deviceId, entry->source, entry->policyFlags,
772 entry->action, entry->flags, entry->keyCode, entry->scanCode, entry->metaState,
Jeff Browne46a0a42010-11-02 17:58:22 -0700773 entry->repeatCount, entry->downTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700774#endif
775}
776
777bool InputDispatcher::dispatchMotionLocked(
Jeff Browne20c9e02010-10-11 14:20:19 -0700778 nsecs_t currentTime, MotionEntry* entry, DropReason* dropReason, nsecs_t* nextWakeupTime) {
Jeff Browne46a0a42010-11-02 17:58:22 -0700779 // Preprocessing.
780 if (! entry->dispatchInProgress) {
781 entry->dispatchInProgress = true;
Jeff Browne46a0a42010-11-02 17:58:22 -0700782
783 logOutboundMotionDetailsLocked("dispatchMotion - ", entry);
784 }
785
Jeff Brown54a18252010-09-16 14:07:33 -0700786 // Clean up if dropping the event.
Jeff Browne20c9e02010-10-11 14:20:19 -0700787 if (*dropReason != DROP_REASON_NOT_DROPPED) {
Jeff Brown3122e442010-10-11 23:32:49 -0700788 setInjectionResultLocked(entry, *dropReason == DROP_REASON_POLICY
789 ? INPUT_EVENT_INJECTION_SUCCEEDED : INPUT_EVENT_INJECTION_FAILED);
Jeff Brown54a18252010-09-16 14:07:33 -0700790 return true;
791 }
792
Jeff Brownb88102f2010-09-08 11:49:43 -0700793 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
794
795 // Identify targets.
Jeff Browne9bb9be2012-02-06 15:47:55 -0800796 Vector<InputTarget> inputTargets;
797
Jeff Browncc0c1592011-02-19 05:07:28 -0800798 bool conflictingPointerActions = false;
Jeff Browne9bb9be2012-02-06 15:47:55 -0800799 int32_t injectionResult;
800 if (isPointerEvent) {
801 // Pointer event. (eg. touchscreen)
802 injectionResult = findTouchedWindowTargetsLocked(currentTime,
803 entry, inputTargets, nextWakeupTime, &conflictingPointerActions);
804 } else {
805 // Non touch event. (eg. trackball)
806 injectionResult = findFocusedWindowTargetsLocked(currentTime,
807 entry, inputTargets, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700808 }
Jeff Browne9bb9be2012-02-06 15:47:55 -0800809 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
810 return false;
811 }
812
813 setInjectionResultLocked(entry, injectionResult);
814 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
815 return true;
816 }
817
818 addMonitoringTargetsLocked(inputTargets);
Jeff Brownb88102f2010-09-08 11:49:43 -0700819
820 // Dispatch the motion.
Jeff Browncc0c1592011-02-19 05:07:28 -0800821 if (conflictingPointerActions) {
Jeff Brownda3d5a92011-03-29 15:11:34 -0700822 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
823 "conflicting pointer actions");
824 synthesizeCancelationEventsForAllConnectionsLocked(options);
Jeff Browncc0c1592011-02-19 05:07:28 -0800825 }
Jeff Browne9bb9be2012-02-06 15:47:55 -0800826 dispatchEventLocked(currentTime, entry, inputTargets);
Jeff Brownb88102f2010-09-08 11:49:43 -0700827 return true;
828}
829
830
831void InputDispatcher::logOutboundMotionDetailsLocked(const char* prefix, const MotionEntry* entry) {
832#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +0000833 ALOGD("%seventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, "
Jeff Brown85a31762010-09-01 17:01:00 -0700834 "action=0x%x, flags=0x%x, "
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700835 "metaState=0x%x, buttonState=0x%x, "
836 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%lld",
Jeff Brownb88102f2010-09-08 11:49:43 -0700837 prefix,
Jeff Brown85a31762010-09-01 17:01:00 -0700838 entry->eventTime, entry->deviceId, entry->source, entry->policyFlags,
839 entry->action, entry->flags,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700840 entry->metaState, entry->buttonState,
841 entry->edgeFlags, entry->xPrecision, entry->yPrecision,
Jeff Brown46b9ac02010-04-22 18:58:52 -0700842 entry->downTime);
843
Jeff Brown46b9ac02010-04-22 18:58:52 -0700844 for (uint32_t i = 0; i < entry->pointerCount; i++) {
Steve Block5baa3a62011-12-20 16:23:08 +0000845 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700846 "x=%f, y=%f, pressure=%f, size=%f, "
Jeff Brown85a31762010-09-01 17:01:00 -0700847 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
Jeff Brown8d608662010-08-30 03:02:23 -0700848 "orientation=%f",
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700849 i, entry->pointerProperties[i].id,
850 entry->pointerProperties[i].toolType,
Jeff Brown3241b6b2012-02-03 15:08:02 -0800851 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
852 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
853 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
854 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
855 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
856 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
857 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
858 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
859 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Jeff Brown46b9ac02010-04-22 18:58:52 -0700860 }
861#endif
Jeff Brown46b9ac02010-04-22 18:58:52 -0700862}
863
Jeff Browne9bb9be2012-02-06 15:47:55 -0800864void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
865 EventEntry* eventEntry, const Vector<InputTarget>& inputTargets) {
Jeff Brown46b9ac02010-04-22 18:58:52 -0700866#if DEBUG_DISPATCH_CYCLE
Jeff Brown3241b6b2012-02-03 15:08:02 -0800867 ALOGD("dispatchEventToCurrentInputTargets");
Jeff Brown46b9ac02010-04-22 18:58:52 -0700868#endif
869
Steve Blockec193de2012-01-09 18:35:44 +0000870 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
Jeff Brown9c3cda02010-06-15 01:31:58 -0700871
Jeff Browne2fe69e2010-10-18 13:21:23 -0700872 pokeUserActivityLocked(eventEntry);
873
Jeff Browne9bb9be2012-02-06 15:47:55 -0800874 for (size_t i = 0; i < inputTargets.size(); i++) {
875 const InputTarget& inputTarget = inputTargets.itemAt(i);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700876
Jeff Brown519e0242010-09-15 15:18:56 -0700877 ssize_t connectionIndex = getConnectionIndexLocked(inputTarget.inputChannel);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700878 if (connectionIndex >= 0) {
Jeff Browncbee6d62012-02-03 20:11:27 -0800879 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
Jeff Brown3241b6b2012-02-03 15:08:02 -0800880 prepareDispatchCycleLocked(currentTime, connection, eventEntry, &inputTarget);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700881 } else {
Jeff Brownb6997262010-10-08 22:31:17 -0700882#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +0000883 ALOGD("Dropping event delivery to target with channel '%s' because it "
Jeff Brownb6997262010-10-08 22:31:17 -0700884 "is no longer registered with the input dispatcher.",
Jeff Brown46b9ac02010-04-22 18:58:52 -0700885 inputTarget.inputChannel->getName().string());
Jeff Brownb6997262010-10-08 22:31:17 -0700886#endif
Jeff Brown46b9ac02010-04-22 18:58:52 -0700887 }
888 }
889}
890
Jeff Brownb88102f2010-09-08 11:49:43 -0700891int32_t InputDispatcher::handleTargetsNotReadyLocked(nsecs_t currentTime,
Jeff Brown9302c872011-07-13 22:51:29 -0700892 const EventEntry* entry,
893 const sp<InputApplicationHandle>& applicationHandle,
894 const sp<InputWindowHandle>& windowHandle,
Jeff Brownb88102f2010-09-08 11:49:43 -0700895 nsecs_t* nextWakeupTime) {
Jeff Brown9302c872011-07-13 22:51:29 -0700896 if (applicationHandle == NULL && windowHandle == NULL) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700897 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY) {
898#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +0000899 ALOGD("Waiting for system to become ready for input.");
Jeff Brownb88102f2010-09-08 11:49:43 -0700900#endif
901 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY;
902 mInputTargetWaitStartTime = currentTime;
903 mInputTargetWaitTimeoutTime = LONG_LONG_MAX;
904 mInputTargetWaitTimeoutExpired = false;
Jeff Brown9302c872011-07-13 22:51:29 -0700905 mInputTargetWaitApplicationHandle.clear();
Jeff Brownb88102f2010-09-08 11:49:43 -0700906 }
907 } else {
908 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
909#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +0000910 ALOGD("Waiting for application to become ready for input: %s",
Jeff Brown9302c872011-07-13 22:51:29 -0700911 getApplicationWindowLabelLocked(applicationHandle, windowHandle).string());
Jeff Brownb88102f2010-09-08 11:49:43 -0700912#endif
Jeff Browncc4f7db2011-08-30 20:34:48 -0700913 nsecs_t timeout;
914 if (windowHandle != NULL) {
915 timeout = windowHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
916 } else if (applicationHandle != NULL) {
917 timeout = applicationHandle->getDispatchingTimeout(
918 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
919 } else {
920 timeout = DEFAULT_INPUT_DISPATCHING_TIMEOUT;
921 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700922
923 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY;
924 mInputTargetWaitStartTime = currentTime;
925 mInputTargetWaitTimeoutTime = currentTime + timeout;
926 mInputTargetWaitTimeoutExpired = false;
Jeff Brown9302c872011-07-13 22:51:29 -0700927 mInputTargetWaitApplicationHandle.clear();
Jeff Brown928e0542011-01-10 11:17:36 -0800928
Jeff Brown9302c872011-07-13 22:51:29 -0700929 if (windowHandle != NULL) {
930 mInputTargetWaitApplicationHandle = windowHandle->inputApplicationHandle;
Jeff Brown928e0542011-01-10 11:17:36 -0800931 }
Jeff Brown9302c872011-07-13 22:51:29 -0700932 if (mInputTargetWaitApplicationHandle == NULL && applicationHandle != NULL) {
933 mInputTargetWaitApplicationHandle = applicationHandle;
Jeff Brown928e0542011-01-10 11:17:36 -0800934 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700935 }
936 }
937
938 if (mInputTargetWaitTimeoutExpired) {
939 return INPUT_EVENT_INJECTION_TIMED_OUT;
940 }
941
942 if (currentTime >= mInputTargetWaitTimeoutTime) {
Jeff Brown9302c872011-07-13 22:51:29 -0700943 onANRLocked(currentTime, applicationHandle, windowHandle,
944 entry->eventTime, mInputTargetWaitStartTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700945
946 // Force poll loop to wake up immediately on next iteration once we get the
947 // ANR response back from the policy.
948 *nextWakeupTime = LONG_LONG_MIN;
949 return INPUT_EVENT_INJECTION_PENDING;
950 } else {
951 // Force poll loop to wake up when timeout is due.
952 if (mInputTargetWaitTimeoutTime < *nextWakeupTime) {
953 *nextWakeupTime = mInputTargetWaitTimeoutTime;
954 }
955 return INPUT_EVENT_INJECTION_PENDING;
956 }
957}
958
Jeff Brown519e0242010-09-15 15:18:56 -0700959void InputDispatcher::resumeAfterTargetsNotReadyTimeoutLocked(nsecs_t newTimeout,
960 const sp<InputChannel>& inputChannel) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700961 if (newTimeout > 0) {
962 // Extend the timeout.
963 mInputTargetWaitTimeoutTime = now() + newTimeout;
964 } else {
965 // Give up.
966 mInputTargetWaitTimeoutExpired = true;
Jeff Brown519e0242010-09-15 15:18:56 -0700967
Jeff Brown01ce2e92010-09-26 22:20:12 -0700968 // Release the touch targets.
969 mTouchState.reset();
Jeff Brown2a95c2a2010-09-16 12:31:46 -0700970
Jeff Brown519e0242010-09-15 15:18:56 -0700971 // Input state will not be realistic. Mark it out of sync.
Jeff Browndc3e0052010-09-16 11:02:16 -0700972 if (inputChannel.get()) {
973 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
974 if (connectionIndex >= 0) {
Jeff Browncbee6d62012-02-03 20:11:27 -0800975 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
Jeff Brown00045a72010-12-09 18:10:30 -0800976 if (connection->status == Connection::STATUS_NORMAL) {
Jeff Brownda3d5a92011-03-29 15:11:34 -0700977 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
Jeff Brown00045a72010-12-09 18:10:30 -0800978 "application not responding");
Jeff Brownda3d5a92011-03-29 15:11:34 -0700979 synthesizeCancelationEventsForConnectionLocked(connection, options);
Jeff Brown00045a72010-12-09 18:10:30 -0800980 }
Jeff Browndc3e0052010-09-16 11:02:16 -0700981 }
Jeff Brown519e0242010-09-15 15:18:56 -0700982 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700983 }
984}
985
Jeff Brown519e0242010-09-15 15:18:56 -0700986nsecs_t InputDispatcher::getTimeSpentWaitingForApplicationLocked(
Jeff Brownb88102f2010-09-08 11:49:43 -0700987 nsecs_t currentTime) {
988 if (mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
989 return currentTime - mInputTargetWaitStartTime;
990 }
991 return 0;
992}
993
994void InputDispatcher::resetANRTimeoutsLocked() {
995#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +0000996 ALOGD("Resetting ANR timeouts.");
Jeff Brownb88102f2010-09-08 11:49:43 -0700997#endif
998
Jeff Brownb88102f2010-09-08 11:49:43 -0700999 // Reset input target wait timeout.
1000 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_NONE;
Jeff Brown5ea29ab2011-07-27 11:50:51 -07001001 mInputTargetWaitApplicationHandle.clear();
Jeff Brownb88102f2010-09-08 11:49:43 -07001002}
1003
Jeff Brown01ce2e92010-09-26 22:20:12 -07001004int32_t InputDispatcher::findFocusedWindowTargetsLocked(nsecs_t currentTime,
Jeff Browne9bb9be2012-02-06 15:47:55 -08001005 const EventEntry* entry, Vector<InputTarget>& inputTargets, nsecs_t* nextWakeupTime) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001006 int32_t injectionResult;
1007
1008 // If there is no currently focused window and no focused application
1009 // then drop the event.
Jeff Brown9302c872011-07-13 22:51:29 -07001010 if (mFocusedWindowHandle == NULL) {
1011 if (mFocusedApplicationHandle != NULL) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001012#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001013 ALOGD("Waiting because there is no focused window but there is a "
Jeff Brown519e0242010-09-15 15:18:56 -07001014 "focused application that may eventually add a window: %s.",
Jeff Brown9302c872011-07-13 22:51:29 -07001015 getApplicationWindowLabelLocked(mFocusedApplicationHandle, NULL).string());
Jeff Brownb88102f2010-09-08 11:49:43 -07001016#endif
1017 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brown9302c872011-07-13 22:51:29 -07001018 mFocusedApplicationHandle, NULL, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -07001019 goto Unresponsive;
1020 }
1021
Steve Block6215d3f2012-01-04 20:05:49 +00001022 ALOGI("Dropping event because there is no focused window or focused application.");
Jeff Brownb88102f2010-09-08 11:49:43 -07001023 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1024 goto Failed;
1025 }
1026
1027 // Check permissions.
Jeff Brown9302c872011-07-13 22:51:29 -07001028 if (! checkInjectionPermission(mFocusedWindowHandle, entry->injectionState)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001029 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1030 goto Failed;
1031 }
1032
1033 // If the currently focused window is paused then keep waiting.
Jeff Browncc4f7db2011-08-30 20:34:48 -07001034 if (mFocusedWindowHandle->getInfo()->paused) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001035#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001036 ALOGD("Waiting because focused window is paused.");
Jeff Brownb88102f2010-09-08 11:49:43 -07001037#endif
1038 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brown9302c872011-07-13 22:51:29 -07001039 mFocusedApplicationHandle, mFocusedWindowHandle, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -07001040 goto Unresponsive;
1041 }
1042
Jeff Brown519e0242010-09-15 15:18:56 -07001043 // If the currently focused window is still working on previous events then keep waiting.
Jeff Brown0952c302012-02-13 13:48:59 -08001044 if (!isWindowReadyForMoreInputLocked(currentTime, mFocusedWindowHandle, entry)) {
Jeff Brown519e0242010-09-15 15:18:56 -07001045#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001046 ALOGD("Waiting because focused window still processing previous input.");
Jeff Brown519e0242010-09-15 15:18:56 -07001047#endif
1048 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brown9302c872011-07-13 22:51:29 -07001049 mFocusedApplicationHandle, mFocusedWindowHandle, nextWakeupTime);
Jeff Brown519e0242010-09-15 15:18:56 -07001050 goto Unresponsive;
1051 }
1052
Jeff Brownb88102f2010-09-08 11:49:43 -07001053 // Success! Output targets.
1054 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
Jeff Brown9302c872011-07-13 22:51:29 -07001055 addWindowTargetLocked(mFocusedWindowHandle,
Jeff Browne9bb9be2012-02-06 15:47:55 -08001056 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS, BitSet32(0),
1057 inputTargets);
Jeff Brownb88102f2010-09-08 11:49:43 -07001058
1059 // Done.
1060Failed:
1061Unresponsive:
Jeff Brown519e0242010-09-15 15:18:56 -07001062 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
1063 updateDispatchStatisticsLocked(currentTime, entry,
1064 injectionResult, timeSpentWaitingForApplication);
Jeff Brownb88102f2010-09-08 11:49:43 -07001065#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001066 ALOGD("findFocusedWindow finished: injectionResult=%d, "
Jeff Brown519e0242010-09-15 15:18:56 -07001067 "timeSpendWaitingForApplication=%0.1fms",
1068 injectionResult, timeSpentWaitingForApplication / 1000000.0);
Jeff Brownb88102f2010-09-08 11:49:43 -07001069#endif
1070 return injectionResult;
1071}
1072
Jeff Brown01ce2e92010-09-26 22:20:12 -07001073int32_t InputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime,
Jeff Browne9bb9be2012-02-06 15:47:55 -08001074 const MotionEntry* entry, Vector<InputTarget>& inputTargets, nsecs_t* nextWakeupTime,
1075 bool* outConflictingPointerActions) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001076 enum InjectionPermission {
1077 INJECTION_PERMISSION_UNKNOWN,
1078 INJECTION_PERMISSION_GRANTED,
1079 INJECTION_PERMISSION_DENIED
1080 };
1081
Jeff Brownb88102f2010-09-08 11:49:43 -07001082 nsecs_t startTime = now();
1083
1084 // For security reasons, we defer updating the touch state until we are sure that
1085 // event injection will be allowed.
1086 //
1087 // FIXME In the original code, screenWasOff could never be set to true.
1088 // The reason is that the POLICY_FLAG_WOKE_HERE
1089 // and POLICY_FLAG_BRIGHT_HERE flags were set only when preprocessing raw
1090 // EV_KEY, EV_REL and EV_ABS events. As it happens, the touch event was
1091 // actually enqueued using the policyFlags that appeared in the final EV_SYN
1092 // events upon which no preprocessing took place. So policyFlags was always 0.
1093 // In the new native input dispatcher we're a bit more careful about event
1094 // preprocessing so the touches we receive can actually have non-zero policyFlags.
1095 // Unfortunately we obtain undesirable behavior.
1096 //
1097 // Here's what happens:
1098 //
1099 // When the device dims in anticipation of going to sleep, touches
1100 // in windows which have FLAG_TOUCHABLE_WHEN_WAKING cause
1101 // the device to brighten and reset the user activity timer.
1102 // Touches on other windows (such as the launcher window)
1103 // are dropped. Then after a moment, the device goes to sleep. Oops.
1104 //
1105 // Also notice how screenWasOff was being initialized using POLICY_FLAG_BRIGHT_HERE
1106 // instead of POLICY_FLAG_WOKE_HERE...
1107 //
1108 bool screenWasOff = false; // original policy: policyFlags & POLICY_FLAG_BRIGHT_HERE;
1109
1110 int32_t action = entry->action;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001111 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Jeff Brownb88102f2010-09-08 11:49:43 -07001112
1113 // Update the touch state as needed based on the properties of the touch event.
Jeff Brown01ce2e92010-09-26 22:20:12 -07001114 int32_t injectionResult = INPUT_EVENT_INJECTION_PENDING;
1115 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
Jeff Brown9302c872011-07-13 22:51:29 -07001116 sp<InputWindowHandle> newHoverWindowHandle;
Jeff Browncc0c1592011-02-19 05:07:28 -08001117
1118 bool isSplit = mTouchState.split;
Jeff Brown2717eff2011-06-30 23:53:07 -07001119 bool switchedDevice = mTouchState.deviceId >= 0
1120 && (mTouchState.deviceId != entry->deviceId
1121 || mTouchState.source != entry->source);
Jeff Browna032cc02011-03-07 16:56:21 -08001122 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE
1123 || maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER
1124 || maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1125 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN
1126 || maskedAction == AMOTION_EVENT_ACTION_SCROLL
1127 || isHoverAction);
Jeff Brown81346812011-06-28 20:08:48 -07001128 bool wrongDevice = false;
Jeff Browna032cc02011-03-07 16:56:21 -08001129 if (newGesture) {
Jeff Browncc0c1592011-02-19 05:07:28 -08001130 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Jeff Brown81346812011-06-28 20:08:48 -07001131 if (switchedDevice && mTouchState.down && !down) {
1132#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001133 ALOGD("Dropping event because a pointer for a different device is already down.");
Jeff Brown81346812011-06-28 20:08:48 -07001134#endif
Jeff Browncc0c1592011-02-19 05:07:28 -08001135 mTempTouchState.copyFrom(mTouchState);
Jeff Brown81346812011-06-28 20:08:48 -07001136 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1137 switchedDevice = false;
1138 wrongDevice = true;
1139 goto Failed;
Jeff Browncc0c1592011-02-19 05:07:28 -08001140 }
Jeff Brown81346812011-06-28 20:08:48 -07001141 mTempTouchState.reset();
1142 mTempTouchState.down = down;
1143 mTempTouchState.deviceId = entry->deviceId;
1144 mTempTouchState.source = entry->source;
1145 isSplit = false;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001146 } else {
1147 mTempTouchState.copyFrom(mTouchState);
Jeff Browncc0c1592011-02-19 05:07:28 -08001148 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001149
Jeff Browna032cc02011-03-07 16:56:21 -08001150 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
Jeff Brown33bbfd22011-02-24 20:55:35 -08001151 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
Jeff Brownb88102f2010-09-08 11:49:43 -07001152
Jeff Brown01ce2e92010-09-26 22:20:12 -07001153 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Jeff Brown3241b6b2012-02-03 15:08:02 -08001154 int32_t x = int32_t(entry->pointerCoords[pointerIndex].
Jeff Brownebbd5d12011-02-17 13:01:34 -08001155 getAxisValue(AMOTION_EVENT_AXIS_X));
Jeff Brown3241b6b2012-02-03 15:08:02 -08001156 int32_t y = int32_t(entry->pointerCoords[pointerIndex].
Jeff Brownebbd5d12011-02-17 13:01:34 -08001157 getAxisValue(AMOTION_EVENT_AXIS_Y));
Jeff Brown9302c872011-07-13 22:51:29 -07001158 sp<InputWindowHandle> newTouchedWindowHandle;
1159 sp<InputWindowHandle> topErrorWindowHandle;
Jeff Browna032cc02011-03-07 16:56:21 -08001160 bool isTouchModal = false;
Jeff Brownb88102f2010-09-08 11:49:43 -07001161
1162 // Traverse windows from front to back to find touched window and outside targets.
Jeff Brown9302c872011-07-13 22:51:29 -07001163 size_t numWindows = mWindowHandles.size();
Jeff Brownb88102f2010-09-08 11:49:43 -07001164 for (size_t i = 0; i < numWindows; i++) {
Jeff Brown9302c872011-07-13 22:51:29 -07001165 sp<InputWindowHandle> windowHandle = mWindowHandles.itemAt(i);
Jeff Browncc4f7db2011-08-30 20:34:48 -07001166 const InputWindowInfo* windowInfo = windowHandle->getInfo();
1167 int32_t flags = windowInfo->layoutParamsFlags;
Jeff Brownb88102f2010-09-08 11:49:43 -07001168
Jeff Browncc4f7db2011-08-30 20:34:48 -07001169 if (flags & InputWindowInfo::FLAG_SYSTEM_ERROR) {
Jeff Brown9302c872011-07-13 22:51:29 -07001170 if (topErrorWindowHandle == NULL) {
1171 topErrorWindowHandle = windowHandle;
Jeff Brownb88102f2010-09-08 11:49:43 -07001172 }
1173 }
1174
Jeff Browncc4f7db2011-08-30 20:34:48 -07001175 if (windowInfo->visible) {
1176 if (! (flags & InputWindowInfo::FLAG_NOT_TOUCHABLE)) {
1177 isTouchModal = (flags & (InputWindowInfo::FLAG_NOT_FOCUSABLE
1178 | InputWindowInfo::FLAG_NOT_TOUCH_MODAL)) == 0;
1179 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
Jeff Brown9302c872011-07-13 22:51:29 -07001180 if (! screenWasOff
Jeff Browncc4f7db2011-08-30 20:34:48 -07001181 || (flags & InputWindowInfo::FLAG_TOUCHABLE_WHEN_WAKING)) {
Jeff Brown9302c872011-07-13 22:51:29 -07001182 newTouchedWindowHandle = windowHandle;
Jeff Brownb88102f2010-09-08 11:49:43 -07001183 }
1184 break; // found touched window, exit window loop
1185 }
1186 }
1187
Jeff Brown01ce2e92010-09-26 22:20:12 -07001188 if (maskedAction == AMOTION_EVENT_ACTION_DOWN
Jeff Browncc4f7db2011-08-30 20:34:48 -07001189 && (flags & InputWindowInfo::FLAG_WATCH_OUTSIDE_TOUCH)) {
Jeff Browna032cc02011-03-07 16:56:21 -08001190 int32_t outsideTargetFlags = InputTarget::FLAG_DISPATCH_AS_OUTSIDE;
Jeff Brown9302c872011-07-13 22:51:29 -07001191 if (isWindowObscuredAtPointLocked(windowHandle, x, y)) {
Jeff Brown19dfc832010-10-05 12:26:23 -07001192 outsideTargetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1193 }
1194
Jeff Brown9302c872011-07-13 22:51:29 -07001195 mTempTouchState.addOrUpdateWindow(
1196 windowHandle, outsideTargetFlags, BitSet32(0));
Jeff Brownb88102f2010-09-08 11:49:43 -07001197 }
1198 }
1199 }
1200
1201 // If there is an error window but it is not taking focus (typically because
1202 // it is invisible) then wait for it. Any other focused window may in
1203 // fact be in ANR state.
Jeff Brown9302c872011-07-13 22:51:29 -07001204 if (topErrorWindowHandle != NULL && newTouchedWindowHandle != topErrorWindowHandle) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001205#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001206 ALOGD("Waiting because system error window is pending.");
Jeff Brownb88102f2010-09-08 11:49:43 -07001207#endif
1208 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
1209 NULL, NULL, nextWakeupTime);
1210 injectionPermission = INJECTION_PERMISSION_UNKNOWN;
1211 goto Unresponsive;
1212 }
1213
Jeff Brown01ce2e92010-09-26 22:20:12 -07001214 // Figure out whether splitting will be allowed for this window.
Jeff Browncc4f7db2011-08-30 20:34:48 -07001215 if (newTouchedWindowHandle != NULL
1216 && newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001217 // New window supports splitting.
1218 isSplit = true;
1219 } else if (isSplit) {
1220 // New window does not support splitting but we have already split events.
1221 // Assign the pointer to the first foreground window we find.
1222 // (May be NULL which is why we put this code block before the next check.)
Jeff Brown9302c872011-07-13 22:51:29 -07001223 newTouchedWindowHandle = mTempTouchState.getFirstForegroundWindowHandle();
Jeff Brown01ce2e92010-09-26 22:20:12 -07001224 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001225
Jeff Brownb88102f2010-09-08 11:49:43 -07001226 // If we did not find a touched window then fail.
Jeff Brown9302c872011-07-13 22:51:29 -07001227 if (newTouchedWindowHandle == NULL) {
1228 if (mFocusedApplicationHandle != NULL) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001229#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001230 ALOGD("Waiting because there is no touched window but there is a "
Jeff Brown519e0242010-09-15 15:18:56 -07001231 "focused application that may eventually add a new window: %s.",
Jeff Brown9302c872011-07-13 22:51:29 -07001232 getApplicationWindowLabelLocked(mFocusedApplicationHandle, NULL).string());
Jeff Brownb88102f2010-09-08 11:49:43 -07001233#endif
1234 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brown9302c872011-07-13 22:51:29 -07001235 mFocusedApplicationHandle, NULL, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -07001236 goto Unresponsive;
1237 }
1238
Steve Block6215d3f2012-01-04 20:05:49 +00001239 ALOGI("Dropping event because there is no touched window or focused application.");
Jeff Brownb88102f2010-09-08 11:49:43 -07001240 injectionResult = INPUT_EVENT_INJECTION_FAILED;
Jeff Brownb88102f2010-09-08 11:49:43 -07001241 goto Failed;
1242 }
1243
Jeff Brown19dfc832010-10-05 12:26:23 -07001244 // Set target flags.
Jeff Browna032cc02011-03-07 16:56:21 -08001245 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
Jeff Brown19dfc832010-10-05 12:26:23 -07001246 if (isSplit) {
1247 targetFlags |= InputTarget::FLAG_SPLIT;
1248 }
Jeff Brown9302c872011-07-13 22:51:29 -07001249 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
Jeff Brown19dfc832010-10-05 12:26:23 -07001250 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1251 }
1252
Jeff Browna032cc02011-03-07 16:56:21 -08001253 // Update hover state.
1254 if (isHoverAction) {
Jeff Brown9302c872011-07-13 22:51:29 -07001255 newHoverWindowHandle = newTouchedWindowHandle;
Jeff Browna032cc02011-03-07 16:56:21 -08001256 } else if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
Jeff Brown9302c872011-07-13 22:51:29 -07001257 newHoverWindowHandle = mLastHoverWindowHandle;
Jeff Browna032cc02011-03-07 16:56:21 -08001258 }
1259
Jeff Brown01ce2e92010-09-26 22:20:12 -07001260 // Update the temporary touch state.
1261 BitSet32 pointerIds;
1262 if (isSplit) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07001263 uint32_t pointerId = entry->pointerProperties[pointerIndex].id;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001264 pointerIds.markBit(pointerId);
Jeff Brownb88102f2010-09-08 11:49:43 -07001265 }
Jeff Brown9302c872011-07-13 22:51:29 -07001266 mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Jeff Brownb88102f2010-09-08 11:49:43 -07001267 } else {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001268 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
Jeff Brownb88102f2010-09-08 11:49:43 -07001269
1270 // If the pointer is not currently down, then ignore the event.
Jeff Brown01ce2e92010-09-26 22:20:12 -07001271 if (! mTempTouchState.down) {
Jeff Browna2cc28d2011-03-25 11:58:46 -07001272#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001273 ALOGD("Dropping event because the pointer is not down or we previously "
Jeff Brown76860e32010-10-25 17:37:46 -07001274 "dropped the pointer down event.");
1275#endif
Jeff Brownb88102f2010-09-08 11:49:43 -07001276 injectionResult = INPUT_EVENT_INJECTION_FAILED;
Jeff Brownb88102f2010-09-08 11:49:43 -07001277 goto Failed;
1278 }
Jeff Brown98db5fa2011-06-08 15:37:10 -07001279
1280 // Check whether touches should slip outside of the current foreground window.
1281 if (maskedAction == AMOTION_EVENT_ACTION_MOVE
1282 && entry->pointerCount == 1
1283 && mTempTouchState.isSlippery()) {
Jeff Brown3241b6b2012-02-03 15:08:02 -08001284 int32_t x = int32_t(entry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
1285 int32_t y = int32_t(entry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Jeff Brown98db5fa2011-06-08 15:37:10 -07001286
Jeff Brown9302c872011-07-13 22:51:29 -07001287 sp<InputWindowHandle> oldTouchedWindowHandle =
1288 mTempTouchState.getFirstForegroundWindowHandle();
1289 sp<InputWindowHandle> newTouchedWindowHandle = findTouchedWindowAtLocked(x, y);
1290 if (oldTouchedWindowHandle != newTouchedWindowHandle
1291 && newTouchedWindowHandle != NULL) {
Jeff Brown98db5fa2011-06-08 15:37:10 -07001292#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001293 ALOGD("Touch is slipping out of window %s into window %s.",
Jeff Browncc4f7db2011-08-30 20:34:48 -07001294 oldTouchedWindowHandle->getName().string(),
1295 newTouchedWindowHandle->getName().string());
Jeff Brown98db5fa2011-06-08 15:37:10 -07001296#endif
1297 // Make a slippery exit from the old window.
Jeff Brown9302c872011-07-13 22:51:29 -07001298 mTempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
Jeff Brown98db5fa2011-06-08 15:37:10 -07001299 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT, BitSet32(0));
1300
1301 // Make a slippery entrance into the new window.
Jeff Browncc4f7db2011-08-30 20:34:48 -07001302 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Jeff Brown98db5fa2011-06-08 15:37:10 -07001303 isSplit = true;
1304 }
1305
1306 int32_t targetFlags = InputTarget::FLAG_FOREGROUND
1307 | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
1308 if (isSplit) {
1309 targetFlags |= InputTarget::FLAG_SPLIT;
1310 }
Jeff Brown9302c872011-07-13 22:51:29 -07001311 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
Jeff Brown98db5fa2011-06-08 15:37:10 -07001312 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1313 }
1314
1315 BitSet32 pointerIds;
1316 if (isSplit) {
1317 pointerIds.markBit(entry->pointerProperties[0].id);
1318 }
Jeff Brown9302c872011-07-13 22:51:29 -07001319 mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Jeff Brown98db5fa2011-06-08 15:37:10 -07001320 }
1321 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001322 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001323
Jeff Brown9302c872011-07-13 22:51:29 -07001324 if (newHoverWindowHandle != mLastHoverWindowHandle) {
Jeff Browna032cc02011-03-07 16:56:21 -08001325 // Let the previous window know that the hover sequence is over.
Jeff Brown9302c872011-07-13 22:51:29 -07001326 if (mLastHoverWindowHandle != NULL) {
Jeff Browna032cc02011-03-07 16:56:21 -08001327#if DEBUG_HOVER
Steve Block5baa3a62011-12-20 16:23:08 +00001328 ALOGD("Sending hover exit event to window %s.",
Jeff Browncc4f7db2011-08-30 20:34:48 -07001329 mLastHoverWindowHandle->getName().string());
Jeff Browna032cc02011-03-07 16:56:21 -08001330#endif
Jeff Brown9302c872011-07-13 22:51:29 -07001331 mTempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
Jeff Browna032cc02011-03-07 16:56:21 -08001332 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
1333 }
1334
1335 // Let the new window know that the hover sequence is starting.
Jeff Brown9302c872011-07-13 22:51:29 -07001336 if (newHoverWindowHandle != NULL) {
Jeff Browna032cc02011-03-07 16:56:21 -08001337#if DEBUG_HOVER
Steve Block5baa3a62011-12-20 16:23:08 +00001338 ALOGD("Sending hover enter event to window %s.",
Jeff Browncc4f7db2011-08-30 20:34:48 -07001339 newHoverWindowHandle->getName().string());
Jeff Browna032cc02011-03-07 16:56:21 -08001340#endif
Jeff Brown9302c872011-07-13 22:51:29 -07001341 mTempTouchState.addOrUpdateWindow(newHoverWindowHandle,
Jeff Browna032cc02011-03-07 16:56:21 -08001342 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER, BitSet32(0));
1343 }
1344 }
1345
Jeff Brown01ce2e92010-09-26 22:20:12 -07001346 // Check permission to inject into all touched foreground windows and ensure there
1347 // is at least one touched foreground window.
1348 {
1349 bool haveForegroundWindow = false;
1350 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1351 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1352 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1353 haveForegroundWindow = true;
Jeff Brown9302c872011-07-13 22:51:29 -07001354 if (! checkInjectionPermission(touchedWindow.windowHandle,
1355 entry->injectionState)) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001356 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1357 injectionPermission = INJECTION_PERMISSION_DENIED;
1358 goto Failed;
1359 }
1360 }
1361 }
1362 if (! haveForegroundWindow) {
Jeff Browna2cc28d2011-03-25 11:58:46 -07001363#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001364 ALOGD("Dropping event because there is no touched foreground window to receive it.");
Jeff Brownb88102f2010-09-08 11:49:43 -07001365#endif
1366 injectionResult = INPUT_EVENT_INJECTION_FAILED;
Jeff Brownb88102f2010-09-08 11:49:43 -07001367 goto Failed;
1368 }
1369
Jeff Brown01ce2e92010-09-26 22:20:12 -07001370 // Permission granted to injection into all touched foreground windows.
1371 injectionPermission = INJECTION_PERMISSION_GRANTED;
1372 }
Jeff Brown519e0242010-09-15 15:18:56 -07001373
Kenny Root7a9db182011-06-02 15:16:05 -07001374 // Check whether windows listening for outside touches are owned by the same UID. If it is
1375 // set the policy flag that we will not reveal coordinate information to this window.
1376 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
Jeff Brown9302c872011-07-13 22:51:29 -07001377 sp<InputWindowHandle> foregroundWindowHandle =
1378 mTempTouchState.getFirstForegroundWindowHandle();
Jeff Browncc4f7db2011-08-30 20:34:48 -07001379 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Kenny Root7a9db182011-06-02 15:16:05 -07001380 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1381 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1382 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
Jeff Brown9302c872011-07-13 22:51:29 -07001383 sp<InputWindowHandle> inputWindowHandle = touchedWindow.windowHandle;
Jeff Browncc4f7db2011-08-30 20:34:48 -07001384 if (inputWindowHandle->getInfo()->ownerUid != foregroundWindowUid) {
Jeff Brown9302c872011-07-13 22:51:29 -07001385 mTempTouchState.addOrUpdateWindow(inputWindowHandle,
Kenny Root7a9db182011-06-02 15:16:05 -07001386 InputTarget::FLAG_ZERO_COORDS, BitSet32(0));
1387 }
1388 }
1389 }
1390 }
1391
Jeff Brown01ce2e92010-09-26 22:20:12 -07001392 // Ensure all touched foreground windows are ready for new input.
1393 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1394 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1395 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1396 // If the touched window is paused then keep waiting.
Jeff Browncc4f7db2011-08-30 20:34:48 -07001397 if (touchedWindow.windowHandle->getInfo()->paused) {
Jeff Browna2cc28d2011-03-25 11:58:46 -07001398#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001399 ALOGD("Waiting because touched window is paused.");
Jeff Brown519e0242010-09-15 15:18:56 -07001400#endif
Jeff Brown01ce2e92010-09-26 22:20:12 -07001401 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brown9302c872011-07-13 22:51:29 -07001402 NULL, touchedWindow.windowHandle, nextWakeupTime);
Jeff Brown01ce2e92010-09-26 22:20:12 -07001403 goto Unresponsive;
1404 }
1405
1406 // If the touched window is still working on previous events then keep waiting.
Jeff Brown0952c302012-02-13 13:48:59 -08001407 if (!isWindowReadyForMoreInputLocked(currentTime, touchedWindow.windowHandle, entry)) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001408#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001409 ALOGD("Waiting because touched window still processing previous input.");
Jeff Brown01ce2e92010-09-26 22:20:12 -07001410#endif
1411 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brown9302c872011-07-13 22:51:29 -07001412 NULL, touchedWindow.windowHandle, nextWakeupTime);
Jeff Brown01ce2e92010-09-26 22:20:12 -07001413 goto Unresponsive;
1414 }
1415 }
1416 }
1417
1418 // If this is the first pointer going down and the touched window has a wallpaper
1419 // then also add the touched wallpaper windows so they are locked in for the duration
1420 // of the touch gesture.
Jeff Brown33bbfd22011-02-24 20:55:35 -08001421 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
1422 // engine only supports touch events. We would need to add a mechanism similar
1423 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
1424 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
Jeff Brown9302c872011-07-13 22:51:29 -07001425 sp<InputWindowHandle> foregroundWindowHandle =
1426 mTempTouchState.getFirstForegroundWindowHandle();
Jeff Browncc4f7db2011-08-30 20:34:48 -07001427 if (foregroundWindowHandle->getInfo()->hasWallpaper) {
Jeff Brown9302c872011-07-13 22:51:29 -07001428 for (size_t i = 0; i < mWindowHandles.size(); i++) {
1429 sp<InputWindowHandle> windowHandle = mWindowHandles.itemAt(i);
Jeff Browncc4f7db2011-08-30 20:34:48 -07001430 if (windowHandle->getInfo()->layoutParamsType
1431 == InputWindowInfo::TYPE_WALLPAPER) {
Jeff Brown9302c872011-07-13 22:51:29 -07001432 mTempTouchState.addOrUpdateWindow(windowHandle,
Jeff Browna032cc02011-03-07 16:56:21 -08001433 InputTarget::FLAG_WINDOW_IS_OBSCURED
1434 | InputTarget::FLAG_DISPATCH_AS_IS,
1435 BitSet32(0));
Jeff Brown01ce2e92010-09-26 22:20:12 -07001436 }
1437 }
1438 }
1439 }
1440
Jeff Brownb88102f2010-09-08 11:49:43 -07001441 // Success! Output targets.
1442 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
Jeff Brownb88102f2010-09-08 11:49:43 -07001443
Jeff Brown01ce2e92010-09-26 22:20:12 -07001444 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1445 const TouchedWindow& touchedWindow = mTempTouchState.windows.itemAt(i);
Jeff Brown9302c872011-07-13 22:51:29 -07001446 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Jeff Browne9bb9be2012-02-06 15:47:55 -08001447 touchedWindow.pointerIds, inputTargets);
Jeff Brownb88102f2010-09-08 11:49:43 -07001448 }
1449
Jeff Browna032cc02011-03-07 16:56:21 -08001450 // Drop the outside or hover touch windows since we will not care about them
1451 // in the next iteration.
1452 mTempTouchState.filterNonAsIsTouchWindows();
Jeff Brown01ce2e92010-09-26 22:20:12 -07001453
Jeff Brownb88102f2010-09-08 11:49:43 -07001454Failed:
1455 // Check injection permission once and for all.
1456 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001457 if (checkInjectionPermission(NULL, entry->injectionState)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001458 injectionPermission = INJECTION_PERMISSION_GRANTED;
1459 } else {
1460 injectionPermission = INJECTION_PERMISSION_DENIED;
1461 }
1462 }
1463
1464 // Update final pieces of touch state if the injector had permission.
1465 if (injectionPermission == INJECTION_PERMISSION_GRANTED) {
Jeff Brown95712852011-01-04 19:41:59 -08001466 if (!wrongDevice) {
Jeff Brown81346812011-06-28 20:08:48 -07001467 if (switchedDevice) {
1468#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001469 ALOGD("Conflicting pointer actions: Switched to a different device.");
Jeff Brown81346812011-06-28 20:08:48 -07001470#endif
1471 *outConflictingPointerActions = true;
1472 }
1473
1474 if (isHoverAction) {
1475 // Started hovering, therefore no longer down.
1476 if (mTouchState.down) {
1477#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001478 ALOGD("Conflicting pointer actions: Hover received while pointer was down.");
Jeff Brown81346812011-06-28 20:08:48 -07001479#endif
1480 *outConflictingPointerActions = true;
1481 }
1482 mTouchState.reset();
1483 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER
1484 || maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
1485 mTouchState.deviceId = entry->deviceId;
1486 mTouchState.source = entry->source;
1487 }
1488 } else if (maskedAction == AMOTION_EVENT_ACTION_UP
1489 || maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Jeff Brown95712852011-01-04 19:41:59 -08001490 // All pointers up or canceled.
Jeff Brown33bbfd22011-02-24 20:55:35 -08001491 mTouchState.reset();
Jeff Brown95712852011-01-04 19:41:59 -08001492 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1493 // First pointer went down.
1494 if (mTouchState.down) {
Jeff Brownb6997262010-10-08 22:31:17 -07001495#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001496 ALOGD("Conflicting pointer actions: Down received while already down.");
Jeff Brownb6997262010-10-08 22:31:17 -07001497#endif
Jeff Brown81346812011-06-28 20:08:48 -07001498 *outConflictingPointerActions = true;
Jeff Brown95712852011-01-04 19:41:59 -08001499 }
Jeff Brown33bbfd22011-02-24 20:55:35 -08001500 mTouchState.copyFrom(mTempTouchState);
Jeff Brown95712852011-01-04 19:41:59 -08001501 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
1502 // One pointer went up.
1503 if (isSplit) {
1504 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07001505 uint32_t pointerId = entry->pointerProperties[pointerIndex].id;
Jeff Brownb88102f2010-09-08 11:49:43 -07001506
Jeff Brown95712852011-01-04 19:41:59 -08001507 for (size_t i = 0; i < mTempTouchState.windows.size(); ) {
1508 TouchedWindow& touchedWindow = mTempTouchState.windows.editItemAt(i);
1509 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
1510 touchedWindow.pointerIds.clearBit(pointerId);
1511 if (touchedWindow.pointerIds.isEmpty()) {
1512 mTempTouchState.windows.removeAt(i);
1513 continue;
1514 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001515 }
Jeff Brown95712852011-01-04 19:41:59 -08001516 i += 1;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001517 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001518 }
Jeff Brown33bbfd22011-02-24 20:55:35 -08001519 mTouchState.copyFrom(mTempTouchState);
1520 } else if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
1521 // Discard temporary touch state since it was only valid for this action.
1522 } else {
1523 // Save changes to touch state as-is for all other actions.
1524 mTouchState.copyFrom(mTempTouchState);
Jeff Brownb88102f2010-09-08 11:49:43 -07001525 }
Jeff Browna032cc02011-03-07 16:56:21 -08001526
1527 // Update hover state.
Jeff Brown9302c872011-07-13 22:51:29 -07001528 mLastHoverWindowHandle = newHoverWindowHandle;
Jeff Brown95712852011-01-04 19:41:59 -08001529 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001530 } else {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001531#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001532 ALOGD("Not updating touch focus because injection was denied.");
Jeff Brown01ce2e92010-09-26 22:20:12 -07001533#endif
Jeff Brownb88102f2010-09-08 11:49:43 -07001534 }
1535
1536Unresponsive:
Jeff Brown120a4592010-10-27 18:43:51 -07001537 // Reset temporary touch state to ensure we release unnecessary references to input channels.
1538 mTempTouchState.reset();
1539
Jeff Brown519e0242010-09-15 15:18:56 -07001540 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
1541 updateDispatchStatisticsLocked(currentTime, entry,
1542 injectionResult, timeSpentWaitingForApplication);
Jeff Brownb88102f2010-09-08 11:49:43 -07001543#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001544 ALOGD("findTouchedWindow finished: injectionResult=%d, injectionPermission=%d, "
Jeff Brown01ce2e92010-09-26 22:20:12 -07001545 "timeSpentWaitingForApplication=%0.1fms",
Jeff Brown519e0242010-09-15 15:18:56 -07001546 injectionResult, injectionPermission, timeSpentWaitingForApplication / 1000000.0);
Jeff Brownb88102f2010-09-08 11:49:43 -07001547#endif
1548 return injectionResult;
1549}
1550
Jeff Brown9302c872011-07-13 22:51:29 -07001551void InputDispatcher::addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
Jeff Browne9bb9be2012-02-06 15:47:55 -08001552 int32_t targetFlags, BitSet32 pointerIds, Vector<InputTarget>& inputTargets) {
1553 inputTargets.push();
Jeff Brownb88102f2010-09-08 11:49:43 -07001554
Jeff Browncc4f7db2011-08-30 20:34:48 -07001555 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Jeff Browne9bb9be2012-02-06 15:47:55 -08001556 InputTarget& target = inputTargets.editTop();
Jeff Browncc4f7db2011-08-30 20:34:48 -07001557 target.inputChannel = windowInfo->inputChannel;
Jeff Brownb88102f2010-09-08 11:49:43 -07001558 target.flags = targetFlags;
Jeff Browncc4f7db2011-08-30 20:34:48 -07001559 target.xOffset = - windowInfo->frameLeft;
1560 target.yOffset = - windowInfo->frameTop;
1561 target.scaleFactor = windowInfo->scaleFactor;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001562 target.pointerIds = pointerIds;
Jeff Brownb88102f2010-09-08 11:49:43 -07001563}
1564
Jeff Browne9bb9be2012-02-06 15:47:55 -08001565void InputDispatcher::addMonitoringTargetsLocked(Vector<InputTarget>& inputTargets) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001566 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
Jeff Browne9bb9be2012-02-06 15:47:55 -08001567 inputTargets.push();
Jeff Brownb88102f2010-09-08 11:49:43 -07001568
Jeff Browne9bb9be2012-02-06 15:47:55 -08001569 InputTarget& target = inputTargets.editTop();
Jeff Brownb88102f2010-09-08 11:49:43 -07001570 target.inputChannel = mMonitoringChannels[i];
Jeff Brownb6110c22011-04-01 16:15:13 -07001571 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
Jeff Brownb88102f2010-09-08 11:49:43 -07001572 target.xOffset = 0;
1573 target.yOffset = 0;
Jeff Brownb6110c22011-04-01 16:15:13 -07001574 target.pointerIds.clear();
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001575 target.scaleFactor = 1.0f;
Jeff Brownb88102f2010-09-08 11:49:43 -07001576 }
1577}
1578
Jeff Brown9302c872011-07-13 22:51:29 -07001579bool InputDispatcher::checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
Jeff Brown01ce2e92010-09-26 22:20:12 -07001580 const InjectionState* injectionState) {
1581 if (injectionState
Jeff Browncc4f7db2011-08-30 20:34:48 -07001582 && (windowHandle == NULL
1583 || windowHandle->getInfo()->ownerUid != injectionState->injectorUid)
Jeff Brownb6997262010-10-08 22:31:17 -07001584 && !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Jeff Brown9302c872011-07-13 22:51:29 -07001585 if (windowHandle != NULL) {
Steve Block8564c8d2012-01-05 23:22:43 +00001586 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
Jeff Brown9302c872011-07-13 22:51:29 -07001587 "owned by uid %d",
Jeff Brownb6997262010-10-08 22:31:17 -07001588 injectionState->injectorPid, injectionState->injectorUid,
Jeff Browncc4f7db2011-08-30 20:34:48 -07001589 windowHandle->getName().string(),
1590 windowHandle->getInfo()->ownerUid);
Jeff Brownb6997262010-10-08 22:31:17 -07001591 } else {
Steve Block8564c8d2012-01-05 23:22:43 +00001592 ALOGW("Permission denied: injecting event from pid %d uid %d",
Jeff Brownb6997262010-10-08 22:31:17 -07001593 injectionState->injectorPid, injectionState->injectorUid);
Jeff Brownb88102f2010-09-08 11:49:43 -07001594 }
Jeff Brownb6997262010-10-08 22:31:17 -07001595 return false;
Jeff Brownb88102f2010-09-08 11:49:43 -07001596 }
1597 return true;
1598}
1599
Jeff Brown19dfc832010-10-05 12:26:23 -07001600bool InputDispatcher::isWindowObscuredAtPointLocked(
Jeff Brown9302c872011-07-13 22:51:29 -07001601 const sp<InputWindowHandle>& windowHandle, int32_t x, int32_t y) const {
1602 size_t numWindows = mWindowHandles.size();
Jeff Brownb88102f2010-09-08 11:49:43 -07001603 for (size_t i = 0; i < numWindows; i++) {
Jeff Brown9302c872011-07-13 22:51:29 -07001604 sp<InputWindowHandle> otherHandle = mWindowHandles.itemAt(i);
1605 if (otherHandle == windowHandle) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001606 break;
1607 }
Jeff Browncc4f7db2011-08-30 20:34:48 -07001608
1609 const InputWindowInfo* otherInfo = otherHandle->getInfo();
1610 if (otherInfo->visible && ! otherInfo->isTrustedOverlay()
1611 && otherInfo->frameContainsPoint(x, y)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001612 return true;
1613 }
1614 }
1615 return false;
1616}
1617
Jeff Brownd1c48a02012-02-06 19:12:47 -08001618bool InputDispatcher::isWindowReadyForMoreInputLocked(nsecs_t currentTime,
Jeff Brown0952c302012-02-13 13:48:59 -08001619 const sp<InputWindowHandle>& windowHandle, const EventEntry* eventEntry) {
Jeff Browncc4f7db2011-08-30 20:34:48 -07001620 ssize_t connectionIndex = getConnectionIndexLocked(windowHandle->getInputChannel());
Jeff Brown519e0242010-09-15 15:18:56 -07001621 if (connectionIndex >= 0) {
Jeff Browncbee6d62012-02-03 20:11:27 -08001622 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
Jeff Brownd1c48a02012-02-06 19:12:47 -08001623 if (connection->inputPublisherBlocked) {
1624 return false;
1625 }
Jeff Brown0952c302012-02-13 13:48:59 -08001626 if (eventEntry->type == EventEntry::TYPE_KEY) {
1627 // If the event is a key event, then we must wait for all previous events to
1628 // complete before delivering it because previous events may have the
1629 // side-effect of transferring focus to a different window and we want to
1630 // ensure that the following keys are sent to the new window.
1631 //
1632 // Suppose the user touches a button in a window then immediately presses "A".
1633 // If the button causes a pop-up window to appear then we want to ensure that
1634 // the "A" key is delivered to the new pop-up window. This is because users
1635 // often anticipate pending UI changes when typing on a keyboard.
1636 // To obtain this behavior, we must serialize key events with respect to all
1637 // prior input events.
Jeff Brownd1c48a02012-02-06 19:12:47 -08001638 return connection->outboundQueue.isEmpty()
1639 && connection->waitQueue.isEmpty();
1640 }
Jeff Brown0952c302012-02-13 13:48:59 -08001641 // Touch events can always be sent to a window immediately because the user intended
1642 // to touch whatever was visible at the time. Even if focus changes or a new
1643 // window appears moments later, the touch event was meant to be delivered to
1644 // whatever window happened to be on screen at the time.
1645 //
1646 // Generic motion events, such as trackball or joystick events are a little trickier.
1647 // Like key events, generic motion events are delivered to the focused window.
1648 // Unlike key events, generic motion events don't tend to transfer focus to other
1649 // windows and it is not important for them to be serialized. So we prefer to deliver
1650 // generic motion events as soon as possible to improve efficiency and reduce lag
1651 // through batching.
1652 //
1653 // The one case where we pause input event delivery is when the wait queue is piling
1654 // up with lots of events because the application is not responding.
1655 // This condition ensures that ANRs are detected reliably.
Jeff Brownd1c48a02012-02-06 19:12:47 -08001656 if (!connection->waitQueue.isEmpty()
1657 && currentTime >= connection->waitQueue.head->eventEntry->eventTime
1658 + STREAM_AHEAD_EVENT_TIMEOUT) {
1659 return false;
1660 }
Jeff Brown519e0242010-09-15 15:18:56 -07001661 }
Jeff Brownd1c48a02012-02-06 19:12:47 -08001662 return true;
Jeff Brown519e0242010-09-15 15:18:56 -07001663}
1664
Jeff Brown9302c872011-07-13 22:51:29 -07001665String8 InputDispatcher::getApplicationWindowLabelLocked(
1666 const sp<InputApplicationHandle>& applicationHandle,
1667 const sp<InputWindowHandle>& windowHandle) {
1668 if (applicationHandle != NULL) {
1669 if (windowHandle != NULL) {
Jeff Browncc4f7db2011-08-30 20:34:48 -07001670 String8 label(applicationHandle->getName());
Jeff Brown519e0242010-09-15 15:18:56 -07001671 label.append(" - ");
Jeff Browncc4f7db2011-08-30 20:34:48 -07001672 label.append(windowHandle->getName());
Jeff Brown519e0242010-09-15 15:18:56 -07001673 return label;
1674 } else {
Jeff Browncc4f7db2011-08-30 20:34:48 -07001675 return applicationHandle->getName();
Jeff Brown519e0242010-09-15 15:18:56 -07001676 }
Jeff Brown9302c872011-07-13 22:51:29 -07001677 } else if (windowHandle != NULL) {
Jeff Browncc4f7db2011-08-30 20:34:48 -07001678 return windowHandle->getName();
Jeff Brown519e0242010-09-15 15:18:56 -07001679 } else {
1680 return String8("<unknown application or window>");
1681 }
1682}
1683
Jeff Browne2fe69e2010-10-18 13:21:23 -07001684void InputDispatcher::pokeUserActivityLocked(const EventEntry* eventEntry) {
Jeff Brown56194eb2011-03-02 19:23:13 -08001685 int32_t eventType = POWER_MANAGER_OTHER_EVENT;
Jeff Brown4d396052010-10-29 21:50:21 -07001686 switch (eventEntry->type) {
1687 case EventEntry::TYPE_MOTION: {
Jeff Browne2fe69e2010-10-18 13:21:23 -07001688 const MotionEntry* motionEntry = static_cast<const MotionEntry*>(eventEntry);
Jeff Brown4d396052010-10-29 21:50:21 -07001689 if (motionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
1690 return;
1691 }
1692
Jeff Brown56194eb2011-03-02 19:23:13 -08001693 if (MotionEvent::isTouchEvent(motionEntry->source, motionEntry->action)) {
Joe Onorato1a542c72010-11-08 09:48:20 -08001694 eventType = POWER_MANAGER_TOUCH_EVENT;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001695 }
Jeff Brown4d396052010-10-29 21:50:21 -07001696 break;
1697 }
1698 case EventEntry::TYPE_KEY: {
1699 const KeyEntry* keyEntry = static_cast<const KeyEntry*>(eventEntry);
1700 if (keyEntry->flags & AKEY_EVENT_FLAG_CANCELED) {
1701 return;
1702 }
Jeff Brown56194eb2011-03-02 19:23:13 -08001703 eventType = POWER_MANAGER_BUTTON_EVENT;
Jeff Brown4d396052010-10-29 21:50:21 -07001704 break;
1705 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001706 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001707
Jeff Brownb88102f2010-09-08 11:49:43 -07001708 CommandEntry* commandEntry = postCommandLocked(
1709 & InputDispatcher::doPokeUserActivityLockedInterruptible);
Jeff Browne2fe69e2010-10-18 13:21:23 -07001710 commandEntry->eventTime = eventEntry->eventTime;
Jeff Brownb88102f2010-09-08 11:49:43 -07001711 commandEntry->userActivityEventType = eventType;
1712}
1713
Jeff Brown7fbdc842010-06-17 20:52:56 -07001714void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001715 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07001716#if DEBUG_DISPATCH_CYCLE
Steve Block5baa3a62011-12-20 16:23:08 +00001717 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
Jeff Brown9cc695c2011-08-23 18:35:04 -07001718 "xOffset=%f, yOffset=%f, scaleFactor=%f, "
Jeff Brown3241b6b2012-02-03 15:08:02 -08001719 "pointerIds=0x%x",
Jeff Brown519e0242010-09-15 15:18:56 -07001720 connection->getInputChannelName(), inputTarget->flags,
Jeff Brown46b9ac02010-04-22 18:58:52 -07001721 inputTarget->xOffset, inputTarget->yOffset,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001722 inputTarget->scaleFactor, inputTarget->pointerIds.value);
Jeff Brown46b9ac02010-04-22 18:58:52 -07001723#endif
1724
1725 // Skip this event if the connection status is not normal.
Jeff Brown519e0242010-09-15 15:18:56 -07001726 // We don't want to enqueue additional outbound events if the connection is broken.
Jeff Brown46b9ac02010-04-22 18:58:52 -07001727 if (connection->status != Connection::STATUS_NORMAL) {
Jeff Brownb6997262010-10-08 22:31:17 -07001728#if DEBUG_DISPATCH_CYCLE
Steve Block5baa3a62011-12-20 16:23:08 +00001729 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Jeff Brownb88102f2010-09-08 11:49:43 -07001730 connection->getInputChannelName(), connection->getStatusLabel());
Jeff Brownb6997262010-10-08 22:31:17 -07001731#endif
Jeff Brown46b9ac02010-04-22 18:58:52 -07001732 return;
1733 }
1734
Jeff Brown01ce2e92010-09-26 22:20:12 -07001735 // Split a motion event if needed.
Jeff Brown3241b6b2012-02-03 15:08:02 -08001736 if (inputTarget->flags & InputTarget::FLAG_SPLIT) {
Steve Blockec193de2012-01-09 18:35:44 +00001737 ALOG_ASSERT(eventEntry->type == EventEntry::TYPE_MOTION);
Jeff Brown01ce2e92010-09-26 22:20:12 -07001738
1739 MotionEntry* originalMotionEntry = static_cast<MotionEntry*>(eventEntry);
1740 if (inputTarget->pointerIds.count() != originalMotionEntry->pointerCount) {
1741 MotionEntry* splitMotionEntry = splitMotionEvent(
1742 originalMotionEntry, inputTarget->pointerIds);
Jeff Brown58a2da82011-01-25 16:02:22 -08001743 if (!splitMotionEntry) {
1744 return; // split event was dropped
1745 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001746#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001747 ALOGD("channel '%s' ~ Split motion event.",
Jeff Brown01ce2e92010-09-26 22:20:12 -07001748 connection->getInputChannelName());
1749 logOutboundMotionDetailsLocked(" ", splitMotionEntry);
1750#endif
Jeff Brownc0cb3dc2012-01-12 18:30:12 -08001751 enqueueDispatchEntriesLocked(currentTime, connection,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001752 splitMotionEntry, inputTarget);
Jeff Brownc0cb3dc2012-01-12 18:30:12 -08001753 splitMotionEntry->release();
1754 return;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001755 }
1756 }
1757
Jeff Brownc0cb3dc2012-01-12 18:30:12 -08001758 // Not splitting. Enqueue dispatch entries for the event as is.
Jeff Brown3241b6b2012-02-03 15:08:02 -08001759 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
Jeff Brownc0cb3dc2012-01-12 18:30:12 -08001760}
1761
1762void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001763 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07001764 bool wasEmpty = connection->outboundQueue.isEmpty();
1765
Jeff Browna032cc02011-03-07 16:56:21 -08001766 // Enqueue dispatch entries for the requested modes.
1767 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001768 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
Jeff Browna032cc02011-03-07 16:56:21 -08001769 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001770 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
Jeff Browna032cc02011-03-07 16:56:21 -08001771 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001772 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
Jeff Browna032cc02011-03-07 16:56:21 -08001773 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001774 InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brown98db5fa2011-06-08 15:37:10 -07001775 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001776 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
Jeff Brown98db5fa2011-06-08 15:37:10 -07001777 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001778 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Jeff Browna032cc02011-03-07 16:56:21 -08001779
1780 // If the outbound queue was previously empty, start the dispatch cycle going.
Jeff Brownb6110c22011-04-01 16:15:13 -07001781 if (wasEmpty && !connection->outboundQueue.isEmpty()) {
Jeff Browna032cc02011-03-07 16:56:21 -08001782 startDispatchCycleLocked(currentTime, connection);
1783 }
1784}
1785
1786void InputDispatcher::enqueueDispatchEntryLocked(
1787 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001788 int32_t dispatchMode) {
Jeff Browna032cc02011-03-07 16:56:21 -08001789 int32_t inputTargetFlags = inputTarget->flags;
1790 if (!(inputTargetFlags & dispatchMode)) {
1791 return;
1792 }
1793 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
1794
Jeff Brown46b9ac02010-04-22 18:58:52 -07001795 // This is a new event.
1796 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Jeff Brownac386072011-07-20 15:19:50 -07001797 DispatchEntry* dispatchEntry = new DispatchEntry(eventEntry, // increments ref
Dianne Hackbornaa9d84c2011-05-09 19:00:59 -07001798 inputTargetFlags, inputTarget->xOffset, inputTarget->yOffset,
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001799 inputTarget->scaleFactor);
Jeff Brown6ec402b2010-07-28 15:48:59 -07001800
Jeff Brown81346812011-06-28 20:08:48 -07001801 // Apply target flags and update the connection's input state.
1802 switch (eventEntry->type) {
1803 case EventEntry::TYPE_KEY: {
1804 KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
1805 dispatchEntry->resolvedAction = keyEntry->action;
1806 dispatchEntry->resolvedFlags = keyEntry->flags;
1807
1808 if (!connection->inputState.trackKey(keyEntry,
1809 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags)) {
1810#if DEBUG_DISPATCH_CYCLE
Steve Block5baa3a62011-12-20 16:23:08 +00001811 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
Jeff Brown81346812011-06-28 20:08:48 -07001812 connection->getInputChannelName());
1813#endif
Jeff Brownc0cb3dc2012-01-12 18:30:12 -08001814 delete dispatchEntry;
Jeff Brown81346812011-06-28 20:08:48 -07001815 return; // skip the inconsistent event
1816 }
1817 break;
1818 }
1819
1820 case EventEntry::TYPE_MOTION: {
1821 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
1822 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
1823 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
1824 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
1825 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
1826 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
1827 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
1828 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
1829 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
1830 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
1831 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
1832 } else {
1833 dispatchEntry->resolvedAction = motionEntry->action;
1834 }
1835 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE
1836 && !connection->inputState.isHovering(
1837 motionEntry->deviceId, motionEntry->source)) {
1838#if DEBUG_DISPATCH_CYCLE
Steve Block5baa3a62011-12-20 16:23:08 +00001839 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter event",
Jeff Brown81346812011-06-28 20:08:48 -07001840 connection->getInputChannelName());
1841#endif
1842 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
1843 }
1844
1845 dispatchEntry->resolvedFlags = motionEntry->flags;
1846 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
1847 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
1848 }
1849
1850 if (!connection->inputState.trackMotion(motionEntry,
1851 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags)) {
1852#if DEBUG_DISPATCH_CYCLE
Steve Block5baa3a62011-12-20 16:23:08 +00001853 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion event",
Jeff Brown81346812011-06-28 20:08:48 -07001854 connection->getInputChannelName());
1855#endif
Jeff Brownc0cb3dc2012-01-12 18:30:12 -08001856 delete dispatchEntry;
Jeff Brown81346812011-06-28 20:08:48 -07001857 return; // skip the inconsistent event
1858 }
1859 break;
1860 }
1861 }
1862
Jeff Brownc0cb3dc2012-01-12 18:30:12 -08001863 // Remember that we are waiting for this dispatch to complete.
1864 if (dispatchEntry->hasForegroundTarget()) {
1865 incrementPendingForegroundDispatchesLocked(eventEntry);
1866 }
1867
Jeff Brown46b9ac02010-04-22 18:58:52 -07001868 // Enqueue the dispatch entry.
1869 connection->outboundQueue.enqueueAtTail(dispatchEntry);
Jeff Brown46b9ac02010-04-22 18:58:52 -07001870}
1871
Jeff Brown7fbdc842010-06-17 20:52:56 -07001872void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Jeff Brown519e0242010-09-15 15:18:56 -07001873 const sp<Connection>& connection) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07001874#if DEBUG_DISPATCH_CYCLE
Steve Block5baa3a62011-12-20 16:23:08 +00001875 ALOGD("channel '%s' ~ startDispatchCycle",
Jeff Brown46b9ac02010-04-22 18:58:52 -07001876 connection->getInputChannelName());
1877#endif
1878
Jeff Brownd1c48a02012-02-06 19:12:47 -08001879 while (connection->status == Connection::STATUS_NORMAL
1880 && !connection->outboundQueue.isEmpty()) {
1881 DispatchEntry* dispatchEntry = connection->outboundQueue.head;
Jeff Brown46b9ac02010-04-22 18:58:52 -07001882
Jeff Brownd1c48a02012-02-06 19:12:47 -08001883 // Publish the event.
1884 status_t status;
1885 EventEntry* eventEntry = dispatchEntry->eventEntry;
1886 switch (eventEntry->type) {
1887 case EventEntry::TYPE_KEY: {
1888 KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
Jeff Brown46b9ac02010-04-22 18:58:52 -07001889
Jeff Brownd1c48a02012-02-06 19:12:47 -08001890 // Publish the key event.
Jeff Brown072ec962012-02-07 14:46:57 -08001891 status = connection->inputPublisher.publishKeyEvent(dispatchEntry->seq,
Jeff Brownd1c48a02012-02-06 19:12:47 -08001892 keyEntry->deviceId, keyEntry->source,
1893 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags,
1894 keyEntry->keyCode, keyEntry->scanCode,
1895 keyEntry->metaState, keyEntry->repeatCount, keyEntry->downTime,
1896 keyEntry->eventTime);
1897 break;
1898 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001899
Jeff Brownd1c48a02012-02-06 19:12:47 -08001900 case EventEntry::TYPE_MOTION: {
1901 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
Jeff Brown46b9ac02010-04-22 18:58:52 -07001902
Jeff Brownd1c48a02012-02-06 19:12:47 -08001903 PointerCoords scaledCoords[MAX_POINTERS];
1904 const PointerCoords* usingCoords = motionEntry->pointerCoords;
Jeff Brown46b9ac02010-04-22 18:58:52 -07001905
Jeff Brownd1c48a02012-02-06 19:12:47 -08001906 // Set the X and Y offset depending on the input source.
1907 float xOffset, yOffset, scaleFactor;
1908 if ((motionEntry->source & AINPUT_SOURCE_CLASS_POINTER)
1909 && !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
1910 scaleFactor = dispatchEntry->scaleFactor;
1911 xOffset = dispatchEntry->xOffset * scaleFactor;
1912 yOffset = dispatchEntry->yOffset * scaleFactor;
1913 if (scaleFactor != 1.0f) {
1914 for (size_t i = 0; i < motionEntry->pointerCount; i++) {
1915 scaledCoords[i] = motionEntry->pointerCoords[i];
1916 scaledCoords[i].scale(scaleFactor);
1917 }
1918 usingCoords = scaledCoords;
1919 }
1920 } else {
1921 xOffset = 0.0f;
1922 yOffset = 0.0f;
1923 scaleFactor = 1.0f;
1924
1925 // We don't want the dispatch target to know.
1926 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
1927 for (size_t i = 0; i < motionEntry->pointerCount; i++) {
1928 scaledCoords[i].clear();
1929 }
1930 usingCoords = scaledCoords;
1931 }
1932 }
1933
1934 // Publish the motion event.
Jeff Brown072ec962012-02-07 14:46:57 -08001935 status = connection->inputPublisher.publishMotionEvent(dispatchEntry->seq,
Jeff Brownd1c48a02012-02-06 19:12:47 -08001936 motionEntry->deviceId, motionEntry->source,
1937 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags,
1938 motionEntry->edgeFlags, motionEntry->metaState, motionEntry->buttonState,
1939 xOffset, yOffset,
1940 motionEntry->xPrecision, motionEntry->yPrecision,
1941 motionEntry->downTime, motionEntry->eventTime,
1942 motionEntry->pointerCount, motionEntry->pointerProperties,
1943 usingCoords);
1944 break;
1945 }
1946
1947 default:
1948 ALOG_ASSERT(false);
Jeff Brown46b9ac02010-04-22 18:58:52 -07001949 return;
1950 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07001951
Jeff Brownd1c48a02012-02-06 19:12:47 -08001952 // Check the result.
Jeff Brown46b9ac02010-04-22 18:58:52 -07001953 if (status) {
Jeff Brownd1c48a02012-02-06 19:12:47 -08001954 if (status == WOULD_BLOCK) {
1955 if (connection->waitQueue.isEmpty()) {
1956 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
1957 "This is unexpected because the wait queue is empty, so the pipe "
1958 "should be empty and we shouldn't have any problems writing an "
1959 "event to it, status=%d", connection->getInputChannelName(), status);
1960 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
1961 } else {
1962 // Pipe is full and we are waiting for the app to finish process some events
1963 // before sending more events to it.
1964#if DEBUG_DISPATCH_CYCLE
1965 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
1966 "waiting for the application to catch up",
1967 connection->getInputChannelName());
1968#endif
1969 connection->inputPublisherBlocked = true;
1970 }
1971 } else {
1972 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
1973 "status=%d", connection->getInputChannelName(), status);
1974 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
1975 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07001976 return;
1977 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07001978
Jeff Brownd1c48a02012-02-06 19:12:47 -08001979 // Re-enqueue the event on the wait queue.
1980 connection->outboundQueue.dequeue(dispatchEntry);
1981 connection->waitQueue.enqueueAtTail(dispatchEntry);
Jeff Brown46b9ac02010-04-22 18:58:52 -07001982 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07001983}
1984
Jeff Brown7fbdc842010-06-17 20:52:56 -07001985void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Jeff Brown072ec962012-02-07 14:46:57 -08001986 const sp<Connection>& connection, uint32_t seq, bool handled) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07001987#if DEBUG_DISPATCH_CYCLE
Jeff Brown072ec962012-02-07 14:46:57 -08001988 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
1989 connection->getInputChannelName(), seq, toString(handled));
Jeff Brown46b9ac02010-04-22 18:58:52 -07001990#endif
1991
Jeff Brownd1c48a02012-02-06 19:12:47 -08001992 connection->inputPublisherBlocked = false;
1993
Jeff Brown9c3cda02010-06-15 01:31:58 -07001994 if (connection->status == Connection::STATUS_BROKEN
1995 || connection->status == Connection::STATUS_ZOMBIE) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07001996 return;
1997 }
1998
Jeff Brown3915bb82010-11-05 15:02:16 -07001999 // Notify other system components and prepare to start the next dispatch cycle.
Jeff Brown072ec962012-02-07 14:46:57 -08002000 onDispatchCycleFinishedLocked(currentTime, connection, seq, handled);
Jeff Brownb88102f2010-09-08 11:49:43 -07002001}
2002
Jeff Brownb6997262010-10-08 22:31:17 -07002003void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Jeff Browncc4f7db2011-08-30 20:34:48 -07002004 const sp<Connection>& connection, bool notify) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002005#if DEBUG_DISPATCH_CYCLE
Steve Block5baa3a62011-12-20 16:23:08 +00002006 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
Jeff Browncc4f7db2011-08-30 20:34:48 -07002007 connection->getInputChannelName(), toString(notify));
Jeff Brown46b9ac02010-04-22 18:58:52 -07002008#endif
2009
Jeff Brownd1c48a02012-02-06 19:12:47 -08002010 // Clear the dispatch queues.
2011 drainDispatchQueueLocked(&connection->outboundQueue);
2012 drainDispatchQueueLocked(&connection->waitQueue);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002013
Jeff Brownb6997262010-10-08 22:31:17 -07002014 // The connection appears to be unrecoverably broken.
Jeff Brown9c3cda02010-06-15 01:31:58 -07002015 // Ignore already broken or zombie connections.
Jeff Brownb6997262010-10-08 22:31:17 -07002016 if (connection->status == Connection::STATUS_NORMAL) {
2017 connection->status = Connection::STATUS_BROKEN;
Jeff Brown46b9ac02010-04-22 18:58:52 -07002018
Jeff Browncc4f7db2011-08-30 20:34:48 -07002019 if (notify) {
2020 // Notify other system components.
2021 onDispatchCycleBrokenLocked(currentTime, connection);
2022 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002023 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002024}
2025
Jeff Brownd1c48a02012-02-06 19:12:47 -08002026void InputDispatcher::drainDispatchQueueLocked(Queue<DispatchEntry>* queue) {
2027 while (!queue->isEmpty()) {
2028 DispatchEntry* dispatchEntry = queue->dequeueAtHead();
2029 releaseDispatchEntryLocked(dispatchEntry);
Jeff Brownb88102f2010-09-08 11:49:43 -07002030 }
Jeff Brownb88102f2010-09-08 11:49:43 -07002031}
2032
Jeff Brownd1c48a02012-02-06 19:12:47 -08002033void InputDispatcher::releaseDispatchEntryLocked(DispatchEntry* dispatchEntry) {
2034 if (dispatchEntry->hasForegroundTarget()) {
2035 decrementPendingForegroundDispatchesLocked(dispatchEntry->eventEntry);
2036 }
2037 delete dispatchEntry;
2038}
2039
Jeff Browncbee6d62012-02-03 20:11:27 -08002040int InputDispatcher::handleReceiveCallback(int fd, int events, void* data) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002041 InputDispatcher* d = static_cast<InputDispatcher*>(data);
2042
2043 { // acquire lock
2044 AutoMutex _l(d->mLock);
2045
Jeff Browncbee6d62012-02-03 20:11:27 -08002046 ssize_t connectionIndex = d->mConnectionsByFd.indexOfKey(fd);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002047 if (connectionIndex < 0) {
Steve Block3762c312012-01-06 19:20:56 +00002048 ALOGE("Received spurious receive callback for unknown input channel. "
Jeff Browncbee6d62012-02-03 20:11:27 -08002049 "fd=%d, events=0x%x", fd, events);
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002050 return 0; // remove the callback
Jeff Brown46b9ac02010-04-22 18:58:52 -07002051 }
2052
Jeff Browncc4f7db2011-08-30 20:34:48 -07002053 bool notify;
Jeff Browncbee6d62012-02-03 20:11:27 -08002054 sp<Connection> connection = d->mConnectionsByFd.valueAt(connectionIndex);
Jeff Browncc4f7db2011-08-30 20:34:48 -07002055 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
2056 if (!(events & ALOOPER_EVENT_INPUT)) {
Steve Block8564c8d2012-01-05 23:22:43 +00002057 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
Jeff Browncc4f7db2011-08-30 20:34:48 -07002058 "events=0x%x", connection->getInputChannelName(), events);
2059 return 1;
2060 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002061
Jeff Brown1adee112012-02-07 10:25:41 -08002062 nsecs_t currentTime = now();
2063 bool gotOne = false;
2064 status_t status;
2065 for (;;) {
Jeff Brown072ec962012-02-07 14:46:57 -08002066 uint32_t seq;
2067 bool handled;
2068 status = connection->inputPublisher.receiveFinishedSignal(&seq, &handled);
Jeff Brown1adee112012-02-07 10:25:41 -08002069 if (status) {
2070 break;
2071 }
Jeff Brown072ec962012-02-07 14:46:57 -08002072 d->finishDispatchCycleLocked(currentTime, connection, seq, handled);
Jeff Brown1adee112012-02-07 10:25:41 -08002073 gotOne = true;
2074 }
2075 if (gotOne) {
Jeff Browncc4f7db2011-08-30 20:34:48 -07002076 d->runCommandsLockedInterruptible();
Jeff Brown1adee112012-02-07 10:25:41 -08002077 if (status == WOULD_BLOCK) {
2078 return 1;
2079 }
Jeff Browncc4f7db2011-08-30 20:34:48 -07002080 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002081
Jeff Brown1adee112012-02-07 10:25:41 -08002082 notify = status != DEAD_OBJECT || !connection->monitor;
2083 if (notify) {
2084 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
2085 connection->getInputChannelName(), status);
2086 }
Jeff Browncc4f7db2011-08-30 20:34:48 -07002087 } else {
2088 // Monitor channels are never explicitly unregistered.
2089 // We do it automatically when the remote endpoint is closed so don't warn
2090 // about them.
2091 notify = !connection->monitor;
2092 if (notify) {
Steve Block8564c8d2012-01-05 23:22:43 +00002093 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. "
Jeff Browncc4f7db2011-08-30 20:34:48 -07002094 "events=0x%x", connection->getInputChannelName(), events);
2095 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002096 }
2097
Jeff Browncc4f7db2011-08-30 20:34:48 -07002098 // Unregister the channel.
2099 d->unregisterInputChannelLocked(connection->inputChannel, notify);
2100 return 0; // remove the callback
Jeff Brown46b9ac02010-04-22 18:58:52 -07002101 } // release lock
2102}
2103
Jeff Brownb6997262010-10-08 22:31:17 -07002104void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Jeff Brownda3d5a92011-03-29 15:11:34 -07002105 const CancelationOptions& options) {
Jeff Browncbee6d62012-02-03 20:11:27 -08002106 for (size_t i = 0; i < mConnectionsByFd.size(); i++) {
Jeff Brownb6997262010-10-08 22:31:17 -07002107 synthesizeCancelationEventsForConnectionLocked(
Jeff Browncbee6d62012-02-03 20:11:27 -08002108 mConnectionsByFd.valueAt(i), options);
Jeff Brownb6997262010-10-08 22:31:17 -07002109 }
2110}
2111
2112void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Jeff Brownda3d5a92011-03-29 15:11:34 -07002113 const sp<InputChannel>& channel, const CancelationOptions& options) {
Jeff Brownb6997262010-10-08 22:31:17 -07002114 ssize_t index = getConnectionIndexLocked(channel);
2115 if (index >= 0) {
2116 synthesizeCancelationEventsForConnectionLocked(
Jeff Browncbee6d62012-02-03 20:11:27 -08002117 mConnectionsByFd.valueAt(index), options);
Jeff Brownb6997262010-10-08 22:31:17 -07002118 }
2119}
2120
2121void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
Jeff Brownda3d5a92011-03-29 15:11:34 -07002122 const sp<Connection>& connection, const CancelationOptions& options) {
Jeff Brownc0cb3dc2012-01-12 18:30:12 -08002123 if (connection->status == Connection::STATUS_BROKEN) {
2124 return;
2125 }
2126
Jeff Brownb6997262010-10-08 22:31:17 -07002127 nsecs_t currentTime = now();
2128
Jeff Brown8b4be5602012-02-06 16:31:05 -08002129 Vector<EventEntry*> cancelationEvents;
Jeff Brownac386072011-07-20 15:19:50 -07002130 connection->inputState.synthesizeCancelationEvents(currentTime,
Jeff Brown8b4be5602012-02-06 16:31:05 -08002131 cancelationEvents, options);
Jeff Brownb6997262010-10-08 22:31:17 -07002132
Jeff Brown8b4be5602012-02-06 16:31:05 -08002133 if (!cancelationEvents.isEmpty()) {
Jeff Brownb6997262010-10-08 22:31:17 -07002134#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00002135 ALOGD("channel '%s' ~ Synthesized %d cancelation events to bring channel back in sync "
Jeff Brownda3d5a92011-03-29 15:11:34 -07002136 "with reality: %s, mode=%d.",
Jeff Brown8b4be5602012-02-06 16:31:05 -08002137 connection->getInputChannelName(), cancelationEvents.size(),
Jeff Brownda3d5a92011-03-29 15:11:34 -07002138 options.reason, options.mode);
Jeff Brownb6997262010-10-08 22:31:17 -07002139#endif
Jeff Brown8b4be5602012-02-06 16:31:05 -08002140 for (size_t i = 0; i < cancelationEvents.size(); i++) {
2141 EventEntry* cancelationEventEntry = cancelationEvents.itemAt(i);
Jeff Brownb6997262010-10-08 22:31:17 -07002142 switch (cancelationEventEntry->type) {
2143 case EventEntry::TYPE_KEY:
2144 logOutboundKeyDetailsLocked("cancel - ",
2145 static_cast<KeyEntry*>(cancelationEventEntry));
2146 break;
2147 case EventEntry::TYPE_MOTION:
2148 logOutboundMotionDetailsLocked("cancel - ",
2149 static_cast<MotionEntry*>(cancelationEventEntry));
2150 break;
2151 }
2152
Jeff Brown81346812011-06-28 20:08:48 -07002153 InputTarget target;
Jeff Brown9302c872011-07-13 22:51:29 -07002154 sp<InputWindowHandle> windowHandle = getWindowHandleLocked(connection->inputChannel);
2155 if (windowHandle != NULL) {
Jeff Browncc4f7db2011-08-30 20:34:48 -07002156 const InputWindowInfo* windowInfo = windowHandle->getInfo();
2157 target.xOffset = -windowInfo->frameLeft;
2158 target.yOffset = -windowInfo->frameTop;
2159 target.scaleFactor = windowInfo->scaleFactor;
Jeff Brownb6997262010-10-08 22:31:17 -07002160 } else {
Jeff Brown81346812011-06-28 20:08:48 -07002161 target.xOffset = 0;
2162 target.yOffset = 0;
2163 target.scaleFactor = 1.0f;
Jeff Brownb6997262010-10-08 22:31:17 -07002164 }
Jeff Brown81346812011-06-28 20:08:48 -07002165 target.inputChannel = connection->inputChannel;
2166 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
Jeff Brownb6997262010-10-08 22:31:17 -07002167
Jeff Brown81346812011-06-28 20:08:48 -07002168 enqueueDispatchEntryLocked(connection, cancelationEventEntry, // increments ref
Jeff Brown3241b6b2012-02-03 15:08:02 -08002169 &target, InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brownb6997262010-10-08 22:31:17 -07002170
Jeff Brownac386072011-07-20 15:19:50 -07002171 cancelationEventEntry->release();
Jeff Brownb6997262010-10-08 22:31:17 -07002172 }
2173
Jeff Brownd1c48a02012-02-06 19:12:47 -08002174 startDispatchCycleLocked(currentTime, connection);
Jeff Brownb6997262010-10-08 22:31:17 -07002175 }
2176}
2177
Jeff Brown01ce2e92010-09-26 22:20:12 -07002178InputDispatcher::MotionEntry*
2179InputDispatcher::splitMotionEvent(const MotionEntry* originalMotionEntry, BitSet32 pointerIds) {
Steve Blockec193de2012-01-09 18:35:44 +00002180 ALOG_ASSERT(pointerIds.value != 0);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002181
2182 uint32_t splitPointerIndexMap[MAX_POINTERS];
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002183 PointerProperties splitPointerProperties[MAX_POINTERS];
Jeff Brown01ce2e92010-09-26 22:20:12 -07002184 PointerCoords splitPointerCoords[MAX_POINTERS];
2185
2186 uint32_t originalPointerCount = originalMotionEntry->pointerCount;
2187 uint32_t splitPointerCount = 0;
2188
2189 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
2190 originalPointerIndex++) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002191 const PointerProperties& pointerProperties =
2192 originalMotionEntry->pointerProperties[originalPointerIndex];
2193 uint32_t pointerId = uint32_t(pointerProperties.id);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002194 if (pointerIds.hasBit(pointerId)) {
2195 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002196 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
Jeff Brownace13b12011-03-09 17:39:48 -08002197 splitPointerCoords[splitPointerCount].copyFrom(
Jeff Brown3241b6b2012-02-03 15:08:02 -08002198 originalMotionEntry->pointerCoords[originalPointerIndex]);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002199 splitPointerCount += 1;
2200 }
2201 }
Jeff Brown58a2da82011-01-25 16:02:22 -08002202
2203 if (splitPointerCount != pointerIds.count()) {
2204 // This is bad. We are missing some of the pointers that we expected to deliver.
2205 // Most likely this indicates that we received an ACTION_MOVE events that has
2206 // different pointer ids than we expected based on the previous ACTION_DOWN
2207 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
2208 // in this way.
Steve Block8564c8d2012-01-05 23:22:43 +00002209 ALOGW("Dropping split motion event because the pointer count is %d but "
Jeff Brown58a2da82011-01-25 16:02:22 -08002210 "we expected there to be %d pointers. This probably means we received "
2211 "a broken sequence of pointer ids from the input device.",
2212 splitPointerCount, pointerIds.count());
2213 return NULL;
2214 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07002215
2216 int32_t action = originalMotionEntry->action;
2217 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
2218 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
2219 || maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2220 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002221 const PointerProperties& pointerProperties =
2222 originalMotionEntry->pointerProperties[originalPointerIndex];
2223 uint32_t pointerId = uint32_t(pointerProperties.id);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002224 if (pointerIds.hasBit(pointerId)) {
2225 if (pointerIds.count() == 1) {
2226 // The first/last pointer went down/up.
2227 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
2228 ? AMOTION_EVENT_ACTION_DOWN : AMOTION_EVENT_ACTION_UP;
Jeff Brown9a01d052010-09-27 16:35:11 -07002229 } else {
2230 // A secondary pointer went down/up.
2231 uint32_t splitPointerIndex = 0;
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002232 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
Jeff Brown9a01d052010-09-27 16:35:11 -07002233 splitPointerIndex += 1;
2234 }
2235 action = maskedAction | (splitPointerIndex
2236 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002237 }
2238 } else {
2239 // An unrelated pointer changed.
2240 action = AMOTION_EVENT_ACTION_MOVE;
2241 }
2242 }
2243
Jeff Brownac386072011-07-20 15:19:50 -07002244 MotionEntry* splitMotionEntry = new MotionEntry(
Jeff Brown01ce2e92010-09-26 22:20:12 -07002245 originalMotionEntry->eventTime,
2246 originalMotionEntry->deviceId,
2247 originalMotionEntry->source,
2248 originalMotionEntry->policyFlags,
2249 action,
2250 originalMotionEntry->flags,
2251 originalMotionEntry->metaState,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002252 originalMotionEntry->buttonState,
Jeff Brown01ce2e92010-09-26 22:20:12 -07002253 originalMotionEntry->edgeFlags,
2254 originalMotionEntry->xPrecision,
2255 originalMotionEntry->yPrecision,
2256 originalMotionEntry->downTime,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002257 splitPointerCount, splitPointerProperties, splitPointerCoords);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002258
Jeff Browna032cc02011-03-07 16:56:21 -08002259 if (originalMotionEntry->injectionState) {
2260 splitMotionEntry->injectionState = originalMotionEntry->injectionState;
2261 splitMotionEntry->injectionState->refCount += 1;
2262 }
2263
Jeff Brown01ce2e92010-09-26 22:20:12 -07002264 return splitMotionEntry;
2265}
2266
Jeff Brownbe1aa822011-07-27 16:04:54 -07002267void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002268#if DEBUG_INBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00002269 ALOGD("notifyConfigurationChanged - eventTime=%lld", args->eventTime);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002270#endif
2271
Jeff Brownb88102f2010-09-08 11:49:43 -07002272 bool needWake;
Jeff Brown46b9ac02010-04-22 18:58:52 -07002273 { // acquire lock
2274 AutoMutex _l(mLock);
2275
Jeff Brownbe1aa822011-07-27 16:04:54 -07002276 ConfigurationChangedEntry* newEntry = new ConfigurationChangedEntry(args->eventTime);
Jeff Brownb88102f2010-09-08 11:49:43 -07002277 needWake = enqueueInboundEventLocked(newEntry);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002278 } // release lock
2279
Jeff Brownb88102f2010-09-08 11:49:43 -07002280 if (needWake) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002281 mLooper->wake();
Jeff Brown46b9ac02010-04-22 18:58:52 -07002282 }
2283}
2284
Jeff Brownbe1aa822011-07-27 16:04:54 -07002285void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002286#if DEBUG_INBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00002287 ALOGD("notifyKey - eventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, action=0x%x, "
Jeff Brown46b9ac02010-04-22 18:58:52 -07002288 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%lld",
Jeff Brownbe1aa822011-07-27 16:04:54 -07002289 args->eventTime, args->deviceId, args->source, args->policyFlags,
2290 args->action, args->flags, args->keyCode, args->scanCode,
2291 args->metaState, args->downTime);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002292#endif
Jeff Brownbe1aa822011-07-27 16:04:54 -07002293 if (!validateKeyEvent(args->action)) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002294 return;
2295 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002296
Jeff Brownbe1aa822011-07-27 16:04:54 -07002297 uint32_t policyFlags = args->policyFlags;
2298 int32_t flags = args->flags;
2299 int32_t metaState = args->metaState;
Jeff Brown1f245102010-11-18 20:53:46 -08002300 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
2301 policyFlags |= POLICY_FLAG_VIRTUAL;
2302 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
2303 }
Jeff Brown924c4d42011-03-07 16:40:47 -08002304 if (policyFlags & POLICY_FLAG_ALT) {
2305 metaState |= AMETA_ALT_ON | AMETA_ALT_LEFT_ON;
2306 }
2307 if (policyFlags & POLICY_FLAG_ALT_GR) {
2308 metaState |= AMETA_ALT_ON | AMETA_ALT_RIGHT_ON;
2309 }
2310 if (policyFlags & POLICY_FLAG_SHIFT) {
2311 metaState |= AMETA_SHIFT_ON | AMETA_SHIFT_LEFT_ON;
2312 }
2313 if (policyFlags & POLICY_FLAG_CAPS_LOCK) {
2314 metaState |= AMETA_CAPS_LOCK_ON;
2315 }
2316 if (policyFlags & POLICY_FLAG_FUNCTION) {
2317 metaState |= AMETA_FUNCTION_ON;
2318 }
Jeff Brown1f245102010-11-18 20:53:46 -08002319
Jeff Browne20c9e02010-10-11 14:20:19 -07002320 policyFlags |= POLICY_FLAG_TRUSTED;
Jeff Brown1f245102010-11-18 20:53:46 -08002321
2322 KeyEvent event;
Jeff Brownbe1aa822011-07-27 16:04:54 -07002323 event.initialize(args->deviceId, args->source, args->action,
2324 flags, args->keyCode, args->scanCode, metaState, 0,
2325 args->downTime, args->eventTime);
Jeff Brown1f245102010-11-18 20:53:46 -08002326
2327 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
2328
2329 if (policyFlags & POLICY_FLAG_WOKE_HERE) {
2330 flags |= AKEY_EVENT_FLAG_WOKE_HERE;
2331 }
Jeff Brownb6997262010-10-08 22:31:17 -07002332
Jeff Brownb88102f2010-09-08 11:49:43 -07002333 bool needWake;
Jeff Brown46b9ac02010-04-22 18:58:52 -07002334 { // acquire lock
Jeff Brown0029c662011-03-30 02:25:18 -07002335 mLock.lock();
2336
2337 if (mInputFilterEnabled) {
2338 mLock.unlock();
2339
2340 policyFlags |= POLICY_FLAG_FILTERED;
2341 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2342 return; // event was consumed by the filter
2343 }
2344
2345 mLock.lock();
2346 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002347
Jeff Brown7fbdc842010-06-17 20:52:56 -07002348 int32_t repeatCount = 0;
Jeff Brownbe1aa822011-07-27 16:04:54 -07002349 KeyEntry* newEntry = new KeyEntry(args->eventTime,
2350 args->deviceId, args->source, policyFlags,
2351 args->action, flags, args->keyCode, args->scanCode,
2352 metaState, repeatCount, args->downTime);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002353
Jeff Brownb88102f2010-09-08 11:49:43 -07002354 needWake = enqueueInboundEventLocked(newEntry);
Jeff Brown0029c662011-03-30 02:25:18 -07002355 mLock.unlock();
Jeff Brown46b9ac02010-04-22 18:58:52 -07002356 } // release lock
2357
Jeff Brownb88102f2010-09-08 11:49:43 -07002358 if (needWake) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002359 mLooper->wake();
Jeff Brown46b9ac02010-04-22 18:58:52 -07002360 }
2361}
2362
Jeff Brownbe1aa822011-07-27 16:04:54 -07002363void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002364#if DEBUG_INBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00002365 ALOGD("notifyMotion - eventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, "
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002366 "action=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, edgeFlags=0x%x, "
Jeff Brown85a31762010-09-01 17:01:00 -07002367 "xPrecision=%f, yPrecision=%f, downTime=%lld",
Jeff Brownbe1aa822011-07-27 16:04:54 -07002368 args->eventTime, args->deviceId, args->source, args->policyFlags,
2369 args->action, args->flags, args->metaState, args->buttonState,
2370 args->edgeFlags, args->xPrecision, args->yPrecision, args->downTime);
2371 for (uint32_t i = 0; i < args->pointerCount; i++) {
Steve Block5baa3a62011-12-20 16:23:08 +00002372 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002373 "x=%f, y=%f, pressure=%f, size=%f, "
Jeff Brown85a31762010-09-01 17:01:00 -07002374 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
Jeff Brown8d608662010-08-30 03:02:23 -07002375 "orientation=%f",
Jeff Brownbe1aa822011-07-27 16:04:54 -07002376 i, args->pointerProperties[i].id,
2377 args->pointerProperties[i].toolType,
2378 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
2379 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
2380 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
2381 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
2382 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
2383 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
2384 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
2385 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
2386 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Jeff Brown46b9ac02010-04-22 18:58:52 -07002387 }
2388#endif
Jeff Brownbe1aa822011-07-27 16:04:54 -07002389 if (!validateMotionEvent(args->action, args->pointerCount, args->pointerProperties)) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002390 return;
2391 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002392
Jeff Brownbe1aa822011-07-27 16:04:54 -07002393 uint32_t policyFlags = args->policyFlags;
Jeff Browne20c9e02010-10-11 14:20:19 -07002394 policyFlags |= POLICY_FLAG_TRUSTED;
Jeff Brownbe1aa822011-07-27 16:04:54 -07002395 mPolicy->interceptMotionBeforeQueueing(args->eventTime, /*byref*/ policyFlags);
Jeff Brownb6997262010-10-08 22:31:17 -07002396
Jeff Brownb88102f2010-09-08 11:49:43 -07002397 bool needWake;
Jeff Brown46b9ac02010-04-22 18:58:52 -07002398 { // acquire lock
Jeff Brown0029c662011-03-30 02:25:18 -07002399 mLock.lock();
2400
2401 if (mInputFilterEnabled) {
2402 mLock.unlock();
2403
2404 MotionEvent event;
Jeff Brownbe1aa822011-07-27 16:04:54 -07002405 event.initialize(args->deviceId, args->source, args->action, args->flags,
2406 args->edgeFlags, args->metaState, args->buttonState, 0, 0,
2407 args->xPrecision, args->yPrecision,
2408 args->downTime, args->eventTime,
2409 args->pointerCount, args->pointerProperties, args->pointerCoords);
Jeff Brown0029c662011-03-30 02:25:18 -07002410
2411 policyFlags |= POLICY_FLAG_FILTERED;
2412 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2413 return; // event was consumed by the filter
2414 }
2415
2416 mLock.lock();
2417 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002418
Jeff Brown46b9ac02010-04-22 18:58:52 -07002419 // Just enqueue a new motion event.
Jeff Brownbe1aa822011-07-27 16:04:54 -07002420 MotionEntry* newEntry = new MotionEntry(args->eventTime,
2421 args->deviceId, args->source, policyFlags,
2422 args->action, args->flags, args->metaState, args->buttonState,
2423 args->edgeFlags, args->xPrecision, args->yPrecision, args->downTime,
2424 args->pointerCount, args->pointerProperties, args->pointerCoords);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002425
Jeff Brownb88102f2010-09-08 11:49:43 -07002426 needWake = enqueueInboundEventLocked(newEntry);
Jeff Brown0029c662011-03-30 02:25:18 -07002427 mLock.unlock();
Jeff Brown46b9ac02010-04-22 18:58:52 -07002428 } // release lock
2429
Jeff Brownb88102f2010-09-08 11:49:43 -07002430 if (needWake) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002431 mLooper->wake();
Jeff Brown46b9ac02010-04-22 18:58:52 -07002432 }
2433}
2434
Jeff Brownbe1aa822011-07-27 16:04:54 -07002435void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
Jeff Brownb6997262010-10-08 22:31:17 -07002436#if DEBUG_INBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00002437 ALOGD("notifySwitch - eventTime=%lld, policyFlags=0x%x, switchCode=%d, switchValue=%d",
Jeff Brownbe1aa822011-07-27 16:04:54 -07002438 args->eventTime, args->policyFlags,
2439 args->switchCode, args->switchValue);
Jeff Brownb6997262010-10-08 22:31:17 -07002440#endif
2441
Jeff Brownbe1aa822011-07-27 16:04:54 -07002442 uint32_t policyFlags = args->policyFlags;
Jeff Browne20c9e02010-10-11 14:20:19 -07002443 policyFlags |= POLICY_FLAG_TRUSTED;
Jeff Brownbe1aa822011-07-27 16:04:54 -07002444 mPolicy->notifySwitch(args->eventTime,
2445 args->switchCode, args->switchValue, policyFlags);
Jeff Brownb6997262010-10-08 22:31:17 -07002446}
2447
Jeff Brown65fd2512011-08-18 11:20:58 -07002448void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
2449#if DEBUG_INBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00002450 ALOGD("notifyDeviceReset - eventTime=%lld, deviceId=%d",
Jeff Brown65fd2512011-08-18 11:20:58 -07002451 args->eventTime, args->deviceId);
2452#endif
2453
2454 bool needWake;
2455 { // acquire lock
2456 AutoMutex _l(mLock);
2457
2458 DeviceResetEntry* newEntry = new DeviceResetEntry(args->eventTime, args->deviceId);
2459 needWake = enqueueInboundEventLocked(newEntry);
2460 } // release lock
2461
2462 if (needWake) {
2463 mLooper->wake();
2464 }
2465}
2466
Jeff Brown7fbdc842010-06-17 20:52:56 -07002467int32_t InputDispatcher::injectInputEvent(const InputEvent* event,
Jeff Brown0029c662011-03-30 02:25:18 -07002468 int32_t injectorPid, int32_t injectorUid, int32_t syncMode, int32_t timeoutMillis,
2469 uint32_t policyFlags) {
Jeff Brown7fbdc842010-06-17 20:52:56 -07002470#if DEBUG_INBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00002471 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Jeff Brown0029c662011-03-30 02:25:18 -07002472 "syncMode=%d, timeoutMillis=%d, policyFlags=0x%08x",
2473 event->getType(), injectorPid, injectorUid, syncMode, timeoutMillis, policyFlags);
Jeff Brown7fbdc842010-06-17 20:52:56 -07002474#endif
2475
2476 nsecs_t endTime = now() + milliseconds_to_nanoseconds(timeoutMillis);
Jeff Browne20c9e02010-10-11 14:20:19 -07002477
Jeff Brown0029c662011-03-30 02:25:18 -07002478 policyFlags |= POLICY_FLAG_INJECTED;
Jeff Browne20c9e02010-10-11 14:20:19 -07002479 if (hasInjectionPermission(injectorPid, injectorUid)) {
2480 policyFlags |= POLICY_FLAG_TRUSTED;
2481 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07002482
Jeff Brown3241b6b2012-02-03 15:08:02 -08002483 EventEntry* firstInjectedEntry;
2484 EventEntry* lastInjectedEntry;
Jeff Brownb6997262010-10-08 22:31:17 -07002485 switch (event->getType()) {
2486 case AINPUT_EVENT_TYPE_KEY: {
2487 const KeyEvent* keyEvent = static_cast<const KeyEvent*>(event);
2488 int32_t action = keyEvent->getAction();
2489 if (! validateKeyEvent(action)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07002490 return INPUT_EVENT_INJECTION_FAILED;
2491 }
2492
Jeff Brownb6997262010-10-08 22:31:17 -07002493 int32_t flags = keyEvent->getFlags();
Jeff Brown1f245102010-11-18 20:53:46 -08002494 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
2495 policyFlags |= POLICY_FLAG_VIRTUAL;
2496 }
2497
Jeff Brown0029c662011-03-30 02:25:18 -07002498 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
2499 mPolicy->interceptKeyBeforeQueueing(keyEvent, /*byref*/ policyFlags);
2500 }
Jeff Brown1f245102010-11-18 20:53:46 -08002501
2502 if (policyFlags & POLICY_FLAG_WOKE_HERE) {
2503 flags |= AKEY_EVENT_FLAG_WOKE_HERE;
2504 }
Jeff Brown6ec402b2010-07-28 15:48:59 -07002505
Jeff Brownb6997262010-10-08 22:31:17 -07002506 mLock.lock();
Jeff Brown3241b6b2012-02-03 15:08:02 -08002507 firstInjectedEntry = new KeyEntry(keyEvent->getEventTime(),
Jeff Brown1f245102010-11-18 20:53:46 -08002508 keyEvent->getDeviceId(), keyEvent->getSource(),
2509 policyFlags, action, flags,
2510 keyEvent->getKeyCode(), keyEvent->getScanCode(), keyEvent->getMetaState(),
Jeff Brownb6997262010-10-08 22:31:17 -07002511 keyEvent->getRepeatCount(), keyEvent->getDownTime());
Jeff Brown3241b6b2012-02-03 15:08:02 -08002512 lastInjectedEntry = firstInjectedEntry;
Jeff Brownb6997262010-10-08 22:31:17 -07002513 break;
2514 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07002515
Jeff Brownb6997262010-10-08 22:31:17 -07002516 case AINPUT_EVENT_TYPE_MOTION: {
2517 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
2518 int32_t action = motionEvent->getAction();
2519 size_t pointerCount = motionEvent->getPointerCount();
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002520 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
2521 if (! validateMotionEvent(action, pointerCount, pointerProperties)) {
Jeff Brownb6997262010-10-08 22:31:17 -07002522 return INPUT_EVENT_INJECTION_FAILED;
2523 }
2524
Jeff Brown0029c662011-03-30 02:25:18 -07002525 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
2526 nsecs_t eventTime = motionEvent->getEventTime();
2527 mPolicy->interceptMotionBeforeQueueing(eventTime, /*byref*/ policyFlags);
2528 }
Jeff Brownb6997262010-10-08 22:31:17 -07002529
2530 mLock.lock();
2531 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
2532 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
Jeff Brown3241b6b2012-02-03 15:08:02 -08002533 firstInjectedEntry = new MotionEntry(*sampleEventTimes,
Jeff Brownb6997262010-10-08 22:31:17 -07002534 motionEvent->getDeviceId(), motionEvent->getSource(), policyFlags,
2535 action, motionEvent->getFlags(),
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002536 motionEvent->getMetaState(), motionEvent->getButtonState(),
2537 motionEvent->getEdgeFlags(),
Jeff Brownb6997262010-10-08 22:31:17 -07002538 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
2539 motionEvent->getDownTime(), uint32_t(pointerCount),
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002540 pointerProperties, samplePointerCoords);
Jeff Brown3241b6b2012-02-03 15:08:02 -08002541 lastInjectedEntry = firstInjectedEntry;
Jeff Brownb6997262010-10-08 22:31:17 -07002542 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
2543 sampleEventTimes += 1;
2544 samplePointerCoords += pointerCount;
Jeff Brown3241b6b2012-02-03 15:08:02 -08002545 MotionEntry* nextInjectedEntry = new MotionEntry(*sampleEventTimes,
2546 motionEvent->getDeviceId(), motionEvent->getSource(), policyFlags,
2547 action, motionEvent->getFlags(),
2548 motionEvent->getMetaState(), motionEvent->getButtonState(),
2549 motionEvent->getEdgeFlags(),
2550 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
2551 motionEvent->getDownTime(), uint32_t(pointerCount),
2552 pointerProperties, samplePointerCoords);
2553 lastInjectedEntry->next = nextInjectedEntry;
2554 lastInjectedEntry = nextInjectedEntry;
Jeff Brownb6997262010-10-08 22:31:17 -07002555 }
Jeff Brownb6997262010-10-08 22:31:17 -07002556 break;
2557 }
2558
2559 default:
Steve Block8564c8d2012-01-05 23:22:43 +00002560 ALOGW("Cannot inject event of type %d", event->getType());
Jeff Brownb6997262010-10-08 22:31:17 -07002561 return INPUT_EVENT_INJECTION_FAILED;
2562 }
2563
Jeff Brownac386072011-07-20 15:19:50 -07002564 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
Jeff Brownb6997262010-10-08 22:31:17 -07002565 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
2566 injectionState->injectionIsAsync = true;
2567 }
2568
2569 injectionState->refCount += 1;
Jeff Brown3241b6b2012-02-03 15:08:02 -08002570 lastInjectedEntry->injectionState = injectionState;
Jeff Brownb6997262010-10-08 22:31:17 -07002571
Jeff Brown3241b6b2012-02-03 15:08:02 -08002572 bool needWake = false;
2573 for (EventEntry* entry = firstInjectedEntry; entry != NULL; ) {
2574 EventEntry* nextEntry = entry->next;
2575 needWake |= enqueueInboundEventLocked(entry);
2576 entry = nextEntry;
2577 }
2578
Jeff Brownb6997262010-10-08 22:31:17 -07002579 mLock.unlock();
Jeff Brown7fbdc842010-06-17 20:52:56 -07002580
Jeff Brownb88102f2010-09-08 11:49:43 -07002581 if (needWake) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002582 mLooper->wake();
Jeff Brown7fbdc842010-06-17 20:52:56 -07002583 }
2584
2585 int32_t injectionResult;
2586 { // acquire lock
2587 AutoMutex _l(mLock);
2588
Jeff Brown6ec402b2010-07-28 15:48:59 -07002589 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
2590 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
2591 } else {
2592 for (;;) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002593 injectionResult = injectionState->injectionResult;
Jeff Brown6ec402b2010-07-28 15:48:59 -07002594 if (injectionResult != INPUT_EVENT_INJECTION_PENDING) {
2595 break;
2596 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07002597
Jeff Brown7fbdc842010-06-17 20:52:56 -07002598 nsecs_t remainingTimeout = endTime - now();
2599 if (remainingTimeout <= 0) {
Jeff Brown6ec402b2010-07-28 15:48:59 -07002600#if DEBUG_INJECTION
Steve Block5baa3a62011-12-20 16:23:08 +00002601 ALOGD("injectInputEvent - Timed out waiting for injection result "
Jeff Brown6ec402b2010-07-28 15:48:59 -07002602 "to become available.");
2603#endif
Jeff Brown7fbdc842010-06-17 20:52:56 -07002604 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
2605 break;
2606 }
2607
Jeff Brown6ec402b2010-07-28 15:48:59 -07002608 mInjectionResultAvailableCondition.waitRelative(mLock, remainingTimeout);
2609 }
2610
2611 if (injectionResult == INPUT_EVENT_INJECTION_SUCCEEDED
2612 && syncMode == INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002613 while (injectionState->pendingForegroundDispatches != 0) {
Jeff Brown6ec402b2010-07-28 15:48:59 -07002614#if DEBUG_INJECTION
Steve Block5baa3a62011-12-20 16:23:08 +00002615 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
Jeff Brown01ce2e92010-09-26 22:20:12 -07002616 injectionState->pendingForegroundDispatches);
Jeff Brown6ec402b2010-07-28 15:48:59 -07002617#endif
2618 nsecs_t remainingTimeout = endTime - now();
2619 if (remainingTimeout <= 0) {
2620#if DEBUG_INJECTION
Steve Block5baa3a62011-12-20 16:23:08 +00002621 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
Jeff Brown6ec402b2010-07-28 15:48:59 -07002622 "dispatches to finish.");
2623#endif
2624 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
2625 break;
2626 }
2627
2628 mInjectionSyncFinishedCondition.waitRelative(mLock, remainingTimeout);
2629 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07002630 }
2631 }
2632
Jeff Brownac386072011-07-20 15:19:50 -07002633 injectionState->release();
Jeff Brown7fbdc842010-06-17 20:52:56 -07002634 } // release lock
2635
Jeff Brown6ec402b2010-07-28 15:48:59 -07002636#if DEBUG_INJECTION
Steve Block5baa3a62011-12-20 16:23:08 +00002637 ALOGD("injectInputEvent - Finished with result %d. "
Jeff Brown6ec402b2010-07-28 15:48:59 -07002638 "injectorPid=%d, injectorUid=%d",
2639 injectionResult, injectorPid, injectorUid);
2640#endif
2641
Jeff Brown7fbdc842010-06-17 20:52:56 -07002642 return injectionResult;
2643}
2644
Jeff Brownb6997262010-10-08 22:31:17 -07002645bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
2646 return injectorUid == 0
2647 || mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
2648}
2649
Jeff Brown7fbdc842010-06-17 20:52:56 -07002650void InputDispatcher::setInjectionResultLocked(EventEntry* entry, int32_t injectionResult) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002651 InjectionState* injectionState = entry->injectionState;
2652 if (injectionState) {
Jeff Brown7fbdc842010-06-17 20:52:56 -07002653#if DEBUG_INJECTION
Steve Block5baa3a62011-12-20 16:23:08 +00002654 ALOGD("Setting input event injection result to %d. "
Jeff Brown7fbdc842010-06-17 20:52:56 -07002655 "injectorPid=%d, injectorUid=%d",
Jeff Brown01ce2e92010-09-26 22:20:12 -07002656 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
Jeff Brown7fbdc842010-06-17 20:52:56 -07002657#endif
2658
Jeff Brown0029c662011-03-30 02:25:18 -07002659 if (injectionState->injectionIsAsync
2660 && !(entry->policyFlags & POLICY_FLAG_FILTERED)) {
Jeff Brown6ec402b2010-07-28 15:48:59 -07002661 // Log the outcome since the injector did not wait for the injection result.
2662 switch (injectionResult) {
2663 case INPUT_EVENT_INJECTION_SUCCEEDED:
Steve Block71f2cf12011-10-20 11:56:00 +01002664 ALOGV("Asynchronous input event injection succeeded.");
Jeff Brown6ec402b2010-07-28 15:48:59 -07002665 break;
2666 case INPUT_EVENT_INJECTION_FAILED:
Steve Block8564c8d2012-01-05 23:22:43 +00002667 ALOGW("Asynchronous input event injection failed.");
Jeff Brown6ec402b2010-07-28 15:48:59 -07002668 break;
2669 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
Steve Block8564c8d2012-01-05 23:22:43 +00002670 ALOGW("Asynchronous input event injection permission denied.");
Jeff Brown6ec402b2010-07-28 15:48:59 -07002671 break;
2672 case INPUT_EVENT_INJECTION_TIMED_OUT:
Steve Block8564c8d2012-01-05 23:22:43 +00002673 ALOGW("Asynchronous input event injection timed out.");
Jeff Brown6ec402b2010-07-28 15:48:59 -07002674 break;
2675 }
2676 }
2677
Jeff Brown01ce2e92010-09-26 22:20:12 -07002678 injectionState->injectionResult = injectionResult;
Jeff Brown7fbdc842010-06-17 20:52:56 -07002679 mInjectionResultAvailableCondition.broadcast();
2680 }
2681}
2682
Jeff Brown01ce2e92010-09-26 22:20:12 -07002683void InputDispatcher::incrementPendingForegroundDispatchesLocked(EventEntry* entry) {
2684 InjectionState* injectionState = entry->injectionState;
2685 if (injectionState) {
2686 injectionState->pendingForegroundDispatches += 1;
2687 }
2688}
2689
Jeff Brown519e0242010-09-15 15:18:56 -07002690void InputDispatcher::decrementPendingForegroundDispatchesLocked(EventEntry* entry) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002691 InjectionState* injectionState = entry->injectionState;
2692 if (injectionState) {
2693 injectionState->pendingForegroundDispatches -= 1;
Jeff Brown6ec402b2010-07-28 15:48:59 -07002694
Jeff Brown01ce2e92010-09-26 22:20:12 -07002695 if (injectionState->pendingForegroundDispatches == 0) {
2696 mInjectionSyncFinishedCondition.broadcast();
2697 }
Jeff Brownb88102f2010-09-08 11:49:43 -07002698 }
2699}
2700
Jeff Brown9302c872011-07-13 22:51:29 -07002701sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
2702 const sp<InputChannel>& inputChannel) const {
2703 size_t numWindows = mWindowHandles.size();
2704 for (size_t i = 0; i < numWindows; i++) {
2705 const sp<InputWindowHandle>& windowHandle = mWindowHandles.itemAt(i);
Jeff Browncc4f7db2011-08-30 20:34:48 -07002706 if (windowHandle->getInputChannel() == inputChannel) {
Jeff Brown9302c872011-07-13 22:51:29 -07002707 return windowHandle;
Jeff Brown01ce2e92010-09-26 22:20:12 -07002708 }
2709 }
2710 return NULL;
2711}
2712
Jeff Brown9302c872011-07-13 22:51:29 -07002713bool InputDispatcher::hasWindowHandleLocked(
2714 const sp<InputWindowHandle>& windowHandle) const {
2715 size_t numWindows = mWindowHandles.size();
2716 for (size_t i = 0; i < numWindows; i++) {
2717 if (mWindowHandles.itemAt(i) == windowHandle) {
2718 return true;
2719 }
2720 }
2721 return false;
2722}
2723
2724void InputDispatcher::setInputWindows(const Vector<sp<InputWindowHandle> >& inputWindowHandles) {
Jeff Brownb88102f2010-09-08 11:49:43 -07002725#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002726 ALOGD("setInputWindows");
Jeff Brownb88102f2010-09-08 11:49:43 -07002727#endif
2728 { // acquire lock
2729 AutoMutex _l(mLock);
2730
Jeff Browncc4f7db2011-08-30 20:34:48 -07002731 Vector<sp<InputWindowHandle> > oldWindowHandles = mWindowHandles;
Jeff Brown9302c872011-07-13 22:51:29 -07002732 mWindowHandles = inputWindowHandles;
Jeff Brownb6997262010-10-08 22:31:17 -07002733
Jeff Brown9302c872011-07-13 22:51:29 -07002734 sp<InputWindowHandle> newFocusedWindowHandle;
2735 bool foundHoveredWindow = false;
2736 for (size_t i = 0; i < mWindowHandles.size(); i++) {
2737 const sp<InputWindowHandle>& windowHandle = mWindowHandles.itemAt(i);
Jeff Browncc4f7db2011-08-30 20:34:48 -07002738 if (!windowHandle->updateInfo() || windowHandle->getInputChannel() == NULL) {
Jeff Brown9302c872011-07-13 22:51:29 -07002739 mWindowHandles.removeAt(i--);
2740 continue;
2741 }
Jeff Browncc4f7db2011-08-30 20:34:48 -07002742 if (windowHandle->getInfo()->hasFocus) {
Jeff Brown9302c872011-07-13 22:51:29 -07002743 newFocusedWindowHandle = windowHandle;
2744 }
2745 if (windowHandle == mLastHoverWindowHandle) {
2746 foundHoveredWindow = true;
Jeff Brownb88102f2010-09-08 11:49:43 -07002747 }
2748 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07002749
Jeff Brown9302c872011-07-13 22:51:29 -07002750 if (!foundHoveredWindow) {
2751 mLastHoverWindowHandle = NULL;
2752 }
2753
2754 if (mFocusedWindowHandle != newFocusedWindowHandle) {
2755 if (mFocusedWindowHandle != NULL) {
Jeff Brownb6997262010-10-08 22:31:17 -07002756#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002757 ALOGD("Focus left window: %s",
Jeff Browncc4f7db2011-08-30 20:34:48 -07002758 mFocusedWindowHandle->getName().string());
Jeff Brownb6997262010-10-08 22:31:17 -07002759#endif
Jeff Browncc4f7db2011-08-30 20:34:48 -07002760 sp<InputChannel> focusedInputChannel = mFocusedWindowHandle->getInputChannel();
2761 if (focusedInputChannel != NULL) {
Christopher Tated9be36c2011-08-16 16:09:33 -07002762 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
2763 "focus left window");
2764 synthesizeCancelationEventsForInputChannelLocked(
Jeff Browncc4f7db2011-08-30 20:34:48 -07002765 focusedInputChannel, options);
Christopher Tated9be36c2011-08-16 16:09:33 -07002766 }
Jeff Brownb6997262010-10-08 22:31:17 -07002767 }
Jeff Brown9302c872011-07-13 22:51:29 -07002768 if (newFocusedWindowHandle != NULL) {
Jeff Brownb6997262010-10-08 22:31:17 -07002769#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002770 ALOGD("Focus entered window: %s",
Jeff Browncc4f7db2011-08-30 20:34:48 -07002771 newFocusedWindowHandle->getName().string());
Jeff Brownb6997262010-10-08 22:31:17 -07002772#endif
Jeff Brown9302c872011-07-13 22:51:29 -07002773 }
2774 mFocusedWindowHandle = newFocusedWindowHandle;
Jeff Brownb6997262010-10-08 22:31:17 -07002775 }
2776
Jeff Brown9302c872011-07-13 22:51:29 -07002777 for (size_t i = 0; i < mTouchState.windows.size(); i++) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002778 TouchedWindow& touchedWindow = mTouchState.windows.editItemAt(i);
Jeff Brown9302c872011-07-13 22:51:29 -07002779 if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
Jeff Brownb6997262010-10-08 22:31:17 -07002780#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002781 ALOGD("Touched window was removed: %s",
Jeff Browncc4f7db2011-08-30 20:34:48 -07002782 touchedWindow.windowHandle->getName().string());
Jeff Brownb6997262010-10-08 22:31:17 -07002783#endif
Jeff Browncc4f7db2011-08-30 20:34:48 -07002784 sp<InputChannel> touchedInputChannel =
2785 touchedWindow.windowHandle->getInputChannel();
2786 if (touchedInputChannel != NULL) {
Christopher Tated9be36c2011-08-16 16:09:33 -07002787 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
2788 "touched window was removed");
2789 synthesizeCancelationEventsForInputChannelLocked(
Jeff Browncc4f7db2011-08-30 20:34:48 -07002790 touchedInputChannel, options);
Christopher Tated9be36c2011-08-16 16:09:33 -07002791 }
Jeff Brown9302c872011-07-13 22:51:29 -07002792 mTouchState.windows.removeAt(i--);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002793 }
2794 }
Jeff Browncc4f7db2011-08-30 20:34:48 -07002795
2796 // Release information for windows that are no longer present.
2797 // This ensures that unused input channels are released promptly.
2798 // Otherwise, they might stick around until the window handle is destroyed
2799 // which might not happen until the next GC.
2800 for (size_t i = 0; i < oldWindowHandles.size(); i++) {
2801 const sp<InputWindowHandle>& oldWindowHandle = oldWindowHandles.itemAt(i);
2802 if (!hasWindowHandleLocked(oldWindowHandle)) {
2803#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002804 ALOGD("Window went away: %s", oldWindowHandle->getName().string());
Jeff Browncc4f7db2011-08-30 20:34:48 -07002805#endif
2806 oldWindowHandle->releaseInfo();
2807 }
2808 }
Jeff Brownb88102f2010-09-08 11:49:43 -07002809 } // release lock
2810
2811 // Wake up poll loop since it may need to make new input dispatching choices.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002812 mLooper->wake();
Jeff Brownb88102f2010-09-08 11:49:43 -07002813}
2814
Jeff Brown9302c872011-07-13 22:51:29 -07002815void InputDispatcher::setFocusedApplication(
2816 const sp<InputApplicationHandle>& inputApplicationHandle) {
Jeff Brownb88102f2010-09-08 11:49:43 -07002817#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002818 ALOGD("setFocusedApplication");
Jeff Brownb88102f2010-09-08 11:49:43 -07002819#endif
2820 { // acquire lock
2821 AutoMutex _l(mLock);
2822
Jeff Browncc4f7db2011-08-30 20:34:48 -07002823 if (inputApplicationHandle != NULL && inputApplicationHandle->updateInfo()) {
Jeff Brown5ea29ab2011-07-27 11:50:51 -07002824 if (mFocusedApplicationHandle != inputApplicationHandle) {
2825 if (mFocusedApplicationHandle != NULL) {
Jeff Browne9bb9be2012-02-06 15:47:55 -08002826 resetANRTimeoutsLocked();
Jeff Browncc4f7db2011-08-30 20:34:48 -07002827 mFocusedApplicationHandle->releaseInfo();
Jeff Brown5ea29ab2011-07-27 11:50:51 -07002828 }
2829 mFocusedApplicationHandle = inputApplicationHandle;
2830 }
2831 } else if (mFocusedApplicationHandle != NULL) {
Jeff Browne9bb9be2012-02-06 15:47:55 -08002832 resetANRTimeoutsLocked();
Jeff Browncc4f7db2011-08-30 20:34:48 -07002833 mFocusedApplicationHandle->releaseInfo();
Jeff Brown9302c872011-07-13 22:51:29 -07002834 mFocusedApplicationHandle.clear();
Jeff Brownb88102f2010-09-08 11:49:43 -07002835 }
2836
2837#if DEBUG_FOCUS
Jeff Brownb6997262010-10-08 22:31:17 -07002838 //logDispatchStateLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -07002839#endif
2840 } // release lock
2841
2842 // Wake up poll loop since it may need to make new input dispatching choices.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002843 mLooper->wake();
Jeff Brownb88102f2010-09-08 11:49:43 -07002844}
2845
Jeff Brownb88102f2010-09-08 11:49:43 -07002846void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
2847#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002848 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
Jeff Brownb88102f2010-09-08 11:49:43 -07002849#endif
2850
2851 bool changed;
2852 { // acquire lock
2853 AutoMutex _l(mLock);
2854
2855 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
Jeff Brown120a4592010-10-27 18:43:51 -07002856 if (mDispatchFrozen && !frozen) {
Jeff Brownb88102f2010-09-08 11:49:43 -07002857 resetANRTimeoutsLocked();
2858 }
2859
Jeff Brown120a4592010-10-27 18:43:51 -07002860 if (mDispatchEnabled && !enabled) {
2861 resetAndDropEverythingLocked("dispatcher is being disabled");
2862 }
2863
Jeff Brownb88102f2010-09-08 11:49:43 -07002864 mDispatchEnabled = enabled;
2865 mDispatchFrozen = frozen;
2866 changed = true;
2867 } else {
2868 changed = false;
2869 }
2870
2871#if DEBUG_FOCUS
Jeff Brownb6997262010-10-08 22:31:17 -07002872 //logDispatchStateLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -07002873#endif
2874 } // release lock
2875
2876 if (changed) {
2877 // Wake up poll loop since it may need to make new input dispatching choices.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002878 mLooper->wake();
Jeff Brown46b9ac02010-04-22 18:58:52 -07002879 }
2880}
2881
Jeff Brown0029c662011-03-30 02:25:18 -07002882void InputDispatcher::setInputFilterEnabled(bool enabled) {
2883#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002884 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
Jeff Brown0029c662011-03-30 02:25:18 -07002885#endif
2886
2887 { // acquire lock
2888 AutoMutex _l(mLock);
2889
2890 if (mInputFilterEnabled == enabled) {
2891 return;
2892 }
2893
2894 mInputFilterEnabled = enabled;
2895 resetAndDropEverythingLocked("input filter is being enabled or disabled");
2896 } // release lock
2897
2898 // Wake up poll loop since there might be work to do to drop everything.
2899 mLooper->wake();
2900}
2901
Jeff Browne6504122010-09-27 14:52:15 -07002902bool InputDispatcher::transferTouchFocus(const sp<InputChannel>& fromChannel,
2903 const sp<InputChannel>& toChannel) {
2904#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002905 ALOGD("transferTouchFocus: fromChannel=%s, toChannel=%s",
Jeff Browne6504122010-09-27 14:52:15 -07002906 fromChannel->getName().string(), toChannel->getName().string());
2907#endif
2908 { // acquire lock
2909 AutoMutex _l(mLock);
2910
Jeff Brown9302c872011-07-13 22:51:29 -07002911 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromChannel);
2912 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toChannel);
2913 if (fromWindowHandle == NULL || toWindowHandle == NULL) {
Jeff Browne6504122010-09-27 14:52:15 -07002914#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002915 ALOGD("Cannot transfer focus because from or to window not found.");
Jeff Browne6504122010-09-27 14:52:15 -07002916#endif
2917 return false;
2918 }
Jeff Brown9302c872011-07-13 22:51:29 -07002919 if (fromWindowHandle == toWindowHandle) {
Jeff Browne6504122010-09-27 14:52:15 -07002920#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002921 ALOGD("Trivial transfer to same window.");
Jeff Browne6504122010-09-27 14:52:15 -07002922#endif
2923 return true;
2924 }
2925
2926 bool found = false;
2927 for (size_t i = 0; i < mTouchState.windows.size(); i++) {
2928 const TouchedWindow& touchedWindow = mTouchState.windows[i];
Jeff Brown9302c872011-07-13 22:51:29 -07002929 if (touchedWindow.windowHandle == fromWindowHandle) {
Jeff Browne6504122010-09-27 14:52:15 -07002930 int32_t oldTargetFlags = touchedWindow.targetFlags;
2931 BitSet32 pointerIds = touchedWindow.pointerIds;
2932
2933 mTouchState.windows.removeAt(i);
2934
Jeff Brown46e75292010-11-10 16:53:45 -08002935 int32_t newTargetFlags = oldTargetFlags
Jeff Browna032cc02011-03-07 16:56:21 -08002936 & (InputTarget::FLAG_FOREGROUND
2937 | InputTarget::FLAG_SPLIT | InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brown9302c872011-07-13 22:51:29 -07002938 mTouchState.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Jeff Browne6504122010-09-27 14:52:15 -07002939
2940 found = true;
2941 break;
2942 }
2943 }
2944
2945 if (! found) {
2946#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002947 ALOGD("Focus transfer failed because from window did not have focus.");
Jeff Browne6504122010-09-27 14:52:15 -07002948#endif
2949 return false;
2950 }
2951
Jeff Brown9c9f1a32010-10-11 18:32:20 -07002952 ssize_t fromConnectionIndex = getConnectionIndexLocked(fromChannel);
2953 ssize_t toConnectionIndex = getConnectionIndexLocked(toChannel);
2954 if (fromConnectionIndex >= 0 && toConnectionIndex >= 0) {
Jeff Browncbee6d62012-02-03 20:11:27 -08002955 sp<Connection> fromConnection = mConnectionsByFd.valueAt(fromConnectionIndex);
2956 sp<Connection> toConnection = mConnectionsByFd.valueAt(toConnectionIndex);
Jeff Brown9c9f1a32010-10-11 18:32:20 -07002957
2958 fromConnection->inputState.copyPointerStateTo(toConnection->inputState);
Jeff Brownda3d5a92011-03-29 15:11:34 -07002959 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Jeff Brown9c9f1a32010-10-11 18:32:20 -07002960 "transferring touch focus from this window to another window");
Jeff Brownda3d5a92011-03-29 15:11:34 -07002961 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Jeff Brown9c9f1a32010-10-11 18:32:20 -07002962 }
2963
Jeff Browne6504122010-09-27 14:52:15 -07002964#if DEBUG_FOCUS
2965 logDispatchStateLocked();
2966#endif
2967 } // release lock
2968
2969 // Wake up poll loop since it may need to make new input dispatching choices.
2970 mLooper->wake();
2971 return true;
2972}
2973
Jeff Brown120a4592010-10-27 18:43:51 -07002974void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
2975#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002976 ALOGD("Resetting and dropping all events (%s).", reason);
Jeff Brown120a4592010-10-27 18:43:51 -07002977#endif
2978
Jeff Brownda3d5a92011-03-29 15:11:34 -07002979 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
2980 synthesizeCancelationEventsForAllConnectionsLocked(options);
Jeff Brown120a4592010-10-27 18:43:51 -07002981
2982 resetKeyRepeatLocked();
2983 releasePendingEventLocked();
2984 drainInboundQueueLocked();
Jeff Browne9bb9be2012-02-06 15:47:55 -08002985 resetANRTimeoutsLocked();
Jeff Brown120a4592010-10-27 18:43:51 -07002986
2987 mTouchState.reset();
Jeff Brown9302c872011-07-13 22:51:29 -07002988 mLastHoverWindowHandle.clear();
Jeff Brown120a4592010-10-27 18:43:51 -07002989}
2990
Jeff Brownb88102f2010-09-08 11:49:43 -07002991void InputDispatcher::logDispatchStateLocked() {
2992 String8 dump;
2993 dumpDispatchStateLocked(dump);
Jeff Brown2a95c2a2010-09-16 12:31:46 -07002994
2995 char* text = dump.lockBuffer(dump.size());
2996 char* start = text;
2997 while (*start != '\0') {
2998 char* end = strchr(start, '\n');
2999 if (*end == '\n') {
3000 *(end++) = '\0';
3001 }
Steve Block5baa3a62011-12-20 16:23:08 +00003002 ALOGD("%s", start);
Jeff Brown2a95c2a2010-09-16 12:31:46 -07003003 start = end;
3004 }
Jeff Brownb88102f2010-09-08 11:49:43 -07003005}
3006
3007void InputDispatcher::dumpDispatchStateLocked(String8& dump) {
Jeff Brownf2f48712010-10-01 17:46:21 -07003008 dump.appendFormat(INDENT "DispatchEnabled: %d\n", mDispatchEnabled);
3009 dump.appendFormat(INDENT "DispatchFrozen: %d\n", mDispatchFrozen);
Jeff Brownb88102f2010-09-08 11:49:43 -07003010
Jeff Brown9302c872011-07-13 22:51:29 -07003011 if (mFocusedApplicationHandle != NULL) {
Jeff Brownf2f48712010-10-01 17:46:21 -07003012 dump.appendFormat(INDENT "FocusedApplication: name='%s', dispatchingTimeout=%0.3fms\n",
Jeff Browncc4f7db2011-08-30 20:34:48 -07003013 mFocusedApplicationHandle->getName().string(),
3014 mFocusedApplicationHandle->getDispatchingTimeout(
3015 DEFAULT_INPUT_DISPATCHING_TIMEOUT) / 1000000.0);
Jeff Brownb88102f2010-09-08 11:49:43 -07003016 } else {
Jeff Brownf2f48712010-10-01 17:46:21 -07003017 dump.append(INDENT "FocusedApplication: <null>\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003018 }
Jeff Brownf2f48712010-10-01 17:46:21 -07003019 dump.appendFormat(INDENT "FocusedWindow: name='%s'\n",
Jeff Browncc4f7db2011-08-30 20:34:48 -07003020 mFocusedWindowHandle != NULL ? mFocusedWindowHandle->getName().string() : "<null>");
Jeff Brownf2f48712010-10-01 17:46:21 -07003021
3022 dump.appendFormat(INDENT "TouchDown: %s\n", toString(mTouchState.down));
3023 dump.appendFormat(INDENT "TouchSplit: %s\n", toString(mTouchState.split));
Jeff Brown95712852011-01-04 19:41:59 -08003024 dump.appendFormat(INDENT "TouchDeviceId: %d\n", mTouchState.deviceId);
Jeff Brown58a2da82011-01-25 16:02:22 -08003025 dump.appendFormat(INDENT "TouchSource: 0x%08x\n", mTouchState.source);
Jeff Brownf2f48712010-10-01 17:46:21 -07003026 if (!mTouchState.windows.isEmpty()) {
3027 dump.append(INDENT "TouchedWindows:\n");
3028 for (size_t i = 0; i < mTouchState.windows.size(); i++) {
3029 const TouchedWindow& touchedWindow = mTouchState.windows[i];
3030 dump.appendFormat(INDENT2 "%d: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
Jeff Browncc4f7db2011-08-30 20:34:48 -07003031 i, touchedWindow.windowHandle->getName().string(),
3032 touchedWindow.pointerIds.value,
Jeff Brownf2f48712010-10-01 17:46:21 -07003033 touchedWindow.targetFlags);
3034 }
3035 } else {
3036 dump.append(INDENT "TouchedWindows: <none>\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003037 }
3038
Jeff Brown9302c872011-07-13 22:51:29 -07003039 if (!mWindowHandles.isEmpty()) {
Jeff Brownf2f48712010-10-01 17:46:21 -07003040 dump.append(INDENT "Windows:\n");
Jeff Brown9302c872011-07-13 22:51:29 -07003041 for (size_t i = 0; i < mWindowHandles.size(); i++) {
3042 const sp<InputWindowHandle>& windowHandle = mWindowHandles.itemAt(i);
Jeff Browncc4f7db2011-08-30 20:34:48 -07003043 const InputWindowInfo* windowInfo = windowHandle->getInfo();
3044
Jeff Brownf2f48712010-10-01 17:46:21 -07003045 dump.appendFormat(INDENT2 "%d: name='%s', paused=%s, hasFocus=%s, hasWallpaper=%s, "
3046 "visible=%s, canReceiveKeys=%s, flags=0x%08x, type=0x%08x, layer=%d, "
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003047 "frame=[%d,%d][%d,%d], scale=%f, "
Jeff Brownfbf09772011-01-16 14:06:57 -08003048 "touchableRegion=",
Jeff Browncc4f7db2011-08-30 20:34:48 -07003049 i, windowInfo->name.string(),
3050 toString(windowInfo->paused),
3051 toString(windowInfo->hasFocus),
3052 toString(windowInfo->hasWallpaper),
3053 toString(windowInfo->visible),
3054 toString(windowInfo->canReceiveKeys),
3055 windowInfo->layoutParamsFlags, windowInfo->layoutParamsType,
3056 windowInfo->layer,
3057 windowInfo->frameLeft, windowInfo->frameTop,
3058 windowInfo->frameRight, windowInfo->frameBottom,
3059 windowInfo->scaleFactor);
3060 dumpRegion(dump, windowInfo->touchableRegion);
3061 dump.appendFormat(", inputFeatures=0x%08x", windowInfo->inputFeatures);
Jeff Brownfbf09772011-01-16 14:06:57 -08003062 dump.appendFormat(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%0.3fms\n",
Jeff Browncc4f7db2011-08-30 20:34:48 -07003063 windowInfo->ownerPid, windowInfo->ownerUid,
3064 windowInfo->dispatchingTimeout / 1000000.0);
Jeff Brownf2f48712010-10-01 17:46:21 -07003065 }
3066 } else {
3067 dump.append(INDENT "Windows: <none>\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003068 }
3069
Jeff Brownf2f48712010-10-01 17:46:21 -07003070 if (!mMonitoringChannels.isEmpty()) {
3071 dump.append(INDENT "MonitoringChannels:\n");
3072 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
3073 const sp<InputChannel>& channel = mMonitoringChannels[i];
3074 dump.appendFormat(INDENT2 "%d: '%s'\n", i, channel->getName().string());
3075 }
3076 } else {
3077 dump.append(INDENT "MonitoringChannels: <none>\n");
3078 }
Jeff Brown519e0242010-09-15 15:18:56 -07003079
Jeff Brownf2f48712010-10-01 17:46:21 -07003080 dump.appendFormat(INDENT "InboundQueue: length=%u\n", mInboundQueue.count());
3081
Jeff Brownb88102f2010-09-08 11:49:43 -07003082 if (isAppSwitchPendingLocked()) {
Jeff Brownf2f48712010-10-01 17:46:21 -07003083 dump.appendFormat(INDENT "AppSwitch: pending, due in %01.1fms\n",
Jeff Brownb88102f2010-09-08 11:49:43 -07003084 (mAppSwitchDueTime - now()) / 1000000.0);
3085 } else {
Jeff Brownf2f48712010-10-01 17:46:21 -07003086 dump.append(INDENT "AppSwitch: not pending\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003087 }
3088}
3089
Jeff Brown928e0542011-01-10 11:17:36 -08003090status_t InputDispatcher::registerInputChannel(const sp<InputChannel>& inputChannel,
3091 const sp<InputWindowHandle>& inputWindowHandle, bool monitor) {
Jeff Brown9c3cda02010-06-15 01:31:58 -07003092#if DEBUG_REGISTRATION
Steve Block5baa3a62011-12-20 16:23:08 +00003093 ALOGD("channel '%s' ~ registerInputChannel - monitor=%s", inputChannel->getName().string(),
Jeff Brownb88102f2010-09-08 11:49:43 -07003094 toString(monitor));
Jeff Brown9c3cda02010-06-15 01:31:58 -07003095#endif
3096
Jeff Brown46b9ac02010-04-22 18:58:52 -07003097 { // acquire lock
3098 AutoMutex _l(mLock);
3099
Jeff Brown519e0242010-09-15 15:18:56 -07003100 if (getConnectionIndexLocked(inputChannel) >= 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00003101 ALOGW("Attempted to register already registered input channel '%s'",
Jeff Brown46b9ac02010-04-22 18:58:52 -07003102 inputChannel->getName().string());
3103 return BAD_VALUE;
3104 }
3105
Jeff Browncc4f7db2011-08-30 20:34:48 -07003106 sp<Connection> connection = new Connection(inputChannel, inputWindowHandle, monitor);
Jeff Brown46b9ac02010-04-22 18:58:52 -07003107
Jeff Brown91e32892012-02-14 15:56:29 -08003108 int fd = inputChannel->getFd();
Jeff Browncbee6d62012-02-03 20:11:27 -08003109 mConnectionsByFd.add(fd, connection);
Jeff Brown9c3cda02010-06-15 01:31:58 -07003110
Jeff Brownb88102f2010-09-08 11:49:43 -07003111 if (monitor) {
3112 mMonitoringChannels.push(inputChannel);
3113 }
3114
Jeff Browncbee6d62012-02-03 20:11:27 -08003115 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
Jeff Brown2cbecea2010-08-17 15:59:26 -07003116
Jeff Brown9c3cda02010-06-15 01:31:58 -07003117 runCommandsLockedInterruptible();
Jeff Brown46b9ac02010-04-22 18:58:52 -07003118 } // release lock
Jeff Brown46b9ac02010-04-22 18:58:52 -07003119 return OK;
3120}
3121
3122status_t InputDispatcher::unregisterInputChannel(const sp<InputChannel>& inputChannel) {
Jeff Brown9c3cda02010-06-15 01:31:58 -07003123#if DEBUG_REGISTRATION
Steve Block5baa3a62011-12-20 16:23:08 +00003124 ALOGD("channel '%s' ~ unregisterInputChannel", inputChannel->getName().string());
Jeff Brown9c3cda02010-06-15 01:31:58 -07003125#endif
3126
Jeff Brown46b9ac02010-04-22 18:58:52 -07003127 { // acquire lock
3128 AutoMutex _l(mLock);
3129
Jeff Browncc4f7db2011-08-30 20:34:48 -07003130 status_t status = unregisterInputChannelLocked(inputChannel, false /*notify*/);
3131 if (status) {
3132 return status;
Jeff Brown46b9ac02010-04-22 18:58:52 -07003133 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07003134 } // release lock
3135
Jeff Brown46b9ac02010-04-22 18:58:52 -07003136 // Wake the poll loop because removing the connection may have changed the current
3137 // synchronization state.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07003138 mLooper->wake();
Jeff Brown46b9ac02010-04-22 18:58:52 -07003139 return OK;
3140}
3141
Jeff Browncc4f7db2011-08-30 20:34:48 -07003142status_t InputDispatcher::unregisterInputChannelLocked(const sp<InputChannel>& inputChannel,
3143 bool notify) {
3144 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
3145 if (connectionIndex < 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00003146 ALOGW("Attempted to unregister already unregistered input channel '%s'",
Jeff Browncc4f7db2011-08-30 20:34:48 -07003147 inputChannel->getName().string());
3148 return BAD_VALUE;
3149 }
3150
Jeff Browncbee6d62012-02-03 20:11:27 -08003151 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
3152 mConnectionsByFd.removeItemsAt(connectionIndex);
Jeff Browncc4f7db2011-08-30 20:34:48 -07003153
3154 if (connection->monitor) {
3155 removeMonitorChannelLocked(inputChannel);
3156 }
3157
Jeff Browncbee6d62012-02-03 20:11:27 -08003158 mLooper->removeFd(inputChannel->getFd());
Jeff Browncc4f7db2011-08-30 20:34:48 -07003159
3160 nsecs_t currentTime = now();
3161 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
3162
3163 runCommandsLockedInterruptible();
3164
3165 connection->status = Connection::STATUS_ZOMBIE;
3166 return OK;
3167}
3168
3169void InputDispatcher::removeMonitorChannelLocked(const sp<InputChannel>& inputChannel) {
3170 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
3171 if (mMonitoringChannels[i] == inputChannel) {
3172 mMonitoringChannels.removeAt(i);
3173 break;
3174 }
3175 }
3176}
3177
Jeff Brown519e0242010-09-15 15:18:56 -07003178ssize_t InputDispatcher::getConnectionIndexLocked(const sp<InputChannel>& inputChannel) {
Jeff Browncbee6d62012-02-03 20:11:27 -08003179 ssize_t connectionIndex = mConnectionsByFd.indexOfKey(inputChannel->getFd());
Jeff Brown2cbecea2010-08-17 15:59:26 -07003180 if (connectionIndex >= 0) {
Jeff Browncbee6d62012-02-03 20:11:27 -08003181 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
Jeff Brown2cbecea2010-08-17 15:59:26 -07003182 if (connection->inputChannel.get() == inputChannel.get()) {
3183 return connectionIndex;
3184 }
3185 }
3186
3187 return -1;
3188}
3189
Jeff Brown9c3cda02010-06-15 01:31:58 -07003190void InputDispatcher::onDispatchCycleFinishedLocked(
Jeff Brown072ec962012-02-07 14:46:57 -08003191 nsecs_t currentTime, const sp<Connection>& connection, uint32_t seq, bool handled) {
Jeff Brown3915bb82010-11-05 15:02:16 -07003192 CommandEntry* commandEntry = postCommandLocked(
3193 & InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
3194 commandEntry->connection = connection;
Jeff Brown072ec962012-02-07 14:46:57 -08003195 commandEntry->seq = seq;
Jeff Brown3915bb82010-11-05 15:02:16 -07003196 commandEntry->handled = handled;
Jeff Brown46b9ac02010-04-22 18:58:52 -07003197}
3198
Jeff Brown9c3cda02010-06-15 01:31:58 -07003199void InputDispatcher::onDispatchCycleBrokenLocked(
Jeff Brown7fbdc842010-06-17 20:52:56 -07003200 nsecs_t currentTime, const sp<Connection>& connection) {
Steve Block3762c312012-01-06 19:20:56 +00003201 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Jeff Brown46b9ac02010-04-22 18:58:52 -07003202 connection->getInputChannelName());
3203
Jeff Brown9c3cda02010-06-15 01:31:58 -07003204 CommandEntry* commandEntry = postCommandLocked(
3205 & InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
Jeff Brown7fbdc842010-06-17 20:52:56 -07003206 commandEntry->connection = connection;
Jeff Brown46b9ac02010-04-22 18:58:52 -07003207}
3208
Jeff Brown519e0242010-09-15 15:18:56 -07003209void InputDispatcher::onANRLocked(
Jeff Brown9302c872011-07-13 22:51:29 -07003210 nsecs_t currentTime, const sp<InputApplicationHandle>& applicationHandle,
3211 const sp<InputWindowHandle>& windowHandle,
Jeff Brown519e0242010-09-15 15:18:56 -07003212 nsecs_t eventTime, nsecs_t waitStartTime) {
Steve Block6215d3f2012-01-04 20:05:49 +00003213 ALOGI("Application is not responding: %s. "
Jeff Brown519e0242010-09-15 15:18:56 -07003214 "%01.1fms since event, %01.1fms since wait started",
Jeff Brown9302c872011-07-13 22:51:29 -07003215 getApplicationWindowLabelLocked(applicationHandle, windowHandle).string(),
Jeff Brown519e0242010-09-15 15:18:56 -07003216 (currentTime - eventTime) / 1000000.0,
3217 (currentTime - waitStartTime) / 1000000.0);
3218
3219 CommandEntry* commandEntry = postCommandLocked(
3220 & InputDispatcher::doNotifyANRLockedInterruptible);
Jeff Brown9302c872011-07-13 22:51:29 -07003221 commandEntry->inputApplicationHandle = applicationHandle;
3222 commandEntry->inputWindowHandle = windowHandle;
Jeff Brown519e0242010-09-15 15:18:56 -07003223}
3224
Jeff Brownb88102f2010-09-08 11:49:43 -07003225void InputDispatcher::doNotifyConfigurationChangedInterruptible(
3226 CommandEntry* commandEntry) {
3227 mLock.unlock();
3228
3229 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
3230
3231 mLock.lock();
3232}
3233
Jeff Brown9c3cda02010-06-15 01:31:58 -07003234void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(
3235 CommandEntry* commandEntry) {
Jeff Brown7fbdc842010-06-17 20:52:56 -07003236 sp<Connection> connection = commandEntry->connection;
Jeff Brown9c3cda02010-06-15 01:31:58 -07003237
Jeff Brown7fbdc842010-06-17 20:52:56 -07003238 if (connection->status != Connection::STATUS_ZOMBIE) {
3239 mLock.unlock();
Jeff Brown9c3cda02010-06-15 01:31:58 -07003240
Jeff Brown928e0542011-01-10 11:17:36 -08003241 mPolicy->notifyInputChannelBroken(connection->inputWindowHandle);
Jeff Brown7fbdc842010-06-17 20:52:56 -07003242
3243 mLock.lock();
3244 }
Jeff Brown9c3cda02010-06-15 01:31:58 -07003245}
3246
Jeff Brown519e0242010-09-15 15:18:56 -07003247void InputDispatcher::doNotifyANRLockedInterruptible(
Jeff Brown9c3cda02010-06-15 01:31:58 -07003248 CommandEntry* commandEntry) {
Jeff Brown519e0242010-09-15 15:18:56 -07003249 mLock.unlock();
Jeff Brown9c3cda02010-06-15 01:31:58 -07003250
Jeff Brown519e0242010-09-15 15:18:56 -07003251 nsecs_t newTimeout = mPolicy->notifyANR(
Jeff Brown928e0542011-01-10 11:17:36 -08003252 commandEntry->inputApplicationHandle, commandEntry->inputWindowHandle);
Jeff Brown9c3cda02010-06-15 01:31:58 -07003253
Jeff Brown519e0242010-09-15 15:18:56 -07003254 mLock.lock();
Jeff Brown7fbdc842010-06-17 20:52:56 -07003255
Jeff Brown9302c872011-07-13 22:51:29 -07003256 resumeAfterTargetsNotReadyTimeoutLocked(newTimeout,
3257 commandEntry->inputWindowHandle != NULL
Jeff Browncc4f7db2011-08-30 20:34:48 -07003258 ? commandEntry->inputWindowHandle->getInputChannel() : NULL);
Jeff Brown9c3cda02010-06-15 01:31:58 -07003259}
3260
Jeff Brownb88102f2010-09-08 11:49:43 -07003261void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
3262 CommandEntry* commandEntry) {
3263 KeyEntry* entry = commandEntry->keyEntry;
Jeff Brown1f245102010-11-18 20:53:46 -08003264
3265 KeyEvent event;
3266 initializeKeyEvent(&event, entry);
Jeff Brownb88102f2010-09-08 11:49:43 -07003267
3268 mLock.unlock();
3269
Jeff Brown905805a2011-10-12 13:57:59 -07003270 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(commandEntry->inputWindowHandle,
Jeff Brown1f245102010-11-18 20:53:46 -08003271 &event, entry->policyFlags);
Jeff Brownb88102f2010-09-08 11:49:43 -07003272
3273 mLock.lock();
3274
Jeff Brown905805a2011-10-12 13:57:59 -07003275 if (delay < 0) {
3276 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
3277 } else if (!delay) {
3278 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
3279 } else {
3280 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
3281 entry->interceptKeyWakeupTime = now() + delay;
3282 }
Jeff Brownac386072011-07-20 15:19:50 -07003283 entry->release();
Jeff Brownb88102f2010-09-08 11:49:43 -07003284}
3285
Jeff Brown3915bb82010-11-05 15:02:16 -07003286void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(
3287 CommandEntry* commandEntry) {
3288 sp<Connection> connection = commandEntry->connection;
Jeff Brown072ec962012-02-07 14:46:57 -08003289 uint32_t seq = commandEntry->seq;
Jeff Brown3915bb82010-11-05 15:02:16 -07003290 bool handled = commandEntry->handled;
3291
Jeff Brown072ec962012-02-07 14:46:57 -08003292 // Handle post-event policy actions.
3293 DispatchEntry* dispatchEntry = connection->findWaitQueueEntry(seq);
3294 if (dispatchEntry) {
Jeff Brownd1c48a02012-02-06 19:12:47 -08003295 bool restartEvent;
Jeff Brownd1c48a02012-02-06 19:12:47 -08003296 if (dispatchEntry->eventEntry->type == EventEntry::TYPE_KEY) {
3297 KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry);
3298 restartEvent = afterKeyEventLockedInterruptible(connection,
3299 dispatchEntry, keyEntry, handled);
3300 } else if (dispatchEntry->eventEntry->type == EventEntry::TYPE_MOTION) {
3301 MotionEntry* motionEntry = static_cast<MotionEntry*>(dispatchEntry->eventEntry);
3302 restartEvent = afterMotionEventLockedInterruptible(connection,
3303 dispatchEntry, motionEntry, handled);
3304 } else {
3305 restartEvent = false;
3306 }
3307
3308 // Dequeue the event and start the next cycle.
3309 // Note that because the lock might have been released, it is possible that the
3310 // contents of the wait queue to have been drained, so we need to double-check
3311 // a few things.
Jeff Brown072ec962012-02-07 14:46:57 -08003312 if (dispatchEntry == connection->findWaitQueueEntry(seq)) {
3313 connection->waitQueue.dequeue(dispatchEntry);
Jeff Brownd1c48a02012-02-06 19:12:47 -08003314 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
3315 connection->outboundQueue.enqueueAtHead(dispatchEntry);
3316 } else {
3317 releaseDispatchEntryLocked(dispatchEntry);
Jeff Brown49ed71d2010-12-06 17:13:33 -08003318 }
Jeff Brown3915bb82010-11-05 15:02:16 -07003319 }
Jeff Brown3915bb82010-11-05 15:02:16 -07003320
Jeff Brownd1c48a02012-02-06 19:12:47 -08003321 // Start the next dispatch cycle for this connection.
3322 startDispatchCycleLocked(now(), connection);
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003323 }
3324}
3325
3326bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
3327 DispatchEntry* dispatchEntry, KeyEntry* keyEntry, bool handled) {
3328 if (!(keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK)) {
3329 // Get the fallback key state.
3330 // Clear it out after dispatching the UP.
3331 int32_t originalKeyCode = keyEntry->keyCode;
3332 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
3333 if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
3334 connection->inputState.removeFallbackKey(originalKeyCode);
3335 }
3336
3337 if (handled || !dispatchEntry->hasForegroundTarget()) {
3338 // If the application handles the original key for which we previously
3339 // generated a fallback or if the window is not a foreground window,
3340 // then cancel the associated fallback key, if any.
3341 if (fallbackKeyCode != -1) {
3342 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
3343 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
3344 "application handled the original non-fallback key "
3345 "or is no longer a foreground target, "
3346 "canceling previously dispatched fallback key");
3347 options.keyCode = fallbackKeyCode;
3348 synthesizeCancelationEventsForConnectionLocked(connection, options);
3349 }
3350 connection->inputState.removeFallbackKey(originalKeyCode);
3351 }
3352 } else {
3353 // If the application did not handle a non-fallback key, first check
3354 // that we are in a good state to perform unhandled key event processing
3355 // Then ask the policy what to do with it.
3356 bool initialDown = keyEntry->action == AKEY_EVENT_ACTION_DOWN
3357 && keyEntry->repeatCount == 0;
3358 if (fallbackKeyCode == -1 && !initialDown) {
3359#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00003360 ALOGD("Unhandled key event: Skipping unhandled key event processing "
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003361 "since this is not an initial down. "
3362 "keyCode=%d, action=%d, repeatCount=%d",
3363 originalKeyCode, keyEntry->action, keyEntry->repeatCount);
3364#endif
3365 return false;
3366 }
3367
3368 // Dispatch the unhandled key to the policy.
3369#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00003370 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003371 "keyCode=%d, action=%d, repeatCount=%d",
3372 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount);
3373#endif
3374 KeyEvent event;
3375 initializeKeyEvent(&event, keyEntry);
3376
3377 mLock.unlock();
3378
3379 bool fallback = mPolicy->dispatchUnhandledKey(connection->inputWindowHandle,
3380 &event, keyEntry->policyFlags, &event);
3381
3382 mLock.lock();
3383
3384 if (connection->status != Connection::STATUS_NORMAL) {
3385 connection->inputState.removeFallbackKey(originalKeyCode);
Jeff Brownd1c48a02012-02-06 19:12:47 -08003386 return false;
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003387 }
3388
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003389 // Latch the fallback keycode for this key on an initial down.
3390 // The fallback keycode cannot change at any other point in the lifecycle.
3391 if (initialDown) {
3392 if (fallback) {
3393 fallbackKeyCode = event.getKeyCode();
3394 } else {
3395 fallbackKeyCode = AKEYCODE_UNKNOWN;
3396 }
3397 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
3398 }
3399
Steve Blockec193de2012-01-09 18:35:44 +00003400 ALOG_ASSERT(fallbackKeyCode != -1);
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003401
3402 // Cancel the fallback key if the policy decides not to send it anymore.
3403 // We will continue to dispatch the key to the policy but we will no
3404 // longer dispatch a fallback key to the application.
3405 if (fallbackKeyCode != AKEYCODE_UNKNOWN
3406 && (!fallback || fallbackKeyCode != event.getKeyCode())) {
3407#if DEBUG_OUTBOUND_EVENT_DETAILS
3408 if (fallback) {
Steve Block5baa3a62011-12-20 16:23:08 +00003409 ALOGD("Unhandled key event: Policy requested to send key %d"
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003410 "as a fallback for %d, but on the DOWN it had requested "
3411 "to send %d instead. Fallback canceled.",
3412 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
3413 } else {
Steve Block5baa3a62011-12-20 16:23:08 +00003414 ALOGD("Unhandled key event: Policy did not request fallback for %d,"
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003415 "but on the DOWN it had requested to send %d. "
3416 "Fallback canceled.",
3417 originalKeyCode, fallbackKeyCode);
3418 }
3419#endif
3420
3421 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
3422 "canceling fallback, policy no longer desires it");
3423 options.keyCode = fallbackKeyCode;
3424 synthesizeCancelationEventsForConnectionLocked(connection, options);
3425
3426 fallback = false;
3427 fallbackKeyCode = AKEYCODE_UNKNOWN;
3428 if (keyEntry->action != AKEY_EVENT_ACTION_UP) {
3429 connection->inputState.setFallbackKey(originalKeyCode,
3430 fallbackKeyCode);
3431 }
3432 }
3433
3434#if DEBUG_OUTBOUND_EVENT_DETAILS
3435 {
3436 String8 msg;
3437 const KeyedVector<int32_t, int32_t>& fallbackKeys =
3438 connection->inputState.getFallbackKeys();
3439 for (size_t i = 0; i < fallbackKeys.size(); i++) {
3440 msg.appendFormat(", %d->%d", fallbackKeys.keyAt(i),
3441 fallbackKeys.valueAt(i));
3442 }
Steve Block5baa3a62011-12-20 16:23:08 +00003443 ALOGD("Unhandled key event: %d currently tracked fallback keys%s.",
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003444 fallbackKeys.size(), msg.string());
3445 }
3446#endif
3447
3448 if (fallback) {
3449 // Restart the dispatch cycle using the fallback key.
3450 keyEntry->eventTime = event.getEventTime();
3451 keyEntry->deviceId = event.getDeviceId();
3452 keyEntry->source = event.getSource();
3453 keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
3454 keyEntry->keyCode = fallbackKeyCode;
3455 keyEntry->scanCode = event.getScanCode();
3456 keyEntry->metaState = event.getMetaState();
3457 keyEntry->repeatCount = event.getRepeatCount();
3458 keyEntry->downTime = event.getDownTime();
3459 keyEntry->syntheticRepeat = false;
3460
3461#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00003462 ALOGD("Unhandled key event: Dispatching fallback key. "
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003463 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
3464 originalKeyCode, fallbackKeyCode, keyEntry->metaState);
3465#endif
Jeff Brownd1c48a02012-02-06 19:12:47 -08003466 return true; // restart the event
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003467 } else {
3468#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00003469 ALOGD("Unhandled key event: No fallback key.");
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003470#endif
3471 }
3472 }
3473 }
3474 return false;
3475}
3476
3477bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
3478 DispatchEntry* dispatchEntry, MotionEntry* motionEntry, bool handled) {
3479 return false;
Jeff Brown3915bb82010-11-05 15:02:16 -07003480}
3481
Jeff Brownb88102f2010-09-08 11:49:43 -07003482void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
3483 mLock.unlock();
3484
Jeff Brown01ce2e92010-09-26 22:20:12 -07003485 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
Jeff Brownb88102f2010-09-08 11:49:43 -07003486
3487 mLock.lock();
3488}
3489
Jeff Brown3915bb82010-11-05 15:02:16 -07003490void InputDispatcher::initializeKeyEvent(KeyEvent* event, const KeyEntry* entry) {
3491 event->initialize(entry->deviceId, entry->source, entry->action, entry->flags,
3492 entry->keyCode, entry->scanCode, entry->metaState, entry->repeatCount,
3493 entry->downTime, entry->eventTime);
3494}
3495
Jeff Brown519e0242010-09-15 15:18:56 -07003496void InputDispatcher::updateDispatchStatisticsLocked(nsecs_t currentTime, const EventEntry* entry,
3497 int32_t injectionResult, nsecs_t timeSpentWaitingForApplication) {
3498 // TODO Write some statistics about how long we spend waiting.
Jeff Brownb88102f2010-09-08 11:49:43 -07003499}
3500
3501void InputDispatcher::dump(String8& dump) {
Jeff Brown89ef0722011-08-10 16:25:21 -07003502 AutoMutex _l(mLock);
3503
Jeff Brownf2f48712010-10-01 17:46:21 -07003504 dump.append("Input Dispatcher State:\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003505 dumpDispatchStateLocked(dump);
Jeff Brown214eaf42011-05-26 19:17:02 -07003506
3507 dump.append(INDENT "Configuration:\n");
Jeff Brown214eaf42011-05-26 19:17:02 -07003508 dump.appendFormat(INDENT2 "KeyRepeatDelay: %0.1fms\n", mConfig.keyRepeatDelay * 0.000001f);
3509 dump.appendFormat(INDENT2 "KeyRepeatTimeout: %0.1fms\n", mConfig.keyRepeatTimeout * 0.000001f);
Jeff Brownb88102f2010-09-08 11:49:43 -07003510}
3511
Jeff Brown89ef0722011-08-10 16:25:21 -07003512void InputDispatcher::monitor() {
3513 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
3514 mLock.lock();
Jeff Brown112b5f52012-01-27 17:32:06 -08003515 mLooper->wake();
3516 mDispatcherIsAliveCondition.wait(mLock);
Jeff Brown89ef0722011-08-10 16:25:21 -07003517 mLock.unlock();
3518}
3519
Jeff Brown9c3cda02010-06-15 01:31:58 -07003520
Jeff Brown519e0242010-09-15 15:18:56 -07003521// --- InputDispatcher::Queue ---
3522
3523template <typename T>
3524uint32_t InputDispatcher::Queue<T>::count() const {
3525 uint32_t result = 0;
Jeff Brownac386072011-07-20 15:19:50 -07003526 for (const T* entry = head; entry; entry = entry->next) {
Jeff Brown519e0242010-09-15 15:18:56 -07003527 result += 1;
3528 }
3529 return result;
3530}
3531
3532
Jeff Brownac386072011-07-20 15:19:50 -07003533// --- InputDispatcher::InjectionState ---
Jeff Brown46b9ac02010-04-22 18:58:52 -07003534
Jeff Brownac386072011-07-20 15:19:50 -07003535InputDispatcher::InjectionState::InjectionState(int32_t injectorPid, int32_t injectorUid) :
3536 refCount(1),
3537 injectorPid(injectorPid), injectorUid(injectorUid),
3538 injectionResult(INPUT_EVENT_INJECTION_PENDING), injectionIsAsync(false),
3539 pendingForegroundDispatches(0) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07003540}
3541
Jeff Brownac386072011-07-20 15:19:50 -07003542InputDispatcher::InjectionState::~InjectionState() {
Jeff Brown01ce2e92010-09-26 22:20:12 -07003543}
3544
Jeff Brownac386072011-07-20 15:19:50 -07003545void InputDispatcher::InjectionState::release() {
3546 refCount -= 1;
3547 if (refCount == 0) {
3548 delete this;
3549 } else {
Steve Blockec193de2012-01-09 18:35:44 +00003550 ALOG_ASSERT(refCount > 0);
Jeff Brown01ce2e92010-09-26 22:20:12 -07003551 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07003552}
3553
Jeff Brownac386072011-07-20 15:19:50 -07003554
3555// --- InputDispatcher::EventEntry ---
3556
3557InputDispatcher::EventEntry::EventEntry(int32_t type, nsecs_t eventTime, uint32_t policyFlags) :
3558 refCount(1), type(type), eventTime(eventTime), policyFlags(policyFlags),
3559 injectionState(NULL), dispatchInProgress(false) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07003560}
3561
Jeff Brownac386072011-07-20 15:19:50 -07003562InputDispatcher::EventEntry::~EventEntry() {
3563 releaseInjectionState();
3564}
3565
3566void InputDispatcher::EventEntry::release() {
3567 refCount -= 1;
3568 if (refCount == 0) {
3569 delete this;
3570 } else {
Steve Blockec193de2012-01-09 18:35:44 +00003571 ALOG_ASSERT(refCount > 0);
Jeff Brownac386072011-07-20 15:19:50 -07003572 }
3573}
3574
3575void InputDispatcher::EventEntry::releaseInjectionState() {
3576 if (injectionState) {
3577 injectionState->release();
3578 injectionState = NULL;
3579 }
3580}
3581
3582
3583// --- InputDispatcher::ConfigurationChangedEntry ---
3584
3585InputDispatcher::ConfigurationChangedEntry::ConfigurationChangedEntry(nsecs_t eventTime) :
3586 EventEntry(TYPE_CONFIGURATION_CHANGED, eventTime, 0) {
3587}
3588
3589InputDispatcher::ConfigurationChangedEntry::~ConfigurationChangedEntry() {
3590}
3591
3592
Jeff Brown65fd2512011-08-18 11:20:58 -07003593// --- InputDispatcher::DeviceResetEntry ---
3594
3595InputDispatcher::DeviceResetEntry::DeviceResetEntry(nsecs_t eventTime, int32_t deviceId) :
3596 EventEntry(TYPE_DEVICE_RESET, eventTime, 0),
3597 deviceId(deviceId) {
3598}
3599
3600InputDispatcher::DeviceResetEntry::~DeviceResetEntry() {
3601}
3602
3603
Jeff Brownac386072011-07-20 15:19:50 -07003604// --- InputDispatcher::KeyEntry ---
3605
3606InputDispatcher::KeyEntry::KeyEntry(nsecs_t eventTime,
Jeff Brown58a2da82011-01-25 16:02:22 -08003607 int32_t deviceId, uint32_t source, uint32_t policyFlags, int32_t action,
Jeff Brown7fbdc842010-06-17 20:52:56 -07003608 int32_t flags, int32_t keyCode, int32_t scanCode, int32_t metaState,
Jeff Brownac386072011-07-20 15:19:50 -07003609 int32_t repeatCount, nsecs_t downTime) :
3610 EventEntry(TYPE_KEY, eventTime, policyFlags),
3611 deviceId(deviceId), source(source), action(action), flags(flags),
3612 keyCode(keyCode), scanCode(scanCode), metaState(metaState),
3613 repeatCount(repeatCount), downTime(downTime),
Jeff Brown905805a2011-10-12 13:57:59 -07003614 syntheticRepeat(false), interceptKeyResult(KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN),
3615 interceptKeyWakeupTime(0) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07003616}
3617
Jeff Brownac386072011-07-20 15:19:50 -07003618InputDispatcher::KeyEntry::~KeyEntry() {
3619}
Jeff Brown7fbdc842010-06-17 20:52:56 -07003620
Jeff Brownac386072011-07-20 15:19:50 -07003621void InputDispatcher::KeyEntry::recycle() {
3622 releaseInjectionState();
3623
3624 dispatchInProgress = false;
3625 syntheticRepeat = false;
3626 interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
Jeff Brown905805a2011-10-12 13:57:59 -07003627 interceptKeyWakeupTime = 0;
Jeff Brownac386072011-07-20 15:19:50 -07003628}
3629
3630
Jeff Brownae9fc032010-08-18 15:51:08 -07003631// --- InputDispatcher::MotionEntry ---
3632
Jeff Brownac386072011-07-20 15:19:50 -07003633InputDispatcher::MotionEntry::MotionEntry(nsecs_t eventTime,
3634 int32_t deviceId, uint32_t source, uint32_t policyFlags, int32_t action, int32_t flags,
3635 int32_t metaState, int32_t buttonState,
3636 int32_t edgeFlags, float xPrecision, float yPrecision,
3637 nsecs_t downTime, uint32_t pointerCount,
3638 const PointerProperties* pointerProperties, const PointerCoords* pointerCoords) :
3639 EventEntry(TYPE_MOTION, eventTime, policyFlags),
Jeff Brown3241b6b2012-02-03 15:08:02 -08003640 eventTime(eventTime),
Jeff Brownac386072011-07-20 15:19:50 -07003641 deviceId(deviceId), source(source), action(action), flags(flags),
3642 metaState(metaState), buttonState(buttonState), edgeFlags(edgeFlags),
3643 xPrecision(xPrecision), yPrecision(yPrecision),
Jeff Brown3241b6b2012-02-03 15:08:02 -08003644 downTime(downTime), pointerCount(pointerCount) {
Jeff Brownac386072011-07-20 15:19:50 -07003645 for (uint32_t i = 0; i < pointerCount; i++) {
3646 this->pointerProperties[i].copyFrom(pointerProperties[i]);
Jeff Brown3241b6b2012-02-03 15:08:02 -08003647 this->pointerCoords[i].copyFrom(pointerCoords[i]);
Jeff Brownac386072011-07-20 15:19:50 -07003648 }
3649}
3650
3651InputDispatcher::MotionEntry::~MotionEntry() {
Jeff Brownac386072011-07-20 15:19:50 -07003652}
3653
3654
3655// --- InputDispatcher::DispatchEntry ---
3656
Jeff Brown072ec962012-02-07 14:46:57 -08003657volatile int32_t InputDispatcher::DispatchEntry::sNextSeqAtomic;
3658
Jeff Brownac386072011-07-20 15:19:50 -07003659InputDispatcher::DispatchEntry::DispatchEntry(EventEntry* eventEntry,
3660 int32_t targetFlags, float xOffset, float yOffset, float scaleFactor) :
Jeff Brown072ec962012-02-07 14:46:57 -08003661 seq(nextSeq()),
Jeff Brownac386072011-07-20 15:19:50 -07003662 eventEntry(eventEntry), targetFlags(targetFlags),
3663 xOffset(xOffset), yOffset(yOffset), scaleFactor(scaleFactor),
Jeff Brown3241b6b2012-02-03 15:08:02 -08003664 resolvedAction(0), resolvedFlags(0) {
Jeff Brownac386072011-07-20 15:19:50 -07003665 eventEntry->refCount += 1;
3666}
3667
3668InputDispatcher::DispatchEntry::~DispatchEntry() {
3669 eventEntry->release();
3670}
3671
Jeff Brown072ec962012-02-07 14:46:57 -08003672uint32_t InputDispatcher::DispatchEntry::nextSeq() {
3673 // Sequence number 0 is reserved and will never be returned.
3674 uint32_t seq;
3675 do {
3676 seq = android_atomic_inc(&sNextSeqAtomic);
3677 } while (!seq);
3678 return seq;
3679}
3680
Jeff Brownb88102f2010-09-08 11:49:43 -07003681
3682// --- InputDispatcher::InputState ---
3683
Jeff Brownb6997262010-10-08 22:31:17 -07003684InputDispatcher::InputState::InputState() {
Jeff Brownb88102f2010-09-08 11:49:43 -07003685}
3686
3687InputDispatcher::InputState::~InputState() {
3688}
3689
3690bool InputDispatcher::InputState::isNeutral() const {
3691 return mKeyMementos.isEmpty() && mMotionMementos.isEmpty();
3692}
3693
Jeff Brown81346812011-06-28 20:08:48 -07003694bool InputDispatcher::InputState::isHovering(int32_t deviceId, uint32_t source) const {
3695 for (size_t i = 0; i < mMotionMementos.size(); i++) {
3696 const MotionMemento& memento = mMotionMementos.itemAt(i);
3697 if (memento.deviceId == deviceId
3698 && memento.source == source
3699 && memento.hovering) {
3700 return true;
3701 }
3702 }
3703 return false;
3704}
Jeff Brownb88102f2010-09-08 11:49:43 -07003705
Jeff Brown81346812011-06-28 20:08:48 -07003706bool InputDispatcher::InputState::trackKey(const KeyEntry* entry,
3707 int32_t action, int32_t flags) {
3708 switch (action) {
3709 case AKEY_EVENT_ACTION_UP: {
3710 if (entry->flags & AKEY_EVENT_FLAG_FALLBACK) {
3711 for (size_t i = 0; i < mFallbackKeys.size(); ) {
3712 if (mFallbackKeys.valueAt(i) == entry->keyCode) {
3713 mFallbackKeys.removeItemsAt(i);
3714 } else {
3715 i += 1;
3716 }
3717 }
3718 }
3719 ssize_t index = findKeyMemento(entry);
3720 if (index >= 0) {
3721 mKeyMementos.removeAt(index);
3722 return true;
3723 }
Jeff Brown68b909d2011-12-07 16:36:01 -08003724 /* FIXME: We can't just drop the key up event because that prevents creating
3725 * popup windows that are automatically shown when a key is held and then
3726 * dismissed when the key is released. The problem is that the popup will
3727 * not have received the original key down, so the key up will be considered
3728 * to be inconsistent with its observed state. We could perhaps handle this
3729 * by synthesizing a key down but that will cause other problems.
3730 *
3731 * So for now, allow inconsistent key up events to be dispatched.
3732 *
Jeff Brown81346812011-06-28 20:08:48 -07003733#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00003734 ALOGD("Dropping inconsistent key up event: deviceId=%d, source=%08x, "
Jeff Brown81346812011-06-28 20:08:48 -07003735 "keyCode=%d, scanCode=%d",
3736 entry->deviceId, entry->source, entry->keyCode, entry->scanCode);
3737#endif
3738 return false;
Jeff Brown68b909d2011-12-07 16:36:01 -08003739 */
3740 return true;
Jeff Brown81346812011-06-28 20:08:48 -07003741 }
3742
3743 case AKEY_EVENT_ACTION_DOWN: {
3744 ssize_t index = findKeyMemento(entry);
3745 if (index >= 0) {
3746 mKeyMementos.removeAt(index);
3747 }
3748 addKeyMemento(entry, flags);
3749 return true;
3750 }
3751
3752 default:
3753 return true;
Jeff Brownb88102f2010-09-08 11:49:43 -07003754 }
3755}
3756
Jeff Brown81346812011-06-28 20:08:48 -07003757bool InputDispatcher::InputState::trackMotion(const MotionEntry* entry,
3758 int32_t action, int32_t flags) {
3759 int32_t actionMasked = action & AMOTION_EVENT_ACTION_MASK;
3760 switch (actionMasked) {
3761 case AMOTION_EVENT_ACTION_UP:
3762 case AMOTION_EVENT_ACTION_CANCEL: {
3763 ssize_t index = findMotionMemento(entry, false /*hovering*/);
3764 if (index >= 0) {
3765 mMotionMementos.removeAt(index);
3766 return true;
Jeff Brownda3d5a92011-03-29 15:11:34 -07003767 }
Jeff Brown81346812011-06-28 20:08:48 -07003768#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00003769 ALOGD("Dropping inconsistent motion up or cancel event: deviceId=%d, source=%08x, "
Jeff Brown81346812011-06-28 20:08:48 -07003770 "actionMasked=%d",
3771 entry->deviceId, entry->source, actionMasked);
3772#endif
3773 return false;
Jeff Brownda3d5a92011-03-29 15:11:34 -07003774 }
3775
Jeff Brown81346812011-06-28 20:08:48 -07003776 case AMOTION_EVENT_ACTION_DOWN: {
3777 ssize_t index = findMotionMemento(entry, false /*hovering*/);
3778 if (index >= 0) {
3779 mMotionMementos.removeAt(index);
3780 }
3781 addMotionMemento(entry, flags, false /*hovering*/);
3782 return true;
3783 }
3784
3785 case AMOTION_EVENT_ACTION_POINTER_UP:
3786 case AMOTION_EVENT_ACTION_POINTER_DOWN:
3787 case AMOTION_EVENT_ACTION_MOVE: {
3788 ssize_t index = findMotionMemento(entry, false /*hovering*/);
3789 if (index >= 0) {
3790 MotionMemento& memento = mMotionMementos.editItemAt(index);
3791 memento.setPointers(entry);
3792 return true;
3793 }
Jeff Brown2e45fb62011-06-29 21:19:05 -07003794 if (actionMasked == AMOTION_EVENT_ACTION_MOVE
3795 && (entry->source & (AINPUT_SOURCE_CLASS_JOYSTICK
3796 | AINPUT_SOURCE_CLASS_NAVIGATION))) {
3797 // Joysticks and trackballs can send MOVE events without corresponding DOWN or UP.
3798 return true;
3799 }
Jeff Brown81346812011-06-28 20:08:48 -07003800#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00003801 ALOGD("Dropping inconsistent motion pointer up/down or move event: "
Jeff Brown81346812011-06-28 20:08:48 -07003802 "deviceId=%d, source=%08x, actionMasked=%d",
3803 entry->deviceId, entry->source, actionMasked);
3804#endif
3805 return false;
3806 }
3807
3808 case AMOTION_EVENT_ACTION_HOVER_EXIT: {
3809 ssize_t index = findMotionMemento(entry, true /*hovering*/);
3810 if (index >= 0) {
3811 mMotionMementos.removeAt(index);
3812 return true;
3813 }
3814#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00003815 ALOGD("Dropping inconsistent motion hover exit event: deviceId=%d, source=%08x",
Jeff Brown81346812011-06-28 20:08:48 -07003816 entry->deviceId, entry->source);
3817#endif
3818 return false;
3819 }
3820
3821 case AMOTION_EVENT_ACTION_HOVER_ENTER:
3822 case AMOTION_EVENT_ACTION_HOVER_MOVE: {
3823 ssize_t index = findMotionMemento(entry, true /*hovering*/);
3824 if (index >= 0) {
3825 mMotionMementos.removeAt(index);
3826 }
3827 addMotionMemento(entry, flags, true /*hovering*/);
3828 return true;
3829 }
3830
3831 default:
3832 return true;
3833 }
3834}
3835
3836ssize_t InputDispatcher::InputState::findKeyMemento(const KeyEntry* entry) const {
Jeff Brownb88102f2010-09-08 11:49:43 -07003837 for (size_t i = 0; i < mKeyMementos.size(); i++) {
Jeff Brown81346812011-06-28 20:08:48 -07003838 const KeyMemento& memento = mKeyMementos.itemAt(i);
Jeff Brownb88102f2010-09-08 11:49:43 -07003839 if (memento.deviceId == entry->deviceId
3840 && memento.source == entry->source
3841 && memento.keyCode == entry->keyCode
3842 && memento.scanCode == entry->scanCode) {
Jeff Brown81346812011-06-28 20:08:48 -07003843 return i;
Jeff Brownb88102f2010-09-08 11:49:43 -07003844 }
3845 }
Jeff Brown81346812011-06-28 20:08:48 -07003846 return -1;
Jeff Brownb88102f2010-09-08 11:49:43 -07003847}
3848
Jeff Brown81346812011-06-28 20:08:48 -07003849ssize_t InputDispatcher::InputState::findMotionMemento(const MotionEntry* entry,
3850 bool hovering) const {
Jeff Brownb88102f2010-09-08 11:49:43 -07003851 for (size_t i = 0; i < mMotionMementos.size(); i++) {
Jeff Brown81346812011-06-28 20:08:48 -07003852 const MotionMemento& memento = mMotionMementos.itemAt(i);
Jeff Brownb88102f2010-09-08 11:49:43 -07003853 if (memento.deviceId == entry->deviceId
Jeff Brown81346812011-06-28 20:08:48 -07003854 && memento.source == entry->source
3855 && memento.hovering == hovering) {
3856 return i;
Jeff Brownb88102f2010-09-08 11:49:43 -07003857 }
3858 }
Jeff Brown81346812011-06-28 20:08:48 -07003859 return -1;
3860}
Jeff Brownb88102f2010-09-08 11:49:43 -07003861
Jeff Brown81346812011-06-28 20:08:48 -07003862void InputDispatcher::InputState::addKeyMemento(const KeyEntry* entry, int32_t flags) {
3863 mKeyMementos.push();
3864 KeyMemento& memento = mKeyMementos.editTop();
3865 memento.deviceId = entry->deviceId;
3866 memento.source = entry->source;
3867 memento.keyCode = entry->keyCode;
3868 memento.scanCode = entry->scanCode;
3869 memento.flags = flags;
3870 memento.downTime = entry->downTime;
3871}
3872
3873void InputDispatcher::InputState::addMotionMemento(const MotionEntry* entry,
3874 int32_t flags, bool hovering) {
3875 mMotionMementos.push();
3876 MotionMemento& memento = mMotionMementos.editTop();
3877 memento.deviceId = entry->deviceId;
3878 memento.source = entry->source;
3879 memento.flags = flags;
3880 memento.xPrecision = entry->xPrecision;
3881 memento.yPrecision = entry->yPrecision;
3882 memento.downTime = entry->downTime;
3883 memento.setPointers(entry);
3884 memento.hovering = hovering;
Jeff Brownb88102f2010-09-08 11:49:43 -07003885}
3886
3887void InputDispatcher::InputState::MotionMemento::setPointers(const MotionEntry* entry) {
3888 pointerCount = entry->pointerCount;
3889 for (uint32_t i = 0; i < entry->pointerCount; i++) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003890 pointerProperties[i].copyFrom(entry->pointerProperties[i]);
Jeff Brown3241b6b2012-02-03 15:08:02 -08003891 pointerCoords[i].copyFrom(entry->pointerCoords[i]);
Jeff Brownb88102f2010-09-08 11:49:43 -07003892 }
3893}
3894
Jeff Brownb6997262010-10-08 22:31:17 -07003895void InputDispatcher::InputState::synthesizeCancelationEvents(nsecs_t currentTime,
Jeff Brownac386072011-07-20 15:19:50 -07003896 Vector<EventEntry*>& outEvents, const CancelationOptions& options) {
Jeff Brown81346812011-06-28 20:08:48 -07003897 for (size_t i = 0; i < mKeyMementos.size(); i++) {
Jeff Brownb88102f2010-09-08 11:49:43 -07003898 const KeyMemento& memento = mKeyMementos.itemAt(i);
Jeff Brown49ed71d2010-12-06 17:13:33 -08003899 if (shouldCancelKey(memento, options)) {
Jeff Brownac386072011-07-20 15:19:50 -07003900 outEvents.push(new KeyEntry(currentTime,
Jeff Brownb6997262010-10-08 22:31:17 -07003901 memento.deviceId, memento.source, 0,
Jeff Brown49ed71d2010-12-06 17:13:33 -08003902 AKEY_EVENT_ACTION_UP, memento.flags | AKEY_EVENT_FLAG_CANCELED,
Jeff Brownb6997262010-10-08 22:31:17 -07003903 memento.keyCode, memento.scanCode, 0, 0, memento.downTime));
Jeff Brownb6997262010-10-08 22:31:17 -07003904 }
Jeff Brownb88102f2010-09-08 11:49:43 -07003905 }
3906
Jeff Brown81346812011-06-28 20:08:48 -07003907 for (size_t i = 0; i < mMotionMementos.size(); i++) {
Jeff Brownb88102f2010-09-08 11:49:43 -07003908 const MotionMemento& memento = mMotionMementos.itemAt(i);
Jeff Brown49ed71d2010-12-06 17:13:33 -08003909 if (shouldCancelMotion(memento, options)) {
Jeff Brownac386072011-07-20 15:19:50 -07003910 outEvents.push(new MotionEntry(currentTime,
Jeff Brownb6997262010-10-08 22:31:17 -07003911 memento.deviceId, memento.source, 0,
Jeff Browna032cc02011-03-07 16:56:21 -08003912 memento.hovering
3913 ? AMOTION_EVENT_ACTION_HOVER_EXIT
3914 : AMOTION_EVENT_ACTION_CANCEL,
Jeff Brown81346812011-06-28 20:08:48 -07003915 memento.flags, 0, 0, 0,
Jeff Brownb6997262010-10-08 22:31:17 -07003916 memento.xPrecision, memento.yPrecision, memento.downTime,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003917 memento.pointerCount, memento.pointerProperties, memento.pointerCoords));
Jeff Brownb6997262010-10-08 22:31:17 -07003918 }
Jeff Brownb88102f2010-09-08 11:49:43 -07003919 }
3920}
3921
3922void InputDispatcher::InputState::clear() {
3923 mKeyMementos.clear();
3924 mMotionMementos.clear();
Jeff Brownda3d5a92011-03-29 15:11:34 -07003925 mFallbackKeys.clear();
Jeff Brownb6997262010-10-08 22:31:17 -07003926}
3927
Jeff Brown9c9f1a32010-10-11 18:32:20 -07003928void InputDispatcher::InputState::copyPointerStateTo(InputState& other) const {
3929 for (size_t i = 0; i < mMotionMementos.size(); i++) {
3930 const MotionMemento& memento = mMotionMementos.itemAt(i);
3931 if (memento.source & AINPUT_SOURCE_CLASS_POINTER) {
3932 for (size_t j = 0; j < other.mMotionMementos.size(); ) {
3933 const MotionMemento& otherMemento = other.mMotionMementos.itemAt(j);
3934 if (memento.deviceId == otherMemento.deviceId
3935 && memento.source == otherMemento.source) {
3936 other.mMotionMementos.removeAt(j);
3937 } else {
3938 j += 1;
3939 }
3940 }
3941 other.mMotionMementos.push(memento);
3942 }
3943 }
3944}
3945
Jeff Brownda3d5a92011-03-29 15:11:34 -07003946int32_t InputDispatcher::InputState::getFallbackKey(int32_t originalKeyCode) {
3947 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
3948 return index >= 0 ? mFallbackKeys.valueAt(index) : -1;
3949}
3950
3951void InputDispatcher::InputState::setFallbackKey(int32_t originalKeyCode,
3952 int32_t fallbackKeyCode) {
3953 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
3954 if (index >= 0) {
3955 mFallbackKeys.replaceValueAt(index, fallbackKeyCode);
3956 } else {
3957 mFallbackKeys.add(originalKeyCode, fallbackKeyCode);
3958 }
3959}
3960
3961void InputDispatcher::InputState::removeFallbackKey(int32_t originalKeyCode) {
3962 mFallbackKeys.removeItem(originalKeyCode);
3963}
3964
Jeff Brown49ed71d2010-12-06 17:13:33 -08003965bool InputDispatcher::InputState::shouldCancelKey(const KeyMemento& memento,
Jeff Brownda3d5a92011-03-29 15:11:34 -07003966 const CancelationOptions& options) {
3967 if (options.keyCode != -1 && memento.keyCode != options.keyCode) {
3968 return false;
3969 }
3970
Jeff Brown65fd2512011-08-18 11:20:58 -07003971 if (options.deviceId != -1 && memento.deviceId != options.deviceId) {
3972 return false;
3973 }
3974
Jeff Brownda3d5a92011-03-29 15:11:34 -07003975 switch (options.mode) {
3976 case CancelationOptions::CANCEL_ALL_EVENTS:
3977 case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
Jeff Brownb6997262010-10-08 22:31:17 -07003978 return true;
Jeff Brownda3d5a92011-03-29 15:11:34 -07003979 case CancelationOptions::CANCEL_FALLBACK_EVENTS:
Jeff Brown49ed71d2010-12-06 17:13:33 -08003980 return memento.flags & AKEY_EVENT_FLAG_FALLBACK;
3981 default:
3982 return false;
3983 }
3984}
3985
3986bool InputDispatcher::InputState::shouldCancelMotion(const MotionMemento& memento,
Jeff Brownda3d5a92011-03-29 15:11:34 -07003987 const CancelationOptions& options) {
Jeff Brown65fd2512011-08-18 11:20:58 -07003988 if (options.deviceId != -1 && memento.deviceId != options.deviceId) {
3989 return false;
3990 }
3991
Jeff Brownda3d5a92011-03-29 15:11:34 -07003992 switch (options.mode) {
3993 case CancelationOptions::CANCEL_ALL_EVENTS:
Jeff Brown49ed71d2010-12-06 17:13:33 -08003994 return true;
Jeff Brownda3d5a92011-03-29 15:11:34 -07003995 case CancelationOptions::CANCEL_POINTER_EVENTS:
Jeff Brown49ed71d2010-12-06 17:13:33 -08003996 return memento.source & AINPUT_SOURCE_CLASS_POINTER;
Jeff Brownda3d5a92011-03-29 15:11:34 -07003997 case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
Jeff Brown49ed71d2010-12-06 17:13:33 -08003998 return !(memento.source & AINPUT_SOURCE_CLASS_POINTER);
3999 default:
4000 return false;
Jeff Brownb6997262010-10-08 22:31:17 -07004001 }
Jeff Brownb88102f2010-09-08 11:49:43 -07004002}
4003
4004
Jeff Brown46b9ac02010-04-22 18:58:52 -07004005// --- InputDispatcher::Connection ---
4006
Jeff Brown928e0542011-01-10 11:17:36 -08004007InputDispatcher::Connection::Connection(const sp<InputChannel>& inputChannel,
Jeff Browncc4f7db2011-08-30 20:34:48 -07004008 const sp<InputWindowHandle>& inputWindowHandle, bool monitor) :
Jeff Brown928e0542011-01-10 11:17:36 -08004009 status(STATUS_NORMAL), inputChannel(inputChannel), inputWindowHandle(inputWindowHandle),
Jeff Browncc4f7db2011-08-30 20:34:48 -07004010 monitor(monitor),
Jeff Brownd1c48a02012-02-06 19:12:47 -08004011 inputPublisher(inputChannel), inputPublisherBlocked(false) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07004012}
4013
4014InputDispatcher::Connection::~Connection() {
4015}
4016
Jeff Brown9c3cda02010-06-15 01:31:58 -07004017const char* InputDispatcher::Connection::getStatusLabel() const {
4018 switch (status) {
4019 case STATUS_NORMAL:
4020 return "NORMAL";
4021
4022 case STATUS_BROKEN:
4023 return "BROKEN";
4024
Jeff Brown9c3cda02010-06-15 01:31:58 -07004025 case STATUS_ZOMBIE:
4026 return "ZOMBIE";
4027
4028 default:
4029 return "UNKNOWN";
4030 }
4031}
4032
Jeff Brown072ec962012-02-07 14:46:57 -08004033InputDispatcher::DispatchEntry* InputDispatcher::Connection::findWaitQueueEntry(uint32_t seq) {
4034 for (DispatchEntry* entry = waitQueue.head; entry != NULL; entry = entry->next) {
4035 if (entry->seq == seq) {
4036 return entry;
4037 }
4038 }
4039 return NULL;
4040}
4041
Jeff Brownb88102f2010-09-08 11:49:43 -07004042
Jeff Brown9c3cda02010-06-15 01:31:58 -07004043// --- InputDispatcher::CommandEntry ---
4044
Jeff Brownac386072011-07-20 15:19:50 -07004045InputDispatcher::CommandEntry::CommandEntry(Command command) :
Jeff Brown072ec962012-02-07 14:46:57 -08004046 command(command), eventTime(0), keyEntry(NULL), userActivityEventType(0),
4047 seq(0), handled(false) {
Jeff Brown9c3cda02010-06-15 01:31:58 -07004048}
4049
4050InputDispatcher::CommandEntry::~CommandEntry() {
4051}
4052
Jeff Brown46b9ac02010-04-22 18:58:52 -07004053
Jeff Brown01ce2e92010-09-26 22:20:12 -07004054// --- InputDispatcher::TouchState ---
4055
4056InputDispatcher::TouchState::TouchState() :
Jeff Brown58a2da82011-01-25 16:02:22 -08004057 down(false), split(false), deviceId(-1), source(0) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07004058}
4059
4060InputDispatcher::TouchState::~TouchState() {
4061}
4062
4063void InputDispatcher::TouchState::reset() {
4064 down = false;
4065 split = false;
Jeff Brown95712852011-01-04 19:41:59 -08004066 deviceId = -1;
Jeff Brown58a2da82011-01-25 16:02:22 -08004067 source = 0;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004068 windows.clear();
4069}
4070
4071void InputDispatcher::TouchState::copyFrom(const TouchState& other) {
4072 down = other.down;
4073 split = other.split;
Jeff Brown95712852011-01-04 19:41:59 -08004074 deviceId = other.deviceId;
Jeff Brown58a2da82011-01-25 16:02:22 -08004075 source = other.source;
Jeff Brown9302c872011-07-13 22:51:29 -07004076 windows = other.windows;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004077}
4078
Jeff Brown9302c872011-07-13 22:51:29 -07004079void InputDispatcher::TouchState::addOrUpdateWindow(const sp<InputWindowHandle>& windowHandle,
Jeff Brown01ce2e92010-09-26 22:20:12 -07004080 int32_t targetFlags, BitSet32 pointerIds) {
4081 if (targetFlags & InputTarget::FLAG_SPLIT) {
4082 split = true;
4083 }
4084
4085 for (size_t i = 0; i < windows.size(); i++) {
4086 TouchedWindow& touchedWindow = windows.editItemAt(i);
Jeff Brown9302c872011-07-13 22:51:29 -07004087 if (touchedWindow.windowHandle == windowHandle) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07004088 touchedWindow.targetFlags |= targetFlags;
Jeff Brown98db5fa2011-06-08 15:37:10 -07004089 if (targetFlags & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
4090 touchedWindow.targetFlags &= ~InputTarget::FLAG_DISPATCH_AS_IS;
4091 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07004092 touchedWindow.pointerIds.value |= pointerIds.value;
4093 return;
4094 }
4095 }
4096
4097 windows.push();
4098
4099 TouchedWindow& touchedWindow = windows.editTop();
Jeff Brown9302c872011-07-13 22:51:29 -07004100 touchedWindow.windowHandle = windowHandle;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004101 touchedWindow.targetFlags = targetFlags;
4102 touchedWindow.pointerIds = pointerIds;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004103}
4104
Jeff Browna032cc02011-03-07 16:56:21 -08004105void InputDispatcher::TouchState::filterNonAsIsTouchWindows() {
Jeff Brown01ce2e92010-09-26 22:20:12 -07004106 for (size_t i = 0 ; i < windows.size(); ) {
Jeff Browna032cc02011-03-07 16:56:21 -08004107 TouchedWindow& window = windows.editItemAt(i);
Jeff Brown98db5fa2011-06-08 15:37:10 -07004108 if (window.targetFlags & (InputTarget::FLAG_DISPATCH_AS_IS
4109 | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER)) {
Jeff Browna032cc02011-03-07 16:56:21 -08004110 window.targetFlags &= ~InputTarget::FLAG_DISPATCH_MASK;
4111 window.targetFlags |= InputTarget::FLAG_DISPATCH_AS_IS;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004112 i += 1;
Jeff Browna032cc02011-03-07 16:56:21 -08004113 } else {
4114 windows.removeAt(i);
Jeff Brown01ce2e92010-09-26 22:20:12 -07004115 }
4116 }
4117}
4118
Jeff Brown9302c872011-07-13 22:51:29 -07004119sp<InputWindowHandle> InputDispatcher::TouchState::getFirstForegroundWindowHandle() const {
Jeff Brown01ce2e92010-09-26 22:20:12 -07004120 for (size_t i = 0; i < windows.size(); i++) {
Jeff Brown98db5fa2011-06-08 15:37:10 -07004121 const TouchedWindow& window = windows.itemAt(i);
4122 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
Jeff Brown9302c872011-07-13 22:51:29 -07004123 return window.windowHandle;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004124 }
4125 }
4126 return NULL;
4127}
4128
Jeff Brown98db5fa2011-06-08 15:37:10 -07004129bool InputDispatcher::TouchState::isSlippery() const {
4130 // Must have exactly one foreground window.
4131 bool haveSlipperyForegroundWindow = false;
4132 for (size_t i = 0; i < windows.size(); i++) {
4133 const TouchedWindow& window = windows.itemAt(i);
4134 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
Jeff Browncc4f7db2011-08-30 20:34:48 -07004135 if (haveSlipperyForegroundWindow
4136 || !(window.windowHandle->getInfo()->layoutParamsFlags
4137 & InputWindowInfo::FLAG_SLIPPERY)) {
Jeff Brown98db5fa2011-06-08 15:37:10 -07004138 return false;
4139 }
4140 haveSlipperyForegroundWindow = true;
4141 }
4142 }
4143 return haveSlipperyForegroundWindow;
4144}
4145
Jeff Brown01ce2e92010-09-26 22:20:12 -07004146
Jeff Brown46b9ac02010-04-22 18:58:52 -07004147// --- InputDispatcherThread ---
4148
4149InputDispatcherThread::InputDispatcherThread(const sp<InputDispatcherInterface>& dispatcher) :
4150 Thread(/*canCallJava*/ true), mDispatcher(dispatcher) {
4151}
4152
4153InputDispatcherThread::~InputDispatcherThread() {
4154}
4155
4156bool InputDispatcherThread::threadLoop() {
4157 mDispatcher->dispatchOnce();
4158 return true;
4159}
4160
4161} // namespace android