blob: 0606307e119b66357f554a872340e08c0ce5689f [file] [log] [blame]
Jeff Brownb4ff35d2011-01-02 16:37:43 -08001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070017#define LOG_TAG "InputDispatcher"
18
19//#define LOG_NDEBUG 0
20
21// Log detailed debug messages about each inbound event notification to the dispatcher.
Jeff Brown349703e2010-06-22 01:27:15 -070022#define DEBUG_INBOUND_EVENT_DETAILS 0
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070023
24// Log detailed debug messages about each outbound event processed by the dispatcher.
Jeff Brown349703e2010-06-22 01:27:15 -070025#define DEBUG_OUTBOUND_EVENT_DETAILS 0
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070026
27// Log debug messages about batching.
Jeff Brown349703e2010-06-22 01:27:15 -070028#define DEBUG_BATCHING 0
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070029
30// Log debug messages about the dispatch cycle.
Jeff Brown349703e2010-06-22 01:27:15 -070031#define DEBUG_DISPATCH_CYCLE 0
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070032
Jeff Brown9c3cda02010-06-15 01:31:58 -070033// Log debug messages about registrations.
Jeff Brown349703e2010-06-22 01:27:15 -070034#define DEBUG_REGISTRATION 0
Jeff Brown9c3cda02010-06-15 01:31:58 -070035
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070036// Log debug messages about performance statistics.
Jeff Brown349703e2010-06-22 01:27:15 -070037#define DEBUG_PERFORMANCE_STATISTICS 0
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070038
Jeff Brown7fbdc842010-06-17 20:52:56 -070039// Log debug messages about input event injection.
Jeff Brown349703e2010-06-22 01:27:15 -070040#define DEBUG_INJECTION 0
Jeff Brown7fbdc842010-06-17 20:52:56 -070041
Jeff Brownae9fc032010-08-18 15:51:08 -070042// Log debug messages about input event throttling.
43#define DEBUG_THROTTLING 0
44
Jeff Brownb88102f2010-09-08 11:49:43 -070045// Log debug messages about input focus tracking.
46#define DEBUG_FOCUS 0
47
48// Log debug messages about the app switch latency optimization.
49#define DEBUG_APP_SWITCH 0
50
Jeff Brownb4ff35d2011-01-02 16:37:43 -080051#include "InputDispatcher.h"
52
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070053#include <cutils/log.h>
Jeff Brownb88102f2010-09-08 11:49:43 -070054#include <ui/PowerManager.h>
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070055
56#include <stddef.h>
57#include <unistd.h>
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070058#include <errno.h>
59#include <limits.h>
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070060
Jeff Brownf2f487182010-10-01 17:46:21 -070061#define INDENT " "
62#define INDENT2 " "
63
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070064namespace android {
65
Jeff Brownb88102f2010-09-08 11:49:43 -070066// Default input dispatching timeout if there is no focused application or paused window
67// from which to determine an appropriate dispatching timeout.
68const nsecs_t DEFAULT_INPUT_DISPATCHING_TIMEOUT = 5000 * 1000000LL; // 5 sec
69
70// Amount of time to allow for all pending events to be processed when an app switch
71// key is on the way. This is used to preempt input dispatch and drop input events
72// when an application takes too long to respond and the user has pressed an app switch key.
73const nsecs_t APP_SWITCH_TIMEOUT = 500 * 1000000LL; // 0.5sec
74
Jeff Brown928e0542011-01-10 11:17:36 -080075// Amount of time to allow for an event to be dispatched (measured since its eventTime)
76// before considering it stale and dropping it.
77const nsecs_t STALE_EVENT_TIMEOUT = 10000 * 1000000LL; // 10sec
78
Jeff Brown46b9ac0a2010-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 Brown46b9ac0a2010-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 Brown46b9ac0a2010-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 Brown46b9ac0a2010-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 Brown46b9ac0a2010-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 Brown46b9ac0a2010-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 Brown46b9ac0a2010-04-22 18:58:52 -0700219
220 while (mConnectionsByReceiveFd.size() != 0) {
221 unregisterInputChannel(mConnectionsByReceiveFd.valueAt(0)->inputChannel);
222 }
Jeff Brown46b9ac0a2010-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 Brown46b9ac0a2010-04-22 18:58:52 -0700228
Jeff Brown46b9ac0a2010-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 Brown46b9ac0a2010-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 Brown46b9ac0a2010-04-22 18:58:52 -0700236 }
Jeff Brown46b9ac0a2010-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 Brown46b9ac0a2010-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 Brown46b9ac0a2010-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 Brown46b9ac0a2010-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 Brown46b9ac0a2010-04-22 18:58:52 -0700645 }
Jeff Brown46b9ac0a2010-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 Brown46b9ac0a2010-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 Brown46b9ac0a2010-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 Brown46b9ac0a2010-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 Brown46b9ac0a2010-04-22 18:58:52 -0700701
Jeff Brownb21fb102010-09-07 10:44:57 -0700702 mKeyRepeatState.nextRepeatTime = currentTime + keyRepeatDelay;
Jeff Brownb88102f2010-09-08 11:49:43 -0700703 return entry;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700704}
705
Jeff Brownb88102f2010-09-08 11:49:43 -0700706bool InputDispatcher::dispatchConfigurationChangedLocked(
707 nsecs_t currentTime, ConfigurationChangedEntry* entry) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700708#if DEBUG_OUTBOUND_EVENT_DETAILS
Jeff Brownb88102f2010-09-08 11:49:43 -0700709 LOGD("dispatchConfigurationChanged - eventTime=%lld", entry->eventTime);
710#endif
711
712 // Reset key repeating in case a keyboard device was added or removed or something.
713 resetKeyRepeatLocked();
714
715 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
716 CommandEntry* commandEntry = postCommandLocked(
717 & InputDispatcher::doNotifyConfigurationChangedInterruptible);
718 commandEntry->eventTime = entry->eventTime;
719 return true;
720}
721
722bool InputDispatcher::dispatchKeyLocked(
723 nsecs_t currentTime, KeyEntry* entry, nsecs_t keyRepeatTimeout,
Jeff Browne20c9e02010-10-11 14:20:19 -0700724 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Jeff Browne46a0a42010-11-02 17:58:22 -0700725 // Preprocessing.
726 if (! entry->dispatchInProgress) {
727 if (entry->repeatCount == 0
728 && entry->action == AKEY_EVENT_ACTION_DOWN
729 && (entry->policyFlags & POLICY_FLAG_TRUSTED)
730 && !entry->isInjected()) {
731 if (mKeyRepeatState.lastKeyEntry
732 && mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode) {
733 // We have seen two identical key downs in a row which indicates that the device
734 // driver is automatically generating key repeats itself. We take note of the
735 // repeat here, but we disable our own next key repeat timer since it is clear that
736 // we will not need to synthesize key repeats ourselves.
737 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
738 resetKeyRepeatLocked();
739 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
740 } else {
741 // Not a repeat. Save key down state in case we do see a repeat later.
742 resetKeyRepeatLocked();
743 mKeyRepeatState.nextRepeatTime = entry->eventTime + keyRepeatTimeout;
744 }
745 mKeyRepeatState.lastKeyEntry = entry;
746 entry->refCount += 1;
747 } else if (! entry->syntheticRepeat) {
748 resetKeyRepeatLocked();
749 }
750
Jeff Browne2e01262011-03-02 20:34:30 -0800751 if (entry->repeatCount == 1) {
752 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
753 } else {
754 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
755 }
756
Jeff Browne46a0a42010-11-02 17:58:22 -0700757 entry->dispatchInProgress = true;
758 resetTargetsLocked();
759
760 logOutboundKeyDetailsLocked("dispatchKey - ", entry);
761 }
762
Jeff Brown54a18252010-09-16 14:07:33 -0700763 // Give the policy a chance to intercept the key.
764 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
Jeff Browne20c9e02010-10-11 14:20:19 -0700765 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Jeff Brown54a18252010-09-16 14:07:33 -0700766 CommandEntry* commandEntry = postCommandLocked(
767 & InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
Jeff Browne20c9e02010-10-11 14:20:19 -0700768 if (mFocusedWindow) {
Jeff Brown928e0542011-01-10 11:17:36 -0800769 commandEntry->inputWindowHandle = mFocusedWindow->inputWindowHandle;
Jeff Brown54a18252010-09-16 14:07:33 -0700770 }
771 commandEntry->keyEntry = entry;
772 entry->refCount += 1;
773 return false; // wait for the command to run
774 } else {
775 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
776 }
777 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Jeff Browne20c9e02010-10-11 14:20:19 -0700778 if (*dropReason == DROP_REASON_NOT_DROPPED) {
779 *dropReason = DROP_REASON_POLICY;
780 }
Jeff Brown54a18252010-09-16 14:07:33 -0700781 }
782
783 // Clean up if dropping the event.
Jeff Browne20c9e02010-10-11 14:20:19 -0700784 if (*dropReason != DROP_REASON_NOT_DROPPED) {
Jeff Brown54a18252010-09-16 14:07:33 -0700785 resetTargetsLocked();
Jeff Brown3122e442010-10-11 23:32:49 -0700786 setInjectionResultLocked(entry, *dropReason == DROP_REASON_POLICY
787 ? INPUT_EVENT_INJECTION_SUCCEEDED : INPUT_EVENT_INJECTION_FAILED);
Jeff Brown54a18252010-09-16 14:07:33 -0700788 return true;
789 }
790
Jeff Brownb88102f2010-09-08 11:49:43 -0700791 // Identify targets.
792 if (! mCurrentInputTargetsValid) {
Jeff Brown01ce2e92010-09-26 22:20:12 -0700793 int32_t injectionResult = findFocusedWindowTargetsLocked(currentTime,
794 entry, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700795 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
796 return false;
797 }
798
799 setInjectionResultLocked(entry, injectionResult);
800 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
801 return true;
802 }
803
804 addMonitoringTargetsLocked();
Jeff Brown01ce2e92010-09-26 22:20:12 -0700805 commitTargetsLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -0700806 }
807
808 // Dispatch the key.
809 dispatchEventToCurrentInputTargetsLocked(currentTime, entry, false);
Jeff Brownb88102f2010-09-08 11:49:43 -0700810 return true;
811}
812
813void InputDispatcher::logOutboundKeyDetailsLocked(const char* prefix, const KeyEntry* entry) {
814#if DEBUG_OUTBOUND_EVENT_DETAILS
Jeff Brown90655042010-12-02 13:50:46 -0800815 LOGD("%seventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, "
Jeff Brownb88102f2010-09-08 11:49:43 -0700816 "action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, "
Jeff Browne46a0a42010-11-02 17:58:22 -0700817 "repeatCount=%d, downTime=%lld",
Jeff Brownb88102f2010-09-08 11:49:43 -0700818 prefix,
819 entry->eventTime, entry->deviceId, entry->source, entry->policyFlags,
820 entry->action, entry->flags, entry->keyCode, entry->scanCode, entry->metaState,
Jeff Browne46a0a42010-11-02 17:58:22 -0700821 entry->repeatCount, entry->downTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700822#endif
823}
824
825bool InputDispatcher::dispatchMotionLocked(
Jeff Browne20c9e02010-10-11 14:20:19 -0700826 nsecs_t currentTime, MotionEntry* entry, DropReason* dropReason, nsecs_t* nextWakeupTime) {
Jeff Browne46a0a42010-11-02 17:58:22 -0700827 // Preprocessing.
828 if (! entry->dispatchInProgress) {
829 entry->dispatchInProgress = true;
830 resetTargetsLocked();
831
832 logOutboundMotionDetailsLocked("dispatchMotion - ", entry);
833 }
834
Jeff Brown54a18252010-09-16 14:07:33 -0700835 // Clean up if dropping the event.
Jeff Browne20c9e02010-10-11 14:20:19 -0700836 if (*dropReason != DROP_REASON_NOT_DROPPED) {
Jeff Brown54a18252010-09-16 14:07:33 -0700837 resetTargetsLocked();
Jeff Brown3122e442010-10-11 23:32:49 -0700838 setInjectionResultLocked(entry, *dropReason == DROP_REASON_POLICY
839 ? INPUT_EVENT_INJECTION_SUCCEEDED : INPUT_EVENT_INJECTION_FAILED);
Jeff Brown54a18252010-09-16 14:07:33 -0700840 return true;
841 }
842
Jeff Brownb88102f2010-09-08 11:49:43 -0700843 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
844
845 // Identify targets.
Jeff Browncc0c1592011-02-19 05:07:28 -0800846 bool conflictingPointerActions = false;
Jeff Brownb88102f2010-09-08 11:49:43 -0700847 if (! mCurrentInputTargetsValid) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700848 int32_t injectionResult;
849 if (isPointerEvent) {
850 // Pointer event. (eg. touchscreen)
Jeff Brown01ce2e92010-09-26 22:20:12 -0700851 injectionResult = findTouchedWindowTargetsLocked(currentTime,
Jeff Browncc0c1592011-02-19 05:07:28 -0800852 entry, nextWakeupTime, &conflictingPointerActions);
Jeff Brownb88102f2010-09-08 11:49:43 -0700853 } else {
854 // Non touch event. (eg. trackball)
Jeff Brown01ce2e92010-09-26 22:20:12 -0700855 injectionResult = findFocusedWindowTargetsLocked(currentTime,
856 entry, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700857 }
858 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
859 return false;
860 }
861
862 setInjectionResultLocked(entry, injectionResult);
863 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
864 return true;
865 }
866
867 addMonitoringTargetsLocked();
Jeff Brown01ce2e92010-09-26 22:20:12 -0700868 commitTargetsLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -0700869 }
870
871 // Dispatch the motion.
Jeff Browncc0c1592011-02-19 05:07:28 -0800872 if (conflictingPointerActions) {
873 synthesizeCancelationEventsForAllConnectionsLocked(
874 InputState::CANCEL_POINTER_EVENTS, "Conflicting pointer actions.");
875 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700876 dispatchEventToCurrentInputTargetsLocked(currentTime, entry, false);
Jeff Brownb88102f2010-09-08 11:49:43 -0700877 return true;
878}
879
880
881void InputDispatcher::logOutboundMotionDetailsLocked(const char* prefix, const MotionEntry* entry) {
882#if DEBUG_OUTBOUND_EVENT_DETAILS
Jeff Brown90655042010-12-02 13:50:46 -0800883 LOGD("%seventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, "
Jeff Brown85a31762010-09-01 17:01:00 -0700884 "action=0x%x, flags=0x%x, "
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700885 "metaState=0x%x, edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%lld",
Jeff Brownb88102f2010-09-08 11:49:43 -0700886 prefix,
Jeff Brown85a31762010-09-01 17:01:00 -0700887 entry->eventTime, entry->deviceId, entry->source, entry->policyFlags,
888 entry->action, entry->flags,
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700889 entry->metaState, entry->edgeFlags, entry->xPrecision, entry->yPrecision,
890 entry->downTime);
891
892 // Print the most recent sample that we have available, this may change due to batching.
893 size_t sampleCount = 1;
Jeff Brownb88102f2010-09-08 11:49:43 -0700894 const MotionSample* sample = & entry->firstSample;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700895 for (; sample->next != NULL; sample = sample->next) {
896 sampleCount += 1;
897 }
898 for (uint32_t i = 0; i < entry->pointerCount; i++) {
Jeff Brown8d608662010-08-30 03:02:23 -0700899 LOGD(" Pointer %d: id=%d, x=%f, y=%f, pressure=%f, size=%f, "
Jeff Brown85a31762010-09-01 17:01:00 -0700900 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
Jeff Brown8d608662010-08-30 03:02:23 -0700901 "orientation=%f",
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700902 i, entry->pointerIds[i],
Jeff Brownebbd5d12011-02-17 13:01:34 -0800903 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
904 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
905 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
906 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
907 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
908 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
909 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
910 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
911 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700912 }
913
914 // Keep in mind that due to batching, it is possible for the number of samples actually
915 // dispatched to change before the application finally consumed them.
Jeff Brownc5ed5912010-07-14 18:48:53 -0700916 if (entry->action == AMOTION_EVENT_ACTION_MOVE) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700917 LOGD(" ... Total movement samples currently batched %d ...", sampleCount);
918 }
919#endif
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700920}
921
922void InputDispatcher::dispatchEventToCurrentInputTargetsLocked(nsecs_t currentTime,
923 EventEntry* eventEntry, bool resumeWithAppendedMotionSample) {
924#if DEBUG_DISPATCH_CYCLE
Jeff Brown9c3cda02010-06-15 01:31:58 -0700925 LOGD("dispatchEventToCurrentInputTargets - "
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700926 "resumeWithAppendedMotionSample=%s",
Jeff Brownb88102f2010-09-08 11:49:43 -0700927 toString(resumeWithAppendedMotionSample));
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700928#endif
929
Jeff Brown9c3cda02010-06-15 01:31:58 -0700930 assert(eventEntry->dispatchInProgress); // should already have been set to true
931
Jeff Browne2fe69e2010-10-18 13:21:23 -0700932 pokeUserActivityLocked(eventEntry);
933
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700934 for (size_t i = 0; i < mCurrentInputTargets.size(); i++) {
935 const InputTarget& inputTarget = mCurrentInputTargets.itemAt(i);
936
Jeff Brown519e0242010-09-15 15:18:56 -0700937 ssize_t connectionIndex = getConnectionIndexLocked(inputTarget.inputChannel);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700938 if (connectionIndex >= 0) {
939 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
Jeff Brown7fbdc842010-06-17 20:52:56 -0700940 prepareDispatchCycleLocked(currentTime, connection, eventEntry, & inputTarget,
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700941 resumeWithAppendedMotionSample);
942 } else {
Jeff Brownb6997262010-10-08 22:31:17 -0700943#if DEBUG_FOCUS
944 LOGD("Dropping event delivery to target with channel '%s' because it "
945 "is no longer registered with the input dispatcher.",
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700946 inputTarget.inputChannel->getName().string());
Jeff Brownb6997262010-10-08 22:31:17 -0700947#endif
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700948 }
949 }
950}
951
Jeff Brown54a18252010-09-16 14:07:33 -0700952void InputDispatcher::resetTargetsLocked() {
Jeff Brownb88102f2010-09-08 11:49:43 -0700953 mCurrentInputTargetsValid = false;
954 mCurrentInputTargets.clear();
Jeff Brownb88102f2010-09-08 11:49:43 -0700955 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_NONE;
Jeff Brown928e0542011-01-10 11:17:36 -0800956 mInputTargetWaitApplication.clear();
Jeff Brownb88102f2010-09-08 11:49:43 -0700957}
958
Jeff Brown01ce2e92010-09-26 22:20:12 -0700959void InputDispatcher::commitTargetsLocked() {
Jeff Brownb88102f2010-09-08 11:49:43 -0700960 mCurrentInputTargetsValid = true;
961}
962
963int32_t InputDispatcher::handleTargetsNotReadyLocked(nsecs_t currentTime,
964 const EventEntry* entry, const InputApplication* application, const InputWindow* window,
965 nsecs_t* nextWakeupTime) {
966 if (application == NULL && window == NULL) {
967 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY) {
968#if DEBUG_FOCUS
969 LOGD("Waiting for system to become ready for input.");
970#endif
971 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY;
972 mInputTargetWaitStartTime = currentTime;
973 mInputTargetWaitTimeoutTime = LONG_LONG_MAX;
974 mInputTargetWaitTimeoutExpired = false;
Jeff Brown928e0542011-01-10 11:17:36 -0800975 mInputTargetWaitApplication.clear();
Jeff Brownb88102f2010-09-08 11:49:43 -0700976 }
977 } else {
978 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
979#if DEBUG_FOCUS
Jeff Brown519e0242010-09-15 15:18:56 -0700980 LOGD("Waiting for application to become ready for input: %s",
981 getApplicationWindowLabelLocked(application, window).string());
Jeff Brownb88102f2010-09-08 11:49:43 -0700982#endif
983 nsecs_t timeout = window ? window->dispatchingTimeout :
984 application ? application->dispatchingTimeout : DEFAULT_INPUT_DISPATCHING_TIMEOUT;
985
986 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY;
987 mInputTargetWaitStartTime = currentTime;
988 mInputTargetWaitTimeoutTime = currentTime + timeout;
989 mInputTargetWaitTimeoutExpired = false;
Jeff Brown928e0542011-01-10 11:17:36 -0800990 mInputTargetWaitApplication.clear();
991
992 if (window && window->inputWindowHandle != NULL) {
993 mInputTargetWaitApplication =
994 window->inputWindowHandle->getInputApplicationHandle();
995 }
996 if (mInputTargetWaitApplication == NULL && application) {
997 mInputTargetWaitApplication = application->inputApplicationHandle;
998 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700999 }
1000 }
1001
1002 if (mInputTargetWaitTimeoutExpired) {
1003 return INPUT_EVENT_INJECTION_TIMED_OUT;
1004 }
1005
1006 if (currentTime >= mInputTargetWaitTimeoutTime) {
Jeff Brown519e0242010-09-15 15:18:56 -07001007 onANRLocked(currentTime, application, window, entry->eventTime, mInputTargetWaitStartTime);
Jeff Brownb88102f2010-09-08 11:49:43 -07001008
1009 // Force poll loop to wake up immediately on next iteration once we get the
1010 // ANR response back from the policy.
1011 *nextWakeupTime = LONG_LONG_MIN;
1012 return INPUT_EVENT_INJECTION_PENDING;
1013 } else {
1014 // Force poll loop to wake up when timeout is due.
1015 if (mInputTargetWaitTimeoutTime < *nextWakeupTime) {
1016 *nextWakeupTime = mInputTargetWaitTimeoutTime;
1017 }
1018 return INPUT_EVENT_INJECTION_PENDING;
1019 }
1020}
1021
Jeff Brown519e0242010-09-15 15:18:56 -07001022void InputDispatcher::resumeAfterTargetsNotReadyTimeoutLocked(nsecs_t newTimeout,
1023 const sp<InputChannel>& inputChannel) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001024 if (newTimeout > 0) {
1025 // Extend the timeout.
1026 mInputTargetWaitTimeoutTime = now() + newTimeout;
1027 } else {
1028 // Give up.
1029 mInputTargetWaitTimeoutExpired = true;
Jeff Brown519e0242010-09-15 15:18:56 -07001030
Jeff Brown01ce2e92010-09-26 22:20:12 -07001031 // Release the touch targets.
1032 mTouchState.reset();
Jeff Brown2a95c2a2010-09-16 12:31:46 -07001033
Jeff Brown519e0242010-09-15 15:18:56 -07001034 // Input state will not be realistic. Mark it out of sync.
Jeff Browndc3e0052010-09-16 11:02:16 -07001035 if (inputChannel.get()) {
1036 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
1037 if (connectionIndex >= 0) {
1038 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
Jeff Brown00045a72010-12-09 18:10:30 -08001039 if (connection->status == Connection::STATUS_NORMAL) {
1040 synthesizeCancelationEventsForConnectionLocked(
1041 connection, InputState::CANCEL_ALL_EVENTS,
1042 "application not responding");
1043 }
Jeff Browndc3e0052010-09-16 11:02:16 -07001044 }
Jeff Brown519e0242010-09-15 15:18:56 -07001045 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001046 }
1047}
1048
Jeff Brown519e0242010-09-15 15:18:56 -07001049nsecs_t InputDispatcher::getTimeSpentWaitingForApplicationLocked(
Jeff Brownb88102f2010-09-08 11:49:43 -07001050 nsecs_t currentTime) {
1051 if (mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
1052 return currentTime - mInputTargetWaitStartTime;
1053 }
1054 return 0;
1055}
1056
1057void InputDispatcher::resetANRTimeoutsLocked() {
1058#if DEBUG_FOCUS
1059 LOGD("Resetting ANR timeouts.");
1060#endif
1061
Jeff Brownb88102f2010-09-08 11:49:43 -07001062 // Reset input target wait timeout.
1063 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_NONE;
1064}
1065
Jeff Brown01ce2e92010-09-26 22:20:12 -07001066int32_t InputDispatcher::findFocusedWindowTargetsLocked(nsecs_t currentTime,
1067 const EventEntry* entry, nsecs_t* nextWakeupTime) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001068 mCurrentInputTargets.clear();
1069
1070 int32_t injectionResult;
1071
1072 // If there is no currently focused window and no focused application
1073 // then drop the event.
1074 if (! mFocusedWindow) {
1075 if (mFocusedApplication) {
1076#if DEBUG_FOCUS
1077 LOGD("Waiting because there is no focused window but there is a "
Jeff Brown519e0242010-09-15 15:18:56 -07001078 "focused application that may eventually add a window: %s.",
1079 getApplicationWindowLabelLocked(mFocusedApplication, NULL).string());
Jeff Brownb88102f2010-09-08 11:49:43 -07001080#endif
1081 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
1082 mFocusedApplication, NULL, nextWakeupTime);
1083 goto Unresponsive;
1084 }
1085
1086 LOGI("Dropping event because there is no focused window or focused application.");
1087 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1088 goto Failed;
1089 }
1090
1091 // Check permissions.
Jeff Brown01ce2e92010-09-26 22:20:12 -07001092 if (! checkInjectionPermission(mFocusedWindow, entry->injectionState)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001093 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1094 goto Failed;
1095 }
1096
1097 // If the currently focused window is paused then keep waiting.
1098 if (mFocusedWindow->paused) {
1099#if DEBUG_FOCUS
1100 LOGD("Waiting because focused window is paused.");
1101#endif
1102 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
1103 mFocusedApplication, mFocusedWindow, nextWakeupTime);
1104 goto Unresponsive;
1105 }
1106
Jeff Brown519e0242010-09-15 15:18:56 -07001107 // If the currently focused window is still working on previous events then keep waiting.
1108 if (! isWindowFinishedWithPreviousInputLocked(mFocusedWindow)) {
1109#if DEBUG_FOCUS
1110 LOGD("Waiting because focused window still processing previous input.");
1111#endif
1112 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
1113 mFocusedApplication, mFocusedWindow, nextWakeupTime);
1114 goto Unresponsive;
1115 }
1116
Jeff Brownb88102f2010-09-08 11:49:43 -07001117 // Success! Output targets.
1118 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001119 addWindowTargetLocked(mFocusedWindow, InputTarget::FLAG_FOREGROUND, BitSet32(0));
Jeff Brownb88102f2010-09-08 11:49:43 -07001120
1121 // Done.
1122Failed:
1123Unresponsive:
Jeff Brown519e0242010-09-15 15:18:56 -07001124 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
1125 updateDispatchStatisticsLocked(currentTime, entry,
1126 injectionResult, timeSpentWaitingForApplication);
Jeff Brownb88102f2010-09-08 11:49:43 -07001127#if DEBUG_FOCUS
Jeff Brown519e0242010-09-15 15:18:56 -07001128 LOGD("findFocusedWindow finished: injectionResult=%d, "
1129 "timeSpendWaitingForApplication=%0.1fms",
1130 injectionResult, timeSpentWaitingForApplication / 1000000.0);
Jeff Brownb88102f2010-09-08 11:49:43 -07001131#endif
1132 return injectionResult;
1133}
1134
Jeff Brown01ce2e92010-09-26 22:20:12 -07001135int32_t InputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime,
Jeff Browncc0c1592011-02-19 05:07:28 -08001136 const MotionEntry* entry, nsecs_t* nextWakeupTime, bool* outConflictingPointerActions) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001137 enum InjectionPermission {
1138 INJECTION_PERMISSION_UNKNOWN,
1139 INJECTION_PERMISSION_GRANTED,
1140 INJECTION_PERMISSION_DENIED
1141 };
1142
Jeff Brownb88102f2010-09-08 11:49:43 -07001143 mCurrentInputTargets.clear();
1144
1145 nsecs_t startTime = now();
1146
1147 // For security reasons, we defer updating the touch state until we are sure that
1148 // event injection will be allowed.
1149 //
1150 // FIXME In the original code, screenWasOff could never be set to true.
1151 // The reason is that the POLICY_FLAG_WOKE_HERE
1152 // and POLICY_FLAG_BRIGHT_HERE flags were set only when preprocessing raw
1153 // EV_KEY, EV_REL and EV_ABS events. As it happens, the touch event was
1154 // actually enqueued using the policyFlags that appeared in the final EV_SYN
1155 // events upon which no preprocessing took place. So policyFlags was always 0.
1156 // In the new native input dispatcher we're a bit more careful about event
1157 // preprocessing so the touches we receive can actually have non-zero policyFlags.
1158 // Unfortunately we obtain undesirable behavior.
1159 //
1160 // Here's what happens:
1161 //
1162 // When the device dims in anticipation of going to sleep, touches
1163 // in windows which have FLAG_TOUCHABLE_WHEN_WAKING cause
1164 // the device to brighten and reset the user activity timer.
1165 // Touches on other windows (such as the launcher window)
1166 // are dropped. Then after a moment, the device goes to sleep. Oops.
1167 //
1168 // Also notice how screenWasOff was being initialized using POLICY_FLAG_BRIGHT_HERE
1169 // instead of POLICY_FLAG_WOKE_HERE...
1170 //
1171 bool screenWasOff = false; // original policy: policyFlags & POLICY_FLAG_BRIGHT_HERE;
1172
1173 int32_t action = entry->action;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001174 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Jeff Brownb88102f2010-09-08 11:49:43 -07001175
1176 // Update the touch state as needed based on the properties of the touch event.
Jeff Brown01ce2e92010-09-26 22:20:12 -07001177 int32_t injectionResult = INPUT_EVENT_INJECTION_PENDING;
1178 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
Jeff Browncc0c1592011-02-19 05:07:28 -08001179
1180 bool isSplit = mTouchState.split;
1181 bool wrongDevice = mTouchState.down
1182 && (mTouchState.deviceId != entry->deviceId
1183 || mTouchState.source != entry->source);
1184 if (maskedAction == AMOTION_EVENT_ACTION_DOWN
Jeff Brown33bbfd22011-02-24 20:55:35 -08001185 || maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE
1186 || maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
Jeff Browncc0c1592011-02-19 05:07:28 -08001187 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
1188 if (wrongDevice && !down) {
1189 mTempTouchState.copyFrom(mTouchState);
1190 } else {
1191 mTempTouchState.reset();
1192 mTempTouchState.down = down;
1193 mTempTouchState.deviceId = entry->deviceId;
1194 mTempTouchState.source = entry->source;
1195 isSplit = false;
1196 wrongDevice = false;
1197 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001198 } else {
1199 mTempTouchState.copyFrom(mTouchState);
Jeff Browncc0c1592011-02-19 05:07:28 -08001200 }
1201 if (wrongDevice) {
Jeff Brown95712852011-01-04 19:41:59 -08001202#if DEBUG_INPUT_DISPATCHER_POLICY
Jeff Browncc0c1592011-02-19 05:07:28 -08001203 LOGD("Dropping event because a pointer for a different device is already down.");
Jeff Brown95712852011-01-04 19:41:59 -08001204#endif
Jeff Browncc0c1592011-02-19 05:07:28 -08001205 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1206 goto Failed;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001207 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001208
Jeff Brown01ce2e92010-09-26 22:20:12 -07001209 if (maskedAction == AMOTION_EVENT_ACTION_DOWN
Jeff Browncc0c1592011-02-19 05:07:28 -08001210 || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)
Jeff Brown33bbfd22011-02-24 20:55:35 -08001211 || maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE
1212 || maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
1213 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
Jeff Brownb88102f2010-09-08 11:49:43 -07001214
Jeff Brown01ce2e92010-09-26 22:20:12 -07001215 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Jeff Brown91c69ab2011-02-14 17:03:18 -08001216 int32_t x = int32_t(entry->firstSample.pointerCoords[pointerIndex].
Jeff Brownebbd5d12011-02-17 13:01:34 -08001217 getAxisValue(AMOTION_EVENT_AXIS_X));
Jeff Brown91c69ab2011-02-14 17:03:18 -08001218 int32_t y = int32_t(entry->firstSample.pointerCoords[pointerIndex].
Jeff Brownebbd5d12011-02-17 13:01:34 -08001219 getAxisValue(AMOTION_EVENT_AXIS_Y));
Jeff Brown01ce2e92010-09-26 22:20:12 -07001220 const InputWindow* newTouchedWindow = NULL;
1221 const InputWindow* topErrorWindow = NULL;
Jeff Brownb88102f2010-09-08 11:49:43 -07001222
1223 // Traverse windows from front to back to find touched window and outside targets.
1224 size_t numWindows = mWindows.size();
1225 for (size_t i = 0; i < numWindows; i++) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001226 const InputWindow* window = & mWindows.editItemAt(i);
Jeff Brownb88102f2010-09-08 11:49:43 -07001227 int32_t flags = window->layoutParamsFlags;
1228
1229 if (flags & InputWindow::FLAG_SYSTEM_ERROR) {
1230 if (! topErrorWindow) {
1231 topErrorWindow = window;
1232 }
1233 }
1234
1235 if (window->visible) {
1236 if (! (flags & InputWindow::FLAG_NOT_TOUCHABLE)) {
1237 bool isTouchModal = (flags & (InputWindow::FLAG_NOT_FOCUSABLE
1238 | InputWindow::FLAG_NOT_TOUCH_MODAL)) == 0;
Jeff Brownfbf09772011-01-16 14:06:57 -08001239 if (isTouchModal || window->touchableRegionContainsPoint(x, y)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001240 if (! screenWasOff || flags & InputWindow::FLAG_TOUCHABLE_WHEN_WAKING) {
1241 newTouchedWindow = window;
Jeff Brownb88102f2010-09-08 11:49:43 -07001242 }
1243 break; // found touched window, exit window loop
1244 }
1245 }
1246
Jeff Brown01ce2e92010-09-26 22:20:12 -07001247 if (maskedAction == AMOTION_EVENT_ACTION_DOWN
1248 && (flags & InputWindow::FLAG_WATCH_OUTSIDE_TOUCH)) {
Jeff Brown19dfc832010-10-05 12:26:23 -07001249 int32_t outsideTargetFlags = InputTarget::FLAG_OUTSIDE;
1250 if (isWindowObscuredAtPointLocked(window, x, y)) {
1251 outsideTargetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1252 }
1253
1254 mTempTouchState.addOrUpdateWindow(window, outsideTargetFlags, BitSet32(0));
Jeff Brownb88102f2010-09-08 11:49:43 -07001255 }
1256 }
1257 }
1258
1259 // If there is an error window but it is not taking focus (typically because
1260 // it is invisible) then wait for it. Any other focused window may in
1261 // fact be in ANR state.
1262 if (topErrorWindow && newTouchedWindow != topErrorWindow) {
1263#if DEBUG_FOCUS
1264 LOGD("Waiting because system error window is pending.");
1265#endif
1266 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
1267 NULL, NULL, nextWakeupTime);
1268 injectionPermission = INJECTION_PERMISSION_UNKNOWN;
1269 goto Unresponsive;
1270 }
1271
Jeff Brown01ce2e92010-09-26 22:20:12 -07001272 // Figure out whether splitting will be allowed for this window.
Jeff Brown46e75292010-11-10 16:53:45 -08001273 if (newTouchedWindow && newTouchedWindow->supportsSplitTouch()) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001274 // New window supports splitting.
1275 isSplit = true;
1276 } else if (isSplit) {
1277 // New window does not support splitting but we have already split events.
1278 // Assign the pointer to the first foreground window we find.
1279 // (May be NULL which is why we put this code block before the next check.)
1280 newTouchedWindow = mTempTouchState.getFirstForegroundWindow();
1281 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001282
Jeff Brownb88102f2010-09-08 11:49:43 -07001283 // If we did not find a touched window then fail.
1284 if (! newTouchedWindow) {
1285 if (mFocusedApplication) {
1286#if DEBUG_FOCUS
1287 LOGD("Waiting because there is no touched window but there is a "
Jeff Brown519e0242010-09-15 15:18:56 -07001288 "focused application that may eventually add a new window: %s.",
1289 getApplicationWindowLabelLocked(mFocusedApplication, NULL).string());
Jeff Brownb88102f2010-09-08 11:49:43 -07001290#endif
1291 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
1292 mFocusedApplication, NULL, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -07001293 goto Unresponsive;
1294 }
1295
1296 LOGI("Dropping event because there is no touched window or focused application.");
1297 injectionResult = INPUT_EVENT_INJECTION_FAILED;
Jeff Brownb88102f2010-09-08 11:49:43 -07001298 goto Failed;
1299 }
1300
Jeff Brown19dfc832010-10-05 12:26:23 -07001301 // Set target flags.
1302 int32_t targetFlags = InputTarget::FLAG_FOREGROUND;
1303 if (isSplit) {
1304 targetFlags |= InputTarget::FLAG_SPLIT;
1305 }
1306 if (isWindowObscuredAtPointLocked(newTouchedWindow, x, y)) {
1307 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1308 }
1309
Jeff Brown01ce2e92010-09-26 22:20:12 -07001310 // Update the temporary touch state.
1311 BitSet32 pointerIds;
1312 if (isSplit) {
1313 uint32_t pointerId = entry->pointerIds[pointerIndex];
1314 pointerIds.markBit(pointerId);
Jeff Brownb88102f2010-09-08 11:49:43 -07001315 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001316 mTempTouchState.addOrUpdateWindow(newTouchedWindow, targetFlags, pointerIds);
Jeff Brownb88102f2010-09-08 11:49:43 -07001317 } else {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001318 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
Jeff Brownb88102f2010-09-08 11:49:43 -07001319
1320 // If the pointer is not currently down, then ignore the event.
Jeff Brown01ce2e92010-09-26 22:20:12 -07001321 if (! mTempTouchState.down) {
Jeff Brown76860e32010-10-25 17:37:46 -07001322#if DEBUG_INPUT_DISPATCHER_POLICY
1323 LOGD("Dropping event because the pointer is not down or we previously "
1324 "dropped the pointer down event.");
1325#endif
Jeff Brownb88102f2010-09-08 11:49:43 -07001326 injectionResult = INPUT_EVENT_INJECTION_FAILED;
Jeff Brownb88102f2010-09-08 11:49:43 -07001327 goto Failed;
1328 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001329 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001330
Jeff Brown01ce2e92010-09-26 22:20:12 -07001331 // Check permission to inject into all touched foreground windows and ensure there
1332 // is at least one touched foreground window.
1333 {
1334 bool haveForegroundWindow = false;
1335 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1336 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1337 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1338 haveForegroundWindow = true;
1339 if (! checkInjectionPermission(touchedWindow.window, entry->injectionState)) {
1340 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1341 injectionPermission = INJECTION_PERMISSION_DENIED;
1342 goto Failed;
1343 }
1344 }
1345 }
1346 if (! haveForegroundWindow) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001347#if DEBUG_INPUT_DISPATCHER_POLICY
Jeff Brown01ce2e92010-09-26 22:20:12 -07001348 LOGD("Dropping event because there is no touched foreground window to receive it.");
Jeff Brownb88102f2010-09-08 11:49:43 -07001349#endif
1350 injectionResult = INPUT_EVENT_INJECTION_FAILED;
Jeff Brownb88102f2010-09-08 11:49:43 -07001351 goto Failed;
1352 }
1353
Jeff Brown01ce2e92010-09-26 22:20:12 -07001354 // Permission granted to injection into all touched foreground windows.
1355 injectionPermission = INJECTION_PERMISSION_GRANTED;
1356 }
Jeff Brown519e0242010-09-15 15:18:56 -07001357
Jeff Brown01ce2e92010-09-26 22:20:12 -07001358 // Ensure all touched foreground windows are ready for new input.
1359 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1360 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1361 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1362 // If the touched window is paused then keep waiting.
1363 if (touchedWindow.window->paused) {
1364#if DEBUG_INPUT_DISPATCHER_POLICY
1365 LOGD("Waiting because touched window is paused.");
Jeff Brown519e0242010-09-15 15:18:56 -07001366#endif
Jeff Brown01ce2e92010-09-26 22:20:12 -07001367 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
1368 NULL, touchedWindow.window, nextWakeupTime);
1369 goto Unresponsive;
1370 }
1371
1372 // If the touched window is still working on previous events then keep waiting.
1373 if (! isWindowFinishedWithPreviousInputLocked(touchedWindow.window)) {
1374#if DEBUG_FOCUS
1375 LOGD("Waiting because touched window still processing previous input.");
1376#endif
1377 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
1378 NULL, touchedWindow.window, nextWakeupTime);
1379 goto Unresponsive;
1380 }
1381 }
1382 }
1383
1384 // If this is the first pointer going down and the touched window has a wallpaper
1385 // then also add the touched wallpaper windows so they are locked in for the duration
1386 // of the touch gesture.
Jeff Brown33bbfd22011-02-24 20:55:35 -08001387 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
1388 // engine only supports touch events. We would need to add a mechanism similar
1389 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
1390 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001391 const InputWindow* foregroundWindow = mTempTouchState.getFirstForegroundWindow();
1392 if (foregroundWindow->hasWallpaper) {
1393 for (size_t i = 0; i < mWindows.size(); i++) {
1394 const InputWindow* window = & mWindows[i];
1395 if (window->layoutParamsType == InputWindow::TYPE_WALLPAPER) {
Jeff Brown19dfc832010-10-05 12:26:23 -07001396 mTempTouchState.addOrUpdateWindow(window,
1397 InputTarget::FLAG_WINDOW_IS_OBSCURED, BitSet32(0));
Jeff Brown01ce2e92010-09-26 22:20:12 -07001398 }
1399 }
1400 }
1401 }
1402
Jeff Brownb88102f2010-09-08 11:49:43 -07001403 // Success! Output targets.
1404 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
Jeff Brownb88102f2010-09-08 11:49:43 -07001405
Jeff Brown01ce2e92010-09-26 22:20:12 -07001406 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1407 const TouchedWindow& touchedWindow = mTempTouchState.windows.itemAt(i);
1408 addWindowTargetLocked(touchedWindow.window, touchedWindow.targetFlags,
1409 touchedWindow.pointerIds);
Jeff Brownb88102f2010-09-08 11:49:43 -07001410 }
1411
Jeff Brown01ce2e92010-09-26 22:20:12 -07001412 // Drop the outside touch window since we will not care about them in the next iteration.
1413 mTempTouchState.removeOutsideTouchWindows();
1414
Jeff Brownb88102f2010-09-08 11:49:43 -07001415Failed:
1416 // Check injection permission once and for all.
1417 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001418 if (checkInjectionPermission(NULL, entry->injectionState)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001419 injectionPermission = INJECTION_PERMISSION_GRANTED;
1420 } else {
1421 injectionPermission = INJECTION_PERMISSION_DENIED;
1422 }
1423 }
1424
1425 // Update final pieces of touch state if the injector had permission.
1426 if (injectionPermission == INJECTION_PERMISSION_GRANTED) {
Jeff Brown95712852011-01-04 19:41:59 -08001427 if (!wrongDevice) {
1428 if (maskedAction == AMOTION_EVENT_ACTION_UP
Jeff Browncc0c1592011-02-19 05:07:28 -08001429 || maskedAction == AMOTION_EVENT_ACTION_CANCEL
1430 || maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Jeff Brown95712852011-01-04 19:41:59 -08001431 // All pointers up or canceled.
Jeff Brown33bbfd22011-02-24 20:55:35 -08001432 mTouchState.reset();
Jeff Brown95712852011-01-04 19:41:59 -08001433 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1434 // First pointer went down.
1435 if (mTouchState.down) {
Jeff Browncc0c1592011-02-19 05:07:28 -08001436 *outConflictingPointerActions = true;
Jeff Brownb6997262010-10-08 22:31:17 -07001437#if DEBUG_FOCUS
Jeff Brown95712852011-01-04 19:41:59 -08001438 LOGD("Pointer down received while already down.");
Jeff Brownb6997262010-10-08 22:31:17 -07001439#endif
Jeff Brown95712852011-01-04 19:41:59 -08001440 }
Jeff Brown33bbfd22011-02-24 20:55:35 -08001441 mTouchState.copyFrom(mTempTouchState);
Jeff Brown95712852011-01-04 19:41:59 -08001442 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
1443 // One pointer went up.
1444 if (isSplit) {
1445 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
1446 uint32_t pointerId = entry->pointerIds[pointerIndex];
Jeff Brownb88102f2010-09-08 11:49:43 -07001447
Jeff Brown95712852011-01-04 19:41:59 -08001448 for (size_t i = 0; i < mTempTouchState.windows.size(); ) {
1449 TouchedWindow& touchedWindow = mTempTouchState.windows.editItemAt(i);
1450 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
1451 touchedWindow.pointerIds.clearBit(pointerId);
1452 if (touchedWindow.pointerIds.isEmpty()) {
1453 mTempTouchState.windows.removeAt(i);
1454 continue;
1455 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001456 }
Jeff Brown95712852011-01-04 19:41:59 -08001457 i += 1;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001458 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001459 }
Jeff Brown33bbfd22011-02-24 20:55:35 -08001460 mTouchState.copyFrom(mTempTouchState);
1461 } else if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
1462 // Discard temporary touch state since it was only valid for this action.
1463 } else {
1464 // Save changes to touch state as-is for all other actions.
1465 mTouchState.copyFrom(mTempTouchState);
Jeff Brownb88102f2010-09-08 11:49:43 -07001466 }
Jeff Brown95712852011-01-04 19:41:59 -08001467 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001468 } else {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001469#if DEBUG_FOCUS
1470 LOGD("Not updating touch focus because injection was denied.");
1471#endif
Jeff Brownb88102f2010-09-08 11:49:43 -07001472 }
1473
1474Unresponsive:
Jeff Brown120a4592010-10-27 18:43:51 -07001475 // Reset temporary touch state to ensure we release unnecessary references to input channels.
1476 mTempTouchState.reset();
1477
Jeff Brown519e0242010-09-15 15:18:56 -07001478 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
1479 updateDispatchStatisticsLocked(currentTime, entry,
1480 injectionResult, timeSpentWaitingForApplication);
Jeff Brownb88102f2010-09-08 11:49:43 -07001481#if DEBUG_FOCUS
Jeff Brown01ce2e92010-09-26 22:20:12 -07001482 LOGD("findTouchedWindow finished: injectionResult=%d, injectionPermission=%d, "
1483 "timeSpentWaitingForApplication=%0.1fms",
Jeff Brown519e0242010-09-15 15:18:56 -07001484 injectionResult, injectionPermission, timeSpentWaitingForApplication / 1000000.0);
Jeff Brownb88102f2010-09-08 11:49:43 -07001485#endif
1486 return injectionResult;
1487}
1488
Jeff Brown01ce2e92010-09-26 22:20:12 -07001489void InputDispatcher::addWindowTargetLocked(const InputWindow* window, int32_t targetFlags,
1490 BitSet32 pointerIds) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001491 mCurrentInputTargets.push();
1492
1493 InputTarget& target = mCurrentInputTargets.editTop();
1494 target.inputChannel = window->inputChannel;
1495 target.flags = targetFlags;
Jeff Brownb88102f2010-09-08 11:49:43 -07001496 target.xOffset = - window->frameLeft;
1497 target.yOffset = - window->frameTop;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001498 target.pointerIds = pointerIds;
Jeff Brownb88102f2010-09-08 11:49:43 -07001499}
1500
1501void InputDispatcher::addMonitoringTargetsLocked() {
1502 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
1503 mCurrentInputTargets.push();
1504
1505 InputTarget& target = mCurrentInputTargets.editTop();
1506 target.inputChannel = mMonitoringChannels[i];
1507 target.flags = 0;
Jeff Brownb88102f2010-09-08 11:49:43 -07001508 target.xOffset = 0;
1509 target.yOffset = 0;
1510 }
1511}
1512
1513bool InputDispatcher::checkInjectionPermission(const InputWindow* window,
Jeff Brown01ce2e92010-09-26 22:20:12 -07001514 const InjectionState* injectionState) {
1515 if (injectionState
Jeff Brownb6997262010-10-08 22:31:17 -07001516 && (window == NULL || window->ownerUid != injectionState->injectorUid)
1517 && !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
1518 if (window) {
1519 LOGW("Permission denied: injecting event from pid %d uid %d to window "
1520 "with input channel %s owned by uid %d",
1521 injectionState->injectorPid, injectionState->injectorUid,
1522 window->inputChannel->getName().string(),
1523 window->ownerUid);
1524 } else {
1525 LOGW("Permission denied: injecting event from pid %d uid %d",
1526 injectionState->injectorPid, injectionState->injectorUid);
Jeff Brownb88102f2010-09-08 11:49:43 -07001527 }
Jeff Brownb6997262010-10-08 22:31:17 -07001528 return false;
Jeff Brownb88102f2010-09-08 11:49:43 -07001529 }
1530 return true;
1531}
1532
Jeff Brown19dfc832010-10-05 12:26:23 -07001533bool InputDispatcher::isWindowObscuredAtPointLocked(
1534 const InputWindow* window, int32_t x, int32_t y) const {
Jeff Brownb88102f2010-09-08 11:49:43 -07001535 size_t numWindows = mWindows.size();
1536 for (size_t i = 0; i < numWindows; i++) {
1537 const InputWindow* other = & mWindows.itemAt(i);
1538 if (other == window) {
1539 break;
1540 }
Jeff Brown19dfc832010-10-05 12:26:23 -07001541 if (other->visible && ! other->isTrustedOverlay() && other->frameContainsPoint(x, y)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001542 return true;
1543 }
1544 }
1545 return false;
1546}
1547
Jeff Brown519e0242010-09-15 15:18:56 -07001548bool InputDispatcher::isWindowFinishedWithPreviousInputLocked(const InputWindow* window) {
1549 ssize_t connectionIndex = getConnectionIndexLocked(window->inputChannel);
1550 if (connectionIndex >= 0) {
1551 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
1552 return connection->outboundQueue.isEmpty();
1553 } else {
1554 return true;
1555 }
1556}
1557
1558String8 InputDispatcher::getApplicationWindowLabelLocked(const InputApplication* application,
1559 const InputWindow* window) {
1560 if (application) {
1561 if (window) {
1562 String8 label(application->name);
1563 label.append(" - ");
1564 label.append(window->name);
1565 return label;
1566 } else {
1567 return application->name;
1568 }
1569 } else if (window) {
1570 return window->name;
1571 } else {
1572 return String8("<unknown application or window>");
1573 }
1574}
1575
Jeff Browne2fe69e2010-10-18 13:21:23 -07001576void InputDispatcher::pokeUserActivityLocked(const EventEntry* eventEntry) {
Jeff Brown56194eb2011-03-02 19:23:13 -08001577 int32_t eventType = POWER_MANAGER_OTHER_EVENT;
Jeff Brown4d396052010-10-29 21:50:21 -07001578 switch (eventEntry->type) {
1579 case EventEntry::TYPE_MOTION: {
Jeff Browne2fe69e2010-10-18 13:21:23 -07001580 const MotionEntry* motionEntry = static_cast<const MotionEntry*>(eventEntry);
Jeff Brown4d396052010-10-29 21:50:21 -07001581 if (motionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
1582 return;
1583 }
1584
Jeff Brown56194eb2011-03-02 19:23:13 -08001585 if (MotionEvent::isTouchEvent(motionEntry->source, motionEntry->action)) {
Joe Onorato1a542c72010-11-08 09:48:20 -08001586 eventType = POWER_MANAGER_TOUCH_EVENT;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001587 }
Jeff Brown4d396052010-10-29 21:50:21 -07001588 break;
1589 }
1590 case EventEntry::TYPE_KEY: {
1591 const KeyEntry* keyEntry = static_cast<const KeyEntry*>(eventEntry);
1592 if (keyEntry->flags & AKEY_EVENT_FLAG_CANCELED) {
1593 return;
1594 }
Jeff Brown56194eb2011-03-02 19:23:13 -08001595 eventType = POWER_MANAGER_BUTTON_EVENT;
Jeff Brown4d396052010-10-29 21:50:21 -07001596 break;
1597 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001598 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001599
Jeff Brownb88102f2010-09-08 11:49:43 -07001600 CommandEntry* commandEntry = postCommandLocked(
1601 & InputDispatcher::doPokeUserActivityLockedInterruptible);
Jeff Browne2fe69e2010-10-18 13:21:23 -07001602 commandEntry->eventTime = eventEntry->eventTime;
Jeff Brownb88102f2010-09-08 11:49:43 -07001603 commandEntry->userActivityEventType = eventType;
1604}
1605
Jeff Brown7fbdc842010-06-17 20:52:56 -07001606void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
1607 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget,
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001608 bool resumeWithAppendedMotionSample) {
1609#if DEBUG_DISPATCH_CYCLE
Jeff Brown519e0242010-09-15 15:18:56 -07001610 LOGD("channel '%s' ~ prepareDispatchCycle - flags=%d, "
Jeff Brown01ce2e92010-09-26 22:20:12 -07001611 "xOffset=%f, yOffset=%f, "
Jeff Brown83c09682010-12-23 17:50:18 -08001612 "pointerIds=0x%x, "
Jeff Brown01ce2e92010-09-26 22:20:12 -07001613 "resumeWithAppendedMotionSample=%s",
Jeff Brown519e0242010-09-15 15:18:56 -07001614 connection->getInputChannelName(), inputTarget->flags,
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001615 inputTarget->xOffset, inputTarget->yOffset,
Jeff Brown83c09682010-12-23 17:50:18 -08001616 inputTarget->pointerIds.value,
Jeff Brownb88102f2010-09-08 11:49:43 -07001617 toString(resumeWithAppendedMotionSample));
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001618#endif
1619
Jeff Brown01ce2e92010-09-26 22:20:12 -07001620 // Make sure we are never called for streaming when splitting across multiple windows.
1621 bool isSplit = inputTarget->flags & InputTarget::FLAG_SPLIT;
1622 assert(! (resumeWithAppendedMotionSample && isSplit));
1623
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001624 // Skip this event if the connection status is not normal.
Jeff Brown519e0242010-09-15 15:18:56 -07001625 // We don't want to enqueue additional outbound events if the connection is broken.
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001626 if (connection->status != Connection::STATUS_NORMAL) {
Jeff Brownb6997262010-10-08 22:31:17 -07001627#if DEBUG_DISPATCH_CYCLE
1628 LOGD("channel '%s' ~ Dropping event because the channel status is %s",
Jeff Brownb88102f2010-09-08 11:49:43 -07001629 connection->getInputChannelName(), connection->getStatusLabel());
Jeff Brownb6997262010-10-08 22:31:17 -07001630#endif
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001631 return;
1632 }
1633
Jeff Brown01ce2e92010-09-26 22:20:12 -07001634 // Split a motion event if needed.
1635 if (isSplit) {
1636 assert(eventEntry->type == EventEntry::TYPE_MOTION);
1637
1638 MotionEntry* originalMotionEntry = static_cast<MotionEntry*>(eventEntry);
1639 if (inputTarget->pointerIds.count() != originalMotionEntry->pointerCount) {
1640 MotionEntry* splitMotionEntry = splitMotionEvent(
1641 originalMotionEntry, inputTarget->pointerIds);
Jeff Brown58a2da82011-01-25 16:02:22 -08001642 if (!splitMotionEntry) {
1643 return; // split event was dropped
1644 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001645#if DEBUG_FOCUS
1646 LOGD("channel '%s' ~ Split motion event.",
1647 connection->getInputChannelName());
1648 logOutboundMotionDetailsLocked(" ", splitMotionEntry);
1649#endif
1650 eventEntry = splitMotionEntry;
1651 }
1652 }
1653
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001654 // Resume the dispatch cycle with a freshly appended motion sample.
1655 // First we check that the last dispatch entry in the outbound queue is for the same
1656 // motion event to which we appended the motion sample. If we find such a dispatch
1657 // entry, and if it is currently in progress then we try to stream the new sample.
1658 bool wasEmpty = connection->outboundQueue.isEmpty();
1659
1660 if (! wasEmpty && resumeWithAppendedMotionSample) {
1661 DispatchEntry* motionEventDispatchEntry =
1662 connection->findQueuedDispatchEntryForEvent(eventEntry);
1663 if (motionEventDispatchEntry) {
1664 // If the dispatch entry is not in progress, then we must be busy dispatching an
1665 // earlier event. Not a problem, the motion event is on the outbound queue and will
1666 // be dispatched later.
1667 if (! motionEventDispatchEntry->inProgress) {
1668#if DEBUG_BATCHING
1669 LOGD("channel '%s' ~ Not streaming because the motion event has "
1670 "not yet been dispatched. "
1671 "(Waiting for earlier events to be consumed.)",
1672 connection->getInputChannelName());
1673#endif
1674 return;
1675 }
1676
1677 // If the dispatch entry is in progress but it already has a tail of pending
1678 // motion samples, then it must mean that the shared memory buffer filled up.
1679 // Not a problem, when this dispatch cycle is finished, we will eventually start
1680 // a new dispatch cycle to process the tail and that tail includes the newly
1681 // appended motion sample.
1682 if (motionEventDispatchEntry->tailMotionSample) {
1683#if DEBUG_BATCHING
1684 LOGD("channel '%s' ~ Not streaming because no new samples can "
1685 "be appended to the motion event in this dispatch cycle. "
1686 "(Waiting for next dispatch cycle to start.)",
1687 connection->getInputChannelName());
1688#endif
1689 return;
1690 }
1691
1692 // The dispatch entry is in progress and is still potentially open for streaming.
1693 // Try to stream the new motion sample. This might fail if the consumer has already
1694 // consumed the motion event (or if the channel is broken).
Jeff Brown01ce2e92010-09-26 22:20:12 -07001695 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
1696 MotionSample* appendedMotionSample = motionEntry->lastSample;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001697 status_t status = connection->inputPublisher.appendMotionSample(
1698 appendedMotionSample->eventTime, appendedMotionSample->pointerCoords);
1699 if (status == OK) {
1700#if DEBUG_BATCHING
1701 LOGD("channel '%s' ~ Successfully streamed new motion sample.",
1702 connection->getInputChannelName());
1703#endif
1704 return;
1705 }
1706
1707#if DEBUG_BATCHING
1708 if (status == NO_MEMORY) {
1709 LOGD("channel '%s' ~ Could not append motion sample to currently "
1710 "dispatched move event because the shared memory buffer is full. "
1711 "(Waiting for next dispatch cycle to start.)",
1712 connection->getInputChannelName());
1713 } else if (status == status_t(FAILED_TRANSACTION)) {
1714 LOGD("channel '%s' ~ Could not append motion sample to currently "
Jeff Brown349703e2010-06-22 01:27:15 -07001715 "dispatched move event because the event has already been consumed. "
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001716 "(Waiting for next dispatch cycle to start.)",
1717 connection->getInputChannelName());
1718 } else {
1719 LOGD("channel '%s' ~ Could not append motion sample to currently "
1720 "dispatched move event due to an error, status=%d. "
1721 "(Waiting for next dispatch cycle to start.)",
1722 connection->getInputChannelName(), status);
1723 }
1724#endif
1725 // Failed to stream. Start a new tail of pending motion samples to dispatch
1726 // in the next cycle.
1727 motionEventDispatchEntry->tailMotionSample = appendedMotionSample;
1728 return;
1729 }
1730 }
1731
1732 // This is a new event.
1733 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Jeff Brownb88102f2010-09-08 11:49:43 -07001734 DispatchEntry* dispatchEntry = mAllocator.obtainDispatchEntry(eventEntry, // increments ref
Jeff Brown519e0242010-09-15 15:18:56 -07001735 inputTarget->flags, inputTarget->xOffset, inputTarget->yOffset);
1736 if (dispatchEntry->hasForegroundTarget()) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001737 incrementPendingForegroundDispatchesLocked(eventEntry);
Jeff Brown6ec402b2010-07-28 15:48:59 -07001738 }
1739
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001740 // Handle the case where we could not stream a new motion sample because the consumer has
1741 // already consumed the motion event (otherwise the corresponding dispatch entry would
1742 // still be in the outbound queue for this connection). We set the head motion sample
1743 // to the list starting with the newly appended motion sample.
1744 if (resumeWithAppendedMotionSample) {
1745#if DEBUG_BATCHING
1746 LOGD("channel '%s' ~ Preparing a new dispatch cycle for additional motion samples "
1747 "that cannot be streamed because the motion event has already been consumed.",
1748 connection->getInputChannelName());
1749#endif
1750 MotionSample* appendedMotionSample = static_cast<MotionEntry*>(eventEntry)->lastSample;
1751 dispatchEntry->headMotionSample = appendedMotionSample;
1752 }
1753
1754 // Enqueue the dispatch entry.
1755 connection->outboundQueue.enqueueAtTail(dispatchEntry);
1756
1757 // If the outbound queue was previously empty, start the dispatch cycle going.
1758 if (wasEmpty) {
Jeff Brown7fbdc842010-06-17 20:52:56 -07001759 activateConnectionLocked(connection.get());
Jeff Brown519e0242010-09-15 15:18:56 -07001760 startDispatchCycleLocked(currentTime, connection);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001761 }
1762}
1763
Jeff Brown7fbdc842010-06-17 20:52:56 -07001764void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Jeff Brown519e0242010-09-15 15:18:56 -07001765 const sp<Connection>& connection) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001766#if DEBUG_DISPATCH_CYCLE
1767 LOGD("channel '%s' ~ startDispatchCycle",
1768 connection->getInputChannelName());
1769#endif
1770
1771 assert(connection->status == Connection::STATUS_NORMAL);
1772 assert(! connection->outboundQueue.isEmpty());
1773
Jeff Brownb88102f2010-09-08 11:49:43 -07001774 DispatchEntry* dispatchEntry = connection->outboundQueue.headSentinel.next;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001775 assert(! dispatchEntry->inProgress);
1776
Jeff Brownb88102f2010-09-08 11:49:43 -07001777 // Mark the dispatch entry as in progress.
1778 dispatchEntry->inProgress = true;
1779
1780 // Update the connection's input state.
Jeff Brown01ce2e92010-09-26 22:20:12 -07001781 EventEntry* eventEntry = dispatchEntry->eventEntry;
Jeff Browncc0c1592011-02-19 05:07:28 -08001782 connection->inputState.trackEvent(eventEntry);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001783
1784 // Publish the event.
1785 status_t status;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001786 switch (eventEntry->type) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001787 case EventEntry::TYPE_KEY: {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001788 KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001789
1790 // Apply target flags.
1791 int32_t action = keyEntry->action;
1792 int32_t flags = keyEntry->flags;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001793
1794 // Publish the key event.
Jeff Brownc5ed5912010-07-14 18:48:53 -07001795 status = connection->inputPublisher.publishKeyEvent(keyEntry->deviceId, keyEntry->source,
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001796 action, flags, keyEntry->keyCode, keyEntry->scanCode,
1797 keyEntry->metaState, keyEntry->repeatCount, keyEntry->downTime,
1798 keyEntry->eventTime);
1799
1800 if (status) {
1801 LOGE("channel '%s' ~ Could not publish key event, "
1802 "status=%d", connection->getInputChannelName(), status);
Jeff Brownb6997262010-10-08 22:31:17 -07001803 abortBrokenDispatchCycleLocked(currentTime, connection);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001804 return;
1805 }
1806 break;
1807 }
1808
1809 case EventEntry::TYPE_MOTION: {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001810 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001811
1812 // Apply target flags.
1813 int32_t action = motionEntry->action;
Jeff Brown85a31762010-09-01 17:01:00 -07001814 int32_t flags = motionEntry->flags;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001815 if (dispatchEntry->targetFlags & InputTarget::FLAG_OUTSIDE) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001816 action = AMOTION_EVENT_ACTION_OUTSIDE;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001817 }
Jeff Brown85a31762010-09-01 17:01:00 -07001818 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
1819 flags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
1820 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001821
1822 // If headMotionSample is non-NULL, then it points to the first new sample that we
1823 // were unable to dispatch during the previous cycle so we resume dispatching from
1824 // that point in the list of motion samples.
1825 // Otherwise, we just start from the first sample of the motion event.
1826 MotionSample* firstMotionSample = dispatchEntry->headMotionSample;
1827 if (! firstMotionSample) {
1828 firstMotionSample = & motionEntry->firstSample;
1829 }
1830
Jeff Brownd3616592010-07-16 17:21:06 -07001831 // Set the X and Y offset depending on the input source.
1832 float xOffset, yOffset;
1833 if (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) {
1834 xOffset = dispatchEntry->xOffset;
1835 yOffset = dispatchEntry->yOffset;
1836 } else {
1837 xOffset = 0.0f;
1838 yOffset = 0.0f;
1839 }
1840
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001841 // Publish the motion event and the first motion sample.
1842 status = connection->inputPublisher.publishMotionEvent(motionEntry->deviceId,
Jeff Brown85a31762010-09-01 17:01:00 -07001843 motionEntry->source, action, flags, motionEntry->edgeFlags, motionEntry->metaState,
Jeff Brownd3616592010-07-16 17:21:06 -07001844 xOffset, yOffset,
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001845 motionEntry->xPrecision, motionEntry->yPrecision,
1846 motionEntry->downTime, firstMotionSample->eventTime,
1847 motionEntry->pointerCount, motionEntry->pointerIds,
1848 firstMotionSample->pointerCoords);
1849
1850 if (status) {
1851 LOGE("channel '%s' ~ Could not publish motion event, "
1852 "status=%d", connection->getInputChannelName(), status);
Jeff Brownb6997262010-10-08 22:31:17 -07001853 abortBrokenDispatchCycleLocked(currentTime, connection);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001854 return;
1855 }
1856
1857 // Append additional motion samples.
1858 MotionSample* nextMotionSample = firstMotionSample->next;
1859 for (; nextMotionSample != NULL; nextMotionSample = nextMotionSample->next) {
1860 status = connection->inputPublisher.appendMotionSample(
1861 nextMotionSample->eventTime, nextMotionSample->pointerCoords);
1862 if (status == NO_MEMORY) {
1863#if DEBUG_DISPATCH_CYCLE
1864 LOGD("channel '%s' ~ Shared memory buffer full. Some motion samples will "
1865 "be sent in the next dispatch cycle.",
1866 connection->getInputChannelName());
1867#endif
1868 break;
1869 }
1870 if (status != OK) {
1871 LOGE("channel '%s' ~ Could not append motion sample "
1872 "for a reason other than out of memory, status=%d",
1873 connection->getInputChannelName(), status);
Jeff Brownb6997262010-10-08 22:31:17 -07001874 abortBrokenDispatchCycleLocked(currentTime, connection);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001875 return;
1876 }
1877 }
1878
1879 // Remember the next motion sample that we could not dispatch, in case we ran out
1880 // of space in the shared memory buffer.
1881 dispatchEntry->tailMotionSample = nextMotionSample;
1882 break;
1883 }
1884
1885 default: {
1886 assert(false);
1887 }
1888 }
1889
1890 // Send the dispatch signal.
1891 status = connection->inputPublisher.sendDispatchSignal();
1892 if (status) {
1893 LOGE("channel '%s' ~ Could not send dispatch signal, status=%d",
1894 connection->getInputChannelName(), status);
Jeff Brownb6997262010-10-08 22:31:17 -07001895 abortBrokenDispatchCycleLocked(currentTime, connection);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001896 return;
1897 }
1898
1899 // Record information about the newly started dispatch cycle.
Jeff Brown01ce2e92010-09-26 22:20:12 -07001900 connection->lastEventTime = eventEntry->eventTime;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001901 connection->lastDispatchTime = currentTime;
1902
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001903 // Notify other system components.
1904 onDispatchCycleStartedLocked(currentTime, connection);
1905}
1906
Jeff Brown7fbdc842010-06-17 20:52:56 -07001907void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Jeff Brown3915bb82010-11-05 15:02:16 -07001908 const sp<Connection>& connection, bool handled) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001909#if DEBUG_DISPATCH_CYCLE
Jeff Brown9c3cda02010-06-15 01:31:58 -07001910 LOGD("channel '%s' ~ finishDispatchCycle - %01.1fms since event, "
Jeff Brown3915bb82010-11-05 15:02:16 -07001911 "%01.1fms since dispatch, handled=%s",
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001912 connection->getInputChannelName(),
1913 connection->getEventLatencyMillis(currentTime),
Jeff Brown3915bb82010-11-05 15:02:16 -07001914 connection->getDispatchLatencyMillis(currentTime),
1915 toString(handled));
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001916#endif
1917
Jeff Brown9c3cda02010-06-15 01:31:58 -07001918 if (connection->status == Connection::STATUS_BROKEN
1919 || connection->status == Connection::STATUS_ZOMBIE) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001920 return;
1921 }
1922
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001923 // Reset the publisher since the event has been consumed.
1924 // We do this now so that the publisher can release some of its internal resources
1925 // while waiting for the next dispatch cycle to begin.
1926 status_t status = connection->inputPublisher.reset();
1927 if (status) {
1928 LOGE("channel '%s' ~ Could not reset publisher, status=%d",
1929 connection->getInputChannelName(), status);
Jeff Brownb6997262010-10-08 22:31:17 -07001930 abortBrokenDispatchCycleLocked(currentTime, connection);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001931 return;
1932 }
1933
Jeff Brown3915bb82010-11-05 15:02:16 -07001934 // Notify other system components and prepare to start the next dispatch cycle.
1935 onDispatchCycleFinishedLocked(currentTime, connection, handled);
Jeff Brownb88102f2010-09-08 11:49:43 -07001936}
1937
1938void InputDispatcher::startNextDispatchCycleLocked(nsecs_t currentTime,
1939 const sp<Connection>& connection) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001940 // Start the next dispatch cycle for this connection.
1941 while (! connection->outboundQueue.isEmpty()) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001942 DispatchEntry* dispatchEntry = connection->outboundQueue.headSentinel.next;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001943 if (dispatchEntry->inProgress) {
1944 // Finish or resume current event in progress.
1945 if (dispatchEntry->tailMotionSample) {
1946 // We have a tail of undispatched motion samples.
1947 // Reuse the same DispatchEntry and start a new cycle.
1948 dispatchEntry->inProgress = false;
1949 dispatchEntry->headMotionSample = dispatchEntry->tailMotionSample;
1950 dispatchEntry->tailMotionSample = NULL;
Jeff Brown519e0242010-09-15 15:18:56 -07001951 startDispatchCycleLocked(currentTime, connection);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001952 return;
1953 }
1954 // Finished.
1955 connection->outboundQueue.dequeueAtHead();
Jeff Brown519e0242010-09-15 15:18:56 -07001956 if (dispatchEntry->hasForegroundTarget()) {
1957 decrementPendingForegroundDispatchesLocked(dispatchEntry->eventEntry);
Jeff Brown6ec402b2010-07-28 15:48:59 -07001958 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001959 mAllocator.releaseDispatchEntry(dispatchEntry);
1960 } else {
1961 // If the head is not in progress, then we must have already dequeued the in
Jeff Brown519e0242010-09-15 15:18:56 -07001962 // progress event, which means we actually aborted it.
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001963 // So just start the next event for this connection.
Jeff Brown519e0242010-09-15 15:18:56 -07001964 startDispatchCycleLocked(currentTime, connection);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001965 return;
1966 }
1967 }
1968
1969 // Outbound queue is empty, deactivate the connection.
Jeff Brown7fbdc842010-06-17 20:52:56 -07001970 deactivateConnectionLocked(connection.get());
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001971}
1972
Jeff Brownb6997262010-10-08 22:31:17 -07001973void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
1974 const sp<Connection>& connection) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001975#if DEBUG_DISPATCH_CYCLE
Jeff Brown83c09682010-12-23 17:50:18 -08001976 LOGD("channel '%s' ~ abortBrokenDispatchCycle",
1977 connection->getInputChannelName());
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001978#endif
1979
Jeff Brownb88102f2010-09-08 11:49:43 -07001980 // Clear the outbound queue.
Jeff Brown519e0242010-09-15 15:18:56 -07001981 drainOutboundQueueLocked(connection.get());
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001982
Jeff Brownb6997262010-10-08 22:31:17 -07001983 // The connection appears to be unrecoverably broken.
Jeff Brown9c3cda02010-06-15 01:31:58 -07001984 // Ignore already broken or zombie connections.
Jeff Brownb6997262010-10-08 22:31:17 -07001985 if (connection->status == Connection::STATUS_NORMAL) {
1986 connection->status = Connection::STATUS_BROKEN;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001987
Jeff Brownb6997262010-10-08 22:31:17 -07001988 // Notify other system components.
1989 onDispatchCycleBrokenLocked(currentTime, connection);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001990 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001991}
1992
Jeff Brown519e0242010-09-15 15:18:56 -07001993void InputDispatcher::drainOutboundQueueLocked(Connection* connection) {
1994 while (! connection->outboundQueue.isEmpty()) {
1995 DispatchEntry* dispatchEntry = connection->outboundQueue.dequeueAtHead();
1996 if (dispatchEntry->hasForegroundTarget()) {
1997 decrementPendingForegroundDispatchesLocked(dispatchEntry->eventEntry);
Jeff Brownb88102f2010-09-08 11:49:43 -07001998 }
1999 mAllocator.releaseDispatchEntry(dispatchEntry);
Jeff Brownb88102f2010-09-08 11:49:43 -07002000 }
2001
Jeff Brown519e0242010-09-15 15:18:56 -07002002 deactivateConnectionLocked(connection);
Jeff Brownb88102f2010-09-08 11:49:43 -07002003}
2004
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002005int InputDispatcher::handleReceiveCallback(int receiveFd, int events, void* data) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002006 InputDispatcher* d = static_cast<InputDispatcher*>(data);
2007
2008 { // acquire lock
2009 AutoMutex _l(d->mLock);
2010
2011 ssize_t connectionIndex = d->mConnectionsByReceiveFd.indexOfKey(receiveFd);
2012 if (connectionIndex < 0) {
2013 LOGE("Received spurious receive callback for unknown input channel. "
2014 "fd=%d, events=0x%x", receiveFd, events);
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002015 return 0; // remove the callback
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002016 }
2017
Jeff Brown7fbdc842010-06-17 20:52:56 -07002018 nsecs_t currentTime = now();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002019
2020 sp<Connection> connection = d->mConnectionsByReceiveFd.valueAt(connectionIndex);
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002021 if (events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP)) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002022 LOGE("channel '%s' ~ Consumer closed input channel or an error occurred. "
2023 "events=0x%x", connection->getInputChannelName(), events);
Jeff Brownb6997262010-10-08 22:31:17 -07002024 d->abortBrokenDispatchCycleLocked(currentTime, connection);
Jeff Brown9c3cda02010-06-15 01:31:58 -07002025 d->runCommandsLockedInterruptible();
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002026 return 0; // remove the callback
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002027 }
2028
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002029 if (! (events & ALOOPER_EVENT_INPUT)) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002030 LOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
2031 "events=0x%x", connection->getInputChannelName(), events);
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002032 return 1;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002033 }
2034
Jeff Brown3915bb82010-11-05 15:02:16 -07002035 bool handled = false;
Jeff Brown49ed71d2010-12-06 17:13:33 -08002036 status_t status = connection->inputPublisher.receiveFinishedSignal(&handled);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002037 if (status) {
2038 LOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
2039 connection->getInputChannelName(), status);
Jeff Brownb6997262010-10-08 22:31:17 -07002040 d->abortBrokenDispatchCycleLocked(currentTime, connection);
Jeff Brown9c3cda02010-06-15 01:31:58 -07002041 d->runCommandsLockedInterruptible();
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002042 return 0; // remove the callback
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002043 }
2044
Jeff Brown3915bb82010-11-05 15:02:16 -07002045 d->finishDispatchCycleLocked(currentTime, connection, handled);
Jeff Brown9c3cda02010-06-15 01:31:58 -07002046 d->runCommandsLockedInterruptible();
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002047 return 1;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002048 } // release lock
2049}
2050
Jeff Brownb6997262010-10-08 22:31:17 -07002051void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
2052 InputState::CancelationOptions options, const char* reason) {
2053 for (size_t i = 0; i < mConnectionsByReceiveFd.size(); i++) {
2054 synthesizeCancelationEventsForConnectionLocked(
2055 mConnectionsByReceiveFd.valueAt(i), options, reason);
2056 }
2057}
2058
2059void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
2060 const sp<InputChannel>& channel, InputState::CancelationOptions options,
2061 const char* reason) {
2062 ssize_t index = getConnectionIndexLocked(channel);
2063 if (index >= 0) {
2064 synthesizeCancelationEventsForConnectionLocked(
2065 mConnectionsByReceiveFd.valueAt(index), options, reason);
2066 }
2067}
2068
2069void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
2070 const sp<Connection>& connection, InputState::CancelationOptions options,
2071 const char* reason) {
2072 nsecs_t currentTime = now();
2073
2074 mTempCancelationEvents.clear();
2075 connection->inputState.synthesizeCancelationEvents(currentTime, & mAllocator,
2076 mTempCancelationEvents, options);
2077
2078 if (! mTempCancelationEvents.isEmpty()
2079 && connection->status != Connection::STATUS_BROKEN) {
2080#if DEBUG_OUTBOUND_EVENT_DETAILS
2081 LOGD("channel '%s' ~ Synthesized %d cancelation events to bring channel back in sync "
2082 "with reality: %s, options=%d.",
2083 connection->getInputChannelName(), mTempCancelationEvents.size(), reason, options);
2084#endif
2085 for (size_t i = 0; i < mTempCancelationEvents.size(); i++) {
2086 EventEntry* cancelationEventEntry = mTempCancelationEvents.itemAt(i);
2087 switch (cancelationEventEntry->type) {
2088 case EventEntry::TYPE_KEY:
2089 logOutboundKeyDetailsLocked("cancel - ",
2090 static_cast<KeyEntry*>(cancelationEventEntry));
2091 break;
2092 case EventEntry::TYPE_MOTION:
2093 logOutboundMotionDetailsLocked("cancel - ",
2094 static_cast<MotionEntry*>(cancelationEventEntry));
2095 break;
2096 }
2097
2098 int32_t xOffset, yOffset;
2099 const InputWindow* window = getWindowLocked(connection->inputChannel);
2100 if (window) {
2101 xOffset = -window->frameLeft;
2102 yOffset = -window->frameTop;
2103 } else {
2104 xOffset = 0;
2105 yOffset = 0;
2106 }
2107
2108 DispatchEntry* cancelationDispatchEntry =
2109 mAllocator.obtainDispatchEntry(cancelationEventEntry, // increments ref
2110 0, xOffset, yOffset);
2111 connection->outboundQueue.enqueueAtTail(cancelationDispatchEntry);
2112
2113 mAllocator.releaseEventEntry(cancelationEventEntry);
2114 }
2115
2116 if (!connection->outboundQueue.headSentinel.next->inProgress) {
2117 startDispatchCycleLocked(currentTime, connection);
2118 }
2119 }
2120}
2121
Jeff Brown01ce2e92010-09-26 22:20:12 -07002122InputDispatcher::MotionEntry*
2123InputDispatcher::splitMotionEvent(const MotionEntry* originalMotionEntry, BitSet32 pointerIds) {
2124 assert(pointerIds.value != 0);
2125
2126 uint32_t splitPointerIndexMap[MAX_POINTERS];
2127 int32_t splitPointerIds[MAX_POINTERS];
2128 PointerCoords splitPointerCoords[MAX_POINTERS];
2129
2130 uint32_t originalPointerCount = originalMotionEntry->pointerCount;
2131 uint32_t splitPointerCount = 0;
2132
2133 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
2134 originalPointerIndex++) {
2135 int32_t pointerId = uint32_t(originalMotionEntry->pointerIds[originalPointerIndex]);
2136 if (pointerIds.hasBit(pointerId)) {
2137 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
2138 splitPointerIds[splitPointerCount] = pointerId;
2139 splitPointerCoords[splitPointerCount] =
2140 originalMotionEntry->firstSample.pointerCoords[originalPointerIndex];
2141 splitPointerCount += 1;
2142 }
2143 }
Jeff Brown58a2da82011-01-25 16:02:22 -08002144
2145 if (splitPointerCount != pointerIds.count()) {
2146 // This is bad. We are missing some of the pointers that we expected to deliver.
2147 // Most likely this indicates that we received an ACTION_MOVE events that has
2148 // different pointer ids than we expected based on the previous ACTION_DOWN
2149 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
2150 // in this way.
2151 LOGW("Dropping split motion event because the pointer count is %d but "
2152 "we expected there to be %d pointers. This probably means we received "
2153 "a broken sequence of pointer ids from the input device.",
2154 splitPointerCount, pointerIds.count());
2155 return NULL;
2156 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07002157
2158 int32_t action = originalMotionEntry->action;
2159 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
2160 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
2161 || maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2162 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
2163 int32_t pointerId = originalMotionEntry->pointerIds[originalPointerIndex];
2164 if (pointerIds.hasBit(pointerId)) {
2165 if (pointerIds.count() == 1) {
2166 // The first/last pointer went down/up.
2167 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
2168 ? AMOTION_EVENT_ACTION_DOWN : AMOTION_EVENT_ACTION_UP;
Jeff Brown9a01d052010-09-27 16:35:11 -07002169 } else {
2170 // A secondary pointer went down/up.
2171 uint32_t splitPointerIndex = 0;
2172 while (pointerId != splitPointerIds[splitPointerIndex]) {
2173 splitPointerIndex += 1;
2174 }
2175 action = maskedAction | (splitPointerIndex
2176 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002177 }
2178 } else {
2179 // An unrelated pointer changed.
2180 action = AMOTION_EVENT_ACTION_MOVE;
2181 }
2182 }
2183
2184 MotionEntry* splitMotionEntry = mAllocator.obtainMotionEntry(
2185 originalMotionEntry->eventTime,
2186 originalMotionEntry->deviceId,
2187 originalMotionEntry->source,
2188 originalMotionEntry->policyFlags,
2189 action,
2190 originalMotionEntry->flags,
2191 originalMotionEntry->metaState,
2192 originalMotionEntry->edgeFlags,
2193 originalMotionEntry->xPrecision,
2194 originalMotionEntry->yPrecision,
2195 originalMotionEntry->downTime,
2196 splitPointerCount, splitPointerIds, splitPointerCoords);
2197
2198 for (MotionSample* originalMotionSample = originalMotionEntry->firstSample.next;
2199 originalMotionSample != NULL; originalMotionSample = originalMotionSample->next) {
2200 for (uint32_t splitPointerIndex = 0; splitPointerIndex < splitPointerCount;
2201 splitPointerIndex++) {
2202 uint32_t originalPointerIndex = splitPointerIndexMap[splitPointerIndex];
2203 splitPointerCoords[splitPointerIndex] =
2204 originalMotionSample->pointerCoords[originalPointerIndex];
2205 }
2206
2207 mAllocator.appendMotionSample(splitMotionEntry, originalMotionSample->eventTime,
2208 splitPointerCoords);
2209 }
2210
2211 return splitMotionEntry;
2212}
2213
Jeff Brown9c3cda02010-06-15 01:31:58 -07002214void InputDispatcher::notifyConfigurationChanged(nsecs_t eventTime) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002215#if DEBUG_INBOUND_EVENT_DETAILS
Jeff Brown9c3cda02010-06-15 01:31:58 -07002216 LOGD("notifyConfigurationChanged - eventTime=%lld", eventTime);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002217#endif
2218
Jeff Brownb88102f2010-09-08 11:49:43 -07002219 bool needWake;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002220 { // acquire lock
2221 AutoMutex _l(mLock);
2222
Jeff Brown7fbdc842010-06-17 20:52:56 -07002223 ConfigurationChangedEntry* newEntry = mAllocator.obtainConfigurationChangedEntry(eventTime);
Jeff Brownb88102f2010-09-08 11:49:43 -07002224 needWake = enqueueInboundEventLocked(newEntry);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002225 } // release lock
2226
Jeff Brownb88102f2010-09-08 11:49:43 -07002227 if (needWake) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002228 mLooper->wake();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002229 }
2230}
2231
Jeff Brown58a2da82011-01-25 16:02:22 -08002232void InputDispatcher::notifyKey(nsecs_t eventTime, int32_t deviceId, uint32_t source,
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002233 uint32_t policyFlags, int32_t action, int32_t flags,
2234 int32_t keyCode, int32_t scanCode, int32_t metaState, nsecs_t downTime) {
2235#if DEBUG_INBOUND_EVENT_DETAILS
Jeff Brown90655042010-12-02 13:50:46 -08002236 LOGD("notifyKey - eventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, action=0x%x, "
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002237 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%lld",
Jeff Brownc5ed5912010-07-14 18:48:53 -07002238 eventTime, deviceId, source, policyFlags, action, flags,
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002239 keyCode, scanCode, metaState, downTime);
2240#endif
Jeff Brown01ce2e92010-09-26 22:20:12 -07002241 if (! validateKeyEvent(action)) {
2242 return;
2243 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002244
Jeff Brown1f245102010-11-18 20:53:46 -08002245 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
2246 policyFlags |= POLICY_FLAG_VIRTUAL;
2247 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
2248 }
2249
Jeff Browne20c9e02010-10-11 14:20:19 -07002250 policyFlags |= POLICY_FLAG_TRUSTED;
Jeff Brown1f245102010-11-18 20:53:46 -08002251
2252 KeyEvent event;
2253 event.initialize(deviceId, source, action, flags, keyCode, scanCode,
2254 metaState, 0, downTime, eventTime);
2255
2256 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
2257
2258 if (policyFlags & POLICY_FLAG_WOKE_HERE) {
2259 flags |= AKEY_EVENT_FLAG_WOKE_HERE;
2260 }
Jeff Brownb6997262010-10-08 22:31:17 -07002261
Jeff Brownb88102f2010-09-08 11:49:43 -07002262 bool needWake;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002263 { // acquire lock
2264 AutoMutex _l(mLock);
2265
Jeff Brown7fbdc842010-06-17 20:52:56 -07002266 int32_t repeatCount = 0;
2267 KeyEntry* newEntry = mAllocator.obtainKeyEntry(eventTime,
Jeff Brownc5ed5912010-07-14 18:48:53 -07002268 deviceId, source, policyFlags, action, flags, keyCode, scanCode,
Jeff Brown7fbdc842010-06-17 20:52:56 -07002269 metaState, repeatCount, downTime);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002270
Jeff Brownb88102f2010-09-08 11:49:43 -07002271 needWake = enqueueInboundEventLocked(newEntry);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002272 } // release lock
2273
Jeff Brownb88102f2010-09-08 11:49:43 -07002274 if (needWake) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002275 mLooper->wake();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002276 }
2277}
2278
Jeff Brown58a2da82011-01-25 16:02:22 -08002279void InputDispatcher::notifyMotion(nsecs_t eventTime, int32_t deviceId, uint32_t source,
Jeff Brown85a31762010-09-01 17:01:00 -07002280 uint32_t policyFlags, int32_t action, int32_t flags, int32_t metaState, int32_t edgeFlags,
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002281 uint32_t pointerCount, const int32_t* pointerIds, const PointerCoords* pointerCoords,
2282 float xPrecision, float yPrecision, nsecs_t downTime) {
2283#if DEBUG_INBOUND_EVENT_DETAILS
Jeff Brown90655042010-12-02 13:50:46 -08002284 LOGD("notifyMotion - eventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, "
Jeff Brown85a31762010-09-01 17:01:00 -07002285 "action=0x%x, flags=0x%x, metaState=0x%x, edgeFlags=0x%x, "
2286 "xPrecision=%f, yPrecision=%f, downTime=%lld",
2287 eventTime, deviceId, source, policyFlags, action, flags, metaState, edgeFlags,
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002288 xPrecision, yPrecision, downTime);
2289 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brown8d608662010-08-30 03:02:23 -07002290 LOGD(" Pointer %d: id=%d, x=%f, y=%f, pressure=%f, size=%f, "
Jeff Brown85a31762010-09-01 17:01:00 -07002291 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
Jeff Brown8d608662010-08-30 03:02:23 -07002292 "orientation=%f",
Jeff Brown91c69ab2011-02-14 17:03:18 -08002293 i, pointerIds[i],
Jeff Brownebbd5d12011-02-17 13:01:34 -08002294 pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
2295 pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
2296 pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
2297 pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
2298 pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
2299 pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
2300 pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
2301 pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
2302 pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002303 }
2304#endif
Jeff Brown01ce2e92010-09-26 22:20:12 -07002305 if (! validateMotionEvent(action, pointerCount, pointerIds)) {
2306 return;
2307 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002308
Jeff Browne20c9e02010-10-11 14:20:19 -07002309 policyFlags |= POLICY_FLAG_TRUSTED;
Jeff Brown56194eb2011-03-02 19:23:13 -08002310 mPolicy->interceptMotionBeforeQueueing(eventTime, /*byref*/ policyFlags);
Jeff Brownb6997262010-10-08 22:31:17 -07002311
Jeff Brownb88102f2010-09-08 11:49:43 -07002312 bool needWake;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002313 { // acquire lock
2314 AutoMutex _l(mLock);
2315
2316 // Attempt batching and streaming of move events.
Jeff Browncc0c1592011-02-19 05:07:28 -08002317 if (action == AMOTION_EVENT_ACTION_MOVE
2318 || action == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002319 // BATCHING CASE
2320 //
2321 // Try to append a move sample to the tail of the inbound queue for this device.
2322 // Give up if we encounter a non-move motion event for this device since that
2323 // means we cannot append any new samples until a new motion event has started.
Jeff Brownb88102f2010-09-08 11:49:43 -07002324 for (EventEntry* entry = mInboundQueue.tailSentinel.prev;
2325 entry != & mInboundQueue.headSentinel; entry = entry->prev) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002326 if (entry->type != EventEntry::TYPE_MOTION) {
2327 // Keep looking for motion events.
2328 continue;
2329 }
2330
2331 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
2332 if (motionEntry->deviceId != deviceId) {
2333 // Keep looking for this device.
2334 continue;
2335 }
2336
Jeff Browncc0c1592011-02-19 05:07:28 -08002337 if (motionEntry->action != action
Jeff Brown58a2da82011-01-25 16:02:22 -08002338 || motionEntry->source != source
Jeff Brown7fbdc842010-06-17 20:52:56 -07002339 || motionEntry->pointerCount != pointerCount
2340 || motionEntry->isInjected()) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002341 // Last motion event in the queue for this device is not compatible for
2342 // appending new samples. Stop here.
2343 goto NoBatchingOrStreaming;
2344 }
2345
2346 // The last motion event is a move and is compatible for appending.
Jeff Brown9c3cda02010-06-15 01:31:58 -07002347 // Do the batching magic.
Jeff Brown7fbdc842010-06-17 20:52:56 -07002348 mAllocator.appendMotionSample(motionEntry, eventTime, pointerCoords);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002349#if DEBUG_BATCHING
2350 LOGD("Appended motion sample onto batch for most recent "
2351 "motion event for this device in the inbound queue.");
2352#endif
Jeff Brown9c3cda02010-06-15 01:31:58 -07002353 return; // done!
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002354 }
2355
2356 // STREAMING CASE
2357 //
2358 // There is no pending motion event (of any kind) for this device in the inbound queue.
Jeff Brown519e0242010-09-15 15:18:56 -07002359 // Search the outbound queue for the current foreground targets to find a dispatched
2360 // motion event that is still in progress. If found, then, appen the new sample to
2361 // that event and push it out to all current targets. The logic in
2362 // prepareDispatchCycleLocked takes care of the case where some targets may
2363 // already have consumed the motion event by starting a new dispatch cycle if needed.
Jeff Brown9c3cda02010-06-15 01:31:58 -07002364 if (mCurrentInputTargetsValid) {
Jeff Brown519e0242010-09-15 15:18:56 -07002365 for (size_t i = 0; i < mCurrentInputTargets.size(); i++) {
2366 const InputTarget& inputTarget = mCurrentInputTargets[i];
2367 if ((inputTarget.flags & InputTarget::FLAG_FOREGROUND) == 0) {
2368 // Skip non-foreground targets. We only want to stream if there is at
2369 // least one foreground target whose dispatch is still in progress.
2370 continue;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002371 }
Jeff Brown519e0242010-09-15 15:18:56 -07002372
2373 ssize_t connectionIndex = getConnectionIndexLocked(inputTarget.inputChannel);
2374 if (connectionIndex < 0) {
2375 // Connection must no longer be valid.
2376 continue;
2377 }
2378
2379 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
2380 if (connection->outboundQueue.isEmpty()) {
2381 // This foreground target has an empty outbound queue.
2382 continue;
2383 }
2384
2385 DispatchEntry* dispatchEntry = connection->outboundQueue.headSentinel.next;
2386 if (! dispatchEntry->inProgress
Jeff Brown01ce2e92010-09-26 22:20:12 -07002387 || dispatchEntry->eventEntry->type != EventEntry::TYPE_MOTION
2388 || dispatchEntry->isSplit()) {
2389 // No motion event is being dispatched, or it is being split across
2390 // windows in which case we cannot stream.
Jeff Brown519e0242010-09-15 15:18:56 -07002391 continue;
2392 }
2393
2394 MotionEntry* motionEntry = static_cast<MotionEntry*>(
2395 dispatchEntry->eventEntry);
Jeff Browncc0c1592011-02-19 05:07:28 -08002396 if (motionEntry->action != action
Jeff Brown519e0242010-09-15 15:18:56 -07002397 || motionEntry->deviceId != deviceId
Jeff Brown58a2da82011-01-25 16:02:22 -08002398 || motionEntry->source != source
Jeff Brown519e0242010-09-15 15:18:56 -07002399 || motionEntry->pointerCount != pointerCount
2400 || motionEntry->isInjected()) {
2401 // The motion event is not compatible with this move.
2402 continue;
2403 }
2404
2405 // Hurray! This foreground target is currently dispatching a move event
2406 // that we can stream onto. Append the motion sample and resume dispatch.
2407 mAllocator.appendMotionSample(motionEntry, eventTime, pointerCoords);
2408#if DEBUG_BATCHING
2409 LOGD("Appended motion sample onto batch for most recently dispatched "
2410 "motion event for this device in the outbound queues. "
2411 "Attempting to stream the motion sample.");
2412#endif
2413 nsecs_t currentTime = now();
2414 dispatchEventToCurrentInputTargetsLocked(currentTime, motionEntry,
2415 true /*resumeWithAppendedMotionSample*/);
2416
2417 runCommandsLockedInterruptible();
2418 return; // done!
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002419 }
2420 }
2421
2422NoBatchingOrStreaming:;
2423 }
2424
2425 // Just enqueue a new motion event.
Jeff Brown7fbdc842010-06-17 20:52:56 -07002426 MotionEntry* newEntry = mAllocator.obtainMotionEntry(eventTime,
Jeff Brown85a31762010-09-01 17:01:00 -07002427 deviceId, source, policyFlags, action, flags, metaState, edgeFlags,
Jeff Brown7fbdc842010-06-17 20:52:56 -07002428 xPrecision, yPrecision, downTime,
2429 pointerCount, pointerIds, pointerCoords);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002430
Jeff Brownb88102f2010-09-08 11:49:43 -07002431 needWake = enqueueInboundEventLocked(newEntry);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002432 } // release lock
2433
Jeff Brownb88102f2010-09-08 11:49:43 -07002434 if (needWake) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002435 mLooper->wake();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002436 }
2437}
2438
Jeff Brownb6997262010-10-08 22:31:17 -07002439void InputDispatcher::notifySwitch(nsecs_t when, int32_t switchCode, int32_t switchValue,
2440 uint32_t policyFlags) {
2441#if DEBUG_INBOUND_EVENT_DETAILS
2442 LOGD("notifySwitch - switchCode=%d, switchValue=%d, policyFlags=0x%x",
2443 switchCode, switchValue, policyFlags);
2444#endif
2445
Jeff Browne20c9e02010-10-11 14:20:19 -07002446 policyFlags |= POLICY_FLAG_TRUSTED;
Jeff Brownb6997262010-10-08 22:31:17 -07002447 mPolicy->notifySwitch(when, switchCode, switchValue, policyFlags);
2448}
2449
Jeff Brown7fbdc842010-06-17 20:52:56 -07002450int32_t InputDispatcher::injectInputEvent(const InputEvent* event,
Jeff Brown6ec402b2010-07-28 15:48:59 -07002451 int32_t injectorPid, int32_t injectorUid, int32_t syncMode, int32_t timeoutMillis) {
Jeff Brown7fbdc842010-06-17 20:52:56 -07002452#if DEBUG_INBOUND_EVENT_DETAILS
2453 LOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Jeff Brown6ec402b2010-07-28 15:48:59 -07002454 "syncMode=%d, timeoutMillis=%d",
2455 event->getType(), injectorPid, injectorUid, syncMode, timeoutMillis);
Jeff Brown7fbdc842010-06-17 20:52:56 -07002456#endif
2457
2458 nsecs_t endTime = now() + milliseconds_to_nanoseconds(timeoutMillis);
Jeff Browne20c9e02010-10-11 14:20:19 -07002459
2460 uint32_t policyFlags = POLICY_FLAG_INJECTED;
2461 if (hasInjectionPermission(injectorPid, injectorUid)) {
2462 policyFlags |= POLICY_FLAG_TRUSTED;
2463 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07002464
Jeff Brownb6997262010-10-08 22:31:17 -07002465 EventEntry* injectedEntry;
2466 switch (event->getType()) {
2467 case AINPUT_EVENT_TYPE_KEY: {
2468 const KeyEvent* keyEvent = static_cast<const KeyEvent*>(event);
2469 int32_t action = keyEvent->getAction();
2470 if (! validateKeyEvent(action)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07002471 return INPUT_EVENT_INJECTION_FAILED;
2472 }
2473
Jeff Brownb6997262010-10-08 22:31:17 -07002474 int32_t flags = keyEvent->getFlags();
Jeff Brown1f245102010-11-18 20:53:46 -08002475 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
2476 policyFlags |= POLICY_FLAG_VIRTUAL;
2477 }
2478
2479 mPolicy->interceptKeyBeforeQueueing(keyEvent, /*byref*/ policyFlags);
2480
2481 if (policyFlags & POLICY_FLAG_WOKE_HERE) {
2482 flags |= AKEY_EVENT_FLAG_WOKE_HERE;
2483 }
Jeff Brown6ec402b2010-07-28 15:48:59 -07002484
Jeff Brownb6997262010-10-08 22:31:17 -07002485 mLock.lock();
Jeff Brown1f245102010-11-18 20:53:46 -08002486 injectedEntry = mAllocator.obtainKeyEntry(keyEvent->getEventTime(),
2487 keyEvent->getDeviceId(), keyEvent->getSource(),
2488 policyFlags, action, flags,
2489 keyEvent->getKeyCode(), keyEvent->getScanCode(), keyEvent->getMetaState(),
Jeff Brownb6997262010-10-08 22:31:17 -07002490 keyEvent->getRepeatCount(), keyEvent->getDownTime());
2491 break;
2492 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07002493
Jeff Brownb6997262010-10-08 22:31:17 -07002494 case AINPUT_EVENT_TYPE_MOTION: {
2495 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
2496 int32_t action = motionEvent->getAction();
2497 size_t pointerCount = motionEvent->getPointerCount();
2498 const int32_t* pointerIds = motionEvent->getPointerIds();
2499 if (! validateMotionEvent(action, pointerCount, pointerIds)) {
2500 return INPUT_EVENT_INJECTION_FAILED;
2501 }
2502
2503 nsecs_t eventTime = motionEvent->getEventTime();
Jeff Brown56194eb2011-03-02 19:23:13 -08002504 mPolicy->interceptMotionBeforeQueueing(eventTime, /*byref*/ policyFlags);
Jeff Brownb6997262010-10-08 22:31:17 -07002505
2506 mLock.lock();
2507 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
2508 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
2509 MotionEntry* motionEntry = mAllocator.obtainMotionEntry(*sampleEventTimes,
2510 motionEvent->getDeviceId(), motionEvent->getSource(), policyFlags,
2511 action, motionEvent->getFlags(),
2512 motionEvent->getMetaState(), motionEvent->getEdgeFlags(),
2513 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
2514 motionEvent->getDownTime(), uint32_t(pointerCount),
2515 pointerIds, samplePointerCoords);
2516 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
2517 sampleEventTimes += 1;
2518 samplePointerCoords += pointerCount;
2519 mAllocator.appendMotionSample(motionEntry, *sampleEventTimes, samplePointerCoords);
2520 }
2521 injectedEntry = motionEntry;
2522 break;
2523 }
2524
2525 default:
2526 LOGW("Cannot inject event of type %d", event->getType());
2527 return INPUT_EVENT_INJECTION_FAILED;
2528 }
2529
2530 InjectionState* injectionState = mAllocator.obtainInjectionState(injectorPid, injectorUid);
2531 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
2532 injectionState->injectionIsAsync = true;
2533 }
2534
2535 injectionState->refCount += 1;
2536 injectedEntry->injectionState = injectionState;
2537
2538 bool needWake = enqueueInboundEventLocked(injectedEntry);
2539 mLock.unlock();
Jeff Brown7fbdc842010-06-17 20:52:56 -07002540
Jeff Brownb88102f2010-09-08 11:49:43 -07002541 if (needWake) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002542 mLooper->wake();
Jeff Brown7fbdc842010-06-17 20:52:56 -07002543 }
2544
2545 int32_t injectionResult;
2546 { // acquire lock
2547 AutoMutex _l(mLock);
2548
Jeff Brown6ec402b2010-07-28 15:48:59 -07002549 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
2550 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
2551 } else {
2552 for (;;) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002553 injectionResult = injectionState->injectionResult;
Jeff Brown6ec402b2010-07-28 15:48:59 -07002554 if (injectionResult != INPUT_EVENT_INJECTION_PENDING) {
2555 break;
2556 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07002557
Jeff Brown7fbdc842010-06-17 20:52:56 -07002558 nsecs_t remainingTimeout = endTime - now();
2559 if (remainingTimeout <= 0) {
Jeff Brown6ec402b2010-07-28 15:48:59 -07002560#if DEBUG_INJECTION
2561 LOGD("injectInputEvent - Timed out waiting for injection result "
2562 "to become available.");
2563#endif
Jeff Brown7fbdc842010-06-17 20:52:56 -07002564 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
2565 break;
2566 }
2567
Jeff Brown6ec402b2010-07-28 15:48:59 -07002568 mInjectionResultAvailableCondition.waitRelative(mLock, remainingTimeout);
2569 }
2570
2571 if (injectionResult == INPUT_EVENT_INJECTION_SUCCEEDED
2572 && syncMode == INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002573 while (injectionState->pendingForegroundDispatches != 0) {
Jeff Brown6ec402b2010-07-28 15:48:59 -07002574#if DEBUG_INJECTION
Jeff Brown519e0242010-09-15 15:18:56 -07002575 LOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
Jeff Brown01ce2e92010-09-26 22:20:12 -07002576 injectionState->pendingForegroundDispatches);
Jeff Brown6ec402b2010-07-28 15:48:59 -07002577#endif
2578 nsecs_t remainingTimeout = endTime - now();
2579 if (remainingTimeout <= 0) {
2580#if DEBUG_INJECTION
Jeff Brown519e0242010-09-15 15:18:56 -07002581 LOGD("injectInputEvent - Timed out waiting for pending foreground "
Jeff Brown6ec402b2010-07-28 15:48:59 -07002582 "dispatches to finish.");
2583#endif
2584 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
2585 break;
2586 }
2587
2588 mInjectionSyncFinishedCondition.waitRelative(mLock, remainingTimeout);
2589 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07002590 }
2591 }
2592
Jeff Brown01ce2e92010-09-26 22:20:12 -07002593 mAllocator.releaseInjectionState(injectionState);
Jeff Brown7fbdc842010-06-17 20:52:56 -07002594 } // release lock
2595
Jeff Brown6ec402b2010-07-28 15:48:59 -07002596#if DEBUG_INJECTION
2597 LOGD("injectInputEvent - Finished with result %d. "
2598 "injectorPid=%d, injectorUid=%d",
2599 injectionResult, injectorPid, injectorUid);
2600#endif
2601
Jeff Brown7fbdc842010-06-17 20:52:56 -07002602 return injectionResult;
2603}
2604
Jeff Brownb6997262010-10-08 22:31:17 -07002605bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
2606 return injectorUid == 0
2607 || mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
2608}
2609
Jeff Brown7fbdc842010-06-17 20:52:56 -07002610void InputDispatcher::setInjectionResultLocked(EventEntry* entry, int32_t injectionResult) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002611 InjectionState* injectionState = entry->injectionState;
2612 if (injectionState) {
Jeff Brown7fbdc842010-06-17 20:52:56 -07002613#if DEBUG_INJECTION
2614 LOGD("Setting input event injection result to %d. "
2615 "injectorPid=%d, injectorUid=%d",
Jeff Brown01ce2e92010-09-26 22:20:12 -07002616 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
Jeff Brown7fbdc842010-06-17 20:52:56 -07002617#endif
2618
Jeff Brown01ce2e92010-09-26 22:20:12 -07002619 if (injectionState->injectionIsAsync) {
Jeff Brown6ec402b2010-07-28 15:48:59 -07002620 // Log the outcome since the injector did not wait for the injection result.
2621 switch (injectionResult) {
2622 case INPUT_EVENT_INJECTION_SUCCEEDED:
2623 LOGV("Asynchronous input event injection succeeded.");
2624 break;
2625 case INPUT_EVENT_INJECTION_FAILED:
2626 LOGW("Asynchronous input event injection failed.");
2627 break;
2628 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
2629 LOGW("Asynchronous input event injection permission denied.");
2630 break;
2631 case INPUT_EVENT_INJECTION_TIMED_OUT:
2632 LOGW("Asynchronous input event injection timed out.");
2633 break;
2634 }
2635 }
2636
Jeff Brown01ce2e92010-09-26 22:20:12 -07002637 injectionState->injectionResult = injectionResult;
Jeff Brown7fbdc842010-06-17 20:52:56 -07002638 mInjectionResultAvailableCondition.broadcast();
2639 }
2640}
2641
Jeff Brown01ce2e92010-09-26 22:20:12 -07002642void InputDispatcher::incrementPendingForegroundDispatchesLocked(EventEntry* entry) {
2643 InjectionState* injectionState = entry->injectionState;
2644 if (injectionState) {
2645 injectionState->pendingForegroundDispatches += 1;
2646 }
2647}
2648
Jeff Brown519e0242010-09-15 15:18:56 -07002649void InputDispatcher::decrementPendingForegroundDispatchesLocked(EventEntry* entry) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002650 InjectionState* injectionState = entry->injectionState;
2651 if (injectionState) {
2652 injectionState->pendingForegroundDispatches -= 1;
Jeff Brown6ec402b2010-07-28 15:48:59 -07002653
Jeff Brown01ce2e92010-09-26 22:20:12 -07002654 if (injectionState->pendingForegroundDispatches == 0) {
2655 mInjectionSyncFinishedCondition.broadcast();
2656 }
Jeff Brownb88102f2010-09-08 11:49:43 -07002657 }
2658}
2659
Jeff Brown01ce2e92010-09-26 22:20:12 -07002660const InputWindow* InputDispatcher::getWindowLocked(const sp<InputChannel>& inputChannel) {
2661 for (size_t i = 0; i < mWindows.size(); i++) {
2662 const InputWindow* window = & mWindows[i];
2663 if (window->inputChannel == inputChannel) {
2664 return window;
2665 }
2666 }
2667 return NULL;
2668}
2669
Jeff Brownb88102f2010-09-08 11:49:43 -07002670void InputDispatcher::setInputWindows(const Vector<InputWindow>& inputWindows) {
2671#if DEBUG_FOCUS
2672 LOGD("setInputWindows");
2673#endif
2674 { // acquire lock
2675 AutoMutex _l(mLock);
2676
Jeff Brown01ce2e92010-09-26 22:20:12 -07002677 // Clear old window pointers.
Jeff Brownb6997262010-10-08 22:31:17 -07002678 sp<InputChannel> oldFocusedWindowChannel;
2679 if (mFocusedWindow) {
2680 oldFocusedWindowChannel = mFocusedWindow->inputChannel;
2681 mFocusedWindow = NULL;
2682 }
2683
Jeff Brownb88102f2010-09-08 11:49:43 -07002684 mWindows.clear();
Jeff Brown2a95c2a2010-09-16 12:31:46 -07002685
2686 // Loop over new windows and rebuild the necessary window pointers for
2687 // tracking focus and touch.
Jeff Brownb88102f2010-09-08 11:49:43 -07002688 mWindows.appendVector(inputWindows);
2689
2690 size_t numWindows = mWindows.size();
2691 for (size_t i = 0; i < numWindows; i++) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002692 const InputWindow* window = & mWindows.itemAt(i);
Jeff Brownb88102f2010-09-08 11:49:43 -07002693 if (window->hasFocus) {
2694 mFocusedWindow = window;
Jeff Brown01ce2e92010-09-26 22:20:12 -07002695 break;
Jeff Brownb88102f2010-09-08 11:49:43 -07002696 }
2697 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07002698
Jeff Brownb6997262010-10-08 22:31:17 -07002699 if (oldFocusedWindowChannel != NULL) {
2700 if (!mFocusedWindow || oldFocusedWindowChannel != mFocusedWindow->inputChannel) {
2701#if DEBUG_FOCUS
2702 LOGD("Focus left window: %s",
2703 oldFocusedWindowChannel->getName().string());
2704#endif
2705 synthesizeCancelationEventsForInputChannelLocked(oldFocusedWindowChannel,
2706 InputState::CANCEL_NON_POINTER_EVENTS, "focus left window");
2707 oldFocusedWindowChannel.clear();
2708 }
2709 }
2710 if (mFocusedWindow && oldFocusedWindowChannel == NULL) {
2711#if DEBUG_FOCUS
2712 LOGD("Focus entered window: %s",
2713 mFocusedWindow->inputChannel->getName().string());
2714#endif
2715 }
2716
Jeff Brown01ce2e92010-09-26 22:20:12 -07002717 for (size_t i = 0; i < mTouchState.windows.size(); ) {
2718 TouchedWindow& touchedWindow = mTouchState.windows.editItemAt(i);
2719 const InputWindow* window = getWindowLocked(touchedWindow.channel);
2720 if (window) {
2721 touchedWindow.window = window;
2722 i += 1;
2723 } else {
Jeff Brownb6997262010-10-08 22:31:17 -07002724#if DEBUG_FOCUS
2725 LOGD("Touched window was removed: %s", touchedWindow.channel->getName().string());
2726#endif
Jeff Brownb6997262010-10-08 22:31:17 -07002727 synthesizeCancelationEventsForInputChannelLocked(touchedWindow.channel,
2728 InputState::CANCEL_POINTER_EVENTS, "touched window was removed");
Jeff Brownaf48cae2010-10-15 16:20:51 -07002729 mTouchState.windows.removeAt(i);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002730 }
2731 }
Jeff Brownb88102f2010-09-08 11:49:43 -07002732
Jeff Brownb88102f2010-09-08 11:49:43 -07002733#if DEBUG_FOCUS
Jeff Brownb6997262010-10-08 22:31:17 -07002734 //logDispatchStateLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -07002735#endif
2736 } // release lock
2737
2738 // Wake up poll loop since it may need to make new input dispatching choices.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002739 mLooper->wake();
Jeff Brownb88102f2010-09-08 11:49:43 -07002740}
2741
2742void InputDispatcher::setFocusedApplication(const InputApplication* inputApplication) {
2743#if DEBUG_FOCUS
2744 LOGD("setFocusedApplication");
2745#endif
2746 { // acquire lock
2747 AutoMutex _l(mLock);
2748
2749 releaseFocusedApplicationLocked();
2750
2751 if (inputApplication) {
2752 mFocusedApplicationStorage = *inputApplication;
2753 mFocusedApplication = & mFocusedApplicationStorage;
2754 }
2755
2756#if DEBUG_FOCUS
Jeff Brownb6997262010-10-08 22:31:17 -07002757 //logDispatchStateLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -07002758#endif
2759 } // release lock
2760
2761 // Wake up poll loop since it may need to make new input dispatching choices.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002762 mLooper->wake();
Jeff Brownb88102f2010-09-08 11:49:43 -07002763}
2764
2765void InputDispatcher::releaseFocusedApplicationLocked() {
2766 if (mFocusedApplication) {
2767 mFocusedApplication = NULL;
Jeff Brown928e0542011-01-10 11:17:36 -08002768 mFocusedApplicationStorage.inputApplicationHandle.clear();
Jeff Brownb88102f2010-09-08 11:49:43 -07002769 }
2770}
2771
2772void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
2773#if DEBUG_FOCUS
2774 LOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
2775#endif
2776
2777 bool changed;
2778 { // acquire lock
2779 AutoMutex _l(mLock);
2780
2781 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
Jeff Brown120a4592010-10-27 18:43:51 -07002782 if (mDispatchFrozen && !frozen) {
Jeff Brownb88102f2010-09-08 11:49:43 -07002783 resetANRTimeoutsLocked();
2784 }
2785
Jeff Brown120a4592010-10-27 18:43:51 -07002786 if (mDispatchEnabled && !enabled) {
2787 resetAndDropEverythingLocked("dispatcher is being disabled");
2788 }
2789
Jeff Brownb88102f2010-09-08 11:49:43 -07002790 mDispatchEnabled = enabled;
2791 mDispatchFrozen = frozen;
2792 changed = true;
2793 } else {
2794 changed = false;
2795 }
2796
2797#if DEBUG_FOCUS
Jeff Brownb6997262010-10-08 22:31:17 -07002798 //logDispatchStateLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -07002799#endif
2800 } // release lock
2801
2802 if (changed) {
2803 // Wake up poll loop since it may need to make new input dispatching choices.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002804 mLooper->wake();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002805 }
2806}
2807
Jeff Browne6504122010-09-27 14:52:15 -07002808bool InputDispatcher::transferTouchFocus(const sp<InputChannel>& fromChannel,
2809 const sp<InputChannel>& toChannel) {
2810#if DEBUG_FOCUS
2811 LOGD("transferTouchFocus: fromChannel=%s, toChannel=%s",
2812 fromChannel->getName().string(), toChannel->getName().string());
2813#endif
2814 { // acquire lock
2815 AutoMutex _l(mLock);
2816
2817 const InputWindow* fromWindow = getWindowLocked(fromChannel);
2818 const InputWindow* toWindow = getWindowLocked(toChannel);
2819 if (! fromWindow || ! toWindow) {
2820#if DEBUG_FOCUS
2821 LOGD("Cannot transfer focus because from or to window not found.");
2822#endif
2823 return false;
2824 }
2825 if (fromWindow == toWindow) {
2826#if DEBUG_FOCUS
2827 LOGD("Trivial transfer to same window.");
2828#endif
2829 return true;
2830 }
2831
2832 bool found = false;
2833 for (size_t i = 0; i < mTouchState.windows.size(); i++) {
2834 const TouchedWindow& touchedWindow = mTouchState.windows[i];
2835 if (touchedWindow.window == fromWindow) {
2836 int32_t oldTargetFlags = touchedWindow.targetFlags;
2837 BitSet32 pointerIds = touchedWindow.pointerIds;
2838
2839 mTouchState.windows.removeAt(i);
2840
Jeff Brown46e75292010-11-10 16:53:45 -08002841 int32_t newTargetFlags = oldTargetFlags
2842 & (InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_SPLIT);
Jeff Browne6504122010-09-27 14:52:15 -07002843 mTouchState.addOrUpdateWindow(toWindow, newTargetFlags, pointerIds);
2844
2845 found = true;
2846 break;
2847 }
2848 }
2849
2850 if (! found) {
2851#if DEBUG_FOCUS
2852 LOGD("Focus transfer failed because from window did not have focus.");
2853#endif
2854 return false;
2855 }
2856
Jeff Brown9c9f1a32010-10-11 18:32:20 -07002857 ssize_t fromConnectionIndex = getConnectionIndexLocked(fromChannel);
2858 ssize_t toConnectionIndex = getConnectionIndexLocked(toChannel);
2859 if (fromConnectionIndex >= 0 && toConnectionIndex >= 0) {
2860 sp<Connection> fromConnection = mConnectionsByReceiveFd.valueAt(fromConnectionIndex);
2861 sp<Connection> toConnection = mConnectionsByReceiveFd.valueAt(toConnectionIndex);
2862
2863 fromConnection->inputState.copyPointerStateTo(toConnection->inputState);
2864 synthesizeCancelationEventsForConnectionLocked(fromConnection,
2865 InputState::CANCEL_POINTER_EVENTS,
2866 "transferring touch focus from this window to another window");
2867 }
2868
Jeff Browne6504122010-09-27 14:52:15 -07002869#if DEBUG_FOCUS
2870 logDispatchStateLocked();
2871#endif
2872 } // release lock
2873
2874 // Wake up poll loop since it may need to make new input dispatching choices.
2875 mLooper->wake();
2876 return true;
2877}
2878
Jeff Brown120a4592010-10-27 18:43:51 -07002879void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
2880#if DEBUG_FOCUS
2881 LOGD("Resetting and dropping all events (%s).", reason);
2882#endif
2883
2884 synthesizeCancelationEventsForAllConnectionsLocked(InputState::CANCEL_ALL_EVENTS, reason);
2885
2886 resetKeyRepeatLocked();
2887 releasePendingEventLocked();
2888 drainInboundQueueLocked();
2889 resetTargetsLocked();
2890
2891 mTouchState.reset();
2892}
2893
Jeff Brownb88102f2010-09-08 11:49:43 -07002894void InputDispatcher::logDispatchStateLocked() {
2895 String8 dump;
2896 dumpDispatchStateLocked(dump);
Jeff Brown2a95c2a2010-09-16 12:31:46 -07002897
2898 char* text = dump.lockBuffer(dump.size());
2899 char* start = text;
2900 while (*start != '\0') {
2901 char* end = strchr(start, '\n');
2902 if (*end == '\n') {
2903 *(end++) = '\0';
2904 }
2905 LOGD("%s", start);
2906 start = end;
2907 }
Jeff Brownb88102f2010-09-08 11:49:43 -07002908}
2909
2910void InputDispatcher::dumpDispatchStateLocked(String8& dump) {
Jeff Brownf2f487182010-10-01 17:46:21 -07002911 dump.appendFormat(INDENT "DispatchEnabled: %d\n", mDispatchEnabled);
2912 dump.appendFormat(INDENT "DispatchFrozen: %d\n", mDispatchFrozen);
Jeff Brownb88102f2010-09-08 11:49:43 -07002913
2914 if (mFocusedApplication) {
Jeff Brownf2f487182010-10-01 17:46:21 -07002915 dump.appendFormat(INDENT "FocusedApplication: name='%s', dispatchingTimeout=%0.3fms\n",
Jeff Brownb88102f2010-09-08 11:49:43 -07002916 mFocusedApplication->name.string(),
2917 mFocusedApplication->dispatchingTimeout / 1000000.0);
2918 } else {
Jeff Brownf2f487182010-10-01 17:46:21 -07002919 dump.append(INDENT "FocusedApplication: <null>\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07002920 }
Jeff Brownf2f487182010-10-01 17:46:21 -07002921 dump.appendFormat(INDENT "FocusedWindow: name='%s'\n",
Jeff Brown2a95c2a2010-09-16 12:31:46 -07002922 mFocusedWindow != NULL ? mFocusedWindow->name.string() : "<null>");
Jeff Brownf2f487182010-10-01 17:46:21 -07002923
2924 dump.appendFormat(INDENT "TouchDown: %s\n", toString(mTouchState.down));
2925 dump.appendFormat(INDENT "TouchSplit: %s\n", toString(mTouchState.split));
Jeff Brown95712852011-01-04 19:41:59 -08002926 dump.appendFormat(INDENT "TouchDeviceId: %d\n", mTouchState.deviceId);
Jeff Brown58a2da82011-01-25 16:02:22 -08002927 dump.appendFormat(INDENT "TouchSource: 0x%08x\n", mTouchState.source);
Jeff Brownf2f487182010-10-01 17:46:21 -07002928 if (!mTouchState.windows.isEmpty()) {
2929 dump.append(INDENT "TouchedWindows:\n");
2930 for (size_t i = 0; i < mTouchState.windows.size(); i++) {
2931 const TouchedWindow& touchedWindow = mTouchState.windows[i];
2932 dump.appendFormat(INDENT2 "%d: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
2933 i, touchedWindow.window->name.string(), touchedWindow.pointerIds.value,
2934 touchedWindow.targetFlags);
2935 }
2936 } else {
2937 dump.append(INDENT "TouchedWindows: <none>\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07002938 }
2939
Jeff Brownf2f487182010-10-01 17:46:21 -07002940 if (!mWindows.isEmpty()) {
2941 dump.append(INDENT "Windows:\n");
2942 for (size_t i = 0; i < mWindows.size(); i++) {
2943 const InputWindow& window = mWindows[i];
2944 dump.appendFormat(INDENT2 "%d: name='%s', paused=%s, hasFocus=%s, hasWallpaper=%s, "
2945 "visible=%s, canReceiveKeys=%s, flags=0x%08x, type=0x%08x, layer=%d, "
2946 "frame=[%d,%d][%d,%d], "
Jeff Brownfbf09772011-01-16 14:06:57 -08002947 "touchableRegion=",
Jeff Brownf2f487182010-10-01 17:46:21 -07002948 i, window.name.string(),
2949 toString(window.paused),
2950 toString(window.hasFocus),
2951 toString(window.hasWallpaper),
2952 toString(window.visible),
2953 toString(window.canReceiveKeys),
2954 window.layoutParamsFlags, window.layoutParamsType,
2955 window.layer,
2956 window.frameLeft, window.frameTop,
Jeff Brownfbf09772011-01-16 14:06:57 -08002957 window.frameRight, window.frameBottom);
2958 dumpRegion(dump, window.touchableRegion);
2959 dump.appendFormat(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%0.3fms\n",
Jeff Brownf2f487182010-10-01 17:46:21 -07002960 window.ownerPid, window.ownerUid,
2961 window.dispatchingTimeout / 1000000.0);
2962 }
2963 } else {
2964 dump.append(INDENT "Windows: <none>\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07002965 }
2966
Jeff Brownf2f487182010-10-01 17:46:21 -07002967 if (!mMonitoringChannels.isEmpty()) {
2968 dump.append(INDENT "MonitoringChannels:\n");
2969 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
2970 const sp<InputChannel>& channel = mMonitoringChannels[i];
2971 dump.appendFormat(INDENT2 "%d: '%s'\n", i, channel->getName().string());
2972 }
2973 } else {
2974 dump.append(INDENT "MonitoringChannels: <none>\n");
2975 }
Jeff Brown519e0242010-09-15 15:18:56 -07002976
Jeff Brownf2f487182010-10-01 17:46:21 -07002977 dump.appendFormat(INDENT "InboundQueue: length=%u\n", mInboundQueue.count());
2978
2979 if (!mActiveConnections.isEmpty()) {
2980 dump.append(INDENT "ActiveConnections:\n");
2981 for (size_t i = 0; i < mActiveConnections.size(); i++) {
2982 const Connection* connection = mActiveConnections[i];
Jeff Brown76860e32010-10-25 17:37:46 -07002983 dump.appendFormat(INDENT2 "%d: '%s', status=%s, outboundQueueLength=%u, "
Jeff Brownb6997262010-10-08 22:31:17 -07002984 "inputState.isNeutral=%s\n",
Jeff Brownf2f487182010-10-01 17:46:21 -07002985 i, connection->getInputChannelName(), connection->getStatusLabel(),
2986 connection->outboundQueue.count(),
Jeff Brownb6997262010-10-08 22:31:17 -07002987 toString(connection->inputState.isNeutral()));
Jeff Brownf2f487182010-10-01 17:46:21 -07002988 }
2989 } else {
2990 dump.append(INDENT "ActiveConnections: <none>\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07002991 }
2992
2993 if (isAppSwitchPendingLocked()) {
Jeff Brownf2f487182010-10-01 17:46:21 -07002994 dump.appendFormat(INDENT "AppSwitch: pending, due in %01.1fms\n",
Jeff Brownb88102f2010-09-08 11:49:43 -07002995 (mAppSwitchDueTime - now()) / 1000000.0);
2996 } else {
Jeff Brownf2f487182010-10-01 17:46:21 -07002997 dump.append(INDENT "AppSwitch: not pending\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07002998 }
2999}
3000
Jeff Brown928e0542011-01-10 11:17:36 -08003001status_t InputDispatcher::registerInputChannel(const sp<InputChannel>& inputChannel,
3002 const sp<InputWindowHandle>& inputWindowHandle, bool monitor) {
Jeff Brown9c3cda02010-06-15 01:31:58 -07003003#if DEBUG_REGISTRATION
Jeff Brownb88102f2010-09-08 11:49:43 -07003004 LOGD("channel '%s' ~ registerInputChannel - monitor=%s", inputChannel->getName().string(),
3005 toString(monitor));
Jeff Brown9c3cda02010-06-15 01:31:58 -07003006#endif
3007
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003008 { // acquire lock
3009 AutoMutex _l(mLock);
3010
Jeff Brown519e0242010-09-15 15:18:56 -07003011 if (getConnectionIndexLocked(inputChannel) >= 0) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003012 LOGW("Attempted to register already registered input channel '%s'",
3013 inputChannel->getName().string());
3014 return BAD_VALUE;
3015 }
3016
Jeff Brown928e0542011-01-10 11:17:36 -08003017 sp<Connection> connection = new Connection(inputChannel, inputWindowHandle);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003018 status_t status = connection->initialize();
3019 if (status) {
3020 LOGE("Failed to initialize input publisher for input channel '%s', status=%d",
3021 inputChannel->getName().string(), status);
3022 return status;
3023 }
3024
Jeff Brown2cbecea2010-08-17 15:59:26 -07003025 int32_t receiveFd = inputChannel->getReceivePipeFd();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003026 mConnectionsByReceiveFd.add(receiveFd, connection);
Jeff Brown9c3cda02010-06-15 01:31:58 -07003027
Jeff Brownb88102f2010-09-08 11:49:43 -07003028 if (monitor) {
3029 mMonitoringChannels.push(inputChannel);
3030 }
3031
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07003032 mLooper->addFd(receiveFd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
Jeff Brown2cbecea2010-08-17 15:59:26 -07003033
Jeff Brown9c3cda02010-06-15 01:31:58 -07003034 runCommandsLockedInterruptible();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003035 } // release lock
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003036 return OK;
3037}
3038
3039status_t InputDispatcher::unregisterInputChannel(const sp<InputChannel>& inputChannel) {
Jeff Brown9c3cda02010-06-15 01:31:58 -07003040#if DEBUG_REGISTRATION
Jeff Brown349703e2010-06-22 01:27:15 -07003041 LOGD("channel '%s' ~ unregisterInputChannel", inputChannel->getName().string());
Jeff Brown9c3cda02010-06-15 01:31:58 -07003042#endif
3043
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003044 { // acquire lock
3045 AutoMutex _l(mLock);
3046
Jeff Brown519e0242010-09-15 15:18:56 -07003047 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003048 if (connectionIndex < 0) {
3049 LOGW("Attempted to unregister already unregistered input channel '%s'",
3050 inputChannel->getName().string());
3051 return BAD_VALUE;
3052 }
3053
3054 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
3055 mConnectionsByReceiveFd.removeItemsAt(connectionIndex);
3056
3057 connection->status = Connection::STATUS_ZOMBIE;
3058
Jeff Brownb88102f2010-09-08 11:49:43 -07003059 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
3060 if (mMonitoringChannels[i] == inputChannel) {
3061 mMonitoringChannels.removeAt(i);
3062 break;
3063 }
3064 }
3065
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07003066 mLooper->removeFd(inputChannel->getReceivePipeFd());
Jeff Brown2cbecea2010-08-17 15:59:26 -07003067
Jeff Brown7fbdc842010-06-17 20:52:56 -07003068 nsecs_t currentTime = now();
Jeff Brownb6997262010-10-08 22:31:17 -07003069 abortBrokenDispatchCycleLocked(currentTime, connection);
Jeff Brown9c3cda02010-06-15 01:31:58 -07003070
3071 runCommandsLockedInterruptible();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003072 } // release lock
3073
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003074 // Wake the poll loop because removing the connection may have changed the current
3075 // synchronization state.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07003076 mLooper->wake();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003077 return OK;
3078}
3079
Jeff Brown519e0242010-09-15 15:18:56 -07003080ssize_t InputDispatcher::getConnectionIndexLocked(const sp<InputChannel>& inputChannel) {
Jeff Brown2cbecea2010-08-17 15:59:26 -07003081 ssize_t connectionIndex = mConnectionsByReceiveFd.indexOfKey(inputChannel->getReceivePipeFd());
3082 if (connectionIndex >= 0) {
3083 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
3084 if (connection->inputChannel.get() == inputChannel.get()) {
3085 return connectionIndex;
3086 }
3087 }
3088
3089 return -1;
3090}
3091
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003092void InputDispatcher::activateConnectionLocked(Connection* connection) {
3093 for (size_t i = 0; i < mActiveConnections.size(); i++) {
3094 if (mActiveConnections.itemAt(i) == connection) {
3095 return;
3096 }
3097 }
3098 mActiveConnections.add(connection);
3099}
3100
3101void InputDispatcher::deactivateConnectionLocked(Connection* connection) {
3102 for (size_t i = 0; i < mActiveConnections.size(); i++) {
3103 if (mActiveConnections.itemAt(i) == connection) {
3104 mActiveConnections.removeAt(i);
3105 return;
3106 }
3107 }
3108}
3109
Jeff Brown9c3cda02010-06-15 01:31:58 -07003110void InputDispatcher::onDispatchCycleStartedLocked(
Jeff Brown7fbdc842010-06-17 20:52:56 -07003111 nsecs_t currentTime, const sp<Connection>& connection) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003112}
3113
Jeff Brown9c3cda02010-06-15 01:31:58 -07003114void InputDispatcher::onDispatchCycleFinishedLocked(
Jeff Brown3915bb82010-11-05 15:02:16 -07003115 nsecs_t currentTime, const sp<Connection>& connection, bool handled) {
3116 CommandEntry* commandEntry = postCommandLocked(
3117 & InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
3118 commandEntry->connection = connection;
3119 commandEntry->handled = handled;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003120}
3121
Jeff Brown9c3cda02010-06-15 01:31:58 -07003122void InputDispatcher::onDispatchCycleBrokenLocked(
Jeff Brown7fbdc842010-06-17 20:52:56 -07003123 nsecs_t currentTime, const sp<Connection>& connection) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003124 LOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
3125 connection->getInputChannelName());
3126
Jeff Brown9c3cda02010-06-15 01:31:58 -07003127 CommandEntry* commandEntry = postCommandLocked(
3128 & InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
Jeff Brown7fbdc842010-06-17 20:52:56 -07003129 commandEntry->connection = connection;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003130}
3131
Jeff Brown519e0242010-09-15 15:18:56 -07003132void InputDispatcher::onANRLocked(
3133 nsecs_t currentTime, const InputApplication* application, const InputWindow* window,
3134 nsecs_t eventTime, nsecs_t waitStartTime) {
3135 LOGI("Application is not responding: %s. "
3136 "%01.1fms since event, %01.1fms since wait started",
3137 getApplicationWindowLabelLocked(application, window).string(),
3138 (currentTime - eventTime) / 1000000.0,
3139 (currentTime - waitStartTime) / 1000000.0);
3140
3141 CommandEntry* commandEntry = postCommandLocked(
3142 & InputDispatcher::doNotifyANRLockedInterruptible);
3143 if (application) {
Jeff Brown928e0542011-01-10 11:17:36 -08003144 commandEntry->inputApplicationHandle = application->inputApplicationHandle;
Jeff Brown519e0242010-09-15 15:18:56 -07003145 }
3146 if (window) {
Jeff Brown928e0542011-01-10 11:17:36 -08003147 commandEntry->inputWindowHandle = window->inputWindowHandle;
Jeff Brown519e0242010-09-15 15:18:56 -07003148 commandEntry->inputChannel = window->inputChannel;
3149 }
3150}
3151
Jeff Brownb88102f2010-09-08 11:49:43 -07003152void InputDispatcher::doNotifyConfigurationChangedInterruptible(
3153 CommandEntry* commandEntry) {
3154 mLock.unlock();
3155
3156 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
3157
3158 mLock.lock();
3159}
3160
Jeff Brown9c3cda02010-06-15 01:31:58 -07003161void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(
3162 CommandEntry* commandEntry) {
Jeff Brown7fbdc842010-06-17 20:52:56 -07003163 sp<Connection> connection = commandEntry->connection;
Jeff Brown9c3cda02010-06-15 01:31:58 -07003164
Jeff Brown7fbdc842010-06-17 20:52:56 -07003165 if (connection->status != Connection::STATUS_ZOMBIE) {
3166 mLock.unlock();
Jeff Brown9c3cda02010-06-15 01:31:58 -07003167
Jeff Brown928e0542011-01-10 11:17:36 -08003168 mPolicy->notifyInputChannelBroken(connection->inputWindowHandle);
Jeff Brown7fbdc842010-06-17 20:52:56 -07003169
3170 mLock.lock();
3171 }
Jeff Brown9c3cda02010-06-15 01:31:58 -07003172}
3173
Jeff Brown519e0242010-09-15 15:18:56 -07003174void InputDispatcher::doNotifyANRLockedInterruptible(
Jeff Brown9c3cda02010-06-15 01:31:58 -07003175 CommandEntry* commandEntry) {
Jeff Brown519e0242010-09-15 15:18:56 -07003176 mLock.unlock();
Jeff Brown9c3cda02010-06-15 01:31:58 -07003177
Jeff Brown519e0242010-09-15 15:18:56 -07003178 nsecs_t newTimeout = mPolicy->notifyANR(
Jeff Brown928e0542011-01-10 11:17:36 -08003179 commandEntry->inputApplicationHandle, commandEntry->inputWindowHandle);
Jeff Brown9c3cda02010-06-15 01:31:58 -07003180
Jeff Brown519e0242010-09-15 15:18:56 -07003181 mLock.lock();
Jeff Brown7fbdc842010-06-17 20:52:56 -07003182
Jeff Brown519e0242010-09-15 15:18:56 -07003183 resumeAfterTargetsNotReadyTimeoutLocked(newTimeout, commandEntry->inputChannel);
Jeff Brown9c3cda02010-06-15 01:31:58 -07003184}
3185
Jeff Brownb88102f2010-09-08 11:49:43 -07003186void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
3187 CommandEntry* commandEntry) {
3188 KeyEntry* entry = commandEntry->keyEntry;
Jeff Brown1f245102010-11-18 20:53:46 -08003189
3190 KeyEvent event;
3191 initializeKeyEvent(&event, entry);
Jeff Brownb88102f2010-09-08 11:49:43 -07003192
3193 mLock.unlock();
3194
Jeff Brown928e0542011-01-10 11:17:36 -08003195 bool consumed = mPolicy->interceptKeyBeforeDispatching(commandEntry->inputWindowHandle,
Jeff Brown1f245102010-11-18 20:53:46 -08003196 &event, entry->policyFlags);
Jeff Brownb88102f2010-09-08 11:49:43 -07003197
3198 mLock.lock();
3199
3200 entry->interceptKeyResult = consumed
3201 ? KeyEntry::INTERCEPT_KEY_RESULT_SKIP
3202 : KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
3203 mAllocator.releaseKeyEntry(entry);
3204}
3205
Jeff Brown3915bb82010-11-05 15:02:16 -07003206void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(
3207 CommandEntry* commandEntry) {
3208 sp<Connection> connection = commandEntry->connection;
3209 bool handled = commandEntry->handled;
3210
Jeff Brown49ed71d2010-12-06 17:13:33 -08003211 if (!connection->outboundQueue.isEmpty()) {
Jeff Brown3915bb82010-11-05 15:02:16 -07003212 DispatchEntry* dispatchEntry = connection->outboundQueue.headSentinel.next;
3213 if (dispatchEntry->inProgress
3214 && dispatchEntry->hasForegroundTarget()
3215 && dispatchEntry->eventEntry->type == EventEntry::TYPE_KEY) {
3216 KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry);
Jeff Brown49ed71d2010-12-06 17:13:33 -08003217 if (!(keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK)) {
3218 if (handled) {
3219 // If the application handled a non-fallback key, then immediately
3220 // cancel all fallback keys previously dispatched to the application.
3221 // This behavior will prevent chording with fallback keys (so they cannot
3222 // be used as modifiers) but it will ensure that fallback keys do not
3223 // get stuck. This takes care of the case where the application does not handle
3224 // the original DOWN so we generate a fallback DOWN but it does handle
Jeff Brownbfaf3b92011-02-22 15:00:50 -08003225 // the original UP in which case we want to send a fallback CANCEL.
Jeff Brown49ed71d2010-12-06 17:13:33 -08003226 synthesizeCancelationEventsForConnectionLocked(connection,
3227 InputState::CANCEL_FALLBACK_EVENTS,
Jeff Brownbfaf3b92011-02-22 15:00:50 -08003228 "application handled a non-fallback event, "
3229 "canceling all fallback events");
3230 connection->originalKeyCodeForFallback = -1;
Jeff Brown49ed71d2010-12-06 17:13:33 -08003231 } else {
Jeff Brownbfaf3b92011-02-22 15:00:50 -08003232 // If the application did not handle a non-fallback key, first check
3233 // that we are in a good state to handle the fallback key. Then ask
3234 // the policy what to do with it.
3235 if (connection->originalKeyCodeForFallback < 0) {
3236 if (keyEntry->action != AKEY_EVENT_ACTION_DOWN
3237 || keyEntry->repeatCount != 0) {
3238#if DEBUG_OUTBOUND_EVENT_DETAILS
3239 LOGD("Unhandled key event: Skipping fallback since this "
3240 "is not an initial down. "
3241 "keyCode=%d, action=%d, repeatCount=%d",
3242 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount);
3243#endif
3244 goto SkipFallback;
3245 }
3246
3247 // Start handling the fallback key on DOWN.
3248 connection->originalKeyCodeForFallback = keyEntry->keyCode;
3249 } else {
3250 if (keyEntry->keyCode != connection->originalKeyCodeForFallback) {
3251#if DEBUG_OUTBOUND_EVENT_DETAILS
3252 LOGD("Unhandled key event: Skipping fallback since there is "
3253 "already a different fallback in progress. "
3254 "keyCode=%d, originalKeyCodeForFallback=%d",
3255 keyEntry->keyCode, connection->originalKeyCodeForFallback);
3256#endif
3257 goto SkipFallback;
3258 }
3259
3260 // Finish handling the fallback key on UP.
3261 if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
3262 connection->originalKeyCodeForFallback = -1;
3263 }
3264 }
3265
3266#if DEBUG_OUTBOUND_EVENT_DETAILS
3267 LOGD("Unhandled key event: Asking policy to perform fallback action. "
3268 "keyCode=%d, action=%d, repeatCount=%d",
3269 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount);
3270#endif
Jeff Brown49ed71d2010-12-06 17:13:33 -08003271 KeyEvent event;
3272 initializeKeyEvent(&event, keyEntry);
Jeff Brown3915bb82010-11-05 15:02:16 -07003273
Jeff Brown49ed71d2010-12-06 17:13:33 -08003274 mLock.unlock();
Jeff Brown3915bb82010-11-05 15:02:16 -07003275
Jeff Brown928e0542011-01-10 11:17:36 -08003276 bool fallback = mPolicy->dispatchUnhandledKey(connection->inputWindowHandle,
Jeff Brown49ed71d2010-12-06 17:13:33 -08003277 &event, keyEntry->policyFlags, &event);
Jeff Brown3915bb82010-11-05 15:02:16 -07003278
Jeff Brown49ed71d2010-12-06 17:13:33 -08003279 mLock.lock();
3280
Jeff Brown00045a72010-12-09 18:10:30 -08003281 if (connection->status != Connection::STATUS_NORMAL) {
3282 return;
3283 }
3284
3285 assert(connection->outboundQueue.headSentinel.next == dispatchEntry);
3286
Jeff Brown49ed71d2010-12-06 17:13:33 -08003287 if (fallback) {
3288 // Restart the dispatch cycle using the fallback key.
3289 keyEntry->eventTime = event.getEventTime();
3290 keyEntry->deviceId = event.getDeviceId();
3291 keyEntry->source = event.getSource();
3292 keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
3293 keyEntry->keyCode = event.getKeyCode();
3294 keyEntry->scanCode = event.getScanCode();
3295 keyEntry->metaState = event.getMetaState();
3296 keyEntry->repeatCount = event.getRepeatCount();
3297 keyEntry->downTime = event.getDownTime();
3298 keyEntry->syntheticRepeat = false;
3299
Jeff Brownbfaf3b92011-02-22 15:00:50 -08003300#if DEBUG_OUTBOUND_EVENT_DETAILS
3301 LOGD("Unhandled key event: Dispatching fallback key. "
3302 "fallbackKeyCode=%d, fallbackMetaState=%08x",
3303 keyEntry->keyCode, keyEntry->metaState);
3304#endif
3305
Jeff Brown49ed71d2010-12-06 17:13:33 -08003306 dispatchEntry->inProgress = false;
3307 startDispatchCycleLocked(now(), connection);
3308 return;
3309 }
3310 }
3311 }
Jeff Brown3915bb82010-11-05 15:02:16 -07003312 }
3313 }
3314
Jeff Brownbfaf3b92011-02-22 15:00:50 -08003315SkipFallback:
Jeff Brown3915bb82010-11-05 15:02:16 -07003316 startNextDispatchCycleLocked(now(), connection);
3317}
3318
Jeff Brownb88102f2010-09-08 11:49:43 -07003319void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
3320 mLock.unlock();
3321
Jeff Brown01ce2e92010-09-26 22:20:12 -07003322 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
Jeff Brownb88102f2010-09-08 11:49:43 -07003323
3324 mLock.lock();
3325}
3326
Jeff Brown3915bb82010-11-05 15:02:16 -07003327void InputDispatcher::initializeKeyEvent(KeyEvent* event, const KeyEntry* entry) {
3328 event->initialize(entry->deviceId, entry->source, entry->action, entry->flags,
3329 entry->keyCode, entry->scanCode, entry->metaState, entry->repeatCount,
3330 entry->downTime, entry->eventTime);
3331}
3332
Jeff Brown519e0242010-09-15 15:18:56 -07003333void InputDispatcher::updateDispatchStatisticsLocked(nsecs_t currentTime, const EventEntry* entry,
3334 int32_t injectionResult, nsecs_t timeSpentWaitingForApplication) {
3335 // TODO Write some statistics about how long we spend waiting.
Jeff Brownb88102f2010-09-08 11:49:43 -07003336}
3337
3338void InputDispatcher::dump(String8& dump) {
Jeff Brownf2f487182010-10-01 17:46:21 -07003339 dump.append("Input Dispatcher State:\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003340 dumpDispatchStateLocked(dump);
3341}
3342
Jeff Brown9c3cda02010-06-15 01:31:58 -07003343
Jeff Brown519e0242010-09-15 15:18:56 -07003344// --- InputDispatcher::Queue ---
3345
3346template <typename T>
3347uint32_t InputDispatcher::Queue<T>::count() const {
3348 uint32_t result = 0;
3349 for (const T* entry = headSentinel.next; entry != & tailSentinel; entry = entry->next) {
3350 result += 1;
3351 }
3352 return result;
3353}
3354
3355
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003356// --- InputDispatcher::Allocator ---
3357
3358InputDispatcher::Allocator::Allocator() {
3359}
3360
Jeff Brown01ce2e92010-09-26 22:20:12 -07003361InputDispatcher::InjectionState*
3362InputDispatcher::Allocator::obtainInjectionState(int32_t injectorPid, int32_t injectorUid) {
3363 InjectionState* injectionState = mInjectionStatePool.alloc();
3364 injectionState->refCount = 1;
3365 injectionState->injectorPid = injectorPid;
3366 injectionState->injectorUid = injectorUid;
3367 injectionState->injectionIsAsync = false;
3368 injectionState->injectionResult = INPUT_EVENT_INJECTION_PENDING;
3369 injectionState->pendingForegroundDispatches = 0;
3370 return injectionState;
3371}
3372
Jeff Brown7fbdc842010-06-17 20:52:56 -07003373void InputDispatcher::Allocator::initializeEventEntry(EventEntry* entry, int32_t type,
Jeff Brownb6997262010-10-08 22:31:17 -07003374 nsecs_t eventTime, uint32_t policyFlags) {
Jeff Brown7fbdc842010-06-17 20:52:56 -07003375 entry->type = type;
3376 entry->refCount = 1;
3377 entry->dispatchInProgress = false;
Christopher Tatee91a5db2010-06-23 16:50:30 -07003378 entry->eventTime = eventTime;
Jeff Brownb6997262010-10-08 22:31:17 -07003379 entry->policyFlags = policyFlags;
Jeff Brown01ce2e92010-09-26 22:20:12 -07003380 entry->injectionState = NULL;
3381}
3382
3383void InputDispatcher::Allocator::releaseEventEntryInjectionState(EventEntry* entry) {
3384 if (entry->injectionState) {
3385 releaseInjectionState(entry->injectionState);
3386 entry->injectionState = NULL;
3387 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07003388}
3389
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003390InputDispatcher::ConfigurationChangedEntry*
Jeff Brown7fbdc842010-06-17 20:52:56 -07003391InputDispatcher::Allocator::obtainConfigurationChangedEntry(nsecs_t eventTime) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003392 ConfigurationChangedEntry* entry = mConfigurationChangeEntryPool.alloc();
Jeff Brownb6997262010-10-08 22:31:17 -07003393 initializeEventEntry(entry, EventEntry::TYPE_CONFIGURATION_CHANGED, eventTime, 0);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003394 return entry;
3395}
3396
Jeff Brown7fbdc842010-06-17 20:52:56 -07003397InputDispatcher::KeyEntry* InputDispatcher::Allocator::obtainKeyEntry(nsecs_t eventTime,
Jeff Brown58a2da82011-01-25 16:02:22 -08003398 int32_t deviceId, uint32_t source, uint32_t policyFlags, int32_t action,
Jeff Brown7fbdc842010-06-17 20:52:56 -07003399 int32_t flags, int32_t keyCode, int32_t scanCode, int32_t metaState,
3400 int32_t repeatCount, nsecs_t downTime) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003401 KeyEntry* entry = mKeyEntryPool.alloc();
Jeff Brownb6997262010-10-08 22:31:17 -07003402 initializeEventEntry(entry, EventEntry::TYPE_KEY, eventTime, policyFlags);
Jeff Brown7fbdc842010-06-17 20:52:56 -07003403
3404 entry->deviceId = deviceId;
Jeff Brownc5ed5912010-07-14 18:48:53 -07003405 entry->source = source;
Jeff Brown7fbdc842010-06-17 20:52:56 -07003406 entry->action = action;
3407 entry->flags = flags;
3408 entry->keyCode = keyCode;
3409 entry->scanCode = scanCode;
3410 entry->metaState = metaState;
3411 entry->repeatCount = repeatCount;
3412 entry->downTime = downTime;
Jeff Brownb88102f2010-09-08 11:49:43 -07003413 entry->syntheticRepeat = false;
3414 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003415 return entry;
3416}
3417
Jeff Brown7fbdc842010-06-17 20:52:56 -07003418InputDispatcher::MotionEntry* InputDispatcher::Allocator::obtainMotionEntry(nsecs_t eventTime,
Jeff Brown58a2da82011-01-25 16:02:22 -08003419 int32_t deviceId, uint32_t source, uint32_t policyFlags, int32_t action, int32_t flags,
Jeff Brown7fbdc842010-06-17 20:52:56 -07003420 int32_t metaState, int32_t edgeFlags, float xPrecision, float yPrecision,
3421 nsecs_t downTime, uint32_t pointerCount,
3422 const int32_t* pointerIds, const PointerCoords* pointerCoords) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003423 MotionEntry* entry = mMotionEntryPool.alloc();
Jeff Brownb6997262010-10-08 22:31:17 -07003424 initializeEventEntry(entry, EventEntry::TYPE_MOTION, eventTime, policyFlags);
Jeff Brown7fbdc842010-06-17 20:52:56 -07003425
3426 entry->eventTime = eventTime;
3427 entry->deviceId = deviceId;
Jeff Brownc5ed5912010-07-14 18:48:53 -07003428 entry->source = source;
Jeff Brown7fbdc842010-06-17 20:52:56 -07003429 entry->action = action;
Jeff Brown85a31762010-09-01 17:01:00 -07003430 entry->flags = flags;
Jeff Brown7fbdc842010-06-17 20:52:56 -07003431 entry->metaState = metaState;
3432 entry->edgeFlags = edgeFlags;
3433 entry->xPrecision = xPrecision;
3434 entry->yPrecision = yPrecision;
3435 entry->downTime = downTime;
3436 entry->pointerCount = pointerCount;
3437 entry->firstSample.eventTime = eventTime;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003438 entry->firstSample.next = NULL;
Jeff Brown7fbdc842010-06-17 20:52:56 -07003439 entry->lastSample = & entry->firstSample;
3440 for (uint32_t i = 0; i < pointerCount; i++) {
3441 entry->pointerIds[i] = pointerIds[i];
3442 entry->firstSample.pointerCoords[i] = pointerCoords[i];
3443 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003444 return entry;
3445}
3446
3447InputDispatcher::DispatchEntry* InputDispatcher::Allocator::obtainDispatchEntry(
Jeff Brownb88102f2010-09-08 11:49:43 -07003448 EventEntry* eventEntry,
Jeff Brown519e0242010-09-15 15:18:56 -07003449 int32_t targetFlags, float xOffset, float yOffset) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003450 DispatchEntry* entry = mDispatchEntryPool.alloc();
3451 entry->eventEntry = eventEntry;
3452 eventEntry->refCount += 1;
Jeff Brownb88102f2010-09-08 11:49:43 -07003453 entry->targetFlags = targetFlags;
3454 entry->xOffset = xOffset;
3455 entry->yOffset = yOffset;
Jeff Brownb88102f2010-09-08 11:49:43 -07003456 entry->inProgress = false;
3457 entry->headMotionSample = NULL;
3458 entry->tailMotionSample = NULL;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003459 return entry;
3460}
3461
Jeff Brown9c3cda02010-06-15 01:31:58 -07003462InputDispatcher::CommandEntry* InputDispatcher::Allocator::obtainCommandEntry(Command command) {
3463 CommandEntry* entry = mCommandEntryPool.alloc();
3464 entry->command = command;
3465 return entry;
3466}
3467
Jeff Brown01ce2e92010-09-26 22:20:12 -07003468void InputDispatcher::Allocator::releaseInjectionState(InjectionState* injectionState) {
3469 injectionState->refCount -= 1;
3470 if (injectionState->refCount == 0) {
3471 mInjectionStatePool.free(injectionState);
3472 } else {
3473 assert(injectionState->refCount > 0);
3474 }
3475}
3476
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003477void InputDispatcher::Allocator::releaseEventEntry(EventEntry* entry) {
3478 switch (entry->type) {
3479 case EventEntry::TYPE_CONFIGURATION_CHANGED:
3480 releaseConfigurationChangedEntry(static_cast<ConfigurationChangedEntry*>(entry));
3481 break;
3482 case EventEntry::TYPE_KEY:
3483 releaseKeyEntry(static_cast<KeyEntry*>(entry));
3484 break;
3485 case EventEntry::TYPE_MOTION:
3486 releaseMotionEntry(static_cast<MotionEntry*>(entry));
3487 break;
3488 default:
3489 assert(false);
3490 break;
3491 }
3492}
3493
3494void InputDispatcher::Allocator::releaseConfigurationChangedEntry(
3495 ConfigurationChangedEntry* entry) {
3496 entry->refCount -= 1;
3497 if (entry->refCount == 0) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07003498 releaseEventEntryInjectionState(entry);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003499 mConfigurationChangeEntryPool.free(entry);
3500 } else {
3501 assert(entry->refCount > 0);
3502 }
3503}
3504
3505void InputDispatcher::Allocator::releaseKeyEntry(KeyEntry* entry) {
3506 entry->refCount -= 1;
3507 if (entry->refCount == 0) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07003508 releaseEventEntryInjectionState(entry);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003509 mKeyEntryPool.free(entry);
3510 } else {
3511 assert(entry->refCount > 0);
3512 }
3513}
3514
3515void InputDispatcher::Allocator::releaseMotionEntry(MotionEntry* entry) {
3516 entry->refCount -= 1;
3517 if (entry->refCount == 0) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07003518 releaseEventEntryInjectionState(entry);
Jeff Brown9c3cda02010-06-15 01:31:58 -07003519 for (MotionSample* sample = entry->firstSample.next; sample != NULL; ) {
3520 MotionSample* next = sample->next;
3521 mMotionSamplePool.free(sample);
3522 sample = next;
3523 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003524 mMotionEntryPool.free(entry);
3525 } else {
3526 assert(entry->refCount > 0);
3527 }
3528}
3529
3530void InputDispatcher::Allocator::releaseDispatchEntry(DispatchEntry* entry) {
3531 releaseEventEntry(entry->eventEntry);
3532 mDispatchEntryPool.free(entry);
3533}
3534
Jeff Brown9c3cda02010-06-15 01:31:58 -07003535void InputDispatcher::Allocator::releaseCommandEntry(CommandEntry* entry) {
3536 mCommandEntryPool.free(entry);
3537}
3538
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003539void InputDispatcher::Allocator::appendMotionSample(MotionEntry* motionEntry,
Jeff Brown7fbdc842010-06-17 20:52:56 -07003540 nsecs_t eventTime, const PointerCoords* pointerCoords) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003541 MotionSample* sample = mMotionSamplePool.alloc();
3542 sample->eventTime = eventTime;
Jeff Brown7fbdc842010-06-17 20:52:56 -07003543 uint32_t pointerCount = motionEntry->pointerCount;
3544 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003545 sample->pointerCoords[i] = pointerCoords[i];
3546 }
3547
3548 sample->next = NULL;
3549 motionEntry->lastSample->next = sample;
3550 motionEntry->lastSample = sample;
3551}
3552
Jeff Brown01ce2e92010-09-26 22:20:12 -07003553void InputDispatcher::Allocator::recycleKeyEntry(KeyEntry* keyEntry) {
3554 releaseEventEntryInjectionState(keyEntry);
Jeff Brownb88102f2010-09-08 11:49:43 -07003555
Jeff Brown01ce2e92010-09-26 22:20:12 -07003556 keyEntry->dispatchInProgress = false;
3557 keyEntry->syntheticRepeat = false;
3558 keyEntry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
Jeff Brownb88102f2010-09-08 11:49:43 -07003559}
3560
3561
Jeff Brownae9fc032010-08-18 15:51:08 -07003562// --- InputDispatcher::MotionEntry ---
3563
3564uint32_t InputDispatcher::MotionEntry::countSamples() const {
3565 uint32_t count = 1;
3566 for (MotionSample* sample = firstSample.next; sample != NULL; sample = sample->next) {
3567 count += 1;
3568 }
3569 return count;
3570}
3571
Jeff Brownb88102f2010-09-08 11:49:43 -07003572
3573// --- InputDispatcher::InputState ---
3574
Jeff Brownb6997262010-10-08 22:31:17 -07003575InputDispatcher::InputState::InputState() {
Jeff Brownb88102f2010-09-08 11:49:43 -07003576}
3577
3578InputDispatcher::InputState::~InputState() {
3579}
3580
3581bool InputDispatcher::InputState::isNeutral() const {
3582 return mKeyMementos.isEmpty() && mMotionMementos.isEmpty();
3583}
3584
Jeff Browncc0c1592011-02-19 05:07:28 -08003585void InputDispatcher::InputState::trackEvent(
Jeff Brownb88102f2010-09-08 11:49:43 -07003586 const EventEntry* entry) {
3587 switch (entry->type) {
3588 case EventEntry::TYPE_KEY:
Jeff Browncc0c1592011-02-19 05:07:28 -08003589 trackKey(static_cast<const KeyEntry*>(entry));
3590 break;
Jeff Brownb88102f2010-09-08 11:49:43 -07003591
3592 case EventEntry::TYPE_MOTION:
Jeff Browncc0c1592011-02-19 05:07:28 -08003593 trackMotion(static_cast<const MotionEntry*>(entry));
3594 break;
Jeff Brownb88102f2010-09-08 11:49:43 -07003595 }
3596}
3597
Jeff Browncc0c1592011-02-19 05:07:28 -08003598void InputDispatcher::InputState::trackKey(
Jeff Brownb88102f2010-09-08 11:49:43 -07003599 const KeyEntry* entry) {
3600 int32_t action = entry->action;
3601 for (size_t i = 0; i < mKeyMementos.size(); i++) {
3602 KeyMemento& memento = mKeyMementos.editItemAt(i);
3603 if (memento.deviceId == entry->deviceId
3604 && memento.source == entry->source
3605 && memento.keyCode == entry->keyCode
3606 && memento.scanCode == entry->scanCode) {
3607 switch (action) {
3608 case AKEY_EVENT_ACTION_UP:
3609 mKeyMementos.removeAt(i);
Jeff Browncc0c1592011-02-19 05:07:28 -08003610 return;
Jeff Brownb88102f2010-09-08 11:49:43 -07003611
3612 case AKEY_EVENT_ACTION_DOWN:
Jeff Browncc0c1592011-02-19 05:07:28 -08003613 mKeyMementos.removeAt(i);
3614 goto Found;
Jeff Brownb88102f2010-09-08 11:49:43 -07003615
3616 default:
Jeff Browncc0c1592011-02-19 05:07:28 -08003617 return;
Jeff Brownb88102f2010-09-08 11:49:43 -07003618 }
3619 }
3620 }
3621
Jeff Browncc0c1592011-02-19 05:07:28 -08003622Found:
3623 if (action == AKEY_EVENT_ACTION_DOWN) {
Jeff Brownb88102f2010-09-08 11:49:43 -07003624 mKeyMementos.push();
3625 KeyMemento& memento = mKeyMementos.editTop();
3626 memento.deviceId = entry->deviceId;
3627 memento.source = entry->source;
3628 memento.keyCode = entry->keyCode;
3629 memento.scanCode = entry->scanCode;
Jeff Brown49ed71d2010-12-06 17:13:33 -08003630 memento.flags = entry->flags;
Jeff Brownb88102f2010-09-08 11:49:43 -07003631 memento.downTime = entry->downTime;
Jeff Brownb88102f2010-09-08 11:49:43 -07003632 }
3633}
3634
Jeff Browncc0c1592011-02-19 05:07:28 -08003635void InputDispatcher::InputState::trackMotion(
Jeff Brownb88102f2010-09-08 11:49:43 -07003636 const MotionEntry* entry) {
3637 int32_t action = entry->action & AMOTION_EVENT_ACTION_MASK;
3638 for (size_t i = 0; i < mMotionMementos.size(); i++) {
3639 MotionMemento& memento = mMotionMementos.editItemAt(i);
3640 if (memento.deviceId == entry->deviceId
3641 && memento.source == entry->source) {
3642 switch (action) {
3643 case AMOTION_EVENT_ACTION_UP:
3644 case AMOTION_EVENT_ACTION_CANCEL:
Jeff Browncc0c1592011-02-19 05:07:28 -08003645 case AMOTION_EVENT_ACTION_HOVER_MOVE:
Jeff Brownb88102f2010-09-08 11:49:43 -07003646 mMotionMementos.removeAt(i);
Jeff Browncc0c1592011-02-19 05:07:28 -08003647 return;
Jeff Brownb88102f2010-09-08 11:49:43 -07003648
3649 case AMOTION_EVENT_ACTION_DOWN:
Jeff Browncc0c1592011-02-19 05:07:28 -08003650 mMotionMementos.removeAt(i);
3651 goto Found;
Jeff Brownb88102f2010-09-08 11:49:43 -07003652
3653 case AMOTION_EVENT_ACTION_POINTER_UP:
Jeff Browncc0c1592011-02-19 05:07:28 -08003654 case AMOTION_EVENT_ACTION_POINTER_DOWN:
Jeff Brownb88102f2010-09-08 11:49:43 -07003655 case AMOTION_EVENT_ACTION_MOVE:
Jeff Browncc0c1592011-02-19 05:07:28 -08003656 memento.setPointers(entry);
3657 return;
Jeff Brownb88102f2010-09-08 11:49:43 -07003658
3659 default:
Jeff Browncc0c1592011-02-19 05:07:28 -08003660 return;
Jeff Brownb88102f2010-09-08 11:49:43 -07003661 }
3662 }
3663 }
3664
Jeff Browncc0c1592011-02-19 05:07:28 -08003665Found:
3666 if (action == AMOTION_EVENT_ACTION_DOWN) {
Jeff Brownb88102f2010-09-08 11:49:43 -07003667 mMotionMementos.push();
3668 MotionMemento& memento = mMotionMementos.editTop();
3669 memento.deviceId = entry->deviceId;
3670 memento.source = entry->source;
3671 memento.xPrecision = entry->xPrecision;
3672 memento.yPrecision = entry->yPrecision;
3673 memento.downTime = entry->downTime;
3674 memento.setPointers(entry);
Jeff Brownb88102f2010-09-08 11:49:43 -07003675 }
3676}
3677
3678void InputDispatcher::InputState::MotionMemento::setPointers(const MotionEntry* entry) {
3679 pointerCount = entry->pointerCount;
3680 for (uint32_t i = 0; i < entry->pointerCount; i++) {
3681 pointerIds[i] = entry->pointerIds[i];
3682 pointerCoords[i] = entry->lastSample->pointerCoords[i];
3683 }
3684}
3685
Jeff Brownb6997262010-10-08 22:31:17 -07003686void InputDispatcher::InputState::synthesizeCancelationEvents(nsecs_t currentTime,
3687 Allocator* allocator, Vector<EventEntry*>& outEvents,
3688 CancelationOptions options) {
3689 for (size_t i = 0; i < mKeyMementos.size(); ) {
Jeff Brownb88102f2010-09-08 11:49:43 -07003690 const KeyMemento& memento = mKeyMementos.itemAt(i);
Jeff Brown49ed71d2010-12-06 17:13:33 -08003691 if (shouldCancelKey(memento, options)) {
Jeff Brownb6997262010-10-08 22:31:17 -07003692 outEvents.push(allocator->obtainKeyEntry(currentTime,
3693 memento.deviceId, memento.source, 0,
Jeff Brown49ed71d2010-12-06 17:13:33 -08003694 AKEY_EVENT_ACTION_UP, memento.flags | AKEY_EVENT_FLAG_CANCELED,
Jeff Brownb6997262010-10-08 22:31:17 -07003695 memento.keyCode, memento.scanCode, 0, 0, memento.downTime));
3696 mKeyMementos.removeAt(i);
3697 } else {
3698 i += 1;
3699 }
Jeff Brownb88102f2010-09-08 11:49:43 -07003700 }
3701
Jeff Browna1160a72010-10-11 18:22:53 -07003702 for (size_t i = 0; i < mMotionMementos.size(); ) {
Jeff Brownb88102f2010-09-08 11:49:43 -07003703 const MotionMemento& memento = mMotionMementos.itemAt(i);
Jeff Brown49ed71d2010-12-06 17:13:33 -08003704 if (shouldCancelMotion(memento, options)) {
Jeff Brownb6997262010-10-08 22:31:17 -07003705 outEvents.push(allocator->obtainMotionEntry(currentTime,
3706 memento.deviceId, memento.source, 0,
3707 AMOTION_EVENT_ACTION_CANCEL, 0, 0, 0,
3708 memento.xPrecision, memento.yPrecision, memento.downTime,
3709 memento.pointerCount, memento.pointerIds, memento.pointerCoords));
3710 mMotionMementos.removeAt(i);
3711 } else {
3712 i += 1;
3713 }
Jeff Brownb88102f2010-09-08 11:49:43 -07003714 }
3715}
3716
3717void InputDispatcher::InputState::clear() {
3718 mKeyMementos.clear();
3719 mMotionMementos.clear();
Jeff Brownb6997262010-10-08 22:31:17 -07003720}
3721
Jeff Brown9c9f1a32010-10-11 18:32:20 -07003722void InputDispatcher::InputState::copyPointerStateTo(InputState& other) const {
3723 for (size_t i = 0; i < mMotionMementos.size(); i++) {
3724 const MotionMemento& memento = mMotionMementos.itemAt(i);
3725 if (memento.source & AINPUT_SOURCE_CLASS_POINTER) {
3726 for (size_t j = 0; j < other.mMotionMementos.size(); ) {
3727 const MotionMemento& otherMemento = other.mMotionMementos.itemAt(j);
3728 if (memento.deviceId == otherMemento.deviceId
3729 && memento.source == otherMemento.source) {
3730 other.mMotionMementos.removeAt(j);
3731 } else {
3732 j += 1;
3733 }
3734 }
3735 other.mMotionMementos.push(memento);
3736 }
3737 }
3738}
3739
Jeff Brown49ed71d2010-12-06 17:13:33 -08003740bool InputDispatcher::InputState::shouldCancelKey(const KeyMemento& memento,
Jeff Brownb6997262010-10-08 22:31:17 -07003741 CancelationOptions options) {
3742 switch (options) {
Jeff Brown49ed71d2010-12-06 17:13:33 -08003743 case CANCEL_ALL_EVENTS:
Jeff Brownb6997262010-10-08 22:31:17 -07003744 case CANCEL_NON_POINTER_EVENTS:
Jeff Brownb6997262010-10-08 22:31:17 -07003745 return true;
Jeff Brown49ed71d2010-12-06 17:13:33 -08003746 case CANCEL_FALLBACK_EVENTS:
3747 return memento.flags & AKEY_EVENT_FLAG_FALLBACK;
3748 default:
3749 return false;
3750 }
3751}
3752
3753bool InputDispatcher::InputState::shouldCancelMotion(const MotionMemento& memento,
3754 CancelationOptions options) {
3755 switch (options) {
3756 case CANCEL_ALL_EVENTS:
3757 return true;
3758 case CANCEL_POINTER_EVENTS:
3759 return memento.source & AINPUT_SOURCE_CLASS_POINTER;
3760 case CANCEL_NON_POINTER_EVENTS:
3761 return !(memento.source & AINPUT_SOURCE_CLASS_POINTER);
3762 default:
3763 return false;
Jeff Brownb6997262010-10-08 22:31:17 -07003764 }
Jeff Brownb88102f2010-09-08 11:49:43 -07003765}
3766
3767
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003768// --- InputDispatcher::Connection ---
3769
Jeff Brown928e0542011-01-10 11:17:36 -08003770InputDispatcher::Connection::Connection(const sp<InputChannel>& inputChannel,
3771 const sp<InputWindowHandle>& inputWindowHandle) :
3772 status(STATUS_NORMAL), inputChannel(inputChannel), inputWindowHandle(inputWindowHandle),
3773 inputPublisher(inputChannel),
Jeff Brownbfaf3b92011-02-22 15:00:50 -08003774 lastEventTime(LONG_LONG_MAX), lastDispatchTime(LONG_LONG_MAX),
3775 originalKeyCodeForFallback(-1) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003776}
3777
3778InputDispatcher::Connection::~Connection() {
3779}
3780
3781status_t InputDispatcher::Connection::initialize() {
3782 return inputPublisher.initialize();
3783}
3784
Jeff Brown9c3cda02010-06-15 01:31:58 -07003785const char* InputDispatcher::Connection::getStatusLabel() const {
3786 switch (status) {
3787 case STATUS_NORMAL:
3788 return "NORMAL";
3789
3790 case STATUS_BROKEN:
3791 return "BROKEN";
3792
Jeff Brown9c3cda02010-06-15 01:31:58 -07003793 case STATUS_ZOMBIE:
3794 return "ZOMBIE";
3795
3796 default:
3797 return "UNKNOWN";
3798 }
3799}
3800
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003801InputDispatcher::DispatchEntry* InputDispatcher::Connection::findQueuedDispatchEntryForEvent(
3802 const EventEntry* eventEntry) const {
Jeff Brownb88102f2010-09-08 11:49:43 -07003803 for (DispatchEntry* dispatchEntry = outboundQueue.tailSentinel.prev;
3804 dispatchEntry != & outboundQueue.headSentinel; dispatchEntry = dispatchEntry->prev) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003805 if (dispatchEntry->eventEntry == eventEntry) {
3806 return dispatchEntry;
3807 }
3808 }
3809 return NULL;
3810}
3811
Jeff Brownb88102f2010-09-08 11:49:43 -07003812
Jeff Brown9c3cda02010-06-15 01:31:58 -07003813// --- InputDispatcher::CommandEntry ---
3814
Jeff Brownb88102f2010-09-08 11:49:43 -07003815InputDispatcher::CommandEntry::CommandEntry() :
3816 keyEntry(NULL) {
Jeff Brown9c3cda02010-06-15 01:31:58 -07003817}
3818
3819InputDispatcher::CommandEntry::~CommandEntry() {
3820}
3821
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003822
Jeff Brown01ce2e92010-09-26 22:20:12 -07003823// --- InputDispatcher::TouchState ---
3824
3825InputDispatcher::TouchState::TouchState() :
Jeff Brown58a2da82011-01-25 16:02:22 -08003826 down(false), split(false), deviceId(-1), source(0) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07003827}
3828
3829InputDispatcher::TouchState::~TouchState() {
3830}
3831
3832void InputDispatcher::TouchState::reset() {
3833 down = false;
3834 split = false;
Jeff Brown95712852011-01-04 19:41:59 -08003835 deviceId = -1;
Jeff Brown58a2da82011-01-25 16:02:22 -08003836 source = 0;
Jeff Brown01ce2e92010-09-26 22:20:12 -07003837 windows.clear();
3838}
3839
3840void InputDispatcher::TouchState::copyFrom(const TouchState& other) {
3841 down = other.down;
3842 split = other.split;
Jeff Brown95712852011-01-04 19:41:59 -08003843 deviceId = other.deviceId;
Jeff Brown58a2da82011-01-25 16:02:22 -08003844 source = other.source;
Jeff Brown01ce2e92010-09-26 22:20:12 -07003845 windows.clear();
3846 windows.appendVector(other.windows);
3847}
3848
3849void InputDispatcher::TouchState::addOrUpdateWindow(const InputWindow* window,
3850 int32_t targetFlags, BitSet32 pointerIds) {
3851 if (targetFlags & InputTarget::FLAG_SPLIT) {
3852 split = true;
3853 }
3854
3855 for (size_t i = 0; i < windows.size(); i++) {
3856 TouchedWindow& touchedWindow = windows.editItemAt(i);
3857 if (touchedWindow.window == window) {
3858 touchedWindow.targetFlags |= targetFlags;
3859 touchedWindow.pointerIds.value |= pointerIds.value;
3860 return;
3861 }
3862 }
3863
3864 windows.push();
3865
3866 TouchedWindow& touchedWindow = windows.editTop();
3867 touchedWindow.window = window;
3868 touchedWindow.targetFlags = targetFlags;
3869 touchedWindow.pointerIds = pointerIds;
3870 touchedWindow.channel = window->inputChannel;
3871}
3872
3873void InputDispatcher::TouchState::removeOutsideTouchWindows() {
3874 for (size_t i = 0 ; i < windows.size(); ) {
3875 if (windows[i].targetFlags & InputTarget::FLAG_OUTSIDE) {
3876 windows.removeAt(i);
3877 } else {
3878 i += 1;
3879 }
3880 }
3881}
3882
3883const InputWindow* InputDispatcher::TouchState::getFirstForegroundWindow() {
3884 for (size_t i = 0; i < windows.size(); i++) {
3885 if (windows[i].targetFlags & InputTarget::FLAG_FOREGROUND) {
3886 return windows[i].window;
3887 }
3888 }
3889 return NULL;
3890}
3891
3892
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003893// --- InputDispatcherThread ---
3894
3895InputDispatcherThread::InputDispatcherThread(const sp<InputDispatcherInterface>& dispatcher) :
3896 Thread(/*canCallJava*/ true), mDispatcher(dispatcher) {
3897}
3898
3899InputDispatcherThread::~InputDispatcherThread() {
3900}
3901
3902bool InputDispatcherThread::threadLoop() {
3903 mDispatcher->dispatchOnce();
3904 return true;
3905}
3906
3907} // namespace android