blob: f8a5cfb7d02a43e033518e8828a50c9e1666204b [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
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400159static void scalePointerCoords(const PointerCoords* inCoords, size_t count, float scaleFactor,
160 PointerCoords* outCoords) {
161 for (size_t i = 0; i < count; i++) {
162 outCoords[i] = inCoords[i];
163 outCoords[i].scale(scaleFactor);
164 }
165}
166
Jeff Brownfbf09772011-01-16 14:06:57 -0800167static void dumpRegion(String8& dump, const SkRegion& region) {
168 if (region.isEmpty()) {
169 dump.append("<empty>");
170 return;
171 }
172
173 bool first = true;
174 for (SkRegion::Iterator it(region); !it.done(); it.next()) {
175 if (first) {
176 first = false;
177 } else {
178 dump.append("|");
179 }
180 const SkIRect& rect = it.rect();
181 dump.appendFormat("[%d,%d][%d,%d]", rect.fLeft, rect.fTop, rect.fRight, rect.fBottom);
182 }
183}
184
Jeff Brownb88102f2010-09-08 11:49:43 -0700185
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700186// --- InputDispatcher ---
187
Jeff Brown9c3cda02010-06-15 01:31:58 -0700188InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy) :
Jeff Brownb88102f2010-09-08 11:49:43 -0700189 mPolicy(policy),
Jeff Brown928e0542011-01-10 11:17:36 -0800190 mPendingEvent(NULL), mAppSwitchSawKeyDown(false), mAppSwitchDueTime(LONG_LONG_MAX),
191 mNextUnblockedEvent(NULL),
Jeff Brownb88102f2010-09-08 11:49:43 -0700192 mDispatchEnabled(true), mDispatchFrozen(false),
Jeff Brown01ce2e92010-09-26 22:20:12 -0700193 mFocusedWindow(NULL),
Jeff Brownb88102f2010-09-08 11:49:43 -0700194 mFocusedApplication(NULL),
195 mCurrentInputTargetsValid(false),
196 mInputTargetWaitCause(INPUT_TARGET_WAIT_CAUSE_NONE) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -0700197 mLooper = new Looper(false);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700198
Jeff Brownb88102f2010-09-08 11:49:43 -0700199 mInboundQueue.headSentinel.refCount = -1;
200 mInboundQueue.headSentinel.type = EventEntry::TYPE_SENTINEL;
201 mInboundQueue.headSentinel.eventTime = LONG_LONG_MIN;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700202
Jeff Brownb88102f2010-09-08 11:49:43 -0700203 mInboundQueue.tailSentinel.refCount = -1;
204 mInboundQueue.tailSentinel.type = EventEntry::TYPE_SENTINEL;
205 mInboundQueue.tailSentinel.eventTime = LONG_LONG_MAX;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700206
207 mKeyRepeatState.lastKeyEntry = NULL;
Jeff Brown9c3cda02010-06-15 01:31:58 -0700208
Jeff Brownae9fc032010-08-18 15:51:08 -0700209 int32_t maxEventsPerSecond = policy->getMaxEventsPerSecond();
210 mThrottleState.minTimeBetweenEvents = 1000000000LL / maxEventsPerSecond;
211 mThrottleState.lastDeviceId = -1;
212
213#if DEBUG_THROTTLING
214 mThrottleState.originalSampleCount = 0;
215 LOGD("Throttling - Max events per second = %d", maxEventsPerSecond);
216#endif
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700217}
218
219InputDispatcher::~InputDispatcher() {
Jeff Brownb88102f2010-09-08 11:49:43 -0700220 { // acquire lock
221 AutoMutex _l(mLock);
222
223 resetKeyRepeatLocked();
Jeff Brown54a18252010-09-16 14:07:33 -0700224 releasePendingEventLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -0700225 drainInboundQueueLocked();
226 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700227
228 while (mConnectionsByReceiveFd.size() != 0) {
229 unregisterInputChannel(mConnectionsByReceiveFd.valueAt(0)->inputChannel);
230 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700231}
232
233void InputDispatcher::dispatchOnce() {
Jeff Brown9c3cda02010-06-15 01:31:58 -0700234 nsecs_t keyRepeatTimeout = mPolicy->getKeyRepeatTimeout();
Jeff Brownb21fb102010-09-07 10:44:57 -0700235 nsecs_t keyRepeatDelay = mPolicy->getKeyRepeatDelay();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700236
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700237 nsecs_t nextWakeupTime = LONG_LONG_MAX;
238 { // acquire lock
239 AutoMutex _l(mLock);
Jeff Brownb88102f2010-09-08 11:49:43 -0700240 dispatchOnceInnerLocked(keyRepeatTimeout, keyRepeatDelay, & nextWakeupTime);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700241
Jeff Brownb88102f2010-09-08 11:49:43 -0700242 if (runCommandsLockedInterruptible()) {
243 nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700244 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700245 } // release lock
246
Jeff Brownb88102f2010-09-08 11:49:43 -0700247 // Wait for callback or timeout or wake. (make sure we round up, not down)
248 nsecs_t currentTime = now();
249 int32_t timeoutMillis;
250 if (nextWakeupTime > currentTime) {
251 uint64_t timeout = uint64_t(nextWakeupTime - currentTime);
252 timeout = (timeout + 999999LL) / 1000000LL;
253 timeoutMillis = timeout > INT_MAX ? -1 : int32_t(timeout);
254 } else {
255 timeoutMillis = 0;
256 }
257
Jeff Brown4fe6c3e2010-09-13 23:17:30 -0700258 mLooper->pollOnce(timeoutMillis);
Jeff Brownb88102f2010-09-08 11:49:43 -0700259}
260
261void InputDispatcher::dispatchOnceInnerLocked(nsecs_t keyRepeatTimeout,
262 nsecs_t keyRepeatDelay, nsecs_t* nextWakeupTime) {
263 nsecs_t currentTime = now();
264
265 // Reset the key repeat timer whenever we disallow key events, even if the next event
266 // is not a key. This is to ensure that we abort a key repeat if the device is just coming
267 // out of sleep.
268 if (keyRepeatTimeout < 0) {
269 resetKeyRepeatLocked();
270 }
271
Jeff Brownb88102f2010-09-08 11:49:43 -0700272 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
273 if (mDispatchFrozen) {
274#if DEBUG_FOCUS
275 LOGD("Dispatch frozen. Waiting some more.");
276#endif
277 return;
278 }
279
280 // Optimize latency of app switches.
281 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
282 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
283 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
284 if (mAppSwitchDueTime < *nextWakeupTime) {
285 *nextWakeupTime = mAppSwitchDueTime;
286 }
287
Jeff Brownb88102f2010-09-08 11:49:43 -0700288 // Ready to start a new event.
289 // If we don't already have a pending event, go grab one.
290 if (! mPendingEvent) {
291 if (mInboundQueue.isEmpty()) {
292 if (isAppSwitchDue) {
293 // The inbound queue is empty so the app switch key we were waiting
294 // for will never arrive. Stop waiting for it.
295 resetPendingAppSwitchLocked(false);
296 isAppSwitchDue = false;
297 }
298
299 // Synthesize a key repeat if appropriate.
300 if (mKeyRepeatState.lastKeyEntry) {
301 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
302 mPendingEvent = synthesizeKeyRepeatLocked(currentTime, keyRepeatDelay);
303 } else {
304 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
305 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
306 }
307 }
308 }
309 if (! mPendingEvent) {
310 return;
311 }
312 } else {
313 // Inbound queue has at least one entry.
314 EventEntry* entry = mInboundQueue.headSentinel.next;
315
316 // Throttle the entry if it is a move event and there are no
317 // other events behind it in the queue. Due to movement batching, additional
318 // samples may be appended to this event by the time the throttling timeout
319 // expires.
320 // TODO Make this smarter and consider throttling per device independently.
Jeff Brownb6997262010-10-08 22:31:17 -0700321 if (entry->type == EventEntry::TYPE_MOTION
322 && !isAppSwitchDue
323 && mDispatchEnabled
324 && (entry->policyFlags & POLICY_FLAG_PASS_TO_USER)
325 && !entry->isInjected()) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700326 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
327 int32_t deviceId = motionEntry->deviceId;
328 uint32_t source = motionEntry->source;
329 if (! isAppSwitchDue
330 && motionEntry->next == & mInboundQueue.tailSentinel // exactly one event
Jeff Browncc0c1592011-02-19 05:07:28 -0800331 && (motionEntry->action == AMOTION_EVENT_ACTION_MOVE
332 || motionEntry->action == AMOTION_EVENT_ACTION_HOVER_MOVE)
Jeff Brownb88102f2010-09-08 11:49:43 -0700333 && deviceId == mThrottleState.lastDeviceId
334 && source == mThrottleState.lastSource) {
335 nsecs_t nextTime = mThrottleState.lastEventTime
336 + mThrottleState.minTimeBetweenEvents;
337 if (currentTime < nextTime) {
338 // Throttle it!
339#if DEBUG_THROTTLING
340 LOGD("Throttling - Delaying motion event for "
Jeff Brown90655042010-12-02 13:50:46 -0800341 "device %d, source 0x%08x by up to %0.3fms.",
Jeff Brownb88102f2010-09-08 11:49:43 -0700342 deviceId, source, (nextTime - currentTime) * 0.000001);
343#endif
344 if (nextTime < *nextWakeupTime) {
345 *nextWakeupTime = nextTime;
346 }
347 if (mThrottleState.originalSampleCount == 0) {
348 mThrottleState.originalSampleCount =
349 motionEntry->countSamples();
350 }
351 return;
352 }
353 }
354
355#if DEBUG_THROTTLING
356 if (mThrottleState.originalSampleCount != 0) {
357 uint32_t count = motionEntry->countSamples();
358 LOGD("Throttling - Motion event sample count grew by %d from %d to %d.",
359 count - mThrottleState.originalSampleCount,
360 mThrottleState.originalSampleCount, count);
361 mThrottleState.originalSampleCount = 0;
362 }
363#endif
364
makarand.karvekarf634ded2011-03-02 15:41:03 -0600365 mThrottleState.lastEventTime = currentTime;
Jeff Brownb88102f2010-09-08 11:49:43 -0700366 mThrottleState.lastDeviceId = deviceId;
367 mThrottleState.lastSource = source;
368 }
369
370 mInboundQueue.dequeue(entry);
371 mPendingEvent = entry;
372 }
Jeff Browne2fe69e2010-10-18 13:21:23 -0700373
374 // Poke user activity for this event.
375 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
376 pokeUserActivityLocked(mPendingEvent);
377 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700378 }
379
380 // Now we have an event to dispatch.
Jeff Brown928e0542011-01-10 11:17:36 -0800381 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Jeff Brownb88102f2010-09-08 11:49:43 -0700382 assert(mPendingEvent != NULL);
Jeff Brown54a18252010-09-16 14:07:33 -0700383 bool done = false;
Jeff Brownb6997262010-10-08 22:31:17 -0700384 DropReason dropReason = DROP_REASON_NOT_DROPPED;
385 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
386 dropReason = DROP_REASON_POLICY;
387 } else if (!mDispatchEnabled) {
388 dropReason = DROP_REASON_DISABLED;
389 }
Jeff Brown928e0542011-01-10 11:17:36 -0800390
391 if (mNextUnblockedEvent == mPendingEvent) {
392 mNextUnblockedEvent = NULL;
393 }
394
Jeff Brownb88102f2010-09-08 11:49:43 -0700395 switch (mPendingEvent->type) {
396 case EventEntry::TYPE_CONFIGURATION_CHANGED: {
397 ConfigurationChangedEntry* typedEntry =
398 static_cast<ConfigurationChangedEntry*>(mPendingEvent);
Jeff Brown54a18252010-09-16 14:07:33 -0700399 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Jeff Brownb6997262010-10-08 22:31:17 -0700400 dropReason = DROP_REASON_NOT_DROPPED; // configuration changes are never dropped
Jeff Brownb88102f2010-09-08 11:49:43 -0700401 break;
402 }
403
404 case EventEntry::TYPE_KEY: {
405 KeyEntry* typedEntry = static_cast<KeyEntry*>(mPendingEvent);
Jeff Brownb6997262010-10-08 22:31:17 -0700406 if (isAppSwitchDue) {
407 if (isAppSwitchKeyEventLocked(typedEntry)) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700408 resetPendingAppSwitchLocked(true);
Jeff Brownb6997262010-10-08 22:31:17 -0700409 isAppSwitchDue = false;
410 } else if (dropReason == DROP_REASON_NOT_DROPPED) {
411 dropReason = DROP_REASON_APP_SWITCH;
Jeff Brownb88102f2010-09-08 11:49:43 -0700412 }
413 }
Jeff Brown928e0542011-01-10 11:17:36 -0800414 if (dropReason == DROP_REASON_NOT_DROPPED
415 && isStaleEventLocked(currentTime, typedEntry)) {
416 dropReason = DROP_REASON_STALE;
417 }
418 if (dropReason == DROP_REASON_NOT_DROPPED && mNextUnblockedEvent) {
419 dropReason = DROP_REASON_BLOCKED;
420 }
Jeff Brownb6997262010-10-08 22:31:17 -0700421 done = dispatchKeyLocked(currentTime, typedEntry, keyRepeatTimeout,
Jeff Browne20c9e02010-10-11 14:20:19 -0700422 &dropReason, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700423 break;
424 }
425
426 case EventEntry::TYPE_MOTION: {
427 MotionEntry* typedEntry = static_cast<MotionEntry*>(mPendingEvent);
Jeff Brownb6997262010-10-08 22:31:17 -0700428 if (dropReason == DROP_REASON_NOT_DROPPED && isAppSwitchDue) {
429 dropReason = DROP_REASON_APP_SWITCH;
Jeff Brownb88102f2010-09-08 11:49:43 -0700430 }
Jeff Brown928e0542011-01-10 11:17:36 -0800431 if (dropReason == DROP_REASON_NOT_DROPPED
432 && isStaleEventLocked(currentTime, typedEntry)) {
433 dropReason = DROP_REASON_STALE;
434 }
435 if (dropReason == DROP_REASON_NOT_DROPPED && mNextUnblockedEvent) {
436 dropReason = DROP_REASON_BLOCKED;
437 }
Jeff Brownb6997262010-10-08 22:31:17 -0700438 done = dispatchMotionLocked(currentTime, typedEntry,
Jeff Browne20c9e02010-10-11 14:20:19 -0700439 &dropReason, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700440 break;
441 }
442
443 default:
444 assert(false);
Jeff Brownb88102f2010-09-08 11:49:43 -0700445 break;
446 }
447
Jeff Brown54a18252010-09-16 14:07:33 -0700448 if (done) {
Jeff Brownb6997262010-10-08 22:31:17 -0700449 if (dropReason != DROP_REASON_NOT_DROPPED) {
450 dropInboundEventLocked(mPendingEvent, dropReason);
451 }
452
Jeff Brown54a18252010-09-16 14:07:33 -0700453 releasePendingEventLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -0700454 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
455 }
456}
457
458bool InputDispatcher::enqueueInboundEventLocked(EventEntry* entry) {
459 bool needWake = mInboundQueue.isEmpty();
460 mInboundQueue.enqueueAtTail(entry);
461
462 switch (entry->type) {
Jeff Brownb6997262010-10-08 22:31:17 -0700463 case EventEntry::TYPE_KEY: {
Jeff Brown928e0542011-01-10 11:17:36 -0800464 // Optimize app switch latency.
465 // If the application takes too long to catch up then we drop all events preceding
466 // the app switch key.
Jeff Brownb6997262010-10-08 22:31:17 -0700467 KeyEntry* keyEntry = static_cast<KeyEntry*>(entry);
468 if (isAppSwitchKeyEventLocked(keyEntry)) {
469 if (keyEntry->action == AKEY_EVENT_ACTION_DOWN) {
470 mAppSwitchSawKeyDown = true;
471 } else if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
472 if (mAppSwitchSawKeyDown) {
473#if DEBUG_APP_SWITCH
474 LOGD("App switch is pending!");
475#endif
476 mAppSwitchDueTime = keyEntry->eventTime + APP_SWITCH_TIMEOUT;
477 mAppSwitchSawKeyDown = false;
478 needWake = true;
479 }
480 }
481 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700482 break;
483 }
Jeff Brown928e0542011-01-10 11:17:36 -0800484
485 case EventEntry::TYPE_MOTION: {
486 // Optimize case where the current application is unresponsive and the user
487 // decides to touch a window in a different application.
488 // If the application takes too long to catch up then we drop all events preceding
489 // the touch into the other window.
490 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
Jeff Brown33bbfd22011-02-24 20:55:35 -0800491 if (motionEntry->action == AMOTION_EVENT_ACTION_DOWN
Jeff Brown928e0542011-01-10 11:17:36 -0800492 && (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER)
493 && mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY
494 && mInputTargetWaitApplication != NULL) {
Jeff Brown91c69ab2011-02-14 17:03:18 -0800495 int32_t x = int32_t(motionEntry->firstSample.pointerCoords[0].
Jeff Brownebbd5d12011-02-17 13:01:34 -0800496 getAxisValue(AMOTION_EVENT_AXIS_X));
Jeff Brown91c69ab2011-02-14 17:03:18 -0800497 int32_t y = int32_t(motionEntry->firstSample.pointerCoords[0].
Jeff Brownebbd5d12011-02-17 13:01:34 -0800498 getAxisValue(AMOTION_EVENT_AXIS_Y));
Jeff Brown928e0542011-01-10 11:17:36 -0800499 const InputWindow* touchedWindow = findTouchedWindowAtLocked(x, y);
500 if (touchedWindow
501 && touchedWindow->inputWindowHandle != NULL
502 && touchedWindow->inputWindowHandle->getInputApplicationHandle()
503 != mInputTargetWaitApplication) {
504 // User touched a different application than the one we are waiting on.
505 // Flag the event, and start pruning the input queue.
506 mNextUnblockedEvent = motionEntry;
507 needWake = true;
508 }
509 }
510 break;
511 }
Jeff Brownb6997262010-10-08 22:31:17 -0700512 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700513
514 return needWake;
515}
516
Jeff Brown928e0542011-01-10 11:17:36 -0800517const InputWindow* InputDispatcher::findTouchedWindowAtLocked(int32_t x, int32_t y) {
518 // Traverse windows from front to back to find touched window.
519 size_t numWindows = mWindows.size();
520 for (size_t i = 0; i < numWindows; i++) {
521 const InputWindow* window = & mWindows.editItemAt(i);
522 int32_t flags = window->layoutParamsFlags;
523
524 if (window->visible) {
525 if (!(flags & InputWindow::FLAG_NOT_TOUCHABLE)) {
526 bool isTouchModal = (flags & (InputWindow::FLAG_NOT_FOCUSABLE
527 | InputWindow::FLAG_NOT_TOUCH_MODAL)) == 0;
Jeff Brownfbf09772011-01-16 14:06:57 -0800528 if (isTouchModal || window->touchableRegionContainsPoint(x, y)) {
Jeff Brown928e0542011-01-10 11:17:36 -0800529 // Found window.
530 return window;
531 }
532 }
533 }
534
535 if (flags & InputWindow::FLAG_SYSTEM_ERROR) {
536 // Error window is on top but not visible, so touch is dropped.
537 return NULL;
538 }
539 }
540 return NULL;
541}
542
Jeff Brownb6997262010-10-08 22:31:17 -0700543void InputDispatcher::dropInboundEventLocked(EventEntry* entry, DropReason dropReason) {
544 const char* reason;
545 switch (dropReason) {
546 case DROP_REASON_POLICY:
Jeff Browne20c9e02010-10-11 14:20:19 -0700547#if DEBUG_INBOUND_EVENT_DETAILS
Jeff Brown3122e442010-10-11 23:32:49 -0700548 LOGD("Dropped event because policy consumed it.");
Jeff Browne20c9e02010-10-11 14:20:19 -0700549#endif
Jeff Brown3122e442010-10-11 23:32:49 -0700550 reason = "inbound event was dropped because the policy consumed it";
Jeff Brownb6997262010-10-08 22:31:17 -0700551 break;
552 case DROP_REASON_DISABLED:
553 LOGI("Dropped event because input dispatch is disabled.");
554 reason = "inbound event was dropped because input dispatch is disabled";
555 break;
556 case DROP_REASON_APP_SWITCH:
557 LOGI("Dropped event because of pending overdue app switch.");
558 reason = "inbound event was dropped because of pending overdue app switch";
559 break;
Jeff Brown928e0542011-01-10 11:17:36 -0800560 case DROP_REASON_BLOCKED:
561 LOGI("Dropped event because the current application is not responding and the user "
562 "has started interating with a different application.");
563 reason = "inbound event was dropped because the current application is not responding "
564 "and the user has started interating with a different application";
565 break;
566 case DROP_REASON_STALE:
567 LOGI("Dropped event because it is stale.");
568 reason = "inbound event was dropped because it is stale";
569 break;
Jeff Brownb6997262010-10-08 22:31:17 -0700570 default:
571 assert(false);
572 return;
573 }
574
575 switch (entry->type) {
576 case EventEntry::TYPE_KEY:
577 synthesizeCancelationEventsForAllConnectionsLocked(
578 InputState::CANCEL_NON_POINTER_EVENTS, reason);
579 break;
580 case EventEntry::TYPE_MOTION: {
581 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
582 if (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) {
583 synthesizeCancelationEventsForAllConnectionsLocked(
584 InputState::CANCEL_POINTER_EVENTS, reason);
585 } else {
586 synthesizeCancelationEventsForAllConnectionsLocked(
587 InputState::CANCEL_NON_POINTER_EVENTS, reason);
588 }
589 break;
590 }
591 }
592}
593
594bool InputDispatcher::isAppSwitchKeyCode(int32_t keyCode) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700595 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL;
596}
597
Jeff Brownb6997262010-10-08 22:31:17 -0700598bool InputDispatcher::isAppSwitchKeyEventLocked(KeyEntry* keyEntry) {
599 return ! (keyEntry->flags & AKEY_EVENT_FLAG_CANCELED)
600 && isAppSwitchKeyCode(keyEntry->keyCode)
Jeff Browne20c9e02010-10-11 14:20:19 -0700601 && (keyEntry->policyFlags & POLICY_FLAG_TRUSTED)
Jeff Brownb6997262010-10-08 22:31:17 -0700602 && (keyEntry->policyFlags & POLICY_FLAG_PASS_TO_USER);
603}
604
Jeff Brownb88102f2010-09-08 11:49:43 -0700605bool InputDispatcher::isAppSwitchPendingLocked() {
606 return mAppSwitchDueTime != LONG_LONG_MAX;
607}
608
Jeff Brownb88102f2010-09-08 11:49:43 -0700609void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
610 mAppSwitchDueTime = LONG_LONG_MAX;
611
612#if DEBUG_APP_SWITCH
613 if (handled) {
614 LOGD("App switch has arrived.");
615 } else {
616 LOGD("App switch was abandoned.");
617 }
618#endif
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700619}
620
Jeff Brown928e0542011-01-10 11:17:36 -0800621bool InputDispatcher::isStaleEventLocked(nsecs_t currentTime, EventEntry* entry) {
622 return currentTime - entry->eventTime >= STALE_EVENT_TIMEOUT;
623}
624
Jeff Brown9c3cda02010-06-15 01:31:58 -0700625bool InputDispatcher::runCommandsLockedInterruptible() {
626 if (mCommandQueue.isEmpty()) {
627 return false;
628 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700629
Jeff Brown9c3cda02010-06-15 01:31:58 -0700630 do {
631 CommandEntry* commandEntry = mCommandQueue.dequeueAtHead();
632
633 Command command = commandEntry->command;
634 (this->*command)(commandEntry); // commands are implicitly 'LockedInterruptible'
635
Jeff Brown7fbdc842010-06-17 20:52:56 -0700636 commandEntry->connection.clear();
Jeff Brown9c3cda02010-06-15 01:31:58 -0700637 mAllocator.releaseCommandEntry(commandEntry);
638 } while (! mCommandQueue.isEmpty());
639 return true;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700640}
641
Jeff Brown9c3cda02010-06-15 01:31:58 -0700642InputDispatcher::CommandEntry* InputDispatcher::postCommandLocked(Command command) {
643 CommandEntry* commandEntry = mAllocator.obtainCommandEntry(command);
644 mCommandQueue.enqueueAtTail(commandEntry);
645 return commandEntry;
646}
647
Jeff Brownb88102f2010-09-08 11:49:43 -0700648void InputDispatcher::drainInboundQueueLocked() {
649 while (! mInboundQueue.isEmpty()) {
650 EventEntry* entry = mInboundQueue.dequeueAtHead();
Jeff Brown54a18252010-09-16 14:07:33 -0700651 releaseInboundEventLocked(entry);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700652 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700653}
654
Jeff Brown54a18252010-09-16 14:07:33 -0700655void InputDispatcher::releasePendingEventLocked() {
Jeff Brownb88102f2010-09-08 11:49:43 -0700656 if (mPendingEvent) {
Jeff Brown54a18252010-09-16 14:07:33 -0700657 releaseInboundEventLocked(mPendingEvent);
Jeff Brownb88102f2010-09-08 11:49:43 -0700658 mPendingEvent = NULL;
659 }
660}
661
Jeff Brown54a18252010-09-16 14:07:33 -0700662void InputDispatcher::releaseInboundEventLocked(EventEntry* entry) {
Jeff Brown01ce2e92010-09-26 22:20:12 -0700663 InjectionState* injectionState = entry->injectionState;
664 if (injectionState && injectionState->injectionResult == INPUT_EVENT_INJECTION_PENDING) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700665#if DEBUG_DISPATCH_CYCLE
Jeff Brown01ce2e92010-09-26 22:20:12 -0700666 LOGD("Injected inbound event was dropped.");
Jeff Brownb88102f2010-09-08 11:49:43 -0700667#endif
668 setInjectionResultLocked(entry, INPUT_EVENT_INJECTION_FAILED);
669 }
670 mAllocator.releaseEventEntry(entry);
671}
672
Jeff Brownb88102f2010-09-08 11:49:43 -0700673void InputDispatcher::resetKeyRepeatLocked() {
674 if (mKeyRepeatState.lastKeyEntry) {
675 mAllocator.releaseKeyEntry(mKeyRepeatState.lastKeyEntry);
676 mKeyRepeatState.lastKeyEntry = NULL;
677 }
678}
679
680InputDispatcher::KeyEntry* InputDispatcher::synthesizeKeyRepeatLocked(
Jeff Brownb21fb102010-09-07 10:44:57 -0700681 nsecs_t currentTime, nsecs_t keyRepeatDelay) {
Jeff Brown349703e2010-06-22 01:27:15 -0700682 KeyEntry* entry = mKeyRepeatState.lastKeyEntry;
683
Jeff Brown349703e2010-06-22 01:27:15 -0700684 // Reuse the repeated key entry if it is otherwise unreferenced.
Jeff Browne20c9e02010-10-11 14:20:19 -0700685 uint32_t policyFlags = (entry->policyFlags & POLICY_FLAG_RAW_MASK)
686 | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700687 if (entry->refCount == 1) {
Jeff Brown01ce2e92010-09-26 22:20:12 -0700688 mAllocator.recycleKeyEntry(entry);
Jeff Brown7fbdc842010-06-17 20:52:56 -0700689 entry->eventTime = currentTime;
Jeff Brown7fbdc842010-06-17 20:52:56 -0700690 entry->policyFlags = policyFlags;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700691 entry->repeatCount += 1;
692 } else {
Jeff Brown7fbdc842010-06-17 20:52:56 -0700693 KeyEntry* newEntry = mAllocator.obtainKeyEntry(currentTime,
Jeff Brownc5ed5912010-07-14 18:48:53 -0700694 entry->deviceId, entry->source, policyFlags,
Jeff Brown7fbdc842010-06-17 20:52:56 -0700695 entry->action, entry->flags, entry->keyCode, entry->scanCode,
Jeff Brown00fa7bd2010-07-02 15:37:36 -0700696 entry->metaState, entry->repeatCount + 1, entry->downTime);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700697
698 mKeyRepeatState.lastKeyEntry = newEntry;
699 mAllocator.releaseKeyEntry(entry);
700
701 entry = newEntry;
702 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700703 entry->syntheticRepeat = true;
704
705 // Increment reference count since we keep a reference to the event in
706 // mKeyRepeatState.lastKeyEntry in addition to the one we return.
707 entry->refCount += 1;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700708
Jeff Brownb21fb102010-09-07 10:44:57 -0700709 mKeyRepeatState.nextRepeatTime = currentTime + keyRepeatDelay;
Jeff Brownb88102f2010-09-08 11:49:43 -0700710 return entry;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700711}
712
Jeff Brownb88102f2010-09-08 11:49:43 -0700713bool InputDispatcher::dispatchConfigurationChangedLocked(
714 nsecs_t currentTime, ConfigurationChangedEntry* entry) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700715#if DEBUG_OUTBOUND_EVENT_DETAILS
Jeff Brownb88102f2010-09-08 11:49:43 -0700716 LOGD("dispatchConfigurationChanged - eventTime=%lld", entry->eventTime);
717#endif
718
719 // Reset key repeating in case a keyboard device was added or removed or something.
720 resetKeyRepeatLocked();
721
722 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
723 CommandEntry* commandEntry = postCommandLocked(
724 & InputDispatcher::doNotifyConfigurationChangedInterruptible);
725 commandEntry->eventTime = entry->eventTime;
726 return true;
727}
728
729bool InputDispatcher::dispatchKeyLocked(
730 nsecs_t currentTime, KeyEntry* entry, nsecs_t keyRepeatTimeout,
Jeff Browne20c9e02010-10-11 14:20:19 -0700731 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Jeff Browne46a0a42010-11-02 17:58:22 -0700732 // Preprocessing.
733 if (! entry->dispatchInProgress) {
734 if (entry->repeatCount == 0
735 && entry->action == AKEY_EVENT_ACTION_DOWN
736 && (entry->policyFlags & POLICY_FLAG_TRUSTED)
737 && !entry->isInjected()) {
738 if (mKeyRepeatState.lastKeyEntry
739 && mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode) {
740 // We have seen two identical key downs in a row which indicates that the device
741 // driver is automatically generating key repeats itself. We take note of the
742 // repeat here, but we disable our own next key repeat timer since it is clear that
743 // we will not need to synthesize key repeats ourselves.
744 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
745 resetKeyRepeatLocked();
746 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
747 } else {
748 // Not a repeat. Save key down state in case we do see a repeat later.
749 resetKeyRepeatLocked();
750 mKeyRepeatState.nextRepeatTime = entry->eventTime + keyRepeatTimeout;
751 }
752 mKeyRepeatState.lastKeyEntry = entry;
753 entry->refCount += 1;
754 } else if (! entry->syntheticRepeat) {
755 resetKeyRepeatLocked();
756 }
757
Jeff Browne2e01262011-03-02 20:34:30 -0800758 if (entry->repeatCount == 1) {
759 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
760 } else {
761 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
762 }
763
Jeff Browne46a0a42010-11-02 17:58:22 -0700764 entry->dispatchInProgress = true;
765 resetTargetsLocked();
766
767 logOutboundKeyDetailsLocked("dispatchKey - ", entry);
768 }
769
Jeff Brown54a18252010-09-16 14:07:33 -0700770 // Give the policy a chance to intercept the key.
771 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
Jeff Browne20c9e02010-10-11 14:20:19 -0700772 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Jeff Brown54a18252010-09-16 14:07:33 -0700773 CommandEntry* commandEntry = postCommandLocked(
774 & InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
Jeff Browne20c9e02010-10-11 14:20:19 -0700775 if (mFocusedWindow) {
Jeff Brown928e0542011-01-10 11:17:36 -0800776 commandEntry->inputWindowHandle = mFocusedWindow->inputWindowHandle;
Jeff Brown54a18252010-09-16 14:07:33 -0700777 }
778 commandEntry->keyEntry = entry;
779 entry->refCount += 1;
780 return false; // wait for the command to run
781 } else {
782 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
783 }
784 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Jeff Browne20c9e02010-10-11 14:20:19 -0700785 if (*dropReason == DROP_REASON_NOT_DROPPED) {
786 *dropReason = DROP_REASON_POLICY;
787 }
Jeff Brown54a18252010-09-16 14:07:33 -0700788 }
789
790 // Clean up if dropping the event.
Jeff Browne20c9e02010-10-11 14:20:19 -0700791 if (*dropReason != DROP_REASON_NOT_DROPPED) {
Jeff Brown54a18252010-09-16 14:07:33 -0700792 resetTargetsLocked();
Jeff Brown3122e442010-10-11 23:32:49 -0700793 setInjectionResultLocked(entry, *dropReason == DROP_REASON_POLICY
794 ? INPUT_EVENT_INJECTION_SUCCEEDED : INPUT_EVENT_INJECTION_FAILED);
Jeff Brown54a18252010-09-16 14:07:33 -0700795 return true;
796 }
797
Jeff Brownb88102f2010-09-08 11:49:43 -0700798 // Identify targets.
799 if (! mCurrentInputTargetsValid) {
Jeff Brown01ce2e92010-09-26 22:20:12 -0700800 int32_t injectionResult = findFocusedWindowTargetsLocked(currentTime,
801 entry, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700802 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
803 return false;
804 }
805
806 setInjectionResultLocked(entry, injectionResult);
807 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
808 return true;
809 }
810
811 addMonitoringTargetsLocked();
Jeff Brown01ce2e92010-09-26 22:20:12 -0700812 commitTargetsLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -0700813 }
814
815 // Dispatch the key.
816 dispatchEventToCurrentInputTargetsLocked(currentTime, entry, false);
Jeff Brownb88102f2010-09-08 11:49:43 -0700817 return true;
818}
819
820void InputDispatcher::logOutboundKeyDetailsLocked(const char* prefix, const KeyEntry* entry) {
821#if DEBUG_OUTBOUND_EVENT_DETAILS
Jeff Brown90655042010-12-02 13:50:46 -0800822 LOGD("%seventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, "
Jeff Brownb88102f2010-09-08 11:49:43 -0700823 "action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, "
Jeff Browne46a0a42010-11-02 17:58:22 -0700824 "repeatCount=%d, downTime=%lld",
Jeff Brownb88102f2010-09-08 11:49:43 -0700825 prefix,
826 entry->eventTime, entry->deviceId, entry->source, entry->policyFlags,
827 entry->action, entry->flags, entry->keyCode, entry->scanCode, entry->metaState,
Jeff Browne46a0a42010-11-02 17:58:22 -0700828 entry->repeatCount, entry->downTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700829#endif
830}
831
832bool InputDispatcher::dispatchMotionLocked(
Jeff Browne20c9e02010-10-11 14:20:19 -0700833 nsecs_t currentTime, MotionEntry* entry, DropReason* dropReason, nsecs_t* nextWakeupTime) {
Jeff Browne46a0a42010-11-02 17:58:22 -0700834 // Preprocessing.
835 if (! entry->dispatchInProgress) {
836 entry->dispatchInProgress = true;
837 resetTargetsLocked();
838
839 logOutboundMotionDetailsLocked("dispatchMotion - ", entry);
840 }
841
Jeff Brown54a18252010-09-16 14:07:33 -0700842 // Clean up if dropping the event.
Jeff Browne20c9e02010-10-11 14:20:19 -0700843 if (*dropReason != DROP_REASON_NOT_DROPPED) {
Jeff Brown54a18252010-09-16 14:07:33 -0700844 resetTargetsLocked();
Jeff Brown3122e442010-10-11 23:32:49 -0700845 setInjectionResultLocked(entry, *dropReason == DROP_REASON_POLICY
846 ? INPUT_EVENT_INJECTION_SUCCEEDED : INPUT_EVENT_INJECTION_FAILED);
Jeff Brown54a18252010-09-16 14:07:33 -0700847 return true;
848 }
849
Jeff Brownb88102f2010-09-08 11:49:43 -0700850 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
851
852 // Identify targets.
Jeff Browncc0c1592011-02-19 05:07:28 -0800853 bool conflictingPointerActions = false;
Jeff Brownb88102f2010-09-08 11:49:43 -0700854 if (! mCurrentInputTargetsValid) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700855 int32_t injectionResult;
856 if (isPointerEvent) {
857 // Pointer event. (eg. touchscreen)
Jeff Brown01ce2e92010-09-26 22:20:12 -0700858 injectionResult = findTouchedWindowTargetsLocked(currentTime,
Jeff Browncc0c1592011-02-19 05:07:28 -0800859 entry, nextWakeupTime, &conflictingPointerActions);
Jeff Brownb88102f2010-09-08 11:49:43 -0700860 } else {
861 // Non touch event. (eg. trackball)
Jeff Brown01ce2e92010-09-26 22:20:12 -0700862 injectionResult = findFocusedWindowTargetsLocked(currentTime,
863 entry, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700864 }
865 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
866 return false;
867 }
868
869 setInjectionResultLocked(entry, injectionResult);
870 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
871 return true;
872 }
873
874 addMonitoringTargetsLocked();
Jeff Brown01ce2e92010-09-26 22:20:12 -0700875 commitTargetsLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -0700876 }
877
878 // Dispatch the motion.
Jeff Browncc0c1592011-02-19 05:07:28 -0800879 if (conflictingPointerActions) {
880 synthesizeCancelationEventsForAllConnectionsLocked(
881 InputState::CANCEL_POINTER_EVENTS, "Conflicting pointer actions.");
882 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700883 dispatchEventToCurrentInputTargetsLocked(currentTime, entry, false);
Jeff Brownb88102f2010-09-08 11:49:43 -0700884 return true;
885}
886
887
888void InputDispatcher::logOutboundMotionDetailsLocked(const char* prefix, const MotionEntry* entry) {
889#if DEBUG_OUTBOUND_EVENT_DETAILS
Jeff Brown90655042010-12-02 13:50:46 -0800890 LOGD("%seventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, "
Jeff Brown85a31762010-09-01 17:01:00 -0700891 "action=0x%x, flags=0x%x, "
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700892 "metaState=0x%x, edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%lld",
Jeff Brownb88102f2010-09-08 11:49:43 -0700893 prefix,
Jeff Brown85a31762010-09-01 17:01:00 -0700894 entry->eventTime, entry->deviceId, entry->source, entry->policyFlags,
895 entry->action, entry->flags,
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700896 entry->metaState, entry->edgeFlags, entry->xPrecision, entry->yPrecision,
897 entry->downTime);
898
899 // Print the most recent sample that we have available, this may change due to batching.
900 size_t sampleCount = 1;
Jeff Brownb88102f2010-09-08 11:49:43 -0700901 const MotionSample* sample = & entry->firstSample;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700902 for (; sample->next != NULL; sample = sample->next) {
903 sampleCount += 1;
904 }
905 for (uint32_t i = 0; i < entry->pointerCount; i++) {
Jeff Brown8d608662010-08-30 03:02:23 -0700906 LOGD(" Pointer %d: id=%d, x=%f, y=%f, pressure=%f, size=%f, "
Jeff Brown85a31762010-09-01 17:01:00 -0700907 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
Jeff Brown8d608662010-08-30 03:02:23 -0700908 "orientation=%f",
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700909 i, entry->pointerIds[i],
Jeff Brownebbd5d12011-02-17 13:01:34 -0800910 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
911 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
912 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
913 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
914 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
915 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
916 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
917 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
918 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700919 }
920
921 // Keep in mind that due to batching, it is possible for the number of samples actually
922 // dispatched to change before the application finally consumed them.
Jeff Brownc5ed5912010-07-14 18:48:53 -0700923 if (entry->action == AMOTION_EVENT_ACTION_MOVE) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700924 LOGD(" ... Total movement samples currently batched %d ...", sampleCount);
925 }
926#endif
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700927}
928
929void InputDispatcher::dispatchEventToCurrentInputTargetsLocked(nsecs_t currentTime,
930 EventEntry* eventEntry, bool resumeWithAppendedMotionSample) {
931#if DEBUG_DISPATCH_CYCLE
Jeff Brown9c3cda02010-06-15 01:31:58 -0700932 LOGD("dispatchEventToCurrentInputTargets - "
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700933 "resumeWithAppendedMotionSample=%s",
Jeff Brownb88102f2010-09-08 11:49:43 -0700934 toString(resumeWithAppendedMotionSample));
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700935#endif
936
Jeff Brown9c3cda02010-06-15 01:31:58 -0700937 assert(eventEntry->dispatchInProgress); // should already have been set to true
938
Jeff Browne2fe69e2010-10-18 13:21:23 -0700939 pokeUserActivityLocked(eventEntry);
940
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700941 for (size_t i = 0; i < mCurrentInputTargets.size(); i++) {
942 const InputTarget& inputTarget = mCurrentInputTargets.itemAt(i);
943
Jeff Brown519e0242010-09-15 15:18:56 -0700944 ssize_t connectionIndex = getConnectionIndexLocked(inputTarget.inputChannel);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700945 if (connectionIndex >= 0) {
946 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
Jeff Brown7fbdc842010-06-17 20:52:56 -0700947 prepareDispatchCycleLocked(currentTime, connection, eventEntry, & inputTarget,
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700948 resumeWithAppendedMotionSample);
949 } else {
Jeff Brownb6997262010-10-08 22:31:17 -0700950#if DEBUG_FOCUS
951 LOGD("Dropping event delivery to target with channel '%s' because it "
952 "is no longer registered with the input dispatcher.",
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700953 inputTarget.inputChannel->getName().string());
Jeff Brownb6997262010-10-08 22:31:17 -0700954#endif
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700955 }
956 }
957}
958
Jeff Brown54a18252010-09-16 14:07:33 -0700959void InputDispatcher::resetTargetsLocked() {
Jeff Brownb88102f2010-09-08 11:49:43 -0700960 mCurrentInputTargetsValid = false;
961 mCurrentInputTargets.clear();
Jeff Brownb88102f2010-09-08 11:49:43 -0700962 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_NONE;
Jeff Brown928e0542011-01-10 11:17:36 -0800963 mInputTargetWaitApplication.clear();
Jeff Brownb88102f2010-09-08 11:49:43 -0700964}
965
Jeff Brown01ce2e92010-09-26 22:20:12 -0700966void InputDispatcher::commitTargetsLocked() {
Jeff Brownb88102f2010-09-08 11:49:43 -0700967 mCurrentInputTargetsValid = true;
968}
969
970int32_t InputDispatcher::handleTargetsNotReadyLocked(nsecs_t currentTime,
971 const EventEntry* entry, const InputApplication* application, const InputWindow* window,
972 nsecs_t* nextWakeupTime) {
973 if (application == NULL && window == NULL) {
974 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY) {
975#if DEBUG_FOCUS
976 LOGD("Waiting for system to become ready for input.");
977#endif
978 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY;
979 mInputTargetWaitStartTime = currentTime;
980 mInputTargetWaitTimeoutTime = LONG_LONG_MAX;
981 mInputTargetWaitTimeoutExpired = false;
Jeff Brown928e0542011-01-10 11:17:36 -0800982 mInputTargetWaitApplication.clear();
Jeff Brownb88102f2010-09-08 11:49:43 -0700983 }
984 } else {
985 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
986#if DEBUG_FOCUS
Jeff Brown519e0242010-09-15 15:18:56 -0700987 LOGD("Waiting for application to become ready for input: %s",
988 getApplicationWindowLabelLocked(application, window).string());
Jeff Brownb88102f2010-09-08 11:49:43 -0700989#endif
990 nsecs_t timeout = window ? window->dispatchingTimeout :
991 application ? application->dispatchingTimeout : DEFAULT_INPUT_DISPATCHING_TIMEOUT;
992
993 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY;
994 mInputTargetWaitStartTime = currentTime;
995 mInputTargetWaitTimeoutTime = currentTime + timeout;
996 mInputTargetWaitTimeoutExpired = false;
Jeff Brown928e0542011-01-10 11:17:36 -0800997 mInputTargetWaitApplication.clear();
998
999 if (window && window->inputWindowHandle != NULL) {
1000 mInputTargetWaitApplication =
1001 window->inputWindowHandle->getInputApplicationHandle();
1002 }
1003 if (mInputTargetWaitApplication == NULL && application) {
1004 mInputTargetWaitApplication = application->inputApplicationHandle;
1005 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001006 }
1007 }
1008
1009 if (mInputTargetWaitTimeoutExpired) {
1010 return INPUT_EVENT_INJECTION_TIMED_OUT;
1011 }
1012
1013 if (currentTime >= mInputTargetWaitTimeoutTime) {
Jeff Brown519e0242010-09-15 15:18:56 -07001014 onANRLocked(currentTime, application, window, entry->eventTime, mInputTargetWaitStartTime);
Jeff Brownb88102f2010-09-08 11:49:43 -07001015
1016 // Force poll loop to wake up immediately on next iteration once we get the
1017 // ANR response back from the policy.
1018 *nextWakeupTime = LONG_LONG_MIN;
1019 return INPUT_EVENT_INJECTION_PENDING;
1020 } else {
1021 // Force poll loop to wake up when timeout is due.
1022 if (mInputTargetWaitTimeoutTime < *nextWakeupTime) {
1023 *nextWakeupTime = mInputTargetWaitTimeoutTime;
1024 }
1025 return INPUT_EVENT_INJECTION_PENDING;
1026 }
1027}
1028
Jeff Brown519e0242010-09-15 15:18:56 -07001029void InputDispatcher::resumeAfterTargetsNotReadyTimeoutLocked(nsecs_t newTimeout,
1030 const sp<InputChannel>& inputChannel) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001031 if (newTimeout > 0) {
1032 // Extend the timeout.
1033 mInputTargetWaitTimeoutTime = now() + newTimeout;
1034 } else {
1035 // Give up.
1036 mInputTargetWaitTimeoutExpired = true;
Jeff Brown519e0242010-09-15 15:18:56 -07001037
Jeff Brown01ce2e92010-09-26 22:20:12 -07001038 // Release the touch targets.
1039 mTouchState.reset();
Jeff Brown2a95c2a2010-09-16 12:31:46 -07001040
Jeff Brown519e0242010-09-15 15:18:56 -07001041 // Input state will not be realistic. Mark it out of sync.
Jeff Browndc3e0052010-09-16 11:02:16 -07001042 if (inputChannel.get()) {
1043 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
1044 if (connectionIndex >= 0) {
1045 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
Jeff Brown00045a72010-12-09 18:10:30 -08001046 if (connection->status == Connection::STATUS_NORMAL) {
1047 synthesizeCancelationEventsForConnectionLocked(
1048 connection, InputState::CANCEL_ALL_EVENTS,
1049 "application not responding");
1050 }
Jeff Browndc3e0052010-09-16 11:02:16 -07001051 }
Jeff Brown519e0242010-09-15 15:18:56 -07001052 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001053 }
1054}
1055
Jeff Brown519e0242010-09-15 15:18:56 -07001056nsecs_t InputDispatcher::getTimeSpentWaitingForApplicationLocked(
Jeff Brownb88102f2010-09-08 11:49:43 -07001057 nsecs_t currentTime) {
1058 if (mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
1059 return currentTime - mInputTargetWaitStartTime;
1060 }
1061 return 0;
1062}
1063
1064void InputDispatcher::resetANRTimeoutsLocked() {
1065#if DEBUG_FOCUS
1066 LOGD("Resetting ANR timeouts.");
1067#endif
1068
Jeff Brownb88102f2010-09-08 11:49:43 -07001069 // Reset input target wait timeout.
1070 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_NONE;
1071}
1072
Jeff Brown01ce2e92010-09-26 22:20:12 -07001073int32_t InputDispatcher::findFocusedWindowTargetsLocked(nsecs_t currentTime,
1074 const EventEntry* entry, nsecs_t* nextWakeupTime) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001075 mCurrentInputTargets.clear();
1076
1077 int32_t injectionResult;
1078
1079 // If there is no currently focused window and no focused application
1080 // then drop the event.
1081 if (! mFocusedWindow) {
1082 if (mFocusedApplication) {
1083#if DEBUG_FOCUS
1084 LOGD("Waiting because there is no focused window but there is a "
Jeff Brown519e0242010-09-15 15:18:56 -07001085 "focused application that may eventually add a window: %s.",
1086 getApplicationWindowLabelLocked(mFocusedApplication, NULL).string());
Jeff Brownb88102f2010-09-08 11:49:43 -07001087#endif
1088 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
1089 mFocusedApplication, NULL, nextWakeupTime);
1090 goto Unresponsive;
1091 }
1092
1093 LOGI("Dropping event because there is no focused window or focused application.");
1094 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1095 goto Failed;
1096 }
1097
1098 // Check permissions.
Jeff Brown01ce2e92010-09-26 22:20:12 -07001099 if (! checkInjectionPermission(mFocusedWindow, entry->injectionState)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001100 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1101 goto Failed;
1102 }
1103
1104 // If the currently focused window is paused then keep waiting.
1105 if (mFocusedWindow->paused) {
1106#if DEBUG_FOCUS
1107 LOGD("Waiting because focused window is paused.");
1108#endif
1109 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
1110 mFocusedApplication, mFocusedWindow, nextWakeupTime);
1111 goto Unresponsive;
1112 }
1113
Jeff Brown519e0242010-09-15 15:18:56 -07001114 // If the currently focused window is still working on previous events then keep waiting.
1115 if (! isWindowFinishedWithPreviousInputLocked(mFocusedWindow)) {
1116#if DEBUG_FOCUS
1117 LOGD("Waiting because focused window still processing previous input.");
1118#endif
1119 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
1120 mFocusedApplication, mFocusedWindow, nextWakeupTime);
1121 goto Unresponsive;
1122 }
1123
Jeff Brownb88102f2010-09-08 11:49:43 -07001124 // Success! Output targets.
1125 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001126 addWindowTargetLocked(mFocusedWindow, InputTarget::FLAG_FOREGROUND, BitSet32(0));
Jeff Brownb88102f2010-09-08 11:49:43 -07001127
1128 // Done.
1129Failed:
1130Unresponsive:
Jeff Brown519e0242010-09-15 15:18:56 -07001131 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
1132 updateDispatchStatisticsLocked(currentTime, entry,
1133 injectionResult, timeSpentWaitingForApplication);
Jeff Brownb88102f2010-09-08 11:49:43 -07001134#if DEBUG_FOCUS
Jeff Brown519e0242010-09-15 15:18:56 -07001135 LOGD("findFocusedWindow finished: injectionResult=%d, "
1136 "timeSpendWaitingForApplication=%0.1fms",
1137 injectionResult, timeSpentWaitingForApplication / 1000000.0);
Jeff Brownb88102f2010-09-08 11:49:43 -07001138#endif
1139 return injectionResult;
1140}
1141
Jeff Brown01ce2e92010-09-26 22:20:12 -07001142int32_t InputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime,
Jeff Browncc0c1592011-02-19 05:07:28 -08001143 const MotionEntry* entry, nsecs_t* nextWakeupTime, bool* outConflictingPointerActions) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001144 enum InjectionPermission {
1145 INJECTION_PERMISSION_UNKNOWN,
1146 INJECTION_PERMISSION_GRANTED,
1147 INJECTION_PERMISSION_DENIED
1148 };
1149
Jeff Brownb88102f2010-09-08 11:49:43 -07001150 mCurrentInputTargets.clear();
1151
1152 nsecs_t startTime = now();
1153
1154 // For security reasons, we defer updating the touch state until we are sure that
1155 // event injection will be allowed.
1156 //
1157 // FIXME In the original code, screenWasOff could never be set to true.
1158 // The reason is that the POLICY_FLAG_WOKE_HERE
1159 // and POLICY_FLAG_BRIGHT_HERE flags were set only when preprocessing raw
1160 // EV_KEY, EV_REL and EV_ABS events. As it happens, the touch event was
1161 // actually enqueued using the policyFlags that appeared in the final EV_SYN
1162 // events upon which no preprocessing took place. So policyFlags was always 0.
1163 // In the new native input dispatcher we're a bit more careful about event
1164 // preprocessing so the touches we receive can actually have non-zero policyFlags.
1165 // Unfortunately we obtain undesirable behavior.
1166 //
1167 // Here's what happens:
1168 //
1169 // When the device dims in anticipation of going to sleep, touches
1170 // in windows which have FLAG_TOUCHABLE_WHEN_WAKING cause
1171 // the device to brighten and reset the user activity timer.
1172 // Touches on other windows (such as the launcher window)
1173 // are dropped. Then after a moment, the device goes to sleep. Oops.
1174 //
1175 // Also notice how screenWasOff was being initialized using POLICY_FLAG_BRIGHT_HERE
1176 // instead of POLICY_FLAG_WOKE_HERE...
1177 //
1178 bool screenWasOff = false; // original policy: policyFlags & POLICY_FLAG_BRIGHT_HERE;
1179
1180 int32_t action = entry->action;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001181 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Jeff Brownb88102f2010-09-08 11:49:43 -07001182
1183 // Update the touch state as needed based on the properties of the touch event.
Jeff Brown01ce2e92010-09-26 22:20:12 -07001184 int32_t injectionResult = INPUT_EVENT_INJECTION_PENDING;
1185 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
Jeff Browncc0c1592011-02-19 05:07:28 -08001186
1187 bool isSplit = mTouchState.split;
1188 bool wrongDevice = mTouchState.down
1189 && (mTouchState.deviceId != entry->deviceId
1190 || mTouchState.source != entry->source);
1191 if (maskedAction == AMOTION_EVENT_ACTION_DOWN
Jeff Brown33bbfd22011-02-24 20:55:35 -08001192 || maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE
1193 || maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
Jeff Browncc0c1592011-02-19 05:07:28 -08001194 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
1195 if (wrongDevice && !down) {
1196 mTempTouchState.copyFrom(mTouchState);
1197 } else {
1198 mTempTouchState.reset();
1199 mTempTouchState.down = down;
1200 mTempTouchState.deviceId = entry->deviceId;
1201 mTempTouchState.source = entry->source;
1202 isSplit = false;
1203 wrongDevice = false;
1204 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001205 } else {
1206 mTempTouchState.copyFrom(mTouchState);
Jeff Browncc0c1592011-02-19 05:07:28 -08001207 }
1208 if (wrongDevice) {
Jeff Brown95712852011-01-04 19:41:59 -08001209#if DEBUG_INPUT_DISPATCHER_POLICY
Jeff Browncc0c1592011-02-19 05:07:28 -08001210 LOGD("Dropping event because a pointer for a different device is already down.");
Jeff Brown95712852011-01-04 19:41:59 -08001211#endif
Jeff Browncc0c1592011-02-19 05:07:28 -08001212 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1213 goto Failed;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001214 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001215
Jeff Brown01ce2e92010-09-26 22:20:12 -07001216 if (maskedAction == AMOTION_EVENT_ACTION_DOWN
Jeff Browncc0c1592011-02-19 05:07:28 -08001217 || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)
Jeff Brown33bbfd22011-02-24 20:55:35 -08001218 || maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE
1219 || maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
1220 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
Jeff Brownb88102f2010-09-08 11:49:43 -07001221
Jeff Brown01ce2e92010-09-26 22:20:12 -07001222 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Jeff Brown91c69ab2011-02-14 17:03:18 -08001223 int32_t x = int32_t(entry->firstSample.pointerCoords[pointerIndex].
Jeff Brownebbd5d12011-02-17 13:01:34 -08001224 getAxisValue(AMOTION_EVENT_AXIS_X));
Jeff Brown91c69ab2011-02-14 17:03:18 -08001225 int32_t y = int32_t(entry->firstSample.pointerCoords[pointerIndex].
Jeff Brownebbd5d12011-02-17 13:01:34 -08001226 getAxisValue(AMOTION_EVENT_AXIS_Y));
Jeff Brown01ce2e92010-09-26 22:20:12 -07001227 const InputWindow* newTouchedWindow = NULL;
1228 const InputWindow* topErrorWindow = NULL;
Jeff Brownb88102f2010-09-08 11:49:43 -07001229
1230 // Traverse windows from front to back to find touched window and outside targets.
1231 size_t numWindows = mWindows.size();
1232 for (size_t i = 0; i < numWindows; i++) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001233 const InputWindow* window = & mWindows.editItemAt(i);
Jeff Brownb88102f2010-09-08 11:49:43 -07001234 int32_t flags = window->layoutParamsFlags;
1235
1236 if (flags & InputWindow::FLAG_SYSTEM_ERROR) {
1237 if (! topErrorWindow) {
1238 topErrorWindow = window;
1239 }
1240 }
1241
1242 if (window->visible) {
1243 if (! (flags & InputWindow::FLAG_NOT_TOUCHABLE)) {
1244 bool isTouchModal = (flags & (InputWindow::FLAG_NOT_FOCUSABLE
1245 | InputWindow::FLAG_NOT_TOUCH_MODAL)) == 0;
Jeff Brownfbf09772011-01-16 14:06:57 -08001246 if (isTouchModal || window->touchableRegionContainsPoint(x, y)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001247 if (! screenWasOff || flags & InputWindow::FLAG_TOUCHABLE_WHEN_WAKING) {
1248 newTouchedWindow = window;
Jeff Brownb88102f2010-09-08 11:49:43 -07001249 }
1250 break; // found touched window, exit window loop
1251 }
1252 }
1253
Jeff Brown01ce2e92010-09-26 22:20:12 -07001254 if (maskedAction == AMOTION_EVENT_ACTION_DOWN
1255 && (flags & InputWindow::FLAG_WATCH_OUTSIDE_TOUCH)) {
Jeff Brown19dfc832010-10-05 12:26:23 -07001256 int32_t outsideTargetFlags = InputTarget::FLAG_OUTSIDE;
1257 if (isWindowObscuredAtPointLocked(window, x, y)) {
1258 outsideTargetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1259 }
1260
1261 mTempTouchState.addOrUpdateWindow(window, outsideTargetFlags, BitSet32(0));
Jeff Brownb88102f2010-09-08 11:49:43 -07001262 }
1263 }
1264 }
1265
1266 // If there is an error window but it is not taking focus (typically because
1267 // it is invisible) then wait for it. Any other focused window may in
1268 // fact be in ANR state.
1269 if (topErrorWindow && newTouchedWindow != topErrorWindow) {
1270#if DEBUG_FOCUS
1271 LOGD("Waiting because system error window is pending.");
1272#endif
1273 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
1274 NULL, NULL, nextWakeupTime);
1275 injectionPermission = INJECTION_PERMISSION_UNKNOWN;
1276 goto Unresponsive;
1277 }
1278
Jeff Brown01ce2e92010-09-26 22:20:12 -07001279 // Figure out whether splitting will be allowed for this window.
Jeff Brown46e75292010-11-10 16:53:45 -08001280 if (newTouchedWindow && newTouchedWindow->supportsSplitTouch()) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001281 // New window supports splitting.
1282 isSplit = true;
1283 } else if (isSplit) {
1284 // New window does not support splitting but we have already split events.
1285 // Assign the pointer to the first foreground window we find.
1286 // (May be NULL which is why we put this code block before the next check.)
1287 newTouchedWindow = mTempTouchState.getFirstForegroundWindow();
1288 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001289
Jeff Brownb88102f2010-09-08 11:49:43 -07001290 // If we did not find a touched window then fail.
1291 if (! newTouchedWindow) {
1292 if (mFocusedApplication) {
1293#if DEBUG_FOCUS
1294 LOGD("Waiting because there is no touched window but there is a "
Jeff Brown519e0242010-09-15 15:18:56 -07001295 "focused application that may eventually add a new window: %s.",
1296 getApplicationWindowLabelLocked(mFocusedApplication, NULL).string());
Jeff Brownb88102f2010-09-08 11:49:43 -07001297#endif
1298 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
1299 mFocusedApplication, NULL, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -07001300 goto Unresponsive;
1301 }
1302
1303 LOGI("Dropping event because there is no touched window or focused application.");
1304 injectionResult = INPUT_EVENT_INJECTION_FAILED;
Jeff Brownb88102f2010-09-08 11:49:43 -07001305 goto Failed;
1306 }
1307
Jeff Brown19dfc832010-10-05 12:26:23 -07001308 // Set target flags.
1309 int32_t targetFlags = InputTarget::FLAG_FOREGROUND;
1310 if (isSplit) {
1311 targetFlags |= InputTarget::FLAG_SPLIT;
1312 }
1313 if (isWindowObscuredAtPointLocked(newTouchedWindow, x, y)) {
1314 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1315 }
1316
Jeff Brown01ce2e92010-09-26 22:20:12 -07001317 // Update the temporary touch state.
1318 BitSet32 pointerIds;
1319 if (isSplit) {
1320 uint32_t pointerId = entry->pointerIds[pointerIndex];
1321 pointerIds.markBit(pointerId);
Jeff Brownb88102f2010-09-08 11:49:43 -07001322 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001323 mTempTouchState.addOrUpdateWindow(newTouchedWindow, targetFlags, pointerIds);
Jeff Brownb88102f2010-09-08 11:49:43 -07001324 } else {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001325 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
Jeff Brownb88102f2010-09-08 11:49:43 -07001326
1327 // If the pointer is not currently down, then ignore the event.
Jeff Brown01ce2e92010-09-26 22:20:12 -07001328 if (! mTempTouchState.down) {
Jeff Brown76860e32010-10-25 17:37:46 -07001329#if DEBUG_INPUT_DISPATCHER_POLICY
1330 LOGD("Dropping event because the pointer is not down or we previously "
1331 "dropped the pointer down event.");
1332#endif
Jeff Brownb88102f2010-09-08 11:49:43 -07001333 injectionResult = INPUT_EVENT_INJECTION_FAILED;
Jeff Brownb88102f2010-09-08 11:49:43 -07001334 goto Failed;
1335 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001336 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001337
Jeff Brown01ce2e92010-09-26 22:20:12 -07001338 // Check permission to inject into all touched foreground windows and ensure there
1339 // is at least one touched foreground window.
1340 {
1341 bool haveForegroundWindow = false;
1342 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1343 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1344 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1345 haveForegroundWindow = true;
1346 if (! checkInjectionPermission(touchedWindow.window, entry->injectionState)) {
1347 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1348 injectionPermission = INJECTION_PERMISSION_DENIED;
1349 goto Failed;
1350 }
1351 }
1352 }
1353 if (! haveForegroundWindow) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001354#if DEBUG_INPUT_DISPATCHER_POLICY
Jeff Brown01ce2e92010-09-26 22:20:12 -07001355 LOGD("Dropping event because there is no touched foreground window to receive it.");
Jeff Brownb88102f2010-09-08 11:49:43 -07001356#endif
1357 injectionResult = INPUT_EVENT_INJECTION_FAILED;
Jeff Brownb88102f2010-09-08 11:49:43 -07001358 goto Failed;
1359 }
1360
Jeff Brown01ce2e92010-09-26 22:20:12 -07001361 // Permission granted to injection into all touched foreground windows.
1362 injectionPermission = INJECTION_PERMISSION_GRANTED;
1363 }
Jeff Brown519e0242010-09-15 15:18:56 -07001364
Jeff Brown01ce2e92010-09-26 22:20:12 -07001365 // Ensure all touched foreground windows are ready for new input.
1366 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1367 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1368 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1369 // If the touched window is paused then keep waiting.
1370 if (touchedWindow.window->paused) {
1371#if DEBUG_INPUT_DISPATCHER_POLICY
1372 LOGD("Waiting because touched window is paused.");
Jeff Brown519e0242010-09-15 15:18:56 -07001373#endif
Jeff Brown01ce2e92010-09-26 22:20:12 -07001374 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
1375 NULL, touchedWindow.window, nextWakeupTime);
1376 goto Unresponsive;
1377 }
1378
1379 // If the touched window is still working on previous events then keep waiting.
1380 if (! isWindowFinishedWithPreviousInputLocked(touchedWindow.window)) {
1381#if DEBUG_FOCUS
1382 LOGD("Waiting because touched window still processing previous input.");
1383#endif
1384 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
1385 NULL, touchedWindow.window, nextWakeupTime);
1386 goto Unresponsive;
1387 }
1388 }
1389 }
1390
1391 // If this is the first pointer going down and the touched window has a wallpaper
1392 // then also add the touched wallpaper windows so they are locked in for the duration
1393 // of the touch gesture.
Jeff Brown33bbfd22011-02-24 20:55:35 -08001394 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
1395 // engine only supports touch events. We would need to add a mechanism similar
1396 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
1397 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001398 const InputWindow* foregroundWindow = mTempTouchState.getFirstForegroundWindow();
1399 if (foregroundWindow->hasWallpaper) {
1400 for (size_t i = 0; i < mWindows.size(); i++) {
1401 const InputWindow* window = & mWindows[i];
1402 if (window->layoutParamsType == InputWindow::TYPE_WALLPAPER) {
Jeff Brown19dfc832010-10-05 12:26:23 -07001403 mTempTouchState.addOrUpdateWindow(window,
1404 InputTarget::FLAG_WINDOW_IS_OBSCURED, BitSet32(0));
Jeff Brown01ce2e92010-09-26 22:20:12 -07001405 }
1406 }
1407 }
1408 }
1409
Jeff Brownb88102f2010-09-08 11:49:43 -07001410 // Success! Output targets.
1411 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
Jeff Brownb88102f2010-09-08 11:49:43 -07001412
Jeff Brown01ce2e92010-09-26 22:20:12 -07001413 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1414 const TouchedWindow& touchedWindow = mTempTouchState.windows.itemAt(i);
1415 addWindowTargetLocked(touchedWindow.window, touchedWindow.targetFlags,
1416 touchedWindow.pointerIds);
Jeff Brownb88102f2010-09-08 11:49:43 -07001417 }
1418
Jeff Brown01ce2e92010-09-26 22:20:12 -07001419 // Drop the outside touch window since we will not care about them in the next iteration.
1420 mTempTouchState.removeOutsideTouchWindows();
1421
Jeff Brownb88102f2010-09-08 11:49:43 -07001422Failed:
1423 // Check injection permission once and for all.
1424 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001425 if (checkInjectionPermission(NULL, entry->injectionState)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001426 injectionPermission = INJECTION_PERMISSION_GRANTED;
1427 } else {
1428 injectionPermission = INJECTION_PERMISSION_DENIED;
1429 }
1430 }
1431
1432 // Update final pieces of touch state if the injector had permission.
1433 if (injectionPermission == INJECTION_PERMISSION_GRANTED) {
Jeff Brown95712852011-01-04 19:41:59 -08001434 if (!wrongDevice) {
1435 if (maskedAction == AMOTION_EVENT_ACTION_UP
Jeff Browncc0c1592011-02-19 05:07:28 -08001436 || maskedAction == AMOTION_EVENT_ACTION_CANCEL
1437 || maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Jeff Brown95712852011-01-04 19:41:59 -08001438 // All pointers up or canceled.
Jeff Brown33bbfd22011-02-24 20:55:35 -08001439 mTouchState.reset();
Jeff Brown95712852011-01-04 19:41:59 -08001440 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1441 // First pointer went down.
1442 if (mTouchState.down) {
Jeff Browncc0c1592011-02-19 05:07:28 -08001443 *outConflictingPointerActions = true;
Jeff Brownb6997262010-10-08 22:31:17 -07001444#if DEBUG_FOCUS
Jeff Brown95712852011-01-04 19:41:59 -08001445 LOGD("Pointer down received while already down.");
Jeff Brownb6997262010-10-08 22:31:17 -07001446#endif
Jeff Brown95712852011-01-04 19:41:59 -08001447 }
Jeff Brown33bbfd22011-02-24 20:55:35 -08001448 mTouchState.copyFrom(mTempTouchState);
Jeff Brown95712852011-01-04 19:41:59 -08001449 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
1450 // One pointer went up.
1451 if (isSplit) {
1452 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
1453 uint32_t pointerId = entry->pointerIds[pointerIndex];
Jeff Brownb88102f2010-09-08 11:49:43 -07001454
Jeff Brown95712852011-01-04 19:41:59 -08001455 for (size_t i = 0; i < mTempTouchState.windows.size(); ) {
1456 TouchedWindow& touchedWindow = mTempTouchState.windows.editItemAt(i);
1457 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
1458 touchedWindow.pointerIds.clearBit(pointerId);
1459 if (touchedWindow.pointerIds.isEmpty()) {
1460 mTempTouchState.windows.removeAt(i);
1461 continue;
1462 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001463 }
Jeff Brown95712852011-01-04 19:41:59 -08001464 i += 1;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001465 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001466 }
Jeff Brown33bbfd22011-02-24 20:55:35 -08001467 mTouchState.copyFrom(mTempTouchState);
1468 } else if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
1469 // Discard temporary touch state since it was only valid for this action.
1470 } else {
1471 // Save changes to touch state as-is for all other actions.
1472 mTouchState.copyFrom(mTempTouchState);
Jeff Brownb88102f2010-09-08 11:49:43 -07001473 }
Jeff Brown95712852011-01-04 19:41:59 -08001474 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001475 } else {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001476#if DEBUG_FOCUS
1477 LOGD("Not updating touch focus because injection was denied.");
1478#endif
Jeff Brownb88102f2010-09-08 11:49:43 -07001479 }
1480
1481Unresponsive:
Jeff Brown120a4592010-10-27 18:43:51 -07001482 // Reset temporary touch state to ensure we release unnecessary references to input channels.
1483 mTempTouchState.reset();
1484
Jeff Brown519e0242010-09-15 15:18:56 -07001485 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
1486 updateDispatchStatisticsLocked(currentTime, entry,
1487 injectionResult, timeSpentWaitingForApplication);
Jeff Brownb88102f2010-09-08 11:49:43 -07001488#if DEBUG_FOCUS
Jeff Brown01ce2e92010-09-26 22:20:12 -07001489 LOGD("findTouchedWindow finished: injectionResult=%d, injectionPermission=%d, "
1490 "timeSpentWaitingForApplication=%0.1fms",
Jeff Brown519e0242010-09-15 15:18:56 -07001491 injectionResult, injectionPermission, timeSpentWaitingForApplication / 1000000.0);
Jeff Brownb88102f2010-09-08 11:49:43 -07001492#endif
1493 return injectionResult;
1494}
1495
Jeff Brown01ce2e92010-09-26 22:20:12 -07001496void InputDispatcher::addWindowTargetLocked(const InputWindow* window, int32_t targetFlags,
1497 BitSet32 pointerIds) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001498 mCurrentInputTargets.push();
1499
1500 InputTarget& target = mCurrentInputTargets.editTop();
1501 target.inputChannel = window->inputChannel;
1502 target.flags = targetFlags;
Jeff Brownb88102f2010-09-08 11:49:43 -07001503 target.xOffset = - window->frameLeft;
1504 target.yOffset = - window->frameTop;
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001505 target.scaleFactor = window->scaleFactor;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001506 target.pointerIds = pointerIds;
Jeff Brownb88102f2010-09-08 11:49:43 -07001507}
1508
1509void InputDispatcher::addMonitoringTargetsLocked() {
1510 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
1511 mCurrentInputTargets.push();
1512
1513 InputTarget& target = mCurrentInputTargets.editTop();
1514 target.inputChannel = mMonitoringChannels[i];
1515 target.flags = 0;
Jeff Brownb88102f2010-09-08 11:49:43 -07001516 target.xOffset = 0;
1517 target.yOffset = 0;
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001518 target.scaleFactor = 1.0f;
Jeff Brownb88102f2010-09-08 11:49:43 -07001519 }
1520}
1521
1522bool InputDispatcher::checkInjectionPermission(const InputWindow* window,
Jeff Brown01ce2e92010-09-26 22:20:12 -07001523 const InjectionState* injectionState) {
1524 if (injectionState
Jeff Brownb6997262010-10-08 22:31:17 -07001525 && (window == NULL || window->ownerUid != injectionState->injectorUid)
1526 && !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
1527 if (window) {
1528 LOGW("Permission denied: injecting event from pid %d uid %d to window "
1529 "with input channel %s owned by uid %d",
1530 injectionState->injectorPid, injectionState->injectorUid,
1531 window->inputChannel->getName().string(),
1532 window->ownerUid);
1533 } else {
1534 LOGW("Permission denied: injecting event from pid %d uid %d",
1535 injectionState->injectorPid, injectionState->injectorUid);
Jeff Brownb88102f2010-09-08 11:49:43 -07001536 }
Jeff Brownb6997262010-10-08 22:31:17 -07001537 return false;
Jeff Brownb88102f2010-09-08 11:49:43 -07001538 }
1539 return true;
1540}
1541
Jeff Brown19dfc832010-10-05 12:26:23 -07001542bool InputDispatcher::isWindowObscuredAtPointLocked(
1543 const InputWindow* window, int32_t x, int32_t y) const {
Jeff Brownb88102f2010-09-08 11:49:43 -07001544 size_t numWindows = mWindows.size();
1545 for (size_t i = 0; i < numWindows; i++) {
1546 const InputWindow* other = & mWindows.itemAt(i);
1547 if (other == window) {
1548 break;
1549 }
Jeff Brown19dfc832010-10-05 12:26:23 -07001550 if (other->visible && ! other->isTrustedOverlay() && other->frameContainsPoint(x, y)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001551 return true;
1552 }
1553 }
1554 return false;
1555}
1556
Jeff Brown519e0242010-09-15 15:18:56 -07001557bool InputDispatcher::isWindowFinishedWithPreviousInputLocked(const InputWindow* window) {
1558 ssize_t connectionIndex = getConnectionIndexLocked(window->inputChannel);
1559 if (connectionIndex >= 0) {
1560 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
1561 return connection->outboundQueue.isEmpty();
1562 } else {
1563 return true;
1564 }
1565}
1566
1567String8 InputDispatcher::getApplicationWindowLabelLocked(const InputApplication* application,
1568 const InputWindow* window) {
1569 if (application) {
1570 if (window) {
1571 String8 label(application->name);
1572 label.append(" - ");
1573 label.append(window->name);
1574 return label;
1575 } else {
1576 return application->name;
1577 }
1578 } else if (window) {
1579 return window->name;
1580 } else {
1581 return String8("<unknown application or window>");
1582 }
1583}
1584
Jeff Browne2fe69e2010-10-18 13:21:23 -07001585void InputDispatcher::pokeUserActivityLocked(const EventEntry* eventEntry) {
Jeff Brown56194eb2011-03-02 19:23:13 -08001586 int32_t eventType = POWER_MANAGER_OTHER_EVENT;
Jeff Brown4d396052010-10-29 21:50:21 -07001587 switch (eventEntry->type) {
1588 case EventEntry::TYPE_MOTION: {
Jeff Browne2fe69e2010-10-18 13:21:23 -07001589 const MotionEntry* motionEntry = static_cast<const MotionEntry*>(eventEntry);
Jeff Brown4d396052010-10-29 21:50:21 -07001590 if (motionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
1591 return;
1592 }
1593
Jeff Brown56194eb2011-03-02 19:23:13 -08001594 if (MotionEvent::isTouchEvent(motionEntry->source, motionEntry->action)) {
Joe Onorato1a542c72010-11-08 09:48:20 -08001595 eventType = POWER_MANAGER_TOUCH_EVENT;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001596 }
Jeff Brown4d396052010-10-29 21:50:21 -07001597 break;
1598 }
1599 case EventEntry::TYPE_KEY: {
1600 const KeyEntry* keyEntry = static_cast<const KeyEntry*>(eventEntry);
1601 if (keyEntry->flags & AKEY_EVENT_FLAG_CANCELED) {
1602 return;
1603 }
Jeff Brown56194eb2011-03-02 19:23:13 -08001604 eventType = POWER_MANAGER_BUTTON_EVENT;
Jeff Brown4d396052010-10-29 21:50:21 -07001605 break;
1606 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001607 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001608
Jeff Brownb88102f2010-09-08 11:49:43 -07001609 CommandEntry* commandEntry = postCommandLocked(
1610 & InputDispatcher::doPokeUserActivityLockedInterruptible);
Jeff Browne2fe69e2010-10-18 13:21:23 -07001611 commandEntry->eventTime = eventEntry->eventTime;
Jeff Brownb88102f2010-09-08 11:49:43 -07001612 commandEntry->userActivityEventType = eventType;
1613}
1614
Jeff Brown7fbdc842010-06-17 20:52:56 -07001615void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
1616 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget,
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001617 bool resumeWithAppendedMotionSample) {
1618#if DEBUG_DISPATCH_CYCLE
Jeff Brown519e0242010-09-15 15:18:56 -07001619 LOGD("channel '%s' ~ prepareDispatchCycle - flags=%d, "
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001620 "xOffset=%f, yOffset=%f, scaleFactor=%f"
Jeff Brown83c09682010-12-23 17:50:18 -08001621 "pointerIds=0x%x, "
Jeff Brown01ce2e92010-09-26 22:20:12 -07001622 "resumeWithAppendedMotionSample=%s",
Jeff Brown519e0242010-09-15 15:18:56 -07001623 connection->getInputChannelName(), inputTarget->flags,
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001624 inputTarget->xOffset, inputTarget->yOffset,
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001625 inputTarget->scaleFactor, inputTarget->pointerIds.value,
Jeff Brownb88102f2010-09-08 11:49:43 -07001626 toString(resumeWithAppendedMotionSample));
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001627#endif
1628
Jeff Brown01ce2e92010-09-26 22:20:12 -07001629 // Make sure we are never called for streaming when splitting across multiple windows.
1630 bool isSplit = inputTarget->flags & InputTarget::FLAG_SPLIT;
1631 assert(! (resumeWithAppendedMotionSample && isSplit));
1632
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001633 // Skip this event if the connection status is not normal.
Jeff Brown519e0242010-09-15 15:18:56 -07001634 // We don't want to enqueue additional outbound events if the connection is broken.
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001635 if (connection->status != Connection::STATUS_NORMAL) {
Jeff Brownb6997262010-10-08 22:31:17 -07001636#if DEBUG_DISPATCH_CYCLE
1637 LOGD("channel '%s' ~ Dropping event because the channel status is %s",
Jeff Brownb88102f2010-09-08 11:49:43 -07001638 connection->getInputChannelName(), connection->getStatusLabel());
Jeff Brownb6997262010-10-08 22:31:17 -07001639#endif
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001640 return;
1641 }
1642
Jeff Brown01ce2e92010-09-26 22:20:12 -07001643 // Split a motion event if needed.
1644 if (isSplit) {
1645 assert(eventEntry->type == EventEntry::TYPE_MOTION);
1646
1647 MotionEntry* originalMotionEntry = static_cast<MotionEntry*>(eventEntry);
1648 if (inputTarget->pointerIds.count() != originalMotionEntry->pointerCount) {
1649 MotionEntry* splitMotionEntry = splitMotionEvent(
1650 originalMotionEntry, inputTarget->pointerIds);
Jeff Brown58a2da82011-01-25 16:02:22 -08001651 if (!splitMotionEntry) {
1652 return; // split event was dropped
1653 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001654#if DEBUG_FOCUS
1655 LOGD("channel '%s' ~ Split motion event.",
1656 connection->getInputChannelName());
1657 logOutboundMotionDetailsLocked(" ", splitMotionEntry);
1658#endif
1659 eventEntry = splitMotionEntry;
1660 }
1661 }
1662
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001663 // Resume the dispatch cycle with a freshly appended motion sample.
1664 // First we check that the last dispatch entry in the outbound queue is for the same
1665 // motion event to which we appended the motion sample. If we find such a dispatch
1666 // entry, and if it is currently in progress then we try to stream the new sample.
1667 bool wasEmpty = connection->outboundQueue.isEmpty();
1668
1669 if (! wasEmpty && resumeWithAppendedMotionSample) {
1670 DispatchEntry* motionEventDispatchEntry =
1671 connection->findQueuedDispatchEntryForEvent(eventEntry);
1672 if (motionEventDispatchEntry) {
1673 // If the dispatch entry is not in progress, then we must be busy dispatching an
1674 // earlier event. Not a problem, the motion event is on the outbound queue and will
1675 // be dispatched later.
1676 if (! motionEventDispatchEntry->inProgress) {
1677#if DEBUG_BATCHING
1678 LOGD("channel '%s' ~ Not streaming because the motion event has "
1679 "not yet been dispatched. "
1680 "(Waiting for earlier events to be consumed.)",
1681 connection->getInputChannelName());
1682#endif
1683 return;
1684 }
1685
1686 // If the dispatch entry is in progress but it already has a tail of pending
1687 // motion samples, then it must mean that the shared memory buffer filled up.
1688 // Not a problem, when this dispatch cycle is finished, we will eventually start
1689 // a new dispatch cycle to process the tail and that tail includes the newly
1690 // appended motion sample.
1691 if (motionEventDispatchEntry->tailMotionSample) {
1692#if DEBUG_BATCHING
1693 LOGD("channel '%s' ~ Not streaming because no new samples can "
1694 "be appended to the motion event in this dispatch cycle. "
1695 "(Waiting for next dispatch cycle to start.)",
1696 connection->getInputChannelName());
1697#endif
1698 return;
1699 }
1700
1701 // The dispatch entry is in progress and is still potentially open for streaming.
1702 // Try to stream the new motion sample. This might fail if the consumer has already
1703 // consumed the motion event (or if the channel is broken).
Jeff Brown01ce2e92010-09-26 22:20:12 -07001704 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
1705 MotionSample* appendedMotionSample = motionEntry->lastSample;
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001706 status_t status;
1707 if (motionEventDispatchEntry->scaleFactor == 1.0f) {
1708 status = connection->inputPublisher.appendMotionSample(
1709 appendedMotionSample->eventTime, appendedMotionSample->pointerCoords);
1710 } else {
1711 PointerCoords scaledCoords[MAX_POINTERS];
1712 for (size_t i = 0; i < motionEntry->pointerCount; i++) {
1713 scaledCoords[i] = appendedMotionSample->pointerCoords[i];
1714 scaledCoords[i].scale(motionEventDispatchEntry->scaleFactor);
1715 }
1716 status = connection->inputPublisher.appendMotionSample(
1717 appendedMotionSample->eventTime, scaledCoords);
1718 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001719 if (status == OK) {
1720#if DEBUG_BATCHING
1721 LOGD("channel '%s' ~ Successfully streamed new motion sample.",
1722 connection->getInputChannelName());
1723#endif
1724 return;
1725 }
1726
1727#if DEBUG_BATCHING
1728 if (status == NO_MEMORY) {
1729 LOGD("channel '%s' ~ Could not append motion sample to currently "
1730 "dispatched move event because the shared memory buffer is full. "
1731 "(Waiting for next dispatch cycle to start.)",
1732 connection->getInputChannelName());
1733 } else if (status == status_t(FAILED_TRANSACTION)) {
1734 LOGD("channel '%s' ~ Could not append motion sample to currently "
Jeff Brown349703e2010-06-22 01:27:15 -07001735 "dispatched move event because the event has already been consumed. "
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001736 "(Waiting for next dispatch cycle to start.)",
1737 connection->getInputChannelName());
1738 } else {
1739 LOGD("channel '%s' ~ Could not append motion sample to currently "
1740 "dispatched move event due to an error, status=%d. "
1741 "(Waiting for next dispatch cycle to start.)",
1742 connection->getInputChannelName(), status);
1743 }
1744#endif
1745 // Failed to stream. Start a new tail of pending motion samples to dispatch
1746 // in the next cycle.
1747 motionEventDispatchEntry->tailMotionSample = appendedMotionSample;
1748 return;
1749 }
1750 }
1751
1752 // This is a new event.
1753 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Jeff Brownb88102f2010-09-08 11:49:43 -07001754 DispatchEntry* dispatchEntry = mAllocator.obtainDispatchEntry(eventEntry, // increments ref
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001755 inputTarget->flags, inputTarget->xOffset, inputTarget->yOffset,
1756 inputTarget->scaleFactor);
Jeff Brown519e0242010-09-15 15:18:56 -07001757 if (dispatchEntry->hasForegroundTarget()) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001758 incrementPendingForegroundDispatchesLocked(eventEntry);
Jeff Brown6ec402b2010-07-28 15:48:59 -07001759 }
1760
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001761 // Handle the case where we could not stream a new motion sample because the consumer has
1762 // already consumed the motion event (otherwise the corresponding dispatch entry would
1763 // still be in the outbound queue for this connection). We set the head motion sample
1764 // to the list starting with the newly appended motion sample.
1765 if (resumeWithAppendedMotionSample) {
1766#if DEBUG_BATCHING
1767 LOGD("channel '%s' ~ Preparing a new dispatch cycle for additional motion samples "
1768 "that cannot be streamed because the motion event has already been consumed.",
1769 connection->getInputChannelName());
1770#endif
1771 MotionSample* appendedMotionSample = static_cast<MotionEntry*>(eventEntry)->lastSample;
1772 dispatchEntry->headMotionSample = appendedMotionSample;
1773 }
1774
1775 // Enqueue the dispatch entry.
1776 connection->outboundQueue.enqueueAtTail(dispatchEntry);
1777
1778 // If the outbound queue was previously empty, start the dispatch cycle going.
1779 if (wasEmpty) {
Jeff Brown7fbdc842010-06-17 20:52:56 -07001780 activateConnectionLocked(connection.get());
Jeff Brown519e0242010-09-15 15:18:56 -07001781 startDispatchCycleLocked(currentTime, connection);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001782 }
1783}
1784
Jeff Brown7fbdc842010-06-17 20:52:56 -07001785void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Jeff Brown519e0242010-09-15 15:18:56 -07001786 const sp<Connection>& connection) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001787#if DEBUG_DISPATCH_CYCLE
1788 LOGD("channel '%s' ~ startDispatchCycle",
1789 connection->getInputChannelName());
1790#endif
1791
1792 assert(connection->status == Connection::STATUS_NORMAL);
1793 assert(! connection->outboundQueue.isEmpty());
1794
Jeff Brownb88102f2010-09-08 11:49:43 -07001795 DispatchEntry* dispatchEntry = connection->outboundQueue.headSentinel.next;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001796 assert(! dispatchEntry->inProgress);
1797
Jeff Brownb88102f2010-09-08 11:49:43 -07001798 // Mark the dispatch entry as in progress.
1799 dispatchEntry->inProgress = true;
1800
1801 // Update the connection's input state.
Jeff Brown01ce2e92010-09-26 22:20:12 -07001802 EventEntry* eventEntry = dispatchEntry->eventEntry;
Jeff Browncc0c1592011-02-19 05:07:28 -08001803 connection->inputState.trackEvent(eventEntry);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001804
1805 // Publish the event.
1806 status_t status;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001807 switch (eventEntry->type) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001808 case EventEntry::TYPE_KEY: {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001809 KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001810
1811 // Apply target flags.
1812 int32_t action = keyEntry->action;
1813 int32_t flags = keyEntry->flags;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001814
1815 // Publish the key event.
Jeff Brownc5ed5912010-07-14 18:48:53 -07001816 status = connection->inputPublisher.publishKeyEvent(keyEntry->deviceId, keyEntry->source,
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001817 action, flags, keyEntry->keyCode, keyEntry->scanCode,
1818 keyEntry->metaState, keyEntry->repeatCount, keyEntry->downTime,
1819 keyEntry->eventTime);
1820
1821 if (status) {
1822 LOGE("channel '%s' ~ Could not publish key event, "
1823 "status=%d", connection->getInputChannelName(), status);
Jeff Brownb6997262010-10-08 22:31:17 -07001824 abortBrokenDispatchCycleLocked(currentTime, connection);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001825 return;
1826 }
1827 break;
1828 }
1829
1830 case EventEntry::TYPE_MOTION: {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001831 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001832
1833 // Apply target flags.
1834 int32_t action = motionEntry->action;
Jeff Brown85a31762010-09-01 17:01:00 -07001835 int32_t flags = motionEntry->flags;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001836 if (dispatchEntry->targetFlags & InputTarget::FLAG_OUTSIDE) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001837 action = AMOTION_EVENT_ACTION_OUTSIDE;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001838 }
Jeff Brown85a31762010-09-01 17:01:00 -07001839 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
1840 flags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
1841 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001842
1843 // If headMotionSample is non-NULL, then it points to the first new sample that we
1844 // were unable to dispatch during the previous cycle so we resume dispatching from
1845 // that point in the list of motion samples.
1846 // Otherwise, we just start from the first sample of the motion event.
1847 MotionSample* firstMotionSample = dispatchEntry->headMotionSample;
1848 if (! firstMotionSample) {
1849 firstMotionSample = & motionEntry->firstSample;
1850 }
1851
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001852 PointerCoords scaledCoords[MAX_POINTERS];
1853 const PointerCoords* usingCoords = firstMotionSample->pointerCoords;
1854
Jeff Brownd3616592010-07-16 17:21:06 -07001855 // Set the X and Y offset depending on the input source.
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001856 float xOffset, yOffset, scaleFactor;
Jeff Brownd3616592010-07-16 17:21:06 -07001857 if (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) {
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001858 scaleFactor = dispatchEntry->scaleFactor;
1859 xOffset = dispatchEntry->xOffset * scaleFactor;
1860 yOffset = dispatchEntry->yOffset * scaleFactor;
1861 if (scaleFactor != 1.0f) {
1862 for (size_t i = 0; i < motionEntry->pointerCount; i++) {
1863 scaledCoords[i] = firstMotionSample->pointerCoords[i];
1864 scaledCoords[i].scale(scaleFactor);
1865 }
1866 usingCoords = scaledCoords;
1867 }
Jeff Brownd3616592010-07-16 17:21:06 -07001868 } else {
1869 xOffset = 0.0f;
1870 yOffset = 0.0f;
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001871 scaleFactor = 1.0f;
Jeff Brownd3616592010-07-16 17:21:06 -07001872 }
1873
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001874 // Publish the motion event and the first motion sample.
1875 status = connection->inputPublisher.publishMotionEvent(motionEntry->deviceId,
Jeff Brown85a31762010-09-01 17:01:00 -07001876 motionEntry->source, action, flags, motionEntry->edgeFlags, motionEntry->metaState,
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001877 xOffset, yOffset, motionEntry->xPrecision, motionEntry->yPrecision,
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001878 motionEntry->downTime, firstMotionSample->eventTime,
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001879 motionEntry->pointerCount, motionEntry->pointerIds, usingCoords);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001880
1881 if (status) {
1882 LOGE("channel '%s' ~ Could not publish motion event, "
1883 "status=%d", connection->getInputChannelName(), status);
Jeff Brownb6997262010-10-08 22:31:17 -07001884 abortBrokenDispatchCycleLocked(currentTime, connection);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001885 return;
1886 }
1887
1888 // Append additional motion samples.
1889 MotionSample* nextMotionSample = firstMotionSample->next;
1890 for (; nextMotionSample != NULL; nextMotionSample = nextMotionSample->next) {
1891 status = connection->inputPublisher.appendMotionSample(
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001892 nextMotionSample->eventTime, usingCoords);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001893 if (status == NO_MEMORY) {
1894#if DEBUG_DISPATCH_CYCLE
1895 LOGD("channel '%s' ~ Shared memory buffer full. Some motion samples will "
1896 "be sent in the next dispatch cycle.",
1897 connection->getInputChannelName());
1898#endif
1899 break;
1900 }
1901 if (status != OK) {
1902 LOGE("channel '%s' ~ Could not append motion sample "
1903 "for a reason other than out of memory, status=%d",
1904 connection->getInputChannelName(), status);
Jeff Brownb6997262010-10-08 22:31:17 -07001905 abortBrokenDispatchCycleLocked(currentTime, connection);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001906 return;
1907 }
1908 }
1909
1910 // Remember the next motion sample that we could not dispatch, in case we ran out
1911 // of space in the shared memory buffer.
1912 dispatchEntry->tailMotionSample = nextMotionSample;
1913 break;
1914 }
1915
1916 default: {
1917 assert(false);
1918 }
1919 }
1920
1921 // Send the dispatch signal.
1922 status = connection->inputPublisher.sendDispatchSignal();
1923 if (status) {
1924 LOGE("channel '%s' ~ Could not send dispatch signal, status=%d",
1925 connection->getInputChannelName(), status);
Jeff Brownb6997262010-10-08 22:31:17 -07001926 abortBrokenDispatchCycleLocked(currentTime, connection);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001927 return;
1928 }
1929
1930 // Record information about the newly started dispatch cycle.
Jeff Brown01ce2e92010-09-26 22:20:12 -07001931 connection->lastEventTime = eventEntry->eventTime;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001932 connection->lastDispatchTime = currentTime;
1933
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001934 // Notify other system components.
1935 onDispatchCycleStartedLocked(currentTime, connection);
1936}
1937
Jeff Brown7fbdc842010-06-17 20:52:56 -07001938void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Jeff Brown3915bb82010-11-05 15:02:16 -07001939 const sp<Connection>& connection, bool handled) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001940#if DEBUG_DISPATCH_CYCLE
Jeff Brown9c3cda02010-06-15 01:31:58 -07001941 LOGD("channel '%s' ~ finishDispatchCycle - %01.1fms since event, "
Jeff Brown3915bb82010-11-05 15:02:16 -07001942 "%01.1fms since dispatch, handled=%s",
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001943 connection->getInputChannelName(),
1944 connection->getEventLatencyMillis(currentTime),
Jeff Brown3915bb82010-11-05 15:02:16 -07001945 connection->getDispatchLatencyMillis(currentTime),
1946 toString(handled));
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001947#endif
1948
Jeff Brown9c3cda02010-06-15 01:31:58 -07001949 if (connection->status == Connection::STATUS_BROKEN
1950 || connection->status == Connection::STATUS_ZOMBIE) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001951 return;
1952 }
1953
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001954 // Reset the publisher since the event has been consumed.
1955 // We do this now so that the publisher can release some of its internal resources
1956 // while waiting for the next dispatch cycle to begin.
1957 status_t status = connection->inputPublisher.reset();
1958 if (status) {
1959 LOGE("channel '%s' ~ Could not reset publisher, status=%d",
1960 connection->getInputChannelName(), status);
Jeff Brownb6997262010-10-08 22:31:17 -07001961 abortBrokenDispatchCycleLocked(currentTime, connection);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001962 return;
1963 }
1964
Jeff Brown3915bb82010-11-05 15:02:16 -07001965 // Notify other system components and prepare to start the next dispatch cycle.
1966 onDispatchCycleFinishedLocked(currentTime, connection, handled);
Jeff Brownb88102f2010-09-08 11:49:43 -07001967}
1968
1969void InputDispatcher::startNextDispatchCycleLocked(nsecs_t currentTime,
1970 const sp<Connection>& connection) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001971 // Start the next dispatch cycle for this connection.
1972 while (! connection->outboundQueue.isEmpty()) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001973 DispatchEntry* dispatchEntry = connection->outboundQueue.headSentinel.next;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001974 if (dispatchEntry->inProgress) {
1975 // Finish or resume current event in progress.
1976 if (dispatchEntry->tailMotionSample) {
1977 // We have a tail of undispatched motion samples.
1978 // Reuse the same DispatchEntry and start a new cycle.
1979 dispatchEntry->inProgress = false;
1980 dispatchEntry->headMotionSample = dispatchEntry->tailMotionSample;
1981 dispatchEntry->tailMotionSample = NULL;
Jeff Brown519e0242010-09-15 15:18:56 -07001982 startDispatchCycleLocked(currentTime, connection);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001983 return;
1984 }
1985 // Finished.
1986 connection->outboundQueue.dequeueAtHead();
Jeff Brown519e0242010-09-15 15:18:56 -07001987 if (dispatchEntry->hasForegroundTarget()) {
1988 decrementPendingForegroundDispatchesLocked(dispatchEntry->eventEntry);
Jeff Brown6ec402b2010-07-28 15:48:59 -07001989 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001990 mAllocator.releaseDispatchEntry(dispatchEntry);
1991 } else {
1992 // If the head is not in progress, then we must have already dequeued the in
Jeff Brown519e0242010-09-15 15:18:56 -07001993 // progress event, which means we actually aborted it.
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001994 // So just start the next event for this connection.
Jeff Brown519e0242010-09-15 15:18:56 -07001995 startDispatchCycleLocked(currentTime, connection);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001996 return;
1997 }
1998 }
1999
2000 // Outbound queue is empty, deactivate the connection.
Jeff Brown7fbdc842010-06-17 20:52:56 -07002001 deactivateConnectionLocked(connection.get());
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002002}
2003
Jeff Brownb6997262010-10-08 22:31:17 -07002004void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
2005 const sp<Connection>& connection) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002006#if DEBUG_DISPATCH_CYCLE
Jeff Brown83c09682010-12-23 17:50:18 -08002007 LOGD("channel '%s' ~ abortBrokenDispatchCycle",
2008 connection->getInputChannelName());
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002009#endif
2010
Jeff Brownb88102f2010-09-08 11:49:43 -07002011 // Clear the outbound queue.
Jeff Brown519e0242010-09-15 15:18:56 -07002012 drainOutboundQueueLocked(connection.get());
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002013
Jeff Brownb6997262010-10-08 22:31:17 -07002014 // The connection appears to be unrecoverably broken.
Jeff Brown9c3cda02010-06-15 01:31:58 -07002015 // Ignore already broken or zombie connections.
Jeff Brownb6997262010-10-08 22:31:17 -07002016 if (connection->status == Connection::STATUS_NORMAL) {
2017 connection->status = Connection::STATUS_BROKEN;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002018
Jeff Brownb6997262010-10-08 22:31:17 -07002019 // Notify other system components.
2020 onDispatchCycleBrokenLocked(currentTime, connection);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002021 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002022}
2023
Jeff Brown519e0242010-09-15 15:18:56 -07002024void InputDispatcher::drainOutboundQueueLocked(Connection* connection) {
2025 while (! connection->outboundQueue.isEmpty()) {
2026 DispatchEntry* dispatchEntry = connection->outboundQueue.dequeueAtHead();
2027 if (dispatchEntry->hasForegroundTarget()) {
2028 decrementPendingForegroundDispatchesLocked(dispatchEntry->eventEntry);
Jeff Brownb88102f2010-09-08 11:49:43 -07002029 }
2030 mAllocator.releaseDispatchEntry(dispatchEntry);
Jeff Brownb88102f2010-09-08 11:49:43 -07002031 }
2032
Jeff Brown519e0242010-09-15 15:18:56 -07002033 deactivateConnectionLocked(connection);
Jeff Brownb88102f2010-09-08 11:49:43 -07002034}
2035
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002036int InputDispatcher::handleReceiveCallback(int receiveFd, int events, void* data) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002037 InputDispatcher* d = static_cast<InputDispatcher*>(data);
2038
2039 { // acquire lock
2040 AutoMutex _l(d->mLock);
2041
2042 ssize_t connectionIndex = d->mConnectionsByReceiveFd.indexOfKey(receiveFd);
2043 if (connectionIndex < 0) {
2044 LOGE("Received spurious receive callback for unknown input channel. "
2045 "fd=%d, events=0x%x", receiveFd, events);
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002046 return 0; // remove the callback
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002047 }
2048
Jeff Brown7fbdc842010-06-17 20:52:56 -07002049 nsecs_t currentTime = now();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002050
2051 sp<Connection> connection = d->mConnectionsByReceiveFd.valueAt(connectionIndex);
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002052 if (events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP)) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002053 LOGE("channel '%s' ~ Consumer closed input channel or an error occurred. "
2054 "events=0x%x", connection->getInputChannelName(), events);
Jeff Brownb6997262010-10-08 22:31:17 -07002055 d->abortBrokenDispatchCycleLocked(currentTime, connection);
Jeff Brown9c3cda02010-06-15 01:31:58 -07002056 d->runCommandsLockedInterruptible();
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002057 return 0; // remove the callback
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002058 }
2059
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002060 if (! (events & ALOOPER_EVENT_INPUT)) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002061 LOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
2062 "events=0x%x", connection->getInputChannelName(), events);
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002063 return 1;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002064 }
2065
Jeff Brown3915bb82010-11-05 15:02:16 -07002066 bool handled = false;
Jeff Brown49ed71d2010-12-06 17:13:33 -08002067 status_t status = connection->inputPublisher.receiveFinishedSignal(&handled);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002068 if (status) {
2069 LOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
2070 connection->getInputChannelName(), status);
Jeff Brownb6997262010-10-08 22:31:17 -07002071 d->abortBrokenDispatchCycleLocked(currentTime, connection);
Jeff Brown9c3cda02010-06-15 01:31:58 -07002072 d->runCommandsLockedInterruptible();
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002073 return 0; // remove the callback
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002074 }
2075
Jeff Brown3915bb82010-11-05 15:02:16 -07002076 d->finishDispatchCycleLocked(currentTime, connection, handled);
Jeff Brown9c3cda02010-06-15 01:31:58 -07002077 d->runCommandsLockedInterruptible();
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002078 return 1;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002079 } // release lock
2080}
2081
Jeff Brownb6997262010-10-08 22:31:17 -07002082void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
2083 InputState::CancelationOptions options, const char* reason) {
2084 for (size_t i = 0; i < mConnectionsByReceiveFd.size(); i++) {
2085 synthesizeCancelationEventsForConnectionLocked(
2086 mConnectionsByReceiveFd.valueAt(i), options, reason);
2087 }
2088}
2089
2090void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
2091 const sp<InputChannel>& channel, InputState::CancelationOptions options,
2092 const char* reason) {
2093 ssize_t index = getConnectionIndexLocked(channel);
2094 if (index >= 0) {
2095 synthesizeCancelationEventsForConnectionLocked(
2096 mConnectionsByReceiveFd.valueAt(index), options, reason);
2097 }
2098}
2099
2100void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
2101 const sp<Connection>& connection, InputState::CancelationOptions options,
2102 const char* reason) {
2103 nsecs_t currentTime = now();
2104
2105 mTempCancelationEvents.clear();
2106 connection->inputState.synthesizeCancelationEvents(currentTime, & mAllocator,
2107 mTempCancelationEvents, options);
2108
2109 if (! mTempCancelationEvents.isEmpty()
2110 && connection->status != Connection::STATUS_BROKEN) {
2111#if DEBUG_OUTBOUND_EVENT_DETAILS
2112 LOGD("channel '%s' ~ Synthesized %d cancelation events to bring channel back in sync "
2113 "with reality: %s, options=%d.",
2114 connection->getInputChannelName(), mTempCancelationEvents.size(), reason, options);
2115#endif
2116 for (size_t i = 0; i < mTempCancelationEvents.size(); i++) {
2117 EventEntry* cancelationEventEntry = mTempCancelationEvents.itemAt(i);
2118 switch (cancelationEventEntry->type) {
2119 case EventEntry::TYPE_KEY:
2120 logOutboundKeyDetailsLocked("cancel - ",
2121 static_cast<KeyEntry*>(cancelationEventEntry));
2122 break;
2123 case EventEntry::TYPE_MOTION:
2124 logOutboundMotionDetailsLocked("cancel - ",
2125 static_cast<MotionEntry*>(cancelationEventEntry));
2126 break;
2127 }
2128
2129 int32_t xOffset, yOffset;
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002130 float scaleFactor;
Jeff Brownb6997262010-10-08 22:31:17 -07002131 const InputWindow* window = getWindowLocked(connection->inputChannel);
2132 if (window) {
2133 xOffset = -window->frameLeft;
2134 yOffset = -window->frameTop;
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002135 scaleFactor = window->scaleFactor;
Jeff Brownb6997262010-10-08 22:31:17 -07002136 } else {
2137 xOffset = 0;
2138 yOffset = 0;
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002139 scaleFactor = 1.0f;
Jeff Brownb6997262010-10-08 22:31:17 -07002140 }
2141
2142 DispatchEntry* cancelationDispatchEntry =
2143 mAllocator.obtainDispatchEntry(cancelationEventEntry, // increments ref
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002144 0, xOffset, yOffset, scaleFactor);
Jeff Brownb6997262010-10-08 22:31:17 -07002145 connection->outboundQueue.enqueueAtTail(cancelationDispatchEntry);
2146
2147 mAllocator.releaseEventEntry(cancelationEventEntry);
2148 }
2149
2150 if (!connection->outboundQueue.headSentinel.next->inProgress) {
2151 startDispatchCycleLocked(currentTime, connection);
2152 }
2153 }
2154}
2155
Jeff Brown01ce2e92010-09-26 22:20:12 -07002156InputDispatcher::MotionEntry*
2157InputDispatcher::splitMotionEvent(const MotionEntry* originalMotionEntry, BitSet32 pointerIds) {
2158 assert(pointerIds.value != 0);
2159
2160 uint32_t splitPointerIndexMap[MAX_POINTERS];
2161 int32_t splitPointerIds[MAX_POINTERS];
2162 PointerCoords splitPointerCoords[MAX_POINTERS];
2163
2164 uint32_t originalPointerCount = originalMotionEntry->pointerCount;
2165 uint32_t splitPointerCount = 0;
2166
2167 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
2168 originalPointerIndex++) {
2169 int32_t pointerId = uint32_t(originalMotionEntry->pointerIds[originalPointerIndex]);
2170 if (pointerIds.hasBit(pointerId)) {
2171 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
2172 splitPointerIds[splitPointerCount] = pointerId;
2173 splitPointerCoords[splitPointerCount] =
2174 originalMotionEntry->firstSample.pointerCoords[originalPointerIndex];
2175 splitPointerCount += 1;
2176 }
2177 }
Jeff Brown58a2da82011-01-25 16:02:22 -08002178
2179 if (splitPointerCount != pointerIds.count()) {
2180 // This is bad. We are missing some of the pointers that we expected to deliver.
2181 // Most likely this indicates that we received an ACTION_MOVE events that has
2182 // different pointer ids than we expected based on the previous ACTION_DOWN
2183 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
2184 // in this way.
2185 LOGW("Dropping split motion event because the pointer count is %d but "
2186 "we expected there to be %d pointers. This probably means we received "
2187 "a broken sequence of pointer ids from the input device.",
2188 splitPointerCount, pointerIds.count());
2189 return NULL;
2190 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07002191
2192 int32_t action = originalMotionEntry->action;
2193 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
2194 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
2195 || maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2196 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
2197 int32_t pointerId = originalMotionEntry->pointerIds[originalPointerIndex];
2198 if (pointerIds.hasBit(pointerId)) {
2199 if (pointerIds.count() == 1) {
2200 // The first/last pointer went down/up.
2201 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
2202 ? AMOTION_EVENT_ACTION_DOWN : AMOTION_EVENT_ACTION_UP;
Jeff Brown9a01d052010-09-27 16:35:11 -07002203 } else {
2204 // A secondary pointer went down/up.
2205 uint32_t splitPointerIndex = 0;
2206 while (pointerId != splitPointerIds[splitPointerIndex]) {
2207 splitPointerIndex += 1;
2208 }
2209 action = maskedAction | (splitPointerIndex
2210 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002211 }
2212 } else {
2213 // An unrelated pointer changed.
2214 action = AMOTION_EVENT_ACTION_MOVE;
2215 }
2216 }
2217
2218 MotionEntry* splitMotionEntry = mAllocator.obtainMotionEntry(
2219 originalMotionEntry->eventTime,
2220 originalMotionEntry->deviceId,
2221 originalMotionEntry->source,
2222 originalMotionEntry->policyFlags,
2223 action,
2224 originalMotionEntry->flags,
2225 originalMotionEntry->metaState,
2226 originalMotionEntry->edgeFlags,
2227 originalMotionEntry->xPrecision,
2228 originalMotionEntry->yPrecision,
2229 originalMotionEntry->downTime,
2230 splitPointerCount, splitPointerIds, splitPointerCoords);
2231
2232 for (MotionSample* originalMotionSample = originalMotionEntry->firstSample.next;
2233 originalMotionSample != NULL; originalMotionSample = originalMotionSample->next) {
2234 for (uint32_t splitPointerIndex = 0; splitPointerIndex < splitPointerCount;
2235 splitPointerIndex++) {
2236 uint32_t originalPointerIndex = splitPointerIndexMap[splitPointerIndex];
2237 splitPointerCoords[splitPointerIndex] =
2238 originalMotionSample->pointerCoords[originalPointerIndex];
2239 }
2240
2241 mAllocator.appendMotionSample(splitMotionEntry, originalMotionSample->eventTime,
2242 splitPointerCoords);
2243 }
2244
2245 return splitMotionEntry;
2246}
2247
Jeff Brown9c3cda02010-06-15 01:31:58 -07002248void InputDispatcher::notifyConfigurationChanged(nsecs_t eventTime) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002249#if DEBUG_INBOUND_EVENT_DETAILS
Jeff Brown9c3cda02010-06-15 01:31:58 -07002250 LOGD("notifyConfigurationChanged - eventTime=%lld", eventTime);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002251#endif
2252
Jeff Brownb88102f2010-09-08 11:49:43 -07002253 bool needWake;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002254 { // acquire lock
2255 AutoMutex _l(mLock);
2256
Jeff Brown7fbdc842010-06-17 20:52:56 -07002257 ConfigurationChangedEntry* newEntry = mAllocator.obtainConfigurationChangedEntry(eventTime);
Jeff Brownb88102f2010-09-08 11:49:43 -07002258 needWake = enqueueInboundEventLocked(newEntry);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002259 } // release lock
2260
Jeff Brownb88102f2010-09-08 11:49:43 -07002261 if (needWake) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002262 mLooper->wake();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002263 }
2264}
2265
Jeff Brown58a2da82011-01-25 16:02:22 -08002266void InputDispatcher::notifyKey(nsecs_t eventTime, int32_t deviceId, uint32_t source,
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002267 uint32_t policyFlags, int32_t action, int32_t flags,
2268 int32_t keyCode, int32_t scanCode, int32_t metaState, nsecs_t downTime) {
2269#if DEBUG_INBOUND_EVENT_DETAILS
Jeff Brown90655042010-12-02 13:50:46 -08002270 LOGD("notifyKey - eventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, action=0x%x, "
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002271 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%lld",
Jeff Brownc5ed5912010-07-14 18:48:53 -07002272 eventTime, deviceId, source, policyFlags, action, flags,
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002273 keyCode, scanCode, metaState, downTime);
2274#endif
Jeff Brown01ce2e92010-09-26 22:20:12 -07002275 if (! validateKeyEvent(action)) {
2276 return;
2277 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002278
Jeff Brown1f245102010-11-18 20:53:46 -08002279 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
2280 policyFlags |= POLICY_FLAG_VIRTUAL;
2281 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
2282 }
Jeff Brown924c4d42011-03-07 16:40:47 -08002283 if (policyFlags & POLICY_FLAG_ALT) {
2284 metaState |= AMETA_ALT_ON | AMETA_ALT_LEFT_ON;
2285 }
2286 if (policyFlags & POLICY_FLAG_ALT_GR) {
2287 metaState |= AMETA_ALT_ON | AMETA_ALT_RIGHT_ON;
2288 }
2289 if (policyFlags & POLICY_FLAG_SHIFT) {
2290 metaState |= AMETA_SHIFT_ON | AMETA_SHIFT_LEFT_ON;
2291 }
2292 if (policyFlags & POLICY_FLAG_CAPS_LOCK) {
2293 metaState |= AMETA_CAPS_LOCK_ON;
2294 }
2295 if (policyFlags & POLICY_FLAG_FUNCTION) {
2296 metaState |= AMETA_FUNCTION_ON;
2297 }
Jeff Brown1f245102010-11-18 20:53:46 -08002298
Jeff Browne20c9e02010-10-11 14:20:19 -07002299 policyFlags |= POLICY_FLAG_TRUSTED;
Jeff Brown1f245102010-11-18 20:53:46 -08002300
2301 KeyEvent event;
2302 event.initialize(deviceId, source, action, flags, keyCode, scanCode,
2303 metaState, 0, downTime, eventTime);
2304
2305 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
2306
2307 if (policyFlags & POLICY_FLAG_WOKE_HERE) {
2308 flags |= AKEY_EVENT_FLAG_WOKE_HERE;
2309 }
Jeff Brownb6997262010-10-08 22:31:17 -07002310
Jeff Brownb88102f2010-09-08 11:49:43 -07002311 bool needWake;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002312 { // acquire lock
2313 AutoMutex _l(mLock);
2314
Jeff Brown7fbdc842010-06-17 20:52:56 -07002315 int32_t repeatCount = 0;
2316 KeyEntry* newEntry = mAllocator.obtainKeyEntry(eventTime,
Jeff Brownc5ed5912010-07-14 18:48:53 -07002317 deviceId, source, policyFlags, action, flags, keyCode, scanCode,
Jeff Brown7fbdc842010-06-17 20:52:56 -07002318 metaState, repeatCount, downTime);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002319
Jeff Brownb88102f2010-09-08 11:49:43 -07002320 needWake = enqueueInboundEventLocked(newEntry);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002321 } // release lock
2322
Jeff Brownb88102f2010-09-08 11:49:43 -07002323 if (needWake) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002324 mLooper->wake();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002325 }
2326}
2327
Jeff Brown58a2da82011-01-25 16:02:22 -08002328void InputDispatcher::notifyMotion(nsecs_t eventTime, int32_t deviceId, uint32_t source,
Jeff Brown85a31762010-09-01 17:01:00 -07002329 uint32_t policyFlags, int32_t action, int32_t flags, int32_t metaState, int32_t edgeFlags,
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002330 uint32_t pointerCount, const int32_t* pointerIds, const PointerCoords* pointerCoords,
2331 float xPrecision, float yPrecision, nsecs_t downTime) {
2332#if DEBUG_INBOUND_EVENT_DETAILS
Jeff Brown90655042010-12-02 13:50:46 -08002333 LOGD("notifyMotion - eventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, "
Jeff Brown85a31762010-09-01 17:01:00 -07002334 "action=0x%x, flags=0x%x, metaState=0x%x, edgeFlags=0x%x, "
2335 "xPrecision=%f, yPrecision=%f, downTime=%lld",
2336 eventTime, deviceId, source, policyFlags, action, flags, metaState, edgeFlags,
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002337 xPrecision, yPrecision, downTime);
2338 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brown8d608662010-08-30 03:02:23 -07002339 LOGD(" Pointer %d: id=%d, x=%f, y=%f, pressure=%f, size=%f, "
Jeff Brown85a31762010-09-01 17:01:00 -07002340 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
Jeff Brown8d608662010-08-30 03:02:23 -07002341 "orientation=%f",
Jeff Brown91c69ab2011-02-14 17:03:18 -08002342 i, pointerIds[i],
Jeff Brownebbd5d12011-02-17 13:01:34 -08002343 pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
2344 pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
2345 pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
2346 pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
2347 pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
2348 pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
2349 pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
2350 pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
2351 pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002352 }
2353#endif
Jeff Brown01ce2e92010-09-26 22:20:12 -07002354 if (! validateMotionEvent(action, pointerCount, pointerIds)) {
2355 return;
2356 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002357
Jeff Browne20c9e02010-10-11 14:20:19 -07002358 policyFlags |= POLICY_FLAG_TRUSTED;
Jeff Brown56194eb2011-03-02 19:23:13 -08002359 mPolicy->interceptMotionBeforeQueueing(eventTime, /*byref*/ policyFlags);
Jeff Brownb6997262010-10-08 22:31:17 -07002360
Jeff Brownb88102f2010-09-08 11:49:43 -07002361 bool needWake;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002362 { // acquire lock
2363 AutoMutex _l(mLock);
2364
2365 // Attempt batching and streaming of move events.
Jeff Browncc0c1592011-02-19 05:07:28 -08002366 if (action == AMOTION_EVENT_ACTION_MOVE
2367 || action == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002368 // BATCHING CASE
2369 //
2370 // Try to append a move sample to the tail of the inbound queue for this device.
2371 // Give up if we encounter a non-move motion event for this device since that
2372 // means we cannot append any new samples until a new motion event has started.
Jeff Brownb88102f2010-09-08 11:49:43 -07002373 for (EventEntry* entry = mInboundQueue.tailSentinel.prev;
2374 entry != & mInboundQueue.headSentinel; entry = entry->prev) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002375 if (entry->type != EventEntry::TYPE_MOTION) {
2376 // Keep looking for motion events.
2377 continue;
2378 }
2379
2380 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
Jeff Brownefd32662011-03-08 15:13:06 -08002381 if (motionEntry->deviceId != deviceId
2382 || motionEntry->source != source) {
2383 // Keep looking for this device and source.
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002384 continue;
2385 }
2386
Jeff Browncc0c1592011-02-19 05:07:28 -08002387 if (motionEntry->action != action
Jeff Brown7fbdc842010-06-17 20:52:56 -07002388 || motionEntry->pointerCount != pointerCount
2389 || motionEntry->isInjected()) {
Jeff Brownefd32662011-03-08 15:13:06 -08002390 // Last motion event in the queue for this device and source is
2391 // not compatible for appending new samples. Stop here.
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002392 goto NoBatchingOrStreaming;
2393 }
2394
2395 // The last motion event is a move and is compatible for appending.
Jeff Brown9c3cda02010-06-15 01:31:58 -07002396 // Do the batching magic.
Jeff Brown7fbdc842010-06-17 20:52:56 -07002397 mAllocator.appendMotionSample(motionEntry, eventTime, pointerCoords);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002398#if DEBUG_BATCHING
2399 LOGD("Appended motion sample onto batch for most recent "
2400 "motion event for this device in the inbound queue.");
2401#endif
Jeff Brown9c3cda02010-06-15 01:31:58 -07002402 return; // done!
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002403 }
2404
2405 // STREAMING CASE
2406 //
2407 // There is no pending motion event (of any kind) for this device in the inbound queue.
Jeff Brown519e0242010-09-15 15:18:56 -07002408 // Search the outbound queue for the current foreground targets to find a dispatched
2409 // motion event that is still in progress. If found, then, appen the new sample to
2410 // that event and push it out to all current targets. The logic in
2411 // prepareDispatchCycleLocked takes care of the case where some targets may
2412 // already have consumed the motion event by starting a new dispatch cycle if needed.
Jeff Brown9c3cda02010-06-15 01:31:58 -07002413 if (mCurrentInputTargetsValid) {
Jeff Brown519e0242010-09-15 15:18:56 -07002414 for (size_t i = 0; i < mCurrentInputTargets.size(); i++) {
2415 const InputTarget& inputTarget = mCurrentInputTargets[i];
2416 if ((inputTarget.flags & InputTarget::FLAG_FOREGROUND) == 0) {
2417 // Skip non-foreground targets. We only want to stream if there is at
2418 // least one foreground target whose dispatch is still in progress.
2419 continue;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002420 }
Jeff Brown519e0242010-09-15 15:18:56 -07002421
2422 ssize_t connectionIndex = getConnectionIndexLocked(inputTarget.inputChannel);
2423 if (connectionIndex < 0) {
2424 // Connection must no longer be valid.
2425 continue;
2426 }
2427
2428 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
2429 if (connection->outboundQueue.isEmpty()) {
2430 // This foreground target has an empty outbound queue.
2431 continue;
2432 }
2433
2434 DispatchEntry* dispatchEntry = connection->outboundQueue.headSentinel.next;
2435 if (! dispatchEntry->inProgress
Jeff Brown01ce2e92010-09-26 22:20:12 -07002436 || dispatchEntry->eventEntry->type != EventEntry::TYPE_MOTION
2437 || dispatchEntry->isSplit()) {
2438 // No motion event is being dispatched, or it is being split across
2439 // windows in which case we cannot stream.
Jeff Brown519e0242010-09-15 15:18:56 -07002440 continue;
2441 }
2442
2443 MotionEntry* motionEntry = static_cast<MotionEntry*>(
2444 dispatchEntry->eventEntry);
Jeff Browncc0c1592011-02-19 05:07:28 -08002445 if (motionEntry->action != action
Jeff Brown519e0242010-09-15 15:18:56 -07002446 || motionEntry->deviceId != deviceId
Jeff Brown58a2da82011-01-25 16:02:22 -08002447 || motionEntry->source != source
Jeff Brown519e0242010-09-15 15:18:56 -07002448 || motionEntry->pointerCount != pointerCount
2449 || motionEntry->isInjected()) {
2450 // The motion event is not compatible with this move.
2451 continue;
2452 }
2453
2454 // Hurray! This foreground target is currently dispatching a move event
2455 // that we can stream onto. Append the motion sample and resume dispatch.
2456 mAllocator.appendMotionSample(motionEntry, eventTime, pointerCoords);
2457#if DEBUG_BATCHING
2458 LOGD("Appended motion sample onto batch for most recently dispatched "
2459 "motion event for this device in the outbound queues. "
2460 "Attempting to stream the motion sample.");
2461#endif
2462 nsecs_t currentTime = now();
2463 dispatchEventToCurrentInputTargetsLocked(currentTime, motionEntry,
2464 true /*resumeWithAppendedMotionSample*/);
2465
2466 runCommandsLockedInterruptible();
2467 return; // done!
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002468 }
2469 }
2470
2471NoBatchingOrStreaming:;
2472 }
2473
2474 // Just enqueue a new motion event.
Jeff Brown7fbdc842010-06-17 20:52:56 -07002475 MotionEntry* newEntry = mAllocator.obtainMotionEntry(eventTime,
Jeff Brown85a31762010-09-01 17:01:00 -07002476 deviceId, source, policyFlags, action, flags, metaState, edgeFlags,
Jeff Brown7fbdc842010-06-17 20:52:56 -07002477 xPrecision, yPrecision, downTime,
2478 pointerCount, pointerIds, pointerCoords);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002479
Jeff Brownb88102f2010-09-08 11:49:43 -07002480 needWake = enqueueInboundEventLocked(newEntry);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002481 } // release lock
2482
Jeff Brownb88102f2010-09-08 11:49:43 -07002483 if (needWake) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002484 mLooper->wake();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002485 }
2486}
2487
Jeff Brownb6997262010-10-08 22:31:17 -07002488void InputDispatcher::notifySwitch(nsecs_t when, int32_t switchCode, int32_t switchValue,
2489 uint32_t policyFlags) {
2490#if DEBUG_INBOUND_EVENT_DETAILS
2491 LOGD("notifySwitch - switchCode=%d, switchValue=%d, policyFlags=0x%x",
2492 switchCode, switchValue, policyFlags);
2493#endif
2494
Jeff Browne20c9e02010-10-11 14:20:19 -07002495 policyFlags |= POLICY_FLAG_TRUSTED;
Jeff Brownb6997262010-10-08 22:31:17 -07002496 mPolicy->notifySwitch(when, switchCode, switchValue, policyFlags);
2497}
2498
Jeff Brown7fbdc842010-06-17 20:52:56 -07002499int32_t InputDispatcher::injectInputEvent(const InputEvent* event,
Jeff Brown6ec402b2010-07-28 15:48:59 -07002500 int32_t injectorPid, int32_t injectorUid, int32_t syncMode, int32_t timeoutMillis) {
Jeff Brown7fbdc842010-06-17 20:52:56 -07002501#if DEBUG_INBOUND_EVENT_DETAILS
2502 LOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Jeff Brown6ec402b2010-07-28 15:48:59 -07002503 "syncMode=%d, timeoutMillis=%d",
2504 event->getType(), injectorPid, injectorUid, syncMode, timeoutMillis);
Jeff Brown7fbdc842010-06-17 20:52:56 -07002505#endif
2506
2507 nsecs_t endTime = now() + milliseconds_to_nanoseconds(timeoutMillis);
Jeff Browne20c9e02010-10-11 14:20:19 -07002508
2509 uint32_t policyFlags = POLICY_FLAG_INJECTED;
2510 if (hasInjectionPermission(injectorPid, injectorUid)) {
2511 policyFlags |= POLICY_FLAG_TRUSTED;
2512 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07002513
Jeff Brownb6997262010-10-08 22:31:17 -07002514 EventEntry* injectedEntry;
2515 switch (event->getType()) {
2516 case AINPUT_EVENT_TYPE_KEY: {
2517 const KeyEvent* keyEvent = static_cast<const KeyEvent*>(event);
2518 int32_t action = keyEvent->getAction();
2519 if (! validateKeyEvent(action)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07002520 return INPUT_EVENT_INJECTION_FAILED;
2521 }
2522
Jeff Brownb6997262010-10-08 22:31:17 -07002523 int32_t flags = keyEvent->getFlags();
Jeff Brown1f245102010-11-18 20:53:46 -08002524 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
2525 policyFlags |= POLICY_FLAG_VIRTUAL;
2526 }
2527
2528 mPolicy->interceptKeyBeforeQueueing(keyEvent, /*byref*/ policyFlags);
2529
2530 if (policyFlags & POLICY_FLAG_WOKE_HERE) {
2531 flags |= AKEY_EVENT_FLAG_WOKE_HERE;
2532 }
Jeff Brown6ec402b2010-07-28 15:48:59 -07002533
Jeff Brownb6997262010-10-08 22:31:17 -07002534 mLock.lock();
Jeff Brown1f245102010-11-18 20:53:46 -08002535 injectedEntry = mAllocator.obtainKeyEntry(keyEvent->getEventTime(),
2536 keyEvent->getDeviceId(), keyEvent->getSource(),
2537 policyFlags, action, flags,
2538 keyEvent->getKeyCode(), keyEvent->getScanCode(), keyEvent->getMetaState(),
Jeff Brownb6997262010-10-08 22:31:17 -07002539 keyEvent->getRepeatCount(), keyEvent->getDownTime());
2540 break;
2541 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07002542
Jeff Brownb6997262010-10-08 22:31:17 -07002543 case AINPUT_EVENT_TYPE_MOTION: {
2544 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
2545 int32_t action = motionEvent->getAction();
2546 size_t pointerCount = motionEvent->getPointerCount();
2547 const int32_t* pointerIds = motionEvent->getPointerIds();
2548 if (! validateMotionEvent(action, pointerCount, pointerIds)) {
2549 return INPUT_EVENT_INJECTION_FAILED;
2550 }
2551
2552 nsecs_t eventTime = motionEvent->getEventTime();
Jeff Brown56194eb2011-03-02 19:23:13 -08002553 mPolicy->interceptMotionBeforeQueueing(eventTime, /*byref*/ policyFlags);
Jeff Brownb6997262010-10-08 22:31:17 -07002554
2555 mLock.lock();
2556 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
2557 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
2558 MotionEntry* motionEntry = mAllocator.obtainMotionEntry(*sampleEventTimes,
2559 motionEvent->getDeviceId(), motionEvent->getSource(), policyFlags,
2560 action, motionEvent->getFlags(),
2561 motionEvent->getMetaState(), motionEvent->getEdgeFlags(),
2562 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
2563 motionEvent->getDownTime(), uint32_t(pointerCount),
2564 pointerIds, samplePointerCoords);
2565 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
2566 sampleEventTimes += 1;
2567 samplePointerCoords += pointerCount;
2568 mAllocator.appendMotionSample(motionEntry, *sampleEventTimes, samplePointerCoords);
2569 }
2570 injectedEntry = motionEntry;
2571 break;
2572 }
2573
2574 default:
2575 LOGW("Cannot inject event of type %d", event->getType());
2576 return INPUT_EVENT_INJECTION_FAILED;
2577 }
2578
2579 InjectionState* injectionState = mAllocator.obtainInjectionState(injectorPid, injectorUid);
2580 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
2581 injectionState->injectionIsAsync = true;
2582 }
2583
2584 injectionState->refCount += 1;
2585 injectedEntry->injectionState = injectionState;
2586
2587 bool needWake = enqueueInboundEventLocked(injectedEntry);
2588 mLock.unlock();
Jeff Brown7fbdc842010-06-17 20:52:56 -07002589
Jeff Brownb88102f2010-09-08 11:49:43 -07002590 if (needWake) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002591 mLooper->wake();
Jeff Brown7fbdc842010-06-17 20:52:56 -07002592 }
2593
2594 int32_t injectionResult;
2595 { // acquire lock
2596 AutoMutex _l(mLock);
2597
Jeff Brown6ec402b2010-07-28 15:48:59 -07002598 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
2599 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
2600 } else {
2601 for (;;) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002602 injectionResult = injectionState->injectionResult;
Jeff Brown6ec402b2010-07-28 15:48:59 -07002603 if (injectionResult != INPUT_EVENT_INJECTION_PENDING) {
2604 break;
2605 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07002606
Jeff Brown7fbdc842010-06-17 20:52:56 -07002607 nsecs_t remainingTimeout = endTime - now();
2608 if (remainingTimeout <= 0) {
Jeff Brown6ec402b2010-07-28 15:48:59 -07002609#if DEBUG_INJECTION
2610 LOGD("injectInputEvent - Timed out waiting for injection result "
2611 "to become available.");
2612#endif
Jeff Brown7fbdc842010-06-17 20:52:56 -07002613 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
2614 break;
2615 }
2616
Jeff Brown6ec402b2010-07-28 15:48:59 -07002617 mInjectionResultAvailableCondition.waitRelative(mLock, remainingTimeout);
2618 }
2619
2620 if (injectionResult == INPUT_EVENT_INJECTION_SUCCEEDED
2621 && syncMode == INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002622 while (injectionState->pendingForegroundDispatches != 0) {
Jeff Brown6ec402b2010-07-28 15:48:59 -07002623#if DEBUG_INJECTION
Jeff Brown519e0242010-09-15 15:18:56 -07002624 LOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
Jeff Brown01ce2e92010-09-26 22:20:12 -07002625 injectionState->pendingForegroundDispatches);
Jeff Brown6ec402b2010-07-28 15:48:59 -07002626#endif
2627 nsecs_t remainingTimeout = endTime - now();
2628 if (remainingTimeout <= 0) {
2629#if DEBUG_INJECTION
Jeff Brown519e0242010-09-15 15:18:56 -07002630 LOGD("injectInputEvent - Timed out waiting for pending foreground "
Jeff Brown6ec402b2010-07-28 15:48:59 -07002631 "dispatches to finish.");
2632#endif
2633 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
2634 break;
2635 }
2636
2637 mInjectionSyncFinishedCondition.waitRelative(mLock, remainingTimeout);
2638 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07002639 }
2640 }
2641
Jeff Brown01ce2e92010-09-26 22:20:12 -07002642 mAllocator.releaseInjectionState(injectionState);
Jeff Brown7fbdc842010-06-17 20:52:56 -07002643 } // release lock
2644
Jeff Brown6ec402b2010-07-28 15:48:59 -07002645#if DEBUG_INJECTION
2646 LOGD("injectInputEvent - Finished with result %d. "
2647 "injectorPid=%d, injectorUid=%d",
2648 injectionResult, injectorPid, injectorUid);
2649#endif
2650
Jeff Brown7fbdc842010-06-17 20:52:56 -07002651 return injectionResult;
2652}
2653
Jeff Brownb6997262010-10-08 22:31:17 -07002654bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
2655 return injectorUid == 0
2656 || mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
2657}
2658
Jeff Brown7fbdc842010-06-17 20:52:56 -07002659void InputDispatcher::setInjectionResultLocked(EventEntry* entry, int32_t injectionResult) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002660 InjectionState* injectionState = entry->injectionState;
2661 if (injectionState) {
Jeff Brown7fbdc842010-06-17 20:52:56 -07002662#if DEBUG_INJECTION
2663 LOGD("Setting input event injection result to %d. "
2664 "injectorPid=%d, injectorUid=%d",
Jeff Brown01ce2e92010-09-26 22:20:12 -07002665 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
Jeff Brown7fbdc842010-06-17 20:52:56 -07002666#endif
2667
Jeff Brown01ce2e92010-09-26 22:20:12 -07002668 if (injectionState->injectionIsAsync) {
Jeff Brown6ec402b2010-07-28 15:48:59 -07002669 // Log the outcome since the injector did not wait for the injection result.
2670 switch (injectionResult) {
2671 case INPUT_EVENT_INJECTION_SUCCEEDED:
2672 LOGV("Asynchronous input event injection succeeded.");
2673 break;
2674 case INPUT_EVENT_INJECTION_FAILED:
2675 LOGW("Asynchronous input event injection failed.");
2676 break;
2677 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
2678 LOGW("Asynchronous input event injection permission denied.");
2679 break;
2680 case INPUT_EVENT_INJECTION_TIMED_OUT:
2681 LOGW("Asynchronous input event injection timed out.");
2682 break;
2683 }
2684 }
2685
Jeff Brown01ce2e92010-09-26 22:20:12 -07002686 injectionState->injectionResult = injectionResult;
Jeff Brown7fbdc842010-06-17 20:52:56 -07002687 mInjectionResultAvailableCondition.broadcast();
2688 }
2689}
2690
Jeff Brown01ce2e92010-09-26 22:20:12 -07002691void InputDispatcher::incrementPendingForegroundDispatchesLocked(EventEntry* entry) {
2692 InjectionState* injectionState = entry->injectionState;
2693 if (injectionState) {
2694 injectionState->pendingForegroundDispatches += 1;
2695 }
2696}
2697
Jeff Brown519e0242010-09-15 15:18:56 -07002698void InputDispatcher::decrementPendingForegroundDispatchesLocked(EventEntry* entry) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002699 InjectionState* injectionState = entry->injectionState;
2700 if (injectionState) {
2701 injectionState->pendingForegroundDispatches -= 1;
Jeff Brown6ec402b2010-07-28 15:48:59 -07002702
Jeff Brown01ce2e92010-09-26 22:20:12 -07002703 if (injectionState->pendingForegroundDispatches == 0) {
2704 mInjectionSyncFinishedCondition.broadcast();
2705 }
Jeff Brownb88102f2010-09-08 11:49:43 -07002706 }
2707}
2708
Jeff Brown01ce2e92010-09-26 22:20:12 -07002709const InputWindow* InputDispatcher::getWindowLocked(const sp<InputChannel>& inputChannel) {
2710 for (size_t i = 0; i < mWindows.size(); i++) {
2711 const InputWindow* window = & mWindows[i];
2712 if (window->inputChannel == inputChannel) {
2713 return window;
2714 }
2715 }
2716 return NULL;
2717}
2718
Jeff Brownb88102f2010-09-08 11:49:43 -07002719void InputDispatcher::setInputWindows(const Vector<InputWindow>& inputWindows) {
2720#if DEBUG_FOCUS
2721 LOGD("setInputWindows");
2722#endif
2723 { // acquire lock
2724 AutoMutex _l(mLock);
2725
Jeff Brown01ce2e92010-09-26 22:20:12 -07002726 // Clear old window pointers.
Jeff Brownb6997262010-10-08 22:31:17 -07002727 sp<InputChannel> oldFocusedWindowChannel;
2728 if (mFocusedWindow) {
2729 oldFocusedWindowChannel = mFocusedWindow->inputChannel;
2730 mFocusedWindow = NULL;
2731 }
2732
Jeff Brownb88102f2010-09-08 11:49:43 -07002733 mWindows.clear();
Jeff Brown2a95c2a2010-09-16 12:31:46 -07002734
2735 // Loop over new windows and rebuild the necessary window pointers for
2736 // tracking focus and touch.
Jeff Brownb88102f2010-09-08 11:49:43 -07002737 mWindows.appendVector(inputWindows);
2738
2739 size_t numWindows = mWindows.size();
2740 for (size_t i = 0; i < numWindows; i++) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002741 const InputWindow* window = & mWindows.itemAt(i);
Jeff Brownb88102f2010-09-08 11:49:43 -07002742 if (window->hasFocus) {
2743 mFocusedWindow = window;
Jeff Brown01ce2e92010-09-26 22:20:12 -07002744 break;
Jeff Brownb88102f2010-09-08 11:49:43 -07002745 }
2746 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07002747
Jeff Brownb6997262010-10-08 22:31:17 -07002748 if (oldFocusedWindowChannel != NULL) {
2749 if (!mFocusedWindow || oldFocusedWindowChannel != mFocusedWindow->inputChannel) {
2750#if DEBUG_FOCUS
2751 LOGD("Focus left window: %s",
2752 oldFocusedWindowChannel->getName().string());
2753#endif
2754 synthesizeCancelationEventsForInputChannelLocked(oldFocusedWindowChannel,
2755 InputState::CANCEL_NON_POINTER_EVENTS, "focus left window");
2756 oldFocusedWindowChannel.clear();
2757 }
2758 }
2759 if (mFocusedWindow && oldFocusedWindowChannel == NULL) {
2760#if DEBUG_FOCUS
2761 LOGD("Focus entered window: %s",
2762 mFocusedWindow->inputChannel->getName().string());
2763#endif
2764 }
2765
Jeff Brown01ce2e92010-09-26 22:20:12 -07002766 for (size_t i = 0; i < mTouchState.windows.size(); ) {
2767 TouchedWindow& touchedWindow = mTouchState.windows.editItemAt(i);
2768 const InputWindow* window = getWindowLocked(touchedWindow.channel);
2769 if (window) {
2770 touchedWindow.window = window;
2771 i += 1;
2772 } else {
Jeff Brownb6997262010-10-08 22:31:17 -07002773#if DEBUG_FOCUS
2774 LOGD("Touched window was removed: %s", touchedWindow.channel->getName().string());
2775#endif
Jeff Brownb6997262010-10-08 22:31:17 -07002776 synthesizeCancelationEventsForInputChannelLocked(touchedWindow.channel,
2777 InputState::CANCEL_POINTER_EVENTS, "touched window was removed");
Jeff Brownaf48cae2010-10-15 16:20:51 -07002778 mTouchState.windows.removeAt(i);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002779 }
2780 }
Jeff Brownb88102f2010-09-08 11:49:43 -07002781
Jeff Brownb88102f2010-09-08 11:49:43 -07002782#if DEBUG_FOCUS
Jeff Brownb6997262010-10-08 22:31:17 -07002783 //logDispatchStateLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -07002784#endif
2785 } // release lock
2786
2787 // Wake up poll loop since it may need to make new input dispatching choices.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002788 mLooper->wake();
Jeff Brownb88102f2010-09-08 11:49:43 -07002789}
2790
2791void InputDispatcher::setFocusedApplication(const InputApplication* inputApplication) {
2792#if DEBUG_FOCUS
2793 LOGD("setFocusedApplication");
2794#endif
2795 { // acquire lock
2796 AutoMutex _l(mLock);
2797
2798 releaseFocusedApplicationLocked();
2799
2800 if (inputApplication) {
2801 mFocusedApplicationStorage = *inputApplication;
2802 mFocusedApplication = & mFocusedApplicationStorage;
2803 }
2804
2805#if DEBUG_FOCUS
Jeff Brownb6997262010-10-08 22:31:17 -07002806 //logDispatchStateLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -07002807#endif
2808 } // release lock
2809
2810 // Wake up poll loop since it may need to make new input dispatching choices.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002811 mLooper->wake();
Jeff Brownb88102f2010-09-08 11:49:43 -07002812}
2813
2814void InputDispatcher::releaseFocusedApplicationLocked() {
2815 if (mFocusedApplication) {
2816 mFocusedApplication = NULL;
Jeff Brown928e0542011-01-10 11:17:36 -08002817 mFocusedApplicationStorage.inputApplicationHandle.clear();
Jeff Brownb88102f2010-09-08 11:49:43 -07002818 }
2819}
2820
2821void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
2822#if DEBUG_FOCUS
2823 LOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
2824#endif
2825
2826 bool changed;
2827 { // acquire lock
2828 AutoMutex _l(mLock);
2829
2830 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
Jeff Brown120a4592010-10-27 18:43:51 -07002831 if (mDispatchFrozen && !frozen) {
Jeff Brownb88102f2010-09-08 11:49:43 -07002832 resetANRTimeoutsLocked();
2833 }
2834
Jeff Brown120a4592010-10-27 18:43:51 -07002835 if (mDispatchEnabled && !enabled) {
2836 resetAndDropEverythingLocked("dispatcher is being disabled");
2837 }
2838
Jeff Brownb88102f2010-09-08 11:49:43 -07002839 mDispatchEnabled = enabled;
2840 mDispatchFrozen = frozen;
2841 changed = true;
2842 } else {
2843 changed = false;
2844 }
2845
2846#if DEBUG_FOCUS
Jeff Brownb6997262010-10-08 22:31:17 -07002847 //logDispatchStateLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -07002848#endif
2849 } // release lock
2850
2851 if (changed) {
2852 // Wake up poll loop since it may need to make new input dispatching choices.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002853 mLooper->wake();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002854 }
2855}
2856
Jeff Browne6504122010-09-27 14:52:15 -07002857bool InputDispatcher::transferTouchFocus(const sp<InputChannel>& fromChannel,
2858 const sp<InputChannel>& toChannel) {
2859#if DEBUG_FOCUS
2860 LOGD("transferTouchFocus: fromChannel=%s, toChannel=%s",
2861 fromChannel->getName().string(), toChannel->getName().string());
2862#endif
2863 { // acquire lock
2864 AutoMutex _l(mLock);
2865
2866 const InputWindow* fromWindow = getWindowLocked(fromChannel);
2867 const InputWindow* toWindow = getWindowLocked(toChannel);
2868 if (! fromWindow || ! toWindow) {
2869#if DEBUG_FOCUS
2870 LOGD("Cannot transfer focus because from or to window not found.");
2871#endif
2872 return false;
2873 }
2874 if (fromWindow == toWindow) {
2875#if DEBUG_FOCUS
2876 LOGD("Trivial transfer to same window.");
2877#endif
2878 return true;
2879 }
2880
2881 bool found = false;
2882 for (size_t i = 0; i < mTouchState.windows.size(); i++) {
2883 const TouchedWindow& touchedWindow = mTouchState.windows[i];
2884 if (touchedWindow.window == fromWindow) {
2885 int32_t oldTargetFlags = touchedWindow.targetFlags;
2886 BitSet32 pointerIds = touchedWindow.pointerIds;
2887
2888 mTouchState.windows.removeAt(i);
2889
Jeff Brown46e75292010-11-10 16:53:45 -08002890 int32_t newTargetFlags = oldTargetFlags
2891 & (InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_SPLIT);
Jeff Browne6504122010-09-27 14:52:15 -07002892 mTouchState.addOrUpdateWindow(toWindow, newTargetFlags, pointerIds);
2893
2894 found = true;
2895 break;
2896 }
2897 }
2898
2899 if (! found) {
2900#if DEBUG_FOCUS
2901 LOGD("Focus transfer failed because from window did not have focus.");
2902#endif
2903 return false;
2904 }
2905
Jeff Brown9c9f1a32010-10-11 18:32:20 -07002906 ssize_t fromConnectionIndex = getConnectionIndexLocked(fromChannel);
2907 ssize_t toConnectionIndex = getConnectionIndexLocked(toChannel);
2908 if (fromConnectionIndex >= 0 && toConnectionIndex >= 0) {
2909 sp<Connection> fromConnection = mConnectionsByReceiveFd.valueAt(fromConnectionIndex);
2910 sp<Connection> toConnection = mConnectionsByReceiveFd.valueAt(toConnectionIndex);
2911
2912 fromConnection->inputState.copyPointerStateTo(toConnection->inputState);
2913 synthesizeCancelationEventsForConnectionLocked(fromConnection,
2914 InputState::CANCEL_POINTER_EVENTS,
2915 "transferring touch focus from this window to another window");
2916 }
2917
Jeff Browne6504122010-09-27 14:52:15 -07002918#if DEBUG_FOCUS
2919 logDispatchStateLocked();
2920#endif
2921 } // release lock
2922
2923 // Wake up poll loop since it may need to make new input dispatching choices.
2924 mLooper->wake();
2925 return true;
2926}
2927
Jeff Brown120a4592010-10-27 18:43:51 -07002928void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
2929#if DEBUG_FOCUS
2930 LOGD("Resetting and dropping all events (%s).", reason);
2931#endif
2932
2933 synthesizeCancelationEventsForAllConnectionsLocked(InputState::CANCEL_ALL_EVENTS, reason);
2934
2935 resetKeyRepeatLocked();
2936 releasePendingEventLocked();
2937 drainInboundQueueLocked();
2938 resetTargetsLocked();
2939
2940 mTouchState.reset();
2941}
2942
Jeff Brownb88102f2010-09-08 11:49:43 -07002943void InputDispatcher::logDispatchStateLocked() {
2944 String8 dump;
2945 dumpDispatchStateLocked(dump);
Jeff Brown2a95c2a2010-09-16 12:31:46 -07002946
2947 char* text = dump.lockBuffer(dump.size());
2948 char* start = text;
2949 while (*start != '\0') {
2950 char* end = strchr(start, '\n');
2951 if (*end == '\n') {
2952 *(end++) = '\0';
2953 }
2954 LOGD("%s", start);
2955 start = end;
2956 }
Jeff Brownb88102f2010-09-08 11:49:43 -07002957}
2958
2959void InputDispatcher::dumpDispatchStateLocked(String8& dump) {
Jeff Brownf2f487182010-10-01 17:46:21 -07002960 dump.appendFormat(INDENT "DispatchEnabled: %d\n", mDispatchEnabled);
2961 dump.appendFormat(INDENT "DispatchFrozen: %d\n", mDispatchFrozen);
Jeff Brownb88102f2010-09-08 11:49:43 -07002962
2963 if (mFocusedApplication) {
Jeff Brownf2f487182010-10-01 17:46:21 -07002964 dump.appendFormat(INDENT "FocusedApplication: name='%s', dispatchingTimeout=%0.3fms\n",
Jeff Brownb88102f2010-09-08 11:49:43 -07002965 mFocusedApplication->name.string(),
2966 mFocusedApplication->dispatchingTimeout / 1000000.0);
2967 } else {
Jeff Brownf2f487182010-10-01 17:46:21 -07002968 dump.append(INDENT "FocusedApplication: <null>\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07002969 }
Jeff Brownf2f487182010-10-01 17:46:21 -07002970 dump.appendFormat(INDENT "FocusedWindow: name='%s'\n",
Jeff Brown2a95c2a2010-09-16 12:31:46 -07002971 mFocusedWindow != NULL ? mFocusedWindow->name.string() : "<null>");
Jeff Brownf2f487182010-10-01 17:46:21 -07002972
2973 dump.appendFormat(INDENT "TouchDown: %s\n", toString(mTouchState.down));
2974 dump.appendFormat(INDENT "TouchSplit: %s\n", toString(mTouchState.split));
Jeff Brown95712852011-01-04 19:41:59 -08002975 dump.appendFormat(INDENT "TouchDeviceId: %d\n", mTouchState.deviceId);
Jeff Brown58a2da82011-01-25 16:02:22 -08002976 dump.appendFormat(INDENT "TouchSource: 0x%08x\n", mTouchState.source);
Jeff Brownf2f487182010-10-01 17:46:21 -07002977 if (!mTouchState.windows.isEmpty()) {
2978 dump.append(INDENT "TouchedWindows:\n");
2979 for (size_t i = 0; i < mTouchState.windows.size(); i++) {
2980 const TouchedWindow& touchedWindow = mTouchState.windows[i];
2981 dump.appendFormat(INDENT2 "%d: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
2982 i, touchedWindow.window->name.string(), touchedWindow.pointerIds.value,
2983 touchedWindow.targetFlags);
2984 }
2985 } else {
2986 dump.append(INDENT "TouchedWindows: <none>\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07002987 }
2988
Jeff Brownf2f487182010-10-01 17:46:21 -07002989 if (!mWindows.isEmpty()) {
2990 dump.append(INDENT "Windows:\n");
2991 for (size_t i = 0; i < mWindows.size(); i++) {
2992 const InputWindow& window = mWindows[i];
2993 dump.appendFormat(INDENT2 "%d: name='%s', paused=%s, hasFocus=%s, hasWallpaper=%s, "
2994 "visible=%s, canReceiveKeys=%s, flags=0x%08x, type=0x%08x, layer=%d, "
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002995 "frame=[%d,%d][%d,%d], scale=%f, "
Jeff Brownfbf09772011-01-16 14:06:57 -08002996 "touchableRegion=",
Jeff Brownf2f487182010-10-01 17:46:21 -07002997 i, window.name.string(),
2998 toString(window.paused),
2999 toString(window.hasFocus),
3000 toString(window.hasWallpaper),
3001 toString(window.visible),
3002 toString(window.canReceiveKeys),
3003 window.layoutParamsFlags, window.layoutParamsType,
3004 window.layer,
3005 window.frameLeft, window.frameTop,
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003006 window.frameRight, window.frameBottom,
3007 window.scaleFactor);
Jeff Brownfbf09772011-01-16 14:06:57 -08003008 dumpRegion(dump, window.touchableRegion);
3009 dump.appendFormat(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%0.3fms\n",
Jeff Brownf2f487182010-10-01 17:46:21 -07003010 window.ownerPid, window.ownerUid,
3011 window.dispatchingTimeout / 1000000.0);
3012 }
3013 } else {
3014 dump.append(INDENT "Windows: <none>\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003015 }
3016
Jeff Brownf2f487182010-10-01 17:46:21 -07003017 if (!mMonitoringChannels.isEmpty()) {
3018 dump.append(INDENT "MonitoringChannels:\n");
3019 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
3020 const sp<InputChannel>& channel = mMonitoringChannels[i];
3021 dump.appendFormat(INDENT2 "%d: '%s'\n", i, channel->getName().string());
3022 }
3023 } else {
3024 dump.append(INDENT "MonitoringChannels: <none>\n");
3025 }
Jeff Brown519e0242010-09-15 15:18:56 -07003026
Jeff Brownf2f487182010-10-01 17:46:21 -07003027 dump.appendFormat(INDENT "InboundQueue: length=%u\n", mInboundQueue.count());
3028
3029 if (!mActiveConnections.isEmpty()) {
3030 dump.append(INDENT "ActiveConnections:\n");
3031 for (size_t i = 0; i < mActiveConnections.size(); i++) {
3032 const Connection* connection = mActiveConnections[i];
Jeff Brown76860e32010-10-25 17:37:46 -07003033 dump.appendFormat(INDENT2 "%d: '%s', status=%s, outboundQueueLength=%u, "
Jeff Brownb6997262010-10-08 22:31:17 -07003034 "inputState.isNeutral=%s\n",
Jeff Brownf2f487182010-10-01 17:46:21 -07003035 i, connection->getInputChannelName(), connection->getStatusLabel(),
3036 connection->outboundQueue.count(),
Jeff Brownb6997262010-10-08 22:31:17 -07003037 toString(connection->inputState.isNeutral()));
Jeff Brownf2f487182010-10-01 17:46:21 -07003038 }
3039 } else {
3040 dump.append(INDENT "ActiveConnections: <none>\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003041 }
3042
3043 if (isAppSwitchPendingLocked()) {
Jeff Brownf2f487182010-10-01 17:46:21 -07003044 dump.appendFormat(INDENT "AppSwitch: pending, due in %01.1fms\n",
Jeff Brownb88102f2010-09-08 11:49:43 -07003045 (mAppSwitchDueTime - now()) / 1000000.0);
3046 } else {
Jeff Brownf2f487182010-10-01 17:46:21 -07003047 dump.append(INDENT "AppSwitch: not pending\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003048 }
3049}
3050
Jeff Brown928e0542011-01-10 11:17:36 -08003051status_t InputDispatcher::registerInputChannel(const sp<InputChannel>& inputChannel,
3052 const sp<InputWindowHandle>& inputWindowHandle, bool monitor) {
Jeff Brown9c3cda02010-06-15 01:31:58 -07003053#if DEBUG_REGISTRATION
Jeff Brownb88102f2010-09-08 11:49:43 -07003054 LOGD("channel '%s' ~ registerInputChannel - monitor=%s", inputChannel->getName().string(),
3055 toString(monitor));
Jeff Brown9c3cda02010-06-15 01:31:58 -07003056#endif
3057
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003058 { // acquire lock
3059 AutoMutex _l(mLock);
3060
Jeff Brown519e0242010-09-15 15:18:56 -07003061 if (getConnectionIndexLocked(inputChannel) >= 0) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003062 LOGW("Attempted to register already registered input channel '%s'",
3063 inputChannel->getName().string());
3064 return BAD_VALUE;
3065 }
3066
Jeff Brown928e0542011-01-10 11:17:36 -08003067 sp<Connection> connection = new Connection(inputChannel, inputWindowHandle);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003068 status_t status = connection->initialize();
3069 if (status) {
3070 LOGE("Failed to initialize input publisher for input channel '%s', status=%d",
3071 inputChannel->getName().string(), status);
3072 return status;
3073 }
3074
Jeff Brown2cbecea2010-08-17 15:59:26 -07003075 int32_t receiveFd = inputChannel->getReceivePipeFd();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003076 mConnectionsByReceiveFd.add(receiveFd, connection);
Jeff Brown9c3cda02010-06-15 01:31:58 -07003077
Jeff Brownb88102f2010-09-08 11:49:43 -07003078 if (monitor) {
3079 mMonitoringChannels.push(inputChannel);
3080 }
3081
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07003082 mLooper->addFd(receiveFd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
Jeff Brown2cbecea2010-08-17 15:59:26 -07003083
Jeff Brown9c3cda02010-06-15 01:31:58 -07003084 runCommandsLockedInterruptible();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003085 } // release lock
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003086 return OK;
3087}
3088
3089status_t InputDispatcher::unregisterInputChannel(const sp<InputChannel>& inputChannel) {
Jeff Brown9c3cda02010-06-15 01:31:58 -07003090#if DEBUG_REGISTRATION
Jeff Brown349703e2010-06-22 01:27:15 -07003091 LOGD("channel '%s' ~ unregisterInputChannel", inputChannel->getName().string());
Jeff Brown9c3cda02010-06-15 01:31:58 -07003092#endif
3093
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003094 { // acquire lock
3095 AutoMutex _l(mLock);
3096
Jeff Brown519e0242010-09-15 15:18:56 -07003097 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003098 if (connectionIndex < 0) {
3099 LOGW("Attempted to unregister already unregistered input channel '%s'",
3100 inputChannel->getName().string());
3101 return BAD_VALUE;
3102 }
3103
3104 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
3105 mConnectionsByReceiveFd.removeItemsAt(connectionIndex);
3106
3107 connection->status = Connection::STATUS_ZOMBIE;
3108
Jeff Brownb88102f2010-09-08 11:49:43 -07003109 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
3110 if (mMonitoringChannels[i] == inputChannel) {
3111 mMonitoringChannels.removeAt(i);
3112 break;
3113 }
3114 }
3115
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07003116 mLooper->removeFd(inputChannel->getReceivePipeFd());
Jeff Brown2cbecea2010-08-17 15:59:26 -07003117
Jeff Brown7fbdc842010-06-17 20:52:56 -07003118 nsecs_t currentTime = now();
Jeff Brownb6997262010-10-08 22:31:17 -07003119 abortBrokenDispatchCycleLocked(currentTime, connection);
Jeff Brown9c3cda02010-06-15 01:31:58 -07003120
3121 runCommandsLockedInterruptible();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003122 } // release lock
3123
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003124 // Wake the poll loop because removing the connection may have changed the current
3125 // synchronization state.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07003126 mLooper->wake();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003127 return OK;
3128}
3129
Jeff Brown519e0242010-09-15 15:18:56 -07003130ssize_t InputDispatcher::getConnectionIndexLocked(const sp<InputChannel>& inputChannel) {
Jeff Brown2cbecea2010-08-17 15:59:26 -07003131 ssize_t connectionIndex = mConnectionsByReceiveFd.indexOfKey(inputChannel->getReceivePipeFd());
3132 if (connectionIndex >= 0) {
3133 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
3134 if (connection->inputChannel.get() == inputChannel.get()) {
3135 return connectionIndex;
3136 }
3137 }
3138
3139 return -1;
3140}
3141
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003142void InputDispatcher::activateConnectionLocked(Connection* connection) {
3143 for (size_t i = 0; i < mActiveConnections.size(); i++) {
3144 if (mActiveConnections.itemAt(i) == connection) {
3145 return;
3146 }
3147 }
3148 mActiveConnections.add(connection);
3149}
3150
3151void InputDispatcher::deactivateConnectionLocked(Connection* connection) {
3152 for (size_t i = 0; i < mActiveConnections.size(); i++) {
3153 if (mActiveConnections.itemAt(i) == connection) {
3154 mActiveConnections.removeAt(i);
3155 return;
3156 }
3157 }
3158}
3159
Jeff Brown9c3cda02010-06-15 01:31:58 -07003160void InputDispatcher::onDispatchCycleStartedLocked(
Jeff Brown7fbdc842010-06-17 20:52:56 -07003161 nsecs_t currentTime, const sp<Connection>& connection) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003162}
3163
Jeff Brown9c3cda02010-06-15 01:31:58 -07003164void InputDispatcher::onDispatchCycleFinishedLocked(
Jeff Brown3915bb82010-11-05 15:02:16 -07003165 nsecs_t currentTime, const sp<Connection>& connection, bool handled) {
3166 CommandEntry* commandEntry = postCommandLocked(
3167 & InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
3168 commandEntry->connection = connection;
3169 commandEntry->handled = handled;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003170}
3171
Jeff Brown9c3cda02010-06-15 01:31:58 -07003172void InputDispatcher::onDispatchCycleBrokenLocked(
Jeff Brown7fbdc842010-06-17 20:52:56 -07003173 nsecs_t currentTime, const sp<Connection>& connection) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003174 LOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
3175 connection->getInputChannelName());
3176
Jeff Brown9c3cda02010-06-15 01:31:58 -07003177 CommandEntry* commandEntry = postCommandLocked(
3178 & InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
Jeff Brown7fbdc842010-06-17 20:52:56 -07003179 commandEntry->connection = connection;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003180}
3181
Jeff Brown519e0242010-09-15 15:18:56 -07003182void InputDispatcher::onANRLocked(
3183 nsecs_t currentTime, const InputApplication* application, const InputWindow* window,
3184 nsecs_t eventTime, nsecs_t waitStartTime) {
3185 LOGI("Application is not responding: %s. "
3186 "%01.1fms since event, %01.1fms since wait started",
3187 getApplicationWindowLabelLocked(application, window).string(),
3188 (currentTime - eventTime) / 1000000.0,
3189 (currentTime - waitStartTime) / 1000000.0);
3190
3191 CommandEntry* commandEntry = postCommandLocked(
3192 & InputDispatcher::doNotifyANRLockedInterruptible);
3193 if (application) {
Jeff Brown928e0542011-01-10 11:17:36 -08003194 commandEntry->inputApplicationHandle = application->inputApplicationHandle;
Jeff Brown519e0242010-09-15 15:18:56 -07003195 }
3196 if (window) {
Jeff Brown928e0542011-01-10 11:17:36 -08003197 commandEntry->inputWindowHandle = window->inputWindowHandle;
Jeff Brown519e0242010-09-15 15:18:56 -07003198 commandEntry->inputChannel = window->inputChannel;
3199 }
3200}
3201
Jeff Brownb88102f2010-09-08 11:49:43 -07003202void InputDispatcher::doNotifyConfigurationChangedInterruptible(
3203 CommandEntry* commandEntry) {
3204 mLock.unlock();
3205
3206 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
3207
3208 mLock.lock();
3209}
3210
Jeff Brown9c3cda02010-06-15 01:31:58 -07003211void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(
3212 CommandEntry* commandEntry) {
Jeff Brown7fbdc842010-06-17 20:52:56 -07003213 sp<Connection> connection = commandEntry->connection;
Jeff Brown9c3cda02010-06-15 01:31:58 -07003214
Jeff Brown7fbdc842010-06-17 20:52:56 -07003215 if (connection->status != Connection::STATUS_ZOMBIE) {
3216 mLock.unlock();
Jeff Brown9c3cda02010-06-15 01:31:58 -07003217
Jeff Brown928e0542011-01-10 11:17:36 -08003218 mPolicy->notifyInputChannelBroken(connection->inputWindowHandle);
Jeff Brown7fbdc842010-06-17 20:52:56 -07003219
3220 mLock.lock();
3221 }
Jeff Brown9c3cda02010-06-15 01:31:58 -07003222}
3223
Jeff Brown519e0242010-09-15 15:18:56 -07003224void InputDispatcher::doNotifyANRLockedInterruptible(
Jeff Brown9c3cda02010-06-15 01:31:58 -07003225 CommandEntry* commandEntry) {
Jeff Brown519e0242010-09-15 15:18:56 -07003226 mLock.unlock();
Jeff Brown9c3cda02010-06-15 01:31:58 -07003227
Jeff Brown519e0242010-09-15 15:18:56 -07003228 nsecs_t newTimeout = mPolicy->notifyANR(
Jeff Brown928e0542011-01-10 11:17:36 -08003229 commandEntry->inputApplicationHandle, commandEntry->inputWindowHandle);
Jeff Brown9c3cda02010-06-15 01:31:58 -07003230
Jeff Brown519e0242010-09-15 15:18:56 -07003231 mLock.lock();
Jeff Brown7fbdc842010-06-17 20:52:56 -07003232
Jeff Brown519e0242010-09-15 15:18:56 -07003233 resumeAfterTargetsNotReadyTimeoutLocked(newTimeout, commandEntry->inputChannel);
Jeff Brown9c3cda02010-06-15 01:31:58 -07003234}
3235
Jeff Brownb88102f2010-09-08 11:49:43 -07003236void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
3237 CommandEntry* commandEntry) {
3238 KeyEntry* entry = commandEntry->keyEntry;
Jeff Brown1f245102010-11-18 20:53:46 -08003239
3240 KeyEvent event;
3241 initializeKeyEvent(&event, entry);
Jeff Brownb88102f2010-09-08 11:49:43 -07003242
3243 mLock.unlock();
3244
Jeff Brown928e0542011-01-10 11:17:36 -08003245 bool consumed = mPolicy->interceptKeyBeforeDispatching(commandEntry->inputWindowHandle,
Jeff Brown1f245102010-11-18 20:53:46 -08003246 &event, entry->policyFlags);
Jeff Brownb88102f2010-09-08 11:49:43 -07003247
3248 mLock.lock();
3249
3250 entry->interceptKeyResult = consumed
3251 ? KeyEntry::INTERCEPT_KEY_RESULT_SKIP
3252 : KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
3253 mAllocator.releaseKeyEntry(entry);
3254}
3255
Jeff Brown3915bb82010-11-05 15:02:16 -07003256void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(
3257 CommandEntry* commandEntry) {
3258 sp<Connection> connection = commandEntry->connection;
3259 bool handled = commandEntry->handled;
3260
Jeff Brown49ed71d2010-12-06 17:13:33 -08003261 if (!connection->outboundQueue.isEmpty()) {
Jeff Brown3915bb82010-11-05 15:02:16 -07003262 DispatchEntry* dispatchEntry = connection->outboundQueue.headSentinel.next;
3263 if (dispatchEntry->inProgress
3264 && dispatchEntry->hasForegroundTarget()
3265 && dispatchEntry->eventEntry->type == EventEntry::TYPE_KEY) {
3266 KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry);
Jeff Brown49ed71d2010-12-06 17:13:33 -08003267 if (!(keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK)) {
3268 if (handled) {
3269 // If the application handled a non-fallback key, then immediately
3270 // cancel all fallback keys previously dispatched to the application.
3271 // This behavior will prevent chording with fallback keys (so they cannot
3272 // be used as modifiers) but it will ensure that fallback keys do not
3273 // get stuck. This takes care of the case where the application does not handle
3274 // the original DOWN so we generate a fallback DOWN but it does handle
Jeff Brownbfaf3b92011-02-22 15:00:50 -08003275 // the original UP in which case we want to send a fallback CANCEL.
Jeff Brown49ed71d2010-12-06 17:13:33 -08003276 synthesizeCancelationEventsForConnectionLocked(connection,
3277 InputState::CANCEL_FALLBACK_EVENTS,
Jeff Brownbfaf3b92011-02-22 15:00:50 -08003278 "application handled a non-fallback event, "
3279 "canceling all fallback events");
3280 connection->originalKeyCodeForFallback = -1;
Jeff Brown49ed71d2010-12-06 17:13:33 -08003281 } else {
Jeff Brownbfaf3b92011-02-22 15:00:50 -08003282 // If the application did not handle a non-fallback key, first check
3283 // that we are in a good state to handle the fallback key. Then ask
3284 // the policy what to do with it.
3285 if (connection->originalKeyCodeForFallback < 0) {
3286 if (keyEntry->action != AKEY_EVENT_ACTION_DOWN
3287 || keyEntry->repeatCount != 0) {
3288#if DEBUG_OUTBOUND_EVENT_DETAILS
3289 LOGD("Unhandled key event: Skipping fallback since this "
3290 "is not an initial down. "
3291 "keyCode=%d, action=%d, repeatCount=%d",
3292 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount);
3293#endif
3294 goto SkipFallback;
3295 }
3296
3297 // Start handling the fallback key on DOWN.
3298 connection->originalKeyCodeForFallback = keyEntry->keyCode;
3299 } else {
3300 if (keyEntry->keyCode != connection->originalKeyCodeForFallback) {
3301#if DEBUG_OUTBOUND_EVENT_DETAILS
3302 LOGD("Unhandled key event: Skipping fallback since there is "
3303 "already a different fallback in progress. "
3304 "keyCode=%d, originalKeyCodeForFallback=%d",
3305 keyEntry->keyCode, connection->originalKeyCodeForFallback);
3306#endif
3307 goto SkipFallback;
3308 }
3309
3310 // Finish handling the fallback key on UP.
3311 if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
3312 connection->originalKeyCodeForFallback = -1;
3313 }
3314 }
3315
3316#if DEBUG_OUTBOUND_EVENT_DETAILS
3317 LOGD("Unhandled key event: Asking policy to perform fallback action. "
3318 "keyCode=%d, action=%d, repeatCount=%d",
3319 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount);
3320#endif
Jeff Brown49ed71d2010-12-06 17:13:33 -08003321 KeyEvent event;
3322 initializeKeyEvent(&event, keyEntry);
Jeff Brown3915bb82010-11-05 15:02:16 -07003323
Jeff Brown49ed71d2010-12-06 17:13:33 -08003324 mLock.unlock();
Jeff Brown3915bb82010-11-05 15:02:16 -07003325
Jeff Brown928e0542011-01-10 11:17:36 -08003326 bool fallback = mPolicy->dispatchUnhandledKey(connection->inputWindowHandle,
Jeff Brown49ed71d2010-12-06 17:13:33 -08003327 &event, keyEntry->policyFlags, &event);
Jeff Brown3915bb82010-11-05 15:02:16 -07003328
Jeff Brown49ed71d2010-12-06 17:13:33 -08003329 mLock.lock();
3330
Jeff Brown00045a72010-12-09 18:10:30 -08003331 if (connection->status != Connection::STATUS_NORMAL) {
3332 return;
3333 }
3334
3335 assert(connection->outboundQueue.headSentinel.next == dispatchEntry);
3336
Jeff Brown49ed71d2010-12-06 17:13:33 -08003337 if (fallback) {
3338 // Restart the dispatch cycle using the fallback key.
3339 keyEntry->eventTime = event.getEventTime();
3340 keyEntry->deviceId = event.getDeviceId();
3341 keyEntry->source = event.getSource();
3342 keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
3343 keyEntry->keyCode = event.getKeyCode();
3344 keyEntry->scanCode = event.getScanCode();
3345 keyEntry->metaState = event.getMetaState();
3346 keyEntry->repeatCount = event.getRepeatCount();
3347 keyEntry->downTime = event.getDownTime();
3348 keyEntry->syntheticRepeat = false;
3349
Jeff Brownbfaf3b92011-02-22 15:00:50 -08003350#if DEBUG_OUTBOUND_EVENT_DETAILS
3351 LOGD("Unhandled key event: Dispatching fallback key. "
3352 "fallbackKeyCode=%d, fallbackMetaState=%08x",
3353 keyEntry->keyCode, keyEntry->metaState);
3354#endif
3355
Jeff Brown49ed71d2010-12-06 17:13:33 -08003356 dispatchEntry->inProgress = false;
3357 startDispatchCycleLocked(now(), connection);
3358 return;
3359 }
3360 }
3361 }
Jeff Brown3915bb82010-11-05 15:02:16 -07003362 }
3363 }
3364
Jeff Brownbfaf3b92011-02-22 15:00:50 -08003365SkipFallback:
Jeff Brown3915bb82010-11-05 15:02:16 -07003366 startNextDispatchCycleLocked(now(), connection);
3367}
3368
Jeff Brownb88102f2010-09-08 11:49:43 -07003369void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
3370 mLock.unlock();
3371
Jeff Brown01ce2e92010-09-26 22:20:12 -07003372 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
Jeff Brownb88102f2010-09-08 11:49:43 -07003373
3374 mLock.lock();
3375}
3376
Jeff Brown3915bb82010-11-05 15:02:16 -07003377void InputDispatcher::initializeKeyEvent(KeyEvent* event, const KeyEntry* entry) {
3378 event->initialize(entry->deviceId, entry->source, entry->action, entry->flags,
3379 entry->keyCode, entry->scanCode, entry->metaState, entry->repeatCount,
3380 entry->downTime, entry->eventTime);
3381}
3382
Jeff Brown519e0242010-09-15 15:18:56 -07003383void InputDispatcher::updateDispatchStatisticsLocked(nsecs_t currentTime, const EventEntry* entry,
3384 int32_t injectionResult, nsecs_t timeSpentWaitingForApplication) {
3385 // TODO Write some statistics about how long we spend waiting.
Jeff Brownb88102f2010-09-08 11:49:43 -07003386}
3387
3388void InputDispatcher::dump(String8& dump) {
Jeff Brownf2f487182010-10-01 17:46:21 -07003389 dump.append("Input Dispatcher State:\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003390 dumpDispatchStateLocked(dump);
3391}
3392
Jeff Brown9c3cda02010-06-15 01:31:58 -07003393
Jeff Brown519e0242010-09-15 15:18:56 -07003394// --- InputDispatcher::Queue ---
3395
3396template <typename T>
3397uint32_t InputDispatcher::Queue<T>::count() const {
3398 uint32_t result = 0;
3399 for (const T* entry = headSentinel.next; entry != & tailSentinel; entry = entry->next) {
3400 result += 1;
3401 }
3402 return result;
3403}
3404
3405
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003406// --- InputDispatcher::Allocator ---
3407
3408InputDispatcher::Allocator::Allocator() {
3409}
3410
Jeff Brown01ce2e92010-09-26 22:20:12 -07003411InputDispatcher::InjectionState*
3412InputDispatcher::Allocator::obtainInjectionState(int32_t injectorPid, int32_t injectorUid) {
3413 InjectionState* injectionState = mInjectionStatePool.alloc();
3414 injectionState->refCount = 1;
3415 injectionState->injectorPid = injectorPid;
3416 injectionState->injectorUid = injectorUid;
3417 injectionState->injectionIsAsync = false;
3418 injectionState->injectionResult = INPUT_EVENT_INJECTION_PENDING;
3419 injectionState->pendingForegroundDispatches = 0;
3420 return injectionState;
3421}
3422
Jeff Brown7fbdc842010-06-17 20:52:56 -07003423void InputDispatcher::Allocator::initializeEventEntry(EventEntry* entry, int32_t type,
Jeff Brownb6997262010-10-08 22:31:17 -07003424 nsecs_t eventTime, uint32_t policyFlags) {
Jeff Brown7fbdc842010-06-17 20:52:56 -07003425 entry->type = type;
3426 entry->refCount = 1;
3427 entry->dispatchInProgress = false;
Christopher Tatee91a5db2010-06-23 16:50:30 -07003428 entry->eventTime = eventTime;
Jeff Brownb6997262010-10-08 22:31:17 -07003429 entry->policyFlags = policyFlags;
Jeff Brown01ce2e92010-09-26 22:20:12 -07003430 entry->injectionState = NULL;
3431}
3432
3433void InputDispatcher::Allocator::releaseEventEntryInjectionState(EventEntry* entry) {
3434 if (entry->injectionState) {
3435 releaseInjectionState(entry->injectionState);
3436 entry->injectionState = NULL;
3437 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07003438}
3439
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003440InputDispatcher::ConfigurationChangedEntry*
Jeff Brown7fbdc842010-06-17 20:52:56 -07003441InputDispatcher::Allocator::obtainConfigurationChangedEntry(nsecs_t eventTime) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003442 ConfigurationChangedEntry* entry = mConfigurationChangeEntryPool.alloc();
Jeff Brownb6997262010-10-08 22:31:17 -07003443 initializeEventEntry(entry, EventEntry::TYPE_CONFIGURATION_CHANGED, eventTime, 0);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003444 return entry;
3445}
3446
Jeff Brown7fbdc842010-06-17 20:52:56 -07003447InputDispatcher::KeyEntry* InputDispatcher::Allocator::obtainKeyEntry(nsecs_t eventTime,
Jeff Brown58a2da82011-01-25 16:02:22 -08003448 int32_t deviceId, uint32_t source, uint32_t policyFlags, int32_t action,
Jeff Brown7fbdc842010-06-17 20:52:56 -07003449 int32_t flags, int32_t keyCode, int32_t scanCode, int32_t metaState,
3450 int32_t repeatCount, nsecs_t downTime) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003451 KeyEntry* entry = mKeyEntryPool.alloc();
Jeff Brownb6997262010-10-08 22:31:17 -07003452 initializeEventEntry(entry, EventEntry::TYPE_KEY, eventTime, policyFlags);
Jeff Brown7fbdc842010-06-17 20:52:56 -07003453
3454 entry->deviceId = deviceId;
Jeff Brownc5ed5912010-07-14 18:48:53 -07003455 entry->source = source;
Jeff Brown7fbdc842010-06-17 20:52:56 -07003456 entry->action = action;
3457 entry->flags = flags;
3458 entry->keyCode = keyCode;
3459 entry->scanCode = scanCode;
3460 entry->metaState = metaState;
3461 entry->repeatCount = repeatCount;
3462 entry->downTime = downTime;
Jeff Brownb88102f2010-09-08 11:49:43 -07003463 entry->syntheticRepeat = false;
3464 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003465 return entry;
3466}
3467
Jeff Brown7fbdc842010-06-17 20:52:56 -07003468InputDispatcher::MotionEntry* InputDispatcher::Allocator::obtainMotionEntry(nsecs_t eventTime,
Jeff Brown58a2da82011-01-25 16:02:22 -08003469 int32_t deviceId, uint32_t source, uint32_t policyFlags, int32_t action, int32_t flags,
Jeff Brown7fbdc842010-06-17 20:52:56 -07003470 int32_t metaState, int32_t edgeFlags, float xPrecision, float yPrecision,
3471 nsecs_t downTime, uint32_t pointerCount,
3472 const int32_t* pointerIds, const PointerCoords* pointerCoords) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003473 MotionEntry* entry = mMotionEntryPool.alloc();
Jeff Brownb6997262010-10-08 22:31:17 -07003474 initializeEventEntry(entry, EventEntry::TYPE_MOTION, eventTime, policyFlags);
Jeff Brown7fbdc842010-06-17 20:52:56 -07003475
3476 entry->eventTime = eventTime;
3477 entry->deviceId = deviceId;
Jeff Brownc5ed5912010-07-14 18:48:53 -07003478 entry->source = source;
Jeff Brown7fbdc842010-06-17 20:52:56 -07003479 entry->action = action;
Jeff Brown85a31762010-09-01 17:01:00 -07003480 entry->flags = flags;
Jeff Brown7fbdc842010-06-17 20:52:56 -07003481 entry->metaState = metaState;
3482 entry->edgeFlags = edgeFlags;
3483 entry->xPrecision = xPrecision;
3484 entry->yPrecision = yPrecision;
3485 entry->downTime = downTime;
3486 entry->pointerCount = pointerCount;
3487 entry->firstSample.eventTime = eventTime;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003488 entry->firstSample.next = NULL;
Jeff Brown7fbdc842010-06-17 20:52:56 -07003489 entry->lastSample = & entry->firstSample;
3490 for (uint32_t i = 0; i < pointerCount; i++) {
3491 entry->pointerIds[i] = pointerIds[i];
3492 entry->firstSample.pointerCoords[i] = pointerCoords[i];
3493 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003494 return entry;
3495}
3496
3497InputDispatcher::DispatchEntry* InputDispatcher::Allocator::obtainDispatchEntry(
Jeff Brownb88102f2010-09-08 11:49:43 -07003498 EventEntry* eventEntry,
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003499 int32_t targetFlags, float xOffset, float yOffset, float scaleFactor) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003500 DispatchEntry* entry = mDispatchEntryPool.alloc();
3501 entry->eventEntry = eventEntry;
3502 eventEntry->refCount += 1;
Jeff Brownb88102f2010-09-08 11:49:43 -07003503 entry->targetFlags = targetFlags;
3504 entry->xOffset = xOffset;
3505 entry->yOffset = yOffset;
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003506 entry->scaleFactor = scaleFactor;
Jeff Brownb88102f2010-09-08 11:49:43 -07003507 entry->inProgress = false;
3508 entry->headMotionSample = NULL;
3509 entry->tailMotionSample = NULL;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003510 return entry;
3511}
3512
Jeff Brown9c3cda02010-06-15 01:31:58 -07003513InputDispatcher::CommandEntry* InputDispatcher::Allocator::obtainCommandEntry(Command command) {
3514 CommandEntry* entry = mCommandEntryPool.alloc();
3515 entry->command = command;
3516 return entry;
3517}
3518
Jeff Brown01ce2e92010-09-26 22:20:12 -07003519void InputDispatcher::Allocator::releaseInjectionState(InjectionState* injectionState) {
3520 injectionState->refCount -= 1;
3521 if (injectionState->refCount == 0) {
3522 mInjectionStatePool.free(injectionState);
3523 } else {
3524 assert(injectionState->refCount > 0);
3525 }
3526}
3527
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003528void InputDispatcher::Allocator::releaseEventEntry(EventEntry* entry) {
3529 switch (entry->type) {
3530 case EventEntry::TYPE_CONFIGURATION_CHANGED:
3531 releaseConfigurationChangedEntry(static_cast<ConfigurationChangedEntry*>(entry));
3532 break;
3533 case EventEntry::TYPE_KEY:
3534 releaseKeyEntry(static_cast<KeyEntry*>(entry));
3535 break;
3536 case EventEntry::TYPE_MOTION:
3537 releaseMotionEntry(static_cast<MotionEntry*>(entry));
3538 break;
3539 default:
3540 assert(false);
3541 break;
3542 }
3543}
3544
3545void InputDispatcher::Allocator::releaseConfigurationChangedEntry(
3546 ConfigurationChangedEntry* entry) {
3547 entry->refCount -= 1;
3548 if (entry->refCount == 0) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07003549 releaseEventEntryInjectionState(entry);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003550 mConfigurationChangeEntryPool.free(entry);
3551 } else {
3552 assert(entry->refCount > 0);
3553 }
3554}
3555
3556void InputDispatcher::Allocator::releaseKeyEntry(KeyEntry* entry) {
3557 entry->refCount -= 1;
3558 if (entry->refCount == 0) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07003559 releaseEventEntryInjectionState(entry);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003560 mKeyEntryPool.free(entry);
3561 } else {
3562 assert(entry->refCount > 0);
3563 }
3564}
3565
3566void InputDispatcher::Allocator::releaseMotionEntry(MotionEntry* entry) {
3567 entry->refCount -= 1;
3568 if (entry->refCount == 0) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07003569 releaseEventEntryInjectionState(entry);
Jeff Brown9c3cda02010-06-15 01:31:58 -07003570 for (MotionSample* sample = entry->firstSample.next; sample != NULL; ) {
3571 MotionSample* next = sample->next;
3572 mMotionSamplePool.free(sample);
3573 sample = next;
3574 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003575 mMotionEntryPool.free(entry);
3576 } else {
3577 assert(entry->refCount > 0);
3578 }
3579}
3580
3581void InputDispatcher::Allocator::releaseDispatchEntry(DispatchEntry* entry) {
3582 releaseEventEntry(entry->eventEntry);
3583 mDispatchEntryPool.free(entry);
3584}
3585
Jeff Brown9c3cda02010-06-15 01:31:58 -07003586void InputDispatcher::Allocator::releaseCommandEntry(CommandEntry* entry) {
3587 mCommandEntryPool.free(entry);
3588}
3589
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003590void InputDispatcher::Allocator::appendMotionSample(MotionEntry* motionEntry,
Jeff Brown7fbdc842010-06-17 20:52:56 -07003591 nsecs_t eventTime, const PointerCoords* pointerCoords) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003592 MotionSample* sample = mMotionSamplePool.alloc();
3593 sample->eventTime = eventTime;
Jeff Brown7fbdc842010-06-17 20:52:56 -07003594 uint32_t pointerCount = motionEntry->pointerCount;
3595 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003596 sample->pointerCoords[i] = pointerCoords[i];
3597 }
3598
3599 sample->next = NULL;
3600 motionEntry->lastSample->next = sample;
3601 motionEntry->lastSample = sample;
3602}
3603
Jeff Brown01ce2e92010-09-26 22:20:12 -07003604void InputDispatcher::Allocator::recycleKeyEntry(KeyEntry* keyEntry) {
3605 releaseEventEntryInjectionState(keyEntry);
Jeff Brownb88102f2010-09-08 11:49:43 -07003606
Jeff Brown01ce2e92010-09-26 22:20:12 -07003607 keyEntry->dispatchInProgress = false;
3608 keyEntry->syntheticRepeat = false;
3609 keyEntry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
Jeff Brownb88102f2010-09-08 11:49:43 -07003610}
3611
3612
Jeff Brownae9fc032010-08-18 15:51:08 -07003613// --- InputDispatcher::MotionEntry ---
3614
3615uint32_t InputDispatcher::MotionEntry::countSamples() const {
3616 uint32_t count = 1;
3617 for (MotionSample* sample = firstSample.next; sample != NULL; sample = sample->next) {
3618 count += 1;
3619 }
3620 return count;
3621}
3622
Jeff Brownb88102f2010-09-08 11:49:43 -07003623
3624// --- InputDispatcher::InputState ---
3625
Jeff Brownb6997262010-10-08 22:31:17 -07003626InputDispatcher::InputState::InputState() {
Jeff Brownb88102f2010-09-08 11:49:43 -07003627}
3628
3629InputDispatcher::InputState::~InputState() {
3630}
3631
3632bool InputDispatcher::InputState::isNeutral() const {
3633 return mKeyMementos.isEmpty() && mMotionMementos.isEmpty();
3634}
3635
Jeff Browncc0c1592011-02-19 05:07:28 -08003636void InputDispatcher::InputState::trackEvent(
Jeff Brownb88102f2010-09-08 11:49:43 -07003637 const EventEntry* entry) {
3638 switch (entry->type) {
3639 case EventEntry::TYPE_KEY:
Jeff Browncc0c1592011-02-19 05:07:28 -08003640 trackKey(static_cast<const KeyEntry*>(entry));
3641 break;
Jeff Brownb88102f2010-09-08 11:49:43 -07003642
3643 case EventEntry::TYPE_MOTION:
Jeff Browncc0c1592011-02-19 05:07:28 -08003644 trackMotion(static_cast<const MotionEntry*>(entry));
3645 break;
Jeff Brownb88102f2010-09-08 11:49:43 -07003646 }
3647}
3648
Jeff Browncc0c1592011-02-19 05:07:28 -08003649void InputDispatcher::InputState::trackKey(
Jeff Brownb88102f2010-09-08 11:49:43 -07003650 const KeyEntry* entry) {
3651 int32_t action = entry->action;
3652 for (size_t i = 0; i < mKeyMementos.size(); i++) {
3653 KeyMemento& memento = mKeyMementos.editItemAt(i);
3654 if (memento.deviceId == entry->deviceId
3655 && memento.source == entry->source
3656 && memento.keyCode == entry->keyCode
3657 && memento.scanCode == entry->scanCode) {
3658 switch (action) {
3659 case AKEY_EVENT_ACTION_UP:
3660 mKeyMementos.removeAt(i);
Jeff Browncc0c1592011-02-19 05:07:28 -08003661 return;
Jeff Brownb88102f2010-09-08 11:49:43 -07003662
3663 case AKEY_EVENT_ACTION_DOWN:
Jeff Browncc0c1592011-02-19 05:07:28 -08003664 mKeyMementos.removeAt(i);
3665 goto Found;
Jeff Brownb88102f2010-09-08 11:49:43 -07003666
3667 default:
Jeff Browncc0c1592011-02-19 05:07:28 -08003668 return;
Jeff Brownb88102f2010-09-08 11:49:43 -07003669 }
3670 }
3671 }
3672
Jeff Browncc0c1592011-02-19 05:07:28 -08003673Found:
3674 if (action == AKEY_EVENT_ACTION_DOWN) {
Jeff Brownb88102f2010-09-08 11:49:43 -07003675 mKeyMementos.push();
3676 KeyMemento& memento = mKeyMementos.editTop();
3677 memento.deviceId = entry->deviceId;
3678 memento.source = entry->source;
3679 memento.keyCode = entry->keyCode;
3680 memento.scanCode = entry->scanCode;
Jeff Brown49ed71d2010-12-06 17:13:33 -08003681 memento.flags = entry->flags;
Jeff Brownb88102f2010-09-08 11:49:43 -07003682 memento.downTime = entry->downTime;
Jeff Brownb88102f2010-09-08 11:49:43 -07003683 }
3684}
3685
Jeff Browncc0c1592011-02-19 05:07:28 -08003686void InputDispatcher::InputState::trackMotion(
Jeff Brownb88102f2010-09-08 11:49:43 -07003687 const MotionEntry* entry) {
3688 int32_t action = entry->action & AMOTION_EVENT_ACTION_MASK;
3689 for (size_t i = 0; i < mMotionMementos.size(); i++) {
3690 MotionMemento& memento = mMotionMementos.editItemAt(i);
3691 if (memento.deviceId == entry->deviceId
3692 && memento.source == entry->source) {
3693 switch (action) {
3694 case AMOTION_EVENT_ACTION_UP:
3695 case AMOTION_EVENT_ACTION_CANCEL:
Jeff Browncc0c1592011-02-19 05:07:28 -08003696 case AMOTION_EVENT_ACTION_HOVER_MOVE:
Jeff Brownb88102f2010-09-08 11:49:43 -07003697 mMotionMementos.removeAt(i);
Jeff Browncc0c1592011-02-19 05:07:28 -08003698 return;
Jeff Brownb88102f2010-09-08 11:49:43 -07003699
3700 case AMOTION_EVENT_ACTION_DOWN:
Jeff Browncc0c1592011-02-19 05:07:28 -08003701 mMotionMementos.removeAt(i);
3702 goto Found;
Jeff Brownb88102f2010-09-08 11:49:43 -07003703
3704 case AMOTION_EVENT_ACTION_POINTER_UP:
Jeff Browncc0c1592011-02-19 05:07:28 -08003705 case AMOTION_EVENT_ACTION_POINTER_DOWN:
Jeff Brownb88102f2010-09-08 11:49:43 -07003706 case AMOTION_EVENT_ACTION_MOVE:
Jeff Browncc0c1592011-02-19 05:07:28 -08003707 memento.setPointers(entry);
3708 return;
Jeff Brownb88102f2010-09-08 11:49:43 -07003709
3710 default:
Jeff Browncc0c1592011-02-19 05:07:28 -08003711 return;
Jeff Brownb88102f2010-09-08 11:49:43 -07003712 }
3713 }
3714 }
3715
Jeff Browncc0c1592011-02-19 05:07:28 -08003716Found:
3717 if (action == AMOTION_EVENT_ACTION_DOWN) {
Jeff Brownb88102f2010-09-08 11:49:43 -07003718 mMotionMementos.push();
3719 MotionMemento& memento = mMotionMementos.editTop();
3720 memento.deviceId = entry->deviceId;
3721 memento.source = entry->source;
3722 memento.xPrecision = entry->xPrecision;
3723 memento.yPrecision = entry->yPrecision;
3724 memento.downTime = entry->downTime;
3725 memento.setPointers(entry);
Jeff Brownb88102f2010-09-08 11:49:43 -07003726 }
3727}
3728
3729void InputDispatcher::InputState::MotionMemento::setPointers(const MotionEntry* entry) {
3730 pointerCount = entry->pointerCount;
3731 for (uint32_t i = 0; i < entry->pointerCount; i++) {
3732 pointerIds[i] = entry->pointerIds[i];
3733 pointerCoords[i] = entry->lastSample->pointerCoords[i];
3734 }
3735}
3736
Jeff Brownb6997262010-10-08 22:31:17 -07003737void InputDispatcher::InputState::synthesizeCancelationEvents(nsecs_t currentTime,
3738 Allocator* allocator, Vector<EventEntry*>& outEvents,
3739 CancelationOptions options) {
3740 for (size_t i = 0; i < mKeyMementos.size(); ) {
Jeff Brownb88102f2010-09-08 11:49:43 -07003741 const KeyMemento& memento = mKeyMementos.itemAt(i);
Jeff Brown49ed71d2010-12-06 17:13:33 -08003742 if (shouldCancelKey(memento, options)) {
Jeff Brownb6997262010-10-08 22:31:17 -07003743 outEvents.push(allocator->obtainKeyEntry(currentTime,
3744 memento.deviceId, memento.source, 0,
Jeff Brown49ed71d2010-12-06 17:13:33 -08003745 AKEY_EVENT_ACTION_UP, memento.flags | AKEY_EVENT_FLAG_CANCELED,
Jeff Brownb6997262010-10-08 22:31:17 -07003746 memento.keyCode, memento.scanCode, 0, 0, memento.downTime));
3747 mKeyMementos.removeAt(i);
3748 } else {
3749 i += 1;
3750 }
Jeff Brownb88102f2010-09-08 11:49:43 -07003751 }
3752
Jeff Browna1160a72010-10-11 18:22:53 -07003753 for (size_t i = 0; i < mMotionMementos.size(); ) {
Jeff Brownb88102f2010-09-08 11:49:43 -07003754 const MotionMemento& memento = mMotionMementos.itemAt(i);
Jeff Brown49ed71d2010-12-06 17:13:33 -08003755 if (shouldCancelMotion(memento, options)) {
Jeff Brownb6997262010-10-08 22:31:17 -07003756 outEvents.push(allocator->obtainMotionEntry(currentTime,
3757 memento.deviceId, memento.source, 0,
3758 AMOTION_EVENT_ACTION_CANCEL, 0, 0, 0,
3759 memento.xPrecision, memento.yPrecision, memento.downTime,
3760 memento.pointerCount, memento.pointerIds, memento.pointerCoords));
3761 mMotionMementos.removeAt(i);
3762 } else {
3763 i += 1;
3764 }
Jeff Brownb88102f2010-09-08 11:49:43 -07003765 }
3766}
3767
3768void InputDispatcher::InputState::clear() {
3769 mKeyMementos.clear();
3770 mMotionMementos.clear();
Jeff Brownb6997262010-10-08 22:31:17 -07003771}
3772
Jeff Brown9c9f1a32010-10-11 18:32:20 -07003773void InputDispatcher::InputState::copyPointerStateTo(InputState& other) const {
3774 for (size_t i = 0; i < mMotionMementos.size(); i++) {
3775 const MotionMemento& memento = mMotionMementos.itemAt(i);
3776 if (memento.source & AINPUT_SOURCE_CLASS_POINTER) {
3777 for (size_t j = 0; j < other.mMotionMementos.size(); ) {
3778 const MotionMemento& otherMemento = other.mMotionMementos.itemAt(j);
3779 if (memento.deviceId == otherMemento.deviceId
3780 && memento.source == otherMemento.source) {
3781 other.mMotionMementos.removeAt(j);
3782 } else {
3783 j += 1;
3784 }
3785 }
3786 other.mMotionMementos.push(memento);
3787 }
3788 }
3789}
3790
Jeff Brown49ed71d2010-12-06 17:13:33 -08003791bool InputDispatcher::InputState::shouldCancelKey(const KeyMemento& memento,
Jeff Brownb6997262010-10-08 22:31:17 -07003792 CancelationOptions options) {
3793 switch (options) {
Jeff Brown49ed71d2010-12-06 17:13:33 -08003794 case CANCEL_ALL_EVENTS:
Jeff Brownb6997262010-10-08 22:31:17 -07003795 case CANCEL_NON_POINTER_EVENTS:
Jeff Brownb6997262010-10-08 22:31:17 -07003796 return true;
Jeff Brown49ed71d2010-12-06 17:13:33 -08003797 case CANCEL_FALLBACK_EVENTS:
3798 return memento.flags & AKEY_EVENT_FLAG_FALLBACK;
3799 default:
3800 return false;
3801 }
3802}
3803
3804bool InputDispatcher::InputState::shouldCancelMotion(const MotionMemento& memento,
3805 CancelationOptions options) {
3806 switch (options) {
3807 case CANCEL_ALL_EVENTS:
3808 return true;
3809 case CANCEL_POINTER_EVENTS:
3810 return memento.source & AINPUT_SOURCE_CLASS_POINTER;
3811 case CANCEL_NON_POINTER_EVENTS:
3812 return !(memento.source & AINPUT_SOURCE_CLASS_POINTER);
3813 default:
3814 return false;
Jeff Brownb6997262010-10-08 22:31:17 -07003815 }
Jeff Brownb88102f2010-09-08 11:49:43 -07003816}
3817
3818
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003819// --- InputDispatcher::Connection ---
3820
Jeff Brown928e0542011-01-10 11:17:36 -08003821InputDispatcher::Connection::Connection(const sp<InputChannel>& inputChannel,
3822 const sp<InputWindowHandle>& inputWindowHandle) :
3823 status(STATUS_NORMAL), inputChannel(inputChannel), inputWindowHandle(inputWindowHandle),
3824 inputPublisher(inputChannel),
Jeff Brownbfaf3b92011-02-22 15:00:50 -08003825 lastEventTime(LONG_LONG_MAX), lastDispatchTime(LONG_LONG_MAX),
3826 originalKeyCodeForFallback(-1) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003827}
3828
3829InputDispatcher::Connection::~Connection() {
3830}
3831
3832status_t InputDispatcher::Connection::initialize() {
3833 return inputPublisher.initialize();
3834}
3835
Jeff Brown9c3cda02010-06-15 01:31:58 -07003836const char* InputDispatcher::Connection::getStatusLabel() const {
3837 switch (status) {
3838 case STATUS_NORMAL:
3839 return "NORMAL";
3840
3841 case STATUS_BROKEN:
3842 return "BROKEN";
3843
Jeff Brown9c3cda02010-06-15 01:31:58 -07003844 case STATUS_ZOMBIE:
3845 return "ZOMBIE";
3846
3847 default:
3848 return "UNKNOWN";
3849 }
3850}
3851
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003852InputDispatcher::DispatchEntry* InputDispatcher::Connection::findQueuedDispatchEntryForEvent(
3853 const EventEntry* eventEntry) const {
Jeff Brownb88102f2010-09-08 11:49:43 -07003854 for (DispatchEntry* dispatchEntry = outboundQueue.tailSentinel.prev;
3855 dispatchEntry != & outboundQueue.headSentinel; dispatchEntry = dispatchEntry->prev) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003856 if (dispatchEntry->eventEntry == eventEntry) {
3857 return dispatchEntry;
3858 }
3859 }
3860 return NULL;
3861}
3862
Jeff Brownb88102f2010-09-08 11:49:43 -07003863
Jeff Brown9c3cda02010-06-15 01:31:58 -07003864// --- InputDispatcher::CommandEntry ---
3865
Jeff Brownb88102f2010-09-08 11:49:43 -07003866InputDispatcher::CommandEntry::CommandEntry() :
3867 keyEntry(NULL) {
Jeff Brown9c3cda02010-06-15 01:31:58 -07003868}
3869
3870InputDispatcher::CommandEntry::~CommandEntry() {
3871}
3872
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003873
Jeff Brown01ce2e92010-09-26 22:20:12 -07003874// --- InputDispatcher::TouchState ---
3875
3876InputDispatcher::TouchState::TouchState() :
Jeff Brown58a2da82011-01-25 16:02:22 -08003877 down(false), split(false), deviceId(-1), source(0) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07003878}
3879
3880InputDispatcher::TouchState::~TouchState() {
3881}
3882
3883void InputDispatcher::TouchState::reset() {
3884 down = false;
3885 split = false;
Jeff Brown95712852011-01-04 19:41:59 -08003886 deviceId = -1;
Jeff Brown58a2da82011-01-25 16:02:22 -08003887 source = 0;
Jeff Brown01ce2e92010-09-26 22:20:12 -07003888 windows.clear();
3889}
3890
3891void InputDispatcher::TouchState::copyFrom(const TouchState& other) {
3892 down = other.down;
3893 split = other.split;
Jeff Brown95712852011-01-04 19:41:59 -08003894 deviceId = other.deviceId;
Jeff Brown58a2da82011-01-25 16:02:22 -08003895 source = other.source;
Jeff Brown01ce2e92010-09-26 22:20:12 -07003896 windows.clear();
3897 windows.appendVector(other.windows);
3898}
3899
3900void InputDispatcher::TouchState::addOrUpdateWindow(const InputWindow* window,
3901 int32_t targetFlags, BitSet32 pointerIds) {
3902 if (targetFlags & InputTarget::FLAG_SPLIT) {
3903 split = true;
3904 }
3905
3906 for (size_t i = 0; i < windows.size(); i++) {
3907 TouchedWindow& touchedWindow = windows.editItemAt(i);
3908 if (touchedWindow.window == window) {
3909 touchedWindow.targetFlags |= targetFlags;
3910 touchedWindow.pointerIds.value |= pointerIds.value;
3911 return;
3912 }
3913 }
3914
3915 windows.push();
3916
3917 TouchedWindow& touchedWindow = windows.editTop();
3918 touchedWindow.window = window;
3919 touchedWindow.targetFlags = targetFlags;
3920 touchedWindow.pointerIds = pointerIds;
3921 touchedWindow.channel = window->inputChannel;
3922}
3923
3924void InputDispatcher::TouchState::removeOutsideTouchWindows() {
3925 for (size_t i = 0 ; i < windows.size(); ) {
3926 if (windows[i].targetFlags & InputTarget::FLAG_OUTSIDE) {
3927 windows.removeAt(i);
3928 } else {
3929 i += 1;
3930 }
3931 }
3932}
3933
3934const InputWindow* InputDispatcher::TouchState::getFirstForegroundWindow() {
3935 for (size_t i = 0; i < windows.size(); i++) {
3936 if (windows[i].targetFlags & InputTarget::FLAG_FOREGROUND) {
3937 return windows[i].window;
3938 }
3939 }
3940 return NULL;
3941}
3942
3943
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003944// --- InputDispatcherThread ---
3945
3946InputDispatcherThread::InputDispatcherThread(const sp<InputDispatcherInterface>& dispatcher) :
3947 Thread(/*canCallJava*/ true), mDispatcher(dispatcher) {
3948}
3949
3950InputDispatcherThread::~InputDispatcherThread() {
3951}
3952
3953bool InputDispatcherThread::threadLoop() {
3954 mDispatcher->dispatchOnce();
3955 return true;
3956}
3957
3958} // namespace android