blob: d9ef819523c2118c58ca21bf50e07c4fb9e9e491 [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 Brownb4ff35d2011-01-02 16:37:43 -080051#include "InputDispatcher.h"
52
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070053#include <cutils/log.h>
Jeff Brownb88102f2010-09-08 11:49:43 -070054#include <ui/PowerManager.h>
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070055
56#include <stddef.h>
57#include <unistd.h>
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070058#include <errno.h>
59#include <limits.h>
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070060
Jeff Brownf2f487182010-10-01 17:46:21 -070061#define INDENT " "
62#define INDENT2 " "
63
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070064namespace android {
65
Jeff Brownb88102f2010-09-08 11:49:43 -070066// Default input dispatching timeout if there is no focused application or paused window
67// from which to determine an appropriate dispatching timeout.
68const nsecs_t DEFAULT_INPUT_DISPATCHING_TIMEOUT = 5000 * 1000000LL; // 5 sec
69
70// Amount of time to allow for all pending events to be processed when an app switch
71// key is on the way. This is used to preempt input dispatch and drop input events
72// when an application takes too long to respond and the user has pressed an app switch key.
73const nsecs_t APP_SWITCH_TIMEOUT = 500 * 1000000LL; // 0.5sec
74
Jeff Brown928e0542011-01-10 11:17:36 -080075// Amount of time to allow for an event to be dispatched (measured since its eventTime)
76// before considering it stale and dropping it.
77const nsecs_t STALE_EVENT_TIMEOUT = 10000 * 1000000LL; // 10sec
78
Jeff Brown5ced76a2011-05-24 11:23:27 -070079// Motion samples that are received within this amount of time are simply coalesced
80// when batched instead of being appended. This is done because some drivers update
81// the location of pointers one at a time instead of all at once.
82// For example, when there are 10 fingers down, the input dispatcher may receive 10
83// samples in quick succession with only one finger's location changed in each sample.
84//
85// This value effectively imposes an upper bound on the touch sampling rate.
86// Touch sensors typically have a 50Hz - 200Hz sampling rate, so we expect distinct
87// samples to become available 5-20ms apart but individual finger reports can trickle
88// in over a period of 2-4ms or so.
89//
90// Empirical testing shows that a 2ms coalescing interval (500Hz) is not enough,
91// a 3ms coalescing interval (333Hz) works well most of the time and doesn't introduce
92// significant quantization noise on current hardware.
93const nsecs_t MOTION_SAMPLE_COALESCE_INTERVAL = 3 * 1000000LL; // 3ms, 333Hz
94
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070095
Jeff Brown7fbdc842010-06-17 20:52:56 -070096static inline nsecs_t now() {
97 return systemTime(SYSTEM_TIME_MONOTONIC);
98}
99
Jeff Brownb88102f2010-09-08 11:49:43 -0700100static inline const char* toString(bool value) {
101 return value ? "true" : "false";
102}
103
Jeff Brown01ce2e92010-09-26 22:20:12 -0700104static inline int32_t getMotionEventActionPointerIndex(int32_t action) {
105 return (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK)
106 >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
107}
108
109static bool isValidKeyAction(int32_t action) {
110 switch (action) {
111 case AKEY_EVENT_ACTION_DOWN:
112 case AKEY_EVENT_ACTION_UP:
113 return true;
114 default:
115 return false;
116 }
117}
118
119static bool validateKeyEvent(int32_t action) {
120 if (! isValidKeyAction(action)) {
121 LOGE("Key event has invalid action code 0x%x", action);
122 return false;
123 }
124 return true;
125}
126
Jeff Brownb6997262010-10-08 22:31:17 -0700127static bool isValidMotionAction(int32_t action, size_t pointerCount) {
Jeff Brown01ce2e92010-09-26 22:20:12 -0700128 switch (action & AMOTION_EVENT_ACTION_MASK) {
129 case AMOTION_EVENT_ACTION_DOWN:
130 case AMOTION_EVENT_ACTION_UP:
131 case AMOTION_EVENT_ACTION_CANCEL:
132 case AMOTION_EVENT_ACTION_MOVE:
Jeff Brown01ce2e92010-09-26 22:20:12 -0700133 case AMOTION_EVENT_ACTION_OUTSIDE:
Jeff Browncc0c1592011-02-19 05:07:28 -0800134 case AMOTION_EVENT_ACTION_HOVER_MOVE:
Jeff Brown33bbfd22011-02-24 20:55:35 -0800135 case AMOTION_EVENT_ACTION_SCROLL:
Jeff Brown01ce2e92010-09-26 22:20:12 -0700136 return true;
Jeff Brownb6997262010-10-08 22:31:17 -0700137 case AMOTION_EVENT_ACTION_POINTER_DOWN:
138 case AMOTION_EVENT_ACTION_POINTER_UP: {
139 int32_t index = getMotionEventActionPointerIndex(action);
140 return index >= 0 && size_t(index) < pointerCount;
141 }
Jeff Brown01ce2e92010-09-26 22:20:12 -0700142 default:
143 return false;
144 }
145}
146
147static bool validateMotionEvent(int32_t action, size_t pointerCount,
148 const int32_t* pointerIds) {
Jeff Brownb6997262010-10-08 22:31:17 -0700149 if (! isValidMotionAction(action, pointerCount)) {
Jeff Brown01ce2e92010-09-26 22:20:12 -0700150 LOGE("Motion event has invalid action code 0x%x", action);
151 return false;
152 }
153 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
154 LOGE("Motion event has invalid pointer count %d; value must be between 1 and %d.",
155 pointerCount, MAX_POINTERS);
156 return false;
157 }
Jeff Brownc3db8582010-10-20 15:33:38 -0700158 BitSet32 pointerIdBits;
Jeff Brown01ce2e92010-09-26 22:20:12 -0700159 for (size_t i = 0; i < pointerCount; i++) {
Jeff Brownc3db8582010-10-20 15:33:38 -0700160 int32_t id = pointerIds[i];
161 if (id < 0 || id > MAX_POINTER_ID) {
Jeff Brown01ce2e92010-09-26 22:20:12 -0700162 LOGE("Motion event has invalid pointer id %d; value must be between 0 and %d",
Jeff Brownc3db8582010-10-20 15:33:38 -0700163 id, MAX_POINTER_ID);
Jeff Brown01ce2e92010-09-26 22:20:12 -0700164 return false;
165 }
Jeff Brownc3db8582010-10-20 15:33:38 -0700166 if (pointerIdBits.hasBit(id)) {
167 LOGE("Motion event has duplicate pointer id %d", id);
168 return false;
169 }
170 pointerIdBits.markBit(id);
Jeff Brown01ce2e92010-09-26 22:20:12 -0700171 }
172 return true;
173}
174
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400175static void scalePointerCoords(const PointerCoords* inCoords, size_t count, float scaleFactor,
176 PointerCoords* outCoords) {
177 for (size_t i = 0; i < count; i++) {
178 outCoords[i] = inCoords[i];
179 outCoords[i].scale(scaleFactor);
180 }
181}
182
Jeff Brownfbf09772011-01-16 14:06:57 -0800183static void dumpRegion(String8& dump, const SkRegion& region) {
184 if (region.isEmpty()) {
185 dump.append("<empty>");
186 return;
187 }
188
189 bool first = true;
190 for (SkRegion::Iterator it(region); !it.done(); it.next()) {
191 if (first) {
192 first = false;
193 } else {
194 dump.append("|");
195 }
196 const SkIRect& rect = it.rect();
197 dump.appendFormat("[%d,%d][%d,%d]", rect.fLeft, rect.fTop, rect.fRight, rect.fBottom);
198 }
199}
200
Jeff Brownb88102f2010-09-08 11:49:43 -0700201
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700202// --- InputDispatcher ---
203
Jeff Brown9c3cda02010-06-15 01:31:58 -0700204InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy) :
Jeff Brownb88102f2010-09-08 11:49:43 -0700205 mPolicy(policy),
Jeff Brown928e0542011-01-10 11:17:36 -0800206 mPendingEvent(NULL), mAppSwitchSawKeyDown(false), mAppSwitchDueTime(LONG_LONG_MAX),
207 mNextUnblockedEvent(NULL),
Jeff Brownb88102f2010-09-08 11:49:43 -0700208 mDispatchEnabled(true), mDispatchFrozen(false),
Jeff Brown01ce2e92010-09-26 22:20:12 -0700209 mFocusedWindow(NULL),
Jeff Brownb88102f2010-09-08 11:49:43 -0700210 mFocusedApplication(NULL),
211 mCurrentInputTargetsValid(false),
212 mInputTargetWaitCause(INPUT_TARGET_WAIT_CAUSE_NONE) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -0700213 mLooper = new Looper(false);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700214
Jeff Brownb88102f2010-09-08 11:49:43 -0700215 mInboundQueue.headSentinel.refCount = -1;
216 mInboundQueue.headSentinel.type = EventEntry::TYPE_SENTINEL;
217 mInboundQueue.headSentinel.eventTime = LONG_LONG_MIN;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700218
Jeff Brownb88102f2010-09-08 11:49:43 -0700219 mInboundQueue.tailSentinel.refCount = -1;
220 mInboundQueue.tailSentinel.type = EventEntry::TYPE_SENTINEL;
221 mInboundQueue.tailSentinel.eventTime = LONG_LONG_MAX;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700222
223 mKeyRepeatState.lastKeyEntry = NULL;
Jeff Brown9c3cda02010-06-15 01:31:58 -0700224
Jeff Brownae9fc032010-08-18 15:51:08 -0700225 int32_t maxEventsPerSecond = policy->getMaxEventsPerSecond();
226 mThrottleState.minTimeBetweenEvents = 1000000000LL / maxEventsPerSecond;
227 mThrottleState.lastDeviceId = -1;
228
229#if DEBUG_THROTTLING
230 mThrottleState.originalSampleCount = 0;
231 LOGD("Throttling - Max events per second = %d", maxEventsPerSecond);
232#endif
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700233}
234
235InputDispatcher::~InputDispatcher() {
Jeff Brownb88102f2010-09-08 11:49:43 -0700236 { // acquire lock
237 AutoMutex _l(mLock);
238
239 resetKeyRepeatLocked();
Jeff Brown54a18252010-09-16 14:07:33 -0700240 releasePendingEventLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -0700241 drainInboundQueueLocked();
242 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700243
244 while (mConnectionsByReceiveFd.size() != 0) {
245 unregisterInputChannel(mConnectionsByReceiveFd.valueAt(0)->inputChannel);
246 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700247}
248
249void InputDispatcher::dispatchOnce() {
Jeff Brown9c3cda02010-06-15 01:31:58 -0700250 nsecs_t keyRepeatTimeout = mPolicy->getKeyRepeatTimeout();
Jeff Brownb21fb102010-09-07 10:44:57 -0700251 nsecs_t keyRepeatDelay = mPolicy->getKeyRepeatDelay();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700252
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700253 nsecs_t nextWakeupTime = LONG_LONG_MAX;
254 { // acquire lock
255 AutoMutex _l(mLock);
Jeff Brownb88102f2010-09-08 11:49:43 -0700256 dispatchOnceInnerLocked(keyRepeatTimeout, keyRepeatDelay, & nextWakeupTime);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700257
Jeff Brownb88102f2010-09-08 11:49:43 -0700258 if (runCommandsLockedInterruptible()) {
259 nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700260 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700261 } // release lock
262
Jeff Brownb88102f2010-09-08 11:49:43 -0700263 // Wait for callback or timeout or wake. (make sure we round up, not down)
264 nsecs_t currentTime = now();
Jeff Brown68d60752011-03-17 01:34:19 -0700265 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
Jeff Brown4fe6c3e2010-09-13 23:17:30 -0700266 mLooper->pollOnce(timeoutMillis);
Jeff Brownb88102f2010-09-08 11:49:43 -0700267}
268
269void InputDispatcher::dispatchOnceInnerLocked(nsecs_t keyRepeatTimeout,
270 nsecs_t keyRepeatDelay, nsecs_t* nextWakeupTime) {
271 nsecs_t currentTime = now();
272
273 // Reset the key repeat timer whenever we disallow key events, even if the next event
274 // is not a key. This is to ensure that we abort a key repeat if the device is just coming
275 // out of sleep.
276 if (keyRepeatTimeout < 0) {
277 resetKeyRepeatLocked();
278 }
279
Jeff Brownb88102f2010-09-08 11:49:43 -0700280 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
281 if (mDispatchFrozen) {
282#if DEBUG_FOCUS
283 LOGD("Dispatch frozen. Waiting some more.");
284#endif
285 return;
286 }
287
288 // Optimize latency of app switches.
289 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
290 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
291 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
292 if (mAppSwitchDueTime < *nextWakeupTime) {
293 *nextWakeupTime = mAppSwitchDueTime;
294 }
295
Jeff Brownb88102f2010-09-08 11:49:43 -0700296 // Ready to start a new event.
297 // If we don't already have a pending event, go grab one.
298 if (! mPendingEvent) {
299 if (mInboundQueue.isEmpty()) {
300 if (isAppSwitchDue) {
301 // The inbound queue is empty so the app switch key we were waiting
302 // for will never arrive. Stop waiting for it.
303 resetPendingAppSwitchLocked(false);
304 isAppSwitchDue = false;
305 }
306
307 // Synthesize a key repeat if appropriate.
308 if (mKeyRepeatState.lastKeyEntry) {
309 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
310 mPendingEvent = synthesizeKeyRepeatLocked(currentTime, keyRepeatDelay);
311 } else {
312 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
313 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
314 }
315 }
316 }
317 if (! mPendingEvent) {
318 return;
319 }
320 } else {
321 // Inbound queue has at least one entry.
322 EventEntry* entry = mInboundQueue.headSentinel.next;
323
324 // Throttle the entry if it is a move event and there are no
325 // other events behind it in the queue. Due to movement batching, additional
326 // samples may be appended to this event by the time the throttling timeout
327 // expires.
328 // TODO Make this smarter and consider throttling per device independently.
Jeff Brownb6997262010-10-08 22:31:17 -0700329 if (entry->type == EventEntry::TYPE_MOTION
330 && !isAppSwitchDue
331 && mDispatchEnabled
332 && (entry->policyFlags & POLICY_FLAG_PASS_TO_USER)
333 && !entry->isInjected()) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700334 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
335 int32_t deviceId = motionEntry->deviceId;
336 uint32_t source = motionEntry->source;
337 if (! isAppSwitchDue
338 && motionEntry->next == & mInboundQueue.tailSentinel // exactly one event
Jeff Browncc0c1592011-02-19 05:07:28 -0800339 && (motionEntry->action == AMOTION_EVENT_ACTION_MOVE
340 || motionEntry->action == AMOTION_EVENT_ACTION_HOVER_MOVE)
Jeff Brownb88102f2010-09-08 11:49:43 -0700341 && deviceId == mThrottleState.lastDeviceId
342 && source == mThrottleState.lastSource) {
343 nsecs_t nextTime = mThrottleState.lastEventTime
344 + mThrottleState.minTimeBetweenEvents;
345 if (currentTime < nextTime) {
346 // Throttle it!
347#if DEBUG_THROTTLING
348 LOGD("Throttling - Delaying motion event for "
Jeff Brown90655042010-12-02 13:50:46 -0800349 "device %d, source 0x%08x by up to %0.3fms.",
Jeff Brownb88102f2010-09-08 11:49:43 -0700350 deviceId, source, (nextTime - currentTime) * 0.000001);
351#endif
352 if (nextTime < *nextWakeupTime) {
353 *nextWakeupTime = nextTime;
354 }
355 if (mThrottleState.originalSampleCount == 0) {
356 mThrottleState.originalSampleCount =
357 motionEntry->countSamples();
358 }
359 return;
360 }
361 }
362
363#if DEBUG_THROTTLING
364 if (mThrottleState.originalSampleCount != 0) {
365 uint32_t count = motionEntry->countSamples();
366 LOGD("Throttling - Motion event sample count grew by %d from %d to %d.",
367 count - mThrottleState.originalSampleCount,
368 mThrottleState.originalSampleCount, count);
369 mThrottleState.originalSampleCount = 0;
370 }
371#endif
372
makarand.karvekarf634ded2011-03-02 15:41:03 -0600373 mThrottleState.lastEventTime = currentTime;
Jeff Brownb88102f2010-09-08 11:49:43 -0700374 mThrottleState.lastDeviceId = deviceId;
375 mThrottleState.lastSource = source;
376 }
377
378 mInboundQueue.dequeue(entry);
379 mPendingEvent = entry;
380 }
Jeff Browne2fe69e2010-10-18 13:21:23 -0700381
382 // Poke user activity for this event.
383 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
384 pokeUserActivityLocked(mPendingEvent);
385 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700386 }
387
388 // Now we have an event to dispatch.
Jeff Brown928e0542011-01-10 11:17:36 -0800389 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Jeff Brownb88102f2010-09-08 11:49:43 -0700390 assert(mPendingEvent != NULL);
Jeff Brown54a18252010-09-16 14:07:33 -0700391 bool done = false;
Jeff Brownb6997262010-10-08 22:31:17 -0700392 DropReason dropReason = DROP_REASON_NOT_DROPPED;
393 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
394 dropReason = DROP_REASON_POLICY;
395 } else if (!mDispatchEnabled) {
396 dropReason = DROP_REASON_DISABLED;
397 }
Jeff Brown928e0542011-01-10 11:17:36 -0800398
399 if (mNextUnblockedEvent == mPendingEvent) {
400 mNextUnblockedEvent = NULL;
401 }
402
Jeff Brownb88102f2010-09-08 11:49:43 -0700403 switch (mPendingEvent->type) {
404 case EventEntry::TYPE_CONFIGURATION_CHANGED: {
405 ConfigurationChangedEntry* typedEntry =
406 static_cast<ConfigurationChangedEntry*>(mPendingEvent);
Jeff Brown54a18252010-09-16 14:07:33 -0700407 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Jeff Brownb6997262010-10-08 22:31:17 -0700408 dropReason = DROP_REASON_NOT_DROPPED; // configuration changes are never dropped
Jeff Brownb88102f2010-09-08 11:49:43 -0700409 break;
410 }
411
412 case EventEntry::TYPE_KEY: {
413 KeyEntry* typedEntry = static_cast<KeyEntry*>(mPendingEvent);
Jeff Brownb6997262010-10-08 22:31:17 -0700414 if (isAppSwitchDue) {
415 if (isAppSwitchKeyEventLocked(typedEntry)) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700416 resetPendingAppSwitchLocked(true);
Jeff Brownb6997262010-10-08 22:31:17 -0700417 isAppSwitchDue = false;
418 } else if (dropReason == DROP_REASON_NOT_DROPPED) {
419 dropReason = DROP_REASON_APP_SWITCH;
Jeff Brownb88102f2010-09-08 11:49:43 -0700420 }
421 }
Jeff Brown928e0542011-01-10 11:17:36 -0800422 if (dropReason == DROP_REASON_NOT_DROPPED
423 && isStaleEventLocked(currentTime, typedEntry)) {
424 dropReason = DROP_REASON_STALE;
425 }
426 if (dropReason == DROP_REASON_NOT_DROPPED && mNextUnblockedEvent) {
427 dropReason = DROP_REASON_BLOCKED;
428 }
Jeff Brownb6997262010-10-08 22:31:17 -0700429 done = dispatchKeyLocked(currentTime, typedEntry, keyRepeatTimeout,
Jeff Browne20c9e02010-10-11 14:20:19 -0700430 &dropReason, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700431 break;
432 }
433
434 case EventEntry::TYPE_MOTION: {
435 MotionEntry* typedEntry = static_cast<MotionEntry*>(mPendingEvent);
Jeff Brownb6997262010-10-08 22:31:17 -0700436 if (dropReason == DROP_REASON_NOT_DROPPED && isAppSwitchDue) {
437 dropReason = DROP_REASON_APP_SWITCH;
Jeff Brownb88102f2010-09-08 11:49:43 -0700438 }
Jeff Brown928e0542011-01-10 11:17:36 -0800439 if (dropReason == DROP_REASON_NOT_DROPPED
440 && isStaleEventLocked(currentTime, typedEntry)) {
441 dropReason = DROP_REASON_STALE;
442 }
443 if (dropReason == DROP_REASON_NOT_DROPPED && mNextUnblockedEvent) {
444 dropReason = DROP_REASON_BLOCKED;
445 }
Jeff Brownb6997262010-10-08 22:31:17 -0700446 done = dispatchMotionLocked(currentTime, typedEntry,
Jeff Browne20c9e02010-10-11 14:20:19 -0700447 &dropReason, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700448 break;
449 }
450
451 default:
452 assert(false);
Jeff Brownb88102f2010-09-08 11:49:43 -0700453 break;
454 }
455
Jeff Brown54a18252010-09-16 14:07:33 -0700456 if (done) {
Jeff Brownb6997262010-10-08 22:31:17 -0700457 if (dropReason != DROP_REASON_NOT_DROPPED) {
458 dropInboundEventLocked(mPendingEvent, dropReason);
459 }
460
Jeff Brown54a18252010-09-16 14:07:33 -0700461 releasePendingEventLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -0700462 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
463 }
464}
465
466bool InputDispatcher::enqueueInboundEventLocked(EventEntry* entry) {
467 bool needWake = mInboundQueue.isEmpty();
468 mInboundQueue.enqueueAtTail(entry);
469
470 switch (entry->type) {
Jeff Brownb6997262010-10-08 22:31:17 -0700471 case EventEntry::TYPE_KEY: {
Jeff Brown928e0542011-01-10 11:17:36 -0800472 // Optimize app switch latency.
473 // If the application takes too long to catch up then we drop all events preceding
474 // the app switch key.
Jeff Brownb6997262010-10-08 22:31:17 -0700475 KeyEntry* keyEntry = static_cast<KeyEntry*>(entry);
476 if (isAppSwitchKeyEventLocked(keyEntry)) {
477 if (keyEntry->action == AKEY_EVENT_ACTION_DOWN) {
478 mAppSwitchSawKeyDown = true;
479 } else if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
480 if (mAppSwitchSawKeyDown) {
481#if DEBUG_APP_SWITCH
482 LOGD("App switch is pending!");
483#endif
484 mAppSwitchDueTime = keyEntry->eventTime + APP_SWITCH_TIMEOUT;
485 mAppSwitchSawKeyDown = false;
486 needWake = true;
487 }
488 }
489 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700490 break;
491 }
Jeff Brown928e0542011-01-10 11:17:36 -0800492
493 case EventEntry::TYPE_MOTION: {
494 // Optimize case where the current application is unresponsive and the user
495 // decides to touch a window in a different application.
496 // If the application takes too long to catch up then we drop all events preceding
497 // the touch into the other window.
498 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
Jeff Brown33bbfd22011-02-24 20:55:35 -0800499 if (motionEntry->action == AMOTION_EVENT_ACTION_DOWN
Jeff Brown928e0542011-01-10 11:17:36 -0800500 && (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER)
501 && mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY
502 && mInputTargetWaitApplication != NULL) {
Jeff Brown91c69ab2011-02-14 17:03:18 -0800503 int32_t x = int32_t(motionEntry->firstSample.pointerCoords[0].
Jeff Brownebbd5d12011-02-17 13:01:34 -0800504 getAxisValue(AMOTION_EVENT_AXIS_X));
Jeff Brown91c69ab2011-02-14 17:03:18 -0800505 int32_t y = int32_t(motionEntry->firstSample.pointerCoords[0].
Jeff Brownebbd5d12011-02-17 13:01:34 -0800506 getAxisValue(AMOTION_EVENT_AXIS_Y));
Jeff Brown928e0542011-01-10 11:17:36 -0800507 const InputWindow* touchedWindow = findTouchedWindowAtLocked(x, y);
508 if (touchedWindow
509 && touchedWindow->inputWindowHandle != NULL
510 && touchedWindow->inputWindowHandle->getInputApplicationHandle()
511 != mInputTargetWaitApplication) {
512 // User touched a different application than the one we are waiting on.
513 // Flag the event, and start pruning the input queue.
514 mNextUnblockedEvent = motionEntry;
515 needWake = true;
516 }
517 }
518 break;
519 }
Jeff Brownb6997262010-10-08 22:31:17 -0700520 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700521
522 return needWake;
523}
524
Jeff Brown928e0542011-01-10 11:17:36 -0800525const InputWindow* InputDispatcher::findTouchedWindowAtLocked(int32_t x, int32_t y) {
526 // Traverse windows from front to back to find touched window.
527 size_t numWindows = mWindows.size();
528 for (size_t i = 0; i < numWindows; i++) {
529 const InputWindow* window = & mWindows.editItemAt(i);
530 int32_t flags = window->layoutParamsFlags;
531
532 if (window->visible) {
533 if (!(flags & InputWindow::FLAG_NOT_TOUCHABLE)) {
534 bool isTouchModal = (flags & (InputWindow::FLAG_NOT_FOCUSABLE
535 | InputWindow::FLAG_NOT_TOUCH_MODAL)) == 0;
Jeff Brownfbf09772011-01-16 14:06:57 -0800536 if (isTouchModal || window->touchableRegionContainsPoint(x, y)) {
Jeff Brown928e0542011-01-10 11:17:36 -0800537 // Found window.
538 return window;
539 }
540 }
541 }
542
543 if (flags & InputWindow::FLAG_SYSTEM_ERROR) {
544 // Error window is on top but not visible, so touch is dropped.
545 return NULL;
546 }
547 }
548 return NULL;
549}
550
Jeff Brownb6997262010-10-08 22:31:17 -0700551void InputDispatcher::dropInboundEventLocked(EventEntry* entry, DropReason dropReason) {
552 const char* reason;
553 switch (dropReason) {
554 case DROP_REASON_POLICY:
Jeff Browne20c9e02010-10-11 14:20:19 -0700555#if DEBUG_INBOUND_EVENT_DETAILS
Jeff Brown3122e442010-10-11 23:32:49 -0700556 LOGD("Dropped event because policy consumed it.");
Jeff Browne20c9e02010-10-11 14:20:19 -0700557#endif
Jeff Brown3122e442010-10-11 23:32:49 -0700558 reason = "inbound event was dropped because the policy consumed it";
Jeff Brownb6997262010-10-08 22:31:17 -0700559 break;
560 case DROP_REASON_DISABLED:
561 LOGI("Dropped event because input dispatch is disabled.");
562 reason = "inbound event was dropped because input dispatch is disabled";
563 break;
564 case DROP_REASON_APP_SWITCH:
565 LOGI("Dropped event because of pending overdue app switch.");
566 reason = "inbound event was dropped because of pending overdue app switch";
567 break;
Jeff Brown928e0542011-01-10 11:17:36 -0800568 case DROP_REASON_BLOCKED:
569 LOGI("Dropped event because the current application is not responding and the user "
570 "has started interating with a different application.");
571 reason = "inbound event was dropped because the current application is not responding "
572 "and the user has started interating with a different application";
573 break;
574 case DROP_REASON_STALE:
575 LOGI("Dropped event because it is stale.");
576 reason = "inbound event was dropped because it is stale";
577 break;
Jeff Brownb6997262010-10-08 22:31:17 -0700578 default:
579 assert(false);
580 return;
581 }
582
583 switch (entry->type) {
Jeff Brown524ee642011-03-29 15:11:34 -0700584 case EventEntry::TYPE_KEY: {
585 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
586 synthesizeCancelationEventsForAllConnectionsLocked(options);
Jeff Brownb6997262010-10-08 22:31:17 -0700587 break;
Jeff Brown524ee642011-03-29 15:11:34 -0700588 }
Jeff Brownb6997262010-10-08 22:31:17 -0700589 case EventEntry::TYPE_MOTION: {
590 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
591 if (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) {
Jeff Brown524ee642011-03-29 15:11:34 -0700592 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
593 synthesizeCancelationEventsForAllConnectionsLocked(options);
Jeff Brownb6997262010-10-08 22:31:17 -0700594 } else {
Jeff Brown524ee642011-03-29 15:11:34 -0700595 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
596 synthesizeCancelationEventsForAllConnectionsLocked(options);
Jeff Brownb6997262010-10-08 22:31:17 -0700597 }
598 break;
599 }
600 }
601}
602
603bool InputDispatcher::isAppSwitchKeyCode(int32_t keyCode) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700604 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL;
605}
606
Jeff Brownb6997262010-10-08 22:31:17 -0700607bool InputDispatcher::isAppSwitchKeyEventLocked(KeyEntry* keyEntry) {
608 return ! (keyEntry->flags & AKEY_EVENT_FLAG_CANCELED)
609 && isAppSwitchKeyCode(keyEntry->keyCode)
Jeff Browne20c9e02010-10-11 14:20:19 -0700610 && (keyEntry->policyFlags & POLICY_FLAG_TRUSTED)
Jeff Brownb6997262010-10-08 22:31:17 -0700611 && (keyEntry->policyFlags & POLICY_FLAG_PASS_TO_USER);
612}
613
Jeff Brownb88102f2010-09-08 11:49:43 -0700614bool InputDispatcher::isAppSwitchPendingLocked() {
615 return mAppSwitchDueTime != LONG_LONG_MAX;
616}
617
Jeff Brownb88102f2010-09-08 11:49:43 -0700618void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
619 mAppSwitchDueTime = LONG_LONG_MAX;
620
621#if DEBUG_APP_SWITCH
622 if (handled) {
623 LOGD("App switch has arrived.");
624 } else {
625 LOGD("App switch was abandoned.");
626 }
627#endif
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700628}
629
Jeff Brown928e0542011-01-10 11:17:36 -0800630bool InputDispatcher::isStaleEventLocked(nsecs_t currentTime, EventEntry* entry) {
631 return currentTime - entry->eventTime >= STALE_EVENT_TIMEOUT;
632}
633
Jeff Brown9c3cda02010-06-15 01:31:58 -0700634bool InputDispatcher::runCommandsLockedInterruptible() {
635 if (mCommandQueue.isEmpty()) {
636 return false;
637 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700638
Jeff Brown9c3cda02010-06-15 01:31:58 -0700639 do {
640 CommandEntry* commandEntry = mCommandQueue.dequeueAtHead();
641
642 Command command = commandEntry->command;
643 (this->*command)(commandEntry); // commands are implicitly 'LockedInterruptible'
644
Jeff Brown7fbdc842010-06-17 20:52:56 -0700645 commandEntry->connection.clear();
Jeff Brown9c3cda02010-06-15 01:31:58 -0700646 mAllocator.releaseCommandEntry(commandEntry);
647 } while (! mCommandQueue.isEmpty());
648 return true;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700649}
650
Jeff Brown9c3cda02010-06-15 01:31:58 -0700651InputDispatcher::CommandEntry* InputDispatcher::postCommandLocked(Command command) {
652 CommandEntry* commandEntry = mAllocator.obtainCommandEntry(command);
653 mCommandQueue.enqueueAtTail(commandEntry);
654 return commandEntry;
655}
656
Jeff Brownb88102f2010-09-08 11:49:43 -0700657void InputDispatcher::drainInboundQueueLocked() {
658 while (! mInboundQueue.isEmpty()) {
659 EventEntry* entry = mInboundQueue.dequeueAtHead();
Jeff Brown54a18252010-09-16 14:07:33 -0700660 releaseInboundEventLocked(entry);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700661 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700662}
663
Jeff Brown54a18252010-09-16 14:07:33 -0700664void InputDispatcher::releasePendingEventLocked() {
Jeff Brownb88102f2010-09-08 11:49:43 -0700665 if (mPendingEvent) {
Jeff Brown54a18252010-09-16 14:07:33 -0700666 releaseInboundEventLocked(mPendingEvent);
Jeff Brownb88102f2010-09-08 11:49:43 -0700667 mPendingEvent = NULL;
668 }
669}
670
Jeff Brown54a18252010-09-16 14:07:33 -0700671void InputDispatcher::releaseInboundEventLocked(EventEntry* entry) {
Jeff Brown01ce2e92010-09-26 22:20:12 -0700672 InjectionState* injectionState = entry->injectionState;
673 if (injectionState && injectionState->injectionResult == INPUT_EVENT_INJECTION_PENDING) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700674#if DEBUG_DISPATCH_CYCLE
Jeff Brown01ce2e92010-09-26 22:20:12 -0700675 LOGD("Injected inbound event was dropped.");
Jeff Brownb88102f2010-09-08 11:49:43 -0700676#endif
677 setInjectionResultLocked(entry, INPUT_EVENT_INJECTION_FAILED);
678 }
679 mAllocator.releaseEventEntry(entry);
680}
681
Jeff Brownb88102f2010-09-08 11:49:43 -0700682void InputDispatcher::resetKeyRepeatLocked() {
683 if (mKeyRepeatState.lastKeyEntry) {
684 mAllocator.releaseKeyEntry(mKeyRepeatState.lastKeyEntry);
685 mKeyRepeatState.lastKeyEntry = NULL;
686 }
687}
688
689InputDispatcher::KeyEntry* InputDispatcher::synthesizeKeyRepeatLocked(
Jeff Brownb21fb102010-09-07 10:44:57 -0700690 nsecs_t currentTime, nsecs_t keyRepeatDelay) {
Jeff Brown349703e2010-06-22 01:27:15 -0700691 KeyEntry* entry = mKeyRepeatState.lastKeyEntry;
692
Jeff Brown349703e2010-06-22 01:27:15 -0700693 // Reuse the repeated key entry if it is otherwise unreferenced.
Jeff Browne20c9e02010-10-11 14:20:19 -0700694 uint32_t policyFlags = (entry->policyFlags & POLICY_FLAG_RAW_MASK)
695 | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700696 if (entry->refCount == 1) {
Jeff Brown01ce2e92010-09-26 22:20:12 -0700697 mAllocator.recycleKeyEntry(entry);
Jeff Brown7fbdc842010-06-17 20:52:56 -0700698 entry->eventTime = currentTime;
Jeff Brown7fbdc842010-06-17 20:52:56 -0700699 entry->policyFlags = policyFlags;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700700 entry->repeatCount += 1;
701 } else {
Jeff Brown7fbdc842010-06-17 20:52:56 -0700702 KeyEntry* newEntry = mAllocator.obtainKeyEntry(currentTime,
Jeff Brownc5ed5912010-07-14 18:48:53 -0700703 entry->deviceId, entry->source, policyFlags,
Jeff Brown7fbdc842010-06-17 20:52:56 -0700704 entry->action, entry->flags, entry->keyCode, entry->scanCode,
Jeff Brown00fa7bd2010-07-02 15:37:36 -0700705 entry->metaState, entry->repeatCount + 1, entry->downTime);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700706
707 mKeyRepeatState.lastKeyEntry = newEntry;
708 mAllocator.releaseKeyEntry(entry);
709
710 entry = newEntry;
711 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700712 entry->syntheticRepeat = true;
713
714 // Increment reference count since we keep a reference to the event in
715 // mKeyRepeatState.lastKeyEntry in addition to the one we return.
716 entry->refCount += 1;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700717
Jeff Brownb21fb102010-09-07 10:44:57 -0700718 mKeyRepeatState.nextRepeatTime = currentTime + keyRepeatDelay;
Jeff Brownb88102f2010-09-08 11:49:43 -0700719 return entry;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700720}
721
Jeff Brownb88102f2010-09-08 11:49:43 -0700722bool InputDispatcher::dispatchConfigurationChangedLocked(
723 nsecs_t currentTime, ConfigurationChangedEntry* entry) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700724#if DEBUG_OUTBOUND_EVENT_DETAILS
Jeff Brownb88102f2010-09-08 11:49:43 -0700725 LOGD("dispatchConfigurationChanged - eventTime=%lld", entry->eventTime);
726#endif
727
728 // Reset key repeating in case a keyboard device was added or removed or something.
729 resetKeyRepeatLocked();
730
731 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
732 CommandEntry* commandEntry = postCommandLocked(
733 & InputDispatcher::doNotifyConfigurationChangedInterruptible);
734 commandEntry->eventTime = entry->eventTime;
735 return true;
736}
737
738bool InputDispatcher::dispatchKeyLocked(
739 nsecs_t currentTime, KeyEntry* entry, nsecs_t keyRepeatTimeout,
Jeff Browne20c9e02010-10-11 14:20:19 -0700740 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Jeff Browne46a0a42010-11-02 17:58:22 -0700741 // Preprocessing.
742 if (! entry->dispatchInProgress) {
743 if (entry->repeatCount == 0
744 && entry->action == AKEY_EVENT_ACTION_DOWN
745 && (entry->policyFlags & POLICY_FLAG_TRUSTED)
746 && !entry->isInjected()) {
747 if (mKeyRepeatState.lastKeyEntry
748 && mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode) {
749 // We have seen two identical key downs in a row which indicates that the device
750 // driver is automatically generating key repeats itself. We take note of the
751 // repeat here, but we disable our own next key repeat timer since it is clear that
752 // we will not need to synthesize key repeats ourselves.
753 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
754 resetKeyRepeatLocked();
755 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
756 } else {
757 // Not a repeat. Save key down state in case we do see a repeat later.
758 resetKeyRepeatLocked();
759 mKeyRepeatState.nextRepeatTime = entry->eventTime + keyRepeatTimeout;
760 }
761 mKeyRepeatState.lastKeyEntry = entry;
762 entry->refCount += 1;
763 } else if (! entry->syntheticRepeat) {
764 resetKeyRepeatLocked();
765 }
766
Jeff Browne2e01262011-03-02 20:34:30 -0800767 if (entry->repeatCount == 1) {
768 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
769 } else {
770 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
771 }
772
Jeff Browne46a0a42010-11-02 17:58:22 -0700773 entry->dispatchInProgress = true;
774 resetTargetsLocked();
775
776 logOutboundKeyDetailsLocked("dispatchKey - ", entry);
777 }
778
Jeff Brown54a18252010-09-16 14:07:33 -0700779 // Give the policy a chance to intercept the key.
780 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
Jeff Browne20c9e02010-10-11 14:20:19 -0700781 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Jeff Brown54a18252010-09-16 14:07:33 -0700782 CommandEntry* commandEntry = postCommandLocked(
783 & InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
Jeff Browne20c9e02010-10-11 14:20:19 -0700784 if (mFocusedWindow) {
Jeff Brown928e0542011-01-10 11:17:36 -0800785 commandEntry->inputWindowHandle = mFocusedWindow->inputWindowHandle;
Jeff Brown54a18252010-09-16 14:07:33 -0700786 }
787 commandEntry->keyEntry = entry;
788 entry->refCount += 1;
789 return false; // wait for the command to run
790 } else {
791 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
792 }
793 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Jeff Browne20c9e02010-10-11 14:20:19 -0700794 if (*dropReason == DROP_REASON_NOT_DROPPED) {
795 *dropReason = DROP_REASON_POLICY;
796 }
Jeff Brown54a18252010-09-16 14:07:33 -0700797 }
798
799 // Clean up if dropping the event.
Jeff Browne20c9e02010-10-11 14:20:19 -0700800 if (*dropReason != DROP_REASON_NOT_DROPPED) {
Jeff Brown54a18252010-09-16 14:07:33 -0700801 resetTargetsLocked();
Jeff Brown3122e442010-10-11 23:32:49 -0700802 setInjectionResultLocked(entry, *dropReason == DROP_REASON_POLICY
803 ? INPUT_EVENT_INJECTION_SUCCEEDED : INPUT_EVENT_INJECTION_FAILED);
Jeff Brown54a18252010-09-16 14:07:33 -0700804 return true;
805 }
806
Jeff Brownb88102f2010-09-08 11:49:43 -0700807 // Identify targets.
808 if (! mCurrentInputTargetsValid) {
Jeff Brown01ce2e92010-09-26 22:20:12 -0700809 int32_t injectionResult = findFocusedWindowTargetsLocked(currentTime,
810 entry, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700811 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
812 return false;
813 }
814
815 setInjectionResultLocked(entry, injectionResult);
816 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
817 return true;
818 }
819
820 addMonitoringTargetsLocked();
Jeff Brown01ce2e92010-09-26 22:20:12 -0700821 commitTargetsLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -0700822 }
823
824 // Dispatch the key.
825 dispatchEventToCurrentInputTargetsLocked(currentTime, entry, false);
Jeff Brownb88102f2010-09-08 11:49:43 -0700826 return true;
827}
828
829void InputDispatcher::logOutboundKeyDetailsLocked(const char* prefix, const KeyEntry* entry) {
830#if DEBUG_OUTBOUND_EVENT_DETAILS
Jeff Brown90655042010-12-02 13:50:46 -0800831 LOGD("%seventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, "
Jeff Brownb88102f2010-09-08 11:49:43 -0700832 "action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, "
Jeff Browne46a0a42010-11-02 17:58:22 -0700833 "repeatCount=%d, downTime=%lld",
Jeff Brownb88102f2010-09-08 11:49:43 -0700834 prefix,
835 entry->eventTime, entry->deviceId, entry->source, entry->policyFlags,
836 entry->action, entry->flags, entry->keyCode, entry->scanCode, entry->metaState,
Jeff Browne46a0a42010-11-02 17:58:22 -0700837 entry->repeatCount, entry->downTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700838#endif
839}
840
841bool InputDispatcher::dispatchMotionLocked(
Jeff Browne20c9e02010-10-11 14:20:19 -0700842 nsecs_t currentTime, MotionEntry* entry, DropReason* dropReason, nsecs_t* nextWakeupTime) {
Jeff Browne46a0a42010-11-02 17:58:22 -0700843 // Preprocessing.
844 if (! entry->dispatchInProgress) {
845 entry->dispatchInProgress = true;
846 resetTargetsLocked();
847
848 logOutboundMotionDetailsLocked("dispatchMotion - ", entry);
849 }
850
Jeff Brown54a18252010-09-16 14:07:33 -0700851 // Clean up if dropping the event.
Jeff Browne20c9e02010-10-11 14:20:19 -0700852 if (*dropReason != DROP_REASON_NOT_DROPPED) {
Jeff Brown54a18252010-09-16 14:07:33 -0700853 resetTargetsLocked();
Jeff Brown3122e442010-10-11 23:32:49 -0700854 setInjectionResultLocked(entry, *dropReason == DROP_REASON_POLICY
855 ? INPUT_EVENT_INJECTION_SUCCEEDED : INPUT_EVENT_INJECTION_FAILED);
Jeff Brown54a18252010-09-16 14:07:33 -0700856 return true;
857 }
858
Jeff Brownb88102f2010-09-08 11:49:43 -0700859 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
860
861 // Identify targets.
Jeff Browncc0c1592011-02-19 05:07:28 -0800862 bool conflictingPointerActions = false;
Jeff Brownb88102f2010-09-08 11:49:43 -0700863 if (! mCurrentInputTargetsValid) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700864 int32_t injectionResult;
865 if (isPointerEvent) {
866 // Pointer event. (eg. touchscreen)
Jeff Brown01ce2e92010-09-26 22:20:12 -0700867 injectionResult = findTouchedWindowTargetsLocked(currentTime,
Jeff Browncc0c1592011-02-19 05:07:28 -0800868 entry, nextWakeupTime, &conflictingPointerActions);
Jeff Brownb88102f2010-09-08 11:49:43 -0700869 } else {
870 // Non touch event. (eg. trackball)
Jeff Brown01ce2e92010-09-26 22:20:12 -0700871 injectionResult = findFocusedWindowTargetsLocked(currentTime,
872 entry, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700873 }
874 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
875 return false;
876 }
877
878 setInjectionResultLocked(entry, injectionResult);
879 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
880 return true;
881 }
882
883 addMonitoringTargetsLocked();
Jeff Brown01ce2e92010-09-26 22:20:12 -0700884 commitTargetsLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -0700885 }
886
887 // Dispatch the motion.
Jeff Browncc0c1592011-02-19 05:07:28 -0800888 if (conflictingPointerActions) {
Jeff Brown524ee642011-03-29 15:11:34 -0700889 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
890 "conflicting pointer actions");
891 synthesizeCancelationEventsForAllConnectionsLocked(options);
Jeff Browncc0c1592011-02-19 05:07:28 -0800892 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700893 dispatchEventToCurrentInputTargetsLocked(currentTime, entry, false);
Jeff Brownb88102f2010-09-08 11:49:43 -0700894 return true;
895}
896
897
898void InputDispatcher::logOutboundMotionDetailsLocked(const char* prefix, const MotionEntry* entry) {
899#if DEBUG_OUTBOUND_EVENT_DETAILS
Jeff Brown90655042010-12-02 13:50:46 -0800900 LOGD("%seventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, "
Jeff Brown85a31762010-09-01 17:01:00 -0700901 "action=0x%x, flags=0x%x, "
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700902 "metaState=0x%x, edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%lld",
Jeff Brownb88102f2010-09-08 11:49:43 -0700903 prefix,
Jeff Brown85a31762010-09-01 17:01:00 -0700904 entry->eventTime, entry->deviceId, entry->source, entry->policyFlags,
905 entry->action, entry->flags,
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700906 entry->metaState, entry->edgeFlags, entry->xPrecision, entry->yPrecision,
907 entry->downTime);
908
909 // Print the most recent sample that we have available, this may change due to batching.
910 size_t sampleCount = 1;
Jeff Brownb88102f2010-09-08 11:49:43 -0700911 const MotionSample* sample = & entry->firstSample;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700912 for (; sample->next != NULL; sample = sample->next) {
913 sampleCount += 1;
914 }
915 for (uint32_t i = 0; i < entry->pointerCount; i++) {
Jeff Brown8d608662010-08-30 03:02:23 -0700916 LOGD(" Pointer %d: id=%d, x=%f, y=%f, pressure=%f, size=%f, "
Jeff Brown85a31762010-09-01 17:01:00 -0700917 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
Jeff Brown8d608662010-08-30 03:02:23 -0700918 "orientation=%f",
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700919 i, entry->pointerIds[i],
Jeff Brownebbd5d12011-02-17 13:01:34 -0800920 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
921 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
922 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
923 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
924 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
925 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
926 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
927 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
928 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700929 }
930
931 // Keep in mind that due to batching, it is possible for the number of samples actually
932 // dispatched to change before the application finally consumed them.
Jeff Brownc5ed5912010-07-14 18:48:53 -0700933 if (entry->action == AMOTION_EVENT_ACTION_MOVE) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700934 LOGD(" ... Total movement samples currently batched %d ...", sampleCount);
935 }
936#endif
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700937}
938
939void InputDispatcher::dispatchEventToCurrentInputTargetsLocked(nsecs_t currentTime,
940 EventEntry* eventEntry, bool resumeWithAppendedMotionSample) {
941#if DEBUG_DISPATCH_CYCLE
Jeff Brown9c3cda02010-06-15 01:31:58 -0700942 LOGD("dispatchEventToCurrentInputTargets - "
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700943 "resumeWithAppendedMotionSample=%s",
Jeff Brownb88102f2010-09-08 11:49:43 -0700944 toString(resumeWithAppendedMotionSample));
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700945#endif
946
Jeff Brown9c3cda02010-06-15 01:31:58 -0700947 assert(eventEntry->dispatchInProgress); // should already have been set to true
948
Jeff Browne2fe69e2010-10-18 13:21:23 -0700949 pokeUserActivityLocked(eventEntry);
950
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700951 for (size_t i = 0; i < mCurrentInputTargets.size(); i++) {
952 const InputTarget& inputTarget = mCurrentInputTargets.itemAt(i);
953
Jeff Brown519e0242010-09-15 15:18:56 -0700954 ssize_t connectionIndex = getConnectionIndexLocked(inputTarget.inputChannel);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700955 if (connectionIndex >= 0) {
956 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
Jeff Brown7fbdc842010-06-17 20:52:56 -0700957 prepareDispatchCycleLocked(currentTime, connection, eventEntry, & inputTarget,
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700958 resumeWithAppendedMotionSample);
959 } else {
Jeff Brownb6997262010-10-08 22:31:17 -0700960#if DEBUG_FOCUS
961 LOGD("Dropping event delivery to target with channel '%s' because it "
962 "is no longer registered with the input dispatcher.",
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700963 inputTarget.inputChannel->getName().string());
Jeff Brownb6997262010-10-08 22:31:17 -0700964#endif
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700965 }
966 }
967}
968
Jeff Brown54a18252010-09-16 14:07:33 -0700969void InputDispatcher::resetTargetsLocked() {
Jeff Brownb88102f2010-09-08 11:49:43 -0700970 mCurrentInputTargetsValid = false;
971 mCurrentInputTargets.clear();
Jeff Brownb88102f2010-09-08 11:49:43 -0700972 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_NONE;
Jeff Brown928e0542011-01-10 11:17:36 -0800973 mInputTargetWaitApplication.clear();
Jeff Brownb88102f2010-09-08 11:49:43 -0700974}
975
Jeff Brown01ce2e92010-09-26 22:20:12 -0700976void InputDispatcher::commitTargetsLocked() {
Jeff Brownb88102f2010-09-08 11:49:43 -0700977 mCurrentInputTargetsValid = true;
978}
979
980int32_t InputDispatcher::handleTargetsNotReadyLocked(nsecs_t currentTime,
981 const EventEntry* entry, const InputApplication* application, const InputWindow* window,
982 nsecs_t* nextWakeupTime) {
983 if (application == NULL && window == NULL) {
984 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY) {
985#if DEBUG_FOCUS
986 LOGD("Waiting for system to become ready for input.");
987#endif
988 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY;
989 mInputTargetWaitStartTime = currentTime;
990 mInputTargetWaitTimeoutTime = LONG_LONG_MAX;
991 mInputTargetWaitTimeoutExpired = false;
Jeff Brown928e0542011-01-10 11:17:36 -0800992 mInputTargetWaitApplication.clear();
Jeff Brownb88102f2010-09-08 11:49:43 -0700993 }
994 } else {
995 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
996#if DEBUG_FOCUS
Jeff Brown519e0242010-09-15 15:18:56 -0700997 LOGD("Waiting for application to become ready for input: %s",
998 getApplicationWindowLabelLocked(application, window).string());
Jeff Brownb88102f2010-09-08 11:49:43 -0700999#endif
1000 nsecs_t timeout = window ? window->dispatchingTimeout :
1001 application ? application->dispatchingTimeout : DEFAULT_INPUT_DISPATCHING_TIMEOUT;
1002
1003 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY;
1004 mInputTargetWaitStartTime = currentTime;
1005 mInputTargetWaitTimeoutTime = currentTime + timeout;
1006 mInputTargetWaitTimeoutExpired = false;
Jeff Brown928e0542011-01-10 11:17:36 -08001007 mInputTargetWaitApplication.clear();
1008
1009 if (window && window->inputWindowHandle != NULL) {
1010 mInputTargetWaitApplication =
1011 window->inputWindowHandle->getInputApplicationHandle();
1012 }
1013 if (mInputTargetWaitApplication == NULL && application) {
1014 mInputTargetWaitApplication = application->inputApplicationHandle;
1015 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001016 }
1017 }
1018
1019 if (mInputTargetWaitTimeoutExpired) {
1020 return INPUT_EVENT_INJECTION_TIMED_OUT;
1021 }
1022
1023 if (currentTime >= mInputTargetWaitTimeoutTime) {
Jeff Brown519e0242010-09-15 15:18:56 -07001024 onANRLocked(currentTime, application, window, entry->eventTime, mInputTargetWaitStartTime);
Jeff Brownb88102f2010-09-08 11:49:43 -07001025
1026 // Force poll loop to wake up immediately on next iteration once we get the
1027 // ANR response back from the policy.
1028 *nextWakeupTime = LONG_LONG_MIN;
1029 return INPUT_EVENT_INJECTION_PENDING;
1030 } else {
1031 // Force poll loop to wake up when timeout is due.
1032 if (mInputTargetWaitTimeoutTime < *nextWakeupTime) {
1033 *nextWakeupTime = mInputTargetWaitTimeoutTime;
1034 }
1035 return INPUT_EVENT_INJECTION_PENDING;
1036 }
1037}
1038
Jeff Brown519e0242010-09-15 15:18:56 -07001039void InputDispatcher::resumeAfterTargetsNotReadyTimeoutLocked(nsecs_t newTimeout,
1040 const sp<InputChannel>& inputChannel) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001041 if (newTimeout > 0) {
1042 // Extend the timeout.
1043 mInputTargetWaitTimeoutTime = now() + newTimeout;
1044 } else {
1045 // Give up.
1046 mInputTargetWaitTimeoutExpired = true;
Jeff Brown519e0242010-09-15 15:18:56 -07001047
Jeff Brown01ce2e92010-09-26 22:20:12 -07001048 // Release the touch targets.
1049 mTouchState.reset();
Jeff Brown2a95c2a2010-09-16 12:31:46 -07001050
Jeff Brown519e0242010-09-15 15:18:56 -07001051 // Input state will not be realistic. Mark it out of sync.
Jeff Browndc3e0052010-09-16 11:02:16 -07001052 if (inputChannel.get()) {
1053 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
1054 if (connectionIndex >= 0) {
1055 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
Jeff Brown00045a72010-12-09 18:10:30 -08001056 if (connection->status == Connection::STATUS_NORMAL) {
Jeff Brown524ee642011-03-29 15:11:34 -07001057 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
Jeff Brown00045a72010-12-09 18:10:30 -08001058 "application not responding");
Jeff Brown524ee642011-03-29 15:11:34 -07001059 synthesizeCancelationEventsForConnectionLocked(connection, options);
Jeff Brown00045a72010-12-09 18:10:30 -08001060 }
Jeff Browndc3e0052010-09-16 11:02:16 -07001061 }
Jeff Brown519e0242010-09-15 15:18:56 -07001062 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001063 }
1064}
1065
Jeff Brown519e0242010-09-15 15:18:56 -07001066nsecs_t InputDispatcher::getTimeSpentWaitingForApplicationLocked(
Jeff Brownb88102f2010-09-08 11:49:43 -07001067 nsecs_t currentTime) {
1068 if (mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
1069 return currentTime - mInputTargetWaitStartTime;
1070 }
1071 return 0;
1072}
1073
1074void InputDispatcher::resetANRTimeoutsLocked() {
1075#if DEBUG_FOCUS
1076 LOGD("Resetting ANR timeouts.");
1077#endif
1078
Jeff Brownb88102f2010-09-08 11:49:43 -07001079 // Reset input target wait timeout.
1080 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_NONE;
1081}
1082
Jeff Brown01ce2e92010-09-26 22:20:12 -07001083int32_t InputDispatcher::findFocusedWindowTargetsLocked(nsecs_t currentTime,
1084 const EventEntry* entry, nsecs_t* nextWakeupTime) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001085 mCurrentInputTargets.clear();
1086
1087 int32_t injectionResult;
1088
1089 // If there is no currently focused window and no focused application
1090 // then drop the event.
1091 if (! mFocusedWindow) {
1092 if (mFocusedApplication) {
1093#if DEBUG_FOCUS
1094 LOGD("Waiting because there is no focused window but there is a "
Jeff Brown519e0242010-09-15 15:18:56 -07001095 "focused application that may eventually add a window: %s.",
1096 getApplicationWindowLabelLocked(mFocusedApplication, NULL).string());
Jeff Brownb88102f2010-09-08 11:49:43 -07001097#endif
1098 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
1099 mFocusedApplication, NULL, nextWakeupTime);
1100 goto Unresponsive;
1101 }
1102
1103 LOGI("Dropping event because there is no focused window or focused application.");
1104 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1105 goto Failed;
1106 }
1107
1108 // Check permissions.
Jeff Brown01ce2e92010-09-26 22:20:12 -07001109 if (! checkInjectionPermission(mFocusedWindow, entry->injectionState)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001110 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1111 goto Failed;
1112 }
1113
1114 // If the currently focused window is paused then keep waiting.
1115 if (mFocusedWindow->paused) {
1116#if DEBUG_FOCUS
1117 LOGD("Waiting because focused window is paused.");
1118#endif
1119 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
1120 mFocusedApplication, mFocusedWindow, nextWakeupTime);
1121 goto Unresponsive;
1122 }
1123
Jeff Brown519e0242010-09-15 15:18:56 -07001124 // If the currently focused window is still working on previous events then keep waiting.
1125 if (! isWindowFinishedWithPreviousInputLocked(mFocusedWindow)) {
1126#if DEBUG_FOCUS
1127 LOGD("Waiting because focused window still processing previous input.");
1128#endif
1129 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
1130 mFocusedApplication, mFocusedWindow, nextWakeupTime);
1131 goto Unresponsive;
1132 }
1133
Jeff Brownb88102f2010-09-08 11:49:43 -07001134 // Success! Output targets.
1135 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001136 addWindowTargetLocked(mFocusedWindow, InputTarget::FLAG_FOREGROUND, BitSet32(0));
Jeff Brownb88102f2010-09-08 11:49:43 -07001137
1138 // Done.
1139Failed:
1140Unresponsive:
Jeff Brown519e0242010-09-15 15:18:56 -07001141 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
1142 updateDispatchStatisticsLocked(currentTime, entry,
1143 injectionResult, timeSpentWaitingForApplication);
Jeff Brownb88102f2010-09-08 11:49:43 -07001144#if DEBUG_FOCUS
Jeff Brown519e0242010-09-15 15:18:56 -07001145 LOGD("findFocusedWindow finished: injectionResult=%d, "
1146 "timeSpendWaitingForApplication=%0.1fms",
1147 injectionResult, timeSpentWaitingForApplication / 1000000.0);
Jeff Brownb88102f2010-09-08 11:49:43 -07001148#endif
1149 return injectionResult;
1150}
1151
Jeff Brown01ce2e92010-09-26 22:20:12 -07001152int32_t InputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime,
Jeff Browncc0c1592011-02-19 05:07:28 -08001153 const MotionEntry* entry, nsecs_t* nextWakeupTime, bool* outConflictingPointerActions) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001154 enum InjectionPermission {
1155 INJECTION_PERMISSION_UNKNOWN,
1156 INJECTION_PERMISSION_GRANTED,
1157 INJECTION_PERMISSION_DENIED
1158 };
1159
Jeff Brownb88102f2010-09-08 11:49:43 -07001160 mCurrentInputTargets.clear();
1161
1162 nsecs_t startTime = now();
1163
1164 // For security reasons, we defer updating the touch state until we are sure that
1165 // event injection will be allowed.
1166 //
1167 // FIXME In the original code, screenWasOff could never be set to true.
1168 // The reason is that the POLICY_FLAG_WOKE_HERE
1169 // and POLICY_FLAG_BRIGHT_HERE flags were set only when preprocessing raw
1170 // EV_KEY, EV_REL and EV_ABS events. As it happens, the touch event was
1171 // actually enqueued using the policyFlags that appeared in the final EV_SYN
1172 // events upon which no preprocessing took place. So policyFlags was always 0.
1173 // In the new native input dispatcher we're a bit more careful about event
1174 // preprocessing so the touches we receive can actually have non-zero policyFlags.
1175 // Unfortunately we obtain undesirable behavior.
1176 //
1177 // Here's what happens:
1178 //
1179 // When the device dims in anticipation of going to sleep, touches
1180 // in windows which have FLAG_TOUCHABLE_WHEN_WAKING cause
1181 // the device to brighten and reset the user activity timer.
1182 // Touches on other windows (such as the launcher window)
1183 // are dropped. Then after a moment, the device goes to sleep. Oops.
1184 //
1185 // Also notice how screenWasOff was being initialized using POLICY_FLAG_BRIGHT_HERE
1186 // instead of POLICY_FLAG_WOKE_HERE...
1187 //
1188 bool screenWasOff = false; // original policy: policyFlags & POLICY_FLAG_BRIGHT_HERE;
1189
1190 int32_t action = entry->action;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001191 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Jeff Brownb88102f2010-09-08 11:49:43 -07001192
1193 // Update the touch state as needed based on the properties of the touch event.
Jeff Brown01ce2e92010-09-26 22:20:12 -07001194 int32_t injectionResult = INPUT_EVENT_INJECTION_PENDING;
1195 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
Jeff Browncc0c1592011-02-19 05:07:28 -08001196
1197 bool isSplit = mTouchState.split;
1198 bool wrongDevice = mTouchState.down
1199 && (mTouchState.deviceId != entry->deviceId
1200 || mTouchState.source != entry->source);
1201 if (maskedAction == AMOTION_EVENT_ACTION_DOWN
Jeff Brown33bbfd22011-02-24 20:55:35 -08001202 || maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE
1203 || maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
Jeff Browncc0c1592011-02-19 05:07:28 -08001204 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
1205 if (wrongDevice && !down) {
1206 mTempTouchState.copyFrom(mTouchState);
1207 } else {
1208 mTempTouchState.reset();
1209 mTempTouchState.down = down;
1210 mTempTouchState.deviceId = entry->deviceId;
1211 mTempTouchState.source = entry->source;
1212 isSplit = false;
1213 wrongDevice = false;
1214 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001215 } else {
1216 mTempTouchState.copyFrom(mTouchState);
Jeff Browncc0c1592011-02-19 05:07:28 -08001217 }
1218 if (wrongDevice) {
Jeff Brown22d789d2011-03-25 11:58:46 -07001219#if DEBUG_FOCUS
Jeff Browncc0c1592011-02-19 05:07:28 -08001220 LOGD("Dropping event because a pointer for a different device is already down.");
Jeff Brown95712852011-01-04 19:41:59 -08001221#endif
Jeff Browncc0c1592011-02-19 05:07:28 -08001222 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1223 goto Failed;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001224 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001225
Jeff Brown01ce2e92010-09-26 22:20:12 -07001226 if (maskedAction == AMOTION_EVENT_ACTION_DOWN
Jeff Browncc0c1592011-02-19 05:07:28 -08001227 || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)
Jeff Brown33bbfd22011-02-24 20:55:35 -08001228 || maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE
1229 || maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
1230 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
Jeff Brownb88102f2010-09-08 11:49:43 -07001231
Jeff Brown01ce2e92010-09-26 22:20:12 -07001232 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Jeff Brown91c69ab2011-02-14 17:03:18 -08001233 int32_t x = int32_t(entry->firstSample.pointerCoords[pointerIndex].
Jeff Brownebbd5d12011-02-17 13:01:34 -08001234 getAxisValue(AMOTION_EVENT_AXIS_X));
Jeff Brown91c69ab2011-02-14 17:03:18 -08001235 int32_t y = int32_t(entry->firstSample.pointerCoords[pointerIndex].
Jeff Brownebbd5d12011-02-17 13:01:34 -08001236 getAxisValue(AMOTION_EVENT_AXIS_Y));
Jeff Brown01ce2e92010-09-26 22:20:12 -07001237 const InputWindow* newTouchedWindow = NULL;
1238 const InputWindow* topErrorWindow = NULL;
Jeff Brownb88102f2010-09-08 11:49:43 -07001239
1240 // Traverse windows from front to back to find touched window and outside targets.
1241 size_t numWindows = mWindows.size();
1242 for (size_t i = 0; i < numWindows; i++) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001243 const InputWindow* window = & mWindows.editItemAt(i);
Jeff Brownb88102f2010-09-08 11:49:43 -07001244 int32_t flags = window->layoutParamsFlags;
1245
1246 if (flags & InputWindow::FLAG_SYSTEM_ERROR) {
1247 if (! topErrorWindow) {
1248 topErrorWindow = window;
1249 }
1250 }
1251
1252 if (window->visible) {
1253 if (! (flags & InputWindow::FLAG_NOT_TOUCHABLE)) {
1254 bool isTouchModal = (flags & (InputWindow::FLAG_NOT_FOCUSABLE
1255 | InputWindow::FLAG_NOT_TOUCH_MODAL)) == 0;
Jeff Brownfbf09772011-01-16 14:06:57 -08001256 if (isTouchModal || window->touchableRegionContainsPoint(x, y)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001257 if (! screenWasOff || flags & InputWindow::FLAG_TOUCHABLE_WHEN_WAKING) {
1258 newTouchedWindow = window;
Jeff Brownb88102f2010-09-08 11:49:43 -07001259 }
1260 break; // found touched window, exit window loop
1261 }
1262 }
1263
Jeff Brown01ce2e92010-09-26 22:20:12 -07001264 if (maskedAction == AMOTION_EVENT_ACTION_DOWN
1265 && (flags & InputWindow::FLAG_WATCH_OUTSIDE_TOUCH)) {
Jeff Brown19dfc832010-10-05 12:26:23 -07001266 int32_t outsideTargetFlags = InputTarget::FLAG_OUTSIDE;
1267 if (isWindowObscuredAtPointLocked(window, x, y)) {
1268 outsideTargetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1269 }
1270
1271 mTempTouchState.addOrUpdateWindow(window, outsideTargetFlags, BitSet32(0));
Jeff Brownb88102f2010-09-08 11:49:43 -07001272 }
1273 }
1274 }
1275
1276 // If there is an error window but it is not taking focus (typically because
1277 // it is invisible) then wait for it. Any other focused window may in
1278 // fact be in ANR state.
1279 if (topErrorWindow && newTouchedWindow != topErrorWindow) {
1280#if DEBUG_FOCUS
1281 LOGD("Waiting because system error window is pending.");
1282#endif
1283 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
1284 NULL, NULL, nextWakeupTime);
1285 injectionPermission = INJECTION_PERMISSION_UNKNOWN;
1286 goto Unresponsive;
1287 }
1288
Jeff Brown01ce2e92010-09-26 22:20:12 -07001289 // Figure out whether splitting will be allowed for this window.
Jeff Brown46e75292010-11-10 16:53:45 -08001290 if (newTouchedWindow && newTouchedWindow->supportsSplitTouch()) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001291 // New window supports splitting.
1292 isSplit = true;
1293 } else if (isSplit) {
1294 // New window does not support splitting but we have already split events.
1295 // Assign the pointer to the first foreground window we find.
1296 // (May be NULL which is why we put this code block before the next check.)
1297 newTouchedWindow = mTempTouchState.getFirstForegroundWindow();
1298 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001299
Jeff Brownb88102f2010-09-08 11:49:43 -07001300 // If we did not find a touched window then fail.
1301 if (! newTouchedWindow) {
1302 if (mFocusedApplication) {
1303#if DEBUG_FOCUS
1304 LOGD("Waiting because there is no touched window but there is a "
Jeff Brown519e0242010-09-15 15:18:56 -07001305 "focused application that may eventually add a new window: %s.",
1306 getApplicationWindowLabelLocked(mFocusedApplication, NULL).string());
Jeff Brownb88102f2010-09-08 11:49:43 -07001307#endif
1308 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
1309 mFocusedApplication, NULL, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -07001310 goto Unresponsive;
1311 }
1312
1313 LOGI("Dropping event because there is no touched window or focused application.");
1314 injectionResult = INPUT_EVENT_INJECTION_FAILED;
Jeff Brownb88102f2010-09-08 11:49:43 -07001315 goto Failed;
1316 }
1317
Jeff Brown19dfc832010-10-05 12:26:23 -07001318 // Set target flags.
1319 int32_t targetFlags = InputTarget::FLAG_FOREGROUND;
1320 if (isSplit) {
1321 targetFlags |= InputTarget::FLAG_SPLIT;
1322 }
1323 if (isWindowObscuredAtPointLocked(newTouchedWindow, x, y)) {
1324 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1325 }
1326
Jeff Brown01ce2e92010-09-26 22:20:12 -07001327 // Update the temporary touch state.
1328 BitSet32 pointerIds;
1329 if (isSplit) {
1330 uint32_t pointerId = entry->pointerIds[pointerIndex];
1331 pointerIds.markBit(pointerId);
Jeff Brownb88102f2010-09-08 11:49:43 -07001332 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001333 mTempTouchState.addOrUpdateWindow(newTouchedWindow, targetFlags, pointerIds);
Jeff Brownb88102f2010-09-08 11:49:43 -07001334 } else {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001335 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
Jeff Brownb88102f2010-09-08 11:49:43 -07001336
1337 // If the pointer is not currently down, then ignore the event.
Jeff Brown01ce2e92010-09-26 22:20:12 -07001338 if (! mTempTouchState.down) {
Jeff Brown22d789d2011-03-25 11:58:46 -07001339#if DEBUG_FOCUS
Jeff Brown76860e32010-10-25 17:37:46 -07001340 LOGD("Dropping event because the pointer is not down or we previously "
1341 "dropped the pointer down event.");
1342#endif
Jeff Brownb88102f2010-09-08 11:49:43 -07001343 injectionResult = INPUT_EVENT_INJECTION_FAILED;
Jeff Brownb88102f2010-09-08 11:49:43 -07001344 goto Failed;
1345 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001346 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001347
Jeff Brown01ce2e92010-09-26 22:20:12 -07001348 // Check permission to inject into all touched foreground windows and ensure there
1349 // is at least one touched foreground window.
1350 {
1351 bool haveForegroundWindow = false;
1352 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1353 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1354 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1355 haveForegroundWindow = true;
1356 if (! checkInjectionPermission(touchedWindow.window, entry->injectionState)) {
1357 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1358 injectionPermission = INJECTION_PERMISSION_DENIED;
1359 goto Failed;
1360 }
1361 }
1362 }
1363 if (! haveForegroundWindow) {
Jeff Brown22d789d2011-03-25 11:58:46 -07001364#if DEBUG_FOCUS
Jeff Brown01ce2e92010-09-26 22:20:12 -07001365 LOGD("Dropping event because there is no touched foreground window to receive it.");
Jeff Brownb88102f2010-09-08 11:49:43 -07001366#endif
1367 injectionResult = INPUT_EVENT_INJECTION_FAILED;
Jeff Brownb88102f2010-09-08 11:49:43 -07001368 goto Failed;
1369 }
1370
Jeff Brown01ce2e92010-09-26 22:20:12 -07001371 // Permission granted to injection into all touched foreground windows.
1372 injectionPermission = INJECTION_PERMISSION_GRANTED;
1373 }
Jeff Brown519e0242010-09-15 15:18:56 -07001374
Jeff Brown01ce2e92010-09-26 22:20:12 -07001375 // Ensure all touched foreground windows are ready for new input.
1376 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1377 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1378 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1379 // If the touched window is paused then keep waiting.
1380 if (touchedWindow.window->paused) {
Jeff Brown22d789d2011-03-25 11:58:46 -07001381#if DEBUG_FOCUS
Jeff Brown01ce2e92010-09-26 22:20:12 -07001382 LOGD("Waiting because touched window is paused.");
Jeff Brown519e0242010-09-15 15:18:56 -07001383#endif
Jeff Brown01ce2e92010-09-26 22:20:12 -07001384 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
1385 NULL, touchedWindow.window, nextWakeupTime);
1386 goto Unresponsive;
1387 }
1388
1389 // If the touched window is still working on previous events then keep waiting.
1390 if (! isWindowFinishedWithPreviousInputLocked(touchedWindow.window)) {
1391#if DEBUG_FOCUS
1392 LOGD("Waiting because touched window still processing previous input.");
1393#endif
1394 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
1395 NULL, touchedWindow.window, nextWakeupTime);
1396 goto Unresponsive;
1397 }
1398 }
1399 }
1400
1401 // If this is the first pointer going down and the touched window has a wallpaper
1402 // then also add the touched wallpaper windows so they are locked in for the duration
1403 // of the touch gesture.
Jeff Brown33bbfd22011-02-24 20:55:35 -08001404 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
1405 // engine only supports touch events. We would need to add a mechanism similar
1406 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
1407 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001408 const InputWindow* foregroundWindow = mTempTouchState.getFirstForegroundWindow();
1409 if (foregroundWindow->hasWallpaper) {
1410 for (size_t i = 0; i < mWindows.size(); i++) {
1411 const InputWindow* window = & mWindows[i];
1412 if (window->layoutParamsType == InputWindow::TYPE_WALLPAPER) {
Jeff Brown19dfc832010-10-05 12:26:23 -07001413 mTempTouchState.addOrUpdateWindow(window,
1414 InputTarget::FLAG_WINDOW_IS_OBSCURED, BitSet32(0));
Jeff Brown01ce2e92010-09-26 22:20:12 -07001415 }
1416 }
1417 }
1418 }
1419
Jeff Brownb88102f2010-09-08 11:49:43 -07001420 // Success! Output targets.
1421 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
Jeff Brownb88102f2010-09-08 11:49:43 -07001422
Jeff Brown01ce2e92010-09-26 22:20:12 -07001423 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1424 const TouchedWindow& touchedWindow = mTempTouchState.windows.itemAt(i);
1425 addWindowTargetLocked(touchedWindow.window, touchedWindow.targetFlags,
1426 touchedWindow.pointerIds);
Jeff Brownb88102f2010-09-08 11:49:43 -07001427 }
1428
Jeff Brown01ce2e92010-09-26 22:20:12 -07001429 // Drop the outside touch window since we will not care about them in the next iteration.
1430 mTempTouchState.removeOutsideTouchWindows();
1431
Jeff Brownb88102f2010-09-08 11:49:43 -07001432Failed:
1433 // Check injection permission once and for all.
1434 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001435 if (checkInjectionPermission(NULL, entry->injectionState)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001436 injectionPermission = INJECTION_PERMISSION_GRANTED;
1437 } else {
1438 injectionPermission = INJECTION_PERMISSION_DENIED;
1439 }
1440 }
1441
1442 // Update final pieces of touch state if the injector had permission.
1443 if (injectionPermission == INJECTION_PERMISSION_GRANTED) {
Jeff Brown95712852011-01-04 19:41:59 -08001444 if (!wrongDevice) {
1445 if (maskedAction == AMOTION_EVENT_ACTION_UP
Jeff Browncc0c1592011-02-19 05:07:28 -08001446 || maskedAction == AMOTION_EVENT_ACTION_CANCEL
1447 || maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Jeff Brown95712852011-01-04 19:41:59 -08001448 // All pointers up or canceled.
Jeff Brown33bbfd22011-02-24 20:55:35 -08001449 mTouchState.reset();
Jeff Brown95712852011-01-04 19:41:59 -08001450 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1451 // First pointer went down.
1452 if (mTouchState.down) {
Jeff Browncc0c1592011-02-19 05:07:28 -08001453 *outConflictingPointerActions = true;
Jeff Brownb6997262010-10-08 22:31:17 -07001454#if DEBUG_FOCUS
Jeff Brown95712852011-01-04 19:41:59 -08001455 LOGD("Pointer down received while already down.");
Jeff Brownb6997262010-10-08 22:31:17 -07001456#endif
Jeff Brown95712852011-01-04 19:41:59 -08001457 }
Jeff Brown33bbfd22011-02-24 20:55:35 -08001458 mTouchState.copyFrom(mTempTouchState);
Jeff Brown95712852011-01-04 19:41:59 -08001459 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
1460 // One pointer went up.
1461 if (isSplit) {
1462 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
1463 uint32_t pointerId = entry->pointerIds[pointerIndex];
Jeff Brownb88102f2010-09-08 11:49:43 -07001464
Jeff Brown95712852011-01-04 19:41:59 -08001465 for (size_t i = 0; i < mTempTouchState.windows.size(); ) {
1466 TouchedWindow& touchedWindow = mTempTouchState.windows.editItemAt(i);
1467 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
1468 touchedWindow.pointerIds.clearBit(pointerId);
1469 if (touchedWindow.pointerIds.isEmpty()) {
1470 mTempTouchState.windows.removeAt(i);
1471 continue;
1472 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001473 }
Jeff Brown95712852011-01-04 19:41:59 -08001474 i += 1;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001475 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001476 }
Jeff Brown33bbfd22011-02-24 20:55:35 -08001477 mTouchState.copyFrom(mTempTouchState);
1478 } else if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
1479 // Discard temporary touch state since it was only valid for this action.
1480 } else {
1481 // Save changes to touch state as-is for all other actions.
1482 mTouchState.copyFrom(mTempTouchState);
Jeff Brownb88102f2010-09-08 11:49:43 -07001483 }
Jeff Brown95712852011-01-04 19:41:59 -08001484 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001485 } else {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001486#if DEBUG_FOCUS
1487 LOGD("Not updating touch focus because injection was denied.");
1488#endif
Jeff Brownb88102f2010-09-08 11:49:43 -07001489 }
1490
1491Unresponsive:
Jeff Brown120a4592010-10-27 18:43:51 -07001492 // Reset temporary touch state to ensure we release unnecessary references to input channels.
1493 mTempTouchState.reset();
1494
Jeff Brown519e0242010-09-15 15:18:56 -07001495 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
1496 updateDispatchStatisticsLocked(currentTime, entry,
1497 injectionResult, timeSpentWaitingForApplication);
Jeff Brownb88102f2010-09-08 11:49:43 -07001498#if DEBUG_FOCUS
Jeff Brown01ce2e92010-09-26 22:20:12 -07001499 LOGD("findTouchedWindow finished: injectionResult=%d, injectionPermission=%d, "
1500 "timeSpentWaitingForApplication=%0.1fms",
Jeff Brown519e0242010-09-15 15:18:56 -07001501 injectionResult, injectionPermission, timeSpentWaitingForApplication / 1000000.0);
Jeff Brownb88102f2010-09-08 11:49:43 -07001502#endif
1503 return injectionResult;
1504}
1505
Jeff Brown01ce2e92010-09-26 22:20:12 -07001506void InputDispatcher::addWindowTargetLocked(const InputWindow* window, int32_t targetFlags,
1507 BitSet32 pointerIds) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001508 mCurrentInputTargets.push();
1509
1510 InputTarget& target = mCurrentInputTargets.editTop();
1511 target.inputChannel = window->inputChannel;
1512 target.flags = targetFlags;
Jeff Brownb88102f2010-09-08 11:49:43 -07001513 target.xOffset = - window->frameLeft;
1514 target.yOffset = - window->frameTop;
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001515 target.scaleFactor = window->scaleFactor;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001516 target.pointerIds = pointerIds;
Jeff Brownb88102f2010-09-08 11:49:43 -07001517}
1518
1519void InputDispatcher::addMonitoringTargetsLocked() {
1520 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
1521 mCurrentInputTargets.push();
1522
1523 InputTarget& target = mCurrentInputTargets.editTop();
1524 target.inputChannel = mMonitoringChannels[i];
1525 target.flags = 0;
Jeff Brownb88102f2010-09-08 11:49:43 -07001526 target.xOffset = 0;
1527 target.yOffset = 0;
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001528 target.scaleFactor = 1.0f;
Jeff Brownb88102f2010-09-08 11:49:43 -07001529 }
1530}
1531
1532bool InputDispatcher::checkInjectionPermission(const InputWindow* window,
Jeff Brown01ce2e92010-09-26 22:20:12 -07001533 const InjectionState* injectionState) {
1534 if (injectionState
Jeff Brownb6997262010-10-08 22:31:17 -07001535 && (window == NULL || window->ownerUid != injectionState->injectorUid)
1536 && !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
1537 if (window) {
1538 LOGW("Permission denied: injecting event from pid %d uid %d to window "
1539 "with input channel %s owned by uid %d",
1540 injectionState->injectorPid, injectionState->injectorUid,
1541 window->inputChannel->getName().string(),
1542 window->ownerUid);
1543 } else {
1544 LOGW("Permission denied: injecting event from pid %d uid %d",
1545 injectionState->injectorPid, injectionState->injectorUid);
Jeff Brownb88102f2010-09-08 11:49:43 -07001546 }
Jeff Brownb6997262010-10-08 22:31:17 -07001547 return false;
Jeff Brownb88102f2010-09-08 11:49:43 -07001548 }
1549 return true;
1550}
1551
Jeff Brown19dfc832010-10-05 12:26:23 -07001552bool InputDispatcher::isWindowObscuredAtPointLocked(
1553 const InputWindow* window, int32_t x, int32_t y) const {
Jeff Brownb88102f2010-09-08 11:49:43 -07001554 size_t numWindows = mWindows.size();
1555 for (size_t i = 0; i < numWindows; i++) {
1556 const InputWindow* other = & mWindows.itemAt(i);
1557 if (other == window) {
1558 break;
1559 }
Jeff Brown19dfc832010-10-05 12:26:23 -07001560 if (other->visible && ! other->isTrustedOverlay() && other->frameContainsPoint(x, y)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001561 return true;
1562 }
1563 }
1564 return false;
1565}
1566
Jeff Brown519e0242010-09-15 15:18:56 -07001567bool InputDispatcher::isWindowFinishedWithPreviousInputLocked(const InputWindow* window) {
1568 ssize_t connectionIndex = getConnectionIndexLocked(window->inputChannel);
1569 if (connectionIndex >= 0) {
1570 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
1571 return connection->outboundQueue.isEmpty();
1572 } else {
1573 return true;
1574 }
1575}
1576
1577String8 InputDispatcher::getApplicationWindowLabelLocked(const InputApplication* application,
1578 const InputWindow* window) {
1579 if (application) {
1580 if (window) {
1581 String8 label(application->name);
1582 label.append(" - ");
1583 label.append(window->name);
1584 return label;
1585 } else {
1586 return application->name;
1587 }
1588 } else if (window) {
1589 return window->name;
1590 } else {
1591 return String8("<unknown application or window>");
1592 }
1593}
1594
Jeff Browne2fe69e2010-10-18 13:21:23 -07001595void InputDispatcher::pokeUserActivityLocked(const EventEntry* eventEntry) {
Jeff Brown56194eb2011-03-02 19:23:13 -08001596 int32_t eventType = POWER_MANAGER_OTHER_EVENT;
Jeff Brown4d396052010-10-29 21:50:21 -07001597 switch (eventEntry->type) {
1598 case EventEntry::TYPE_MOTION: {
Jeff Browne2fe69e2010-10-18 13:21:23 -07001599 const MotionEntry* motionEntry = static_cast<const MotionEntry*>(eventEntry);
Jeff Brown4d396052010-10-29 21:50:21 -07001600 if (motionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
1601 return;
1602 }
1603
Jeff Brown56194eb2011-03-02 19:23:13 -08001604 if (MotionEvent::isTouchEvent(motionEntry->source, motionEntry->action)) {
Joe Onorato1a542c72010-11-08 09:48:20 -08001605 eventType = POWER_MANAGER_TOUCH_EVENT;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001606 }
Jeff Brown4d396052010-10-29 21:50:21 -07001607 break;
1608 }
1609 case EventEntry::TYPE_KEY: {
1610 const KeyEntry* keyEntry = static_cast<const KeyEntry*>(eventEntry);
1611 if (keyEntry->flags & AKEY_EVENT_FLAG_CANCELED) {
1612 return;
1613 }
Jeff Brown56194eb2011-03-02 19:23:13 -08001614 eventType = POWER_MANAGER_BUTTON_EVENT;
Jeff Brown4d396052010-10-29 21:50:21 -07001615 break;
1616 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001617 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001618
Jeff Brownb88102f2010-09-08 11:49:43 -07001619 CommandEntry* commandEntry = postCommandLocked(
1620 & InputDispatcher::doPokeUserActivityLockedInterruptible);
Jeff Browne2fe69e2010-10-18 13:21:23 -07001621 commandEntry->eventTime = eventEntry->eventTime;
Jeff Brownb88102f2010-09-08 11:49:43 -07001622 commandEntry->userActivityEventType = eventType;
1623}
1624
Jeff Brown7fbdc842010-06-17 20:52:56 -07001625void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
1626 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget,
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001627 bool resumeWithAppendedMotionSample) {
1628#if DEBUG_DISPATCH_CYCLE
Jeff Brown519e0242010-09-15 15:18:56 -07001629 LOGD("channel '%s' ~ prepareDispatchCycle - flags=%d, "
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001630 "xOffset=%f, yOffset=%f, scaleFactor=%f"
Jeff Brown83c09682010-12-23 17:50:18 -08001631 "pointerIds=0x%x, "
Jeff Brown01ce2e92010-09-26 22:20:12 -07001632 "resumeWithAppendedMotionSample=%s",
Jeff Brown519e0242010-09-15 15:18:56 -07001633 connection->getInputChannelName(), inputTarget->flags,
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001634 inputTarget->xOffset, inputTarget->yOffset,
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001635 inputTarget->scaleFactor, inputTarget->pointerIds.value,
Jeff Brownb88102f2010-09-08 11:49:43 -07001636 toString(resumeWithAppendedMotionSample));
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001637#endif
1638
Jeff Brown01ce2e92010-09-26 22:20:12 -07001639 // Make sure we are never called for streaming when splitting across multiple windows.
1640 bool isSplit = inputTarget->flags & InputTarget::FLAG_SPLIT;
1641 assert(! (resumeWithAppendedMotionSample && isSplit));
1642
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001643 // Skip this event if the connection status is not normal.
Jeff Brown519e0242010-09-15 15:18:56 -07001644 // We don't want to enqueue additional outbound events if the connection is broken.
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001645 if (connection->status != Connection::STATUS_NORMAL) {
Jeff Brownb6997262010-10-08 22:31:17 -07001646#if DEBUG_DISPATCH_CYCLE
1647 LOGD("channel '%s' ~ Dropping event because the channel status is %s",
Jeff Brownb88102f2010-09-08 11:49:43 -07001648 connection->getInputChannelName(), connection->getStatusLabel());
Jeff Brownb6997262010-10-08 22:31:17 -07001649#endif
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001650 return;
1651 }
1652
Jeff Brown01ce2e92010-09-26 22:20:12 -07001653 // Split a motion event if needed.
1654 if (isSplit) {
1655 assert(eventEntry->type == EventEntry::TYPE_MOTION);
1656
1657 MotionEntry* originalMotionEntry = static_cast<MotionEntry*>(eventEntry);
1658 if (inputTarget->pointerIds.count() != originalMotionEntry->pointerCount) {
1659 MotionEntry* splitMotionEntry = splitMotionEvent(
1660 originalMotionEntry, inputTarget->pointerIds);
Jeff Brown58a2da82011-01-25 16:02:22 -08001661 if (!splitMotionEntry) {
1662 return; // split event was dropped
1663 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001664#if DEBUG_FOCUS
1665 LOGD("channel '%s' ~ Split motion event.",
1666 connection->getInputChannelName());
1667 logOutboundMotionDetailsLocked(" ", splitMotionEntry);
1668#endif
1669 eventEntry = splitMotionEntry;
1670 }
1671 }
1672
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001673 // Resume the dispatch cycle with a freshly appended motion sample.
1674 // First we check that the last dispatch entry in the outbound queue is for the same
1675 // motion event to which we appended the motion sample. If we find such a dispatch
1676 // entry, and if it is currently in progress then we try to stream the new sample.
1677 bool wasEmpty = connection->outboundQueue.isEmpty();
1678
1679 if (! wasEmpty && resumeWithAppendedMotionSample) {
1680 DispatchEntry* motionEventDispatchEntry =
1681 connection->findQueuedDispatchEntryForEvent(eventEntry);
1682 if (motionEventDispatchEntry) {
1683 // If the dispatch entry is not in progress, then we must be busy dispatching an
1684 // earlier event. Not a problem, the motion event is on the outbound queue and will
1685 // be dispatched later.
1686 if (! motionEventDispatchEntry->inProgress) {
1687#if DEBUG_BATCHING
1688 LOGD("channel '%s' ~ Not streaming because the motion event has "
1689 "not yet been dispatched. "
1690 "(Waiting for earlier events to be consumed.)",
1691 connection->getInputChannelName());
1692#endif
1693 return;
1694 }
1695
1696 // If the dispatch entry is in progress but it already has a tail of pending
1697 // motion samples, then it must mean that the shared memory buffer filled up.
1698 // Not a problem, when this dispatch cycle is finished, we will eventually start
1699 // a new dispatch cycle to process the tail and that tail includes the newly
1700 // appended motion sample.
1701 if (motionEventDispatchEntry->tailMotionSample) {
1702#if DEBUG_BATCHING
1703 LOGD("channel '%s' ~ Not streaming because no new samples can "
1704 "be appended to the motion event in this dispatch cycle. "
1705 "(Waiting for next dispatch cycle to start.)",
1706 connection->getInputChannelName());
1707#endif
1708 return;
1709 }
1710
1711 // The dispatch entry is in progress and is still potentially open for streaming.
1712 // Try to stream the new motion sample. This might fail if the consumer has already
1713 // consumed the motion event (or if the channel is broken).
Jeff Brown01ce2e92010-09-26 22:20:12 -07001714 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
1715 MotionSample* appendedMotionSample = motionEntry->lastSample;
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001716 status_t status;
1717 if (motionEventDispatchEntry->scaleFactor == 1.0f) {
1718 status = connection->inputPublisher.appendMotionSample(
1719 appendedMotionSample->eventTime, appendedMotionSample->pointerCoords);
1720 } else {
1721 PointerCoords scaledCoords[MAX_POINTERS];
1722 for (size_t i = 0; i < motionEntry->pointerCount; i++) {
1723 scaledCoords[i] = appendedMotionSample->pointerCoords[i];
1724 scaledCoords[i].scale(motionEventDispatchEntry->scaleFactor);
1725 }
1726 status = connection->inputPublisher.appendMotionSample(
1727 appendedMotionSample->eventTime, scaledCoords);
1728 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001729 if (status == OK) {
1730#if DEBUG_BATCHING
1731 LOGD("channel '%s' ~ Successfully streamed new motion sample.",
1732 connection->getInputChannelName());
1733#endif
1734 return;
1735 }
1736
1737#if DEBUG_BATCHING
1738 if (status == NO_MEMORY) {
1739 LOGD("channel '%s' ~ Could not append motion sample to currently "
1740 "dispatched move event because the shared memory buffer is full. "
1741 "(Waiting for next dispatch cycle to start.)",
1742 connection->getInputChannelName());
1743 } else if (status == status_t(FAILED_TRANSACTION)) {
1744 LOGD("channel '%s' ~ Could not append motion sample to currently "
Jeff Brown349703e2010-06-22 01:27:15 -07001745 "dispatched move event because the event has already been consumed. "
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001746 "(Waiting for next dispatch cycle to start.)",
1747 connection->getInputChannelName());
1748 } else {
1749 LOGD("channel '%s' ~ Could not append motion sample to currently "
1750 "dispatched move event due to an error, status=%d. "
1751 "(Waiting for next dispatch cycle to start.)",
1752 connection->getInputChannelName(), status);
1753 }
1754#endif
1755 // Failed to stream. Start a new tail of pending motion samples to dispatch
1756 // in the next cycle.
1757 motionEventDispatchEntry->tailMotionSample = appendedMotionSample;
1758 return;
1759 }
1760 }
1761
1762 // This is a new event.
1763 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Jeff Brownb88102f2010-09-08 11:49:43 -07001764 DispatchEntry* dispatchEntry = mAllocator.obtainDispatchEntry(eventEntry, // increments ref
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001765 inputTarget->flags, inputTarget->xOffset, inputTarget->yOffset,
1766 inputTarget->scaleFactor);
Jeff Brown519e0242010-09-15 15:18:56 -07001767 if (dispatchEntry->hasForegroundTarget()) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001768 incrementPendingForegroundDispatchesLocked(eventEntry);
Jeff Brown6ec402b2010-07-28 15:48:59 -07001769 }
1770
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001771 // Handle the case where we could not stream a new motion sample because the consumer has
1772 // already consumed the motion event (otherwise the corresponding dispatch entry would
1773 // still be in the outbound queue for this connection). We set the head motion sample
1774 // to the list starting with the newly appended motion sample.
1775 if (resumeWithAppendedMotionSample) {
1776#if DEBUG_BATCHING
1777 LOGD("channel '%s' ~ Preparing a new dispatch cycle for additional motion samples "
1778 "that cannot be streamed because the motion event has already been consumed.",
1779 connection->getInputChannelName());
1780#endif
1781 MotionSample* appendedMotionSample = static_cast<MotionEntry*>(eventEntry)->lastSample;
1782 dispatchEntry->headMotionSample = appendedMotionSample;
1783 }
1784
1785 // Enqueue the dispatch entry.
1786 connection->outboundQueue.enqueueAtTail(dispatchEntry);
1787
1788 // If the outbound queue was previously empty, start the dispatch cycle going.
1789 if (wasEmpty) {
Jeff Brown7fbdc842010-06-17 20:52:56 -07001790 activateConnectionLocked(connection.get());
Jeff Brown519e0242010-09-15 15:18:56 -07001791 startDispatchCycleLocked(currentTime, connection);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001792 }
1793}
1794
Jeff Brown7fbdc842010-06-17 20:52:56 -07001795void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Jeff Brown519e0242010-09-15 15:18:56 -07001796 const sp<Connection>& connection) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001797#if DEBUG_DISPATCH_CYCLE
1798 LOGD("channel '%s' ~ startDispatchCycle",
1799 connection->getInputChannelName());
1800#endif
1801
1802 assert(connection->status == Connection::STATUS_NORMAL);
1803 assert(! connection->outboundQueue.isEmpty());
1804
Jeff Brownb88102f2010-09-08 11:49:43 -07001805 DispatchEntry* dispatchEntry = connection->outboundQueue.headSentinel.next;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001806 assert(! dispatchEntry->inProgress);
1807
Jeff Brownb88102f2010-09-08 11:49:43 -07001808 // Mark the dispatch entry as in progress.
1809 dispatchEntry->inProgress = true;
1810
1811 // Update the connection's input state.
Jeff Brown01ce2e92010-09-26 22:20:12 -07001812 EventEntry* eventEntry = dispatchEntry->eventEntry;
Jeff Browncc0c1592011-02-19 05:07:28 -08001813 connection->inputState.trackEvent(eventEntry);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001814
1815 // Publish the event.
1816 status_t status;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001817 switch (eventEntry->type) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001818 case EventEntry::TYPE_KEY: {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001819 KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001820
1821 // Apply target flags.
1822 int32_t action = keyEntry->action;
1823 int32_t flags = keyEntry->flags;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001824
1825 // Publish the key event.
Jeff Brownc5ed5912010-07-14 18:48:53 -07001826 status = connection->inputPublisher.publishKeyEvent(keyEntry->deviceId, keyEntry->source,
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001827 action, flags, keyEntry->keyCode, keyEntry->scanCode,
1828 keyEntry->metaState, keyEntry->repeatCount, keyEntry->downTime,
1829 keyEntry->eventTime);
1830
1831 if (status) {
1832 LOGE("channel '%s' ~ Could not publish key event, "
1833 "status=%d", connection->getInputChannelName(), status);
Jeff Brownb6997262010-10-08 22:31:17 -07001834 abortBrokenDispatchCycleLocked(currentTime, connection);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001835 return;
1836 }
1837 break;
1838 }
1839
1840 case EventEntry::TYPE_MOTION: {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001841 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001842
1843 // Apply target flags.
1844 int32_t action = motionEntry->action;
Jeff Brown85a31762010-09-01 17:01:00 -07001845 int32_t flags = motionEntry->flags;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001846 if (dispatchEntry->targetFlags & InputTarget::FLAG_OUTSIDE) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001847 action = AMOTION_EVENT_ACTION_OUTSIDE;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001848 }
Jeff Brown85a31762010-09-01 17:01:00 -07001849 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
1850 flags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
1851 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001852
1853 // If headMotionSample is non-NULL, then it points to the first new sample that we
1854 // were unable to dispatch during the previous cycle so we resume dispatching from
1855 // that point in the list of motion samples.
1856 // Otherwise, we just start from the first sample of the motion event.
1857 MotionSample* firstMotionSample = dispatchEntry->headMotionSample;
1858 if (! firstMotionSample) {
1859 firstMotionSample = & motionEntry->firstSample;
1860 }
1861
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001862 PointerCoords scaledCoords[MAX_POINTERS];
1863 const PointerCoords* usingCoords = firstMotionSample->pointerCoords;
1864
Jeff Brownd3616592010-07-16 17:21:06 -07001865 // Set the X and Y offset depending on the input source.
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001866 float xOffset, yOffset, scaleFactor;
Jeff Brownd3616592010-07-16 17:21:06 -07001867 if (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) {
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001868 scaleFactor = dispatchEntry->scaleFactor;
1869 xOffset = dispatchEntry->xOffset * scaleFactor;
1870 yOffset = dispatchEntry->yOffset * scaleFactor;
1871 if (scaleFactor != 1.0f) {
1872 for (size_t i = 0; i < motionEntry->pointerCount; i++) {
1873 scaledCoords[i] = firstMotionSample->pointerCoords[i];
1874 scaledCoords[i].scale(scaleFactor);
1875 }
1876 usingCoords = scaledCoords;
1877 }
Jeff Brownd3616592010-07-16 17:21:06 -07001878 } else {
1879 xOffset = 0.0f;
1880 yOffset = 0.0f;
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001881 scaleFactor = 1.0f;
Jeff Brownd3616592010-07-16 17:21:06 -07001882 }
1883
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001884 // Publish the motion event and the first motion sample.
1885 status = connection->inputPublisher.publishMotionEvent(motionEntry->deviceId,
Jeff Brown85a31762010-09-01 17:01:00 -07001886 motionEntry->source, action, flags, motionEntry->edgeFlags, motionEntry->metaState,
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001887 xOffset, yOffset, motionEntry->xPrecision, motionEntry->yPrecision,
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001888 motionEntry->downTime, firstMotionSample->eventTime,
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001889 motionEntry->pointerCount, motionEntry->pointerIds, usingCoords);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001890
1891 if (status) {
1892 LOGE("channel '%s' ~ Could not publish motion event, "
1893 "status=%d", connection->getInputChannelName(), status);
Jeff Brownb6997262010-10-08 22:31:17 -07001894 abortBrokenDispatchCycleLocked(currentTime, connection);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001895 return;
1896 }
1897
1898 // Append additional motion samples.
1899 MotionSample* nextMotionSample = firstMotionSample->next;
1900 for (; nextMotionSample != NULL; nextMotionSample = nextMotionSample->next) {
Dianne Hackborne7d25b72011-05-09 21:19:26 -07001901 if ((motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) != 0 && scaleFactor != 1.0f) {
1902 for (size_t i = 0; i < motionEntry->pointerCount; i++) {
1903 scaledCoords[i] = nextMotionSample->pointerCoords[i];
1904 scaledCoords[i].scale(scaleFactor);
1905 }
1906 } else {
1907 usingCoords = nextMotionSample->pointerCoords;
1908 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001909 status = connection->inputPublisher.appendMotionSample(
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001910 nextMotionSample->eventTime, usingCoords);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001911 if (status == NO_MEMORY) {
1912#if DEBUG_DISPATCH_CYCLE
1913 LOGD("channel '%s' ~ Shared memory buffer full. Some motion samples will "
1914 "be sent in the next dispatch cycle.",
1915 connection->getInputChannelName());
1916#endif
1917 break;
1918 }
1919 if (status != OK) {
1920 LOGE("channel '%s' ~ Could not append motion sample "
1921 "for a reason other than out of memory, status=%d",
1922 connection->getInputChannelName(), status);
Jeff Brownb6997262010-10-08 22:31:17 -07001923 abortBrokenDispatchCycleLocked(currentTime, connection);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001924 return;
1925 }
1926 }
1927
1928 // Remember the next motion sample that we could not dispatch, in case we ran out
1929 // of space in the shared memory buffer.
1930 dispatchEntry->tailMotionSample = nextMotionSample;
1931 break;
1932 }
1933
1934 default: {
1935 assert(false);
1936 }
1937 }
1938
1939 // Send the dispatch signal.
1940 status = connection->inputPublisher.sendDispatchSignal();
1941 if (status) {
1942 LOGE("channel '%s' ~ Could not send dispatch signal, status=%d",
1943 connection->getInputChannelName(), status);
Jeff Brownb6997262010-10-08 22:31:17 -07001944 abortBrokenDispatchCycleLocked(currentTime, connection);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001945 return;
1946 }
1947
1948 // Record information about the newly started dispatch cycle.
Jeff Brown01ce2e92010-09-26 22:20:12 -07001949 connection->lastEventTime = eventEntry->eventTime;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001950 connection->lastDispatchTime = currentTime;
1951
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001952 // Notify other system components.
1953 onDispatchCycleStartedLocked(currentTime, connection);
1954}
1955
Jeff Brown7fbdc842010-06-17 20:52:56 -07001956void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Jeff Brown3915bb82010-11-05 15:02:16 -07001957 const sp<Connection>& connection, bool handled) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001958#if DEBUG_DISPATCH_CYCLE
Jeff Brown9c3cda02010-06-15 01:31:58 -07001959 LOGD("channel '%s' ~ finishDispatchCycle - %01.1fms since event, "
Jeff Brown3915bb82010-11-05 15:02:16 -07001960 "%01.1fms since dispatch, handled=%s",
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001961 connection->getInputChannelName(),
1962 connection->getEventLatencyMillis(currentTime),
Jeff Brown3915bb82010-11-05 15:02:16 -07001963 connection->getDispatchLatencyMillis(currentTime),
1964 toString(handled));
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001965#endif
1966
Jeff Brown9c3cda02010-06-15 01:31:58 -07001967 if (connection->status == Connection::STATUS_BROKEN
1968 || connection->status == Connection::STATUS_ZOMBIE) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001969 return;
1970 }
1971
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001972 // Reset the publisher since the event has been consumed.
1973 // We do this now so that the publisher can release some of its internal resources
1974 // while waiting for the next dispatch cycle to begin.
1975 status_t status = connection->inputPublisher.reset();
1976 if (status) {
1977 LOGE("channel '%s' ~ Could not reset publisher, status=%d",
1978 connection->getInputChannelName(), status);
Jeff Brownb6997262010-10-08 22:31:17 -07001979 abortBrokenDispatchCycleLocked(currentTime, connection);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001980 return;
1981 }
1982
Jeff Brown3915bb82010-11-05 15:02:16 -07001983 // Notify other system components and prepare to start the next dispatch cycle.
1984 onDispatchCycleFinishedLocked(currentTime, connection, handled);
Jeff Brownb88102f2010-09-08 11:49:43 -07001985}
1986
1987void InputDispatcher::startNextDispatchCycleLocked(nsecs_t currentTime,
1988 const sp<Connection>& connection) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001989 // Start the next dispatch cycle for this connection.
1990 while (! connection->outboundQueue.isEmpty()) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001991 DispatchEntry* dispatchEntry = connection->outboundQueue.headSentinel.next;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001992 if (dispatchEntry->inProgress) {
1993 // Finish or resume current event in progress.
1994 if (dispatchEntry->tailMotionSample) {
1995 // We have a tail of undispatched motion samples.
1996 // Reuse the same DispatchEntry and start a new cycle.
1997 dispatchEntry->inProgress = false;
1998 dispatchEntry->headMotionSample = dispatchEntry->tailMotionSample;
1999 dispatchEntry->tailMotionSample = NULL;
Jeff Brown519e0242010-09-15 15:18:56 -07002000 startDispatchCycleLocked(currentTime, connection);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002001 return;
2002 }
2003 // Finished.
2004 connection->outboundQueue.dequeueAtHead();
Jeff Brown519e0242010-09-15 15:18:56 -07002005 if (dispatchEntry->hasForegroundTarget()) {
2006 decrementPendingForegroundDispatchesLocked(dispatchEntry->eventEntry);
Jeff Brown6ec402b2010-07-28 15:48:59 -07002007 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002008 mAllocator.releaseDispatchEntry(dispatchEntry);
2009 } else {
2010 // If the head is not in progress, then we must have already dequeued the in
Jeff Brown519e0242010-09-15 15:18:56 -07002011 // progress event, which means we actually aborted it.
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002012 // So just start the next event for this connection.
Jeff Brown519e0242010-09-15 15:18:56 -07002013 startDispatchCycleLocked(currentTime, connection);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002014 return;
2015 }
2016 }
2017
2018 // Outbound queue is empty, deactivate the connection.
Jeff Brown7fbdc842010-06-17 20:52:56 -07002019 deactivateConnectionLocked(connection.get());
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002020}
2021
Jeff Brownb6997262010-10-08 22:31:17 -07002022void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
2023 const sp<Connection>& connection) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002024#if DEBUG_DISPATCH_CYCLE
Jeff Brown83c09682010-12-23 17:50:18 -08002025 LOGD("channel '%s' ~ abortBrokenDispatchCycle",
2026 connection->getInputChannelName());
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002027#endif
2028
Jeff Brownb88102f2010-09-08 11:49:43 -07002029 // Clear the outbound queue.
Jeff Brown519e0242010-09-15 15:18:56 -07002030 drainOutboundQueueLocked(connection.get());
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002031
Jeff Brownb6997262010-10-08 22:31:17 -07002032 // The connection appears to be unrecoverably broken.
Jeff Brown9c3cda02010-06-15 01:31:58 -07002033 // Ignore already broken or zombie connections.
Jeff Brownb6997262010-10-08 22:31:17 -07002034 if (connection->status == Connection::STATUS_NORMAL) {
2035 connection->status = Connection::STATUS_BROKEN;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002036
Jeff Brownb6997262010-10-08 22:31:17 -07002037 // Notify other system components.
2038 onDispatchCycleBrokenLocked(currentTime, connection);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002039 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002040}
2041
Jeff Brown519e0242010-09-15 15:18:56 -07002042void InputDispatcher::drainOutboundQueueLocked(Connection* connection) {
2043 while (! connection->outboundQueue.isEmpty()) {
2044 DispatchEntry* dispatchEntry = connection->outboundQueue.dequeueAtHead();
2045 if (dispatchEntry->hasForegroundTarget()) {
2046 decrementPendingForegroundDispatchesLocked(dispatchEntry->eventEntry);
Jeff Brownb88102f2010-09-08 11:49:43 -07002047 }
2048 mAllocator.releaseDispatchEntry(dispatchEntry);
Jeff Brownb88102f2010-09-08 11:49:43 -07002049 }
2050
Jeff Brown519e0242010-09-15 15:18:56 -07002051 deactivateConnectionLocked(connection);
Jeff Brownb88102f2010-09-08 11:49:43 -07002052}
2053
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002054int InputDispatcher::handleReceiveCallback(int receiveFd, int events, void* data) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002055 InputDispatcher* d = static_cast<InputDispatcher*>(data);
2056
2057 { // acquire lock
2058 AutoMutex _l(d->mLock);
2059
2060 ssize_t connectionIndex = d->mConnectionsByReceiveFd.indexOfKey(receiveFd);
2061 if (connectionIndex < 0) {
2062 LOGE("Received spurious receive callback for unknown input channel. "
2063 "fd=%d, events=0x%x", receiveFd, events);
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002064 return 0; // remove the callback
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002065 }
2066
Jeff Brown7fbdc842010-06-17 20:52:56 -07002067 nsecs_t currentTime = now();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002068
2069 sp<Connection> connection = d->mConnectionsByReceiveFd.valueAt(connectionIndex);
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002070 if (events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP)) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002071 LOGE("channel '%s' ~ Consumer closed input channel or an error occurred. "
2072 "events=0x%x", connection->getInputChannelName(), events);
Jeff Brownb6997262010-10-08 22:31:17 -07002073 d->abortBrokenDispatchCycleLocked(currentTime, connection);
Jeff Brown9c3cda02010-06-15 01:31:58 -07002074 d->runCommandsLockedInterruptible();
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002075 return 0; // remove the callback
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002076 }
2077
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002078 if (! (events & ALOOPER_EVENT_INPUT)) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002079 LOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
2080 "events=0x%x", connection->getInputChannelName(), events);
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002081 return 1;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002082 }
2083
Jeff Brown3915bb82010-11-05 15:02:16 -07002084 bool handled = false;
Jeff Brown49ed71d2010-12-06 17:13:33 -08002085 status_t status = connection->inputPublisher.receiveFinishedSignal(&handled);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002086 if (status) {
2087 LOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
2088 connection->getInputChannelName(), status);
Jeff Brownb6997262010-10-08 22:31:17 -07002089 d->abortBrokenDispatchCycleLocked(currentTime, connection);
Jeff Brown9c3cda02010-06-15 01:31:58 -07002090 d->runCommandsLockedInterruptible();
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002091 return 0; // remove the callback
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002092 }
2093
Jeff Brown3915bb82010-11-05 15:02:16 -07002094 d->finishDispatchCycleLocked(currentTime, connection, handled);
Jeff Brown9c3cda02010-06-15 01:31:58 -07002095 d->runCommandsLockedInterruptible();
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002096 return 1;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002097 } // release lock
2098}
2099
Jeff Brownb6997262010-10-08 22:31:17 -07002100void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Jeff Brown524ee642011-03-29 15:11:34 -07002101 const CancelationOptions& options) {
Jeff Brownb6997262010-10-08 22:31:17 -07002102 for (size_t i = 0; i < mConnectionsByReceiveFd.size(); i++) {
2103 synthesizeCancelationEventsForConnectionLocked(
Jeff Brown524ee642011-03-29 15:11:34 -07002104 mConnectionsByReceiveFd.valueAt(i), options);
Jeff Brownb6997262010-10-08 22:31:17 -07002105 }
2106}
2107
2108void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Jeff Brown524ee642011-03-29 15:11:34 -07002109 const sp<InputChannel>& channel, const CancelationOptions& options) {
Jeff Brownb6997262010-10-08 22:31:17 -07002110 ssize_t index = getConnectionIndexLocked(channel);
2111 if (index >= 0) {
2112 synthesizeCancelationEventsForConnectionLocked(
Jeff Brown524ee642011-03-29 15:11:34 -07002113 mConnectionsByReceiveFd.valueAt(index), options);
Jeff Brownb6997262010-10-08 22:31:17 -07002114 }
2115}
2116
2117void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
Jeff Brown524ee642011-03-29 15:11:34 -07002118 const sp<Connection>& connection, const CancelationOptions& options) {
Jeff Brownb6997262010-10-08 22:31:17 -07002119 nsecs_t currentTime = now();
2120
2121 mTempCancelationEvents.clear();
2122 connection->inputState.synthesizeCancelationEvents(currentTime, & mAllocator,
2123 mTempCancelationEvents, options);
2124
2125 if (! mTempCancelationEvents.isEmpty()
2126 && connection->status != Connection::STATUS_BROKEN) {
2127#if DEBUG_OUTBOUND_EVENT_DETAILS
2128 LOGD("channel '%s' ~ Synthesized %d cancelation events to bring channel back in sync "
Jeff Brown524ee642011-03-29 15:11:34 -07002129 "with reality: %s, mode=%d.",
2130 connection->getInputChannelName(), mTempCancelationEvents.size(),
2131 options.reason, options.mode);
Jeff Brownb6997262010-10-08 22:31:17 -07002132#endif
2133 for (size_t i = 0; i < mTempCancelationEvents.size(); i++) {
2134 EventEntry* cancelationEventEntry = mTempCancelationEvents.itemAt(i);
2135 switch (cancelationEventEntry->type) {
2136 case EventEntry::TYPE_KEY:
2137 logOutboundKeyDetailsLocked("cancel - ",
2138 static_cast<KeyEntry*>(cancelationEventEntry));
2139 break;
2140 case EventEntry::TYPE_MOTION:
2141 logOutboundMotionDetailsLocked("cancel - ",
2142 static_cast<MotionEntry*>(cancelationEventEntry));
2143 break;
2144 }
2145
2146 int32_t xOffset, yOffset;
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002147 float scaleFactor;
Jeff Brownb6997262010-10-08 22:31:17 -07002148 const InputWindow* window = getWindowLocked(connection->inputChannel);
2149 if (window) {
2150 xOffset = -window->frameLeft;
2151 yOffset = -window->frameTop;
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002152 scaleFactor = window->scaleFactor;
Jeff Brownb6997262010-10-08 22:31:17 -07002153 } else {
2154 xOffset = 0;
2155 yOffset = 0;
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002156 scaleFactor = 1.0f;
Jeff Brownb6997262010-10-08 22:31:17 -07002157 }
2158
2159 DispatchEntry* cancelationDispatchEntry =
2160 mAllocator.obtainDispatchEntry(cancelationEventEntry, // increments ref
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002161 0, xOffset, yOffset, scaleFactor);
Jeff Brownb6997262010-10-08 22:31:17 -07002162 connection->outboundQueue.enqueueAtTail(cancelationDispatchEntry);
2163
2164 mAllocator.releaseEventEntry(cancelationEventEntry);
2165 }
2166
2167 if (!connection->outboundQueue.headSentinel.next->inProgress) {
2168 startDispatchCycleLocked(currentTime, connection);
2169 }
2170 }
2171}
2172
Jeff Brown01ce2e92010-09-26 22:20:12 -07002173InputDispatcher::MotionEntry*
2174InputDispatcher::splitMotionEvent(const MotionEntry* originalMotionEntry, BitSet32 pointerIds) {
2175 assert(pointerIds.value != 0);
2176
2177 uint32_t splitPointerIndexMap[MAX_POINTERS];
2178 int32_t splitPointerIds[MAX_POINTERS];
2179 PointerCoords splitPointerCoords[MAX_POINTERS];
2180
2181 uint32_t originalPointerCount = originalMotionEntry->pointerCount;
2182 uint32_t splitPointerCount = 0;
2183
2184 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
2185 originalPointerIndex++) {
2186 int32_t pointerId = uint32_t(originalMotionEntry->pointerIds[originalPointerIndex]);
2187 if (pointerIds.hasBit(pointerId)) {
2188 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
2189 splitPointerIds[splitPointerCount] = pointerId;
Jeff Brown96ad3972011-03-09 17:39:48 -08002190 splitPointerCoords[splitPointerCount].copyFrom(
2191 originalMotionEntry->firstSample.pointerCoords[originalPointerIndex]);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002192 splitPointerCount += 1;
2193 }
2194 }
Jeff Brown58a2da82011-01-25 16:02:22 -08002195
2196 if (splitPointerCount != pointerIds.count()) {
2197 // This is bad. We are missing some of the pointers that we expected to deliver.
2198 // Most likely this indicates that we received an ACTION_MOVE events that has
2199 // different pointer ids than we expected based on the previous ACTION_DOWN
2200 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
2201 // in this way.
2202 LOGW("Dropping split motion event because the pointer count is %d but "
2203 "we expected there to be %d pointers. This probably means we received "
2204 "a broken sequence of pointer ids from the input device.",
2205 splitPointerCount, pointerIds.count());
2206 return NULL;
2207 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07002208
2209 int32_t action = originalMotionEntry->action;
2210 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
2211 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
2212 || maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2213 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
2214 int32_t pointerId = originalMotionEntry->pointerIds[originalPointerIndex];
2215 if (pointerIds.hasBit(pointerId)) {
2216 if (pointerIds.count() == 1) {
2217 // The first/last pointer went down/up.
2218 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
2219 ? AMOTION_EVENT_ACTION_DOWN : AMOTION_EVENT_ACTION_UP;
Jeff Brown9a01d052010-09-27 16:35:11 -07002220 } else {
2221 // A secondary pointer went down/up.
2222 uint32_t splitPointerIndex = 0;
2223 while (pointerId != splitPointerIds[splitPointerIndex]) {
2224 splitPointerIndex += 1;
2225 }
2226 action = maskedAction | (splitPointerIndex
2227 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002228 }
2229 } else {
2230 // An unrelated pointer changed.
2231 action = AMOTION_EVENT_ACTION_MOVE;
2232 }
2233 }
2234
2235 MotionEntry* splitMotionEntry = mAllocator.obtainMotionEntry(
2236 originalMotionEntry->eventTime,
2237 originalMotionEntry->deviceId,
2238 originalMotionEntry->source,
2239 originalMotionEntry->policyFlags,
2240 action,
2241 originalMotionEntry->flags,
2242 originalMotionEntry->metaState,
2243 originalMotionEntry->edgeFlags,
2244 originalMotionEntry->xPrecision,
2245 originalMotionEntry->yPrecision,
2246 originalMotionEntry->downTime,
2247 splitPointerCount, splitPointerIds, splitPointerCoords);
2248
2249 for (MotionSample* originalMotionSample = originalMotionEntry->firstSample.next;
2250 originalMotionSample != NULL; originalMotionSample = originalMotionSample->next) {
2251 for (uint32_t splitPointerIndex = 0; splitPointerIndex < splitPointerCount;
2252 splitPointerIndex++) {
2253 uint32_t originalPointerIndex = splitPointerIndexMap[splitPointerIndex];
Jeff Brown96ad3972011-03-09 17:39:48 -08002254 splitPointerCoords[splitPointerIndex].copyFrom(
2255 originalMotionSample->pointerCoords[originalPointerIndex]);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002256 }
2257
2258 mAllocator.appendMotionSample(splitMotionEntry, originalMotionSample->eventTime,
2259 splitPointerCoords);
2260 }
2261
2262 return splitMotionEntry;
2263}
2264
Jeff Brown9c3cda02010-06-15 01:31:58 -07002265void InputDispatcher::notifyConfigurationChanged(nsecs_t eventTime) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002266#if DEBUG_INBOUND_EVENT_DETAILS
Jeff Brown9c3cda02010-06-15 01:31:58 -07002267 LOGD("notifyConfigurationChanged - eventTime=%lld", eventTime);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002268#endif
2269
Jeff Brownb88102f2010-09-08 11:49:43 -07002270 bool needWake;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002271 { // acquire lock
2272 AutoMutex _l(mLock);
2273
Jeff Brown7fbdc842010-06-17 20:52:56 -07002274 ConfigurationChangedEntry* newEntry = mAllocator.obtainConfigurationChangedEntry(eventTime);
Jeff Brownb88102f2010-09-08 11:49:43 -07002275 needWake = enqueueInboundEventLocked(newEntry);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002276 } // release lock
2277
Jeff Brownb88102f2010-09-08 11:49:43 -07002278 if (needWake) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002279 mLooper->wake();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002280 }
2281}
2282
Jeff Brown58a2da82011-01-25 16:02:22 -08002283void InputDispatcher::notifyKey(nsecs_t eventTime, int32_t deviceId, uint32_t source,
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002284 uint32_t policyFlags, int32_t action, int32_t flags,
2285 int32_t keyCode, int32_t scanCode, int32_t metaState, nsecs_t downTime) {
2286#if DEBUG_INBOUND_EVENT_DETAILS
Jeff Brown90655042010-12-02 13:50:46 -08002287 LOGD("notifyKey - eventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, action=0x%x, "
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002288 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%lld",
Jeff Brownc5ed5912010-07-14 18:48:53 -07002289 eventTime, deviceId, source, policyFlags, action, flags,
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002290 keyCode, scanCode, metaState, downTime);
2291#endif
Jeff Brown01ce2e92010-09-26 22:20:12 -07002292 if (! validateKeyEvent(action)) {
2293 return;
2294 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002295
Jeff Brown1f245102010-11-18 20:53:46 -08002296 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
2297 policyFlags |= POLICY_FLAG_VIRTUAL;
2298 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
2299 }
Jeff Brown924c4d42011-03-07 16:40:47 -08002300 if (policyFlags & POLICY_FLAG_ALT) {
2301 metaState |= AMETA_ALT_ON | AMETA_ALT_LEFT_ON;
2302 }
2303 if (policyFlags & POLICY_FLAG_ALT_GR) {
2304 metaState |= AMETA_ALT_ON | AMETA_ALT_RIGHT_ON;
2305 }
2306 if (policyFlags & POLICY_FLAG_SHIFT) {
2307 metaState |= AMETA_SHIFT_ON | AMETA_SHIFT_LEFT_ON;
2308 }
2309 if (policyFlags & POLICY_FLAG_CAPS_LOCK) {
2310 metaState |= AMETA_CAPS_LOCK_ON;
2311 }
2312 if (policyFlags & POLICY_FLAG_FUNCTION) {
2313 metaState |= AMETA_FUNCTION_ON;
2314 }
Jeff Brown1f245102010-11-18 20:53:46 -08002315
Jeff Browne20c9e02010-10-11 14:20:19 -07002316 policyFlags |= POLICY_FLAG_TRUSTED;
Jeff Brown1f245102010-11-18 20:53:46 -08002317
2318 KeyEvent event;
2319 event.initialize(deviceId, source, action, flags, keyCode, scanCode,
2320 metaState, 0, downTime, eventTime);
2321
2322 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
2323
2324 if (policyFlags & POLICY_FLAG_WOKE_HERE) {
2325 flags |= AKEY_EVENT_FLAG_WOKE_HERE;
2326 }
Jeff Brownb6997262010-10-08 22:31:17 -07002327
Jeff Brownb88102f2010-09-08 11:49:43 -07002328 bool needWake;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002329 { // acquire lock
2330 AutoMutex _l(mLock);
2331
Jeff Brown7fbdc842010-06-17 20:52:56 -07002332 int32_t repeatCount = 0;
2333 KeyEntry* newEntry = mAllocator.obtainKeyEntry(eventTime,
Jeff Brownc5ed5912010-07-14 18:48:53 -07002334 deviceId, source, policyFlags, action, flags, keyCode, scanCode,
Jeff Brown7fbdc842010-06-17 20:52:56 -07002335 metaState, repeatCount, downTime);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002336
Jeff Brownb88102f2010-09-08 11:49:43 -07002337 needWake = enqueueInboundEventLocked(newEntry);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002338 } // release lock
2339
Jeff Brownb88102f2010-09-08 11:49:43 -07002340 if (needWake) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002341 mLooper->wake();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002342 }
2343}
2344
Jeff Brown58a2da82011-01-25 16:02:22 -08002345void InputDispatcher::notifyMotion(nsecs_t eventTime, int32_t deviceId, uint32_t source,
Jeff Brown85a31762010-09-01 17:01:00 -07002346 uint32_t policyFlags, int32_t action, int32_t flags, int32_t metaState, int32_t edgeFlags,
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002347 uint32_t pointerCount, const int32_t* pointerIds, const PointerCoords* pointerCoords,
2348 float xPrecision, float yPrecision, nsecs_t downTime) {
2349#if DEBUG_INBOUND_EVENT_DETAILS
Jeff Brown90655042010-12-02 13:50:46 -08002350 LOGD("notifyMotion - eventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, "
Jeff Brown85a31762010-09-01 17:01:00 -07002351 "action=0x%x, flags=0x%x, metaState=0x%x, edgeFlags=0x%x, "
2352 "xPrecision=%f, yPrecision=%f, downTime=%lld",
2353 eventTime, deviceId, source, policyFlags, action, flags, metaState, edgeFlags,
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002354 xPrecision, yPrecision, downTime);
2355 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brown8d608662010-08-30 03:02:23 -07002356 LOGD(" Pointer %d: id=%d, x=%f, y=%f, pressure=%f, size=%f, "
Jeff Brown85a31762010-09-01 17:01:00 -07002357 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
Jeff Brown8d608662010-08-30 03:02:23 -07002358 "orientation=%f",
Jeff Brown91c69ab2011-02-14 17:03:18 -08002359 i, pointerIds[i],
Jeff Brownebbd5d12011-02-17 13:01:34 -08002360 pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
2361 pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
2362 pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
2363 pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
2364 pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
2365 pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
2366 pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
2367 pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
2368 pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002369 }
2370#endif
Jeff Brown01ce2e92010-09-26 22:20:12 -07002371 if (! validateMotionEvent(action, pointerCount, pointerIds)) {
2372 return;
2373 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002374
Jeff Browne20c9e02010-10-11 14:20:19 -07002375 policyFlags |= POLICY_FLAG_TRUSTED;
Jeff Brown56194eb2011-03-02 19:23:13 -08002376 mPolicy->interceptMotionBeforeQueueing(eventTime, /*byref*/ policyFlags);
Jeff Brownb6997262010-10-08 22:31:17 -07002377
Jeff Brownb88102f2010-09-08 11:49:43 -07002378 bool needWake;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002379 { // acquire lock
2380 AutoMutex _l(mLock);
2381
2382 // Attempt batching and streaming of move events.
Jeff Browncc0c1592011-02-19 05:07:28 -08002383 if (action == AMOTION_EVENT_ACTION_MOVE
2384 || action == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002385 // BATCHING CASE
2386 //
2387 // Try to append a move sample to the tail of the inbound queue for this device.
2388 // Give up if we encounter a non-move motion event for this device since that
2389 // means we cannot append any new samples until a new motion event has started.
Jeff Brownb88102f2010-09-08 11:49:43 -07002390 for (EventEntry* entry = mInboundQueue.tailSentinel.prev;
2391 entry != & mInboundQueue.headSentinel; entry = entry->prev) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002392 if (entry->type != EventEntry::TYPE_MOTION) {
2393 // Keep looking for motion events.
2394 continue;
2395 }
2396
2397 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
Jeff Brownefd32662011-03-08 15:13:06 -08002398 if (motionEntry->deviceId != deviceId
2399 || motionEntry->source != source) {
2400 // Keep looking for this device and source.
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002401 continue;
2402 }
2403
Jeff Brown5ced76a2011-05-24 11:23:27 -07002404 if (!motionEntry->canAppendSamples(action, pointerCount, pointerIds)) {
Jeff Brownefd32662011-03-08 15:13:06 -08002405 // Last motion event in the queue for this device and source is
2406 // not compatible for appending new samples. Stop here.
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002407 goto NoBatchingOrStreaming;
2408 }
2409
Jeff Brown9c3cda02010-06-15 01:31:58 -07002410 // Do the batching magic.
Jeff Brown5ced76a2011-05-24 11:23:27 -07002411 batchMotionLocked(motionEntry, eventTime, metaState, pointerCoords,
2412 "most recent motion event for this device and source in the inbound queue");
Jeff Brown9c3cda02010-06-15 01:31:58 -07002413 return; // done!
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002414 }
2415
Jeff Brown7157f6f2011-04-06 17:19:48 -07002416 // BATCHING ONTO PENDING EVENT CASE
2417 //
2418 // Try to append a move sample to the currently pending event, if there is one.
2419 // We can do this as long as we are still waiting to find the targets for the
2420 // event. Once the targets are locked-in we can only do streaming.
2421 if (mPendingEvent
2422 && (!mPendingEvent->dispatchInProgress || !mCurrentInputTargetsValid)
2423 && mPendingEvent->type == EventEntry::TYPE_MOTION) {
2424 MotionEntry* motionEntry = static_cast<MotionEntry*>(mPendingEvent);
2425 if (motionEntry->deviceId == deviceId && motionEntry->source == source) {
Jeff Brown5ced76a2011-05-24 11:23:27 -07002426 if (!motionEntry->canAppendSamples(action, pointerCount, pointerIds)) {
2427 // Pending motion event is for this device and source but it is
2428 // not compatible for appending new samples. Stop here.
Jeff Brown7157f6f2011-04-06 17:19:48 -07002429 goto NoBatchingOrStreaming;
2430 }
2431
Jeff Brown7157f6f2011-04-06 17:19:48 -07002432 // Do the batching magic.
Jeff Brown5ced76a2011-05-24 11:23:27 -07002433 batchMotionLocked(motionEntry, eventTime, metaState, pointerCoords,
2434 "pending motion event");
Jeff Brown7157f6f2011-04-06 17:19:48 -07002435 mLock.unlock();
2436 return; // done!
2437 }
2438 }
2439
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002440 // STREAMING CASE
2441 //
2442 // There is no pending motion event (of any kind) for this device in the inbound queue.
Jeff Brown519e0242010-09-15 15:18:56 -07002443 // Search the outbound queue for the current foreground targets to find a dispatched
2444 // motion event that is still in progress. If found, then, appen the new sample to
2445 // that event and push it out to all current targets. The logic in
2446 // prepareDispatchCycleLocked takes care of the case where some targets may
2447 // already have consumed the motion event by starting a new dispatch cycle if needed.
Jeff Brown9c3cda02010-06-15 01:31:58 -07002448 if (mCurrentInputTargetsValid) {
Jeff Brown519e0242010-09-15 15:18:56 -07002449 for (size_t i = 0; i < mCurrentInputTargets.size(); i++) {
2450 const InputTarget& inputTarget = mCurrentInputTargets[i];
2451 if ((inputTarget.flags & InputTarget::FLAG_FOREGROUND) == 0) {
2452 // Skip non-foreground targets. We only want to stream if there is at
2453 // least one foreground target whose dispatch is still in progress.
2454 continue;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002455 }
Jeff Brown519e0242010-09-15 15:18:56 -07002456
2457 ssize_t connectionIndex = getConnectionIndexLocked(inputTarget.inputChannel);
2458 if (connectionIndex < 0) {
2459 // Connection must no longer be valid.
2460 continue;
2461 }
2462
2463 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
2464 if (connection->outboundQueue.isEmpty()) {
2465 // This foreground target has an empty outbound queue.
2466 continue;
2467 }
2468
2469 DispatchEntry* dispatchEntry = connection->outboundQueue.headSentinel.next;
2470 if (! dispatchEntry->inProgress
Jeff Brown01ce2e92010-09-26 22:20:12 -07002471 || dispatchEntry->eventEntry->type != EventEntry::TYPE_MOTION
2472 || dispatchEntry->isSplit()) {
2473 // No motion event is being dispatched, or it is being split across
2474 // windows in which case we cannot stream.
Jeff Brown519e0242010-09-15 15:18:56 -07002475 continue;
2476 }
2477
2478 MotionEntry* motionEntry = static_cast<MotionEntry*>(
2479 dispatchEntry->eventEntry);
Jeff Browncc0c1592011-02-19 05:07:28 -08002480 if (motionEntry->action != action
Jeff Brown519e0242010-09-15 15:18:56 -07002481 || motionEntry->deviceId != deviceId
Jeff Brown58a2da82011-01-25 16:02:22 -08002482 || motionEntry->source != source
Jeff Brown519e0242010-09-15 15:18:56 -07002483 || motionEntry->pointerCount != pointerCount
2484 || motionEntry->isInjected()) {
2485 // The motion event is not compatible with this move.
2486 continue;
2487 }
2488
2489 // Hurray! This foreground target is currently dispatching a move event
2490 // that we can stream onto. Append the motion sample and resume dispatch.
2491 mAllocator.appendMotionSample(motionEntry, eventTime, pointerCoords);
2492#if DEBUG_BATCHING
2493 LOGD("Appended motion sample onto batch for most recently dispatched "
Jeff Brown5ced76a2011-05-24 11:23:27 -07002494 "motion event for this device and source in the outbound queues. "
Jeff Brown519e0242010-09-15 15:18:56 -07002495 "Attempting to stream the motion sample.");
2496#endif
2497 nsecs_t currentTime = now();
2498 dispatchEventToCurrentInputTargetsLocked(currentTime, motionEntry,
2499 true /*resumeWithAppendedMotionSample*/);
2500
2501 runCommandsLockedInterruptible();
2502 return; // done!
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002503 }
2504 }
2505
2506NoBatchingOrStreaming:;
2507 }
2508
2509 // Just enqueue a new motion event.
Jeff Brown7fbdc842010-06-17 20:52:56 -07002510 MotionEntry* newEntry = mAllocator.obtainMotionEntry(eventTime,
Jeff Brown85a31762010-09-01 17:01:00 -07002511 deviceId, source, policyFlags, action, flags, metaState, edgeFlags,
Jeff Brown7fbdc842010-06-17 20:52:56 -07002512 xPrecision, yPrecision, downTime,
2513 pointerCount, pointerIds, pointerCoords);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002514
Jeff Brownb88102f2010-09-08 11:49:43 -07002515 needWake = enqueueInboundEventLocked(newEntry);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002516 } // release lock
2517
Jeff Brownb88102f2010-09-08 11:49:43 -07002518 if (needWake) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002519 mLooper->wake();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002520 }
2521}
2522
Jeff Brown5ced76a2011-05-24 11:23:27 -07002523void InputDispatcher::batchMotionLocked(MotionEntry* entry, nsecs_t eventTime,
2524 int32_t metaState, const PointerCoords* pointerCoords, const char* eventDescription) {
2525 // Combine meta states.
2526 entry->metaState |= metaState;
2527
2528 // Coalesce this sample if not enough time has elapsed since the last sample was
2529 // initially appended to the batch.
2530 MotionSample* lastSample = entry->lastSample;
2531 long interval = eventTime - lastSample->eventTimeBeforeCoalescing;
2532 if (interval <= MOTION_SAMPLE_COALESCE_INTERVAL) {
2533 uint32_t pointerCount = entry->pointerCount;
2534 for (uint32_t i = 0; i < pointerCount; i++) {
2535 lastSample->pointerCoords[i].copyFrom(pointerCoords[i]);
2536 }
2537 lastSample->eventTime = eventTime;
2538#if DEBUG_BATCHING
2539 LOGD("Coalesced motion into last sample of batch for %s, events were %0.3f ms apart",
2540 eventDescription, interval * 0.000001f);
2541#endif
2542 return;
2543 }
2544
2545 // Append the sample.
2546 mAllocator.appendMotionSample(entry, eventTime, pointerCoords);
2547#if DEBUG_BATCHING
2548 LOGD("Appended motion sample onto batch for %s, events were %0.3f ms apart",
2549 eventDescription, interval * 0.000001f);
2550#endif
2551}
2552
Jeff Brownb6997262010-10-08 22:31:17 -07002553void InputDispatcher::notifySwitch(nsecs_t when, int32_t switchCode, int32_t switchValue,
2554 uint32_t policyFlags) {
2555#if DEBUG_INBOUND_EVENT_DETAILS
2556 LOGD("notifySwitch - switchCode=%d, switchValue=%d, policyFlags=0x%x",
2557 switchCode, switchValue, policyFlags);
2558#endif
2559
Jeff Browne20c9e02010-10-11 14:20:19 -07002560 policyFlags |= POLICY_FLAG_TRUSTED;
Jeff Brownb6997262010-10-08 22:31:17 -07002561 mPolicy->notifySwitch(when, switchCode, switchValue, policyFlags);
2562}
2563
Jeff Brown7fbdc842010-06-17 20:52:56 -07002564int32_t InputDispatcher::injectInputEvent(const InputEvent* event,
Jeff Brown6ec402b2010-07-28 15:48:59 -07002565 int32_t injectorPid, int32_t injectorUid, int32_t syncMode, int32_t timeoutMillis) {
Jeff Brown7fbdc842010-06-17 20:52:56 -07002566#if DEBUG_INBOUND_EVENT_DETAILS
2567 LOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Jeff Brown6ec402b2010-07-28 15:48:59 -07002568 "syncMode=%d, timeoutMillis=%d",
2569 event->getType(), injectorPid, injectorUid, syncMode, timeoutMillis);
Jeff Brown7fbdc842010-06-17 20:52:56 -07002570#endif
2571
2572 nsecs_t endTime = now() + milliseconds_to_nanoseconds(timeoutMillis);
Jeff Browne20c9e02010-10-11 14:20:19 -07002573
2574 uint32_t policyFlags = POLICY_FLAG_INJECTED;
2575 if (hasInjectionPermission(injectorPid, injectorUid)) {
2576 policyFlags |= POLICY_FLAG_TRUSTED;
2577 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07002578
Jeff Brownb6997262010-10-08 22:31:17 -07002579 EventEntry* injectedEntry;
2580 switch (event->getType()) {
2581 case AINPUT_EVENT_TYPE_KEY: {
2582 const KeyEvent* keyEvent = static_cast<const KeyEvent*>(event);
2583 int32_t action = keyEvent->getAction();
2584 if (! validateKeyEvent(action)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07002585 return INPUT_EVENT_INJECTION_FAILED;
2586 }
2587
Jeff Brownb6997262010-10-08 22:31:17 -07002588 int32_t flags = keyEvent->getFlags();
Jeff Brown1f245102010-11-18 20:53:46 -08002589 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
2590 policyFlags |= POLICY_FLAG_VIRTUAL;
2591 }
2592
2593 mPolicy->interceptKeyBeforeQueueing(keyEvent, /*byref*/ policyFlags);
2594
2595 if (policyFlags & POLICY_FLAG_WOKE_HERE) {
2596 flags |= AKEY_EVENT_FLAG_WOKE_HERE;
2597 }
Jeff Brown6ec402b2010-07-28 15:48:59 -07002598
Jeff Brownb6997262010-10-08 22:31:17 -07002599 mLock.lock();
Jeff Brown1f245102010-11-18 20:53:46 -08002600 injectedEntry = mAllocator.obtainKeyEntry(keyEvent->getEventTime(),
2601 keyEvent->getDeviceId(), keyEvent->getSource(),
2602 policyFlags, action, flags,
2603 keyEvent->getKeyCode(), keyEvent->getScanCode(), keyEvent->getMetaState(),
Jeff Brownb6997262010-10-08 22:31:17 -07002604 keyEvent->getRepeatCount(), keyEvent->getDownTime());
2605 break;
2606 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07002607
Jeff Brownb6997262010-10-08 22:31:17 -07002608 case AINPUT_EVENT_TYPE_MOTION: {
2609 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
2610 int32_t action = motionEvent->getAction();
2611 size_t pointerCount = motionEvent->getPointerCount();
2612 const int32_t* pointerIds = motionEvent->getPointerIds();
2613 if (! validateMotionEvent(action, pointerCount, pointerIds)) {
2614 return INPUT_EVENT_INJECTION_FAILED;
2615 }
2616
2617 nsecs_t eventTime = motionEvent->getEventTime();
Jeff Brown56194eb2011-03-02 19:23:13 -08002618 mPolicy->interceptMotionBeforeQueueing(eventTime, /*byref*/ policyFlags);
Jeff Brownb6997262010-10-08 22:31:17 -07002619
2620 mLock.lock();
2621 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
2622 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
2623 MotionEntry* motionEntry = mAllocator.obtainMotionEntry(*sampleEventTimes,
2624 motionEvent->getDeviceId(), motionEvent->getSource(), policyFlags,
2625 action, motionEvent->getFlags(),
2626 motionEvent->getMetaState(), motionEvent->getEdgeFlags(),
2627 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
2628 motionEvent->getDownTime(), uint32_t(pointerCount),
2629 pointerIds, samplePointerCoords);
2630 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
2631 sampleEventTimes += 1;
2632 samplePointerCoords += pointerCount;
2633 mAllocator.appendMotionSample(motionEntry, *sampleEventTimes, samplePointerCoords);
2634 }
2635 injectedEntry = motionEntry;
2636 break;
2637 }
2638
2639 default:
2640 LOGW("Cannot inject event of type %d", event->getType());
2641 return INPUT_EVENT_INJECTION_FAILED;
2642 }
2643
2644 InjectionState* injectionState = mAllocator.obtainInjectionState(injectorPid, injectorUid);
2645 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
2646 injectionState->injectionIsAsync = true;
2647 }
2648
2649 injectionState->refCount += 1;
2650 injectedEntry->injectionState = injectionState;
2651
2652 bool needWake = enqueueInboundEventLocked(injectedEntry);
2653 mLock.unlock();
Jeff Brown7fbdc842010-06-17 20:52:56 -07002654
Jeff Brownb88102f2010-09-08 11:49:43 -07002655 if (needWake) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002656 mLooper->wake();
Jeff Brown7fbdc842010-06-17 20:52:56 -07002657 }
2658
2659 int32_t injectionResult;
2660 { // acquire lock
2661 AutoMutex _l(mLock);
2662
Jeff Brown6ec402b2010-07-28 15:48:59 -07002663 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
2664 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
2665 } else {
2666 for (;;) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002667 injectionResult = injectionState->injectionResult;
Jeff Brown6ec402b2010-07-28 15:48:59 -07002668 if (injectionResult != INPUT_EVENT_INJECTION_PENDING) {
2669 break;
2670 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07002671
Jeff Brown7fbdc842010-06-17 20:52:56 -07002672 nsecs_t remainingTimeout = endTime - now();
2673 if (remainingTimeout <= 0) {
Jeff Brown6ec402b2010-07-28 15:48:59 -07002674#if DEBUG_INJECTION
2675 LOGD("injectInputEvent - Timed out waiting for injection result "
2676 "to become available.");
2677#endif
Jeff Brown7fbdc842010-06-17 20:52:56 -07002678 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
2679 break;
2680 }
2681
Jeff Brown6ec402b2010-07-28 15:48:59 -07002682 mInjectionResultAvailableCondition.waitRelative(mLock, remainingTimeout);
2683 }
2684
2685 if (injectionResult == INPUT_EVENT_INJECTION_SUCCEEDED
2686 && syncMode == INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002687 while (injectionState->pendingForegroundDispatches != 0) {
Jeff Brown6ec402b2010-07-28 15:48:59 -07002688#if DEBUG_INJECTION
Jeff Brown519e0242010-09-15 15:18:56 -07002689 LOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
Jeff Brown01ce2e92010-09-26 22:20:12 -07002690 injectionState->pendingForegroundDispatches);
Jeff Brown6ec402b2010-07-28 15:48:59 -07002691#endif
2692 nsecs_t remainingTimeout = endTime - now();
2693 if (remainingTimeout <= 0) {
2694#if DEBUG_INJECTION
Jeff Brown519e0242010-09-15 15:18:56 -07002695 LOGD("injectInputEvent - Timed out waiting for pending foreground "
Jeff Brown6ec402b2010-07-28 15:48:59 -07002696 "dispatches to finish.");
2697#endif
2698 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
2699 break;
2700 }
2701
2702 mInjectionSyncFinishedCondition.waitRelative(mLock, remainingTimeout);
2703 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07002704 }
2705 }
2706
Jeff Brown01ce2e92010-09-26 22:20:12 -07002707 mAllocator.releaseInjectionState(injectionState);
Jeff Brown7fbdc842010-06-17 20:52:56 -07002708 } // release lock
2709
Jeff Brown6ec402b2010-07-28 15:48:59 -07002710#if DEBUG_INJECTION
2711 LOGD("injectInputEvent - Finished with result %d. "
2712 "injectorPid=%d, injectorUid=%d",
2713 injectionResult, injectorPid, injectorUid);
2714#endif
2715
Jeff Brown7fbdc842010-06-17 20:52:56 -07002716 return injectionResult;
2717}
2718
Jeff Brownb6997262010-10-08 22:31:17 -07002719bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
2720 return injectorUid == 0
2721 || mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
2722}
2723
Jeff Brown7fbdc842010-06-17 20:52:56 -07002724void InputDispatcher::setInjectionResultLocked(EventEntry* entry, int32_t injectionResult) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002725 InjectionState* injectionState = entry->injectionState;
2726 if (injectionState) {
Jeff Brown7fbdc842010-06-17 20:52:56 -07002727#if DEBUG_INJECTION
2728 LOGD("Setting input event injection result to %d. "
2729 "injectorPid=%d, injectorUid=%d",
Jeff Brown01ce2e92010-09-26 22:20:12 -07002730 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
Jeff Brown7fbdc842010-06-17 20:52:56 -07002731#endif
2732
Jeff Brown01ce2e92010-09-26 22:20:12 -07002733 if (injectionState->injectionIsAsync) {
Jeff Brown6ec402b2010-07-28 15:48:59 -07002734 // Log the outcome since the injector did not wait for the injection result.
2735 switch (injectionResult) {
2736 case INPUT_EVENT_INJECTION_SUCCEEDED:
2737 LOGV("Asynchronous input event injection succeeded.");
2738 break;
2739 case INPUT_EVENT_INJECTION_FAILED:
2740 LOGW("Asynchronous input event injection failed.");
2741 break;
2742 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
2743 LOGW("Asynchronous input event injection permission denied.");
2744 break;
2745 case INPUT_EVENT_INJECTION_TIMED_OUT:
2746 LOGW("Asynchronous input event injection timed out.");
2747 break;
2748 }
2749 }
2750
Jeff Brown01ce2e92010-09-26 22:20:12 -07002751 injectionState->injectionResult = injectionResult;
Jeff Brown7fbdc842010-06-17 20:52:56 -07002752 mInjectionResultAvailableCondition.broadcast();
2753 }
2754}
2755
Jeff Brown01ce2e92010-09-26 22:20:12 -07002756void InputDispatcher::incrementPendingForegroundDispatchesLocked(EventEntry* entry) {
2757 InjectionState* injectionState = entry->injectionState;
2758 if (injectionState) {
2759 injectionState->pendingForegroundDispatches += 1;
2760 }
2761}
2762
Jeff Brown519e0242010-09-15 15:18:56 -07002763void InputDispatcher::decrementPendingForegroundDispatchesLocked(EventEntry* entry) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002764 InjectionState* injectionState = entry->injectionState;
2765 if (injectionState) {
2766 injectionState->pendingForegroundDispatches -= 1;
Jeff Brown6ec402b2010-07-28 15:48:59 -07002767
Jeff Brown01ce2e92010-09-26 22:20:12 -07002768 if (injectionState->pendingForegroundDispatches == 0) {
2769 mInjectionSyncFinishedCondition.broadcast();
2770 }
Jeff Brownb88102f2010-09-08 11:49:43 -07002771 }
2772}
2773
Jeff Brown01ce2e92010-09-26 22:20:12 -07002774const InputWindow* InputDispatcher::getWindowLocked(const sp<InputChannel>& inputChannel) {
2775 for (size_t i = 0; i < mWindows.size(); i++) {
2776 const InputWindow* window = & mWindows[i];
2777 if (window->inputChannel == inputChannel) {
2778 return window;
2779 }
2780 }
2781 return NULL;
2782}
2783
Jeff Brownb88102f2010-09-08 11:49:43 -07002784void InputDispatcher::setInputWindows(const Vector<InputWindow>& inputWindows) {
2785#if DEBUG_FOCUS
2786 LOGD("setInputWindows");
2787#endif
2788 { // acquire lock
2789 AutoMutex _l(mLock);
2790
Jeff Brown01ce2e92010-09-26 22:20:12 -07002791 // Clear old window pointers.
Jeff Brownb6997262010-10-08 22:31:17 -07002792 sp<InputChannel> oldFocusedWindowChannel;
2793 if (mFocusedWindow) {
2794 oldFocusedWindowChannel = mFocusedWindow->inputChannel;
2795 mFocusedWindow = NULL;
2796 }
2797
Jeff Brownb88102f2010-09-08 11:49:43 -07002798 mWindows.clear();
Jeff Brown2a95c2a2010-09-16 12:31:46 -07002799
2800 // Loop over new windows and rebuild the necessary window pointers for
2801 // tracking focus and touch.
Jeff Brownb88102f2010-09-08 11:49:43 -07002802 mWindows.appendVector(inputWindows);
2803
2804 size_t numWindows = mWindows.size();
2805 for (size_t i = 0; i < numWindows; i++) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002806 const InputWindow* window = & mWindows.itemAt(i);
Jeff Brownb88102f2010-09-08 11:49:43 -07002807 if (window->hasFocus) {
2808 mFocusedWindow = window;
Jeff Brown01ce2e92010-09-26 22:20:12 -07002809 break;
Jeff Brownb88102f2010-09-08 11:49:43 -07002810 }
2811 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07002812
Jeff Brownb6997262010-10-08 22:31:17 -07002813 if (oldFocusedWindowChannel != NULL) {
2814 if (!mFocusedWindow || oldFocusedWindowChannel != mFocusedWindow->inputChannel) {
2815#if DEBUG_FOCUS
2816 LOGD("Focus left window: %s",
2817 oldFocusedWindowChannel->getName().string());
2818#endif
Jeff Brown524ee642011-03-29 15:11:34 -07002819 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
2820 "focus left window");
2821 synthesizeCancelationEventsForInputChannelLocked(oldFocusedWindowChannel, options);
Jeff Brownb6997262010-10-08 22:31:17 -07002822 oldFocusedWindowChannel.clear();
2823 }
2824 }
2825 if (mFocusedWindow && oldFocusedWindowChannel == NULL) {
2826#if DEBUG_FOCUS
2827 LOGD("Focus entered window: %s",
2828 mFocusedWindow->inputChannel->getName().string());
2829#endif
2830 }
2831
Jeff Brown01ce2e92010-09-26 22:20:12 -07002832 for (size_t i = 0; i < mTouchState.windows.size(); ) {
2833 TouchedWindow& touchedWindow = mTouchState.windows.editItemAt(i);
2834 const InputWindow* window = getWindowLocked(touchedWindow.channel);
2835 if (window) {
2836 touchedWindow.window = window;
2837 i += 1;
2838 } else {
Jeff Brownb6997262010-10-08 22:31:17 -07002839#if DEBUG_FOCUS
2840 LOGD("Touched window was removed: %s", touchedWindow.channel->getName().string());
2841#endif
Jeff Brown524ee642011-03-29 15:11:34 -07002842 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
2843 "touched window was removed");
2844 synthesizeCancelationEventsForInputChannelLocked(touchedWindow.channel, options);
Jeff Brownaf48cae2010-10-15 16:20:51 -07002845 mTouchState.windows.removeAt(i);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002846 }
2847 }
Jeff Brownb88102f2010-09-08 11:49:43 -07002848
Jeff Brownb88102f2010-09-08 11:49:43 -07002849#if DEBUG_FOCUS
Jeff Brownb6997262010-10-08 22:31:17 -07002850 //logDispatchStateLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -07002851#endif
2852 } // release lock
2853
2854 // Wake up poll loop since it may need to make new input dispatching choices.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002855 mLooper->wake();
Jeff Brownb88102f2010-09-08 11:49:43 -07002856}
2857
2858void InputDispatcher::setFocusedApplication(const InputApplication* inputApplication) {
2859#if DEBUG_FOCUS
2860 LOGD("setFocusedApplication");
2861#endif
2862 { // acquire lock
2863 AutoMutex _l(mLock);
2864
2865 releaseFocusedApplicationLocked();
2866
2867 if (inputApplication) {
2868 mFocusedApplicationStorage = *inputApplication;
2869 mFocusedApplication = & mFocusedApplicationStorage;
2870 }
2871
2872#if DEBUG_FOCUS
Jeff Brownb6997262010-10-08 22:31:17 -07002873 //logDispatchStateLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -07002874#endif
2875 } // release lock
2876
2877 // Wake up poll loop since it may need to make new input dispatching choices.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002878 mLooper->wake();
Jeff Brownb88102f2010-09-08 11:49:43 -07002879}
2880
2881void InputDispatcher::releaseFocusedApplicationLocked() {
2882 if (mFocusedApplication) {
2883 mFocusedApplication = NULL;
Jeff Brown928e0542011-01-10 11:17:36 -08002884 mFocusedApplicationStorage.inputApplicationHandle.clear();
Jeff Brownb88102f2010-09-08 11:49:43 -07002885 }
2886}
2887
2888void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
2889#if DEBUG_FOCUS
2890 LOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
2891#endif
2892
2893 bool changed;
2894 { // acquire lock
2895 AutoMutex _l(mLock);
2896
2897 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
Jeff Brown120a4592010-10-27 18:43:51 -07002898 if (mDispatchFrozen && !frozen) {
Jeff Brownb88102f2010-09-08 11:49:43 -07002899 resetANRTimeoutsLocked();
2900 }
2901
Jeff Brown120a4592010-10-27 18:43:51 -07002902 if (mDispatchEnabled && !enabled) {
2903 resetAndDropEverythingLocked("dispatcher is being disabled");
2904 }
2905
Jeff Brownb88102f2010-09-08 11:49:43 -07002906 mDispatchEnabled = enabled;
2907 mDispatchFrozen = frozen;
2908 changed = true;
2909 } else {
2910 changed = false;
2911 }
2912
2913#if DEBUG_FOCUS
Jeff Brownb6997262010-10-08 22:31:17 -07002914 //logDispatchStateLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -07002915#endif
2916 } // release lock
2917
2918 if (changed) {
2919 // Wake up poll loop since it may need to make new input dispatching choices.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002920 mLooper->wake();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002921 }
2922}
2923
Jeff Browne6504122010-09-27 14:52:15 -07002924bool InputDispatcher::transferTouchFocus(const sp<InputChannel>& fromChannel,
2925 const sp<InputChannel>& toChannel) {
2926#if DEBUG_FOCUS
2927 LOGD("transferTouchFocus: fromChannel=%s, toChannel=%s",
2928 fromChannel->getName().string(), toChannel->getName().string());
2929#endif
2930 { // acquire lock
2931 AutoMutex _l(mLock);
2932
2933 const InputWindow* fromWindow = getWindowLocked(fromChannel);
2934 const InputWindow* toWindow = getWindowLocked(toChannel);
2935 if (! fromWindow || ! toWindow) {
2936#if DEBUG_FOCUS
2937 LOGD("Cannot transfer focus because from or to window not found.");
2938#endif
2939 return false;
2940 }
2941 if (fromWindow == toWindow) {
2942#if DEBUG_FOCUS
2943 LOGD("Trivial transfer to same window.");
2944#endif
2945 return true;
2946 }
2947
2948 bool found = false;
2949 for (size_t i = 0; i < mTouchState.windows.size(); i++) {
2950 const TouchedWindow& touchedWindow = mTouchState.windows[i];
2951 if (touchedWindow.window == fromWindow) {
2952 int32_t oldTargetFlags = touchedWindow.targetFlags;
2953 BitSet32 pointerIds = touchedWindow.pointerIds;
2954
2955 mTouchState.windows.removeAt(i);
2956
Jeff Brown46e75292010-11-10 16:53:45 -08002957 int32_t newTargetFlags = oldTargetFlags
2958 & (InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_SPLIT);
Jeff Browne6504122010-09-27 14:52:15 -07002959 mTouchState.addOrUpdateWindow(toWindow, newTargetFlags, pointerIds);
2960
2961 found = true;
2962 break;
2963 }
2964 }
2965
2966 if (! found) {
2967#if DEBUG_FOCUS
2968 LOGD("Focus transfer failed because from window did not have focus.");
2969#endif
2970 return false;
2971 }
2972
Jeff Brown9c9f1a32010-10-11 18:32:20 -07002973 ssize_t fromConnectionIndex = getConnectionIndexLocked(fromChannel);
2974 ssize_t toConnectionIndex = getConnectionIndexLocked(toChannel);
2975 if (fromConnectionIndex >= 0 && toConnectionIndex >= 0) {
2976 sp<Connection> fromConnection = mConnectionsByReceiveFd.valueAt(fromConnectionIndex);
2977 sp<Connection> toConnection = mConnectionsByReceiveFd.valueAt(toConnectionIndex);
2978
2979 fromConnection->inputState.copyPointerStateTo(toConnection->inputState);
Jeff Brown524ee642011-03-29 15:11:34 -07002980 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Jeff Brown9c9f1a32010-10-11 18:32:20 -07002981 "transferring touch focus from this window to another window");
Jeff Brown524ee642011-03-29 15:11:34 -07002982 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Jeff Brown9c9f1a32010-10-11 18:32:20 -07002983 }
2984
Jeff Browne6504122010-09-27 14:52:15 -07002985#if DEBUG_FOCUS
2986 logDispatchStateLocked();
2987#endif
2988 } // release lock
2989
2990 // Wake up poll loop since it may need to make new input dispatching choices.
2991 mLooper->wake();
2992 return true;
2993}
2994
Jeff Brown120a4592010-10-27 18:43:51 -07002995void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
2996#if DEBUG_FOCUS
2997 LOGD("Resetting and dropping all events (%s).", reason);
2998#endif
2999
Jeff Brown524ee642011-03-29 15:11:34 -07003000 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
3001 synthesizeCancelationEventsForAllConnectionsLocked(options);
Jeff Brown120a4592010-10-27 18:43:51 -07003002
3003 resetKeyRepeatLocked();
3004 releasePendingEventLocked();
3005 drainInboundQueueLocked();
3006 resetTargetsLocked();
3007
3008 mTouchState.reset();
3009}
3010
Jeff Brownb88102f2010-09-08 11:49:43 -07003011void InputDispatcher::logDispatchStateLocked() {
3012 String8 dump;
3013 dumpDispatchStateLocked(dump);
Jeff Brown2a95c2a2010-09-16 12:31:46 -07003014
3015 char* text = dump.lockBuffer(dump.size());
3016 char* start = text;
3017 while (*start != '\0') {
3018 char* end = strchr(start, '\n');
3019 if (*end == '\n') {
3020 *(end++) = '\0';
3021 }
3022 LOGD("%s", start);
3023 start = end;
3024 }
Jeff Brownb88102f2010-09-08 11:49:43 -07003025}
3026
3027void InputDispatcher::dumpDispatchStateLocked(String8& dump) {
Jeff Brownf2f487182010-10-01 17:46:21 -07003028 dump.appendFormat(INDENT "DispatchEnabled: %d\n", mDispatchEnabled);
3029 dump.appendFormat(INDENT "DispatchFrozen: %d\n", mDispatchFrozen);
Jeff Brownb88102f2010-09-08 11:49:43 -07003030
3031 if (mFocusedApplication) {
Jeff Brownf2f487182010-10-01 17:46:21 -07003032 dump.appendFormat(INDENT "FocusedApplication: name='%s', dispatchingTimeout=%0.3fms\n",
Jeff Brownb88102f2010-09-08 11:49:43 -07003033 mFocusedApplication->name.string(),
3034 mFocusedApplication->dispatchingTimeout / 1000000.0);
3035 } else {
Jeff Brownf2f487182010-10-01 17:46:21 -07003036 dump.append(INDENT "FocusedApplication: <null>\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003037 }
Jeff Brownf2f487182010-10-01 17:46:21 -07003038 dump.appendFormat(INDENT "FocusedWindow: name='%s'\n",
Jeff Brown2a95c2a2010-09-16 12:31:46 -07003039 mFocusedWindow != NULL ? mFocusedWindow->name.string() : "<null>");
Jeff Brownf2f487182010-10-01 17:46:21 -07003040
3041 dump.appendFormat(INDENT "TouchDown: %s\n", toString(mTouchState.down));
3042 dump.appendFormat(INDENT "TouchSplit: %s\n", toString(mTouchState.split));
Jeff Brown95712852011-01-04 19:41:59 -08003043 dump.appendFormat(INDENT "TouchDeviceId: %d\n", mTouchState.deviceId);
Jeff Brown58a2da82011-01-25 16:02:22 -08003044 dump.appendFormat(INDENT "TouchSource: 0x%08x\n", mTouchState.source);
Jeff Brownf2f487182010-10-01 17:46:21 -07003045 if (!mTouchState.windows.isEmpty()) {
3046 dump.append(INDENT "TouchedWindows:\n");
3047 for (size_t i = 0; i < mTouchState.windows.size(); i++) {
3048 const TouchedWindow& touchedWindow = mTouchState.windows[i];
3049 dump.appendFormat(INDENT2 "%d: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
3050 i, touchedWindow.window->name.string(), touchedWindow.pointerIds.value,
3051 touchedWindow.targetFlags);
3052 }
3053 } else {
3054 dump.append(INDENT "TouchedWindows: <none>\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003055 }
3056
Jeff Brownf2f487182010-10-01 17:46:21 -07003057 if (!mWindows.isEmpty()) {
3058 dump.append(INDENT "Windows:\n");
3059 for (size_t i = 0; i < mWindows.size(); i++) {
3060 const InputWindow& window = mWindows[i];
3061 dump.appendFormat(INDENT2 "%d: name='%s', paused=%s, hasFocus=%s, hasWallpaper=%s, "
3062 "visible=%s, canReceiveKeys=%s, flags=0x%08x, type=0x%08x, layer=%d, "
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003063 "frame=[%d,%d][%d,%d], scale=%f, "
Jeff Brownfbf09772011-01-16 14:06:57 -08003064 "touchableRegion=",
Jeff Brownf2f487182010-10-01 17:46:21 -07003065 i, window.name.string(),
3066 toString(window.paused),
3067 toString(window.hasFocus),
3068 toString(window.hasWallpaper),
3069 toString(window.visible),
3070 toString(window.canReceiveKeys),
3071 window.layoutParamsFlags, window.layoutParamsType,
3072 window.layer,
3073 window.frameLeft, window.frameTop,
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003074 window.frameRight, window.frameBottom,
3075 window.scaleFactor);
Jeff Brownfbf09772011-01-16 14:06:57 -08003076 dumpRegion(dump, window.touchableRegion);
3077 dump.appendFormat(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%0.3fms\n",
Jeff Brownf2f487182010-10-01 17:46:21 -07003078 window.ownerPid, window.ownerUid,
3079 window.dispatchingTimeout / 1000000.0);
3080 }
3081 } else {
3082 dump.append(INDENT "Windows: <none>\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003083 }
3084
Jeff Brownf2f487182010-10-01 17:46:21 -07003085 if (!mMonitoringChannels.isEmpty()) {
3086 dump.append(INDENT "MonitoringChannels:\n");
3087 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
3088 const sp<InputChannel>& channel = mMonitoringChannels[i];
3089 dump.appendFormat(INDENT2 "%d: '%s'\n", i, channel->getName().string());
3090 }
3091 } else {
3092 dump.append(INDENT "MonitoringChannels: <none>\n");
3093 }
Jeff Brown519e0242010-09-15 15:18:56 -07003094
Jeff Brownf2f487182010-10-01 17:46:21 -07003095 dump.appendFormat(INDENT "InboundQueue: length=%u\n", mInboundQueue.count());
3096
3097 if (!mActiveConnections.isEmpty()) {
3098 dump.append(INDENT "ActiveConnections:\n");
3099 for (size_t i = 0; i < mActiveConnections.size(); i++) {
3100 const Connection* connection = mActiveConnections[i];
Jeff Brown76860e32010-10-25 17:37:46 -07003101 dump.appendFormat(INDENT2 "%d: '%s', status=%s, outboundQueueLength=%u, "
Jeff Brownb6997262010-10-08 22:31:17 -07003102 "inputState.isNeutral=%s\n",
Jeff Brownf2f487182010-10-01 17:46:21 -07003103 i, connection->getInputChannelName(), connection->getStatusLabel(),
3104 connection->outboundQueue.count(),
Jeff Brownb6997262010-10-08 22:31:17 -07003105 toString(connection->inputState.isNeutral()));
Jeff Brownf2f487182010-10-01 17:46:21 -07003106 }
3107 } else {
3108 dump.append(INDENT "ActiveConnections: <none>\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003109 }
3110
3111 if (isAppSwitchPendingLocked()) {
Jeff Brownf2f487182010-10-01 17:46:21 -07003112 dump.appendFormat(INDENT "AppSwitch: pending, due in %01.1fms\n",
Jeff Brownb88102f2010-09-08 11:49:43 -07003113 (mAppSwitchDueTime - now()) / 1000000.0);
3114 } else {
Jeff Brownf2f487182010-10-01 17:46:21 -07003115 dump.append(INDENT "AppSwitch: not pending\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003116 }
3117}
3118
Jeff Brown928e0542011-01-10 11:17:36 -08003119status_t InputDispatcher::registerInputChannel(const sp<InputChannel>& inputChannel,
3120 const sp<InputWindowHandle>& inputWindowHandle, bool monitor) {
Jeff Brown9c3cda02010-06-15 01:31:58 -07003121#if DEBUG_REGISTRATION
Jeff Brownb88102f2010-09-08 11:49:43 -07003122 LOGD("channel '%s' ~ registerInputChannel - monitor=%s", inputChannel->getName().string(),
3123 toString(monitor));
Jeff Brown9c3cda02010-06-15 01:31:58 -07003124#endif
3125
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003126 { // acquire lock
3127 AutoMutex _l(mLock);
3128
Jeff Brown519e0242010-09-15 15:18:56 -07003129 if (getConnectionIndexLocked(inputChannel) >= 0) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003130 LOGW("Attempted to register already registered input channel '%s'",
3131 inputChannel->getName().string());
3132 return BAD_VALUE;
3133 }
3134
Jeff Brown928e0542011-01-10 11:17:36 -08003135 sp<Connection> connection = new Connection(inputChannel, inputWindowHandle);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003136 status_t status = connection->initialize();
3137 if (status) {
3138 LOGE("Failed to initialize input publisher for input channel '%s', status=%d",
3139 inputChannel->getName().string(), status);
3140 return status;
3141 }
3142
Jeff Brown2cbecea2010-08-17 15:59:26 -07003143 int32_t receiveFd = inputChannel->getReceivePipeFd();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003144 mConnectionsByReceiveFd.add(receiveFd, connection);
Jeff Brown9c3cda02010-06-15 01:31:58 -07003145
Jeff Brownb88102f2010-09-08 11:49:43 -07003146 if (monitor) {
3147 mMonitoringChannels.push(inputChannel);
3148 }
3149
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07003150 mLooper->addFd(receiveFd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
Jeff Brown2cbecea2010-08-17 15:59:26 -07003151
Jeff Brown9c3cda02010-06-15 01:31:58 -07003152 runCommandsLockedInterruptible();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003153 } // release lock
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003154 return OK;
3155}
3156
3157status_t InputDispatcher::unregisterInputChannel(const sp<InputChannel>& inputChannel) {
Jeff Brown9c3cda02010-06-15 01:31:58 -07003158#if DEBUG_REGISTRATION
Jeff Brown349703e2010-06-22 01:27:15 -07003159 LOGD("channel '%s' ~ unregisterInputChannel", inputChannel->getName().string());
Jeff Brown9c3cda02010-06-15 01:31:58 -07003160#endif
3161
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003162 { // acquire lock
3163 AutoMutex _l(mLock);
3164
Jeff Brown519e0242010-09-15 15:18:56 -07003165 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003166 if (connectionIndex < 0) {
3167 LOGW("Attempted to unregister already unregistered input channel '%s'",
3168 inputChannel->getName().string());
3169 return BAD_VALUE;
3170 }
3171
3172 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
3173 mConnectionsByReceiveFd.removeItemsAt(connectionIndex);
3174
3175 connection->status = Connection::STATUS_ZOMBIE;
3176
Jeff Brownb88102f2010-09-08 11:49:43 -07003177 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
3178 if (mMonitoringChannels[i] == inputChannel) {
3179 mMonitoringChannels.removeAt(i);
3180 break;
3181 }
3182 }
3183
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07003184 mLooper->removeFd(inputChannel->getReceivePipeFd());
Jeff Brown2cbecea2010-08-17 15:59:26 -07003185
Jeff Brown7fbdc842010-06-17 20:52:56 -07003186 nsecs_t currentTime = now();
Jeff Brownb6997262010-10-08 22:31:17 -07003187 abortBrokenDispatchCycleLocked(currentTime, connection);
Jeff Brown9c3cda02010-06-15 01:31:58 -07003188
3189 runCommandsLockedInterruptible();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003190 } // release lock
3191
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003192 // Wake the poll loop because removing the connection may have changed the current
3193 // synchronization state.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07003194 mLooper->wake();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003195 return OK;
3196}
3197
Jeff Brown519e0242010-09-15 15:18:56 -07003198ssize_t InputDispatcher::getConnectionIndexLocked(const sp<InputChannel>& inputChannel) {
Jeff Brown2cbecea2010-08-17 15:59:26 -07003199 ssize_t connectionIndex = mConnectionsByReceiveFd.indexOfKey(inputChannel->getReceivePipeFd());
3200 if (connectionIndex >= 0) {
3201 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
3202 if (connection->inputChannel.get() == inputChannel.get()) {
3203 return connectionIndex;
3204 }
3205 }
3206
3207 return -1;
3208}
3209
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003210void InputDispatcher::activateConnectionLocked(Connection* connection) {
3211 for (size_t i = 0; i < mActiveConnections.size(); i++) {
3212 if (mActiveConnections.itemAt(i) == connection) {
3213 return;
3214 }
3215 }
3216 mActiveConnections.add(connection);
3217}
3218
3219void InputDispatcher::deactivateConnectionLocked(Connection* connection) {
3220 for (size_t i = 0; i < mActiveConnections.size(); i++) {
3221 if (mActiveConnections.itemAt(i) == connection) {
3222 mActiveConnections.removeAt(i);
3223 return;
3224 }
3225 }
3226}
3227
Jeff Brown9c3cda02010-06-15 01:31:58 -07003228void InputDispatcher::onDispatchCycleStartedLocked(
Jeff Brown7fbdc842010-06-17 20:52:56 -07003229 nsecs_t currentTime, const sp<Connection>& connection) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003230}
3231
Jeff Brown9c3cda02010-06-15 01:31:58 -07003232void InputDispatcher::onDispatchCycleFinishedLocked(
Jeff Brown3915bb82010-11-05 15:02:16 -07003233 nsecs_t currentTime, const sp<Connection>& connection, bool handled) {
3234 CommandEntry* commandEntry = postCommandLocked(
3235 & InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
3236 commandEntry->connection = connection;
3237 commandEntry->handled = handled;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003238}
3239
Jeff Brown9c3cda02010-06-15 01:31:58 -07003240void InputDispatcher::onDispatchCycleBrokenLocked(
Jeff Brown7fbdc842010-06-17 20:52:56 -07003241 nsecs_t currentTime, const sp<Connection>& connection) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003242 LOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
3243 connection->getInputChannelName());
3244
Jeff Brown9c3cda02010-06-15 01:31:58 -07003245 CommandEntry* commandEntry = postCommandLocked(
3246 & InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
Jeff Brown7fbdc842010-06-17 20:52:56 -07003247 commandEntry->connection = connection;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003248}
3249
Jeff Brown519e0242010-09-15 15:18:56 -07003250void InputDispatcher::onANRLocked(
3251 nsecs_t currentTime, const InputApplication* application, const InputWindow* window,
3252 nsecs_t eventTime, nsecs_t waitStartTime) {
3253 LOGI("Application is not responding: %s. "
3254 "%01.1fms since event, %01.1fms since wait started",
3255 getApplicationWindowLabelLocked(application, window).string(),
3256 (currentTime - eventTime) / 1000000.0,
3257 (currentTime - waitStartTime) / 1000000.0);
3258
3259 CommandEntry* commandEntry = postCommandLocked(
3260 & InputDispatcher::doNotifyANRLockedInterruptible);
3261 if (application) {
Jeff Brown928e0542011-01-10 11:17:36 -08003262 commandEntry->inputApplicationHandle = application->inputApplicationHandle;
Jeff Brown519e0242010-09-15 15:18:56 -07003263 }
3264 if (window) {
Jeff Brown928e0542011-01-10 11:17:36 -08003265 commandEntry->inputWindowHandle = window->inputWindowHandle;
Jeff Brown519e0242010-09-15 15:18:56 -07003266 commandEntry->inputChannel = window->inputChannel;
3267 }
3268}
3269
Jeff Brownb88102f2010-09-08 11:49:43 -07003270void InputDispatcher::doNotifyConfigurationChangedInterruptible(
3271 CommandEntry* commandEntry) {
3272 mLock.unlock();
3273
3274 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
3275
3276 mLock.lock();
3277}
3278
Jeff Brown9c3cda02010-06-15 01:31:58 -07003279void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(
3280 CommandEntry* commandEntry) {
Jeff Brown7fbdc842010-06-17 20:52:56 -07003281 sp<Connection> connection = commandEntry->connection;
Jeff Brown9c3cda02010-06-15 01:31:58 -07003282
Jeff Brown7fbdc842010-06-17 20:52:56 -07003283 if (connection->status != Connection::STATUS_ZOMBIE) {
3284 mLock.unlock();
Jeff Brown9c3cda02010-06-15 01:31:58 -07003285
Jeff Brown928e0542011-01-10 11:17:36 -08003286 mPolicy->notifyInputChannelBroken(connection->inputWindowHandle);
Jeff Brown7fbdc842010-06-17 20:52:56 -07003287
3288 mLock.lock();
3289 }
Jeff Brown9c3cda02010-06-15 01:31:58 -07003290}
3291
Jeff Brown519e0242010-09-15 15:18:56 -07003292void InputDispatcher::doNotifyANRLockedInterruptible(
Jeff Brown9c3cda02010-06-15 01:31:58 -07003293 CommandEntry* commandEntry) {
Jeff Brown519e0242010-09-15 15:18:56 -07003294 mLock.unlock();
Jeff Brown9c3cda02010-06-15 01:31:58 -07003295
Jeff Brown519e0242010-09-15 15:18:56 -07003296 nsecs_t newTimeout = mPolicy->notifyANR(
Jeff Brown928e0542011-01-10 11:17:36 -08003297 commandEntry->inputApplicationHandle, commandEntry->inputWindowHandle);
Jeff Brown9c3cda02010-06-15 01:31:58 -07003298
Jeff Brown519e0242010-09-15 15:18:56 -07003299 mLock.lock();
Jeff Brown7fbdc842010-06-17 20:52:56 -07003300
Jeff Brown519e0242010-09-15 15:18:56 -07003301 resumeAfterTargetsNotReadyTimeoutLocked(newTimeout, commandEntry->inputChannel);
Jeff Brown9c3cda02010-06-15 01:31:58 -07003302}
3303
Jeff Brownb88102f2010-09-08 11:49:43 -07003304void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
3305 CommandEntry* commandEntry) {
3306 KeyEntry* entry = commandEntry->keyEntry;
Jeff Brown1f245102010-11-18 20:53:46 -08003307
3308 KeyEvent event;
3309 initializeKeyEvent(&event, entry);
Jeff Brownb88102f2010-09-08 11:49:43 -07003310
3311 mLock.unlock();
3312
Jeff Brown928e0542011-01-10 11:17:36 -08003313 bool consumed = mPolicy->interceptKeyBeforeDispatching(commandEntry->inputWindowHandle,
Jeff Brown1f245102010-11-18 20:53:46 -08003314 &event, entry->policyFlags);
Jeff Brownb88102f2010-09-08 11:49:43 -07003315
3316 mLock.lock();
3317
3318 entry->interceptKeyResult = consumed
3319 ? KeyEntry::INTERCEPT_KEY_RESULT_SKIP
3320 : KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
3321 mAllocator.releaseKeyEntry(entry);
3322}
3323
Jeff Brown3915bb82010-11-05 15:02:16 -07003324void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(
3325 CommandEntry* commandEntry) {
3326 sp<Connection> connection = commandEntry->connection;
3327 bool handled = commandEntry->handled;
3328
Jeff Brown49ed71d2010-12-06 17:13:33 -08003329 if (!connection->outboundQueue.isEmpty()) {
Jeff Brown3915bb82010-11-05 15:02:16 -07003330 DispatchEntry* dispatchEntry = connection->outboundQueue.headSentinel.next;
3331 if (dispatchEntry->inProgress
Jeff Brown3915bb82010-11-05 15:02:16 -07003332 && dispatchEntry->eventEntry->type == EventEntry::TYPE_KEY) {
3333 KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry);
Jeff Brown49ed71d2010-12-06 17:13:33 -08003334 if (!(keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK)) {
Jeff Brown524ee642011-03-29 15:11:34 -07003335 // Get the fallback key state.
3336 // Clear it out after dispatching the UP.
3337 int32_t originalKeyCode = keyEntry->keyCode;
3338 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
3339 if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
3340 connection->inputState.removeFallbackKey(originalKeyCode);
3341 }
3342
3343 if (handled || !dispatchEntry->hasForegroundTarget()) {
3344 // If the application handles the original key for which we previously
3345 // generated a fallback or if the window is not a foreground window,
3346 // then cancel the associated fallback key, if any.
3347 if (fallbackKeyCode != -1) {
3348 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
3349 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
3350 "application handled the original non-fallback key "
3351 "or is no longer a foreground target, "
3352 "canceling previously dispatched fallback key");
3353 options.keyCode = fallbackKeyCode;
3354 synthesizeCancelationEventsForConnectionLocked(connection, options);
3355 }
3356 connection->inputState.removeFallbackKey(originalKeyCode);
3357 }
Jeff Brown49ed71d2010-12-06 17:13:33 -08003358 } else {
Jeff Brownbfaf3b92011-02-22 15:00:50 -08003359 // If the application did not handle a non-fallback key, first check
Jeff Brown524ee642011-03-29 15:11:34 -07003360 // that we are in a good state to perform unhandled key event processing
3361 // Then ask the policy what to do with it.
3362 bool initialDown = keyEntry->action == AKEY_EVENT_ACTION_DOWN
3363 && keyEntry->repeatCount == 0;
3364 if (fallbackKeyCode == -1 && !initialDown) {
Jeff Brownbfaf3b92011-02-22 15:00:50 -08003365#if DEBUG_OUTBOUND_EVENT_DETAILS
Jeff Brown524ee642011-03-29 15:11:34 -07003366 LOGD("Unhandled key event: Skipping unhandled key event processing "
3367 "since this is not an initial down. "
3368 "keyCode=%d, action=%d, repeatCount=%d",
3369 originalKeyCode, keyEntry->action, keyEntry->repeatCount);
Jeff Brownbfaf3b92011-02-22 15:00:50 -08003370#endif
Jeff Brown524ee642011-03-29 15:11:34 -07003371 goto SkipFallback;
Jeff Brownbfaf3b92011-02-22 15:00:50 -08003372 }
3373
Jeff Brown524ee642011-03-29 15:11:34 -07003374 // Dispatch the unhandled key to the policy.
Jeff Brownbfaf3b92011-02-22 15:00:50 -08003375#if DEBUG_OUTBOUND_EVENT_DETAILS
3376 LOGD("Unhandled key event: Asking policy to perform fallback action. "
3377 "keyCode=%d, action=%d, repeatCount=%d",
3378 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount);
3379#endif
Jeff Brown49ed71d2010-12-06 17:13:33 -08003380 KeyEvent event;
3381 initializeKeyEvent(&event, keyEntry);
Jeff Brown3915bb82010-11-05 15:02:16 -07003382
Jeff Brown49ed71d2010-12-06 17:13:33 -08003383 mLock.unlock();
Jeff Brown3915bb82010-11-05 15:02:16 -07003384
Jeff Brown928e0542011-01-10 11:17:36 -08003385 bool fallback = mPolicy->dispatchUnhandledKey(connection->inputWindowHandle,
Jeff Brown49ed71d2010-12-06 17:13:33 -08003386 &event, keyEntry->policyFlags, &event);
Jeff Brown3915bb82010-11-05 15:02:16 -07003387
Jeff Brown49ed71d2010-12-06 17:13:33 -08003388 mLock.lock();
3389
Jeff Brown00045a72010-12-09 18:10:30 -08003390 if (connection->status != Connection::STATUS_NORMAL) {
Jeff Brown524ee642011-03-29 15:11:34 -07003391 connection->inputState.removeFallbackKey(originalKeyCode);
Jeff Brown00045a72010-12-09 18:10:30 -08003392 return;
3393 }
3394
3395 assert(connection->outboundQueue.headSentinel.next == dispatchEntry);
3396
Jeff Brown524ee642011-03-29 15:11:34 -07003397 // Latch the fallback keycode for this key on an initial down.
3398 // The fallback keycode cannot change at any other point in the lifecycle.
3399 if (initialDown) {
3400 if (fallback) {
3401 fallbackKeyCode = event.getKeyCode();
3402 } else {
3403 fallbackKeyCode = AKEYCODE_UNKNOWN;
3404 }
3405 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
3406 }
3407
3408 assert(fallbackKeyCode != -1);
3409
3410 // Cancel the fallback key if the policy decides not to send it anymore.
3411 // We will continue to dispatch the key to the policy but we will no
3412 // longer dispatch a fallback key to the application.
3413 if (fallbackKeyCode != AKEYCODE_UNKNOWN
3414 && (!fallback || fallbackKeyCode != event.getKeyCode())) {
3415#if DEBUG_OUTBOUND_EVENT_DETAILS
3416 if (fallback) {
3417 LOGD("Unhandled key event: Policy requested to send key %d"
3418 "as a fallback for %d, but on the DOWN it had requested "
3419 "to send %d instead. Fallback canceled.",
3420 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
3421 } else {
3422 LOGD("Unhandled key event: Policy did not request fallback for %d,"
3423 "but on the DOWN it had requested to send %d. "
3424 "Fallback canceled.",
3425 originalKeyCode, fallbackKeyCode);
3426 }
3427#endif
3428
3429 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
3430 "canceling fallback, policy no longer desires it");
3431 options.keyCode = fallbackKeyCode;
3432 synthesizeCancelationEventsForConnectionLocked(connection, options);
3433
3434 fallback = false;
3435 fallbackKeyCode = AKEYCODE_UNKNOWN;
3436 if (keyEntry->action != AKEY_EVENT_ACTION_UP) {
3437 connection->inputState.setFallbackKey(originalKeyCode,
3438 fallbackKeyCode);
3439 }
3440 }
3441
3442#if DEBUG_OUTBOUND_EVENT_DETAILS
3443 {
3444 String8 msg;
3445 const KeyedVector<int32_t, int32_t>& fallbackKeys =
3446 connection->inputState.getFallbackKeys();
3447 for (size_t i = 0; i < fallbackKeys.size(); i++) {
3448 msg.appendFormat(", %d->%d", fallbackKeys.keyAt(i),
3449 fallbackKeys.valueAt(i));
3450 }
3451 LOGD("Unhandled key event: %d currently tracked fallback keys%s.",
3452 fallbackKeys.size(), msg.string());
3453 }
3454#endif
3455
Jeff Brown49ed71d2010-12-06 17:13:33 -08003456 if (fallback) {
3457 // Restart the dispatch cycle using the fallback key.
3458 keyEntry->eventTime = event.getEventTime();
3459 keyEntry->deviceId = event.getDeviceId();
3460 keyEntry->source = event.getSource();
3461 keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
Jeff Brown524ee642011-03-29 15:11:34 -07003462 keyEntry->keyCode = fallbackKeyCode;
Jeff Brown49ed71d2010-12-06 17:13:33 -08003463 keyEntry->scanCode = event.getScanCode();
3464 keyEntry->metaState = event.getMetaState();
3465 keyEntry->repeatCount = event.getRepeatCount();
3466 keyEntry->downTime = event.getDownTime();
3467 keyEntry->syntheticRepeat = false;
3468
Jeff Brownbfaf3b92011-02-22 15:00:50 -08003469#if DEBUG_OUTBOUND_EVENT_DETAILS
3470 LOGD("Unhandled key event: Dispatching fallback key. "
Jeff Brown524ee642011-03-29 15:11:34 -07003471 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
3472 originalKeyCode, fallbackKeyCode, keyEntry->metaState);
Jeff Brownbfaf3b92011-02-22 15:00:50 -08003473#endif
3474
Jeff Brown49ed71d2010-12-06 17:13:33 -08003475 dispatchEntry->inProgress = false;
3476 startDispatchCycleLocked(now(), connection);
3477 return;
Jeff Brown524ee642011-03-29 15:11:34 -07003478 } else {
3479#if DEBUG_OUTBOUND_EVENT_DETAILS
3480 LOGD("Unhandled key event: No fallback key.");
3481#endif
Jeff Brown49ed71d2010-12-06 17:13:33 -08003482 }
3483 }
3484 }
Jeff Brown3915bb82010-11-05 15:02:16 -07003485 }
3486 }
3487
Jeff Brownbfaf3b92011-02-22 15:00:50 -08003488SkipFallback:
Jeff Brown3915bb82010-11-05 15:02:16 -07003489 startNextDispatchCycleLocked(now(), connection);
3490}
3491
Jeff Brownb88102f2010-09-08 11:49:43 -07003492void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
3493 mLock.unlock();
3494
Jeff Brown01ce2e92010-09-26 22:20:12 -07003495 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
Jeff Brownb88102f2010-09-08 11:49:43 -07003496
3497 mLock.lock();
3498}
3499
Jeff Brown3915bb82010-11-05 15:02:16 -07003500void InputDispatcher::initializeKeyEvent(KeyEvent* event, const KeyEntry* entry) {
3501 event->initialize(entry->deviceId, entry->source, entry->action, entry->flags,
3502 entry->keyCode, entry->scanCode, entry->metaState, entry->repeatCount,
3503 entry->downTime, entry->eventTime);
3504}
3505
Jeff Brown519e0242010-09-15 15:18:56 -07003506void InputDispatcher::updateDispatchStatisticsLocked(nsecs_t currentTime, const EventEntry* entry,
3507 int32_t injectionResult, nsecs_t timeSpentWaitingForApplication) {
3508 // TODO Write some statistics about how long we spend waiting.
Jeff Brownb88102f2010-09-08 11:49:43 -07003509}
3510
3511void InputDispatcher::dump(String8& dump) {
Jeff Brownf2f487182010-10-01 17:46:21 -07003512 dump.append("Input Dispatcher State:\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003513 dumpDispatchStateLocked(dump);
3514}
3515
Jeff Brown9c3cda02010-06-15 01:31:58 -07003516
Jeff Brown519e0242010-09-15 15:18:56 -07003517// --- InputDispatcher::Queue ---
3518
3519template <typename T>
3520uint32_t InputDispatcher::Queue<T>::count() const {
3521 uint32_t result = 0;
3522 for (const T* entry = headSentinel.next; entry != & tailSentinel; entry = entry->next) {
3523 result += 1;
3524 }
3525 return result;
3526}
3527
3528
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003529// --- InputDispatcher::Allocator ---
3530
3531InputDispatcher::Allocator::Allocator() {
3532}
3533
Jeff Brown01ce2e92010-09-26 22:20:12 -07003534InputDispatcher::InjectionState*
3535InputDispatcher::Allocator::obtainInjectionState(int32_t injectorPid, int32_t injectorUid) {
3536 InjectionState* injectionState = mInjectionStatePool.alloc();
3537 injectionState->refCount = 1;
3538 injectionState->injectorPid = injectorPid;
3539 injectionState->injectorUid = injectorUid;
3540 injectionState->injectionIsAsync = false;
3541 injectionState->injectionResult = INPUT_EVENT_INJECTION_PENDING;
3542 injectionState->pendingForegroundDispatches = 0;
3543 return injectionState;
3544}
3545
Jeff Brown7fbdc842010-06-17 20:52:56 -07003546void InputDispatcher::Allocator::initializeEventEntry(EventEntry* entry, int32_t type,
Jeff Brownb6997262010-10-08 22:31:17 -07003547 nsecs_t eventTime, uint32_t policyFlags) {
Jeff Brown7fbdc842010-06-17 20:52:56 -07003548 entry->type = type;
3549 entry->refCount = 1;
3550 entry->dispatchInProgress = false;
Christopher Tatee91a5db2010-06-23 16:50:30 -07003551 entry->eventTime = eventTime;
Jeff Brownb6997262010-10-08 22:31:17 -07003552 entry->policyFlags = policyFlags;
Jeff Brown01ce2e92010-09-26 22:20:12 -07003553 entry->injectionState = NULL;
3554}
3555
3556void InputDispatcher::Allocator::releaseEventEntryInjectionState(EventEntry* entry) {
3557 if (entry->injectionState) {
3558 releaseInjectionState(entry->injectionState);
3559 entry->injectionState = NULL;
3560 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07003561}
3562
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003563InputDispatcher::ConfigurationChangedEntry*
Jeff Brown7fbdc842010-06-17 20:52:56 -07003564InputDispatcher::Allocator::obtainConfigurationChangedEntry(nsecs_t eventTime) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003565 ConfigurationChangedEntry* entry = mConfigurationChangeEntryPool.alloc();
Jeff Brownb6997262010-10-08 22:31:17 -07003566 initializeEventEntry(entry, EventEntry::TYPE_CONFIGURATION_CHANGED, eventTime, 0);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003567 return entry;
3568}
3569
Jeff Brown7fbdc842010-06-17 20:52:56 -07003570InputDispatcher::KeyEntry* InputDispatcher::Allocator::obtainKeyEntry(nsecs_t eventTime,
Jeff Brown58a2da82011-01-25 16:02:22 -08003571 int32_t deviceId, uint32_t source, uint32_t policyFlags, int32_t action,
Jeff Brown7fbdc842010-06-17 20:52:56 -07003572 int32_t flags, int32_t keyCode, int32_t scanCode, int32_t metaState,
3573 int32_t repeatCount, nsecs_t downTime) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003574 KeyEntry* entry = mKeyEntryPool.alloc();
Jeff Brownb6997262010-10-08 22:31:17 -07003575 initializeEventEntry(entry, EventEntry::TYPE_KEY, eventTime, policyFlags);
Jeff Brown7fbdc842010-06-17 20:52:56 -07003576
3577 entry->deviceId = deviceId;
Jeff Brownc5ed5912010-07-14 18:48:53 -07003578 entry->source = source;
Jeff Brown7fbdc842010-06-17 20:52:56 -07003579 entry->action = action;
3580 entry->flags = flags;
3581 entry->keyCode = keyCode;
3582 entry->scanCode = scanCode;
3583 entry->metaState = metaState;
3584 entry->repeatCount = repeatCount;
3585 entry->downTime = downTime;
Jeff Brownb88102f2010-09-08 11:49:43 -07003586 entry->syntheticRepeat = false;
3587 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003588 return entry;
3589}
3590
Jeff Brown7fbdc842010-06-17 20:52:56 -07003591InputDispatcher::MotionEntry* InputDispatcher::Allocator::obtainMotionEntry(nsecs_t eventTime,
Jeff Brown58a2da82011-01-25 16:02:22 -08003592 int32_t deviceId, uint32_t source, uint32_t policyFlags, int32_t action, int32_t flags,
Jeff Brown7fbdc842010-06-17 20:52:56 -07003593 int32_t metaState, int32_t edgeFlags, float xPrecision, float yPrecision,
3594 nsecs_t downTime, uint32_t pointerCount,
3595 const int32_t* pointerIds, const PointerCoords* pointerCoords) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003596 MotionEntry* entry = mMotionEntryPool.alloc();
Jeff Brownb6997262010-10-08 22:31:17 -07003597 initializeEventEntry(entry, EventEntry::TYPE_MOTION, eventTime, policyFlags);
Jeff Brown7fbdc842010-06-17 20:52:56 -07003598
3599 entry->eventTime = eventTime;
3600 entry->deviceId = deviceId;
Jeff Brownc5ed5912010-07-14 18:48:53 -07003601 entry->source = source;
Jeff Brown7fbdc842010-06-17 20:52:56 -07003602 entry->action = action;
Jeff Brown85a31762010-09-01 17:01:00 -07003603 entry->flags = flags;
Jeff Brown7fbdc842010-06-17 20:52:56 -07003604 entry->metaState = metaState;
3605 entry->edgeFlags = edgeFlags;
3606 entry->xPrecision = xPrecision;
3607 entry->yPrecision = yPrecision;
3608 entry->downTime = downTime;
3609 entry->pointerCount = pointerCount;
3610 entry->firstSample.eventTime = eventTime;
Jeff Brown5ced76a2011-05-24 11:23:27 -07003611 entry->firstSample.eventTimeBeforeCoalescing = eventTime;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003612 entry->firstSample.next = NULL;
Jeff Brown7fbdc842010-06-17 20:52:56 -07003613 entry->lastSample = & entry->firstSample;
3614 for (uint32_t i = 0; i < pointerCount; i++) {
3615 entry->pointerIds[i] = pointerIds[i];
Jeff Brown96ad3972011-03-09 17:39:48 -08003616 entry->firstSample.pointerCoords[i].copyFrom(pointerCoords[i]);
Jeff Brown7fbdc842010-06-17 20:52:56 -07003617 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003618 return entry;
3619}
3620
3621InputDispatcher::DispatchEntry* InputDispatcher::Allocator::obtainDispatchEntry(
Jeff Brownb88102f2010-09-08 11:49:43 -07003622 EventEntry* eventEntry,
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003623 int32_t targetFlags, float xOffset, float yOffset, float scaleFactor) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003624 DispatchEntry* entry = mDispatchEntryPool.alloc();
3625 entry->eventEntry = eventEntry;
3626 eventEntry->refCount += 1;
Jeff Brownb88102f2010-09-08 11:49:43 -07003627 entry->targetFlags = targetFlags;
3628 entry->xOffset = xOffset;
3629 entry->yOffset = yOffset;
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003630 entry->scaleFactor = scaleFactor;
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
3705void InputDispatcher::Allocator::releaseDispatchEntry(DispatchEntry* entry) {
3706 releaseEventEntry(entry->eventEntry);
3707 mDispatchEntryPool.free(entry);
3708}
3709
Jeff Brown9c3cda02010-06-15 01:31:58 -07003710void InputDispatcher::Allocator::releaseCommandEntry(CommandEntry* entry) {
3711 mCommandEntryPool.free(entry);
3712}
3713
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003714void InputDispatcher::Allocator::appendMotionSample(MotionEntry* motionEntry,
Jeff Brown7fbdc842010-06-17 20:52:56 -07003715 nsecs_t eventTime, const PointerCoords* pointerCoords) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003716 MotionSample* sample = mMotionSamplePool.alloc();
3717 sample->eventTime = eventTime;
Jeff Brown5ced76a2011-05-24 11:23:27 -07003718 sample->eventTimeBeforeCoalescing = eventTime;
Jeff Brown7fbdc842010-06-17 20:52:56 -07003719 uint32_t pointerCount = motionEntry->pointerCount;
3720 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brown96ad3972011-03-09 17:39:48 -08003721 sample->pointerCoords[i].copyFrom(pointerCoords[i]);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003722 }
3723
3724 sample->next = NULL;
3725 motionEntry->lastSample->next = sample;
3726 motionEntry->lastSample = sample;
3727}
3728
Jeff Brown01ce2e92010-09-26 22:20:12 -07003729void InputDispatcher::Allocator::recycleKeyEntry(KeyEntry* keyEntry) {
3730 releaseEventEntryInjectionState(keyEntry);
Jeff Brownb88102f2010-09-08 11:49:43 -07003731
Jeff Brown01ce2e92010-09-26 22:20:12 -07003732 keyEntry->dispatchInProgress = false;
3733 keyEntry->syntheticRepeat = false;
3734 keyEntry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
Jeff Brownb88102f2010-09-08 11:49:43 -07003735}
3736
3737
Jeff Brownae9fc032010-08-18 15:51:08 -07003738// --- InputDispatcher::MotionEntry ---
3739
3740uint32_t InputDispatcher::MotionEntry::countSamples() const {
3741 uint32_t count = 1;
3742 for (MotionSample* sample = firstSample.next; sample != NULL; sample = sample->next) {
3743 count += 1;
3744 }
3745 return count;
3746}
3747
Jeff Brown5ced76a2011-05-24 11:23:27 -07003748bool InputDispatcher::MotionEntry::canAppendSamples(int32_t action, uint32_t pointerCount,
3749 const int32_t* pointerIds) const {
3750 if (this->action != action
3751 || this->pointerCount != pointerCount
3752 || this->isInjected()) {
3753 return false;
3754 }
3755 for (uint32_t i = 0; i < pointerCount; i++) {
3756 if (this->pointerIds[i] != pointerIds[i]) {
3757 return false;
3758 }
3759 }
3760 return true;
3761}
3762
Jeff Brownb88102f2010-09-08 11:49:43 -07003763
3764// --- InputDispatcher::InputState ---
3765
Jeff Brownb6997262010-10-08 22:31:17 -07003766InputDispatcher::InputState::InputState() {
Jeff Brownb88102f2010-09-08 11:49:43 -07003767}
3768
3769InputDispatcher::InputState::~InputState() {
3770}
3771
3772bool InputDispatcher::InputState::isNeutral() const {
3773 return mKeyMementos.isEmpty() && mMotionMementos.isEmpty();
3774}
3775
Jeff Browncc0c1592011-02-19 05:07:28 -08003776void InputDispatcher::InputState::trackEvent(
Jeff Brownb88102f2010-09-08 11:49:43 -07003777 const EventEntry* entry) {
3778 switch (entry->type) {
3779 case EventEntry::TYPE_KEY:
Jeff Browncc0c1592011-02-19 05:07:28 -08003780 trackKey(static_cast<const KeyEntry*>(entry));
3781 break;
Jeff Brownb88102f2010-09-08 11:49:43 -07003782
3783 case EventEntry::TYPE_MOTION:
Jeff Browncc0c1592011-02-19 05:07:28 -08003784 trackMotion(static_cast<const MotionEntry*>(entry));
3785 break;
Jeff Brownb88102f2010-09-08 11:49:43 -07003786 }
3787}
3788
Jeff Browncc0c1592011-02-19 05:07:28 -08003789void InputDispatcher::InputState::trackKey(
Jeff Brownb88102f2010-09-08 11:49:43 -07003790 const KeyEntry* entry) {
3791 int32_t action = entry->action;
Jeff Brown524ee642011-03-29 15:11:34 -07003792 if (action == AKEY_EVENT_ACTION_UP
3793 && (entry->flags & AKEY_EVENT_FLAG_FALLBACK)) {
3794 for (size_t i = 0; i < mFallbackKeys.size(); ) {
3795 if (mFallbackKeys.valueAt(i) == entry->keyCode) {
3796 mFallbackKeys.removeItemsAt(i);
3797 } else {
3798 i += 1;
3799 }
3800 }
3801 }
3802
Jeff Brownb88102f2010-09-08 11:49:43 -07003803 for (size_t i = 0; i < mKeyMementos.size(); i++) {
3804 KeyMemento& memento = mKeyMementos.editItemAt(i);
3805 if (memento.deviceId == entry->deviceId
3806 && memento.source == entry->source
3807 && memento.keyCode == entry->keyCode
3808 && memento.scanCode == entry->scanCode) {
3809 switch (action) {
3810 case AKEY_EVENT_ACTION_UP:
3811 mKeyMementos.removeAt(i);
Jeff Browncc0c1592011-02-19 05:07:28 -08003812 return;
Jeff Brownb88102f2010-09-08 11:49:43 -07003813
3814 case AKEY_EVENT_ACTION_DOWN:
Jeff Browncc0c1592011-02-19 05:07:28 -08003815 mKeyMementos.removeAt(i);
3816 goto Found;
Jeff Brownb88102f2010-09-08 11:49:43 -07003817
3818 default:
Jeff Browncc0c1592011-02-19 05:07:28 -08003819 return;
Jeff Brownb88102f2010-09-08 11:49:43 -07003820 }
3821 }
3822 }
3823
Jeff Browncc0c1592011-02-19 05:07:28 -08003824Found:
3825 if (action == AKEY_EVENT_ACTION_DOWN) {
Jeff Brownb88102f2010-09-08 11:49:43 -07003826 mKeyMementos.push();
3827 KeyMemento& memento = mKeyMementos.editTop();
3828 memento.deviceId = entry->deviceId;
3829 memento.source = entry->source;
3830 memento.keyCode = entry->keyCode;
3831 memento.scanCode = entry->scanCode;
Jeff Brown49ed71d2010-12-06 17:13:33 -08003832 memento.flags = entry->flags;
Jeff Brownb88102f2010-09-08 11:49:43 -07003833 memento.downTime = entry->downTime;
Jeff Brownb88102f2010-09-08 11:49:43 -07003834 }
3835}
3836
Jeff Browncc0c1592011-02-19 05:07:28 -08003837void InputDispatcher::InputState::trackMotion(
Jeff Brownb88102f2010-09-08 11:49:43 -07003838 const MotionEntry* entry) {
3839 int32_t action = entry->action & AMOTION_EVENT_ACTION_MASK;
3840 for (size_t i = 0; i < mMotionMementos.size(); i++) {
3841 MotionMemento& memento = mMotionMementos.editItemAt(i);
3842 if (memento.deviceId == entry->deviceId
3843 && memento.source == entry->source) {
3844 switch (action) {
3845 case AMOTION_EVENT_ACTION_UP:
3846 case AMOTION_EVENT_ACTION_CANCEL:
Jeff Browncc0c1592011-02-19 05:07:28 -08003847 case AMOTION_EVENT_ACTION_HOVER_MOVE:
Jeff Brownb88102f2010-09-08 11:49:43 -07003848 mMotionMementos.removeAt(i);
Jeff Browncc0c1592011-02-19 05:07:28 -08003849 return;
Jeff Brownb88102f2010-09-08 11:49:43 -07003850
3851 case AMOTION_EVENT_ACTION_DOWN:
Jeff Browncc0c1592011-02-19 05:07:28 -08003852 mMotionMementos.removeAt(i);
3853 goto Found;
Jeff Brownb88102f2010-09-08 11:49:43 -07003854
3855 case AMOTION_EVENT_ACTION_POINTER_UP:
Jeff Browncc0c1592011-02-19 05:07:28 -08003856 case AMOTION_EVENT_ACTION_POINTER_DOWN:
Jeff Brownb88102f2010-09-08 11:49:43 -07003857 case AMOTION_EVENT_ACTION_MOVE:
Jeff Browncc0c1592011-02-19 05:07:28 -08003858 memento.setPointers(entry);
3859 return;
Jeff Brownb88102f2010-09-08 11:49:43 -07003860
3861 default:
Jeff Browncc0c1592011-02-19 05:07:28 -08003862 return;
Jeff Brownb88102f2010-09-08 11:49:43 -07003863 }
3864 }
3865 }
3866
Jeff Browncc0c1592011-02-19 05:07:28 -08003867Found:
3868 if (action == AMOTION_EVENT_ACTION_DOWN) {
Jeff Brownb88102f2010-09-08 11:49:43 -07003869 mMotionMementos.push();
3870 MotionMemento& memento = mMotionMementos.editTop();
3871 memento.deviceId = entry->deviceId;
3872 memento.source = entry->source;
3873 memento.xPrecision = entry->xPrecision;
3874 memento.yPrecision = entry->yPrecision;
3875 memento.downTime = entry->downTime;
3876 memento.setPointers(entry);
Jeff Brownb88102f2010-09-08 11:49:43 -07003877 }
3878}
3879
3880void InputDispatcher::InputState::MotionMemento::setPointers(const MotionEntry* entry) {
3881 pointerCount = entry->pointerCount;
3882 for (uint32_t i = 0; i < entry->pointerCount; i++) {
3883 pointerIds[i] = entry->pointerIds[i];
Jeff Brown96ad3972011-03-09 17:39:48 -08003884 pointerCoords[i].copyFrom(entry->lastSample->pointerCoords[i]);
Jeff Brownb88102f2010-09-08 11:49:43 -07003885 }
3886}
3887
Jeff Brownb6997262010-10-08 22:31:17 -07003888void InputDispatcher::InputState::synthesizeCancelationEvents(nsecs_t currentTime,
3889 Allocator* allocator, Vector<EventEntry*>& outEvents,
Jeff Brown524ee642011-03-29 15:11:34 -07003890 const CancelationOptions& options) {
Jeff Brownb6997262010-10-08 22:31:17 -07003891 for (size_t i = 0; i < mKeyMementos.size(); ) {
Jeff Brownb88102f2010-09-08 11:49:43 -07003892 const KeyMemento& memento = mKeyMementos.itemAt(i);
Jeff Brown49ed71d2010-12-06 17:13:33 -08003893 if (shouldCancelKey(memento, options)) {
Jeff Brownb6997262010-10-08 22:31:17 -07003894 outEvents.push(allocator->obtainKeyEntry(currentTime,
3895 memento.deviceId, memento.source, 0,
Jeff Brown49ed71d2010-12-06 17:13:33 -08003896 AKEY_EVENT_ACTION_UP, memento.flags | AKEY_EVENT_FLAG_CANCELED,
Jeff Brownb6997262010-10-08 22:31:17 -07003897 memento.keyCode, memento.scanCode, 0, 0, memento.downTime));
3898 mKeyMementos.removeAt(i);
3899 } else {
3900 i += 1;
3901 }
Jeff Brownb88102f2010-09-08 11:49:43 -07003902 }
3903
Jeff Browna1160a72010-10-11 18:22:53 -07003904 for (size_t i = 0; i < mMotionMementos.size(); ) {
Jeff Brownb88102f2010-09-08 11:49:43 -07003905 const MotionMemento& memento = mMotionMementos.itemAt(i);
Jeff Brown49ed71d2010-12-06 17:13:33 -08003906 if (shouldCancelMotion(memento, options)) {
Jeff Brownb6997262010-10-08 22:31:17 -07003907 outEvents.push(allocator->obtainMotionEntry(currentTime,
3908 memento.deviceId, memento.source, 0,
3909 AMOTION_EVENT_ACTION_CANCEL, 0, 0, 0,
3910 memento.xPrecision, memento.yPrecision, memento.downTime,
3911 memento.pointerCount, memento.pointerIds, memento.pointerCoords));
3912 mMotionMementos.removeAt(i);
3913 } else {
3914 i += 1;
3915 }
Jeff Brownb88102f2010-09-08 11:49:43 -07003916 }
3917}
3918
3919void InputDispatcher::InputState::clear() {
3920 mKeyMementos.clear();
3921 mMotionMementos.clear();
Jeff Brown524ee642011-03-29 15:11:34 -07003922 mFallbackKeys.clear();
Jeff Brownb6997262010-10-08 22:31:17 -07003923}
3924
Jeff Brown9c9f1a32010-10-11 18:32:20 -07003925void InputDispatcher::InputState::copyPointerStateTo(InputState& other) const {
3926 for (size_t i = 0; i < mMotionMementos.size(); i++) {
3927 const MotionMemento& memento = mMotionMementos.itemAt(i);
3928 if (memento.source & AINPUT_SOURCE_CLASS_POINTER) {
3929 for (size_t j = 0; j < other.mMotionMementos.size(); ) {
3930 const MotionMemento& otherMemento = other.mMotionMementos.itemAt(j);
3931 if (memento.deviceId == otherMemento.deviceId
3932 && memento.source == otherMemento.source) {
3933 other.mMotionMementos.removeAt(j);
3934 } else {
3935 j += 1;
3936 }
3937 }
3938 other.mMotionMementos.push(memento);
3939 }
3940 }
3941}
3942
Jeff Brown524ee642011-03-29 15:11:34 -07003943int32_t InputDispatcher::InputState::getFallbackKey(int32_t originalKeyCode) {
3944 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
3945 return index >= 0 ? mFallbackKeys.valueAt(index) : -1;
3946}
3947
3948void InputDispatcher::InputState::setFallbackKey(int32_t originalKeyCode,
3949 int32_t fallbackKeyCode) {
3950 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
3951 if (index >= 0) {
3952 mFallbackKeys.replaceValueAt(index, fallbackKeyCode);
3953 } else {
3954 mFallbackKeys.add(originalKeyCode, fallbackKeyCode);
3955 }
3956}
3957
3958void InputDispatcher::InputState::removeFallbackKey(int32_t originalKeyCode) {
3959 mFallbackKeys.removeItem(originalKeyCode);
3960}
3961
Jeff Brown49ed71d2010-12-06 17:13:33 -08003962bool InputDispatcher::InputState::shouldCancelKey(const KeyMemento& memento,
Jeff Brown524ee642011-03-29 15:11:34 -07003963 const CancelationOptions& options) {
3964 if (options.keyCode != -1 && memento.keyCode != options.keyCode) {
3965 return false;
3966 }
3967
3968 switch (options.mode) {
3969 case CancelationOptions::CANCEL_ALL_EVENTS:
3970 case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
Jeff Brownb6997262010-10-08 22:31:17 -07003971 return true;
Jeff Brown524ee642011-03-29 15:11:34 -07003972 case CancelationOptions::CANCEL_FALLBACK_EVENTS:
Jeff Brown49ed71d2010-12-06 17:13:33 -08003973 return memento.flags & AKEY_EVENT_FLAG_FALLBACK;
3974 default:
3975 return false;
3976 }
3977}
3978
3979bool InputDispatcher::InputState::shouldCancelMotion(const MotionMemento& memento,
Jeff Brown524ee642011-03-29 15:11:34 -07003980 const CancelationOptions& options) {
3981 switch (options.mode) {
3982 case CancelationOptions::CANCEL_ALL_EVENTS:
Jeff Brown49ed71d2010-12-06 17:13:33 -08003983 return true;
Jeff Brown524ee642011-03-29 15:11:34 -07003984 case CancelationOptions::CANCEL_POINTER_EVENTS:
Jeff Brown49ed71d2010-12-06 17:13:33 -08003985 return memento.source & AINPUT_SOURCE_CLASS_POINTER;
Jeff Brown524ee642011-03-29 15:11:34 -07003986 case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
Jeff Brown49ed71d2010-12-06 17:13:33 -08003987 return !(memento.source & AINPUT_SOURCE_CLASS_POINTER);
3988 default:
3989 return false;
Jeff Brownb6997262010-10-08 22:31:17 -07003990 }
Jeff Brownb88102f2010-09-08 11:49:43 -07003991}
3992
3993
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003994// --- InputDispatcher::Connection ---
3995
Jeff Brown928e0542011-01-10 11:17:36 -08003996InputDispatcher::Connection::Connection(const sp<InputChannel>& inputChannel,
3997 const sp<InputWindowHandle>& inputWindowHandle) :
3998 status(STATUS_NORMAL), inputChannel(inputChannel), inputWindowHandle(inputWindowHandle),
3999 inputPublisher(inputChannel),
Jeff Brown524ee642011-03-29 15:11:34 -07004000 lastEventTime(LONG_LONG_MAX), lastDispatchTime(LONG_LONG_MAX) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004001}
4002
4003InputDispatcher::Connection::~Connection() {
4004}
4005
4006status_t InputDispatcher::Connection::initialize() {
4007 return inputPublisher.initialize();
4008}
4009
Jeff Brown9c3cda02010-06-15 01:31:58 -07004010const char* InputDispatcher::Connection::getStatusLabel() const {
4011 switch (status) {
4012 case STATUS_NORMAL:
4013 return "NORMAL";
4014
4015 case STATUS_BROKEN:
4016 return "BROKEN";
4017
Jeff Brown9c3cda02010-06-15 01:31:58 -07004018 case STATUS_ZOMBIE:
4019 return "ZOMBIE";
4020
4021 default:
4022 return "UNKNOWN";
4023 }
4024}
4025
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004026InputDispatcher::DispatchEntry* InputDispatcher::Connection::findQueuedDispatchEntryForEvent(
4027 const EventEntry* eventEntry) const {
Jeff Brownb88102f2010-09-08 11:49:43 -07004028 for (DispatchEntry* dispatchEntry = outboundQueue.tailSentinel.prev;
4029 dispatchEntry != & outboundQueue.headSentinel; dispatchEntry = dispatchEntry->prev) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004030 if (dispatchEntry->eventEntry == eventEntry) {
4031 return dispatchEntry;
4032 }
4033 }
4034 return NULL;
4035}
4036
Jeff Brownb88102f2010-09-08 11:49:43 -07004037
Jeff Brown9c3cda02010-06-15 01:31:58 -07004038// --- InputDispatcher::CommandEntry ---
4039
Jeff Brownb88102f2010-09-08 11:49:43 -07004040InputDispatcher::CommandEntry::CommandEntry() :
4041 keyEntry(NULL) {
Jeff Brown9c3cda02010-06-15 01:31:58 -07004042}
4043
4044InputDispatcher::CommandEntry::~CommandEntry() {
4045}
4046
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004047
Jeff Brown01ce2e92010-09-26 22:20:12 -07004048// --- InputDispatcher::TouchState ---
4049
4050InputDispatcher::TouchState::TouchState() :
Jeff Brown58a2da82011-01-25 16:02:22 -08004051 down(false), split(false), deviceId(-1), source(0) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07004052}
4053
4054InputDispatcher::TouchState::~TouchState() {
4055}
4056
4057void InputDispatcher::TouchState::reset() {
4058 down = false;
4059 split = false;
Jeff Brown95712852011-01-04 19:41:59 -08004060 deviceId = -1;
Jeff Brown58a2da82011-01-25 16:02:22 -08004061 source = 0;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004062 windows.clear();
4063}
4064
4065void InputDispatcher::TouchState::copyFrom(const TouchState& other) {
4066 down = other.down;
4067 split = other.split;
Jeff Brown95712852011-01-04 19:41:59 -08004068 deviceId = other.deviceId;
Jeff Brown58a2da82011-01-25 16:02:22 -08004069 source = other.source;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004070 windows.clear();
4071 windows.appendVector(other.windows);
4072}
4073
4074void InputDispatcher::TouchState::addOrUpdateWindow(const InputWindow* window,
4075 int32_t targetFlags, BitSet32 pointerIds) {
4076 if (targetFlags & InputTarget::FLAG_SPLIT) {
4077 split = true;
4078 }
4079
4080 for (size_t i = 0; i < windows.size(); i++) {
4081 TouchedWindow& touchedWindow = windows.editItemAt(i);
4082 if (touchedWindow.window == window) {
4083 touchedWindow.targetFlags |= targetFlags;
4084 touchedWindow.pointerIds.value |= pointerIds.value;
4085 return;
4086 }
4087 }
4088
4089 windows.push();
4090
4091 TouchedWindow& touchedWindow = windows.editTop();
4092 touchedWindow.window = window;
4093 touchedWindow.targetFlags = targetFlags;
4094 touchedWindow.pointerIds = pointerIds;
4095 touchedWindow.channel = window->inputChannel;
4096}
4097
4098void InputDispatcher::TouchState::removeOutsideTouchWindows() {
4099 for (size_t i = 0 ; i < windows.size(); ) {
4100 if (windows[i].targetFlags & InputTarget::FLAG_OUTSIDE) {
4101 windows.removeAt(i);
4102 } else {
4103 i += 1;
4104 }
4105 }
4106}
4107
4108const InputWindow* InputDispatcher::TouchState::getFirstForegroundWindow() {
4109 for (size_t i = 0; i < windows.size(); i++) {
4110 if (windows[i].targetFlags & InputTarget::FLAG_FOREGROUND) {
4111 return windows[i].window;
4112 }
4113 }
4114 return NULL;
4115}
4116
4117
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004118// --- InputDispatcherThread ---
4119
4120InputDispatcherThread::InputDispatcherThread(const sp<InputDispatcherInterface>& dispatcher) :
4121 Thread(/*canCallJava*/ true), mDispatcher(dispatcher) {
4122}
4123
4124InputDispatcherThread::~InputDispatcherThread() {
4125}
4126
4127bool InputDispatcherThread::threadLoop() {
4128 mDispatcher->dispatchOnce();
4129 return true;
4130}
4131
4132} // namespace android