blob: 7ac2f13440880a67076fb1c82d37cae2a9b609a6 [file] [log] [blame]
Jeff Brownb4ff35d2011-01-02 16:37:43 -08001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070017#define LOG_TAG "InputDispatcher"
18
19//#define LOG_NDEBUG 0
20
21// Log detailed debug messages about each inbound event notification to the dispatcher.
Jeff Brown349703e2010-06-22 01:27:15 -070022#define DEBUG_INBOUND_EVENT_DETAILS 0
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070023
24// Log detailed debug messages about each outbound event processed by the dispatcher.
Jeff Brown349703e2010-06-22 01:27:15 -070025#define DEBUG_OUTBOUND_EVENT_DETAILS 0
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070026
27// Log debug messages about batching.
Jeff Brown349703e2010-06-22 01:27:15 -070028#define DEBUG_BATCHING 0
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070029
30// Log debug messages about the dispatch cycle.
Jeff Brown349703e2010-06-22 01:27:15 -070031#define DEBUG_DISPATCH_CYCLE 0
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070032
Jeff Brown9c3cda02010-06-15 01:31:58 -070033// Log debug messages about registrations.
Jeff Brown349703e2010-06-22 01:27:15 -070034#define DEBUG_REGISTRATION 0
Jeff Brown9c3cda02010-06-15 01:31:58 -070035
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070036// Log debug messages about performance statistics.
Jeff Brown349703e2010-06-22 01:27:15 -070037#define DEBUG_PERFORMANCE_STATISTICS 0
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070038
Jeff Brown7fbdc842010-06-17 20:52:56 -070039// Log debug messages about input event injection.
Jeff Brown349703e2010-06-22 01:27:15 -070040#define DEBUG_INJECTION 0
Jeff Brown7fbdc842010-06-17 20:52:56 -070041
Jeff Brownae9fc032010-08-18 15:51:08 -070042// Log debug messages about input event throttling.
43#define DEBUG_THROTTLING 0
44
Jeff Brownb88102f2010-09-08 11:49:43 -070045// Log debug messages about input focus tracking.
46#define DEBUG_FOCUS 0
47
48// Log debug messages about the app switch latency optimization.
49#define DEBUG_APP_SWITCH 0
50
Jeff Brownb4ff35d2011-01-02 16:37:43 -080051#include "InputDispatcher.h"
52
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070053#include <cutils/log.h>
Jeff Brownb88102f2010-09-08 11:49:43 -070054#include <ui/PowerManager.h>
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070055
56#include <stddef.h>
57#include <unistd.h>
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070058#include <errno.h>
59#include <limits.h>
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070060
Jeff Brownf2f487182010-10-01 17:46:21 -070061#define INDENT " "
62#define INDENT2 " "
63
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070064namespace android {
65
Jeff Brownb88102f2010-09-08 11:49:43 -070066// Default input dispatching timeout if there is no focused application or paused window
67// from which to determine an appropriate dispatching timeout.
68const nsecs_t DEFAULT_INPUT_DISPATCHING_TIMEOUT = 5000 * 1000000LL; // 5 sec
69
70// Amount of time to allow for all pending events to be processed when an app switch
71// key is on the way. This is used to preempt input dispatch and drop input events
72// when an application takes too long to respond and the user has pressed an app switch key.
73const nsecs_t APP_SWITCH_TIMEOUT = 500 * 1000000LL; // 0.5sec
74
Jeff Brown928e0542011-01-10 11:17:36 -080075// Amount of time to allow for an event to be dispatched (measured since its eventTime)
76// before considering it stale and dropping it.
77const nsecs_t STALE_EVENT_TIMEOUT = 10000 * 1000000LL; // 10sec
78
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070079
Jeff Brown7fbdc842010-06-17 20:52:56 -070080static inline nsecs_t now() {
81 return systemTime(SYSTEM_TIME_MONOTONIC);
82}
83
Jeff Brownb88102f2010-09-08 11:49:43 -070084static inline const char* toString(bool value) {
85 return value ? "true" : "false";
86}
87
Jeff Brown01ce2e92010-09-26 22:20:12 -070088static inline int32_t getMotionEventActionPointerIndex(int32_t action) {
89 return (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK)
90 >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
91}
92
93static bool isValidKeyAction(int32_t action) {
94 switch (action) {
95 case AKEY_EVENT_ACTION_DOWN:
96 case AKEY_EVENT_ACTION_UP:
97 return true;
98 default:
99 return false;
100 }
101}
102
103static bool validateKeyEvent(int32_t action) {
104 if (! isValidKeyAction(action)) {
105 LOGE("Key event has invalid action code 0x%x", action);
106 return false;
107 }
108 return true;
109}
110
Jeff Brownb6997262010-10-08 22:31:17 -0700111static bool isValidMotionAction(int32_t action, size_t pointerCount) {
Jeff Brown01ce2e92010-09-26 22:20:12 -0700112 switch (action & AMOTION_EVENT_ACTION_MASK) {
113 case AMOTION_EVENT_ACTION_DOWN:
114 case AMOTION_EVENT_ACTION_UP:
115 case AMOTION_EVENT_ACTION_CANCEL:
116 case AMOTION_EVENT_ACTION_MOVE:
Jeff Brown01ce2e92010-09-26 22:20:12 -0700117 case AMOTION_EVENT_ACTION_OUTSIDE:
Jeff Browncc0c1592011-02-19 05:07:28 -0800118 case AMOTION_EVENT_ACTION_HOVER_MOVE:
Jeff Brown33bbfd22011-02-24 20:55:35 -0800119 case AMOTION_EVENT_ACTION_SCROLL:
Jeff Brown01ce2e92010-09-26 22:20:12 -0700120 return true;
Jeff Brownb6997262010-10-08 22:31:17 -0700121 case AMOTION_EVENT_ACTION_POINTER_DOWN:
122 case AMOTION_EVENT_ACTION_POINTER_UP: {
123 int32_t index = getMotionEventActionPointerIndex(action);
124 return index >= 0 && size_t(index) < pointerCount;
125 }
Jeff Brown01ce2e92010-09-26 22:20:12 -0700126 default:
127 return false;
128 }
129}
130
131static bool validateMotionEvent(int32_t action, size_t pointerCount,
132 const int32_t* pointerIds) {
Jeff Brownb6997262010-10-08 22:31:17 -0700133 if (! isValidMotionAction(action, pointerCount)) {
Jeff Brown01ce2e92010-09-26 22:20:12 -0700134 LOGE("Motion event has invalid action code 0x%x", action);
135 return false;
136 }
137 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
138 LOGE("Motion event has invalid pointer count %d; value must be between 1 and %d.",
139 pointerCount, MAX_POINTERS);
140 return false;
141 }
Jeff Brownc3db8582010-10-20 15:33:38 -0700142 BitSet32 pointerIdBits;
Jeff Brown01ce2e92010-09-26 22:20:12 -0700143 for (size_t i = 0; i < pointerCount; i++) {
Jeff Brownc3db8582010-10-20 15:33:38 -0700144 int32_t id = pointerIds[i];
145 if (id < 0 || id > MAX_POINTER_ID) {
Jeff Brown01ce2e92010-09-26 22:20:12 -0700146 LOGE("Motion event has invalid pointer id %d; value must be between 0 and %d",
Jeff Brownc3db8582010-10-20 15:33:38 -0700147 id, MAX_POINTER_ID);
Jeff Brown01ce2e92010-09-26 22:20:12 -0700148 return false;
149 }
Jeff Brownc3db8582010-10-20 15:33:38 -0700150 if (pointerIdBits.hasBit(id)) {
151 LOGE("Motion event has duplicate pointer id %d", id);
152 return false;
153 }
154 pointerIdBits.markBit(id);
Jeff Brown01ce2e92010-09-26 22:20:12 -0700155 }
156 return true;
157}
158
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400159static void scalePointerCoords(const PointerCoords* inCoords, size_t count, float scaleFactor,
160 PointerCoords* outCoords) {
161 for (size_t i = 0; i < count; i++) {
162 outCoords[i] = inCoords[i];
163 outCoords[i].scale(scaleFactor);
164 }
165}
166
Jeff Brownfbf09772011-01-16 14:06:57 -0800167static void dumpRegion(String8& dump, const SkRegion& region) {
168 if (region.isEmpty()) {
169 dump.append("<empty>");
170 return;
171 }
172
173 bool first = true;
174 for (SkRegion::Iterator it(region); !it.done(); it.next()) {
175 if (first) {
176 first = false;
177 } else {
178 dump.append("|");
179 }
180 const SkIRect& rect = it.rect();
181 dump.appendFormat("[%d,%d][%d,%d]", rect.fLeft, rect.fTop, rect.fRight, rect.fBottom);
182 }
183}
184
Jeff Brownb88102f2010-09-08 11:49:43 -0700185
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700186// --- InputDispatcher ---
187
Jeff Brown9c3cda02010-06-15 01:31:58 -0700188InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy) :
Jeff Brownb88102f2010-09-08 11:49:43 -0700189 mPolicy(policy),
Jeff Brown928e0542011-01-10 11:17:36 -0800190 mPendingEvent(NULL), mAppSwitchSawKeyDown(false), mAppSwitchDueTime(LONG_LONG_MAX),
191 mNextUnblockedEvent(NULL),
Jeff Brownb88102f2010-09-08 11:49:43 -0700192 mDispatchEnabled(true), mDispatchFrozen(false),
Jeff Brown01ce2e92010-09-26 22:20:12 -0700193 mFocusedWindow(NULL),
Jeff Brownb88102f2010-09-08 11:49:43 -0700194 mFocusedApplication(NULL),
195 mCurrentInputTargetsValid(false),
196 mInputTargetWaitCause(INPUT_TARGET_WAIT_CAUSE_NONE) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -0700197 mLooper = new Looper(false);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700198
Jeff Brownb88102f2010-09-08 11:49:43 -0700199 mInboundQueue.headSentinel.refCount = -1;
200 mInboundQueue.headSentinel.type = EventEntry::TYPE_SENTINEL;
201 mInboundQueue.headSentinel.eventTime = LONG_LONG_MIN;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700202
Jeff Brownb88102f2010-09-08 11:49:43 -0700203 mInboundQueue.tailSentinel.refCount = -1;
204 mInboundQueue.tailSentinel.type = EventEntry::TYPE_SENTINEL;
205 mInboundQueue.tailSentinel.eventTime = LONG_LONG_MAX;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700206
207 mKeyRepeatState.lastKeyEntry = NULL;
Jeff Brown9c3cda02010-06-15 01:31:58 -0700208
Jeff Brownae9fc032010-08-18 15:51:08 -0700209 int32_t maxEventsPerSecond = policy->getMaxEventsPerSecond();
210 mThrottleState.minTimeBetweenEvents = 1000000000LL / maxEventsPerSecond;
211 mThrottleState.lastDeviceId = -1;
212
213#if DEBUG_THROTTLING
214 mThrottleState.originalSampleCount = 0;
215 LOGD("Throttling - Max events per second = %d", maxEventsPerSecond);
216#endif
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700217}
218
219InputDispatcher::~InputDispatcher() {
Jeff Brownb88102f2010-09-08 11:49:43 -0700220 { // acquire lock
221 AutoMutex _l(mLock);
222
223 resetKeyRepeatLocked();
Jeff Brown54a18252010-09-16 14:07:33 -0700224 releasePendingEventLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -0700225 drainInboundQueueLocked();
226 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700227
228 while (mConnectionsByReceiveFd.size() != 0) {
229 unregisterInputChannel(mConnectionsByReceiveFd.valueAt(0)->inputChannel);
230 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700231}
232
233void InputDispatcher::dispatchOnce() {
Jeff Brown9c3cda02010-06-15 01:31:58 -0700234 nsecs_t keyRepeatTimeout = mPolicy->getKeyRepeatTimeout();
Jeff Brownb21fb102010-09-07 10:44:57 -0700235 nsecs_t keyRepeatDelay = mPolicy->getKeyRepeatDelay();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700236
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700237 nsecs_t nextWakeupTime = LONG_LONG_MAX;
238 { // acquire lock
239 AutoMutex _l(mLock);
Jeff Brownb88102f2010-09-08 11:49:43 -0700240 dispatchOnceInnerLocked(keyRepeatTimeout, keyRepeatDelay, & nextWakeupTime);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700241
Jeff Brownb88102f2010-09-08 11:49:43 -0700242 if (runCommandsLockedInterruptible()) {
243 nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700244 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700245 } // release lock
246
Jeff Brownb88102f2010-09-08 11:49:43 -0700247 // Wait for callback or timeout or wake. (make sure we round up, not down)
248 nsecs_t currentTime = now();
Jeff Brown68d60752011-03-17 01:34:19 -0700249 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
Jeff Brown4fe6c3e2010-09-13 23:17:30 -0700250 mLooper->pollOnce(timeoutMillis);
Jeff Brownb88102f2010-09-08 11:49:43 -0700251}
252
253void InputDispatcher::dispatchOnceInnerLocked(nsecs_t keyRepeatTimeout,
254 nsecs_t keyRepeatDelay, nsecs_t* nextWakeupTime) {
255 nsecs_t currentTime = now();
256
257 // Reset the key repeat timer whenever we disallow key events, even if the next event
258 // is not a key. This is to ensure that we abort a key repeat if the device is just coming
259 // out of sleep.
260 if (keyRepeatTimeout < 0) {
261 resetKeyRepeatLocked();
262 }
263
Jeff Brownb88102f2010-09-08 11:49:43 -0700264 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
265 if (mDispatchFrozen) {
266#if DEBUG_FOCUS
267 LOGD("Dispatch frozen. Waiting some more.");
268#endif
269 return;
270 }
271
272 // Optimize latency of app switches.
273 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
274 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
275 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
276 if (mAppSwitchDueTime < *nextWakeupTime) {
277 *nextWakeupTime = mAppSwitchDueTime;
278 }
279
Jeff Brownb88102f2010-09-08 11:49:43 -0700280 // Ready to start a new event.
281 // If we don't already have a pending event, go grab one.
282 if (! mPendingEvent) {
283 if (mInboundQueue.isEmpty()) {
284 if (isAppSwitchDue) {
285 // The inbound queue is empty so the app switch key we were waiting
286 // for will never arrive. Stop waiting for it.
287 resetPendingAppSwitchLocked(false);
288 isAppSwitchDue = false;
289 }
290
291 // Synthesize a key repeat if appropriate.
292 if (mKeyRepeatState.lastKeyEntry) {
293 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
294 mPendingEvent = synthesizeKeyRepeatLocked(currentTime, keyRepeatDelay);
295 } else {
296 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
297 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
298 }
299 }
300 }
301 if (! mPendingEvent) {
302 return;
303 }
304 } else {
305 // Inbound queue has at least one entry.
306 EventEntry* entry = mInboundQueue.headSentinel.next;
307
308 // Throttle the entry if it is a move event and there are no
309 // other events behind it in the queue. Due to movement batching, additional
310 // samples may be appended to this event by the time the throttling timeout
311 // expires.
312 // TODO Make this smarter and consider throttling per device independently.
Jeff Brownb6997262010-10-08 22:31:17 -0700313 if (entry->type == EventEntry::TYPE_MOTION
314 && !isAppSwitchDue
315 && mDispatchEnabled
316 && (entry->policyFlags & POLICY_FLAG_PASS_TO_USER)
317 && !entry->isInjected()) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700318 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
319 int32_t deviceId = motionEntry->deviceId;
320 uint32_t source = motionEntry->source;
321 if (! isAppSwitchDue
322 && motionEntry->next == & mInboundQueue.tailSentinel // exactly one event
Jeff Browncc0c1592011-02-19 05:07:28 -0800323 && (motionEntry->action == AMOTION_EVENT_ACTION_MOVE
324 || motionEntry->action == AMOTION_EVENT_ACTION_HOVER_MOVE)
Jeff Brownb88102f2010-09-08 11:49:43 -0700325 && deviceId == mThrottleState.lastDeviceId
326 && source == mThrottleState.lastSource) {
327 nsecs_t nextTime = mThrottleState.lastEventTime
328 + mThrottleState.minTimeBetweenEvents;
329 if (currentTime < nextTime) {
330 // Throttle it!
331#if DEBUG_THROTTLING
332 LOGD("Throttling - Delaying motion event for "
Jeff Brown90655042010-12-02 13:50:46 -0800333 "device %d, source 0x%08x by up to %0.3fms.",
Jeff Brownb88102f2010-09-08 11:49:43 -0700334 deviceId, source, (nextTime - currentTime) * 0.000001);
335#endif
336 if (nextTime < *nextWakeupTime) {
337 *nextWakeupTime = nextTime;
338 }
339 if (mThrottleState.originalSampleCount == 0) {
340 mThrottleState.originalSampleCount =
341 motionEntry->countSamples();
342 }
343 return;
344 }
345 }
346
347#if DEBUG_THROTTLING
348 if (mThrottleState.originalSampleCount != 0) {
349 uint32_t count = motionEntry->countSamples();
350 LOGD("Throttling - Motion event sample count grew by %d from %d to %d.",
351 count - mThrottleState.originalSampleCount,
352 mThrottleState.originalSampleCount, count);
353 mThrottleState.originalSampleCount = 0;
354 }
355#endif
356
makarand.karvekarf634ded2011-03-02 15:41:03 -0600357 mThrottleState.lastEventTime = currentTime;
Jeff Brownb88102f2010-09-08 11:49:43 -0700358 mThrottleState.lastDeviceId = deviceId;
359 mThrottleState.lastSource = source;
360 }
361
362 mInboundQueue.dequeue(entry);
363 mPendingEvent = entry;
364 }
Jeff Browne2fe69e2010-10-18 13:21:23 -0700365
366 // Poke user activity for this event.
367 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
368 pokeUserActivityLocked(mPendingEvent);
369 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700370 }
371
372 // Now we have an event to dispatch.
Jeff Brown928e0542011-01-10 11:17:36 -0800373 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Jeff Brownb88102f2010-09-08 11:49:43 -0700374 assert(mPendingEvent != NULL);
Jeff Brown54a18252010-09-16 14:07:33 -0700375 bool done = false;
Jeff Brownb6997262010-10-08 22:31:17 -0700376 DropReason dropReason = DROP_REASON_NOT_DROPPED;
377 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
378 dropReason = DROP_REASON_POLICY;
379 } else if (!mDispatchEnabled) {
380 dropReason = DROP_REASON_DISABLED;
381 }
Jeff Brown928e0542011-01-10 11:17:36 -0800382
383 if (mNextUnblockedEvent == mPendingEvent) {
384 mNextUnblockedEvent = NULL;
385 }
386
Jeff Brownb88102f2010-09-08 11:49:43 -0700387 switch (mPendingEvent->type) {
388 case EventEntry::TYPE_CONFIGURATION_CHANGED: {
389 ConfigurationChangedEntry* typedEntry =
390 static_cast<ConfigurationChangedEntry*>(mPendingEvent);
Jeff Brown54a18252010-09-16 14:07:33 -0700391 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Jeff Brownb6997262010-10-08 22:31:17 -0700392 dropReason = DROP_REASON_NOT_DROPPED; // configuration changes are never dropped
Jeff Brownb88102f2010-09-08 11:49:43 -0700393 break;
394 }
395
396 case EventEntry::TYPE_KEY: {
397 KeyEntry* typedEntry = static_cast<KeyEntry*>(mPendingEvent);
Jeff Brownb6997262010-10-08 22:31:17 -0700398 if (isAppSwitchDue) {
399 if (isAppSwitchKeyEventLocked(typedEntry)) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700400 resetPendingAppSwitchLocked(true);
Jeff Brownb6997262010-10-08 22:31:17 -0700401 isAppSwitchDue = false;
402 } else if (dropReason == DROP_REASON_NOT_DROPPED) {
403 dropReason = DROP_REASON_APP_SWITCH;
Jeff Brownb88102f2010-09-08 11:49:43 -0700404 }
405 }
Jeff Brown928e0542011-01-10 11:17:36 -0800406 if (dropReason == DROP_REASON_NOT_DROPPED
407 && isStaleEventLocked(currentTime, typedEntry)) {
408 dropReason = DROP_REASON_STALE;
409 }
410 if (dropReason == DROP_REASON_NOT_DROPPED && mNextUnblockedEvent) {
411 dropReason = DROP_REASON_BLOCKED;
412 }
Jeff Brownb6997262010-10-08 22:31:17 -0700413 done = dispatchKeyLocked(currentTime, typedEntry, keyRepeatTimeout,
Jeff Browne20c9e02010-10-11 14:20:19 -0700414 &dropReason, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700415 break;
416 }
417
418 case EventEntry::TYPE_MOTION: {
419 MotionEntry* typedEntry = static_cast<MotionEntry*>(mPendingEvent);
Jeff Brownb6997262010-10-08 22:31:17 -0700420 if (dropReason == DROP_REASON_NOT_DROPPED && isAppSwitchDue) {
421 dropReason = DROP_REASON_APP_SWITCH;
Jeff Brownb88102f2010-09-08 11:49:43 -0700422 }
Jeff Brown928e0542011-01-10 11:17:36 -0800423 if (dropReason == DROP_REASON_NOT_DROPPED
424 && isStaleEventLocked(currentTime, typedEntry)) {
425 dropReason = DROP_REASON_STALE;
426 }
427 if (dropReason == DROP_REASON_NOT_DROPPED && mNextUnblockedEvent) {
428 dropReason = DROP_REASON_BLOCKED;
429 }
Jeff Brownb6997262010-10-08 22:31:17 -0700430 done = dispatchMotionLocked(currentTime, typedEntry,
Jeff Browne20c9e02010-10-11 14:20:19 -0700431 &dropReason, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700432 break;
433 }
434
435 default:
436 assert(false);
Jeff Brownb88102f2010-09-08 11:49:43 -0700437 break;
438 }
439
Jeff Brown54a18252010-09-16 14:07:33 -0700440 if (done) {
Jeff Brownb6997262010-10-08 22:31:17 -0700441 if (dropReason != DROP_REASON_NOT_DROPPED) {
442 dropInboundEventLocked(mPendingEvent, dropReason);
443 }
444
Jeff Brown54a18252010-09-16 14:07:33 -0700445 releasePendingEventLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -0700446 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
447 }
448}
449
450bool InputDispatcher::enqueueInboundEventLocked(EventEntry* entry) {
451 bool needWake = mInboundQueue.isEmpty();
452 mInboundQueue.enqueueAtTail(entry);
453
454 switch (entry->type) {
Jeff Brownb6997262010-10-08 22:31:17 -0700455 case EventEntry::TYPE_KEY: {
Jeff Brown928e0542011-01-10 11:17:36 -0800456 // Optimize app switch latency.
457 // If the application takes too long to catch up then we drop all events preceding
458 // the app switch key.
Jeff Brownb6997262010-10-08 22:31:17 -0700459 KeyEntry* keyEntry = static_cast<KeyEntry*>(entry);
460 if (isAppSwitchKeyEventLocked(keyEntry)) {
461 if (keyEntry->action == AKEY_EVENT_ACTION_DOWN) {
462 mAppSwitchSawKeyDown = true;
463 } else if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
464 if (mAppSwitchSawKeyDown) {
465#if DEBUG_APP_SWITCH
466 LOGD("App switch is pending!");
467#endif
468 mAppSwitchDueTime = keyEntry->eventTime + APP_SWITCH_TIMEOUT;
469 mAppSwitchSawKeyDown = false;
470 needWake = true;
471 }
472 }
473 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700474 break;
475 }
Jeff Brown928e0542011-01-10 11:17:36 -0800476
477 case EventEntry::TYPE_MOTION: {
478 // Optimize case where the current application is unresponsive and the user
479 // decides to touch a window in a different application.
480 // If the application takes too long to catch up then we drop all events preceding
481 // the touch into the other window.
482 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
Jeff Brown33bbfd22011-02-24 20:55:35 -0800483 if (motionEntry->action == AMOTION_EVENT_ACTION_DOWN
Jeff Brown928e0542011-01-10 11:17:36 -0800484 && (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER)
485 && mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY
486 && mInputTargetWaitApplication != NULL) {
Jeff Brown91c69ab2011-02-14 17:03:18 -0800487 int32_t x = int32_t(motionEntry->firstSample.pointerCoords[0].
Jeff Brownebbd5d12011-02-17 13:01:34 -0800488 getAxisValue(AMOTION_EVENT_AXIS_X));
Jeff Brown91c69ab2011-02-14 17:03:18 -0800489 int32_t y = int32_t(motionEntry->firstSample.pointerCoords[0].
Jeff Brownebbd5d12011-02-17 13:01:34 -0800490 getAxisValue(AMOTION_EVENT_AXIS_Y));
Jeff Brown928e0542011-01-10 11:17:36 -0800491 const InputWindow* touchedWindow = findTouchedWindowAtLocked(x, y);
492 if (touchedWindow
493 && touchedWindow->inputWindowHandle != NULL
494 && touchedWindow->inputWindowHandle->getInputApplicationHandle()
495 != mInputTargetWaitApplication) {
496 // User touched a different application than the one we are waiting on.
497 // Flag the event, and start pruning the input queue.
498 mNextUnblockedEvent = motionEntry;
499 needWake = true;
500 }
501 }
502 break;
503 }
Jeff Brownb6997262010-10-08 22:31:17 -0700504 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700505
506 return needWake;
507}
508
Jeff Brown928e0542011-01-10 11:17:36 -0800509const InputWindow* InputDispatcher::findTouchedWindowAtLocked(int32_t x, int32_t y) {
510 // Traverse windows from front to back to find touched window.
511 size_t numWindows = mWindows.size();
512 for (size_t i = 0; i < numWindows; i++) {
513 const InputWindow* window = & mWindows.editItemAt(i);
514 int32_t flags = window->layoutParamsFlags;
515
516 if (window->visible) {
517 if (!(flags & InputWindow::FLAG_NOT_TOUCHABLE)) {
518 bool isTouchModal = (flags & (InputWindow::FLAG_NOT_FOCUSABLE
519 | InputWindow::FLAG_NOT_TOUCH_MODAL)) == 0;
Jeff Brownfbf09772011-01-16 14:06:57 -0800520 if (isTouchModal || window->touchableRegionContainsPoint(x, y)) {
Jeff Brown928e0542011-01-10 11:17:36 -0800521 // Found window.
522 return window;
523 }
524 }
525 }
526
527 if (flags & InputWindow::FLAG_SYSTEM_ERROR) {
528 // Error window is on top but not visible, so touch is dropped.
529 return NULL;
530 }
531 }
532 return NULL;
533}
534
Jeff Brownb6997262010-10-08 22:31:17 -0700535void InputDispatcher::dropInboundEventLocked(EventEntry* entry, DropReason dropReason) {
536 const char* reason;
537 switch (dropReason) {
538 case DROP_REASON_POLICY:
Jeff Browne20c9e02010-10-11 14:20:19 -0700539#if DEBUG_INBOUND_EVENT_DETAILS
Jeff Brown3122e442010-10-11 23:32:49 -0700540 LOGD("Dropped event because policy consumed it.");
Jeff Browne20c9e02010-10-11 14:20:19 -0700541#endif
Jeff Brown3122e442010-10-11 23:32:49 -0700542 reason = "inbound event was dropped because the policy consumed it";
Jeff Brownb6997262010-10-08 22:31:17 -0700543 break;
544 case DROP_REASON_DISABLED:
545 LOGI("Dropped event because input dispatch is disabled.");
546 reason = "inbound event was dropped because input dispatch is disabled";
547 break;
548 case DROP_REASON_APP_SWITCH:
549 LOGI("Dropped event because of pending overdue app switch.");
550 reason = "inbound event was dropped because of pending overdue app switch";
551 break;
Jeff Brown928e0542011-01-10 11:17:36 -0800552 case DROP_REASON_BLOCKED:
553 LOGI("Dropped event because the current application is not responding and the user "
554 "has started interating with a different application.");
555 reason = "inbound event was dropped because the current application is not responding "
556 "and the user has started interating with a different application";
557 break;
558 case DROP_REASON_STALE:
559 LOGI("Dropped event because it is stale.");
560 reason = "inbound event was dropped because it is stale";
561 break;
Jeff Brownb6997262010-10-08 22:31:17 -0700562 default:
563 assert(false);
564 return;
565 }
566
567 switch (entry->type) {
Jeff Brown524ee642011-03-29 15:11:34 -0700568 case EventEntry::TYPE_KEY: {
569 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
570 synthesizeCancelationEventsForAllConnectionsLocked(options);
Jeff Brownb6997262010-10-08 22:31:17 -0700571 break;
Jeff Brown524ee642011-03-29 15:11:34 -0700572 }
Jeff Brownb6997262010-10-08 22:31:17 -0700573 case EventEntry::TYPE_MOTION: {
574 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
575 if (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) {
Jeff Brown524ee642011-03-29 15:11:34 -0700576 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
577 synthesizeCancelationEventsForAllConnectionsLocked(options);
Jeff Brownb6997262010-10-08 22:31:17 -0700578 } else {
Jeff Brown524ee642011-03-29 15:11:34 -0700579 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
580 synthesizeCancelationEventsForAllConnectionsLocked(options);
Jeff Brownb6997262010-10-08 22:31:17 -0700581 }
582 break;
583 }
584 }
585}
586
587bool InputDispatcher::isAppSwitchKeyCode(int32_t keyCode) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700588 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL;
589}
590
Jeff Brownb6997262010-10-08 22:31:17 -0700591bool InputDispatcher::isAppSwitchKeyEventLocked(KeyEntry* keyEntry) {
592 return ! (keyEntry->flags & AKEY_EVENT_FLAG_CANCELED)
593 && isAppSwitchKeyCode(keyEntry->keyCode)
Jeff Browne20c9e02010-10-11 14:20:19 -0700594 && (keyEntry->policyFlags & POLICY_FLAG_TRUSTED)
Jeff Brownb6997262010-10-08 22:31:17 -0700595 && (keyEntry->policyFlags & POLICY_FLAG_PASS_TO_USER);
596}
597
Jeff Brownb88102f2010-09-08 11:49:43 -0700598bool InputDispatcher::isAppSwitchPendingLocked() {
599 return mAppSwitchDueTime != LONG_LONG_MAX;
600}
601
Jeff Brownb88102f2010-09-08 11:49:43 -0700602void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
603 mAppSwitchDueTime = LONG_LONG_MAX;
604
605#if DEBUG_APP_SWITCH
606 if (handled) {
607 LOGD("App switch has arrived.");
608 } else {
609 LOGD("App switch was abandoned.");
610 }
611#endif
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700612}
613
Jeff Brown928e0542011-01-10 11:17:36 -0800614bool InputDispatcher::isStaleEventLocked(nsecs_t currentTime, EventEntry* entry) {
615 return currentTime - entry->eventTime >= STALE_EVENT_TIMEOUT;
616}
617
Jeff Brown9c3cda02010-06-15 01:31:58 -0700618bool InputDispatcher::runCommandsLockedInterruptible() {
619 if (mCommandQueue.isEmpty()) {
620 return false;
621 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700622
Jeff Brown9c3cda02010-06-15 01:31:58 -0700623 do {
624 CommandEntry* commandEntry = mCommandQueue.dequeueAtHead();
625
626 Command command = commandEntry->command;
627 (this->*command)(commandEntry); // commands are implicitly 'LockedInterruptible'
628
Jeff Brown7fbdc842010-06-17 20:52:56 -0700629 commandEntry->connection.clear();
Jeff Brown9c3cda02010-06-15 01:31:58 -0700630 mAllocator.releaseCommandEntry(commandEntry);
631 } while (! mCommandQueue.isEmpty());
632 return true;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700633}
634
Jeff Brown9c3cda02010-06-15 01:31:58 -0700635InputDispatcher::CommandEntry* InputDispatcher::postCommandLocked(Command command) {
636 CommandEntry* commandEntry = mAllocator.obtainCommandEntry(command);
637 mCommandQueue.enqueueAtTail(commandEntry);
638 return commandEntry;
639}
640
Jeff Brownb88102f2010-09-08 11:49:43 -0700641void InputDispatcher::drainInboundQueueLocked() {
642 while (! mInboundQueue.isEmpty()) {
643 EventEntry* entry = mInboundQueue.dequeueAtHead();
Jeff Brown54a18252010-09-16 14:07:33 -0700644 releaseInboundEventLocked(entry);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700645 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700646}
647
Jeff Brown54a18252010-09-16 14:07:33 -0700648void InputDispatcher::releasePendingEventLocked() {
Jeff Brownb88102f2010-09-08 11:49:43 -0700649 if (mPendingEvent) {
Jeff Brown54a18252010-09-16 14:07:33 -0700650 releaseInboundEventLocked(mPendingEvent);
Jeff Brownb88102f2010-09-08 11:49:43 -0700651 mPendingEvent = NULL;
652 }
653}
654
Jeff Brown54a18252010-09-16 14:07:33 -0700655void InputDispatcher::releaseInboundEventLocked(EventEntry* entry) {
Jeff Brown01ce2e92010-09-26 22:20:12 -0700656 InjectionState* injectionState = entry->injectionState;
657 if (injectionState && injectionState->injectionResult == INPUT_EVENT_INJECTION_PENDING) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700658#if DEBUG_DISPATCH_CYCLE
Jeff Brown01ce2e92010-09-26 22:20:12 -0700659 LOGD("Injected inbound event was dropped.");
Jeff Brownb88102f2010-09-08 11:49:43 -0700660#endif
661 setInjectionResultLocked(entry, INPUT_EVENT_INJECTION_FAILED);
662 }
663 mAllocator.releaseEventEntry(entry);
664}
665
Jeff Brownb88102f2010-09-08 11:49:43 -0700666void InputDispatcher::resetKeyRepeatLocked() {
667 if (mKeyRepeatState.lastKeyEntry) {
668 mAllocator.releaseKeyEntry(mKeyRepeatState.lastKeyEntry);
669 mKeyRepeatState.lastKeyEntry = NULL;
670 }
671}
672
673InputDispatcher::KeyEntry* InputDispatcher::synthesizeKeyRepeatLocked(
Jeff Brownb21fb102010-09-07 10:44:57 -0700674 nsecs_t currentTime, nsecs_t keyRepeatDelay) {
Jeff Brown349703e2010-06-22 01:27:15 -0700675 KeyEntry* entry = mKeyRepeatState.lastKeyEntry;
676
Jeff Brown349703e2010-06-22 01:27:15 -0700677 // Reuse the repeated key entry if it is otherwise unreferenced.
Jeff Browne20c9e02010-10-11 14:20:19 -0700678 uint32_t policyFlags = (entry->policyFlags & POLICY_FLAG_RAW_MASK)
679 | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700680 if (entry->refCount == 1) {
Jeff Brown01ce2e92010-09-26 22:20:12 -0700681 mAllocator.recycleKeyEntry(entry);
Jeff Brown7fbdc842010-06-17 20:52:56 -0700682 entry->eventTime = currentTime;
Jeff Brown7fbdc842010-06-17 20:52:56 -0700683 entry->policyFlags = policyFlags;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700684 entry->repeatCount += 1;
685 } else {
Jeff Brown7fbdc842010-06-17 20:52:56 -0700686 KeyEntry* newEntry = mAllocator.obtainKeyEntry(currentTime,
Jeff Brownc5ed5912010-07-14 18:48:53 -0700687 entry->deviceId, entry->source, policyFlags,
Jeff Brown7fbdc842010-06-17 20:52:56 -0700688 entry->action, entry->flags, entry->keyCode, entry->scanCode,
Jeff Brown00fa7bd2010-07-02 15:37:36 -0700689 entry->metaState, entry->repeatCount + 1, entry->downTime);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700690
691 mKeyRepeatState.lastKeyEntry = newEntry;
692 mAllocator.releaseKeyEntry(entry);
693
694 entry = newEntry;
695 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700696 entry->syntheticRepeat = true;
697
698 // Increment reference count since we keep a reference to the event in
699 // mKeyRepeatState.lastKeyEntry in addition to the one we return.
700 entry->refCount += 1;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700701
Jeff Brownb21fb102010-09-07 10:44:57 -0700702 mKeyRepeatState.nextRepeatTime = currentTime + keyRepeatDelay;
Jeff Brownb88102f2010-09-08 11:49:43 -0700703 return entry;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700704}
705
Jeff Brownb88102f2010-09-08 11:49:43 -0700706bool InputDispatcher::dispatchConfigurationChangedLocked(
707 nsecs_t currentTime, ConfigurationChangedEntry* entry) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700708#if DEBUG_OUTBOUND_EVENT_DETAILS
Jeff Brownb88102f2010-09-08 11:49:43 -0700709 LOGD("dispatchConfigurationChanged - eventTime=%lld", entry->eventTime);
710#endif
711
712 // Reset key repeating in case a keyboard device was added or removed or something.
713 resetKeyRepeatLocked();
714
715 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
716 CommandEntry* commandEntry = postCommandLocked(
717 & InputDispatcher::doNotifyConfigurationChangedInterruptible);
718 commandEntry->eventTime = entry->eventTime;
719 return true;
720}
721
722bool InputDispatcher::dispatchKeyLocked(
723 nsecs_t currentTime, KeyEntry* entry, nsecs_t keyRepeatTimeout,
Jeff Browne20c9e02010-10-11 14:20:19 -0700724 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Jeff Browne46a0a42010-11-02 17:58:22 -0700725 // Preprocessing.
726 if (! entry->dispatchInProgress) {
727 if (entry->repeatCount == 0
728 && entry->action == AKEY_EVENT_ACTION_DOWN
729 && (entry->policyFlags & POLICY_FLAG_TRUSTED)
730 && !entry->isInjected()) {
731 if (mKeyRepeatState.lastKeyEntry
732 && mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode) {
733 // We have seen two identical key downs in a row which indicates that the device
734 // driver is automatically generating key repeats itself. We take note of the
735 // repeat here, but we disable our own next key repeat timer since it is clear that
736 // we will not need to synthesize key repeats ourselves.
737 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
738 resetKeyRepeatLocked();
739 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
740 } else {
741 // Not a repeat. Save key down state in case we do see a repeat later.
742 resetKeyRepeatLocked();
743 mKeyRepeatState.nextRepeatTime = entry->eventTime + keyRepeatTimeout;
744 }
745 mKeyRepeatState.lastKeyEntry = entry;
746 entry->refCount += 1;
747 } else if (! entry->syntheticRepeat) {
748 resetKeyRepeatLocked();
749 }
750
Jeff Browne2e01262011-03-02 20:34:30 -0800751 if (entry->repeatCount == 1) {
752 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
753 } else {
754 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
755 }
756
Jeff Browne46a0a42010-11-02 17:58:22 -0700757 entry->dispatchInProgress = true;
758 resetTargetsLocked();
759
760 logOutboundKeyDetailsLocked("dispatchKey - ", entry);
761 }
762
Jeff Brown54a18252010-09-16 14:07:33 -0700763 // Give the policy a chance to intercept the key.
764 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
Jeff Browne20c9e02010-10-11 14:20:19 -0700765 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Jeff Brown54a18252010-09-16 14:07:33 -0700766 CommandEntry* commandEntry = postCommandLocked(
767 & InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
Jeff Browne20c9e02010-10-11 14:20:19 -0700768 if (mFocusedWindow) {
Jeff Brown928e0542011-01-10 11:17:36 -0800769 commandEntry->inputWindowHandle = mFocusedWindow->inputWindowHandle;
Jeff Brown54a18252010-09-16 14:07:33 -0700770 }
771 commandEntry->keyEntry = entry;
772 entry->refCount += 1;
773 return false; // wait for the command to run
774 } else {
775 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
776 }
777 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Jeff Browne20c9e02010-10-11 14:20:19 -0700778 if (*dropReason == DROP_REASON_NOT_DROPPED) {
779 *dropReason = DROP_REASON_POLICY;
780 }
Jeff Brown54a18252010-09-16 14:07:33 -0700781 }
782
783 // Clean up if dropping the event.
Jeff Browne20c9e02010-10-11 14:20:19 -0700784 if (*dropReason != DROP_REASON_NOT_DROPPED) {
Jeff Brown54a18252010-09-16 14:07:33 -0700785 resetTargetsLocked();
Jeff Brown3122e442010-10-11 23:32:49 -0700786 setInjectionResultLocked(entry, *dropReason == DROP_REASON_POLICY
787 ? INPUT_EVENT_INJECTION_SUCCEEDED : INPUT_EVENT_INJECTION_FAILED);
Jeff Brown54a18252010-09-16 14:07:33 -0700788 return true;
789 }
790
Jeff Brownb88102f2010-09-08 11:49:43 -0700791 // Identify targets.
792 if (! mCurrentInputTargetsValid) {
Jeff Brown01ce2e92010-09-26 22:20:12 -0700793 int32_t injectionResult = findFocusedWindowTargetsLocked(currentTime,
794 entry, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700795 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
796 return false;
797 }
798
799 setInjectionResultLocked(entry, injectionResult);
800 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
801 return true;
802 }
803
804 addMonitoringTargetsLocked();
Jeff Brown01ce2e92010-09-26 22:20:12 -0700805 commitTargetsLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -0700806 }
807
808 // Dispatch the key.
809 dispatchEventToCurrentInputTargetsLocked(currentTime, entry, false);
Jeff Brownb88102f2010-09-08 11:49:43 -0700810 return true;
811}
812
813void InputDispatcher::logOutboundKeyDetailsLocked(const char* prefix, const KeyEntry* entry) {
814#if DEBUG_OUTBOUND_EVENT_DETAILS
Jeff Brown90655042010-12-02 13:50:46 -0800815 LOGD("%seventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, "
Jeff Brownb88102f2010-09-08 11:49:43 -0700816 "action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, "
Jeff Browne46a0a42010-11-02 17:58:22 -0700817 "repeatCount=%d, downTime=%lld",
Jeff Brownb88102f2010-09-08 11:49:43 -0700818 prefix,
819 entry->eventTime, entry->deviceId, entry->source, entry->policyFlags,
820 entry->action, entry->flags, entry->keyCode, entry->scanCode, entry->metaState,
Jeff Browne46a0a42010-11-02 17:58:22 -0700821 entry->repeatCount, entry->downTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700822#endif
823}
824
825bool InputDispatcher::dispatchMotionLocked(
Jeff Browne20c9e02010-10-11 14:20:19 -0700826 nsecs_t currentTime, MotionEntry* entry, DropReason* dropReason, nsecs_t* nextWakeupTime) {
Jeff Browne46a0a42010-11-02 17:58:22 -0700827 // Preprocessing.
828 if (! entry->dispatchInProgress) {
829 entry->dispatchInProgress = true;
830 resetTargetsLocked();
831
832 logOutboundMotionDetailsLocked("dispatchMotion - ", entry);
833 }
834
Jeff Brown54a18252010-09-16 14:07:33 -0700835 // Clean up if dropping the event.
Jeff Browne20c9e02010-10-11 14:20:19 -0700836 if (*dropReason != DROP_REASON_NOT_DROPPED) {
Jeff Brown54a18252010-09-16 14:07:33 -0700837 resetTargetsLocked();
Jeff Brown3122e442010-10-11 23:32:49 -0700838 setInjectionResultLocked(entry, *dropReason == DROP_REASON_POLICY
839 ? INPUT_EVENT_INJECTION_SUCCEEDED : INPUT_EVENT_INJECTION_FAILED);
Jeff Brown54a18252010-09-16 14:07:33 -0700840 return true;
841 }
842
Jeff Brownb88102f2010-09-08 11:49:43 -0700843 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
844
845 // Identify targets.
Jeff Browncc0c1592011-02-19 05:07:28 -0800846 bool conflictingPointerActions = false;
Jeff Brownb88102f2010-09-08 11:49:43 -0700847 if (! mCurrentInputTargetsValid) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700848 int32_t injectionResult;
849 if (isPointerEvent) {
850 // Pointer event. (eg. touchscreen)
Jeff Brown01ce2e92010-09-26 22:20:12 -0700851 injectionResult = findTouchedWindowTargetsLocked(currentTime,
Jeff Browncc0c1592011-02-19 05:07:28 -0800852 entry, nextWakeupTime, &conflictingPointerActions);
Jeff Brownb88102f2010-09-08 11:49:43 -0700853 } else {
854 // Non touch event. (eg. trackball)
Jeff Brown01ce2e92010-09-26 22:20:12 -0700855 injectionResult = findFocusedWindowTargetsLocked(currentTime,
856 entry, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700857 }
858 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
859 return false;
860 }
861
862 setInjectionResultLocked(entry, injectionResult);
863 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
864 return true;
865 }
866
867 addMonitoringTargetsLocked();
Jeff Brown01ce2e92010-09-26 22:20:12 -0700868 commitTargetsLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -0700869 }
870
871 // Dispatch the motion.
Jeff Browncc0c1592011-02-19 05:07:28 -0800872 if (conflictingPointerActions) {
Jeff Brown524ee642011-03-29 15:11:34 -0700873 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
874 "conflicting pointer actions");
875 synthesizeCancelationEventsForAllConnectionsLocked(options);
Jeff Browncc0c1592011-02-19 05:07:28 -0800876 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700877 dispatchEventToCurrentInputTargetsLocked(currentTime, entry, false);
Jeff Brownb88102f2010-09-08 11:49:43 -0700878 return true;
879}
880
881
882void InputDispatcher::logOutboundMotionDetailsLocked(const char* prefix, const MotionEntry* entry) {
883#if DEBUG_OUTBOUND_EVENT_DETAILS
Jeff Brown90655042010-12-02 13:50:46 -0800884 LOGD("%seventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, "
Jeff Brown85a31762010-09-01 17:01:00 -0700885 "action=0x%x, flags=0x%x, "
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700886 "metaState=0x%x, edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%lld",
Jeff Brownb88102f2010-09-08 11:49:43 -0700887 prefix,
Jeff Brown85a31762010-09-01 17:01:00 -0700888 entry->eventTime, entry->deviceId, entry->source, entry->policyFlags,
889 entry->action, entry->flags,
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700890 entry->metaState, entry->edgeFlags, entry->xPrecision, entry->yPrecision,
891 entry->downTime);
892
893 // Print the most recent sample that we have available, this may change due to batching.
894 size_t sampleCount = 1;
Jeff Brownb88102f2010-09-08 11:49:43 -0700895 const MotionSample* sample = & entry->firstSample;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700896 for (; sample->next != NULL; sample = sample->next) {
897 sampleCount += 1;
898 }
899 for (uint32_t i = 0; i < entry->pointerCount; i++) {
Jeff Brown8d608662010-08-30 03:02:23 -0700900 LOGD(" Pointer %d: id=%d, x=%f, y=%f, pressure=%f, size=%f, "
Jeff Brown85a31762010-09-01 17:01:00 -0700901 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
Jeff Brown8d608662010-08-30 03:02:23 -0700902 "orientation=%f",
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700903 i, entry->pointerIds[i],
Jeff Brownebbd5d12011-02-17 13:01:34 -0800904 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
905 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
906 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
907 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
908 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
909 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
910 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
911 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
912 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700913 }
914
915 // Keep in mind that due to batching, it is possible for the number of samples actually
916 // dispatched to change before the application finally consumed them.
Jeff Brownc5ed5912010-07-14 18:48:53 -0700917 if (entry->action == AMOTION_EVENT_ACTION_MOVE) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700918 LOGD(" ... Total movement samples currently batched %d ...", sampleCount);
919 }
920#endif
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700921}
922
923void InputDispatcher::dispatchEventToCurrentInputTargetsLocked(nsecs_t currentTime,
924 EventEntry* eventEntry, bool resumeWithAppendedMotionSample) {
925#if DEBUG_DISPATCH_CYCLE
Jeff Brown9c3cda02010-06-15 01:31:58 -0700926 LOGD("dispatchEventToCurrentInputTargets - "
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700927 "resumeWithAppendedMotionSample=%s",
Jeff Brownb88102f2010-09-08 11:49:43 -0700928 toString(resumeWithAppendedMotionSample));
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700929#endif
930
Jeff Brown9c3cda02010-06-15 01:31:58 -0700931 assert(eventEntry->dispatchInProgress); // should already have been set to true
932
Jeff Browne2fe69e2010-10-18 13:21:23 -0700933 pokeUserActivityLocked(eventEntry);
934
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700935 for (size_t i = 0; i < mCurrentInputTargets.size(); i++) {
936 const InputTarget& inputTarget = mCurrentInputTargets.itemAt(i);
937
Jeff Brown519e0242010-09-15 15:18:56 -0700938 ssize_t connectionIndex = getConnectionIndexLocked(inputTarget.inputChannel);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700939 if (connectionIndex >= 0) {
940 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
Jeff Brown7fbdc842010-06-17 20:52:56 -0700941 prepareDispatchCycleLocked(currentTime, connection, eventEntry, & inputTarget,
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700942 resumeWithAppendedMotionSample);
943 } else {
Jeff Brownb6997262010-10-08 22:31:17 -0700944#if DEBUG_FOCUS
945 LOGD("Dropping event delivery to target with channel '%s' because it "
946 "is no longer registered with the input dispatcher.",
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700947 inputTarget.inputChannel->getName().string());
Jeff Brownb6997262010-10-08 22:31:17 -0700948#endif
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700949 }
950 }
951}
952
Jeff Brown54a18252010-09-16 14:07:33 -0700953void InputDispatcher::resetTargetsLocked() {
Jeff Brownb88102f2010-09-08 11:49:43 -0700954 mCurrentInputTargetsValid = false;
955 mCurrentInputTargets.clear();
Jeff Brownb88102f2010-09-08 11:49:43 -0700956 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_NONE;
Jeff Brown928e0542011-01-10 11:17:36 -0800957 mInputTargetWaitApplication.clear();
Jeff Brownb88102f2010-09-08 11:49:43 -0700958}
959
Jeff Brown01ce2e92010-09-26 22:20:12 -0700960void InputDispatcher::commitTargetsLocked() {
Jeff Brownb88102f2010-09-08 11:49:43 -0700961 mCurrentInputTargetsValid = true;
962}
963
964int32_t InputDispatcher::handleTargetsNotReadyLocked(nsecs_t currentTime,
965 const EventEntry* entry, const InputApplication* application, const InputWindow* window,
966 nsecs_t* nextWakeupTime) {
967 if (application == NULL && window == NULL) {
968 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY) {
969#if DEBUG_FOCUS
970 LOGD("Waiting for system to become ready for input.");
971#endif
972 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY;
973 mInputTargetWaitStartTime = currentTime;
974 mInputTargetWaitTimeoutTime = LONG_LONG_MAX;
975 mInputTargetWaitTimeoutExpired = false;
Jeff Brown928e0542011-01-10 11:17:36 -0800976 mInputTargetWaitApplication.clear();
Jeff Brownb88102f2010-09-08 11:49:43 -0700977 }
978 } else {
979 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
980#if DEBUG_FOCUS
Jeff Brown519e0242010-09-15 15:18:56 -0700981 LOGD("Waiting for application to become ready for input: %s",
982 getApplicationWindowLabelLocked(application, window).string());
Jeff Brownb88102f2010-09-08 11:49:43 -0700983#endif
984 nsecs_t timeout = window ? window->dispatchingTimeout :
985 application ? application->dispatchingTimeout : DEFAULT_INPUT_DISPATCHING_TIMEOUT;
986
987 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY;
988 mInputTargetWaitStartTime = currentTime;
989 mInputTargetWaitTimeoutTime = currentTime + timeout;
990 mInputTargetWaitTimeoutExpired = false;
Jeff Brown928e0542011-01-10 11:17:36 -0800991 mInputTargetWaitApplication.clear();
992
993 if (window && window->inputWindowHandle != NULL) {
994 mInputTargetWaitApplication =
995 window->inputWindowHandle->getInputApplicationHandle();
996 }
997 if (mInputTargetWaitApplication == NULL && application) {
998 mInputTargetWaitApplication = application->inputApplicationHandle;
999 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001000 }
1001 }
1002
1003 if (mInputTargetWaitTimeoutExpired) {
1004 return INPUT_EVENT_INJECTION_TIMED_OUT;
1005 }
1006
1007 if (currentTime >= mInputTargetWaitTimeoutTime) {
Jeff Brown519e0242010-09-15 15:18:56 -07001008 onANRLocked(currentTime, application, window, entry->eventTime, mInputTargetWaitStartTime);
Jeff Brownb88102f2010-09-08 11:49:43 -07001009
1010 // Force poll loop to wake up immediately on next iteration once we get the
1011 // ANR response back from the policy.
1012 *nextWakeupTime = LONG_LONG_MIN;
1013 return INPUT_EVENT_INJECTION_PENDING;
1014 } else {
1015 // Force poll loop to wake up when timeout is due.
1016 if (mInputTargetWaitTimeoutTime < *nextWakeupTime) {
1017 *nextWakeupTime = mInputTargetWaitTimeoutTime;
1018 }
1019 return INPUT_EVENT_INJECTION_PENDING;
1020 }
1021}
1022
Jeff Brown519e0242010-09-15 15:18:56 -07001023void InputDispatcher::resumeAfterTargetsNotReadyTimeoutLocked(nsecs_t newTimeout,
1024 const sp<InputChannel>& inputChannel) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001025 if (newTimeout > 0) {
1026 // Extend the timeout.
1027 mInputTargetWaitTimeoutTime = now() + newTimeout;
1028 } else {
1029 // Give up.
1030 mInputTargetWaitTimeoutExpired = true;
Jeff Brown519e0242010-09-15 15:18:56 -07001031
Jeff Brown01ce2e92010-09-26 22:20:12 -07001032 // Release the touch targets.
1033 mTouchState.reset();
Jeff Brown2a95c2a2010-09-16 12:31:46 -07001034
Jeff Brown519e0242010-09-15 15:18:56 -07001035 // Input state will not be realistic. Mark it out of sync.
Jeff Browndc3e0052010-09-16 11:02:16 -07001036 if (inputChannel.get()) {
1037 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
1038 if (connectionIndex >= 0) {
1039 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
Jeff Brown00045a72010-12-09 18:10:30 -08001040 if (connection->status == Connection::STATUS_NORMAL) {
Jeff Brown524ee642011-03-29 15:11:34 -07001041 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
Jeff Brown00045a72010-12-09 18:10:30 -08001042 "application not responding");
Jeff Brown524ee642011-03-29 15:11:34 -07001043 synthesizeCancelationEventsForConnectionLocked(connection, options);
Jeff Brown00045a72010-12-09 18:10:30 -08001044 }
Jeff Browndc3e0052010-09-16 11:02:16 -07001045 }
Jeff Brown519e0242010-09-15 15:18:56 -07001046 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001047 }
1048}
1049
Jeff Brown519e0242010-09-15 15:18:56 -07001050nsecs_t InputDispatcher::getTimeSpentWaitingForApplicationLocked(
Jeff Brownb88102f2010-09-08 11:49:43 -07001051 nsecs_t currentTime) {
1052 if (mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
1053 return currentTime - mInputTargetWaitStartTime;
1054 }
1055 return 0;
1056}
1057
1058void InputDispatcher::resetANRTimeoutsLocked() {
1059#if DEBUG_FOCUS
1060 LOGD("Resetting ANR timeouts.");
1061#endif
1062
Jeff Brownb88102f2010-09-08 11:49:43 -07001063 // Reset input target wait timeout.
1064 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_NONE;
1065}
1066
Jeff Brown01ce2e92010-09-26 22:20:12 -07001067int32_t InputDispatcher::findFocusedWindowTargetsLocked(nsecs_t currentTime,
1068 const EventEntry* entry, nsecs_t* nextWakeupTime) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001069 mCurrentInputTargets.clear();
1070
1071 int32_t injectionResult;
1072
1073 // If there is no currently focused window and no focused application
1074 // then drop the event.
1075 if (! mFocusedWindow) {
1076 if (mFocusedApplication) {
1077#if DEBUG_FOCUS
1078 LOGD("Waiting because there is no focused window but there is a "
Jeff Brown519e0242010-09-15 15:18:56 -07001079 "focused application that may eventually add a window: %s.",
1080 getApplicationWindowLabelLocked(mFocusedApplication, NULL).string());
Jeff Brownb88102f2010-09-08 11:49:43 -07001081#endif
1082 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
1083 mFocusedApplication, NULL, nextWakeupTime);
1084 goto Unresponsive;
1085 }
1086
1087 LOGI("Dropping event because there is no focused window or focused application.");
1088 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1089 goto Failed;
1090 }
1091
1092 // Check permissions.
Jeff Brown01ce2e92010-09-26 22:20:12 -07001093 if (! checkInjectionPermission(mFocusedWindow, entry->injectionState)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001094 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1095 goto Failed;
1096 }
1097
1098 // If the currently focused window is paused then keep waiting.
1099 if (mFocusedWindow->paused) {
1100#if DEBUG_FOCUS
1101 LOGD("Waiting because focused window is paused.");
1102#endif
1103 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
1104 mFocusedApplication, mFocusedWindow, nextWakeupTime);
1105 goto Unresponsive;
1106 }
1107
Jeff Brown519e0242010-09-15 15:18:56 -07001108 // If the currently focused window is still working on previous events then keep waiting.
1109 if (! isWindowFinishedWithPreviousInputLocked(mFocusedWindow)) {
1110#if DEBUG_FOCUS
1111 LOGD("Waiting because focused window still processing previous input.");
1112#endif
1113 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
1114 mFocusedApplication, mFocusedWindow, nextWakeupTime);
1115 goto Unresponsive;
1116 }
1117
Jeff Brownb88102f2010-09-08 11:49:43 -07001118 // Success! Output targets.
1119 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001120 addWindowTargetLocked(mFocusedWindow, InputTarget::FLAG_FOREGROUND, BitSet32(0));
Jeff Brownb88102f2010-09-08 11:49:43 -07001121
1122 // Done.
1123Failed:
1124Unresponsive:
Jeff Brown519e0242010-09-15 15:18:56 -07001125 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
1126 updateDispatchStatisticsLocked(currentTime, entry,
1127 injectionResult, timeSpentWaitingForApplication);
Jeff Brownb88102f2010-09-08 11:49:43 -07001128#if DEBUG_FOCUS
Jeff Brown519e0242010-09-15 15:18:56 -07001129 LOGD("findFocusedWindow finished: injectionResult=%d, "
1130 "timeSpendWaitingForApplication=%0.1fms",
1131 injectionResult, timeSpentWaitingForApplication / 1000000.0);
Jeff Brownb88102f2010-09-08 11:49:43 -07001132#endif
1133 return injectionResult;
1134}
1135
Jeff Brown01ce2e92010-09-26 22:20:12 -07001136int32_t InputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime,
Jeff Browncc0c1592011-02-19 05:07:28 -08001137 const MotionEntry* entry, nsecs_t* nextWakeupTime, bool* outConflictingPointerActions) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001138 enum InjectionPermission {
1139 INJECTION_PERMISSION_UNKNOWN,
1140 INJECTION_PERMISSION_GRANTED,
1141 INJECTION_PERMISSION_DENIED
1142 };
1143
Jeff Brownb88102f2010-09-08 11:49:43 -07001144 mCurrentInputTargets.clear();
1145
1146 nsecs_t startTime = now();
1147
1148 // For security reasons, we defer updating the touch state until we are sure that
1149 // event injection will be allowed.
1150 //
1151 // FIXME In the original code, screenWasOff could never be set to true.
1152 // The reason is that the POLICY_FLAG_WOKE_HERE
1153 // and POLICY_FLAG_BRIGHT_HERE flags were set only when preprocessing raw
1154 // EV_KEY, EV_REL and EV_ABS events. As it happens, the touch event was
1155 // actually enqueued using the policyFlags that appeared in the final EV_SYN
1156 // events upon which no preprocessing took place. So policyFlags was always 0.
1157 // In the new native input dispatcher we're a bit more careful about event
1158 // preprocessing so the touches we receive can actually have non-zero policyFlags.
1159 // Unfortunately we obtain undesirable behavior.
1160 //
1161 // Here's what happens:
1162 //
1163 // When the device dims in anticipation of going to sleep, touches
1164 // in windows which have FLAG_TOUCHABLE_WHEN_WAKING cause
1165 // the device to brighten and reset the user activity timer.
1166 // Touches on other windows (such as the launcher window)
1167 // are dropped. Then after a moment, the device goes to sleep. Oops.
1168 //
1169 // Also notice how screenWasOff was being initialized using POLICY_FLAG_BRIGHT_HERE
1170 // instead of POLICY_FLAG_WOKE_HERE...
1171 //
1172 bool screenWasOff = false; // original policy: policyFlags & POLICY_FLAG_BRIGHT_HERE;
1173
1174 int32_t action = entry->action;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001175 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Jeff Brownb88102f2010-09-08 11:49:43 -07001176
1177 // Update the touch state as needed based on the properties of the touch event.
Jeff Brown01ce2e92010-09-26 22:20:12 -07001178 int32_t injectionResult = INPUT_EVENT_INJECTION_PENDING;
1179 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
Jeff Browncc0c1592011-02-19 05:07:28 -08001180
1181 bool isSplit = mTouchState.split;
1182 bool wrongDevice = mTouchState.down
1183 && (mTouchState.deviceId != entry->deviceId
1184 || mTouchState.source != entry->source);
1185 if (maskedAction == AMOTION_EVENT_ACTION_DOWN
Jeff Brown33bbfd22011-02-24 20:55:35 -08001186 || maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE
1187 || maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
Jeff Browncc0c1592011-02-19 05:07:28 -08001188 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
1189 if (wrongDevice && !down) {
1190 mTempTouchState.copyFrom(mTouchState);
1191 } else {
1192 mTempTouchState.reset();
1193 mTempTouchState.down = down;
1194 mTempTouchState.deviceId = entry->deviceId;
1195 mTempTouchState.source = entry->source;
1196 isSplit = false;
1197 wrongDevice = false;
1198 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001199 } else {
1200 mTempTouchState.copyFrom(mTouchState);
Jeff Browncc0c1592011-02-19 05:07:28 -08001201 }
1202 if (wrongDevice) {
Jeff Brown22d789d2011-03-25 11:58:46 -07001203#if DEBUG_FOCUS
Jeff Browncc0c1592011-02-19 05:07:28 -08001204 LOGD("Dropping event because a pointer for a different device is already down.");
Jeff Brown95712852011-01-04 19:41:59 -08001205#endif
Jeff Browncc0c1592011-02-19 05:07:28 -08001206 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1207 goto Failed;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001208 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001209
Jeff Brown01ce2e92010-09-26 22:20:12 -07001210 if (maskedAction == AMOTION_EVENT_ACTION_DOWN
Jeff Browncc0c1592011-02-19 05:07:28 -08001211 || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)
Jeff Brown33bbfd22011-02-24 20:55:35 -08001212 || maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE
1213 || maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
1214 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
Jeff Brownb88102f2010-09-08 11:49:43 -07001215
Jeff Brown01ce2e92010-09-26 22:20:12 -07001216 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Jeff Brown91c69ab2011-02-14 17:03:18 -08001217 int32_t x = int32_t(entry->firstSample.pointerCoords[pointerIndex].
Jeff Brownebbd5d12011-02-17 13:01:34 -08001218 getAxisValue(AMOTION_EVENT_AXIS_X));
Jeff Brown91c69ab2011-02-14 17:03:18 -08001219 int32_t y = int32_t(entry->firstSample.pointerCoords[pointerIndex].
Jeff Brownebbd5d12011-02-17 13:01:34 -08001220 getAxisValue(AMOTION_EVENT_AXIS_Y));
Jeff Brown01ce2e92010-09-26 22:20:12 -07001221 const InputWindow* newTouchedWindow = NULL;
1222 const InputWindow* topErrorWindow = NULL;
Jeff Brownb88102f2010-09-08 11:49:43 -07001223
1224 // Traverse windows from front to back to find touched window and outside targets.
1225 size_t numWindows = mWindows.size();
1226 for (size_t i = 0; i < numWindows; i++) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001227 const InputWindow* window = & mWindows.editItemAt(i);
Jeff Brownb88102f2010-09-08 11:49:43 -07001228 int32_t flags = window->layoutParamsFlags;
1229
1230 if (flags & InputWindow::FLAG_SYSTEM_ERROR) {
1231 if (! topErrorWindow) {
1232 topErrorWindow = window;
1233 }
1234 }
1235
1236 if (window->visible) {
1237 if (! (flags & InputWindow::FLAG_NOT_TOUCHABLE)) {
1238 bool isTouchModal = (flags & (InputWindow::FLAG_NOT_FOCUSABLE
1239 | InputWindow::FLAG_NOT_TOUCH_MODAL)) == 0;
Jeff Brownfbf09772011-01-16 14:06:57 -08001240 if (isTouchModal || window->touchableRegionContainsPoint(x, y)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001241 if (! screenWasOff || flags & InputWindow::FLAG_TOUCHABLE_WHEN_WAKING) {
1242 newTouchedWindow = window;
Jeff Brownb88102f2010-09-08 11:49:43 -07001243 }
1244 break; // found touched window, exit window loop
1245 }
1246 }
1247
Jeff Brown01ce2e92010-09-26 22:20:12 -07001248 if (maskedAction == AMOTION_EVENT_ACTION_DOWN
1249 && (flags & InputWindow::FLAG_WATCH_OUTSIDE_TOUCH)) {
Jeff Brown19dfc832010-10-05 12:26:23 -07001250 int32_t outsideTargetFlags = InputTarget::FLAG_OUTSIDE;
1251 if (isWindowObscuredAtPointLocked(window, x, y)) {
1252 outsideTargetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1253 }
1254
1255 mTempTouchState.addOrUpdateWindow(window, outsideTargetFlags, BitSet32(0));
Jeff Brownb88102f2010-09-08 11:49:43 -07001256 }
1257 }
1258 }
1259
1260 // If there is an error window but it is not taking focus (typically because
1261 // it is invisible) then wait for it. Any other focused window may in
1262 // fact be in ANR state.
1263 if (topErrorWindow && newTouchedWindow != topErrorWindow) {
1264#if DEBUG_FOCUS
1265 LOGD("Waiting because system error window is pending.");
1266#endif
1267 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
1268 NULL, NULL, nextWakeupTime);
1269 injectionPermission = INJECTION_PERMISSION_UNKNOWN;
1270 goto Unresponsive;
1271 }
1272
Jeff Brown01ce2e92010-09-26 22:20:12 -07001273 // Figure out whether splitting will be allowed for this window.
Jeff Brown46e75292010-11-10 16:53:45 -08001274 if (newTouchedWindow && newTouchedWindow->supportsSplitTouch()) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001275 // New window supports splitting.
1276 isSplit = true;
1277 } else if (isSplit) {
1278 // New window does not support splitting but we have already split events.
1279 // Assign the pointer to the first foreground window we find.
1280 // (May be NULL which is why we put this code block before the next check.)
1281 newTouchedWindow = mTempTouchState.getFirstForegroundWindow();
1282 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001283
Jeff Brownb88102f2010-09-08 11:49:43 -07001284 // If we did not find a touched window then fail.
1285 if (! newTouchedWindow) {
1286 if (mFocusedApplication) {
1287#if DEBUG_FOCUS
1288 LOGD("Waiting because there is no touched window but there is a "
Jeff Brown519e0242010-09-15 15:18:56 -07001289 "focused application that may eventually add a new window: %s.",
1290 getApplicationWindowLabelLocked(mFocusedApplication, NULL).string());
Jeff Brownb88102f2010-09-08 11:49:43 -07001291#endif
1292 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
1293 mFocusedApplication, NULL, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -07001294 goto Unresponsive;
1295 }
1296
1297 LOGI("Dropping event because there is no touched window or focused application.");
1298 injectionResult = INPUT_EVENT_INJECTION_FAILED;
Jeff Brownb88102f2010-09-08 11:49:43 -07001299 goto Failed;
1300 }
1301
Jeff Brown19dfc832010-10-05 12:26:23 -07001302 // Set target flags.
1303 int32_t targetFlags = InputTarget::FLAG_FOREGROUND;
1304 if (isSplit) {
1305 targetFlags |= InputTarget::FLAG_SPLIT;
1306 }
1307 if (isWindowObscuredAtPointLocked(newTouchedWindow, x, y)) {
1308 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1309 }
1310
Jeff Brown01ce2e92010-09-26 22:20:12 -07001311 // Update the temporary touch state.
1312 BitSet32 pointerIds;
1313 if (isSplit) {
1314 uint32_t pointerId = entry->pointerIds[pointerIndex];
1315 pointerIds.markBit(pointerId);
Jeff Brownb88102f2010-09-08 11:49:43 -07001316 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001317 mTempTouchState.addOrUpdateWindow(newTouchedWindow, targetFlags, pointerIds);
Jeff Brownb88102f2010-09-08 11:49:43 -07001318 } else {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001319 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
Jeff Brownb88102f2010-09-08 11:49:43 -07001320
1321 // If the pointer is not currently down, then ignore the event.
Jeff Brown01ce2e92010-09-26 22:20:12 -07001322 if (! mTempTouchState.down) {
Jeff Brown22d789d2011-03-25 11:58:46 -07001323#if DEBUG_FOCUS
Jeff Brown76860e32010-10-25 17:37:46 -07001324 LOGD("Dropping event because the pointer is not down or we previously "
1325 "dropped the pointer down event.");
1326#endif
Jeff Brownb88102f2010-09-08 11:49:43 -07001327 injectionResult = INPUT_EVENT_INJECTION_FAILED;
Jeff Brownb88102f2010-09-08 11:49:43 -07001328 goto Failed;
1329 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001330 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001331
Jeff Brown01ce2e92010-09-26 22:20:12 -07001332 // Check permission to inject into all touched foreground windows and ensure there
1333 // is at least one touched foreground window.
1334 {
1335 bool haveForegroundWindow = false;
1336 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1337 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1338 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1339 haveForegroundWindow = true;
1340 if (! checkInjectionPermission(touchedWindow.window, entry->injectionState)) {
1341 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1342 injectionPermission = INJECTION_PERMISSION_DENIED;
1343 goto Failed;
1344 }
1345 }
1346 }
1347 if (! haveForegroundWindow) {
Jeff Brown22d789d2011-03-25 11:58:46 -07001348#if DEBUG_FOCUS
Jeff Brown01ce2e92010-09-26 22:20:12 -07001349 LOGD("Dropping event because there is no touched foreground window to receive it.");
Jeff Brownb88102f2010-09-08 11:49:43 -07001350#endif
1351 injectionResult = INPUT_EVENT_INJECTION_FAILED;
Jeff Brownb88102f2010-09-08 11:49:43 -07001352 goto Failed;
1353 }
1354
Jeff Brown01ce2e92010-09-26 22:20:12 -07001355 // Permission granted to injection into all touched foreground windows.
1356 injectionPermission = INJECTION_PERMISSION_GRANTED;
1357 }
Jeff Brown519e0242010-09-15 15:18:56 -07001358
Jeff Brown01ce2e92010-09-26 22:20:12 -07001359 // Ensure all touched foreground windows are ready for new input.
1360 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1361 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1362 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1363 // If the touched window is paused then keep waiting.
1364 if (touchedWindow.window->paused) {
Jeff Brown22d789d2011-03-25 11:58:46 -07001365#if DEBUG_FOCUS
Jeff Brown01ce2e92010-09-26 22:20:12 -07001366 LOGD("Waiting because touched window is paused.");
Jeff Brown519e0242010-09-15 15:18:56 -07001367#endif
Jeff Brown01ce2e92010-09-26 22:20:12 -07001368 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
1369 NULL, touchedWindow.window, nextWakeupTime);
1370 goto Unresponsive;
1371 }
1372
1373 // If the touched window is still working on previous events then keep waiting.
1374 if (! isWindowFinishedWithPreviousInputLocked(touchedWindow.window)) {
1375#if DEBUG_FOCUS
1376 LOGD("Waiting because touched window still processing previous input.");
1377#endif
1378 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
1379 NULL, touchedWindow.window, nextWakeupTime);
1380 goto Unresponsive;
1381 }
1382 }
1383 }
1384
1385 // If this is the first pointer going down and the touched window has a wallpaper
1386 // then also add the touched wallpaper windows so they are locked in for the duration
1387 // of the touch gesture.
Jeff Brown33bbfd22011-02-24 20:55:35 -08001388 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
1389 // engine only supports touch events. We would need to add a mechanism similar
1390 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
1391 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001392 const InputWindow* foregroundWindow = mTempTouchState.getFirstForegroundWindow();
1393 if (foregroundWindow->hasWallpaper) {
1394 for (size_t i = 0; i < mWindows.size(); i++) {
1395 const InputWindow* window = & mWindows[i];
1396 if (window->layoutParamsType == InputWindow::TYPE_WALLPAPER) {
Jeff Brown19dfc832010-10-05 12:26:23 -07001397 mTempTouchState.addOrUpdateWindow(window,
1398 InputTarget::FLAG_WINDOW_IS_OBSCURED, BitSet32(0));
Jeff Brown01ce2e92010-09-26 22:20:12 -07001399 }
1400 }
1401 }
1402 }
1403
Jeff Brownb88102f2010-09-08 11:49:43 -07001404 // Success! Output targets.
1405 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
Jeff Brownb88102f2010-09-08 11:49:43 -07001406
Jeff Brown01ce2e92010-09-26 22:20:12 -07001407 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1408 const TouchedWindow& touchedWindow = mTempTouchState.windows.itemAt(i);
1409 addWindowTargetLocked(touchedWindow.window, touchedWindow.targetFlags,
1410 touchedWindow.pointerIds);
Jeff Brownb88102f2010-09-08 11:49:43 -07001411 }
1412
Jeff Brown01ce2e92010-09-26 22:20:12 -07001413 // Drop the outside touch window since we will not care about them in the next iteration.
1414 mTempTouchState.removeOutsideTouchWindows();
1415
Jeff Brownb88102f2010-09-08 11:49:43 -07001416Failed:
1417 // Check injection permission once and for all.
1418 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001419 if (checkInjectionPermission(NULL, entry->injectionState)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001420 injectionPermission = INJECTION_PERMISSION_GRANTED;
1421 } else {
1422 injectionPermission = INJECTION_PERMISSION_DENIED;
1423 }
1424 }
1425
1426 // Update final pieces of touch state if the injector had permission.
1427 if (injectionPermission == INJECTION_PERMISSION_GRANTED) {
Jeff Brown95712852011-01-04 19:41:59 -08001428 if (!wrongDevice) {
1429 if (maskedAction == AMOTION_EVENT_ACTION_UP
Jeff Browncc0c1592011-02-19 05:07:28 -08001430 || maskedAction == AMOTION_EVENT_ACTION_CANCEL
1431 || maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Jeff Brown95712852011-01-04 19:41:59 -08001432 // All pointers up or canceled.
Jeff Brown33bbfd22011-02-24 20:55:35 -08001433 mTouchState.reset();
Jeff Brown95712852011-01-04 19:41:59 -08001434 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1435 // First pointer went down.
1436 if (mTouchState.down) {
Jeff Browncc0c1592011-02-19 05:07:28 -08001437 *outConflictingPointerActions = true;
Jeff Brownb6997262010-10-08 22:31:17 -07001438#if DEBUG_FOCUS
Jeff Brown95712852011-01-04 19:41:59 -08001439 LOGD("Pointer down received while already down.");
Jeff Brownb6997262010-10-08 22:31:17 -07001440#endif
Jeff Brown95712852011-01-04 19:41:59 -08001441 }
Jeff Brown33bbfd22011-02-24 20:55:35 -08001442 mTouchState.copyFrom(mTempTouchState);
Jeff Brown95712852011-01-04 19:41:59 -08001443 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
1444 // One pointer went up.
1445 if (isSplit) {
1446 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
1447 uint32_t pointerId = entry->pointerIds[pointerIndex];
Jeff Brownb88102f2010-09-08 11:49:43 -07001448
Jeff Brown95712852011-01-04 19:41:59 -08001449 for (size_t i = 0; i < mTempTouchState.windows.size(); ) {
1450 TouchedWindow& touchedWindow = mTempTouchState.windows.editItemAt(i);
1451 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
1452 touchedWindow.pointerIds.clearBit(pointerId);
1453 if (touchedWindow.pointerIds.isEmpty()) {
1454 mTempTouchState.windows.removeAt(i);
1455 continue;
1456 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001457 }
Jeff Brown95712852011-01-04 19:41:59 -08001458 i += 1;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001459 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001460 }
Jeff Brown33bbfd22011-02-24 20:55:35 -08001461 mTouchState.copyFrom(mTempTouchState);
1462 } else if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
1463 // Discard temporary touch state since it was only valid for this action.
1464 } else {
1465 // Save changes to touch state as-is for all other actions.
1466 mTouchState.copyFrom(mTempTouchState);
Jeff Brownb88102f2010-09-08 11:49:43 -07001467 }
Jeff Brown95712852011-01-04 19:41:59 -08001468 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001469 } else {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001470#if DEBUG_FOCUS
1471 LOGD("Not updating touch focus because injection was denied.");
1472#endif
Jeff Brownb88102f2010-09-08 11:49:43 -07001473 }
1474
1475Unresponsive:
Jeff Brown120a4592010-10-27 18:43:51 -07001476 // Reset temporary touch state to ensure we release unnecessary references to input channels.
1477 mTempTouchState.reset();
1478
Jeff Brown519e0242010-09-15 15:18:56 -07001479 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
1480 updateDispatchStatisticsLocked(currentTime, entry,
1481 injectionResult, timeSpentWaitingForApplication);
Jeff Brownb88102f2010-09-08 11:49:43 -07001482#if DEBUG_FOCUS
Jeff Brown01ce2e92010-09-26 22:20:12 -07001483 LOGD("findTouchedWindow finished: injectionResult=%d, injectionPermission=%d, "
1484 "timeSpentWaitingForApplication=%0.1fms",
Jeff Brown519e0242010-09-15 15:18:56 -07001485 injectionResult, injectionPermission, timeSpentWaitingForApplication / 1000000.0);
Jeff Brownb88102f2010-09-08 11:49:43 -07001486#endif
1487 return injectionResult;
1488}
1489
Jeff Brown01ce2e92010-09-26 22:20:12 -07001490void InputDispatcher::addWindowTargetLocked(const InputWindow* window, int32_t targetFlags,
1491 BitSet32 pointerIds) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001492 mCurrentInputTargets.push();
1493
1494 InputTarget& target = mCurrentInputTargets.editTop();
1495 target.inputChannel = window->inputChannel;
1496 target.flags = targetFlags;
Jeff Brownb88102f2010-09-08 11:49:43 -07001497 target.xOffset = - window->frameLeft;
1498 target.yOffset = - window->frameTop;
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001499 target.scaleFactor = window->scaleFactor;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001500 target.pointerIds = pointerIds;
Jeff Brownb88102f2010-09-08 11:49:43 -07001501}
1502
1503void InputDispatcher::addMonitoringTargetsLocked() {
1504 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
1505 mCurrentInputTargets.push();
1506
1507 InputTarget& target = mCurrentInputTargets.editTop();
1508 target.inputChannel = mMonitoringChannels[i];
1509 target.flags = 0;
Jeff Brownb88102f2010-09-08 11:49:43 -07001510 target.xOffset = 0;
1511 target.yOffset = 0;
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001512 target.scaleFactor = 1.0f;
Jeff Brownb88102f2010-09-08 11:49:43 -07001513 }
1514}
1515
1516bool InputDispatcher::checkInjectionPermission(const InputWindow* window,
Jeff Brown01ce2e92010-09-26 22:20:12 -07001517 const InjectionState* injectionState) {
1518 if (injectionState
Jeff Brownb6997262010-10-08 22:31:17 -07001519 && (window == NULL || window->ownerUid != injectionState->injectorUid)
1520 && !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
1521 if (window) {
1522 LOGW("Permission denied: injecting event from pid %d uid %d to window "
1523 "with input channel %s owned by uid %d",
1524 injectionState->injectorPid, injectionState->injectorUid,
1525 window->inputChannel->getName().string(),
1526 window->ownerUid);
1527 } else {
1528 LOGW("Permission denied: injecting event from pid %d uid %d",
1529 injectionState->injectorPid, injectionState->injectorUid);
Jeff Brownb88102f2010-09-08 11:49:43 -07001530 }
Jeff Brownb6997262010-10-08 22:31:17 -07001531 return false;
Jeff Brownb88102f2010-09-08 11:49:43 -07001532 }
1533 return true;
1534}
1535
Jeff Brown19dfc832010-10-05 12:26:23 -07001536bool InputDispatcher::isWindowObscuredAtPointLocked(
1537 const InputWindow* window, int32_t x, int32_t y) const {
Jeff Brownb88102f2010-09-08 11:49:43 -07001538 size_t numWindows = mWindows.size();
1539 for (size_t i = 0; i < numWindows; i++) {
1540 const InputWindow* other = & mWindows.itemAt(i);
1541 if (other == window) {
1542 break;
1543 }
Jeff Brown19dfc832010-10-05 12:26:23 -07001544 if (other->visible && ! other->isTrustedOverlay() && other->frameContainsPoint(x, y)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001545 return true;
1546 }
1547 }
1548 return false;
1549}
1550
Jeff Brown519e0242010-09-15 15:18:56 -07001551bool InputDispatcher::isWindowFinishedWithPreviousInputLocked(const InputWindow* window) {
1552 ssize_t connectionIndex = getConnectionIndexLocked(window->inputChannel);
1553 if (connectionIndex >= 0) {
1554 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
1555 return connection->outboundQueue.isEmpty();
1556 } else {
1557 return true;
1558 }
1559}
1560
1561String8 InputDispatcher::getApplicationWindowLabelLocked(const InputApplication* application,
1562 const InputWindow* window) {
1563 if (application) {
1564 if (window) {
1565 String8 label(application->name);
1566 label.append(" - ");
1567 label.append(window->name);
1568 return label;
1569 } else {
1570 return application->name;
1571 }
1572 } else if (window) {
1573 return window->name;
1574 } else {
1575 return String8("<unknown application or window>");
1576 }
1577}
1578
Jeff Browne2fe69e2010-10-18 13:21:23 -07001579void InputDispatcher::pokeUserActivityLocked(const EventEntry* eventEntry) {
Jeff Brown56194eb2011-03-02 19:23:13 -08001580 int32_t eventType = POWER_MANAGER_OTHER_EVENT;
Jeff Brown4d396052010-10-29 21:50:21 -07001581 switch (eventEntry->type) {
1582 case EventEntry::TYPE_MOTION: {
Jeff Browne2fe69e2010-10-18 13:21:23 -07001583 const MotionEntry* motionEntry = static_cast<const MotionEntry*>(eventEntry);
Jeff Brown4d396052010-10-29 21:50:21 -07001584 if (motionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
1585 return;
1586 }
1587
Jeff Brown56194eb2011-03-02 19:23:13 -08001588 if (MotionEvent::isTouchEvent(motionEntry->source, motionEntry->action)) {
Joe Onorato1a542c72010-11-08 09:48:20 -08001589 eventType = POWER_MANAGER_TOUCH_EVENT;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001590 }
Jeff Brown4d396052010-10-29 21:50:21 -07001591 break;
1592 }
1593 case EventEntry::TYPE_KEY: {
1594 const KeyEntry* keyEntry = static_cast<const KeyEntry*>(eventEntry);
1595 if (keyEntry->flags & AKEY_EVENT_FLAG_CANCELED) {
1596 return;
1597 }
Jeff Brown56194eb2011-03-02 19:23:13 -08001598 eventType = POWER_MANAGER_BUTTON_EVENT;
Jeff Brown4d396052010-10-29 21:50:21 -07001599 break;
1600 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001601 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001602
Jeff Brownb88102f2010-09-08 11:49:43 -07001603 CommandEntry* commandEntry = postCommandLocked(
1604 & InputDispatcher::doPokeUserActivityLockedInterruptible);
Jeff Browne2fe69e2010-10-18 13:21:23 -07001605 commandEntry->eventTime = eventEntry->eventTime;
Jeff Brownb88102f2010-09-08 11:49:43 -07001606 commandEntry->userActivityEventType = eventType;
1607}
1608
Jeff Brown7fbdc842010-06-17 20:52:56 -07001609void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
1610 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget,
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001611 bool resumeWithAppendedMotionSample) {
1612#if DEBUG_DISPATCH_CYCLE
Jeff Brown519e0242010-09-15 15:18:56 -07001613 LOGD("channel '%s' ~ prepareDispatchCycle - flags=%d, "
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001614 "xOffset=%f, yOffset=%f, scaleFactor=%f"
Jeff Brown83c09682010-12-23 17:50:18 -08001615 "pointerIds=0x%x, "
Jeff Brown01ce2e92010-09-26 22:20:12 -07001616 "resumeWithAppendedMotionSample=%s",
Jeff Brown519e0242010-09-15 15:18:56 -07001617 connection->getInputChannelName(), inputTarget->flags,
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001618 inputTarget->xOffset, inputTarget->yOffset,
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001619 inputTarget->scaleFactor, inputTarget->pointerIds.value,
Jeff Brownb88102f2010-09-08 11:49:43 -07001620 toString(resumeWithAppendedMotionSample));
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001621#endif
1622
Jeff Brown01ce2e92010-09-26 22:20:12 -07001623 // Make sure we are never called for streaming when splitting across multiple windows.
1624 bool isSplit = inputTarget->flags & InputTarget::FLAG_SPLIT;
1625 assert(! (resumeWithAppendedMotionSample && isSplit));
1626
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001627 // Skip this event if the connection status is not normal.
Jeff Brown519e0242010-09-15 15:18:56 -07001628 // We don't want to enqueue additional outbound events if the connection is broken.
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001629 if (connection->status != Connection::STATUS_NORMAL) {
Jeff Brownb6997262010-10-08 22:31:17 -07001630#if DEBUG_DISPATCH_CYCLE
1631 LOGD("channel '%s' ~ Dropping event because the channel status is %s",
Jeff Brownb88102f2010-09-08 11:49:43 -07001632 connection->getInputChannelName(), connection->getStatusLabel());
Jeff Brownb6997262010-10-08 22:31:17 -07001633#endif
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001634 return;
1635 }
1636
Jeff Brown01ce2e92010-09-26 22:20:12 -07001637 // Split a motion event if needed.
1638 if (isSplit) {
1639 assert(eventEntry->type == EventEntry::TYPE_MOTION);
1640
1641 MotionEntry* originalMotionEntry = static_cast<MotionEntry*>(eventEntry);
1642 if (inputTarget->pointerIds.count() != originalMotionEntry->pointerCount) {
1643 MotionEntry* splitMotionEntry = splitMotionEvent(
1644 originalMotionEntry, inputTarget->pointerIds);
Jeff Brown58a2da82011-01-25 16:02:22 -08001645 if (!splitMotionEntry) {
1646 return; // split event was dropped
1647 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001648#if DEBUG_FOCUS
1649 LOGD("channel '%s' ~ Split motion event.",
1650 connection->getInputChannelName());
1651 logOutboundMotionDetailsLocked(" ", splitMotionEntry);
1652#endif
1653 eventEntry = splitMotionEntry;
1654 }
1655 }
1656
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001657 // Resume the dispatch cycle with a freshly appended motion sample.
1658 // First we check that the last dispatch entry in the outbound queue is for the same
1659 // motion event to which we appended the motion sample. If we find such a dispatch
1660 // entry, and if it is currently in progress then we try to stream the new sample.
1661 bool wasEmpty = connection->outboundQueue.isEmpty();
1662
1663 if (! wasEmpty && resumeWithAppendedMotionSample) {
1664 DispatchEntry* motionEventDispatchEntry =
1665 connection->findQueuedDispatchEntryForEvent(eventEntry);
1666 if (motionEventDispatchEntry) {
1667 // If the dispatch entry is not in progress, then we must be busy dispatching an
1668 // earlier event. Not a problem, the motion event is on the outbound queue and will
1669 // be dispatched later.
1670 if (! motionEventDispatchEntry->inProgress) {
1671#if DEBUG_BATCHING
1672 LOGD("channel '%s' ~ Not streaming because the motion event has "
1673 "not yet been dispatched. "
1674 "(Waiting for earlier events to be consumed.)",
1675 connection->getInputChannelName());
1676#endif
1677 return;
1678 }
1679
1680 // If the dispatch entry is in progress but it already has a tail of pending
1681 // motion samples, then it must mean that the shared memory buffer filled up.
1682 // Not a problem, when this dispatch cycle is finished, we will eventually start
1683 // a new dispatch cycle to process the tail and that tail includes the newly
1684 // appended motion sample.
1685 if (motionEventDispatchEntry->tailMotionSample) {
1686#if DEBUG_BATCHING
1687 LOGD("channel '%s' ~ Not streaming because no new samples can "
1688 "be appended to the motion event in this dispatch cycle. "
1689 "(Waiting for next dispatch cycle to start.)",
1690 connection->getInputChannelName());
1691#endif
1692 return;
1693 }
1694
1695 // The dispatch entry is in progress and is still potentially open for streaming.
1696 // Try to stream the new motion sample. This might fail if the consumer has already
1697 // consumed the motion event (or if the channel is broken).
Jeff Brown01ce2e92010-09-26 22:20:12 -07001698 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
1699 MotionSample* appendedMotionSample = motionEntry->lastSample;
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001700 status_t status;
1701 if (motionEventDispatchEntry->scaleFactor == 1.0f) {
1702 status = connection->inputPublisher.appendMotionSample(
1703 appendedMotionSample->eventTime, appendedMotionSample->pointerCoords);
1704 } else {
1705 PointerCoords scaledCoords[MAX_POINTERS];
1706 for (size_t i = 0; i < motionEntry->pointerCount; i++) {
1707 scaledCoords[i] = appendedMotionSample->pointerCoords[i];
1708 scaledCoords[i].scale(motionEventDispatchEntry->scaleFactor);
1709 }
1710 status = connection->inputPublisher.appendMotionSample(
1711 appendedMotionSample->eventTime, scaledCoords);
1712 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001713 if (status == OK) {
1714#if DEBUG_BATCHING
1715 LOGD("channel '%s' ~ Successfully streamed new motion sample.",
1716 connection->getInputChannelName());
1717#endif
1718 return;
1719 }
1720
1721#if DEBUG_BATCHING
1722 if (status == NO_MEMORY) {
1723 LOGD("channel '%s' ~ Could not append motion sample to currently "
1724 "dispatched move event because the shared memory buffer is full. "
1725 "(Waiting for next dispatch cycle to start.)",
1726 connection->getInputChannelName());
1727 } else if (status == status_t(FAILED_TRANSACTION)) {
1728 LOGD("channel '%s' ~ Could not append motion sample to currently "
Jeff Brown349703e2010-06-22 01:27:15 -07001729 "dispatched move event because the event has already been consumed. "
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001730 "(Waiting for next dispatch cycle to start.)",
1731 connection->getInputChannelName());
1732 } else {
1733 LOGD("channel '%s' ~ Could not append motion sample to currently "
1734 "dispatched move event due to an error, status=%d. "
1735 "(Waiting for next dispatch cycle to start.)",
1736 connection->getInputChannelName(), status);
1737 }
1738#endif
1739 // Failed to stream. Start a new tail of pending motion samples to dispatch
1740 // in the next cycle.
1741 motionEventDispatchEntry->tailMotionSample = appendedMotionSample;
1742 return;
1743 }
1744 }
1745
1746 // This is a new event.
1747 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Jeff Brownb88102f2010-09-08 11:49:43 -07001748 DispatchEntry* dispatchEntry = mAllocator.obtainDispatchEntry(eventEntry, // increments ref
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001749 inputTarget->flags, inputTarget->xOffset, inputTarget->yOffset,
1750 inputTarget->scaleFactor);
Jeff Brown519e0242010-09-15 15:18:56 -07001751 if (dispatchEntry->hasForegroundTarget()) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001752 incrementPendingForegroundDispatchesLocked(eventEntry);
Jeff Brown6ec402b2010-07-28 15:48:59 -07001753 }
1754
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001755 // Handle the case where we could not stream a new motion sample because the consumer has
1756 // already consumed the motion event (otherwise the corresponding dispatch entry would
1757 // still be in the outbound queue for this connection). We set the head motion sample
1758 // to the list starting with the newly appended motion sample.
1759 if (resumeWithAppendedMotionSample) {
1760#if DEBUG_BATCHING
1761 LOGD("channel '%s' ~ Preparing a new dispatch cycle for additional motion samples "
1762 "that cannot be streamed because the motion event has already been consumed.",
1763 connection->getInputChannelName());
1764#endif
1765 MotionSample* appendedMotionSample = static_cast<MotionEntry*>(eventEntry)->lastSample;
1766 dispatchEntry->headMotionSample = appendedMotionSample;
1767 }
1768
1769 // Enqueue the dispatch entry.
1770 connection->outboundQueue.enqueueAtTail(dispatchEntry);
1771
1772 // If the outbound queue was previously empty, start the dispatch cycle going.
1773 if (wasEmpty) {
Jeff Brown7fbdc842010-06-17 20:52:56 -07001774 activateConnectionLocked(connection.get());
Jeff Brown519e0242010-09-15 15:18:56 -07001775 startDispatchCycleLocked(currentTime, connection);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001776 }
1777}
1778
Jeff Brown7fbdc842010-06-17 20:52:56 -07001779void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Jeff Brown519e0242010-09-15 15:18:56 -07001780 const sp<Connection>& connection) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001781#if DEBUG_DISPATCH_CYCLE
1782 LOGD("channel '%s' ~ startDispatchCycle",
1783 connection->getInputChannelName());
1784#endif
1785
1786 assert(connection->status == Connection::STATUS_NORMAL);
1787 assert(! connection->outboundQueue.isEmpty());
1788
Jeff Brownb88102f2010-09-08 11:49:43 -07001789 DispatchEntry* dispatchEntry = connection->outboundQueue.headSentinel.next;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001790 assert(! dispatchEntry->inProgress);
1791
Jeff Brownb88102f2010-09-08 11:49:43 -07001792 // Mark the dispatch entry as in progress.
1793 dispatchEntry->inProgress = true;
1794
1795 // Update the connection's input state.
Jeff Brown01ce2e92010-09-26 22:20:12 -07001796 EventEntry* eventEntry = dispatchEntry->eventEntry;
Jeff Browncc0c1592011-02-19 05:07:28 -08001797 connection->inputState.trackEvent(eventEntry);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001798
1799 // Publish the event.
1800 status_t status;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001801 switch (eventEntry->type) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001802 case EventEntry::TYPE_KEY: {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001803 KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001804
1805 // Apply target flags.
1806 int32_t action = keyEntry->action;
1807 int32_t flags = keyEntry->flags;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001808
1809 // Publish the key event.
Jeff Brownc5ed5912010-07-14 18:48:53 -07001810 status = connection->inputPublisher.publishKeyEvent(keyEntry->deviceId, keyEntry->source,
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001811 action, flags, keyEntry->keyCode, keyEntry->scanCode,
1812 keyEntry->metaState, keyEntry->repeatCount, keyEntry->downTime,
1813 keyEntry->eventTime);
1814
1815 if (status) {
1816 LOGE("channel '%s' ~ Could not publish key event, "
1817 "status=%d", connection->getInputChannelName(), status);
Jeff Brownb6997262010-10-08 22:31:17 -07001818 abortBrokenDispatchCycleLocked(currentTime, connection);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001819 return;
1820 }
1821 break;
1822 }
1823
1824 case EventEntry::TYPE_MOTION: {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001825 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001826
1827 // Apply target flags.
1828 int32_t action = motionEntry->action;
Jeff Brown85a31762010-09-01 17:01:00 -07001829 int32_t flags = motionEntry->flags;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001830 if (dispatchEntry->targetFlags & InputTarget::FLAG_OUTSIDE) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001831 action = AMOTION_EVENT_ACTION_OUTSIDE;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001832 }
Jeff Brown85a31762010-09-01 17:01:00 -07001833 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
1834 flags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
1835 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001836
1837 // If headMotionSample is non-NULL, then it points to the first new sample that we
1838 // were unable to dispatch during the previous cycle so we resume dispatching from
1839 // that point in the list of motion samples.
1840 // Otherwise, we just start from the first sample of the motion event.
1841 MotionSample* firstMotionSample = dispatchEntry->headMotionSample;
1842 if (! firstMotionSample) {
1843 firstMotionSample = & motionEntry->firstSample;
1844 }
1845
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001846 PointerCoords scaledCoords[MAX_POINTERS];
1847 const PointerCoords* usingCoords = firstMotionSample->pointerCoords;
1848
Jeff Brownd3616592010-07-16 17:21:06 -07001849 // Set the X and Y offset depending on the input source.
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001850 float xOffset, yOffset, scaleFactor;
Jeff Brownd3616592010-07-16 17:21:06 -07001851 if (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) {
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001852 scaleFactor = dispatchEntry->scaleFactor;
1853 xOffset = dispatchEntry->xOffset * scaleFactor;
1854 yOffset = dispatchEntry->yOffset * scaleFactor;
1855 if (scaleFactor != 1.0f) {
1856 for (size_t i = 0; i < motionEntry->pointerCount; i++) {
1857 scaledCoords[i] = firstMotionSample->pointerCoords[i];
1858 scaledCoords[i].scale(scaleFactor);
1859 }
1860 usingCoords = scaledCoords;
1861 }
Jeff Brownd3616592010-07-16 17:21:06 -07001862 } else {
1863 xOffset = 0.0f;
1864 yOffset = 0.0f;
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001865 scaleFactor = 1.0f;
Jeff Brownd3616592010-07-16 17:21:06 -07001866 }
1867
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001868 // Publish the motion event and the first motion sample.
1869 status = connection->inputPublisher.publishMotionEvent(motionEntry->deviceId,
Jeff Brown85a31762010-09-01 17:01:00 -07001870 motionEntry->source, action, flags, motionEntry->edgeFlags, motionEntry->metaState,
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001871 xOffset, yOffset, motionEntry->xPrecision, motionEntry->yPrecision,
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001872 motionEntry->downTime, firstMotionSample->eventTime,
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001873 motionEntry->pointerCount, motionEntry->pointerIds, usingCoords);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001874
1875 if (status) {
1876 LOGE("channel '%s' ~ Could not publish motion event, "
1877 "status=%d", connection->getInputChannelName(), status);
Jeff Brownb6997262010-10-08 22:31:17 -07001878 abortBrokenDispatchCycleLocked(currentTime, connection);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001879 return;
1880 }
1881
1882 // Append additional motion samples.
1883 MotionSample* nextMotionSample = firstMotionSample->next;
1884 for (; nextMotionSample != NULL; nextMotionSample = nextMotionSample->next) {
Dianne Hackborne7d25b72011-05-09 21:19:26 -07001885 if ((motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) != 0 && scaleFactor != 1.0f) {
1886 for (size_t i = 0; i < motionEntry->pointerCount; i++) {
1887 scaledCoords[i] = nextMotionSample->pointerCoords[i];
1888 scaledCoords[i].scale(scaleFactor);
1889 }
1890 } else {
1891 usingCoords = nextMotionSample->pointerCoords;
1892 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001893 status = connection->inputPublisher.appendMotionSample(
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001894 nextMotionSample->eventTime, usingCoords);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001895 if (status == NO_MEMORY) {
1896#if DEBUG_DISPATCH_CYCLE
1897 LOGD("channel '%s' ~ Shared memory buffer full. Some motion samples will "
1898 "be sent in the next dispatch cycle.",
1899 connection->getInputChannelName());
1900#endif
1901 break;
1902 }
1903 if (status != OK) {
1904 LOGE("channel '%s' ~ Could not append motion sample "
1905 "for a reason other than out of memory, status=%d",
1906 connection->getInputChannelName(), status);
Jeff Brownb6997262010-10-08 22:31:17 -07001907 abortBrokenDispatchCycleLocked(currentTime, connection);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001908 return;
1909 }
1910 }
1911
1912 // Remember the next motion sample that we could not dispatch, in case we ran out
1913 // of space in the shared memory buffer.
1914 dispatchEntry->tailMotionSample = nextMotionSample;
1915 break;
1916 }
1917
1918 default: {
1919 assert(false);
1920 }
1921 }
1922
1923 // Send the dispatch signal.
1924 status = connection->inputPublisher.sendDispatchSignal();
1925 if (status) {
1926 LOGE("channel '%s' ~ Could not send dispatch signal, status=%d",
1927 connection->getInputChannelName(), status);
Jeff Brownb6997262010-10-08 22:31:17 -07001928 abortBrokenDispatchCycleLocked(currentTime, connection);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001929 return;
1930 }
1931
1932 // Record information about the newly started dispatch cycle.
Jeff Brown01ce2e92010-09-26 22:20:12 -07001933 connection->lastEventTime = eventEntry->eventTime;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001934 connection->lastDispatchTime = currentTime;
1935
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001936 // Notify other system components.
1937 onDispatchCycleStartedLocked(currentTime, connection);
1938}
1939
Jeff Brown7fbdc842010-06-17 20:52:56 -07001940void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Jeff Brown3915bb82010-11-05 15:02:16 -07001941 const sp<Connection>& connection, bool handled) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001942#if DEBUG_DISPATCH_CYCLE
Jeff Brown9c3cda02010-06-15 01:31:58 -07001943 LOGD("channel '%s' ~ finishDispatchCycle - %01.1fms since event, "
Jeff Brown3915bb82010-11-05 15:02:16 -07001944 "%01.1fms since dispatch, handled=%s",
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001945 connection->getInputChannelName(),
1946 connection->getEventLatencyMillis(currentTime),
Jeff Brown3915bb82010-11-05 15:02:16 -07001947 connection->getDispatchLatencyMillis(currentTime),
1948 toString(handled));
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001949#endif
1950
Jeff Brown9c3cda02010-06-15 01:31:58 -07001951 if (connection->status == Connection::STATUS_BROKEN
1952 || connection->status == Connection::STATUS_ZOMBIE) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001953 return;
1954 }
1955
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001956 // Reset the publisher since the event has been consumed.
1957 // We do this now so that the publisher can release some of its internal resources
1958 // while waiting for the next dispatch cycle to begin.
1959 status_t status = connection->inputPublisher.reset();
1960 if (status) {
1961 LOGE("channel '%s' ~ Could not reset publisher, status=%d",
1962 connection->getInputChannelName(), status);
Jeff Brownb6997262010-10-08 22:31:17 -07001963 abortBrokenDispatchCycleLocked(currentTime, connection);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001964 return;
1965 }
1966
Jeff Brown3915bb82010-11-05 15:02:16 -07001967 // Notify other system components and prepare to start the next dispatch cycle.
1968 onDispatchCycleFinishedLocked(currentTime, connection, handled);
Jeff Brownb88102f2010-09-08 11:49:43 -07001969}
1970
1971void InputDispatcher::startNextDispatchCycleLocked(nsecs_t currentTime,
1972 const sp<Connection>& connection) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001973 // Start the next dispatch cycle for this connection.
1974 while (! connection->outboundQueue.isEmpty()) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001975 DispatchEntry* dispatchEntry = connection->outboundQueue.headSentinel.next;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001976 if (dispatchEntry->inProgress) {
1977 // Finish or resume current event in progress.
1978 if (dispatchEntry->tailMotionSample) {
1979 // We have a tail of undispatched motion samples.
1980 // Reuse the same DispatchEntry and start a new cycle.
1981 dispatchEntry->inProgress = false;
1982 dispatchEntry->headMotionSample = dispatchEntry->tailMotionSample;
1983 dispatchEntry->tailMotionSample = NULL;
Jeff Brown519e0242010-09-15 15:18:56 -07001984 startDispatchCycleLocked(currentTime, connection);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001985 return;
1986 }
1987 // Finished.
1988 connection->outboundQueue.dequeueAtHead();
Jeff Brown519e0242010-09-15 15:18:56 -07001989 if (dispatchEntry->hasForegroundTarget()) {
1990 decrementPendingForegroundDispatchesLocked(dispatchEntry->eventEntry);
Jeff Brown6ec402b2010-07-28 15:48:59 -07001991 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001992 mAllocator.releaseDispatchEntry(dispatchEntry);
1993 } else {
1994 // If the head is not in progress, then we must have already dequeued the in
Jeff Brown519e0242010-09-15 15:18:56 -07001995 // progress event, which means we actually aborted it.
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001996 // So just start the next event for this connection.
Jeff Brown519e0242010-09-15 15:18:56 -07001997 startDispatchCycleLocked(currentTime, connection);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001998 return;
1999 }
2000 }
2001
2002 // Outbound queue is empty, deactivate the connection.
Jeff Brown7fbdc842010-06-17 20:52:56 -07002003 deactivateConnectionLocked(connection.get());
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002004}
2005
Jeff Brownb6997262010-10-08 22:31:17 -07002006void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
2007 const sp<Connection>& connection) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002008#if DEBUG_DISPATCH_CYCLE
Jeff Brown83c09682010-12-23 17:50:18 -08002009 LOGD("channel '%s' ~ abortBrokenDispatchCycle",
2010 connection->getInputChannelName());
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002011#endif
2012
Jeff Brownb88102f2010-09-08 11:49:43 -07002013 // Clear the outbound queue.
Jeff Brown519e0242010-09-15 15:18:56 -07002014 drainOutboundQueueLocked(connection.get());
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002015
Jeff Brownb6997262010-10-08 22:31:17 -07002016 // The connection appears to be unrecoverably broken.
Jeff Brown9c3cda02010-06-15 01:31:58 -07002017 // Ignore already broken or zombie connections.
Jeff Brownb6997262010-10-08 22:31:17 -07002018 if (connection->status == Connection::STATUS_NORMAL) {
2019 connection->status = Connection::STATUS_BROKEN;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002020
Jeff Brownb6997262010-10-08 22:31:17 -07002021 // Notify other system components.
2022 onDispatchCycleBrokenLocked(currentTime, connection);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002023 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002024}
2025
Jeff Brown519e0242010-09-15 15:18:56 -07002026void InputDispatcher::drainOutboundQueueLocked(Connection* connection) {
2027 while (! connection->outboundQueue.isEmpty()) {
2028 DispatchEntry* dispatchEntry = connection->outboundQueue.dequeueAtHead();
2029 if (dispatchEntry->hasForegroundTarget()) {
2030 decrementPendingForegroundDispatchesLocked(dispatchEntry->eventEntry);
Jeff Brownb88102f2010-09-08 11:49:43 -07002031 }
2032 mAllocator.releaseDispatchEntry(dispatchEntry);
Jeff Brownb88102f2010-09-08 11:49:43 -07002033 }
2034
Jeff Brown519e0242010-09-15 15:18:56 -07002035 deactivateConnectionLocked(connection);
Jeff Brownb88102f2010-09-08 11:49:43 -07002036}
2037
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002038int InputDispatcher::handleReceiveCallback(int receiveFd, int events, void* data) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002039 InputDispatcher* d = static_cast<InputDispatcher*>(data);
2040
2041 { // acquire lock
2042 AutoMutex _l(d->mLock);
2043
2044 ssize_t connectionIndex = d->mConnectionsByReceiveFd.indexOfKey(receiveFd);
2045 if (connectionIndex < 0) {
2046 LOGE("Received spurious receive callback for unknown input channel. "
2047 "fd=%d, events=0x%x", receiveFd, events);
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002048 return 0; // remove the callback
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002049 }
2050
Jeff Brown7fbdc842010-06-17 20:52:56 -07002051 nsecs_t currentTime = now();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002052
2053 sp<Connection> connection = d->mConnectionsByReceiveFd.valueAt(connectionIndex);
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002054 if (events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP)) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002055 LOGE("channel '%s' ~ Consumer closed input channel or an error occurred. "
2056 "events=0x%x", connection->getInputChannelName(), events);
Jeff Brownb6997262010-10-08 22:31:17 -07002057 d->abortBrokenDispatchCycleLocked(currentTime, connection);
Jeff Brown9c3cda02010-06-15 01:31:58 -07002058 d->runCommandsLockedInterruptible();
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002059 return 0; // remove the callback
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002060 }
2061
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002062 if (! (events & ALOOPER_EVENT_INPUT)) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002063 LOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
2064 "events=0x%x", connection->getInputChannelName(), events);
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002065 return 1;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002066 }
2067
Jeff Brown3915bb82010-11-05 15:02:16 -07002068 bool handled = false;
Jeff Brown49ed71d2010-12-06 17:13:33 -08002069 status_t status = connection->inputPublisher.receiveFinishedSignal(&handled);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002070 if (status) {
2071 LOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
2072 connection->getInputChannelName(), status);
Jeff Brownb6997262010-10-08 22:31:17 -07002073 d->abortBrokenDispatchCycleLocked(currentTime, connection);
Jeff Brown9c3cda02010-06-15 01:31:58 -07002074 d->runCommandsLockedInterruptible();
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002075 return 0; // remove the callback
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002076 }
2077
Jeff Brown3915bb82010-11-05 15:02:16 -07002078 d->finishDispatchCycleLocked(currentTime, connection, handled);
Jeff Brown9c3cda02010-06-15 01:31:58 -07002079 d->runCommandsLockedInterruptible();
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002080 return 1;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002081 } // release lock
2082}
2083
Jeff Brownb6997262010-10-08 22:31:17 -07002084void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Jeff Brown524ee642011-03-29 15:11:34 -07002085 const CancelationOptions& options) {
Jeff Brownb6997262010-10-08 22:31:17 -07002086 for (size_t i = 0; i < mConnectionsByReceiveFd.size(); i++) {
2087 synthesizeCancelationEventsForConnectionLocked(
Jeff Brown524ee642011-03-29 15:11:34 -07002088 mConnectionsByReceiveFd.valueAt(i), options);
Jeff Brownb6997262010-10-08 22:31:17 -07002089 }
2090}
2091
2092void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Jeff Brown524ee642011-03-29 15:11:34 -07002093 const sp<InputChannel>& channel, const CancelationOptions& options) {
Jeff Brownb6997262010-10-08 22:31:17 -07002094 ssize_t index = getConnectionIndexLocked(channel);
2095 if (index >= 0) {
2096 synthesizeCancelationEventsForConnectionLocked(
Jeff Brown524ee642011-03-29 15:11:34 -07002097 mConnectionsByReceiveFd.valueAt(index), options);
Jeff Brownb6997262010-10-08 22:31:17 -07002098 }
2099}
2100
2101void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
Jeff Brown524ee642011-03-29 15:11:34 -07002102 const sp<Connection>& connection, const CancelationOptions& options) {
Jeff Brownb6997262010-10-08 22:31:17 -07002103 nsecs_t currentTime = now();
2104
2105 mTempCancelationEvents.clear();
2106 connection->inputState.synthesizeCancelationEvents(currentTime, & mAllocator,
2107 mTempCancelationEvents, options);
2108
2109 if (! mTempCancelationEvents.isEmpty()
2110 && connection->status != Connection::STATUS_BROKEN) {
2111#if DEBUG_OUTBOUND_EVENT_DETAILS
2112 LOGD("channel '%s' ~ Synthesized %d cancelation events to bring channel back in sync "
Jeff Brown524ee642011-03-29 15:11:34 -07002113 "with reality: %s, mode=%d.",
2114 connection->getInputChannelName(), mTempCancelationEvents.size(),
2115 options.reason, options.mode);
Jeff Brownb6997262010-10-08 22:31:17 -07002116#endif
2117 for (size_t i = 0; i < mTempCancelationEvents.size(); i++) {
2118 EventEntry* cancelationEventEntry = mTempCancelationEvents.itemAt(i);
2119 switch (cancelationEventEntry->type) {
2120 case EventEntry::TYPE_KEY:
2121 logOutboundKeyDetailsLocked("cancel - ",
2122 static_cast<KeyEntry*>(cancelationEventEntry));
2123 break;
2124 case EventEntry::TYPE_MOTION:
2125 logOutboundMotionDetailsLocked("cancel - ",
2126 static_cast<MotionEntry*>(cancelationEventEntry));
2127 break;
2128 }
2129
2130 int32_t xOffset, yOffset;
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002131 float scaleFactor;
Jeff Brownb6997262010-10-08 22:31:17 -07002132 const InputWindow* window = getWindowLocked(connection->inputChannel);
2133 if (window) {
2134 xOffset = -window->frameLeft;
2135 yOffset = -window->frameTop;
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002136 scaleFactor = window->scaleFactor;
Jeff Brownb6997262010-10-08 22:31:17 -07002137 } else {
2138 xOffset = 0;
2139 yOffset = 0;
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002140 scaleFactor = 1.0f;
Jeff Brownb6997262010-10-08 22:31:17 -07002141 }
2142
2143 DispatchEntry* cancelationDispatchEntry =
2144 mAllocator.obtainDispatchEntry(cancelationEventEntry, // increments ref
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002145 0, xOffset, yOffset, scaleFactor);
Jeff Brownb6997262010-10-08 22:31:17 -07002146 connection->outboundQueue.enqueueAtTail(cancelationDispatchEntry);
2147
2148 mAllocator.releaseEventEntry(cancelationEventEntry);
2149 }
2150
2151 if (!connection->outboundQueue.headSentinel.next->inProgress) {
2152 startDispatchCycleLocked(currentTime, connection);
2153 }
2154 }
2155}
2156
Jeff Brown01ce2e92010-09-26 22:20:12 -07002157InputDispatcher::MotionEntry*
2158InputDispatcher::splitMotionEvent(const MotionEntry* originalMotionEntry, BitSet32 pointerIds) {
2159 assert(pointerIds.value != 0);
2160
2161 uint32_t splitPointerIndexMap[MAX_POINTERS];
2162 int32_t splitPointerIds[MAX_POINTERS];
2163 PointerCoords splitPointerCoords[MAX_POINTERS];
2164
2165 uint32_t originalPointerCount = originalMotionEntry->pointerCount;
2166 uint32_t splitPointerCount = 0;
2167
2168 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
2169 originalPointerIndex++) {
2170 int32_t pointerId = uint32_t(originalMotionEntry->pointerIds[originalPointerIndex]);
2171 if (pointerIds.hasBit(pointerId)) {
2172 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
2173 splitPointerIds[splitPointerCount] = pointerId;
Jeff Brown96ad3972011-03-09 17:39:48 -08002174 splitPointerCoords[splitPointerCount].copyFrom(
2175 originalMotionEntry->firstSample.pointerCoords[originalPointerIndex]);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002176 splitPointerCount += 1;
2177 }
2178 }
Jeff Brown58a2da82011-01-25 16:02:22 -08002179
2180 if (splitPointerCount != pointerIds.count()) {
2181 // This is bad. We are missing some of the pointers that we expected to deliver.
2182 // Most likely this indicates that we received an ACTION_MOVE events that has
2183 // different pointer ids than we expected based on the previous ACTION_DOWN
2184 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
2185 // in this way.
2186 LOGW("Dropping split motion event because the pointer count is %d but "
2187 "we expected there to be %d pointers. This probably means we received "
2188 "a broken sequence of pointer ids from the input device.",
2189 splitPointerCount, pointerIds.count());
2190 return NULL;
2191 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07002192
2193 int32_t action = originalMotionEntry->action;
2194 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
2195 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
2196 || maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2197 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
2198 int32_t pointerId = originalMotionEntry->pointerIds[originalPointerIndex];
2199 if (pointerIds.hasBit(pointerId)) {
2200 if (pointerIds.count() == 1) {
2201 // The first/last pointer went down/up.
2202 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
2203 ? AMOTION_EVENT_ACTION_DOWN : AMOTION_EVENT_ACTION_UP;
Jeff Brown9a01d052010-09-27 16:35:11 -07002204 } else {
2205 // A secondary pointer went down/up.
2206 uint32_t splitPointerIndex = 0;
2207 while (pointerId != splitPointerIds[splitPointerIndex]) {
2208 splitPointerIndex += 1;
2209 }
2210 action = maskedAction | (splitPointerIndex
2211 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002212 }
2213 } else {
2214 // An unrelated pointer changed.
2215 action = AMOTION_EVENT_ACTION_MOVE;
2216 }
2217 }
2218
2219 MotionEntry* splitMotionEntry = mAllocator.obtainMotionEntry(
2220 originalMotionEntry->eventTime,
2221 originalMotionEntry->deviceId,
2222 originalMotionEntry->source,
2223 originalMotionEntry->policyFlags,
2224 action,
2225 originalMotionEntry->flags,
2226 originalMotionEntry->metaState,
2227 originalMotionEntry->edgeFlags,
2228 originalMotionEntry->xPrecision,
2229 originalMotionEntry->yPrecision,
2230 originalMotionEntry->downTime,
2231 splitPointerCount, splitPointerIds, splitPointerCoords);
2232
2233 for (MotionSample* originalMotionSample = originalMotionEntry->firstSample.next;
2234 originalMotionSample != NULL; originalMotionSample = originalMotionSample->next) {
2235 for (uint32_t splitPointerIndex = 0; splitPointerIndex < splitPointerCount;
2236 splitPointerIndex++) {
2237 uint32_t originalPointerIndex = splitPointerIndexMap[splitPointerIndex];
Jeff Brown96ad3972011-03-09 17:39:48 -08002238 splitPointerCoords[splitPointerIndex].copyFrom(
2239 originalMotionSample->pointerCoords[originalPointerIndex]);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002240 }
2241
2242 mAllocator.appendMotionSample(splitMotionEntry, originalMotionSample->eventTime,
2243 splitPointerCoords);
2244 }
2245
2246 return splitMotionEntry;
2247}
2248
Jeff Brown9c3cda02010-06-15 01:31:58 -07002249void InputDispatcher::notifyConfigurationChanged(nsecs_t eventTime) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002250#if DEBUG_INBOUND_EVENT_DETAILS
Jeff Brown9c3cda02010-06-15 01:31:58 -07002251 LOGD("notifyConfigurationChanged - eventTime=%lld", eventTime);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002252#endif
2253
Jeff Brownb88102f2010-09-08 11:49:43 -07002254 bool needWake;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002255 { // acquire lock
2256 AutoMutex _l(mLock);
2257
Jeff Brown7fbdc842010-06-17 20:52:56 -07002258 ConfigurationChangedEntry* newEntry = mAllocator.obtainConfigurationChangedEntry(eventTime);
Jeff Brownb88102f2010-09-08 11:49:43 -07002259 needWake = enqueueInboundEventLocked(newEntry);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002260 } // release lock
2261
Jeff Brownb88102f2010-09-08 11:49:43 -07002262 if (needWake) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002263 mLooper->wake();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002264 }
2265}
2266
Jeff Brown58a2da82011-01-25 16:02:22 -08002267void InputDispatcher::notifyKey(nsecs_t eventTime, int32_t deviceId, uint32_t source,
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002268 uint32_t policyFlags, int32_t action, int32_t flags,
2269 int32_t keyCode, int32_t scanCode, int32_t metaState, nsecs_t downTime) {
2270#if DEBUG_INBOUND_EVENT_DETAILS
Jeff Brown90655042010-12-02 13:50:46 -08002271 LOGD("notifyKey - eventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, action=0x%x, "
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002272 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%lld",
Jeff Brownc5ed5912010-07-14 18:48:53 -07002273 eventTime, deviceId, source, policyFlags, action, flags,
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002274 keyCode, scanCode, metaState, downTime);
2275#endif
Jeff Brown01ce2e92010-09-26 22:20:12 -07002276 if (! validateKeyEvent(action)) {
2277 return;
2278 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002279
Jeff Brown1f245102010-11-18 20:53:46 -08002280 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
2281 policyFlags |= POLICY_FLAG_VIRTUAL;
2282 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
2283 }
Jeff Brown924c4d42011-03-07 16:40:47 -08002284 if (policyFlags & POLICY_FLAG_ALT) {
2285 metaState |= AMETA_ALT_ON | AMETA_ALT_LEFT_ON;
2286 }
2287 if (policyFlags & POLICY_FLAG_ALT_GR) {
2288 metaState |= AMETA_ALT_ON | AMETA_ALT_RIGHT_ON;
2289 }
2290 if (policyFlags & POLICY_FLAG_SHIFT) {
2291 metaState |= AMETA_SHIFT_ON | AMETA_SHIFT_LEFT_ON;
2292 }
2293 if (policyFlags & POLICY_FLAG_CAPS_LOCK) {
2294 metaState |= AMETA_CAPS_LOCK_ON;
2295 }
2296 if (policyFlags & POLICY_FLAG_FUNCTION) {
2297 metaState |= AMETA_FUNCTION_ON;
2298 }
Jeff Brown1f245102010-11-18 20:53:46 -08002299
Jeff Browne20c9e02010-10-11 14:20:19 -07002300 policyFlags |= POLICY_FLAG_TRUSTED;
Jeff Brown1f245102010-11-18 20:53:46 -08002301
2302 KeyEvent event;
2303 event.initialize(deviceId, source, action, flags, keyCode, scanCode,
2304 metaState, 0, downTime, eventTime);
2305
2306 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
2307
2308 if (policyFlags & POLICY_FLAG_WOKE_HERE) {
2309 flags |= AKEY_EVENT_FLAG_WOKE_HERE;
2310 }
Jeff Brownb6997262010-10-08 22:31:17 -07002311
Jeff Brownb88102f2010-09-08 11:49:43 -07002312 bool needWake;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002313 { // acquire lock
2314 AutoMutex _l(mLock);
2315
Jeff Brown7fbdc842010-06-17 20:52:56 -07002316 int32_t repeatCount = 0;
2317 KeyEntry* newEntry = mAllocator.obtainKeyEntry(eventTime,
Jeff Brownc5ed5912010-07-14 18:48:53 -07002318 deviceId, source, policyFlags, action, flags, keyCode, scanCode,
Jeff Brown7fbdc842010-06-17 20:52:56 -07002319 metaState, repeatCount, downTime);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002320
Jeff Brownb88102f2010-09-08 11:49:43 -07002321 needWake = enqueueInboundEventLocked(newEntry);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002322 } // release lock
2323
Jeff Brownb88102f2010-09-08 11:49:43 -07002324 if (needWake) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002325 mLooper->wake();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002326 }
2327}
2328
Jeff Brown58a2da82011-01-25 16:02:22 -08002329void InputDispatcher::notifyMotion(nsecs_t eventTime, int32_t deviceId, uint32_t source,
Jeff Brown85a31762010-09-01 17:01:00 -07002330 uint32_t policyFlags, int32_t action, int32_t flags, int32_t metaState, int32_t edgeFlags,
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002331 uint32_t pointerCount, const int32_t* pointerIds, const PointerCoords* pointerCoords,
2332 float xPrecision, float yPrecision, nsecs_t downTime) {
2333#if DEBUG_INBOUND_EVENT_DETAILS
Jeff Brown90655042010-12-02 13:50:46 -08002334 LOGD("notifyMotion - eventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, "
Jeff Brown85a31762010-09-01 17:01:00 -07002335 "action=0x%x, flags=0x%x, metaState=0x%x, edgeFlags=0x%x, "
2336 "xPrecision=%f, yPrecision=%f, downTime=%lld",
2337 eventTime, deviceId, source, policyFlags, action, flags, metaState, edgeFlags,
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002338 xPrecision, yPrecision, downTime);
2339 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brown8d608662010-08-30 03:02:23 -07002340 LOGD(" Pointer %d: id=%d, x=%f, y=%f, pressure=%f, size=%f, "
Jeff Brown85a31762010-09-01 17:01:00 -07002341 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
Jeff Brown8d608662010-08-30 03:02:23 -07002342 "orientation=%f",
Jeff Brown91c69ab2011-02-14 17:03:18 -08002343 i, pointerIds[i],
Jeff Brownebbd5d12011-02-17 13:01:34 -08002344 pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
2345 pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
2346 pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
2347 pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
2348 pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
2349 pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
2350 pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
2351 pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
2352 pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002353 }
2354#endif
Jeff Brown01ce2e92010-09-26 22:20:12 -07002355 if (! validateMotionEvent(action, pointerCount, pointerIds)) {
2356 return;
2357 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002358
Jeff Browne20c9e02010-10-11 14:20:19 -07002359 policyFlags |= POLICY_FLAG_TRUSTED;
Jeff Brown56194eb2011-03-02 19:23:13 -08002360 mPolicy->interceptMotionBeforeQueueing(eventTime, /*byref*/ policyFlags);
Jeff Brownb6997262010-10-08 22:31:17 -07002361
Jeff Brownb88102f2010-09-08 11:49:43 -07002362 bool needWake;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002363 { // acquire lock
2364 AutoMutex _l(mLock);
2365
2366 // Attempt batching and streaming of move events.
Jeff Browncc0c1592011-02-19 05:07:28 -08002367 if (action == AMOTION_EVENT_ACTION_MOVE
2368 || action == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002369 // BATCHING CASE
2370 //
2371 // Try to append a move sample to the tail of the inbound queue for this device.
2372 // Give up if we encounter a non-move motion event for this device since that
2373 // means we cannot append any new samples until a new motion event has started.
Jeff Brownb88102f2010-09-08 11:49:43 -07002374 for (EventEntry* entry = mInboundQueue.tailSentinel.prev;
2375 entry != & mInboundQueue.headSentinel; entry = entry->prev) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002376 if (entry->type != EventEntry::TYPE_MOTION) {
2377 // Keep looking for motion events.
2378 continue;
2379 }
2380
2381 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
Jeff Brownefd32662011-03-08 15:13:06 -08002382 if (motionEntry->deviceId != deviceId
2383 || motionEntry->source != source) {
2384 // Keep looking for this device and source.
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002385 continue;
2386 }
2387
Jeff Browncc0c1592011-02-19 05:07:28 -08002388 if (motionEntry->action != action
Jeff Brown7fbdc842010-06-17 20:52:56 -07002389 || motionEntry->pointerCount != pointerCount
2390 || motionEntry->isInjected()) {
Jeff Brownefd32662011-03-08 15:13:06 -08002391 // Last motion event in the queue for this device and source is
2392 // not compatible for appending new samples. Stop here.
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002393 goto NoBatchingOrStreaming;
2394 }
2395
2396 // The last motion event is a move and is compatible for appending.
Jeff Brown9c3cda02010-06-15 01:31:58 -07002397 // Do the batching magic.
Jeff Brown7fbdc842010-06-17 20:52:56 -07002398 mAllocator.appendMotionSample(motionEntry, eventTime, pointerCoords);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002399#if DEBUG_BATCHING
2400 LOGD("Appended motion sample onto batch for most recent "
2401 "motion event for this device in the inbound queue.");
2402#endif
Jeff Brown9c3cda02010-06-15 01:31:58 -07002403 return; // done!
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002404 }
2405
2406 // STREAMING CASE
2407 //
2408 // There is no pending motion event (of any kind) for this device in the inbound queue.
Jeff Brown519e0242010-09-15 15:18:56 -07002409 // Search the outbound queue for the current foreground targets to find a dispatched
2410 // motion event that is still in progress. If found, then, appen the new sample to
2411 // that event and push it out to all current targets. The logic in
2412 // prepareDispatchCycleLocked takes care of the case where some targets may
2413 // already have consumed the motion event by starting a new dispatch cycle if needed.
Jeff Brown9c3cda02010-06-15 01:31:58 -07002414 if (mCurrentInputTargetsValid) {
Jeff Brown519e0242010-09-15 15:18:56 -07002415 for (size_t i = 0; i < mCurrentInputTargets.size(); i++) {
2416 const InputTarget& inputTarget = mCurrentInputTargets[i];
2417 if ((inputTarget.flags & InputTarget::FLAG_FOREGROUND) == 0) {
2418 // Skip non-foreground targets. We only want to stream if there is at
2419 // least one foreground target whose dispatch is still in progress.
2420 continue;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002421 }
Jeff Brown519e0242010-09-15 15:18:56 -07002422
2423 ssize_t connectionIndex = getConnectionIndexLocked(inputTarget.inputChannel);
2424 if (connectionIndex < 0) {
2425 // Connection must no longer be valid.
2426 continue;
2427 }
2428
2429 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
2430 if (connection->outboundQueue.isEmpty()) {
2431 // This foreground target has an empty outbound queue.
2432 continue;
2433 }
2434
2435 DispatchEntry* dispatchEntry = connection->outboundQueue.headSentinel.next;
2436 if (! dispatchEntry->inProgress
Jeff Brown01ce2e92010-09-26 22:20:12 -07002437 || dispatchEntry->eventEntry->type != EventEntry::TYPE_MOTION
2438 || dispatchEntry->isSplit()) {
2439 // No motion event is being dispatched, or it is being split across
2440 // windows in which case we cannot stream.
Jeff Brown519e0242010-09-15 15:18:56 -07002441 continue;
2442 }
2443
2444 MotionEntry* motionEntry = static_cast<MotionEntry*>(
2445 dispatchEntry->eventEntry);
Jeff Browncc0c1592011-02-19 05:07:28 -08002446 if (motionEntry->action != action
Jeff Brown519e0242010-09-15 15:18:56 -07002447 || motionEntry->deviceId != deviceId
Jeff Brown58a2da82011-01-25 16:02:22 -08002448 || motionEntry->source != source
Jeff Brown519e0242010-09-15 15:18:56 -07002449 || motionEntry->pointerCount != pointerCount
2450 || motionEntry->isInjected()) {
2451 // The motion event is not compatible with this move.
2452 continue;
2453 }
2454
2455 // Hurray! This foreground target is currently dispatching a move event
2456 // that we can stream onto. Append the motion sample and resume dispatch.
2457 mAllocator.appendMotionSample(motionEntry, eventTime, pointerCoords);
2458#if DEBUG_BATCHING
2459 LOGD("Appended motion sample onto batch for most recently dispatched "
2460 "motion event for this device in the outbound queues. "
2461 "Attempting to stream the motion sample.");
2462#endif
2463 nsecs_t currentTime = now();
2464 dispatchEventToCurrentInputTargetsLocked(currentTime, motionEntry,
2465 true /*resumeWithAppendedMotionSample*/);
2466
2467 runCommandsLockedInterruptible();
2468 return; // done!
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002469 }
2470 }
2471
2472NoBatchingOrStreaming:;
2473 }
2474
2475 // Just enqueue a new motion event.
Jeff Brown7fbdc842010-06-17 20:52:56 -07002476 MotionEntry* newEntry = mAllocator.obtainMotionEntry(eventTime,
Jeff Brown85a31762010-09-01 17:01:00 -07002477 deviceId, source, policyFlags, action, flags, metaState, edgeFlags,
Jeff Brown7fbdc842010-06-17 20:52:56 -07002478 xPrecision, yPrecision, downTime,
2479 pointerCount, pointerIds, pointerCoords);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002480
Jeff Brownb88102f2010-09-08 11:49:43 -07002481 needWake = enqueueInboundEventLocked(newEntry);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002482 } // release lock
2483
Jeff Brownb88102f2010-09-08 11:49:43 -07002484 if (needWake) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002485 mLooper->wake();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002486 }
2487}
2488
Jeff Brownb6997262010-10-08 22:31:17 -07002489void InputDispatcher::notifySwitch(nsecs_t when, int32_t switchCode, int32_t switchValue,
2490 uint32_t policyFlags) {
2491#if DEBUG_INBOUND_EVENT_DETAILS
2492 LOGD("notifySwitch - switchCode=%d, switchValue=%d, policyFlags=0x%x",
2493 switchCode, switchValue, policyFlags);
2494#endif
2495
Jeff Browne20c9e02010-10-11 14:20:19 -07002496 policyFlags |= POLICY_FLAG_TRUSTED;
Jeff Brownb6997262010-10-08 22:31:17 -07002497 mPolicy->notifySwitch(when, switchCode, switchValue, policyFlags);
2498}
2499
Jeff Brown7fbdc842010-06-17 20:52:56 -07002500int32_t InputDispatcher::injectInputEvent(const InputEvent* event,
Jeff Brown6ec402b2010-07-28 15:48:59 -07002501 int32_t injectorPid, int32_t injectorUid, int32_t syncMode, int32_t timeoutMillis) {
Jeff Brown7fbdc842010-06-17 20:52:56 -07002502#if DEBUG_INBOUND_EVENT_DETAILS
2503 LOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Jeff Brown6ec402b2010-07-28 15:48:59 -07002504 "syncMode=%d, timeoutMillis=%d",
2505 event->getType(), injectorPid, injectorUid, syncMode, timeoutMillis);
Jeff Brown7fbdc842010-06-17 20:52:56 -07002506#endif
2507
2508 nsecs_t endTime = now() + milliseconds_to_nanoseconds(timeoutMillis);
Jeff Browne20c9e02010-10-11 14:20:19 -07002509
2510 uint32_t policyFlags = POLICY_FLAG_INJECTED;
2511 if (hasInjectionPermission(injectorPid, injectorUid)) {
2512 policyFlags |= POLICY_FLAG_TRUSTED;
2513 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07002514
Jeff Brownb6997262010-10-08 22:31:17 -07002515 EventEntry* injectedEntry;
2516 switch (event->getType()) {
2517 case AINPUT_EVENT_TYPE_KEY: {
2518 const KeyEvent* keyEvent = static_cast<const KeyEvent*>(event);
2519 int32_t action = keyEvent->getAction();
2520 if (! validateKeyEvent(action)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07002521 return INPUT_EVENT_INJECTION_FAILED;
2522 }
2523
Jeff Brownb6997262010-10-08 22:31:17 -07002524 int32_t flags = keyEvent->getFlags();
Jeff Brown1f245102010-11-18 20:53:46 -08002525 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
2526 policyFlags |= POLICY_FLAG_VIRTUAL;
2527 }
2528
2529 mPolicy->interceptKeyBeforeQueueing(keyEvent, /*byref*/ policyFlags);
2530
2531 if (policyFlags & POLICY_FLAG_WOKE_HERE) {
2532 flags |= AKEY_EVENT_FLAG_WOKE_HERE;
2533 }
Jeff Brown6ec402b2010-07-28 15:48:59 -07002534
Jeff Brownb6997262010-10-08 22:31:17 -07002535 mLock.lock();
Jeff Brown1f245102010-11-18 20:53:46 -08002536 injectedEntry = mAllocator.obtainKeyEntry(keyEvent->getEventTime(),
2537 keyEvent->getDeviceId(), keyEvent->getSource(),
2538 policyFlags, action, flags,
2539 keyEvent->getKeyCode(), keyEvent->getScanCode(), keyEvent->getMetaState(),
Jeff Brownb6997262010-10-08 22:31:17 -07002540 keyEvent->getRepeatCount(), keyEvent->getDownTime());
2541 break;
2542 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07002543
Jeff Brownb6997262010-10-08 22:31:17 -07002544 case AINPUT_EVENT_TYPE_MOTION: {
2545 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
2546 int32_t action = motionEvent->getAction();
2547 size_t pointerCount = motionEvent->getPointerCount();
2548 const int32_t* pointerIds = motionEvent->getPointerIds();
2549 if (! validateMotionEvent(action, pointerCount, pointerIds)) {
2550 return INPUT_EVENT_INJECTION_FAILED;
2551 }
2552
2553 nsecs_t eventTime = motionEvent->getEventTime();
Jeff Brown56194eb2011-03-02 19:23:13 -08002554 mPolicy->interceptMotionBeforeQueueing(eventTime, /*byref*/ policyFlags);
Jeff Brownb6997262010-10-08 22:31:17 -07002555
2556 mLock.lock();
2557 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
2558 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
2559 MotionEntry* motionEntry = mAllocator.obtainMotionEntry(*sampleEventTimes,
2560 motionEvent->getDeviceId(), motionEvent->getSource(), policyFlags,
2561 action, motionEvent->getFlags(),
2562 motionEvent->getMetaState(), motionEvent->getEdgeFlags(),
2563 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
2564 motionEvent->getDownTime(), uint32_t(pointerCount),
2565 pointerIds, samplePointerCoords);
2566 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
2567 sampleEventTimes += 1;
2568 samplePointerCoords += pointerCount;
2569 mAllocator.appendMotionSample(motionEntry, *sampleEventTimes, samplePointerCoords);
2570 }
2571 injectedEntry = motionEntry;
2572 break;
2573 }
2574
2575 default:
2576 LOGW("Cannot inject event of type %d", event->getType());
2577 return INPUT_EVENT_INJECTION_FAILED;
2578 }
2579
2580 InjectionState* injectionState = mAllocator.obtainInjectionState(injectorPid, injectorUid);
2581 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
2582 injectionState->injectionIsAsync = true;
2583 }
2584
2585 injectionState->refCount += 1;
2586 injectedEntry->injectionState = injectionState;
2587
2588 bool needWake = enqueueInboundEventLocked(injectedEntry);
2589 mLock.unlock();
Jeff Brown7fbdc842010-06-17 20:52:56 -07002590
Jeff Brownb88102f2010-09-08 11:49:43 -07002591 if (needWake) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002592 mLooper->wake();
Jeff Brown7fbdc842010-06-17 20:52:56 -07002593 }
2594
2595 int32_t injectionResult;
2596 { // acquire lock
2597 AutoMutex _l(mLock);
2598
Jeff Brown6ec402b2010-07-28 15:48:59 -07002599 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
2600 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
2601 } else {
2602 for (;;) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002603 injectionResult = injectionState->injectionResult;
Jeff Brown6ec402b2010-07-28 15:48:59 -07002604 if (injectionResult != INPUT_EVENT_INJECTION_PENDING) {
2605 break;
2606 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07002607
Jeff Brown7fbdc842010-06-17 20:52:56 -07002608 nsecs_t remainingTimeout = endTime - now();
2609 if (remainingTimeout <= 0) {
Jeff Brown6ec402b2010-07-28 15:48:59 -07002610#if DEBUG_INJECTION
2611 LOGD("injectInputEvent - Timed out waiting for injection result "
2612 "to become available.");
2613#endif
Jeff Brown7fbdc842010-06-17 20:52:56 -07002614 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
2615 break;
2616 }
2617
Jeff Brown6ec402b2010-07-28 15:48:59 -07002618 mInjectionResultAvailableCondition.waitRelative(mLock, remainingTimeout);
2619 }
2620
2621 if (injectionResult == INPUT_EVENT_INJECTION_SUCCEEDED
2622 && syncMode == INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002623 while (injectionState->pendingForegroundDispatches != 0) {
Jeff Brown6ec402b2010-07-28 15:48:59 -07002624#if DEBUG_INJECTION
Jeff Brown519e0242010-09-15 15:18:56 -07002625 LOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
Jeff Brown01ce2e92010-09-26 22:20:12 -07002626 injectionState->pendingForegroundDispatches);
Jeff Brown6ec402b2010-07-28 15:48:59 -07002627#endif
2628 nsecs_t remainingTimeout = endTime - now();
2629 if (remainingTimeout <= 0) {
2630#if DEBUG_INJECTION
Jeff Brown519e0242010-09-15 15:18:56 -07002631 LOGD("injectInputEvent - Timed out waiting for pending foreground "
Jeff Brown6ec402b2010-07-28 15:48:59 -07002632 "dispatches to finish.");
2633#endif
2634 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
2635 break;
2636 }
2637
2638 mInjectionSyncFinishedCondition.waitRelative(mLock, remainingTimeout);
2639 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07002640 }
2641 }
2642
Jeff Brown01ce2e92010-09-26 22:20:12 -07002643 mAllocator.releaseInjectionState(injectionState);
Jeff Brown7fbdc842010-06-17 20:52:56 -07002644 } // release lock
2645
Jeff Brown6ec402b2010-07-28 15:48:59 -07002646#if DEBUG_INJECTION
2647 LOGD("injectInputEvent - Finished with result %d. "
2648 "injectorPid=%d, injectorUid=%d",
2649 injectionResult, injectorPid, injectorUid);
2650#endif
2651
Jeff Brown7fbdc842010-06-17 20:52:56 -07002652 return injectionResult;
2653}
2654
Jeff Brownb6997262010-10-08 22:31:17 -07002655bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
2656 return injectorUid == 0
2657 || mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
2658}
2659
Jeff Brown7fbdc842010-06-17 20:52:56 -07002660void InputDispatcher::setInjectionResultLocked(EventEntry* entry, int32_t injectionResult) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002661 InjectionState* injectionState = entry->injectionState;
2662 if (injectionState) {
Jeff Brown7fbdc842010-06-17 20:52:56 -07002663#if DEBUG_INJECTION
2664 LOGD("Setting input event injection result to %d. "
2665 "injectorPid=%d, injectorUid=%d",
Jeff Brown01ce2e92010-09-26 22:20:12 -07002666 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
Jeff Brown7fbdc842010-06-17 20:52:56 -07002667#endif
2668
Jeff Brown01ce2e92010-09-26 22:20:12 -07002669 if (injectionState->injectionIsAsync) {
Jeff Brown6ec402b2010-07-28 15:48:59 -07002670 // Log the outcome since the injector did not wait for the injection result.
2671 switch (injectionResult) {
2672 case INPUT_EVENT_INJECTION_SUCCEEDED:
2673 LOGV("Asynchronous input event injection succeeded.");
2674 break;
2675 case INPUT_EVENT_INJECTION_FAILED:
2676 LOGW("Asynchronous input event injection failed.");
2677 break;
2678 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
2679 LOGW("Asynchronous input event injection permission denied.");
2680 break;
2681 case INPUT_EVENT_INJECTION_TIMED_OUT:
2682 LOGW("Asynchronous input event injection timed out.");
2683 break;
2684 }
2685 }
2686
Jeff Brown01ce2e92010-09-26 22:20:12 -07002687 injectionState->injectionResult = injectionResult;
Jeff Brown7fbdc842010-06-17 20:52:56 -07002688 mInjectionResultAvailableCondition.broadcast();
2689 }
2690}
2691
Jeff Brown01ce2e92010-09-26 22:20:12 -07002692void InputDispatcher::incrementPendingForegroundDispatchesLocked(EventEntry* entry) {
2693 InjectionState* injectionState = entry->injectionState;
2694 if (injectionState) {
2695 injectionState->pendingForegroundDispatches += 1;
2696 }
2697}
2698
Jeff Brown519e0242010-09-15 15:18:56 -07002699void InputDispatcher::decrementPendingForegroundDispatchesLocked(EventEntry* entry) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002700 InjectionState* injectionState = entry->injectionState;
2701 if (injectionState) {
2702 injectionState->pendingForegroundDispatches -= 1;
Jeff Brown6ec402b2010-07-28 15:48:59 -07002703
Jeff Brown01ce2e92010-09-26 22:20:12 -07002704 if (injectionState->pendingForegroundDispatches == 0) {
2705 mInjectionSyncFinishedCondition.broadcast();
2706 }
Jeff Brownb88102f2010-09-08 11:49:43 -07002707 }
2708}
2709
Jeff Brown01ce2e92010-09-26 22:20:12 -07002710const InputWindow* InputDispatcher::getWindowLocked(const sp<InputChannel>& inputChannel) {
2711 for (size_t i = 0; i < mWindows.size(); i++) {
2712 const InputWindow* window = & mWindows[i];
2713 if (window->inputChannel == inputChannel) {
2714 return window;
2715 }
2716 }
2717 return NULL;
2718}
2719
Jeff Brownb88102f2010-09-08 11:49:43 -07002720void InputDispatcher::setInputWindows(const Vector<InputWindow>& inputWindows) {
2721#if DEBUG_FOCUS
2722 LOGD("setInputWindows");
2723#endif
2724 { // acquire lock
2725 AutoMutex _l(mLock);
2726
Jeff Brown01ce2e92010-09-26 22:20:12 -07002727 // Clear old window pointers.
Jeff Brownb6997262010-10-08 22:31:17 -07002728 sp<InputChannel> oldFocusedWindowChannel;
2729 if (mFocusedWindow) {
2730 oldFocusedWindowChannel = mFocusedWindow->inputChannel;
2731 mFocusedWindow = NULL;
2732 }
2733
Jeff Brownb88102f2010-09-08 11:49:43 -07002734 mWindows.clear();
Jeff Brown2a95c2a2010-09-16 12:31:46 -07002735
2736 // Loop over new windows and rebuild the necessary window pointers for
2737 // tracking focus and touch.
Jeff Brownb88102f2010-09-08 11:49:43 -07002738 mWindows.appendVector(inputWindows);
2739
2740 size_t numWindows = mWindows.size();
2741 for (size_t i = 0; i < numWindows; i++) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002742 const InputWindow* window = & mWindows.itemAt(i);
Jeff Brownb88102f2010-09-08 11:49:43 -07002743 if (window->hasFocus) {
2744 mFocusedWindow = window;
Jeff Brown01ce2e92010-09-26 22:20:12 -07002745 break;
Jeff Brownb88102f2010-09-08 11:49:43 -07002746 }
2747 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07002748
Jeff Brownb6997262010-10-08 22:31:17 -07002749 if (oldFocusedWindowChannel != NULL) {
2750 if (!mFocusedWindow || oldFocusedWindowChannel != mFocusedWindow->inputChannel) {
2751#if DEBUG_FOCUS
2752 LOGD("Focus left window: %s",
2753 oldFocusedWindowChannel->getName().string());
2754#endif
Jeff Brown524ee642011-03-29 15:11:34 -07002755 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
2756 "focus left window");
2757 synthesizeCancelationEventsForInputChannelLocked(oldFocusedWindowChannel, options);
Jeff Brownb6997262010-10-08 22:31:17 -07002758 oldFocusedWindowChannel.clear();
2759 }
2760 }
2761 if (mFocusedWindow && oldFocusedWindowChannel == NULL) {
2762#if DEBUG_FOCUS
2763 LOGD("Focus entered window: %s",
2764 mFocusedWindow->inputChannel->getName().string());
2765#endif
2766 }
2767
Jeff Brown01ce2e92010-09-26 22:20:12 -07002768 for (size_t i = 0; i < mTouchState.windows.size(); ) {
2769 TouchedWindow& touchedWindow = mTouchState.windows.editItemAt(i);
2770 const InputWindow* window = getWindowLocked(touchedWindow.channel);
2771 if (window) {
2772 touchedWindow.window = window;
2773 i += 1;
2774 } else {
Jeff Brownb6997262010-10-08 22:31:17 -07002775#if DEBUG_FOCUS
2776 LOGD("Touched window was removed: %s", touchedWindow.channel->getName().string());
2777#endif
Jeff Brown524ee642011-03-29 15:11:34 -07002778 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
2779 "touched window was removed");
2780 synthesizeCancelationEventsForInputChannelLocked(touchedWindow.channel, options);
Jeff Brownaf48cae2010-10-15 16:20:51 -07002781 mTouchState.windows.removeAt(i);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002782 }
2783 }
Jeff Brownb88102f2010-09-08 11:49:43 -07002784
Jeff Brownb88102f2010-09-08 11:49:43 -07002785#if DEBUG_FOCUS
Jeff Brownb6997262010-10-08 22:31:17 -07002786 //logDispatchStateLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -07002787#endif
2788 } // release lock
2789
2790 // Wake up poll loop since it may need to make new input dispatching choices.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002791 mLooper->wake();
Jeff Brownb88102f2010-09-08 11:49:43 -07002792}
2793
2794void InputDispatcher::setFocusedApplication(const InputApplication* inputApplication) {
2795#if DEBUG_FOCUS
2796 LOGD("setFocusedApplication");
2797#endif
2798 { // acquire lock
2799 AutoMutex _l(mLock);
2800
2801 releaseFocusedApplicationLocked();
2802
2803 if (inputApplication) {
2804 mFocusedApplicationStorage = *inputApplication;
2805 mFocusedApplication = & mFocusedApplicationStorage;
2806 }
2807
2808#if DEBUG_FOCUS
Jeff Brownb6997262010-10-08 22:31:17 -07002809 //logDispatchStateLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -07002810#endif
2811 } // release lock
2812
2813 // Wake up poll loop since it may need to make new input dispatching choices.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002814 mLooper->wake();
Jeff Brownb88102f2010-09-08 11:49:43 -07002815}
2816
2817void InputDispatcher::releaseFocusedApplicationLocked() {
2818 if (mFocusedApplication) {
2819 mFocusedApplication = NULL;
Jeff Brown928e0542011-01-10 11:17:36 -08002820 mFocusedApplicationStorage.inputApplicationHandle.clear();
Jeff Brownb88102f2010-09-08 11:49:43 -07002821 }
2822}
2823
2824void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
2825#if DEBUG_FOCUS
2826 LOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
2827#endif
2828
2829 bool changed;
2830 { // acquire lock
2831 AutoMutex _l(mLock);
2832
2833 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
Jeff Brown120a4592010-10-27 18:43:51 -07002834 if (mDispatchFrozen && !frozen) {
Jeff Brownb88102f2010-09-08 11:49:43 -07002835 resetANRTimeoutsLocked();
2836 }
2837
Jeff Brown120a4592010-10-27 18:43:51 -07002838 if (mDispatchEnabled && !enabled) {
2839 resetAndDropEverythingLocked("dispatcher is being disabled");
2840 }
2841
Jeff Brownb88102f2010-09-08 11:49:43 -07002842 mDispatchEnabled = enabled;
2843 mDispatchFrozen = frozen;
2844 changed = true;
2845 } else {
2846 changed = false;
2847 }
2848
2849#if DEBUG_FOCUS
Jeff Brownb6997262010-10-08 22:31:17 -07002850 //logDispatchStateLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -07002851#endif
2852 } // release lock
2853
2854 if (changed) {
2855 // Wake up poll loop since it may need to make new input dispatching choices.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002856 mLooper->wake();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002857 }
2858}
2859
Jeff Browne6504122010-09-27 14:52:15 -07002860bool InputDispatcher::transferTouchFocus(const sp<InputChannel>& fromChannel,
2861 const sp<InputChannel>& toChannel) {
2862#if DEBUG_FOCUS
2863 LOGD("transferTouchFocus: fromChannel=%s, toChannel=%s",
2864 fromChannel->getName().string(), toChannel->getName().string());
2865#endif
2866 { // acquire lock
2867 AutoMutex _l(mLock);
2868
2869 const InputWindow* fromWindow = getWindowLocked(fromChannel);
2870 const InputWindow* toWindow = getWindowLocked(toChannel);
2871 if (! fromWindow || ! toWindow) {
2872#if DEBUG_FOCUS
2873 LOGD("Cannot transfer focus because from or to window not found.");
2874#endif
2875 return false;
2876 }
2877 if (fromWindow == toWindow) {
2878#if DEBUG_FOCUS
2879 LOGD("Trivial transfer to same window.");
2880#endif
2881 return true;
2882 }
2883
2884 bool found = false;
2885 for (size_t i = 0; i < mTouchState.windows.size(); i++) {
2886 const TouchedWindow& touchedWindow = mTouchState.windows[i];
2887 if (touchedWindow.window == fromWindow) {
2888 int32_t oldTargetFlags = touchedWindow.targetFlags;
2889 BitSet32 pointerIds = touchedWindow.pointerIds;
2890
2891 mTouchState.windows.removeAt(i);
2892
Jeff Brown46e75292010-11-10 16:53:45 -08002893 int32_t newTargetFlags = oldTargetFlags
2894 & (InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_SPLIT);
Jeff Browne6504122010-09-27 14:52:15 -07002895 mTouchState.addOrUpdateWindow(toWindow, newTargetFlags, pointerIds);
2896
2897 found = true;
2898 break;
2899 }
2900 }
2901
2902 if (! found) {
2903#if DEBUG_FOCUS
2904 LOGD("Focus transfer failed because from window did not have focus.");
2905#endif
2906 return false;
2907 }
2908
Jeff Brown9c9f1a32010-10-11 18:32:20 -07002909 ssize_t fromConnectionIndex = getConnectionIndexLocked(fromChannel);
2910 ssize_t toConnectionIndex = getConnectionIndexLocked(toChannel);
2911 if (fromConnectionIndex >= 0 && toConnectionIndex >= 0) {
2912 sp<Connection> fromConnection = mConnectionsByReceiveFd.valueAt(fromConnectionIndex);
2913 sp<Connection> toConnection = mConnectionsByReceiveFd.valueAt(toConnectionIndex);
2914
2915 fromConnection->inputState.copyPointerStateTo(toConnection->inputState);
Jeff Brown524ee642011-03-29 15:11:34 -07002916 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Jeff Brown9c9f1a32010-10-11 18:32:20 -07002917 "transferring touch focus from this window to another window");
Jeff Brown524ee642011-03-29 15:11:34 -07002918 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Jeff Brown9c9f1a32010-10-11 18:32:20 -07002919 }
2920
Jeff Browne6504122010-09-27 14:52:15 -07002921#if DEBUG_FOCUS
2922 logDispatchStateLocked();
2923#endif
2924 } // release lock
2925
2926 // Wake up poll loop since it may need to make new input dispatching choices.
2927 mLooper->wake();
2928 return true;
2929}
2930
Jeff Brown120a4592010-10-27 18:43:51 -07002931void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
2932#if DEBUG_FOCUS
2933 LOGD("Resetting and dropping all events (%s).", reason);
2934#endif
2935
Jeff Brown524ee642011-03-29 15:11:34 -07002936 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
2937 synthesizeCancelationEventsForAllConnectionsLocked(options);
Jeff Brown120a4592010-10-27 18:43:51 -07002938
2939 resetKeyRepeatLocked();
2940 releasePendingEventLocked();
2941 drainInboundQueueLocked();
2942 resetTargetsLocked();
2943
2944 mTouchState.reset();
2945}
2946
Jeff Brownb88102f2010-09-08 11:49:43 -07002947void InputDispatcher::logDispatchStateLocked() {
2948 String8 dump;
2949 dumpDispatchStateLocked(dump);
Jeff Brown2a95c2a2010-09-16 12:31:46 -07002950
2951 char* text = dump.lockBuffer(dump.size());
2952 char* start = text;
2953 while (*start != '\0') {
2954 char* end = strchr(start, '\n');
2955 if (*end == '\n') {
2956 *(end++) = '\0';
2957 }
2958 LOGD("%s", start);
2959 start = end;
2960 }
Jeff Brownb88102f2010-09-08 11:49:43 -07002961}
2962
2963void InputDispatcher::dumpDispatchStateLocked(String8& dump) {
Jeff Brownf2f487182010-10-01 17:46:21 -07002964 dump.appendFormat(INDENT "DispatchEnabled: %d\n", mDispatchEnabled);
2965 dump.appendFormat(INDENT "DispatchFrozen: %d\n", mDispatchFrozen);
Jeff Brownb88102f2010-09-08 11:49:43 -07002966
2967 if (mFocusedApplication) {
Jeff Brownf2f487182010-10-01 17:46:21 -07002968 dump.appendFormat(INDENT "FocusedApplication: name='%s', dispatchingTimeout=%0.3fms\n",
Jeff Brownb88102f2010-09-08 11:49:43 -07002969 mFocusedApplication->name.string(),
2970 mFocusedApplication->dispatchingTimeout / 1000000.0);
2971 } else {
Jeff Brownf2f487182010-10-01 17:46:21 -07002972 dump.append(INDENT "FocusedApplication: <null>\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07002973 }
Jeff Brownf2f487182010-10-01 17:46:21 -07002974 dump.appendFormat(INDENT "FocusedWindow: name='%s'\n",
Jeff Brown2a95c2a2010-09-16 12:31:46 -07002975 mFocusedWindow != NULL ? mFocusedWindow->name.string() : "<null>");
Jeff Brownf2f487182010-10-01 17:46:21 -07002976
2977 dump.appendFormat(INDENT "TouchDown: %s\n", toString(mTouchState.down));
2978 dump.appendFormat(INDENT "TouchSplit: %s\n", toString(mTouchState.split));
Jeff Brown95712852011-01-04 19:41:59 -08002979 dump.appendFormat(INDENT "TouchDeviceId: %d\n", mTouchState.deviceId);
Jeff Brown58a2da82011-01-25 16:02:22 -08002980 dump.appendFormat(INDENT "TouchSource: 0x%08x\n", mTouchState.source);
Jeff Brownf2f487182010-10-01 17:46:21 -07002981 if (!mTouchState.windows.isEmpty()) {
2982 dump.append(INDENT "TouchedWindows:\n");
2983 for (size_t i = 0; i < mTouchState.windows.size(); i++) {
2984 const TouchedWindow& touchedWindow = mTouchState.windows[i];
2985 dump.appendFormat(INDENT2 "%d: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
2986 i, touchedWindow.window->name.string(), touchedWindow.pointerIds.value,
2987 touchedWindow.targetFlags);
2988 }
2989 } else {
2990 dump.append(INDENT "TouchedWindows: <none>\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07002991 }
2992
Jeff Brownf2f487182010-10-01 17:46:21 -07002993 if (!mWindows.isEmpty()) {
2994 dump.append(INDENT "Windows:\n");
2995 for (size_t i = 0; i < mWindows.size(); i++) {
2996 const InputWindow& window = mWindows[i];
2997 dump.appendFormat(INDENT2 "%d: name='%s', paused=%s, hasFocus=%s, hasWallpaper=%s, "
2998 "visible=%s, canReceiveKeys=%s, flags=0x%08x, type=0x%08x, layer=%d, "
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002999 "frame=[%d,%d][%d,%d], scale=%f, "
Jeff Brownfbf09772011-01-16 14:06:57 -08003000 "touchableRegion=",
Jeff Brownf2f487182010-10-01 17:46:21 -07003001 i, window.name.string(),
3002 toString(window.paused),
3003 toString(window.hasFocus),
3004 toString(window.hasWallpaper),
3005 toString(window.visible),
3006 toString(window.canReceiveKeys),
3007 window.layoutParamsFlags, window.layoutParamsType,
3008 window.layer,
3009 window.frameLeft, window.frameTop,
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003010 window.frameRight, window.frameBottom,
3011 window.scaleFactor);
Jeff Brownfbf09772011-01-16 14:06:57 -08003012 dumpRegion(dump, window.touchableRegion);
3013 dump.appendFormat(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%0.3fms\n",
Jeff Brownf2f487182010-10-01 17:46:21 -07003014 window.ownerPid, window.ownerUid,
3015 window.dispatchingTimeout / 1000000.0);
3016 }
3017 } else {
3018 dump.append(INDENT "Windows: <none>\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003019 }
3020
Jeff Brownf2f487182010-10-01 17:46:21 -07003021 if (!mMonitoringChannels.isEmpty()) {
3022 dump.append(INDENT "MonitoringChannels:\n");
3023 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
3024 const sp<InputChannel>& channel = mMonitoringChannels[i];
3025 dump.appendFormat(INDENT2 "%d: '%s'\n", i, channel->getName().string());
3026 }
3027 } else {
3028 dump.append(INDENT "MonitoringChannels: <none>\n");
3029 }
Jeff Brown519e0242010-09-15 15:18:56 -07003030
Jeff Brownf2f487182010-10-01 17:46:21 -07003031 dump.appendFormat(INDENT "InboundQueue: length=%u\n", mInboundQueue.count());
3032
3033 if (!mActiveConnections.isEmpty()) {
3034 dump.append(INDENT "ActiveConnections:\n");
3035 for (size_t i = 0; i < mActiveConnections.size(); i++) {
3036 const Connection* connection = mActiveConnections[i];
Jeff Brown76860e32010-10-25 17:37:46 -07003037 dump.appendFormat(INDENT2 "%d: '%s', status=%s, outboundQueueLength=%u, "
Jeff Brownb6997262010-10-08 22:31:17 -07003038 "inputState.isNeutral=%s\n",
Jeff Brownf2f487182010-10-01 17:46:21 -07003039 i, connection->getInputChannelName(), connection->getStatusLabel(),
3040 connection->outboundQueue.count(),
Jeff Brownb6997262010-10-08 22:31:17 -07003041 toString(connection->inputState.isNeutral()));
Jeff Brownf2f487182010-10-01 17:46:21 -07003042 }
3043 } else {
3044 dump.append(INDENT "ActiveConnections: <none>\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003045 }
3046
3047 if (isAppSwitchPendingLocked()) {
Jeff Brownf2f487182010-10-01 17:46:21 -07003048 dump.appendFormat(INDENT "AppSwitch: pending, due in %01.1fms\n",
Jeff Brownb88102f2010-09-08 11:49:43 -07003049 (mAppSwitchDueTime - now()) / 1000000.0);
3050 } else {
Jeff Brownf2f487182010-10-01 17:46:21 -07003051 dump.append(INDENT "AppSwitch: not pending\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003052 }
3053}
3054
Jeff Brown928e0542011-01-10 11:17:36 -08003055status_t InputDispatcher::registerInputChannel(const sp<InputChannel>& inputChannel,
3056 const sp<InputWindowHandle>& inputWindowHandle, bool monitor) {
Jeff Brown9c3cda02010-06-15 01:31:58 -07003057#if DEBUG_REGISTRATION
Jeff Brownb88102f2010-09-08 11:49:43 -07003058 LOGD("channel '%s' ~ registerInputChannel - monitor=%s", inputChannel->getName().string(),
3059 toString(monitor));
Jeff Brown9c3cda02010-06-15 01:31:58 -07003060#endif
3061
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003062 { // acquire lock
3063 AutoMutex _l(mLock);
3064
Jeff Brown519e0242010-09-15 15:18:56 -07003065 if (getConnectionIndexLocked(inputChannel) >= 0) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003066 LOGW("Attempted to register already registered input channel '%s'",
3067 inputChannel->getName().string());
3068 return BAD_VALUE;
3069 }
3070
Jeff Brown928e0542011-01-10 11:17:36 -08003071 sp<Connection> connection = new Connection(inputChannel, inputWindowHandle);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003072 status_t status = connection->initialize();
3073 if (status) {
3074 LOGE("Failed to initialize input publisher for input channel '%s', status=%d",
3075 inputChannel->getName().string(), status);
3076 return status;
3077 }
3078
Jeff Brown2cbecea2010-08-17 15:59:26 -07003079 int32_t receiveFd = inputChannel->getReceivePipeFd();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003080 mConnectionsByReceiveFd.add(receiveFd, connection);
Jeff Brown9c3cda02010-06-15 01:31:58 -07003081
Jeff Brownb88102f2010-09-08 11:49:43 -07003082 if (monitor) {
3083 mMonitoringChannels.push(inputChannel);
3084 }
3085
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07003086 mLooper->addFd(receiveFd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
Jeff Brown2cbecea2010-08-17 15:59:26 -07003087
Jeff Brown9c3cda02010-06-15 01:31:58 -07003088 runCommandsLockedInterruptible();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003089 } // release lock
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003090 return OK;
3091}
3092
3093status_t InputDispatcher::unregisterInputChannel(const sp<InputChannel>& inputChannel) {
Jeff Brown9c3cda02010-06-15 01:31:58 -07003094#if DEBUG_REGISTRATION
Jeff Brown349703e2010-06-22 01:27:15 -07003095 LOGD("channel '%s' ~ unregisterInputChannel", inputChannel->getName().string());
Jeff Brown9c3cda02010-06-15 01:31:58 -07003096#endif
3097
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003098 { // acquire lock
3099 AutoMutex _l(mLock);
3100
Jeff Brown519e0242010-09-15 15:18:56 -07003101 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003102 if (connectionIndex < 0) {
3103 LOGW("Attempted to unregister already unregistered input channel '%s'",
3104 inputChannel->getName().string());
3105 return BAD_VALUE;
3106 }
3107
3108 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
3109 mConnectionsByReceiveFd.removeItemsAt(connectionIndex);
3110
3111 connection->status = Connection::STATUS_ZOMBIE;
3112
Jeff Brownb88102f2010-09-08 11:49:43 -07003113 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
3114 if (mMonitoringChannels[i] == inputChannel) {
3115 mMonitoringChannels.removeAt(i);
3116 break;
3117 }
3118 }
3119
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07003120 mLooper->removeFd(inputChannel->getReceivePipeFd());
Jeff Brown2cbecea2010-08-17 15:59:26 -07003121
Jeff Brown7fbdc842010-06-17 20:52:56 -07003122 nsecs_t currentTime = now();
Jeff Brownb6997262010-10-08 22:31:17 -07003123 abortBrokenDispatchCycleLocked(currentTime, connection);
Jeff Brown9c3cda02010-06-15 01:31:58 -07003124
3125 runCommandsLockedInterruptible();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003126 } // release lock
3127
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003128 // Wake the poll loop because removing the connection may have changed the current
3129 // synchronization state.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07003130 mLooper->wake();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003131 return OK;
3132}
3133
Jeff Brown519e0242010-09-15 15:18:56 -07003134ssize_t InputDispatcher::getConnectionIndexLocked(const sp<InputChannel>& inputChannel) {
Jeff Brown2cbecea2010-08-17 15:59:26 -07003135 ssize_t connectionIndex = mConnectionsByReceiveFd.indexOfKey(inputChannel->getReceivePipeFd());
3136 if (connectionIndex >= 0) {
3137 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
3138 if (connection->inputChannel.get() == inputChannel.get()) {
3139 return connectionIndex;
3140 }
3141 }
3142
3143 return -1;
3144}
3145
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003146void InputDispatcher::activateConnectionLocked(Connection* connection) {
3147 for (size_t i = 0; i < mActiveConnections.size(); i++) {
3148 if (mActiveConnections.itemAt(i) == connection) {
3149 return;
3150 }
3151 }
3152 mActiveConnections.add(connection);
3153}
3154
3155void InputDispatcher::deactivateConnectionLocked(Connection* connection) {
3156 for (size_t i = 0; i < mActiveConnections.size(); i++) {
3157 if (mActiveConnections.itemAt(i) == connection) {
3158 mActiveConnections.removeAt(i);
3159 return;
3160 }
3161 }
3162}
3163
Jeff Brown9c3cda02010-06-15 01:31:58 -07003164void InputDispatcher::onDispatchCycleStartedLocked(
Jeff Brown7fbdc842010-06-17 20:52:56 -07003165 nsecs_t currentTime, const sp<Connection>& connection) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003166}
3167
Jeff Brown9c3cda02010-06-15 01:31:58 -07003168void InputDispatcher::onDispatchCycleFinishedLocked(
Jeff Brown3915bb82010-11-05 15:02:16 -07003169 nsecs_t currentTime, const sp<Connection>& connection, bool handled) {
3170 CommandEntry* commandEntry = postCommandLocked(
3171 & InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
3172 commandEntry->connection = connection;
3173 commandEntry->handled = handled;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003174}
3175
Jeff Brown9c3cda02010-06-15 01:31:58 -07003176void InputDispatcher::onDispatchCycleBrokenLocked(
Jeff Brown7fbdc842010-06-17 20:52:56 -07003177 nsecs_t currentTime, const sp<Connection>& connection) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003178 LOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
3179 connection->getInputChannelName());
3180
Jeff Brown9c3cda02010-06-15 01:31:58 -07003181 CommandEntry* commandEntry = postCommandLocked(
3182 & InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
Jeff Brown7fbdc842010-06-17 20:52:56 -07003183 commandEntry->connection = connection;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003184}
3185
Jeff Brown519e0242010-09-15 15:18:56 -07003186void InputDispatcher::onANRLocked(
3187 nsecs_t currentTime, const InputApplication* application, const InputWindow* window,
3188 nsecs_t eventTime, nsecs_t waitStartTime) {
3189 LOGI("Application is not responding: %s. "
3190 "%01.1fms since event, %01.1fms since wait started",
3191 getApplicationWindowLabelLocked(application, window).string(),
3192 (currentTime - eventTime) / 1000000.0,
3193 (currentTime - waitStartTime) / 1000000.0);
3194
3195 CommandEntry* commandEntry = postCommandLocked(
3196 & InputDispatcher::doNotifyANRLockedInterruptible);
3197 if (application) {
Jeff Brown928e0542011-01-10 11:17:36 -08003198 commandEntry->inputApplicationHandle = application->inputApplicationHandle;
Jeff Brown519e0242010-09-15 15:18:56 -07003199 }
3200 if (window) {
Jeff Brown928e0542011-01-10 11:17:36 -08003201 commandEntry->inputWindowHandle = window->inputWindowHandle;
Jeff Brown519e0242010-09-15 15:18:56 -07003202 commandEntry->inputChannel = window->inputChannel;
3203 }
3204}
3205
Jeff Brownb88102f2010-09-08 11:49:43 -07003206void InputDispatcher::doNotifyConfigurationChangedInterruptible(
3207 CommandEntry* commandEntry) {
3208 mLock.unlock();
3209
3210 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
3211
3212 mLock.lock();
3213}
3214
Jeff Brown9c3cda02010-06-15 01:31:58 -07003215void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(
3216 CommandEntry* commandEntry) {
Jeff Brown7fbdc842010-06-17 20:52:56 -07003217 sp<Connection> connection = commandEntry->connection;
Jeff Brown9c3cda02010-06-15 01:31:58 -07003218
Jeff Brown7fbdc842010-06-17 20:52:56 -07003219 if (connection->status != Connection::STATUS_ZOMBIE) {
3220 mLock.unlock();
Jeff Brown9c3cda02010-06-15 01:31:58 -07003221
Jeff Brown928e0542011-01-10 11:17:36 -08003222 mPolicy->notifyInputChannelBroken(connection->inputWindowHandle);
Jeff Brown7fbdc842010-06-17 20:52:56 -07003223
3224 mLock.lock();
3225 }
Jeff Brown9c3cda02010-06-15 01:31:58 -07003226}
3227
Jeff Brown519e0242010-09-15 15:18:56 -07003228void InputDispatcher::doNotifyANRLockedInterruptible(
Jeff Brown9c3cda02010-06-15 01:31:58 -07003229 CommandEntry* commandEntry) {
Jeff Brown519e0242010-09-15 15:18:56 -07003230 mLock.unlock();
Jeff Brown9c3cda02010-06-15 01:31:58 -07003231
Jeff Brown519e0242010-09-15 15:18:56 -07003232 nsecs_t newTimeout = mPolicy->notifyANR(
Jeff Brown928e0542011-01-10 11:17:36 -08003233 commandEntry->inputApplicationHandle, commandEntry->inputWindowHandle);
Jeff Brown9c3cda02010-06-15 01:31:58 -07003234
Jeff Brown519e0242010-09-15 15:18:56 -07003235 mLock.lock();
Jeff Brown7fbdc842010-06-17 20:52:56 -07003236
Jeff Brown519e0242010-09-15 15:18:56 -07003237 resumeAfterTargetsNotReadyTimeoutLocked(newTimeout, commandEntry->inputChannel);
Jeff Brown9c3cda02010-06-15 01:31:58 -07003238}
3239
Jeff Brownb88102f2010-09-08 11:49:43 -07003240void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
3241 CommandEntry* commandEntry) {
3242 KeyEntry* entry = commandEntry->keyEntry;
Jeff Brown1f245102010-11-18 20:53:46 -08003243
3244 KeyEvent event;
3245 initializeKeyEvent(&event, entry);
Jeff Brownb88102f2010-09-08 11:49:43 -07003246
3247 mLock.unlock();
3248
Jeff Brown928e0542011-01-10 11:17:36 -08003249 bool consumed = mPolicy->interceptKeyBeforeDispatching(commandEntry->inputWindowHandle,
Jeff Brown1f245102010-11-18 20:53:46 -08003250 &event, entry->policyFlags);
Jeff Brownb88102f2010-09-08 11:49:43 -07003251
3252 mLock.lock();
3253
3254 entry->interceptKeyResult = consumed
3255 ? KeyEntry::INTERCEPT_KEY_RESULT_SKIP
3256 : KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
3257 mAllocator.releaseKeyEntry(entry);
3258}
3259
Jeff Brown3915bb82010-11-05 15:02:16 -07003260void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(
3261 CommandEntry* commandEntry) {
3262 sp<Connection> connection = commandEntry->connection;
3263 bool handled = commandEntry->handled;
3264
Jeff Brown49ed71d2010-12-06 17:13:33 -08003265 if (!connection->outboundQueue.isEmpty()) {
Jeff Brown3915bb82010-11-05 15:02:16 -07003266 DispatchEntry* dispatchEntry = connection->outboundQueue.headSentinel.next;
3267 if (dispatchEntry->inProgress
Jeff Brown3915bb82010-11-05 15:02:16 -07003268 && dispatchEntry->eventEntry->type == EventEntry::TYPE_KEY) {
3269 KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry);
Jeff Brown49ed71d2010-12-06 17:13:33 -08003270 if (!(keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK)) {
Jeff Brown524ee642011-03-29 15:11:34 -07003271 // Get the fallback key state.
3272 // Clear it out after dispatching the UP.
3273 int32_t originalKeyCode = keyEntry->keyCode;
3274 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
3275 if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
3276 connection->inputState.removeFallbackKey(originalKeyCode);
3277 }
3278
3279 if (handled || !dispatchEntry->hasForegroundTarget()) {
3280 // If the application handles the original key for which we previously
3281 // generated a fallback or if the window is not a foreground window,
3282 // then cancel the associated fallback key, if any.
3283 if (fallbackKeyCode != -1) {
3284 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
3285 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
3286 "application handled the original non-fallback key "
3287 "or is no longer a foreground target, "
3288 "canceling previously dispatched fallback key");
3289 options.keyCode = fallbackKeyCode;
3290 synthesizeCancelationEventsForConnectionLocked(connection, options);
3291 }
3292 connection->inputState.removeFallbackKey(originalKeyCode);
3293 }
Jeff Brown49ed71d2010-12-06 17:13:33 -08003294 } else {
Jeff Brownbfaf3b92011-02-22 15:00:50 -08003295 // If the application did not handle a non-fallback key, first check
Jeff Brown524ee642011-03-29 15:11:34 -07003296 // that we are in a good state to perform unhandled key event processing
3297 // Then ask the policy what to do with it.
3298 bool initialDown = keyEntry->action == AKEY_EVENT_ACTION_DOWN
3299 && keyEntry->repeatCount == 0;
3300 if (fallbackKeyCode == -1 && !initialDown) {
Jeff Brownbfaf3b92011-02-22 15:00:50 -08003301#if DEBUG_OUTBOUND_EVENT_DETAILS
Jeff Brown524ee642011-03-29 15:11:34 -07003302 LOGD("Unhandled key event: Skipping unhandled key event processing "
3303 "since this is not an initial down. "
3304 "keyCode=%d, action=%d, repeatCount=%d",
3305 originalKeyCode, keyEntry->action, keyEntry->repeatCount);
Jeff Brownbfaf3b92011-02-22 15:00:50 -08003306#endif
Jeff Brown524ee642011-03-29 15:11:34 -07003307 goto SkipFallback;
Jeff Brownbfaf3b92011-02-22 15:00:50 -08003308 }
3309
Jeff Brown524ee642011-03-29 15:11:34 -07003310 // Dispatch the unhandled key to the policy.
Jeff Brownbfaf3b92011-02-22 15:00:50 -08003311#if DEBUG_OUTBOUND_EVENT_DETAILS
3312 LOGD("Unhandled key event: Asking policy to perform fallback action. "
3313 "keyCode=%d, action=%d, repeatCount=%d",
3314 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount);
3315#endif
Jeff Brown49ed71d2010-12-06 17:13:33 -08003316 KeyEvent event;
3317 initializeKeyEvent(&event, keyEntry);
Jeff Brown3915bb82010-11-05 15:02:16 -07003318
Jeff Brown49ed71d2010-12-06 17:13:33 -08003319 mLock.unlock();
Jeff Brown3915bb82010-11-05 15:02:16 -07003320
Jeff Brown928e0542011-01-10 11:17:36 -08003321 bool fallback = mPolicy->dispatchUnhandledKey(connection->inputWindowHandle,
Jeff Brown49ed71d2010-12-06 17:13:33 -08003322 &event, keyEntry->policyFlags, &event);
Jeff Brown3915bb82010-11-05 15:02:16 -07003323
Jeff Brown49ed71d2010-12-06 17:13:33 -08003324 mLock.lock();
3325
Jeff Brown00045a72010-12-09 18:10:30 -08003326 if (connection->status != Connection::STATUS_NORMAL) {
Jeff Brown524ee642011-03-29 15:11:34 -07003327 connection->inputState.removeFallbackKey(originalKeyCode);
Jeff Brown00045a72010-12-09 18:10:30 -08003328 return;
3329 }
3330
3331 assert(connection->outboundQueue.headSentinel.next == dispatchEntry);
3332
Jeff Brown524ee642011-03-29 15:11:34 -07003333 // Latch the fallback keycode for this key on an initial down.
3334 // The fallback keycode cannot change at any other point in the lifecycle.
3335 if (initialDown) {
3336 if (fallback) {
3337 fallbackKeyCode = event.getKeyCode();
3338 } else {
3339 fallbackKeyCode = AKEYCODE_UNKNOWN;
3340 }
3341 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
3342 }
3343
3344 assert(fallbackKeyCode != -1);
3345
3346 // Cancel the fallback key if the policy decides not to send it anymore.
3347 // We will continue to dispatch the key to the policy but we will no
3348 // longer dispatch a fallback key to the application.
3349 if (fallbackKeyCode != AKEYCODE_UNKNOWN
3350 && (!fallback || fallbackKeyCode != event.getKeyCode())) {
3351#if DEBUG_OUTBOUND_EVENT_DETAILS
3352 if (fallback) {
3353 LOGD("Unhandled key event: Policy requested to send key %d"
3354 "as a fallback for %d, but on the DOWN it had requested "
3355 "to send %d instead. Fallback canceled.",
3356 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
3357 } else {
3358 LOGD("Unhandled key event: Policy did not request fallback for %d,"
3359 "but on the DOWN it had requested to send %d. "
3360 "Fallback canceled.",
3361 originalKeyCode, fallbackKeyCode);
3362 }
3363#endif
3364
3365 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
3366 "canceling fallback, policy no longer desires it");
3367 options.keyCode = fallbackKeyCode;
3368 synthesizeCancelationEventsForConnectionLocked(connection, options);
3369
3370 fallback = false;
3371 fallbackKeyCode = AKEYCODE_UNKNOWN;
3372 if (keyEntry->action != AKEY_EVENT_ACTION_UP) {
3373 connection->inputState.setFallbackKey(originalKeyCode,
3374 fallbackKeyCode);
3375 }
3376 }
3377
3378#if DEBUG_OUTBOUND_EVENT_DETAILS
3379 {
3380 String8 msg;
3381 const KeyedVector<int32_t, int32_t>& fallbackKeys =
3382 connection->inputState.getFallbackKeys();
3383 for (size_t i = 0; i < fallbackKeys.size(); i++) {
3384 msg.appendFormat(", %d->%d", fallbackKeys.keyAt(i),
3385 fallbackKeys.valueAt(i));
3386 }
3387 LOGD("Unhandled key event: %d currently tracked fallback keys%s.",
3388 fallbackKeys.size(), msg.string());
3389 }
3390#endif
3391
Jeff Brown49ed71d2010-12-06 17:13:33 -08003392 if (fallback) {
3393 // Restart the dispatch cycle using the fallback key.
3394 keyEntry->eventTime = event.getEventTime();
3395 keyEntry->deviceId = event.getDeviceId();
3396 keyEntry->source = event.getSource();
3397 keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
Jeff Brown524ee642011-03-29 15:11:34 -07003398 keyEntry->keyCode = fallbackKeyCode;
Jeff Brown49ed71d2010-12-06 17:13:33 -08003399 keyEntry->scanCode = event.getScanCode();
3400 keyEntry->metaState = event.getMetaState();
3401 keyEntry->repeatCount = event.getRepeatCount();
3402 keyEntry->downTime = event.getDownTime();
3403 keyEntry->syntheticRepeat = false;
3404
Jeff Brownbfaf3b92011-02-22 15:00:50 -08003405#if DEBUG_OUTBOUND_EVENT_DETAILS
3406 LOGD("Unhandled key event: Dispatching fallback key. "
Jeff Brown524ee642011-03-29 15:11:34 -07003407 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
3408 originalKeyCode, fallbackKeyCode, keyEntry->metaState);
Jeff Brownbfaf3b92011-02-22 15:00:50 -08003409#endif
3410
Jeff Brown49ed71d2010-12-06 17:13:33 -08003411 dispatchEntry->inProgress = false;
3412 startDispatchCycleLocked(now(), connection);
3413 return;
Jeff Brown524ee642011-03-29 15:11:34 -07003414 } else {
3415#if DEBUG_OUTBOUND_EVENT_DETAILS
3416 LOGD("Unhandled key event: No fallback key.");
3417#endif
Jeff Brown49ed71d2010-12-06 17:13:33 -08003418 }
3419 }
3420 }
Jeff Brown3915bb82010-11-05 15:02:16 -07003421 }
3422 }
3423
Jeff Brownbfaf3b92011-02-22 15:00:50 -08003424SkipFallback:
Jeff Brown3915bb82010-11-05 15:02:16 -07003425 startNextDispatchCycleLocked(now(), connection);
3426}
3427
Jeff Brownb88102f2010-09-08 11:49:43 -07003428void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
3429 mLock.unlock();
3430
Jeff Brown01ce2e92010-09-26 22:20:12 -07003431 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
Jeff Brownb88102f2010-09-08 11:49:43 -07003432
3433 mLock.lock();
3434}
3435
Jeff Brown3915bb82010-11-05 15:02:16 -07003436void InputDispatcher::initializeKeyEvent(KeyEvent* event, const KeyEntry* entry) {
3437 event->initialize(entry->deviceId, entry->source, entry->action, entry->flags,
3438 entry->keyCode, entry->scanCode, entry->metaState, entry->repeatCount,
3439 entry->downTime, entry->eventTime);
3440}
3441
Jeff Brown519e0242010-09-15 15:18:56 -07003442void InputDispatcher::updateDispatchStatisticsLocked(nsecs_t currentTime, const EventEntry* entry,
3443 int32_t injectionResult, nsecs_t timeSpentWaitingForApplication) {
3444 // TODO Write some statistics about how long we spend waiting.
Jeff Brownb88102f2010-09-08 11:49:43 -07003445}
3446
3447void InputDispatcher::dump(String8& dump) {
Jeff Brownf2f487182010-10-01 17:46:21 -07003448 dump.append("Input Dispatcher State:\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003449 dumpDispatchStateLocked(dump);
3450}
3451
Jeff Brown9c3cda02010-06-15 01:31:58 -07003452
Jeff Brown519e0242010-09-15 15:18:56 -07003453// --- InputDispatcher::Queue ---
3454
3455template <typename T>
3456uint32_t InputDispatcher::Queue<T>::count() const {
3457 uint32_t result = 0;
3458 for (const T* entry = headSentinel.next; entry != & tailSentinel; entry = entry->next) {
3459 result += 1;
3460 }
3461 return result;
3462}
3463
3464
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003465// --- InputDispatcher::Allocator ---
3466
3467InputDispatcher::Allocator::Allocator() {
3468}
3469
Jeff Brown01ce2e92010-09-26 22:20:12 -07003470InputDispatcher::InjectionState*
3471InputDispatcher::Allocator::obtainInjectionState(int32_t injectorPid, int32_t injectorUid) {
3472 InjectionState* injectionState = mInjectionStatePool.alloc();
3473 injectionState->refCount = 1;
3474 injectionState->injectorPid = injectorPid;
3475 injectionState->injectorUid = injectorUid;
3476 injectionState->injectionIsAsync = false;
3477 injectionState->injectionResult = INPUT_EVENT_INJECTION_PENDING;
3478 injectionState->pendingForegroundDispatches = 0;
3479 return injectionState;
3480}
3481
Jeff Brown7fbdc842010-06-17 20:52:56 -07003482void InputDispatcher::Allocator::initializeEventEntry(EventEntry* entry, int32_t type,
Jeff Brownb6997262010-10-08 22:31:17 -07003483 nsecs_t eventTime, uint32_t policyFlags) {
Jeff Brown7fbdc842010-06-17 20:52:56 -07003484 entry->type = type;
3485 entry->refCount = 1;
3486 entry->dispatchInProgress = false;
Christopher Tatee91a5db2010-06-23 16:50:30 -07003487 entry->eventTime = eventTime;
Jeff Brownb6997262010-10-08 22:31:17 -07003488 entry->policyFlags = policyFlags;
Jeff Brown01ce2e92010-09-26 22:20:12 -07003489 entry->injectionState = NULL;
3490}
3491
3492void InputDispatcher::Allocator::releaseEventEntryInjectionState(EventEntry* entry) {
3493 if (entry->injectionState) {
3494 releaseInjectionState(entry->injectionState);
3495 entry->injectionState = NULL;
3496 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07003497}
3498
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003499InputDispatcher::ConfigurationChangedEntry*
Jeff Brown7fbdc842010-06-17 20:52:56 -07003500InputDispatcher::Allocator::obtainConfigurationChangedEntry(nsecs_t eventTime) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003501 ConfigurationChangedEntry* entry = mConfigurationChangeEntryPool.alloc();
Jeff Brownb6997262010-10-08 22:31:17 -07003502 initializeEventEntry(entry, EventEntry::TYPE_CONFIGURATION_CHANGED, eventTime, 0);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003503 return entry;
3504}
3505
Jeff Brown7fbdc842010-06-17 20:52:56 -07003506InputDispatcher::KeyEntry* InputDispatcher::Allocator::obtainKeyEntry(nsecs_t eventTime,
Jeff Brown58a2da82011-01-25 16:02:22 -08003507 int32_t deviceId, uint32_t source, uint32_t policyFlags, int32_t action,
Jeff Brown7fbdc842010-06-17 20:52:56 -07003508 int32_t flags, int32_t keyCode, int32_t scanCode, int32_t metaState,
3509 int32_t repeatCount, nsecs_t downTime) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003510 KeyEntry* entry = mKeyEntryPool.alloc();
Jeff Brownb6997262010-10-08 22:31:17 -07003511 initializeEventEntry(entry, EventEntry::TYPE_KEY, eventTime, policyFlags);
Jeff Brown7fbdc842010-06-17 20:52:56 -07003512
3513 entry->deviceId = deviceId;
Jeff Brownc5ed5912010-07-14 18:48:53 -07003514 entry->source = source;
Jeff Brown7fbdc842010-06-17 20:52:56 -07003515 entry->action = action;
3516 entry->flags = flags;
3517 entry->keyCode = keyCode;
3518 entry->scanCode = scanCode;
3519 entry->metaState = metaState;
3520 entry->repeatCount = repeatCount;
3521 entry->downTime = downTime;
Jeff Brownb88102f2010-09-08 11:49:43 -07003522 entry->syntheticRepeat = false;
3523 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003524 return entry;
3525}
3526
Jeff Brown7fbdc842010-06-17 20:52:56 -07003527InputDispatcher::MotionEntry* InputDispatcher::Allocator::obtainMotionEntry(nsecs_t eventTime,
Jeff Brown58a2da82011-01-25 16:02:22 -08003528 int32_t deviceId, uint32_t source, uint32_t policyFlags, int32_t action, int32_t flags,
Jeff Brown7fbdc842010-06-17 20:52:56 -07003529 int32_t metaState, int32_t edgeFlags, float xPrecision, float yPrecision,
3530 nsecs_t downTime, uint32_t pointerCount,
3531 const int32_t* pointerIds, const PointerCoords* pointerCoords) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003532 MotionEntry* entry = mMotionEntryPool.alloc();
Jeff Brownb6997262010-10-08 22:31:17 -07003533 initializeEventEntry(entry, EventEntry::TYPE_MOTION, eventTime, policyFlags);
Jeff Brown7fbdc842010-06-17 20:52:56 -07003534
3535 entry->eventTime = eventTime;
3536 entry->deviceId = deviceId;
Jeff Brownc5ed5912010-07-14 18:48:53 -07003537 entry->source = source;
Jeff Brown7fbdc842010-06-17 20:52:56 -07003538 entry->action = action;
Jeff Brown85a31762010-09-01 17:01:00 -07003539 entry->flags = flags;
Jeff Brown7fbdc842010-06-17 20:52:56 -07003540 entry->metaState = metaState;
3541 entry->edgeFlags = edgeFlags;
3542 entry->xPrecision = xPrecision;
3543 entry->yPrecision = yPrecision;
3544 entry->downTime = downTime;
3545 entry->pointerCount = pointerCount;
3546 entry->firstSample.eventTime = eventTime;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003547 entry->firstSample.next = NULL;
Jeff Brown7fbdc842010-06-17 20:52:56 -07003548 entry->lastSample = & entry->firstSample;
3549 for (uint32_t i = 0; i < pointerCount; i++) {
3550 entry->pointerIds[i] = pointerIds[i];
Jeff Brown96ad3972011-03-09 17:39:48 -08003551 entry->firstSample.pointerCoords[i].copyFrom(pointerCoords[i]);
Jeff Brown7fbdc842010-06-17 20:52:56 -07003552 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003553 return entry;
3554}
3555
3556InputDispatcher::DispatchEntry* InputDispatcher::Allocator::obtainDispatchEntry(
Jeff Brownb88102f2010-09-08 11:49:43 -07003557 EventEntry* eventEntry,
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003558 int32_t targetFlags, float xOffset, float yOffset, float scaleFactor) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003559 DispatchEntry* entry = mDispatchEntryPool.alloc();
3560 entry->eventEntry = eventEntry;
3561 eventEntry->refCount += 1;
Jeff Brownb88102f2010-09-08 11:49:43 -07003562 entry->targetFlags = targetFlags;
3563 entry->xOffset = xOffset;
3564 entry->yOffset = yOffset;
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003565 entry->scaleFactor = scaleFactor;
Jeff Brownb88102f2010-09-08 11:49:43 -07003566 entry->inProgress = false;
3567 entry->headMotionSample = NULL;
3568 entry->tailMotionSample = NULL;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003569 return entry;
3570}
3571
Jeff Brown9c3cda02010-06-15 01:31:58 -07003572InputDispatcher::CommandEntry* InputDispatcher::Allocator::obtainCommandEntry(Command command) {
3573 CommandEntry* entry = mCommandEntryPool.alloc();
3574 entry->command = command;
3575 return entry;
3576}
3577
Jeff Brown01ce2e92010-09-26 22:20:12 -07003578void InputDispatcher::Allocator::releaseInjectionState(InjectionState* injectionState) {
3579 injectionState->refCount -= 1;
3580 if (injectionState->refCount == 0) {
3581 mInjectionStatePool.free(injectionState);
3582 } else {
3583 assert(injectionState->refCount > 0);
3584 }
3585}
3586
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003587void InputDispatcher::Allocator::releaseEventEntry(EventEntry* entry) {
3588 switch (entry->type) {
3589 case EventEntry::TYPE_CONFIGURATION_CHANGED:
3590 releaseConfigurationChangedEntry(static_cast<ConfigurationChangedEntry*>(entry));
3591 break;
3592 case EventEntry::TYPE_KEY:
3593 releaseKeyEntry(static_cast<KeyEntry*>(entry));
3594 break;
3595 case EventEntry::TYPE_MOTION:
3596 releaseMotionEntry(static_cast<MotionEntry*>(entry));
3597 break;
3598 default:
3599 assert(false);
3600 break;
3601 }
3602}
3603
3604void InputDispatcher::Allocator::releaseConfigurationChangedEntry(
3605 ConfigurationChangedEntry* entry) {
3606 entry->refCount -= 1;
3607 if (entry->refCount == 0) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07003608 releaseEventEntryInjectionState(entry);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003609 mConfigurationChangeEntryPool.free(entry);
3610 } else {
3611 assert(entry->refCount > 0);
3612 }
3613}
3614
3615void InputDispatcher::Allocator::releaseKeyEntry(KeyEntry* entry) {
3616 entry->refCount -= 1;
3617 if (entry->refCount == 0) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07003618 releaseEventEntryInjectionState(entry);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003619 mKeyEntryPool.free(entry);
3620 } else {
3621 assert(entry->refCount > 0);
3622 }
3623}
3624
3625void InputDispatcher::Allocator::releaseMotionEntry(MotionEntry* entry) {
3626 entry->refCount -= 1;
3627 if (entry->refCount == 0) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07003628 releaseEventEntryInjectionState(entry);
Jeff Brown9c3cda02010-06-15 01:31:58 -07003629 for (MotionSample* sample = entry->firstSample.next; sample != NULL; ) {
3630 MotionSample* next = sample->next;
3631 mMotionSamplePool.free(sample);
3632 sample = next;
3633 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003634 mMotionEntryPool.free(entry);
3635 } else {
3636 assert(entry->refCount > 0);
3637 }
3638}
3639
3640void InputDispatcher::Allocator::releaseDispatchEntry(DispatchEntry* entry) {
3641 releaseEventEntry(entry->eventEntry);
3642 mDispatchEntryPool.free(entry);
3643}
3644
Jeff Brown9c3cda02010-06-15 01:31:58 -07003645void InputDispatcher::Allocator::releaseCommandEntry(CommandEntry* entry) {
3646 mCommandEntryPool.free(entry);
3647}
3648
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003649void InputDispatcher::Allocator::appendMotionSample(MotionEntry* motionEntry,
Jeff Brown7fbdc842010-06-17 20:52:56 -07003650 nsecs_t eventTime, const PointerCoords* pointerCoords) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003651 MotionSample* sample = mMotionSamplePool.alloc();
3652 sample->eventTime = eventTime;
Jeff Brown7fbdc842010-06-17 20:52:56 -07003653 uint32_t pointerCount = motionEntry->pointerCount;
3654 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brown96ad3972011-03-09 17:39:48 -08003655 sample->pointerCoords[i].copyFrom(pointerCoords[i]);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003656 }
3657
3658 sample->next = NULL;
3659 motionEntry->lastSample->next = sample;
3660 motionEntry->lastSample = sample;
3661}
3662
Jeff Brown01ce2e92010-09-26 22:20:12 -07003663void InputDispatcher::Allocator::recycleKeyEntry(KeyEntry* keyEntry) {
3664 releaseEventEntryInjectionState(keyEntry);
Jeff Brownb88102f2010-09-08 11:49:43 -07003665
Jeff Brown01ce2e92010-09-26 22:20:12 -07003666 keyEntry->dispatchInProgress = false;
3667 keyEntry->syntheticRepeat = false;
3668 keyEntry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
Jeff Brownb88102f2010-09-08 11:49:43 -07003669}
3670
3671
Jeff Brownae9fc032010-08-18 15:51:08 -07003672// --- InputDispatcher::MotionEntry ---
3673
3674uint32_t InputDispatcher::MotionEntry::countSamples() const {
3675 uint32_t count = 1;
3676 for (MotionSample* sample = firstSample.next; sample != NULL; sample = sample->next) {
3677 count += 1;
3678 }
3679 return count;
3680}
3681
Jeff Brownb88102f2010-09-08 11:49:43 -07003682
3683// --- InputDispatcher::InputState ---
3684
Jeff Brownb6997262010-10-08 22:31:17 -07003685InputDispatcher::InputState::InputState() {
Jeff Brownb88102f2010-09-08 11:49:43 -07003686}
3687
3688InputDispatcher::InputState::~InputState() {
3689}
3690
3691bool InputDispatcher::InputState::isNeutral() const {
3692 return mKeyMementos.isEmpty() && mMotionMementos.isEmpty();
3693}
3694
Jeff Browncc0c1592011-02-19 05:07:28 -08003695void InputDispatcher::InputState::trackEvent(
Jeff Brownb88102f2010-09-08 11:49:43 -07003696 const EventEntry* entry) {
3697 switch (entry->type) {
3698 case EventEntry::TYPE_KEY:
Jeff Browncc0c1592011-02-19 05:07:28 -08003699 trackKey(static_cast<const KeyEntry*>(entry));
3700 break;
Jeff Brownb88102f2010-09-08 11:49:43 -07003701
3702 case EventEntry::TYPE_MOTION:
Jeff Browncc0c1592011-02-19 05:07:28 -08003703 trackMotion(static_cast<const MotionEntry*>(entry));
3704 break;
Jeff Brownb88102f2010-09-08 11:49:43 -07003705 }
3706}
3707
Jeff Browncc0c1592011-02-19 05:07:28 -08003708void InputDispatcher::InputState::trackKey(
Jeff Brownb88102f2010-09-08 11:49:43 -07003709 const KeyEntry* entry) {
3710 int32_t action = entry->action;
Jeff Brown524ee642011-03-29 15:11:34 -07003711 if (action == AKEY_EVENT_ACTION_UP
3712 && (entry->flags & AKEY_EVENT_FLAG_FALLBACK)) {
3713 for (size_t i = 0; i < mFallbackKeys.size(); ) {
3714 if (mFallbackKeys.valueAt(i) == entry->keyCode) {
3715 mFallbackKeys.removeItemsAt(i);
3716 } else {
3717 i += 1;
3718 }
3719 }
3720 }
3721
Jeff Brownb88102f2010-09-08 11:49:43 -07003722 for (size_t i = 0; i < mKeyMementos.size(); i++) {
3723 KeyMemento& memento = mKeyMementos.editItemAt(i);
3724 if (memento.deviceId == entry->deviceId
3725 && memento.source == entry->source
3726 && memento.keyCode == entry->keyCode
3727 && memento.scanCode == entry->scanCode) {
3728 switch (action) {
3729 case AKEY_EVENT_ACTION_UP:
3730 mKeyMementos.removeAt(i);
Jeff Browncc0c1592011-02-19 05:07:28 -08003731 return;
Jeff Brownb88102f2010-09-08 11:49:43 -07003732
3733 case AKEY_EVENT_ACTION_DOWN:
Jeff Browncc0c1592011-02-19 05:07:28 -08003734 mKeyMementos.removeAt(i);
3735 goto Found;
Jeff Brownb88102f2010-09-08 11:49:43 -07003736
3737 default:
Jeff Browncc0c1592011-02-19 05:07:28 -08003738 return;
Jeff Brownb88102f2010-09-08 11:49:43 -07003739 }
3740 }
3741 }
3742
Jeff Browncc0c1592011-02-19 05:07:28 -08003743Found:
3744 if (action == AKEY_EVENT_ACTION_DOWN) {
Jeff Brownb88102f2010-09-08 11:49:43 -07003745 mKeyMementos.push();
3746 KeyMemento& memento = mKeyMementos.editTop();
3747 memento.deviceId = entry->deviceId;
3748 memento.source = entry->source;
3749 memento.keyCode = entry->keyCode;
3750 memento.scanCode = entry->scanCode;
Jeff Brown49ed71d2010-12-06 17:13:33 -08003751 memento.flags = entry->flags;
Jeff Brownb88102f2010-09-08 11:49:43 -07003752 memento.downTime = entry->downTime;
Jeff Brownb88102f2010-09-08 11:49:43 -07003753 }
3754}
3755
Jeff Browncc0c1592011-02-19 05:07:28 -08003756void InputDispatcher::InputState::trackMotion(
Jeff Brownb88102f2010-09-08 11:49:43 -07003757 const MotionEntry* entry) {
3758 int32_t action = entry->action & AMOTION_EVENT_ACTION_MASK;
3759 for (size_t i = 0; i < mMotionMementos.size(); i++) {
3760 MotionMemento& memento = mMotionMementos.editItemAt(i);
3761 if (memento.deviceId == entry->deviceId
3762 && memento.source == entry->source) {
3763 switch (action) {
3764 case AMOTION_EVENT_ACTION_UP:
3765 case AMOTION_EVENT_ACTION_CANCEL:
Jeff Browncc0c1592011-02-19 05:07:28 -08003766 case AMOTION_EVENT_ACTION_HOVER_MOVE:
Jeff Brownb88102f2010-09-08 11:49:43 -07003767 mMotionMementos.removeAt(i);
Jeff Browncc0c1592011-02-19 05:07:28 -08003768 return;
Jeff Brownb88102f2010-09-08 11:49:43 -07003769
3770 case AMOTION_EVENT_ACTION_DOWN:
Jeff Browncc0c1592011-02-19 05:07:28 -08003771 mMotionMementos.removeAt(i);
3772 goto Found;
Jeff Brownb88102f2010-09-08 11:49:43 -07003773
3774 case AMOTION_EVENT_ACTION_POINTER_UP:
Jeff Browncc0c1592011-02-19 05:07:28 -08003775 case AMOTION_EVENT_ACTION_POINTER_DOWN:
Jeff Brownb88102f2010-09-08 11:49:43 -07003776 case AMOTION_EVENT_ACTION_MOVE:
Jeff Browncc0c1592011-02-19 05:07:28 -08003777 memento.setPointers(entry);
3778 return;
Jeff Brownb88102f2010-09-08 11:49:43 -07003779
3780 default:
Jeff Browncc0c1592011-02-19 05:07:28 -08003781 return;
Jeff Brownb88102f2010-09-08 11:49:43 -07003782 }
3783 }
3784 }
3785
Jeff Browncc0c1592011-02-19 05:07:28 -08003786Found:
3787 if (action == AMOTION_EVENT_ACTION_DOWN) {
Jeff Brownb88102f2010-09-08 11:49:43 -07003788 mMotionMementos.push();
3789 MotionMemento& memento = mMotionMementos.editTop();
3790 memento.deviceId = entry->deviceId;
3791 memento.source = entry->source;
3792 memento.xPrecision = entry->xPrecision;
3793 memento.yPrecision = entry->yPrecision;
3794 memento.downTime = entry->downTime;
3795 memento.setPointers(entry);
Jeff Brownb88102f2010-09-08 11:49:43 -07003796 }
3797}
3798
3799void InputDispatcher::InputState::MotionMemento::setPointers(const MotionEntry* entry) {
3800 pointerCount = entry->pointerCount;
3801 for (uint32_t i = 0; i < entry->pointerCount; i++) {
3802 pointerIds[i] = entry->pointerIds[i];
Jeff Brown96ad3972011-03-09 17:39:48 -08003803 pointerCoords[i].copyFrom(entry->lastSample->pointerCoords[i]);
Jeff Brownb88102f2010-09-08 11:49:43 -07003804 }
3805}
3806
Jeff Brownb6997262010-10-08 22:31:17 -07003807void InputDispatcher::InputState::synthesizeCancelationEvents(nsecs_t currentTime,
3808 Allocator* allocator, Vector<EventEntry*>& outEvents,
Jeff Brown524ee642011-03-29 15:11:34 -07003809 const CancelationOptions& options) {
Jeff Brownb6997262010-10-08 22:31:17 -07003810 for (size_t i = 0; i < mKeyMementos.size(); ) {
Jeff Brownb88102f2010-09-08 11:49:43 -07003811 const KeyMemento& memento = mKeyMementos.itemAt(i);
Jeff Brown49ed71d2010-12-06 17:13:33 -08003812 if (shouldCancelKey(memento, options)) {
Jeff Brownb6997262010-10-08 22:31:17 -07003813 outEvents.push(allocator->obtainKeyEntry(currentTime,
3814 memento.deviceId, memento.source, 0,
Jeff Brown49ed71d2010-12-06 17:13:33 -08003815 AKEY_EVENT_ACTION_UP, memento.flags | AKEY_EVENT_FLAG_CANCELED,
Jeff Brownb6997262010-10-08 22:31:17 -07003816 memento.keyCode, memento.scanCode, 0, 0, memento.downTime));
3817 mKeyMementos.removeAt(i);
3818 } else {
3819 i += 1;
3820 }
Jeff Brownb88102f2010-09-08 11:49:43 -07003821 }
3822
Jeff Browna1160a72010-10-11 18:22:53 -07003823 for (size_t i = 0; i < mMotionMementos.size(); ) {
Jeff Brownb88102f2010-09-08 11:49:43 -07003824 const MotionMemento& memento = mMotionMementos.itemAt(i);
Jeff Brown49ed71d2010-12-06 17:13:33 -08003825 if (shouldCancelMotion(memento, options)) {
Jeff Brownb6997262010-10-08 22:31:17 -07003826 outEvents.push(allocator->obtainMotionEntry(currentTime,
3827 memento.deviceId, memento.source, 0,
3828 AMOTION_EVENT_ACTION_CANCEL, 0, 0, 0,
3829 memento.xPrecision, memento.yPrecision, memento.downTime,
3830 memento.pointerCount, memento.pointerIds, memento.pointerCoords));
3831 mMotionMementos.removeAt(i);
3832 } else {
3833 i += 1;
3834 }
Jeff Brownb88102f2010-09-08 11:49:43 -07003835 }
3836}
3837
3838void InputDispatcher::InputState::clear() {
3839 mKeyMementos.clear();
3840 mMotionMementos.clear();
Jeff Brown524ee642011-03-29 15:11:34 -07003841 mFallbackKeys.clear();
Jeff Brownb6997262010-10-08 22:31:17 -07003842}
3843
Jeff Brown9c9f1a32010-10-11 18:32:20 -07003844void InputDispatcher::InputState::copyPointerStateTo(InputState& other) const {
3845 for (size_t i = 0; i < mMotionMementos.size(); i++) {
3846 const MotionMemento& memento = mMotionMementos.itemAt(i);
3847 if (memento.source & AINPUT_SOURCE_CLASS_POINTER) {
3848 for (size_t j = 0; j < other.mMotionMementos.size(); ) {
3849 const MotionMemento& otherMemento = other.mMotionMementos.itemAt(j);
3850 if (memento.deviceId == otherMemento.deviceId
3851 && memento.source == otherMemento.source) {
3852 other.mMotionMementos.removeAt(j);
3853 } else {
3854 j += 1;
3855 }
3856 }
3857 other.mMotionMementos.push(memento);
3858 }
3859 }
3860}
3861
Jeff Brown524ee642011-03-29 15:11:34 -07003862int32_t InputDispatcher::InputState::getFallbackKey(int32_t originalKeyCode) {
3863 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
3864 return index >= 0 ? mFallbackKeys.valueAt(index) : -1;
3865}
3866
3867void InputDispatcher::InputState::setFallbackKey(int32_t originalKeyCode,
3868 int32_t fallbackKeyCode) {
3869 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
3870 if (index >= 0) {
3871 mFallbackKeys.replaceValueAt(index, fallbackKeyCode);
3872 } else {
3873 mFallbackKeys.add(originalKeyCode, fallbackKeyCode);
3874 }
3875}
3876
3877void InputDispatcher::InputState::removeFallbackKey(int32_t originalKeyCode) {
3878 mFallbackKeys.removeItem(originalKeyCode);
3879}
3880
Jeff Brown49ed71d2010-12-06 17:13:33 -08003881bool InputDispatcher::InputState::shouldCancelKey(const KeyMemento& memento,
Jeff Brown524ee642011-03-29 15:11:34 -07003882 const CancelationOptions& options) {
3883 if (options.keyCode != -1 && memento.keyCode != options.keyCode) {
3884 return false;
3885 }
3886
3887 switch (options.mode) {
3888 case CancelationOptions::CANCEL_ALL_EVENTS:
3889 case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
Jeff Brownb6997262010-10-08 22:31:17 -07003890 return true;
Jeff Brown524ee642011-03-29 15:11:34 -07003891 case CancelationOptions::CANCEL_FALLBACK_EVENTS:
Jeff Brown49ed71d2010-12-06 17:13:33 -08003892 return memento.flags & AKEY_EVENT_FLAG_FALLBACK;
3893 default:
3894 return false;
3895 }
3896}
3897
3898bool InputDispatcher::InputState::shouldCancelMotion(const MotionMemento& memento,
Jeff Brown524ee642011-03-29 15:11:34 -07003899 const CancelationOptions& options) {
3900 switch (options.mode) {
3901 case CancelationOptions::CANCEL_ALL_EVENTS:
Jeff Brown49ed71d2010-12-06 17:13:33 -08003902 return true;
Jeff Brown524ee642011-03-29 15:11:34 -07003903 case CancelationOptions::CANCEL_POINTER_EVENTS:
Jeff Brown49ed71d2010-12-06 17:13:33 -08003904 return memento.source & AINPUT_SOURCE_CLASS_POINTER;
Jeff Brown524ee642011-03-29 15:11:34 -07003905 case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
Jeff Brown49ed71d2010-12-06 17:13:33 -08003906 return !(memento.source & AINPUT_SOURCE_CLASS_POINTER);
3907 default:
3908 return false;
Jeff Brownb6997262010-10-08 22:31:17 -07003909 }
Jeff Brownb88102f2010-09-08 11:49:43 -07003910}
3911
3912
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003913// --- InputDispatcher::Connection ---
3914
Jeff Brown928e0542011-01-10 11:17:36 -08003915InputDispatcher::Connection::Connection(const sp<InputChannel>& inputChannel,
3916 const sp<InputWindowHandle>& inputWindowHandle) :
3917 status(STATUS_NORMAL), inputChannel(inputChannel), inputWindowHandle(inputWindowHandle),
3918 inputPublisher(inputChannel),
Jeff Brown524ee642011-03-29 15:11:34 -07003919 lastEventTime(LONG_LONG_MAX), lastDispatchTime(LONG_LONG_MAX) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003920}
3921
3922InputDispatcher::Connection::~Connection() {
3923}
3924
3925status_t InputDispatcher::Connection::initialize() {
3926 return inputPublisher.initialize();
3927}
3928
Jeff Brown9c3cda02010-06-15 01:31:58 -07003929const char* InputDispatcher::Connection::getStatusLabel() const {
3930 switch (status) {
3931 case STATUS_NORMAL:
3932 return "NORMAL";
3933
3934 case STATUS_BROKEN:
3935 return "BROKEN";
3936
Jeff Brown9c3cda02010-06-15 01:31:58 -07003937 case STATUS_ZOMBIE:
3938 return "ZOMBIE";
3939
3940 default:
3941 return "UNKNOWN";
3942 }
3943}
3944
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003945InputDispatcher::DispatchEntry* InputDispatcher::Connection::findQueuedDispatchEntryForEvent(
3946 const EventEntry* eventEntry) const {
Jeff Brownb88102f2010-09-08 11:49:43 -07003947 for (DispatchEntry* dispatchEntry = outboundQueue.tailSentinel.prev;
3948 dispatchEntry != & outboundQueue.headSentinel; dispatchEntry = dispatchEntry->prev) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003949 if (dispatchEntry->eventEntry == eventEntry) {
3950 return dispatchEntry;
3951 }
3952 }
3953 return NULL;
3954}
3955
Jeff Brownb88102f2010-09-08 11:49:43 -07003956
Jeff Brown9c3cda02010-06-15 01:31:58 -07003957// --- InputDispatcher::CommandEntry ---
3958
Jeff Brownb88102f2010-09-08 11:49:43 -07003959InputDispatcher::CommandEntry::CommandEntry() :
3960 keyEntry(NULL) {
Jeff Brown9c3cda02010-06-15 01:31:58 -07003961}
3962
3963InputDispatcher::CommandEntry::~CommandEntry() {
3964}
3965
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003966
Jeff Brown01ce2e92010-09-26 22:20:12 -07003967// --- InputDispatcher::TouchState ---
3968
3969InputDispatcher::TouchState::TouchState() :
Jeff Brown58a2da82011-01-25 16:02:22 -08003970 down(false), split(false), deviceId(-1), source(0) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07003971}
3972
3973InputDispatcher::TouchState::~TouchState() {
3974}
3975
3976void InputDispatcher::TouchState::reset() {
3977 down = false;
3978 split = false;
Jeff Brown95712852011-01-04 19:41:59 -08003979 deviceId = -1;
Jeff Brown58a2da82011-01-25 16:02:22 -08003980 source = 0;
Jeff Brown01ce2e92010-09-26 22:20:12 -07003981 windows.clear();
3982}
3983
3984void InputDispatcher::TouchState::copyFrom(const TouchState& other) {
3985 down = other.down;
3986 split = other.split;
Jeff Brown95712852011-01-04 19:41:59 -08003987 deviceId = other.deviceId;
Jeff Brown58a2da82011-01-25 16:02:22 -08003988 source = other.source;
Jeff Brown01ce2e92010-09-26 22:20:12 -07003989 windows.clear();
3990 windows.appendVector(other.windows);
3991}
3992
3993void InputDispatcher::TouchState::addOrUpdateWindow(const InputWindow* window,
3994 int32_t targetFlags, BitSet32 pointerIds) {
3995 if (targetFlags & InputTarget::FLAG_SPLIT) {
3996 split = true;
3997 }
3998
3999 for (size_t i = 0; i < windows.size(); i++) {
4000 TouchedWindow& touchedWindow = windows.editItemAt(i);
4001 if (touchedWindow.window == window) {
4002 touchedWindow.targetFlags |= targetFlags;
4003 touchedWindow.pointerIds.value |= pointerIds.value;
4004 return;
4005 }
4006 }
4007
4008 windows.push();
4009
4010 TouchedWindow& touchedWindow = windows.editTop();
4011 touchedWindow.window = window;
4012 touchedWindow.targetFlags = targetFlags;
4013 touchedWindow.pointerIds = pointerIds;
4014 touchedWindow.channel = window->inputChannel;
4015}
4016
4017void InputDispatcher::TouchState::removeOutsideTouchWindows() {
4018 for (size_t i = 0 ; i < windows.size(); ) {
4019 if (windows[i].targetFlags & InputTarget::FLAG_OUTSIDE) {
4020 windows.removeAt(i);
4021 } else {
4022 i += 1;
4023 }
4024 }
4025}
4026
4027const InputWindow* InputDispatcher::TouchState::getFirstForegroundWindow() {
4028 for (size_t i = 0; i < windows.size(); i++) {
4029 if (windows[i].targetFlags & InputTarget::FLAG_FOREGROUND) {
4030 return windows[i].window;
4031 }
4032 }
4033 return NULL;
4034}
4035
4036
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004037// --- InputDispatcherThread ---
4038
4039InputDispatcherThread::InputDispatcherThread(const sp<InputDispatcherInterface>& dispatcher) :
4040 Thread(/*canCallJava*/ true), mDispatcher(dispatcher) {
4041}
4042
4043InputDispatcherThread::~InputDispatcherThread() {
4044}
4045
4046bool InputDispatcherThread::threadLoop() {
4047 mDispatcher->dispatchOnce();
4048 return true;
4049}
4050
4051} // namespace android