blob: 9a77af353cbbc1eccfb35249598166fc8b584429 [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 return; // done!
2436 }
2437 }
2438
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002439 // STREAMING CASE
2440 //
2441 // There is no pending motion event (of any kind) for this device in the inbound queue.
Jeff Brown519e0242010-09-15 15:18:56 -07002442 // Search the outbound queue for the current foreground targets to find a dispatched
2443 // motion event that is still in progress. If found, then, appen the new sample to
2444 // that event and push it out to all current targets. The logic in
2445 // prepareDispatchCycleLocked takes care of the case where some targets may
2446 // already have consumed the motion event by starting a new dispatch cycle if needed.
Jeff Brown9c3cda02010-06-15 01:31:58 -07002447 if (mCurrentInputTargetsValid) {
Jeff Brown519e0242010-09-15 15:18:56 -07002448 for (size_t i = 0; i < mCurrentInputTargets.size(); i++) {
2449 const InputTarget& inputTarget = mCurrentInputTargets[i];
2450 if ((inputTarget.flags & InputTarget::FLAG_FOREGROUND) == 0) {
2451 // Skip non-foreground targets. We only want to stream if there is at
2452 // least one foreground target whose dispatch is still in progress.
2453 continue;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002454 }
Jeff Brown519e0242010-09-15 15:18:56 -07002455
2456 ssize_t connectionIndex = getConnectionIndexLocked(inputTarget.inputChannel);
2457 if (connectionIndex < 0) {
2458 // Connection must no longer be valid.
2459 continue;
2460 }
2461
2462 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
2463 if (connection->outboundQueue.isEmpty()) {
2464 // This foreground target has an empty outbound queue.
2465 continue;
2466 }
2467
2468 DispatchEntry* dispatchEntry = connection->outboundQueue.headSentinel.next;
2469 if (! dispatchEntry->inProgress
Jeff Brown01ce2e92010-09-26 22:20:12 -07002470 || dispatchEntry->eventEntry->type != EventEntry::TYPE_MOTION
2471 || dispatchEntry->isSplit()) {
2472 // No motion event is being dispatched, or it is being split across
2473 // windows in which case we cannot stream.
Jeff Brown519e0242010-09-15 15:18:56 -07002474 continue;
2475 }
2476
2477 MotionEntry* motionEntry = static_cast<MotionEntry*>(
2478 dispatchEntry->eventEntry);
Jeff Browncc0c1592011-02-19 05:07:28 -08002479 if (motionEntry->action != action
Jeff Brown519e0242010-09-15 15:18:56 -07002480 || motionEntry->deviceId != deviceId
Jeff Brown58a2da82011-01-25 16:02:22 -08002481 || motionEntry->source != source
Jeff Brown519e0242010-09-15 15:18:56 -07002482 || motionEntry->pointerCount != pointerCount
2483 || motionEntry->isInjected()) {
2484 // The motion event is not compatible with this move.
2485 continue;
2486 }
2487
2488 // Hurray! This foreground target is currently dispatching a move event
2489 // that we can stream onto. Append the motion sample and resume dispatch.
2490 mAllocator.appendMotionSample(motionEntry, eventTime, pointerCoords);
2491#if DEBUG_BATCHING
2492 LOGD("Appended motion sample onto batch for most recently dispatched "
Jeff Brown5ced76a2011-05-24 11:23:27 -07002493 "motion event for this device and source in the outbound queues. "
Jeff Brown519e0242010-09-15 15:18:56 -07002494 "Attempting to stream the motion sample.");
2495#endif
2496 nsecs_t currentTime = now();
2497 dispatchEventToCurrentInputTargetsLocked(currentTime, motionEntry,
2498 true /*resumeWithAppendedMotionSample*/);
2499
2500 runCommandsLockedInterruptible();
2501 return; // done!
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002502 }
2503 }
2504
2505NoBatchingOrStreaming:;
2506 }
2507
2508 // Just enqueue a new motion event.
Jeff Brown7fbdc842010-06-17 20:52:56 -07002509 MotionEntry* newEntry = mAllocator.obtainMotionEntry(eventTime,
Jeff Brown85a31762010-09-01 17:01:00 -07002510 deviceId, source, policyFlags, action, flags, metaState, edgeFlags,
Jeff Brown7fbdc842010-06-17 20:52:56 -07002511 xPrecision, yPrecision, downTime,
2512 pointerCount, pointerIds, pointerCoords);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002513
Jeff Brownb88102f2010-09-08 11:49:43 -07002514 needWake = enqueueInboundEventLocked(newEntry);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002515 } // release lock
2516
Jeff Brownb88102f2010-09-08 11:49:43 -07002517 if (needWake) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002518 mLooper->wake();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002519 }
2520}
2521
Jeff Brown5ced76a2011-05-24 11:23:27 -07002522void InputDispatcher::batchMotionLocked(MotionEntry* entry, nsecs_t eventTime,
2523 int32_t metaState, const PointerCoords* pointerCoords, const char* eventDescription) {
2524 // Combine meta states.
2525 entry->metaState |= metaState;
2526
2527 // Coalesce this sample if not enough time has elapsed since the last sample was
2528 // initially appended to the batch.
2529 MotionSample* lastSample = entry->lastSample;
2530 long interval = eventTime - lastSample->eventTimeBeforeCoalescing;
2531 if (interval <= MOTION_SAMPLE_COALESCE_INTERVAL) {
2532 uint32_t pointerCount = entry->pointerCount;
2533 for (uint32_t i = 0; i < pointerCount; i++) {
2534 lastSample->pointerCoords[i].copyFrom(pointerCoords[i]);
2535 }
2536 lastSample->eventTime = eventTime;
2537#if DEBUG_BATCHING
2538 LOGD("Coalesced motion into last sample of batch for %s, events were %0.3f ms apart",
2539 eventDescription, interval * 0.000001f);
2540#endif
2541 return;
2542 }
2543
2544 // Append the sample.
2545 mAllocator.appendMotionSample(entry, eventTime, pointerCoords);
2546#if DEBUG_BATCHING
2547 LOGD("Appended motion sample onto batch for %s, events were %0.3f ms apart",
2548 eventDescription, interval * 0.000001f);
2549#endif
2550}
2551
Jeff Brownb6997262010-10-08 22:31:17 -07002552void InputDispatcher::notifySwitch(nsecs_t when, int32_t switchCode, int32_t switchValue,
2553 uint32_t policyFlags) {
2554#if DEBUG_INBOUND_EVENT_DETAILS
2555 LOGD("notifySwitch - switchCode=%d, switchValue=%d, policyFlags=0x%x",
2556 switchCode, switchValue, policyFlags);
2557#endif
2558
Jeff Browne20c9e02010-10-11 14:20:19 -07002559 policyFlags |= POLICY_FLAG_TRUSTED;
Jeff Brownb6997262010-10-08 22:31:17 -07002560 mPolicy->notifySwitch(when, switchCode, switchValue, policyFlags);
2561}
2562
Jeff Brown7fbdc842010-06-17 20:52:56 -07002563int32_t InputDispatcher::injectInputEvent(const InputEvent* event,
Jeff Brown6ec402b2010-07-28 15:48:59 -07002564 int32_t injectorPid, int32_t injectorUid, int32_t syncMode, int32_t timeoutMillis) {
Jeff Brown7fbdc842010-06-17 20:52:56 -07002565#if DEBUG_INBOUND_EVENT_DETAILS
2566 LOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Jeff Brown6ec402b2010-07-28 15:48:59 -07002567 "syncMode=%d, timeoutMillis=%d",
2568 event->getType(), injectorPid, injectorUid, syncMode, timeoutMillis);
Jeff Brown7fbdc842010-06-17 20:52:56 -07002569#endif
2570
2571 nsecs_t endTime = now() + milliseconds_to_nanoseconds(timeoutMillis);
Jeff Browne20c9e02010-10-11 14:20:19 -07002572
2573 uint32_t policyFlags = POLICY_FLAG_INJECTED;
2574 if (hasInjectionPermission(injectorPid, injectorUid)) {
2575 policyFlags |= POLICY_FLAG_TRUSTED;
2576 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07002577
Jeff Brownb6997262010-10-08 22:31:17 -07002578 EventEntry* injectedEntry;
2579 switch (event->getType()) {
2580 case AINPUT_EVENT_TYPE_KEY: {
2581 const KeyEvent* keyEvent = static_cast<const KeyEvent*>(event);
2582 int32_t action = keyEvent->getAction();
2583 if (! validateKeyEvent(action)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07002584 return INPUT_EVENT_INJECTION_FAILED;
2585 }
2586
Jeff Brownb6997262010-10-08 22:31:17 -07002587 int32_t flags = keyEvent->getFlags();
Jeff Brown1f245102010-11-18 20:53:46 -08002588 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
2589 policyFlags |= POLICY_FLAG_VIRTUAL;
2590 }
2591
2592 mPolicy->interceptKeyBeforeQueueing(keyEvent, /*byref*/ policyFlags);
2593
2594 if (policyFlags & POLICY_FLAG_WOKE_HERE) {
2595 flags |= AKEY_EVENT_FLAG_WOKE_HERE;
2596 }
Jeff Brown6ec402b2010-07-28 15:48:59 -07002597
Jeff Brownb6997262010-10-08 22:31:17 -07002598 mLock.lock();
Jeff Brown1f245102010-11-18 20:53:46 -08002599 injectedEntry = mAllocator.obtainKeyEntry(keyEvent->getEventTime(),
2600 keyEvent->getDeviceId(), keyEvent->getSource(),
2601 policyFlags, action, flags,
2602 keyEvent->getKeyCode(), keyEvent->getScanCode(), keyEvent->getMetaState(),
Jeff Brownb6997262010-10-08 22:31:17 -07002603 keyEvent->getRepeatCount(), keyEvent->getDownTime());
2604 break;
2605 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07002606
Jeff Brownb6997262010-10-08 22:31:17 -07002607 case AINPUT_EVENT_TYPE_MOTION: {
2608 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
2609 int32_t action = motionEvent->getAction();
2610 size_t pointerCount = motionEvent->getPointerCount();
2611 const int32_t* pointerIds = motionEvent->getPointerIds();
2612 if (! validateMotionEvent(action, pointerCount, pointerIds)) {
2613 return INPUT_EVENT_INJECTION_FAILED;
2614 }
2615
2616 nsecs_t eventTime = motionEvent->getEventTime();
Jeff Brown56194eb2011-03-02 19:23:13 -08002617 mPolicy->interceptMotionBeforeQueueing(eventTime, /*byref*/ policyFlags);
Jeff Brownb6997262010-10-08 22:31:17 -07002618
2619 mLock.lock();
2620 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
2621 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
2622 MotionEntry* motionEntry = mAllocator.obtainMotionEntry(*sampleEventTimes,
2623 motionEvent->getDeviceId(), motionEvent->getSource(), policyFlags,
2624 action, motionEvent->getFlags(),
2625 motionEvent->getMetaState(), motionEvent->getEdgeFlags(),
2626 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
2627 motionEvent->getDownTime(), uint32_t(pointerCount),
2628 pointerIds, samplePointerCoords);
2629 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
2630 sampleEventTimes += 1;
2631 samplePointerCoords += pointerCount;
2632 mAllocator.appendMotionSample(motionEntry, *sampleEventTimes, samplePointerCoords);
2633 }
2634 injectedEntry = motionEntry;
2635 break;
2636 }
2637
2638 default:
2639 LOGW("Cannot inject event of type %d", event->getType());
2640 return INPUT_EVENT_INJECTION_FAILED;
2641 }
2642
2643 InjectionState* injectionState = mAllocator.obtainInjectionState(injectorPid, injectorUid);
2644 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
2645 injectionState->injectionIsAsync = true;
2646 }
2647
2648 injectionState->refCount += 1;
2649 injectedEntry->injectionState = injectionState;
2650
2651 bool needWake = enqueueInboundEventLocked(injectedEntry);
2652 mLock.unlock();
Jeff Brown7fbdc842010-06-17 20:52:56 -07002653
Jeff Brownb88102f2010-09-08 11:49:43 -07002654 if (needWake) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002655 mLooper->wake();
Jeff Brown7fbdc842010-06-17 20:52:56 -07002656 }
2657
2658 int32_t injectionResult;
2659 { // acquire lock
2660 AutoMutex _l(mLock);
2661
Jeff Brown6ec402b2010-07-28 15:48:59 -07002662 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
2663 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
2664 } else {
2665 for (;;) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002666 injectionResult = injectionState->injectionResult;
Jeff Brown6ec402b2010-07-28 15:48:59 -07002667 if (injectionResult != INPUT_EVENT_INJECTION_PENDING) {
2668 break;
2669 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07002670
Jeff Brown7fbdc842010-06-17 20:52:56 -07002671 nsecs_t remainingTimeout = endTime - now();
2672 if (remainingTimeout <= 0) {
Jeff Brown6ec402b2010-07-28 15:48:59 -07002673#if DEBUG_INJECTION
2674 LOGD("injectInputEvent - Timed out waiting for injection result "
2675 "to become available.");
2676#endif
Jeff Brown7fbdc842010-06-17 20:52:56 -07002677 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
2678 break;
2679 }
2680
Jeff Brown6ec402b2010-07-28 15:48:59 -07002681 mInjectionResultAvailableCondition.waitRelative(mLock, remainingTimeout);
2682 }
2683
2684 if (injectionResult == INPUT_EVENT_INJECTION_SUCCEEDED
2685 && syncMode == INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002686 while (injectionState->pendingForegroundDispatches != 0) {
Jeff Brown6ec402b2010-07-28 15:48:59 -07002687#if DEBUG_INJECTION
Jeff Brown519e0242010-09-15 15:18:56 -07002688 LOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
Jeff Brown01ce2e92010-09-26 22:20:12 -07002689 injectionState->pendingForegroundDispatches);
Jeff Brown6ec402b2010-07-28 15:48:59 -07002690#endif
2691 nsecs_t remainingTimeout = endTime - now();
2692 if (remainingTimeout <= 0) {
2693#if DEBUG_INJECTION
Jeff Brown519e0242010-09-15 15:18:56 -07002694 LOGD("injectInputEvent - Timed out waiting for pending foreground "
Jeff Brown6ec402b2010-07-28 15:48:59 -07002695 "dispatches to finish.");
2696#endif
2697 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
2698 break;
2699 }
2700
2701 mInjectionSyncFinishedCondition.waitRelative(mLock, remainingTimeout);
2702 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07002703 }
2704 }
2705
Jeff Brown01ce2e92010-09-26 22:20:12 -07002706 mAllocator.releaseInjectionState(injectionState);
Jeff Brown7fbdc842010-06-17 20:52:56 -07002707 } // release lock
2708
Jeff Brown6ec402b2010-07-28 15:48:59 -07002709#if DEBUG_INJECTION
2710 LOGD("injectInputEvent - Finished with result %d. "
2711 "injectorPid=%d, injectorUid=%d",
2712 injectionResult, injectorPid, injectorUid);
2713#endif
2714
Jeff Brown7fbdc842010-06-17 20:52:56 -07002715 return injectionResult;
2716}
2717
Jeff Brownb6997262010-10-08 22:31:17 -07002718bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
2719 return injectorUid == 0
2720 || mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
2721}
2722
Jeff Brown7fbdc842010-06-17 20:52:56 -07002723void InputDispatcher::setInjectionResultLocked(EventEntry* entry, int32_t injectionResult) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002724 InjectionState* injectionState = entry->injectionState;
2725 if (injectionState) {
Jeff Brown7fbdc842010-06-17 20:52:56 -07002726#if DEBUG_INJECTION
2727 LOGD("Setting input event injection result to %d. "
2728 "injectorPid=%d, injectorUid=%d",
Jeff Brown01ce2e92010-09-26 22:20:12 -07002729 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
Jeff Brown7fbdc842010-06-17 20:52:56 -07002730#endif
2731
Jeff Brown01ce2e92010-09-26 22:20:12 -07002732 if (injectionState->injectionIsAsync) {
Jeff Brown6ec402b2010-07-28 15:48:59 -07002733 // Log the outcome since the injector did not wait for the injection result.
2734 switch (injectionResult) {
2735 case INPUT_EVENT_INJECTION_SUCCEEDED:
2736 LOGV("Asynchronous input event injection succeeded.");
2737 break;
2738 case INPUT_EVENT_INJECTION_FAILED:
2739 LOGW("Asynchronous input event injection failed.");
2740 break;
2741 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
2742 LOGW("Asynchronous input event injection permission denied.");
2743 break;
2744 case INPUT_EVENT_INJECTION_TIMED_OUT:
2745 LOGW("Asynchronous input event injection timed out.");
2746 break;
2747 }
2748 }
2749
Jeff Brown01ce2e92010-09-26 22:20:12 -07002750 injectionState->injectionResult = injectionResult;
Jeff Brown7fbdc842010-06-17 20:52:56 -07002751 mInjectionResultAvailableCondition.broadcast();
2752 }
2753}
2754
Jeff Brown01ce2e92010-09-26 22:20:12 -07002755void InputDispatcher::incrementPendingForegroundDispatchesLocked(EventEntry* entry) {
2756 InjectionState* injectionState = entry->injectionState;
2757 if (injectionState) {
2758 injectionState->pendingForegroundDispatches += 1;
2759 }
2760}
2761
Jeff Brown519e0242010-09-15 15:18:56 -07002762void InputDispatcher::decrementPendingForegroundDispatchesLocked(EventEntry* entry) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002763 InjectionState* injectionState = entry->injectionState;
2764 if (injectionState) {
2765 injectionState->pendingForegroundDispatches -= 1;
Jeff Brown6ec402b2010-07-28 15:48:59 -07002766
Jeff Brown01ce2e92010-09-26 22:20:12 -07002767 if (injectionState->pendingForegroundDispatches == 0) {
2768 mInjectionSyncFinishedCondition.broadcast();
2769 }
Jeff Brownb88102f2010-09-08 11:49:43 -07002770 }
2771}
2772
Jeff Brown01ce2e92010-09-26 22:20:12 -07002773const InputWindow* InputDispatcher::getWindowLocked(const sp<InputChannel>& inputChannel) {
2774 for (size_t i = 0; i < mWindows.size(); i++) {
2775 const InputWindow* window = & mWindows[i];
2776 if (window->inputChannel == inputChannel) {
2777 return window;
2778 }
2779 }
2780 return NULL;
2781}
2782
Jeff Brownb88102f2010-09-08 11:49:43 -07002783void InputDispatcher::setInputWindows(const Vector<InputWindow>& inputWindows) {
2784#if DEBUG_FOCUS
2785 LOGD("setInputWindows");
2786#endif
2787 { // acquire lock
2788 AutoMutex _l(mLock);
2789
Jeff Brown01ce2e92010-09-26 22:20:12 -07002790 // Clear old window pointers.
Jeff Brownb6997262010-10-08 22:31:17 -07002791 sp<InputChannel> oldFocusedWindowChannel;
2792 if (mFocusedWindow) {
2793 oldFocusedWindowChannel = mFocusedWindow->inputChannel;
2794 mFocusedWindow = NULL;
2795 }
2796
Jeff Brownb88102f2010-09-08 11:49:43 -07002797 mWindows.clear();
Jeff Brown2a95c2a2010-09-16 12:31:46 -07002798
2799 // Loop over new windows and rebuild the necessary window pointers for
2800 // tracking focus and touch.
Jeff Brownb88102f2010-09-08 11:49:43 -07002801 mWindows.appendVector(inputWindows);
2802
2803 size_t numWindows = mWindows.size();
2804 for (size_t i = 0; i < numWindows; i++) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002805 const InputWindow* window = & mWindows.itemAt(i);
Jeff Brownb88102f2010-09-08 11:49:43 -07002806 if (window->hasFocus) {
2807 mFocusedWindow = window;
Jeff Brown01ce2e92010-09-26 22:20:12 -07002808 break;
Jeff Brownb88102f2010-09-08 11:49:43 -07002809 }
2810 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07002811
Jeff Brownb6997262010-10-08 22:31:17 -07002812 if (oldFocusedWindowChannel != NULL) {
2813 if (!mFocusedWindow || oldFocusedWindowChannel != mFocusedWindow->inputChannel) {
2814#if DEBUG_FOCUS
2815 LOGD("Focus left window: %s",
2816 oldFocusedWindowChannel->getName().string());
2817#endif
Jeff Brown524ee642011-03-29 15:11:34 -07002818 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
2819 "focus left window");
2820 synthesizeCancelationEventsForInputChannelLocked(oldFocusedWindowChannel, options);
Jeff Brownb6997262010-10-08 22:31:17 -07002821 oldFocusedWindowChannel.clear();
2822 }
2823 }
2824 if (mFocusedWindow && oldFocusedWindowChannel == NULL) {
2825#if DEBUG_FOCUS
2826 LOGD("Focus entered window: %s",
2827 mFocusedWindow->inputChannel->getName().string());
2828#endif
2829 }
2830
Jeff Brown01ce2e92010-09-26 22:20:12 -07002831 for (size_t i = 0; i < mTouchState.windows.size(); ) {
2832 TouchedWindow& touchedWindow = mTouchState.windows.editItemAt(i);
2833 const InputWindow* window = getWindowLocked(touchedWindow.channel);
2834 if (window) {
2835 touchedWindow.window = window;
2836 i += 1;
2837 } else {
Jeff Brownb6997262010-10-08 22:31:17 -07002838#if DEBUG_FOCUS
2839 LOGD("Touched window was removed: %s", touchedWindow.channel->getName().string());
2840#endif
Jeff Brown524ee642011-03-29 15:11:34 -07002841 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
2842 "touched window was removed");
2843 synthesizeCancelationEventsForInputChannelLocked(touchedWindow.channel, options);
Jeff Brownaf48cae2010-10-15 16:20:51 -07002844 mTouchState.windows.removeAt(i);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002845 }
2846 }
Jeff Brownb88102f2010-09-08 11:49:43 -07002847
Jeff Brownb88102f2010-09-08 11:49:43 -07002848#if DEBUG_FOCUS
Jeff Brownb6997262010-10-08 22:31:17 -07002849 //logDispatchStateLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -07002850#endif
2851 } // release lock
2852
2853 // Wake up poll loop since it may need to make new input dispatching choices.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002854 mLooper->wake();
Jeff Brownb88102f2010-09-08 11:49:43 -07002855}
2856
2857void InputDispatcher::setFocusedApplication(const InputApplication* inputApplication) {
2858#if DEBUG_FOCUS
2859 LOGD("setFocusedApplication");
2860#endif
2861 { // acquire lock
2862 AutoMutex _l(mLock);
2863
2864 releaseFocusedApplicationLocked();
2865
2866 if (inputApplication) {
2867 mFocusedApplicationStorage = *inputApplication;
2868 mFocusedApplication = & mFocusedApplicationStorage;
2869 }
2870
2871#if DEBUG_FOCUS
Jeff Brownb6997262010-10-08 22:31:17 -07002872 //logDispatchStateLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -07002873#endif
2874 } // release lock
2875
2876 // Wake up poll loop since it may need to make new input dispatching choices.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002877 mLooper->wake();
Jeff Brownb88102f2010-09-08 11:49:43 -07002878}
2879
2880void InputDispatcher::releaseFocusedApplicationLocked() {
2881 if (mFocusedApplication) {
2882 mFocusedApplication = NULL;
Jeff Brown928e0542011-01-10 11:17:36 -08002883 mFocusedApplicationStorage.inputApplicationHandle.clear();
Jeff Brownb88102f2010-09-08 11:49:43 -07002884 }
2885}
2886
2887void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
2888#if DEBUG_FOCUS
2889 LOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
2890#endif
2891
2892 bool changed;
2893 { // acquire lock
2894 AutoMutex _l(mLock);
2895
2896 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
Jeff Brown120a4592010-10-27 18:43:51 -07002897 if (mDispatchFrozen && !frozen) {
Jeff Brownb88102f2010-09-08 11:49:43 -07002898 resetANRTimeoutsLocked();
2899 }
2900
Jeff Brown120a4592010-10-27 18:43:51 -07002901 if (mDispatchEnabled && !enabled) {
2902 resetAndDropEverythingLocked("dispatcher is being disabled");
2903 }
2904
Jeff Brownb88102f2010-09-08 11:49:43 -07002905 mDispatchEnabled = enabled;
2906 mDispatchFrozen = frozen;
2907 changed = true;
2908 } else {
2909 changed = false;
2910 }
2911
2912#if DEBUG_FOCUS
Jeff Brownb6997262010-10-08 22:31:17 -07002913 //logDispatchStateLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -07002914#endif
2915 } // release lock
2916
2917 if (changed) {
2918 // Wake up poll loop since it may need to make new input dispatching choices.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002919 mLooper->wake();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002920 }
2921}
2922
Jeff Browne6504122010-09-27 14:52:15 -07002923bool InputDispatcher::transferTouchFocus(const sp<InputChannel>& fromChannel,
2924 const sp<InputChannel>& toChannel) {
2925#if DEBUG_FOCUS
2926 LOGD("transferTouchFocus: fromChannel=%s, toChannel=%s",
2927 fromChannel->getName().string(), toChannel->getName().string());
2928#endif
2929 { // acquire lock
2930 AutoMutex _l(mLock);
2931
2932 const InputWindow* fromWindow = getWindowLocked(fromChannel);
2933 const InputWindow* toWindow = getWindowLocked(toChannel);
2934 if (! fromWindow || ! toWindow) {
2935#if DEBUG_FOCUS
2936 LOGD("Cannot transfer focus because from or to window not found.");
2937#endif
2938 return false;
2939 }
2940 if (fromWindow == toWindow) {
2941#if DEBUG_FOCUS
2942 LOGD("Trivial transfer to same window.");
2943#endif
2944 return true;
2945 }
2946
2947 bool found = false;
2948 for (size_t i = 0; i < mTouchState.windows.size(); i++) {
2949 const TouchedWindow& touchedWindow = mTouchState.windows[i];
2950 if (touchedWindow.window == fromWindow) {
2951 int32_t oldTargetFlags = touchedWindow.targetFlags;
2952 BitSet32 pointerIds = touchedWindow.pointerIds;
2953
2954 mTouchState.windows.removeAt(i);
2955
Jeff Brown46e75292010-11-10 16:53:45 -08002956 int32_t newTargetFlags = oldTargetFlags
2957 & (InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_SPLIT);
Jeff Browne6504122010-09-27 14:52:15 -07002958 mTouchState.addOrUpdateWindow(toWindow, newTargetFlags, pointerIds);
2959
2960 found = true;
2961 break;
2962 }
2963 }
2964
2965 if (! found) {
2966#if DEBUG_FOCUS
2967 LOGD("Focus transfer failed because from window did not have focus.");
2968#endif
2969 return false;
2970 }
2971
Jeff Brown9c9f1a32010-10-11 18:32:20 -07002972 ssize_t fromConnectionIndex = getConnectionIndexLocked(fromChannel);
2973 ssize_t toConnectionIndex = getConnectionIndexLocked(toChannel);
2974 if (fromConnectionIndex >= 0 && toConnectionIndex >= 0) {
2975 sp<Connection> fromConnection = mConnectionsByReceiveFd.valueAt(fromConnectionIndex);
2976 sp<Connection> toConnection = mConnectionsByReceiveFd.valueAt(toConnectionIndex);
2977
2978 fromConnection->inputState.copyPointerStateTo(toConnection->inputState);
Jeff Brown524ee642011-03-29 15:11:34 -07002979 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Jeff Brown9c9f1a32010-10-11 18:32:20 -07002980 "transferring touch focus from this window to another window");
Jeff Brown524ee642011-03-29 15:11:34 -07002981 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Jeff Brown9c9f1a32010-10-11 18:32:20 -07002982 }
2983
Jeff Browne6504122010-09-27 14:52:15 -07002984#if DEBUG_FOCUS
2985 logDispatchStateLocked();
2986#endif
2987 } // release lock
2988
2989 // Wake up poll loop since it may need to make new input dispatching choices.
2990 mLooper->wake();
2991 return true;
2992}
2993
Jeff Brown120a4592010-10-27 18:43:51 -07002994void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
2995#if DEBUG_FOCUS
2996 LOGD("Resetting and dropping all events (%s).", reason);
2997#endif
2998
Jeff Brown524ee642011-03-29 15:11:34 -07002999 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
3000 synthesizeCancelationEventsForAllConnectionsLocked(options);
Jeff Brown120a4592010-10-27 18:43:51 -07003001
3002 resetKeyRepeatLocked();
3003 releasePendingEventLocked();
3004 drainInboundQueueLocked();
3005 resetTargetsLocked();
3006
3007 mTouchState.reset();
3008}
3009
Jeff Brownb88102f2010-09-08 11:49:43 -07003010void InputDispatcher::logDispatchStateLocked() {
3011 String8 dump;
3012 dumpDispatchStateLocked(dump);
Jeff Brown2a95c2a2010-09-16 12:31:46 -07003013
3014 char* text = dump.lockBuffer(dump.size());
3015 char* start = text;
3016 while (*start != '\0') {
3017 char* end = strchr(start, '\n');
3018 if (*end == '\n') {
3019 *(end++) = '\0';
3020 }
3021 LOGD("%s", start);
3022 start = end;
3023 }
Jeff Brownb88102f2010-09-08 11:49:43 -07003024}
3025
3026void InputDispatcher::dumpDispatchStateLocked(String8& dump) {
Jeff Brownf2f487182010-10-01 17:46:21 -07003027 dump.appendFormat(INDENT "DispatchEnabled: %d\n", mDispatchEnabled);
3028 dump.appendFormat(INDENT "DispatchFrozen: %d\n", mDispatchFrozen);
Jeff Brownb88102f2010-09-08 11:49:43 -07003029
3030 if (mFocusedApplication) {
Jeff Brownf2f487182010-10-01 17:46:21 -07003031 dump.appendFormat(INDENT "FocusedApplication: name='%s', dispatchingTimeout=%0.3fms\n",
Jeff Brownb88102f2010-09-08 11:49:43 -07003032 mFocusedApplication->name.string(),
3033 mFocusedApplication->dispatchingTimeout / 1000000.0);
3034 } else {
Jeff Brownf2f487182010-10-01 17:46:21 -07003035 dump.append(INDENT "FocusedApplication: <null>\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003036 }
Jeff Brownf2f487182010-10-01 17:46:21 -07003037 dump.appendFormat(INDENT "FocusedWindow: name='%s'\n",
Jeff Brown2a95c2a2010-09-16 12:31:46 -07003038 mFocusedWindow != NULL ? mFocusedWindow->name.string() : "<null>");
Jeff Brownf2f487182010-10-01 17:46:21 -07003039
3040 dump.appendFormat(INDENT "TouchDown: %s\n", toString(mTouchState.down));
3041 dump.appendFormat(INDENT "TouchSplit: %s\n", toString(mTouchState.split));
Jeff Brown95712852011-01-04 19:41:59 -08003042 dump.appendFormat(INDENT "TouchDeviceId: %d\n", mTouchState.deviceId);
Jeff Brown58a2da82011-01-25 16:02:22 -08003043 dump.appendFormat(INDENT "TouchSource: 0x%08x\n", mTouchState.source);
Jeff Brownf2f487182010-10-01 17:46:21 -07003044 if (!mTouchState.windows.isEmpty()) {
3045 dump.append(INDENT "TouchedWindows:\n");
3046 for (size_t i = 0; i < mTouchState.windows.size(); i++) {
3047 const TouchedWindow& touchedWindow = mTouchState.windows[i];
3048 dump.appendFormat(INDENT2 "%d: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
3049 i, touchedWindow.window->name.string(), touchedWindow.pointerIds.value,
3050 touchedWindow.targetFlags);
3051 }
3052 } else {
3053 dump.append(INDENT "TouchedWindows: <none>\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003054 }
3055
Jeff Brownf2f487182010-10-01 17:46:21 -07003056 if (!mWindows.isEmpty()) {
3057 dump.append(INDENT "Windows:\n");
3058 for (size_t i = 0; i < mWindows.size(); i++) {
3059 const InputWindow& window = mWindows[i];
3060 dump.appendFormat(INDENT2 "%d: name='%s', paused=%s, hasFocus=%s, hasWallpaper=%s, "
3061 "visible=%s, canReceiveKeys=%s, flags=0x%08x, type=0x%08x, layer=%d, "
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003062 "frame=[%d,%d][%d,%d], scale=%f, "
Jeff Brownfbf09772011-01-16 14:06:57 -08003063 "touchableRegion=",
Jeff Brownf2f487182010-10-01 17:46:21 -07003064 i, window.name.string(),
3065 toString(window.paused),
3066 toString(window.hasFocus),
3067 toString(window.hasWallpaper),
3068 toString(window.visible),
3069 toString(window.canReceiveKeys),
3070 window.layoutParamsFlags, window.layoutParamsType,
3071 window.layer,
3072 window.frameLeft, window.frameTop,
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003073 window.frameRight, window.frameBottom,
3074 window.scaleFactor);
Jeff Brownfbf09772011-01-16 14:06:57 -08003075 dumpRegion(dump, window.touchableRegion);
3076 dump.appendFormat(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%0.3fms\n",
Jeff Brownf2f487182010-10-01 17:46:21 -07003077 window.ownerPid, window.ownerUid,
3078 window.dispatchingTimeout / 1000000.0);
3079 }
3080 } else {
3081 dump.append(INDENT "Windows: <none>\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003082 }
3083
Jeff Brownf2f487182010-10-01 17:46:21 -07003084 if (!mMonitoringChannels.isEmpty()) {
3085 dump.append(INDENT "MonitoringChannels:\n");
3086 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
3087 const sp<InputChannel>& channel = mMonitoringChannels[i];
3088 dump.appendFormat(INDENT2 "%d: '%s'\n", i, channel->getName().string());
3089 }
3090 } else {
3091 dump.append(INDENT "MonitoringChannels: <none>\n");
3092 }
Jeff Brown519e0242010-09-15 15:18:56 -07003093
Jeff Brownf2f487182010-10-01 17:46:21 -07003094 dump.appendFormat(INDENT "InboundQueue: length=%u\n", mInboundQueue.count());
3095
3096 if (!mActiveConnections.isEmpty()) {
3097 dump.append(INDENT "ActiveConnections:\n");
3098 for (size_t i = 0; i < mActiveConnections.size(); i++) {
3099 const Connection* connection = mActiveConnections[i];
Jeff Brown76860e32010-10-25 17:37:46 -07003100 dump.appendFormat(INDENT2 "%d: '%s', status=%s, outboundQueueLength=%u, "
Jeff Brownb6997262010-10-08 22:31:17 -07003101 "inputState.isNeutral=%s\n",
Jeff Brownf2f487182010-10-01 17:46:21 -07003102 i, connection->getInputChannelName(), connection->getStatusLabel(),
3103 connection->outboundQueue.count(),
Jeff Brownb6997262010-10-08 22:31:17 -07003104 toString(connection->inputState.isNeutral()));
Jeff Brownf2f487182010-10-01 17:46:21 -07003105 }
3106 } else {
3107 dump.append(INDENT "ActiveConnections: <none>\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003108 }
3109
3110 if (isAppSwitchPendingLocked()) {
Jeff Brownf2f487182010-10-01 17:46:21 -07003111 dump.appendFormat(INDENT "AppSwitch: pending, due in %01.1fms\n",
Jeff Brownb88102f2010-09-08 11:49:43 -07003112 (mAppSwitchDueTime - now()) / 1000000.0);
3113 } else {
Jeff Brownf2f487182010-10-01 17:46:21 -07003114 dump.append(INDENT "AppSwitch: not pending\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003115 }
3116}
3117
Jeff Brown928e0542011-01-10 11:17:36 -08003118status_t InputDispatcher::registerInputChannel(const sp<InputChannel>& inputChannel,
3119 const sp<InputWindowHandle>& inputWindowHandle, bool monitor) {
Jeff Brown9c3cda02010-06-15 01:31:58 -07003120#if DEBUG_REGISTRATION
Jeff Brownb88102f2010-09-08 11:49:43 -07003121 LOGD("channel '%s' ~ registerInputChannel - monitor=%s", inputChannel->getName().string(),
3122 toString(monitor));
Jeff Brown9c3cda02010-06-15 01:31:58 -07003123#endif
3124
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003125 { // acquire lock
3126 AutoMutex _l(mLock);
3127
Jeff Brown519e0242010-09-15 15:18:56 -07003128 if (getConnectionIndexLocked(inputChannel) >= 0) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003129 LOGW("Attempted to register already registered input channel '%s'",
3130 inputChannel->getName().string());
3131 return BAD_VALUE;
3132 }
3133
Jeff Brown928e0542011-01-10 11:17:36 -08003134 sp<Connection> connection = new Connection(inputChannel, inputWindowHandle);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003135 status_t status = connection->initialize();
3136 if (status) {
3137 LOGE("Failed to initialize input publisher for input channel '%s', status=%d",
3138 inputChannel->getName().string(), status);
3139 return status;
3140 }
3141
Jeff Brown2cbecea2010-08-17 15:59:26 -07003142 int32_t receiveFd = inputChannel->getReceivePipeFd();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003143 mConnectionsByReceiveFd.add(receiveFd, connection);
Jeff Brown9c3cda02010-06-15 01:31:58 -07003144
Jeff Brownb88102f2010-09-08 11:49:43 -07003145 if (monitor) {
3146 mMonitoringChannels.push(inputChannel);
3147 }
3148
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07003149 mLooper->addFd(receiveFd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
Jeff Brown2cbecea2010-08-17 15:59:26 -07003150
Jeff Brown9c3cda02010-06-15 01:31:58 -07003151 runCommandsLockedInterruptible();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003152 } // release lock
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003153 return OK;
3154}
3155
3156status_t InputDispatcher::unregisterInputChannel(const sp<InputChannel>& inputChannel) {
Jeff Brown9c3cda02010-06-15 01:31:58 -07003157#if DEBUG_REGISTRATION
Jeff Brown349703e2010-06-22 01:27:15 -07003158 LOGD("channel '%s' ~ unregisterInputChannel", inputChannel->getName().string());
Jeff Brown9c3cda02010-06-15 01:31:58 -07003159#endif
3160
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003161 { // acquire lock
3162 AutoMutex _l(mLock);
3163
Jeff Brown519e0242010-09-15 15:18:56 -07003164 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003165 if (connectionIndex < 0) {
3166 LOGW("Attempted to unregister already unregistered input channel '%s'",
3167 inputChannel->getName().string());
3168 return BAD_VALUE;
3169 }
3170
3171 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
3172 mConnectionsByReceiveFd.removeItemsAt(connectionIndex);
3173
3174 connection->status = Connection::STATUS_ZOMBIE;
3175
Jeff Brownb88102f2010-09-08 11:49:43 -07003176 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
3177 if (mMonitoringChannels[i] == inputChannel) {
3178 mMonitoringChannels.removeAt(i);
3179 break;
3180 }
3181 }
3182
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07003183 mLooper->removeFd(inputChannel->getReceivePipeFd());
Jeff Brown2cbecea2010-08-17 15:59:26 -07003184
Jeff Brown7fbdc842010-06-17 20:52:56 -07003185 nsecs_t currentTime = now();
Jeff Brownb6997262010-10-08 22:31:17 -07003186 abortBrokenDispatchCycleLocked(currentTime, connection);
Jeff Brown9c3cda02010-06-15 01:31:58 -07003187
3188 runCommandsLockedInterruptible();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003189 } // release lock
3190
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003191 // Wake the poll loop because removing the connection may have changed the current
3192 // synchronization state.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07003193 mLooper->wake();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003194 return OK;
3195}
3196
Jeff Brown519e0242010-09-15 15:18:56 -07003197ssize_t InputDispatcher::getConnectionIndexLocked(const sp<InputChannel>& inputChannel) {
Jeff Brown2cbecea2010-08-17 15:59:26 -07003198 ssize_t connectionIndex = mConnectionsByReceiveFd.indexOfKey(inputChannel->getReceivePipeFd());
3199 if (connectionIndex >= 0) {
3200 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
3201 if (connection->inputChannel.get() == inputChannel.get()) {
3202 return connectionIndex;
3203 }
3204 }
3205
3206 return -1;
3207}
3208
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003209void InputDispatcher::activateConnectionLocked(Connection* connection) {
3210 for (size_t i = 0; i < mActiveConnections.size(); i++) {
3211 if (mActiveConnections.itemAt(i) == connection) {
3212 return;
3213 }
3214 }
3215 mActiveConnections.add(connection);
3216}
3217
3218void InputDispatcher::deactivateConnectionLocked(Connection* connection) {
3219 for (size_t i = 0; i < mActiveConnections.size(); i++) {
3220 if (mActiveConnections.itemAt(i) == connection) {
3221 mActiveConnections.removeAt(i);
3222 return;
3223 }
3224 }
3225}
3226
Jeff Brown9c3cda02010-06-15 01:31:58 -07003227void InputDispatcher::onDispatchCycleStartedLocked(
Jeff Brown7fbdc842010-06-17 20:52:56 -07003228 nsecs_t currentTime, const sp<Connection>& connection) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003229}
3230
Jeff Brown9c3cda02010-06-15 01:31:58 -07003231void InputDispatcher::onDispatchCycleFinishedLocked(
Jeff Brown3915bb82010-11-05 15:02:16 -07003232 nsecs_t currentTime, const sp<Connection>& connection, bool handled) {
3233 CommandEntry* commandEntry = postCommandLocked(
3234 & InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
3235 commandEntry->connection = connection;
3236 commandEntry->handled = handled;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003237}
3238
Jeff Brown9c3cda02010-06-15 01:31:58 -07003239void InputDispatcher::onDispatchCycleBrokenLocked(
Jeff Brown7fbdc842010-06-17 20:52:56 -07003240 nsecs_t currentTime, const sp<Connection>& connection) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003241 LOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
3242 connection->getInputChannelName());
3243
Jeff Brown9c3cda02010-06-15 01:31:58 -07003244 CommandEntry* commandEntry = postCommandLocked(
3245 & InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
Jeff Brown7fbdc842010-06-17 20:52:56 -07003246 commandEntry->connection = connection;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003247}
3248
Jeff Brown519e0242010-09-15 15:18:56 -07003249void InputDispatcher::onANRLocked(
3250 nsecs_t currentTime, const InputApplication* application, const InputWindow* window,
3251 nsecs_t eventTime, nsecs_t waitStartTime) {
3252 LOGI("Application is not responding: %s. "
3253 "%01.1fms since event, %01.1fms since wait started",
3254 getApplicationWindowLabelLocked(application, window).string(),
3255 (currentTime - eventTime) / 1000000.0,
3256 (currentTime - waitStartTime) / 1000000.0);
3257
3258 CommandEntry* commandEntry = postCommandLocked(
3259 & InputDispatcher::doNotifyANRLockedInterruptible);
3260 if (application) {
Jeff Brown928e0542011-01-10 11:17:36 -08003261 commandEntry->inputApplicationHandle = application->inputApplicationHandle;
Jeff Brown519e0242010-09-15 15:18:56 -07003262 }
3263 if (window) {
Jeff Brown928e0542011-01-10 11:17:36 -08003264 commandEntry->inputWindowHandle = window->inputWindowHandle;
Jeff Brown519e0242010-09-15 15:18:56 -07003265 commandEntry->inputChannel = window->inputChannel;
3266 }
3267}
3268
Jeff Brownb88102f2010-09-08 11:49:43 -07003269void InputDispatcher::doNotifyConfigurationChangedInterruptible(
3270 CommandEntry* commandEntry) {
3271 mLock.unlock();
3272
3273 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
3274
3275 mLock.lock();
3276}
3277
Jeff Brown9c3cda02010-06-15 01:31:58 -07003278void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(
3279 CommandEntry* commandEntry) {
Jeff Brown7fbdc842010-06-17 20:52:56 -07003280 sp<Connection> connection = commandEntry->connection;
Jeff Brown9c3cda02010-06-15 01:31:58 -07003281
Jeff Brown7fbdc842010-06-17 20:52:56 -07003282 if (connection->status != Connection::STATUS_ZOMBIE) {
3283 mLock.unlock();
Jeff Brown9c3cda02010-06-15 01:31:58 -07003284
Jeff Brown928e0542011-01-10 11:17:36 -08003285 mPolicy->notifyInputChannelBroken(connection->inputWindowHandle);
Jeff Brown7fbdc842010-06-17 20:52:56 -07003286
3287 mLock.lock();
3288 }
Jeff Brown9c3cda02010-06-15 01:31:58 -07003289}
3290
Jeff Brown519e0242010-09-15 15:18:56 -07003291void InputDispatcher::doNotifyANRLockedInterruptible(
Jeff Brown9c3cda02010-06-15 01:31:58 -07003292 CommandEntry* commandEntry) {
Jeff Brown519e0242010-09-15 15:18:56 -07003293 mLock.unlock();
Jeff Brown9c3cda02010-06-15 01:31:58 -07003294
Jeff Brown519e0242010-09-15 15:18:56 -07003295 nsecs_t newTimeout = mPolicy->notifyANR(
Jeff Brown928e0542011-01-10 11:17:36 -08003296 commandEntry->inputApplicationHandle, commandEntry->inputWindowHandle);
Jeff Brown9c3cda02010-06-15 01:31:58 -07003297
Jeff Brown519e0242010-09-15 15:18:56 -07003298 mLock.lock();
Jeff Brown7fbdc842010-06-17 20:52:56 -07003299
Jeff Brown519e0242010-09-15 15:18:56 -07003300 resumeAfterTargetsNotReadyTimeoutLocked(newTimeout, commandEntry->inputChannel);
Jeff Brown9c3cda02010-06-15 01:31:58 -07003301}
3302
Jeff Brownb88102f2010-09-08 11:49:43 -07003303void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
3304 CommandEntry* commandEntry) {
3305 KeyEntry* entry = commandEntry->keyEntry;
Jeff Brown1f245102010-11-18 20:53:46 -08003306
3307 KeyEvent event;
3308 initializeKeyEvent(&event, entry);
Jeff Brownb88102f2010-09-08 11:49:43 -07003309
3310 mLock.unlock();
3311
Jeff Brown928e0542011-01-10 11:17:36 -08003312 bool consumed = mPolicy->interceptKeyBeforeDispatching(commandEntry->inputWindowHandle,
Jeff Brown1f245102010-11-18 20:53:46 -08003313 &event, entry->policyFlags);
Jeff Brownb88102f2010-09-08 11:49:43 -07003314
3315 mLock.lock();
3316
3317 entry->interceptKeyResult = consumed
3318 ? KeyEntry::INTERCEPT_KEY_RESULT_SKIP
3319 : KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
3320 mAllocator.releaseKeyEntry(entry);
3321}
3322
Jeff Brown3915bb82010-11-05 15:02:16 -07003323void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(
3324 CommandEntry* commandEntry) {
3325 sp<Connection> connection = commandEntry->connection;
3326 bool handled = commandEntry->handled;
3327
Jeff Brown49ed71d2010-12-06 17:13:33 -08003328 if (!connection->outboundQueue.isEmpty()) {
Jeff Brown3915bb82010-11-05 15:02:16 -07003329 DispatchEntry* dispatchEntry = connection->outboundQueue.headSentinel.next;
3330 if (dispatchEntry->inProgress
Jeff Brown3915bb82010-11-05 15:02:16 -07003331 && dispatchEntry->eventEntry->type == EventEntry::TYPE_KEY) {
3332 KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry);
Jeff Brown49ed71d2010-12-06 17:13:33 -08003333 if (!(keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK)) {
Jeff Brown524ee642011-03-29 15:11:34 -07003334 // Get the fallback key state.
3335 // Clear it out after dispatching the UP.
3336 int32_t originalKeyCode = keyEntry->keyCode;
3337 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
3338 if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
3339 connection->inputState.removeFallbackKey(originalKeyCode);
3340 }
3341
3342 if (handled || !dispatchEntry->hasForegroundTarget()) {
3343 // If the application handles the original key for which we previously
3344 // generated a fallback or if the window is not a foreground window,
3345 // then cancel the associated fallback key, if any.
3346 if (fallbackKeyCode != -1) {
3347 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
3348 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
3349 "application handled the original non-fallback key "
3350 "or is no longer a foreground target, "
3351 "canceling previously dispatched fallback key");
3352 options.keyCode = fallbackKeyCode;
3353 synthesizeCancelationEventsForConnectionLocked(connection, options);
3354 }
3355 connection->inputState.removeFallbackKey(originalKeyCode);
3356 }
Jeff Brown49ed71d2010-12-06 17:13:33 -08003357 } else {
Jeff Brownbfaf3b92011-02-22 15:00:50 -08003358 // If the application did not handle a non-fallback key, first check
Jeff Brown524ee642011-03-29 15:11:34 -07003359 // that we are in a good state to perform unhandled key event processing
3360 // Then ask the policy what to do with it.
3361 bool initialDown = keyEntry->action == AKEY_EVENT_ACTION_DOWN
3362 && keyEntry->repeatCount == 0;
3363 if (fallbackKeyCode == -1 && !initialDown) {
Jeff Brownbfaf3b92011-02-22 15:00:50 -08003364#if DEBUG_OUTBOUND_EVENT_DETAILS
Jeff Brown524ee642011-03-29 15:11:34 -07003365 LOGD("Unhandled key event: Skipping unhandled key event processing "
3366 "since this is not an initial down. "
3367 "keyCode=%d, action=%d, repeatCount=%d",
3368 originalKeyCode, keyEntry->action, keyEntry->repeatCount);
Jeff Brownbfaf3b92011-02-22 15:00:50 -08003369#endif
Jeff Brown524ee642011-03-29 15:11:34 -07003370 goto SkipFallback;
Jeff Brownbfaf3b92011-02-22 15:00:50 -08003371 }
3372
Jeff Brown524ee642011-03-29 15:11:34 -07003373 // Dispatch the unhandled key to the policy.
Jeff Brownbfaf3b92011-02-22 15:00:50 -08003374#if DEBUG_OUTBOUND_EVENT_DETAILS
3375 LOGD("Unhandled key event: Asking policy to perform fallback action. "
3376 "keyCode=%d, action=%d, repeatCount=%d",
3377 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount);
3378#endif
Jeff Brown49ed71d2010-12-06 17:13:33 -08003379 KeyEvent event;
3380 initializeKeyEvent(&event, keyEntry);
Jeff Brown3915bb82010-11-05 15:02:16 -07003381
Jeff Brown49ed71d2010-12-06 17:13:33 -08003382 mLock.unlock();
Jeff Brown3915bb82010-11-05 15:02:16 -07003383
Jeff Brown928e0542011-01-10 11:17:36 -08003384 bool fallback = mPolicy->dispatchUnhandledKey(connection->inputWindowHandle,
Jeff Brown49ed71d2010-12-06 17:13:33 -08003385 &event, keyEntry->policyFlags, &event);
Jeff Brown3915bb82010-11-05 15:02:16 -07003386
Jeff Brown49ed71d2010-12-06 17:13:33 -08003387 mLock.lock();
3388
Jeff Brown00045a72010-12-09 18:10:30 -08003389 if (connection->status != Connection::STATUS_NORMAL) {
Jeff Brown524ee642011-03-29 15:11:34 -07003390 connection->inputState.removeFallbackKey(originalKeyCode);
Jeff Brown00045a72010-12-09 18:10:30 -08003391 return;
3392 }
3393
3394 assert(connection->outboundQueue.headSentinel.next == dispatchEntry);
3395
Jeff Brown524ee642011-03-29 15:11:34 -07003396 // Latch the fallback keycode for this key on an initial down.
3397 // The fallback keycode cannot change at any other point in the lifecycle.
3398 if (initialDown) {
3399 if (fallback) {
3400 fallbackKeyCode = event.getKeyCode();
3401 } else {
3402 fallbackKeyCode = AKEYCODE_UNKNOWN;
3403 }
3404 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
3405 }
3406
3407 assert(fallbackKeyCode != -1);
3408
3409 // Cancel the fallback key if the policy decides not to send it anymore.
3410 // We will continue to dispatch the key to the policy but we will no
3411 // longer dispatch a fallback key to the application.
3412 if (fallbackKeyCode != AKEYCODE_UNKNOWN
3413 && (!fallback || fallbackKeyCode != event.getKeyCode())) {
3414#if DEBUG_OUTBOUND_EVENT_DETAILS
3415 if (fallback) {
3416 LOGD("Unhandled key event: Policy requested to send key %d"
3417 "as a fallback for %d, but on the DOWN it had requested "
3418 "to send %d instead. Fallback canceled.",
3419 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
3420 } else {
3421 LOGD("Unhandled key event: Policy did not request fallback for %d,"
3422 "but on the DOWN it had requested to send %d. "
3423 "Fallback canceled.",
3424 originalKeyCode, fallbackKeyCode);
3425 }
3426#endif
3427
3428 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
3429 "canceling fallback, policy no longer desires it");
3430 options.keyCode = fallbackKeyCode;
3431 synthesizeCancelationEventsForConnectionLocked(connection, options);
3432
3433 fallback = false;
3434 fallbackKeyCode = AKEYCODE_UNKNOWN;
3435 if (keyEntry->action != AKEY_EVENT_ACTION_UP) {
3436 connection->inputState.setFallbackKey(originalKeyCode,
3437 fallbackKeyCode);
3438 }
3439 }
3440
3441#if DEBUG_OUTBOUND_EVENT_DETAILS
3442 {
3443 String8 msg;
3444 const KeyedVector<int32_t, int32_t>& fallbackKeys =
3445 connection->inputState.getFallbackKeys();
3446 for (size_t i = 0; i < fallbackKeys.size(); i++) {
3447 msg.appendFormat(", %d->%d", fallbackKeys.keyAt(i),
3448 fallbackKeys.valueAt(i));
3449 }
3450 LOGD("Unhandled key event: %d currently tracked fallback keys%s.",
3451 fallbackKeys.size(), msg.string());
3452 }
3453#endif
3454
Jeff Brown49ed71d2010-12-06 17:13:33 -08003455 if (fallback) {
3456 // Restart the dispatch cycle using the fallback key.
3457 keyEntry->eventTime = event.getEventTime();
3458 keyEntry->deviceId = event.getDeviceId();
3459 keyEntry->source = event.getSource();
3460 keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
Jeff Brown524ee642011-03-29 15:11:34 -07003461 keyEntry->keyCode = fallbackKeyCode;
Jeff Brown49ed71d2010-12-06 17:13:33 -08003462 keyEntry->scanCode = event.getScanCode();
3463 keyEntry->metaState = event.getMetaState();
3464 keyEntry->repeatCount = event.getRepeatCount();
3465 keyEntry->downTime = event.getDownTime();
3466 keyEntry->syntheticRepeat = false;
3467
Jeff Brownbfaf3b92011-02-22 15:00:50 -08003468#if DEBUG_OUTBOUND_EVENT_DETAILS
3469 LOGD("Unhandled key event: Dispatching fallback key. "
Jeff Brown524ee642011-03-29 15:11:34 -07003470 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
3471 originalKeyCode, fallbackKeyCode, keyEntry->metaState);
Jeff Brownbfaf3b92011-02-22 15:00:50 -08003472#endif
3473
Jeff Brown49ed71d2010-12-06 17:13:33 -08003474 dispatchEntry->inProgress = false;
3475 startDispatchCycleLocked(now(), connection);
3476 return;
Jeff Brown524ee642011-03-29 15:11:34 -07003477 } else {
3478#if DEBUG_OUTBOUND_EVENT_DETAILS
3479 LOGD("Unhandled key event: No fallback key.");
3480#endif
Jeff Brown49ed71d2010-12-06 17:13:33 -08003481 }
3482 }
3483 }
Jeff Brown3915bb82010-11-05 15:02:16 -07003484 }
3485 }
3486
Jeff Brownbfaf3b92011-02-22 15:00:50 -08003487SkipFallback:
Jeff Brown3915bb82010-11-05 15:02:16 -07003488 startNextDispatchCycleLocked(now(), connection);
3489}
3490
Jeff Brownb88102f2010-09-08 11:49:43 -07003491void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
3492 mLock.unlock();
3493
Jeff Brown01ce2e92010-09-26 22:20:12 -07003494 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
Jeff Brownb88102f2010-09-08 11:49:43 -07003495
3496 mLock.lock();
3497}
3498
Jeff Brown3915bb82010-11-05 15:02:16 -07003499void InputDispatcher::initializeKeyEvent(KeyEvent* event, const KeyEntry* entry) {
3500 event->initialize(entry->deviceId, entry->source, entry->action, entry->flags,
3501 entry->keyCode, entry->scanCode, entry->metaState, entry->repeatCount,
3502 entry->downTime, entry->eventTime);
3503}
3504
Jeff Brown519e0242010-09-15 15:18:56 -07003505void InputDispatcher::updateDispatchStatisticsLocked(nsecs_t currentTime, const EventEntry* entry,
3506 int32_t injectionResult, nsecs_t timeSpentWaitingForApplication) {
3507 // TODO Write some statistics about how long we spend waiting.
Jeff Brownb88102f2010-09-08 11:49:43 -07003508}
3509
3510void InputDispatcher::dump(String8& dump) {
Jeff Brownf2f487182010-10-01 17:46:21 -07003511 dump.append("Input Dispatcher State:\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003512 dumpDispatchStateLocked(dump);
3513}
3514
Jeff Brown9c3cda02010-06-15 01:31:58 -07003515
Jeff Brown519e0242010-09-15 15:18:56 -07003516// --- InputDispatcher::Queue ---
3517
3518template <typename T>
3519uint32_t InputDispatcher::Queue<T>::count() const {
3520 uint32_t result = 0;
3521 for (const T* entry = headSentinel.next; entry != & tailSentinel; entry = entry->next) {
3522 result += 1;
3523 }
3524 return result;
3525}
3526
3527
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003528// --- InputDispatcher::Allocator ---
3529
3530InputDispatcher::Allocator::Allocator() {
3531}
3532
Jeff Brown01ce2e92010-09-26 22:20:12 -07003533InputDispatcher::InjectionState*
3534InputDispatcher::Allocator::obtainInjectionState(int32_t injectorPid, int32_t injectorUid) {
3535 InjectionState* injectionState = mInjectionStatePool.alloc();
3536 injectionState->refCount = 1;
3537 injectionState->injectorPid = injectorPid;
3538 injectionState->injectorUid = injectorUid;
3539 injectionState->injectionIsAsync = false;
3540 injectionState->injectionResult = INPUT_EVENT_INJECTION_PENDING;
3541 injectionState->pendingForegroundDispatches = 0;
3542 return injectionState;
3543}
3544
Jeff Brown7fbdc842010-06-17 20:52:56 -07003545void InputDispatcher::Allocator::initializeEventEntry(EventEntry* entry, int32_t type,
Jeff Brownb6997262010-10-08 22:31:17 -07003546 nsecs_t eventTime, uint32_t policyFlags) {
Jeff Brown7fbdc842010-06-17 20:52:56 -07003547 entry->type = type;
3548 entry->refCount = 1;
3549 entry->dispatchInProgress = false;
Christopher Tatee91a5db2010-06-23 16:50:30 -07003550 entry->eventTime = eventTime;
Jeff Brownb6997262010-10-08 22:31:17 -07003551 entry->policyFlags = policyFlags;
Jeff Brown01ce2e92010-09-26 22:20:12 -07003552 entry->injectionState = NULL;
3553}
3554
3555void InputDispatcher::Allocator::releaseEventEntryInjectionState(EventEntry* entry) {
3556 if (entry->injectionState) {
3557 releaseInjectionState(entry->injectionState);
3558 entry->injectionState = NULL;
3559 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07003560}
3561
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003562InputDispatcher::ConfigurationChangedEntry*
Jeff Brown7fbdc842010-06-17 20:52:56 -07003563InputDispatcher::Allocator::obtainConfigurationChangedEntry(nsecs_t eventTime) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003564 ConfigurationChangedEntry* entry = mConfigurationChangeEntryPool.alloc();
Jeff Brownb6997262010-10-08 22:31:17 -07003565 initializeEventEntry(entry, EventEntry::TYPE_CONFIGURATION_CHANGED, eventTime, 0);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003566 return entry;
3567}
3568
Jeff Brown7fbdc842010-06-17 20:52:56 -07003569InputDispatcher::KeyEntry* InputDispatcher::Allocator::obtainKeyEntry(nsecs_t eventTime,
Jeff Brown58a2da82011-01-25 16:02:22 -08003570 int32_t deviceId, uint32_t source, uint32_t policyFlags, int32_t action,
Jeff Brown7fbdc842010-06-17 20:52:56 -07003571 int32_t flags, int32_t keyCode, int32_t scanCode, int32_t metaState,
3572 int32_t repeatCount, nsecs_t downTime) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003573 KeyEntry* entry = mKeyEntryPool.alloc();
Jeff Brownb6997262010-10-08 22:31:17 -07003574 initializeEventEntry(entry, EventEntry::TYPE_KEY, eventTime, policyFlags);
Jeff Brown7fbdc842010-06-17 20:52:56 -07003575
3576 entry->deviceId = deviceId;
Jeff Brownc5ed5912010-07-14 18:48:53 -07003577 entry->source = source;
Jeff Brown7fbdc842010-06-17 20:52:56 -07003578 entry->action = action;
3579 entry->flags = flags;
3580 entry->keyCode = keyCode;
3581 entry->scanCode = scanCode;
3582 entry->metaState = metaState;
3583 entry->repeatCount = repeatCount;
3584 entry->downTime = downTime;
Jeff Brownb88102f2010-09-08 11:49:43 -07003585 entry->syntheticRepeat = false;
3586 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003587 return entry;
3588}
3589
Jeff Brown7fbdc842010-06-17 20:52:56 -07003590InputDispatcher::MotionEntry* InputDispatcher::Allocator::obtainMotionEntry(nsecs_t eventTime,
Jeff Brown58a2da82011-01-25 16:02:22 -08003591 int32_t deviceId, uint32_t source, uint32_t policyFlags, int32_t action, int32_t flags,
Jeff Brown7fbdc842010-06-17 20:52:56 -07003592 int32_t metaState, int32_t edgeFlags, float xPrecision, float yPrecision,
3593 nsecs_t downTime, uint32_t pointerCount,
3594 const int32_t* pointerIds, const PointerCoords* pointerCoords) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003595 MotionEntry* entry = mMotionEntryPool.alloc();
Jeff Brownb6997262010-10-08 22:31:17 -07003596 initializeEventEntry(entry, EventEntry::TYPE_MOTION, eventTime, policyFlags);
Jeff Brown7fbdc842010-06-17 20:52:56 -07003597
3598 entry->eventTime = eventTime;
3599 entry->deviceId = deviceId;
Jeff Brownc5ed5912010-07-14 18:48:53 -07003600 entry->source = source;
Jeff Brown7fbdc842010-06-17 20:52:56 -07003601 entry->action = action;
Jeff Brown85a31762010-09-01 17:01:00 -07003602 entry->flags = flags;
Jeff Brown7fbdc842010-06-17 20:52:56 -07003603 entry->metaState = metaState;
3604 entry->edgeFlags = edgeFlags;
3605 entry->xPrecision = xPrecision;
3606 entry->yPrecision = yPrecision;
3607 entry->downTime = downTime;
3608 entry->pointerCount = pointerCount;
3609 entry->firstSample.eventTime = eventTime;
Jeff Brown5ced76a2011-05-24 11:23:27 -07003610 entry->firstSample.eventTimeBeforeCoalescing = eventTime;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003611 entry->firstSample.next = NULL;
Jeff Brown7fbdc842010-06-17 20:52:56 -07003612 entry->lastSample = & entry->firstSample;
3613 for (uint32_t i = 0; i < pointerCount; i++) {
3614 entry->pointerIds[i] = pointerIds[i];
Jeff Brown96ad3972011-03-09 17:39:48 -08003615 entry->firstSample.pointerCoords[i].copyFrom(pointerCoords[i]);
Jeff Brown7fbdc842010-06-17 20:52:56 -07003616 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003617 return entry;
3618}
3619
3620InputDispatcher::DispatchEntry* InputDispatcher::Allocator::obtainDispatchEntry(
Jeff Brownb88102f2010-09-08 11:49:43 -07003621 EventEntry* eventEntry,
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003622 int32_t targetFlags, float xOffset, float yOffset, float scaleFactor) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003623 DispatchEntry* entry = mDispatchEntryPool.alloc();
3624 entry->eventEntry = eventEntry;
3625 eventEntry->refCount += 1;
Jeff Brownb88102f2010-09-08 11:49:43 -07003626 entry->targetFlags = targetFlags;
3627 entry->xOffset = xOffset;
3628 entry->yOffset = yOffset;
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003629 entry->scaleFactor = scaleFactor;
Jeff Brownb88102f2010-09-08 11:49:43 -07003630 entry->inProgress = false;
3631 entry->headMotionSample = NULL;
3632 entry->tailMotionSample = NULL;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003633 return entry;
3634}
3635
Jeff Brown9c3cda02010-06-15 01:31:58 -07003636InputDispatcher::CommandEntry* InputDispatcher::Allocator::obtainCommandEntry(Command command) {
3637 CommandEntry* entry = mCommandEntryPool.alloc();
3638 entry->command = command;
3639 return entry;
3640}
3641
Jeff Brown01ce2e92010-09-26 22:20:12 -07003642void InputDispatcher::Allocator::releaseInjectionState(InjectionState* injectionState) {
3643 injectionState->refCount -= 1;
3644 if (injectionState->refCount == 0) {
3645 mInjectionStatePool.free(injectionState);
3646 } else {
3647 assert(injectionState->refCount > 0);
3648 }
3649}
3650
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003651void InputDispatcher::Allocator::releaseEventEntry(EventEntry* entry) {
3652 switch (entry->type) {
3653 case EventEntry::TYPE_CONFIGURATION_CHANGED:
3654 releaseConfigurationChangedEntry(static_cast<ConfigurationChangedEntry*>(entry));
3655 break;
3656 case EventEntry::TYPE_KEY:
3657 releaseKeyEntry(static_cast<KeyEntry*>(entry));
3658 break;
3659 case EventEntry::TYPE_MOTION:
3660 releaseMotionEntry(static_cast<MotionEntry*>(entry));
3661 break;
3662 default:
3663 assert(false);
3664 break;
3665 }
3666}
3667
3668void InputDispatcher::Allocator::releaseConfigurationChangedEntry(
3669 ConfigurationChangedEntry* entry) {
3670 entry->refCount -= 1;
3671 if (entry->refCount == 0) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07003672 releaseEventEntryInjectionState(entry);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003673 mConfigurationChangeEntryPool.free(entry);
3674 } else {
3675 assert(entry->refCount > 0);
3676 }
3677}
3678
3679void InputDispatcher::Allocator::releaseKeyEntry(KeyEntry* entry) {
3680 entry->refCount -= 1;
3681 if (entry->refCount == 0) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07003682 releaseEventEntryInjectionState(entry);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003683 mKeyEntryPool.free(entry);
3684 } else {
3685 assert(entry->refCount > 0);
3686 }
3687}
3688
3689void InputDispatcher::Allocator::releaseMotionEntry(MotionEntry* entry) {
3690 entry->refCount -= 1;
3691 if (entry->refCount == 0) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07003692 releaseEventEntryInjectionState(entry);
Jeff Brown9c3cda02010-06-15 01:31:58 -07003693 for (MotionSample* sample = entry->firstSample.next; sample != NULL; ) {
3694 MotionSample* next = sample->next;
3695 mMotionSamplePool.free(sample);
3696 sample = next;
3697 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003698 mMotionEntryPool.free(entry);
3699 } else {
3700 assert(entry->refCount > 0);
3701 }
3702}
3703
3704void InputDispatcher::Allocator::releaseDispatchEntry(DispatchEntry* entry) {
3705 releaseEventEntry(entry->eventEntry);
3706 mDispatchEntryPool.free(entry);
3707}
3708
Jeff Brown9c3cda02010-06-15 01:31:58 -07003709void InputDispatcher::Allocator::releaseCommandEntry(CommandEntry* entry) {
3710 mCommandEntryPool.free(entry);
3711}
3712
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003713void InputDispatcher::Allocator::appendMotionSample(MotionEntry* motionEntry,
Jeff Brown7fbdc842010-06-17 20:52:56 -07003714 nsecs_t eventTime, const PointerCoords* pointerCoords) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003715 MotionSample* sample = mMotionSamplePool.alloc();
3716 sample->eventTime = eventTime;
Jeff Brown5ced76a2011-05-24 11:23:27 -07003717 sample->eventTimeBeforeCoalescing = eventTime;
Jeff Brown7fbdc842010-06-17 20:52:56 -07003718 uint32_t pointerCount = motionEntry->pointerCount;
3719 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brown96ad3972011-03-09 17:39:48 -08003720 sample->pointerCoords[i].copyFrom(pointerCoords[i]);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003721 }
3722
3723 sample->next = NULL;
3724 motionEntry->lastSample->next = sample;
3725 motionEntry->lastSample = sample;
3726}
3727
Jeff Brown01ce2e92010-09-26 22:20:12 -07003728void InputDispatcher::Allocator::recycleKeyEntry(KeyEntry* keyEntry) {
3729 releaseEventEntryInjectionState(keyEntry);
Jeff Brownb88102f2010-09-08 11:49:43 -07003730
Jeff Brown01ce2e92010-09-26 22:20:12 -07003731 keyEntry->dispatchInProgress = false;
3732 keyEntry->syntheticRepeat = false;
3733 keyEntry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
Jeff Brownb88102f2010-09-08 11:49:43 -07003734}
3735
3736
Jeff Brownae9fc032010-08-18 15:51:08 -07003737// --- InputDispatcher::MotionEntry ---
3738
3739uint32_t InputDispatcher::MotionEntry::countSamples() const {
3740 uint32_t count = 1;
3741 for (MotionSample* sample = firstSample.next; sample != NULL; sample = sample->next) {
3742 count += 1;
3743 }
3744 return count;
3745}
3746
Jeff Brown5ced76a2011-05-24 11:23:27 -07003747bool InputDispatcher::MotionEntry::canAppendSamples(int32_t action, uint32_t pointerCount,
3748 const int32_t* pointerIds) const {
3749 if (this->action != action
3750 || this->pointerCount != pointerCount
3751 || this->isInjected()) {
3752 return false;
3753 }
3754 for (uint32_t i = 0; i < pointerCount; i++) {
3755 if (this->pointerIds[i] != pointerIds[i]) {
3756 return false;
3757 }
3758 }
3759 return true;
3760}
3761
Jeff Brownb88102f2010-09-08 11:49:43 -07003762
3763// --- InputDispatcher::InputState ---
3764
Jeff Brownb6997262010-10-08 22:31:17 -07003765InputDispatcher::InputState::InputState() {
Jeff Brownb88102f2010-09-08 11:49:43 -07003766}
3767
3768InputDispatcher::InputState::~InputState() {
3769}
3770
3771bool InputDispatcher::InputState::isNeutral() const {
3772 return mKeyMementos.isEmpty() && mMotionMementos.isEmpty();
3773}
3774
Jeff Browncc0c1592011-02-19 05:07:28 -08003775void InputDispatcher::InputState::trackEvent(
Jeff Brownb88102f2010-09-08 11:49:43 -07003776 const EventEntry* entry) {
3777 switch (entry->type) {
3778 case EventEntry::TYPE_KEY:
Jeff Browncc0c1592011-02-19 05:07:28 -08003779 trackKey(static_cast<const KeyEntry*>(entry));
3780 break;
Jeff Brownb88102f2010-09-08 11:49:43 -07003781
3782 case EventEntry::TYPE_MOTION:
Jeff Browncc0c1592011-02-19 05:07:28 -08003783 trackMotion(static_cast<const MotionEntry*>(entry));
3784 break;
Jeff Brownb88102f2010-09-08 11:49:43 -07003785 }
3786}
3787
Jeff Browncc0c1592011-02-19 05:07:28 -08003788void InputDispatcher::InputState::trackKey(
Jeff Brownb88102f2010-09-08 11:49:43 -07003789 const KeyEntry* entry) {
3790 int32_t action = entry->action;
Jeff Brown524ee642011-03-29 15:11:34 -07003791 if (action == AKEY_EVENT_ACTION_UP
3792 && (entry->flags & AKEY_EVENT_FLAG_FALLBACK)) {
3793 for (size_t i = 0; i < mFallbackKeys.size(); ) {
3794 if (mFallbackKeys.valueAt(i) == entry->keyCode) {
3795 mFallbackKeys.removeItemsAt(i);
3796 } else {
3797 i += 1;
3798 }
3799 }
3800 }
3801
Jeff Brownb88102f2010-09-08 11:49:43 -07003802 for (size_t i = 0; i < mKeyMementos.size(); i++) {
3803 KeyMemento& memento = mKeyMementos.editItemAt(i);
3804 if (memento.deviceId == entry->deviceId
3805 && memento.source == entry->source
3806 && memento.keyCode == entry->keyCode
3807 && memento.scanCode == entry->scanCode) {
3808 switch (action) {
3809 case AKEY_EVENT_ACTION_UP:
3810 mKeyMementos.removeAt(i);
Jeff Browncc0c1592011-02-19 05:07:28 -08003811 return;
Jeff Brownb88102f2010-09-08 11:49:43 -07003812
3813 case AKEY_EVENT_ACTION_DOWN:
Jeff Browncc0c1592011-02-19 05:07:28 -08003814 mKeyMementos.removeAt(i);
3815 goto Found;
Jeff Brownb88102f2010-09-08 11:49:43 -07003816
3817 default:
Jeff Browncc0c1592011-02-19 05:07:28 -08003818 return;
Jeff Brownb88102f2010-09-08 11:49:43 -07003819 }
3820 }
3821 }
3822
Jeff Browncc0c1592011-02-19 05:07:28 -08003823Found:
3824 if (action == AKEY_EVENT_ACTION_DOWN) {
Jeff Brownb88102f2010-09-08 11:49:43 -07003825 mKeyMementos.push();
3826 KeyMemento& memento = mKeyMementos.editTop();
3827 memento.deviceId = entry->deviceId;
3828 memento.source = entry->source;
3829 memento.keyCode = entry->keyCode;
3830 memento.scanCode = entry->scanCode;
Jeff Brown49ed71d2010-12-06 17:13:33 -08003831 memento.flags = entry->flags;
Jeff Brownb88102f2010-09-08 11:49:43 -07003832 memento.downTime = entry->downTime;
Jeff Brownb88102f2010-09-08 11:49:43 -07003833 }
3834}
3835
Jeff Browncc0c1592011-02-19 05:07:28 -08003836void InputDispatcher::InputState::trackMotion(
Jeff Brownb88102f2010-09-08 11:49:43 -07003837 const MotionEntry* entry) {
3838 int32_t action = entry->action & AMOTION_EVENT_ACTION_MASK;
3839 for (size_t i = 0; i < mMotionMementos.size(); i++) {
3840 MotionMemento& memento = mMotionMementos.editItemAt(i);
3841 if (memento.deviceId == entry->deviceId
3842 && memento.source == entry->source) {
3843 switch (action) {
3844 case AMOTION_EVENT_ACTION_UP:
3845 case AMOTION_EVENT_ACTION_CANCEL:
Jeff Browncc0c1592011-02-19 05:07:28 -08003846 case AMOTION_EVENT_ACTION_HOVER_MOVE:
Jeff Brownb88102f2010-09-08 11:49:43 -07003847 mMotionMementos.removeAt(i);
Jeff Browncc0c1592011-02-19 05:07:28 -08003848 return;
Jeff Brownb88102f2010-09-08 11:49:43 -07003849
3850 case AMOTION_EVENT_ACTION_DOWN:
Jeff Browncc0c1592011-02-19 05:07:28 -08003851 mMotionMementos.removeAt(i);
3852 goto Found;
Jeff Brownb88102f2010-09-08 11:49:43 -07003853
3854 case AMOTION_EVENT_ACTION_POINTER_UP:
Jeff Browncc0c1592011-02-19 05:07:28 -08003855 case AMOTION_EVENT_ACTION_POINTER_DOWN:
Jeff Brownb88102f2010-09-08 11:49:43 -07003856 case AMOTION_EVENT_ACTION_MOVE:
Jeff Browncc0c1592011-02-19 05:07:28 -08003857 memento.setPointers(entry);
3858 return;
Jeff Brownb88102f2010-09-08 11:49:43 -07003859
3860 default:
Jeff Browncc0c1592011-02-19 05:07:28 -08003861 return;
Jeff Brownb88102f2010-09-08 11:49:43 -07003862 }
3863 }
3864 }
3865
Jeff Browncc0c1592011-02-19 05:07:28 -08003866Found:
3867 if (action == AMOTION_EVENT_ACTION_DOWN) {
Jeff Brownb88102f2010-09-08 11:49:43 -07003868 mMotionMementos.push();
3869 MotionMemento& memento = mMotionMementos.editTop();
3870 memento.deviceId = entry->deviceId;
3871 memento.source = entry->source;
3872 memento.xPrecision = entry->xPrecision;
3873 memento.yPrecision = entry->yPrecision;
3874 memento.downTime = entry->downTime;
3875 memento.setPointers(entry);
Jeff Brownb88102f2010-09-08 11:49:43 -07003876 }
3877}
3878
3879void InputDispatcher::InputState::MotionMemento::setPointers(const MotionEntry* entry) {
3880 pointerCount = entry->pointerCount;
3881 for (uint32_t i = 0; i < entry->pointerCount; i++) {
3882 pointerIds[i] = entry->pointerIds[i];
Jeff Brown96ad3972011-03-09 17:39:48 -08003883 pointerCoords[i].copyFrom(entry->lastSample->pointerCoords[i]);
Jeff Brownb88102f2010-09-08 11:49:43 -07003884 }
3885}
3886
Jeff Brownb6997262010-10-08 22:31:17 -07003887void InputDispatcher::InputState::synthesizeCancelationEvents(nsecs_t currentTime,
3888 Allocator* allocator, Vector<EventEntry*>& outEvents,
Jeff Brown524ee642011-03-29 15:11:34 -07003889 const CancelationOptions& options) {
Jeff Brownb6997262010-10-08 22:31:17 -07003890 for (size_t i = 0; i < mKeyMementos.size(); ) {
Jeff Brownb88102f2010-09-08 11:49:43 -07003891 const KeyMemento& memento = mKeyMementos.itemAt(i);
Jeff Brown49ed71d2010-12-06 17:13:33 -08003892 if (shouldCancelKey(memento, options)) {
Jeff Brownb6997262010-10-08 22:31:17 -07003893 outEvents.push(allocator->obtainKeyEntry(currentTime,
3894 memento.deviceId, memento.source, 0,
Jeff Brown49ed71d2010-12-06 17:13:33 -08003895 AKEY_EVENT_ACTION_UP, memento.flags | AKEY_EVENT_FLAG_CANCELED,
Jeff Brownb6997262010-10-08 22:31:17 -07003896 memento.keyCode, memento.scanCode, 0, 0, memento.downTime));
3897 mKeyMementos.removeAt(i);
3898 } else {
3899 i += 1;
3900 }
Jeff Brownb88102f2010-09-08 11:49:43 -07003901 }
3902
Jeff Browna1160a72010-10-11 18:22:53 -07003903 for (size_t i = 0; i < mMotionMementos.size(); ) {
Jeff Brownb88102f2010-09-08 11:49:43 -07003904 const MotionMemento& memento = mMotionMementos.itemAt(i);
Jeff Brown49ed71d2010-12-06 17:13:33 -08003905 if (shouldCancelMotion(memento, options)) {
Jeff Brownb6997262010-10-08 22:31:17 -07003906 outEvents.push(allocator->obtainMotionEntry(currentTime,
3907 memento.deviceId, memento.source, 0,
3908 AMOTION_EVENT_ACTION_CANCEL, 0, 0, 0,
3909 memento.xPrecision, memento.yPrecision, memento.downTime,
3910 memento.pointerCount, memento.pointerIds, memento.pointerCoords));
3911 mMotionMementos.removeAt(i);
3912 } else {
3913 i += 1;
3914 }
Jeff Brownb88102f2010-09-08 11:49:43 -07003915 }
3916}
3917
3918void InputDispatcher::InputState::clear() {
3919 mKeyMementos.clear();
3920 mMotionMementos.clear();
Jeff Brown524ee642011-03-29 15:11:34 -07003921 mFallbackKeys.clear();
Jeff Brownb6997262010-10-08 22:31:17 -07003922}
3923
Jeff Brown9c9f1a32010-10-11 18:32:20 -07003924void InputDispatcher::InputState::copyPointerStateTo(InputState& other) const {
3925 for (size_t i = 0; i < mMotionMementos.size(); i++) {
3926 const MotionMemento& memento = mMotionMementos.itemAt(i);
3927 if (memento.source & AINPUT_SOURCE_CLASS_POINTER) {
3928 for (size_t j = 0; j < other.mMotionMementos.size(); ) {
3929 const MotionMemento& otherMemento = other.mMotionMementos.itemAt(j);
3930 if (memento.deviceId == otherMemento.deviceId
3931 && memento.source == otherMemento.source) {
3932 other.mMotionMementos.removeAt(j);
3933 } else {
3934 j += 1;
3935 }
3936 }
3937 other.mMotionMementos.push(memento);
3938 }
3939 }
3940}
3941
Jeff Brown524ee642011-03-29 15:11:34 -07003942int32_t InputDispatcher::InputState::getFallbackKey(int32_t originalKeyCode) {
3943 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
3944 return index >= 0 ? mFallbackKeys.valueAt(index) : -1;
3945}
3946
3947void InputDispatcher::InputState::setFallbackKey(int32_t originalKeyCode,
3948 int32_t fallbackKeyCode) {
3949 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
3950 if (index >= 0) {
3951 mFallbackKeys.replaceValueAt(index, fallbackKeyCode);
3952 } else {
3953 mFallbackKeys.add(originalKeyCode, fallbackKeyCode);
3954 }
3955}
3956
3957void InputDispatcher::InputState::removeFallbackKey(int32_t originalKeyCode) {
3958 mFallbackKeys.removeItem(originalKeyCode);
3959}
3960
Jeff Brown49ed71d2010-12-06 17:13:33 -08003961bool InputDispatcher::InputState::shouldCancelKey(const KeyMemento& memento,
Jeff Brown524ee642011-03-29 15:11:34 -07003962 const CancelationOptions& options) {
3963 if (options.keyCode != -1 && memento.keyCode != options.keyCode) {
3964 return false;
3965 }
3966
3967 switch (options.mode) {
3968 case CancelationOptions::CANCEL_ALL_EVENTS:
3969 case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
Jeff Brownb6997262010-10-08 22:31:17 -07003970 return true;
Jeff Brown524ee642011-03-29 15:11:34 -07003971 case CancelationOptions::CANCEL_FALLBACK_EVENTS:
Jeff Brown49ed71d2010-12-06 17:13:33 -08003972 return memento.flags & AKEY_EVENT_FLAG_FALLBACK;
3973 default:
3974 return false;
3975 }
3976}
3977
3978bool InputDispatcher::InputState::shouldCancelMotion(const MotionMemento& memento,
Jeff Brown524ee642011-03-29 15:11:34 -07003979 const CancelationOptions& options) {
3980 switch (options.mode) {
3981 case CancelationOptions::CANCEL_ALL_EVENTS:
Jeff Brown49ed71d2010-12-06 17:13:33 -08003982 return true;
Jeff Brown524ee642011-03-29 15:11:34 -07003983 case CancelationOptions::CANCEL_POINTER_EVENTS:
Jeff Brown49ed71d2010-12-06 17:13:33 -08003984 return memento.source & AINPUT_SOURCE_CLASS_POINTER;
Jeff Brown524ee642011-03-29 15:11:34 -07003985 case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
Jeff Brown49ed71d2010-12-06 17:13:33 -08003986 return !(memento.source & AINPUT_SOURCE_CLASS_POINTER);
3987 default:
3988 return false;
Jeff Brownb6997262010-10-08 22:31:17 -07003989 }
Jeff Brownb88102f2010-09-08 11:49:43 -07003990}
3991
3992
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003993// --- InputDispatcher::Connection ---
3994
Jeff Brown928e0542011-01-10 11:17:36 -08003995InputDispatcher::Connection::Connection(const sp<InputChannel>& inputChannel,
3996 const sp<InputWindowHandle>& inputWindowHandle) :
3997 status(STATUS_NORMAL), inputChannel(inputChannel), inputWindowHandle(inputWindowHandle),
3998 inputPublisher(inputChannel),
Jeff Brown524ee642011-03-29 15:11:34 -07003999 lastEventTime(LONG_LONG_MAX), lastDispatchTime(LONG_LONG_MAX) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004000}
4001
4002InputDispatcher::Connection::~Connection() {
4003}
4004
4005status_t InputDispatcher::Connection::initialize() {
4006 return inputPublisher.initialize();
4007}
4008
Jeff Brown9c3cda02010-06-15 01:31:58 -07004009const char* InputDispatcher::Connection::getStatusLabel() const {
4010 switch (status) {
4011 case STATUS_NORMAL:
4012 return "NORMAL";
4013
4014 case STATUS_BROKEN:
4015 return "BROKEN";
4016
Jeff Brown9c3cda02010-06-15 01:31:58 -07004017 case STATUS_ZOMBIE:
4018 return "ZOMBIE";
4019
4020 default:
4021 return "UNKNOWN";
4022 }
4023}
4024
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004025InputDispatcher::DispatchEntry* InputDispatcher::Connection::findQueuedDispatchEntryForEvent(
4026 const EventEntry* eventEntry) const {
Jeff Brownb88102f2010-09-08 11:49:43 -07004027 for (DispatchEntry* dispatchEntry = outboundQueue.tailSentinel.prev;
4028 dispatchEntry != & outboundQueue.headSentinel; dispatchEntry = dispatchEntry->prev) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004029 if (dispatchEntry->eventEntry == eventEntry) {
4030 return dispatchEntry;
4031 }
4032 }
4033 return NULL;
4034}
4035
Jeff Brownb88102f2010-09-08 11:49:43 -07004036
Jeff Brown9c3cda02010-06-15 01:31:58 -07004037// --- InputDispatcher::CommandEntry ---
4038
Jeff Brownb88102f2010-09-08 11:49:43 -07004039InputDispatcher::CommandEntry::CommandEntry() :
4040 keyEntry(NULL) {
Jeff Brown9c3cda02010-06-15 01:31:58 -07004041}
4042
4043InputDispatcher::CommandEntry::~CommandEntry() {
4044}
4045
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004046
Jeff Brown01ce2e92010-09-26 22:20:12 -07004047// --- InputDispatcher::TouchState ---
4048
4049InputDispatcher::TouchState::TouchState() :
Jeff Brown58a2da82011-01-25 16:02:22 -08004050 down(false), split(false), deviceId(-1), source(0) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07004051}
4052
4053InputDispatcher::TouchState::~TouchState() {
4054}
4055
4056void InputDispatcher::TouchState::reset() {
4057 down = false;
4058 split = false;
Jeff Brown95712852011-01-04 19:41:59 -08004059 deviceId = -1;
Jeff Brown58a2da82011-01-25 16:02:22 -08004060 source = 0;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004061 windows.clear();
4062}
4063
4064void InputDispatcher::TouchState::copyFrom(const TouchState& other) {
4065 down = other.down;
4066 split = other.split;
Jeff Brown95712852011-01-04 19:41:59 -08004067 deviceId = other.deviceId;
Jeff Brown58a2da82011-01-25 16:02:22 -08004068 source = other.source;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004069 windows.clear();
4070 windows.appendVector(other.windows);
4071}
4072
4073void InputDispatcher::TouchState::addOrUpdateWindow(const InputWindow* window,
4074 int32_t targetFlags, BitSet32 pointerIds) {
4075 if (targetFlags & InputTarget::FLAG_SPLIT) {
4076 split = true;
4077 }
4078
4079 for (size_t i = 0; i < windows.size(); i++) {
4080 TouchedWindow& touchedWindow = windows.editItemAt(i);
4081 if (touchedWindow.window == window) {
4082 touchedWindow.targetFlags |= targetFlags;
4083 touchedWindow.pointerIds.value |= pointerIds.value;
4084 return;
4085 }
4086 }
4087
4088 windows.push();
4089
4090 TouchedWindow& touchedWindow = windows.editTop();
4091 touchedWindow.window = window;
4092 touchedWindow.targetFlags = targetFlags;
4093 touchedWindow.pointerIds = pointerIds;
4094 touchedWindow.channel = window->inputChannel;
4095}
4096
4097void InputDispatcher::TouchState::removeOutsideTouchWindows() {
4098 for (size_t i = 0 ; i < windows.size(); ) {
4099 if (windows[i].targetFlags & InputTarget::FLAG_OUTSIDE) {
4100 windows.removeAt(i);
4101 } else {
4102 i += 1;
4103 }
4104 }
4105}
4106
4107const InputWindow* InputDispatcher::TouchState::getFirstForegroundWindow() {
4108 for (size_t i = 0; i < windows.size(); i++) {
4109 if (windows[i].targetFlags & InputTarget::FLAG_FOREGROUND) {
4110 return windows[i].window;
4111 }
4112 }
4113 return NULL;
4114}
4115
4116
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004117// --- InputDispatcherThread ---
4118
4119InputDispatcherThread::InputDispatcherThread(const sp<InputDispatcherInterface>& dispatcher) :
4120 Thread(/*canCallJava*/ true), mDispatcher(dispatcher) {
4121}
4122
4123InputDispatcherThread::~InputDispatcherThread() {
4124}
4125
4126bool InputDispatcherThread::threadLoop() {
4127 mDispatcher->dispatchOnce();
4128 return true;
4129}
4130
4131} // namespace android