blob: 1953aa80fd5f017ba75286165ab566171f3acc57 [file] [log] [blame]
Jeff Brownb4ff35d2011-01-02 16:37:43 -08001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Jeff Brown46b9ac02010-04-22 18:58:52 -070017#define LOG_TAG "InputDispatcher"
18
19//#define LOG_NDEBUG 0
20
21// Log detailed debug messages about each inbound event notification to the dispatcher.
Jeff Brown349703e2010-06-22 01:27:15 -070022#define DEBUG_INBOUND_EVENT_DETAILS 0
Jeff Brown46b9ac02010-04-22 18:58:52 -070023
24// Log detailed debug messages about each outbound event processed by the dispatcher.
Jeff Brown349703e2010-06-22 01:27:15 -070025#define DEBUG_OUTBOUND_EVENT_DETAILS 0
Jeff Brown46b9ac02010-04-22 18:58:52 -070026
Jeff Brown46b9ac02010-04-22 18:58:52 -070027// Log debug messages about the dispatch cycle.
Jeff Brown349703e2010-06-22 01:27:15 -070028#define DEBUG_DISPATCH_CYCLE 0
Jeff Brown46b9ac02010-04-22 18:58:52 -070029
Jeff Brown9c3cda02010-06-15 01:31:58 -070030// Log debug messages about registrations.
Jeff Brown349703e2010-06-22 01:27:15 -070031#define DEBUG_REGISTRATION 0
Jeff Brown9c3cda02010-06-15 01:31:58 -070032
Jeff Brown7fbdc842010-06-17 20:52:56 -070033// Log debug messages about input event injection.
Jeff Brown349703e2010-06-22 01:27:15 -070034#define DEBUG_INJECTION 0
Jeff Brown7fbdc842010-06-17 20:52:56 -070035
Jeff Brownb88102f2010-09-08 11:49:43 -070036// Log debug messages about input focus tracking.
37#define DEBUG_FOCUS 0
38
39// Log debug messages about the app switch latency optimization.
40#define DEBUG_APP_SWITCH 0
41
Jeff Browna032cc02011-03-07 16:56:21 -080042// Log debug messages about hover events.
43#define DEBUG_HOVER 0
44
Jeff Brownb4ff35d2011-01-02 16:37:43 -080045#include "InputDispatcher.h"
46
Jeff Brown46b9ac02010-04-22 18:58:52 -070047#include <cutils/log.h>
Jeff Brownb88102f2010-09-08 11:49:43 -070048#include <ui/PowerManager.h>
Jeff Brown46b9ac02010-04-22 18:58:52 -070049
50#include <stddef.h>
51#include <unistd.h>
Jeff Brown46b9ac02010-04-22 18:58:52 -070052#include <errno.h>
53#include <limits.h>
Jeff Brown46b9ac02010-04-22 18:58:52 -070054
Jeff Brownf2f487182010-10-01 17:46:21 -070055#define INDENT " "
56#define INDENT2 " "
57
Jeff Brown46b9ac02010-04-22 18:58:52 -070058namespace android {
59
Jeff Brownb88102f2010-09-08 11:49:43 -070060// Default input dispatching timeout if there is no focused application or paused window
61// from which to determine an appropriate dispatching timeout.
62const nsecs_t DEFAULT_INPUT_DISPATCHING_TIMEOUT = 5000 * 1000000LL; // 5 sec
63
64// Amount of time to allow for all pending events to be processed when an app switch
65// key is on the way. This is used to preempt input dispatch and drop input events
66// when an application takes too long to respond and the user has pressed an app switch key.
67const nsecs_t APP_SWITCH_TIMEOUT = 500 * 1000000LL; // 0.5sec
68
Jeff Brown928e0542011-01-10 11:17:36 -080069// Amount of time to allow for an event to be dispatched (measured since its eventTime)
70// before considering it stale and dropping it.
71const nsecs_t STALE_EVENT_TIMEOUT = 10000 * 1000000LL; // 10sec
72
Jeff Brown46b9ac02010-04-22 18:58:52 -070073
Jeff Brown7fbdc842010-06-17 20:52:56 -070074static inline nsecs_t now() {
75 return systemTime(SYSTEM_TIME_MONOTONIC);
76}
77
Jeff Brownb88102f2010-09-08 11:49:43 -070078static inline const char* toString(bool value) {
79 return value ? "true" : "false";
80}
81
Jeff Brown01ce2e92010-09-26 22:20:12 -070082static inline int32_t getMotionEventActionPointerIndex(int32_t action) {
83 return (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK)
84 >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
85}
86
87static bool isValidKeyAction(int32_t action) {
88 switch (action) {
89 case AKEY_EVENT_ACTION_DOWN:
90 case AKEY_EVENT_ACTION_UP:
91 return true;
92 default:
93 return false;
94 }
95}
96
97static bool validateKeyEvent(int32_t action) {
98 if (! isValidKeyAction(action)) {
Steve Block3762c312012-01-06 19:20:56 +000099 ALOGE("Key event has invalid action code 0x%x", action);
Jeff Brown01ce2e92010-09-26 22:20:12 -0700100 return false;
101 }
102 return true;
103}
104
Jeff Brownb6997262010-10-08 22:31:17 -0700105static bool isValidMotionAction(int32_t action, size_t pointerCount) {
Jeff Brown01ce2e92010-09-26 22:20:12 -0700106 switch (action & AMOTION_EVENT_ACTION_MASK) {
107 case AMOTION_EVENT_ACTION_DOWN:
108 case AMOTION_EVENT_ACTION_UP:
109 case AMOTION_EVENT_ACTION_CANCEL:
110 case AMOTION_EVENT_ACTION_MOVE:
Jeff Brown01ce2e92010-09-26 22:20:12 -0700111 case AMOTION_EVENT_ACTION_OUTSIDE:
Jeff Browna032cc02011-03-07 16:56:21 -0800112 case AMOTION_EVENT_ACTION_HOVER_ENTER:
Jeff Browncc0c1592011-02-19 05:07:28 -0800113 case AMOTION_EVENT_ACTION_HOVER_MOVE:
Jeff Browna032cc02011-03-07 16:56:21 -0800114 case AMOTION_EVENT_ACTION_HOVER_EXIT:
Jeff Brown33bbfd22011-02-24 20:55:35 -0800115 case AMOTION_EVENT_ACTION_SCROLL:
Jeff Brown01ce2e92010-09-26 22:20:12 -0700116 return true;
Jeff Brownb6997262010-10-08 22:31:17 -0700117 case AMOTION_EVENT_ACTION_POINTER_DOWN:
118 case AMOTION_EVENT_ACTION_POINTER_UP: {
119 int32_t index = getMotionEventActionPointerIndex(action);
120 return index >= 0 && size_t(index) < pointerCount;
121 }
Jeff Brown01ce2e92010-09-26 22:20:12 -0700122 default:
123 return false;
124 }
125}
126
127static bool validateMotionEvent(int32_t action, size_t pointerCount,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700128 const PointerProperties* pointerProperties) {
Jeff Brownb6997262010-10-08 22:31:17 -0700129 if (! isValidMotionAction(action, pointerCount)) {
Steve Block3762c312012-01-06 19:20:56 +0000130 ALOGE("Motion event has invalid action code 0x%x", action);
Jeff Brown01ce2e92010-09-26 22:20:12 -0700131 return false;
132 }
133 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Steve Block3762c312012-01-06 19:20:56 +0000134 ALOGE("Motion event has invalid pointer count %d; value must be between 1 and %d.",
Jeff Brown01ce2e92010-09-26 22:20:12 -0700135 pointerCount, MAX_POINTERS);
136 return false;
137 }
Jeff Brownc3db8582010-10-20 15:33:38 -0700138 BitSet32 pointerIdBits;
Jeff Brown01ce2e92010-09-26 22:20:12 -0700139 for (size_t i = 0; i < pointerCount; i++) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700140 int32_t id = pointerProperties[i].id;
Jeff Brownc3db8582010-10-20 15:33:38 -0700141 if (id < 0 || id > MAX_POINTER_ID) {
Steve Block3762c312012-01-06 19:20:56 +0000142 ALOGE("Motion event has invalid pointer id %d; value must be between 0 and %d",
Jeff Brownc3db8582010-10-20 15:33:38 -0700143 id, MAX_POINTER_ID);
Jeff Brown01ce2e92010-09-26 22:20:12 -0700144 return false;
145 }
Jeff Brownc3db8582010-10-20 15:33:38 -0700146 if (pointerIdBits.hasBit(id)) {
Steve Block3762c312012-01-06 19:20:56 +0000147 ALOGE("Motion event has duplicate pointer id %d", id);
Jeff Brownc3db8582010-10-20 15:33:38 -0700148 return false;
149 }
150 pointerIdBits.markBit(id);
Jeff Brown01ce2e92010-09-26 22:20:12 -0700151 }
152 return true;
153}
154
Jeff Brownfbf09772011-01-16 14:06:57 -0800155static void dumpRegion(String8& dump, const SkRegion& region) {
156 if (region.isEmpty()) {
157 dump.append("<empty>");
158 return;
159 }
160
161 bool first = true;
162 for (SkRegion::Iterator it(region); !it.done(); it.next()) {
163 if (first) {
164 first = false;
165 } else {
166 dump.append("|");
167 }
168 const SkIRect& rect = it.rect();
169 dump.appendFormat("[%d,%d][%d,%d]", rect.fLeft, rect.fTop, rect.fRight, rect.fBottom);
170 }
171}
172
Jeff Brownb88102f2010-09-08 11:49:43 -0700173
Jeff Brown46b9ac02010-04-22 18:58:52 -0700174// --- InputDispatcher ---
175
Jeff Brown9c3cda02010-06-15 01:31:58 -0700176InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy) :
Jeff Brownb88102f2010-09-08 11:49:43 -0700177 mPolicy(policy),
Jeff Brown928e0542011-01-10 11:17:36 -0800178 mPendingEvent(NULL), mAppSwitchSawKeyDown(false), mAppSwitchDueTime(LONG_LONG_MAX),
179 mNextUnblockedEvent(NULL),
Jeff Brown0029c662011-03-30 02:25:18 -0700180 mDispatchEnabled(true), mDispatchFrozen(false), mInputFilterEnabled(false),
Jeff Brownb88102f2010-09-08 11:49:43 -0700181 mCurrentInputTargetsValid(false),
Jeff Brown9302c872011-07-13 22:51:29 -0700182 mInputTargetWaitCause(INPUT_TARGET_WAIT_CAUSE_NONE) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -0700183 mLooper = new Looper(false);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700184
Jeff Brown46b9ac02010-04-22 18:58:52 -0700185 mKeyRepeatState.lastKeyEntry = NULL;
Jeff Brown9c3cda02010-06-15 01:31:58 -0700186
Jeff Brown214eaf42011-05-26 19:17:02 -0700187 policy->getDispatcherConfiguration(&mConfig);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700188}
189
190InputDispatcher::~InputDispatcher() {
Jeff Brownb88102f2010-09-08 11:49:43 -0700191 { // acquire lock
192 AutoMutex _l(mLock);
193
194 resetKeyRepeatLocked();
Jeff Brown54a18252010-09-16 14:07:33 -0700195 releasePendingEventLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -0700196 drainInboundQueueLocked();
197 }
Jeff Brown46b9ac02010-04-22 18:58:52 -0700198
199 while (mConnectionsByReceiveFd.size() != 0) {
200 unregisterInputChannel(mConnectionsByReceiveFd.valueAt(0)->inputChannel);
201 }
Jeff Brown46b9ac02010-04-22 18:58:52 -0700202}
203
204void InputDispatcher::dispatchOnce() {
Jeff Brown46b9ac02010-04-22 18:58:52 -0700205 nsecs_t nextWakeupTime = LONG_LONG_MAX;
206 { // acquire lock
207 AutoMutex _l(mLock);
Jeff Brown112b5f52012-01-27 17:32:06 -0800208 mDispatcherIsAliveCondition.broadcast();
209
Jeff Brown214eaf42011-05-26 19:17:02 -0700210 dispatchOnceInnerLocked(&nextWakeupTime);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700211
Jeff Brownb88102f2010-09-08 11:49:43 -0700212 if (runCommandsLockedInterruptible()) {
213 nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
Jeff Brown46b9ac02010-04-22 18:58:52 -0700214 }
Jeff Brown46b9ac02010-04-22 18:58:52 -0700215 } // release lock
216
Jeff Brownb88102f2010-09-08 11:49:43 -0700217 // Wait for callback or timeout or wake. (make sure we round up, not down)
218 nsecs_t currentTime = now();
Jeff Brownaa3855d2011-03-17 01:34:19 -0700219 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
Jeff Brown4fe6c3e2010-09-13 23:17:30 -0700220 mLooper->pollOnce(timeoutMillis);
Jeff Brownb88102f2010-09-08 11:49:43 -0700221}
222
Jeff Brown214eaf42011-05-26 19:17:02 -0700223void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700224 nsecs_t currentTime = now();
225
226 // Reset the key repeat timer whenever we disallow key events, even if the next event
227 // is not a key. This is to ensure that we abort a key repeat if the device is just coming
228 // out of sleep.
Jeff Brown214eaf42011-05-26 19:17:02 -0700229 if (!mPolicy->isKeyRepeatEnabled()) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700230 resetKeyRepeatLocked();
231 }
232
Jeff Brownb88102f2010-09-08 11:49:43 -0700233 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
234 if (mDispatchFrozen) {
235#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +0000236 ALOGD("Dispatch frozen. Waiting some more.");
Jeff Brownb88102f2010-09-08 11:49:43 -0700237#endif
238 return;
239 }
240
241 // Optimize latency of app switches.
242 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
243 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
244 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
245 if (mAppSwitchDueTime < *nextWakeupTime) {
246 *nextWakeupTime = mAppSwitchDueTime;
247 }
248
Jeff Brownb88102f2010-09-08 11:49:43 -0700249 // Ready to start a new event.
250 // If we don't already have a pending event, go grab one.
251 if (! mPendingEvent) {
252 if (mInboundQueue.isEmpty()) {
253 if (isAppSwitchDue) {
254 // The inbound queue is empty so the app switch key we were waiting
255 // for will never arrive. Stop waiting for it.
256 resetPendingAppSwitchLocked(false);
257 isAppSwitchDue = false;
258 }
259
260 // Synthesize a key repeat if appropriate.
261 if (mKeyRepeatState.lastKeyEntry) {
262 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
Jeff Brown214eaf42011-05-26 19:17:02 -0700263 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700264 } else {
265 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
266 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
267 }
268 }
269 }
Jeff Browncc4f7db2011-08-30 20:34:48 -0700270
271 // Nothing to do if there is no pending event.
Jeff Brownb88102f2010-09-08 11:49:43 -0700272 if (! mPendingEvent) {
Jeff Browncc4f7db2011-08-30 20:34:48 -0700273 if (mActiveConnections.isEmpty()) {
274 dispatchIdleLocked();
275 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700276 return;
277 }
278 } else {
279 // Inbound queue has at least one entry.
Jeff Brown30802802012-02-03 13:35:13 -0800280 EventEntry* entry = mInboundQueue.dequeueAtHead();
Jeff Brownb88102f2010-09-08 11:49:43 -0700281 mPendingEvent = entry;
282 }
Jeff Browne2fe69e2010-10-18 13:21:23 -0700283
284 // Poke user activity for this event.
285 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
286 pokeUserActivityLocked(mPendingEvent);
287 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700288 }
289
290 // Now we have an event to dispatch.
Jeff Brown928e0542011-01-10 11:17:36 -0800291 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Steve Blockec193de2012-01-09 18:35:44 +0000292 ALOG_ASSERT(mPendingEvent != NULL);
Jeff Brown54a18252010-09-16 14:07:33 -0700293 bool done = false;
Jeff Brownb6997262010-10-08 22:31:17 -0700294 DropReason dropReason = DROP_REASON_NOT_DROPPED;
295 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
296 dropReason = DROP_REASON_POLICY;
297 } else if (!mDispatchEnabled) {
298 dropReason = DROP_REASON_DISABLED;
299 }
Jeff Brown928e0542011-01-10 11:17:36 -0800300
301 if (mNextUnblockedEvent == mPendingEvent) {
302 mNextUnblockedEvent = NULL;
303 }
304
Jeff Brownb88102f2010-09-08 11:49:43 -0700305 switch (mPendingEvent->type) {
306 case EventEntry::TYPE_CONFIGURATION_CHANGED: {
307 ConfigurationChangedEntry* typedEntry =
308 static_cast<ConfigurationChangedEntry*>(mPendingEvent);
Jeff Brown54a18252010-09-16 14:07:33 -0700309 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Jeff Brownb6997262010-10-08 22:31:17 -0700310 dropReason = DROP_REASON_NOT_DROPPED; // configuration changes are never dropped
Jeff Brownb88102f2010-09-08 11:49:43 -0700311 break;
312 }
313
Jeff Brown65fd2512011-08-18 11:20:58 -0700314 case EventEntry::TYPE_DEVICE_RESET: {
315 DeviceResetEntry* typedEntry =
316 static_cast<DeviceResetEntry*>(mPendingEvent);
317 done = dispatchDeviceResetLocked(currentTime, typedEntry);
318 dropReason = DROP_REASON_NOT_DROPPED; // device resets are never dropped
319 break;
320 }
321
Jeff Brownb88102f2010-09-08 11:49:43 -0700322 case EventEntry::TYPE_KEY: {
323 KeyEntry* typedEntry = static_cast<KeyEntry*>(mPendingEvent);
Jeff Brownb6997262010-10-08 22:31:17 -0700324 if (isAppSwitchDue) {
325 if (isAppSwitchKeyEventLocked(typedEntry)) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700326 resetPendingAppSwitchLocked(true);
Jeff Brownb6997262010-10-08 22:31:17 -0700327 isAppSwitchDue = false;
328 } else if (dropReason == DROP_REASON_NOT_DROPPED) {
329 dropReason = DROP_REASON_APP_SWITCH;
Jeff Brownb88102f2010-09-08 11:49:43 -0700330 }
331 }
Jeff Brown928e0542011-01-10 11:17:36 -0800332 if (dropReason == DROP_REASON_NOT_DROPPED
333 && isStaleEventLocked(currentTime, typedEntry)) {
334 dropReason = DROP_REASON_STALE;
335 }
336 if (dropReason == DROP_REASON_NOT_DROPPED && mNextUnblockedEvent) {
337 dropReason = DROP_REASON_BLOCKED;
338 }
Jeff Brown214eaf42011-05-26 19:17:02 -0700339 done = dispatchKeyLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700340 break;
341 }
342
343 case EventEntry::TYPE_MOTION: {
344 MotionEntry* typedEntry = static_cast<MotionEntry*>(mPendingEvent);
Jeff Brownb6997262010-10-08 22:31:17 -0700345 if (dropReason == DROP_REASON_NOT_DROPPED && isAppSwitchDue) {
346 dropReason = DROP_REASON_APP_SWITCH;
Jeff Brownb88102f2010-09-08 11:49:43 -0700347 }
Jeff Brown928e0542011-01-10 11:17:36 -0800348 if (dropReason == DROP_REASON_NOT_DROPPED
349 && isStaleEventLocked(currentTime, typedEntry)) {
350 dropReason = DROP_REASON_STALE;
351 }
352 if (dropReason == DROP_REASON_NOT_DROPPED && mNextUnblockedEvent) {
353 dropReason = DROP_REASON_BLOCKED;
354 }
Jeff Brownb6997262010-10-08 22:31:17 -0700355 done = dispatchMotionLocked(currentTime, typedEntry,
Jeff Browne20c9e02010-10-11 14:20:19 -0700356 &dropReason, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700357 break;
358 }
359
360 default:
Steve Blockec193de2012-01-09 18:35:44 +0000361 ALOG_ASSERT(false);
Jeff Brownb88102f2010-09-08 11:49:43 -0700362 break;
363 }
364
Jeff Brown54a18252010-09-16 14:07:33 -0700365 if (done) {
Jeff Brownb6997262010-10-08 22:31:17 -0700366 if (dropReason != DROP_REASON_NOT_DROPPED) {
367 dropInboundEventLocked(mPendingEvent, dropReason);
368 }
369
Jeff Brown54a18252010-09-16 14:07:33 -0700370 releasePendingEventLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -0700371 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
372 }
373}
374
Jeff Browncc4f7db2011-08-30 20:34:48 -0700375void InputDispatcher::dispatchIdleLocked() {
376#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +0000377 ALOGD("Dispatcher idle. There are no pending events or active connections.");
Jeff Browncc4f7db2011-08-30 20:34:48 -0700378#endif
379
380 // Reset targets when idle, to release input channels and other resources
381 // they are holding onto.
382 resetTargetsLocked();
383}
384
Jeff Brownb88102f2010-09-08 11:49:43 -0700385bool InputDispatcher::enqueueInboundEventLocked(EventEntry* entry) {
386 bool needWake = mInboundQueue.isEmpty();
387 mInboundQueue.enqueueAtTail(entry);
388
389 switch (entry->type) {
Jeff Brownb6997262010-10-08 22:31:17 -0700390 case EventEntry::TYPE_KEY: {
Jeff Brown928e0542011-01-10 11:17:36 -0800391 // Optimize app switch latency.
392 // If the application takes too long to catch up then we drop all events preceding
393 // the app switch key.
Jeff Brownb6997262010-10-08 22:31:17 -0700394 KeyEntry* keyEntry = static_cast<KeyEntry*>(entry);
395 if (isAppSwitchKeyEventLocked(keyEntry)) {
396 if (keyEntry->action == AKEY_EVENT_ACTION_DOWN) {
397 mAppSwitchSawKeyDown = true;
398 } else if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
399 if (mAppSwitchSawKeyDown) {
400#if DEBUG_APP_SWITCH
Steve Block5baa3a62011-12-20 16:23:08 +0000401 ALOGD("App switch is pending!");
Jeff Brownb6997262010-10-08 22:31:17 -0700402#endif
403 mAppSwitchDueTime = keyEntry->eventTime + APP_SWITCH_TIMEOUT;
404 mAppSwitchSawKeyDown = false;
405 needWake = true;
406 }
407 }
408 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700409 break;
410 }
Jeff Brown928e0542011-01-10 11:17:36 -0800411
412 case EventEntry::TYPE_MOTION: {
413 // Optimize case where the current application is unresponsive and the user
414 // decides to touch a window in a different application.
415 // If the application takes too long to catch up then we drop all events preceding
416 // the touch into the other window.
417 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
Jeff Brown33bbfd22011-02-24 20:55:35 -0800418 if (motionEntry->action == AMOTION_EVENT_ACTION_DOWN
Jeff Brown928e0542011-01-10 11:17:36 -0800419 && (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER)
420 && mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY
Jeff Brown9302c872011-07-13 22:51:29 -0700421 && mInputTargetWaitApplicationHandle != NULL) {
Jeff Brown3241b6b2012-02-03 15:08:02 -0800422 int32_t x = int32_t(motionEntry->pointerCoords[0].
Jeff Brownebbd5d12011-02-17 13:01:34 -0800423 getAxisValue(AMOTION_EVENT_AXIS_X));
Jeff Brown3241b6b2012-02-03 15:08:02 -0800424 int32_t y = int32_t(motionEntry->pointerCoords[0].
Jeff Brownebbd5d12011-02-17 13:01:34 -0800425 getAxisValue(AMOTION_EVENT_AXIS_Y));
Jeff Brown9302c872011-07-13 22:51:29 -0700426 sp<InputWindowHandle> touchedWindowHandle = findTouchedWindowAtLocked(x, y);
427 if (touchedWindowHandle != NULL
428 && touchedWindowHandle->inputApplicationHandle
429 != mInputTargetWaitApplicationHandle) {
Jeff Brown928e0542011-01-10 11:17:36 -0800430 // User touched a different application than the one we are waiting on.
431 // Flag the event, and start pruning the input queue.
432 mNextUnblockedEvent = motionEntry;
433 needWake = true;
434 }
435 }
436 break;
437 }
Jeff Brownb6997262010-10-08 22:31:17 -0700438 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700439
440 return needWake;
441}
442
Jeff Brown9302c872011-07-13 22:51:29 -0700443sp<InputWindowHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t x, int32_t y) {
Jeff Brown928e0542011-01-10 11:17:36 -0800444 // Traverse windows from front to back to find touched window.
Jeff Brown9302c872011-07-13 22:51:29 -0700445 size_t numWindows = mWindowHandles.size();
Jeff Brown928e0542011-01-10 11:17:36 -0800446 for (size_t i = 0; i < numWindows; i++) {
Jeff Brown9302c872011-07-13 22:51:29 -0700447 sp<InputWindowHandle> windowHandle = mWindowHandles.itemAt(i);
Jeff Browncc4f7db2011-08-30 20:34:48 -0700448 const InputWindowInfo* windowInfo = windowHandle->getInfo();
449 int32_t flags = windowInfo->layoutParamsFlags;
Jeff Brown928e0542011-01-10 11:17:36 -0800450
Jeff Browncc4f7db2011-08-30 20:34:48 -0700451 if (windowInfo->visible) {
452 if (!(flags & InputWindowInfo::FLAG_NOT_TOUCHABLE)) {
453 bool isTouchModal = (flags & (InputWindowInfo::FLAG_NOT_FOCUSABLE
454 | InputWindowInfo::FLAG_NOT_TOUCH_MODAL)) == 0;
455 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
Jeff Brown928e0542011-01-10 11:17:36 -0800456 // Found window.
Jeff Brown9302c872011-07-13 22:51:29 -0700457 return windowHandle;
Jeff Brown928e0542011-01-10 11:17:36 -0800458 }
459 }
460 }
461
Jeff Browncc4f7db2011-08-30 20:34:48 -0700462 if (flags & InputWindowInfo::FLAG_SYSTEM_ERROR) {
Jeff Brown928e0542011-01-10 11:17:36 -0800463 // Error window is on top but not visible, so touch is dropped.
464 return NULL;
465 }
466 }
467 return NULL;
468}
469
Jeff Brownb6997262010-10-08 22:31:17 -0700470void InputDispatcher::dropInboundEventLocked(EventEntry* entry, DropReason dropReason) {
471 const char* reason;
472 switch (dropReason) {
473 case DROP_REASON_POLICY:
Jeff Browne20c9e02010-10-11 14:20:19 -0700474#if DEBUG_INBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +0000475 ALOGD("Dropped event because policy consumed it.");
Jeff Browne20c9e02010-10-11 14:20:19 -0700476#endif
Jeff Brown3122e442010-10-11 23:32:49 -0700477 reason = "inbound event was dropped because the policy consumed it";
Jeff Brownb6997262010-10-08 22:31:17 -0700478 break;
479 case DROP_REASON_DISABLED:
Steve Block6215d3f2012-01-04 20:05:49 +0000480 ALOGI("Dropped event because input dispatch is disabled.");
Jeff Brownb6997262010-10-08 22:31:17 -0700481 reason = "inbound event was dropped because input dispatch is disabled";
482 break;
483 case DROP_REASON_APP_SWITCH:
Steve Block6215d3f2012-01-04 20:05:49 +0000484 ALOGI("Dropped event because of pending overdue app switch.");
Jeff Brownb6997262010-10-08 22:31:17 -0700485 reason = "inbound event was dropped because of pending overdue app switch";
486 break;
Jeff Brown928e0542011-01-10 11:17:36 -0800487 case DROP_REASON_BLOCKED:
Steve Block6215d3f2012-01-04 20:05:49 +0000488 ALOGI("Dropped event because the current application is not responding and the user "
Jeff Brown81346812011-06-28 20:08:48 -0700489 "has started interacting with a different application.");
Jeff Brown928e0542011-01-10 11:17:36 -0800490 reason = "inbound event was dropped because the current application is not responding "
Jeff Brown81346812011-06-28 20:08:48 -0700491 "and the user has started interacting with a different application";
Jeff Brown928e0542011-01-10 11:17:36 -0800492 break;
493 case DROP_REASON_STALE:
Steve Block6215d3f2012-01-04 20:05:49 +0000494 ALOGI("Dropped event because it is stale.");
Jeff Brown928e0542011-01-10 11:17:36 -0800495 reason = "inbound event was dropped because it is stale";
496 break;
Jeff Brownb6997262010-10-08 22:31:17 -0700497 default:
Steve Blockec193de2012-01-09 18:35:44 +0000498 ALOG_ASSERT(false);
Jeff Brownb6997262010-10-08 22:31:17 -0700499 return;
500 }
501
502 switch (entry->type) {
Jeff Brownda3d5a92011-03-29 15:11:34 -0700503 case EventEntry::TYPE_KEY: {
504 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
505 synthesizeCancelationEventsForAllConnectionsLocked(options);
Jeff Brownb6997262010-10-08 22:31:17 -0700506 break;
Jeff Brownda3d5a92011-03-29 15:11:34 -0700507 }
Jeff Brownb6997262010-10-08 22:31:17 -0700508 case EventEntry::TYPE_MOTION: {
509 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
510 if (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) {
Jeff Brownda3d5a92011-03-29 15:11:34 -0700511 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
512 synthesizeCancelationEventsForAllConnectionsLocked(options);
Jeff Brownb6997262010-10-08 22:31:17 -0700513 } else {
Jeff Brownda3d5a92011-03-29 15:11:34 -0700514 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
515 synthesizeCancelationEventsForAllConnectionsLocked(options);
Jeff Brownb6997262010-10-08 22:31:17 -0700516 }
517 break;
518 }
519 }
520}
521
522bool InputDispatcher::isAppSwitchKeyCode(int32_t keyCode) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700523 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL;
524}
525
Jeff Brownb6997262010-10-08 22:31:17 -0700526bool InputDispatcher::isAppSwitchKeyEventLocked(KeyEntry* keyEntry) {
527 return ! (keyEntry->flags & AKEY_EVENT_FLAG_CANCELED)
528 && isAppSwitchKeyCode(keyEntry->keyCode)
Jeff Browne20c9e02010-10-11 14:20:19 -0700529 && (keyEntry->policyFlags & POLICY_FLAG_TRUSTED)
Jeff Brownb6997262010-10-08 22:31:17 -0700530 && (keyEntry->policyFlags & POLICY_FLAG_PASS_TO_USER);
531}
532
Jeff Brownb88102f2010-09-08 11:49:43 -0700533bool InputDispatcher::isAppSwitchPendingLocked() {
534 return mAppSwitchDueTime != LONG_LONG_MAX;
535}
536
Jeff Brownb88102f2010-09-08 11:49:43 -0700537void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
538 mAppSwitchDueTime = LONG_LONG_MAX;
539
540#if DEBUG_APP_SWITCH
541 if (handled) {
Steve Block5baa3a62011-12-20 16:23:08 +0000542 ALOGD("App switch has arrived.");
Jeff Brownb88102f2010-09-08 11:49:43 -0700543 } else {
Steve Block5baa3a62011-12-20 16:23:08 +0000544 ALOGD("App switch was abandoned.");
Jeff Brownb88102f2010-09-08 11:49:43 -0700545 }
546#endif
Jeff Brown46b9ac02010-04-22 18:58:52 -0700547}
548
Jeff Brown928e0542011-01-10 11:17:36 -0800549bool InputDispatcher::isStaleEventLocked(nsecs_t currentTime, EventEntry* entry) {
550 return currentTime - entry->eventTime >= STALE_EVENT_TIMEOUT;
551}
552
Jeff Brown9c3cda02010-06-15 01:31:58 -0700553bool InputDispatcher::runCommandsLockedInterruptible() {
554 if (mCommandQueue.isEmpty()) {
555 return false;
556 }
Jeff Brown46b9ac02010-04-22 18:58:52 -0700557
Jeff Brown9c3cda02010-06-15 01:31:58 -0700558 do {
559 CommandEntry* commandEntry = mCommandQueue.dequeueAtHead();
560
561 Command command = commandEntry->command;
562 (this->*command)(commandEntry); // commands are implicitly 'LockedInterruptible'
563
Jeff Brown7fbdc842010-06-17 20:52:56 -0700564 commandEntry->connection.clear();
Jeff Brownac386072011-07-20 15:19:50 -0700565 delete commandEntry;
Jeff Brown9c3cda02010-06-15 01:31:58 -0700566 } while (! mCommandQueue.isEmpty());
567 return true;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700568}
569
Jeff Brown9c3cda02010-06-15 01:31:58 -0700570InputDispatcher::CommandEntry* InputDispatcher::postCommandLocked(Command command) {
Jeff Brownac386072011-07-20 15:19:50 -0700571 CommandEntry* commandEntry = new CommandEntry(command);
Jeff Brown9c3cda02010-06-15 01:31:58 -0700572 mCommandQueue.enqueueAtTail(commandEntry);
573 return commandEntry;
574}
575
Jeff Brownb88102f2010-09-08 11:49:43 -0700576void InputDispatcher::drainInboundQueueLocked() {
577 while (! mInboundQueue.isEmpty()) {
578 EventEntry* entry = mInboundQueue.dequeueAtHead();
Jeff Brown54a18252010-09-16 14:07:33 -0700579 releaseInboundEventLocked(entry);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700580 }
Jeff Brown46b9ac02010-04-22 18:58:52 -0700581}
582
Jeff Brown54a18252010-09-16 14:07:33 -0700583void InputDispatcher::releasePendingEventLocked() {
Jeff Brownb88102f2010-09-08 11:49:43 -0700584 if (mPendingEvent) {
Jeff Brown54a18252010-09-16 14:07:33 -0700585 releaseInboundEventLocked(mPendingEvent);
Jeff Brownb88102f2010-09-08 11:49:43 -0700586 mPendingEvent = NULL;
587 }
588}
589
Jeff Brown54a18252010-09-16 14:07:33 -0700590void InputDispatcher::releaseInboundEventLocked(EventEntry* entry) {
Jeff Brown01ce2e92010-09-26 22:20:12 -0700591 InjectionState* injectionState = entry->injectionState;
592 if (injectionState && injectionState->injectionResult == INPUT_EVENT_INJECTION_PENDING) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700593#if DEBUG_DISPATCH_CYCLE
Steve Block5baa3a62011-12-20 16:23:08 +0000594 ALOGD("Injected inbound event was dropped.");
Jeff Brownb88102f2010-09-08 11:49:43 -0700595#endif
596 setInjectionResultLocked(entry, INPUT_EVENT_INJECTION_FAILED);
597 }
Jeff Brownabb4d442011-08-15 12:55:32 -0700598 if (entry == mNextUnblockedEvent) {
599 mNextUnblockedEvent = NULL;
600 }
Jeff Brownac386072011-07-20 15:19:50 -0700601 entry->release();
Jeff Brownb88102f2010-09-08 11:49:43 -0700602}
603
Jeff Brownb88102f2010-09-08 11:49:43 -0700604void InputDispatcher::resetKeyRepeatLocked() {
605 if (mKeyRepeatState.lastKeyEntry) {
Jeff Brownac386072011-07-20 15:19:50 -0700606 mKeyRepeatState.lastKeyEntry->release();
Jeff Brownb88102f2010-09-08 11:49:43 -0700607 mKeyRepeatState.lastKeyEntry = NULL;
608 }
609}
610
Jeff Brown214eaf42011-05-26 19:17:02 -0700611InputDispatcher::KeyEntry* InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
Jeff Brown349703e2010-06-22 01:27:15 -0700612 KeyEntry* entry = mKeyRepeatState.lastKeyEntry;
613
Jeff Brown349703e2010-06-22 01:27:15 -0700614 // Reuse the repeated key entry if it is otherwise unreferenced.
Jeff Browne20c9e02010-10-11 14:20:19 -0700615 uint32_t policyFlags = (entry->policyFlags & POLICY_FLAG_RAW_MASK)
616 | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700617 if (entry->refCount == 1) {
Jeff Brownac386072011-07-20 15:19:50 -0700618 entry->recycle();
Jeff Brown7fbdc842010-06-17 20:52:56 -0700619 entry->eventTime = currentTime;
Jeff Brown7fbdc842010-06-17 20:52:56 -0700620 entry->policyFlags = policyFlags;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700621 entry->repeatCount += 1;
622 } else {
Jeff Brownac386072011-07-20 15:19:50 -0700623 KeyEntry* newEntry = new KeyEntry(currentTime,
Jeff Brownc5ed5912010-07-14 18:48:53 -0700624 entry->deviceId, entry->source, policyFlags,
Jeff Brown7fbdc842010-06-17 20:52:56 -0700625 entry->action, entry->flags, entry->keyCode, entry->scanCode,
Jeff Brown00fa7bd2010-07-02 15:37:36 -0700626 entry->metaState, entry->repeatCount + 1, entry->downTime);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700627
628 mKeyRepeatState.lastKeyEntry = newEntry;
Jeff Brownac386072011-07-20 15:19:50 -0700629 entry->release();
Jeff Brown46b9ac02010-04-22 18:58:52 -0700630
631 entry = newEntry;
632 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700633 entry->syntheticRepeat = true;
634
635 // Increment reference count since we keep a reference to the event in
636 // mKeyRepeatState.lastKeyEntry in addition to the one we return.
637 entry->refCount += 1;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700638
Jeff Brown214eaf42011-05-26 19:17:02 -0700639 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Jeff Brownb88102f2010-09-08 11:49:43 -0700640 return entry;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700641}
642
Jeff Brownb88102f2010-09-08 11:49:43 -0700643bool InputDispatcher::dispatchConfigurationChangedLocked(
644 nsecs_t currentTime, ConfigurationChangedEntry* entry) {
Jeff Brown46b9ac02010-04-22 18:58:52 -0700645#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +0000646 ALOGD("dispatchConfigurationChanged - eventTime=%lld", entry->eventTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700647#endif
648
649 // Reset key repeating in case a keyboard device was added or removed or something.
650 resetKeyRepeatLocked();
651
652 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
653 CommandEntry* commandEntry = postCommandLocked(
654 & InputDispatcher::doNotifyConfigurationChangedInterruptible);
655 commandEntry->eventTime = entry->eventTime;
656 return true;
657}
658
Jeff Brown65fd2512011-08-18 11:20:58 -0700659bool InputDispatcher::dispatchDeviceResetLocked(
660 nsecs_t currentTime, DeviceResetEntry* entry) {
661#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +0000662 ALOGD("dispatchDeviceReset - eventTime=%lld, deviceId=%d", entry->eventTime, entry->deviceId);
Jeff Brown65fd2512011-08-18 11:20:58 -0700663#endif
664
665 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
666 "device was reset");
667 options.deviceId = entry->deviceId;
668 synthesizeCancelationEventsForAllConnectionsLocked(options);
669 return true;
670}
671
Jeff Brown214eaf42011-05-26 19:17:02 -0700672bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, KeyEntry* entry,
Jeff Browne20c9e02010-10-11 14:20:19 -0700673 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Jeff Browne46a0a42010-11-02 17:58:22 -0700674 // Preprocessing.
675 if (! entry->dispatchInProgress) {
676 if (entry->repeatCount == 0
677 && entry->action == AKEY_EVENT_ACTION_DOWN
678 && (entry->policyFlags & POLICY_FLAG_TRUSTED)
Jeff Brown0029c662011-03-30 02:25:18 -0700679 && (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
Jeff Browne46a0a42010-11-02 17:58:22 -0700680 if (mKeyRepeatState.lastKeyEntry
681 && mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode) {
682 // We have seen two identical key downs in a row which indicates that the device
683 // driver is automatically generating key repeats itself. We take note of the
684 // repeat here, but we disable our own next key repeat timer since it is clear that
685 // we will not need to synthesize key repeats ourselves.
686 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
687 resetKeyRepeatLocked();
688 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
689 } else {
690 // Not a repeat. Save key down state in case we do see a repeat later.
691 resetKeyRepeatLocked();
Jeff Brown214eaf42011-05-26 19:17:02 -0700692 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
Jeff Browne46a0a42010-11-02 17:58:22 -0700693 }
694 mKeyRepeatState.lastKeyEntry = entry;
695 entry->refCount += 1;
696 } else if (! entry->syntheticRepeat) {
697 resetKeyRepeatLocked();
698 }
699
Jeff Browne2e01262011-03-02 20:34:30 -0800700 if (entry->repeatCount == 1) {
701 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
702 } else {
703 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
704 }
705
Jeff Browne46a0a42010-11-02 17:58:22 -0700706 entry->dispatchInProgress = true;
707 resetTargetsLocked();
708
709 logOutboundKeyDetailsLocked("dispatchKey - ", entry);
710 }
711
Jeff Brown905805a2011-10-12 13:57:59 -0700712 // Handle case where the policy asked us to try again later last time.
713 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
714 if (currentTime < entry->interceptKeyWakeupTime) {
715 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
716 *nextWakeupTime = entry->interceptKeyWakeupTime;
717 }
718 return false; // wait until next wakeup
719 }
720 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
721 entry->interceptKeyWakeupTime = 0;
722 }
723
Jeff Brown54a18252010-09-16 14:07:33 -0700724 // Give the policy a chance to intercept the key.
725 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
Jeff Browne20c9e02010-10-11 14:20:19 -0700726 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Jeff Brown54a18252010-09-16 14:07:33 -0700727 CommandEntry* commandEntry = postCommandLocked(
728 & InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
Jeff Brown9302c872011-07-13 22:51:29 -0700729 if (mFocusedWindowHandle != NULL) {
730 commandEntry->inputWindowHandle = mFocusedWindowHandle;
Jeff Brown54a18252010-09-16 14:07:33 -0700731 }
732 commandEntry->keyEntry = entry;
733 entry->refCount += 1;
734 return false; // wait for the command to run
735 } else {
736 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
737 }
738 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Jeff Browne20c9e02010-10-11 14:20:19 -0700739 if (*dropReason == DROP_REASON_NOT_DROPPED) {
740 *dropReason = DROP_REASON_POLICY;
741 }
Jeff Brown54a18252010-09-16 14:07:33 -0700742 }
743
744 // Clean up if dropping the event.
Jeff Browne20c9e02010-10-11 14:20:19 -0700745 if (*dropReason != DROP_REASON_NOT_DROPPED) {
Jeff Brown54a18252010-09-16 14:07:33 -0700746 resetTargetsLocked();
Jeff Brown3122e442010-10-11 23:32:49 -0700747 setInjectionResultLocked(entry, *dropReason == DROP_REASON_POLICY
748 ? INPUT_EVENT_INJECTION_SUCCEEDED : INPUT_EVENT_INJECTION_FAILED);
Jeff Brown54a18252010-09-16 14:07:33 -0700749 return true;
750 }
751
Jeff Brownb88102f2010-09-08 11:49:43 -0700752 // Identify targets.
753 if (! mCurrentInputTargetsValid) {
Jeff Brown01ce2e92010-09-26 22:20:12 -0700754 int32_t injectionResult = findFocusedWindowTargetsLocked(currentTime,
755 entry, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700756 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
757 return false;
758 }
759
760 setInjectionResultLocked(entry, injectionResult);
761 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
762 return true;
763 }
764
765 addMonitoringTargetsLocked();
Jeff Brown01ce2e92010-09-26 22:20:12 -0700766 commitTargetsLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -0700767 }
768
769 // Dispatch the key.
Jeff Brown3241b6b2012-02-03 15:08:02 -0800770 dispatchEventToCurrentInputTargetsLocked(currentTime, entry);
Jeff Brownb88102f2010-09-08 11:49:43 -0700771 return true;
772}
773
774void InputDispatcher::logOutboundKeyDetailsLocked(const char* prefix, const KeyEntry* entry) {
775#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +0000776 ALOGD("%seventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, "
Jeff Brownb88102f2010-09-08 11:49:43 -0700777 "action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, "
Jeff Browne46a0a42010-11-02 17:58:22 -0700778 "repeatCount=%d, downTime=%lld",
Jeff Brownb88102f2010-09-08 11:49:43 -0700779 prefix,
780 entry->eventTime, entry->deviceId, entry->source, entry->policyFlags,
781 entry->action, entry->flags, entry->keyCode, entry->scanCode, entry->metaState,
Jeff Browne46a0a42010-11-02 17:58:22 -0700782 entry->repeatCount, entry->downTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700783#endif
784}
785
786bool InputDispatcher::dispatchMotionLocked(
Jeff Browne20c9e02010-10-11 14:20:19 -0700787 nsecs_t currentTime, MotionEntry* entry, DropReason* dropReason, nsecs_t* nextWakeupTime) {
Jeff Browne46a0a42010-11-02 17:58:22 -0700788 // Preprocessing.
789 if (! entry->dispatchInProgress) {
790 entry->dispatchInProgress = true;
791 resetTargetsLocked();
792
793 logOutboundMotionDetailsLocked("dispatchMotion - ", entry);
794 }
795
Jeff Brown54a18252010-09-16 14:07:33 -0700796 // Clean up if dropping the event.
Jeff Browne20c9e02010-10-11 14:20:19 -0700797 if (*dropReason != DROP_REASON_NOT_DROPPED) {
Jeff Brown54a18252010-09-16 14:07:33 -0700798 resetTargetsLocked();
Jeff Brown3122e442010-10-11 23:32:49 -0700799 setInjectionResultLocked(entry, *dropReason == DROP_REASON_POLICY
800 ? INPUT_EVENT_INJECTION_SUCCEEDED : INPUT_EVENT_INJECTION_FAILED);
Jeff Brown54a18252010-09-16 14:07:33 -0700801 return true;
802 }
803
Jeff Brownb88102f2010-09-08 11:49:43 -0700804 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
805
806 // Identify targets.
Jeff Browncc0c1592011-02-19 05:07:28 -0800807 bool conflictingPointerActions = false;
Jeff Brownb88102f2010-09-08 11:49:43 -0700808 if (! mCurrentInputTargetsValid) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700809 int32_t injectionResult;
810 if (isPointerEvent) {
811 // Pointer event. (eg. touchscreen)
Jeff Brown01ce2e92010-09-26 22:20:12 -0700812 injectionResult = findTouchedWindowTargetsLocked(currentTime,
Jeff Brown3241b6b2012-02-03 15:08:02 -0800813 entry, nextWakeupTime, &conflictingPointerActions);
Jeff Brownb88102f2010-09-08 11:49:43 -0700814 } else {
815 // Non touch event. (eg. trackball)
Jeff Brown01ce2e92010-09-26 22:20:12 -0700816 injectionResult = findFocusedWindowTargetsLocked(currentTime,
817 entry, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700818 }
819 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
820 return false;
821 }
822
823 setInjectionResultLocked(entry, injectionResult);
824 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
825 return true;
826 }
827
828 addMonitoringTargetsLocked();
Jeff Brown01ce2e92010-09-26 22:20:12 -0700829 commitTargetsLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -0700830 }
831
832 // Dispatch the motion.
Jeff Browncc0c1592011-02-19 05:07:28 -0800833 if (conflictingPointerActions) {
Jeff Brownda3d5a92011-03-29 15:11:34 -0700834 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
835 "conflicting pointer actions");
836 synthesizeCancelationEventsForAllConnectionsLocked(options);
Jeff Browncc0c1592011-02-19 05:07:28 -0800837 }
Jeff Brown3241b6b2012-02-03 15:08:02 -0800838 dispatchEventToCurrentInputTargetsLocked(currentTime, entry);
Jeff Brownb88102f2010-09-08 11:49:43 -0700839 return true;
840}
841
842
843void InputDispatcher::logOutboundMotionDetailsLocked(const char* prefix, const MotionEntry* entry) {
844#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +0000845 ALOGD("%seventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, "
Jeff Brown85a31762010-09-01 17:01:00 -0700846 "action=0x%x, flags=0x%x, "
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700847 "metaState=0x%x, buttonState=0x%x, "
848 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%lld",
Jeff Brownb88102f2010-09-08 11:49:43 -0700849 prefix,
Jeff Brown85a31762010-09-01 17:01:00 -0700850 entry->eventTime, entry->deviceId, entry->source, entry->policyFlags,
851 entry->action, entry->flags,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700852 entry->metaState, entry->buttonState,
853 entry->edgeFlags, entry->xPrecision, entry->yPrecision,
Jeff Brown46b9ac02010-04-22 18:58:52 -0700854 entry->downTime);
855
Jeff Brown46b9ac02010-04-22 18:58:52 -0700856 for (uint32_t i = 0; i < entry->pointerCount; i++) {
Steve Block5baa3a62011-12-20 16:23:08 +0000857 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700858 "x=%f, y=%f, pressure=%f, size=%f, "
Jeff Brown85a31762010-09-01 17:01:00 -0700859 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
Jeff Brown8d608662010-08-30 03:02:23 -0700860 "orientation=%f",
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700861 i, entry->pointerProperties[i].id,
862 entry->pointerProperties[i].toolType,
Jeff Brown3241b6b2012-02-03 15:08:02 -0800863 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
864 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
865 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
866 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
867 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
868 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
869 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
870 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
871 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Jeff Brown46b9ac02010-04-22 18:58:52 -0700872 }
873#endif
Jeff Brown46b9ac02010-04-22 18:58:52 -0700874}
875
876void InputDispatcher::dispatchEventToCurrentInputTargetsLocked(nsecs_t currentTime,
Jeff Brown3241b6b2012-02-03 15:08:02 -0800877 EventEntry* eventEntry) {
Jeff Brown46b9ac02010-04-22 18:58:52 -0700878#if DEBUG_DISPATCH_CYCLE
Jeff Brown3241b6b2012-02-03 15:08:02 -0800879 ALOGD("dispatchEventToCurrentInputTargets");
Jeff Brown46b9ac02010-04-22 18:58:52 -0700880#endif
881
Steve Blockec193de2012-01-09 18:35:44 +0000882 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
Jeff Brown9c3cda02010-06-15 01:31:58 -0700883
Jeff Browne2fe69e2010-10-18 13:21:23 -0700884 pokeUserActivityLocked(eventEntry);
885
Jeff Brown46b9ac02010-04-22 18:58:52 -0700886 for (size_t i = 0; i < mCurrentInputTargets.size(); i++) {
887 const InputTarget& inputTarget = mCurrentInputTargets.itemAt(i);
888
Jeff Brown519e0242010-09-15 15:18:56 -0700889 ssize_t connectionIndex = getConnectionIndexLocked(inputTarget.inputChannel);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700890 if (connectionIndex >= 0) {
891 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
Jeff Brown3241b6b2012-02-03 15:08:02 -0800892 prepareDispatchCycleLocked(currentTime, connection, eventEntry, &inputTarget);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700893 } else {
Jeff Brownb6997262010-10-08 22:31:17 -0700894#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +0000895 ALOGD("Dropping event delivery to target with channel '%s' because it "
Jeff Brownb6997262010-10-08 22:31:17 -0700896 "is no longer registered with the input dispatcher.",
Jeff Brown46b9ac02010-04-22 18:58:52 -0700897 inputTarget.inputChannel->getName().string());
Jeff Brownb6997262010-10-08 22:31:17 -0700898#endif
Jeff Brown46b9ac02010-04-22 18:58:52 -0700899 }
900 }
901}
902
Jeff Brown54a18252010-09-16 14:07:33 -0700903void InputDispatcher::resetTargetsLocked() {
Jeff Brownb88102f2010-09-08 11:49:43 -0700904 mCurrentInputTargetsValid = false;
905 mCurrentInputTargets.clear();
Jeff Brown5ea29ab2011-07-27 11:50:51 -0700906 resetANRTimeoutsLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -0700907}
908
Jeff Brown01ce2e92010-09-26 22:20:12 -0700909void InputDispatcher::commitTargetsLocked() {
Jeff Brownb88102f2010-09-08 11:49:43 -0700910 mCurrentInputTargetsValid = true;
911}
912
913int32_t InputDispatcher::handleTargetsNotReadyLocked(nsecs_t currentTime,
Jeff Brown9302c872011-07-13 22:51:29 -0700914 const EventEntry* entry,
915 const sp<InputApplicationHandle>& applicationHandle,
916 const sp<InputWindowHandle>& windowHandle,
Jeff Brownb88102f2010-09-08 11:49:43 -0700917 nsecs_t* nextWakeupTime) {
Jeff Brown9302c872011-07-13 22:51:29 -0700918 if (applicationHandle == NULL && windowHandle == NULL) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700919 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY) {
920#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +0000921 ALOGD("Waiting for system to become ready for input.");
Jeff Brownb88102f2010-09-08 11:49:43 -0700922#endif
923 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY;
924 mInputTargetWaitStartTime = currentTime;
925 mInputTargetWaitTimeoutTime = LONG_LONG_MAX;
926 mInputTargetWaitTimeoutExpired = false;
Jeff Brown9302c872011-07-13 22:51:29 -0700927 mInputTargetWaitApplicationHandle.clear();
Jeff Brownb88102f2010-09-08 11:49:43 -0700928 }
929 } else {
930 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
931#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +0000932 ALOGD("Waiting for application to become ready for input: %s",
Jeff Brown9302c872011-07-13 22:51:29 -0700933 getApplicationWindowLabelLocked(applicationHandle, windowHandle).string());
Jeff Brownb88102f2010-09-08 11:49:43 -0700934#endif
Jeff Browncc4f7db2011-08-30 20:34:48 -0700935 nsecs_t timeout;
936 if (windowHandle != NULL) {
937 timeout = windowHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
938 } else if (applicationHandle != NULL) {
939 timeout = applicationHandle->getDispatchingTimeout(
940 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
941 } else {
942 timeout = DEFAULT_INPUT_DISPATCHING_TIMEOUT;
943 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700944
945 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY;
946 mInputTargetWaitStartTime = currentTime;
947 mInputTargetWaitTimeoutTime = currentTime + timeout;
948 mInputTargetWaitTimeoutExpired = false;
Jeff Brown9302c872011-07-13 22:51:29 -0700949 mInputTargetWaitApplicationHandle.clear();
Jeff Brown928e0542011-01-10 11:17:36 -0800950
Jeff Brown9302c872011-07-13 22:51:29 -0700951 if (windowHandle != NULL) {
952 mInputTargetWaitApplicationHandle = windowHandle->inputApplicationHandle;
Jeff Brown928e0542011-01-10 11:17:36 -0800953 }
Jeff Brown9302c872011-07-13 22:51:29 -0700954 if (mInputTargetWaitApplicationHandle == NULL && applicationHandle != NULL) {
955 mInputTargetWaitApplicationHandle = applicationHandle;
Jeff Brown928e0542011-01-10 11:17:36 -0800956 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700957 }
958 }
959
960 if (mInputTargetWaitTimeoutExpired) {
961 return INPUT_EVENT_INJECTION_TIMED_OUT;
962 }
963
964 if (currentTime >= mInputTargetWaitTimeoutTime) {
Jeff Brown9302c872011-07-13 22:51:29 -0700965 onANRLocked(currentTime, applicationHandle, windowHandle,
966 entry->eventTime, mInputTargetWaitStartTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700967
968 // Force poll loop to wake up immediately on next iteration once we get the
969 // ANR response back from the policy.
970 *nextWakeupTime = LONG_LONG_MIN;
971 return INPUT_EVENT_INJECTION_PENDING;
972 } else {
973 // Force poll loop to wake up when timeout is due.
974 if (mInputTargetWaitTimeoutTime < *nextWakeupTime) {
975 *nextWakeupTime = mInputTargetWaitTimeoutTime;
976 }
977 return INPUT_EVENT_INJECTION_PENDING;
978 }
979}
980
Jeff Brown519e0242010-09-15 15:18:56 -0700981void InputDispatcher::resumeAfterTargetsNotReadyTimeoutLocked(nsecs_t newTimeout,
982 const sp<InputChannel>& inputChannel) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700983 if (newTimeout > 0) {
984 // Extend the timeout.
985 mInputTargetWaitTimeoutTime = now() + newTimeout;
986 } else {
987 // Give up.
988 mInputTargetWaitTimeoutExpired = true;
Jeff Brown519e0242010-09-15 15:18:56 -0700989
Jeff Brown01ce2e92010-09-26 22:20:12 -0700990 // Release the touch targets.
991 mTouchState.reset();
Jeff Brown2a95c2a2010-09-16 12:31:46 -0700992
Jeff Brown519e0242010-09-15 15:18:56 -0700993 // Input state will not be realistic. Mark it out of sync.
Jeff Browndc3e0052010-09-16 11:02:16 -0700994 if (inputChannel.get()) {
995 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
996 if (connectionIndex >= 0) {
997 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
Jeff Brown00045a72010-12-09 18:10:30 -0800998 if (connection->status == Connection::STATUS_NORMAL) {
Jeff Brownda3d5a92011-03-29 15:11:34 -0700999 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
Jeff Brown00045a72010-12-09 18:10:30 -08001000 "application not responding");
Jeff Brownda3d5a92011-03-29 15:11:34 -07001001 synthesizeCancelationEventsForConnectionLocked(connection, options);
Jeff Brown00045a72010-12-09 18:10:30 -08001002 }
Jeff Browndc3e0052010-09-16 11:02:16 -07001003 }
Jeff Brown519e0242010-09-15 15:18:56 -07001004 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001005 }
1006}
1007
Jeff Brown519e0242010-09-15 15:18:56 -07001008nsecs_t InputDispatcher::getTimeSpentWaitingForApplicationLocked(
Jeff Brownb88102f2010-09-08 11:49:43 -07001009 nsecs_t currentTime) {
1010 if (mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
1011 return currentTime - mInputTargetWaitStartTime;
1012 }
1013 return 0;
1014}
1015
1016void InputDispatcher::resetANRTimeoutsLocked() {
1017#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001018 ALOGD("Resetting ANR timeouts.");
Jeff Brownb88102f2010-09-08 11:49:43 -07001019#endif
1020
Jeff Brownb88102f2010-09-08 11:49:43 -07001021 // Reset input target wait timeout.
1022 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_NONE;
Jeff Brown5ea29ab2011-07-27 11:50:51 -07001023 mInputTargetWaitApplicationHandle.clear();
Jeff Brownb88102f2010-09-08 11:49:43 -07001024}
1025
Jeff Brown01ce2e92010-09-26 22:20:12 -07001026int32_t InputDispatcher::findFocusedWindowTargetsLocked(nsecs_t currentTime,
1027 const EventEntry* entry, nsecs_t* nextWakeupTime) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001028 mCurrentInputTargets.clear();
1029
1030 int32_t injectionResult;
1031
1032 // If there is no currently focused window and no focused application
1033 // then drop the event.
Jeff Brown9302c872011-07-13 22:51:29 -07001034 if (mFocusedWindowHandle == NULL) {
1035 if (mFocusedApplicationHandle != NULL) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001036#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001037 ALOGD("Waiting because there is no focused window but there is a "
Jeff Brown519e0242010-09-15 15:18:56 -07001038 "focused application that may eventually add a window: %s.",
Jeff Brown9302c872011-07-13 22:51:29 -07001039 getApplicationWindowLabelLocked(mFocusedApplicationHandle, NULL).string());
Jeff Brownb88102f2010-09-08 11:49:43 -07001040#endif
1041 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brown9302c872011-07-13 22:51:29 -07001042 mFocusedApplicationHandle, NULL, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -07001043 goto Unresponsive;
1044 }
1045
Steve Block6215d3f2012-01-04 20:05:49 +00001046 ALOGI("Dropping event because there is no focused window or focused application.");
Jeff Brownb88102f2010-09-08 11:49:43 -07001047 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1048 goto Failed;
1049 }
1050
1051 // Check permissions.
Jeff Brown9302c872011-07-13 22:51:29 -07001052 if (! checkInjectionPermission(mFocusedWindowHandle, entry->injectionState)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001053 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1054 goto Failed;
1055 }
1056
1057 // If the currently focused window is paused then keep waiting.
Jeff Browncc4f7db2011-08-30 20:34:48 -07001058 if (mFocusedWindowHandle->getInfo()->paused) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001059#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001060 ALOGD("Waiting because focused window is paused.");
Jeff Brownb88102f2010-09-08 11:49:43 -07001061#endif
1062 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brown9302c872011-07-13 22:51:29 -07001063 mFocusedApplicationHandle, mFocusedWindowHandle, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -07001064 goto Unresponsive;
1065 }
1066
Jeff Brown519e0242010-09-15 15:18:56 -07001067 // If the currently focused window is still working on previous events then keep waiting.
Jeff Brown9302c872011-07-13 22:51:29 -07001068 if (! isWindowFinishedWithPreviousInputLocked(mFocusedWindowHandle)) {
Jeff Brown519e0242010-09-15 15:18:56 -07001069#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001070 ALOGD("Waiting because focused window still processing previous input.");
Jeff Brown519e0242010-09-15 15:18:56 -07001071#endif
1072 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brown9302c872011-07-13 22:51:29 -07001073 mFocusedApplicationHandle, mFocusedWindowHandle, nextWakeupTime);
Jeff Brown519e0242010-09-15 15:18:56 -07001074 goto Unresponsive;
1075 }
1076
Jeff Brownb88102f2010-09-08 11:49:43 -07001077 // Success! Output targets.
1078 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
Jeff Brown9302c872011-07-13 22:51:29 -07001079 addWindowTargetLocked(mFocusedWindowHandle,
Jeff Browna032cc02011-03-07 16:56:21 -08001080 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS, BitSet32(0));
Jeff Brownb88102f2010-09-08 11:49:43 -07001081
1082 // Done.
1083Failed:
1084Unresponsive:
Jeff Brown519e0242010-09-15 15:18:56 -07001085 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
1086 updateDispatchStatisticsLocked(currentTime, entry,
1087 injectionResult, timeSpentWaitingForApplication);
Jeff Brownb88102f2010-09-08 11:49:43 -07001088#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001089 ALOGD("findFocusedWindow finished: injectionResult=%d, "
Jeff Brown519e0242010-09-15 15:18:56 -07001090 "timeSpendWaitingForApplication=%0.1fms",
1091 injectionResult, timeSpentWaitingForApplication / 1000000.0);
Jeff Brownb88102f2010-09-08 11:49:43 -07001092#endif
1093 return injectionResult;
1094}
1095
Jeff Brown01ce2e92010-09-26 22:20:12 -07001096int32_t InputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001097 const MotionEntry* entry, nsecs_t* nextWakeupTime, bool* outConflictingPointerActions) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001098 enum InjectionPermission {
1099 INJECTION_PERMISSION_UNKNOWN,
1100 INJECTION_PERMISSION_GRANTED,
1101 INJECTION_PERMISSION_DENIED
1102 };
1103
Jeff Brownb88102f2010-09-08 11:49:43 -07001104 mCurrentInputTargets.clear();
1105
1106 nsecs_t startTime = now();
1107
1108 // For security reasons, we defer updating the touch state until we are sure that
1109 // event injection will be allowed.
1110 //
1111 // FIXME In the original code, screenWasOff could never be set to true.
1112 // The reason is that the POLICY_FLAG_WOKE_HERE
1113 // and POLICY_FLAG_BRIGHT_HERE flags were set only when preprocessing raw
1114 // EV_KEY, EV_REL and EV_ABS events. As it happens, the touch event was
1115 // actually enqueued using the policyFlags that appeared in the final EV_SYN
1116 // events upon which no preprocessing took place. So policyFlags was always 0.
1117 // In the new native input dispatcher we're a bit more careful about event
1118 // preprocessing so the touches we receive can actually have non-zero policyFlags.
1119 // Unfortunately we obtain undesirable behavior.
1120 //
1121 // Here's what happens:
1122 //
1123 // When the device dims in anticipation of going to sleep, touches
1124 // in windows which have FLAG_TOUCHABLE_WHEN_WAKING cause
1125 // the device to brighten and reset the user activity timer.
1126 // Touches on other windows (such as the launcher window)
1127 // are dropped. Then after a moment, the device goes to sleep. Oops.
1128 //
1129 // Also notice how screenWasOff was being initialized using POLICY_FLAG_BRIGHT_HERE
1130 // instead of POLICY_FLAG_WOKE_HERE...
1131 //
1132 bool screenWasOff = false; // original policy: policyFlags & POLICY_FLAG_BRIGHT_HERE;
1133
1134 int32_t action = entry->action;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001135 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Jeff Brownb88102f2010-09-08 11:49:43 -07001136
1137 // Update the touch state as needed based on the properties of the touch event.
Jeff Brown01ce2e92010-09-26 22:20:12 -07001138 int32_t injectionResult = INPUT_EVENT_INJECTION_PENDING;
1139 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
Jeff Brown9302c872011-07-13 22:51:29 -07001140 sp<InputWindowHandle> newHoverWindowHandle;
Jeff Browncc0c1592011-02-19 05:07:28 -08001141
1142 bool isSplit = mTouchState.split;
Jeff Brown2717eff2011-06-30 23:53:07 -07001143 bool switchedDevice = mTouchState.deviceId >= 0
1144 && (mTouchState.deviceId != entry->deviceId
1145 || mTouchState.source != entry->source);
Jeff Browna032cc02011-03-07 16:56:21 -08001146 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE
1147 || maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER
1148 || maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1149 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN
1150 || maskedAction == AMOTION_EVENT_ACTION_SCROLL
1151 || isHoverAction);
Jeff Brown81346812011-06-28 20:08:48 -07001152 bool wrongDevice = false;
Jeff Browna032cc02011-03-07 16:56:21 -08001153 if (newGesture) {
Jeff Browncc0c1592011-02-19 05:07:28 -08001154 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Jeff Brown81346812011-06-28 20:08:48 -07001155 if (switchedDevice && mTouchState.down && !down) {
1156#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001157 ALOGD("Dropping event because a pointer for a different device is already down.");
Jeff Brown81346812011-06-28 20:08:48 -07001158#endif
Jeff Browncc0c1592011-02-19 05:07:28 -08001159 mTempTouchState.copyFrom(mTouchState);
Jeff Brown81346812011-06-28 20:08:48 -07001160 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1161 switchedDevice = false;
1162 wrongDevice = true;
1163 goto Failed;
Jeff Browncc0c1592011-02-19 05:07:28 -08001164 }
Jeff Brown81346812011-06-28 20:08:48 -07001165 mTempTouchState.reset();
1166 mTempTouchState.down = down;
1167 mTempTouchState.deviceId = entry->deviceId;
1168 mTempTouchState.source = entry->source;
1169 isSplit = false;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001170 } else {
1171 mTempTouchState.copyFrom(mTouchState);
Jeff Browncc0c1592011-02-19 05:07:28 -08001172 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001173
Jeff Browna032cc02011-03-07 16:56:21 -08001174 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
Jeff Brown33bbfd22011-02-24 20:55:35 -08001175 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
Jeff Brownb88102f2010-09-08 11:49:43 -07001176
Jeff Brown01ce2e92010-09-26 22:20:12 -07001177 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Jeff Brown3241b6b2012-02-03 15:08:02 -08001178 int32_t x = int32_t(entry->pointerCoords[pointerIndex].
Jeff Brownebbd5d12011-02-17 13:01:34 -08001179 getAxisValue(AMOTION_EVENT_AXIS_X));
Jeff Brown3241b6b2012-02-03 15:08:02 -08001180 int32_t y = int32_t(entry->pointerCoords[pointerIndex].
Jeff Brownebbd5d12011-02-17 13:01:34 -08001181 getAxisValue(AMOTION_EVENT_AXIS_Y));
Jeff Brown9302c872011-07-13 22:51:29 -07001182 sp<InputWindowHandle> newTouchedWindowHandle;
1183 sp<InputWindowHandle> topErrorWindowHandle;
Jeff Browna032cc02011-03-07 16:56:21 -08001184 bool isTouchModal = false;
Jeff Brownb88102f2010-09-08 11:49:43 -07001185
1186 // Traverse windows from front to back to find touched window and outside targets.
Jeff Brown9302c872011-07-13 22:51:29 -07001187 size_t numWindows = mWindowHandles.size();
Jeff Brownb88102f2010-09-08 11:49:43 -07001188 for (size_t i = 0; i < numWindows; i++) {
Jeff Brown9302c872011-07-13 22:51:29 -07001189 sp<InputWindowHandle> windowHandle = mWindowHandles.itemAt(i);
Jeff Browncc4f7db2011-08-30 20:34:48 -07001190 const InputWindowInfo* windowInfo = windowHandle->getInfo();
1191 int32_t flags = windowInfo->layoutParamsFlags;
Jeff Brownb88102f2010-09-08 11:49:43 -07001192
Jeff Browncc4f7db2011-08-30 20:34:48 -07001193 if (flags & InputWindowInfo::FLAG_SYSTEM_ERROR) {
Jeff Brown9302c872011-07-13 22:51:29 -07001194 if (topErrorWindowHandle == NULL) {
1195 topErrorWindowHandle = windowHandle;
Jeff Brownb88102f2010-09-08 11:49:43 -07001196 }
1197 }
1198
Jeff Browncc4f7db2011-08-30 20:34:48 -07001199 if (windowInfo->visible) {
1200 if (! (flags & InputWindowInfo::FLAG_NOT_TOUCHABLE)) {
1201 isTouchModal = (flags & (InputWindowInfo::FLAG_NOT_FOCUSABLE
1202 | InputWindowInfo::FLAG_NOT_TOUCH_MODAL)) == 0;
1203 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
Jeff Brown9302c872011-07-13 22:51:29 -07001204 if (! screenWasOff
Jeff Browncc4f7db2011-08-30 20:34:48 -07001205 || (flags & InputWindowInfo::FLAG_TOUCHABLE_WHEN_WAKING)) {
Jeff Brown9302c872011-07-13 22:51:29 -07001206 newTouchedWindowHandle = windowHandle;
Jeff Brownb88102f2010-09-08 11:49:43 -07001207 }
1208 break; // found touched window, exit window loop
1209 }
1210 }
1211
Jeff Brown01ce2e92010-09-26 22:20:12 -07001212 if (maskedAction == AMOTION_EVENT_ACTION_DOWN
Jeff Browncc4f7db2011-08-30 20:34:48 -07001213 && (flags & InputWindowInfo::FLAG_WATCH_OUTSIDE_TOUCH)) {
Jeff Browna032cc02011-03-07 16:56:21 -08001214 int32_t outsideTargetFlags = InputTarget::FLAG_DISPATCH_AS_OUTSIDE;
Jeff Brown9302c872011-07-13 22:51:29 -07001215 if (isWindowObscuredAtPointLocked(windowHandle, x, y)) {
Jeff Brown19dfc832010-10-05 12:26:23 -07001216 outsideTargetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1217 }
1218
Jeff Brown9302c872011-07-13 22:51:29 -07001219 mTempTouchState.addOrUpdateWindow(
1220 windowHandle, outsideTargetFlags, BitSet32(0));
Jeff Brownb88102f2010-09-08 11:49:43 -07001221 }
1222 }
1223 }
1224
1225 // If there is an error window but it is not taking focus (typically because
1226 // it is invisible) then wait for it. Any other focused window may in
1227 // fact be in ANR state.
Jeff Brown9302c872011-07-13 22:51:29 -07001228 if (topErrorWindowHandle != NULL && newTouchedWindowHandle != topErrorWindowHandle) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001229#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001230 ALOGD("Waiting because system error window is pending.");
Jeff Brownb88102f2010-09-08 11:49:43 -07001231#endif
1232 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
1233 NULL, NULL, nextWakeupTime);
1234 injectionPermission = INJECTION_PERMISSION_UNKNOWN;
1235 goto Unresponsive;
1236 }
1237
Jeff Brown01ce2e92010-09-26 22:20:12 -07001238 // Figure out whether splitting will be allowed for this window.
Jeff Browncc4f7db2011-08-30 20:34:48 -07001239 if (newTouchedWindowHandle != NULL
1240 && newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001241 // New window supports splitting.
1242 isSplit = true;
1243 } else if (isSplit) {
1244 // New window does not support splitting but we have already split events.
1245 // Assign the pointer to the first foreground window we find.
1246 // (May be NULL which is why we put this code block before the next check.)
Jeff Brown9302c872011-07-13 22:51:29 -07001247 newTouchedWindowHandle = mTempTouchState.getFirstForegroundWindowHandle();
Jeff Brown01ce2e92010-09-26 22:20:12 -07001248 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001249
Jeff Brownb88102f2010-09-08 11:49:43 -07001250 // If we did not find a touched window then fail.
Jeff Brown9302c872011-07-13 22:51:29 -07001251 if (newTouchedWindowHandle == NULL) {
1252 if (mFocusedApplicationHandle != NULL) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001253#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001254 ALOGD("Waiting because there is no touched window but there is a "
Jeff Brown519e0242010-09-15 15:18:56 -07001255 "focused application that may eventually add a new window: %s.",
Jeff Brown9302c872011-07-13 22:51:29 -07001256 getApplicationWindowLabelLocked(mFocusedApplicationHandle, NULL).string());
Jeff Brownb88102f2010-09-08 11:49:43 -07001257#endif
1258 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brown9302c872011-07-13 22:51:29 -07001259 mFocusedApplicationHandle, NULL, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -07001260 goto Unresponsive;
1261 }
1262
Steve Block6215d3f2012-01-04 20:05:49 +00001263 ALOGI("Dropping event because there is no touched window or focused application.");
Jeff Brownb88102f2010-09-08 11:49:43 -07001264 injectionResult = INPUT_EVENT_INJECTION_FAILED;
Jeff Brownb88102f2010-09-08 11:49:43 -07001265 goto Failed;
1266 }
1267
Jeff Brown19dfc832010-10-05 12:26:23 -07001268 // Set target flags.
Jeff Browna032cc02011-03-07 16:56:21 -08001269 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
Jeff Brown19dfc832010-10-05 12:26:23 -07001270 if (isSplit) {
1271 targetFlags |= InputTarget::FLAG_SPLIT;
1272 }
Jeff Brown9302c872011-07-13 22:51:29 -07001273 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
Jeff Brown19dfc832010-10-05 12:26:23 -07001274 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1275 }
1276
Jeff Browna032cc02011-03-07 16:56:21 -08001277 // Update hover state.
1278 if (isHoverAction) {
Jeff Brown9302c872011-07-13 22:51:29 -07001279 newHoverWindowHandle = newTouchedWindowHandle;
Jeff Browna032cc02011-03-07 16:56:21 -08001280 } else if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
Jeff Brown9302c872011-07-13 22:51:29 -07001281 newHoverWindowHandle = mLastHoverWindowHandle;
Jeff Browna032cc02011-03-07 16:56:21 -08001282 }
1283
Jeff Brown01ce2e92010-09-26 22:20:12 -07001284 // Update the temporary touch state.
1285 BitSet32 pointerIds;
1286 if (isSplit) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07001287 uint32_t pointerId = entry->pointerProperties[pointerIndex].id;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001288 pointerIds.markBit(pointerId);
Jeff Brownb88102f2010-09-08 11:49:43 -07001289 }
Jeff Brown9302c872011-07-13 22:51:29 -07001290 mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Jeff Brownb88102f2010-09-08 11:49:43 -07001291 } else {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001292 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
Jeff Brownb88102f2010-09-08 11:49:43 -07001293
1294 // If the pointer is not currently down, then ignore the event.
Jeff Brown01ce2e92010-09-26 22:20:12 -07001295 if (! mTempTouchState.down) {
Jeff Browna2cc28d2011-03-25 11:58:46 -07001296#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001297 ALOGD("Dropping event because the pointer is not down or we previously "
Jeff Brown76860e32010-10-25 17:37:46 -07001298 "dropped the pointer down event.");
1299#endif
Jeff Brownb88102f2010-09-08 11:49:43 -07001300 injectionResult = INPUT_EVENT_INJECTION_FAILED;
Jeff Brownb88102f2010-09-08 11:49:43 -07001301 goto Failed;
1302 }
Jeff Brown98db5fa2011-06-08 15:37:10 -07001303
1304 // Check whether touches should slip outside of the current foreground window.
1305 if (maskedAction == AMOTION_EVENT_ACTION_MOVE
1306 && entry->pointerCount == 1
1307 && mTempTouchState.isSlippery()) {
Jeff Brown3241b6b2012-02-03 15:08:02 -08001308 int32_t x = int32_t(entry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
1309 int32_t y = int32_t(entry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Jeff Brown98db5fa2011-06-08 15:37:10 -07001310
Jeff Brown9302c872011-07-13 22:51:29 -07001311 sp<InputWindowHandle> oldTouchedWindowHandle =
1312 mTempTouchState.getFirstForegroundWindowHandle();
1313 sp<InputWindowHandle> newTouchedWindowHandle = findTouchedWindowAtLocked(x, y);
1314 if (oldTouchedWindowHandle != newTouchedWindowHandle
1315 && newTouchedWindowHandle != NULL) {
Jeff Brown98db5fa2011-06-08 15:37:10 -07001316#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001317 ALOGD("Touch is slipping out of window %s into window %s.",
Jeff Browncc4f7db2011-08-30 20:34:48 -07001318 oldTouchedWindowHandle->getName().string(),
1319 newTouchedWindowHandle->getName().string());
Jeff Brown98db5fa2011-06-08 15:37:10 -07001320#endif
1321 // Make a slippery exit from the old window.
Jeff Brown9302c872011-07-13 22:51:29 -07001322 mTempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
Jeff Brown98db5fa2011-06-08 15:37:10 -07001323 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT, BitSet32(0));
1324
1325 // Make a slippery entrance into the new window.
Jeff Browncc4f7db2011-08-30 20:34:48 -07001326 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Jeff Brown98db5fa2011-06-08 15:37:10 -07001327 isSplit = true;
1328 }
1329
1330 int32_t targetFlags = InputTarget::FLAG_FOREGROUND
1331 | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
1332 if (isSplit) {
1333 targetFlags |= InputTarget::FLAG_SPLIT;
1334 }
Jeff Brown9302c872011-07-13 22:51:29 -07001335 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
Jeff Brown98db5fa2011-06-08 15:37:10 -07001336 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1337 }
1338
1339 BitSet32 pointerIds;
1340 if (isSplit) {
1341 pointerIds.markBit(entry->pointerProperties[0].id);
1342 }
Jeff Brown9302c872011-07-13 22:51:29 -07001343 mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Jeff Brown98db5fa2011-06-08 15:37:10 -07001344 }
1345 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001346 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001347
Jeff Brown9302c872011-07-13 22:51:29 -07001348 if (newHoverWindowHandle != mLastHoverWindowHandle) {
Jeff Browna032cc02011-03-07 16:56:21 -08001349 // Let the previous window know that the hover sequence is over.
Jeff Brown9302c872011-07-13 22:51:29 -07001350 if (mLastHoverWindowHandle != NULL) {
Jeff Browna032cc02011-03-07 16:56:21 -08001351#if DEBUG_HOVER
Steve Block5baa3a62011-12-20 16:23:08 +00001352 ALOGD("Sending hover exit event to window %s.",
Jeff Browncc4f7db2011-08-30 20:34:48 -07001353 mLastHoverWindowHandle->getName().string());
Jeff Browna032cc02011-03-07 16:56:21 -08001354#endif
Jeff Brown9302c872011-07-13 22:51:29 -07001355 mTempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
Jeff Browna032cc02011-03-07 16:56:21 -08001356 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
1357 }
1358
1359 // Let the new window know that the hover sequence is starting.
Jeff Brown9302c872011-07-13 22:51:29 -07001360 if (newHoverWindowHandle != NULL) {
Jeff Browna032cc02011-03-07 16:56:21 -08001361#if DEBUG_HOVER
Steve Block5baa3a62011-12-20 16:23:08 +00001362 ALOGD("Sending hover enter event to window %s.",
Jeff Browncc4f7db2011-08-30 20:34:48 -07001363 newHoverWindowHandle->getName().string());
Jeff Browna032cc02011-03-07 16:56:21 -08001364#endif
Jeff Brown9302c872011-07-13 22:51:29 -07001365 mTempTouchState.addOrUpdateWindow(newHoverWindowHandle,
Jeff Browna032cc02011-03-07 16:56:21 -08001366 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER, BitSet32(0));
1367 }
1368 }
1369
Jeff Brown01ce2e92010-09-26 22:20:12 -07001370 // Check permission to inject into all touched foreground windows and ensure there
1371 // is at least one touched foreground window.
1372 {
1373 bool haveForegroundWindow = false;
1374 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1375 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1376 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1377 haveForegroundWindow = true;
Jeff Brown9302c872011-07-13 22:51:29 -07001378 if (! checkInjectionPermission(touchedWindow.windowHandle,
1379 entry->injectionState)) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001380 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1381 injectionPermission = INJECTION_PERMISSION_DENIED;
1382 goto Failed;
1383 }
1384 }
1385 }
1386 if (! haveForegroundWindow) {
Jeff Browna2cc28d2011-03-25 11:58:46 -07001387#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001388 ALOGD("Dropping event because there is no touched foreground window to receive it.");
Jeff Brownb88102f2010-09-08 11:49:43 -07001389#endif
1390 injectionResult = INPUT_EVENT_INJECTION_FAILED;
Jeff Brownb88102f2010-09-08 11:49:43 -07001391 goto Failed;
1392 }
1393
Jeff Brown01ce2e92010-09-26 22:20:12 -07001394 // Permission granted to injection into all touched foreground windows.
1395 injectionPermission = INJECTION_PERMISSION_GRANTED;
1396 }
Jeff Brown519e0242010-09-15 15:18:56 -07001397
Kenny Root7a9db182011-06-02 15:16:05 -07001398 // Check whether windows listening for outside touches are owned by the same UID. If it is
1399 // set the policy flag that we will not reveal coordinate information to this window.
1400 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
Jeff Brown9302c872011-07-13 22:51:29 -07001401 sp<InputWindowHandle> foregroundWindowHandle =
1402 mTempTouchState.getFirstForegroundWindowHandle();
Jeff Browncc4f7db2011-08-30 20:34:48 -07001403 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Kenny Root7a9db182011-06-02 15:16:05 -07001404 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1405 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1406 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
Jeff Brown9302c872011-07-13 22:51:29 -07001407 sp<InputWindowHandle> inputWindowHandle = touchedWindow.windowHandle;
Jeff Browncc4f7db2011-08-30 20:34:48 -07001408 if (inputWindowHandle->getInfo()->ownerUid != foregroundWindowUid) {
Jeff Brown9302c872011-07-13 22:51:29 -07001409 mTempTouchState.addOrUpdateWindow(inputWindowHandle,
Kenny Root7a9db182011-06-02 15:16:05 -07001410 InputTarget::FLAG_ZERO_COORDS, BitSet32(0));
1411 }
1412 }
1413 }
1414 }
1415
Jeff Brown01ce2e92010-09-26 22:20:12 -07001416 // Ensure all touched foreground windows are ready for new input.
1417 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1418 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1419 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1420 // If the touched window is paused then keep waiting.
Jeff Browncc4f7db2011-08-30 20:34:48 -07001421 if (touchedWindow.windowHandle->getInfo()->paused) {
Jeff Browna2cc28d2011-03-25 11:58:46 -07001422#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001423 ALOGD("Waiting because touched window is paused.");
Jeff Brown519e0242010-09-15 15:18:56 -07001424#endif
Jeff Brown01ce2e92010-09-26 22:20:12 -07001425 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brown9302c872011-07-13 22:51:29 -07001426 NULL, touchedWindow.windowHandle, nextWakeupTime);
Jeff Brown01ce2e92010-09-26 22:20:12 -07001427 goto Unresponsive;
1428 }
1429
1430 // If the touched window is still working on previous events then keep waiting.
Jeff Brown9302c872011-07-13 22:51:29 -07001431 if (! isWindowFinishedWithPreviousInputLocked(touchedWindow.windowHandle)) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001432#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001433 ALOGD("Waiting because touched window still processing previous input.");
Jeff Brown01ce2e92010-09-26 22:20:12 -07001434#endif
1435 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brown9302c872011-07-13 22:51:29 -07001436 NULL, touchedWindow.windowHandle, nextWakeupTime);
Jeff Brown01ce2e92010-09-26 22:20:12 -07001437 goto Unresponsive;
1438 }
1439 }
1440 }
1441
1442 // If this is the first pointer going down and the touched window has a wallpaper
1443 // then also add the touched wallpaper windows so they are locked in for the duration
1444 // of the touch gesture.
Jeff Brown33bbfd22011-02-24 20:55:35 -08001445 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
1446 // engine only supports touch events. We would need to add a mechanism similar
1447 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
1448 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
Jeff Brown9302c872011-07-13 22:51:29 -07001449 sp<InputWindowHandle> foregroundWindowHandle =
1450 mTempTouchState.getFirstForegroundWindowHandle();
Jeff Browncc4f7db2011-08-30 20:34:48 -07001451 if (foregroundWindowHandle->getInfo()->hasWallpaper) {
Jeff Brown9302c872011-07-13 22:51:29 -07001452 for (size_t i = 0; i < mWindowHandles.size(); i++) {
1453 sp<InputWindowHandle> windowHandle = mWindowHandles.itemAt(i);
Jeff Browncc4f7db2011-08-30 20:34:48 -07001454 if (windowHandle->getInfo()->layoutParamsType
1455 == InputWindowInfo::TYPE_WALLPAPER) {
Jeff Brown9302c872011-07-13 22:51:29 -07001456 mTempTouchState.addOrUpdateWindow(windowHandle,
Jeff Browna032cc02011-03-07 16:56:21 -08001457 InputTarget::FLAG_WINDOW_IS_OBSCURED
1458 | InputTarget::FLAG_DISPATCH_AS_IS,
1459 BitSet32(0));
Jeff Brown01ce2e92010-09-26 22:20:12 -07001460 }
1461 }
1462 }
1463 }
1464
Jeff Brownb88102f2010-09-08 11:49:43 -07001465 // Success! Output targets.
1466 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
Jeff Brownb88102f2010-09-08 11:49:43 -07001467
Jeff Brown01ce2e92010-09-26 22:20:12 -07001468 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1469 const TouchedWindow& touchedWindow = mTempTouchState.windows.itemAt(i);
Jeff Brown9302c872011-07-13 22:51:29 -07001470 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Jeff Brown01ce2e92010-09-26 22:20:12 -07001471 touchedWindow.pointerIds);
Jeff Brownb88102f2010-09-08 11:49:43 -07001472 }
1473
Jeff Browna032cc02011-03-07 16:56:21 -08001474 // Drop the outside or hover touch windows since we will not care about them
1475 // in the next iteration.
1476 mTempTouchState.filterNonAsIsTouchWindows();
Jeff Brown01ce2e92010-09-26 22:20:12 -07001477
Jeff Brownb88102f2010-09-08 11:49:43 -07001478Failed:
1479 // Check injection permission once and for all.
1480 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001481 if (checkInjectionPermission(NULL, entry->injectionState)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001482 injectionPermission = INJECTION_PERMISSION_GRANTED;
1483 } else {
1484 injectionPermission = INJECTION_PERMISSION_DENIED;
1485 }
1486 }
1487
1488 // Update final pieces of touch state if the injector had permission.
1489 if (injectionPermission == INJECTION_PERMISSION_GRANTED) {
Jeff Brown95712852011-01-04 19:41:59 -08001490 if (!wrongDevice) {
Jeff Brown81346812011-06-28 20:08:48 -07001491 if (switchedDevice) {
1492#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001493 ALOGD("Conflicting pointer actions: Switched to a different device.");
Jeff Brown81346812011-06-28 20:08:48 -07001494#endif
1495 *outConflictingPointerActions = true;
1496 }
1497
1498 if (isHoverAction) {
1499 // Started hovering, therefore no longer down.
1500 if (mTouchState.down) {
1501#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001502 ALOGD("Conflicting pointer actions: Hover received while pointer was down.");
Jeff Brown81346812011-06-28 20:08:48 -07001503#endif
1504 *outConflictingPointerActions = true;
1505 }
1506 mTouchState.reset();
1507 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER
1508 || maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
1509 mTouchState.deviceId = entry->deviceId;
1510 mTouchState.source = entry->source;
1511 }
1512 } else if (maskedAction == AMOTION_EVENT_ACTION_UP
1513 || maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Jeff Brown95712852011-01-04 19:41:59 -08001514 // All pointers up or canceled.
Jeff Brown33bbfd22011-02-24 20:55:35 -08001515 mTouchState.reset();
Jeff Brown95712852011-01-04 19:41:59 -08001516 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1517 // First pointer went down.
1518 if (mTouchState.down) {
Jeff Brownb6997262010-10-08 22:31:17 -07001519#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001520 ALOGD("Conflicting pointer actions: Down received while already down.");
Jeff Brownb6997262010-10-08 22:31:17 -07001521#endif
Jeff Brown81346812011-06-28 20:08:48 -07001522 *outConflictingPointerActions = true;
Jeff Brown95712852011-01-04 19:41:59 -08001523 }
Jeff Brown33bbfd22011-02-24 20:55:35 -08001524 mTouchState.copyFrom(mTempTouchState);
Jeff Brown95712852011-01-04 19:41:59 -08001525 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
1526 // One pointer went up.
1527 if (isSplit) {
1528 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07001529 uint32_t pointerId = entry->pointerProperties[pointerIndex].id;
Jeff Brownb88102f2010-09-08 11:49:43 -07001530
Jeff Brown95712852011-01-04 19:41:59 -08001531 for (size_t i = 0; i < mTempTouchState.windows.size(); ) {
1532 TouchedWindow& touchedWindow = mTempTouchState.windows.editItemAt(i);
1533 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
1534 touchedWindow.pointerIds.clearBit(pointerId);
1535 if (touchedWindow.pointerIds.isEmpty()) {
1536 mTempTouchState.windows.removeAt(i);
1537 continue;
1538 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001539 }
Jeff Brown95712852011-01-04 19:41:59 -08001540 i += 1;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001541 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001542 }
Jeff Brown33bbfd22011-02-24 20:55:35 -08001543 mTouchState.copyFrom(mTempTouchState);
1544 } else if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
1545 // Discard temporary touch state since it was only valid for this action.
1546 } else {
1547 // Save changes to touch state as-is for all other actions.
1548 mTouchState.copyFrom(mTempTouchState);
Jeff Brownb88102f2010-09-08 11:49:43 -07001549 }
Jeff Browna032cc02011-03-07 16:56:21 -08001550
1551 // Update hover state.
Jeff Brown9302c872011-07-13 22:51:29 -07001552 mLastHoverWindowHandle = newHoverWindowHandle;
Jeff Brown95712852011-01-04 19:41:59 -08001553 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001554 } else {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001555#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001556 ALOGD("Not updating touch focus because injection was denied.");
Jeff Brown01ce2e92010-09-26 22:20:12 -07001557#endif
Jeff Brownb88102f2010-09-08 11:49:43 -07001558 }
1559
1560Unresponsive:
Jeff Brown120a4592010-10-27 18:43:51 -07001561 // Reset temporary touch state to ensure we release unnecessary references to input channels.
1562 mTempTouchState.reset();
1563
Jeff Brown519e0242010-09-15 15:18:56 -07001564 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
1565 updateDispatchStatisticsLocked(currentTime, entry,
1566 injectionResult, timeSpentWaitingForApplication);
Jeff Brownb88102f2010-09-08 11:49:43 -07001567#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001568 ALOGD("findTouchedWindow finished: injectionResult=%d, injectionPermission=%d, "
Jeff Brown01ce2e92010-09-26 22:20:12 -07001569 "timeSpentWaitingForApplication=%0.1fms",
Jeff Brown519e0242010-09-15 15:18:56 -07001570 injectionResult, injectionPermission, timeSpentWaitingForApplication / 1000000.0);
Jeff Brownb88102f2010-09-08 11:49:43 -07001571#endif
1572 return injectionResult;
1573}
1574
Jeff Brown9302c872011-07-13 22:51:29 -07001575void InputDispatcher::addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
1576 int32_t targetFlags, BitSet32 pointerIds) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001577 mCurrentInputTargets.push();
1578
Jeff Browncc4f7db2011-08-30 20:34:48 -07001579 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Jeff Brownb88102f2010-09-08 11:49:43 -07001580 InputTarget& target = mCurrentInputTargets.editTop();
Jeff Browncc4f7db2011-08-30 20:34:48 -07001581 target.inputChannel = windowInfo->inputChannel;
Jeff Brownb88102f2010-09-08 11:49:43 -07001582 target.flags = targetFlags;
Jeff Browncc4f7db2011-08-30 20:34:48 -07001583 target.xOffset = - windowInfo->frameLeft;
1584 target.yOffset = - windowInfo->frameTop;
1585 target.scaleFactor = windowInfo->scaleFactor;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001586 target.pointerIds = pointerIds;
Jeff Brownb88102f2010-09-08 11:49:43 -07001587}
1588
1589void InputDispatcher::addMonitoringTargetsLocked() {
1590 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
1591 mCurrentInputTargets.push();
1592
1593 InputTarget& target = mCurrentInputTargets.editTop();
1594 target.inputChannel = mMonitoringChannels[i];
Jeff Brownb6110c22011-04-01 16:15:13 -07001595 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
Jeff Brownb88102f2010-09-08 11:49:43 -07001596 target.xOffset = 0;
1597 target.yOffset = 0;
Jeff Brownb6110c22011-04-01 16:15:13 -07001598 target.pointerIds.clear();
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001599 target.scaleFactor = 1.0f;
Jeff Brownb88102f2010-09-08 11:49:43 -07001600 }
1601}
1602
Jeff Brown9302c872011-07-13 22:51:29 -07001603bool InputDispatcher::checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
Jeff Brown01ce2e92010-09-26 22:20:12 -07001604 const InjectionState* injectionState) {
1605 if (injectionState
Jeff Browncc4f7db2011-08-30 20:34:48 -07001606 && (windowHandle == NULL
1607 || windowHandle->getInfo()->ownerUid != injectionState->injectorUid)
Jeff Brownb6997262010-10-08 22:31:17 -07001608 && !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Jeff Brown9302c872011-07-13 22:51:29 -07001609 if (windowHandle != NULL) {
Steve Block8564c8d2012-01-05 23:22:43 +00001610 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
Jeff Brown9302c872011-07-13 22:51:29 -07001611 "owned by uid %d",
Jeff Brownb6997262010-10-08 22:31:17 -07001612 injectionState->injectorPid, injectionState->injectorUid,
Jeff Browncc4f7db2011-08-30 20:34:48 -07001613 windowHandle->getName().string(),
1614 windowHandle->getInfo()->ownerUid);
Jeff Brownb6997262010-10-08 22:31:17 -07001615 } else {
Steve Block8564c8d2012-01-05 23:22:43 +00001616 ALOGW("Permission denied: injecting event from pid %d uid %d",
Jeff Brownb6997262010-10-08 22:31:17 -07001617 injectionState->injectorPid, injectionState->injectorUid);
Jeff Brownb88102f2010-09-08 11:49:43 -07001618 }
Jeff Brownb6997262010-10-08 22:31:17 -07001619 return false;
Jeff Brownb88102f2010-09-08 11:49:43 -07001620 }
1621 return true;
1622}
1623
Jeff Brown19dfc832010-10-05 12:26:23 -07001624bool InputDispatcher::isWindowObscuredAtPointLocked(
Jeff Brown9302c872011-07-13 22:51:29 -07001625 const sp<InputWindowHandle>& windowHandle, int32_t x, int32_t y) const {
1626 size_t numWindows = mWindowHandles.size();
Jeff Brownb88102f2010-09-08 11:49:43 -07001627 for (size_t i = 0; i < numWindows; i++) {
Jeff Brown9302c872011-07-13 22:51:29 -07001628 sp<InputWindowHandle> otherHandle = mWindowHandles.itemAt(i);
1629 if (otherHandle == windowHandle) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001630 break;
1631 }
Jeff Browncc4f7db2011-08-30 20:34:48 -07001632
1633 const InputWindowInfo* otherInfo = otherHandle->getInfo();
1634 if (otherInfo->visible && ! otherInfo->isTrustedOverlay()
1635 && otherInfo->frameContainsPoint(x, y)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001636 return true;
1637 }
1638 }
1639 return false;
1640}
1641
Jeff Brown9302c872011-07-13 22:51:29 -07001642bool InputDispatcher::isWindowFinishedWithPreviousInputLocked(
1643 const sp<InputWindowHandle>& windowHandle) {
Jeff Browncc4f7db2011-08-30 20:34:48 -07001644 ssize_t connectionIndex = getConnectionIndexLocked(windowHandle->getInputChannel());
Jeff Brown519e0242010-09-15 15:18:56 -07001645 if (connectionIndex >= 0) {
1646 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
1647 return connection->outboundQueue.isEmpty();
1648 } else {
1649 return true;
1650 }
1651}
1652
Jeff Brown9302c872011-07-13 22:51:29 -07001653String8 InputDispatcher::getApplicationWindowLabelLocked(
1654 const sp<InputApplicationHandle>& applicationHandle,
1655 const sp<InputWindowHandle>& windowHandle) {
1656 if (applicationHandle != NULL) {
1657 if (windowHandle != NULL) {
Jeff Browncc4f7db2011-08-30 20:34:48 -07001658 String8 label(applicationHandle->getName());
Jeff Brown519e0242010-09-15 15:18:56 -07001659 label.append(" - ");
Jeff Browncc4f7db2011-08-30 20:34:48 -07001660 label.append(windowHandle->getName());
Jeff Brown519e0242010-09-15 15:18:56 -07001661 return label;
1662 } else {
Jeff Browncc4f7db2011-08-30 20:34:48 -07001663 return applicationHandle->getName();
Jeff Brown519e0242010-09-15 15:18:56 -07001664 }
Jeff Brown9302c872011-07-13 22:51:29 -07001665 } else if (windowHandle != NULL) {
Jeff Browncc4f7db2011-08-30 20:34:48 -07001666 return windowHandle->getName();
Jeff Brown519e0242010-09-15 15:18:56 -07001667 } else {
1668 return String8("<unknown application or window>");
1669 }
1670}
1671
Jeff Browne2fe69e2010-10-18 13:21:23 -07001672void InputDispatcher::pokeUserActivityLocked(const EventEntry* eventEntry) {
Jeff Brown56194eb2011-03-02 19:23:13 -08001673 int32_t eventType = POWER_MANAGER_OTHER_EVENT;
Jeff Brown4d396052010-10-29 21:50:21 -07001674 switch (eventEntry->type) {
1675 case EventEntry::TYPE_MOTION: {
Jeff Browne2fe69e2010-10-18 13:21:23 -07001676 const MotionEntry* motionEntry = static_cast<const MotionEntry*>(eventEntry);
Jeff Brown4d396052010-10-29 21:50:21 -07001677 if (motionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
1678 return;
1679 }
1680
Jeff Brown56194eb2011-03-02 19:23:13 -08001681 if (MotionEvent::isTouchEvent(motionEntry->source, motionEntry->action)) {
Joe Onorato1a542c72010-11-08 09:48:20 -08001682 eventType = POWER_MANAGER_TOUCH_EVENT;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001683 }
Jeff Brown4d396052010-10-29 21:50:21 -07001684 break;
1685 }
1686 case EventEntry::TYPE_KEY: {
1687 const KeyEntry* keyEntry = static_cast<const KeyEntry*>(eventEntry);
1688 if (keyEntry->flags & AKEY_EVENT_FLAG_CANCELED) {
1689 return;
1690 }
Jeff Brown56194eb2011-03-02 19:23:13 -08001691 eventType = POWER_MANAGER_BUTTON_EVENT;
Jeff Brown4d396052010-10-29 21:50:21 -07001692 break;
1693 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001694 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001695
Jeff Brownb88102f2010-09-08 11:49:43 -07001696 CommandEntry* commandEntry = postCommandLocked(
1697 & InputDispatcher::doPokeUserActivityLockedInterruptible);
Jeff Browne2fe69e2010-10-18 13:21:23 -07001698 commandEntry->eventTime = eventEntry->eventTime;
Jeff Brownb88102f2010-09-08 11:49:43 -07001699 commandEntry->userActivityEventType = eventType;
1700}
1701
Jeff Brown7fbdc842010-06-17 20:52:56 -07001702void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001703 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07001704#if DEBUG_DISPATCH_CYCLE
Steve Block5baa3a62011-12-20 16:23:08 +00001705 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
Jeff Brown9cc695c2011-08-23 18:35:04 -07001706 "xOffset=%f, yOffset=%f, scaleFactor=%f, "
Jeff Brown3241b6b2012-02-03 15:08:02 -08001707 "pointerIds=0x%x",
Jeff Brown519e0242010-09-15 15:18:56 -07001708 connection->getInputChannelName(), inputTarget->flags,
Jeff Brown46b9ac02010-04-22 18:58:52 -07001709 inputTarget->xOffset, inputTarget->yOffset,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001710 inputTarget->scaleFactor, inputTarget->pointerIds.value);
Jeff Brown46b9ac02010-04-22 18:58:52 -07001711#endif
1712
1713 // Skip this event if the connection status is not normal.
Jeff Brown519e0242010-09-15 15:18:56 -07001714 // We don't want to enqueue additional outbound events if the connection is broken.
Jeff Brown46b9ac02010-04-22 18:58:52 -07001715 if (connection->status != Connection::STATUS_NORMAL) {
Jeff Brownb6997262010-10-08 22:31:17 -07001716#if DEBUG_DISPATCH_CYCLE
Steve Block5baa3a62011-12-20 16:23:08 +00001717 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Jeff Brownb88102f2010-09-08 11:49:43 -07001718 connection->getInputChannelName(), connection->getStatusLabel());
Jeff Brownb6997262010-10-08 22:31:17 -07001719#endif
Jeff Brown46b9ac02010-04-22 18:58:52 -07001720 return;
1721 }
1722
Jeff Brown01ce2e92010-09-26 22:20:12 -07001723 // Split a motion event if needed.
Jeff Brown3241b6b2012-02-03 15:08:02 -08001724 if (inputTarget->flags & InputTarget::FLAG_SPLIT) {
Steve Blockec193de2012-01-09 18:35:44 +00001725 ALOG_ASSERT(eventEntry->type == EventEntry::TYPE_MOTION);
Jeff Brown01ce2e92010-09-26 22:20:12 -07001726
1727 MotionEntry* originalMotionEntry = static_cast<MotionEntry*>(eventEntry);
1728 if (inputTarget->pointerIds.count() != originalMotionEntry->pointerCount) {
1729 MotionEntry* splitMotionEntry = splitMotionEvent(
1730 originalMotionEntry, inputTarget->pointerIds);
Jeff Brown58a2da82011-01-25 16:02:22 -08001731 if (!splitMotionEntry) {
1732 return; // split event was dropped
1733 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001734#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001735 ALOGD("channel '%s' ~ Split motion event.",
Jeff Brown01ce2e92010-09-26 22:20:12 -07001736 connection->getInputChannelName());
1737 logOutboundMotionDetailsLocked(" ", splitMotionEntry);
1738#endif
Jeff Brownc0cb3dc2012-01-12 18:30:12 -08001739 enqueueDispatchEntriesLocked(currentTime, connection,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001740 splitMotionEntry, inputTarget);
Jeff Brownc0cb3dc2012-01-12 18:30:12 -08001741 splitMotionEntry->release();
1742 return;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001743 }
1744 }
1745
Jeff Brownc0cb3dc2012-01-12 18:30:12 -08001746 // Not splitting. Enqueue dispatch entries for the event as is.
Jeff Brown3241b6b2012-02-03 15:08:02 -08001747 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
Jeff Brownc0cb3dc2012-01-12 18:30:12 -08001748}
1749
1750void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001751 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07001752 bool wasEmpty = connection->outboundQueue.isEmpty();
1753
Jeff Browna032cc02011-03-07 16:56:21 -08001754 // Enqueue dispatch entries for the requested modes.
1755 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001756 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
Jeff Browna032cc02011-03-07 16:56:21 -08001757 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001758 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
Jeff Browna032cc02011-03-07 16:56:21 -08001759 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001760 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
Jeff Browna032cc02011-03-07 16:56:21 -08001761 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001762 InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brown98db5fa2011-06-08 15:37:10 -07001763 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001764 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
Jeff Brown98db5fa2011-06-08 15:37:10 -07001765 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001766 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Jeff Browna032cc02011-03-07 16:56:21 -08001767
1768 // If the outbound queue was previously empty, start the dispatch cycle going.
Jeff Brownb6110c22011-04-01 16:15:13 -07001769 if (wasEmpty && !connection->outboundQueue.isEmpty()) {
Jeff Browna032cc02011-03-07 16:56:21 -08001770 activateConnectionLocked(connection.get());
1771 startDispatchCycleLocked(currentTime, connection);
1772 }
1773}
1774
1775void InputDispatcher::enqueueDispatchEntryLocked(
1776 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001777 int32_t dispatchMode) {
Jeff Browna032cc02011-03-07 16:56:21 -08001778 int32_t inputTargetFlags = inputTarget->flags;
1779 if (!(inputTargetFlags & dispatchMode)) {
1780 return;
1781 }
1782 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
1783
Jeff Brown46b9ac02010-04-22 18:58:52 -07001784 // This is a new event.
1785 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Jeff Brownac386072011-07-20 15:19:50 -07001786 DispatchEntry* dispatchEntry = new DispatchEntry(eventEntry, // increments ref
Dianne Hackbornaa9d84c2011-05-09 19:00:59 -07001787 inputTargetFlags, inputTarget->xOffset, inputTarget->yOffset,
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001788 inputTarget->scaleFactor);
Jeff Brown6ec402b2010-07-28 15:48:59 -07001789
Jeff Brown81346812011-06-28 20:08:48 -07001790 // Apply target flags and update the connection's input state.
1791 switch (eventEntry->type) {
1792 case EventEntry::TYPE_KEY: {
1793 KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
1794 dispatchEntry->resolvedAction = keyEntry->action;
1795 dispatchEntry->resolvedFlags = keyEntry->flags;
1796
1797 if (!connection->inputState.trackKey(keyEntry,
1798 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags)) {
1799#if DEBUG_DISPATCH_CYCLE
Steve Block5baa3a62011-12-20 16:23:08 +00001800 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
Jeff Brown81346812011-06-28 20:08:48 -07001801 connection->getInputChannelName());
1802#endif
Jeff Brownc0cb3dc2012-01-12 18:30:12 -08001803 delete dispatchEntry;
Jeff Brown81346812011-06-28 20:08:48 -07001804 return; // skip the inconsistent event
1805 }
1806 break;
1807 }
1808
1809 case EventEntry::TYPE_MOTION: {
1810 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
1811 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
1812 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
1813 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
1814 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
1815 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
1816 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
1817 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
1818 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
1819 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
1820 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
1821 } else {
1822 dispatchEntry->resolvedAction = motionEntry->action;
1823 }
1824 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE
1825 && !connection->inputState.isHovering(
1826 motionEntry->deviceId, motionEntry->source)) {
1827#if DEBUG_DISPATCH_CYCLE
Steve Block5baa3a62011-12-20 16:23:08 +00001828 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter event",
Jeff Brown81346812011-06-28 20:08:48 -07001829 connection->getInputChannelName());
1830#endif
1831 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
1832 }
1833
1834 dispatchEntry->resolvedFlags = motionEntry->flags;
1835 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
1836 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
1837 }
1838
1839 if (!connection->inputState.trackMotion(motionEntry,
1840 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags)) {
1841#if DEBUG_DISPATCH_CYCLE
Steve Block5baa3a62011-12-20 16:23:08 +00001842 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion event",
Jeff Brown81346812011-06-28 20:08:48 -07001843 connection->getInputChannelName());
1844#endif
Jeff Brownc0cb3dc2012-01-12 18:30:12 -08001845 delete dispatchEntry;
Jeff Brown81346812011-06-28 20:08:48 -07001846 return; // skip the inconsistent event
1847 }
1848 break;
1849 }
1850 }
1851
Jeff Brownc0cb3dc2012-01-12 18:30:12 -08001852 // Remember that we are waiting for this dispatch to complete.
1853 if (dispatchEntry->hasForegroundTarget()) {
1854 incrementPendingForegroundDispatchesLocked(eventEntry);
1855 }
1856
Jeff Brown46b9ac02010-04-22 18:58:52 -07001857 // Enqueue the dispatch entry.
1858 connection->outboundQueue.enqueueAtTail(dispatchEntry);
Jeff Brown46b9ac02010-04-22 18:58:52 -07001859}
1860
Jeff Brown7fbdc842010-06-17 20:52:56 -07001861void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Jeff Brown519e0242010-09-15 15:18:56 -07001862 const sp<Connection>& connection) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07001863#if DEBUG_DISPATCH_CYCLE
Steve Block5baa3a62011-12-20 16:23:08 +00001864 ALOGD("channel '%s' ~ startDispatchCycle",
Jeff Brown46b9ac02010-04-22 18:58:52 -07001865 connection->getInputChannelName());
1866#endif
1867
Steve Blockec193de2012-01-09 18:35:44 +00001868 ALOG_ASSERT(connection->status == Connection::STATUS_NORMAL);
1869 ALOG_ASSERT(! connection->outboundQueue.isEmpty());
Jeff Brown46b9ac02010-04-22 18:58:52 -07001870
Jeff Brownac386072011-07-20 15:19:50 -07001871 DispatchEntry* dispatchEntry = connection->outboundQueue.head;
Steve Blockec193de2012-01-09 18:35:44 +00001872 ALOG_ASSERT(! dispatchEntry->inProgress);
Jeff Brown46b9ac02010-04-22 18:58:52 -07001873
Jeff Brownb88102f2010-09-08 11:49:43 -07001874 // Mark the dispatch entry as in progress.
1875 dispatchEntry->inProgress = true;
1876
Jeff Brown46b9ac02010-04-22 18:58:52 -07001877 // Publish the event.
1878 status_t status;
Jeff Browna032cc02011-03-07 16:56:21 -08001879 EventEntry* eventEntry = dispatchEntry->eventEntry;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001880 switch (eventEntry->type) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07001881 case EventEntry::TYPE_KEY: {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001882 KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
Jeff Brown46b9ac02010-04-22 18:58:52 -07001883
Jeff Brown46b9ac02010-04-22 18:58:52 -07001884 // Publish the key event.
Jeff Brown81346812011-06-28 20:08:48 -07001885 status = connection->inputPublisher.publishKeyEvent(
1886 keyEntry->deviceId, keyEntry->source,
1887 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags,
1888 keyEntry->keyCode, keyEntry->scanCode,
Jeff Brown46b9ac02010-04-22 18:58:52 -07001889 keyEntry->metaState, keyEntry->repeatCount, keyEntry->downTime,
1890 keyEntry->eventTime);
1891
1892 if (status) {
Steve Block3762c312012-01-06 19:20:56 +00001893 ALOGE("channel '%s' ~ Could not publish key event, "
Jeff Brown46b9ac02010-04-22 18:58:52 -07001894 "status=%d", connection->getInputChannelName(), status);
Jeff Browncc4f7db2011-08-30 20:34:48 -07001895 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
Jeff Brown46b9ac02010-04-22 18:58:52 -07001896 return;
1897 }
1898 break;
1899 }
1900
1901 case EventEntry::TYPE_MOTION: {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001902 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
Jeff Brown46b9ac02010-04-22 18:58:52 -07001903
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001904 PointerCoords scaledCoords[MAX_POINTERS];
Jeff Brown3241b6b2012-02-03 15:08:02 -08001905 const PointerCoords* usingCoords = motionEntry->pointerCoords;
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001906
Jeff Brownd3616592010-07-16 17:21:06 -07001907 // Set the X and Y offset depending on the input source.
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001908 float xOffset, yOffset, scaleFactor;
Kenny Root7a9db182011-06-02 15:16:05 -07001909 if (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER
1910 && !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001911 scaleFactor = dispatchEntry->scaleFactor;
1912 xOffset = dispatchEntry->xOffset * scaleFactor;
1913 yOffset = dispatchEntry->yOffset * scaleFactor;
1914 if (scaleFactor != 1.0f) {
1915 for (size_t i = 0; i < motionEntry->pointerCount; i++) {
Jeff Brown3241b6b2012-02-03 15:08:02 -08001916 scaledCoords[i] = motionEntry->pointerCoords[i];
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001917 scaledCoords[i].scale(scaleFactor);
1918 }
1919 usingCoords = scaledCoords;
1920 }
Jeff Brownd3616592010-07-16 17:21:06 -07001921 } else {
1922 xOffset = 0.0f;
1923 yOffset = 0.0f;
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001924 scaleFactor = 1.0f;
Kenny Root7a9db182011-06-02 15:16:05 -07001925
1926 // We don't want the dispatch target to know.
1927 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
1928 for (size_t i = 0; i < motionEntry->pointerCount; i++) {
1929 scaledCoords[i].clear();
1930 }
1931 usingCoords = scaledCoords;
1932 }
Jeff Brownd3616592010-07-16 17:21:06 -07001933 }
1934
Jeff Brown3241b6b2012-02-03 15:08:02 -08001935 // Publish the motion event.
Jeff Brown81346812011-06-28 20:08:48 -07001936 status = connection->inputPublisher.publishMotionEvent(
1937 motionEntry->deviceId, motionEntry->source,
1938 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags,
1939 motionEntry->edgeFlags, motionEntry->metaState, motionEntry->buttonState,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07001940 xOffset, yOffset,
1941 motionEntry->xPrecision, motionEntry->yPrecision,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001942 motionEntry->downTime, motionEntry->eventTime,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07001943 motionEntry->pointerCount, motionEntry->pointerProperties,
1944 usingCoords);
Jeff Brown46b9ac02010-04-22 18:58:52 -07001945
1946 if (status) {
Steve Block3762c312012-01-06 19:20:56 +00001947 ALOGE("channel '%s' ~ Could not publish motion event, "
Jeff Brown46b9ac02010-04-22 18:58:52 -07001948 "status=%d", connection->getInputChannelName(), status);
Jeff Browncc4f7db2011-08-30 20:34:48 -07001949 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
Jeff Brown46b9ac02010-04-22 18:58:52 -07001950 return;
1951 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07001952 break;
1953 }
1954
1955 default: {
Steve Blockec193de2012-01-09 18:35:44 +00001956 ALOG_ASSERT(false);
Jeff Brown46b9ac02010-04-22 18:58:52 -07001957 }
1958 }
1959
1960 // Send the dispatch signal.
1961 status = connection->inputPublisher.sendDispatchSignal();
1962 if (status) {
Steve Block3762c312012-01-06 19:20:56 +00001963 ALOGE("channel '%s' ~ Could not send dispatch signal, status=%d",
Jeff Brown46b9ac02010-04-22 18:58:52 -07001964 connection->getInputChannelName(), status);
Jeff Browncc4f7db2011-08-30 20:34:48 -07001965 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
Jeff Brown46b9ac02010-04-22 18:58:52 -07001966 return;
1967 }
1968
1969 // Record information about the newly started dispatch cycle.
Jeff Brown01ce2e92010-09-26 22:20:12 -07001970 connection->lastEventTime = eventEntry->eventTime;
Jeff Brown46b9ac02010-04-22 18:58:52 -07001971 connection->lastDispatchTime = currentTime;
1972
Jeff Brown46b9ac02010-04-22 18:58:52 -07001973 // Notify other system components.
1974 onDispatchCycleStartedLocked(currentTime, connection);
1975}
1976
Jeff Brown7fbdc842010-06-17 20:52:56 -07001977void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Jeff Brown3915bb82010-11-05 15:02:16 -07001978 const sp<Connection>& connection, bool handled) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07001979#if DEBUG_DISPATCH_CYCLE
Steve Block5baa3a62011-12-20 16:23:08 +00001980 ALOGD("channel '%s' ~ finishDispatchCycle - %01.1fms since event, "
Jeff Brown3915bb82010-11-05 15:02:16 -07001981 "%01.1fms since dispatch, handled=%s",
Jeff Brown46b9ac02010-04-22 18:58:52 -07001982 connection->getInputChannelName(),
1983 connection->getEventLatencyMillis(currentTime),
Jeff Brown3915bb82010-11-05 15:02:16 -07001984 connection->getDispatchLatencyMillis(currentTime),
1985 toString(handled));
Jeff Brown46b9ac02010-04-22 18:58:52 -07001986#endif
1987
Jeff Brown9c3cda02010-06-15 01:31:58 -07001988 if (connection->status == Connection::STATUS_BROKEN
1989 || connection->status == Connection::STATUS_ZOMBIE) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07001990 return;
1991 }
1992
Jeff Brown46b9ac02010-04-22 18:58:52 -07001993 // Reset the publisher since the event has been consumed.
1994 // We do this now so that the publisher can release some of its internal resources
1995 // while waiting for the next dispatch cycle to begin.
1996 status_t status = connection->inputPublisher.reset();
1997 if (status) {
Steve Block3762c312012-01-06 19:20:56 +00001998 ALOGE("channel '%s' ~ Could not reset publisher, status=%d",
Jeff Brown46b9ac02010-04-22 18:58:52 -07001999 connection->getInputChannelName(), status);
Jeff Browncc4f7db2011-08-30 20:34:48 -07002000 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002001 return;
2002 }
2003
Jeff Brown3915bb82010-11-05 15:02:16 -07002004 // Notify other system components and prepare to start the next dispatch cycle.
2005 onDispatchCycleFinishedLocked(currentTime, connection, handled);
Jeff Brownb88102f2010-09-08 11:49:43 -07002006}
2007
2008void InputDispatcher::startNextDispatchCycleLocked(nsecs_t currentTime,
2009 const sp<Connection>& connection) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002010 // Start the next dispatch cycle for this connection.
2011 while (! connection->outboundQueue.isEmpty()) {
Jeff Brownac386072011-07-20 15:19:50 -07002012 DispatchEntry* dispatchEntry = connection->outboundQueue.head;
Jeff Brown46b9ac02010-04-22 18:58:52 -07002013 if (dispatchEntry->inProgress) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002014 // Finished.
2015 connection->outboundQueue.dequeueAtHead();
Jeff Brown519e0242010-09-15 15:18:56 -07002016 if (dispatchEntry->hasForegroundTarget()) {
2017 decrementPendingForegroundDispatchesLocked(dispatchEntry->eventEntry);
Jeff Brown6ec402b2010-07-28 15:48:59 -07002018 }
Jeff Brownac386072011-07-20 15:19:50 -07002019 delete dispatchEntry;
Jeff Brown46b9ac02010-04-22 18:58:52 -07002020 } else {
2021 // If the head is not in progress, then we must have already dequeued the in
Jeff Brown519e0242010-09-15 15:18:56 -07002022 // progress event, which means we actually aborted it.
Jeff Brown46b9ac02010-04-22 18:58:52 -07002023 // So just start the next event for this connection.
Jeff Brown519e0242010-09-15 15:18:56 -07002024 startDispatchCycleLocked(currentTime, connection);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002025 return;
2026 }
2027 }
2028
2029 // Outbound queue is empty, deactivate the connection.
Jeff Brown7fbdc842010-06-17 20:52:56 -07002030 deactivateConnectionLocked(connection.get());
Jeff Brown46b9ac02010-04-22 18:58:52 -07002031}
2032
Jeff Brownb6997262010-10-08 22:31:17 -07002033void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Jeff Browncc4f7db2011-08-30 20:34:48 -07002034 const sp<Connection>& connection, bool notify) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002035#if DEBUG_DISPATCH_CYCLE
Steve Block5baa3a62011-12-20 16:23:08 +00002036 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
Jeff Browncc4f7db2011-08-30 20:34:48 -07002037 connection->getInputChannelName(), toString(notify));
Jeff Brown46b9ac02010-04-22 18:58:52 -07002038#endif
2039
Jeff Brownb88102f2010-09-08 11:49:43 -07002040 // Clear the outbound queue.
Jeff Brown519e0242010-09-15 15:18:56 -07002041 drainOutboundQueueLocked(connection.get());
Jeff Brown46b9ac02010-04-22 18:58:52 -07002042
Jeff Brownb6997262010-10-08 22:31:17 -07002043 // The connection appears to be unrecoverably broken.
Jeff Brown9c3cda02010-06-15 01:31:58 -07002044 // Ignore already broken or zombie connections.
Jeff Brownb6997262010-10-08 22:31:17 -07002045 if (connection->status == Connection::STATUS_NORMAL) {
2046 connection->status = Connection::STATUS_BROKEN;
Jeff Brown46b9ac02010-04-22 18:58:52 -07002047
Jeff Browncc4f7db2011-08-30 20:34:48 -07002048 if (notify) {
2049 // Notify other system components.
2050 onDispatchCycleBrokenLocked(currentTime, connection);
2051 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002052 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002053}
2054
Jeff Brown519e0242010-09-15 15:18:56 -07002055void InputDispatcher::drainOutboundQueueLocked(Connection* connection) {
2056 while (! connection->outboundQueue.isEmpty()) {
2057 DispatchEntry* dispatchEntry = connection->outboundQueue.dequeueAtHead();
2058 if (dispatchEntry->hasForegroundTarget()) {
2059 decrementPendingForegroundDispatchesLocked(dispatchEntry->eventEntry);
Jeff Brownb88102f2010-09-08 11:49:43 -07002060 }
Jeff Brownac386072011-07-20 15:19:50 -07002061 delete dispatchEntry;
Jeff Brownb88102f2010-09-08 11:49:43 -07002062 }
2063
Jeff Brown519e0242010-09-15 15:18:56 -07002064 deactivateConnectionLocked(connection);
Jeff Brownb88102f2010-09-08 11:49:43 -07002065}
2066
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002067int InputDispatcher::handleReceiveCallback(int receiveFd, int events, void* data) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002068 InputDispatcher* d = static_cast<InputDispatcher*>(data);
2069
2070 { // acquire lock
2071 AutoMutex _l(d->mLock);
2072
2073 ssize_t connectionIndex = d->mConnectionsByReceiveFd.indexOfKey(receiveFd);
2074 if (connectionIndex < 0) {
Steve Block3762c312012-01-06 19:20:56 +00002075 ALOGE("Received spurious receive callback for unknown input channel. "
Jeff Brown46b9ac02010-04-22 18:58:52 -07002076 "fd=%d, events=0x%x", receiveFd, events);
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002077 return 0; // remove the callback
Jeff Brown46b9ac02010-04-22 18:58:52 -07002078 }
2079
Jeff Browncc4f7db2011-08-30 20:34:48 -07002080 bool notify;
Jeff Brown46b9ac02010-04-22 18:58:52 -07002081 sp<Connection> connection = d->mConnectionsByReceiveFd.valueAt(connectionIndex);
Jeff Browncc4f7db2011-08-30 20:34:48 -07002082 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
2083 if (!(events & ALOOPER_EVENT_INPUT)) {
Steve Block8564c8d2012-01-05 23:22:43 +00002084 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
Jeff Browncc4f7db2011-08-30 20:34:48 -07002085 "events=0x%x", connection->getInputChannelName(), events);
2086 return 1;
2087 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002088
Jeff Browncc4f7db2011-08-30 20:34:48 -07002089 bool handled = false;
2090 status_t status = connection->inputPublisher.receiveFinishedSignal(&handled);
2091 if (!status) {
2092 nsecs_t currentTime = now();
2093 d->finishDispatchCycleLocked(currentTime, connection, handled);
2094 d->runCommandsLockedInterruptible();
2095 return 1;
2096 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002097
Steve Block3762c312012-01-06 19:20:56 +00002098 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
Jeff Brown46b9ac02010-04-22 18:58:52 -07002099 connection->getInputChannelName(), status);
Jeff Browncc4f7db2011-08-30 20:34:48 -07002100 notify = true;
2101 } else {
2102 // Monitor channels are never explicitly unregistered.
2103 // We do it automatically when the remote endpoint is closed so don't warn
2104 // about them.
2105 notify = !connection->monitor;
2106 if (notify) {
Steve Block8564c8d2012-01-05 23:22:43 +00002107 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. "
Jeff Browncc4f7db2011-08-30 20:34:48 -07002108 "events=0x%x", connection->getInputChannelName(), events);
2109 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002110 }
2111
Jeff Browncc4f7db2011-08-30 20:34:48 -07002112 // Unregister the channel.
2113 d->unregisterInputChannelLocked(connection->inputChannel, notify);
2114 return 0; // remove the callback
Jeff Brown46b9ac02010-04-22 18:58:52 -07002115 } // release lock
2116}
2117
Jeff Brownb6997262010-10-08 22:31:17 -07002118void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Jeff Brownda3d5a92011-03-29 15:11:34 -07002119 const CancelationOptions& options) {
Jeff Brownb6997262010-10-08 22:31:17 -07002120 for (size_t i = 0; i < mConnectionsByReceiveFd.size(); i++) {
2121 synthesizeCancelationEventsForConnectionLocked(
Jeff Brownda3d5a92011-03-29 15:11:34 -07002122 mConnectionsByReceiveFd.valueAt(i), options);
Jeff Brownb6997262010-10-08 22:31:17 -07002123 }
2124}
2125
2126void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Jeff Brownda3d5a92011-03-29 15:11:34 -07002127 const sp<InputChannel>& channel, const CancelationOptions& options) {
Jeff Brownb6997262010-10-08 22:31:17 -07002128 ssize_t index = getConnectionIndexLocked(channel);
2129 if (index >= 0) {
2130 synthesizeCancelationEventsForConnectionLocked(
Jeff Brownda3d5a92011-03-29 15:11:34 -07002131 mConnectionsByReceiveFd.valueAt(index), options);
Jeff Brownb6997262010-10-08 22:31:17 -07002132 }
2133}
2134
2135void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
Jeff Brownda3d5a92011-03-29 15:11:34 -07002136 const sp<Connection>& connection, const CancelationOptions& options) {
Jeff Brownc0cb3dc2012-01-12 18:30:12 -08002137 if (connection->status == Connection::STATUS_BROKEN) {
2138 return;
2139 }
2140
Jeff Brownb6997262010-10-08 22:31:17 -07002141 nsecs_t currentTime = now();
2142
2143 mTempCancelationEvents.clear();
Jeff Brownac386072011-07-20 15:19:50 -07002144 connection->inputState.synthesizeCancelationEvents(currentTime,
Jeff Brownb6997262010-10-08 22:31:17 -07002145 mTempCancelationEvents, options);
2146
Jeff Brownc0cb3dc2012-01-12 18:30:12 -08002147 if (!mTempCancelationEvents.isEmpty()) {
Jeff Brownb6997262010-10-08 22:31:17 -07002148#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00002149 ALOGD("channel '%s' ~ Synthesized %d cancelation events to bring channel back in sync "
Jeff Brownda3d5a92011-03-29 15:11:34 -07002150 "with reality: %s, mode=%d.",
2151 connection->getInputChannelName(), mTempCancelationEvents.size(),
2152 options.reason, options.mode);
Jeff Brownb6997262010-10-08 22:31:17 -07002153#endif
2154 for (size_t i = 0; i < mTempCancelationEvents.size(); i++) {
2155 EventEntry* cancelationEventEntry = mTempCancelationEvents.itemAt(i);
2156 switch (cancelationEventEntry->type) {
2157 case EventEntry::TYPE_KEY:
2158 logOutboundKeyDetailsLocked("cancel - ",
2159 static_cast<KeyEntry*>(cancelationEventEntry));
2160 break;
2161 case EventEntry::TYPE_MOTION:
2162 logOutboundMotionDetailsLocked("cancel - ",
2163 static_cast<MotionEntry*>(cancelationEventEntry));
2164 break;
2165 }
2166
Jeff Brown81346812011-06-28 20:08:48 -07002167 InputTarget target;
Jeff Brown9302c872011-07-13 22:51:29 -07002168 sp<InputWindowHandle> windowHandle = getWindowHandleLocked(connection->inputChannel);
2169 if (windowHandle != NULL) {
Jeff Browncc4f7db2011-08-30 20:34:48 -07002170 const InputWindowInfo* windowInfo = windowHandle->getInfo();
2171 target.xOffset = -windowInfo->frameLeft;
2172 target.yOffset = -windowInfo->frameTop;
2173 target.scaleFactor = windowInfo->scaleFactor;
Jeff Brownb6997262010-10-08 22:31:17 -07002174 } else {
Jeff Brown81346812011-06-28 20:08:48 -07002175 target.xOffset = 0;
2176 target.yOffset = 0;
2177 target.scaleFactor = 1.0f;
Jeff Brownb6997262010-10-08 22:31:17 -07002178 }
Jeff Brown81346812011-06-28 20:08:48 -07002179 target.inputChannel = connection->inputChannel;
2180 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
Jeff Brownb6997262010-10-08 22:31:17 -07002181
Jeff Brown81346812011-06-28 20:08:48 -07002182 enqueueDispatchEntryLocked(connection, cancelationEventEntry, // increments ref
Jeff Brown3241b6b2012-02-03 15:08:02 -08002183 &target, InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brownb6997262010-10-08 22:31:17 -07002184
Jeff Brownac386072011-07-20 15:19:50 -07002185 cancelationEventEntry->release();
Jeff Brownb6997262010-10-08 22:31:17 -07002186 }
2187
Jeff Brownac386072011-07-20 15:19:50 -07002188 if (!connection->outboundQueue.head->inProgress) {
Jeff Brownb6997262010-10-08 22:31:17 -07002189 startDispatchCycleLocked(currentTime, connection);
2190 }
2191 }
2192}
2193
Jeff Brown01ce2e92010-09-26 22:20:12 -07002194InputDispatcher::MotionEntry*
2195InputDispatcher::splitMotionEvent(const MotionEntry* originalMotionEntry, BitSet32 pointerIds) {
Steve Blockec193de2012-01-09 18:35:44 +00002196 ALOG_ASSERT(pointerIds.value != 0);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002197
2198 uint32_t splitPointerIndexMap[MAX_POINTERS];
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002199 PointerProperties splitPointerProperties[MAX_POINTERS];
Jeff Brown01ce2e92010-09-26 22:20:12 -07002200 PointerCoords splitPointerCoords[MAX_POINTERS];
2201
2202 uint32_t originalPointerCount = originalMotionEntry->pointerCount;
2203 uint32_t splitPointerCount = 0;
2204
2205 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
2206 originalPointerIndex++) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002207 const PointerProperties& pointerProperties =
2208 originalMotionEntry->pointerProperties[originalPointerIndex];
2209 uint32_t pointerId = uint32_t(pointerProperties.id);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002210 if (pointerIds.hasBit(pointerId)) {
2211 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002212 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
Jeff Brownace13b12011-03-09 17:39:48 -08002213 splitPointerCoords[splitPointerCount].copyFrom(
Jeff Brown3241b6b2012-02-03 15:08:02 -08002214 originalMotionEntry->pointerCoords[originalPointerIndex]);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002215 splitPointerCount += 1;
2216 }
2217 }
Jeff Brown58a2da82011-01-25 16:02:22 -08002218
2219 if (splitPointerCount != pointerIds.count()) {
2220 // This is bad. We are missing some of the pointers that we expected to deliver.
2221 // Most likely this indicates that we received an ACTION_MOVE events that has
2222 // different pointer ids than we expected based on the previous ACTION_DOWN
2223 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
2224 // in this way.
Steve Block8564c8d2012-01-05 23:22:43 +00002225 ALOGW("Dropping split motion event because the pointer count is %d but "
Jeff Brown58a2da82011-01-25 16:02:22 -08002226 "we expected there to be %d pointers. This probably means we received "
2227 "a broken sequence of pointer ids from the input device.",
2228 splitPointerCount, pointerIds.count());
2229 return NULL;
2230 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07002231
2232 int32_t action = originalMotionEntry->action;
2233 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
2234 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
2235 || maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2236 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002237 const PointerProperties& pointerProperties =
2238 originalMotionEntry->pointerProperties[originalPointerIndex];
2239 uint32_t pointerId = uint32_t(pointerProperties.id);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002240 if (pointerIds.hasBit(pointerId)) {
2241 if (pointerIds.count() == 1) {
2242 // The first/last pointer went down/up.
2243 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
2244 ? AMOTION_EVENT_ACTION_DOWN : AMOTION_EVENT_ACTION_UP;
Jeff Brown9a01d052010-09-27 16:35:11 -07002245 } else {
2246 // A secondary pointer went down/up.
2247 uint32_t splitPointerIndex = 0;
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002248 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
Jeff Brown9a01d052010-09-27 16:35:11 -07002249 splitPointerIndex += 1;
2250 }
2251 action = maskedAction | (splitPointerIndex
2252 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002253 }
2254 } else {
2255 // An unrelated pointer changed.
2256 action = AMOTION_EVENT_ACTION_MOVE;
2257 }
2258 }
2259
Jeff Brownac386072011-07-20 15:19:50 -07002260 MotionEntry* splitMotionEntry = new MotionEntry(
Jeff Brown01ce2e92010-09-26 22:20:12 -07002261 originalMotionEntry->eventTime,
2262 originalMotionEntry->deviceId,
2263 originalMotionEntry->source,
2264 originalMotionEntry->policyFlags,
2265 action,
2266 originalMotionEntry->flags,
2267 originalMotionEntry->metaState,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002268 originalMotionEntry->buttonState,
Jeff Brown01ce2e92010-09-26 22:20:12 -07002269 originalMotionEntry->edgeFlags,
2270 originalMotionEntry->xPrecision,
2271 originalMotionEntry->yPrecision,
2272 originalMotionEntry->downTime,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002273 splitPointerCount, splitPointerProperties, splitPointerCoords);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002274
Jeff Browna032cc02011-03-07 16:56:21 -08002275 if (originalMotionEntry->injectionState) {
2276 splitMotionEntry->injectionState = originalMotionEntry->injectionState;
2277 splitMotionEntry->injectionState->refCount += 1;
2278 }
2279
Jeff Brown01ce2e92010-09-26 22:20:12 -07002280 return splitMotionEntry;
2281}
2282
Jeff Brownbe1aa822011-07-27 16:04:54 -07002283void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002284#if DEBUG_INBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00002285 ALOGD("notifyConfigurationChanged - eventTime=%lld", args->eventTime);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002286#endif
2287
Jeff Brownb88102f2010-09-08 11:49:43 -07002288 bool needWake;
Jeff Brown46b9ac02010-04-22 18:58:52 -07002289 { // acquire lock
2290 AutoMutex _l(mLock);
2291
Jeff Brownbe1aa822011-07-27 16:04:54 -07002292 ConfigurationChangedEntry* newEntry = new ConfigurationChangedEntry(args->eventTime);
Jeff Brownb88102f2010-09-08 11:49:43 -07002293 needWake = enqueueInboundEventLocked(newEntry);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002294 } // release lock
2295
Jeff Brownb88102f2010-09-08 11:49:43 -07002296 if (needWake) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002297 mLooper->wake();
Jeff Brown46b9ac02010-04-22 18:58:52 -07002298 }
2299}
2300
Jeff Brownbe1aa822011-07-27 16:04:54 -07002301void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002302#if DEBUG_INBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00002303 ALOGD("notifyKey - eventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, action=0x%x, "
Jeff Brown46b9ac02010-04-22 18:58:52 -07002304 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%lld",
Jeff Brownbe1aa822011-07-27 16:04:54 -07002305 args->eventTime, args->deviceId, args->source, args->policyFlags,
2306 args->action, args->flags, args->keyCode, args->scanCode,
2307 args->metaState, args->downTime);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002308#endif
Jeff Brownbe1aa822011-07-27 16:04:54 -07002309 if (!validateKeyEvent(args->action)) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002310 return;
2311 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002312
Jeff Brownbe1aa822011-07-27 16:04:54 -07002313 uint32_t policyFlags = args->policyFlags;
2314 int32_t flags = args->flags;
2315 int32_t metaState = args->metaState;
Jeff Brown1f245102010-11-18 20:53:46 -08002316 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
2317 policyFlags |= POLICY_FLAG_VIRTUAL;
2318 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
2319 }
Jeff Brown924c4d42011-03-07 16:40:47 -08002320 if (policyFlags & POLICY_FLAG_ALT) {
2321 metaState |= AMETA_ALT_ON | AMETA_ALT_LEFT_ON;
2322 }
2323 if (policyFlags & POLICY_FLAG_ALT_GR) {
2324 metaState |= AMETA_ALT_ON | AMETA_ALT_RIGHT_ON;
2325 }
2326 if (policyFlags & POLICY_FLAG_SHIFT) {
2327 metaState |= AMETA_SHIFT_ON | AMETA_SHIFT_LEFT_ON;
2328 }
2329 if (policyFlags & POLICY_FLAG_CAPS_LOCK) {
2330 metaState |= AMETA_CAPS_LOCK_ON;
2331 }
2332 if (policyFlags & POLICY_FLAG_FUNCTION) {
2333 metaState |= AMETA_FUNCTION_ON;
2334 }
Jeff Brown1f245102010-11-18 20:53:46 -08002335
Jeff Browne20c9e02010-10-11 14:20:19 -07002336 policyFlags |= POLICY_FLAG_TRUSTED;
Jeff Brown1f245102010-11-18 20:53:46 -08002337
2338 KeyEvent event;
Jeff Brownbe1aa822011-07-27 16:04:54 -07002339 event.initialize(args->deviceId, args->source, args->action,
2340 flags, args->keyCode, args->scanCode, metaState, 0,
2341 args->downTime, args->eventTime);
Jeff Brown1f245102010-11-18 20:53:46 -08002342
2343 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
2344
2345 if (policyFlags & POLICY_FLAG_WOKE_HERE) {
2346 flags |= AKEY_EVENT_FLAG_WOKE_HERE;
2347 }
Jeff Brownb6997262010-10-08 22:31:17 -07002348
Jeff Brownb88102f2010-09-08 11:49:43 -07002349 bool needWake;
Jeff Brown46b9ac02010-04-22 18:58:52 -07002350 { // acquire lock
Jeff Brown0029c662011-03-30 02:25:18 -07002351 mLock.lock();
2352
2353 if (mInputFilterEnabled) {
2354 mLock.unlock();
2355
2356 policyFlags |= POLICY_FLAG_FILTERED;
2357 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2358 return; // event was consumed by the filter
2359 }
2360
2361 mLock.lock();
2362 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002363
Jeff Brown7fbdc842010-06-17 20:52:56 -07002364 int32_t repeatCount = 0;
Jeff Brownbe1aa822011-07-27 16:04:54 -07002365 KeyEntry* newEntry = new KeyEntry(args->eventTime,
2366 args->deviceId, args->source, policyFlags,
2367 args->action, flags, args->keyCode, args->scanCode,
2368 metaState, repeatCount, args->downTime);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002369
Jeff Brownb88102f2010-09-08 11:49:43 -07002370 needWake = enqueueInboundEventLocked(newEntry);
Jeff Brown0029c662011-03-30 02:25:18 -07002371 mLock.unlock();
Jeff Brown46b9ac02010-04-22 18:58:52 -07002372 } // release lock
2373
Jeff Brownb88102f2010-09-08 11:49:43 -07002374 if (needWake) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002375 mLooper->wake();
Jeff Brown46b9ac02010-04-22 18:58:52 -07002376 }
2377}
2378
Jeff Brownbe1aa822011-07-27 16:04:54 -07002379void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002380#if DEBUG_INBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00002381 ALOGD("notifyMotion - eventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, "
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002382 "action=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, edgeFlags=0x%x, "
Jeff Brown85a31762010-09-01 17:01:00 -07002383 "xPrecision=%f, yPrecision=%f, downTime=%lld",
Jeff Brownbe1aa822011-07-27 16:04:54 -07002384 args->eventTime, args->deviceId, args->source, args->policyFlags,
2385 args->action, args->flags, args->metaState, args->buttonState,
2386 args->edgeFlags, args->xPrecision, args->yPrecision, args->downTime);
2387 for (uint32_t i = 0; i < args->pointerCount; i++) {
Steve Block5baa3a62011-12-20 16:23:08 +00002388 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002389 "x=%f, y=%f, pressure=%f, size=%f, "
Jeff Brown85a31762010-09-01 17:01:00 -07002390 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
Jeff Brown8d608662010-08-30 03:02:23 -07002391 "orientation=%f",
Jeff Brownbe1aa822011-07-27 16:04:54 -07002392 i, args->pointerProperties[i].id,
2393 args->pointerProperties[i].toolType,
2394 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
2395 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
2396 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
2397 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
2398 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
2399 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
2400 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
2401 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
2402 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Jeff Brown46b9ac02010-04-22 18:58:52 -07002403 }
2404#endif
Jeff Brownbe1aa822011-07-27 16:04:54 -07002405 if (!validateMotionEvent(args->action, args->pointerCount, args->pointerProperties)) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002406 return;
2407 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002408
Jeff Brownbe1aa822011-07-27 16:04:54 -07002409 uint32_t policyFlags = args->policyFlags;
Jeff Browne20c9e02010-10-11 14:20:19 -07002410 policyFlags |= POLICY_FLAG_TRUSTED;
Jeff Brownbe1aa822011-07-27 16:04:54 -07002411 mPolicy->interceptMotionBeforeQueueing(args->eventTime, /*byref*/ policyFlags);
Jeff Brownb6997262010-10-08 22:31:17 -07002412
Jeff Brownb88102f2010-09-08 11:49:43 -07002413 bool needWake;
Jeff Brown46b9ac02010-04-22 18:58:52 -07002414 { // acquire lock
Jeff Brown0029c662011-03-30 02:25:18 -07002415 mLock.lock();
2416
2417 if (mInputFilterEnabled) {
2418 mLock.unlock();
2419
2420 MotionEvent event;
Jeff Brownbe1aa822011-07-27 16:04:54 -07002421 event.initialize(args->deviceId, args->source, args->action, args->flags,
2422 args->edgeFlags, args->metaState, args->buttonState, 0, 0,
2423 args->xPrecision, args->yPrecision,
2424 args->downTime, args->eventTime,
2425 args->pointerCount, args->pointerProperties, args->pointerCoords);
Jeff Brown0029c662011-03-30 02:25:18 -07002426
2427 policyFlags |= POLICY_FLAG_FILTERED;
2428 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2429 return; // event was consumed by the filter
2430 }
2431
2432 mLock.lock();
2433 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002434
Jeff Brown46b9ac02010-04-22 18:58:52 -07002435 // Just enqueue a new motion event.
Jeff Brownbe1aa822011-07-27 16:04:54 -07002436 MotionEntry* newEntry = new MotionEntry(args->eventTime,
2437 args->deviceId, args->source, policyFlags,
2438 args->action, args->flags, args->metaState, args->buttonState,
2439 args->edgeFlags, args->xPrecision, args->yPrecision, args->downTime,
2440 args->pointerCount, args->pointerProperties, args->pointerCoords);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002441
Jeff Brownb88102f2010-09-08 11:49:43 -07002442 needWake = enqueueInboundEventLocked(newEntry);
Jeff Brown0029c662011-03-30 02:25:18 -07002443 mLock.unlock();
Jeff Brown46b9ac02010-04-22 18:58:52 -07002444 } // release lock
2445
Jeff Brownb88102f2010-09-08 11:49:43 -07002446 if (needWake) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002447 mLooper->wake();
Jeff Brown46b9ac02010-04-22 18:58:52 -07002448 }
2449}
2450
Jeff Brownbe1aa822011-07-27 16:04:54 -07002451void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
Jeff Brownb6997262010-10-08 22:31:17 -07002452#if DEBUG_INBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00002453 ALOGD("notifySwitch - eventTime=%lld, policyFlags=0x%x, switchCode=%d, switchValue=%d",
Jeff Brownbe1aa822011-07-27 16:04:54 -07002454 args->eventTime, args->policyFlags,
2455 args->switchCode, args->switchValue);
Jeff Brownb6997262010-10-08 22:31:17 -07002456#endif
2457
Jeff Brownbe1aa822011-07-27 16:04:54 -07002458 uint32_t policyFlags = args->policyFlags;
Jeff Browne20c9e02010-10-11 14:20:19 -07002459 policyFlags |= POLICY_FLAG_TRUSTED;
Jeff Brownbe1aa822011-07-27 16:04:54 -07002460 mPolicy->notifySwitch(args->eventTime,
2461 args->switchCode, args->switchValue, policyFlags);
Jeff Brownb6997262010-10-08 22:31:17 -07002462}
2463
Jeff Brown65fd2512011-08-18 11:20:58 -07002464void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
2465#if DEBUG_INBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00002466 ALOGD("notifyDeviceReset - eventTime=%lld, deviceId=%d",
Jeff Brown65fd2512011-08-18 11:20:58 -07002467 args->eventTime, args->deviceId);
2468#endif
2469
2470 bool needWake;
2471 { // acquire lock
2472 AutoMutex _l(mLock);
2473
2474 DeviceResetEntry* newEntry = new DeviceResetEntry(args->eventTime, args->deviceId);
2475 needWake = enqueueInboundEventLocked(newEntry);
2476 } // release lock
2477
2478 if (needWake) {
2479 mLooper->wake();
2480 }
2481}
2482
Jeff Brown7fbdc842010-06-17 20:52:56 -07002483int32_t InputDispatcher::injectInputEvent(const InputEvent* event,
Jeff Brown0029c662011-03-30 02:25:18 -07002484 int32_t injectorPid, int32_t injectorUid, int32_t syncMode, int32_t timeoutMillis,
2485 uint32_t policyFlags) {
Jeff Brown7fbdc842010-06-17 20:52:56 -07002486#if DEBUG_INBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00002487 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Jeff Brown0029c662011-03-30 02:25:18 -07002488 "syncMode=%d, timeoutMillis=%d, policyFlags=0x%08x",
2489 event->getType(), injectorPid, injectorUid, syncMode, timeoutMillis, policyFlags);
Jeff Brown7fbdc842010-06-17 20:52:56 -07002490#endif
2491
2492 nsecs_t endTime = now() + milliseconds_to_nanoseconds(timeoutMillis);
Jeff Browne20c9e02010-10-11 14:20:19 -07002493
Jeff Brown0029c662011-03-30 02:25:18 -07002494 policyFlags |= POLICY_FLAG_INJECTED;
Jeff Browne20c9e02010-10-11 14:20:19 -07002495 if (hasInjectionPermission(injectorPid, injectorUid)) {
2496 policyFlags |= POLICY_FLAG_TRUSTED;
2497 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07002498
Jeff Brown3241b6b2012-02-03 15:08:02 -08002499 EventEntry* firstInjectedEntry;
2500 EventEntry* lastInjectedEntry;
Jeff Brownb6997262010-10-08 22:31:17 -07002501 switch (event->getType()) {
2502 case AINPUT_EVENT_TYPE_KEY: {
2503 const KeyEvent* keyEvent = static_cast<const KeyEvent*>(event);
2504 int32_t action = keyEvent->getAction();
2505 if (! validateKeyEvent(action)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07002506 return INPUT_EVENT_INJECTION_FAILED;
2507 }
2508
Jeff Brownb6997262010-10-08 22:31:17 -07002509 int32_t flags = keyEvent->getFlags();
Jeff Brown1f245102010-11-18 20:53:46 -08002510 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
2511 policyFlags |= POLICY_FLAG_VIRTUAL;
2512 }
2513
Jeff Brown0029c662011-03-30 02:25:18 -07002514 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
2515 mPolicy->interceptKeyBeforeQueueing(keyEvent, /*byref*/ policyFlags);
2516 }
Jeff Brown1f245102010-11-18 20:53:46 -08002517
2518 if (policyFlags & POLICY_FLAG_WOKE_HERE) {
2519 flags |= AKEY_EVENT_FLAG_WOKE_HERE;
2520 }
Jeff Brown6ec402b2010-07-28 15:48:59 -07002521
Jeff Brownb6997262010-10-08 22:31:17 -07002522 mLock.lock();
Jeff Brown3241b6b2012-02-03 15:08:02 -08002523 firstInjectedEntry = new KeyEntry(keyEvent->getEventTime(),
Jeff Brown1f245102010-11-18 20:53:46 -08002524 keyEvent->getDeviceId(), keyEvent->getSource(),
2525 policyFlags, action, flags,
2526 keyEvent->getKeyCode(), keyEvent->getScanCode(), keyEvent->getMetaState(),
Jeff Brownb6997262010-10-08 22:31:17 -07002527 keyEvent->getRepeatCount(), keyEvent->getDownTime());
Jeff Brown3241b6b2012-02-03 15:08:02 -08002528 lastInjectedEntry = firstInjectedEntry;
Jeff Brownb6997262010-10-08 22:31:17 -07002529 break;
2530 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07002531
Jeff Brownb6997262010-10-08 22:31:17 -07002532 case AINPUT_EVENT_TYPE_MOTION: {
2533 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
2534 int32_t action = motionEvent->getAction();
2535 size_t pointerCount = motionEvent->getPointerCount();
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002536 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
2537 if (! validateMotionEvent(action, pointerCount, pointerProperties)) {
Jeff Brownb6997262010-10-08 22:31:17 -07002538 return INPUT_EVENT_INJECTION_FAILED;
2539 }
2540
Jeff Brown0029c662011-03-30 02:25:18 -07002541 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
2542 nsecs_t eventTime = motionEvent->getEventTime();
2543 mPolicy->interceptMotionBeforeQueueing(eventTime, /*byref*/ policyFlags);
2544 }
Jeff Brownb6997262010-10-08 22:31:17 -07002545
2546 mLock.lock();
2547 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
2548 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
Jeff Brown3241b6b2012-02-03 15:08:02 -08002549 firstInjectedEntry = new MotionEntry(*sampleEventTimes,
Jeff Brownb6997262010-10-08 22:31:17 -07002550 motionEvent->getDeviceId(), motionEvent->getSource(), policyFlags,
2551 action, motionEvent->getFlags(),
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002552 motionEvent->getMetaState(), motionEvent->getButtonState(),
2553 motionEvent->getEdgeFlags(),
Jeff Brownb6997262010-10-08 22:31:17 -07002554 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
2555 motionEvent->getDownTime(), uint32_t(pointerCount),
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002556 pointerProperties, samplePointerCoords);
Jeff Brown3241b6b2012-02-03 15:08:02 -08002557 lastInjectedEntry = firstInjectedEntry;
Jeff Brownb6997262010-10-08 22:31:17 -07002558 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
2559 sampleEventTimes += 1;
2560 samplePointerCoords += pointerCount;
Jeff Brown3241b6b2012-02-03 15:08:02 -08002561 MotionEntry* nextInjectedEntry = new MotionEntry(*sampleEventTimes,
2562 motionEvent->getDeviceId(), motionEvent->getSource(), policyFlags,
2563 action, motionEvent->getFlags(),
2564 motionEvent->getMetaState(), motionEvent->getButtonState(),
2565 motionEvent->getEdgeFlags(),
2566 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
2567 motionEvent->getDownTime(), uint32_t(pointerCount),
2568 pointerProperties, samplePointerCoords);
2569 lastInjectedEntry->next = nextInjectedEntry;
2570 lastInjectedEntry = nextInjectedEntry;
Jeff Brownb6997262010-10-08 22:31:17 -07002571 }
Jeff Brownb6997262010-10-08 22:31:17 -07002572 break;
2573 }
2574
2575 default:
Steve Block8564c8d2012-01-05 23:22:43 +00002576 ALOGW("Cannot inject event of type %d", event->getType());
Jeff Brownb6997262010-10-08 22:31:17 -07002577 return INPUT_EVENT_INJECTION_FAILED;
2578 }
2579
Jeff Brownac386072011-07-20 15:19:50 -07002580 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
Jeff Brownb6997262010-10-08 22:31:17 -07002581 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
2582 injectionState->injectionIsAsync = true;
2583 }
2584
2585 injectionState->refCount += 1;
Jeff Brown3241b6b2012-02-03 15:08:02 -08002586 lastInjectedEntry->injectionState = injectionState;
Jeff Brownb6997262010-10-08 22:31:17 -07002587
Jeff Brown3241b6b2012-02-03 15:08:02 -08002588 bool needWake = false;
2589 for (EventEntry* entry = firstInjectedEntry; entry != NULL; ) {
2590 EventEntry* nextEntry = entry->next;
2591 needWake |= enqueueInboundEventLocked(entry);
2592 entry = nextEntry;
2593 }
2594
Jeff Brownb6997262010-10-08 22:31:17 -07002595 mLock.unlock();
Jeff Brown7fbdc842010-06-17 20:52:56 -07002596
Jeff Brownb88102f2010-09-08 11:49:43 -07002597 if (needWake) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002598 mLooper->wake();
Jeff Brown7fbdc842010-06-17 20:52:56 -07002599 }
2600
2601 int32_t injectionResult;
2602 { // acquire lock
2603 AutoMutex _l(mLock);
2604
Jeff Brown6ec402b2010-07-28 15:48:59 -07002605 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
2606 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
2607 } else {
2608 for (;;) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002609 injectionResult = injectionState->injectionResult;
Jeff Brown6ec402b2010-07-28 15:48:59 -07002610 if (injectionResult != INPUT_EVENT_INJECTION_PENDING) {
2611 break;
2612 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07002613
Jeff Brown7fbdc842010-06-17 20:52:56 -07002614 nsecs_t remainingTimeout = endTime - now();
2615 if (remainingTimeout <= 0) {
Jeff Brown6ec402b2010-07-28 15:48:59 -07002616#if DEBUG_INJECTION
Steve Block5baa3a62011-12-20 16:23:08 +00002617 ALOGD("injectInputEvent - Timed out waiting for injection result "
Jeff Brown6ec402b2010-07-28 15:48:59 -07002618 "to become available.");
2619#endif
Jeff Brown7fbdc842010-06-17 20:52:56 -07002620 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
2621 break;
2622 }
2623
Jeff Brown6ec402b2010-07-28 15:48:59 -07002624 mInjectionResultAvailableCondition.waitRelative(mLock, remainingTimeout);
2625 }
2626
2627 if (injectionResult == INPUT_EVENT_INJECTION_SUCCEEDED
2628 && syncMode == INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002629 while (injectionState->pendingForegroundDispatches != 0) {
Jeff Brown6ec402b2010-07-28 15:48:59 -07002630#if DEBUG_INJECTION
Steve Block5baa3a62011-12-20 16:23:08 +00002631 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
Jeff Brown01ce2e92010-09-26 22:20:12 -07002632 injectionState->pendingForegroundDispatches);
Jeff Brown6ec402b2010-07-28 15:48:59 -07002633#endif
2634 nsecs_t remainingTimeout = endTime - now();
2635 if (remainingTimeout <= 0) {
2636#if DEBUG_INJECTION
Steve Block5baa3a62011-12-20 16:23:08 +00002637 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
Jeff Brown6ec402b2010-07-28 15:48:59 -07002638 "dispatches to finish.");
2639#endif
2640 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
2641 break;
2642 }
2643
2644 mInjectionSyncFinishedCondition.waitRelative(mLock, remainingTimeout);
2645 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07002646 }
2647 }
2648
Jeff Brownac386072011-07-20 15:19:50 -07002649 injectionState->release();
Jeff Brown7fbdc842010-06-17 20:52:56 -07002650 } // release lock
2651
Jeff Brown6ec402b2010-07-28 15:48:59 -07002652#if DEBUG_INJECTION
Steve Block5baa3a62011-12-20 16:23:08 +00002653 ALOGD("injectInputEvent - Finished with result %d. "
Jeff Brown6ec402b2010-07-28 15:48:59 -07002654 "injectorPid=%d, injectorUid=%d",
2655 injectionResult, injectorPid, injectorUid);
2656#endif
2657
Jeff Brown7fbdc842010-06-17 20:52:56 -07002658 return injectionResult;
2659}
2660
Jeff Brownb6997262010-10-08 22:31:17 -07002661bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
2662 return injectorUid == 0
2663 || mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
2664}
2665
Jeff Brown7fbdc842010-06-17 20:52:56 -07002666void InputDispatcher::setInjectionResultLocked(EventEntry* entry, int32_t injectionResult) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002667 InjectionState* injectionState = entry->injectionState;
2668 if (injectionState) {
Jeff Brown7fbdc842010-06-17 20:52:56 -07002669#if DEBUG_INJECTION
Steve Block5baa3a62011-12-20 16:23:08 +00002670 ALOGD("Setting input event injection result to %d. "
Jeff Brown7fbdc842010-06-17 20:52:56 -07002671 "injectorPid=%d, injectorUid=%d",
Jeff Brown01ce2e92010-09-26 22:20:12 -07002672 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
Jeff Brown7fbdc842010-06-17 20:52:56 -07002673#endif
2674
Jeff Brown0029c662011-03-30 02:25:18 -07002675 if (injectionState->injectionIsAsync
2676 && !(entry->policyFlags & POLICY_FLAG_FILTERED)) {
Jeff Brown6ec402b2010-07-28 15:48:59 -07002677 // Log the outcome since the injector did not wait for the injection result.
2678 switch (injectionResult) {
2679 case INPUT_EVENT_INJECTION_SUCCEEDED:
Steve Block71f2cf12011-10-20 11:56:00 +01002680 ALOGV("Asynchronous input event injection succeeded.");
Jeff Brown6ec402b2010-07-28 15:48:59 -07002681 break;
2682 case INPUT_EVENT_INJECTION_FAILED:
Steve Block8564c8d2012-01-05 23:22:43 +00002683 ALOGW("Asynchronous input event injection failed.");
Jeff Brown6ec402b2010-07-28 15:48:59 -07002684 break;
2685 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
Steve Block8564c8d2012-01-05 23:22:43 +00002686 ALOGW("Asynchronous input event injection permission denied.");
Jeff Brown6ec402b2010-07-28 15:48:59 -07002687 break;
2688 case INPUT_EVENT_INJECTION_TIMED_OUT:
Steve Block8564c8d2012-01-05 23:22:43 +00002689 ALOGW("Asynchronous input event injection timed out.");
Jeff Brown6ec402b2010-07-28 15:48:59 -07002690 break;
2691 }
2692 }
2693
Jeff Brown01ce2e92010-09-26 22:20:12 -07002694 injectionState->injectionResult = injectionResult;
Jeff Brown7fbdc842010-06-17 20:52:56 -07002695 mInjectionResultAvailableCondition.broadcast();
2696 }
2697}
2698
Jeff Brown01ce2e92010-09-26 22:20:12 -07002699void InputDispatcher::incrementPendingForegroundDispatchesLocked(EventEntry* entry) {
2700 InjectionState* injectionState = entry->injectionState;
2701 if (injectionState) {
2702 injectionState->pendingForegroundDispatches += 1;
2703 }
2704}
2705
Jeff Brown519e0242010-09-15 15:18:56 -07002706void InputDispatcher::decrementPendingForegroundDispatchesLocked(EventEntry* entry) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002707 InjectionState* injectionState = entry->injectionState;
2708 if (injectionState) {
2709 injectionState->pendingForegroundDispatches -= 1;
Jeff Brown6ec402b2010-07-28 15:48:59 -07002710
Jeff Brown01ce2e92010-09-26 22:20:12 -07002711 if (injectionState->pendingForegroundDispatches == 0) {
2712 mInjectionSyncFinishedCondition.broadcast();
2713 }
Jeff Brownb88102f2010-09-08 11:49:43 -07002714 }
2715}
2716
Jeff Brown9302c872011-07-13 22:51:29 -07002717sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
2718 const sp<InputChannel>& inputChannel) const {
2719 size_t numWindows = mWindowHandles.size();
2720 for (size_t i = 0; i < numWindows; i++) {
2721 const sp<InputWindowHandle>& windowHandle = mWindowHandles.itemAt(i);
Jeff Browncc4f7db2011-08-30 20:34:48 -07002722 if (windowHandle->getInputChannel() == inputChannel) {
Jeff Brown9302c872011-07-13 22:51:29 -07002723 return windowHandle;
Jeff Brown01ce2e92010-09-26 22:20:12 -07002724 }
2725 }
2726 return NULL;
2727}
2728
Jeff Brown9302c872011-07-13 22:51:29 -07002729bool InputDispatcher::hasWindowHandleLocked(
2730 const sp<InputWindowHandle>& windowHandle) const {
2731 size_t numWindows = mWindowHandles.size();
2732 for (size_t i = 0; i < numWindows; i++) {
2733 if (mWindowHandles.itemAt(i) == windowHandle) {
2734 return true;
2735 }
2736 }
2737 return false;
2738}
2739
2740void InputDispatcher::setInputWindows(const Vector<sp<InputWindowHandle> >& inputWindowHandles) {
Jeff Brownb88102f2010-09-08 11:49:43 -07002741#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002742 ALOGD("setInputWindows");
Jeff Brownb88102f2010-09-08 11:49:43 -07002743#endif
2744 { // acquire lock
2745 AutoMutex _l(mLock);
2746
Jeff Browncc4f7db2011-08-30 20:34:48 -07002747 Vector<sp<InputWindowHandle> > oldWindowHandles = mWindowHandles;
Jeff Brown9302c872011-07-13 22:51:29 -07002748 mWindowHandles = inputWindowHandles;
Jeff Brownb6997262010-10-08 22:31:17 -07002749
Jeff Brown9302c872011-07-13 22:51:29 -07002750 sp<InputWindowHandle> newFocusedWindowHandle;
2751 bool foundHoveredWindow = false;
2752 for (size_t i = 0; i < mWindowHandles.size(); i++) {
2753 const sp<InputWindowHandle>& windowHandle = mWindowHandles.itemAt(i);
Jeff Browncc4f7db2011-08-30 20:34:48 -07002754 if (!windowHandle->updateInfo() || windowHandle->getInputChannel() == NULL) {
Jeff Brown9302c872011-07-13 22:51:29 -07002755 mWindowHandles.removeAt(i--);
2756 continue;
2757 }
Jeff Browncc4f7db2011-08-30 20:34:48 -07002758 if (windowHandle->getInfo()->hasFocus) {
Jeff Brown9302c872011-07-13 22:51:29 -07002759 newFocusedWindowHandle = windowHandle;
2760 }
2761 if (windowHandle == mLastHoverWindowHandle) {
2762 foundHoveredWindow = true;
Jeff Brownb88102f2010-09-08 11:49:43 -07002763 }
2764 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07002765
Jeff Brown9302c872011-07-13 22:51:29 -07002766 if (!foundHoveredWindow) {
2767 mLastHoverWindowHandle = NULL;
2768 }
2769
2770 if (mFocusedWindowHandle != newFocusedWindowHandle) {
2771 if (mFocusedWindowHandle != NULL) {
Jeff Brownb6997262010-10-08 22:31:17 -07002772#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002773 ALOGD("Focus left window: %s",
Jeff Browncc4f7db2011-08-30 20:34:48 -07002774 mFocusedWindowHandle->getName().string());
Jeff Brownb6997262010-10-08 22:31:17 -07002775#endif
Jeff Browncc4f7db2011-08-30 20:34:48 -07002776 sp<InputChannel> focusedInputChannel = mFocusedWindowHandle->getInputChannel();
2777 if (focusedInputChannel != NULL) {
Christopher Tated9be36c2011-08-16 16:09:33 -07002778 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
2779 "focus left window");
2780 synthesizeCancelationEventsForInputChannelLocked(
Jeff Browncc4f7db2011-08-30 20:34:48 -07002781 focusedInputChannel, options);
Christopher Tated9be36c2011-08-16 16:09:33 -07002782 }
Jeff Brownb6997262010-10-08 22:31:17 -07002783 }
Jeff Brown9302c872011-07-13 22:51:29 -07002784 if (newFocusedWindowHandle != NULL) {
Jeff Brownb6997262010-10-08 22:31:17 -07002785#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002786 ALOGD("Focus entered window: %s",
Jeff Browncc4f7db2011-08-30 20:34:48 -07002787 newFocusedWindowHandle->getName().string());
Jeff Brownb6997262010-10-08 22:31:17 -07002788#endif
Jeff Brown9302c872011-07-13 22:51:29 -07002789 }
2790 mFocusedWindowHandle = newFocusedWindowHandle;
Jeff Brownb6997262010-10-08 22:31:17 -07002791 }
2792
Jeff Brown9302c872011-07-13 22:51:29 -07002793 for (size_t i = 0; i < mTouchState.windows.size(); i++) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002794 TouchedWindow& touchedWindow = mTouchState.windows.editItemAt(i);
Jeff Brown9302c872011-07-13 22:51:29 -07002795 if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
Jeff Brownb6997262010-10-08 22:31:17 -07002796#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002797 ALOGD("Touched window was removed: %s",
Jeff Browncc4f7db2011-08-30 20:34:48 -07002798 touchedWindow.windowHandle->getName().string());
Jeff Brownb6997262010-10-08 22:31:17 -07002799#endif
Jeff Browncc4f7db2011-08-30 20:34:48 -07002800 sp<InputChannel> touchedInputChannel =
2801 touchedWindow.windowHandle->getInputChannel();
2802 if (touchedInputChannel != NULL) {
Christopher Tated9be36c2011-08-16 16:09:33 -07002803 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
2804 "touched window was removed");
2805 synthesizeCancelationEventsForInputChannelLocked(
Jeff Browncc4f7db2011-08-30 20:34:48 -07002806 touchedInputChannel, options);
Christopher Tated9be36c2011-08-16 16:09:33 -07002807 }
Jeff Brown9302c872011-07-13 22:51:29 -07002808 mTouchState.windows.removeAt(i--);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002809 }
2810 }
Jeff Browncc4f7db2011-08-30 20:34:48 -07002811
2812 // Release information for windows that are no longer present.
2813 // This ensures that unused input channels are released promptly.
2814 // Otherwise, they might stick around until the window handle is destroyed
2815 // which might not happen until the next GC.
2816 for (size_t i = 0; i < oldWindowHandles.size(); i++) {
2817 const sp<InputWindowHandle>& oldWindowHandle = oldWindowHandles.itemAt(i);
2818 if (!hasWindowHandleLocked(oldWindowHandle)) {
2819#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002820 ALOGD("Window went away: %s", oldWindowHandle->getName().string());
Jeff Browncc4f7db2011-08-30 20:34:48 -07002821#endif
2822 oldWindowHandle->releaseInfo();
2823 }
2824 }
Jeff Brownb88102f2010-09-08 11:49:43 -07002825 } // release lock
2826
2827 // Wake up poll loop since it may need to make new input dispatching choices.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002828 mLooper->wake();
Jeff Brownb88102f2010-09-08 11:49:43 -07002829}
2830
Jeff Brown9302c872011-07-13 22:51:29 -07002831void InputDispatcher::setFocusedApplication(
2832 const sp<InputApplicationHandle>& inputApplicationHandle) {
Jeff Brownb88102f2010-09-08 11:49:43 -07002833#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002834 ALOGD("setFocusedApplication");
Jeff Brownb88102f2010-09-08 11:49:43 -07002835#endif
2836 { // acquire lock
2837 AutoMutex _l(mLock);
2838
Jeff Browncc4f7db2011-08-30 20:34:48 -07002839 if (inputApplicationHandle != NULL && inputApplicationHandle->updateInfo()) {
Jeff Brown5ea29ab2011-07-27 11:50:51 -07002840 if (mFocusedApplicationHandle != inputApplicationHandle) {
2841 if (mFocusedApplicationHandle != NULL) {
2842 resetTargetsLocked();
Jeff Browncc4f7db2011-08-30 20:34:48 -07002843 mFocusedApplicationHandle->releaseInfo();
Jeff Brown5ea29ab2011-07-27 11:50:51 -07002844 }
2845 mFocusedApplicationHandle = inputApplicationHandle;
2846 }
2847 } else if (mFocusedApplicationHandle != NULL) {
2848 resetTargetsLocked();
Jeff Browncc4f7db2011-08-30 20:34:48 -07002849 mFocusedApplicationHandle->releaseInfo();
Jeff Brown9302c872011-07-13 22:51:29 -07002850 mFocusedApplicationHandle.clear();
Jeff Brownb88102f2010-09-08 11:49:43 -07002851 }
2852
2853#if DEBUG_FOCUS
Jeff Brownb6997262010-10-08 22:31:17 -07002854 //logDispatchStateLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -07002855#endif
2856 } // release lock
2857
2858 // Wake up poll loop since it may need to make new input dispatching choices.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002859 mLooper->wake();
Jeff Brownb88102f2010-09-08 11:49:43 -07002860}
2861
Jeff Brownb88102f2010-09-08 11:49:43 -07002862void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
2863#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002864 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
Jeff Brownb88102f2010-09-08 11:49:43 -07002865#endif
2866
2867 bool changed;
2868 { // acquire lock
2869 AutoMutex _l(mLock);
2870
2871 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
Jeff Brown120a4592010-10-27 18:43:51 -07002872 if (mDispatchFrozen && !frozen) {
Jeff Brownb88102f2010-09-08 11:49:43 -07002873 resetANRTimeoutsLocked();
2874 }
2875
Jeff Brown120a4592010-10-27 18:43:51 -07002876 if (mDispatchEnabled && !enabled) {
2877 resetAndDropEverythingLocked("dispatcher is being disabled");
2878 }
2879
Jeff Brownb88102f2010-09-08 11:49:43 -07002880 mDispatchEnabled = enabled;
2881 mDispatchFrozen = frozen;
2882 changed = true;
2883 } else {
2884 changed = false;
2885 }
2886
2887#if DEBUG_FOCUS
Jeff Brownb6997262010-10-08 22:31:17 -07002888 //logDispatchStateLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -07002889#endif
2890 } // release lock
2891
2892 if (changed) {
2893 // Wake up poll loop since it may need to make new input dispatching choices.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002894 mLooper->wake();
Jeff Brown46b9ac02010-04-22 18:58:52 -07002895 }
2896}
2897
Jeff Brown0029c662011-03-30 02:25:18 -07002898void InputDispatcher::setInputFilterEnabled(bool enabled) {
2899#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002900 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
Jeff Brown0029c662011-03-30 02:25:18 -07002901#endif
2902
2903 { // acquire lock
2904 AutoMutex _l(mLock);
2905
2906 if (mInputFilterEnabled == enabled) {
2907 return;
2908 }
2909
2910 mInputFilterEnabled = enabled;
2911 resetAndDropEverythingLocked("input filter is being enabled or disabled");
2912 } // release lock
2913
2914 // Wake up poll loop since there might be work to do to drop everything.
2915 mLooper->wake();
2916}
2917
Jeff Browne6504122010-09-27 14:52:15 -07002918bool InputDispatcher::transferTouchFocus(const sp<InputChannel>& fromChannel,
2919 const sp<InputChannel>& toChannel) {
2920#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002921 ALOGD("transferTouchFocus: fromChannel=%s, toChannel=%s",
Jeff Browne6504122010-09-27 14:52:15 -07002922 fromChannel->getName().string(), toChannel->getName().string());
2923#endif
2924 { // acquire lock
2925 AutoMutex _l(mLock);
2926
Jeff Brown9302c872011-07-13 22:51:29 -07002927 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromChannel);
2928 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toChannel);
2929 if (fromWindowHandle == NULL || toWindowHandle == NULL) {
Jeff Browne6504122010-09-27 14:52:15 -07002930#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002931 ALOGD("Cannot transfer focus because from or to window not found.");
Jeff Browne6504122010-09-27 14:52:15 -07002932#endif
2933 return false;
2934 }
Jeff Brown9302c872011-07-13 22:51:29 -07002935 if (fromWindowHandle == toWindowHandle) {
Jeff Browne6504122010-09-27 14:52:15 -07002936#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002937 ALOGD("Trivial transfer to same window.");
Jeff Browne6504122010-09-27 14:52:15 -07002938#endif
2939 return true;
2940 }
2941
2942 bool found = false;
2943 for (size_t i = 0; i < mTouchState.windows.size(); i++) {
2944 const TouchedWindow& touchedWindow = mTouchState.windows[i];
Jeff Brown9302c872011-07-13 22:51:29 -07002945 if (touchedWindow.windowHandle == fromWindowHandle) {
Jeff Browne6504122010-09-27 14:52:15 -07002946 int32_t oldTargetFlags = touchedWindow.targetFlags;
2947 BitSet32 pointerIds = touchedWindow.pointerIds;
2948
2949 mTouchState.windows.removeAt(i);
2950
Jeff Brown46e75292010-11-10 16:53:45 -08002951 int32_t newTargetFlags = oldTargetFlags
Jeff Browna032cc02011-03-07 16:56:21 -08002952 & (InputTarget::FLAG_FOREGROUND
2953 | InputTarget::FLAG_SPLIT | InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brown9302c872011-07-13 22:51:29 -07002954 mTouchState.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Jeff Browne6504122010-09-27 14:52:15 -07002955
2956 found = true;
2957 break;
2958 }
2959 }
2960
2961 if (! found) {
2962#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002963 ALOGD("Focus transfer failed because from window did not have focus.");
Jeff Browne6504122010-09-27 14:52:15 -07002964#endif
2965 return false;
2966 }
2967
Jeff Brown9c9f1a32010-10-11 18:32:20 -07002968 ssize_t fromConnectionIndex = getConnectionIndexLocked(fromChannel);
2969 ssize_t toConnectionIndex = getConnectionIndexLocked(toChannel);
2970 if (fromConnectionIndex >= 0 && toConnectionIndex >= 0) {
2971 sp<Connection> fromConnection = mConnectionsByReceiveFd.valueAt(fromConnectionIndex);
2972 sp<Connection> toConnection = mConnectionsByReceiveFd.valueAt(toConnectionIndex);
2973
2974 fromConnection->inputState.copyPointerStateTo(toConnection->inputState);
Jeff Brownda3d5a92011-03-29 15:11:34 -07002975 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Jeff Brown9c9f1a32010-10-11 18:32:20 -07002976 "transferring touch focus from this window to another window");
Jeff Brownda3d5a92011-03-29 15:11:34 -07002977 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Jeff Brown9c9f1a32010-10-11 18:32:20 -07002978 }
2979
Jeff Browne6504122010-09-27 14:52:15 -07002980#if DEBUG_FOCUS
2981 logDispatchStateLocked();
2982#endif
2983 } // release lock
2984
2985 // Wake up poll loop since it may need to make new input dispatching choices.
2986 mLooper->wake();
2987 return true;
2988}
2989
Jeff Brown120a4592010-10-27 18:43:51 -07002990void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
2991#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002992 ALOGD("Resetting and dropping all events (%s).", reason);
Jeff Brown120a4592010-10-27 18:43:51 -07002993#endif
2994
Jeff Brownda3d5a92011-03-29 15:11:34 -07002995 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
2996 synthesizeCancelationEventsForAllConnectionsLocked(options);
Jeff Brown120a4592010-10-27 18:43:51 -07002997
2998 resetKeyRepeatLocked();
2999 releasePendingEventLocked();
3000 drainInboundQueueLocked();
3001 resetTargetsLocked();
3002
3003 mTouchState.reset();
Jeff Brown9302c872011-07-13 22:51:29 -07003004 mLastHoverWindowHandle.clear();
Jeff Brown120a4592010-10-27 18:43:51 -07003005}
3006
Jeff Brownb88102f2010-09-08 11:49:43 -07003007void InputDispatcher::logDispatchStateLocked() {
3008 String8 dump;
3009 dumpDispatchStateLocked(dump);
Jeff Brown2a95c2a2010-09-16 12:31:46 -07003010
3011 char* text = dump.lockBuffer(dump.size());
3012 char* start = text;
3013 while (*start != '\0') {
3014 char* end = strchr(start, '\n');
3015 if (*end == '\n') {
3016 *(end++) = '\0';
3017 }
Steve Block5baa3a62011-12-20 16:23:08 +00003018 ALOGD("%s", start);
Jeff Brown2a95c2a2010-09-16 12:31:46 -07003019 start = end;
3020 }
Jeff Brownb88102f2010-09-08 11:49:43 -07003021}
3022
3023void InputDispatcher::dumpDispatchStateLocked(String8& dump) {
Jeff Brownf2f487182010-10-01 17:46:21 -07003024 dump.appendFormat(INDENT "DispatchEnabled: %d\n", mDispatchEnabled);
3025 dump.appendFormat(INDENT "DispatchFrozen: %d\n", mDispatchFrozen);
Jeff Brownb88102f2010-09-08 11:49:43 -07003026
Jeff Brown9302c872011-07-13 22:51:29 -07003027 if (mFocusedApplicationHandle != NULL) {
Jeff Brownf2f487182010-10-01 17:46:21 -07003028 dump.appendFormat(INDENT "FocusedApplication: name='%s', dispatchingTimeout=%0.3fms\n",
Jeff Browncc4f7db2011-08-30 20:34:48 -07003029 mFocusedApplicationHandle->getName().string(),
3030 mFocusedApplicationHandle->getDispatchingTimeout(
3031 DEFAULT_INPUT_DISPATCHING_TIMEOUT) / 1000000.0);
Jeff Brownb88102f2010-09-08 11:49:43 -07003032 } else {
Jeff Brownf2f487182010-10-01 17:46:21 -07003033 dump.append(INDENT "FocusedApplication: <null>\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003034 }
Jeff Brownf2f487182010-10-01 17:46:21 -07003035 dump.appendFormat(INDENT "FocusedWindow: name='%s'\n",
Jeff Browncc4f7db2011-08-30 20:34:48 -07003036 mFocusedWindowHandle != NULL ? mFocusedWindowHandle->getName().string() : "<null>");
Jeff Brownf2f487182010-10-01 17:46:21 -07003037
3038 dump.appendFormat(INDENT "TouchDown: %s\n", toString(mTouchState.down));
3039 dump.appendFormat(INDENT "TouchSplit: %s\n", toString(mTouchState.split));
Jeff Brown95712852011-01-04 19:41:59 -08003040 dump.appendFormat(INDENT "TouchDeviceId: %d\n", mTouchState.deviceId);
Jeff Brown58a2da82011-01-25 16:02:22 -08003041 dump.appendFormat(INDENT "TouchSource: 0x%08x\n", mTouchState.source);
Jeff Brownf2f487182010-10-01 17:46:21 -07003042 if (!mTouchState.windows.isEmpty()) {
3043 dump.append(INDENT "TouchedWindows:\n");
3044 for (size_t i = 0; i < mTouchState.windows.size(); i++) {
3045 const TouchedWindow& touchedWindow = mTouchState.windows[i];
3046 dump.appendFormat(INDENT2 "%d: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
Jeff Browncc4f7db2011-08-30 20:34:48 -07003047 i, touchedWindow.windowHandle->getName().string(),
3048 touchedWindow.pointerIds.value,
Jeff Brownf2f487182010-10-01 17:46:21 -07003049 touchedWindow.targetFlags);
3050 }
3051 } else {
3052 dump.append(INDENT "TouchedWindows: <none>\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003053 }
3054
Jeff Brown9302c872011-07-13 22:51:29 -07003055 if (!mWindowHandles.isEmpty()) {
Jeff Brownf2f487182010-10-01 17:46:21 -07003056 dump.append(INDENT "Windows:\n");
Jeff Brown9302c872011-07-13 22:51:29 -07003057 for (size_t i = 0; i < mWindowHandles.size(); i++) {
3058 const sp<InputWindowHandle>& windowHandle = mWindowHandles.itemAt(i);
Jeff Browncc4f7db2011-08-30 20:34:48 -07003059 const InputWindowInfo* windowInfo = windowHandle->getInfo();
3060
Jeff Brownf2f487182010-10-01 17:46:21 -07003061 dump.appendFormat(INDENT2 "%d: name='%s', paused=%s, hasFocus=%s, hasWallpaper=%s, "
3062 "visible=%s, canReceiveKeys=%s, flags=0x%08x, type=0x%08x, layer=%d, "
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003063 "frame=[%d,%d][%d,%d], scale=%f, "
Jeff Brownfbf09772011-01-16 14:06:57 -08003064 "touchableRegion=",
Jeff Browncc4f7db2011-08-30 20:34:48 -07003065 i, windowInfo->name.string(),
3066 toString(windowInfo->paused),
3067 toString(windowInfo->hasFocus),
3068 toString(windowInfo->hasWallpaper),
3069 toString(windowInfo->visible),
3070 toString(windowInfo->canReceiveKeys),
3071 windowInfo->layoutParamsFlags, windowInfo->layoutParamsType,
3072 windowInfo->layer,
3073 windowInfo->frameLeft, windowInfo->frameTop,
3074 windowInfo->frameRight, windowInfo->frameBottom,
3075 windowInfo->scaleFactor);
3076 dumpRegion(dump, windowInfo->touchableRegion);
3077 dump.appendFormat(", inputFeatures=0x%08x", windowInfo->inputFeatures);
Jeff Brownfbf09772011-01-16 14:06:57 -08003078 dump.appendFormat(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%0.3fms\n",
Jeff Browncc4f7db2011-08-30 20:34:48 -07003079 windowInfo->ownerPid, windowInfo->ownerUid,
3080 windowInfo->dispatchingTimeout / 1000000.0);
Jeff Brownf2f487182010-10-01 17:46:21 -07003081 }
3082 } else {
3083 dump.append(INDENT "Windows: <none>\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003084 }
3085
Jeff Brownf2f487182010-10-01 17:46:21 -07003086 if (!mMonitoringChannels.isEmpty()) {
3087 dump.append(INDENT "MonitoringChannels:\n");
3088 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
3089 const sp<InputChannel>& channel = mMonitoringChannels[i];
3090 dump.appendFormat(INDENT2 "%d: '%s'\n", i, channel->getName().string());
3091 }
3092 } else {
3093 dump.append(INDENT "MonitoringChannels: <none>\n");
3094 }
Jeff Brown519e0242010-09-15 15:18:56 -07003095
Jeff Brownf2f487182010-10-01 17:46:21 -07003096 dump.appendFormat(INDENT "InboundQueue: length=%u\n", mInboundQueue.count());
3097
3098 if (!mActiveConnections.isEmpty()) {
3099 dump.append(INDENT "ActiveConnections:\n");
3100 for (size_t i = 0; i < mActiveConnections.size(); i++) {
3101 const Connection* connection = mActiveConnections[i];
Jeff Brown76860e32010-10-25 17:37:46 -07003102 dump.appendFormat(INDENT2 "%d: '%s', status=%s, outboundQueueLength=%u, "
Jeff Brownb6997262010-10-08 22:31:17 -07003103 "inputState.isNeutral=%s\n",
Jeff Brownf2f487182010-10-01 17:46:21 -07003104 i, connection->getInputChannelName(), connection->getStatusLabel(),
3105 connection->outboundQueue.count(),
Jeff Brownb6997262010-10-08 22:31:17 -07003106 toString(connection->inputState.isNeutral()));
Jeff Brownf2f487182010-10-01 17:46:21 -07003107 }
3108 } else {
3109 dump.append(INDENT "ActiveConnections: <none>\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003110 }
3111
3112 if (isAppSwitchPendingLocked()) {
Jeff Brownf2f487182010-10-01 17:46:21 -07003113 dump.appendFormat(INDENT "AppSwitch: pending, due in %01.1fms\n",
Jeff Brownb88102f2010-09-08 11:49:43 -07003114 (mAppSwitchDueTime - now()) / 1000000.0);
3115 } else {
Jeff Brownf2f487182010-10-01 17:46:21 -07003116 dump.append(INDENT "AppSwitch: not pending\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003117 }
3118}
3119
Jeff Brown928e0542011-01-10 11:17:36 -08003120status_t InputDispatcher::registerInputChannel(const sp<InputChannel>& inputChannel,
3121 const sp<InputWindowHandle>& inputWindowHandle, bool monitor) {
Jeff Brown9c3cda02010-06-15 01:31:58 -07003122#if DEBUG_REGISTRATION
Steve Block5baa3a62011-12-20 16:23:08 +00003123 ALOGD("channel '%s' ~ registerInputChannel - monitor=%s", inputChannel->getName().string(),
Jeff Brownb88102f2010-09-08 11:49:43 -07003124 toString(monitor));
Jeff Brown9c3cda02010-06-15 01:31:58 -07003125#endif
3126
Jeff Brown46b9ac02010-04-22 18:58:52 -07003127 { // acquire lock
3128 AutoMutex _l(mLock);
3129
Jeff Brown519e0242010-09-15 15:18:56 -07003130 if (getConnectionIndexLocked(inputChannel) >= 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00003131 ALOGW("Attempted to register already registered input channel '%s'",
Jeff Brown46b9ac02010-04-22 18:58:52 -07003132 inputChannel->getName().string());
3133 return BAD_VALUE;
3134 }
3135
Jeff Browncc4f7db2011-08-30 20:34:48 -07003136 sp<Connection> connection = new Connection(inputChannel, inputWindowHandle, monitor);
Jeff Brown46b9ac02010-04-22 18:58:52 -07003137 status_t status = connection->initialize();
3138 if (status) {
Steve Block3762c312012-01-06 19:20:56 +00003139 ALOGE("Failed to initialize input publisher for input channel '%s', status=%d",
Jeff Brown46b9ac02010-04-22 18:58:52 -07003140 inputChannel->getName().string(), status);
3141 return status;
3142 }
3143
Jeff Brown2cbecea2010-08-17 15:59:26 -07003144 int32_t receiveFd = inputChannel->getReceivePipeFd();
Jeff Brown46b9ac02010-04-22 18:58:52 -07003145 mConnectionsByReceiveFd.add(receiveFd, connection);
Jeff Brown9c3cda02010-06-15 01:31:58 -07003146
Jeff Brownb88102f2010-09-08 11:49:43 -07003147 if (monitor) {
3148 mMonitoringChannels.push(inputChannel);
3149 }
3150
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07003151 mLooper->addFd(receiveFd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
Jeff Brown2cbecea2010-08-17 15:59:26 -07003152
Jeff Brown9c3cda02010-06-15 01:31:58 -07003153 runCommandsLockedInterruptible();
Jeff Brown46b9ac02010-04-22 18:58:52 -07003154 } // release lock
Jeff Brown46b9ac02010-04-22 18:58:52 -07003155 return OK;
3156}
3157
3158status_t InputDispatcher::unregisterInputChannel(const sp<InputChannel>& inputChannel) {
Jeff Brown9c3cda02010-06-15 01:31:58 -07003159#if DEBUG_REGISTRATION
Steve Block5baa3a62011-12-20 16:23:08 +00003160 ALOGD("channel '%s' ~ unregisterInputChannel", inputChannel->getName().string());
Jeff Brown9c3cda02010-06-15 01:31:58 -07003161#endif
3162
Jeff Brown46b9ac02010-04-22 18:58:52 -07003163 { // acquire lock
3164 AutoMutex _l(mLock);
3165
Jeff Browncc4f7db2011-08-30 20:34:48 -07003166 status_t status = unregisterInputChannelLocked(inputChannel, false /*notify*/);
3167 if (status) {
3168 return status;
Jeff Brown46b9ac02010-04-22 18:58:52 -07003169 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07003170 } // release lock
3171
Jeff Brown46b9ac02010-04-22 18:58:52 -07003172 // Wake the poll loop because removing the connection may have changed the current
3173 // synchronization state.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07003174 mLooper->wake();
Jeff Brown46b9ac02010-04-22 18:58:52 -07003175 return OK;
3176}
3177
Jeff Browncc4f7db2011-08-30 20:34:48 -07003178status_t InputDispatcher::unregisterInputChannelLocked(const sp<InputChannel>& inputChannel,
3179 bool notify) {
3180 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
3181 if (connectionIndex < 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00003182 ALOGW("Attempted to unregister already unregistered input channel '%s'",
Jeff Browncc4f7db2011-08-30 20:34:48 -07003183 inputChannel->getName().string());
3184 return BAD_VALUE;
3185 }
3186
3187 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
3188 mConnectionsByReceiveFd.removeItemsAt(connectionIndex);
3189
3190 if (connection->monitor) {
3191 removeMonitorChannelLocked(inputChannel);
3192 }
3193
3194 mLooper->removeFd(inputChannel->getReceivePipeFd());
3195
3196 nsecs_t currentTime = now();
3197 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
3198
3199 runCommandsLockedInterruptible();
3200
3201 connection->status = Connection::STATUS_ZOMBIE;
3202 return OK;
3203}
3204
3205void InputDispatcher::removeMonitorChannelLocked(const sp<InputChannel>& inputChannel) {
3206 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
3207 if (mMonitoringChannels[i] == inputChannel) {
3208 mMonitoringChannels.removeAt(i);
3209 break;
3210 }
3211 }
3212}
3213
Jeff Brown519e0242010-09-15 15:18:56 -07003214ssize_t InputDispatcher::getConnectionIndexLocked(const sp<InputChannel>& inputChannel) {
Jeff Brown2cbecea2010-08-17 15:59:26 -07003215 ssize_t connectionIndex = mConnectionsByReceiveFd.indexOfKey(inputChannel->getReceivePipeFd());
3216 if (connectionIndex >= 0) {
3217 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
3218 if (connection->inputChannel.get() == inputChannel.get()) {
3219 return connectionIndex;
3220 }
3221 }
3222
3223 return -1;
3224}
3225
Jeff Brown46b9ac02010-04-22 18:58:52 -07003226void InputDispatcher::activateConnectionLocked(Connection* connection) {
3227 for (size_t i = 0; i < mActiveConnections.size(); i++) {
3228 if (mActiveConnections.itemAt(i) == connection) {
3229 return;
3230 }
3231 }
3232 mActiveConnections.add(connection);
3233}
3234
3235void InputDispatcher::deactivateConnectionLocked(Connection* connection) {
3236 for (size_t i = 0; i < mActiveConnections.size(); i++) {
3237 if (mActiveConnections.itemAt(i) == connection) {
3238 mActiveConnections.removeAt(i);
3239 return;
3240 }
3241 }
3242}
3243
Jeff Brown9c3cda02010-06-15 01:31:58 -07003244void InputDispatcher::onDispatchCycleStartedLocked(
Jeff Brown7fbdc842010-06-17 20:52:56 -07003245 nsecs_t currentTime, const sp<Connection>& connection) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07003246}
3247
Jeff Brown9c3cda02010-06-15 01:31:58 -07003248void InputDispatcher::onDispatchCycleFinishedLocked(
Jeff Brown3915bb82010-11-05 15:02:16 -07003249 nsecs_t currentTime, const sp<Connection>& connection, bool handled) {
3250 CommandEntry* commandEntry = postCommandLocked(
3251 & InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
3252 commandEntry->connection = connection;
3253 commandEntry->handled = handled;
Jeff Brown46b9ac02010-04-22 18:58:52 -07003254}
3255
Jeff Brown9c3cda02010-06-15 01:31:58 -07003256void InputDispatcher::onDispatchCycleBrokenLocked(
Jeff Brown7fbdc842010-06-17 20:52:56 -07003257 nsecs_t currentTime, const sp<Connection>& connection) {
Steve Block3762c312012-01-06 19:20:56 +00003258 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Jeff Brown46b9ac02010-04-22 18:58:52 -07003259 connection->getInputChannelName());
3260
Jeff Brown9c3cda02010-06-15 01:31:58 -07003261 CommandEntry* commandEntry = postCommandLocked(
3262 & InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
Jeff Brown7fbdc842010-06-17 20:52:56 -07003263 commandEntry->connection = connection;
Jeff Brown46b9ac02010-04-22 18:58:52 -07003264}
3265
Jeff Brown519e0242010-09-15 15:18:56 -07003266void InputDispatcher::onANRLocked(
Jeff Brown9302c872011-07-13 22:51:29 -07003267 nsecs_t currentTime, const sp<InputApplicationHandle>& applicationHandle,
3268 const sp<InputWindowHandle>& windowHandle,
Jeff Brown519e0242010-09-15 15:18:56 -07003269 nsecs_t eventTime, nsecs_t waitStartTime) {
Steve Block6215d3f2012-01-04 20:05:49 +00003270 ALOGI("Application is not responding: %s. "
Jeff Brown519e0242010-09-15 15:18:56 -07003271 "%01.1fms since event, %01.1fms since wait started",
Jeff Brown9302c872011-07-13 22:51:29 -07003272 getApplicationWindowLabelLocked(applicationHandle, windowHandle).string(),
Jeff Brown519e0242010-09-15 15:18:56 -07003273 (currentTime - eventTime) / 1000000.0,
3274 (currentTime - waitStartTime) / 1000000.0);
3275
3276 CommandEntry* commandEntry = postCommandLocked(
3277 & InputDispatcher::doNotifyANRLockedInterruptible);
Jeff Brown9302c872011-07-13 22:51:29 -07003278 commandEntry->inputApplicationHandle = applicationHandle;
3279 commandEntry->inputWindowHandle = windowHandle;
Jeff Brown519e0242010-09-15 15:18:56 -07003280}
3281
Jeff Brownb88102f2010-09-08 11:49:43 -07003282void InputDispatcher::doNotifyConfigurationChangedInterruptible(
3283 CommandEntry* commandEntry) {
3284 mLock.unlock();
3285
3286 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
3287
3288 mLock.lock();
3289}
3290
Jeff Brown9c3cda02010-06-15 01:31:58 -07003291void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(
3292 CommandEntry* commandEntry) {
Jeff Brown7fbdc842010-06-17 20:52:56 -07003293 sp<Connection> connection = commandEntry->connection;
Jeff Brown9c3cda02010-06-15 01:31:58 -07003294
Jeff Brown7fbdc842010-06-17 20:52:56 -07003295 if (connection->status != Connection::STATUS_ZOMBIE) {
3296 mLock.unlock();
Jeff Brown9c3cda02010-06-15 01:31:58 -07003297
Jeff Brown928e0542011-01-10 11:17:36 -08003298 mPolicy->notifyInputChannelBroken(connection->inputWindowHandle);
Jeff Brown7fbdc842010-06-17 20:52:56 -07003299
3300 mLock.lock();
3301 }
Jeff Brown9c3cda02010-06-15 01:31:58 -07003302}
3303
Jeff Brown519e0242010-09-15 15:18:56 -07003304void InputDispatcher::doNotifyANRLockedInterruptible(
Jeff Brown9c3cda02010-06-15 01:31:58 -07003305 CommandEntry* commandEntry) {
Jeff Brown519e0242010-09-15 15:18:56 -07003306 mLock.unlock();
Jeff Brown9c3cda02010-06-15 01:31:58 -07003307
Jeff Brown519e0242010-09-15 15:18:56 -07003308 nsecs_t newTimeout = mPolicy->notifyANR(
Jeff Brown928e0542011-01-10 11:17:36 -08003309 commandEntry->inputApplicationHandle, commandEntry->inputWindowHandle);
Jeff Brown9c3cda02010-06-15 01:31:58 -07003310
Jeff Brown519e0242010-09-15 15:18:56 -07003311 mLock.lock();
Jeff Brown7fbdc842010-06-17 20:52:56 -07003312
Jeff Brown9302c872011-07-13 22:51:29 -07003313 resumeAfterTargetsNotReadyTimeoutLocked(newTimeout,
3314 commandEntry->inputWindowHandle != NULL
Jeff Browncc4f7db2011-08-30 20:34:48 -07003315 ? commandEntry->inputWindowHandle->getInputChannel() : NULL);
Jeff Brown9c3cda02010-06-15 01:31:58 -07003316}
3317
Jeff Brownb88102f2010-09-08 11:49:43 -07003318void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
3319 CommandEntry* commandEntry) {
3320 KeyEntry* entry = commandEntry->keyEntry;
Jeff Brown1f245102010-11-18 20:53:46 -08003321
3322 KeyEvent event;
3323 initializeKeyEvent(&event, entry);
Jeff Brownb88102f2010-09-08 11:49:43 -07003324
3325 mLock.unlock();
3326
Jeff Brown905805a2011-10-12 13:57:59 -07003327 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(commandEntry->inputWindowHandle,
Jeff Brown1f245102010-11-18 20:53:46 -08003328 &event, entry->policyFlags);
Jeff Brownb88102f2010-09-08 11:49:43 -07003329
3330 mLock.lock();
3331
Jeff Brown905805a2011-10-12 13:57:59 -07003332 if (delay < 0) {
3333 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
3334 } else if (!delay) {
3335 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
3336 } else {
3337 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
3338 entry->interceptKeyWakeupTime = now() + delay;
3339 }
Jeff Brownac386072011-07-20 15:19:50 -07003340 entry->release();
Jeff Brownb88102f2010-09-08 11:49:43 -07003341}
3342
Jeff Brown3915bb82010-11-05 15:02:16 -07003343void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(
3344 CommandEntry* commandEntry) {
3345 sp<Connection> connection = commandEntry->connection;
3346 bool handled = commandEntry->handled;
3347
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003348 bool skipNext = false;
Jeff Brown49ed71d2010-12-06 17:13:33 -08003349 if (!connection->outboundQueue.isEmpty()) {
Jeff Brownac386072011-07-20 15:19:50 -07003350 DispatchEntry* dispatchEntry = connection->outboundQueue.head;
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003351 if (dispatchEntry->inProgress) {
3352 if (dispatchEntry->eventEntry->type == EventEntry::TYPE_KEY) {
3353 KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry);
3354 skipNext = afterKeyEventLockedInterruptible(connection,
3355 dispatchEntry, keyEntry, handled);
3356 } else if (dispatchEntry->eventEntry->type == EventEntry::TYPE_MOTION) {
3357 MotionEntry* motionEntry = static_cast<MotionEntry*>(dispatchEntry->eventEntry);
3358 skipNext = afterMotionEventLockedInterruptible(connection,
3359 dispatchEntry, motionEntry, handled);
Jeff Brown49ed71d2010-12-06 17:13:33 -08003360 }
Jeff Brown3915bb82010-11-05 15:02:16 -07003361 }
3362 }
3363
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003364 if (!skipNext) {
3365 startNextDispatchCycleLocked(now(), connection);
3366 }
3367}
3368
3369bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
3370 DispatchEntry* dispatchEntry, KeyEntry* keyEntry, bool handled) {
3371 if (!(keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK)) {
3372 // Get the fallback key state.
3373 // Clear it out after dispatching the UP.
3374 int32_t originalKeyCode = keyEntry->keyCode;
3375 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
3376 if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
3377 connection->inputState.removeFallbackKey(originalKeyCode);
3378 }
3379
3380 if (handled || !dispatchEntry->hasForegroundTarget()) {
3381 // If the application handles the original key for which we previously
3382 // generated a fallback or if the window is not a foreground window,
3383 // then cancel the associated fallback key, if any.
3384 if (fallbackKeyCode != -1) {
3385 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
3386 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
3387 "application handled the original non-fallback key "
3388 "or is no longer a foreground target, "
3389 "canceling previously dispatched fallback key");
3390 options.keyCode = fallbackKeyCode;
3391 synthesizeCancelationEventsForConnectionLocked(connection, options);
3392 }
3393 connection->inputState.removeFallbackKey(originalKeyCode);
3394 }
3395 } else {
3396 // If the application did not handle a non-fallback key, first check
3397 // that we are in a good state to perform unhandled key event processing
3398 // Then ask the policy what to do with it.
3399 bool initialDown = keyEntry->action == AKEY_EVENT_ACTION_DOWN
3400 && keyEntry->repeatCount == 0;
3401 if (fallbackKeyCode == -1 && !initialDown) {
3402#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00003403 ALOGD("Unhandled key event: Skipping unhandled key event processing "
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003404 "since this is not an initial down. "
3405 "keyCode=%d, action=%d, repeatCount=%d",
3406 originalKeyCode, keyEntry->action, keyEntry->repeatCount);
3407#endif
3408 return false;
3409 }
3410
3411 // Dispatch the unhandled key to the policy.
3412#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00003413 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003414 "keyCode=%d, action=%d, repeatCount=%d",
3415 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount);
3416#endif
3417 KeyEvent event;
3418 initializeKeyEvent(&event, keyEntry);
3419
3420 mLock.unlock();
3421
3422 bool fallback = mPolicy->dispatchUnhandledKey(connection->inputWindowHandle,
3423 &event, keyEntry->policyFlags, &event);
3424
3425 mLock.lock();
3426
3427 if (connection->status != Connection::STATUS_NORMAL) {
3428 connection->inputState.removeFallbackKey(originalKeyCode);
3429 return true; // skip next cycle
3430 }
3431
Steve Blockec193de2012-01-09 18:35:44 +00003432 ALOG_ASSERT(connection->outboundQueue.head == dispatchEntry);
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003433
3434 // Latch the fallback keycode for this key on an initial down.
3435 // The fallback keycode cannot change at any other point in the lifecycle.
3436 if (initialDown) {
3437 if (fallback) {
3438 fallbackKeyCode = event.getKeyCode();
3439 } else {
3440 fallbackKeyCode = AKEYCODE_UNKNOWN;
3441 }
3442 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
3443 }
3444
Steve Blockec193de2012-01-09 18:35:44 +00003445 ALOG_ASSERT(fallbackKeyCode != -1);
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003446
3447 // Cancel the fallback key if the policy decides not to send it anymore.
3448 // We will continue to dispatch the key to the policy but we will no
3449 // longer dispatch a fallback key to the application.
3450 if (fallbackKeyCode != AKEYCODE_UNKNOWN
3451 && (!fallback || fallbackKeyCode != event.getKeyCode())) {
3452#if DEBUG_OUTBOUND_EVENT_DETAILS
3453 if (fallback) {
Steve Block5baa3a62011-12-20 16:23:08 +00003454 ALOGD("Unhandled key event: Policy requested to send key %d"
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003455 "as a fallback for %d, but on the DOWN it had requested "
3456 "to send %d instead. Fallback canceled.",
3457 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
3458 } else {
Steve Block5baa3a62011-12-20 16:23:08 +00003459 ALOGD("Unhandled key event: Policy did not request fallback for %d,"
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003460 "but on the DOWN it had requested to send %d. "
3461 "Fallback canceled.",
3462 originalKeyCode, fallbackKeyCode);
3463 }
3464#endif
3465
3466 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
3467 "canceling fallback, policy no longer desires it");
3468 options.keyCode = fallbackKeyCode;
3469 synthesizeCancelationEventsForConnectionLocked(connection, options);
3470
3471 fallback = false;
3472 fallbackKeyCode = AKEYCODE_UNKNOWN;
3473 if (keyEntry->action != AKEY_EVENT_ACTION_UP) {
3474 connection->inputState.setFallbackKey(originalKeyCode,
3475 fallbackKeyCode);
3476 }
3477 }
3478
3479#if DEBUG_OUTBOUND_EVENT_DETAILS
3480 {
3481 String8 msg;
3482 const KeyedVector<int32_t, int32_t>& fallbackKeys =
3483 connection->inputState.getFallbackKeys();
3484 for (size_t i = 0; i < fallbackKeys.size(); i++) {
3485 msg.appendFormat(", %d->%d", fallbackKeys.keyAt(i),
3486 fallbackKeys.valueAt(i));
3487 }
Steve Block5baa3a62011-12-20 16:23:08 +00003488 ALOGD("Unhandled key event: %d currently tracked fallback keys%s.",
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003489 fallbackKeys.size(), msg.string());
3490 }
3491#endif
3492
3493 if (fallback) {
3494 // Restart the dispatch cycle using the fallback key.
3495 keyEntry->eventTime = event.getEventTime();
3496 keyEntry->deviceId = event.getDeviceId();
3497 keyEntry->source = event.getSource();
3498 keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
3499 keyEntry->keyCode = fallbackKeyCode;
3500 keyEntry->scanCode = event.getScanCode();
3501 keyEntry->metaState = event.getMetaState();
3502 keyEntry->repeatCount = event.getRepeatCount();
3503 keyEntry->downTime = event.getDownTime();
3504 keyEntry->syntheticRepeat = false;
3505
3506#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00003507 ALOGD("Unhandled key event: Dispatching fallback key. "
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003508 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
3509 originalKeyCode, fallbackKeyCode, keyEntry->metaState);
3510#endif
3511
3512 dispatchEntry->inProgress = false;
3513 startDispatchCycleLocked(now(), connection);
3514 return true; // already started next cycle
3515 } else {
3516#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00003517 ALOGD("Unhandled key event: No fallback key.");
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003518#endif
3519 }
3520 }
3521 }
3522 return false;
3523}
3524
3525bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
3526 DispatchEntry* dispatchEntry, MotionEntry* motionEntry, bool handled) {
3527 return false;
Jeff Brown3915bb82010-11-05 15:02:16 -07003528}
3529
Jeff Brownb88102f2010-09-08 11:49:43 -07003530void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
3531 mLock.unlock();
3532
Jeff Brown01ce2e92010-09-26 22:20:12 -07003533 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
Jeff Brownb88102f2010-09-08 11:49:43 -07003534
3535 mLock.lock();
3536}
3537
Jeff Brown3915bb82010-11-05 15:02:16 -07003538void InputDispatcher::initializeKeyEvent(KeyEvent* event, const KeyEntry* entry) {
3539 event->initialize(entry->deviceId, entry->source, entry->action, entry->flags,
3540 entry->keyCode, entry->scanCode, entry->metaState, entry->repeatCount,
3541 entry->downTime, entry->eventTime);
3542}
3543
Jeff Brown519e0242010-09-15 15:18:56 -07003544void InputDispatcher::updateDispatchStatisticsLocked(nsecs_t currentTime, const EventEntry* entry,
3545 int32_t injectionResult, nsecs_t timeSpentWaitingForApplication) {
3546 // TODO Write some statistics about how long we spend waiting.
Jeff Brownb88102f2010-09-08 11:49:43 -07003547}
3548
3549void InputDispatcher::dump(String8& dump) {
Jeff Brown89ef0722011-08-10 16:25:21 -07003550 AutoMutex _l(mLock);
3551
Jeff Brownf2f487182010-10-01 17:46:21 -07003552 dump.append("Input Dispatcher State:\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003553 dumpDispatchStateLocked(dump);
Jeff Brown214eaf42011-05-26 19:17:02 -07003554
3555 dump.append(INDENT "Configuration:\n");
Jeff Brown214eaf42011-05-26 19:17:02 -07003556 dump.appendFormat(INDENT2 "KeyRepeatDelay: %0.1fms\n", mConfig.keyRepeatDelay * 0.000001f);
3557 dump.appendFormat(INDENT2 "KeyRepeatTimeout: %0.1fms\n", mConfig.keyRepeatTimeout * 0.000001f);
Jeff Brownb88102f2010-09-08 11:49:43 -07003558}
3559
Jeff Brown89ef0722011-08-10 16:25:21 -07003560void InputDispatcher::monitor() {
3561 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
3562 mLock.lock();
Jeff Brown112b5f52012-01-27 17:32:06 -08003563 mLooper->wake();
3564 mDispatcherIsAliveCondition.wait(mLock);
Jeff Brown89ef0722011-08-10 16:25:21 -07003565 mLock.unlock();
3566}
3567
Jeff Brown9c3cda02010-06-15 01:31:58 -07003568
Jeff Brown519e0242010-09-15 15:18:56 -07003569// --- InputDispatcher::Queue ---
3570
3571template <typename T>
3572uint32_t InputDispatcher::Queue<T>::count() const {
3573 uint32_t result = 0;
Jeff Brownac386072011-07-20 15:19:50 -07003574 for (const T* entry = head; entry; entry = entry->next) {
Jeff Brown519e0242010-09-15 15:18:56 -07003575 result += 1;
3576 }
3577 return result;
3578}
3579
3580
Jeff Brownac386072011-07-20 15:19:50 -07003581// --- InputDispatcher::InjectionState ---
Jeff Brown46b9ac02010-04-22 18:58:52 -07003582
Jeff Brownac386072011-07-20 15:19:50 -07003583InputDispatcher::InjectionState::InjectionState(int32_t injectorPid, int32_t injectorUid) :
3584 refCount(1),
3585 injectorPid(injectorPid), injectorUid(injectorUid),
3586 injectionResult(INPUT_EVENT_INJECTION_PENDING), injectionIsAsync(false),
3587 pendingForegroundDispatches(0) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07003588}
3589
Jeff Brownac386072011-07-20 15:19:50 -07003590InputDispatcher::InjectionState::~InjectionState() {
Jeff Brown01ce2e92010-09-26 22:20:12 -07003591}
3592
Jeff Brownac386072011-07-20 15:19:50 -07003593void InputDispatcher::InjectionState::release() {
3594 refCount -= 1;
3595 if (refCount == 0) {
3596 delete this;
3597 } else {
Steve Blockec193de2012-01-09 18:35:44 +00003598 ALOG_ASSERT(refCount > 0);
Jeff Brown01ce2e92010-09-26 22:20:12 -07003599 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07003600}
3601
Jeff Brownac386072011-07-20 15:19:50 -07003602
3603// --- InputDispatcher::EventEntry ---
3604
3605InputDispatcher::EventEntry::EventEntry(int32_t type, nsecs_t eventTime, uint32_t policyFlags) :
3606 refCount(1), type(type), eventTime(eventTime), policyFlags(policyFlags),
3607 injectionState(NULL), dispatchInProgress(false) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07003608}
3609
Jeff Brownac386072011-07-20 15:19:50 -07003610InputDispatcher::EventEntry::~EventEntry() {
3611 releaseInjectionState();
3612}
3613
3614void InputDispatcher::EventEntry::release() {
3615 refCount -= 1;
3616 if (refCount == 0) {
3617 delete this;
3618 } else {
Steve Blockec193de2012-01-09 18:35:44 +00003619 ALOG_ASSERT(refCount > 0);
Jeff Brownac386072011-07-20 15:19:50 -07003620 }
3621}
3622
3623void InputDispatcher::EventEntry::releaseInjectionState() {
3624 if (injectionState) {
3625 injectionState->release();
3626 injectionState = NULL;
3627 }
3628}
3629
3630
3631// --- InputDispatcher::ConfigurationChangedEntry ---
3632
3633InputDispatcher::ConfigurationChangedEntry::ConfigurationChangedEntry(nsecs_t eventTime) :
3634 EventEntry(TYPE_CONFIGURATION_CHANGED, eventTime, 0) {
3635}
3636
3637InputDispatcher::ConfigurationChangedEntry::~ConfigurationChangedEntry() {
3638}
3639
3640
Jeff Brown65fd2512011-08-18 11:20:58 -07003641// --- InputDispatcher::DeviceResetEntry ---
3642
3643InputDispatcher::DeviceResetEntry::DeviceResetEntry(nsecs_t eventTime, int32_t deviceId) :
3644 EventEntry(TYPE_DEVICE_RESET, eventTime, 0),
3645 deviceId(deviceId) {
3646}
3647
3648InputDispatcher::DeviceResetEntry::~DeviceResetEntry() {
3649}
3650
3651
Jeff Brownac386072011-07-20 15:19:50 -07003652// --- InputDispatcher::KeyEntry ---
3653
3654InputDispatcher::KeyEntry::KeyEntry(nsecs_t eventTime,
Jeff Brown58a2da82011-01-25 16:02:22 -08003655 int32_t deviceId, uint32_t source, uint32_t policyFlags, int32_t action,
Jeff Brown7fbdc842010-06-17 20:52:56 -07003656 int32_t flags, int32_t keyCode, int32_t scanCode, int32_t metaState,
Jeff Brownac386072011-07-20 15:19:50 -07003657 int32_t repeatCount, nsecs_t downTime) :
3658 EventEntry(TYPE_KEY, eventTime, policyFlags),
3659 deviceId(deviceId), source(source), action(action), flags(flags),
3660 keyCode(keyCode), scanCode(scanCode), metaState(metaState),
3661 repeatCount(repeatCount), downTime(downTime),
Jeff Brown905805a2011-10-12 13:57:59 -07003662 syntheticRepeat(false), interceptKeyResult(KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN),
3663 interceptKeyWakeupTime(0) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07003664}
3665
Jeff Brownac386072011-07-20 15:19:50 -07003666InputDispatcher::KeyEntry::~KeyEntry() {
3667}
Jeff Brown7fbdc842010-06-17 20:52:56 -07003668
Jeff Brownac386072011-07-20 15:19:50 -07003669void InputDispatcher::KeyEntry::recycle() {
3670 releaseInjectionState();
3671
3672 dispatchInProgress = false;
3673 syntheticRepeat = false;
3674 interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
Jeff Brown905805a2011-10-12 13:57:59 -07003675 interceptKeyWakeupTime = 0;
Jeff Brownac386072011-07-20 15:19:50 -07003676}
3677
3678
Jeff Brownae9fc032010-08-18 15:51:08 -07003679// --- InputDispatcher::MotionEntry ---
3680
Jeff Brownac386072011-07-20 15:19:50 -07003681InputDispatcher::MotionEntry::MotionEntry(nsecs_t eventTime,
3682 int32_t deviceId, uint32_t source, uint32_t policyFlags, int32_t action, int32_t flags,
3683 int32_t metaState, int32_t buttonState,
3684 int32_t edgeFlags, float xPrecision, float yPrecision,
3685 nsecs_t downTime, uint32_t pointerCount,
3686 const PointerProperties* pointerProperties, const PointerCoords* pointerCoords) :
3687 EventEntry(TYPE_MOTION, eventTime, policyFlags),
Jeff Brown3241b6b2012-02-03 15:08:02 -08003688 eventTime(eventTime),
Jeff Brownac386072011-07-20 15:19:50 -07003689 deviceId(deviceId), source(source), action(action), flags(flags),
3690 metaState(metaState), buttonState(buttonState), edgeFlags(edgeFlags),
3691 xPrecision(xPrecision), yPrecision(yPrecision),
Jeff Brown3241b6b2012-02-03 15:08:02 -08003692 downTime(downTime), pointerCount(pointerCount) {
Jeff Brownac386072011-07-20 15:19:50 -07003693 for (uint32_t i = 0; i < pointerCount; i++) {
3694 this->pointerProperties[i].copyFrom(pointerProperties[i]);
Jeff Brown3241b6b2012-02-03 15:08:02 -08003695 this->pointerCoords[i].copyFrom(pointerCoords[i]);
Jeff Brownac386072011-07-20 15:19:50 -07003696 }
3697}
3698
3699InputDispatcher::MotionEntry::~MotionEntry() {
Jeff Brownac386072011-07-20 15:19:50 -07003700}
3701
3702
3703// --- InputDispatcher::DispatchEntry ---
3704
3705InputDispatcher::DispatchEntry::DispatchEntry(EventEntry* eventEntry,
3706 int32_t targetFlags, float xOffset, float yOffset, float scaleFactor) :
3707 eventEntry(eventEntry), targetFlags(targetFlags),
3708 xOffset(xOffset), yOffset(yOffset), scaleFactor(scaleFactor),
3709 inProgress(false),
Jeff Brown3241b6b2012-02-03 15:08:02 -08003710 resolvedAction(0), resolvedFlags(0) {
Jeff Brownac386072011-07-20 15:19:50 -07003711 eventEntry->refCount += 1;
3712}
3713
3714InputDispatcher::DispatchEntry::~DispatchEntry() {
3715 eventEntry->release();
3716}
3717
Jeff Brownb88102f2010-09-08 11:49:43 -07003718
3719// --- InputDispatcher::InputState ---
3720
Jeff Brownb6997262010-10-08 22:31:17 -07003721InputDispatcher::InputState::InputState() {
Jeff Brownb88102f2010-09-08 11:49:43 -07003722}
3723
3724InputDispatcher::InputState::~InputState() {
3725}
3726
3727bool InputDispatcher::InputState::isNeutral() const {
3728 return mKeyMementos.isEmpty() && mMotionMementos.isEmpty();
3729}
3730
Jeff Brown81346812011-06-28 20:08:48 -07003731bool InputDispatcher::InputState::isHovering(int32_t deviceId, uint32_t source) const {
3732 for (size_t i = 0; i < mMotionMementos.size(); i++) {
3733 const MotionMemento& memento = mMotionMementos.itemAt(i);
3734 if (memento.deviceId == deviceId
3735 && memento.source == source
3736 && memento.hovering) {
3737 return true;
3738 }
3739 }
3740 return false;
3741}
Jeff Brownb88102f2010-09-08 11:49:43 -07003742
Jeff Brown81346812011-06-28 20:08:48 -07003743bool InputDispatcher::InputState::trackKey(const KeyEntry* entry,
3744 int32_t action, int32_t flags) {
3745 switch (action) {
3746 case AKEY_EVENT_ACTION_UP: {
3747 if (entry->flags & AKEY_EVENT_FLAG_FALLBACK) {
3748 for (size_t i = 0; i < mFallbackKeys.size(); ) {
3749 if (mFallbackKeys.valueAt(i) == entry->keyCode) {
3750 mFallbackKeys.removeItemsAt(i);
3751 } else {
3752 i += 1;
3753 }
3754 }
3755 }
3756 ssize_t index = findKeyMemento(entry);
3757 if (index >= 0) {
3758 mKeyMementos.removeAt(index);
3759 return true;
3760 }
Jeff Brown68b909d2011-12-07 16:36:01 -08003761 /* FIXME: We can't just drop the key up event because that prevents creating
3762 * popup windows that are automatically shown when a key is held and then
3763 * dismissed when the key is released. The problem is that the popup will
3764 * not have received the original key down, so the key up will be considered
3765 * to be inconsistent with its observed state. We could perhaps handle this
3766 * by synthesizing a key down but that will cause other problems.
3767 *
3768 * So for now, allow inconsistent key up events to be dispatched.
3769 *
Jeff Brown81346812011-06-28 20:08:48 -07003770#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00003771 ALOGD("Dropping inconsistent key up event: deviceId=%d, source=%08x, "
Jeff Brown81346812011-06-28 20:08:48 -07003772 "keyCode=%d, scanCode=%d",
3773 entry->deviceId, entry->source, entry->keyCode, entry->scanCode);
3774#endif
3775 return false;
Jeff Brown68b909d2011-12-07 16:36:01 -08003776 */
3777 return true;
Jeff Brown81346812011-06-28 20:08:48 -07003778 }
3779
3780 case AKEY_EVENT_ACTION_DOWN: {
3781 ssize_t index = findKeyMemento(entry);
3782 if (index >= 0) {
3783 mKeyMementos.removeAt(index);
3784 }
3785 addKeyMemento(entry, flags);
3786 return true;
3787 }
3788
3789 default:
3790 return true;
Jeff Brownb88102f2010-09-08 11:49:43 -07003791 }
3792}
3793
Jeff Brown81346812011-06-28 20:08:48 -07003794bool InputDispatcher::InputState::trackMotion(const MotionEntry* entry,
3795 int32_t action, int32_t flags) {
3796 int32_t actionMasked = action & AMOTION_EVENT_ACTION_MASK;
3797 switch (actionMasked) {
3798 case AMOTION_EVENT_ACTION_UP:
3799 case AMOTION_EVENT_ACTION_CANCEL: {
3800 ssize_t index = findMotionMemento(entry, false /*hovering*/);
3801 if (index >= 0) {
3802 mMotionMementos.removeAt(index);
3803 return true;
Jeff Brownda3d5a92011-03-29 15:11:34 -07003804 }
Jeff Brown81346812011-06-28 20:08:48 -07003805#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00003806 ALOGD("Dropping inconsistent motion up or cancel event: deviceId=%d, source=%08x, "
Jeff Brown81346812011-06-28 20:08:48 -07003807 "actionMasked=%d",
3808 entry->deviceId, entry->source, actionMasked);
3809#endif
3810 return false;
Jeff Brownda3d5a92011-03-29 15:11:34 -07003811 }
3812
Jeff Brown81346812011-06-28 20:08:48 -07003813 case AMOTION_EVENT_ACTION_DOWN: {
3814 ssize_t index = findMotionMemento(entry, false /*hovering*/);
3815 if (index >= 0) {
3816 mMotionMementos.removeAt(index);
3817 }
3818 addMotionMemento(entry, flags, false /*hovering*/);
3819 return true;
3820 }
3821
3822 case AMOTION_EVENT_ACTION_POINTER_UP:
3823 case AMOTION_EVENT_ACTION_POINTER_DOWN:
3824 case AMOTION_EVENT_ACTION_MOVE: {
3825 ssize_t index = findMotionMemento(entry, false /*hovering*/);
3826 if (index >= 0) {
3827 MotionMemento& memento = mMotionMementos.editItemAt(index);
3828 memento.setPointers(entry);
3829 return true;
3830 }
Jeff Brown2e45fb62011-06-29 21:19:05 -07003831 if (actionMasked == AMOTION_EVENT_ACTION_MOVE
3832 && (entry->source & (AINPUT_SOURCE_CLASS_JOYSTICK
3833 | AINPUT_SOURCE_CLASS_NAVIGATION))) {
3834 // Joysticks and trackballs can send MOVE events without corresponding DOWN or UP.
3835 return true;
3836 }
Jeff Brown81346812011-06-28 20:08:48 -07003837#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00003838 ALOGD("Dropping inconsistent motion pointer up/down or move event: "
Jeff Brown81346812011-06-28 20:08:48 -07003839 "deviceId=%d, source=%08x, actionMasked=%d",
3840 entry->deviceId, entry->source, actionMasked);
3841#endif
3842 return false;
3843 }
3844
3845 case AMOTION_EVENT_ACTION_HOVER_EXIT: {
3846 ssize_t index = findMotionMemento(entry, true /*hovering*/);
3847 if (index >= 0) {
3848 mMotionMementos.removeAt(index);
3849 return true;
3850 }
3851#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00003852 ALOGD("Dropping inconsistent motion hover exit event: deviceId=%d, source=%08x",
Jeff Brown81346812011-06-28 20:08:48 -07003853 entry->deviceId, entry->source);
3854#endif
3855 return false;
3856 }
3857
3858 case AMOTION_EVENT_ACTION_HOVER_ENTER:
3859 case AMOTION_EVENT_ACTION_HOVER_MOVE: {
3860 ssize_t index = findMotionMemento(entry, true /*hovering*/);
3861 if (index >= 0) {
3862 mMotionMementos.removeAt(index);
3863 }
3864 addMotionMemento(entry, flags, true /*hovering*/);
3865 return true;
3866 }
3867
3868 default:
3869 return true;
3870 }
3871}
3872
3873ssize_t InputDispatcher::InputState::findKeyMemento(const KeyEntry* entry) const {
Jeff Brownb88102f2010-09-08 11:49:43 -07003874 for (size_t i = 0; i < mKeyMementos.size(); i++) {
Jeff Brown81346812011-06-28 20:08:48 -07003875 const KeyMemento& memento = mKeyMementos.itemAt(i);
Jeff Brownb88102f2010-09-08 11:49:43 -07003876 if (memento.deviceId == entry->deviceId
3877 && memento.source == entry->source
3878 && memento.keyCode == entry->keyCode
3879 && memento.scanCode == entry->scanCode) {
Jeff Brown81346812011-06-28 20:08:48 -07003880 return i;
Jeff Brownb88102f2010-09-08 11:49:43 -07003881 }
3882 }
Jeff Brown81346812011-06-28 20:08:48 -07003883 return -1;
Jeff Brownb88102f2010-09-08 11:49:43 -07003884}
3885
Jeff Brown81346812011-06-28 20:08:48 -07003886ssize_t InputDispatcher::InputState::findMotionMemento(const MotionEntry* entry,
3887 bool hovering) const {
Jeff Brownb88102f2010-09-08 11:49:43 -07003888 for (size_t i = 0; i < mMotionMementos.size(); i++) {
Jeff Brown81346812011-06-28 20:08:48 -07003889 const MotionMemento& memento = mMotionMementos.itemAt(i);
Jeff Brownb88102f2010-09-08 11:49:43 -07003890 if (memento.deviceId == entry->deviceId
Jeff Brown81346812011-06-28 20:08:48 -07003891 && memento.source == entry->source
3892 && memento.hovering == hovering) {
3893 return i;
Jeff Brownb88102f2010-09-08 11:49:43 -07003894 }
3895 }
Jeff Brown81346812011-06-28 20:08:48 -07003896 return -1;
3897}
Jeff Brownb88102f2010-09-08 11:49:43 -07003898
Jeff Brown81346812011-06-28 20:08:48 -07003899void InputDispatcher::InputState::addKeyMemento(const KeyEntry* entry, int32_t flags) {
3900 mKeyMementos.push();
3901 KeyMemento& memento = mKeyMementos.editTop();
3902 memento.deviceId = entry->deviceId;
3903 memento.source = entry->source;
3904 memento.keyCode = entry->keyCode;
3905 memento.scanCode = entry->scanCode;
3906 memento.flags = flags;
3907 memento.downTime = entry->downTime;
3908}
3909
3910void InputDispatcher::InputState::addMotionMemento(const MotionEntry* entry,
3911 int32_t flags, bool hovering) {
3912 mMotionMementos.push();
3913 MotionMemento& memento = mMotionMementos.editTop();
3914 memento.deviceId = entry->deviceId;
3915 memento.source = entry->source;
3916 memento.flags = flags;
3917 memento.xPrecision = entry->xPrecision;
3918 memento.yPrecision = entry->yPrecision;
3919 memento.downTime = entry->downTime;
3920 memento.setPointers(entry);
3921 memento.hovering = hovering;
Jeff Brownb88102f2010-09-08 11:49:43 -07003922}
3923
3924void InputDispatcher::InputState::MotionMemento::setPointers(const MotionEntry* entry) {
3925 pointerCount = entry->pointerCount;
3926 for (uint32_t i = 0; i < entry->pointerCount; i++) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003927 pointerProperties[i].copyFrom(entry->pointerProperties[i]);
Jeff Brown3241b6b2012-02-03 15:08:02 -08003928 pointerCoords[i].copyFrom(entry->pointerCoords[i]);
Jeff Brownb88102f2010-09-08 11:49:43 -07003929 }
3930}
3931
Jeff Brownb6997262010-10-08 22:31:17 -07003932void InputDispatcher::InputState::synthesizeCancelationEvents(nsecs_t currentTime,
Jeff Brownac386072011-07-20 15:19:50 -07003933 Vector<EventEntry*>& outEvents, const CancelationOptions& options) {
Jeff Brown81346812011-06-28 20:08:48 -07003934 for (size_t i = 0; i < mKeyMementos.size(); i++) {
Jeff Brownb88102f2010-09-08 11:49:43 -07003935 const KeyMemento& memento = mKeyMementos.itemAt(i);
Jeff Brown49ed71d2010-12-06 17:13:33 -08003936 if (shouldCancelKey(memento, options)) {
Jeff Brownac386072011-07-20 15:19:50 -07003937 outEvents.push(new KeyEntry(currentTime,
Jeff Brownb6997262010-10-08 22:31:17 -07003938 memento.deviceId, memento.source, 0,
Jeff Brown49ed71d2010-12-06 17:13:33 -08003939 AKEY_EVENT_ACTION_UP, memento.flags | AKEY_EVENT_FLAG_CANCELED,
Jeff Brownb6997262010-10-08 22:31:17 -07003940 memento.keyCode, memento.scanCode, 0, 0, memento.downTime));
Jeff Brownb6997262010-10-08 22:31:17 -07003941 }
Jeff Brownb88102f2010-09-08 11:49:43 -07003942 }
3943
Jeff Brown81346812011-06-28 20:08:48 -07003944 for (size_t i = 0; i < mMotionMementos.size(); i++) {
Jeff Brownb88102f2010-09-08 11:49:43 -07003945 const MotionMemento& memento = mMotionMementos.itemAt(i);
Jeff Brown49ed71d2010-12-06 17:13:33 -08003946 if (shouldCancelMotion(memento, options)) {
Jeff Brownac386072011-07-20 15:19:50 -07003947 outEvents.push(new MotionEntry(currentTime,
Jeff Brownb6997262010-10-08 22:31:17 -07003948 memento.deviceId, memento.source, 0,
Jeff Browna032cc02011-03-07 16:56:21 -08003949 memento.hovering
3950 ? AMOTION_EVENT_ACTION_HOVER_EXIT
3951 : AMOTION_EVENT_ACTION_CANCEL,
Jeff Brown81346812011-06-28 20:08:48 -07003952 memento.flags, 0, 0, 0,
Jeff Brownb6997262010-10-08 22:31:17 -07003953 memento.xPrecision, memento.yPrecision, memento.downTime,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003954 memento.pointerCount, memento.pointerProperties, memento.pointerCoords));
Jeff Brownb6997262010-10-08 22:31:17 -07003955 }
Jeff Brownb88102f2010-09-08 11:49:43 -07003956 }
3957}
3958
3959void InputDispatcher::InputState::clear() {
3960 mKeyMementos.clear();
3961 mMotionMementos.clear();
Jeff Brownda3d5a92011-03-29 15:11:34 -07003962 mFallbackKeys.clear();
Jeff Brownb6997262010-10-08 22:31:17 -07003963}
3964
Jeff Brown9c9f1a32010-10-11 18:32:20 -07003965void InputDispatcher::InputState::copyPointerStateTo(InputState& other) const {
3966 for (size_t i = 0; i < mMotionMementos.size(); i++) {
3967 const MotionMemento& memento = mMotionMementos.itemAt(i);
3968 if (memento.source & AINPUT_SOURCE_CLASS_POINTER) {
3969 for (size_t j = 0; j < other.mMotionMementos.size(); ) {
3970 const MotionMemento& otherMemento = other.mMotionMementos.itemAt(j);
3971 if (memento.deviceId == otherMemento.deviceId
3972 && memento.source == otherMemento.source) {
3973 other.mMotionMementos.removeAt(j);
3974 } else {
3975 j += 1;
3976 }
3977 }
3978 other.mMotionMementos.push(memento);
3979 }
3980 }
3981}
3982
Jeff Brownda3d5a92011-03-29 15:11:34 -07003983int32_t InputDispatcher::InputState::getFallbackKey(int32_t originalKeyCode) {
3984 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
3985 return index >= 0 ? mFallbackKeys.valueAt(index) : -1;
3986}
3987
3988void InputDispatcher::InputState::setFallbackKey(int32_t originalKeyCode,
3989 int32_t fallbackKeyCode) {
3990 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
3991 if (index >= 0) {
3992 mFallbackKeys.replaceValueAt(index, fallbackKeyCode);
3993 } else {
3994 mFallbackKeys.add(originalKeyCode, fallbackKeyCode);
3995 }
3996}
3997
3998void InputDispatcher::InputState::removeFallbackKey(int32_t originalKeyCode) {
3999 mFallbackKeys.removeItem(originalKeyCode);
4000}
4001
Jeff Brown49ed71d2010-12-06 17:13:33 -08004002bool InputDispatcher::InputState::shouldCancelKey(const KeyMemento& memento,
Jeff Brownda3d5a92011-03-29 15:11:34 -07004003 const CancelationOptions& options) {
4004 if (options.keyCode != -1 && memento.keyCode != options.keyCode) {
4005 return false;
4006 }
4007
Jeff Brown65fd2512011-08-18 11:20:58 -07004008 if (options.deviceId != -1 && memento.deviceId != options.deviceId) {
4009 return false;
4010 }
4011
Jeff Brownda3d5a92011-03-29 15:11:34 -07004012 switch (options.mode) {
4013 case CancelationOptions::CANCEL_ALL_EVENTS:
4014 case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
Jeff Brownb6997262010-10-08 22:31:17 -07004015 return true;
Jeff Brownda3d5a92011-03-29 15:11:34 -07004016 case CancelationOptions::CANCEL_FALLBACK_EVENTS:
Jeff Brown49ed71d2010-12-06 17:13:33 -08004017 return memento.flags & AKEY_EVENT_FLAG_FALLBACK;
4018 default:
4019 return false;
4020 }
4021}
4022
4023bool InputDispatcher::InputState::shouldCancelMotion(const MotionMemento& memento,
Jeff Brownda3d5a92011-03-29 15:11:34 -07004024 const CancelationOptions& options) {
Jeff Brown65fd2512011-08-18 11:20:58 -07004025 if (options.deviceId != -1 && memento.deviceId != options.deviceId) {
4026 return false;
4027 }
4028
Jeff Brownda3d5a92011-03-29 15:11:34 -07004029 switch (options.mode) {
4030 case CancelationOptions::CANCEL_ALL_EVENTS:
Jeff Brown49ed71d2010-12-06 17:13:33 -08004031 return true;
Jeff Brownda3d5a92011-03-29 15:11:34 -07004032 case CancelationOptions::CANCEL_POINTER_EVENTS:
Jeff Brown49ed71d2010-12-06 17:13:33 -08004033 return memento.source & AINPUT_SOURCE_CLASS_POINTER;
Jeff Brownda3d5a92011-03-29 15:11:34 -07004034 case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
Jeff Brown49ed71d2010-12-06 17:13:33 -08004035 return !(memento.source & AINPUT_SOURCE_CLASS_POINTER);
4036 default:
4037 return false;
Jeff Brownb6997262010-10-08 22:31:17 -07004038 }
Jeff Brownb88102f2010-09-08 11:49:43 -07004039}
4040
4041
Jeff Brown46b9ac02010-04-22 18:58:52 -07004042// --- InputDispatcher::Connection ---
4043
Jeff Brown928e0542011-01-10 11:17:36 -08004044InputDispatcher::Connection::Connection(const sp<InputChannel>& inputChannel,
Jeff Browncc4f7db2011-08-30 20:34:48 -07004045 const sp<InputWindowHandle>& inputWindowHandle, bool monitor) :
Jeff Brown928e0542011-01-10 11:17:36 -08004046 status(STATUS_NORMAL), inputChannel(inputChannel), inputWindowHandle(inputWindowHandle),
Jeff Browncc4f7db2011-08-30 20:34:48 -07004047 monitor(monitor),
Jeff Brown928e0542011-01-10 11:17:36 -08004048 inputPublisher(inputChannel),
Jeff Brownda3d5a92011-03-29 15:11:34 -07004049 lastEventTime(LONG_LONG_MAX), lastDispatchTime(LONG_LONG_MAX) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07004050}
4051
4052InputDispatcher::Connection::~Connection() {
4053}
4054
4055status_t InputDispatcher::Connection::initialize() {
4056 return inputPublisher.initialize();
4057}
4058
Jeff Brown9c3cda02010-06-15 01:31:58 -07004059const char* InputDispatcher::Connection::getStatusLabel() const {
4060 switch (status) {
4061 case STATUS_NORMAL:
4062 return "NORMAL";
4063
4064 case STATUS_BROKEN:
4065 return "BROKEN";
4066
Jeff Brown9c3cda02010-06-15 01:31:58 -07004067 case STATUS_ZOMBIE:
4068 return "ZOMBIE";
4069
4070 default:
4071 return "UNKNOWN";
4072 }
4073}
4074
Jeff Brown46b9ac02010-04-22 18:58:52 -07004075InputDispatcher::DispatchEntry* InputDispatcher::Connection::findQueuedDispatchEntryForEvent(
4076 const EventEntry* eventEntry) const {
Jeff Brownac386072011-07-20 15:19:50 -07004077 for (DispatchEntry* dispatchEntry = outboundQueue.tail; dispatchEntry;
4078 dispatchEntry = dispatchEntry->prev) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07004079 if (dispatchEntry->eventEntry == eventEntry) {
4080 return dispatchEntry;
4081 }
4082 }
4083 return NULL;
4084}
4085
Jeff Brownb88102f2010-09-08 11:49:43 -07004086
Jeff Brown9c3cda02010-06-15 01:31:58 -07004087// --- InputDispatcher::CommandEntry ---
4088
Jeff Brownac386072011-07-20 15:19:50 -07004089InputDispatcher::CommandEntry::CommandEntry(Command command) :
4090 command(command), eventTime(0), keyEntry(NULL), userActivityEventType(0), handled(false) {
Jeff Brown9c3cda02010-06-15 01:31:58 -07004091}
4092
4093InputDispatcher::CommandEntry::~CommandEntry() {
4094}
4095
Jeff Brown46b9ac02010-04-22 18:58:52 -07004096
Jeff Brown01ce2e92010-09-26 22:20:12 -07004097// --- InputDispatcher::TouchState ---
4098
4099InputDispatcher::TouchState::TouchState() :
Jeff Brown58a2da82011-01-25 16:02:22 -08004100 down(false), split(false), deviceId(-1), source(0) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07004101}
4102
4103InputDispatcher::TouchState::~TouchState() {
4104}
4105
4106void InputDispatcher::TouchState::reset() {
4107 down = false;
4108 split = false;
Jeff Brown95712852011-01-04 19:41:59 -08004109 deviceId = -1;
Jeff Brown58a2da82011-01-25 16:02:22 -08004110 source = 0;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004111 windows.clear();
4112}
4113
4114void InputDispatcher::TouchState::copyFrom(const TouchState& other) {
4115 down = other.down;
4116 split = other.split;
Jeff Brown95712852011-01-04 19:41:59 -08004117 deviceId = other.deviceId;
Jeff Brown58a2da82011-01-25 16:02:22 -08004118 source = other.source;
Jeff Brown9302c872011-07-13 22:51:29 -07004119 windows = other.windows;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004120}
4121
Jeff Brown9302c872011-07-13 22:51:29 -07004122void InputDispatcher::TouchState::addOrUpdateWindow(const sp<InputWindowHandle>& windowHandle,
Jeff Brown01ce2e92010-09-26 22:20:12 -07004123 int32_t targetFlags, BitSet32 pointerIds) {
4124 if (targetFlags & InputTarget::FLAG_SPLIT) {
4125 split = true;
4126 }
4127
4128 for (size_t i = 0; i < windows.size(); i++) {
4129 TouchedWindow& touchedWindow = windows.editItemAt(i);
Jeff Brown9302c872011-07-13 22:51:29 -07004130 if (touchedWindow.windowHandle == windowHandle) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07004131 touchedWindow.targetFlags |= targetFlags;
Jeff Brown98db5fa2011-06-08 15:37:10 -07004132 if (targetFlags & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
4133 touchedWindow.targetFlags &= ~InputTarget::FLAG_DISPATCH_AS_IS;
4134 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07004135 touchedWindow.pointerIds.value |= pointerIds.value;
4136 return;
4137 }
4138 }
4139
4140 windows.push();
4141
4142 TouchedWindow& touchedWindow = windows.editTop();
Jeff Brown9302c872011-07-13 22:51:29 -07004143 touchedWindow.windowHandle = windowHandle;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004144 touchedWindow.targetFlags = targetFlags;
4145 touchedWindow.pointerIds = pointerIds;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004146}
4147
Jeff Browna032cc02011-03-07 16:56:21 -08004148void InputDispatcher::TouchState::filterNonAsIsTouchWindows() {
Jeff Brown01ce2e92010-09-26 22:20:12 -07004149 for (size_t i = 0 ; i < windows.size(); ) {
Jeff Browna032cc02011-03-07 16:56:21 -08004150 TouchedWindow& window = windows.editItemAt(i);
Jeff Brown98db5fa2011-06-08 15:37:10 -07004151 if (window.targetFlags & (InputTarget::FLAG_DISPATCH_AS_IS
4152 | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER)) {
Jeff Browna032cc02011-03-07 16:56:21 -08004153 window.targetFlags &= ~InputTarget::FLAG_DISPATCH_MASK;
4154 window.targetFlags |= InputTarget::FLAG_DISPATCH_AS_IS;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004155 i += 1;
Jeff Browna032cc02011-03-07 16:56:21 -08004156 } else {
4157 windows.removeAt(i);
Jeff Brown01ce2e92010-09-26 22:20:12 -07004158 }
4159 }
4160}
4161
Jeff Brown9302c872011-07-13 22:51:29 -07004162sp<InputWindowHandle> InputDispatcher::TouchState::getFirstForegroundWindowHandle() const {
Jeff Brown01ce2e92010-09-26 22:20:12 -07004163 for (size_t i = 0; i < windows.size(); i++) {
Jeff Brown98db5fa2011-06-08 15:37:10 -07004164 const TouchedWindow& window = windows.itemAt(i);
4165 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
Jeff Brown9302c872011-07-13 22:51:29 -07004166 return window.windowHandle;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004167 }
4168 }
4169 return NULL;
4170}
4171
Jeff Brown98db5fa2011-06-08 15:37:10 -07004172bool InputDispatcher::TouchState::isSlippery() const {
4173 // Must have exactly one foreground window.
4174 bool haveSlipperyForegroundWindow = false;
4175 for (size_t i = 0; i < windows.size(); i++) {
4176 const TouchedWindow& window = windows.itemAt(i);
4177 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
Jeff Browncc4f7db2011-08-30 20:34:48 -07004178 if (haveSlipperyForegroundWindow
4179 || !(window.windowHandle->getInfo()->layoutParamsFlags
4180 & InputWindowInfo::FLAG_SLIPPERY)) {
Jeff Brown98db5fa2011-06-08 15:37:10 -07004181 return false;
4182 }
4183 haveSlipperyForegroundWindow = true;
4184 }
4185 }
4186 return haveSlipperyForegroundWindow;
4187}
4188
Jeff Brown01ce2e92010-09-26 22:20:12 -07004189
Jeff Brown46b9ac02010-04-22 18:58:52 -07004190// --- InputDispatcherThread ---
4191
4192InputDispatcherThread::InputDispatcherThread(const sp<InputDispatcherInterface>& dispatcher) :
4193 Thread(/*canCallJava*/ true), mDispatcher(dispatcher) {
4194}
4195
4196InputDispatcherThread::~InputDispatcherThread() {
4197}
4198
4199bool InputDispatcherThread::threadLoop() {
4200 mDispatcher->dispatchOnce();
4201 return true;
4202}
4203
4204} // namespace android