blob: 46de93310754fd1d150feb76b33e87bc2da74c06 [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,
153 const int32_t* pointerIds) {
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 Brownc3db8582010-10-20 15:33:38 -0700165 int32_t id = pointerIds[i];
166 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
Jeff Brownfbf09772011-01-16 14:06:57 -0800180static void dumpRegion(String8& dump, const SkRegion& region) {
181 if (region.isEmpty()) {
182 dump.append("<empty>");
183 return;
184 }
185
186 bool first = true;
187 for (SkRegion::Iterator it(region); !it.done(); it.next()) {
188 if (first) {
189 first = false;
190 } else {
191 dump.append("|");
192 }
193 const SkIRect& rect = it.rect();
194 dump.appendFormat("[%d,%d][%d,%d]", rect.fLeft, rect.fTop, rect.fRight, rect.fBottom);
195 }
196}
197
Jeff Brownb88102f2010-09-08 11:49:43 -0700198
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700199// --- InputDispatcher ---
200
Jeff Brown9c3cda02010-06-15 01:31:58 -0700201InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy) :
Jeff Brownb88102f2010-09-08 11:49:43 -0700202 mPolicy(policy),
Jeff Brown928e0542011-01-10 11:17:36 -0800203 mPendingEvent(NULL), mAppSwitchSawKeyDown(false), mAppSwitchDueTime(LONG_LONG_MAX),
204 mNextUnblockedEvent(NULL),
Jeff Brown0029c662011-03-30 02:25:18 -0700205 mDispatchEnabled(true), mDispatchFrozen(false), mInputFilterEnabled(false),
Jeff Brown01ce2e92010-09-26 22:20:12 -0700206 mFocusedWindow(NULL),
Jeff Brownb88102f2010-09-08 11:49:43 -0700207 mFocusedApplication(NULL),
208 mCurrentInputTargetsValid(false),
Jeff Browna032cc02011-03-07 16:56:21 -0800209 mInputTargetWaitCause(INPUT_TARGET_WAIT_CAUSE_NONE),
210 mLastHoverWindow(NULL) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -0700211 mLooper = new Looper(false);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700212
Jeff Brownb88102f2010-09-08 11:49:43 -0700213 mInboundQueue.headSentinel.refCount = -1;
214 mInboundQueue.headSentinel.type = EventEntry::TYPE_SENTINEL;
215 mInboundQueue.headSentinel.eventTime = LONG_LONG_MIN;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700216
Jeff Brownb88102f2010-09-08 11:49:43 -0700217 mInboundQueue.tailSentinel.refCount = -1;
218 mInboundQueue.tailSentinel.type = EventEntry::TYPE_SENTINEL;
219 mInboundQueue.tailSentinel.eventTime = LONG_LONG_MAX;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700220
221 mKeyRepeatState.lastKeyEntry = NULL;
Jeff Brown9c3cda02010-06-15 01:31:58 -0700222
Jeff Brownae9fc032010-08-18 15:51:08 -0700223 int32_t maxEventsPerSecond = policy->getMaxEventsPerSecond();
224 mThrottleState.minTimeBetweenEvents = 1000000000LL / maxEventsPerSecond;
225 mThrottleState.lastDeviceId = -1;
226
227#if DEBUG_THROTTLING
228 mThrottleState.originalSampleCount = 0;
229 LOGD("Throttling - Max events per second = %d", maxEventsPerSecond);
230#endif
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700231}
232
233InputDispatcher::~InputDispatcher() {
Jeff Brownb88102f2010-09-08 11:49:43 -0700234 { // acquire lock
235 AutoMutex _l(mLock);
236
237 resetKeyRepeatLocked();
Jeff Brown54a18252010-09-16 14:07:33 -0700238 releasePendingEventLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -0700239 drainInboundQueueLocked();
240 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700241
242 while (mConnectionsByReceiveFd.size() != 0) {
243 unregisterInputChannel(mConnectionsByReceiveFd.valueAt(0)->inputChannel);
244 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700245}
246
247void InputDispatcher::dispatchOnce() {
Jeff Brown9c3cda02010-06-15 01:31:58 -0700248 nsecs_t keyRepeatTimeout = mPolicy->getKeyRepeatTimeout();
Jeff Brownb21fb102010-09-07 10:44:57 -0700249 nsecs_t keyRepeatDelay = mPolicy->getKeyRepeatDelay();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700250
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700251 nsecs_t nextWakeupTime = LONG_LONG_MAX;
252 { // acquire lock
253 AutoMutex _l(mLock);
Jeff Brownb88102f2010-09-08 11:49:43 -0700254 dispatchOnceInnerLocked(keyRepeatTimeout, keyRepeatDelay, & nextWakeupTime);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700255
Jeff Brownb88102f2010-09-08 11:49:43 -0700256 if (runCommandsLockedInterruptible()) {
257 nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700258 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700259 } // release lock
260
Jeff Brownb88102f2010-09-08 11:49:43 -0700261 // Wait for callback or timeout or wake. (make sure we round up, not down)
262 nsecs_t currentTime = now();
Jeff Brownaa3855d2011-03-17 01:34:19 -0700263 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
Jeff Brown4fe6c3e2010-09-13 23:17:30 -0700264 mLooper->pollOnce(timeoutMillis);
Jeff Brownb88102f2010-09-08 11:49:43 -0700265}
266
267void InputDispatcher::dispatchOnceInnerLocked(nsecs_t keyRepeatTimeout,
268 nsecs_t keyRepeatDelay, nsecs_t* nextWakeupTime) {
269 nsecs_t currentTime = now();
270
271 // Reset the key repeat timer whenever we disallow key events, even if the next event
272 // is not a key. This is to ensure that we abort a key repeat if the device is just coming
273 // out of sleep.
274 if (keyRepeatTimeout < 0) {
275 resetKeyRepeatLocked();
276 }
277
Jeff Brownb88102f2010-09-08 11:49:43 -0700278 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
279 if (mDispatchFrozen) {
280#if DEBUG_FOCUS
281 LOGD("Dispatch frozen. Waiting some more.");
282#endif
283 return;
284 }
285
286 // Optimize latency of app switches.
287 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
288 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
289 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
290 if (mAppSwitchDueTime < *nextWakeupTime) {
291 *nextWakeupTime = mAppSwitchDueTime;
292 }
293
Jeff Brownb88102f2010-09-08 11:49:43 -0700294 // Ready to start a new event.
295 // If we don't already have a pending event, go grab one.
296 if (! mPendingEvent) {
297 if (mInboundQueue.isEmpty()) {
298 if (isAppSwitchDue) {
299 // The inbound queue is empty so the app switch key we were waiting
300 // for will never arrive. Stop waiting for it.
301 resetPendingAppSwitchLocked(false);
302 isAppSwitchDue = false;
303 }
304
305 // Synthesize a key repeat if appropriate.
306 if (mKeyRepeatState.lastKeyEntry) {
307 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
308 mPendingEvent = synthesizeKeyRepeatLocked(currentTime, keyRepeatDelay);
309 } else {
310 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
311 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
312 }
313 }
314 }
315 if (! mPendingEvent) {
316 return;
317 }
318 } else {
319 // Inbound queue has at least one entry.
320 EventEntry* entry = mInboundQueue.headSentinel.next;
321
322 // Throttle the entry if it is a move event and there are no
323 // other events behind it in the queue. Due to movement batching, additional
324 // samples may be appended to this event by the time the throttling timeout
325 // expires.
326 // TODO Make this smarter and consider throttling per device independently.
Jeff Brownb6997262010-10-08 22:31:17 -0700327 if (entry->type == EventEntry::TYPE_MOTION
328 && !isAppSwitchDue
329 && mDispatchEnabled
330 && (entry->policyFlags & POLICY_FLAG_PASS_TO_USER)
331 && !entry->isInjected()) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700332 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
333 int32_t deviceId = motionEntry->deviceId;
334 uint32_t source = motionEntry->source;
335 if (! isAppSwitchDue
336 && motionEntry->next == & mInboundQueue.tailSentinel // exactly one event
Jeff Browncc0c1592011-02-19 05:07:28 -0800337 && (motionEntry->action == AMOTION_EVENT_ACTION_MOVE
338 || motionEntry->action == AMOTION_EVENT_ACTION_HOVER_MOVE)
Jeff Brownb88102f2010-09-08 11:49:43 -0700339 && deviceId == mThrottleState.lastDeviceId
340 && source == mThrottleState.lastSource) {
341 nsecs_t nextTime = mThrottleState.lastEventTime
342 + mThrottleState.minTimeBetweenEvents;
343 if (currentTime < nextTime) {
344 // Throttle it!
345#if DEBUG_THROTTLING
346 LOGD("Throttling - Delaying motion event for "
Jeff Brown90655042010-12-02 13:50:46 -0800347 "device %d, source 0x%08x by up to %0.3fms.",
Jeff Brownb88102f2010-09-08 11:49:43 -0700348 deviceId, source, (nextTime - currentTime) * 0.000001);
349#endif
350 if (nextTime < *nextWakeupTime) {
351 *nextWakeupTime = nextTime;
352 }
353 if (mThrottleState.originalSampleCount == 0) {
354 mThrottleState.originalSampleCount =
355 motionEntry->countSamples();
356 }
357 return;
358 }
359 }
360
361#if DEBUG_THROTTLING
362 if (mThrottleState.originalSampleCount != 0) {
363 uint32_t count = motionEntry->countSamples();
364 LOGD("Throttling - Motion event sample count grew by %d from %d to %d.",
365 count - mThrottleState.originalSampleCount,
366 mThrottleState.originalSampleCount, count);
367 mThrottleState.originalSampleCount = 0;
368 }
369#endif
370
makarand.karvekarf634ded2011-03-02 15:41:03 -0600371 mThrottleState.lastEventTime = currentTime;
Jeff Brownb88102f2010-09-08 11:49:43 -0700372 mThrottleState.lastDeviceId = deviceId;
373 mThrottleState.lastSource = source;
374 }
375
376 mInboundQueue.dequeue(entry);
377 mPendingEvent = entry;
378 }
Jeff Browne2fe69e2010-10-18 13:21:23 -0700379
380 // Poke user activity for this event.
381 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
382 pokeUserActivityLocked(mPendingEvent);
383 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700384 }
385
386 // Now we have an event to dispatch.
Jeff Brown928e0542011-01-10 11:17:36 -0800387 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Jeff Brownb6110c22011-04-01 16:15:13 -0700388 LOG_ASSERT(mPendingEvent != NULL);
Jeff Brown54a18252010-09-16 14:07:33 -0700389 bool done = false;
Jeff Brownb6997262010-10-08 22:31:17 -0700390 DropReason dropReason = DROP_REASON_NOT_DROPPED;
391 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
392 dropReason = DROP_REASON_POLICY;
393 } else if (!mDispatchEnabled) {
394 dropReason = DROP_REASON_DISABLED;
395 }
Jeff Brown928e0542011-01-10 11:17:36 -0800396
397 if (mNextUnblockedEvent == mPendingEvent) {
398 mNextUnblockedEvent = NULL;
399 }
400
Jeff Brownb88102f2010-09-08 11:49:43 -0700401 switch (mPendingEvent->type) {
402 case EventEntry::TYPE_CONFIGURATION_CHANGED: {
403 ConfigurationChangedEntry* typedEntry =
404 static_cast<ConfigurationChangedEntry*>(mPendingEvent);
Jeff Brown54a18252010-09-16 14:07:33 -0700405 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Jeff Brownb6997262010-10-08 22:31:17 -0700406 dropReason = DROP_REASON_NOT_DROPPED; // configuration changes are never dropped
Jeff Brownb88102f2010-09-08 11:49:43 -0700407 break;
408 }
409
410 case EventEntry::TYPE_KEY: {
411 KeyEntry* typedEntry = static_cast<KeyEntry*>(mPendingEvent);
Jeff Brownb6997262010-10-08 22:31:17 -0700412 if (isAppSwitchDue) {
413 if (isAppSwitchKeyEventLocked(typedEntry)) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700414 resetPendingAppSwitchLocked(true);
Jeff Brownb6997262010-10-08 22:31:17 -0700415 isAppSwitchDue = false;
416 } else if (dropReason == DROP_REASON_NOT_DROPPED) {
417 dropReason = DROP_REASON_APP_SWITCH;
Jeff Brownb88102f2010-09-08 11:49:43 -0700418 }
419 }
Jeff Brown928e0542011-01-10 11:17:36 -0800420 if (dropReason == DROP_REASON_NOT_DROPPED
421 && isStaleEventLocked(currentTime, typedEntry)) {
422 dropReason = DROP_REASON_STALE;
423 }
424 if (dropReason == DROP_REASON_NOT_DROPPED && mNextUnblockedEvent) {
425 dropReason = DROP_REASON_BLOCKED;
426 }
Jeff Brownb6997262010-10-08 22:31:17 -0700427 done = dispatchKeyLocked(currentTime, typedEntry, keyRepeatTimeout,
Jeff Browne20c9e02010-10-11 14:20:19 -0700428 &dropReason, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700429 break;
430 }
431
432 case EventEntry::TYPE_MOTION: {
433 MotionEntry* typedEntry = static_cast<MotionEntry*>(mPendingEvent);
Jeff Brownb6997262010-10-08 22:31:17 -0700434 if (dropReason == DROP_REASON_NOT_DROPPED && isAppSwitchDue) {
435 dropReason = DROP_REASON_APP_SWITCH;
Jeff Brownb88102f2010-09-08 11:49:43 -0700436 }
Jeff Brown928e0542011-01-10 11:17:36 -0800437 if (dropReason == DROP_REASON_NOT_DROPPED
438 && isStaleEventLocked(currentTime, typedEntry)) {
439 dropReason = DROP_REASON_STALE;
440 }
441 if (dropReason == DROP_REASON_NOT_DROPPED && mNextUnblockedEvent) {
442 dropReason = DROP_REASON_BLOCKED;
443 }
Jeff Brownb6997262010-10-08 22:31:17 -0700444 done = dispatchMotionLocked(currentTime, typedEntry,
Jeff Browne20c9e02010-10-11 14:20:19 -0700445 &dropReason, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700446 break;
447 }
448
449 default:
Jeff Brownb6110c22011-04-01 16:15:13 -0700450 LOG_ASSERT(false);
Jeff Brownb88102f2010-09-08 11:49:43 -0700451 break;
452 }
453
Jeff Brown54a18252010-09-16 14:07:33 -0700454 if (done) {
Jeff Brownb6997262010-10-08 22:31:17 -0700455 if (dropReason != DROP_REASON_NOT_DROPPED) {
456 dropInboundEventLocked(mPendingEvent, dropReason);
457 }
458
Jeff Brown54a18252010-09-16 14:07:33 -0700459 releasePendingEventLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -0700460 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
461 }
462}
463
464bool InputDispatcher::enqueueInboundEventLocked(EventEntry* entry) {
465 bool needWake = mInboundQueue.isEmpty();
466 mInboundQueue.enqueueAtTail(entry);
467
468 switch (entry->type) {
Jeff Brownb6997262010-10-08 22:31:17 -0700469 case EventEntry::TYPE_KEY: {
Jeff Brown928e0542011-01-10 11:17:36 -0800470 // Optimize app switch latency.
471 // If the application takes too long to catch up then we drop all events preceding
472 // the app switch key.
Jeff Brownb6997262010-10-08 22:31:17 -0700473 KeyEntry* keyEntry = static_cast<KeyEntry*>(entry);
474 if (isAppSwitchKeyEventLocked(keyEntry)) {
475 if (keyEntry->action == AKEY_EVENT_ACTION_DOWN) {
476 mAppSwitchSawKeyDown = true;
477 } else if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
478 if (mAppSwitchSawKeyDown) {
479#if DEBUG_APP_SWITCH
480 LOGD("App switch is pending!");
481#endif
482 mAppSwitchDueTime = keyEntry->eventTime + APP_SWITCH_TIMEOUT;
483 mAppSwitchSawKeyDown = false;
484 needWake = true;
485 }
486 }
487 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700488 break;
489 }
Jeff Brown928e0542011-01-10 11:17:36 -0800490
491 case EventEntry::TYPE_MOTION: {
492 // Optimize case where the current application is unresponsive and the user
493 // decides to touch a window in a different application.
494 // If the application takes too long to catch up then we drop all events preceding
495 // the touch into the other window.
496 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
Jeff Brown33bbfd22011-02-24 20:55:35 -0800497 if (motionEntry->action == AMOTION_EVENT_ACTION_DOWN
Jeff Brown928e0542011-01-10 11:17:36 -0800498 && (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER)
499 && mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY
500 && mInputTargetWaitApplication != NULL) {
Jeff Brown91c69ab2011-02-14 17:03:18 -0800501 int32_t x = int32_t(motionEntry->firstSample.pointerCoords[0].
Jeff Brownebbd5d12011-02-17 13:01:34 -0800502 getAxisValue(AMOTION_EVENT_AXIS_X));
Jeff Brown91c69ab2011-02-14 17:03:18 -0800503 int32_t y = int32_t(motionEntry->firstSample.pointerCoords[0].
Jeff Brownebbd5d12011-02-17 13:01:34 -0800504 getAxisValue(AMOTION_EVENT_AXIS_Y));
Jeff Brown928e0542011-01-10 11:17:36 -0800505 const InputWindow* touchedWindow = findTouchedWindowAtLocked(x, y);
506 if (touchedWindow
507 && touchedWindow->inputWindowHandle != NULL
508 && touchedWindow->inputWindowHandle->getInputApplicationHandle()
509 != mInputTargetWaitApplication) {
510 // User touched a different application than the one we are waiting on.
511 // Flag the event, and start pruning the input queue.
512 mNextUnblockedEvent = motionEntry;
513 needWake = true;
514 }
515 }
516 break;
517 }
Jeff Brownb6997262010-10-08 22:31:17 -0700518 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700519
520 return needWake;
521}
522
Jeff Brown928e0542011-01-10 11:17:36 -0800523const InputWindow* InputDispatcher::findTouchedWindowAtLocked(int32_t x, int32_t y) {
524 // Traverse windows from front to back to find touched window.
525 size_t numWindows = mWindows.size();
526 for (size_t i = 0; i < numWindows; i++) {
527 const InputWindow* window = & mWindows.editItemAt(i);
528 int32_t flags = window->layoutParamsFlags;
529
530 if (window->visible) {
531 if (!(flags & InputWindow::FLAG_NOT_TOUCHABLE)) {
532 bool isTouchModal = (flags & (InputWindow::FLAG_NOT_FOCUSABLE
533 | InputWindow::FLAG_NOT_TOUCH_MODAL)) == 0;
Jeff Brownfbf09772011-01-16 14:06:57 -0800534 if (isTouchModal || window->touchableRegionContainsPoint(x, y)) {
Jeff Brown928e0542011-01-10 11:17:36 -0800535 // Found window.
536 return window;
537 }
538 }
539 }
540
541 if (flags & InputWindow::FLAG_SYSTEM_ERROR) {
542 // Error window is on top but not visible, so touch is dropped.
543 return NULL;
544 }
545 }
546 return NULL;
547}
548
Jeff Brownb6997262010-10-08 22:31:17 -0700549void InputDispatcher::dropInboundEventLocked(EventEntry* entry, DropReason dropReason) {
550 const char* reason;
551 switch (dropReason) {
552 case DROP_REASON_POLICY:
Jeff Browne20c9e02010-10-11 14:20:19 -0700553#if DEBUG_INBOUND_EVENT_DETAILS
Jeff Brown3122e442010-10-11 23:32:49 -0700554 LOGD("Dropped event because policy consumed it.");
Jeff Browne20c9e02010-10-11 14:20:19 -0700555#endif
Jeff Brown3122e442010-10-11 23:32:49 -0700556 reason = "inbound event was dropped because the policy consumed it";
Jeff Brownb6997262010-10-08 22:31:17 -0700557 break;
558 case DROP_REASON_DISABLED:
559 LOGI("Dropped event because input dispatch is disabled.");
560 reason = "inbound event was dropped because input dispatch is disabled";
561 break;
562 case DROP_REASON_APP_SWITCH:
563 LOGI("Dropped event because of pending overdue app switch.");
564 reason = "inbound event was dropped because of pending overdue app switch";
565 break;
Jeff Brown928e0542011-01-10 11:17:36 -0800566 case DROP_REASON_BLOCKED:
567 LOGI("Dropped event because the current application is not responding and the user "
568 "has started interating with a different application.");
569 reason = "inbound event was dropped because the current application is not responding "
570 "and the user has started interating with a different application";
571 break;
572 case DROP_REASON_STALE:
573 LOGI("Dropped event because it is stale.");
574 reason = "inbound event was dropped because it is stale";
575 break;
Jeff Brownb6997262010-10-08 22:31:17 -0700576 default:
Jeff Brownb6110c22011-04-01 16:15:13 -0700577 LOG_ASSERT(false);
Jeff Brownb6997262010-10-08 22:31:17 -0700578 return;
579 }
580
581 switch (entry->type) {
Jeff Brownda3d5a92011-03-29 15:11:34 -0700582 case EventEntry::TYPE_KEY: {
583 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
584 synthesizeCancelationEventsForAllConnectionsLocked(options);
Jeff Brownb6997262010-10-08 22:31:17 -0700585 break;
Jeff Brownda3d5a92011-03-29 15:11:34 -0700586 }
Jeff Brownb6997262010-10-08 22:31:17 -0700587 case EventEntry::TYPE_MOTION: {
588 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
589 if (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) {
Jeff Brownda3d5a92011-03-29 15:11:34 -0700590 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
591 synthesizeCancelationEventsForAllConnectionsLocked(options);
Jeff Brownb6997262010-10-08 22:31:17 -0700592 } else {
Jeff Brownda3d5a92011-03-29 15:11:34 -0700593 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
594 synthesizeCancelationEventsForAllConnectionsLocked(options);
Jeff Brownb6997262010-10-08 22:31:17 -0700595 }
596 break;
597 }
598 }
599}
600
601bool InputDispatcher::isAppSwitchKeyCode(int32_t keyCode) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700602 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL;
603}
604
Jeff Brownb6997262010-10-08 22:31:17 -0700605bool InputDispatcher::isAppSwitchKeyEventLocked(KeyEntry* keyEntry) {
606 return ! (keyEntry->flags & AKEY_EVENT_FLAG_CANCELED)
607 && isAppSwitchKeyCode(keyEntry->keyCode)
Jeff Browne20c9e02010-10-11 14:20:19 -0700608 && (keyEntry->policyFlags & POLICY_FLAG_TRUSTED)
Jeff Brownb6997262010-10-08 22:31:17 -0700609 && (keyEntry->policyFlags & POLICY_FLAG_PASS_TO_USER);
610}
611
Jeff Brownb88102f2010-09-08 11:49:43 -0700612bool InputDispatcher::isAppSwitchPendingLocked() {
613 return mAppSwitchDueTime != LONG_LONG_MAX;
614}
615
Jeff Brownb88102f2010-09-08 11:49:43 -0700616void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
617 mAppSwitchDueTime = LONG_LONG_MAX;
618
619#if DEBUG_APP_SWITCH
620 if (handled) {
621 LOGD("App switch has arrived.");
622 } else {
623 LOGD("App switch was abandoned.");
624 }
625#endif
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700626}
627
Jeff Brown928e0542011-01-10 11:17:36 -0800628bool InputDispatcher::isStaleEventLocked(nsecs_t currentTime, EventEntry* entry) {
629 return currentTime - entry->eventTime >= STALE_EVENT_TIMEOUT;
630}
631
Jeff Brown9c3cda02010-06-15 01:31:58 -0700632bool InputDispatcher::runCommandsLockedInterruptible() {
633 if (mCommandQueue.isEmpty()) {
634 return false;
635 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700636
Jeff Brown9c3cda02010-06-15 01:31:58 -0700637 do {
638 CommandEntry* commandEntry = mCommandQueue.dequeueAtHead();
639
640 Command command = commandEntry->command;
641 (this->*command)(commandEntry); // commands are implicitly 'LockedInterruptible'
642
Jeff Brown7fbdc842010-06-17 20:52:56 -0700643 commandEntry->connection.clear();
Jeff Brown9c3cda02010-06-15 01:31:58 -0700644 mAllocator.releaseCommandEntry(commandEntry);
645 } while (! mCommandQueue.isEmpty());
646 return true;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700647}
648
Jeff Brown9c3cda02010-06-15 01:31:58 -0700649InputDispatcher::CommandEntry* InputDispatcher::postCommandLocked(Command command) {
650 CommandEntry* commandEntry = mAllocator.obtainCommandEntry(command);
651 mCommandQueue.enqueueAtTail(commandEntry);
652 return commandEntry;
653}
654
Jeff Brownb88102f2010-09-08 11:49:43 -0700655void InputDispatcher::drainInboundQueueLocked() {
656 while (! mInboundQueue.isEmpty()) {
657 EventEntry* entry = mInboundQueue.dequeueAtHead();
Jeff Brown54a18252010-09-16 14:07:33 -0700658 releaseInboundEventLocked(entry);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700659 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700660}
661
Jeff Brown54a18252010-09-16 14:07:33 -0700662void InputDispatcher::releasePendingEventLocked() {
Jeff Brownb88102f2010-09-08 11:49:43 -0700663 if (mPendingEvent) {
Jeff Brown54a18252010-09-16 14:07:33 -0700664 releaseInboundEventLocked(mPendingEvent);
Jeff Brownb88102f2010-09-08 11:49:43 -0700665 mPendingEvent = NULL;
666 }
667}
668
Jeff Brown54a18252010-09-16 14:07:33 -0700669void InputDispatcher::releaseInboundEventLocked(EventEntry* entry) {
Jeff Brown01ce2e92010-09-26 22:20:12 -0700670 InjectionState* injectionState = entry->injectionState;
671 if (injectionState && injectionState->injectionResult == INPUT_EVENT_INJECTION_PENDING) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700672#if DEBUG_DISPATCH_CYCLE
Jeff Brown01ce2e92010-09-26 22:20:12 -0700673 LOGD("Injected inbound event was dropped.");
Jeff Brownb88102f2010-09-08 11:49:43 -0700674#endif
675 setInjectionResultLocked(entry, INPUT_EVENT_INJECTION_FAILED);
676 }
677 mAllocator.releaseEventEntry(entry);
678}
679
Jeff Brownb88102f2010-09-08 11:49:43 -0700680void InputDispatcher::resetKeyRepeatLocked() {
681 if (mKeyRepeatState.lastKeyEntry) {
682 mAllocator.releaseKeyEntry(mKeyRepeatState.lastKeyEntry);
683 mKeyRepeatState.lastKeyEntry = NULL;
684 }
685}
686
687InputDispatcher::KeyEntry* InputDispatcher::synthesizeKeyRepeatLocked(
Jeff Brownb21fb102010-09-07 10:44:57 -0700688 nsecs_t currentTime, nsecs_t keyRepeatDelay) {
Jeff Brown349703e2010-06-22 01:27:15 -0700689 KeyEntry* entry = mKeyRepeatState.lastKeyEntry;
690
Jeff Brown349703e2010-06-22 01:27:15 -0700691 // Reuse the repeated key entry if it is otherwise unreferenced.
Jeff Browne20c9e02010-10-11 14:20:19 -0700692 uint32_t policyFlags = (entry->policyFlags & POLICY_FLAG_RAW_MASK)
693 | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700694 if (entry->refCount == 1) {
Jeff Brown01ce2e92010-09-26 22:20:12 -0700695 mAllocator.recycleKeyEntry(entry);
Jeff Brown7fbdc842010-06-17 20:52:56 -0700696 entry->eventTime = currentTime;
Jeff Brown7fbdc842010-06-17 20:52:56 -0700697 entry->policyFlags = policyFlags;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700698 entry->repeatCount += 1;
699 } else {
Jeff Brown7fbdc842010-06-17 20:52:56 -0700700 KeyEntry* newEntry = mAllocator.obtainKeyEntry(currentTime,
Jeff Brownc5ed5912010-07-14 18:48:53 -0700701 entry->deviceId, entry->source, policyFlags,
Jeff Brown7fbdc842010-06-17 20:52:56 -0700702 entry->action, entry->flags, entry->keyCode, entry->scanCode,
Jeff Brown00fa7bd2010-07-02 15:37:36 -0700703 entry->metaState, entry->repeatCount + 1, entry->downTime);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700704
705 mKeyRepeatState.lastKeyEntry = newEntry;
706 mAllocator.releaseKeyEntry(entry);
707
708 entry = newEntry;
709 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700710 entry->syntheticRepeat = true;
711
712 // Increment reference count since we keep a reference to the event in
713 // mKeyRepeatState.lastKeyEntry in addition to the one we return.
714 entry->refCount += 1;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700715
Jeff Brownb21fb102010-09-07 10:44:57 -0700716 mKeyRepeatState.nextRepeatTime = currentTime + keyRepeatDelay;
Jeff Brownb88102f2010-09-08 11:49:43 -0700717 return entry;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700718}
719
Jeff Brownb88102f2010-09-08 11:49:43 -0700720bool InputDispatcher::dispatchConfigurationChangedLocked(
721 nsecs_t currentTime, ConfigurationChangedEntry* entry) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700722#if DEBUG_OUTBOUND_EVENT_DETAILS
Jeff Brownb88102f2010-09-08 11:49:43 -0700723 LOGD("dispatchConfigurationChanged - eventTime=%lld", entry->eventTime);
724#endif
725
726 // Reset key repeating in case a keyboard device was added or removed or something.
727 resetKeyRepeatLocked();
728
729 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
730 CommandEntry* commandEntry = postCommandLocked(
731 & InputDispatcher::doNotifyConfigurationChangedInterruptible);
732 commandEntry->eventTime = entry->eventTime;
733 return true;
734}
735
736bool InputDispatcher::dispatchKeyLocked(
737 nsecs_t currentTime, KeyEntry* entry, nsecs_t keyRepeatTimeout,
Jeff Browne20c9e02010-10-11 14:20:19 -0700738 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Jeff Browne46a0a42010-11-02 17:58:22 -0700739 // Preprocessing.
740 if (! entry->dispatchInProgress) {
741 if (entry->repeatCount == 0
742 && entry->action == AKEY_EVENT_ACTION_DOWN
743 && (entry->policyFlags & POLICY_FLAG_TRUSTED)
Jeff Brown0029c662011-03-30 02:25:18 -0700744 && (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
Jeff Browne46a0a42010-11-02 17:58:22 -0700745 if (mKeyRepeatState.lastKeyEntry
746 && mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode) {
747 // We have seen two identical key downs in a row which indicates that the device
748 // driver is automatically generating key repeats itself. We take note of the
749 // repeat here, but we disable our own next key repeat timer since it is clear that
750 // we will not need to synthesize key repeats ourselves.
751 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
752 resetKeyRepeatLocked();
753 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
754 } else {
755 // Not a repeat. Save key down state in case we do see a repeat later.
756 resetKeyRepeatLocked();
757 mKeyRepeatState.nextRepeatTime = entry->eventTime + keyRepeatTimeout;
758 }
759 mKeyRepeatState.lastKeyEntry = entry;
760 entry->refCount += 1;
761 } else if (! entry->syntheticRepeat) {
762 resetKeyRepeatLocked();
763 }
764
Jeff Browne2e01262011-03-02 20:34:30 -0800765 if (entry->repeatCount == 1) {
766 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
767 } else {
768 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
769 }
770
Jeff Browne46a0a42010-11-02 17:58:22 -0700771 entry->dispatchInProgress = true;
772 resetTargetsLocked();
773
774 logOutboundKeyDetailsLocked("dispatchKey - ", entry);
775 }
776
Jeff Brown54a18252010-09-16 14:07:33 -0700777 // Give the policy a chance to intercept the key.
778 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
Jeff Browne20c9e02010-10-11 14:20:19 -0700779 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Jeff Brown54a18252010-09-16 14:07:33 -0700780 CommandEntry* commandEntry = postCommandLocked(
781 & InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
Jeff Browne20c9e02010-10-11 14:20:19 -0700782 if (mFocusedWindow) {
Jeff Brown928e0542011-01-10 11:17:36 -0800783 commandEntry->inputWindowHandle = mFocusedWindow->inputWindowHandle;
Jeff Brown54a18252010-09-16 14:07:33 -0700784 }
785 commandEntry->keyEntry = entry;
786 entry->refCount += 1;
787 return false; // wait for the command to run
788 } else {
789 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
790 }
791 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Jeff Browne20c9e02010-10-11 14:20:19 -0700792 if (*dropReason == DROP_REASON_NOT_DROPPED) {
793 *dropReason = DROP_REASON_POLICY;
794 }
Jeff Brown54a18252010-09-16 14:07:33 -0700795 }
796
797 // Clean up if dropping the event.
Jeff Browne20c9e02010-10-11 14:20:19 -0700798 if (*dropReason != DROP_REASON_NOT_DROPPED) {
Jeff Brown54a18252010-09-16 14:07:33 -0700799 resetTargetsLocked();
Jeff Brown3122e442010-10-11 23:32:49 -0700800 setInjectionResultLocked(entry, *dropReason == DROP_REASON_POLICY
801 ? INPUT_EVENT_INJECTION_SUCCEEDED : INPUT_EVENT_INJECTION_FAILED);
Jeff Brown54a18252010-09-16 14:07:33 -0700802 return true;
803 }
804
Jeff Brownb88102f2010-09-08 11:49:43 -0700805 // Identify targets.
806 if (! mCurrentInputTargetsValid) {
Jeff Brown01ce2e92010-09-26 22:20:12 -0700807 int32_t injectionResult = findFocusedWindowTargetsLocked(currentTime,
808 entry, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700809 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
810 return false;
811 }
812
813 setInjectionResultLocked(entry, injectionResult);
814 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
815 return true;
816 }
817
818 addMonitoringTargetsLocked();
Jeff Brown01ce2e92010-09-26 22:20:12 -0700819 commitTargetsLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -0700820 }
821
822 // Dispatch the key.
823 dispatchEventToCurrentInputTargetsLocked(currentTime, entry, false);
Jeff Brownb88102f2010-09-08 11:49:43 -0700824 return true;
825}
826
827void InputDispatcher::logOutboundKeyDetailsLocked(const char* prefix, const KeyEntry* entry) {
828#if DEBUG_OUTBOUND_EVENT_DETAILS
Jeff Brown90655042010-12-02 13:50:46 -0800829 LOGD("%seventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, "
Jeff Brownb88102f2010-09-08 11:49:43 -0700830 "action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, "
Jeff Browne46a0a42010-11-02 17:58:22 -0700831 "repeatCount=%d, downTime=%lld",
Jeff Brownb88102f2010-09-08 11:49:43 -0700832 prefix,
833 entry->eventTime, entry->deviceId, entry->source, entry->policyFlags,
834 entry->action, entry->flags, entry->keyCode, entry->scanCode, entry->metaState,
Jeff Browne46a0a42010-11-02 17:58:22 -0700835 entry->repeatCount, entry->downTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700836#endif
837}
838
839bool InputDispatcher::dispatchMotionLocked(
Jeff Browne20c9e02010-10-11 14:20:19 -0700840 nsecs_t currentTime, MotionEntry* entry, DropReason* dropReason, nsecs_t* nextWakeupTime) {
Jeff Browne46a0a42010-11-02 17:58:22 -0700841 // Preprocessing.
842 if (! entry->dispatchInProgress) {
843 entry->dispatchInProgress = true;
844 resetTargetsLocked();
845
846 logOutboundMotionDetailsLocked("dispatchMotion - ", entry);
847 }
848
Jeff Brown54a18252010-09-16 14:07:33 -0700849 // Clean up if dropping the event.
Jeff Browne20c9e02010-10-11 14:20:19 -0700850 if (*dropReason != DROP_REASON_NOT_DROPPED) {
Jeff Brown54a18252010-09-16 14:07:33 -0700851 resetTargetsLocked();
Jeff Brown3122e442010-10-11 23:32:49 -0700852 setInjectionResultLocked(entry, *dropReason == DROP_REASON_POLICY
853 ? INPUT_EVENT_INJECTION_SUCCEEDED : INPUT_EVENT_INJECTION_FAILED);
Jeff Brown54a18252010-09-16 14:07:33 -0700854 return true;
855 }
856
Jeff Brownb88102f2010-09-08 11:49:43 -0700857 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
858
859 // Identify targets.
Jeff Browncc0c1592011-02-19 05:07:28 -0800860 bool conflictingPointerActions = false;
Jeff Brownb88102f2010-09-08 11:49:43 -0700861 if (! mCurrentInputTargetsValid) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700862 int32_t injectionResult;
Jeff Browna032cc02011-03-07 16:56:21 -0800863 const MotionSample* splitBatchAfterSample = NULL;
Jeff Brownb88102f2010-09-08 11:49:43 -0700864 if (isPointerEvent) {
865 // Pointer event. (eg. touchscreen)
Jeff Brown01ce2e92010-09-26 22:20:12 -0700866 injectionResult = findTouchedWindowTargetsLocked(currentTime,
Jeff Browna032cc02011-03-07 16:56:21 -0800867 entry, nextWakeupTime, &conflictingPointerActions, &splitBatchAfterSample);
Jeff Brownb88102f2010-09-08 11:49:43 -0700868 } else {
869 // Non touch event. (eg. trackball)
Jeff Brown01ce2e92010-09-26 22:20:12 -0700870 injectionResult = findFocusedWindowTargetsLocked(currentTime,
871 entry, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700872 }
873 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
874 return false;
875 }
876
877 setInjectionResultLocked(entry, injectionResult);
878 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
879 return true;
880 }
881
882 addMonitoringTargetsLocked();
Jeff Brown01ce2e92010-09-26 22:20:12 -0700883 commitTargetsLocked();
Jeff Browna032cc02011-03-07 16:56:21 -0800884
885 // Unbatch the event if necessary by splitting it into two parts after the
886 // motion sample indicated by splitBatchAfterSample.
887 if (splitBatchAfterSample && splitBatchAfterSample->next) {
888#if DEBUG_BATCHING
889 uint32_t originalSampleCount = entry->countSamples();
890#endif
891 MotionSample* nextSample = splitBatchAfterSample->next;
892 MotionEntry* nextEntry = mAllocator.obtainMotionEntry(nextSample->eventTime,
893 entry->deviceId, entry->source, entry->policyFlags,
894 entry->action, entry->flags, entry->metaState, entry->edgeFlags,
895 entry->xPrecision, entry->yPrecision, entry->downTime,
896 entry->pointerCount, entry->pointerIds, nextSample->pointerCoords);
897 if (nextSample != entry->lastSample) {
898 nextEntry->firstSample.next = nextSample->next;
899 nextEntry->lastSample = entry->lastSample;
900 }
901 mAllocator.freeMotionSample(nextSample);
902
903 entry->lastSample = const_cast<MotionSample*>(splitBatchAfterSample);
904 entry->lastSample->next = NULL;
905
906 if (entry->injectionState) {
907 nextEntry->injectionState = entry->injectionState;
908 entry->injectionState->refCount += 1;
909 }
910
911#if DEBUG_BATCHING
912 LOGD("Split batch of %d samples into two parts, first part has %d samples, "
913 "second part has %d samples.", originalSampleCount,
914 entry->countSamples(), nextEntry->countSamples());
915#endif
916
917 mInboundQueue.enqueueAtHead(nextEntry);
918 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700919 }
920
921 // Dispatch the motion.
Jeff Browncc0c1592011-02-19 05:07:28 -0800922 if (conflictingPointerActions) {
Jeff Brownda3d5a92011-03-29 15:11:34 -0700923 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
924 "conflicting pointer actions");
925 synthesizeCancelationEventsForAllConnectionsLocked(options);
Jeff Browncc0c1592011-02-19 05:07:28 -0800926 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700927 dispatchEventToCurrentInputTargetsLocked(currentTime, entry, false);
Jeff Brownb88102f2010-09-08 11:49:43 -0700928 return true;
929}
930
931
932void InputDispatcher::logOutboundMotionDetailsLocked(const char* prefix, const MotionEntry* entry) {
933#if DEBUG_OUTBOUND_EVENT_DETAILS
Jeff Brown90655042010-12-02 13:50:46 -0800934 LOGD("%seventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, "
Jeff Brown85a31762010-09-01 17:01:00 -0700935 "action=0x%x, flags=0x%x, "
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700936 "metaState=0x%x, edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%lld",
Jeff Brownb88102f2010-09-08 11:49:43 -0700937 prefix,
Jeff Brown85a31762010-09-01 17:01:00 -0700938 entry->eventTime, entry->deviceId, entry->source, entry->policyFlags,
939 entry->action, entry->flags,
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700940 entry->metaState, entry->edgeFlags, entry->xPrecision, entry->yPrecision,
941 entry->downTime);
942
943 // Print the most recent sample that we have available, this may change due to batching.
944 size_t sampleCount = 1;
Jeff Brownb88102f2010-09-08 11:49:43 -0700945 const MotionSample* sample = & entry->firstSample;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700946 for (; sample->next != NULL; sample = sample->next) {
947 sampleCount += 1;
948 }
949 for (uint32_t i = 0; i < entry->pointerCount; i++) {
Jeff Brown8d608662010-08-30 03:02:23 -0700950 LOGD(" Pointer %d: id=%d, x=%f, y=%f, pressure=%f, size=%f, "
Jeff Brown85a31762010-09-01 17:01:00 -0700951 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
Jeff Brown8d608662010-08-30 03:02:23 -0700952 "orientation=%f",
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700953 i, entry->pointerIds[i],
Jeff Brownebbd5d12011-02-17 13:01:34 -0800954 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
955 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
956 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
957 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
958 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
959 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
960 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
961 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
962 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700963 }
964
965 // Keep in mind that due to batching, it is possible for the number of samples actually
966 // dispatched to change before the application finally consumed them.
Jeff Brownc5ed5912010-07-14 18:48:53 -0700967 if (entry->action == AMOTION_EVENT_ACTION_MOVE) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700968 LOGD(" ... Total movement samples currently batched %d ...", sampleCount);
969 }
970#endif
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700971}
972
973void InputDispatcher::dispatchEventToCurrentInputTargetsLocked(nsecs_t currentTime,
974 EventEntry* eventEntry, bool resumeWithAppendedMotionSample) {
975#if DEBUG_DISPATCH_CYCLE
Jeff Brown9c3cda02010-06-15 01:31:58 -0700976 LOGD("dispatchEventToCurrentInputTargets - "
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700977 "resumeWithAppendedMotionSample=%s",
Jeff Brownb88102f2010-09-08 11:49:43 -0700978 toString(resumeWithAppendedMotionSample));
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700979#endif
980
Jeff Brownb6110c22011-04-01 16:15:13 -0700981 LOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
Jeff Brown9c3cda02010-06-15 01:31:58 -0700982
Jeff Browne2fe69e2010-10-18 13:21:23 -0700983 pokeUserActivityLocked(eventEntry);
984
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700985 for (size_t i = 0; i < mCurrentInputTargets.size(); i++) {
986 const InputTarget& inputTarget = mCurrentInputTargets.itemAt(i);
987
Jeff Brown519e0242010-09-15 15:18:56 -0700988 ssize_t connectionIndex = getConnectionIndexLocked(inputTarget.inputChannel);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700989 if (connectionIndex >= 0) {
990 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
Jeff Brown7fbdc842010-06-17 20:52:56 -0700991 prepareDispatchCycleLocked(currentTime, connection, eventEntry, & inputTarget,
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700992 resumeWithAppendedMotionSample);
993 } else {
Jeff Brownb6997262010-10-08 22:31:17 -0700994#if DEBUG_FOCUS
995 LOGD("Dropping event delivery to target with channel '%s' because it "
996 "is no longer registered with the input dispatcher.",
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700997 inputTarget.inputChannel->getName().string());
Jeff Brownb6997262010-10-08 22:31:17 -0700998#endif
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700999 }
1000 }
1001}
1002
Jeff Brown54a18252010-09-16 14:07:33 -07001003void InputDispatcher::resetTargetsLocked() {
Jeff Brownb88102f2010-09-08 11:49:43 -07001004 mCurrentInputTargetsValid = false;
1005 mCurrentInputTargets.clear();
Jeff Brownb88102f2010-09-08 11:49:43 -07001006 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_NONE;
Jeff Brown928e0542011-01-10 11:17:36 -08001007 mInputTargetWaitApplication.clear();
Jeff Brownb88102f2010-09-08 11:49:43 -07001008}
1009
Jeff Brown01ce2e92010-09-26 22:20:12 -07001010void InputDispatcher::commitTargetsLocked() {
Jeff Brownb88102f2010-09-08 11:49:43 -07001011 mCurrentInputTargetsValid = true;
1012}
1013
1014int32_t InputDispatcher::handleTargetsNotReadyLocked(nsecs_t currentTime,
1015 const EventEntry* entry, const InputApplication* application, const InputWindow* window,
1016 nsecs_t* nextWakeupTime) {
1017 if (application == NULL && window == NULL) {
1018 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY) {
1019#if DEBUG_FOCUS
1020 LOGD("Waiting for system to become ready for input.");
1021#endif
1022 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY;
1023 mInputTargetWaitStartTime = currentTime;
1024 mInputTargetWaitTimeoutTime = LONG_LONG_MAX;
1025 mInputTargetWaitTimeoutExpired = false;
Jeff Brown928e0542011-01-10 11:17:36 -08001026 mInputTargetWaitApplication.clear();
Jeff Brownb88102f2010-09-08 11:49:43 -07001027 }
1028 } else {
1029 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
1030#if DEBUG_FOCUS
Jeff Brown519e0242010-09-15 15:18:56 -07001031 LOGD("Waiting for application to become ready for input: %s",
1032 getApplicationWindowLabelLocked(application, window).string());
Jeff Brownb88102f2010-09-08 11:49:43 -07001033#endif
1034 nsecs_t timeout = window ? window->dispatchingTimeout :
1035 application ? application->dispatchingTimeout : DEFAULT_INPUT_DISPATCHING_TIMEOUT;
1036
1037 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY;
1038 mInputTargetWaitStartTime = currentTime;
1039 mInputTargetWaitTimeoutTime = currentTime + timeout;
1040 mInputTargetWaitTimeoutExpired = false;
Jeff Brown928e0542011-01-10 11:17:36 -08001041 mInputTargetWaitApplication.clear();
1042
1043 if (window && window->inputWindowHandle != NULL) {
1044 mInputTargetWaitApplication =
1045 window->inputWindowHandle->getInputApplicationHandle();
1046 }
1047 if (mInputTargetWaitApplication == NULL && application) {
1048 mInputTargetWaitApplication = application->inputApplicationHandle;
1049 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001050 }
1051 }
1052
1053 if (mInputTargetWaitTimeoutExpired) {
1054 return INPUT_EVENT_INJECTION_TIMED_OUT;
1055 }
1056
1057 if (currentTime >= mInputTargetWaitTimeoutTime) {
Jeff Brown519e0242010-09-15 15:18:56 -07001058 onANRLocked(currentTime, application, window, entry->eventTime, mInputTargetWaitStartTime);
Jeff Brownb88102f2010-09-08 11:49:43 -07001059
1060 // Force poll loop to wake up immediately on next iteration once we get the
1061 // ANR response back from the policy.
1062 *nextWakeupTime = LONG_LONG_MIN;
1063 return INPUT_EVENT_INJECTION_PENDING;
1064 } else {
1065 // Force poll loop to wake up when timeout is due.
1066 if (mInputTargetWaitTimeoutTime < *nextWakeupTime) {
1067 *nextWakeupTime = mInputTargetWaitTimeoutTime;
1068 }
1069 return INPUT_EVENT_INJECTION_PENDING;
1070 }
1071}
1072
Jeff Brown519e0242010-09-15 15:18:56 -07001073void InputDispatcher::resumeAfterTargetsNotReadyTimeoutLocked(nsecs_t newTimeout,
1074 const sp<InputChannel>& inputChannel) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001075 if (newTimeout > 0) {
1076 // Extend the timeout.
1077 mInputTargetWaitTimeoutTime = now() + newTimeout;
1078 } else {
1079 // Give up.
1080 mInputTargetWaitTimeoutExpired = true;
Jeff Brown519e0242010-09-15 15:18:56 -07001081
Jeff Brown01ce2e92010-09-26 22:20:12 -07001082 // Release the touch targets.
1083 mTouchState.reset();
Jeff Brown2a95c2a2010-09-16 12:31:46 -07001084
Jeff Brown519e0242010-09-15 15:18:56 -07001085 // Input state will not be realistic. Mark it out of sync.
Jeff Browndc3e0052010-09-16 11:02:16 -07001086 if (inputChannel.get()) {
1087 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
1088 if (connectionIndex >= 0) {
1089 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
Jeff Brown00045a72010-12-09 18:10:30 -08001090 if (connection->status == Connection::STATUS_NORMAL) {
Jeff Brownda3d5a92011-03-29 15:11:34 -07001091 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
Jeff Brown00045a72010-12-09 18:10:30 -08001092 "application not responding");
Jeff Brownda3d5a92011-03-29 15:11:34 -07001093 synthesizeCancelationEventsForConnectionLocked(connection, options);
Jeff Brown00045a72010-12-09 18:10:30 -08001094 }
Jeff Browndc3e0052010-09-16 11:02:16 -07001095 }
Jeff Brown519e0242010-09-15 15:18:56 -07001096 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001097 }
1098}
1099
Jeff Brown519e0242010-09-15 15:18:56 -07001100nsecs_t InputDispatcher::getTimeSpentWaitingForApplicationLocked(
Jeff Brownb88102f2010-09-08 11:49:43 -07001101 nsecs_t currentTime) {
1102 if (mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
1103 return currentTime - mInputTargetWaitStartTime;
1104 }
1105 return 0;
1106}
1107
1108void InputDispatcher::resetANRTimeoutsLocked() {
1109#if DEBUG_FOCUS
1110 LOGD("Resetting ANR timeouts.");
1111#endif
1112
Jeff Brownb88102f2010-09-08 11:49:43 -07001113 // Reset input target wait timeout.
1114 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_NONE;
1115}
1116
Jeff Brown01ce2e92010-09-26 22:20:12 -07001117int32_t InputDispatcher::findFocusedWindowTargetsLocked(nsecs_t currentTime,
1118 const EventEntry* entry, nsecs_t* nextWakeupTime) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001119 mCurrentInputTargets.clear();
1120
1121 int32_t injectionResult;
1122
1123 // If there is no currently focused window and no focused application
1124 // then drop the event.
1125 if (! mFocusedWindow) {
1126 if (mFocusedApplication) {
1127#if DEBUG_FOCUS
1128 LOGD("Waiting because there is no focused window but there is a "
Jeff Brown519e0242010-09-15 15:18:56 -07001129 "focused application that may eventually add a window: %s.",
1130 getApplicationWindowLabelLocked(mFocusedApplication, NULL).string());
Jeff Brownb88102f2010-09-08 11:49:43 -07001131#endif
1132 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
1133 mFocusedApplication, NULL, nextWakeupTime);
1134 goto Unresponsive;
1135 }
1136
1137 LOGI("Dropping event because there is no focused window or focused application.");
1138 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1139 goto Failed;
1140 }
1141
1142 // Check permissions.
Jeff Brown01ce2e92010-09-26 22:20:12 -07001143 if (! checkInjectionPermission(mFocusedWindow, entry->injectionState)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001144 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1145 goto Failed;
1146 }
1147
1148 // If the currently focused window is paused then keep waiting.
1149 if (mFocusedWindow->paused) {
1150#if DEBUG_FOCUS
1151 LOGD("Waiting because focused window is paused.");
1152#endif
1153 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
1154 mFocusedApplication, mFocusedWindow, nextWakeupTime);
1155 goto Unresponsive;
1156 }
1157
Jeff Brown519e0242010-09-15 15:18:56 -07001158 // If the currently focused window is still working on previous events then keep waiting.
1159 if (! isWindowFinishedWithPreviousInputLocked(mFocusedWindow)) {
1160#if DEBUG_FOCUS
1161 LOGD("Waiting because focused window still processing previous input.");
1162#endif
1163 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
1164 mFocusedApplication, mFocusedWindow, nextWakeupTime);
1165 goto Unresponsive;
1166 }
1167
Jeff Brownb88102f2010-09-08 11:49:43 -07001168 // Success! Output targets.
1169 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
Jeff Browna032cc02011-03-07 16:56:21 -08001170 addWindowTargetLocked(mFocusedWindow,
1171 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS, BitSet32(0));
Jeff Brownb88102f2010-09-08 11:49:43 -07001172
1173 // Done.
1174Failed:
1175Unresponsive:
Jeff Brown519e0242010-09-15 15:18:56 -07001176 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
1177 updateDispatchStatisticsLocked(currentTime, entry,
1178 injectionResult, timeSpentWaitingForApplication);
Jeff Brownb88102f2010-09-08 11:49:43 -07001179#if DEBUG_FOCUS
Jeff Brown519e0242010-09-15 15:18:56 -07001180 LOGD("findFocusedWindow finished: injectionResult=%d, "
1181 "timeSpendWaitingForApplication=%0.1fms",
1182 injectionResult, timeSpentWaitingForApplication / 1000000.0);
Jeff Brownb88102f2010-09-08 11:49:43 -07001183#endif
1184 return injectionResult;
1185}
1186
Jeff Brown01ce2e92010-09-26 22:20:12 -07001187int32_t InputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime,
Jeff Browna032cc02011-03-07 16:56:21 -08001188 const MotionEntry* entry, nsecs_t* nextWakeupTime, bool* outConflictingPointerActions,
1189 const MotionSample** outSplitBatchAfterSample) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001190 enum InjectionPermission {
1191 INJECTION_PERMISSION_UNKNOWN,
1192 INJECTION_PERMISSION_GRANTED,
1193 INJECTION_PERMISSION_DENIED
1194 };
1195
Jeff Brownb88102f2010-09-08 11:49:43 -07001196 mCurrentInputTargets.clear();
1197
1198 nsecs_t startTime = now();
1199
1200 // For security reasons, we defer updating the touch state until we are sure that
1201 // event injection will be allowed.
1202 //
1203 // FIXME In the original code, screenWasOff could never be set to true.
1204 // The reason is that the POLICY_FLAG_WOKE_HERE
1205 // and POLICY_FLAG_BRIGHT_HERE flags were set only when preprocessing raw
1206 // EV_KEY, EV_REL and EV_ABS events. As it happens, the touch event was
1207 // actually enqueued using the policyFlags that appeared in the final EV_SYN
1208 // events upon which no preprocessing took place. So policyFlags was always 0.
1209 // In the new native input dispatcher we're a bit more careful about event
1210 // preprocessing so the touches we receive can actually have non-zero policyFlags.
1211 // Unfortunately we obtain undesirable behavior.
1212 //
1213 // Here's what happens:
1214 //
1215 // When the device dims in anticipation of going to sleep, touches
1216 // in windows which have FLAG_TOUCHABLE_WHEN_WAKING cause
1217 // the device to brighten and reset the user activity timer.
1218 // Touches on other windows (such as the launcher window)
1219 // are dropped. Then after a moment, the device goes to sleep. Oops.
1220 //
1221 // Also notice how screenWasOff was being initialized using POLICY_FLAG_BRIGHT_HERE
1222 // instead of POLICY_FLAG_WOKE_HERE...
1223 //
1224 bool screenWasOff = false; // original policy: policyFlags & POLICY_FLAG_BRIGHT_HERE;
1225
1226 int32_t action = entry->action;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001227 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Jeff Brownb88102f2010-09-08 11:49:43 -07001228
1229 // Update the touch state as needed based on the properties of the touch event.
Jeff Brown01ce2e92010-09-26 22:20:12 -07001230 int32_t injectionResult = INPUT_EVENT_INJECTION_PENDING;
1231 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
Jeff Browna032cc02011-03-07 16:56:21 -08001232 const InputWindow* newHoverWindow = NULL;
Jeff Browncc0c1592011-02-19 05:07:28 -08001233
1234 bool isSplit = mTouchState.split;
1235 bool wrongDevice = mTouchState.down
1236 && (mTouchState.deviceId != entry->deviceId
1237 || mTouchState.source != entry->source);
Jeff Browna032cc02011-03-07 16:56:21 -08001238 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE
1239 || maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER
1240 || maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1241 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN
1242 || maskedAction == AMOTION_EVENT_ACTION_SCROLL
1243 || isHoverAction);
1244 if (newGesture) {
Jeff Browncc0c1592011-02-19 05:07:28 -08001245 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
1246 if (wrongDevice && !down) {
1247 mTempTouchState.copyFrom(mTouchState);
1248 } else {
1249 mTempTouchState.reset();
1250 mTempTouchState.down = down;
1251 mTempTouchState.deviceId = entry->deviceId;
1252 mTempTouchState.source = entry->source;
1253 isSplit = false;
1254 wrongDevice = false;
1255 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001256 } else {
1257 mTempTouchState.copyFrom(mTouchState);
Jeff Browncc0c1592011-02-19 05:07:28 -08001258 }
1259 if (wrongDevice) {
Jeff Browna2cc28d2011-03-25 11:58:46 -07001260#if DEBUG_FOCUS
Jeff Browncc0c1592011-02-19 05:07:28 -08001261 LOGD("Dropping event because a pointer for a different device is already down.");
Jeff Brown95712852011-01-04 19:41:59 -08001262#endif
Jeff Browncc0c1592011-02-19 05:07:28 -08001263 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1264 goto Failed;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001265 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001266
Jeff Browna032cc02011-03-07 16:56:21 -08001267 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
Jeff Brown33bbfd22011-02-24 20:55:35 -08001268 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
Jeff Brownb88102f2010-09-08 11:49:43 -07001269
Jeff Browna032cc02011-03-07 16:56:21 -08001270 const MotionSample* sample = &entry->firstSample;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001271 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Jeff Browna032cc02011-03-07 16:56:21 -08001272 int32_t x = int32_t(sample->pointerCoords[pointerIndex].
Jeff Brownebbd5d12011-02-17 13:01:34 -08001273 getAxisValue(AMOTION_EVENT_AXIS_X));
Jeff Browna032cc02011-03-07 16:56:21 -08001274 int32_t y = int32_t(sample->pointerCoords[pointerIndex].
Jeff Brownebbd5d12011-02-17 13:01:34 -08001275 getAxisValue(AMOTION_EVENT_AXIS_Y));
Jeff Brown01ce2e92010-09-26 22:20:12 -07001276 const InputWindow* newTouchedWindow = NULL;
1277 const InputWindow* topErrorWindow = NULL;
Jeff Browna032cc02011-03-07 16:56:21 -08001278 bool isTouchModal = false;
Jeff Brownb88102f2010-09-08 11:49:43 -07001279
1280 // Traverse windows from front to back to find touched window and outside targets.
1281 size_t numWindows = mWindows.size();
1282 for (size_t i = 0; i < numWindows; i++) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001283 const InputWindow* window = & mWindows.editItemAt(i);
Jeff Brownb88102f2010-09-08 11:49:43 -07001284 int32_t flags = window->layoutParamsFlags;
1285
1286 if (flags & InputWindow::FLAG_SYSTEM_ERROR) {
1287 if (! topErrorWindow) {
1288 topErrorWindow = window;
1289 }
1290 }
1291
1292 if (window->visible) {
1293 if (! (flags & InputWindow::FLAG_NOT_TOUCHABLE)) {
Jeff Browna032cc02011-03-07 16:56:21 -08001294 isTouchModal = (flags & (InputWindow::FLAG_NOT_FOCUSABLE
Jeff Brownb88102f2010-09-08 11:49:43 -07001295 | InputWindow::FLAG_NOT_TOUCH_MODAL)) == 0;
Jeff Brownfbf09772011-01-16 14:06:57 -08001296 if (isTouchModal || window->touchableRegionContainsPoint(x, y)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001297 if (! screenWasOff || flags & InputWindow::FLAG_TOUCHABLE_WHEN_WAKING) {
1298 newTouchedWindow = window;
Jeff Brownb88102f2010-09-08 11:49:43 -07001299 }
1300 break; // found touched window, exit window loop
1301 }
1302 }
1303
Jeff Brown01ce2e92010-09-26 22:20:12 -07001304 if (maskedAction == AMOTION_EVENT_ACTION_DOWN
1305 && (flags & InputWindow::FLAG_WATCH_OUTSIDE_TOUCH)) {
Jeff Browna032cc02011-03-07 16:56:21 -08001306 int32_t outsideTargetFlags = InputTarget::FLAG_DISPATCH_AS_OUTSIDE;
Jeff Brown19dfc832010-10-05 12:26:23 -07001307 if (isWindowObscuredAtPointLocked(window, x, y)) {
1308 outsideTargetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1309 }
1310
1311 mTempTouchState.addOrUpdateWindow(window, outsideTargetFlags, BitSet32(0));
Jeff Brownb88102f2010-09-08 11:49:43 -07001312 }
1313 }
1314 }
1315
1316 // If there is an error window but it is not taking focus (typically because
1317 // it is invisible) then wait for it. Any other focused window may in
1318 // fact be in ANR state.
1319 if (topErrorWindow && newTouchedWindow != topErrorWindow) {
1320#if DEBUG_FOCUS
1321 LOGD("Waiting because system error window is pending.");
1322#endif
1323 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
1324 NULL, NULL, nextWakeupTime);
1325 injectionPermission = INJECTION_PERMISSION_UNKNOWN;
1326 goto Unresponsive;
1327 }
1328
Jeff Brown01ce2e92010-09-26 22:20:12 -07001329 // Figure out whether splitting will be allowed for this window.
Jeff Brown46e75292010-11-10 16:53:45 -08001330 if (newTouchedWindow && newTouchedWindow->supportsSplitTouch()) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001331 // New window supports splitting.
1332 isSplit = true;
1333 } else if (isSplit) {
1334 // New window does not support splitting but we have already split events.
1335 // Assign the pointer to the first foreground window we find.
1336 // (May be NULL which is why we put this code block before the next check.)
1337 newTouchedWindow = mTempTouchState.getFirstForegroundWindow();
1338 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001339
Jeff Brownb88102f2010-09-08 11:49:43 -07001340 // If we did not find a touched window then fail.
1341 if (! newTouchedWindow) {
1342 if (mFocusedApplication) {
1343#if DEBUG_FOCUS
1344 LOGD("Waiting because there is no touched window but there is a "
Jeff Brown519e0242010-09-15 15:18:56 -07001345 "focused application that may eventually add a new window: %s.",
1346 getApplicationWindowLabelLocked(mFocusedApplication, NULL).string());
Jeff Brownb88102f2010-09-08 11:49:43 -07001347#endif
1348 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
1349 mFocusedApplication, NULL, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -07001350 goto Unresponsive;
1351 }
1352
1353 LOGI("Dropping event because there is no touched window or focused application.");
1354 injectionResult = INPUT_EVENT_INJECTION_FAILED;
Jeff Brownb88102f2010-09-08 11:49:43 -07001355 goto Failed;
1356 }
1357
Jeff Brown19dfc832010-10-05 12:26:23 -07001358 // Set target flags.
Jeff Browna032cc02011-03-07 16:56:21 -08001359 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
Jeff Brown19dfc832010-10-05 12:26:23 -07001360 if (isSplit) {
1361 targetFlags |= InputTarget::FLAG_SPLIT;
1362 }
1363 if (isWindowObscuredAtPointLocked(newTouchedWindow, x, y)) {
1364 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1365 }
1366
Jeff Browna032cc02011-03-07 16:56:21 -08001367 // Update hover state.
1368 if (isHoverAction) {
1369 newHoverWindow = newTouchedWindow;
1370
1371 // Ensure all subsequent motion samples are also within the touched window.
1372 // Set *outSplitBatchAfterSample to the sample before the first one that is not
1373 // within the touched window.
1374 if (!isTouchModal) {
1375 while (sample->next) {
1376 if (!newHoverWindow->touchableRegionContainsPoint(
1377 sample->next->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X),
1378 sample->next->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y))) {
1379 *outSplitBatchAfterSample = sample;
1380 break;
1381 }
1382 sample = sample->next;
1383 }
1384 }
1385 } else if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
1386 newHoverWindow = mLastHoverWindow;
1387 }
1388
Jeff Brown01ce2e92010-09-26 22:20:12 -07001389 // Update the temporary touch state.
1390 BitSet32 pointerIds;
1391 if (isSplit) {
1392 uint32_t pointerId = entry->pointerIds[pointerIndex];
1393 pointerIds.markBit(pointerId);
Jeff Brownb88102f2010-09-08 11:49:43 -07001394 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001395 mTempTouchState.addOrUpdateWindow(newTouchedWindow, targetFlags, pointerIds);
Jeff Brownb88102f2010-09-08 11:49:43 -07001396 } else {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001397 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
Jeff Brownb88102f2010-09-08 11:49:43 -07001398
1399 // If the pointer is not currently down, then ignore the event.
Jeff Brown01ce2e92010-09-26 22:20:12 -07001400 if (! mTempTouchState.down) {
Jeff Browna2cc28d2011-03-25 11:58:46 -07001401#if DEBUG_FOCUS
Jeff Brown76860e32010-10-25 17:37:46 -07001402 LOGD("Dropping event because the pointer is not down or we previously "
1403 "dropped the pointer down event.");
1404#endif
Jeff Brownb88102f2010-09-08 11:49:43 -07001405 injectionResult = INPUT_EVENT_INJECTION_FAILED;
Jeff Brownb88102f2010-09-08 11:49:43 -07001406 goto Failed;
1407 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001408 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001409
Jeff Browna032cc02011-03-07 16:56:21 -08001410 if (newHoverWindow != mLastHoverWindow) {
1411 // Split the batch here so we send exactly one sample as part of ENTER or EXIT.
1412 *outSplitBatchAfterSample = &entry->firstSample;
1413
1414 // Let the previous window know that the hover sequence is over.
1415 if (mLastHoverWindow) {
1416#if DEBUG_HOVER
1417 LOGD("Sending hover exit event to window %s.", mLastHoverWindow->name.string());
1418#endif
1419 mTempTouchState.addOrUpdateWindow(mLastHoverWindow,
1420 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
1421 }
1422
1423 // Let the new window know that the hover sequence is starting.
1424 if (newHoverWindow) {
1425#if DEBUG_HOVER
1426 LOGD("Sending hover enter event to window %s.", newHoverWindow->name.string());
1427#endif
1428 mTempTouchState.addOrUpdateWindow(newHoverWindow,
1429 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER, BitSet32(0));
1430 }
1431 }
1432
Jeff Brown01ce2e92010-09-26 22:20:12 -07001433 // Check permission to inject into all touched foreground windows and ensure there
1434 // is at least one touched foreground window.
1435 {
1436 bool haveForegroundWindow = false;
1437 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1438 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1439 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1440 haveForegroundWindow = true;
1441 if (! checkInjectionPermission(touchedWindow.window, entry->injectionState)) {
1442 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1443 injectionPermission = INJECTION_PERMISSION_DENIED;
1444 goto Failed;
1445 }
1446 }
1447 }
1448 if (! haveForegroundWindow) {
Jeff Browna2cc28d2011-03-25 11:58:46 -07001449#if DEBUG_FOCUS
Jeff Brown01ce2e92010-09-26 22:20:12 -07001450 LOGD("Dropping event because there is no touched foreground window to receive it.");
Jeff Brownb88102f2010-09-08 11:49:43 -07001451#endif
1452 injectionResult = INPUT_EVENT_INJECTION_FAILED;
Jeff Brownb88102f2010-09-08 11:49:43 -07001453 goto Failed;
1454 }
1455
Jeff Brown01ce2e92010-09-26 22:20:12 -07001456 // Permission granted to injection into all touched foreground windows.
1457 injectionPermission = INJECTION_PERMISSION_GRANTED;
1458 }
Jeff Brown519e0242010-09-15 15:18:56 -07001459
Jeff Brown01ce2e92010-09-26 22:20:12 -07001460 // Ensure all touched foreground windows are ready for new input.
1461 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1462 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1463 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1464 // If the touched window is paused then keep waiting.
1465 if (touchedWindow.window->paused) {
Jeff Browna2cc28d2011-03-25 11:58:46 -07001466#if DEBUG_FOCUS
Jeff Brown01ce2e92010-09-26 22:20:12 -07001467 LOGD("Waiting because touched window is paused.");
Jeff Brown519e0242010-09-15 15:18:56 -07001468#endif
Jeff Brown01ce2e92010-09-26 22:20:12 -07001469 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
1470 NULL, touchedWindow.window, nextWakeupTime);
1471 goto Unresponsive;
1472 }
1473
1474 // If the touched window is still working on previous events then keep waiting.
1475 if (! isWindowFinishedWithPreviousInputLocked(touchedWindow.window)) {
1476#if DEBUG_FOCUS
1477 LOGD("Waiting because touched window still processing previous input.");
1478#endif
1479 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
1480 NULL, touchedWindow.window, nextWakeupTime);
1481 goto Unresponsive;
1482 }
1483 }
1484 }
1485
1486 // If this is the first pointer going down and the touched window has a wallpaper
1487 // then also add the touched wallpaper windows so they are locked in for the duration
1488 // of the touch gesture.
Jeff Brown33bbfd22011-02-24 20:55:35 -08001489 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
1490 // engine only supports touch events. We would need to add a mechanism similar
1491 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
1492 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001493 const InputWindow* foregroundWindow = mTempTouchState.getFirstForegroundWindow();
1494 if (foregroundWindow->hasWallpaper) {
1495 for (size_t i = 0; i < mWindows.size(); i++) {
1496 const InputWindow* window = & mWindows[i];
1497 if (window->layoutParamsType == InputWindow::TYPE_WALLPAPER) {
Jeff Brown19dfc832010-10-05 12:26:23 -07001498 mTempTouchState.addOrUpdateWindow(window,
Jeff Browna032cc02011-03-07 16:56:21 -08001499 InputTarget::FLAG_WINDOW_IS_OBSCURED
1500 | InputTarget::FLAG_DISPATCH_AS_IS,
1501 BitSet32(0));
Jeff Brown01ce2e92010-09-26 22:20:12 -07001502 }
1503 }
1504 }
1505 }
1506
Jeff Brownb88102f2010-09-08 11:49:43 -07001507 // Success! Output targets.
1508 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
Jeff Brownb88102f2010-09-08 11:49:43 -07001509
Jeff Brown01ce2e92010-09-26 22:20:12 -07001510 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1511 const TouchedWindow& touchedWindow = mTempTouchState.windows.itemAt(i);
1512 addWindowTargetLocked(touchedWindow.window, touchedWindow.targetFlags,
1513 touchedWindow.pointerIds);
Jeff Brownb88102f2010-09-08 11:49:43 -07001514 }
1515
Jeff Browna032cc02011-03-07 16:56:21 -08001516 // Drop the outside or hover touch windows since we will not care about them
1517 // in the next iteration.
1518 mTempTouchState.filterNonAsIsTouchWindows();
Jeff Brown01ce2e92010-09-26 22:20:12 -07001519
Jeff Brownb88102f2010-09-08 11:49:43 -07001520Failed:
1521 // Check injection permission once and for all.
1522 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001523 if (checkInjectionPermission(NULL, entry->injectionState)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001524 injectionPermission = INJECTION_PERMISSION_GRANTED;
1525 } else {
1526 injectionPermission = INJECTION_PERMISSION_DENIED;
1527 }
1528 }
1529
1530 // Update final pieces of touch state if the injector had permission.
1531 if (injectionPermission == INJECTION_PERMISSION_GRANTED) {
Jeff Brown95712852011-01-04 19:41:59 -08001532 if (!wrongDevice) {
1533 if (maskedAction == AMOTION_EVENT_ACTION_UP
Jeff Browncc0c1592011-02-19 05:07:28 -08001534 || maskedAction == AMOTION_EVENT_ACTION_CANCEL
Jeff Browna032cc02011-03-07 16:56:21 -08001535 || isHoverAction) {
Jeff Brown95712852011-01-04 19:41:59 -08001536 // All pointers up or canceled.
Jeff Brown33bbfd22011-02-24 20:55:35 -08001537 mTouchState.reset();
Jeff Brown95712852011-01-04 19:41:59 -08001538 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1539 // First pointer went down.
1540 if (mTouchState.down) {
Jeff Browncc0c1592011-02-19 05:07:28 -08001541 *outConflictingPointerActions = true;
Jeff Brownb6997262010-10-08 22:31:17 -07001542#if DEBUG_FOCUS
Jeff Brown95712852011-01-04 19:41:59 -08001543 LOGD("Pointer down received while already down.");
Jeff Brownb6997262010-10-08 22:31:17 -07001544#endif
Jeff Brown95712852011-01-04 19:41:59 -08001545 }
Jeff Brown33bbfd22011-02-24 20:55:35 -08001546 mTouchState.copyFrom(mTempTouchState);
Jeff Brown95712852011-01-04 19:41:59 -08001547 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
1548 // One pointer went up.
1549 if (isSplit) {
1550 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
1551 uint32_t pointerId = entry->pointerIds[pointerIndex];
Jeff Brownb88102f2010-09-08 11:49:43 -07001552
Jeff Brown95712852011-01-04 19:41:59 -08001553 for (size_t i = 0; i < mTempTouchState.windows.size(); ) {
1554 TouchedWindow& touchedWindow = mTempTouchState.windows.editItemAt(i);
1555 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
1556 touchedWindow.pointerIds.clearBit(pointerId);
1557 if (touchedWindow.pointerIds.isEmpty()) {
1558 mTempTouchState.windows.removeAt(i);
1559 continue;
1560 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001561 }
Jeff Brown95712852011-01-04 19:41:59 -08001562 i += 1;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001563 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001564 }
Jeff Brown33bbfd22011-02-24 20:55:35 -08001565 mTouchState.copyFrom(mTempTouchState);
1566 } else if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
1567 // Discard temporary touch state since it was only valid for this action.
1568 } else {
1569 // Save changes to touch state as-is for all other actions.
1570 mTouchState.copyFrom(mTempTouchState);
Jeff Brownb88102f2010-09-08 11:49:43 -07001571 }
Jeff Browna032cc02011-03-07 16:56:21 -08001572
1573 // Update hover state.
1574 mLastHoverWindow = newHoverWindow;
Jeff Brown95712852011-01-04 19:41:59 -08001575 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001576 } else {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001577#if DEBUG_FOCUS
1578 LOGD("Not updating touch focus because injection was denied.");
1579#endif
Jeff Brownb88102f2010-09-08 11:49:43 -07001580 }
1581
1582Unresponsive:
Jeff Brown120a4592010-10-27 18:43:51 -07001583 // Reset temporary touch state to ensure we release unnecessary references to input channels.
1584 mTempTouchState.reset();
1585
Jeff Brown519e0242010-09-15 15:18:56 -07001586 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
1587 updateDispatchStatisticsLocked(currentTime, entry,
1588 injectionResult, timeSpentWaitingForApplication);
Jeff Brownb88102f2010-09-08 11:49:43 -07001589#if DEBUG_FOCUS
Jeff Brown01ce2e92010-09-26 22:20:12 -07001590 LOGD("findTouchedWindow finished: injectionResult=%d, injectionPermission=%d, "
1591 "timeSpentWaitingForApplication=%0.1fms",
Jeff Brown519e0242010-09-15 15:18:56 -07001592 injectionResult, injectionPermission, timeSpentWaitingForApplication / 1000000.0);
Jeff Brownb88102f2010-09-08 11:49:43 -07001593#endif
1594 return injectionResult;
1595}
1596
Jeff Brown01ce2e92010-09-26 22:20:12 -07001597void InputDispatcher::addWindowTargetLocked(const InputWindow* window, int32_t targetFlags,
1598 BitSet32 pointerIds) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001599 mCurrentInputTargets.push();
1600
1601 InputTarget& target = mCurrentInputTargets.editTop();
1602 target.inputChannel = window->inputChannel;
1603 target.flags = targetFlags;
Jeff Brownb88102f2010-09-08 11:49:43 -07001604 target.xOffset = - window->frameLeft;
1605 target.yOffset = - window->frameTop;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001606 target.pointerIds = pointerIds;
Jeff Brownb88102f2010-09-08 11:49:43 -07001607}
1608
1609void InputDispatcher::addMonitoringTargetsLocked() {
1610 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
1611 mCurrentInputTargets.push();
1612
1613 InputTarget& target = mCurrentInputTargets.editTop();
1614 target.inputChannel = mMonitoringChannels[i];
Jeff Brownb6110c22011-04-01 16:15:13 -07001615 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
Jeff Brownb88102f2010-09-08 11:49:43 -07001616 target.xOffset = 0;
1617 target.yOffset = 0;
Jeff Brownb6110c22011-04-01 16:15:13 -07001618 target.pointerIds.clear();
Jeff Brownb88102f2010-09-08 11:49:43 -07001619 }
1620}
1621
1622bool InputDispatcher::checkInjectionPermission(const InputWindow* window,
Jeff Brown01ce2e92010-09-26 22:20:12 -07001623 const InjectionState* injectionState) {
1624 if (injectionState
Jeff Brownb6997262010-10-08 22:31:17 -07001625 && (window == NULL || window->ownerUid != injectionState->injectorUid)
1626 && !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
1627 if (window) {
1628 LOGW("Permission denied: injecting event from pid %d uid %d to window "
1629 "with input channel %s owned by uid %d",
1630 injectionState->injectorPid, injectionState->injectorUid,
1631 window->inputChannel->getName().string(),
1632 window->ownerUid);
1633 } else {
1634 LOGW("Permission denied: injecting event from pid %d uid %d",
1635 injectionState->injectorPid, injectionState->injectorUid);
Jeff Brownb88102f2010-09-08 11:49:43 -07001636 }
Jeff Brownb6997262010-10-08 22:31:17 -07001637 return false;
Jeff Brownb88102f2010-09-08 11:49:43 -07001638 }
1639 return true;
1640}
1641
Jeff Brown19dfc832010-10-05 12:26:23 -07001642bool InputDispatcher::isWindowObscuredAtPointLocked(
1643 const InputWindow* window, int32_t x, int32_t y) const {
Jeff Brownb88102f2010-09-08 11:49:43 -07001644 size_t numWindows = mWindows.size();
1645 for (size_t i = 0; i < numWindows; i++) {
1646 const InputWindow* other = & mWindows.itemAt(i);
1647 if (other == window) {
1648 break;
1649 }
Jeff Brown19dfc832010-10-05 12:26:23 -07001650 if (other->visible && ! other->isTrustedOverlay() && other->frameContainsPoint(x, y)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001651 return true;
1652 }
1653 }
1654 return false;
1655}
1656
Jeff Brown519e0242010-09-15 15:18:56 -07001657bool InputDispatcher::isWindowFinishedWithPreviousInputLocked(const InputWindow* window) {
1658 ssize_t connectionIndex = getConnectionIndexLocked(window->inputChannel);
1659 if (connectionIndex >= 0) {
1660 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
1661 return connection->outboundQueue.isEmpty();
1662 } else {
1663 return true;
1664 }
1665}
1666
1667String8 InputDispatcher::getApplicationWindowLabelLocked(const InputApplication* application,
1668 const InputWindow* window) {
1669 if (application) {
1670 if (window) {
1671 String8 label(application->name);
1672 label.append(" - ");
1673 label.append(window->name);
1674 return label;
1675 } else {
1676 return application->name;
1677 }
1678 } else if (window) {
1679 return window->name;
1680 } else {
1681 return String8("<unknown application or window>");
1682 }
1683}
1684
Jeff Browne2fe69e2010-10-18 13:21:23 -07001685void InputDispatcher::pokeUserActivityLocked(const EventEntry* eventEntry) {
Jeff Brown56194eb2011-03-02 19:23:13 -08001686 int32_t eventType = POWER_MANAGER_OTHER_EVENT;
Jeff Brown4d396052010-10-29 21:50:21 -07001687 switch (eventEntry->type) {
1688 case EventEntry::TYPE_MOTION: {
Jeff Browne2fe69e2010-10-18 13:21:23 -07001689 const MotionEntry* motionEntry = static_cast<const MotionEntry*>(eventEntry);
Jeff Brown4d396052010-10-29 21:50:21 -07001690 if (motionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
1691 return;
1692 }
1693
Jeff Brown56194eb2011-03-02 19:23:13 -08001694 if (MotionEvent::isTouchEvent(motionEntry->source, motionEntry->action)) {
Joe Onorato1a542c72010-11-08 09:48:20 -08001695 eventType = POWER_MANAGER_TOUCH_EVENT;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001696 }
Jeff Brown4d396052010-10-29 21:50:21 -07001697 break;
1698 }
1699 case EventEntry::TYPE_KEY: {
1700 const KeyEntry* keyEntry = static_cast<const KeyEntry*>(eventEntry);
1701 if (keyEntry->flags & AKEY_EVENT_FLAG_CANCELED) {
1702 return;
1703 }
Jeff Brown56194eb2011-03-02 19:23:13 -08001704 eventType = POWER_MANAGER_BUTTON_EVENT;
Jeff Brown4d396052010-10-29 21:50:21 -07001705 break;
1706 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001707 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001708
Jeff Brownb88102f2010-09-08 11:49:43 -07001709 CommandEntry* commandEntry = postCommandLocked(
1710 & InputDispatcher::doPokeUserActivityLockedInterruptible);
Jeff Browne2fe69e2010-10-18 13:21:23 -07001711 commandEntry->eventTime = eventEntry->eventTime;
Jeff Brownb88102f2010-09-08 11:49:43 -07001712 commandEntry->userActivityEventType = eventType;
1713}
1714
Jeff Brown7fbdc842010-06-17 20:52:56 -07001715void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
1716 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget,
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001717 bool resumeWithAppendedMotionSample) {
1718#if DEBUG_DISPATCH_CYCLE
Jeff Brown519e0242010-09-15 15:18:56 -07001719 LOGD("channel '%s' ~ prepareDispatchCycle - flags=%d, "
Jeff Brown01ce2e92010-09-26 22:20:12 -07001720 "xOffset=%f, yOffset=%f, "
Jeff Brown83c09682010-12-23 17:50:18 -08001721 "pointerIds=0x%x, "
Jeff Brown01ce2e92010-09-26 22:20:12 -07001722 "resumeWithAppendedMotionSample=%s",
Jeff Brown519e0242010-09-15 15:18:56 -07001723 connection->getInputChannelName(), inputTarget->flags,
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001724 inputTarget->xOffset, inputTarget->yOffset,
Jeff Brown83c09682010-12-23 17:50:18 -08001725 inputTarget->pointerIds.value,
Jeff Brownb88102f2010-09-08 11:49:43 -07001726 toString(resumeWithAppendedMotionSample));
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001727#endif
1728
Jeff Brown01ce2e92010-09-26 22:20:12 -07001729 // Make sure we are never called for streaming when splitting across multiple windows.
1730 bool isSplit = inputTarget->flags & InputTarget::FLAG_SPLIT;
Jeff Brownb6110c22011-04-01 16:15:13 -07001731 LOG_ASSERT(! (resumeWithAppendedMotionSample && isSplit));
Jeff Brown01ce2e92010-09-26 22:20:12 -07001732
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001733 // Skip this event if the connection status is not normal.
Jeff Brown519e0242010-09-15 15:18:56 -07001734 // We don't want to enqueue additional outbound events if the connection is broken.
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001735 if (connection->status != Connection::STATUS_NORMAL) {
Jeff Brownb6997262010-10-08 22:31:17 -07001736#if DEBUG_DISPATCH_CYCLE
1737 LOGD("channel '%s' ~ Dropping event because the channel status is %s",
Jeff Brownb88102f2010-09-08 11:49:43 -07001738 connection->getInputChannelName(), connection->getStatusLabel());
Jeff Brownb6997262010-10-08 22:31:17 -07001739#endif
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001740 return;
1741 }
1742
Jeff Brown01ce2e92010-09-26 22:20:12 -07001743 // Split a motion event if needed.
1744 if (isSplit) {
Jeff Brownb6110c22011-04-01 16:15:13 -07001745 LOG_ASSERT(eventEntry->type == EventEntry::TYPE_MOTION);
Jeff Brown01ce2e92010-09-26 22:20:12 -07001746
1747 MotionEntry* originalMotionEntry = static_cast<MotionEntry*>(eventEntry);
1748 if (inputTarget->pointerIds.count() != originalMotionEntry->pointerCount) {
1749 MotionEntry* splitMotionEntry = splitMotionEvent(
1750 originalMotionEntry, inputTarget->pointerIds);
Jeff Brown58a2da82011-01-25 16:02:22 -08001751 if (!splitMotionEntry) {
1752 return; // split event was dropped
1753 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001754#if DEBUG_FOCUS
1755 LOGD("channel '%s' ~ Split motion event.",
1756 connection->getInputChannelName());
1757 logOutboundMotionDetailsLocked(" ", splitMotionEntry);
1758#endif
1759 eventEntry = splitMotionEntry;
1760 }
1761 }
1762
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001763 // Resume the dispatch cycle with a freshly appended motion sample.
1764 // First we check that the last dispatch entry in the outbound queue is for the same
1765 // motion event to which we appended the motion sample. If we find such a dispatch
1766 // entry, and if it is currently in progress then we try to stream the new sample.
1767 bool wasEmpty = connection->outboundQueue.isEmpty();
1768
1769 if (! wasEmpty && resumeWithAppendedMotionSample) {
1770 DispatchEntry* motionEventDispatchEntry =
1771 connection->findQueuedDispatchEntryForEvent(eventEntry);
1772 if (motionEventDispatchEntry) {
1773 // If the dispatch entry is not in progress, then we must be busy dispatching an
1774 // earlier event. Not a problem, the motion event is on the outbound queue and will
1775 // be dispatched later.
1776 if (! motionEventDispatchEntry->inProgress) {
1777#if DEBUG_BATCHING
1778 LOGD("channel '%s' ~ Not streaming because the motion event has "
1779 "not yet been dispatched. "
1780 "(Waiting for earlier events to be consumed.)",
1781 connection->getInputChannelName());
1782#endif
1783 return;
1784 }
1785
1786 // If the dispatch entry is in progress but it already has a tail of pending
1787 // motion samples, then it must mean that the shared memory buffer filled up.
1788 // Not a problem, when this dispatch cycle is finished, we will eventually start
1789 // a new dispatch cycle to process the tail and that tail includes the newly
1790 // appended motion sample.
1791 if (motionEventDispatchEntry->tailMotionSample) {
1792#if DEBUG_BATCHING
1793 LOGD("channel '%s' ~ Not streaming because no new samples can "
1794 "be appended to the motion event in this dispatch cycle. "
1795 "(Waiting for next dispatch cycle to start.)",
1796 connection->getInputChannelName());
1797#endif
1798 return;
1799 }
1800
1801 // The dispatch entry is in progress and is still potentially open for streaming.
1802 // Try to stream the new motion sample. This might fail if the consumer has already
1803 // consumed the motion event (or if the channel is broken).
Jeff Brown01ce2e92010-09-26 22:20:12 -07001804 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
1805 MotionSample* appendedMotionSample = motionEntry->lastSample;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001806 status_t status = connection->inputPublisher.appendMotionSample(
1807 appendedMotionSample->eventTime, appendedMotionSample->pointerCoords);
1808 if (status == OK) {
1809#if DEBUG_BATCHING
1810 LOGD("channel '%s' ~ Successfully streamed new motion sample.",
1811 connection->getInputChannelName());
1812#endif
1813 return;
1814 }
1815
1816#if DEBUG_BATCHING
1817 if (status == NO_MEMORY) {
1818 LOGD("channel '%s' ~ Could not append motion sample to currently "
1819 "dispatched move event because the shared memory buffer is full. "
1820 "(Waiting for next dispatch cycle to start.)",
1821 connection->getInputChannelName());
1822 } else if (status == status_t(FAILED_TRANSACTION)) {
1823 LOGD("channel '%s' ~ Could not append motion sample to currently "
Jeff Brown349703e2010-06-22 01:27:15 -07001824 "dispatched move event because the event has already been consumed. "
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001825 "(Waiting for next dispatch cycle to start.)",
1826 connection->getInputChannelName());
1827 } else {
1828 LOGD("channel '%s' ~ Could not append motion sample to currently "
1829 "dispatched move event due to an error, status=%d. "
1830 "(Waiting for next dispatch cycle to start.)",
1831 connection->getInputChannelName(), status);
1832 }
1833#endif
1834 // Failed to stream. Start a new tail of pending motion samples to dispatch
1835 // in the next cycle.
1836 motionEventDispatchEntry->tailMotionSample = appendedMotionSample;
1837 return;
1838 }
1839 }
1840
Jeff Browna032cc02011-03-07 16:56:21 -08001841 // Enqueue dispatch entries for the requested modes.
1842 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1843 resumeWithAppendedMotionSample, InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
1844 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1845 resumeWithAppendedMotionSample, InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
1846 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1847 resumeWithAppendedMotionSample, InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
1848 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1849 resumeWithAppendedMotionSample, InputTarget::FLAG_DISPATCH_AS_IS);
1850
1851 // If the outbound queue was previously empty, start the dispatch cycle going.
Jeff Brownb6110c22011-04-01 16:15:13 -07001852 if (wasEmpty && !connection->outboundQueue.isEmpty()) {
Jeff Browna032cc02011-03-07 16:56:21 -08001853 activateConnectionLocked(connection.get());
1854 startDispatchCycleLocked(currentTime, connection);
1855 }
1856}
1857
1858void InputDispatcher::enqueueDispatchEntryLocked(
1859 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget,
1860 bool resumeWithAppendedMotionSample, int32_t dispatchMode) {
1861 int32_t inputTargetFlags = inputTarget->flags;
1862 if (!(inputTargetFlags & dispatchMode)) {
1863 return;
1864 }
1865 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
1866
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001867 // This is a new event.
1868 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Jeff Brownb88102f2010-09-08 11:49:43 -07001869 DispatchEntry* dispatchEntry = mAllocator.obtainDispatchEntry(eventEntry, // increments ref
Jeff Browna032cc02011-03-07 16:56:21 -08001870 inputTargetFlags, inputTarget->xOffset, inputTarget->yOffset);
Jeff Brown519e0242010-09-15 15:18:56 -07001871 if (dispatchEntry->hasForegroundTarget()) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001872 incrementPendingForegroundDispatchesLocked(eventEntry);
Jeff Brown6ec402b2010-07-28 15:48:59 -07001873 }
1874
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001875 // Handle the case where we could not stream a new motion sample because the consumer has
1876 // already consumed the motion event (otherwise the corresponding dispatch entry would
1877 // still be in the outbound queue for this connection). We set the head motion sample
1878 // to the list starting with the newly appended motion sample.
1879 if (resumeWithAppendedMotionSample) {
1880#if DEBUG_BATCHING
1881 LOGD("channel '%s' ~ Preparing a new dispatch cycle for additional motion samples "
1882 "that cannot be streamed because the motion event has already been consumed.",
1883 connection->getInputChannelName());
1884#endif
1885 MotionSample* appendedMotionSample = static_cast<MotionEntry*>(eventEntry)->lastSample;
1886 dispatchEntry->headMotionSample = appendedMotionSample;
1887 }
1888
1889 // Enqueue the dispatch entry.
1890 connection->outboundQueue.enqueueAtTail(dispatchEntry);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001891}
1892
Jeff Brown7fbdc842010-06-17 20:52:56 -07001893void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Jeff Brown519e0242010-09-15 15:18:56 -07001894 const sp<Connection>& connection) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001895#if DEBUG_DISPATCH_CYCLE
1896 LOGD("channel '%s' ~ startDispatchCycle",
1897 connection->getInputChannelName());
1898#endif
1899
Jeff Brownb6110c22011-04-01 16:15:13 -07001900 LOG_ASSERT(connection->status == Connection::STATUS_NORMAL);
1901 LOG_ASSERT(! connection->outboundQueue.isEmpty());
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001902
Jeff Brownb88102f2010-09-08 11:49:43 -07001903 DispatchEntry* dispatchEntry = connection->outboundQueue.headSentinel.next;
Jeff Brownb6110c22011-04-01 16:15:13 -07001904 LOG_ASSERT(! dispatchEntry->inProgress);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001905
Jeff Brownb88102f2010-09-08 11:49:43 -07001906 // Mark the dispatch entry as in progress.
1907 dispatchEntry->inProgress = true;
1908
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001909 // Publish the event.
1910 status_t status;
Jeff Browna032cc02011-03-07 16:56:21 -08001911 EventEntry* eventEntry = dispatchEntry->eventEntry;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001912 switch (eventEntry->type) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001913 case EventEntry::TYPE_KEY: {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001914 KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001915
1916 // Apply target flags.
1917 int32_t action = keyEntry->action;
1918 int32_t flags = keyEntry->flags;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001919
Jeff Browna032cc02011-03-07 16:56:21 -08001920 // Update the connection's input state.
1921 connection->inputState.trackKey(keyEntry, action);
1922
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001923 // Publish the key event.
Jeff Brownc5ed5912010-07-14 18:48:53 -07001924 status = connection->inputPublisher.publishKeyEvent(keyEntry->deviceId, keyEntry->source,
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001925 action, flags, keyEntry->keyCode, keyEntry->scanCode,
1926 keyEntry->metaState, keyEntry->repeatCount, keyEntry->downTime,
1927 keyEntry->eventTime);
1928
1929 if (status) {
1930 LOGE("channel '%s' ~ Could not publish key event, "
1931 "status=%d", connection->getInputChannelName(), status);
Jeff Brownb6997262010-10-08 22:31:17 -07001932 abortBrokenDispatchCycleLocked(currentTime, connection);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001933 return;
1934 }
1935 break;
1936 }
1937
1938 case EventEntry::TYPE_MOTION: {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001939 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001940
1941 // Apply target flags.
1942 int32_t action = motionEntry->action;
Jeff Brown85a31762010-09-01 17:01:00 -07001943 int32_t flags = motionEntry->flags;
Jeff Browna032cc02011-03-07 16:56:21 -08001944 if (dispatchEntry->targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001945 action = AMOTION_EVENT_ACTION_OUTSIDE;
Jeff Browna032cc02011-03-07 16:56:21 -08001946 } else if (dispatchEntry->targetFlags & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
1947 action = AMOTION_EVENT_ACTION_HOVER_EXIT;
1948 } else if (dispatchEntry->targetFlags & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
1949 action = AMOTION_EVENT_ACTION_HOVER_ENTER;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001950 }
Jeff Brown85a31762010-09-01 17:01:00 -07001951 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
1952 flags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
1953 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001954
1955 // If headMotionSample is non-NULL, then it points to the first new sample that we
1956 // were unable to dispatch during the previous cycle so we resume dispatching from
1957 // that point in the list of motion samples.
1958 // Otherwise, we just start from the first sample of the motion event.
1959 MotionSample* firstMotionSample = dispatchEntry->headMotionSample;
1960 if (! firstMotionSample) {
1961 firstMotionSample = & motionEntry->firstSample;
1962 }
1963
Jeff Brownd3616592010-07-16 17:21:06 -07001964 // Set the X and Y offset depending on the input source.
1965 float xOffset, yOffset;
1966 if (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) {
1967 xOffset = dispatchEntry->xOffset;
1968 yOffset = dispatchEntry->yOffset;
1969 } else {
1970 xOffset = 0.0f;
1971 yOffset = 0.0f;
1972 }
1973
Jeff Browna032cc02011-03-07 16:56:21 -08001974 // Update the connection's input state.
1975 connection->inputState.trackMotion(motionEntry, action);
1976
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001977 // Publish the motion event and the first motion sample.
1978 status = connection->inputPublisher.publishMotionEvent(motionEntry->deviceId,
Jeff Brown85a31762010-09-01 17:01:00 -07001979 motionEntry->source, action, flags, motionEntry->edgeFlags, motionEntry->metaState,
Jeff Brownd3616592010-07-16 17:21:06 -07001980 xOffset, yOffset,
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001981 motionEntry->xPrecision, motionEntry->yPrecision,
1982 motionEntry->downTime, firstMotionSample->eventTime,
1983 motionEntry->pointerCount, motionEntry->pointerIds,
1984 firstMotionSample->pointerCoords);
1985
1986 if (status) {
1987 LOGE("channel '%s' ~ Could not publish motion event, "
1988 "status=%d", connection->getInputChannelName(), status);
Jeff Brownb6997262010-10-08 22:31:17 -07001989 abortBrokenDispatchCycleLocked(currentTime, connection);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001990 return;
1991 }
1992
Jeff Browna032cc02011-03-07 16:56:21 -08001993 if (action == AMOTION_EVENT_ACTION_MOVE
1994 || action == AMOTION_EVENT_ACTION_HOVER_MOVE) {
1995 // Append additional motion samples.
1996 MotionSample* nextMotionSample = firstMotionSample->next;
1997 for (; nextMotionSample != NULL; nextMotionSample = nextMotionSample->next) {
1998 status = connection->inputPublisher.appendMotionSample(
1999 nextMotionSample->eventTime, nextMotionSample->pointerCoords);
2000 if (status == NO_MEMORY) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002001#if DEBUG_DISPATCH_CYCLE
2002 LOGD("channel '%s' ~ Shared memory buffer full. Some motion samples will "
2003 "be sent in the next dispatch cycle.",
2004 connection->getInputChannelName());
2005#endif
Jeff Browna032cc02011-03-07 16:56:21 -08002006 break;
2007 }
2008 if (status != OK) {
2009 LOGE("channel '%s' ~ Could not append motion sample "
2010 "for a reason other than out of memory, status=%d",
2011 connection->getInputChannelName(), status);
2012 abortBrokenDispatchCycleLocked(currentTime, connection);
2013 return;
2014 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002015 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002016
Jeff Browna032cc02011-03-07 16:56:21 -08002017 // Remember the next motion sample that we could not dispatch, in case we ran out
2018 // of space in the shared memory buffer.
2019 dispatchEntry->tailMotionSample = nextMotionSample;
2020 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002021 break;
2022 }
2023
2024 default: {
Jeff Brownb6110c22011-04-01 16:15:13 -07002025 LOG_ASSERT(false);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002026 }
2027 }
2028
2029 // Send the dispatch signal.
2030 status = connection->inputPublisher.sendDispatchSignal();
2031 if (status) {
2032 LOGE("channel '%s' ~ Could not send dispatch signal, status=%d",
2033 connection->getInputChannelName(), status);
Jeff Brownb6997262010-10-08 22:31:17 -07002034 abortBrokenDispatchCycleLocked(currentTime, connection);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002035 return;
2036 }
2037
2038 // Record information about the newly started dispatch cycle.
Jeff Brown01ce2e92010-09-26 22:20:12 -07002039 connection->lastEventTime = eventEntry->eventTime;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002040 connection->lastDispatchTime = currentTime;
2041
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002042 // Notify other system components.
2043 onDispatchCycleStartedLocked(currentTime, connection);
2044}
2045
Jeff Brown7fbdc842010-06-17 20:52:56 -07002046void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Jeff Brown3915bb82010-11-05 15:02:16 -07002047 const sp<Connection>& connection, bool handled) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002048#if DEBUG_DISPATCH_CYCLE
Jeff Brown9c3cda02010-06-15 01:31:58 -07002049 LOGD("channel '%s' ~ finishDispatchCycle - %01.1fms since event, "
Jeff Brown3915bb82010-11-05 15:02:16 -07002050 "%01.1fms since dispatch, handled=%s",
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002051 connection->getInputChannelName(),
2052 connection->getEventLatencyMillis(currentTime),
Jeff Brown3915bb82010-11-05 15:02:16 -07002053 connection->getDispatchLatencyMillis(currentTime),
2054 toString(handled));
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002055#endif
2056
Jeff Brown9c3cda02010-06-15 01:31:58 -07002057 if (connection->status == Connection::STATUS_BROKEN
2058 || connection->status == Connection::STATUS_ZOMBIE) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002059 return;
2060 }
2061
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002062 // Reset the publisher since the event has been consumed.
2063 // We do this now so that the publisher can release some of its internal resources
2064 // while waiting for the next dispatch cycle to begin.
2065 status_t status = connection->inputPublisher.reset();
2066 if (status) {
2067 LOGE("channel '%s' ~ Could not reset publisher, status=%d",
2068 connection->getInputChannelName(), status);
Jeff Brownb6997262010-10-08 22:31:17 -07002069 abortBrokenDispatchCycleLocked(currentTime, connection);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002070 return;
2071 }
2072
Jeff Brown3915bb82010-11-05 15:02:16 -07002073 // Notify other system components and prepare to start the next dispatch cycle.
2074 onDispatchCycleFinishedLocked(currentTime, connection, handled);
Jeff Brownb88102f2010-09-08 11:49:43 -07002075}
2076
2077void InputDispatcher::startNextDispatchCycleLocked(nsecs_t currentTime,
2078 const sp<Connection>& connection) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002079 // Start the next dispatch cycle for this connection.
2080 while (! connection->outboundQueue.isEmpty()) {
Jeff Brownb88102f2010-09-08 11:49:43 -07002081 DispatchEntry* dispatchEntry = connection->outboundQueue.headSentinel.next;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002082 if (dispatchEntry->inProgress) {
2083 // Finish or resume current event in progress.
2084 if (dispatchEntry->tailMotionSample) {
2085 // We have a tail of undispatched motion samples.
2086 // Reuse the same DispatchEntry and start a new cycle.
2087 dispatchEntry->inProgress = false;
2088 dispatchEntry->headMotionSample = dispatchEntry->tailMotionSample;
2089 dispatchEntry->tailMotionSample = NULL;
Jeff Brown519e0242010-09-15 15:18:56 -07002090 startDispatchCycleLocked(currentTime, connection);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002091 return;
2092 }
2093 // Finished.
2094 connection->outboundQueue.dequeueAtHead();
Jeff Brown519e0242010-09-15 15:18:56 -07002095 if (dispatchEntry->hasForegroundTarget()) {
2096 decrementPendingForegroundDispatchesLocked(dispatchEntry->eventEntry);
Jeff Brown6ec402b2010-07-28 15:48:59 -07002097 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002098 mAllocator.releaseDispatchEntry(dispatchEntry);
2099 } else {
2100 // If the head is not in progress, then we must have already dequeued the in
Jeff Brown519e0242010-09-15 15:18:56 -07002101 // progress event, which means we actually aborted it.
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002102 // So just start the next event for this connection.
Jeff Brown519e0242010-09-15 15:18:56 -07002103 startDispatchCycleLocked(currentTime, connection);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002104 return;
2105 }
2106 }
2107
2108 // Outbound queue is empty, deactivate the connection.
Jeff Brown7fbdc842010-06-17 20:52:56 -07002109 deactivateConnectionLocked(connection.get());
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002110}
2111
Jeff Brownb6997262010-10-08 22:31:17 -07002112void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
2113 const sp<Connection>& connection) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002114#if DEBUG_DISPATCH_CYCLE
Jeff Brown83c09682010-12-23 17:50:18 -08002115 LOGD("channel '%s' ~ abortBrokenDispatchCycle",
2116 connection->getInputChannelName());
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002117#endif
2118
Jeff Brownb88102f2010-09-08 11:49:43 -07002119 // Clear the outbound queue.
Jeff Brown519e0242010-09-15 15:18:56 -07002120 drainOutboundQueueLocked(connection.get());
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002121
Jeff Brownb6997262010-10-08 22:31:17 -07002122 // The connection appears to be unrecoverably broken.
Jeff Brown9c3cda02010-06-15 01:31:58 -07002123 // Ignore already broken or zombie connections.
Jeff Brownb6997262010-10-08 22:31:17 -07002124 if (connection->status == Connection::STATUS_NORMAL) {
2125 connection->status = Connection::STATUS_BROKEN;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002126
Jeff Brownb6997262010-10-08 22:31:17 -07002127 // Notify other system components.
2128 onDispatchCycleBrokenLocked(currentTime, connection);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002129 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002130}
2131
Jeff Brown519e0242010-09-15 15:18:56 -07002132void InputDispatcher::drainOutboundQueueLocked(Connection* connection) {
2133 while (! connection->outboundQueue.isEmpty()) {
2134 DispatchEntry* dispatchEntry = connection->outboundQueue.dequeueAtHead();
2135 if (dispatchEntry->hasForegroundTarget()) {
2136 decrementPendingForegroundDispatchesLocked(dispatchEntry->eventEntry);
Jeff Brownb88102f2010-09-08 11:49:43 -07002137 }
2138 mAllocator.releaseDispatchEntry(dispatchEntry);
Jeff Brownb88102f2010-09-08 11:49:43 -07002139 }
2140
Jeff Brown519e0242010-09-15 15:18:56 -07002141 deactivateConnectionLocked(connection);
Jeff Brownb88102f2010-09-08 11:49:43 -07002142}
2143
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002144int InputDispatcher::handleReceiveCallback(int receiveFd, int events, void* data) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002145 InputDispatcher* d = static_cast<InputDispatcher*>(data);
2146
2147 { // acquire lock
2148 AutoMutex _l(d->mLock);
2149
2150 ssize_t connectionIndex = d->mConnectionsByReceiveFd.indexOfKey(receiveFd);
2151 if (connectionIndex < 0) {
2152 LOGE("Received spurious receive callback for unknown input channel. "
2153 "fd=%d, events=0x%x", receiveFd, events);
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002154 return 0; // remove the callback
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002155 }
2156
Jeff Brown7fbdc842010-06-17 20:52:56 -07002157 nsecs_t currentTime = now();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002158
2159 sp<Connection> connection = d->mConnectionsByReceiveFd.valueAt(connectionIndex);
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002160 if (events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP)) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002161 LOGE("channel '%s' ~ Consumer closed input channel or an error occurred. "
2162 "events=0x%x", connection->getInputChannelName(), events);
Jeff Brownb6997262010-10-08 22:31:17 -07002163 d->abortBrokenDispatchCycleLocked(currentTime, connection);
Jeff Brown9c3cda02010-06-15 01:31:58 -07002164 d->runCommandsLockedInterruptible();
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002165 return 0; // remove the callback
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002166 }
2167
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002168 if (! (events & ALOOPER_EVENT_INPUT)) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002169 LOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
2170 "events=0x%x", connection->getInputChannelName(), events);
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002171 return 1;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002172 }
2173
Jeff Brown3915bb82010-11-05 15:02:16 -07002174 bool handled = false;
Jeff Brown49ed71d2010-12-06 17:13:33 -08002175 status_t status = connection->inputPublisher.receiveFinishedSignal(&handled);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002176 if (status) {
2177 LOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
2178 connection->getInputChannelName(), status);
Jeff Brownb6997262010-10-08 22:31:17 -07002179 d->abortBrokenDispatchCycleLocked(currentTime, connection);
Jeff Brown9c3cda02010-06-15 01:31:58 -07002180 d->runCommandsLockedInterruptible();
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002181 return 0; // remove the callback
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002182 }
2183
Jeff Brown3915bb82010-11-05 15:02:16 -07002184 d->finishDispatchCycleLocked(currentTime, connection, handled);
Jeff Brown9c3cda02010-06-15 01:31:58 -07002185 d->runCommandsLockedInterruptible();
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002186 return 1;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002187 } // release lock
2188}
2189
Jeff Brownb6997262010-10-08 22:31:17 -07002190void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Jeff Brownda3d5a92011-03-29 15:11:34 -07002191 const CancelationOptions& options) {
Jeff Brownb6997262010-10-08 22:31:17 -07002192 for (size_t i = 0; i < mConnectionsByReceiveFd.size(); i++) {
2193 synthesizeCancelationEventsForConnectionLocked(
Jeff Brownda3d5a92011-03-29 15:11:34 -07002194 mConnectionsByReceiveFd.valueAt(i), options);
Jeff Brownb6997262010-10-08 22:31:17 -07002195 }
2196}
2197
2198void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Jeff Brownda3d5a92011-03-29 15:11:34 -07002199 const sp<InputChannel>& channel, const CancelationOptions& options) {
Jeff Brownb6997262010-10-08 22:31:17 -07002200 ssize_t index = getConnectionIndexLocked(channel);
2201 if (index >= 0) {
2202 synthesizeCancelationEventsForConnectionLocked(
Jeff Brownda3d5a92011-03-29 15:11:34 -07002203 mConnectionsByReceiveFd.valueAt(index), options);
Jeff Brownb6997262010-10-08 22:31:17 -07002204 }
2205}
2206
2207void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
Jeff Brownda3d5a92011-03-29 15:11:34 -07002208 const sp<Connection>& connection, const CancelationOptions& options) {
Jeff Brownb6997262010-10-08 22:31:17 -07002209 nsecs_t currentTime = now();
2210
2211 mTempCancelationEvents.clear();
2212 connection->inputState.synthesizeCancelationEvents(currentTime, & mAllocator,
2213 mTempCancelationEvents, options);
2214
2215 if (! mTempCancelationEvents.isEmpty()
2216 && connection->status != Connection::STATUS_BROKEN) {
2217#if DEBUG_OUTBOUND_EVENT_DETAILS
2218 LOGD("channel '%s' ~ Synthesized %d cancelation events to bring channel back in sync "
Jeff Brownda3d5a92011-03-29 15:11:34 -07002219 "with reality: %s, mode=%d.",
2220 connection->getInputChannelName(), mTempCancelationEvents.size(),
2221 options.reason, options.mode);
Jeff Brownb6997262010-10-08 22:31:17 -07002222#endif
2223 for (size_t i = 0; i < mTempCancelationEvents.size(); i++) {
2224 EventEntry* cancelationEventEntry = mTempCancelationEvents.itemAt(i);
2225 switch (cancelationEventEntry->type) {
2226 case EventEntry::TYPE_KEY:
2227 logOutboundKeyDetailsLocked("cancel - ",
2228 static_cast<KeyEntry*>(cancelationEventEntry));
2229 break;
2230 case EventEntry::TYPE_MOTION:
2231 logOutboundMotionDetailsLocked("cancel - ",
2232 static_cast<MotionEntry*>(cancelationEventEntry));
2233 break;
2234 }
2235
2236 int32_t xOffset, yOffset;
2237 const InputWindow* window = getWindowLocked(connection->inputChannel);
2238 if (window) {
2239 xOffset = -window->frameLeft;
2240 yOffset = -window->frameTop;
2241 } else {
2242 xOffset = 0;
2243 yOffset = 0;
2244 }
2245
2246 DispatchEntry* cancelationDispatchEntry =
2247 mAllocator.obtainDispatchEntry(cancelationEventEntry, // increments ref
2248 0, xOffset, yOffset);
2249 connection->outboundQueue.enqueueAtTail(cancelationDispatchEntry);
2250
2251 mAllocator.releaseEventEntry(cancelationEventEntry);
2252 }
2253
2254 if (!connection->outboundQueue.headSentinel.next->inProgress) {
2255 startDispatchCycleLocked(currentTime, connection);
2256 }
2257 }
2258}
2259
Jeff Brown01ce2e92010-09-26 22:20:12 -07002260InputDispatcher::MotionEntry*
2261InputDispatcher::splitMotionEvent(const MotionEntry* originalMotionEntry, BitSet32 pointerIds) {
Jeff Brownb6110c22011-04-01 16:15:13 -07002262 LOG_ASSERT(pointerIds.value != 0);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002263
2264 uint32_t splitPointerIndexMap[MAX_POINTERS];
2265 int32_t splitPointerIds[MAX_POINTERS];
2266 PointerCoords splitPointerCoords[MAX_POINTERS];
2267
2268 uint32_t originalPointerCount = originalMotionEntry->pointerCount;
2269 uint32_t splitPointerCount = 0;
2270
2271 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
2272 originalPointerIndex++) {
2273 int32_t pointerId = uint32_t(originalMotionEntry->pointerIds[originalPointerIndex]);
2274 if (pointerIds.hasBit(pointerId)) {
2275 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
2276 splitPointerIds[splitPointerCount] = pointerId;
Jeff Brownace13b12011-03-09 17:39:48 -08002277 splitPointerCoords[splitPointerCount].copyFrom(
2278 originalMotionEntry->firstSample.pointerCoords[originalPointerIndex]);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002279 splitPointerCount += 1;
2280 }
2281 }
Jeff Brown58a2da82011-01-25 16:02:22 -08002282
2283 if (splitPointerCount != pointerIds.count()) {
2284 // This is bad. We are missing some of the pointers that we expected to deliver.
2285 // Most likely this indicates that we received an ACTION_MOVE events that has
2286 // different pointer ids than we expected based on the previous ACTION_DOWN
2287 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
2288 // in this way.
2289 LOGW("Dropping split motion event because the pointer count is %d but "
2290 "we expected there to be %d pointers. This probably means we received "
2291 "a broken sequence of pointer ids from the input device.",
2292 splitPointerCount, pointerIds.count());
2293 return NULL;
2294 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07002295
2296 int32_t action = originalMotionEntry->action;
2297 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
2298 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
2299 || maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2300 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
2301 int32_t pointerId = originalMotionEntry->pointerIds[originalPointerIndex];
2302 if (pointerIds.hasBit(pointerId)) {
2303 if (pointerIds.count() == 1) {
2304 // The first/last pointer went down/up.
2305 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
2306 ? AMOTION_EVENT_ACTION_DOWN : AMOTION_EVENT_ACTION_UP;
Jeff Brown9a01d052010-09-27 16:35:11 -07002307 } else {
2308 // A secondary pointer went down/up.
2309 uint32_t splitPointerIndex = 0;
2310 while (pointerId != splitPointerIds[splitPointerIndex]) {
2311 splitPointerIndex += 1;
2312 }
2313 action = maskedAction | (splitPointerIndex
2314 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002315 }
2316 } else {
2317 // An unrelated pointer changed.
2318 action = AMOTION_EVENT_ACTION_MOVE;
2319 }
2320 }
2321
2322 MotionEntry* splitMotionEntry = mAllocator.obtainMotionEntry(
2323 originalMotionEntry->eventTime,
2324 originalMotionEntry->deviceId,
2325 originalMotionEntry->source,
2326 originalMotionEntry->policyFlags,
2327 action,
2328 originalMotionEntry->flags,
2329 originalMotionEntry->metaState,
2330 originalMotionEntry->edgeFlags,
2331 originalMotionEntry->xPrecision,
2332 originalMotionEntry->yPrecision,
2333 originalMotionEntry->downTime,
2334 splitPointerCount, splitPointerIds, splitPointerCoords);
2335
2336 for (MotionSample* originalMotionSample = originalMotionEntry->firstSample.next;
2337 originalMotionSample != NULL; originalMotionSample = originalMotionSample->next) {
2338 for (uint32_t splitPointerIndex = 0; splitPointerIndex < splitPointerCount;
2339 splitPointerIndex++) {
2340 uint32_t originalPointerIndex = splitPointerIndexMap[splitPointerIndex];
Jeff Brownace13b12011-03-09 17:39:48 -08002341 splitPointerCoords[splitPointerIndex].copyFrom(
2342 originalMotionSample->pointerCoords[originalPointerIndex]);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002343 }
2344
2345 mAllocator.appendMotionSample(splitMotionEntry, originalMotionSample->eventTime,
2346 splitPointerCoords);
2347 }
2348
Jeff Browna032cc02011-03-07 16:56:21 -08002349 if (originalMotionEntry->injectionState) {
2350 splitMotionEntry->injectionState = originalMotionEntry->injectionState;
2351 splitMotionEntry->injectionState->refCount += 1;
2352 }
2353
Jeff Brown01ce2e92010-09-26 22:20:12 -07002354 return splitMotionEntry;
2355}
2356
Jeff Brown9c3cda02010-06-15 01:31:58 -07002357void InputDispatcher::notifyConfigurationChanged(nsecs_t eventTime) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002358#if DEBUG_INBOUND_EVENT_DETAILS
Jeff Brown9c3cda02010-06-15 01:31:58 -07002359 LOGD("notifyConfigurationChanged - eventTime=%lld", eventTime);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002360#endif
2361
Jeff Brownb88102f2010-09-08 11:49:43 -07002362 bool needWake;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002363 { // acquire lock
2364 AutoMutex _l(mLock);
2365
Jeff Brown7fbdc842010-06-17 20:52:56 -07002366 ConfigurationChangedEntry* newEntry = mAllocator.obtainConfigurationChangedEntry(eventTime);
Jeff Brownb88102f2010-09-08 11:49:43 -07002367 needWake = enqueueInboundEventLocked(newEntry);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002368 } // release lock
2369
Jeff Brownb88102f2010-09-08 11:49:43 -07002370 if (needWake) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002371 mLooper->wake();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002372 }
2373}
2374
Jeff Brown58a2da82011-01-25 16:02:22 -08002375void InputDispatcher::notifyKey(nsecs_t eventTime, int32_t deviceId, uint32_t source,
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002376 uint32_t policyFlags, int32_t action, int32_t flags,
2377 int32_t keyCode, int32_t scanCode, int32_t metaState, nsecs_t downTime) {
2378#if DEBUG_INBOUND_EVENT_DETAILS
Jeff Brown90655042010-12-02 13:50:46 -08002379 LOGD("notifyKey - eventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, action=0x%x, "
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002380 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%lld",
Jeff Brownc5ed5912010-07-14 18:48:53 -07002381 eventTime, deviceId, source, policyFlags, action, flags,
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002382 keyCode, scanCode, metaState, downTime);
2383#endif
Jeff Brown01ce2e92010-09-26 22:20:12 -07002384 if (! validateKeyEvent(action)) {
2385 return;
2386 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002387
Jeff Brown1f245102010-11-18 20:53:46 -08002388 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
2389 policyFlags |= POLICY_FLAG_VIRTUAL;
2390 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
2391 }
Jeff Brown924c4d42011-03-07 16:40:47 -08002392 if (policyFlags & POLICY_FLAG_ALT) {
2393 metaState |= AMETA_ALT_ON | AMETA_ALT_LEFT_ON;
2394 }
2395 if (policyFlags & POLICY_FLAG_ALT_GR) {
2396 metaState |= AMETA_ALT_ON | AMETA_ALT_RIGHT_ON;
2397 }
2398 if (policyFlags & POLICY_FLAG_SHIFT) {
2399 metaState |= AMETA_SHIFT_ON | AMETA_SHIFT_LEFT_ON;
2400 }
2401 if (policyFlags & POLICY_FLAG_CAPS_LOCK) {
2402 metaState |= AMETA_CAPS_LOCK_ON;
2403 }
2404 if (policyFlags & POLICY_FLAG_FUNCTION) {
2405 metaState |= AMETA_FUNCTION_ON;
2406 }
Jeff Brown1f245102010-11-18 20:53:46 -08002407
Jeff Browne20c9e02010-10-11 14:20:19 -07002408 policyFlags |= POLICY_FLAG_TRUSTED;
Jeff Brown1f245102010-11-18 20:53:46 -08002409
2410 KeyEvent event;
2411 event.initialize(deviceId, source, action, flags, keyCode, scanCode,
2412 metaState, 0, downTime, eventTime);
2413
2414 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
2415
2416 if (policyFlags & POLICY_FLAG_WOKE_HERE) {
2417 flags |= AKEY_EVENT_FLAG_WOKE_HERE;
2418 }
Jeff Brownb6997262010-10-08 22:31:17 -07002419
Jeff Brownb88102f2010-09-08 11:49:43 -07002420 bool needWake;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002421 { // acquire lock
Jeff Brown0029c662011-03-30 02:25:18 -07002422 mLock.lock();
2423
2424 if (mInputFilterEnabled) {
2425 mLock.unlock();
2426
2427 policyFlags |= POLICY_FLAG_FILTERED;
2428 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2429 return; // event was consumed by the filter
2430 }
2431
2432 mLock.lock();
2433 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002434
Jeff Brown7fbdc842010-06-17 20:52:56 -07002435 int32_t repeatCount = 0;
2436 KeyEntry* newEntry = mAllocator.obtainKeyEntry(eventTime,
Jeff Brownc5ed5912010-07-14 18:48:53 -07002437 deviceId, source, policyFlags, action, flags, keyCode, scanCode,
Jeff Brown7fbdc842010-06-17 20:52:56 -07002438 metaState, repeatCount, downTime);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002439
Jeff Brownb88102f2010-09-08 11:49:43 -07002440 needWake = enqueueInboundEventLocked(newEntry);
Jeff Brown0029c662011-03-30 02:25:18 -07002441 mLock.unlock();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002442 } // release lock
2443
Jeff Brownb88102f2010-09-08 11:49:43 -07002444 if (needWake) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002445 mLooper->wake();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002446 }
2447}
2448
Jeff Brown58a2da82011-01-25 16:02:22 -08002449void InputDispatcher::notifyMotion(nsecs_t eventTime, int32_t deviceId, uint32_t source,
Jeff Brown85a31762010-09-01 17:01:00 -07002450 uint32_t policyFlags, int32_t action, int32_t flags, int32_t metaState, int32_t edgeFlags,
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002451 uint32_t pointerCount, const int32_t* pointerIds, const PointerCoords* pointerCoords,
2452 float xPrecision, float yPrecision, nsecs_t downTime) {
2453#if DEBUG_INBOUND_EVENT_DETAILS
Jeff Brown90655042010-12-02 13:50:46 -08002454 LOGD("notifyMotion - eventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, "
Jeff Brown85a31762010-09-01 17:01:00 -07002455 "action=0x%x, flags=0x%x, metaState=0x%x, edgeFlags=0x%x, "
2456 "xPrecision=%f, yPrecision=%f, downTime=%lld",
2457 eventTime, deviceId, source, policyFlags, action, flags, metaState, edgeFlags,
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002458 xPrecision, yPrecision, downTime);
2459 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brown8d608662010-08-30 03:02:23 -07002460 LOGD(" Pointer %d: id=%d, x=%f, y=%f, pressure=%f, size=%f, "
Jeff Brown85a31762010-09-01 17:01:00 -07002461 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
Jeff Brown8d608662010-08-30 03:02:23 -07002462 "orientation=%f",
Jeff Brown91c69ab2011-02-14 17:03:18 -08002463 i, pointerIds[i],
Jeff Brownebbd5d12011-02-17 13:01:34 -08002464 pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
2465 pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
2466 pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
2467 pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
2468 pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
2469 pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
2470 pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
2471 pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
2472 pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002473 }
2474#endif
Jeff Brown01ce2e92010-09-26 22:20:12 -07002475 if (! validateMotionEvent(action, pointerCount, pointerIds)) {
2476 return;
2477 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002478
Jeff Browne20c9e02010-10-11 14:20:19 -07002479 policyFlags |= POLICY_FLAG_TRUSTED;
Jeff Brown56194eb2011-03-02 19:23:13 -08002480 mPolicy->interceptMotionBeforeQueueing(eventTime, /*byref*/ policyFlags);
Jeff Brownb6997262010-10-08 22:31:17 -07002481
Jeff Brownb88102f2010-09-08 11:49:43 -07002482 bool needWake;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002483 { // acquire lock
Jeff Brown0029c662011-03-30 02:25:18 -07002484 mLock.lock();
2485
2486 if (mInputFilterEnabled) {
2487 mLock.unlock();
2488
2489 MotionEvent event;
2490 event.initialize(deviceId, source, action, flags, edgeFlags, metaState, 0, 0,
2491 xPrecision, yPrecision, downTime, eventTime,
2492 pointerCount, pointerIds, pointerCoords);
2493
2494 policyFlags |= POLICY_FLAG_FILTERED;
2495 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2496 return; // event was consumed by the filter
2497 }
2498
2499 mLock.lock();
2500 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002501
2502 // Attempt batching and streaming of move events.
Jeff Browncc0c1592011-02-19 05:07:28 -08002503 if (action == AMOTION_EVENT_ACTION_MOVE
2504 || action == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002505 // BATCHING CASE
2506 //
2507 // Try to append a move sample to the tail of the inbound queue for this device.
2508 // Give up if we encounter a non-move motion event for this device since that
2509 // means we cannot append any new samples until a new motion event has started.
Jeff Brownb88102f2010-09-08 11:49:43 -07002510 for (EventEntry* entry = mInboundQueue.tailSentinel.prev;
2511 entry != & mInboundQueue.headSentinel; entry = entry->prev) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002512 if (entry->type != EventEntry::TYPE_MOTION) {
2513 // Keep looking for motion events.
2514 continue;
2515 }
2516
2517 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
Jeff Brownefd32662011-03-08 15:13:06 -08002518 if (motionEntry->deviceId != deviceId
2519 || motionEntry->source != source) {
2520 // Keep looking for this device and source.
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002521 continue;
2522 }
2523
Jeff Brown4e91a182011-04-07 11:38:09 -07002524 if (!motionEntry->canAppendSamples(action, pointerCount, pointerIds)) {
Jeff Brownefd32662011-03-08 15:13:06 -08002525 // Last motion event in the queue for this device and source is
2526 // not compatible for appending new samples. Stop here.
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002527 goto NoBatchingOrStreaming;
2528 }
2529
Jeff Brown9c3cda02010-06-15 01:31:58 -07002530 // Do the batching magic.
Jeff Brown4e91a182011-04-07 11:38:09 -07002531 batchMotionLocked(motionEntry, eventTime, metaState, pointerCoords,
2532 "most recent motion event for this device and source in the inbound queue");
Jeff Brown0029c662011-03-30 02:25:18 -07002533 mLock.unlock();
Jeff Brown9c3cda02010-06-15 01:31:58 -07002534 return; // done!
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002535 }
2536
Jeff Brownf6989da2011-04-06 17:19:48 -07002537 // BATCHING ONTO PENDING EVENT CASE
2538 //
2539 // Try to append a move sample to the currently pending event, if there is one.
2540 // We can do this as long as we are still waiting to find the targets for the
2541 // event. Once the targets are locked-in we can only do streaming.
2542 if (mPendingEvent
2543 && (!mPendingEvent->dispatchInProgress || !mCurrentInputTargetsValid)
2544 && mPendingEvent->type == EventEntry::TYPE_MOTION) {
2545 MotionEntry* motionEntry = static_cast<MotionEntry*>(mPendingEvent);
2546 if (motionEntry->deviceId == deviceId && motionEntry->source == source) {
Jeff Brown4e91a182011-04-07 11:38:09 -07002547 if (!motionEntry->canAppendSamples(action, pointerCount, pointerIds)) {
2548 // Pending motion event is for this device and source but it is
2549 // not compatible for appending new samples. Stop here.
Jeff Brownf6989da2011-04-06 17:19:48 -07002550 goto NoBatchingOrStreaming;
2551 }
2552
Jeff Brownf6989da2011-04-06 17:19:48 -07002553 // Do the batching magic.
Jeff Brown4e91a182011-04-07 11:38:09 -07002554 batchMotionLocked(motionEntry, eventTime, metaState, pointerCoords,
2555 "pending motion event");
Jeff Brownf6989da2011-04-06 17:19:48 -07002556 mLock.unlock();
2557 return; // done!
2558 }
2559 }
2560
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002561 // STREAMING CASE
2562 //
2563 // There is no pending motion event (of any kind) for this device in the inbound queue.
Jeff Brown519e0242010-09-15 15:18:56 -07002564 // Search the outbound queue for the current foreground targets to find a dispatched
2565 // motion event that is still in progress. If found, then, appen the new sample to
2566 // that event and push it out to all current targets. The logic in
2567 // prepareDispatchCycleLocked takes care of the case where some targets may
2568 // already have consumed the motion event by starting a new dispatch cycle if needed.
Jeff Brown9c3cda02010-06-15 01:31:58 -07002569 if (mCurrentInputTargetsValid) {
Jeff Brown519e0242010-09-15 15:18:56 -07002570 for (size_t i = 0; i < mCurrentInputTargets.size(); i++) {
2571 const InputTarget& inputTarget = mCurrentInputTargets[i];
2572 if ((inputTarget.flags & InputTarget::FLAG_FOREGROUND) == 0) {
2573 // Skip non-foreground targets. We only want to stream if there is at
2574 // least one foreground target whose dispatch is still in progress.
2575 continue;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002576 }
Jeff Brown519e0242010-09-15 15:18:56 -07002577
2578 ssize_t connectionIndex = getConnectionIndexLocked(inputTarget.inputChannel);
2579 if (connectionIndex < 0) {
2580 // Connection must no longer be valid.
2581 continue;
2582 }
2583
2584 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
2585 if (connection->outboundQueue.isEmpty()) {
2586 // This foreground target has an empty outbound queue.
2587 continue;
2588 }
2589
2590 DispatchEntry* dispatchEntry = connection->outboundQueue.headSentinel.next;
2591 if (! dispatchEntry->inProgress
Jeff Brown01ce2e92010-09-26 22:20:12 -07002592 || dispatchEntry->eventEntry->type != EventEntry::TYPE_MOTION
2593 || dispatchEntry->isSplit()) {
2594 // No motion event is being dispatched, or it is being split across
2595 // windows in which case we cannot stream.
Jeff Brown519e0242010-09-15 15:18:56 -07002596 continue;
2597 }
2598
2599 MotionEntry* motionEntry = static_cast<MotionEntry*>(
2600 dispatchEntry->eventEntry);
Jeff Browncc0c1592011-02-19 05:07:28 -08002601 if (motionEntry->action != action
Jeff Brown519e0242010-09-15 15:18:56 -07002602 || motionEntry->deviceId != deviceId
Jeff Brown58a2da82011-01-25 16:02:22 -08002603 || motionEntry->source != source
Jeff Brown519e0242010-09-15 15:18:56 -07002604 || motionEntry->pointerCount != pointerCount
2605 || motionEntry->isInjected()) {
2606 // The motion event is not compatible with this move.
2607 continue;
2608 }
2609
Jeff Browna032cc02011-03-07 16:56:21 -08002610 if (action == AMOTION_EVENT_ACTION_HOVER_MOVE) {
2611 if (!mLastHoverWindow) {
2612#if DEBUG_BATCHING
2613 LOGD("Not streaming hover move because there is no "
2614 "last hovered window.");
2615#endif
2616 goto NoBatchingOrStreaming;
2617 }
2618
2619 const InputWindow* hoverWindow = findTouchedWindowAtLocked(
2620 pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X),
2621 pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
2622 if (mLastHoverWindow != hoverWindow) {
2623#if DEBUG_BATCHING
2624 LOGD("Not streaming hover move because the last hovered window "
2625 "is '%s' but the currently hovered window is '%s'.",
2626 mLastHoverWindow->name.string(),
2627 hoverWindow ? hoverWindow->name.string() : "<null>");
2628#endif
2629 goto NoBatchingOrStreaming;
2630 }
2631 }
2632
Jeff Brown519e0242010-09-15 15:18:56 -07002633 // Hurray! This foreground target is currently dispatching a move event
2634 // that we can stream onto. Append the motion sample and resume dispatch.
2635 mAllocator.appendMotionSample(motionEntry, eventTime, pointerCoords);
2636#if DEBUG_BATCHING
2637 LOGD("Appended motion sample onto batch for most recently dispatched "
Jeff Brown4e91a182011-04-07 11:38:09 -07002638 "motion event for this device and source in the outbound queues. "
Jeff Brown519e0242010-09-15 15:18:56 -07002639 "Attempting to stream the motion sample.");
2640#endif
2641 nsecs_t currentTime = now();
2642 dispatchEventToCurrentInputTargetsLocked(currentTime, motionEntry,
2643 true /*resumeWithAppendedMotionSample*/);
2644
2645 runCommandsLockedInterruptible();
Jeff Brown0029c662011-03-30 02:25:18 -07002646 mLock.unlock();
Jeff Brown519e0242010-09-15 15:18:56 -07002647 return; // done!
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002648 }
2649 }
2650
2651NoBatchingOrStreaming:;
2652 }
2653
2654 // Just enqueue a new motion event.
Jeff Brown7fbdc842010-06-17 20:52:56 -07002655 MotionEntry* newEntry = mAllocator.obtainMotionEntry(eventTime,
Jeff Brown85a31762010-09-01 17:01:00 -07002656 deviceId, source, policyFlags, action, flags, metaState, edgeFlags,
Jeff Brown7fbdc842010-06-17 20:52:56 -07002657 xPrecision, yPrecision, downTime,
2658 pointerCount, pointerIds, pointerCoords);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002659
Jeff Brownb88102f2010-09-08 11:49:43 -07002660 needWake = enqueueInboundEventLocked(newEntry);
Jeff Brown0029c662011-03-30 02:25:18 -07002661 mLock.unlock();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002662 } // release lock
2663
Jeff Brownb88102f2010-09-08 11:49:43 -07002664 if (needWake) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002665 mLooper->wake();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002666 }
2667}
2668
Jeff Brown4e91a182011-04-07 11:38:09 -07002669void InputDispatcher::batchMotionLocked(MotionEntry* entry, nsecs_t eventTime,
2670 int32_t metaState, const PointerCoords* pointerCoords, const char* eventDescription) {
2671 // Combine meta states.
2672 entry->metaState |= metaState;
2673
2674 // Coalesce this sample if not enough time has elapsed since the last sample was
2675 // initially appended to the batch.
2676 MotionSample* lastSample = entry->lastSample;
2677 long interval = eventTime - lastSample->eventTimeBeforeCoalescing;
2678 if (interval <= MOTION_SAMPLE_COALESCE_INTERVAL) {
2679 uint32_t pointerCount = entry->pointerCount;
2680 for (uint32_t i = 0; i < pointerCount; i++) {
2681 lastSample->pointerCoords[i].copyFrom(pointerCoords[i]);
2682 }
2683 lastSample->eventTime = eventTime;
2684#if DEBUG_BATCHING
2685 LOGD("Coalesced motion into last sample of batch for %s, events were %0.3f ms apart",
2686 eventDescription, interval * 0.000001f);
2687#endif
2688 return;
2689 }
2690
2691 // Append the sample.
2692 mAllocator.appendMotionSample(entry, eventTime, pointerCoords);
2693#if DEBUG_BATCHING
2694 LOGD("Appended motion sample onto batch for %s, events were %0.3f ms apart",
2695 eventDescription, interval * 0.000001f);
2696#endif
2697}
2698
Jeff Brownb6997262010-10-08 22:31:17 -07002699void InputDispatcher::notifySwitch(nsecs_t when, int32_t switchCode, int32_t switchValue,
2700 uint32_t policyFlags) {
2701#if DEBUG_INBOUND_EVENT_DETAILS
2702 LOGD("notifySwitch - switchCode=%d, switchValue=%d, policyFlags=0x%x",
2703 switchCode, switchValue, policyFlags);
2704#endif
2705
Jeff Browne20c9e02010-10-11 14:20:19 -07002706 policyFlags |= POLICY_FLAG_TRUSTED;
Jeff Brownb6997262010-10-08 22:31:17 -07002707 mPolicy->notifySwitch(when, switchCode, switchValue, policyFlags);
2708}
2709
Jeff Brown7fbdc842010-06-17 20:52:56 -07002710int32_t InputDispatcher::injectInputEvent(const InputEvent* event,
Jeff Brown0029c662011-03-30 02:25:18 -07002711 int32_t injectorPid, int32_t injectorUid, int32_t syncMode, int32_t timeoutMillis,
2712 uint32_t policyFlags) {
Jeff Brown7fbdc842010-06-17 20:52:56 -07002713#if DEBUG_INBOUND_EVENT_DETAILS
2714 LOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Jeff Brown0029c662011-03-30 02:25:18 -07002715 "syncMode=%d, timeoutMillis=%d, policyFlags=0x%08x",
2716 event->getType(), injectorPid, injectorUid, syncMode, timeoutMillis, policyFlags);
Jeff Brown7fbdc842010-06-17 20:52:56 -07002717#endif
2718
2719 nsecs_t endTime = now() + milliseconds_to_nanoseconds(timeoutMillis);
Jeff Browne20c9e02010-10-11 14:20:19 -07002720
Jeff Brown0029c662011-03-30 02:25:18 -07002721 policyFlags |= POLICY_FLAG_INJECTED;
Jeff Browne20c9e02010-10-11 14:20:19 -07002722 if (hasInjectionPermission(injectorPid, injectorUid)) {
2723 policyFlags |= POLICY_FLAG_TRUSTED;
2724 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07002725
Jeff Brownb6997262010-10-08 22:31:17 -07002726 EventEntry* injectedEntry;
2727 switch (event->getType()) {
2728 case AINPUT_EVENT_TYPE_KEY: {
2729 const KeyEvent* keyEvent = static_cast<const KeyEvent*>(event);
2730 int32_t action = keyEvent->getAction();
2731 if (! validateKeyEvent(action)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07002732 return INPUT_EVENT_INJECTION_FAILED;
2733 }
2734
Jeff Brownb6997262010-10-08 22:31:17 -07002735 int32_t flags = keyEvent->getFlags();
Jeff Brown1f245102010-11-18 20:53:46 -08002736 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
2737 policyFlags |= POLICY_FLAG_VIRTUAL;
2738 }
2739
Jeff Brown0029c662011-03-30 02:25:18 -07002740 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
2741 mPolicy->interceptKeyBeforeQueueing(keyEvent, /*byref*/ policyFlags);
2742 }
Jeff Brown1f245102010-11-18 20:53:46 -08002743
2744 if (policyFlags & POLICY_FLAG_WOKE_HERE) {
2745 flags |= AKEY_EVENT_FLAG_WOKE_HERE;
2746 }
Jeff Brown6ec402b2010-07-28 15:48:59 -07002747
Jeff Brownb6997262010-10-08 22:31:17 -07002748 mLock.lock();
Jeff Brown1f245102010-11-18 20:53:46 -08002749 injectedEntry = mAllocator.obtainKeyEntry(keyEvent->getEventTime(),
2750 keyEvent->getDeviceId(), keyEvent->getSource(),
2751 policyFlags, action, flags,
2752 keyEvent->getKeyCode(), keyEvent->getScanCode(), keyEvent->getMetaState(),
Jeff Brownb6997262010-10-08 22:31:17 -07002753 keyEvent->getRepeatCount(), keyEvent->getDownTime());
2754 break;
2755 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07002756
Jeff Brownb6997262010-10-08 22:31:17 -07002757 case AINPUT_EVENT_TYPE_MOTION: {
2758 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
2759 int32_t action = motionEvent->getAction();
2760 size_t pointerCount = motionEvent->getPointerCount();
2761 const int32_t* pointerIds = motionEvent->getPointerIds();
2762 if (! validateMotionEvent(action, pointerCount, pointerIds)) {
2763 return INPUT_EVENT_INJECTION_FAILED;
2764 }
2765
Jeff Brown0029c662011-03-30 02:25:18 -07002766 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
2767 nsecs_t eventTime = motionEvent->getEventTime();
2768 mPolicy->interceptMotionBeforeQueueing(eventTime, /*byref*/ policyFlags);
2769 }
Jeff Brownb6997262010-10-08 22:31:17 -07002770
2771 mLock.lock();
2772 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
2773 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
2774 MotionEntry* motionEntry = mAllocator.obtainMotionEntry(*sampleEventTimes,
2775 motionEvent->getDeviceId(), motionEvent->getSource(), policyFlags,
2776 action, motionEvent->getFlags(),
2777 motionEvent->getMetaState(), motionEvent->getEdgeFlags(),
2778 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
2779 motionEvent->getDownTime(), uint32_t(pointerCount),
2780 pointerIds, samplePointerCoords);
2781 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
2782 sampleEventTimes += 1;
2783 samplePointerCoords += pointerCount;
2784 mAllocator.appendMotionSample(motionEntry, *sampleEventTimes, samplePointerCoords);
2785 }
2786 injectedEntry = motionEntry;
2787 break;
2788 }
2789
2790 default:
2791 LOGW("Cannot inject event of type %d", event->getType());
2792 return INPUT_EVENT_INJECTION_FAILED;
2793 }
2794
2795 InjectionState* injectionState = mAllocator.obtainInjectionState(injectorPid, injectorUid);
2796 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
2797 injectionState->injectionIsAsync = true;
2798 }
2799
2800 injectionState->refCount += 1;
2801 injectedEntry->injectionState = injectionState;
2802
2803 bool needWake = enqueueInboundEventLocked(injectedEntry);
2804 mLock.unlock();
Jeff Brown7fbdc842010-06-17 20:52:56 -07002805
Jeff Brownb88102f2010-09-08 11:49:43 -07002806 if (needWake) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002807 mLooper->wake();
Jeff Brown7fbdc842010-06-17 20:52:56 -07002808 }
2809
2810 int32_t injectionResult;
2811 { // acquire lock
2812 AutoMutex _l(mLock);
2813
Jeff Brown6ec402b2010-07-28 15:48:59 -07002814 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
2815 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
2816 } else {
2817 for (;;) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002818 injectionResult = injectionState->injectionResult;
Jeff Brown6ec402b2010-07-28 15:48:59 -07002819 if (injectionResult != INPUT_EVENT_INJECTION_PENDING) {
2820 break;
2821 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07002822
Jeff Brown7fbdc842010-06-17 20:52:56 -07002823 nsecs_t remainingTimeout = endTime - now();
2824 if (remainingTimeout <= 0) {
Jeff Brown6ec402b2010-07-28 15:48:59 -07002825#if DEBUG_INJECTION
2826 LOGD("injectInputEvent - Timed out waiting for injection result "
2827 "to become available.");
2828#endif
Jeff Brown7fbdc842010-06-17 20:52:56 -07002829 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
2830 break;
2831 }
2832
Jeff Brown6ec402b2010-07-28 15:48:59 -07002833 mInjectionResultAvailableCondition.waitRelative(mLock, remainingTimeout);
2834 }
2835
2836 if (injectionResult == INPUT_EVENT_INJECTION_SUCCEEDED
2837 && syncMode == INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002838 while (injectionState->pendingForegroundDispatches != 0) {
Jeff Brown6ec402b2010-07-28 15:48:59 -07002839#if DEBUG_INJECTION
Jeff Brown519e0242010-09-15 15:18:56 -07002840 LOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
Jeff Brown01ce2e92010-09-26 22:20:12 -07002841 injectionState->pendingForegroundDispatches);
Jeff Brown6ec402b2010-07-28 15:48:59 -07002842#endif
2843 nsecs_t remainingTimeout = endTime - now();
2844 if (remainingTimeout <= 0) {
2845#if DEBUG_INJECTION
Jeff Brown519e0242010-09-15 15:18:56 -07002846 LOGD("injectInputEvent - Timed out waiting for pending foreground "
Jeff Brown6ec402b2010-07-28 15:48:59 -07002847 "dispatches to finish.");
2848#endif
2849 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
2850 break;
2851 }
2852
2853 mInjectionSyncFinishedCondition.waitRelative(mLock, remainingTimeout);
2854 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07002855 }
2856 }
2857
Jeff Brown01ce2e92010-09-26 22:20:12 -07002858 mAllocator.releaseInjectionState(injectionState);
Jeff Brown7fbdc842010-06-17 20:52:56 -07002859 } // release lock
2860
Jeff Brown6ec402b2010-07-28 15:48:59 -07002861#if DEBUG_INJECTION
2862 LOGD("injectInputEvent - Finished with result %d. "
2863 "injectorPid=%d, injectorUid=%d",
2864 injectionResult, injectorPid, injectorUid);
2865#endif
2866
Jeff Brown7fbdc842010-06-17 20:52:56 -07002867 return injectionResult;
2868}
2869
Jeff Brownb6997262010-10-08 22:31:17 -07002870bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
2871 return injectorUid == 0
2872 || mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
2873}
2874
Jeff Brown7fbdc842010-06-17 20:52:56 -07002875void InputDispatcher::setInjectionResultLocked(EventEntry* entry, int32_t injectionResult) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002876 InjectionState* injectionState = entry->injectionState;
2877 if (injectionState) {
Jeff Brown7fbdc842010-06-17 20:52:56 -07002878#if DEBUG_INJECTION
2879 LOGD("Setting input event injection result to %d. "
2880 "injectorPid=%d, injectorUid=%d",
Jeff Brown01ce2e92010-09-26 22:20:12 -07002881 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
Jeff Brown7fbdc842010-06-17 20:52:56 -07002882#endif
2883
Jeff Brown0029c662011-03-30 02:25:18 -07002884 if (injectionState->injectionIsAsync
2885 && !(entry->policyFlags & POLICY_FLAG_FILTERED)) {
Jeff Brown6ec402b2010-07-28 15:48:59 -07002886 // Log the outcome since the injector did not wait for the injection result.
2887 switch (injectionResult) {
2888 case INPUT_EVENT_INJECTION_SUCCEEDED:
2889 LOGV("Asynchronous input event injection succeeded.");
2890 break;
2891 case INPUT_EVENT_INJECTION_FAILED:
2892 LOGW("Asynchronous input event injection failed.");
2893 break;
2894 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
2895 LOGW("Asynchronous input event injection permission denied.");
2896 break;
2897 case INPUT_EVENT_INJECTION_TIMED_OUT:
2898 LOGW("Asynchronous input event injection timed out.");
2899 break;
2900 }
2901 }
2902
Jeff Brown01ce2e92010-09-26 22:20:12 -07002903 injectionState->injectionResult = injectionResult;
Jeff Brown7fbdc842010-06-17 20:52:56 -07002904 mInjectionResultAvailableCondition.broadcast();
2905 }
2906}
2907
Jeff Brown01ce2e92010-09-26 22:20:12 -07002908void InputDispatcher::incrementPendingForegroundDispatchesLocked(EventEntry* entry) {
2909 InjectionState* injectionState = entry->injectionState;
2910 if (injectionState) {
2911 injectionState->pendingForegroundDispatches += 1;
2912 }
2913}
2914
Jeff Brown519e0242010-09-15 15:18:56 -07002915void InputDispatcher::decrementPendingForegroundDispatchesLocked(EventEntry* entry) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002916 InjectionState* injectionState = entry->injectionState;
2917 if (injectionState) {
2918 injectionState->pendingForegroundDispatches -= 1;
Jeff Brown6ec402b2010-07-28 15:48:59 -07002919
Jeff Brown01ce2e92010-09-26 22:20:12 -07002920 if (injectionState->pendingForegroundDispatches == 0) {
2921 mInjectionSyncFinishedCondition.broadcast();
2922 }
Jeff Brownb88102f2010-09-08 11:49:43 -07002923 }
2924}
2925
Jeff Brown01ce2e92010-09-26 22:20:12 -07002926const InputWindow* InputDispatcher::getWindowLocked(const sp<InputChannel>& inputChannel) {
2927 for (size_t i = 0; i < mWindows.size(); i++) {
2928 const InputWindow* window = & mWindows[i];
2929 if (window->inputChannel == inputChannel) {
2930 return window;
2931 }
2932 }
2933 return NULL;
2934}
2935
Jeff Brownb88102f2010-09-08 11:49:43 -07002936void InputDispatcher::setInputWindows(const Vector<InputWindow>& inputWindows) {
2937#if DEBUG_FOCUS
2938 LOGD("setInputWindows");
2939#endif
2940 { // acquire lock
2941 AutoMutex _l(mLock);
2942
Jeff Brown01ce2e92010-09-26 22:20:12 -07002943 // Clear old window pointers.
Jeff Brownb6997262010-10-08 22:31:17 -07002944 sp<InputChannel> oldFocusedWindowChannel;
2945 if (mFocusedWindow) {
2946 oldFocusedWindowChannel = mFocusedWindow->inputChannel;
2947 mFocusedWindow = NULL;
2948 }
Jeff Browna032cc02011-03-07 16:56:21 -08002949 sp<InputChannel> oldLastHoverWindowChannel;
2950 if (mLastHoverWindow) {
2951 oldLastHoverWindowChannel = mLastHoverWindow->inputChannel;
2952 mLastHoverWindow = NULL;
2953 }
Jeff Brownb6997262010-10-08 22:31:17 -07002954
Jeff Brownb88102f2010-09-08 11:49:43 -07002955 mWindows.clear();
Jeff Brown2a95c2a2010-09-16 12:31:46 -07002956
2957 // Loop over new windows and rebuild the necessary window pointers for
2958 // tracking focus and touch.
Jeff Brownb88102f2010-09-08 11:49:43 -07002959 mWindows.appendVector(inputWindows);
2960
2961 size_t numWindows = mWindows.size();
2962 for (size_t i = 0; i < numWindows; i++) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002963 const InputWindow* window = & mWindows.itemAt(i);
Jeff Brownb88102f2010-09-08 11:49:43 -07002964 if (window->hasFocus) {
2965 mFocusedWindow = window;
Jeff Brown01ce2e92010-09-26 22:20:12 -07002966 break;
Jeff Brownb88102f2010-09-08 11:49:43 -07002967 }
2968 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07002969
Jeff Brownb6997262010-10-08 22:31:17 -07002970 if (oldFocusedWindowChannel != NULL) {
2971 if (!mFocusedWindow || oldFocusedWindowChannel != mFocusedWindow->inputChannel) {
2972#if DEBUG_FOCUS
2973 LOGD("Focus left window: %s",
2974 oldFocusedWindowChannel->getName().string());
2975#endif
Jeff Brownda3d5a92011-03-29 15:11:34 -07002976 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
2977 "focus left window");
2978 synthesizeCancelationEventsForInputChannelLocked(oldFocusedWindowChannel, options);
Jeff Brownb6997262010-10-08 22:31:17 -07002979 oldFocusedWindowChannel.clear();
2980 }
2981 }
2982 if (mFocusedWindow && oldFocusedWindowChannel == NULL) {
2983#if DEBUG_FOCUS
2984 LOGD("Focus entered window: %s",
2985 mFocusedWindow->inputChannel->getName().string());
2986#endif
2987 }
2988
Jeff Brown01ce2e92010-09-26 22:20:12 -07002989 for (size_t i = 0; i < mTouchState.windows.size(); ) {
2990 TouchedWindow& touchedWindow = mTouchState.windows.editItemAt(i);
2991 const InputWindow* window = getWindowLocked(touchedWindow.channel);
2992 if (window) {
2993 touchedWindow.window = window;
2994 i += 1;
2995 } else {
Jeff Brownb6997262010-10-08 22:31:17 -07002996#if DEBUG_FOCUS
2997 LOGD("Touched window was removed: %s", touchedWindow.channel->getName().string());
2998#endif
Jeff Brownda3d5a92011-03-29 15:11:34 -07002999 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
3000 "touched window was removed");
3001 synthesizeCancelationEventsForInputChannelLocked(touchedWindow.channel, options);
Jeff Brownaf48cae2010-10-15 16:20:51 -07003002 mTouchState.windows.removeAt(i);
Jeff Brown01ce2e92010-09-26 22:20:12 -07003003 }
3004 }
Jeff Brownb88102f2010-09-08 11:49:43 -07003005
Jeff Browna032cc02011-03-07 16:56:21 -08003006 // Recover the last hovered window.
3007 if (oldLastHoverWindowChannel != NULL) {
3008 mLastHoverWindow = getWindowLocked(oldLastHoverWindowChannel);
3009 oldLastHoverWindowChannel.clear();
3010 }
3011
Jeff Brownb88102f2010-09-08 11:49:43 -07003012#if DEBUG_FOCUS
Jeff Brownb6997262010-10-08 22:31:17 -07003013 //logDispatchStateLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -07003014#endif
3015 } // release lock
3016
3017 // Wake up poll loop since it may need to make new input dispatching choices.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07003018 mLooper->wake();
Jeff Brownb88102f2010-09-08 11:49:43 -07003019}
3020
3021void InputDispatcher::setFocusedApplication(const InputApplication* inputApplication) {
3022#if DEBUG_FOCUS
3023 LOGD("setFocusedApplication");
3024#endif
3025 { // acquire lock
3026 AutoMutex _l(mLock);
3027
3028 releaseFocusedApplicationLocked();
3029
3030 if (inputApplication) {
3031 mFocusedApplicationStorage = *inputApplication;
3032 mFocusedApplication = & mFocusedApplicationStorage;
3033 }
3034
3035#if DEBUG_FOCUS
Jeff Brownb6997262010-10-08 22:31:17 -07003036 //logDispatchStateLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -07003037#endif
3038 } // release lock
3039
3040 // Wake up poll loop since it may need to make new input dispatching choices.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07003041 mLooper->wake();
Jeff Brownb88102f2010-09-08 11:49:43 -07003042}
3043
3044void InputDispatcher::releaseFocusedApplicationLocked() {
3045 if (mFocusedApplication) {
3046 mFocusedApplication = NULL;
Jeff Brown928e0542011-01-10 11:17:36 -08003047 mFocusedApplicationStorage.inputApplicationHandle.clear();
Jeff Brownb88102f2010-09-08 11:49:43 -07003048 }
3049}
3050
3051void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
3052#if DEBUG_FOCUS
3053 LOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
3054#endif
3055
3056 bool changed;
3057 { // acquire lock
3058 AutoMutex _l(mLock);
3059
3060 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
Jeff Brown120a4592010-10-27 18:43:51 -07003061 if (mDispatchFrozen && !frozen) {
Jeff Brownb88102f2010-09-08 11:49:43 -07003062 resetANRTimeoutsLocked();
3063 }
3064
Jeff Brown120a4592010-10-27 18:43:51 -07003065 if (mDispatchEnabled && !enabled) {
3066 resetAndDropEverythingLocked("dispatcher is being disabled");
3067 }
3068
Jeff Brownb88102f2010-09-08 11:49:43 -07003069 mDispatchEnabled = enabled;
3070 mDispatchFrozen = frozen;
3071 changed = true;
3072 } else {
3073 changed = false;
3074 }
3075
3076#if DEBUG_FOCUS
Jeff Brownb6997262010-10-08 22:31:17 -07003077 //logDispatchStateLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -07003078#endif
3079 } // release lock
3080
3081 if (changed) {
3082 // Wake up poll loop since it may need to make new input dispatching choices.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07003083 mLooper->wake();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003084 }
3085}
3086
Jeff Brown0029c662011-03-30 02:25:18 -07003087void InputDispatcher::setInputFilterEnabled(bool enabled) {
3088#if DEBUG_FOCUS
3089 LOGD("setInputFilterEnabled: enabled=%d", enabled);
3090#endif
3091
3092 { // acquire lock
3093 AutoMutex _l(mLock);
3094
3095 if (mInputFilterEnabled == enabled) {
3096 return;
3097 }
3098
3099 mInputFilterEnabled = enabled;
3100 resetAndDropEverythingLocked("input filter is being enabled or disabled");
3101 } // release lock
3102
3103 // Wake up poll loop since there might be work to do to drop everything.
3104 mLooper->wake();
3105}
3106
Jeff Browne6504122010-09-27 14:52:15 -07003107bool InputDispatcher::transferTouchFocus(const sp<InputChannel>& fromChannel,
3108 const sp<InputChannel>& toChannel) {
3109#if DEBUG_FOCUS
3110 LOGD("transferTouchFocus: fromChannel=%s, toChannel=%s",
3111 fromChannel->getName().string(), toChannel->getName().string());
3112#endif
3113 { // acquire lock
3114 AutoMutex _l(mLock);
3115
3116 const InputWindow* fromWindow = getWindowLocked(fromChannel);
3117 const InputWindow* toWindow = getWindowLocked(toChannel);
3118 if (! fromWindow || ! toWindow) {
3119#if DEBUG_FOCUS
3120 LOGD("Cannot transfer focus because from or to window not found.");
3121#endif
3122 return false;
3123 }
3124 if (fromWindow == toWindow) {
3125#if DEBUG_FOCUS
3126 LOGD("Trivial transfer to same window.");
3127#endif
3128 return true;
3129 }
3130
3131 bool found = false;
3132 for (size_t i = 0; i < mTouchState.windows.size(); i++) {
3133 const TouchedWindow& touchedWindow = mTouchState.windows[i];
3134 if (touchedWindow.window == fromWindow) {
3135 int32_t oldTargetFlags = touchedWindow.targetFlags;
3136 BitSet32 pointerIds = touchedWindow.pointerIds;
3137
3138 mTouchState.windows.removeAt(i);
3139
Jeff Brown46e75292010-11-10 16:53:45 -08003140 int32_t newTargetFlags = oldTargetFlags
Jeff Browna032cc02011-03-07 16:56:21 -08003141 & (InputTarget::FLAG_FOREGROUND
3142 | InputTarget::FLAG_SPLIT | InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Browne6504122010-09-27 14:52:15 -07003143 mTouchState.addOrUpdateWindow(toWindow, newTargetFlags, pointerIds);
3144
3145 found = true;
3146 break;
3147 }
3148 }
3149
3150 if (! found) {
3151#if DEBUG_FOCUS
3152 LOGD("Focus transfer failed because from window did not have focus.");
3153#endif
3154 return false;
3155 }
3156
Jeff Brown9c9f1a32010-10-11 18:32:20 -07003157 ssize_t fromConnectionIndex = getConnectionIndexLocked(fromChannel);
3158 ssize_t toConnectionIndex = getConnectionIndexLocked(toChannel);
3159 if (fromConnectionIndex >= 0 && toConnectionIndex >= 0) {
3160 sp<Connection> fromConnection = mConnectionsByReceiveFd.valueAt(fromConnectionIndex);
3161 sp<Connection> toConnection = mConnectionsByReceiveFd.valueAt(toConnectionIndex);
3162
3163 fromConnection->inputState.copyPointerStateTo(toConnection->inputState);
Jeff Brownda3d5a92011-03-29 15:11:34 -07003164 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Jeff Brown9c9f1a32010-10-11 18:32:20 -07003165 "transferring touch focus from this window to another window");
Jeff Brownda3d5a92011-03-29 15:11:34 -07003166 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Jeff Brown9c9f1a32010-10-11 18:32:20 -07003167 }
3168
Jeff Browne6504122010-09-27 14:52:15 -07003169#if DEBUG_FOCUS
3170 logDispatchStateLocked();
3171#endif
3172 } // release lock
3173
3174 // Wake up poll loop since it may need to make new input dispatching choices.
3175 mLooper->wake();
3176 return true;
3177}
3178
Jeff Brown120a4592010-10-27 18:43:51 -07003179void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
3180#if DEBUG_FOCUS
3181 LOGD("Resetting and dropping all events (%s).", reason);
3182#endif
3183
Jeff Brownda3d5a92011-03-29 15:11:34 -07003184 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
3185 synthesizeCancelationEventsForAllConnectionsLocked(options);
Jeff Brown120a4592010-10-27 18:43:51 -07003186
3187 resetKeyRepeatLocked();
3188 releasePendingEventLocked();
3189 drainInboundQueueLocked();
3190 resetTargetsLocked();
3191
3192 mTouchState.reset();
3193}
3194
Jeff Brownb88102f2010-09-08 11:49:43 -07003195void InputDispatcher::logDispatchStateLocked() {
3196 String8 dump;
3197 dumpDispatchStateLocked(dump);
Jeff Brown2a95c2a2010-09-16 12:31:46 -07003198
3199 char* text = dump.lockBuffer(dump.size());
3200 char* start = text;
3201 while (*start != '\0') {
3202 char* end = strchr(start, '\n');
3203 if (*end == '\n') {
3204 *(end++) = '\0';
3205 }
3206 LOGD("%s", start);
3207 start = end;
3208 }
Jeff Brownb88102f2010-09-08 11:49:43 -07003209}
3210
3211void InputDispatcher::dumpDispatchStateLocked(String8& dump) {
Jeff Brownf2f487182010-10-01 17:46:21 -07003212 dump.appendFormat(INDENT "DispatchEnabled: %d\n", mDispatchEnabled);
3213 dump.appendFormat(INDENT "DispatchFrozen: %d\n", mDispatchFrozen);
Jeff Brownb88102f2010-09-08 11:49:43 -07003214
3215 if (mFocusedApplication) {
Jeff Brownf2f487182010-10-01 17:46:21 -07003216 dump.appendFormat(INDENT "FocusedApplication: name='%s', dispatchingTimeout=%0.3fms\n",
Jeff Brownb88102f2010-09-08 11:49:43 -07003217 mFocusedApplication->name.string(),
3218 mFocusedApplication->dispatchingTimeout / 1000000.0);
3219 } else {
Jeff Brownf2f487182010-10-01 17:46:21 -07003220 dump.append(INDENT "FocusedApplication: <null>\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003221 }
Jeff Brownf2f487182010-10-01 17:46:21 -07003222 dump.appendFormat(INDENT "FocusedWindow: name='%s'\n",
Jeff Brown2a95c2a2010-09-16 12:31:46 -07003223 mFocusedWindow != NULL ? mFocusedWindow->name.string() : "<null>");
Jeff Brownf2f487182010-10-01 17:46:21 -07003224
3225 dump.appendFormat(INDENT "TouchDown: %s\n", toString(mTouchState.down));
3226 dump.appendFormat(INDENT "TouchSplit: %s\n", toString(mTouchState.split));
Jeff Brown95712852011-01-04 19:41:59 -08003227 dump.appendFormat(INDENT "TouchDeviceId: %d\n", mTouchState.deviceId);
Jeff Brown58a2da82011-01-25 16:02:22 -08003228 dump.appendFormat(INDENT "TouchSource: 0x%08x\n", mTouchState.source);
Jeff Brownf2f487182010-10-01 17:46:21 -07003229 if (!mTouchState.windows.isEmpty()) {
3230 dump.append(INDENT "TouchedWindows:\n");
3231 for (size_t i = 0; i < mTouchState.windows.size(); i++) {
3232 const TouchedWindow& touchedWindow = mTouchState.windows[i];
3233 dump.appendFormat(INDENT2 "%d: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
3234 i, touchedWindow.window->name.string(), touchedWindow.pointerIds.value,
3235 touchedWindow.targetFlags);
3236 }
3237 } else {
3238 dump.append(INDENT "TouchedWindows: <none>\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003239 }
3240
Jeff Brownf2f487182010-10-01 17:46:21 -07003241 if (!mWindows.isEmpty()) {
3242 dump.append(INDENT "Windows:\n");
3243 for (size_t i = 0; i < mWindows.size(); i++) {
3244 const InputWindow& window = mWindows[i];
3245 dump.appendFormat(INDENT2 "%d: name='%s', paused=%s, hasFocus=%s, hasWallpaper=%s, "
3246 "visible=%s, canReceiveKeys=%s, flags=0x%08x, type=0x%08x, layer=%d, "
3247 "frame=[%d,%d][%d,%d], "
Jeff Brownfbf09772011-01-16 14:06:57 -08003248 "touchableRegion=",
Jeff Brownf2f487182010-10-01 17:46:21 -07003249 i, window.name.string(),
3250 toString(window.paused),
3251 toString(window.hasFocus),
3252 toString(window.hasWallpaper),
3253 toString(window.visible),
3254 toString(window.canReceiveKeys),
3255 window.layoutParamsFlags, window.layoutParamsType,
3256 window.layer,
3257 window.frameLeft, window.frameTop,
Jeff Brownfbf09772011-01-16 14:06:57 -08003258 window.frameRight, window.frameBottom);
3259 dumpRegion(dump, window.touchableRegion);
3260 dump.appendFormat(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%0.3fms\n",
Jeff Brownf2f487182010-10-01 17:46:21 -07003261 window.ownerPid, window.ownerUid,
3262 window.dispatchingTimeout / 1000000.0);
3263 }
3264 } else {
3265 dump.append(INDENT "Windows: <none>\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003266 }
3267
Jeff Brownf2f487182010-10-01 17:46:21 -07003268 if (!mMonitoringChannels.isEmpty()) {
3269 dump.append(INDENT "MonitoringChannels:\n");
3270 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
3271 const sp<InputChannel>& channel = mMonitoringChannels[i];
3272 dump.appendFormat(INDENT2 "%d: '%s'\n", i, channel->getName().string());
3273 }
3274 } else {
3275 dump.append(INDENT "MonitoringChannels: <none>\n");
3276 }
Jeff Brown519e0242010-09-15 15:18:56 -07003277
Jeff Brownf2f487182010-10-01 17:46:21 -07003278 dump.appendFormat(INDENT "InboundQueue: length=%u\n", mInboundQueue.count());
3279
3280 if (!mActiveConnections.isEmpty()) {
3281 dump.append(INDENT "ActiveConnections:\n");
3282 for (size_t i = 0; i < mActiveConnections.size(); i++) {
3283 const Connection* connection = mActiveConnections[i];
Jeff Brown76860e32010-10-25 17:37:46 -07003284 dump.appendFormat(INDENT2 "%d: '%s', status=%s, outboundQueueLength=%u, "
Jeff Brownb6997262010-10-08 22:31:17 -07003285 "inputState.isNeutral=%s\n",
Jeff Brownf2f487182010-10-01 17:46:21 -07003286 i, connection->getInputChannelName(), connection->getStatusLabel(),
3287 connection->outboundQueue.count(),
Jeff Brownb6997262010-10-08 22:31:17 -07003288 toString(connection->inputState.isNeutral()));
Jeff Brownf2f487182010-10-01 17:46:21 -07003289 }
3290 } else {
3291 dump.append(INDENT "ActiveConnections: <none>\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003292 }
3293
3294 if (isAppSwitchPendingLocked()) {
Jeff Brownf2f487182010-10-01 17:46:21 -07003295 dump.appendFormat(INDENT "AppSwitch: pending, due in %01.1fms\n",
Jeff Brownb88102f2010-09-08 11:49:43 -07003296 (mAppSwitchDueTime - now()) / 1000000.0);
3297 } else {
Jeff Brownf2f487182010-10-01 17:46:21 -07003298 dump.append(INDENT "AppSwitch: not pending\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003299 }
3300}
3301
Jeff Brown928e0542011-01-10 11:17:36 -08003302status_t InputDispatcher::registerInputChannel(const sp<InputChannel>& inputChannel,
3303 const sp<InputWindowHandle>& inputWindowHandle, bool monitor) {
Jeff Brown9c3cda02010-06-15 01:31:58 -07003304#if DEBUG_REGISTRATION
Jeff Brownb88102f2010-09-08 11:49:43 -07003305 LOGD("channel '%s' ~ registerInputChannel - monitor=%s", inputChannel->getName().string(),
3306 toString(monitor));
Jeff Brown9c3cda02010-06-15 01:31:58 -07003307#endif
3308
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003309 { // acquire lock
3310 AutoMutex _l(mLock);
3311
Jeff Brown519e0242010-09-15 15:18:56 -07003312 if (getConnectionIndexLocked(inputChannel) >= 0) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003313 LOGW("Attempted to register already registered input channel '%s'",
3314 inputChannel->getName().string());
3315 return BAD_VALUE;
3316 }
3317
Jeff Brown928e0542011-01-10 11:17:36 -08003318 sp<Connection> connection = new Connection(inputChannel, inputWindowHandle);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003319 status_t status = connection->initialize();
3320 if (status) {
3321 LOGE("Failed to initialize input publisher for input channel '%s', status=%d",
3322 inputChannel->getName().string(), status);
3323 return status;
3324 }
3325
Jeff Brown2cbecea2010-08-17 15:59:26 -07003326 int32_t receiveFd = inputChannel->getReceivePipeFd();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003327 mConnectionsByReceiveFd.add(receiveFd, connection);
Jeff Brown9c3cda02010-06-15 01:31:58 -07003328
Jeff Brownb88102f2010-09-08 11:49:43 -07003329 if (monitor) {
3330 mMonitoringChannels.push(inputChannel);
3331 }
3332
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07003333 mLooper->addFd(receiveFd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
Jeff Brown2cbecea2010-08-17 15:59:26 -07003334
Jeff Brown9c3cda02010-06-15 01:31:58 -07003335 runCommandsLockedInterruptible();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003336 } // release lock
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003337 return OK;
3338}
3339
3340status_t InputDispatcher::unregisterInputChannel(const sp<InputChannel>& inputChannel) {
Jeff Brown9c3cda02010-06-15 01:31:58 -07003341#if DEBUG_REGISTRATION
Jeff Brown349703e2010-06-22 01:27:15 -07003342 LOGD("channel '%s' ~ unregisterInputChannel", inputChannel->getName().string());
Jeff Brown9c3cda02010-06-15 01:31:58 -07003343#endif
3344
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003345 { // acquire lock
3346 AutoMutex _l(mLock);
3347
Jeff Brown519e0242010-09-15 15:18:56 -07003348 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003349 if (connectionIndex < 0) {
3350 LOGW("Attempted to unregister already unregistered input channel '%s'",
3351 inputChannel->getName().string());
3352 return BAD_VALUE;
3353 }
3354
3355 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
3356 mConnectionsByReceiveFd.removeItemsAt(connectionIndex);
3357
3358 connection->status = Connection::STATUS_ZOMBIE;
3359
Jeff Brownb88102f2010-09-08 11:49:43 -07003360 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
3361 if (mMonitoringChannels[i] == inputChannel) {
3362 mMonitoringChannels.removeAt(i);
3363 break;
3364 }
3365 }
3366
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07003367 mLooper->removeFd(inputChannel->getReceivePipeFd());
Jeff Brown2cbecea2010-08-17 15:59:26 -07003368
Jeff Brown7fbdc842010-06-17 20:52:56 -07003369 nsecs_t currentTime = now();
Jeff Brownb6997262010-10-08 22:31:17 -07003370 abortBrokenDispatchCycleLocked(currentTime, connection);
Jeff Brown9c3cda02010-06-15 01:31:58 -07003371
3372 runCommandsLockedInterruptible();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003373 } // release lock
3374
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003375 // Wake the poll loop because removing the connection may have changed the current
3376 // synchronization state.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07003377 mLooper->wake();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003378 return OK;
3379}
3380
Jeff Brown519e0242010-09-15 15:18:56 -07003381ssize_t InputDispatcher::getConnectionIndexLocked(const sp<InputChannel>& inputChannel) {
Jeff Brown2cbecea2010-08-17 15:59:26 -07003382 ssize_t connectionIndex = mConnectionsByReceiveFd.indexOfKey(inputChannel->getReceivePipeFd());
3383 if (connectionIndex >= 0) {
3384 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
3385 if (connection->inputChannel.get() == inputChannel.get()) {
3386 return connectionIndex;
3387 }
3388 }
3389
3390 return -1;
3391}
3392
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003393void InputDispatcher::activateConnectionLocked(Connection* connection) {
3394 for (size_t i = 0; i < mActiveConnections.size(); i++) {
3395 if (mActiveConnections.itemAt(i) == connection) {
3396 return;
3397 }
3398 }
3399 mActiveConnections.add(connection);
3400}
3401
3402void InputDispatcher::deactivateConnectionLocked(Connection* connection) {
3403 for (size_t i = 0; i < mActiveConnections.size(); i++) {
3404 if (mActiveConnections.itemAt(i) == connection) {
3405 mActiveConnections.removeAt(i);
3406 return;
3407 }
3408 }
3409}
3410
Jeff Brown9c3cda02010-06-15 01:31:58 -07003411void InputDispatcher::onDispatchCycleStartedLocked(
Jeff Brown7fbdc842010-06-17 20:52:56 -07003412 nsecs_t currentTime, const sp<Connection>& connection) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003413}
3414
Jeff Brown9c3cda02010-06-15 01:31:58 -07003415void InputDispatcher::onDispatchCycleFinishedLocked(
Jeff Brown3915bb82010-11-05 15:02:16 -07003416 nsecs_t currentTime, const sp<Connection>& connection, bool handled) {
3417 CommandEntry* commandEntry = postCommandLocked(
3418 & InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
3419 commandEntry->connection = connection;
3420 commandEntry->handled = handled;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003421}
3422
Jeff Brown9c3cda02010-06-15 01:31:58 -07003423void InputDispatcher::onDispatchCycleBrokenLocked(
Jeff Brown7fbdc842010-06-17 20:52:56 -07003424 nsecs_t currentTime, const sp<Connection>& connection) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003425 LOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
3426 connection->getInputChannelName());
3427
Jeff Brown9c3cda02010-06-15 01:31:58 -07003428 CommandEntry* commandEntry = postCommandLocked(
3429 & InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
Jeff Brown7fbdc842010-06-17 20:52:56 -07003430 commandEntry->connection = connection;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003431}
3432
Jeff Brown519e0242010-09-15 15:18:56 -07003433void InputDispatcher::onANRLocked(
3434 nsecs_t currentTime, const InputApplication* application, const InputWindow* window,
3435 nsecs_t eventTime, nsecs_t waitStartTime) {
3436 LOGI("Application is not responding: %s. "
3437 "%01.1fms since event, %01.1fms since wait started",
3438 getApplicationWindowLabelLocked(application, window).string(),
3439 (currentTime - eventTime) / 1000000.0,
3440 (currentTime - waitStartTime) / 1000000.0);
3441
3442 CommandEntry* commandEntry = postCommandLocked(
3443 & InputDispatcher::doNotifyANRLockedInterruptible);
3444 if (application) {
Jeff Brown928e0542011-01-10 11:17:36 -08003445 commandEntry->inputApplicationHandle = application->inputApplicationHandle;
Jeff Brown519e0242010-09-15 15:18:56 -07003446 }
3447 if (window) {
Jeff Brown928e0542011-01-10 11:17:36 -08003448 commandEntry->inputWindowHandle = window->inputWindowHandle;
Jeff Brown519e0242010-09-15 15:18:56 -07003449 commandEntry->inputChannel = window->inputChannel;
3450 }
3451}
3452
Jeff Brownb88102f2010-09-08 11:49:43 -07003453void InputDispatcher::doNotifyConfigurationChangedInterruptible(
3454 CommandEntry* commandEntry) {
3455 mLock.unlock();
3456
3457 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
3458
3459 mLock.lock();
3460}
3461
Jeff Brown9c3cda02010-06-15 01:31:58 -07003462void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(
3463 CommandEntry* commandEntry) {
Jeff Brown7fbdc842010-06-17 20:52:56 -07003464 sp<Connection> connection = commandEntry->connection;
Jeff Brown9c3cda02010-06-15 01:31:58 -07003465
Jeff Brown7fbdc842010-06-17 20:52:56 -07003466 if (connection->status != Connection::STATUS_ZOMBIE) {
3467 mLock.unlock();
Jeff Brown9c3cda02010-06-15 01:31:58 -07003468
Jeff Brown928e0542011-01-10 11:17:36 -08003469 mPolicy->notifyInputChannelBroken(connection->inputWindowHandle);
Jeff Brown7fbdc842010-06-17 20:52:56 -07003470
3471 mLock.lock();
3472 }
Jeff Brown9c3cda02010-06-15 01:31:58 -07003473}
3474
Jeff Brown519e0242010-09-15 15:18:56 -07003475void InputDispatcher::doNotifyANRLockedInterruptible(
Jeff Brown9c3cda02010-06-15 01:31:58 -07003476 CommandEntry* commandEntry) {
Jeff Brown519e0242010-09-15 15:18:56 -07003477 mLock.unlock();
Jeff Brown9c3cda02010-06-15 01:31:58 -07003478
Jeff Brown519e0242010-09-15 15:18:56 -07003479 nsecs_t newTimeout = mPolicy->notifyANR(
Jeff Brown928e0542011-01-10 11:17:36 -08003480 commandEntry->inputApplicationHandle, commandEntry->inputWindowHandle);
Jeff Brown9c3cda02010-06-15 01:31:58 -07003481
Jeff Brown519e0242010-09-15 15:18:56 -07003482 mLock.lock();
Jeff Brown7fbdc842010-06-17 20:52:56 -07003483
Jeff Brown519e0242010-09-15 15:18:56 -07003484 resumeAfterTargetsNotReadyTimeoutLocked(newTimeout, commandEntry->inputChannel);
Jeff Brown9c3cda02010-06-15 01:31:58 -07003485}
3486
Jeff Brownb88102f2010-09-08 11:49:43 -07003487void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
3488 CommandEntry* commandEntry) {
3489 KeyEntry* entry = commandEntry->keyEntry;
Jeff Brown1f245102010-11-18 20:53:46 -08003490
3491 KeyEvent event;
3492 initializeKeyEvent(&event, entry);
Jeff Brownb88102f2010-09-08 11:49:43 -07003493
3494 mLock.unlock();
3495
Jeff Brown928e0542011-01-10 11:17:36 -08003496 bool consumed = mPolicy->interceptKeyBeforeDispatching(commandEntry->inputWindowHandle,
Jeff Brown1f245102010-11-18 20:53:46 -08003497 &event, entry->policyFlags);
Jeff Brownb88102f2010-09-08 11:49:43 -07003498
3499 mLock.lock();
3500
3501 entry->interceptKeyResult = consumed
3502 ? KeyEntry::INTERCEPT_KEY_RESULT_SKIP
3503 : KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
3504 mAllocator.releaseKeyEntry(entry);
3505}
3506
Jeff Brown3915bb82010-11-05 15:02:16 -07003507void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(
3508 CommandEntry* commandEntry) {
3509 sp<Connection> connection = commandEntry->connection;
3510 bool handled = commandEntry->handled;
3511
Jeff Brown49ed71d2010-12-06 17:13:33 -08003512 if (!connection->outboundQueue.isEmpty()) {
Jeff Brown3915bb82010-11-05 15:02:16 -07003513 DispatchEntry* dispatchEntry = connection->outboundQueue.headSentinel.next;
3514 if (dispatchEntry->inProgress
Jeff Brown3915bb82010-11-05 15:02:16 -07003515 && dispatchEntry->eventEntry->type == EventEntry::TYPE_KEY) {
3516 KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry);
Jeff Brown49ed71d2010-12-06 17:13:33 -08003517 if (!(keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK)) {
Jeff Brownda3d5a92011-03-29 15:11:34 -07003518 // Get the fallback key state.
3519 // Clear it out after dispatching the UP.
3520 int32_t originalKeyCode = keyEntry->keyCode;
3521 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
3522 if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
3523 connection->inputState.removeFallbackKey(originalKeyCode);
3524 }
3525
3526 if (handled || !dispatchEntry->hasForegroundTarget()) {
3527 // If the application handles the original key for which we previously
3528 // generated a fallback or if the window is not a foreground window,
3529 // then cancel the associated fallback key, if any.
3530 if (fallbackKeyCode != -1) {
3531 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
3532 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
3533 "application handled the original non-fallback key "
3534 "or is no longer a foreground target, "
3535 "canceling previously dispatched fallback key");
3536 options.keyCode = fallbackKeyCode;
3537 synthesizeCancelationEventsForConnectionLocked(connection, options);
3538 }
3539 connection->inputState.removeFallbackKey(originalKeyCode);
3540 }
Jeff Brown49ed71d2010-12-06 17:13:33 -08003541 } else {
Jeff Brownbfaf3b92011-02-22 15:00:50 -08003542 // If the application did not handle a non-fallback key, first check
Jeff Brownda3d5a92011-03-29 15:11:34 -07003543 // that we are in a good state to perform unhandled key event processing
3544 // Then ask the policy what to do with it.
3545 bool initialDown = keyEntry->action == AKEY_EVENT_ACTION_DOWN
3546 && keyEntry->repeatCount == 0;
3547 if (fallbackKeyCode == -1 && !initialDown) {
Jeff Brownbfaf3b92011-02-22 15:00:50 -08003548#if DEBUG_OUTBOUND_EVENT_DETAILS
Jeff Brownda3d5a92011-03-29 15:11:34 -07003549 LOGD("Unhandled key event: Skipping unhandled key event processing "
3550 "since this is not an initial down. "
3551 "keyCode=%d, action=%d, repeatCount=%d",
3552 originalKeyCode, keyEntry->action, keyEntry->repeatCount);
Jeff Brownbfaf3b92011-02-22 15:00:50 -08003553#endif
Jeff Brownda3d5a92011-03-29 15:11:34 -07003554 goto SkipFallback;
Jeff Brownbfaf3b92011-02-22 15:00:50 -08003555 }
3556
Jeff Brownda3d5a92011-03-29 15:11:34 -07003557 // Dispatch the unhandled key to the policy.
Jeff Brownbfaf3b92011-02-22 15:00:50 -08003558#if DEBUG_OUTBOUND_EVENT_DETAILS
3559 LOGD("Unhandled key event: Asking policy to perform fallback action. "
3560 "keyCode=%d, action=%d, repeatCount=%d",
3561 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount);
3562#endif
Jeff Brown49ed71d2010-12-06 17:13:33 -08003563 KeyEvent event;
3564 initializeKeyEvent(&event, keyEntry);
Jeff Brown3915bb82010-11-05 15:02:16 -07003565
Jeff Brown49ed71d2010-12-06 17:13:33 -08003566 mLock.unlock();
Jeff Brown3915bb82010-11-05 15:02:16 -07003567
Jeff Brown928e0542011-01-10 11:17:36 -08003568 bool fallback = mPolicy->dispatchUnhandledKey(connection->inputWindowHandle,
Jeff Brown49ed71d2010-12-06 17:13:33 -08003569 &event, keyEntry->policyFlags, &event);
Jeff Brown3915bb82010-11-05 15:02:16 -07003570
Jeff Brown49ed71d2010-12-06 17:13:33 -08003571 mLock.lock();
3572
Jeff Brown00045a72010-12-09 18:10:30 -08003573 if (connection->status != Connection::STATUS_NORMAL) {
Jeff Brownda3d5a92011-03-29 15:11:34 -07003574 connection->inputState.removeFallbackKey(originalKeyCode);
Jeff Brown00045a72010-12-09 18:10:30 -08003575 return;
3576 }
3577
Jeff Brownb6110c22011-04-01 16:15:13 -07003578 LOG_ASSERT(connection->outboundQueue.headSentinel.next == dispatchEntry);
Jeff Brown00045a72010-12-09 18:10:30 -08003579
Jeff Brownda3d5a92011-03-29 15:11:34 -07003580 // Latch the fallback keycode for this key on an initial down.
3581 // The fallback keycode cannot change at any other point in the lifecycle.
3582 if (initialDown) {
3583 if (fallback) {
3584 fallbackKeyCode = event.getKeyCode();
3585 } else {
3586 fallbackKeyCode = AKEYCODE_UNKNOWN;
3587 }
3588 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
3589 }
3590
Jeff Brownb6110c22011-04-01 16:15:13 -07003591 LOG_ASSERT(fallbackKeyCode != -1);
Jeff Brownda3d5a92011-03-29 15:11:34 -07003592
3593 // Cancel the fallback key if the policy decides not to send it anymore.
3594 // We will continue to dispatch the key to the policy but we will no
3595 // longer dispatch a fallback key to the application.
3596 if (fallbackKeyCode != AKEYCODE_UNKNOWN
3597 && (!fallback || fallbackKeyCode != event.getKeyCode())) {
3598#if DEBUG_OUTBOUND_EVENT_DETAILS
3599 if (fallback) {
3600 LOGD("Unhandled key event: Policy requested to send key %d"
3601 "as a fallback for %d, but on the DOWN it had requested "
3602 "to send %d instead. Fallback canceled.",
3603 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
3604 } else {
3605 LOGD("Unhandled key event: Policy did not request fallback for %d,"
3606 "but on the DOWN it had requested to send %d. "
3607 "Fallback canceled.",
3608 originalKeyCode, fallbackKeyCode);
3609 }
3610#endif
3611
3612 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
3613 "canceling fallback, policy no longer desires it");
3614 options.keyCode = fallbackKeyCode;
3615 synthesizeCancelationEventsForConnectionLocked(connection, options);
3616
3617 fallback = false;
3618 fallbackKeyCode = AKEYCODE_UNKNOWN;
3619 if (keyEntry->action != AKEY_EVENT_ACTION_UP) {
3620 connection->inputState.setFallbackKey(originalKeyCode,
3621 fallbackKeyCode);
3622 }
3623 }
3624
3625#if DEBUG_OUTBOUND_EVENT_DETAILS
3626 {
3627 String8 msg;
3628 const KeyedVector<int32_t, int32_t>& fallbackKeys =
3629 connection->inputState.getFallbackKeys();
3630 for (size_t i = 0; i < fallbackKeys.size(); i++) {
3631 msg.appendFormat(", %d->%d", fallbackKeys.keyAt(i),
3632 fallbackKeys.valueAt(i));
3633 }
3634 LOGD("Unhandled key event: %d currently tracked fallback keys%s.",
3635 fallbackKeys.size(), msg.string());
3636 }
3637#endif
3638
Jeff Brown49ed71d2010-12-06 17:13:33 -08003639 if (fallback) {
3640 // Restart the dispatch cycle using the fallback key.
3641 keyEntry->eventTime = event.getEventTime();
3642 keyEntry->deviceId = event.getDeviceId();
3643 keyEntry->source = event.getSource();
3644 keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
Jeff Brownda3d5a92011-03-29 15:11:34 -07003645 keyEntry->keyCode = fallbackKeyCode;
Jeff Brown49ed71d2010-12-06 17:13:33 -08003646 keyEntry->scanCode = event.getScanCode();
3647 keyEntry->metaState = event.getMetaState();
3648 keyEntry->repeatCount = event.getRepeatCount();
3649 keyEntry->downTime = event.getDownTime();
3650 keyEntry->syntheticRepeat = false;
3651
Jeff Brownbfaf3b92011-02-22 15:00:50 -08003652#if DEBUG_OUTBOUND_EVENT_DETAILS
3653 LOGD("Unhandled key event: Dispatching fallback key. "
Jeff Brownda3d5a92011-03-29 15:11:34 -07003654 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
3655 originalKeyCode, fallbackKeyCode, keyEntry->metaState);
Jeff Brownbfaf3b92011-02-22 15:00:50 -08003656#endif
3657
Jeff Brown49ed71d2010-12-06 17:13:33 -08003658 dispatchEntry->inProgress = false;
3659 startDispatchCycleLocked(now(), connection);
3660 return;
Jeff Brownda3d5a92011-03-29 15:11:34 -07003661 } else {
3662#if DEBUG_OUTBOUND_EVENT_DETAILS
3663 LOGD("Unhandled key event: No fallback key.");
3664#endif
Jeff Brown49ed71d2010-12-06 17:13:33 -08003665 }
3666 }
3667 }
Jeff Brown3915bb82010-11-05 15:02:16 -07003668 }
3669 }
3670
Jeff Brownbfaf3b92011-02-22 15:00:50 -08003671SkipFallback:
Jeff Brown3915bb82010-11-05 15:02:16 -07003672 startNextDispatchCycleLocked(now(), connection);
3673}
3674
Jeff Brownb88102f2010-09-08 11:49:43 -07003675void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
3676 mLock.unlock();
3677
Jeff Brown01ce2e92010-09-26 22:20:12 -07003678 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
Jeff Brownb88102f2010-09-08 11:49:43 -07003679
3680 mLock.lock();
3681}
3682
Jeff Brown3915bb82010-11-05 15:02:16 -07003683void InputDispatcher::initializeKeyEvent(KeyEvent* event, const KeyEntry* entry) {
3684 event->initialize(entry->deviceId, entry->source, entry->action, entry->flags,
3685 entry->keyCode, entry->scanCode, entry->metaState, entry->repeatCount,
3686 entry->downTime, entry->eventTime);
3687}
3688
Jeff Brown519e0242010-09-15 15:18:56 -07003689void InputDispatcher::updateDispatchStatisticsLocked(nsecs_t currentTime, const EventEntry* entry,
3690 int32_t injectionResult, nsecs_t timeSpentWaitingForApplication) {
3691 // TODO Write some statistics about how long we spend waiting.
Jeff Brownb88102f2010-09-08 11:49:43 -07003692}
3693
3694void InputDispatcher::dump(String8& dump) {
Jeff Brownf2f487182010-10-01 17:46:21 -07003695 dump.append("Input Dispatcher State:\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003696 dumpDispatchStateLocked(dump);
3697}
3698
Jeff Brown9c3cda02010-06-15 01:31:58 -07003699
Jeff Brown519e0242010-09-15 15:18:56 -07003700// --- InputDispatcher::Queue ---
3701
3702template <typename T>
3703uint32_t InputDispatcher::Queue<T>::count() const {
3704 uint32_t result = 0;
3705 for (const T* entry = headSentinel.next; entry != & tailSentinel; entry = entry->next) {
3706 result += 1;
3707 }
3708 return result;
3709}
3710
3711
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003712// --- InputDispatcher::Allocator ---
3713
3714InputDispatcher::Allocator::Allocator() {
3715}
3716
Jeff Brown01ce2e92010-09-26 22:20:12 -07003717InputDispatcher::InjectionState*
3718InputDispatcher::Allocator::obtainInjectionState(int32_t injectorPid, int32_t injectorUid) {
3719 InjectionState* injectionState = mInjectionStatePool.alloc();
3720 injectionState->refCount = 1;
3721 injectionState->injectorPid = injectorPid;
3722 injectionState->injectorUid = injectorUid;
3723 injectionState->injectionIsAsync = false;
3724 injectionState->injectionResult = INPUT_EVENT_INJECTION_PENDING;
3725 injectionState->pendingForegroundDispatches = 0;
3726 return injectionState;
3727}
3728
Jeff Brown7fbdc842010-06-17 20:52:56 -07003729void InputDispatcher::Allocator::initializeEventEntry(EventEntry* entry, int32_t type,
Jeff Brownb6997262010-10-08 22:31:17 -07003730 nsecs_t eventTime, uint32_t policyFlags) {
Jeff Brown7fbdc842010-06-17 20:52:56 -07003731 entry->type = type;
3732 entry->refCount = 1;
3733 entry->dispatchInProgress = false;
Christopher Tatee91a5db2010-06-23 16:50:30 -07003734 entry->eventTime = eventTime;
Jeff Brownb6997262010-10-08 22:31:17 -07003735 entry->policyFlags = policyFlags;
Jeff Brown01ce2e92010-09-26 22:20:12 -07003736 entry->injectionState = NULL;
3737}
3738
3739void InputDispatcher::Allocator::releaseEventEntryInjectionState(EventEntry* entry) {
3740 if (entry->injectionState) {
3741 releaseInjectionState(entry->injectionState);
3742 entry->injectionState = NULL;
3743 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07003744}
3745
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003746InputDispatcher::ConfigurationChangedEntry*
Jeff Brown7fbdc842010-06-17 20:52:56 -07003747InputDispatcher::Allocator::obtainConfigurationChangedEntry(nsecs_t eventTime) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003748 ConfigurationChangedEntry* entry = mConfigurationChangeEntryPool.alloc();
Jeff Brownb6997262010-10-08 22:31:17 -07003749 initializeEventEntry(entry, EventEntry::TYPE_CONFIGURATION_CHANGED, eventTime, 0);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003750 return entry;
3751}
3752
Jeff Brown7fbdc842010-06-17 20:52:56 -07003753InputDispatcher::KeyEntry* InputDispatcher::Allocator::obtainKeyEntry(nsecs_t eventTime,
Jeff Brown58a2da82011-01-25 16:02:22 -08003754 int32_t deviceId, uint32_t source, uint32_t policyFlags, int32_t action,
Jeff Brown7fbdc842010-06-17 20:52:56 -07003755 int32_t flags, int32_t keyCode, int32_t scanCode, int32_t metaState,
3756 int32_t repeatCount, nsecs_t downTime) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003757 KeyEntry* entry = mKeyEntryPool.alloc();
Jeff Brownb6997262010-10-08 22:31:17 -07003758 initializeEventEntry(entry, EventEntry::TYPE_KEY, eventTime, policyFlags);
Jeff Brown7fbdc842010-06-17 20:52:56 -07003759
3760 entry->deviceId = deviceId;
Jeff Brownc5ed5912010-07-14 18:48:53 -07003761 entry->source = source;
Jeff Brown7fbdc842010-06-17 20:52:56 -07003762 entry->action = action;
3763 entry->flags = flags;
3764 entry->keyCode = keyCode;
3765 entry->scanCode = scanCode;
3766 entry->metaState = metaState;
3767 entry->repeatCount = repeatCount;
3768 entry->downTime = downTime;
Jeff Brownb88102f2010-09-08 11:49:43 -07003769 entry->syntheticRepeat = false;
3770 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003771 return entry;
3772}
3773
Jeff Brown7fbdc842010-06-17 20:52:56 -07003774InputDispatcher::MotionEntry* InputDispatcher::Allocator::obtainMotionEntry(nsecs_t eventTime,
Jeff Brown58a2da82011-01-25 16:02:22 -08003775 int32_t deviceId, uint32_t source, uint32_t policyFlags, int32_t action, int32_t flags,
Jeff Brown7fbdc842010-06-17 20:52:56 -07003776 int32_t metaState, int32_t edgeFlags, float xPrecision, float yPrecision,
3777 nsecs_t downTime, uint32_t pointerCount,
3778 const int32_t* pointerIds, const PointerCoords* pointerCoords) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003779 MotionEntry* entry = mMotionEntryPool.alloc();
Jeff Brownb6997262010-10-08 22:31:17 -07003780 initializeEventEntry(entry, EventEntry::TYPE_MOTION, eventTime, policyFlags);
Jeff Brown7fbdc842010-06-17 20:52:56 -07003781
3782 entry->eventTime = eventTime;
3783 entry->deviceId = deviceId;
Jeff Brownc5ed5912010-07-14 18:48:53 -07003784 entry->source = source;
Jeff Brown7fbdc842010-06-17 20:52:56 -07003785 entry->action = action;
Jeff Brown85a31762010-09-01 17:01:00 -07003786 entry->flags = flags;
Jeff Brown7fbdc842010-06-17 20:52:56 -07003787 entry->metaState = metaState;
3788 entry->edgeFlags = edgeFlags;
3789 entry->xPrecision = xPrecision;
3790 entry->yPrecision = yPrecision;
3791 entry->downTime = downTime;
3792 entry->pointerCount = pointerCount;
3793 entry->firstSample.eventTime = eventTime;
Jeff Brown4e91a182011-04-07 11:38:09 -07003794 entry->firstSample.eventTimeBeforeCoalescing = eventTime;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003795 entry->firstSample.next = NULL;
Jeff Brown7fbdc842010-06-17 20:52:56 -07003796 entry->lastSample = & entry->firstSample;
3797 for (uint32_t i = 0; i < pointerCount; i++) {
3798 entry->pointerIds[i] = pointerIds[i];
Jeff Brownace13b12011-03-09 17:39:48 -08003799 entry->firstSample.pointerCoords[i].copyFrom(pointerCoords[i]);
Jeff Brown7fbdc842010-06-17 20:52:56 -07003800 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003801 return entry;
3802}
3803
3804InputDispatcher::DispatchEntry* InputDispatcher::Allocator::obtainDispatchEntry(
Jeff Brownb88102f2010-09-08 11:49:43 -07003805 EventEntry* eventEntry,
Jeff Brown519e0242010-09-15 15:18:56 -07003806 int32_t targetFlags, float xOffset, float yOffset) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003807 DispatchEntry* entry = mDispatchEntryPool.alloc();
3808 entry->eventEntry = eventEntry;
3809 eventEntry->refCount += 1;
Jeff Brownb88102f2010-09-08 11:49:43 -07003810 entry->targetFlags = targetFlags;
3811 entry->xOffset = xOffset;
3812 entry->yOffset = yOffset;
Jeff Brownb88102f2010-09-08 11:49:43 -07003813 entry->inProgress = false;
3814 entry->headMotionSample = NULL;
3815 entry->tailMotionSample = NULL;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003816 return entry;
3817}
3818
Jeff Brown9c3cda02010-06-15 01:31:58 -07003819InputDispatcher::CommandEntry* InputDispatcher::Allocator::obtainCommandEntry(Command command) {
3820 CommandEntry* entry = mCommandEntryPool.alloc();
3821 entry->command = command;
3822 return entry;
3823}
3824
Jeff Brown01ce2e92010-09-26 22:20:12 -07003825void InputDispatcher::Allocator::releaseInjectionState(InjectionState* injectionState) {
3826 injectionState->refCount -= 1;
3827 if (injectionState->refCount == 0) {
3828 mInjectionStatePool.free(injectionState);
3829 } else {
Jeff Brownb6110c22011-04-01 16:15:13 -07003830 LOG_ASSERT(injectionState->refCount > 0);
Jeff Brown01ce2e92010-09-26 22:20:12 -07003831 }
3832}
3833
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003834void InputDispatcher::Allocator::releaseEventEntry(EventEntry* entry) {
3835 switch (entry->type) {
3836 case EventEntry::TYPE_CONFIGURATION_CHANGED:
3837 releaseConfigurationChangedEntry(static_cast<ConfigurationChangedEntry*>(entry));
3838 break;
3839 case EventEntry::TYPE_KEY:
3840 releaseKeyEntry(static_cast<KeyEntry*>(entry));
3841 break;
3842 case EventEntry::TYPE_MOTION:
3843 releaseMotionEntry(static_cast<MotionEntry*>(entry));
3844 break;
3845 default:
Jeff Brownb6110c22011-04-01 16:15:13 -07003846 LOG_ASSERT(false);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003847 break;
3848 }
3849}
3850
3851void InputDispatcher::Allocator::releaseConfigurationChangedEntry(
3852 ConfigurationChangedEntry* entry) {
3853 entry->refCount -= 1;
3854 if (entry->refCount == 0) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07003855 releaseEventEntryInjectionState(entry);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003856 mConfigurationChangeEntryPool.free(entry);
3857 } else {
Jeff Brownb6110c22011-04-01 16:15:13 -07003858 LOG_ASSERT(entry->refCount > 0);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003859 }
3860}
3861
3862void InputDispatcher::Allocator::releaseKeyEntry(KeyEntry* entry) {
3863 entry->refCount -= 1;
3864 if (entry->refCount == 0) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07003865 releaseEventEntryInjectionState(entry);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003866 mKeyEntryPool.free(entry);
3867 } else {
Jeff Brownb6110c22011-04-01 16:15:13 -07003868 LOG_ASSERT(entry->refCount > 0);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003869 }
3870}
3871
3872void InputDispatcher::Allocator::releaseMotionEntry(MotionEntry* entry) {
3873 entry->refCount -= 1;
3874 if (entry->refCount == 0) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07003875 releaseEventEntryInjectionState(entry);
Jeff Brown9c3cda02010-06-15 01:31:58 -07003876 for (MotionSample* sample = entry->firstSample.next; sample != NULL; ) {
3877 MotionSample* next = sample->next;
3878 mMotionSamplePool.free(sample);
3879 sample = next;
3880 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003881 mMotionEntryPool.free(entry);
3882 } else {
Jeff Brownb6110c22011-04-01 16:15:13 -07003883 LOG_ASSERT(entry->refCount > 0);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003884 }
3885}
3886
Jeff Browna032cc02011-03-07 16:56:21 -08003887void InputDispatcher::Allocator::freeMotionSample(MotionSample* sample) {
3888 mMotionSamplePool.free(sample);
3889}
3890
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003891void InputDispatcher::Allocator::releaseDispatchEntry(DispatchEntry* entry) {
3892 releaseEventEntry(entry->eventEntry);
3893 mDispatchEntryPool.free(entry);
3894}
3895
Jeff Brown9c3cda02010-06-15 01:31:58 -07003896void InputDispatcher::Allocator::releaseCommandEntry(CommandEntry* entry) {
3897 mCommandEntryPool.free(entry);
3898}
3899
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003900void InputDispatcher::Allocator::appendMotionSample(MotionEntry* motionEntry,
Jeff Brown7fbdc842010-06-17 20:52:56 -07003901 nsecs_t eventTime, const PointerCoords* pointerCoords) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003902 MotionSample* sample = mMotionSamplePool.alloc();
3903 sample->eventTime = eventTime;
Jeff Brown4e91a182011-04-07 11:38:09 -07003904 sample->eventTimeBeforeCoalescing = eventTime;
Jeff Brown7fbdc842010-06-17 20:52:56 -07003905 uint32_t pointerCount = motionEntry->pointerCount;
3906 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brownace13b12011-03-09 17:39:48 -08003907 sample->pointerCoords[i].copyFrom(pointerCoords[i]);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003908 }
3909
3910 sample->next = NULL;
3911 motionEntry->lastSample->next = sample;
3912 motionEntry->lastSample = sample;
3913}
3914
Jeff Brown01ce2e92010-09-26 22:20:12 -07003915void InputDispatcher::Allocator::recycleKeyEntry(KeyEntry* keyEntry) {
3916 releaseEventEntryInjectionState(keyEntry);
Jeff Brownb88102f2010-09-08 11:49:43 -07003917
Jeff Brown01ce2e92010-09-26 22:20:12 -07003918 keyEntry->dispatchInProgress = false;
3919 keyEntry->syntheticRepeat = false;
3920 keyEntry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
Jeff Brownb88102f2010-09-08 11:49:43 -07003921}
3922
3923
Jeff Brownae9fc032010-08-18 15:51:08 -07003924// --- InputDispatcher::MotionEntry ---
3925
3926uint32_t InputDispatcher::MotionEntry::countSamples() const {
3927 uint32_t count = 1;
3928 for (MotionSample* sample = firstSample.next; sample != NULL; sample = sample->next) {
3929 count += 1;
3930 }
3931 return count;
3932}
3933
Jeff Brown4e91a182011-04-07 11:38:09 -07003934bool InputDispatcher::MotionEntry::canAppendSamples(int32_t action, uint32_t pointerCount,
3935 const int32_t* pointerIds) const {
3936 if (this->action != action
3937 || this->pointerCount != pointerCount
3938 || this->isInjected()) {
3939 return false;
3940 }
3941 for (uint32_t i = 0; i < pointerCount; i++) {
3942 if (this->pointerIds[i] != pointerIds[i]) {
3943 return false;
3944 }
3945 }
3946 return true;
3947}
3948
Jeff Brownb88102f2010-09-08 11:49:43 -07003949
3950// --- InputDispatcher::InputState ---
3951
Jeff Brownb6997262010-10-08 22:31:17 -07003952InputDispatcher::InputState::InputState() {
Jeff Brownb88102f2010-09-08 11:49:43 -07003953}
3954
3955InputDispatcher::InputState::~InputState() {
3956}
3957
3958bool InputDispatcher::InputState::isNeutral() const {
3959 return mKeyMementos.isEmpty() && mMotionMementos.isEmpty();
3960}
3961
Jeff Browna032cc02011-03-07 16:56:21 -08003962void InputDispatcher::InputState::trackEvent(const EventEntry* entry, int32_t action) {
Jeff Brownb88102f2010-09-08 11:49:43 -07003963 switch (entry->type) {
3964 case EventEntry::TYPE_KEY:
Jeff Browna032cc02011-03-07 16:56:21 -08003965 trackKey(static_cast<const KeyEntry*>(entry), action);
Jeff Browncc0c1592011-02-19 05:07:28 -08003966 break;
Jeff Brownb88102f2010-09-08 11:49:43 -07003967
3968 case EventEntry::TYPE_MOTION:
Jeff Browna032cc02011-03-07 16:56:21 -08003969 trackMotion(static_cast<const MotionEntry*>(entry), action);
Jeff Browncc0c1592011-02-19 05:07:28 -08003970 break;
Jeff Brownb88102f2010-09-08 11:49:43 -07003971 }
3972}
3973
Jeff Browna032cc02011-03-07 16:56:21 -08003974void InputDispatcher::InputState::trackKey(const KeyEntry* entry, int32_t action) {
Jeff Brownda3d5a92011-03-29 15:11:34 -07003975 if (action == AKEY_EVENT_ACTION_UP
3976 && (entry->flags & AKEY_EVENT_FLAG_FALLBACK)) {
3977 for (size_t i = 0; i < mFallbackKeys.size(); ) {
3978 if (mFallbackKeys.valueAt(i) == entry->keyCode) {
3979 mFallbackKeys.removeItemsAt(i);
3980 } else {
3981 i += 1;
3982 }
3983 }
3984 }
3985
Jeff Brownb88102f2010-09-08 11:49:43 -07003986 for (size_t i = 0; i < mKeyMementos.size(); i++) {
3987 KeyMemento& memento = mKeyMementos.editItemAt(i);
3988 if (memento.deviceId == entry->deviceId
3989 && memento.source == entry->source
3990 && memento.keyCode == entry->keyCode
3991 && memento.scanCode == entry->scanCode) {
3992 switch (action) {
3993 case AKEY_EVENT_ACTION_UP:
3994 mKeyMementos.removeAt(i);
Jeff Browncc0c1592011-02-19 05:07:28 -08003995 return;
Jeff Brownb88102f2010-09-08 11:49:43 -07003996
3997 case AKEY_EVENT_ACTION_DOWN:
Jeff Browncc0c1592011-02-19 05:07:28 -08003998 mKeyMementos.removeAt(i);
3999 goto Found;
Jeff Brownb88102f2010-09-08 11:49:43 -07004000
4001 default:
Jeff Browncc0c1592011-02-19 05:07:28 -08004002 return;
Jeff Brownb88102f2010-09-08 11:49:43 -07004003 }
4004 }
4005 }
4006
Jeff Browncc0c1592011-02-19 05:07:28 -08004007Found:
4008 if (action == AKEY_EVENT_ACTION_DOWN) {
Jeff Brownb88102f2010-09-08 11:49:43 -07004009 mKeyMementos.push();
4010 KeyMemento& memento = mKeyMementos.editTop();
4011 memento.deviceId = entry->deviceId;
4012 memento.source = entry->source;
4013 memento.keyCode = entry->keyCode;
4014 memento.scanCode = entry->scanCode;
Jeff Brown49ed71d2010-12-06 17:13:33 -08004015 memento.flags = entry->flags;
Jeff Brownb88102f2010-09-08 11:49:43 -07004016 memento.downTime = entry->downTime;
Jeff Brownb88102f2010-09-08 11:49:43 -07004017 }
4018}
4019
Jeff Browna032cc02011-03-07 16:56:21 -08004020void InputDispatcher::InputState::trackMotion(const MotionEntry* entry, int32_t action) {
4021 int32_t actionMasked = action & AMOTION_EVENT_ACTION_MASK;
Jeff Brownb88102f2010-09-08 11:49:43 -07004022 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4023 MotionMemento& memento = mMotionMementos.editItemAt(i);
4024 if (memento.deviceId == entry->deviceId
4025 && memento.source == entry->source) {
Jeff Browna032cc02011-03-07 16:56:21 -08004026 switch (actionMasked) {
Jeff Brownb88102f2010-09-08 11:49:43 -07004027 case AMOTION_EVENT_ACTION_UP:
4028 case AMOTION_EVENT_ACTION_CANCEL:
Jeff Browna032cc02011-03-07 16:56:21 -08004029 case AMOTION_EVENT_ACTION_HOVER_ENTER:
Jeff Browncc0c1592011-02-19 05:07:28 -08004030 case AMOTION_EVENT_ACTION_HOVER_MOVE:
Jeff Browna032cc02011-03-07 16:56:21 -08004031 case AMOTION_EVENT_ACTION_HOVER_EXIT:
Jeff Brownb88102f2010-09-08 11:49:43 -07004032 mMotionMementos.removeAt(i);
Jeff Browncc0c1592011-02-19 05:07:28 -08004033 return;
Jeff Brownb88102f2010-09-08 11:49:43 -07004034
4035 case AMOTION_EVENT_ACTION_DOWN:
Jeff Browncc0c1592011-02-19 05:07:28 -08004036 mMotionMementos.removeAt(i);
4037 goto Found;
Jeff Brownb88102f2010-09-08 11:49:43 -07004038
4039 case AMOTION_EVENT_ACTION_POINTER_UP:
Jeff Browncc0c1592011-02-19 05:07:28 -08004040 case AMOTION_EVENT_ACTION_POINTER_DOWN:
Jeff Brownb88102f2010-09-08 11:49:43 -07004041 case AMOTION_EVENT_ACTION_MOVE:
Jeff Browncc0c1592011-02-19 05:07:28 -08004042 memento.setPointers(entry);
4043 return;
Jeff Brownb88102f2010-09-08 11:49:43 -07004044
4045 default:
Jeff Browncc0c1592011-02-19 05:07:28 -08004046 return;
Jeff Brownb88102f2010-09-08 11:49:43 -07004047 }
4048 }
4049 }
4050
Jeff Browncc0c1592011-02-19 05:07:28 -08004051Found:
Jeff Browna032cc02011-03-07 16:56:21 -08004052 switch (actionMasked) {
4053 case AMOTION_EVENT_ACTION_DOWN:
4054 case AMOTION_EVENT_ACTION_HOVER_ENTER:
4055 case AMOTION_EVENT_ACTION_HOVER_MOVE:
4056 case AMOTION_EVENT_ACTION_HOVER_EXIT:
Jeff Brownb88102f2010-09-08 11:49:43 -07004057 mMotionMementos.push();
4058 MotionMemento& memento = mMotionMementos.editTop();
4059 memento.deviceId = entry->deviceId;
4060 memento.source = entry->source;
4061 memento.xPrecision = entry->xPrecision;
4062 memento.yPrecision = entry->yPrecision;
4063 memento.downTime = entry->downTime;
4064 memento.setPointers(entry);
Jeff Browna032cc02011-03-07 16:56:21 -08004065 memento.hovering = actionMasked != AMOTION_EVENT_ACTION_DOWN;
Jeff Brownb88102f2010-09-08 11:49:43 -07004066 }
4067}
4068
4069void InputDispatcher::InputState::MotionMemento::setPointers(const MotionEntry* entry) {
4070 pointerCount = entry->pointerCount;
4071 for (uint32_t i = 0; i < entry->pointerCount; i++) {
4072 pointerIds[i] = entry->pointerIds[i];
Jeff Brownace13b12011-03-09 17:39:48 -08004073 pointerCoords[i].copyFrom(entry->lastSample->pointerCoords[i]);
Jeff Brownb88102f2010-09-08 11:49:43 -07004074 }
4075}
4076
Jeff Brownb6997262010-10-08 22:31:17 -07004077void InputDispatcher::InputState::synthesizeCancelationEvents(nsecs_t currentTime,
4078 Allocator* allocator, Vector<EventEntry*>& outEvents,
Jeff Brownda3d5a92011-03-29 15:11:34 -07004079 const CancelationOptions& options) {
Jeff Brownb6997262010-10-08 22:31:17 -07004080 for (size_t i = 0; i < mKeyMementos.size(); ) {
Jeff Brownb88102f2010-09-08 11:49:43 -07004081 const KeyMemento& memento = mKeyMementos.itemAt(i);
Jeff Brown49ed71d2010-12-06 17:13:33 -08004082 if (shouldCancelKey(memento, options)) {
Jeff Brownb6997262010-10-08 22:31:17 -07004083 outEvents.push(allocator->obtainKeyEntry(currentTime,
4084 memento.deviceId, memento.source, 0,
Jeff Brown49ed71d2010-12-06 17:13:33 -08004085 AKEY_EVENT_ACTION_UP, memento.flags | AKEY_EVENT_FLAG_CANCELED,
Jeff Brownb6997262010-10-08 22:31:17 -07004086 memento.keyCode, memento.scanCode, 0, 0, memento.downTime));
4087 mKeyMementos.removeAt(i);
4088 } else {
4089 i += 1;
4090 }
Jeff Brownb88102f2010-09-08 11:49:43 -07004091 }
4092
Jeff Browna1160a72010-10-11 18:22:53 -07004093 for (size_t i = 0; i < mMotionMementos.size(); ) {
Jeff Brownb88102f2010-09-08 11:49:43 -07004094 const MotionMemento& memento = mMotionMementos.itemAt(i);
Jeff Brown49ed71d2010-12-06 17:13:33 -08004095 if (shouldCancelMotion(memento, options)) {
Jeff Brownb6997262010-10-08 22:31:17 -07004096 outEvents.push(allocator->obtainMotionEntry(currentTime,
4097 memento.deviceId, memento.source, 0,
Jeff Browna032cc02011-03-07 16:56:21 -08004098 memento.hovering
4099 ? AMOTION_EVENT_ACTION_HOVER_EXIT
4100 : AMOTION_EVENT_ACTION_CANCEL,
4101 0, 0, 0,
Jeff Brownb6997262010-10-08 22:31:17 -07004102 memento.xPrecision, memento.yPrecision, memento.downTime,
4103 memento.pointerCount, memento.pointerIds, memento.pointerCoords));
4104 mMotionMementos.removeAt(i);
4105 } else {
4106 i += 1;
4107 }
Jeff Brownb88102f2010-09-08 11:49:43 -07004108 }
4109}
4110
4111void InputDispatcher::InputState::clear() {
4112 mKeyMementos.clear();
4113 mMotionMementos.clear();
Jeff Brownda3d5a92011-03-29 15:11:34 -07004114 mFallbackKeys.clear();
Jeff Brownb6997262010-10-08 22:31:17 -07004115}
4116
Jeff Brown9c9f1a32010-10-11 18:32:20 -07004117void InputDispatcher::InputState::copyPointerStateTo(InputState& other) const {
4118 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4119 const MotionMemento& memento = mMotionMementos.itemAt(i);
4120 if (memento.source & AINPUT_SOURCE_CLASS_POINTER) {
4121 for (size_t j = 0; j < other.mMotionMementos.size(); ) {
4122 const MotionMemento& otherMemento = other.mMotionMementos.itemAt(j);
4123 if (memento.deviceId == otherMemento.deviceId
4124 && memento.source == otherMemento.source) {
4125 other.mMotionMementos.removeAt(j);
4126 } else {
4127 j += 1;
4128 }
4129 }
4130 other.mMotionMementos.push(memento);
4131 }
4132 }
4133}
4134
Jeff Brownda3d5a92011-03-29 15:11:34 -07004135int32_t InputDispatcher::InputState::getFallbackKey(int32_t originalKeyCode) {
4136 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
4137 return index >= 0 ? mFallbackKeys.valueAt(index) : -1;
4138}
4139
4140void InputDispatcher::InputState::setFallbackKey(int32_t originalKeyCode,
4141 int32_t fallbackKeyCode) {
4142 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
4143 if (index >= 0) {
4144 mFallbackKeys.replaceValueAt(index, fallbackKeyCode);
4145 } else {
4146 mFallbackKeys.add(originalKeyCode, fallbackKeyCode);
4147 }
4148}
4149
4150void InputDispatcher::InputState::removeFallbackKey(int32_t originalKeyCode) {
4151 mFallbackKeys.removeItem(originalKeyCode);
4152}
4153
Jeff Brown49ed71d2010-12-06 17:13:33 -08004154bool InputDispatcher::InputState::shouldCancelKey(const KeyMemento& memento,
Jeff Brownda3d5a92011-03-29 15:11:34 -07004155 const CancelationOptions& options) {
4156 if (options.keyCode != -1 && memento.keyCode != options.keyCode) {
4157 return false;
4158 }
4159
4160 switch (options.mode) {
4161 case CancelationOptions::CANCEL_ALL_EVENTS:
4162 case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
Jeff Brownb6997262010-10-08 22:31:17 -07004163 return true;
Jeff Brownda3d5a92011-03-29 15:11:34 -07004164 case CancelationOptions::CANCEL_FALLBACK_EVENTS:
Jeff Brown49ed71d2010-12-06 17:13:33 -08004165 return memento.flags & AKEY_EVENT_FLAG_FALLBACK;
4166 default:
4167 return false;
4168 }
4169}
4170
4171bool InputDispatcher::InputState::shouldCancelMotion(const MotionMemento& memento,
Jeff Brownda3d5a92011-03-29 15:11:34 -07004172 const CancelationOptions& options) {
4173 switch (options.mode) {
4174 case CancelationOptions::CANCEL_ALL_EVENTS:
Jeff Brown49ed71d2010-12-06 17:13:33 -08004175 return true;
Jeff Brownda3d5a92011-03-29 15:11:34 -07004176 case CancelationOptions::CANCEL_POINTER_EVENTS:
Jeff Brown49ed71d2010-12-06 17:13:33 -08004177 return memento.source & AINPUT_SOURCE_CLASS_POINTER;
Jeff Brownda3d5a92011-03-29 15:11:34 -07004178 case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
Jeff Brown49ed71d2010-12-06 17:13:33 -08004179 return !(memento.source & AINPUT_SOURCE_CLASS_POINTER);
4180 default:
4181 return false;
Jeff Brownb6997262010-10-08 22:31:17 -07004182 }
Jeff Brownb88102f2010-09-08 11:49:43 -07004183}
4184
4185
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004186// --- InputDispatcher::Connection ---
4187
Jeff Brown928e0542011-01-10 11:17:36 -08004188InputDispatcher::Connection::Connection(const sp<InputChannel>& inputChannel,
4189 const sp<InputWindowHandle>& inputWindowHandle) :
4190 status(STATUS_NORMAL), inputChannel(inputChannel), inputWindowHandle(inputWindowHandle),
4191 inputPublisher(inputChannel),
Jeff Brownda3d5a92011-03-29 15:11:34 -07004192 lastEventTime(LONG_LONG_MAX), lastDispatchTime(LONG_LONG_MAX) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004193}
4194
4195InputDispatcher::Connection::~Connection() {
4196}
4197
4198status_t InputDispatcher::Connection::initialize() {
4199 return inputPublisher.initialize();
4200}
4201
Jeff Brown9c3cda02010-06-15 01:31:58 -07004202const char* InputDispatcher::Connection::getStatusLabel() const {
4203 switch (status) {
4204 case STATUS_NORMAL:
4205 return "NORMAL";
4206
4207 case STATUS_BROKEN:
4208 return "BROKEN";
4209
Jeff Brown9c3cda02010-06-15 01:31:58 -07004210 case STATUS_ZOMBIE:
4211 return "ZOMBIE";
4212
4213 default:
4214 return "UNKNOWN";
4215 }
4216}
4217
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004218InputDispatcher::DispatchEntry* InputDispatcher::Connection::findQueuedDispatchEntryForEvent(
4219 const EventEntry* eventEntry) const {
Jeff Brownb88102f2010-09-08 11:49:43 -07004220 for (DispatchEntry* dispatchEntry = outboundQueue.tailSentinel.prev;
4221 dispatchEntry != & outboundQueue.headSentinel; dispatchEntry = dispatchEntry->prev) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004222 if (dispatchEntry->eventEntry == eventEntry) {
4223 return dispatchEntry;
4224 }
4225 }
4226 return NULL;
4227}
4228
Jeff Brownb88102f2010-09-08 11:49:43 -07004229
Jeff Brown9c3cda02010-06-15 01:31:58 -07004230// --- InputDispatcher::CommandEntry ---
4231
Jeff Brownb88102f2010-09-08 11:49:43 -07004232InputDispatcher::CommandEntry::CommandEntry() :
4233 keyEntry(NULL) {
Jeff Brown9c3cda02010-06-15 01:31:58 -07004234}
4235
4236InputDispatcher::CommandEntry::~CommandEntry() {
4237}
4238
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004239
Jeff Brown01ce2e92010-09-26 22:20:12 -07004240// --- InputDispatcher::TouchState ---
4241
4242InputDispatcher::TouchState::TouchState() :
Jeff Brown58a2da82011-01-25 16:02:22 -08004243 down(false), split(false), deviceId(-1), source(0) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07004244}
4245
4246InputDispatcher::TouchState::~TouchState() {
4247}
4248
4249void InputDispatcher::TouchState::reset() {
4250 down = false;
4251 split = false;
Jeff Brown95712852011-01-04 19:41:59 -08004252 deviceId = -1;
Jeff Brown58a2da82011-01-25 16:02:22 -08004253 source = 0;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004254 windows.clear();
4255}
4256
4257void InputDispatcher::TouchState::copyFrom(const TouchState& other) {
4258 down = other.down;
4259 split = other.split;
Jeff Brown95712852011-01-04 19:41:59 -08004260 deviceId = other.deviceId;
Jeff Brown58a2da82011-01-25 16:02:22 -08004261 source = other.source;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004262 windows.clear();
4263 windows.appendVector(other.windows);
4264}
4265
4266void InputDispatcher::TouchState::addOrUpdateWindow(const InputWindow* window,
4267 int32_t targetFlags, BitSet32 pointerIds) {
4268 if (targetFlags & InputTarget::FLAG_SPLIT) {
4269 split = true;
4270 }
4271
4272 for (size_t i = 0; i < windows.size(); i++) {
4273 TouchedWindow& touchedWindow = windows.editItemAt(i);
4274 if (touchedWindow.window == window) {
4275 touchedWindow.targetFlags |= targetFlags;
4276 touchedWindow.pointerIds.value |= pointerIds.value;
4277 return;
4278 }
4279 }
4280
4281 windows.push();
4282
4283 TouchedWindow& touchedWindow = windows.editTop();
4284 touchedWindow.window = window;
4285 touchedWindow.targetFlags = targetFlags;
4286 touchedWindow.pointerIds = pointerIds;
4287 touchedWindow.channel = window->inputChannel;
4288}
4289
Jeff Browna032cc02011-03-07 16:56:21 -08004290void InputDispatcher::TouchState::filterNonAsIsTouchWindows() {
Jeff Brown01ce2e92010-09-26 22:20:12 -07004291 for (size_t i = 0 ; i < windows.size(); ) {
Jeff Browna032cc02011-03-07 16:56:21 -08004292 TouchedWindow& window = windows.editItemAt(i);
4293 if (window.targetFlags & InputTarget::FLAG_DISPATCH_AS_IS) {
4294 window.targetFlags &= ~InputTarget::FLAG_DISPATCH_MASK;
4295 window.targetFlags |= InputTarget::FLAG_DISPATCH_AS_IS;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004296 i += 1;
Jeff Browna032cc02011-03-07 16:56:21 -08004297 } else {
4298 windows.removeAt(i);
Jeff Brown01ce2e92010-09-26 22:20:12 -07004299 }
4300 }
4301}
4302
4303const InputWindow* InputDispatcher::TouchState::getFirstForegroundWindow() {
4304 for (size_t i = 0; i < windows.size(); i++) {
4305 if (windows[i].targetFlags & InputTarget::FLAG_FOREGROUND) {
4306 return windows[i].window;
4307 }
4308 }
4309 return NULL;
4310}
4311
4312
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004313// --- InputDispatcherThread ---
4314
4315InputDispatcherThread::InputDispatcherThread(const sp<InputDispatcherInterface>& dispatcher) :
4316 Thread(/*canCallJava*/ true), mDispatcher(dispatcher) {
4317}
4318
4319InputDispatcherThread::~InputDispatcherThread() {
4320}
4321
4322bool InputDispatcherThread::threadLoop() {
4323 mDispatcher->dispatchOnce();
4324 return true;
4325}
4326
4327} // namespace android