blob: c064a9ceb157560ab7fcb7a72a5759cd39bdd26a [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 Brown46b9ac02010-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 Brown46b9ac02010-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 Brown46b9ac02010-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 Brown46b9ac02010-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 Brown46b9ac02010-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 Brown46b9ac02010-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 Brown46b9ac02010-04-22 18:58:52 -070038
Jeff Brown7fbdc842010-06-17 20:52:56 -070039// Log debug messages about input event injection.
Jeff Brown349703e2010-06-22 01:27:15 -070040#define DEBUG_INJECTION 0
Jeff Brown7fbdc842010-06-17 20:52:56 -070041
Jeff Brownae9fc032010-08-18 15:51:08 -070042// Log debug messages about input event throttling.
43#define DEBUG_THROTTLING 0
44
Jeff Brownb88102f2010-09-08 11:49:43 -070045// Log debug messages about input focus tracking.
46#define DEBUG_FOCUS 0
47
48// Log debug messages about the app switch latency optimization.
49#define DEBUG_APP_SWITCH 0
50
Jeff Brownb4ff35d2011-01-02 16:37:43 -080051#include "InputDispatcher.h"
52
Jeff Brown46b9ac02010-04-22 18:58:52 -070053#include <cutils/log.h>
Jeff Brownb88102f2010-09-08 11:49:43 -070054#include <ui/PowerManager.h>
Jeff Brown46b9ac02010-04-22 18:58:52 -070055
56#include <stddef.h>
57#include <unistd.h>
Jeff Brown46b9ac02010-04-22 18:58:52 -070058#include <errno.h>
59#include <limits.h>
Jeff Brown46b9ac02010-04-22 18:58:52 -070060
Jeff Brownf2f48712010-10-01 17:46:21 -070061#define INDENT " "
62#define INDENT2 " "
63
Jeff Brown46b9ac02010-04-22 18:58:52 -070064namespace android {
65
Jeff Brownb88102f2010-09-08 11:49:43 -070066// Default input dispatching timeout if there is no focused application or paused window
67// from which to determine an appropriate dispatching timeout.
68const nsecs_t DEFAULT_INPUT_DISPATCHING_TIMEOUT = 5000 * 1000000LL; // 5 sec
69
70// Amount of time to allow for all pending events to be processed when an app switch
71// key is on the way. This is used to preempt input dispatch and drop input events
72// when an application takes too long to respond and the user has pressed an app switch key.
73const nsecs_t APP_SWITCH_TIMEOUT = 500 * 1000000LL; // 0.5sec
74
Jeff Brown928e0542011-01-10 11:17:36 -080075// Amount of time to allow for an event to be dispatched (measured since its eventTime)
76// before considering it stale and dropping it.
77const nsecs_t STALE_EVENT_TIMEOUT = 10000 * 1000000LL; // 10sec
78
Jeff Brown46b9ac02010-04-22 18:58:52 -070079
Jeff Brown7fbdc842010-06-17 20:52:56 -070080static inline nsecs_t now() {
81 return systemTime(SYSTEM_TIME_MONOTONIC);
82}
83
Jeff Brownb88102f2010-09-08 11:49:43 -070084static inline const char* toString(bool value) {
85 return value ? "true" : "false";
86}
87
Jeff Brown01ce2e92010-09-26 22:20:12 -070088static inline int32_t getMotionEventActionPointerIndex(int32_t action) {
89 return (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK)
90 >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
91}
92
93static bool isValidKeyAction(int32_t action) {
94 switch (action) {
95 case AKEY_EVENT_ACTION_DOWN:
96 case AKEY_EVENT_ACTION_UP:
97 return true;
98 default:
99 return false;
100 }
101}
102
103static bool validateKeyEvent(int32_t action) {
104 if (! isValidKeyAction(action)) {
105 LOGE("Key event has invalid action code 0x%x", action);
106 return false;
107 }
108 return true;
109}
110
Jeff Brownb6997262010-10-08 22:31:17 -0700111static bool isValidMotionAction(int32_t action, size_t pointerCount) {
Jeff Brown01ce2e92010-09-26 22:20:12 -0700112 switch (action & AMOTION_EVENT_ACTION_MASK) {
113 case AMOTION_EVENT_ACTION_DOWN:
114 case AMOTION_EVENT_ACTION_UP:
115 case AMOTION_EVENT_ACTION_CANCEL:
116 case AMOTION_EVENT_ACTION_MOVE:
Jeff Brown01ce2e92010-09-26 22:20:12 -0700117 case AMOTION_EVENT_ACTION_OUTSIDE:
Jeff Browncc0c1592011-02-19 05:07:28 -0800118 case AMOTION_EVENT_ACTION_HOVER_MOVE:
Jeff Brown33bbfd22011-02-24 20:55:35 -0800119 case AMOTION_EVENT_ACTION_SCROLL:
Jeff Brown01ce2e92010-09-26 22:20:12 -0700120 return true;
Jeff Brownb6997262010-10-08 22:31:17 -0700121 case AMOTION_EVENT_ACTION_POINTER_DOWN:
122 case AMOTION_EVENT_ACTION_POINTER_UP: {
123 int32_t index = getMotionEventActionPointerIndex(action);
124 return index >= 0 && size_t(index) < pointerCount;
125 }
Jeff Brown01ce2e92010-09-26 22:20:12 -0700126 default:
127 return false;
128 }
129}
130
131static bool validateMotionEvent(int32_t action, size_t pointerCount,
132 const int32_t* pointerIds) {
Jeff Brownb6997262010-10-08 22:31:17 -0700133 if (! isValidMotionAction(action, pointerCount)) {
Jeff Brown01ce2e92010-09-26 22:20:12 -0700134 LOGE("Motion event has invalid action code 0x%x", action);
135 return false;
136 }
137 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
138 LOGE("Motion event has invalid pointer count %d; value must be between 1 and %d.",
139 pointerCount, MAX_POINTERS);
140 return false;
141 }
Jeff Brownc3db8582010-10-20 15:33:38 -0700142 BitSet32 pointerIdBits;
Jeff Brown01ce2e92010-09-26 22:20:12 -0700143 for (size_t i = 0; i < pointerCount; i++) {
Jeff Brownc3db8582010-10-20 15:33:38 -0700144 int32_t id = pointerIds[i];
145 if (id < 0 || id > MAX_POINTER_ID) {
Jeff Brown01ce2e92010-09-26 22:20:12 -0700146 LOGE("Motion event has invalid pointer id %d; value must be between 0 and %d",
Jeff Brownc3db8582010-10-20 15:33:38 -0700147 id, MAX_POINTER_ID);
Jeff Brown01ce2e92010-09-26 22:20:12 -0700148 return false;
149 }
Jeff Brownc3db8582010-10-20 15:33:38 -0700150 if (pointerIdBits.hasBit(id)) {
151 LOGE("Motion event has duplicate pointer id %d", id);
152 return false;
153 }
154 pointerIdBits.markBit(id);
Jeff Brown01ce2e92010-09-26 22:20:12 -0700155 }
156 return true;
157}
158
Jeff Brownfbf09772011-01-16 14:06:57 -0800159static void dumpRegion(String8& dump, const SkRegion& region) {
160 if (region.isEmpty()) {
161 dump.append("<empty>");
162 return;
163 }
164
165 bool first = true;
166 for (SkRegion::Iterator it(region); !it.done(); it.next()) {
167 if (first) {
168 first = false;
169 } else {
170 dump.append("|");
171 }
172 const SkIRect& rect = it.rect();
173 dump.appendFormat("[%d,%d][%d,%d]", rect.fLeft, rect.fTop, rect.fRight, rect.fBottom);
174 }
175}
176
Jeff Brownb88102f2010-09-08 11:49:43 -0700177
Jeff Brown46b9ac02010-04-22 18:58:52 -0700178// --- InputDispatcher ---
179
Jeff Brown9c3cda02010-06-15 01:31:58 -0700180InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy) :
Jeff Brownb88102f2010-09-08 11:49:43 -0700181 mPolicy(policy),
Jeff Brown928e0542011-01-10 11:17:36 -0800182 mPendingEvent(NULL), mAppSwitchSawKeyDown(false), mAppSwitchDueTime(LONG_LONG_MAX),
183 mNextUnblockedEvent(NULL),
Jeff Brownb88102f2010-09-08 11:49:43 -0700184 mDispatchEnabled(true), mDispatchFrozen(false),
Jeff Brown01ce2e92010-09-26 22:20:12 -0700185 mFocusedWindow(NULL),
Jeff Brownb88102f2010-09-08 11:49:43 -0700186 mFocusedApplication(NULL),
187 mCurrentInputTargetsValid(false),
188 mInputTargetWaitCause(INPUT_TARGET_WAIT_CAUSE_NONE) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -0700189 mLooper = new Looper(false);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700190
Jeff Brownb88102f2010-09-08 11:49:43 -0700191 mInboundQueue.headSentinel.refCount = -1;
192 mInboundQueue.headSentinel.type = EventEntry::TYPE_SENTINEL;
193 mInboundQueue.headSentinel.eventTime = LONG_LONG_MIN;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700194
Jeff Brownb88102f2010-09-08 11:49:43 -0700195 mInboundQueue.tailSentinel.refCount = -1;
196 mInboundQueue.tailSentinel.type = EventEntry::TYPE_SENTINEL;
197 mInboundQueue.tailSentinel.eventTime = LONG_LONG_MAX;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700198
199 mKeyRepeatState.lastKeyEntry = NULL;
Jeff Brown9c3cda02010-06-15 01:31:58 -0700200
Jeff Brownae9fc032010-08-18 15:51:08 -0700201 int32_t maxEventsPerSecond = policy->getMaxEventsPerSecond();
202 mThrottleState.minTimeBetweenEvents = 1000000000LL / maxEventsPerSecond;
203 mThrottleState.lastDeviceId = -1;
204
205#if DEBUG_THROTTLING
206 mThrottleState.originalSampleCount = 0;
207 LOGD("Throttling - Max events per second = %d", maxEventsPerSecond);
208#endif
Jeff Brown46b9ac02010-04-22 18:58:52 -0700209}
210
211InputDispatcher::~InputDispatcher() {
Jeff Brownb88102f2010-09-08 11:49:43 -0700212 { // acquire lock
213 AutoMutex _l(mLock);
214
215 resetKeyRepeatLocked();
Jeff Brown54a18252010-09-16 14:07:33 -0700216 releasePendingEventLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -0700217 drainInboundQueueLocked();
218 }
Jeff Brown46b9ac02010-04-22 18:58:52 -0700219
220 while (mConnectionsByReceiveFd.size() != 0) {
221 unregisterInputChannel(mConnectionsByReceiveFd.valueAt(0)->inputChannel);
222 }
Jeff Brown46b9ac02010-04-22 18:58:52 -0700223}
224
225void InputDispatcher::dispatchOnce() {
Jeff Brown9c3cda02010-06-15 01:31:58 -0700226 nsecs_t keyRepeatTimeout = mPolicy->getKeyRepeatTimeout();
Jeff Brownb21fb102010-09-07 10:44:57 -0700227 nsecs_t keyRepeatDelay = mPolicy->getKeyRepeatDelay();
Jeff Brown46b9ac02010-04-22 18:58:52 -0700228
Jeff Brown46b9ac02010-04-22 18:58:52 -0700229 nsecs_t nextWakeupTime = LONG_LONG_MAX;
230 { // acquire lock
231 AutoMutex _l(mLock);
Jeff Brownb88102f2010-09-08 11:49:43 -0700232 dispatchOnceInnerLocked(keyRepeatTimeout, keyRepeatDelay, & nextWakeupTime);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700233
Jeff Brownb88102f2010-09-08 11:49:43 -0700234 if (runCommandsLockedInterruptible()) {
235 nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
Jeff Brown46b9ac02010-04-22 18:58:52 -0700236 }
Jeff Brown46b9ac02010-04-22 18:58:52 -0700237 } // release lock
238
Jeff Brownb88102f2010-09-08 11:49:43 -0700239 // Wait for callback or timeout or wake. (make sure we round up, not down)
240 nsecs_t currentTime = now();
241 int32_t timeoutMillis;
242 if (nextWakeupTime > currentTime) {
243 uint64_t timeout = uint64_t(nextWakeupTime - currentTime);
244 timeout = (timeout + 999999LL) / 1000000LL;
245 timeoutMillis = timeout > INT_MAX ? -1 : int32_t(timeout);
246 } else {
247 timeoutMillis = 0;
248 }
249
Jeff Brown4fe6c3e2010-09-13 23:17:30 -0700250 mLooper->pollOnce(timeoutMillis);
Jeff Brownb88102f2010-09-08 11:49:43 -0700251}
252
253void InputDispatcher::dispatchOnceInnerLocked(nsecs_t keyRepeatTimeout,
254 nsecs_t keyRepeatDelay, nsecs_t* nextWakeupTime) {
255 nsecs_t currentTime = now();
256
257 // Reset the key repeat timer whenever we disallow key events, even if the next event
258 // is not a key. This is to ensure that we abort a key repeat if the device is just coming
259 // out of sleep.
260 if (keyRepeatTimeout < 0) {
261 resetKeyRepeatLocked();
262 }
263
Jeff Brownb88102f2010-09-08 11:49:43 -0700264 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
265 if (mDispatchFrozen) {
266#if DEBUG_FOCUS
267 LOGD("Dispatch frozen. Waiting some more.");
268#endif
269 return;
270 }
271
272 // Optimize latency of app switches.
273 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
274 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
275 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
276 if (mAppSwitchDueTime < *nextWakeupTime) {
277 *nextWakeupTime = mAppSwitchDueTime;
278 }
279
Jeff Brownb88102f2010-09-08 11:49:43 -0700280 // Ready to start a new event.
281 // If we don't already have a pending event, go grab one.
282 if (! mPendingEvent) {
283 if (mInboundQueue.isEmpty()) {
284 if (isAppSwitchDue) {
285 // The inbound queue is empty so the app switch key we were waiting
286 // for will never arrive. Stop waiting for it.
287 resetPendingAppSwitchLocked(false);
288 isAppSwitchDue = false;
289 }
290
291 // Synthesize a key repeat if appropriate.
292 if (mKeyRepeatState.lastKeyEntry) {
293 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
294 mPendingEvent = synthesizeKeyRepeatLocked(currentTime, keyRepeatDelay);
295 } else {
296 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
297 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
298 }
299 }
300 }
301 if (! mPendingEvent) {
302 return;
303 }
304 } else {
305 // Inbound queue has at least one entry.
306 EventEntry* entry = mInboundQueue.headSentinel.next;
307
308 // Throttle the entry if it is a move event and there are no
309 // other events behind it in the queue. Due to movement batching, additional
310 // samples may be appended to this event by the time the throttling timeout
311 // expires.
312 // TODO Make this smarter and consider throttling per device independently.
Jeff Brownb6997262010-10-08 22:31:17 -0700313 if (entry->type == EventEntry::TYPE_MOTION
314 && !isAppSwitchDue
315 && mDispatchEnabled
316 && (entry->policyFlags & POLICY_FLAG_PASS_TO_USER)
317 && !entry->isInjected()) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700318 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
319 int32_t deviceId = motionEntry->deviceId;
320 uint32_t source = motionEntry->source;
321 if (! isAppSwitchDue
322 && motionEntry->next == & mInboundQueue.tailSentinel // exactly one event
Jeff Browncc0c1592011-02-19 05:07:28 -0800323 && (motionEntry->action == AMOTION_EVENT_ACTION_MOVE
324 || motionEntry->action == AMOTION_EVENT_ACTION_HOVER_MOVE)
Jeff Brownb88102f2010-09-08 11:49:43 -0700325 && deviceId == mThrottleState.lastDeviceId
326 && source == mThrottleState.lastSource) {
327 nsecs_t nextTime = mThrottleState.lastEventTime
328 + mThrottleState.minTimeBetweenEvents;
329 if (currentTime < nextTime) {
330 // Throttle it!
331#if DEBUG_THROTTLING
332 LOGD("Throttling - Delaying motion event for "
Jeff Brown90655042010-12-02 13:50:46 -0800333 "device %d, source 0x%08x by up to %0.3fms.",
Jeff Brownb88102f2010-09-08 11:49:43 -0700334 deviceId, source, (nextTime - currentTime) * 0.000001);
335#endif
336 if (nextTime < *nextWakeupTime) {
337 *nextWakeupTime = nextTime;
338 }
339 if (mThrottleState.originalSampleCount == 0) {
340 mThrottleState.originalSampleCount =
341 motionEntry->countSamples();
342 }
343 return;
344 }
345 }
346
347#if DEBUG_THROTTLING
348 if (mThrottleState.originalSampleCount != 0) {
349 uint32_t count = motionEntry->countSamples();
350 LOGD("Throttling - Motion event sample count grew by %d from %d to %d.",
351 count - mThrottleState.originalSampleCount,
352 mThrottleState.originalSampleCount, count);
353 mThrottleState.originalSampleCount = 0;
354 }
355#endif
356
357 mThrottleState.lastEventTime = entry->eventTime < currentTime
358 ? entry->eventTime : currentTime;
359 mThrottleState.lastDeviceId = deviceId;
360 mThrottleState.lastSource = source;
361 }
362
363 mInboundQueue.dequeue(entry);
364 mPendingEvent = entry;
365 }
Jeff Browne2fe69e2010-10-18 13:21:23 -0700366
367 // Poke user activity for this event.
368 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
369 pokeUserActivityLocked(mPendingEvent);
370 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700371 }
372
373 // Now we have an event to dispatch.
Jeff Brown928e0542011-01-10 11:17:36 -0800374 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Jeff Brownb88102f2010-09-08 11:49:43 -0700375 assert(mPendingEvent != NULL);
Jeff Brown54a18252010-09-16 14:07:33 -0700376 bool done = false;
Jeff Brownb6997262010-10-08 22:31:17 -0700377 DropReason dropReason = DROP_REASON_NOT_DROPPED;
378 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
379 dropReason = DROP_REASON_POLICY;
380 } else if (!mDispatchEnabled) {
381 dropReason = DROP_REASON_DISABLED;
382 }
Jeff Brown928e0542011-01-10 11:17:36 -0800383
384 if (mNextUnblockedEvent == mPendingEvent) {
385 mNextUnblockedEvent = NULL;
386 }
387
Jeff Brownb88102f2010-09-08 11:49:43 -0700388 switch (mPendingEvent->type) {
389 case EventEntry::TYPE_CONFIGURATION_CHANGED: {
390 ConfigurationChangedEntry* typedEntry =
391 static_cast<ConfigurationChangedEntry*>(mPendingEvent);
Jeff Brown54a18252010-09-16 14:07:33 -0700392 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Jeff Brownb6997262010-10-08 22:31:17 -0700393 dropReason = DROP_REASON_NOT_DROPPED; // configuration changes are never dropped
Jeff Brownb88102f2010-09-08 11:49:43 -0700394 break;
395 }
396
397 case EventEntry::TYPE_KEY: {
398 KeyEntry* typedEntry = static_cast<KeyEntry*>(mPendingEvent);
Jeff Brownb6997262010-10-08 22:31:17 -0700399 if (isAppSwitchDue) {
400 if (isAppSwitchKeyEventLocked(typedEntry)) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700401 resetPendingAppSwitchLocked(true);
Jeff Brownb6997262010-10-08 22:31:17 -0700402 isAppSwitchDue = false;
403 } else if (dropReason == DROP_REASON_NOT_DROPPED) {
404 dropReason = DROP_REASON_APP_SWITCH;
Jeff Brownb88102f2010-09-08 11:49:43 -0700405 }
406 }
Jeff Brown928e0542011-01-10 11:17:36 -0800407 if (dropReason == DROP_REASON_NOT_DROPPED
408 && isStaleEventLocked(currentTime, typedEntry)) {
409 dropReason = DROP_REASON_STALE;
410 }
411 if (dropReason == DROP_REASON_NOT_DROPPED && mNextUnblockedEvent) {
412 dropReason = DROP_REASON_BLOCKED;
413 }
Jeff Brownb6997262010-10-08 22:31:17 -0700414 done = dispatchKeyLocked(currentTime, typedEntry, keyRepeatTimeout,
Jeff Browne20c9e02010-10-11 14:20:19 -0700415 &dropReason, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700416 break;
417 }
418
419 case EventEntry::TYPE_MOTION: {
420 MotionEntry* typedEntry = static_cast<MotionEntry*>(mPendingEvent);
Jeff Brownb6997262010-10-08 22:31:17 -0700421 if (dropReason == DROP_REASON_NOT_DROPPED && isAppSwitchDue) {
422 dropReason = DROP_REASON_APP_SWITCH;
Jeff Brownb88102f2010-09-08 11:49:43 -0700423 }
Jeff Brown928e0542011-01-10 11:17:36 -0800424 if (dropReason == DROP_REASON_NOT_DROPPED
425 && isStaleEventLocked(currentTime, typedEntry)) {
426 dropReason = DROP_REASON_STALE;
427 }
428 if (dropReason == DROP_REASON_NOT_DROPPED && mNextUnblockedEvent) {
429 dropReason = DROP_REASON_BLOCKED;
430 }
Jeff Brownb6997262010-10-08 22:31:17 -0700431 done = dispatchMotionLocked(currentTime, typedEntry,
Jeff Browne20c9e02010-10-11 14:20:19 -0700432 &dropReason, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700433 break;
434 }
435
436 default:
437 assert(false);
Jeff Brownb88102f2010-09-08 11:49:43 -0700438 break;
439 }
440
Jeff Brown54a18252010-09-16 14:07:33 -0700441 if (done) {
Jeff Brownb6997262010-10-08 22:31:17 -0700442 if (dropReason != DROP_REASON_NOT_DROPPED) {
443 dropInboundEventLocked(mPendingEvent, dropReason);
444 }
445
Jeff Brown54a18252010-09-16 14:07:33 -0700446 releasePendingEventLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -0700447 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
448 }
449}
450
451bool InputDispatcher::enqueueInboundEventLocked(EventEntry* entry) {
452 bool needWake = mInboundQueue.isEmpty();
453 mInboundQueue.enqueueAtTail(entry);
454
455 switch (entry->type) {
Jeff Brownb6997262010-10-08 22:31:17 -0700456 case EventEntry::TYPE_KEY: {
Jeff Brown928e0542011-01-10 11:17:36 -0800457 // Optimize app switch latency.
458 // If the application takes too long to catch up then we drop all events preceding
459 // the app switch key.
Jeff Brownb6997262010-10-08 22:31:17 -0700460 KeyEntry* keyEntry = static_cast<KeyEntry*>(entry);
461 if (isAppSwitchKeyEventLocked(keyEntry)) {
462 if (keyEntry->action == AKEY_EVENT_ACTION_DOWN) {
463 mAppSwitchSawKeyDown = true;
464 } else if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
465 if (mAppSwitchSawKeyDown) {
466#if DEBUG_APP_SWITCH
467 LOGD("App switch is pending!");
468#endif
469 mAppSwitchDueTime = keyEntry->eventTime + APP_SWITCH_TIMEOUT;
470 mAppSwitchSawKeyDown = false;
471 needWake = true;
472 }
473 }
474 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700475 break;
476 }
Jeff Brown928e0542011-01-10 11:17:36 -0800477
478 case EventEntry::TYPE_MOTION: {
479 // Optimize case where the current application is unresponsive and the user
480 // decides to touch a window in a different application.
481 // If the application takes too long to catch up then we drop all events preceding
482 // the touch into the other window.
483 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
Jeff Brown33bbfd22011-02-24 20:55:35 -0800484 if (motionEntry->action == AMOTION_EVENT_ACTION_DOWN
Jeff Brown928e0542011-01-10 11:17:36 -0800485 && (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER)
486 && mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY
487 && mInputTargetWaitApplication != NULL) {
Jeff Brown91c69ab2011-02-14 17:03:18 -0800488 int32_t x = int32_t(motionEntry->firstSample.pointerCoords[0].
Jeff Brownebbd5d12011-02-17 13:01:34 -0800489 getAxisValue(AMOTION_EVENT_AXIS_X));
Jeff Brown91c69ab2011-02-14 17:03:18 -0800490 int32_t y = int32_t(motionEntry->firstSample.pointerCoords[0].
Jeff Brownebbd5d12011-02-17 13:01:34 -0800491 getAxisValue(AMOTION_EVENT_AXIS_Y));
Jeff Brown928e0542011-01-10 11:17:36 -0800492 const InputWindow* touchedWindow = findTouchedWindowAtLocked(x, y);
493 if (touchedWindow
494 && touchedWindow->inputWindowHandle != NULL
495 && touchedWindow->inputWindowHandle->getInputApplicationHandle()
496 != mInputTargetWaitApplication) {
497 // User touched a different application than the one we are waiting on.
498 // Flag the event, and start pruning the input queue.
499 mNextUnblockedEvent = motionEntry;
500 needWake = true;
501 }
502 }
503 break;
504 }
Jeff Brownb6997262010-10-08 22:31:17 -0700505 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700506
507 return needWake;
508}
509
Jeff Brown928e0542011-01-10 11:17:36 -0800510const InputWindow* InputDispatcher::findTouchedWindowAtLocked(int32_t x, int32_t y) {
511 // Traverse windows from front to back to find touched window.
512 size_t numWindows = mWindows.size();
513 for (size_t i = 0; i < numWindows; i++) {
514 const InputWindow* window = & mWindows.editItemAt(i);
515 int32_t flags = window->layoutParamsFlags;
516
517 if (window->visible) {
518 if (!(flags & InputWindow::FLAG_NOT_TOUCHABLE)) {
519 bool isTouchModal = (flags & (InputWindow::FLAG_NOT_FOCUSABLE
520 | InputWindow::FLAG_NOT_TOUCH_MODAL)) == 0;
Jeff Brownfbf09772011-01-16 14:06:57 -0800521 if (isTouchModal || window->touchableRegionContainsPoint(x, y)) {
Jeff Brown928e0542011-01-10 11:17:36 -0800522 // Found window.
523 return window;
524 }
525 }
526 }
527
528 if (flags & InputWindow::FLAG_SYSTEM_ERROR) {
529 // Error window is on top but not visible, so touch is dropped.
530 return NULL;
531 }
532 }
533 return NULL;
534}
535
Jeff Brownb6997262010-10-08 22:31:17 -0700536void InputDispatcher::dropInboundEventLocked(EventEntry* entry, DropReason dropReason) {
537 const char* reason;
538 switch (dropReason) {
539 case DROP_REASON_POLICY:
Jeff Browne20c9e02010-10-11 14:20:19 -0700540#if DEBUG_INBOUND_EVENT_DETAILS
Jeff Brown3122e442010-10-11 23:32:49 -0700541 LOGD("Dropped event because policy consumed it.");
Jeff Browne20c9e02010-10-11 14:20:19 -0700542#endif
Jeff Brown3122e442010-10-11 23:32:49 -0700543 reason = "inbound event was dropped because the policy consumed it";
Jeff Brownb6997262010-10-08 22:31:17 -0700544 break;
545 case DROP_REASON_DISABLED:
546 LOGI("Dropped event because input dispatch is disabled.");
547 reason = "inbound event was dropped because input dispatch is disabled";
548 break;
549 case DROP_REASON_APP_SWITCH:
550 LOGI("Dropped event because of pending overdue app switch.");
551 reason = "inbound event was dropped because of pending overdue app switch";
552 break;
Jeff Brown928e0542011-01-10 11:17:36 -0800553 case DROP_REASON_BLOCKED:
554 LOGI("Dropped event because the current application is not responding and the user "
555 "has started interating with a different application.");
556 reason = "inbound event was dropped because the current application is not responding "
557 "and the user has started interating with a different application";
558 break;
559 case DROP_REASON_STALE:
560 LOGI("Dropped event because it is stale.");
561 reason = "inbound event was dropped because it is stale";
562 break;
Jeff Brownb6997262010-10-08 22:31:17 -0700563 default:
564 assert(false);
565 return;
566 }
567
568 switch (entry->type) {
569 case EventEntry::TYPE_KEY:
570 synthesizeCancelationEventsForAllConnectionsLocked(
571 InputState::CANCEL_NON_POINTER_EVENTS, reason);
572 break;
573 case EventEntry::TYPE_MOTION: {
574 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
575 if (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) {
576 synthesizeCancelationEventsForAllConnectionsLocked(
577 InputState::CANCEL_POINTER_EVENTS, reason);
578 } else {
579 synthesizeCancelationEventsForAllConnectionsLocked(
580 InputState::CANCEL_NON_POINTER_EVENTS, reason);
581 }
582 break;
583 }
584 }
585}
586
587bool InputDispatcher::isAppSwitchKeyCode(int32_t keyCode) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700588 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL;
589}
590
Jeff Brownb6997262010-10-08 22:31:17 -0700591bool InputDispatcher::isAppSwitchKeyEventLocked(KeyEntry* keyEntry) {
592 return ! (keyEntry->flags & AKEY_EVENT_FLAG_CANCELED)
593 && isAppSwitchKeyCode(keyEntry->keyCode)
Jeff Browne20c9e02010-10-11 14:20:19 -0700594 && (keyEntry->policyFlags & POLICY_FLAG_TRUSTED)
Jeff Brownb6997262010-10-08 22:31:17 -0700595 && (keyEntry->policyFlags & POLICY_FLAG_PASS_TO_USER);
596}
597
Jeff Brownb88102f2010-09-08 11:49:43 -0700598bool InputDispatcher::isAppSwitchPendingLocked() {
599 return mAppSwitchDueTime != LONG_LONG_MAX;
600}
601
Jeff Brownb88102f2010-09-08 11:49:43 -0700602void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
603 mAppSwitchDueTime = LONG_LONG_MAX;
604
605#if DEBUG_APP_SWITCH
606 if (handled) {
607 LOGD("App switch has arrived.");
608 } else {
609 LOGD("App switch was abandoned.");
610 }
611#endif
Jeff Brown46b9ac02010-04-22 18:58:52 -0700612}
613
Jeff Brown928e0542011-01-10 11:17:36 -0800614bool InputDispatcher::isStaleEventLocked(nsecs_t currentTime, EventEntry* entry) {
615 return currentTime - entry->eventTime >= STALE_EVENT_TIMEOUT;
616}
617
Jeff Brown9c3cda02010-06-15 01:31:58 -0700618bool InputDispatcher::runCommandsLockedInterruptible() {
619 if (mCommandQueue.isEmpty()) {
620 return false;
621 }
Jeff Brown46b9ac02010-04-22 18:58:52 -0700622
Jeff Brown9c3cda02010-06-15 01:31:58 -0700623 do {
624 CommandEntry* commandEntry = mCommandQueue.dequeueAtHead();
625
626 Command command = commandEntry->command;
627 (this->*command)(commandEntry); // commands are implicitly 'LockedInterruptible'
628
Jeff Brown7fbdc842010-06-17 20:52:56 -0700629 commandEntry->connection.clear();
Jeff Brown9c3cda02010-06-15 01:31:58 -0700630 mAllocator.releaseCommandEntry(commandEntry);
631 } while (! mCommandQueue.isEmpty());
632 return true;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700633}
634
Jeff Brown9c3cda02010-06-15 01:31:58 -0700635InputDispatcher::CommandEntry* InputDispatcher::postCommandLocked(Command command) {
636 CommandEntry* commandEntry = mAllocator.obtainCommandEntry(command);
637 mCommandQueue.enqueueAtTail(commandEntry);
638 return commandEntry;
639}
640
Jeff Brownb88102f2010-09-08 11:49:43 -0700641void InputDispatcher::drainInboundQueueLocked() {
642 while (! mInboundQueue.isEmpty()) {
643 EventEntry* entry = mInboundQueue.dequeueAtHead();
Jeff Brown54a18252010-09-16 14:07:33 -0700644 releaseInboundEventLocked(entry);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700645 }
Jeff Brown46b9ac02010-04-22 18:58:52 -0700646}
647
Jeff Brown54a18252010-09-16 14:07:33 -0700648void InputDispatcher::releasePendingEventLocked() {
Jeff Brownb88102f2010-09-08 11:49:43 -0700649 if (mPendingEvent) {
Jeff Brown54a18252010-09-16 14:07:33 -0700650 releaseInboundEventLocked(mPendingEvent);
Jeff Brownb88102f2010-09-08 11:49:43 -0700651 mPendingEvent = NULL;
652 }
653}
654
Jeff Brown54a18252010-09-16 14:07:33 -0700655void InputDispatcher::releaseInboundEventLocked(EventEntry* entry) {
Jeff Brown01ce2e92010-09-26 22:20:12 -0700656 InjectionState* injectionState = entry->injectionState;
657 if (injectionState && injectionState->injectionResult == INPUT_EVENT_INJECTION_PENDING) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700658#if DEBUG_DISPATCH_CYCLE
Jeff Brown01ce2e92010-09-26 22:20:12 -0700659 LOGD("Injected inbound event was dropped.");
Jeff Brownb88102f2010-09-08 11:49:43 -0700660#endif
661 setInjectionResultLocked(entry, INPUT_EVENT_INJECTION_FAILED);
662 }
663 mAllocator.releaseEventEntry(entry);
664}
665
Jeff Brownb88102f2010-09-08 11:49:43 -0700666void InputDispatcher::resetKeyRepeatLocked() {
667 if (mKeyRepeatState.lastKeyEntry) {
668 mAllocator.releaseKeyEntry(mKeyRepeatState.lastKeyEntry);
669 mKeyRepeatState.lastKeyEntry = NULL;
670 }
671}
672
673InputDispatcher::KeyEntry* InputDispatcher::synthesizeKeyRepeatLocked(
Jeff Brownb21fb102010-09-07 10:44:57 -0700674 nsecs_t currentTime, nsecs_t keyRepeatDelay) {
Jeff Brown349703e2010-06-22 01:27:15 -0700675 KeyEntry* entry = mKeyRepeatState.lastKeyEntry;
676
Jeff Brown349703e2010-06-22 01:27:15 -0700677 // Reuse the repeated key entry if it is otherwise unreferenced.
Jeff Browne20c9e02010-10-11 14:20:19 -0700678 uint32_t policyFlags = (entry->policyFlags & POLICY_FLAG_RAW_MASK)
679 | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700680 if (entry->refCount == 1) {
Jeff Brown01ce2e92010-09-26 22:20:12 -0700681 mAllocator.recycleKeyEntry(entry);
Jeff Brown7fbdc842010-06-17 20:52:56 -0700682 entry->eventTime = currentTime;
Jeff Brown7fbdc842010-06-17 20:52:56 -0700683 entry->policyFlags = policyFlags;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700684 entry->repeatCount += 1;
685 } else {
Jeff Brown7fbdc842010-06-17 20:52:56 -0700686 KeyEntry* newEntry = mAllocator.obtainKeyEntry(currentTime,
Jeff Brownc5ed5912010-07-14 18:48:53 -0700687 entry->deviceId, entry->source, policyFlags,
Jeff Brown7fbdc842010-06-17 20:52:56 -0700688 entry->action, entry->flags, entry->keyCode, entry->scanCode,
Jeff Brown00fa7bd2010-07-02 15:37:36 -0700689 entry->metaState, entry->repeatCount + 1, entry->downTime);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700690
691 mKeyRepeatState.lastKeyEntry = newEntry;
692 mAllocator.releaseKeyEntry(entry);
693
694 entry = newEntry;
695 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700696 entry->syntheticRepeat = true;
697
698 // Increment reference count since we keep a reference to the event in
699 // mKeyRepeatState.lastKeyEntry in addition to the one we return.
700 entry->refCount += 1;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700701
Jeff Brown00fa7bd2010-07-02 15:37:36 -0700702 if (entry->repeatCount == 1) {
Jeff Brownc5ed5912010-07-14 18:48:53 -0700703 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
Jeff Brown00fa7bd2010-07-02 15:37:36 -0700704 }
705
Jeff Brownb21fb102010-09-07 10:44:57 -0700706 mKeyRepeatState.nextRepeatTime = currentTime + keyRepeatDelay;
Jeff Brownb88102f2010-09-08 11:49:43 -0700707 return entry;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700708}
709
Jeff Brownb88102f2010-09-08 11:49:43 -0700710bool InputDispatcher::dispatchConfigurationChangedLocked(
711 nsecs_t currentTime, ConfigurationChangedEntry* entry) {
Jeff Brown46b9ac02010-04-22 18:58:52 -0700712#if DEBUG_OUTBOUND_EVENT_DETAILS
Jeff Brownb88102f2010-09-08 11:49:43 -0700713 LOGD("dispatchConfigurationChanged - eventTime=%lld", entry->eventTime);
714#endif
715
716 // Reset key repeating in case a keyboard device was added or removed or something.
717 resetKeyRepeatLocked();
718
719 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
720 CommandEntry* commandEntry = postCommandLocked(
721 & InputDispatcher::doNotifyConfigurationChangedInterruptible);
722 commandEntry->eventTime = entry->eventTime;
723 return true;
724}
725
726bool InputDispatcher::dispatchKeyLocked(
727 nsecs_t currentTime, KeyEntry* entry, nsecs_t keyRepeatTimeout,
Jeff Browne20c9e02010-10-11 14:20:19 -0700728 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Jeff Browne46a0a42010-11-02 17:58:22 -0700729 // Preprocessing.
730 if (! entry->dispatchInProgress) {
731 if (entry->repeatCount == 0
732 && entry->action == AKEY_EVENT_ACTION_DOWN
733 && (entry->policyFlags & POLICY_FLAG_TRUSTED)
734 && !entry->isInjected()) {
735 if (mKeyRepeatState.lastKeyEntry
736 && mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode) {
737 // We have seen two identical key downs in a row which indicates that the device
738 // driver is automatically generating key repeats itself. We take note of the
739 // repeat here, but we disable our own next key repeat timer since it is clear that
740 // we will not need to synthesize key repeats ourselves.
741 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
742 resetKeyRepeatLocked();
743 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
744 } else {
745 // Not a repeat. Save key down state in case we do see a repeat later.
746 resetKeyRepeatLocked();
747 mKeyRepeatState.nextRepeatTime = entry->eventTime + keyRepeatTimeout;
748 }
749 mKeyRepeatState.lastKeyEntry = entry;
750 entry->refCount += 1;
751 } else if (! entry->syntheticRepeat) {
752 resetKeyRepeatLocked();
753 }
754
755 entry->dispatchInProgress = true;
756 resetTargetsLocked();
757
758 logOutboundKeyDetailsLocked("dispatchKey - ", entry);
759 }
760
Jeff Brown54a18252010-09-16 14:07:33 -0700761 // Give the policy a chance to intercept the key.
762 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
Jeff Browne20c9e02010-10-11 14:20:19 -0700763 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Jeff Brown54a18252010-09-16 14:07:33 -0700764 CommandEntry* commandEntry = postCommandLocked(
765 & InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
Jeff Browne20c9e02010-10-11 14:20:19 -0700766 if (mFocusedWindow) {
Jeff Brown928e0542011-01-10 11:17:36 -0800767 commandEntry->inputWindowHandle = mFocusedWindow->inputWindowHandle;
Jeff Brown54a18252010-09-16 14:07:33 -0700768 }
769 commandEntry->keyEntry = entry;
770 entry->refCount += 1;
771 return false; // wait for the command to run
772 } else {
773 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
774 }
775 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Jeff Browne20c9e02010-10-11 14:20:19 -0700776 if (*dropReason == DROP_REASON_NOT_DROPPED) {
777 *dropReason = DROP_REASON_POLICY;
778 }
Jeff Brown54a18252010-09-16 14:07:33 -0700779 }
780
781 // Clean up if dropping the event.
Jeff Browne20c9e02010-10-11 14:20:19 -0700782 if (*dropReason != DROP_REASON_NOT_DROPPED) {
Jeff Brown54a18252010-09-16 14:07:33 -0700783 resetTargetsLocked();
Jeff Brown3122e442010-10-11 23:32:49 -0700784 setInjectionResultLocked(entry, *dropReason == DROP_REASON_POLICY
785 ? INPUT_EVENT_INJECTION_SUCCEEDED : INPUT_EVENT_INJECTION_FAILED);
Jeff Brown54a18252010-09-16 14:07:33 -0700786 return true;
787 }
788
Jeff Brownb88102f2010-09-08 11:49:43 -0700789 // Identify targets.
790 if (! mCurrentInputTargetsValid) {
Jeff Brown01ce2e92010-09-26 22:20:12 -0700791 int32_t injectionResult = findFocusedWindowTargetsLocked(currentTime,
792 entry, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700793 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
794 return false;
795 }
796
797 setInjectionResultLocked(entry, injectionResult);
798 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
799 return true;
800 }
801
802 addMonitoringTargetsLocked();
Jeff Brown01ce2e92010-09-26 22:20:12 -0700803 commitTargetsLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -0700804 }
805
806 // Dispatch the key.
807 dispatchEventToCurrentInputTargetsLocked(currentTime, entry, false);
Jeff Brownb88102f2010-09-08 11:49:43 -0700808 return true;
809}
810
811void InputDispatcher::logOutboundKeyDetailsLocked(const char* prefix, const KeyEntry* entry) {
812#if DEBUG_OUTBOUND_EVENT_DETAILS
Jeff Brown90655042010-12-02 13:50:46 -0800813 LOGD("%seventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, "
Jeff Brownb88102f2010-09-08 11:49:43 -0700814 "action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, "
Jeff Browne46a0a42010-11-02 17:58:22 -0700815 "repeatCount=%d, downTime=%lld",
Jeff Brownb88102f2010-09-08 11:49:43 -0700816 prefix,
817 entry->eventTime, entry->deviceId, entry->source, entry->policyFlags,
818 entry->action, entry->flags, entry->keyCode, entry->scanCode, entry->metaState,
Jeff Browne46a0a42010-11-02 17:58:22 -0700819 entry->repeatCount, entry->downTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700820#endif
821}
822
823bool InputDispatcher::dispatchMotionLocked(
Jeff Browne20c9e02010-10-11 14:20:19 -0700824 nsecs_t currentTime, MotionEntry* entry, DropReason* dropReason, nsecs_t* nextWakeupTime) {
Jeff Browne46a0a42010-11-02 17:58:22 -0700825 // Preprocessing.
826 if (! entry->dispatchInProgress) {
827 entry->dispatchInProgress = true;
828 resetTargetsLocked();
829
830 logOutboundMotionDetailsLocked("dispatchMotion - ", entry);
831 }
832
Jeff Brown54a18252010-09-16 14:07:33 -0700833 // Clean up if dropping the event.
Jeff Browne20c9e02010-10-11 14:20:19 -0700834 if (*dropReason != DROP_REASON_NOT_DROPPED) {
Jeff Brown54a18252010-09-16 14:07:33 -0700835 resetTargetsLocked();
Jeff Brown3122e442010-10-11 23:32:49 -0700836 setInjectionResultLocked(entry, *dropReason == DROP_REASON_POLICY
837 ? INPUT_EVENT_INJECTION_SUCCEEDED : INPUT_EVENT_INJECTION_FAILED);
Jeff Brown54a18252010-09-16 14:07:33 -0700838 return true;
839 }
840
Jeff Brownb88102f2010-09-08 11:49:43 -0700841 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
842
843 // Identify targets.
Jeff Browncc0c1592011-02-19 05:07:28 -0800844 bool conflictingPointerActions = false;
Jeff Brownb88102f2010-09-08 11:49:43 -0700845 if (! mCurrentInputTargetsValid) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700846 int32_t injectionResult;
847 if (isPointerEvent) {
848 // Pointer event. (eg. touchscreen)
Jeff Brown01ce2e92010-09-26 22:20:12 -0700849 injectionResult = findTouchedWindowTargetsLocked(currentTime,
Jeff Browncc0c1592011-02-19 05:07:28 -0800850 entry, nextWakeupTime, &conflictingPointerActions);
Jeff Brownb88102f2010-09-08 11:49:43 -0700851 } else {
852 // Non touch event. (eg. trackball)
Jeff Brown01ce2e92010-09-26 22:20:12 -0700853 injectionResult = findFocusedWindowTargetsLocked(currentTime,
854 entry, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700855 }
856 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
857 return false;
858 }
859
860 setInjectionResultLocked(entry, injectionResult);
861 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
862 return true;
863 }
864
865 addMonitoringTargetsLocked();
Jeff Brown01ce2e92010-09-26 22:20:12 -0700866 commitTargetsLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -0700867 }
868
869 // Dispatch the motion.
Jeff Browncc0c1592011-02-19 05:07:28 -0800870 if (conflictingPointerActions) {
871 synthesizeCancelationEventsForAllConnectionsLocked(
872 InputState::CANCEL_POINTER_EVENTS, "Conflicting pointer actions.");
873 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700874 dispatchEventToCurrentInputTargetsLocked(currentTime, entry, false);
Jeff Brownb88102f2010-09-08 11:49:43 -0700875 return true;
876}
877
878
879void InputDispatcher::logOutboundMotionDetailsLocked(const char* prefix, const MotionEntry* entry) {
880#if DEBUG_OUTBOUND_EVENT_DETAILS
Jeff Brown90655042010-12-02 13:50:46 -0800881 LOGD("%seventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, "
Jeff Brown85a31762010-09-01 17:01:00 -0700882 "action=0x%x, flags=0x%x, "
Jeff Brown46b9ac02010-04-22 18:58:52 -0700883 "metaState=0x%x, edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%lld",
Jeff Brownb88102f2010-09-08 11:49:43 -0700884 prefix,
Jeff Brown85a31762010-09-01 17:01:00 -0700885 entry->eventTime, entry->deviceId, entry->source, entry->policyFlags,
886 entry->action, entry->flags,
Jeff Brown46b9ac02010-04-22 18:58:52 -0700887 entry->metaState, entry->edgeFlags, entry->xPrecision, entry->yPrecision,
888 entry->downTime);
889
890 // Print the most recent sample that we have available, this may change due to batching.
891 size_t sampleCount = 1;
Jeff Brownb88102f2010-09-08 11:49:43 -0700892 const MotionSample* sample = & entry->firstSample;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700893 for (; sample->next != NULL; sample = sample->next) {
894 sampleCount += 1;
895 }
896 for (uint32_t i = 0; i < entry->pointerCount; i++) {
Jeff Brown8d608662010-08-30 03:02:23 -0700897 LOGD(" Pointer %d: id=%d, x=%f, y=%f, pressure=%f, size=%f, "
Jeff Brown85a31762010-09-01 17:01:00 -0700898 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
Jeff Brown8d608662010-08-30 03:02:23 -0700899 "orientation=%f",
Jeff Brown46b9ac02010-04-22 18:58:52 -0700900 i, entry->pointerIds[i],
Jeff Brownebbd5d12011-02-17 13:01:34 -0800901 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
902 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
903 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
904 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
905 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
906 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
907 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
908 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
909 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Jeff Brown46b9ac02010-04-22 18:58:52 -0700910 }
911
912 // Keep in mind that due to batching, it is possible for the number of samples actually
913 // dispatched to change before the application finally consumed them.
Jeff Brownc5ed5912010-07-14 18:48:53 -0700914 if (entry->action == AMOTION_EVENT_ACTION_MOVE) {
Jeff Brown46b9ac02010-04-22 18:58:52 -0700915 LOGD(" ... Total movement samples currently batched %d ...", sampleCount);
916 }
917#endif
Jeff Brown46b9ac02010-04-22 18:58:52 -0700918}
919
920void InputDispatcher::dispatchEventToCurrentInputTargetsLocked(nsecs_t currentTime,
921 EventEntry* eventEntry, bool resumeWithAppendedMotionSample) {
922#if DEBUG_DISPATCH_CYCLE
Jeff Brown9c3cda02010-06-15 01:31:58 -0700923 LOGD("dispatchEventToCurrentInputTargets - "
Jeff Brown46b9ac02010-04-22 18:58:52 -0700924 "resumeWithAppendedMotionSample=%s",
Jeff Brownb88102f2010-09-08 11:49:43 -0700925 toString(resumeWithAppendedMotionSample));
Jeff Brown46b9ac02010-04-22 18:58:52 -0700926#endif
927
Jeff Brown9c3cda02010-06-15 01:31:58 -0700928 assert(eventEntry->dispatchInProgress); // should already have been set to true
929
Jeff Browne2fe69e2010-10-18 13:21:23 -0700930 pokeUserActivityLocked(eventEntry);
931
Jeff Brown46b9ac02010-04-22 18:58:52 -0700932 for (size_t i = 0; i < mCurrentInputTargets.size(); i++) {
933 const InputTarget& inputTarget = mCurrentInputTargets.itemAt(i);
934
Jeff Brown519e0242010-09-15 15:18:56 -0700935 ssize_t connectionIndex = getConnectionIndexLocked(inputTarget.inputChannel);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700936 if (connectionIndex >= 0) {
937 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
Jeff Brown7fbdc842010-06-17 20:52:56 -0700938 prepareDispatchCycleLocked(currentTime, connection, eventEntry, & inputTarget,
Jeff Brown46b9ac02010-04-22 18:58:52 -0700939 resumeWithAppendedMotionSample);
940 } else {
Jeff Brownb6997262010-10-08 22:31:17 -0700941#if DEBUG_FOCUS
942 LOGD("Dropping event delivery to target with channel '%s' because it "
943 "is no longer registered with the input dispatcher.",
Jeff Brown46b9ac02010-04-22 18:58:52 -0700944 inputTarget.inputChannel->getName().string());
Jeff Brownb6997262010-10-08 22:31:17 -0700945#endif
Jeff Brown46b9ac02010-04-22 18:58:52 -0700946 }
947 }
948}
949
Jeff Brown54a18252010-09-16 14:07:33 -0700950void InputDispatcher::resetTargetsLocked() {
Jeff Brownb88102f2010-09-08 11:49:43 -0700951 mCurrentInputTargetsValid = false;
952 mCurrentInputTargets.clear();
Jeff Brownb88102f2010-09-08 11:49:43 -0700953 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_NONE;
Jeff Brown928e0542011-01-10 11:17:36 -0800954 mInputTargetWaitApplication.clear();
Jeff Brownb88102f2010-09-08 11:49:43 -0700955}
956
Jeff Brown01ce2e92010-09-26 22:20:12 -0700957void InputDispatcher::commitTargetsLocked() {
Jeff Brownb88102f2010-09-08 11:49:43 -0700958 mCurrentInputTargetsValid = true;
959}
960
961int32_t InputDispatcher::handleTargetsNotReadyLocked(nsecs_t currentTime,
962 const EventEntry* entry, const InputApplication* application, const InputWindow* window,
963 nsecs_t* nextWakeupTime) {
964 if (application == NULL && window == NULL) {
965 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY) {
966#if DEBUG_FOCUS
967 LOGD("Waiting for system to become ready for input.");
968#endif
969 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY;
970 mInputTargetWaitStartTime = currentTime;
971 mInputTargetWaitTimeoutTime = LONG_LONG_MAX;
972 mInputTargetWaitTimeoutExpired = false;
Jeff Brown928e0542011-01-10 11:17:36 -0800973 mInputTargetWaitApplication.clear();
Jeff Brownb88102f2010-09-08 11:49:43 -0700974 }
975 } else {
976 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
977#if DEBUG_FOCUS
Jeff Brown519e0242010-09-15 15:18:56 -0700978 LOGD("Waiting for application to become ready for input: %s",
979 getApplicationWindowLabelLocked(application, window).string());
Jeff Brownb88102f2010-09-08 11:49:43 -0700980#endif
981 nsecs_t timeout = window ? window->dispatchingTimeout :
982 application ? application->dispatchingTimeout : DEFAULT_INPUT_DISPATCHING_TIMEOUT;
983
984 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY;
985 mInputTargetWaitStartTime = currentTime;
986 mInputTargetWaitTimeoutTime = currentTime + timeout;
987 mInputTargetWaitTimeoutExpired = false;
Jeff Brown928e0542011-01-10 11:17:36 -0800988 mInputTargetWaitApplication.clear();
989
990 if (window && window->inputWindowHandle != NULL) {
991 mInputTargetWaitApplication =
992 window->inputWindowHandle->getInputApplicationHandle();
993 }
994 if (mInputTargetWaitApplication == NULL && application) {
995 mInputTargetWaitApplication = application->inputApplicationHandle;
996 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700997 }
998 }
999
1000 if (mInputTargetWaitTimeoutExpired) {
1001 return INPUT_EVENT_INJECTION_TIMED_OUT;
1002 }
1003
1004 if (currentTime >= mInputTargetWaitTimeoutTime) {
Jeff Brown519e0242010-09-15 15:18:56 -07001005 onANRLocked(currentTime, application, window, entry->eventTime, mInputTargetWaitStartTime);
Jeff Brownb88102f2010-09-08 11:49:43 -07001006
1007 // Force poll loop to wake up immediately on next iteration once we get the
1008 // ANR response back from the policy.
1009 *nextWakeupTime = LONG_LONG_MIN;
1010 return INPUT_EVENT_INJECTION_PENDING;
1011 } else {
1012 // Force poll loop to wake up when timeout is due.
1013 if (mInputTargetWaitTimeoutTime < *nextWakeupTime) {
1014 *nextWakeupTime = mInputTargetWaitTimeoutTime;
1015 }
1016 return INPUT_EVENT_INJECTION_PENDING;
1017 }
1018}
1019
Jeff Brown519e0242010-09-15 15:18:56 -07001020void InputDispatcher::resumeAfterTargetsNotReadyTimeoutLocked(nsecs_t newTimeout,
1021 const sp<InputChannel>& inputChannel) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001022 if (newTimeout > 0) {
1023 // Extend the timeout.
1024 mInputTargetWaitTimeoutTime = now() + newTimeout;
1025 } else {
1026 // Give up.
1027 mInputTargetWaitTimeoutExpired = true;
Jeff Brown519e0242010-09-15 15:18:56 -07001028
Jeff Brown01ce2e92010-09-26 22:20:12 -07001029 // Release the touch targets.
1030 mTouchState.reset();
Jeff Brown2a95c2a2010-09-16 12:31:46 -07001031
Jeff Brown519e0242010-09-15 15:18:56 -07001032 // Input state will not be realistic. Mark it out of sync.
Jeff Browndc3e0052010-09-16 11:02:16 -07001033 if (inputChannel.get()) {
1034 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
1035 if (connectionIndex >= 0) {
1036 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
Jeff Brown00045a72010-12-09 18:10:30 -08001037 if (connection->status == Connection::STATUS_NORMAL) {
1038 synthesizeCancelationEventsForConnectionLocked(
1039 connection, InputState::CANCEL_ALL_EVENTS,
1040 "application not responding");
1041 }
Jeff Browndc3e0052010-09-16 11:02:16 -07001042 }
Jeff Brown519e0242010-09-15 15:18:56 -07001043 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001044 }
1045}
1046
Jeff Brown519e0242010-09-15 15:18:56 -07001047nsecs_t InputDispatcher::getTimeSpentWaitingForApplicationLocked(
Jeff Brownb88102f2010-09-08 11:49:43 -07001048 nsecs_t currentTime) {
1049 if (mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
1050 return currentTime - mInputTargetWaitStartTime;
1051 }
1052 return 0;
1053}
1054
1055void InputDispatcher::resetANRTimeoutsLocked() {
1056#if DEBUG_FOCUS
1057 LOGD("Resetting ANR timeouts.");
1058#endif
1059
Jeff Brownb88102f2010-09-08 11:49:43 -07001060 // Reset input target wait timeout.
1061 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_NONE;
1062}
1063
Jeff Brown01ce2e92010-09-26 22:20:12 -07001064int32_t InputDispatcher::findFocusedWindowTargetsLocked(nsecs_t currentTime,
1065 const EventEntry* entry, nsecs_t* nextWakeupTime) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001066 mCurrentInputTargets.clear();
1067
1068 int32_t injectionResult;
1069
1070 // If there is no currently focused window and no focused application
1071 // then drop the event.
1072 if (! mFocusedWindow) {
1073 if (mFocusedApplication) {
1074#if DEBUG_FOCUS
1075 LOGD("Waiting because there is no focused window but there is a "
Jeff Brown519e0242010-09-15 15:18:56 -07001076 "focused application that may eventually add a window: %s.",
1077 getApplicationWindowLabelLocked(mFocusedApplication, NULL).string());
Jeff Brownb88102f2010-09-08 11:49:43 -07001078#endif
1079 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
1080 mFocusedApplication, NULL, nextWakeupTime);
1081 goto Unresponsive;
1082 }
1083
1084 LOGI("Dropping event because there is no focused window or focused application.");
1085 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1086 goto Failed;
1087 }
1088
1089 // Check permissions.
Jeff Brown01ce2e92010-09-26 22:20:12 -07001090 if (! checkInjectionPermission(mFocusedWindow, entry->injectionState)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001091 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1092 goto Failed;
1093 }
1094
1095 // If the currently focused window is paused then keep waiting.
1096 if (mFocusedWindow->paused) {
1097#if DEBUG_FOCUS
1098 LOGD("Waiting because focused window is paused.");
1099#endif
1100 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
1101 mFocusedApplication, mFocusedWindow, nextWakeupTime);
1102 goto Unresponsive;
1103 }
1104
Jeff Brown519e0242010-09-15 15:18:56 -07001105 // If the currently focused window is still working on previous events then keep waiting.
1106 if (! isWindowFinishedWithPreviousInputLocked(mFocusedWindow)) {
1107#if DEBUG_FOCUS
1108 LOGD("Waiting because focused window still processing previous input.");
1109#endif
1110 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
1111 mFocusedApplication, mFocusedWindow, nextWakeupTime);
1112 goto Unresponsive;
1113 }
1114
Jeff Brownb88102f2010-09-08 11:49:43 -07001115 // Success! Output targets.
1116 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001117 addWindowTargetLocked(mFocusedWindow, InputTarget::FLAG_FOREGROUND, BitSet32(0));
Jeff Brownb88102f2010-09-08 11:49:43 -07001118
1119 // Done.
1120Failed:
1121Unresponsive:
Jeff Brown519e0242010-09-15 15:18:56 -07001122 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
1123 updateDispatchStatisticsLocked(currentTime, entry,
1124 injectionResult, timeSpentWaitingForApplication);
Jeff Brownb88102f2010-09-08 11:49:43 -07001125#if DEBUG_FOCUS
Jeff Brown519e0242010-09-15 15:18:56 -07001126 LOGD("findFocusedWindow finished: injectionResult=%d, "
1127 "timeSpendWaitingForApplication=%0.1fms",
1128 injectionResult, timeSpentWaitingForApplication / 1000000.0);
Jeff Brownb88102f2010-09-08 11:49:43 -07001129#endif
1130 return injectionResult;
1131}
1132
Jeff Brown01ce2e92010-09-26 22:20:12 -07001133int32_t InputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime,
Jeff Browncc0c1592011-02-19 05:07:28 -08001134 const MotionEntry* entry, nsecs_t* nextWakeupTime, bool* outConflictingPointerActions) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001135 enum InjectionPermission {
1136 INJECTION_PERMISSION_UNKNOWN,
1137 INJECTION_PERMISSION_GRANTED,
1138 INJECTION_PERMISSION_DENIED
1139 };
1140
Jeff Brownb88102f2010-09-08 11:49:43 -07001141 mCurrentInputTargets.clear();
1142
1143 nsecs_t startTime = now();
1144
1145 // For security reasons, we defer updating the touch state until we are sure that
1146 // event injection will be allowed.
1147 //
1148 // FIXME In the original code, screenWasOff could never be set to true.
1149 // The reason is that the POLICY_FLAG_WOKE_HERE
1150 // and POLICY_FLAG_BRIGHT_HERE flags were set only when preprocessing raw
1151 // EV_KEY, EV_REL and EV_ABS events. As it happens, the touch event was
1152 // actually enqueued using the policyFlags that appeared in the final EV_SYN
1153 // events upon which no preprocessing took place. So policyFlags was always 0.
1154 // In the new native input dispatcher we're a bit more careful about event
1155 // preprocessing so the touches we receive can actually have non-zero policyFlags.
1156 // Unfortunately we obtain undesirable behavior.
1157 //
1158 // Here's what happens:
1159 //
1160 // When the device dims in anticipation of going to sleep, touches
1161 // in windows which have FLAG_TOUCHABLE_WHEN_WAKING cause
1162 // the device to brighten and reset the user activity timer.
1163 // Touches on other windows (such as the launcher window)
1164 // are dropped. Then after a moment, the device goes to sleep. Oops.
1165 //
1166 // Also notice how screenWasOff was being initialized using POLICY_FLAG_BRIGHT_HERE
1167 // instead of POLICY_FLAG_WOKE_HERE...
1168 //
1169 bool screenWasOff = false; // original policy: policyFlags & POLICY_FLAG_BRIGHT_HERE;
1170
1171 int32_t action = entry->action;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001172 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Jeff Brownb88102f2010-09-08 11:49:43 -07001173
1174 // Update the touch state as needed based on the properties of the touch event.
Jeff Brown01ce2e92010-09-26 22:20:12 -07001175 int32_t injectionResult = INPUT_EVENT_INJECTION_PENDING;
1176 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
Jeff Browncc0c1592011-02-19 05:07:28 -08001177
1178 bool isSplit = mTouchState.split;
1179 bool wrongDevice = mTouchState.down
1180 && (mTouchState.deviceId != entry->deviceId
1181 || mTouchState.source != entry->source);
1182 if (maskedAction == AMOTION_EVENT_ACTION_DOWN
Jeff Brown33bbfd22011-02-24 20:55:35 -08001183 || maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE
1184 || maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
Jeff Browncc0c1592011-02-19 05:07:28 -08001185 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
1186 if (wrongDevice && !down) {
1187 mTempTouchState.copyFrom(mTouchState);
1188 } else {
1189 mTempTouchState.reset();
1190 mTempTouchState.down = down;
1191 mTempTouchState.deviceId = entry->deviceId;
1192 mTempTouchState.source = entry->source;
1193 isSplit = false;
1194 wrongDevice = false;
1195 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001196 } else {
1197 mTempTouchState.copyFrom(mTouchState);
Jeff Browncc0c1592011-02-19 05:07:28 -08001198 }
1199 if (wrongDevice) {
Jeff Brown95712852011-01-04 19:41:59 -08001200#if DEBUG_INPUT_DISPATCHER_POLICY
Jeff Browncc0c1592011-02-19 05:07:28 -08001201 LOGD("Dropping event because a pointer for a different device is already down.");
Jeff Brown95712852011-01-04 19:41:59 -08001202#endif
Jeff Browncc0c1592011-02-19 05:07:28 -08001203 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1204 goto Failed;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001205 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001206
Jeff Brown01ce2e92010-09-26 22:20:12 -07001207 if (maskedAction == AMOTION_EVENT_ACTION_DOWN
Jeff Browncc0c1592011-02-19 05:07:28 -08001208 || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)
Jeff Brown33bbfd22011-02-24 20:55:35 -08001209 || maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE
1210 || maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
1211 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
Jeff Brownb88102f2010-09-08 11:49:43 -07001212
Jeff Brown01ce2e92010-09-26 22:20:12 -07001213 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Jeff Brown91c69ab2011-02-14 17:03:18 -08001214 int32_t x = int32_t(entry->firstSample.pointerCoords[pointerIndex].
Jeff Brownebbd5d12011-02-17 13:01:34 -08001215 getAxisValue(AMOTION_EVENT_AXIS_X));
Jeff Brown91c69ab2011-02-14 17:03:18 -08001216 int32_t y = int32_t(entry->firstSample.pointerCoords[pointerIndex].
Jeff Brownebbd5d12011-02-17 13:01:34 -08001217 getAxisValue(AMOTION_EVENT_AXIS_Y));
Jeff Brown01ce2e92010-09-26 22:20:12 -07001218 const InputWindow* newTouchedWindow = NULL;
1219 const InputWindow* topErrorWindow = NULL;
Jeff Brownb88102f2010-09-08 11:49:43 -07001220
1221 // Traverse windows from front to back to find touched window and outside targets.
1222 size_t numWindows = mWindows.size();
1223 for (size_t i = 0; i < numWindows; i++) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001224 const InputWindow* window = & mWindows.editItemAt(i);
Jeff Brownb88102f2010-09-08 11:49:43 -07001225 int32_t flags = window->layoutParamsFlags;
1226
1227 if (flags & InputWindow::FLAG_SYSTEM_ERROR) {
1228 if (! topErrorWindow) {
1229 topErrorWindow = window;
1230 }
1231 }
1232
1233 if (window->visible) {
1234 if (! (flags & InputWindow::FLAG_NOT_TOUCHABLE)) {
1235 bool isTouchModal = (flags & (InputWindow::FLAG_NOT_FOCUSABLE
1236 | InputWindow::FLAG_NOT_TOUCH_MODAL)) == 0;
Jeff Brownfbf09772011-01-16 14:06:57 -08001237 if (isTouchModal || window->touchableRegionContainsPoint(x, y)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001238 if (! screenWasOff || flags & InputWindow::FLAG_TOUCHABLE_WHEN_WAKING) {
1239 newTouchedWindow = window;
Jeff Brownb88102f2010-09-08 11:49:43 -07001240 }
1241 break; // found touched window, exit window loop
1242 }
1243 }
1244
Jeff Brown01ce2e92010-09-26 22:20:12 -07001245 if (maskedAction == AMOTION_EVENT_ACTION_DOWN
1246 && (flags & InputWindow::FLAG_WATCH_OUTSIDE_TOUCH)) {
Jeff Brown19dfc832010-10-05 12:26:23 -07001247 int32_t outsideTargetFlags = InputTarget::FLAG_OUTSIDE;
1248 if (isWindowObscuredAtPointLocked(window, x, y)) {
1249 outsideTargetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1250 }
1251
1252 mTempTouchState.addOrUpdateWindow(window, outsideTargetFlags, BitSet32(0));
Jeff Brownb88102f2010-09-08 11:49:43 -07001253 }
1254 }
1255 }
1256
1257 // If there is an error window but it is not taking focus (typically because
1258 // it is invisible) then wait for it. Any other focused window may in
1259 // fact be in ANR state.
1260 if (topErrorWindow && newTouchedWindow != topErrorWindow) {
1261#if DEBUG_FOCUS
1262 LOGD("Waiting because system error window is pending.");
1263#endif
1264 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
1265 NULL, NULL, nextWakeupTime);
1266 injectionPermission = INJECTION_PERMISSION_UNKNOWN;
1267 goto Unresponsive;
1268 }
1269
Jeff Brown01ce2e92010-09-26 22:20:12 -07001270 // Figure out whether splitting will be allowed for this window.
Jeff Brown46e75292010-11-10 16:53:45 -08001271 if (newTouchedWindow && newTouchedWindow->supportsSplitTouch()) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001272 // New window supports splitting.
1273 isSplit = true;
1274 } else if (isSplit) {
1275 // New window does not support splitting but we have already split events.
1276 // Assign the pointer to the first foreground window we find.
1277 // (May be NULL which is why we put this code block before the next check.)
1278 newTouchedWindow = mTempTouchState.getFirstForegroundWindow();
1279 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001280
Jeff Brownb88102f2010-09-08 11:49:43 -07001281 // If we did not find a touched window then fail.
1282 if (! newTouchedWindow) {
1283 if (mFocusedApplication) {
1284#if DEBUG_FOCUS
1285 LOGD("Waiting because there is no touched window but there is a "
Jeff Brown519e0242010-09-15 15:18:56 -07001286 "focused application that may eventually add a new window: %s.",
1287 getApplicationWindowLabelLocked(mFocusedApplication, NULL).string());
Jeff Brownb88102f2010-09-08 11:49:43 -07001288#endif
1289 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
1290 mFocusedApplication, NULL, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -07001291 goto Unresponsive;
1292 }
1293
1294 LOGI("Dropping event because there is no touched window or focused application.");
1295 injectionResult = INPUT_EVENT_INJECTION_FAILED;
Jeff Brownb88102f2010-09-08 11:49:43 -07001296 goto Failed;
1297 }
1298
Jeff Brown19dfc832010-10-05 12:26:23 -07001299 // Set target flags.
1300 int32_t targetFlags = InputTarget::FLAG_FOREGROUND;
1301 if (isSplit) {
1302 targetFlags |= InputTarget::FLAG_SPLIT;
1303 }
1304 if (isWindowObscuredAtPointLocked(newTouchedWindow, x, y)) {
1305 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1306 }
1307
Jeff Brown01ce2e92010-09-26 22:20:12 -07001308 // Update the temporary touch state.
1309 BitSet32 pointerIds;
1310 if (isSplit) {
1311 uint32_t pointerId = entry->pointerIds[pointerIndex];
1312 pointerIds.markBit(pointerId);
Jeff Brownb88102f2010-09-08 11:49:43 -07001313 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001314 mTempTouchState.addOrUpdateWindow(newTouchedWindow, targetFlags, pointerIds);
Jeff Brownb88102f2010-09-08 11:49:43 -07001315 } else {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001316 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
Jeff Brownb88102f2010-09-08 11:49:43 -07001317
1318 // If the pointer is not currently down, then ignore the event.
Jeff Brown01ce2e92010-09-26 22:20:12 -07001319 if (! mTempTouchState.down) {
Jeff Brown76860e32010-10-25 17:37:46 -07001320#if DEBUG_INPUT_DISPATCHER_POLICY
1321 LOGD("Dropping event because the pointer is not down or we previously "
1322 "dropped the pointer down event.");
1323#endif
Jeff Brownb88102f2010-09-08 11:49:43 -07001324 injectionResult = INPUT_EVENT_INJECTION_FAILED;
Jeff Brownb88102f2010-09-08 11:49:43 -07001325 goto Failed;
1326 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001327 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001328
Jeff Brown01ce2e92010-09-26 22:20:12 -07001329 // Check permission to inject into all touched foreground windows and ensure there
1330 // is at least one touched foreground window.
1331 {
1332 bool haveForegroundWindow = false;
1333 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1334 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1335 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1336 haveForegroundWindow = true;
1337 if (! checkInjectionPermission(touchedWindow.window, entry->injectionState)) {
1338 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1339 injectionPermission = INJECTION_PERMISSION_DENIED;
1340 goto Failed;
1341 }
1342 }
1343 }
1344 if (! haveForegroundWindow) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001345#if DEBUG_INPUT_DISPATCHER_POLICY
Jeff Brown01ce2e92010-09-26 22:20:12 -07001346 LOGD("Dropping event because there is no touched foreground window to receive it.");
Jeff Brownb88102f2010-09-08 11:49:43 -07001347#endif
1348 injectionResult = INPUT_EVENT_INJECTION_FAILED;
Jeff Brownb88102f2010-09-08 11:49:43 -07001349 goto Failed;
1350 }
1351
Jeff Brown01ce2e92010-09-26 22:20:12 -07001352 // Permission granted to injection into all touched foreground windows.
1353 injectionPermission = INJECTION_PERMISSION_GRANTED;
1354 }
Jeff Brown519e0242010-09-15 15:18:56 -07001355
Jeff Brown01ce2e92010-09-26 22:20:12 -07001356 // Ensure all touched foreground windows are ready for new input.
1357 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1358 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1359 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1360 // If the touched window is paused then keep waiting.
1361 if (touchedWindow.window->paused) {
1362#if DEBUG_INPUT_DISPATCHER_POLICY
1363 LOGD("Waiting because touched window is paused.");
Jeff Brown519e0242010-09-15 15:18:56 -07001364#endif
Jeff Brown01ce2e92010-09-26 22:20:12 -07001365 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
1366 NULL, touchedWindow.window, nextWakeupTime);
1367 goto Unresponsive;
1368 }
1369
1370 // If the touched window is still working on previous events then keep waiting.
1371 if (! isWindowFinishedWithPreviousInputLocked(touchedWindow.window)) {
1372#if DEBUG_FOCUS
1373 LOGD("Waiting because touched window still processing previous input.");
1374#endif
1375 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
1376 NULL, touchedWindow.window, nextWakeupTime);
1377 goto Unresponsive;
1378 }
1379 }
1380 }
1381
1382 // If this is the first pointer going down and the touched window has a wallpaper
1383 // then also add the touched wallpaper windows so they are locked in for the duration
1384 // of the touch gesture.
Jeff Brown33bbfd22011-02-24 20:55:35 -08001385 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
1386 // engine only supports touch events. We would need to add a mechanism similar
1387 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
1388 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001389 const InputWindow* foregroundWindow = mTempTouchState.getFirstForegroundWindow();
1390 if (foregroundWindow->hasWallpaper) {
1391 for (size_t i = 0; i < mWindows.size(); i++) {
1392 const InputWindow* window = & mWindows[i];
1393 if (window->layoutParamsType == InputWindow::TYPE_WALLPAPER) {
Jeff Brown19dfc832010-10-05 12:26:23 -07001394 mTempTouchState.addOrUpdateWindow(window,
1395 InputTarget::FLAG_WINDOW_IS_OBSCURED, BitSet32(0));
Jeff Brown01ce2e92010-09-26 22:20:12 -07001396 }
1397 }
1398 }
1399 }
1400
Jeff Brownb88102f2010-09-08 11:49:43 -07001401 // Success! Output targets.
1402 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
Jeff Brownb88102f2010-09-08 11:49:43 -07001403
Jeff Brown01ce2e92010-09-26 22:20:12 -07001404 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1405 const TouchedWindow& touchedWindow = mTempTouchState.windows.itemAt(i);
1406 addWindowTargetLocked(touchedWindow.window, touchedWindow.targetFlags,
1407 touchedWindow.pointerIds);
Jeff Brownb88102f2010-09-08 11:49:43 -07001408 }
1409
Jeff Brown01ce2e92010-09-26 22:20:12 -07001410 // Drop the outside touch window since we will not care about them in the next iteration.
1411 mTempTouchState.removeOutsideTouchWindows();
1412
Jeff Brownb88102f2010-09-08 11:49:43 -07001413Failed:
1414 // Check injection permission once and for all.
1415 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001416 if (checkInjectionPermission(NULL, entry->injectionState)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001417 injectionPermission = INJECTION_PERMISSION_GRANTED;
1418 } else {
1419 injectionPermission = INJECTION_PERMISSION_DENIED;
1420 }
1421 }
1422
1423 // Update final pieces of touch state if the injector had permission.
1424 if (injectionPermission == INJECTION_PERMISSION_GRANTED) {
Jeff Brown95712852011-01-04 19:41:59 -08001425 if (!wrongDevice) {
1426 if (maskedAction == AMOTION_EVENT_ACTION_UP
Jeff Browncc0c1592011-02-19 05:07:28 -08001427 || maskedAction == AMOTION_EVENT_ACTION_CANCEL
1428 || maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Jeff Brown95712852011-01-04 19:41:59 -08001429 // All pointers up or canceled.
Jeff Brown33bbfd22011-02-24 20:55:35 -08001430 mTouchState.reset();
Jeff Brown95712852011-01-04 19:41:59 -08001431 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1432 // First pointer went down.
1433 if (mTouchState.down) {
Jeff Browncc0c1592011-02-19 05:07:28 -08001434 *outConflictingPointerActions = true;
Jeff Brownb6997262010-10-08 22:31:17 -07001435#if DEBUG_FOCUS
Jeff Brown95712852011-01-04 19:41:59 -08001436 LOGD("Pointer down received while already down.");
Jeff Brownb6997262010-10-08 22:31:17 -07001437#endif
Jeff Brown95712852011-01-04 19:41:59 -08001438 }
Jeff Brown33bbfd22011-02-24 20:55:35 -08001439 mTouchState.copyFrom(mTempTouchState);
Jeff Brown95712852011-01-04 19:41:59 -08001440 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
1441 // One pointer went up.
1442 if (isSplit) {
1443 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
1444 uint32_t pointerId = entry->pointerIds[pointerIndex];
Jeff Brownb88102f2010-09-08 11:49:43 -07001445
Jeff Brown95712852011-01-04 19:41:59 -08001446 for (size_t i = 0; i < mTempTouchState.windows.size(); ) {
1447 TouchedWindow& touchedWindow = mTempTouchState.windows.editItemAt(i);
1448 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
1449 touchedWindow.pointerIds.clearBit(pointerId);
1450 if (touchedWindow.pointerIds.isEmpty()) {
1451 mTempTouchState.windows.removeAt(i);
1452 continue;
1453 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001454 }
Jeff Brown95712852011-01-04 19:41:59 -08001455 i += 1;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001456 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001457 }
Jeff Brown33bbfd22011-02-24 20:55:35 -08001458 mTouchState.copyFrom(mTempTouchState);
1459 } else if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
1460 // Discard temporary touch state since it was only valid for this action.
1461 } else {
1462 // Save changes to touch state as-is for all other actions.
1463 mTouchState.copyFrom(mTempTouchState);
Jeff Brownb88102f2010-09-08 11:49:43 -07001464 }
Jeff Brown95712852011-01-04 19:41:59 -08001465 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001466 } else {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001467#if DEBUG_FOCUS
1468 LOGD("Not updating touch focus because injection was denied.");
1469#endif
Jeff Brownb88102f2010-09-08 11:49:43 -07001470 }
1471
1472Unresponsive:
Jeff Brown120a4592010-10-27 18:43:51 -07001473 // Reset temporary touch state to ensure we release unnecessary references to input channels.
1474 mTempTouchState.reset();
1475
Jeff Brown519e0242010-09-15 15:18:56 -07001476 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
1477 updateDispatchStatisticsLocked(currentTime, entry,
1478 injectionResult, timeSpentWaitingForApplication);
Jeff Brownb88102f2010-09-08 11:49:43 -07001479#if DEBUG_FOCUS
Jeff Brown01ce2e92010-09-26 22:20:12 -07001480 LOGD("findTouchedWindow finished: injectionResult=%d, injectionPermission=%d, "
1481 "timeSpentWaitingForApplication=%0.1fms",
Jeff Brown519e0242010-09-15 15:18:56 -07001482 injectionResult, injectionPermission, timeSpentWaitingForApplication / 1000000.0);
Jeff Brownb88102f2010-09-08 11:49:43 -07001483#endif
1484 return injectionResult;
1485}
1486
Jeff Brown01ce2e92010-09-26 22:20:12 -07001487void InputDispatcher::addWindowTargetLocked(const InputWindow* window, int32_t targetFlags,
1488 BitSet32 pointerIds) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001489 mCurrentInputTargets.push();
1490
1491 InputTarget& target = mCurrentInputTargets.editTop();
1492 target.inputChannel = window->inputChannel;
1493 target.flags = targetFlags;
Jeff Brownb88102f2010-09-08 11:49:43 -07001494 target.xOffset = - window->frameLeft;
1495 target.yOffset = - window->frameTop;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001496 target.pointerIds = pointerIds;
Jeff Brownb88102f2010-09-08 11:49:43 -07001497}
1498
1499void InputDispatcher::addMonitoringTargetsLocked() {
1500 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
1501 mCurrentInputTargets.push();
1502
1503 InputTarget& target = mCurrentInputTargets.editTop();
1504 target.inputChannel = mMonitoringChannels[i];
1505 target.flags = 0;
Jeff Brownb88102f2010-09-08 11:49:43 -07001506 target.xOffset = 0;
1507 target.yOffset = 0;
1508 }
1509}
1510
1511bool InputDispatcher::checkInjectionPermission(const InputWindow* window,
Jeff Brown01ce2e92010-09-26 22:20:12 -07001512 const InjectionState* injectionState) {
1513 if (injectionState
Jeff Brownb6997262010-10-08 22:31:17 -07001514 && (window == NULL || window->ownerUid != injectionState->injectorUid)
1515 && !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
1516 if (window) {
1517 LOGW("Permission denied: injecting event from pid %d uid %d to window "
1518 "with input channel %s owned by uid %d",
1519 injectionState->injectorPid, injectionState->injectorUid,
1520 window->inputChannel->getName().string(),
1521 window->ownerUid);
1522 } else {
1523 LOGW("Permission denied: injecting event from pid %d uid %d",
1524 injectionState->injectorPid, injectionState->injectorUid);
Jeff Brownb88102f2010-09-08 11:49:43 -07001525 }
Jeff Brownb6997262010-10-08 22:31:17 -07001526 return false;
Jeff Brownb88102f2010-09-08 11:49:43 -07001527 }
1528 return true;
1529}
1530
Jeff Brown19dfc832010-10-05 12:26:23 -07001531bool InputDispatcher::isWindowObscuredAtPointLocked(
1532 const InputWindow* window, int32_t x, int32_t y) const {
Jeff Brownb88102f2010-09-08 11:49:43 -07001533 size_t numWindows = mWindows.size();
1534 for (size_t i = 0; i < numWindows; i++) {
1535 const InputWindow* other = & mWindows.itemAt(i);
1536 if (other == window) {
1537 break;
1538 }
Jeff Brown19dfc832010-10-05 12:26:23 -07001539 if (other->visible && ! other->isTrustedOverlay() && other->frameContainsPoint(x, y)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001540 return true;
1541 }
1542 }
1543 return false;
1544}
1545
Jeff Brown519e0242010-09-15 15:18:56 -07001546bool InputDispatcher::isWindowFinishedWithPreviousInputLocked(const InputWindow* window) {
1547 ssize_t connectionIndex = getConnectionIndexLocked(window->inputChannel);
1548 if (connectionIndex >= 0) {
1549 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
1550 return connection->outboundQueue.isEmpty();
1551 } else {
1552 return true;
1553 }
1554}
1555
1556String8 InputDispatcher::getApplicationWindowLabelLocked(const InputApplication* application,
1557 const InputWindow* window) {
1558 if (application) {
1559 if (window) {
1560 String8 label(application->name);
1561 label.append(" - ");
1562 label.append(window->name);
1563 return label;
1564 } else {
1565 return application->name;
1566 }
1567 } else if (window) {
1568 return window->name;
1569 } else {
1570 return String8("<unknown application or window>");
1571 }
1572}
1573
Jeff Browne2fe69e2010-10-18 13:21:23 -07001574void InputDispatcher::pokeUserActivityLocked(const EventEntry* eventEntry) {
1575 int32_t eventType = POWER_MANAGER_BUTTON_EVENT;
Jeff Brown4d396052010-10-29 21:50:21 -07001576 switch (eventEntry->type) {
1577 case EventEntry::TYPE_MOTION: {
Jeff Browne2fe69e2010-10-18 13:21:23 -07001578 const MotionEntry* motionEntry = static_cast<const MotionEntry*>(eventEntry);
Jeff Brown4d396052010-10-29 21:50:21 -07001579 if (motionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
1580 return;
1581 }
1582
Jeff Browne2fe69e2010-10-18 13:21:23 -07001583 if (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) {
Joe Onorato1a542c72010-11-08 09:48:20 -08001584 eventType = POWER_MANAGER_TOUCH_EVENT;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001585 }
Jeff Brown4d396052010-10-29 21:50:21 -07001586 break;
1587 }
1588 case EventEntry::TYPE_KEY: {
1589 const KeyEntry* keyEntry = static_cast<const KeyEntry*>(eventEntry);
1590 if (keyEntry->flags & AKEY_EVENT_FLAG_CANCELED) {
1591 return;
1592 }
1593 break;
1594 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001595 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001596
Jeff Brownb88102f2010-09-08 11:49:43 -07001597 CommandEntry* commandEntry = postCommandLocked(
1598 & InputDispatcher::doPokeUserActivityLockedInterruptible);
Jeff Browne2fe69e2010-10-18 13:21:23 -07001599 commandEntry->eventTime = eventEntry->eventTime;
Jeff Brownb88102f2010-09-08 11:49:43 -07001600 commandEntry->userActivityEventType = eventType;
1601}
1602
Jeff Brown7fbdc842010-06-17 20:52:56 -07001603void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
1604 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget,
Jeff Brown46b9ac02010-04-22 18:58:52 -07001605 bool resumeWithAppendedMotionSample) {
1606#if DEBUG_DISPATCH_CYCLE
Jeff Brown519e0242010-09-15 15:18:56 -07001607 LOGD("channel '%s' ~ prepareDispatchCycle - flags=%d, "
Jeff Brown01ce2e92010-09-26 22:20:12 -07001608 "xOffset=%f, yOffset=%f, "
Jeff Brown83c09682010-12-23 17:50:18 -08001609 "pointerIds=0x%x, "
Jeff Brown01ce2e92010-09-26 22:20:12 -07001610 "resumeWithAppendedMotionSample=%s",
Jeff Brown519e0242010-09-15 15:18:56 -07001611 connection->getInputChannelName(), inputTarget->flags,
Jeff Brown46b9ac02010-04-22 18:58:52 -07001612 inputTarget->xOffset, inputTarget->yOffset,
Jeff Brown83c09682010-12-23 17:50:18 -08001613 inputTarget->pointerIds.value,
Jeff Brownb88102f2010-09-08 11:49:43 -07001614 toString(resumeWithAppendedMotionSample));
Jeff Brown46b9ac02010-04-22 18:58:52 -07001615#endif
1616
Jeff Brown01ce2e92010-09-26 22:20:12 -07001617 // Make sure we are never called for streaming when splitting across multiple windows.
1618 bool isSplit = inputTarget->flags & InputTarget::FLAG_SPLIT;
1619 assert(! (resumeWithAppendedMotionSample && isSplit));
1620
Jeff Brown46b9ac02010-04-22 18:58:52 -07001621 // Skip this event if the connection status is not normal.
Jeff Brown519e0242010-09-15 15:18:56 -07001622 // We don't want to enqueue additional outbound events if the connection is broken.
Jeff Brown46b9ac02010-04-22 18:58:52 -07001623 if (connection->status != Connection::STATUS_NORMAL) {
Jeff Brownb6997262010-10-08 22:31:17 -07001624#if DEBUG_DISPATCH_CYCLE
1625 LOGD("channel '%s' ~ Dropping event because the channel status is %s",
Jeff Brownb88102f2010-09-08 11:49:43 -07001626 connection->getInputChannelName(), connection->getStatusLabel());
Jeff Brownb6997262010-10-08 22:31:17 -07001627#endif
Jeff Brown46b9ac02010-04-22 18:58:52 -07001628 return;
1629 }
1630
Jeff Brown01ce2e92010-09-26 22:20:12 -07001631 // Split a motion event if needed.
1632 if (isSplit) {
1633 assert(eventEntry->type == EventEntry::TYPE_MOTION);
1634
1635 MotionEntry* originalMotionEntry = static_cast<MotionEntry*>(eventEntry);
1636 if (inputTarget->pointerIds.count() != originalMotionEntry->pointerCount) {
1637 MotionEntry* splitMotionEntry = splitMotionEvent(
1638 originalMotionEntry, inputTarget->pointerIds);
Jeff Brown58a2da82011-01-25 16:02:22 -08001639 if (!splitMotionEntry) {
1640 return; // split event was dropped
1641 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001642#if DEBUG_FOCUS
1643 LOGD("channel '%s' ~ Split motion event.",
1644 connection->getInputChannelName());
1645 logOutboundMotionDetailsLocked(" ", splitMotionEntry);
1646#endif
1647 eventEntry = splitMotionEntry;
1648 }
1649 }
1650
Jeff Brown46b9ac02010-04-22 18:58:52 -07001651 // Resume the dispatch cycle with a freshly appended motion sample.
1652 // First we check that the last dispatch entry in the outbound queue is for the same
1653 // motion event to which we appended the motion sample. If we find such a dispatch
1654 // entry, and if it is currently in progress then we try to stream the new sample.
1655 bool wasEmpty = connection->outboundQueue.isEmpty();
1656
1657 if (! wasEmpty && resumeWithAppendedMotionSample) {
1658 DispatchEntry* motionEventDispatchEntry =
1659 connection->findQueuedDispatchEntryForEvent(eventEntry);
1660 if (motionEventDispatchEntry) {
1661 // If the dispatch entry is not in progress, then we must be busy dispatching an
1662 // earlier event. Not a problem, the motion event is on the outbound queue and will
1663 // be dispatched later.
1664 if (! motionEventDispatchEntry->inProgress) {
1665#if DEBUG_BATCHING
1666 LOGD("channel '%s' ~ Not streaming because the motion event has "
1667 "not yet been dispatched. "
1668 "(Waiting for earlier events to be consumed.)",
1669 connection->getInputChannelName());
1670#endif
1671 return;
1672 }
1673
1674 // If the dispatch entry is in progress but it already has a tail of pending
1675 // motion samples, then it must mean that the shared memory buffer filled up.
1676 // Not a problem, when this dispatch cycle is finished, we will eventually start
1677 // a new dispatch cycle to process the tail and that tail includes the newly
1678 // appended motion sample.
1679 if (motionEventDispatchEntry->tailMotionSample) {
1680#if DEBUG_BATCHING
1681 LOGD("channel '%s' ~ Not streaming because no new samples can "
1682 "be appended to the motion event in this dispatch cycle. "
1683 "(Waiting for next dispatch cycle to start.)",
1684 connection->getInputChannelName());
1685#endif
1686 return;
1687 }
1688
1689 // The dispatch entry is in progress and is still potentially open for streaming.
1690 // Try to stream the new motion sample. This might fail if the consumer has already
1691 // consumed the motion event (or if the channel is broken).
Jeff Brown01ce2e92010-09-26 22:20:12 -07001692 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
1693 MotionSample* appendedMotionSample = motionEntry->lastSample;
Jeff Brown46b9ac02010-04-22 18:58:52 -07001694 status_t status = connection->inputPublisher.appendMotionSample(
1695 appendedMotionSample->eventTime, appendedMotionSample->pointerCoords);
1696 if (status == OK) {
1697#if DEBUG_BATCHING
1698 LOGD("channel '%s' ~ Successfully streamed new motion sample.",
1699 connection->getInputChannelName());
1700#endif
1701 return;
1702 }
1703
1704#if DEBUG_BATCHING
1705 if (status == NO_MEMORY) {
1706 LOGD("channel '%s' ~ Could not append motion sample to currently "
1707 "dispatched move event because the shared memory buffer is full. "
1708 "(Waiting for next dispatch cycle to start.)",
1709 connection->getInputChannelName());
1710 } else if (status == status_t(FAILED_TRANSACTION)) {
1711 LOGD("channel '%s' ~ Could not append motion sample to currently "
Jeff Brown349703e2010-06-22 01:27:15 -07001712 "dispatched move event because the event has already been consumed. "
Jeff Brown46b9ac02010-04-22 18:58:52 -07001713 "(Waiting for next dispatch cycle to start.)",
1714 connection->getInputChannelName());
1715 } else {
1716 LOGD("channel '%s' ~ Could not append motion sample to currently "
1717 "dispatched move event due to an error, status=%d. "
1718 "(Waiting for next dispatch cycle to start.)",
1719 connection->getInputChannelName(), status);
1720 }
1721#endif
1722 // Failed to stream. Start a new tail of pending motion samples to dispatch
1723 // in the next cycle.
1724 motionEventDispatchEntry->tailMotionSample = appendedMotionSample;
1725 return;
1726 }
1727 }
1728
1729 // This is a new event.
1730 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Jeff Brownb88102f2010-09-08 11:49:43 -07001731 DispatchEntry* dispatchEntry = mAllocator.obtainDispatchEntry(eventEntry, // increments ref
Jeff Brown519e0242010-09-15 15:18:56 -07001732 inputTarget->flags, inputTarget->xOffset, inputTarget->yOffset);
1733 if (dispatchEntry->hasForegroundTarget()) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001734 incrementPendingForegroundDispatchesLocked(eventEntry);
Jeff Brown6ec402b2010-07-28 15:48:59 -07001735 }
1736
Jeff Brown46b9ac02010-04-22 18:58:52 -07001737 // Handle the case where we could not stream a new motion sample because the consumer has
1738 // already consumed the motion event (otherwise the corresponding dispatch entry would
1739 // still be in the outbound queue for this connection). We set the head motion sample
1740 // to the list starting with the newly appended motion sample.
1741 if (resumeWithAppendedMotionSample) {
1742#if DEBUG_BATCHING
1743 LOGD("channel '%s' ~ Preparing a new dispatch cycle for additional motion samples "
1744 "that cannot be streamed because the motion event has already been consumed.",
1745 connection->getInputChannelName());
1746#endif
1747 MotionSample* appendedMotionSample = static_cast<MotionEntry*>(eventEntry)->lastSample;
1748 dispatchEntry->headMotionSample = appendedMotionSample;
1749 }
1750
1751 // Enqueue the dispatch entry.
1752 connection->outboundQueue.enqueueAtTail(dispatchEntry);
1753
1754 // If the outbound queue was previously empty, start the dispatch cycle going.
1755 if (wasEmpty) {
Jeff Brown7fbdc842010-06-17 20:52:56 -07001756 activateConnectionLocked(connection.get());
Jeff Brown519e0242010-09-15 15:18:56 -07001757 startDispatchCycleLocked(currentTime, connection);
Jeff Brown46b9ac02010-04-22 18:58:52 -07001758 }
1759}
1760
Jeff Brown7fbdc842010-06-17 20:52:56 -07001761void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Jeff Brown519e0242010-09-15 15:18:56 -07001762 const sp<Connection>& connection) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07001763#if DEBUG_DISPATCH_CYCLE
1764 LOGD("channel '%s' ~ startDispatchCycle",
1765 connection->getInputChannelName());
1766#endif
1767
1768 assert(connection->status == Connection::STATUS_NORMAL);
1769 assert(! connection->outboundQueue.isEmpty());
1770
Jeff Brownb88102f2010-09-08 11:49:43 -07001771 DispatchEntry* dispatchEntry = connection->outboundQueue.headSentinel.next;
Jeff Brown46b9ac02010-04-22 18:58:52 -07001772 assert(! dispatchEntry->inProgress);
1773
Jeff Brownb88102f2010-09-08 11:49:43 -07001774 // Mark the dispatch entry as in progress.
1775 dispatchEntry->inProgress = true;
1776
1777 // Update the connection's input state.
Jeff Brown01ce2e92010-09-26 22:20:12 -07001778 EventEntry* eventEntry = dispatchEntry->eventEntry;
Jeff Browncc0c1592011-02-19 05:07:28 -08001779 connection->inputState.trackEvent(eventEntry);
Jeff Brown46b9ac02010-04-22 18:58:52 -07001780
1781 // Publish the event.
1782 status_t status;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001783 switch (eventEntry->type) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07001784 case EventEntry::TYPE_KEY: {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001785 KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
Jeff Brown46b9ac02010-04-22 18:58:52 -07001786
1787 // Apply target flags.
1788 int32_t action = keyEntry->action;
1789 int32_t flags = keyEntry->flags;
Jeff Brown46b9ac02010-04-22 18:58:52 -07001790
1791 // Publish the key event.
Jeff Brownc5ed5912010-07-14 18:48:53 -07001792 status = connection->inputPublisher.publishKeyEvent(keyEntry->deviceId, keyEntry->source,
Jeff Brown46b9ac02010-04-22 18:58:52 -07001793 action, flags, keyEntry->keyCode, keyEntry->scanCode,
1794 keyEntry->metaState, keyEntry->repeatCount, keyEntry->downTime,
1795 keyEntry->eventTime);
1796
1797 if (status) {
1798 LOGE("channel '%s' ~ Could not publish key event, "
1799 "status=%d", connection->getInputChannelName(), status);
Jeff Brownb6997262010-10-08 22:31:17 -07001800 abortBrokenDispatchCycleLocked(currentTime, connection);
Jeff Brown46b9ac02010-04-22 18:58:52 -07001801 return;
1802 }
1803 break;
1804 }
1805
1806 case EventEntry::TYPE_MOTION: {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001807 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
Jeff Brown46b9ac02010-04-22 18:58:52 -07001808
1809 // Apply target flags.
1810 int32_t action = motionEntry->action;
Jeff Brown85a31762010-09-01 17:01:00 -07001811 int32_t flags = motionEntry->flags;
Jeff Brown46b9ac02010-04-22 18:58:52 -07001812 if (dispatchEntry->targetFlags & InputTarget::FLAG_OUTSIDE) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001813 action = AMOTION_EVENT_ACTION_OUTSIDE;
Jeff Brown46b9ac02010-04-22 18:58:52 -07001814 }
Jeff Brown85a31762010-09-01 17:01:00 -07001815 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
1816 flags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
1817 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07001818
1819 // If headMotionSample is non-NULL, then it points to the first new sample that we
1820 // were unable to dispatch during the previous cycle so we resume dispatching from
1821 // that point in the list of motion samples.
1822 // Otherwise, we just start from the first sample of the motion event.
1823 MotionSample* firstMotionSample = dispatchEntry->headMotionSample;
1824 if (! firstMotionSample) {
1825 firstMotionSample = & motionEntry->firstSample;
1826 }
1827
Jeff Brownd3616592010-07-16 17:21:06 -07001828 // Set the X and Y offset depending on the input source.
1829 float xOffset, yOffset;
1830 if (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) {
1831 xOffset = dispatchEntry->xOffset;
1832 yOffset = dispatchEntry->yOffset;
1833 } else {
1834 xOffset = 0.0f;
1835 yOffset = 0.0f;
1836 }
1837
Jeff Brown46b9ac02010-04-22 18:58:52 -07001838 // Publish the motion event and the first motion sample.
1839 status = connection->inputPublisher.publishMotionEvent(motionEntry->deviceId,
Jeff Brown85a31762010-09-01 17:01:00 -07001840 motionEntry->source, action, flags, motionEntry->edgeFlags, motionEntry->metaState,
Jeff Brownd3616592010-07-16 17:21:06 -07001841 xOffset, yOffset,
Jeff Brown46b9ac02010-04-22 18:58:52 -07001842 motionEntry->xPrecision, motionEntry->yPrecision,
1843 motionEntry->downTime, firstMotionSample->eventTime,
1844 motionEntry->pointerCount, motionEntry->pointerIds,
1845 firstMotionSample->pointerCoords);
1846
1847 if (status) {
1848 LOGE("channel '%s' ~ Could not publish motion event, "
1849 "status=%d", connection->getInputChannelName(), status);
Jeff Brownb6997262010-10-08 22:31:17 -07001850 abortBrokenDispatchCycleLocked(currentTime, connection);
Jeff Brown46b9ac02010-04-22 18:58:52 -07001851 return;
1852 }
1853
1854 // Append additional motion samples.
1855 MotionSample* nextMotionSample = firstMotionSample->next;
1856 for (; nextMotionSample != NULL; nextMotionSample = nextMotionSample->next) {
1857 status = connection->inputPublisher.appendMotionSample(
1858 nextMotionSample->eventTime, nextMotionSample->pointerCoords);
1859 if (status == NO_MEMORY) {
1860#if DEBUG_DISPATCH_CYCLE
1861 LOGD("channel '%s' ~ Shared memory buffer full. Some motion samples will "
1862 "be sent in the next dispatch cycle.",
1863 connection->getInputChannelName());
1864#endif
1865 break;
1866 }
1867 if (status != OK) {
1868 LOGE("channel '%s' ~ Could not append motion sample "
1869 "for a reason other than out of memory, status=%d",
1870 connection->getInputChannelName(), status);
Jeff Brownb6997262010-10-08 22:31:17 -07001871 abortBrokenDispatchCycleLocked(currentTime, connection);
Jeff Brown46b9ac02010-04-22 18:58:52 -07001872 return;
1873 }
1874 }
1875
1876 // Remember the next motion sample that we could not dispatch, in case we ran out
1877 // of space in the shared memory buffer.
1878 dispatchEntry->tailMotionSample = nextMotionSample;
1879 break;
1880 }
1881
1882 default: {
1883 assert(false);
1884 }
1885 }
1886
1887 // Send the dispatch signal.
1888 status = connection->inputPublisher.sendDispatchSignal();
1889 if (status) {
1890 LOGE("channel '%s' ~ Could not send dispatch signal, status=%d",
1891 connection->getInputChannelName(), status);
Jeff Brownb6997262010-10-08 22:31:17 -07001892 abortBrokenDispatchCycleLocked(currentTime, connection);
Jeff Brown46b9ac02010-04-22 18:58:52 -07001893 return;
1894 }
1895
1896 // Record information about the newly started dispatch cycle.
Jeff Brown01ce2e92010-09-26 22:20:12 -07001897 connection->lastEventTime = eventEntry->eventTime;
Jeff Brown46b9ac02010-04-22 18:58:52 -07001898 connection->lastDispatchTime = currentTime;
1899
Jeff Brown46b9ac02010-04-22 18:58:52 -07001900 // Notify other system components.
1901 onDispatchCycleStartedLocked(currentTime, connection);
1902}
1903
Jeff Brown7fbdc842010-06-17 20:52:56 -07001904void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Jeff Brown3915bb82010-11-05 15:02:16 -07001905 const sp<Connection>& connection, bool handled) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07001906#if DEBUG_DISPATCH_CYCLE
Jeff Brown9c3cda02010-06-15 01:31:58 -07001907 LOGD("channel '%s' ~ finishDispatchCycle - %01.1fms since event, "
Jeff Brown3915bb82010-11-05 15:02:16 -07001908 "%01.1fms since dispatch, handled=%s",
Jeff Brown46b9ac02010-04-22 18:58:52 -07001909 connection->getInputChannelName(),
1910 connection->getEventLatencyMillis(currentTime),
Jeff Brown3915bb82010-11-05 15:02:16 -07001911 connection->getDispatchLatencyMillis(currentTime),
1912 toString(handled));
Jeff Brown46b9ac02010-04-22 18:58:52 -07001913#endif
1914
Jeff Brown9c3cda02010-06-15 01:31:58 -07001915 if (connection->status == Connection::STATUS_BROKEN
1916 || connection->status == Connection::STATUS_ZOMBIE) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07001917 return;
1918 }
1919
Jeff Brown46b9ac02010-04-22 18:58:52 -07001920 // Reset the publisher since the event has been consumed.
1921 // We do this now so that the publisher can release some of its internal resources
1922 // while waiting for the next dispatch cycle to begin.
1923 status_t status = connection->inputPublisher.reset();
1924 if (status) {
1925 LOGE("channel '%s' ~ Could not reset publisher, status=%d",
1926 connection->getInputChannelName(), status);
Jeff Brownb6997262010-10-08 22:31:17 -07001927 abortBrokenDispatchCycleLocked(currentTime, connection);
Jeff Brown46b9ac02010-04-22 18:58:52 -07001928 return;
1929 }
1930
Jeff Brown3915bb82010-11-05 15:02:16 -07001931 // Notify other system components and prepare to start the next dispatch cycle.
1932 onDispatchCycleFinishedLocked(currentTime, connection, handled);
Jeff Brownb88102f2010-09-08 11:49:43 -07001933}
1934
1935void InputDispatcher::startNextDispatchCycleLocked(nsecs_t currentTime,
1936 const sp<Connection>& connection) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07001937 // Start the next dispatch cycle for this connection.
1938 while (! connection->outboundQueue.isEmpty()) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001939 DispatchEntry* dispatchEntry = connection->outboundQueue.headSentinel.next;
Jeff Brown46b9ac02010-04-22 18:58:52 -07001940 if (dispatchEntry->inProgress) {
1941 // Finish or resume current event in progress.
1942 if (dispatchEntry->tailMotionSample) {
1943 // We have a tail of undispatched motion samples.
1944 // Reuse the same DispatchEntry and start a new cycle.
1945 dispatchEntry->inProgress = false;
1946 dispatchEntry->headMotionSample = dispatchEntry->tailMotionSample;
1947 dispatchEntry->tailMotionSample = NULL;
Jeff Brown519e0242010-09-15 15:18:56 -07001948 startDispatchCycleLocked(currentTime, connection);
Jeff Brown46b9ac02010-04-22 18:58:52 -07001949 return;
1950 }
1951 // Finished.
1952 connection->outboundQueue.dequeueAtHead();
Jeff Brown519e0242010-09-15 15:18:56 -07001953 if (dispatchEntry->hasForegroundTarget()) {
1954 decrementPendingForegroundDispatchesLocked(dispatchEntry->eventEntry);
Jeff Brown6ec402b2010-07-28 15:48:59 -07001955 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07001956 mAllocator.releaseDispatchEntry(dispatchEntry);
1957 } else {
1958 // If the head is not in progress, then we must have already dequeued the in
Jeff Brown519e0242010-09-15 15:18:56 -07001959 // progress event, which means we actually aborted it.
Jeff Brown46b9ac02010-04-22 18:58:52 -07001960 // So just start the next event for this connection.
Jeff Brown519e0242010-09-15 15:18:56 -07001961 startDispatchCycleLocked(currentTime, connection);
Jeff Brown46b9ac02010-04-22 18:58:52 -07001962 return;
1963 }
1964 }
1965
1966 // Outbound queue is empty, deactivate the connection.
Jeff Brown7fbdc842010-06-17 20:52:56 -07001967 deactivateConnectionLocked(connection.get());
Jeff Brown46b9ac02010-04-22 18:58:52 -07001968}
1969
Jeff Brownb6997262010-10-08 22:31:17 -07001970void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
1971 const sp<Connection>& connection) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07001972#if DEBUG_DISPATCH_CYCLE
Jeff Brown83c09682010-12-23 17:50:18 -08001973 LOGD("channel '%s' ~ abortBrokenDispatchCycle",
1974 connection->getInputChannelName());
Jeff Brown46b9ac02010-04-22 18:58:52 -07001975#endif
1976
Jeff Brownb88102f2010-09-08 11:49:43 -07001977 // Clear the outbound queue.
Jeff Brown519e0242010-09-15 15:18:56 -07001978 drainOutboundQueueLocked(connection.get());
Jeff Brown46b9ac02010-04-22 18:58:52 -07001979
Jeff Brownb6997262010-10-08 22:31:17 -07001980 // The connection appears to be unrecoverably broken.
Jeff Brown9c3cda02010-06-15 01:31:58 -07001981 // Ignore already broken or zombie connections.
Jeff Brownb6997262010-10-08 22:31:17 -07001982 if (connection->status == Connection::STATUS_NORMAL) {
1983 connection->status = Connection::STATUS_BROKEN;
Jeff Brown46b9ac02010-04-22 18:58:52 -07001984
Jeff Brownb6997262010-10-08 22:31:17 -07001985 // Notify other system components.
1986 onDispatchCycleBrokenLocked(currentTime, connection);
Jeff Brown46b9ac02010-04-22 18:58:52 -07001987 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07001988}
1989
Jeff Brown519e0242010-09-15 15:18:56 -07001990void InputDispatcher::drainOutboundQueueLocked(Connection* connection) {
1991 while (! connection->outboundQueue.isEmpty()) {
1992 DispatchEntry* dispatchEntry = connection->outboundQueue.dequeueAtHead();
1993 if (dispatchEntry->hasForegroundTarget()) {
1994 decrementPendingForegroundDispatchesLocked(dispatchEntry->eventEntry);
Jeff Brownb88102f2010-09-08 11:49:43 -07001995 }
1996 mAllocator.releaseDispatchEntry(dispatchEntry);
Jeff Brownb88102f2010-09-08 11:49:43 -07001997 }
1998
Jeff Brown519e0242010-09-15 15:18:56 -07001999 deactivateConnectionLocked(connection);
Jeff Brownb88102f2010-09-08 11:49:43 -07002000}
2001
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002002int InputDispatcher::handleReceiveCallback(int receiveFd, int events, void* data) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002003 InputDispatcher* d = static_cast<InputDispatcher*>(data);
2004
2005 { // acquire lock
2006 AutoMutex _l(d->mLock);
2007
2008 ssize_t connectionIndex = d->mConnectionsByReceiveFd.indexOfKey(receiveFd);
2009 if (connectionIndex < 0) {
2010 LOGE("Received spurious receive callback for unknown input channel. "
2011 "fd=%d, events=0x%x", receiveFd, events);
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002012 return 0; // remove the callback
Jeff Brown46b9ac02010-04-22 18:58:52 -07002013 }
2014
Jeff Brown7fbdc842010-06-17 20:52:56 -07002015 nsecs_t currentTime = now();
Jeff Brown46b9ac02010-04-22 18:58:52 -07002016
2017 sp<Connection> connection = d->mConnectionsByReceiveFd.valueAt(connectionIndex);
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002018 if (events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP)) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002019 LOGE("channel '%s' ~ Consumer closed input channel or an error occurred. "
2020 "events=0x%x", connection->getInputChannelName(), events);
Jeff Brownb6997262010-10-08 22:31:17 -07002021 d->abortBrokenDispatchCycleLocked(currentTime, connection);
Jeff Brown9c3cda02010-06-15 01:31:58 -07002022 d->runCommandsLockedInterruptible();
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002023 return 0; // remove the callback
Jeff Brown46b9ac02010-04-22 18:58:52 -07002024 }
2025
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002026 if (! (events & ALOOPER_EVENT_INPUT)) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002027 LOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
2028 "events=0x%x", connection->getInputChannelName(), events);
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002029 return 1;
Jeff Brown46b9ac02010-04-22 18:58:52 -07002030 }
2031
Jeff Brown3915bb82010-11-05 15:02:16 -07002032 bool handled = false;
Jeff Brown49ed71d2010-12-06 17:13:33 -08002033 status_t status = connection->inputPublisher.receiveFinishedSignal(&handled);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002034 if (status) {
2035 LOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
2036 connection->getInputChannelName(), status);
Jeff Brownb6997262010-10-08 22:31:17 -07002037 d->abortBrokenDispatchCycleLocked(currentTime, connection);
Jeff Brown9c3cda02010-06-15 01:31:58 -07002038 d->runCommandsLockedInterruptible();
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002039 return 0; // remove the callback
Jeff Brown46b9ac02010-04-22 18:58:52 -07002040 }
2041
Jeff Brown3915bb82010-11-05 15:02:16 -07002042 d->finishDispatchCycleLocked(currentTime, connection, handled);
Jeff Brown9c3cda02010-06-15 01:31:58 -07002043 d->runCommandsLockedInterruptible();
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002044 return 1;
Jeff Brown46b9ac02010-04-22 18:58:52 -07002045 } // release lock
2046}
2047
Jeff Brownb6997262010-10-08 22:31:17 -07002048void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
2049 InputState::CancelationOptions options, const char* reason) {
2050 for (size_t i = 0; i < mConnectionsByReceiveFd.size(); i++) {
2051 synthesizeCancelationEventsForConnectionLocked(
2052 mConnectionsByReceiveFd.valueAt(i), options, reason);
2053 }
2054}
2055
2056void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
2057 const sp<InputChannel>& channel, InputState::CancelationOptions options,
2058 const char* reason) {
2059 ssize_t index = getConnectionIndexLocked(channel);
2060 if (index >= 0) {
2061 synthesizeCancelationEventsForConnectionLocked(
2062 mConnectionsByReceiveFd.valueAt(index), options, reason);
2063 }
2064}
2065
2066void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
2067 const sp<Connection>& connection, InputState::CancelationOptions options,
2068 const char* reason) {
2069 nsecs_t currentTime = now();
2070
2071 mTempCancelationEvents.clear();
2072 connection->inputState.synthesizeCancelationEvents(currentTime, & mAllocator,
2073 mTempCancelationEvents, options);
2074
2075 if (! mTempCancelationEvents.isEmpty()
2076 && connection->status != Connection::STATUS_BROKEN) {
2077#if DEBUG_OUTBOUND_EVENT_DETAILS
2078 LOGD("channel '%s' ~ Synthesized %d cancelation events to bring channel back in sync "
2079 "with reality: %s, options=%d.",
2080 connection->getInputChannelName(), mTempCancelationEvents.size(), reason, options);
2081#endif
2082 for (size_t i = 0; i < mTempCancelationEvents.size(); i++) {
2083 EventEntry* cancelationEventEntry = mTempCancelationEvents.itemAt(i);
2084 switch (cancelationEventEntry->type) {
2085 case EventEntry::TYPE_KEY:
2086 logOutboundKeyDetailsLocked("cancel - ",
2087 static_cast<KeyEntry*>(cancelationEventEntry));
2088 break;
2089 case EventEntry::TYPE_MOTION:
2090 logOutboundMotionDetailsLocked("cancel - ",
2091 static_cast<MotionEntry*>(cancelationEventEntry));
2092 break;
2093 }
2094
2095 int32_t xOffset, yOffset;
2096 const InputWindow* window = getWindowLocked(connection->inputChannel);
2097 if (window) {
2098 xOffset = -window->frameLeft;
2099 yOffset = -window->frameTop;
2100 } else {
2101 xOffset = 0;
2102 yOffset = 0;
2103 }
2104
2105 DispatchEntry* cancelationDispatchEntry =
2106 mAllocator.obtainDispatchEntry(cancelationEventEntry, // increments ref
2107 0, xOffset, yOffset);
2108 connection->outboundQueue.enqueueAtTail(cancelationDispatchEntry);
2109
2110 mAllocator.releaseEventEntry(cancelationEventEntry);
2111 }
2112
2113 if (!connection->outboundQueue.headSentinel.next->inProgress) {
2114 startDispatchCycleLocked(currentTime, connection);
2115 }
2116 }
2117}
2118
Jeff Brown01ce2e92010-09-26 22:20:12 -07002119InputDispatcher::MotionEntry*
2120InputDispatcher::splitMotionEvent(const MotionEntry* originalMotionEntry, BitSet32 pointerIds) {
2121 assert(pointerIds.value != 0);
2122
2123 uint32_t splitPointerIndexMap[MAX_POINTERS];
2124 int32_t splitPointerIds[MAX_POINTERS];
2125 PointerCoords splitPointerCoords[MAX_POINTERS];
2126
2127 uint32_t originalPointerCount = originalMotionEntry->pointerCount;
2128 uint32_t splitPointerCount = 0;
2129
2130 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
2131 originalPointerIndex++) {
2132 int32_t pointerId = uint32_t(originalMotionEntry->pointerIds[originalPointerIndex]);
2133 if (pointerIds.hasBit(pointerId)) {
2134 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
2135 splitPointerIds[splitPointerCount] = pointerId;
2136 splitPointerCoords[splitPointerCount] =
2137 originalMotionEntry->firstSample.pointerCoords[originalPointerIndex];
2138 splitPointerCount += 1;
2139 }
2140 }
Jeff Brown58a2da82011-01-25 16:02:22 -08002141
2142 if (splitPointerCount != pointerIds.count()) {
2143 // This is bad. We are missing some of the pointers that we expected to deliver.
2144 // Most likely this indicates that we received an ACTION_MOVE events that has
2145 // different pointer ids than we expected based on the previous ACTION_DOWN
2146 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
2147 // in this way.
2148 LOGW("Dropping split motion event because the pointer count is %d but "
2149 "we expected there to be %d pointers. This probably means we received "
2150 "a broken sequence of pointer ids from the input device.",
2151 splitPointerCount, pointerIds.count());
2152 return NULL;
2153 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07002154
2155 int32_t action = originalMotionEntry->action;
2156 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
2157 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
2158 || maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2159 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
2160 int32_t pointerId = originalMotionEntry->pointerIds[originalPointerIndex];
2161 if (pointerIds.hasBit(pointerId)) {
2162 if (pointerIds.count() == 1) {
2163 // The first/last pointer went down/up.
2164 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
2165 ? AMOTION_EVENT_ACTION_DOWN : AMOTION_EVENT_ACTION_UP;
Jeff Brown9a01d052010-09-27 16:35:11 -07002166 } else {
2167 // A secondary pointer went down/up.
2168 uint32_t splitPointerIndex = 0;
2169 while (pointerId != splitPointerIds[splitPointerIndex]) {
2170 splitPointerIndex += 1;
2171 }
2172 action = maskedAction | (splitPointerIndex
2173 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002174 }
2175 } else {
2176 // An unrelated pointer changed.
2177 action = AMOTION_EVENT_ACTION_MOVE;
2178 }
2179 }
2180
2181 MotionEntry* splitMotionEntry = mAllocator.obtainMotionEntry(
2182 originalMotionEntry->eventTime,
2183 originalMotionEntry->deviceId,
2184 originalMotionEntry->source,
2185 originalMotionEntry->policyFlags,
2186 action,
2187 originalMotionEntry->flags,
2188 originalMotionEntry->metaState,
2189 originalMotionEntry->edgeFlags,
2190 originalMotionEntry->xPrecision,
2191 originalMotionEntry->yPrecision,
2192 originalMotionEntry->downTime,
2193 splitPointerCount, splitPointerIds, splitPointerCoords);
2194
2195 for (MotionSample* originalMotionSample = originalMotionEntry->firstSample.next;
2196 originalMotionSample != NULL; originalMotionSample = originalMotionSample->next) {
2197 for (uint32_t splitPointerIndex = 0; splitPointerIndex < splitPointerCount;
2198 splitPointerIndex++) {
2199 uint32_t originalPointerIndex = splitPointerIndexMap[splitPointerIndex];
2200 splitPointerCoords[splitPointerIndex] =
2201 originalMotionSample->pointerCoords[originalPointerIndex];
2202 }
2203
2204 mAllocator.appendMotionSample(splitMotionEntry, originalMotionSample->eventTime,
2205 splitPointerCoords);
2206 }
2207
2208 return splitMotionEntry;
2209}
2210
Jeff Brown9c3cda02010-06-15 01:31:58 -07002211void InputDispatcher::notifyConfigurationChanged(nsecs_t eventTime) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002212#if DEBUG_INBOUND_EVENT_DETAILS
Jeff Brown9c3cda02010-06-15 01:31:58 -07002213 LOGD("notifyConfigurationChanged - eventTime=%lld", eventTime);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002214#endif
2215
Jeff Brownb88102f2010-09-08 11:49:43 -07002216 bool needWake;
Jeff Brown46b9ac02010-04-22 18:58:52 -07002217 { // acquire lock
2218 AutoMutex _l(mLock);
2219
Jeff Brown7fbdc842010-06-17 20:52:56 -07002220 ConfigurationChangedEntry* newEntry = mAllocator.obtainConfigurationChangedEntry(eventTime);
Jeff Brownb88102f2010-09-08 11:49:43 -07002221 needWake = enqueueInboundEventLocked(newEntry);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002222 } // release lock
2223
Jeff Brownb88102f2010-09-08 11:49:43 -07002224 if (needWake) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002225 mLooper->wake();
Jeff Brown46b9ac02010-04-22 18:58:52 -07002226 }
2227}
2228
Jeff Brown58a2da82011-01-25 16:02:22 -08002229void InputDispatcher::notifyKey(nsecs_t eventTime, int32_t deviceId, uint32_t source,
Jeff Brown46b9ac02010-04-22 18:58:52 -07002230 uint32_t policyFlags, int32_t action, int32_t flags,
2231 int32_t keyCode, int32_t scanCode, int32_t metaState, nsecs_t downTime) {
2232#if DEBUG_INBOUND_EVENT_DETAILS
Jeff Brown90655042010-12-02 13:50:46 -08002233 LOGD("notifyKey - eventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, action=0x%x, "
Jeff Brown46b9ac02010-04-22 18:58:52 -07002234 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%lld",
Jeff Brownc5ed5912010-07-14 18:48:53 -07002235 eventTime, deviceId, source, policyFlags, action, flags,
Jeff Brown46b9ac02010-04-22 18:58:52 -07002236 keyCode, scanCode, metaState, downTime);
2237#endif
Jeff Brown01ce2e92010-09-26 22:20:12 -07002238 if (! validateKeyEvent(action)) {
2239 return;
2240 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002241
Jeff Brown1f245102010-11-18 20:53:46 -08002242 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
2243 policyFlags |= POLICY_FLAG_VIRTUAL;
2244 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
2245 }
2246
Jeff Browne20c9e02010-10-11 14:20:19 -07002247 policyFlags |= POLICY_FLAG_TRUSTED;
Jeff Brown1f245102010-11-18 20:53:46 -08002248
2249 KeyEvent event;
2250 event.initialize(deviceId, source, action, flags, keyCode, scanCode,
2251 metaState, 0, downTime, eventTime);
2252
2253 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
2254
2255 if (policyFlags & POLICY_FLAG_WOKE_HERE) {
2256 flags |= AKEY_EVENT_FLAG_WOKE_HERE;
2257 }
Jeff Brownb6997262010-10-08 22:31:17 -07002258
Jeff Brownb88102f2010-09-08 11:49:43 -07002259 bool needWake;
Jeff Brown46b9ac02010-04-22 18:58:52 -07002260 { // acquire lock
2261 AutoMutex _l(mLock);
2262
Jeff Brown7fbdc842010-06-17 20:52:56 -07002263 int32_t repeatCount = 0;
2264 KeyEntry* newEntry = mAllocator.obtainKeyEntry(eventTime,
Jeff Brownc5ed5912010-07-14 18:48:53 -07002265 deviceId, source, policyFlags, action, flags, keyCode, scanCode,
Jeff Brown7fbdc842010-06-17 20:52:56 -07002266 metaState, repeatCount, downTime);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002267
Jeff Brownb88102f2010-09-08 11:49:43 -07002268 needWake = enqueueInboundEventLocked(newEntry);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002269 } // release lock
2270
Jeff Brownb88102f2010-09-08 11:49:43 -07002271 if (needWake) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002272 mLooper->wake();
Jeff Brown46b9ac02010-04-22 18:58:52 -07002273 }
2274}
2275
Jeff Brown58a2da82011-01-25 16:02:22 -08002276void InputDispatcher::notifyMotion(nsecs_t eventTime, int32_t deviceId, uint32_t source,
Jeff Brown85a31762010-09-01 17:01:00 -07002277 uint32_t policyFlags, int32_t action, int32_t flags, int32_t metaState, int32_t edgeFlags,
Jeff Brown46b9ac02010-04-22 18:58:52 -07002278 uint32_t pointerCount, const int32_t* pointerIds, const PointerCoords* pointerCoords,
2279 float xPrecision, float yPrecision, nsecs_t downTime) {
2280#if DEBUG_INBOUND_EVENT_DETAILS
Jeff Brown90655042010-12-02 13:50:46 -08002281 LOGD("notifyMotion - eventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, "
Jeff Brown85a31762010-09-01 17:01:00 -07002282 "action=0x%x, flags=0x%x, metaState=0x%x, edgeFlags=0x%x, "
2283 "xPrecision=%f, yPrecision=%f, downTime=%lld",
2284 eventTime, deviceId, source, policyFlags, action, flags, metaState, edgeFlags,
Jeff Brown46b9ac02010-04-22 18:58:52 -07002285 xPrecision, yPrecision, downTime);
2286 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brown8d608662010-08-30 03:02:23 -07002287 LOGD(" Pointer %d: id=%d, x=%f, y=%f, pressure=%f, size=%f, "
Jeff Brown85a31762010-09-01 17:01:00 -07002288 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
Jeff Brown8d608662010-08-30 03:02:23 -07002289 "orientation=%f",
Jeff Brown91c69ab2011-02-14 17:03:18 -08002290 i, pointerIds[i],
Jeff Brownebbd5d12011-02-17 13:01:34 -08002291 pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
2292 pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
2293 pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
2294 pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
2295 pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
2296 pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
2297 pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
2298 pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
2299 pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Jeff Brown46b9ac02010-04-22 18:58:52 -07002300 }
2301#endif
Jeff Brown01ce2e92010-09-26 22:20:12 -07002302 if (! validateMotionEvent(action, pointerCount, pointerIds)) {
2303 return;
2304 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002305
Jeff Browne20c9e02010-10-11 14:20:19 -07002306 policyFlags |= POLICY_FLAG_TRUSTED;
Jeff Brownb6997262010-10-08 22:31:17 -07002307 mPolicy->interceptGenericBeforeQueueing(eventTime, /*byref*/ policyFlags);
2308
Jeff Brownb88102f2010-09-08 11:49:43 -07002309 bool needWake;
Jeff Brown46b9ac02010-04-22 18:58:52 -07002310 { // acquire lock
2311 AutoMutex _l(mLock);
2312
2313 // Attempt batching and streaming of move events.
Jeff Browncc0c1592011-02-19 05:07:28 -08002314 if (action == AMOTION_EVENT_ACTION_MOVE
2315 || action == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002316 // BATCHING CASE
2317 //
2318 // Try to append a move sample to the tail of the inbound queue for this device.
2319 // Give up if we encounter a non-move motion event for this device since that
2320 // means we cannot append any new samples until a new motion event has started.
Jeff Brownb88102f2010-09-08 11:49:43 -07002321 for (EventEntry* entry = mInboundQueue.tailSentinel.prev;
2322 entry != & mInboundQueue.headSentinel; entry = entry->prev) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002323 if (entry->type != EventEntry::TYPE_MOTION) {
2324 // Keep looking for motion events.
2325 continue;
2326 }
2327
2328 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
2329 if (motionEntry->deviceId != deviceId) {
2330 // Keep looking for this device.
2331 continue;
2332 }
2333
Jeff Browncc0c1592011-02-19 05:07:28 -08002334 if (motionEntry->action != action
Jeff Brown58a2da82011-01-25 16:02:22 -08002335 || motionEntry->source != source
Jeff Brown7fbdc842010-06-17 20:52:56 -07002336 || motionEntry->pointerCount != pointerCount
2337 || motionEntry->isInjected()) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002338 // Last motion event in the queue for this device is not compatible for
2339 // appending new samples. Stop here.
2340 goto NoBatchingOrStreaming;
2341 }
2342
2343 // The last motion event is a move and is compatible for appending.
Jeff Brown9c3cda02010-06-15 01:31:58 -07002344 // Do the batching magic.
Jeff Brown7fbdc842010-06-17 20:52:56 -07002345 mAllocator.appendMotionSample(motionEntry, eventTime, pointerCoords);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002346#if DEBUG_BATCHING
2347 LOGD("Appended motion sample onto batch for most recent "
2348 "motion event for this device in the inbound queue.");
2349#endif
Jeff Brown9c3cda02010-06-15 01:31:58 -07002350 return; // done!
Jeff Brown46b9ac02010-04-22 18:58:52 -07002351 }
2352
2353 // STREAMING CASE
2354 //
2355 // There is no pending motion event (of any kind) for this device in the inbound queue.
Jeff Brown519e0242010-09-15 15:18:56 -07002356 // Search the outbound queue for the current foreground targets to find a dispatched
2357 // motion event that is still in progress. If found, then, appen the new sample to
2358 // that event and push it out to all current targets. The logic in
2359 // prepareDispatchCycleLocked takes care of the case where some targets may
2360 // already have consumed the motion event by starting a new dispatch cycle if needed.
Jeff Brown9c3cda02010-06-15 01:31:58 -07002361 if (mCurrentInputTargetsValid) {
Jeff Brown519e0242010-09-15 15:18:56 -07002362 for (size_t i = 0; i < mCurrentInputTargets.size(); i++) {
2363 const InputTarget& inputTarget = mCurrentInputTargets[i];
2364 if ((inputTarget.flags & InputTarget::FLAG_FOREGROUND) == 0) {
2365 // Skip non-foreground targets. We only want to stream if there is at
2366 // least one foreground target whose dispatch is still in progress.
2367 continue;
Jeff Brown46b9ac02010-04-22 18:58:52 -07002368 }
Jeff Brown519e0242010-09-15 15:18:56 -07002369
2370 ssize_t connectionIndex = getConnectionIndexLocked(inputTarget.inputChannel);
2371 if (connectionIndex < 0) {
2372 // Connection must no longer be valid.
2373 continue;
2374 }
2375
2376 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
2377 if (connection->outboundQueue.isEmpty()) {
2378 // This foreground target has an empty outbound queue.
2379 continue;
2380 }
2381
2382 DispatchEntry* dispatchEntry = connection->outboundQueue.headSentinel.next;
2383 if (! dispatchEntry->inProgress
Jeff Brown01ce2e92010-09-26 22:20:12 -07002384 || dispatchEntry->eventEntry->type != EventEntry::TYPE_MOTION
2385 || dispatchEntry->isSplit()) {
2386 // No motion event is being dispatched, or it is being split across
2387 // windows in which case we cannot stream.
Jeff Brown519e0242010-09-15 15:18:56 -07002388 continue;
2389 }
2390
2391 MotionEntry* motionEntry = static_cast<MotionEntry*>(
2392 dispatchEntry->eventEntry);
Jeff Browncc0c1592011-02-19 05:07:28 -08002393 if (motionEntry->action != action
Jeff Brown519e0242010-09-15 15:18:56 -07002394 || motionEntry->deviceId != deviceId
Jeff Brown58a2da82011-01-25 16:02:22 -08002395 || motionEntry->source != source
Jeff Brown519e0242010-09-15 15:18:56 -07002396 || motionEntry->pointerCount != pointerCount
2397 || motionEntry->isInjected()) {
2398 // The motion event is not compatible with this move.
2399 continue;
2400 }
2401
2402 // Hurray! This foreground target is currently dispatching a move event
2403 // that we can stream onto. Append the motion sample and resume dispatch.
2404 mAllocator.appendMotionSample(motionEntry, eventTime, pointerCoords);
2405#if DEBUG_BATCHING
2406 LOGD("Appended motion sample onto batch for most recently dispatched "
2407 "motion event for this device in the outbound queues. "
2408 "Attempting to stream the motion sample.");
2409#endif
2410 nsecs_t currentTime = now();
2411 dispatchEventToCurrentInputTargetsLocked(currentTime, motionEntry,
2412 true /*resumeWithAppendedMotionSample*/);
2413
2414 runCommandsLockedInterruptible();
2415 return; // done!
Jeff Brown46b9ac02010-04-22 18:58:52 -07002416 }
2417 }
2418
2419NoBatchingOrStreaming:;
2420 }
2421
2422 // Just enqueue a new motion event.
Jeff Brown7fbdc842010-06-17 20:52:56 -07002423 MotionEntry* newEntry = mAllocator.obtainMotionEntry(eventTime,
Jeff Brown85a31762010-09-01 17:01:00 -07002424 deviceId, source, policyFlags, action, flags, metaState, edgeFlags,
Jeff Brown7fbdc842010-06-17 20:52:56 -07002425 xPrecision, yPrecision, downTime,
2426 pointerCount, pointerIds, pointerCoords);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002427
Jeff Brownb88102f2010-09-08 11:49:43 -07002428 needWake = enqueueInboundEventLocked(newEntry);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002429 } // release lock
2430
Jeff Brownb88102f2010-09-08 11:49:43 -07002431 if (needWake) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002432 mLooper->wake();
Jeff Brown46b9ac02010-04-22 18:58:52 -07002433 }
2434}
2435
Jeff Brownb6997262010-10-08 22:31:17 -07002436void InputDispatcher::notifySwitch(nsecs_t when, int32_t switchCode, int32_t switchValue,
2437 uint32_t policyFlags) {
2438#if DEBUG_INBOUND_EVENT_DETAILS
2439 LOGD("notifySwitch - switchCode=%d, switchValue=%d, policyFlags=0x%x",
2440 switchCode, switchValue, policyFlags);
2441#endif
2442
Jeff Browne20c9e02010-10-11 14:20:19 -07002443 policyFlags |= POLICY_FLAG_TRUSTED;
Jeff Brownb6997262010-10-08 22:31:17 -07002444 mPolicy->notifySwitch(when, switchCode, switchValue, policyFlags);
2445}
2446
Jeff Brown7fbdc842010-06-17 20:52:56 -07002447int32_t InputDispatcher::injectInputEvent(const InputEvent* event,
Jeff Brown6ec402b2010-07-28 15:48:59 -07002448 int32_t injectorPid, int32_t injectorUid, int32_t syncMode, int32_t timeoutMillis) {
Jeff Brown7fbdc842010-06-17 20:52:56 -07002449#if DEBUG_INBOUND_EVENT_DETAILS
2450 LOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Jeff Brown6ec402b2010-07-28 15:48:59 -07002451 "syncMode=%d, timeoutMillis=%d",
2452 event->getType(), injectorPid, injectorUid, syncMode, timeoutMillis);
Jeff Brown7fbdc842010-06-17 20:52:56 -07002453#endif
2454
2455 nsecs_t endTime = now() + milliseconds_to_nanoseconds(timeoutMillis);
Jeff Browne20c9e02010-10-11 14:20:19 -07002456
2457 uint32_t policyFlags = POLICY_FLAG_INJECTED;
2458 if (hasInjectionPermission(injectorPid, injectorUid)) {
2459 policyFlags |= POLICY_FLAG_TRUSTED;
2460 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07002461
Jeff Brownb6997262010-10-08 22:31:17 -07002462 EventEntry* injectedEntry;
2463 switch (event->getType()) {
2464 case AINPUT_EVENT_TYPE_KEY: {
2465 const KeyEvent* keyEvent = static_cast<const KeyEvent*>(event);
2466 int32_t action = keyEvent->getAction();
2467 if (! validateKeyEvent(action)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07002468 return INPUT_EVENT_INJECTION_FAILED;
2469 }
2470
Jeff Brownb6997262010-10-08 22:31:17 -07002471 int32_t flags = keyEvent->getFlags();
Jeff Brown1f245102010-11-18 20:53:46 -08002472 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
2473 policyFlags |= POLICY_FLAG_VIRTUAL;
2474 }
2475
2476 mPolicy->interceptKeyBeforeQueueing(keyEvent, /*byref*/ policyFlags);
2477
2478 if (policyFlags & POLICY_FLAG_WOKE_HERE) {
2479 flags |= AKEY_EVENT_FLAG_WOKE_HERE;
2480 }
Jeff Brown6ec402b2010-07-28 15:48:59 -07002481
Jeff Brownb6997262010-10-08 22:31:17 -07002482 mLock.lock();
Jeff Brown1f245102010-11-18 20:53:46 -08002483 injectedEntry = mAllocator.obtainKeyEntry(keyEvent->getEventTime(),
2484 keyEvent->getDeviceId(), keyEvent->getSource(),
2485 policyFlags, action, flags,
2486 keyEvent->getKeyCode(), keyEvent->getScanCode(), keyEvent->getMetaState(),
Jeff Brownb6997262010-10-08 22:31:17 -07002487 keyEvent->getRepeatCount(), keyEvent->getDownTime());
2488 break;
2489 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07002490
Jeff Brownb6997262010-10-08 22:31:17 -07002491 case AINPUT_EVENT_TYPE_MOTION: {
2492 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
2493 int32_t action = motionEvent->getAction();
2494 size_t pointerCount = motionEvent->getPointerCount();
2495 const int32_t* pointerIds = motionEvent->getPointerIds();
2496 if (! validateMotionEvent(action, pointerCount, pointerIds)) {
2497 return INPUT_EVENT_INJECTION_FAILED;
2498 }
2499
2500 nsecs_t eventTime = motionEvent->getEventTime();
Jeff Browne20c9e02010-10-11 14:20:19 -07002501 mPolicy->interceptGenericBeforeQueueing(eventTime, /*byref*/ policyFlags);
Jeff Brownb6997262010-10-08 22:31:17 -07002502
2503 mLock.lock();
2504 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
2505 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
2506 MotionEntry* motionEntry = mAllocator.obtainMotionEntry(*sampleEventTimes,
2507 motionEvent->getDeviceId(), motionEvent->getSource(), policyFlags,
2508 action, motionEvent->getFlags(),
2509 motionEvent->getMetaState(), motionEvent->getEdgeFlags(),
2510 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
2511 motionEvent->getDownTime(), uint32_t(pointerCount),
2512 pointerIds, samplePointerCoords);
2513 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
2514 sampleEventTimes += 1;
2515 samplePointerCoords += pointerCount;
2516 mAllocator.appendMotionSample(motionEntry, *sampleEventTimes, samplePointerCoords);
2517 }
2518 injectedEntry = motionEntry;
2519 break;
2520 }
2521
2522 default:
2523 LOGW("Cannot inject event of type %d", event->getType());
2524 return INPUT_EVENT_INJECTION_FAILED;
2525 }
2526
2527 InjectionState* injectionState = mAllocator.obtainInjectionState(injectorPid, injectorUid);
2528 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
2529 injectionState->injectionIsAsync = true;
2530 }
2531
2532 injectionState->refCount += 1;
2533 injectedEntry->injectionState = injectionState;
2534
2535 bool needWake = enqueueInboundEventLocked(injectedEntry);
2536 mLock.unlock();
Jeff Brown7fbdc842010-06-17 20:52:56 -07002537
Jeff Brownb88102f2010-09-08 11:49:43 -07002538 if (needWake) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002539 mLooper->wake();
Jeff Brown7fbdc842010-06-17 20:52:56 -07002540 }
2541
2542 int32_t injectionResult;
2543 { // acquire lock
2544 AutoMutex _l(mLock);
2545
Jeff Brown6ec402b2010-07-28 15:48:59 -07002546 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
2547 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
2548 } else {
2549 for (;;) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002550 injectionResult = injectionState->injectionResult;
Jeff Brown6ec402b2010-07-28 15:48:59 -07002551 if (injectionResult != INPUT_EVENT_INJECTION_PENDING) {
2552 break;
2553 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07002554
Jeff Brown7fbdc842010-06-17 20:52:56 -07002555 nsecs_t remainingTimeout = endTime - now();
2556 if (remainingTimeout <= 0) {
Jeff Brown6ec402b2010-07-28 15:48:59 -07002557#if DEBUG_INJECTION
2558 LOGD("injectInputEvent - Timed out waiting for injection result "
2559 "to become available.");
2560#endif
Jeff Brown7fbdc842010-06-17 20:52:56 -07002561 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
2562 break;
2563 }
2564
Jeff Brown6ec402b2010-07-28 15:48:59 -07002565 mInjectionResultAvailableCondition.waitRelative(mLock, remainingTimeout);
2566 }
2567
2568 if (injectionResult == INPUT_EVENT_INJECTION_SUCCEEDED
2569 && syncMode == INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002570 while (injectionState->pendingForegroundDispatches != 0) {
Jeff Brown6ec402b2010-07-28 15:48:59 -07002571#if DEBUG_INJECTION
Jeff Brown519e0242010-09-15 15:18:56 -07002572 LOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
Jeff Brown01ce2e92010-09-26 22:20:12 -07002573 injectionState->pendingForegroundDispatches);
Jeff Brown6ec402b2010-07-28 15:48:59 -07002574#endif
2575 nsecs_t remainingTimeout = endTime - now();
2576 if (remainingTimeout <= 0) {
2577#if DEBUG_INJECTION
Jeff Brown519e0242010-09-15 15:18:56 -07002578 LOGD("injectInputEvent - Timed out waiting for pending foreground "
Jeff Brown6ec402b2010-07-28 15:48:59 -07002579 "dispatches to finish.");
2580#endif
2581 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
2582 break;
2583 }
2584
2585 mInjectionSyncFinishedCondition.waitRelative(mLock, remainingTimeout);
2586 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07002587 }
2588 }
2589
Jeff Brown01ce2e92010-09-26 22:20:12 -07002590 mAllocator.releaseInjectionState(injectionState);
Jeff Brown7fbdc842010-06-17 20:52:56 -07002591 } // release lock
2592
Jeff Brown6ec402b2010-07-28 15:48:59 -07002593#if DEBUG_INJECTION
2594 LOGD("injectInputEvent - Finished with result %d. "
2595 "injectorPid=%d, injectorUid=%d",
2596 injectionResult, injectorPid, injectorUid);
2597#endif
2598
Jeff Brown7fbdc842010-06-17 20:52:56 -07002599 return injectionResult;
2600}
2601
Jeff Brownb6997262010-10-08 22:31:17 -07002602bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
2603 return injectorUid == 0
2604 || mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
2605}
2606
Jeff Brown7fbdc842010-06-17 20:52:56 -07002607void InputDispatcher::setInjectionResultLocked(EventEntry* entry, int32_t injectionResult) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002608 InjectionState* injectionState = entry->injectionState;
2609 if (injectionState) {
Jeff Brown7fbdc842010-06-17 20:52:56 -07002610#if DEBUG_INJECTION
2611 LOGD("Setting input event injection result to %d. "
2612 "injectorPid=%d, injectorUid=%d",
Jeff Brown01ce2e92010-09-26 22:20:12 -07002613 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
Jeff Brown7fbdc842010-06-17 20:52:56 -07002614#endif
2615
Jeff Brown01ce2e92010-09-26 22:20:12 -07002616 if (injectionState->injectionIsAsync) {
Jeff Brown6ec402b2010-07-28 15:48:59 -07002617 // Log the outcome since the injector did not wait for the injection result.
2618 switch (injectionResult) {
2619 case INPUT_EVENT_INJECTION_SUCCEEDED:
2620 LOGV("Asynchronous input event injection succeeded.");
2621 break;
2622 case INPUT_EVENT_INJECTION_FAILED:
2623 LOGW("Asynchronous input event injection failed.");
2624 break;
2625 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
2626 LOGW("Asynchronous input event injection permission denied.");
2627 break;
2628 case INPUT_EVENT_INJECTION_TIMED_OUT:
2629 LOGW("Asynchronous input event injection timed out.");
2630 break;
2631 }
2632 }
2633
Jeff Brown01ce2e92010-09-26 22:20:12 -07002634 injectionState->injectionResult = injectionResult;
Jeff Brown7fbdc842010-06-17 20:52:56 -07002635 mInjectionResultAvailableCondition.broadcast();
2636 }
2637}
2638
Jeff Brown01ce2e92010-09-26 22:20:12 -07002639void InputDispatcher::incrementPendingForegroundDispatchesLocked(EventEntry* entry) {
2640 InjectionState* injectionState = entry->injectionState;
2641 if (injectionState) {
2642 injectionState->pendingForegroundDispatches += 1;
2643 }
2644}
2645
Jeff Brown519e0242010-09-15 15:18:56 -07002646void InputDispatcher::decrementPendingForegroundDispatchesLocked(EventEntry* entry) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002647 InjectionState* injectionState = entry->injectionState;
2648 if (injectionState) {
2649 injectionState->pendingForegroundDispatches -= 1;
Jeff Brown6ec402b2010-07-28 15:48:59 -07002650
Jeff Brown01ce2e92010-09-26 22:20:12 -07002651 if (injectionState->pendingForegroundDispatches == 0) {
2652 mInjectionSyncFinishedCondition.broadcast();
2653 }
Jeff Brownb88102f2010-09-08 11:49:43 -07002654 }
2655}
2656
Jeff Brown01ce2e92010-09-26 22:20:12 -07002657const InputWindow* InputDispatcher::getWindowLocked(const sp<InputChannel>& inputChannel) {
2658 for (size_t i = 0; i < mWindows.size(); i++) {
2659 const InputWindow* window = & mWindows[i];
2660 if (window->inputChannel == inputChannel) {
2661 return window;
2662 }
2663 }
2664 return NULL;
2665}
2666
Jeff Brownb88102f2010-09-08 11:49:43 -07002667void InputDispatcher::setInputWindows(const Vector<InputWindow>& inputWindows) {
2668#if DEBUG_FOCUS
2669 LOGD("setInputWindows");
2670#endif
2671 { // acquire lock
2672 AutoMutex _l(mLock);
2673
Jeff Brown01ce2e92010-09-26 22:20:12 -07002674 // Clear old window pointers.
Jeff Brownb6997262010-10-08 22:31:17 -07002675 sp<InputChannel> oldFocusedWindowChannel;
2676 if (mFocusedWindow) {
2677 oldFocusedWindowChannel = mFocusedWindow->inputChannel;
2678 mFocusedWindow = NULL;
2679 }
2680
Jeff Brownb88102f2010-09-08 11:49:43 -07002681 mWindows.clear();
Jeff Brown2a95c2a2010-09-16 12:31:46 -07002682
2683 // Loop over new windows and rebuild the necessary window pointers for
2684 // tracking focus and touch.
Jeff Brownb88102f2010-09-08 11:49:43 -07002685 mWindows.appendVector(inputWindows);
2686
2687 size_t numWindows = mWindows.size();
2688 for (size_t i = 0; i < numWindows; i++) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002689 const InputWindow* window = & mWindows.itemAt(i);
Jeff Brownb88102f2010-09-08 11:49:43 -07002690 if (window->hasFocus) {
2691 mFocusedWindow = window;
Jeff Brown01ce2e92010-09-26 22:20:12 -07002692 break;
Jeff Brownb88102f2010-09-08 11:49:43 -07002693 }
2694 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07002695
Jeff Brownb6997262010-10-08 22:31:17 -07002696 if (oldFocusedWindowChannel != NULL) {
2697 if (!mFocusedWindow || oldFocusedWindowChannel != mFocusedWindow->inputChannel) {
2698#if DEBUG_FOCUS
2699 LOGD("Focus left window: %s",
2700 oldFocusedWindowChannel->getName().string());
2701#endif
2702 synthesizeCancelationEventsForInputChannelLocked(oldFocusedWindowChannel,
2703 InputState::CANCEL_NON_POINTER_EVENTS, "focus left window");
2704 oldFocusedWindowChannel.clear();
2705 }
2706 }
2707 if (mFocusedWindow && oldFocusedWindowChannel == NULL) {
2708#if DEBUG_FOCUS
2709 LOGD("Focus entered window: %s",
2710 mFocusedWindow->inputChannel->getName().string());
2711#endif
2712 }
2713
Jeff Brown01ce2e92010-09-26 22:20:12 -07002714 for (size_t i = 0; i < mTouchState.windows.size(); ) {
2715 TouchedWindow& touchedWindow = mTouchState.windows.editItemAt(i);
2716 const InputWindow* window = getWindowLocked(touchedWindow.channel);
2717 if (window) {
2718 touchedWindow.window = window;
2719 i += 1;
2720 } else {
Jeff Brownb6997262010-10-08 22:31:17 -07002721#if DEBUG_FOCUS
2722 LOGD("Touched window was removed: %s", touchedWindow.channel->getName().string());
2723#endif
Jeff Brownb6997262010-10-08 22:31:17 -07002724 synthesizeCancelationEventsForInputChannelLocked(touchedWindow.channel,
2725 InputState::CANCEL_POINTER_EVENTS, "touched window was removed");
Jeff Brownaf48cae2010-10-15 16:20:51 -07002726 mTouchState.windows.removeAt(i);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002727 }
2728 }
Jeff Brownb88102f2010-09-08 11:49:43 -07002729
Jeff Brownb88102f2010-09-08 11:49:43 -07002730#if DEBUG_FOCUS
Jeff Brownb6997262010-10-08 22:31:17 -07002731 //logDispatchStateLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -07002732#endif
2733 } // release lock
2734
2735 // Wake up poll loop since it may need to make new input dispatching choices.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002736 mLooper->wake();
Jeff Brownb88102f2010-09-08 11:49:43 -07002737}
2738
2739void InputDispatcher::setFocusedApplication(const InputApplication* inputApplication) {
2740#if DEBUG_FOCUS
2741 LOGD("setFocusedApplication");
2742#endif
2743 { // acquire lock
2744 AutoMutex _l(mLock);
2745
2746 releaseFocusedApplicationLocked();
2747
2748 if (inputApplication) {
2749 mFocusedApplicationStorage = *inputApplication;
2750 mFocusedApplication = & mFocusedApplicationStorage;
2751 }
2752
2753#if DEBUG_FOCUS
Jeff Brownb6997262010-10-08 22:31:17 -07002754 //logDispatchStateLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -07002755#endif
2756 } // release lock
2757
2758 // Wake up poll loop since it may need to make new input dispatching choices.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002759 mLooper->wake();
Jeff Brownb88102f2010-09-08 11:49:43 -07002760}
2761
2762void InputDispatcher::releaseFocusedApplicationLocked() {
2763 if (mFocusedApplication) {
2764 mFocusedApplication = NULL;
Jeff Brown928e0542011-01-10 11:17:36 -08002765 mFocusedApplicationStorage.inputApplicationHandle.clear();
Jeff Brownb88102f2010-09-08 11:49:43 -07002766 }
2767}
2768
2769void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
2770#if DEBUG_FOCUS
2771 LOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
2772#endif
2773
2774 bool changed;
2775 { // acquire lock
2776 AutoMutex _l(mLock);
2777
2778 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
Jeff Brown120a4592010-10-27 18:43:51 -07002779 if (mDispatchFrozen && !frozen) {
Jeff Brownb88102f2010-09-08 11:49:43 -07002780 resetANRTimeoutsLocked();
2781 }
2782
Jeff Brown120a4592010-10-27 18:43:51 -07002783 if (mDispatchEnabled && !enabled) {
2784 resetAndDropEverythingLocked("dispatcher is being disabled");
2785 }
2786
Jeff Brownb88102f2010-09-08 11:49:43 -07002787 mDispatchEnabled = enabled;
2788 mDispatchFrozen = frozen;
2789 changed = true;
2790 } else {
2791 changed = false;
2792 }
2793
2794#if DEBUG_FOCUS
Jeff Brownb6997262010-10-08 22:31:17 -07002795 //logDispatchStateLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -07002796#endif
2797 } // release lock
2798
2799 if (changed) {
2800 // Wake up poll loop since it may need to make new input dispatching choices.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002801 mLooper->wake();
Jeff Brown46b9ac02010-04-22 18:58:52 -07002802 }
2803}
2804
Jeff Browne6504122010-09-27 14:52:15 -07002805bool InputDispatcher::transferTouchFocus(const sp<InputChannel>& fromChannel,
2806 const sp<InputChannel>& toChannel) {
2807#if DEBUG_FOCUS
2808 LOGD("transferTouchFocus: fromChannel=%s, toChannel=%s",
2809 fromChannel->getName().string(), toChannel->getName().string());
2810#endif
2811 { // acquire lock
2812 AutoMutex _l(mLock);
2813
2814 const InputWindow* fromWindow = getWindowLocked(fromChannel);
2815 const InputWindow* toWindow = getWindowLocked(toChannel);
2816 if (! fromWindow || ! toWindow) {
2817#if DEBUG_FOCUS
2818 LOGD("Cannot transfer focus because from or to window not found.");
2819#endif
2820 return false;
2821 }
2822 if (fromWindow == toWindow) {
2823#if DEBUG_FOCUS
2824 LOGD("Trivial transfer to same window.");
2825#endif
2826 return true;
2827 }
2828
2829 bool found = false;
2830 for (size_t i = 0; i < mTouchState.windows.size(); i++) {
2831 const TouchedWindow& touchedWindow = mTouchState.windows[i];
2832 if (touchedWindow.window == fromWindow) {
2833 int32_t oldTargetFlags = touchedWindow.targetFlags;
2834 BitSet32 pointerIds = touchedWindow.pointerIds;
2835
2836 mTouchState.windows.removeAt(i);
2837
Jeff Brown46e75292010-11-10 16:53:45 -08002838 int32_t newTargetFlags = oldTargetFlags
2839 & (InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_SPLIT);
Jeff Browne6504122010-09-27 14:52:15 -07002840 mTouchState.addOrUpdateWindow(toWindow, newTargetFlags, pointerIds);
2841
2842 found = true;
2843 break;
2844 }
2845 }
2846
2847 if (! found) {
2848#if DEBUG_FOCUS
2849 LOGD("Focus transfer failed because from window did not have focus.");
2850#endif
2851 return false;
2852 }
2853
Jeff Brown9c9f1a32010-10-11 18:32:20 -07002854 ssize_t fromConnectionIndex = getConnectionIndexLocked(fromChannel);
2855 ssize_t toConnectionIndex = getConnectionIndexLocked(toChannel);
2856 if (fromConnectionIndex >= 0 && toConnectionIndex >= 0) {
2857 sp<Connection> fromConnection = mConnectionsByReceiveFd.valueAt(fromConnectionIndex);
2858 sp<Connection> toConnection = mConnectionsByReceiveFd.valueAt(toConnectionIndex);
2859
2860 fromConnection->inputState.copyPointerStateTo(toConnection->inputState);
2861 synthesizeCancelationEventsForConnectionLocked(fromConnection,
2862 InputState::CANCEL_POINTER_EVENTS,
2863 "transferring touch focus from this window to another window");
2864 }
2865
Jeff Browne6504122010-09-27 14:52:15 -07002866#if DEBUG_FOCUS
2867 logDispatchStateLocked();
2868#endif
2869 } // release lock
2870
2871 // Wake up poll loop since it may need to make new input dispatching choices.
2872 mLooper->wake();
2873 return true;
2874}
2875
Jeff Brown120a4592010-10-27 18:43:51 -07002876void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
2877#if DEBUG_FOCUS
2878 LOGD("Resetting and dropping all events (%s).", reason);
2879#endif
2880
2881 synthesizeCancelationEventsForAllConnectionsLocked(InputState::CANCEL_ALL_EVENTS, reason);
2882
2883 resetKeyRepeatLocked();
2884 releasePendingEventLocked();
2885 drainInboundQueueLocked();
2886 resetTargetsLocked();
2887
2888 mTouchState.reset();
2889}
2890
Jeff Brownb88102f2010-09-08 11:49:43 -07002891void InputDispatcher::logDispatchStateLocked() {
2892 String8 dump;
2893 dumpDispatchStateLocked(dump);
Jeff Brown2a95c2a2010-09-16 12:31:46 -07002894
2895 char* text = dump.lockBuffer(dump.size());
2896 char* start = text;
2897 while (*start != '\0') {
2898 char* end = strchr(start, '\n');
2899 if (*end == '\n') {
2900 *(end++) = '\0';
2901 }
2902 LOGD("%s", start);
2903 start = end;
2904 }
Jeff Brownb88102f2010-09-08 11:49:43 -07002905}
2906
2907void InputDispatcher::dumpDispatchStateLocked(String8& dump) {
Jeff Brownf2f48712010-10-01 17:46:21 -07002908 dump.appendFormat(INDENT "DispatchEnabled: %d\n", mDispatchEnabled);
2909 dump.appendFormat(INDENT "DispatchFrozen: %d\n", mDispatchFrozen);
Jeff Brownb88102f2010-09-08 11:49:43 -07002910
2911 if (mFocusedApplication) {
Jeff Brownf2f48712010-10-01 17:46:21 -07002912 dump.appendFormat(INDENT "FocusedApplication: name='%s', dispatchingTimeout=%0.3fms\n",
Jeff Brownb88102f2010-09-08 11:49:43 -07002913 mFocusedApplication->name.string(),
2914 mFocusedApplication->dispatchingTimeout / 1000000.0);
2915 } else {
Jeff Brownf2f48712010-10-01 17:46:21 -07002916 dump.append(INDENT "FocusedApplication: <null>\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07002917 }
Jeff Brownf2f48712010-10-01 17:46:21 -07002918 dump.appendFormat(INDENT "FocusedWindow: name='%s'\n",
Jeff Brown2a95c2a2010-09-16 12:31:46 -07002919 mFocusedWindow != NULL ? mFocusedWindow->name.string() : "<null>");
Jeff Brownf2f48712010-10-01 17:46:21 -07002920
2921 dump.appendFormat(INDENT "TouchDown: %s\n", toString(mTouchState.down));
2922 dump.appendFormat(INDENT "TouchSplit: %s\n", toString(mTouchState.split));
Jeff Brown95712852011-01-04 19:41:59 -08002923 dump.appendFormat(INDENT "TouchDeviceId: %d\n", mTouchState.deviceId);
Jeff Brown58a2da82011-01-25 16:02:22 -08002924 dump.appendFormat(INDENT "TouchSource: 0x%08x\n", mTouchState.source);
Jeff Brownf2f48712010-10-01 17:46:21 -07002925 if (!mTouchState.windows.isEmpty()) {
2926 dump.append(INDENT "TouchedWindows:\n");
2927 for (size_t i = 0; i < mTouchState.windows.size(); i++) {
2928 const TouchedWindow& touchedWindow = mTouchState.windows[i];
2929 dump.appendFormat(INDENT2 "%d: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
2930 i, touchedWindow.window->name.string(), touchedWindow.pointerIds.value,
2931 touchedWindow.targetFlags);
2932 }
2933 } else {
2934 dump.append(INDENT "TouchedWindows: <none>\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07002935 }
2936
Jeff Brownf2f48712010-10-01 17:46:21 -07002937 if (!mWindows.isEmpty()) {
2938 dump.append(INDENT "Windows:\n");
2939 for (size_t i = 0; i < mWindows.size(); i++) {
2940 const InputWindow& window = mWindows[i];
2941 dump.appendFormat(INDENT2 "%d: name='%s', paused=%s, hasFocus=%s, hasWallpaper=%s, "
2942 "visible=%s, canReceiveKeys=%s, flags=0x%08x, type=0x%08x, layer=%d, "
2943 "frame=[%d,%d][%d,%d], "
Jeff Brownfbf09772011-01-16 14:06:57 -08002944 "touchableRegion=",
Jeff Brownf2f48712010-10-01 17:46:21 -07002945 i, window.name.string(),
2946 toString(window.paused),
2947 toString(window.hasFocus),
2948 toString(window.hasWallpaper),
2949 toString(window.visible),
2950 toString(window.canReceiveKeys),
2951 window.layoutParamsFlags, window.layoutParamsType,
2952 window.layer,
2953 window.frameLeft, window.frameTop,
Jeff Brownfbf09772011-01-16 14:06:57 -08002954 window.frameRight, window.frameBottom);
2955 dumpRegion(dump, window.touchableRegion);
2956 dump.appendFormat(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%0.3fms\n",
Jeff Brownf2f48712010-10-01 17:46:21 -07002957 window.ownerPid, window.ownerUid,
2958 window.dispatchingTimeout / 1000000.0);
2959 }
2960 } else {
2961 dump.append(INDENT "Windows: <none>\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07002962 }
2963
Jeff Brownf2f48712010-10-01 17:46:21 -07002964 if (!mMonitoringChannels.isEmpty()) {
2965 dump.append(INDENT "MonitoringChannels:\n");
2966 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
2967 const sp<InputChannel>& channel = mMonitoringChannels[i];
2968 dump.appendFormat(INDENT2 "%d: '%s'\n", i, channel->getName().string());
2969 }
2970 } else {
2971 dump.append(INDENT "MonitoringChannels: <none>\n");
2972 }
Jeff Brown519e0242010-09-15 15:18:56 -07002973
Jeff Brownf2f48712010-10-01 17:46:21 -07002974 dump.appendFormat(INDENT "InboundQueue: length=%u\n", mInboundQueue.count());
2975
2976 if (!mActiveConnections.isEmpty()) {
2977 dump.append(INDENT "ActiveConnections:\n");
2978 for (size_t i = 0; i < mActiveConnections.size(); i++) {
2979 const Connection* connection = mActiveConnections[i];
Jeff Brown76860e32010-10-25 17:37:46 -07002980 dump.appendFormat(INDENT2 "%d: '%s', status=%s, outboundQueueLength=%u, "
Jeff Brownb6997262010-10-08 22:31:17 -07002981 "inputState.isNeutral=%s\n",
Jeff Brownf2f48712010-10-01 17:46:21 -07002982 i, connection->getInputChannelName(), connection->getStatusLabel(),
2983 connection->outboundQueue.count(),
Jeff Brownb6997262010-10-08 22:31:17 -07002984 toString(connection->inputState.isNeutral()));
Jeff Brownf2f48712010-10-01 17:46:21 -07002985 }
2986 } else {
2987 dump.append(INDENT "ActiveConnections: <none>\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07002988 }
2989
2990 if (isAppSwitchPendingLocked()) {
Jeff Brownf2f48712010-10-01 17:46:21 -07002991 dump.appendFormat(INDENT "AppSwitch: pending, due in %01.1fms\n",
Jeff Brownb88102f2010-09-08 11:49:43 -07002992 (mAppSwitchDueTime - now()) / 1000000.0);
2993 } else {
Jeff Brownf2f48712010-10-01 17:46:21 -07002994 dump.append(INDENT "AppSwitch: not pending\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07002995 }
2996}
2997
Jeff Brown928e0542011-01-10 11:17:36 -08002998status_t InputDispatcher::registerInputChannel(const sp<InputChannel>& inputChannel,
2999 const sp<InputWindowHandle>& inputWindowHandle, bool monitor) {
Jeff Brown9c3cda02010-06-15 01:31:58 -07003000#if DEBUG_REGISTRATION
Jeff Brownb88102f2010-09-08 11:49:43 -07003001 LOGD("channel '%s' ~ registerInputChannel - monitor=%s", inputChannel->getName().string(),
3002 toString(monitor));
Jeff Brown9c3cda02010-06-15 01:31:58 -07003003#endif
3004
Jeff Brown46b9ac02010-04-22 18:58:52 -07003005 { // acquire lock
3006 AutoMutex _l(mLock);
3007
Jeff Brown519e0242010-09-15 15:18:56 -07003008 if (getConnectionIndexLocked(inputChannel) >= 0) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07003009 LOGW("Attempted to register already registered input channel '%s'",
3010 inputChannel->getName().string());
3011 return BAD_VALUE;
3012 }
3013
Jeff Brown928e0542011-01-10 11:17:36 -08003014 sp<Connection> connection = new Connection(inputChannel, inputWindowHandle);
Jeff Brown46b9ac02010-04-22 18:58:52 -07003015 status_t status = connection->initialize();
3016 if (status) {
3017 LOGE("Failed to initialize input publisher for input channel '%s', status=%d",
3018 inputChannel->getName().string(), status);
3019 return status;
3020 }
3021
Jeff Brown2cbecea2010-08-17 15:59:26 -07003022 int32_t receiveFd = inputChannel->getReceivePipeFd();
Jeff Brown46b9ac02010-04-22 18:58:52 -07003023 mConnectionsByReceiveFd.add(receiveFd, connection);
Jeff Brown9c3cda02010-06-15 01:31:58 -07003024
Jeff Brownb88102f2010-09-08 11:49:43 -07003025 if (monitor) {
3026 mMonitoringChannels.push(inputChannel);
3027 }
3028
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07003029 mLooper->addFd(receiveFd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
Jeff Brown2cbecea2010-08-17 15:59:26 -07003030
Jeff Brown9c3cda02010-06-15 01:31:58 -07003031 runCommandsLockedInterruptible();
Jeff Brown46b9ac02010-04-22 18:58:52 -07003032 } // release lock
Jeff Brown46b9ac02010-04-22 18:58:52 -07003033 return OK;
3034}
3035
3036status_t InputDispatcher::unregisterInputChannel(const sp<InputChannel>& inputChannel) {
Jeff Brown9c3cda02010-06-15 01:31:58 -07003037#if DEBUG_REGISTRATION
Jeff Brown349703e2010-06-22 01:27:15 -07003038 LOGD("channel '%s' ~ unregisterInputChannel", inputChannel->getName().string());
Jeff Brown9c3cda02010-06-15 01:31:58 -07003039#endif
3040
Jeff Brown46b9ac02010-04-22 18:58:52 -07003041 { // acquire lock
3042 AutoMutex _l(mLock);
3043
Jeff Brown519e0242010-09-15 15:18:56 -07003044 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
Jeff Brown46b9ac02010-04-22 18:58:52 -07003045 if (connectionIndex < 0) {
3046 LOGW("Attempted to unregister already unregistered input channel '%s'",
3047 inputChannel->getName().string());
3048 return BAD_VALUE;
3049 }
3050
3051 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
3052 mConnectionsByReceiveFd.removeItemsAt(connectionIndex);
3053
3054 connection->status = Connection::STATUS_ZOMBIE;
3055
Jeff Brownb88102f2010-09-08 11:49:43 -07003056 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
3057 if (mMonitoringChannels[i] == inputChannel) {
3058 mMonitoringChannels.removeAt(i);
3059 break;
3060 }
3061 }
3062
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07003063 mLooper->removeFd(inputChannel->getReceivePipeFd());
Jeff Brown2cbecea2010-08-17 15:59:26 -07003064
Jeff Brown7fbdc842010-06-17 20:52:56 -07003065 nsecs_t currentTime = now();
Jeff Brownb6997262010-10-08 22:31:17 -07003066 abortBrokenDispatchCycleLocked(currentTime, connection);
Jeff Brown9c3cda02010-06-15 01:31:58 -07003067
3068 runCommandsLockedInterruptible();
Jeff Brown46b9ac02010-04-22 18:58:52 -07003069 } // release lock
3070
Jeff Brown46b9ac02010-04-22 18:58:52 -07003071 // Wake the poll loop because removing the connection may have changed the current
3072 // synchronization state.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07003073 mLooper->wake();
Jeff Brown46b9ac02010-04-22 18:58:52 -07003074 return OK;
3075}
3076
Jeff Brown519e0242010-09-15 15:18:56 -07003077ssize_t InputDispatcher::getConnectionIndexLocked(const sp<InputChannel>& inputChannel) {
Jeff Brown2cbecea2010-08-17 15:59:26 -07003078 ssize_t connectionIndex = mConnectionsByReceiveFd.indexOfKey(inputChannel->getReceivePipeFd());
3079 if (connectionIndex >= 0) {
3080 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
3081 if (connection->inputChannel.get() == inputChannel.get()) {
3082 return connectionIndex;
3083 }
3084 }
3085
3086 return -1;
3087}
3088
Jeff Brown46b9ac02010-04-22 18:58:52 -07003089void InputDispatcher::activateConnectionLocked(Connection* connection) {
3090 for (size_t i = 0; i < mActiveConnections.size(); i++) {
3091 if (mActiveConnections.itemAt(i) == connection) {
3092 return;
3093 }
3094 }
3095 mActiveConnections.add(connection);
3096}
3097
3098void InputDispatcher::deactivateConnectionLocked(Connection* connection) {
3099 for (size_t i = 0; i < mActiveConnections.size(); i++) {
3100 if (mActiveConnections.itemAt(i) == connection) {
3101 mActiveConnections.removeAt(i);
3102 return;
3103 }
3104 }
3105}
3106
Jeff Brown9c3cda02010-06-15 01:31:58 -07003107void InputDispatcher::onDispatchCycleStartedLocked(
Jeff Brown7fbdc842010-06-17 20:52:56 -07003108 nsecs_t currentTime, const sp<Connection>& connection) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07003109}
3110
Jeff Brown9c3cda02010-06-15 01:31:58 -07003111void InputDispatcher::onDispatchCycleFinishedLocked(
Jeff Brown3915bb82010-11-05 15:02:16 -07003112 nsecs_t currentTime, const sp<Connection>& connection, bool handled) {
3113 CommandEntry* commandEntry = postCommandLocked(
3114 & InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
3115 commandEntry->connection = connection;
3116 commandEntry->handled = handled;
Jeff Brown46b9ac02010-04-22 18:58:52 -07003117}
3118
Jeff Brown9c3cda02010-06-15 01:31:58 -07003119void InputDispatcher::onDispatchCycleBrokenLocked(
Jeff Brown7fbdc842010-06-17 20:52:56 -07003120 nsecs_t currentTime, const sp<Connection>& connection) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07003121 LOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
3122 connection->getInputChannelName());
3123
Jeff Brown9c3cda02010-06-15 01:31:58 -07003124 CommandEntry* commandEntry = postCommandLocked(
3125 & InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
Jeff Brown7fbdc842010-06-17 20:52:56 -07003126 commandEntry->connection = connection;
Jeff Brown46b9ac02010-04-22 18:58:52 -07003127}
3128
Jeff Brown519e0242010-09-15 15:18:56 -07003129void InputDispatcher::onANRLocked(
3130 nsecs_t currentTime, const InputApplication* application, const InputWindow* window,
3131 nsecs_t eventTime, nsecs_t waitStartTime) {
3132 LOGI("Application is not responding: %s. "
3133 "%01.1fms since event, %01.1fms since wait started",
3134 getApplicationWindowLabelLocked(application, window).string(),
3135 (currentTime - eventTime) / 1000000.0,
3136 (currentTime - waitStartTime) / 1000000.0);
3137
3138 CommandEntry* commandEntry = postCommandLocked(
3139 & InputDispatcher::doNotifyANRLockedInterruptible);
3140 if (application) {
Jeff Brown928e0542011-01-10 11:17:36 -08003141 commandEntry->inputApplicationHandle = application->inputApplicationHandle;
Jeff Brown519e0242010-09-15 15:18:56 -07003142 }
3143 if (window) {
Jeff Brown928e0542011-01-10 11:17:36 -08003144 commandEntry->inputWindowHandle = window->inputWindowHandle;
Jeff Brown519e0242010-09-15 15:18:56 -07003145 commandEntry->inputChannel = window->inputChannel;
3146 }
3147}
3148
Jeff Brownb88102f2010-09-08 11:49:43 -07003149void InputDispatcher::doNotifyConfigurationChangedInterruptible(
3150 CommandEntry* commandEntry) {
3151 mLock.unlock();
3152
3153 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
3154
3155 mLock.lock();
3156}
3157
Jeff Brown9c3cda02010-06-15 01:31:58 -07003158void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(
3159 CommandEntry* commandEntry) {
Jeff Brown7fbdc842010-06-17 20:52:56 -07003160 sp<Connection> connection = commandEntry->connection;
Jeff Brown9c3cda02010-06-15 01:31:58 -07003161
Jeff Brown7fbdc842010-06-17 20:52:56 -07003162 if (connection->status != Connection::STATUS_ZOMBIE) {
3163 mLock.unlock();
Jeff Brown9c3cda02010-06-15 01:31:58 -07003164
Jeff Brown928e0542011-01-10 11:17:36 -08003165 mPolicy->notifyInputChannelBroken(connection->inputWindowHandle);
Jeff Brown7fbdc842010-06-17 20:52:56 -07003166
3167 mLock.lock();
3168 }
Jeff Brown9c3cda02010-06-15 01:31:58 -07003169}
3170
Jeff Brown519e0242010-09-15 15:18:56 -07003171void InputDispatcher::doNotifyANRLockedInterruptible(
Jeff Brown9c3cda02010-06-15 01:31:58 -07003172 CommandEntry* commandEntry) {
Jeff Brown519e0242010-09-15 15:18:56 -07003173 mLock.unlock();
Jeff Brown9c3cda02010-06-15 01:31:58 -07003174
Jeff Brown519e0242010-09-15 15:18:56 -07003175 nsecs_t newTimeout = mPolicy->notifyANR(
Jeff Brown928e0542011-01-10 11:17:36 -08003176 commandEntry->inputApplicationHandle, commandEntry->inputWindowHandle);
Jeff Brown9c3cda02010-06-15 01:31:58 -07003177
Jeff Brown519e0242010-09-15 15:18:56 -07003178 mLock.lock();
Jeff Brown7fbdc842010-06-17 20:52:56 -07003179
Jeff Brown519e0242010-09-15 15:18:56 -07003180 resumeAfterTargetsNotReadyTimeoutLocked(newTimeout, commandEntry->inputChannel);
Jeff Brown9c3cda02010-06-15 01:31:58 -07003181}
3182
Jeff Brownb88102f2010-09-08 11:49:43 -07003183void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
3184 CommandEntry* commandEntry) {
3185 KeyEntry* entry = commandEntry->keyEntry;
Jeff Brown1f245102010-11-18 20:53:46 -08003186
3187 KeyEvent event;
3188 initializeKeyEvent(&event, entry);
Jeff Brownb88102f2010-09-08 11:49:43 -07003189
3190 mLock.unlock();
3191
Jeff Brown928e0542011-01-10 11:17:36 -08003192 bool consumed = mPolicy->interceptKeyBeforeDispatching(commandEntry->inputWindowHandle,
Jeff Brown1f245102010-11-18 20:53:46 -08003193 &event, entry->policyFlags);
Jeff Brownb88102f2010-09-08 11:49:43 -07003194
3195 mLock.lock();
3196
3197 entry->interceptKeyResult = consumed
3198 ? KeyEntry::INTERCEPT_KEY_RESULT_SKIP
3199 : KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
3200 mAllocator.releaseKeyEntry(entry);
3201}
3202
Jeff Brown3915bb82010-11-05 15:02:16 -07003203void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(
3204 CommandEntry* commandEntry) {
3205 sp<Connection> connection = commandEntry->connection;
3206 bool handled = commandEntry->handled;
3207
Jeff Brown49ed71d2010-12-06 17:13:33 -08003208 if (!connection->outboundQueue.isEmpty()) {
Jeff Brown3915bb82010-11-05 15:02:16 -07003209 DispatchEntry* dispatchEntry = connection->outboundQueue.headSentinel.next;
3210 if (dispatchEntry->inProgress
3211 && dispatchEntry->hasForegroundTarget()
3212 && dispatchEntry->eventEntry->type == EventEntry::TYPE_KEY) {
3213 KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry);
Jeff Brown49ed71d2010-12-06 17:13:33 -08003214 if (!(keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK)) {
3215 if (handled) {
3216 // If the application handled a non-fallback key, then immediately
3217 // cancel all fallback keys previously dispatched to the application.
3218 // This behavior will prevent chording with fallback keys (so they cannot
3219 // be used as modifiers) but it will ensure that fallback keys do not
3220 // get stuck. This takes care of the case where the application does not handle
3221 // the original DOWN so we generate a fallback DOWN but it does handle
Jeff Brownbfaf3b92011-02-22 15:00:50 -08003222 // the original UP in which case we want to send a fallback CANCEL.
Jeff Brown49ed71d2010-12-06 17:13:33 -08003223 synthesizeCancelationEventsForConnectionLocked(connection,
3224 InputState::CANCEL_FALLBACK_EVENTS,
Jeff Brownbfaf3b92011-02-22 15:00:50 -08003225 "application handled a non-fallback event, "
3226 "canceling all fallback events");
3227 connection->originalKeyCodeForFallback = -1;
Jeff Brown49ed71d2010-12-06 17:13:33 -08003228 } else {
Jeff Brownbfaf3b92011-02-22 15:00:50 -08003229 // If the application did not handle a non-fallback key, first check
3230 // that we are in a good state to handle the fallback key. Then ask
3231 // the policy what to do with it.
3232 if (connection->originalKeyCodeForFallback < 0) {
3233 if (keyEntry->action != AKEY_EVENT_ACTION_DOWN
3234 || keyEntry->repeatCount != 0) {
3235#if DEBUG_OUTBOUND_EVENT_DETAILS
3236 LOGD("Unhandled key event: Skipping fallback since this "
3237 "is not an initial down. "
3238 "keyCode=%d, action=%d, repeatCount=%d",
3239 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount);
3240#endif
3241 goto SkipFallback;
3242 }
3243
3244 // Start handling the fallback key on DOWN.
3245 connection->originalKeyCodeForFallback = keyEntry->keyCode;
3246 } else {
3247 if (keyEntry->keyCode != connection->originalKeyCodeForFallback) {
3248#if DEBUG_OUTBOUND_EVENT_DETAILS
3249 LOGD("Unhandled key event: Skipping fallback since there is "
3250 "already a different fallback in progress. "
3251 "keyCode=%d, originalKeyCodeForFallback=%d",
3252 keyEntry->keyCode, connection->originalKeyCodeForFallback);
3253#endif
3254 goto SkipFallback;
3255 }
3256
3257 // Finish handling the fallback key on UP.
3258 if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
3259 connection->originalKeyCodeForFallback = -1;
3260 }
3261 }
3262
3263#if DEBUG_OUTBOUND_EVENT_DETAILS
3264 LOGD("Unhandled key event: Asking policy to perform fallback action. "
3265 "keyCode=%d, action=%d, repeatCount=%d",
3266 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount);
3267#endif
Jeff Brown49ed71d2010-12-06 17:13:33 -08003268 KeyEvent event;
3269 initializeKeyEvent(&event, keyEntry);
Jeff Brown3915bb82010-11-05 15:02:16 -07003270
Jeff Brown49ed71d2010-12-06 17:13:33 -08003271 mLock.unlock();
Jeff Brown3915bb82010-11-05 15:02:16 -07003272
Jeff Brown928e0542011-01-10 11:17:36 -08003273 bool fallback = mPolicy->dispatchUnhandledKey(connection->inputWindowHandle,
Jeff Brown49ed71d2010-12-06 17:13:33 -08003274 &event, keyEntry->policyFlags, &event);
Jeff Brown3915bb82010-11-05 15:02:16 -07003275
Jeff Brown49ed71d2010-12-06 17:13:33 -08003276 mLock.lock();
3277
Jeff Brown00045a72010-12-09 18:10:30 -08003278 if (connection->status != Connection::STATUS_NORMAL) {
3279 return;
3280 }
3281
3282 assert(connection->outboundQueue.headSentinel.next == dispatchEntry);
3283
Jeff Brown49ed71d2010-12-06 17:13:33 -08003284 if (fallback) {
3285 // Restart the dispatch cycle using the fallback key.
3286 keyEntry->eventTime = event.getEventTime();
3287 keyEntry->deviceId = event.getDeviceId();
3288 keyEntry->source = event.getSource();
3289 keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
3290 keyEntry->keyCode = event.getKeyCode();
3291 keyEntry->scanCode = event.getScanCode();
3292 keyEntry->metaState = event.getMetaState();
3293 keyEntry->repeatCount = event.getRepeatCount();
3294 keyEntry->downTime = event.getDownTime();
3295 keyEntry->syntheticRepeat = false;
3296
Jeff Brownbfaf3b92011-02-22 15:00:50 -08003297#if DEBUG_OUTBOUND_EVENT_DETAILS
3298 LOGD("Unhandled key event: Dispatching fallback key. "
3299 "fallbackKeyCode=%d, fallbackMetaState=%08x",
3300 keyEntry->keyCode, keyEntry->metaState);
3301#endif
3302
Jeff Brown49ed71d2010-12-06 17:13:33 -08003303 dispatchEntry->inProgress = false;
3304 startDispatchCycleLocked(now(), connection);
3305 return;
3306 }
3307 }
3308 }
Jeff Brown3915bb82010-11-05 15:02:16 -07003309 }
3310 }
3311
Jeff Brownbfaf3b92011-02-22 15:00:50 -08003312SkipFallback:
Jeff Brown3915bb82010-11-05 15:02:16 -07003313 startNextDispatchCycleLocked(now(), connection);
3314}
3315
Jeff Brownb88102f2010-09-08 11:49:43 -07003316void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
3317 mLock.unlock();
3318
Jeff Brown01ce2e92010-09-26 22:20:12 -07003319 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
Jeff Brownb88102f2010-09-08 11:49:43 -07003320
3321 mLock.lock();
3322}
3323
Jeff Brown3915bb82010-11-05 15:02:16 -07003324void InputDispatcher::initializeKeyEvent(KeyEvent* event, const KeyEntry* entry) {
3325 event->initialize(entry->deviceId, entry->source, entry->action, entry->flags,
3326 entry->keyCode, entry->scanCode, entry->metaState, entry->repeatCount,
3327 entry->downTime, entry->eventTime);
3328}
3329
Jeff Brown519e0242010-09-15 15:18:56 -07003330void InputDispatcher::updateDispatchStatisticsLocked(nsecs_t currentTime, const EventEntry* entry,
3331 int32_t injectionResult, nsecs_t timeSpentWaitingForApplication) {
3332 // TODO Write some statistics about how long we spend waiting.
Jeff Brownb88102f2010-09-08 11:49:43 -07003333}
3334
3335void InputDispatcher::dump(String8& dump) {
Jeff Brownf2f48712010-10-01 17:46:21 -07003336 dump.append("Input Dispatcher State:\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003337 dumpDispatchStateLocked(dump);
3338}
3339
Jeff Brown9c3cda02010-06-15 01:31:58 -07003340
Jeff Brown519e0242010-09-15 15:18:56 -07003341// --- InputDispatcher::Queue ---
3342
3343template <typename T>
3344uint32_t InputDispatcher::Queue<T>::count() const {
3345 uint32_t result = 0;
3346 for (const T* entry = headSentinel.next; entry != & tailSentinel; entry = entry->next) {
3347 result += 1;
3348 }
3349 return result;
3350}
3351
3352
Jeff Brown46b9ac02010-04-22 18:58:52 -07003353// --- InputDispatcher::Allocator ---
3354
3355InputDispatcher::Allocator::Allocator() {
3356}
3357
Jeff Brown01ce2e92010-09-26 22:20:12 -07003358InputDispatcher::InjectionState*
3359InputDispatcher::Allocator::obtainInjectionState(int32_t injectorPid, int32_t injectorUid) {
3360 InjectionState* injectionState = mInjectionStatePool.alloc();
3361 injectionState->refCount = 1;
3362 injectionState->injectorPid = injectorPid;
3363 injectionState->injectorUid = injectorUid;
3364 injectionState->injectionIsAsync = false;
3365 injectionState->injectionResult = INPUT_EVENT_INJECTION_PENDING;
3366 injectionState->pendingForegroundDispatches = 0;
3367 return injectionState;
3368}
3369
Jeff Brown7fbdc842010-06-17 20:52:56 -07003370void InputDispatcher::Allocator::initializeEventEntry(EventEntry* entry, int32_t type,
Jeff Brownb6997262010-10-08 22:31:17 -07003371 nsecs_t eventTime, uint32_t policyFlags) {
Jeff Brown7fbdc842010-06-17 20:52:56 -07003372 entry->type = type;
3373 entry->refCount = 1;
3374 entry->dispatchInProgress = false;
Christopher Tatee91a5db2010-06-23 16:50:30 -07003375 entry->eventTime = eventTime;
Jeff Brownb6997262010-10-08 22:31:17 -07003376 entry->policyFlags = policyFlags;
Jeff Brown01ce2e92010-09-26 22:20:12 -07003377 entry->injectionState = NULL;
3378}
3379
3380void InputDispatcher::Allocator::releaseEventEntryInjectionState(EventEntry* entry) {
3381 if (entry->injectionState) {
3382 releaseInjectionState(entry->injectionState);
3383 entry->injectionState = NULL;
3384 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07003385}
3386
Jeff Brown46b9ac02010-04-22 18:58:52 -07003387InputDispatcher::ConfigurationChangedEntry*
Jeff Brown7fbdc842010-06-17 20:52:56 -07003388InputDispatcher::Allocator::obtainConfigurationChangedEntry(nsecs_t eventTime) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07003389 ConfigurationChangedEntry* entry = mConfigurationChangeEntryPool.alloc();
Jeff Brownb6997262010-10-08 22:31:17 -07003390 initializeEventEntry(entry, EventEntry::TYPE_CONFIGURATION_CHANGED, eventTime, 0);
Jeff Brown46b9ac02010-04-22 18:58:52 -07003391 return entry;
3392}
3393
Jeff Brown7fbdc842010-06-17 20:52:56 -07003394InputDispatcher::KeyEntry* InputDispatcher::Allocator::obtainKeyEntry(nsecs_t eventTime,
Jeff Brown58a2da82011-01-25 16:02:22 -08003395 int32_t deviceId, uint32_t source, uint32_t policyFlags, int32_t action,
Jeff Brown7fbdc842010-06-17 20:52:56 -07003396 int32_t flags, int32_t keyCode, int32_t scanCode, int32_t metaState,
3397 int32_t repeatCount, nsecs_t downTime) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07003398 KeyEntry* entry = mKeyEntryPool.alloc();
Jeff Brownb6997262010-10-08 22:31:17 -07003399 initializeEventEntry(entry, EventEntry::TYPE_KEY, eventTime, policyFlags);
Jeff Brown7fbdc842010-06-17 20:52:56 -07003400
3401 entry->deviceId = deviceId;
Jeff Brownc5ed5912010-07-14 18:48:53 -07003402 entry->source = source;
Jeff Brown7fbdc842010-06-17 20:52:56 -07003403 entry->action = action;
3404 entry->flags = flags;
3405 entry->keyCode = keyCode;
3406 entry->scanCode = scanCode;
3407 entry->metaState = metaState;
3408 entry->repeatCount = repeatCount;
3409 entry->downTime = downTime;
Jeff Brownb88102f2010-09-08 11:49:43 -07003410 entry->syntheticRepeat = false;
3411 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
Jeff Brown46b9ac02010-04-22 18:58:52 -07003412 return entry;
3413}
3414
Jeff Brown7fbdc842010-06-17 20:52:56 -07003415InputDispatcher::MotionEntry* InputDispatcher::Allocator::obtainMotionEntry(nsecs_t eventTime,
Jeff Brown58a2da82011-01-25 16:02:22 -08003416 int32_t deviceId, uint32_t source, uint32_t policyFlags, int32_t action, int32_t flags,
Jeff Brown7fbdc842010-06-17 20:52:56 -07003417 int32_t metaState, int32_t edgeFlags, float xPrecision, float yPrecision,
3418 nsecs_t downTime, uint32_t pointerCount,
3419 const int32_t* pointerIds, const PointerCoords* pointerCoords) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07003420 MotionEntry* entry = mMotionEntryPool.alloc();
Jeff Brownb6997262010-10-08 22:31:17 -07003421 initializeEventEntry(entry, EventEntry::TYPE_MOTION, eventTime, policyFlags);
Jeff Brown7fbdc842010-06-17 20:52:56 -07003422
3423 entry->eventTime = eventTime;
3424 entry->deviceId = deviceId;
Jeff Brownc5ed5912010-07-14 18:48:53 -07003425 entry->source = source;
Jeff Brown7fbdc842010-06-17 20:52:56 -07003426 entry->action = action;
Jeff Brown85a31762010-09-01 17:01:00 -07003427 entry->flags = flags;
Jeff Brown7fbdc842010-06-17 20:52:56 -07003428 entry->metaState = metaState;
3429 entry->edgeFlags = edgeFlags;
3430 entry->xPrecision = xPrecision;
3431 entry->yPrecision = yPrecision;
3432 entry->downTime = downTime;
3433 entry->pointerCount = pointerCount;
3434 entry->firstSample.eventTime = eventTime;
Jeff Brown46b9ac02010-04-22 18:58:52 -07003435 entry->firstSample.next = NULL;
Jeff Brown7fbdc842010-06-17 20:52:56 -07003436 entry->lastSample = & entry->firstSample;
3437 for (uint32_t i = 0; i < pointerCount; i++) {
3438 entry->pointerIds[i] = pointerIds[i];
3439 entry->firstSample.pointerCoords[i] = pointerCoords[i];
3440 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07003441 return entry;
3442}
3443
3444InputDispatcher::DispatchEntry* InputDispatcher::Allocator::obtainDispatchEntry(
Jeff Brownb88102f2010-09-08 11:49:43 -07003445 EventEntry* eventEntry,
Jeff Brown519e0242010-09-15 15:18:56 -07003446 int32_t targetFlags, float xOffset, float yOffset) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07003447 DispatchEntry* entry = mDispatchEntryPool.alloc();
3448 entry->eventEntry = eventEntry;
3449 eventEntry->refCount += 1;
Jeff Brownb88102f2010-09-08 11:49:43 -07003450 entry->targetFlags = targetFlags;
3451 entry->xOffset = xOffset;
3452 entry->yOffset = yOffset;
Jeff Brownb88102f2010-09-08 11:49:43 -07003453 entry->inProgress = false;
3454 entry->headMotionSample = NULL;
3455 entry->tailMotionSample = NULL;
Jeff Brown46b9ac02010-04-22 18:58:52 -07003456 return entry;
3457}
3458
Jeff Brown9c3cda02010-06-15 01:31:58 -07003459InputDispatcher::CommandEntry* InputDispatcher::Allocator::obtainCommandEntry(Command command) {
3460 CommandEntry* entry = mCommandEntryPool.alloc();
3461 entry->command = command;
3462 return entry;
3463}
3464
Jeff Brown01ce2e92010-09-26 22:20:12 -07003465void InputDispatcher::Allocator::releaseInjectionState(InjectionState* injectionState) {
3466 injectionState->refCount -= 1;
3467 if (injectionState->refCount == 0) {
3468 mInjectionStatePool.free(injectionState);
3469 } else {
3470 assert(injectionState->refCount > 0);
3471 }
3472}
3473
Jeff Brown46b9ac02010-04-22 18:58:52 -07003474void InputDispatcher::Allocator::releaseEventEntry(EventEntry* entry) {
3475 switch (entry->type) {
3476 case EventEntry::TYPE_CONFIGURATION_CHANGED:
3477 releaseConfigurationChangedEntry(static_cast<ConfigurationChangedEntry*>(entry));
3478 break;
3479 case EventEntry::TYPE_KEY:
3480 releaseKeyEntry(static_cast<KeyEntry*>(entry));
3481 break;
3482 case EventEntry::TYPE_MOTION:
3483 releaseMotionEntry(static_cast<MotionEntry*>(entry));
3484 break;
3485 default:
3486 assert(false);
3487 break;
3488 }
3489}
3490
3491void InputDispatcher::Allocator::releaseConfigurationChangedEntry(
3492 ConfigurationChangedEntry* entry) {
3493 entry->refCount -= 1;
3494 if (entry->refCount == 0) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07003495 releaseEventEntryInjectionState(entry);
Jeff Brown46b9ac02010-04-22 18:58:52 -07003496 mConfigurationChangeEntryPool.free(entry);
3497 } else {
3498 assert(entry->refCount > 0);
3499 }
3500}
3501
3502void InputDispatcher::Allocator::releaseKeyEntry(KeyEntry* entry) {
3503 entry->refCount -= 1;
3504 if (entry->refCount == 0) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07003505 releaseEventEntryInjectionState(entry);
Jeff Brown46b9ac02010-04-22 18:58:52 -07003506 mKeyEntryPool.free(entry);
3507 } else {
3508 assert(entry->refCount > 0);
3509 }
3510}
3511
3512void InputDispatcher::Allocator::releaseMotionEntry(MotionEntry* entry) {
3513 entry->refCount -= 1;
3514 if (entry->refCount == 0) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07003515 releaseEventEntryInjectionState(entry);
Jeff Brown9c3cda02010-06-15 01:31:58 -07003516 for (MotionSample* sample = entry->firstSample.next; sample != NULL; ) {
3517 MotionSample* next = sample->next;
3518 mMotionSamplePool.free(sample);
3519 sample = next;
3520 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07003521 mMotionEntryPool.free(entry);
3522 } else {
3523 assert(entry->refCount > 0);
3524 }
3525}
3526
3527void InputDispatcher::Allocator::releaseDispatchEntry(DispatchEntry* entry) {
3528 releaseEventEntry(entry->eventEntry);
3529 mDispatchEntryPool.free(entry);
3530}
3531
Jeff Brown9c3cda02010-06-15 01:31:58 -07003532void InputDispatcher::Allocator::releaseCommandEntry(CommandEntry* entry) {
3533 mCommandEntryPool.free(entry);
3534}
3535
Jeff Brown46b9ac02010-04-22 18:58:52 -07003536void InputDispatcher::Allocator::appendMotionSample(MotionEntry* motionEntry,
Jeff Brown7fbdc842010-06-17 20:52:56 -07003537 nsecs_t eventTime, const PointerCoords* pointerCoords) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07003538 MotionSample* sample = mMotionSamplePool.alloc();
3539 sample->eventTime = eventTime;
Jeff Brown7fbdc842010-06-17 20:52:56 -07003540 uint32_t pointerCount = motionEntry->pointerCount;
3541 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07003542 sample->pointerCoords[i] = pointerCoords[i];
3543 }
3544
3545 sample->next = NULL;
3546 motionEntry->lastSample->next = sample;
3547 motionEntry->lastSample = sample;
3548}
3549
Jeff Brown01ce2e92010-09-26 22:20:12 -07003550void InputDispatcher::Allocator::recycleKeyEntry(KeyEntry* keyEntry) {
3551 releaseEventEntryInjectionState(keyEntry);
Jeff Brownb88102f2010-09-08 11:49:43 -07003552
Jeff Brown01ce2e92010-09-26 22:20:12 -07003553 keyEntry->dispatchInProgress = false;
3554 keyEntry->syntheticRepeat = false;
3555 keyEntry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
Jeff Brownb88102f2010-09-08 11:49:43 -07003556}
3557
3558
Jeff Brownae9fc032010-08-18 15:51:08 -07003559// --- InputDispatcher::MotionEntry ---
3560
3561uint32_t InputDispatcher::MotionEntry::countSamples() const {
3562 uint32_t count = 1;
3563 for (MotionSample* sample = firstSample.next; sample != NULL; sample = sample->next) {
3564 count += 1;
3565 }
3566 return count;
3567}
3568
Jeff Brownb88102f2010-09-08 11:49:43 -07003569
3570// --- InputDispatcher::InputState ---
3571
Jeff Brownb6997262010-10-08 22:31:17 -07003572InputDispatcher::InputState::InputState() {
Jeff Brownb88102f2010-09-08 11:49:43 -07003573}
3574
3575InputDispatcher::InputState::~InputState() {
3576}
3577
3578bool InputDispatcher::InputState::isNeutral() const {
3579 return mKeyMementos.isEmpty() && mMotionMementos.isEmpty();
3580}
3581
Jeff Browncc0c1592011-02-19 05:07:28 -08003582void InputDispatcher::InputState::trackEvent(
Jeff Brownb88102f2010-09-08 11:49:43 -07003583 const EventEntry* entry) {
3584 switch (entry->type) {
3585 case EventEntry::TYPE_KEY:
Jeff Browncc0c1592011-02-19 05:07:28 -08003586 trackKey(static_cast<const KeyEntry*>(entry));
3587 break;
Jeff Brownb88102f2010-09-08 11:49:43 -07003588
3589 case EventEntry::TYPE_MOTION:
Jeff Browncc0c1592011-02-19 05:07:28 -08003590 trackMotion(static_cast<const MotionEntry*>(entry));
3591 break;
Jeff Brownb88102f2010-09-08 11:49:43 -07003592 }
3593}
3594
Jeff Browncc0c1592011-02-19 05:07:28 -08003595void InputDispatcher::InputState::trackKey(
Jeff Brownb88102f2010-09-08 11:49:43 -07003596 const KeyEntry* entry) {
3597 int32_t action = entry->action;
3598 for (size_t i = 0; i < mKeyMementos.size(); i++) {
3599 KeyMemento& memento = mKeyMementos.editItemAt(i);
3600 if (memento.deviceId == entry->deviceId
3601 && memento.source == entry->source
3602 && memento.keyCode == entry->keyCode
3603 && memento.scanCode == entry->scanCode) {
3604 switch (action) {
3605 case AKEY_EVENT_ACTION_UP:
3606 mKeyMementos.removeAt(i);
Jeff Browncc0c1592011-02-19 05:07:28 -08003607 return;
Jeff Brownb88102f2010-09-08 11:49:43 -07003608
3609 case AKEY_EVENT_ACTION_DOWN:
Jeff Browncc0c1592011-02-19 05:07:28 -08003610 mKeyMementos.removeAt(i);
3611 goto Found;
Jeff Brownb88102f2010-09-08 11:49:43 -07003612
3613 default:
Jeff Browncc0c1592011-02-19 05:07:28 -08003614 return;
Jeff Brownb88102f2010-09-08 11:49:43 -07003615 }
3616 }
3617 }
3618
Jeff Browncc0c1592011-02-19 05:07:28 -08003619Found:
3620 if (action == AKEY_EVENT_ACTION_DOWN) {
Jeff Brownb88102f2010-09-08 11:49:43 -07003621 mKeyMementos.push();
3622 KeyMemento& memento = mKeyMementos.editTop();
3623 memento.deviceId = entry->deviceId;
3624 memento.source = entry->source;
3625 memento.keyCode = entry->keyCode;
3626 memento.scanCode = entry->scanCode;
Jeff Brown49ed71d2010-12-06 17:13:33 -08003627 memento.flags = entry->flags;
Jeff Brownb88102f2010-09-08 11:49:43 -07003628 memento.downTime = entry->downTime;
Jeff Brownb88102f2010-09-08 11:49:43 -07003629 }
3630}
3631
Jeff Browncc0c1592011-02-19 05:07:28 -08003632void InputDispatcher::InputState::trackMotion(
Jeff Brownb88102f2010-09-08 11:49:43 -07003633 const MotionEntry* entry) {
3634 int32_t action = entry->action & AMOTION_EVENT_ACTION_MASK;
3635 for (size_t i = 0; i < mMotionMementos.size(); i++) {
3636 MotionMemento& memento = mMotionMementos.editItemAt(i);
3637 if (memento.deviceId == entry->deviceId
3638 && memento.source == entry->source) {
3639 switch (action) {
3640 case AMOTION_EVENT_ACTION_UP:
3641 case AMOTION_EVENT_ACTION_CANCEL:
Jeff Browncc0c1592011-02-19 05:07:28 -08003642 case AMOTION_EVENT_ACTION_HOVER_MOVE:
Jeff Brownb88102f2010-09-08 11:49:43 -07003643 mMotionMementos.removeAt(i);
Jeff Browncc0c1592011-02-19 05:07:28 -08003644 return;
Jeff Brownb88102f2010-09-08 11:49:43 -07003645
3646 case AMOTION_EVENT_ACTION_DOWN:
Jeff Browncc0c1592011-02-19 05:07:28 -08003647 mMotionMementos.removeAt(i);
3648 goto Found;
Jeff Brownb88102f2010-09-08 11:49:43 -07003649
3650 case AMOTION_EVENT_ACTION_POINTER_UP:
Jeff Browncc0c1592011-02-19 05:07:28 -08003651 case AMOTION_EVENT_ACTION_POINTER_DOWN:
Jeff Brownb88102f2010-09-08 11:49:43 -07003652 case AMOTION_EVENT_ACTION_MOVE:
Jeff Browncc0c1592011-02-19 05:07:28 -08003653 memento.setPointers(entry);
3654 return;
Jeff Brownb88102f2010-09-08 11:49:43 -07003655
3656 default:
Jeff Browncc0c1592011-02-19 05:07:28 -08003657 return;
Jeff Brownb88102f2010-09-08 11:49:43 -07003658 }
3659 }
3660 }
3661
Jeff Browncc0c1592011-02-19 05:07:28 -08003662Found:
3663 if (action == AMOTION_EVENT_ACTION_DOWN) {
Jeff Brownb88102f2010-09-08 11:49:43 -07003664 mMotionMementos.push();
3665 MotionMemento& memento = mMotionMementos.editTop();
3666 memento.deviceId = entry->deviceId;
3667 memento.source = entry->source;
3668 memento.xPrecision = entry->xPrecision;
3669 memento.yPrecision = entry->yPrecision;
3670 memento.downTime = entry->downTime;
3671 memento.setPointers(entry);
Jeff Brownb88102f2010-09-08 11:49:43 -07003672 }
3673}
3674
3675void InputDispatcher::InputState::MotionMemento::setPointers(const MotionEntry* entry) {
3676 pointerCount = entry->pointerCount;
3677 for (uint32_t i = 0; i < entry->pointerCount; i++) {
3678 pointerIds[i] = entry->pointerIds[i];
3679 pointerCoords[i] = entry->lastSample->pointerCoords[i];
3680 }
3681}
3682
Jeff Brownb6997262010-10-08 22:31:17 -07003683void InputDispatcher::InputState::synthesizeCancelationEvents(nsecs_t currentTime,
3684 Allocator* allocator, Vector<EventEntry*>& outEvents,
3685 CancelationOptions options) {
3686 for (size_t i = 0; i < mKeyMementos.size(); ) {
Jeff Brownb88102f2010-09-08 11:49:43 -07003687 const KeyMemento& memento = mKeyMementos.itemAt(i);
Jeff Brown49ed71d2010-12-06 17:13:33 -08003688 if (shouldCancelKey(memento, options)) {
Jeff Brownb6997262010-10-08 22:31:17 -07003689 outEvents.push(allocator->obtainKeyEntry(currentTime,
3690 memento.deviceId, memento.source, 0,
Jeff Brown49ed71d2010-12-06 17:13:33 -08003691 AKEY_EVENT_ACTION_UP, memento.flags | AKEY_EVENT_FLAG_CANCELED,
Jeff Brownb6997262010-10-08 22:31:17 -07003692 memento.keyCode, memento.scanCode, 0, 0, memento.downTime));
3693 mKeyMementos.removeAt(i);
3694 } else {
3695 i += 1;
3696 }
Jeff Brownb88102f2010-09-08 11:49:43 -07003697 }
3698
Jeff Browna1160a72010-10-11 18:22:53 -07003699 for (size_t i = 0; i < mMotionMementos.size(); ) {
Jeff Brownb88102f2010-09-08 11:49:43 -07003700 const MotionMemento& memento = mMotionMementos.itemAt(i);
Jeff Brown49ed71d2010-12-06 17:13:33 -08003701 if (shouldCancelMotion(memento, options)) {
Jeff Brownb6997262010-10-08 22:31:17 -07003702 outEvents.push(allocator->obtainMotionEntry(currentTime,
3703 memento.deviceId, memento.source, 0,
3704 AMOTION_EVENT_ACTION_CANCEL, 0, 0, 0,
3705 memento.xPrecision, memento.yPrecision, memento.downTime,
3706 memento.pointerCount, memento.pointerIds, memento.pointerCoords));
3707 mMotionMementos.removeAt(i);
3708 } else {
3709 i += 1;
3710 }
Jeff Brownb88102f2010-09-08 11:49:43 -07003711 }
3712}
3713
3714void InputDispatcher::InputState::clear() {
3715 mKeyMementos.clear();
3716 mMotionMementos.clear();
Jeff Brownb6997262010-10-08 22:31:17 -07003717}
3718
Jeff Brown9c9f1a32010-10-11 18:32:20 -07003719void InputDispatcher::InputState::copyPointerStateTo(InputState& other) const {
3720 for (size_t i = 0; i < mMotionMementos.size(); i++) {
3721 const MotionMemento& memento = mMotionMementos.itemAt(i);
3722 if (memento.source & AINPUT_SOURCE_CLASS_POINTER) {
3723 for (size_t j = 0; j < other.mMotionMementos.size(); ) {
3724 const MotionMemento& otherMemento = other.mMotionMementos.itemAt(j);
3725 if (memento.deviceId == otherMemento.deviceId
3726 && memento.source == otherMemento.source) {
3727 other.mMotionMementos.removeAt(j);
3728 } else {
3729 j += 1;
3730 }
3731 }
3732 other.mMotionMementos.push(memento);
3733 }
3734 }
3735}
3736
Jeff Brown49ed71d2010-12-06 17:13:33 -08003737bool InputDispatcher::InputState::shouldCancelKey(const KeyMemento& memento,
Jeff Brownb6997262010-10-08 22:31:17 -07003738 CancelationOptions options) {
3739 switch (options) {
Jeff Brown49ed71d2010-12-06 17:13:33 -08003740 case CANCEL_ALL_EVENTS:
Jeff Brownb6997262010-10-08 22:31:17 -07003741 case CANCEL_NON_POINTER_EVENTS:
Jeff Brownb6997262010-10-08 22:31:17 -07003742 return true;
Jeff Brown49ed71d2010-12-06 17:13:33 -08003743 case CANCEL_FALLBACK_EVENTS:
3744 return memento.flags & AKEY_EVENT_FLAG_FALLBACK;
3745 default:
3746 return false;
3747 }
3748}
3749
3750bool InputDispatcher::InputState::shouldCancelMotion(const MotionMemento& memento,
3751 CancelationOptions options) {
3752 switch (options) {
3753 case CANCEL_ALL_EVENTS:
3754 return true;
3755 case CANCEL_POINTER_EVENTS:
3756 return memento.source & AINPUT_SOURCE_CLASS_POINTER;
3757 case CANCEL_NON_POINTER_EVENTS:
3758 return !(memento.source & AINPUT_SOURCE_CLASS_POINTER);
3759 default:
3760 return false;
Jeff Brownb6997262010-10-08 22:31:17 -07003761 }
Jeff Brownb88102f2010-09-08 11:49:43 -07003762}
3763
3764
Jeff Brown46b9ac02010-04-22 18:58:52 -07003765// --- InputDispatcher::Connection ---
3766
Jeff Brown928e0542011-01-10 11:17:36 -08003767InputDispatcher::Connection::Connection(const sp<InputChannel>& inputChannel,
3768 const sp<InputWindowHandle>& inputWindowHandle) :
3769 status(STATUS_NORMAL), inputChannel(inputChannel), inputWindowHandle(inputWindowHandle),
3770 inputPublisher(inputChannel),
Jeff Brownbfaf3b92011-02-22 15:00:50 -08003771 lastEventTime(LONG_LONG_MAX), lastDispatchTime(LONG_LONG_MAX),
3772 originalKeyCodeForFallback(-1) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07003773}
3774
3775InputDispatcher::Connection::~Connection() {
3776}
3777
3778status_t InputDispatcher::Connection::initialize() {
3779 return inputPublisher.initialize();
3780}
3781
Jeff Brown9c3cda02010-06-15 01:31:58 -07003782const char* InputDispatcher::Connection::getStatusLabel() const {
3783 switch (status) {
3784 case STATUS_NORMAL:
3785 return "NORMAL";
3786
3787 case STATUS_BROKEN:
3788 return "BROKEN";
3789
Jeff Brown9c3cda02010-06-15 01:31:58 -07003790 case STATUS_ZOMBIE:
3791 return "ZOMBIE";
3792
3793 default:
3794 return "UNKNOWN";
3795 }
3796}
3797
Jeff Brown46b9ac02010-04-22 18:58:52 -07003798InputDispatcher::DispatchEntry* InputDispatcher::Connection::findQueuedDispatchEntryForEvent(
3799 const EventEntry* eventEntry) const {
Jeff Brownb88102f2010-09-08 11:49:43 -07003800 for (DispatchEntry* dispatchEntry = outboundQueue.tailSentinel.prev;
3801 dispatchEntry != & outboundQueue.headSentinel; dispatchEntry = dispatchEntry->prev) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07003802 if (dispatchEntry->eventEntry == eventEntry) {
3803 return dispatchEntry;
3804 }
3805 }
3806 return NULL;
3807}
3808
Jeff Brownb88102f2010-09-08 11:49:43 -07003809
Jeff Brown9c3cda02010-06-15 01:31:58 -07003810// --- InputDispatcher::CommandEntry ---
3811
Jeff Brownb88102f2010-09-08 11:49:43 -07003812InputDispatcher::CommandEntry::CommandEntry() :
3813 keyEntry(NULL) {
Jeff Brown9c3cda02010-06-15 01:31:58 -07003814}
3815
3816InputDispatcher::CommandEntry::~CommandEntry() {
3817}
3818
Jeff Brown46b9ac02010-04-22 18:58:52 -07003819
Jeff Brown01ce2e92010-09-26 22:20:12 -07003820// --- InputDispatcher::TouchState ---
3821
3822InputDispatcher::TouchState::TouchState() :
Jeff Brown58a2da82011-01-25 16:02:22 -08003823 down(false), split(false), deviceId(-1), source(0) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07003824}
3825
3826InputDispatcher::TouchState::~TouchState() {
3827}
3828
3829void InputDispatcher::TouchState::reset() {
3830 down = false;
3831 split = false;
Jeff Brown95712852011-01-04 19:41:59 -08003832 deviceId = -1;
Jeff Brown58a2da82011-01-25 16:02:22 -08003833 source = 0;
Jeff Brown01ce2e92010-09-26 22:20:12 -07003834 windows.clear();
3835}
3836
3837void InputDispatcher::TouchState::copyFrom(const TouchState& other) {
3838 down = other.down;
3839 split = other.split;
Jeff Brown95712852011-01-04 19:41:59 -08003840 deviceId = other.deviceId;
Jeff Brown58a2da82011-01-25 16:02:22 -08003841 source = other.source;
Jeff Brown01ce2e92010-09-26 22:20:12 -07003842 windows.clear();
3843 windows.appendVector(other.windows);
3844}
3845
3846void InputDispatcher::TouchState::addOrUpdateWindow(const InputWindow* window,
3847 int32_t targetFlags, BitSet32 pointerIds) {
3848 if (targetFlags & InputTarget::FLAG_SPLIT) {
3849 split = true;
3850 }
3851
3852 for (size_t i = 0; i < windows.size(); i++) {
3853 TouchedWindow& touchedWindow = windows.editItemAt(i);
3854 if (touchedWindow.window == window) {
3855 touchedWindow.targetFlags |= targetFlags;
3856 touchedWindow.pointerIds.value |= pointerIds.value;
3857 return;
3858 }
3859 }
3860
3861 windows.push();
3862
3863 TouchedWindow& touchedWindow = windows.editTop();
3864 touchedWindow.window = window;
3865 touchedWindow.targetFlags = targetFlags;
3866 touchedWindow.pointerIds = pointerIds;
3867 touchedWindow.channel = window->inputChannel;
3868}
3869
3870void InputDispatcher::TouchState::removeOutsideTouchWindows() {
3871 for (size_t i = 0 ; i < windows.size(); ) {
3872 if (windows[i].targetFlags & InputTarget::FLAG_OUTSIDE) {
3873 windows.removeAt(i);
3874 } else {
3875 i += 1;
3876 }
3877 }
3878}
3879
3880const InputWindow* InputDispatcher::TouchState::getFirstForegroundWindow() {
3881 for (size_t i = 0; i < windows.size(); i++) {
3882 if (windows[i].targetFlags & InputTarget::FLAG_FOREGROUND) {
3883 return windows[i].window;
3884 }
3885 }
3886 return NULL;
3887}
3888
3889
Jeff Brown46b9ac02010-04-22 18:58:52 -07003890// --- InputDispatcherThread ---
3891
3892InputDispatcherThread::InputDispatcherThread(const sp<InputDispatcherInterface>& dispatcher) :
3893 Thread(/*canCallJava*/ true), mDispatcher(dispatcher) {
3894}
3895
3896InputDispatcherThread::~InputDispatcherThread() {
3897}
3898
3899bool InputDispatcherThread::threadLoop() {
3900 mDispatcher->dispatchOnce();
3901 return true;
3902}
3903
3904} // namespace android