blob: 8c535d6318640617e667d2d22cf632edb1f0f5d1 [file] [log] [blame]
Jeff Brownb4ff35d2011-01-02 16:37:43 -08001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070017#define LOG_TAG "InputDispatcher"
18
19//#define LOG_NDEBUG 0
20
21// Log detailed debug messages about each inbound event notification to the dispatcher.
Jeff Brown349703e2010-06-22 01:27:15 -070022#define DEBUG_INBOUND_EVENT_DETAILS 0
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070023
24// Log detailed debug messages about each outbound event processed by the dispatcher.
Jeff Brown349703e2010-06-22 01:27:15 -070025#define DEBUG_OUTBOUND_EVENT_DETAILS 0
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070026
27// Log debug messages about batching.
Jeff Brown349703e2010-06-22 01:27:15 -070028#define DEBUG_BATCHING 0
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070029
30// Log debug messages about the dispatch cycle.
Jeff Brown349703e2010-06-22 01:27:15 -070031#define DEBUG_DISPATCH_CYCLE 0
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070032
Jeff Brown9c3cda02010-06-15 01:31:58 -070033// Log debug messages about registrations.
Jeff Brown349703e2010-06-22 01:27:15 -070034#define DEBUG_REGISTRATION 0
Jeff Brown9c3cda02010-06-15 01:31:58 -070035
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070036// Log debug messages about performance statistics.
Jeff Brown349703e2010-06-22 01:27:15 -070037#define DEBUG_PERFORMANCE_STATISTICS 0
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070038
Jeff Brown7fbdc842010-06-17 20:52:56 -070039// Log debug messages about input event injection.
Jeff Brown349703e2010-06-22 01:27:15 -070040#define DEBUG_INJECTION 0
Jeff Brown7fbdc842010-06-17 20:52:56 -070041
Jeff Brownae9fc032010-08-18 15:51:08 -070042// Log debug messages about input event throttling.
43#define DEBUG_THROTTLING 0
44
Jeff Brownb88102f2010-09-08 11:49:43 -070045// Log debug messages about input focus tracking.
46#define DEBUG_FOCUS 0
47
48// Log debug messages about the app switch latency optimization.
49#define DEBUG_APP_SWITCH 0
50
Jeff Browna032cc02011-03-07 16:56:21 -080051// Log debug messages about hover events.
52#define DEBUG_HOVER 0
53
Jeff Brownb4ff35d2011-01-02 16:37:43 -080054#include "InputDispatcher.h"
55
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070056#include <cutils/log.h>
Jeff Brownb88102f2010-09-08 11:49:43 -070057#include <ui/PowerManager.h>
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070058
59#include <stddef.h>
60#include <unistd.h>
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070061#include <errno.h>
62#include <limits.h>
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070063
Jeff Brownf2f487182010-10-01 17:46:21 -070064#define INDENT " "
65#define INDENT2 " "
66
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070067namespace android {
68
Jeff Brownb88102f2010-09-08 11:49:43 -070069// Default input dispatching timeout if there is no focused application or paused window
70// from which to determine an appropriate dispatching timeout.
71const nsecs_t DEFAULT_INPUT_DISPATCHING_TIMEOUT = 5000 * 1000000LL; // 5 sec
72
73// Amount of time to allow for all pending events to be processed when an app switch
74// key is on the way. This is used to preempt input dispatch and drop input events
75// when an application takes too long to respond and the user has pressed an app switch key.
76const nsecs_t APP_SWITCH_TIMEOUT = 500 * 1000000LL; // 0.5sec
77
Jeff Brown928e0542011-01-10 11:17:36 -080078// Amount of time to allow for an event to be dispatched (measured since its eventTime)
79// before considering it stale and dropping it.
80const nsecs_t STALE_EVENT_TIMEOUT = 10000 * 1000000LL; // 10sec
81
Jeff Brown4e91a182011-04-07 11:38:09 -070082// Motion samples that are received within this amount of time are simply coalesced
83// when batched instead of being appended. This is done because some drivers update
84// the location of pointers one at a time instead of all at once.
85// For example, when there are 10 fingers down, the input dispatcher may receive 10
86// samples in quick succession with only one finger's location changed in each sample.
87//
88// This value effectively imposes an upper bound on the touch sampling rate.
89// Touch sensors typically have a 50Hz - 200Hz sampling rate, so we expect distinct
90// samples to become available 5-20ms apart but individual finger reports can trickle
91// in over a period of 2-4ms or so.
92//
93// Empirical testing shows that a 2ms coalescing interval (500Hz) is not enough,
94// a 3ms coalescing interval (333Hz) works well most of the time and doesn't introduce
95// significant quantization noise on current hardware.
96const nsecs_t MOTION_SAMPLE_COALESCE_INTERVAL = 3 * 1000000LL; // 3ms, 333Hz
97
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070098
Jeff Brown7fbdc842010-06-17 20:52:56 -070099static inline nsecs_t now() {
100 return systemTime(SYSTEM_TIME_MONOTONIC);
101}
102
Jeff Brownb88102f2010-09-08 11:49:43 -0700103static inline const char* toString(bool value) {
104 return value ? "true" : "false";
105}
106
Jeff Brown01ce2e92010-09-26 22:20:12 -0700107static inline int32_t getMotionEventActionPointerIndex(int32_t action) {
108 return (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK)
109 >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
110}
111
112static bool isValidKeyAction(int32_t action) {
113 switch (action) {
114 case AKEY_EVENT_ACTION_DOWN:
115 case AKEY_EVENT_ACTION_UP:
116 return true;
117 default:
118 return false;
119 }
120}
121
122static bool validateKeyEvent(int32_t action) {
123 if (! isValidKeyAction(action)) {
124 LOGE("Key event has invalid action code 0x%x", action);
125 return false;
126 }
127 return true;
128}
129
Jeff Brownb6997262010-10-08 22:31:17 -0700130static bool isValidMotionAction(int32_t action, size_t pointerCount) {
Jeff Brown01ce2e92010-09-26 22:20:12 -0700131 switch (action & AMOTION_EVENT_ACTION_MASK) {
132 case AMOTION_EVENT_ACTION_DOWN:
133 case AMOTION_EVENT_ACTION_UP:
134 case AMOTION_EVENT_ACTION_CANCEL:
135 case AMOTION_EVENT_ACTION_MOVE:
Jeff Brown01ce2e92010-09-26 22:20:12 -0700136 case AMOTION_EVENT_ACTION_OUTSIDE:
Jeff Browna032cc02011-03-07 16:56:21 -0800137 case AMOTION_EVENT_ACTION_HOVER_ENTER:
Jeff Browncc0c1592011-02-19 05:07:28 -0800138 case AMOTION_EVENT_ACTION_HOVER_MOVE:
Jeff Browna032cc02011-03-07 16:56:21 -0800139 case AMOTION_EVENT_ACTION_HOVER_EXIT:
Jeff Brown33bbfd22011-02-24 20:55:35 -0800140 case AMOTION_EVENT_ACTION_SCROLL:
Jeff Brown01ce2e92010-09-26 22:20:12 -0700141 return true;
Jeff Brownb6997262010-10-08 22:31:17 -0700142 case AMOTION_EVENT_ACTION_POINTER_DOWN:
143 case AMOTION_EVENT_ACTION_POINTER_UP: {
144 int32_t index = getMotionEventActionPointerIndex(action);
145 return index >= 0 && size_t(index) < pointerCount;
146 }
Jeff Brown01ce2e92010-09-26 22:20:12 -0700147 default:
148 return false;
149 }
150}
151
152static bool validateMotionEvent(int32_t action, size_t pointerCount,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700153 const PointerProperties* pointerProperties) {
Jeff Brownb6997262010-10-08 22:31:17 -0700154 if (! isValidMotionAction(action, pointerCount)) {
Jeff Brown01ce2e92010-09-26 22:20:12 -0700155 LOGE("Motion event has invalid action code 0x%x", action);
156 return false;
157 }
158 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
159 LOGE("Motion event has invalid pointer count %d; value must be between 1 and %d.",
160 pointerCount, MAX_POINTERS);
161 return false;
162 }
Jeff Brownc3db8582010-10-20 15:33:38 -0700163 BitSet32 pointerIdBits;
Jeff Brown01ce2e92010-09-26 22:20:12 -0700164 for (size_t i = 0; i < pointerCount; i++) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700165 int32_t id = pointerProperties[i].id;
Jeff Brownc3db8582010-10-20 15:33:38 -0700166 if (id < 0 || id > MAX_POINTER_ID) {
Jeff Brown01ce2e92010-09-26 22:20:12 -0700167 LOGE("Motion event has invalid pointer id %d; value must be between 0 and %d",
Jeff Brownc3db8582010-10-20 15:33:38 -0700168 id, MAX_POINTER_ID);
Jeff Brown01ce2e92010-09-26 22:20:12 -0700169 return false;
170 }
Jeff Brownc3db8582010-10-20 15:33:38 -0700171 if (pointerIdBits.hasBit(id)) {
172 LOGE("Motion event has duplicate pointer id %d", id);
173 return false;
174 }
175 pointerIdBits.markBit(id);
Jeff Brown01ce2e92010-09-26 22:20:12 -0700176 }
177 return true;
178}
179
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400180static void scalePointerCoords(const PointerCoords* inCoords, size_t count, float scaleFactor,
181 PointerCoords* outCoords) {
182 for (size_t i = 0; i < count; i++) {
183 outCoords[i] = inCoords[i];
184 outCoords[i].scale(scaleFactor);
185 }
186}
187
Jeff Brownfbf09772011-01-16 14:06:57 -0800188static void dumpRegion(String8& dump, const SkRegion& region) {
189 if (region.isEmpty()) {
190 dump.append("<empty>");
191 return;
192 }
193
194 bool first = true;
195 for (SkRegion::Iterator it(region); !it.done(); it.next()) {
196 if (first) {
197 first = false;
198 } else {
199 dump.append("|");
200 }
201 const SkIRect& rect = it.rect();
202 dump.appendFormat("[%d,%d][%d,%d]", rect.fLeft, rect.fTop, rect.fRight, rect.fBottom);
203 }
204}
205
Jeff Brownb88102f2010-09-08 11:49:43 -0700206
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700207// --- InputDispatcher ---
208
Jeff Brown9c3cda02010-06-15 01:31:58 -0700209InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy) :
Jeff Brownb88102f2010-09-08 11:49:43 -0700210 mPolicy(policy),
Jeff Brown928e0542011-01-10 11:17:36 -0800211 mPendingEvent(NULL), mAppSwitchSawKeyDown(false), mAppSwitchDueTime(LONG_LONG_MAX),
212 mNextUnblockedEvent(NULL),
Jeff Brown0029c662011-03-30 02:25:18 -0700213 mDispatchEnabled(true), mDispatchFrozen(false), mInputFilterEnabled(false),
Jeff Brown01ce2e92010-09-26 22:20:12 -0700214 mFocusedWindow(NULL),
Jeff Brownb88102f2010-09-08 11:49:43 -0700215 mFocusedApplication(NULL),
216 mCurrentInputTargetsValid(false),
Jeff Browna032cc02011-03-07 16:56:21 -0800217 mInputTargetWaitCause(INPUT_TARGET_WAIT_CAUSE_NONE),
218 mLastHoverWindow(NULL) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -0700219 mLooper = new Looper(false);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700220
Jeff Brownb88102f2010-09-08 11:49:43 -0700221 mInboundQueue.headSentinel.refCount = -1;
222 mInboundQueue.headSentinel.type = EventEntry::TYPE_SENTINEL;
223 mInboundQueue.headSentinel.eventTime = LONG_LONG_MIN;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700224
Jeff Brownb88102f2010-09-08 11:49:43 -0700225 mInboundQueue.tailSentinel.refCount = -1;
226 mInboundQueue.tailSentinel.type = EventEntry::TYPE_SENTINEL;
227 mInboundQueue.tailSentinel.eventTime = LONG_LONG_MAX;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700228
229 mKeyRepeatState.lastKeyEntry = NULL;
Jeff Brown9c3cda02010-06-15 01:31:58 -0700230
Jeff Brownae9fc032010-08-18 15:51:08 -0700231 int32_t maxEventsPerSecond = policy->getMaxEventsPerSecond();
232 mThrottleState.minTimeBetweenEvents = 1000000000LL / maxEventsPerSecond;
233 mThrottleState.lastDeviceId = -1;
234
235#if DEBUG_THROTTLING
236 mThrottleState.originalSampleCount = 0;
237 LOGD("Throttling - Max events per second = %d", maxEventsPerSecond);
238#endif
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700239}
240
241InputDispatcher::~InputDispatcher() {
Jeff Brownb88102f2010-09-08 11:49:43 -0700242 { // acquire lock
243 AutoMutex _l(mLock);
244
245 resetKeyRepeatLocked();
Jeff Brown54a18252010-09-16 14:07:33 -0700246 releasePendingEventLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -0700247 drainInboundQueueLocked();
248 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700249
250 while (mConnectionsByReceiveFd.size() != 0) {
251 unregisterInputChannel(mConnectionsByReceiveFd.valueAt(0)->inputChannel);
252 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700253}
254
255void InputDispatcher::dispatchOnce() {
Jeff Brown9c3cda02010-06-15 01:31:58 -0700256 nsecs_t keyRepeatTimeout = mPolicy->getKeyRepeatTimeout();
Jeff Brownb21fb102010-09-07 10:44:57 -0700257 nsecs_t keyRepeatDelay = mPolicy->getKeyRepeatDelay();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700258
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700259 nsecs_t nextWakeupTime = LONG_LONG_MAX;
260 { // acquire lock
261 AutoMutex _l(mLock);
Jeff Brownb88102f2010-09-08 11:49:43 -0700262 dispatchOnceInnerLocked(keyRepeatTimeout, keyRepeatDelay, & nextWakeupTime);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700263
Jeff Brownb88102f2010-09-08 11:49:43 -0700264 if (runCommandsLockedInterruptible()) {
265 nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700266 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700267 } // release lock
268
Jeff Brownb88102f2010-09-08 11:49:43 -0700269 // Wait for callback or timeout or wake. (make sure we round up, not down)
270 nsecs_t currentTime = now();
Jeff Brownaa3855d2011-03-17 01:34:19 -0700271 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
Jeff Brown4fe6c3e2010-09-13 23:17:30 -0700272 mLooper->pollOnce(timeoutMillis);
Jeff Brownb88102f2010-09-08 11:49:43 -0700273}
274
275void InputDispatcher::dispatchOnceInnerLocked(nsecs_t keyRepeatTimeout,
276 nsecs_t keyRepeatDelay, nsecs_t* nextWakeupTime) {
277 nsecs_t currentTime = now();
278
279 // Reset the key repeat timer whenever we disallow key events, even if the next event
280 // is not a key. This is to ensure that we abort a key repeat if the device is just coming
281 // out of sleep.
282 if (keyRepeatTimeout < 0) {
283 resetKeyRepeatLocked();
284 }
285
Jeff Brownb88102f2010-09-08 11:49:43 -0700286 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
287 if (mDispatchFrozen) {
288#if DEBUG_FOCUS
289 LOGD("Dispatch frozen. Waiting some more.");
290#endif
291 return;
292 }
293
294 // Optimize latency of app switches.
295 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
296 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
297 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
298 if (mAppSwitchDueTime < *nextWakeupTime) {
299 *nextWakeupTime = mAppSwitchDueTime;
300 }
301
Jeff Brownb88102f2010-09-08 11:49:43 -0700302 // Ready to start a new event.
303 // If we don't already have a pending event, go grab one.
304 if (! mPendingEvent) {
305 if (mInboundQueue.isEmpty()) {
306 if (isAppSwitchDue) {
307 // The inbound queue is empty so the app switch key we were waiting
308 // for will never arrive. Stop waiting for it.
309 resetPendingAppSwitchLocked(false);
310 isAppSwitchDue = false;
311 }
312
313 // Synthesize a key repeat if appropriate.
314 if (mKeyRepeatState.lastKeyEntry) {
315 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
316 mPendingEvent = synthesizeKeyRepeatLocked(currentTime, keyRepeatDelay);
317 } else {
318 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
319 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
320 }
321 }
322 }
323 if (! mPendingEvent) {
324 return;
325 }
326 } else {
327 // Inbound queue has at least one entry.
328 EventEntry* entry = mInboundQueue.headSentinel.next;
329
330 // Throttle the entry if it is a move event and there are no
331 // other events behind it in the queue. Due to movement batching, additional
332 // samples may be appended to this event by the time the throttling timeout
333 // expires.
334 // TODO Make this smarter and consider throttling per device independently.
Jeff Brownb6997262010-10-08 22:31:17 -0700335 if (entry->type == EventEntry::TYPE_MOTION
336 && !isAppSwitchDue
337 && mDispatchEnabled
338 && (entry->policyFlags & POLICY_FLAG_PASS_TO_USER)
339 && !entry->isInjected()) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700340 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
341 int32_t deviceId = motionEntry->deviceId;
342 uint32_t source = motionEntry->source;
343 if (! isAppSwitchDue
344 && motionEntry->next == & mInboundQueue.tailSentinel // exactly one event
Jeff Browncc0c1592011-02-19 05:07:28 -0800345 && (motionEntry->action == AMOTION_EVENT_ACTION_MOVE
346 || motionEntry->action == AMOTION_EVENT_ACTION_HOVER_MOVE)
Jeff Brownb88102f2010-09-08 11:49:43 -0700347 && deviceId == mThrottleState.lastDeviceId
348 && source == mThrottleState.lastSource) {
349 nsecs_t nextTime = mThrottleState.lastEventTime
350 + mThrottleState.minTimeBetweenEvents;
351 if (currentTime < nextTime) {
352 // Throttle it!
353#if DEBUG_THROTTLING
354 LOGD("Throttling - Delaying motion event for "
Jeff Brown90655042010-12-02 13:50:46 -0800355 "device %d, source 0x%08x by up to %0.3fms.",
Jeff Brownb88102f2010-09-08 11:49:43 -0700356 deviceId, source, (nextTime - currentTime) * 0.000001);
357#endif
358 if (nextTime < *nextWakeupTime) {
359 *nextWakeupTime = nextTime;
360 }
361 if (mThrottleState.originalSampleCount == 0) {
362 mThrottleState.originalSampleCount =
363 motionEntry->countSamples();
364 }
365 return;
366 }
367 }
368
369#if DEBUG_THROTTLING
370 if (mThrottleState.originalSampleCount != 0) {
371 uint32_t count = motionEntry->countSamples();
372 LOGD("Throttling - Motion event sample count grew by %d from %d to %d.",
373 count - mThrottleState.originalSampleCount,
374 mThrottleState.originalSampleCount, count);
375 mThrottleState.originalSampleCount = 0;
376 }
377#endif
378
makarand.karvekarf634ded2011-03-02 15:41:03 -0600379 mThrottleState.lastEventTime = currentTime;
Jeff Brownb88102f2010-09-08 11:49:43 -0700380 mThrottleState.lastDeviceId = deviceId;
381 mThrottleState.lastSource = source;
382 }
383
384 mInboundQueue.dequeue(entry);
385 mPendingEvent = entry;
386 }
Jeff Browne2fe69e2010-10-18 13:21:23 -0700387
388 // Poke user activity for this event.
389 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
390 pokeUserActivityLocked(mPendingEvent);
391 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700392 }
393
394 // Now we have an event to dispatch.
Jeff Brown928e0542011-01-10 11:17:36 -0800395 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Jeff Brownb6110c22011-04-01 16:15:13 -0700396 LOG_ASSERT(mPendingEvent != NULL);
Jeff Brown54a18252010-09-16 14:07:33 -0700397 bool done = false;
Jeff Brownb6997262010-10-08 22:31:17 -0700398 DropReason dropReason = DROP_REASON_NOT_DROPPED;
399 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
400 dropReason = DROP_REASON_POLICY;
401 } else if (!mDispatchEnabled) {
402 dropReason = DROP_REASON_DISABLED;
403 }
Jeff Brown928e0542011-01-10 11:17:36 -0800404
405 if (mNextUnblockedEvent == mPendingEvent) {
406 mNextUnblockedEvent = NULL;
407 }
408
Jeff Brownb88102f2010-09-08 11:49:43 -0700409 switch (mPendingEvent->type) {
410 case EventEntry::TYPE_CONFIGURATION_CHANGED: {
411 ConfigurationChangedEntry* typedEntry =
412 static_cast<ConfigurationChangedEntry*>(mPendingEvent);
Jeff Brown54a18252010-09-16 14:07:33 -0700413 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Jeff Brownb6997262010-10-08 22:31:17 -0700414 dropReason = DROP_REASON_NOT_DROPPED; // configuration changes are never dropped
Jeff Brownb88102f2010-09-08 11:49:43 -0700415 break;
416 }
417
418 case EventEntry::TYPE_KEY: {
419 KeyEntry* typedEntry = static_cast<KeyEntry*>(mPendingEvent);
Jeff Brownb6997262010-10-08 22:31:17 -0700420 if (isAppSwitchDue) {
421 if (isAppSwitchKeyEventLocked(typedEntry)) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700422 resetPendingAppSwitchLocked(true);
Jeff Brownb6997262010-10-08 22:31:17 -0700423 isAppSwitchDue = false;
424 } else if (dropReason == DROP_REASON_NOT_DROPPED) {
425 dropReason = DROP_REASON_APP_SWITCH;
Jeff Brownb88102f2010-09-08 11:49:43 -0700426 }
427 }
Jeff Brown928e0542011-01-10 11:17:36 -0800428 if (dropReason == DROP_REASON_NOT_DROPPED
429 && isStaleEventLocked(currentTime, typedEntry)) {
430 dropReason = DROP_REASON_STALE;
431 }
432 if (dropReason == DROP_REASON_NOT_DROPPED && mNextUnblockedEvent) {
433 dropReason = DROP_REASON_BLOCKED;
434 }
Jeff Brownb6997262010-10-08 22:31:17 -0700435 done = dispatchKeyLocked(currentTime, typedEntry, keyRepeatTimeout,
Jeff Browne20c9e02010-10-11 14:20:19 -0700436 &dropReason, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700437 break;
438 }
439
440 case EventEntry::TYPE_MOTION: {
441 MotionEntry* typedEntry = static_cast<MotionEntry*>(mPendingEvent);
Jeff Brownb6997262010-10-08 22:31:17 -0700442 if (dropReason == DROP_REASON_NOT_DROPPED && isAppSwitchDue) {
443 dropReason = DROP_REASON_APP_SWITCH;
Jeff Brownb88102f2010-09-08 11:49:43 -0700444 }
Jeff Brown928e0542011-01-10 11:17:36 -0800445 if (dropReason == DROP_REASON_NOT_DROPPED
446 && isStaleEventLocked(currentTime, typedEntry)) {
447 dropReason = DROP_REASON_STALE;
448 }
449 if (dropReason == DROP_REASON_NOT_DROPPED && mNextUnblockedEvent) {
450 dropReason = DROP_REASON_BLOCKED;
451 }
Jeff Brownb6997262010-10-08 22:31:17 -0700452 done = dispatchMotionLocked(currentTime, typedEntry,
Jeff Browne20c9e02010-10-11 14:20:19 -0700453 &dropReason, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700454 break;
455 }
456
457 default:
Jeff Brownb6110c22011-04-01 16:15:13 -0700458 LOG_ASSERT(false);
Jeff Brownb88102f2010-09-08 11:49:43 -0700459 break;
460 }
461
Jeff Brown54a18252010-09-16 14:07:33 -0700462 if (done) {
Jeff Brownb6997262010-10-08 22:31:17 -0700463 if (dropReason != DROP_REASON_NOT_DROPPED) {
464 dropInboundEventLocked(mPendingEvent, dropReason);
465 }
466
Jeff Brown54a18252010-09-16 14:07:33 -0700467 releasePendingEventLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -0700468 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
469 }
470}
471
472bool InputDispatcher::enqueueInboundEventLocked(EventEntry* entry) {
473 bool needWake = mInboundQueue.isEmpty();
474 mInboundQueue.enqueueAtTail(entry);
475
476 switch (entry->type) {
Jeff Brownb6997262010-10-08 22:31:17 -0700477 case EventEntry::TYPE_KEY: {
Jeff Brown928e0542011-01-10 11:17:36 -0800478 // Optimize app switch latency.
479 // If the application takes too long to catch up then we drop all events preceding
480 // the app switch key.
Jeff Brownb6997262010-10-08 22:31:17 -0700481 KeyEntry* keyEntry = static_cast<KeyEntry*>(entry);
482 if (isAppSwitchKeyEventLocked(keyEntry)) {
483 if (keyEntry->action == AKEY_EVENT_ACTION_DOWN) {
484 mAppSwitchSawKeyDown = true;
485 } else if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
486 if (mAppSwitchSawKeyDown) {
487#if DEBUG_APP_SWITCH
488 LOGD("App switch is pending!");
489#endif
490 mAppSwitchDueTime = keyEntry->eventTime + APP_SWITCH_TIMEOUT;
491 mAppSwitchSawKeyDown = false;
492 needWake = true;
493 }
494 }
495 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700496 break;
497 }
Jeff Brown928e0542011-01-10 11:17:36 -0800498
499 case EventEntry::TYPE_MOTION: {
500 // Optimize case where the current application is unresponsive and the user
501 // decides to touch a window in a different application.
502 // If the application takes too long to catch up then we drop all events preceding
503 // the touch into the other window.
504 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
Jeff Brown33bbfd22011-02-24 20:55:35 -0800505 if (motionEntry->action == AMOTION_EVENT_ACTION_DOWN
Jeff Brown928e0542011-01-10 11:17:36 -0800506 && (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER)
507 && mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY
508 && mInputTargetWaitApplication != NULL) {
Jeff Brown91c69ab2011-02-14 17:03:18 -0800509 int32_t x = int32_t(motionEntry->firstSample.pointerCoords[0].
Jeff Brownebbd5d12011-02-17 13:01:34 -0800510 getAxisValue(AMOTION_EVENT_AXIS_X));
Jeff Brown91c69ab2011-02-14 17:03:18 -0800511 int32_t y = int32_t(motionEntry->firstSample.pointerCoords[0].
Jeff Brownebbd5d12011-02-17 13:01:34 -0800512 getAxisValue(AMOTION_EVENT_AXIS_Y));
Jeff Brown928e0542011-01-10 11:17:36 -0800513 const InputWindow* touchedWindow = findTouchedWindowAtLocked(x, y);
514 if (touchedWindow
515 && touchedWindow->inputWindowHandle != NULL
516 && touchedWindow->inputWindowHandle->getInputApplicationHandle()
517 != mInputTargetWaitApplication) {
518 // User touched a different application than the one we are waiting on.
519 // Flag the event, and start pruning the input queue.
520 mNextUnblockedEvent = motionEntry;
521 needWake = true;
522 }
523 }
524 break;
525 }
Jeff Brownb6997262010-10-08 22:31:17 -0700526 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700527
528 return needWake;
529}
530
Jeff Brown928e0542011-01-10 11:17:36 -0800531const InputWindow* InputDispatcher::findTouchedWindowAtLocked(int32_t x, int32_t y) {
532 // Traverse windows from front to back to find touched window.
533 size_t numWindows = mWindows.size();
534 for (size_t i = 0; i < numWindows; i++) {
535 const InputWindow* window = & mWindows.editItemAt(i);
536 int32_t flags = window->layoutParamsFlags;
537
538 if (window->visible) {
539 if (!(flags & InputWindow::FLAG_NOT_TOUCHABLE)) {
540 bool isTouchModal = (flags & (InputWindow::FLAG_NOT_FOCUSABLE
541 | InputWindow::FLAG_NOT_TOUCH_MODAL)) == 0;
Jeff Brownfbf09772011-01-16 14:06:57 -0800542 if (isTouchModal || window->touchableRegionContainsPoint(x, y)) {
Jeff Brown928e0542011-01-10 11:17:36 -0800543 // Found window.
544 return window;
545 }
546 }
547 }
548
549 if (flags & InputWindow::FLAG_SYSTEM_ERROR) {
550 // Error window is on top but not visible, so touch is dropped.
551 return NULL;
552 }
553 }
554 return NULL;
555}
556
Jeff Brownb6997262010-10-08 22:31:17 -0700557void InputDispatcher::dropInboundEventLocked(EventEntry* entry, DropReason dropReason) {
558 const char* reason;
559 switch (dropReason) {
560 case DROP_REASON_POLICY:
Jeff Browne20c9e02010-10-11 14:20:19 -0700561#if DEBUG_INBOUND_EVENT_DETAILS
Jeff Brown3122e442010-10-11 23:32:49 -0700562 LOGD("Dropped event because policy consumed it.");
Jeff Browne20c9e02010-10-11 14:20:19 -0700563#endif
Jeff Brown3122e442010-10-11 23:32:49 -0700564 reason = "inbound event was dropped because the policy consumed it";
Jeff Brownb6997262010-10-08 22:31:17 -0700565 break;
566 case DROP_REASON_DISABLED:
567 LOGI("Dropped event because input dispatch is disabled.");
568 reason = "inbound event was dropped because input dispatch is disabled";
569 break;
570 case DROP_REASON_APP_SWITCH:
571 LOGI("Dropped event because of pending overdue app switch.");
572 reason = "inbound event was dropped because of pending overdue app switch";
573 break;
Jeff Brown928e0542011-01-10 11:17:36 -0800574 case DROP_REASON_BLOCKED:
575 LOGI("Dropped event because the current application is not responding and the user "
576 "has started interating with a different application.");
577 reason = "inbound event was dropped because the current application is not responding "
578 "and the user has started interating with a different application";
579 break;
580 case DROP_REASON_STALE:
581 LOGI("Dropped event because it is stale.");
582 reason = "inbound event was dropped because it is stale";
583 break;
Jeff Brownb6997262010-10-08 22:31:17 -0700584 default:
Jeff Brownb6110c22011-04-01 16:15:13 -0700585 LOG_ASSERT(false);
Jeff Brownb6997262010-10-08 22:31:17 -0700586 return;
587 }
588
589 switch (entry->type) {
Jeff Brownda3d5a92011-03-29 15:11:34 -0700590 case EventEntry::TYPE_KEY: {
591 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
592 synthesizeCancelationEventsForAllConnectionsLocked(options);
Jeff Brownb6997262010-10-08 22:31:17 -0700593 break;
Jeff Brownda3d5a92011-03-29 15:11:34 -0700594 }
Jeff Brownb6997262010-10-08 22:31:17 -0700595 case EventEntry::TYPE_MOTION: {
596 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
597 if (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) {
Jeff Brownda3d5a92011-03-29 15:11:34 -0700598 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
599 synthesizeCancelationEventsForAllConnectionsLocked(options);
Jeff Brownb6997262010-10-08 22:31:17 -0700600 } else {
Jeff Brownda3d5a92011-03-29 15:11:34 -0700601 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
602 synthesizeCancelationEventsForAllConnectionsLocked(options);
Jeff Brownb6997262010-10-08 22:31:17 -0700603 }
604 break;
605 }
606 }
607}
608
609bool InputDispatcher::isAppSwitchKeyCode(int32_t keyCode) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700610 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL;
611}
612
Jeff Brownb6997262010-10-08 22:31:17 -0700613bool InputDispatcher::isAppSwitchKeyEventLocked(KeyEntry* keyEntry) {
614 return ! (keyEntry->flags & AKEY_EVENT_FLAG_CANCELED)
615 && isAppSwitchKeyCode(keyEntry->keyCode)
Jeff Browne20c9e02010-10-11 14:20:19 -0700616 && (keyEntry->policyFlags & POLICY_FLAG_TRUSTED)
Jeff Brownb6997262010-10-08 22:31:17 -0700617 && (keyEntry->policyFlags & POLICY_FLAG_PASS_TO_USER);
618}
619
Jeff Brownb88102f2010-09-08 11:49:43 -0700620bool InputDispatcher::isAppSwitchPendingLocked() {
621 return mAppSwitchDueTime != LONG_LONG_MAX;
622}
623
Jeff Brownb88102f2010-09-08 11:49:43 -0700624void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
625 mAppSwitchDueTime = LONG_LONG_MAX;
626
627#if DEBUG_APP_SWITCH
628 if (handled) {
629 LOGD("App switch has arrived.");
630 } else {
631 LOGD("App switch was abandoned.");
632 }
633#endif
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700634}
635
Jeff Brown928e0542011-01-10 11:17:36 -0800636bool InputDispatcher::isStaleEventLocked(nsecs_t currentTime, EventEntry* entry) {
637 return currentTime - entry->eventTime >= STALE_EVENT_TIMEOUT;
638}
639
Jeff Brown9c3cda02010-06-15 01:31:58 -0700640bool InputDispatcher::runCommandsLockedInterruptible() {
641 if (mCommandQueue.isEmpty()) {
642 return false;
643 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700644
Jeff Brown9c3cda02010-06-15 01:31:58 -0700645 do {
646 CommandEntry* commandEntry = mCommandQueue.dequeueAtHead();
647
648 Command command = commandEntry->command;
649 (this->*command)(commandEntry); // commands are implicitly 'LockedInterruptible'
650
Jeff Brown7fbdc842010-06-17 20:52:56 -0700651 commandEntry->connection.clear();
Jeff Brown9c3cda02010-06-15 01:31:58 -0700652 mAllocator.releaseCommandEntry(commandEntry);
653 } while (! mCommandQueue.isEmpty());
654 return true;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700655}
656
Jeff Brown9c3cda02010-06-15 01:31:58 -0700657InputDispatcher::CommandEntry* InputDispatcher::postCommandLocked(Command command) {
658 CommandEntry* commandEntry = mAllocator.obtainCommandEntry(command);
659 mCommandQueue.enqueueAtTail(commandEntry);
660 return commandEntry;
661}
662
Jeff Brownb88102f2010-09-08 11:49:43 -0700663void InputDispatcher::drainInboundQueueLocked() {
664 while (! mInboundQueue.isEmpty()) {
665 EventEntry* entry = mInboundQueue.dequeueAtHead();
Jeff Brown54a18252010-09-16 14:07:33 -0700666 releaseInboundEventLocked(entry);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700667 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700668}
669
Jeff Brown54a18252010-09-16 14:07:33 -0700670void InputDispatcher::releasePendingEventLocked() {
Jeff Brownb88102f2010-09-08 11:49:43 -0700671 if (mPendingEvent) {
Jeff Brown54a18252010-09-16 14:07:33 -0700672 releaseInboundEventLocked(mPendingEvent);
Jeff Brownb88102f2010-09-08 11:49:43 -0700673 mPendingEvent = NULL;
674 }
675}
676
Jeff Brown54a18252010-09-16 14:07:33 -0700677void InputDispatcher::releaseInboundEventLocked(EventEntry* entry) {
Jeff Brown01ce2e92010-09-26 22:20:12 -0700678 InjectionState* injectionState = entry->injectionState;
679 if (injectionState && injectionState->injectionResult == INPUT_EVENT_INJECTION_PENDING) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700680#if DEBUG_DISPATCH_CYCLE
Jeff Brown01ce2e92010-09-26 22:20:12 -0700681 LOGD("Injected inbound event was dropped.");
Jeff Brownb88102f2010-09-08 11:49:43 -0700682#endif
683 setInjectionResultLocked(entry, INPUT_EVENT_INJECTION_FAILED);
684 }
685 mAllocator.releaseEventEntry(entry);
686}
687
Jeff Brownb88102f2010-09-08 11:49:43 -0700688void InputDispatcher::resetKeyRepeatLocked() {
689 if (mKeyRepeatState.lastKeyEntry) {
690 mAllocator.releaseKeyEntry(mKeyRepeatState.lastKeyEntry);
691 mKeyRepeatState.lastKeyEntry = NULL;
692 }
693}
694
695InputDispatcher::KeyEntry* InputDispatcher::synthesizeKeyRepeatLocked(
Jeff Brownb21fb102010-09-07 10:44:57 -0700696 nsecs_t currentTime, nsecs_t keyRepeatDelay) {
Jeff Brown349703e2010-06-22 01:27:15 -0700697 KeyEntry* entry = mKeyRepeatState.lastKeyEntry;
698
Jeff Brown349703e2010-06-22 01:27:15 -0700699 // Reuse the repeated key entry if it is otherwise unreferenced.
Jeff Browne20c9e02010-10-11 14:20:19 -0700700 uint32_t policyFlags = (entry->policyFlags & POLICY_FLAG_RAW_MASK)
701 | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700702 if (entry->refCount == 1) {
Jeff Brown01ce2e92010-09-26 22:20:12 -0700703 mAllocator.recycleKeyEntry(entry);
Jeff Brown7fbdc842010-06-17 20:52:56 -0700704 entry->eventTime = currentTime;
Jeff Brown7fbdc842010-06-17 20:52:56 -0700705 entry->policyFlags = policyFlags;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700706 entry->repeatCount += 1;
707 } else {
Jeff Brown7fbdc842010-06-17 20:52:56 -0700708 KeyEntry* newEntry = mAllocator.obtainKeyEntry(currentTime,
Jeff Brownc5ed5912010-07-14 18:48:53 -0700709 entry->deviceId, entry->source, policyFlags,
Jeff Brown7fbdc842010-06-17 20:52:56 -0700710 entry->action, entry->flags, entry->keyCode, entry->scanCode,
Jeff Brown00fa7bd2010-07-02 15:37:36 -0700711 entry->metaState, entry->repeatCount + 1, entry->downTime);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700712
713 mKeyRepeatState.lastKeyEntry = newEntry;
714 mAllocator.releaseKeyEntry(entry);
715
716 entry = newEntry;
717 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700718 entry->syntheticRepeat = true;
719
720 // Increment reference count since we keep a reference to the event in
721 // mKeyRepeatState.lastKeyEntry in addition to the one we return.
722 entry->refCount += 1;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700723
Jeff Brownb21fb102010-09-07 10:44:57 -0700724 mKeyRepeatState.nextRepeatTime = currentTime + keyRepeatDelay;
Jeff Brownb88102f2010-09-08 11:49:43 -0700725 return entry;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700726}
727
Jeff Brownb88102f2010-09-08 11:49:43 -0700728bool InputDispatcher::dispatchConfigurationChangedLocked(
729 nsecs_t currentTime, ConfigurationChangedEntry* entry) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700730#if DEBUG_OUTBOUND_EVENT_DETAILS
Jeff Brownb88102f2010-09-08 11:49:43 -0700731 LOGD("dispatchConfigurationChanged - eventTime=%lld", entry->eventTime);
732#endif
733
734 // Reset key repeating in case a keyboard device was added or removed or something.
735 resetKeyRepeatLocked();
736
737 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
738 CommandEntry* commandEntry = postCommandLocked(
739 & InputDispatcher::doNotifyConfigurationChangedInterruptible);
740 commandEntry->eventTime = entry->eventTime;
741 return true;
742}
743
744bool InputDispatcher::dispatchKeyLocked(
745 nsecs_t currentTime, KeyEntry* entry, nsecs_t keyRepeatTimeout,
Jeff Browne20c9e02010-10-11 14:20:19 -0700746 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Jeff Browne46a0a42010-11-02 17:58:22 -0700747 // Preprocessing.
748 if (! entry->dispatchInProgress) {
749 if (entry->repeatCount == 0
750 && entry->action == AKEY_EVENT_ACTION_DOWN
751 && (entry->policyFlags & POLICY_FLAG_TRUSTED)
Jeff Brown0029c662011-03-30 02:25:18 -0700752 && (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
Jeff Browne46a0a42010-11-02 17:58:22 -0700753 if (mKeyRepeatState.lastKeyEntry
754 && mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode) {
755 // We have seen two identical key downs in a row which indicates that the device
756 // driver is automatically generating key repeats itself. We take note of the
757 // repeat here, but we disable our own next key repeat timer since it is clear that
758 // we will not need to synthesize key repeats ourselves.
759 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
760 resetKeyRepeatLocked();
761 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
762 } else {
763 // Not a repeat. Save key down state in case we do see a repeat later.
764 resetKeyRepeatLocked();
765 mKeyRepeatState.nextRepeatTime = entry->eventTime + keyRepeatTimeout;
766 }
767 mKeyRepeatState.lastKeyEntry = entry;
768 entry->refCount += 1;
769 } else if (! entry->syntheticRepeat) {
770 resetKeyRepeatLocked();
771 }
772
Jeff Browne2e01262011-03-02 20:34:30 -0800773 if (entry->repeatCount == 1) {
774 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
775 } else {
776 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
777 }
778
Jeff Browne46a0a42010-11-02 17:58:22 -0700779 entry->dispatchInProgress = true;
780 resetTargetsLocked();
781
782 logOutboundKeyDetailsLocked("dispatchKey - ", entry);
783 }
784
Jeff Brown54a18252010-09-16 14:07:33 -0700785 // Give the policy a chance to intercept the key.
786 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
Jeff Browne20c9e02010-10-11 14:20:19 -0700787 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Jeff Brown54a18252010-09-16 14:07:33 -0700788 CommandEntry* commandEntry = postCommandLocked(
789 & InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
Jeff Browne20c9e02010-10-11 14:20:19 -0700790 if (mFocusedWindow) {
Jeff Brown928e0542011-01-10 11:17:36 -0800791 commandEntry->inputWindowHandle = mFocusedWindow->inputWindowHandle;
Jeff Brown54a18252010-09-16 14:07:33 -0700792 }
793 commandEntry->keyEntry = entry;
794 entry->refCount += 1;
795 return false; // wait for the command to run
796 } else {
797 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
798 }
799 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Jeff Browne20c9e02010-10-11 14:20:19 -0700800 if (*dropReason == DROP_REASON_NOT_DROPPED) {
801 *dropReason = DROP_REASON_POLICY;
802 }
Jeff Brown54a18252010-09-16 14:07:33 -0700803 }
804
805 // Clean up if dropping the event.
Jeff Browne20c9e02010-10-11 14:20:19 -0700806 if (*dropReason != DROP_REASON_NOT_DROPPED) {
Jeff Brown54a18252010-09-16 14:07:33 -0700807 resetTargetsLocked();
Jeff Brown3122e442010-10-11 23:32:49 -0700808 setInjectionResultLocked(entry, *dropReason == DROP_REASON_POLICY
809 ? INPUT_EVENT_INJECTION_SUCCEEDED : INPUT_EVENT_INJECTION_FAILED);
Jeff Brown54a18252010-09-16 14:07:33 -0700810 return true;
811 }
812
Jeff Brownb88102f2010-09-08 11:49:43 -0700813 // Identify targets.
814 if (! mCurrentInputTargetsValid) {
Jeff Brown01ce2e92010-09-26 22:20:12 -0700815 int32_t injectionResult = findFocusedWindowTargetsLocked(currentTime,
816 entry, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700817 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
818 return false;
819 }
820
821 setInjectionResultLocked(entry, injectionResult);
822 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
823 return true;
824 }
825
826 addMonitoringTargetsLocked();
Jeff Brown01ce2e92010-09-26 22:20:12 -0700827 commitTargetsLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -0700828 }
829
830 // Dispatch the key.
831 dispatchEventToCurrentInputTargetsLocked(currentTime, entry, false);
Jeff Brownb88102f2010-09-08 11:49:43 -0700832 return true;
833}
834
835void InputDispatcher::logOutboundKeyDetailsLocked(const char* prefix, const KeyEntry* entry) {
836#if DEBUG_OUTBOUND_EVENT_DETAILS
Jeff Brown90655042010-12-02 13:50:46 -0800837 LOGD("%seventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, "
Jeff Brownb88102f2010-09-08 11:49:43 -0700838 "action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, "
Jeff Browne46a0a42010-11-02 17:58:22 -0700839 "repeatCount=%d, downTime=%lld",
Jeff Brownb88102f2010-09-08 11:49:43 -0700840 prefix,
841 entry->eventTime, entry->deviceId, entry->source, entry->policyFlags,
842 entry->action, entry->flags, entry->keyCode, entry->scanCode, entry->metaState,
Jeff Browne46a0a42010-11-02 17:58:22 -0700843 entry->repeatCount, entry->downTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700844#endif
845}
846
847bool InputDispatcher::dispatchMotionLocked(
Jeff Browne20c9e02010-10-11 14:20:19 -0700848 nsecs_t currentTime, MotionEntry* entry, DropReason* dropReason, nsecs_t* nextWakeupTime) {
Jeff Browne46a0a42010-11-02 17:58:22 -0700849 // Preprocessing.
850 if (! entry->dispatchInProgress) {
851 entry->dispatchInProgress = true;
852 resetTargetsLocked();
853
854 logOutboundMotionDetailsLocked("dispatchMotion - ", entry);
855 }
856
Jeff Brown54a18252010-09-16 14:07:33 -0700857 // Clean up if dropping the event.
Jeff Browne20c9e02010-10-11 14:20:19 -0700858 if (*dropReason != DROP_REASON_NOT_DROPPED) {
Jeff Brown54a18252010-09-16 14:07:33 -0700859 resetTargetsLocked();
Jeff Brown3122e442010-10-11 23:32:49 -0700860 setInjectionResultLocked(entry, *dropReason == DROP_REASON_POLICY
861 ? INPUT_EVENT_INJECTION_SUCCEEDED : INPUT_EVENT_INJECTION_FAILED);
Jeff Brown54a18252010-09-16 14:07:33 -0700862 return true;
863 }
864
Jeff Brownb88102f2010-09-08 11:49:43 -0700865 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
866
867 // Identify targets.
Jeff Browncc0c1592011-02-19 05:07:28 -0800868 bool conflictingPointerActions = false;
Jeff Brownb88102f2010-09-08 11:49:43 -0700869 if (! mCurrentInputTargetsValid) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700870 int32_t injectionResult;
Jeff Browna032cc02011-03-07 16:56:21 -0800871 const MotionSample* splitBatchAfterSample = NULL;
Jeff Brownb88102f2010-09-08 11:49:43 -0700872 if (isPointerEvent) {
873 // Pointer event. (eg. touchscreen)
Jeff Brown01ce2e92010-09-26 22:20:12 -0700874 injectionResult = findTouchedWindowTargetsLocked(currentTime,
Jeff Browna032cc02011-03-07 16:56:21 -0800875 entry, nextWakeupTime, &conflictingPointerActions, &splitBatchAfterSample);
Jeff Brownb88102f2010-09-08 11:49:43 -0700876 } else {
877 // Non touch event. (eg. trackball)
Jeff Brown01ce2e92010-09-26 22:20:12 -0700878 injectionResult = findFocusedWindowTargetsLocked(currentTime,
879 entry, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700880 }
881 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
882 return false;
883 }
884
885 setInjectionResultLocked(entry, injectionResult);
886 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
887 return true;
888 }
889
890 addMonitoringTargetsLocked();
Jeff Brown01ce2e92010-09-26 22:20:12 -0700891 commitTargetsLocked();
Jeff Browna032cc02011-03-07 16:56:21 -0800892
893 // Unbatch the event if necessary by splitting it into two parts after the
894 // motion sample indicated by splitBatchAfterSample.
895 if (splitBatchAfterSample && splitBatchAfterSample->next) {
896#if DEBUG_BATCHING
897 uint32_t originalSampleCount = entry->countSamples();
898#endif
899 MotionSample* nextSample = splitBatchAfterSample->next;
900 MotionEntry* nextEntry = mAllocator.obtainMotionEntry(nextSample->eventTime,
901 entry->deviceId, entry->source, entry->policyFlags,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700902 entry->action, entry->flags,
903 entry->metaState, entry->buttonState, entry->edgeFlags,
Jeff Browna032cc02011-03-07 16:56:21 -0800904 entry->xPrecision, entry->yPrecision, entry->downTime,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700905 entry->pointerCount, entry->pointerProperties, nextSample->pointerCoords);
Jeff Browna032cc02011-03-07 16:56:21 -0800906 if (nextSample != entry->lastSample) {
907 nextEntry->firstSample.next = nextSample->next;
908 nextEntry->lastSample = entry->lastSample;
909 }
910 mAllocator.freeMotionSample(nextSample);
911
912 entry->lastSample = const_cast<MotionSample*>(splitBatchAfterSample);
913 entry->lastSample->next = NULL;
914
915 if (entry->injectionState) {
916 nextEntry->injectionState = entry->injectionState;
917 entry->injectionState->refCount += 1;
918 }
919
920#if DEBUG_BATCHING
921 LOGD("Split batch of %d samples into two parts, first part has %d samples, "
922 "second part has %d samples.", originalSampleCount,
923 entry->countSamples(), nextEntry->countSamples());
924#endif
925
926 mInboundQueue.enqueueAtHead(nextEntry);
927 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700928 }
929
930 // Dispatch the motion.
Jeff Browncc0c1592011-02-19 05:07:28 -0800931 if (conflictingPointerActions) {
Jeff Brownda3d5a92011-03-29 15:11:34 -0700932 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
933 "conflicting pointer actions");
934 synthesizeCancelationEventsForAllConnectionsLocked(options);
Jeff Browncc0c1592011-02-19 05:07:28 -0800935 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700936 dispatchEventToCurrentInputTargetsLocked(currentTime, entry, false);
Jeff Brownb88102f2010-09-08 11:49:43 -0700937 return true;
938}
939
940
941void InputDispatcher::logOutboundMotionDetailsLocked(const char* prefix, const MotionEntry* entry) {
942#if DEBUG_OUTBOUND_EVENT_DETAILS
Jeff Brown90655042010-12-02 13:50:46 -0800943 LOGD("%seventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, "
Jeff Brown85a31762010-09-01 17:01:00 -0700944 "action=0x%x, flags=0x%x, "
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700945 "metaState=0x%x, buttonState=0x%x, "
946 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%lld",
Jeff Brownb88102f2010-09-08 11:49:43 -0700947 prefix,
Jeff Brown85a31762010-09-01 17:01:00 -0700948 entry->eventTime, entry->deviceId, entry->source, entry->policyFlags,
949 entry->action, entry->flags,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700950 entry->metaState, entry->buttonState,
951 entry->edgeFlags, entry->xPrecision, entry->yPrecision,
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700952 entry->downTime);
953
954 // Print the most recent sample that we have available, this may change due to batching.
955 size_t sampleCount = 1;
Jeff Brownb88102f2010-09-08 11:49:43 -0700956 const MotionSample* sample = & entry->firstSample;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700957 for (; sample->next != NULL; sample = sample->next) {
958 sampleCount += 1;
959 }
960 for (uint32_t i = 0; i < entry->pointerCount; i++) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700961 LOGD(" Pointer %d: id=%d, toolType=%d, "
962 "x=%f, y=%f, pressure=%f, size=%f, "
Jeff Brown85a31762010-09-01 17:01:00 -0700963 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
Jeff Brown8d608662010-08-30 03:02:23 -0700964 "orientation=%f",
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700965 i, entry->pointerProperties[i].id,
966 entry->pointerProperties[i].toolType,
Jeff Brownebbd5d12011-02-17 13:01:34 -0800967 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
968 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
969 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
970 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
971 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
972 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
973 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
974 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
975 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700976 }
977
978 // Keep in mind that due to batching, it is possible for the number of samples actually
979 // dispatched to change before the application finally consumed them.
Jeff Brownc5ed5912010-07-14 18:48:53 -0700980 if (entry->action == AMOTION_EVENT_ACTION_MOVE) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700981 LOGD(" ... Total movement samples currently batched %d ...", sampleCount);
982 }
983#endif
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700984}
985
986void InputDispatcher::dispatchEventToCurrentInputTargetsLocked(nsecs_t currentTime,
987 EventEntry* eventEntry, bool resumeWithAppendedMotionSample) {
988#if DEBUG_DISPATCH_CYCLE
Jeff Brown9c3cda02010-06-15 01:31:58 -0700989 LOGD("dispatchEventToCurrentInputTargets - "
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700990 "resumeWithAppendedMotionSample=%s",
Jeff Brownb88102f2010-09-08 11:49:43 -0700991 toString(resumeWithAppendedMotionSample));
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700992#endif
993
Jeff Brownb6110c22011-04-01 16:15:13 -0700994 LOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
Jeff Brown9c3cda02010-06-15 01:31:58 -0700995
Jeff Browne2fe69e2010-10-18 13:21:23 -0700996 pokeUserActivityLocked(eventEntry);
997
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700998 for (size_t i = 0; i < mCurrentInputTargets.size(); i++) {
999 const InputTarget& inputTarget = mCurrentInputTargets.itemAt(i);
1000
Jeff Brown519e0242010-09-15 15:18:56 -07001001 ssize_t connectionIndex = getConnectionIndexLocked(inputTarget.inputChannel);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001002 if (connectionIndex >= 0) {
1003 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
Jeff Brown7fbdc842010-06-17 20:52:56 -07001004 prepareDispatchCycleLocked(currentTime, connection, eventEntry, & inputTarget,
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001005 resumeWithAppendedMotionSample);
1006 } else {
Jeff Brownb6997262010-10-08 22:31:17 -07001007#if DEBUG_FOCUS
1008 LOGD("Dropping event delivery to target with channel '%s' because it "
1009 "is no longer registered with the input dispatcher.",
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001010 inputTarget.inputChannel->getName().string());
Jeff Brownb6997262010-10-08 22:31:17 -07001011#endif
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001012 }
1013 }
1014}
1015
Jeff Brown54a18252010-09-16 14:07:33 -07001016void InputDispatcher::resetTargetsLocked() {
Jeff Brownb88102f2010-09-08 11:49:43 -07001017 mCurrentInputTargetsValid = false;
1018 mCurrentInputTargets.clear();
Jeff Brownb88102f2010-09-08 11:49:43 -07001019 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_NONE;
Jeff Brown928e0542011-01-10 11:17:36 -08001020 mInputTargetWaitApplication.clear();
Jeff Brownb88102f2010-09-08 11:49:43 -07001021}
1022
Jeff Brown01ce2e92010-09-26 22:20:12 -07001023void InputDispatcher::commitTargetsLocked() {
Jeff Brownb88102f2010-09-08 11:49:43 -07001024 mCurrentInputTargetsValid = true;
1025}
1026
1027int32_t InputDispatcher::handleTargetsNotReadyLocked(nsecs_t currentTime,
1028 const EventEntry* entry, const InputApplication* application, const InputWindow* window,
1029 nsecs_t* nextWakeupTime) {
1030 if (application == NULL && window == NULL) {
1031 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY) {
1032#if DEBUG_FOCUS
1033 LOGD("Waiting for system to become ready for input.");
1034#endif
1035 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY;
1036 mInputTargetWaitStartTime = currentTime;
1037 mInputTargetWaitTimeoutTime = LONG_LONG_MAX;
1038 mInputTargetWaitTimeoutExpired = false;
Jeff Brown928e0542011-01-10 11:17:36 -08001039 mInputTargetWaitApplication.clear();
Jeff Brownb88102f2010-09-08 11:49:43 -07001040 }
1041 } else {
1042 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
1043#if DEBUG_FOCUS
Jeff Brown519e0242010-09-15 15:18:56 -07001044 LOGD("Waiting for application to become ready for input: %s",
1045 getApplicationWindowLabelLocked(application, window).string());
Jeff Brownb88102f2010-09-08 11:49:43 -07001046#endif
1047 nsecs_t timeout = window ? window->dispatchingTimeout :
1048 application ? application->dispatchingTimeout : DEFAULT_INPUT_DISPATCHING_TIMEOUT;
1049
1050 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY;
1051 mInputTargetWaitStartTime = currentTime;
1052 mInputTargetWaitTimeoutTime = currentTime + timeout;
1053 mInputTargetWaitTimeoutExpired = false;
Jeff Brown928e0542011-01-10 11:17:36 -08001054 mInputTargetWaitApplication.clear();
1055
1056 if (window && window->inputWindowHandle != NULL) {
1057 mInputTargetWaitApplication =
1058 window->inputWindowHandle->getInputApplicationHandle();
1059 }
1060 if (mInputTargetWaitApplication == NULL && application) {
1061 mInputTargetWaitApplication = application->inputApplicationHandle;
1062 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001063 }
1064 }
1065
1066 if (mInputTargetWaitTimeoutExpired) {
1067 return INPUT_EVENT_INJECTION_TIMED_OUT;
1068 }
1069
1070 if (currentTime >= mInputTargetWaitTimeoutTime) {
Jeff Brown519e0242010-09-15 15:18:56 -07001071 onANRLocked(currentTime, application, window, entry->eventTime, mInputTargetWaitStartTime);
Jeff Brownb88102f2010-09-08 11:49:43 -07001072
1073 // Force poll loop to wake up immediately on next iteration once we get the
1074 // ANR response back from the policy.
1075 *nextWakeupTime = LONG_LONG_MIN;
1076 return INPUT_EVENT_INJECTION_PENDING;
1077 } else {
1078 // Force poll loop to wake up when timeout is due.
1079 if (mInputTargetWaitTimeoutTime < *nextWakeupTime) {
1080 *nextWakeupTime = mInputTargetWaitTimeoutTime;
1081 }
1082 return INPUT_EVENT_INJECTION_PENDING;
1083 }
1084}
1085
Jeff Brown519e0242010-09-15 15:18:56 -07001086void InputDispatcher::resumeAfterTargetsNotReadyTimeoutLocked(nsecs_t newTimeout,
1087 const sp<InputChannel>& inputChannel) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001088 if (newTimeout > 0) {
1089 // Extend the timeout.
1090 mInputTargetWaitTimeoutTime = now() + newTimeout;
1091 } else {
1092 // Give up.
1093 mInputTargetWaitTimeoutExpired = true;
Jeff Brown519e0242010-09-15 15:18:56 -07001094
Jeff Brown01ce2e92010-09-26 22:20:12 -07001095 // Release the touch targets.
1096 mTouchState.reset();
Jeff Brown2a95c2a2010-09-16 12:31:46 -07001097
Jeff Brown519e0242010-09-15 15:18:56 -07001098 // Input state will not be realistic. Mark it out of sync.
Jeff Browndc3e0052010-09-16 11:02:16 -07001099 if (inputChannel.get()) {
1100 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
1101 if (connectionIndex >= 0) {
1102 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
Jeff Brown00045a72010-12-09 18:10:30 -08001103 if (connection->status == Connection::STATUS_NORMAL) {
Jeff Brownda3d5a92011-03-29 15:11:34 -07001104 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
Jeff Brown00045a72010-12-09 18:10:30 -08001105 "application not responding");
Jeff Brownda3d5a92011-03-29 15:11:34 -07001106 synthesizeCancelationEventsForConnectionLocked(connection, options);
Jeff Brown00045a72010-12-09 18:10:30 -08001107 }
Jeff Browndc3e0052010-09-16 11:02:16 -07001108 }
Jeff Brown519e0242010-09-15 15:18:56 -07001109 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001110 }
1111}
1112
Jeff Brown519e0242010-09-15 15:18:56 -07001113nsecs_t InputDispatcher::getTimeSpentWaitingForApplicationLocked(
Jeff Brownb88102f2010-09-08 11:49:43 -07001114 nsecs_t currentTime) {
1115 if (mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
1116 return currentTime - mInputTargetWaitStartTime;
1117 }
1118 return 0;
1119}
1120
1121void InputDispatcher::resetANRTimeoutsLocked() {
1122#if DEBUG_FOCUS
1123 LOGD("Resetting ANR timeouts.");
1124#endif
1125
Jeff Brownb88102f2010-09-08 11:49:43 -07001126 // Reset input target wait timeout.
1127 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_NONE;
1128}
1129
Jeff Brown01ce2e92010-09-26 22:20:12 -07001130int32_t InputDispatcher::findFocusedWindowTargetsLocked(nsecs_t currentTime,
1131 const EventEntry* entry, nsecs_t* nextWakeupTime) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001132 mCurrentInputTargets.clear();
1133
1134 int32_t injectionResult;
1135
1136 // If there is no currently focused window and no focused application
1137 // then drop the event.
1138 if (! mFocusedWindow) {
1139 if (mFocusedApplication) {
1140#if DEBUG_FOCUS
1141 LOGD("Waiting because there is no focused window but there is a "
Jeff Brown519e0242010-09-15 15:18:56 -07001142 "focused application that may eventually add a window: %s.",
1143 getApplicationWindowLabelLocked(mFocusedApplication, NULL).string());
Jeff Brownb88102f2010-09-08 11:49:43 -07001144#endif
1145 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
1146 mFocusedApplication, NULL, nextWakeupTime);
1147 goto Unresponsive;
1148 }
1149
1150 LOGI("Dropping event because there is no focused window or focused application.");
1151 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1152 goto Failed;
1153 }
1154
1155 // Check permissions.
Jeff Brown01ce2e92010-09-26 22:20:12 -07001156 if (! checkInjectionPermission(mFocusedWindow, entry->injectionState)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001157 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1158 goto Failed;
1159 }
1160
1161 // If the currently focused window is paused then keep waiting.
1162 if (mFocusedWindow->paused) {
1163#if DEBUG_FOCUS
1164 LOGD("Waiting because focused window is paused.");
1165#endif
1166 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
1167 mFocusedApplication, mFocusedWindow, nextWakeupTime);
1168 goto Unresponsive;
1169 }
1170
Jeff Brown519e0242010-09-15 15:18:56 -07001171 // If the currently focused window is still working on previous events then keep waiting.
1172 if (! isWindowFinishedWithPreviousInputLocked(mFocusedWindow)) {
1173#if DEBUG_FOCUS
1174 LOGD("Waiting because focused window still processing previous input.");
1175#endif
1176 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
1177 mFocusedApplication, mFocusedWindow, nextWakeupTime);
1178 goto Unresponsive;
1179 }
1180
Jeff Brownb88102f2010-09-08 11:49:43 -07001181 // Success! Output targets.
1182 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
Jeff Browna032cc02011-03-07 16:56:21 -08001183 addWindowTargetLocked(mFocusedWindow,
1184 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS, BitSet32(0));
Jeff Brownb88102f2010-09-08 11:49:43 -07001185
1186 // Done.
1187Failed:
1188Unresponsive:
Jeff Brown519e0242010-09-15 15:18:56 -07001189 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
1190 updateDispatchStatisticsLocked(currentTime, entry,
1191 injectionResult, timeSpentWaitingForApplication);
Jeff Brownb88102f2010-09-08 11:49:43 -07001192#if DEBUG_FOCUS
Jeff Brown519e0242010-09-15 15:18:56 -07001193 LOGD("findFocusedWindow finished: injectionResult=%d, "
1194 "timeSpendWaitingForApplication=%0.1fms",
1195 injectionResult, timeSpentWaitingForApplication / 1000000.0);
Jeff Brownb88102f2010-09-08 11:49:43 -07001196#endif
1197 return injectionResult;
1198}
1199
Jeff Brown01ce2e92010-09-26 22:20:12 -07001200int32_t InputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime,
Jeff Browna032cc02011-03-07 16:56:21 -08001201 const MotionEntry* entry, nsecs_t* nextWakeupTime, bool* outConflictingPointerActions,
1202 const MotionSample** outSplitBatchAfterSample) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001203 enum InjectionPermission {
1204 INJECTION_PERMISSION_UNKNOWN,
1205 INJECTION_PERMISSION_GRANTED,
1206 INJECTION_PERMISSION_DENIED
1207 };
1208
Jeff Brownb88102f2010-09-08 11:49:43 -07001209 mCurrentInputTargets.clear();
1210
1211 nsecs_t startTime = now();
1212
1213 // For security reasons, we defer updating the touch state until we are sure that
1214 // event injection will be allowed.
1215 //
1216 // FIXME In the original code, screenWasOff could never be set to true.
1217 // The reason is that the POLICY_FLAG_WOKE_HERE
1218 // and POLICY_FLAG_BRIGHT_HERE flags were set only when preprocessing raw
1219 // EV_KEY, EV_REL and EV_ABS events. As it happens, the touch event was
1220 // actually enqueued using the policyFlags that appeared in the final EV_SYN
1221 // events upon which no preprocessing took place. So policyFlags was always 0.
1222 // In the new native input dispatcher we're a bit more careful about event
1223 // preprocessing so the touches we receive can actually have non-zero policyFlags.
1224 // Unfortunately we obtain undesirable behavior.
1225 //
1226 // Here's what happens:
1227 //
1228 // When the device dims in anticipation of going to sleep, touches
1229 // in windows which have FLAG_TOUCHABLE_WHEN_WAKING cause
1230 // the device to brighten and reset the user activity timer.
1231 // Touches on other windows (such as the launcher window)
1232 // are dropped. Then after a moment, the device goes to sleep. Oops.
1233 //
1234 // Also notice how screenWasOff was being initialized using POLICY_FLAG_BRIGHT_HERE
1235 // instead of POLICY_FLAG_WOKE_HERE...
1236 //
1237 bool screenWasOff = false; // original policy: policyFlags & POLICY_FLAG_BRIGHT_HERE;
1238
1239 int32_t action = entry->action;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001240 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Jeff Brownb88102f2010-09-08 11:49:43 -07001241
1242 // Update the touch state as needed based on the properties of the touch event.
Jeff Brown01ce2e92010-09-26 22:20:12 -07001243 int32_t injectionResult = INPUT_EVENT_INJECTION_PENDING;
1244 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
Jeff Browna032cc02011-03-07 16:56:21 -08001245 const InputWindow* newHoverWindow = NULL;
Jeff Browncc0c1592011-02-19 05:07:28 -08001246
1247 bool isSplit = mTouchState.split;
1248 bool wrongDevice = mTouchState.down
1249 && (mTouchState.deviceId != entry->deviceId
1250 || mTouchState.source != entry->source);
Jeff Browna032cc02011-03-07 16:56:21 -08001251 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE
1252 || maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER
1253 || maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1254 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN
1255 || maskedAction == AMOTION_EVENT_ACTION_SCROLL
1256 || isHoverAction);
1257 if (newGesture) {
Jeff Browncc0c1592011-02-19 05:07:28 -08001258 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
1259 if (wrongDevice && !down) {
1260 mTempTouchState.copyFrom(mTouchState);
1261 } else {
1262 mTempTouchState.reset();
1263 mTempTouchState.down = down;
1264 mTempTouchState.deviceId = entry->deviceId;
1265 mTempTouchState.source = entry->source;
1266 isSplit = false;
1267 wrongDevice = false;
1268 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001269 } else {
1270 mTempTouchState.copyFrom(mTouchState);
Jeff Browncc0c1592011-02-19 05:07:28 -08001271 }
1272 if (wrongDevice) {
Jeff Browna2cc28d2011-03-25 11:58:46 -07001273#if DEBUG_FOCUS
Jeff Browncc0c1592011-02-19 05:07:28 -08001274 LOGD("Dropping event because a pointer for a different device is already down.");
Jeff Brown95712852011-01-04 19:41:59 -08001275#endif
Jeff Browncc0c1592011-02-19 05:07:28 -08001276 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1277 goto Failed;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001278 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001279
Jeff Browna032cc02011-03-07 16:56:21 -08001280 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
Jeff Brown33bbfd22011-02-24 20:55:35 -08001281 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
Jeff Brownb88102f2010-09-08 11:49:43 -07001282
Jeff Browna032cc02011-03-07 16:56:21 -08001283 const MotionSample* sample = &entry->firstSample;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001284 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Jeff Browna032cc02011-03-07 16:56:21 -08001285 int32_t x = int32_t(sample->pointerCoords[pointerIndex].
Jeff Brownebbd5d12011-02-17 13:01:34 -08001286 getAxisValue(AMOTION_EVENT_AXIS_X));
Jeff Browna032cc02011-03-07 16:56:21 -08001287 int32_t y = int32_t(sample->pointerCoords[pointerIndex].
Jeff Brownebbd5d12011-02-17 13:01:34 -08001288 getAxisValue(AMOTION_EVENT_AXIS_Y));
Jeff Brown01ce2e92010-09-26 22:20:12 -07001289 const InputWindow* newTouchedWindow = NULL;
1290 const InputWindow* topErrorWindow = NULL;
Jeff Browna032cc02011-03-07 16:56:21 -08001291 bool isTouchModal = false;
Jeff Brownb88102f2010-09-08 11:49:43 -07001292
1293 // Traverse windows from front to back to find touched window and outside targets.
1294 size_t numWindows = mWindows.size();
1295 for (size_t i = 0; i < numWindows; i++) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001296 const InputWindow* window = & mWindows.editItemAt(i);
Jeff Brownb88102f2010-09-08 11:49:43 -07001297 int32_t flags = window->layoutParamsFlags;
1298
1299 if (flags & InputWindow::FLAG_SYSTEM_ERROR) {
1300 if (! topErrorWindow) {
1301 topErrorWindow = window;
1302 }
1303 }
1304
1305 if (window->visible) {
1306 if (! (flags & InputWindow::FLAG_NOT_TOUCHABLE)) {
Jeff Browna032cc02011-03-07 16:56:21 -08001307 isTouchModal = (flags & (InputWindow::FLAG_NOT_FOCUSABLE
Jeff Brownb88102f2010-09-08 11:49:43 -07001308 | InputWindow::FLAG_NOT_TOUCH_MODAL)) == 0;
Jeff Brownfbf09772011-01-16 14:06:57 -08001309 if (isTouchModal || window->touchableRegionContainsPoint(x, y)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001310 if (! screenWasOff || flags & InputWindow::FLAG_TOUCHABLE_WHEN_WAKING) {
1311 newTouchedWindow = window;
Jeff Brownb88102f2010-09-08 11:49:43 -07001312 }
1313 break; // found touched window, exit window loop
1314 }
1315 }
1316
Jeff Brown01ce2e92010-09-26 22:20:12 -07001317 if (maskedAction == AMOTION_EVENT_ACTION_DOWN
1318 && (flags & InputWindow::FLAG_WATCH_OUTSIDE_TOUCH)) {
Jeff Browna032cc02011-03-07 16:56:21 -08001319 int32_t outsideTargetFlags = InputTarget::FLAG_DISPATCH_AS_OUTSIDE;
Jeff Brown19dfc832010-10-05 12:26:23 -07001320 if (isWindowObscuredAtPointLocked(window, x, y)) {
1321 outsideTargetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1322 }
1323
1324 mTempTouchState.addOrUpdateWindow(window, outsideTargetFlags, BitSet32(0));
Jeff Brownb88102f2010-09-08 11:49:43 -07001325 }
1326 }
1327 }
1328
1329 // If there is an error window but it is not taking focus (typically because
1330 // it is invisible) then wait for it. Any other focused window may in
1331 // fact be in ANR state.
1332 if (topErrorWindow && newTouchedWindow != topErrorWindow) {
1333#if DEBUG_FOCUS
1334 LOGD("Waiting because system error window is pending.");
1335#endif
1336 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
1337 NULL, NULL, nextWakeupTime);
1338 injectionPermission = INJECTION_PERMISSION_UNKNOWN;
1339 goto Unresponsive;
1340 }
1341
Jeff Brown01ce2e92010-09-26 22:20:12 -07001342 // Figure out whether splitting will be allowed for this window.
Jeff Brown46e75292010-11-10 16:53:45 -08001343 if (newTouchedWindow && newTouchedWindow->supportsSplitTouch()) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001344 // New window supports splitting.
1345 isSplit = true;
1346 } else if (isSplit) {
1347 // New window does not support splitting but we have already split events.
1348 // Assign the pointer to the first foreground window we find.
1349 // (May be NULL which is why we put this code block before the next check.)
1350 newTouchedWindow = mTempTouchState.getFirstForegroundWindow();
1351 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001352
Jeff Brownb88102f2010-09-08 11:49:43 -07001353 // If we did not find a touched window then fail.
1354 if (! newTouchedWindow) {
1355 if (mFocusedApplication) {
1356#if DEBUG_FOCUS
1357 LOGD("Waiting because there is no touched window but there is a "
Jeff Brown519e0242010-09-15 15:18:56 -07001358 "focused application that may eventually add a new window: %s.",
1359 getApplicationWindowLabelLocked(mFocusedApplication, NULL).string());
Jeff Brownb88102f2010-09-08 11:49:43 -07001360#endif
1361 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
1362 mFocusedApplication, NULL, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -07001363 goto Unresponsive;
1364 }
1365
1366 LOGI("Dropping event because there is no touched window or focused application.");
1367 injectionResult = INPUT_EVENT_INJECTION_FAILED;
Jeff Brownb88102f2010-09-08 11:49:43 -07001368 goto Failed;
1369 }
1370
Jeff Brown19dfc832010-10-05 12:26:23 -07001371 // Set target flags.
Jeff Browna032cc02011-03-07 16:56:21 -08001372 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
Jeff Brown19dfc832010-10-05 12:26:23 -07001373 if (isSplit) {
1374 targetFlags |= InputTarget::FLAG_SPLIT;
1375 }
1376 if (isWindowObscuredAtPointLocked(newTouchedWindow, x, y)) {
1377 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1378 }
1379
Jeff Browna032cc02011-03-07 16:56:21 -08001380 // Update hover state.
1381 if (isHoverAction) {
1382 newHoverWindow = newTouchedWindow;
1383
1384 // Ensure all subsequent motion samples are also within the touched window.
1385 // Set *outSplitBatchAfterSample to the sample before the first one that is not
1386 // within the touched window.
1387 if (!isTouchModal) {
1388 while (sample->next) {
1389 if (!newHoverWindow->touchableRegionContainsPoint(
1390 sample->next->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X),
1391 sample->next->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y))) {
1392 *outSplitBatchAfterSample = sample;
1393 break;
1394 }
1395 sample = sample->next;
1396 }
1397 }
1398 } else if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
1399 newHoverWindow = mLastHoverWindow;
1400 }
1401
Jeff Brown01ce2e92010-09-26 22:20:12 -07001402 // Update the temporary touch state.
1403 BitSet32 pointerIds;
1404 if (isSplit) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07001405 uint32_t pointerId = entry->pointerProperties[pointerIndex].id;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001406 pointerIds.markBit(pointerId);
Jeff Brownb88102f2010-09-08 11:49:43 -07001407 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001408 mTempTouchState.addOrUpdateWindow(newTouchedWindow, targetFlags, pointerIds);
Jeff Brownb88102f2010-09-08 11:49:43 -07001409 } else {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001410 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
Jeff Brownb88102f2010-09-08 11:49:43 -07001411
1412 // If the pointer is not currently down, then ignore the event.
Jeff Brown01ce2e92010-09-26 22:20:12 -07001413 if (! mTempTouchState.down) {
Jeff Browna2cc28d2011-03-25 11:58:46 -07001414#if DEBUG_FOCUS
Jeff Brown76860e32010-10-25 17:37:46 -07001415 LOGD("Dropping event because the pointer is not down or we previously "
1416 "dropped the pointer down event.");
1417#endif
Jeff Brownb88102f2010-09-08 11:49:43 -07001418 injectionResult = INPUT_EVENT_INJECTION_FAILED;
Jeff Brownb88102f2010-09-08 11:49:43 -07001419 goto Failed;
1420 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001421 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001422
Jeff Browna032cc02011-03-07 16:56:21 -08001423 if (newHoverWindow != mLastHoverWindow) {
1424 // Split the batch here so we send exactly one sample as part of ENTER or EXIT.
1425 *outSplitBatchAfterSample = &entry->firstSample;
1426
1427 // Let the previous window know that the hover sequence is over.
1428 if (mLastHoverWindow) {
1429#if DEBUG_HOVER
1430 LOGD("Sending hover exit event to window %s.", mLastHoverWindow->name.string());
1431#endif
1432 mTempTouchState.addOrUpdateWindow(mLastHoverWindow,
1433 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
1434 }
1435
1436 // Let the new window know that the hover sequence is starting.
1437 if (newHoverWindow) {
1438#if DEBUG_HOVER
1439 LOGD("Sending hover enter event to window %s.", newHoverWindow->name.string());
1440#endif
1441 mTempTouchState.addOrUpdateWindow(newHoverWindow,
1442 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER, BitSet32(0));
1443 }
1444 }
1445
Jeff Brown01ce2e92010-09-26 22:20:12 -07001446 // Check permission to inject into all touched foreground windows and ensure there
1447 // is at least one touched foreground window.
1448 {
1449 bool haveForegroundWindow = false;
1450 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1451 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1452 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1453 haveForegroundWindow = true;
1454 if (! checkInjectionPermission(touchedWindow.window, entry->injectionState)) {
1455 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1456 injectionPermission = INJECTION_PERMISSION_DENIED;
1457 goto Failed;
1458 }
1459 }
1460 }
1461 if (! haveForegroundWindow) {
Jeff Browna2cc28d2011-03-25 11:58:46 -07001462#if DEBUG_FOCUS
Jeff Brown01ce2e92010-09-26 22:20:12 -07001463 LOGD("Dropping event because there is no touched foreground window to receive it.");
Jeff Brownb88102f2010-09-08 11:49:43 -07001464#endif
1465 injectionResult = INPUT_EVENT_INJECTION_FAILED;
Jeff Brownb88102f2010-09-08 11:49:43 -07001466 goto Failed;
1467 }
1468
Jeff Brown01ce2e92010-09-26 22:20:12 -07001469 // Permission granted to injection into all touched foreground windows.
1470 injectionPermission = INJECTION_PERMISSION_GRANTED;
1471 }
Jeff Brown519e0242010-09-15 15:18:56 -07001472
Jeff Brown01ce2e92010-09-26 22:20:12 -07001473 // Ensure all touched foreground windows are ready for new input.
1474 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1475 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1476 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1477 // If the touched window is paused then keep waiting.
1478 if (touchedWindow.window->paused) {
Jeff Browna2cc28d2011-03-25 11:58:46 -07001479#if DEBUG_FOCUS
Jeff Brown01ce2e92010-09-26 22:20:12 -07001480 LOGD("Waiting because touched window is paused.");
Jeff Brown519e0242010-09-15 15:18:56 -07001481#endif
Jeff Brown01ce2e92010-09-26 22:20:12 -07001482 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
1483 NULL, touchedWindow.window, nextWakeupTime);
1484 goto Unresponsive;
1485 }
1486
1487 // If the touched window is still working on previous events then keep waiting.
1488 if (! isWindowFinishedWithPreviousInputLocked(touchedWindow.window)) {
1489#if DEBUG_FOCUS
1490 LOGD("Waiting because touched window still processing previous input.");
1491#endif
1492 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
1493 NULL, touchedWindow.window, nextWakeupTime);
1494 goto Unresponsive;
1495 }
1496 }
1497 }
1498
1499 // If this is the first pointer going down and the touched window has a wallpaper
1500 // then also add the touched wallpaper windows so they are locked in for the duration
1501 // of the touch gesture.
Jeff Brown33bbfd22011-02-24 20:55:35 -08001502 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
1503 // engine only supports touch events. We would need to add a mechanism similar
1504 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
1505 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001506 const InputWindow* foregroundWindow = mTempTouchState.getFirstForegroundWindow();
1507 if (foregroundWindow->hasWallpaper) {
1508 for (size_t i = 0; i < mWindows.size(); i++) {
1509 const InputWindow* window = & mWindows[i];
1510 if (window->layoutParamsType == InputWindow::TYPE_WALLPAPER) {
Jeff Brown19dfc832010-10-05 12:26:23 -07001511 mTempTouchState.addOrUpdateWindow(window,
Jeff Browna032cc02011-03-07 16:56:21 -08001512 InputTarget::FLAG_WINDOW_IS_OBSCURED
1513 | InputTarget::FLAG_DISPATCH_AS_IS,
1514 BitSet32(0));
Jeff Brown01ce2e92010-09-26 22:20:12 -07001515 }
1516 }
1517 }
1518 }
1519
Jeff Brownb88102f2010-09-08 11:49:43 -07001520 // Success! Output targets.
1521 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
Jeff Brownb88102f2010-09-08 11:49:43 -07001522
Jeff Brown01ce2e92010-09-26 22:20:12 -07001523 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1524 const TouchedWindow& touchedWindow = mTempTouchState.windows.itemAt(i);
1525 addWindowTargetLocked(touchedWindow.window, touchedWindow.targetFlags,
1526 touchedWindow.pointerIds);
Jeff Brownb88102f2010-09-08 11:49:43 -07001527 }
1528
Jeff Browna032cc02011-03-07 16:56:21 -08001529 // Drop the outside or hover touch windows since we will not care about them
1530 // in the next iteration.
1531 mTempTouchState.filterNonAsIsTouchWindows();
Jeff Brown01ce2e92010-09-26 22:20:12 -07001532
Jeff Brownb88102f2010-09-08 11:49:43 -07001533Failed:
1534 // Check injection permission once and for all.
1535 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001536 if (checkInjectionPermission(NULL, entry->injectionState)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001537 injectionPermission = INJECTION_PERMISSION_GRANTED;
1538 } else {
1539 injectionPermission = INJECTION_PERMISSION_DENIED;
1540 }
1541 }
1542
1543 // Update final pieces of touch state if the injector had permission.
1544 if (injectionPermission == INJECTION_PERMISSION_GRANTED) {
Jeff Brown95712852011-01-04 19:41:59 -08001545 if (!wrongDevice) {
1546 if (maskedAction == AMOTION_EVENT_ACTION_UP
Jeff Browncc0c1592011-02-19 05:07:28 -08001547 || maskedAction == AMOTION_EVENT_ACTION_CANCEL
Jeff Browna032cc02011-03-07 16:56:21 -08001548 || isHoverAction) {
Jeff Brown95712852011-01-04 19:41:59 -08001549 // All pointers up or canceled.
Jeff Brown33bbfd22011-02-24 20:55:35 -08001550 mTouchState.reset();
Jeff Brown95712852011-01-04 19:41:59 -08001551 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1552 // First pointer went down.
1553 if (mTouchState.down) {
Jeff Browncc0c1592011-02-19 05:07:28 -08001554 *outConflictingPointerActions = true;
Jeff Brownb6997262010-10-08 22:31:17 -07001555#if DEBUG_FOCUS
Jeff Brown95712852011-01-04 19:41:59 -08001556 LOGD("Pointer down received while already down.");
Jeff Brownb6997262010-10-08 22:31:17 -07001557#endif
Jeff Brown95712852011-01-04 19:41:59 -08001558 }
Jeff Brown33bbfd22011-02-24 20:55:35 -08001559 mTouchState.copyFrom(mTempTouchState);
Jeff Brown95712852011-01-04 19:41:59 -08001560 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
1561 // One pointer went up.
1562 if (isSplit) {
1563 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07001564 uint32_t pointerId = entry->pointerProperties[pointerIndex].id;
Jeff Brownb88102f2010-09-08 11:49:43 -07001565
Jeff Brown95712852011-01-04 19:41:59 -08001566 for (size_t i = 0; i < mTempTouchState.windows.size(); ) {
1567 TouchedWindow& touchedWindow = mTempTouchState.windows.editItemAt(i);
1568 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
1569 touchedWindow.pointerIds.clearBit(pointerId);
1570 if (touchedWindow.pointerIds.isEmpty()) {
1571 mTempTouchState.windows.removeAt(i);
1572 continue;
1573 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001574 }
Jeff Brown95712852011-01-04 19:41:59 -08001575 i += 1;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001576 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001577 }
Jeff Brown33bbfd22011-02-24 20:55:35 -08001578 mTouchState.copyFrom(mTempTouchState);
1579 } else if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
1580 // Discard temporary touch state since it was only valid for this action.
1581 } else {
1582 // Save changes to touch state as-is for all other actions.
1583 mTouchState.copyFrom(mTempTouchState);
Jeff Brownb88102f2010-09-08 11:49:43 -07001584 }
Jeff Browna032cc02011-03-07 16:56:21 -08001585
1586 // Update hover state.
1587 mLastHoverWindow = newHoverWindow;
Jeff Brown95712852011-01-04 19:41:59 -08001588 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001589 } else {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001590#if DEBUG_FOCUS
1591 LOGD("Not updating touch focus because injection was denied.");
1592#endif
Jeff Brownb88102f2010-09-08 11:49:43 -07001593 }
1594
1595Unresponsive:
Jeff Brown120a4592010-10-27 18:43:51 -07001596 // Reset temporary touch state to ensure we release unnecessary references to input channels.
1597 mTempTouchState.reset();
1598
Jeff Brown519e0242010-09-15 15:18:56 -07001599 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
1600 updateDispatchStatisticsLocked(currentTime, entry,
1601 injectionResult, timeSpentWaitingForApplication);
Jeff Brownb88102f2010-09-08 11:49:43 -07001602#if DEBUG_FOCUS
Jeff Brown01ce2e92010-09-26 22:20:12 -07001603 LOGD("findTouchedWindow finished: injectionResult=%d, injectionPermission=%d, "
1604 "timeSpentWaitingForApplication=%0.1fms",
Jeff Brown519e0242010-09-15 15:18:56 -07001605 injectionResult, injectionPermission, timeSpentWaitingForApplication / 1000000.0);
Jeff Brownb88102f2010-09-08 11:49:43 -07001606#endif
1607 return injectionResult;
1608}
1609
Jeff Brown01ce2e92010-09-26 22:20:12 -07001610void InputDispatcher::addWindowTargetLocked(const InputWindow* window, int32_t targetFlags,
1611 BitSet32 pointerIds) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001612 mCurrentInputTargets.push();
1613
1614 InputTarget& target = mCurrentInputTargets.editTop();
1615 target.inputChannel = window->inputChannel;
1616 target.flags = targetFlags;
Jeff Brownb88102f2010-09-08 11:49:43 -07001617 target.xOffset = - window->frameLeft;
1618 target.yOffset = - window->frameTop;
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001619 target.scaleFactor = window->scaleFactor;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001620 target.pointerIds = pointerIds;
Jeff Brownb88102f2010-09-08 11:49:43 -07001621}
1622
1623void InputDispatcher::addMonitoringTargetsLocked() {
1624 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
1625 mCurrentInputTargets.push();
1626
1627 InputTarget& target = mCurrentInputTargets.editTop();
1628 target.inputChannel = mMonitoringChannels[i];
Jeff Brownb6110c22011-04-01 16:15:13 -07001629 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
Jeff Brownb88102f2010-09-08 11:49:43 -07001630 target.xOffset = 0;
1631 target.yOffset = 0;
Jeff Brownb6110c22011-04-01 16:15:13 -07001632 target.pointerIds.clear();
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001633 target.scaleFactor = 1.0f;
Jeff Brownb88102f2010-09-08 11:49:43 -07001634 }
1635}
1636
1637bool InputDispatcher::checkInjectionPermission(const InputWindow* window,
Jeff Brown01ce2e92010-09-26 22:20:12 -07001638 const InjectionState* injectionState) {
1639 if (injectionState
Jeff Brownb6997262010-10-08 22:31:17 -07001640 && (window == NULL || window->ownerUid != injectionState->injectorUid)
1641 && !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
1642 if (window) {
1643 LOGW("Permission denied: injecting event from pid %d uid %d to window "
1644 "with input channel %s owned by uid %d",
1645 injectionState->injectorPid, injectionState->injectorUid,
1646 window->inputChannel->getName().string(),
1647 window->ownerUid);
1648 } else {
1649 LOGW("Permission denied: injecting event from pid %d uid %d",
1650 injectionState->injectorPid, injectionState->injectorUid);
Jeff Brownb88102f2010-09-08 11:49:43 -07001651 }
Jeff Brownb6997262010-10-08 22:31:17 -07001652 return false;
Jeff Brownb88102f2010-09-08 11:49:43 -07001653 }
1654 return true;
1655}
1656
Jeff Brown19dfc832010-10-05 12:26:23 -07001657bool InputDispatcher::isWindowObscuredAtPointLocked(
1658 const InputWindow* window, int32_t x, int32_t y) const {
Jeff Brownb88102f2010-09-08 11:49:43 -07001659 size_t numWindows = mWindows.size();
1660 for (size_t i = 0; i < numWindows; i++) {
1661 const InputWindow* other = & mWindows.itemAt(i);
1662 if (other == window) {
1663 break;
1664 }
Jeff Brown19dfc832010-10-05 12:26:23 -07001665 if (other->visible && ! other->isTrustedOverlay() && other->frameContainsPoint(x, y)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001666 return true;
1667 }
1668 }
1669 return false;
1670}
1671
Jeff Brown519e0242010-09-15 15:18:56 -07001672bool InputDispatcher::isWindowFinishedWithPreviousInputLocked(const InputWindow* window) {
1673 ssize_t connectionIndex = getConnectionIndexLocked(window->inputChannel);
1674 if (connectionIndex >= 0) {
1675 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
1676 return connection->outboundQueue.isEmpty();
1677 } else {
1678 return true;
1679 }
1680}
1681
1682String8 InputDispatcher::getApplicationWindowLabelLocked(const InputApplication* application,
1683 const InputWindow* window) {
1684 if (application) {
1685 if (window) {
1686 String8 label(application->name);
1687 label.append(" - ");
1688 label.append(window->name);
1689 return label;
1690 } else {
1691 return application->name;
1692 }
1693 } else if (window) {
1694 return window->name;
1695 } else {
1696 return String8("<unknown application or window>");
1697 }
1698}
1699
Jeff Browne2fe69e2010-10-18 13:21:23 -07001700void InputDispatcher::pokeUserActivityLocked(const EventEntry* eventEntry) {
Jeff Brown56194eb2011-03-02 19:23:13 -08001701 int32_t eventType = POWER_MANAGER_OTHER_EVENT;
Jeff Brown4d396052010-10-29 21:50:21 -07001702 switch (eventEntry->type) {
1703 case EventEntry::TYPE_MOTION: {
Jeff Browne2fe69e2010-10-18 13:21:23 -07001704 const MotionEntry* motionEntry = static_cast<const MotionEntry*>(eventEntry);
Jeff Brown4d396052010-10-29 21:50:21 -07001705 if (motionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
1706 return;
1707 }
1708
Jeff Brown56194eb2011-03-02 19:23:13 -08001709 if (MotionEvent::isTouchEvent(motionEntry->source, motionEntry->action)) {
Joe Onorato1a542c72010-11-08 09:48:20 -08001710 eventType = POWER_MANAGER_TOUCH_EVENT;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001711 }
Jeff Brown4d396052010-10-29 21:50:21 -07001712 break;
1713 }
1714 case EventEntry::TYPE_KEY: {
1715 const KeyEntry* keyEntry = static_cast<const KeyEntry*>(eventEntry);
1716 if (keyEntry->flags & AKEY_EVENT_FLAG_CANCELED) {
1717 return;
1718 }
Jeff Brown56194eb2011-03-02 19:23:13 -08001719 eventType = POWER_MANAGER_BUTTON_EVENT;
Jeff Brown4d396052010-10-29 21:50:21 -07001720 break;
1721 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001722 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001723
Jeff Brownb88102f2010-09-08 11:49:43 -07001724 CommandEntry* commandEntry = postCommandLocked(
1725 & InputDispatcher::doPokeUserActivityLockedInterruptible);
Jeff Browne2fe69e2010-10-18 13:21:23 -07001726 commandEntry->eventTime = eventEntry->eventTime;
Jeff Brownb88102f2010-09-08 11:49:43 -07001727 commandEntry->userActivityEventType = eventType;
1728}
1729
Jeff Brown7fbdc842010-06-17 20:52:56 -07001730void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
1731 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget,
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001732 bool resumeWithAppendedMotionSample) {
1733#if DEBUG_DISPATCH_CYCLE
Jeff Brown519e0242010-09-15 15:18:56 -07001734 LOGD("channel '%s' ~ prepareDispatchCycle - flags=%d, "
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001735 "xOffset=%f, yOffset=%f, scaleFactor=%f"
Jeff Brown83c09682010-12-23 17:50:18 -08001736 "pointerIds=0x%x, "
Jeff Brown01ce2e92010-09-26 22:20:12 -07001737 "resumeWithAppendedMotionSample=%s",
Jeff Brown519e0242010-09-15 15:18:56 -07001738 connection->getInputChannelName(), inputTarget->flags,
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001739 inputTarget->xOffset, inputTarget->yOffset,
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001740 inputTarget->scaleFactor, inputTarget->pointerIds.value,
Jeff Brownb88102f2010-09-08 11:49:43 -07001741 toString(resumeWithAppendedMotionSample));
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001742#endif
1743
Jeff Brown01ce2e92010-09-26 22:20:12 -07001744 // Make sure we are never called for streaming when splitting across multiple windows.
1745 bool isSplit = inputTarget->flags & InputTarget::FLAG_SPLIT;
Jeff Brownb6110c22011-04-01 16:15:13 -07001746 LOG_ASSERT(! (resumeWithAppendedMotionSample && isSplit));
Jeff Brown01ce2e92010-09-26 22:20:12 -07001747
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001748 // Skip this event if the connection status is not normal.
Jeff Brown519e0242010-09-15 15:18:56 -07001749 // We don't want to enqueue additional outbound events if the connection is broken.
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001750 if (connection->status != Connection::STATUS_NORMAL) {
Jeff Brownb6997262010-10-08 22:31:17 -07001751#if DEBUG_DISPATCH_CYCLE
1752 LOGD("channel '%s' ~ Dropping event because the channel status is %s",
Jeff Brownb88102f2010-09-08 11:49:43 -07001753 connection->getInputChannelName(), connection->getStatusLabel());
Jeff Brownb6997262010-10-08 22:31:17 -07001754#endif
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001755 return;
1756 }
1757
Jeff Brown01ce2e92010-09-26 22:20:12 -07001758 // Split a motion event if needed.
1759 if (isSplit) {
Jeff Brownb6110c22011-04-01 16:15:13 -07001760 LOG_ASSERT(eventEntry->type == EventEntry::TYPE_MOTION);
Jeff Brown01ce2e92010-09-26 22:20:12 -07001761
1762 MotionEntry* originalMotionEntry = static_cast<MotionEntry*>(eventEntry);
1763 if (inputTarget->pointerIds.count() != originalMotionEntry->pointerCount) {
1764 MotionEntry* splitMotionEntry = splitMotionEvent(
1765 originalMotionEntry, inputTarget->pointerIds);
Jeff Brown58a2da82011-01-25 16:02:22 -08001766 if (!splitMotionEntry) {
1767 return; // split event was dropped
1768 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001769#if DEBUG_FOCUS
1770 LOGD("channel '%s' ~ Split motion event.",
1771 connection->getInputChannelName());
1772 logOutboundMotionDetailsLocked(" ", splitMotionEntry);
1773#endif
1774 eventEntry = splitMotionEntry;
1775 }
1776 }
1777
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001778 // Resume the dispatch cycle with a freshly appended motion sample.
1779 // First we check that the last dispatch entry in the outbound queue is for the same
1780 // motion event to which we appended the motion sample. If we find such a dispatch
1781 // entry, and if it is currently in progress then we try to stream the new sample.
1782 bool wasEmpty = connection->outboundQueue.isEmpty();
1783
1784 if (! wasEmpty && resumeWithAppendedMotionSample) {
1785 DispatchEntry* motionEventDispatchEntry =
1786 connection->findQueuedDispatchEntryForEvent(eventEntry);
1787 if (motionEventDispatchEntry) {
1788 // If the dispatch entry is not in progress, then we must be busy dispatching an
1789 // earlier event. Not a problem, the motion event is on the outbound queue and will
1790 // be dispatched later.
1791 if (! motionEventDispatchEntry->inProgress) {
1792#if DEBUG_BATCHING
1793 LOGD("channel '%s' ~ Not streaming because the motion event has "
1794 "not yet been dispatched. "
1795 "(Waiting for earlier events to be consumed.)",
1796 connection->getInputChannelName());
1797#endif
1798 return;
1799 }
1800
1801 // If the dispatch entry is in progress but it already has a tail of pending
1802 // motion samples, then it must mean that the shared memory buffer filled up.
1803 // Not a problem, when this dispatch cycle is finished, we will eventually start
1804 // a new dispatch cycle to process the tail and that tail includes the newly
1805 // appended motion sample.
1806 if (motionEventDispatchEntry->tailMotionSample) {
1807#if DEBUG_BATCHING
1808 LOGD("channel '%s' ~ Not streaming because no new samples can "
1809 "be appended to the motion event in this dispatch cycle. "
1810 "(Waiting for next dispatch cycle to start.)",
1811 connection->getInputChannelName());
1812#endif
1813 return;
1814 }
1815
1816 // The dispatch entry is in progress and is still potentially open for streaming.
1817 // Try to stream the new motion sample. This might fail if the consumer has already
1818 // consumed the motion event (or if the channel is broken).
Jeff Brown01ce2e92010-09-26 22:20:12 -07001819 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
1820 MotionSample* appendedMotionSample = motionEntry->lastSample;
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001821 status_t status;
1822 if (motionEventDispatchEntry->scaleFactor == 1.0f) {
1823 status = connection->inputPublisher.appendMotionSample(
1824 appendedMotionSample->eventTime, appendedMotionSample->pointerCoords);
1825 } else {
1826 PointerCoords scaledCoords[MAX_POINTERS];
1827 for (size_t i = 0; i < motionEntry->pointerCount; i++) {
1828 scaledCoords[i] = appendedMotionSample->pointerCoords[i];
1829 scaledCoords[i].scale(motionEventDispatchEntry->scaleFactor);
1830 }
1831 status = connection->inputPublisher.appendMotionSample(
1832 appendedMotionSample->eventTime, scaledCoords);
1833 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001834 if (status == OK) {
1835#if DEBUG_BATCHING
1836 LOGD("channel '%s' ~ Successfully streamed new motion sample.",
1837 connection->getInputChannelName());
1838#endif
1839 return;
1840 }
1841
1842#if DEBUG_BATCHING
1843 if (status == NO_MEMORY) {
1844 LOGD("channel '%s' ~ Could not append motion sample to currently "
1845 "dispatched move event because the shared memory buffer is full. "
1846 "(Waiting for next dispatch cycle to start.)",
1847 connection->getInputChannelName());
1848 } else if (status == status_t(FAILED_TRANSACTION)) {
1849 LOGD("channel '%s' ~ Could not append motion sample to currently "
Jeff Brown349703e2010-06-22 01:27:15 -07001850 "dispatched move event because the event has already been consumed. "
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001851 "(Waiting for next dispatch cycle to start.)",
1852 connection->getInputChannelName());
1853 } else {
1854 LOGD("channel '%s' ~ Could not append motion sample to currently "
1855 "dispatched move event due to an error, status=%d. "
1856 "(Waiting for next dispatch cycle to start.)",
1857 connection->getInputChannelName(), status);
1858 }
1859#endif
1860 // Failed to stream. Start a new tail of pending motion samples to dispatch
1861 // in the next cycle.
1862 motionEventDispatchEntry->tailMotionSample = appendedMotionSample;
1863 return;
1864 }
1865 }
1866
Jeff Browna032cc02011-03-07 16:56:21 -08001867 // Enqueue dispatch entries for the requested modes.
1868 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1869 resumeWithAppendedMotionSample, InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
1870 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1871 resumeWithAppendedMotionSample, InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
1872 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1873 resumeWithAppendedMotionSample, InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
1874 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1875 resumeWithAppendedMotionSample, InputTarget::FLAG_DISPATCH_AS_IS);
1876
1877 // If the outbound queue was previously empty, start the dispatch cycle going.
Jeff Brownb6110c22011-04-01 16:15:13 -07001878 if (wasEmpty && !connection->outboundQueue.isEmpty()) {
Jeff Browna032cc02011-03-07 16:56:21 -08001879 activateConnectionLocked(connection.get());
1880 startDispatchCycleLocked(currentTime, connection);
1881 }
1882}
1883
1884void InputDispatcher::enqueueDispatchEntryLocked(
1885 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget,
1886 bool resumeWithAppendedMotionSample, int32_t dispatchMode) {
1887 int32_t inputTargetFlags = inputTarget->flags;
1888 if (!(inputTargetFlags & dispatchMode)) {
1889 return;
1890 }
1891 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
1892
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001893 // This is a new event.
1894 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Jeff Brownb88102f2010-09-08 11:49:43 -07001895 DispatchEntry* dispatchEntry = mAllocator.obtainDispatchEntry(eventEntry, // increments ref
Dianne Hackbornaa9d84c2011-05-09 19:00:59 -07001896 inputTargetFlags, inputTarget->xOffset, inputTarget->yOffset,
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001897 inputTarget->scaleFactor);
Jeff Brown519e0242010-09-15 15:18:56 -07001898 if (dispatchEntry->hasForegroundTarget()) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001899 incrementPendingForegroundDispatchesLocked(eventEntry);
Jeff Brown6ec402b2010-07-28 15:48:59 -07001900 }
1901
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001902 // Handle the case where we could not stream a new motion sample because the consumer has
1903 // already consumed the motion event (otherwise the corresponding dispatch entry would
1904 // still be in the outbound queue for this connection). We set the head motion sample
1905 // to the list starting with the newly appended motion sample.
1906 if (resumeWithAppendedMotionSample) {
1907#if DEBUG_BATCHING
1908 LOGD("channel '%s' ~ Preparing a new dispatch cycle for additional motion samples "
1909 "that cannot be streamed because the motion event has already been consumed.",
1910 connection->getInputChannelName());
1911#endif
1912 MotionSample* appendedMotionSample = static_cast<MotionEntry*>(eventEntry)->lastSample;
1913 dispatchEntry->headMotionSample = appendedMotionSample;
1914 }
1915
1916 // Enqueue the dispatch entry.
1917 connection->outboundQueue.enqueueAtTail(dispatchEntry);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001918}
1919
Jeff Brown7fbdc842010-06-17 20:52:56 -07001920void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Jeff Brown519e0242010-09-15 15:18:56 -07001921 const sp<Connection>& connection) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001922#if DEBUG_DISPATCH_CYCLE
1923 LOGD("channel '%s' ~ startDispatchCycle",
1924 connection->getInputChannelName());
1925#endif
1926
Jeff Brownb6110c22011-04-01 16:15:13 -07001927 LOG_ASSERT(connection->status == Connection::STATUS_NORMAL);
1928 LOG_ASSERT(! connection->outboundQueue.isEmpty());
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001929
Jeff Brownb88102f2010-09-08 11:49:43 -07001930 DispatchEntry* dispatchEntry = connection->outboundQueue.headSentinel.next;
Jeff Brownb6110c22011-04-01 16:15:13 -07001931 LOG_ASSERT(! dispatchEntry->inProgress);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001932
Jeff Brownb88102f2010-09-08 11:49:43 -07001933 // Mark the dispatch entry as in progress.
1934 dispatchEntry->inProgress = true;
1935
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001936 // Publish the event.
1937 status_t status;
Jeff Browna032cc02011-03-07 16:56:21 -08001938 EventEntry* eventEntry = dispatchEntry->eventEntry;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001939 switch (eventEntry->type) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001940 case EventEntry::TYPE_KEY: {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001941 KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001942
1943 // Apply target flags.
1944 int32_t action = keyEntry->action;
1945 int32_t flags = keyEntry->flags;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001946
Jeff Browna032cc02011-03-07 16:56:21 -08001947 // Update the connection's input state.
1948 connection->inputState.trackKey(keyEntry, action);
1949
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001950 // Publish the key event.
Jeff Brownc5ed5912010-07-14 18:48:53 -07001951 status = connection->inputPublisher.publishKeyEvent(keyEntry->deviceId, keyEntry->source,
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001952 action, flags, keyEntry->keyCode, keyEntry->scanCode,
1953 keyEntry->metaState, keyEntry->repeatCount, keyEntry->downTime,
1954 keyEntry->eventTime);
1955
1956 if (status) {
1957 LOGE("channel '%s' ~ Could not publish key event, "
1958 "status=%d", connection->getInputChannelName(), status);
Jeff Brownb6997262010-10-08 22:31:17 -07001959 abortBrokenDispatchCycleLocked(currentTime, connection);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001960 return;
1961 }
1962 break;
1963 }
1964
1965 case EventEntry::TYPE_MOTION: {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001966 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001967
1968 // Apply target flags.
1969 int32_t action = motionEntry->action;
Jeff Brown85a31762010-09-01 17:01:00 -07001970 int32_t flags = motionEntry->flags;
Jeff Browna032cc02011-03-07 16:56:21 -08001971 if (dispatchEntry->targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001972 action = AMOTION_EVENT_ACTION_OUTSIDE;
Jeff Browna032cc02011-03-07 16:56:21 -08001973 } else if (dispatchEntry->targetFlags & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
1974 action = AMOTION_EVENT_ACTION_HOVER_EXIT;
1975 } else if (dispatchEntry->targetFlags & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
1976 action = AMOTION_EVENT_ACTION_HOVER_ENTER;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001977 }
Jeff Brown85a31762010-09-01 17:01:00 -07001978 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
1979 flags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
1980 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001981
1982 // If headMotionSample is non-NULL, then it points to the first new sample that we
1983 // were unable to dispatch during the previous cycle so we resume dispatching from
1984 // that point in the list of motion samples.
1985 // Otherwise, we just start from the first sample of the motion event.
1986 MotionSample* firstMotionSample = dispatchEntry->headMotionSample;
1987 if (! firstMotionSample) {
1988 firstMotionSample = & motionEntry->firstSample;
1989 }
1990
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001991 PointerCoords scaledCoords[MAX_POINTERS];
1992 const PointerCoords* usingCoords = firstMotionSample->pointerCoords;
1993
Jeff Brownd3616592010-07-16 17:21:06 -07001994 // Set the X and Y offset depending on the input source.
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001995 float xOffset, yOffset, scaleFactor;
Jeff Brownd3616592010-07-16 17:21:06 -07001996 if (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) {
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001997 scaleFactor = dispatchEntry->scaleFactor;
1998 xOffset = dispatchEntry->xOffset * scaleFactor;
1999 yOffset = dispatchEntry->yOffset * scaleFactor;
2000 if (scaleFactor != 1.0f) {
2001 for (size_t i = 0; i < motionEntry->pointerCount; i++) {
2002 scaledCoords[i] = firstMotionSample->pointerCoords[i];
2003 scaledCoords[i].scale(scaleFactor);
2004 }
2005 usingCoords = scaledCoords;
2006 }
Jeff Brownd3616592010-07-16 17:21:06 -07002007 } else {
2008 xOffset = 0.0f;
2009 yOffset = 0.0f;
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002010 scaleFactor = 1.0f;
Jeff Brownd3616592010-07-16 17:21:06 -07002011 }
2012
Jeff Browna032cc02011-03-07 16:56:21 -08002013 // Update the connection's input state.
2014 connection->inputState.trackMotion(motionEntry, action);
2015
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002016 // Publish the motion event and the first motion sample.
2017 status = connection->inputPublisher.publishMotionEvent(motionEntry->deviceId,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002018 motionEntry->source, action, flags, motionEntry->edgeFlags,
2019 motionEntry->metaState, motionEntry->buttonState,
2020 xOffset, yOffset,
2021 motionEntry->xPrecision, motionEntry->yPrecision,
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002022 motionEntry->downTime, firstMotionSample->eventTime,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002023 motionEntry->pointerCount, motionEntry->pointerProperties,
2024 usingCoords);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002025
2026 if (status) {
2027 LOGE("channel '%s' ~ Could not publish motion event, "
2028 "status=%d", connection->getInputChannelName(), status);
Jeff Brownb6997262010-10-08 22:31:17 -07002029 abortBrokenDispatchCycleLocked(currentTime, connection);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002030 return;
2031 }
2032
Jeff Browna032cc02011-03-07 16:56:21 -08002033 if (action == AMOTION_EVENT_ACTION_MOVE
2034 || action == AMOTION_EVENT_ACTION_HOVER_MOVE) {
2035 // Append additional motion samples.
2036 MotionSample* nextMotionSample = firstMotionSample->next;
2037 for (; nextMotionSample != NULL; nextMotionSample = nextMotionSample->next) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002038 if (usingCoords == scaledCoords) {
Dianne Hackborn2ba3e802011-05-11 10:59:54 -07002039 for (size_t i = 0; i < motionEntry->pointerCount; i++) {
2040 scaledCoords[i] = nextMotionSample->pointerCoords[i];
2041 scaledCoords[i].scale(scaleFactor);
2042 }
2043 } else {
2044 usingCoords = nextMotionSample->pointerCoords;
Dianne Hackborne7d25b72011-05-09 21:19:26 -07002045 }
Jeff Browna032cc02011-03-07 16:56:21 -08002046 status = connection->inputPublisher.appendMotionSample(
Dianne Hackbornaa9d84c2011-05-09 19:00:59 -07002047 nextMotionSample->eventTime, usingCoords);
Jeff Browna032cc02011-03-07 16:56:21 -08002048 if (status == NO_MEMORY) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002049#if DEBUG_DISPATCH_CYCLE
2050 LOGD("channel '%s' ~ Shared memory buffer full. Some motion samples will "
2051 "be sent in the next dispatch cycle.",
2052 connection->getInputChannelName());
2053#endif
Jeff Browna032cc02011-03-07 16:56:21 -08002054 break;
2055 }
2056 if (status != OK) {
2057 LOGE("channel '%s' ~ Could not append motion sample "
2058 "for a reason other than out of memory, status=%d",
2059 connection->getInputChannelName(), status);
2060 abortBrokenDispatchCycleLocked(currentTime, connection);
2061 return;
2062 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002063 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002064
Jeff Browna032cc02011-03-07 16:56:21 -08002065 // Remember the next motion sample that we could not dispatch, in case we ran out
2066 // of space in the shared memory buffer.
2067 dispatchEntry->tailMotionSample = nextMotionSample;
2068 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002069 break;
2070 }
2071
2072 default: {
Jeff Brownb6110c22011-04-01 16:15:13 -07002073 LOG_ASSERT(false);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002074 }
2075 }
2076
2077 // Send the dispatch signal.
2078 status = connection->inputPublisher.sendDispatchSignal();
2079 if (status) {
2080 LOGE("channel '%s' ~ Could not send dispatch signal, status=%d",
2081 connection->getInputChannelName(), status);
Jeff Brownb6997262010-10-08 22:31:17 -07002082 abortBrokenDispatchCycleLocked(currentTime, connection);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002083 return;
2084 }
2085
2086 // Record information about the newly started dispatch cycle.
Jeff Brown01ce2e92010-09-26 22:20:12 -07002087 connection->lastEventTime = eventEntry->eventTime;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002088 connection->lastDispatchTime = currentTime;
2089
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002090 // Notify other system components.
2091 onDispatchCycleStartedLocked(currentTime, connection);
2092}
2093
Jeff Brown7fbdc842010-06-17 20:52:56 -07002094void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Jeff Brown3915bb82010-11-05 15:02:16 -07002095 const sp<Connection>& connection, bool handled) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002096#if DEBUG_DISPATCH_CYCLE
Jeff Brown9c3cda02010-06-15 01:31:58 -07002097 LOGD("channel '%s' ~ finishDispatchCycle - %01.1fms since event, "
Jeff Brown3915bb82010-11-05 15:02:16 -07002098 "%01.1fms since dispatch, handled=%s",
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002099 connection->getInputChannelName(),
2100 connection->getEventLatencyMillis(currentTime),
Jeff Brown3915bb82010-11-05 15:02:16 -07002101 connection->getDispatchLatencyMillis(currentTime),
2102 toString(handled));
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002103#endif
2104
Jeff Brown9c3cda02010-06-15 01:31:58 -07002105 if (connection->status == Connection::STATUS_BROKEN
2106 || connection->status == Connection::STATUS_ZOMBIE) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002107 return;
2108 }
2109
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002110 // Reset the publisher since the event has been consumed.
2111 // We do this now so that the publisher can release some of its internal resources
2112 // while waiting for the next dispatch cycle to begin.
2113 status_t status = connection->inputPublisher.reset();
2114 if (status) {
2115 LOGE("channel '%s' ~ Could not reset publisher, status=%d",
2116 connection->getInputChannelName(), status);
Jeff Brownb6997262010-10-08 22:31:17 -07002117 abortBrokenDispatchCycleLocked(currentTime, connection);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002118 return;
2119 }
2120
Jeff Brown3915bb82010-11-05 15:02:16 -07002121 // Notify other system components and prepare to start the next dispatch cycle.
2122 onDispatchCycleFinishedLocked(currentTime, connection, handled);
Jeff Brownb88102f2010-09-08 11:49:43 -07002123}
2124
2125void InputDispatcher::startNextDispatchCycleLocked(nsecs_t currentTime,
2126 const sp<Connection>& connection) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002127 // Start the next dispatch cycle for this connection.
2128 while (! connection->outboundQueue.isEmpty()) {
Jeff Brownb88102f2010-09-08 11:49:43 -07002129 DispatchEntry* dispatchEntry = connection->outboundQueue.headSentinel.next;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002130 if (dispatchEntry->inProgress) {
2131 // Finish or resume current event in progress.
2132 if (dispatchEntry->tailMotionSample) {
2133 // We have a tail of undispatched motion samples.
2134 // Reuse the same DispatchEntry and start a new cycle.
2135 dispatchEntry->inProgress = false;
2136 dispatchEntry->headMotionSample = dispatchEntry->tailMotionSample;
2137 dispatchEntry->tailMotionSample = NULL;
Jeff Brown519e0242010-09-15 15:18:56 -07002138 startDispatchCycleLocked(currentTime, connection);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002139 return;
2140 }
2141 // Finished.
2142 connection->outboundQueue.dequeueAtHead();
Jeff Brown519e0242010-09-15 15:18:56 -07002143 if (dispatchEntry->hasForegroundTarget()) {
2144 decrementPendingForegroundDispatchesLocked(dispatchEntry->eventEntry);
Jeff Brown6ec402b2010-07-28 15:48:59 -07002145 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002146 mAllocator.releaseDispatchEntry(dispatchEntry);
2147 } else {
2148 // If the head is not in progress, then we must have already dequeued the in
Jeff Brown519e0242010-09-15 15:18:56 -07002149 // progress event, which means we actually aborted it.
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002150 // So just start the next event for this connection.
Jeff Brown519e0242010-09-15 15:18:56 -07002151 startDispatchCycleLocked(currentTime, connection);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002152 return;
2153 }
2154 }
2155
2156 // Outbound queue is empty, deactivate the connection.
Jeff Brown7fbdc842010-06-17 20:52:56 -07002157 deactivateConnectionLocked(connection.get());
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002158}
2159
Jeff Brownb6997262010-10-08 22:31:17 -07002160void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
2161 const sp<Connection>& connection) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002162#if DEBUG_DISPATCH_CYCLE
Jeff Brown83c09682010-12-23 17:50:18 -08002163 LOGD("channel '%s' ~ abortBrokenDispatchCycle",
2164 connection->getInputChannelName());
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002165#endif
2166
Jeff Brownb88102f2010-09-08 11:49:43 -07002167 // Clear the outbound queue.
Jeff Brown519e0242010-09-15 15:18:56 -07002168 drainOutboundQueueLocked(connection.get());
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002169
Jeff Brownb6997262010-10-08 22:31:17 -07002170 // The connection appears to be unrecoverably broken.
Jeff Brown9c3cda02010-06-15 01:31:58 -07002171 // Ignore already broken or zombie connections.
Jeff Brownb6997262010-10-08 22:31:17 -07002172 if (connection->status == Connection::STATUS_NORMAL) {
2173 connection->status = Connection::STATUS_BROKEN;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002174
Jeff Brownb6997262010-10-08 22:31:17 -07002175 // Notify other system components.
2176 onDispatchCycleBrokenLocked(currentTime, connection);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002177 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002178}
2179
Jeff Brown519e0242010-09-15 15:18:56 -07002180void InputDispatcher::drainOutboundQueueLocked(Connection* connection) {
2181 while (! connection->outboundQueue.isEmpty()) {
2182 DispatchEntry* dispatchEntry = connection->outboundQueue.dequeueAtHead();
2183 if (dispatchEntry->hasForegroundTarget()) {
2184 decrementPendingForegroundDispatchesLocked(dispatchEntry->eventEntry);
Jeff Brownb88102f2010-09-08 11:49:43 -07002185 }
2186 mAllocator.releaseDispatchEntry(dispatchEntry);
Jeff Brownb88102f2010-09-08 11:49:43 -07002187 }
2188
Jeff Brown519e0242010-09-15 15:18:56 -07002189 deactivateConnectionLocked(connection);
Jeff Brownb88102f2010-09-08 11:49:43 -07002190}
2191
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002192int InputDispatcher::handleReceiveCallback(int receiveFd, int events, void* data) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002193 InputDispatcher* d = static_cast<InputDispatcher*>(data);
2194
2195 { // acquire lock
2196 AutoMutex _l(d->mLock);
2197
2198 ssize_t connectionIndex = d->mConnectionsByReceiveFd.indexOfKey(receiveFd);
2199 if (connectionIndex < 0) {
2200 LOGE("Received spurious receive callback for unknown input channel. "
2201 "fd=%d, events=0x%x", receiveFd, events);
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002202 return 0; // remove the callback
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002203 }
2204
Jeff Brown7fbdc842010-06-17 20:52:56 -07002205 nsecs_t currentTime = now();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002206
2207 sp<Connection> connection = d->mConnectionsByReceiveFd.valueAt(connectionIndex);
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002208 if (events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP)) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002209 LOGE("channel '%s' ~ Consumer closed input channel or an error occurred. "
2210 "events=0x%x", connection->getInputChannelName(), events);
Jeff Brownb6997262010-10-08 22:31:17 -07002211 d->abortBrokenDispatchCycleLocked(currentTime, connection);
Jeff Brown9c3cda02010-06-15 01:31:58 -07002212 d->runCommandsLockedInterruptible();
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002213 return 0; // remove the callback
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002214 }
2215
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002216 if (! (events & ALOOPER_EVENT_INPUT)) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002217 LOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
2218 "events=0x%x", connection->getInputChannelName(), events);
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002219 return 1;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002220 }
2221
Jeff Brown3915bb82010-11-05 15:02:16 -07002222 bool handled = false;
Jeff Brown49ed71d2010-12-06 17:13:33 -08002223 status_t status = connection->inputPublisher.receiveFinishedSignal(&handled);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002224 if (status) {
2225 LOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
2226 connection->getInputChannelName(), status);
Jeff Brownb6997262010-10-08 22:31:17 -07002227 d->abortBrokenDispatchCycleLocked(currentTime, connection);
Jeff Brown9c3cda02010-06-15 01:31:58 -07002228 d->runCommandsLockedInterruptible();
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002229 return 0; // remove the callback
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002230 }
2231
Jeff Brown3915bb82010-11-05 15:02:16 -07002232 d->finishDispatchCycleLocked(currentTime, connection, handled);
Jeff Brown9c3cda02010-06-15 01:31:58 -07002233 d->runCommandsLockedInterruptible();
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002234 return 1;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002235 } // release lock
2236}
2237
Jeff Brownb6997262010-10-08 22:31:17 -07002238void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Jeff Brownda3d5a92011-03-29 15:11:34 -07002239 const CancelationOptions& options) {
Jeff Brownb6997262010-10-08 22:31:17 -07002240 for (size_t i = 0; i < mConnectionsByReceiveFd.size(); i++) {
2241 synthesizeCancelationEventsForConnectionLocked(
Jeff Brownda3d5a92011-03-29 15:11:34 -07002242 mConnectionsByReceiveFd.valueAt(i), options);
Jeff Brownb6997262010-10-08 22:31:17 -07002243 }
2244}
2245
2246void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Jeff Brownda3d5a92011-03-29 15:11:34 -07002247 const sp<InputChannel>& channel, const CancelationOptions& options) {
Jeff Brownb6997262010-10-08 22:31:17 -07002248 ssize_t index = getConnectionIndexLocked(channel);
2249 if (index >= 0) {
2250 synthesizeCancelationEventsForConnectionLocked(
Jeff Brownda3d5a92011-03-29 15:11:34 -07002251 mConnectionsByReceiveFd.valueAt(index), options);
Jeff Brownb6997262010-10-08 22:31:17 -07002252 }
2253}
2254
2255void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
Jeff Brownda3d5a92011-03-29 15:11:34 -07002256 const sp<Connection>& connection, const CancelationOptions& options) {
Jeff Brownb6997262010-10-08 22:31:17 -07002257 nsecs_t currentTime = now();
2258
2259 mTempCancelationEvents.clear();
2260 connection->inputState.synthesizeCancelationEvents(currentTime, & mAllocator,
2261 mTempCancelationEvents, options);
2262
2263 if (! mTempCancelationEvents.isEmpty()
2264 && connection->status != Connection::STATUS_BROKEN) {
2265#if DEBUG_OUTBOUND_EVENT_DETAILS
2266 LOGD("channel '%s' ~ Synthesized %d cancelation events to bring channel back in sync "
Jeff Brownda3d5a92011-03-29 15:11:34 -07002267 "with reality: %s, mode=%d.",
2268 connection->getInputChannelName(), mTempCancelationEvents.size(),
2269 options.reason, options.mode);
Jeff Brownb6997262010-10-08 22:31:17 -07002270#endif
2271 for (size_t i = 0; i < mTempCancelationEvents.size(); i++) {
2272 EventEntry* cancelationEventEntry = mTempCancelationEvents.itemAt(i);
2273 switch (cancelationEventEntry->type) {
2274 case EventEntry::TYPE_KEY:
2275 logOutboundKeyDetailsLocked("cancel - ",
2276 static_cast<KeyEntry*>(cancelationEventEntry));
2277 break;
2278 case EventEntry::TYPE_MOTION:
2279 logOutboundMotionDetailsLocked("cancel - ",
2280 static_cast<MotionEntry*>(cancelationEventEntry));
2281 break;
2282 }
2283
2284 int32_t xOffset, yOffset;
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002285 float scaleFactor;
Jeff Brownb6997262010-10-08 22:31:17 -07002286 const InputWindow* window = getWindowLocked(connection->inputChannel);
2287 if (window) {
2288 xOffset = -window->frameLeft;
2289 yOffset = -window->frameTop;
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002290 scaleFactor = window->scaleFactor;
Jeff Brownb6997262010-10-08 22:31:17 -07002291 } else {
2292 xOffset = 0;
2293 yOffset = 0;
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002294 scaleFactor = 1.0f;
Jeff Brownb6997262010-10-08 22:31:17 -07002295 }
2296
2297 DispatchEntry* cancelationDispatchEntry =
2298 mAllocator.obtainDispatchEntry(cancelationEventEntry, // increments ref
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002299 0, xOffset, yOffset, scaleFactor);
Jeff Brownb6997262010-10-08 22:31:17 -07002300 connection->outboundQueue.enqueueAtTail(cancelationDispatchEntry);
2301
2302 mAllocator.releaseEventEntry(cancelationEventEntry);
2303 }
2304
2305 if (!connection->outboundQueue.headSentinel.next->inProgress) {
2306 startDispatchCycleLocked(currentTime, connection);
2307 }
2308 }
2309}
2310
Jeff Brown01ce2e92010-09-26 22:20:12 -07002311InputDispatcher::MotionEntry*
2312InputDispatcher::splitMotionEvent(const MotionEntry* originalMotionEntry, BitSet32 pointerIds) {
Jeff Brownb6110c22011-04-01 16:15:13 -07002313 LOG_ASSERT(pointerIds.value != 0);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002314
2315 uint32_t splitPointerIndexMap[MAX_POINTERS];
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002316 PointerProperties splitPointerProperties[MAX_POINTERS];
Jeff Brown01ce2e92010-09-26 22:20:12 -07002317 PointerCoords splitPointerCoords[MAX_POINTERS];
2318
2319 uint32_t originalPointerCount = originalMotionEntry->pointerCount;
2320 uint32_t splitPointerCount = 0;
2321
2322 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
2323 originalPointerIndex++) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002324 const PointerProperties& pointerProperties =
2325 originalMotionEntry->pointerProperties[originalPointerIndex];
2326 uint32_t pointerId = uint32_t(pointerProperties.id);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002327 if (pointerIds.hasBit(pointerId)) {
2328 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002329 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
Jeff Brownace13b12011-03-09 17:39:48 -08002330 splitPointerCoords[splitPointerCount].copyFrom(
2331 originalMotionEntry->firstSample.pointerCoords[originalPointerIndex]);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002332 splitPointerCount += 1;
2333 }
2334 }
Jeff Brown58a2da82011-01-25 16:02:22 -08002335
2336 if (splitPointerCount != pointerIds.count()) {
2337 // This is bad. We are missing some of the pointers that we expected to deliver.
2338 // Most likely this indicates that we received an ACTION_MOVE events that has
2339 // different pointer ids than we expected based on the previous ACTION_DOWN
2340 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
2341 // in this way.
2342 LOGW("Dropping split motion event because the pointer count is %d but "
2343 "we expected there to be %d pointers. This probably means we received "
2344 "a broken sequence of pointer ids from the input device.",
2345 splitPointerCount, pointerIds.count());
2346 return NULL;
2347 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07002348
2349 int32_t action = originalMotionEntry->action;
2350 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
2351 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
2352 || maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2353 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002354 const PointerProperties& pointerProperties =
2355 originalMotionEntry->pointerProperties[originalPointerIndex];
2356 uint32_t pointerId = uint32_t(pointerProperties.id);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002357 if (pointerIds.hasBit(pointerId)) {
2358 if (pointerIds.count() == 1) {
2359 // The first/last pointer went down/up.
2360 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
2361 ? AMOTION_EVENT_ACTION_DOWN : AMOTION_EVENT_ACTION_UP;
Jeff Brown9a01d052010-09-27 16:35:11 -07002362 } else {
2363 // A secondary pointer went down/up.
2364 uint32_t splitPointerIndex = 0;
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002365 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
Jeff Brown9a01d052010-09-27 16:35:11 -07002366 splitPointerIndex += 1;
2367 }
2368 action = maskedAction | (splitPointerIndex
2369 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002370 }
2371 } else {
2372 // An unrelated pointer changed.
2373 action = AMOTION_EVENT_ACTION_MOVE;
2374 }
2375 }
2376
2377 MotionEntry* splitMotionEntry = mAllocator.obtainMotionEntry(
2378 originalMotionEntry->eventTime,
2379 originalMotionEntry->deviceId,
2380 originalMotionEntry->source,
2381 originalMotionEntry->policyFlags,
2382 action,
2383 originalMotionEntry->flags,
2384 originalMotionEntry->metaState,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002385 originalMotionEntry->buttonState,
Jeff Brown01ce2e92010-09-26 22:20:12 -07002386 originalMotionEntry->edgeFlags,
2387 originalMotionEntry->xPrecision,
2388 originalMotionEntry->yPrecision,
2389 originalMotionEntry->downTime,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002390 splitPointerCount, splitPointerProperties, splitPointerCoords);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002391
2392 for (MotionSample* originalMotionSample = originalMotionEntry->firstSample.next;
2393 originalMotionSample != NULL; originalMotionSample = originalMotionSample->next) {
2394 for (uint32_t splitPointerIndex = 0; splitPointerIndex < splitPointerCount;
2395 splitPointerIndex++) {
2396 uint32_t originalPointerIndex = splitPointerIndexMap[splitPointerIndex];
Jeff Brownace13b12011-03-09 17:39:48 -08002397 splitPointerCoords[splitPointerIndex].copyFrom(
2398 originalMotionSample->pointerCoords[originalPointerIndex]);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002399 }
2400
2401 mAllocator.appendMotionSample(splitMotionEntry, originalMotionSample->eventTime,
2402 splitPointerCoords);
2403 }
2404
Jeff Browna032cc02011-03-07 16:56:21 -08002405 if (originalMotionEntry->injectionState) {
2406 splitMotionEntry->injectionState = originalMotionEntry->injectionState;
2407 splitMotionEntry->injectionState->refCount += 1;
2408 }
2409
Jeff Brown01ce2e92010-09-26 22:20:12 -07002410 return splitMotionEntry;
2411}
2412
Jeff Brown9c3cda02010-06-15 01:31:58 -07002413void InputDispatcher::notifyConfigurationChanged(nsecs_t eventTime) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002414#if DEBUG_INBOUND_EVENT_DETAILS
Jeff Brown9c3cda02010-06-15 01:31:58 -07002415 LOGD("notifyConfigurationChanged - eventTime=%lld", eventTime);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002416#endif
2417
Jeff Brownb88102f2010-09-08 11:49:43 -07002418 bool needWake;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002419 { // acquire lock
2420 AutoMutex _l(mLock);
2421
Jeff Brown7fbdc842010-06-17 20:52:56 -07002422 ConfigurationChangedEntry* newEntry = mAllocator.obtainConfigurationChangedEntry(eventTime);
Jeff Brownb88102f2010-09-08 11:49:43 -07002423 needWake = enqueueInboundEventLocked(newEntry);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002424 } // release lock
2425
Jeff Brownb88102f2010-09-08 11:49:43 -07002426 if (needWake) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002427 mLooper->wake();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002428 }
2429}
2430
Jeff Brown58a2da82011-01-25 16:02:22 -08002431void InputDispatcher::notifyKey(nsecs_t eventTime, int32_t deviceId, uint32_t source,
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002432 uint32_t policyFlags, int32_t action, int32_t flags,
2433 int32_t keyCode, int32_t scanCode, int32_t metaState, nsecs_t downTime) {
2434#if DEBUG_INBOUND_EVENT_DETAILS
Jeff Brown90655042010-12-02 13:50:46 -08002435 LOGD("notifyKey - eventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, action=0x%x, "
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002436 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%lld",
Jeff Brownc5ed5912010-07-14 18:48:53 -07002437 eventTime, deviceId, source, policyFlags, action, flags,
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002438 keyCode, scanCode, metaState, downTime);
2439#endif
Jeff Brown01ce2e92010-09-26 22:20:12 -07002440 if (! validateKeyEvent(action)) {
2441 return;
2442 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002443
Jeff Brown1f245102010-11-18 20:53:46 -08002444 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
2445 policyFlags |= POLICY_FLAG_VIRTUAL;
2446 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
2447 }
Jeff Brown924c4d42011-03-07 16:40:47 -08002448 if (policyFlags & POLICY_FLAG_ALT) {
2449 metaState |= AMETA_ALT_ON | AMETA_ALT_LEFT_ON;
2450 }
2451 if (policyFlags & POLICY_FLAG_ALT_GR) {
2452 metaState |= AMETA_ALT_ON | AMETA_ALT_RIGHT_ON;
2453 }
2454 if (policyFlags & POLICY_FLAG_SHIFT) {
2455 metaState |= AMETA_SHIFT_ON | AMETA_SHIFT_LEFT_ON;
2456 }
2457 if (policyFlags & POLICY_FLAG_CAPS_LOCK) {
2458 metaState |= AMETA_CAPS_LOCK_ON;
2459 }
2460 if (policyFlags & POLICY_FLAG_FUNCTION) {
2461 metaState |= AMETA_FUNCTION_ON;
2462 }
Jeff Brown1f245102010-11-18 20:53:46 -08002463
Jeff Browne20c9e02010-10-11 14:20:19 -07002464 policyFlags |= POLICY_FLAG_TRUSTED;
Jeff Brown1f245102010-11-18 20:53:46 -08002465
2466 KeyEvent event;
2467 event.initialize(deviceId, source, action, flags, keyCode, scanCode,
2468 metaState, 0, downTime, eventTime);
2469
2470 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
2471
2472 if (policyFlags & POLICY_FLAG_WOKE_HERE) {
2473 flags |= AKEY_EVENT_FLAG_WOKE_HERE;
2474 }
Jeff Brownb6997262010-10-08 22:31:17 -07002475
Jeff Brownb88102f2010-09-08 11:49:43 -07002476 bool needWake;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002477 { // acquire lock
Jeff Brown0029c662011-03-30 02:25:18 -07002478 mLock.lock();
2479
2480 if (mInputFilterEnabled) {
2481 mLock.unlock();
2482
2483 policyFlags |= POLICY_FLAG_FILTERED;
2484 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2485 return; // event was consumed by the filter
2486 }
2487
2488 mLock.lock();
2489 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002490
Jeff Brown7fbdc842010-06-17 20:52:56 -07002491 int32_t repeatCount = 0;
2492 KeyEntry* newEntry = mAllocator.obtainKeyEntry(eventTime,
Jeff Brownc5ed5912010-07-14 18:48:53 -07002493 deviceId, source, policyFlags, action, flags, keyCode, scanCode,
Jeff Brown7fbdc842010-06-17 20:52:56 -07002494 metaState, repeatCount, downTime);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002495
Jeff Brownb88102f2010-09-08 11:49:43 -07002496 needWake = enqueueInboundEventLocked(newEntry);
Jeff Brown0029c662011-03-30 02:25:18 -07002497 mLock.unlock();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002498 } // release lock
2499
Jeff Brownb88102f2010-09-08 11:49:43 -07002500 if (needWake) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002501 mLooper->wake();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002502 }
2503}
2504
Jeff Brown58a2da82011-01-25 16:02:22 -08002505void InputDispatcher::notifyMotion(nsecs_t eventTime, int32_t deviceId, uint32_t source,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002506 uint32_t policyFlags, int32_t action, int32_t flags,
2507 int32_t metaState, int32_t buttonState, int32_t edgeFlags,
2508 uint32_t pointerCount, const PointerProperties* pointerProperties,
2509 const PointerCoords* pointerCoords,
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002510 float xPrecision, float yPrecision, nsecs_t downTime) {
2511#if DEBUG_INBOUND_EVENT_DETAILS
Jeff Brown90655042010-12-02 13:50:46 -08002512 LOGD("notifyMotion - eventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, "
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002513 "action=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, edgeFlags=0x%x, "
Jeff Brown85a31762010-09-01 17:01:00 -07002514 "xPrecision=%f, yPrecision=%f, downTime=%lld",
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002515 eventTime, deviceId, source, policyFlags, action, flags,
2516 metaState, buttonState, edgeFlags,
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002517 xPrecision, yPrecision, downTime);
2518 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002519 LOGD(" Pointer %d: id=%d, toolType=%d, "
2520 "x=%f, y=%f, pressure=%f, size=%f, "
Jeff Brown85a31762010-09-01 17:01:00 -07002521 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
Jeff Brown8d608662010-08-30 03:02:23 -07002522 "orientation=%f",
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002523 i, pointerProperties[i].id,
2524 pointerProperties[i].toolType,
Jeff Brownebbd5d12011-02-17 13:01:34 -08002525 pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
2526 pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
2527 pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
2528 pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
2529 pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
2530 pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
2531 pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
2532 pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
2533 pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002534 }
2535#endif
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002536 if (! validateMotionEvent(action, pointerCount, pointerProperties)) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002537 return;
2538 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002539
Jeff Browne20c9e02010-10-11 14:20:19 -07002540 policyFlags |= POLICY_FLAG_TRUSTED;
Jeff Brown56194eb2011-03-02 19:23:13 -08002541 mPolicy->interceptMotionBeforeQueueing(eventTime, /*byref*/ policyFlags);
Jeff Brownb6997262010-10-08 22:31:17 -07002542
Jeff Brownb88102f2010-09-08 11:49:43 -07002543 bool needWake;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002544 { // acquire lock
Jeff Brown0029c662011-03-30 02:25:18 -07002545 mLock.lock();
2546
2547 if (mInputFilterEnabled) {
2548 mLock.unlock();
2549
2550 MotionEvent event;
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002551 event.initialize(deviceId, source, action, flags, edgeFlags, metaState,
2552 buttonState, 0, 0,
Jeff Brown0029c662011-03-30 02:25:18 -07002553 xPrecision, yPrecision, downTime, eventTime,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002554 pointerCount, pointerProperties, pointerCoords);
Jeff Brown0029c662011-03-30 02:25:18 -07002555
2556 policyFlags |= POLICY_FLAG_FILTERED;
2557 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2558 return; // event was consumed by the filter
2559 }
2560
2561 mLock.lock();
2562 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002563
2564 // Attempt batching and streaming of move events.
Jeff Browncc0c1592011-02-19 05:07:28 -08002565 if (action == AMOTION_EVENT_ACTION_MOVE
2566 || action == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002567 // BATCHING CASE
2568 //
2569 // Try to append a move sample to the tail of the inbound queue for this device.
2570 // Give up if we encounter a non-move motion event for this device since that
2571 // means we cannot append any new samples until a new motion event has started.
Jeff Brownb88102f2010-09-08 11:49:43 -07002572 for (EventEntry* entry = mInboundQueue.tailSentinel.prev;
2573 entry != & mInboundQueue.headSentinel; entry = entry->prev) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002574 if (entry->type != EventEntry::TYPE_MOTION) {
2575 // Keep looking for motion events.
2576 continue;
2577 }
2578
2579 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
Jeff Brownefd32662011-03-08 15:13:06 -08002580 if (motionEntry->deviceId != deviceId
2581 || motionEntry->source != source) {
2582 // Keep looking for this device and source.
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002583 continue;
2584 }
2585
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002586 if (!motionEntry->canAppendSamples(action, pointerCount, pointerProperties)) {
Jeff Brownefd32662011-03-08 15:13:06 -08002587 // Last motion event in the queue for this device and source is
2588 // not compatible for appending new samples. Stop here.
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002589 goto NoBatchingOrStreaming;
2590 }
2591
Jeff Brown9c3cda02010-06-15 01:31:58 -07002592 // Do the batching magic.
Jeff Brown4e91a182011-04-07 11:38:09 -07002593 batchMotionLocked(motionEntry, eventTime, metaState, pointerCoords,
2594 "most recent motion event for this device and source in the inbound queue");
Jeff Brown0029c662011-03-30 02:25:18 -07002595 mLock.unlock();
Jeff Brown9c3cda02010-06-15 01:31:58 -07002596 return; // done!
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002597 }
2598
Jeff Brownf6989da2011-04-06 17:19:48 -07002599 // BATCHING ONTO PENDING EVENT CASE
2600 //
2601 // Try to append a move sample to the currently pending event, if there is one.
2602 // We can do this as long as we are still waiting to find the targets for the
2603 // event. Once the targets are locked-in we can only do streaming.
2604 if (mPendingEvent
2605 && (!mPendingEvent->dispatchInProgress || !mCurrentInputTargetsValid)
2606 && mPendingEvent->type == EventEntry::TYPE_MOTION) {
2607 MotionEntry* motionEntry = static_cast<MotionEntry*>(mPendingEvent);
2608 if (motionEntry->deviceId == deviceId && motionEntry->source == source) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002609 if (!motionEntry->canAppendSamples(action, pointerCount, pointerProperties)) {
Jeff Brown4e91a182011-04-07 11:38:09 -07002610 // Pending motion event is for this device and source but it is
2611 // not compatible for appending new samples. Stop here.
Jeff Brownf6989da2011-04-06 17:19:48 -07002612 goto NoBatchingOrStreaming;
2613 }
2614
Jeff Brownf6989da2011-04-06 17:19:48 -07002615 // Do the batching magic.
Jeff Brown4e91a182011-04-07 11:38:09 -07002616 batchMotionLocked(motionEntry, eventTime, metaState, pointerCoords,
2617 "pending motion event");
Jeff Brownf6989da2011-04-06 17:19:48 -07002618 mLock.unlock();
2619 return; // done!
2620 }
2621 }
2622
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002623 // STREAMING CASE
2624 //
2625 // There is no pending motion event (of any kind) for this device in the inbound queue.
Jeff Brown519e0242010-09-15 15:18:56 -07002626 // Search the outbound queue for the current foreground targets to find a dispatched
2627 // motion event that is still in progress. If found, then, appen the new sample to
2628 // that event and push it out to all current targets. The logic in
2629 // prepareDispatchCycleLocked takes care of the case where some targets may
2630 // already have consumed the motion event by starting a new dispatch cycle if needed.
Jeff Brown9c3cda02010-06-15 01:31:58 -07002631 if (mCurrentInputTargetsValid) {
Jeff Brown519e0242010-09-15 15:18:56 -07002632 for (size_t i = 0; i < mCurrentInputTargets.size(); i++) {
2633 const InputTarget& inputTarget = mCurrentInputTargets[i];
2634 if ((inputTarget.flags & InputTarget::FLAG_FOREGROUND) == 0) {
2635 // Skip non-foreground targets. We only want to stream if there is at
2636 // least one foreground target whose dispatch is still in progress.
2637 continue;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002638 }
Jeff Brown519e0242010-09-15 15:18:56 -07002639
2640 ssize_t connectionIndex = getConnectionIndexLocked(inputTarget.inputChannel);
2641 if (connectionIndex < 0) {
2642 // Connection must no longer be valid.
2643 continue;
2644 }
2645
2646 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
2647 if (connection->outboundQueue.isEmpty()) {
2648 // This foreground target has an empty outbound queue.
2649 continue;
2650 }
2651
2652 DispatchEntry* dispatchEntry = connection->outboundQueue.headSentinel.next;
2653 if (! dispatchEntry->inProgress
Jeff Brown01ce2e92010-09-26 22:20:12 -07002654 || dispatchEntry->eventEntry->type != EventEntry::TYPE_MOTION
2655 || dispatchEntry->isSplit()) {
2656 // No motion event is being dispatched, or it is being split across
2657 // windows in which case we cannot stream.
Jeff Brown519e0242010-09-15 15:18:56 -07002658 continue;
2659 }
2660
2661 MotionEntry* motionEntry = static_cast<MotionEntry*>(
2662 dispatchEntry->eventEntry);
Jeff Browncc0c1592011-02-19 05:07:28 -08002663 if (motionEntry->action != action
Jeff Brown519e0242010-09-15 15:18:56 -07002664 || motionEntry->deviceId != deviceId
Jeff Brown58a2da82011-01-25 16:02:22 -08002665 || motionEntry->source != source
Jeff Brown519e0242010-09-15 15:18:56 -07002666 || motionEntry->pointerCount != pointerCount
2667 || motionEntry->isInjected()) {
2668 // The motion event is not compatible with this move.
2669 continue;
2670 }
2671
Jeff Browna032cc02011-03-07 16:56:21 -08002672 if (action == AMOTION_EVENT_ACTION_HOVER_MOVE) {
2673 if (!mLastHoverWindow) {
2674#if DEBUG_BATCHING
2675 LOGD("Not streaming hover move because there is no "
2676 "last hovered window.");
2677#endif
2678 goto NoBatchingOrStreaming;
2679 }
2680
2681 const InputWindow* hoverWindow = findTouchedWindowAtLocked(
2682 pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X),
2683 pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
2684 if (mLastHoverWindow != hoverWindow) {
2685#if DEBUG_BATCHING
2686 LOGD("Not streaming hover move because the last hovered window "
2687 "is '%s' but the currently hovered window is '%s'.",
2688 mLastHoverWindow->name.string(),
2689 hoverWindow ? hoverWindow->name.string() : "<null>");
2690#endif
2691 goto NoBatchingOrStreaming;
2692 }
2693 }
2694
Jeff Brown519e0242010-09-15 15:18:56 -07002695 // Hurray! This foreground target is currently dispatching a move event
2696 // that we can stream onto. Append the motion sample and resume dispatch.
2697 mAllocator.appendMotionSample(motionEntry, eventTime, pointerCoords);
2698#if DEBUG_BATCHING
2699 LOGD("Appended motion sample onto batch for most recently dispatched "
Jeff Brown4e91a182011-04-07 11:38:09 -07002700 "motion event for this device and source in the outbound queues. "
Jeff Brown519e0242010-09-15 15:18:56 -07002701 "Attempting to stream the motion sample.");
2702#endif
2703 nsecs_t currentTime = now();
2704 dispatchEventToCurrentInputTargetsLocked(currentTime, motionEntry,
2705 true /*resumeWithAppendedMotionSample*/);
2706
2707 runCommandsLockedInterruptible();
Jeff Brown0029c662011-03-30 02:25:18 -07002708 mLock.unlock();
Jeff Brown519e0242010-09-15 15:18:56 -07002709 return; // done!
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002710 }
2711 }
2712
2713NoBatchingOrStreaming:;
2714 }
2715
2716 // Just enqueue a new motion event.
Jeff Brown7fbdc842010-06-17 20:52:56 -07002717 MotionEntry* newEntry = mAllocator.obtainMotionEntry(eventTime,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002718 deviceId, source, policyFlags, action, flags, metaState, buttonState, edgeFlags,
Jeff Brown7fbdc842010-06-17 20:52:56 -07002719 xPrecision, yPrecision, downTime,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002720 pointerCount, pointerProperties, pointerCoords);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002721
Jeff Brownb88102f2010-09-08 11:49:43 -07002722 needWake = enqueueInboundEventLocked(newEntry);
Jeff Brown0029c662011-03-30 02:25:18 -07002723 mLock.unlock();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002724 } // release lock
2725
Jeff Brownb88102f2010-09-08 11:49:43 -07002726 if (needWake) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002727 mLooper->wake();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002728 }
2729}
2730
Jeff Brown4e91a182011-04-07 11:38:09 -07002731void InputDispatcher::batchMotionLocked(MotionEntry* entry, nsecs_t eventTime,
2732 int32_t metaState, const PointerCoords* pointerCoords, const char* eventDescription) {
2733 // Combine meta states.
2734 entry->metaState |= metaState;
2735
2736 // Coalesce this sample if not enough time has elapsed since the last sample was
2737 // initially appended to the batch.
2738 MotionSample* lastSample = entry->lastSample;
2739 long interval = eventTime - lastSample->eventTimeBeforeCoalescing;
2740 if (interval <= MOTION_SAMPLE_COALESCE_INTERVAL) {
2741 uint32_t pointerCount = entry->pointerCount;
2742 for (uint32_t i = 0; i < pointerCount; i++) {
2743 lastSample->pointerCoords[i].copyFrom(pointerCoords[i]);
2744 }
2745 lastSample->eventTime = eventTime;
2746#if DEBUG_BATCHING
2747 LOGD("Coalesced motion into last sample of batch for %s, events were %0.3f ms apart",
2748 eventDescription, interval * 0.000001f);
2749#endif
2750 return;
2751 }
2752
2753 // Append the sample.
2754 mAllocator.appendMotionSample(entry, eventTime, pointerCoords);
2755#if DEBUG_BATCHING
2756 LOGD("Appended motion sample onto batch for %s, events were %0.3f ms apart",
2757 eventDescription, interval * 0.000001f);
2758#endif
2759}
2760
Jeff Brownb6997262010-10-08 22:31:17 -07002761void InputDispatcher::notifySwitch(nsecs_t when, int32_t switchCode, int32_t switchValue,
2762 uint32_t policyFlags) {
2763#if DEBUG_INBOUND_EVENT_DETAILS
2764 LOGD("notifySwitch - switchCode=%d, switchValue=%d, policyFlags=0x%x",
2765 switchCode, switchValue, policyFlags);
2766#endif
2767
Jeff Browne20c9e02010-10-11 14:20:19 -07002768 policyFlags |= POLICY_FLAG_TRUSTED;
Jeff Brownb6997262010-10-08 22:31:17 -07002769 mPolicy->notifySwitch(when, switchCode, switchValue, policyFlags);
2770}
2771
Jeff Brown7fbdc842010-06-17 20:52:56 -07002772int32_t InputDispatcher::injectInputEvent(const InputEvent* event,
Jeff Brown0029c662011-03-30 02:25:18 -07002773 int32_t injectorPid, int32_t injectorUid, int32_t syncMode, int32_t timeoutMillis,
2774 uint32_t policyFlags) {
Jeff Brown7fbdc842010-06-17 20:52:56 -07002775#if DEBUG_INBOUND_EVENT_DETAILS
2776 LOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Jeff Brown0029c662011-03-30 02:25:18 -07002777 "syncMode=%d, timeoutMillis=%d, policyFlags=0x%08x",
2778 event->getType(), injectorPid, injectorUid, syncMode, timeoutMillis, policyFlags);
Jeff Brown7fbdc842010-06-17 20:52:56 -07002779#endif
2780
2781 nsecs_t endTime = now() + milliseconds_to_nanoseconds(timeoutMillis);
Jeff Browne20c9e02010-10-11 14:20:19 -07002782
Jeff Brown0029c662011-03-30 02:25:18 -07002783 policyFlags |= POLICY_FLAG_INJECTED;
Jeff Browne20c9e02010-10-11 14:20:19 -07002784 if (hasInjectionPermission(injectorPid, injectorUid)) {
2785 policyFlags |= POLICY_FLAG_TRUSTED;
2786 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07002787
Jeff Brownb6997262010-10-08 22:31:17 -07002788 EventEntry* injectedEntry;
2789 switch (event->getType()) {
2790 case AINPUT_EVENT_TYPE_KEY: {
2791 const KeyEvent* keyEvent = static_cast<const KeyEvent*>(event);
2792 int32_t action = keyEvent->getAction();
2793 if (! validateKeyEvent(action)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07002794 return INPUT_EVENT_INJECTION_FAILED;
2795 }
2796
Jeff Brownb6997262010-10-08 22:31:17 -07002797 int32_t flags = keyEvent->getFlags();
Jeff Brown1f245102010-11-18 20:53:46 -08002798 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
2799 policyFlags |= POLICY_FLAG_VIRTUAL;
2800 }
2801
Jeff Brown0029c662011-03-30 02:25:18 -07002802 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
2803 mPolicy->interceptKeyBeforeQueueing(keyEvent, /*byref*/ policyFlags);
2804 }
Jeff Brown1f245102010-11-18 20:53:46 -08002805
2806 if (policyFlags & POLICY_FLAG_WOKE_HERE) {
2807 flags |= AKEY_EVENT_FLAG_WOKE_HERE;
2808 }
Jeff Brown6ec402b2010-07-28 15:48:59 -07002809
Jeff Brownb6997262010-10-08 22:31:17 -07002810 mLock.lock();
Jeff Brown1f245102010-11-18 20:53:46 -08002811 injectedEntry = mAllocator.obtainKeyEntry(keyEvent->getEventTime(),
2812 keyEvent->getDeviceId(), keyEvent->getSource(),
2813 policyFlags, action, flags,
2814 keyEvent->getKeyCode(), keyEvent->getScanCode(), keyEvent->getMetaState(),
Jeff Brownb6997262010-10-08 22:31:17 -07002815 keyEvent->getRepeatCount(), keyEvent->getDownTime());
2816 break;
2817 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07002818
Jeff Brownb6997262010-10-08 22:31:17 -07002819 case AINPUT_EVENT_TYPE_MOTION: {
2820 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
2821 int32_t action = motionEvent->getAction();
2822 size_t pointerCount = motionEvent->getPointerCount();
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002823 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
2824 if (! validateMotionEvent(action, pointerCount, pointerProperties)) {
Jeff Brownb6997262010-10-08 22:31:17 -07002825 return INPUT_EVENT_INJECTION_FAILED;
2826 }
2827
Jeff Brown0029c662011-03-30 02:25:18 -07002828 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
2829 nsecs_t eventTime = motionEvent->getEventTime();
2830 mPolicy->interceptMotionBeforeQueueing(eventTime, /*byref*/ policyFlags);
2831 }
Jeff Brownb6997262010-10-08 22:31:17 -07002832
2833 mLock.lock();
2834 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
2835 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
2836 MotionEntry* motionEntry = mAllocator.obtainMotionEntry(*sampleEventTimes,
2837 motionEvent->getDeviceId(), motionEvent->getSource(), policyFlags,
2838 action, motionEvent->getFlags(),
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002839 motionEvent->getMetaState(), motionEvent->getButtonState(),
2840 motionEvent->getEdgeFlags(),
Jeff Brownb6997262010-10-08 22:31:17 -07002841 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
2842 motionEvent->getDownTime(), uint32_t(pointerCount),
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002843 pointerProperties, samplePointerCoords);
Jeff Brownb6997262010-10-08 22:31:17 -07002844 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
2845 sampleEventTimes += 1;
2846 samplePointerCoords += pointerCount;
2847 mAllocator.appendMotionSample(motionEntry, *sampleEventTimes, samplePointerCoords);
2848 }
2849 injectedEntry = motionEntry;
2850 break;
2851 }
2852
2853 default:
2854 LOGW("Cannot inject event of type %d", event->getType());
2855 return INPUT_EVENT_INJECTION_FAILED;
2856 }
2857
2858 InjectionState* injectionState = mAllocator.obtainInjectionState(injectorPid, injectorUid);
2859 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
2860 injectionState->injectionIsAsync = true;
2861 }
2862
2863 injectionState->refCount += 1;
2864 injectedEntry->injectionState = injectionState;
2865
2866 bool needWake = enqueueInboundEventLocked(injectedEntry);
2867 mLock.unlock();
Jeff Brown7fbdc842010-06-17 20:52:56 -07002868
Jeff Brownb88102f2010-09-08 11:49:43 -07002869 if (needWake) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002870 mLooper->wake();
Jeff Brown7fbdc842010-06-17 20:52:56 -07002871 }
2872
2873 int32_t injectionResult;
2874 { // acquire lock
2875 AutoMutex _l(mLock);
2876
Jeff Brown6ec402b2010-07-28 15:48:59 -07002877 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
2878 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
2879 } else {
2880 for (;;) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002881 injectionResult = injectionState->injectionResult;
Jeff Brown6ec402b2010-07-28 15:48:59 -07002882 if (injectionResult != INPUT_EVENT_INJECTION_PENDING) {
2883 break;
2884 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07002885
Jeff Brown7fbdc842010-06-17 20:52:56 -07002886 nsecs_t remainingTimeout = endTime - now();
2887 if (remainingTimeout <= 0) {
Jeff Brown6ec402b2010-07-28 15:48:59 -07002888#if DEBUG_INJECTION
2889 LOGD("injectInputEvent - Timed out waiting for injection result "
2890 "to become available.");
2891#endif
Jeff Brown7fbdc842010-06-17 20:52:56 -07002892 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
2893 break;
2894 }
2895
Jeff Brown6ec402b2010-07-28 15:48:59 -07002896 mInjectionResultAvailableCondition.waitRelative(mLock, remainingTimeout);
2897 }
2898
2899 if (injectionResult == INPUT_EVENT_INJECTION_SUCCEEDED
2900 && syncMode == INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002901 while (injectionState->pendingForegroundDispatches != 0) {
Jeff Brown6ec402b2010-07-28 15:48:59 -07002902#if DEBUG_INJECTION
Jeff Brown519e0242010-09-15 15:18:56 -07002903 LOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
Jeff Brown01ce2e92010-09-26 22:20:12 -07002904 injectionState->pendingForegroundDispatches);
Jeff Brown6ec402b2010-07-28 15:48:59 -07002905#endif
2906 nsecs_t remainingTimeout = endTime - now();
2907 if (remainingTimeout <= 0) {
2908#if DEBUG_INJECTION
Jeff Brown519e0242010-09-15 15:18:56 -07002909 LOGD("injectInputEvent - Timed out waiting for pending foreground "
Jeff Brown6ec402b2010-07-28 15:48:59 -07002910 "dispatches to finish.");
2911#endif
2912 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
2913 break;
2914 }
2915
2916 mInjectionSyncFinishedCondition.waitRelative(mLock, remainingTimeout);
2917 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07002918 }
2919 }
2920
Jeff Brown01ce2e92010-09-26 22:20:12 -07002921 mAllocator.releaseInjectionState(injectionState);
Jeff Brown7fbdc842010-06-17 20:52:56 -07002922 } // release lock
2923
Jeff Brown6ec402b2010-07-28 15:48:59 -07002924#if DEBUG_INJECTION
2925 LOGD("injectInputEvent - Finished with result %d. "
2926 "injectorPid=%d, injectorUid=%d",
2927 injectionResult, injectorPid, injectorUid);
2928#endif
2929
Jeff Brown7fbdc842010-06-17 20:52:56 -07002930 return injectionResult;
2931}
2932
Jeff Brownb6997262010-10-08 22:31:17 -07002933bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
2934 return injectorUid == 0
2935 || mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
2936}
2937
Jeff Brown7fbdc842010-06-17 20:52:56 -07002938void InputDispatcher::setInjectionResultLocked(EventEntry* entry, int32_t injectionResult) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002939 InjectionState* injectionState = entry->injectionState;
2940 if (injectionState) {
Jeff Brown7fbdc842010-06-17 20:52:56 -07002941#if DEBUG_INJECTION
2942 LOGD("Setting input event injection result to %d. "
2943 "injectorPid=%d, injectorUid=%d",
Jeff Brown01ce2e92010-09-26 22:20:12 -07002944 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
Jeff Brown7fbdc842010-06-17 20:52:56 -07002945#endif
2946
Jeff Brown0029c662011-03-30 02:25:18 -07002947 if (injectionState->injectionIsAsync
2948 && !(entry->policyFlags & POLICY_FLAG_FILTERED)) {
Jeff Brown6ec402b2010-07-28 15:48:59 -07002949 // Log the outcome since the injector did not wait for the injection result.
2950 switch (injectionResult) {
2951 case INPUT_EVENT_INJECTION_SUCCEEDED:
2952 LOGV("Asynchronous input event injection succeeded.");
2953 break;
2954 case INPUT_EVENT_INJECTION_FAILED:
2955 LOGW("Asynchronous input event injection failed.");
2956 break;
2957 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
2958 LOGW("Asynchronous input event injection permission denied.");
2959 break;
2960 case INPUT_EVENT_INJECTION_TIMED_OUT:
2961 LOGW("Asynchronous input event injection timed out.");
2962 break;
2963 }
2964 }
2965
Jeff Brown01ce2e92010-09-26 22:20:12 -07002966 injectionState->injectionResult = injectionResult;
Jeff Brown7fbdc842010-06-17 20:52:56 -07002967 mInjectionResultAvailableCondition.broadcast();
2968 }
2969}
2970
Jeff Brown01ce2e92010-09-26 22:20:12 -07002971void InputDispatcher::incrementPendingForegroundDispatchesLocked(EventEntry* entry) {
2972 InjectionState* injectionState = entry->injectionState;
2973 if (injectionState) {
2974 injectionState->pendingForegroundDispatches += 1;
2975 }
2976}
2977
Jeff Brown519e0242010-09-15 15:18:56 -07002978void InputDispatcher::decrementPendingForegroundDispatchesLocked(EventEntry* entry) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002979 InjectionState* injectionState = entry->injectionState;
2980 if (injectionState) {
2981 injectionState->pendingForegroundDispatches -= 1;
Jeff Brown6ec402b2010-07-28 15:48:59 -07002982
Jeff Brown01ce2e92010-09-26 22:20:12 -07002983 if (injectionState->pendingForegroundDispatches == 0) {
2984 mInjectionSyncFinishedCondition.broadcast();
2985 }
Jeff Brownb88102f2010-09-08 11:49:43 -07002986 }
2987}
2988
Jeff Brown01ce2e92010-09-26 22:20:12 -07002989const InputWindow* InputDispatcher::getWindowLocked(const sp<InputChannel>& inputChannel) {
2990 for (size_t i = 0; i < mWindows.size(); i++) {
2991 const InputWindow* window = & mWindows[i];
2992 if (window->inputChannel == inputChannel) {
2993 return window;
2994 }
2995 }
2996 return NULL;
2997}
2998
Jeff Brownb88102f2010-09-08 11:49:43 -07002999void InputDispatcher::setInputWindows(const Vector<InputWindow>& inputWindows) {
3000#if DEBUG_FOCUS
3001 LOGD("setInputWindows");
3002#endif
3003 { // acquire lock
3004 AutoMutex _l(mLock);
3005
Jeff Brown01ce2e92010-09-26 22:20:12 -07003006 // Clear old window pointers.
Jeff Brownb6997262010-10-08 22:31:17 -07003007 sp<InputChannel> oldFocusedWindowChannel;
3008 if (mFocusedWindow) {
3009 oldFocusedWindowChannel = mFocusedWindow->inputChannel;
3010 mFocusedWindow = NULL;
3011 }
Jeff Browna032cc02011-03-07 16:56:21 -08003012 sp<InputChannel> oldLastHoverWindowChannel;
3013 if (mLastHoverWindow) {
3014 oldLastHoverWindowChannel = mLastHoverWindow->inputChannel;
3015 mLastHoverWindow = NULL;
3016 }
Jeff Brownb6997262010-10-08 22:31:17 -07003017
Jeff Brownb88102f2010-09-08 11:49:43 -07003018 mWindows.clear();
Jeff Brown2a95c2a2010-09-16 12:31:46 -07003019
3020 // Loop over new windows and rebuild the necessary window pointers for
3021 // tracking focus and touch.
Jeff Brownb88102f2010-09-08 11:49:43 -07003022 mWindows.appendVector(inputWindows);
3023
3024 size_t numWindows = mWindows.size();
3025 for (size_t i = 0; i < numWindows; i++) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07003026 const InputWindow* window = & mWindows.itemAt(i);
Jeff Brownb88102f2010-09-08 11:49:43 -07003027 if (window->hasFocus) {
3028 mFocusedWindow = window;
Jeff Brown01ce2e92010-09-26 22:20:12 -07003029 break;
Jeff Brownb88102f2010-09-08 11:49:43 -07003030 }
3031 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07003032
Jeff Brownb6997262010-10-08 22:31:17 -07003033 if (oldFocusedWindowChannel != NULL) {
3034 if (!mFocusedWindow || oldFocusedWindowChannel != mFocusedWindow->inputChannel) {
3035#if DEBUG_FOCUS
3036 LOGD("Focus left window: %s",
3037 oldFocusedWindowChannel->getName().string());
3038#endif
Jeff Brownda3d5a92011-03-29 15:11:34 -07003039 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
3040 "focus left window");
3041 synthesizeCancelationEventsForInputChannelLocked(oldFocusedWindowChannel, options);
Jeff Brownb6997262010-10-08 22:31:17 -07003042 oldFocusedWindowChannel.clear();
3043 }
3044 }
3045 if (mFocusedWindow && oldFocusedWindowChannel == NULL) {
3046#if DEBUG_FOCUS
3047 LOGD("Focus entered window: %s",
3048 mFocusedWindow->inputChannel->getName().string());
3049#endif
3050 }
3051
Jeff Brown01ce2e92010-09-26 22:20:12 -07003052 for (size_t i = 0; i < mTouchState.windows.size(); ) {
3053 TouchedWindow& touchedWindow = mTouchState.windows.editItemAt(i);
3054 const InputWindow* window = getWindowLocked(touchedWindow.channel);
3055 if (window) {
3056 touchedWindow.window = window;
3057 i += 1;
3058 } else {
Jeff Brownb6997262010-10-08 22:31:17 -07003059#if DEBUG_FOCUS
3060 LOGD("Touched window was removed: %s", touchedWindow.channel->getName().string());
3061#endif
Jeff Brownda3d5a92011-03-29 15:11:34 -07003062 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
3063 "touched window was removed");
3064 synthesizeCancelationEventsForInputChannelLocked(touchedWindow.channel, options);
Jeff Brownaf48cae2010-10-15 16:20:51 -07003065 mTouchState.windows.removeAt(i);
Jeff Brown01ce2e92010-09-26 22:20:12 -07003066 }
3067 }
Jeff Brownb88102f2010-09-08 11:49:43 -07003068
Jeff Browna032cc02011-03-07 16:56:21 -08003069 // Recover the last hovered window.
3070 if (oldLastHoverWindowChannel != NULL) {
3071 mLastHoverWindow = getWindowLocked(oldLastHoverWindowChannel);
3072 oldLastHoverWindowChannel.clear();
3073 }
3074
Jeff Brownb88102f2010-09-08 11:49:43 -07003075#if DEBUG_FOCUS
Jeff Brownb6997262010-10-08 22:31:17 -07003076 //logDispatchStateLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -07003077#endif
3078 } // release lock
3079
3080 // Wake up poll loop since it may need to make new input dispatching choices.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07003081 mLooper->wake();
Jeff Brownb88102f2010-09-08 11:49:43 -07003082}
3083
3084void InputDispatcher::setFocusedApplication(const InputApplication* inputApplication) {
3085#if DEBUG_FOCUS
3086 LOGD("setFocusedApplication");
3087#endif
3088 { // acquire lock
3089 AutoMutex _l(mLock);
3090
3091 releaseFocusedApplicationLocked();
3092
3093 if (inputApplication) {
3094 mFocusedApplicationStorage = *inputApplication;
3095 mFocusedApplication = & mFocusedApplicationStorage;
3096 }
3097
3098#if DEBUG_FOCUS
Jeff Brownb6997262010-10-08 22:31:17 -07003099 //logDispatchStateLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -07003100#endif
3101 } // release lock
3102
3103 // Wake up poll loop since it may need to make new input dispatching choices.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07003104 mLooper->wake();
Jeff Brownb88102f2010-09-08 11:49:43 -07003105}
3106
3107void InputDispatcher::releaseFocusedApplicationLocked() {
3108 if (mFocusedApplication) {
3109 mFocusedApplication = NULL;
Jeff Brown928e0542011-01-10 11:17:36 -08003110 mFocusedApplicationStorage.inputApplicationHandle.clear();
Jeff Brownb88102f2010-09-08 11:49:43 -07003111 }
3112}
3113
3114void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
3115#if DEBUG_FOCUS
3116 LOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
3117#endif
3118
3119 bool changed;
3120 { // acquire lock
3121 AutoMutex _l(mLock);
3122
3123 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
Jeff Brown120a4592010-10-27 18:43:51 -07003124 if (mDispatchFrozen && !frozen) {
Jeff Brownb88102f2010-09-08 11:49:43 -07003125 resetANRTimeoutsLocked();
3126 }
3127
Jeff Brown120a4592010-10-27 18:43:51 -07003128 if (mDispatchEnabled && !enabled) {
3129 resetAndDropEverythingLocked("dispatcher is being disabled");
3130 }
3131
Jeff Brownb88102f2010-09-08 11:49:43 -07003132 mDispatchEnabled = enabled;
3133 mDispatchFrozen = frozen;
3134 changed = true;
3135 } else {
3136 changed = false;
3137 }
3138
3139#if DEBUG_FOCUS
Jeff Brownb6997262010-10-08 22:31:17 -07003140 //logDispatchStateLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -07003141#endif
3142 } // release lock
3143
3144 if (changed) {
3145 // Wake up poll loop since it may need to make new input dispatching choices.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07003146 mLooper->wake();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003147 }
3148}
3149
Jeff Brown0029c662011-03-30 02:25:18 -07003150void InputDispatcher::setInputFilterEnabled(bool enabled) {
3151#if DEBUG_FOCUS
3152 LOGD("setInputFilterEnabled: enabled=%d", enabled);
3153#endif
3154
3155 { // acquire lock
3156 AutoMutex _l(mLock);
3157
3158 if (mInputFilterEnabled == enabled) {
3159 return;
3160 }
3161
3162 mInputFilterEnabled = enabled;
3163 resetAndDropEverythingLocked("input filter is being enabled or disabled");
3164 } // release lock
3165
3166 // Wake up poll loop since there might be work to do to drop everything.
3167 mLooper->wake();
3168}
3169
Jeff Browne6504122010-09-27 14:52:15 -07003170bool InputDispatcher::transferTouchFocus(const sp<InputChannel>& fromChannel,
3171 const sp<InputChannel>& toChannel) {
3172#if DEBUG_FOCUS
3173 LOGD("transferTouchFocus: fromChannel=%s, toChannel=%s",
3174 fromChannel->getName().string(), toChannel->getName().string());
3175#endif
3176 { // acquire lock
3177 AutoMutex _l(mLock);
3178
3179 const InputWindow* fromWindow = getWindowLocked(fromChannel);
3180 const InputWindow* toWindow = getWindowLocked(toChannel);
3181 if (! fromWindow || ! toWindow) {
3182#if DEBUG_FOCUS
3183 LOGD("Cannot transfer focus because from or to window not found.");
3184#endif
3185 return false;
3186 }
3187 if (fromWindow == toWindow) {
3188#if DEBUG_FOCUS
3189 LOGD("Trivial transfer to same window.");
3190#endif
3191 return true;
3192 }
3193
3194 bool found = false;
3195 for (size_t i = 0; i < mTouchState.windows.size(); i++) {
3196 const TouchedWindow& touchedWindow = mTouchState.windows[i];
3197 if (touchedWindow.window == fromWindow) {
3198 int32_t oldTargetFlags = touchedWindow.targetFlags;
3199 BitSet32 pointerIds = touchedWindow.pointerIds;
3200
3201 mTouchState.windows.removeAt(i);
3202
Jeff Brown46e75292010-11-10 16:53:45 -08003203 int32_t newTargetFlags = oldTargetFlags
Jeff Browna032cc02011-03-07 16:56:21 -08003204 & (InputTarget::FLAG_FOREGROUND
3205 | InputTarget::FLAG_SPLIT | InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Browne6504122010-09-27 14:52:15 -07003206 mTouchState.addOrUpdateWindow(toWindow, newTargetFlags, pointerIds);
3207
3208 found = true;
3209 break;
3210 }
3211 }
3212
3213 if (! found) {
3214#if DEBUG_FOCUS
3215 LOGD("Focus transfer failed because from window did not have focus.");
3216#endif
3217 return false;
3218 }
3219
Jeff Brown9c9f1a32010-10-11 18:32:20 -07003220 ssize_t fromConnectionIndex = getConnectionIndexLocked(fromChannel);
3221 ssize_t toConnectionIndex = getConnectionIndexLocked(toChannel);
3222 if (fromConnectionIndex >= 0 && toConnectionIndex >= 0) {
3223 sp<Connection> fromConnection = mConnectionsByReceiveFd.valueAt(fromConnectionIndex);
3224 sp<Connection> toConnection = mConnectionsByReceiveFd.valueAt(toConnectionIndex);
3225
3226 fromConnection->inputState.copyPointerStateTo(toConnection->inputState);
Jeff Brownda3d5a92011-03-29 15:11:34 -07003227 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Jeff Brown9c9f1a32010-10-11 18:32:20 -07003228 "transferring touch focus from this window to another window");
Jeff Brownda3d5a92011-03-29 15:11:34 -07003229 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Jeff Brown9c9f1a32010-10-11 18:32:20 -07003230 }
3231
Jeff Browne6504122010-09-27 14:52:15 -07003232#if DEBUG_FOCUS
3233 logDispatchStateLocked();
3234#endif
3235 } // release lock
3236
3237 // Wake up poll loop since it may need to make new input dispatching choices.
3238 mLooper->wake();
3239 return true;
3240}
3241
Jeff Brown120a4592010-10-27 18:43:51 -07003242void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
3243#if DEBUG_FOCUS
3244 LOGD("Resetting and dropping all events (%s).", reason);
3245#endif
3246
Jeff Brownda3d5a92011-03-29 15:11:34 -07003247 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
3248 synthesizeCancelationEventsForAllConnectionsLocked(options);
Jeff Brown120a4592010-10-27 18:43:51 -07003249
3250 resetKeyRepeatLocked();
3251 releasePendingEventLocked();
3252 drainInboundQueueLocked();
3253 resetTargetsLocked();
3254
3255 mTouchState.reset();
3256}
3257
Jeff Brownb88102f2010-09-08 11:49:43 -07003258void InputDispatcher::logDispatchStateLocked() {
3259 String8 dump;
3260 dumpDispatchStateLocked(dump);
Jeff Brown2a95c2a2010-09-16 12:31:46 -07003261
3262 char* text = dump.lockBuffer(dump.size());
3263 char* start = text;
3264 while (*start != '\0') {
3265 char* end = strchr(start, '\n');
3266 if (*end == '\n') {
3267 *(end++) = '\0';
3268 }
3269 LOGD("%s", start);
3270 start = end;
3271 }
Jeff Brownb88102f2010-09-08 11:49:43 -07003272}
3273
3274void InputDispatcher::dumpDispatchStateLocked(String8& dump) {
Jeff Brownf2f487182010-10-01 17:46:21 -07003275 dump.appendFormat(INDENT "DispatchEnabled: %d\n", mDispatchEnabled);
3276 dump.appendFormat(INDENT "DispatchFrozen: %d\n", mDispatchFrozen);
Jeff Brownb88102f2010-09-08 11:49:43 -07003277
3278 if (mFocusedApplication) {
Jeff Brownf2f487182010-10-01 17:46:21 -07003279 dump.appendFormat(INDENT "FocusedApplication: name='%s', dispatchingTimeout=%0.3fms\n",
Jeff Brownb88102f2010-09-08 11:49:43 -07003280 mFocusedApplication->name.string(),
3281 mFocusedApplication->dispatchingTimeout / 1000000.0);
3282 } else {
Jeff Brownf2f487182010-10-01 17:46:21 -07003283 dump.append(INDENT "FocusedApplication: <null>\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003284 }
Jeff Brownf2f487182010-10-01 17:46:21 -07003285 dump.appendFormat(INDENT "FocusedWindow: name='%s'\n",
Jeff Brown2a95c2a2010-09-16 12:31:46 -07003286 mFocusedWindow != NULL ? mFocusedWindow->name.string() : "<null>");
Jeff Brownf2f487182010-10-01 17:46:21 -07003287
3288 dump.appendFormat(INDENT "TouchDown: %s\n", toString(mTouchState.down));
3289 dump.appendFormat(INDENT "TouchSplit: %s\n", toString(mTouchState.split));
Jeff Brown95712852011-01-04 19:41:59 -08003290 dump.appendFormat(INDENT "TouchDeviceId: %d\n", mTouchState.deviceId);
Jeff Brown58a2da82011-01-25 16:02:22 -08003291 dump.appendFormat(INDENT "TouchSource: 0x%08x\n", mTouchState.source);
Jeff Brownf2f487182010-10-01 17:46:21 -07003292 if (!mTouchState.windows.isEmpty()) {
3293 dump.append(INDENT "TouchedWindows:\n");
3294 for (size_t i = 0; i < mTouchState.windows.size(); i++) {
3295 const TouchedWindow& touchedWindow = mTouchState.windows[i];
3296 dump.appendFormat(INDENT2 "%d: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
3297 i, touchedWindow.window->name.string(), touchedWindow.pointerIds.value,
3298 touchedWindow.targetFlags);
3299 }
3300 } else {
3301 dump.append(INDENT "TouchedWindows: <none>\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003302 }
3303
Jeff Brownf2f487182010-10-01 17:46:21 -07003304 if (!mWindows.isEmpty()) {
3305 dump.append(INDENT "Windows:\n");
3306 for (size_t i = 0; i < mWindows.size(); i++) {
3307 const InputWindow& window = mWindows[i];
3308 dump.appendFormat(INDENT2 "%d: name='%s', paused=%s, hasFocus=%s, hasWallpaper=%s, "
3309 "visible=%s, canReceiveKeys=%s, flags=0x%08x, type=0x%08x, layer=%d, "
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003310 "frame=[%d,%d][%d,%d], scale=%f, "
Jeff Brownfbf09772011-01-16 14:06:57 -08003311 "touchableRegion=",
Jeff Brownf2f487182010-10-01 17:46:21 -07003312 i, window.name.string(),
3313 toString(window.paused),
3314 toString(window.hasFocus),
3315 toString(window.hasWallpaper),
3316 toString(window.visible),
3317 toString(window.canReceiveKeys),
3318 window.layoutParamsFlags, window.layoutParamsType,
3319 window.layer,
3320 window.frameLeft, window.frameTop,
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003321 window.frameRight, window.frameBottom,
3322 window.scaleFactor);
Jeff Brownfbf09772011-01-16 14:06:57 -08003323 dumpRegion(dump, window.touchableRegion);
3324 dump.appendFormat(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%0.3fms\n",
Jeff Brownf2f487182010-10-01 17:46:21 -07003325 window.ownerPid, window.ownerUid,
3326 window.dispatchingTimeout / 1000000.0);
3327 }
3328 } else {
3329 dump.append(INDENT "Windows: <none>\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003330 }
3331
Jeff Brownf2f487182010-10-01 17:46:21 -07003332 if (!mMonitoringChannels.isEmpty()) {
3333 dump.append(INDENT "MonitoringChannels:\n");
3334 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
3335 const sp<InputChannel>& channel = mMonitoringChannels[i];
3336 dump.appendFormat(INDENT2 "%d: '%s'\n", i, channel->getName().string());
3337 }
3338 } else {
3339 dump.append(INDENT "MonitoringChannels: <none>\n");
3340 }
Jeff Brown519e0242010-09-15 15:18:56 -07003341
Jeff Brownf2f487182010-10-01 17:46:21 -07003342 dump.appendFormat(INDENT "InboundQueue: length=%u\n", mInboundQueue.count());
3343
3344 if (!mActiveConnections.isEmpty()) {
3345 dump.append(INDENT "ActiveConnections:\n");
3346 for (size_t i = 0; i < mActiveConnections.size(); i++) {
3347 const Connection* connection = mActiveConnections[i];
Jeff Brown76860e32010-10-25 17:37:46 -07003348 dump.appendFormat(INDENT2 "%d: '%s', status=%s, outboundQueueLength=%u, "
Jeff Brownb6997262010-10-08 22:31:17 -07003349 "inputState.isNeutral=%s\n",
Jeff Brownf2f487182010-10-01 17:46:21 -07003350 i, connection->getInputChannelName(), connection->getStatusLabel(),
3351 connection->outboundQueue.count(),
Jeff Brownb6997262010-10-08 22:31:17 -07003352 toString(connection->inputState.isNeutral()));
Jeff Brownf2f487182010-10-01 17:46:21 -07003353 }
3354 } else {
3355 dump.append(INDENT "ActiveConnections: <none>\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003356 }
3357
3358 if (isAppSwitchPendingLocked()) {
Jeff Brownf2f487182010-10-01 17:46:21 -07003359 dump.appendFormat(INDENT "AppSwitch: pending, due in %01.1fms\n",
Jeff Brownb88102f2010-09-08 11:49:43 -07003360 (mAppSwitchDueTime - now()) / 1000000.0);
3361 } else {
Jeff Brownf2f487182010-10-01 17:46:21 -07003362 dump.append(INDENT "AppSwitch: not pending\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003363 }
3364}
3365
Jeff Brown928e0542011-01-10 11:17:36 -08003366status_t InputDispatcher::registerInputChannel(const sp<InputChannel>& inputChannel,
3367 const sp<InputWindowHandle>& inputWindowHandle, bool monitor) {
Jeff Brown9c3cda02010-06-15 01:31:58 -07003368#if DEBUG_REGISTRATION
Jeff Brownb88102f2010-09-08 11:49:43 -07003369 LOGD("channel '%s' ~ registerInputChannel - monitor=%s", inputChannel->getName().string(),
3370 toString(monitor));
Jeff Brown9c3cda02010-06-15 01:31:58 -07003371#endif
3372
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003373 { // acquire lock
3374 AutoMutex _l(mLock);
3375
Jeff Brown519e0242010-09-15 15:18:56 -07003376 if (getConnectionIndexLocked(inputChannel) >= 0) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003377 LOGW("Attempted to register already registered input channel '%s'",
3378 inputChannel->getName().string());
3379 return BAD_VALUE;
3380 }
3381
Jeff Brown928e0542011-01-10 11:17:36 -08003382 sp<Connection> connection = new Connection(inputChannel, inputWindowHandle);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003383 status_t status = connection->initialize();
3384 if (status) {
3385 LOGE("Failed to initialize input publisher for input channel '%s', status=%d",
3386 inputChannel->getName().string(), status);
3387 return status;
3388 }
3389
Jeff Brown2cbecea2010-08-17 15:59:26 -07003390 int32_t receiveFd = inputChannel->getReceivePipeFd();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003391 mConnectionsByReceiveFd.add(receiveFd, connection);
Jeff Brown9c3cda02010-06-15 01:31:58 -07003392
Jeff Brownb88102f2010-09-08 11:49:43 -07003393 if (monitor) {
3394 mMonitoringChannels.push(inputChannel);
3395 }
3396
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07003397 mLooper->addFd(receiveFd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
Jeff Brown2cbecea2010-08-17 15:59:26 -07003398
Jeff Brown9c3cda02010-06-15 01:31:58 -07003399 runCommandsLockedInterruptible();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003400 } // release lock
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003401 return OK;
3402}
3403
3404status_t InputDispatcher::unregisterInputChannel(const sp<InputChannel>& inputChannel) {
Jeff Brown9c3cda02010-06-15 01:31:58 -07003405#if DEBUG_REGISTRATION
Jeff Brown349703e2010-06-22 01:27:15 -07003406 LOGD("channel '%s' ~ unregisterInputChannel", inputChannel->getName().string());
Jeff Brown9c3cda02010-06-15 01:31:58 -07003407#endif
3408
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003409 { // acquire lock
3410 AutoMutex _l(mLock);
3411
Jeff Brown519e0242010-09-15 15:18:56 -07003412 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003413 if (connectionIndex < 0) {
3414 LOGW("Attempted to unregister already unregistered input channel '%s'",
3415 inputChannel->getName().string());
3416 return BAD_VALUE;
3417 }
3418
3419 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
3420 mConnectionsByReceiveFd.removeItemsAt(connectionIndex);
3421
3422 connection->status = Connection::STATUS_ZOMBIE;
3423
Jeff Brownb88102f2010-09-08 11:49:43 -07003424 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
3425 if (mMonitoringChannels[i] == inputChannel) {
3426 mMonitoringChannels.removeAt(i);
3427 break;
3428 }
3429 }
3430
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07003431 mLooper->removeFd(inputChannel->getReceivePipeFd());
Jeff Brown2cbecea2010-08-17 15:59:26 -07003432
Jeff Brown7fbdc842010-06-17 20:52:56 -07003433 nsecs_t currentTime = now();
Jeff Brownb6997262010-10-08 22:31:17 -07003434 abortBrokenDispatchCycleLocked(currentTime, connection);
Jeff Brown9c3cda02010-06-15 01:31:58 -07003435
3436 runCommandsLockedInterruptible();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003437 } // release lock
3438
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003439 // Wake the poll loop because removing the connection may have changed the current
3440 // synchronization state.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07003441 mLooper->wake();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003442 return OK;
3443}
3444
Jeff Brown519e0242010-09-15 15:18:56 -07003445ssize_t InputDispatcher::getConnectionIndexLocked(const sp<InputChannel>& inputChannel) {
Jeff Brown2cbecea2010-08-17 15:59:26 -07003446 ssize_t connectionIndex = mConnectionsByReceiveFd.indexOfKey(inputChannel->getReceivePipeFd());
3447 if (connectionIndex >= 0) {
3448 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
3449 if (connection->inputChannel.get() == inputChannel.get()) {
3450 return connectionIndex;
3451 }
3452 }
3453
3454 return -1;
3455}
3456
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003457void InputDispatcher::activateConnectionLocked(Connection* connection) {
3458 for (size_t i = 0; i < mActiveConnections.size(); i++) {
3459 if (mActiveConnections.itemAt(i) == connection) {
3460 return;
3461 }
3462 }
3463 mActiveConnections.add(connection);
3464}
3465
3466void InputDispatcher::deactivateConnectionLocked(Connection* connection) {
3467 for (size_t i = 0; i < mActiveConnections.size(); i++) {
3468 if (mActiveConnections.itemAt(i) == connection) {
3469 mActiveConnections.removeAt(i);
3470 return;
3471 }
3472 }
3473}
3474
Jeff Brown9c3cda02010-06-15 01:31:58 -07003475void InputDispatcher::onDispatchCycleStartedLocked(
Jeff Brown7fbdc842010-06-17 20:52:56 -07003476 nsecs_t currentTime, const sp<Connection>& connection) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003477}
3478
Jeff Brown9c3cda02010-06-15 01:31:58 -07003479void InputDispatcher::onDispatchCycleFinishedLocked(
Jeff Brown3915bb82010-11-05 15:02:16 -07003480 nsecs_t currentTime, const sp<Connection>& connection, bool handled) {
3481 CommandEntry* commandEntry = postCommandLocked(
3482 & InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
3483 commandEntry->connection = connection;
3484 commandEntry->handled = handled;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003485}
3486
Jeff Brown9c3cda02010-06-15 01:31:58 -07003487void InputDispatcher::onDispatchCycleBrokenLocked(
Jeff Brown7fbdc842010-06-17 20:52:56 -07003488 nsecs_t currentTime, const sp<Connection>& connection) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003489 LOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
3490 connection->getInputChannelName());
3491
Jeff Brown9c3cda02010-06-15 01:31:58 -07003492 CommandEntry* commandEntry = postCommandLocked(
3493 & InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
Jeff Brown7fbdc842010-06-17 20:52:56 -07003494 commandEntry->connection = connection;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003495}
3496
Jeff Brown519e0242010-09-15 15:18:56 -07003497void InputDispatcher::onANRLocked(
3498 nsecs_t currentTime, const InputApplication* application, const InputWindow* window,
3499 nsecs_t eventTime, nsecs_t waitStartTime) {
3500 LOGI("Application is not responding: %s. "
3501 "%01.1fms since event, %01.1fms since wait started",
3502 getApplicationWindowLabelLocked(application, window).string(),
3503 (currentTime - eventTime) / 1000000.0,
3504 (currentTime - waitStartTime) / 1000000.0);
3505
3506 CommandEntry* commandEntry = postCommandLocked(
3507 & InputDispatcher::doNotifyANRLockedInterruptible);
3508 if (application) {
Jeff Brown928e0542011-01-10 11:17:36 -08003509 commandEntry->inputApplicationHandle = application->inputApplicationHandle;
Jeff Brown519e0242010-09-15 15:18:56 -07003510 }
3511 if (window) {
Jeff Brown928e0542011-01-10 11:17:36 -08003512 commandEntry->inputWindowHandle = window->inputWindowHandle;
Jeff Brown519e0242010-09-15 15:18:56 -07003513 commandEntry->inputChannel = window->inputChannel;
3514 }
3515}
3516
Jeff Brownb88102f2010-09-08 11:49:43 -07003517void InputDispatcher::doNotifyConfigurationChangedInterruptible(
3518 CommandEntry* commandEntry) {
3519 mLock.unlock();
3520
3521 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
3522
3523 mLock.lock();
3524}
3525
Jeff Brown9c3cda02010-06-15 01:31:58 -07003526void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(
3527 CommandEntry* commandEntry) {
Jeff Brown7fbdc842010-06-17 20:52:56 -07003528 sp<Connection> connection = commandEntry->connection;
Jeff Brown9c3cda02010-06-15 01:31:58 -07003529
Jeff Brown7fbdc842010-06-17 20:52:56 -07003530 if (connection->status != Connection::STATUS_ZOMBIE) {
3531 mLock.unlock();
Jeff Brown9c3cda02010-06-15 01:31:58 -07003532
Jeff Brown928e0542011-01-10 11:17:36 -08003533 mPolicy->notifyInputChannelBroken(connection->inputWindowHandle);
Jeff Brown7fbdc842010-06-17 20:52:56 -07003534
3535 mLock.lock();
3536 }
Jeff Brown9c3cda02010-06-15 01:31:58 -07003537}
3538
Jeff Brown519e0242010-09-15 15:18:56 -07003539void InputDispatcher::doNotifyANRLockedInterruptible(
Jeff Brown9c3cda02010-06-15 01:31:58 -07003540 CommandEntry* commandEntry) {
Jeff Brown519e0242010-09-15 15:18:56 -07003541 mLock.unlock();
Jeff Brown9c3cda02010-06-15 01:31:58 -07003542
Jeff Brown519e0242010-09-15 15:18:56 -07003543 nsecs_t newTimeout = mPolicy->notifyANR(
Jeff Brown928e0542011-01-10 11:17:36 -08003544 commandEntry->inputApplicationHandle, commandEntry->inputWindowHandle);
Jeff Brown9c3cda02010-06-15 01:31:58 -07003545
Jeff Brown519e0242010-09-15 15:18:56 -07003546 mLock.lock();
Jeff Brown7fbdc842010-06-17 20:52:56 -07003547
Jeff Brown519e0242010-09-15 15:18:56 -07003548 resumeAfterTargetsNotReadyTimeoutLocked(newTimeout, commandEntry->inputChannel);
Jeff Brown9c3cda02010-06-15 01:31:58 -07003549}
3550
Jeff Brownb88102f2010-09-08 11:49:43 -07003551void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
3552 CommandEntry* commandEntry) {
3553 KeyEntry* entry = commandEntry->keyEntry;
Jeff Brown1f245102010-11-18 20:53:46 -08003554
3555 KeyEvent event;
3556 initializeKeyEvent(&event, entry);
Jeff Brownb88102f2010-09-08 11:49:43 -07003557
3558 mLock.unlock();
3559
Jeff Brown928e0542011-01-10 11:17:36 -08003560 bool consumed = mPolicy->interceptKeyBeforeDispatching(commandEntry->inputWindowHandle,
Jeff Brown1f245102010-11-18 20:53:46 -08003561 &event, entry->policyFlags);
Jeff Brownb88102f2010-09-08 11:49:43 -07003562
3563 mLock.lock();
3564
3565 entry->interceptKeyResult = consumed
3566 ? KeyEntry::INTERCEPT_KEY_RESULT_SKIP
3567 : KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
3568 mAllocator.releaseKeyEntry(entry);
3569}
3570
Jeff Brown3915bb82010-11-05 15:02:16 -07003571void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(
3572 CommandEntry* commandEntry) {
3573 sp<Connection> connection = commandEntry->connection;
3574 bool handled = commandEntry->handled;
3575
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003576 bool skipNext = false;
Jeff Brown49ed71d2010-12-06 17:13:33 -08003577 if (!connection->outboundQueue.isEmpty()) {
Jeff Brown3915bb82010-11-05 15:02:16 -07003578 DispatchEntry* dispatchEntry = connection->outboundQueue.headSentinel.next;
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003579 if (dispatchEntry->inProgress) {
3580 if (dispatchEntry->eventEntry->type == EventEntry::TYPE_KEY) {
3581 KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry);
3582 skipNext = afterKeyEventLockedInterruptible(connection,
3583 dispatchEntry, keyEntry, handled);
3584 } else if (dispatchEntry->eventEntry->type == EventEntry::TYPE_MOTION) {
3585 MotionEntry* motionEntry = static_cast<MotionEntry*>(dispatchEntry->eventEntry);
3586 skipNext = afterMotionEventLockedInterruptible(connection,
3587 dispatchEntry, motionEntry, handled);
Jeff Brown49ed71d2010-12-06 17:13:33 -08003588 }
Jeff Brown3915bb82010-11-05 15:02:16 -07003589 }
3590 }
3591
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003592 if (!skipNext) {
3593 startNextDispatchCycleLocked(now(), connection);
3594 }
3595}
3596
3597bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
3598 DispatchEntry* dispatchEntry, KeyEntry* keyEntry, bool handled) {
3599 if (!(keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK)) {
3600 // Get the fallback key state.
3601 // Clear it out after dispatching the UP.
3602 int32_t originalKeyCode = keyEntry->keyCode;
3603 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
3604 if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
3605 connection->inputState.removeFallbackKey(originalKeyCode);
3606 }
3607
3608 if (handled || !dispatchEntry->hasForegroundTarget()) {
3609 // If the application handles the original key for which we previously
3610 // generated a fallback or if the window is not a foreground window,
3611 // then cancel the associated fallback key, if any.
3612 if (fallbackKeyCode != -1) {
3613 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
3614 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
3615 "application handled the original non-fallback key "
3616 "or is no longer a foreground target, "
3617 "canceling previously dispatched fallback key");
3618 options.keyCode = fallbackKeyCode;
3619 synthesizeCancelationEventsForConnectionLocked(connection, options);
3620 }
3621 connection->inputState.removeFallbackKey(originalKeyCode);
3622 }
3623 } else {
3624 // If the application did not handle a non-fallback key, first check
3625 // that we are in a good state to perform unhandled key event processing
3626 // Then ask the policy what to do with it.
3627 bool initialDown = keyEntry->action == AKEY_EVENT_ACTION_DOWN
3628 && keyEntry->repeatCount == 0;
3629 if (fallbackKeyCode == -1 && !initialDown) {
3630#if DEBUG_OUTBOUND_EVENT_DETAILS
3631 LOGD("Unhandled key event: Skipping unhandled key event processing "
3632 "since this is not an initial down. "
3633 "keyCode=%d, action=%d, repeatCount=%d",
3634 originalKeyCode, keyEntry->action, keyEntry->repeatCount);
3635#endif
3636 return false;
3637 }
3638
3639 // Dispatch the unhandled key to the policy.
3640#if DEBUG_OUTBOUND_EVENT_DETAILS
3641 LOGD("Unhandled key event: Asking policy to perform fallback action. "
3642 "keyCode=%d, action=%d, repeatCount=%d",
3643 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount);
3644#endif
3645 KeyEvent event;
3646 initializeKeyEvent(&event, keyEntry);
3647
3648 mLock.unlock();
3649
3650 bool fallback = mPolicy->dispatchUnhandledKey(connection->inputWindowHandle,
3651 &event, keyEntry->policyFlags, &event);
3652
3653 mLock.lock();
3654
3655 if (connection->status != Connection::STATUS_NORMAL) {
3656 connection->inputState.removeFallbackKey(originalKeyCode);
3657 return true; // skip next cycle
3658 }
3659
3660 LOG_ASSERT(connection->outboundQueue.headSentinel.next == dispatchEntry);
3661
3662 // Latch the fallback keycode for this key on an initial down.
3663 // The fallback keycode cannot change at any other point in the lifecycle.
3664 if (initialDown) {
3665 if (fallback) {
3666 fallbackKeyCode = event.getKeyCode();
3667 } else {
3668 fallbackKeyCode = AKEYCODE_UNKNOWN;
3669 }
3670 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
3671 }
3672
3673 LOG_ASSERT(fallbackKeyCode != -1);
3674
3675 // Cancel the fallback key if the policy decides not to send it anymore.
3676 // We will continue to dispatch the key to the policy but we will no
3677 // longer dispatch a fallback key to the application.
3678 if (fallbackKeyCode != AKEYCODE_UNKNOWN
3679 && (!fallback || fallbackKeyCode != event.getKeyCode())) {
3680#if DEBUG_OUTBOUND_EVENT_DETAILS
3681 if (fallback) {
3682 LOGD("Unhandled key event: Policy requested to send key %d"
3683 "as a fallback for %d, but on the DOWN it had requested "
3684 "to send %d instead. Fallback canceled.",
3685 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
3686 } else {
3687 LOGD("Unhandled key event: Policy did not request fallback for %d,"
3688 "but on the DOWN it had requested to send %d. "
3689 "Fallback canceled.",
3690 originalKeyCode, fallbackKeyCode);
3691 }
3692#endif
3693
3694 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
3695 "canceling fallback, policy no longer desires it");
3696 options.keyCode = fallbackKeyCode;
3697 synthesizeCancelationEventsForConnectionLocked(connection, options);
3698
3699 fallback = false;
3700 fallbackKeyCode = AKEYCODE_UNKNOWN;
3701 if (keyEntry->action != AKEY_EVENT_ACTION_UP) {
3702 connection->inputState.setFallbackKey(originalKeyCode,
3703 fallbackKeyCode);
3704 }
3705 }
3706
3707#if DEBUG_OUTBOUND_EVENT_DETAILS
3708 {
3709 String8 msg;
3710 const KeyedVector<int32_t, int32_t>& fallbackKeys =
3711 connection->inputState.getFallbackKeys();
3712 for (size_t i = 0; i < fallbackKeys.size(); i++) {
3713 msg.appendFormat(", %d->%d", fallbackKeys.keyAt(i),
3714 fallbackKeys.valueAt(i));
3715 }
3716 LOGD("Unhandled key event: %d currently tracked fallback keys%s.",
3717 fallbackKeys.size(), msg.string());
3718 }
3719#endif
3720
3721 if (fallback) {
3722 // Restart the dispatch cycle using the fallback key.
3723 keyEntry->eventTime = event.getEventTime();
3724 keyEntry->deviceId = event.getDeviceId();
3725 keyEntry->source = event.getSource();
3726 keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
3727 keyEntry->keyCode = fallbackKeyCode;
3728 keyEntry->scanCode = event.getScanCode();
3729 keyEntry->metaState = event.getMetaState();
3730 keyEntry->repeatCount = event.getRepeatCount();
3731 keyEntry->downTime = event.getDownTime();
3732 keyEntry->syntheticRepeat = false;
3733
3734#if DEBUG_OUTBOUND_EVENT_DETAILS
3735 LOGD("Unhandled key event: Dispatching fallback key. "
3736 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
3737 originalKeyCode, fallbackKeyCode, keyEntry->metaState);
3738#endif
3739
3740 dispatchEntry->inProgress = false;
3741 startDispatchCycleLocked(now(), connection);
3742 return true; // already started next cycle
3743 } else {
3744#if DEBUG_OUTBOUND_EVENT_DETAILS
3745 LOGD("Unhandled key event: No fallback key.");
3746#endif
3747 }
3748 }
3749 }
3750 return false;
3751}
3752
3753bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
3754 DispatchEntry* dispatchEntry, MotionEntry* motionEntry, bool handled) {
3755 return false;
Jeff Brown3915bb82010-11-05 15:02:16 -07003756}
3757
Jeff Brownb88102f2010-09-08 11:49:43 -07003758void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
3759 mLock.unlock();
3760
Jeff Brown01ce2e92010-09-26 22:20:12 -07003761 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
Jeff Brownb88102f2010-09-08 11:49:43 -07003762
3763 mLock.lock();
3764}
3765
Jeff Brown3915bb82010-11-05 15:02:16 -07003766void InputDispatcher::initializeKeyEvent(KeyEvent* event, const KeyEntry* entry) {
3767 event->initialize(entry->deviceId, entry->source, entry->action, entry->flags,
3768 entry->keyCode, entry->scanCode, entry->metaState, entry->repeatCount,
3769 entry->downTime, entry->eventTime);
3770}
3771
Jeff Brown519e0242010-09-15 15:18:56 -07003772void InputDispatcher::updateDispatchStatisticsLocked(nsecs_t currentTime, const EventEntry* entry,
3773 int32_t injectionResult, nsecs_t timeSpentWaitingForApplication) {
3774 // TODO Write some statistics about how long we spend waiting.
Jeff Brownb88102f2010-09-08 11:49:43 -07003775}
3776
3777void InputDispatcher::dump(String8& dump) {
Jeff Brownf2f487182010-10-01 17:46:21 -07003778 dump.append("Input Dispatcher State:\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003779 dumpDispatchStateLocked(dump);
3780}
3781
Jeff Brown9c3cda02010-06-15 01:31:58 -07003782
Jeff Brown519e0242010-09-15 15:18:56 -07003783// --- InputDispatcher::Queue ---
3784
3785template <typename T>
3786uint32_t InputDispatcher::Queue<T>::count() const {
3787 uint32_t result = 0;
3788 for (const T* entry = headSentinel.next; entry != & tailSentinel; entry = entry->next) {
3789 result += 1;
3790 }
3791 return result;
3792}
3793
3794
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003795// --- InputDispatcher::Allocator ---
3796
3797InputDispatcher::Allocator::Allocator() {
3798}
3799
Jeff Brown01ce2e92010-09-26 22:20:12 -07003800InputDispatcher::InjectionState*
3801InputDispatcher::Allocator::obtainInjectionState(int32_t injectorPid, int32_t injectorUid) {
3802 InjectionState* injectionState = mInjectionStatePool.alloc();
3803 injectionState->refCount = 1;
3804 injectionState->injectorPid = injectorPid;
3805 injectionState->injectorUid = injectorUid;
3806 injectionState->injectionIsAsync = false;
3807 injectionState->injectionResult = INPUT_EVENT_INJECTION_PENDING;
3808 injectionState->pendingForegroundDispatches = 0;
3809 return injectionState;
3810}
3811
Jeff Brown7fbdc842010-06-17 20:52:56 -07003812void InputDispatcher::Allocator::initializeEventEntry(EventEntry* entry, int32_t type,
Jeff Brownb6997262010-10-08 22:31:17 -07003813 nsecs_t eventTime, uint32_t policyFlags) {
Jeff Brown7fbdc842010-06-17 20:52:56 -07003814 entry->type = type;
3815 entry->refCount = 1;
3816 entry->dispatchInProgress = false;
Christopher Tatee91a5db2010-06-23 16:50:30 -07003817 entry->eventTime = eventTime;
Jeff Brownb6997262010-10-08 22:31:17 -07003818 entry->policyFlags = policyFlags;
Jeff Brown01ce2e92010-09-26 22:20:12 -07003819 entry->injectionState = NULL;
3820}
3821
3822void InputDispatcher::Allocator::releaseEventEntryInjectionState(EventEntry* entry) {
3823 if (entry->injectionState) {
3824 releaseInjectionState(entry->injectionState);
3825 entry->injectionState = NULL;
3826 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07003827}
3828
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003829InputDispatcher::ConfigurationChangedEntry*
Jeff Brown7fbdc842010-06-17 20:52:56 -07003830InputDispatcher::Allocator::obtainConfigurationChangedEntry(nsecs_t eventTime) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003831 ConfigurationChangedEntry* entry = mConfigurationChangeEntryPool.alloc();
Jeff Brownb6997262010-10-08 22:31:17 -07003832 initializeEventEntry(entry, EventEntry::TYPE_CONFIGURATION_CHANGED, eventTime, 0);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003833 return entry;
3834}
3835
Jeff Brown7fbdc842010-06-17 20:52:56 -07003836InputDispatcher::KeyEntry* InputDispatcher::Allocator::obtainKeyEntry(nsecs_t eventTime,
Jeff Brown58a2da82011-01-25 16:02:22 -08003837 int32_t deviceId, uint32_t source, uint32_t policyFlags, int32_t action,
Jeff Brown7fbdc842010-06-17 20:52:56 -07003838 int32_t flags, int32_t keyCode, int32_t scanCode, int32_t metaState,
3839 int32_t repeatCount, nsecs_t downTime) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003840 KeyEntry* entry = mKeyEntryPool.alloc();
Jeff Brownb6997262010-10-08 22:31:17 -07003841 initializeEventEntry(entry, EventEntry::TYPE_KEY, eventTime, policyFlags);
Jeff Brown7fbdc842010-06-17 20:52:56 -07003842
3843 entry->deviceId = deviceId;
Jeff Brownc5ed5912010-07-14 18:48:53 -07003844 entry->source = source;
Jeff Brown7fbdc842010-06-17 20:52:56 -07003845 entry->action = action;
3846 entry->flags = flags;
3847 entry->keyCode = keyCode;
3848 entry->scanCode = scanCode;
3849 entry->metaState = metaState;
3850 entry->repeatCount = repeatCount;
3851 entry->downTime = downTime;
Jeff Brownb88102f2010-09-08 11:49:43 -07003852 entry->syntheticRepeat = false;
3853 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003854 return entry;
3855}
3856
Jeff Brown7fbdc842010-06-17 20:52:56 -07003857InputDispatcher::MotionEntry* InputDispatcher::Allocator::obtainMotionEntry(nsecs_t eventTime,
Jeff Brown58a2da82011-01-25 16:02:22 -08003858 int32_t deviceId, uint32_t source, uint32_t policyFlags, int32_t action, int32_t flags,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003859 int32_t metaState, int32_t buttonState,
3860 int32_t edgeFlags, float xPrecision, float yPrecision,
Jeff Brown7fbdc842010-06-17 20:52:56 -07003861 nsecs_t downTime, uint32_t pointerCount,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003862 const PointerProperties* pointerProperties, const PointerCoords* pointerCoords) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003863 MotionEntry* entry = mMotionEntryPool.alloc();
Jeff Brownb6997262010-10-08 22:31:17 -07003864 initializeEventEntry(entry, EventEntry::TYPE_MOTION, eventTime, policyFlags);
Jeff Brown7fbdc842010-06-17 20:52:56 -07003865
3866 entry->eventTime = eventTime;
3867 entry->deviceId = deviceId;
Jeff Brownc5ed5912010-07-14 18:48:53 -07003868 entry->source = source;
Jeff Brown7fbdc842010-06-17 20:52:56 -07003869 entry->action = action;
Jeff Brown85a31762010-09-01 17:01:00 -07003870 entry->flags = flags;
Jeff Brown7fbdc842010-06-17 20:52:56 -07003871 entry->metaState = metaState;
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003872 entry->buttonState = buttonState;
Jeff Brown7fbdc842010-06-17 20:52:56 -07003873 entry->edgeFlags = edgeFlags;
3874 entry->xPrecision = xPrecision;
3875 entry->yPrecision = yPrecision;
3876 entry->downTime = downTime;
3877 entry->pointerCount = pointerCount;
3878 entry->firstSample.eventTime = eventTime;
Jeff Brown4e91a182011-04-07 11:38:09 -07003879 entry->firstSample.eventTimeBeforeCoalescing = eventTime;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003880 entry->firstSample.next = NULL;
Jeff Brown7fbdc842010-06-17 20:52:56 -07003881 entry->lastSample = & entry->firstSample;
3882 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003883 entry->pointerProperties[i].copyFrom(pointerProperties[i]);
Jeff Brownace13b12011-03-09 17:39:48 -08003884 entry->firstSample.pointerCoords[i].copyFrom(pointerCoords[i]);
Jeff Brown7fbdc842010-06-17 20:52:56 -07003885 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003886 return entry;
3887}
3888
3889InputDispatcher::DispatchEntry* InputDispatcher::Allocator::obtainDispatchEntry(
Jeff Brownb88102f2010-09-08 11:49:43 -07003890 EventEntry* eventEntry,
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003891 int32_t targetFlags, float xOffset, float yOffset, float scaleFactor) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003892 DispatchEntry* entry = mDispatchEntryPool.alloc();
3893 entry->eventEntry = eventEntry;
3894 eventEntry->refCount += 1;
Jeff Brownb88102f2010-09-08 11:49:43 -07003895 entry->targetFlags = targetFlags;
3896 entry->xOffset = xOffset;
3897 entry->yOffset = yOffset;
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003898 entry->scaleFactor = scaleFactor;
Jeff Brownb88102f2010-09-08 11:49:43 -07003899 entry->inProgress = false;
3900 entry->headMotionSample = NULL;
3901 entry->tailMotionSample = NULL;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003902 return entry;
3903}
3904
Jeff Brown9c3cda02010-06-15 01:31:58 -07003905InputDispatcher::CommandEntry* InputDispatcher::Allocator::obtainCommandEntry(Command command) {
3906 CommandEntry* entry = mCommandEntryPool.alloc();
3907 entry->command = command;
3908 return entry;
3909}
3910
Jeff Brown01ce2e92010-09-26 22:20:12 -07003911void InputDispatcher::Allocator::releaseInjectionState(InjectionState* injectionState) {
3912 injectionState->refCount -= 1;
3913 if (injectionState->refCount == 0) {
3914 mInjectionStatePool.free(injectionState);
3915 } else {
Jeff Brownb6110c22011-04-01 16:15:13 -07003916 LOG_ASSERT(injectionState->refCount > 0);
Jeff Brown01ce2e92010-09-26 22:20:12 -07003917 }
3918}
3919
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003920void InputDispatcher::Allocator::releaseEventEntry(EventEntry* entry) {
3921 switch (entry->type) {
3922 case EventEntry::TYPE_CONFIGURATION_CHANGED:
3923 releaseConfigurationChangedEntry(static_cast<ConfigurationChangedEntry*>(entry));
3924 break;
3925 case EventEntry::TYPE_KEY:
3926 releaseKeyEntry(static_cast<KeyEntry*>(entry));
3927 break;
3928 case EventEntry::TYPE_MOTION:
3929 releaseMotionEntry(static_cast<MotionEntry*>(entry));
3930 break;
3931 default:
Jeff Brownb6110c22011-04-01 16:15:13 -07003932 LOG_ASSERT(false);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003933 break;
3934 }
3935}
3936
3937void InputDispatcher::Allocator::releaseConfigurationChangedEntry(
3938 ConfigurationChangedEntry* entry) {
3939 entry->refCount -= 1;
3940 if (entry->refCount == 0) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07003941 releaseEventEntryInjectionState(entry);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003942 mConfigurationChangeEntryPool.free(entry);
3943 } else {
Jeff Brownb6110c22011-04-01 16:15:13 -07003944 LOG_ASSERT(entry->refCount > 0);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003945 }
3946}
3947
3948void InputDispatcher::Allocator::releaseKeyEntry(KeyEntry* entry) {
3949 entry->refCount -= 1;
3950 if (entry->refCount == 0) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07003951 releaseEventEntryInjectionState(entry);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003952 mKeyEntryPool.free(entry);
3953 } else {
Jeff Brownb6110c22011-04-01 16:15:13 -07003954 LOG_ASSERT(entry->refCount > 0);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003955 }
3956}
3957
3958void InputDispatcher::Allocator::releaseMotionEntry(MotionEntry* entry) {
3959 entry->refCount -= 1;
3960 if (entry->refCount == 0) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07003961 releaseEventEntryInjectionState(entry);
Jeff Brown9c3cda02010-06-15 01:31:58 -07003962 for (MotionSample* sample = entry->firstSample.next; sample != NULL; ) {
3963 MotionSample* next = sample->next;
3964 mMotionSamplePool.free(sample);
3965 sample = next;
3966 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003967 mMotionEntryPool.free(entry);
3968 } else {
Jeff Brownb6110c22011-04-01 16:15:13 -07003969 LOG_ASSERT(entry->refCount > 0);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003970 }
3971}
3972
Jeff Browna032cc02011-03-07 16:56:21 -08003973void InputDispatcher::Allocator::freeMotionSample(MotionSample* sample) {
3974 mMotionSamplePool.free(sample);
3975}
3976
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003977void InputDispatcher::Allocator::releaseDispatchEntry(DispatchEntry* entry) {
3978 releaseEventEntry(entry->eventEntry);
3979 mDispatchEntryPool.free(entry);
3980}
3981
Jeff Brown9c3cda02010-06-15 01:31:58 -07003982void InputDispatcher::Allocator::releaseCommandEntry(CommandEntry* entry) {
3983 mCommandEntryPool.free(entry);
3984}
3985
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003986void InputDispatcher::Allocator::appendMotionSample(MotionEntry* motionEntry,
Jeff Brown7fbdc842010-06-17 20:52:56 -07003987 nsecs_t eventTime, const PointerCoords* pointerCoords) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003988 MotionSample* sample = mMotionSamplePool.alloc();
3989 sample->eventTime = eventTime;
Jeff Brown4e91a182011-04-07 11:38:09 -07003990 sample->eventTimeBeforeCoalescing = eventTime;
Jeff Brown7fbdc842010-06-17 20:52:56 -07003991 uint32_t pointerCount = motionEntry->pointerCount;
3992 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brownace13b12011-03-09 17:39:48 -08003993 sample->pointerCoords[i].copyFrom(pointerCoords[i]);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003994 }
3995
3996 sample->next = NULL;
3997 motionEntry->lastSample->next = sample;
3998 motionEntry->lastSample = sample;
3999}
4000
Jeff Brown01ce2e92010-09-26 22:20:12 -07004001void InputDispatcher::Allocator::recycleKeyEntry(KeyEntry* keyEntry) {
4002 releaseEventEntryInjectionState(keyEntry);
Jeff Brownb88102f2010-09-08 11:49:43 -07004003
Jeff Brown01ce2e92010-09-26 22:20:12 -07004004 keyEntry->dispatchInProgress = false;
4005 keyEntry->syntheticRepeat = false;
4006 keyEntry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
Jeff Brownb88102f2010-09-08 11:49:43 -07004007}
4008
4009
Jeff Brownae9fc032010-08-18 15:51:08 -07004010// --- InputDispatcher::MotionEntry ---
4011
4012uint32_t InputDispatcher::MotionEntry::countSamples() const {
4013 uint32_t count = 1;
4014 for (MotionSample* sample = firstSample.next; sample != NULL; sample = sample->next) {
4015 count += 1;
4016 }
4017 return count;
4018}
4019
Jeff Brown4e91a182011-04-07 11:38:09 -07004020bool InputDispatcher::MotionEntry::canAppendSamples(int32_t action, uint32_t pointerCount,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07004021 const PointerProperties* pointerProperties) const {
Jeff Brown4e91a182011-04-07 11:38:09 -07004022 if (this->action != action
4023 || this->pointerCount != pointerCount
4024 || this->isInjected()) {
4025 return false;
4026 }
4027 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07004028 if (this->pointerProperties[i] != pointerProperties[i]) {
Jeff Brown4e91a182011-04-07 11:38:09 -07004029 return false;
4030 }
4031 }
4032 return true;
4033}
4034
Jeff Brownb88102f2010-09-08 11:49:43 -07004035
4036// --- InputDispatcher::InputState ---
4037
Jeff Brownb6997262010-10-08 22:31:17 -07004038InputDispatcher::InputState::InputState() {
Jeff Brownb88102f2010-09-08 11:49:43 -07004039}
4040
4041InputDispatcher::InputState::~InputState() {
4042}
4043
4044bool InputDispatcher::InputState::isNeutral() const {
4045 return mKeyMementos.isEmpty() && mMotionMementos.isEmpty();
4046}
4047
Jeff Browna032cc02011-03-07 16:56:21 -08004048void InputDispatcher::InputState::trackEvent(const EventEntry* entry, int32_t action) {
Jeff Brownb88102f2010-09-08 11:49:43 -07004049 switch (entry->type) {
4050 case EventEntry::TYPE_KEY:
Jeff Browna032cc02011-03-07 16:56:21 -08004051 trackKey(static_cast<const KeyEntry*>(entry), action);
Jeff Browncc0c1592011-02-19 05:07:28 -08004052 break;
Jeff Brownb88102f2010-09-08 11:49:43 -07004053
4054 case EventEntry::TYPE_MOTION:
Jeff Browna032cc02011-03-07 16:56:21 -08004055 trackMotion(static_cast<const MotionEntry*>(entry), action);
Jeff Browncc0c1592011-02-19 05:07:28 -08004056 break;
Jeff Brownb88102f2010-09-08 11:49:43 -07004057 }
4058}
4059
Jeff Browna032cc02011-03-07 16:56:21 -08004060void InputDispatcher::InputState::trackKey(const KeyEntry* entry, int32_t action) {
Jeff Brownda3d5a92011-03-29 15:11:34 -07004061 if (action == AKEY_EVENT_ACTION_UP
4062 && (entry->flags & AKEY_EVENT_FLAG_FALLBACK)) {
4063 for (size_t i = 0; i < mFallbackKeys.size(); ) {
4064 if (mFallbackKeys.valueAt(i) == entry->keyCode) {
4065 mFallbackKeys.removeItemsAt(i);
4066 } else {
4067 i += 1;
4068 }
4069 }
4070 }
4071
Jeff Brownb88102f2010-09-08 11:49:43 -07004072 for (size_t i = 0; i < mKeyMementos.size(); i++) {
4073 KeyMemento& memento = mKeyMementos.editItemAt(i);
4074 if (memento.deviceId == entry->deviceId
4075 && memento.source == entry->source
4076 && memento.keyCode == entry->keyCode
4077 && memento.scanCode == entry->scanCode) {
4078 switch (action) {
4079 case AKEY_EVENT_ACTION_UP:
4080 mKeyMementos.removeAt(i);
Jeff Browncc0c1592011-02-19 05:07:28 -08004081 return;
Jeff Brownb88102f2010-09-08 11:49:43 -07004082
4083 case AKEY_EVENT_ACTION_DOWN:
Jeff Browncc0c1592011-02-19 05:07:28 -08004084 mKeyMementos.removeAt(i);
4085 goto Found;
Jeff Brownb88102f2010-09-08 11:49:43 -07004086
4087 default:
Jeff Browncc0c1592011-02-19 05:07:28 -08004088 return;
Jeff Brownb88102f2010-09-08 11:49:43 -07004089 }
4090 }
4091 }
4092
Jeff Browncc0c1592011-02-19 05:07:28 -08004093Found:
4094 if (action == AKEY_EVENT_ACTION_DOWN) {
Jeff Brownb88102f2010-09-08 11:49:43 -07004095 mKeyMementos.push();
4096 KeyMemento& memento = mKeyMementos.editTop();
4097 memento.deviceId = entry->deviceId;
4098 memento.source = entry->source;
4099 memento.keyCode = entry->keyCode;
4100 memento.scanCode = entry->scanCode;
Jeff Brown49ed71d2010-12-06 17:13:33 -08004101 memento.flags = entry->flags;
Jeff Brownb88102f2010-09-08 11:49:43 -07004102 memento.downTime = entry->downTime;
Jeff Brownb88102f2010-09-08 11:49:43 -07004103 }
4104}
4105
Jeff Browna032cc02011-03-07 16:56:21 -08004106void InputDispatcher::InputState::trackMotion(const MotionEntry* entry, int32_t action) {
4107 int32_t actionMasked = action & AMOTION_EVENT_ACTION_MASK;
Jeff Brownb88102f2010-09-08 11:49:43 -07004108 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4109 MotionMemento& memento = mMotionMementos.editItemAt(i);
4110 if (memento.deviceId == entry->deviceId
4111 && memento.source == entry->source) {
Jeff Browna032cc02011-03-07 16:56:21 -08004112 switch (actionMasked) {
Jeff Brownb88102f2010-09-08 11:49:43 -07004113 case AMOTION_EVENT_ACTION_UP:
4114 case AMOTION_EVENT_ACTION_CANCEL:
Jeff Browna032cc02011-03-07 16:56:21 -08004115 case AMOTION_EVENT_ACTION_HOVER_ENTER:
Jeff Browncc0c1592011-02-19 05:07:28 -08004116 case AMOTION_EVENT_ACTION_HOVER_MOVE:
Jeff Browna032cc02011-03-07 16:56:21 -08004117 case AMOTION_EVENT_ACTION_HOVER_EXIT:
Jeff Brownb88102f2010-09-08 11:49:43 -07004118 mMotionMementos.removeAt(i);
Jeff Browncc0c1592011-02-19 05:07:28 -08004119 return;
Jeff Brownb88102f2010-09-08 11:49:43 -07004120
4121 case AMOTION_EVENT_ACTION_DOWN:
Jeff Browncc0c1592011-02-19 05:07:28 -08004122 mMotionMementos.removeAt(i);
4123 goto Found;
Jeff Brownb88102f2010-09-08 11:49:43 -07004124
4125 case AMOTION_EVENT_ACTION_POINTER_UP:
Jeff Browncc0c1592011-02-19 05:07:28 -08004126 case AMOTION_EVENT_ACTION_POINTER_DOWN:
Jeff Brownb88102f2010-09-08 11:49:43 -07004127 case AMOTION_EVENT_ACTION_MOVE:
Jeff Browncc0c1592011-02-19 05:07:28 -08004128 memento.setPointers(entry);
4129 return;
Jeff Brownb88102f2010-09-08 11:49:43 -07004130
4131 default:
Jeff Browncc0c1592011-02-19 05:07:28 -08004132 return;
Jeff Brownb88102f2010-09-08 11:49:43 -07004133 }
4134 }
4135 }
4136
Jeff Browncc0c1592011-02-19 05:07:28 -08004137Found:
Jeff Browna032cc02011-03-07 16:56:21 -08004138 switch (actionMasked) {
4139 case AMOTION_EVENT_ACTION_DOWN:
4140 case AMOTION_EVENT_ACTION_HOVER_ENTER:
4141 case AMOTION_EVENT_ACTION_HOVER_MOVE:
4142 case AMOTION_EVENT_ACTION_HOVER_EXIT:
Jeff Brownb88102f2010-09-08 11:49:43 -07004143 mMotionMementos.push();
4144 MotionMemento& memento = mMotionMementos.editTop();
4145 memento.deviceId = entry->deviceId;
4146 memento.source = entry->source;
4147 memento.xPrecision = entry->xPrecision;
4148 memento.yPrecision = entry->yPrecision;
4149 memento.downTime = entry->downTime;
4150 memento.setPointers(entry);
Jeff Browna032cc02011-03-07 16:56:21 -08004151 memento.hovering = actionMasked != AMOTION_EVENT_ACTION_DOWN;
Jeff Brownb88102f2010-09-08 11:49:43 -07004152 }
4153}
4154
4155void InputDispatcher::InputState::MotionMemento::setPointers(const MotionEntry* entry) {
4156 pointerCount = entry->pointerCount;
4157 for (uint32_t i = 0; i < entry->pointerCount; i++) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07004158 pointerProperties[i].copyFrom(entry->pointerProperties[i]);
Jeff Brownace13b12011-03-09 17:39:48 -08004159 pointerCoords[i].copyFrom(entry->lastSample->pointerCoords[i]);
Jeff Brownb88102f2010-09-08 11:49:43 -07004160 }
4161}
4162
Jeff Brownb6997262010-10-08 22:31:17 -07004163void InputDispatcher::InputState::synthesizeCancelationEvents(nsecs_t currentTime,
4164 Allocator* allocator, Vector<EventEntry*>& outEvents,
Jeff Brownda3d5a92011-03-29 15:11:34 -07004165 const CancelationOptions& options) {
Jeff Brownb6997262010-10-08 22:31:17 -07004166 for (size_t i = 0; i < mKeyMementos.size(); ) {
Jeff Brownb88102f2010-09-08 11:49:43 -07004167 const KeyMemento& memento = mKeyMementos.itemAt(i);
Jeff Brown49ed71d2010-12-06 17:13:33 -08004168 if (shouldCancelKey(memento, options)) {
Jeff Brownb6997262010-10-08 22:31:17 -07004169 outEvents.push(allocator->obtainKeyEntry(currentTime,
4170 memento.deviceId, memento.source, 0,
Jeff Brown49ed71d2010-12-06 17:13:33 -08004171 AKEY_EVENT_ACTION_UP, memento.flags | AKEY_EVENT_FLAG_CANCELED,
Jeff Brownb6997262010-10-08 22:31:17 -07004172 memento.keyCode, memento.scanCode, 0, 0, memento.downTime));
4173 mKeyMementos.removeAt(i);
4174 } else {
4175 i += 1;
4176 }
Jeff Brownb88102f2010-09-08 11:49:43 -07004177 }
4178
Jeff Browna1160a72010-10-11 18:22:53 -07004179 for (size_t i = 0; i < mMotionMementos.size(); ) {
Jeff Brownb88102f2010-09-08 11:49:43 -07004180 const MotionMemento& memento = mMotionMementos.itemAt(i);
Jeff Brown49ed71d2010-12-06 17:13:33 -08004181 if (shouldCancelMotion(memento, options)) {
Jeff Brownb6997262010-10-08 22:31:17 -07004182 outEvents.push(allocator->obtainMotionEntry(currentTime,
4183 memento.deviceId, memento.source, 0,
Jeff Browna032cc02011-03-07 16:56:21 -08004184 memento.hovering
4185 ? AMOTION_EVENT_ACTION_HOVER_EXIT
4186 : AMOTION_EVENT_ACTION_CANCEL,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07004187 0, 0, 0, 0,
Jeff Brownb6997262010-10-08 22:31:17 -07004188 memento.xPrecision, memento.yPrecision, memento.downTime,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07004189 memento.pointerCount, memento.pointerProperties, memento.pointerCoords));
Jeff Brownb6997262010-10-08 22:31:17 -07004190 mMotionMementos.removeAt(i);
4191 } else {
4192 i += 1;
4193 }
Jeff Brownb88102f2010-09-08 11:49:43 -07004194 }
4195}
4196
4197void InputDispatcher::InputState::clear() {
4198 mKeyMementos.clear();
4199 mMotionMementos.clear();
Jeff Brownda3d5a92011-03-29 15:11:34 -07004200 mFallbackKeys.clear();
Jeff Brownb6997262010-10-08 22:31:17 -07004201}
4202
Jeff Brown9c9f1a32010-10-11 18:32:20 -07004203void InputDispatcher::InputState::copyPointerStateTo(InputState& other) const {
4204 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4205 const MotionMemento& memento = mMotionMementos.itemAt(i);
4206 if (memento.source & AINPUT_SOURCE_CLASS_POINTER) {
4207 for (size_t j = 0; j < other.mMotionMementos.size(); ) {
4208 const MotionMemento& otherMemento = other.mMotionMementos.itemAt(j);
4209 if (memento.deviceId == otherMemento.deviceId
4210 && memento.source == otherMemento.source) {
4211 other.mMotionMementos.removeAt(j);
4212 } else {
4213 j += 1;
4214 }
4215 }
4216 other.mMotionMementos.push(memento);
4217 }
4218 }
4219}
4220
Jeff Brownda3d5a92011-03-29 15:11:34 -07004221int32_t InputDispatcher::InputState::getFallbackKey(int32_t originalKeyCode) {
4222 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
4223 return index >= 0 ? mFallbackKeys.valueAt(index) : -1;
4224}
4225
4226void InputDispatcher::InputState::setFallbackKey(int32_t originalKeyCode,
4227 int32_t fallbackKeyCode) {
4228 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
4229 if (index >= 0) {
4230 mFallbackKeys.replaceValueAt(index, fallbackKeyCode);
4231 } else {
4232 mFallbackKeys.add(originalKeyCode, fallbackKeyCode);
4233 }
4234}
4235
4236void InputDispatcher::InputState::removeFallbackKey(int32_t originalKeyCode) {
4237 mFallbackKeys.removeItem(originalKeyCode);
4238}
4239
Jeff Brown49ed71d2010-12-06 17:13:33 -08004240bool InputDispatcher::InputState::shouldCancelKey(const KeyMemento& memento,
Jeff Brownda3d5a92011-03-29 15:11:34 -07004241 const CancelationOptions& options) {
4242 if (options.keyCode != -1 && memento.keyCode != options.keyCode) {
4243 return false;
4244 }
4245
4246 switch (options.mode) {
4247 case CancelationOptions::CANCEL_ALL_EVENTS:
4248 case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
Jeff Brownb6997262010-10-08 22:31:17 -07004249 return true;
Jeff Brownda3d5a92011-03-29 15:11:34 -07004250 case CancelationOptions::CANCEL_FALLBACK_EVENTS:
Jeff Brown49ed71d2010-12-06 17:13:33 -08004251 return memento.flags & AKEY_EVENT_FLAG_FALLBACK;
4252 default:
4253 return false;
4254 }
4255}
4256
4257bool InputDispatcher::InputState::shouldCancelMotion(const MotionMemento& memento,
Jeff Brownda3d5a92011-03-29 15:11:34 -07004258 const CancelationOptions& options) {
4259 switch (options.mode) {
4260 case CancelationOptions::CANCEL_ALL_EVENTS:
Jeff Brown49ed71d2010-12-06 17:13:33 -08004261 return true;
Jeff Brownda3d5a92011-03-29 15:11:34 -07004262 case CancelationOptions::CANCEL_POINTER_EVENTS:
Jeff Brown49ed71d2010-12-06 17:13:33 -08004263 return memento.source & AINPUT_SOURCE_CLASS_POINTER;
Jeff Brownda3d5a92011-03-29 15:11:34 -07004264 case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
Jeff Brown49ed71d2010-12-06 17:13:33 -08004265 return !(memento.source & AINPUT_SOURCE_CLASS_POINTER);
4266 default:
4267 return false;
Jeff Brownb6997262010-10-08 22:31:17 -07004268 }
Jeff Brownb88102f2010-09-08 11:49:43 -07004269}
4270
4271
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004272// --- InputDispatcher::Connection ---
4273
Jeff Brown928e0542011-01-10 11:17:36 -08004274InputDispatcher::Connection::Connection(const sp<InputChannel>& inputChannel,
4275 const sp<InputWindowHandle>& inputWindowHandle) :
4276 status(STATUS_NORMAL), inputChannel(inputChannel), inputWindowHandle(inputWindowHandle),
4277 inputPublisher(inputChannel),
Jeff Brownda3d5a92011-03-29 15:11:34 -07004278 lastEventTime(LONG_LONG_MAX), lastDispatchTime(LONG_LONG_MAX) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004279}
4280
4281InputDispatcher::Connection::~Connection() {
4282}
4283
4284status_t InputDispatcher::Connection::initialize() {
4285 return inputPublisher.initialize();
4286}
4287
Jeff Brown9c3cda02010-06-15 01:31:58 -07004288const char* InputDispatcher::Connection::getStatusLabel() const {
4289 switch (status) {
4290 case STATUS_NORMAL:
4291 return "NORMAL";
4292
4293 case STATUS_BROKEN:
4294 return "BROKEN";
4295
Jeff Brown9c3cda02010-06-15 01:31:58 -07004296 case STATUS_ZOMBIE:
4297 return "ZOMBIE";
4298
4299 default:
4300 return "UNKNOWN";
4301 }
4302}
4303
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004304InputDispatcher::DispatchEntry* InputDispatcher::Connection::findQueuedDispatchEntryForEvent(
4305 const EventEntry* eventEntry) const {
Jeff Brownb88102f2010-09-08 11:49:43 -07004306 for (DispatchEntry* dispatchEntry = outboundQueue.tailSentinel.prev;
4307 dispatchEntry != & outboundQueue.headSentinel; dispatchEntry = dispatchEntry->prev) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004308 if (dispatchEntry->eventEntry == eventEntry) {
4309 return dispatchEntry;
4310 }
4311 }
4312 return NULL;
4313}
4314
Jeff Brownb88102f2010-09-08 11:49:43 -07004315
Jeff Brown9c3cda02010-06-15 01:31:58 -07004316// --- InputDispatcher::CommandEntry ---
4317
Jeff Brownb88102f2010-09-08 11:49:43 -07004318InputDispatcher::CommandEntry::CommandEntry() :
4319 keyEntry(NULL) {
Jeff Brown9c3cda02010-06-15 01:31:58 -07004320}
4321
4322InputDispatcher::CommandEntry::~CommandEntry() {
4323}
4324
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004325
Jeff Brown01ce2e92010-09-26 22:20:12 -07004326// --- InputDispatcher::TouchState ---
4327
4328InputDispatcher::TouchState::TouchState() :
Jeff Brown58a2da82011-01-25 16:02:22 -08004329 down(false), split(false), deviceId(-1), source(0) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07004330}
4331
4332InputDispatcher::TouchState::~TouchState() {
4333}
4334
4335void InputDispatcher::TouchState::reset() {
4336 down = false;
4337 split = false;
Jeff Brown95712852011-01-04 19:41:59 -08004338 deviceId = -1;
Jeff Brown58a2da82011-01-25 16:02:22 -08004339 source = 0;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004340 windows.clear();
4341}
4342
4343void InputDispatcher::TouchState::copyFrom(const TouchState& other) {
4344 down = other.down;
4345 split = other.split;
Jeff Brown95712852011-01-04 19:41:59 -08004346 deviceId = other.deviceId;
Jeff Brown58a2da82011-01-25 16:02:22 -08004347 source = other.source;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004348 windows.clear();
4349 windows.appendVector(other.windows);
4350}
4351
4352void InputDispatcher::TouchState::addOrUpdateWindow(const InputWindow* window,
4353 int32_t targetFlags, BitSet32 pointerIds) {
4354 if (targetFlags & InputTarget::FLAG_SPLIT) {
4355 split = true;
4356 }
4357
4358 for (size_t i = 0; i < windows.size(); i++) {
4359 TouchedWindow& touchedWindow = windows.editItemAt(i);
4360 if (touchedWindow.window == window) {
4361 touchedWindow.targetFlags |= targetFlags;
4362 touchedWindow.pointerIds.value |= pointerIds.value;
4363 return;
4364 }
4365 }
4366
4367 windows.push();
4368
4369 TouchedWindow& touchedWindow = windows.editTop();
4370 touchedWindow.window = window;
4371 touchedWindow.targetFlags = targetFlags;
4372 touchedWindow.pointerIds = pointerIds;
4373 touchedWindow.channel = window->inputChannel;
4374}
4375
Jeff Browna032cc02011-03-07 16:56:21 -08004376void InputDispatcher::TouchState::filterNonAsIsTouchWindows() {
Jeff Brown01ce2e92010-09-26 22:20:12 -07004377 for (size_t i = 0 ; i < windows.size(); ) {
Jeff Browna032cc02011-03-07 16:56:21 -08004378 TouchedWindow& window = windows.editItemAt(i);
4379 if (window.targetFlags & InputTarget::FLAG_DISPATCH_AS_IS) {
4380 window.targetFlags &= ~InputTarget::FLAG_DISPATCH_MASK;
4381 window.targetFlags |= InputTarget::FLAG_DISPATCH_AS_IS;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004382 i += 1;
Jeff Browna032cc02011-03-07 16:56:21 -08004383 } else {
4384 windows.removeAt(i);
Jeff Brown01ce2e92010-09-26 22:20:12 -07004385 }
4386 }
4387}
4388
4389const InputWindow* InputDispatcher::TouchState::getFirstForegroundWindow() {
4390 for (size_t i = 0; i < windows.size(); i++) {
4391 if (windows[i].targetFlags & InputTarget::FLAG_FOREGROUND) {
4392 return windows[i].window;
4393 }
4394 }
4395 return NULL;
4396}
4397
4398
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004399// --- InputDispatcherThread ---
4400
4401InputDispatcherThread::InputDispatcherThread(const sp<InputDispatcherInterface>& dispatcher) :
4402 Thread(/*canCallJava*/ true), mDispatcher(dispatcher) {
4403}
4404
4405InputDispatcherThread::~InputDispatcherThread() {
4406}
4407
4408bool InputDispatcherThread::threadLoop() {
4409 mDispatcher->dispatchOnce();
4410 return true;
4411}
4412
4413} // namespace android