blob: eaa7fa854abc0a477566368889e65aa83ba3ae9b [file] [log] [blame]
Jeff Brownb4ff35d2011-01-02 16:37:43 -08001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070017#define LOG_TAG "InputDispatcher"
18
19//#define LOG_NDEBUG 0
20
21// Log detailed debug messages about each inbound event notification to the dispatcher.
Jeff Brown349703e2010-06-22 01:27:15 -070022#define DEBUG_INBOUND_EVENT_DETAILS 0
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070023
24// Log detailed debug messages about each outbound event processed by the dispatcher.
Jeff Brown349703e2010-06-22 01:27:15 -070025#define DEBUG_OUTBOUND_EVENT_DETAILS 0
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070026
27// Log debug messages about batching.
Jeff Brown349703e2010-06-22 01:27:15 -070028#define DEBUG_BATCHING 0
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070029
30// Log debug messages about the dispatch cycle.
Jeff Brown349703e2010-06-22 01:27:15 -070031#define DEBUG_DISPATCH_CYCLE 0
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070032
Jeff Brown9c3cda02010-06-15 01:31:58 -070033// Log debug messages about registrations.
Jeff Brown349703e2010-06-22 01:27:15 -070034#define DEBUG_REGISTRATION 0
Jeff Brown9c3cda02010-06-15 01:31:58 -070035
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070036// Log debug messages about performance statistics.
Jeff Brown349703e2010-06-22 01:27:15 -070037#define DEBUG_PERFORMANCE_STATISTICS 0
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070038
Jeff Brown7fbdc842010-06-17 20:52:56 -070039// Log debug messages about input event injection.
Jeff Brown349703e2010-06-22 01:27:15 -070040#define DEBUG_INJECTION 0
Jeff Brown7fbdc842010-06-17 20:52:56 -070041
Jeff Brownae9fc032010-08-18 15:51:08 -070042// Log debug messages about input event throttling.
43#define DEBUG_THROTTLING 0
44
Jeff Brownb88102f2010-09-08 11:49:43 -070045// Log debug messages about input focus tracking.
46#define DEBUG_FOCUS 0
47
48// Log debug messages about the app switch latency optimization.
49#define DEBUG_APP_SWITCH 0
50
Jeff Browna032cc02011-03-07 16:56:21 -080051// Log debug messages about hover events.
52#define DEBUG_HOVER 0
53
Jeff Brownb4ff35d2011-01-02 16:37:43 -080054#include "InputDispatcher.h"
55
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070056#include <cutils/log.h>
Jeff Brownb88102f2010-09-08 11:49:43 -070057#include <ui/PowerManager.h>
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070058
59#include <stddef.h>
60#include <unistd.h>
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070061#include <errno.h>
62#include <limits.h>
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070063
Jeff Brownf2f487182010-10-01 17:46:21 -070064#define INDENT " "
65#define INDENT2 " "
66
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070067namespace android {
68
Jeff Brownb88102f2010-09-08 11:49:43 -070069// Default input dispatching timeout if there is no focused application or paused window
70// from which to determine an appropriate dispatching timeout.
71const nsecs_t DEFAULT_INPUT_DISPATCHING_TIMEOUT = 5000 * 1000000LL; // 5 sec
72
73// Amount of time to allow for all pending events to be processed when an app switch
74// key is on the way. This is used to preempt input dispatch and drop input events
75// when an application takes too long to respond and the user has pressed an app switch key.
76const nsecs_t APP_SWITCH_TIMEOUT = 500 * 1000000LL; // 0.5sec
77
Jeff Brown928e0542011-01-10 11:17:36 -080078// Amount of time to allow for an event to be dispatched (measured since its eventTime)
79// before considering it stale and dropping it.
80const nsecs_t STALE_EVENT_TIMEOUT = 10000 * 1000000LL; // 10sec
81
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070082
Jeff Brown7fbdc842010-06-17 20:52:56 -070083static inline nsecs_t now() {
84 return systemTime(SYSTEM_TIME_MONOTONIC);
85}
86
Jeff Brownb88102f2010-09-08 11:49:43 -070087static inline const char* toString(bool value) {
88 return value ? "true" : "false";
89}
90
Jeff Brown01ce2e92010-09-26 22:20:12 -070091static inline int32_t getMotionEventActionPointerIndex(int32_t action) {
92 return (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK)
93 >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
94}
95
96static bool isValidKeyAction(int32_t action) {
97 switch (action) {
98 case AKEY_EVENT_ACTION_DOWN:
99 case AKEY_EVENT_ACTION_UP:
100 return true;
101 default:
102 return false;
103 }
104}
105
106static bool validateKeyEvent(int32_t action) {
107 if (! isValidKeyAction(action)) {
108 LOGE("Key event has invalid action code 0x%x", action);
109 return false;
110 }
111 return true;
112}
113
Jeff Brownb6997262010-10-08 22:31:17 -0700114static bool isValidMotionAction(int32_t action, size_t pointerCount) {
Jeff Brown01ce2e92010-09-26 22:20:12 -0700115 switch (action & AMOTION_EVENT_ACTION_MASK) {
116 case AMOTION_EVENT_ACTION_DOWN:
117 case AMOTION_EVENT_ACTION_UP:
118 case AMOTION_EVENT_ACTION_CANCEL:
119 case AMOTION_EVENT_ACTION_MOVE:
Jeff Brown01ce2e92010-09-26 22:20:12 -0700120 case AMOTION_EVENT_ACTION_OUTSIDE:
Jeff Browna032cc02011-03-07 16:56:21 -0800121 case AMOTION_EVENT_ACTION_HOVER_ENTER:
Jeff Browncc0c1592011-02-19 05:07:28 -0800122 case AMOTION_EVENT_ACTION_HOVER_MOVE:
Jeff Browna032cc02011-03-07 16:56:21 -0800123 case AMOTION_EVENT_ACTION_HOVER_EXIT:
Jeff Brown33bbfd22011-02-24 20:55:35 -0800124 case AMOTION_EVENT_ACTION_SCROLL:
Jeff Brown01ce2e92010-09-26 22:20:12 -0700125 return true;
Jeff Brownb6997262010-10-08 22:31:17 -0700126 case AMOTION_EVENT_ACTION_POINTER_DOWN:
127 case AMOTION_EVENT_ACTION_POINTER_UP: {
128 int32_t index = getMotionEventActionPointerIndex(action);
129 return index >= 0 && size_t(index) < pointerCount;
130 }
Jeff Brown01ce2e92010-09-26 22:20:12 -0700131 default:
132 return false;
133 }
134}
135
136static bool validateMotionEvent(int32_t action, size_t pointerCount,
137 const int32_t* pointerIds) {
Jeff Brownb6997262010-10-08 22:31:17 -0700138 if (! isValidMotionAction(action, pointerCount)) {
Jeff Brown01ce2e92010-09-26 22:20:12 -0700139 LOGE("Motion event has invalid action code 0x%x", action);
140 return false;
141 }
142 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
143 LOGE("Motion event has invalid pointer count %d; value must be between 1 and %d.",
144 pointerCount, MAX_POINTERS);
145 return false;
146 }
Jeff Brownc3db8582010-10-20 15:33:38 -0700147 BitSet32 pointerIdBits;
Jeff Brown01ce2e92010-09-26 22:20:12 -0700148 for (size_t i = 0; i < pointerCount; i++) {
Jeff Brownc3db8582010-10-20 15:33:38 -0700149 int32_t id = pointerIds[i];
150 if (id < 0 || id > MAX_POINTER_ID) {
Jeff Brown01ce2e92010-09-26 22:20:12 -0700151 LOGE("Motion event has invalid pointer id %d; value must be between 0 and %d",
Jeff Brownc3db8582010-10-20 15:33:38 -0700152 id, MAX_POINTER_ID);
Jeff Brown01ce2e92010-09-26 22:20:12 -0700153 return false;
154 }
Jeff Brownc3db8582010-10-20 15:33:38 -0700155 if (pointerIdBits.hasBit(id)) {
156 LOGE("Motion event has duplicate pointer id %d", id);
157 return false;
158 }
159 pointerIdBits.markBit(id);
Jeff Brown01ce2e92010-09-26 22:20:12 -0700160 }
161 return true;
162}
163
Jeff Brownfbf09772011-01-16 14:06:57 -0800164static void dumpRegion(String8& dump, const SkRegion& region) {
165 if (region.isEmpty()) {
166 dump.append("<empty>");
167 return;
168 }
169
170 bool first = true;
171 for (SkRegion::Iterator it(region); !it.done(); it.next()) {
172 if (first) {
173 first = false;
174 } else {
175 dump.append("|");
176 }
177 const SkIRect& rect = it.rect();
178 dump.appendFormat("[%d,%d][%d,%d]", rect.fLeft, rect.fTop, rect.fRight, rect.fBottom);
179 }
180}
181
Jeff Brownb88102f2010-09-08 11:49:43 -0700182
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700183// --- InputDispatcher ---
184
Jeff Brown9c3cda02010-06-15 01:31:58 -0700185InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy) :
Jeff Brownb88102f2010-09-08 11:49:43 -0700186 mPolicy(policy),
Jeff Brown928e0542011-01-10 11:17:36 -0800187 mPendingEvent(NULL), mAppSwitchSawKeyDown(false), mAppSwitchDueTime(LONG_LONG_MAX),
188 mNextUnblockedEvent(NULL),
Jeff Brownb88102f2010-09-08 11:49:43 -0700189 mDispatchEnabled(true), mDispatchFrozen(false),
Jeff Brown01ce2e92010-09-26 22:20:12 -0700190 mFocusedWindow(NULL),
Jeff Brownb88102f2010-09-08 11:49:43 -0700191 mFocusedApplication(NULL),
192 mCurrentInputTargetsValid(false),
Jeff Browna032cc02011-03-07 16:56:21 -0800193 mInputTargetWaitCause(INPUT_TARGET_WAIT_CAUSE_NONE),
194 mLastHoverWindow(NULL) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -0700195 mLooper = new Looper(false);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700196
Jeff Brownb88102f2010-09-08 11:49:43 -0700197 mInboundQueue.headSentinel.refCount = -1;
198 mInboundQueue.headSentinel.type = EventEntry::TYPE_SENTINEL;
199 mInboundQueue.headSentinel.eventTime = LONG_LONG_MIN;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700200
Jeff Brownb88102f2010-09-08 11:49:43 -0700201 mInboundQueue.tailSentinel.refCount = -1;
202 mInboundQueue.tailSentinel.type = EventEntry::TYPE_SENTINEL;
203 mInboundQueue.tailSentinel.eventTime = LONG_LONG_MAX;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700204
205 mKeyRepeatState.lastKeyEntry = NULL;
Jeff Brown9c3cda02010-06-15 01:31:58 -0700206
Jeff Brownae9fc032010-08-18 15:51:08 -0700207 int32_t maxEventsPerSecond = policy->getMaxEventsPerSecond();
208 mThrottleState.minTimeBetweenEvents = 1000000000LL / maxEventsPerSecond;
209 mThrottleState.lastDeviceId = -1;
210
211#if DEBUG_THROTTLING
212 mThrottleState.originalSampleCount = 0;
213 LOGD("Throttling - Max events per second = %d", maxEventsPerSecond);
214#endif
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700215}
216
217InputDispatcher::~InputDispatcher() {
Jeff Brownb88102f2010-09-08 11:49:43 -0700218 { // acquire lock
219 AutoMutex _l(mLock);
220
221 resetKeyRepeatLocked();
Jeff Brown54a18252010-09-16 14:07:33 -0700222 releasePendingEventLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -0700223 drainInboundQueueLocked();
224 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700225
226 while (mConnectionsByReceiveFd.size() != 0) {
227 unregisterInputChannel(mConnectionsByReceiveFd.valueAt(0)->inputChannel);
228 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700229}
230
231void InputDispatcher::dispatchOnce() {
Jeff Brown9c3cda02010-06-15 01:31:58 -0700232 nsecs_t keyRepeatTimeout = mPolicy->getKeyRepeatTimeout();
Jeff Brownb21fb102010-09-07 10:44:57 -0700233 nsecs_t keyRepeatDelay = mPolicy->getKeyRepeatDelay();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700234
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700235 nsecs_t nextWakeupTime = LONG_LONG_MAX;
236 { // acquire lock
237 AutoMutex _l(mLock);
Jeff Brownb88102f2010-09-08 11:49:43 -0700238 dispatchOnceInnerLocked(keyRepeatTimeout, keyRepeatDelay, & nextWakeupTime);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700239
Jeff Brownb88102f2010-09-08 11:49:43 -0700240 if (runCommandsLockedInterruptible()) {
241 nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700242 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700243 } // release lock
244
Jeff Brownb88102f2010-09-08 11:49:43 -0700245 // Wait for callback or timeout or wake. (make sure we round up, not down)
246 nsecs_t currentTime = now();
Jeff Brownaa3855d2011-03-17 01:34:19 -0700247 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
Jeff Brown4fe6c3e2010-09-13 23:17:30 -0700248 mLooper->pollOnce(timeoutMillis);
Jeff Brownb88102f2010-09-08 11:49:43 -0700249}
250
251void InputDispatcher::dispatchOnceInnerLocked(nsecs_t keyRepeatTimeout,
252 nsecs_t keyRepeatDelay, nsecs_t* nextWakeupTime) {
253 nsecs_t currentTime = now();
254
255 // Reset the key repeat timer whenever we disallow key events, even if the next event
256 // is not a key. This is to ensure that we abort a key repeat if the device is just coming
257 // out of sleep.
258 if (keyRepeatTimeout < 0) {
259 resetKeyRepeatLocked();
260 }
261
Jeff Brownb88102f2010-09-08 11:49:43 -0700262 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
263 if (mDispatchFrozen) {
264#if DEBUG_FOCUS
265 LOGD("Dispatch frozen. Waiting some more.");
266#endif
267 return;
268 }
269
270 // Optimize latency of app switches.
271 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
272 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
273 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
274 if (mAppSwitchDueTime < *nextWakeupTime) {
275 *nextWakeupTime = mAppSwitchDueTime;
276 }
277
Jeff Brownb88102f2010-09-08 11:49:43 -0700278 // Ready to start a new event.
279 // If we don't already have a pending event, go grab one.
280 if (! mPendingEvent) {
281 if (mInboundQueue.isEmpty()) {
282 if (isAppSwitchDue) {
283 // The inbound queue is empty so the app switch key we were waiting
284 // for will never arrive. Stop waiting for it.
285 resetPendingAppSwitchLocked(false);
286 isAppSwitchDue = false;
287 }
288
289 // Synthesize a key repeat if appropriate.
290 if (mKeyRepeatState.lastKeyEntry) {
291 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
292 mPendingEvent = synthesizeKeyRepeatLocked(currentTime, keyRepeatDelay);
293 } else {
294 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
295 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
296 }
297 }
298 }
299 if (! mPendingEvent) {
300 return;
301 }
302 } else {
303 // Inbound queue has at least one entry.
304 EventEntry* entry = mInboundQueue.headSentinel.next;
305
306 // Throttle the entry if it is a move event and there are no
307 // other events behind it in the queue. Due to movement batching, additional
308 // samples may be appended to this event by the time the throttling timeout
309 // expires.
310 // TODO Make this smarter and consider throttling per device independently.
Jeff Brownb6997262010-10-08 22:31:17 -0700311 if (entry->type == EventEntry::TYPE_MOTION
312 && !isAppSwitchDue
313 && mDispatchEnabled
314 && (entry->policyFlags & POLICY_FLAG_PASS_TO_USER)
315 && !entry->isInjected()) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700316 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
317 int32_t deviceId = motionEntry->deviceId;
318 uint32_t source = motionEntry->source;
319 if (! isAppSwitchDue
320 && motionEntry->next == & mInboundQueue.tailSentinel // exactly one event
Jeff Browncc0c1592011-02-19 05:07:28 -0800321 && (motionEntry->action == AMOTION_EVENT_ACTION_MOVE
322 || motionEntry->action == AMOTION_EVENT_ACTION_HOVER_MOVE)
Jeff Brownb88102f2010-09-08 11:49:43 -0700323 && deviceId == mThrottleState.lastDeviceId
324 && source == mThrottleState.lastSource) {
325 nsecs_t nextTime = mThrottleState.lastEventTime
326 + mThrottleState.minTimeBetweenEvents;
327 if (currentTime < nextTime) {
328 // Throttle it!
329#if DEBUG_THROTTLING
330 LOGD("Throttling - Delaying motion event for "
Jeff Brown90655042010-12-02 13:50:46 -0800331 "device %d, source 0x%08x by up to %0.3fms.",
Jeff Brownb88102f2010-09-08 11:49:43 -0700332 deviceId, source, (nextTime - currentTime) * 0.000001);
333#endif
334 if (nextTime < *nextWakeupTime) {
335 *nextWakeupTime = nextTime;
336 }
337 if (mThrottleState.originalSampleCount == 0) {
338 mThrottleState.originalSampleCount =
339 motionEntry->countSamples();
340 }
341 return;
342 }
343 }
344
345#if DEBUG_THROTTLING
346 if (mThrottleState.originalSampleCount != 0) {
347 uint32_t count = motionEntry->countSamples();
348 LOGD("Throttling - Motion event sample count grew by %d from %d to %d.",
349 count - mThrottleState.originalSampleCount,
350 mThrottleState.originalSampleCount, count);
351 mThrottleState.originalSampleCount = 0;
352 }
353#endif
354
makarand.karvekarf634ded2011-03-02 15:41:03 -0600355 mThrottleState.lastEventTime = currentTime;
Jeff Brownb88102f2010-09-08 11:49:43 -0700356 mThrottleState.lastDeviceId = deviceId;
357 mThrottleState.lastSource = source;
358 }
359
360 mInboundQueue.dequeue(entry);
361 mPendingEvent = entry;
362 }
Jeff Browne2fe69e2010-10-18 13:21:23 -0700363
364 // Poke user activity for this event.
365 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
366 pokeUserActivityLocked(mPendingEvent);
367 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700368 }
369
370 // Now we have an event to dispatch.
Jeff Brown928e0542011-01-10 11:17:36 -0800371 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Jeff Brownb88102f2010-09-08 11:49:43 -0700372 assert(mPendingEvent != NULL);
Jeff Brown54a18252010-09-16 14:07:33 -0700373 bool done = false;
Jeff Brownb6997262010-10-08 22:31:17 -0700374 DropReason dropReason = DROP_REASON_NOT_DROPPED;
375 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
376 dropReason = DROP_REASON_POLICY;
377 } else if (!mDispatchEnabled) {
378 dropReason = DROP_REASON_DISABLED;
379 }
Jeff Brown928e0542011-01-10 11:17:36 -0800380
381 if (mNextUnblockedEvent == mPendingEvent) {
382 mNextUnblockedEvent = NULL;
383 }
384
Jeff Brownb88102f2010-09-08 11:49:43 -0700385 switch (mPendingEvent->type) {
386 case EventEntry::TYPE_CONFIGURATION_CHANGED: {
387 ConfigurationChangedEntry* typedEntry =
388 static_cast<ConfigurationChangedEntry*>(mPendingEvent);
Jeff Brown54a18252010-09-16 14:07:33 -0700389 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Jeff Brownb6997262010-10-08 22:31:17 -0700390 dropReason = DROP_REASON_NOT_DROPPED; // configuration changes are never dropped
Jeff Brownb88102f2010-09-08 11:49:43 -0700391 break;
392 }
393
394 case EventEntry::TYPE_KEY: {
395 KeyEntry* typedEntry = static_cast<KeyEntry*>(mPendingEvent);
Jeff Brownb6997262010-10-08 22:31:17 -0700396 if (isAppSwitchDue) {
397 if (isAppSwitchKeyEventLocked(typedEntry)) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700398 resetPendingAppSwitchLocked(true);
Jeff Brownb6997262010-10-08 22:31:17 -0700399 isAppSwitchDue = false;
400 } else if (dropReason == DROP_REASON_NOT_DROPPED) {
401 dropReason = DROP_REASON_APP_SWITCH;
Jeff Brownb88102f2010-09-08 11:49:43 -0700402 }
403 }
Jeff Brown928e0542011-01-10 11:17:36 -0800404 if (dropReason == DROP_REASON_NOT_DROPPED
405 && isStaleEventLocked(currentTime, typedEntry)) {
406 dropReason = DROP_REASON_STALE;
407 }
408 if (dropReason == DROP_REASON_NOT_DROPPED && mNextUnblockedEvent) {
409 dropReason = DROP_REASON_BLOCKED;
410 }
Jeff Brownb6997262010-10-08 22:31:17 -0700411 done = dispatchKeyLocked(currentTime, typedEntry, keyRepeatTimeout,
Jeff Browne20c9e02010-10-11 14:20:19 -0700412 &dropReason, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700413 break;
414 }
415
416 case EventEntry::TYPE_MOTION: {
417 MotionEntry* typedEntry = static_cast<MotionEntry*>(mPendingEvent);
Jeff Brownb6997262010-10-08 22:31:17 -0700418 if (dropReason == DROP_REASON_NOT_DROPPED && isAppSwitchDue) {
419 dropReason = DROP_REASON_APP_SWITCH;
Jeff Brownb88102f2010-09-08 11:49:43 -0700420 }
Jeff Brown928e0542011-01-10 11:17:36 -0800421 if (dropReason == DROP_REASON_NOT_DROPPED
422 && isStaleEventLocked(currentTime, typedEntry)) {
423 dropReason = DROP_REASON_STALE;
424 }
425 if (dropReason == DROP_REASON_NOT_DROPPED && mNextUnblockedEvent) {
426 dropReason = DROP_REASON_BLOCKED;
427 }
Jeff Brownb6997262010-10-08 22:31:17 -0700428 done = dispatchMotionLocked(currentTime, typedEntry,
Jeff Browne20c9e02010-10-11 14:20:19 -0700429 &dropReason, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700430 break;
431 }
432
433 default:
434 assert(false);
Jeff Brownb88102f2010-09-08 11:49:43 -0700435 break;
436 }
437
Jeff Brown54a18252010-09-16 14:07:33 -0700438 if (done) {
Jeff Brownb6997262010-10-08 22:31:17 -0700439 if (dropReason != DROP_REASON_NOT_DROPPED) {
440 dropInboundEventLocked(mPendingEvent, dropReason);
441 }
442
Jeff Brown54a18252010-09-16 14:07:33 -0700443 releasePendingEventLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -0700444 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
445 }
446}
447
448bool InputDispatcher::enqueueInboundEventLocked(EventEntry* entry) {
449 bool needWake = mInboundQueue.isEmpty();
450 mInboundQueue.enqueueAtTail(entry);
451
452 switch (entry->type) {
Jeff Brownb6997262010-10-08 22:31:17 -0700453 case EventEntry::TYPE_KEY: {
Jeff Brown928e0542011-01-10 11:17:36 -0800454 // Optimize app switch latency.
455 // If the application takes too long to catch up then we drop all events preceding
456 // the app switch key.
Jeff Brownb6997262010-10-08 22:31:17 -0700457 KeyEntry* keyEntry = static_cast<KeyEntry*>(entry);
458 if (isAppSwitchKeyEventLocked(keyEntry)) {
459 if (keyEntry->action == AKEY_EVENT_ACTION_DOWN) {
460 mAppSwitchSawKeyDown = true;
461 } else if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
462 if (mAppSwitchSawKeyDown) {
463#if DEBUG_APP_SWITCH
464 LOGD("App switch is pending!");
465#endif
466 mAppSwitchDueTime = keyEntry->eventTime + APP_SWITCH_TIMEOUT;
467 mAppSwitchSawKeyDown = false;
468 needWake = true;
469 }
470 }
471 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700472 break;
473 }
Jeff Brown928e0542011-01-10 11:17:36 -0800474
475 case EventEntry::TYPE_MOTION: {
476 // Optimize case where the current application is unresponsive and the user
477 // decides to touch a window in a different application.
478 // If the application takes too long to catch up then we drop all events preceding
479 // the touch into the other window.
480 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
Jeff Brown33bbfd22011-02-24 20:55:35 -0800481 if (motionEntry->action == AMOTION_EVENT_ACTION_DOWN
Jeff Brown928e0542011-01-10 11:17:36 -0800482 && (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER)
483 && mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY
484 && mInputTargetWaitApplication != NULL) {
Jeff Brown91c69ab2011-02-14 17:03:18 -0800485 int32_t x = int32_t(motionEntry->firstSample.pointerCoords[0].
Jeff Brownebbd5d12011-02-17 13:01:34 -0800486 getAxisValue(AMOTION_EVENT_AXIS_X));
Jeff Brown91c69ab2011-02-14 17:03:18 -0800487 int32_t y = int32_t(motionEntry->firstSample.pointerCoords[0].
Jeff Brownebbd5d12011-02-17 13:01:34 -0800488 getAxisValue(AMOTION_EVENT_AXIS_Y));
Jeff Brown928e0542011-01-10 11:17:36 -0800489 const InputWindow* touchedWindow = findTouchedWindowAtLocked(x, y);
490 if (touchedWindow
491 && touchedWindow->inputWindowHandle != NULL
492 && touchedWindow->inputWindowHandle->getInputApplicationHandle()
493 != mInputTargetWaitApplication) {
494 // User touched a different application than the one we are waiting on.
495 // Flag the event, and start pruning the input queue.
496 mNextUnblockedEvent = motionEntry;
497 needWake = true;
498 }
499 }
500 break;
501 }
Jeff Brownb6997262010-10-08 22:31:17 -0700502 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700503
504 return needWake;
505}
506
Jeff Brown928e0542011-01-10 11:17:36 -0800507const InputWindow* InputDispatcher::findTouchedWindowAtLocked(int32_t x, int32_t y) {
508 // Traverse windows from front to back to find touched window.
509 size_t numWindows = mWindows.size();
510 for (size_t i = 0; i < numWindows; i++) {
511 const InputWindow* window = & mWindows.editItemAt(i);
512 int32_t flags = window->layoutParamsFlags;
513
514 if (window->visible) {
515 if (!(flags & InputWindow::FLAG_NOT_TOUCHABLE)) {
516 bool isTouchModal = (flags & (InputWindow::FLAG_NOT_FOCUSABLE
517 | InputWindow::FLAG_NOT_TOUCH_MODAL)) == 0;
Jeff Brownfbf09772011-01-16 14:06:57 -0800518 if (isTouchModal || window->touchableRegionContainsPoint(x, y)) {
Jeff Brown928e0542011-01-10 11:17:36 -0800519 // Found window.
520 return window;
521 }
522 }
523 }
524
525 if (flags & InputWindow::FLAG_SYSTEM_ERROR) {
526 // Error window is on top but not visible, so touch is dropped.
527 return NULL;
528 }
529 }
530 return NULL;
531}
532
Jeff Brownb6997262010-10-08 22:31:17 -0700533void InputDispatcher::dropInboundEventLocked(EventEntry* entry, DropReason dropReason) {
534 const char* reason;
535 switch (dropReason) {
536 case DROP_REASON_POLICY:
Jeff Browne20c9e02010-10-11 14:20:19 -0700537#if DEBUG_INBOUND_EVENT_DETAILS
Jeff Brown3122e442010-10-11 23:32:49 -0700538 LOGD("Dropped event because policy consumed it.");
Jeff Browne20c9e02010-10-11 14:20:19 -0700539#endif
Jeff Brown3122e442010-10-11 23:32:49 -0700540 reason = "inbound event was dropped because the policy consumed it";
Jeff Brownb6997262010-10-08 22:31:17 -0700541 break;
542 case DROP_REASON_DISABLED:
543 LOGI("Dropped event because input dispatch is disabled.");
544 reason = "inbound event was dropped because input dispatch is disabled";
545 break;
546 case DROP_REASON_APP_SWITCH:
547 LOGI("Dropped event because of pending overdue app switch.");
548 reason = "inbound event was dropped because of pending overdue app switch";
549 break;
Jeff Brown928e0542011-01-10 11:17:36 -0800550 case DROP_REASON_BLOCKED:
551 LOGI("Dropped event because the current application is not responding and the user "
552 "has started interating with a different application.");
553 reason = "inbound event was dropped because the current application is not responding "
554 "and the user has started interating with a different application";
555 break;
556 case DROP_REASON_STALE:
557 LOGI("Dropped event because it is stale.");
558 reason = "inbound event was dropped because it is stale";
559 break;
Jeff Brownb6997262010-10-08 22:31:17 -0700560 default:
561 assert(false);
562 return;
563 }
564
565 switch (entry->type) {
566 case EventEntry::TYPE_KEY:
567 synthesizeCancelationEventsForAllConnectionsLocked(
568 InputState::CANCEL_NON_POINTER_EVENTS, reason);
569 break;
570 case EventEntry::TYPE_MOTION: {
571 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
572 if (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) {
573 synthesizeCancelationEventsForAllConnectionsLocked(
574 InputState::CANCEL_POINTER_EVENTS, reason);
575 } else {
576 synthesizeCancelationEventsForAllConnectionsLocked(
577 InputState::CANCEL_NON_POINTER_EVENTS, reason);
578 }
579 break;
580 }
581 }
582}
583
584bool InputDispatcher::isAppSwitchKeyCode(int32_t keyCode) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700585 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL;
586}
587
Jeff Brownb6997262010-10-08 22:31:17 -0700588bool InputDispatcher::isAppSwitchKeyEventLocked(KeyEntry* keyEntry) {
589 return ! (keyEntry->flags & AKEY_EVENT_FLAG_CANCELED)
590 && isAppSwitchKeyCode(keyEntry->keyCode)
Jeff Browne20c9e02010-10-11 14:20:19 -0700591 && (keyEntry->policyFlags & POLICY_FLAG_TRUSTED)
Jeff Brownb6997262010-10-08 22:31:17 -0700592 && (keyEntry->policyFlags & POLICY_FLAG_PASS_TO_USER);
593}
594
Jeff Brownb88102f2010-09-08 11:49:43 -0700595bool InputDispatcher::isAppSwitchPendingLocked() {
596 return mAppSwitchDueTime != LONG_LONG_MAX;
597}
598
Jeff Brownb88102f2010-09-08 11:49:43 -0700599void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
600 mAppSwitchDueTime = LONG_LONG_MAX;
601
602#if DEBUG_APP_SWITCH
603 if (handled) {
604 LOGD("App switch has arrived.");
605 } else {
606 LOGD("App switch was abandoned.");
607 }
608#endif
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700609}
610
Jeff Brown928e0542011-01-10 11:17:36 -0800611bool InputDispatcher::isStaleEventLocked(nsecs_t currentTime, EventEntry* entry) {
612 return currentTime - entry->eventTime >= STALE_EVENT_TIMEOUT;
613}
614
Jeff Brown9c3cda02010-06-15 01:31:58 -0700615bool InputDispatcher::runCommandsLockedInterruptible() {
616 if (mCommandQueue.isEmpty()) {
617 return false;
618 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700619
Jeff Brown9c3cda02010-06-15 01:31:58 -0700620 do {
621 CommandEntry* commandEntry = mCommandQueue.dequeueAtHead();
622
623 Command command = commandEntry->command;
624 (this->*command)(commandEntry); // commands are implicitly 'LockedInterruptible'
625
Jeff Brown7fbdc842010-06-17 20:52:56 -0700626 commandEntry->connection.clear();
Jeff Brown9c3cda02010-06-15 01:31:58 -0700627 mAllocator.releaseCommandEntry(commandEntry);
628 } while (! mCommandQueue.isEmpty());
629 return true;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700630}
631
Jeff Brown9c3cda02010-06-15 01:31:58 -0700632InputDispatcher::CommandEntry* InputDispatcher::postCommandLocked(Command command) {
633 CommandEntry* commandEntry = mAllocator.obtainCommandEntry(command);
634 mCommandQueue.enqueueAtTail(commandEntry);
635 return commandEntry;
636}
637
Jeff Brownb88102f2010-09-08 11:49:43 -0700638void InputDispatcher::drainInboundQueueLocked() {
639 while (! mInboundQueue.isEmpty()) {
640 EventEntry* entry = mInboundQueue.dequeueAtHead();
Jeff Brown54a18252010-09-16 14:07:33 -0700641 releaseInboundEventLocked(entry);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700642 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700643}
644
Jeff Brown54a18252010-09-16 14:07:33 -0700645void InputDispatcher::releasePendingEventLocked() {
Jeff Brownb88102f2010-09-08 11:49:43 -0700646 if (mPendingEvent) {
Jeff Brown54a18252010-09-16 14:07:33 -0700647 releaseInboundEventLocked(mPendingEvent);
Jeff Brownb88102f2010-09-08 11:49:43 -0700648 mPendingEvent = NULL;
649 }
650}
651
Jeff Brown54a18252010-09-16 14:07:33 -0700652void InputDispatcher::releaseInboundEventLocked(EventEntry* entry) {
Jeff Brown01ce2e92010-09-26 22:20:12 -0700653 InjectionState* injectionState = entry->injectionState;
654 if (injectionState && injectionState->injectionResult == INPUT_EVENT_INJECTION_PENDING) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700655#if DEBUG_DISPATCH_CYCLE
Jeff Brown01ce2e92010-09-26 22:20:12 -0700656 LOGD("Injected inbound event was dropped.");
Jeff Brownb88102f2010-09-08 11:49:43 -0700657#endif
658 setInjectionResultLocked(entry, INPUT_EVENT_INJECTION_FAILED);
659 }
660 mAllocator.releaseEventEntry(entry);
661}
662
Jeff Brownb88102f2010-09-08 11:49:43 -0700663void InputDispatcher::resetKeyRepeatLocked() {
664 if (mKeyRepeatState.lastKeyEntry) {
665 mAllocator.releaseKeyEntry(mKeyRepeatState.lastKeyEntry);
666 mKeyRepeatState.lastKeyEntry = NULL;
667 }
668}
669
670InputDispatcher::KeyEntry* InputDispatcher::synthesizeKeyRepeatLocked(
Jeff Brownb21fb102010-09-07 10:44:57 -0700671 nsecs_t currentTime, nsecs_t keyRepeatDelay) {
Jeff Brown349703e2010-06-22 01:27:15 -0700672 KeyEntry* entry = mKeyRepeatState.lastKeyEntry;
673
Jeff Brown349703e2010-06-22 01:27:15 -0700674 // Reuse the repeated key entry if it is otherwise unreferenced.
Jeff Browne20c9e02010-10-11 14:20:19 -0700675 uint32_t policyFlags = (entry->policyFlags & POLICY_FLAG_RAW_MASK)
676 | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700677 if (entry->refCount == 1) {
Jeff Brown01ce2e92010-09-26 22:20:12 -0700678 mAllocator.recycleKeyEntry(entry);
Jeff Brown7fbdc842010-06-17 20:52:56 -0700679 entry->eventTime = currentTime;
Jeff Brown7fbdc842010-06-17 20:52:56 -0700680 entry->policyFlags = policyFlags;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700681 entry->repeatCount += 1;
682 } else {
Jeff Brown7fbdc842010-06-17 20:52:56 -0700683 KeyEntry* newEntry = mAllocator.obtainKeyEntry(currentTime,
Jeff Brownc5ed5912010-07-14 18:48:53 -0700684 entry->deviceId, entry->source, policyFlags,
Jeff Brown7fbdc842010-06-17 20:52:56 -0700685 entry->action, entry->flags, entry->keyCode, entry->scanCode,
Jeff Brown00fa7bd2010-07-02 15:37:36 -0700686 entry->metaState, entry->repeatCount + 1, entry->downTime);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700687
688 mKeyRepeatState.lastKeyEntry = newEntry;
689 mAllocator.releaseKeyEntry(entry);
690
691 entry = newEntry;
692 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700693 entry->syntheticRepeat = true;
694
695 // Increment reference count since we keep a reference to the event in
696 // mKeyRepeatState.lastKeyEntry in addition to the one we return.
697 entry->refCount += 1;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700698
Jeff Brownb21fb102010-09-07 10:44:57 -0700699 mKeyRepeatState.nextRepeatTime = currentTime + keyRepeatDelay;
Jeff Brownb88102f2010-09-08 11:49:43 -0700700 return entry;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700701}
702
Jeff Brownb88102f2010-09-08 11:49:43 -0700703bool InputDispatcher::dispatchConfigurationChangedLocked(
704 nsecs_t currentTime, ConfigurationChangedEntry* entry) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700705#if DEBUG_OUTBOUND_EVENT_DETAILS
Jeff Brownb88102f2010-09-08 11:49:43 -0700706 LOGD("dispatchConfigurationChanged - eventTime=%lld", entry->eventTime);
707#endif
708
709 // Reset key repeating in case a keyboard device was added or removed or something.
710 resetKeyRepeatLocked();
711
712 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
713 CommandEntry* commandEntry = postCommandLocked(
714 & InputDispatcher::doNotifyConfigurationChangedInterruptible);
715 commandEntry->eventTime = entry->eventTime;
716 return true;
717}
718
719bool InputDispatcher::dispatchKeyLocked(
720 nsecs_t currentTime, KeyEntry* entry, nsecs_t keyRepeatTimeout,
Jeff Browne20c9e02010-10-11 14:20:19 -0700721 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Jeff Browne46a0a42010-11-02 17:58:22 -0700722 // Preprocessing.
723 if (! entry->dispatchInProgress) {
724 if (entry->repeatCount == 0
725 && entry->action == AKEY_EVENT_ACTION_DOWN
726 && (entry->policyFlags & POLICY_FLAG_TRUSTED)
727 && !entry->isInjected()) {
728 if (mKeyRepeatState.lastKeyEntry
729 && mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode) {
730 // We have seen two identical key downs in a row which indicates that the device
731 // driver is automatically generating key repeats itself. We take note of the
732 // repeat here, but we disable our own next key repeat timer since it is clear that
733 // we will not need to synthesize key repeats ourselves.
734 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
735 resetKeyRepeatLocked();
736 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
737 } else {
738 // Not a repeat. Save key down state in case we do see a repeat later.
739 resetKeyRepeatLocked();
740 mKeyRepeatState.nextRepeatTime = entry->eventTime + keyRepeatTimeout;
741 }
742 mKeyRepeatState.lastKeyEntry = entry;
743 entry->refCount += 1;
744 } else if (! entry->syntheticRepeat) {
745 resetKeyRepeatLocked();
746 }
747
Jeff Browne2e01262011-03-02 20:34:30 -0800748 if (entry->repeatCount == 1) {
749 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
750 } else {
751 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
752 }
753
Jeff Browne46a0a42010-11-02 17:58:22 -0700754 entry->dispatchInProgress = true;
755 resetTargetsLocked();
756
757 logOutboundKeyDetailsLocked("dispatchKey - ", entry);
758 }
759
Jeff Brown54a18252010-09-16 14:07:33 -0700760 // Give the policy a chance to intercept the key.
761 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
Jeff Browne20c9e02010-10-11 14:20:19 -0700762 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Jeff Brown54a18252010-09-16 14:07:33 -0700763 CommandEntry* commandEntry = postCommandLocked(
764 & InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
Jeff Browne20c9e02010-10-11 14:20:19 -0700765 if (mFocusedWindow) {
Jeff Brown928e0542011-01-10 11:17:36 -0800766 commandEntry->inputWindowHandle = mFocusedWindow->inputWindowHandle;
Jeff Brown54a18252010-09-16 14:07:33 -0700767 }
768 commandEntry->keyEntry = entry;
769 entry->refCount += 1;
770 return false; // wait for the command to run
771 } else {
772 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
773 }
774 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Jeff Browne20c9e02010-10-11 14:20:19 -0700775 if (*dropReason == DROP_REASON_NOT_DROPPED) {
776 *dropReason = DROP_REASON_POLICY;
777 }
Jeff Brown54a18252010-09-16 14:07:33 -0700778 }
779
780 // Clean up if dropping the event.
Jeff Browne20c9e02010-10-11 14:20:19 -0700781 if (*dropReason != DROP_REASON_NOT_DROPPED) {
Jeff Brown54a18252010-09-16 14:07:33 -0700782 resetTargetsLocked();
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.
789 if (! mCurrentInputTargetsValid) {
Jeff Brown01ce2e92010-09-26 22:20:12 -0700790 int32_t injectionResult = findFocusedWindowTargetsLocked(currentTime,
791 entry, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700792 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
793 return false;
794 }
795
796 setInjectionResultLocked(entry, injectionResult);
797 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
798 return true;
799 }
800
801 addMonitoringTargetsLocked();
Jeff Brown01ce2e92010-09-26 22:20:12 -0700802 commitTargetsLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -0700803 }
804
805 // Dispatch the key.
806 dispatchEventToCurrentInputTargetsLocked(currentTime, entry, false);
Jeff Brownb88102f2010-09-08 11:49:43 -0700807 return true;
808}
809
810void InputDispatcher::logOutboundKeyDetailsLocked(const char* prefix, const KeyEntry* entry) {
811#if DEBUG_OUTBOUND_EVENT_DETAILS
Jeff Brown90655042010-12-02 13:50:46 -0800812 LOGD("%seventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, "
Jeff Brownb88102f2010-09-08 11:49:43 -0700813 "action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, "
Jeff Browne46a0a42010-11-02 17:58:22 -0700814 "repeatCount=%d, downTime=%lld",
Jeff Brownb88102f2010-09-08 11:49:43 -0700815 prefix,
816 entry->eventTime, entry->deviceId, entry->source, entry->policyFlags,
817 entry->action, entry->flags, entry->keyCode, entry->scanCode, entry->metaState,
Jeff Browne46a0a42010-11-02 17:58:22 -0700818 entry->repeatCount, entry->downTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700819#endif
820}
821
822bool InputDispatcher::dispatchMotionLocked(
Jeff Browne20c9e02010-10-11 14:20:19 -0700823 nsecs_t currentTime, MotionEntry* entry, DropReason* dropReason, nsecs_t* nextWakeupTime) {
Jeff Browne46a0a42010-11-02 17:58:22 -0700824 // Preprocessing.
825 if (! entry->dispatchInProgress) {
826 entry->dispatchInProgress = true;
827 resetTargetsLocked();
828
829 logOutboundMotionDetailsLocked("dispatchMotion - ", entry);
830 }
831
Jeff Brown54a18252010-09-16 14:07:33 -0700832 // Clean up if dropping the event.
Jeff Browne20c9e02010-10-11 14:20:19 -0700833 if (*dropReason != DROP_REASON_NOT_DROPPED) {
Jeff Brown54a18252010-09-16 14:07:33 -0700834 resetTargetsLocked();
Jeff Brown3122e442010-10-11 23:32:49 -0700835 setInjectionResultLocked(entry, *dropReason == DROP_REASON_POLICY
836 ? INPUT_EVENT_INJECTION_SUCCEEDED : INPUT_EVENT_INJECTION_FAILED);
Jeff Brown54a18252010-09-16 14:07:33 -0700837 return true;
838 }
839
Jeff Brownb88102f2010-09-08 11:49:43 -0700840 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
841
842 // Identify targets.
Jeff Browncc0c1592011-02-19 05:07:28 -0800843 bool conflictingPointerActions = false;
Jeff Brownb88102f2010-09-08 11:49:43 -0700844 if (! mCurrentInputTargetsValid) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700845 int32_t injectionResult;
Jeff Browna032cc02011-03-07 16:56:21 -0800846 const MotionSample* splitBatchAfterSample = NULL;
Jeff Brownb88102f2010-09-08 11:49:43 -0700847 if (isPointerEvent) {
848 // Pointer event. (eg. touchscreen)
Jeff Brown01ce2e92010-09-26 22:20:12 -0700849 injectionResult = findTouchedWindowTargetsLocked(currentTime,
Jeff Browna032cc02011-03-07 16:56:21 -0800850 entry, nextWakeupTime, &conflictingPointerActions, &splitBatchAfterSample);
Jeff Brownb88102f2010-09-08 11:49:43 -0700851 } else {
852 // Non touch event. (eg. trackball)
Jeff Brown01ce2e92010-09-26 22:20:12 -0700853 injectionResult = findFocusedWindowTargetsLocked(currentTime,
854 entry, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700855 }
856 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
857 return false;
858 }
859
860 setInjectionResultLocked(entry, injectionResult);
861 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
862 return true;
863 }
864
865 addMonitoringTargetsLocked();
Jeff Brown01ce2e92010-09-26 22:20:12 -0700866 commitTargetsLocked();
Jeff Browna032cc02011-03-07 16:56:21 -0800867
868 // Unbatch the event if necessary by splitting it into two parts after the
869 // motion sample indicated by splitBatchAfterSample.
870 if (splitBatchAfterSample && splitBatchAfterSample->next) {
871#if DEBUG_BATCHING
872 uint32_t originalSampleCount = entry->countSamples();
873#endif
874 MotionSample* nextSample = splitBatchAfterSample->next;
875 MotionEntry* nextEntry = mAllocator.obtainMotionEntry(nextSample->eventTime,
876 entry->deviceId, entry->source, entry->policyFlags,
877 entry->action, entry->flags, entry->metaState, entry->edgeFlags,
878 entry->xPrecision, entry->yPrecision, entry->downTime,
879 entry->pointerCount, entry->pointerIds, nextSample->pointerCoords);
880 if (nextSample != entry->lastSample) {
881 nextEntry->firstSample.next = nextSample->next;
882 nextEntry->lastSample = entry->lastSample;
883 }
884 mAllocator.freeMotionSample(nextSample);
885
886 entry->lastSample = const_cast<MotionSample*>(splitBatchAfterSample);
887 entry->lastSample->next = NULL;
888
889 if (entry->injectionState) {
890 nextEntry->injectionState = entry->injectionState;
891 entry->injectionState->refCount += 1;
892 }
893
894#if DEBUG_BATCHING
895 LOGD("Split batch of %d samples into two parts, first part has %d samples, "
896 "second part has %d samples.", originalSampleCount,
897 entry->countSamples(), nextEntry->countSamples());
898#endif
899
900 mInboundQueue.enqueueAtHead(nextEntry);
901 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700902 }
903
904 // Dispatch the motion.
Jeff Browncc0c1592011-02-19 05:07:28 -0800905 if (conflictingPointerActions) {
906 synthesizeCancelationEventsForAllConnectionsLocked(
907 InputState::CANCEL_POINTER_EVENTS, "Conflicting pointer actions.");
908 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700909 dispatchEventToCurrentInputTargetsLocked(currentTime, entry, false);
Jeff Brownb88102f2010-09-08 11:49:43 -0700910 return true;
911}
912
913
914void InputDispatcher::logOutboundMotionDetailsLocked(const char* prefix, const MotionEntry* entry) {
915#if DEBUG_OUTBOUND_EVENT_DETAILS
Jeff Brown90655042010-12-02 13:50:46 -0800916 LOGD("%seventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, "
Jeff Brown85a31762010-09-01 17:01:00 -0700917 "action=0x%x, flags=0x%x, "
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700918 "metaState=0x%x, edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%lld",
Jeff Brownb88102f2010-09-08 11:49:43 -0700919 prefix,
Jeff Brown85a31762010-09-01 17:01:00 -0700920 entry->eventTime, entry->deviceId, entry->source, entry->policyFlags,
921 entry->action, entry->flags,
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700922 entry->metaState, entry->edgeFlags, entry->xPrecision, entry->yPrecision,
923 entry->downTime);
924
925 // Print the most recent sample that we have available, this may change due to batching.
926 size_t sampleCount = 1;
Jeff Brownb88102f2010-09-08 11:49:43 -0700927 const MotionSample* sample = & entry->firstSample;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700928 for (; sample->next != NULL; sample = sample->next) {
929 sampleCount += 1;
930 }
931 for (uint32_t i = 0; i < entry->pointerCount; i++) {
Jeff Brown8d608662010-08-30 03:02:23 -0700932 LOGD(" Pointer %d: id=%d, x=%f, y=%f, pressure=%f, size=%f, "
Jeff Brown85a31762010-09-01 17:01:00 -0700933 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
Jeff Brown8d608662010-08-30 03:02:23 -0700934 "orientation=%f",
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700935 i, entry->pointerIds[i],
Jeff Brownebbd5d12011-02-17 13:01:34 -0800936 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
937 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
938 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
939 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
940 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
941 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
942 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
943 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
944 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700945 }
946
947 // Keep in mind that due to batching, it is possible for the number of samples actually
948 // dispatched to change before the application finally consumed them.
Jeff Brownc5ed5912010-07-14 18:48:53 -0700949 if (entry->action == AMOTION_EVENT_ACTION_MOVE) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700950 LOGD(" ... Total movement samples currently batched %d ...", sampleCount);
951 }
952#endif
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700953}
954
955void InputDispatcher::dispatchEventToCurrentInputTargetsLocked(nsecs_t currentTime,
956 EventEntry* eventEntry, bool resumeWithAppendedMotionSample) {
957#if DEBUG_DISPATCH_CYCLE
Jeff Brown9c3cda02010-06-15 01:31:58 -0700958 LOGD("dispatchEventToCurrentInputTargets - "
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700959 "resumeWithAppendedMotionSample=%s",
Jeff Brownb88102f2010-09-08 11:49:43 -0700960 toString(resumeWithAppendedMotionSample));
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700961#endif
962
Jeff Brown9c3cda02010-06-15 01:31:58 -0700963 assert(eventEntry->dispatchInProgress); // should already have been set to true
964
Jeff Browne2fe69e2010-10-18 13:21:23 -0700965 pokeUserActivityLocked(eventEntry);
966
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700967 for (size_t i = 0; i < mCurrentInputTargets.size(); i++) {
968 const InputTarget& inputTarget = mCurrentInputTargets.itemAt(i);
969
Jeff Brown519e0242010-09-15 15:18:56 -0700970 ssize_t connectionIndex = getConnectionIndexLocked(inputTarget.inputChannel);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700971 if (connectionIndex >= 0) {
972 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
Jeff Brown7fbdc842010-06-17 20:52:56 -0700973 prepareDispatchCycleLocked(currentTime, connection, eventEntry, & inputTarget,
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700974 resumeWithAppendedMotionSample);
975 } else {
Jeff Brownb6997262010-10-08 22:31:17 -0700976#if DEBUG_FOCUS
977 LOGD("Dropping event delivery to target with channel '%s' because it "
978 "is no longer registered with the input dispatcher.",
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700979 inputTarget.inputChannel->getName().string());
Jeff Brownb6997262010-10-08 22:31:17 -0700980#endif
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700981 }
982 }
983}
984
Jeff Brown54a18252010-09-16 14:07:33 -0700985void InputDispatcher::resetTargetsLocked() {
Jeff Brownb88102f2010-09-08 11:49:43 -0700986 mCurrentInputTargetsValid = false;
987 mCurrentInputTargets.clear();
Jeff Brownb88102f2010-09-08 11:49:43 -0700988 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_NONE;
Jeff Brown928e0542011-01-10 11:17:36 -0800989 mInputTargetWaitApplication.clear();
Jeff Brownb88102f2010-09-08 11:49:43 -0700990}
991
Jeff Brown01ce2e92010-09-26 22:20:12 -0700992void InputDispatcher::commitTargetsLocked() {
Jeff Brownb88102f2010-09-08 11:49:43 -0700993 mCurrentInputTargetsValid = true;
994}
995
996int32_t InputDispatcher::handleTargetsNotReadyLocked(nsecs_t currentTime,
997 const EventEntry* entry, const InputApplication* application, const InputWindow* window,
998 nsecs_t* nextWakeupTime) {
999 if (application == NULL && window == NULL) {
1000 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY) {
1001#if DEBUG_FOCUS
1002 LOGD("Waiting for system to become ready for input.");
1003#endif
1004 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY;
1005 mInputTargetWaitStartTime = currentTime;
1006 mInputTargetWaitTimeoutTime = LONG_LONG_MAX;
1007 mInputTargetWaitTimeoutExpired = false;
Jeff Brown928e0542011-01-10 11:17:36 -08001008 mInputTargetWaitApplication.clear();
Jeff Brownb88102f2010-09-08 11:49:43 -07001009 }
1010 } else {
1011 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
1012#if DEBUG_FOCUS
Jeff Brown519e0242010-09-15 15:18:56 -07001013 LOGD("Waiting for application to become ready for input: %s",
1014 getApplicationWindowLabelLocked(application, window).string());
Jeff Brownb88102f2010-09-08 11:49:43 -07001015#endif
1016 nsecs_t timeout = window ? window->dispatchingTimeout :
1017 application ? application->dispatchingTimeout : DEFAULT_INPUT_DISPATCHING_TIMEOUT;
1018
1019 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY;
1020 mInputTargetWaitStartTime = currentTime;
1021 mInputTargetWaitTimeoutTime = currentTime + timeout;
1022 mInputTargetWaitTimeoutExpired = false;
Jeff Brown928e0542011-01-10 11:17:36 -08001023 mInputTargetWaitApplication.clear();
1024
1025 if (window && window->inputWindowHandle != NULL) {
1026 mInputTargetWaitApplication =
1027 window->inputWindowHandle->getInputApplicationHandle();
1028 }
1029 if (mInputTargetWaitApplication == NULL && application) {
1030 mInputTargetWaitApplication = application->inputApplicationHandle;
1031 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001032 }
1033 }
1034
1035 if (mInputTargetWaitTimeoutExpired) {
1036 return INPUT_EVENT_INJECTION_TIMED_OUT;
1037 }
1038
1039 if (currentTime >= mInputTargetWaitTimeoutTime) {
Jeff Brown519e0242010-09-15 15:18:56 -07001040 onANRLocked(currentTime, application, window, entry->eventTime, mInputTargetWaitStartTime);
Jeff Brownb88102f2010-09-08 11:49:43 -07001041
1042 // Force poll loop to wake up immediately on next iteration once we get the
1043 // ANR response back from the policy.
1044 *nextWakeupTime = LONG_LONG_MIN;
1045 return INPUT_EVENT_INJECTION_PENDING;
1046 } else {
1047 // Force poll loop to wake up when timeout is due.
1048 if (mInputTargetWaitTimeoutTime < *nextWakeupTime) {
1049 *nextWakeupTime = mInputTargetWaitTimeoutTime;
1050 }
1051 return INPUT_EVENT_INJECTION_PENDING;
1052 }
1053}
1054
Jeff Brown519e0242010-09-15 15:18:56 -07001055void InputDispatcher::resumeAfterTargetsNotReadyTimeoutLocked(nsecs_t newTimeout,
1056 const sp<InputChannel>& inputChannel) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001057 if (newTimeout > 0) {
1058 // Extend the timeout.
1059 mInputTargetWaitTimeoutTime = now() + newTimeout;
1060 } else {
1061 // Give up.
1062 mInputTargetWaitTimeoutExpired = true;
Jeff Brown519e0242010-09-15 15:18:56 -07001063
Jeff Brown01ce2e92010-09-26 22:20:12 -07001064 // Release the touch targets.
1065 mTouchState.reset();
Jeff Brown2a95c2a2010-09-16 12:31:46 -07001066
Jeff Brown519e0242010-09-15 15:18:56 -07001067 // Input state will not be realistic. Mark it out of sync.
Jeff Browndc3e0052010-09-16 11:02:16 -07001068 if (inputChannel.get()) {
1069 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
1070 if (connectionIndex >= 0) {
1071 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
Jeff Brown00045a72010-12-09 18:10:30 -08001072 if (connection->status == Connection::STATUS_NORMAL) {
1073 synthesizeCancelationEventsForConnectionLocked(
1074 connection, InputState::CANCEL_ALL_EVENTS,
1075 "application not responding");
1076 }
Jeff Browndc3e0052010-09-16 11:02:16 -07001077 }
Jeff Brown519e0242010-09-15 15:18:56 -07001078 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001079 }
1080}
1081
Jeff Brown519e0242010-09-15 15:18:56 -07001082nsecs_t InputDispatcher::getTimeSpentWaitingForApplicationLocked(
Jeff Brownb88102f2010-09-08 11:49:43 -07001083 nsecs_t currentTime) {
1084 if (mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
1085 return currentTime - mInputTargetWaitStartTime;
1086 }
1087 return 0;
1088}
1089
1090void InputDispatcher::resetANRTimeoutsLocked() {
1091#if DEBUG_FOCUS
1092 LOGD("Resetting ANR timeouts.");
1093#endif
1094
Jeff Brownb88102f2010-09-08 11:49:43 -07001095 // Reset input target wait timeout.
1096 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_NONE;
1097}
1098
Jeff Brown01ce2e92010-09-26 22:20:12 -07001099int32_t InputDispatcher::findFocusedWindowTargetsLocked(nsecs_t currentTime,
1100 const EventEntry* entry, nsecs_t* nextWakeupTime) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001101 mCurrentInputTargets.clear();
1102
1103 int32_t injectionResult;
1104
1105 // If there is no currently focused window and no focused application
1106 // then drop the event.
1107 if (! mFocusedWindow) {
1108 if (mFocusedApplication) {
1109#if DEBUG_FOCUS
1110 LOGD("Waiting because there is no focused window but there is a "
Jeff Brown519e0242010-09-15 15:18:56 -07001111 "focused application that may eventually add a window: %s.",
1112 getApplicationWindowLabelLocked(mFocusedApplication, NULL).string());
Jeff Brownb88102f2010-09-08 11:49:43 -07001113#endif
1114 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
1115 mFocusedApplication, NULL, nextWakeupTime);
1116 goto Unresponsive;
1117 }
1118
1119 LOGI("Dropping event because there is no focused window or focused application.");
1120 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1121 goto Failed;
1122 }
1123
1124 // Check permissions.
Jeff Brown01ce2e92010-09-26 22:20:12 -07001125 if (! checkInjectionPermission(mFocusedWindow, entry->injectionState)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001126 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1127 goto Failed;
1128 }
1129
1130 // If the currently focused window is paused then keep waiting.
1131 if (mFocusedWindow->paused) {
1132#if DEBUG_FOCUS
1133 LOGD("Waiting because focused window is paused.");
1134#endif
1135 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
1136 mFocusedApplication, mFocusedWindow, nextWakeupTime);
1137 goto Unresponsive;
1138 }
1139
Jeff Brown519e0242010-09-15 15:18:56 -07001140 // If the currently focused window is still working on previous events then keep waiting.
1141 if (! isWindowFinishedWithPreviousInputLocked(mFocusedWindow)) {
1142#if DEBUG_FOCUS
1143 LOGD("Waiting because focused window still processing previous input.");
1144#endif
1145 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
1146 mFocusedApplication, mFocusedWindow, nextWakeupTime);
1147 goto Unresponsive;
1148 }
1149
Jeff Brownb88102f2010-09-08 11:49:43 -07001150 // Success! Output targets.
1151 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
Jeff Browna032cc02011-03-07 16:56:21 -08001152 addWindowTargetLocked(mFocusedWindow,
1153 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS, BitSet32(0));
Jeff Brownb88102f2010-09-08 11:49:43 -07001154
1155 // Done.
1156Failed:
1157Unresponsive:
Jeff Brown519e0242010-09-15 15:18:56 -07001158 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
1159 updateDispatchStatisticsLocked(currentTime, entry,
1160 injectionResult, timeSpentWaitingForApplication);
Jeff Brownb88102f2010-09-08 11:49:43 -07001161#if DEBUG_FOCUS
Jeff Brown519e0242010-09-15 15:18:56 -07001162 LOGD("findFocusedWindow finished: injectionResult=%d, "
1163 "timeSpendWaitingForApplication=%0.1fms",
1164 injectionResult, timeSpentWaitingForApplication / 1000000.0);
Jeff Brownb88102f2010-09-08 11:49:43 -07001165#endif
1166 return injectionResult;
1167}
1168
Jeff Brown01ce2e92010-09-26 22:20:12 -07001169int32_t InputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime,
Jeff Browna032cc02011-03-07 16:56:21 -08001170 const MotionEntry* entry, nsecs_t* nextWakeupTime, bool* outConflictingPointerActions,
1171 const MotionSample** outSplitBatchAfterSample) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001172 enum InjectionPermission {
1173 INJECTION_PERMISSION_UNKNOWN,
1174 INJECTION_PERMISSION_GRANTED,
1175 INJECTION_PERMISSION_DENIED
1176 };
1177
Jeff Brownb88102f2010-09-08 11:49:43 -07001178 mCurrentInputTargets.clear();
1179
1180 nsecs_t startTime = now();
1181
1182 // For security reasons, we defer updating the touch state until we are sure that
1183 // event injection will be allowed.
1184 //
1185 // FIXME In the original code, screenWasOff could never be set to true.
1186 // The reason is that the POLICY_FLAG_WOKE_HERE
1187 // and POLICY_FLAG_BRIGHT_HERE flags were set only when preprocessing raw
1188 // EV_KEY, EV_REL and EV_ABS events. As it happens, the touch event was
1189 // actually enqueued using the policyFlags that appeared in the final EV_SYN
1190 // events upon which no preprocessing took place. So policyFlags was always 0.
1191 // In the new native input dispatcher we're a bit more careful about event
1192 // preprocessing so the touches we receive can actually have non-zero policyFlags.
1193 // Unfortunately we obtain undesirable behavior.
1194 //
1195 // Here's what happens:
1196 //
1197 // When the device dims in anticipation of going to sleep, touches
1198 // in windows which have FLAG_TOUCHABLE_WHEN_WAKING cause
1199 // the device to brighten and reset the user activity timer.
1200 // Touches on other windows (such as the launcher window)
1201 // are dropped. Then after a moment, the device goes to sleep. Oops.
1202 //
1203 // Also notice how screenWasOff was being initialized using POLICY_FLAG_BRIGHT_HERE
1204 // instead of POLICY_FLAG_WOKE_HERE...
1205 //
1206 bool screenWasOff = false; // original policy: policyFlags & POLICY_FLAG_BRIGHT_HERE;
1207
1208 int32_t action = entry->action;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001209 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Jeff Brownb88102f2010-09-08 11:49:43 -07001210
1211 // Update the touch state as needed based on the properties of the touch event.
Jeff Brown01ce2e92010-09-26 22:20:12 -07001212 int32_t injectionResult = INPUT_EVENT_INJECTION_PENDING;
1213 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
Jeff Browna032cc02011-03-07 16:56:21 -08001214 const InputWindow* newHoverWindow = NULL;
Jeff Browncc0c1592011-02-19 05:07:28 -08001215
1216 bool isSplit = mTouchState.split;
1217 bool wrongDevice = mTouchState.down
1218 && (mTouchState.deviceId != entry->deviceId
1219 || mTouchState.source != entry->source);
Jeff Browna032cc02011-03-07 16:56:21 -08001220 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE
1221 || maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER
1222 || maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1223 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN
1224 || maskedAction == AMOTION_EVENT_ACTION_SCROLL
1225 || isHoverAction);
1226 if (newGesture) {
Jeff Browncc0c1592011-02-19 05:07:28 -08001227 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
1228 if (wrongDevice && !down) {
1229 mTempTouchState.copyFrom(mTouchState);
1230 } else {
1231 mTempTouchState.reset();
1232 mTempTouchState.down = down;
1233 mTempTouchState.deviceId = entry->deviceId;
1234 mTempTouchState.source = entry->source;
1235 isSplit = false;
1236 wrongDevice = false;
1237 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001238 } else {
1239 mTempTouchState.copyFrom(mTouchState);
Jeff Browncc0c1592011-02-19 05:07:28 -08001240 }
1241 if (wrongDevice) {
Jeff Brown95712852011-01-04 19:41:59 -08001242#if DEBUG_INPUT_DISPATCHER_POLICY
Jeff Browncc0c1592011-02-19 05:07:28 -08001243 LOGD("Dropping event because a pointer for a different device is already down.");
Jeff Brown95712852011-01-04 19:41:59 -08001244#endif
Jeff Browncc0c1592011-02-19 05:07:28 -08001245 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1246 goto Failed;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001247 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001248
Jeff Browna032cc02011-03-07 16:56:21 -08001249 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
Jeff Brown33bbfd22011-02-24 20:55:35 -08001250 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
Jeff Brownb88102f2010-09-08 11:49:43 -07001251
Jeff Browna032cc02011-03-07 16:56:21 -08001252 const MotionSample* sample = &entry->firstSample;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001253 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Jeff Browna032cc02011-03-07 16:56:21 -08001254 int32_t x = int32_t(sample->pointerCoords[pointerIndex].
Jeff Brownebbd5d12011-02-17 13:01:34 -08001255 getAxisValue(AMOTION_EVENT_AXIS_X));
Jeff Browna032cc02011-03-07 16:56:21 -08001256 int32_t y = int32_t(sample->pointerCoords[pointerIndex].
Jeff Brownebbd5d12011-02-17 13:01:34 -08001257 getAxisValue(AMOTION_EVENT_AXIS_Y));
Jeff Brown01ce2e92010-09-26 22:20:12 -07001258 const InputWindow* newTouchedWindow = NULL;
1259 const InputWindow* topErrorWindow = NULL;
Jeff Browna032cc02011-03-07 16:56:21 -08001260 bool isTouchModal = false;
Jeff Brownb88102f2010-09-08 11:49:43 -07001261
1262 // Traverse windows from front to back to find touched window and outside targets.
1263 size_t numWindows = mWindows.size();
1264 for (size_t i = 0; i < numWindows; i++) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001265 const InputWindow* window = & mWindows.editItemAt(i);
Jeff Brownb88102f2010-09-08 11:49:43 -07001266 int32_t flags = window->layoutParamsFlags;
1267
1268 if (flags & InputWindow::FLAG_SYSTEM_ERROR) {
1269 if (! topErrorWindow) {
1270 topErrorWindow = window;
1271 }
1272 }
1273
1274 if (window->visible) {
1275 if (! (flags & InputWindow::FLAG_NOT_TOUCHABLE)) {
Jeff Browna032cc02011-03-07 16:56:21 -08001276 isTouchModal = (flags & (InputWindow::FLAG_NOT_FOCUSABLE
Jeff Brownb88102f2010-09-08 11:49:43 -07001277 | InputWindow::FLAG_NOT_TOUCH_MODAL)) == 0;
Jeff Brownfbf09772011-01-16 14:06:57 -08001278 if (isTouchModal || window->touchableRegionContainsPoint(x, y)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001279 if (! screenWasOff || flags & InputWindow::FLAG_TOUCHABLE_WHEN_WAKING) {
1280 newTouchedWindow = window;
Jeff Brownb88102f2010-09-08 11:49:43 -07001281 }
1282 break; // found touched window, exit window loop
1283 }
1284 }
1285
Jeff Brown01ce2e92010-09-26 22:20:12 -07001286 if (maskedAction == AMOTION_EVENT_ACTION_DOWN
1287 && (flags & InputWindow::FLAG_WATCH_OUTSIDE_TOUCH)) {
Jeff Browna032cc02011-03-07 16:56:21 -08001288 int32_t outsideTargetFlags = InputTarget::FLAG_DISPATCH_AS_OUTSIDE;
Jeff Brown19dfc832010-10-05 12:26:23 -07001289 if (isWindowObscuredAtPointLocked(window, x, y)) {
1290 outsideTargetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1291 }
1292
1293 mTempTouchState.addOrUpdateWindow(window, outsideTargetFlags, BitSet32(0));
Jeff Brownb88102f2010-09-08 11:49:43 -07001294 }
1295 }
1296 }
1297
1298 // If there is an error window but it is not taking focus (typically because
1299 // it is invisible) then wait for it. Any other focused window may in
1300 // fact be in ANR state.
1301 if (topErrorWindow && newTouchedWindow != topErrorWindow) {
1302#if DEBUG_FOCUS
1303 LOGD("Waiting because system error window is pending.");
1304#endif
1305 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
1306 NULL, NULL, nextWakeupTime);
1307 injectionPermission = INJECTION_PERMISSION_UNKNOWN;
1308 goto Unresponsive;
1309 }
1310
Jeff Brown01ce2e92010-09-26 22:20:12 -07001311 // Figure out whether splitting will be allowed for this window.
Jeff Brown46e75292010-11-10 16:53:45 -08001312 if (newTouchedWindow && newTouchedWindow->supportsSplitTouch()) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001313 // New window supports splitting.
1314 isSplit = true;
1315 } else if (isSplit) {
1316 // New window does not support splitting but we have already split events.
1317 // Assign the pointer to the first foreground window we find.
1318 // (May be NULL which is why we put this code block before the next check.)
1319 newTouchedWindow = mTempTouchState.getFirstForegroundWindow();
1320 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001321
Jeff Brownb88102f2010-09-08 11:49:43 -07001322 // If we did not find a touched window then fail.
1323 if (! newTouchedWindow) {
1324 if (mFocusedApplication) {
1325#if DEBUG_FOCUS
1326 LOGD("Waiting because there is no touched window but there is a "
Jeff Brown519e0242010-09-15 15:18:56 -07001327 "focused application that may eventually add a new window: %s.",
1328 getApplicationWindowLabelLocked(mFocusedApplication, NULL).string());
Jeff Brownb88102f2010-09-08 11:49:43 -07001329#endif
1330 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
1331 mFocusedApplication, NULL, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -07001332 goto Unresponsive;
1333 }
1334
1335 LOGI("Dropping event because there is no touched window or focused application.");
1336 injectionResult = INPUT_EVENT_INJECTION_FAILED;
Jeff Brownb88102f2010-09-08 11:49:43 -07001337 goto Failed;
1338 }
1339
Jeff Brown19dfc832010-10-05 12:26:23 -07001340 // Set target flags.
Jeff Browna032cc02011-03-07 16:56:21 -08001341 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
Jeff Brown19dfc832010-10-05 12:26:23 -07001342 if (isSplit) {
1343 targetFlags |= InputTarget::FLAG_SPLIT;
1344 }
1345 if (isWindowObscuredAtPointLocked(newTouchedWindow, x, y)) {
1346 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1347 }
1348
Jeff Browna032cc02011-03-07 16:56:21 -08001349 // Update hover state.
1350 if (isHoverAction) {
1351 newHoverWindow = newTouchedWindow;
1352
1353 // Ensure all subsequent motion samples are also within the touched window.
1354 // Set *outSplitBatchAfterSample to the sample before the first one that is not
1355 // within the touched window.
1356 if (!isTouchModal) {
1357 while (sample->next) {
1358 if (!newHoverWindow->touchableRegionContainsPoint(
1359 sample->next->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X),
1360 sample->next->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y))) {
1361 *outSplitBatchAfterSample = sample;
1362 break;
1363 }
1364 sample = sample->next;
1365 }
1366 }
1367 } else if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
1368 newHoverWindow = mLastHoverWindow;
1369 }
1370
Jeff Brown01ce2e92010-09-26 22:20:12 -07001371 // Update the temporary touch state.
1372 BitSet32 pointerIds;
1373 if (isSplit) {
1374 uint32_t pointerId = entry->pointerIds[pointerIndex];
1375 pointerIds.markBit(pointerId);
Jeff Brownb88102f2010-09-08 11:49:43 -07001376 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001377 mTempTouchState.addOrUpdateWindow(newTouchedWindow, targetFlags, pointerIds);
Jeff Brownb88102f2010-09-08 11:49:43 -07001378 } else {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001379 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
Jeff Brownb88102f2010-09-08 11:49:43 -07001380
1381 // If the pointer is not currently down, then ignore the event.
Jeff Brown01ce2e92010-09-26 22:20:12 -07001382 if (! mTempTouchState.down) {
Jeff Brown76860e32010-10-25 17:37:46 -07001383#if DEBUG_INPUT_DISPATCHER_POLICY
1384 LOGD("Dropping event because the pointer is not down or we previously "
1385 "dropped the pointer down event.");
1386#endif
Jeff Brownb88102f2010-09-08 11:49:43 -07001387 injectionResult = INPUT_EVENT_INJECTION_FAILED;
Jeff Brownb88102f2010-09-08 11:49:43 -07001388 goto Failed;
1389 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001390 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001391
Jeff Browna032cc02011-03-07 16:56:21 -08001392 if (newHoverWindow != mLastHoverWindow) {
1393 // Split the batch here so we send exactly one sample as part of ENTER or EXIT.
1394 *outSplitBatchAfterSample = &entry->firstSample;
1395
1396 // Let the previous window know that the hover sequence is over.
1397 if (mLastHoverWindow) {
1398#if DEBUG_HOVER
1399 LOGD("Sending hover exit event to window %s.", mLastHoverWindow->name.string());
1400#endif
1401 mTempTouchState.addOrUpdateWindow(mLastHoverWindow,
1402 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
1403 }
1404
1405 // Let the new window know that the hover sequence is starting.
1406 if (newHoverWindow) {
1407#if DEBUG_HOVER
1408 LOGD("Sending hover enter event to window %s.", newHoverWindow->name.string());
1409#endif
1410 mTempTouchState.addOrUpdateWindow(newHoverWindow,
1411 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER, BitSet32(0));
1412 }
1413 }
1414
Jeff Brown01ce2e92010-09-26 22:20:12 -07001415 // Check permission to inject into all touched foreground windows and ensure there
1416 // is at least one touched foreground window.
1417 {
1418 bool haveForegroundWindow = false;
1419 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1420 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1421 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1422 haveForegroundWindow = true;
1423 if (! checkInjectionPermission(touchedWindow.window, entry->injectionState)) {
1424 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1425 injectionPermission = INJECTION_PERMISSION_DENIED;
1426 goto Failed;
1427 }
1428 }
1429 }
1430 if (! haveForegroundWindow) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001431#if DEBUG_INPUT_DISPATCHER_POLICY
Jeff Brown01ce2e92010-09-26 22:20:12 -07001432 LOGD("Dropping event because there is no touched foreground window to receive it.");
Jeff Brownb88102f2010-09-08 11:49:43 -07001433#endif
1434 injectionResult = INPUT_EVENT_INJECTION_FAILED;
Jeff Brownb88102f2010-09-08 11:49:43 -07001435 goto Failed;
1436 }
1437
Jeff Brown01ce2e92010-09-26 22:20:12 -07001438 // Permission granted to injection into all touched foreground windows.
1439 injectionPermission = INJECTION_PERMISSION_GRANTED;
1440 }
Jeff Brown519e0242010-09-15 15:18:56 -07001441
Jeff Brown01ce2e92010-09-26 22:20:12 -07001442 // Ensure all touched foreground windows are ready for new input.
1443 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1444 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1445 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1446 // If the touched window is paused then keep waiting.
1447 if (touchedWindow.window->paused) {
1448#if DEBUG_INPUT_DISPATCHER_POLICY
1449 LOGD("Waiting because touched window is paused.");
Jeff Brown519e0242010-09-15 15:18:56 -07001450#endif
Jeff Brown01ce2e92010-09-26 22:20:12 -07001451 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
1452 NULL, touchedWindow.window, nextWakeupTime);
1453 goto Unresponsive;
1454 }
1455
1456 // If the touched window is still working on previous events then keep waiting.
1457 if (! isWindowFinishedWithPreviousInputLocked(touchedWindow.window)) {
1458#if DEBUG_FOCUS
1459 LOGD("Waiting because touched window still processing previous input.");
1460#endif
1461 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
1462 NULL, touchedWindow.window, nextWakeupTime);
1463 goto Unresponsive;
1464 }
1465 }
1466 }
1467
1468 // If this is the first pointer going down and the touched window has a wallpaper
1469 // then also add the touched wallpaper windows so they are locked in for the duration
1470 // of the touch gesture.
Jeff Brown33bbfd22011-02-24 20:55:35 -08001471 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
1472 // engine only supports touch events. We would need to add a mechanism similar
1473 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
1474 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001475 const InputWindow* foregroundWindow = mTempTouchState.getFirstForegroundWindow();
1476 if (foregroundWindow->hasWallpaper) {
1477 for (size_t i = 0; i < mWindows.size(); i++) {
1478 const InputWindow* window = & mWindows[i];
1479 if (window->layoutParamsType == InputWindow::TYPE_WALLPAPER) {
Jeff Brown19dfc832010-10-05 12:26:23 -07001480 mTempTouchState.addOrUpdateWindow(window,
Jeff Browna032cc02011-03-07 16:56:21 -08001481 InputTarget::FLAG_WINDOW_IS_OBSCURED
1482 | InputTarget::FLAG_DISPATCH_AS_IS,
1483 BitSet32(0));
Jeff Brown01ce2e92010-09-26 22:20:12 -07001484 }
1485 }
1486 }
1487 }
1488
Jeff Brownb88102f2010-09-08 11:49:43 -07001489 // Success! Output targets.
1490 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
Jeff Brownb88102f2010-09-08 11:49:43 -07001491
Jeff Brown01ce2e92010-09-26 22:20:12 -07001492 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1493 const TouchedWindow& touchedWindow = mTempTouchState.windows.itemAt(i);
1494 addWindowTargetLocked(touchedWindow.window, touchedWindow.targetFlags,
1495 touchedWindow.pointerIds);
Jeff Brownb88102f2010-09-08 11:49:43 -07001496 }
1497
Jeff Browna032cc02011-03-07 16:56:21 -08001498 // Drop the outside or hover touch windows since we will not care about them
1499 // in the next iteration.
1500 mTempTouchState.filterNonAsIsTouchWindows();
Jeff Brown01ce2e92010-09-26 22:20:12 -07001501
Jeff Brownb88102f2010-09-08 11:49:43 -07001502Failed:
1503 // Check injection permission once and for all.
1504 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001505 if (checkInjectionPermission(NULL, entry->injectionState)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001506 injectionPermission = INJECTION_PERMISSION_GRANTED;
1507 } else {
1508 injectionPermission = INJECTION_PERMISSION_DENIED;
1509 }
1510 }
1511
1512 // Update final pieces of touch state if the injector had permission.
1513 if (injectionPermission == INJECTION_PERMISSION_GRANTED) {
Jeff Brown95712852011-01-04 19:41:59 -08001514 if (!wrongDevice) {
1515 if (maskedAction == AMOTION_EVENT_ACTION_UP
Jeff Browncc0c1592011-02-19 05:07:28 -08001516 || maskedAction == AMOTION_EVENT_ACTION_CANCEL
Jeff Browna032cc02011-03-07 16:56:21 -08001517 || isHoverAction) {
Jeff Brown95712852011-01-04 19:41:59 -08001518 // All pointers up or canceled.
Jeff Brown33bbfd22011-02-24 20:55:35 -08001519 mTouchState.reset();
Jeff Brown95712852011-01-04 19:41:59 -08001520 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1521 // First pointer went down.
1522 if (mTouchState.down) {
Jeff Browncc0c1592011-02-19 05:07:28 -08001523 *outConflictingPointerActions = true;
Jeff Brownb6997262010-10-08 22:31:17 -07001524#if DEBUG_FOCUS
Jeff Brown95712852011-01-04 19:41:59 -08001525 LOGD("Pointer down received while already down.");
Jeff Brownb6997262010-10-08 22:31:17 -07001526#endif
Jeff Brown95712852011-01-04 19:41:59 -08001527 }
Jeff Brown33bbfd22011-02-24 20:55:35 -08001528 mTouchState.copyFrom(mTempTouchState);
Jeff Brown95712852011-01-04 19:41:59 -08001529 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
1530 // One pointer went up.
1531 if (isSplit) {
1532 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
1533 uint32_t pointerId = entry->pointerIds[pointerIndex];
Jeff Brownb88102f2010-09-08 11:49:43 -07001534
Jeff Brown95712852011-01-04 19:41:59 -08001535 for (size_t i = 0; i < mTempTouchState.windows.size(); ) {
1536 TouchedWindow& touchedWindow = mTempTouchState.windows.editItemAt(i);
1537 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
1538 touchedWindow.pointerIds.clearBit(pointerId);
1539 if (touchedWindow.pointerIds.isEmpty()) {
1540 mTempTouchState.windows.removeAt(i);
1541 continue;
1542 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001543 }
Jeff Brown95712852011-01-04 19:41:59 -08001544 i += 1;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001545 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001546 }
Jeff Brown33bbfd22011-02-24 20:55:35 -08001547 mTouchState.copyFrom(mTempTouchState);
1548 } else if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
1549 // Discard temporary touch state since it was only valid for this action.
1550 } else {
1551 // Save changes to touch state as-is for all other actions.
1552 mTouchState.copyFrom(mTempTouchState);
Jeff Brownb88102f2010-09-08 11:49:43 -07001553 }
Jeff Browna032cc02011-03-07 16:56:21 -08001554
1555 // Update hover state.
1556 mLastHoverWindow = newHoverWindow;
Jeff Brown95712852011-01-04 19:41:59 -08001557 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001558 } else {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001559#if DEBUG_FOCUS
1560 LOGD("Not updating touch focus because injection was denied.");
1561#endif
Jeff Brownb88102f2010-09-08 11:49:43 -07001562 }
1563
1564Unresponsive:
Jeff Brown120a4592010-10-27 18:43:51 -07001565 // Reset temporary touch state to ensure we release unnecessary references to input channels.
1566 mTempTouchState.reset();
1567
Jeff Brown519e0242010-09-15 15:18:56 -07001568 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
1569 updateDispatchStatisticsLocked(currentTime, entry,
1570 injectionResult, timeSpentWaitingForApplication);
Jeff Brownb88102f2010-09-08 11:49:43 -07001571#if DEBUG_FOCUS
Jeff Brown01ce2e92010-09-26 22:20:12 -07001572 LOGD("findTouchedWindow finished: injectionResult=%d, injectionPermission=%d, "
1573 "timeSpentWaitingForApplication=%0.1fms",
Jeff Brown519e0242010-09-15 15:18:56 -07001574 injectionResult, injectionPermission, timeSpentWaitingForApplication / 1000000.0);
Jeff Brownb88102f2010-09-08 11:49:43 -07001575#endif
1576 return injectionResult;
1577}
1578
Jeff Brown01ce2e92010-09-26 22:20:12 -07001579void InputDispatcher::addWindowTargetLocked(const InputWindow* window, int32_t targetFlags,
1580 BitSet32 pointerIds) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001581 mCurrentInputTargets.push();
1582
1583 InputTarget& target = mCurrentInputTargets.editTop();
1584 target.inputChannel = window->inputChannel;
1585 target.flags = targetFlags;
Jeff Brownb88102f2010-09-08 11:49:43 -07001586 target.xOffset = - window->frameLeft;
1587 target.yOffset = - window->frameTop;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001588 target.pointerIds = pointerIds;
Jeff Brownb88102f2010-09-08 11:49:43 -07001589}
1590
1591void InputDispatcher::addMonitoringTargetsLocked() {
1592 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
1593 mCurrentInputTargets.push();
1594
1595 InputTarget& target = mCurrentInputTargets.editTop();
1596 target.inputChannel = mMonitoringChannels[i];
1597 target.flags = 0;
Jeff Brownb88102f2010-09-08 11:49:43 -07001598 target.xOffset = 0;
1599 target.yOffset = 0;
1600 }
1601}
1602
1603bool InputDispatcher::checkInjectionPermission(const InputWindow* window,
Jeff Brown01ce2e92010-09-26 22:20:12 -07001604 const InjectionState* injectionState) {
1605 if (injectionState
Jeff Brownb6997262010-10-08 22:31:17 -07001606 && (window == NULL || window->ownerUid != injectionState->injectorUid)
1607 && !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
1608 if (window) {
1609 LOGW("Permission denied: injecting event from pid %d uid %d to window "
1610 "with input channel %s owned by uid %d",
1611 injectionState->injectorPid, injectionState->injectorUid,
1612 window->inputChannel->getName().string(),
1613 window->ownerUid);
1614 } else {
1615 LOGW("Permission denied: injecting event from pid %d uid %d",
1616 injectionState->injectorPid, injectionState->injectorUid);
Jeff Brownb88102f2010-09-08 11:49:43 -07001617 }
Jeff Brownb6997262010-10-08 22:31:17 -07001618 return false;
Jeff Brownb88102f2010-09-08 11:49:43 -07001619 }
1620 return true;
1621}
1622
Jeff Brown19dfc832010-10-05 12:26:23 -07001623bool InputDispatcher::isWindowObscuredAtPointLocked(
1624 const InputWindow* window, int32_t x, int32_t y) const {
Jeff Brownb88102f2010-09-08 11:49:43 -07001625 size_t numWindows = mWindows.size();
1626 for (size_t i = 0; i < numWindows; i++) {
1627 const InputWindow* other = & mWindows.itemAt(i);
1628 if (other == window) {
1629 break;
1630 }
Jeff Brown19dfc832010-10-05 12:26:23 -07001631 if (other->visible && ! other->isTrustedOverlay() && other->frameContainsPoint(x, y)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001632 return true;
1633 }
1634 }
1635 return false;
1636}
1637
Jeff Brown519e0242010-09-15 15:18:56 -07001638bool InputDispatcher::isWindowFinishedWithPreviousInputLocked(const InputWindow* window) {
1639 ssize_t connectionIndex = getConnectionIndexLocked(window->inputChannel);
1640 if (connectionIndex >= 0) {
1641 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
1642 return connection->outboundQueue.isEmpty();
1643 } else {
1644 return true;
1645 }
1646}
1647
1648String8 InputDispatcher::getApplicationWindowLabelLocked(const InputApplication* application,
1649 const InputWindow* window) {
1650 if (application) {
1651 if (window) {
1652 String8 label(application->name);
1653 label.append(" - ");
1654 label.append(window->name);
1655 return label;
1656 } else {
1657 return application->name;
1658 }
1659 } else if (window) {
1660 return window->name;
1661 } else {
1662 return String8("<unknown application or window>");
1663 }
1664}
1665
Jeff Browne2fe69e2010-10-18 13:21:23 -07001666void InputDispatcher::pokeUserActivityLocked(const EventEntry* eventEntry) {
Jeff Brown56194eb2011-03-02 19:23:13 -08001667 int32_t eventType = POWER_MANAGER_OTHER_EVENT;
Jeff Brown4d396052010-10-29 21:50:21 -07001668 switch (eventEntry->type) {
1669 case EventEntry::TYPE_MOTION: {
Jeff Browne2fe69e2010-10-18 13:21:23 -07001670 const MotionEntry* motionEntry = static_cast<const MotionEntry*>(eventEntry);
Jeff Brown4d396052010-10-29 21:50:21 -07001671 if (motionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
1672 return;
1673 }
1674
Jeff Brown56194eb2011-03-02 19:23:13 -08001675 if (MotionEvent::isTouchEvent(motionEntry->source, motionEntry->action)) {
Joe Onorato1a542c72010-11-08 09:48:20 -08001676 eventType = POWER_MANAGER_TOUCH_EVENT;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001677 }
Jeff Brown4d396052010-10-29 21:50:21 -07001678 break;
1679 }
1680 case EventEntry::TYPE_KEY: {
1681 const KeyEntry* keyEntry = static_cast<const KeyEntry*>(eventEntry);
1682 if (keyEntry->flags & AKEY_EVENT_FLAG_CANCELED) {
1683 return;
1684 }
Jeff Brown56194eb2011-03-02 19:23:13 -08001685 eventType = POWER_MANAGER_BUTTON_EVENT;
Jeff Brown4d396052010-10-29 21:50:21 -07001686 break;
1687 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001688 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001689
Jeff Brownb88102f2010-09-08 11:49:43 -07001690 CommandEntry* commandEntry = postCommandLocked(
1691 & InputDispatcher::doPokeUserActivityLockedInterruptible);
Jeff Browne2fe69e2010-10-18 13:21:23 -07001692 commandEntry->eventTime = eventEntry->eventTime;
Jeff Brownb88102f2010-09-08 11:49:43 -07001693 commandEntry->userActivityEventType = eventType;
1694}
1695
Jeff Brown7fbdc842010-06-17 20:52:56 -07001696void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
1697 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget,
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001698 bool resumeWithAppendedMotionSample) {
1699#if DEBUG_DISPATCH_CYCLE
Jeff Brown519e0242010-09-15 15:18:56 -07001700 LOGD("channel '%s' ~ prepareDispatchCycle - flags=%d, "
Jeff Brown01ce2e92010-09-26 22:20:12 -07001701 "xOffset=%f, yOffset=%f, "
Jeff Brown83c09682010-12-23 17:50:18 -08001702 "pointerIds=0x%x, "
Jeff Brown01ce2e92010-09-26 22:20:12 -07001703 "resumeWithAppendedMotionSample=%s",
Jeff Brown519e0242010-09-15 15:18:56 -07001704 connection->getInputChannelName(), inputTarget->flags,
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001705 inputTarget->xOffset, inputTarget->yOffset,
Jeff Brown83c09682010-12-23 17:50:18 -08001706 inputTarget->pointerIds.value,
Jeff Brownb88102f2010-09-08 11:49:43 -07001707 toString(resumeWithAppendedMotionSample));
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001708#endif
1709
Jeff Brown01ce2e92010-09-26 22:20:12 -07001710 // Make sure we are never called for streaming when splitting across multiple windows.
1711 bool isSplit = inputTarget->flags & InputTarget::FLAG_SPLIT;
1712 assert(! (resumeWithAppendedMotionSample && isSplit));
1713
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001714 // Skip this event if the connection status is not normal.
Jeff Brown519e0242010-09-15 15:18:56 -07001715 // We don't want to enqueue additional outbound events if the connection is broken.
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001716 if (connection->status != Connection::STATUS_NORMAL) {
Jeff Brownb6997262010-10-08 22:31:17 -07001717#if DEBUG_DISPATCH_CYCLE
1718 LOGD("channel '%s' ~ Dropping event because the channel status is %s",
Jeff Brownb88102f2010-09-08 11:49:43 -07001719 connection->getInputChannelName(), connection->getStatusLabel());
Jeff Brownb6997262010-10-08 22:31:17 -07001720#endif
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001721 return;
1722 }
1723
Jeff Brown01ce2e92010-09-26 22:20:12 -07001724 // Split a motion event if needed.
1725 if (isSplit) {
1726 assert(eventEntry->type == EventEntry::TYPE_MOTION);
1727
1728 MotionEntry* originalMotionEntry = static_cast<MotionEntry*>(eventEntry);
1729 if (inputTarget->pointerIds.count() != originalMotionEntry->pointerCount) {
1730 MotionEntry* splitMotionEntry = splitMotionEvent(
1731 originalMotionEntry, inputTarget->pointerIds);
Jeff Brown58a2da82011-01-25 16:02:22 -08001732 if (!splitMotionEntry) {
1733 return; // split event was dropped
1734 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001735#if DEBUG_FOCUS
1736 LOGD("channel '%s' ~ Split motion event.",
1737 connection->getInputChannelName());
1738 logOutboundMotionDetailsLocked(" ", splitMotionEntry);
1739#endif
1740 eventEntry = splitMotionEntry;
1741 }
1742 }
1743
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001744 // Resume the dispatch cycle with a freshly appended motion sample.
1745 // First we check that the last dispatch entry in the outbound queue is for the same
1746 // motion event to which we appended the motion sample. If we find such a dispatch
1747 // entry, and if it is currently in progress then we try to stream the new sample.
1748 bool wasEmpty = connection->outboundQueue.isEmpty();
1749
1750 if (! wasEmpty && resumeWithAppendedMotionSample) {
1751 DispatchEntry* motionEventDispatchEntry =
1752 connection->findQueuedDispatchEntryForEvent(eventEntry);
1753 if (motionEventDispatchEntry) {
1754 // If the dispatch entry is not in progress, then we must be busy dispatching an
1755 // earlier event. Not a problem, the motion event is on the outbound queue and will
1756 // be dispatched later.
1757 if (! motionEventDispatchEntry->inProgress) {
1758#if DEBUG_BATCHING
1759 LOGD("channel '%s' ~ Not streaming because the motion event has "
1760 "not yet been dispatched. "
1761 "(Waiting for earlier events to be consumed.)",
1762 connection->getInputChannelName());
1763#endif
1764 return;
1765 }
1766
1767 // If the dispatch entry is in progress but it already has a tail of pending
1768 // motion samples, then it must mean that the shared memory buffer filled up.
1769 // Not a problem, when this dispatch cycle is finished, we will eventually start
1770 // a new dispatch cycle to process the tail and that tail includes the newly
1771 // appended motion sample.
1772 if (motionEventDispatchEntry->tailMotionSample) {
1773#if DEBUG_BATCHING
1774 LOGD("channel '%s' ~ Not streaming because no new samples can "
1775 "be appended to the motion event in this dispatch cycle. "
1776 "(Waiting for next dispatch cycle to start.)",
1777 connection->getInputChannelName());
1778#endif
1779 return;
1780 }
1781
1782 // The dispatch entry is in progress and is still potentially open for streaming.
1783 // Try to stream the new motion sample. This might fail if the consumer has already
1784 // consumed the motion event (or if the channel is broken).
Jeff Brown01ce2e92010-09-26 22:20:12 -07001785 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
1786 MotionSample* appendedMotionSample = motionEntry->lastSample;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001787 status_t status = connection->inputPublisher.appendMotionSample(
1788 appendedMotionSample->eventTime, appendedMotionSample->pointerCoords);
1789 if (status == OK) {
1790#if DEBUG_BATCHING
1791 LOGD("channel '%s' ~ Successfully streamed new motion sample.",
1792 connection->getInputChannelName());
1793#endif
1794 return;
1795 }
1796
1797#if DEBUG_BATCHING
1798 if (status == NO_MEMORY) {
1799 LOGD("channel '%s' ~ Could not append motion sample to currently "
1800 "dispatched move event because the shared memory buffer is full. "
1801 "(Waiting for next dispatch cycle to start.)",
1802 connection->getInputChannelName());
1803 } else if (status == status_t(FAILED_TRANSACTION)) {
1804 LOGD("channel '%s' ~ Could not append motion sample to currently "
Jeff Brown349703e2010-06-22 01:27:15 -07001805 "dispatched move event because the event has already been consumed. "
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001806 "(Waiting for next dispatch cycle to start.)",
1807 connection->getInputChannelName());
1808 } else {
1809 LOGD("channel '%s' ~ Could not append motion sample to currently "
1810 "dispatched move event due to an error, status=%d. "
1811 "(Waiting for next dispatch cycle to start.)",
1812 connection->getInputChannelName(), status);
1813 }
1814#endif
1815 // Failed to stream. Start a new tail of pending motion samples to dispatch
1816 // in the next cycle.
1817 motionEventDispatchEntry->tailMotionSample = appendedMotionSample;
1818 return;
1819 }
1820 }
1821
Jeff Browna032cc02011-03-07 16:56:21 -08001822 // Enqueue dispatch entries for the requested modes.
1823 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1824 resumeWithAppendedMotionSample, InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
1825 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1826 resumeWithAppendedMotionSample, InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
1827 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1828 resumeWithAppendedMotionSample, InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
1829 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1830 resumeWithAppendedMotionSample, InputTarget::FLAG_DISPATCH_AS_IS);
1831
1832 // If the outbound queue was previously empty, start the dispatch cycle going.
1833 if (wasEmpty) {
1834 activateConnectionLocked(connection.get());
1835 startDispatchCycleLocked(currentTime, connection);
1836 }
1837}
1838
1839void InputDispatcher::enqueueDispatchEntryLocked(
1840 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget,
1841 bool resumeWithAppendedMotionSample, int32_t dispatchMode) {
1842 int32_t inputTargetFlags = inputTarget->flags;
1843 if (!(inputTargetFlags & dispatchMode)) {
1844 return;
1845 }
1846 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
1847
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001848 // This is a new event.
1849 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Jeff Brownb88102f2010-09-08 11:49:43 -07001850 DispatchEntry* dispatchEntry = mAllocator.obtainDispatchEntry(eventEntry, // increments ref
Jeff Browna032cc02011-03-07 16:56:21 -08001851 inputTargetFlags, inputTarget->xOffset, inputTarget->yOffset);
Jeff Brown519e0242010-09-15 15:18:56 -07001852 if (dispatchEntry->hasForegroundTarget()) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001853 incrementPendingForegroundDispatchesLocked(eventEntry);
Jeff Brown6ec402b2010-07-28 15:48:59 -07001854 }
1855
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001856 // Handle the case where we could not stream a new motion sample because the consumer has
1857 // already consumed the motion event (otherwise the corresponding dispatch entry would
1858 // still be in the outbound queue for this connection). We set the head motion sample
1859 // to the list starting with the newly appended motion sample.
1860 if (resumeWithAppendedMotionSample) {
1861#if DEBUG_BATCHING
1862 LOGD("channel '%s' ~ Preparing a new dispatch cycle for additional motion samples "
1863 "that cannot be streamed because the motion event has already been consumed.",
1864 connection->getInputChannelName());
1865#endif
1866 MotionSample* appendedMotionSample = static_cast<MotionEntry*>(eventEntry)->lastSample;
1867 dispatchEntry->headMotionSample = appendedMotionSample;
1868 }
1869
1870 // Enqueue the dispatch entry.
1871 connection->outboundQueue.enqueueAtTail(dispatchEntry);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001872}
1873
Jeff Brown7fbdc842010-06-17 20:52:56 -07001874void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Jeff Brown519e0242010-09-15 15:18:56 -07001875 const sp<Connection>& connection) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001876#if DEBUG_DISPATCH_CYCLE
1877 LOGD("channel '%s' ~ startDispatchCycle",
1878 connection->getInputChannelName());
1879#endif
1880
1881 assert(connection->status == Connection::STATUS_NORMAL);
1882 assert(! connection->outboundQueue.isEmpty());
1883
Jeff Brownb88102f2010-09-08 11:49:43 -07001884 DispatchEntry* dispatchEntry = connection->outboundQueue.headSentinel.next;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001885 assert(! dispatchEntry->inProgress);
1886
Jeff Brownb88102f2010-09-08 11:49:43 -07001887 // Mark the dispatch entry as in progress.
1888 dispatchEntry->inProgress = true;
1889
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001890 // Publish the event.
1891 status_t status;
Jeff Browna032cc02011-03-07 16:56:21 -08001892 EventEntry* eventEntry = dispatchEntry->eventEntry;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001893 switch (eventEntry->type) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001894 case EventEntry::TYPE_KEY: {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001895 KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001896
1897 // Apply target flags.
1898 int32_t action = keyEntry->action;
1899 int32_t flags = keyEntry->flags;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001900
Jeff Browna032cc02011-03-07 16:56:21 -08001901 // Update the connection's input state.
1902 connection->inputState.trackKey(keyEntry, action);
1903
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001904 // Publish the key event.
Jeff Brownc5ed5912010-07-14 18:48:53 -07001905 status = connection->inputPublisher.publishKeyEvent(keyEntry->deviceId, keyEntry->source,
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001906 action, flags, keyEntry->keyCode, keyEntry->scanCode,
1907 keyEntry->metaState, keyEntry->repeatCount, keyEntry->downTime,
1908 keyEntry->eventTime);
1909
1910 if (status) {
1911 LOGE("channel '%s' ~ Could not publish key event, "
1912 "status=%d", connection->getInputChannelName(), status);
Jeff Brownb6997262010-10-08 22:31:17 -07001913 abortBrokenDispatchCycleLocked(currentTime, connection);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001914 return;
1915 }
1916 break;
1917 }
1918
1919 case EventEntry::TYPE_MOTION: {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001920 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001921
1922 // Apply target flags.
1923 int32_t action = motionEntry->action;
Jeff Brown85a31762010-09-01 17:01:00 -07001924 int32_t flags = motionEntry->flags;
Jeff Browna032cc02011-03-07 16:56:21 -08001925 if (dispatchEntry->targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001926 action = AMOTION_EVENT_ACTION_OUTSIDE;
Jeff Browna032cc02011-03-07 16:56:21 -08001927 } else if (dispatchEntry->targetFlags & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
1928 action = AMOTION_EVENT_ACTION_HOVER_EXIT;
1929 } else if (dispatchEntry->targetFlags & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
1930 action = AMOTION_EVENT_ACTION_HOVER_ENTER;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001931 }
Jeff Brown85a31762010-09-01 17:01:00 -07001932 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
1933 flags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
1934 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001935
1936 // If headMotionSample is non-NULL, then it points to the first new sample that we
1937 // were unable to dispatch during the previous cycle so we resume dispatching from
1938 // that point in the list of motion samples.
1939 // Otherwise, we just start from the first sample of the motion event.
1940 MotionSample* firstMotionSample = dispatchEntry->headMotionSample;
1941 if (! firstMotionSample) {
1942 firstMotionSample = & motionEntry->firstSample;
1943 }
1944
Jeff Brownd3616592010-07-16 17:21:06 -07001945 // Set the X and Y offset depending on the input source.
1946 float xOffset, yOffset;
1947 if (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) {
1948 xOffset = dispatchEntry->xOffset;
1949 yOffset = dispatchEntry->yOffset;
1950 } else {
1951 xOffset = 0.0f;
1952 yOffset = 0.0f;
1953 }
1954
Jeff Browna032cc02011-03-07 16:56:21 -08001955 // Update the connection's input state.
1956 connection->inputState.trackMotion(motionEntry, action);
1957
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001958 // Publish the motion event and the first motion sample.
1959 status = connection->inputPublisher.publishMotionEvent(motionEntry->deviceId,
Jeff Brown85a31762010-09-01 17:01:00 -07001960 motionEntry->source, action, flags, motionEntry->edgeFlags, motionEntry->metaState,
Jeff Brownd3616592010-07-16 17:21:06 -07001961 xOffset, yOffset,
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001962 motionEntry->xPrecision, motionEntry->yPrecision,
1963 motionEntry->downTime, firstMotionSample->eventTime,
1964 motionEntry->pointerCount, motionEntry->pointerIds,
1965 firstMotionSample->pointerCoords);
1966
1967 if (status) {
1968 LOGE("channel '%s' ~ Could not publish motion event, "
1969 "status=%d", connection->getInputChannelName(), status);
Jeff Brownb6997262010-10-08 22:31:17 -07001970 abortBrokenDispatchCycleLocked(currentTime, connection);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001971 return;
1972 }
1973
Jeff Browna032cc02011-03-07 16:56:21 -08001974 if (action == AMOTION_EVENT_ACTION_MOVE
1975 || action == AMOTION_EVENT_ACTION_HOVER_MOVE) {
1976 // Append additional motion samples.
1977 MotionSample* nextMotionSample = firstMotionSample->next;
1978 for (; nextMotionSample != NULL; nextMotionSample = nextMotionSample->next) {
1979 status = connection->inputPublisher.appendMotionSample(
1980 nextMotionSample->eventTime, nextMotionSample->pointerCoords);
1981 if (status == NO_MEMORY) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001982#if DEBUG_DISPATCH_CYCLE
1983 LOGD("channel '%s' ~ Shared memory buffer full. Some motion samples will "
1984 "be sent in the next dispatch cycle.",
1985 connection->getInputChannelName());
1986#endif
Jeff Browna032cc02011-03-07 16:56:21 -08001987 break;
1988 }
1989 if (status != OK) {
1990 LOGE("channel '%s' ~ Could not append motion sample "
1991 "for a reason other than out of memory, status=%d",
1992 connection->getInputChannelName(), status);
1993 abortBrokenDispatchCycleLocked(currentTime, connection);
1994 return;
1995 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001996 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001997
Jeff Browna032cc02011-03-07 16:56:21 -08001998 // Remember the next motion sample that we could not dispatch, in case we ran out
1999 // of space in the shared memory buffer.
2000 dispatchEntry->tailMotionSample = nextMotionSample;
2001 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002002 break;
2003 }
2004
2005 default: {
2006 assert(false);
2007 }
2008 }
2009
2010 // Send the dispatch signal.
2011 status = connection->inputPublisher.sendDispatchSignal();
2012 if (status) {
2013 LOGE("channel '%s' ~ Could not send dispatch signal, status=%d",
2014 connection->getInputChannelName(), status);
Jeff Brownb6997262010-10-08 22:31:17 -07002015 abortBrokenDispatchCycleLocked(currentTime, connection);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002016 return;
2017 }
2018
2019 // Record information about the newly started dispatch cycle.
Jeff Brown01ce2e92010-09-26 22:20:12 -07002020 connection->lastEventTime = eventEntry->eventTime;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002021 connection->lastDispatchTime = currentTime;
2022
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002023 // Notify other system components.
2024 onDispatchCycleStartedLocked(currentTime, connection);
2025}
2026
Jeff Brown7fbdc842010-06-17 20:52:56 -07002027void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Jeff Brown3915bb82010-11-05 15:02:16 -07002028 const sp<Connection>& connection, bool handled) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002029#if DEBUG_DISPATCH_CYCLE
Jeff Brown9c3cda02010-06-15 01:31:58 -07002030 LOGD("channel '%s' ~ finishDispatchCycle - %01.1fms since event, "
Jeff Brown3915bb82010-11-05 15:02:16 -07002031 "%01.1fms since dispatch, handled=%s",
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002032 connection->getInputChannelName(),
2033 connection->getEventLatencyMillis(currentTime),
Jeff Brown3915bb82010-11-05 15:02:16 -07002034 connection->getDispatchLatencyMillis(currentTime),
2035 toString(handled));
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002036#endif
2037
Jeff Brown9c3cda02010-06-15 01:31:58 -07002038 if (connection->status == Connection::STATUS_BROKEN
2039 || connection->status == Connection::STATUS_ZOMBIE) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002040 return;
2041 }
2042
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002043 // Reset the publisher since the event has been consumed.
2044 // We do this now so that the publisher can release some of its internal resources
2045 // while waiting for the next dispatch cycle to begin.
2046 status_t status = connection->inputPublisher.reset();
2047 if (status) {
2048 LOGE("channel '%s' ~ Could not reset publisher, status=%d",
2049 connection->getInputChannelName(), status);
Jeff Brownb6997262010-10-08 22:31:17 -07002050 abortBrokenDispatchCycleLocked(currentTime, connection);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002051 return;
2052 }
2053
Jeff Brown3915bb82010-11-05 15:02:16 -07002054 // Notify other system components and prepare to start the next dispatch cycle.
2055 onDispatchCycleFinishedLocked(currentTime, connection, handled);
Jeff Brownb88102f2010-09-08 11:49:43 -07002056}
2057
2058void InputDispatcher::startNextDispatchCycleLocked(nsecs_t currentTime,
2059 const sp<Connection>& connection) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002060 // Start the next dispatch cycle for this connection.
2061 while (! connection->outboundQueue.isEmpty()) {
Jeff Brownb88102f2010-09-08 11:49:43 -07002062 DispatchEntry* dispatchEntry = connection->outboundQueue.headSentinel.next;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002063 if (dispatchEntry->inProgress) {
2064 // Finish or resume current event in progress.
2065 if (dispatchEntry->tailMotionSample) {
2066 // We have a tail of undispatched motion samples.
2067 // Reuse the same DispatchEntry and start a new cycle.
2068 dispatchEntry->inProgress = false;
2069 dispatchEntry->headMotionSample = dispatchEntry->tailMotionSample;
2070 dispatchEntry->tailMotionSample = NULL;
Jeff Brown519e0242010-09-15 15:18:56 -07002071 startDispatchCycleLocked(currentTime, connection);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002072 return;
2073 }
2074 // Finished.
2075 connection->outboundQueue.dequeueAtHead();
Jeff Brown519e0242010-09-15 15:18:56 -07002076 if (dispatchEntry->hasForegroundTarget()) {
2077 decrementPendingForegroundDispatchesLocked(dispatchEntry->eventEntry);
Jeff Brown6ec402b2010-07-28 15:48:59 -07002078 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002079 mAllocator.releaseDispatchEntry(dispatchEntry);
2080 } else {
2081 // If the head is not in progress, then we must have already dequeued the in
Jeff Brown519e0242010-09-15 15:18:56 -07002082 // progress event, which means we actually aborted it.
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002083 // So just start the next event for this connection.
Jeff Brown519e0242010-09-15 15:18:56 -07002084 startDispatchCycleLocked(currentTime, connection);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002085 return;
2086 }
2087 }
2088
2089 // Outbound queue is empty, deactivate the connection.
Jeff Brown7fbdc842010-06-17 20:52:56 -07002090 deactivateConnectionLocked(connection.get());
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002091}
2092
Jeff Brownb6997262010-10-08 22:31:17 -07002093void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
2094 const sp<Connection>& connection) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002095#if DEBUG_DISPATCH_CYCLE
Jeff Brown83c09682010-12-23 17:50:18 -08002096 LOGD("channel '%s' ~ abortBrokenDispatchCycle",
2097 connection->getInputChannelName());
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002098#endif
2099
Jeff Brownb88102f2010-09-08 11:49:43 -07002100 // Clear the outbound queue.
Jeff Brown519e0242010-09-15 15:18:56 -07002101 drainOutboundQueueLocked(connection.get());
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002102
Jeff Brownb6997262010-10-08 22:31:17 -07002103 // The connection appears to be unrecoverably broken.
Jeff Brown9c3cda02010-06-15 01:31:58 -07002104 // Ignore already broken or zombie connections.
Jeff Brownb6997262010-10-08 22:31:17 -07002105 if (connection->status == Connection::STATUS_NORMAL) {
2106 connection->status = Connection::STATUS_BROKEN;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002107
Jeff Brownb6997262010-10-08 22:31:17 -07002108 // Notify other system components.
2109 onDispatchCycleBrokenLocked(currentTime, connection);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002110 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002111}
2112
Jeff Brown519e0242010-09-15 15:18:56 -07002113void InputDispatcher::drainOutboundQueueLocked(Connection* connection) {
2114 while (! connection->outboundQueue.isEmpty()) {
2115 DispatchEntry* dispatchEntry = connection->outboundQueue.dequeueAtHead();
2116 if (dispatchEntry->hasForegroundTarget()) {
2117 decrementPendingForegroundDispatchesLocked(dispatchEntry->eventEntry);
Jeff Brownb88102f2010-09-08 11:49:43 -07002118 }
2119 mAllocator.releaseDispatchEntry(dispatchEntry);
Jeff Brownb88102f2010-09-08 11:49:43 -07002120 }
2121
Jeff Brown519e0242010-09-15 15:18:56 -07002122 deactivateConnectionLocked(connection);
Jeff Brownb88102f2010-09-08 11:49:43 -07002123}
2124
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002125int InputDispatcher::handleReceiveCallback(int receiveFd, int events, void* data) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002126 InputDispatcher* d = static_cast<InputDispatcher*>(data);
2127
2128 { // acquire lock
2129 AutoMutex _l(d->mLock);
2130
2131 ssize_t connectionIndex = d->mConnectionsByReceiveFd.indexOfKey(receiveFd);
2132 if (connectionIndex < 0) {
2133 LOGE("Received spurious receive callback for unknown input channel. "
2134 "fd=%d, events=0x%x", receiveFd, events);
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002135 return 0; // remove the callback
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002136 }
2137
Jeff Brown7fbdc842010-06-17 20:52:56 -07002138 nsecs_t currentTime = now();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002139
2140 sp<Connection> connection = d->mConnectionsByReceiveFd.valueAt(connectionIndex);
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002141 if (events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP)) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002142 LOGE("channel '%s' ~ Consumer closed input channel or an error occurred. "
2143 "events=0x%x", connection->getInputChannelName(), events);
Jeff Brownb6997262010-10-08 22:31:17 -07002144 d->abortBrokenDispatchCycleLocked(currentTime, connection);
Jeff Brown9c3cda02010-06-15 01:31:58 -07002145 d->runCommandsLockedInterruptible();
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002146 return 0; // remove the callback
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002147 }
2148
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002149 if (! (events & ALOOPER_EVENT_INPUT)) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002150 LOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
2151 "events=0x%x", connection->getInputChannelName(), events);
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002152 return 1;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002153 }
2154
Jeff Brown3915bb82010-11-05 15:02:16 -07002155 bool handled = false;
Jeff Brown49ed71d2010-12-06 17:13:33 -08002156 status_t status = connection->inputPublisher.receiveFinishedSignal(&handled);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002157 if (status) {
2158 LOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
2159 connection->getInputChannelName(), status);
Jeff Brownb6997262010-10-08 22:31:17 -07002160 d->abortBrokenDispatchCycleLocked(currentTime, connection);
Jeff Brown9c3cda02010-06-15 01:31:58 -07002161 d->runCommandsLockedInterruptible();
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002162 return 0; // remove the callback
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002163 }
2164
Jeff Brown3915bb82010-11-05 15:02:16 -07002165 d->finishDispatchCycleLocked(currentTime, connection, handled);
Jeff Brown9c3cda02010-06-15 01:31:58 -07002166 d->runCommandsLockedInterruptible();
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002167 return 1;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002168 } // release lock
2169}
2170
Jeff Brownb6997262010-10-08 22:31:17 -07002171void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
2172 InputState::CancelationOptions options, const char* reason) {
2173 for (size_t i = 0; i < mConnectionsByReceiveFd.size(); i++) {
2174 synthesizeCancelationEventsForConnectionLocked(
2175 mConnectionsByReceiveFd.valueAt(i), options, reason);
2176 }
2177}
2178
2179void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
2180 const sp<InputChannel>& channel, InputState::CancelationOptions options,
2181 const char* reason) {
2182 ssize_t index = getConnectionIndexLocked(channel);
2183 if (index >= 0) {
2184 synthesizeCancelationEventsForConnectionLocked(
2185 mConnectionsByReceiveFd.valueAt(index), options, reason);
2186 }
2187}
2188
2189void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
2190 const sp<Connection>& connection, InputState::CancelationOptions options,
2191 const char* reason) {
2192 nsecs_t currentTime = now();
2193
2194 mTempCancelationEvents.clear();
2195 connection->inputState.synthesizeCancelationEvents(currentTime, & mAllocator,
2196 mTempCancelationEvents, options);
2197
2198 if (! mTempCancelationEvents.isEmpty()
2199 && connection->status != Connection::STATUS_BROKEN) {
2200#if DEBUG_OUTBOUND_EVENT_DETAILS
2201 LOGD("channel '%s' ~ Synthesized %d cancelation events to bring channel back in sync "
2202 "with reality: %s, options=%d.",
2203 connection->getInputChannelName(), mTempCancelationEvents.size(), reason, options);
2204#endif
2205 for (size_t i = 0; i < mTempCancelationEvents.size(); i++) {
2206 EventEntry* cancelationEventEntry = mTempCancelationEvents.itemAt(i);
2207 switch (cancelationEventEntry->type) {
2208 case EventEntry::TYPE_KEY:
2209 logOutboundKeyDetailsLocked("cancel - ",
2210 static_cast<KeyEntry*>(cancelationEventEntry));
2211 break;
2212 case EventEntry::TYPE_MOTION:
2213 logOutboundMotionDetailsLocked("cancel - ",
2214 static_cast<MotionEntry*>(cancelationEventEntry));
2215 break;
2216 }
2217
2218 int32_t xOffset, yOffset;
2219 const InputWindow* window = getWindowLocked(connection->inputChannel);
2220 if (window) {
2221 xOffset = -window->frameLeft;
2222 yOffset = -window->frameTop;
2223 } else {
2224 xOffset = 0;
2225 yOffset = 0;
2226 }
2227
2228 DispatchEntry* cancelationDispatchEntry =
2229 mAllocator.obtainDispatchEntry(cancelationEventEntry, // increments ref
2230 0, xOffset, yOffset);
2231 connection->outboundQueue.enqueueAtTail(cancelationDispatchEntry);
2232
2233 mAllocator.releaseEventEntry(cancelationEventEntry);
2234 }
2235
2236 if (!connection->outboundQueue.headSentinel.next->inProgress) {
2237 startDispatchCycleLocked(currentTime, connection);
2238 }
2239 }
2240}
2241
Jeff Brown01ce2e92010-09-26 22:20:12 -07002242InputDispatcher::MotionEntry*
2243InputDispatcher::splitMotionEvent(const MotionEntry* originalMotionEntry, BitSet32 pointerIds) {
2244 assert(pointerIds.value != 0);
2245
2246 uint32_t splitPointerIndexMap[MAX_POINTERS];
2247 int32_t splitPointerIds[MAX_POINTERS];
2248 PointerCoords splitPointerCoords[MAX_POINTERS];
2249
2250 uint32_t originalPointerCount = originalMotionEntry->pointerCount;
2251 uint32_t splitPointerCount = 0;
2252
2253 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
2254 originalPointerIndex++) {
2255 int32_t pointerId = uint32_t(originalMotionEntry->pointerIds[originalPointerIndex]);
2256 if (pointerIds.hasBit(pointerId)) {
2257 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
2258 splitPointerIds[splitPointerCount] = pointerId;
Jeff Brownace13b12011-03-09 17:39:48 -08002259 splitPointerCoords[splitPointerCount].copyFrom(
2260 originalMotionEntry->firstSample.pointerCoords[originalPointerIndex]);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002261 splitPointerCount += 1;
2262 }
2263 }
Jeff Brown58a2da82011-01-25 16:02:22 -08002264
2265 if (splitPointerCount != pointerIds.count()) {
2266 // This is bad. We are missing some of the pointers that we expected to deliver.
2267 // Most likely this indicates that we received an ACTION_MOVE events that has
2268 // different pointer ids than we expected based on the previous ACTION_DOWN
2269 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
2270 // in this way.
2271 LOGW("Dropping split motion event because the pointer count is %d but "
2272 "we expected there to be %d pointers. This probably means we received "
2273 "a broken sequence of pointer ids from the input device.",
2274 splitPointerCount, pointerIds.count());
2275 return NULL;
2276 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07002277
2278 int32_t action = originalMotionEntry->action;
2279 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
2280 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
2281 || maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2282 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
2283 int32_t pointerId = originalMotionEntry->pointerIds[originalPointerIndex];
2284 if (pointerIds.hasBit(pointerId)) {
2285 if (pointerIds.count() == 1) {
2286 // The first/last pointer went down/up.
2287 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
2288 ? AMOTION_EVENT_ACTION_DOWN : AMOTION_EVENT_ACTION_UP;
Jeff Brown9a01d052010-09-27 16:35:11 -07002289 } else {
2290 // A secondary pointer went down/up.
2291 uint32_t splitPointerIndex = 0;
2292 while (pointerId != splitPointerIds[splitPointerIndex]) {
2293 splitPointerIndex += 1;
2294 }
2295 action = maskedAction | (splitPointerIndex
2296 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002297 }
2298 } else {
2299 // An unrelated pointer changed.
2300 action = AMOTION_EVENT_ACTION_MOVE;
2301 }
2302 }
2303
2304 MotionEntry* splitMotionEntry = mAllocator.obtainMotionEntry(
2305 originalMotionEntry->eventTime,
2306 originalMotionEntry->deviceId,
2307 originalMotionEntry->source,
2308 originalMotionEntry->policyFlags,
2309 action,
2310 originalMotionEntry->flags,
2311 originalMotionEntry->metaState,
2312 originalMotionEntry->edgeFlags,
2313 originalMotionEntry->xPrecision,
2314 originalMotionEntry->yPrecision,
2315 originalMotionEntry->downTime,
2316 splitPointerCount, splitPointerIds, splitPointerCoords);
2317
2318 for (MotionSample* originalMotionSample = originalMotionEntry->firstSample.next;
2319 originalMotionSample != NULL; originalMotionSample = originalMotionSample->next) {
2320 for (uint32_t splitPointerIndex = 0; splitPointerIndex < splitPointerCount;
2321 splitPointerIndex++) {
2322 uint32_t originalPointerIndex = splitPointerIndexMap[splitPointerIndex];
Jeff Brownace13b12011-03-09 17:39:48 -08002323 splitPointerCoords[splitPointerIndex].copyFrom(
2324 originalMotionSample->pointerCoords[originalPointerIndex]);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002325 }
2326
2327 mAllocator.appendMotionSample(splitMotionEntry, originalMotionSample->eventTime,
2328 splitPointerCoords);
2329 }
2330
Jeff Browna032cc02011-03-07 16:56:21 -08002331 if (originalMotionEntry->injectionState) {
2332 splitMotionEntry->injectionState = originalMotionEntry->injectionState;
2333 splitMotionEntry->injectionState->refCount += 1;
2334 }
2335
Jeff Brown01ce2e92010-09-26 22:20:12 -07002336 return splitMotionEntry;
2337}
2338
Jeff Brown9c3cda02010-06-15 01:31:58 -07002339void InputDispatcher::notifyConfigurationChanged(nsecs_t eventTime) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002340#if DEBUG_INBOUND_EVENT_DETAILS
Jeff Brown9c3cda02010-06-15 01:31:58 -07002341 LOGD("notifyConfigurationChanged - eventTime=%lld", eventTime);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002342#endif
2343
Jeff Brownb88102f2010-09-08 11:49:43 -07002344 bool needWake;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002345 { // acquire lock
2346 AutoMutex _l(mLock);
2347
Jeff Brown7fbdc842010-06-17 20:52:56 -07002348 ConfigurationChangedEntry* newEntry = mAllocator.obtainConfigurationChangedEntry(eventTime);
Jeff Brownb88102f2010-09-08 11:49:43 -07002349 needWake = enqueueInboundEventLocked(newEntry);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002350 } // release lock
2351
Jeff Brownb88102f2010-09-08 11:49:43 -07002352 if (needWake) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002353 mLooper->wake();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002354 }
2355}
2356
Jeff Brown58a2da82011-01-25 16:02:22 -08002357void InputDispatcher::notifyKey(nsecs_t eventTime, int32_t deviceId, uint32_t source,
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002358 uint32_t policyFlags, int32_t action, int32_t flags,
2359 int32_t keyCode, int32_t scanCode, int32_t metaState, nsecs_t downTime) {
2360#if DEBUG_INBOUND_EVENT_DETAILS
Jeff Brown90655042010-12-02 13:50:46 -08002361 LOGD("notifyKey - eventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, action=0x%x, "
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002362 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%lld",
Jeff Brownc5ed5912010-07-14 18:48:53 -07002363 eventTime, deviceId, source, policyFlags, action, flags,
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002364 keyCode, scanCode, metaState, downTime);
2365#endif
Jeff Brown01ce2e92010-09-26 22:20:12 -07002366 if (! validateKeyEvent(action)) {
2367 return;
2368 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002369
Jeff Brown1f245102010-11-18 20:53:46 -08002370 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
2371 policyFlags |= POLICY_FLAG_VIRTUAL;
2372 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
2373 }
Jeff Brown924c4d42011-03-07 16:40:47 -08002374 if (policyFlags & POLICY_FLAG_ALT) {
2375 metaState |= AMETA_ALT_ON | AMETA_ALT_LEFT_ON;
2376 }
2377 if (policyFlags & POLICY_FLAG_ALT_GR) {
2378 metaState |= AMETA_ALT_ON | AMETA_ALT_RIGHT_ON;
2379 }
2380 if (policyFlags & POLICY_FLAG_SHIFT) {
2381 metaState |= AMETA_SHIFT_ON | AMETA_SHIFT_LEFT_ON;
2382 }
2383 if (policyFlags & POLICY_FLAG_CAPS_LOCK) {
2384 metaState |= AMETA_CAPS_LOCK_ON;
2385 }
2386 if (policyFlags & POLICY_FLAG_FUNCTION) {
2387 metaState |= AMETA_FUNCTION_ON;
2388 }
Jeff Brown1f245102010-11-18 20:53:46 -08002389
Jeff Browne20c9e02010-10-11 14:20:19 -07002390 policyFlags |= POLICY_FLAG_TRUSTED;
Jeff Brown1f245102010-11-18 20:53:46 -08002391
2392 KeyEvent event;
2393 event.initialize(deviceId, source, action, flags, keyCode, scanCode,
2394 metaState, 0, downTime, eventTime);
2395
2396 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
2397
2398 if (policyFlags & POLICY_FLAG_WOKE_HERE) {
2399 flags |= AKEY_EVENT_FLAG_WOKE_HERE;
2400 }
Jeff Brownb6997262010-10-08 22:31:17 -07002401
Jeff Brownb88102f2010-09-08 11:49:43 -07002402 bool needWake;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002403 { // acquire lock
2404 AutoMutex _l(mLock);
2405
Jeff Brown7fbdc842010-06-17 20:52:56 -07002406 int32_t repeatCount = 0;
2407 KeyEntry* newEntry = mAllocator.obtainKeyEntry(eventTime,
Jeff Brownc5ed5912010-07-14 18:48:53 -07002408 deviceId, source, policyFlags, action, flags, keyCode, scanCode,
Jeff Brown7fbdc842010-06-17 20:52:56 -07002409 metaState, repeatCount, downTime);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002410
Jeff Brownb88102f2010-09-08 11:49:43 -07002411 needWake = enqueueInboundEventLocked(newEntry);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002412 } // release lock
2413
Jeff Brownb88102f2010-09-08 11:49:43 -07002414 if (needWake) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002415 mLooper->wake();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002416 }
2417}
2418
Jeff Brown58a2da82011-01-25 16:02:22 -08002419void InputDispatcher::notifyMotion(nsecs_t eventTime, int32_t deviceId, uint32_t source,
Jeff Brown85a31762010-09-01 17:01:00 -07002420 uint32_t policyFlags, int32_t action, int32_t flags, int32_t metaState, int32_t edgeFlags,
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002421 uint32_t pointerCount, const int32_t* pointerIds, const PointerCoords* pointerCoords,
2422 float xPrecision, float yPrecision, nsecs_t downTime) {
2423#if DEBUG_INBOUND_EVENT_DETAILS
Jeff Brown90655042010-12-02 13:50:46 -08002424 LOGD("notifyMotion - eventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, "
Jeff Brown85a31762010-09-01 17:01:00 -07002425 "action=0x%x, flags=0x%x, metaState=0x%x, edgeFlags=0x%x, "
2426 "xPrecision=%f, yPrecision=%f, downTime=%lld",
2427 eventTime, deviceId, source, policyFlags, action, flags, metaState, edgeFlags,
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002428 xPrecision, yPrecision, downTime);
2429 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brown8d608662010-08-30 03:02:23 -07002430 LOGD(" Pointer %d: id=%d, x=%f, y=%f, pressure=%f, size=%f, "
Jeff Brown85a31762010-09-01 17:01:00 -07002431 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
Jeff Brown8d608662010-08-30 03:02:23 -07002432 "orientation=%f",
Jeff Brown91c69ab2011-02-14 17:03:18 -08002433 i, pointerIds[i],
Jeff Brownebbd5d12011-02-17 13:01:34 -08002434 pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
2435 pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
2436 pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
2437 pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
2438 pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
2439 pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
2440 pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
2441 pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
2442 pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002443 }
2444#endif
Jeff Brown01ce2e92010-09-26 22:20:12 -07002445 if (! validateMotionEvent(action, pointerCount, pointerIds)) {
2446 return;
2447 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002448
Jeff Browne20c9e02010-10-11 14:20:19 -07002449 policyFlags |= POLICY_FLAG_TRUSTED;
Jeff Brown56194eb2011-03-02 19:23:13 -08002450 mPolicy->interceptMotionBeforeQueueing(eventTime, /*byref*/ policyFlags);
Jeff Brownb6997262010-10-08 22:31:17 -07002451
Jeff Brownb88102f2010-09-08 11:49:43 -07002452 bool needWake;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002453 { // acquire lock
2454 AutoMutex _l(mLock);
2455
2456 // Attempt batching and streaming of move events.
Jeff Browncc0c1592011-02-19 05:07:28 -08002457 if (action == AMOTION_EVENT_ACTION_MOVE
2458 || action == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002459 // BATCHING CASE
2460 //
2461 // Try to append a move sample to the tail of the inbound queue for this device.
2462 // Give up if we encounter a non-move motion event for this device since that
2463 // means we cannot append any new samples until a new motion event has started.
Jeff Brownb88102f2010-09-08 11:49:43 -07002464 for (EventEntry* entry = mInboundQueue.tailSentinel.prev;
2465 entry != & mInboundQueue.headSentinel; entry = entry->prev) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002466 if (entry->type != EventEntry::TYPE_MOTION) {
2467 // Keep looking for motion events.
2468 continue;
2469 }
2470
2471 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
Jeff Brownefd32662011-03-08 15:13:06 -08002472 if (motionEntry->deviceId != deviceId
2473 || motionEntry->source != source) {
2474 // Keep looking for this device and source.
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002475 continue;
2476 }
2477
Jeff Browncc0c1592011-02-19 05:07:28 -08002478 if (motionEntry->action != action
Jeff Brown7fbdc842010-06-17 20:52:56 -07002479 || motionEntry->pointerCount != pointerCount
2480 || motionEntry->isInjected()) {
Jeff Brownefd32662011-03-08 15:13:06 -08002481 // Last motion event in the queue for this device and source is
2482 // not compatible for appending new samples. Stop here.
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002483 goto NoBatchingOrStreaming;
2484 }
2485
2486 // The last motion event is a move and is compatible for appending.
Jeff Brown9c3cda02010-06-15 01:31:58 -07002487 // Do the batching magic.
Jeff Brown7fbdc842010-06-17 20:52:56 -07002488 mAllocator.appendMotionSample(motionEntry, eventTime, pointerCoords);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002489#if DEBUG_BATCHING
2490 LOGD("Appended motion sample onto batch for most recent "
2491 "motion event for this device in the inbound queue.");
2492#endif
Jeff Brown9c3cda02010-06-15 01:31:58 -07002493 return; // done!
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002494 }
2495
2496 // STREAMING CASE
2497 //
2498 // There is no pending motion event (of any kind) for this device in the inbound queue.
Jeff Brown519e0242010-09-15 15:18:56 -07002499 // Search the outbound queue for the current foreground targets to find a dispatched
2500 // motion event that is still in progress. If found, then, appen the new sample to
2501 // that event and push it out to all current targets. The logic in
2502 // prepareDispatchCycleLocked takes care of the case where some targets may
2503 // already have consumed the motion event by starting a new dispatch cycle if needed.
Jeff Brown9c3cda02010-06-15 01:31:58 -07002504 if (mCurrentInputTargetsValid) {
Jeff Brown519e0242010-09-15 15:18:56 -07002505 for (size_t i = 0; i < mCurrentInputTargets.size(); i++) {
2506 const InputTarget& inputTarget = mCurrentInputTargets[i];
2507 if ((inputTarget.flags & InputTarget::FLAG_FOREGROUND) == 0) {
2508 // Skip non-foreground targets. We only want to stream if there is at
2509 // least one foreground target whose dispatch is still in progress.
2510 continue;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002511 }
Jeff Brown519e0242010-09-15 15:18:56 -07002512
2513 ssize_t connectionIndex = getConnectionIndexLocked(inputTarget.inputChannel);
2514 if (connectionIndex < 0) {
2515 // Connection must no longer be valid.
2516 continue;
2517 }
2518
2519 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
2520 if (connection->outboundQueue.isEmpty()) {
2521 // This foreground target has an empty outbound queue.
2522 continue;
2523 }
2524
2525 DispatchEntry* dispatchEntry = connection->outboundQueue.headSentinel.next;
2526 if (! dispatchEntry->inProgress
Jeff Brown01ce2e92010-09-26 22:20:12 -07002527 || dispatchEntry->eventEntry->type != EventEntry::TYPE_MOTION
2528 || dispatchEntry->isSplit()) {
2529 // No motion event is being dispatched, or it is being split across
2530 // windows in which case we cannot stream.
Jeff Brown519e0242010-09-15 15:18:56 -07002531 continue;
2532 }
2533
2534 MotionEntry* motionEntry = static_cast<MotionEntry*>(
2535 dispatchEntry->eventEntry);
Jeff Browncc0c1592011-02-19 05:07:28 -08002536 if (motionEntry->action != action
Jeff Brown519e0242010-09-15 15:18:56 -07002537 || motionEntry->deviceId != deviceId
Jeff Brown58a2da82011-01-25 16:02:22 -08002538 || motionEntry->source != source
Jeff Brown519e0242010-09-15 15:18:56 -07002539 || motionEntry->pointerCount != pointerCount
2540 || motionEntry->isInjected()) {
2541 // The motion event is not compatible with this move.
2542 continue;
2543 }
2544
Jeff Browna032cc02011-03-07 16:56:21 -08002545 if (action == AMOTION_EVENT_ACTION_HOVER_MOVE) {
2546 if (!mLastHoverWindow) {
2547#if DEBUG_BATCHING
2548 LOGD("Not streaming hover move because there is no "
2549 "last hovered window.");
2550#endif
2551 goto NoBatchingOrStreaming;
2552 }
2553
2554 const InputWindow* hoverWindow = findTouchedWindowAtLocked(
2555 pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X),
2556 pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
2557 if (mLastHoverWindow != hoverWindow) {
2558#if DEBUG_BATCHING
2559 LOGD("Not streaming hover move because the last hovered window "
2560 "is '%s' but the currently hovered window is '%s'.",
2561 mLastHoverWindow->name.string(),
2562 hoverWindow ? hoverWindow->name.string() : "<null>");
2563#endif
2564 goto NoBatchingOrStreaming;
2565 }
2566 }
2567
Jeff Brown519e0242010-09-15 15:18:56 -07002568 // Hurray! This foreground target is currently dispatching a move event
2569 // that we can stream onto. Append the motion sample and resume dispatch.
2570 mAllocator.appendMotionSample(motionEntry, eventTime, pointerCoords);
2571#if DEBUG_BATCHING
2572 LOGD("Appended motion sample onto batch for most recently dispatched "
2573 "motion event for this device in the outbound queues. "
2574 "Attempting to stream the motion sample.");
2575#endif
2576 nsecs_t currentTime = now();
2577 dispatchEventToCurrentInputTargetsLocked(currentTime, motionEntry,
2578 true /*resumeWithAppendedMotionSample*/);
2579
2580 runCommandsLockedInterruptible();
2581 return; // done!
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002582 }
2583 }
2584
2585NoBatchingOrStreaming:;
2586 }
2587
2588 // Just enqueue a new motion event.
Jeff Brown7fbdc842010-06-17 20:52:56 -07002589 MotionEntry* newEntry = mAllocator.obtainMotionEntry(eventTime,
Jeff Brown85a31762010-09-01 17:01:00 -07002590 deviceId, source, policyFlags, action, flags, metaState, edgeFlags,
Jeff Brown7fbdc842010-06-17 20:52:56 -07002591 xPrecision, yPrecision, downTime,
2592 pointerCount, pointerIds, pointerCoords);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002593
Jeff Brownb88102f2010-09-08 11:49:43 -07002594 needWake = enqueueInboundEventLocked(newEntry);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002595 } // release lock
2596
Jeff Brownb88102f2010-09-08 11:49:43 -07002597 if (needWake) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002598 mLooper->wake();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002599 }
2600}
2601
Jeff Brownb6997262010-10-08 22:31:17 -07002602void InputDispatcher::notifySwitch(nsecs_t when, int32_t switchCode, int32_t switchValue,
2603 uint32_t policyFlags) {
2604#if DEBUG_INBOUND_EVENT_DETAILS
2605 LOGD("notifySwitch - switchCode=%d, switchValue=%d, policyFlags=0x%x",
2606 switchCode, switchValue, policyFlags);
2607#endif
2608
Jeff Browne20c9e02010-10-11 14:20:19 -07002609 policyFlags |= POLICY_FLAG_TRUSTED;
Jeff Brownb6997262010-10-08 22:31:17 -07002610 mPolicy->notifySwitch(when, switchCode, switchValue, policyFlags);
2611}
2612
Jeff Brown7fbdc842010-06-17 20:52:56 -07002613int32_t InputDispatcher::injectInputEvent(const InputEvent* event,
Jeff Brown6ec402b2010-07-28 15:48:59 -07002614 int32_t injectorPid, int32_t injectorUid, int32_t syncMode, int32_t timeoutMillis) {
Jeff Brown7fbdc842010-06-17 20:52:56 -07002615#if DEBUG_INBOUND_EVENT_DETAILS
2616 LOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Jeff Brown6ec402b2010-07-28 15:48:59 -07002617 "syncMode=%d, timeoutMillis=%d",
2618 event->getType(), injectorPid, injectorUid, syncMode, timeoutMillis);
Jeff Brown7fbdc842010-06-17 20:52:56 -07002619#endif
2620
2621 nsecs_t endTime = now() + milliseconds_to_nanoseconds(timeoutMillis);
Jeff Browne20c9e02010-10-11 14:20:19 -07002622
2623 uint32_t policyFlags = POLICY_FLAG_INJECTED;
2624 if (hasInjectionPermission(injectorPid, injectorUid)) {
2625 policyFlags |= POLICY_FLAG_TRUSTED;
2626 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07002627
Jeff Brownb6997262010-10-08 22:31:17 -07002628 EventEntry* injectedEntry;
2629 switch (event->getType()) {
2630 case AINPUT_EVENT_TYPE_KEY: {
2631 const KeyEvent* keyEvent = static_cast<const KeyEvent*>(event);
2632 int32_t action = keyEvent->getAction();
2633 if (! validateKeyEvent(action)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07002634 return INPUT_EVENT_INJECTION_FAILED;
2635 }
2636
Jeff Brownb6997262010-10-08 22:31:17 -07002637 int32_t flags = keyEvent->getFlags();
Jeff Brown1f245102010-11-18 20:53:46 -08002638 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
2639 policyFlags |= POLICY_FLAG_VIRTUAL;
2640 }
2641
2642 mPolicy->interceptKeyBeforeQueueing(keyEvent, /*byref*/ policyFlags);
2643
2644 if (policyFlags & POLICY_FLAG_WOKE_HERE) {
2645 flags |= AKEY_EVENT_FLAG_WOKE_HERE;
2646 }
Jeff Brown6ec402b2010-07-28 15:48:59 -07002647
Jeff Brownb6997262010-10-08 22:31:17 -07002648 mLock.lock();
Jeff Brown1f245102010-11-18 20:53:46 -08002649 injectedEntry = mAllocator.obtainKeyEntry(keyEvent->getEventTime(),
2650 keyEvent->getDeviceId(), keyEvent->getSource(),
2651 policyFlags, action, flags,
2652 keyEvent->getKeyCode(), keyEvent->getScanCode(), keyEvent->getMetaState(),
Jeff Brownb6997262010-10-08 22:31:17 -07002653 keyEvent->getRepeatCount(), keyEvent->getDownTime());
2654 break;
2655 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07002656
Jeff Brownb6997262010-10-08 22:31:17 -07002657 case AINPUT_EVENT_TYPE_MOTION: {
2658 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
2659 int32_t action = motionEvent->getAction();
2660 size_t pointerCount = motionEvent->getPointerCount();
2661 const int32_t* pointerIds = motionEvent->getPointerIds();
2662 if (! validateMotionEvent(action, pointerCount, pointerIds)) {
2663 return INPUT_EVENT_INJECTION_FAILED;
2664 }
2665
2666 nsecs_t eventTime = motionEvent->getEventTime();
Jeff Brown56194eb2011-03-02 19:23:13 -08002667 mPolicy->interceptMotionBeforeQueueing(eventTime, /*byref*/ policyFlags);
Jeff Brownb6997262010-10-08 22:31:17 -07002668
2669 mLock.lock();
2670 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
2671 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
2672 MotionEntry* motionEntry = mAllocator.obtainMotionEntry(*sampleEventTimes,
2673 motionEvent->getDeviceId(), motionEvent->getSource(), policyFlags,
2674 action, motionEvent->getFlags(),
2675 motionEvent->getMetaState(), motionEvent->getEdgeFlags(),
2676 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
2677 motionEvent->getDownTime(), uint32_t(pointerCount),
2678 pointerIds, samplePointerCoords);
2679 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
2680 sampleEventTimes += 1;
2681 samplePointerCoords += pointerCount;
2682 mAllocator.appendMotionSample(motionEntry, *sampleEventTimes, samplePointerCoords);
2683 }
2684 injectedEntry = motionEntry;
2685 break;
2686 }
2687
2688 default:
2689 LOGW("Cannot inject event of type %d", event->getType());
2690 return INPUT_EVENT_INJECTION_FAILED;
2691 }
2692
2693 InjectionState* injectionState = mAllocator.obtainInjectionState(injectorPid, injectorUid);
2694 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
2695 injectionState->injectionIsAsync = true;
2696 }
2697
2698 injectionState->refCount += 1;
2699 injectedEntry->injectionState = injectionState;
2700
2701 bool needWake = enqueueInboundEventLocked(injectedEntry);
2702 mLock.unlock();
Jeff Brown7fbdc842010-06-17 20:52:56 -07002703
Jeff Brownb88102f2010-09-08 11:49:43 -07002704 if (needWake) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002705 mLooper->wake();
Jeff Brown7fbdc842010-06-17 20:52:56 -07002706 }
2707
2708 int32_t injectionResult;
2709 { // acquire lock
2710 AutoMutex _l(mLock);
2711
Jeff Brown6ec402b2010-07-28 15:48:59 -07002712 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
2713 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
2714 } else {
2715 for (;;) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002716 injectionResult = injectionState->injectionResult;
Jeff Brown6ec402b2010-07-28 15:48:59 -07002717 if (injectionResult != INPUT_EVENT_INJECTION_PENDING) {
2718 break;
2719 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07002720
Jeff Brown7fbdc842010-06-17 20:52:56 -07002721 nsecs_t remainingTimeout = endTime - now();
2722 if (remainingTimeout <= 0) {
Jeff Brown6ec402b2010-07-28 15:48:59 -07002723#if DEBUG_INJECTION
2724 LOGD("injectInputEvent - Timed out waiting for injection result "
2725 "to become available.");
2726#endif
Jeff Brown7fbdc842010-06-17 20:52:56 -07002727 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
2728 break;
2729 }
2730
Jeff Brown6ec402b2010-07-28 15:48:59 -07002731 mInjectionResultAvailableCondition.waitRelative(mLock, remainingTimeout);
2732 }
2733
2734 if (injectionResult == INPUT_EVENT_INJECTION_SUCCEEDED
2735 && syncMode == INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002736 while (injectionState->pendingForegroundDispatches != 0) {
Jeff Brown6ec402b2010-07-28 15:48:59 -07002737#if DEBUG_INJECTION
Jeff Brown519e0242010-09-15 15:18:56 -07002738 LOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
Jeff Brown01ce2e92010-09-26 22:20:12 -07002739 injectionState->pendingForegroundDispatches);
Jeff Brown6ec402b2010-07-28 15:48:59 -07002740#endif
2741 nsecs_t remainingTimeout = endTime - now();
2742 if (remainingTimeout <= 0) {
2743#if DEBUG_INJECTION
Jeff Brown519e0242010-09-15 15:18:56 -07002744 LOGD("injectInputEvent - Timed out waiting for pending foreground "
Jeff Brown6ec402b2010-07-28 15:48:59 -07002745 "dispatches to finish.");
2746#endif
2747 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
2748 break;
2749 }
2750
2751 mInjectionSyncFinishedCondition.waitRelative(mLock, remainingTimeout);
2752 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07002753 }
2754 }
2755
Jeff Brown01ce2e92010-09-26 22:20:12 -07002756 mAllocator.releaseInjectionState(injectionState);
Jeff Brown7fbdc842010-06-17 20:52:56 -07002757 } // release lock
2758
Jeff Brown6ec402b2010-07-28 15:48:59 -07002759#if DEBUG_INJECTION
2760 LOGD("injectInputEvent - Finished with result %d. "
2761 "injectorPid=%d, injectorUid=%d",
2762 injectionResult, injectorPid, injectorUid);
2763#endif
2764
Jeff Brown7fbdc842010-06-17 20:52:56 -07002765 return injectionResult;
2766}
2767
Jeff Brownb6997262010-10-08 22:31:17 -07002768bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
2769 return injectorUid == 0
2770 || mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
2771}
2772
Jeff Brown7fbdc842010-06-17 20:52:56 -07002773void InputDispatcher::setInjectionResultLocked(EventEntry* entry, int32_t injectionResult) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002774 InjectionState* injectionState = entry->injectionState;
2775 if (injectionState) {
Jeff Brown7fbdc842010-06-17 20:52:56 -07002776#if DEBUG_INJECTION
2777 LOGD("Setting input event injection result to %d. "
2778 "injectorPid=%d, injectorUid=%d",
Jeff Brown01ce2e92010-09-26 22:20:12 -07002779 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
Jeff Brown7fbdc842010-06-17 20:52:56 -07002780#endif
2781
Jeff Brown01ce2e92010-09-26 22:20:12 -07002782 if (injectionState->injectionIsAsync) {
Jeff Brown6ec402b2010-07-28 15:48:59 -07002783 // Log the outcome since the injector did not wait for the injection result.
2784 switch (injectionResult) {
2785 case INPUT_EVENT_INJECTION_SUCCEEDED:
2786 LOGV("Asynchronous input event injection succeeded.");
2787 break;
2788 case INPUT_EVENT_INJECTION_FAILED:
2789 LOGW("Asynchronous input event injection failed.");
2790 break;
2791 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
2792 LOGW("Asynchronous input event injection permission denied.");
2793 break;
2794 case INPUT_EVENT_INJECTION_TIMED_OUT:
2795 LOGW("Asynchronous input event injection timed out.");
2796 break;
2797 }
2798 }
2799
Jeff Brown01ce2e92010-09-26 22:20:12 -07002800 injectionState->injectionResult = injectionResult;
Jeff Brown7fbdc842010-06-17 20:52:56 -07002801 mInjectionResultAvailableCondition.broadcast();
2802 }
2803}
2804
Jeff Brown01ce2e92010-09-26 22:20:12 -07002805void InputDispatcher::incrementPendingForegroundDispatchesLocked(EventEntry* entry) {
2806 InjectionState* injectionState = entry->injectionState;
2807 if (injectionState) {
2808 injectionState->pendingForegroundDispatches += 1;
2809 }
2810}
2811
Jeff Brown519e0242010-09-15 15:18:56 -07002812void InputDispatcher::decrementPendingForegroundDispatchesLocked(EventEntry* entry) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002813 InjectionState* injectionState = entry->injectionState;
2814 if (injectionState) {
2815 injectionState->pendingForegroundDispatches -= 1;
Jeff Brown6ec402b2010-07-28 15:48:59 -07002816
Jeff Brown01ce2e92010-09-26 22:20:12 -07002817 if (injectionState->pendingForegroundDispatches == 0) {
2818 mInjectionSyncFinishedCondition.broadcast();
2819 }
Jeff Brownb88102f2010-09-08 11:49:43 -07002820 }
2821}
2822
Jeff Brown01ce2e92010-09-26 22:20:12 -07002823const InputWindow* InputDispatcher::getWindowLocked(const sp<InputChannel>& inputChannel) {
2824 for (size_t i = 0; i < mWindows.size(); i++) {
2825 const InputWindow* window = & mWindows[i];
2826 if (window->inputChannel == inputChannel) {
2827 return window;
2828 }
2829 }
2830 return NULL;
2831}
2832
Jeff Brownb88102f2010-09-08 11:49:43 -07002833void InputDispatcher::setInputWindows(const Vector<InputWindow>& inputWindows) {
2834#if DEBUG_FOCUS
2835 LOGD("setInputWindows");
2836#endif
2837 { // acquire lock
2838 AutoMutex _l(mLock);
2839
Jeff Brown01ce2e92010-09-26 22:20:12 -07002840 // Clear old window pointers.
Jeff Brownb6997262010-10-08 22:31:17 -07002841 sp<InputChannel> oldFocusedWindowChannel;
2842 if (mFocusedWindow) {
2843 oldFocusedWindowChannel = mFocusedWindow->inputChannel;
2844 mFocusedWindow = NULL;
2845 }
Jeff Browna032cc02011-03-07 16:56:21 -08002846 sp<InputChannel> oldLastHoverWindowChannel;
2847 if (mLastHoverWindow) {
2848 oldLastHoverWindowChannel = mLastHoverWindow->inputChannel;
2849 mLastHoverWindow = NULL;
2850 }
Jeff Brownb6997262010-10-08 22:31:17 -07002851
Jeff Brownb88102f2010-09-08 11:49:43 -07002852 mWindows.clear();
Jeff Brown2a95c2a2010-09-16 12:31:46 -07002853
2854 // Loop over new windows and rebuild the necessary window pointers for
2855 // tracking focus and touch.
Jeff Brownb88102f2010-09-08 11:49:43 -07002856 mWindows.appendVector(inputWindows);
2857
2858 size_t numWindows = mWindows.size();
2859 for (size_t i = 0; i < numWindows; i++) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002860 const InputWindow* window = & mWindows.itemAt(i);
Jeff Brownb88102f2010-09-08 11:49:43 -07002861 if (window->hasFocus) {
2862 mFocusedWindow = window;
Jeff Brown01ce2e92010-09-26 22:20:12 -07002863 break;
Jeff Brownb88102f2010-09-08 11:49:43 -07002864 }
2865 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07002866
Jeff Brownb6997262010-10-08 22:31:17 -07002867 if (oldFocusedWindowChannel != NULL) {
2868 if (!mFocusedWindow || oldFocusedWindowChannel != mFocusedWindow->inputChannel) {
2869#if DEBUG_FOCUS
2870 LOGD("Focus left window: %s",
2871 oldFocusedWindowChannel->getName().string());
2872#endif
2873 synthesizeCancelationEventsForInputChannelLocked(oldFocusedWindowChannel,
2874 InputState::CANCEL_NON_POINTER_EVENTS, "focus left window");
2875 oldFocusedWindowChannel.clear();
2876 }
2877 }
2878 if (mFocusedWindow && oldFocusedWindowChannel == NULL) {
2879#if DEBUG_FOCUS
2880 LOGD("Focus entered window: %s",
2881 mFocusedWindow->inputChannel->getName().string());
2882#endif
2883 }
2884
Jeff Brown01ce2e92010-09-26 22:20:12 -07002885 for (size_t i = 0; i < mTouchState.windows.size(); ) {
2886 TouchedWindow& touchedWindow = mTouchState.windows.editItemAt(i);
2887 const InputWindow* window = getWindowLocked(touchedWindow.channel);
2888 if (window) {
2889 touchedWindow.window = window;
2890 i += 1;
2891 } else {
Jeff Brownb6997262010-10-08 22:31:17 -07002892#if DEBUG_FOCUS
2893 LOGD("Touched window was removed: %s", touchedWindow.channel->getName().string());
2894#endif
Jeff Brownb6997262010-10-08 22:31:17 -07002895 synthesizeCancelationEventsForInputChannelLocked(touchedWindow.channel,
2896 InputState::CANCEL_POINTER_EVENTS, "touched window was removed");
Jeff Brownaf48cae2010-10-15 16:20:51 -07002897 mTouchState.windows.removeAt(i);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002898 }
2899 }
Jeff Brownb88102f2010-09-08 11:49:43 -07002900
Jeff Browna032cc02011-03-07 16:56:21 -08002901 // Recover the last hovered window.
2902 if (oldLastHoverWindowChannel != NULL) {
2903 mLastHoverWindow = getWindowLocked(oldLastHoverWindowChannel);
2904 oldLastHoverWindowChannel.clear();
2905 }
2906
Jeff Brownb88102f2010-09-08 11:49:43 -07002907#if DEBUG_FOCUS
Jeff Brownb6997262010-10-08 22:31:17 -07002908 //logDispatchStateLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -07002909#endif
2910 } // release lock
2911
2912 // Wake up poll loop since it may need to make new input dispatching choices.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002913 mLooper->wake();
Jeff Brownb88102f2010-09-08 11:49:43 -07002914}
2915
2916void InputDispatcher::setFocusedApplication(const InputApplication* inputApplication) {
2917#if DEBUG_FOCUS
2918 LOGD("setFocusedApplication");
2919#endif
2920 { // acquire lock
2921 AutoMutex _l(mLock);
2922
2923 releaseFocusedApplicationLocked();
2924
2925 if (inputApplication) {
2926 mFocusedApplicationStorage = *inputApplication;
2927 mFocusedApplication = & mFocusedApplicationStorage;
2928 }
2929
2930#if DEBUG_FOCUS
Jeff Brownb6997262010-10-08 22:31:17 -07002931 //logDispatchStateLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -07002932#endif
2933 } // release lock
2934
2935 // Wake up poll loop since it may need to make new input dispatching choices.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002936 mLooper->wake();
Jeff Brownb88102f2010-09-08 11:49:43 -07002937}
2938
2939void InputDispatcher::releaseFocusedApplicationLocked() {
2940 if (mFocusedApplication) {
2941 mFocusedApplication = NULL;
Jeff Brown928e0542011-01-10 11:17:36 -08002942 mFocusedApplicationStorage.inputApplicationHandle.clear();
Jeff Brownb88102f2010-09-08 11:49:43 -07002943 }
2944}
2945
2946void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
2947#if DEBUG_FOCUS
2948 LOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
2949#endif
2950
2951 bool changed;
2952 { // acquire lock
2953 AutoMutex _l(mLock);
2954
2955 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
Jeff Brown120a4592010-10-27 18:43:51 -07002956 if (mDispatchFrozen && !frozen) {
Jeff Brownb88102f2010-09-08 11:49:43 -07002957 resetANRTimeoutsLocked();
2958 }
2959
Jeff Brown120a4592010-10-27 18:43:51 -07002960 if (mDispatchEnabled && !enabled) {
2961 resetAndDropEverythingLocked("dispatcher is being disabled");
2962 }
2963
Jeff Brownb88102f2010-09-08 11:49:43 -07002964 mDispatchEnabled = enabled;
2965 mDispatchFrozen = frozen;
2966 changed = true;
2967 } else {
2968 changed = false;
2969 }
2970
2971#if DEBUG_FOCUS
Jeff Brownb6997262010-10-08 22:31:17 -07002972 //logDispatchStateLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -07002973#endif
2974 } // release lock
2975
2976 if (changed) {
2977 // Wake up poll loop since it may need to make new input dispatching choices.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002978 mLooper->wake();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002979 }
2980}
2981
Jeff Browne6504122010-09-27 14:52:15 -07002982bool InputDispatcher::transferTouchFocus(const sp<InputChannel>& fromChannel,
2983 const sp<InputChannel>& toChannel) {
2984#if DEBUG_FOCUS
2985 LOGD("transferTouchFocus: fromChannel=%s, toChannel=%s",
2986 fromChannel->getName().string(), toChannel->getName().string());
2987#endif
2988 { // acquire lock
2989 AutoMutex _l(mLock);
2990
2991 const InputWindow* fromWindow = getWindowLocked(fromChannel);
2992 const InputWindow* toWindow = getWindowLocked(toChannel);
2993 if (! fromWindow || ! toWindow) {
2994#if DEBUG_FOCUS
2995 LOGD("Cannot transfer focus because from or to window not found.");
2996#endif
2997 return false;
2998 }
2999 if (fromWindow == toWindow) {
3000#if DEBUG_FOCUS
3001 LOGD("Trivial transfer to same window.");
3002#endif
3003 return true;
3004 }
3005
3006 bool found = false;
3007 for (size_t i = 0; i < mTouchState.windows.size(); i++) {
3008 const TouchedWindow& touchedWindow = mTouchState.windows[i];
3009 if (touchedWindow.window == fromWindow) {
3010 int32_t oldTargetFlags = touchedWindow.targetFlags;
3011 BitSet32 pointerIds = touchedWindow.pointerIds;
3012
3013 mTouchState.windows.removeAt(i);
3014
Jeff Brown46e75292010-11-10 16:53:45 -08003015 int32_t newTargetFlags = oldTargetFlags
Jeff Browna032cc02011-03-07 16:56:21 -08003016 & (InputTarget::FLAG_FOREGROUND
3017 | InputTarget::FLAG_SPLIT | InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Browne6504122010-09-27 14:52:15 -07003018 mTouchState.addOrUpdateWindow(toWindow, newTargetFlags, pointerIds);
3019
3020 found = true;
3021 break;
3022 }
3023 }
3024
3025 if (! found) {
3026#if DEBUG_FOCUS
3027 LOGD("Focus transfer failed because from window did not have focus.");
3028#endif
3029 return false;
3030 }
3031
Jeff Brown9c9f1a32010-10-11 18:32:20 -07003032 ssize_t fromConnectionIndex = getConnectionIndexLocked(fromChannel);
3033 ssize_t toConnectionIndex = getConnectionIndexLocked(toChannel);
3034 if (fromConnectionIndex >= 0 && toConnectionIndex >= 0) {
3035 sp<Connection> fromConnection = mConnectionsByReceiveFd.valueAt(fromConnectionIndex);
3036 sp<Connection> toConnection = mConnectionsByReceiveFd.valueAt(toConnectionIndex);
3037
3038 fromConnection->inputState.copyPointerStateTo(toConnection->inputState);
3039 synthesizeCancelationEventsForConnectionLocked(fromConnection,
3040 InputState::CANCEL_POINTER_EVENTS,
3041 "transferring touch focus from this window to another window");
3042 }
3043
Jeff Browne6504122010-09-27 14:52:15 -07003044#if DEBUG_FOCUS
3045 logDispatchStateLocked();
3046#endif
3047 } // release lock
3048
3049 // Wake up poll loop since it may need to make new input dispatching choices.
3050 mLooper->wake();
3051 return true;
3052}
3053
Jeff Brown120a4592010-10-27 18:43:51 -07003054void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
3055#if DEBUG_FOCUS
3056 LOGD("Resetting and dropping all events (%s).", reason);
3057#endif
3058
3059 synthesizeCancelationEventsForAllConnectionsLocked(InputState::CANCEL_ALL_EVENTS, reason);
3060
3061 resetKeyRepeatLocked();
3062 releasePendingEventLocked();
3063 drainInboundQueueLocked();
3064 resetTargetsLocked();
3065
3066 mTouchState.reset();
3067}
3068
Jeff Brownb88102f2010-09-08 11:49:43 -07003069void InputDispatcher::logDispatchStateLocked() {
3070 String8 dump;
3071 dumpDispatchStateLocked(dump);
Jeff Brown2a95c2a2010-09-16 12:31:46 -07003072
3073 char* text = dump.lockBuffer(dump.size());
3074 char* start = text;
3075 while (*start != '\0') {
3076 char* end = strchr(start, '\n');
3077 if (*end == '\n') {
3078 *(end++) = '\0';
3079 }
3080 LOGD("%s", start);
3081 start = end;
3082 }
Jeff Brownb88102f2010-09-08 11:49:43 -07003083}
3084
3085void InputDispatcher::dumpDispatchStateLocked(String8& dump) {
Jeff Brownf2f487182010-10-01 17:46:21 -07003086 dump.appendFormat(INDENT "DispatchEnabled: %d\n", mDispatchEnabled);
3087 dump.appendFormat(INDENT "DispatchFrozen: %d\n", mDispatchFrozen);
Jeff Brownb88102f2010-09-08 11:49:43 -07003088
3089 if (mFocusedApplication) {
Jeff Brownf2f487182010-10-01 17:46:21 -07003090 dump.appendFormat(INDENT "FocusedApplication: name='%s', dispatchingTimeout=%0.3fms\n",
Jeff Brownb88102f2010-09-08 11:49:43 -07003091 mFocusedApplication->name.string(),
3092 mFocusedApplication->dispatchingTimeout / 1000000.0);
3093 } else {
Jeff Brownf2f487182010-10-01 17:46:21 -07003094 dump.append(INDENT "FocusedApplication: <null>\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003095 }
Jeff Brownf2f487182010-10-01 17:46:21 -07003096 dump.appendFormat(INDENT "FocusedWindow: name='%s'\n",
Jeff Brown2a95c2a2010-09-16 12:31:46 -07003097 mFocusedWindow != NULL ? mFocusedWindow->name.string() : "<null>");
Jeff Brownf2f487182010-10-01 17:46:21 -07003098
3099 dump.appendFormat(INDENT "TouchDown: %s\n", toString(mTouchState.down));
3100 dump.appendFormat(INDENT "TouchSplit: %s\n", toString(mTouchState.split));
Jeff Brown95712852011-01-04 19:41:59 -08003101 dump.appendFormat(INDENT "TouchDeviceId: %d\n", mTouchState.deviceId);
Jeff Brown58a2da82011-01-25 16:02:22 -08003102 dump.appendFormat(INDENT "TouchSource: 0x%08x\n", mTouchState.source);
Jeff Brownf2f487182010-10-01 17:46:21 -07003103 if (!mTouchState.windows.isEmpty()) {
3104 dump.append(INDENT "TouchedWindows:\n");
3105 for (size_t i = 0; i < mTouchState.windows.size(); i++) {
3106 const TouchedWindow& touchedWindow = mTouchState.windows[i];
3107 dump.appendFormat(INDENT2 "%d: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
3108 i, touchedWindow.window->name.string(), touchedWindow.pointerIds.value,
3109 touchedWindow.targetFlags);
3110 }
3111 } else {
3112 dump.append(INDENT "TouchedWindows: <none>\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003113 }
3114
Jeff Brownf2f487182010-10-01 17:46:21 -07003115 if (!mWindows.isEmpty()) {
3116 dump.append(INDENT "Windows:\n");
3117 for (size_t i = 0; i < mWindows.size(); i++) {
3118 const InputWindow& window = mWindows[i];
3119 dump.appendFormat(INDENT2 "%d: name='%s', paused=%s, hasFocus=%s, hasWallpaper=%s, "
3120 "visible=%s, canReceiveKeys=%s, flags=0x%08x, type=0x%08x, layer=%d, "
3121 "frame=[%d,%d][%d,%d], "
Jeff Brownfbf09772011-01-16 14:06:57 -08003122 "touchableRegion=",
Jeff Brownf2f487182010-10-01 17:46:21 -07003123 i, window.name.string(),
3124 toString(window.paused),
3125 toString(window.hasFocus),
3126 toString(window.hasWallpaper),
3127 toString(window.visible),
3128 toString(window.canReceiveKeys),
3129 window.layoutParamsFlags, window.layoutParamsType,
3130 window.layer,
3131 window.frameLeft, window.frameTop,
Jeff Brownfbf09772011-01-16 14:06:57 -08003132 window.frameRight, window.frameBottom);
3133 dumpRegion(dump, window.touchableRegion);
3134 dump.appendFormat(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%0.3fms\n",
Jeff Brownf2f487182010-10-01 17:46:21 -07003135 window.ownerPid, window.ownerUid,
3136 window.dispatchingTimeout / 1000000.0);
3137 }
3138 } else {
3139 dump.append(INDENT "Windows: <none>\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003140 }
3141
Jeff Brownf2f487182010-10-01 17:46:21 -07003142 if (!mMonitoringChannels.isEmpty()) {
3143 dump.append(INDENT "MonitoringChannels:\n");
3144 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
3145 const sp<InputChannel>& channel = mMonitoringChannels[i];
3146 dump.appendFormat(INDENT2 "%d: '%s'\n", i, channel->getName().string());
3147 }
3148 } else {
3149 dump.append(INDENT "MonitoringChannels: <none>\n");
3150 }
Jeff Brown519e0242010-09-15 15:18:56 -07003151
Jeff Brownf2f487182010-10-01 17:46:21 -07003152 dump.appendFormat(INDENT "InboundQueue: length=%u\n", mInboundQueue.count());
3153
3154 if (!mActiveConnections.isEmpty()) {
3155 dump.append(INDENT "ActiveConnections:\n");
3156 for (size_t i = 0; i < mActiveConnections.size(); i++) {
3157 const Connection* connection = mActiveConnections[i];
Jeff Brown76860e32010-10-25 17:37:46 -07003158 dump.appendFormat(INDENT2 "%d: '%s', status=%s, outboundQueueLength=%u, "
Jeff Brownb6997262010-10-08 22:31:17 -07003159 "inputState.isNeutral=%s\n",
Jeff Brownf2f487182010-10-01 17:46:21 -07003160 i, connection->getInputChannelName(), connection->getStatusLabel(),
3161 connection->outboundQueue.count(),
Jeff Brownb6997262010-10-08 22:31:17 -07003162 toString(connection->inputState.isNeutral()));
Jeff Brownf2f487182010-10-01 17:46:21 -07003163 }
3164 } else {
3165 dump.append(INDENT "ActiveConnections: <none>\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003166 }
3167
3168 if (isAppSwitchPendingLocked()) {
Jeff Brownf2f487182010-10-01 17:46:21 -07003169 dump.appendFormat(INDENT "AppSwitch: pending, due in %01.1fms\n",
Jeff Brownb88102f2010-09-08 11:49:43 -07003170 (mAppSwitchDueTime - now()) / 1000000.0);
3171 } else {
Jeff Brownf2f487182010-10-01 17:46:21 -07003172 dump.append(INDENT "AppSwitch: not pending\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003173 }
3174}
3175
Jeff Brown928e0542011-01-10 11:17:36 -08003176status_t InputDispatcher::registerInputChannel(const sp<InputChannel>& inputChannel,
3177 const sp<InputWindowHandle>& inputWindowHandle, bool monitor) {
Jeff Brown9c3cda02010-06-15 01:31:58 -07003178#if DEBUG_REGISTRATION
Jeff Brownb88102f2010-09-08 11:49:43 -07003179 LOGD("channel '%s' ~ registerInputChannel - monitor=%s", inputChannel->getName().string(),
3180 toString(monitor));
Jeff Brown9c3cda02010-06-15 01:31:58 -07003181#endif
3182
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003183 { // acquire lock
3184 AutoMutex _l(mLock);
3185
Jeff Brown519e0242010-09-15 15:18:56 -07003186 if (getConnectionIndexLocked(inputChannel) >= 0) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003187 LOGW("Attempted to register already registered input channel '%s'",
3188 inputChannel->getName().string());
3189 return BAD_VALUE;
3190 }
3191
Jeff Brown928e0542011-01-10 11:17:36 -08003192 sp<Connection> connection = new Connection(inputChannel, inputWindowHandle);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003193 status_t status = connection->initialize();
3194 if (status) {
3195 LOGE("Failed to initialize input publisher for input channel '%s', status=%d",
3196 inputChannel->getName().string(), status);
3197 return status;
3198 }
3199
Jeff Brown2cbecea2010-08-17 15:59:26 -07003200 int32_t receiveFd = inputChannel->getReceivePipeFd();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003201 mConnectionsByReceiveFd.add(receiveFd, connection);
Jeff Brown9c3cda02010-06-15 01:31:58 -07003202
Jeff Brownb88102f2010-09-08 11:49:43 -07003203 if (monitor) {
3204 mMonitoringChannels.push(inputChannel);
3205 }
3206
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07003207 mLooper->addFd(receiveFd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
Jeff Brown2cbecea2010-08-17 15:59:26 -07003208
Jeff Brown9c3cda02010-06-15 01:31:58 -07003209 runCommandsLockedInterruptible();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003210 } // release lock
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003211 return OK;
3212}
3213
3214status_t InputDispatcher::unregisterInputChannel(const sp<InputChannel>& inputChannel) {
Jeff Brown9c3cda02010-06-15 01:31:58 -07003215#if DEBUG_REGISTRATION
Jeff Brown349703e2010-06-22 01:27:15 -07003216 LOGD("channel '%s' ~ unregisterInputChannel", inputChannel->getName().string());
Jeff Brown9c3cda02010-06-15 01:31:58 -07003217#endif
3218
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003219 { // acquire lock
3220 AutoMutex _l(mLock);
3221
Jeff Brown519e0242010-09-15 15:18:56 -07003222 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003223 if (connectionIndex < 0) {
3224 LOGW("Attempted to unregister already unregistered input channel '%s'",
3225 inputChannel->getName().string());
3226 return BAD_VALUE;
3227 }
3228
3229 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
3230 mConnectionsByReceiveFd.removeItemsAt(connectionIndex);
3231
3232 connection->status = Connection::STATUS_ZOMBIE;
3233
Jeff Brownb88102f2010-09-08 11:49:43 -07003234 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
3235 if (mMonitoringChannels[i] == inputChannel) {
3236 mMonitoringChannels.removeAt(i);
3237 break;
3238 }
3239 }
3240
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07003241 mLooper->removeFd(inputChannel->getReceivePipeFd());
Jeff Brown2cbecea2010-08-17 15:59:26 -07003242
Jeff Brown7fbdc842010-06-17 20:52:56 -07003243 nsecs_t currentTime = now();
Jeff Brownb6997262010-10-08 22:31:17 -07003244 abortBrokenDispatchCycleLocked(currentTime, connection);
Jeff Brown9c3cda02010-06-15 01:31:58 -07003245
3246 runCommandsLockedInterruptible();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003247 } // release lock
3248
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003249 // Wake the poll loop because removing the connection may have changed the current
3250 // synchronization state.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07003251 mLooper->wake();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003252 return OK;
3253}
3254
Jeff Brown519e0242010-09-15 15:18:56 -07003255ssize_t InputDispatcher::getConnectionIndexLocked(const sp<InputChannel>& inputChannel) {
Jeff Brown2cbecea2010-08-17 15:59:26 -07003256 ssize_t connectionIndex = mConnectionsByReceiveFd.indexOfKey(inputChannel->getReceivePipeFd());
3257 if (connectionIndex >= 0) {
3258 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
3259 if (connection->inputChannel.get() == inputChannel.get()) {
3260 return connectionIndex;
3261 }
3262 }
3263
3264 return -1;
3265}
3266
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003267void InputDispatcher::activateConnectionLocked(Connection* connection) {
3268 for (size_t i = 0; i < mActiveConnections.size(); i++) {
3269 if (mActiveConnections.itemAt(i) == connection) {
3270 return;
3271 }
3272 }
3273 mActiveConnections.add(connection);
3274}
3275
3276void InputDispatcher::deactivateConnectionLocked(Connection* connection) {
3277 for (size_t i = 0; i < mActiveConnections.size(); i++) {
3278 if (mActiveConnections.itemAt(i) == connection) {
3279 mActiveConnections.removeAt(i);
3280 return;
3281 }
3282 }
3283}
3284
Jeff Brown9c3cda02010-06-15 01:31:58 -07003285void InputDispatcher::onDispatchCycleStartedLocked(
Jeff Brown7fbdc842010-06-17 20:52:56 -07003286 nsecs_t currentTime, const sp<Connection>& connection) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003287}
3288
Jeff Brown9c3cda02010-06-15 01:31:58 -07003289void InputDispatcher::onDispatchCycleFinishedLocked(
Jeff Brown3915bb82010-11-05 15:02:16 -07003290 nsecs_t currentTime, const sp<Connection>& connection, bool handled) {
3291 CommandEntry* commandEntry = postCommandLocked(
3292 & InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
3293 commandEntry->connection = connection;
3294 commandEntry->handled = handled;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003295}
3296
Jeff Brown9c3cda02010-06-15 01:31:58 -07003297void InputDispatcher::onDispatchCycleBrokenLocked(
Jeff Brown7fbdc842010-06-17 20:52:56 -07003298 nsecs_t currentTime, const sp<Connection>& connection) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003299 LOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
3300 connection->getInputChannelName());
3301
Jeff Brown9c3cda02010-06-15 01:31:58 -07003302 CommandEntry* commandEntry = postCommandLocked(
3303 & InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
Jeff Brown7fbdc842010-06-17 20:52:56 -07003304 commandEntry->connection = connection;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003305}
3306
Jeff Brown519e0242010-09-15 15:18:56 -07003307void InputDispatcher::onANRLocked(
3308 nsecs_t currentTime, const InputApplication* application, const InputWindow* window,
3309 nsecs_t eventTime, nsecs_t waitStartTime) {
3310 LOGI("Application is not responding: %s. "
3311 "%01.1fms since event, %01.1fms since wait started",
3312 getApplicationWindowLabelLocked(application, window).string(),
3313 (currentTime - eventTime) / 1000000.0,
3314 (currentTime - waitStartTime) / 1000000.0);
3315
3316 CommandEntry* commandEntry = postCommandLocked(
3317 & InputDispatcher::doNotifyANRLockedInterruptible);
3318 if (application) {
Jeff Brown928e0542011-01-10 11:17:36 -08003319 commandEntry->inputApplicationHandle = application->inputApplicationHandle;
Jeff Brown519e0242010-09-15 15:18:56 -07003320 }
3321 if (window) {
Jeff Brown928e0542011-01-10 11:17:36 -08003322 commandEntry->inputWindowHandle = window->inputWindowHandle;
Jeff Brown519e0242010-09-15 15:18:56 -07003323 commandEntry->inputChannel = window->inputChannel;
3324 }
3325}
3326
Jeff Brownb88102f2010-09-08 11:49:43 -07003327void InputDispatcher::doNotifyConfigurationChangedInterruptible(
3328 CommandEntry* commandEntry) {
3329 mLock.unlock();
3330
3331 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
3332
3333 mLock.lock();
3334}
3335
Jeff Brown9c3cda02010-06-15 01:31:58 -07003336void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(
3337 CommandEntry* commandEntry) {
Jeff Brown7fbdc842010-06-17 20:52:56 -07003338 sp<Connection> connection = commandEntry->connection;
Jeff Brown9c3cda02010-06-15 01:31:58 -07003339
Jeff Brown7fbdc842010-06-17 20:52:56 -07003340 if (connection->status != Connection::STATUS_ZOMBIE) {
3341 mLock.unlock();
Jeff Brown9c3cda02010-06-15 01:31:58 -07003342
Jeff Brown928e0542011-01-10 11:17:36 -08003343 mPolicy->notifyInputChannelBroken(connection->inputWindowHandle);
Jeff Brown7fbdc842010-06-17 20:52:56 -07003344
3345 mLock.lock();
3346 }
Jeff Brown9c3cda02010-06-15 01:31:58 -07003347}
3348
Jeff Brown519e0242010-09-15 15:18:56 -07003349void InputDispatcher::doNotifyANRLockedInterruptible(
Jeff Brown9c3cda02010-06-15 01:31:58 -07003350 CommandEntry* commandEntry) {
Jeff Brown519e0242010-09-15 15:18:56 -07003351 mLock.unlock();
Jeff Brown9c3cda02010-06-15 01:31:58 -07003352
Jeff Brown519e0242010-09-15 15:18:56 -07003353 nsecs_t newTimeout = mPolicy->notifyANR(
Jeff Brown928e0542011-01-10 11:17:36 -08003354 commandEntry->inputApplicationHandle, commandEntry->inputWindowHandle);
Jeff Brown9c3cda02010-06-15 01:31:58 -07003355
Jeff Brown519e0242010-09-15 15:18:56 -07003356 mLock.lock();
Jeff Brown7fbdc842010-06-17 20:52:56 -07003357
Jeff Brown519e0242010-09-15 15:18:56 -07003358 resumeAfterTargetsNotReadyTimeoutLocked(newTimeout, commandEntry->inputChannel);
Jeff Brown9c3cda02010-06-15 01:31:58 -07003359}
3360
Jeff Brownb88102f2010-09-08 11:49:43 -07003361void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
3362 CommandEntry* commandEntry) {
3363 KeyEntry* entry = commandEntry->keyEntry;
Jeff Brown1f245102010-11-18 20:53:46 -08003364
3365 KeyEvent event;
3366 initializeKeyEvent(&event, entry);
Jeff Brownb88102f2010-09-08 11:49:43 -07003367
3368 mLock.unlock();
3369
Jeff Brown928e0542011-01-10 11:17:36 -08003370 bool consumed = mPolicy->interceptKeyBeforeDispatching(commandEntry->inputWindowHandle,
Jeff Brown1f245102010-11-18 20:53:46 -08003371 &event, entry->policyFlags);
Jeff Brownb88102f2010-09-08 11:49:43 -07003372
3373 mLock.lock();
3374
3375 entry->interceptKeyResult = consumed
3376 ? KeyEntry::INTERCEPT_KEY_RESULT_SKIP
3377 : KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
3378 mAllocator.releaseKeyEntry(entry);
3379}
3380
Jeff Brown3915bb82010-11-05 15:02:16 -07003381void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(
3382 CommandEntry* commandEntry) {
3383 sp<Connection> connection = commandEntry->connection;
3384 bool handled = commandEntry->handled;
3385
Jeff Brown49ed71d2010-12-06 17:13:33 -08003386 if (!connection->outboundQueue.isEmpty()) {
Jeff Brown3915bb82010-11-05 15:02:16 -07003387 DispatchEntry* dispatchEntry = connection->outboundQueue.headSentinel.next;
3388 if (dispatchEntry->inProgress
3389 && dispatchEntry->hasForegroundTarget()
3390 && dispatchEntry->eventEntry->type == EventEntry::TYPE_KEY) {
3391 KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry);
Jeff Brown49ed71d2010-12-06 17:13:33 -08003392 if (!(keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK)) {
3393 if (handled) {
3394 // If the application handled a non-fallback key, then immediately
3395 // cancel all fallback keys previously dispatched to the application.
3396 // This behavior will prevent chording with fallback keys (so they cannot
3397 // be used as modifiers) but it will ensure that fallback keys do not
3398 // get stuck. This takes care of the case where the application does not handle
3399 // the original DOWN so we generate a fallback DOWN but it does handle
Jeff Brownbfaf3b92011-02-22 15:00:50 -08003400 // the original UP in which case we want to send a fallback CANCEL.
Jeff Brown49ed71d2010-12-06 17:13:33 -08003401 synthesizeCancelationEventsForConnectionLocked(connection,
3402 InputState::CANCEL_FALLBACK_EVENTS,
Jeff Brownbfaf3b92011-02-22 15:00:50 -08003403 "application handled a non-fallback event, "
3404 "canceling all fallback events");
3405 connection->originalKeyCodeForFallback = -1;
Jeff Brown49ed71d2010-12-06 17:13:33 -08003406 } else {
Jeff Brownbfaf3b92011-02-22 15:00:50 -08003407 // If the application did not handle a non-fallback key, first check
3408 // that we are in a good state to handle the fallback key. Then ask
3409 // the policy what to do with it.
3410 if (connection->originalKeyCodeForFallback < 0) {
3411 if (keyEntry->action != AKEY_EVENT_ACTION_DOWN
3412 || keyEntry->repeatCount != 0) {
3413#if DEBUG_OUTBOUND_EVENT_DETAILS
3414 LOGD("Unhandled key event: Skipping fallback since this "
3415 "is not an initial down. "
3416 "keyCode=%d, action=%d, repeatCount=%d",
3417 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount);
3418#endif
3419 goto SkipFallback;
3420 }
3421
3422 // Start handling the fallback key on DOWN.
3423 connection->originalKeyCodeForFallback = keyEntry->keyCode;
3424 } else {
3425 if (keyEntry->keyCode != connection->originalKeyCodeForFallback) {
3426#if DEBUG_OUTBOUND_EVENT_DETAILS
3427 LOGD("Unhandled key event: Skipping fallback since there is "
3428 "already a different fallback in progress. "
3429 "keyCode=%d, originalKeyCodeForFallback=%d",
3430 keyEntry->keyCode, connection->originalKeyCodeForFallback);
3431#endif
3432 goto SkipFallback;
3433 }
3434
3435 // Finish handling the fallback key on UP.
3436 if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
3437 connection->originalKeyCodeForFallback = -1;
3438 }
3439 }
3440
3441#if DEBUG_OUTBOUND_EVENT_DETAILS
3442 LOGD("Unhandled key event: Asking policy to perform fallback action. "
3443 "keyCode=%d, action=%d, repeatCount=%d",
3444 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount);
3445#endif
Jeff Brown49ed71d2010-12-06 17:13:33 -08003446 KeyEvent event;
3447 initializeKeyEvent(&event, keyEntry);
Jeff Brown3915bb82010-11-05 15:02:16 -07003448
Jeff Brown49ed71d2010-12-06 17:13:33 -08003449 mLock.unlock();
Jeff Brown3915bb82010-11-05 15:02:16 -07003450
Jeff Brown928e0542011-01-10 11:17:36 -08003451 bool fallback = mPolicy->dispatchUnhandledKey(connection->inputWindowHandle,
Jeff Brown49ed71d2010-12-06 17:13:33 -08003452 &event, keyEntry->policyFlags, &event);
Jeff Brown3915bb82010-11-05 15:02:16 -07003453
Jeff Brown49ed71d2010-12-06 17:13:33 -08003454 mLock.lock();
3455
Jeff Brown00045a72010-12-09 18:10:30 -08003456 if (connection->status != Connection::STATUS_NORMAL) {
3457 return;
3458 }
3459
3460 assert(connection->outboundQueue.headSentinel.next == dispatchEntry);
3461
Jeff Brown49ed71d2010-12-06 17:13:33 -08003462 if (fallback) {
3463 // Restart the dispatch cycle using the fallback key.
3464 keyEntry->eventTime = event.getEventTime();
3465 keyEntry->deviceId = event.getDeviceId();
3466 keyEntry->source = event.getSource();
3467 keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
3468 keyEntry->keyCode = event.getKeyCode();
3469 keyEntry->scanCode = event.getScanCode();
3470 keyEntry->metaState = event.getMetaState();
3471 keyEntry->repeatCount = event.getRepeatCount();
3472 keyEntry->downTime = event.getDownTime();
3473 keyEntry->syntheticRepeat = false;
3474
Jeff Brownbfaf3b92011-02-22 15:00:50 -08003475#if DEBUG_OUTBOUND_EVENT_DETAILS
3476 LOGD("Unhandled key event: Dispatching fallback key. "
3477 "fallbackKeyCode=%d, fallbackMetaState=%08x",
3478 keyEntry->keyCode, keyEntry->metaState);
3479#endif
3480
Jeff Brown49ed71d2010-12-06 17:13:33 -08003481 dispatchEntry->inProgress = false;
3482 startDispatchCycleLocked(now(), connection);
3483 return;
3484 }
3485 }
3486 }
Jeff Brown3915bb82010-11-05 15:02:16 -07003487 }
3488 }
3489
Jeff Brownbfaf3b92011-02-22 15:00:50 -08003490SkipFallback:
Jeff Brown3915bb82010-11-05 15:02:16 -07003491 startNextDispatchCycleLocked(now(), connection);
3492}
3493
Jeff Brownb88102f2010-09-08 11:49:43 -07003494void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
3495 mLock.unlock();
3496
Jeff Brown01ce2e92010-09-26 22:20:12 -07003497 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
Jeff Brownb88102f2010-09-08 11:49:43 -07003498
3499 mLock.lock();
3500}
3501
Jeff Brown3915bb82010-11-05 15:02:16 -07003502void InputDispatcher::initializeKeyEvent(KeyEvent* event, const KeyEntry* entry) {
3503 event->initialize(entry->deviceId, entry->source, entry->action, entry->flags,
3504 entry->keyCode, entry->scanCode, entry->metaState, entry->repeatCount,
3505 entry->downTime, entry->eventTime);
3506}
3507
Jeff Brown519e0242010-09-15 15:18:56 -07003508void InputDispatcher::updateDispatchStatisticsLocked(nsecs_t currentTime, const EventEntry* entry,
3509 int32_t injectionResult, nsecs_t timeSpentWaitingForApplication) {
3510 // TODO Write some statistics about how long we spend waiting.
Jeff Brownb88102f2010-09-08 11:49:43 -07003511}
3512
3513void InputDispatcher::dump(String8& dump) {
Jeff Brownf2f487182010-10-01 17:46:21 -07003514 dump.append("Input Dispatcher State:\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003515 dumpDispatchStateLocked(dump);
3516}
3517
Jeff Brown9c3cda02010-06-15 01:31:58 -07003518
Jeff Brown519e0242010-09-15 15:18:56 -07003519// --- InputDispatcher::Queue ---
3520
3521template <typename T>
3522uint32_t InputDispatcher::Queue<T>::count() const {
3523 uint32_t result = 0;
3524 for (const T* entry = headSentinel.next; entry != & tailSentinel; entry = entry->next) {
3525 result += 1;
3526 }
3527 return result;
3528}
3529
3530
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003531// --- InputDispatcher::Allocator ---
3532
3533InputDispatcher::Allocator::Allocator() {
3534}
3535
Jeff Brown01ce2e92010-09-26 22:20:12 -07003536InputDispatcher::InjectionState*
3537InputDispatcher::Allocator::obtainInjectionState(int32_t injectorPid, int32_t injectorUid) {
3538 InjectionState* injectionState = mInjectionStatePool.alloc();
3539 injectionState->refCount = 1;
3540 injectionState->injectorPid = injectorPid;
3541 injectionState->injectorUid = injectorUid;
3542 injectionState->injectionIsAsync = false;
3543 injectionState->injectionResult = INPUT_EVENT_INJECTION_PENDING;
3544 injectionState->pendingForegroundDispatches = 0;
3545 return injectionState;
3546}
3547
Jeff Brown7fbdc842010-06-17 20:52:56 -07003548void InputDispatcher::Allocator::initializeEventEntry(EventEntry* entry, int32_t type,
Jeff Brownb6997262010-10-08 22:31:17 -07003549 nsecs_t eventTime, uint32_t policyFlags) {
Jeff Brown7fbdc842010-06-17 20:52:56 -07003550 entry->type = type;
3551 entry->refCount = 1;
3552 entry->dispatchInProgress = false;
Christopher Tatee91a5db2010-06-23 16:50:30 -07003553 entry->eventTime = eventTime;
Jeff Brownb6997262010-10-08 22:31:17 -07003554 entry->policyFlags = policyFlags;
Jeff Brown01ce2e92010-09-26 22:20:12 -07003555 entry->injectionState = NULL;
3556}
3557
3558void InputDispatcher::Allocator::releaseEventEntryInjectionState(EventEntry* entry) {
3559 if (entry->injectionState) {
3560 releaseInjectionState(entry->injectionState);
3561 entry->injectionState = NULL;
3562 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07003563}
3564
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003565InputDispatcher::ConfigurationChangedEntry*
Jeff Brown7fbdc842010-06-17 20:52:56 -07003566InputDispatcher::Allocator::obtainConfigurationChangedEntry(nsecs_t eventTime) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003567 ConfigurationChangedEntry* entry = mConfigurationChangeEntryPool.alloc();
Jeff Brownb6997262010-10-08 22:31:17 -07003568 initializeEventEntry(entry, EventEntry::TYPE_CONFIGURATION_CHANGED, eventTime, 0);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003569 return entry;
3570}
3571
Jeff Brown7fbdc842010-06-17 20:52:56 -07003572InputDispatcher::KeyEntry* InputDispatcher::Allocator::obtainKeyEntry(nsecs_t eventTime,
Jeff Brown58a2da82011-01-25 16:02:22 -08003573 int32_t deviceId, uint32_t source, uint32_t policyFlags, int32_t action,
Jeff Brown7fbdc842010-06-17 20:52:56 -07003574 int32_t flags, int32_t keyCode, int32_t scanCode, int32_t metaState,
3575 int32_t repeatCount, nsecs_t downTime) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003576 KeyEntry* entry = mKeyEntryPool.alloc();
Jeff Brownb6997262010-10-08 22:31:17 -07003577 initializeEventEntry(entry, EventEntry::TYPE_KEY, eventTime, policyFlags);
Jeff Brown7fbdc842010-06-17 20:52:56 -07003578
3579 entry->deviceId = deviceId;
Jeff Brownc5ed5912010-07-14 18:48:53 -07003580 entry->source = source;
Jeff Brown7fbdc842010-06-17 20:52:56 -07003581 entry->action = action;
3582 entry->flags = flags;
3583 entry->keyCode = keyCode;
3584 entry->scanCode = scanCode;
3585 entry->metaState = metaState;
3586 entry->repeatCount = repeatCount;
3587 entry->downTime = downTime;
Jeff Brownb88102f2010-09-08 11:49:43 -07003588 entry->syntheticRepeat = false;
3589 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003590 return entry;
3591}
3592
Jeff Brown7fbdc842010-06-17 20:52:56 -07003593InputDispatcher::MotionEntry* InputDispatcher::Allocator::obtainMotionEntry(nsecs_t eventTime,
Jeff Brown58a2da82011-01-25 16:02:22 -08003594 int32_t deviceId, uint32_t source, uint32_t policyFlags, int32_t action, int32_t flags,
Jeff Brown7fbdc842010-06-17 20:52:56 -07003595 int32_t metaState, int32_t edgeFlags, float xPrecision, float yPrecision,
3596 nsecs_t downTime, uint32_t pointerCount,
3597 const int32_t* pointerIds, const PointerCoords* pointerCoords) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003598 MotionEntry* entry = mMotionEntryPool.alloc();
Jeff Brownb6997262010-10-08 22:31:17 -07003599 initializeEventEntry(entry, EventEntry::TYPE_MOTION, eventTime, policyFlags);
Jeff Brown7fbdc842010-06-17 20:52:56 -07003600
3601 entry->eventTime = eventTime;
3602 entry->deviceId = deviceId;
Jeff Brownc5ed5912010-07-14 18:48:53 -07003603 entry->source = source;
Jeff Brown7fbdc842010-06-17 20:52:56 -07003604 entry->action = action;
Jeff Brown85a31762010-09-01 17:01:00 -07003605 entry->flags = flags;
Jeff Brown7fbdc842010-06-17 20:52:56 -07003606 entry->metaState = metaState;
3607 entry->edgeFlags = edgeFlags;
3608 entry->xPrecision = xPrecision;
3609 entry->yPrecision = yPrecision;
3610 entry->downTime = downTime;
3611 entry->pointerCount = pointerCount;
3612 entry->firstSample.eventTime = eventTime;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003613 entry->firstSample.next = NULL;
Jeff Brown7fbdc842010-06-17 20:52:56 -07003614 entry->lastSample = & entry->firstSample;
3615 for (uint32_t i = 0; i < pointerCount; i++) {
3616 entry->pointerIds[i] = pointerIds[i];
Jeff Brownace13b12011-03-09 17:39:48 -08003617 entry->firstSample.pointerCoords[i].copyFrom(pointerCoords[i]);
Jeff Brown7fbdc842010-06-17 20:52:56 -07003618 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003619 return entry;
3620}
3621
3622InputDispatcher::DispatchEntry* InputDispatcher::Allocator::obtainDispatchEntry(
Jeff Brownb88102f2010-09-08 11:49:43 -07003623 EventEntry* eventEntry,
Jeff Brown519e0242010-09-15 15:18:56 -07003624 int32_t targetFlags, float xOffset, float yOffset) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003625 DispatchEntry* entry = mDispatchEntryPool.alloc();
3626 entry->eventEntry = eventEntry;
3627 eventEntry->refCount += 1;
Jeff Brownb88102f2010-09-08 11:49:43 -07003628 entry->targetFlags = targetFlags;
3629 entry->xOffset = xOffset;
3630 entry->yOffset = yOffset;
Jeff Brownb88102f2010-09-08 11:49:43 -07003631 entry->inProgress = false;
3632 entry->headMotionSample = NULL;
3633 entry->tailMotionSample = NULL;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003634 return entry;
3635}
3636
Jeff Brown9c3cda02010-06-15 01:31:58 -07003637InputDispatcher::CommandEntry* InputDispatcher::Allocator::obtainCommandEntry(Command command) {
3638 CommandEntry* entry = mCommandEntryPool.alloc();
3639 entry->command = command;
3640 return entry;
3641}
3642
Jeff Brown01ce2e92010-09-26 22:20:12 -07003643void InputDispatcher::Allocator::releaseInjectionState(InjectionState* injectionState) {
3644 injectionState->refCount -= 1;
3645 if (injectionState->refCount == 0) {
3646 mInjectionStatePool.free(injectionState);
3647 } else {
3648 assert(injectionState->refCount > 0);
3649 }
3650}
3651
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003652void InputDispatcher::Allocator::releaseEventEntry(EventEntry* entry) {
3653 switch (entry->type) {
3654 case EventEntry::TYPE_CONFIGURATION_CHANGED:
3655 releaseConfigurationChangedEntry(static_cast<ConfigurationChangedEntry*>(entry));
3656 break;
3657 case EventEntry::TYPE_KEY:
3658 releaseKeyEntry(static_cast<KeyEntry*>(entry));
3659 break;
3660 case EventEntry::TYPE_MOTION:
3661 releaseMotionEntry(static_cast<MotionEntry*>(entry));
3662 break;
3663 default:
3664 assert(false);
3665 break;
3666 }
3667}
3668
3669void InputDispatcher::Allocator::releaseConfigurationChangedEntry(
3670 ConfigurationChangedEntry* entry) {
3671 entry->refCount -= 1;
3672 if (entry->refCount == 0) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07003673 releaseEventEntryInjectionState(entry);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003674 mConfigurationChangeEntryPool.free(entry);
3675 } else {
3676 assert(entry->refCount > 0);
3677 }
3678}
3679
3680void InputDispatcher::Allocator::releaseKeyEntry(KeyEntry* entry) {
3681 entry->refCount -= 1;
3682 if (entry->refCount == 0) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07003683 releaseEventEntryInjectionState(entry);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003684 mKeyEntryPool.free(entry);
3685 } else {
3686 assert(entry->refCount > 0);
3687 }
3688}
3689
3690void InputDispatcher::Allocator::releaseMotionEntry(MotionEntry* entry) {
3691 entry->refCount -= 1;
3692 if (entry->refCount == 0) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07003693 releaseEventEntryInjectionState(entry);
Jeff Brown9c3cda02010-06-15 01:31:58 -07003694 for (MotionSample* sample = entry->firstSample.next; sample != NULL; ) {
3695 MotionSample* next = sample->next;
3696 mMotionSamplePool.free(sample);
3697 sample = next;
3698 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003699 mMotionEntryPool.free(entry);
3700 } else {
3701 assert(entry->refCount > 0);
3702 }
3703}
3704
Jeff Browna032cc02011-03-07 16:56:21 -08003705void InputDispatcher::Allocator::freeMotionSample(MotionSample* sample) {
3706 mMotionSamplePool.free(sample);
3707}
3708
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003709void InputDispatcher::Allocator::releaseDispatchEntry(DispatchEntry* entry) {
3710 releaseEventEntry(entry->eventEntry);
3711 mDispatchEntryPool.free(entry);
3712}
3713
Jeff Brown9c3cda02010-06-15 01:31:58 -07003714void InputDispatcher::Allocator::releaseCommandEntry(CommandEntry* entry) {
3715 mCommandEntryPool.free(entry);
3716}
3717
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003718void InputDispatcher::Allocator::appendMotionSample(MotionEntry* motionEntry,
Jeff Brown7fbdc842010-06-17 20:52:56 -07003719 nsecs_t eventTime, const PointerCoords* pointerCoords) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003720 MotionSample* sample = mMotionSamplePool.alloc();
3721 sample->eventTime = eventTime;
Jeff Brown7fbdc842010-06-17 20:52:56 -07003722 uint32_t pointerCount = motionEntry->pointerCount;
3723 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brownace13b12011-03-09 17:39:48 -08003724 sample->pointerCoords[i].copyFrom(pointerCoords[i]);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003725 }
3726
3727 sample->next = NULL;
3728 motionEntry->lastSample->next = sample;
3729 motionEntry->lastSample = sample;
3730}
3731
Jeff Brown01ce2e92010-09-26 22:20:12 -07003732void InputDispatcher::Allocator::recycleKeyEntry(KeyEntry* keyEntry) {
3733 releaseEventEntryInjectionState(keyEntry);
Jeff Brownb88102f2010-09-08 11:49:43 -07003734
Jeff Brown01ce2e92010-09-26 22:20:12 -07003735 keyEntry->dispatchInProgress = false;
3736 keyEntry->syntheticRepeat = false;
3737 keyEntry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
Jeff Brownb88102f2010-09-08 11:49:43 -07003738}
3739
3740
Jeff Brownae9fc032010-08-18 15:51:08 -07003741// --- InputDispatcher::MotionEntry ---
3742
3743uint32_t InputDispatcher::MotionEntry::countSamples() const {
3744 uint32_t count = 1;
3745 for (MotionSample* sample = firstSample.next; sample != NULL; sample = sample->next) {
3746 count += 1;
3747 }
3748 return count;
3749}
3750
Jeff Brownb88102f2010-09-08 11:49:43 -07003751
3752// --- InputDispatcher::InputState ---
3753
Jeff Brownb6997262010-10-08 22:31:17 -07003754InputDispatcher::InputState::InputState() {
Jeff Brownb88102f2010-09-08 11:49:43 -07003755}
3756
3757InputDispatcher::InputState::~InputState() {
3758}
3759
3760bool InputDispatcher::InputState::isNeutral() const {
3761 return mKeyMementos.isEmpty() && mMotionMementos.isEmpty();
3762}
3763
Jeff Browna032cc02011-03-07 16:56:21 -08003764void InputDispatcher::InputState::trackEvent(const EventEntry* entry, int32_t action) {
Jeff Brownb88102f2010-09-08 11:49:43 -07003765 switch (entry->type) {
3766 case EventEntry::TYPE_KEY:
Jeff Browna032cc02011-03-07 16:56:21 -08003767 trackKey(static_cast<const KeyEntry*>(entry), action);
Jeff Browncc0c1592011-02-19 05:07:28 -08003768 break;
Jeff Brownb88102f2010-09-08 11:49:43 -07003769
3770 case EventEntry::TYPE_MOTION:
Jeff Browna032cc02011-03-07 16:56:21 -08003771 trackMotion(static_cast<const MotionEntry*>(entry), action);
Jeff Browncc0c1592011-02-19 05:07:28 -08003772 break;
Jeff Brownb88102f2010-09-08 11:49:43 -07003773 }
3774}
3775
Jeff Browna032cc02011-03-07 16:56:21 -08003776void InputDispatcher::InputState::trackKey(const KeyEntry* entry, int32_t action) {
Jeff Brownb88102f2010-09-08 11:49:43 -07003777 for (size_t i = 0; i < mKeyMementos.size(); i++) {
3778 KeyMemento& memento = mKeyMementos.editItemAt(i);
3779 if (memento.deviceId == entry->deviceId
3780 && memento.source == entry->source
3781 && memento.keyCode == entry->keyCode
3782 && memento.scanCode == entry->scanCode) {
3783 switch (action) {
3784 case AKEY_EVENT_ACTION_UP:
3785 mKeyMementos.removeAt(i);
Jeff Browncc0c1592011-02-19 05:07:28 -08003786 return;
Jeff Brownb88102f2010-09-08 11:49:43 -07003787
3788 case AKEY_EVENT_ACTION_DOWN:
Jeff Browncc0c1592011-02-19 05:07:28 -08003789 mKeyMementos.removeAt(i);
3790 goto Found;
Jeff Brownb88102f2010-09-08 11:49:43 -07003791
3792 default:
Jeff Browncc0c1592011-02-19 05:07:28 -08003793 return;
Jeff Brownb88102f2010-09-08 11:49:43 -07003794 }
3795 }
3796 }
3797
Jeff Browncc0c1592011-02-19 05:07:28 -08003798Found:
3799 if (action == AKEY_EVENT_ACTION_DOWN) {
Jeff Brownb88102f2010-09-08 11:49:43 -07003800 mKeyMementos.push();
3801 KeyMemento& memento = mKeyMementos.editTop();
3802 memento.deviceId = entry->deviceId;
3803 memento.source = entry->source;
3804 memento.keyCode = entry->keyCode;
3805 memento.scanCode = entry->scanCode;
Jeff Brown49ed71d2010-12-06 17:13:33 -08003806 memento.flags = entry->flags;
Jeff Brownb88102f2010-09-08 11:49:43 -07003807 memento.downTime = entry->downTime;
Jeff Brownb88102f2010-09-08 11:49:43 -07003808 }
3809}
3810
Jeff Browna032cc02011-03-07 16:56:21 -08003811void InputDispatcher::InputState::trackMotion(const MotionEntry* entry, int32_t action) {
3812 int32_t actionMasked = action & AMOTION_EVENT_ACTION_MASK;
Jeff Brownb88102f2010-09-08 11:49:43 -07003813 for (size_t i = 0; i < mMotionMementos.size(); i++) {
3814 MotionMemento& memento = mMotionMementos.editItemAt(i);
3815 if (memento.deviceId == entry->deviceId
3816 && memento.source == entry->source) {
Jeff Browna032cc02011-03-07 16:56:21 -08003817 switch (actionMasked) {
Jeff Brownb88102f2010-09-08 11:49:43 -07003818 case AMOTION_EVENT_ACTION_UP:
3819 case AMOTION_EVENT_ACTION_CANCEL:
Jeff Browna032cc02011-03-07 16:56:21 -08003820 case AMOTION_EVENT_ACTION_HOVER_ENTER:
Jeff Browncc0c1592011-02-19 05:07:28 -08003821 case AMOTION_EVENT_ACTION_HOVER_MOVE:
Jeff Browna032cc02011-03-07 16:56:21 -08003822 case AMOTION_EVENT_ACTION_HOVER_EXIT:
Jeff Brownb88102f2010-09-08 11:49:43 -07003823 mMotionMementos.removeAt(i);
Jeff Browncc0c1592011-02-19 05:07:28 -08003824 return;
Jeff Brownb88102f2010-09-08 11:49:43 -07003825
3826 case AMOTION_EVENT_ACTION_DOWN:
Jeff Browncc0c1592011-02-19 05:07:28 -08003827 mMotionMementos.removeAt(i);
3828 goto Found;
Jeff Brownb88102f2010-09-08 11:49:43 -07003829
3830 case AMOTION_EVENT_ACTION_POINTER_UP:
Jeff Browncc0c1592011-02-19 05:07:28 -08003831 case AMOTION_EVENT_ACTION_POINTER_DOWN:
Jeff Brownb88102f2010-09-08 11:49:43 -07003832 case AMOTION_EVENT_ACTION_MOVE:
Jeff Browncc0c1592011-02-19 05:07:28 -08003833 memento.setPointers(entry);
3834 return;
Jeff Brownb88102f2010-09-08 11:49:43 -07003835
3836 default:
Jeff Browncc0c1592011-02-19 05:07:28 -08003837 return;
Jeff Brownb88102f2010-09-08 11:49:43 -07003838 }
3839 }
3840 }
3841
Jeff Browncc0c1592011-02-19 05:07:28 -08003842Found:
Jeff Browna032cc02011-03-07 16:56:21 -08003843 switch (actionMasked) {
3844 case AMOTION_EVENT_ACTION_DOWN:
3845 case AMOTION_EVENT_ACTION_HOVER_ENTER:
3846 case AMOTION_EVENT_ACTION_HOVER_MOVE:
3847 case AMOTION_EVENT_ACTION_HOVER_EXIT:
Jeff Brownb88102f2010-09-08 11:49:43 -07003848 mMotionMementos.push();
3849 MotionMemento& memento = mMotionMementos.editTop();
3850 memento.deviceId = entry->deviceId;
3851 memento.source = entry->source;
3852 memento.xPrecision = entry->xPrecision;
3853 memento.yPrecision = entry->yPrecision;
3854 memento.downTime = entry->downTime;
3855 memento.setPointers(entry);
Jeff Browna032cc02011-03-07 16:56:21 -08003856 memento.hovering = actionMasked != AMOTION_EVENT_ACTION_DOWN;
Jeff Brownb88102f2010-09-08 11:49:43 -07003857 }
3858}
3859
3860void InputDispatcher::InputState::MotionMemento::setPointers(const MotionEntry* entry) {
3861 pointerCount = entry->pointerCount;
3862 for (uint32_t i = 0; i < entry->pointerCount; i++) {
3863 pointerIds[i] = entry->pointerIds[i];
Jeff Brownace13b12011-03-09 17:39:48 -08003864 pointerCoords[i].copyFrom(entry->lastSample->pointerCoords[i]);
Jeff Brownb88102f2010-09-08 11:49:43 -07003865 }
3866}
3867
Jeff Brownb6997262010-10-08 22:31:17 -07003868void InputDispatcher::InputState::synthesizeCancelationEvents(nsecs_t currentTime,
3869 Allocator* allocator, Vector<EventEntry*>& outEvents,
3870 CancelationOptions options) {
3871 for (size_t i = 0; i < mKeyMementos.size(); ) {
Jeff Brownb88102f2010-09-08 11:49:43 -07003872 const KeyMemento& memento = mKeyMementos.itemAt(i);
Jeff Brown49ed71d2010-12-06 17:13:33 -08003873 if (shouldCancelKey(memento, options)) {
Jeff Brownb6997262010-10-08 22:31:17 -07003874 outEvents.push(allocator->obtainKeyEntry(currentTime,
3875 memento.deviceId, memento.source, 0,
Jeff Brown49ed71d2010-12-06 17:13:33 -08003876 AKEY_EVENT_ACTION_UP, memento.flags | AKEY_EVENT_FLAG_CANCELED,
Jeff Brownb6997262010-10-08 22:31:17 -07003877 memento.keyCode, memento.scanCode, 0, 0, memento.downTime));
3878 mKeyMementos.removeAt(i);
3879 } else {
3880 i += 1;
3881 }
Jeff Brownb88102f2010-09-08 11:49:43 -07003882 }
3883
Jeff Browna1160a72010-10-11 18:22:53 -07003884 for (size_t i = 0; i < mMotionMementos.size(); ) {
Jeff Brownb88102f2010-09-08 11:49:43 -07003885 const MotionMemento& memento = mMotionMementos.itemAt(i);
Jeff Brown49ed71d2010-12-06 17:13:33 -08003886 if (shouldCancelMotion(memento, options)) {
Jeff Brownb6997262010-10-08 22:31:17 -07003887 outEvents.push(allocator->obtainMotionEntry(currentTime,
3888 memento.deviceId, memento.source, 0,
Jeff Browna032cc02011-03-07 16:56:21 -08003889 memento.hovering
3890 ? AMOTION_EVENT_ACTION_HOVER_EXIT
3891 : AMOTION_EVENT_ACTION_CANCEL,
3892 0, 0, 0,
Jeff Brownb6997262010-10-08 22:31:17 -07003893 memento.xPrecision, memento.yPrecision, memento.downTime,
3894 memento.pointerCount, memento.pointerIds, memento.pointerCoords));
3895 mMotionMementos.removeAt(i);
3896 } else {
3897 i += 1;
3898 }
Jeff Brownb88102f2010-09-08 11:49:43 -07003899 }
3900}
3901
3902void InputDispatcher::InputState::clear() {
3903 mKeyMementos.clear();
3904 mMotionMementos.clear();
Jeff Brownb6997262010-10-08 22:31:17 -07003905}
3906
Jeff Brown9c9f1a32010-10-11 18:32:20 -07003907void InputDispatcher::InputState::copyPointerStateTo(InputState& other) const {
3908 for (size_t i = 0; i < mMotionMementos.size(); i++) {
3909 const MotionMemento& memento = mMotionMementos.itemAt(i);
3910 if (memento.source & AINPUT_SOURCE_CLASS_POINTER) {
3911 for (size_t j = 0; j < other.mMotionMementos.size(); ) {
3912 const MotionMemento& otherMemento = other.mMotionMementos.itemAt(j);
3913 if (memento.deviceId == otherMemento.deviceId
3914 && memento.source == otherMemento.source) {
3915 other.mMotionMementos.removeAt(j);
3916 } else {
3917 j += 1;
3918 }
3919 }
3920 other.mMotionMementos.push(memento);
3921 }
3922 }
3923}
3924
Jeff Brown49ed71d2010-12-06 17:13:33 -08003925bool InputDispatcher::InputState::shouldCancelKey(const KeyMemento& memento,
Jeff Brownb6997262010-10-08 22:31:17 -07003926 CancelationOptions options) {
3927 switch (options) {
Jeff Brown49ed71d2010-12-06 17:13:33 -08003928 case CANCEL_ALL_EVENTS:
Jeff Brownb6997262010-10-08 22:31:17 -07003929 case CANCEL_NON_POINTER_EVENTS:
Jeff Brownb6997262010-10-08 22:31:17 -07003930 return true;
Jeff Brown49ed71d2010-12-06 17:13:33 -08003931 case CANCEL_FALLBACK_EVENTS:
3932 return memento.flags & AKEY_EVENT_FLAG_FALLBACK;
3933 default:
3934 return false;
3935 }
3936}
3937
3938bool InputDispatcher::InputState::shouldCancelMotion(const MotionMemento& memento,
3939 CancelationOptions options) {
3940 switch (options) {
3941 case CANCEL_ALL_EVENTS:
3942 return true;
3943 case CANCEL_POINTER_EVENTS:
3944 return memento.source & AINPUT_SOURCE_CLASS_POINTER;
3945 case CANCEL_NON_POINTER_EVENTS:
3946 return !(memento.source & AINPUT_SOURCE_CLASS_POINTER);
3947 default:
3948 return false;
Jeff Brownb6997262010-10-08 22:31:17 -07003949 }
Jeff Brownb88102f2010-09-08 11:49:43 -07003950}
3951
3952
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003953// --- InputDispatcher::Connection ---
3954
Jeff Brown928e0542011-01-10 11:17:36 -08003955InputDispatcher::Connection::Connection(const sp<InputChannel>& inputChannel,
3956 const sp<InputWindowHandle>& inputWindowHandle) :
3957 status(STATUS_NORMAL), inputChannel(inputChannel), inputWindowHandle(inputWindowHandle),
3958 inputPublisher(inputChannel),
Jeff Brownbfaf3b92011-02-22 15:00:50 -08003959 lastEventTime(LONG_LONG_MAX), lastDispatchTime(LONG_LONG_MAX),
3960 originalKeyCodeForFallback(-1) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003961}
3962
3963InputDispatcher::Connection::~Connection() {
3964}
3965
3966status_t InputDispatcher::Connection::initialize() {
3967 return inputPublisher.initialize();
3968}
3969
Jeff Brown9c3cda02010-06-15 01:31:58 -07003970const char* InputDispatcher::Connection::getStatusLabel() const {
3971 switch (status) {
3972 case STATUS_NORMAL:
3973 return "NORMAL";
3974
3975 case STATUS_BROKEN:
3976 return "BROKEN";
3977
Jeff Brown9c3cda02010-06-15 01:31:58 -07003978 case STATUS_ZOMBIE:
3979 return "ZOMBIE";
3980
3981 default:
3982 return "UNKNOWN";
3983 }
3984}
3985
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003986InputDispatcher::DispatchEntry* InputDispatcher::Connection::findQueuedDispatchEntryForEvent(
3987 const EventEntry* eventEntry) const {
Jeff Brownb88102f2010-09-08 11:49:43 -07003988 for (DispatchEntry* dispatchEntry = outboundQueue.tailSentinel.prev;
3989 dispatchEntry != & outboundQueue.headSentinel; dispatchEntry = dispatchEntry->prev) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003990 if (dispatchEntry->eventEntry == eventEntry) {
3991 return dispatchEntry;
3992 }
3993 }
3994 return NULL;
3995}
3996
Jeff Brownb88102f2010-09-08 11:49:43 -07003997
Jeff Brown9c3cda02010-06-15 01:31:58 -07003998// --- InputDispatcher::CommandEntry ---
3999
Jeff Brownb88102f2010-09-08 11:49:43 -07004000InputDispatcher::CommandEntry::CommandEntry() :
4001 keyEntry(NULL) {
Jeff Brown9c3cda02010-06-15 01:31:58 -07004002}
4003
4004InputDispatcher::CommandEntry::~CommandEntry() {
4005}
4006
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004007
Jeff Brown01ce2e92010-09-26 22:20:12 -07004008// --- InputDispatcher::TouchState ---
4009
4010InputDispatcher::TouchState::TouchState() :
Jeff Brown58a2da82011-01-25 16:02:22 -08004011 down(false), split(false), deviceId(-1), source(0) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07004012}
4013
4014InputDispatcher::TouchState::~TouchState() {
4015}
4016
4017void InputDispatcher::TouchState::reset() {
4018 down = false;
4019 split = false;
Jeff Brown95712852011-01-04 19:41:59 -08004020 deviceId = -1;
Jeff Brown58a2da82011-01-25 16:02:22 -08004021 source = 0;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004022 windows.clear();
4023}
4024
4025void InputDispatcher::TouchState::copyFrom(const TouchState& other) {
4026 down = other.down;
4027 split = other.split;
Jeff Brown95712852011-01-04 19:41:59 -08004028 deviceId = other.deviceId;
Jeff Brown58a2da82011-01-25 16:02:22 -08004029 source = other.source;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004030 windows.clear();
4031 windows.appendVector(other.windows);
4032}
4033
4034void InputDispatcher::TouchState::addOrUpdateWindow(const InputWindow* window,
4035 int32_t targetFlags, BitSet32 pointerIds) {
4036 if (targetFlags & InputTarget::FLAG_SPLIT) {
4037 split = true;
4038 }
4039
4040 for (size_t i = 0; i < windows.size(); i++) {
4041 TouchedWindow& touchedWindow = windows.editItemAt(i);
4042 if (touchedWindow.window == window) {
4043 touchedWindow.targetFlags |= targetFlags;
4044 touchedWindow.pointerIds.value |= pointerIds.value;
4045 return;
4046 }
4047 }
4048
4049 windows.push();
4050
4051 TouchedWindow& touchedWindow = windows.editTop();
4052 touchedWindow.window = window;
4053 touchedWindow.targetFlags = targetFlags;
4054 touchedWindow.pointerIds = pointerIds;
4055 touchedWindow.channel = window->inputChannel;
4056}
4057
Jeff Browna032cc02011-03-07 16:56:21 -08004058void InputDispatcher::TouchState::filterNonAsIsTouchWindows() {
Jeff Brown01ce2e92010-09-26 22:20:12 -07004059 for (size_t i = 0 ; i < windows.size(); ) {
Jeff Browna032cc02011-03-07 16:56:21 -08004060 TouchedWindow& window = windows.editItemAt(i);
4061 if (window.targetFlags & InputTarget::FLAG_DISPATCH_AS_IS) {
4062 window.targetFlags &= ~InputTarget::FLAG_DISPATCH_MASK;
4063 window.targetFlags |= InputTarget::FLAG_DISPATCH_AS_IS;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004064 i += 1;
Jeff Browna032cc02011-03-07 16:56:21 -08004065 } else {
4066 windows.removeAt(i);
Jeff Brown01ce2e92010-09-26 22:20:12 -07004067 }
4068 }
4069}
4070
4071const InputWindow* InputDispatcher::TouchState::getFirstForegroundWindow() {
4072 for (size_t i = 0; i < windows.size(); i++) {
4073 if (windows[i].targetFlags & InputTarget::FLAG_FOREGROUND) {
4074 return windows[i].window;
4075 }
4076 }
4077 return NULL;
4078}
4079
4080
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004081// --- InputDispatcherThread ---
4082
4083InputDispatcherThread::InputDispatcherThread(const sp<InputDispatcherInterface>& dispatcher) :
4084 Thread(/*canCallJava*/ true), mDispatcher(dispatcher) {
4085}
4086
4087InputDispatcherThread::~InputDispatcherThread() {
4088}
4089
4090bool InputDispatcherThread::threadLoop() {
4091 mDispatcher->dispatchOnce();
4092 return true;
4093}
4094
4095} // namespace android