blob: 456e0e6ecb41322065fc4e9db71e344a04722610 [file] [log] [blame]
Jeff Brownb4ff35d2011-01-02 16:37:43 -08001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Jeff Brown46b9ac02010-04-22 18:58:52 -070017#define LOG_TAG "InputDispatcher"
18
19//#define LOG_NDEBUG 0
20
21// Log detailed debug messages about each inbound event notification to the dispatcher.
Jeff Brown349703e2010-06-22 01:27:15 -070022#define DEBUG_INBOUND_EVENT_DETAILS 0
Jeff Brown46b9ac02010-04-22 18:58:52 -070023
24// Log detailed debug messages about each outbound event processed by the dispatcher.
Jeff Brown349703e2010-06-22 01:27:15 -070025#define DEBUG_OUTBOUND_EVENT_DETAILS 0
Jeff Brown46b9ac02010-04-22 18:58:52 -070026
27// Log debug messages about batching.
Jeff Brown349703e2010-06-22 01:27:15 -070028#define DEBUG_BATCHING 0
Jeff Brown46b9ac02010-04-22 18:58:52 -070029
30// Log debug messages about the dispatch cycle.
Jeff Brown349703e2010-06-22 01:27:15 -070031#define DEBUG_DISPATCH_CYCLE 0
Jeff Brown46b9ac02010-04-22 18:58:52 -070032
Jeff Brown9c3cda02010-06-15 01:31:58 -070033// Log debug messages about registrations.
Jeff Brown349703e2010-06-22 01:27:15 -070034#define DEBUG_REGISTRATION 0
Jeff Brown9c3cda02010-06-15 01:31:58 -070035
Jeff Brown46b9ac02010-04-22 18:58:52 -070036// Log debug messages about performance statistics.
Jeff Brown349703e2010-06-22 01:27:15 -070037#define DEBUG_PERFORMANCE_STATISTICS 0
Jeff Brown46b9ac02010-04-22 18:58:52 -070038
Jeff Brown7fbdc842010-06-17 20:52:56 -070039// Log debug messages about input event injection.
Jeff Brown349703e2010-06-22 01:27:15 -070040#define DEBUG_INJECTION 0
Jeff Brown7fbdc842010-06-17 20:52:56 -070041
Jeff Brownae9fc032010-08-18 15:51:08 -070042// Log debug messages about input event throttling.
43#define DEBUG_THROTTLING 0
44
Jeff Brownb88102f2010-09-08 11:49:43 -070045// Log debug messages about input focus tracking.
46#define DEBUG_FOCUS 0
47
48// Log debug messages about the app switch latency optimization.
49#define DEBUG_APP_SWITCH 0
50
Jeff Brownb4ff35d2011-01-02 16:37:43 -080051#include "InputDispatcher.h"
52
Jeff Brown46b9ac02010-04-22 18:58:52 -070053#include <cutils/log.h>
Jeff Brownb88102f2010-09-08 11:49:43 -070054#include <ui/PowerManager.h>
Jeff Brown46b9ac02010-04-22 18:58:52 -070055
56#include <stddef.h>
57#include <unistd.h>
Jeff Brown46b9ac02010-04-22 18:58:52 -070058#include <errno.h>
59#include <limits.h>
Jeff Brown46b9ac02010-04-22 18:58:52 -070060
Jeff Brownf2f48712010-10-01 17:46:21 -070061#define INDENT " "
62#define INDENT2 " "
63
Jeff Brown46b9ac02010-04-22 18:58:52 -070064namespace android {
65
Jeff Brownb88102f2010-09-08 11:49:43 -070066// Default input dispatching timeout if there is no focused application or paused window
67// from which to determine an appropriate dispatching timeout.
68const nsecs_t DEFAULT_INPUT_DISPATCHING_TIMEOUT = 5000 * 1000000LL; // 5 sec
69
70// Amount of time to allow for all pending events to be processed when an app switch
71// key is on the way. This is used to preempt input dispatch and drop input events
72// when an application takes too long to respond and the user has pressed an app switch key.
73const nsecs_t APP_SWITCH_TIMEOUT = 500 * 1000000LL; // 0.5sec
74
Jeff Brown928e0542011-01-10 11:17:36 -080075// Amount of time to allow for an event to be dispatched (measured since its eventTime)
76// before considering it stale and dropping it.
77const nsecs_t STALE_EVENT_TIMEOUT = 10000 * 1000000LL; // 10sec
78
Jeff Brown46b9ac02010-04-22 18:58:52 -070079
Jeff Brown7fbdc842010-06-17 20:52:56 -070080static inline nsecs_t now() {
81 return systemTime(SYSTEM_TIME_MONOTONIC);
82}
83
Jeff Brownb88102f2010-09-08 11:49:43 -070084static inline const char* toString(bool value) {
85 return value ? "true" : "false";
86}
87
Jeff Brown01ce2e92010-09-26 22:20:12 -070088static inline int32_t getMotionEventActionPointerIndex(int32_t action) {
89 return (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK)
90 >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
91}
92
93static bool isValidKeyAction(int32_t action) {
94 switch (action) {
95 case AKEY_EVENT_ACTION_DOWN:
96 case AKEY_EVENT_ACTION_UP:
97 return true;
98 default:
99 return false;
100 }
101}
102
103static bool validateKeyEvent(int32_t action) {
104 if (! isValidKeyAction(action)) {
105 LOGE("Key event has invalid action code 0x%x", action);
106 return false;
107 }
108 return true;
109}
110
Jeff Brownb6997262010-10-08 22:31:17 -0700111static bool isValidMotionAction(int32_t action, size_t pointerCount) {
Jeff Brown01ce2e92010-09-26 22:20:12 -0700112 switch (action & AMOTION_EVENT_ACTION_MASK) {
113 case AMOTION_EVENT_ACTION_DOWN:
114 case AMOTION_EVENT_ACTION_UP:
115 case AMOTION_EVENT_ACTION_CANCEL:
116 case AMOTION_EVENT_ACTION_MOVE:
Jeff Brown01ce2e92010-09-26 22:20:12 -0700117 case AMOTION_EVENT_ACTION_OUTSIDE:
Jeff Browncc0c1592011-02-19 05:07:28 -0800118 case AMOTION_EVENT_ACTION_HOVER_MOVE:
Jeff Brown33bbfd22011-02-24 20:55:35 -0800119 case AMOTION_EVENT_ACTION_SCROLL:
Jeff Brown01ce2e92010-09-26 22:20:12 -0700120 return true;
Jeff Brownb6997262010-10-08 22:31:17 -0700121 case AMOTION_EVENT_ACTION_POINTER_DOWN:
122 case AMOTION_EVENT_ACTION_POINTER_UP: {
123 int32_t index = getMotionEventActionPointerIndex(action);
124 return index >= 0 && size_t(index) < pointerCount;
125 }
Jeff Brown01ce2e92010-09-26 22:20:12 -0700126 default:
127 return false;
128 }
129}
130
131static bool validateMotionEvent(int32_t action, size_t pointerCount,
132 const int32_t* pointerIds) {
Jeff Brownb6997262010-10-08 22:31:17 -0700133 if (! isValidMotionAction(action, pointerCount)) {
Jeff Brown01ce2e92010-09-26 22:20:12 -0700134 LOGE("Motion event has invalid action code 0x%x", action);
135 return false;
136 }
137 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
138 LOGE("Motion event has invalid pointer count %d; value must be between 1 and %d.",
139 pointerCount, MAX_POINTERS);
140 return false;
141 }
Jeff Brownc3db8582010-10-20 15:33:38 -0700142 BitSet32 pointerIdBits;
Jeff Brown01ce2e92010-09-26 22:20:12 -0700143 for (size_t i = 0; i < pointerCount; i++) {
Jeff Brownc3db8582010-10-20 15:33:38 -0700144 int32_t id = pointerIds[i];
145 if (id < 0 || id > MAX_POINTER_ID) {
Jeff Brown01ce2e92010-09-26 22:20:12 -0700146 LOGE("Motion event has invalid pointer id %d; value must be between 0 and %d",
Jeff Brownc3db8582010-10-20 15:33:38 -0700147 id, MAX_POINTER_ID);
Jeff Brown01ce2e92010-09-26 22:20:12 -0700148 return false;
149 }
Jeff Brownc3db8582010-10-20 15:33:38 -0700150 if (pointerIdBits.hasBit(id)) {
151 LOGE("Motion event has duplicate pointer id %d", id);
152 return false;
153 }
154 pointerIdBits.markBit(id);
Jeff Brown01ce2e92010-09-26 22:20:12 -0700155 }
156 return true;
157}
158
Jeff Brownfbf09772011-01-16 14:06:57 -0800159static void dumpRegion(String8& dump, const SkRegion& region) {
160 if (region.isEmpty()) {
161 dump.append("<empty>");
162 return;
163 }
164
165 bool first = true;
166 for (SkRegion::Iterator it(region); !it.done(); it.next()) {
167 if (first) {
168 first = false;
169 } else {
170 dump.append("|");
171 }
172 const SkIRect& rect = it.rect();
173 dump.appendFormat("[%d,%d][%d,%d]", rect.fLeft, rect.fTop, rect.fRight, rect.fBottom);
174 }
175}
176
Jeff Brownb88102f2010-09-08 11:49:43 -0700177
Jeff Brown46b9ac02010-04-22 18:58:52 -0700178// --- InputDispatcher ---
179
Jeff Brown9c3cda02010-06-15 01:31:58 -0700180InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy) :
Jeff Brownb88102f2010-09-08 11:49:43 -0700181 mPolicy(policy),
Jeff Brown928e0542011-01-10 11:17:36 -0800182 mPendingEvent(NULL), mAppSwitchSawKeyDown(false), mAppSwitchDueTime(LONG_LONG_MAX),
183 mNextUnblockedEvent(NULL),
Jeff Brownb88102f2010-09-08 11:49:43 -0700184 mDispatchEnabled(true), mDispatchFrozen(false),
Jeff Brown01ce2e92010-09-26 22:20:12 -0700185 mFocusedWindow(NULL),
Jeff Brownb88102f2010-09-08 11:49:43 -0700186 mFocusedApplication(NULL),
187 mCurrentInputTargetsValid(false),
188 mInputTargetWaitCause(INPUT_TARGET_WAIT_CAUSE_NONE) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -0700189 mLooper = new Looper(false);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700190
Jeff Brownb88102f2010-09-08 11:49:43 -0700191 mInboundQueue.headSentinel.refCount = -1;
192 mInboundQueue.headSentinel.type = EventEntry::TYPE_SENTINEL;
193 mInboundQueue.headSentinel.eventTime = LONG_LONG_MIN;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700194
Jeff Brownb88102f2010-09-08 11:49:43 -0700195 mInboundQueue.tailSentinel.refCount = -1;
196 mInboundQueue.tailSentinel.type = EventEntry::TYPE_SENTINEL;
197 mInboundQueue.tailSentinel.eventTime = LONG_LONG_MAX;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700198
199 mKeyRepeatState.lastKeyEntry = NULL;
Jeff Brown9c3cda02010-06-15 01:31:58 -0700200
Jeff Brownae9fc032010-08-18 15:51:08 -0700201 int32_t maxEventsPerSecond = policy->getMaxEventsPerSecond();
202 mThrottleState.minTimeBetweenEvents = 1000000000LL / maxEventsPerSecond;
203 mThrottleState.lastDeviceId = -1;
204
205#if DEBUG_THROTTLING
206 mThrottleState.originalSampleCount = 0;
207 LOGD("Throttling - Max events per second = %d", maxEventsPerSecond);
208#endif
Jeff Brown46b9ac02010-04-22 18:58:52 -0700209}
210
211InputDispatcher::~InputDispatcher() {
Jeff Brownb88102f2010-09-08 11:49:43 -0700212 { // acquire lock
213 AutoMutex _l(mLock);
214
215 resetKeyRepeatLocked();
Jeff Brown54a18252010-09-16 14:07:33 -0700216 releasePendingEventLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -0700217 drainInboundQueueLocked();
218 }
Jeff Brown46b9ac02010-04-22 18:58:52 -0700219
220 while (mConnectionsByReceiveFd.size() != 0) {
221 unregisterInputChannel(mConnectionsByReceiveFd.valueAt(0)->inputChannel);
222 }
Jeff Brown46b9ac02010-04-22 18:58:52 -0700223}
224
225void InputDispatcher::dispatchOnce() {
Jeff Brown9c3cda02010-06-15 01:31:58 -0700226 nsecs_t keyRepeatTimeout = mPolicy->getKeyRepeatTimeout();
Jeff Brownb21fb102010-09-07 10:44:57 -0700227 nsecs_t keyRepeatDelay = mPolicy->getKeyRepeatDelay();
Jeff Brown46b9ac02010-04-22 18:58:52 -0700228
Jeff Brown46b9ac02010-04-22 18:58:52 -0700229 nsecs_t nextWakeupTime = LONG_LONG_MAX;
230 { // acquire lock
231 AutoMutex _l(mLock);
Jeff Brownb88102f2010-09-08 11:49:43 -0700232 dispatchOnceInnerLocked(keyRepeatTimeout, keyRepeatDelay, & nextWakeupTime);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700233
Jeff Brownb88102f2010-09-08 11:49:43 -0700234 if (runCommandsLockedInterruptible()) {
235 nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
Jeff Brown46b9ac02010-04-22 18:58:52 -0700236 }
Jeff Brown46b9ac02010-04-22 18:58:52 -0700237 } // release lock
238
Jeff Brownb88102f2010-09-08 11:49:43 -0700239 // Wait for callback or timeout or wake. (make sure we round up, not down)
240 nsecs_t currentTime = now();
Jeff Brownaa3855d2011-03-17 01:34:19 -0700241 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
Jeff Brown4fe6c3e2010-09-13 23:17:30 -0700242 mLooper->pollOnce(timeoutMillis);
Jeff Brownb88102f2010-09-08 11:49:43 -0700243}
244
245void InputDispatcher::dispatchOnceInnerLocked(nsecs_t keyRepeatTimeout,
246 nsecs_t keyRepeatDelay, nsecs_t* nextWakeupTime) {
247 nsecs_t currentTime = now();
248
249 // Reset the key repeat timer whenever we disallow key events, even if the next event
250 // is not a key. This is to ensure that we abort a key repeat if the device is just coming
251 // out of sleep.
252 if (keyRepeatTimeout < 0) {
253 resetKeyRepeatLocked();
254 }
255
Jeff Brownb88102f2010-09-08 11:49:43 -0700256 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
257 if (mDispatchFrozen) {
258#if DEBUG_FOCUS
259 LOGD("Dispatch frozen. Waiting some more.");
260#endif
261 return;
262 }
263
264 // Optimize latency of app switches.
265 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
266 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
267 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
268 if (mAppSwitchDueTime < *nextWakeupTime) {
269 *nextWakeupTime = mAppSwitchDueTime;
270 }
271
Jeff Brownb88102f2010-09-08 11:49:43 -0700272 // Ready to start a new event.
273 // If we don't already have a pending event, go grab one.
274 if (! mPendingEvent) {
275 if (mInboundQueue.isEmpty()) {
276 if (isAppSwitchDue) {
277 // The inbound queue is empty so the app switch key we were waiting
278 // for will never arrive. Stop waiting for it.
279 resetPendingAppSwitchLocked(false);
280 isAppSwitchDue = false;
281 }
282
283 // Synthesize a key repeat if appropriate.
284 if (mKeyRepeatState.lastKeyEntry) {
285 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
286 mPendingEvent = synthesizeKeyRepeatLocked(currentTime, keyRepeatDelay);
287 } else {
288 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
289 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
290 }
291 }
292 }
293 if (! mPendingEvent) {
294 return;
295 }
296 } else {
297 // Inbound queue has at least one entry.
298 EventEntry* entry = mInboundQueue.headSentinel.next;
299
300 // Throttle the entry if it is a move event and there are no
301 // other events behind it in the queue. Due to movement batching, additional
302 // samples may be appended to this event by the time the throttling timeout
303 // expires.
304 // TODO Make this smarter and consider throttling per device independently.
Jeff Brownb6997262010-10-08 22:31:17 -0700305 if (entry->type == EventEntry::TYPE_MOTION
306 && !isAppSwitchDue
307 && mDispatchEnabled
308 && (entry->policyFlags & POLICY_FLAG_PASS_TO_USER)
309 && !entry->isInjected()) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700310 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
311 int32_t deviceId = motionEntry->deviceId;
312 uint32_t source = motionEntry->source;
313 if (! isAppSwitchDue
314 && motionEntry->next == & mInboundQueue.tailSentinel // exactly one event
Jeff Browncc0c1592011-02-19 05:07:28 -0800315 && (motionEntry->action == AMOTION_EVENT_ACTION_MOVE
316 || motionEntry->action == AMOTION_EVENT_ACTION_HOVER_MOVE)
Jeff Brownb88102f2010-09-08 11:49:43 -0700317 && deviceId == mThrottleState.lastDeviceId
318 && source == mThrottleState.lastSource) {
319 nsecs_t nextTime = mThrottleState.lastEventTime
320 + mThrottleState.minTimeBetweenEvents;
321 if (currentTime < nextTime) {
322 // Throttle it!
323#if DEBUG_THROTTLING
324 LOGD("Throttling - Delaying motion event for "
Jeff Brown90655042010-12-02 13:50:46 -0800325 "device %d, source 0x%08x by up to %0.3fms.",
Jeff Brownb88102f2010-09-08 11:49:43 -0700326 deviceId, source, (nextTime - currentTime) * 0.000001);
327#endif
328 if (nextTime < *nextWakeupTime) {
329 *nextWakeupTime = nextTime;
330 }
331 if (mThrottleState.originalSampleCount == 0) {
332 mThrottleState.originalSampleCount =
333 motionEntry->countSamples();
334 }
335 return;
336 }
337 }
338
339#if DEBUG_THROTTLING
340 if (mThrottleState.originalSampleCount != 0) {
341 uint32_t count = motionEntry->countSamples();
342 LOGD("Throttling - Motion event sample count grew by %d from %d to %d.",
343 count - mThrottleState.originalSampleCount,
344 mThrottleState.originalSampleCount, count);
345 mThrottleState.originalSampleCount = 0;
346 }
347#endif
348
makarand.karvekarf634ded2011-03-02 15:41:03 -0600349 mThrottleState.lastEventTime = currentTime;
Jeff Brownb88102f2010-09-08 11:49:43 -0700350 mThrottleState.lastDeviceId = deviceId;
351 mThrottleState.lastSource = source;
352 }
353
354 mInboundQueue.dequeue(entry);
355 mPendingEvent = entry;
356 }
Jeff Browne2fe69e2010-10-18 13:21:23 -0700357
358 // Poke user activity for this event.
359 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
360 pokeUserActivityLocked(mPendingEvent);
361 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700362 }
363
364 // Now we have an event to dispatch.
Jeff Brown928e0542011-01-10 11:17:36 -0800365 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Jeff Brownb88102f2010-09-08 11:49:43 -0700366 assert(mPendingEvent != NULL);
Jeff Brown54a18252010-09-16 14:07:33 -0700367 bool done = false;
Jeff Brownb6997262010-10-08 22:31:17 -0700368 DropReason dropReason = DROP_REASON_NOT_DROPPED;
369 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
370 dropReason = DROP_REASON_POLICY;
371 } else if (!mDispatchEnabled) {
372 dropReason = DROP_REASON_DISABLED;
373 }
Jeff Brown928e0542011-01-10 11:17:36 -0800374
375 if (mNextUnblockedEvent == mPendingEvent) {
376 mNextUnblockedEvent = NULL;
377 }
378
Jeff Brownb88102f2010-09-08 11:49:43 -0700379 switch (mPendingEvent->type) {
380 case EventEntry::TYPE_CONFIGURATION_CHANGED: {
381 ConfigurationChangedEntry* typedEntry =
382 static_cast<ConfigurationChangedEntry*>(mPendingEvent);
Jeff Brown54a18252010-09-16 14:07:33 -0700383 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Jeff Brownb6997262010-10-08 22:31:17 -0700384 dropReason = DROP_REASON_NOT_DROPPED; // configuration changes are never dropped
Jeff Brownb88102f2010-09-08 11:49:43 -0700385 break;
386 }
387
388 case EventEntry::TYPE_KEY: {
389 KeyEntry* typedEntry = static_cast<KeyEntry*>(mPendingEvent);
Jeff Brownb6997262010-10-08 22:31:17 -0700390 if (isAppSwitchDue) {
391 if (isAppSwitchKeyEventLocked(typedEntry)) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700392 resetPendingAppSwitchLocked(true);
Jeff Brownb6997262010-10-08 22:31:17 -0700393 isAppSwitchDue = false;
394 } else if (dropReason == DROP_REASON_NOT_DROPPED) {
395 dropReason = DROP_REASON_APP_SWITCH;
Jeff Brownb88102f2010-09-08 11:49:43 -0700396 }
397 }
Jeff Brown928e0542011-01-10 11:17:36 -0800398 if (dropReason == DROP_REASON_NOT_DROPPED
399 && isStaleEventLocked(currentTime, typedEntry)) {
400 dropReason = DROP_REASON_STALE;
401 }
402 if (dropReason == DROP_REASON_NOT_DROPPED && mNextUnblockedEvent) {
403 dropReason = DROP_REASON_BLOCKED;
404 }
Jeff Brownb6997262010-10-08 22:31:17 -0700405 done = dispatchKeyLocked(currentTime, typedEntry, keyRepeatTimeout,
Jeff Browne20c9e02010-10-11 14:20:19 -0700406 &dropReason, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700407 break;
408 }
409
410 case EventEntry::TYPE_MOTION: {
411 MotionEntry* typedEntry = static_cast<MotionEntry*>(mPendingEvent);
Jeff Brownb6997262010-10-08 22:31:17 -0700412 if (dropReason == DROP_REASON_NOT_DROPPED && isAppSwitchDue) {
413 dropReason = DROP_REASON_APP_SWITCH;
Jeff Brownb88102f2010-09-08 11:49:43 -0700414 }
Jeff Brown928e0542011-01-10 11:17:36 -0800415 if (dropReason == DROP_REASON_NOT_DROPPED
416 && isStaleEventLocked(currentTime, typedEntry)) {
417 dropReason = DROP_REASON_STALE;
418 }
419 if (dropReason == DROP_REASON_NOT_DROPPED && mNextUnblockedEvent) {
420 dropReason = DROP_REASON_BLOCKED;
421 }
Jeff Brownb6997262010-10-08 22:31:17 -0700422 done = dispatchMotionLocked(currentTime, typedEntry,
Jeff Browne20c9e02010-10-11 14:20:19 -0700423 &dropReason, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700424 break;
425 }
426
427 default:
428 assert(false);
Jeff Brownb88102f2010-09-08 11:49:43 -0700429 break;
430 }
431
Jeff Brown54a18252010-09-16 14:07:33 -0700432 if (done) {
Jeff Brownb6997262010-10-08 22:31:17 -0700433 if (dropReason != DROP_REASON_NOT_DROPPED) {
434 dropInboundEventLocked(mPendingEvent, dropReason);
435 }
436
Jeff Brown54a18252010-09-16 14:07:33 -0700437 releasePendingEventLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -0700438 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
439 }
440}
441
442bool InputDispatcher::enqueueInboundEventLocked(EventEntry* entry) {
443 bool needWake = mInboundQueue.isEmpty();
444 mInboundQueue.enqueueAtTail(entry);
445
446 switch (entry->type) {
Jeff Brownb6997262010-10-08 22:31:17 -0700447 case EventEntry::TYPE_KEY: {
Jeff Brown928e0542011-01-10 11:17:36 -0800448 // Optimize app switch latency.
449 // If the application takes too long to catch up then we drop all events preceding
450 // the app switch key.
Jeff Brownb6997262010-10-08 22:31:17 -0700451 KeyEntry* keyEntry = static_cast<KeyEntry*>(entry);
452 if (isAppSwitchKeyEventLocked(keyEntry)) {
453 if (keyEntry->action == AKEY_EVENT_ACTION_DOWN) {
454 mAppSwitchSawKeyDown = true;
455 } else if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
456 if (mAppSwitchSawKeyDown) {
457#if DEBUG_APP_SWITCH
458 LOGD("App switch is pending!");
459#endif
460 mAppSwitchDueTime = keyEntry->eventTime + APP_SWITCH_TIMEOUT;
461 mAppSwitchSawKeyDown = false;
462 needWake = true;
463 }
464 }
465 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700466 break;
467 }
Jeff Brown928e0542011-01-10 11:17:36 -0800468
469 case EventEntry::TYPE_MOTION: {
470 // Optimize case where the current application is unresponsive and the user
471 // decides to touch a window in a different application.
472 // If the application takes too long to catch up then we drop all events preceding
473 // the touch into the other window.
474 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
Jeff Brown33bbfd22011-02-24 20:55:35 -0800475 if (motionEntry->action == AMOTION_EVENT_ACTION_DOWN
Jeff Brown928e0542011-01-10 11:17:36 -0800476 && (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER)
477 && mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY
478 && mInputTargetWaitApplication != NULL) {
Jeff Brown91c69ab2011-02-14 17:03:18 -0800479 int32_t x = int32_t(motionEntry->firstSample.pointerCoords[0].
Jeff Brownebbd5d12011-02-17 13:01:34 -0800480 getAxisValue(AMOTION_EVENT_AXIS_X));
Jeff Brown91c69ab2011-02-14 17:03:18 -0800481 int32_t y = int32_t(motionEntry->firstSample.pointerCoords[0].
Jeff Brownebbd5d12011-02-17 13:01:34 -0800482 getAxisValue(AMOTION_EVENT_AXIS_Y));
Jeff Brown928e0542011-01-10 11:17:36 -0800483 const InputWindow* touchedWindow = findTouchedWindowAtLocked(x, y);
484 if (touchedWindow
485 && touchedWindow->inputWindowHandle != NULL
486 && touchedWindow->inputWindowHandle->getInputApplicationHandle()
487 != mInputTargetWaitApplication) {
488 // User touched a different application than the one we are waiting on.
489 // Flag the event, and start pruning the input queue.
490 mNextUnblockedEvent = motionEntry;
491 needWake = true;
492 }
493 }
494 break;
495 }
Jeff Brownb6997262010-10-08 22:31:17 -0700496 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700497
498 return needWake;
499}
500
Jeff Brown928e0542011-01-10 11:17:36 -0800501const InputWindow* InputDispatcher::findTouchedWindowAtLocked(int32_t x, int32_t y) {
502 // Traverse windows from front to back to find touched window.
503 size_t numWindows = mWindows.size();
504 for (size_t i = 0; i < numWindows; i++) {
505 const InputWindow* window = & mWindows.editItemAt(i);
506 int32_t flags = window->layoutParamsFlags;
507
508 if (window->visible) {
509 if (!(flags & InputWindow::FLAG_NOT_TOUCHABLE)) {
510 bool isTouchModal = (flags & (InputWindow::FLAG_NOT_FOCUSABLE
511 | InputWindow::FLAG_NOT_TOUCH_MODAL)) == 0;
Jeff Brownfbf09772011-01-16 14:06:57 -0800512 if (isTouchModal || window->touchableRegionContainsPoint(x, y)) {
Jeff Brown928e0542011-01-10 11:17:36 -0800513 // Found window.
514 return window;
515 }
516 }
517 }
518
519 if (flags & InputWindow::FLAG_SYSTEM_ERROR) {
520 // Error window is on top but not visible, so touch is dropped.
521 return NULL;
522 }
523 }
524 return NULL;
525}
526
Jeff Brownb6997262010-10-08 22:31:17 -0700527void InputDispatcher::dropInboundEventLocked(EventEntry* entry, DropReason dropReason) {
528 const char* reason;
529 switch (dropReason) {
530 case DROP_REASON_POLICY:
Jeff Browne20c9e02010-10-11 14:20:19 -0700531#if DEBUG_INBOUND_EVENT_DETAILS
Jeff Brown3122e442010-10-11 23:32:49 -0700532 LOGD("Dropped event because policy consumed it.");
Jeff Browne20c9e02010-10-11 14:20:19 -0700533#endif
Jeff Brown3122e442010-10-11 23:32:49 -0700534 reason = "inbound event was dropped because the policy consumed it";
Jeff Brownb6997262010-10-08 22:31:17 -0700535 break;
536 case DROP_REASON_DISABLED:
537 LOGI("Dropped event because input dispatch is disabled.");
538 reason = "inbound event was dropped because input dispatch is disabled";
539 break;
540 case DROP_REASON_APP_SWITCH:
541 LOGI("Dropped event because of pending overdue app switch.");
542 reason = "inbound event was dropped because of pending overdue app switch";
543 break;
Jeff Brown928e0542011-01-10 11:17:36 -0800544 case DROP_REASON_BLOCKED:
545 LOGI("Dropped event because the current application is not responding and the user "
546 "has started interating with a different application.");
547 reason = "inbound event was dropped because the current application is not responding "
548 "and the user has started interating with a different application";
549 break;
550 case DROP_REASON_STALE:
551 LOGI("Dropped event because it is stale.");
552 reason = "inbound event was dropped because it is stale";
553 break;
Jeff Brownb6997262010-10-08 22:31:17 -0700554 default:
555 assert(false);
556 return;
557 }
558
559 switch (entry->type) {
560 case EventEntry::TYPE_KEY:
561 synthesizeCancelationEventsForAllConnectionsLocked(
562 InputState::CANCEL_NON_POINTER_EVENTS, reason);
563 break;
564 case EventEntry::TYPE_MOTION: {
565 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
566 if (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) {
567 synthesizeCancelationEventsForAllConnectionsLocked(
568 InputState::CANCEL_POINTER_EVENTS, reason);
569 } else {
570 synthesizeCancelationEventsForAllConnectionsLocked(
571 InputState::CANCEL_NON_POINTER_EVENTS, reason);
572 }
573 break;
574 }
575 }
576}
577
578bool InputDispatcher::isAppSwitchKeyCode(int32_t keyCode) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700579 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL;
580}
581
Jeff Brownb6997262010-10-08 22:31:17 -0700582bool InputDispatcher::isAppSwitchKeyEventLocked(KeyEntry* keyEntry) {
583 return ! (keyEntry->flags & AKEY_EVENT_FLAG_CANCELED)
584 && isAppSwitchKeyCode(keyEntry->keyCode)
Jeff Browne20c9e02010-10-11 14:20:19 -0700585 && (keyEntry->policyFlags & POLICY_FLAG_TRUSTED)
Jeff Brownb6997262010-10-08 22:31:17 -0700586 && (keyEntry->policyFlags & POLICY_FLAG_PASS_TO_USER);
587}
588
Jeff Brownb88102f2010-09-08 11:49:43 -0700589bool InputDispatcher::isAppSwitchPendingLocked() {
590 return mAppSwitchDueTime != LONG_LONG_MAX;
591}
592
Jeff Brownb88102f2010-09-08 11:49:43 -0700593void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
594 mAppSwitchDueTime = LONG_LONG_MAX;
595
596#if DEBUG_APP_SWITCH
597 if (handled) {
598 LOGD("App switch has arrived.");
599 } else {
600 LOGD("App switch was abandoned.");
601 }
602#endif
Jeff Brown46b9ac02010-04-22 18:58:52 -0700603}
604
Jeff Brown928e0542011-01-10 11:17:36 -0800605bool InputDispatcher::isStaleEventLocked(nsecs_t currentTime, EventEntry* entry) {
606 return currentTime - entry->eventTime >= STALE_EVENT_TIMEOUT;
607}
608
Jeff Brown9c3cda02010-06-15 01:31:58 -0700609bool InputDispatcher::runCommandsLockedInterruptible() {
610 if (mCommandQueue.isEmpty()) {
611 return false;
612 }
Jeff Brown46b9ac02010-04-22 18:58:52 -0700613
Jeff Brown9c3cda02010-06-15 01:31:58 -0700614 do {
615 CommandEntry* commandEntry = mCommandQueue.dequeueAtHead();
616
617 Command command = commandEntry->command;
618 (this->*command)(commandEntry); // commands are implicitly 'LockedInterruptible'
619
Jeff Brown7fbdc842010-06-17 20:52:56 -0700620 commandEntry->connection.clear();
Jeff Brown9c3cda02010-06-15 01:31:58 -0700621 mAllocator.releaseCommandEntry(commandEntry);
622 } while (! mCommandQueue.isEmpty());
623 return true;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700624}
625
Jeff Brown9c3cda02010-06-15 01:31:58 -0700626InputDispatcher::CommandEntry* InputDispatcher::postCommandLocked(Command command) {
627 CommandEntry* commandEntry = mAllocator.obtainCommandEntry(command);
628 mCommandQueue.enqueueAtTail(commandEntry);
629 return commandEntry;
630}
631
Jeff Brownb88102f2010-09-08 11:49:43 -0700632void InputDispatcher::drainInboundQueueLocked() {
633 while (! mInboundQueue.isEmpty()) {
634 EventEntry* entry = mInboundQueue.dequeueAtHead();
Jeff Brown54a18252010-09-16 14:07:33 -0700635 releaseInboundEventLocked(entry);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700636 }
Jeff Brown46b9ac02010-04-22 18:58:52 -0700637}
638
Jeff Brown54a18252010-09-16 14:07:33 -0700639void InputDispatcher::releasePendingEventLocked() {
Jeff Brownb88102f2010-09-08 11:49:43 -0700640 if (mPendingEvent) {
Jeff Brown54a18252010-09-16 14:07:33 -0700641 releaseInboundEventLocked(mPendingEvent);
Jeff Brownb88102f2010-09-08 11:49:43 -0700642 mPendingEvent = NULL;
643 }
644}
645
Jeff Brown54a18252010-09-16 14:07:33 -0700646void InputDispatcher::releaseInboundEventLocked(EventEntry* entry) {
Jeff Brown01ce2e92010-09-26 22:20:12 -0700647 InjectionState* injectionState = entry->injectionState;
648 if (injectionState && injectionState->injectionResult == INPUT_EVENT_INJECTION_PENDING) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700649#if DEBUG_DISPATCH_CYCLE
Jeff Brown01ce2e92010-09-26 22:20:12 -0700650 LOGD("Injected inbound event was dropped.");
Jeff Brownb88102f2010-09-08 11:49:43 -0700651#endif
652 setInjectionResultLocked(entry, INPUT_EVENT_INJECTION_FAILED);
653 }
654 mAllocator.releaseEventEntry(entry);
655}
656
Jeff Brownb88102f2010-09-08 11:49:43 -0700657void InputDispatcher::resetKeyRepeatLocked() {
658 if (mKeyRepeatState.lastKeyEntry) {
659 mAllocator.releaseKeyEntry(mKeyRepeatState.lastKeyEntry);
660 mKeyRepeatState.lastKeyEntry = NULL;
661 }
662}
663
664InputDispatcher::KeyEntry* InputDispatcher::synthesizeKeyRepeatLocked(
Jeff Brownb21fb102010-09-07 10:44:57 -0700665 nsecs_t currentTime, nsecs_t keyRepeatDelay) {
Jeff Brown349703e2010-06-22 01:27:15 -0700666 KeyEntry* entry = mKeyRepeatState.lastKeyEntry;
667
Jeff Brown349703e2010-06-22 01:27:15 -0700668 // Reuse the repeated key entry if it is otherwise unreferenced.
Jeff Browne20c9e02010-10-11 14:20:19 -0700669 uint32_t policyFlags = (entry->policyFlags & POLICY_FLAG_RAW_MASK)
670 | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700671 if (entry->refCount == 1) {
Jeff Brown01ce2e92010-09-26 22:20:12 -0700672 mAllocator.recycleKeyEntry(entry);
Jeff Brown7fbdc842010-06-17 20:52:56 -0700673 entry->eventTime = currentTime;
Jeff Brown7fbdc842010-06-17 20:52:56 -0700674 entry->policyFlags = policyFlags;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700675 entry->repeatCount += 1;
676 } else {
Jeff Brown7fbdc842010-06-17 20:52:56 -0700677 KeyEntry* newEntry = mAllocator.obtainKeyEntry(currentTime,
Jeff Brownc5ed5912010-07-14 18:48:53 -0700678 entry->deviceId, entry->source, policyFlags,
Jeff Brown7fbdc842010-06-17 20:52:56 -0700679 entry->action, entry->flags, entry->keyCode, entry->scanCode,
Jeff Brown00fa7bd2010-07-02 15:37:36 -0700680 entry->metaState, entry->repeatCount + 1, entry->downTime);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700681
682 mKeyRepeatState.lastKeyEntry = newEntry;
683 mAllocator.releaseKeyEntry(entry);
684
685 entry = newEntry;
686 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700687 entry->syntheticRepeat = true;
688
689 // Increment reference count since we keep a reference to the event in
690 // mKeyRepeatState.lastKeyEntry in addition to the one we return.
691 entry->refCount += 1;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700692
Jeff Brownb21fb102010-09-07 10:44:57 -0700693 mKeyRepeatState.nextRepeatTime = currentTime + keyRepeatDelay;
Jeff Brownb88102f2010-09-08 11:49:43 -0700694 return entry;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700695}
696
Jeff Brownb88102f2010-09-08 11:49:43 -0700697bool InputDispatcher::dispatchConfigurationChangedLocked(
698 nsecs_t currentTime, ConfigurationChangedEntry* entry) {
Jeff Brown46b9ac02010-04-22 18:58:52 -0700699#if DEBUG_OUTBOUND_EVENT_DETAILS
Jeff Brownb88102f2010-09-08 11:49:43 -0700700 LOGD("dispatchConfigurationChanged - eventTime=%lld", entry->eventTime);
701#endif
702
703 // Reset key repeating in case a keyboard device was added or removed or something.
704 resetKeyRepeatLocked();
705
706 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
707 CommandEntry* commandEntry = postCommandLocked(
708 & InputDispatcher::doNotifyConfigurationChangedInterruptible);
709 commandEntry->eventTime = entry->eventTime;
710 return true;
711}
712
713bool InputDispatcher::dispatchKeyLocked(
714 nsecs_t currentTime, KeyEntry* entry, nsecs_t keyRepeatTimeout,
Jeff Browne20c9e02010-10-11 14:20:19 -0700715 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Jeff Browne46a0a42010-11-02 17:58:22 -0700716 // Preprocessing.
717 if (! entry->dispatchInProgress) {
718 if (entry->repeatCount == 0
719 && entry->action == AKEY_EVENT_ACTION_DOWN
720 && (entry->policyFlags & POLICY_FLAG_TRUSTED)
721 && !entry->isInjected()) {
722 if (mKeyRepeatState.lastKeyEntry
723 && mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode) {
724 // We have seen two identical key downs in a row which indicates that the device
725 // driver is automatically generating key repeats itself. We take note of the
726 // repeat here, but we disable our own next key repeat timer since it is clear that
727 // we will not need to synthesize key repeats ourselves.
728 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
729 resetKeyRepeatLocked();
730 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
731 } else {
732 // Not a repeat. Save key down state in case we do see a repeat later.
733 resetKeyRepeatLocked();
734 mKeyRepeatState.nextRepeatTime = entry->eventTime + keyRepeatTimeout;
735 }
736 mKeyRepeatState.lastKeyEntry = entry;
737 entry->refCount += 1;
738 } else if (! entry->syntheticRepeat) {
739 resetKeyRepeatLocked();
740 }
741
Jeff Browne2e01262011-03-02 20:34:30 -0800742 if (entry->repeatCount == 1) {
743 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
744 } else {
745 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
746 }
747
Jeff Browne46a0a42010-11-02 17:58:22 -0700748 entry->dispatchInProgress = true;
749 resetTargetsLocked();
750
751 logOutboundKeyDetailsLocked("dispatchKey - ", entry);
752 }
753
Jeff Brown54a18252010-09-16 14:07:33 -0700754 // Give the policy a chance to intercept the key.
755 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
Jeff Browne20c9e02010-10-11 14:20:19 -0700756 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Jeff Brown54a18252010-09-16 14:07:33 -0700757 CommandEntry* commandEntry = postCommandLocked(
758 & InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
Jeff Browne20c9e02010-10-11 14:20:19 -0700759 if (mFocusedWindow) {
Jeff Brown928e0542011-01-10 11:17:36 -0800760 commandEntry->inputWindowHandle = mFocusedWindow->inputWindowHandle;
Jeff Brown54a18252010-09-16 14:07:33 -0700761 }
762 commandEntry->keyEntry = entry;
763 entry->refCount += 1;
764 return false; // wait for the command to run
765 } else {
766 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
767 }
768 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Jeff Browne20c9e02010-10-11 14:20:19 -0700769 if (*dropReason == DROP_REASON_NOT_DROPPED) {
770 *dropReason = DROP_REASON_POLICY;
771 }
Jeff Brown54a18252010-09-16 14:07:33 -0700772 }
773
774 // Clean up if dropping the event.
Jeff Browne20c9e02010-10-11 14:20:19 -0700775 if (*dropReason != DROP_REASON_NOT_DROPPED) {
Jeff Brown54a18252010-09-16 14:07:33 -0700776 resetTargetsLocked();
Jeff Brown3122e442010-10-11 23:32:49 -0700777 setInjectionResultLocked(entry, *dropReason == DROP_REASON_POLICY
778 ? INPUT_EVENT_INJECTION_SUCCEEDED : INPUT_EVENT_INJECTION_FAILED);
Jeff Brown54a18252010-09-16 14:07:33 -0700779 return true;
780 }
781
Jeff Brownb88102f2010-09-08 11:49:43 -0700782 // Identify targets.
783 if (! mCurrentInputTargetsValid) {
Jeff Brown01ce2e92010-09-26 22:20:12 -0700784 int32_t injectionResult = findFocusedWindowTargetsLocked(currentTime,
785 entry, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700786 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
787 return false;
788 }
789
790 setInjectionResultLocked(entry, injectionResult);
791 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
792 return true;
793 }
794
795 addMonitoringTargetsLocked();
Jeff Brown01ce2e92010-09-26 22:20:12 -0700796 commitTargetsLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -0700797 }
798
799 // Dispatch the key.
800 dispatchEventToCurrentInputTargetsLocked(currentTime, entry, false);
Jeff Brownb88102f2010-09-08 11:49:43 -0700801 return true;
802}
803
804void InputDispatcher::logOutboundKeyDetailsLocked(const char* prefix, const KeyEntry* entry) {
805#if DEBUG_OUTBOUND_EVENT_DETAILS
Jeff Brown90655042010-12-02 13:50:46 -0800806 LOGD("%seventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, "
Jeff Brownb88102f2010-09-08 11:49:43 -0700807 "action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, "
Jeff Browne46a0a42010-11-02 17:58:22 -0700808 "repeatCount=%d, downTime=%lld",
Jeff Brownb88102f2010-09-08 11:49:43 -0700809 prefix,
810 entry->eventTime, entry->deviceId, entry->source, entry->policyFlags,
811 entry->action, entry->flags, entry->keyCode, entry->scanCode, entry->metaState,
Jeff Browne46a0a42010-11-02 17:58:22 -0700812 entry->repeatCount, entry->downTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700813#endif
814}
815
816bool InputDispatcher::dispatchMotionLocked(
Jeff Browne20c9e02010-10-11 14:20:19 -0700817 nsecs_t currentTime, MotionEntry* entry, DropReason* dropReason, nsecs_t* nextWakeupTime) {
Jeff Browne46a0a42010-11-02 17:58:22 -0700818 // Preprocessing.
819 if (! entry->dispatchInProgress) {
820 entry->dispatchInProgress = true;
821 resetTargetsLocked();
822
823 logOutboundMotionDetailsLocked("dispatchMotion - ", entry);
824 }
825
Jeff Brown54a18252010-09-16 14:07:33 -0700826 // Clean up if dropping the event.
Jeff Browne20c9e02010-10-11 14:20:19 -0700827 if (*dropReason != DROP_REASON_NOT_DROPPED) {
Jeff Brown54a18252010-09-16 14:07:33 -0700828 resetTargetsLocked();
Jeff Brown3122e442010-10-11 23:32:49 -0700829 setInjectionResultLocked(entry, *dropReason == DROP_REASON_POLICY
830 ? INPUT_EVENT_INJECTION_SUCCEEDED : INPUT_EVENT_INJECTION_FAILED);
Jeff Brown54a18252010-09-16 14:07:33 -0700831 return true;
832 }
833
Jeff Brownb88102f2010-09-08 11:49:43 -0700834 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
835
836 // Identify targets.
Jeff Browncc0c1592011-02-19 05:07:28 -0800837 bool conflictingPointerActions = false;
Jeff Brownb88102f2010-09-08 11:49:43 -0700838 if (! mCurrentInputTargetsValid) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700839 int32_t injectionResult;
840 if (isPointerEvent) {
841 // Pointer event. (eg. touchscreen)
Jeff Brown01ce2e92010-09-26 22:20:12 -0700842 injectionResult = findTouchedWindowTargetsLocked(currentTime,
Jeff Browncc0c1592011-02-19 05:07:28 -0800843 entry, nextWakeupTime, &conflictingPointerActions);
Jeff Brownb88102f2010-09-08 11:49:43 -0700844 } else {
845 // Non touch event. (eg. trackball)
Jeff Brown01ce2e92010-09-26 22:20:12 -0700846 injectionResult = findFocusedWindowTargetsLocked(currentTime,
847 entry, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700848 }
849 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
850 return false;
851 }
852
853 setInjectionResultLocked(entry, injectionResult);
854 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
855 return true;
856 }
857
858 addMonitoringTargetsLocked();
Jeff Brown01ce2e92010-09-26 22:20:12 -0700859 commitTargetsLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -0700860 }
861
862 // Dispatch the motion.
Jeff Browncc0c1592011-02-19 05:07:28 -0800863 if (conflictingPointerActions) {
864 synthesizeCancelationEventsForAllConnectionsLocked(
865 InputState::CANCEL_POINTER_EVENTS, "Conflicting pointer actions.");
866 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700867 dispatchEventToCurrentInputTargetsLocked(currentTime, entry, false);
Jeff Brownb88102f2010-09-08 11:49:43 -0700868 return true;
869}
870
871
872void InputDispatcher::logOutboundMotionDetailsLocked(const char* prefix, const MotionEntry* entry) {
873#if DEBUG_OUTBOUND_EVENT_DETAILS
Jeff Brown90655042010-12-02 13:50:46 -0800874 LOGD("%seventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, "
Jeff Brown85a31762010-09-01 17:01:00 -0700875 "action=0x%x, flags=0x%x, "
Jeff Brown46b9ac02010-04-22 18:58:52 -0700876 "metaState=0x%x, edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%lld",
Jeff Brownb88102f2010-09-08 11:49:43 -0700877 prefix,
Jeff Brown85a31762010-09-01 17:01:00 -0700878 entry->eventTime, entry->deviceId, entry->source, entry->policyFlags,
879 entry->action, entry->flags,
Jeff Brown46b9ac02010-04-22 18:58:52 -0700880 entry->metaState, entry->edgeFlags, entry->xPrecision, entry->yPrecision,
881 entry->downTime);
882
883 // Print the most recent sample that we have available, this may change due to batching.
884 size_t sampleCount = 1;
Jeff Brownb88102f2010-09-08 11:49:43 -0700885 const MotionSample* sample = & entry->firstSample;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700886 for (; sample->next != NULL; sample = sample->next) {
887 sampleCount += 1;
888 }
889 for (uint32_t i = 0; i < entry->pointerCount; i++) {
Jeff Brown8d608662010-08-30 03:02:23 -0700890 LOGD(" Pointer %d: id=%d, x=%f, y=%f, pressure=%f, size=%f, "
Jeff Brown85a31762010-09-01 17:01:00 -0700891 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
Jeff Brown8d608662010-08-30 03:02:23 -0700892 "orientation=%f",
Jeff Brown46b9ac02010-04-22 18:58:52 -0700893 i, entry->pointerIds[i],
Jeff Brownebbd5d12011-02-17 13:01:34 -0800894 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
895 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
896 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
897 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
898 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
899 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
900 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
901 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
902 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Jeff Brown46b9ac02010-04-22 18:58:52 -0700903 }
904
905 // Keep in mind that due to batching, it is possible for the number of samples actually
906 // dispatched to change before the application finally consumed them.
Jeff Brownc5ed5912010-07-14 18:48:53 -0700907 if (entry->action == AMOTION_EVENT_ACTION_MOVE) {
Jeff Brown46b9ac02010-04-22 18:58:52 -0700908 LOGD(" ... Total movement samples currently batched %d ...", sampleCount);
909 }
910#endif
Jeff Brown46b9ac02010-04-22 18:58:52 -0700911}
912
913void InputDispatcher::dispatchEventToCurrentInputTargetsLocked(nsecs_t currentTime,
914 EventEntry* eventEntry, bool resumeWithAppendedMotionSample) {
915#if DEBUG_DISPATCH_CYCLE
Jeff Brown9c3cda02010-06-15 01:31:58 -0700916 LOGD("dispatchEventToCurrentInputTargets - "
Jeff Brown46b9ac02010-04-22 18:58:52 -0700917 "resumeWithAppendedMotionSample=%s",
Jeff Brownb88102f2010-09-08 11:49:43 -0700918 toString(resumeWithAppendedMotionSample));
Jeff Brown46b9ac02010-04-22 18:58:52 -0700919#endif
920
Jeff Brown9c3cda02010-06-15 01:31:58 -0700921 assert(eventEntry->dispatchInProgress); // should already have been set to true
922
Jeff Browne2fe69e2010-10-18 13:21:23 -0700923 pokeUserActivityLocked(eventEntry);
924
Jeff Brown46b9ac02010-04-22 18:58:52 -0700925 for (size_t i = 0; i < mCurrentInputTargets.size(); i++) {
926 const InputTarget& inputTarget = mCurrentInputTargets.itemAt(i);
927
Jeff Brown519e0242010-09-15 15:18:56 -0700928 ssize_t connectionIndex = getConnectionIndexLocked(inputTarget.inputChannel);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700929 if (connectionIndex >= 0) {
930 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
Jeff Brown7fbdc842010-06-17 20:52:56 -0700931 prepareDispatchCycleLocked(currentTime, connection, eventEntry, & inputTarget,
Jeff Brown46b9ac02010-04-22 18:58:52 -0700932 resumeWithAppendedMotionSample);
933 } else {
Jeff Brownb6997262010-10-08 22:31:17 -0700934#if DEBUG_FOCUS
935 LOGD("Dropping event delivery to target with channel '%s' because it "
936 "is no longer registered with the input dispatcher.",
Jeff Brown46b9ac02010-04-22 18:58:52 -0700937 inputTarget.inputChannel->getName().string());
Jeff Brownb6997262010-10-08 22:31:17 -0700938#endif
Jeff Brown46b9ac02010-04-22 18:58:52 -0700939 }
940 }
941}
942
Jeff Brown54a18252010-09-16 14:07:33 -0700943void InputDispatcher::resetTargetsLocked() {
Jeff Brownb88102f2010-09-08 11:49:43 -0700944 mCurrentInputTargetsValid = false;
945 mCurrentInputTargets.clear();
Jeff Brownb88102f2010-09-08 11:49:43 -0700946 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_NONE;
Jeff Brown928e0542011-01-10 11:17:36 -0800947 mInputTargetWaitApplication.clear();
Jeff Brownb88102f2010-09-08 11:49:43 -0700948}
949
Jeff Brown01ce2e92010-09-26 22:20:12 -0700950void InputDispatcher::commitTargetsLocked() {
Jeff Brownb88102f2010-09-08 11:49:43 -0700951 mCurrentInputTargetsValid = true;
952}
953
954int32_t InputDispatcher::handleTargetsNotReadyLocked(nsecs_t currentTime,
955 const EventEntry* entry, const InputApplication* application, const InputWindow* window,
956 nsecs_t* nextWakeupTime) {
957 if (application == NULL && window == NULL) {
958 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY) {
959#if DEBUG_FOCUS
960 LOGD("Waiting for system to become ready for input.");
961#endif
962 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY;
963 mInputTargetWaitStartTime = currentTime;
964 mInputTargetWaitTimeoutTime = LONG_LONG_MAX;
965 mInputTargetWaitTimeoutExpired = false;
Jeff Brown928e0542011-01-10 11:17:36 -0800966 mInputTargetWaitApplication.clear();
Jeff Brownb88102f2010-09-08 11:49:43 -0700967 }
968 } else {
969 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
970#if DEBUG_FOCUS
Jeff Brown519e0242010-09-15 15:18:56 -0700971 LOGD("Waiting for application to become ready for input: %s",
972 getApplicationWindowLabelLocked(application, window).string());
Jeff Brownb88102f2010-09-08 11:49:43 -0700973#endif
974 nsecs_t timeout = window ? window->dispatchingTimeout :
975 application ? application->dispatchingTimeout : DEFAULT_INPUT_DISPATCHING_TIMEOUT;
976
977 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY;
978 mInputTargetWaitStartTime = currentTime;
979 mInputTargetWaitTimeoutTime = currentTime + timeout;
980 mInputTargetWaitTimeoutExpired = false;
Jeff Brown928e0542011-01-10 11:17:36 -0800981 mInputTargetWaitApplication.clear();
982
983 if (window && window->inputWindowHandle != NULL) {
984 mInputTargetWaitApplication =
985 window->inputWindowHandle->getInputApplicationHandle();
986 }
987 if (mInputTargetWaitApplication == NULL && application) {
988 mInputTargetWaitApplication = application->inputApplicationHandle;
989 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700990 }
991 }
992
993 if (mInputTargetWaitTimeoutExpired) {
994 return INPUT_EVENT_INJECTION_TIMED_OUT;
995 }
996
997 if (currentTime >= mInputTargetWaitTimeoutTime) {
Jeff Brown519e0242010-09-15 15:18:56 -0700998 onANRLocked(currentTime, application, window, entry->eventTime, mInputTargetWaitStartTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700999
1000 // Force poll loop to wake up immediately on next iteration once we get the
1001 // ANR response back from the policy.
1002 *nextWakeupTime = LONG_LONG_MIN;
1003 return INPUT_EVENT_INJECTION_PENDING;
1004 } else {
1005 // Force poll loop to wake up when timeout is due.
1006 if (mInputTargetWaitTimeoutTime < *nextWakeupTime) {
1007 *nextWakeupTime = mInputTargetWaitTimeoutTime;
1008 }
1009 return INPUT_EVENT_INJECTION_PENDING;
1010 }
1011}
1012
Jeff Brown519e0242010-09-15 15:18:56 -07001013void InputDispatcher::resumeAfterTargetsNotReadyTimeoutLocked(nsecs_t newTimeout,
1014 const sp<InputChannel>& inputChannel) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001015 if (newTimeout > 0) {
1016 // Extend the timeout.
1017 mInputTargetWaitTimeoutTime = now() + newTimeout;
1018 } else {
1019 // Give up.
1020 mInputTargetWaitTimeoutExpired = true;
Jeff Brown519e0242010-09-15 15:18:56 -07001021
Jeff Brown01ce2e92010-09-26 22:20:12 -07001022 // Release the touch targets.
1023 mTouchState.reset();
Jeff Brown2a95c2a2010-09-16 12:31:46 -07001024
Jeff Brown519e0242010-09-15 15:18:56 -07001025 // Input state will not be realistic. Mark it out of sync.
Jeff Browndc3e0052010-09-16 11:02:16 -07001026 if (inputChannel.get()) {
1027 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
1028 if (connectionIndex >= 0) {
1029 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
Jeff Brown00045a72010-12-09 18:10:30 -08001030 if (connection->status == Connection::STATUS_NORMAL) {
1031 synthesizeCancelationEventsForConnectionLocked(
1032 connection, InputState::CANCEL_ALL_EVENTS,
1033 "application not responding");
1034 }
Jeff Browndc3e0052010-09-16 11:02:16 -07001035 }
Jeff Brown519e0242010-09-15 15:18:56 -07001036 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001037 }
1038}
1039
Jeff Brown519e0242010-09-15 15:18:56 -07001040nsecs_t InputDispatcher::getTimeSpentWaitingForApplicationLocked(
Jeff Brownb88102f2010-09-08 11:49:43 -07001041 nsecs_t currentTime) {
1042 if (mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
1043 return currentTime - mInputTargetWaitStartTime;
1044 }
1045 return 0;
1046}
1047
1048void InputDispatcher::resetANRTimeoutsLocked() {
1049#if DEBUG_FOCUS
1050 LOGD("Resetting ANR timeouts.");
1051#endif
1052
Jeff Brownb88102f2010-09-08 11:49:43 -07001053 // Reset input target wait timeout.
1054 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_NONE;
1055}
1056
Jeff Brown01ce2e92010-09-26 22:20:12 -07001057int32_t InputDispatcher::findFocusedWindowTargetsLocked(nsecs_t currentTime,
1058 const EventEntry* entry, nsecs_t* nextWakeupTime) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001059 mCurrentInputTargets.clear();
1060
1061 int32_t injectionResult;
1062
1063 // If there is no currently focused window and no focused application
1064 // then drop the event.
1065 if (! mFocusedWindow) {
1066 if (mFocusedApplication) {
1067#if DEBUG_FOCUS
1068 LOGD("Waiting because there is no focused window but there is a "
Jeff Brown519e0242010-09-15 15:18:56 -07001069 "focused application that may eventually add a window: %s.",
1070 getApplicationWindowLabelLocked(mFocusedApplication, NULL).string());
Jeff Brownb88102f2010-09-08 11:49:43 -07001071#endif
1072 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
1073 mFocusedApplication, NULL, nextWakeupTime);
1074 goto Unresponsive;
1075 }
1076
1077 LOGI("Dropping event because there is no focused window or focused application.");
1078 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1079 goto Failed;
1080 }
1081
1082 // Check permissions.
Jeff Brown01ce2e92010-09-26 22:20:12 -07001083 if (! checkInjectionPermission(mFocusedWindow, entry->injectionState)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001084 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1085 goto Failed;
1086 }
1087
1088 // If the currently focused window is paused then keep waiting.
1089 if (mFocusedWindow->paused) {
1090#if DEBUG_FOCUS
1091 LOGD("Waiting because focused window is paused.");
1092#endif
1093 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
1094 mFocusedApplication, mFocusedWindow, nextWakeupTime);
1095 goto Unresponsive;
1096 }
1097
Jeff Brown519e0242010-09-15 15:18:56 -07001098 // If the currently focused window is still working on previous events then keep waiting.
1099 if (! isWindowFinishedWithPreviousInputLocked(mFocusedWindow)) {
1100#if DEBUG_FOCUS
1101 LOGD("Waiting because focused window still processing previous input.");
1102#endif
1103 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
1104 mFocusedApplication, mFocusedWindow, nextWakeupTime);
1105 goto Unresponsive;
1106 }
1107
Jeff Brownb88102f2010-09-08 11:49:43 -07001108 // Success! Output targets.
1109 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001110 addWindowTargetLocked(mFocusedWindow, InputTarget::FLAG_FOREGROUND, BitSet32(0));
Jeff Brownb88102f2010-09-08 11:49:43 -07001111
1112 // Done.
1113Failed:
1114Unresponsive:
Jeff Brown519e0242010-09-15 15:18:56 -07001115 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
1116 updateDispatchStatisticsLocked(currentTime, entry,
1117 injectionResult, timeSpentWaitingForApplication);
Jeff Brownb88102f2010-09-08 11:49:43 -07001118#if DEBUG_FOCUS
Jeff Brown519e0242010-09-15 15:18:56 -07001119 LOGD("findFocusedWindow finished: injectionResult=%d, "
1120 "timeSpendWaitingForApplication=%0.1fms",
1121 injectionResult, timeSpentWaitingForApplication / 1000000.0);
Jeff Brownb88102f2010-09-08 11:49:43 -07001122#endif
1123 return injectionResult;
1124}
1125
Jeff Brown01ce2e92010-09-26 22:20:12 -07001126int32_t InputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime,
Jeff Browncc0c1592011-02-19 05:07:28 -08001127 const MotionEntry* entry, nsecs_t* nextWakeupTime, bool* outConflictingPointerActions) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001128 enum InjectionPermission {
1129 INJECTION_PERMISSION_UNKNOWN,
1130 INJECTION_PERMISSION_GRANTED,
1131 INJECTION_PERMISSION_DENIED
1132 };
1133
Jeff Brownb88102f2010-09-08 11:49:43 -07001134 mCurrentInputTargets.clear();
1135
1136 nsecs_t startTime = now();
1137
1138 // For security reasons, we defer updating the touch state until we are sure that
1139 // event injection will be allowed.
1140 //
1141 // FIXME In the original code, screenWasOff could never be set to true.
1142 // The reason is that the POLICY_FLAG_WOKE_HERE
1143 // and POLICY_FLAG_BRIGHT_HERE flags were set only when preprocessing raw
1144 // EV_KEY, EV_REL and EV_ABS events. As it happens, the touch event was
1145 // actually enqueued using the policyFlags that appeared in the final EV_SYN
1146 // events upon which no preprocessing took place. So policyFlags was always 0.
1147 // In the new native input dispatcher we're a bit more careful about event
1148 // preprocessing so the touches we receive can actually have non-zero policyFlags.
1149 // Unfortunately we obtain undesirable behavior.
1150 //
1151 // Here's what happens:
1152 //
1153 // When the device dims in anticipation of going to sleep, touches
1154 // in windows which have FLAG_TOUCHABLE_WHEN_WAKING cause
1155 // the device to brighten and reset the user activity timer.
1156 // Touches on other windows (such as the launcher window)
1157 // are dropped. Then after a moment, the device goes to sleep. Oops.
1158 //
1159 // Also notice how screenWasOff was being initialized using POLICY_FLAG_BRIGHT_HERE
1160 // instead of POLICY_FLAG_WOKE_HERE...
1161 //
1162 bool screenWasOff = false; // original policy: policyFlags & POLICY_FLAG_BRIGHT_HERE;
1163
1164 int32_t action = entry->action;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001165 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Jeff Brownb88102f2010-09-08 11:49:43 -07001166
1167 // Update the touch state as needed based on the properties of the touch event.
Jeff Brown01ce2e92010-09-26 22:20:12 -07001168 int32_t injectionResult = INPUT_EVENT_INJECTION_PENDING;
1169 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
Jeff Browncc0c1592011-02-19 05:07:28 -08001170
1171 bool isSplit = mTouchState.split;
1172 bool wrongDevice = mTouchState.down
1173 && (mTouchState.deviceId != entry->deviceId
1174 || mTouchState.source != entry->source);
1175 if (maskedAction == AMOTION_EVENT_ACTION_DOWN
Jeff Brown33bbfd22011-02-24 20:55:35 -08001176 || maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE
1177 || maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
Jeff Browncc0c1592011-02-19 05:07:28 -08001178 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
1179 if (wrongDevice && !down) {
1180 mTempTouchState.copyFrom(mTouchState);
1181 } else {
1182 mTempTouchState.reset();
1183 mTempTouchState.down = down;
1184 mTempTouchState.deviceId = entry->deviceId;
1185 mTempTouchState.source = entry->source;
1186 isSplit = false;
1187 wrongDevice = false;
1188 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001189 } else {
1190 mTempTouchState.copyFrom(mTouchState);
Jeff Browncc0c1592011-02-19 05:07:28 -08001191 }
1192 if (wrongDevice) {
Jeff Brown95712852011-01-04 19:41:59 -08001193#if DEBUG_INPUT_DISPATCHER_POLICY
Jeff Browncc0c1592011-02-19 05:07:28 -08001194 LOGD("Dropping event because a pointer for a different device is already down.");
Jeff Brown95712852011-01-04 19:41:59 -08001195#endif
Jeff Browncc0c1592011-02-19 05:07:28 -08001196 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1197 goto Failed;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001198 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001199
Jeff Brown01ce2e92010-09-26 22:20:12 -07001200 if (maskedAction == AMOTION_EVENT_ACTION_DOWN
Jeff Browncc0c1592011-02-19 05:07:28 -08001201 || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)
Jeff Brown33bbfd22011-02-24 20:55:35 -08001202 || maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE
1203 || maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
1204 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
Jeff Brownb88102f2010-09-08 11:49:43 -07001205
Jeff Brown01ce2e92010-09-26 22:20:12 -07001206 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Jeff Brown91c69ab2011-02-14 17:03:18 -08001207 int32_t x = int32_t(entry->firstSample.pointerCoords[pointerIndex].
Jeff Brownebbd5d12011-02-17 13:01:34 -08001208 getAxisValue(AMOTION_EVENT_AXIS_X));
Jeff Brown91c69ab2011-02-14 17:03:18 -08001209 int32_t y = int32_t(entry->firstSample.pointerCoords[pointerIndex].
Jeff Brownebbd5d12011-02-17 13:01:34 -08001210 getAxisValue(AMOTION_EVENT_AXIS_Y));
Jeff Brown01ce2e92010-09-26 22:20:12 -07001211 const InputWindow* newTouchedWindow = NULL;
1212 const InputWindow* topErrorWindow = NULL;
Jeff Brownb88102f2010-09-08 11:49:43 -07001213
1214 // Traverse windows from front to back to find touched window and outside targets.
1215 size_t numWindows = mWindows.size();
1216 for (size_t i = 0; i < numWindows; i++) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001217 const InputWindow* window = & mWindows.editItemAt(i);
Jeff Brownb88102f2010-09-08 11:49:43 -07001218 int32_t flags = window->layoutParamsFlags;
1219
1220 if (flags & InputWindow::FLAG_SYSTEM_ERROR) {
1221 if (! topErrorWindow) {
1222 topErrorWindow = window;
1223 }
1224 }
1225
1226 if (window->visible) {
1227 if (! (flags & InputWindow::FLAG_NOT_TOUCHABLE)) {
1228 bool isTouchModal = (flags & (InputWindow::FLAG_NOT_FOCUSABLE
1229 | InputWindow::FLAG_NOT_TOUCH_MODAL)) == 0;
Jeff Brownfbf09772011-01-16 14:06:57 -08001230 if (isTouchModal || window->touchableRegionContainsPoint(x, y)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001231 if (! screenWasOff || flags & InputWindow::FLAG_TOUCHABLE_WHEN_WAKING) {
1232 newTouchedWindow = window;
Jeff Brownb88102f2010-09-08 11:49:43 -07001233 }
1234 break; // found touched window, exit window loop
1235 }
1236 }
1237
Jeff Brown01ce2e92010-09-26 22:20:12 -07001238 if (maskedAction == AMOTION_EVENT_ACTION_DOWN
1239 && (flags & InputWindow::FLAG_WATCH_OUTSIDE_TOUCH)) {
Jeff Brown19dfc832010-10-05 12:26:23 -07001240 int32_t outsideTargetFlags = InputTarget::FLAG_OUTSIDE;
1241 if (isWindowObscuredAtPointLocked(window, x, y)) {
1242 outsideTargetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1243 }
1244
1245 mTempTouchState.addOrUpdateWindow(window, outsideTargetFlags, BitSet32(0));
Jeff Brownb88102f2010-09-08 11:49:43 -07001246 }
1247 }
1248 }
1249
1250 // If there is an error window but it is not taking focus (typically because
1251 // it is invisible) then wait for it. Any other focused window may in
1252 // fact be in ANR state.
1253 if (topErrorWindow && newTouchedWindow != topErrorWindow) {
1254#if DEBUG_FOCUS
1255 LOGD("Waiting because system error window is pending.");
1256#endif
1257 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
1258 NULL, NULL, nextWakeupTime);
1259 injectionPermission = INJECTION_PERMISSION_UNKNOWN;
1260 goto Unresponsive;
1261 }
1262
Jeff Brown01ce2e92010-09-26 22:20:12 -07001263 // Figure out whether splitting will be allowed for this window.
Jeff Brown46e75292010-11-10 16:53:45 -08001264 if (newTouchedWindow && newTouchedWindow->supportsSplitTouch()) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001265 // New window supports splitting.
1266 isSplit = true;
1267 } else if (isSplit) {
1268 // New window does not support splitting but we have already split events.
1269 // Assign the pointer to the first foreground window we find.
1270 // (May be NULL which is why we put this code block before the next check.)
1271 newTouchedWindow = mTempTouchState.getFirstForegroundWindow();
1272 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001273
Jeff Brownb88102f2010-09-08 11:49:43 -07001274 // If we did not find a touched window then fail.
1275 if (! newTouchedWindow) {
1276 if (mFocusedApplication) {
1277#if DEBUG_FOCUS
1278 LOGD("Waiting because there is no touched window but there is a "
Jeff Brown519e0242010-09-15 15:18:56 -07001279 "focused application that may eventually add a new window: %s.",
1280 getApplicationWindowLabelLocked(mFocusedApplication, NULL).string());
Jeff Brownb88102f2010-09-08 11:49:43 -07001281#endif
1282 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
1283 mFocusedApplication, NULL, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -07001284 goto Unresponsive;
1285 }
1286
1287 LOGI("Dropping event because there is no touched window or focused application.");
1288 injectionResult = INPUT_EVENT_INJECTION_FAILED;
Jeff Brownb88102f2010-09-08 11:49:43 -07001289 goto Failed;
1290 }
1291
Jeff Brown19dfc832010-10-05 12:26:23 -07001292 // Set target flags.
1293 int32_t targetFlags = InputTarget::FLAG_FOREGROUND;
1294 if (isSplit) {
1295 targetFlags |= InputTarget::FLAG_SPLIT;
1296 }
1297 if (isWindowObscuredAtPointLocked(newTouchedWindow, x, y)) {
1298 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1299 }
1300
Jeff Brown01ce2e92010-09-26 22:20:12 -07001301 // Update the temporary touch state.
1302 BitSet32 pointerIds;
1303 if (isSplit) {
1304 uint32_t pointerId = entry->pointerIds[pointerIndex];
1305 pointerIds.markBit(pointerId);
Jeff Brownb88102f2010-09-08 11:49:43 -07001306 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001307 mTempTouchState.addOrUpdateWindow(newTouchedWindow, targetFlags, pointerIds);
Jeff Brownb88102f2010-09-08 11:49:43 -07001308 } else {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001309 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
Jeff Brownb88102f2010-09-08 11:49:43 -07001310
1311 // If the pointer is not currently down, then ignore the event.
Jeff Brown01ce2e92010-09-26 22:20:12 -07001312 if (! mTempTouchState.down) {
Jeff Brown76860e32010-10-25 17:37:46 -07001313#if DEBUG_INPUT_DISPATCHER_POLICY
1314 LOGD("Dropping event because the pointer is not down or we previously "
1315 "dropped the pointer down event.");
1316#endif
Jeff Brownb88102f2010-09-08 11:49:43 -07001317 injectionResult = INPUT_EVENT_INJECTION_FAILED;
Jeff Brownb88102f2010-09-08 11:49:43 -07001318 goto Failed;
1319 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001320 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001321
Jeff Brown01ce2e92010-09-26 22:20:12 -07001322 // Check permission to inject into all touched foreground windows and ensure there
1323 // is at least one touched foreground window.
1324 {
1325 bool haveForegroundWindow = false;
1326 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1327 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1328 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1329 haveForegroundWindow = true;
1330 if (! checkInjectionPermission(touchedWindow.window, entry->injectionState)) {
1331 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1332 injectionPermission = INJECTION_PERMISSION_DENIED;
1333 goto Failed;
1334 }
1335 }
1336 }
1337 if (! haveForegroundWindow) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001338#if DEBUG_INPUT_DISPATCHER_POLICY
Jeff Brown01ce2e92010-09-26 22:20:12 -07001339 LOGD("Dropping event because there is no touched foreground window to receive it.");
Jeff Brownb88102f2010-09-08 11:49:43 -07001340#endif
1341 injectionResult = INPUT_EVENT_INJECTION_FAILED;
Jeff Brownb88102f2010-09-08 11:49:43 -07001342 goto Failed;
1343 }
1344
Jeff Brown01ce2e92010-09-26 22:20:12 -07001345 // Permission granted to injection into all touched foreground windows.
1346 injectionPermission = INJECTION_PERMISSION_GRANTED;
1347 }
Jeff Brown519e0242010-09-15 15:18:56 -07001348
Jeff Brown01ce2e92010-09-26 22:20:12 -07001349 // Ensure all touched foreground windows are ready for new input.
1350 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1351 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1352 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1353 // If the touched window is paused then keep waiting.
1354 if (touchedWindow.window->paused) {
1355#if DEBUG_INPUT_DISPATCHER_POLICY
1356 LOGD("Waiting because touched window is paused.");
Jeff Brown519e0242010-09-15 15:18:56 -07001357#endif
Jeff Brown01ce2e92010-09-26 22:20:12 -07001358 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
1359 NULL, touchedWindow.window, nextWakeupTime);
1360 goto Unresponsive;
1361 }
1362
1363 // If the touched window is still working on previous events then keep waiting.
1364 if (! isWindowFinishedWithPreviousInputLocked(touchedWindow.window)) {
1365#if DEBUG_FOCUS
1366 LOGD("Waiting because touched window still processing previous input.");
1367#endif
1368 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
1369 NULL, touchedWindow.window, nextWakeupTime);
1370 goto Unresponsive;
1371 }
1372 }
1373 }
1374
1375 // If this is the first pointer going down and the touched window has a wallpaper
1376 // then also add the touched wallpaper windows so they are locked in for the duration
1377 // of the touch gesture.
Jeff Brown33bbfd22011-02-24 20:55:35 -08001378 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
1379 // engine only supports touch events. We would need to add a mechanism similar
1380 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
1381 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001382 const InputWindow* foregroundWindow = mTempTouchState.getFirstForegroundWindow();
1383 if (foregroundWindow->hasWallpaper) {
1384 for (size_t i = 0; i < mWindows.size(); i++) {
1385 const InputWindow* window = & mWindows[i];
1386 if (window->layoutParamsType == InputWindow::TYPE_WALLPAPER) {
Jeff Brown19dfc832010-10-05 12:26:23 -07001387 mTempTouchState.addOrUpdateWindow(window,
1388 InputTarget::FLAG_WINDOW_IS_OBSCURED, BitSet32(0));
Jeff Brown01ce2e92010-09-26 22:20:12 -07001389 }
1390 }
1391 }
1392 }
1393
Jeff Brownb88102f2010-09-08 11:49:43 -07001394 // Success! Output targets.
1395 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
Jeff Brownb88102f2010-09-08 11:49:43 -07001396
Jeff Brown01ce2e92010-09-26 22:20:12 -07001397 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1398 const TouchedWindow& touchedWindow = mTempTouchState.windows.itemAt(i);
1399 addWindowTargetLocked(touchedWindow.window, touchedWindow.targetFlags,
1400 touchedWindow.pointerIds);
Jeff Brownb88102f2010-09-08 11:49:43 -07001401 }
1402
Jeff Brown01ce2e92010-09-26 22:20:12 -07001403 // Drop the outside touch window since we will not care about them in the next iteration.
1404 mTempTouchState.removeOutsideTouchWindows();
1405
Jeff Brownb88102f2010-09-08 11:49:43 -07001406Failed:
1407 // Check injection permission once and for all.
1408 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001409 if (checkInjectionPermission(NULL, entry->injectionState)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001410 injectionPermission = INJECTION_PERMISSION_GRANTED;
1411 } else {
1412 injectionPermission = INJECTION_PERMISSION_DENIED;
1413 }
1414 }
1415
1416 // Update final pieces of touch state if the injector had permission.
1417 if (injectionPermission == INJECTION_PERMISSION_GRANTED) {
Jeff Brown95712852011-01-04 19:41:59 -08001418 if (!wrongDevice) {
1419 if (maskedAction == AMOTION_EVENT_ACTION_UP
Jeff Browncc0c1592011-02-19 05:07:28 -08001420 || maskedAction == AMOTION_EVENT_ACTION_CANCEL
1421 || maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Jeff Brown95712852011-01-04 19:41:59 -08001422 // All pointers up or canceled.
Jeff Brown33bbfd22011-02-24 20:55:35 -08001423 mTouchState.reset();
Jeff Brown95712852011-01-04 19:41:59 -08001424 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1425 // First pointer went down.
1426 if (mTouchState.down) {
Jeff Browncc0c1592011-02-19 05:07:28 -08001427 *outConflictingPointerActions = true;
Jeff Brownb6997262010-10-08 22:31:17 -07001428#if DEBUG_FOCUS
Jeff Brown95712852011-01-04 19:41:59 -08001429 LOGD("Pointer down received while already down.");
Jeff Brownb6997262010-10-08 22:31:17 -07001430#endif
Jeff Brown95712852011-01-04 19:41:59 -08001431 }
Jeff Brown33bbfd22011-02-24 20:55:35 -08001432 mTouchState.copyFrom(mTempTouchState);
Jeff Brown95712852011-01-04 19:41:59 -08001433 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
1434 // One pointer went up.
1435 if (isSplit) {
1436 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
1437 uint32_t pointerId = entry->pointerIds[pointerIndex];
Jeff Brownb88102f2010-09-08 11:49:43 -07001438
Jeff Brown95712852011-01-04 19:41:59 -08001439 for (size_t i = 0; i < mTempTouchState.windows.size(); ) {
1440 TouchedWindow& touchedWindow = mTempTouchState.windows.editItemAt(i);
1441 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
1442 touchedWindow.pointerIds.clearBit(pointerId);
1443 if (touchedWindow.pointerIds.isEmpty()) {
1444 mTempTouchState.windows.removeAt(i);
1445 continue;
1446 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001447 }
Jeff Brown95712852011-01-04 19:41:59 -08001448 i += 1;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001449 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001450 }
Jeff Brown33bbfd22011-02-24 20:55:35 -08001451 mTouchState.copyFrom(mTempTouchState);
1452 } else if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
1453 // Discard temporary touch state since it was only valid for this action.
1454 } else {
1455 // Save changes to touch state as-is for all other actions.
1456 mTouchState.copyFrom(mTempTouchState);
Jeff Brownb88102f2010-09-08 11:49:43 -07001457 }
Jeff Brown95712852011-01-04 19:41:59 -08001458 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001459 } else {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001460#if DEBUG_FOCUS
1461 LOGD("Not updating touch focus because injection was denied.");
1462#endif
Jeff Brownb88102f2010-09-08 11:49:43 -07001463 }
1464
1465Unresponsive:
Jeff Brown120a4592010-10-27 18:43:51 -07001466 // Reset temporary touch state to ensure we release unnecessary references to input channels.
1467 mTempTouchState.reset();
1468
Jeff Brown519e0242010-09-15 15:18:56 -07001469 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
1470 updateDispatchStatisticsLocked(currentTime, entry,
1471 injectionResult, timeSpentWaitingForApplication);
Jeff Brownb88102f2010-09-08 11:49:43 -07001472#if DEBUG_FOCUS
Jeff Brown01ce2e92010-09-26 22:20:12 -07001473 LOGD("findTouchedWindow finished: injectionResult=%d, injectionPermission=%d, "
1474 "timeSpentWaitingForApplication=%0.1fms",
Jeff Brown519e0242010-09-15 15:18:56 -07001475 injectionResult, injectionPermission, timeSpentWaitingForApplication / 1000000.0);
Jeff Brownb88102f2010-09-08 11:49:43 -07001476#endif
1477 return injectionResult;
1478}
1479
Jeff Brown01ce2e92010-09-26 22:20:12 -07001480void InputDispatcher::addWindowTargetLocked(const InputWindow* window, int32_t targetFlags,
1481 BitSet32 pointerIds) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001482 mCurrentInputTargets.push();
1483
1484 InputTarget& target = mCurrentInputTargets.editTop();
1485 target.inputChannel = window->inputChannel;
1486 target.flags = targetFlags;
Jeff Brownb88102f2010-09-08 11:49:43 -07001487 target.xOffset = - window->frameLeft;
1488 target.yOffset = - window->frameTop;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001489 target.pointerIds = pointerIds;
Jeff Brownb88102f2010-09-08 11:49:43 -07001490}
1491
1492void InputDispatcher::addMonitoringTargetsLocked() {
1493 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
1494 mCurrentInputTargets.push();
1495
1496 InputTarget& target = mCurrentInputTargets.editTop();
1497 target.inputChannel = mMonitoringChannels[i];
1498 target.flags = 0;
Jeff Brownb88102f2010-09-08 11:49:43 -07001499 target.xOffset = 0;
1500 target.yOffset = 0;
1501 }
1502}
1503
1504bool InputDispatcher::checkInjectionPermission(const InputWindow* window,
Jeff Brown01ce2e92010-09-26 22:20:12 -07001505 const InjectionState* injectionState) {
1506 if (injectionState
Jeff Brownb6997262010-10-08 22:31:17 -07001507 && (window == NULL || window->ownerUid != injectionState->injectorUid)
1508 && !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
1509 if (window) {
1510 LOGW("Permission denied: injecting event from pid %d uid %d to window "
1511 "with input channel %s owned by uid %d",
1512 injectionState->injectorPid, injectionState->injectorUid,
1513 window->inputChannel->getName().string(),
1514 window->ownerUid);
1515 } else {
1516 LOGW("Permission denied: injecting event from pid %d uid %d",
1517 injectionState->injectorPid, injectionState->injectorUid);
Jeff Brownb88102f2010-09-08 11:49:43 -07001518 }
Jeff Brownb6997262010-10-08 22:31:17 -07001519 return false;
Jeff Brownb88102f2010-09-08 11:49:43 -07001520 }
1521 return true;
1522}
1523
Jeff Brown19dfc832010-10-05 12:26:23 -07001524bool InputDispatcher::isWindowObscuredAtPointLocked(
1525 const InputWindow* window, int32_t x, int32_t y) const {
Jeff Brownb88102f2010-09-08 11:49:43 -07001526 size_t numWindows = mWindows.size();
1527 for (size_t i = 0; i < numWindows; i++) {
1528 const InputWindow* other = & mWindows.itemAt(i);
1529 if (other == window) {
1530 break;
1531 }
Jeff Brown19dfc832010-10-05 12:26:23 -07001532 if (other->visible && ! other->isTrustedOverlay() && other->frameContainsPoint(x, y)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001533 return true;
1534 }
1535 }
1536 return false;
1537}
1538
Jeff Brown519e0242010-09-15 15:18:56 -07001539bool InputDispatcher::isWindowFinishedWithPreviousInputLocked(const InputWindow* window) {
1540 ssize_t connectionIndex = getConnectionIndexLocked(window->inputChannel);
1541 if (connectionIndex >= 0) {
1542 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
1543 return connection->outboundQueue.isEmpty();
1544 } else {
1545 return true;
1546 }
1547}
1548
1549String8 InputDispatcher::getApplicationWindowLabelLocked(const InputApplication* application,
1550 const InputWindow* window) {
1551 if (application) {
1552 if (window) {
1553 String8 label(application->name);
1554 label.append(" - ");
1555 label.append(window->name);
1556 return label;
1557 } else {
1558 return application->name;
1559 }
1560 } else if (window) {
1561 return window->name;
1562 } else {
1563 return String8("<unknown application or window>");
1564 }
1565}
1566
Jeff Browne2fe69e2010-10-18 13:21:23 -07001567void InputDispatcher::pokeUserActivityLocked(const EventEntry* eventEntry) {
Jeff Brown56194eb2011-03-02 19:23:13 -08001568 int32_t eventType = POWER_MANAGER_OTHER_EVENT;
Jeff Brown4d396052010-10-29 21:50:21 -07001569 switch (eventEntry->type) {
1570 case EventEntry::TYPE_MOTION: {
Jeff Browne2fe69e2010-10-18 13:21:23 -07001571 const MotionEntry* motionEntry = static_cast<const MotionEntry*>(eventEntry);
Jeff Brown4d396052010-10-29 21:50:21 -07001572 if (motionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
1573 return;
1574 }
1575
Jeff Brown56194eb2011-03-02 19:23:13 -08001576 if (MotionEvent::isTouchEvent(motionEntry->source, motionEntry->action)) {
Joe Onorato1a542c72010-11-08 09:48:20 -08001577 eventType = POWER_MANAGER_TOUCH_EVENT;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001578 }
Jeff Brown4d396052010-10-29 21:50:21 -07001579 break;
1580 }
1581 case EventEntry::TYPE_KEY: {
1582 const KeyEntry* keyEntry = static_cast<const KeyEntry*>(eventEntry);
1583 if (keyEntry->flags & AKEY_EVENT_FLAG_CANCELED) {
1584 return;
1585 }
Jeff Brown56194eb2011-03-02 19:23:13 -08001586 eventType = POWER_MANAGER_BUTTON_EVENT;
Jeff Brown4d396052010-10-29 21:50:21 -07001587 break;
1588 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001589 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001590
Jeff Brownb88102f2010-09-08 11:49:43 -07001591 CommandEntry* commandEntry = postCommandLocked(
1592 & InputDispatcher::doPokeUserActivityLockedInterruptible);
Jeff Browne2fe69e2010-10-18 13:21:23 -07001593 commandEntry->eventTime = eventEntry->eventTime;
Jeff Brownb88102f2010-09-08 11:49:43 -07001594 commandEntry->userActivityEventType = eventType;
1595}
1596
Jeff Brown7fbdc842010-06-17 20:52:56 -07001597void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
1598 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget,
Jeff Brown46b9ac02010-04-22 18:58:52 -07001599 bool resumeWithAppendedMotionSample) {
1600#if DEBUG_DISPATCH_CYCLE
Jeff Brown519e0242010-09-15 15:18:56 -07001601 LOGD("channel '%s' ~ prepareDispatchCycle - flags=%d, "
Jeff Brown01ce2e92010-09-26 22:20:12 -07001602 "xOffset=%f, yOffset=%f, "
Jeff Brown83c09682010-12-23 17:50:18 -08001603 "pointerIds=0x%x, "
Jeff Brown01ce2e92010-09-26 22:20:12 -07001604 "resumeWithAppendedMotionSample=%s",
Jeff Brown519e0242010-09-15 15:18:56 -07001605 connection->getInputChannelName(), inputTarget->flags,
Jeff Brown46b9ac02010-04-22 18:58:52 -07001606 inputTarget->xOffset, inputTarget->yOffset,
Jeff Brown83c09682010-12-23 17:50:18 -08001607 inputTarget->pointerIds.value,
Jeff Brownb88102f2010-09-08 11:49:43 -07001608 toString(resumeWithAppendedMotionSample));
Jeff Brown46b9ac02010-04-22 18:58:52 -07001609#endif
1610
Jeff Brown01ce2e92010-09-26 22:20:12 -07001611 // Make sure we are never called for streaming when splitting across multiple windows.
1612 bool isSplit = inputTarget->flags & InputTarget::FLAG_SPLIT;
1613 assert(! (resumeWithAppendedMotionSample && isSplit));
1614
Jeff Brown46b9ac02010-04-22 18:58:52 -07001615 // Skip this event if the connection status is not normal.
Jeff Brown519e0242010-09-15 15:18:56 -07001616 // We don't want to enqueue additional outbound events if the connection is broken.
Jeff Brown46b9ac02010-04-22 18:58:52 -07001617 if (connection->status != Connection::STATUS_NORMAL) {
Jeff Brownb6997262010-10-08 22:31:17 -07001618#if DEBUG_DISPATCH_CYCLE
1619 LOGD("channel '%s' ~ Dropping event because the channel status is %s",
Jeff Brownb88102f2010-09-08 11:49:43 -07001620 connection->getInputChannelName(), connection->getStatusLabel());
Jeff Brownb6997262010-10-08 22:31:17 -07001621#endif
Jeff Brown46b9ac02010-04-22 18:58:52 -07001622 return;
1623 }
1624
Jeff Brown01ce2e92010-09-26 22:20:12 -07001625 // Split a motion event if needed.
1626 if (isSplit) {
1627 assert(eventEntry->type == EventEntry::TYPE_MOTION);
1628
1629 MotionEntry* originalMotionEntry = static_cast<MotionEntry*>(eventEntry);
1630 if (inputTarget->pointerIds.count() != originalMotionEntry->pointerCount) {
1631 MotionEntry* splitMotionEntry = splitMotionEvent(
1632 originalMotionEntry, inputTarget->pointerIds);
Jeff Brown58a2da82011-01-25 16:02:22 -08001633 if (!splitMotionEntry) {
1634 return; // split event was dropped
1635 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001636#if DEBUG_FOCUS
1637 LOGD("channel '%s' ~ Split motion event.",
1638 connection->getInputChannelName());
1639 logOutboundMotionDetailsLocked(" ", splitMotionEntry);
1640#endif
1641 eventEntry = splitMotionEntry;
1642 }
1643 }
1644
Jeff Brown46b9ac02010-04-22 18:58:52 -07001645 // Resume the dispatch cycle with a freshly appended motion sample.
1646 // First we check that the last dispatch entry in the outbound queue is for the same
1647 // motion event to which we appended the motion sample. If we find such a dispatch
1648 // entry, and if it is currently in progress then we try to stream the new sample.
1649 bool wasEmpty = connection->outboundQueue.isEmpty();
1650
1651 if (! wasEmpty && resumeWithAppendedMotionSample) {
1652 DispatchEntry* motionEventDispatchEntry =
1653 connection->findQueuedDispatchEntryForEvent(eventEntry);
1654 if (motionEventDispatchEntry) {
1655 // If the dispatch entry is not in progress, then we must be busy dispatching an
1656 // earlier event. Not a problem, the motion event is on the outbound queue and will
1657 // be dispatched later.
1658 if (! motionEventDispatchEntry->inProgress) {
1659#if DEBUG_BATCHING
1660 LOGD("channel '%s' ~ Not streaming because the motion event has "
1661 "not yet been dispatched. "
1662 "(Waiting for earlier events to be consumed.)",
1663 connection->getInputChannelName());
1664#endif
1665 return;
1666 }
1667
1668 // If the dispatch entry is in progress but it already has a tail of pending
1669 // motion samples, then it must mean that the shared memory buffer filled up.
1670 // Not a problem, when this dispatch cycle is finished, we will eventually start
1671 // a new dispatch cycle to process the tail and that tail includes the newly
1672 // appended motion sample.
1673 if (motionEventDispatchEntry->tailMotionSample) {
1674#if DEBUG_BATCHING
1675 LOGD("channel '%s' ~ Not streaming because no new samples can "
1676 "be appended to the motion event in this dispatch cycle. "
1677 "(Waiting for next dispatch cycle to start.)",
1678 connection->getInputChannelName());
1679#endif
1680 return;
1681 }
1682
1683 // The dispatch entry is in progress and is still potentially open for streaming.
1684 // Try to stream the new motion sample. This might fail if the consumer has already
1685 // consumed the motion event (or if the channel is broken).
Jeff Brown01ce2e92010-09-26 22:20:12 -07001686 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
1687 MotionSample* appendedMotionSample = motionEntry->lastSample;
Jeff Brown46b9ac02010-04-22 18:58:52 -07001688 status_t status = connection->inputPublisher.appendMotionSample(
1689 appendedMotionSample->eventTime, appendedMotionSample->pointerCoords);
1690 if (status == OK) {
1691#if DEBUG_BATCHING
1692 LOGD("channel '%s' ~ Successfully streamed new motion sample.",
1693 connection->getInputChannelName());
1694#endif
1695 return;
1696 }
1697
1698#if DEBUG_BATCHING
1699 if (status == NO_MEMORY) {
1700 LOGD("channel '%s' ~ Could not append motion sample to currently "
1701 "dispatched move event because the shared memory buffer is full. "
1702 "(Waiting for next dispatch cycle to start.)",
1703 connection->getInputChannelName());
1704 } else if (status == status_t(FAILED_TRANSACTION)) {
1705 LOGD("channel '%s' ~ Could not append motion sample to currently "
Jeff Brown349703e2010-06-22 01:27:15 -07001706 "dispatched move event because the event has already been consumed. "
Jeff Brown46b9ac02010-04-22 18:58:52 -07001707 "(Waiting for next dispatch cycle to start.)",
1708 connection->getInputChannelName());
1709 } else {
1710 LOGD("channel '%s' ~ Could not append motion sample to currently "
1711 "dispatched move event due to an error, status=%d. "
1712 "(Waiting for next dispatch cycle to start.)",
1713 connection->getInputChannelName(), status);
1714 }
1715#endif
1716 // Failed to stream. Start a new tail of pending motion samples to dispatch
1717 // in the next cycle.
1718 motionEventDispatchEntry->tailMotionSample = appendedMotionSample;
1719 return;
1720 }
1721 }
1722
1723 // This is a new event.
1724 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Jeff Brownb88102f2010-09-08 11:49:43 -07001725 DispatchEntry* dispatchEntry = mAllocator.obtainDispatchEntry(eventEntry, // increments ref
Jeff Brown519e0242010-09-15 15:18:56 -07001726 inputTarget->flags, inputTarget->xOffset, inputTarget->yOffset);
1727 if (dispatchEntry->hasForegroundTarget()) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001728 incrementPendingForegroundDispatchesLocked(eventEntry);
Jeff Brown6ec402b2010-07-28 15:48:59 -07001729 }
1730
Jeff Brown46b9ac02010-04-22 18:58:52 -07001731 // Handle the case where we could not stream a new motion sample because the consumer has
1732 // already consumed the motion event (otherwise the corresponding dispatch entry would
1733 // still be in the outbound queue for this connection). We set the head motion sample
1734 // to the list starting with the newly appended motion sample.
1735 if (resumeWithAppendedMotionSample) {
1736#if DEBUG_BATCHING
1737 LOGD("channel '%s' ~ Preparing a new dispatch cycle for additional motion samples "
1738 "that cannot be streamed because the motion event has already been consumed.",
1739 connection->getInputChannelName());
1740#endif
1741 MotionSample* appendedMotionSample = static_cast<MotionEntry*>(eventEntry)->lastSample;
1742 dispatchEntry->headMotionSample = appendedMotionSample;
1743 }
1744
1745 // Enqueue the dispatch entry.
1746 connection->outboundQueue.enqueueAtTail(dispatchEntry);
1747
1748 // If the outbound queue was previously empty, start the dispatch cycle going.
1749 if (wasEmpty) {
Jeff Brown7fbdc842010-06-17 20:52:56 -07001750 activateConnectionLocked(connection.get());
Jeff Brown519e0242010-09-15 15:18:56 -07001751 startDispatchCycleLocked(currentTime, connection);
Jeff Brown46b9ac02010-04-22 18:58:52 -07001752 }
1753}
1754
Jeff Brown7fbdc842010-06-17 20:52:56 -07001755void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Jeff Brown519e0242010-09-15 15:18:56 -07001756 const sp<Connection>& connection) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07001757#if DEBUG_DISPATCH_CYCLE
1758 LOGD("channel '%s' ~ startDispatchCycle",
1759 connection->getInputChannelName());
1760#endif
1761
1762 assert(connection->status == Connection::STATUS_NORMAL);
1763 assert(! connection->outboundQueue.isEmpty());
1764
Jeff Brownb88102f2010-09-08 11:49:43 -07001765 DispatchEntry* dispatchEntry = connection->outboundQueue.headSentinel.next;
Jeff Brown46b9ac02010-04-22 18:58:52 -07001766 assert(! dispatchEntry->inProgress);
1767
Jeff Brownb88102f2010-09-08 11:49:43 -07001768 // Mark the dispatch entry as in progress.
1769 dispatchEntry->inProgress = true;
1770
1771 // Update the connection's input state.
Jeff Brown01ce2e92010-09-26 22:20:12 -07001772 EventEntry* eventEntry = dispatchEntry->eventEntry;
Jeff Browncc0c1592011-02-19 05:07:28 -08001773 connection->inputState.trackEvent(eventEntry);
Jeff Brown46b9ac02010-04-22 18:58:52 -07001774
1775 // Publish the event.
1776 status_t status;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001777 switch (eventEntry->type) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07001778 case EventEntry::TYPE_KEY: {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001779 KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
Jeff Brown46b9ac02010-04-22 18:58:52 -07001780
1781 // Apply target flags.
1782 int32_t action = keyEntry->action;
1783 int32_t flags = keyEntry->flags;
Jeff Brown46b9ac02010-04-22 18:58:52 -07001784
1785 // Publish the key event.
Jeff Brownc5ed5912010-07-14 18:48:53 -07001786 status = connection->inputPublisher.publishKeyEvent(keyEntry->deviceId, keyEntry->source,
Jeff Brown46b9ac02010-04-22 18:58:52 -07001787 action, flags, keyEntry->keyCode, keyEntry->scanCode,
1788 keyEntry->metaState, keyEntry->repeatCount, keyEntry->downTime,
1789 keyEntry->eventTime);
1790
1791 if (status) {
1792 LOGE("channel '%s' ~ Could not publish key event, "
1793 "status=%d", connection->getInputChannelName(), status);
Jeff Brownb6997262010-10-08 22:31:17 -07001794 abortBrokenDispatchCycleLocked(currentTime, connection);
Jeff Brown46b9ac02010-04-22 18:58:52 -07001795 return;
1796 }
1797 break;
1798 }
1799
1800 case EventEntry::TYPE_MOTION: {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001801 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
Jeff Brown46b9ac02010-04-22 18:58:52 -07001802
1803 // Apply target flags.
1804 int32_t action = motionEntry->action;
Jeff Brown85a31762010-09-01 17:01:00 -07001805 int32_t flags = motionEntry->flags;
Jeff Brown46b9ac02010-04-22 18:58:52 -07001806 if (dispatchEntry->targetFlags & InputTarget::FLAG_OUTSIDE) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001807 action = AMOTION_EVENT_ACTION_OUTSIDE;
Jeff Brown46b9ac02010-04-22 18:58:52 -07001808 }
Jeff Brown85a31762010-09-01 17:01:00 -07001809 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
1810 flags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
1811 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07001812
1813 // If headMotionSample is non-NULL, then it points to the first new sample that we
1814 // were unable to dispatch during the previous cycle so we resume dispatching from
1815 // that point in the list of motion samples.
1816 // Otherwise, we just start from the first sample of the motion event.
1817 MotionSample* firstMotionSample = dispatchEntry->headMotionSample;
1818 if (! firstMotionSample) {
1819 firstMotionSample = & motionEntry->firstSample;
1820 }
1821
Jeff Brownd3616592010-07-16 17:21:06 -07001822 // Set the X and Y offset depending on the input source.
1823 float xOffset, yOffset;
1824 if (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) {
1825 xOffset = dispatchEntry->xOffset;
1826 yOffset = dispatchEntry->yOffset;
1827 } else {
1828 xOffset = 0.0f;
1829 yOffset = 0.0f;
1830 }
1831
Jeff Brown46b9ac02010-04-22 18:58:52 -07001832 // Publish the motion event and the first motion sample.
1833 status = connection->inputPublisher.publishMotionEvent(motionEntry->deviceId,
Jeff Brown85a31762010-09-01 17:01:00 -07001834 motionEntry->source, action, flags, motionEntry->edgeFlags, motionEntry->metaState,
Jeff Brownd3616592010-07-16 17:21:06 -07001835 xOffset, yOffset,
Jeff Brown46b9ac02010-04-22 18:58:52 -07001836 motionEntry->xPrecision, motionEntry->yPrecision,
1837 motionEntry->downTime, firstMotionSample->eventTime,
1838 motionEntry->pointerCount, motionEntry->pointerIds,
1839 firstMotionSample->pointerCoords);
1840
1841 if (status) {
1842 LOGE("channel '%s' ~ Could not publish motion event, "
1843 "status=%d", connection->getInputChannelName(), status);
Jeff Brownb6997262010-10-08 22:31:17 -07001844 abortBrokenDispatchCycleLocked(currentTime, connection);
Jeff Brown46b9ac02010-04-22 18:58:52 -07001845 return;
1846 }
1847
1848 // Append additional motion samples.
1849 MotionSample* nextMotionSample = firstMotionSample->next;
1850 for (; nextMotionSample != NULL; nextMotionSample = nextMotionSample->next) {
1851 status = connection->inputPublisher.appendMotionSample(
1852 nextMotionSample->eventTime, nextMotionSample->pointerCoords);
1853 if (status == NO_MEMORY) {
1854#if DEBUG_DISPATCH_CYCLE
1855 LOGD("channel '%s' ~ Shared memory buffer full. Some motion samples will "
1856 "be sent in the next dispatch cycle.",
1857 connection->getInputChannelName());
1858#endif
1859 break;
1860 }
1861 if (status != OK) {
1862 LOGE("channel '%s' ~ Could not append motion sample "
1863 "for a reason other than out of memory, status=%d",
1864 connection->getInputChannelName(), status);
Jeff Brownb6997262010-10-08 22:31:17 -07001865 abortBrokenDispatchCycleLocked(currentTime, connection);
Jeff Brown46b9ac02010-04-22 18:58:52 -07001866 return;
1867 }
1868 }
1869
1870 // Remember the next motion sample that we could not dispatch, in case we ran out
1871 // of space in the shared memory buffer.
1872 dispatchEntry->tailMotionSample = nextMotionSample;
1873 break;
1874 }
1875
1876 default: {
1877 assert(false);
1878 }
1879 }
1880
1881 // Send the dispatch signal.
1882 status = connection->inputPublisher.sendDispatchSignal();
1883 if (status) {
1884 LOGE("channel '%s' ~ Could not send dispatch signal, status=%d",
1885 connection->getInputChannelName(), status);
Jeff Brownb6997262010-10-08 22:31:17 -07001886 abortBrokenDispatchCycleLocked(currentTime, connection);
Jeff Brown46b9ac02010-04-22 18:58:52 -07001887 return;
1888 }
1889
1890 // Record information about the newly started dispatch cycle.
Jeff Brown01ce2e92010-09-26 22:20:12 -07001891 connection->lastEventTime = eventEntry->eventTime;
Jeff Brown46b9ac02010-04-22 18:58:52 -07001892 connection->lastDispatchTime = currentTime;
1893
Jeff Brown46b9ac02010-04-22 18:58:52 -07001894 // Notify other system components.
1895 onDispatchCycleStartedLocked(currentTime, connection);
1896}
1897
Jeff Brown7fbdc842010-06-17 20:52:56 -07001898void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Jeff Brown3915bb82010-11-05 15:02:16 -07001899 const sp<Connection>& connection, bool handled) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07001900#if DEBUG_DISPATCH_CYCLE
Jeff Brown9c3cda02010-06-15 01:31:58 -07001901 LOGD("channel '%s' ~ finishDispatchCycle - %01.1fms since event, "
Jeff Brown3915bb82010-11-05 15:02:16 -07001902 "%01.1fms since dispatch, handled=%s",
Jeff Brown46b9ac02010-04-22 18:58:52 -07001903 connection->getInputChannelName(),
1904 connection->getEventLatencyMillis(currentTime),
Jeff Brown3915bb82010-11-05 15:02:16 -07001905 connection->getDispatchLatencyMillis(currentTime),
1906 toString(handled));
Jeff Brown46b9ac02010-04-22 18:58:52 -07001907#endif
1908
Jeff Brown9c3cda02010-06-15 01:31:58 -07001909 if (connection->status == Connection::STATUS_BROKEN
1910 || connection->status == Connection::STATUS_ZOMBIE) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07001911 return;
1912 }
1913
Jeff Brown46b9ac02010-04-22 18:58:52 -07001914 // Reset the publisher since the event has been consumed.
1915 // We do this now so that the publisher can release some of its internal resources
1916 // while waiting for the next dispatch cycle to begin.
1917 status_t status = connection->inputPublisher.reset();
1918 if (status) {
1919 LOGE("channel '%s' ~ Could not reset publisher, status=%d",
1920 connection->getInputChannelName(), status);
Jeff Brownb6997262010-10-08 22:31:17 -07001921 abortBrokenDispatchCycleLocked(currentTime, connection);
Jeff Brown46b9ac02010-04-22 18:58:52 -07001922 return;
1923 }
1924
Jeff Brown3915bb82010-11-05 15:02:16 -07001925 // Notify other system components and prepare to start the next dispatch cycle.
1926 onDispatchCycleFinishedLocked(currentTime, connection, handled);
Jeff Brownb88102f2010-09-08 11:49:43 -07001927}
1928
1929void InputDispatcher::startNextDispatchCycleLocked(nsecs_t currentTime,
1930 const sp<Connection>& connection) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07001931 // Start the next dispatch cycle for this connection.
1932 while (! connection->outboundQueue.isEmpty()) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001933 DispatchEntry* dispatchEntry = connection->outboundQueue.headSentinel.next;
Jeff Brown46b9ac02010-04-22 18:58:52 -07001934 if (dispatchEntry->inProgress) {
1935 // Finish or resume current event in progress.
1936 if (dispatchEntry->tailMotionSample) {
1937 // We have a tail of undispatched motion samples.
1938 // Reuse the same DispatchEntry and start a new cycle.
1939 dispatchEntry->inProgress = false;
1940 dispatchEntry->headMotionSample = dispatchEntry->tailMotionSample;
1941 dispatchEntry->tailMotionSample = NULL;
Jeff Brown519e0242010-09-15 15:18:56 -07001942 startDispatchCycleLocked(currentTime, connection);
Jeff Brown46b9ac02010-04-22 18:58:52 -07001943 return;
1944 }
1945 // Finished.
1946 connection->outboundQueue.dequeueAtHead();
Jeff Brown519e0242010-09-15 15:18:56 -07001947 if (dispatchEntry->hasForegroundTarget()) {
1948 decrementPendingForegroundDispatchesLocked(dispatchEntry->eventEntry);
Jeff Brown6ec402b2010-07-28 15:48:59 -07001949 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07001950 mAllocator.releaseDispatchEntry(dispatchEntry);
1951 } else {
1952 // If the head is not in progress, then we must have already dequeued the in
Jeff Brown519e0242010-09-15 15:18:56 -07001953 // progress event, which means we actually aborted it.
Jeff Brown46b9ac02010-04-22 18:58:52 -07001954 // So just start the next event for this connection.
Jeff Brown519e0242010-09-15 15:18:56 -07001955 startDispatchCycleLocked(currentTime, connection);
Jeff Brown46b9ac02010-04-22 18:58:52 -07001956 return;
1957 }
1958 }
1959
1960 // Outbound queue is empty, deactivate the connection.
Jeff Brown7fbdc842010-06-17 20:52:56 -07001961 deactivateConnectionLocked(connection.get());
Jeff Brown46b9ac02010-04-22 18:58:52 -07001962}
1963
Jeff Brownb6997262010-10-08 22:31:17 -07001964void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
1965 const sp<Connection>& connection) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07001966#if DEBUG_DISPATCH_CYCLE
Jeff Brown83c09682010-12-23 17:50:18 -08001967 LOGD("channel '%s' ~ abortBrokenDispatchCycle",
1968 connection->getInputChannelName());
Jeff Brown46b9ac02010-04-22 18:58:52 -07001969#endif
1970
Jeff Brownb88102f2010-09-08 11:49:43 -07001971 // Clear the outbound queue.
Jeff Brown519e0242010-09-15 15:18:56 -07001972 drainOutboundQueueLocked(connection.get());
Jeff Brown46b9ac02010-04-22 18:58:52 -07001973
Jeff Brownb6997262010-10-08 22:31:17 -07001974 // The connection appears to be unrecoverably broken.
Jeff Brown9c3cda02010-06-15 01:31:58 -07001975 // Ignore already broken or zombie connections.
Jeff Brownb6997262010-10-08 22:31:17 -07001976 if (connection->status == Connection::STATUS_NORMAL) {
1977 connection->status = Connection::STATUS_BROKEN;
Jeff Brown46b9ac02010-04-22 18:58:52 -07001978
Jeff Brownb6997262010-10-08 22:31:17 -07001979 // Notify other system components.
1980 onDispatchCycleBrokenLocked(currentTime, connection);
Jeff Brown46b9ac02010-04-22 18:58:52 -07001981 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07001982}
1983
Jeff Brown519e0242010-09-15 15:18:56 -07001984void InputDispatcher::drainOutboundQueueLocked(Connection* connection) {
1985 while (! connection->outboundQueue.isEmpty()) {
1986 DispatchEntry* dispatchEntry = connection->outboundQueue.dequeueAtHead();
1987 if (dispatchEntry->hasForegroundTarget()) {
1988 decrementPendingForegroundDispatchesLocked(dispatchEntry->eventEntry);
Jeff Brownb88102f2010-09-08 11:49:43 -07001989 }
1990 mAllocator.releaseDispatchEntry(dispatchEntry);
Jeff Brownb88102f2010-09-08 11:49:43 -07001991 }
1992
Jeff Brown519e0242010-09-15 15:18:56 -07001993 deactivateConnectionLocked(connection);
Jeff Brownb88102f2010-09-08 11:49:43 -07001994}
1995
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07001996int InputDispatcher::handleReceiveCallback(int receiveFd, int events, void* data) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07001997 InputDispatcher* d = static_cast<InputDispatcher*>(data);
1998
1999 { // acquire lock
2000 AutoMutex _l(d->mLock);
2001
2002 ssize_t connectionIndex = d->mConnectionsByReceiveFd.indexOfKey(receiveFd);
2003 if (connectionIndex < 0) {
2004 LOGE("Received spurious receive callback for unknown input channel. "
2005 "fd=%d, events=0x%x", receiveFd, events);
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002006 return 0; // remove the callback
Jeff Brown46b9ac02010-04-22 18:58:52 -07002007 }
2008
Jeff Brown7fbdc842010-06-17 20:52:56 -07002009 nsecs_t currentTime = now();
Jeff Brown46b9ac02010-04-22 18:58:52 -07002010
2011 sp<Connection> connection = d->mConnectionsByReceiveFd.valueAt(connectionIndex);
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002012 if (events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP)) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002013 LOGE("channel '%s' ~ Consumer closed input channel or an error occurred. "
2014 "events=0x%x", connection->getInputChannelName(), events);
Jeff Brownb6997262010-10-08 22:31:17 -07002015 d->abortBrokenDispatchCycleLocked(currentTime, connection);
Jeff Brown9c3cda02010-06-15 01:31:58 -07002016 d->runCommandsLockedInterruptible();
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002017 return 0; // remove the callback
Jeff Brown46b9ac02010-04-22 18:58:52 -07002018 }
2019
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002020 if (! (events & ALOOPER_EVENT_INPUT)) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002021 LOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
2022 "events=0x%x", connection->getInputChannelName(), events);
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002023 return 1;
Jeff Brown46b9ac02010-04-22 18:58:52 -07002024 }
2025
Jeff Brown3915bb82010-11-05 15:02:16 -07002026 bool handled = false;
Jeff Brown49ed71d2010-12-06 17:13:33 -08002027 status_t status = connection->inputPublisher.receiveFinishedSignal(&handled);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002028 if (status) {
2029 LOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
2030 connection->getInputChannelName(), status);
Jeff Brownb6997262010-10-08 22:31:17 -07002031 d->abortBrokenDispatchCycleLocked(currentTime, connection);
Jeff Brown9c3cda02010-06-15 01:31:58 -07002032 d->runCommandsLockedInterruptible();
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002033 return 0; // remove the callback
Jeff Brown46b9ac02010-04-22 18:58:52 -07002034 }
2035
Jeff Brown3915bb82010-11-05 15:02:16 -07002036 d->finishDispatchCycleLocked(currentTime, connection, handled);
Jeff Brown9c3cda02010-06-15 01:31:58 -07002037 d->runCommandsLockedInterruptible();
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002038 return 1;
Jeff Brown46b9ac02010-04-22 18:58:52 -07002039 } // release lock
2040}
2041
Jeff Brownb6997262010-10-08 22:31:17 -07002042void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
2043 InputState::CancelationOptions options, const char* reason) {
2044 for (size_t i = 0; i < mConnectionsByReceiveFd.size(); i++) {
2045 synthesizeCancelationEventsForConnectionLocked(
2046 mConnectionsByReceiveFd.valueAt(i), options, reason);
2047 }
2048}
2049
2050void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
2051 const sp<InputChannel>& channel, InputState::CancelationOptions options,
2052 const char* reason) {
2053 ssize_t index = getConnectionIndexLocked(channel);
2054 if (index >= 0) {
2055 synthesizeCancelationEventsForConnectionLocked(
2056 mConnectionsByReceiveFd.valueAt(index), options, reason);
2057 }
2058}
2059
2060void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
2061 const sp<Connection>& connection, InputState::CancelationOptions options,
2062 const char* reason) {
2063 nsecs_t currentTime = now();
2064
2065 mTempCancelationEvents.clear();
2066 connection->inputState.synthesizeCancelationEvents(currentTime, & mAllocator,
2067 mTempCancelationEvents, options);
2068
2069 if (! mTempCancelationEvents.isEmpty()
2070 && connection->status != Connection::STATUS_BROKEN) {
2071#if DEBUG_OUTBOUND_EVENT_DETAILS
2072 LOGD("channel '%s' ~ Synthesized %d cancelation events to bring channel back in sync "
2073 "with reality: %s, options=%d.",
2074 connection->getInputChannelName(), mTempCancelationEvents.size(), reason, options);
2075#endif
2076 for (size_t i = 0; i < mTempCancelationEvents.size(); i++) {
2077 EventEntry* cancelationEventEntry = mTempCancelationEvents.itemAt(i);
2078 switch (cancelationEventEntry->type) {
2079 case EventEntry::TYPE_KEY:
2080 logOutboundKeyDetailsLocked("cancel - ",
2081 static_cast<KeyEntry*>(cancelationEventEntry));
2082 break;
2083 case EventEntry::TYPE_MOTION:
2084 logOutboundMotionDetailsLocked("cancel - ",
2085 static_cast<MotionEntry*>(cancelationEventEntry));
2086 break;
2087 }
2088
2089 int32_t xOffset, yOffset;
2090 const InputWindow* window = getWindowLocked(connection->inputChannel);
2091 if (window) {
2092 xOffset = -window->frameLeft;
2093 yOffset = -window->frameTop;
2094 } else {
2095 xOffset = 0;
2096 yOffset = 0;
2097 }
2098
2099 DispatchEntry* cancelationDispatchEntry =
2100 mAllocator.obtainDispatchEntry(cancelationEventEntry, // increments ref
2101 0, xOffset, yOffset);
2102 connection->outboundQueue.enqueueAtTail(cancelationDispatchEntry);
2103
2104 mAllocator.releaseEventEntry(cancelationEventEntry);
2105 }
2106
2107 if (!connection->outboundQueue.headSentinel.next->inProgress) {
2108 startDispatchCycleLocked(currentTime, connection);
2109 }
2110 }
2111}
2112
Jeff Brown01ce2e92010-09-26 22:20:12 -07002113InputDispatcher::MotionEntry*
2114InputDispatcher::splitMotionEvent(const MotionEntry* originalMotionEntry, BitSet32 pointerIds) {
2115 assert(pointerIds.value != 0);
2116
2117 uint32_t splitPointerIndexMap[MAX_POINTERS];
2118 int32_t splitPointerIds[MAX_POINTERS];
2119 PointerCoords splitPointerCoords[MAX_POINTERS];
2120
2121 uint32_t originalPointerCount = originalMotionEntry->pointerCount;
2122 uint32_t splitPointerCount = 0;
2123
2124 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
2125 originalPointerIndex++) {
2126 int32_t pointerId = uint32_t(originalMotionEntry->pointerIds[originalPointerIndex]);
2127 if (pointerIds.hasBit(pointerId)) {
2128 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
2129 splitPointerIds[splitPointerCount] = pointerId;
Jeff Brownace13b12011-03-09 17:39:48 -08002130 splitPointerCoords[splitPointerCount].copyFrom(
2131 originalMotionEntry->firstSample.pointerCoords[originalPointerIndex]);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002132 splitPointerCount += 1;
2133 }
2134 }
Jeff Brown58a2da82011-01-25 16:02:22 -08002135
2136 if (splitPointerCount != pointerIds.count()) {
2137 // This is bad. We are missing some of the pointers that we expected to deliver.
2138 // Most likely this indicates that we received an ACTION_MOVE events that has
2139 // different pointer ids than we expected based on the previous ACTION_DOWN
2140 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
2141 // in this way.
2142 LOGW("Dropping split motion event because the pointer count is %d but "
2143 "we expected there to be %d pointers. This probably means we received "
2144 "a broken sequence of pointer ids from the input device.",
2145 splitPointerCount, pointerIds.count());
2146 return NULL;
2147 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07002148
2149 int32_t action = originalMotionEntry->action;
2150 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
2151 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
2152 || maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2153 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
2154 int32_t pointerId = originalMotionEntry->pointerIds[originalPointerIndex];
2155 if (pointerIds.hasBit(pointerId)) {
2156 if (pointerIds.count() == 1) {
2157 // The first/last pointer went down/up.
2158 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
2159 ? AMOTION_EVENT_ACTION_DOWN : AMOTION_EVENT_ACTION_UP;
Jeff Brown9a01d052010-09-27 16:35:11 -07002160 } else {
2161 // A secondary pointer went down/up.
2162 uint32_t splitPointerIndex = 0;
2163 while (pointerId != splitPointerIds[splitPointerIndex]) {
2164 splitPointerIndex += 1;
2165 }
2166 action = maskedAction | (splitPointerIndex
2167 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002168 }
2169 } else {
2170 // An unrelated pointer changed.
2171 action = AMOTION_EVENT_ACTION_MOVE;
2172 }
2173 }
2174
2175 MotionEntry* splitMotionEntry = mAllocator.obtainMotionEntry(
2176 originalMotionEntry->eventTime,
2177 originalMotionEntry->deviceId,
2178 originalMotionEntry->source,
2179 originalMotionEntry->policyFlags,
2180 action,
2181 originalMotionEntry->flags,
2182 originalMotionEntry->metaState,
2183 originalMotionEntry->edgeFlags,
2184 originalMotionEntry->xPrecision,
2185 originalMotionEntry->yPrecision,
2186 originalMotionEntry->downTime,
2187 splitPointerCount, splitPointerIds, splitPointerCoords);
2188
2189 for (MotionSample* originalMotionSample = originalMotionEntry->firstSample.next;
2190 originalMotionSample != NULL; originalMotionSample = originalMotionSample->next) {
2191 for (uint32_t splitPointerIndex = 0; splitPointerIndex < splitPointerCount;
2192 splitPointerIndex++) {
2193 uint32_t originalPointerIndex = splitPointerIndexMap[splitPointerIndex];
Jeff Brownace13b12011-03-09 17:39:48 -08002194 splitPointerCoords[splitPointerIndex].copyFrom(
2195 originalMotionSample->pointerCoords[originalPointerIndex]);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002196 }
2197
2198 mAllocator.appendMotionSample(splitMotionEntry, originalMotionSample->eventTime,
2199 splitPointerCoords);
2200 }
2201
2202 return splitMotionEntry;
2203}
2204
Jeff Brown9c3cda02010-06-15 01:31:58 -07002205void InputDispatcher::notifyConfigurationChanged(nsecs_t eventTime) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002206#if DEBUG_INBOUND_EVENT_DETAILS
Jeff Brown9c3cda02010-06-15 01:31:58 -07002207 LOGD("notifyConfigurationChanged - eventTime=%lld", eventTime);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002208#endif
2209
Jeff Brownb88102f2010-09-08 11:49:43 -07002210 bool needWake;
Jeff Brown46b9ac02010-04-22 18:58:52 -07002211 { // acquire lock
2212 AutoMutex _l(mLock);
2213
Jeff Brown7fbdc842010-06-17 20:52:56 -07002214 ConfigurationChangedEntry* newEntry = mAllocator.obtainConfigurationChangedEntry(eventTime);
Jeff Brownb88102f2010-09-08 11:49:43 -07002215 needWake = enqueueInboundEventLocked(newEntry);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002216 } // release lock
2217
Jeff Brownb88102f2010-09-08 11:49:43 -07002218 if (needWake) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002219 mLooper->wake();
Jeff Brown46b9ac02010-04-22 18:58:52 -07002220 }
2221}
2222
Jeff Brown58a2da82011-01-25 16:02:22 -08002223void InputDispatcher::notifyKey(nsecs_t eventTime, int32_t deviceId, uint32_t source,
Jeff Brown46b9ac02010-04-22 18:58:52 -07002224 uint32_t policyFlags, int32_t action, int32_t flags,
2225 int32_t keyCode, int32_t scanCode, int32_t metaState, nsecs_t downTime) {
2226#if DEBUG_INBOUND_EVENT_DETAILS
Jeff Brown90655042010-12-02 13:50:46 -08002227 LOGD("notifyKey - eventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, action=0x%x, "
Jeff Brown46b9ac02010-04-22 18:58:52 -07002228 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%lld",
Jeff Brownc5ed5912010-07-14 18:48:53 -07002229 eventTime, deviceId, source, policyFlags, action, flags,
Jeff Brown46b9ac02010-04-22 18:58:52 -07002230 keyCode, scanCode, metaState, downTime);
2231#endif
Jeff Brown01ce2e92010-09-26 22:20:12 -07002232 if (! validateKeyEvent(action)) {
2233 return;
2234 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002235
Jeff Brown1f245102010-11-18 20:53:46 -08002236 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
2237 policyFlags |= POLICY_FLAG_VIRTUAL;
2238 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
2239 }
Jeff Brown924c4d42011-03-07 16:40:47 -08002240 if (policyFlags & POLICY_FLAG_ALT) {
2241 metaState |= AMETA_ALT_ON | AMETA_ALT_LEFT_ON;
2242 }
2243 if (policyFlags & POLICY_FLAG_ALT_GR) {
2244 metaState |= AMETA_ALT_ON | AMETA_ALT_RIGHT_ON;
2245 }
2246 if (policyFlags & POLICY_FLAG_SHIFT) {
2247 metaState |= AMETA_SHIFT_ON | AMETA_SHIFT_LEFT_ON;
2248 }
2249 if (policyFlags & POLICY_FLAG_CAPS_LOCK) {
2250 metaState |= AMETA_CAPS_LOCK_ON;
2251 }
2252 if (policyFlags & POLICY_FLAG_FUNCTION) {
2253 metaState |= AMETA_FUNCTION_ON;
2254 }
Jeff Brown1f245102010-11-18 20:53:46 -08002255
Jeff Browne20c9e02010-10-11 14:20:19 -07002256 policyFlags |= POLICY_FLAG_TRUSTED;
Jeff Brown1f245102010-11-18 20:53:46 -08002257
2258 KeyEvent event;
2259 event.initialize(deviceId, source, action, flags, keyCode, scanCode,
2260 metaState, 0, downTime, eventTime);
2261
2262 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
2263
2264 if (policyFlags & POLICY_FLAG_WOKE_HERE) {
2265 flags |= AKEY_EVENT_FLAG_WOKE_HERE;
2266 }
Jeff Brownb6997262010-10-08 22:31:17 -07002267
Jeff Brownb88102f2010-09-08 11:49:43 -07002268 bool needWake;
Jeff Brown46b9ac02010-04-22 18:58:52 -07002269 { // acquire lock
2270 AutoMutex _l(mLock);
2271
Jeff Brown7fbdc842010-06-17 20:52:56 -07002272 int32_t repeatCount = 0;
2273 KeyEntry* newEntry = mAllocator.obtainKeyEntry(eventTime,
Jeff Brownc5ed5912010-07-14 18:48:53 -07002274 deviceId, source, policyFlags, action, flags, keyCode, scanCode,
Jeff Brown7fbdc842010-06-17 20:52:56 -07002275 metaState, repeatCount, downTime);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002276
Jeff Brownb88102f2010-09-08 11:49:43 -07002277 needWake = enqueueInboundEventLocked(newEntry);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002278 } // release lock
2279
Jeff Brownb88102f2010-09-08 11:49:43 -07002280 if (needWake) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002281 mLooper->wake();
Jeff Brown46b9ac02010-04-22 18:58:52 -07002282 }
2283}
2284
Jeff Brown58a2da82011-01-25 16:02:22 -08002285void InputDispatcher::notifyMotion(nsecs_t eventTime, int32_t deviceId, uint32_t source,
Jeff Brown85a31762010-09-01 17:01:00 -07002286 uint32_t policyFlags, int32_t action, int32_t flags, int32_t metaState, int32_t edgeFlags,
Jeff Brown46b9ac02010-04-22 18:58:52 -07002287 uint32_t pointerCount, const int32_t* pointerIds, const PointerCoords* pointerCoords,
2288 float xPrecision, float yPrecision, nsecs_t downTime) {
2289#if DEBUG_INBOUND_EVENT_DETAILS
Jeff Brown90655042010-12-02 13:50:46 -08002290 LOGD("notifyMotion - eventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, "
Jeff Brown85a31762010-09-01 17:01:00 -07002291 "action=0x%x, flags=0x%x, metaState=0x%x, edgeFlags=0x%x, "
2292 "xPrecision=%f, yPrecision=%f, downTime=%lld",
2293 eventTime, deviceId, source, policyFlags, action, flags, metaState, edgeFlags,
Jeff Brown46b9ac02010-04-22 18:58:52 -07002294 xPrecision, yPrecision, downTime);
2295 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brown8d608662010-08-30 03:02:23 -07002296 LOGD(" Pointer %d: id=%d, x=%f, y=%f, pressure=%f, size=%f, "
Jeff Brown85a31762010-09-01 17:01:00 -07002297 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
Jeff Brown8d608662010-08-30 03:02:23 -07002298 "orientation=%f",
Jeff Brown91c69ab2011-02-14 17:03:18 -08002299 i, pointerIds[i],
Jeff Brownebbd5d12011-02-17 13:01:34 -08002300 pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
2301 pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
2302 pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
2303 pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
2304 pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
2305 pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
2306 pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
2307 pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
2308 pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Jeff Brown46b9ac02010-04-22 18:58:52 -07002309 }
2310#endif
Jeff Brown01ce2e92010-09-26 22:20:12 -07002311 if (! validateMotionEvent(action, pointerCount, pointerIds)) {
2312 return;
2313 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002314
Jeff Browne20c9e02010-10-11 14:20:19 -07002315 policyFlags |= POLICY_FLAG_TRUSTED;
Jeff Brown56194eb2011-03-02 19:23:13 -08002316 mPolicy->interceptMotionBeforeQueueing(eventTime, /*byref*/ policyFlags);
Jeff Brownb6997262010-10-08 22:31:17 -07002317
Jeff Brownb88102f2010-09-08 11:49:43 -07002318 bool needWake;
Jeff Brown46b9ac02010-04-22 18:58:52 -07002319 { // acquire lock
2320 AutoMutex _l(mLock);
2321
2322 // Attempt batching and streaming of move events.
Jeff Browncc0c1592011-02-19 05:07:28 -08002323 if (action == AMOTION_EVENT_ACTION_MOVE
2324 || action == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002325 // BATCHING CASE
2326 //
2327 // Try to append a move sample to the tail of the inbound queue for this device.
2328 // Give up if we encounter a non-move motion event for this device since that
2329 // means we cannot append any new samples until a new motion event has started.
Jeff Brownb88102f2010-09-08 11:49:43 -07002330 for (EventEntry* entry = mInboundQueue.tailSentinel.prev;
2331 entry != & mInboundQueue.headSentinel; entry = entry->prev) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002332 if (entry->type != EventEntry::TYPE_MOTION) {
2333 // Keep looking for motion events.
2334 continue;
2335 }
2336
2337 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
Jeff Brownefd32662011-03-08 15:13:06 -08002338 if (motionEntry->deviceId != deviceId
2339 || motionEntry->source != source) {
2340 // Keep looking for this device and source.
Jeff Brown46b9ac02010-04-22 18:58:52 -07002341 continue;
2342 }
2343
Jeff Browncc0c1592011-02-19 05:07:28 -08002344 if (motionEntry->action != action
Jeff Brown7fbdc842010-06-17 20:52:56 -07002345 || motionEntry->pointerCount != pointerCount
2346 || motionEntry->isInjected()) {
Jeff Brownefd32662011-03-08 15:13:06 -08002347 // Last motion event in the queue for this device and source is
2348 // not compatible for appending new samples. Stop here.
Jeff Brown46b9ac02010-04-22 18:58:52 -07002349 goto NoBatchingOrStreaming;
2350 }
2351
2352 // The last motion event is a move and is compatible for appending.
Jeff Brown9c3cda02010-06-15 01:31:58 -07002353 // Do the batching magic.
Jeff Brown7fbdc842010-06-17 20:52:56 -07002354 mAllocator.appendMotionSample(motionEntry, eventTime, pointerCoords);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002355#if DEBUG_BATCHING
2356 LOGD("Appended motion sample onto batch for most recent "
2357 "motion event for this device in the inbound queue.");
2358#endif
Jeff Brown9c3cda02010-06-15 01:31:58 -07002359 return; // done!
Jeff Brown46b9ac02010-04-22 18:58:52 -07002360 }
2361
2362 // STREAMING CASE
2363 //
2364 // There is no pending motion event (of any kind) for this device in the inbound queue.
Jeff Brown519e0242010-09-15 15:18:56 -07002365 // Search the outbound queue for the current foreground targets to find a dispatched
2366 // motion event that is still in progress. If found, then, appen the new sample to
2367 // that event and push it out to all current targets. The logic in
2368 // prepareDispatchCycleLocked takes care of the case where some targets may
2369 // already have consumed the motion event by starting a new dispatch cycle if needed.
Jeff Brown9c3cda02010-06-15 01:31:58 -07002370 if (mCurrentInputTargetsValid) {
Jeff Brown519e0242010-09-15 15:18:56 -07002371 for (size_t i = 0; i < mCurrentInputTargets.size(); i++) {
2372 const InputTarget& inputTarget = mCurrentInputTargets[i];
2373 if ((inputTarget.flags & InputTarget::FLAG_FOREGROUND) == 0) {
2374 // Skip non-foreground targets. We only want to stream if there is at
2375 // least one foreground target whose dispatch is still in progress.
2376 continue;
Jeff Brown46b9ac02010-04-22 18:58:52 -07002377 }
Jeff Brown519e0242010-09-15 15:18:56 -07002378
2379 ssize_t connectionIndex = getConnectionIndexLocked(inputTarget.inputChannel);
2380 if (connectionIndex < 0) {
2381 // Connection must no longer be valid.
2382 continue;
2383 }
2384
2385 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
2386 if (connection->outboundQueue.isEmpty()) {
2387 // This foreground target has an empty outbound queue.
2388 continue;
2389 }
2390
2391 DispatchEntry* dispatchEntry = connection->outboundQueue.headSentinel.next;
2392 if (! dispatchEntry->inProgress
Jeff Brown01ce2e92010-09-26 22:20:12 -07002393 || dispatchEntry->eventEntry->type != EventEntry::TYPE_MOTION
2394 || dispatchEntry->isSplit()) {
2395 // No motion event is being dispatched, or it is being split across
2396 // windows in which case we cannot stream.
Jeff Brown519e0242010-09-15 15:18:56 -07002397 continue;
2398 }
2399
2400 MotionEntry* motionEntry = static_cast<MotionEntry*>(
2401 dispatchEntry->eventEntry);
Jeff Browncc0c1592011-02-19 05:07:28 -08002402 if (motionEntry->action != action
Jeff Brown519e0242010-09-15 15:18:56 -07002403 || motionEntry->deviceId != deviceId
Jeff Brown58a2da82011-01-25 16:02:22 -08002404 || motionEntry->source != source
Jeff Brown519e0242010-09-15 15:18:56 -07002405 || motionEntry->pointerCount != pointerCount
2406 || motionEntry->isInjected()) {
2407 // The motion event is not compatible with this move.
2408 continue;
2409 }
2410
2411 // Hurray! This foreground target is currently dispatching a move event
2412 // that we can stream onto. Append the motion sample and resume dispatch.
2413 mAllocator.appendMotionSample(motionEntry, eventTime, pointerCoords);
2414#if DEBUG_BATCHING
2415 LOGD("Appended motion sample onto batch for most recently dispatched "
2416 "motion event for this device in the outbound queues. "
2417 "Attempting to stream the motion sample.");
2418#endif
2419 nsecs_t currentTime = now();
2420 dispatchEventToCurrentInputTargetsLocked(currentTime, motionEntry,
2421 true /*resumeWithAppendedMotionSample*/);
2422
2423 runCommandsLockedInterruptible();
2424 return; // done!
Jeff Brown46b9ac02010-04-22 18:58:52 -07002425 }
2426 }
2427
2428NoBatchingOrStreaming:;
2429 }
2430
2431 // Just enqueue a new motion event.
Jeff Brown7fbdc842010-06-17 20:52:56 -07002432 MotionEntry* newEntry = mAllocator.obtainMotionEntry(eventTime,
Jeff Brown85a31762010-09-01 17:01:00 -07002433 deviceId, source, policyFlags, action, flags, metaState, edgeFlags,
Jeff Brown7fbdc842010-06-17 20:52:56 -07002434 xPrecision, yPrecision, downTime,
2435 pointerCount, pointerIds, pointerCoords);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002436
Jeff Brownb88102f2010-09-08 11:49:43 -07002437 needWake = enqueueInboundEventLocked(newEntry);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002438 } // release lock
2439
Jeff Brownb88102f2010-09-08 11:49:43 -07002440 if (needWake) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002441 mLooper->wake();
Jeff Brown46b9ac02010-04-22 18:58:52 -07002442 }
2443}
2444
Jeff Brownb6997262010-10-08 22:31:17 -07002445void InputDispatcher::notifySwitch(nsecs_t when, int32_t switchCode, int32_t switchValue,
2446 uint32_t policyFlags) {
2447#if DEBUG_INBOUND_EVENT_DETAILS
2448 LOGD("notifySwitch - switchCode=%d, switchValue=%d, policyFlags=0x%x",
2449 switchCode, switchValue, policyFlags);
2450#endif
2451
Jeff Browne20c9e02010-10-11 14:20:19 -07002452 policyFlags |= POLICY_FLAG_TRUSTED;
Jeff Brownb6997262010-10-08 22:31:17 -07002453 mPolicy->notifySwitch(when, switchCode, switchValue, policyFlags);
2454}
2455
Jeff Brown7fbdc842010-06-17 20:52:56 -07002456int32_t InputDispatcher::injectInputEvent(const InputEvent* event,
Jeff Brown6ec402b2010-07-28 15:48:59 -07002457 int32_t injectorPid, int32_t injectorUid, int32_t syncMode, int32_t timeoutMillis) {
Jeff Brown7fbdc842010-06-17 20:52:56 -07002458#if DEBUG_INBOUND_EVENT_DETAILS
2459 LOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Jeff Brown6ec402b2010-07-28 15:48:59 -07002460 "syncMode=%d, timeoutMillis=%d",
2461 event->getType(), injectorPid, injectorUid, syncMode, timeoutMillis);
Jeff Brown7fbdc842010-06-17 20:52:56 -07002462#endif
2463
2464 nsecs_t endTime = now() + milliseconds_to_nanoseconds(timeoutMillis);
Jeff Browne20c9e02010-10-11 14:20:19 -07002465
2466 uint32_t policyFlags = POLICY_FLAG_INJECTED;
2467 if (hasInjectionPermission(injectorPid, injectorUid)) {
2468 policyFlags |= POLICY_FLAG_TRUSTED;
2469 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07002470
Jeff Brownb6997262010-10-08 22:31:17 -07002471 EventEntry* injectedEntry;
2472 switch (event->getType()) {
2473 case AINPUT_EVENT_TYPE_KEY: {
2474 const KeyEvent* keyEvent = static_cast<const KeyEvent*>(event);
2475 int32_t action = keyEvent->getAction();
2476 if (! validateKeyEvent(action)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07002477 return INPUT_EVENT_INJECTION_FAILED;
2478 }
2479
Jeff Brownb6997262010-10-08 22:31:17 -07002480 int32_t flags = keyEvent->getFlags();
Jeff Brown1f245102010-11-18 20:53:46 -08002481 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
2482 policyFlags |= POLICY_FLAG_VIRTUAL;
2483 }
2484
2485 mPolicy->interceptKeyBeforeQueueing(keyEvent, /*byref*/ policyFlags);
2486
2487 if (policyFlags & POLICY_FLAG_WOKE_HERE) {
2488 flags |= AKEY_EVENT_FLAG_WOKE_HERE;
2489 }
Jeff Brown6ec402b2010-07-28 15:48:59 -07002490
Jeff Brownb6997262010-10-08 22:31:17 -07002491 mLock.lock();
Jeff Brown1f245102010-11-18 20:53:46 -08002492 injectedEntry = mAllocator.obtainKeyEntry(keyEvent->getEventTime(),
2493 keyEvent->getDeviceId(), keyEvent->getSource(),
2494 policyFlags, action, flags,
2495 keyEvent->getKeyCode(), keyEvent->getScanCode(), keyEvent->getMetaState(),
Jeff Brownb6997262010-10-08 22:31:17 -07002496 keyEvent->getRepeatCount(), keyEvent->getDownTime());
2497 break;
2498 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07002499
Jeff Brownb6997262010-10-08 22:31:17 -07002500 case AINPUT_EVENT_TYPE_MOTION: {
2501 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
2502 int32_t action = motionEvent->getAction();
2503 size_t pointerCount = motionEvent->getPointerCount();
2504 const int32_t* pointerIds = motionEvent->getPointerIds();
2505 if (! validateMotionEvent(action, pointerCount, pointerIds)) {
2506 return INPUT_EVENT_INJECTION_FAILED;
2507 }
2508
2509 nsecs_t eventTime = motionEvent->getEventTime();
Jeff Brown56194eb2011-03-02 19:23:13 -08002510 mPolicy->interceptMotionBeforeQueueing(eventTime, /*byref*/ policyFlags);
Jeff Brownb6997262010-10-08 22:31:17 -07002511
2512 mLock.lock();
2513 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
2514 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
2515 MotionEntry* motionEntry = mAllocator.obtainMotionEntry(*sampleEventTimes,
2516 motionEvent->getDeviceId(), motionEvent->getSource(), policyFlags,
2517 action, motionEvent->getFlags(),
2518 motionEvent->getMetaState(), motionEvent->getEdgeFlags(),
2519 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
2520 motionEvent->getDownTime(), uint32_t(pointerCount),
2521 pointerIds, samplePointerCoords);
2522 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
2523 sampleEventTimes += 1;
2524 samplePointerCoords += pointerCount;
2525 mAllocator.appendMotionSample(motionEntry, *sampleEventTimes, samplePointerCoords);
2526 }
2527 injectedEntry = motionEntry;
2528 break;
2529 }
2530
2531 default:
2532 LOGW("Cannot inject event of type %d", event->getType());
2533 return INPUT_EVENT_INJECTION_FAILED;
2534 }
2535
2536 InjectionState* injectionState = mAllocator.obtainInjectionState(injectorPid, injectorUid);
2537 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
2538 injectionState->injectionIsAsync = true;
2539 }
2540
2541 injectionState->refCount += 1;
2542 injectedEntry->injectionState = injectionState;
2543
2544 bool needWake = enqueueInboundEventLocked(injectedEntry);
2545 mLock.unlock();
Jeff Brown7fbdc842010-06-17 20:52:56 -07002546
Jeff Brownb88102f2010-09-08 11:49:43 -07002547 if (needWake) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002548 mLooper->wake();
Jeff Brown7fbdc842010-06-17 20:52:56 -07002549 }
2550
2551 int32_t injectionResult;
2552 { // acquire lock
2553 AutoMutex _l(mLock);
2554
Jeff Brown6ec402b2010-07-28 15:48:59 -07002555 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
2556 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
2557 } else {
2558 for (;;) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002559 injectionResult = injectionState->injectionResult;
Jeff Brown6ec402b2010-07-28 15:48:59 -07002560 if (injectionResult != INPUT_EVENT_INJECTION_PENDING) {
2561 break;
2562 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07002563
Jeff Brown7fbdc842010-06-17 20:52:56 -07002564 nsecs_t remainingTimeout = endTime - now();
2565 if (remainingTimeout <= 0) {
Jeff Brown6ec402b2010-07-28 15:48:59 -07002566#if DEBUG_INJECTION
2567 LOGD("injectInputEvent - Timed out waiting for injection result "
2568 "to become available.");
2569#endif
Jeff Brown7fbdc842010-06-17 20:52:56 -07002570 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
2571 break;
2572 }
2573
Jeff Brown6ec402b2010-07-28 15:48:59 -07002574 mInjectionResultAvailableCondition.waitRelative(mLock, remainingTimeout);
2575 }
2576
2577 if (injectionResult == INPUT_EVENT_INJECTION_SUCCEEDED
2578 && syncMode == INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002579 while (injectionState->pendingForegroundDispatches != 0) {
Jeff Brown6ec402b2010-07-28 15:48:59 -07002580#if DEBUG_INJECTION
Jeff Brown519e0242010-09-15 15:18:56 -07002581 LOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
Jeff Brown01ce2e92010-09-26 22:20:12 -07002582 injectionState->pendingForegroundDispatches);
Jeff Brown6ec402b2010-07-28 15:48:59 -07002583#endif
2584 nsecs_t remainingTimeout = endTime - now();
2585 if (remainingTimeout <= 0) {
2586#if DEBUG_INJECTION
Jeff Brown519e0242010-09-15 15:18:56 -07002587 LOGD("injectInputEvent - Timed out waiting for pending foreground "
Jeff Brown6ec402b2010-07-28 15:48:59 -07002588 "dispatches to finish.");
2589#endif
2590 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
2591 break;
2592 }
2593
2594 mInjectionSyncFinishedCondition.waitRelative(mLock, remainingTimeout);
2595 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07002596 }
2597 }
2598
Jeff Brown01ce2e92010-09-26 22:20:12 -07002599 mAllocator.releaseInjectionState(injectionState);
Jeff Brown7fbdc842010-06-17 20:52:56 -07002600 } // release lock
2601
Jeff Brown6ec402b2010-07-28 15:48:59 -07002602#if DEBUG_INJECTION
2603 LOGD("injectInputEvent - Finished with result %d. "
2604 "injectorPid=%d, injectorUid=%d",
2605 injectionResult, injectorPid, injectorUid);
2606#endif
2607
Jeff Brown7fbdc842010-06-17 20:52:56 -07002608 return injectionResult;
2609}
2610
Jeff Brownb6997262010-10-08 22:31:17 -07002611bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
2612 return injectorUid == 0
2613 || mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
2614}
2615
Jeff Brown7fbdc842010-06-17 20:52:56 -07002616void InputDispatcher::setInjectionResultLocked(EventEntry* entry, int32_t injectionResult) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002617 InjectionState* injectionState = entry->injectionState;
2618 if (injectionState) {
Jeff Brown7fbdc842010-06-17 20:52:56 -07002619#if DEBUG_INJECTION
2620 LOGD("Setting input event injection result to %d. "
2621 "injectorPid=%d, injectorUid=%d",
Jeff Brown01ce2e92010-09-26 22:20:12 -07002622 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
Jeff Brown7fbdc842010-06-17 20:52:56 -07002623#endif
2624
Jeff Brown01ce2e92010-09-26 22:20:12 -07002625 if (injectionState->injectionIsAsync) {
Jeff Brown6ec402b2010-07-28 15:48:59 -07002626 // Log the outcome since the injector did not wait for the injection result.
2627 switch (injectionResult) {
2628 case INPUT_EVENT_INJECTION_SUCCEEDED:
2629 LOGV("Asynchronous input event injection succeeded.");
2630 break;
2631 case INPUT_EVENT_INJECTION_FAILED:
2632 LOGW("Asynchronous input event injection failed.");
2633 break;
2634 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
2635 LOGW("Asynchronous input event injection permission denied.");
2636 break;
2637 case INPUT_EVENT_INJECTION_TIMED_OUT:
2638 LOGW("Asynchronous input event injection timed out.");
2639 break;
2640 }
2641 }
2642
Jeff Brown01ce2e92010-09-26 22:20:12 -07002643 injectionState->injectionResult = injectionResult;
Jeff Brown7fbdc842010-06-17 20:52:56 -07002644 mInjectionResultAvailableCondition.broadcast();
2645 }
2646}
2647
Jeff Brown01ce2e92010-09-26 22:20:12 -07002648void InputDispatcher::incrementPendingForegroundDispatchesLocked(EventEntry* entry) {
2649 InjectionState* injectionState = entry->injectionState;
2650 if (injectionState) {
2651 injectionState->pendingForegroundDispatches += 1;
2652 }
2653}
2654
Jeff Brown519e0242010-09-15 15:18:56 -07002655void InputDispatcher::decrementPendingForegroundDispatchesLocked(EventEntry* entry) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002656 InjectionState* injectionState = entry->injectionState;
2657 if (injectionState) {
2658 injectionState->pendingForegroundDispatches -= 1;
Jeff Brown6ec402b2010-07-28 15:48:59 -07002659
Jeff Brown01ce2e92010-09-26 22:20:12 -07002660 if (injectionState->pendingForegroundDispatches == 0) {
2661 mInjectionSyncFinishedCondition.broadcast();
2662 }
Jeff Brownb88102f2010-09-08 11:49:43 -07002663 }
2664}
2665
Jeff Brown01ce2e92010-09-26 22:20:12 -07002666const InputWindow* InputDispatcher::getWindowLocked(const sp<InputChannel>& inputChannel) {
2667 for (size_t i = 0; i < mWindows.size(); i++) {
2668 const InputWindow* window = & mWindows[i];
2669 if (window->inputChannel == inputChannel) {
2670 return window;
2671 }
2672 }
2673 return NULL;
2674}
2675
Jeff Brownb88102f2010-09-08 11:49:43 -07002676void InputDispatcher::setInputWindows(const Vector<InputWindow>& inputWindows) {
2677#if DEBUG_FOCUS
2678 LOGD("setInputWindows");
2679#endif
2680 { // acquire lock
2681 AutoMutex _l(mLock);
2682
Jeff Brown01ce2e92010-09-26 22:20:12 -07002683 // Clear old window pointers.
Jeff Brownb6997262010-10-08 22:31:17 -07002684 sp<InputChannel> oldFocusedWindowChannel;
2685 if (mFocusedWindow) {
2686 oldFocusedWindowChannel = mFocusedWindow->inputChannel;
2687 mFocusedWindow = NULL;
2688 }
2689
Jeff Brownb88102f2010-09-08 11:49:43 -07002690 mWindows.clear();
Jeff Brown2a95c2a2010-09-16 12:31:46 -07002691
2692 // Loop over new windows and rebuild the necessary window pointers for
2693 // tracking focus and touch.
Jeff Brownb88102f2010-09-08 11:49:43 -07002694 mWindows.appendVector(inputWindows);
2695
2696 size_t numWindows = mWindows.size();
2697 for (size_t i = 0; i < numWindows; i++) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002698 const InputWindow* window = & mWindows.itemAt(i);
Jeff Brownb88102f2010-09-08 11:49:43 -07002699 if (window->hasFocus) {
2700 mFocusedWindow = window;
Jeff Brown01ce2e92010-09-26 22:20:12 -07002701 break;
Jeff Brownb88102f2010-09-08 11:49:43 -07002702 }
2703 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07002704
Jeff Brownb6997262010-10-08 22:31:17 -07002705 if (oldFocusedWindowChannel != NULL) {
2706 if (!mFocusedWindow || oldFocusedWindowChannel != mFocusedWindow->inputChannel) {
2707#if DEBUG_FOCUS
2708 LOGD("Focus left window: %s",
2709 oldFocusedWindowChannel->getName().string());
2710#endif
2711 synthesizeCancelationEventsForInputChannelLocked(oldFocusedWindowChannel,
2712 InputState::CANCEL_NON_POINTER_EVENTS, "focus left window");
2713 oldFocusedWindowChannel.clear();
2714 }
2715 }
2716 if (mFocusedWindow && oldFocusedWindowChannel == NULL) {
2717#if DEBUG_FOCUS
2718 LOGD("Focus entered window: %s",
2719 mFocusedWindow->inputChannel->getName().string());
2720#endif
2721 }
2722
Jeff Brown01ce2e92010-09-26 22:20:12 -07002723 for (size_t i = 0; i < mTouchState.windows.size(); ) {
2724 TouchedWindow& touchedWindow = mTouchState.windows.editItemAt(i);
2725 const InputWindow* window = getWindowLocked(touchedWindow.channel);
2726 if (window) {
2727 touchedWindow.window = window;
2728 i += 1;
2729 } else {
Jeff Brownb6997262010-10-08 22:31:17 -07002730#if DEBUG_FOCUS
2731 LOGD("Touched window was removed: %s", touchedWindow.channel->getName().string());
2732#endif
Jeff Brownb6997262010-10-08 22:31:17 -07002733 synthesizeCancelationEventsForInputChannelLocked(touchedWindow.channel,
2734 InputState::CANCEL_POINTER_EVENTS, "touched window was removed");
Jeff Brownaf48cae2010-10-15 16:20:51 -07002735 mTouchState.windows.removeAt(i);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002736 }
2737 }
Jeff Brownb88102f2010-09-08 11:49:43 -07002738
Jeff Brownb88102f2010-09-08 11:49:43 -07002739#if DEBUG_FOCUS
Jeff Brownb6997262010-10-08 22:31:17 -07002740 //logDispatchStateLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -07002741#endif
2742 } // release lock
2743
2744 // Wake up poll loop since it may need to make new input dispatching choices.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002745 mLooper->wake();
Jeff Brownb88102f2010-09-08 11:49:43 -07002746}
2747
2748void InputDispatcher::setFocusedApplication(const InputApplication* inputApplication) {
2749#if DEBUG_FOCUS
2750 LOGD("setFocusedApplication");
2751#endif
2752 { // acquire lock
2753 AutoMutex _l(mLock);
2754
2755 releaseFocusedApplicationLocked();
2756
2757 if (inputApplication) {
2758 mFocusedApplicationStorage = *inputApplication;
2759 mFocusedApplication = & mFocusedApplicationStorage;
2760 }
2761
2762#if DEBUG_FOCUS
Jeff Brownb6997262010-10-08 22:31:17 -07002763 //logDispatchStateLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -07002764#endif
2765 } // release lock
2766
2767 // Wake up poll loop since it may need to make new input dispatching choices.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002768 mLooper->wake();
Jeff Brownb88102f2010-09-08 11:49:43 -07002769}
2770
2771void InputDispatcher::releaseFocusedApplicationLocked() {
2772 if (mFocusedApplication) {
2773 mFocusedApplication = NULL;
Jeff Brown928e0542011-01-10 11:17:36 -08002774 mFocusedApplicationStorage.inputApplicationHandle.clear();
Jeff Brownb88102f2010-09-08 11:49:43 -07002775 }
2776}
2777
2778void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
2779#if DEBUG_FOCUS
2780 LOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
2781#endif
2782
2783 bool changed;
2784 { // acquire lock
2785 AutoMutex _l(mLock);
2786
2787 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
Jeff Brown120a4592010-10-27 18:43:51 -07002788 if (mDispatchFrozen && !frozen) {
Jeff Brownb88102f2010-09-08 11:49:43 -07002789 resetANRTimeoutsLocked();
2790 }
2791
Jeff Brown120a4592010-10-27 18:43:51 -07002792 if (mDispatchEnabled && !enabled) {
2793 resetAndDropEverythingLocked("dispatcher is being disabled");
2794 }
2795
Jeff Brownb88102f2010-09-08 11:49:43 -07002796 mDispatchEnabled = enabled;
2797 mDispatchFrozen = frozen;
2798 changed = true;
2799 } else {
2800 changed = false;
2801 }
2802
2803#if DEBUG_FOCUS
Jeff Brownb6997262010-10-08 22:31:17 -07002804 //logDispatchStateLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -07002805#endif
2806 } // release lock
2807
2808 if (changed) {
2809 // Wake up poll loop since it may need to make new input dispatching choices.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002810 mLooper->wake();
Jeff Brown46b9ac02010-04-22 18:58:52 -07002811 }
2812}
2813
Jeff Browne6504122010-09-27 14:52:15 -07002814bool InputDispatcher::transferTouchFocus(const sp<InputChannel>& fromChannel,
2815 const sp<InputChannel>& toChannel) {
2816#if DEBUG_FOCUS
2817 LOGD("transferTouchFocus: fromChannel=%s, toChannel=%s",
2818 fromChannel->getName().string(), toChannel->getName().string());
2819#endif
2820 { // acquire lock
2821 AutoMutex _l(mLock);
2822
2823 const InputWindow* fromWindow = getWindowLocked(fromChannel);
2824 const InputWindow* toWindow = getWindowLocked(toChannel);
2825 if (! fromWindow || ! toWindow) {
2826#if DEBUG_FOCUS
2827 LOGD("Cannot transfer focus because from or to window not found.");
2828#endif
2829 return false;
2830 }
2831 if (fromWindow == toWindow) {
2832#if DEBUG_FOCUS
2833 LOGD("Trivial transfer to same window.");
2834#endif
2835 return true;
2836 }
2837
2838 bool found = false;
2839 for (size_t i = 0; i < mTouchState.windows.size(); i++) {
2840 const TouchedWindow& touchedWindow = mTouchState.windows[i];
2841 if (touchedWindow.window == fromWindow) {
2842 int32_t oldTargetFlags = touchedWindow.targetFlags;
2843 BitSet32 pointerIds = touchedWindow.pointerIds;
2844
2845 mTouchState.windows.removeAt(i);
2846
Jeff Brown46e75292010-11-10 16:53:45 -08002847 int32_t newTargetFlags = oldTargetFlags
2848 & (InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_SPLIT);
Jeff Browne6504122010-09-27 14:52:15 -07002849 mTouchState.addOrUpdateWindow(toWindow, newTargetFlags, pointerIds);
2850
2851 found = true;
2852 break;
2853 }
2854 }
2855
2856 if (! found) {
2857#if DEBUG_FOCUS
2858 LOGD("Focus transfer failed because from window did not have focus.");
2859#endif
2860 return false;
2861 }
2862
Jeff Brown9c9f1a32010-10-11 18:32:20 -07002863 ssize_t fromConnectionIndex = getConnectionIndexLocked(fromChannel);
2864 ssize_t toConnectionIndex = getConnectionIndexLocked(toChannel);
2865 if (fromConnectionIndex >= 0 && toConnectionIndex >= 0) {
2866 sp<Connection> fromConnection = mConnectionsByReceiveFd.valueAt(fromConnectionIndex);
2867 sp<Connection> toConnection = mConnectionsByReceiveFd.valueAt(toConnectionIndex);
2868
2869 fromConnection->inputState.copyPointerStateTo(toConnection->inputState);
2870 synthesizeCancelationEventsForConnectionLocked(fromConnection,
2871 InputState::CANCEL_POINTER_EVENTS,
2872 "transferring touch focus from this window to another window");
2873 }
2874
Jeff Browne6504122010-09-27 14:52:15 -07002875#if DEBUG_FOCUS
2876 logDispatchStateLocked();
2877#endif
2878 } // release lock
2879
2880 // Wake up poll loop since it may need to make new input dispatching choices.
2881 mLooper->wake();
2882 return true;
2883}
2884
Jeff Brown120a4592010-10-27 18:43:51 -07002885void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
2886#if DEBUG_FOCUS
2887 LOGD("Resetting and dropping all events (%s).", reason);
2888#endif
2889
2890 synthesizeCancelationEventsForAllConnectionsLocked(InputState::CANCEL_ALL_EVENTS, reason);
2891
2892 resetKeyRepeatLocked();
2893 releasePendingEventLocked();
2894 drainInboundQueueLocked();
2895 resetTargetsLocked();
2896
2897 mTouchState.reset();
2898}
2899
Jeff Brownb88102f2010-09-08 11:49:43 -07002900void InputDispatcher::logDispatchStateLocked() {
2901 String8 dump;
2902 dumpDispatchStateLocked(dump);
Jeff Brown2a95c2a2010-09-16 12:31:46 -07002903
2904 char* text = dump.lockBuffer(dump.size());
2905 char* start = text;
2906 while (*start != '\0') {
2907 char* end = strchr(start, '\n');
2908 if (*end == '\n') {
2909 *(end++) = '\0';
2910 }
2911 LOGD("%s", start);
2912 start = end;
2913 }
Jeff Brownb88102f2010-09-08 11:49:43 -07002914}
2915
2916void InputDispatcher::dumpDispatchStateLocked(String8& dump) {
Jeff Brownf2f48712010-10-01 17:46:21 -07002917 dump.appendFormat(INDENT "DispatchEnabled: %d\n", mDispatchEnabled);
2918 dump.appendFormat(INDENT "DispatchFrozen: %d\n", mDispatchFrozen);
Jeff Brownb88102f2010-09-08 11:49:43 -07002919
2920 if (mFocusedApplication) {
Jeff Brownf2f48712010-10-01 17:46:21 -07002921 dump.appendFormat(INDENT "FocusedApplication: name='%s', dispatchingTimeout=%0.3fms\n",
Jeff Brownb88102f2010-09-08 11:49:43 -07002922 mFocusedApplication->name.string(),
2923 mFocusedApplication->dispatchingTimeout / 1000000.0);
2924 } else {
Jeff Brownf2f48712010-10-01 17:46:21 -07002925 dump.append(INDENT "FocusedApplication: <null>\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07002926 }
Jeff Brownf2f48712010-10-01 17:46:21 -07002927 dump.appendFormat(INDENT "FocusedWindow: name='%s'\n",
Jeff Brown2a95c2a2010-09-16 12:31:46 -07002928 mFocusedWindow != NULL ? mFocusedWindow->name.string() : "<null>");
Jeff Brownf2f48712010-10-01 17:46:21 -07002929
2930 dump.appendFormat(INDENT "TouchDown: %s\n", toString(mTouchState.down));
2931 dump.appendFormat(INDENT "TouchSplit: %s\n", toString(mTouchState.split));
Jeff Brown95712852011-01-04 19:41:59 -08002932 dump.appendFormat(INDENT "TouchDeviceId: %d\n", mTouchState.deviceId);
Jeff Brown58a2da82011-01-25 16:02:22 -08002933 dump.appendFormat(INDENT "TouchSource: 0x%08x\n", mTouchState.source);
Jeff Brownf2f48712010-10-01 17:46:21 -07002934 if (!mTouchState.windows.isEmpty()) {
2935 dump.append(INDENT "TouchedWindows:\n");
2936 for (size_t i = 0; i < mTouchState.windows.size(); i++) {
2937 const TouchedWindow& touchedWindow = mTouchState.windows[i];
2938 dump.appendFormat(INDENT2 "%d: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
2939 i, touchedWindow.window->name.string(), touchedWindow.pointerIds.value,
2940 touchedWindow.targetFlags);
2941 }
2942 } else {
2943 dump.append(INDENT "TouchedWindows: <none>\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07002944 }
2945
Jeff Brownf2f48712010-10-01 17:46:21 -07002946 if (!mWindows.isEmpty()) {
2947 dump.append(INDENT "Windows:\n");
2948 for (size_t i = 0; i < mWindows.size(); i++) {
2949 const InputWindow& window = mWindows[i];
2950 dump.appendFormat(INDENT2 "%d: name='%s', paused=%s, hasFocus=%s, hasWallpaper=%s, "
2951 "visible=%s, canReceiveKeys=%s, flags=0x%08x, type=0x%08x, layer=%d, "
2952 "frame=[%d,%d][%d,%d], "
Jeff Brownfbf09772011-01-16 14:06:57 -08002953 "touchableRegion=",
Jeff Brownf2f48712010-10-01 17:46:21 -07002954 i, window.name.string(),
2955 toString(window.paused),
2956 toString(window.hasFocus),
2957 toString(window.hasWallpaper),
2958 toString(window.visible),
2959 toString(window.canReceiveKeys),
2960 window.layoutParamsFlags, window.layoutParamsType,
2961 window.layer,
2962 window.frameLeft, window.frameTop,
Jeff Brownfbf09772011-01-16 14:06:57 -08002963 window.frameRight, window.frameBottom);
2964 dumpRegion(dump, window.touchableRegion);
2965 dump.appendFormat(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%0.3fms\n",
Jeff Brownf2f48712010-10-01 17:46:21 -07002966 window.ownerPid, window.ownerUid,
2967 window.dispatchingTimeout / 1000000.0);
2968 }
2969 } else {
2970 dump.append(INDENT "Windows: <none>\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07002971 }
2972
Jeff Brownf2f48712010-10-01 17:46:21 -07002973 if (!mMonitoringChannels.isEmpty()) {
2974 dump.append(INDENT "MonitoringChannels:\n");
2975 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
2976 const sp<InputChannel>& channel = mMonitoringChannels[i];
2977 dump.appendFormat(INDENT2 "%d: '%s'\n", i, channel->getName().string());
2978 }
2979 } else {
2980 dump.append(INDENT "MonitoringChannels: <none>\n");
2981 }
Jeff Brown519e0242010-09-15 15:18:56 -07002982
Jeff Brownf2f48712010-10-01 17:46:21 -07002983 dump.appendFormat(INDENT "InboundQueue: length=%u\n", mInboundQueue.count());
2984
2985 if (!mActiveConnections.isEmpty()) {
2986 dump.append(INDENT "ActiveConnections:\n");
2987 for (size_t i = 0; i < mActiveConnections.size(); i++) {
2988 const Connection* connection = mActiveConnections[i];
Jeff Brown76860e32010-10-25 17:37:46 -07002989 dump.appendFormat(INDENT2 "%d: '%s', status=%s, outboundQueueLength=%u, "
Jeff Brownb6997262010-10-08 22:31:17 -07002990 "inputState.isNeutral=%s\n",
Jeff Brownf2f48712010-10-01 17:46:21 -07002991 i, connection->getInputChannelName(), connection->getStatusLabel(),
2992 connection->outboundQueue.count(),
Jeff Brownb6997262010-10-08 22:31:17 -07002993 toString(connection->inputState.isNeutral()));
Jeff Brownf2f48712010-10-01 17:46:21 -07002994 }
2995 } else {
2996 dump.append(INDENT "ActiveConnections: <none>\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07002997 }
2998
2999 if (isAppSwitchPendingLocked()) {
Jeff Brownf2f48712010-10-01 17:46:21 -07003000 dump.appendFormat(INDENT "AppSwitch: pending, due in %01.1fms\n",
Jeff Brownb88102f2010-09-08 11:49:43 -07003001 (mAppSwitchDueTime - now()) / 1000000.0);
3002 } else {
Jeff Brownf2f48712010-10-01 17:46:21 -07003003 dump.append(INDENT "AppSwitch: not pending\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003004 }
3005}
3006
Jeff Brown928e0542011-01-10 11:17:36 -08003007status_t InputDispatcher::registerInputChannel(const sp<InputChannel>& inputChannel,
3008 const sp<InputWindowHandle>& inputWindowHandle, bool monitor) {
Jeff Brown9c3cda02010-06-15 01:31:58 -07003009#if DEBUG_REGISTRATION
Jeff Brownb88102f2010-09-08 11:49:43 -07003010 LOGD("channel '%s' ~ registerInputChannel - monitor=%s", inputChannel->getName().string(),
3011 toString(monitor));
Jeff Brown9c3cda02010-06-15 01:31:58 -07003012#endif
3013
Jeff Brown46b9ac02010-04-22 18:58:52 -07003014 { // acquire lock
3015 AutoMutex _l(mLock);
3016
Jeff Brown519e0242010-09-15 15:18:56 -07003017 if (getConnectionIndexLocked(inputChannel) >= 0) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07003018 LOGW("Attempted to register already registered input channel '%s'",
3019 inputChannel->getName().string());
3020 return BAD_VALUE;
3021 }
3022
Jeff Brown928e0542011-01-10 11:17:36 -08003023 sp<Connection> connection = new Connection(inputChannel, inputWindowHandle);
Jeff Brown46b9ac02010-04-22 18:58:52 -07003024 status_t status = connection->initialize();
3025 if (status) {
3026 LOGE("Failed to initialize input publisher for input channel '%s', status=%d",
3027 inputChannel->getName().string(), status);
3028 return status;
3029 }
3030
Jeff Brown2cbecea2010-08-17 15:59:26 -07003031 int32_t receiveFd = inputChannel->getReceivePipeFd();
Jeff Brown46b9ac02010-04-22 18:58:52 -07003032 mConnectionsByReceiveFd.add(receiveFd, connection);
Jeff Brown9c3cda02010-06-15 01:31:58 -07003033
Jeff Brownb88102f2010-09-08 11:49:43 -07003034 if (monitor) {
3035 mMonitoringChannels.push(inputChannel);
3036 }
3037
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07003038 mLooper->addFd(receiveFd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
Jeff Brown2cbecea2010-08-17 15:59:26 -07003039
Jeff Brown9c3cda02010-06-15 01:31:58 -07003040 runCommandsLockedInterruptible();
Jeff Brown46b9ac02010-04-22 18:58:52 -07003041 } // release lock
Jeff Brown46b9ac02010-04-22 18:58:52 -07003042 return OK;
3043}
3044
3045status_t InputDispatcher::unregisterInputChannel(const sp<InputChannel>& inputChannel) {
Jeff Brown9c3cda02010-06-15 01:31:58 -07003046#if DEBUG_REGISTRATION
Jeff Brown349703e2010-06-22 01:27:15 -07003047 LOGD("channel '%s' ~ unregisterInputChannel", inputChannel->getName().string());
Jeff Brown9c3cda02010-06-15 01:31:58 -07003048#endif
3049
Jeff Brown46b9ac02010-04-22 18:58:52 -07003050 { // acquire lock
3051 AutoMutex _l(mLock);
3052
Jeff Brown519e0242010-09-15 15:18:56 -07003053 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
Jeff Brown46b9ac02010-04-22 18:58:52 -07003054 if (connectionIndex < 0) {
3055 LOGW("Attempted to unregister already unregistered input channel '%s'",
3056 inputChannel->getName().string());
3057 return BAD_VALUE;
3058 }
3059
3060 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
3061 mConnectionsByReceiveFd.removeItemsAt(connectionIndex);
3062
3063 connection->status = Connection::STATUS_ZOMBIE;
3064
Jeff Brownb88102f2010-09-08 11:49:43 -07003065 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
3066 if (mMonitoringChannels[i] == inputChannel) {
3067 mMonitoringChannels.removeAt(i);
3068 break;
3069 }
3070 }
3071
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07003072 mLooper->removeFd(inputChannel->getReceivePipeFd());
Jeff Brown2cbecea2010-08-17 15:59:26 -07003073
Jeff Brown7fbdc842010-06-17 20:52:56 -07003074 nsecs_t currentTime = now();
Jeff Brownb6997262010-10-08 22:31:17 -07003075 abortBrokenDispatchCycleLocked(currentTime, connection);
Jeff Brown9c3cda02010-06-15 01:31:58 -07003076
3077 runCommandsLockedInterruptible();
Jeff Brown46b9ac02010-04-22 18:58:52 -07003078 } // release lock
3079
Jeff Brown46b9ac02010-04-22 18:58:52 -07003080 // Wake the poll loop because removing the connection may have changed the current
3081 // synchronization state.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07003082 mLooper->wake();
Jeff Brown46b9ac02010-04-22 18:58:52 -07003083 return OK;
3084}
3085
Jeff Brown519e0242010-09-15 15:18:56 -07003086ssize_t InputDispatcher::getConnectionIndexLocked(const sp<InputChannel>& inputChannel) {
Jeff Brown2cbecea2010-08-17 15:59:26 -07003087 ssize_t connectionIndex = mConnectionsByReceiveFd.indexOfKey(inputChannel->getReceivePipeFd());
3088 if (connectionIndex >= 0) {
3089 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
3090 if (connection->inputChannel.get() == inputChannel.get()) {
3091 return connectionIndex;
3092 }
3093 }
3094
3095 return -1;
3096}
3097
Jeff Brown46b9ac02010-04-22 18:58:52 -07003098void InputDispatcher::activateConnectionLocked(Connection* connection) {
3099 for (size_t i = 0; i < mActiveConnections.size(); i++) {
3100 if (mActiveConnections.itemAt(i) == connection) {
3101 return;
3102 }
3103 }
3104 mActiveConnections.add(connection);
3105}
3106
3107void InputDispatcher::deactivateConnectionLocked(Connection* connection) {
3108 for (size_t i = 0; i < mActiveConnections.size(); i++) {
3109 if (mActiveConnections.itemAt(i) == connection) {
3110 mActiveConnections.removeAt(i);
3111 return;
3112 }
3113 }
3114}
3115
Jeff Brown9c3cda02010-06-15 01:31:58 -07003116void InputDispatcher::onDispatchCycleStartedLocked(
Jeff Brown7fbdc842010-06-17 20:52:56 -07003117 nsecs_t currentTime, const sp<Connection>& connection) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07003118}
3119
Jeff Brown9c3cda02010-06-15 01:31:58 -07003120void InputDispatcher::onDispatchCycleFinishedLocked(
Jeff Brown3915bb82010-11-05 15:02:16 -07003121 nsecs_t currentTime, const sp<Connection>& connection, bool handled) {
3122 CommandEntry* commandEntry = postCommandLocked(
3123 & InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
3124 commandEntry->connection = connection;
3125 commandEntry->handled = handled;
Jeff Brown46b9ac02010-04-22 18:58:52 -07003126}
3127
Jeff Brown9c3cda02010-06-15 01:31:58 -07003128void InputDispatcher::onDispatchCycleBrokenLocked(
Jeff Brown7fbdc842010-06-17 20:52:56 -07003129 nsecs_t currentTime, const sp<Connection>& connection) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07003130 LOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
3131 connection->getInputChannelName());
3132
Jeff Brown9c3cda02010-06-15 01:31:58 -07003133 CommandEntry* commandEntry = postCommandLocked(
3134 & InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
Jeff Brown7fbdc842010-06-17 20:52:56 -07003135 commandEntry->connection = connection;
Jeff Brown46b9ac02010-04-22 18:58:52 -07003136}
3137
Jeff Brown519e0242010-09-15 15:18:56 -07003138void InputDispatcher::onANRLocked(
3139 nsecs_t currentTime, const InputApplication* application, const InputWindow* window,
3140 nsecs_t eventTime, nsecs_t waitStartTime) {
3141 LOGI("Application is not responding: %s. "
3142 "%01.1fms since event, %01.1fms since wait started",
3143 getApplicationWindowLabelLocked(application, window).string(),
3144 (currentTime - eventTime) / 1000000.0,
3145 (currentTime - waitStartTime) / 1000000.0);
3146
3147 CommandEntry* commandEntry = postCommandLocked(
3148 & InputDispatcher::doNotifyANRLockedInterruptible);
3149 if (application) {
Jeff Brown928e0542011-01-10 11:17:36 -08003150 commandEntry->inputApplicationHandle = application->inputApplicationHandle;
Jeff Brown519e0242010-09-15 15:18:56 -07003151 }
3152 if (window) {
Jeff Brown928e0542011-01-10 11:17:36 -08003153 commandEntry->inputWindowHandle = window->inputWindowHandle;
Jeff Brown519e0242010-09-15 15:18:56 -07003154 commandEntry->inputChannel = window->inputChannel;
3155 }
3156}
3157
Jeff Brownb88102f2010-09-08 11:49:43 -07003158void InputDispatcher::doNotifyConfigurationChangedInterruptible(
3159 CommandEntry* commandEntry) {
3160 mLock.unlock();
3161
3162 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
3163
3164 mLock.lock();
3165}
3166
Jeff Brown9c3cda02010-06-15 01:31:58 -07003167void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(
3168 CommandEntry* commandEntry) {
Jeff Brown7fbdc842010-06-17 20:52:56 -07003169 sp<Connection> connection = commandEntry->connection;
Jeff Brown9c3cda02010-06-15 01:31:58 -07003170
Jeff Brown7fbdc842010-06-17 20:52:56 -07003171 if (connection->status != Connection::STATUS_ZOMBIE) {
3172 mLock.unlock();
Jeff Brown9c3cda02010-06-15 01:31:58 -07003173
Jeff Brown928e0542011-01-10 11:17:36 -08003174 mPolicy->notifyInputChannelBroken(connection->inputWindowHandle);
Jeff Brown7fbdc842010-06-17 20:52:56 -07003175
3176 mLock.lock();
3177 }
Jeff Brown9c3cda02010-06-15 01:31:58 -07003178}
3179
Jeff Brown519e0242010-09-15 15:18:56 -07003180void InputDispatcher::doNotifyANRLockedInterruptible(
Jeff Brown9c3cda02010-06-15 01:31:58 -07003181 CommandEntry* commandEntry) {
Jeff Brown519e0242010-09-15 15:18:56 -07003182 mLock.unlock();
Jeff Brown9c3cda02010-06-15 01:31:58 -07003183
Jeff Brown519e0242010-09-15 15:18:56 -07003184 nsecs_t newTimeout = mPolicy->notifyANR(
Jeff Brown928e0542011-01-10 11:17:36 -08003185 commandEntry->inputApplicationHandle, commandEntry->inputWindowHandle);
Jeff Brown9c3cda02010-06-15 01:31:58 -07003186
Jeff Brown519e0242010-09-15 15:18:56 -07003187 mLock.lock();
Jeff Brown7fbdc842010-06-17 20:52:56 -07003188
Jeff Brown519e0242010-09-15 15:18:56 -07003189 resumeAfterTargetsNotReadyTimeoutLocked(newTimeout, commandEntry->inputChannel);
Jeff Brown9c3cda02010-06-15 01:31:58 -07003190}
3191
Jeff Brownb88102f2010-09-08 11:49:43 -07003192void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
3193 CommandEntry* commandEntry) {
3194 KeyEntry* entry = commandEntry->keyEntry;
Jeff Brown1f245102010-11-18 20:53:46 -08003195
3196 KeyEvent event;
3197 initializeKeyEvent(&event, entry);
Jeff Brownb88102f2010-09-08 11:49:43 -07003198
3199 mLock.unlock();
3200
Jeff Brown928e0542011-01-10 11:17:36 -08003201 bool consumed = mPolicy->interceptKeyBeforeDispatching(commandEntry->inputWindowHandle,
Jeff Brown1f245102010-11-18 20:53:46 -08003202 &event, entry->policyFlags);
Jeff Brownb88102f2010-09-08 11:49:43 -07003203
3204 mLock.lock();
3205
3206 entry->interceptKeyResult = consumed
3207 ? KeyEntry::INTERCEPT_KEY_RESULT_SKIP
3208 : KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
3209 mAllocator.releaseKeyEntry(entry);
3210}
3211
Jeff Brown3915bb82010-11-05 15:02:16 -07003212void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(
3213 CommandEntry* commandEntry) {
3214 sp<Connection> connection = commandEntry->connection;
3215 bool handled = commandEntry->handled;
3216
Jeff Brown49ed71d2010-12-06 17:13:33 -08003217 if (!connection->outboundQueue.isEmpty()) {
Jeff Brown3915bb82010-11-05 15:02:16 -07003218 DispatchEntry* dispatchEntry = connection->outboundQueue.headSentinel.next;
3219 if (dispatchEntry->inProgress
3220 && dispatchEntry->hasForegroundTarget()
3221 && dispatchEntry->eventEntry->type == EventEntry::TYPE_KEY) {
3222 KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry);
Jeff Brown49ed71d2010-12-06 17:13:33 -08003223 if (!(keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK)) {
3224 if (handled) {
3225 // If the application handled a non-fallback key, then immediately
3226 // cancel all fallback keys previously dispatched to the application.
3227 // This behavior will prevent chording with fallback keys (so they cannot
3228 // be used as modifiers) but it will ensure that fallback keys do not
3229 // get stuck. This takes care of the case where the application does not handle
3230 // the original DOWN so we generate a fallback DOWN but it does handle
Jeff Brownbfaf3b92011-02-22 15:00:50 -08003231 // the original UP in which case we want to send a fallback CANCEL.
Jeff Brown49ed71d2010-12-06 17:13:33 -08003232 synthesizeCancelationEventsForConnectionLocked(connection,
3233 InputState::CANCEL_FALLBACK_EVENTS,
Jeff Brownbfaf3b92011-02-22 15:00:50 -08003234 "application handled a non-fallback event, "
3235 "canceling all fallback events");
3236 connection->originalKeyCodeForFallback = -1;
Jeff Brown49ed71d2010-12-06 17:13:33 -08003237 } else {
Jeff Brownbfaf3b92011-02-22 15:00:50 -08003238 // If the application did not handle a non-fallback key, first check
3239 // that we are in a good state to handle the fallback key. Then ask
3240 // the policy what to do with it.
3241 if (connection->originalKeyCodeForFallback < 0) {
3242 if (keyEntry->action != AKEY_EVENT_ACTION_DOWN
3243 || keyEntry->repeatCount != 0) {
3244#if DEBUG_OUTBOUND_EVENT_DETAILS
3245 LOGD("Unhandled key event: Skipping fallback since this "
3246 "is not an initial down. "
3247 "keyCode=%d, action=%d, repeatCount=%d",
3248 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount);
3249#endif
3250 goto SkipFallback;
3251 }
3252
3253 // Start handling the fallback key on DOWN.
3254 connection->originalKeyCodeForFallback = keyEntry->keyCode;
3255 } else {
3256 if (keyEntry->keyCode != connection->originalKeyCodeForFallback) {
3257#if DEBUG_OUTBOUND_EVENT_DETAILS
3258 LOGD("Unhandled key event: Skipping fallback since there is "
3259 "already a different fallback in progress. "
3260 "keyCode=%d, originalKeyCodeForFallback=%d",
3261 keyEntry->keyCode, connection->originalKeyCodeForFallback);
3262#endif
3263 goto SkipFallback;
3264 }
3265
3266 // Finish handling the fallback key on UP.
3267 if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
3268 connection->originalKeyCodeForFallback = -1;
3269 }
3270 }
3271
3272#if DEBUG_OUTBOUND_EVENT_DETAILS
3273 LOGD("Unhandled key event: Asking policy to perform fallback action. "
3274 "keyCode=%d, action=%d, repeatCount=%d",
3275 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount);
3276#endif
Jeff Brown49ed71d2010-12-06 17:13:33 -08003277 KeyEvent event;
3278 initializeKeyEvent(&event, keyEntry);
Jeff Brown3915bb82010-11-05 15:02:16 -07003279
Jeff Brown49ed71d2010-12-06 17:13:33 -08003280 mLock.unlock();
Jeff Brown3915bb82010-11-05 15:02:16 -07003281
Jeff Brown928e0542011-01-10 11:17:36 -08003282 bool fallback = mPolicy->dispatchUnhandledKey(connection->inputWindowHandle,
Jeff Brown49ed71d2010-12-06 17:13:33 -08003283 &event, keyEntry->policyFlags, &event);
Jeff Brown3915bb82010-11-05 15:02:16 -07003284
Jeff Brown49ed71d2010-12-06 17:13:33 -08003285 mLock.lock();
3286
Jeff Brown00045a72010-12-09 18:10:30 -08003287 if (connection->status != Connection::STATUS_NORMAL) {
3288 return;
3289 }
3290
3291 assert(connection->outboundQueue.headSentinel.next == dispatchEntry);
3292
Jeff Brown49ed71d2010-12-06 17:13:33 -08003293 if (fallback) {
3294 // Restart the dispatch cycle using the fallback key.
3295 keyEntry->eventTime = event.getEventTime();
3296 keyEntry->deviceId = event.getDeviceId();
3297 keyEntry->source = event.getSource();
3298 keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
3299 keyEntry->keyCode = event.getKeyCode();
3300 keyEntry->scanCode = event.getScanCode();
3301 keyEntry->metaState = event.getMetaState();
3302 keyEntry->repeatCount = event.getRepeatCount();
3303 keyEntry->downTime = event.getDownTime();
3304 keyEntry->syntheticRepeat = false;
3305
Jeff Brownbfaf3b92011-02-22 15:00:50 -08003306#if DEBUG_OUTBOUND_EVENT_DETAILS
3307 LOGD("Unhandled key event: Dispatching fallback key. "
3308 "fallbackKeyCode=%d, fallbackMetaState=%08x",
3309 keyEntry->keyCode, keyEntry->metaState);
3310#endif
3311
Jeff Brown49ed71d2010-12-06 17:13:33 -08003312 dispatchEntry->inProgress = false;
3313 startDispatchCycleLocked(now(), connection);
3314 return;
3315 }
3316 }
3317 }
Jeff Brown3915bb82010-11-05 15:02:16 -07003318 }
3319 }
3320
Jeff Brownbfaf3b92011-02-22 15:00:50 -08003321SkipFallback:
Jeff Brown3915bb82010-11-05 15:02:16 -07003322 startNextDispatchCycleLocked(now(), connection);
3323}
3324
Jeff Brownb88102f2010-09-08 11:49:43 -07003325void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
3326 mLock.unlock();
3327
Jeff Brown01ce2e92010-09-26 22:20:12 -07003328 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
Jeff Brownb88102f2010-09-08 11:49:43 -07003329
3330 mLock.lock();
3331}
3332
Jeff Brown3915bb82010-11-05 15:02:16 -07003333void InputDispatcher::initializeKeyEvent(KeyEvent* event, const KeyEntry* entry) {
3334 event->initialize(entry->deviceId, entry->source, entry->action, entry->flags,
3335 entry->keyCode, entry->scanCode, entry->metaState, entry->repeatCount,
3336 entry->downTime, entry->eventTime);
3337}
3338
Jeff Brown519e0242010-09-15 15:18:56 -07003339void InputDispatcher::updateDispatchStatisticsLocked(nsecs_t currentTime, const EventEntry* entry,
3340 int32_t injectionResult, nsecs_t timeSpentWaitingForApplication) {
3341 // TODO Write some statistics about how long we spend waiting.
Jeff Brownb88102f2010-09-08 11:49:43 -07003342}
3343
3344void InputDispatcher::dump(String8& dump) {
Jeff Brownf2f48712010-10-01 17:46:21 -07003345 dump.append("Input Dispatcher State:\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003346 dumpDispatchStateLocked(dump);
3347}
3348
Jeff Brown9c3cda02010-06-15 01:31:58 -07003349
Jeff Brown519e0242010-09-15 15:18:56 -07003350// --- InputDispatcher::Queue ---
3351
3352template <typename T>
3353uint32_t InputDispatcher::Queue<T>::count() const {
3354 uint32_t result = 0;
3355 for (const T* entry = headSentinel.next; entry != & tailSentinel; entry = entry->next) {
3356 result += 1;
3357 }
3358 return result;
3359}
3360
3361
Jeff Brown46b9ac02010-04-22 18:58:52 -07003362// --- InputDispatcher::Allocator ---
3363
3364InputDispatcher::Allocator::Allocator() {
3365}
3366
Jeff Brown01ce2e92010-09-26 22:20:12 -07003367InputDispatcher::InjectionState*
3368InputDispatcher::Allocator::obtainInjectionState(int32_t injectorPid, int32_t injectorUid) {
3369 InjectionState* injectionState = mInjectionStatePool.alloc();
3370 injectionState->refCount = 1;
3371 injectionState->injectorPid = injectorPid;
3372 injectionState->injectorUid = injectorUid;
3373 injectionState->injectionIsAsync = false;
3374 injectionState->injectionResult = INPUT_EVENT_INJECTION_PENDING;
3375 injectionState->pendingForegroundDispatches = 0;
3376 return injectionState;
3377}
3378
Jeff Brown7fbdc842010-06-17 20:52:56 -07003379void InputDispatcher::Allocator::initializeEventEntry(EventEntry* entry, int32_t type,
Jeff Brownb6997262010-10-08 22:31:17 -07003380 nsecs_t eventTime, uint32_t policyFlags) {
Jeff Brown7fbdc842010-06-17 20:52:56 -07003381 entry->type = type;
3382 entry->refCount = 1;
3383 entry->dispatchInProgress = false;
Christopher Tatee91a5db2010-06-23 16:50:30 -07003384 entry->eventTime = eventTime;
Jeff Brownb6997262010-10-08 22:31:17 -07003385 entry->policyFlags = policyFlags;
Jeff Brown01ce2e92010-09-26 22:20:12 -07003386 entry->injectionState = NULL;
3387}
3388
3389void InputDispatcher::Allocator::releaseEventEntryInjectionState(EventEntry* entry) {
3390 if (entry->injectionState) {
3391 releaseInjectionState(entry->injectionState);
3392 entry->injectionState = NULL;
3393 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07003394}
3395
Jeff Brown46b9ac02010-04-22 18:58:52 -07003396InputDispatcher::ConfigurationChangedEntry*
Jeff Brown7fbdc842010-06-17 20:52:56 -07003397InputDispatcher::Allocator::obtainConfigurationChangedEntry(nsecs_t eventTime) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07003398 ConfigurationChangedEntry* entry = mConfigurationChangeEntryPool.alloc();
Jeff Brownb6997262010-10-08 22:31:17 -07003399 initializeEventEntry(entry, EventEntry::TYPE_CONFIGURATION_CHANGED, eventTime, 0);
Jeff Brown46b9ac02010-04-22 18:58:52 -07003400 return entry;
3401}
3402
Jeff Brown7fbdc842010-06-17 20:52:56 -07003403InputDispatcher::KeyEntry* InputDispatcher::Allocator::obtainKeyEntry(nsecs_t eventTime,
Jeff Brown58a2da82011-01-25 16:02:22 -08003404 int32_t deviceId, uint32_t source, uint32_t policyFlags, int32_t action,
Jeff Brown7fbdc842010-06-17 20:52:56 -07003405 int32_t flags, int32_t keyCode, int32_t scanCode, int32_t metaState,
3406 int32_t repeatCount, nsecs_t downTime) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07003407 KeyEntry* entry = mKeyEntryPool.alloc();
Jeff Brownb6997262010-10-08 22:31:17 -07003408 initializeEventEntry(entry, EventEntry::TYPE_KEY, eventTime, policyFlags);
Jeff Brown7fbdc842010-06-17 20:52:56 -07003409
3410 entry->deviceId = deviceId;
Jeff Brownc5ed5912010-07-14 18:48:53 -07003411 entry->source = source;
Jeff Brown7fbdc842010-06-17 20:52:56 -07003412 entry->action = action;
3413 entry->flags = flags;
3414 entry->keyCode = keyCode;
3415 entry->scanCode = scanCode;
3416 entry->metaState = metaState;
3417 entry->repeatCount = repeatCount;
3418 entry->downTime = downTime;
Jeff Brownb88102f2010-09-08 11:49:43 -07003419 entry->syntheticRepeat = false;
3420 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
Jeff Brown46b9ac02010-04-22 18:58:52 -07003421 return entry;
3422}
3423
Jeff Brown7fbdc842010-06-17 20:52:56 -07003424InputDispatcher::MotionEntry* InputDispatcher::Allocator::obtainMotionEntry(nsecs_t eventTime,
Jeff Brown58a2da82011-01-25 16:02:22 -08003425 int32_t deviceId, uint32_t source, uint32_t policyFlags, int32_t action, int32_t flags,
Jeff Brown7fbdc842010-06-17 20:52:56 -07003426 int32_t metaState, int32_t edgeFlags, float xPrecision, float yPrecision,
3427 nsecs_t downTime, uint32_t pointerCount,
3428 const int32_t* pointerIds, const PointerCoords* pointerCoords) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07003429 MotionEntry* entry = mMotionEntryPool.alloc();
Jeff Brownb6997262010-10-08 22:31:17 -07003430 initializeEventEntry(entry, EventEntry::TYPE_MOTION, eventTime, policyFlags);
Jeff Brown7fbdc842010-06-17 20:52:56 -07003431
3432 entry->eventTime = eventTime;
3433 entry->deviceId = deviceId;
Jeff Brownc5ed5912010-07-14 18:48:53 -07003434 entry->source = source;
Jeff Brown7fbdc842010-06-17 20:52:56 -07003435 entry->action = action;
Jeff Brown85a31762010-09-01 17:01:00 -07003436 entry->flags = flags;
Jeff Brown7fbdc842010-06-17 20:52:56 -07003437 entry->metaState = metaState;
3438 entry->edgeFlags = edgeFlags;
3439 entry->xPrecision = xPrecision;
3440 entry->yPrecision = yPrecision;
3441 entry->downTime = downTime;
3442 entry->pointerCount = pointerCount;
3443 entry->firstSample.eventTime = eventTime;
Jeff Brown46b9ac02010-04-22 18:58:52 -07003444 entry->firstSample.next = NULL;
Jeff Brown7fbdc842010-06-17 20:52:56 -07003445 entry->lastSample = & entry->firstSample;
3446 for (uint32_t i = 0; i < pointerCount; i++) {
3447 entry->pointerIds[i] = pointerIds[i];
Jeff Brownace13b12011-03-09 17:39:48 -08003448 entry->firstSample.pointerCoords[i].copyFrom(pointerCoords[i]);
Jeff Brown7fbdc842010-06-17 20:52:56 -07003449 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07003450 return entry;
3451}
3452
3453InputDispatcher::DispatchEntry* InputDispatcher::Allocator::obtainDispatchEntry(
Jeff Brownb88102f2010-09-08 11:49:43 -07003454 EventEntry* eventEntry,
Jeff Brown519e0242010-09-15 15:18:56 -07003455 int32_t targetFlags, float xOffset, float yOffset) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07003456 DispatchEntry* entry = mDispatchEntryPool.alloc();
3457 entry->eventEntry = eventEntry;
3458 eventEntry->refCount += 1;
Jeff Brownb88102f2010-09-08 11:49:43 -07003459 entry->targetFlags = targetFlags;
3460 entry->xOffset = xOffset;
3461 entry->yOffset = yOffset;
Jeff Brownb88102f2010-09-08 11:49:43 -07003462 entry->inProgress = false;
3463 entry->headMotionSample = NULL;
3464 entry->tailMotionSample = NULL;
Jeff Brown46b9ac02010-04-22 18:58:52 -07003465 return entry;
3466}
3467
Jeff Brown9c3cda02010-06-15 01:31:58 -07003468InputDispatcher::CommandEntry* InputDispatcher::Allocator::obtainCommandEntry(Command command) {
3469 CommandEntry* entry = mCommandEntryPool.alloc();
3470 entry->command = command;
3471 return entry;
3472}
3473
Jeff Brown01ce2e92010-09-26 22:20:12 -07003474void InputDispatcher::Allocator::releaseInjectionState(InjectionState* injectionState) {
3475 injectionState->refCount -= 1;
3476 if (injectionState->refCount == 0) {
3477 mInjectionStatePool.free(injectionState);
3478 } else {
3479 assert(injectionState->refCount > 0);
3480 }
3481}
3482
Jeff Brown46b9ac02010-04-22 18:58:52 -07003483void InputDispatcher::Allocator::releaseEventEntry(EventEntry* entry) {
3484 switch (entry->type) {
3485 case EventEntry::TYPE_CONFIGURATION_CHANGED:
3486 releaseConfigurationChangedEntry(static_cast<ConfigurationChangedEntry*>(entry));
3487 break;
3488 case EventEntry::TYPE_KEY:
3489 releaseKeyEntry(static_cast<KeyEntry*>(entry));
3490 break;
3491 case EventEntry::TYPE_MOTION:
3492 releaseMotionEntry(static_cast<MotionEntry*>(entry));
3493 break;
3494 default:
3495 assert(false);
3496 break;
3497 }
3498}
3499
3500void InputDispatcher::Allocator::releaseConfigurationChangedEntry(
3501 ConfigurationChangedEntry* entry) {
3502 entry->refCount -= 1;
3503 if (entry->refCount == 0) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07003504 releaseEventEntryInjectionState(entry);
Jeff Brown46b9ac02010-04-22 18:58:52 -07003505 mConfigurationChangeEntryPool.free(entry);
3506 } else {
3507 assert(entry->refCount > 0);
3508 }
3509}
3510
3511void InputDispatcher::Allocator::releaseKeyEntry(KeyEntry* entry) {
3512 entry->refCount -= 1;
3513 if (entry->refCount == 0) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07003514 releaseEventEntryInjectionState(entry);
Jeff Brown46b9ac02010-04-22 18:58:52 -07003515 mKeyEntryPool.free(entry);
3516 } else {
3517 assert(entry->refCount > 0);
3518 }
3519}
3520
3521void InputDispatcher::Allocator::releaseMotionEntry(MotionEntry* entry) {
3522 entry->refCount -= 1;
3523 if (entry->refCount == 0) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07003524 releaseEventEntryInjectionState(entry);
Jeff Brown9c3cda02010-06-15 01:31:58 -07003525 for (MotionSample* sample = entry->firstSample.next; sample != NULL; ) {
3526 MotionSample* next = sample->next;
3527 mMotionSamplePool.free(sample);
3528 sample = next;
3529 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07003530 mMotionEntryPool.free(entry);
3531 } else {
3532 assert(entry->refCount > 0);
3533 }
3534}
3535
3536void InputDispatcher::Allocator::releaseDispatchEntry(DispatchEntry* entry) {
3537 releaseEventEntry(entry->eventEntry);
3538 mDispatchEntryPool.free(entry);
3539}
3540
Jeff Brown9c3cda02010-06-15 01:31:58 -07003541void InputDispatcher::Allocator::releaseCommandEntry(CommandEntry* entry) {
3542 mCommandEntryPool.free(entry);
3543}
3544
Jeff Brown46b9ac02010-04-22 18:58:52 -07003545void InputDispatcher::Allocator::appendMotionSample(MotionEntry* motionEntry,
Jeff Brown7fbdc842010-06-17 20:52:56 -07003546 nsecs_t eventTime, const PointerCoords* pointerCoords) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07003547 MotionSample* sample = mMotionSamplePool.alloc();
3548 sample->eventTime = eventTime;
Jeff Brown7fbdc842010-06-17 20:52:56 -07003549 uint32_t pointerCount = motionEntry->pointerCount;
3550 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brownace13b12011-03-09 17:39:48 -08003551 sample->pointerCoords[i].copyFrom(pointerCoords[i]);
Jeff Brown46b9ac02010-04-22 18:58:52 -07003552 }
3553
3554 sample->next = NULL;
3555 motionEntry->lastSample->next = sample;
3556 motionEntry->lastSample = sample;
3557}
3558
Jeff Brown01ce2e92010-09-26 22:20:12 -07003559void InputDispatcher::Allocator::recycleKeyEntry(KeyEntry* keyEntry) {
3560 releaseEventEntryInjectionState(keyEntry);
Jeff Brownb88102f2010-09-08 11:49:43 -07003561
Jeff Brown01ce2e92010-09-26 22:20:12 -07003562 keyEntry->dispatchInProgress = false;
3563 keyEntry->syntheticRepeat = false;
3564 keyEntry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
Jeff Brownb88102f2010-09-08 11:49:43 -07003565}
3566
3567
Jeff Brownae9fc032010-08-18 15:51:08 -07003568// --- InputDispatcher::MotionEntry ---
3569
3570uint32_t InputDispatcher::MotionEntry::countSamples() const {
3571 uint32_t count = 1;
3572 for (MotionSample* sample = firstSample.next; sample != NULL; sample = sample->next) {
3573 count += 1;
3574 }
3575 return count;
3576}
3577
Jeff Brownb88102f2010-09-08 11:49:43 -07003578
3579// --- InputDispatcher::InputState ---
3580
Jeff Brownb6997262010-10-08 22:31:17 -07003581InputDispatcher::InputState::InputState() {
Jeff Brownb88102f2010-09-08 11:49:43 -07003582}
3583
3584InputDispatcher::InputState::~InputState() {
3585}
3586
3587bool InputDispatcher::InputState::isNeutral() const {
3588 return mKeyMementos.isEmpty() && mMotionMementos.isEmpty();
3589}
3590
Jeff Browncc0c1592011-02-19 05:07:28 -08003591void InputDispatcher::InputState::trackEvent(
Jeff Brownb88102f2010-09-08 11:49:43 -07003592 const EventEntry* entry) {
3593 switch (entry->type) {
3594 case EventEntry::TYPE_KEY:
Jeff Browncc0c1592011-02-19 05:07:28 -08003595 trackKey(static_cast<const KeyEntry*>(entry));
3596 break;
Jeff Brownb88102f2010-09-08 11:49:43 -07003597
3598 case EventEntry::TYPE_MOTION:
Jeff Browncc0c1592011-02-19 05:07:28 -08003599 trackMotion(static_cast<const MotionEntry*>(entry));
3600 break;
Jeff Brownb88102f2010-09-08 11:49:43 -07003601 }
3602}
3603
Jeff Browncc0c1592011-02-19 05:07:28 -08003604void InputDispatcher::InputState::trackKey(
Jeff Brownb88102f2010-09-08 11:49:43 -07003605 const KeyEntry* entry) {
3606 int32_t action = entry->action;
3607 for (size_t i = 0; i < mKeyMementos.size(); i++) {
3608 KeyMemento& memento = mKeyMementos.editItemAt(i);
3609 if (memento.deviceId == entry->deviceId
3610 && memento.source == entry->source
3611 && memento.keyCode == entry->keyCode
3612 && memento.scanCode == entry->scanCode) {
3613 switch (action) {
3614 case AKEY_EVENT_ACTION_UP:
3615 mKeyMementos.removeAt(i);
Jeff Browncc0c1592011-02-19 05:07:28 -08003616 return;
Jeff Brownb88102f2010-09-08 11:49:43 -07003617
3618 case AKEY_EVENT_ACTION_DOWN:
Jeff Browncc0c1592011-02-19 05:07:28 -08003619 mKeyMementos.removeAt(i);
3620 goto Found;
Jeff Brownb88102f2010-09-08 11:49:43 -07003621
3622 default:
Jeff Browncc0c1592011-02-19 05:07:28 -08003623 return;
Jeff Brownb88102f2010-09-08 11:49:43 -07003624 }
3625 }
3626 }
3627
Jeff Browncc0c1592011-02-19 05:07:28 -08003628Found:
3629 if (action == AKEY_EVENT_ACTION_DOWN) {
Jeff Brownb88102f2010-09-08 11:49:43 -07003630 mKeyMementos.push();
3631 KeyMemento& memento = mKeyMementos.editTop();
3632 memento.deviceId = entry->deviceId;
3633 memento.source = entry->source;
3634 memento.keyCode = entry->keyCode;
3635 memento.scanCode = entry->scanCode;
Jeff Brown49ed71d2010-12-06 17:13:33 -08003636 memento.flags = entry->flags;
Jeff Brownb88102f2010-09-08 11:49:43 -07003637 memento.downTime = entry->downTime;
Jeff Brownb88102f2010-09-08 11:49:43 -07003638 }
3639}
3640
Jeff Browncc0c1592011-02-19 05:07:28 -08003641void InputDispatcher::InputState::trackMotion(
Jeff Brownb88102f2010-09-08 11:49:43 -07003642 const MotionEntry* entry) {
3643 int32_t action = entry->action & AMOTION_EVENT_ACTION_MASK;
3644 for (size_t i = 0; i < mMotionMementos.size(); i++) {
3645 MotionMemento& memento = mMotionMementos.editItemAt(i);
3646 if (memento.deviceId == entry->deviceId
3647 && memento.source == entry->source) {
3648 switch (action) {
3649 case AMOTION_EVENT_ACTION_UP:
3650 case AMOTION_EVENT_ACTION_CANCEL:
Jeff Browncc0c1592011-02-19 05:07:28 -08003651 case AMOTION_EVENT_ACTION_HOVER_MOVE:
Jeff Brownb88102f2010-09-08 11:49:43 -07003652 mMotionMementos.removeAt(i);
Jeff Browncc0c1592011-02-19 05:07:28 -08003653 return;
Jeff Brownb88102f2010-09-08 11:49:43 -07003654
3655 case AMOTION_EVENT_ACTION_DOWN:
Jeff Browncc0c1592011-02-19 05:07:28 -08003656 mMotionMementos.removeAt(i);
3657 goto Found;
Jeff Brownb88102f2010-09-08 11:49:43 -07003658
3659 case AMOTION_EVENT_ACTION_POINTER_UP:
Jeff Browncc0c1592011-02-19 05:07:28 -08003660 case AMOTION_EVENT_ACTION_POINTER_DOWN:
Jeff Brownb88102f2010-09-08 11:49:43 -07003661 case AMOTION_EVENT_ACTION_MOVE:
Jeff Browncc0c1592011-02-19 05:07:28 -08003662 memento.setPointers(entry);
3663 return;
Jeff Brownb88102f2010-09-08 11:49:43 -07003664
3665 default:
Jeff Browncc0c1592011-02-19 05:07:28 -08003666 return;
Jeff Brownb88102f2010-09-08 11:49:43 -07003667 }
3668 }
3669 }
3670
Jeff Browncc0c1592011-02-19 05:07:28 -08003671Found:
3672 if (action == AMOTION_EVENT_ACTION_DOWN) {
Jeff Brownb88102f2010-09-08 11:49:43 -07003673 mMotionMementos.push();
3674 MotionMemento& memento = mMotionMementos.editTop();
3675 memento.deviceId = entry->deviceId;
3676 memento.source = entry->source;
3677 memento.xPrecision = entry->xPrecision;
3678 memento.yPrecision = entry->yPrecision;
3679 memento.downTime = entry->downTime;
3680 memento.setPointers(entry);
Jeff Brownb88102f2010-09-08 11:49:43 -07003681 }
3682}
3683
3684void InputDispatcher::InputState::MotionMemento::setPointers(const MotionEntry* entry) {
3685 pointerCount = entry->pointerCount;
3686 for (uint32_t i = 0; i < entry->pointerCount; i++) {
3687 pointerIds[i] = entry->pointerIds[i];
Jeff Brownace13b12011-03-09 17:39:48 -08003688 pointerCoords[i].copyFrom(entry->lastSample->pointerCoords[i]);
Jeff Brownb88102f2010-09-08 11:49:43 -07003689 }
3690}
3691
Jeff Brownb6997262010-10-08 22:31:17 -07003692void InputDispatcher::InputState::synthesizeCancelationEvents(nsecs_t currentTime,
3693 Allocator* allocator, Vector<EventEntry*>& outEvents,
3694 CancelationOptions options) {
3695 for (size_t i = 0; i < mKeyMementos.size(); ) {
Jeff Brownb88102f2010-09-08 11:49:43 -07003696 const KeyMemento& memento = mKeyMementos.itemAt(i);
Jeff Brown49ed71d2010-12-06 17:13:33 -08003697 if (shouldCancelKey(memento, options)) {
Jeff Brownb6997262010-10-08 22:31:17 -07003698 outEvents.push(allocator->obtainKeyEntry(currentTime,
3699 memento.deviceId, memento.source, 0,
Jeff Brown49ed71d2010-12-06 17:13:33 -08003700 AKEY_EVENT_ACTION_UP, memento.flags | AKEY_EVENT_FLAG_CANCELED,
Jeff Brownb6997262010-10-08 22:31:17 -07003701 memento.keyCode, memento.scanCode, 0, 0, memento.downTime));
3702 mKeyMementos.removeAt(i);
3703 } else {
3704 i += 1;
3705 }
Jeff Brownb88102f2010-09-08 11:49:43 -07003706 }
3707
Jeff Browna1160a72010-10-11 18:22:53 -07003708 for (size_t i = 0; i < mMotionMementos.size(); ) {
Jeff Brownb88102f2010-09-08 11:49:43 -07003709 const MotionMemento& memento = mMotionMementos.itemAt(i);
Jeff Brown49ed71d2010-12-06 17:13:33 -08003710 if (shouldCancelMotion(memento, options)) {
Jeff Brownb6997262010-10-08 22:31:17 -07003711 outEvents.push(allocator->obtainMotionEntry(currentTime,
3712 memento.deviceId, memento.source, 0,
3713 AMOTION_EVENT_ACTION_CANCEL, 0, 0, 0,
3714 memento.xPrecision, memento.yPrecision, memento.downTime,
3715 memento.pointerCount, memento.pointerIds, memento.pointerCoords));
3716 mMotionMementos.removeAt(i);
3717 } else {
3718 i += 1;
3719 }
Jeff Brownb88102f2010-09-08 11:49:43 -07003720 }
3721}
3722
3723void InputDispatcher::InputState::clear() {
3724 mKeyMementos.clear();
3725 mMotionMementos.clear();
Jeff Brownb6997262010-10-08 22:31:17 -07003726}
3727
Jeff Brown9c9f1a32010-10-11 18:32:20 -07003728void InputDispatcher::InputState::copyPointerStateTo(InputState& other) const {
3729 for (size_t i = 0; i < mMotionMementos.size(); i++) {
3730 const MotionMemento& memento = mMotionMementos.itemAt(i);
3731 if (memento.source & AINPUT_SOURCE_CLASS_POINTER) {
3732 for (size_t j = 0; j < other.mMotionMementos.size(); ) {
3733 const MotionMemento& otherMemento = other.mMotionMementos.itemAt(j);
3734 if (memento.deviceId == otherMemento.deviceId
3735 && memento.source == otherMemento.source) {
3736 other.mMotionMementos.removeAt(j);
3737 } else {
3738 j += 1;
3739 }
3740 }
3741 other.mMotionMementos.push(memento);
3742 }
3743 }
3744}
3745
Jeff Brown49ed71d2010-12-06 17:13:33 -08003746bool InputDispatcher::InputState::shouldCancelKey(const KeyMemento& memento,
Jeff Brownb6997262010-10-08 22:31:17 -07003747 CancelationOptions options) {
3748 switch (options) {
Jeff Brown49ed71d2010-12-06 17:13:33 -08003749 case CANCEL_ALL_EVENTS:
Jeff Brownb6997262010-10-08 22:31:17 -07003750 case CANCEL_NON_POINTER_EVENTS:
Jeff Brownb6997262010-10-08 22:31:17 -07003751 return true;
Jeff Brown49ed71d2010-12-06 17:13:33 -08003752 case CANCEL_FALLBACK_EVENTS:
3753 return memento.flags & AKEY_EVENT_FLAG_FALLBACK;
3754 default:
3755 return false;
3756 }
3757}
3758
3759bool InputDispatcher::InputState::shouldCancelMotion(const MotionMemento& memento,
3760 CancelationOptions options) {
3761 switch (options) {
3762 case CANCEL_ALL_EVENTS:
3763 return true;
3764 case CANCEL_POINTER_EVENTS:
3765 return memento.source & AINPUT_SOURCE_CLASS_POINTER;
3766 case CANCEL_NON_POINTER_EVENTS:
3767 return !(memento.source & AINPUT_SOURCE_CLASS_POINTER);
3768 default:
3769 return false;
Jeff Brownb6997262010-10-08 22:31:17 -07003770 }
Jeff Brownb88102f2010-09-08 11:49:43 -07003771}
3772
3773
Jeff Brown46b9ac02010-04-22 18:58:52 -07003774// --- InputDispatcher::Connection ---
3775
Jeff Brown928e0542011-01-10 11:17:36 -08003776InputDispatcher::Connection::Connection(const sp<InputChannel>& inputChannel,
3777 const sp<InputWindowHandle>& inputWindowHandle) :
3778 status(STATUS_NORMAL), inputChannel(inputChannel), inputWindowHandle(inputWindowHandle),
3779 inputPublisher(inputChannel),
Jeff Brownbfaf3b92011-02-22 15:00:50 -08003780 lastEventTime(LONG_LONG_MAX), lastDispatchTime(LONG_LONG_MAX),
3781 originalKeyCodeForFallback(-1) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07003782}
3783
3784InputDispatcher::Connection::~Connection() {
3785}
3786
3787status_t InputDispatcher::Connection::initialize() {
3788 return inputPublisher.initialize();
3789}
3790
Jeff Brown9c3cda02010-06-15 01:31:58 -07003791const char* InputDispatcher::Connection::getStatusLabel() const {
3792 switch (status) {
3793 case STATUS_NORMAL:
3794 return "NORMAL";
3795
3796 case STATUS_BROKEN:
3797 return "BROKEN";
3798
Jeff Brown9c3cda02010-06-15 01:31:58 -07003799 case STATUS_ZOMBIE:
3800 return "ZOMBIE";
3801
3802 default:
3803 return "UNKNOWN";
3804 }
3805}
3806
Jeff Brown46b9ac02010-04-22 18:58:52 -07003807InputDispatcher::DispatchEntry* InputDispatcher::Connection::findQueuedDispatchEntryForEvent(
3808 const EventEntry* eventEntry) const {
Jeff Brownb88102f2010-09-08 11:49:43 -07003809 for (DispatchEntry* dispatchEntry = outboundQueue.tailSentinel.prev;
3810 dispatchEntry != & outboundQueue.headSentinel; dispatchEntry = dispatchEntry->prev) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07003811 if (dispatchEntry->eventEntry == eventEntry) {
3812 return dispatchEntry;
3813 }
3814 }
3815 return NULL;
3816}
3817
Jeff Brownb88102f2010-09-08 11:49:43 -07003818
Jeff Brown9c3cda02010-06-15 01:31:58 -07003819// --- InputDispatcher::CommandEntry ---
3820
Jeff Brownb88102f2010-09-08 11:49:43 -07003821InputDispatcher::CommandEntry::CommandEntry() :
3822 keyEntry(NULL) {
Jeff Brown9c3cda02010-06-15 01:31:58 -07003823}
3824
3825InputDispatcher::CommandEntry::~CommandEntry() {
3826}
3827
Jeff Brown46b9ac02010-04-22 18:58:52 -07003828
Jeff Brown01ce2e92010-09-26 22:20:12 -07003829// --- InputDispatcher::TouchState ---
3830
3831InputDispatcher::TouchState::TouchState() :
Jeff Brown58a2da82011-01-25 16:02:22 -08003832 down(false), split(false), deviceId(-1), source(0) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07003833}
3834
3835InputDispatcher::TouchState::~TouchState() {
3836}
3837
3838void InputDispatcher::TouchState::reset() {
3839 down = false;
3840 split = false;
Jeff Brown95712852011-01-04 19:41:59 -08003841 deviceId = -1;
Jeff Brown58a2da82011-01-25 16:02:22 -08003842 source = 0;
Jeff Brown01ce2e92010-09-26 22:20:12 -07003843 windows.clear();
3844}
3845
3846void InputDispatcher::TouchState::copyFrom(const TouchState& other) {
3847 down = other.down;
3848 split = other.split;
Jeff Brown95712852011-01-04 19:41:59 -08003849 deviceId = other.deviceId;
Jeff Brown58a2da82011-01-25 16:02:22 -08003850 source = other.source;
Jeff Brown01ce2e92010-09-26 22:20:12 -07003851 windows.clear();
3852 windows.appendVector(other.windows);
3853}
3854
3855void InputDispatcher::TouchState::addOrUpdateWindow(const InputWindow* window,
3856 int32_t targetFlags, BitSet32 pointerIds) {
3857 if (targetFlags & InputTarget::FLAG_SPLIT) {
3858 split = true;
3859 }
3860
3861 for (size_t i = 0; i < windows.size(); i++) {
3862 TouchedWindow& touchedWindow = windows.editItemAt(i);
3863 if (touchedWindow.window == window) {
3864 touchedWindow.targetFlags |= targetFlags;
3865 touchedWindow.pointerIds.value |= pointerIds.value;
3866 return;
3867 }
3868 }
3869
3870 windows.push();
3871
3872 TouchedWindow& touchedWindow = windows.editTop();
3873 touchedWindow.window = window;
3874 touchedWindow.targetFlags = targetFlags;
3875 touchedWindow.pointerIds = pointerIds;
3876 touchedWindow.channel = window->inputChannel;
3877}
3878
3879void InputDispatcher::TouchState::removeOutsideTouchWindows() {
3880 for (size_t i = 0 ; i < windows.size(); ) {
3881 if (windows[i].targetFlags & InputTarget::FLAG_OUTSIDE) {
3882 windows.removeAt(i);
3883 } else {
3884 i += 1;
3885 }
3886 }
3887}
3888
3889const InputWindow* InputDispatcher::TouchState::getFirstForegroundWindow() {
3890 for (size_t i = 0; i < windows.size(); i++) {
3891 if (windows[i].targetFlags & InputTarget::FLAG_FOREGROUND) {
3892 return windows[i].window;
3893 }
3894 }
3895 return NULL;
3896}
3897
3898
Jeff Brown46b9ac02010-04-22 18:58:52 -07003899// --- InputDispatcherThread ---
3900
3901InputDispatcherThread::InputDispatcherThread(const sp<InputDispatcherInterface>& dispatcher) :
3902 Thread(/*canCallJava*/ true), mDispatcher(dispatcher) {
3903}
3904
3905InputDispatcherThread::~InputDispatcherThread() {
3906}
3907
3908bool InputDispatcherThread::threadLoop() {
3909 mDispatcher->dispatchOnce();
3910 return true;
3911}
3912
3913} // namespace android