blob: 291a816e7a7a152edf76aaa2d9f7729df74feef4 [file] [log] [blame]
Jeff Brownb4ff35d2011-01-02 16:37:43 -08001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070017#define LOG_TAG "InputDispatcher"
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 Brown46b9ac0a2010-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 Brown46b9ac0a2010-04-22 18:58:52 -070026
Jeff Brown46b9ac0a2010-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 Brown46b9ac0a2010-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 Brown46b9ac0a2010-04-22 18:58:52 -070047#include <cutils/log.h>
Jeff Brownb88102f2010-09-08 11:49:43 -070048#include <ui/PowerManager.h>
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070049
50#include <stddef.h>
51#include <unistd.h>
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070052#include <errno.h>
53#include <limits.h>
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070054
Jeff Brownf2f487182010-10-01 17:46:21 -070055#define INDENT " "
56#define INDENT2 " "
57
Jeff Brown46b9ac0a2010-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 Brown46b9ac0a2010-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 Brown46b9ac0a2010-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 Brown46b9ac0a2010-04-22 18:58:52 -0700189
Jeff Brown46b9ac0a2010-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 Brown46b9ac0a2010-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 Brown46b9ac0a2010-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 Brown46b9ac0a2010-04-22 18:58:52 -0700206 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700207}
208
209void InputDispatcher::dispatchOnce() {
Jeff Brown46b9ac0a2010-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 Brown46b9ac0a2010-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 Brown46b9ac0a2010-04-22 18:58:52 -0700219 }
Jeff Brown46b9ac0a2010-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 Brown46b9ac0a2010-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 Brown46b9ac0a2010-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 Brown46b9ac0a2010-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 Brown46b9ac0a2010-04-22 18:58:52 -0700574 }
Jeff Brown46b9ac0a2010-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 Brown46b9ac0a2010-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 Brown46b9ac0a2010-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 Brown46b9ac0a2010-04-22 18:58:52 -0700622
623 mKeyRepeatState.lastKeyEntry = newEntry;
Jeff Brownac386072011-07-20 15:19:50 -0700624 entry->release();
Jeff Brown46b9ac0a2010-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 Brown46b9ac0a2010-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 Brown46b9ac0a2010-04-22 18:58:52 -0700636}
637
Jeff Brownb88102f2010-09-08 11:49:43 -0700638bool InputDispatcher::dispatchConfigurationChangedLocked(
639 nsecs_t currentTime, ConfigurationChangedEntry* entry) {
Jeff Brown46b9ac0a2010-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 Brown46b9ac0a2010-04-22 18:58:52 -0700842 entry->downTime);
843
Jeff Brown46b9ac0a2010-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 Brown46b9ac0a2010-04-22 18:58:52 -0700860 }
861#endif
Jeff Brown46b9ac0a2010-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 Brown46b9ac0a2010-04-22 18:58:52 -0700866#if DEBUG_DISPATCH_CYCLE
Jeff Brown3241b6b2012-02-03 15:08:02 -0800867 ALOGD("dispatchEventToCurrentInputTargets");
Jeff Brown46b9ac0a2010-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 Brown46b9ac0a2010-04-22 18:58:52 -0700876
Jeff Brown519e0242010-09-15 15:18:56 -0700877 ssize_t connectionIndex = getConnectionIndexLocked(inputTarget.inputChannel);
Jeff Brown46b9ac0a2010-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 Brown46b9ac0a2010-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 Brown46b9ac0a2010-04-22 18:58:52 -0700885 inputTarget.inputChannel->getName().string());
Jeff Brownb6997262010-10-08 22:31:17 -0700886#endif
Jeff Brown46b9ac0a2010-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 Brownd1c48a02012-02-06 19:12:47 -08001044 if (!isWindowReadyForMoreInputLocked(currentTime,
1045 mFocusedWindowHandle, true /*focusedEvent*/)) {
Jeff Brown519e0242010-09-15 15:18:56 -07001046#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001047 ALOGD("Waiting because focused window still processing previous input.");
Jeff Brown519e0242010-09-15 15:18:56 -07001048#endif
1049 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brown9302c872011-07-13 22:51:29 -07001050 mFocusedApplicationHandle, mFocusedWindowHandle, nextWakeupTime);
Jeff Brown519e0242010-09-15 15:18:56 -07001051 goto Unresponsive;
1052 }
1053
Jeff Brownb88102f2010-09-08 11:49:43 -07001054 // Success! Output targets.
1055 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
Jeff Brown9302c872011-07-13 22:51:29 -07001056 addWindowTargetLocked(mFocusedWindowHandle,
Jeff Browne9bb9be2012-02-06 15:47:55 -08001057 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS, BitSet32(0),
1058 inputTargets);
Jeff Brownb88102f2010-09-08 11:49:43 -07001059
1060 // Done.
1061Failed:
1062Unresponsive:
Jeff Brown519e0242010-09-15 15:18:56 -07001063 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
1064 updateDispatchStatisticsLocked(currentTime, entry,
1065 injectionResult, timeSpentWaitingForApplication);
Jeff Brownb88102f2010-09-08 11:49:43 -07001066#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001067 ALOGD("findFocusedWindow finished: injectionResult=%d, "
Jeff Brown519e0242010-09-15 15:18:56 -07001068 "timeSpendWaitingForApplication=%0.1fms",
1069 injectionResult, timeSpentWaitingForApplication / 1000000.0);
Jeff Brownb88102f2010-09-08 11:49:43 -07001070#endif
1071 return injectionResult;
1072}
1073
Jeff Brown01ce2e92010-09-26 22:20:12 -07001074int32_t InputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime,
Jeff Browne9bb9be2012-02-06 15:47:55 -08001075 const MotionEntry* entry, Vector<InputTarget>& inputTargets, nsecs_t* nextWakeupTime,
1076 bool* outConflictingPointerActions) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001077 enum InjectionPermission {
1078 INJECTION_PERMISSION_UNKNOWN,
1079 INJECTION_PERMISSION_GRANTED,
1080 INJECTION_PERMISSION_DENIED
1081 };
1082
Jeff Brownb88102f2010-09-08 11:49:43 -07001083 nsecs_t startTime = now();
1084
1085 // For security reasons, we defer updating the touch state until we are sure that
1086 // event injection will be allowed.
1087 //
1088 // FIXME In the original code, screenWasOff could never be set to true.
1089 // The reason is that the POLICY_FLAG_WOKE_HERE
1090 // and POLICY_FLAG_BRIGHT_HERE flags were set only when preprocessing raw
1091 // EV_KEY, EV_REL and EV_ABS events. As it happens, the touch event was
1092 // actually enqueued using the policyFlags that appeared in the final EV_SYN
1093 // events upon which no preprocessing took place. So policyFlags was always 0.
1094 // In the new native input dispatcher we're a bit more careful about event
1095 // preprocessing so the touches we receive can actually have non-zero policyFlags.
1096 // Unfortunately we obtain undesirable behavior.
1097 //
1098 // Here's what happens:
1099 //
1100 // When the device dims in anticipation of going to sleep, touches
1101 // in windows which have FLAG_TOUCHABLE_WHEN_WAKING cause
1102 // the device to brighten and reset the user activity timer.
1103 // Touches on other windows (such as the launcher window)
1104 // are dropped. Then after a moment, the device goes to sleep. Oops.
1105 //
1106 // Also notice how screenWasOff was being initialized using POLICY_FLAG_BRIGHT_HERE
1107 // instead of POLICY_FLAG_WOKE_HERE...
1108 //
1109 bool screenWasOff = false; // original policy: policyFlags & POLICY_FLAG_BRIGHT_HERE;
1110
1111 int32_t action = entry->action;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001112 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Jeff Brownb88102f2010-09-08 11:49:43 -07001113
1114 // Update the touch state as needed based on the properties of the touch event.
Jeff Brown01ce2e92010-09-26 22:20:12 -07001115 int32_t injectionResult = INPUT_EVENT_INJECTION_PENDING;
1116 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
Jeff Brown9302c872011-07-13 22:51:29 -07001117 sp<InputWindowHandle> newHoverWindowHandle;
Jeff Browncc0c1592011-02-19 05:07:28 -08001118
1119 bool isSplit = mTouchState.split;
Jeff Brown2717eff2011-06-30 23:53:07 -07001120 bool switchedDevice = mTouchState.deviceId >= 0
1121 && (mTouchState.deviceId != entry->deviceId
1122 || mTouchState.source != entry->source);
Jeff Browna032cc02011-03-07 16:56:21 -08001123 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE
1124 || maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER
1125 || maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1126 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN
1127 || maskedAction == AMOTION_EVENT_ACTION_SCROLL
1128 || isHoverAction);
Jeff Brown81346812011-06-28 20:08:48 -07001129 bool wrongDevice = false;
Jeff Browna032cc02011-03-07 16:56:21 -08001130 if (newGesture) {
Jeff Browncc0c1592011-02-19 05:07:28 -08001131 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Jeff Brown81346812011-06-28 20:08:48 -07001132 if (switchedDevice && mTouchState.down && !down) {
1133#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001134 ALOGD("Dropping event because a pointer for a different device is already down.");
Jeff Brown81346812011-06-28 20:08:48 -07001135#endif
Jeff Browncc0c1592011-02-19 05:07:28 -08001136 mTempTouchState.copyFrom(mTouchState);
Jeff Brown81346812011-06-28 20:08:48 -07001137 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1138 switchedDevice = false;
1139 wrongDevice = true;
1140 goto Failed;
Jeff Browncc0c1592011-02-19 05:07:28 -08001141 }
Jeff Brown81346812011-06-28 20:08:48 -07001142 mTempTouchState.reset();
1143 mTempTouchState.down = down;
1144 mTempTouchState.deviceId = entry->deviceId;
1145 mTempTouchState.source = entry->source;
1146 isSplit = false;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001147 } else {
1148 mTempTouchState.copyFrom(mTouchState);
Jeff Browncc0c1592011-02-19 05:07:28 -08001149 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001150
Jeff Browna032cc02011-03-07 16:56:21 -08001151 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
Jeff Brown33bbfd22011-02-24 20:55:35 -08001152 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
Jeff Brownb88102f2010-09-08 11:49:43 -07001153
Jeff Brown01ce2e92010-09-26 22:20:12 -07001154 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Jeff Brown3241b6b2012-02-03 15:08:02 -08001155 int32_t x = int32_t(entry->pointerCoords[pointerIndex].
Jeff Brownebbd5d12011-02-17 13:01:34 -08001156 getAxisValue(AMOTION_EVENT_AXIS_X));
Jeff Brown3241b6b2012-02-03 15:08:02 -08001157 int32_t y = int32_t(entry->pointerCoords[pointerIndex].
Jeff Brownebbd5d12011-02-17 13:01:34 -08001158 getAxisValue(AMOTION_EVENT_AXIS_Y));
Jeff Brown9302c872011-07-13 22:51:29 -07001159 sp<InputWindowHandle> newTouchedWindowHandle;
1160 sp<InputWindowHandle> topErrorWindowHandle;
Jeff Browna032cc02011-03-07 16:56:21 -08001161 bool isTouchModal = false;
Jeff Brownb88102f2010-09-08 11:49:43 -07001162
1163 // Traverse windows from front to back to find touched window and outside targets.
Jeff Brown9302c872011-07-13 22:51:29 -07001164 size_t numWindows = mWindowHandles.size();
Jeff Brownb88102f2010-09-08 11:49:43 -07001165 for (size_t i = 0; i < numWindows; i++) {
Jeff Brown9302c872011-07-13 22:51:29 -07001166 sp<InputWindowHandle> windowHandle = mWindowHandles.itemAt(i);
Jeff Browncc4f7db2011-08-30 20:34:48 -07001167 const InputWindowInfo* windowInfo = windowHandle->getInfo();
1168 int32_t flags = windowInfo->layoutParamsFlags;
Jeff Brownb88102f2010-09-08 11:49:43 -07001169
Jeff Browncc4f7db2011-08-30 20:34:48 -07001170 if (flags & InputWindowInfo::FLAG_SYSTEM_ERROR) {
Jeff Brown9302c872011-07-13 22:51:29 -07001171 if (topErrorWindowHandle == NULL) {
1172 topErrorWindowHandle = windowHandle;
Jeff Brownb88102f2010-09-08 11:49:43 -07001173 }
1174 }
1175
Jeff Browncc4f7db2011-08-30 20:34:48 -07001176 if (windowInfo->visible) {
1177 if (! (flags & InputWindowInfo::FLAG_NOT_TOUCHABLE)) {
1178 isTouchModal = (flags & (InputWindowInfo::FLAG_NOT_FOCUSABLE
1179 | InputWindowInfo::FLAG_NOT_TOUCH_MODAL)) == 0;
1180 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
Jeff Brown9302c872011-07-13 22:51:29 -07001181 if (! screenWasOff
Jeff Browncc4f7db2011-08-30 20:34:48 -07001182 || (flags & InputWindowInfo::FLAG_TOUCHABLE_WHEN_WAKING)) {
Jeff Brown9302c872011-07-13 22:51:29 -07001183 newTouchedWindowHandle = windowHandle;
Jeff Brownb88102f2010-09-08 11:49:43 -07001184 }
1185 break; // found touched window, exit window loop
1186 }
1187 }
1188
Jeff Brown01ce2e92010-09-26 22:20:12 -07001189 if (maskedAction == AMOTION_EVENT_ACTION_DOWN
Jeff Browncc4f7db2011-08-30 20:34:48 -07001190 && (flags & InputWindowInfo::FLAG_WATCH_OUTSIDE_TOUCH)) {
Jeff Browna032cc02011-03-07 16:56:21 -08001191 int32_t outsideTargetFlags = InputTarget::FLAG_DISPATCH_AS_OUTSIDE;
Jeff Brown9302c872011-07-13 22:51:29 -07001192 if (isWindowObscuredAtPointLocked(windowHandle, x, y)) {
Jeff Brown19dfc832010-10-05 12:26:23 -07001193 outsideTargetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1194 }
1195
Jeff Brown9302c872011-07-13 22:51:29 -07001196 mTempTouchState.addOrUpdateWindow(
1197 windowHandle, outsideTargetFlags, BitSet32(0));
Jeff Brownb88102f2010-09-08 11:49:43 -07001198 }
1199 }
1200 }
1201
1202 // If there is an error window but it is not taking focus (typically because
1203 // it is invisible) then wait for it. Any other focused window may in
1204 // fact be in ANR state.
Jeff Brown9302c872011-07-13 22:51:29 -07001205 if (topErrorWindowHandle != NULL && newTouchedWindowHandle != topErrorWindowHandle) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001206#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001207 ALOGD("Waiting because system error window is pending.");
Jeff Brownb88102f2010-09-08 11:49:43 -07001208#endif
1209 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
1210 NULL, NULL, nextWakeupTime);
1211 injectionPermission = INJECTION_PERMISSION_UNKNOWN;
1212 goto Unresponsive;
1213 }
1214
Jeff Brown01ce2e92010-09-26 22:20:12 -07001215 // Figure out whether splitting will be allowed for this window.
Jeff Browncc4f7db2011-08-30 20:34:48 -07001216 if (newTouchedWindowHandle != NULL
1217 && newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001218 // New window supports splitting.
1219 isSplit = true;
1220 } else if (isSplit) {
1221 // New window does not support splitting but we have already split events.
1222 // Assign the pointer to the first foreground window we find.
1223 // (May be NULL which is why we put this code block before the next check.)
Jeff Brown9302c872011-07-13 22:51:29 -07001224 newTouchedWindowHandle = mTempTouchState.getFirstForegroundWindowHandle();
Jeff Brown01ce2e92010-09-26 22:20:12 -07001225 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001226
Jeff Brownb88102f2010-09-08 11:49:43 -07001227 // If we did not find a touched window then fail.
Jeff Brown9302c872011-07-13 22:51:29 -07001228 if (newTouchedWindowHandle == NULL) {
1229 if (mFocusedApplicationHandle != NULL) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001230#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001231 ALOGD("Waiting because there is no touched window but there is a "
Jeff Brown519e0242010-09-15 15:18:56 -07001232 "focused application that may eventually add a new window: %s.",
Jeff Brown9302c872011-07-13 22:51:29 -07001233 getApplicationWindowLabelLocked(mFocusedApplicationHandle, NULL).string());
Jeff Brownb88102f2010-09-08 11:49:43 -07001234#endif
1235 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brown9302c872011-07-13 22:51:29 -07001236 mFocusedApplicationHandle, NULL, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -07001237 goto Unresponsive;
1238 }
1239
Steve Block6215d3f2012-01-04 20:05:49 +00001240 ALOGI("Dropping event because there is no touched window or focused application.");
Jeff Brownb88102f2010-09-08 11:49:43 -07001241 injectionResult = INPUT_EVENT_INJECTION_FAILED;
Jeff Brownb88102f2010-09-08 11:49:43 -07001242 goto Failed;
1243 }
1244
Jeff Brown19dfc832010-10-05 12:26:23 -07001245 // Set target flags.
Jeff Browna032cc02011-03-07 16:56:21 -08001246 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
Jeff Brown19dfc832010-10-05 12:26:23 -07001247 if (isSplit) {
1248 targetFlags |= InputTarget::FLAG_SPLIT;
1249 }
Jeff Brown9302c872011-07-13 22:51:29 -07001250 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
Jeff Brown19dfc832010-10-05 12:26:23 -07001251 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1252 }
1253
Jeff Browna032cc02011-03-07 16:56:21 -08001254 // Update hover state.
1255 if (isHoverAction) {
Jeff Brown9302c872011-07-13 22:51:29 -07001256 newHoverWindowHandle = newTouchedWindowHandle;
Jeff Browna032cc02011-03-07 16:56:21 -08001257 } else if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
Jeff Brown9302c872011-07-13 22:51:29 -07001258 newHoverWindowHandle = mLastHoverWindowHandle;
Jeff Browna032cc02011-03-07 16:56:21 -08001259 }
1260
Jeff Brown01ce2e92010-09-26 22:20:12 -07001261 // Update the temporary touch state.
1262 BitSet32 pointerIds;
1263 if (isSplit) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07001264 uint32_t pointerId = entry->pointerProperties[pointerIndex].id;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001265 pointerIds.markBit(pointerId);
Jeff Brownb88102f2010-09-08 11:49:43 -07001266 }
Jeff Brown9302c872011-07-13 22:51:29 -07001267 mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Jeff Brownb88102f2010-09-08 11:49:43 -07001268 } else {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001269 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
Jeff Brownb88102f2010-09-08 11:49:43 -07001270
1271 // If the pointer is not currently down, then ignore the event.
Jeff Brown01ce2e92010-09-26 22:20:12 -07001272 if (! mTempTouchState.down) {
Jeff Browna2cc28d2011-03-25 11:58:46 -07001273#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001274 ALOGD("Dropping event because the pointer is not down or we previously "
Jeff Brown76860e32010-10-25 17:37:46 -07001275 "dropped the pointer down event.");
1276#endif
Jeff Brownb88102f2010-09-08 11:49:43 -07001277 injectionResult = INPUT_EVENT_INJECTION_FAILED;
Jeff Brownb88102f2010-09-08 11:49:43 -07001278 goto Failed;
1279 }
Jeff Brown98db5fa2011-06-08 15:37:10 -07001280
1281 // Check whether touches should slip outside of the current foreground window.
1282 if (maskedAction == AMOTION_EVENT_ACTION_MOVE
1283 && entry->pointerCount == 1
1284 && mTempTouchState.isSlippery()) {
Jeff Brown3241b6b2012-02-03 15:08:02 -08001285 int32_t x = int32_t(entry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
1286 int32_t y = int32_t(entry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Jeff Brown98db5fa2011-06-08 15:37:10 -07001287
Jeff Brown9302c872011-07-13 22:51:29 -07001288 sp<InputWindowHandle> oldTouchedWindowHandle =
1289 mTempTouchState.getFirstForegroundWindowHandle();
1290 sp<InputWindowHandle> newTouchedWindowHandle = findTouchedWindowAtLocked(x, y);
1291 if (oldTouchedWindowHandle != newTouchedWindowHandle
1292 && newTouchedWindowHandle != NULL) {
Jeff Brown98db5fa2011-06-08 15:37:10 -07001293#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001294 ALOGD("Touch is slipping out of window %s into window %s.",
Jeff Browncc4f7db2011-08-30 20:34:48 -07001295 oldTouchedWindowHandle->getName().string(),
1296 newTouchedWindowHandle->getName().string());
Jeff Brown98db5fa2011-06-08 15:37:10 -07001297#endif
1298 // Make a slippery exit from the old window.
Jeff Brown9302c872011-07-13 22:51:29 -07001299 mTempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
Jeff Brown98db5fa2011-06-08 15:37:10 -07001300 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT, BitSet32(0));
1301
1302 // Make a slippery entrance into the new window.
Jeff Browncc4f7db2011-08-30 20:34:48 -07001303 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Jeff Brown98db5fa2011-06-08 15:37:10 -07001304 isSplit = true;
1305 }
1306
1307 int32_t targetFlags = InputTarget::FLAG_FOREGROUND
1308 | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
1309 if (isSplit) {
1310 targetFlags |= InputTarget::FLAG_SPLIT;
1311 }
Jeff Brown9302c872011-07-13 22:51:29 -07001312 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
Jeff Brown98db5fa2011-06-08 15:37:10 -07001313 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1314 }
1315
1316 BitSet32 pointerIds;
1317 if (isSplit) {
1318 pointerIds.markBit(entry->pointerProperties[0].id);
1319 }
Jeff Brown9302c872011-07-13 22:51:29 -07001320 mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Jeff Brown98db5fa2011-06-08 15:37:10 -07001321 }
1322 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001323 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001324
Jeff Brown9302c872011-07-13 22:51:29 -07001325 if (newHoverWindowHandle != mLastHoverWindowHandle) {
Jeff Browna032cc02011-03-07 16:56:21 -08001326 // Let the previous window know that the hover sequence is over.
Jeff Brown9302c872011-07-13 22:51:29 -07001327 if (mLastHoverWindowHandle != NULL) {
Jeff Browna032cc02011-03-07 16:56:21 -08001328#if DEBUG_HOVER
Steve Block5baa3a62011-12-20 16:23:08 +00001329 ALOGD("Sending hover exit event to window %s.",
Jeff Browncc4f7db2011-08-30 20:34:48 -07001330 mLastHoverWindowHandle->getName().string());
Jeff Browna032cc02011-03-07 16:56:21 -08001331#endif
Jeff Brown9302c872011-07-13 22:51:29 -07001332 mTempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
Jeff Browna032cc02011-03-07 16:56:21 -08001333 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
1334 }
1335
1336 // Let the new window know that the hover sequence is starting.
Jeff Brown9302c872011-07-13 22:51:29 -07001337 if (newHoverWindowHandle != NULL) {
Jeff Browna032cc02011-03-07 16:56:21 -08001338#if DEBUG_HOVER
Steve Block5baa3a62011-12-20 16:23:08 +00001339 ALOGD("Sending hover enter event to window %s.",
Jeff Browncc4f7db2011-08-30 20:34:48 -07001340 newHoverWindowHandle->getName().string());
Jeff Browna032cc02011-03-07 16:56:21 -08001341#endif
Jeff Brown9302c872011-07-13 22:51:29 -07001342 mTempTouchState.addOrUpdateWindow(newHoverWindowHandle,
Jeff Browna032cc02011-03-07 16:56:21 -08001343 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER, BitSet32(0));
1344 }
1345 }
1346
Jeff Brown01ce2e92010-09-26 22:20:12 -07001347 // Check permission to inject into all touched foreground windows and ensure there
1348 // is at least one touched foreground window.
1349 {
1350 bool haveForegroundWindow = false;
1351 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1352 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1353 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1354 haveForegroundWindow = true;
Jeff Brown9302c872011-07-13 22:51:29 -07001355 if (! checkInjectionPermission(touchedWindow.windowHandle,
1356 entry->injectionState)) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001357 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1358 injectionPermission = INJECTION_PERMISSION_DENIED;
1359 goto Failed;
1360 }
1361 }
1362 }
1363 if (! haveForegroundWindow) {
Jeff Browna2cc28d2011-03-25 11:58:46 -07001364#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001365 ALOGD("Dropping event because there is no touched foreground window to receive it.");
Jeff Brownb88102f2010-09-08 11:49:43 -07001366#endif
1367 injectionResult = INPUT_EVENT_INJECTION_FAILED;
Jeff Brownb88102f2010-09-08 11:49:43 -07001368 goto Failed;
1369 }
1370
Jeff Brown01ce2e92010-09-26 22:20:12 -07001371 // Permission granted to injection into all touched foreground windows.
1372 injectionPermission = INJECTION_PERMISSION_GRANTED;
1373 }
Jeff Brown519e0242010-09-15 15:18:56 -07001374
Kenny Root7a9db182011-06-02 15:16:05 -07001375 // Check whether windows listening for outside touches are owned by the same UID. If it is
1376 // set the policy flag that we will not reveal coordinate information to this window.
1377 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
Jeff Brown9302c872011-07-13 22:51:29 -07001378 sp<InputWindowHandle> foregroundWindowHandle =
1379 mTempTouchState.getFirstForegroundWindowHandle();
Jeff Browncc4f7db2011-08-30 20:34:48 -07001380 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Kenny Root7a9db182011-06-02 15:16:05 -07001381 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1382 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1383 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
Jeff Brown9302c872011-07-13 22:51:29 -07001384 sp<InputWindowHandle> inputWindowHandle = touchedWindow.windowHandle;
Jeff Browncc4f7db2011-08-30 20:34:48 -07001385 if (inputWindowHandle->getInfo()->ownerUid != foregroundWindowUid) {
Jeff Brown9302c872011-07-13 22:51:29 -07001386 mTempTouchState.addOrUpdateWindow(inputWindowHandle,
Kenny Root7a9db182011-06-02 15:16:05 -07001387 InputTarget::FLAG_ZERO_COORDS, BitSet32(0));
1388 }
1389 }
1390 }
1391 }
1392
Jeff Brown01ce2e92010-09-26 22:20:12 -07001393 // Ensure all touched foreground windows are ready for new input.
1394 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1395 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1396 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1397 // If the touched window is paused then keep waiting.
Jeff Browncc4f7db2011-08-30 20:34:48 -07001398 if (touchedWindow.windowHandle->getInfo()->paused) {
Jeff Browna2cc28d2011-03-25 11:58:46 -07001399#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001400 ALOGD("Waiting because touched window is paused.");
Jeff Brown519e0242010-09-15 15:18:56 -07001401#endif
Jeff Brown01ce2e92010-09-26 22:20:12 -07001402 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brown9302c872011-07-13 22:51:29 -07001403 NULL, touchedWindow.windowHandle, nextWakeupTime);
Jeff Brown01ce2e92010-09-26 22:20:12 -07001404 goto Unresponsive;
1405 }
1406
1407 // If the touched window is still working on previous events then keep waiting.
Jeff Brownd1c48a02012-02-06 19:12:47 -08001408 if (!isWindowReadyForMoreInputLocked(currentTime,
1409 touchedWindow.windowHandle, false /*focusedEvent*/)) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001410#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001411 ALOGD("Waiting because touched window still processing previous input.");
Jeff Brown01ce2e92010-09-26 22:20:12 -07001412#endif
1413 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brown9302c872011-07-13 22:51:29 -07001414 NULL, touchedWindow.windowHandle, nextWakeupTime);
Jeff Brown01ce2e92010-09-26 22:20:12 -07001415 goto Unresponsive;
1416 }
1417 }
1418 }
1419
1420 // If this is the first pointer going down and the touched window has a wallpaper
1421 // then also add the touched wallpaper windows so they are locked in for the duration
1422 // of the touch gesture.
Jeff Brown33bbfd22011-02-24 20:55:35 -08001423 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
1424 // engine only supports touch events. We would need to add a mechanism similar
1425 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
1426 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
Jeff Brown9302c872011-07-13 22:51:29 -07001427 sp<InputWindowHandle> foregroundWindowHandle =
1428 mTempTouchState.getFirstForegroundWindowHandle();
Jeff Browncc4f7db2011-08-30 20:34:48 -07001429 if (foregroundWindowHandle->getInfo()->hasWallpaper) {
Jeff Brown9302c872011-07-13 22:51:29 -07001430 for (size_t i = 0; i < mWindowHandles.size(); i++) {
1431 sp<InputWindowHandle> windowHandle = mWindowHandles.itemAt(i);
Jeff Browncc4f7db2011-08-30 20:34:48 -07001432 if (windowHandle->getInfo()->layoutParamsType
1433 == InputWindowInfo::TYPE_WALLPAPER) {
Jeff Brown9302c872011-07-13 22:51:29 -07001434 mTempTouchState.addOrUpdateWindow(windowHandle,
Jeff Browna032cc02011-03-07 16:56:21 -08001435 InputTarget::FLAG_WINDOW_IS_OBSCURED
1436 | InputTarget::FLAG_DISPATCH_AS_IS,
1437 BitSet32(0));
Jeff Brown01ce2e92010-09-26 22:20:12 -07001438 }
1439 }
1440 }
1441 }
1442
Jeff Brownb88102f2010-09-08 11:49:43 -07001443 // Success! Output targets.
1444 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
Jeff Brownb88102f2010-09-08 11:49:43 -07001445
Jeff Brown01ce2e92010-09-26 22:20:12 -07001446 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1447 const TouchedWindow& touchedWindow = mTempTouchState.windows.itemAt(i);
Jeff Brown9302c872011-07-13 22:51:29 -07001448 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Jeff Browne9bb9be2012-02-06 15:47:55 -08001449 touchedWindow.pointerIds, inputTargets);
Jeff Brownb88102f2010-09-08 11:49:43 -07001450 }
1451
Jeff Browna032cc02011-03-07 16:56:21 -08001452 // Drop the outside or hover touch windows since we will not care about them
1453 // in the next iteration.
1454 mTempTouchState.filterNonAsIsTouchWindows();
Jeff Brown01ce2e92010-09-26 22:20:12 -07001455
Jeff Brownb88102f2010-09-08 11:49:43 -07001456Failed:
1457 // Check injection permission once and for all.
1458 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001459 if (checkInjectionPermission(NULL, entry->injectionState)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001460 injectionPermission = INJECTION_PERMISSION_GRANTED;
1461 } else {
1462 injectionPermission = INJECTION_PERMISSION_DENIED;
1463 }
1464 }
1465
1466 // Update final pieces of touch state if the injector had permission.
1467 if (injectionPermission == INJECTION_PERMISSION_GRANTED) {
Jeff Brown95712852011-01-04 19:41:59 -08001468 if (!wrongDevice) {
Jeff Brown81346812011-06-28 20:08:48 -07001469 if (switchedDevice) {
1470#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001471 ALOGD("Conflicting pointer actions: Switched to a different device.");
Jeff Brown81346812011-06-28 20:08:48 -07001472#endif
1473 *outConflictingPointerActions = true;
1474 }
1475
1476 if (isHoverAction) {
1477 // Started hovering, therefore no longer down.
1478 if (mTouchState.down) {
1479#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001480 ALOGD("Conflicting pointer actions: Hover received while pointer was down.");
Jeff Brown81346812011-06-28 20:08:48 -07001481#endif
1482 *outConflictingPointerActions = true;
1483 }
1484 mTouchState.reset();
1485 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER
1486 || maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
1487 mTouchState.deviceId = entry->deviceId;
1488 mTouchState.source = entry->source;
1489 }
1490 } else if (maskedAction == AMOTION_EVENT_ACTION_UP
1491 || maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Jeff Brown95712852011-01-04 19:41:59 -08001492 // All pointers up or canceled.
Jeff Brown33bbfd22011-02-24 20:55:35 -08001493 mTouchState.reset();
Jeff Brown95712852011-01-04 19:41:59 -08001494 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1495 // First pointer went down.
1496 if (mTouchState.down) {
Jeff Brownb6997262010-10-08 22:31:17 -07001497#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001498 ALOGD("Conflicting pointer actions: Down received while already down.");
Jeff Brownb6997262010-10-08 22:31:17 -07001499#endif
Jeff Brown81346812011-06-28 20:08:48 -07001500 *outConflictingPointerActions = true;
Jeff Brown95712852011-01-04 19:41:59 -08001501 }
Jeff Brown33bbfd22011-02-24 20:55:35 -08001502 mTouchState.copyFrom(mTempTouchState);
Jeff Brown95712852011-01-04 19:41:59 -08001503 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
1504 // One pointer went up.
1505 if (isSplit) {
1506 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07001507 uint32_t pointerId = entry->pointerProperties[pointerIndex].id;
Jeff Brownb88102f2010-09-08 11:49:43 -07001508
Jeff Brown95712852011-01-04 19:41:59 -08001509 for (size_t i = 0; i < mTempTouchState.windows.size(); ) {
1510 TouchedWindow& touchedWindow = mTempTouchState.windows.editItemAt(i);
1511 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
1512 touchedWindow.pointerIds.clearBit(pointerId);
1513 if (touchedWindow.pointerIds.isEmpty()) {
1514 mTempTouchState.windows.removeAt(i);
1515 continue;
1516 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001517 }
Jeff Brown95712852011-01-04 19:41:59 -08001518 i += 1;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001519 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001520 }
Jeff Brown33bbfd22011-02-24 20:55:35 -08001521 mTouchState.copyFrom(mTempTouchState);
1522 } else if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
1523 // Discard temporary touch state since it was only valid for this action.
1524 } else {
1525 // Save changes to touch state as-is for all other actions.
1526 mTouchState.copyFrom(mTempTouchState);
Jeff Brownb88102f2010-09-08 11:49:43 -07001527 }
Jeff Browna032cc02011-03-07 16:56:21 -08001528
1529 // Update hover state.
Jeff Brown9302c872011-07-13 22:51:29 -07001530 mLastHoverWindowHandle = newHoverWindowHandle;
Jeff Brown95712852011-01-04 19:41:59 -08001531 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001532 } else {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001533#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001534 ALOGD("Not updating touch focus because injection was denied.");
Jeff Brown01ce2e92010-09-26 22:20:12 -07001535#endif
Jeff Brownb88102f2010-09-08 11:49:43 -07001536 }
1537
1538Unresponsive:
Jeff Brown120a4592010-10-27 18:43:51 -07001539 // Reset temporary touch state to ensure we release unnecessary references to input channels.
1540 mTempTouchState.reset();
1541
Jeff Brown519e0242010-09-15 15:18:56 -07001542 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
1543 updateDispatchStatisticsLocked(currentTime, entry,
1544 injectionResult, timeSpentWaitingForApplication);
Jeff Brownb88102f2010-09-08 11:49:43 -07001545#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001546 ALOGD("findTouchedWindow finished: injectionResult=%d, injectionPermission=%d, "
Jeff Brown01ce2e92010-09-26 22:20:12 -07001547 "timeSpentWaitingForApplication=%0.1fms",
Jeff Brown519e0242010-09-15 15:18:56 -07001548 injectionResult, injectionPermission, timeSpentWaitingForApplication / 1000000.0);
Jeff Brownb88102f2010-09-08 11:49:43 -07001549#endif
1550 return injectionResult;
1551}
1552
Jeff Brown9302c872011-07-13 22:51:29 -07001553void InputDispatcher::addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
Jeff Browne9bb9be2012-02-06 15:47:55 -08001554 int32_t targetFlags, BitSet32 pointerIds, Vector<InputTarget>& inputTargets) {
1555 inputTargets.push();
Jeff Brownb88102f2010-09-08 11:49:43 -07001556
Jeff Browncc4f7db2011-08-30 20:34:48 -07001557 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Jeff Browne9bb9be2012-02-06 15:47:55 -08001558 InputTarget& target = inputTargets.editTop();
Jeff Browncc4f7db2011-08-30 20:34:48 -07001559 target.inputChannel = windowInfo->inputChannel;
Jeff Brownb88102f2010-09-08 11:49:43 -07001560 target.flags = targetFlags;
Jeff Browncc4f7db2011-08-30 20:34:48 -07001561 target.xOffset = - windowInfo->frameLeft;
1562 target.yOffset = - windowInfo->frameTop;
1563 target.scaleFactor = windowInfo->scaleFactor;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001564 target.pointerIds = pointerIds;
Jeff Brownb88102f2010-09-08 11:49:43 -07001565}
1566
Jeff Browne9bb9be2012-02-06 15:47:55 -08001567void InputDispatcher::addMonitoringTargetsLocked(Vector<InputTarget>& inputTargets) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001568 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
Jeff Browne9bb9be2012-02-06 15:47:55 -08001569 inputTargets.push();
Jeff Brownb88102f2010-09-08 11:49:43 -07001570
Jeff Browne9bb9be2012-02-06 15:47:55 -08001571 InputTarget& target = inputTargets.editTop();
Jeff Brownb88102f2010-09-08 11:49:43 -07001572 target.inputChannel = mMonitoringChannels[i];
Jeff Brownb6110c22011-04-01 16:15:13 -07001573 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
Jeff Brownb88102f2010-09-08 11:49:43 -07001574 target.xOffset = 0;
1575 target.yOffset = 0;
Jeff Brownb6110c22011-04-01 16:15:13 -07001576 target.pointerIds.clear();
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001577 target.scaleFactor = 1.0f;
Jeff Brownb88102f2010-09-08 11:49:43 -07001578 }
1579}
1580
Jeff Brown9302c872011-07-13 22:51:29 -07001581bool InputDispatcher::checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
Jeff Brown01ce2e92010-09-26 22:20:12 -07001582 const InjectionState* injectionState) {
1583 if (injectionState
Jeff Browncc4f7db2011-08-30 20:34:48 -07001584 && (windowHandle == NULL
1585 || windowHandle->getInfo()->ownerUid != injectionState->injectorUid)
Jeff Brownb6997262010-10-08 22:31:17 -07001586 && !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Jeff Brown9302c872011-07-13 22:51:29 -07001587 if (windowHandle != NULL) {
Steve Block8564c8d2012-01-05 23:22:43 +00001588 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
Jeff Brown9302c872011-07-13 22:51:29 -07001589 "owned by uid %d",
Jeff Brownb6997262010-10-08 22:31:17 -07001590 injectionState->injectorPid, injectionState->injectorUid,
Jeff Browncc4f7db2011-08-30 20:34:48 -07001591 windowHandle->getName().string(),
1592 windowHandle->getInfo()->ownerUid);
Jeff Brownb6997262010-10-08 22:31:17 -07001593 } else {
Steve Block8564c8d2012-01-05 23:22:43 +00001594 ALOGW("Permission denied: injecting event from pid %d uid %d",
Jeff Brownb6997262010-10-08 22:31:17 -07001595 injectionState->injectorPid, injectionState->injectorUid);
Jeff Brownb88102f2010-09-08 11:49:43 -07001596 }
Jeff Brownb6997262010-10-08 22:31:17 -07001597 return false;
Jeff Brownb88102f2010-09-08 11:49:43 -07001598 }
1599 return true;
1600}
1601
Jeff Brown19dfc832010-10-05 12:26:23 -07001602bool InputDispatcher::isWindowObscuredAtPointLocked(
Jeff Brown9302c872011-07-13 22:51:29 -07001603 const sp<InputWindowHandle>& windowHandle, int32_t x, int32_t y) const {
1604 size_t numWindows = mWindowHandles.size();
Jeff Brownb88102f2010-09-08 11:49:43 -07001605 for (size_t i = 0; i < numWindows; i++) {
Jeff Brown9302c872011-07-13 22:51:29 -07001606 sp<InputWindowHandle> otherHandle = mWindowHandles.itemAt(i);
1607 if (otherHandle == windowHandle) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001608 break;
1609 }
Jeff Browncc4f7db2011-08-30 20:34:48 -07001610
1611 const InputWindowInfo* otherInfo = otherHandle->getInfo();
1612 if (otherInfo->visible && ! otherInfo->isTrustedOverlay()
1613 && otherInfo->frameContainsPoint(x, y)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001614 return true;
1615 }
1616 }
1617 return false;
1618}
1619
Jeff Brownd1c48a02012-02-06 19:12:47 -08001620bool InputDispatcher::isWindowReadyForMoreInputLocked(nsecs_t currentTime,
1621 const sp<InputWindowHandle>& windowHandle, bool focusedEvent) {
Jeff Browncc4f7db2011-08-30 20:34:48 -07001622 ssize_t connectionIndex = getConnectionIndexLocked(windowHandle->getInputChannel());
Jeff Brown519e0242010-09-15 15:18:56 -07001623 if (connectionIndex >= 0) {
Jeff Browncbee6d62012-02-03 20:11:27 -08001624 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
Jeff Brownd1c48a02012-02-06 19:12:47 -08001625 if (connection->inputPublisherBlocked) {
1626 return false;
1627 }
1628 if (focusedEvent) {
1629 // If the event relies on input focus (such as a key event), then we must
1630 // wait for all previous events to complete before delivering it because they
1631 // may move focus elsewhere.
1632 return connection->outboundQueue.isEmpty()
1633 && connection->waitQueue.isEmpty();
1634 }
1635 // Touch events can always be sent to a window because the user intended to touch
1636 // whatever was visible immediately. Even if focus changes or a new window appears,
1637 // the touch event was meant for whatever happened to be on screen at the time.
1638 // However, if the wait queue is piling up with lots of events, then hold up
1639 // new events for awhile. This condition ensures that ANRs still work.
1640 if (!connection->waitQueue.isEmpty()
1641 && currentTime >= connection->waitQueue.head->eventEntry->eventTime
1642 + STREAM_AHEAD_EVENT_TIMEOUT) {
1643 return false;
1644 }
Jeff Brown519e0242010-09-15 15:18:56 -07001645 }
Jeff Brownd1c48a02012-02-06 19:12:47 -08001646 return true;
Jeff Brown519e0242010-09-15 15:18:56 -07001647}
1648
Jeff Brown9302c872011-07-13 22:51:29 -07001649String8 InputDispatcher::getApplicationWindowLabelLocked(
1650 const sp<InputApplicationHandle>& applicationHandle,
1651 const sp<InputWindowHandle>& windowHandle) {
1652 if (applicationHandle != NULL) {
1653 if (windowHandle != NULL) {
Jeff Browncc4f7db2011-08-30 20:34:48 -07001654 String8 label(applicationHandle->getName());
Jeff Brown519e0242010-09-15 15:18:56 -07001655 label.append(" - ");
Jeff Browncc4f7db2011-08-30 20:34:48 -07001656 label.append(windowHandle->getName());
Jeff Brown519e0242010-09-15 15:18:56 -07001657 return label;
1658 } else {
Jeff Browncc4f7db2011-08-30 20:34:48 -07001659 return applicationHandle->getName();
Jeff Brown519e0242010-09-15 15:18:56 -07001660 }
Jeff Brown9302c872011-07-13 22:51:29 -07001661 } else if (windowHandle != NULL) {
Jeff Browncc4f7db2011-08-30 20:34:48 -07001662 return windowHandle->getName();
Jeff Brown519e0242010-09-15 15:18:56 -07001663 } else {
1664 return String8("<unknown application or window>");
1665 }
1666}
1667
Jeff Browne2fe69e2010-10-18 13:21:23 -07001668void InputDispatcher::pokeUserActivityLocked(const EventEntry* eventEntry) {
Jeff Brown56194eb2011-03-02 19:23:13 -08001669 int32_t eventType = POWER_MANAGER_OTHER_EVENT;
Jeff Brown4d396052010-10-29 21:50:21 -07001670 switch (eventEntry->type) {
1671 case EventEntry::TYPE_MOTION: {
Jeff Browne2fe69e2010-10-18 13:21:23 -07001672 const MotionEntry* motionEntry = static_cast<const MotionEntry*>(eventEntry);
Jeff Brown4d396052010-10-29 21:50:21 -07001673 if (motionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
1674 return;
1675 }
1676
Jeff Brown56194eb2011-03-02 19:23:13 -08001677 if (MotionEvent::isTouchEvent(motionEntry->source, motionEntry->action)) {
Joe Onorato1a542c72010-11-08 09:48:20 -08001678 eventType = POWER_MANAGER_TOUCH_EVENT;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001679 }
Jeff Brown4d396052010-10-29 21:50:21 -07001680 break;
1681 }
1682 case EventEntry::TYPE_KEY: {
1683 const KeyEntry* keyEntry = static_cast<const KeyEntry*>(eventEntry);
1684 if (keyEntry->flags & AKEY_EVENT_FLAG_CANCELED) {
1685 return;
1686 }
Jeff Brown56194eb2011-03-02 19:23:13 -08001687 eventType = POWER_MANAGER_BUTTON_EVENT;
Jeff Brown4d396052010-10-29 21:50:21 -07001688 break;
1689 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001690 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001691
Jeff Brownb88102f2010-09-08 11:49:43 -07001692 CommandEntry* commandEntry = postCommandLocked(
1693 & InputDispatcher::doPokeUserActivityLockedInterruptible);
Jeff Browne2fe69e2010-10-18 13:21:23 -07001694 commandEntry->eventTime = eventEntry->eventTime;
Jeff Brownb88102f2010-09-08 11:49:43 -07001695 commandEntry->userActivityEventType = eventType;
1696}
1697
Jeff Brown7fbdc842010-06-17 20:52:56 -07001698void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001699 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001700#if DEBUG_DISPATCH_CYCLE
Steve Block5baa3a62011-12-20 16:23:08 +00001701 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
Jeff Brown9cc695c2011-08-23 18:35:04 -07001702 "xOffset=%f, yOffset=%f, scaleFactor=%f, "
Jeff Brown3241b6b2012-02-03 15:08:02 -08001703 "pointerIds=0x%x",
Jeff Brown519e0242010-09-15 15:18:56 -07001704 connection->getInputChannelName(), inputTarget->flags,
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001705 inputTarget->xOffset, inputTarget->yOffset,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001706 inputTarget->scaleFactor, inputTarget->pointerIds.value);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001707#endif
1708
1709 // Skip this event if the connection status is not normal.
Jeff Brown519e0242010-09-15 15:18:56 -07001710 // We don't want to enqueue additional outbound events if the connection is broken.
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001711 if (connection->status != Connection::STATUS_NORMAL) {
Jeff Brownb6997262010-10-08 22:31:17 -07001712#if DEBUG_DISPATCH_CYCLE
Steve Block5baa3a62011-12-20 16:23:08 +00001713 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Jeff Brownb88102f2010-09-08 11:49:43 -07001714 connection->getInputChannelName(), connection->getStatusLabel());
Jeff Brownb6997262010-10-08 22:31:17 -07001715#endif
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001716 return;
1717 }
1718
Jeff Brown01ce2e92010-09-26 22:20:12 -07001719 // Split a motion event if needed.
Jeff Brown3241b6b2012-02-03 15:08:02 -08001720 if (inputTarget->flags & InputTarget::FLAG_SPLIT) {
Steve Blockec193de2012-01-09 18:35:44 +00001721 ALOG_ASSERT(eventEntry->type == EventEntry::TYPE_MOTION);
Jeff Brown01ce2e92010-09-26 22:20:12 -07001722
1723 MotionEntry* originalMotionEntry = static_cast<MotionEntry*>(eventEntry);
1724 if (inputTarget->pointerIds.count() != originalMotionEntry->pointerCount) {
1725 MotionEntry* splitMotionEntry = splitMotionEvent(
1726 originalMotionEntry, inputTarget->pointerIds);
Jeff Brown58a2da82011-01-25 16:02:22 -08001727 if (!splitMotionEntry) {
1728 return; // split event was dropped
1729 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001730#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001731 ALOGD("channel '%s' ~ Split motion event.",
Jeff Brown01ce2e92010-09-26 22:20:12 -07001732 connection->getInputChannelName());
1733 logOutboundMotionDetailsLocked(" ", splitMotionEntry);
1734#endif
Jeff Brownc0cb3dc2012-01-12 18:30:12 -08001735 enqueueDispatchEntriesLocked(currentTime, connection,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001736 splitMotionEntry, inputTarget);
Jeff Brownc0cb3dc2012-01-12 18:30:12 -08001737 splitMotionEntry->release();
1738 return;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001739 }
1740 }
1741
Jeff Brownc0cb3dc2012-01-12 18:30:12 -08001742 // Not splitting. Enqueue dispatch entries for the event as is.
Jeff Brown3241b6b2012-02-03 15:08:02 -08001743 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
Jeff Brownc0cb3dc2012-01-12 18:30:12 -08001744}
1745
1746void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001747 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001748 bool wasEmpty = connection->outboundQueue.isEmpty();
1749
Jeff Browna032cc02011-03-07 16:56:21 -08001750 // Enqueue dispatch entries for the requested modes.
1751 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001752 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
Jeff Browna032cc02011-03-07 16:56:21 -08001753 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001754 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
Jeff Browna032cc02011-03-07 16:56:21 -08001755 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001756 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
Jeff Browna032cc02011-03-07 16:56:21 -08001757 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001758 InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brown98db5fa2011-06-08 15:37:10 -07001759 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001760 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
Jeff Brown98db5fa2011-06-08 15:37:10 -07001761 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001762 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Jeff Browna032cc02011-03-07 16:56:21 -08001763
1764 // If the outbound queue was previously empty, start the dispatch cycle going.
Jeff Brownb6110c22011-04-01 16:15:13 -07001765 if (wasEmpty && !connection->outboundQueue.isEmpty()) {
Jeff Browna032cc02011-03-07 16:56:21 -08001766 startDispatchCycleLocked(currentTime, connection);
1767 }
1768}
1769
1770void InputDispatcher::enqueueDispatchEntryLocked(
1771 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001772 int32_t dispatchMode) {
Jeff Browna032cc02011-03-07 16:56:21 -08001773 int32_t inputTargetFlags = inputTarget->flags;
1774 if (!(inputTargetFlags & dispatchMode)) {
1775 return;
1776 }
1777 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
1778
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001779 // This is a new event.
1780 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Jeff Brownac386072011-07-20 15:19:50 -07001781 DispatchEntry* dispatchEntry = new DispatchEntry(eventEntry, // increments ref
Dianne Hackbornaa9d84c2011-05-09 19:00:59 -07001782 inputTargetFlags, inputTarget->xOffset, inputTarget->yOffset,
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001783 inputTarget->scaleFactor);
Jeff Brown6ec402b2010-07-28 15:48:59 -07001784
Jeff Brown81346812011-06-28 20:08:48 -07001785 // Apply target flags and update the connection's input state.
1786 switch (eventEntry->type) {
1787 case EventEntry::TYPE_KEY: {
1788 KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
1789 dispatchEntry->resolvedAction = keyEntry->action;
1790 dispatchEntry->resolvedFlags = keyEntry->flags;
1791
1792 if (!connection->inputState.trackKey(keyEntry,
1793 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags)) {
1794#if DEBUG_DISPATCH_CYCLE
Steve Block5baa3a62011-12-20 16:23:08 +00001795 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
Jeff Brown81346812011-06-28 20:08:48 -07001796 connection->getInputChannelName());
1797#endif
Jeff Brownc0cb3dc2012-01-12 18:30:12 -08001798 delete dispatchEntry;
Jeff Brown81346812011-06-28 20:08:48 -07001799 return; // skip the inconsistent event
1800 }
1801 break;
1802 }
1803
1804 case EventEntry::TYPE_MOTION: {
1805 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
1806 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
1807 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
1808 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
1809 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
1810 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
1811 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
1812 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
1813 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
1814 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
1815 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
1816 } else {
1817 dispatchEntry->resolvedAction = motionEntry->action;
1818 }
1819 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE
1820 && !connection->inputState.isHovering(
1821 motionEntry->deviceId, motionEntry->source)) {
1822#if DEBUG_DISPATCH_CYCLE
Steve Block5baa3a62011-12-20 16:23:08 +00001823 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter event",
Jeff Brown81346812011-06-28 20:08:48 -07001824 connection->getInputChannelName());
1825#endif
1826 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
1827 }
1828
1829 dispatchEntry->resolvedFlags = motionEntry->flags;
1830 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
1831 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
1832 }
1833
1834 if (!connection->inputState.trackMotion(motionEntry,
1835 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags)) {
1836#if DEBUG_DISPATCH_CYCLE
Steve Block5baa3a62011-12-20 16:23:08 +00001837 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion event",
Jeff Brown81346812011-06-28 20:08:48 -07001838 connection->getInputChannelName());
1839#endif
Jeff Brownc0cb3dc2012-01-12 18:30:12 -08001840 delete dispatchEntry;
Jeff Brown81346812011-06-28 20:08:48 -07001841 return; // skip the inconsistent event
1842 }
1843 break;
1844 }
1845 }
1846
Jeff Brownc0cb3dc2012-01-12 18:30:12 -08001847 // Remember that we are waiting for this dispatch to complete.
1848 if (dispatchEntry->hasForegroundTarget()) {
1849 incrementPendingForegroundDispatchesLocked(eventEntry);
1850 }
1851
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001852 // Enqueue the dispatch entry.
1853 connection->outboundQueue.enqueueAtTail(dispatchEntry);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001854}
1855
Jeff Brown7fbdc842010-06-17 20:52:56 -07001856void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Jeff Brown519e0242010-09-15 15:18:56 -07001857 const sp<Connection>& connection) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001858#if DEBUG_DISPATCH_CYCLE
Steve Block5baa3a62011-12-20 16:23:08 +00001859 ALOGD("channel '%s' ~ startDispatchCycle",
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001860 connection->getInputChannelName());
1861#endif
1862
Jeff Brownd1c48a02012-02-06 19:12:47 -08001863 while (connection->status == Connection::STATUS_NORMAL
1864 && !connection->outboundQueue.isEmpty()) {
1865 DispatchEntry* dispatchEntry = connection->outboundQueue.head;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001866
Jeff Brownd1c48a02012-02-06 19:12:47 -08001867 // Publish the event.
1868 status_t status;
1869 EventEntry* eventEntry = dispatchEntry->eventEntry;
1870 switch (eventEntry->type) {
1871 case EventEntry::TYPE_KEY: {
1872 KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001873
Jeff Brownd1c48a02012-02-06 19:12:47 -08001874 // Publish the key event.
1875 status = connection->inputPublisher.publishKeyEvent(
1876 keyEntry->deviceId, keyEntry->source,
1877 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags,
1878 keyEntry->keyCode, keyEntry->scanCode,
1879 keyEntry->metaState, keyEntry->repeatCount, keyEntry->downTime,
1880 keyEntry->eventTime);
1881 break;
1882 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001883
Jeff Brownd1c48a02012-02-06 19:12:47 -08001884 case EventEntry::TYPE_MOTION: {
1885 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001886
Jeff Brownd1c48a02012-02-06 19:12:47 -08001887 PointerCoords scaledCoords[MAX_POINTERS];
1888 const PointerCoords* usingCoords = motionEntry->pointerCoords;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001889
Jeff Brownd1c48a02012-02-06 19:12:47 -08001890 // Set the X and Y offset depending on the input source.
1891 float xOffset, yOffset, scaleFactor;
1892 if ((motionEntry->source & AINPUT_SOURCE_CLASS_POINTER)
1893 && !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
1894 scaleFactor = dispatchEntry->scaleFactor;
1895 xOffset = dispatchEntry->xOffset * scaleFactor;
1896 yOffset = dispatchEntry->yOffset * scaleFactor;
1897 if (scaleFactor != 1.0f) {
1898 for (size_t i = 0; i < motionEntry->pointerCount; i++) {
1899 scaledCoords[i] = motionEntry->pointerCoords[i];
1900 scaledCoords[i].scale(scaleFactor);
1901 }
1902 usingCoords = scaledCoords;
1903 }
1904 } else {
1905 xOffset = 0.0f;
1906 yOffset = 0.0f;
1907 scaleFactor = 1.0f;
1908
1909 // We don't want the dispatch target to know.
1910 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
1911 for (size_t i = 0; i < motionEntry->pointerCount; i++) {
1912 scaledCoords[i].clear();
1913 }
1914 usingCoords = scaledCoords;
1915 }
1916 }
1917
1918 // Publish the motion event.
1919 status = connection->inputPublisher.publishMotionEvent(
1920 motionEntry->deviceId, motionEntry->source,
1921 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags,
1922 motionEntry->edgeFlags, motionEntry->metaState, motionEntry->buttonState,
1923 xOffset, yOffset,
1924 motionEntry->xPrecision, motionEntry->yPrecision,
1925 motionEntry->downTime, motionEntry->eventTime,
1926 motionEntry->pointerCount, motionEntry->pointerProperties,
1927 usingCoords);
1928 break;
1929 }
1930
1931 default:
1932 ALOG_ASSERT(false);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001933 return;
1934 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001935
Jeff Brownd1c48a02012-02-06 19:12:47 -08001936 // Check the result.
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001937 if (status) {
Jeff Brownd1c48a02012-02-06 19:12:47 -08001938 if (status == WOULD_BLOCK) {
1939 if (connection->waitQueue.isEmpty()) {
1940 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
1941 "This is unexpected because the wait queue is empty, so the pipe "
1942 "should be empty and we shouldn't have any problems writing an "
1943 "event to it, status=%d", connection->getInputChannelName(), status);
1944 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
1945 } else {
1946 // Pipe is full and we are waiting for the app to finish process some events
1947 // before sending more events to it.
1948#if DEBUG_DISPATCH_CYCLE
1949 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
1950 "waiting for the application to catch up",
1951 connection->getInputChannelName());
1952#endif
1953 connection->inputPublisherBlocked = true;
1954 }
1955 } else {
1956 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
1957 "status=%d", connection->getInputChannelName(), status);
1958 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
1959 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001960 return;
1961 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001962
Jeff Brownd1c48a02012-02-06 19:12:47 -08001963 // Re-enqueue the event on the wait queue.
1964 connection->outboundQueue.dequeue(dispatchEntry);
1965 connection->waitQueue.enqueueAtTail(dispatchEntry);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001966 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001967}
1968
Jeff Brown7fbdc842010-06-17 20:52:56 -07001969void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Jeff Brown3915bb82010-11-05 15:02:16 -07001970 const sp<Connection>& connection, bool handled) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001971#if DEBUG_DISPATCH_CYCLE
Jeff Brown59f1ff92012-02-06 16:23:50 -08001972 ALOGD("channel '%s' ~ finishDispatchCycle - handled=%s",
1973 connection->getInputChannelName(), toString(handled));
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001974#endif
1975
Jeff Brownd1c48a02012-02-06 19:12:47 -08001976 connection->inputPublisherBlocked = false;
1977
Jeff Brown9c3cda02010-06-15 01:31:58 -07001978 if (connection->status == Connection::STATUS_BROKEN
1979 || connection->status == Connection::STATUS_ZOMBIE) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001980 return;
1981 }
1982
Jeff Brown3915bb82010-11-05 15:02:16 -07001983 // Notify other system components and prepare to start the next dispatch cycle.
1984 onDispatchCycleFinishedLocked(currentTime, connection, handled);
Jeff Brownb88102f2010-09-08 11:49:43 -07001985}
1986
Jeff Brownb6997262010-10-08 22:31:17 -07001987void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Jeff Browncc4f7db2011-08-30 20:34:48 -07001988 const sp<Connection>& connection, bool notify) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001989#if DEBUG_DISPATCH_CYCLE
Steve Block5baa3a62011-12-20 16:23:08 +00001990 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
Jeff Browncc4f7db2011-08-30 20:34:48 -07001991 connection->getInputChannelName(), toString(notify));
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001992#endif
1993
Jeff Brownd1c48a02012-02-06 19:12:47 -08001994 // Clear the dispatch queues.
1995 drainDispatchQueueLocked(&connection->outboundQueue);
1996 drainDispatchQueueLocked(&connection->waitQueue);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001997
Jeff Brownb6997262010-10-08 22:31:17 -07001998 // The connection appears to be unrecoverably broken.
Jeff Brown9c3cda02010-06-15 01:31:58 -07001999 // Ignore already broken or zombie connections.
Jeff Brownb6997262010-10-08 22:31:17 -07002000 if (connection->status == Connection::STATUS_NORMAL) {
2001 connection->status = Connection::STATUS_BROKEN;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002002
Jeff Browncc4f7db2011-08-30 20:34:48 -07002003 if (notify) {
2004 // Notify other system components.
2005 onDispatchCycleBrokenLocked(currentTime, connection);
2006 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002007 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002008}
2009
Jeff Brownd1c48a02012-02-06 19:12:47 -08002010void InputDispatcher::drainDispatchQueueLocked(Queue<DispatchEntry>* queue) {
2011 while (!queue->isEmpty()) {
2012 DispatchEntry* dispatchEntry = queue->dequeueAtHead();
2013 releaseDispatchEntryLocked(dispatchEntry);
Jeff Brownb88102f2010-09-08 11:49:43 -07002014 }
Jeff Brownb88102f2010-09-08 11:49:43 -07002015}
2016
Jeff Brownd1c48a02012-02-06 19:12:47 -08002017void InputDispatcher::releaseDispatchEntryLocked(DispatchEntry* dispatchEntry) {
2018 if (dispatchEntry->hasForegroundTarget()) {
2019 decrementPendingForegroundDispatchesLocked(dispatchEntry->eventEntry);
2020 }
2021 delete dispatchEntry;
2022}
2023
Jeff Browncbee6d62012-02-03 20:11:27 -08002024int InputDispatcher::handleReceiveCallback(int fd, int events, void* data) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002025 InputDispatcher* d = static_cast<InputDispatcher*>(data);
2026
2027 { // acquire lock
2028 AutoMutex _l(d->mLock);
2029
Jeff Browncbee6d62012-02-03 20:11:27 -08002030 ssize_t connectionIndex = d->mConnectionsByFd.indexOfKey(fd);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002031 if (connectionIndex < 0) {
Steve Block3762c312012-01-06 19:20:56 +00002032 ALOGE("Received spurious receive callback for unknown input channel. "
Jeff Browncbee6d62012-02-03 20:11:27 -08002033 "fd=%d, events=0x%x", fd, events);
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002034 return 0; // remove the callback
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002035 }
2036
Jeff Browncc4f7db2011-08-30 20:34:48 -07002037 bool notify;
Jeff Browncbee6d62012-02-03 20:11:27 -08002038 sp<Connection> connection = d->mConnectionsByFd.valueAt(connectionIndex);
Jeff Browncc4f7db2011-08-30 20:34:48 -07002039 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
2040 if (!(events & ALOOPER_EVENT_INPUT)) {
Steve Block8564c8d2012-01-05 23:22:43 +00002041 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
Jeff Browncc4f7db2011-08-30 20:34:48 -07002042 "events=0x%x", connection->getInputChannelName(), events);
2043 return 1;
2044 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002045
Jeff Browncc4f7db2011-08-30 20:34:48 -07002046 bool handled = false;
2047 status_t status = connection->inputPublisher.receiveFinishedSignal(&handled);
2048 if (!status) {
2049 nsecs_t currentTime = now();
2050 d->finishDispatchCycleLocked(currentTime, connection, handled);
2051 d->runCommandsLockedInterruptible();
2052 return 1;
2053 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002054
Steve Block3762c312012-01-06 19:20:56 +00002055 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002056 connection->getInputChannelName(), status);
Jeff Browncc4f7db2011-08-30 20:34:48 -07002057 notify = true;
2058 } else {
2059 // Monitor channels are never explicitly unregistered.
2060 // We do it automatically when the remote endpoint is closed so don't warn
2061 // about them.
2062 notify = !connection->monitor;
2063 if (notify) {
Steve Block8564c8d2012-01-05 23:22:43 +00002064 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. "
Jeff Browncc4f7db2011-08-30 20:34:48 -07002065 "events=0x%x", connection->getInputChannelName(), events);
2066 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002067 }
2068
Jeff Browncc4f7db2011-08-30 20:34:48 -07002069 // Unregister the channel.
2070 d->unregisterInputChannelLocked(connection->inputChannel, notify);
2071 return 0; // remove the callback
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002072 } // release lock
2073}
2074
Jeff Brownb6997262010-10-08 22:31:17 -07002075void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Jeff Brownda3d5a92011-03-29 15:11:34 -07002076 const CancelationOptions& options) {
Jeff Browncbee6d62012-02-03 20:11:27 -08002077 for (size_t i = 0; i < mConnectionsByFd.size(); i++) {
Jeff Brownb6997262010-10-08 22:31:17 -07002078 synthesizeCancelationEventsForConnectionLocked(
Jeff Browncbee6d62012-02-03 20:11:27 -08002079 mConnectionsByFd.valueAt(i), options);
Jeff Brownb6997262010-10-08 22:31:17 -07002080 }
2081}
2082
2083void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Jeff Brownda3d5a92011-03-29 15:11:34 -07002084 const sp<InputChannel>& channel, const CancelationOptions& options) {
Jeff Brownb6997262010-10-08 22:31:17 -07002085 ssize_t index = getConnectionIndexLocked(channel);
2086 if (index >= 0) {
2087 synthesizeCancelationEventsForConnectionLocked(
Jeff Browncbee6d62012-02-03 20:11:27 -08002088 mConnectionsByFd.valueAt(index), options);
Jeff Brownb6997262010-10-08 22:31:17 -07002089 }
2090}
2091
2092void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
Jeff Brownda3d5a92011-03-29 15:11:34 -07002093 const sp<Connection>& connection, const CancelationOptions& options) {
Jeff Brownc0cb3dc2012-01-12 18:30:12 -08002094 if (connection->status == Connection::STATUS_BROKEN) {
2095 return;
2096 }
2097
Jeff Brownb6997262010-10-08 22:31:17 -07002098 nsecs_t currentTime = now();
2099
Jeff Brown8b4be5602012-02-06 16:31:05 -08002100 Vector<EventEntry*> cancelationEvents;
Jeff Brownac386072011-07-20 15:19:50 -07002101 connection->inputState.synthesizeCancelationEvents(currentTime,
Jeff Brown8b4be5602012-02-06 16:31:05 -08002102 cancelationEvents, options);
Jeff Brownb6997262010-10-08 22:31:17 -07002103
Jeff Brown8b4be5602012-02-06 16:31:05 -08002104 if (!cancelationEvents.isEmpty()) {
Jeff Brownb6997262010-10-08 22:31:17 -07002105#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00002106 ALOGD("channel '%s' ~ Synthesized %d cancelation events to bring channel back in sync "
Jeff Brownda3d5a92011-03-29 15:11:34 -07002107 "with reality: %s, mode=%d.",
Jeff Brown8b4be5602012-02-06 16:31:05 -08002108 connection->getInputChannelName(), cancelationEvents.size(),
Jeff Brownda3d5a92011-03-29 15:11:34 -07002109 options.reason, options.mode);
Jeff Brownb6997262010-10-08 22:31:17 -07002110#endif
Jeff Brown8b4be5602012-02-06 16:31:05 -08002111 for (size_t i = 0; i < cancelationEvents.size(); i++) {
2112 EventEntry* cancelationEventEntry = cancelationEvents.itemAt(i);
Jeff Brownb6997262010-10-08 22:31:17 -07002113 switch (cancelationEventEntry->type) {
2114 case EventEntry::TYPE_KEY:
2115 logOutboundKeyDetailsLocked("cancel - ",
2116 static_cast<KeyEntry*>(cancelationEventEntry));
2117 break;
2118 case EventEntry::TYPE_MOTION:
2119 logOutboundMotionDetailsLocked("cancel - ",
2120 static_cast<MotionEntry*>(cancelationEventEntry));
2121 break;
2122 }
2123
Jeff Brown81346812011-06-28 20:08:48 -07002124 InputTarget target;
Jeff Brown9302c872011-07-13 22:51:29 -07002125 sp<InputWindowHandle> windowHandle = getWindowHandleLocked(connection->inputChannel);
2126 if (windowHandle != NULL) {
Jeff Browncc4f7db2011-08-30 20:34:48 -07002127 const InputWindowInfo* windowInfo = windowHandle->getInfo();
2128 target.xOffset = -windowInfo->frameLeft;
2129 target.yOffset = -windowInfo->frameTop;
2130 target.scaleFactor = windowInfo->scaleFactor;
Jeff Brownb6997262010-10-08 22:31:17 -07002131 } else {
Jeff Brown81346812011-06-28 20:08:48 -07002132 target.xOffset = 0;
2133 target.yOffset = 0;
2134 target.scaleFactor = 1.0f;
Jeff Brownb6997262010-10-08 22:31:17 -07002135 }
Jeff Brown81346812011-06-28 20:08:48 -07002136 target.inputChannel = connection->inputChannel;
2137 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
Jeff Brownb6997262010-10-08 22:31:17 -07002138
Jeff Brown81346812011-06-28 20:08:48 -07002139 enqueueDispatchEntryLocked(connection, cancelationEventEntry, // increments ref
Jeff Brown3241b6b2012-02-03 15:08:02 -08002140 &target, InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brownb6997262010-10-08 22:31:17 -07002141
Jeff Brownac386072011-07-20 15:19:50 -07002142 cancelationEventEntry->release();
Jeff Brownb6997262010-10-08 22:31:17 -07002143 }
2144
Jeff Brownd1c48a02012-02-06 19:12:47 -08002145 startDispatchCycleLocked(currentTime, connection);
Jeff Brownb6997262010-10-08 22:31:17 -07002146 }
2147}
2148
Jeff Brown01ce2e92010-09-26 22:20:12 -07002149InputDispatcher::MotionEntry*
2150InputDispatcher::splitMotionEvent(const MotionEntry* originalMotionEntry, BitSet32 pointerIds) {
Steve Blockec193de2012-01-09 18:35:44 +00002151 ALOG_ASSERT(pointerIds.value != 0);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002152
2153 uint32_t splitPointerIndexMap[MAX_POINTERS];
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002154 PointerProperties splitPointerProperties[MAX_POINTERS];
Jeff Brown01ce2e92010-09-26 22:20:12 -07002155 PointerCoords splitPointerCoords[MAX_POINTERS];
2156
2157 uint32_t originalPointerCount = originalMotionEntry->pointerCount;
2158 uint32_t splitPointerCount = 0;
2159
2160 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
2161 originalPointerIndex++) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002162 const PointerProperties& pointerProperties =
2163 originalMotionEntry->pointerProperties[originalPointerIndex];
2164 uint32_t pointerId = uint32_t(pointerProperties.id);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002165 if (pointerIds.hasBit(pointerId)) {
2166 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002167 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
Jeff Brownace13b12011-03-09 17:39:48 -08002168 splitPointerCoords[splitPointerCount].copyFrom(
Jeff Brown3241b6b2012-02-03 15:08:02 -08002169 originalMotionEntry->pointerCoords[originalPointerIndex]);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002170 splitPointerCount += 1;
2171 }
2172 }
Jeff Brown58a2da82011-01-25 16:02:22 -08002173
2174 if (splitPointerCount != pointerIds.count()) {
2175 // This is bad. We are missing some of the pointers that we expected to deliver.
2176 // Most likely this indicates that we received an ACTION_MOVE events that has
2177 // different pointer ids than we expected based on the previous ACTION_DOWN
2178 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
2179 // in this way.
Steve Block8564c8d2012-01-05 23:22:43 +00002180 ALOGW("Dropping split motion event because the pointer count is %d but "
Jeff Brown58a2da82011-01-25 16:02:22 -08002181 "we expected there to be %d pointers. This probably means we received "
2182 "a broken sequence of pointer ids from the input device.",
2183 splitPointerCount, pointerIds.count());
2184 return NULL;
2185 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07002186
2187 int32_t action = originalMotionEntry->action;
2188 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
2189 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
2190 || maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2191 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002192 const PointerProperties& pointerProperties =
2193 originalMotionEntry->pointerProperties[originalPointerIndex];
2194 uint32_t pointerId = uint32_t(pointerProperties.id);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002195 if (pointerIds.hasBit(pointerId)) {
2196 if (pointerIds.count() == 1) {
2197 // The first/last pointer went down/up.
2198 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
2199 ? AMOTION_EVENT_ACTION_DOWN : AMOTION_EVENT_ACTION_UP;
Jeff Brown9a01d052010-09-27 16:35:11 -07002200 } else {
2201 // A secondary pointer went down/up.
2202 uint32_t splitPointerIndex = 0;
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002203 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
Jeff Brown9a01d052010-09-27 16:35:11 -07002204 splitPointerIndex += 1;
2205 }
2206 action = maskedAction | (splitPointerIndex
2207 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002208 }
2209 } else {
2210 // An unrelated pointer changed.
2211 action = AMOTION_EVENT_ACTION_MOVE;
2212 }
2213 }
2214
Jeff Brownac386072011-07-20 15:19:50 -07002215 MotionEntry* splitMotionEntry = new MotionEntry(
Jeff Brown01ce2e92010-09-26 22:20:12 -07002216 originalMotionEntry->eventTime,
2217 originalMotionEntry->deviceId,
2218 originalMotionEntry->source,
2219 originalMotionEntry->policyFlags,
2220 action,
2221 originalMotionEntry->flags,
2222 originalMotionEntry->metaState,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002223 originalMotionEntry->buttonState,
Jeff Brown01ce2e92010-09-26 22:20:12 -07002224 originalMotionEntry->edgeFlags,
2225 originalMotionEntry->xPrecision,
2226 originalMotionEntry->yPrecision,
2227 originalMotionEntry->downTime,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002228 splitPointerCount, splitPointerProperties, splitPointerCoords);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002229
Jeff Browna032cc02011-03-07 16:56:21 -08002230 if (originalMotionEntry->injectionState) {
2231 splitMotionEntry->injectionState = originalMotionEntry->injectionState;
2232 splitMotionEntry->injectionState->refCount += 1;
2233 }
2234
Jeff Brown01ce2e92010-09-26 22:20:12 -07002235 return splitMotionEntry;
2236}
2237
Jeff Brownbe1aa822011-07-27 16:04:54 -07002238void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002239#if DEBUG_INBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00002240 ALOGD("notifyConfigurationChanged - eventTime=%lld", args->eventTime);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002241#endif
2242
Jeff Brownb88102f2010-09-08 11:49:43 -07002243 bool needWake;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002244 { // acquire lock
2245 AutoMutex _l(mLock);
2246
Jeff Brownbe1aa822011-07-27 16:04:54 -07002247 ConfigurationChangedEntry* newEntry = new ConfigurationChangedEntry(args->eventTime);
Jeff Brownb88102f2010-09-08 11:49:43 -07002248 needWake = enqueueInboundEventLocked(newEntry);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002249 } // release lock
2250
Jeff Brownb88102f2010-09-08 11:49:43 -07002251 if (needWake) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002252 mLooper->wake();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002253 }
2254}
2255
Jeff Brownbe1aa822011-07-27 16:04:54 -07002256void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002257#if DEBUG_INBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00002258 ALOGD("notifyKey - eventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, action=0x%x, "
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002259 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%lld",
Jeff Brownbe1aa822011-07-27 16:04:54 -07002260 args->eventTime, args->deviceId, args->source, args->policyFlags,
2261 args->action, args->flags, args->keyCode, args->scanCode,
2262 args->metaState, args->downTime);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002263#endif
Jeff Brownbe1aa822011-07-27 16:04:54 -07002264 if (!validateKeyEvent(args->action)) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002265 return;
2266 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002267
Jeff Brownbe1aa822011-07-27 16:04:54 -07002268 uint32_t policyFlags = args->policyFlags;
2269 int32_t flags = args->flags;
2270 int32_t metaState = args->metaState;
Jeff Brown1f245102010-11-18 20:53:46 -08002271 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
2272 policyFlags |= POLICY_FLAG_VIRTUAL;
2273 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
2274 }
Jeff Brown924c4d42011-03-07 16:40:47 -08002275 if (policyFlags & POLICY_FLAG_ALT) {
2276 metaState |= AMETA_ALT_ON | AMETA_ALT_LEFT_ON;
2277 }
2278 if (policyFlags & POLICY_FLAG_ALT_GR) {
2279 metaState |= AMETA_ALT_ON | AMETA_ALT_RIGHT_ON;
2280 }
2281 if (policyFlags & POLICY_FLAG_SHIFT) {
2282 metaState |= AMETA_SHIFT_ON | AMETA_SHIFT_LEFT_ON;
2283 }
2284 if (policyFlags & POLICY_FLAG_CAPS_LOCK) {
2285 metaState |= AMETA_CAPS_LOCK_ON;
2286 }
2287 if (policyFlags & POLICY_FLAG_FUNCTION) {
2288 metaState |= AMETA_FUNCTION_ON;
2289 }
Jeff Brown1f245102010-11-18 20:53:46 -08002290
Jeff Browne20c9e02010-10-11 14:20:19 -07002291 policyFlags |= POLICY_FLAG_TRUSTED;
Jeff Brown1f245102010-11-18 20:53:46 -08002292
2293 KeyEvent event;
Jeff Brownbe1aa822011-07-27 16:04:54 -07002294 event.initialize(args->deviceId, args->source, args->action,
2295 flags, args->keyCode, args->scanCode, metaState, 0,
2296 args->downTime, args->eventTime);
Jeff Brown1f245102010-11-18 20:53:46 -08002297
2298 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
2299
2300 if (policyFlags & POLICY_FLAG_WOKE_HERE) {
2301 flags |= AKEY_EVENT_FLAG_WOKE_HERE;
2302 }
Jeff Brownb6997262010-10-08 22:31:17 -07002303
Jeff Brownb88102f2010-09-08 11:49:43 -07002304 bool needWake;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002305 { // acquire lock
Jeff Brown0029c662011-03-30 02:25:18 -07002306 mLock.lock();
2307
2308 if (mInputFilterEnabled) {
2309 mLock.unlock();
2310
2311 policyFlags |= POLICY_FLAG_FILTERED;
2312 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2313 return; // event was consumed by the filter
2314 }
2315
2316 mLock.lock();
2317 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002318
Jeff Brown7fbdc842010-06-17 20:52:56 -07002319 int32_t repeatCount = 0;
Jeff Brownbe1aa822011-07-27 16:04:54 -07002320 KeyEntry* newEntry = new KeyEntry(args->eventTime,
2321 args->deviceId, args->source, policyFlags,
2322 args->action, flags, args->keyCode, args->scanCode,
2323 metaState, repeatCount, args->downTime);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002324
Jeff Brownb88102f2010-09-08 11:49:43 -07002325 needWake = enqueueInboundEventLocked(newEntry);
Jeff Brown0029c662011-03-30 02:25:18 -07002326 mLock.unlock();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002327 } // release lock
2328
Jeff Brownb88102f2010-09-08 11:49:43 -07002329 if (needWake) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002330 mLooper->wake();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002331 }
2332}
2333
Jeff Brownbe1aa822011-07-27 16:04:54 -07002334void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002335#if DEBUG_INBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00002336 ALOGD("notifyMotion - eventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, "
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002337 "action=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, edgeFlags=0x%x, "
Jeff Brown85a31762010-09-01 17:01:00 -07002338 "xPrecision=%f, yPrecision=%f, downTime=%lld",
Jeff Brownbe1aa822011-07-27 16:04:54 -07002339 args->eventTime, args->deviceId, args->source, args->policyFlags,
2340 args->action, args->flags, args->metaState, args->buttonState,
2341 args->edgeFlags, args->xPrecision, args->yPrecision, args->downTime);
2342 for (uint32_t i = 0; i < args->pointerCount; i++) {
Steve Block5baa3a62011-12-20 16:23:08 +00002343 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002344 "x=%f, y=%f, pressure=%f, size=%f, "
Jeff Brown85a31762010-09-01 17:01:00 -07002345 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
Jeff Brown8d608662010-08-30 03:02:23 -07002346 "orientation=%f",
Jeff Brownbe1aa822011-07-27 16:04:54 -07002347 i, args->pointerProperties[i].id,
2348 args->pointerProperties[i].toolType,
2349 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
2350 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
2351 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
2352 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
2353 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
2354 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
2355 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
2356 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
2357 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002358 }
2359#endif
Jeff Brownbe1aa822011-07-27 16:04:54 -07002360 if (!validateMotionEvent(args->action, args->pointerCount, args->pointerProperties)) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002361 return;
2362 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002363
Jeff Brownbe1aa822011-07-27 16:04:54 -07002364 uint32_t policyFlags = args->policyFlags;
Jeff Browne20c9e02010-10-11 14:20:19 -07002365 policyFlags |= POLICY_FLAG_TRUSTED;
Jeff Brownbe1aa822011-07-27 16:04:54 -07002366 mPolicy->interceptMotionBeforeQueueing(args->eventTime, /*byref*/ policyFlags);
Jeff Brownb6997262010-10-08 22:31:17 -07002367
Jeff Brownb88102f2010-09-08 11:49:43 -07002368 bool needWake;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002369 { // acquire lock
Jeff Brown0029c662011-03-30 02:25:18 -07002370 mLock.lock();
2371
2372 if (mInputFilterEnabled) {
2373 mLock.unlock();
2374
2375 MotionEvent event;
Jeff Brownbe1aa822011-07-27 16:04:54 -07002376 event.initialize(args->deviceId, args->source, args->action, args->flags,
2377 args->edgeFlags, args->metaState, args->buttonState, 0, 0,
2378 args->xPrecision, args->yPrecision,
2379 args->downTime, args->eventTime,
2380 args->pointerCount, args->pointerProperties, args->pointerCoords);
Jeff Brown0029c662011-03-30 02:25:18 -07002381
2382 policyFlags |= POLICY_FLAG_FILTERED;
2383 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2384 return; // event was consumed by the filter
2385 }
2386
2387 mLock.lock();
2388 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002389
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002390 // Just enqueue a new motion event.
Jeff Brownbe1aa822011-07-27 16:04:54 -07002391 MotionEntry* newEntry = new MotionEntry(args->eventTime,
2392 args->deviceId, args->source, policyFlags,
2393 args->action, args->flags, args->metaState, args->buttonState,
2394 args->edgeFlags, args->xPrecision, args->yPrecision, args->downTime,
2395 args->pointerCount, args->pointerProperties, args->pointerCoords);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002396
Jeff Brownb88102f2010-09-08 11:49:43 -07002397 needWake = enqueueInboundEventLocked(newEntry);
Jeff Brown0029c662011-03-30 02:25:18 -07002398 mLock.unlock();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002399 } // release lock
2400
Jeff Brownb88102f2010-09-08 11:49:43 -07002401 if (needWake) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002402 mLooper->wake();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002403 }
2404}
2405
Jeff Brownbe1aa822011-07-27 16:04:54 -07002406void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
Jeff Brownb6997262010-10-08 22:31:17 -07002407#if DEBUG_INBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00002408 ALOGD("notifySwitch - eventTime=%lld, policyFlags=0x%x, switchCode=%d, switchValue=%d",
Jeff Brownbe1aa822011-07-27 16:04:54 -07002409 args->eventTime, args->policyFlags,
2410 args->switchCode, args->switchValue);
Jeff Brownb6997262010-10-08 22:31:17 -07002411#endif
2412
Jeff Brownbe1aa822011-07-27 16:04:54 -07002413 uint32_t policyFlags = args->policyFlags;
Jeff Browne20c9e02010-10-11 14:20:19 -07002414 policyFlags |= POLICY_FLAG_TRUSTED;
Jeff Brownbe1aa822011-07-27 16:04:54 -07002415 mPolicy->notifySwitch(args->eventTime,
2416 args->switchCode, args->switchValue, policyFlags);
Jeff Brownb6997262010-10-08 22:31:17 -07002417}
2418
Jeff Brown65fd2512011-08-18 11:20:58 -07002419void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
2420#if DEBUG_INBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00002421 ALOGD("notifyDeviceReset - eventTime=%lld, deviceId=%d",
Jeff Brown65fd2512011-08-18 11:20:58 -07002422 args->eventTime, args->deviceId);
2423#endif
2424
2425 bool needWake;
2426 { // acquire lock
2427 AutoMutex _l(mLock);
2428
2429 DeviceResetEntry* newEntry = new DeviceResetEntry(args->eventTime, args->deviceId);
2430 needWake = enqueueInboundEventLocked(newEntry);
2431 } // release lock
2432
2433 if (needWake) {
2434 mLooper->wake();
2435 }
2436}
2437
Jeff Brown7fbdc842010-06-17 20:52:56 -07002438int32_t InputDispatcher::injectInputEvent(const InputEvent* event,
Jeff Brown0029c662011-03-30 02:25:18 -07002439 int32_t injectorPid, int32_t injectorUid, int32_t syncMode, int32_t timeoutMillis,
2440 uint32_t policyFlags) {
Jeff Brown7fbdc842010-06-17 20:52:56 -07002441#if DEBUG_INBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00002442 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Jeff Brown0029c662011-03-30 02:25:18 -07002443 "syncMode=%d, timeoutMillis=%d, policyFlags=0x%08x",
2444 event->getType(), injectorPid, injectorUid, syncMode, timeoutMillis, policyFlags);
Jeff Brown7fbdc842010-06-17 20:52:56 -07002445#endif
2446
2447 nsecs_t endTime = now() + milliseconds_to_nanoseconds(timeoutMillis);
Jeff Browne20c9e02010-10-11 14:20:19 -07002448
Jeff Brown0029c662011-03-30 02:25:18 -07002449 policyFlags |= POLICY_FLAG_INJECTED;
Jeff Browne20c9e02010-10-11 14:20:19 -07002450 if (hasInjectionPermission(injectorPid, injectorUid)) {
2451 policyFlags |= POLICY_FLAG_TRUSTED;
2452 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07002453
Jeff Brown3241b6b2012-02-03 15:08:02 -08002454 EventEntry* firstInjectedEntry;
2455 EventEntry* lastInjectedEntry;
Jeff Brownb6997262010-10-08 22:31:17 -07002456 switch (event->getType()) {
2457 case AINPUT_EVENT_TYPE_KEY: {
2458 const KeyEvent* keyEvent = static_cast<const KeyEvent*>(event);
2459 int32_t action = keyEvent->getAction();
2460 if (! validateKeyEvent(action)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07002461 return INPUT_EVENT_INJECTION_FAILED;
2462 }
2463
Jeff Brownb6997262010-10-08 22:31:17 -07002464 int32_t flags = keyEvent->getFlags();
Jeff Brown1f245102010-11-18 20:53:46 -08002465 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
2466 policyFlags |= POLICY_FLAG_VIRTUAL;
2467 }
2468
Jeff Brown0029c662011-03-30 02:25:18 -07002469 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
2470 mPolicy->interceptKeyBeforeQueueing(keyEvent, /*byref*/ policyFlags);
2471 }
Jeff Brown1f245102010-11-18 20:53:46 -08002472
2473 if (policyFlags & POLICY_FLAG_WOKE_HERE) {
2474 flags |= AKEY_EVENT_FLAG_WOKE_HERE;
2475 }
Jeff Brown6ec402b2010-07-28 15:48:59 -07002476
Jeff Brownb6997262010-10-08 22:31:17 -07002477 mLock.lock();
Jeff Brown3241b6b2012-02-03 15:08:02 -08002478 firstInjectedEntry = new KeyEntry(keyEvent->getEventTime(),
Jeff Brown1f245102010-11-18 20:53:46 -08002479 keyEvent->getDeviceId(), keyEvent->getSource(),
2480 policyFlags, action, flags,
2481 keyEvent->getKeyCode(), keyEvent->getScanCode(), keyEvent->getMetaState(),
Jeff Brownb6997262010-10-08 22:31:17 -07002482 keyEvent->getRepeatCount(), keyEvent->getDownTime());
Jeff Brown3241b6b2012-02-03 15:08:02 -08002483 lastInjectedEntry = firstInjectedEntry;
Jeff Brownb6997262010-10-08 22:31:17 -07002484 break;
2485 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07002486
Jeff Brownb6997262010-10-08 22:31:17 -07002487 case AINPUT_EVENT_TYPE_MOTION: {
2488 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
2489 int32_t action = motionEvent->getAction();
2490 size_t pointerCount = motionEvent->getPointerCount();
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002491 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
2492 if (! validateMotionEvent(action, pointerCount, pointerProperties)) {
Jeff Brownb6997262010-10-08 22:31:17 -07002493 return INPUT_EVENT_INJECTION_FAILED;
2494 }
2495
Jeff Brown0029c662011-03-30 02:25:18 -07002496 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
2497 nsecs_t eventTime = motionEvent->getEventTime();
2498 mPolicy->interceptMotionBeforeQueueing(eventTime, /*byref*/ policyFlags);
2499 }
Jeff Brownb6997262010-10-08 22:31:17 -07002500
2501 mLock.lock();
2502 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
2503 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
Jeff Brown3241b6b2012-02-03 15:08:02 -08002504 firstInjectedEntry = new MotionEntry(*sampleEventTimes,
Jeff Brownb6997262010-10-08 22:31:17 -07002505 motionEvent->getDeviceId(), motionEvent->getSource(), policyFlags,
2506 action, motionEvent->getFlags(),
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002507 motionEvent->getMetaState(), motionEvent->getButtonState(),
2508 motionEvent->getEdgeFlags(),
Jeff Brownb6997262010-10-08 22:31:17 -07002509 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
2510 motionEvent->getDownTime(), uint32_t(pointerCount),
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002511 pointerProperties, samplePointerCoords);
Jeff Brown3241b6b2012-02-03 15:08:02 -08002512 lastInjectedEntry = firstInjectedEntry;
Jeff Brownb6997262010-10-08 22:31:17 -07002513 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
2514 sampleEventTimes += 1;
2515 samplePointerCoords += pointerCount;
Jeff Brown3241b6b2012-02-03 15:08:02 -08002516 MotionEntry* nextInjectedEntry = new MotionEntry(*sampleEventTimes,
2517 motionEvent->getDeviceId(), motionEvent->getSource(), policyFlags,
2518 action, motionEvent->getFlags(),
2519 motionEvent->getMetaState(), motionEvent->getButtonState(),
2520 motionEvent->getEdgeFlags(),
2521 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
2522 motionEvent->getDownTime(), uint32_t(pointerCount),
2523 pointerProperties, samplePointerCoords);
2524 lastInjectedEntry->next = nextInjectedEntry;
2525 lastInjectedEntry = nextInjectedEntry;
Jeff Brownb6997262010-10-08 22:31:17 -07002526 }
Jeff Brownb6997262010-10-08 22:31:17 -07002527 break;
2528 }
2529
2530 default:
Steve Block8564c8d2012-01-05 23:22:43 +00002531 ALOGW("Cannot inject event of type %d", event->getType());
Jeff Brownb6997262010-10-08 22:31:17 -07002532 return INPUT_EVENT_INJECTION_FAILED;
2533 }
2534
Jeff Brownac386072011-07-20 15:19:50 -07002535 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
Jeff Brownb6997262010-10-08 22:31:17 -07002536 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
2537 injectionState->injectionIsAsync = true;
2538 }
2539
2540 injectionState->refCount += 1;
Jeff Brown3241b6b2012-02-03 15:08:02 -08002541 lastInjectedEntry->injectionState = injectionState;
Jeff Brownb6997262010-10-08 22:31:17 -07002542
Jeff Brown3241b6b2012-02-03 15:08:02 -08002543 bool needWake = false;
2544 for (EventEntry* entry = firstInjectedEntry; entry != NULL; ) {
2545 EventEntry* nextEntry = entry->next;
2546 needWake |= enqueueInboundEventLocked(entry);
2547 entry = nextEntry;
2548 }
2549
Jeff Brownb6997262010-10-08 22:31:17 -07002550 mLock.unlock();
Jeff Brown7fbdc842010-06-17 20:52:56 -07002551
Jeff Brownb88102f2010-09-08 11:49:43 -07002552 if (needWake) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002553 mLooper->wake();
Jeff Brown7fbdc842010-06-17 20:52:56 -07002554 }
2555
2556 int32_t injectionResult;
2557 { // acquire lock
2558 AutoMutex _l(mLock);
2559
Jeff Brown6ec402b2010-07-28 15:48:59 -07002560 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
2561 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
2562 } else {
2563 for (;;) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002564 injectionResult = injectionState->injectionResult;
Jeff Brown6ec402b2010-07-28 15:48:59 -07002565 if (injectionResult != INPUT_EVENT_INJECTION_PENDING) {
2566 break;
2567 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07002568
Jeff Brown7fbdc842010-06-17 20:52:56 -07002569 nsecs_t remainingTimeout = endTime - now();
2570 if (remainingTimeout <= 0) {
Jeff Brown6ec402b2010-07-28 15:48:59 -07002571#if DEBUG_INJECTION
Steve Block5baa3a62011-12-20 16:23:08 +00002572 ALOGD("injectInputEvent - Timed out waiting for injection result "
Jeff Brown6ec402b2010-07-28 15:48:59 -07002573 "to become available.");
2574#endif
Jeff Brown7fbdc842010-06-17 20:52:56 -07002575 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
2576 break;
2577 }
2578
Jeff Brown6ec402b2010-07-28 15:48:59 -07002579 mInjectionResultAvailableCondition.waitRelative(mLock, remainingTimeout);
2580 }
2581
2582 if (injectionResult == INPUT_EVENT_INJECTION_SUCCEEDED
2583 && syncMode == INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002584 while (injectionState->pendingForegroundDispatches != 0) {
Jeff Brown6ec402b2010-07-28 15:48:59 -07002585#if DEBUG_INJECTION
Steve Block5baa3a62011-12-20 16:23:08 +00002586 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
Jeff Brown01ce2e92010-09-26 22:20:12 -07002587 injectionState->pendingForegroundDispatches);
Jeff Brown6ec402b2010-07-28 15:48:59 -07002588#endif
2589 nsecs_t remainingTimeout = endTime - now();
2590 if (remainingTimeout <= 0) {
2591#if DEBUG_INJECTION
Steve Block5baa3a62011-12-20 16:23:08 +00002592 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
Jeff Brown6ec402b2010-07-28 15:48:59 -07002593 "dispatches to finish.");
2594#endif
2595 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
2596 break;
2597 }
2598
2599 mInjectionSyncFinishedCondition.waitRelative(mLock, remainingTimeout);
2600 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07002601 }
2602 }
2603
Jeff Brownac386072011-07-20 15:19:50 -07002604 injectionState->release();
Jeff Brown7fbdc842010-06-17 20:52:56 -07002605 } // release lock
2606
Jeff Brown6ec402b2010-07-28 15:48:59 -07002607#if DEBUG_INJECTION
Steve Block5baa3a62011-12-20 16:23:08 +00002608 ALOGD("injectInputEvent - Finished with result %d. "
Jeff Brown6ec402b2010-07-28 15:48:59 -07002609 "injectorPid=%d, injectorUid=%d",
2610 injectionResult, injectorPid, injectorUid);
2611#endif
2612
Jeff Brown7fbdc842010-06-17 20:52:56 -07002613 return injectionResult;
2614}
2615
Jeff Brownb6997262010-10-08 22:31:17 -07002616bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
2617 return injectorUid == 0
2618 || mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
2619}
2620
Jeff Brown7fbdc842010-06-17 20:52:56 -07002621void InputDispatcher::setInjectionResultLocked(EventEntry* entry, int32_t injectionResult) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002622 InjectionState* injectionState = entry->injectionState;
2623 if (injectionState) {
Jeff Brown7fbdc842010-06-17 20:52:56 -07002624#if DEBUG_INJECTION
Steve Block5baa3a62011-12-20 16:23:08 +00002625 ALOGD("Setting input event injection result to %d. "
Jeff Brown7fbdc842010-06-17 20:52:56 -07002626 "injectorPid=%d, injectorUid=%d",
Jeff Brown01ce2e92010-09-26 22:20:12 -07002627 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
Jeff Brown7fbdc842010-06-17 20:52:56 -07002628#endif
2629
Jeff Brown0029c662011-03-30 02:25:18 -07002630 if (injectionState->injectionIsAsync
2631 && !(entry->policyFlags & POLICY_FLAG_FILTERED)) {
Jeff Brown6ec402b2010-07-28 15:48:59 -07002632 // Log the outcome since the injector did not wait for the injection result.
2633 switch (injectionResult) {
2634 case INPUT_EVENT_INJECTION_SUCCEEDED:
Steve Block71f2cf12011-10-20 11:56:00 +01002635 ALOGV("Asynchronous input event injection succeeded.");
Jeff Brown6ec402b2010-07-28 15:48:59 -07002636 break;
2637 case INPUT_EVENT_INJECTION_FAILED:
Steve Block8564c8d2012-01-05 23:22:43 +00002638 ALOGW("Asynchronous input event injection failed.");
Jeff Brown6ec402b2010-07-28 15:48:59 -07002639 break;
2640 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
Steve Block8564c8d2012-01-05 23:22:43 +00002641 ALOGW("Asynchronous input event injection permission denied.");
Jeff Brown6ec402b2010-07-28 15:48:59 -07002642 break;
2643 case INPUT_EVENT_INJECTION_TIMED_OUT:
Steve Block8564c8d2012-01-05 23:22:43 +00002644 ALOGW("Asynchronous input event injection timed out.");
Jeff Brown6ec402b2010-07-28 15:48:59 -07002645 break;
2646 }
2647 }
2648
Jeff Brown01ce2e92010-09-26 22:20:12 -07002649 injectionState->injectionResult = injectionResult;
Jeff Brown7fbdc842010-06-17 20:52:56 -07002650 mInjectionResultAvailableCondition.broadcast();
2651 }
2652}
2653
Jeff Brown01ce2e92010-09-26 22:20:12 -07002654void InputDispatcher::incrementPendingForegroundDispatchesLocked(EventEntry* entry) {
2655 InjectionState* injectionState = entry->injectionState;
2656 if (injectionState) {
2657 injectionState->pendingForegroundDispatches += 1;
2658 }
2659}
2660
Jeff Brown519e0242010-09-15 15:18:56 -07002661void InputDispatcher::decrementPendingForegroundDispatchesLocked(EventEntry* entry) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002662 InjectionState* injectionState = entry->injectionState;
2663 if (injectionState) {
2664 injectionState->pendingForegroundDispatches -= 1;
Jeff Brown6ec402b2010-07-28 15:48:59 -07002665
Jeff Brown01ce2e92010-09-26 22:20:12 -07002666 if (injectionState->pendingForegroundDispatches == 0) {
2667 mInjectionSyncFinishedCondition.broadcast();
2668 }
Jeff Brownb88102f2010-09-08 11:49:43 -07002669 }
2670}
2671
Jeff Brown9302c872011-07-13 22:51:29 -07002672sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
2673 const sp<InputChannel>& inputChannel) const {
2674 size_t numWindows = mWindowHandles.size();
2675 for (size_t i = 0; i < numWindows; i++) {
2676 const sp<InputWindowHandle>& windowHandle = mWindowHandles.itemAt(i);
Jeff Browncc4f7db2011-08-30 20:34:48 -07002677 if (windowHandle->getInputChannel() == inputChannel) {
Jeff Brown9302c872011-07-13 22:51:29 -07002678 return windowHandle;
Jeff Brown01ce2e92010-09-26 22:20:12 -07002679 }
2680 }
2681 return NULL;
2682}
2683
Jeff Brown9302c872011-07-13 22:51:29 -07002684bool InputDispatcher::hasWindowHandleLocked(
2685 const sp<InputWindowHandle>& windowHandle) const {
2686 size_t numWindows = mWindowHandles.size();
2687 for (size_t i = 0; i < numWindows; i++) {
2688 if (mWindowHandles.itemAt(i) == windowHandle) {
2689 return true;
2690 }
2691 }
2692 return false;
2693}
2694
2695void InputDispatcher::setInputWindows(const Vector<sp<InputWindowHandle> >& inputWindowHandles) {
Jeff Brownb88102f2010-09-08 11:49:43 -07002696#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002697 ALOGD("setInputWindows");
Jeff Brownb88102f2010-09-08 11:49:43 -07002698#endif
2699 { // acquire lock
2700 AutoMutex _l(mLock);
2701
Jeff Browncc4f7db2011-08-30 20:34:48 -07002702 Vector<sp<InputWindowHandle> > oldWindowHandles = mWindowHandles;
Jeff Brown9302c872011-07-13 22:51:29 -07002703 mWindowHandles = inputWindowHandles;
Jeff Brownb6997262010-10-08 22:31:17 -07002704
Jeff Brown9302c872011-07-13 22:51:29 -07002705 sp<InputWindowHandle> newFocusedWindowHandle;
2706 bool foundHoveredWindow = false;
2707 for (size_t i = 0; i < mWindowHandles.size(); i++) {
2708 const sp<InputWindowHandle>& windowHandle = mWindowHandles.itemAt(i);
Jeff Browncc4f7db2011-08-30 20:34:48 -07002709 if (!windowHandle->updateInfo() || windowHandle->getInputChannel() == NULL) {
Jeff Brown9302c872011-07-13 22:51:29 -07002710 mWindowHandles.removeAt(i--);
2711 continue;
2712 }
Jeff Browncc4f7db2011-08-30 20:34:48 -07002713 if (windowHandle->getInfo()->hasFocus) {
Jeff Brown9302c872011-07-13 22:51:29 -07002714 newFocusedWindowHandle = windowHandle;
2715 }
2716 if (windowHandle == mLastHoverWindowHandle) {
2717 foundHoveredWindow = true;
Jeff Brownb88102f2010-09-08 11:49:43 -07002718 }
2719 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07002720
Jeff Brown9302c872011-07-13 22:51:29 -07002721 if (!foundHoveredWindow) {
2722 mLastHoverWindowHandle = NULL;
2723 }
2724
2725 if (mFocusedWindowHandle != newFocusedWindowHandle) {
2726 if (mFocusedWindowHandle != NULL) {
Jeff Brownb6997262010-10-08 22:31:17 -07002727#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002728 ALOGD("Focus left window: %s",
Jeff Browncc4f7db2011-08-30 20:34:48 -07002729 mFocusedWindowHandle->getName().string());
Jeff Brownb6997262010-10-08 22:31:17 -07002730#endif
Jeff Browncc4f7db2011-08-30 20:34:48 -07002731 sp<InputChannel> focusedInputChannel = mFocusedWindowHandle->getInputChannel();
2732 if (focusedInputChannel != NULL) {
Christopher Tated9be36c2011-08-16 16:09:33 -07002733 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
2734 "focus left window");
2735 synthesizeCancelationEventsForInputChannelLocked(
Jeff Browncc4f7db2011-08-30 20:34:48 -07002736 focusedInputChannel, options);
Christopher Tated9be36c2011-08-16 16:09:33 -07002737 }
Jeff Brownb6997262010-10-08 22:31:17 -07002738 }
Jeff Brown9302c872011-07-13 22:51:29 -07002739 if (newFocusedWindowHandle != NULL) {
Jeff Brownb6997262010-10-08 22:31:17 -07002740#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002741 ALOGD("Focus entered window: %s",
Jeff Browncc4f7db2011-08-30 20:34:48 -07002742 newFocusedWindowHandle->getName().string());
Jeff Brownb6997262010-10-08 22:31:17 -07002743#endif
Jeff Brown9302c872011-07-13 22:51:29 -07002744 }
2745 mFocusedWindowHandle = newFocusedWindowHandle;
Jeff Brownb6997262010-10-08 22:31:17 -07002746 }
2747
Jeff Brown9302c872011-07-13 22:51:29 -07002748 for (size_t i = 0; i < mTouchState.windows.size(); i++) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002749 TouchedWindow& touchedWindow = mTouchState.windows.editItemAt(i);
Jeff Brown9302c872011-07-13 22:51:29 -07002750 if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
Jeff Brownb6997262010-10-08 22:31:17 -07002751#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002752 ALOGD("Touched window was removed: %s",
Jeff Browncc4f7db2011-08-30 20:34:48 -07002753 touchedWindow.windowHandle->getName().string());
Jeff Brownb6997262010-10-08 22:31:17 -07002754#endif
Jeff Browncc4f7db2011-08-30 20:34:48 -07002755 sp<InputChannel> touchedInputChannel =
2756 touchedWindow.windowHandle->getInputChannel();
2757 if (touchedInputChannel != NULL) {
Christopher Tated9be36c2011-08-16 16:09:33 -07002758 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
2759 "touched window was removed");
2760 synthesizeCancelationEventsForInputChannelLocked(
Jeff Browncc4f7db2011-08-30 20:34:48 -07002761 touchedInputChannel, options);
Christopher Tated9be36c2011-08-16 16:09:33 -07002762 }
Jeff Brown9302c872011-07-13 22:51:29 -07002763 mTouchState.windows.removeAt(i--);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002764 }
2765 }
Jeff Browncc4f7db2011-08-30 20:34:48 -07002766
2767 // Release information for windows that are no longer present.
2768 // This ensures that unused input channels are released promptly.
2769 // Otherwise, they might stick around until the window handle is destroyed
2770 // which might not happen until the next GC.
2771 for (size_t i = 0; i < oldWindowHandles.size(); i++) {
2772 const sp<InputWindowHandle>& oldWindowHandle = oldWindowHandles.itemAt(i);
2773 if (!hasWindowHandleLocked(oldWindowHandle)) {
2774#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002775 ALOGD("Window went away: %s", oldWindowHandle->getName().string());
Jeff Browncc4f7db2011-08-30 20:34:48 -07002776#endif
2777 oldWindowHandle->releaseInfo();
2778 }
2779 }
Jeff Brownb88102f2010-09-08 11:49:43 -07002780 } // release lock
2781
2782 // Wake up poll loop since it may need to make new input dispatching choices.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002783 mLooper->wake();
Jeff Brownb88102f2010-09-08 11:49:43 -07002784}
2785
Jeff Brown9302c872011-07-13 22:51:29 -07002786void InputDispatcher::setFocusedApplication(
2787 const sp<InputApplicationHandle>& inputApplicationHandle) {
Jeff Brownb88102f2010-09-08 11:49:43 -07002788#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002789 ALOGD("setFocusedApplication");
Jeff Brownb88102f2010-09-08 11:49:43 -07002790#endif
2791 { // acquire lock
2792 AutoMutex _l(mLock);
2793
Jeff Browncc4f7db2011-08-30 20:34:48 -07002794 if (inputApplicationHandle != NULL && inputApplicationHandle->updateInfo()) {
Jeff Brown5ea29ab2011-07-27 11:50:51 -07002795 if (mFocusedApplicationHandle != inputApplicationHandle) {
2796 if (mFocusedApplicationHandle != NULL) {
Jeff Browne9bb9be2012-02-06 15:47:55 -08002797 resetANRTimeoutsLocked();
Jeff Browncc4f7db2011-08-30 20:34:48 -07002798 mFocusedApplicationHandle->releaseInfo();
Jeff Brown5ea29ab2011-07-27 11:50:51 -07002799 }
2800 mFocusedApplicationHandle = inputApplicationHandle;
2801 }
2802 } else if (mFocusedApplicationHandle != NULL) {
Jeff Browne9bb9be2012-02-06 15:47:55 -08002803 resetANRTimeoutsLocked();
Jeff Browncc4f7db2011-08-30 20:34:48 -07002804 mFocusedApplicationHandle->releaseInfo();
Jeff Brown9302c872011-07-13 22:51:29 -07002805 mFocusedApplicationHandle.clear();
Jeff Brownb88102f2010-09-08 11:49:43 -07002806 }
2807
2808#if DEBUG_FOCUS
Jeff Brownb6997262010-10-08 22:31:17 -07002809 //logDispatchStateLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -07002810#endif
2811 } // release lock
2812
2813 // Wake up poll loop since it may need to make new input dispatching choices.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002814 mLooper->wake();
Jeff Brownb88102f2010-09-08 11:49:43 -07002815}
2816
Jeff Brownb88102f2010-09-08 11:49:43 -07002817void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
2818#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002819 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
Jeff Brownb88102f2010-09-08 11:49:43 -07002820#endif
2821
2822 bool changed;
2823 { // acquire lock
2824 AutoMutex _l(mLock);
2825
2826 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
Jeff Brown120a4592010-10-27 18:43:51 -07002827 if (mDispatchFrozen && !frozen) {
Jeff Brownb88102f2010-09-08 11:49:43 -07002828 resetANRTimeoutsLocked();
2829 }
2830
Jeff Brown120a4592010-10-27 18:43:51 -07002831 if (mDispatchEnabled && !enabled) {
2832 resetAndDropEverythingLocked("dispatcher is being disabled");
2833 }
2834
Jeff Brownb88102f2010-09-08 11:49:43 -07002835 mDispatchEnabled = enabled;
2836 mDispatchFrozen = frozen;
2837 changed = true;
2838 } else {
2839 changed = false;
2840 }
2841
2842#if DEBUG_FOCUS
Jeff Brownb6997262010-10-08 22:31:17 -07002843 //logDispatchStateLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -07002844#endif
2845 } // release lock
2846
2847 if (changed) {
2848 // Wake up poll loop since it may need to make new input dispatching choices.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002849 mLooper->wake();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002850 }
2851}
2852
Jeff Brown0029c662011-03-30 02:25:18 -07002853void InputDispatcher::setInputFilterEnabled(bool enabled) {
2854#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002855 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
Jeff Brown0029c662011-03-30 02:25:18 -07002856#endif
2857
2858 { // acquire lock
2859 AutoMutex _l(mLock);
2860
2861 if (mInputFilterEnabled == enabled) {
2862 return;
2863 }
2864
2865 mInputFilterEnabled = enabled;
2866 resetAndDropEverythingLocked("input filter is being enabled or disabled");
2867 } // release lock
2868
2869 // Wake up poll loop since there might be work to do to drop everything.
2870 mLooper->wake();
2871}
2872
Jeff Browne6504122010-09-27 14:52:15 -07002873bool InputDispatcher::transferTouchFocus(const sp<InputChannel>& fromChannel,
2874 const sp<InputChannel>& toChannel) {
2875#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002876 ALOGD("transferTouchFocus: fromChannel=%s, toChannel=%s",
Jeff Browne6504122010-09-27 14:52:15 -07002877 fromChannel->getName().string(), toChannel->getName().string());
2878#endif
2879 { // acquire lock
2880 AutoMutex _l(mLock);
2881
Jeff Brown9302c872011-07-13 22:51:29 -07002882 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromChannel);
2883 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toChannel);
2884 if (fromWindowHandle == NULL || toWindowHandle == NULL) {
Jeff Browne6504122010-09-27 14:52:15 -07002885#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002886 ALOGD("Cannot transfer focus because from or to window not found.");
Jeff Browne6504122010-09-27 14:52:15 -07002887#endif
2888 return false;
2889 }
Jeff Brown9302c872011-07-13 22:51:29 -07002890 if (fromWindowHandle == toWindowHandle) {
Jeff Browne6504122010-09-27 14:52:15 -07002891#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002892 ALOGD("Trivial transfer to same window.");
Jeff Browne6504122010-09-27 14:52:15 -07002893#endif
2894 return true;
2895 }
2896
2897 bool found = false;
2898 for (size_t i = 0; i < mTouchState.windows.size(); i++) {
2899 const TouchedWindow& touchedWindow = mTouchState.windows[i];
Jeff Brown9302c872011-07-13 22:51:29 -07002900 if (touchedWindow.windowHandle == fromWindowHandle) {
Jeff Browne6504122010-09-27 14:52:15 -07002901 int32_t oldTargetFlags = touchedWindow.targetFlags;
2902 BitSet32 pointerIds = touchedWindow.pointerIds;
2903
2904 mTouchState.windows.removeAt(i);
2905
Jeff Brown46e75292010-11-10 16:53:45 -08002906 int32_t newTargetFlags = oldTargetFlags
Jeff Browna032cc02011-03-07 16:56:21 -08002907 & (InputTarget::FLAG_FOREGROUND
2908 | InputTarget::FLAG_SPLIT | InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brown9302c872011-07-13 22:51:29 -07002909 mTouchState.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Jeff Browne6504122010-09-27 14:52:15 -07002910
2911 found = true;
2912 break;
2913 }
2914 }
2915
2916 if (! found) {
2917#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002918 ALOGD("Focus transfer failed because from window did not have focus.");
Jeff Browne6504122010-09-27 14:52:15 -07002919#endif
2920 return false;
2921 }
2922
Jeff Brown9c9f1a32010-10-11 18:32:20 -07002923 ssize_t fromConnectionIndex = getConnectionIndexLocked(fromChannel);
2924 ssize_t toConnectionIndex = getConnectionIndexLocked(toChannel);
2925 if (fromConnectionIndex >= 0 && toConnectionIndex >= 0) {
Jeff Browncbee6d62012-02-03 20:11:27 -08002926 sp<Connection> fromConnection = mConnectionsByFd.valueAt(fromConnectionIndex);
2927 sp<Connection> toConnection = mConnectionsByFd.valueAt(toConnectionIndex);
Jeff Brown9c9f1a32010-10-11 18:32:20 -07002928
2929 fromConnection->inputState.copyPointerStateTo(toConnection->inputState);
Jeff Brownda3d5a92011-03-29 15:11:34 -07002930 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Jeff Brown9c9f1a32010-10-11 18:32:20 -07002931 "transferring touch focus from this window to another window");
Jeff Brownda3d5a92011-03-29 15:11:34 -07002932 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Jeff Brown9c9f1a32010-10-11 18:32:20 -07002933 }
2934
Jeff Browne6504122010-09-27 14:52:15 -07002935#if DEBUG_FOCUS
2936 logDispatchStateLocked();
2937#endif
2938 } // release lock
2939
2940 // Wake up poll loop since it may need to make new input dispatching choices.
2941 mLooper->wake();
2942 return true;
2943}
2944
Jeff Brown120a4592010-10-27 18:43:51 -07002945void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
2946#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002947 ALOGD("Resetting and dropping all events (%s).", reason);
Jeff Brown120a4592010-10-27 18:43:51 -07002948#endif
2949
Jeff Brownda3d5a92011-03-29 15:11:34 -07002950 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
2951 synthesizeCancelationEventsForAllConnectionsLocked(options);
Jeff Brown120a4592010-10-27 18:43:51 -07002952
2953 resetKeyRepeatLocked();
2954 releasePendingEventLocked();
2955 drainInboundQueueLocked();
Jeff Browne9bb9be2012-02-06 15:47:55 -08002956 resetANRTimeoutsLocked();
Jeff Brown120a4592010-10-27 18:43:51 -07002957
2958 mTouchState.reset();
Jeff Brown9302c872011-07-13 22:51:29 -07002959 mLastHoverWindowHandle.clear();
Jeff Brown120a4592010-10-27 18:43:51 -07002960}
2961
Jeff Brownb88102f2010-09-08 11:49:43 -07002962void InputDispatcher::logDispatchStateLocked() {
2963 String8 dump;
2964 dumpDispatchStateLocked(dump);
Jeff Brown2a95c2a2010-09-16 12:31:46 -07002965
2966 char* text = dump.lockBuffer(dump.size());
2967 char* start = text;
2968 while (*start != '\0') {
2969 char* end = strchr(start, '\n');
2970 if (*end == '\n') {
2971 *(end++) = '\0';
2972 }
Steve Block5baa3a62011-12-20 16:23:08 +00002973 ALOGD("%s", start);
Jeff Brown2a95c2a2010-09-16 12:31:46 -07002974 start = end;
2975 }
Jeff Brownb88102f2010-09-08 11:49:43 -07002976}
2977
2978void InputDispatcher::dumpDispatchStateLocked(String8& dump) {
Jeff Brownf2f487182010-10-01 17:46:21 -07002979 dump.appendFormat(INDENT "DispatchEnabled: %d\n", mDispatchEnabled);
2980 dump.appendFormat(INDENT "DispatchFrozen: %d\n", mDispatchFrozen);
Jeff Brownb88102f2010-09-08 11:49:43 -07002981
Jeff Brown9302c872011-07-13 22:51:29 -07002982 if (mFocusedApplicationHandle != NULL) {
Jeff Brownf2f487182010-10-01 17:46:21 -07002983 dump.appendFormat(INDENT "FocusedApplication: name='%s', dispatchingTimeout=%0.3fms\n",
Jeff Browncc4f7db2011-08-30 20:34:48 -07002984 mFocusedApplicationHandle->getName().string(),
2985 mFocusedApplicationHandle->getDispatchingTimeout(
2986 DEFAULT_INPUT_DISPATCHING_TIMEOUT) / 1000000.0);
Jeff Brownb88102f2010-09-08 11:49:43 -07002987 } else {
Jeff Brownf2f487182010-10-01 17:46:21 -07002988 dump.append(INDENT "FocusedApplication: <null>\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07002989 }
Jeff Brownf2f487182010-10-01 17:46:21 -07002990 dump.appendFormat(INDENT "FocusedWindow: name='%s'\n",
Jeff Browncc4f7db2011-08-30 20:34:48 -07002991 mFocusedWindowHandle != NULL ? mFocusedWindowHandle->getName().string() : "<null>");
Jeff Brownf2f487182010-10-01 17:46:21 -07002992
2993 dump.appendFormat(INDENT "TouchDown: %s\n", toString(mTouchState.down));
2994 dump.appendFormat(INDENT "TouchSplit: %s\n", toString(mTouchState.split));
Jeff Brown95712852011-01-04 19:41:59 -08002995 dump.appendFormat(INDENT "TouchDeviceId: %d\n", mTouchState.deviceId);
Jeff Brown58a2da82011-01-25 16:02:22 -08002996 dump.appendFormat(INDENT "TouchSource: 0x%08x\n", mTouchState.source);
Jeff Brownf2f487182010-10-01 17:46:21 -07002997 if (!mTouchState.windows.isEmpty()) {
2998 dump.append(INDENT "TouchedWindows:\n");
2999 for (size_t i = 0; i < mTouchState.windows.size(); i++) {
3000 const TouchedWindow& touchedWindow = mTouchState.windows[i];
3001 dump.appendFormat(INDENT2 "%d: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
Jeff Browncc4f7db2011-08-30 20:34:48 -07003002 i, touchedWindow.windowHandle->getName().string(),
3003 touchedWindow.pointerIds.value,
Jeff Brownf2f487182010-10-01 17:46:21 -07003004 touchedWindow.targetFlags);
3005 }
3006 } else {
3007 dump.append(INDENT "TouchedWindows: <none>\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003008 }
3009
Jeff Brown9302c872011-07-13 22:51:29 -07003010 if (!mWindowHandles.isEmpty()) {
Jeff Brownf2f487182010-10-01 17:46:21 -07003011 dump.append(INDENT "Windows:\n");
Jeff Brown9302c872011-07-13 22:51:29 -07003012 for (size_t i = 0; i < mWindowHandles.size(); i++) {
3013 const sp<InputWindowHandle>& windowHandle = mWindowHandles.itemAt(i);
Jeff Browncc4f7db2011-08-30 20:34:48 -07003014 const InputWindowInfo* windowInfo = windowHandle->getInfo();
3015
Jeff Brownf2f487182010-10-01 17:46:21 -07003016 dump.appendFormat(INDENT2 "%d: name='%s', paused=%s, hasFocus=%s, hasWallpaper=%s, "
3017 "visible=%s, canReceiveKeys=%s, flags=0x%08x, type=0x%08x, layer=%d, "
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003018 "frame=[%d,%d][%d,%d], scale=%f, "
Jeff Brownfbf09772011-01-16 14:06:57 -08003019 "touchableRegion=",
Jeff Browncc4f7db2011-08-30 20:34:48 -07003020 i, windowInfo->name.string(),
3021 toString(windowInfo->paused),
3022 toString(windowInfo->hasFocus),
3023 toString(windowInfo->hasWallpaper),
3024 toString(windowInfo->visible),
3025 toString(windowInfo->canReceiveKeys),
3026 windowInfo->layoutParamsFlags, windowInfo->layoutParamsType,
3027 windowInfo->layer,
3028 windowInfo->frameLeft, windowInfo->frameTop,
3029 windowInfo->frameRight, windowInfo->frameBottom,
3030 windowInfo->scaleFactor);
3031 dumpRegion(dump, windowInfo->touchableRegion);
3032 dump.appendFormat(", inputFeatures=0x%08x", windowInfo->inputFeatures);
Jeff Brownfbf09772011-01-16 14:06:57 -08003033 dump.appendFormat(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%0.3fms\n",
Jeff Browncc4f7db2011-08-30 20:34:48 -07003034 windowInfo->ownerPid, windowInfo->ownerUid,
3035 windowInfo->dispatchingTimeout / 1000000.0);
Jeff Brownf2f487182010-10-01 17:46:21 -07003036 }
3037 } else {
3038 dump.append(INDENT "Windows: <none>\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003039 }
3040
Jeff Brownf2f487182010-10-01 17:46:21 -07003041 if (!mMonitoringChannels.isEmpty()) {
3042 dump.append(INDENT "MonitoringChannels:\n");
3043 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
3044 const sp<InputChannel>& channel = mMonitoringChannels[i];
3045 dump.appendFormat(INDENT2 "%d: '%s'\n", i, channel->getName().string());
3046 }
3047 } else {
3048 dump.append(INDENT "MonitoringChannels: <none>\n");
3049 }
Jeff Brown519e0242010-09-15 15:18:56 -07003050
Jeff Brownf2f487182010-10-01 17:46:21 -07003051 dump.appendFormat(INDENT "InboundQueue: length=%u\n", mInboundQueue.count());
3052
Jeff Brownb88102f2010-09-08 11:49:43 -07003053 if (isAppSwitchPendingLocked()) {
Jeff Brownf2f487182010-10-01 17:46:21 -07003054 dump.appendFormat(INDENT "AppSwitch: pending, due in %01.1fms\n",
Jeff Brownb88102f2010-09-08 11:49:43 -07003055 (mAppSwitchDueTime - now()) / 1000000.0);
3056 } else {
Jeff Brownf2f487182010-10-01 17:46:21 -07003057 dump.append(INDENT "AppSwitch: not pending\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003058 }
3059}
3060
Jeff Brown928e0542011-01-10 11:17:36 -08003061status_t InputDispatcher::registerInputChannel(const sp<InputChannel>& inputChannel,
3062 const sp<InputWindowHandle>& inputWindowHandle, bool monitor) {
Jeff Brown9c3cda02010-06-15 01:31:58 -07003063#if DEBUG_REGISTRATION
Steve Block5baa3a62011-12-20 16:23:08 +00003064 ALOGD("channel '%s' ~ registerInputChannel - monitor=%s", inputChannel->getName().string(),
Jeff Brownb88102f2010-09-08 11:49:43 -07003065 toString(monitor));
Jeff Brown9c3cda02010-06-15 01:31:58 -07003066#endif
3067
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003068 { // acquire lock
3069 AutoMutex _l(mLock);
3070
Jeff Brown519e0242010-09-15 15:18:56 -07003071 if (getConnectionIndexLocked(inputChannel) >= 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00003072 ALOGW("Attempted to register already registered input channel '%s'",
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003073 inputChannel->getName().string());
3074 return BAD_VALUE;
3075 }
3076
Jeff Browncc4f7db2011-08-30 20:34:48 -07003077 sp<Connection> connection = new Connection(inputChannel, inputWindowHandle, monitor);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003078
Jeff Browncbee6d62012-02-03 20:11:27 -08003079 int32_t fd = inputChannel->getFd();
3080 mConnectionsByFd.add(fd, connection);
Jeff Brown9c3cda02010-06-15 01:31:58 -07003081
Jeff Brownb88102f2010-09-08 11:49:43 -07003082 if (monitor) {
3083 mMonitoringChannels.push(inputChannel);
3084 }
3085
Jeff Browncbee6d62012-02-03 20:11:27 -08003086 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
Jeff Brown2cbecea2010-08-17 15:59:26 -07003087
Jeff Brown9c3cda02010-06-15 01:31:58 -07003088 runCommandsLockedInterruptible();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003089 } // release lock
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003090 return OK;
3091}
3092
3093status_t InputDispatcher::unregisterInputChannel(const sp<InputChannel>& inputChannel) {
Jeff Brown9c3cda02010-06-15 01:31:58 -07003094#if DEBUG_REGISTRATION
Steve Block5baa3a62011-12-20 16:23:08 +00003095 ALOGD("channel '%s' ~ unregisterInputChannel", inputChannel->getName().string());
Jeff Brown9c3cda02010-06-15 01:31:58 -07003096#endif
3097
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003098 { // acquire lock
3099 AutoMutex _l(mLock);
3100
Jeff Browncc4f7db2011-08-30 20:34:48 -07003101 status_t status = unregisterInputChannelLocked(inputChannel, false /*notify*/);
3102 if (status) {
3103 return status;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003104 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003105 } // release lock
3106
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003107 // Wake the poll loop because removing the connection may have changed the current
3108 // synchronization state.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07003109 mLooper->wake();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003110 return OK;
3111}
3112
Jeff Browncc4f7db2011-08-30 20:34:48 -07003113status_t InputDispatcher::unregisterInputChannelLocked(const sp<InputChannel>& inputChannel,
3114 bool notify) {
3115 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
3116 if (connectionIndex < 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00003117 ALOGW("Attempted to unregister already unregistered input channel '%s'",
Jeff Browncc4f7db2011-08-30 20:34:48 -07003118 inputChannel->getName().string());
3119 return BAD_VALUE;
3120 }
3121
Jeff Browncbee6d62012-02-03 20:11:27 -08003122 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
3123 mConnectionsByFd.removeItemsAt(connectionIndex);
Jeff Browncc4f7db2011-08-30 20:34:48 -07003124
3125 if (connection->monitor) {
3126 removeMonitorChannelLocked(inputChannel);
3127 }
3128
Jeff Browncbee6d62012-02-03 20:11:27 -08003129 mLooper->removeFd(inputChannel->getFd());
Jeff Browncc4f7db2011-08-30 20:34:48 -07003130
3131 nsecs_t currentTime = now();
3132 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
3133
3134 runCommandsLockedInterruptible();
3135
3136 connection->status = Connection::STATUS_ZOMBIE;
3137 return OK;
3138}
3139
3140void InputDispatcher::removeMonitorChannelLocked(const sp<InputChannel>& inputChannel) {
3141 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
3142 if (mMonitoringChannels[i] == inputChannel) {
3143 mMonitoringChannels.removeAt(i);
3144 break;
3145 }
3146 }
3147}
3148
Jeff Brown519e0242010-09-15 15:18:56 -07003149ssize_t InputDispatcher::getConnectionIndexLocked(const sp<InputChannel>& inputChannel) {
Jeff Browncbee6d62012-02-03 20:11:27 -08003150 ssize_t connectionIndex = mConnectionsByFd.indexOfKey(inputChannel->getFd());
Jeff Brown2cbecea2010-08-17 15:59:26 -07003151 if (connectionIndex >= 0) {
Jeff Browncbee6d62012-02-03 20:11:27 -08003152 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
Jeff Brown2cbecea2010-08-17 15:59:26 -07003153 if (connection->inputChannel.get() == inputChannel.get()) {
3154 return connectionIndex;
3155 }
3156 }
3157
3158 return -1;
3159}
3160
Jeff Brown9c3cda02010-06-15 01:31:58 -07003161void InputDispatcher::onDispatchCycleFinishedLocked(
Jeff Brown3915bb82010-11-05 15:02:16 -07003162 nsecs_t currentTime, const sp<Connection>& connection, bool handled) {
3163 CommandEntry* commandEntry = postCommandLocked(
3164 & InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
3165 commandEntry->connection = connection;
3166 commandEntry->handled = handled;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003167}
3168
Jeff Brown9c3cda02010-06-15 01:31:58 -07003169void InputDispatcher::onDispatchCycleBrokenLocked(
Jeff Brown7fbdc842010-06-17 20:52:56 -07003170 nsecs_t currentTime, const sp<Connection>& connection) {
Steve Block3762c312012-01-06 19:20:56 +00003171 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003172 connection->getInputChannelName());
3173
Jeff Brown9c3cda02010-06-15 01:31:58 -07003174 CommandEntry* commandEntry = postCommandLocked(
3175 & InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
Jeff Brown7fbdc842010-06-17 20:52:56 -07003176 commandEntry->connection = connection;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003177}
3178
Jeff Brown519e0242010-09-15 15:18:56 -07003179void InputDispatcher::onANRLocked(
Jeff Brown9302c872011-07-13 22:51:29 -07003180 nsecs_t currentTime, const sp<InputApplicationHandle>& applicationHandle,
3181 const sp<InputWindowHandle>& windowHandle,
Jeff Brown519e0242010-09-15 15:18:56 -07003182 nsecs_t eventTime, nsecs_t waitStartTime) {
Steve Block6215d3f2012-01-04 20:05:49 +00003183 ALOGI("Application is not responding: %s. "
Jeff Brown519e0242010-09-15 15:18:56 -07003184 "%01.1fms since event, %01.1fms since wait started",
Jeff Brown9302c872011-07-13 22:51:29 -07003185 getApplicationWindowLabelLocked(applicationHandle, windowHandle).string(),
Jeff Brown519e0242010-09-15 15:18:56 -07003186 (currentTime - eventTime) / 1000000.0,
3187 (currentTime - waitStartTime) / 1000000.0);
3188
3189 CommandEntry* commandEntry = postCommandLocked(
3190 & InputDispatcher::doNotifyANRLockedInterruptible);
Jeff Brown9302c872011-07-13 22:51:29 -07003191 commandEntry->inputApplicationHandle = applicationHandle;
3192 commandEntry->inputWindowHandle = windowHandle;
Jeff Brown519e0242010-09-15 15:18:56 -07003193}
3194
Jeff Brownb88102f2010-09-08 11:49:43 -07003195void InputDispatcher::doNotifyConfigurationChangedInterruptible(
3196 CommandEntry* commandEntry) {
3197 mLock.unlock();
3198
3199 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
3200
3201 mLock.lock();
3202}
3203
Jeff Brown9c3cda02010-06-15 01:31:58 -07003204void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(
3205 CommandEntry* commandEntry) {
Jeff Brown7fbdc842010-06-17 20:52:56 -07003206 sp<Connection> connection = commandEntry->connection;
Jeff Brown9c3cda02010-06-15 01:31:58 -07003207
Jeff Brown7fbdc842010-06-17 20:52:56 -07003208 if (connection->status != Connection::STATUS_ZOMBIE) {
3209 mLock.unlock();
Jeff Brown9c3cda02010-06-15 01:31:58 -07003210
Jeff Brown928e0542011-01-10 11:17:36 -08003211 mPolicy->notifyInputChannelBroken(connection->inputWindowHandle);
Jeff Brown7fbdc842010-06-17 20:52:56 -07003212
3213 mLock.lock();
3214 }
Jeff Brown9c3cda02010-06-15 01:31:58 -07003215}
3216
Jeff Brown519e0242010-09-15 15:18:56 -07003217void InputDispatcher::doNotifyANRLockedInterruptible(
Jeff Brown9c3cda02010-06-15 01:31:58 -07003218 CommandEntry* commandEntry) {
Jeff Brown519e0242010-09-15 15:18:56 -07003219 mLock.unlock();
Jeff Brown9c3cda02010-06-15 01:31:58 -07003220
Jeff Brown519e0242010-09-15 15:18:56 -07003221 nsecs_t newTimeout = mPolicy->notifyANR(
Jeff Brown928e0542011-01-10 11:17:36 -08003222 commandEntry->inputApplicationHandle, commandEntry->inputWindowHandle);
Jeff Brown9c3cda02010-06-15 01:31:58 -07003223
Jeff Brown519e0242010-09-15 15:18:56 -07003224 mLock.lock();
Jeff Brown7fbdc842010-06-17 20:52:56 -07003225
Jeff Brown9302c872011-07-13 22:51:29 -07003226 resumeAfterTargetsNotReadyTimeoutLocked(newTimeout,
3227 commandEntry->inputWindowHandle != NULL
Jeff Browncc4f7db2011-08-30 20:34:48 -07003228 ? commandEntry->inputWindowHandle->getInputChannel() : NULL);
Jeff Brown9c3cda02010-06-15 01:31:58 -07003229}
3230
Jeff Brownb88102f2010-09-08 11:49:43 -07003231void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
3232 CommandEntry* commandEntry) {
3233 KeyEntry* entry = commandEntry->keyEntry;
Jeff Brown1f245102010-11-18 20:53:46 -08003234
3235 KeyEvent event;
3236 initializeKeyEvent(&event, entry);
Jeff Brownb88102f2010-09-08 11:49:43 -07003237
3238 mLock.unlock();
3239
Jeff Brown905805a2011-10-12 13:57:59 -07003240 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(commandEntry->inputWindowHandle,
Jeff Brown1f245102010-11-18 20:53:46 -08003241 &event, entry->policyFlags);
Jeff Brownb88102f2010-09-08 11:49:43 -07003242
3243 mLock.lock();
3244
Jeff Brown905805a2011-10-12 13:57:59 -07003245 if (delay < 0) {
3246 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
3247 } else if (!delay) {
3248 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
3249 } else {
3250 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
3251 entry->interceptKeyWakeupTime = now() + delay;
3252 }
Jeff Brownac386072011-07-20 15:19:50 -07003253 entry->release();
Jeff Brownb88102f2010-09-08 11:49:43 -07003254}
3255
Jeff Brown3915bb82010-11-05 15:02:16 -07003256void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(
3257 CommandEntry* commandEntry) {
3258 sp<Connection> connection = commandEntry->connection;
3259 bool handled = commandEntry->handled;
3260
Jeff Brownd1c48a02012-02-06 19:12:47 -08003261 if (!connection->waitQueue.isEmpty()) {
3262 // Handle post-event policy actions.
3263 bool restartEvent;
3264 DispatchEntry* dispatchEntry = connection->waitQueue.head;
3265 if (dispatchEntry->eventEntry->type == EventEntry::TYPE_KEY) {
3266 KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry);
3267 restartEvent = afterKeyEventLockedInterruptible(connection,
3268 dispatchEntry, keyEntry, handled);
3269 } else if (dispatchEntry->eventEntry->type == EventEntry::TYPE_MOTION) {
3270 MotionEntry* motionEntry = static_cast<MotionEntry*>(dispatchEntry->eventEntry);
3271 restartEvent = afterMotionEventLockedInterruptible(connection,
3272 dispatchEntry, motionEntry, handled);
3273 } else {
3274 restartEvent = false;
3275 }
3276
3277 // Dequeue the event and start the next cycle.
3278 // Note that because the lock might have been released, it is possible that the
3279 // contents of the wait queue to have been drained, so we need to double-check
3280 // a few things.
3281 if (connection->waitQueue.head == dispatchEntry) {
3282 connection->waitQueue.dequeueAtHead();
3283 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
3284 connection->outboundQueue.enqueueAtHead(dispatchEntry);
3285 } else {
3286 releaseDispatchEntryLocked(dispatchEntry);
Jeff Brown49ed71d2010-12-06 17:13:33 -08003287 }
Jeff Brown3915bb82010-11-05 15:02:16 -07003288 }
Jeff Brown3915bb82010-11-05 15:02:16 -07003289
Jeff Brownd1c48a02012-02-06 19:12:47 -08003290 // Start the next dispatch cycle for this connection.
3291 startDispatchCycleLocked(now(), connection);
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003292 }
3293}
3294
3295bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
3296 DispatchEntry* dispatchEntry, KeyEntry* keyEntry, bool handled) {
3297 if (!(keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK)) {
3298 // Get the fallback key state.
3299 // Clear it out after dispatching the UP.
3300 int32_t originalKeyCode = keyEntry->keyCode;
3301 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
3302 if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
3303 connection->inputState.removeFallbackKey(originalKeyCode);
3304 }
3305
3306 if (handled || !dispatchEntry->hasForegroundTarget()) {
3307 // If the application handles the original key for which we previously
3308 // generated a fallback or if the window is not a foreground window,
3309 // then cancel the associated fallback key, if any.
3310 if (fallbackKeyCode != -1) {
3311 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
3312 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
3313 "application handled the original non-fallback key "
3314 "or is no longer a foreground target, "
3315 "canceling previously dispatched fallback key");
3316 options.keyCode = fallbackKeyCode;
3317 synthesizeCancelationEventsForConnectionLocked(connection, options);
3318 }
3319 connection->inputState.removeFallbackKey(originalKeyCode);
3320 }
3321 } else {
3322 // If the application did not handle a non-fallback key, first check
3323 // that we are in a good state to perform unhandled key event processing
3324 // Then ask the policy what to do with it.
3325 bool initialDown = keyEntry->action == AKEY_EVENT_ACTION_DOWN
3326 && keyEntry->repeatCount == 0;
3327 if (fallbackKeyCode == -1 && !initialDown) {
3328#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00003329 ALOGD("Unhandled key event: Skipping unhandled key event processing "
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003330 "since this is not an initial down. "
3331 "keyCode=%d, action=%d, repeatCount=%d",
3332 originalKeyCode, keyEntry->action, keyEntry->repeatCount);
3333#endif
3334 return false;
3335 }
3336
3337 // Dispatch the unhandled key to the policy.
3338#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00003339 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003340 "keyCode=%d, action=%d, repeatCount=%d",
3341 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount);
3342#endif
3343 KeyEvent event;
3344 initializeKeyEvent(&event, keyEntry);
3345
3346 mLock.unlock();
3347
3348 bool fallback = mPolicy->dispatchUnhandledKey(connection->inputWindowHandle,
3349 &event, keyEntry->policyFlags, &event);
3350
3351 mLock.lock();
3352
3353 if (connection->status != Connection::STATUS_NORMAL) {
3354 connection->inputState.removeFallbackKey(originalKeyCode);
Jeff Brownd1c48a02012-02-06 19:12:47 -08003355 return false;
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003356 }
3357
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003358 // Latch the fallback keycode for this key on an initial down.
3359 // The fallback keycode cannot change at any other point in the lifecycle.
3360 if (initialDown) {
3361 if (fallback) {
3362 fallbackKeyCode = event.getKeyCode();
3363 } else {
3364 fallbackKeyCode = AKEYCODE_UNKNOWN;
3365 }
3366 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
3367 }
3368
Steve Blockec193de2012-01-09 18:35:44 +00003369 ALOG_ASSERT(fallbackKeyCode != -1);
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003370
3371 // Cancel the fallback key if the policy decides not to send it anymore.
3372 // We will continue to dispatch the key to the policy but we will no
3373 // longer dispatch a fallback key to the application.
3374 if (fallbackKeyCode != AKEYCODE_UNKNOWN
3375 && (!fallback || fallbackKeyCode != event.getKeyCode())) {
3376#if DEBUG_OUTBOUND_EVENT_DETAILS
3377 if (fallback) {
Steve Block5baa3a62011-12-20 16:23:08 +00003378 ALOGD("Unhandled key event: Policy requested to send key %d"
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003379 "as a fallback for %d, but on the DOWN it had requested "
3380 "to send %d instead. Fallback canceled.",
3381 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
3382 } else {
Steve Block5baa3a62011-12-20 16:23:08 +00003383 ALOGD("Unhandled key event: Policy did not request fallback for %d,"
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003384 "but on the DOWN it had requested to send %d. "
3385 "Fallback canceled.",
3386 originalKeyCode, fallbackKeyCode);
3387 }
3388#endif
3389
3390 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
3391 "canceling fallback, policy no longer desires it");
3392 options.keyCode = fallbackKeyCode;
3393 synthesizeCancelationEventsForConnectionLocked(connection, options);
3394
3395 fallback = false;
3396 fallbackKeyCode = AKEYCODE_UNKNOWN;
3397 if (keyEntry->action != AKEY_EVENT_ACTION_UP) {
3398 connection->inputState.setFallbackKey(originalKeyCode,
3399 fallbackKeyCode);
3400 }
3401 }
3402
3403#if DEBUG_OUTBOUND_EVENT_DETAILS
3404 {
3405 String8 msg;
3406 const KeyedVector<int32_t, int32_t>& fallbackKeys =
3407 connection->inputState.getFallbackKeys();
3408 for (size_t i = 0; i < fallbackKeys.size(); i++) {
3409 msg.appendFormat(", %d->%d", fallbackKeys.keyAt(i),
3410 fallbackKeys.valueAt(i));
3411 }
Steve Block5baa3a62011-12-20 16:23:08 +00003412 ALOGD("Unhandled key event: %d currently tracked fallback keys%s.",
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003413 fallbackKeys.size(), msg.string());
3414 }
3415#endif
3416
3417 if (fallback) {
3418 // Restart the dispatch cycle using the fallback key.
3419 keyEntry->eventTime = event.getEventTime();
3420 keyEntry->deviceId = event.getDeviceId();
3421 keyEntry->source = event.getSource();
3422 keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
3423 keyEntry->keyCode = fallbackKeyCode;
3424 keyEntry->scanCode = event.getScanCode();
3425 keyEntry->metaState = event.getMetaState();
3426 keyEntry->repeatCount = event.getRepeatCount();
3427 keyEntry->downTime = event.getDownTime();
3428 keyEntry->syntheticRepeat = false;
3429
3430#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00003431 ALOGD("Unhandled key event: Dispatching fallback key. "
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003432 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
3433 originalKeyCode, fallbackKeyCode, keyEntry->metaState);
3434#endif
Jeff Brownd1c48a02012-02-06 19:12:47 -08003435 return true; // restart the event
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003436 } else {
3437#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00003438 ALOGD("Unhandled key event: No fallback key.");
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003439#endif
3440 }
3441 }
3442 }
3443 return false;
3444}
3445
3446bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
3447 DispatchEntry* dispatchEntry, MotionEntry* motionEntry, bool handled) {
3448 return false;
Jeff Brown3915bb82010-11-05 15:02:16 -07003449}
3450
Jeff Brownb88102f2010-09-08 11:49:43 -07003451void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
3452 mLock.unlock();
3453
Jeff Brown01ce2e92010-09-26 22:20:12 -07003454 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
Jeff Brownb88102f2010-09-08 11:49:43 -07003455
3456 mLock.lock();
3457}
3458
Jeff Brown3915bb82010-11-05 15:02:16 -07003459void InputDispatcher::initializeKeyEvent(KeyEvent* event, const KeyEntry* entry) {
3460 event->initialize(entry->deviceId, entry->source, entry->action, entry->flags,
3461 entry->keyCode, entry->scanCode, entry->metaState, entry->repeatCount,
3462 entry->downTime, entry->eventTime);
3463}
3464
Jeff Brown519e0242010-09-15 15:18:56 -07003465void InputDispatcher::updateDispatchStatisticsLocked(nsecs_t currentTime, const EventEntry* entry,
3466 int32_t injectionResult, nsecs_t timeSpentWaitingForApplication) {
3467 // TODO Write some statistics about how long we spend waiting.
Jeff Brownb88102f2010-09-08 11:49:43 -07003468}
3469
3470void InputDispatcher::dump(String8& dump) {
Jeff Brown89ef0722011-08-10 16:25:21 -07003471 AutoMutex _l(mLock);
3472
Jeff Brownf2f487182010-10-01 17:46:21 -07003473 dump.append("Input Dispatcher State:\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003474 dumpDispatchStateLocked(dump);
Jeff Brown214eaf42011-05-26 19:17:02 -07003475
3476 dump.append(INDENT "Configuration:\n");
Jeff Brown214eaf42011-05-26 19:17:02 -07003477 dump.appendFormat(INDENT2 "KeyRepeatDelay: %0.1fms\n", mConfig.keyRepeatDelay * 0.000001f);
3478 dump.appendFormat(INDENT2 "KeyRepeatTimeout: %0.1fms\n", mConfig.keyRepeatTimeout * 0.000001f);
Jeff Brownb88102f2010-09-08 11:49:43 -07003479}
3480
Jeff Brown89ef0722011-08-10 16:25:21 -07003481void InputDispatcher::monitor() {
3482 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
3483 mLock.lock();
Jeff Brown112b5f52012-01-27 17:32:06 -08003484 mLooper->wake();
3485 mDispatcherIsAliveCondition.wait(mLock);
Jeff Brown89ef0722011-08-10 16:25:21 -07003486 mLock.unlock();
3487}
3488
Jeff Brown9c3cda02010-06-15 01:31:58 -07003489
Jeff Brown519e0242010-09-15 15:18:56 -07003490// --- InputDispatcher::Queue ---
3491
3492template <typename T>
3493uint32_t InputDispatcher::Queue<T>::count() const {
3494 uint32_t result = 0;
Jeff Brownac386072011-07-20 15:19:50 -07003495 for (const T* entry = head; entry; entry = entry->next) {
Jeff Brown519e0242010-09-15 15:18:56 -07003496 result += 1;
3497 }
3498 return result;
3499}
3500
3501
Jeff Brownac386072011-07-20 15:19:50 -07003502// --- InputDispatcher::InjectionState ---
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003503
Jeff Brownac386072011-07-20 15:19:50 -07003504InputDispatcher::InjectionState::InjectionState(int32_t injectorPid, int32_t injectorUid) :
3505 refCount(1),
3506 injectorPid(injectorPid), injectorUid(injectorUid),
3507 injectionResult(INPUT_EVENT_INJECTION_PENDING), injectionIsAsync(false),
3508 pendingForegroundDispatches(0) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003509}
3510
Jeff Brownac386072011-07-20 15:19:50 -07003511InputDispatcher::InjectionState::~InjectionState() {
Jeff Brown01ce2e92010-09-26 22:20:12 -07003512}
3513
Jeff Brownac386072011-07-20 15:19:50 -07003514void InputDispatcher::InjectionState::release() {
3515 refCount -= 1;
3516 if (refCount == 0) {
3517 delete this;
3518 } else {
Steve Blockec193de2012-01-09 18:35:44 +00003519 ALOG_ASSERT(refCount > 0);
Jeff Brown01ce2e92010-09-26 22:20:12 -07003520 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07003521}
3522
Jeff Brownac386072011-07-20 15:19:50 -07003523
3524// --- InputDispatcher::EventEntry ---
3525
3526InputDispatcher::EventEntry::EventEntry(int32_t type, nsecs_t eventTime, uint32_t policyFlags) :
3527 refCount(1), type(type), eventTime(eventTime), policyFlags(policyFlags),
3528 injectionState(NULL), dispatchInProgress(false) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003529}
3530
Jeff Brownac386072011-07-20 15:19:50 -07003531InputDispatcher::EventEntry::~EventEntry() {
3532 releaseInjectionState();
3533}
3534
3535void InputDispatcher::EventEntry::release() {
3536 refCount -= 1;
3537 if (refCount == 0) {
3538 delete this;
3539 } else {
Steve Blockec193de2012-01-09 18:35:44 +00003540 ALOG_ASSERT(refCount > 0);
Jeff Brownac386072011-07-20 15:19:50 -07003541 }
3542}
3543
3544void InputDispatcher::EventEntry::releaseInjectionState() {
3545 if (injectionState) {
3546 injectionState->release();
3547 injectionState = NULL;
3548 }
3549}
3550
3551
3552// --- InputDispatcher::ConfigurationChangedEntry ---
3553
3554InputDispatcher::ConfigurationChangedEntry::ConfigurationChangedEntry(nsecs_t eventTime) :
3555 EventEntry(TYPE_CONFIGURATION_CHANGED, eventTime, 0) {
3556}
3557
3558InputDispatcher::ConfigurationChangedEntry::~ConfigurationChangedEntry() {
3559}
3560
3561
Jeff Brown65fd2512011-08-18 11:20:58 -07003562// --- InputDispatcher::DeviceResetEntry ---
3563
3564InputDispatcher::DeviceResetEntry::DeviceResetEntry(nsecs_t eventTime, int32_t deviceId) :
3565 EventEntry(TYPE_DEVICE_RESET, eventTime, 0),
3566 deviceId(deviceId) {
3567}
3568
3569InputDispatcher::DeviceResetEntry::~DeviceResetEntry() {
3570}
3571
3572
Jeff Brownac386072011-07-20 15:19:50 -07003573// --- InputDispatcher::KeyEntry ---
3574
3575InputDispatcher::KeyEntry::KeyEntry(nsecs_t eventTime,
Jeff Brown58a2da82011-01-25 16:02:22 -08003576 int32_t deviceId, uint32_t source, uint32_t policyFlags, int32_t action,
Jeff Brown7fbdc842010-06-17 20:52:56 -07003577 int32_t flags, int32_t keyCode, int32_t scanCode, int32_t metaState,
Jeff Brownac386072011-07-20 15:19:50 -07003578 int32_t repeatCount, nsecs_t downTime) :
3579 EventEntry(TYPE_KEY, eventTime, policyFlags),
3580 deviceId(deviceId), source(source), action(action), flags(flags),
3581 keyCode(keyCode), scanCode(scanCode), metaState(metaState),
3582 repeatCount(repeatCount), downTime(downTime),
Jeff Brown905805a2011-10-12 13:57:59 -07003583 syntheticRepeat(false), interceptKeyResult(KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN),
3584 interceptKeyWakeupTime(0) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003585}
3586
Jeff Brownac386072011-07-20 15:19:50 -07003587InputDispatcher::KeyEntry::~KeyEntry() {
3588}
Jeff Brown7fbdc842010-06-17 20:52:56 -07003589
Jeff Brownac386072011-07-20 15:19:50 -07003590void InputDispatcher::KeyEntry::recycle() {
3591 releaseInjectionState();
3592
3593 dispatchInProgress = false;
3594 syntheticRepeat = false;
3595 interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
Jeff Brown905805a2011-10-12 13:57:59 -07003596 interceptKeyWakeupTime = 0;
Jeff Brownac386072011-07-20 15:19:50 -07003597}
3598
3599
Jeff Brownae9fc032010-08-18 15:51:08 -07003600// --- InputDispatcher::MotionEntry ---
3601
Jeff Brownac386072011-07-20 15:19:50 -07003602InputDispatcher::MotionEntry::MotionEntry(nsecs_t eventTime,
3603 int32_t deviceId, uint32_t source, uint32_t policyFlags, int32_t action, int32_t flags,
3604 int32_t metaState, int32_t buttonState,
3605 int32_t edgeFlags, float xPrecision, float yPrecision,
3606 nsecs_t downTime, uint32_t pointerCount,
3607 const PointerProperties* pointerProperties, const PointerCoords* pointerCoords) :
3608 EventEntry(TYPE_MOTION, eventTime, policyFlags),
Jeff Brown3241b6b2012-02-03 15:08:02 -08003609 eventTime(eventTime),
Jeff Brownac386072011-07-20 15:19:50 -07003610 deviceId(deviceId), source(source), action(action), flags(flags),
3611 metaState(metaState), buttonState(buttonState), edgeFlags(edgeFlags),
3612 xPrecision(xPrecision), yPrecision(yPrecision),
Jeff Brown3241b6b2012-02-03 15:08:02 -08003613 downTime(downTime), pointerCount(pointerCount) {
Jeff Brownac386072011-07-20 15:19:50 -07003614 for (uint32_t i = 0; i < pointerCount; i++) {
3615 this->pointerProperties[i].copyFrom(pointerProperties[i]);
Jeff Brown3241b6b2012-02-03 15:08:02 -08003616 this->pointerCoords[i].copyFrom(pointerCoords[i]);
Jeff Brownac386072011-07-20 15:19:50 -07003617 }
3618}
3619
3620InputDispatcher::MotionEntry::~MotionEntry() {
Jeff Brownac386072011-07-20 15:19:50 -07003621}
3622
3623
3624// --- InputDispatcher::DispatchEntry ---
3625
3626InputDispatcher::DispatchEntry::DispatchEntry(EventEntry* eventEntry,
3627 int32_t targetFlags, float xOffset, float yOffset, float scaleFactor) :
3628 eventEntry(eventEntry), targetFlags(targetFlags),
3629 xOffset(xOffset), yOffset(yOffset), scaleFactor(scaleFactor),
Jeff Brown3241b6b2012-02-03 15:08:02 -08003630 resolvedAction(0), resolvedFlags(0) {
Jeff Brownac386072011-07-20 15:19:50 -07003631 eventEntry->refCount += 1;
3632}
3633
3634InputDispatcher::DispatchEntry::~DispatchEntry() {
3635 eventEntry->release();
3636}
3637
Jeff Brownb88102f2010-09-08 11:49:43 -07003638
3639// --- InputDispatcher::InputState ---
3640
Jeff Brownb6997262010-10-08 22:31:17 -07003641InputDispatcher::InputState::InputState() {
Jeff Brownb88102f2010-09-08 11:49:43 -07003642}
3643
3644InputDispatcher::InputState::~InputState() {
3645}
3646
3647bool InputDispatcher::InputState::isNeutral() const {
3648 return mKeyMementos.isEmpty() && mMotionMementos.isEmpty();
3649}
3650
Jeff Brown81346812011-06-28 20:08:48 -07003651bool InputDispatcher::InputState::isHovering(int32_t deviceId, uint32_t source) const {
3652 for (size_t i = 0; i < mMotionMementos.size(); i++) {
3653 const MotionMemento& memento = mMotionMementos.itemAt(i);
3654 if (memento.deviceId == deviceId
3655 && memento.source == source
3656 && memento.hovering) {
3657 return true;
3658 }
3659 }
3660 return false;
3661}
Jeff Brownb88102f2010-09-08 11:49:43 -07003662
Jeff Brown81346812011-06-28 20:08:48 -07003663bool InputDispatcher::InputState::trackKey(const KeyEntry* entry,
3664 int32_t action, int32_t flags) {
3665 switch (action) {
3666 case AKEY_EVENT_ACTION_UP: {
3667 if (entry->flags & AKEY_EVENT_FLAG_FALLBACK) {
3668 for (size_t i = 0; i < mFallbackKeys.size(); ) {
3669 if (mFallbackKeys.valueAt(i) == entry->keyCode) {
3670 mFallbackKeys.removeItemsAt(i);
3671 } else {
3672 i += 1;
3673 }
3674 }
3675 }
3676 ssize_t index = findKeyMemento(entry);
3677 if (index >= 0) {
3678 mKeyMementos.removeAt(index);
3679 return true;
3680 }
Jeff Brown68b909d2011-12-07 16:36:01 -08003681 /* FIXME: We can't just drop the key up event because that prevents creating
3682 * popup windows that are automatically shown when a key is held and then
3683 * dismissed when the key is released. The problem is that the popup will
3684 * not have received the original key down, so the key up will be considered
3685 * to be inconsistent with its observed state. We could perhaps handle this
3686 * by synthesizing a key down but that will cause other problems.
3687 *
3688 * So for now, allow inconsistent key up events to be dispatched.
3689 *
Jeff Brown81346812011-06-28 20:08:48 -07003690#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00003691 ALOGD("Dropping inconsistent key up event: deviceId=%d, source=%08x, "
Jeff Brown81346812011-06-28 20:08:48 -07003692 "keyCode=%d, scanCode=%d",
3693 entry->deviceId, entry->source, entry->keyCode, entry->scanCode);
3694#endif
3695 return false;
Jeff Brown68b909d2011-12-07 16:36:01 -08003696 */
3697 return true;
Jeff Brown81346812011-06-28 20:08:48 -07003698 }
3699
3700 case AKEY_EVENT_ACTION_DOWN: {
3701 ssize_t index = findKeyMemento(entry);
3702 if (index >= 0) {
3703 mKeyMementos.removeAt(index);
3704 }
3705 addKeyMemento(entry, flags);
3706 return true;
3707 }
3708
3709 default:
3710 return true;
Jeff Brownb88102f2010-09-08 11:49:43 -07003711 }
3712}
3713
Jeff Brown81346812011-06-28 20:08:48 -07003714bool InputDispatcher::InputState::trackMotion(const MotionEntry* entry,
3715 int32_t action, int32_t flags) {
3716 int32_t actionMasked = action & AMOTION_EVENT_ACTION_MASK;
3717 switch (actionMasked) {
3718 case AMOTION_EVENT_ACTION_UP:
3719 case AMOTION_EVENT_ACTION_CANCEL: {
3720 ssize_t index = findMotionMemento(entry, false /*hovering*/);
3721 if (index >= 0) {
3722 mMotionMementos.removeAt(index);
3723 return true;
Jeff Brownda3d5a92011-03-29 15:11:34 -07003724 }
Jeff Brown81346812011-06-28 20:08:48 -07003725#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00003726 ALOGD("Dropping inconsistent motion up or cancel event: deviceId=%d, source=%08x, "
Jeff Brown81346812011-06-28 20:08:48 -07003727 "actionMasked=%d",
3728 entry->deviceId, entry->source, actionMasked);
3729#endif
3730 return false;
Jeff Brownda3d5a92011-03-29 15:11:34 -07003731 }
3732
Jeff Brown81346812011-06-28 20:08:48 -07003733 case AMOTION_EVENT_ACTION_DOWN: {
3734 ssize_t index = findMotionMemento(entry, false /*hovering*/);
3735 if (index >= 0) {
3736 mMotionMementos.removeAt(index);
3737 }
3738 addMotionMemento(entry, flags, false /*hovering*/);
3739 return true;
3740 }
3741
3742 case AMOTION_EVENT_ACTION_POINTER_UP:
3743 case AMOTION_EVENT_ACTION_POINTER_DOWN:
3744 case AMOTION_EVENT_ACTION_MOVE: {
3745 ssize_t index = findMotionMemento(entry, false /*hovering*/);
3746 if (index >= 0) {
3747 MotionMemento& memento = mMotionMementos.editItemAt(index);
3748 memento.setPointers(entry);
3749 return true;
3750 }
Jeff Brown2e45fb62011-06-29 21:19:05 -07003751 if (actionMasked == AMOTION_EVENT_ACTION_MOVE
3752 && (entry->source & (AINPUT_SOURCE_CLASS_JOYSTICK
3753 | AINPUT_SOURCE_CLASS_NAVIGATION))) {
3754 // Joysticks and trackballs can send MOVE events without corresponding DOWN or UP.
3755 return true;
3756 }
Jeff Brown81346812011-06-28 20:08:48 -07003757#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00003758 ALOGD("Dropping inconsistent motion pointer up/down or move event: "
Jeff Brown81346812011-06-28 20:08:48 -07003759 "deviceId=%d, source=%08x, actionMasked=%d",
3760 entry->deviceId, entry->source, actionMasked);
3761#endif
3762 return false;
3763 }
3764
3765 case AMOTION_EVENT_ACTION_HOVER_EXIT: {
3766 ssize_t index = findMotionMemento(entry, true /*hovering*/);
3767 if (index >= 0) {
3768 mMotionMementos.removeAt(index);
3769 return true;
3770 }
3771#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00003772 ALOGD("Dropping inconsistent motion hover exit event: deviceId=%d, source=%08x",
Jeff Brown81346812011-06-28 20:08:48 -07003773 entry->deviceId, entry->source);
3774#endif
3775 return false;
3776 }
3777
3778 case AMOTION_EVENT_ACTION_HOVER_ENTER:
3779 case AMOTION_EVENT_ACTION_HOVER_MOVE: {
3780 ssize_t index = findMotionMemento(entry, true /*hovering*/);
3781 if (index >= 0) {
3782 mMotionMementos.removeAt(index);
3783 }
3784 addMotionMemento(entry, flags, true /*hovering*/);
3785 return true;
3786 }
3787
3788 default:
3789 return true;
3790 }
3791}
3792
3793ssize_t InputDispatcher::InputState::findKeyMemento(const KeyEntry* entry) const {
Jeff Brownb88102f2010-09-08 11:49:43 -07003794 for (size_t i = 0; i < mKeyMementos.size(); i++) {
Jeff Brown81346812011-06-28 20:08:48 -07003795 const KeyMemento& memento = mKeyMementos.itemAt(i);
Jeff Brownb88102f2010-09-08 11:49:43 -07003796 if (memento.deviceId == entry->deviceId
3797 && memento.source == entry->source
3798 && memento.keyCode == entry->keyCode
3799 && memento.scanCode == entry->scanCode) {
Jeff Brown81346812011-06-28 20:08:48 -07003800 return i;
Jeff Brownb88102f2010-09-08 11:49:43 -07003801 }
3802 }
Jeff Brown81346812011-06-28 20:08:48 -07003803 return -1;
Jeff Brownb88102f2010-09-08 11:49:43 -07003804}
3805
Jeff Brown81346812011-06-28 20:08:48 -07003806ssize_t InputDispatcher::InputState::findMotionMemento(const MotionEntry* entry,
3807 bool hovering) const {
Jeff Brownb88102f2010-09-08 11:49:43 -07003808 for (size_t i = 0; i < mMotionMementos.size(); i++) {
Jeff Brown81346812011-06-28 20:08:48 -07003809 const MotionMemento& memento = mMotionMementos.itemAt(i);
Jeff Brownb88102f2010-09-08 11:49:43 -07003810 if (memento.deviceId == entry->deviceId
Jeff Brown81346812011-06-28 20:08:48 -07003811 && memento.source == entry->source
3812 && memento.hovering == hovering) {
3813 return i;
Jeff Brownb88102f2010-09-08 11:49:43 -07003814 }
3815 }
Jeff Brown81346812011-06-28 20:08:48 -07003816 return -1;
3817}
Jeff Brownb88102f2010-09-08 11:49:43 -07003818
Jeff Brown81346812011-06-28 20:08:48 -07003819void InputDispatcher::InputState::addKeyMemento(const KeyEntry* entry, int32_t flags) {
3820 mKeyMementos.push();
3821 KeyMemento& memento = mKeyMementos.editTop();
3822 memento.deviceId = entry->deviceId;
3823 memento.source = entry->source;
3824 memento.keyCode = entry->keyCode;
3825 memento.scanCode = entry->scanCode;
3826 memento.flags = flags;
3827 memento.downTime = entry->downTime;
3828}
3829
3830void InputDispatcher::InputState::addMotionMemento(const MotionEntry* entry,
3831 int32_t flags, bool hovering) {
3832 mMotionMementos.push();
3833 MotionMemento& memento = mMotionMementos.editTop();
3834 memento.deviceId = entry->deviceId;
3835 memento.source = entry->source;
3836 memento.flags = flags;
3837 memento.xPrecision = entry->xPrecision;
3838 memento.yPrecision = entry->yPrecision;
3839 memento.downTime = entry->downTime;
3840 memento.setPointers(entry);
3841 memento.hovering = hovering;
Jeff Brownb88102f2010-09-08 11:49:43 -07003842}
3843
3844void InputDispatcher::InputState::MotionMemento::setPointers(const MotionEntry* entry) {
3845 pointerCount = entry->pointerCount;
3846 for (uint32_t i = 0; i < entry->pointerCount; i++) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003847 pointerProperties[i].copyFrom(entry->pointerProperties[i]);
Jeff Brown3241b6b2012-02-03 15:08:02 -08003848 pointerCoords[i].copyFrom(entry->pointerCoords[i]);
Jeff Brownb88102f2010-09-08 11:49:43 -07003849 }
3850}
3851
Jeff Brownb6997262010-10-08 22:31:17 -07003852void InputDispatcher::InputState::synthesizeCancelationEvents(nsecs_t currentTime,
Jeff Brownac386072011-07-20 15:19:50 -07003853 Vector<EventEntry*>& outEvents, const CancelationOptions& options) {
Jeff Brown81346812011-06-28 20:08:48 -07003854 for (size_t i = 0; i < mKeyMementos.size(); i++) {
Jeff Brownb88102f2010-09-08 11:49:43 -07003855 const KeyMemento& memento = mKeyMementos.itemAt(i);
Jeff Brown49ed71d2010-12-06 17:13:33 -08003856 if (shouldCancelKey(memento, options)) {
Jeff Brownac386072011-07-20 15:19:50 -07003857 outEvents.push(new KeyEntry(currentTime,
Jeff Brownb6997262010-10-08 22:31:17 -07003858 memento.deviceId, memento.source, 0,
Jeff Brown49ed71d2010-12-06 17:13:33 -08003859 AKEY_EVENT_ACTION_UP, memento.flags | AKEY_EVENT_FLAG_CANCELED,
Jeff Brownb6997262010-10-08 22:31:17 -07003860 memento.keyCode, memento.scanCode, 0, 0, memento.downTime));
Jeff Brownb6997262010-10-08 22:31:17 -07003861 }
Jeff Brownb88102f2010-09-08 11:49:43 -07003862 }
3863
Jeff Brown81346812011-06-28 20:08:48 -07003864 for (size_t i = 0; i < mMotionMementos.size(); i++) {
Jeff Brownb88102f2010-09-08 11:49:43 -07003865 const MotionMemento& memento = mMotionMementos.itemAt(i);
Jeff Brown49ed71d2010-12-06 17:13:33 -08003866 if (shouldCancelMotion(memento, options)) {
Jeff Brownac386072011-07-20 15:19:50 -07003867 outEvents.push(new MotionEntry(currentTime,
Jeff Brownb6997262010-10-08 22:31:17 -07003868 memento.deviceId, memento.source, 0,
Jeff Browna032cc02011-03-07 16:56:21 -08003869 memento.hovering
3870 ? AMOTION_EVENT_ACTION_HOVER_EXIT
3871 : AMOTION_EVENT_ACTION_CANCEL,
Jeff Brown81346812011-06-28 20:08:48 -07003872 memento.flags, 0, 0, 0,
Jeff Brownb6997262010-10-08 22:31:17 -07003873 memento.xPrecision, memento.yPrecision, memento.downTime,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003874 memento.pointerCount, memento.pointerProperties, memento.pointerCoords));
Jeff Brownb6997262010-10-08 22:31:17 -07003875 }
Jeff Brownb88102f2010-09-08 11:49:43 -07003876 }
3877}
3878
3879void InputDispatcher::InputState::clear() {
3880 mKeyMementos.clear();
3881 mMotionMementos.clear();
Jeff Brownda3d5a92011-03-29 15:11:34 -07003882 mFallbackKeys.clear();
Jeff Brownb6997262010-10-08 22:31:17 -07003883}
3884
Jeff Brown9c9f1a32010-10-11 18:32:20 -07003885void InputDispatcher::InputState::copyPointerStateTo(InputState& other) const {
3886 for (size_t i = 0; i < mMotionMementos.size(); i++) {
3887 const MotionMemento& memento = mMotionMementos.itemAt(i);
3888 if (memento.source & AINPUT_SOURCE_CLASS_POINTER) {
3889 for (size_t j = 0; j < other.mMotionMementos.size(); ) {
3890 const MotionMemento& otherMemento = other.mMotionMementos.itemAt(j);
3891 if (memento.deviceId == otherMemento.deviceId
3892 && memento.source == otherMemento.source) {
3893 other.mMotionMementos.removeAt(j);
3894 } else {
3895 j += 1;
3896 }
3897 }
3898 other.mMotionMementos.push(memento);
3899 }
3900 }
3901}
3902
Jeff Brownda3d5a92011-03-29 15:11:34 -07003903int32_t InputDispatcher::InputState::getFallbackKey(int32_t originalKeyCode) {
3904 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
3905 return index >= 0 ? mFallbackKeys.valueAt(index) : -1;
3906}
3907
3908void InputDispatcher::InputState::setFallbackKey(int32_t originalKeyCode,
3909 int32_t fallbackKeyCode) {
3910 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
3911 if (index >= 0) {
3912 mFallbackKeys.replaceValueAt(index, fallbackKeyCode);
3913 } else {
3914 mFallbackKeys.add(originalKeyCode, fallbackKeyCode);
3915 }
3916}
3917
3918void InputDispatcher::InputState::removeFallbackKey(int32_t originalKeyCode) {
3919 mFallbackKeys.removeItem(originalKeyCode);
3920}
3921
Jeff Brown49ed71d2010-12-06 17:13:33 -08003922bool InputDispatcher::InputState::shouldCancelKey(const KeyMemento& memento,
Jeff Brownda3d5a92011-03-29 15:11:34 -07003923 const CancelationOptions& options) {
3924 if (options.keyCode != -1 && memento.keyCode != options.keyCode) {
3925 return false;
3926 }
3927
Jeff Brown65fd2512011-08-18 11:20:58 -07003928 if (options.deviceId != -1 && memento.deviceId != options.deviceId) {
3929 return false;
3930 }
3931
Jeff Brownda3d5a92011-03-29 15:11:34 -07003932 switch (options.mode) {
3933 case CancelationOptions::CANCEL_ALL_EVENTS:
3934 case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
Jeff Brownb6997262010-10-08 22:31:17 -07003935 return true;
Jeff Brownda3d5a92011-03-29 15:11:34 -07003936 case CancelationOptions::CANCEL_FALLBACK_EVENTS:
Jeff Brown49ed71d2010-12-06 17:13:33 -08003937 return memento.flags & AKEY_EVENT_FLAG_FALLBACK;
3938 default:
3939 return false;
3940 }
3941}
3942
3943bool InputDispatcher::InputState::shouldCancelMotion(const MotionMemento& memento,
Jeff Brownda3d5a92011-03-29 15:11:34 -07003944 const CancelationOptions& options) {
Jeff Brown65fd2512011-08-18 11:20:58 -07003945 if (options.deviceId != -1 && memento.deviceId != options.deviceId) {
3946 return false;
3947 }
3948
Jeff Brownda3d5a92011-03-29 15:11:34 -07003949 switch (options.mode) {
3950 case CancelationOptions::CANCEL_ALL_EVENTS:
Jeff Brown49ed71d2010-12-06 17:13:33 -08003951 return true;
Jeff Brownda3d5a92011-03-29 15:11:34 -07003952 case CancelationOptions::CANCEL_POINTER_EVENTS:
Jeff Brown49ed71d2010-12-06 17:13:33 -08003953 return memento.source & AINPUT_SOURCE_CLASS_POINTER;
Jeff Brownda3d5a92011-03-29 15:11:34 -07003954 case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
Jeff Brown49ed71d2010-12-06 17:13:33 -08003955 return !(memento.source & AINPUT_SOURCE_CLASS_POINTER);
3956 default:
3957 return false;
Jeff Brownb6997262010-10-08 22:31:17 -07003958 }
Jeff Brownb88102f2010-09-08 11:49:43 -07003959}
3960
3961
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003962// --- InputDispatcher::Connection ---
3963
Jeff Brown928e0542011-01-10 11:17:36 -08003964InputDispatcher::Connection::Connection(const sp<InputChannel>& inputChannel,
Jeff Browncc4f7db2011-08-30 20:34:48 -07003965 const sp<InputWindowHandle>& inputWindowHandle, bool monitor) :
Jeff Brown928e0542011-01-10 11:17:36 -08003966 status(STATUS_NORMAL), inputChannel(inputChannel), inputWindowHandle(inputWindowHandle),
Jeff Browncc4f7db2011-08-30 20:34:48 -07003967 monitor(monitor),
Jeff Brownd1c48a02012-02-06 19:12:47 -08003968 inputPublisher(inputChannel), inputPublisherBlocked(false) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003969}
3970
3971InputDispatcher::Connection::~Connection() {
3972}
3973
Jeff Brown9c3cda02010-06-15 01:31:58 -07003974const char* InputDispatcher::Connection::getStatusLabel() const {
3975 switch (status) {
3976 case STATUS_NORMAL:
3977 return "NORMAL";
3978
3979 case STATUS_BROKEN:
3980 return "BROKEN";
3981
Jeff Brown9c3cda02010-06-15 01:31:58 -07003982 case STATUS_ZOMBIE:
3983 return "ZOMBIE";
3984
3985 default:
3986 return "UNKNOWN";
3987 }
3988}
3989
Jeff Brownb88102f2010-09-08 11:49:43 -07003990
Jeff Brown9c3cda02010-06-15 01:31:58 -07003991// --- InputDispatcher::CommandEntry ---
3992
Jeff Brownac386072011-07-20 15:19:50 -07003993InputDispatcher::CommandEntry::CommandEntry(Command command) :
3994 command(command), eventTime(0), keyEntry(NULL), userActivityEventType(0), handled(false) {
Jeff Brown9c3cda02010-06-15 01:31:58 -07003995}
3996
3997InputDispatcher::CommandEntry::~CommandEntry() {
3998}
3999
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004000
Jeff Brown01ce2e92010-09-26 22:20:12 -07004001// --- InputDispatcher::TouchState ---
4002
4003InputDispatcher::TouchState::TouchState() :
Jeff Brown58a2da82011-01-25 16:02:22 -08004004 down(false), split(false), deviceId(-1), source(0) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07004005}
4006
4007InputDispatcher::TouchState::~TouchState() {
4008}
4009
4010void InputDispatcher::TouchState::reset() {
4011 down = false;
4012 split = false;
Jeff Brown95712852011-01-04 19:41:59 -08004013 deviceId = -1;
Jeff Brown58a2da82011-01-25 16:02:22 -08004014 source = 0;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004015 windows.clear();
4016}
4017
4018void InputDispatcher::TouchState::copyFrom(const TouchState& other) {
4019 down = other.down;
4020 split = other.split;
Jeff Brown95712852011-01-04 19:41:59 -08004021 deviceId = other.deviceId;
Jeff Brown58a2da82011-01-25 16:02:22 -08004022 source = other.source;
Jeff Brown9302c872011-07-13 22:51:29 -07004023 windows = other.windows;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004024}
4025
Jeff Brown9302c872011-07-13 22:51:29 -07004026void InputDispatcher::TouchState::addOrUpdateWindow(const sp<InputWindowHandle>& windowHandle,
Jeff Brown01ce2e92010-09-26 22:20:12 -07004027 int32_t targetFlags, BitSet32 pointerIds) {
4028 if (targetFlags & InputTarget::FLAG_SPLIT) {
4029 split = true;
4030 }
4031
4032 for (size_t i = 0; i < windows.size(); i++) {
4033 TouchedWindow& touchedWindow = windows.editItemAt(i);
Jeff Brown9302c872011-07-13 22:51:29 -07004034 if (touchedWindow.windowHandle == windowHandle) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07004035 touchedWindow.targetFlags |= targetFlags;
Jeff Brown98db5fa2011-06-08 15:37:10 -07004036 if (targetFlags & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
4037 touchedWindow.targetFlags &= ~InputTarget::FLAG_DISPATCH_AS_IS;
4038 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07004039 touchedWindow.pointerIds.value |= pointerIds.value;
4040 return;
4041 }
4042 }
4043
4044 windows.push();
4045
4046 TouchedWindow& touchedWindow = windows.editTop();
Jeff Brown9302c872011-07-13 22:51:29 -07004047 touchedWindow.windowHandle = windowHandle;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004048 touchedWindow.targetFlags = targetFlags;
4049 touchedWindow.pointerIds = pointerIds;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004050}
4051
Jeff Browna032cc02011-03-07 16:56:21 -08004052void InputDispatcher::TouchState::filterNonAsIsTouchWindows() {
Jeff Brown01ce2e92010-09-26 22:20:12 -07004053 for (size_t i = 0 ; i < windows.size(); ) {
Jeff Browna032cc02011-03-07 16:56:21 -08004054 TouchedWindow& window = windows.editItemAt(i);
Jeff Brown98db5fa2011-06-08 15:37:10 -07004055 if (window.targetFlags & (InputTarget::FLAG_DISPATCH_AS_IS
4056 | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER)) {
Jeff Browna032cc02011-03-07 16:56:21 -08004057 window.targetFlags &= ~InputTarget::FLAG_DISPATCH_MASK;
4058 window.targetFlags |= InputTarget::FLAG_DISPATCH_AS_IS;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004059 i += 1;
Jeff Browna032cc02011-03-07 16:56:21 -08004060 } else {
4061 windows.removeAt(i);
Jeff Brown01ce2e92010-09-26 22:20:12 -07004062 }
4063 }
4064}
4065
Jeff Brown9302c872011-07-13 22:51:29 -07004066sp<InputWindowHandle> InputDispatcher::TouchState::getFirstForegroundWindowHandle() const {
Jeff Brown01ce2e92010-09-26 22:20:12 -07004067 for (size_t i = 0; i < windows.size(); i++) {
Jeff Brown98db5fa2011-06-08 15:37:10 -07004068 const TouchedWindow& window = windows.itemAt(i);
4069 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
Jeff Brown9302c872011-07-13 22:51:29 -07004070 return window.windowHandle;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004071 }
4072 }
4073 return NULL;
4074}
4075
Jeff Brown98db5fa2011-06-08 15:37:10 -07004076bool InputDispatcher::TouchState::isSlippery() const {
4077 // Must have exactly one foreground window.
4078 bool haveSlipperyForegroundWindow = false;
4079 for (size_t i = 0; i < windows.size(); i++) {
4080 const TouchedWindow& window = windows.itemAt(i);
4081 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
Jeff Browncc4f7db2011-08-30 20:34:48 -07004082 if (haveSlipperyForegroundWindow
4083 || !(window.windowHandle->getInfo()->layoutParamsFlags
4084 & InputWindowInfo::FLAG_SLIPPERY)) {
Jeff Brown98db5fa2011-06-08 15:37:10 -07004085 return false;
4086 }
4087 haveSlipperyForegroundWindow = true;
4088 }
4089 }
4090 return haveSlipperyForegroundWindow;
4091}
4092
Jeff Brown01ce2e92010-09-26 22:20:12 -07004093
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004094// --- InputDispatcherThread ---
4095
4096InputDispatcherThread::InputDispatcherThread(const sp<InputDispatcherInterface>& dispatcher) :
4097 Thread(/*canCallJava*/ true), mDispatcher(dispatcher) {
4098}
4099
4100InputDispatcherThread::~InputDispatcherThread() {
4101}
4102
4103bool InputDispatcherThread::threadLoop() {
4104 mDispatcher->dispatchOnce();
4105 return true;
4106}
4107
4108} // namespace android