blob: 7164a13489af55be75b5a3975f2f0af4c706572c [file] [log] [blame]
Jeff Brownb4ff35d2011-01-02 16:37:43 -08001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Jeff Brown46b9ac02010-04-22 18:58:52 -070017#define LOG_TAG "InputDispatcher"
Jeff Brown481c1572012-03-09 14:41:15 -080018#define ATRACE_TAG ATRACE_TAG_INPUT
Jeff Brown46b9ac02010-04-22 18:58:52 -070019
20//#define LOG_NDEBUG 0
21
22// Log detailed debug messages about each inbound event notification to the dispatcher.
Jeff Brown349703e2010-06-22 01:27:15 -070023#define DEBUG_INBOUND_EVENT_DETAILS 0
Jeff Brown46b9ac02010-04-22 18:58:52 -070024
25// Log detailed debug messages about each outbound event processed by the dispatcher.
Jeff Brown349703e2010-06-22 01:27:15 -070026#define DEBUG_OUTBOUND_EVENT_DETAILS 0
Jeff Brown46b9ac02010-04-22 18:58:52 -070027
Jeff Brown46b9ac02010-04-22 18:58:52 -070028// Log debug messages about the dispatch cycle.
Jeff Brown349703e2010-06-22 01:27:15 -070029#define DEBUG_DISPATCH_CYCLE 0
Jeff Brown46b9ac02010-04-22 18:58:52 -070030
Jeff Brown9c3cda02010-06-15 01:31:58 -070031// Log debug messages about registrations.
Jeff Brown349703e2010-06-22 01:27:15 -070032#define DEBUG_REGISTRATION 0
Jeff Brown9c3cda02010-06-15 01:31:58 -070033
Jeff Brown7fbdc842010-06-17 20:52:56 -070034// Log debug messages about input event injection.
Jeff Brown349703e2010-06-22 01:27:15 -070035#define DEBUG_INJECTION 0
Jeff Brown7fbdc842010-06-17 20:52:56 -070036
Jeff Brownb88102f2010-09-08 11:49:43 -070037// Log debug messages about input focus tracking.
38#define DEBUG_FOCUS 0
39
40// Log debug messages about the app switch latency optimization.
41#define DEBUG_APP_SWITCH 0
42
Jeff Browna032cc02011-03-07 16:56:21 -080043// Log debug messages about hover events.
44#define DEBUG_HOVER 0
45
Jeff Brownb4ff35d2011-01-02 16:37:43 -080046#include "InputDispatcher.h"
47
Jeff Brown481c1572012-03-09 14:41:15 -080048#include <utils/Trace.h>
Jeff Brown46b9ac02010-04-22 18:58:52 -070049#include <cutils/log.h>
Mathias Agopianb93a03f82012-02-17 15:34:57 -080050#include <androidfw/PowerManager.h>
Jeff Brown46b9ac02010-04-22 18:58:52 -070051
52#include <stddef.h>
53#include <unistd.h>
Jeff Brown46b9ac02010-04-22 18:58:52 -070054#include <errno.h>
55#include <limits.h>
Jeff Brown22aa5122012-06-17 12:01:06 -070056#include <time.h>
Jeff Brown46b9ac02010-04-22 18:58:52 -070057
Jeff Brownf2f48712010-10-01 17:46:21 -070058#define INDENT " "
59#define INDENT2 " "
Jeff Brown265f1cc2012-06-11 18:01:06 -070060#define INDENT3 " "
61#define INDENT4 " "
Jeff Brownf2f48712010-10-01 17:46:21 -070062
Jeff Brown46b9ac02010-04-22 18:58:52 -070063namespace android {
64
Jeff Brownb88102f2010-09-08 11:49:43 -070065// Default input dispatching timeout if there is no focused application or paused window
66// from which to determine an appropriate dispatching timeout.
67const nsecs_t DEFAULT_INPUT_DISPATCHING_TIMEOUT = 5000 * 1000000LL; // 5 sec
68
69// Amount of time to allow for all pending events to be processed when an app switch
70// key is on the way. This is used to preempt input dispatch and drop input events
71// when an application takes too long to respond and the user has pressed an app switch key.
72const nsecs_t APP_SWITCH_TIMEOUT = 500 * 1000000LL; // 0.5sec
73
Jeff Brown928e0542011-01-10 11:17:36 -080074// Amount of time to allow for an event to be dispatched (measured since its eventTime)
75// before considering it stale and dropping it.
76const nsecs_t STALE_EVENT_TIMEOUT = 10000 * 1000000LL; // 10sec
77
Jeff Brownd1c48a02012-02-06 19:12:47 -080078// Amount of time to allow touch events to be streamed out to a connection before requiring
79// that the first event be finished. This value extends the ANR timeout by the specified
80// amount. For example, if streaming is allowed to get ahead by one second relative to the
81// queue of waiting unfinished events, then ANRs will similarly be delayed by one second.
82const nsecs_t STREAM_AHEAD_EVENT_TIMEOUT = 500 * 1000000LL; // 0.5sec
83
Jeff Brown265f1cc2012-06-11 18:01:06 -070084// Log a warning when an event takes longer than this to process, even if an ANR does not occur.
85const nsecs_t SLOW_EVENT_PROCESSING_WARNING_TIMEOUT = 2000 * 1000000LL; // 2sec
86
Jeff Brown6876f322013-08-07 16:46:50 -070087// Number of recent events to keep for debugging purposes.
88const size_t RECENT_QUEUE_MAX_SIZE = 10;
Jeff Brown46b9ac02010-04-22 18:58:52 -070089
Jeff Brown7fbdc842010-06-17 20:52:56 -070090static inline nsecs_t now() {
91 return systemTime(SYSTEM_TIME_MONOTONIC);
92}
93
Jeff Brownb88102f2010-09-08 11:49:43 -070094static inline const char* toString(bool value) {
95 return value ? "true" : "false";
96}
97
Jeff Brown01ce2e92010-09-26 22:20:12 -070098static inline int32_t getMotionEventActionPointerIndex(int32_t action) {
99 return (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK)
100 >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
101}
102
103static bool isValidKeyAction(int32_t action) {
104 switch (action) {
105 case AKEY_EVENT_ACTION_DOWN:
106 case AKEY_EVENT_ACTION_UP:
107 return true;
108 default:
109 return false;
110 }
111}
112
113static bool validateKeyEvent(int32_t action) {
114 if (! isValidKeyAction(action)) {
Steve Block3762c312012-01-06 19:20:56 +0000115 ALOGE("Key event has invalid action code 0x%x", action);
Jeff Brown01ce2e92010-09-26 22:20:12 -0700116 return false;
117 }
118 return true;
119}
120
Jeff Brownb6997262010-10-08 22:31:17 -0700121static bool isValidMotionAction(int32_t action, size_t pointerCount) {
Jeff Brown01ce2e92010-09-26 22:20:12 -0700122 switch (action & AMOTION_EVENT_ACTION_MASK) {
123 case AMOTION_EVENT_ACTION_DOWN:
124 case AMOTION_EVENT_ACTION_UP:
125 case AMOTION_EVENT_ACTION_CANCEL:
126 case AMOTION_EVENT_ACTION_MOVE:
Jeff Brown01ce2e92010-09-26 22:20:12 -0700127 case AMOTION_EVENT_ACTION_OUTSIDE:
Jeff Browna032cc02011-03-07 16:56:21 -0800128 case AMOTION_EVENT_ACTION_HOVER_ENTER:
Jeff Browncc0c1592011-02-19 05:07:28 -0800129 case AMOTION_EVENT_ACTION_HOVER_MOVE:
Jeff Browna032cc02011-03-07 16:56:21 -0800130 case AMOTION_EVENT_ACTION_HOVER_EXIT:
Jeff Brown33bbfd22011-02-24 20:55:35 -0800131 case AMOTION_EVENT_ACTION_SCROLL:
Jeff Brown01ce2e92010-09-26 22:20:12 -0700132 return true;
Jeff Brownb6997262010-10-08 22:31:17 -0700133 case AMOTION_EVENT_ACTION_POINTER_DOWN:
134 case AMOTION_EVENT_ACTION_POINTER_UP: {
135 int32_t index = getMotionEventActionPointerIndex(action);
136 return index >= 0 && size_t(index) < pointerCount;
137 }
Jeff Brown01ce2e92010-09-26 22:20:12 -0700138 default:
139 return false;
140 }
141}
142
143static bool validateMotionEvent(int32_t action, size_t pointerCount,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700144 const PointerProperties* pointerProperties) {
Jeff Brownb6997262010-10-08 22:31:17 -0700145 if (! isValidMotionAction(action, pointerCount)) {
Steve Block3762c312012-01-06 19:20:56 +0000146 ALOGE("Motion event has invalid action code 0x%x", action);
Jeff Brown01ce2e92010-09-26 22:20:12 -0700147 return false;
148 }
149 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Steve Block3762c312012-01-06 19:20:56 +0000150 ALOGE("Motion event has invalid pointer count %d; value must be between 1 and %d.",
Jeff Brown01ce2e92010-09-26 22:20:12 -0700151 pointerCount, MAX_POINTERS);
152 return false;
153 }
Jeff Brownc3db8582010-10-20 15:33:38 -0700154 BitSet32 pointerIdBits;
Jeff Brown01ce2e92010-09-26 22:20:12 -0700155 for (size_t i = 0; i < pointerCount; i++) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700156 int32_t id = pointerProperties[i].id;
Jeff Brownc3db8582010-10-20 15:33:38 -0700157 if (id < 0 || id > MAX_POINTER_ID) {
Steve Block3762c312012-01-06 19:20:56 +0000158 ALOGE("Motion event has invalid pointer id %d; value must be between 0 and %d",
Jeff Brownc3db8582010-10-20 15:33:38 -0700159 id, MAX_POINTER_ID);
Jeff Brown01ce2e92010-09-26 22:20:12 -0700160 return false;
161 }
Jeff Brownc3db8582010-10-20 15:33:38 -0700162 if (pointerIdBits.hasBit(id)) {
Steve Block3762c312012-01-06 19:20:56 +0000163 ALOGE("Motion event has duplicate pointer id %d", id);
Jeff Brownc3db8582010-10-20 15:33:38 -0700164 return false;
165 }
166 pointerIdBits.markBit(id);
Jeff Brown01ce2e92010-09-26 22:20:12 -0700167 }
168 return true;
169}
170
Jeff Brown83d616a2012-09-09 20:33:43 -0700171static bool isMainDisplay(int32_t displayId) {
172 return displayId == ADISPLAY_ID_DEFAULT || displayId == ADISPLAY_ID_NONE;
173}
174
Jeff Brownfbf09772011-01-16 14:06:57 -0800175static void dumpRegion(String8& dump, const SkRegion& region) {
176 if (region.isEmpty()) {
177 dump.append("<empty>");
178 return;
179 }
180
181 bool first = true;
182 for (SkRegion::Iterator it(region); !it.done(); it.next()) {
183 if (first) {
184 first = false;
185 } else {
186 dump.append("|");
187 }
188 const SkIRect& rect = it.rect();
189 dump.appendFormat("[%d,%d][%d,%d]", rect.fLeft, rect.fTop, rect.fRight, rect.fBottom);
190 }
191}
192
Jeff Brownb88102f2010-09-08 11:49:43 -0700193
Jeff Brown46b9ac02010-04-22 18:58:52 -0700194// --- InputDispatcher ---
195
Jeff Brown9c3cda02010-06-15 01:31:58 -0700196InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy) :
Jeff Brownb88102f2010-09-08 11:49:43 -0700197 mPolicy(policy),
Jeff Brown928e0542011-01-10 11:17:36 -0800198 mPendingEvent(NULL), mAppSwitchSawKeyDown(false), mAppSwitchDueTime(LONG_LONG_MAX),
199 mNextUnblockedEvent(NULL),
Jeff Brownc042ee22012-05-08 13:03:42 -0700200 mDispatchEnabled(false), mDispatchFrozen(false), mInputFilterEnabled(false),
Jeff Brown9302c872011-07-13 22:51:29 -0700201 mInputTargetWaitCause(INPUT_TARGET_WAIT_CAUSE_NONE) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -0700202 mLooper = new Looper(false);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700203
Jeff Brown46b9ac02010-04-22 18:58:52 -0700204 mKeyRepeatState.lastKeyEntry = NULL;
Jeff Brown9c3cda02010-06-15 01:31:58 -0700205
Jeff Brown214eaf42011-05-26 19:17:02 -0700206 policy->getDispatcherConfiguration(&mConfig);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700207}
208
209InputDispatcher::~InputDispatcher() {
Jeff Brownb88102f2010-09-08 11:49:43 -0700210 { // acquire lock
211 AutoMutex _l(mLock);
212
213 resetKeyRepeatLocked();
Jeff Brown54a18252010-09-16 14:07:33 -0700214 releasePendingEventLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -0700215 drainInboundQueueLocked();
216 }
Jeff Brown46b9ac02010-04-22 18:58:52 -0700217
Jeff Browncbee6d62012-02-03 20:11:27 -0800218 while (mConnectionsByFd.size() != 0) {
219 unregisterInputChannel(mConnectionsByFd.valueAt(0)->inputChannel);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700220 }
Jeff Brown46b9ac02010-04-22 18:58:52 -0700221}
222
223void InputDispatcher::dispatchOnce() {
Jeff Brown46b9ac02010-04-22 18:58:52 -0700224 nsecs_t nextWakeupTime = LONG_LONG_MAX;
225 { // acquire lock
226 AutoMutex _l(mLock);
Jeff Brown112b5f52012-01-27 17:32:06 -0800227 mDispatcherIsAliveCondition.broadcast();
228
Jeff Brown074b8b72012-10-31 19:01:31 -0700229 // Run a dispatch loop if there are no pending commands.
230 // The dispatch loop might enqueue commands to run afterwards.
231 if (!haveCommandsLocked()) {
232 dispatchOnceInnerLocked(&nextWakeupTime);
233 }
Jeff Brown46b9ac02010-04-22 18:58:52 -0700234
Jeff Brown074b8b72012-10-31 19:01:31 -0700235 // Run all pending commands if there are any.
236 // If any commands were run then force the next poll to wake up immediately.
Jeff Brownb88102f2010-09-08 11:49:43 -0700237 if (runCommandsLockedInterruptible()) {
Jeff Brown074b8b72012-10-31 19:01:31 -0700238 nextWakeupTime = LONG_LONG_MIN;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700239 }
Jeff Brown46b9ac02010-04-22 18:58:52 -0700240 } // release lock
241
Jeff Brownb88102f2010-09-08 11:49:43 -0700242 // Wait for callback or timeout or wake. (make sure we round up, not down)
243 nsecs_t currentTime = now();
Jeff Brownaa3855d2011-03-17 01:34:19 -0700244 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
Jeff Brown4fe6c3e2010-09-13 23:17:30 -0700245 mLooper->pollOnce(timeoutMillis);
Jeff Brownb88102f2010-09-08 11:49:43 -0700246}
247
Jeff Brown214eaf42011-05-26 19:17:02 -0700248void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700249 nsecs_t currentTime = now();
250
Jeff Brown037c33e2014-04-09 00:31:55 -0700251 // Reset the key repeat timer whenever normal dispatch is suspended while the
252 // device is in a non-interactive state. This is to ensure that we abort a key
253 // repeat if the device is just coming out of sleep.
254 if (!mDispatchEnabled) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700255 resetKeyRepeatLocked();
256 }
257
Jeff Brownb88102f2010-09-08 11:49:43 -0700258 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
259 if (mDispatchFrozen) {
260#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +0000261 ALOGD("Dispatch frozen. Waiting some more.");
Jeff Brownb88102f2010-09-08 11:49:43 -0700262#endif
263 return;
264 }
265
266 // Optimize latency of app switches.
267 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
268 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
269 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
270 if (mAppSwitchDueTime < *nextWakeupTime) {
271 *nextWakeupTime = mAppSwitchDueTime;
272 }
273
Jeff Brownb88102f2010-09-08 11:49:43 -0700274 // Ready to start a new event.
275 // If we don't already have a pending event, go grab one.
276 if (! mPendingEvent) {
277 if (mInboundQueue.isEmpty()) {
278 if (isAppSwitchDue) {
279 // The inbound queue is empty so the app switch key we were waiting
280 // for will never arrive. Stop waiting for it.
281 resetPendingAppSwitchLocked(false);
282 isAppSwitchDue = false;
283 }
284
285 // Synthesize a key repeat if appropriate.
286 if (mKeyRepeatState.lastKeyEntry) {
287 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
Jeff Brown214eaf42011-05-26 19:17:02 -0700288 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700289 } else {
290 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
291 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
292 }
293 }
294 }
Jeff Browncc4f7db2011-08-30 20:34:48 -0700295
296 // Nothing to do if there is no pending event.
Jeff Browne9bb9be2012-02-06 15:47:55 -0800297 if (!mPendingEvent) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700298 return;
299 }
300 } else {
301 // Inbound queue has at least one entry.
Jeff Browne9bb9be2012-02-06 15:47:55 -0800302 mPendingEvent = mInboundQueue.dequeueAtHead();
Jeff Brown481c1572012-03-09 14:41:15 -0800303 traceInboundQueueLengthLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -0700304 }
Jeff Browne2fe69e2010-10-18 13:21:23 -0700305
306 // Poke user activity for this event.
307 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
308 pokeUserActivityLocked(mPendingEvent);
309 }
Jeff Browne9bb9be2012-02-06 15:47:55 -0800310
311 // Get ready to dispatch the event.
312 resetANRTimeoutsLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -0700313 }
314
315 // Now we have an event to dispatch.
Jeff Brown928e0542011-01-10 11:17:36 -0800316 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Steve Blockec193de2012-01-09 18:35:44 +0000317 ALOG_ASSERT(mPendingEvent != NULL);
Jeff Brown54a18252010-09-16 14:07:33 -0700318 bool done = false;
Jeff Brownb6997262010-10-08 22:31:17 -0700319 DropReason dropReason = DROP_REASON_NOT_DROPPED;
320 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
321 dropReason = DROP_REASON_POLICY;
322 } else if (!mDispatchEnabled) {
323 dropReason = DROP_REASON_DISABLED;
324 }
Jeff Brown928e0542011-01-10 11:17:36 -0800325
326 if (mNextUnblockedEvent == mPendingEvent) {
327 mNextUnblockedEvent = NULL;
328 }
329
Jeff Brownb88102f2010-09-08 11:49:43 -0700330 switch (mPendingEvent->type) {
331 case EventEntry::TYPE_CONFIGURATION_CHANGED: {
332 ConfigurationChangedEntry* typedEntry =
333 static_cast<ConfigurationChangedEntry*>(mPendingEvent);
Jeff Brown54a18252010-09-16 14:07:33 -0700334 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Jeff Brownb6997262010-10-08 22:31:17 -0700335 dropReason = DROP_REASON_NOT_DROPPED; // configuration changes are never dropped
Jeff Brownb88102f2010-09-08 11:49:43 -0700336 break;
337 }
338
Jeff Brown65fd2512011-08-18 11:20:58 -0700339 case EventEntry::TYPE_DEVICE_RESET: {
340 DeviceResetEntry* typedEntry =
341 static_cast<DeviceResetEntry*>(mPendingEvent);
342 done = dispatchDeviceResetLocked(currentTime, typedEntry);
343 dropReason = DROP_REASON_NOT_DROPPED; // device resets are never dropped
344 break;
345 }
346
Jeff Brownb88102f2010-09-08 11:49:43 -0700347 case EventEntry::TYPE_KEY: {
348 KeyEntry* typedEntry = static_cast<KeyEntry*>(mPendingEvent);
Jeff Brownb6997262010-10-08 22:31:17 -0700349 if (isAppSwitchDue) {
350 if (isAppSwitchKeyEventLocked(typedEntry)) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700351 resetPendingAppSwitchLocked(true);
Jeff Brownb6997262010-10-08 22:31:17 -0700352 isAppSwitchDue = false;
353 } else if (dropReason == DROP_REASON_NOT_DROPPED) {
354 dropReason = DROP_REASON_APP_SWITCH;
Jeff Brownb88102f2010-09-08 11:49:43 -0700355 }
356 }
Jeff Brown928e0542011-01-10 11:17:36 -0800357 if (dropReason == DROP_REASON_NOT_DROPPED
358 && isStaleEventLocked(currentTime, typedEntry)) {
359 dropReason = DROP_REASON_STALE;
360 }
361 if (dropReason == DROP_REASON_NOT_DROPPED && mNextUnblockedEvent) {
362 dropReason = DROP_REASON_BLOCKED;
363 }
Jeff Brown214eaf42011-05-26 19:17:02 -0700364 done = dispatchKeyLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700365 break;
366 }
367
368 case EventEntry::TYPE_MOTION: {
369 MotionEntry* typedEntry = static_cast<MotionEntry*>(mPendingEvent);
Jeff Brownb6997262010-10-08 22:31:17 -0700370 if (dropReason == DROP_REASON_NOT_DROPPED && isAppSwitchDue) {
371 dropReason = DROP_REASON_APP_SWITCH;
Jeff Brownb88102f2010-09-08 11:49:43 -0700372 }
Jeff Brown928e0542011-01-10 11:17:36 -0800373 if (dropReason == DROP_REASON_NOT_DROPPED
374 && isStaleEventLocked(currentTime, typedEntry)) {
375 dropReason = DROP_REASON_STALE;
376 }
377 if (dropReason == DROP_REASON_NOT_DROPPED && mNextUnblockedEvent) {
378 dropReason = DROP_REASON_BLOCKED;
379 }
Jeff Brownb6997262010-10-08 22:31:17 -0700380 done = dispatchMotionLocked(currentTime, typedEntry,
Jeff Browne20c9e02010-10-11 14:20:19 -0700381 &dropReason, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700382 break;
383 }
384
385 default:
Steve Blockec193de2012-01-09 18:35:44 +0000386 ALOG_ASSERT(false);
Jeff Brownb88102f2010-09-08 11:49:43 -0700387 break;
388 }
389
Jeff Brown54a18252010-09-16 14:07:33 -0700390 if (done) {
Jeff Brownb6997262010-10-08 22:31:17 -0700391 if (dropReason != DROP_REASON_NOT_DROPPED) {
392 dropInboundEventLocked(mPendingEvent, dropReason);
393 }
394
Jeff Brown54a18252010-09-16 14:07:33 -0700395 releasePendingEventLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -0700396 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
397 }
398}
399
400bool InputDispatcher::enqueueInboundEventLocked(EventEntry* entry) {
401 bool needWake = mInboundQueue.isEmpty();
402 mInboundQueue.enqueueAtTail(entry);
Jeff Brown481c1572012-03-09 14:41:15 -0800403 traceInboundQueueLengthLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -0700404
405 switch (entry->type) {
Jeff Brownb6997262010-10-08 22:31:17 -0700406 case EventEntry::TYPE_KEY: {
Jeff Brown928e0542011-01-10 11:17:36 -0800407 // Optimize app switch latency.
408 // If the application takes too long to catch up then we drop all events preceding
409 // the app switch key.
Jeff Brownb6997262010-10-08 22:31:17 -0700410 KeyEntry* keyEntry = static_cast<KeyEntry*>(entry);
411 if (isAppSwitchKeyEventLocked(keyEntry)) {
412 if (keyEntry->action == AKEY_EVENT_ACTION_DOWN) {
413 mAppSwitchSawKeyDown = true;
414 } else if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
415 if (mAppSwitchSawKeyDown) {
416#if DEBUG_APP_SWITCH
Steve Block5baa3a62011-12-20 16:23:08 +0000417 ALOGD("App switch is pending!");
Jeff Brownb6997262010-10-08 22:31:17 -0700418#endif
419 mAppSwitchDueTime = keyEntry->eventTime + APP_SWITCH_TIMEOUT;
420 mAppSwitchSawKeyDown = false;
421 needWake = true;
422 }
423 }
424 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700425 break;
426 }
Jeff Brown928e0542011-01-10 11:17:36 -0800427
428 case EventEntry::TYPE_MOTION: {
429 // Optimize case where the current application is unresponsive and the user
430 // decides to touch a window in a different application.
431 // If the application takes too long to catch up then we drop all events preceding
432 // the touch into the other window.
433 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
Jeff Brown33bbfd22011-02-24 20:55:35 -0800434 if (motionEntry->action == AMOTION_EVENT_ACTION_DOWN
Jeff Brown928e0542011-01-10 11:17:36 -0800435 && (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER)
436 && mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY
Jeff Brown9302c872011-07-13 22:51:29 -0700437 && mInputTargetWaitApplicationHandle != NULL) {
Jeff Brown83d616a2012-09-09 20:33:43 -0700438 int32_t displayId = motionEntry->displayId;
Jeff Brown3241b6b2012-02-03 15:08:02 -0800439 int32_t x = int32_t(motionEntry->pointerCoords[0].
Jeff Brownebbd5d12011-02-17 13:01:34 -0800440 getAxisValue(AMOTION_EVENT_AXIS_X));
Jeff Brown3241b6b2012-02-03 15:08:02 -0800441 int32_t y = int32_t(motionEntry->pointerCoords[0].
Jeff Brownebbd5d12011-02-17 13:01:34 -0800442 getAxisValue(AMOTION_EVENT_AXIS_Y));
Jeff Brown83d616a2012-09-09 20:33:43 -0700443 sp<InputWindowHandle> touchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y);
Jeff Brown9302c872011-07-13 22:51:29 -0700444 if (touchedWindowHandle != NULL
445 && touchedWindowHandle->inputApplicationHandle
446 != mInputTargetWaitApplicationHandle) {
Jeff Brown928e0542011-01-10 11:17:36 -0800447 // User touched a different application than the one we are waiting on.
448 // Flag the event, and start pruning the input queue.
449 mNextUnblockedEvent = motionEntry;
450 needWake = true;
451 }
452 }
453 break;
454 }
Jeff Brownb6997262010-10-08 22:31:17 -0700455 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700456
457 return needWake;
458}
459
Jeff Brown6876f322013-08-07 16:46:50 -0700460void InputDispatcher::addRecentEventLocked(EventEntry* entry) {
461 entry->refCount += 1;
462 mRecentQueue.enqueueAtTail(entry);
463 if (mRecentQueue.count() > RECENT_QUEUE_MAX_SIZE) {
464 mRecentQueue.dequeueAtHead()->release();
465 }
466}
467
Jeff Brown83d616a2012-09-09 20:33:43 -0700468sp<InputWindowHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId,
469 int32_t x, int32_t y) {
Jeff Brown928e0542011-01-10 11:17:36 -0800470 // Traverse windows from front to back to find touched window.
Jeff Brown9302c872011-07-13 22:51:29 -0700471 size_t numWindows = mWindowHandles.size();
Jeff Brown928e0542011-01-10 11:17:36 -0800472 for (size_t i = 0; i < numWindows; i++) {
Jeff Brown9302c872011-07-13 22:51:29 -0700473 sp<InputWindowHandle> windowHandle = mWindowHandles.itemAt(i);
Jeff Browncc4f7db2011-08-30 20:34:48 -0700474 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Jeff Brown83d616a2012-09-09 20:33:43 -0700475 if (windowInfo->displayId == displayId) {
476 int32_t flags = windowInfo->layoutParamsFlags;
Adam Lesinski95c42972013-10-02 10:13:27 -0700477 int32_t privateFlags = windowInfo->layoutParamsPrivateFlags;
Jeff Brown928e0542011-01-10 11:17:36 -0800478
Jeff Brown83d616a2012-09-09 20:33:43 -0700479 if (windowInfo->visible) {
480 if (!(flags & InputWindowInfo::FLAG_NOT_TOUCHABLE)) {
481 bool isTouchModal = (flags & (InputWindowInfo::FLAG_NOT_FOCUSABLE
482 | InputWindowInfo::FLAG_NOT_TOUCH_MODAL)) == 0;
483 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
484 // Found window.
485 return windowHandle;
486 }
Jeff Brown928e0542011-01-10 11:17:36 -0800487 }
488 }
Jeff Brown928e0542011-01-10 11:17:36 -0800489
Adam Lesinski95c42972013-10-02 10:13:27 -0700490 if (privateFlags & InputWindowInfo::PRIVATE_FLAG_SYSTEM_ERROR) {
Jeff Brown83d616a2012-09-09 20:33:43 -0700491 // Error window is on top but not visible, so touch is dropped.
492 return NULL;
493 }
Jeff Brown928e0542011-01-10 11:17:36 -0800494 }
495 }
496 return NULL;
497}
498
Jeff Brownb6997262010-10-08 22:31:17 -0700499void InputDispatcher::dropInboundEventLocked(EventEntry* entry, DropReason dropReason) {
500 const char* reason;
501 switch (dropReason) {
502 case DROP_REASON_POLICY:
Jeff Browne20c9e02010-10-11 14:20:19 -0700503#if DEBUG_INBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +0000504 ALOGD("Dropped event because policy consumed it.");
Jeff Browne20c9e02010-10-11 14:20:19 -0700505#endif
Jeff Brown3122e442010-10-11 23:32:49 -0700506 reason = "inbound event was dropped because the policy consumed it";
Jeff Brownb6997262010-10-08 22:31:17 -0700507 break;
508 case DROP_REASON_DISABLED:
Steve Block6215d3f2012-01-04 20:05:49 +0000509 ALOGI("Dropped event because input dispatch is disabled.");
Jeff Brownb6997262010-10-08 22:31:17 -0700510 reason = "inbound event was dropped because input dispatch is disabled";
511 break;
512 case DROP_REASON_APP_SWITCH:
Steve Block6215d3f2012-01-04 20:05:49 +0000513 ALOGI("Dropped event because of pending overdue app switch.");
Jeff Brownb6997262010-10-08 22:31:17 -0700514 reason = "inbound event was dropped because of pending overdue app switch";
515 break;
Jeff Brown928e0542011-01-10 11:17:36 -0800516 case DROP_REASON_BLOCKED:
Steve Block6215d3f2012-01-04 20:05:49 +0000517 ALOGI("Dropped event because the current application is not responding and the user "
Jeff Brown81346812011-06-28 20:08:48 -0700518 "has started interacting with a different application.");
Jeff Brown928e0542011-01-10 11:17:36 -0800519 reason = "inbound event was dropped because the current application is not responding "
Jeff Brown81346812011-06-28 20:08:48 -0700520 "and the user has started interacting with a different application";
Jeff Brown928e0542011-01-10 11:17:36 -0800521 break;
522 case DROP_REASON_STALE:
Steve Block6215d3f2012-01-04 20:05:49 +0000523 ALOGI("Dropped event because it is stale.");
Jeff Brown928e0542011-01-10 11:17:36 -0800524 reason = "inbound event was dropped because it is stale";
525 break;
Jeff Brownb6997262010-10-08 22:31:17 -0700526 default:
Steve Blockec193de2012-01-09 18:35:44 +0000527 ALOG_ASSERT(false);
Jeff Brownb6997262010-10-08 22:31:17 -0700528 return;
529 }
530
531 switch (entry->type) {
Jeff Brownda3d5a92011-03-29 15:11:34 -0700532 case EventEntry::TYPE_KEY: {
533 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
534 synthesizeCancelationEventsForAllConnectionsLocked(options);
Jeff Brownb6997262010-10-08 22:31:17 -0700535 break;
Jeff Brownda3d5a92011-03-29 15:11:34 -0700536 }
Jeff Brownb6997262010-10-08 22:31:17 -0700537 case EventEntry::TYPE_MOTION: {
538 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
539 if (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) {
Jeff Brownda3d5a92011-03-29 15:11:34 -0700540 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
541 synthesizeCancelationEventsForAllConnectionsLocked(options);
Jeff Brownb6997262010-10-08 22:31:17 -0700542 } else {
Jeff Brownda3d5a92011-03-29 15:11:34 -0700543 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
544 synthesizeCancelationEventsForAllConnectionsLocked(options);
Jeff Brownb6997262010-10-08 22:31:17 -0700545 }
546 break;
547 }
548 }
549}
550
551bool InputDispatcher::isAppSwitchKeyCode(int32_t keyCode) {
Michael Wright75ebb37f2013-03-15 16:27:29 -0700552 return keyCode == AKEYCODE_HOME
553 || keyCode == AKEYCODE_ENDCALL
554 || keyCode == AKEYCODE_APP_SWITCH;
Jeff Brownb88102f2010-09-08 11:49:43 -0700555}
556
Jeff Brownb6997262010-10-08 22:31:17 -0700557bool InputDispatcher::isAppSwitchKeyEventLocked(KeyEntry* keyEntry) {
558 return ! (keyEntry->flags & AKEY_EVENT_FLAG_CANCELED)
559 && isAppSwitchKeyCode(keyEntry->keyCode)
Jeff Browne20c9e02010-10-11 14:20:19 -0700560 && (keyEntry->policyFlags & POLICY_FLAG_TRUSTED)
Jeff Brownb6997262010-10-08 22:31:17 -0700561 && (keyEntry->policyFlags & POLICY_FLAG_PASS_TO_USER);
562}
563
Jeff Brownb88102f2010-09-08 11:49:43 -0700564bool InputDispatcher::isAppSwitchPendingLocked() {
565 return mAppSwitchDueTime != LONG_LONG_MAX;
566}
567
Jeff Brownb88102f2010-09-08 11:49:43 -0700568void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
569 mAppSwitchDueTime = LONG_LONG_MAX;
570
571#if DEBUG_APP_SWITCH
572 if (handled) {
Steve Block5baa3a62011-12-20 16:23:08 +0000573 ALOGD("App switch has arrived.");
Jeff Brownb88102f2010-09-08 11:49:43 -0700574 } else {
Steve Block5baa3a62011-12-20 16:23:08 +0000575 ALOGD("App switch was abandoned.");
Jeff Brownb88102f2010-09-08 11:49:43 -0700576 }
577#endif
Jeff Brown46b9ac02010-04-22 18:58:52 -0700578}
579
Jeff Brown928e0542011-01-10 11:17:36 -0800580bool InputDispatcher::isStaleEventLocked(nsecs_t currentTime, EventEntry* entry) {
581 return currentTime - entry->eventTime >= STALE_EVENT_TIMEOUT;
582}
583
Jeff Brown074b8b72012-10-31 19:01:31 -0700584bool InputDispatcher::haveCommandsLocked() const {
585 return !mCommandQueue.isEmpty();
586}
587
Jeff Brown9c3cda02010-06-15 01:31:58 -0700588bool InputDispatcher::runCommandsLockedInterruptible() {
589 if (mCommandQueue.isEmpty()) {
590 return false;
591 }
Jeff Brown46b9ac02010-04-22 18:58:52 -0700592
Jeff Brown9c3cda02010-06-15 01:31:58 -0700593 do {
594 CommandEntry* commandEntry = mCommandQueue.dequeueAtHead();
595
596 Command command = commandEntry->command;
597 (this->*command)(commandEntry); // commands are implicitly 'LockedInterruptible'
598
Jeff Brown7fbdc842010-06-17 20:52:56 -0700599 commandEntry->connection.clear();
Jeff Brownac386072011-07-20 15:19:50 -0700600 delete commandEntry;
Jeff Brown9c3cda02010-06-15 01:31:58 -0700601 } while (! mCommandQueue.isEmpty());
602 return true;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700603}
604
Jeff Brown9c3cda02010-06-15 01:31:58 -0700605InputDispatcher::CommandEntry* InputDispatcher::postCommandLocked(Command command) {
Jeff Brownac386072011-07-20 15:19:50 -0700606 CommandEntry* commandEntry = new CommandEntry(command);
Jeff Brown9c3cda02010-06-15 01:31:58 -0700607 mCommandQueue.enqueueAtTail(commandEntry);
608 return commandEntry;
609}
610
Jeff Brownb88102f2010-09-08 11:49:43 -0700611void InputDispatcher::drainInboundQueueLocked() {
612 while (! mInboundQueue.isEmpty()) {
613 EventEntry* entry = mInboundQueue.dequeueAtHead();
Jeff Brown54a18252010-09-16 14:07:33 -0700614 releaseInboundEventLocked(entry);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700615 }
Jeff Brown481c1572012-03-09 14:41:15 -0800616 traceInboundQueueLengthLocked();
Jeff Brown46b9ac02010-04-22 18:58:52 -0700617}
618
Jeff Brown54a18252010-09-16 14:07:33 -0700619void InputDispatcher::releasePendingEventLocked() {
Jeff Brownb88102f2010-09-08 11:49:43 -0700620 if (mPendingEvent) {
Jeff Browne9bb9be2012-02-06 15:47:55 -0800621 resetANRTimeoutsLocked();
Jeff Brown54a18252010-09-16 14:07:33 -0700622 releaseInboundEventLocked(mPendingEvent);
Jeff Brownb88102f2010-09-08 11:49:43 -0700623 mPendingEvent = NULL;
624 }
625}
626
Jeff Brown54a18252010-09-16 14:07:33 -0700627void InputDispatcher::releaseInboundEventLocked(EventEntry* entry) {
Jeff Brown01ce2e92010-09-26 22:20:12 -0700628 InjectionState* injectionState = entry->injectionState;
629 if (injectionState && injectionState->injectionResult == INPUT_EVENT_INJECTION_PENDING) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700630#if DEBUG_DISPATCH_CYCLE
Steve Block5baa3a62011-12-20 16:23:08 +0000631 ALOGD("Injected inbound event was dropped.");
Jeff Brownb88102f2010-09-08 11:49:43 -0700632#endif
633 setInjectionResultLocked(entry, INPUT_EVENT_INJECTION_FAILED);
634 }
Jeff Brownabb4d442011-08-15 12:55:32 -0700635 if (entry == mNextUnblockedEvent) {
636 mNextUnblockedEvent = NULL;
637 }
Jeff Brown6876f322013-08-07 16:46:50 -0700638 addRecentEventLocked(entry);
Jeff Brownac386072011-07-20 15:19:50 -0700639 entry->release();
Jeff Brownb88102f2010-09-08 11:49:43 -0700640}
641
Jeff Brownb88102f2010-09-08 11:49:43 -0700642void InputDispatcher::resetKeyRepeatLocked() {
643 if (mKeyRepeatState.lastKeyEntry) {
Jeff Brownac386072011-07-20 15:19:50 -0700644 mKeyRepeatState.lastKeyEntry->release();
Jeff Brownb88102f2010-09-08 11:49:43 -0700645 mKeyRepeatState.lastKeyEntry = NULL;
646 }
647}
648
Jeff Brown214eaf42011-05-26 19:17:02 -0700649InputDispatcher::KeyEntry* InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
Jeff Brown349703e2010-06-22 01:27:15 -0700650 KeyEntry* entry = mKeyRepeatState.lastKeyEntry;
651
Jeff Brown349703e2010-06-22 01:27:15 -0700652 // Reuse the repeated key entry if it is otherwise unreferenced.
Jeff Browne20c9e02010-10-11 14:20:19 -0700653 uint32_t policyFlags = (entry->policyFlags & POLICY_FLAG_RAW_MASK)
654 | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700655 if (entry->refCount == 1) {
Jeff Brownac386072011-07-20 15:19:50 -0700656 entry->recycle();
Jeff Brown7fbdc842010-06-17 20:52:56 -0700657 entry->eventTime = currentTime;
Jeff Brown7fbdc842010-06-17 20:52:56 -0700658 entry->policyFlags = policyFlags;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700659 entry->repeatCount += 1;
660 } else {
Jeff Brownac386072011-07-20 15:19:50 -0700661 KeyEntry* newEntry = new KeyEntry(currentTime,
Jeff Brownc5ed5912010-07-14 18:48:53 -0700662 entry->deviceId, entry->source, policyFlags,
Jeff Brown7fbdc842010-06-17 20:52:56 -0700663 entry->action, entry->flags, entry->keyCode, entry->scanCode,
Jeff Brown00fa7bd2010-07-02 15:37:36 -0700664 entry->metaState, entry->repeatCount + 1, entry->downTime);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700665
666 mKeyRepeatState.lastKeyEntry = newEntry;
Jeff Brownac386072011-07-20 15:19:50 -0700667 entry->release();
Jeff Brown46b9ac02010-04-22 18:58:52 -0700668
669 entry = newEntry;
670 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700671 entry->syntheticRepeat = true;
672
673 // Increment reference count since we keep a reference to the event in
674 // mKeyRepeatState.lastKeyEntry in addition to the one we return.
675 entry->refCount += 1;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700676
Jeff Brown214eaf42011-05-26 19:17:02 -0700677 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Jeff Brownb88102f2010-09-08 11:49:43 -0700678 return entry;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700679}
680
Jeff Brownb88102f2010-09-08 11:49:43 -0700681bool InputDispatcher::dispatchConfigurationChangedLocked(
682 nsecs_t currentTime, ConfigurationChangedEntry* entry) {
Jeff Brown46b9ac02010-04-22 18:58:52 -0700683#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +0000684 ALOGD("dispatchConfigurationChanged - eventTime=%lld", entry->eventTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700685#endif
686
687 // Reset key repeating in case a keyboard device was added or removed or something.
688 resetKeyRepeatLocked();
689
690 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
691 CommandEntry* commandEntry = postCommandLocked(
692 & InputDispatcher::doNotifyConfigurationChangedInterruptible);
693 commandEntry->eventTime = entry->eventTime;
694 return true;
695}
696
Jeff Brown65fd2512011-08-18 11:20:58 -0700697bool InputDispatcher::dispatchDeviceResetLocked(
698 nsecs_t currentTime, DeviceResetEntry* entry) {
699#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +0000700 ALOGD("dispatchDeviceReset - eventTime=%lld, deviceId=%d", entry->eventTime, entry->deviceId);
Jeff Brown65fd2512011-08-18 11:20:58 -0700701#endif
702
703 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
704 "device was reset");
705 options.deviceId = entry->deviceId;
706 synthesizeCancelationEventsForAllConnectionsLocked(options);
707 return true;
708}
709
Jeff Brown214eaf42011-05-26 19:17:02 -0700710bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, KeyEntry* entry,
Jeff Browne20c9e02010-10-11 14:20:19 -0700711 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Jeff Browne46a0a42010-11-02 17:58:22 -0700712 // Preprocessing.
713 if (! entry->dispatchInProgress) {
714 if (entry->repeatCount == 0
715 && entry->action == AKEY_EVENT_ACTION_DOWN
716 && (entry->policyFlags & POLICY_FLAG_TRUSTED)
Jeff Brown0029c662011-03-30 02:25:18 -0700717 && (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
Jeff Browne46a0a42010-11-02 17:58:22 -0700718 if (mKeyRepeatState.lastKeyEntry
719 && mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode) {
720 // We have seen two identical key downs in a row which indicates that the device
721 // driver is automatically generating key repeats itself. We take note of the
722 // repeat here, but we disable our own next key repeat timer since it is clear that
723 // we will not need to synthesize key repeats ourselves.
724 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
725 resetKeyRepeatLocked();
726 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
727 } else {
728 // Not a repeat. Save key down state in case we do see a repeat later.
729 resetKeyRepeatLocked();
Jeff Brown214eaf42011-05-26 19:17:02 -0700730 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
Jeff Browne46a0a42010-11-02 17:58:22 -0700731 }
732 mKeyRepeatState.lastKeyEntry = entry;
733 entry->refCount += 1;
734 } else if (! entry->syntheticRepeat) {
735 resetKeyRepeatLocked();
736 }
737
Jeff Browne2e01262011-03-02 20:34:30 -0800738 if (entry->repeatCount == 1) {
739 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
740 } else {
741 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
742 }
743
Jeff Browne46a0a42010-11-02 17:58:22 -0700744 entry->dispatchInProgress = true;
Jeff Browne46a0a42010-11-02 17:58:22 -0700745
746 logOutboundKeyDetailsLocked("dispatchKey - ", entry);
747 }
748
Jeff Brown905805a2011-10-12 13:57:59 -0700749 // Handle case where the policy asked us to try again later last time.
750 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
751 if (currentTime < entry->interceptKeyWakeupTime) {
752 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
753 *nextWakeupTime = entry->interceptKeyWakeupTime;
754 }
755 return false; // wait until next wakeup
756 }
757 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
758 entry->interceptKeyWakeupTime = 0;
759 }
760
Jeff Brown54a18252010-09-16 14:07:33 -0700761 // Give the policy a chance to intercept the key.
762 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
Jeff Browne20c9e02010-10-11 14:20:19 -0700763 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Jeff Brown54a18252010-09-16 14:07:33 -0700764 CommandEntry* commandEntry = postCommandLocked(
765 & InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
Jeff Brown9302c872011-07-13 22:51:29 -0700766 if (mFocusedWindowHandle != NULL) {
767 commandEntry->inputWindowHandle = mFocusedWindowHandle;
Jeff Brown54a18252010-09-16 14:07:33 -0700768 }
769 commandEntry->keyEntry = entry;
770 entry->refCount += 1;
771 return false; // wait for the command to run
772 } else {
773 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
774 }
775 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Jeff Browne20c9e02010-10-11 14:20:19 -0700776 if (*dropReason == DROP_REASON_NOT_DROPPED) {
777 *dropReason = DROP_REASON_POLICY;
778 }
Jeff Brown54a18252010-09-16 14:07:33 -0700779 }
780
781 // Clean up if dropping the event.
Jeff Browne20c9e02010-10-11 14:20:19 -0700782 if (*dropReason != DROP_REASON_NOT_DROPPED) {
Jeff Brown3122e442010-10-11 23:32:49 -0700783 setInjectionResultLocked(entry, *dropReason == DROP_REASON_POLICY
784 ? INPUT_EVENT_INJECTION_SUCCEEDED : INPUT_EVENT_INJECTION_FAILED);
Jeff Brown54a18252010-09-16 14:07:33 -0700785 return true;
786 }
787
Jeff Brownb88102f2010-09-08 11:49:43 -0700788 // Identify targets.
Jeff Browne9bb9be2012-02-06 15:47:55 -0800789 Vector<InputTarget> inputTargets;
790 int32_t injectionResult = findFocusedWindowTargetsLocked(currentTime,
791 entry, inputTargets, nextWakeupTime);
792 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
793 return false;
Jeff Brownb88102f2010-09-08 11:49:43 -0700794 }
795
Jeff Browne9bb9be2012-02-06 15:47:55 -0800796 setInjectionResultLocked(entry, injectionResult);
797 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
798 return true;
799 }
800
801 addMonitoringTargetsLocked(inputTargets);
802
Jeff Brownb88102f2010-09-08 11:49:43 -0700803 // Dispatch the key.
Jeff Browne9bb9be2012-02-06 15:47:55 -0800804 dispatchEventLocked(currentTime, entry, inputTargets);
Jeff Brownb88102f2010-09-08 11:49:43 -0700805 return true;
806}
807
808void InputDispatcher::logOutboundKeyDetailsLocked(const char* prefix, const KeyEntry* entry) {
809#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +0000810 ALOGD("%seventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, "
Jeff Brownb88102f2010-09-08 11:49:43 -0700811 "action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, "
Jeff Browne46a0a42010-11-02 17:58:22 -0700812 "repeatCount=%d, downTime=%lld",
Jeff Brownb88102f2010-09-08 11:49:43 -0700813 prefix,
814 entry->eventTime, entry->deviceId, entry->source, entry->policyFlags,
815 entry->action, entry->flags, entry->keyCode, entry->scanCode, entry->metaState,
Jeff Browne46a0a42010-11-02 17:58:22 -0700816 entry->repeatCount, entry->downTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700817#endif
818}
819
820bool InputDispatcher::dispatchMotionLocked(
Jeff Browne20c9e02010-10-11 14:20:19 -0700821 nsecs_t currentTime, MotionEntry* entry, DropReason* dropReason, nsecs_t* nextWakeupTime) {
Jeff Browne46a0a42010-11-02 17:58:22 -0700822 // Preprocessing.
823 if (! entry->dispatchInProgress) {
824 entry->dispatchInProgress = true;
Jeff Browne46a0a42010-11-02 17:58:22 -0700825
826 logOutboundMotionDetailsLocked("dispatchMotion - ", entry);
827 }
828
Jeff Brown54a18252010-09-16 14:07:33 -0700829 // Clean up if dropping the event.
Jeff Browne20c9e02010-10-11 14:20:19 -0700830 if (*dropReason != DROP_REASON_NOT_DROPPED) {
Jeff Brown3122e442010-10-11 23:32:49 -0700831 setInjectionResultLocked(entry, *dropReason == DROP_REASON_POLICY
832 ? INPUT_EVENT_INJECTION_SUCCEEDED : INPUT_EVENT_INJECTION_FAILED);
Jeff Brown54a18252010-09-16 14:07:33 -0700833 return true;
834 }
835
Jeff Brownb88102f2010-09-08 11:49:43 -0700836 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
837
838 // Identify targets.
Jeff Browne9bb9be2012-02-06 15:47:55 -0800839 Vector<InputTarget> inputTargets;
840
Jeff Browncc0c1592011-02-19 05:07:28 -0800841 bool conflictingPointerActions = false;
Jeff Browne9bb9be2012-02-06 15:47:55 -0800842 int32_t injectionResult;
843 if (isPointerEvent) {
844 // Pointer event. (eg. touchscreen)
845 injectionResult = findTouchedWindowTargetsLocked(currentTime,
846 entry, inputTargets, nextWakeupTime, &conflictingPointerActions);
847 } else {
848 // Non touch event. (eg. trackball)
849 injectionResult = findFocusedWindowTargetsLocked(currentTime,
850 entry, inputTargets, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700851 }
Jeff Browne9bb9be2012-02-06 15:47:55 -0800852 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
853 return false;
854 }
855
856 setInjectionResultLocked(entry, injectionResult);
857 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
858 return true;
859 }
860
Jeff Brown83d616a2012-09-09 20:33:43 -0700861 // TODO: support sending secondary display events to input monitors
862 if (isMainDisplay(entry->displayId)) {
863 addMonitoringTargetsLocked(inputTargets);
864 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700865
866 // Dispatch the motion.
Jeff Browncc0c1592011-02-19 05:07:28 -0800867 if (conflictingPointerActions) {
Jeff Brownda3d5a92011-03-29 15:11:34 -0700868 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
869 "conflicting pointer actions");
870 synthesizeCancelationEventsForAllConnectionsLocked(options);
Jeff Browncc0c1592011-02-19 05:07:28 -0800871 }
Jeff Browne9bb9be2012-02-06 15:47:55 -0800872 dispatchEventLocked(currentTime, entry, inputTargets);
Jeff Brownb88102f2010-09-08 11:49:43 -0700873 return true;
874}
875
876
877void InputDispatcher::logOutboundMotionDetailsLocked(const char* prefix, const MotionEntry* entry) {
878#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +0000879 ALOGD("%seventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, "
Jeff Brown85a31762010-09-01 17:01:00 -0700880 "action=0x%x, flags=0x%x, "
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700881 "metaState=0x%x, buttonState=0x%x, "
882 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%lld",
Jeff Brownb88102f2010-09-08 11:49:43 -0700883 prefix,
Jeff Brown85a31762010-09-01 17:01:00 -0700884 entry->eventTime, entry->deviceId, entry->source, entry->policyFlags,
885 entry->action, entry->flags,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700886 entry->metaState, entry->buttonState,
887 entry->edgeFlags, entry->xPrecision, entry->yPrecision,
Jeff Brown46b9ac02010-04-22 18:58:52 -0700888 entry->downTime);
889
Jeff Brown46b9ac02010-04-22 18:58:52 -0700890 for (uint32_t i = 0; i < entry->pointerCount; i++) {
Steve Block5baa3a62011-12-20 16:23:08 +0000891 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700892 "x=%f, y=%f, pressure=%f, size=%f, "
Jeff Brown85a31762010-09-01 17:01:00 -0700893 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
Jeff Brown8d608662010-08-30 03:02:23 -0700894 "orientation=%f",
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700895 i, entry->pointerProperties[i].id,
896 entry->pointerProperties[i].toolType,
Jeff Brown3241b6b2012-02-03 15:08:02 -0800897 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
898 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
899 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
900 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
901 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
902 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
903 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
904 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
905 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Jeff Brown46b9ac02010-04-22 18:58:52 -0700906 }
907#endif
Jeff Brown46b9ac02010-04-22 18:58:52 -0700908}
909
Jeff Browne9bb9be2012-02-06 15:47:55 -0800910void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
911 EventEntry* eventEntry, const Vector<InputTarget>& inputTargets) {
Jeff Brown46b9ac02010-04-22 18:58:52 -0700912#if DEBUG_DISPATCH_CYCLE
Jeff Brown3241b6b2012-02-03 15:08:02 -0800913 ALOGD("dispatchEventToCurrentInputTargets");
Jeff Brown46b9ac02010-04-22 18:58:52 -0700914#endif
915
Steve Blockec193de2012-01-09 18:35:44 +0000916 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
Jeff Brown9c3cda02010-06-15 01:31:58 -0700917
Jeff Browne2fe69e2010-10-18 13:21:23 -0700918 pokeUserActivityLocked(eventEntry);
919
Jeff Browne9bb9be2012-02-06 15:47:55 -0800920 for (size_t i = 0; i < inputTargets.size(); i++) {
921 const InputTarget& inputTarget = inputTargets.itemAt(i);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700922
Jeff Brown519e0242010-09-15 15:18:56 -0700923 ssize_t connectionIndex = getConnectionIndexLocked(inputTarget.inputChannel);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700924 if (connectionIndex >= 0) {
Jeff Browncbee6d62012-02-03 20:11:27 -0800925 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
Jeff Brown3241b6b2012-02-03 15:08:02 -0800926 prepareDispatchCycleLocked(currentTime, connection, eventEntry, &inputTarget);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700927 } else {
Jeff Brownb6997262010-10-08 22:31:17 -0700928#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +0000929 ALOGD("Dropping event delivery to target with channel '%s' because it "
Jeff Brownb6997262010-10-08 22:31:17 -0700930 "is no longer registered with the input dispatcher.",
Jeff Brown46b9ac02010-04-22 18:58:52 -0700931 inputTarget.inputChannel->getName().string());
Jeff Brownb6997262010-10-08 22:31:17 -0700932#endif
Jeff Brown46b9ac02010-04-22 18:58:52 -0700933 }
934 }
935}
936
Jeff Brownb88102f2010-09-08 11:49:43 -0700937int32_t InputDispatcher::handleTargetsNotReadyLocked(nsecs_t currentTime,
Jeff Brown9302c872011-07-13 22:51:29 -0700938 const EventEntry* entry,
939 const sp<InputApplicationHandle>& applicationHandle,
940 const sp<InputWindowHandle>& windowHandle,
Jeff Brown265f1cc2012-06-11 18:01:06 -0700941 nsecs_t* nextWakeupTime, const char* reason) {
Jeff Brown9302c872011-07-13 22:51:29 -0700942 if (applicationHandle == NULL && windowHandle == NULL) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700943 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY) {
944#if DEBUG_FOCUS
Jeff Brown265f1cc2012-06-11 18:01:06 -0700945 ALOGD("Waiting for system to become ready for input. Reason: %s", reason);
Jeff Brownb88102f2010-09-08 11:49:43 -0700946#endif
947 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY;
948 mInputTargetWaitStartTime = currentTime;
949 mInputTargetWaitTimeoutTime = LONG_LONG_MAX;
950 mInputTargetWaitTimeoutExpired = false;
Jeff Brown9302c872011-07-13 22:51:29 -0700951 mInputTargetWaitApplicationHandle.clear();
Jeff Brownb88102f2010-09-08 11:49:43 -0700952 }
953 } else {
954 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
955#if DEBUG_FOCUS
Jeff Brown265f1cc2012-06-11 18:01:06 -0700956 ALOGD("Waiting for application to become ready for input: %s. Reason: %s",
957 getApplicationWindowLabelLocked(applicationHandle, windowHandle).string(),
958 reason);
Jeff Brownb88102f2010-09-08 11:49:43 -0700959#endif
Jeff Browncc4f7db2011-08-30 20:34:48 -0700960 nsecs_t timeout;
961 if (windowHandle != NULL) {
962 timeout = windowHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
963 } else if (applicationHandle != NULL) {
964 timeout = applicationHandle->getDispatchingTimeout(
965 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
966 } else {
967 timeout = DEFAULT_INPUT_DISPATCHING_TIMEOUT;
968 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700969
970 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY;
971 mInputTargetWaitStartTime = currentTime;
972 mInputTargetWaitTimeoutTime = currentTime + timeout;
973 mInputTargetWaitTimeoutExpired = false;
Jeff Brown9302c872011-07-13 22:51:29 -0700974 mInputTargetWaitApplicationHandle.clear();
Jeff Brown928e0542011-01-10 11:17:36 -0800975
Jeff Brown9302c872011-07-13 22:51:29 -0700976 if (windowHandle != NULL) {
977 mInputTargetWaitApplicationHandle = windowHandle->inputApplicationHandle;
Jeff Brown928e0542011-01-10 11:17:36 -0800978 }
Jeff Brown9302c872011-07-13 22:51:29 -0700979 if (mInputTargetWaitApplicationHandle == NULL && applicationHandle != NULL) {
980 mInputTargetWaitApplicationHandle = applicationHandle;
Jeff Brown928e0542011-01-10 11:17:36 -0800981 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700982 }
983 }
984
985 if (mInputTargetWaitTimeoutExpired) {
986 return INPUT_EVENT_INJECTION_TIMED_OUT;
987 }
988
989 if (currentTime >= mInputTargetWaitTimeoutTime) {
Jeff Brown9302c872011-07-13 22:51:29 -0700990 onANRLocked(currentTime, applicationHandle, windowHandle,
Jeff Brown265f1cc2012-06-11 18:01:06 -0700991 entry->eventTime, mInputTargetWaitStartTime, reason);
Jeff Brownb88102f2010-09-08 11:49:43 -0700992
993 // Force poll loop to wake up immediately on next iteration once we get the
994 // ANR response back from the policy.
995 *nextWakeupTime = LONG_LONG_MIN;
996 return INPUT_EVENT_INJECTION_PENDING;
997 } else {
998 // Force poll loop to wake up when timeout is due.
999 if (mInputTargetWaitTimeoutTime < *nextWakeupTime) {
1000 *nextWakeupTime = mInputTargetWaitTimeoutTime;
1001 }
1002 return INPUT_EVENT_INJECTION_PENDING;
1003 }
1004}
1005
Jeff Brown519e0242010-09-15 15:18:56 -07001006void InputDispatcher::resumeAfterTargetsNotReadyTimeoutLocked(nsecs_t newTimeout,
1007 const sp<InputChannel>& inputChannel) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001008 if (newTimeout > 0) {
1009 // Extend the timeout.
1010 mInputTargetWaitTimeoutTime = now() + newTimeout;
1011 } else {
1012 // Give up.
1013 mInputTargetWaitTimeoutExpired = true;
Jeff Brown519e0242010-09-15 15:18:56 -07001014
1015 // Input state will not be realistic. Mark it out of sync.
Jeff Browndc3e0052010-09-16 11:02:16 -07001016 if (inputChannel.get()) {
1017 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
1018 if (connectionIndex >= 0) {
Jeff Browncbee6d62012-02-03 20:11:27 -08001019 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
Jeff Brownf44e3942012-04-20 11:33:27 -07001020 sp<InputWindowHandle> windowHandle = connection->inputWindowHandle;
1021
1022 if (windowHandle != NULL) {
Jeff Brown38f96e52014-02-11 14:32:56 -08001023 const InputWindowInfo* info = windowHandle->getInfo();
1024 if (info) {
1025 ssize_t stateIndex = mTouchStatesByDisplay.indexOfKey(info->displayId);
1026 if (stateIndex >= 0) {
1027 mTouchStatesByDisplay.editValueAt(stateIndex).removeWindow(
1028 windowHandle);
1029 }
1030 }
Jeff Brownf44e3942012-04-20 11:33:27 -07001031 }
1032
Jeff Brown00045a72010-12-09 18:10:30 -08001033 if (connection->status == Connection::STATUS_NORMAL) {
Jeff Brownda3d5a92011-03-29 15:11:34 -07001034 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
Jeff Brown00045a72010-12-09 18:10:30 -08001035 "application not responding");
Jeff Brownda3d5a92011-03-29 15:11:34 -07001036 synthesizeCancelationEventsForConnectionLocked(connection, options);
Jeff Brown00045a72010-12-09 18:10:30 -08001037 }
Jeff Browndc3e0052010-09-16 11:02:16 -07001038 }
Jeff Brown519e0242010-09-15 15:18:56 -07001039 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001040 }
1041}
1042
Jeff Brown519e0242010-09-15 15:18:56 -07001043nsecs_t InputDispatcher::getTimeSpentWaitingForApplicationLocked(
Jeff Brownb88102f2010-09-08 11:49:43 -07001044 nsecs_t currentTime) {
1045 if (mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
1046 return currentTime - mInputTargetWaitStartTime;
1047 }
1048 return 0;
1049}
1050
1051void InputDispatcher::resetANRTimeoutsLocked() {
1052#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001053 ALOGD("Resetting ANR timeouts.");
Jeff Brownb88102f2010-09-08 11:49:43 -07001054#endif
1055
Jeff Brownb88102f2010-09-08 11:49:43 -07001056 // Reset input target wait timeout.
1057 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_NONE;
Jeff Brown5ea29ab2011-07-27 11:50:51 -07001058 mInputTargetWaitApplicationHandle.clear();
Jeff Brownb88102f2010-09-08 11:49:43 -07001059}
1060
Jeff Brown01ce2e92010-09-26 22:20:12 -07001061int32_t InputDispatcher::findFocusedWindowTargetsLocked(nsecs_t currentTime,
Jeff Browne9bb9be2012-02-06 15:47:55 -08001062 const EventEntry* entry, Vector<InputTarget>& inputTargets, nsecs_t* nextWakeupTime) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001063 int32_t injectionResult;
1064
1065 // If there is no currently focused window and no focused application
1066 // then drop the event.
Jeff Brown9302c872011-07-13 22:51:29 -07001067 if (mFocusedWindowHandle == NULL) {
1068 if (mFocusedApplicationHandle != NULL) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001069 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brown265f1cc2012-06-11 18:01:06 -07001070 mFocusedApplicationHandle, NULL, nextWakeupTime,
1071 "Waiting because no window has focus but there is a "
1072 "focused application that may eventually add a window "
1073 "when it finishes starting up.");
Jeff Brownb88102f2010-09-08 11:49:43 -07001074 goto Unresponsive;
1075 }
1076
Steve Block6215d3f2012-01-04 20:05:49 +00001077 ALOGI("Dropping event because there is no focused window or focused application.");
Jeff Brownb88102f2010-09-08 11:49:43 -07001078 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1079 goto Failed;
1080 }
1081
1082 // Check permissions.
Jeff Brown9302c872011-07-13 22:51:29 -07001083 if (! checkInjectionPermission(mFocusedWindowHandle, entry->injectionState)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001084 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1085 goto Failed;
1086 }
1087
1088 // If the currently focused window is paused then keep waiting.
Jeff Browncc4f7db2011-08-30 20:34:48 -07001089 if (mFocusedWindowHandle->getInfo()->paused) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001090 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brown265f1cc2012-06-11 18:01:06 -07001091 mFocusedApplicationHandle, mFocusedWindowHandle, nextWakeupTime,
1092 "Waiting because the focused window is paused.");
Jeff Brownb88102f2010-09-08 11:49:43 -07001093 goto Unresponsive;
1094 }
1095
Jeff Brown519e0242010-09-15 15:18:56 -07001096 // If the currently focused window is still working on previous events then keep waiting.
Jeff Brown0952c302012-02-13 13:48:59 -08001097 if (!isWindowReadyForMoreInputLocked(currentTime, mFocusedWindowHandle, entry)) {
Jeff Brown519e0242010-09-15 15:18:56 -07001098 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brown265f1cc2012-06-11 18:01:06 -07001099 mFocusedApplicationHandle, mFocusedWindowHandle, nextWakeupTime,
1100 "Waiting because the focused window has not finished "
1101 "processing the input events that were previously delivered to it.");
Jeff Brown519e0242010-09-15 15:18:56 -07001102 goto Unresponsive;
1103 }
1104
Jeff Brownb88102f2010-09-08 11:49:43 -07001105 // Success! Output targets.
1106 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
Jeff Brown9302c872011-07-13 22:51:29 -07001107 addWindowTargetLocked(mFocusedWindowHandle,
Jeff Browne9bb9be2012-02-06 15:47:55 -08001108 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS, BitSet32(0),
1109 inputTargets);
Jeff Brownb88102f2010-09-08 11:49:43 -07001110
1111 // Done.
1112Failed:
1113Unresponsive:
Jeff Brown519e0242010-09-15 15:18:56 -07001114 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
1115 updateDispatchStatisticsLocked(currentTime, entry,
1116 injectionResult, timeSpentWaitingForApplication);
Jeff Brownb88102f2010-09-08 11:49:43 -07001117#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001118 ALOGD("findFocusedWindow finished: injectionResult=%d, "
Jeff Brown22aa5122012-06-17 12:01:06 -07001119 "timeSpentWaitingForApplication=%0.1fms",
Jeff Brown519e0242010-09-15 15:18:56 -07001120 injectionResult, timeSpentWaitingForApplication / 1000000.0);
Jeff Brownb88102f2010-09-08 11:49:43 -07001121#endif
1122 return injectionResult;
1123}
1124
Jeff Brown01ce2e92010-09-26 22:20:12 -07001125int32_t InputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime,
Jeff Browne9bb9be2012-02-06 15:47:55 -08001126 const MotionEntry* entry, Vector<InputTarget>& inputTargets, nsecs_t* nextWakeupTime,
1127 bool* outConflictingPointerActions) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001128 enum InjectionPermission {
1129 INJECTION_PERMISSION_UNKNOWN,
1130 INJECTION_PERMISSION_GRANTED,
1131 INJECTION_PERMISSION_DENIED
1132 };
1133
Jeff Brownb88102f2010-09-08 11:49:43 -07001134 nsecs_t startTime = now();
1135
1136 // For security reasons, we defer updating the touch state until we are sure that
1137 // event injection will be allowed.
Jeff Brown83d616a2012-09-09 20:33:43 -07001138 int32_t displayId = entry->displayId;
Jeff Brownb88102f2010-09-08 11:49:43 -07001139 int32_t action = entry->action;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001140 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Jeff Brownb88102f2010-09-08 11:49:43 -07001141
1142 // Update the touch state as needed based on the properties of the touch event.
Jeff Brown01ce2e92010-09-26 22:20:12 -07001143 int32_t injectionResult = INPUT_EVENT_INJECTION_PENDING;
1144 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
Jeff Brown9302c872011-07-13 22:51:29 -07001145 sp<InputWindowHandle> newHoverWindowHandle;
Jeff Browncc0c1592011-02-19 05:07:28 -08001146
Jeff Brown38f96e52014-02-11 14:32:56 -08001147 // Copy current touch state into mTempTouchState.
1148 // This state is always reset at the end of this function, so if we don't find state
1149 // for the specified display then our initial state will be empty.
1150 const TouchState* oldState = NULL;
1151 ssize_t oldStateIndex = mTouchStatesByDisplay.indexOfKey(displayId);
1152 if (oldStateIndex >= 0) {
1153 oldState = &mTouchStatesByDisplay.valueAt(oldStateIndex);
1154 mTempTouchState.copyFrom(*oldState);
1155 }
1156
1157 bool isSplit = mTempTouchState.split;
1158 bool switchedDevice = mTempTouchState.deviceId >= 0 && mTempTouchState.displayId >= 0
1159 && (mTempTouchState.deviceId != entry->deviceId
1160 || mTempTouchState.source != entry->source
1161 || mTempTouchState.displayId != displayId);
Jeff Browna032cc02011-03-07 16:56:21 -08001162 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE
1163 || maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER
1164 || maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1165 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN
1166 || maskedAction == AMOTION_EVENT_ACTION_SCROLL
1167 || isHoverAction);
Jeff Brown81346812011-06-28 20:08:48 -07001168 bool wrongDevice = false;
Jeff Browna032cc02011-03-07 16:56:21 -08001169 if (newGesture) {
Jeff Browncc0c1592011-02-19 05:07:28 -08001170 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Jeff Brown38f96e52014-02-11 14:32:56 -08001171 if (switchedDevice && mTempTouchState.down && !down) {
Jeff Brown81346812011-06-28 20:08:48 -07001172#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001173 ALOGD("Dropping event because a pointer for a different device is already down.");
Jeff Brown81346812011-06-28 20:08:48 -07001174#endif
Jeff Brown81346812011-06-28 20:08:48 -07001175 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1176 switchedDevice = false;
1177 wrongDevice = true;
1178 goto Failed;
Jeff Browncc0c1592011-02-19 05:07:28 -08001179 }
Jeff Brown81346812011-06-28 20:08:48 -07001180 mTempTouchState.reset();
1181 mTempTouchState.down = down;
1182 mTempTouchState.deviceId = entry->deviceId;
1183 mTempTouchState.source = entry->source;
Jeff Brown83d616a2012-09-09 20:33:43 -07001184 mTempTouchState.displayId = displayId;
Jeff Brown81346812011-06-28 20:08:48 -07001185 isSplit = false;
Jeff Browncc0c1592011-02-19 05:07:28 -08001186 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001187
Jeff Browna032cc02011-03-07 16:56:21 -08001188 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
Jeff Brown33bbfd22011-02-24 20:55:35 -08001189 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
Jeff Brownb88102f2010-09-08 11:49:43 -07001190
Jeff Brown01ce2e92010-09-26 22:20:12 -07001191 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Jeff Brown3241b6b2012-02-03 15:08:02 -08001192 int32_t x = int32_t(entry->pointerCoords[pointerIndex].
Jeff Brownebbd5d12011-02-17 13:01:34 -08001193 getAxisValue(AMOTION_EVENT_AXIS_X));
Jeff Brown3241b6b2012-02-03 15:08:02 -08001194 int32_t y = int32_t(entry->pointerCoords[pointerIndex].
Jeff Brownebbd5d12011-02-17 13:01:34 -08001195 getAxisValue(AMOTION_EVENT_AXIS_Y));
Jeff Brown9302c872011-07-13 22:51:29 -07001196 sp<InputWindowHandle> newTouchedWindowHandle;
1197 sp<InputWindowHandle> topErrorWindowHandle;
Jeff Browna032cc02011-03-07 16:56:21 -08001198 bool isTouchModal = false;
Jeff Brownb88102f2010-09-08 11:49:43 -07001199
1200 // Traverse windows from front to back to find touched window and outside targets.
Jeff Brown9302c872011-07-13 22:51:29 -07001201 size_t numWindows = mWindowHandles.size();
Jeff Brownb88102f2010-09-08 11:49:43 -07001202 for (size_t i = 0; i < numWindows; i++) {
Jeff Brown9302c872011-07-13 22:51:29 -07001203 sp<InputWindowHandle> windowHandle = mWindowHandles.itemAt(i);
Jeff Browncc4f7db2011-08-30 20:34:48 -07001204 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Jeff Brown83d616a2012-09-09 20:33:43 -07001205 if (windowInfo->displayId != displayId) {
1206 continue; // wrong display
1207 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001208
Adam Lesinski95c42972013-10-02 10:13:27 -07001209 int32_t privateFlags = windowInfo->layoutParamsPrivateFlags;
1210 if (privateFlags & InputWindowInfo::PRIVATE_FLAG_SYSTEM_ERROR) {
Jeff Brown9302c872011-07-13 22:51:29 -07001211 if (topErrorWindowHandle == NULL) {
1212 topErrorWindowHandle = windowHandle;
Jeff Brownb88102f2010-09-08 11:49:43 -07001213 }
1214 }
1215
Adam Lesinski95c42972013-10-02 10:13:27 -07001216 int32_t flags = windowInfo->layoutParamsFlags;
Jeff Browncc4f7db2011-08-30 20:34:48 -07001217 if (windowInfo->visible) {
1218 if (! (flags & InputWindowInfo::FLAG_NOT_TOUCHABLE)) {
1219 isTouchModal = (flags & (InputWindowInfo::FLAG_NOT_FOCUSABLE
1220 | InputWindowInfo::FLAG_NOT_TOUCH_MODAL)) == 0;
1221 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
Jeff Brown037c33e2014-04-09 00:31:55 -07001222 newTouchedWindowHandle = windowHandle;
Jeff Brownb88102f2010-09-08 11:49:43 -07001223 break; // found touched window, exit window loop
1224 }
1225 }
1226
Jeff Brown01ce2e92010-09-26 22:20:12 -07001227 if (maskedAction == AMOTION_EVENT_ACTION_DOWN
Jeff Browncc4f7db2011-08-30 20:34:48 -07001228 && (flags & InputWindowInfo::FLAG_WATCH_OUTSIDE_TOUCH)) {
Jeff Browna032cc02011-03-07 16:56:21 -08001229 int32_t outsideTargetFlags = InputTarget::FLAG_DISPATCH_AS_OUTSIDE;
Jeff Brown9302c872011-07-13 22:51:29 -07001230 if (isWindowObscuredAtPointLocked(windowHandle, x, y)) {
Jeff Brown19dfc832010-10-05 12:26:23 -07001231 outsideTargetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1232 }
1233
Jeff Brown9302c872011-07-13 22:51:29 -07001234 mTempTouchState.addOrUpdateWindow(
1235 windowHandle, outsideTargetFlags, BitSet32(0));
Jeff Brownb88102f2010-09-08 11:49:43 -07001236 }
1237 }
1238 }
1239
1240 // If there is an error window but it is not taking focus (typically because
1241 // it is invisible) then wait for it. Any other focused window may in
1242 // fact be in ANR state.
Jeff Brown9302c872011-07-13 22:51:29 -07001243 if (topErrorWindowHandle != NULL && newTouchedWindowHandle != topErrorWindowHandle) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001244 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brown265f1cc2012-06-11 18:01:06 -07001245 NULL, NULL, nextWakeupTime,
1246 "Waiting because a system error window is about to be displayed.");
Jeff Brownb88102f2010-09-08 11:49:43 -07001247 injectionPermission = INJECTION_PERMISSION_UNKNOWN;
1248 goto Unresponsive;
1249 }
1250
Jeff Brown01ce2e92010-09-26 22:20:12 -07001251 // Figure out whether splitting will be allowed for this window.
Jeff Browncc4f7db2011-08-30 20:34:48 -07001252 if (newTouchedWindowHandle != NULL
1253 && newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001254 // New window supports splitting.
1255 isSplit = true;
1256 } else if (isSplit) {
1257 // New window does not support splitting but we have already split events.
Jeff Brown8249fc62012-05-24 18:57:32 -07001258 // Ignore the new window.
1259 newTouchedWindowHandle = NULL;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001260 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001261
Jeff Brown8249fc62012-05-24 18:57:32 -07001262 // Handle the case where we did not find a window.
Jeff Brown9302c872011-07-13 22:51:29 -07001263 if (newTouchedWindowHandle == NULL) {
Jeff Brown8249fc62012-05-24 18:57:32 -07001264 // Try to assign the pointer to the first foreground window we find, if there is one.
1265 newTouchedWindowHandle = mTempTouchState.getFirstForegroundWindowHandle();
1266 if (newTouchedWindowHandle == NULL) {
Jeff Brown0b31d812013-08-22 19:41:29 -07001267 ALOGI("Dropping event because there is no touchable window at (%d, %d).", x, y);
Jeff Brown8249fc62012-05-24 18:57:32 -07001268 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1269 goto Failed;
1270 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001271 }
1272
Jeff Brown19dfc832010-10-05 12:26:23 -07001273 // Set target flags.
Jeff Browna032cc02011-03-07 16:56:21 -08001274 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
Jeff Brown19dfc832010-10-05 12:26:23 -07001275 if (isSplit) {
1276 targetFlags |= InputTarget::FLAG_SPLIT;
1277 }
Jeff Brown9302c872011-07-13 22:51:29 -07001278 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
Jeff Brown19dfc832010-10-05 12:26:23 -07001279 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1280 }
1281
Jeff Browna032cc02011-03-07 16:56:21 -08001282 // Update hover state.
1283 if (isHoverAction) {
Jeff Brown9302c872011-07-13 22:51:29 -07001284 newHoverWindowHandle = newTouchedWindowHandle;
Jeff Browna032cc02011-03-07 16:56:21 -08001285 } else if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
Jeff Brown9302c872011-07-13 22:51:29 -07001286 newHoverWindowHandle = mLastHoverWindowHandle;
Jeff Browna032cc02011-03-07 16:56:21 -08001287 }
1288
Jeff Brown01ce2e92010-09-26 22:20:12 -07001289 // Update the temporary touch state.
1290 BitSet32 pointerIds;
1291 if (isSplit) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07001292 uint32_t pointerId = entry->pointerProperties[pointerIndex].id;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001293 pointerIds.markBit(pointerId);
Jeff Brownb88102f2010-09-08 11:49:43 -07001294 }
Jeff Brown9302c872011-07-13 22:51:29 -07001295 mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Jeff Brownb88102f2010-09-08 11:49:43 -07001296 } else {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001297 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
Jeff Brownb88102f2010-09-08 11:49:43 -07001298
1299 // If the pointer is not currently down, then ignore the event.
Jeff Brown01ce2e92010-09-26 22:20:12 -07001300 if (! mTempTouchState.down) {
Jeff Browna2cc28d2011-03-25 11:58:46 -07001301#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001302 ALOGD("Dropping event because the pointer is not down or we previously "
Jeff Brown76860e32010-10-25 17:37:46 -07001303 "dropped the pointer down event.");
1304#endif
Jeff Brownb88102f2010-09-08 11:49:43 -07001305 injectionResult = INPUT_EVENT_INJECTION_FAILED;
Jeff Brownb88102f2010-09-08 11:49:43 -07001306 goto Failed;
1307 }
Jeff Brown98db5fa2011-06-08 15:37:10 -07001308
1309 // Check whether touches should slip outside of the current foreground window.
1310 if (maskedAction == AMOTION_EVENT_ACTION_MOVE
1311 && entry->pointerCount == 1
1312 && mTempTouchState.isSlippery()) {
Jeff Brown3241b6b2012-02-03 15:08:02 -08001313 int32_t x = int32_t(entry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
1314 int32_t y = int32_t(entry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Jeff Brown98db5fa2011-06-08 15:37:10 -07001315
Jeff Brown9302c872011-07-13 22:51:29 -07001316 sp<InputWindowHandle> oldTouchedWindowHandle =
1317 mTempTouchState.getFirstForegroundWindowHandle();
Jeff Brown83d616a2012-09-09 20:33:43 -07001318 sp<InputWindowHandle> newTouchedWindowHandle =
1319 findTouchedWindowAtLocked(displayId, x, y);
Jeff Brown9302c872011-07-13 22:51:29 -07001320 if (oldTouchedWindowHandle != newTouchedWindowHandle
1321 && newTouchedWindowHandle != NULL) {
Jeff Brown98db5fa2011-06-08 15:37:10 -07001322#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001323 ALOGD("Touch is slipping out of window %s into window %s.",
Jeff Browncc4f7db2011-08-30 20:34:48 -07001324 oldTouchedWindowHandle->getName().string(),
1325 newTouchedWindowHandle->getName().string());
Jeff Brown98db5fa2011-06-08 15:37:10 -07001326#endif
1327 // Make a slippery exit from the old window.
Jeff Brown9302c872011-07-13 22:51:29 -07001328 mTempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
Jeff Brown98db5fa2011-06-08 15:37:10 -07001329 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT, BitSet32(0));
1330
1331 // Make a slippery entrance into the new window.
Jeff Browncc4f7db2011-08-30 20:34:48 -07001332 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Jeff Brown98db5fa2011-06-08 15:37:10 -07001333 isSplit = true;
1334 }
1335
1336 int32_t targetFlags = InputTarget::FLAG_FOREGROUND
1337 | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
1338 if (isSplit) {
1339 targetFlags |= InputTarget::FLAG_SPLIT;
1340 }
Jeff Brown9302c872011-07-13 22:51:29 -07001341 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
Jeff Brown98db5fa2011-06-08 15:37:10 -07001342 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1343 }
1344
1345 BitSet32 pointerIds;
1346 if (isSplit) {
1347 pointerIds.markBit(entry->pointerProperties[0].id);
1348 }
Jeff Brown9302c872011-07-13 22:51:29 -07001349 mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Jeff Brown98db5fa2011-06-08 15:37:10 -07001350 }
1351 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001352 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001353
Jeff Brown9302c872011-07-13 22:51:29 -07001354 if (newHoverWindowHandle != mLastHoverWindowHandle) {
Jeff Browna032cc02011-03-07 16:56:21 -08001355 // Let the previous window know that the hover sequence is over.
Jeff Brown9302c872011-07-13 22:51:29 -07001356 if (mLastHoverWindowHandle != NULL) {
Jeff Browna032cc02011-03-07 16:56:21 -08001357#if DEBUG_HOVER
Steve Block5baa3a62011-12-20 16:23:08 +00001358 ALOGD("Sending hover exit event to window %s.",
Jeff Browncc4f7db2011-08-30 20:34:48 -07001359 mLastHoverWindowHandle->getName().string());
Jeff Browna032cc02011-03-07 16:56:21 -08001360#endif
Jeff Brown9302c872011-07-13 22:51:29 -07001361 mTempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
Jeff Browna032cc02011-03-07 16:56:21 -08001362 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
1363 }
1364
1365 // Let the new window know that the hover sequence is starting.
Jeff Brown9302c872011-07-13 22:51:29 -07001366 if (newHoverWindowHandle != NULL) {
Jeff Browna032cc02011-03-07 16:56:21 -08001367#if DEBUG_HOVER
Steve Block5baa3a62011-12-20 16:23:08 +00001368 ALOGD("Sending hover enter event to window %s.",
Jeff Browncc4f7db2011-08-30 20:34:48 -07001369 newHoverWindowHandle->getName().string());
Jeff Browna032cc02011-03-07 16:56:21 -08001370#endif
Jeff Brown9302c872011-07-13 22:51:29 -07001371 mTempTouchState.addOrUpdateWindow(newHoverWindowHandle,
Jeff Browna032cc02011-03-07 16:56:21 -08001372 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER, BitSet32(0));
1373 }
1374 }
1375
Jeff Brown01ce2e92010-09-26 22:20:12 -07001376 // Check permission to inject into all touched foreground windows and ensure there
1377 // is at least one touched foreground window.
1378 {
1379 bool haveForegroundWindow = false;
1380 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1381 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1382 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1383 haveForegroundWindow = true;
Jeff Brown9302c872011-07-13 22:51:29 -07001384 if (! checkInjectionPermission(touchedWindow.windowHandle,
1385 entry->injectionState)) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001386 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1387 injectionPermission = INJECTION_PERMISSION_DENIED;
1388 goto Failed;
1389 }
1390 }
1391 }
1392 if (! haveForegroundWindow) {
Jeff Browna2cc28d2011-03-25 11:58:46 -07001393#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001394 ALOGD("Dropping event because there is no touched foreground window to receive it.");
Jeff Brownb88102f2010-09-08 11:49:43 -07001395#endif
1396 injectionResult = INPUT_EVENT_INJECTION_FAILED;
Jeff Brownb88102f2010-09-08 11:49:43 -07001397 goto Failed;
1398 }
1399
Jeff Brown01ce2e92010-09-26 22:20:12 -07001400 // Permission granted to injection into all touched foreground windows.
1401 injectionPermission = INJECTION_PERMISSION_GRANTED;
1402 }
Jeff Brown519e0242010-09-15 15:18:56 -07001403
Kenny Root7a9db182011-06-02 15:16:05 -07001404 // Check whether windows listening for outside touches are owned by the same UID. If it is
1405 // set the policy flag that we will not reveal coordinate information to this window.
1406 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
Jeff Brown9302c872011-07-13 22:51:29 -07001407 sp<InputWindowHandle> foregroundWindowHandle =
1408 mTempTouchState.getFirstForegroundWindowHandle();
Jeff Browncc4f7db2011-08-30 20:34:48 -07001409 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Kenny Root7a9db182011-06-02 15:16:05 -07001410 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1411 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1412 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
Jeff Brown9302c872011-07-13 22:51:29 -07001413 sp<InputWindowHandle> inputWindowHandle = touchedWindow.windowHandle;
Jeff Browncc4f7db2011-08-30 20:34:48 -07001414 if (inputWindowHandle->getInfo()->ownerUid != foregroundWindowUid) {
Jeff Brown9302c872011-07-13 22:51:29 -07001415 mTempTouchState.addOrUpdateWindow(inputWindowHandle,
Kenny Root7a9db182011-06-02 15:16:05 -07001416 InputTarget::FLAG_ZERO_COORDS, BitSet32(0));
1417 }
1418 }
1419 }
1420 }
1421
Jeff Brown01ce2e92010-09-26 22:20:12 -07001422 // Ensure all touched foreground windows are ready for new input.
1423 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1424 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1425 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1426 // If the touched window is paused then keep waiting.
Jeff Browncc4f7db2011-08-30 20:34:48 -07001427 if (touchedWindow.windowHandle->getInfo()->paused) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001428 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brown265f1cc2012-06-11 18:01:06 -07001429 NULL, touchedWindow.windowHandle, nextWakeupTime,
1430 "Waiting because the touched window is paused.");
Jeff Brown01ce2e92010-09-26 22:20:12 -07001431 goto Unresponsive;
1432 }
1433
1434 // If the touched window is still working on previous events then keep waiting.
Jeff Brown0952c302012-02-13 13:48:59 -08001435 if (!isWindowReadyForMoreInputLocked(currentTime, touchedWindow.windowHandle, entry)) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001436 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brown265f1cc2012-06-11 18:01:06 -07001437 NULL, touchedWindow.windowHandle, nextWakeupTime,
1438 "Waiting because the touched window has not finished "
1439 "processing the input events that were previously delivered to it.");
Jeff Brown01ce2e92010-09-26 22:20:12 -07001440 goto Unresponsive;
1441 }
1442 }
1443 }
1444
1445 // If this is the first pointer going down and the touched window has a wallpaper
1446 // then also add the touched wallpaper windows so they are locked in for the duration
1447 // of the touch gesture.
Jeff Brown33bbfd22011-02-24 20:55:35 -08001448 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
1449 // engine only supports touch events. We would need to add a mechanism similar
1450 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
1451 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
Jeff Brown9302c872011-07-13 22:51:29 -07001452 sp<InputWindowHandle> foregroundWindowHandle =
1453 mTempTouchState.getFirstForegroundWindowHandle();
Jeff Browncc4f7db2011-08-30 20:34:48 -07001454 if (foregroundWindowHandle->getInfo()->hasWallpaper) {
Jeff Brown9302c872011-07-13 22:51:29 -07001455 for (size_t i = 0; i < mWindowHandles.size(); i++) {
1456 sp<InputWindowHandle> windowHandle = mWindowHandles.itemAt(i);
Jeff Brown83d616a2012-09-09 20:33:43 -07001457 const InputWindowInfo* info = windowHandle->getInfo();
1458 if (info->displayId == displayId
1459 && windowHandle->getInfo()->layoutParamsType
1460 == InputWindowInfo::TYPE_WALLPAPER) {
Jeff Brown9302c872011-07-13 22:51:29 -07001461 mTempTouchState.addOrUpdateWindow(windowHandle,
Jeff Browna032cc02011-03-07 16:56:21 -08001462 InputTarget::FLAG_WINDOW_IS_OBSCURED
1463 | InputTarget::FLAG_DISPATCH_AS_IS,
1464 BitSet32(0));
Jeff Brown01ce2e92010-09-26 22:20:12 -07001465 }
1466 }
1467 }
1468 }
1469
Jeff Brownb88102f2010-09-08 11:49:43 -07001470 // Success! Output targets.
1471 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
Jeff Brownb88102f2010-09-08 11:49:43 -07001472
Jeff Brown01ce2e92010-09-26 22:20:12 -07001473 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1474 const TouchedWindow& touchedWindow = mTempTouchState.windows.itemAt(i);
Jeff Brown9302c872011-07-13 22:51:29 -07001475 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Jeff Browne9bb9be2012-02-06 15:47:55 -08001476 touchedWindow.pointerIds, inputTargets);
Jeff Brownb88102f2010-09-08 11:49:43 -07001477 }
1478
Jeff Browna032cc02011-03-07 16:56:21 -08001479 // Drop the outside or hover touch windows since we will not care about them
1480 // in the next iteration.
1481 mTempTouchState.filterNonAsIsTouchWindows();
Jeff Brown01ce2e92010-09-26 22:20:12 -07001482
Jeff Brownb88102f2010-09-08 11:49:43 -07001483Failed:
1484 // Check injection permission once and for all.
1485 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001486 if (checkInjectionPermission(NULL, entry->injectionState)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001487 injectionPermission = INJECTION_PERMISSION_GRANTED;
1488 } else {
1489 injectionPermission = INJECTION_PERMISSION_DENIED;
1490 }
1491 }
1492
1493 // Update final pieces of touch state if the injector had permission.
1494 if (injectionPermission == INJECTION_PERMISSION_GRANTED) {
Jeff Brown95712852011-01-04 19:41:59 -08001495 if (!wrongDevice) {
Jeff Brown81346812011-06-28 20:08:48 -07001496 if (switchedDevice) {
1497#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001498 ALOGD("Conflicting pointer actions: Switched to a different device.");
Jeff Brown81346812011-06-28 20:08:48 -07001499#endif
1500 *outConflictingPointerActions = true;
1501 }
1502
1503 if (isHoverAction) {
1504 // Started hovering, therefore no longer down.
Jeff Brown38f96e52014-02-11 14:32:56 -08001505 if (oldState && oldState->down) {
Jeff Brown81346812011-06-28 20:08:48 -07001506#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001507 ALOGD("Conflicting pointer actions: Hover received while pointer was down.");
Jeff Brown81346812011-06-28 20:08:48 -07001508#endif
1509 *outConflictingPointerActions = true;
1510 }
Jeff Brown38f96e52014-02-11 14:32:56 -08001511 mTempTouchState.reset();
Jeff Brown81346812011-06-28 20:08:48 -07001512 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER
1513 || maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Jeff Brown38f96e52014-02-11 14:32:56 -08001514 mTempTouchState.deviceId = entry->deviceId;
1515 mTempTouchState.source = entry->source;
1516 mTempTouchState.displayId = displayId;
Jeff Brown81346812011-06-28 20:08:48 -07001517 }
1518 } else if (maskedAction == AMOTION_EVENT_ACTION_UP
1519 || maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Jeff Brown95712852011-01-04 19:41:59 -08001520 // All pointers up or canceled.
Jeff Brown38f96e52014-02-11 14:32:56 -08001521 mTempTouchState.reset();
Jeff Brown95712852011-01-04 19:41:59 -08001522 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1523 // First pointer went down.
Jeff Brown38f96e52014-02-11 14:32:56 -08001524 if (oldState && oldState->down) {
Jeff Brownb6997262010-10-08 22:31:17 -07001525#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001526 ALOGD("Conflicting pointer actions: Down received while already down.");
Jeff Brownb6997262010-10-08 22:31:17 -07001527#endif
Jeff Brown81346812011-06-28 20:08:48 -07001528 *outConflictingPointerActions = true;
Jeff Brown95712852011-01-04 19:41:59 -08001529 }
1530 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
1531 // One pointer went up.
1532 if (isSplit) {
1533 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07001534 uint32_t pointerId = entry->pointerProperties[pointerIndex].id;
Jeff Brownb88102f2010-09-08 11:49:43 -07001535
Jeff Brown95712852011-01-04 19:41:59 -08001536 for (size_t i = 0; i < mTempTouchState.windows.size(); ) {
1537 TouchedWindow& touchedWindow = mTempTouchState.windows.editItemAt(i);
1538 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
1539 touchedWindow.pointerIds.clearBit(pointerId);
1540 if (touchedWindow.pointerIds.isEmpty()) {
1541 mTempTouchState.windows.removeAt(i);
1542 continue;
1543 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001544 }
Jeff Brown95712852011-01-04 19:41:59 -08001545 i += 1;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001546 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001547 }
Jeff Brown38f96e52014-02-11 14:32:56 -08001548 }
1549
1550 // Save changes unless the action was scroll in which case the temporary touch
1551 // state was only valid for this one action.
1552 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
1553 if (mTempTouchState.displayId >= 0) {
1554 if (oldStateIndex >= 0) {
1555 mTouchStatesByDisplay.editValueAt(oldStateIndex).copyFrom(mTempTouchState);
1556 } else {
1557 mTouchStatesByDisplay.add(displayId, mTempTouchState);
1558 }
1559 } else if (oldStateIndex >= 0) {
1560 mTouchStatesByDisplay.removeItemsAt(oldStateIndex);
1561 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001562 }
Jeff Browna032cc02011-03-07 16:56:21 -08001563
1564 // Update hover state.
Jeff Brown9302c872011-07-13 22:51:29 -07001565 mLastHoverWindowHandle = newHoverWindowHandle;
Jeff Brown95712852011-01-04 19:41:59 -08001566 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001567 } else {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001568#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001569 ALOGD("Not updating touch focus because injection was denied.");
Jeff Brown01ce2e92010-09-26 22:20:12 -07001570#endif
Jeff Brownb88102f2010-09-08 11:49:43 -07001571 }
1572
1573Unresponsive:
Jeff Brown120a4592010-10-27 18:43:51 -07001574 // Reset temporary touch state to ensure we release unnecessary references to input channels.
1575 mTempTouchState.reset();
1576
Jeff Brown519e0242010-09-15 15:18:56 -07001577 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
1578 updateDispatchStatisticsLocked(currentTime, entry,
1579 injectionResult, timeSpentWaitingForApplication);
Jeff Brownb88102f2010-09-08 11:49:43 -07001580#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001581 ALOGD("findTouchedWindow finished: injectionResult=%d, injectionPermission=%d, "
Jeff Brown01ce2e92010-09-26 22:20:12 -07001582 "timeSpentWaitingForApplication=%0.1fms",
Jeff Brown519e0242010-09-15 15:18:56 -07001583 injectionResult, injectionPermission, timeSpentWaitingForApplication / 1000000.0);
Jeff Brownb88102f2010-09-08 11:49:43 -07001584#endif
1585 return injectionResult;
1586}
1587
Jeff Brown9302c872011-07-13 22:51:29 -07001588void InputDispatcher::addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
Jeff Browne9bb9be2012-02-06 15:47:55 -08001589 int32_t targetFlags, BitSet32 pointerIds, Vector<InputTarget>& inputTargets) {
1590 inputTargets.push();
Jeff Brownb88102f2010-09-08 11:49:43 -07001591
Jeff Browncc4f7db2011-08-30 20:34:48 -07001592 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Jeff Browne9bb9be2012-02-06 15:47:55 -08001593 InputTarget& target = inputTargets.editTop();
Jeff Browncc4f7db2011-08-30 20:34:48 -07001594 target.inputChannel = windowInfo->inputChannel;
Jeff Brownb88102f2010-09-08 11:49:43 -07001595 target.flags = targetFlags;
Jeff Browncc4f7db2011-08-30 20:34:48 -07001596 target.xOffset = - windowInfo->frameLeft;
1597 target.yOffset = - windowInfo->frameTop;
1598 target.scaleFactor = windowInfo->scaleFactor;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001599 target.pointerIds = pointerIds;
Jeff Brownb88102f2010-09-08 11:49:43 -07001600}
1601
Jeff Browne9bb9be2012-02-06 15:47:55 -08001602void InputDispatcher::addMonitoringTargetsLocked(Vector<InputTarget>& inputTargets) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001603 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
Jeff Browne9bb9be2012-02-06 15:47:55 -08001604 inputTargets.push();
Jeff Brownb88102f2010-09-08 11:49:43 -07001605
Jeff Browne9bb9be2012-02-06 15:47:55 -08001606 InputTarget& target = inputTargets.editTop();
Jeff Brownb88102f2010-09-08 11:49:43 -07001607 target.inputChannel = mMonitoringChannels[i];
Jeff Brownb6110c22011-04-01 16:15:13 -07001608 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
Jeff Brownb88102f2010-09-08 11:49:43 -07001609 target.xOffset = 0;
1610 target.yOffset = 0;
Jeff Brownb6110c22011-04-01 16:15:13 -07001611 target.pointerIds.clear();
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001612 target.scaleFactor = 1.0f;
Jeff Brownb88102f2010-09-08 11:49:43 -07001613 }
1614}
1615
Jeff Brown9302c872011-07-13 22:51:29 -07001616bool InputDispatcher::checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
Jeff Brown01ce2e92010-09-26 22:20:12 -07001617 const InjectionState* injectionState) {
1618 if (injectionState
Jeff Browncc4f7db2011-08-30 20:34:48 -07001619 && (windowHandle == NULL
1620 || windowHandle->getInfo()->ownerUid != injectionState->injectorUid)
Jeff Brownb6997262010-10-08 22:31:17 -07001621 && !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Jeff Brown9302c872011-07-13 22:51:29 -07001622 if (windowHandle != NULL) {
Steve Block8564c8d2012-01-05 23:22:43 +00001623 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
Jeff Brown9302c872011-07-13 22:51:29 -07001624 "owned by uid %d",
Jeff Brownb6997262010-10-08 22:31:17 -07001625 injectionState->injectorPid, injectionState->injectorUid,
Jeff Browncc4f7db2011-08-30 20:34:48 -07001626 windowHandle->getName().string(),
1627 windowHandle->getInfo()->ownerUid);
Jeff Brownb6997262010-10-08 22:31:17 -07001628 } else {
Steve Block8564c8d2012-01-05 23:22:43 +00001629 ALOGW("Permission denied: injecting event from pid %d uid %d",
Jeff Brownb6997262010-10-08 22:31:17 -07001630 injectionState->injectorPid, injectionState->injectorUid);
Jeff Brownb88102f2010-09-08 11:49:43 -07001631 }
Jeff Brownb6997262010-10-08 22:31:17 -07001632 return false;
Jeff Brownb88102f2010-09-08 11:49:43 -07001633 }
1634 return true;
1635}
1636
Jeff Brown19dfc832010-10-05 12:26:23 -07001637bool InputDispatcher::isWindowObscuredAtPointLocked(
Jeff Brown9302c872011-07-13 22:51:29 -07001638 const sp<InputWindowHandle>& windowHandle, int32_t x, int32_t y) const {
Jeff Brown83d616a2012-09-09 20:33:43 -07001639 int32_t displayId = windowHandle->getInfo()->displayId;
Jeff Brown9302c872011-07-13 22:51:29 -07001640 size_t numWindows = mWindowHandles.size();
Jeff Brownb88102f2010-09-08 11:49:43 -07001641 for (size_t i = 0; i < numWindows; i++) {
Jeff Brown9302c872011-07-13 22:51:29 -07001642 sp<InputWindowHandle> otherHandle = mWindowHandles.itemAt(i);
1643 if (otherHandle == windowHandle) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001644 break;
1645 }
Jeff Browncc4f7db2011-08-30 20:34:48 -07001646
1647 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Jeff Brown83d616a2012-09-09 20:33:43 -07001648 if (otherInfo->displayId == displayId
1649 && otherInfo->visible && !otherInfo->isTrustedOverlay()
Jeff Browncc4f7db2011-08-30 20:34:48 -07001650 && otherInfo->frameContainsPoint(x, y)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001651 return true;
1652 }
1653 }
1654 return false;
1655}
1656
Jeff Brownd1c48a02012-02-06 19:12:47 -08001657bool InputDispatcher::isWindowReadyForMoreInputLocked(nsecs_t currentTime,
Jeff Brown0952c302012-02-13 13:48:59 -08001658 const sp<InputWindowHandle>& windowHandle, const EventEntry* eventEntry) {
Jeff Browncc4f7db2011-08-30 20:34:48 -07001659 ssize_t connectionIndex = getConnectionIndexLocked(windowHandle->getInputChannel());
Jeff Brown519e0242010-09-15 15:18:56 -07001660 if (connectionIndex >= 0) {
Jeff Browncbee6d62012-02-03 20:11:27 -08001661 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
Jeff Brownd1c48a02012-02-06 19:12:47 -08001662 if (connection->inputPublisherBlocked) {
1663 return false;
1664 }
Jeff Brown0952c302012-02-13 13:48:59 -08001665 if (eventEntry->type == EventEntry::TYPE_KEY) {
1666 // If the event is a key event, then we must wait for all previous events to
1667 // complete before delivering it because previous events may have the
1668 // side-effect of transferring focus to a different window and we want to
1669 // ensure that the following keys are sent to the new window.
1670 //
1671 // Suppose the user touches a button in a window then immediately presses "A".
1672 // If the button causes a pop-up window to appear then we want to ensure that
1673 // the "A" key is delivered to the new pop-up window. This is because users
1674 // often anticipate pending UI changes when typing on a keyboard.
1675 // To obtain this behavior, we must serialize key events with respect to all
1676 // prior input events.
Jeff Brownd1c48a02012-02-06 19:12:47 -08001677 return connection->outboundQueue.isEmpty()
1678 && connection->waitQueue.isEmpty();
1679 }
Jeff Brown0952c302012-02-13 13:48:59 -08001680 // Touch events can always be sent to a window immediately because the user intended
1681 // to touch whatever was visible at the time. Even if focus changes or a new
1682 // window appears moments later, the touch event was meant to be delivered to
1683 // whatever window happened to be on screen at the time.
1684 //
1685 // Generic motion events, such as trackball or joystick events are a little trickier.
1686 // Like key events, generic motion events are delivered to the focused window.
1687 // Unlike key events, generic motion events don't tend to transfer focus to other
1688 // windows and it is not important for them to be serialized. So we prefer to deliver
1689 // generic motion events as soon as possible to improve efficiency and reduce lag
1690 // through batching.
1691 //
1692 // The one case where we pause input event delivery is when the wait queue is piling
1693 // up with lots of events because the application is not responding.
1694 // This condition ensures that ANRs are detected reliably.
Jeff Brownd1c48a02012-02-06 19:12:47 -08001695 if (!connection->waitQueue.isEmpty()
Jeff Brown786dccf2013-10-17 19:40:40 -07001696 && currentTime >= connection->waitQueue.head->deliveryTime
Jeff Brownd1c48a02012-02-06 19:12:47 -08001697 + STREAM_AHEAD_EVENT_TIMEOUT) {
1698 return false;
1699 }
Jeff Brown519e0242010-09-15 15:18:56 -07001700 }
Jeff Brownd1c48a02012-02-06 19:12:47 -08001701 return true;
Jeff Brown519e0242010-09-15 15:18:56 -07001702}
1703
Jeff Brown9302c872011-07-13 22:51:29 -07001704String8 InputDispatcher::getApplicationWindowLabelLocked(
1705 const sp<InputApplicationHandle>& applicationHandle,
1706 const sp<InputWindowHandle>& windowHandle) {
1707 if (applicationHandle != NULL) {
1708 if (windowHandle != NULL) {
Jeff Browncc4f7db2011-08-30 20:34:48 -07001709 String8 label(applicationHandle->getName());
Jeff Brown519e0242010-09-15 15:18:56 -07001710 label.append(" - ");
Jeff Browncc4f7db2011-08-30 20:34:48 -07001711 label.append(windowHandle->getName());
Jeff Brown519e0242010-09-15 15:18:56 -07001712 return label;
1713 } else {
Jeff Browncc4f7db2011-08-30 20:34:48 -07001714 return applicationHandle->getName();
Jeff Brown519e0242010-09-15 15:18:56 -07001715 }
Jeff Brown9302c872011-07-13 22:51:29 -07001716 } else if (windowHandle != NULL) {
Jeff Browncc4f7db2011-08-30 20:34:48 -07001717 return windowHandle->getName();
Jeff Brown519e0242010-09-15 15:18:56 -07001718 } else {
1719 return String8("<unknown application or window>");
1720 }
1721}
1722
Jeff Browne2fe69e2010-10-18 13:21:23 -07001723void InputDispatcher::pokeUserActivityLocked(const EventEntry* eventEntry) {
Jeff Brown1e3b98d2012-09-30 18:58:59 -07001724 if (mFocusedWindowHandle != NULL) {
1725 const InputWindowInfo* info = mFocusedWindowHandle->getInfo();
1726 if (info->inputFeatures & InputWindowInfo::INPUT_FEATURE_DISABLE_USER_ACTIVITY) {
1727#if DEBUG_DISPATCH_CYCLE
1728 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.string());
1729#endif
1730 return;
1731 }
1732 }
1733
Jeff Brownb696de52012-07-27 15:38:50 -07001734 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Jeff Brown4d396052010-10-29 21:50:21 -07001735 switch (eventEntry->type) {
1736 case EventEntry::TYPE_MOTION: {
Jeff Browne2fe69e2010-10-18 13:21:23 -07001737 const MotionEntry* motionEntry = static_cast<const MotionEntry*>(eventEntry);
Jeff Brown4d396052010-10-29 21:50:21 -07001738 if (motionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
1739 return;
1740 }
1741
Jeff Brown56194eb2011-03-02 19:23:13 -08001742 if (MotionEvent::isTouchEvent(motionEntry->source, motionEntry->action)) {
Jeff Brownb696de52012-07-27 15:38:50 -07001743 eventType = USER_ACTIVITY_EVENT_TOUCH;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001744 }
Jeff Brown4d396052010-10-29 21:50:21 -07001745 break;
1746 }
1747 case EventEntry::TYPE_KEY: {
1748 const KeyEntry* keyEntry = static_cast<const KeyEntry*>(eventEntry);
1749 if (keyEntry->flags & AKEY_EVENT_FLAG_CANCELED) {
1750 return;
1751 }
Jeff Brownb696de52012-07-27 15:38:50 -07001752 eventType = USER_ACTIVITY_EVENT_BUTTON;
Jeff Brown4d396052010-10-29 21:50:21 -07001753 break;
1754 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001755 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001756
Jeff Brownb88102f2010-09-08 11:49:43 -07001757 CommandEntry* commandEntry = postCommandLocked(
1758 & InputDispatcher::doPokeUserActivityLockedInterruptible);
Jeff Browne2fe69e2010-10-18 13:21:23 -07001759 commandEntry->eventTime = eventEntry->eventTime;
Jeff Brownb88102f2010-09-08 11:49:43 -07001760 commandEntry->userActivityEventType = eventType;
1761}
1762
Jeff Brown7fbdc842010-06-17 20:52:56 -07001763void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001764 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07001765#if DEBUG_DISPATCH_CYCLE
Steve Block5baa3a62011-12-20 16:23:08 +00001766 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
Jeff Brown9cc695c2011-08-23 18:35:04 -07001767 "xOffset=%f, yOffset=%f, scaleFactor=%f, "
Jeff Brown3241b6b2012-02-03 15:08:02 -08001768 "pointerIds=0x%x",
Jeff Brown519e0242010-09-15 15:18:56 -07001769 connection->getInputChannelName(), inputTarget->flags,
Jeff Brown46b9ac02010-04-22 18:58:52 -07001770 inputTarget->xOffset, inputTarget->yOffset,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001771 inputTarget->scaleFactor, inputTarget->pointerIds.value);
Jeff Brown46b9ac02010-04-22 18:58:52 -07001772#endif
1773
1774 // Skip this event if the connection status is not normal.
Jeff Brown519e0242010-09-15 15:18:56 -07001775 // We don't want to enqueue additional outbound events if the connection is broken.
Jeff Brown46b9ac02010-04-22 18:58:52 -07001776 if (connection->status != Connection::STATUS_NORMAL) {
Jeff Brownb6997262010-10-08 22:31:17 -07001777#if DEBUG_DISPATCH_CYCLE
Steve Block5baa3a62011-12-20 16:23:08 +00001778 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Jeff Brownb88102f2010-09-08 11:49:43 -07001779 connection->getInputChannelName(), connection->getStatusLabel());
Jeff Brownb6997262010-10-08 22:31:17 -07001780#endif
Jeff Brown46b9ac02010-04-22 18:58:52 -07001781 return;
1782 }
1783
Jeff Brown01ce2e92010-09-26 22:20:12 -07001784 // Split a motion event if needed.
Jeff Brown3241b6b2012-02-03 15:08:02 -08001785 if (inputTarget->flags & InputTarget::FLAG_SPLIT) {
Steve Blockec193de2012-01-09 18:35:44 +00001786 ALOG_ASSERT(eventEntry->type == EventEntry::TYPE_MOTION);
Jeff Brown01ce2e92010-09-26 22:20:12 -07001787
1788 MotionEntry* originalMotionEntry = static_cast<MotionEntry*>(eventEntry);
1789 if (inputTarget->pointerIds.count() != originalMotionEntry->pointerCount) {
1790 MotionEntry* splitMotionEntry = splitMotionEvent(
1791 originalMotionEntry, inputTarget->pointerIds);
Jeff Brown58a2da82011-01-25 16:02:22 -08001792 if (!splitMotionEntry) {
1793 return; // split event was dropped
1794 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001795#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001796 ALOGD("channel '%s' ~ Split motion event.",
Jeff Brown01ce2e92010-09-26 22:20:12 -07001797 connection->getInputChannelName());
1798 logOutboundMotionDetailsLocked(" ", splitMotionEntry);
1799#endif
Jeff Brownc0cb3dc2012-01-12 18:30:12 -08001800 enqueueDispatchEntriesLocked(currentTime, connection,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001801 splitMotionEntry, inputTarget);
Jeff Brownc0cb3dc2012-01-12 18:30:12 -08001802 splitMotionEntry->release();
1803 return;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001804 }
1805 }
1806
Jeff Brownc0cb3dc2012-01-12 18:30:12 -08001807 // Not splitting. Enqueue dispatch entries for the event as is.
Jeff Brown3241b6b2012-02-03 15:08:02 -08001808 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
Jeff Brownc0cb3dc2012-01-12 18:30:12 -08001809}
1810
1811void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001812 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07001813 bool wasEmpty = connection->outboundQueue.isEmpty();
1814
Jeff Browna032cc02011-03-07 16:56:21 -08001815 // Enqueue dispatch entries for the requested modes.
1816 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001817 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
Jeff Browna032cc02011-03-07 16:56:21 -08001818 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001819 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
Jeff Browna032cc02011-03-07 16:56:21 -08001820 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001821 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
Jeff Browna032cc02011-03-07 16:56:21 -08001822 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001823 InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brown98db5fa2011-06-08 15:37:10 -07001824 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001825 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
Jeff Brown98db5fa2011-06-08 15:37:10 -07001826 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001827 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Jeff Browna032cc02011-03-07 16:56:21 -08001828
1829 // If the outbound queue was previously empty, start the dispatch cycle going.
Jeff Brownb6110c22011-04-01 16:15:13 -07001830 if (wasEmpty && !connection->outboundQueue.isEmpty()) {
Jeff Browna032cc02011-03-07 16:56:21 -08001831 startDispatchCycleLocked(currentTime, connection);
1832 }
1833}
1834
1835void InputDispatcher::enqueueDispatchEntryLocked(
1836 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001837 int32_t dispatchMode) {
Jeff Browna032cc02011-03-07 16:56:21 -08001838 int32_t inputTargetFlags = inputTarget->flags;
1839 if (!(inputTargetFlags & dispatchMode)) {
1840 return;
1841 }
1842 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
1843
Jeff Brown46b9ac02010-04-22 18:58:52 -07001844 // This is a new event.
1845 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Jeff Brownac386072011-07-20 15:19:50 -07001846 DispatchEntry* dispatchEntry = new DispatchEntry(eventEntry, // increments ref
Dianne Hackbornaa9d84c2011-05-09 19:00:59 -07001847 inputTargetFlags, inputTarget->xOffset, inputTarget->yOffset,
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001848 inputTarget->scaleFactor);
Jeff Brown6ec402b2010-07-28 15:48:59 -07001849
Jeff Brown81346812011-06-28 20:08:48 -07001850 // Apply target flags and update the connection's input state.
1851 switch (eventEntry->type) {
1852 case EventEntry::TYPE_KEY: {
1853 KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
1854 dispatchEntry->resolvedAction = keyEntry->action;
1855 dispatchEntry->resolvedFlags = keyEntry->flags;
1856
1857 if (!connection->inputState.trackKey(keyEntry,
1858 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags)) {
1859#if DEBUG_DISPATCH_CYCLE
Steve Block5baa3a62011-12-20 16:23:08 +00001860 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
Jeff Brown81346812011-06-28 20:08:48 -07001861 connection->getInputChannelName());
1862#endif
Jeff Brownc0cb3dc2012-01-12 18:30:12 -08001863 delete dispatchEntry;
Jeff Brown81346812011-06-28 20:08:48 -07001864 return; // skip the inconsistent event
1865 }
1866 break;
1867 }
1868
1869 case EventEntry::TYPE_MOTION: {
1870 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
1871 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
1872 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
1873 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
1874 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
1875 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
1876 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
1877 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
1878 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
1879 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
1880 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
1881 } else {
1882 dispatchEntry->resolvedAction = motionEntry->action;
1883 }
1884 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE
1885 && !connection->inputState.isHovering(
Jeff Brown83d616a2012-09-09 20:33:43 -07001886 motionEntry->deviceId, motionEntry->source, motionEntry->displayId)) {
Jeff Brown81346812011-06-28 20:08:48 -07001887#if DEBUG_DISPATCH_CYCLE
Steve Block5baa3a62011-12-20 16:23:08 +00001888 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter event",
Jeff Brown81346812011-06-28 20:08:48 -07001889 connection->getInputChannelName());
1890#endif
1891 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
1892 }
1893
1894 dispatchEntry->resolvedFlags = motionEntry->flags;
1895 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
1896 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
1897 }
1898
1899 if (!connection->inputState.trackMotion(motionEntry,
1900 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags)) {
1901#if DEBUG_DISPATCH_CYCLE
Steve Block5baa3a62011-12-20 16:23:08 +00001902 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion event",
Jeff Brown81346812011-06-28 20:08:48 -07001903 connection->getInputChannelName());
1904#endif
Jeff Brownc0cb3dc2012-01-12 18:30:12 -08001905 delete dispatchEntry;
Jeff Brown81346812011-06-28 20:08:48 -07001906 return; // skip the inconsistent event
1907 }
1908 break;
1909 }
1910 }
1911
Jeff Brownc0cb3dc2012-01-12 18:30:12 -08001912 // Remember that we are waiting for this dispatch to complete.
1913 if (dispatchEntry->hasForegroundTarget()) {
1914 incrementPendingForegroundDispatchesLocked(eventEntry);
1915 }
1916
Jeff Brown46b9ac02010-04-22 18:58:52 -07001917 // Enqueue the dispatch entry.
1918 connection->outboundQueue.enqueueAtTail(dispatchEntry);
Jeff Brown481c1572012-03-09 14:41:15 -08001919 traceOutboundQueueLengthLocked(connection);
Jeff Brown46b9ac02010-04-22 18:58:52 -07001920}
1921
Jeff Brown7fbdc842010-06-17 20:52:56 -07001922void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Jeff Brown519e0242010-09-15 15:18:56 -07001923 const sp<Connection>& connection) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07001924#if DEBUG_DISPATCH_CYCLE
Steve Block5baa3a62011-12-20 16:23:08 +00001925 ALOGD("channel '%s' ~ startDispatchCycle",
Jeff Brown46b9ac02010-04-22 18:58:52 -07001926 connection->getInputChannelName());
1927#endif
1928
Jeff Brownd1c48a02012-02-06 19:12:47 -08001929 while (connection->status == Connection::STATUS_NORMAL
1930 && !connection->outboundQueue.isEmpty()) {
1931 DispatchEntry* dispatchEntry = connection->outboundQueue.head;
Jeff Brown265f1cc2012-06-11 18:01:06 -07001932 dispatchEntry->deliveryTime = currentTime;
Jeff Brown46b9ac02010-04-22 18:58:52 -07001933
Jeff Brownd1c48a02012-02-06 19:12:47 -08001934 // Publish the event.
1935 status_t status;
1936 EventEntry* eventEntry = dispatchEntry->eventEntry;
1937 switch (eventEntry->type) {
1938 case EventEntry::TYPE_KEY: {
1939 KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
Jeff Brown46b9ac02010-04-22 18:58:52 -07001940
Jeff Brownd1c48a02012-02-06 19:12:47 -08001941 // Publish the key event.
Jeff Brown072ec962012-02-07 14:46:57 -08001942 status = connection->inputPublisher.publishKeyEvent(dispatchEntry->seq,
Jeff Brownd1c48a02012-02-06 19:12:47 -08001943 keyEntry->deviceId, keyEntry->source,
1944 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags,
1945 keyEntry->keyCode, keyEntry->scanCode,
1946 keyEntry->metaState, keyEntry->repeatCount, keyEntry->downTime,
1947 keyEntry->eventTime);
1948 break;
1949 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001950
Jeff Brownd1c48a02012-02-06 19:12:47 -08001951 case EventEntry::TYPE_MOTION: {
1952 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
Jeff Brown46b9ac02010-04-22 18:58:52 -07001953
Jeff Brownd1c48a02012-02-06 19:12:47 -08001954 PointerCoords scaledCoords[MAX_POINTERS];
1955 const PointerCoords* usingCoords = motionEntry->pointerCoords;
Jeff Brown46b9ac02010-04-22 18:58:52 -07001956
Jeff Brownd1c48a02012-02-06 19:12:47 -08001957 // Set the X and Y offset depending on the input source.
1958 float xOffset, yOffset, scaleFactor;
1959 if ((motionEntry->source & AINPUT_SOURCE_CLASS_POINTER)
1960 && !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
1961 scaleFactor = dispatchEntry->scaleFactor;
1962 xOffset = dispatchEntry->xOffset * scaleFactor;
1963 yOffset = dispatchEntry->yOffset * scaleFactor;
1964 if (scaleFactor != 1.0f) {
1965 for (size_t i = 0; i < motionEntry->pointerCount; i++) {
1966 scaledCoords[i] = motionEntry->pointerCoords[i];
1967 scaledCoords[i].scale(scaleFactor);
1968 }
1969 usingCoords = scaledCoords;
1970 }
1971 } else {
1972 xOffset = 0.0f;
1973 yOffset = 0.0f;
1974 scaleFactor = 1.0f;
1975
1976 // We don't want the dispatch target to know.
1977 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
1978 for (size_t i = 0; i < motionEntry->pointerCount; i++) {
1979 scaledCoords[i].clear();
1980 }
1981 usingCoords = scaledCoords;
1982 }
1983 }
1984
1985 // Publish the motion event.
Jeff Brown072ec962012-02-07 14:46:57 -08001986 status = connection->inputPublisher.publishMotionEvent(dispatchEntry->seq,
Jeff Brownd1c48a02012-02-06 19:12:47 -08001987 motionEntry->deviceId, motionEntry->source,
1988 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags,
1989 motionEntry->edgeFlags, motionEntry->metaState, motionEntry->buttonState,
1990 xOffset, yOffset,
1991 motionEntry->xPrecision, motionEntry->yPrecision,
1992 motionEntry->downTime, motionEntry->eventTime,
1993 motionEntry->pointerCount, motionEntry->pointerProperties,
1994 usingCoords);
1995 break;
1996 }
1997
1998 default:
1999 ALOG_ASSERT(false);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002000 return;
2001 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002002
Jeff Brownd1c48a02012-02-06 19:12:47 -08002003 // Check the result.
Jeff Brown46b9ac02010-04-22 18:58:52 -07002004 if (status) {
Jeff Brownd1c48a02012-02-06 19:12:47 -08002005 if (status == WOULD_BLOCK) {
2006 if (connection->waitQueue.isEmpty()) {
2007 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
2008 "This is unexpected because the wait queue is empty, so the pipe "
2009 "should be empty and we shouldn't have any problems writing an "
2010 "event to it, status=%d", connection->getInputChannelName(), status);
2011 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2012 } else {
2013 // Pipe is full and we are waiting for the app to finish process some events
2014 // before sending more events to it.
2015#if DEBUG_DISPATCH_CYCLE
2016 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
2017 "waiting for the application to catch up",
2018 connection->getInputChannelName());
2019#endif
2020 connection->inputPublisherBlocked = true;
2021 }
2022 } else {
2023 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
2024 "status=%d", connection->getInputChannelName(), status);
2025 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2026 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002027 return;
2028 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002029
Jeff Brownd1c48a02012-02-06 19:12:47 -08002030 // Re-enqueue the event on the wait queue.
2031 connection->outboundQueue.dequeue(dispatchEntry);
Jeff Brown481c1572012-03-09 14:41:15 -08002032 traceOutboundQueueLengthLocked(connection);
Jeff Brownd1c48a02012-02-06 19:12:47 -08002033 connection->waitQueue.enqueueAtTail(dispatchEntry);
Jeff Brown481c1572012-03-09 14:41:15 -08002034 traceWaitQueueLengthLocked(connection);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002035 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002036}
2037
Jeff Brown7fbdc842010-06-17 20:52:56 -07002038void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Jeff Brown072ec962012-02-07 14:46:57 -08002039 const sp<Connection>& connection, uint32_t seq, bool handled) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002040#if DEBUG_DISPATCH_CYCLE
Jeff Brown072ec962012-02-07 14:46:57 -08002041 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
2042 connection->getInputChannelName(), seq, toString(handled));
Jeff Brown46b9ac02010-04-22 18:58:52 -07002043#endif
2044
Jeff Brownd1c48a02012-02-06 19:12:47 -08002045 connection->inputPublisherBlocked = false;
2046
Jeff Brown9c3cda02010-06-15 01:31:58 -07002047 if (connection->status == Connection::STATUS_BROKEN
2048 || connection->status == Connection::STATUS_ZOMBIE) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002049 return;
2050 }
2051
Jeff Brown3915bb82010-11-05 15:02:16 -07002052 // Notify other system components and prepare to start the next dispatch cycle.
Jeff Brown072ec962012-02-07 14:46:57 -08002053 onDispatchCycleFinishedLocked(currentTime, connection, seq, handled);
Jeff Brownb88102f2010-09-08 11:49:43 -07002054}
2055
Jeff Brownb6997262010-10-08 22:31:17 -07002056void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Jeff Browncc4f7db2011-08-30 20:34:48 -07002057 const sp<Connection>& connection, bool notify) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002058#if DEBUG_DISPATCH_CYCLE
Steve Block5baa3a62011-12-20 16:23:08 +00002059 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
Jeff Browncc4f7db2011-08-30 20:34:48 -07002060 connection->getInputChannelName(), toString(notify));
Jeff Brown46b9ac02010-04-22 18:58:52 -07002061#endif
2062
Jeff Brownd1c48a02012-02-06 19:12:47 -08002063 // Clear the dispatch queues.
2064 drainDispatchQueueLocked(&connection->outboundQueue);
Jeff Brown481c1572012-03-09 14:41:15 -08002065 traceOutboundQueueLengthLocked(connection);
Jeff Brownd1c48a02012-02-06 19:12:47 -08002066 drainDispatchQueueLocked(&connection->waitQueue);
Jeff Brown481c1572012-03-09 14:41:15 -08002067 traceWaitQueueLengthLocked(connection);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002068
Jeff Brownb6997262010-10-08 22:31:17 -07002069 // The connection appears to be unrecoverably broken.
Jeff Brown9c3cda02010-06-15 01:31:58 -07002070 // Ignore already broken or zombie connections.
Jeff Brownb6997262010-10-08 22:31:17 -07002071 if (connection->status == Connection::STATUS_NORMAL) {
2072 connection->status = Connection::STATUS_BROKEN;
Jeff Brown46b9ac02010-04-22 18:58:52 -07002073
Jeff Browncc4f7db2011-08-30 20:34:48 -07002074 if (notify) {
2075 // Notify other system components.
2076 onDispatchCycleBrokenLocked(currentTime, connection);
2077 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002078 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002079}
2080
Jeff Brownd1c48a02012-02-06 19:12:47 -08002081void InputDispatcher::drainDispatchQueueLocked(Queue<DispatchEntry>* queue) {
2082 while (!queue->isEmpty()) {
2083 DispatchEntry* dispatchEntry = queue->dequeueAtHead();
2084 releaseDispatchEntryLocked(dispatchEntry);
Jeff Brownb88102f2010-09-08 11:49:43 -07002085 }
Jeff Brownb88102f2010-09-08 11:49:43 -07002086}
2087
Jeff Brownd1c48a02012-02-06 19:12:47 -08002088void InputDispatcher::releaseDispatchEntryLocked(DispatchEntry* dispatchEntry) {
2089 if (dispatchEntry->hasForegroundTarget()) {
2090 decrementPendingForegroundDispatchesLocked(dispatchEntry->eventEntry);
2091 }
2092 delete dispatchEntry;
2093}
2094
Jeff Browncbee6d62012-02-03 20:11:27 -08002095int InputDispatcher::handleReceiveCallback(int fd, int events, void* data) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002096 InputDispatcher* d = static_cast<InputDispatcher*>(data);
2097
2098 { // acquire lock
2099 AutoMutex _l(d->mLock);
2100
Jeff Browncbee6d62012-02-03 20:11:27 -08002101 ssize_t connectionIndex = d->mConnectionsByFd.indexOfKey(fd);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002102 if (connectionIndex < 0) {
Steve Block3762c312012-01-06 19:20:56 +00002103 ALOGE("Received spurious receive callback for unknown input channel. "
Jeff Browncbee6d62012-02-03 20:11:27 -08002104 "fd=%d, events=0x%x", fd, events);
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002105 return 0; // remove the callback
Jeff Brown46b9ac02010-04-22 18:58:52 -07002106 }
2107
Jeff Browncc4f7db2011-08-30 20:34:48 -07002108 bool notify;
Jeff Browncbee6d62012-02-03 20:11:27 -08002109 sp<Connection> connection = d->mConnectionsByFd.valueAt(connectionIndex);
Jeff Browncc4f7db2011-08-30 20:34:48 -07002110 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
2111 if (!(events & ALOOPER_EVENT_INPUT)) {
Steve Block8564c8d2012-01-05 23:22:43 +00002112 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
Jeff Browncc4f7db2011-08-30 20:34:48 -07002113 "events=0x%x", connection->getInputChannelName(), events);
2114 return 1;
2115 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002116
Jeff Brown1adee112012-02-07 10:25:41 -08002117 nsecs_t currentTime = now();
2118 bool gotOne = false;
2119 status_t status;
2120 for (;;) {
Jeff Brown072ec962012-02-07 14:46:57 -08002121 uint32_t seq;
2122 bool handled;
2123 status = connection->inputPublisher.receiveFinishedSignal(&seq, &handled);
Jeff Brown1adee112012-02-07 10:25:41 -08002124 if (status) {
2125 break;
2126 }
Jeff Brown072ec962012-02-07 14:46:57 -08002127 d->finishDispatchCycleLocked(currentTime, connection, seq, handled);
Jeff Brown1adee112012-02-07 10:25:41 -08002128 gotOne = true;
2129 }
2130 if (gotOne) {
Jeff Browncc4f7db2011-08-30 20:34:48 -07002131 d->runCommandsLockedInterruptible();
Jeff Brown1adee112012-02-07 10:25:41 -08002132 if (status == WOULD_BLOCK) {
2133 return 1;
2134 }
Jeff Browncc4f7db2011-08-30 20:34:48 -07002135 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002136
Jeff Brown1adee112012-02-07 10:25:41 -08002137 notify = status != DEAD_OBJECT || !connection->monitor;
2138 if (notify) {
2139 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
2140 connection->getInputChannelName(), status);
2141 }
Jeff Browncc4f7db2011-08-30 20:34:48 -07002142 } else {
2143 // Monitor channels are never explicitly unregistered.
2144 // We do it automatically when the remote endpoint is closed so don't warn
2145 // about them.
2146 notify = !connection->monitor;
2147 if (notify) {
Steve Block8564c8d2012-01-05 23:22:43 +00002148 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. "
Jeff Browncc4f7db2011-08-30 20:34:48 -07002149 "events=0x%x", connection->getInputChannelName(), events);
2150 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002151 }
2152
Jeff Browncc4f7db2011-08-30 20:34:48 -07002153 // Unregister the channel.
2154 d->unregisterInputChannelLocked(connection->inputChannel, notify);
2155 return 0; // remove the callback
Jeff Brown46b9ac02010-04-22 18:58:52 -07002156 } // release lock
2157}
2158
Jeff Brownb6997262010-10-08 22:31:17 -07002159void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Jeff Brownda3d5a92011-03-29 15:11:34 -07002160 const CancelationOptions& options) {
Jeff Browncbee6d62012-02-03 20:11:27 -08002161 for (size_t i = 0; i < mConnectionsByFd.size(); i++) {
Jeff Brownb6997262010-10-08 22:31:17 -07002162 synthesizeCancelationEventsForConnectionLocked(
Jeff Browncbee6d62012-02-03 20:11:27 -08002163 mConnectionsByFd.valueAt(i), options);
Jeff Brownb6997262010-10-08 22:31:17 -07002164 }
2165}
2166
2167void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Jeff Brownda3d5a92011-03-29 15:11:34 -07002168 const sp<InputChannel>& channel, const CancelationOptions& options) {
Jeff Brownb6997262010-10-08 22:31:17 -07002169 ssize_t index = getConnectionIndexLocked(channel);
2170 if (index >= 0) {
2171 synthesizeCancelationEventsForConnectionLocked(
Jeff Browncbee6d62012-02-03 20:11:27 -08002172 mConnectionsByFd.valueAt(index), options);
Jeff Brownb6997262010-10-08 22:31:17 -07002173 }
2174}
2175
2176void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
Jeff Brownda3d5a92011-03-29 15:11:34 -07002177 const sp<Connection>& connection, const CancelationOptions& options) {
Jeff Brownc0cb3dc2012-01-12 18:30:12 -08002178 if (connection->status == Connection::STATUS_BROKEN) {
2179 return;
2180 }
2181
Jeff Brownb6997262010-10-08 22:31:17 -07002182 nsecs_t currentTime = now();
2183
Jeff Brown8b4be5602012-02-06 16:31:05 -08002184 Vector<EventEntry*> cancelationEvents;
Jeff Brownac386072011-07-20 15:19:50 -07002185 connection->inputState.synthesizeCancelationEvents(currentTime,
Jeff Brown8b4be5602012-02-06 16:31:05 -08002186 cancelationEvents, options);
Jeff Brownb6997262010-10-08 22:31:17 -07002187
Jeff Brown8b4be5602012-02-06 16:31:05 -08002188 if (!cancelationEvents.isEmpty()) {
Jeff Brownb6997262010-10-08 22:31:17 -07002189#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00002190 ALOGD("channel '%s' ~ Synthesized %d cancelation events to bring channel back in sync "
Jeff Brownda3d5a92011-03-29 15:11:34 -07002191 "with reality: %s, mode=%d.",
Jeff Brown8b4be5602012-02-06 16:31:05 -08002192 connection->getInputChannelName(), cancelationEvents.size(),
Jeff Brownda3d5a92011-03-29 15:11:34 -07002193 options.reason, options.mode);
Jeff Brownb6997262010-10-08 22:31:17 -07002194#endif
Jeff Brown8b4be5602012-02-06 16:31:05 -08002195 for (size_t i = 0; i < cancelationEvents.size(); i++) {
2196 EventEntry* cancelationEventEntry = cancelationEvents.itemAt(i);
Jeff Brownb6997262010-10-08 22:31:17 -07002197 switch (cancelationEventEntry->type) {
2198 case EventEntry::TYPE_KEY:
2199 logOutboundKeyDetailsLocked("cancel - ",
2200 static_cast<KeyEntry*>(cancelationEventEntry));
2201 break;
2202 case EventEntry::TYPE_MOTION:
2203 logOutboundMotionDetailsLocked("cancel - ",
2204 static_cast<MotionEntry*>(cancelationEventEntry));
2205 break;
2206 }
2207
Jeff Brown81346812011-06-28 20:08:48 -07002208 InputTarget target;
Jeff Brown9302c872011-07-13 22:51:29 -07002209 sp<InputWindowHandle> windowHandle = getWindowHandleLocked(connection->inputChannel);
2210 if (windowHandle != NULL) {
Jeff Browncc4f7db2011-08-30 20:34:48 -07002211 const InputWindowInfo* windowInfo = windowHandle->getInfo();
2212 target.xOffset = -windowInfo->frameLeft;
2213 target.yOffset = -windowInfo->frameTop;
2214 target.scaleFactor = windowInfo->scaleFactor;
Jeff Brownb6997262010-10-08 22:31:17 -07002215 } else {
Jeff Brown81346812011-06-28 20:08:48 -07002216 target.xOffset = 0;
2217 target.yOffset = 0;
2218 target.scaleFactor = 1.0f;
Jeff Brownb6997262010-10-08 22:31:17 -07002219 }
Jeff Brown81346812011-06-28 20:08:48 -07002220 target.inputChannel = connection->inputChannel;
2221 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
Jeff Brownb6997262010-10-08 22:31:17 -07002222
Jeff Brown81346812011-06-28 20:08:48 -07002223 enqueueDispatchEntryLocked(connection, cancelationEventEntry, // increments ref
Jeff Brown3241b6b2012-02-03 15:08:02 -08002224 &target, InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brownb6997262010-10-08 22:31:17 -07002225
Jeff Brownac386072011-07-20 15:19:50 -07002226 cancelationEventEntry->release();
Jeff Brownb6997262010-10-08 22:31:17 -07002227 }
2228
Jeff Brownd1c48a02012-02-06 19:12:47 -08002229 startDispatchCycleLocked(currentTime, connection);
Jeff Brownb6997262010-10-08 22:31:17 -07002230 }
2231}
2232
Jeff Brown01ce2e92010-09-26 22:20:12 -07002233InputDispatcher::MotionEntry*
2234InputDispatcher::splitMotionEvent(const MotionEntry* originalMotionEntry, BitSet32 pointerIds) {
Steve Blockec193de2012-01-09 18:35:44 +00002235 ALOG_ASSERT(pointerIds.value != 0);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002236
2237 uint32_t splitPointerIndexMap[MAX_POINTERS];
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002238 PointerProperties splitPointerProperties[MAX_POINTERS];
Jeff Brown01ce2e92010-09-26 22:20:12 -07002239 PointerCoords splitPointerCoords[MAX_POINTERS];
2240
2241 uint32_t originalPointerCount = originalMotionEntry->pointerCount;
2242 uint32_t splitPointerCount = 0;
2243
2244 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
2245 originalPointerIndex++) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002246 const PointerProperties& pointerProperties =
2247 originalMotionEntry->pointerProperties[originalPointerIndex];
2248 uint32_t pointerId = uint32_t(pointerProperties.id);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002249 if (pointerIds.hasBit(pointerId)) {
2250 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002251 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
Jeff Brownace13b12011-03-09 17:39:48 -08002252 splitPointerCoords[splitPointerCount].copyFrom(
Jeff Brown3241b6b2012-02-03 15:08:02 -08002253 originalMotionEntry->pointerCoords[originalPointerIndex]);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002254 splitPointerCount += 1;
2255 }
2256 }
Jeff Brown58a2da82011-01-25 16:02:22 -08002257
2258 if (splitPointerCount != pointerIds.count()) {
2259 // This is bad. We are missing some of the pointers that we expected to deliver.
2260 // Most likely this indicates that we received an ACTION_MOVE events that has
2261 // different pointer ids than we expected based on the previous ACTION_DOWN
2262 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
2263 // in this way.
Steve Block8564c8d2012-01-05 23:22:43 +00002264 ALOGW("Dropping split motion event because the pointer count is %d but "
Jeff Brown58a2da82011-01-25 16:02:22 -08002265 "we expected there to be %d pointers. This probably means we received "
2266 "a broken sequence of pointer ids from the input device.",
2267 splitPointerCount, pointerIds.count());
2268 return NULL;
2269 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07002270
2271 int32_t action = originalMotionEntry->action;
2272 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
2273 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
2274 || maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2275 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002276 const PointerProperties& pointerProperties =
2277 originalMotionEntry->pointerProperties[originalPointerIndex];
2278 uint32_t pointerId = uint32_t(pointerProperties.id);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002279 if (pointerIds.hasBit(pointerId)) {
2280 if (pointerIds.count() == 1) {
2281 // The first/last pointer went down/up.
2282 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
2283 ? AMOTION_EVENT_ACTION_DOWN : AMOTION_EVENT_ACTION_UP;
Jeff Brown9a01d052010-09-27 16:35:11 -07002284 } else {
2285 // A secondary pointer went down/up.
2286 uint32_t splitPointerIndex = 0;
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002287 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
Jeff Brown9a01d052010-09-27 16:35:11 -07002288 splitPointerIndex += 1;
2289 }
2290 action = maskedAction | (splitPointerIndex
2291 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002292 }
2293 } else {
2294 // An unrelated pointer changed.
2295 action = AMOTION_EVENT_ACTION_MOVE;
2296 }
2297 }
2298
Jeff Brownac386072011-07-20 15:19:50 -07002299 MotionEntry* splitMotionEntry = new MotionEntry(
Jeff Brown01ce2e92010-09-26 22:20:12 -07002300 originalMotionEntry->eventTime,
2301 originalMotionEntry->deviceId,
2302 originalMotionEntry->source,
2303 originalMotionEntry->policyFlags,
2304 action,
2305 originalMotionEntry->flags,
2306 originalMotionEntry->metaState,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002307 originalMotionEntry->buttonState,
Jeff Brown01ce2e92010-09-26 22:20:12 -07002308 originalMotionEntry->edgeFlags,
2309 originalMotionEntry->xPrecision,
2310 originalMotionEntry->yPrecision,
2311 originalMotionEntry->downTime,
Jeff Brown83d616a2012-09-09 20:33:43 -07002312 originalMotionEntry->displayId,
Jeff Brown38f96e52014-02-11 14:32:56 -08002313 splitPointerCount, splitPointerProperties, splitPointerCoords, 0, 0);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002314
Jeff Browna032cc02011-03-07 16:56:21 -08002315 if (originalMotionEntry->injectionState) {
2316 splitMotionEntry->injectionState = originalMotionEntry->injectionState;
2317 splitMotionEntry->injectionState->refCount += 1;
2318 }
2319
Jeff Brown01ce2e92010-09-26 22:20:12 -07002320 return splitMotionEntry;
2321}
2322
Jeff Brownbe1aa822011-07-27 16:04:54 -07002323void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002324#if DEBUG_INBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00002325 ALOGD("notifyConfigurationChanged - eventTime=%lld", args->eventTime);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002326#endif
2327
Jeff Brownb88102f2010-09-08 11:49:43 -07002328 bool needWake;
Jeff Brown46b9ac02010-04-22 18:58:52 -07002329 { // acquire lock
2330 AutoMutex _l(mLock);
2331
Jeff Brownbe1aa822011-07-27 16:04:54 -07002332 ConfigurationChangedEntry* newEntry = new ConfigurationChangedEntry(args->eventTime);
Jeff Brownb88102f2010-09-08 11:49:43 -07002333 needWake = enqueueInboundEventLocked(newEntry);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002334 } // release lock
2335
Jeff Brownb88102f2010-09-08 11:49:43 -07002336 if (needWake) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002337 mLooper->wake();
Jeff Brown46b9ac02010-04-22 18:58:52 -07002338 }
2339}
2340
Jeff Brownbe1aa822011-07-27 16:04:54 -07002341void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002342#if DEBUG_INBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00002343 ALOGD("notifyKey - eventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, action=0x%x, "
Jeff Brown46b9ac02010-04-22 18:58:52 -07002344 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%lld",
Jeff Brownbe1aa822011-07-27 16:04:54 -07002345 args->eventTime, args->deviceId, args->source, args->policyFlags,
2346 args->action, args->flags, args->keyCode, args->scanCode,
2347 args->metaState, args->downTime);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002348#endif
Jeff Brownbe1aa822011-07-27 16:04:54 -07002349 if (!validateKeyEvent(args->action)) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002350 return;
2351 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002352
Jeff Brownbe1aa822011-07-27 16:04:54 -07002353 uint32_t policyFlags = args->policyFlags;
2354 int32_t flags = args->flags;
2355 int32_t metaState = args->metaState;
Jeff Brown1f245102010-11-18 20:53:46 -08002356 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
2357 policyFlags |= POLICY_FLAG_VIRTUAL;
2358 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
2359 }
Jeff Brown924c4d42011-03-07 16:40:47 -08002360 if (policyFlags & POLICY_FLAG_ALT) {
2361 metaState |= AMETA_ALT_ON | AMETA_ALT_LEFT_ON;
2362 }
2363 if (policyFlags & POLICY_FLAG_ALT_GR) {
2364 metaState |= AMETA_ALT_ON | AMETA_ALT_RIGHT_ON;
2365 }
2366 if (policyFlags & POLICY_FLAG_SHIFT) {
2367 metaState |= AMETA_SHIFT_ON | AMETA_SHIFT_LEFT_ON;
2368 }
2369 if (policyFlags & POLICY_FLAG_CAPS_LOCK) {
2370 metaState |= AMETA_CAPS_LOCK_ON;
2371 }
2372 if (policyFlags & POLICY_FLAG_FUNCTION) {
2373 metaState |= AMETA_FUNCTION_ON;
2374 }
Jeff Brown1f245102010-11-18 20:53:46 -08002375
Jeff Browne20c9e02010-10-11 14:20:19 -07002376 policyFlags |= POLICY_FLAG_TRUSTED;
Jeff Brown1f245102010-11-18 20:53:46 -08002377
2378 KeyEvent event;
Jeff Brownbe1aa822011-07-27 16:04:54 -07002379 event.initialize(args->deviceId, args->source, args->action,
2380 flags, args->keyCode, args->scanCode, metaState, 0,
2381 args->downTime, args->eventTime);
Jeff Brown1f245102010-11-18 20:53:46 -08002382
2383 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
2384
Jeff Brownb88102f2010-09-08 11:49:43 -07002385 bool needWake;
Jeff Brown46b9ac02010-04-22 18:58:52 -07002386 { // acquire lock
Jeff Brown0029c662011-03-30 02:25:18 -07002387 mLock.lock();
2388
Jeff Brown83d616a2012-09-09 20:33:43 -07002389 if (shouldSendKeyToInputFilterLocked(args)) {
Jeff Brown0029c662011-03-30 02:25:18 -07002390 mLock.unlock();
2391
2392 policyFlags |= POLICY_FLAG_FILTERED;
2393 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2394 return; // event was consumed by the filter
2395 }
2396
2397 mLock.lock();
2398 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002399
Jeff Brown7fbdc842010-06-17 20:52:56 -07002400 int32_t repeatCount = 0;
Jeff Brownbe1aa822011-07-27 16:04:54 -07002401 KeyEntry* newEntry = new KeyEntry(args->eventTime,
2402 args->deviceId, args->source, policyFlags,
2403 args->action, flags, args->keyCode, args->scanCode,
2404 metaState, repeatCount, args->downTime);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002405
Jeff Brownb88102f2010-09-08 11:49:43 -07002406 needWake = enqueueInboundEventLocked(newEntry);
Jeff Brown0029c662011-03-30 02:25:18 -07002407 mLock.unlock();
Jeff Brown46b9ac02010-04-22 18:58:52 -07002408 } // release lock
2409
Jeff Brownb88102f2010-09-08 11:49:43 -07002410 if (needWake) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002411 mLooper->wake();
Jeff Brown46b9ac02010-04-22 18:58:52 -07002412 }
2413}
2414
Jeff Brown83d616a2012-09-09 20:33:43 -07002415bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
2416 return mInputFilterEnabled;
2417}
2418
Jeff Brownbe1aa822011-07-27 16:04:54 -07002419void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002420#if DEBUG_INBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00002421 ALOGD("notifyMotion - eventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, "
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002422 "action=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, edgeFlags=0x%x, "
Jeff Brown85a31762010-09-01 17:01:00 -07002423 "xPrecision=%f, yPrecision=%f, downTime=%lld",
Jeff Brownbe1aa822011-07-27 16:04:54 -07002424 args->eventTime, args->deviceId, args->source, args->policyFlags,
2425 args->action, args->flags, args->metaState, args->buttonState,
2426 args->edgeFlags, args->xPrecision, args->yPrecision, args->downTime);
2427 for (uint32_t i = 0; i < args->pointerCount; i++) {
Steve Block5baa3a62011-12-20 16:23:08 +00002428 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002429 "x=%f, y=%f, pressure=%f, size=%f, "
Jeff Brown85a31762010-09-01 17:01:00 -07002430 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
Jeff Brown8d608662010-08-30 03:02:23 -07002431 "orientation=%f",
Jeff Brownbe1aa822011-07-27 16:04:54 -07002432 i, args->pointerProperties[i].id,
2433 args->pointerProperties[i].toolType,
2434 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
2435 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
2436 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
2437 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
2438 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
2439 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
2440 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
2441 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
2442 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Jeff Brown46b9ac02010-04-22 18:58:52 -07002443 }
2444#endif
Jeff Brownbe1aa822011-07-27 16:04:54 -07002445 if (!validateMotionEvent(args->action, args->pointerCount, args->pointerProperties)) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002446 return;
2447 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002448
Jeff Brownbe1aa822011-07-27 16:04:54 -07002449 uint32_t policyFlags = args->policyFlags;
Jeff Browne20c9e02010-10-11 14:20:19 -07002450 policyFlags |= POLICY_FLAG_TRUSTED;
Jeff Brownbe1aa822011-07-27 16:04:54 -07002451 mPolicy->interceptMotionBeforeQueueing(args->eventTime, /*byref*/ policyFlags);
Jeff Brownb6997262010-10-08 22:31:17 -07002452
Jeff Brownb88102f2010-09-08 11:49:43 -07002453 bool needWake;
Jeff Brown46b9ac02010-04-22 18:58:52 -07002454 { // acquire lock
Jeff Brown0029c662011-03-30 02:25:18 -07002455 mLock.lock();
2456
Jeff Brown83d616a2012-09-09 20:33:43 -07002457 if (shouldSendMotionToInputFilterLocked(args)) {
Jeff Brown0029c662011-03-30 02:25:18 -07002458 mLock.unlock();
2459
2460 MotionEvent event;
Jeff Brownbe1aa822011-07-27 16:04:54 -07002461 event.initialize(args->deviceId, args->source, args->action, args->flags,
2462 args->edgeFlags, args->metaState, args->buttonState, 0, 0,
2463 args->xPrecision, args->yPrecision,
2464 args->downTime, args->eventTime,
2465 args->pointerCount, args->pointerProperties, args->pointerCoords);
Jeff Brown0029c662011-03-30 02:25:18 -07002466
2467 policyFlags |= POLICY_FLAG_FILTERED;
2468 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2469 return; // event was consumed by the filter
2470 }
2471
2472 mLock.lock();
2473 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002474
Jeff Brown46b9ac02010-04-22 18:58:52 -07002475 // Just enqueue a new motion event.
Jeff Brownbe1aa822011-07-27 16:04:54 -07002476 MotionEntry* newEntry = new MotionEntry(args->eventTime,
2477 args->deviceId, args->source, policyFlags,
2478 args->action, args->flags, args->metaState, args->buttonState,
2479 args->edgeFlags, args->xPrecision, args->yPrecision, args->downTime,
Jeff Brown83d616a2012-09-09 20:33:43 -07002480 args->displayId,
Jeff Brown38f96e52014-02-11 14:32:56 -08002481 args->pointerCount, args->pointerProperties, args->pointerCoords, 0, 0);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002482
Jeff Brownb88102f2010-09-08 11:49:43 -07002483 needWake = enqueueInboundEventLocked(newEntry);
Jeff Brown0029c662011-03-30 02:25:18 -07002484 mLock.unlock();
Jeff Brown46b9ac02010-04-22 18:58:52 -07002485 } // release lock
2486
Jeff Brownb88102f2010-09-08 11:49:43 -07002487 if (needWake) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002488 mLooper->wake();
Jeff Brown46b9ac02010-04-22 18:58:52 -07002489 }
2490}
2491
Jeff Brown83d616a2012-09-09 20:33:43 -07002492bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
2493 // TODO: support sending secondary display events to input filter
2494 return mInputFilterEnabled && isMainDisplay(args->displayId);
2495}
2496
Jeff Brownbe1aa822011-07-27 16:04:54 -07002497void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
Jeff Brownb6997262010-10-08 22:31:17 -07002498#if DEBUG_INBOUND_EVENT_DETAILS
Jeff Brownbcc046a2012-09-27 20:46:43 -07002499 ALOGD("notifySwitch - eventTime=%lld, policyFlags=0x%x, switchValues=0x%08x, switchMask=0x%08x",
Jeff Brownbe1aa822011-07-27 16:04:54 -07002500 args->eventTime, args->policyFlags,
Jeff Brownbcc046a2012-09-27 20:46:43 -07002501 args->switchValues, args->switchMask);
Jeff Brownb6997262010-10-08 22:31:17 -07002502#endif
2503
Jeff Brownbe1aa822011-07-27 16:04:54 -07002504 uint32_t policyFlags = args->policyFlags;
Jeff Browne20c9e02010-10-11 14:20:19 -07002505 policyFlags |= POLICY_FLAG_TRUSTED;
Jeff Brownbe1aa822011-07-27 16:04:54 -07002506 mPolicy->notifySwitch(args->eventTime,
Jeff Brownbcc046a2012-09-27 20:46:43 -07002507 args->switchValues, args->switchMask, policyFlags);
Jeff Brownb6997262010-10-08 22:31:17 -07002508}
2509
Jeff Brown65fd2512011-08-18 11:20:58 -07002510void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
2511#if DEBUG_INBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00002512 ALOGD("notifyDeviceReset - eventTime=%lld, deviceId=%d",
Jeff Brown65fd2512011-08-18 11:20:58 -07002513 args->eventTime, args->deviceId);
2514#endif
2515
2516 bool needWake;
2517 { // acquire lock
2518 AutoMutex _l(mLock);
2519
2520 DeviceResetEntry* newEntry = new DeviceResetEntry(args->eventTime, args->deviceId);
2521 needWake = enqueueInboundEventLocked(newEntry);
2522 } // release lock
2523
2524 if (needWake) {
2525 mLooper->wake();
2526 }
2527}
2528
Jeff Brown38f96e52014-02-11 14:32:56 -08002529int32_t InputDispatcher::injectInputEvent(const InputEvent* event, int32_t displayId,
Jeff Brown0029c662011-03-30 02:25:18 -07002530 int32_t injectorPid, int32_t injectorUid, int32_t syncMode, int32_t timeoutMillis,
2531 uint32_t policyFlags) {
Jeff Brown7fbdc842010-06-17 20:52:56 -07002532#if DEBUG_INBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00002533 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Jeff Brown0029c662011-03-30 02:25:18 -07002534 "syncMode=%d, timeoutMillis=%d, policyFlags=0x%08x",
2535 event->getType(), injectorPid, injectorUid, syncMode, timeoutMillis, policyFlags);
Jeff Brown7fbdc842010-06-17 20:52:56 -07002536#endif
2537
2538 nsecs_t endTime = now() + milliseconds_to_nanoseconds(timeoutMillis);
Jeff Browne20c9e02010-10-11 14:20:19 -07002539
Jeff Brown0029c662011-03-30 02:25:18 -07002540 policyFlags |= POLICY_FLAG_INJECTED;
Jeff Browne20c9e02010-10-11 14:20:19 -07002541 if (hasInjectionPermission(injectorPid, injectorUid)) {
2542 policyFlags |= POLICY_FLAG_TRUSTED;
2543 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07002544
Jeff Brown3241b6b2012-02-03 15:08:02 -08002545 EventEntry* firstInjectedEntry;
2546 EventEntry* lastInjectedEntry;
Jeff Brownb6997262010-10-08 22:31:17 -07002547 switch (event->getType()) {
2548 case AINPUT_EVENT_TYPE_KEY: {
2549 const KeyEvent* keyEvent = static_cast<const KeyEvent*>(event);
2550 int32_t action = keyEvent->getAction();
2551 if (! validateKeyEvent(action)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07002552 return INPUT_EVENT_INJECTION_FAILED;
2553 }
2554
Jeff Brownb6997262010-10-08 22:31:17 -07002555 int32_t flags = keyEvent->getFlags();
Jeff Brown1f245102010-11-18 20:53:46 -08002556 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
2557 policyFlags |= POLICY_FLAG_VIRTUAL;
2558 }
2559
Jeff Brown0029c662011-03-30 02:25:18 -07002560 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
2561 mPolicy->interceptKeyBeforeQueueing(keyEvent, /*byref*/ policyFlags);
2562 }
Jeff Brown1f245102010-11-18 20:53:46 -08002563
Jeff Brownb6997262010-10-08 22:31:17 -07002564 mLock.lock();
Jeff Brown3241b6b2012-02-03 15:08:02 -08002565 firstInjectedEntry = new KeyEntry(keyEvent->getEventTime(),
Jeff Brown1f245102010-11-18 20:53:46 -08002566 keyEvent->getDeviceId(), keyEvent->getSource(),
2567 policyFlags, action, flags,
2568 keyEvent->getKeyCode(), keyEvent->getScanCode(), keyEvent->getMetaState(),
Jeff Brownb6997262010-10-08 22:31:17 -07002569 keyEvent->getRepeatCount(), keyEvent->getDownTime());
Jeff Brown3241b6b2012-02-03 15:08:02 -08002570 lastInjectedEntry = firstInjectedEntry;
Jeff Brownb6997262010-10-08 22:31:17 -07002571 break;
2572 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07002573
Jeff Brownb6997262010-10-08 22:31:17 -07002574 case AINPUT_EVENT_TYPE_MOTION: {
2575 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
2576 int32_t action = motionEvent->getAction();
2577 size_t pointerCount = motionEvent->getPointerCount();
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002578 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
2579 if (! validateMotionEvent(action, pointerCount, pointerProperties)) {
Jeff Brownb6997262010-10-08 22:31:17 -07002580 return INPUT_EVENT_INJECTION_FAILED;
2581 }
2582
Jeff Brown0029c662011-03-30 02:25:18 -07002583 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
2584 nsecs_t eventTime = motionEvent->getEventTime();
2585 mPolicy->interceptMotionBeforeQueueing(eventTime, /*byref*/ policyFlags);
2586 }
Jeff Brownb6997262010-10-08 22:31:17 -07002587
2588 mLock.lock();
2589 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
2590 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
Jeff Brown3241b6b2012-02-03 15:08:02 -08002591 firstInjectedEntry = new MotionEntry(*sampleEventTimes,
Jeff Brownb6997262010-10-08 22:31:17 -07002592 motionEvent->getDeviceId(), motionEvent->getSource(), policyFlags,
2593 action, motionEvent->getFlags(),
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002594 motionEvent->getMetaState(), motionEvent->getButtonState(),
2595 motionEvent->getEdgeFlags(),
Jeff Brownb6997262010-10-08 22:31:17 -07002596 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
Jeff Brown83d616a2012-09-09 20:33:43 -07002597 motionEvent->getDownTime(), displayId,
Jeff Brown38f96e52014-02-11 14:32:56 -08002598 uint32_t(pointerCount), pointerProperties, samplePointerCoords,
2599 motionEvent->getXOffset(), motionEvent->getYOffset());
Jeff Brown3241b6b2012-02-03 15:08:02 -08002600 lastInjectedEntry = firstInjectedEntry;
Jeff Brownb6997262010-10-08 22:31:17 -07002601 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
2602 sampleEventTimes += 1;
2603 samplePointerCoords += pointerCount;
Jeff Brown3241b6b2012-02-03 15:08:02 -08002604 MotionEntry* nextInjectedEntry = new MotionEntry(*sampleEventTimes,
2605 motionEvent->getDeviceId(), motionEvent->getSource(), policyFlags,
2606 action, motionEvent->getFlags(),
2607 motionEvent->getMetaState(), motionEvent->getButtonState(),
2608 motionEvent->getEdgeFlags(),
2609 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
Jeff Brown83d616a2012-09-09 20:33:43 -07002610 motionEvent->getDownTime(), displayId,
Jeff Brown38f96e52014-02-11 14:32:56 -08002611 uint32_t(pointerCount), pointerProperties, samplePointerCoords,
2612 motionEvent->getXOffset(), motionEvent->getYOffset());
Jeff Brown3241b6b2012-02-03 15:08:02 -08002613 lastInjectedEntry->next = nextInjectedEntry;
2614 lastInjectedEntry = nextInjectedEntry;
Jeff Brownb6997262010-10-08 22:31:17 -07002615 }
Jeff Brownb6997262010-10-08 22:31:17 -07002616 break;
2617 }
2618
2619 default:
Steve Block8564c8d2012-01-05 23:22:43 +00002620 ALOGW("Cannot inject event of type %d", event->getType());
Jeff Brownb6997262010-10-08 22:31:17 -07002621 return INPUT_EVENT_INJECTION_FAILED;
2622 }
2623
Jeff Brownac386072011-07-20 15:19:50 -07002624 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
Jeff Brownb6997262010-10-08 22:31:17 -07002625 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
2626 injectionState->injectionIsAsync = true;
2627 }
2628
2629 injectionState->refCount += 1;
Jeff Brown3241b6b2012-02-03 15:08:02 -08002630 lastInjectedEntry->injectionState = injectionState;
Jeff Brownb6997262010-10-08 22:31:17 -07002631
Jeff Brown3241b6b2012-02-03 15:08:02 -08002632 bool needWake = false;
2633 for (EventEntry* entry = firstInjectedEntry; entry != NULL; ) {
2634 EventEntry* nextEntry = entry->next;
2635 needWake |= enqueueInboundEventLocked(entry);
2636 entry = nextEntry;
2637 }
2638
Jeff Brownb6997262010-10-08 22:31:17 -07002639 mLock.unlock();
Jeff Brown7fbdc842010-06-17 20:52:56 -07002640
Jeff Brownb88102f2010-09-08 11:49:43 -07002641 if (needWake) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002642 mLooper->wake();
Jeff Brown7fbdc842010-06-17 20:52:56 -07002643 }
2644
2645 int32_t injectionResult;
2646 { // acquire lock
2647 AutoMutex _l(mLock);
2648
Jeff Brown6ec402b2010-07-28 15:48:59 -07002649 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
2650 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
2651 } else {
2652 for (;;) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002653 injectionResult = injectionState->injectionResult;
Jeff Brown6ec402b2010-07-28 15:48:59 -07002654 if (injectionResult != INPUT_EVENT_INJECTION_PENDING) {
2655 break;
2656 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07002657
Jeff Brown7fbdc842010-06-17 20:52:56 -07002658 nsecs_t remainingTimeout = endTime - now();
2659 if (remainingTimeout <= 0) {
Jeff Brown6ec402b2010-07-28 15:48:59 -07002660#if DEBUG_INJECTION
Steve Block5baa3a62011-12-20 16:23:08 +00002661 ALOGD("injectInputEvent - Timed out waiting for injection result "
Jeff Brown6ec402b2010-07-28 15:48:59 -07002662 "to become available.");
2663#endif
Jeff Brown7fbdc842010-06-17 20:52:56 -07002664 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
2665 break;
2666 }
2667
Jeff Brown6ec402b2010-07-28 15:48:59 -07002668 mInjectionResultAvailableCondition.waitRelative(mLock, remainingTimeout);
2669 }
2670
2671 if (injectionResult == INPUT_EVENT_INJECTION_SUCCEEDED
2672 && syncMode == INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002673 while (injectionState->pendingForegroundDispatches != 0) {
Jeff Brown6ec402b2010-07-28 15:48:59 -07002674#if DEBUG_INJECTION
Steve Block5baa3a62011-12-20 16:23:08 +00002675 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
Jeff Brown01ce2e92010-09-26 22:20:12 -07002676 injectionState->pendingForegroundDispatches);
Jeff Brown6ec402b2010-07-28 15:48:59 -07002677#endif
2678 nsecs_t remainingTimeout = endTime - now();
2679 if (remainingTimeout <= 0) {
2680#if DEBUG_INJECTION
Steve Block5baa3a62011-12-20 16:23:08 +00002681 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
Jeff Brown6ec402b2010-07-28 15:48:59 -07002682 "dispatches to finish.");
2683#endif
2684 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
2685 break;
2686 }
2687
2688 mInjectionSyncFinishedCondition.waitRelative(mLock, remainingTimeout);
2689 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07002690 }
2691 }
2692
Jeff Brownac386072011-07-20 15:19:50 -07002693 injectionState->release();
Jeff Brown7fbdc842010-06-17 20:52:56 -07002694 } // release lock
2695
Jeff Brown6ec402b2010-07-28 15:48:59 -07002696#if DEBUG_INJECTION
Steve Block5baa3a62011-12-20 16:23:08 +00002697 ALOGD("injectInputEvent - Finished with result %d. "
Jeff Brown6ec402b2010-07-28 15:48:59 -07002698 "injectorPid=%d, injectorUid=%d",
2699 injectionResult, injectorPid, injectorUid);
2700#endif
2701
Jeff Brown7fbdc842010-06-17 20:52:56 -07002702 return injectionResult;
2703}
2704
Jeff Brownb6997262010-10-08 22:31:17 -07002705bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
2706 return injectorUid == 0
2707 || mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
2708}
2709
Jeff Brown7fbdc842010-06-17 20:52:56 -07002710void InputDispatcher::setInjectionResultLocked(EventEntry* entry, int32_t injectionResult) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002711 InjectionState* injectionState = entry->injectionState;
2712 if (injectionState) {
Jeff Brown7fbdc842010-06-17 20:52:56 -07002713#if DEBUG_INJECTION
Steve Block5baa3a62011-12-20 16:23:08 +00002714 ALOGD("Setting input event injection result to %d. "
Jeff Brown7fbdc842010-06-17 20:52:56 -07002715 "injectorPid=%d, injectorUid=%d",
Jeff Brown01ce2e92010-09-26 22:20:12 -07002716 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
Jeff Brown7fbdc842010-06-17 20:52:56 -07002717#endif
2718
Jeff Brown0029c662011-03-30 02:25:18 -07002719 if (injectionState->injectionIsAsync
2720 && !(entry->policyFlags & POLICY_FLAG_FILTERED)) {
Jeff Brown6ec402b2010-07-28 15:48:59 -07002721 // Log the outcome since the injector did not wait for the injection result.
2722 switch (injectionResult) {
2723 case INPUT_EVENT_INJECTION_SUCCEEDED:
Steve Block71f2cf12011-10-20 11:56:00 +01002724 ALOGV("Asynchronous input event injection succeeded.");
Jeff Brown6ec402b2010-07-28 15:48:59 -07002725 break;
2726 case INPUT_EVENT_INJECTION_FAILED:
Steve Block8564c8d2012-01-05 23:22:43 +00002727 ALOGW("Asynchronous input event injection failed.");
Jeff Brown6ec402b2010-07-28 15:48:59 -07002728 break;
2729 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
Steve Block8564c8d2012-01-05 23:22:43 +00002730 ALOGW("Asynchronous input event injection permission denied.");
Jeff Brown6ec402b2010-07-28 15:48:59 -07002731 break;
2732 case INPUT_EVENT_INJECTION_TIMED_OUT:
Steve Block8564c8d2012-01-05 23:22:43 +00002733 ALOGW("Asynchronous input event injection timed out.");
Jeff Brown6ec402b2010-07-28 15:48:59 -07002734 break;
2735 }
2736 }
2737
Jeff Brown01ce2e92010-09-26 22:20:12 -07002738 injectionState->injectionResult = injectionResult;
Jeff Brown7fbdc842010-06-17 20:52:56 -07002739 mInjectionResultAvailableCondition.broadcast();
2740 }
2741}
2742
Jeff Brown01ce2e92010-09-26 22:20:12 -07002743void InputDispatcher::incrementPendingForegroundDispatchesLocked(EventEntry* entry) {
2744 InjectionState* injectionState = entry->injectionState;
2745 if (injectionState) {
2746 injectionState->pendingForegroundDispatches += 1;
2747 }
2748}
2749
Jeff Brown519e0242010-09-15 15:18:56 -07002750void InputDispatcher::decrementPendingForegroundDispatchesLocked(EventEntry* entry) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002751 InjectionState* injectionState = entry->injectionState;
2752 if (injectionState) {
2753 injectionState->pendingForegroundDispatches -= 1;
Jeff Brown6ec402b2010-07-28 15:48:59 -07002754
Jeff Brown01ce2e92010-09-26 22:20:12 -07002755 if (injectionState->pendingForegroundDispatches == 0) {
2756 mInjectionSyncFinishedCondition.broadcast();
2757 }
Jeff Brownb88102f2010-09-08 11:49:43 -07002758 }
2759}
2760
Jeff Brown9302c872011-07-13 22:51:29 -07002761sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
2762 const sp<InputChannel>& inputChannel) const {
2763 size_t numWindows = mWindowHandles.size();
2764 for (size_t i = 0; i < numWindows; i++) {
2765 const sp<InputWindowHandle>& windowHandle = mWindowHandles.itemAt(i);
Jeff Browncc4f7db2011-08-30 20:34:48 -07002766 if (windowHandle->getInputChannel() == inputChannel) {
Jeff Brown9302c872011-07-13 22:51:29 -07002767 return windowHandle;
Jeff Brown01ce2e92010-09-26 22:20:12 -07002768 }
2769 }
2770 return NULL;
2771}
2772
Jeff Brown9302c872011-07-13 22:51:29 -07002773bool InputDispatcher::hasWindowHandleLocked(
2774 const sp<InputWindowHandle>& windowHandle) const {
2775 size_t numWindows = mWindowHandles.size();
2776 for (size_t i = 0; i < numWindows; i++) {
2777 if (mWindowHandles.itemAt(i) == windowHandle) {
2778 return true;
2779 }
2780 }
2781 return false;
2782}
2783
2784void InputDispatcher::setInputWindows(const Vector<sp<InputWindowHandle> >& inputWindowHandles) {
Jeff Brownb88102f2010-09-08 11:49:43 -07002785#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002786 ALOGD("setInputWindows");
Jeff Brownb88102f2010-09-08 11:49:43 -07002787#endif
2788 { // acquire lock
2789 AutoMutex _l(mLock);
2790
Jeff Browncc4f7db2011-08-30 20:34:48 -07002791 Vector<sp<InputWindowHandle> > oldWindowHandles = mWindowHandles;
Jeff Brown9302c872011-07-13 22:51:29 -07002792 mWindowHandles = inputWindowHandles;
Jeff Brownb6997262010-10-08 22:31:17 -07002793
Jeff Brown9302c872011-07-13 22:51:29 -07002794 sp<InputWindowHandle> newFocusedWindowHandle;
2795 bool foundHoveredWindow = false;
2796 for (size_t i = 0; i < mWindowHandles.size(); i++) {
2797 const sp<InputWindowHandle>& windowHandle = mWindowHandles.itemAt(i);
Jeff Browncc4f7db2011-08-30 20:34:48 -07002798 if (!windowHandle->updateInfo() || windowHandle->getInputChannel() == NULL) {
Jeff Brown9302c872011-07-13 22:51:29 -07002799 mWindowHandles.removeAt(i--);
2800 continue;
2801 }
Jeff Browncc4f7db2011-08-30 20:34:48 -07002802 if (windowHandle->getInfo()->hasFocus) {
Jeff Brown9302c872011-07-13 22:51:29 -07002803 newFocusedWindowHandle = windowHandle;
2804 }
2805 if (windowHandle == mLastHoverWindowHandle) {
2806 foundHoveredWindow = true;
Jeff Brownb88102f2010-09-08 11:49:43 -07002807 }
2808 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07002809
Jeff Brown9302c872011-07-13 22:51:29 -07002810 if (!foundHoveredWindow) {
2811 mLastHoverWindowHandle = NULL;
2812 }
2813
2814 if (mFocusedWindowHandle != newFocusedWindowHandle) {
2815 if (mFocusedWindowHandle != NULL) {
Jeff Brownb6997262010-10-08 22:31:17 -07002816#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002817 ALOGD("Focus left window: %s",
Jeff Browncc4f7db2011-08-30 20:34:48 -07002818 mFocusedWindowHandle->getName().string());
Jeff Brownb6997262010-10-08 22:31:17 -07002819#endif
Jeff Browncc4f7db2011-08-30 20:34:48 -07002820 sp<InputChannel> focusedInputChannel = mFocusedWindowHandle->getInputChannel();
2821 if (focusedInputChannel != NULL) {
Christopher Tated9be36c2011-08-16 16:09:33 -07002822 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
2823 "focus left window");
2824 synthesizeCancelationEventsForInputChannelLocked(
Jeff Browncc4f7db2011-08-30 20:34:48 -07002825 focusedInputChannel, options);
Christopher Tated9be36c2011-08-16 16:09:33 -07002826 }
Jeff Brownb6997262010-10-08 22:31:17 -07002827 }
Jeff Brown9302c872011-07-13 22:51:29 -07002828 if (newFocusedWindowHandle != NULL) {
Jeff Brownb6997262010-10-08 22:31:17 -07002829#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002830 ALOGD("Focus entered window: %s",
Jeff Browncc4f7db2011-08-30 20:34:48 -07002831 newFocusedWindowHandle->getName().string());
Jeff Brownb6997262010-10-08 22:31:17 -07002832#endif
Jeff Brown9302c872011-07-13 22:51:29 -07002833 }
2834 mFocusedWindowHandle = newFocusedWindowHandle;
Jeff Brownb6997262010-10-08 22:31:17 -07002835 }
2836
Jeff Brown38f96e52014-02-11 14:32:56 -08002837 for (size_t d = 0; d < mTouchStatesByDisplay.size(); d++) {
2838 TouchState& state = mTouchStatesByDisplay.editValueAt(d);
2839 for (size_t i = 0; i < state.windows.size(); i++) {
2840 TouchedWindow& touchedWindow = state.windows.editItemAt(i);
2841 if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
Jeff Brownb6997262010-10-08 22:31:17 -07002842#if DEBUG_FOCUS
Jeff Brown38f96e52014-02-11 14:32:56 -08002843 ALOGD("Touched window was removed: %s",
2844 touchedWindow.windowHandle->getName().string());
Jeff Brownb6997262010-10-08 22:31:17 -07002845#endif
Jeff Brown38f96e52014-02-11 14:32:56 -08002846 sp<InputChannel> touchedInputChannel =
2847 touchedWindow.windowHandle->getInputChannel();
2848 if (touchedInputChannel != NULL) {
2849 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
2850 "touched window was removed");
2851 synthesizeCancelationEventsForInputChannelLocked(
2852 touchedInputChannel, options);
2853 }
2854 state.windows.removeAt(i--);
Christopher Tated9be36c2011-08-16 16:09:33 -07002855 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07002856 }
2857 }
Jeff Browncc4f7db2011-08-30 20:34:48 -07002858
2859 // Release information for windows that are no longer present.
2860 // This ensures that unused input channels are released promptly.
2861 // Otherwise, they might stick around until the window handle is destroyed
2862 // which might not happen until the next GC.
2863 for (size_t i = 0; i < oldWindowHandles.size(); i++) {
2864 const sp<InputWindowHandle>& oldWindowHandle = oldWindowHandles.itemAt(i);
2865 if (!hasWindowHandleLocked(oldWindowHandle)) {
2866#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002867 ALOGD("Window went away: %s", oldWindowHandle->getName().string());
Jeff Browncc4f7db2011-08-30 20:34:48 -07002868#endif
2869 oldWindowHandle->releaseInfo();
2870 }
2871 }
Jeff Brownb88102f2010-09-08 11:49:43 -07002872 } // release lock
2873
2874 // Wake up poll loop since it may need to make new input dispatching choices.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002875 mLooper->wake();
Jeff Brownb88102f2010-09-08 11:49:43 -07002876}
2877
Jeff Brown9302c872011-07-13 22:51:29 -07002878void InputDispatcher::setFocusedApplication(
2879 const sp<InputApplicationHandle>& inputApplicationHandle) {
Jeff Brownb88102f2010-09-08 11:49:43 -07002880#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002881 ALOGD("setFocusedApplication");
Jeff Brownb88102f2010-09-08 11:49:43 -07002882#endif
2883 { // acquire lock
2884 AutoMutex _l(mLock);
2885
Jeff Browncc4f7db2011-08-30 20:34:48 -07002886 if (inputApplicationHandle != NULL && inputApplicationHandle->updateInfo()) {
Jeff Brown5ea29ab2011-07-27 11:50:51 -07002887 if (mFocusedApplicationHandle != inputApplicationHandle) {
2888 if (mFocusedApplicationHandle != NULL) {
Jeff Browne9bb9be2012-02-06 15:47:55 -08002889 resetANRTimeoutsLocked();
Jeff Browncc4f7db2011-08-30 20:34:48 -07002890 mFocusedApplicationHandle->releaseInfo();
Jeff Brown5ea29ab2011-07-27 11:50:51 -07002891 }
2892 mFocusedApplicationHandle = inputApplicationHandle;
2893 }
2894 } else if (mFocusedApplicationHandle != NULL) {
Jeff Browne9bb9be2012-02-06 15:47:55 -08002895 resetANRTimeoutsLocked();
Jeff Browncc4f7db2011-08-30 20:34:48 -07002896 mFocusedApplicationHandle->releaseInfo();
Jeff Brown9302c872011-07-13 22:51:29 -07002897 mFocusedApplicationHandle.clear();
Jeff Brownb88102f2010-09-08 11:49:43 -07002898 }
2899
2900#if DEBUG_FOCUS
Jeff Brownb6997262010-10-08 22:31:17 -07002901 //logDispatchStateLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -07002902#endif
2903 } // release lock
2904
2905 // Wake up poll loop since it may need to make new input dispatching choices.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002906 mLooper->wake();
Jeff Brownb88102f2010-09-08 11:49:43 -07002907}
2908
Jeff Brownb88102f2010-09-08 11:49:43 -07002909void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
2910#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002911 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
Jeff Brownb88102f2010-09-08 11:49:43 -07002912#endif
2913
2914 bool changed;
2915 { // acquire lock
2916 AutoMutex _l(mLock);
2917
2918 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
Jeff Brown120a4592010-10-27 18:43:51 -07002919 if (mDispatchFrozen && !frozen) {
Jeff Brownb88102f2010-09-08 11:49:43 -07002920 resetANRTimeoutsLocked();
2921 }
2922
Jeff Brown120a4592010-10-27 18:43:51 -07002923 if (mDispatchEnabled && !enabled) {
2924 resetAndDropEverythingLocked("dispatcher is being disabled");
2925 }
2926
Jeff Brownb88102f2010-09-08 11:49:43 -07002927 mDispatchEnabled = enabled;
2928 mDispatchFrozen = frozen;
2929 changed = true;
2930 } else {
2931 changed = false;
2932 }
2933
2934#if DEBUG_FOCUS
Jeff Brownb6997262010-10-08 22:31:17 -07002935 //logDispatchStateLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -07002936#endif
2937 } // release lock
2938
2939 if (changed) {
2940 // Wake up poll loop since it may need to make new input dispatching choices.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002941 mLooper->wake();
Jeff Brown46b9ac02010-04-22 18:58:52 -07002942 }
2943}
2944
Jeff Brown0029c662011-03-30 02:25:18 -07002945void InputDispatcher::setInputFilterEnabled(bool enabled) {
2946#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002947 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
Jeff Brown0029c662011-03-30 02:25:18 -07002948#endif
2949
2950 { // acquire lock
2951 AutoMutex _l(mLock);
2952
2953 if (mInputFilterEnabled == enabled) {
2954 return;
2955 }
2956
2957 mInputFilterEnabled = enabled;
2958 resetAndDropEverythingLocked("input filter is being enabled or disabled");
2959 } // release lock
2960
2961 // Wake up poll loop since there might be work to do to drop everything.
2962 mLooper->wake();
2963}
2964
Jeff Browne6504122010-09-27 14:52:15 -07002965bool InputDispatcher::transferTouchFocus(const sp<InputChannel>& fromChannel,
2966 const sp<InputChannel>& toChannel) {
2967#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002968 ALOGD("transferTouchFocus: fromChannel=%s, toChannel=%s",
Jeff Browne6504122010-09-27 14:52:15 -07002969 fromChannel->getName().string(), toChannel->getName().string());
2970#endif
2971 { // acquire lock
2972 AutoMutex _l(mLock);
2973
Jeff Brown9302c872011-07-13 22:51:29 -07002974 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromChannel);
2975 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toChannel);
2976 if (fromWindowHandle == NULL || toWindowHandle == NULL) {
Jeff Browne6504122010-09-27 14:52:15 -07002977#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002978 ALOGD("Cannot transfer focus because from or to window not found.");
Jeff Browne6504122010-09-27 14:52:15 -07002979#endif
2980 return false;
2981 }
Jeff Brown9302c872011-07-13 22:51:29 -07002982 if (fromWindowHandle == toWindowHandle) {
Jeff Browne6504122010-09-27 14:52:15 -07002983#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002984 ALOGD("Trivial transfer to same window.");
Jeff Browne6504122010-09-27 14:52:15 -07002985#endif
2986 return true;
2987 }
Jeff Brown83d616a2012-09-09 20:33:43 -07002988 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
2989#if DEBUG_FOCUS
2990 ALOGD("Cannot transfer focus because windows are on different displays.");
2991#endif
2992 return false;
2993 }
Jeff Browne6504122010-09-27 14:52:15 -07002994
2995 bool found = false;
Jeff Brown38f96e52014-02-11 14:32:56 -08002996 for (size_t d = 0; d < mTouchStatesByDisplay.size(); d++) {
2997 TouchState& state = mTouchStatesByDisplay.editValueAt(d);
2998 for (size_t i = 0; i < state.windows.size(); i++) {
2999 const TouchedWindow& touchedWindow = state.windows[i];
3000 if (touchedWindow.windowHandle == fromWindowHandle) {
3001 int32_t oldTargetFlags = touchedWindow.targetFlags;
3002 BitSet32 pointerIds = touchedWindow.pointerIds;
Jeff Browne6504122010-09-27 14:52:15 -07003003
Jeff Brown38f96e52014-02-11 14:32:56 -08003004 state.windows.removeAt(i);
Jeff Browne6504122010-09-27 14:52:15 -07003005
Jeff Brown38f96e52014-02-11 14:32:56 -08003006 int32_t newTargetFlags = oldTargetFlags
3007 & (InputTarget::FLAG_FOREGROUND
3008 | InputTarget::FLAG_SPLIT | InputTarget::FLAG_DISPATCH_AS_IS);
3009 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Jeff Browne6504122010-09-27 14:52:15 -07003010
Jeff Brown38f96e52014-02-11 14:32:56 -08003011 found = true;
3012 goto Found;
3013 }
Jeff Browne6504122010-09-27 14:52:15 -07003014 }
3015 }
Jeff Brown38f96e52014-02-11 14:32:56 -08003016Found:
Jeff Browne6504122010-09-27 14:52:15 -07003017
3018 if (! found) {
3019#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00003020 ALOGD("Focus transfer failed because from window did not have focus.");
Jeff Browne6504122010-09-27 14:52:15 -07003021#endif
3022 return false;
3023 }
3024
Jeff Brown9c9f1a32010-10-11 18:32:20 -07003025 ssize_t fromConnectionIndex = getConnectionIndexLocked(fromChannel);
3026 ssize_t toConnectionIndex = getConnectionIndexLocked(toChannel);
3027 if (fromConnectionIndex >= 0 && toConnectionIndex >= 0) {
Jeff Browncbee6d62012-02-03 20:11:27 -08003028 sp<Connection> fromConnection = mConnectionsByFd.valueAt(fromConnectionIndex);
3029 sp<Connection> toConnection = mConnectionsByFd.valueAt(toConnectionIndex);
Jeff Brown9c9f1a32010-10-11 18:32:20 -07003030
3031 fromConnection->inputState.copyPointerStateTo(toConnection->inputState);
Jeff Brownda3d5a92011-03-29 15:11:34 -07003032 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Jeff Brown9c9f1a32010-10-11 18:32:20 -07003033 "transferring touch focus from this window to another window");
Jeff Brownda3d5a92011-03-29 15:11:34 -07003034 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Jeff Brown9c9f1a32010-10-11 18:32:20 -07003035 }
3036
Jeff Browne6504122010-09-27 14:52:15 -07003037#if DEBUG_FOCUS
3038 logDispatchStateLocked();
3039#endif
3040 } // release lock
3041
3042 // Wake up poll loop since it may need to make new input dispatching choices.
3043 mLooper->wake();
3044 return true;
3045}
3046
Jeff Brown120a4592010-10-27 18:43:51 -07003047void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
3048#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00003049 ALOGD("Resetting and dropping all events (%s).", reason);
Jeff Brown120a4592010-10-27 18:43:51 -07003050#endif
3051
Jeff Brownda3d5a92011-03-29 15:11:34 -07003052 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
3053 synthesizeCancelationEventsForAllConnectionsLocked(options);
Jeff Brown120a4592010-10-27 18:43:51 -07003054
3055 resetKeyRepeatLocked();
3056 releasePendingEventLocked();
3057 drainInboundQueueLocked();
Jeff Browne9bb9be2012-02-06 15:47:55 -08003058 resetANRTimeoutsLocked();
Jeff Brown120a4592010-10-27 18:43:51 -07003059
Jeff Brown38f96e52014-02-11 14:32:56 -08003060 mTouchStatesByDisplay.clear();
Jeff Brown9302c872011-07-13 22:51:29 -07003061 mLastHoverWindowHandle.clear();
Jeff Brown120a4592010-10-27 18:43:51 -07003062}
3063
Jeff Brownb88102f2010-09-08 11:49:43 -07003064void InputDispatcher::logDispatchStateLocked() {
3065 String8 dump;
3066 dumpDispatchStateLocked(dump);
Jeff Brown2a95c2a2010-09-16 12:31:46 -07003067
3068 char* text = dump.lockBuffer(dump.size());
3069 char* start = text;
3070 while (*start != '\0') {
3071 char* end = strchr(start, '\n');
3072 if (*end == '\n') {
3073 *(end++) = '\0';
3074 }
Steve Block5baa3a62011-12-20 16:23:08 +00003075 ALOGD("%s", start);
Jeff Brown2a95c2a2010-09-16 12:31:46 -07003076 start = end;
3077 }
Jeff Brownb88102f2010-09-08 11:49:43 -07003078}
3079
3080void InputDispatcher::dumpDispatchStateLocked(String8& dump) {
Jeff Brownf2f48712010-10-01 17:46:21 -07003081 dump.appendFormat(INDENT "DispatchEnabled: %d\n", mDispatchEnabled);
3082 dump.appendFormat(INDENT "DispatchFrozen: %d\n", mDispatchFrozen);
Jeff Brownb88102f2010-09-08 11:49:43 -07003083
Jeff Brown9302c872011-07-13 22:51:29 -07003084 if (mFocusedApplicationHandle != NULL) {
Jeff Brownf2f48712010-10-01 17:46:21 -07003085 dump.appendFormat(INDENT "FocusedApplication: name='%s', dispatchingTimeout=%0.3fms\n",
Jeff Browncc4f7db2011-08-30 20:34:48 -07003086 mFocusedApplicationHandle->getName().string(),
3087 mFocusedApplicationHandle->getDispatchingTimeout(
3088 DEFAULT_INPUT_DISPATCHING_TIMEOUT) / 1000000.0);
Jeff Brownb88102f2010-09-08 11:49:43 -07003089 } else {
Jeff Brownf2f48712010-10-01 17:46:21 -07003090 dump.append(INDENT "FocusedApplication: <null>\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003091 }
Jeff Brownf2f48712010-10-01 17:46:21 -07003092 dump.appendFormat(INDENT "FocusedWindow: name='%s'\n",
Jeff Browncc4f7db2011-08-30 20:34:48 -07003093 mFocusedWindowHandle != NULL ? mFocusedWindowHandle->getName().string() : "<null>");
Jeff Brownf2f48712010-10-01 17:46:21 -07003094
Jeff Brown38f96e52014-02-11 14:32:56 -08003095 if (!mTouchStatesByDisplay.isEmpty()) {
3096 dump.appendFormat(INDENT "TouchStatesByDisplay:\n");
3097 for (size_t i = 0; i < mTouchStatesByDisplay.size(); i++) {
3098 const TouchState& state = mTouchStatesByDisplay.valueAt(i);
3099 dump.appendFormat(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
3100 state.displayId, toString(state.down), toString(state.split),
3101 state.deviceId, state.source);
3102 if (!state.windows.isEmpty()) {
3103 dump.append(INDENT3 "Windows:\n");
3104 for (size_t i = 0; i < state.windows.size(); i++) {
3105 const TouchedWindow& touchedWindow = state.windows[i];
3106 dump.appendFormat(INDENT4 "%d: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
3107 i, touchedWindow.windowHandle->getName().string(),
3108 touchedWindow.pointerIds.value,
3109 touchedWindow.targetFlags);
3110 }
3111 } else {
3112 dump.append(INDENT3 "Windows: <none>\n");
3113 }
Jeff Brownf2f48712010-10-01 17:46:21 -07003114 }
3115 } else {
Jeff Brown38f96e52014-02-11 14:32:56 -08003116 dump.append(INDENT "TouchStates: <no displays touched>\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003117 }
3118
Jeff Brown9302c872011-07-13 22:51:29 -07003119 if (!mWindowHandles.isEmpty()) {
Jeff Brownf2f48712010-10-01 17:46:21 -07003120 dump.append(INDENT "Windows:\n");
Jeff Brown9302c872011-07-13 22:51:29 -07003121 for (size_t i = 0; i < mWindowHandles.size(); i++) {
3122 const sp<InputWindowHandle>& windowHandle = mWindowHandles.itemAt(i);
Jeff Browncc4f7db2011-08-30 20:34:48 -07003123 const InputWindowInfo* windowInfo = windowHandle->getInfo();
3124
Jeff Brown83d616a2012-09-09 20:33:43 -07003125 dump.appendFormat(INDENT2 "%d: name='%s', displayId=%d, "
3126 "paused=%s, hasFocus=%s, hasWallpaper=%s, "
Jeff Brownf2f48712010-10-01 17:46:21 -07003127 "visible=%s, canReceiveKeys=%s, flags=0x%08x, type=0x%08x, layer=%d, "
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003128 "frame=[%d,%d][%d,%d], scale=%f, "
Jeff Brownfbf09772011-01-16 14:06:57 -08003129 "touchableRegion=",
Jeff Brown83d616a2012-09-09 20:33:43 -07003130 i, windowInfo->name.string(), windowInfo->displayId,
Jeff Browncc4f7db2011-08-30 20:34:48 -07003131 toString(windowInfo->paused),
3132 toString(windowInfo->hasFocus),
3133 toString(windowInfo->hasWallpaper),
3134 toString(windowInfo->visible),
3135 toString(windowInfo->canReceiveKeys),
3136 windowInfo->layoutParamsFlags, windowInfo->layoutParamsType,
3137 windowInfo->layer,
3138 windowInfo->frameLeft, windowInfo->frameTop,
3139 windowInfo->frameRight, windowInfo->frameBottom,
3140 windowInfo->scaleFactor);
3141 dumpRegion(dump, windowInfo->touchableRegion);
3142 dump.appendFormat(", inputFeatures=0x%08x", windowInfo->inputFeatures);
Jeff Brownfbf09772011-01-16 14:06:57 -08003143 dump.appendFormat(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%0.3fms\n",
Jeff Browncc4f7db2011-08-30 20:34:48 -07003144 windowInfo->ownerPid, windowInfo->ownerUid,
3145 windowInfo->dispatchingTimeout / 1000000.0);
Jeff Brownf2f48712010-10-01 17:46:21 -07003146 }
3147 } else {
3148 dump.append(INDENT "Windows: <none>\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003149 }
3150
Jeff Brownf2f48712010-10-01 17:46:21 -07003151 if (!mMonitoringChannels.isEmpty()) {
3152 dump.append(INDENT "MonitoringChannels:\n");
3153 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
3154 const sp<InputChannel>& channel = mMonitoringChannels[i];
3155 dump.appendFormat(INDENT2 "%d: '%s'\n", i, channel->getName().string());
3156 }
3157 } else {
3158 dump.append(INDENT "MonitoringChannels: <none>\n");
3159 }
Jeff Brown519e0242010-09-15 15:18:56 -07003160
Jeff Brown265f1cc2012-06-11 18:01:06 -07003161 nsecs_t currentTime = now();
3162
Jeff Brown6876f322013-08-07 16:46:50 -07003163 // Dump recently dispatched or dropped events from oldest to newest.
3164 if (!mRecentQueue.isEmpty()) {
3165 dump.appendFormat(INDENT "RecentQueue: length=%u\n", mRecentQueue.count());
3166 for (EventEntry* entry = mRecentQueue.head; entry; entry = entry->next) {
3167 dump.append(INDENT2);
3168 entry->appendDescription(dump);
3169 dump.appendFormat(", age=%0.1fms\n",
3170 (currentTime - entry->eventTime) * 0.000001f);
3171 }
3172 } else {
3173 dump.append(INDENT "RecentQueue: <empty>\n");
3174 }
3175
3176 // Dump event currently being dispatched.
3177 if (mPendingEvent) {
3178 dump.append(INDENT "PendingEvent:\n");
3179 dump.append(INDENT2);
3180 mPendingEvent->appendDescription(dump);
3181 dump.appendFormat(", age=%0.1fms\n",
3182 (currentTime - mPendingEvent->eventTime) * 0.000001f);
3183 } else {
3184 dump.append(INDENT "PendingEvent: <none>\n");
3185 }
3186
3187 // Dump inbound events from oldest to newest.
Jeff Brown265f1cc2012-06-11 18:01:06 -07003188 if (!mInboundQueue.isEmpty()) {
3189 dump.appendFormat(INDENT "InboundQueue: length=%u\n", mInboundQueue.count());
3190 for (EventEntry* entry = mInboundQueue.head; entry; entry = entry->next) {
3191 dump.append(INDENT2);
3192 entry->appendDescription(dump);
Jeff Brown22aa5122012-06-17 12:01:06 -07003193 dump.appendFormat(", age=%0.1fms\n",
Jeff Brown265f1cc2012-06-11 18:01:06 -07003194 (currentTime - entry->eventTime) * 0.000001f);
3195 }
3196 } else {
3197 dump.append(INDENT "InboundQueue: <empty>\n");
3198 }
3199
3200 if (!mConnectionsByFd.isEmpty()) {
3201 dump.append(INDENT "Connections:\n");
3202 for (size_t i = 0; i < mConnectionsByFd.size(); i++) {
3203 const sp<Connection>& connection = mConnectionsByFd.valueAt(i);
3204 dump.appendFormat(INDENT2 "%d: channelName='%s', windowName='%s', "
3205 "status=%s, monitor=%s, inputPublisherBlocked=%s\n",
3206 i, connection->getInputChannelName(), connection->getWindowName(),
3207 connection->getStatusLabel(), toString(connection->monitor),
3208 toString(connection->inputPublisherBlocked));
3209
3210 if (!connection->outboundQueue.isEmpty()) {
3211 dump.appendFormat(INDENT3 "OutboundQueue: length=%u\n",
3212 connection->outboundQueue.count());
3213 for (DispatchEntry* entry = connection->outboundQueue.head; entry;
3214 entry = entry->next) {
3215 dump.append(INDENT4);
3216 entry->eventEntry->appendDescription(dump);
Jeff Brown22aa5122012-06-17 12:01:06 -07003217 dump.appendFormat(", targetFlags=0x%08x, resolvedAction=%d, age=%0.1fms\n",
Jeff Brown265f1cc2012-06-11 18:01:06 -07003218 entry->targetFlags, entry->resolvedAction,
3219 (currentTime - entry->eventEntry->eventTime) * 0.000001f);
3220 }
3221 } else {
3222 dump.append(INDENT3 "OutboundQueue: <empty>\n");
3223 }
3224
3225 if (!connection->waitQueue.isEmpty()) {
3226 dump.appendFormat(INDENT3 "WaitQueue: length=%u\n",
3227 connection->waitQueue.count());
3228 for (DispatchEntry* entry = connection->waitQueue.head; entry;
3229 entry = entry->next) {
3230 dump.append(INDENT4);
3231 entry->eventEntry->appendDescription(dump);
3232 dump.appendFormat(", targetFlags=0x%08x, resolvedAction=%d, "
Jeff Brown22aa5122012-06-17 12:01:06 -07003233 "age=%0.1fms, wait=%0.1fms\n",
Jeff Brown265f1cc2012-06-11 18:01:06 -07003234 entry->targetFlags, entry->resolvedAction,
3235 (currentTime - entry->eventEntry->eventTime) * 0.000001f,
3236 (currentTime - entry->deliveryTime) * 0.000001f);
3237 }
3238 } else {
3239 dump.append(INDENT3 "WaitQueue: <empty>\n");
3240 }
3241 }
3242 } else {
3243 dump.append(INDENT "Connections: <none>\n");
3244 }
Jeff Brownf2f48712010-10-01 17:46:21 -07003245
Jeff Brownb88102f2010-09-08 11:49:43 -07003246 if (isAppSwitchPendingLocked()) {
Jeff Brown22aa5122012-06-17 12:01:06 -07003247 dump.appendFormat(INDENT "AppSwitch: pending, due in %0.1fms\n",
Jeff Brownb88102f2010-09-08 11:49:43 -07003248 (mAppSwitchDueTime - now()) / 1000000.0);
3249 } else {
Jeff Brownf2f48712010-10-01 17:46:21 -07003250 dump.append(INDENT "AppSwitch: not pending\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003251 }
Jeff Brown22aa5122012-06-17 12:01:06 -07003252
3253 dump.append(INDENT "Configuration:\n");
3254 dump.appendFormat(INDENT2 "KeyRepeatDelay: %0.1fms\n",
3255 mConfig.keyRepeatDelay * 0.000001f);
3256 dump.appendFormat(INDENT2 "KeyRepeatTimeout: %0.1fms\n",
3257 mConfig.keyRepeatTimeout * 0.000001f);
Jeff Brownb88102f2010-09-08 11:49:43 -07003258}
3259
Jeff Brown928e0542011-01-10 11:17:36 -08003260status_t InputDispatcher::registerInputChannel(const sp<InputChannel>& inputChannel,
3261 const sp<InputWindowHandle>& inputWindowHandle, bool monitor) {
Jeff Brown9c3cda02010-06-15 01:31:58 -07003262#if DEBUG_REGISTRATION
Steve Block5baa3a62011-12-20 16:23:08 +00003263 ALOGD("channel '%s' ~ registerInputChannel - monitor=%s", inputChannel->getName().string(),
Jeff Brownb88102f2010-09-08 11:49:43 -07003264 toString(monitor));
Jeff Brown9c3cda02010-06-15 01:31:58 -07003265#endif
3266
Jeff Brown46b9ac02010-04-22 18:58:52 -07003267 { // acquire lock
3268 AutoMutex _l(mLock);
3269
Jeff Brown519e0242010-09-15 15:18:56 -07003270 if (getConnectionIndexLocked(inputChannel) >= 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00003271 ALOGW("Attempted to register already registered input channel '%s'",
Jeff Brown46b9ac02010-04-22 18:58:52 -07003272 inputChannel->getName().string());
3273 return BAD_VALUE;
3274 }
3275
Jeff Browncc4f7db2011-08-30 20:34:48 -07003276 sp<Connection> connection = new Connection(inputChannel, inputWindowHandle, monitor);
Jeff Brown46b9ac02010-04-22 18:58:52 -07003277
Jeff Brown91e32892012-02-14 15:56:29 -08003278 int fd = inputChannel->getFd();
Jeff Browncbee6d62012-02-03 20:11:27 -08003279 mConnectionsByFd.add(fd, connection);
Jeff Brown9c3cda02010-06-15 01:31:58 -07003280
Jeff Brownb88102f2010-09-08 11:49:43 -07003281 if (monitor) {
3282 mMonitoringChannels.push(inputChannel);
3283 }
3284
Jeff Browncbee6d62012-02-03 20:11:27 -08003285 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
Jeff Brown46b9ac02010-04-22 18:58:52 -07003286 } // release lock
Jeff Brown074b8b72012-10-31 19:01:31 -07003287
3288 // Wake the looper because some connections have changed.
3289 mLooper->wake();
Jeff Brown46b9ac02010-04-22 18:58:52 -07003290 return OK;
3291}
3292
3293status_t InputDispatcher::unregisterInputChannel(const sp<InputChannel>& inputChannel) {
Jeff Brown9c3cda02010-06-15 01:31:58 -07003294#if DEBUG_REGISTRATION
Steve Block5baa3a62011-12-20 16:23:08 +00003295 ALOGD("channel '%s' ~ unregisterInputChannel", inputChannel->getName().string());
Jeff Brown9c3cda02010-06-15 01:31:58 -07003296#endif
3297
Jeff Brown46b9ac02010-04-22 18:58:52 -07003298 { // acquire lock
3299 AutoMutex _l(mLock);
3300
Jeff Browncc4f7db2011-08-30 20:34:48 -07003301 status_t status = unregisterInputChannelLocked(inputChannel, false /*notify*/);
3302 if (status) {
3303 return status;
Jeff Brown46b9ac02010-04-22 18:58:52 -07003304 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07003305 } // release lock
3306
Jeff Brown46b9ac02010-04-22 18:58:52 -07003307 // Wake the poll loop because removing the connection may have changed the current
3308 // synchronization state.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07003309 mLooper->wake();
Jeff Brown46b9ac02010-04-22 18:58:52 -07003310 return OK;
3311}
3312
Jeff Browncc4f7db2011-08-30 20:34:48 -07003313status_t InputDispatcher::unregisterInputChannelLocked(const sp<InputChannel>& inputChannel,
3314 bool notify) {
3315 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
3316 if (connectionIndex < 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00003317 ALOGW("Attempted to unregister already unregistered input channel '%s'",
Jeff Browncc4f7db2011-08-30 20:34:48 -07003318 inputChannel->getName().string());
3319 return BAD_VALUE;
3320 }
3321
Jeff Browncbee6d62012-02-03 20:11:27 -08003322 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
3323 mConnectionsByFd.removeItemsAt(connectionIndex);
Jeff Browncc4f7db2011-08-30 20:34:48 -07003324
3325 if (connection->monitor) {
3326 removeMonitorChannelLocked(inputChannel);
3327 }
3328
Jeff Browncbee6d62012-02-03 20:11:27 -08003329 mLooper->removeFd(inputChannel->getFd());
Jeff Browncc4f7db2011-08-30 20:34:48 -07003330
3331 nsecs_t currentTime = now();
3332 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
3333
Jeff Browncc4f7db2011-08-30 20:34:48 -07003334 connection->status = Connection::STATUS_ZOMBIE;
3335 return OK;
3336}
3337
3338void InputDispatcher::removeMonitorChannelLocked(const sp<InputChannel>& inputChannel) {
3339 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
3340 if (mMonitoringChannels[i] == inputChannel) {
3341 mMonitoringChannels.removeAt(i);
3342 break;
3343 }
3344 }
3345}
3346
Jeff Brown519e0242010-09-15 15:18:56 -07003347ssize_t InputDispatcher::getConnectionIndexLocked(const sp<InputChannel>& inputChannel) {
Jeff Browncbee6d62012-02-03 20:11:27 -08003348 ssize_t connectionIndex = mConnectionsByFd.indexOfKey(inputChannel->getFd());
Jeff Brown2cbecea2010-08-17 15:59:26 -07003349 if (connectionIndex >= 0) {
Jeff Browncbee6d62012-02-03 20:11:27 -08003350 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
Jeff Brown2cbecea2010-08-17 15:59:26 -07003351 if (connection->inputChannel.get() == inputChannel.get()) {
3352 return connectionIndex;
3353 }
3354 }
3355
3356 return -1;
3357}
3358
Jeff Brown9c3cda02010-06-15 01:31:58 -07003359void InputDispatcher::onDispatchCycleFinishedLocked(
Jeff Brown072ec962012-02-07 14:46:57 -08003360 nsecs_t currentTime, const sp<Connection>& connection, uint32_t seq, bool handled) {
Jeff Brown3915bb82010-11-05 15:02:16 -07003361 CommandEntry* commandEntry = postCommandLocked(
3362 & InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
3363 commandEntry->connection = connection;
Jeff Brown265f1cc2012-06-11 18:01:06 -07003364 commandEntry->eventTime = currentTime;
Jeff Brown072ec962012-02-07 14:46:57 -08003365 commandEntry->seq = seq;
Jeff Brown3915bb82010-11-05 15:02:16 -07003366 commandEntry->handled = handled;
Jeff Brown46b9ac02010-04-22 18:58:52 -07003367}
3368
Jeff Brown9c3cda02010-06-15 01:31:58 -07003369void InputDispatcher::onDispatchCycleBrokenLocked(
Jeff Brown7fbdc842010-06-17 20:52:56 -07003370 nsecs_t currentTime, const sp<Connection>& connection) {
Steve Block3762c312012-01-06 19:20:56 +00003371 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Jeff Brown46b9ac02010-04-22 18:58:52 -07003372 connection->getInputChannelName());
3373
Jeff Brown9c3cda02010-06-15 01:31:58 -07003374 CommandEntry* commandEntry = postCommandLocked(
3375 & InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
Jeff Brown7fbdc842010-06-17 20:52:56 -07003376 commandEntry->connection = connection;
Jeff Brown46b9ac02010-04-22 18:58:52 -07003377}
3378
Jeff Brown519e0242010-09-15 15:18:56 -07003379void InputDispatcher::onANRLocked(
Jeff Brown9302c872011-07-13 22:51:29 -07003380 nsecs_t currentTime, const sp<InputApplicationHandle>& applicationHandle,
3381 const sp<InputWindowHandle>& windowHandle,
Jeff Brown265f1cc2012-06-11 18:01:06 -07003382 nsecs_t eventTime, nsecs_t waitStartTime, const char* reason) {
Jeff Brown22aa5122012-06-17 12:01:06 -07003383 float dispatchLatency = (currentTime - eventTime) * 0.000001f;
3384 float waitDuration = (currentTime - waitStartTime) * 0.000001f;
Steve Block6215d3f2012-01-04 20:05:49 +00003385 ALOGI("Application is not responding: %s. "
Jeff Brown22aa5122012-06-17 12:01:06 -07003386 "It has been %0.1fms since event, %0.1fms since wait started. Reason: %s",
Jeff Brown9302c872011-07-13 22:51:29 -07003387 getApplicationWindowLabelLocked(applicationHandle, windowHandle).string(),
Jeff Brown22aa5122012-06-17 12:01:06 -07003388 dispatchLatency, waitDuration, reason);
3389
3390 // Capture a record of the InputDispatcher state at the time of the ANR.
3391 time_t t = time(NULL);
3392 struct tm tm;
3393 localtime_r(&t, &tm);
3394 char timestr[64];
3395 strftime(timestr, sizeof(timestr), "%F %T", &tm);
3396 mLastANRState.clear();
3397 mLastANRState.append(INDENT "ANR:\n");
3398 mLastANRState.appendFormat(INDENT2 "Time: %s\n", timestr);
3399 mLastANRState.appendFormat(INDENT2 "Window: %s\n",
3400 getApplicationWindowLabelLocked(applicationHandle, windowHandle).string());
3401 mLastANRState.appendFormat(INDENT2 "DispatchLatency: %0.1fms\n", dispatchLatency);
3402 mLastANRState.appendFormat(INDENT2 "WaitDuration: %0.1fms\n", waitDuration);
3403 mLastANRState.appendFormat(INDENT2 "Reason: %s\n", reason);
3404 dumpDispatchStateLocked(mLastANRState);
Jeff Brown519e0242010-09-15 15:18:56 -07003405
3406 CommandEntry* commandEntry = postCommandLocked(
3407 & InputDispatcher::doNotifyANRLockedInterruptible);
Jeff Brown9302c872011-07-13 22:51:29 -07003408 commandEntry->inputApplicationHandle = applicationHandle;
3409 commandEntry->inputWindowHandle = windowHandle;
Jeff Brownbd181bb2013-09-10 16:44:24 -07003410 commandEntry->reason = reason;
Jeff Brown519e0242010-09-15 15:18:56 -07003411}
3412
Jeff Brownb88102f2010-09-08 11:49:43 -07003413void InputDispatcher::doNotifyConfigurationChangedInterruptible(
3414 CommandEntry* commandEntry) {
3415 mLock.unlock();
3416
3417 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
3418
3419 mLock.lock();
3420}
3421
Jeff Brown9c3cda02010-06-15 01:31:58 -07003422void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(
3423 CommandEntry* commandEntry) {
Jeff Brown7fbdc842010-06-17 20:52:56 -07003424 sp<Connection> connection = commandEntry->connection;
Jeff Brown9c3cda02010-06-15 01:31:58 -07003425
Jeff Brown7fbdc842010-06-17 20:52:56 -07003426 if (connection->status != Connection::STATUS_ZOMBIE) {
3427 mLock.unlock();
Jeff Brown9c3cda02010-06-15 01:31:58 -07003428
Jeff Brown928e0542011-01-10 11:17:36 -08003429 mPolicy->notifyInputChannelBroken(connection->inputWindowHandle);
Jeff Brown7fbdc842010-06-17 20:52:56 -07003430
3431 mLock.lock();
3432 }
Jeff Brown9c3cda02010-06-15 01:31:58 -07003433}
3434
Jeff Brown519e0242010-09-15 15:18:56 -07003435void InputDispatcher::doNotifyANRLockedInterruptible(
Jeff Brown9c3cda02010-06-15 01:31:58 -07003436 CommandEntry* commandEntry) {
Jeff Brown519e0242010-09-15 15:18:56 -07003437 mLock.unlock();
Jeff Brown9c3cda02010-06-15 01:31:58 -07003438
Jeff Brown519e0242010-09-15 15:18:56 -07003439 nsecs_t newTimeout = mPolicy->notifyANR(
Jeff Brownbd181bb2013-09-10 16:44:24 -07003440 commandEntry->inputApplicationHandle, commandEntry->inputWindowHandle,
3441 commandEntry->reason);
Jeff Brown9c3cda02010-06-15 01:31:58 -07003442
Jeff Brown519e0242010-09-15 15:18:56 -07003443 mLock.lock();
Jeff Brown7fbdc842010-06-17 20:52:56 -07003444
Jeff Brown9302c872011-07-13 22:51:29 -07003445 resumeAfterTargetsNotReadyTimeoutLocked(newTimeout,
3446 commandEntry->inputWindowHandle != NULL
Jeff Browncc4f7db2011-08-30 20:34:48 -07003447 ? commandEntry->inputWindowHandle->getInputChannel() : NULL);
Jeff Brown9c3cda02010-06-15 01:31:58 -07003448}
3449
Jeff Brownb88102f2010-09-08 11:49:43 -07003450void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
3451 CommandEntry* commandEntry) {
3452 KeyEntry* entry = commandEntry->keyEntry;
Jeff Brown1f245102010-11-18 20:53:46 -08003453
3454 KeyEvent event;
3455 initializeKeyEvent(&event, entry);
Jeff Brownb88102f2010-09-08 11:49:43 -07003456
3457 mLock.unlock();
3458
Jeff Brown905805a2011-10-12 13:57:59 -07003459 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(commandEntry->inputWindowHandle,
Jeff Brown1f245102010-11-18 20:53:46 -08003460 &event, entry->policyFlags);
Jeff Brownb88102f2010-09-08 11:49:43 -07003461
3462 mLock.lock();
3463
Jeff Brown905805a2011-10-12 13:57:59 -07003464 if (delay < 0) {
3465 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
3466 } else if (!delay) {
3467 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
3468 } else {
3469 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
3470 entry->interceptKeyWakeupTime = now() + delay;
3471 }
Jeff Brownac386072011-07-20 15:19:50 -07003472 entry->release();
Jeff Brownb88102f2010-09-08 11:49:43 -07003473}
3474
Jeff Brown3915bb82010-11-05 15:02:16 -07003475void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(
3476 CommandEntry* commandEntry) {
3477 sp<Connection> connection = commandEntry->connection;
Jeff Brown265f1cc2012-06-11 18:01:06 -07003478 nsecs_t finishTime = commandEntry->eventTime;
Jeff Brown072ec962012-02-07 14:46:57 -08003479 uint32_t seq = commandEntry->seq;
Jeff Brown3915bb82010-11-05 15:02:16 -07003480 bool handled = commandEntry->handled;
3481
Jeff Brown072ec962012-02-07 14:46:57 -08003482 // Handle post-event policy actions.
3483 DispatchEntry* dispatchEntry = connection->findWaitQueueEntry(seq);
3484 if (dispatchEntry) {
Jeff Brown265f1cc2012-06-11 18:01:06 -07003485 nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
3486 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
3487 String8 msg;
Jeff Brown22aa5122012-06-17 12:01:06 -07003488 msg.appendFormat("Window '%s' spent %0.1fms processing the last input event: ",
Jeff Brown265f1cc2012-06-11 18:01:06 -07003489 connection->getWindowName(), eventDuration * 0.000001f);
3490 dispatchEntry->eventEntry->appendDescription(msg);
3491 ALOGI("%s", msg.string());
3492 }
3493
Jeff Brownd1c48a02012-02-06 19:12:47 -08003494 bool restartEvent;
Jeff Brownd1c48a02012-02-06 19:12:47 -08003495 if (dispatchEntry->eventEntry->type == EventEntry::TYPE_KEY) {
3496 KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry);
3497 restartEvent = afterKeyEventLockedInterruptible(connection,
3498 dispatchEntry, keyEntry, handled);
3499 } else if (dispatchEntry->eventEntry->type == EventEntry::TYPE_MOTION) {
3500 MotionEntry* motionEntry = static_cast<MotionEntry*>(dispatchEntry->eventEntry);
3501 restartEvent = afterMotionEventLockedInterruptible(connection,
3502 dispatchEntry, motionEntry, handled);
3503 } else {
3504 restartEvent = false;
3505 }
3506
3507 // Dequeue the event and start the next cycle.
3508 // Note that because the lock might have been released, it is possible that the
3509 // contents of the wait queue to have been drained, so we need to double-check
3510 // a few things.
Jeff Brown072ec962012-02-07 14:46:57 -08003511 if (dispatchEntry == connection->findWaitQueueEntry(seq)) {
3512 connection->waitQueue.dequeue(dispatchEntry);
Jeff Brown481c1572012-03-09 14:41:15 -08003513 traceWaitQueueLengthLocked(connection);
Jeff Brownd1c48a02012-02-06 19:12:47 -08003514 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
3515 connection->outboundQueue.enqueueAtHead(dispatchEntry);
Jeff Brown481c1572012-03-09 14:41:15 -08003516 traceOutboundQueueLengthLocked(connection);
Jeff Brownd1c48a02012-02-06 19:12:47 -08003517 } else {
3518 releaseDispatchEntryLocked(dispatchEntry);
Jeff Brown49ed71d2010-12-06 17:13:33 -08003519 }
Jeff Brown3915bb82010-11-05 15:02:16 -07003520 }
Jeff Brown3915bb82010-11-05 15:02:16 -07003521
Jeff Brownd1c48a02012-02-06 19:12:47 -08003522 // Start the next dispatch cycle for this connection.
3523 startDispatchCycleLocked(now(), connection);
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003524 }
3525}
3526
3527bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
3528 DispatchEntry* dispatchEntry, KeyEntry* keyEntry, bool handled) {
3529 if (!(keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK)) {
3530 // Get the fallback key state.
3531 // Clear it out after dispatching the UP.
3532 int32_t originalKeyCode = keyEntry->keyCode;
3533 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
3534 if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
3535 connection->inputState.removeFallbackKey(originalKeyCode);
3536 }
3537
3538 if (handled || !dispatchEntry->hasForegroundTarget()) {
3539 // If the application handles the original key for which we previously
3540 // generated a fallback or if the window is not a foreground window,
3541 // then cancel the associated fallback key, if any.
3542 if (fallbackKeyCode != -1) {
Jeff Brownfd23e3e2012-05-09 13:34:28 -07003543 // Dispatch the unhandled key to the policy with the cancel flag.
3544#if DEBUG_OUTBOUND_EVENT_DETAILS
3545 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
3546 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
3547 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
3548 keyEntry->policyFlags);
3549#endif
3550 KeyEvent event;
3551 initializeKeyEvent(&event, keyEntry);
3552 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
3553
3554 mLock.unlock();
3555
3556 mPolicy->dispatchUnhandledKey(connection->inputWindowHandle,
3557 &event, keyEntry->policyFlags, &event);
3558
3559 mLock.lock();
3560
3561 // Cancel the fallback key.
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003562 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
3563 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
3564 "application handled the original non-fallback key "
3565 "or is no longer a foreground target, "
3566 "canceling previously dispatched fallback key");
3567 options.keyCode = fallbackKeyCode;
3568 synthesizeCancelationEventsForConnectionLocked(connection, options);
3569 }
3570 connection->inputState.removeFallbackKey(originalKeyCode);
3571 }
3572 } else {
3573 // If the application did not handle a non-fallback key, first check
3574 // that we are in a good state to perform unhandled key event processing
3575 // Then ask the policy what to do with it.
3576 bool initialDown = keyEntry->action == AKEY_EVENT_ACTION_DOWN
3577 && keyEntry->repeatCount == 0;
3578 if (fallbackKeyCode == -1 && !initialDown) {
3579#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00003580 ALOGD("Unhandled key event: Skipping unhandled key event processing "
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003581 "since this is not an initial down. "
Jeff Brownfd23e3e2012-05-09 13:34:28 -07003582 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
3583 originalKeyCode, keyEntry->action, keyEntry->repeatCount,
3584 keyEntry->policyFlags);
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003585#endif
3586 return false;
3587 }
3588
3589 // Dispatch the unhandled key to the policy.
3590#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00003591 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
Jeff Brownfd23e3e2012-05-09 13:34:28 -07003592 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
3593 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
3594 keyEntry->policyFlags);
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003595#endif
3596 KeyEvent event;
3597 initializeKeyEvent(&event, keyEntry);
3598
3599 mLock.unlock();
3600
3601 bool fallback = mPolicy->dispatchUnhandledKey(connection->inputWindowHandle,
3602 &event, keyEntry->policyFlags, &event);
3603
3604 mLock.lock();
3605
3606 if (connection->status != Connection::STATUS_NORMAL) {
3607 connection->inputState.removeFallbackKey(originalKeyCode);
Jeff Brownd1c48a02012-02-06 19:12:47 -08003608 return false;
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003609 }
3610
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003611 // Latch the fallback keycode for this key on an initial down.
3612 // The fallback keycode cannot change at any other point in the lifecycle.
3613 if (initialDown) {
3614 if (fallback) {
3615 fallbackKeyCode = event.getKeyCode();
3616 } else {
3617 fallbackKeyCode = AKEYCODE_UNKNOWN;
3618 }
3619 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
3620 }
3621
Steve Blockec193de2012-01-09 18:35:44 +00003622 ALOG_ASSERT(fallbackKeyCode != -1);
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003623
3624 // Cancel the fallback key if the policy decides not to send it anymore.
3625 // We will continue to dispatch the key to the policy but we will no
3626 // longer dispatch a fallback key to the application.
3627 if (fallbackKeyCode != AKEYCODE_UNKNOWN
3628 && (!fallback || fallbackKeyCode != event.getKeyCode())) {
3629#if DEBUG_OUTBOUND_EVENT_DETAILS
3630 if (fallback) {
Steve Block5baa3a62011-12-20 16:23:08 +00003631 ALOGD("Unhandled key event: Policy requested to send key %d"
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003632 "as a fallback for %d, but on the DOWN it had requested "
3633 "to send %d instead. Fallback canceled.",
3634 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
3635 } else {
Jeff Brownfd23e3e2012-05-09 13:34:28 -07003636 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003637 "but on the DOWN it had requested to send %d. "
3638 "Fallback canceled.",
3639 originalKeyCode, fallbackKeyCode);
3640 }
3641#endif
3642
3643 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
3644 "canceling fallback, policy no longer desires it");
3645 options.keyCode = fallbackKeyCode;
3646 synthesizeCancelationEventsForConnectionLocked(connection, options);
3647
3648 fallback = false;
3649 fallbackKeyCode = AKEYCODE_UNKNOWN;
3650 if (keyEntry->action != AKEY_EVENT_ACTION_UP) {
3651 connection->inputState.setFallbackKey(originalKeyCode,
3652 fallbackKeyCode);
3653 }
3654 }
3655
3656#if DEBUG_OUTBOUND_EVENT_DETAILS
3657 {
3658 String8 msg;
3659 const KeyedVector<int32_t, int32_t>& fallbackKeys =
3660 connection->inputState.getFallbackKeys();
3661 for (size_t i = 0; i < fallbackKeys.size(); i++) {
3662 msg.appendFormat(", %d->%d", fallbackKeys.keyAt(i),
3663 fallbackKeys.valueAt(i));
3664 }
Steve Block5baa3a62011-12-20 16:23:08 +00003665 ALOGD("Unhandled key event: %d currently tracked fallback keys%s.",
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003666 fallbackKeys.size(), msg.string());
3667 }
3668#endif
3669
3670 if (fallback) {
3671 // Restart the dispatch cycle using the fallback key.
3672 keyEntry->eventTime = event.getEventTime();
3673 keyEntry->deviceId = event.getDeviceId();
3674 keyEntry->source = event.getSource();
3675 keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
3676 keyEntry->keyCode = fallbackKeyCode;
3677 keyEntry->scanCode = event.getScanCode();
3678 keyEntry->metaState = event.getMetaState();
3679 keyEntry->repeatCount = event.getRepeatCount();
3680 keyEntry->downTime = event.getDownTime();
3681 keyEntry->syntheticRepeat = false;
3682
3683#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00003684 ALOGD("Unhandled key event: Dispatching fallback key. "
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003685 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
3686 originalKeyCode, fallbackKeyCode, keyEntry->metaState);
3687#endif
Jeff Brownd1c48a02012-02-06 19:12:47 -08003688 return true; // restart the event
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003689 } else {
3690#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00003691 ALOGD("Unhandled key event: No fallback key.");
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003692#endif
3693 }
3694 }
3695 }
3696 return false;
3697}
3698
3699bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
3700 DispatchEntry* dispatchEntry, MotionEntry* motionEntry, bool handled) {
3701 return false;
Jeff Brown3915bb82010-11-05 15:02:16 -07003702}
3703
Jeff Brownb88102f2010-09-08 11:49:43 -07003704void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
3705 mLock.unlock();
3706
Jeff Brown01ce2e92010-09-26 22:20:12 -07003707 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
Jeff Brownb88102f2010-09-08 11:49:43 -07003708
3709 mLock.lock();
3710}
3711
Jeff Brown3915bb82010-11-05 15:02:16 -07003712void InputDispatcher::initializeKeyEvent(KeyEvent* event, const KeyEntry* entry) {
3713 event->initialize(entry->deviceId, entry->source, entry->action, entry->flags,
3714 entry->keyCode, entry->scanCode, entry->metaState, entry->repeatCount,
3715 entry->downTime, entry->eventTime);
3716}
3717
Jeff Brown519e0242010-09-15 15:18:56 -07003718void InputDispatcher::updateDispatchStatisticsLocked(nsecs_t currentTime, const EventEntry* entry,
3719 int32_t injectionResult, nsecs_t timeSpentWaitingForApplication) {
3720 // TODO Write some statistics about how long we spend waiting.
Jeff Brownb88102f2010-09-08 11:49:43 -07003721}
3722
Jeff Brown481c1572012-03-09 14:41:15 -08003723void InputDispatcher::traceInboundQueueLengthLocked() {
3724 if (ATRACE_ENABLED()) {
3725 ATRACE_INT("iq", mInboundQueue.count());
3726 }
3727}
3728
3729void InputDispatcher::traceOutboundQueueLengthLocked(const sp<Connection>& connection) {
3730 if (ATRACE_ENABLED()) {
3731 char counterName[40];
3732 snprintf(counterName, sizeof(counterName), "oq:%s", connection->getWindowName());
3733 ATRACE_INT(counterName, connection->outboundQueue.count());
3734 }
3735}
3736
3737void InputDispatcher::traceWaitQueueLengthLocked(const sp<Connection>& connection) {
3738 if (ATRACE_ENABLED()) {
3739 char counterName[40];
3740 snprintf(counterName, sizeof(counterName), "wq:%s", connection->getWindowName());
3741 ATRACE_INT(counterName, connection->waitQueue.count());
3742 }
3743}
3744
Jeff Brownb88102f2010-09-08 11:49:43 -07003745void InputDispatcher::dump(String8& dump) {
Jeff Brown89ef0722011-08-10 16:25:21 -07003746 AutoMutex _l(mLock);
3747
Jeff Brownf2f48712010-10-01 17:46:21 -07003748 dump.append("Input Dispatcher State:\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003749 dumpDispatchStateLocked(dump);
Jeff Brown214eaf42011-05-26 19:17:02 -07003750
Jeff Brown22aa5122012-06-17 12:01:06 -07003751 if (!mLastANRState.isEmpty()) {
3752 dump.append("\nInput Dispatcher State at time of last ANR:\n");
3753 dump.append(mLastANRState);
3754 }
Jeff Brownb88102f2010-09-08 11:49:43 -07003755}
3756
Jeff Brown89ef0722011-08-10 16:25:21 -07003757void InputDispatcher::monitor() {
3758 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
3759 mLock.lock();
Jeff Brown112b5f52012-01-27 17:32:06 -08003760 mLooper->wake();
3761 mDispatcherIsAliveCondition.wait(mLock);
Jeff Brown89ef0722011-08-10 16:25:21 -07003762 mLock.unlock();
3763}
3764
Jeff Brown9c3cda02010-06-15 01:31:58 -07003765
Jeff Brown519e0242010-09-15 15:18:56 -07003766// --- InputDispatcher::Queue ---
3767
3768template <typename T>
3769uint32_t InputDispatcher::Queue<T>::count() const {
3770 uint32_t result = 0;
Jeff Brownac386072011-07-20 15:19:50 -07003771 for (const T* entry = head; entry; entry = entry->next) {
Jeff Brown519e0242010-09-15 15:18:56 -07003772 result += 1;
3773 }
3774 return result;
3775}
3776
3777
Jeff Brownac386072011-07-20 15:19:50 -07003778// --- InputDispatcher::InjectionState ---
Jeff Brown46b9ac02010-04-22 18:58:52 -07003779
Jeff Brownac386072011-07-20 15:19:50 -07003780InputDispatcher::InjectionState::InjectionState(int32_t injectorPid, int32_t injectorUid) :
3781 refCount(1),
3782 injectorPid(injectorPid), injectorUid(injectorUid),
3783 injectionResult(INPUT_EVENT_INJECTION_PENDING), injectionIsAsync(false),
3784 pendingForegroundDispatches(0) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07003785}
3786
Jeff Brownac386072011-07-20 15:19:50 -07003787InputDispatcher::InjectionState::~InjectionState() {
Jeff Brown01ce2e92010-09-26 22:20:12 -07003788}
3789
Jeff Brownac386072011-07-20 15:19:50 -07003790void InputDispatcher::InjectionState::release() {
3791 refCount -= 1;
3792 if (refCount == 0) {
3793 delete this;
3794 } else {
Steve Blockec193de2012-01-09 18:35:44 +00003795 ALOG_ASSERT(refCount > 0);
Jeff Brown01ce2e92010-09-26 22:20:12 -07003796 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07003797}
3798
Jeff Brownac386072011-07-20 15:19:50 -07003799
3800// --- InputDispatcher::EventEntry ---
3801
3802InputDispatcher::EventEntry::EventEntry(int32_t type, nsecs_t eventTime, uint32_t policyFlags) :
3803 refCount(1), type(type), eventTime(eventTime), policyFlags(policyFlags),
3804 injectionState(NULL), dispatchInProgress(false) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07003805}
3806
Jeff Brownac386072011-07-20 15:19:50 -07003807InputDispatcher::EventEntry::~EventEntry() {
3808 releaseInjectionState();
3809}
3810
3811void InputDispatcher::EventEntry::release() {
3812 refCount -= 1;
3813 if (refCount == 0) {
3814 delete this;
3815 } else {
Steve Blockec193de2012-01-09 18:35:44 +00003816 ALOG_ASSERT(refCount > 0);
Jeff Brownac386072011-07-20 15:19:50 -07003817 }
3818}
3819
3820void InputDispatcher::EventEntry::releaseInjectionState() {
3821 if (injectionState) {
3822 injectionState->release();
3823 injectionState = NULL;
3824 }
3825}
3826
3827
3828// --- InputDispatcher::ConfigurationChangedEntry ---
3829
3830InputDispatcher::ConfigurationChangedEntry::ConfigurationChangedEntry(nsecs_t eventTime) :
3831 EventEntry(TYPE_CONFIGURATION_CHANGED, eventTime, 0) {
3832}
3833
3834InputDispatcher::ConfigurationChangedEntry::~ConfigurationChangedEntry() {
3835}
3836
Jeff Brown265f1cc2012-06-11 18:01:06 -07003837void InputDispatcher::ConfigurationChangedEntry::appendDescription(String8& msg) const {
Jeff Brown6876f322013-08-07 16:46:50 -07003838 msg.append("ConfigurationChangedEvent(), policyFlags=0x%08x",
3839 policyFlags);
Jeff Brown265f1cc2012-06-11 18:01:06 -07003840}
3841
Jeff Brownac386072011-07-20 15:19:50 -07003842
Jeff Brown65fd2512011-08-18 11:20:58 -07003843// --- InputDispatcher::DeviceResetEntry ---
3844
3845InputDispatcher::DeviceResetEntry::DeviceResetEntry(nsecs_t eventTime, int32_t deviceId) :
3846 EventEntry(TYPE_DEVICE_RESET, eventTime, 0),
3847 deviceId(deviceId) {
3848}
3849
3850InputDispatcher::DeviceResetEntry::~DeviceResetEntry() {
3851}
3852
Jeff Brown265f1cc2012-06-11 18:01:06 -07003853void InputDispatcher::DeviceResetEntry::appendDescription(String8& msg) const {
Jeff Brown6876f322013-08-07 16:46:50 -07003854 msg.appendFormat("DeviceResetEvent(deviceId=%d), policyFlags=0x%08x",
3855 deviceId, policyFlags);
Jeff Brown265f1cc2012-06-11 18:01:06 -07003856}
3857
Jeff Brown65fd2512011-08-18 11:20:58 -07003858
Jeff Brownac386072011-07-20 15:19:50 -07003859// --- InputDispatcher::KeyEntry ---
3860
3861InputDispatcher::KeyEntry::KeyEntry(nsecs_t eventTime,
Jeff Brown58a2da82011-01-25 16:02:22 -08003862 int32_t deviceId, uint32_t source, uint32_t policyFlags, int32_t action,
Jeff Brown7fbdc842010-06-17 20:52:56 -07003863 int32_t flags, int32_t keyCode, int32_t scanCode, int32_t metaState,
Jeff Brownac386072011-07-20 15:19:50 -07003864 int32_t repeatCount, nsecs_t downTime) :
3865 EventEntry(TYPE_KEY, eventTime, policyFlags),
3866 deviceId(deviceId), source(source), action(action), flags(flags),
3867 keyCode(keyCode), scanCode(scanCode), metaState(metaState),
3868 repeatCount(repeatCount), downTime(downTime),
Jeff Brown905805a2011-10-12 13:57:59 -07003869 syntheticRepeat(false), interceptKeyResult(KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN),
3870 interceptKeyWakeupTime(0) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07003871}
3872
Jeff Brownac386072011-07-20 15:19:50 -07003873InputDispatcher::KeyEntry::~KeyEntry() {
3874}
Jeff Brown7fbdc842010-06-17 20:52:56 -07003875
Jeff Brown265f1cc2012-06-11 18:01:06 -07003876void InputDispatcher::KeyEntry::appendDescription(String8& msg) const {
Jeff Brown6876f322013-08-07 16:46:50 -07003877 msg.appendFormat("KeyEvent(deviceId=%d, source=0x%08x, action=%d, "
3878 "flags=0x%08x, keyCode=%d, scanCode=%d, metaState=0x%08x, "
3879 "repeatCount=%d), policyFlags=0x%08x",
3880 deviceId, source, action, flags, keyCode, scanCode, metaState,
3881 repeatCount, policyFlags);
Jeff Brown265f1cc2012-06-11 18:01:06 -07003882}
3883
Jeff Brownac386072011-07-20 15:19:50 -07003884void InputDispatcher::KeyEntry::recycle() {
3885 releaseInjectionState();
3886
3887 dispatchInProgress = false;
3888 syntheticRepeat = false;
3889 interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
Jeff Brown905805a2011-10-12 13:57:59 -07003890 interceptKeyWakeupTime = 0;
Jeff Brownac386072011-07-20 15:19:50 -07003891}
3892
3893
Jeff Brownae9fc032010-08-18 15:51:08 -07003894// --- InputDispatcher::MotionEntry ---
3895
Jeff Brownac386072011-07-20 15:19:50 -07003896InputDispatcher::MotionEntry::MotionEntry(nsecs_t eventTime,
3897 int32_t deviceId, uint32_t source, uint32_t policyFlags, int32_t action, int32_t flags,
3898 int32_t metaState, int32_t buttonState,
3899 int32_t edgeFlags, float xPrecision, float yPrecision,
Jeff Brown83d616a2012-09-09 20:33:43 -07003900 nsecs_t downTime, int32_t displayId, uint32_t pointerCount,
Jeff Brown38f96e52014-02-11 14:32:56 -08003901 const PointerProperties* pointerProperties, const PointerCoords* pointerCoords,
3902 float xOffset, float yOffset) :
Jeff Brownac386072011-07-20 15:19:50 -07003903 EventEntry(TYPE_MOTION, eventTime, policyFlags),
Jeff Brown3241b6b2012-02-03 15:08:02 -08003904 eventTime(eventTime),
Jeff Brownac386072011-07-20 15:19:50 -07003905 deviceId(deviceId), source(source), action(action), flags(flags),
3906 metaState(metaState), buttonState(buttonState), edgeFlags(edgeFlags),
3907 xPrecision(xPrecision), yPrecision(yPrecision),
Jeff Brown83d616a2012-09-09 20:33:43 -07003908 downTime(downTime), displayId(displayId), pointerCount(pointerCount) {
Jeff Brownac386072011-07-20 15:19:50 -07003909 for (uint32_t i = 0; i < pointerCount; i++) {
3910 this->pointerProperties[i].copyFrom(pointerProperties[i]);
Jeff Brown3241b6b2012-02-03 15:08:02 -08003911 this->pointerCoords[i].copyFrom(pointerCoords[i]);
Jeff Brown38f96e52014-02-11 14:32:56 -08003912 if (xOffset || yOffset) {
3913 this->pointerCoords[i].applyOffset(xOffset, yOffset);
3914 }
Jeff Brownac386072011-07-20 15:19:50 -07003915 }
3916}
3917
3918InputDispatcher::MotionEntry::~MotionEntry() {
Jeff Brownac386072011-07-20 15:19:50 -07003919}
3920
Jeff Brown265f1cc2012-06-11 18:01:06 -07003921void InputDispatcher::MotionEntry::appendDescription(String8& msg) const {
Jeff Brown6876f322013-08-07 16:46:50 -07003922 msg.appendFormat("MotionEvent(deviceId=%d, source=0x%08x, action=%d, "
3923 "flags=0x%08x, metaState=0x%08x, buttonState=0x%08x, edgeFlags=0x%08x, "
3924 "xPrecision=%.1f, yPrecision=%.1f, displayId=%d, pointers=[",
3925 deviceId, source, action, flags, metaState, buttonState, edgeFlags,
3926 xPrecision, yPrecision, displayId);
3927 for (uint32_t i = 0; i < pointerCount; i++) {
3928 if (i) {
3929 msg.append(", ");
3930 }
3931 msg.appendFormat("%d: (%.1f, %.1f)", pointerProperties[i].id,
3932 pointerCoords[i].getX(), pointerCoords[i].getY());
3933 }
3934 msg.appendFormat("]), policyFlags=0x%08x", policyFlags);
Jeff Brown265f1cc2012-06-11 18:01:06 -07003935}
3936
Jeff Brownac386072011-07-20 15:19:50 -07003937
3938// --- InputDispatcher::DispatchEntry ---
3939
Jeff Brown072ec962012-02-07 14:46:57 -08003940volatile int32_t InputDispatcher::DispatchEntry::sNextSeqAtomic;
3941
Jeff Brownac386072011-07-20 15:19:50 -07003942InputDispatcher::DispatchEntry::DispatchEntry(EventEntry* eventEntry,
3943 int32_t targetFlags, float xOffset, float yOffset, float scaleFactor) :
Jeff Brown072ec962012-02-07 14:46:57 -08003944 seq(nextSeq()),
Jeff Brownac386072011-07-20 15:19:50 -07003945 eventEntry(eventEntry), targetFlags(targetFlags),
3946 xOffset(xOffset), yOffset(yOffset), scaleFactor(scaleFactor),
Jeff Brown265f1cc2012-06-11 18:01:06 -07003947 deliveryTime(0), resolvedAction(0), resolvedFlags(0) {
Jeff Brownac386072011-07-20 15:19:50 -07003948 eventEntry->refCount += 1;
3949}
3950
3951InputDispatcher::DispatchEntry::~DispatchEntry() {
3952 eventEntry->release();
3953}
3954
Jeff Brown072ec962012-02-07 14:46:57 -08003955uint32_t InputDispatcher::DispatchEntry::nextSeq() {
3956 // Sequence number 0 is reserved and will never be returned.
3957 uint32_t seq;
3958 do {
3959 seq = android_atomic_inc(&sNextSeqAtomic);
3960 } while (!seq);
3961 return seq;
3962}
3963
Jeff Brownb88102f2010-09-08 11:49:43 -07003964
3965// --- InputDispatcher::InputState ---
3966
Jeff Brownb6997262010-10-08 22:31:17 -07003967InputDispatcher::InputState::InputState() {
Jeff Brownb88102f2010-09-08 11:49:43 -07003968}
3969
3970InputDispatcher::InputState::~InputState() {
3971}
3972
3973bool InputDispatcher::InputState::isNeutral() const {
3974 return mKeyMementos.isEmpty() && mMotionMementos.isEmpty();
3975}
3976
Jeff Brown83d616a2012-09-09 20:33:43 -07003977bool InputDispatcher::InputState::isHovering(int32_t deviceId, uint32_t source,
3978 int32_t displayId) const {
Jeff Brown81346812011-06-28 20:08:48 -07003979 for (size_t i = 0; i < mMotionMementos.size(); i++) {
3980 const MotionMemento& memento = mMotionMementos.itemAt(i);
3981 if (memento.deviceId == deviceId
3982 && memento.source == source
Jeff Brown83d616a2012-09-09 20:33:43 -07003983 && memento.displayId == displayId
Jeff Brown81346812011-06-28 20:08:48 -07003984 && memento.hovering) {
3985 return true;
3986 }
3987 }
3988 return false;
3989}
Jeff Brownb88102f2010-09-08 11:49:43 -07003990
Jeff Brown81346812011-06-28 20:08:48 -07003991bool InputDispatcher::InputState::trackKey(const KeyEntry* entry,
3992 int32_t action, int32_t flags) {
3993 switch (action) {
3994 case AKEY_EVENT_ACTION_UP: {
3995 if (entry->flags & AKEY_EVENT_FLAG_FALLBACK) {
3996 for (size_t i = 0; i < mFallbackKeys.size(); ) {
3997 if (mFallbackKeys.valueAt(i) == entry->keyCode) {
3998 mFallbackKeys.removeItemsAt(i);
3999 } else {
4000 i += 1;
4001 }
4002 }
4003 }
4004 ssize_t index = findKeyMemento(entry);
4005 if (index >= 0) {
4006 mKeyMementos.removeAt(index);
4007 return true;
4008 }
Jeff Brown68b909d2011-12-07 16:36:01 -08004009 /* FIXME: We can't just drop the key up event because that prevents creating
4010 * popup windows that are automatically shown when a key is held and then
4011 * dismissed when the key is released. The problem is that the popup will
4012 * not have received the original key down, so the key up will be considered
4013 * to be inconsistent with its observed state. We could perhaps handle this
4014 * by synthesizing a key down but that will cause other problems.
4015 *
4016 * So for now, allow inconsistent key up events to be dispatched.
4017 *
Jeff Brown81346812011-06-28 20:08:48 -07004018#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00004019 ALOGD("Dropping inconsistent key up event: deviceId=%d, source=%08x, "
Jeff Brown81346812011-06-28 20:08:48 -07004020 "keyCode=%d, scanCode=%d",
4021 entry->deviceId, entry->source, entry->keyCode, entry->scanCode);
4022#endif
4023 return false;
Jeff Brown68b909d2011-12-07 16:36:01 -08004024 */
4025 return true;
Jeff Brown81346812011-06-28 20:08:48 -07004026 }
4027
4028 case AKEY_EVENT_ACTION_DOWN: {
4029 ssize_t index = findKeyMemento(entry);
4030 if (index >= 0) {
4031 mKeyMementos.removeAt(index);
4032 }
4033 addKeyMemento(entry, flags);
4034 return true;
4035 }
4036
4037 default:
4038 return true;
Jeff Brownb88102f2010-09-08 11:49:43 -07004039 }
4040}
4041
Jeff Brown81346812011-06-28 20:08:48 -07004042bool InputDispatcher::InputState::trackMotion(const MotionEntry* entry,
4043 int32_t action, int32_t flags) {
4044 int32_t actionMasked = action & AMOTION_EVENT_ACTION_MASK;
4045 switch (actionMasked) {
4046 case AMOTION_EVENT_ACTION_UP:
4047 case AMOTION_EVENT_ACTION_CANCEL: {
4048 ssize_t index = findMotionMemento(entry, false /*hovering*/);
4049 if (index >= 0) {
4050 mMotionMementos.removeAt(index);
4051 return true;
Jeff Brownda3d5a92011-03-29 15:11:34 -07004052 }
Jeff Brown81346812011-06-28 20:08:48 -07004053#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00004054 ALOGD("Dropping inconsistent motion up or cancel event: deviceId=%d, source=%08x, "
Jeff Brown81346812011-06-28 20:08:48 -07004055 "actionMasked=%d",
4056 entry->deviceId, entry->source, actionMasked);
4057#endif
4058 return false;
Jeff Brownda3d5a92011-03-29 15:11:34 -07004059 }
4060
Jeff Brown81346812011-06-28 20:08:48 -07004061 case AMOTION_EVENT_ACTION_DOWN: {
4062 ssize_t index = findMotionMemento(entry, false /*hovering*/);
4063 if (index >= 0) {
4064 mMotionMementos.removeAt(index);
4065 }
4066 addMotionMemento(entry, flags, false /*hovering*/);
4067 return true;
4068 }
4069
4070 case AMOTION_EVENT_ACTION_POINTER_UP:
4071 case AMOTION_EVENT_ACTION_POINTER_DOWN:
4072 case AMOTION_EVENT_ACTION_MOVE: {
Michael Wright1b108692014-03-19 11:51:26 -07004073 if (entry->source & AINPUT_SOURCE_CLASS_NAVIGATION) {
4074 // Trackballs can send MOVE events with a corresponding DOWN or UP. There's no need to
4075 // generate cancellation events for these since they're based in relative rather than
4076 // absolute units.
4077 return true;
4078 }
4079
Jeff Brown81346812011-06-28 20:08:48 -07004080 ssize_t index = findMotionMemento(entry, false /*hovering*/);
Michael Wright1b108692014-03-19 11:51:26 -07004081
4082 if (entry->source & AINPUT_SOURCE_CLASS_JOYSTICK) {
4083 // Joysticks can send MOVE events without a corresponding DOWN or UP. Since all
4084 // joystick axes are normalized to [-1, 1] we can trust that 0 means it's neutral. Any
4085 // other value and we need to track the motion so we can send cancellation events for
4086 // anything generating fallback events (e.g. DPad keys for joystick movements).
4087 if (index >= 0) {
4088 if (entry->pointerCoords[0].isEmpty()) {
4089 mMotionMementos.removeAt(index);
4090 } else {
4091 MotionMemento& memento = mMotionMementos.editItemAt(index);
4092 memento.setPointers(entry);
4093 }
4094 } else if (!entry->pointerCoords[0].isEmpty()) {
4095 addMotionMemento(entry, flags, false /*hovering*/);
4096 }
4097
4098 // Joysticks and trackballs can send MOVE events without corresponding DOWN or UP.
4099 return true;
4100 }
Jeff Brown81346812011-06-28 20:08:48 -07004101 if (index >= 0) {
4102 MotionMemento& memento = mMotionMementos.editItemAt(index);
4103 memento.setPointers(entry);
4104 return true;
4105 }
4106#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00004107 ALOGD("Dropping inconsistent motion pointer up/down or move event: "
Jeff Brown81346812011-06-28 20:08:48 -07004108 "deviceId=%d, source=%08x, actionMasked=%d",
4109 entry->deviceId, entry->source, actionMasked);
4110#endif
4111 return false;
4112 }
4113
4114 case AMOTION_EVENT_ACTION_HOVER_EXIT: {
4115 ssize_t index = findMotionMemento(entry, true /*hovering*/);
4116 if (index >= 0) {
4117 mMotionMementos.removeAt(index);
4118 return true;
4119 }
4120#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00004121 ALOGD("Dropping inconsistent motion hover exit event: deviceId=%d, source=%08x",
Jeff Brown81346812011-06-28 20:08:48 -07004122 entry->deviceId, entry->source);
4123#endif
4124 return false;
4125 }
4126
4127 case AMOTION_EVENT_ACTION_HOVER_ENTER:
4128 case AMOTION_EVENT_ACTION_HOVER_MOVE: {
4129 ssize_t index = findMotionMemento(entry, true /*hovering*/);
4130 if (index >= 0) {
4131 mMotionMementos.removeAt(index);
4132 }
4133 addMotionMemento(entry, flags, true /*hovering*/);
4134 return true;
4135 }
4136
4137 default:
4138 return true;
4139 }
4140}
4141
4142ssize_t InputDispatcher::InputState::findKeyMemento(const KeyEntry* entry) const {
Jeff Brownb88102f2010-09-08 11:49:43 -07004143 for (size_t i = 0; i < mKeyMementos.size(); i++) {
Jeff Brown81346812011-06-28 20:08:48 -07004144 const KeyMemento& memento = mKeyMementos.itemAt(i);
Jeff Brownb88102f2010-09-08 11:49:43 -07004145 if (memento.deviceId == entry->deviceId
4146 && memento.source == entry->source
4147 && memento.keyCode == entry->keyCode
4148 && memento.scanCode == entry->scanCode) {
Jeff Brown81346812011-06-28 20:08:48 -07004149 return i;
Jeff Brownb88102f2010-09-08 11:49:43 -07004150 }
4151 }
Jeff Brown81346812011-06-28 20:08:48 -07004152 return -1;
Jeff Brownb88102f2010-09-08 11:49:43 -07004153}
4154
Jeff Brown81346812011-06-28 20:08:48 -07004155ssize_t InputDispatcher::InputState::findMotionMemento(const MotionEntry* entry,
4156 bool hovering) const {
Jeff Brownb88102f2010-09-08 11:49:43 -07004157 for (size_t i = 0; i < mMotionMementos.size(); i++) {
Jeff Brown81346812011-06-28 20:08:48 -07004158 const MotionMemento& memento = mMotionMementos.itemAt(i);
Jeff Brownb88102f2010-09-08 11:49:43 -07004159 if (memento.deviceId == entry->deviceId
Jeff Brown81346812011-06-28 20:08:48 -07004160 && memento.source == entry->source
Jeff Brown83d616a2012-09-09 20:33:43 -07004161 && memento.displayId == entry->displayId
Jeff Brown81346812011-06-28 20:08:48 -07004162 && memento.hovering == hovering) {
4163 return i;
Jeff Brownb88102f2010-09-08 11:49:43 -07004164 }
4165 }
Jeff Brown81346812011-06-28 20:08:48 -07004166 return -1;
4167}
Jeff Brownb88102f2010-09-08 11:49:43 -07004168
Jeff Brown81346812011-06-28 20:08:48 -07004169void InputDispatcher::InputState::addKeyMemento(const KeyEntry* entry, int32_t flags) {
4170 mKeyMementos.push();
4171 KeyMemento& memento = mKeyMementos.editTop();
4172 memento.deviceId = entry->deviceId;
4173 memento.source = entry->source;
4174 memento.keyCode = entry->keyCode;
4175 memento.scanCode = entry->scanCode;
Jeff Brownfd23e3e2012-05-09 13:34:28 -07004176 memento.metaState = entry->metaState;
Jeff Brown81346812011-06-28 20:08:48 -07004177 memento.flags = flags;
4178 memento.downTime = entry->downTime;
Jeff Brownfd23e3e2012-05-09 13:34:28 -07004179 memento.policyFlags = entry->policyFlags;
Jeff Brown81346812011-06-28 20:08:48 -07004180}
4181
4182void InputDispatcher::InputState::addMotionMemento(const MotionEntry* entry,
4183 int32_t flags, bool hovering) {
4184 mMotionMementos.push();
4185 MotionMemento& memento = mMotionMementos.editTop();
4186 memento.deviceId = entry->deviceId;
4187 memento.source = entry->source;
4188 memento.flags = flags;
4189 memento.xPrecision = entry->xPrecision;
4190 memento.yPrecision = entry->yPrecision;
4191 memento.downTime = entry->downTime;
Jeff Brown83d616a2012-09-09 20:33:43 -07004192 memento.displayId = entry->displayId;
Jeff Brown81346812011-06-28 20:08:48 -07004193 memento.setPointers(entry);
4194 memento.hovering = hovering;
Jeff Brownfd23e3e2012-05-09 13:34:28 -07004195 memento.policyFlags = entry->policyFlags;
Jeff Brownb88102f2010-09-08 11:49:43 -07004196}
4197
4198void InputDispatcher::InputState::MotionMemento::setPointers(const MotionEntry* entry) {
4199 pointerCount = entry->pointerCount;
4200 for (uint32_t i = 0; i < entry->pointerCount; i++) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07004201 pointerProperties[i].copyFrom(entry->pointerProperties[i]);
Jeff Brown3241b6b2012-02-03 15:08:02 -08004202 pointerCoords[i].copyFrom(entry->pointerCoords[i]);
Jeff Brownb88102f2010-09-08 11:49:43 -07004203 }
4204}
4205
Jeff Brownb6997262010-10-08 22:31:17 -07004206void InputDispatcher::InputState::synthesizeCancelationEvents(nsecs_t currentTime,
Jeff Brownac386072011-07-20 15:19:50 -07004207 Vector<EventEntry*>& outEvents, const CancelationOptions& options) {
Jeff Brown81346812011-06-28 20:08:48 -07004208 for (size_t i = 0; i < mKeyMementos.size(); i++) {
Jeff Brownb88102f2010-09-08 11:49:43 -07004209 const KeyMemento& memento = mKeyMementos.itemAt(i);
Jeff Brown49ed71d2010-12-06 17:13:33 -08004210 if (shouldCancelKey(memento, options)) {
Jeff Brownac386072011-07-20 15:19:50 -07004211 outEvents.push(new KeyEntry(currentTime,
Jeff Brownfd23e3e2012-05-09 13:34:28 -07004212 memento.deviceId, memento.source, memento.policyFlags,
Jeff Brown49ed71d2010-12-06 17:13:33 -08004213 AKEY_EVENT_ACTION_UP, memento.flags | AKEY_EVENT_FLAG_CANCELED,
Jeff Brownfd23e3e2012-05-09 13:34:28 -07004214 memento.keyCode, memento.scanCode, memento.metaState, 0, memento.downTime));
Jeff Brownb6997262010-10-08 22:31:17 -07004215 }
Jeff Brownb88102f2010-09-08 11:49:43 -07004216 }
4217
Jeff Brown81346812011-06-28 20:08:48 -07004218 for (size_t i = 0; i < mMotionMementos.size(); i++) {
Jeff Brownb88102f2010-09-08 11:49:43 -07004219 const MotionMemento& memento = mMotionMementos.itemAt(i);
Jeff Brown49ed71d2010-12-06 17:13:33 -08004220 if (shouldCancelMotion(memento, options)) {
Jeff Brownac386072011-07-20 15:19:50 -07004221 outEvents.push(new MotionEntry(currentTime,
Jeff Brownfd23e3e2012-05-09 13:34:28 -07004222 memento.deviceId, memento.source, memento.policyFlags,
Jeff Browna032cc02011-03-07 16:56:21 -08004223 memento.hovering
4224 ? AMOTION_EVENT_ACTION_HOVER_EXIT
4225 : AMOTION_EVENT_ACTION_CANCEL,
Jeff Brown81346812011-06-28 20:08:48 -07004226 memento.flags, 0, 0, 0,
Jeff Brownb6997262010-10-08 22:31:17 -07004227 memento.xPrecision, memento.yPrecision, memento.downTime,
Jeff Brown83d616a2012-09-09 20:33:43 -07004228 memento.displayId,
Jeff Brown38f96e52014-02-11 14:32:56 -08004229 memento.pointerCount, memento.pointerProperties, memento.pointerCoords,
4230 0, 0));
Jeff Brownb6997262010-10-08 22:31:17 -07004231 }
Jeff Brownb88102f2010-09-08 11:49:43 -07004232 }
4233}
4234
4235void InputDispatcher::InputState::clear() {
4236 mKeyMementos.clear();
4237 mMotionMementos.clear();
Jeff Brownda3d5a92011-03-29 15:11:34 -07004238 mFallbackKeys.clear();
Jeff Brownb6997262010-10-08 22:31:17 -07004239}
4240
Jeff Brown9c9f1a32010-10-11 18:32:20 -07004241void InputDispatcher::InputState::copyPointerStateTo(InputState& other) const {
4242 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4243 const MotionMemento& memento = mMotionMementos.itemAt(i);
4244 if (memento.source & AINPUT_SOURCE_CLASS_POINTER) {
4245 for (size_t j = 0; j < other.mMotionMementos.size(); ) {
4246 const MotionMemento& otherMemento = other.mMotionMementos.itemAt(j);
4247 if (memento.deviceId == otherMemento.deviceId
Jeff Brown83d616a2012-09-09 20:33:43 -07004248 && memento.source == otherMemento.source
4249 && memento.displayId == otherMemento.displayId) {
Jeff Brown9c9f1a32010-10-11 18:32:20 -07004250 other.mMotionMementos.removeAt(j);
4251 } else {
4252 j += 1;
4253 }
4254 }
4255 other.mMotionMementos.push(memento);
4256 }
4257 }
4258}
4259
Jeff Brownda3d5a92011-03-29 15:11:34 -07004260int32_t InputDispatcher::InputState::getFallbackKey(int32_t originalKeyCode) {
4261 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
4262 return index >= 0 ? mFallbackKeys.valueAt(index) : -1;
4263}
4264
4265void InputDispatcher::InputState::setFallbackKey(int32_t originalKeyCode,
4266 int32_t fallbackKeyCode) {
4267 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
4268 if (index >= 0) {
4269 mFallbackKeys.replaceValueAt(index, fallbackKeyCode);
4270 } else {
4271 mFallbackKeys.add(originalKeyCode, fallbackKeyCode);
4272 }
4273}
4274
4275void InputDispatcher::InputState::removeFallbackKey(int32_t originalKeyCode) {
4276 mFallbackKeys.removeItem(originalKeyCode);
4277}
4278
Jeff Brown49ed71d2010-12-06 17:13:33 -08004279bool InputDispatcher::InputState::shouldCancelKey(const KeyMemento& memento,
Jeff Brownda3d5a92011-03-29 15:11:34 -07004280 const CancelationOptions& options) {
4281 if (options.keyCode != -1 && memento.keyCode != options.keyCode) {
4282 return false;
4283 }
4284
Jeff Brown65fd2512011-08-18 11:20:58 -07004285 if (options.deviceId != -1 && memento.deviceId != options.deviceId) {
4286 return false;
4287 }
4288
Jeff Brownda3d5a92011-03-29 15:11:34 -07004289 switch (options.mode) {
4290 case CancelationOptions::CANCEL_ALL_EVENTS:
4291 case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
Jeff Brownb6997262010-10-08 22:31:17 -07004292 return true;
Jeff Brownda3d5a92011-03-29 15:11:34 -07004293 case CancelationOptions::CANCEL_FALLBACK_EVENTS:
Jeff Brown49ed71d2010-12-06 17:13:33 -08004294 return memento.flags & AKEY_EVENT_FLAG_FALLBACK;
4295 default:
4296 return false;
4297 }
4298}
4299
4300bool InputDispatcher::InputState::shouldCancelMotion(const MotionMemento& memento,
Jeff Brownda3d5a92011-03-29 15:11:34 -07004301 const CancelationOptions& options) {
Jeff Brown65fd2512011-08-18 11:20:58 -07004302 if (options.deviceId != -1 && memento.deviceId != options.deviceId) {
4303 return false;
4304 }
4305
Jeff Brownda3d5a92011-03-29 15:11:34 -07004306 switch (options.mode) {
4307 case CancelationOptions::CANCEL_ALL_EVENTS:
Jeff Brown49ed71d2010-12-06 17:13:33 -08004308 return true;
Jeff Brownda3d5a92011-03-29 15:11:34 -07004309 case CancelationOptions::CANCEL_POINTER_EVENTS:
Jeff Brown49ed71d2010-12-06 17:13:33 -08004310 return memento.source & AINPUT_SOURCE_CLASS_POINTER;
Jeff Brownda3d5a92011-03-29 15:11:34 -07004311 case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
Jeff Brown49ed71d2010-12-06 17:13:33 -08004312 return !(memento.source & AINPUT_SOURCE_CLASS_POINTER);
4313 default:
4314 return false;
Jeff Brownb6997262010-10-08 22:31:17 -07004315 }
Jeff Brownb88102f2010-09-08 11:49:43 -07004316}
4317
4318
Jeff Brown46b9ac02010-04-22 18:58:52 -07004319// --- InputDispatcher::Connection ---
4320
Jeff Brown928e0542011-01-10 11:17:36 -08004321InputDispatcher::Connection::Connection(const sp<InputChannel>& inputChannel,
Jeff Browncc4f7db2011-08-30 20:34:48 -07004322 const sp<InputWindowHandle>& inputWindowHandle, bool monitor) :
Jeff Brown928e0542011-01-10 11:17:36 -08004323 status(STATUS_NORMAL), inputChannel(inputChannel), inputWindowHandle(inputWindowHandle),
Jeff Browncc4f7db2011-08-30 20:34:48 -07004324 monitor(monitor),
Jeff Brownd1c48a02012-02-06 19:12:47 -08004325 inputPublisher(inputChannel), inputPublisherBlocked(false) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07004326}
4327
4328InputDispatcher::Connection::~Connection() {
4329}
4330
Jeff Brown481c1572012-03-09 14:41:15 -08004331const char* InputDispatcher::Connection::getWindowName() const {
4332 if (inputWindowHandle != NULL) {
4333 return inputWindowHandle->getName().string();
4334 }
4335 if (monitor) {
4336 return "monitor";
4337 }
4338 return "?";
4339}
4340
Jeff Brown9c3cda02010-06-15 01:31:58 -07004341const char* InputDispatcher::Connection::getStatusLabel() const {
4342 switch (status) {
4343 case STATUS_NORMAL:
4344 return "NORMAL";
4345
4346 case STATUS_BROKEN:
4347 return "BROKEN";
4348
Jeff Brown9c3cda02010-06-15 01:31:58 -07004349 case STATUS_ZOMBIE:
4350 return "ZOMBIE";
4351
4352 default:
4353 return "UNKNOWN";
4354 }
4355}
4356
Jeff Brown072ec962012-02-07 14:46:57 -08004357InputDispatcher::DispatchEntry* InputDispatcher::Connection::findWaitQueueEntry(uint32_t seq) {
4358 for (DispatchEntry* entry = waitQueue.head; entry != NULL; entry = entry->next) {
4359 if (entry->seq == seq) {
4360 return entry;
4361 }
4362 }
4363 return NULL;
4364}
4365
Jeff Brownb88102f2010-09-08 11:49:43 -07004366
Jeff Brown9c3cda02010-06-15 01:31:58 -07004367// --- InputDispatcher::CommandEntry ---
4368
Jeff Brownac386072011-07-20 15:19:50 -07004369InputDispatcher::CommandEntry::CommandEntry(Command command) :
Jeff Brown072ec962012-02-07 14:46:57 -08004370 command(command), eventTime(0), keyEntry(NULL), userActivityEventType(0),
4371 seq(0), handled(false) {
Jeff Brown9c3cda02010-06-15 01:31:58 -07004372}
4373
4374InputDispatcher::CommandEntry::~CommandEntry() {
4375}
4376
Jeff Brown46b9ac02010-04-22 18:58:52 -07004377
Jeff Brown01ce2e92010-09-26 22:20:12 -07004378// --- InputDispatcher::TouchState ---
4379
4380InputDispatcher::TouchState::TouchState() :
Jeff Brown83d616a2012-09-09 20:33:43 -07004381 down(false), split(false), deviceId(-1), source(0), displayId(-1) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07004382}
4383
4384InputDispatcher::TouchState::~TouchState() {
4385}
4386
4387void InputDispatcher::TouchState::reset() {
4388 down = false;
4389 split = false;
Jeff Brown95712852011-01-04 19:41:59 -08004390 deviceId = -1;
Jeff Brown58a2da82011-01-25 16:02:22 -08004391 source = 0;
Jeff Brown83d616a2012-09-09 20:33:43 -07004392 displayId = -1;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004393 windows.clear();
4394}
4395
4396void InputDispatcher::TouchState::copyFrom(const TouchState& other) {
4397 down = other.down;
4398 split = other.split;
Jeff Brown95712852011-01-04 19:41:59 -08004399 deviceId = other.deviceId;
Jeff Brown58a2da82011-01-25 16:02:22 -08004400 source = other.source;
Jeff Brown83d616a2012-09-09 20:33:43 -07004401 displayId = other.displayId;
Jeff Brown9302c872011-07-13 22:51:29 -07004402 windows = other.windows;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004403}
4404
Jeff Brown9302c872011-07-13 22:51:29 -07004405void InputDispatcher::TouchState::addOrUpdateWindow(const sp<InputWindowHandle>& windowHandle,
Jeff Brown01ce2e92010-09-26 22:20:12 -07004406 int32_t targetFlags, BitSet32 pointerIds) {
4407 if (targetFlags & InputTarget::FLAG_SPLIT) {
4408 split = true;
4409 }
4410
4411 for (size_t i = 0; i < windows.size(); i++) {
4412 TouchedWindow& touchedWindow = windows.editItemAt(i);
Jeff Brown9302c872011-07-13 22:51:29 -07004413 if (touchedWindow.windowHandle == windowHandle) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07004414 touchedWindow.targetFlags |= targetFlags;
Jeff Brown98db5fa2011-06-08 15:37:10 -07004415 if (targetFlags & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
4416 touchedWindow.targetFlags &= ~InputTarget::FLAG_DISPATCH_AS_IS;
4417 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07004418 touchedWindow.pointerIds.value |= pointerIds.value;
4419 return;
4420 }
4421 }
4422
4423 windows.push();
4424
4425 TouchedWindow& touchedWindow = windows.editTop();
Jeff Brown9302c872011-07-13 22:51:29 -07004426 touchedWindow.windowHandle = windowHandle;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004427 touchedWindow.targetFlags = targetFlags;
4428 touchedWindow.pointerIds = pointerIds;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004429}
4430
Jeff Brownf44e3942012-04-20 11:33:27 -07004431void InputDispatcher::TouchState::removeWindow(const sp<InputWindowHandle>& windowHandle) {
4432 for (size_t i = 0; i < windows.size(); i++) {
4433 if (windows.itemAt(i).windowHandle == windowHandle) {
4434 windows.removeAt(i);
4435 return;
4436 }
4437 }
4438}
4439
Jeff Browna032cc02011-03-07 16:56:21 -08004440void InputDispatcher::TouchState::filterNonAsIsTouchWindows() {
Jeff Brown01ce2e92010-09-26 22:20:12 -07004441 for (size_t i = 0 ; i < windows.size(); ) {
Jeff Browna032cc02011-03-07 16:56:21 -08004442 TouchedWindow& window = windows.editItemAt(i);
Jeff Brown98db5fa2011-06-08 15:37:10 -07004443 if (window.targetFlags & (InputTarget::FLAG_DISPATCH_AS_IS
4444 | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER)) {
Jeff Browna032cc02011-03-07 16:56:21 -08004445 window.targetFlags &= ~InputTarget::FLAG_DISPATCH_MASK;
4446 window.targetFlags |= InputTarget::FLAG_DISPATCH_AS_IS;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004447 i += 1;
Jeff Browna032cc02011-03-07 16:56:21 -08004448 } else {
4449 windows.removeAt(i);
Jeff Brown01ce2e92010-09-26 22:20:12 -07004450 }
4451 }
4452}
4453
Jeff Brown9302c872011-07-13 22:51:29 -07004454sp<InputWindowHandle> InputDispatcher::TouchState::getFirstForegroundWindowHandle() const {
Jeff Brown01ce2e92010-09-26 22:20:12 -07004455 for (size_t i = 0; i < windows.size(); i++) {
Jeff Brown98db5fa2011-06-08 15:37:10 -07004456 const TouchedWindow& window = windows.itemAt(i);
4457 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
Jeff Brown9302c872011-07-13 22:51:29 -07004458 return window.windowHandle;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004459 }
4460 }
4461 return NULL;
4462}
4463
Jeff Brown98db5fa2011-06-08 15:37:10 -07004464bool InputDispatcher::TouchState::isSlippery() const {
4465 // Must have exactly one foreground window.
4466 bool haveSlipperyForegroundWindow = false;
4467 for (size_t i = 0; i < windows.size(); i++) {
4468 const TouchedWindow& window = windows.itemAt(i);
4469 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
Jeff Browncc4f7db2011-08-30 20:34:48 -07004470 if (haveSlipperyForegroundWindow
4471 || !(window.windowHandle->getInfo()->layoutParamsFlags
4472 & InputWindowInfo::FLAG_SLIPPERY)) {
Jeff Brown98db5fa2011-06-08 15:37:10 -07004473 return false;
4474 }
4475 haveSlipperyForegroundWindow = true;
4476 }
4477 }
4478 return haveSlipperyForegroundWindow;
4479}
4480
Jeff Brown01ce2e92010-09-26 22:20:12 -07004481
Jeff Brown46b9ac02010-04-22 18:58:52 -07004482// --- InputDispatcherThread ---
4483
4484InputDispatcherThread::InputDispatcherThread(const sp<InputDispatcherInterface>& dispatcher) :
4485 Thread(/*canCallJava*/ true), mDispatcher(dispatcher) {
4486}
4487
4488InputDispatcherThread::~InputDispatcherThread() {
4489}
4490
4491bool InputDispatcherThread::threadLoop() {
4492 mDispatcher->dispatchOnce();
4493 return true;
4494}
4495
4496} // namespace android