blob: 810b7091da3644a2d08657886aa3ec2851668150 [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 Browna032cc02011-03-07 16:56:21 -080051// Log debug messages about hover events.
52#define DEBUG_HOVER 0
53
Jeff Brownb4ff35d2011-01-02 16:37:43 -080054#include "InputDispatcher.h"
55
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070056#include <cutils/log.h>
Jeff Brownb88102f2010-09-08 11:49:43 -070057#include <ui/PowerManager.h>
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070058
59#include <stddef.h>
60#include <unistd.h>
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070061#include <errno.h>
62#include <limits.h>
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070063
Jeff Brownf2f487182010-10-01 17:46:21 -070064#define INDENT " "
65#define INDENT2 " "
66
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070067namespace android {
68
Jeff Brownb88102f2010-09-08 11:49:43 -070069// Default input dispatching timeout if there is no focused application or paused window
70// from which to determine an appropriate dispatching timeout.
71const nsecs_t DEFAULT_INPUT_DISPATCHING_TIMEOUT = 5000 * 1000000LL; // 5 sec
72
73// Amount of time to allow for all pending events to be processed when an app switch
74// key is on the way. This is used to preempt input dispatch and drop input events
75// when an application takes too long to respond and the user has pressed an app switch key.
76const nsecs_t APP_SWITCH_TIMEOUT = 500 * 1000000LL; // 0.5sec
77
Jeff Brown928e0542011-01-10 11:17:36 -080078// Amount of time to allow for an event to be dispatched (measured since its eventTime)
79// before considering it stale and dropping it.
80const nsecs_t STALE_EVENT_TIMEOUT = 10000 * 1000000LL; // 10sec
81
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070082
Jeff Brown7fbdc842010-06-17 20:52:56 -070083static inline nsecs_t now() {
84 return systemTime(SYSTEM_TIME_MONOTONIC);
85}
86
Jeff Brownb88102f2010-09-08 11:49:43 -070087static inline const char* toString(bool value) {
88 return value ? "true" : "false";
89}
90
Jeff Brown01ce2e92010-09-26 22:20:12 -070091static inline int32_t getMotionEventActionPointerIndex(int32_t action) {
92 return (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK)
93 >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
94}
95
96static bool isValidKeyAction(int32_t action) {
97 switch (action) {
98 case AKEY_EVENT_ACTION_DOWN:
99 case AKEY_EVENT_ACTION_UP:
100 return true;
101 default:
102 return false;
103 }
104}
105
106static bool validateKeyEvent(int32_t action) {
107 if (! isValidKeyAction(action)) {
108 LOGE("Key event has invalid action code 0x%x", action);
109 return false;
110 }
111 return true;
112}
113
Jeff Brownb6997262010-10-08 22:31:17 -0700114static bool isValidMotionAction(int32_t action, size_t pointerCount) {
Jeff Brown01ce2e92010-09-26 22:20:12 -0700115 switch (action & AMOTION_EVENT_ACTION_MASK) {
116 case AMOTION_EVENT_ACTION_DOWN:
117 case AMOTION_EVENT_ACTION_UP:
118 case AMOTION_EVENT_ACTION_CANCEL:
119 case AMOTION_EVENT_ACTION_MOVE:
Jeff Brown01ce2e92010-09-26 22:20:12 -0700120 case AMOTION_EVENT_ACTION_OUTSIDE:
Jeff Browna032cc02011-03-07 16:56:21 -0800121 case AMOTION_EVENT_ACTION_HOVER_ENTER:
Jeff Browncc0c1592011-02-19 05:07:28 -0800122 case AMOTION_EVENT_ACTION_HOVER_MOVE:
Jeff Browna032cc02011-03-07 16:56:21 -0800123 case AMOTION_EVENT_ACTION_HOVER_EXIT:
Jeff Brown33bbfd22011-02-24 20:55:35 -0800124 case AMOTION_EVENT_ACTION_SCROLL:
Jeff Brown01ce2e92010-09-26 22:20:12 -0700125 return true;
Jeff Brownb6997262010-10-08 22:31:17 -0700126 case AMOTION_EVENT_ACTION_POINTER_DOWN:
127 case AMOTION_EVENT_ACTION_POINTER_UP: {
128 int32_t index = getMotionEventActionPointerIndex(action);
129 return index >= 0 && size_t(index) < pointerCount;
130 }
Jeff Brown01ce2e92010-09-26 22:20:12 -0700131 default:
132 return false;
133 }
134}
135
136static bool validateMotionEvent(int32_t action, size_t pointerCount,
137 const int32_t* pointerIds) {
Jeff Brownb6997262010-10-08 22:31:17 -0700138 if (! isValidMotionAction(action, pointerCount)) {
Jeff Brown01ce2e92010-09-26 22:20:12 -0700139 LOGE("Motion event has invalid action code 0x%x", action);
140 return false;
141 }
142 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
143 LOGE("Motion event has invalid pointer count %d; value must be between 1 and %d.",
144 pointerCount, MAX_POINTERS);
145 return false;
146 }
Jeff Brownc3db8582010-10-20 15:33:38 -0700147 BitSet32 pointerIdBits;
Jeff Brown01ce2e92010-09-26 22:20:12 -0700148 for (size_t i = 0; i < pointerCount; i++) {
Jeff Brownc3db8582010-10-20 15:33:38 -0700149 int32_t id = pointerIds[i];
150 if (id < 0 || id > MAX_POINTER_ID) {
Jeff Brown01ce2e92010-09-26 22:20:12 -0700151 LOGE("Motion event has invalid pointer id %d; value must be between 0 and %d",
Jeff Brownc3db8582010-10-20 15:33:38 -0700152 id, MAX_POINTER_ID);
Jeff Brown01ce2e92010-09-26 22:20:12 -0700153 return false;
154 }
Jeff Brownc3db8582010-10-20 15:33:38 -0700155 if (pointerIdBits.hasBit(id)) {
156 LOGE("Motion event has duplicate pointer id %d", id);
157 return false;
158 }
159 pointerIdBits.markBit(id);
Jeff Brown01ce2e92010-09-26 22:20:12 -0700160 }
161 return true;
162}
163
Jeff Brownfbf09772011-01-16 14:06:57 -0800164static void dumpRegion(String8& dump, const SkRegion& region) {
165 if (region.isEmpty()) {
166 dump.append("<empty>");
167 return;
168 }
169
170 bool first = true;
171 for (SkRegion::Iterator it(region); !it.done(); it.next()) {
172 if (first) {
173 first = false;
174 } else {
175 dump.append("|");
176 }
177 const SkIRect& rect = it.rect();
178 dump.appendFormat("[%d,%d][%d,%d]", rect.fLeft, rect.fTop, rect.fRight, rect.fBottom);
179 }
180}
181
Jeff Brownb88102f2010-09-08 11:49:43 -0700182
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700183// --- InputDispatcher ---
184
Jeff Brown9c3cda02010-06-15 01:31:58 -0700185InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy) :
Jeff Brownb88102f2010-09-08 11:49:43 -0700186 mPolicy(policy),
Jeff Brown928e0542011-01-10 11:17:36 -0800187 mPendingEvent(NULL), mAppSwitchSawKeyDown(false), mAppSwitchDueTime(LONG_LONG_MAX),
188 mNextUnblockedEvent(NULL),
Jeff Brown0029c662011-03-30 02:25:18 -0700189 mDispatchEnabled(true), mDispatchFrozen(false), mInputFilterEnabled(false),
Jeff Brown01ce2e92010-09-26 22:20:12 -0700190 mFocusedWindow(NULL),
Jeff Brownb88102f2010-09-08 11:49:43 -0700191 mFocusedApplication(NULL),
192 mCurrentInputTargetsValid(false),
Jeff Browna032cc02011-03-07 16:56:21 -0800193 mInputTargetWaitCause(INPUT_TARGET_WAIT_CAUSE_NONE),
194 mLastHoverWindow(NULL) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -0700195 mLooper = new Looper(false);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700196
Jeff Brownb88102f2010-09-08 11:49:43 -0700197 mInboundQueue.headSentinel.refCount = -1;
198 mInboundQueue.headSentinel.type = EventEntry::TYPE_SENTINEL;
199 mInboundQueue.headSentinel.eventTime = LONG_LONG_MIN;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700200
Jeff Brownb88102f2010-09-08 11:49:43 -0700201 mInboundQueue.tailSentinel.refCount = -1;
202 mInboundQueue.tailSentinel.type = EventEntry::TYPE_SENTINEL;
203 mInboundQueue.tailSentinel.eventTime = LONG_LONG_MAX;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700204
205 mKeyRepeatState.lastKeyEntry = NULL;
Jeff Brown9c3cda02010-06-15 01:31:58 -0700206
Jeff Brownae9fc032010-08-18 15:51:08 -0700207 int32_t maxEventsPerSecond = policy->getMaxEventsPerSecond();
208 mThrottleState.minTimeBetweenEvents = 1000000000LL / maxEventsPerSecond;
209 mThrottleState.lastDeviceId = -1;
210
211#if DEBUG_THROTTLING
212 mThrottleState.originalSampleCount = 0;
213 LOGD("Throttling - Max events per second = %d", maxEventsPerSecond);
214#endif
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700215}
216
217InputDispatcher::~InputDispatcher() {
Jeff Brownb88102f2010-09-08 11:49:43 -0700218 { // acquire lock
219 AutoMutex _l(mLock);
220
221 resetKeyRepeatLocked();
Jeff Brown54a18252010-09-16 14:07:33 -0700222 releasePendingEventLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -0700223 drainInboundQueueLocked();
224 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700225
226 while (mConnectionsByReceiveFd.size() != 0) {
227 unregisterInputChannel(mConnectionsByReceiveFd.valueAt(0)->inputChannel);
228 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700229}
230
231void InputDispatcher::dispatchOnce() {
Jeff Brown9c3cda02010-06-15 01:31:58 -0700232 nsecs_t keyRepeatTimeout = mPolicy->getKeyRepeatTimeout();
Jeff Brownb21fb102010-09-07 10:44:57 -0700233 nsecs_t keyRepeatDelay = mPolicy->getKeyRepeatDelay();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700234
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700235 nsecs_t nextWakeupTime = LONG_LONG_MAX;
236 { // acquire lock
237 AutoMutex _l(mLock);
Jeff Brownb88102f2010-09-08 11:49:43 -0700238 dispatchOnceInnerLocked(keyRepeatTimeout, keyRepeatDelay, & nextWakeupTime);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700239
Jeff Brownb88102f2010-09-08 11:49:43 -0700240 if (runCommandsLockedInterruptible()) {
241 nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700242 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700243 } // release lock
244
Jeff Brownb88102f2010-09-08 11:49:43 -0700245 // Wait for callback or timeout or wake. (make sure we round up, not down)
246 nsecs_t currentTime = now();
Jeff Brownaa3855d2011-03-17 01:34:19 -0700247 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
Jeff Brown4fe6c3e2010-09-13 23:17:30 -0700248 mLooper->pollOnce(timeoutMillis);
Jeff Brownb88102f2010-09-08 11:49:43 -0700249}
250
251void InputDispatcher::dispatchOnceInnerLocked(nsecs_t keyRepeatTimeout,
252 nsecs_t keyRepeatDelay, nsecs_t* nextWakeupTime) {
253 nsecs_t currentTime = now();
254
255 // Reset the key repeat timer whenever we disallow key events, even if the next event
256 // is not a key. This is to ensure that we abort a key repeat if the device is just coming
257 // out of sleep.
258 if (keyRepeatTimeout < 0) {
259 resetKeyRepeatLocked();
260 }
261
Jeff Brownb88102f2010-09-08 11:49:43 -0700262 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
263 if (mDispatchFrozen) {
264#if DEBUG_FOCUS
265 LOGD("Dispatch frozen. Waiting some more.");
266#endif
267 return;
268 }
269
270 // Optimize latency of app switches.
271 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
272 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
273 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
274 if (mAppSwitchDueTime < *nextWakeupTime) {
275 *nextWakeupTime = mAppSwitchDueTime;
276 }
277
Jeff Brownb88102f2010-09-08 11:49:43 -0700278 // Ready to start a new event.
279 // If we don't already have a pending event, go grab one.
280 if (! mPendingEvent) {
281 if (mInboundQueue.isEmpty()) {
282 if (isAppSwitchDue) {
283 // The inbound queue is empty so the app switch key we were waiting
284 // for will never arrive. Stop waiting for it.
285 resetPendingAppSwitchLocked(false);
286 isAppSwitchDue = false;
287 }
288
289 // Synthesize a key repeat if appropriate.
290 if (mKeyRepeatState.lastKeyEntry) {
291 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
292 mPendingEvent = synthesizeKeyRepeatLocked(currentTime, keyRepeatDelay);
293 } else {
294 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
295 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
296 }
297 }
298 }
299 if (! mPendingEvent) {
300 return;
301 }
302 } else {
303 // Inbound queue has at least one entry.
304 EventEntry* entry = mInboundQueue.headSentinel.next;
305
306 // Throttle the entry if it is a move event and there are no
307 // other events behind it in the queue. Due to movement batching, additional
308 // samples may be appended to this event by the time the throttling timeout
309 // expires.
310 // TODO Make this smarter and consider throttling per device independently.
Jeff Brownb6997262010-10-08 22:31:17 -0700311 if (entry->type == EventEntry::TYPE_MOTION
312 && !isAppSwitchDue
313 && mDispatchEnabled
314 && (entry->policyFlags & POLICY_FLAG_PASS_TO_USER)
315 && !entry->isInjected()) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700316 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
317 int32_t deviceId = motionEntry->deviceId;
318 uint32_t source = motionEntry->source;
319 if (! isAppSwitchDue
320 && motionEntry->next == & mInboundQueue.tailSentinel // exactly one event
Jeff Browncc0c1592011-02-19 05:07:28 -0800321 && (motionEntry->action == AMOTION_EVENT_ACTION_MOVE
322 || motionEntry->action == AMOTION_EVENT_ACTION_HOVER_MOVE)
Jeff Brownb88102f2010-09-08 11:49:43 -0700323 && deviceId == mThrottleState.lastDeviceId
324 && source == mThrottleState.lastSource) {
325 nsecs_t nextTime = mThrottleState.lastEventTime
326 + mThrottleState.minTimeBetweenEvents;
327 if (currentTime < nextTime) {
328 // Throttle it!
329#if DEBUG_THROTTLING
330 LOGD("Throttling - Delaying motion event for "
Jeff Brown90655042010-12-02 13:50:46 -0800331 "device %d, source 0x%08x by up to %0.3fms.",
Jeff Brownb88102f2010-09-08 11:49:43 -0700332 deviceId, source, (nextTime - currentTime) * 0.000001);
333#endif
334 if (nextTime < *nextWakeupTime) {
335 *nextWakeupTime = nextTime;
336 }
337 if (mThrottleState.originalSampleCount == 0) {
338 mThrottleState.originalSampleCount =
339 motionEntry->countSamples();
340 }
341 return;
342 }
343 }
344
345#if DEBUG_THROTTLING
346 if (mThrottleState.originalSampleCount != 0) {
347 uint32_t count = motionEntry->countSamples();
348 LOGD("Throttling - Motion event sample count grew by %d from %d to %d.",
349 count - mThrottleState.originalSampleCount,
350 mThrottleState.originalSampleCount, count);
351 mThrottleState.originalSampleCount = 0;
352 }
353#endif
354
makarand.karvekarf634ded2011-03-02 15:41:03 -0600355 mThrottleState.lastEventTime = currentTime;
Jeff Brownb88102f2010-09-08 11:49:43 -0700356 mThrottleState.lastDeviceId = deviceId;
357 mThrottleState.lastSource = source;
358 }
359
360 mInboundQueue.dequeue(entry);
361 mPendingEvent = entry;
362 }
Jeff Browne2fe69e2010-10-18 13:21:23 -0700363
364 // Poke user activity for this event.
365 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
366 pokeUserActivityLocked(mPendingEvent);
367 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700368 }
369
370 // Now we have an event to dispatch.
Jeff Brown928e0542011-01-10 11:17:36 -0800371 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Jeff Brownb6110c22011-04-01 16:15:13 -0700372 LOG_ASSERT(mPendingEvent != NULL);
Jeff Brown54a18252010-09-16 14:07:33 -0700373 bool done = false;
Jeff Brownb6997262010-10-08 22:31:17 -0700374 DropReason dropReason = DROP_REASON_NOT_DROPPED;
375 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
376 dropReason = DROP_REASON_POLICY;
377 } else if (!mDispatchEnabled) {
378 dropReason = DROP_REASON_DISABLED;
379 }
Jeff Brown928e0542011-01-10 11:17:36 -0800380
381 if (mNextUnblockedEvent == mPendingEvent) {
382 mNextUnblockedEvent = NULL;
383 }
384
Jeff Brownb88102f2010-09-08 11:49:43 -0700385 switch (mPendingEvent->type) {
386 case EventEntry::TYPE_CONFIGURATION_CHANGED: {
387 ConfigurationChangedEntry* typedEntry =
388 static_cast<ConfigurationChangedEntry*>(mPendingEvent);
Jeff Brown54a18252010-09-16 14:07:33 -0700389 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Jeff Brownb6997262010-10-08 22:31:17 -0700390 dropReason = DROP_REASON_NOT_DROPPED; // configuration changes are never dropped
Jeff Brownb88102f2010-09-08 11:49:43 -0700391 break;
392 }
393
394 case EventEntry::TYPE_KEY: {
395 KeyEntry* typedEntry = static_cast<KeyEntry*>(mPendingEvent);
Jeff Brownb6997262010-10-08 22:31:17 -0700396 if (isAppSwitchDue) {
397 if (isAppSwitchKeyEventLocked(typedEntry)) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700398 resetPendingAppSwitchLocked(true);
Jeff Brownb6997262010-10-08 22:31:17 -0700399 isAppSwitchDue = false;
400 } else if (dropReason == DROP_REASON_NOT_DROPPED) {
401 dropReason = DROP_REASON_APP_SWITCH;
Jeff Brownb88102f2010-09-08 11:49:43 -0700402 }
403 }
Jeff Brown928e0542011-01-10 11:17:36 -0800404 if (dropReason == DROP_REASON_NOT_DROPPED
405 && isStaleEventLocked(currentTime, typedEntry)) {
406 dropReason = DROP_REASON_STALE;
407 }
408 if (dropReason == DROP_REASON_NOT_DROPPED && mNextUnblockedEvent) {
409 dropReason = DROP_REASON_BLOCKED;
410 }
Jeff Brownb6997262010-10-08 22:31:17 -0700411 done = dispatchKeyLocked(currentTime, typedEntry, keyRepeatTimeout,
Jeff Browne20c9e02010-10-11 14:20:19 -0700412 &dropReason, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700413 break;
414 }
415
416 case EventEntry::TYPE_MOTION: {
417 MotionEntry* typedEntry = static_cast<MotionEntry*>(mPendingEvent);
Jeff Brownb6997262010-10-08 22:31:17 -0700418 if (dropReason == DROP_REASON_NOT_DROPPED && isAppSwitchDue) {
419 dropReason = DROP_REASON_APP_SWITCH;
Jeff Brownb88102f2010-09-08 11:49:43 -0700420 }
Jeff Brown928e0542011-01-10 11:17:36 -0800421 if (dropReason == DROP_REASON_NOT_DROPPED
422 && isStaleEventLocked(currentTime, typedEntry)) {
423 dropReason = DROP_REASON_STALE;
424 }
425 if (dropReason == DROP_REASON_NOT_DROPPED && mNextUnblockedEvent) {
426 dropReason = DROP_REASON_BLOCKED;
427 }
Jeff Brownb6997262010-10-08 22:31:17 -0700428 done = dispatchMotionLocked(currentTime, typedEntry,
Jeff Browne20c9e02010-10-11 14:20:19 -0700429 &dropReason, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700430 break;
431 }
432
433 default:
Jeff Brownb6110c22011-04-01 16:15:13 -0700434 LOG_ASSERT(false);
Jeff Brownb88102f2010-09-08 11:49:43 -0700435 break;
436 }
437
Jeff Brown54a18252010-09-16 14:07:33 -0700438 if (done) {
Jeff Brownb6997262010-10-08 22:31:17 -0700439 if (dropReason != DROP_REASON_NOT_DROPPED) {
440 dropInboundEventLocked(mPendingEvent, dropReason);
441 }
442
Jeff Brown54a18252010-09-16 14:07:33 -0700443 releasePendingEventLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -0700444 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
445 }
446}
447
448bool InputDispatcher::enqueueInboundEventLocked(EventEntry* entry) {
449 bool needWake = mInboundQueue.isEmpty();
450 mInboundQueue.enqueueAtTail(entry);
451
452 switch (entry->type) {
Jeff Brownb6997262010-10-08 22:31:17 -0700453 case EventEntry::TYPE_KEY: {
Jeff Brown928e0542011-01-10 11:17:36 -0800454 // Optimize app switch latency.
455 // If the application takes too long to catch up then we drop all events preceding
456 // the app switch key.
Jeff Brownb6997262010-10-08 22:31:17 -0700457 KeyEntry* keyEntry = static_cast<KeyEntry*>(entry);
458 if (isAppSwitchKeyEventLocked(keyEntry)) {
459 if (keyEntry->action == AKEY_EVENT_ACTION_DOWN) {
460 mAppSwitchSawKeyDown = true;
461 } else if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
462 if (mAppSwitchSawKeyDown) {
463#if DEBUG_APP_SWITCH
464 LOGD("App switch is pending!");
465#endif
466 mAppSwitchDueTime = keyEntry->eventTime + APP_SWITCH_TIMEOUT;
467 mAppSwitchSawKeyDown = false;
468 needWake = true;
469 }
470 }
471 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700472 break;
473 }
Jeff Brown928e0542011-01-10 11:17:36 -0800474
475 case EventEntry::TYPE_MOTION: {
476 // Optimize case where the current application is unresponsive and the user
477 // decides to touch a window in a different application.
478 // If the application takes too long to catch up then we drop all events preceding
479 // the touch into the other window.
480 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
Jeff Brown33bbfd22011-02-24 20:55:35 -0800481 if (motionEntry->action == AMOTION_EVENT_ACTION_DOWN
Jeff Brown928e0542011-01-10 11:17:36 -0800482 && (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER)
483 && mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY
484 && mInputTargetWaitApplication != NULL) {
Jeff Brown91c69ab2011-02-14 17:03:18 -0800485 int32_t x = int32_t(motionEntry->firstSample.pointerCoords[0].
Jeff Brownebbd5d12011-02-17 13:01:34 -0800486 getAxisValue(AMOTION_EVENT_AXIS_X));
Jeff Brown91c69ab2011-02-14 17:03:18 -0800487 int32_t y = int32_t(motionEntry->firstSample.pointerCoords[0].
Jeff Brownebbd5d12011-02-17 13:01:34 -0800488 getAxisValue(AMOTION_EVENT_AXIS_Y));
Jeff Brown928e0542011-01-10 11:17:36 -0800489 const InputWindow* touchedWindow = findTouchedWindowAtLocked(x, y);
490 if (touchedWindow
491 && touchedWindow->inputWindowHandle != NULL
492 && touchedWindow->inputWindowHandle->getInputApplicationHandle()
493 != mInputTargetWaitApplication) {
494 // User touched a different application than the one we are waiting on.
495 // Flag the event, and start pruning the input queue.
496 mNextUnblockedEvent = motionEntry;
497 needWake = true;
498 }
499 }
500 break;
501 }
Jeff Brownb6997262010-10-08 22:31:17 -0700502 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700503
504 return needWake;
505}
506
Jeff Brown928e0542011-01-10 11:17:36 -0800507const InputWindow* InputDispatcher::findTouchedWindowAtLocked(int32_t x, int32_t y) {
508 // Traverse windows from front to back to find touched window.
509 size_t numWindows = mWindows.size();
510 for (size_t i = 0; i < numWindows; i++) {
511 const InputWindow* window = & mWindows.editItemAt(i);
512 int32_t flags = window->layoutParamsFlags;
513
514 if (window->visible) {
515 if (!(flags & InputWindow::FLAG_NOT_TOUCHABLE)) {
516 bool isTouchModal = (flags & (InputWindow::FLAG_NOT_FOCUSABLE
517 | InputWindow::FLAG_NOT_TOUCH_MODAL)) == 0;
Jeff Brownfbf09772011-01-16 14:06:57 -0800518 if (isTouchModal || window->touchableRegionContainsPoint(x, y)) {
Jeff Brown928e0542011-01-10 11:17:36 -0800519 // Found window.
520 return window;
521 }
522 }
523 }
524
525 if (flags & InputWindow::FLAG_SYSTEM_ERROR) {
526 // Error window is on top but not visible, so touch is dropped.
527 return NULL;
528 }
529 }
530 return NULL;
531}
532
Jeff Brownb6997262010-10-08 22:31:17 -0700533void InputDispatcher::dropInboundEventLocked(EventEntry* entry, DropReason dropReason) {
534 const char* reason;
535 switch (dropReason) {
536 case DROP_REASON_POLICY:
Jeff Browne20c9e02010-10-11 14:20:19 -0700537#if DEBUG_INBOUND_EVENT_DETAILS
Jeff Brown3122e442010-10-11 23:32:49 -0700538 LOGD("Dropped event because policy consumed it.");
Jeff Browne20c9e02010-10-11 14:20:19 -0700539#endif
Jeff Brown3122e442010-10-11 23:32:49 -0700540 reason = "inbound event was dropped because the policy consumed it";
Jeff Brownb6997262010-10-08 22:31:17 -0700541 break;
542 case DROP_REASON_DISABLED:
543 LOGI("Dropped event because input dispatch is disabled.");
544 reason = "inbound event was dropped because input dispatch is disabled";
545 break;
546 case DROP_REASON_APP_SWITCH:
547 LOGI("Dropped event because of pending overdue app switch.");
548 reason = "inbound event was dropped because of pending overdue app switch";
549 break;
Jeff Brown928e0542011-01-10 11:17:36 -0800550 case DROP_REASON_BLOCKED:
551 LOGI("Dropped event because the current application is not responding and the user "
552 "has started interating with a different application.");
553 reason = "inbound event was dropped because the current application is not responding "
554 "and the user has started interating with a different application";
555 break;
556 case DROP_REASON_STALE:
557 LOGI("Dropped event because it is stale.");
558 reason = "inbound event was dropped because it is stale";
559 break;
Jeff Brownb6997262010-10-08 22:31:17 -0700560 default:
Jeff Brownb6110c22011-04-01 16:15:13 -0700561 LOG_ASSERT(false);
Jeff Brownb6997262010-10-08 22:31:17 -0700562 return;
563 }
564
565 switch (entry->type) {
Jeff Brownda3d5a92011-03-29 15:11:34 -0700566 case EventEntry::TYPE_KEY: {
567 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
568 synthesizeCancelationEventsForAllConnectionsLocked(options);
Jeff Brownb6997262010-10-08 22:31:17 -0700569 break;
Jeff Brownda3d5a92011-03-29 15:11:34 -0700570 }
Jeff Brownb6997262010-10-08 22:31:17 -0700571 case EventEntry::TYPE_MOTION: {
572 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
573 if (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) {
Jeff Brownda3d5a92011-03-29 15:11:34 -0700574 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
575 synthesizeCancelationEventsForAllConnectionsLocked(options);
Jeff Brownb6997262010-10-08 22:31:17 -0700576 } else {
Jeff Brownda3d5a92011-03-29 15:11:34 -0700577 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
578 synthesizeCancelationEventsForAllConnectionsLocked(options);
Jeff Brownb6997262010-10-08 22:31:17 -0700579 }
580 break;
581 }
582 }
583}
584
585bool InputDispatcher::isAppSwitchKeyCode(int32_t keyCode) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700586 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL;
587}
588
Jeff Brownb6997262010-10-08 22:31:17 -0700589bool InputDispatcher::isAppSwitchKeyEventLocked(KeyEntry* keyEntry) {
590 return ! (keyEntry->flags & AKEY_EVENT_FLAG_CANCELED)
591 && isAppSwitchKeyCode(keyEntry->keyCode)
Jeff Browne20c9e02010-10-11 14:20:19 -0700592 && (keyEntry->policyFlags & POLICY_FLAG_TRUSTED)
Jeff Brownb6997262010-10-08 22:31:17 -0700593 && (keyEntry->policyFlags & POLICY_FLAG_PASS_TO_USER);
594}
595
Jeff Brownb88102f2010-09-08 11:49:43 -0700596bool InputDispatcher::isAppSwitchPendingLocked() {
597 return mAppSwitchDueTime != LONG_LONG_MAX;
598}
599
Jeff Brownb88102f2010-09-08 11:49:43 -0700600void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
601 mAppSwitchDueTime = LONG_LONG_MAX;
602
603#if DEBUG_APP_SWITCH
604 if (handled) {
605 LOGD("App switch has arrived.");
606 } else {
607 LOGD("App switch was abandoned.");
608 }
609#endif
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700610}
611
Jeff Brown928e0542011-01-10 11:17:36 -0800612bool InputDispatcher::isStaleEventLocked(nsecs_t currentTime, EventEntry* entry) {
613 return currentTime - entry->eventTime >= STALE_EVENT_TIMEOUT;
614}
615
Jeff Brown9c3cda02010-06-15 01:31:58 -0700616bool InputDispatcher::runCommandsLockedInterruptible() {
617 if (mCommandQueue.isEmpty()) {
618 return false;
619 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700620
Jeff Brown9c3cda02010-06-15 01:31:58 -0700621 do {
622 CommandEntry* commandEntry = mCommandQueue.dequeueAtHead();
623
624 Command command = commandEntry->command;
625 (this->*command)(commandEntry); // commands are implicitly 'LockedInterruptible'
626
Jeff Brown7fbdc842010-06-17 20:52:56 -0700627 commandEntry->connection.clear();
Jeff Brown9c3cda02010-06-15 01:31:58 -0700628 mAllocator.releaseCommandEntry(commandEntry);
629 } while (! mCommandQueue.isEmpty());
630 return true;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700631}
632
Jeff Brown9c3cda02010-06-15 01:31:58 -0700633InputDispatcher::CommandEntry* InputDispatcher::postCommandLocked(Command command) {
634 CommandEntry* commandEntry = mAllocator.obtainCommandEntry(command);
635 mCommandQueue.enqueueAtTail(commandEntry);
636 return commandEntry;
637}
638
Jeff Brownb88102f2010-09-08 11:49:43 -0700639void InputDispatcher::drainInboundQueueLocked() {
640 while (! mInboundQueue.isEmpty()) {
641 EventEntry* entry = mInboundQueue.dequeueAtHead();
Jeff Brown54a18252010-09-16 14:07:33 -0700642 releaseInboundEventLocked(entry);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700643 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700644}
645
Jeff Brown54a18252010-09-16 14:07:33 -0700646void InputDispatcher::releasePendingEventLocked() {
Jeff Brownb88102f2010-09-08 11:49:43 -0700647 if (mPendingEvent) {
Jeff Brown54a18252010-09-16 14:07:33 -0700648 releaseInboundEventLocked(mPendingEvent);
Jeff Brownb88102f2010-09-08 11:49:43 -0700649 mPendingEvent = NULL;
650 }
651}
652
Jeff Brown54a18252010-09-16 14:07:33 -0700653void InputDispatcher::releaseInboundEventLocked(EventEntry* entry) {
Jeff Brown01ce2e92010-09-26 22:20:12 -0700654 InjectionState* injectionState = entry->injectionState;
655 if (injectionState && injectionState->injectionResult == INPUT_EVENT_INJECTION_PENDING) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700656#if DEBUG_DISPATCH_CYCLE
Jeff Brown01ce2e92010-09-26 22:20:12 -0700657 LOGD("Injected inbound event was dropped.");
Jeff Brownb88102f2010-09-08 11:49:43 -0700658#endif
659 setInjectionResultLocked(entry, INPUT_EVENT_INJECTION_FAILED);
660 }
661 mAllocator.releaseEventEntry(entry);
662}
663
Jeff Brownb88102f2010-09-08 11:49:43 -0700664void InputDispatcher::resetKeyRepeatLocked() {
665 if (mKeyRepeatState.lastKeyEntry) {
666 mAllocator.releaseKeyEntry(mKeyRepeatState.lastKeyEntry);
667 mKeyRepeatState.lastKeyEntry = NULL;
668 }
669}
670
671InputDispatcher::KeyEntry* InputDispatcher::synthesizeKeyRepeatLocked(
Jeff Brownb21fb102010-09-07 10:44:57 -0700672 nsecs_t currentTime, nsecs_t keyRepeatDelay) {
Jeff Brown349703e2010-06-22 01:27:15 -0700673 KeyEntry* entry = mKeyRepeatState.lastKeyEntry;
674
Jeff Brown349703e2010-06-22 01:27:15 -0700675 // Reuse the repeated key entry if it is otherwise unreferenced.
Jeff Browne20c9e02010-10-11 14:20:19 -0700676 uint32_t policyFlags = (entry->policyFlags & POLICY_FLAG_RAW_MASK)
677 | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700678 if (entry->refCount == 1) {
Jeff Brown01ce2e92010-09-26 22:20:12 -0700679 mAllocator.recycleKeyEntry(entry);
Jeff Brown7fbdc842010-06-17 20:52:56 -0700680 entry->eventTime = currentTime;
Jeff Brown7fbdc842010-06-17 20:52:56 -0700681 entry->policyFlags = policyFlags;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700682 entry->repeatCount += 1;
683 } else {
Jeff Brown7fbdc842010-06-17 20:52:56 -0700684 KeyEntry* newEntry = mAllocator.obtainKeyEntry(currentTime,
Jeff Brownc5ed5912010-07-14 18:48:53 -0700685 entry->deviceId, entry->source, policyFlags,
Jeff Brown7fbdc842010-06-17 20:52:56 -0700686 entry->action, entry->flags, entry->keyCode, entry->scanCode,
Jeff Brown00fa7bd2010-07-02 15:37:36 -0700687 entry->metaState, entry->repeatCount + 1, entry->downTime);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700688
689 mKeyRepeatState.lastKeyEntry = newEntry;
690 mAllocator.releaseKeyEntry(entry);
691
692 entry = newEntry;
693 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700694 entry->syntheticRepeat = true;
695
696 // Increment reference count since we keep a reference to the event in
697 // mKeyRepeatState.lastKeyEntry in addition to the one we return.
698 entry->refCount += 1;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700699
Jeff Brownb21fb102010-09-07 10:44:57 -0700700 mKeyRepeatState.nextRepeatTime = currentTime + keyRepeatDelay;
Jeff Brownb88102f2010-09-08 11:49:43 -0700701 return entry;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700702}
703
Jeff Brownb88102f2010-09-08 11:49:43 -0700704bool InputDispatcher::dispatchConfigurationChangedLocked(
705 nsecs_t currentTime, ConfigurationChangedEntry* entry) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700706#if DEBUG_OUTBOUND_EVENT_DETAILS
Jeff Brownb88102f2010-09-08 11:49:43 -0700707 LOGD("dispatchConfigurationChanged - eventTime=%lld", entry->eventTime);
708#endif
709
710 // Reset key repeating in case a keyboard device was added or removed or something.
711 resetKeyRepeatLocked();
712
713 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
714 CommandEntry* commandEntry = postCommandLocked(
715 & InputDispatcher::doNotifyConfigurationChangedInterruptible);
716 commandEntry->eventTime = entry->eventTime;
717 return true;
718}
719
720bool InputDispatcher::dispatchKeyLocked(
721 nsecs_t currentTime, KeyEntry* entry, nsecs_t keyRepeatTimeout,
Jeff Browne20c9e02010-10-11 14:20:19 -0700722 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Jeff Browne46a0a42010-11-02 17:58:22 -0700723 // Preprocessing.
724 if (! entry->dispatchInProgress) {
725 if (entry->repeatCount == 0
726 && entry->action == AKEY_EVENT_ACTION_DOWN
727 && (entry->policyFlags & POLICY_FLAG_TRUSTED)
Jeff Brown0029c662011-03-30 02:25:18 -0700728 && (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
Jeff Browne46a0a42010-11-02 17:58:22 -0700729 if (mKeyRepeatState.lastKeyEntry
730 && mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode) {
731 // We have seen two identical key downs in a row which indicates that the device
732 // driver is automatically generating key repeats itself. We take note of the
733 // repeat here, but we disable our own next key repeat timer since it is clear that
734 // we will not need to synthesize key repeats ourselves.
735 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
736 resetKeyRepeatLocked();
737 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
738 } else {
739 // Not a repeat. Save key down state in case we do see a repeat later.
740 resetKeyRepeatLocked();
741 mKeyRepeatState.nextRepeatTime = entry->eventTime + keyRepeatTimeout;
742 }
743 mKeyRepeatState.lastKeyEntry = entry;
744 entry->refCount += 1;
745 } else if (! entry->syntheticRepeat) {
746 resetKeyRepeatLocked();
747 }
748
Jeff Browne2e01262011-03-02 20:34:30 -0800749 if (entry->repeatCount == 1) {
750 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
751 } else {
752 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
753 }
754
Jeff Browne46a0a42010-11-02 17:58:22 -0700755 entry->dispatchInProgress = true;
756 resetTargetsLocked();
757
758 logOutboundKeyDetailsLocked("dispatchKey - ", entry);
759 }
760
Jeff Brown54a18252010-09-16 14:07:33 -0700761 // Give the policy a chance to intercept the key.
762 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
Jeff Browne20c9e02010-10-11 14:20:19 -0700763 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Jeff Brown54a18252010-09-16 14:07:33 -0700764 CommandEntry* commandEntry = postCommandLocked(
765 & InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
Jeff Browne20c9e02010-10-11 14:20:19 -0700766 if (mFocusedWindow) {
Jeff Brown928e0542011-01-10 11:17:36 -0800767 commandEntry->inputWindowHandle = mFocusedWindow->inputWindowHandle;
Jeff Brown54a18252010-09-16 14:07:33 -0700768 }
769 commandEntry->keyEntry = entry;
770 entry->refCount += 1;
771 return false; // wait for the command to run
772 } else {
773 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
774 }
775 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Jeff Browne20c9e02010-10-11 14:20:19 -0700776 if (*dropReason == DROP_REASON_NOT_DROPPED) {
777 *dropReason = DROP_REASON_POLICY;
778 }
Jeff Brown54a18252010-09-16 14:07:33 -0700779 }
780
781 // Clean up if dropping the event.
Jeff Browne20c9e02010-10-11 14:20:19 -0700782 if (*dropReason != DROP_REASON_NOT_DROPPED) {
Jeff Brown54a18252010-09-16 14:07:33 -0700783 resetTargetsLocked();
Jeff Brown3122e442010-10-11 23:32:49 -0700784 setInjectionResultLocked(entry, *dropReason == DROP_REASON_POLICY
785 ? INPUT_EVENT_INJECTION_SUCCEEDED : INPUT_EVENT_INJECTION_FAILED);
Jeff Brown54a18252010-09-16 14:07:33 -0700786 return true;
787 }
788
Jeff Brownb88102f2010-09-08 11:49:43 -0700789 // Identify targets.
790 if (! mCurrentInputTargetsValid) {
Jeff Brown01ce2e92010-09-26 22:20:12 -0700791 int32_t injectionResult = findFocusedWindowTargetsLocked(currentTime,
792 entry, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700793 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
794 return false;
795 }
796
797 setInjectionResultLocked(entry, injectionResult);
798 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
799 return true;
800 }
801
802 addMonitoringTargetsLocked();
Jeff Brown01ce2e92010-09-26 22:20:12 -0700803 commitTargetsLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -0700804 }
805
806 // Dispatch the key.
807 dispatchEventToCurrentInputTargetsLocked(currentTime, entry, false);
Jeff Brownb88102f2010-09-08 11:49:43 -0700808 return true;
809}
810
811void InputDispatcher::logOutboundKeyDetailsLocked(const char* prefix, const KeyEntry* entry) {
812#if DEBUG_OUTBOUND_EVENT_DETAILS
Jeff Brown90655042010-12-02 13:50:46 -0800813 LOGD("%seventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, "
Jeff Brownb88102f2010-09-08 11:49:43 -0700814 "action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, "
Jeff Browne46a0a42010-11-02 17:58:22 -0700815 "repeatCount=%d, downTime=%lld",
Jeff Brownb88102f2010-09-08 11:49:43 -0700816 prefix,
817 entry->eventTime, entry->deviceId, entry->source, entry->policyFlags,
818 entry->action, entry->flags, entry->keyCode, entry->scanCode, entry->metaState,
Jeff Browne46a0a42010-11-02 17:58:22 -0700819 entry->repeatCount, entry->downTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700820#endif
821}
822
823bool InputDispatcher::dispatchMotionLocked(
Jeff Browne20c9e02010-10-11 14:20:19 -0700824 nsecs_t currentTime, MotionEntry* entry, DropReason* dropReason, nsecs_t* nextWakeupTime) {
Jeff Browne46a0a42010-11-02 17:58:22 -0700825 // Preprocessing.
826 if (! entry->dispatchInProgress) {
827 entry->dispatchInProgress = true;
828 resetTargetsLocked();
829
830 logOutboundMotionDetailsLocked("dispatchMotion - ", entry);
831 }
832
Jeff Brown54a18252010-09-16 14:07:33 -0700833 // Clean up if dropping the event.
Jeff Browne20c9e02010-10-11 14:20:19 -0700834 if (*dropReason != DROP_REASON_NOT_DROPPED) {
Jeff Brown54a18252010-09-16 14:07:33 -0700835 resetTargetsLocked();
Jeff Brown3122e442010-10-11 23:32:49 -0700836 setInjectionResultLocked(entry, *dropReason == DROP_REASON_POLICY
837 ? INPUT_EVENT_INJECTION_SUCCEEDED : INPUT_EVENT_INJECTION_FAILED);
Jeff Brown54a18252010-09-16 14:07:33 -0700838 return true;
839 }
840
Jeff Brownb88102f2010-09-08 11:49:43 -0700841 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
842
843 // Identify targets.
Jeff Browncc0c1592011-02-19 05:07:28 -0800844 bool conflictingPointerActions = false;
Jeff Brownb88102f2010-09-08 11:49:43 -0700845 if (! mCurrentInputTargetsValid) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700846 int32_t injectionResult;
Jeff Browna032cc02011-03-07 16:56:21 -0800847 const MotionSample* splitBatchAfterSample = NULL;
Jeff Brownb88102f2010-09-08 11:49:43 -0700848 if (isPointerEvent) {
849 // Pointer event. (eg. touchscreen)
Jeff Brown01ce2e92010-09-26 22:20:12 -0700850 injectionResult = findTouchedWindowTargetsLocked(currentTime,
Jeff Browna032cc02011-03-07 16:56:21 -0800851 entry, nextWakeupTime, &conflictingPointerActions, &splitBatchAfterSample);
Jeff Brownb88102f2010-09-08 11:49:43 -0700852 } else {
853 // Non touch event. (eg. trackball)
Jeff Brown01ce2e92010-09-26 22:20:12 -0700854 injectionResult = findFocusedWindowTargetsLocked(currentTime,
855 entry, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700856 }
857 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
858 return false;
859 }
860
861 setInjectionResultLocked(entry, injectionResult);
862 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
863 return true;
864 }
865
866 addMonitoringTargetsLocked();
Jeff Brown01ce2e92010-09-26 22:20:12 -0700867 commitTargetsLocked();
Jeff Browna032cc02011-03-07 16:56:21 -0800868
869 // Unbatch the event if necessary by splitting it into two parts after the
870 // motion sample indicated by splitBatchAfterSample.
871 if (splitBatchAfterSample && splitBatchAfterSample->next) {
872#if DEBUG_BATCHING
873 uint32_t originalSampleCount = entry->countSamples();
874#endif
875 MotionSample* nextSample = splitBatchAfterSample->next;
876 MotionEntry* nextEntry = mAllocator.obtainMotionEntry(nextSample->eventTime,
877 entry->deviceId, entry->source, entry->policyFlags,
878 entry->action, entry->flags, entry->metaState, entry->edgeFlags,
879 entry->xPrecision, entry->yPrecision, entry->downTime,
880 entry->pointerCount, entry->pointerIds, nextSample->pointerCoords);
881 if (nextSample != entry->lastSample) {
882 nextEntry->firstSample.next = nextSample->next;
883 nextEntry->lastSample = entry->lastSample;
884 }
885 mAllocator.freeMotionSample(nextSample);
886
887 entry->lastSample = const_cast<MotionSample*>(splitBatchAfterSample);
888 entry->lastSample->next = NULL;
889
890 if (entry->injectionState) {
891 nextEntry->injectionState = entry->injectionState;
892 entry->injectionState->refCount += 1;
893 }
894
895#if DEBUG_BATCHING
896 LOGD("Split batch of %d samples into two parts, first part has %d samples, "
897 "second part has %d samples.", originalSampleCount,
898 entry->countSamples(), nextEntry->countSamples());
899#endif
900
901 mInboundQueue.enqueueAtHead(nextEntry);
902 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700903 }
904
905 // Dispatch the motion.
Jeff Browncc0c1592011-02-19 05:07:28 -0800906 if (conflictingPointerActions) {
Jeff Brownda3d5a92011-03-29 15:11:34 -0700907 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
908 "conflicting pointer actions");
909 synthesizeCancelationEventsForAllConnectionsLocked(options);
Jeff Browncc0c1592011-02-19 05:07:28 -0800910 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700911 dispatchEventToCurrentInputTargetsLocked(currentTime, entry, false);
Jeff Brownb88102f2010-09-08 11:49:43 -0700912 return true;
913}
914
915
916void InputDispatcher::logOutboundMotionDetailsLocked(const char* prefix, const MotionEntry* entry) {
917#if DEBUG_OUTBOUND_EVENT_DETAILS
Jeff Brown90655042010-12-02 13:50:46 -0800918 LOGD("%seventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, "
Jeff Brown85a31762010-09-01 17:01:00 -0700919 "action=0x%x, flags=0x%x, "
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700920 "metaState=0x%x, edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%lld",
Jeff Brownb88102f2010-09-08 11:49:43 -0700921 prefix,
Jeff Brown85a31762010-09-01 17:01:00 -0700922 entry->eventTime, entry->deviceId, entry->source, entry->policyFlags,
923 entry->action, entry->flags,
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700924 entry->metaState, entry->edgeFlags, entry->xPrecision, entry->yPrecision,
925 entry->downTime);
926
927 // Print the most recent sample that we have available, this may change due to batching.
928 size_t sampleCount = 1;
Jeff Brownb88102f2010-09-08 11:49:43 -0700929 const MotionSample* sample = & entry->firstSample;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700930 for (; sample->next != NULL; sample = sample->next) {
931 sampleCount += 1;
932 }
933 for (uint32_t i = 0; i < entry->pointerCount; i++) {
Jeff Brown8d608662010-08-30 03:02:23 -0700934 LOGD(" Pointer %d: id=%d, x=%f, y=%f, pressure=%f, size=%f, "
Jeff Brown85a31762010-09-01 17:01:00 -0700935 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
Jeff Brown8d608662010-08-30 03:02:23 -0700936 "orientation=%f",
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700937 i, entry->pointerIds[i],
Jeff Brownebbd5d12011-02-17 13:01:34 -0800938 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
939 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
940 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
941 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
942 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
943 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
944 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
945 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
946 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700947 }
948
949 // Keep in mind that due to batching, it is possible for the number of samples actually
950 // dispatched to change before the application finally consumed them.
Jeff Brownc5ed5912010-07-14 18:48:53 -0700951 if (entry->action == AMOTION_EVENT_ACTION_MOVE) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700952 LOGD(" ... Total movement samples currently batched %d ...", sampleCount);
953 }
954#endif
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700955}
956
957void InputDispatcher::dispatchEventToCurrentInputTargetsLocked(nsecs_t currentTime,
958 EventEntry* eventEntry, bool resumeWithAppendedMotionSample) {
959#if DEBUG_DISPATCH_CYCLE
Jeff Brown9c3cda02010-06-15 01:31:58 -0700960 LOGD("dispatchEventToCurrentInputTargets - "
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700961 "resumeWithAppendedMotionSample=%s",
Jeff Brownb88102f2010-09-08 11:49:43 -0700962 toString(resumeWithAppendedMotionSample));
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700963#endif
964
Jeff Brownb6110c22011-04-01 16:15:13 -0700965 LOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
Jeff Brown9c3cda02010-06-15 01:31:58 -0700966
Jeff Browne2fe69e2010-10-18 13:21:23 -0700967 pokeUserActivityLocked(eventEntry);
968
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700969 for (size_t i = 0; i < mCurrentInputTargets.size(); i++) {
970 const InputTarget& inputTarget = mCurrentInputTargets.itemAt(i);
971
Jeff Brown519e0242010-09-15 15:18:56 -0700972 ssize_t connectionIndex = getConnectionIndexLocked(inputTarget.inputChannel);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700973 if (connectionIndex >= 0) {
974 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
Jeff Brown7fbdc842010-06-17 20:52:56 -0700975 prepareDispatchCycleLocked(currentTime, connection, eventEntry, & inputTarget,
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700976 resumeWithAppendedMotionSample);
977 } else {
Jeff Brownb6997262010-10-08 22:31:17 -0700978#if DEBUG_FOCUS
979 LOGD("Dropping event delivery to target with channel '%s' because it "
980 "is no longer registered with the input dispatcher.",
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700981 inputTarget.inputChannel->getName().string());
Jeff Brownb6997262010-10-08 22:31:17 -0700982#endif
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700983 }
984 }
985}
986
Jeff Brown54a18252010-09-16 14:07:33 -0700987void InputDispatcher::resetTargetsLocked() {
Jeff Brownb88102f2010-09-08 11:49:43 -0700988 mCurrentInputTargetsValid = false;
989 mCurrentInputTargets.clear();
Jeff Brownb88102f2010-09-08 11:49:43 -0700990 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_NONE;
Jeff Brown928e0542011-01-10 11:17:36 -0800991 mInputTargetWaitApplication.clear();
Jeff Brownb88102f2010-09-08 11:49:43 -0700992}
993
Jeff Brown01ce2e92010-09-26 22:20:12 -0700994void InputDispatcher::commitTargetsLocked() {
Jeff Brownb88102f2010-09-08 11:49:43 -0700995 mCurrentInputTargetsValid = true;
996}
997
998int32_t InputDispatcher::handleTargetsNotReadyLocked(nsecs_t currentTime,
999 const EventEntry* entry, const InputApplication* application, const InputWindow* window,
1000 nsecs_t* nextWakeupTime) {
1001 if (application == NULL && window == NULL) {
1002 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY) {
1003#if DEBUG_FOCUS
1004 LOGD("Waiting for system to become ready for input.");
1005#endif
1006 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY;
1007 mInputTargetWaitStartTime = currentTime;
1008 mInputTargetWaitTimeoutTime = LONG_LONG_MAX;
1009 mInputTargetWaitTimeoutExpired = false;
Jeff Brown928e0542011-01-10 11:17:36 -08001010 mInputTargetWaitApplication.clear();
Jeff Brownb88102f2010-09-08 11:49:43 -07001011 }
1012 } else {
1013 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
1014#if DEBUG_FOCUS
Jeff Brown519e0242010-09-15 15:18:56 -07001015 LOGD("Waiting for application to become ready for input: %s",
1016 getApplicationWindowLabelLocked(application, window).string());
Jeff Brownb88102f2010-09-08 11:49:43 -07001017#endif
1018 nsecs_t timeout = window ? window->dispatchingTimeout :
1019 application ? application->dispatchingTimeout : DEFAULT_INPUT_DISPATCHING_TIMEOUT;
1020
1021 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY;
1022 mInputTargetWaitStartTime = currentTime;
1023 mInputTargetWaitTimeoutTime = currentTime + timeout;
1024 mInputTargetWaitTimeoutExpired = false;
Jeff Brown928e0542011-01-10 11:17:36 -08001025 mInputTargetWaitApplication.clear();
1026
1027 if (window && window->inputWindowHandle != NULL) {
1028 mInputTargetWaitApplication =
1029 window->inputWindowHandle->getInputApplicationHandle();
1030 }
1031 if (mInputTargetWaitApplication == NULL && application) {
1032 mInputTargetWaitApplication = application->inputApplicationHandle;
1033 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001034 }
1035 }
1036
1037 if (mInputTargetWaitTimeoutExpired) {
1038 return INPUT_EVENT_INJECTION_TIMED_OUT;
1039 }
1040
1041 if (currentTime >= mInputTargetWaitTimeoutTime) {
Jeff Brown519e0242010-09-15 15:18:56 -07001042 onANRLocked(currentTime, application, window, entry->eventTime, mInputTargetWaitStartTime);
Jeff Brownb88102f2010-09-08 11:49:43 -07001043
1044 // Force poll loop to wake up immediately on next iteration once we get the
1045 // ANR response back from the policy.
1046 *nextWakeupTime = LONG_LONG_MIN;
1047 return INPUT_EVENT_INJECTION_PENDING;
1048 } else {
1049 // Force poll loop to wake up when timeout is due.
1050 if (mInputTargetWaitTimeoutTime < *nextWakeupTime) {
1051 *nextWakeupTime = mInputTargetWaitTimeoutTime;
1052 }
1053 return INPUT_EVENT_INJECTION_PENDING;
1054 }
1055}
1056
Jeff Brown519e0242010-09-15 15:18:56 -07001057void InputDispatcher::resumeAfterTargetsNotReadyTimeoutLocked(nsecs_t newTimeout,
1058 const sp<InputChannel>& inputChannel) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001059 if (newTimeout > 0) {
1060 // Extend the timeout.
1061 mInputTargetWaitTimeoutTime = now() + newTimeout;
1062 } else {
1063 // Give up.
1064 mInputTargetWaitTimeoutExpired = true;
Jeff Brown519e0242010-09-15 15:18:56 -07001065
Jeff Brown01ce2e92010-09-26 22:20:12 -07001066 // Release the touch targets.
1067 mTouchState.reset();
Jeff Brown2a95c2a2010-09-16 12:31:46 -07001068
Jeff Brown519e0242010-09-15 15:18:56 -07001069 // Input state will not be realistic. Mark it out of sync.
Jeff Browndc3e0052010-09-16 11:02:16 -07001070 if (inputChannel.get()) {
1071 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
1072 if (connectionIndex >= 0) {
1073 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
Jeff Brown00045a72010-12-09 18:10:30 -08001074 if (connection->status == Connection::STATUS_NORMAL) {
Jeff Brownda3d5a92011-03-29 15:11:34 -07001075 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
Jeff Brown00045a72010-12-09 18:10:30 -08001076 "application not responding");
Jeff Brownda3d5a92011-03-29 15:11:34 -07001077 synthesizeCancelationEventsForConnectionLocked(connection, options);
Jeff Brown00045a72010-12-09 18:10:30 -08001078 }
Jeff Browndc3e0052010-09-16 11:02:16 -07001079 }
Jeff Brown519e0242010-09-15 15:18:56 -07001080 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001081 }
1082}
1083
Jeff Brown519e0242010-09-15 15:18:56 -07001084nsecs_t InputDispatcher::getTimeSpentWaitingForApplicationLocked(
Jeff Brownb88102f2010-09-08 11:49:43 -07001085 nsecs_t currentTime) {
1086 if (mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
1087 return currentTime - mInputTargetWaitStartTime;
1088 }
1089 return 0;
1090}
1091
1092void InputDispatcher::resetANRTimeoutsLocked() {
1093#if DEBUG_FOCUS
1094 LOGD("Resetting ANR timeouts.");
1095#endif
1096
Jeff Brownb88102f2010-09-08 11:49:43 -07001097 // Reset input target wait timeout.
1098 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_NONE;
1099}
1100
Jeff Brown01ce2e92010-09-26 22:20:12 -07001101int32_t InputDispatcher::findFocusedWindowTargetsLocked(nsecs_t currentTime,
1102 const EventEntry* entry, nsecs_t* nextWakeupTime) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001103 mCurrentInputTargets.clear();
1104
1105 int32_t injectionResult;
1106
1107 // If there is no currently focused window and no focused application
1108 // then drop the event.
1109 if (! mFocusedWindow) {
1110 if (mFocusedApplication) {
1111#if DEBUG_FOCUS
1112 LOGD("Waiting because there is no focused window but there is a "
Jeff Brown519e0242010-09-15 15:18:56 -07001113 "focused application that may eventually add a window: %s.",
1114 getApplicationWindowLabelLocked(mFocusedApplication, NULL).string());
Jeff Brownb88102f2010-09-08 11:49:43 -07001115#endif
1116 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
1117 mFocusedApplication, NULL, nextWakeupTime);
1118 goto Unresponsive;
1119 }
1120
1121 LOGI("Dropping event because there is no focused window or focused application.");
1122 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1123 goto Failed;
1124 }
1125
1126 // Check permissions.
Jeff Brown01ce2e92010-09-26 22:20:12 -07001127 if (! checkInjectionPermission(mFocusedWindow, entry->injectionState)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001128 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1129 goto Failed;
1130 }
1131
1132 // If the currently focused window is paused then keep waiting.
1133 if (mFocusedWindow->paused) {
1134#if DEBUG_FOCUS
1135 LOGD("Waiting because focused window is paused.");
1136#endif
1137 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
1138 mFocusedApplication, mFocusedWindow, nextWakeupTime);
1139 goto Unresponsive;
1140 }
1141
Jeff Brown519e0242010-09-15 15:18:56 -07001142 // If the currently focused window is still working on previous events then keep waiting.
1143 if (! isWindowFinishedWithPreviousInputLocked(mFocusedWindow)) {
1144#if DEBUG_FOCUS
1145 LOGD("Waiting because focused window still processing previous input.");
1146#endif
1147 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
1148 mFocusedApplication, mFocusedWindow, nextWakeupTime);
1149 goto Unresponsive;
1150 }
1151
Jeff Brownb88102f2010-09-08 11:49:43 -07001152 // Success! Output targets.
1153 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
Jeff Browna032cc02011-03-07 16:56:21 -08001154 addWindowTargetLocked(mFocusedWindow,
1155 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS, BitSet32(0));
Jeff Brownb88102f2010-09-08 11:49:43 -07001156
1157 // Done.
1158Failed:
1159Unresponsive:
Jeff Brown519e0242010-09-15 15:18:56 -07001160 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
1161 updateDispatchStatisticsLocked(currentTime, entry,
1162 injectionResult, timeSpentWaitingForApplication);
Jeff Brownb88102f2010-09-08 11:49:43 -07001163#if DEBUG_FOCUS
Jeff Brown519e0242010-09-15 15:18:56 -07001164 LOGD("findFocusedWindow finished: injectionResult=%d, "
1165 "timeSpendWaitingForApplication=%0.1fms",
1166 injectionResult, timeSpentWaitingForApplication / 1000000.0);
Jeff Brownb88102f2010-09-08 11:49:43 -07001167#endif
1168 return injectionResult;
1169}
1170
Jeff Brown01ce2e92010-09-26 22:20:12 -07001171int32_t InputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime,
Jeff Browna032cc02011-03-07 16:56:21 -08001172 const MotionEntry* entry, nsecs_t* nextWakeupTime, bool* outConflictingPointerActions,
1173 const MotionSample** outSplitBatchAfterSample) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001174 enum InjectionPermission {
1175 INJECTION_PERMISSION_UNKNOWN,
1176 INJECTION_PERMISSION_GRANTED,
1177 INJECTION_PERMISSION_DENIED
1178 };
1179
Jeff Brownb88102f2010-09-08 11:49:43 -07001180 mCurrentInputTargets.clear();
1181
1182 nsecs_t startTime = now();
1183
1184 // For security reasons, we defer updating the touch state until we are sure that
1185 // event injection will be allowed.
1186 //
1187 // FIXME In the original code, screenWasOff could never be set to true.
1188 // The reason is that the POLICY_FLAG_WOKE_HERE
1189 // and POLICY_FLAG_BRIGHT_HERE flags were set only when preprocessing raw
1190 // EV_KEY, EV_REL and EV_ABS events. As it happens, the touch event was
1191 // actually enqueued using the policyFlags that appeared in the final EV_SYN
1192 // events upon which no preprocessing took place. So policyFlags was always 0.
1193 // In the new native input dispatcher we're a bit more careful about event
1194 // preprocessing so the touches we receive can actually have non-zero policyFlags.
1195 // Unfortunately we obtain undesirable behavior.
1196 //
1197 // Here's what happens:
1198 //
1199 // When the device dims in anticipation of going to sleep, touches
1200 // in windows which have FLAG_TOUCHABLE_WHEN_WAKING cause
1201 // the device to brighten and reset the user activity timer.
1202 // Touches on other windows (such as the launcher window)
1203 // are dropped. Then after a moment, the device goes to sleep. Oops.
1204 //
1205 // Also notice how screenWasOff was being initialized using POLICY_FLAG_BRIGHT_HERE
1206 // instead of POLICY_FLAG_WOKE_HERE...
1207 //
1208 bool screenWasOff = false; // original policy: policyFlags & POLICY_FLAG_BRIGHT_HERE;
1209
1210 int32_t action = entry->action;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001211 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Jeff Brownb88102f2010-09-08 11:49:43 -07001212
1213 // Update the touch state as needed based on the properties of the touch event.
Jeff Brown01ce2e92010-09-26 22:20:12 -07001214 int32_t injectionResult = INPUT_EVENT_INJECTION_PENDING;
1215 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
Jeff Browna032cc02011-03-07 16:56:21 -08001216 const InputWindow* newHoverWindow = NULL;
Jeff Browncc0c1592011-02-19 05:07:28 -08001217
1218 bool isSplit = mTouchState.split;
1219 bool wrongDevice = mTouchState.down
1220 && (mTouchState.deviceId != entry->deviceId
1221 || mTouchState.source != entry->source);
Jeff Browna032cc02011-03-07 16:56:21 -08001222 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE
1223 || maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER
1224 || maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1225 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN
1226 || maskedAction == AMOTION_EVENT_ACTION_SCROLL
1227 || isHoverAction);
1228 if (newGesture) {
Jeff Browncc0c1592011-02-19 05:07:28 -08001229 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
1230 if (wrongDevice && !down) {
1231 mTempTouchState.copyFrom(mTouchState);
1232 } else {
1233 mTempTouchState.reset();
1234 mTempTouchState.down = down;
1235 mTempTouchState.deviceId = entry->deviceId;
1236 mTempTouchState.source = entry->source;
1237 isSplit = false;
1238 wrongDevice = false;
1239 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001240 } else {
1241 mTempTouchState.copyFrom(mTouchState);
Jeff Browncc0c1592011-02-19 05:07:28 -08001242 }
1243 if (wrongDevice) {
Jeff Browna2cc28d2011-03-25 11:58:46 -07001244#if DEBUG_FOCUS
Jeff Browncc0c1592011-02-19 05:07:28 -08001245 LOGD("Dropping event because a pointer for a different device is already down.");
Jeff Brown95712852011-01-04 19:41:59 -08001246#endif
Jeff Browncc0c1592011-02-19 05:07:28 -08001247 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1248 goto Failed;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001249 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001250
Jeff Browna032cc02011-03-07 16:56:21 -08001251 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
Jeff Brown33bbfd22011-02-24 20:55:35 -08001252 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
Jeff Brownb88102f2010-09-08 11:49:43 -07001253
Jeff Browna032cc02011-03-07 16:56:21 -08001254 const MotionSample* sample = &entry->firstSample;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001255 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Jeff Browna032cc02011-03-07 16:56:21 -08001256 int32_t x = int32_t(sample->pointerCoords[pointerIndex].
Jeff Brownebbd5d12011-02-17 13:01:34 -08001257 getAxisValue(AMOTION_EVENT_AXIS_X));
Jeff Browna032cc02011-03-07 16:56:21 -08001258 int32_t y = int32_t(sample->pointerCoords[pointerIndex].
Jeff Brownebbd5d12011-02-17 13:01:34 -08001259 getAxisValue(AMOTION_EVENT_AXIS_Y));
Jeff Brown01ce2e92010-09-26 22:20:12 -07001260 const InputWindow* newTouchedWindow = NULL;
1261 const InputWindow* topErrorWindow = NULL;
Jeff Browna032cc02011-03-07 16:56:21 -08001262 bool isTouchModal = false;
Jeff Brownb88102f2010-09-08 11:49:43 -07001263
1264 // Traverse windows from front to back to find touched window and outside targets.
1265 size_t numWindows = mWindows.size();
1266 for (size_t i = 0; i < numWindows; i++) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001267 const InputWindow* window = & mWindows.editItemAt(i);
Jeff Brownb88102f2010-09-08 11:49:43 -07001268 int32_t flags = window->layoutParamsFlags;
1269
1270 if (flags & InputWindow::FLAG_SYSTEM_ERROR) {
1271 if (! topErrorWindow) {
1272 topErrorWindow = window;
1273 }
1274 }
1275
1276 if (window->visible) {
1277 if (! (flags & InputWindow::FLAG_NOT_TOUCHABLE)) {
Jeff Browna032cc02011-03-07 16:56:21 -08001278 isTouchModal = (flags & (InputWindow::FLAG_NOT_FOCUSABLE
Jeff Brownb88102f2010-09-08 11:49:43 -07001279 | InputWindow::FLAG_NOT_TOUCH_MODAL)) == 0;
Jeff Brownfbf09772011-01-16 14:06:57 -08001280 if (isTouchModal || window->touchableRegionContainsPoint(x, y)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001281 if (! screenWasOff || flags & InputWindow::FLAG_TOUCHABLE_WHEN_WAKING) {
1282 newTouchedWindow = window;
Jeff Brownb88102f2010-09-08 11:49:43 -07001283 }
1284 break; // found touched window, exit window loop
1285 }
1286 }
1287
Jeff Brown01ce2e92010-09-26 22:20:12 -07001288 if (maskedAction == AMOTION_EVENT_ACTION_DOWN
1289 && (flags & InputWindow::FLAG_WATCH_OUTSIDE_TOUCH)) {
Jeff Browna032cc02011-03-07 16:56:21 -08001290 int32_t outsideTargetFlags = InputTarget::FLAG_DISPATCH_AS_OUTSIDE;
Jeff Brown19dfc832010-10-05 12:26:23 -07001291 if (isWindowObscuredAtPointLocked(window, x, y)) {
1292 outsideTargetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1293 }
1294
1295 mTempTouchState.addOrUpdateWindow(window, outsideTargetFlags, BitSet32(0));
Jeff Brownb88102f2010-09-08 11:49:43 -07001296 }
1297 }
1298 }
1299
1300 // If there is an error window but it is not taking focus (typically because
1301 // it is invisible) then wait for it. Any other focused window may in
1302 // fact be in ANR state.
1303 if (topErrorWindow && newTouchedWindow != topErrorWindow) {
1304#if DEBUG_FOCUS
1305 LOGD("Waiting because system error window is pending.");
1306#endif
1307 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
1308 NULL, NULL, nextWakeupTime);
1309 injectionPermission = INJECTION_PERMISSION_UNKNOWN;
1310 goto Unresponsive;
1311 }
1312
Jeff Brown01ce2e92010-09-26 22:20:12 -07001313 // Figure out whether splitting will be allowed for this window.
Jeff Brown46e75292010-11-10 16:53:45 -08001314 if (newTouchedWindow && newTouchedWindow->supportsSplitTouch()) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001315 // New window supports splitting.
1316 isSplit = true;
1317 } else if (isSplit) {
1318 // New window does not support splitting but we have already split events.
1319 // Assign the pointer to the first foreground window we find.
1320 // (May be NULL which is why we put this code block before the next check.)
1321 newTouchedWindow = mTempTouchState.getFirstForegroundWindow();
1322 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001323
Jeff Brownb88102f2010-09-08 11:49:43 -07001324 // If we did not find a touched window then fail.
1325 if (! newTouchedWindow) {
1326 if (mFocusedApplication) {
1327#if DEBUG_FOCUS
1328 LOGD("Waiting because there is no touched window but there is a "
Jeff Brown519e0242010-09-15 15:18:56 -07001329 "focused application that may eventually add a new window: %s.",
1330 getApplicationWindowLabelLocked(mFocusedApplication, NULL).string());
Jeff Brownb88102f2010-09-08 11:49:43 -07001331#endif
1332 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
1333 mFocusedApplication, NULL, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -07001334 goto Unresponsive;
1335 }
1336
1337 LOGI("Dropping event because there is no touched window or focused application.");
1338 injectionResult = INPUT_EVENT_INJECTION_FAILED;
Jeff Brownb88102f2010-09-08 11:49:43 -07001339 goto Failed;
1340 }
1341
Jeff Brown19dfc832010-10-05 12:26:23 -07001342 // Set target flags.
Jeff Browna032cc02011-03-07 16:56:21 -08001343 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
Jeff Brown19dfc832010-10-05 12:26:23 -07001344 if (isSplit) {
1345 targetFlags |= InputTarget::FLAG_SPLIT;
1346 }
1347 if (isWindowObscuredAtPointLocked(newTouchedWindow, x, y)) {
1348 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1349 }
1350
Jeff Browna032cc02011-03-07 16:56:21 -08001351 // Update hover state.
1352 if (isHoverAction) {
1353 newHoverWindow = newTouchedWindow;
1354
1355 // Ensure all subsequent motion samples are also within the touched window.
1356 // Set *outSplitBatchAfterSample to the sample before the first one that is not
1357 // within the touched window.
1358 if (!isTouchModal) {
1359 while (sample->next) {
1360 if (!newHoverWindow->touchableRegionContainsPoint(
1361 sample->next->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X),
1362 sample->next->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y))) {
1363 *outSplitBatchAfterSample = sample;
1364 break;
1365 }
1366 sample = sample->next;
1367 }
1368 }
1369 } else if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
1370 newHoverWindow = mLastHoverWindow;
1371 }
1372
Jeff Brown01ce2e92010-09-26 22:20:12 -07001373 // Update the temporary touch state.
1374 BitSet32 pointerIds;
1375 if (isSplit) {
1376 uint32_t pointerId = entry->pointerIds[pointerIndex];
1377 pointerIds.markBit(pointerId);
Jeff Brownb88102f2010-09-08 11:49:43 -07001378 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001379 mTempTouchState.addOrUpdateWindow(newTouchedWindow, targetFlags, pointerIds);
Jeff Brownb88102f2010-09-08 11:49:43 -07001380 } else {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001381 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
Jeff Brownb88102f2010-09-08 11:49:43 -07001382
1383 // If the pointer is not currently down, then ignore the event.
Jeff Brown01ce2e92010-09-26 22:20:12 -07001384 if (! mTempTouchState.down) {
Jeff Browna2cc28d2011-03-25 11:58:46 -07001385#if DEBUG_FOCUS
Jeff Brown76860e32010-10-25 17:37:46 -07001386 LOGD("Dropping event because the pointer is not down or we previously "
1387 "dropped the pointer down event.");
1388#endif
Jeff Brownb88102f2010-09-08 11:49:43 -07001389 injectionResult = INPUT_EVENT_INJECTION_FAILED;
Jeff Brownb88102f2010-09-08 11:49:43 -07001390 goto Failed;
1391 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001392 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001393
Jeff Browna032cc02011-03-07 16:56:21 -08001394 if (newHoverWindow != mLastHoverWindow) {
1395 // Split the batch here so we send exactly one sample as part of ENTER or EXIT.
1396 *outSplitBatchAfterSample = &entry->firstSample;
1397
1398 // Let the previous window know that the hover sequence is over.
1399 if (mLastHoverWindow) {
1400#if DEBUG_HOVER
1401 LOGD("Sending hover exit event to window %s.", mLastHoverWindow->name.string());
1402#endif
1403 mTempTouchState.addOrUpdateWindow(mLastHoverWindow,
1404 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
1405 }
1406
1407 // Let the new window know that the hover sequence is starting.
1408 if (newHoverWindow) {
1409#if DEBUG_HOVER
1410 LOGD("Sending hover enter event to window %s.", newHoverWindow->name.string());
1411#endif
1412 mTempTouchState.addOrUpdateWindow(newHoverWindow,
1413 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER, BitSet32(0));
1414 }
1415 }
1416
Jeff Brown01ce2e92010-09-26 22:20:12 -07001417 // Check permission to inject into all touched foreground windows and ensure there
1418 // is at least one touched foreground window.
1419 {
1420 bool haveForegroundWindow = false;
1421 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1422 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1423 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1424 haveForegroundWindow = true;
1425 if (! checkInjectionPermission(touchedWindow.window, entry->injectionState)) {
1426 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1427 injectionPermission = INJECTION_PERMISSION_DENIED;
1428 goto Failed;
1429 }
1430 }
1431 }
1432 if (! haveForegroundWindow) {
Jeff Browna2cc28d2011-03-25 11:58:46 -07001433#if DEBUG_FOCUS
Jeff Brown01ce2e92010-09-26 22:20:12 -07001434 LOGD("Dropping event because there is no touched foreground window to receive it.");
Jeff Brownb88102f2010-09-08 11:49:43 -07001435#endif
1436 injectionResult = INPUT_EVENT_INJECTION_FAILED;
Jeff Brownb88102f2010-09-08 11:49:43 -07001437 goto Failed;
1438 }
1439
Jeff Brown01ce2e92010-09-26 22:20:12 -07001440 // Permission granted to injection into all touched foreground windows.
1441 injectionPermission = INJECTION_PERMISSION_GRANTED;
1442 }
Jeff Brown519e0242010-09-15 15:18:56 -07001443
Jeff Brown01ce2e92010-09-26 22:20:12 -07001444 // Ensure all touched foreground windows are ready for new input.
1445 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1446 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1447 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1448 // If the touched window is paused then keep waiting.
1449 if (touchedWindow.window->paused) {
Jeff Browna2cc28d2011-03-25 11:58:46 -07001450#if DEBUG_FOCUS
Jeff Brown01ce2e92010-09-26 22:20:12 -07001451 LOGD("Waiting because touched window is paused.");
Jeff Brown519e0242010-09-15 15:18:56 -07001452#endif
Jeff Brown01ce2e92010-09-26 22:20:12 -07001453 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
1454 NULL, touchedWindow.window, nextWakeupTime);
1455 goto Unresponsive;
1456 }
1457
1458 // If the touched window is still working on previous events then keep waiting.
1459 if (! isWindowFinishedWithPreviousInputLocked(touchedWindow.window)) {
1460#if DEBUG_FOCUS
1461 LOGD("Waiting because touched window still processing previous input.");
1462#endif
1463 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
1464 NULL, touchedWindow.window, nextWakeupTime);
1465 goto Unresponsive;
1466 }
1467 }
1468 }
1469
1470 // If this is the first pointer going down and the touched window has a wallpaper
1471 // then also add the touched wallpaper windows so they are locked in for the duration
1472 // of the touch gesture.
Jeff Brown33bbfd22011-02-24 20:55:35 -08001473 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
1474 // engine only supports touch events. We would need to add a mechanism similar
1475 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
1476 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001477 const InputWindow* foregroundWindow = mTempTouchState.getFirstForegroundWindow();
1478 if (foregroundWindow->hasWallpaper) {
1479 for (size_t i = 0; i < mWindows.size(); i++) {
1480 const InputWindow* window = & mWindows[i];
1481 if (window->layoutParamsType == InputWindow::TYPE_WALLPAPER) {
Jeff Brown19dfc832010-10-05 12:26:23 -07001482 mTempTouchState.addOrUpdateWindow(window,
Jeff Browna032cc02011-03-07 16:56:21 -08001483 InputTarget::FLAG_WINDOW_IS_OBSCURED
1484 | InputTarget::FLAG_DISPATCH_AS_IS,
1485 BitSet32(0));
Jeff Brown01ce2e92010-09-26 22:20:12 -07001486 }
1487 }
1488 }
1489 }
1490
Jeff Brownb88102f2010-09-08 11:49:43 -07001491 // Success! Output targets.
1492 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
Jeff Brownb88102f2010-09-08 11:49:43 -07001493
Jeff Brown01ce2e92010-09-26 22:20:12 -07001494 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1495 const TouchedWindow& touchedWindow = mTempTouchState.windows.itemAt(i);
1496 addWindowTargetLocked(touchedWindow.window, touchedWindow.targetFlags,
1497 touchedWindow.pointerIds);
Jeff Brownb88102f2010-09-08 11:49:43 -07001498 }
1499
Jeff Browna032cc02011-03-07 16:56:21 -08001500 // Drop the outside or hover touch windows since we will not care about them
1501 // in the next iteration.
1502 mTempTouchState.filterNonAsIsTouchWindows();
Jeff Brown01ce2e92010-09-26 22:20:12 -07001503
Jeff Brownb88102f2010-09-08 11:49:43 -07001504Failed:
1505 // Check injection permission once and for all.
1506 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001507 if (checkInjectionPermission(NULL, entry->injectionState)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001508 injectionPermission = INJECTION_PERMISSION_GRANTED;
1509 } else {
1510 injectionPermission = INJECTION_PERMISSION_DENIED;
1511 }
1512 }
1513
1514 // Update final pieces of touch state if the injector had permission.
1515 if (injectionPermission == INJECTION_PERMISSION_GRANTED) {
Jeff Brown95712852011-01-04 19:41:59 -08001516 if (!wrongDevice) {
1517 if (maskedAction == AMOTION_EVENT_ACTION_UP
Jeff Browncc0c1592011-02-19 05:07:28 -08001518 || maskedAction == AMOTION_EVENT_ACTION_CANCEL
Jeff Browna032cc02011-03-07 16:56:21 -08001519 || isHoverAction) {
Jeff Brown95712852011-01-04 19:41:59 -08001520 // All pointers up or canceled.
Jeff Brown33bbfd22011-02-24 20:55:35 -08001521 mTouchState.reset();
Jeff Brown95712852011-01-04 19:41:59 -08001522 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1523 // First pointer went down.
1524 if (mTouchState.down) {
Jeff Browncc0c1592011-02-19 05:07:28 -08001525 *outConflictingPointerActions = true;
Jeff Brownb6997262010-10-08 22:31:17 -07001526#if DEBUG_FOCUS
Jeff Brown95712852011-01-04 19:41:59 -08001527 LOGD("Pointer down received while already down.");
Jeff Brownb6997262010-10-08 22:31:17 -07001528#endif
Jeff Brown95712852011-01-04 19:41:59 -08001529 }
Jeff Brown33bbfd22011-02-24 20:55:35 -08001530 mTouchState.copyFrom(mTempTouchState);
Jeff Brown95712852011-01-04 19:41:59 -08001531 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
1532 // One pointer went up.
1533 if (isSplit) {
1534 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
1535 uint32_t pointerId = entry->pointerIds[pointerIndex];
Jeff Brownb88102f2010-09-08 11:49:43 -07001536
Jeff Brown95712852011-01-04 19:41:59 -08001537 for (size_t i = 0; i < mTempTouchState.windows.size(); ) {
1538 TouchedWindow& touchedWindow = mTempTouchState.windows.editItemAt(i);
1539 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
1540 touchedWindow.pointerIds.clearBit(pointerId);
1541 if (touchedWindow.pointerIds.isEmpty()) {
1542 mTempTouchState.windows.removeAt(i);
1543 continue;
1544 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001545 }
Jeff Brown95712852011-01-04 19:41:59 -08001546 i += 1;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001547 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001548 }
Jeff Brown33bbfd22011-02-24 20:55:35 -08001549 mTouchState.copyFrom(mTempTouchState);
1550 } else if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
1551 // Discard temporary touch state since it was only valid for this action.
1552 } else {
1553 // Save changes to touch state as-is for all other actions.
1554 mTouchState.copyFrom(mTempTouchState);
Jeff Brownb88102f2010-09-08 11:49:43 -07001555 }
Jeff Browna032cc02011-03-07 16:56:21 -08001556
1557 // Update hover state.
1558 mLastHoverWindow = newHoverWindow;
Jeff Brown95712852011-01-04 19:41:59 -08001559 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001560 } else {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001561#if DEBUG_FOCUS
1562 LOGD("Not updating touch focus because injection was denied.");
1563#endif
Jeff Brownb88102f2010-09-08 11:49:43 -07001564 }
1565
1566Unresponsive:
Jeff Brown120a4592010-10-27 18:43:51 -07001567 // Reset temporary touch state to ensure we release unnecessary references to input channels.
1568 mTempTouchState.reset();
1569
Jeff Brown519e0242010-09-15 15:18:56 -07001570 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
1571 updateDispatchStatisticsLocked(currentTime, entry,
1572 injectionResult, timeSpentWaitingForApplication);
Jeff Brownb88102f2010-09-08 11:49:43 -07001573#if DEBUG_FOCUS
Jeff Brown01ce2e92010-09-26 22:20:12 -07001574 LOGD("findTouchedWindow finished: injectionResult=%d, injectionPermission=%d, "
1575 "timeSpentWaitingForApplication=%0.1fms",
Jeff Brown519e0242010-09-15 15:18:56 -07001576 injectionResult, injectionPermission, timeSpentWaitingForApplication / 1000000.0);
Jeff Brownb88102f2010-09-08 11:49:43 -07001577#endif
1578 return injectionResult;
1579}
1580
Jeff Brown01ce2e92010-09-26 22:20:12 -07001581void InputDispatcher::addWindowTargetLocked(const InputWindow* window, int32_t targetFlags,
1582 BitSet32 pointerIds) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001583 mCurrentInputTargets.push();
1584
1585 InputTarget& target = mCurrentInputTargets.editTop();
1586 target.inputChannel = window->inputChannel;
1587 target.flags = targetFlags;
Jeff Brownb88102f2010-09-08 11:49:43 -07001588 target.xOffset = - window->frameLeft;
1589 target.yOffset = - window->frameTop;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001590 target.pointerIds = pointerIds;
Jeff Brownb88102f2010-09-08 11:49:43 -07001591}
1592
1593void InputDispatcher::addMonitoringTargetsLocked() {
1594 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
1595 mCurrentInputTargets.push();
1596
1597 InputTarget& target = mCurrentInputTargets.editTop();
1598 target.inputChannel = mMonitoringChannels[i];
Jeff Brownb6110c22011-04-01 16:15:13 -07001599 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
Jeff Brownb88102f2010-09-08 11:49:43 -07001600 target.xOffset = 0;
1601 target.yOffset = 0;
Jeff Brownb6110c22011-04-01 16:15:13 -07001602 target.pointerIds.clear();
Jeff Brownb88102f2010-09-08 11:49:43 -07001603 }
1604}
1605
1606bool InputDispatcher::checkInjectionPermission(const InputWindow* window,
Jeff Brown01ce2e92010-09-26 22:20:12 -07001607 const InjectionState* injectionState) {
1608 if (injectionState
Jeff Brownb6997262010-10-08 22:31:17 -07001609 && (window == NULL || window->ownerUid != injectionState->injectorUid)
1610 && !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
1611 if (window) {
1612 LOGW("Permission denied: injecting event from pid %d uid %d to window "
1613 "with input channel %s owned by uid %d",
1614 injectionState->injectorPid, injectionState->injectorUid,
1615 window->inputChannel->getName().string(),
1616 window->ownerUid);
1617 } else {
1618 LOGW("Permission denied: injecting event from pid %d uid %d",
1619 injectionState->injectorPid, injectionState->injectorUid);
Jeff Brownb88102f2010-09-08 11:49:43 -07001620 }
Jeff Brownb6997262010-10-08 22:31:17 -07001621 return false;
Jeff Brownb88102f2010-09-08 11:49:43 -07001622 }
1623 return true;
1624}
1625
Jeff Brown19dfc832010-10-05 12:26:23 -07001626bool InputDispatcher::isWindowObscuredAtPointLocked(
1627 const InputWindow* window, int32_t x, int32_t y) const {
Jeff Brownb88102f2010-09-08 11:49:43 -07001628 size_t numWindows = mWindows.size();
1629 for (size_t i = 0; i < numWindows; i++) {
1630 const InputWindow* other = & mWindows.itemAt(i);
1631 if (other == window) {
1632 break;
1633 }
Jeff Brown19dfc832010-10-05 12:26:23 -07001634 if (other->visible && ! other->isTrustedOverlay() && other->frameContainsPoint(x, y)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001635 return true;
1636 }
1637 }
1638 return false;
1639}
1640
Jeff Brown519e0242010-09-15 15:18:56 -07001641bool InputDispatcher::isWindowFinishedWithPreviousInputLocked(const InputWindow* window) {
1642 ssize_t connectionIndex = getConnectionIndexLocked(window->inputChannel);
1643 if (connectionIndex >= 0) {
1644 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
1645 return connection->outboundQueue.isEmpty();
1646 } else {
1647 return true;
1648 }
1649}
1650
1651String8 InputDispatcher::getApplicationWindowLabelLocked(const InputApplication* application,
1652 const InputWindow* window) {
1653 if (application) {
1654 if (window) {
1655 String8 label(application->name);
1656 label.append(" - ");
1657 label.append(window->name);
1658 return label;
1659 } else {
1660 return application->name;
1661 }
1662 } else if (window) {
1663 return window->name;
1664 } else {
1665 return String8("<unknown application or window>");
1666 }
1667}
1668
Jeff Browne2fe69e2010-10-18 13:21:23 -07001669void InputDispatcher::pokeUserActivityLocked(const EventEntry* eventEntry) {
Jeff Brown56194eb2011-03-02 19:23:13 -08001670 int32_t eventType = POWER_MANAGER_OTHER_EVENT;
Jeff Brown4d396052010-10-29 21:50:21 -07001671 switch (eventEntry->type) {
1672 case EventEntry::TYPE_MOTION: {
Jeff Browne2fe69e2010-10-18 13:21:23 -07001673 const MotionEntry* motionEntry = static_cast<const MotionEntry*>(eventEntry);
Jeff Brown4d396052010-10-29 21:50:21 -07001674 if (motionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
1675 return;
1676 }
1677
Jeff Brown56194eb2011-03-02 19:23:13 -08001678 if (MotionEvent::isTouchEvent(motionEntry->source, motionEntry->action)) {
Joe Onorato1a542c72010-11-08 09:48:20 -08001679 eventType = POWER_MANAGER_TOUCH_EVENT;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001680 }
Jeff Brown4d396052010-10-29 21:50:21 -07001681 break;
1682 }
1683 case EventEntry::TYPE_KEY: {
1684 const KeyEntry* keyEntry = static_cast<const KeyEntry*>(eventEntry);
1685 if (keyEntry->flags & AKEY_EVENT_FLAG_CANCELED) {
1686 return;
1687 }
Jeff Brown56194eb2011-03-02 19:23:13 -08001688 eventType = POWER_MANAGER_BUTTON_EVENT;
Jeff Brown4d396052010-10-29 21:50:21 -07001689 break;
1690 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001691 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001692
Jeff Brownb88102f2010-09-08 11:49:43 -07001693 CommandEntry* commandEntry = postCommandLocked(
1694 & InputDispatcher::doPokeUserActivityLockedInterruptible);
Jeff Browne2fe69e2010-10-18 13:21:23 -07001695 commandEntry->eventTime = eventEntry->eventTime;
Jeff Brownb88102f2010-09-08 11:49:43 -07001696 commandEntry->userActivityEventType = eventType;
1697}
1698
Jeff Brown7fbdc842010-06-17 20:52:56 -07001699void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
1700 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget,
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001701 bool resumeWithAppendedMotionSample) {
1702#if DEBUG_DISPATCH_CYCLE
Jeff Brown519e0242010-09-15 15:18:56 -07001703 LOGD("channel '%s' ~ prepareDispatchCycle - flags=%d, "
Jeff Brown01ce2e92010-09-26 22:20:12 -07001704 "xOffset=%f, yOffset=%f, "
Jeff Brown83c09682010-12-23 17:50:18 -08001705 "pointerIds=0x%x, "
Jeff Brown01ce2e92010-09-26 22:20:12 -07001706 "resumeWithAppendedMotionSample=%s",
Jeff Brown519e0242010-09-15 15:18:56 -07001707 connection->getInputChannelName(), inputTarget->flags,
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001708 inputTarget->xOffset, inputTarget->yOffset,
Jeff Brown83c09682010-12-23 17:50:18 -08001709 inputTarget->pointerIds.value,
Jeff Brownb88102f2010-09-08 11:49:43 -07001710 toString(resumeWithAppendedMotionSample));
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001711#endif
1712
Jeff Brown01ce2e92010-09-26 22:20:12 -07001713 // Make sure we are never called for streaming when splitting across multiple windows.
1714 bool isSplit = inputTarget->flags & InputTarget::FLAG_SPLIT;
Jeff Brownb6110c22011-04-01 16:15:13 -07001715 LOG_ASSERT(! (resumeWithAppendedMotionSample && isSplit));
Jeff Brown01ce2e92010-09-26 22:20:12 -07001716
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001717 // Skip this event if the connection status is not normal.
Jeff Brown519e0242010-09-15 15:18:56 -07001718 // We don't want to enqueue additional outbound events if the connection is broken.
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001719 if (connection->status != Connection::STATUS_NORMAL) {
Jeff Brownb6997262010-10-08 22:31:17 -07001720#if DEBUG_DISPATCH_CYCLE
1721 LOGD("channel '%s' ~ Dropping event because the channel status is %s",
Jeff Brownb88102f2010-09-08 11:49:43 -07001722 connection->getInputChannelName(), connection->getStatusLabel());
Jeff Brownb6997262010-10-08 22:31:17 -07001723#endif
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001724 return;
1725 }
1726
Jeff Brown01ce2e92010-09-26 22:20:12 -07001727 // Split a motion event if needed.
1728 if (isSplit) {
Jeff Brownb6110c22011-04-01 16:15:13 -07001729 LOG_ASSERT(eventEntry->type == EventEntry::TYPE_MOTION);
Jeff Brown01ce2e92010-09-26 22:20:12 -07001730
1731 MotionEntry* originalMotionEntry = static_cast<MotionEntry*>(eventEntry);
1732 if (inputTarget->pointerIds.count() != originalMotionEntry->pointerCount) {
1733 MotionEntry* splitMotionEntry = splitMotionEvent(
1734 originalMotionEntry, inputTarget->pointerIds);
Jeff Brown58a2da82011-01-25 16:02:22 -08001735 if (!splitMotionEntry) {
1736 return; // split event was dropped
1737 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001738#if DEBUG_FOCUS
1739 LOGD("channel '%s' ~ Split motion event.",
1740 connection->getInputChannelName());
1741 logOutboundMotionDetailsLocked(" ", splitMotionEntry);
1742#endif
1743 eventEntry = splitMotionEntry;
1744 }
1745 }
1746
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001747 // Resume the dispatch cycle with a freshly appended motion sample.
1748 // First we check that the last dispatch entry in the outbound queue is for the same
1749 // motion event to which we appended the motion sample. If we find such a dispatch
1750 // entry, and if it is currently in progress then we try to stream the new sample.
1751 bool wasEmpty = connection->outboundQueue.isEmpty();
1752
1753 if (! wasEmpty && resumeWithAppendedMotionSample) {
1754 DispatchEntry* motionEventDispatchEntry =
1755 connection->findQueuedDispatchEntryForEvent(eventEntry);
1756 if (motionEventDispatchEntry) {
1757 // If the dispatch entry is not in progress, then we must be busy dispatching an
1758 // earlier event. Not a problem, the motion event is on the outbound queue and will
1759 // be dispatched later.
1760 if (! motionEventDispatchEntry->inProgress) {
1761#if DEBUG_BATCHING
1762 LOGD("channel '%s' ~ Not streaming because the motion event has "
1763 "not yet been dispatched. "
1764 "(Waiting for earlier events to be consumed.)",
1765 connection->getInputChannelName());
1766#endif
1767 return;
1768 }
1769
1770 // If the dispatch entry is in progress but it already has a tail of pending
1771 // motion samples, then it must mean that the shared memory buffer filled up.
1772 // Not a problem, when this dispatch cycle is finished, we will eventually start
1773 // a new dispatch cycle to process the tail and that tail includes the newly
1774 // appended motion sample.
1775 if (motionEventDispatchEntry->tailMotionSample) {
1776#if DEBUG_BATCHING
1777 LOGD("channel '%s' ~ Not streaming because no new samples can "
1778 "be appended to the motion event in this dispatch cycle. "
1779 "(Waiting for next dispatch cycle to start.)",
1780 connection->getInputChannelName());
1781#endif
1782 return;
1783 }
1784
1785 // The dispatch entry is in progress and is still potentially open for streaming.
1786 // Try to stream the new motion sample. This might fail if the consumer has already
1787 // consumed the motion event (or if the channel is broken).
Jeff Brown01ce2e92010-09-26 22:20:12 -07001788 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
1789 MotionSample* appendedMotionSample = motionEntry->lastSample;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001790 status_t status = connection->inputPublisher.appendMotionSample(
1791 appendedMotionSample->eventTime, appendedMotionSample->pointerCoords);
1792 if (status == OK) {
1793#if DEBUG_BATCHING
1794 LOGD("channel '%s' ~ Successfully streamed new motion sample.",
1795 connection->getInputChannelName());
1796#endif
1797 return;
1798 }
1799
1800#if DEBUG_BATCHING
1801 if (status == NO_MEMORY) {
1802 LOGD("channel '%s' ~ Could not append motion sample to currently "
1803 "dispatched move event because the shared memory buffer is full. "
1804 "(Waiting for next dispatch cycle to start.)",
1805 connection->getInputChannelName());
1806 } else if (status == status_t(FAILED_TRANSACTION)) {
1807 LOGD("channel '%s' ~ Could not append motion sample to currently "
Jeff Brown349703e2010-06-22 01:27:15 -07001808 "dispatched move event because the event has already been consumed. "
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001809 "(Waiting for next dispatch cycle to start.)",
1810 connection->getInputChannelName());
1811 } else {
1812 LOGD("channel '%s' ~ Could not append motion sample to currently "
1813 "dispatched move event due to an error, status=%d. "
1814 "(Waiting for next dispatch cycle to start.)",
1815 connection->getInputChannelName(), status);
1816 }
1817#endif
1818 // Failed to stream. Start a new tail of pending motion samples to dispatch
1819 // in the next cycle.
1820 motionEventDispatchEntry->tailMotionSample = appendedMotionSample;
1821 return;
1822 }
1823 }
1824
Jeff Browna032cc02011-03-07 16:56:21 -08001825 // Enqueue dispatch entries for the requested modes.
1826 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1827 resumeWithAppendedMotionSample, InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
1828 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1829 resumeWithAppendedMotionSample, InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
1830 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1831 resumeWithAppendedMotionSample, InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
1832 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1833 resumeWithAppendedMotionSample, InputTarget::FLAG_DISPATCH_AS_IS);
1834
1835 // If the outbound queue was previously empty, start the dispatch cycle going.
Jeff Brownb6110c22011-04-01 16:15:13 -07001836 if (wasEmpty && !connection->outboundQueue.isEmpty()) {
Jeff Browna032cc02011-03-07 16:56:21 -08001837 activateConnectionLocked(connection.get());
1838 startDispatchCycleLocked(currentTime, connection);
1839 }
1840}
1841
1842void InputDispatcher::enqueueDispatchEntryLocked(
1843 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget,
1844 bool resumeWithAppendedMotionSample, int32_t dispatchMode) {
1845 int32_t inputTargetFlags = inputTarget->flags;
1846 if (!(inputTargetFlags & dispatchMode)) {
1847 return;
1848 }
1849 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
1850
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001851 // This is a new event.
1852 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Jeff Brownb88102f2010-09-08 11:49:43 -07001853 DispatchEntry* dispatchEntry = mAllocator.obtainDispatchEntry(eventEntry, // increments ref
Jeff Browna032cc02011-03-07 16:56:21 -08001854 inputTargetFlags, inputTarget->xOffset, inputTarget->yOffset);
Jeff Brown519e0242010-09-15 15:18:56 -07001855 if (dispatchEntry->hasForegroundTarget()) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001856 incrementPendingForegroundDispatchesLocked(eventEntry);
Jeff Brown6ec402b2010-07-28 15:48:59 -07001857 }
1858
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001859 // Handle the case where we could not stream a new motion sample because the consumer has
1860 // already consumed the motion event (otherwise the corresponding dispatch entry would
1861 // still be in the outbound queue for this connection). We set the head motion sample
1862 // to the list starting with the newly appended motion sample.
1863 if (resumeWithAppendedMotionSample) {
1864#if DEBUG_BATCHING
1865 LOGD("channel '%s' ~ Preparing a new dispatch cycle for additional motion samples "
1866 "that cannot be streamed because the motion event has already been consumed.",
1867 connection->getInputChannelName());
1868#endif
1869 MotionSample* appendedMotionSample = static_cast<MotionEntry*>(eventEntry)->lastSample;
1870 dispatchEntry->headMotionSample = appendedMotionSample;
1871 }
1872
1873 // Enqueue the dispatch entry.
1874 connection->outboundQueue.enqueueAtTail(dispatchEntry);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001875}
1876
Jeff Brown7fbdc842010-06-17 20:52:56 -07001877void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Jeff Brown519e0242010-09-15 15:18:56 -07001878 const sp<Connection>& connection) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001879#if DEBUG_DISPATCH_CYCLE
1880 LOGD("channel '%s' ~ startDispatchCycle",
1881 connection->getInputChannelName());
1882#endif
1883
Jeff Brownb6110c22011-04-01 16:15:13 -07001884 LOG_ASSERT(connection->status == Connection::STATUS_NORMAL);
1885 LOG_ASSERT(! connection->outboundQueue.isEmpty());
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001886
Jeff Brownb88102f2010-09-08 11:49:43 -07001887 DispatchEntry* dispatchEntry = connection->outboundQueue.headSentinel.next;
Jeff Brownb6110c22011-04-01 16:15:13 -07001888 LOG_ASSERT(! dispatchEntry->inProgress);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001889
Jeff Brownb88102f2010-09-08 11:49:43 -07001890 // Mark the dispatch entry as in progress.
1891 dispatchEntry->inProgress = true;
1892
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001893 // Publish the event.
1894 status_t status;
Jeff Browna032cc02011-03-07 16:56:21 -08001895 EventEntry* eventEntry = dispatchEntry->eventEntry;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001896 switch (eventEntry->type) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001897 case EventEntry::TYPE_KEY: {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001898 KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001899
1900 // Apply target flags.
1901 int32_t action = keyEntry->action;
1902 int32_t flags = keyEntry->flags;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001903
Jeff Browna032cc02011-03-07 16:56:21 -08001904 // Update the connection's input state.
1905 connection->inputState.trackKey(keyEntry, action);
1906
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001907 // Publish the key event.
Jeff Brownc5ed5912010-07-14 18:48:53 -07001908 status = connection->inputPublisher.publishKeyEvent(keyEntry->deviceId, keyEntry->source,
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001909 action, flags, keyEntry->keyCode, keyEntry->scanCode,
1910 keyEntry->metaState, keyEntry->repeatCount, keyEntry->downTime,
1911 keyEntry->eventTime);
1912
1913 if (status) {
1914 LOGE("channel '%s' ~ Could not publish key event, "
1915 "status=%d", connection->getInputChannelName(), status);
Jeff Brownb6997262010-10-08 22:31:17 -07001916 abortBrokenDispatchCycleLocked(currentTime, connection);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001917 return;
1918 }
1919 break;
1920 }
1921
1922 case EventEntry::TYPE_MOTION: {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001923 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001924
1925 // Apply target flags.
1926 int32_t action = motionEntry->action;
Jeff Brown85a31762010-09-01 17:01:00 -07001927 int32_t flags = motionEntry->flags;
Jeff Browna032cc02011-03-07 16:56:21 -08001928 if (dispatchEntry->targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001929 action = AMOTION_EVENT_ACTION_OUTSIDE;
Jeff Browna032cc02011-03-07 16:56:21 -08001930 } else if (dispatchEntry->targetFlags & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
1931 action = AMOTION_EVENT_ACTION_HOVER_EXIT;
1932 } else if (dispatchEntry->targetFlags & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
1933 action = AMOTION_EVENT_ACTION_HOVER_ENTER;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001934 }
Jeff Brown85a31762010-09-01 17:01:00 -07001935 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
1936 flags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
1937 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001938
1939 // If headMotionSample is non-NULL, then it points to the first new sample that we
1940 // were unable to dispatch during the previous cycle so we resume dispatching from
1941 // that point in the list of motion samples.
1942 // Otherwise, we just start from the first sample of the motion event.
1943 MotionSample* firstMotionSample = dispatchEntry->headMotionSample;
1944 if (! firstMotionSample) {
1945 firstMotionSample = & motionEntry->firstSample;
1946 }
1947
Jeff Brownd3616592010-07-16 17:21:06 -07001948 // Set the X and Y offset depending on the input source.
1949 float xOffset, yOffset;
1950 if (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) {
1951 xOffset = dispatchEntry->xOffset;
1952 yOffset = dispatchEntry->yOffset;
1953 } else {
1954 xOffset = 0.0f;
1955 yOffset = 0.0f;
1956 }
1957
Jeff Browna032cc02011-03-07 16:56:21 -08001958 // Update the connection's input state.
1959 connection->inputState.trackMotion(motionEntry, action);
1960
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001961 // Publish the motion event and the first motion sample.
1962 status = connection->inputPublisher.publishMotionEvent(motionEntry->deviceId,
Jeff Brown85a31762010-09-01 17:01:00 -07001963 motionEntry->source, action, flags, motionEntry->edgeFlags, motionEntry->metaState,
Jeff Brownd3616592010-07-16 17:21:06 -07001964 xOffset, yOffset,
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001965 motionEntry->xPrecision, motionEntry->yPrecision,
1966 motionEntry->downTime, firstMotionSample->eventTime,
1967 motionEntry->pointerCount, motionEntry->pointerIds,
1968 firstMotionSample->pointerCoords);
1969
1970 if (status) {
1971 LOGE("channel '%s' ~ Could not publish motion event, "
1972 "status=%d", connection->getInputChannelName(), status);
Jeff Brownb6997262010-10-08 22:31:17 -07001973 abortBrokenDispatchCycleLocked(currentTime, connection);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001974 return;
1975 }
1976
Jeff Browna032cc02011-03-07 16:56:21 -08001977 if (action == AMOTION_EVENT_ACTION_MOVE
1978 || action == AMOTION_EVENT_ACTION_HOVER_MOVE) {
1979 // Append additional motion samples.
1980 MotionSample* nextMotionSample = firstMotionSample->next;
1981 for (; nextMotionSample != NULL; nextMotionSample = nextMotionSample->next) {
1982 status = connection->inputPublisher.appendMotionSample(
1983 nextMotionSample->eventTime, nextMotionSample->pointerCoords);
1984 if (status == NO_MEMORY) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001985#if DEBUG_DISPATCH_CYCLE
1986 LOGD("channel '%s' ~ Shared memory buffer full. Some motion samples will "
1987 "be sent in the next dispatch cycle.",
1988 connection->getInputChannelName());
1989#endif
Jeff Browna032cc02011-03-07 16:56:21 -08001990 break;
1991 }
1992 if (status != OK) {
1993 LOGE("channel '%s' ~ Could not append motion sample "
1994 "for a reason other than out of memory, status=%d",
1995 connection->getInputChannelName(), status);
1996 abortBrokenDispatchCycleLocked(currentTime, connection);
1997 return;
1998 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001999 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002000
Jeff Browna032cc02011-03-07 16:56:21 -08002001 // Remember the next motion sample that we could not dispatch, in case we ran out
2002 // of space in the shared memory buffer.
2003 dispatchEntry->tailMotionSample = nextMotionSample;
2004 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002005 break;
2006 }
2007
2008 default: {
Jeff Brownb6110c22011-04-01 16:15:13 -07002009 LOG_ASSERT(false);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002010 }
2011 }
2012
2013 // Send the dispatch signal.
2014 status = connection->inputPublisher.sendDispatchSignal();
2015 if (status) {
2016 LOGE("channel '%s' ~ Could not send dispatch signal, status=%d",
2017 connection->getInputChannelName(), status);
Jeff Brownb6997262010-10-08 22:31:17 -07002018 abortBrokenDispatchCycleLocked(currentTime, connection);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002019 return;
2020 }
2021
2022 // Record information about the newly started dispatch cycle.
Jeff Brown01ce2e92010-09-26 22:20:12 -07002023 connection->lastEventTime = eventEntry->eventTime;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002024 connection->lastDispatchTime = currentTime;
2025
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002026 // Notify other system components.
2027 onDispatchCycleStartedLocked(currentTime, connection);
2028}
2029
Jeff Brown7fbdc842010-06-17 20:52:56 -07002030void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Jeff Brown3915bb82010-11-05 15:02:16 -07002031 const sp<Connection>& connection, bool handled) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002032#if DEBUG_DISPATCH_CYCLE
Jeff Brown9c3cda02010-06-15 01:31:58 -07002033 LOGD("channel '%s' ~ finishDispatchCycle - %01.1fms since event, "
Jeff Brown3915bb82010-11-05 15:02:16 -07002034 "%01.1fms since dispatch, handled=%s",
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002035 connection->getInputChannelName(),
2036 connection->getEventLatencyMillis(currentTime),
Jeff Brown3915bb82010-11-05 15:02:16 -07002037 connection->getDispatchLatencyMillis(currentTime),
2038 toString(handled));
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002039#endif
2040
Jeff Brown9c3cda02010-06-15 01:31:58 -07002041 if (connection->status == Connection::STATUS_BROKEN
2042 || connection->status == Connection::STATUS_ZOMBIE) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002043 return;
2044 }
2045
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002046 // Reset the publisher since the event has been consumed.
2047 // We do this now so that the publisher can release some of its internal resources
2048 // while waiting for the next dispatch cycle to begin.
2049 status_t status = connection->inputPublisher.reset();
2050 if (status) {
2051 LOGE("channel '%s' ~ Could not reset publisher, status=%d",
2052 connection->getInputChannelName(), status);
Jeff Brownb6997262010-10-08 22:31:17 -07002053 abortBrokenDispatchCycleLocked(currentTime, connection);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002054 return;
2055 }
2056
Jeff Brown3915bb82010-11-05 15:02:16 -07002057 // Notify other system components and prepare to start the next dispatch cycle.
2058 onDispatchCycleFinishedLocked(currentTime, connection, handled);
Jeff Brownb88102f2010-09-08 11:49:43 -07002059}
2060
2061void InputDispatcher::startNextDispatchCycleLocked(nsecs_t currentTime,
2062 const sp<Connection>& connection) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002063 // Start the next dispatch cycle for this connection.
2064 while (! connection->outboundQueue.isEmpty()) {
Jeff Brownb88102f2010-09-08 11:49:43 -07002065 DispatchEntry* dispatchEntry = connection->outboundQueue.headSentinel.next;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002066 if (dispatchEntry->inProgress) {
2067 // Finish or resume current event in progress.
2068 if (dispatchEntry->tailMotionSample) {
2069 // We have a tail of undispatched motion samples.
2070 // Reuse the same DispatchEntry and start a new cycle.
2071 dispatchEntry->inProgress = false;
2072 dispatchEntry->headMotionSample = dispatchEntry->tailMotionSample;
2073 dispatchEntry->tailMotionSample = NULL;
Jeff Brown519e0242010-09-15 15:18:56 -07002074 startDispatchCycleLocked(currentTime, connection);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002075 return;
2076 }
2077 // Finished.
2078 connection->outboundQueue.dequeueAtHead();
Jeff Brown519e0242010-09-15 15:18:56 -07002079 if (dispatchEntry->hasForegroundTarget()) {
2080 decrementPendingForegroundDispatchesLocked(dispatchEntry->eventEntry);
Jeff Brown6ec402b2010-07-28 15:48:59 -07002081 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002082 mAllocator.releaseDispatchEntry(dispatchEntry);
2083 } else {
2084 // If the head is not in progress, then we must have already dequeued the in
Jeff Brown519e0242010-09-15 15:18:56 -07002085 // progress event, which means we actually aborted it.
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002086 // So just start the next event for this connection.
Jeff Brown519e0242010-09-15 15:18:56 -07002087 startDispatchCycleLocked(currentTime, connection);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002088 return;
2089 }
2090 }
2091
2092 // Outbound queue is empty, deactivate the connection.
Jeff Brown7fbdc842010-06-17 20:52:56 -07002093 deactivateConnectionLocked(connection.get());
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002094}
2095
Jeff Brownb6997262010-10-08 22:31:17 -07002096void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
2097 const sp<Connection>& connection) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002098#if DEBUG_DISPATCH_CYCLE
Jeff Brown83c09682010-12-23 17:50:18 -08002099 LOGD("channel '%s' ~ abortBrokenDispatchCycle",
2100 connection->getInputChannelName());
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002101#endif
2102
Jeff Brownb88102f2010-09-08 11:49:43 -07002103 // Clear the outbound queue.
Jeff Brown519e0242010-09-15 15:18:56 -07002104 drainOutboundQueueLocked(connection.get());
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002105
Jeff Brownb6997262010-10-08 22:31:17 -07002106 // The connection appears to be unrecoverably broken.
Jeff Brown9c3cda02010-06-15 01:31:58 -07002107 // Ignore already broken or zombie connections.
Jeff Brownb6997262010-10-08 22:31:17 -07002108 if (connection->status == Connection::STATUS_NORMAL) {
2109 connection->status = Connection::STATUS_BROKEN;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002110
Jeff Brownb6997262010-10-08 22:31:17 -07002111 // Notify other system components.
2112 onDispatchCycleBrokenLocked(currentTime, connection);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002113 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002114}
2115
Jeff Brown519e0242010-09-15 15:18:56 -07002116void InputDispatcher::drainOutboundQueueLocked(Connection* connection) {
2117 while (! connection->outboundQueue.isEmpty()) {
2118 DispatchEntry* dispatchEntry = connection->outboundQueue.dequeueAtHead();
2119 if (dispatchEntry->hasForegroundTarget()) {
2120 decrementPendingForegroundDispatchesLocked(dispatchEntry->eventEntry);
Jeff Brownb88102f2010-09-08 11:49:43 -07002121 }
2122 mAllocator.releaseDispatchEntry(dispatchEntry);
Jeff Brownb88102f2010-09-08 11:49:43 -07002123 }
2124
Jeff Brown519e0242010-09-15 15:18:56 -07002125 deactivateConnectionLocked(connection);
Jeff Brownb88102f2010-09-08 11:49:43 -07002126}
2127
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002128int InputDispatcher::handleReceiveCallback(int receiveFd, int events, void* data) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002129 InputDispatcher* d = static_cast<InputDispatcher*>(data);
2130
2131 { // acquire lock
2132 AutoMutex _l(d->mLock);
2133
2134 ssize_t connectionIndex = d->mConnectionsByReceiveFd.indexOfKey(receiveFd);
2135 if (connectionIndex < 0) {
2136 LOGE("Received spurious receive callback for unknown input channel. "
2137 "fd=%d, events=0x%x", receiveFd, events);
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002138 return 0; // remove the callback
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002139 }
2140
Jeff Brown7fbdc842010-06-17 20:52:56 -07002141 nsecs_t currentTime = now();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002142
2143 sp<Connection> connection = d->mConnectionsByReceiveFd.valueAt(connectionIndex);
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002144 if (events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP)) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002145 LOGE("channel '%s' ~ Consumer closed input channel or an error occurred. "
2146 "events=0x%x", connection->getInputChannelName(), events);
Jeff Brownb6997262010-10-08 22:31:17 -07002147 d->abortBrokenDispatchCycleLocked(currentTime, connection);
Jeff Brown9c3cda02010-06-15 01:31:58 -07002148 d->runCommandsLockedInterruptible();
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002149 return 0; // remove the callback
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002150 }
2151
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002152 if (! (events & ALOOPER_EVENT_INPUT)) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002153 LOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
2154 "events=0x%x", connection->getInputChannelName(), events);
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002155 return 1;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002156 }
2157
Jeff Brown3915bb82010-11-05 15:02:16 -07002158 bool handled = false;
Jeff Brown49ed71d2010-12-06 17:13:33 -08002159 status_t status = connection->inputPublisher.receiveFinishedSignal(&handled);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002160 if (status) {
2161 LOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
2162 connection->getInputChannelName(), status);
Jeff Brownb6997262010-10-08 22:31:17 -07002163 d->abortBrokenDispatchCycleLocked(currentTime, connection);
Jeff Brown9c3cda02010-06-15 01:31:58 -07002164 d->runCommandsLockedInterruptible();
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002165 return 0; // remove the callback
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002166 }
2167
Jeff Brown3915bb82010-11-05 15:02:16 -07002168 d->finishDispatchCycleLocked(currentTime, connection, handled);
Jeff Brown9c3cda02010-06-15 01:31:58 -07002169 d->runCommandsLockedInterruptible();
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002170 return 1;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002171 } // release lock
2172}
2173
Jeff Brownb6997262010-10-08 22:31:17 -07002174void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Jeff Brownda3d5a92011-03-29 15:11:34 -07002175 const CancelationOptions& options) {
Jeff Brownb6997262010-10-08 22:31:17 -07002176 for (size_t i = 0; i < mConnectionsByReceiveFd.size(); i++) {
2177 synthesizeCancelationEventsForConnectionLocked(
Jeff Brownda3d5a92011-03-29 15:11:34 -07002178 mConnectionsByReceiveFd.valueAt(i), options);
Jeff Brownb6997262010-10-08 22:31:17 -07002179 }
2180}
2181
2182void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Jeff Brownda3d5a92011-03-29 15:11:34 -07002183 const sp<InputChannel>& channel, const CancelationOptions& options) {
Jeff Brownb6997262010-10-08 22:31:17 -07002184 ssize_t index = getConnectionIndexLocked(channel);
2185 if (index >= 0) {
2186 synthesizeCancelationEventsForConnectionLocked(
Jeff Brownda3d5a92011-03-29 15:11:34 -07002187 mConnectionsByReceiveFd.valueAt(index), options);
Jeff Brownb6997262010-10-08 22:31:17 -07002188 }
2189}
2190
2191void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
Jeff Brownda3d5a92011-03-29 15:11:34 -07002192 const sp<Connection>& connection, const CancelationOptions& options) {
Jeff Brownb6997262010-10-08 22:31:17 -07002193 nsecs_t currentTime = now();
2194
2195 mTempCancelationEvents.clear();
2196 connection->inputState.synthesizeCancelationEvents(currentTime, & mAllocator,
2197 mTempCancelationEvents, options);
2198
2199 if (! mTempCancelationEvents.isEmpty()
2200 && connection->status != Connection::STATUS_BROKEN) {
2201#if DEBUG_OUTBOUND_EVENT_DETAILS
2202 LOGD("channel '%s' ~ Synthesized %d cancelation events to bring channel back in sync "
Jeff Brownda3d5a92011-03-29 15:11:34 -07002203 "with reality: %s, mode=%d.",
2204 connection->getInputChannelName(), mTempCancelationEvents.size(),
2205 options.reason, options.mode);
Jeff Brownb6997262010-10-08 22:31:17 -07002206#endif
2207 for (size_t i = 0; i < mTempCancelationEvents.size(); i++) {
2208 EventEntry* cancelationEventEntry = mTempCancelationEvents.itemAt(i);
2209 switch (cancelationEventEntry->type) {
2210 case EventEntry::TYPE_KEY:
2211 logOutboundKeyDetailsLocked("cancel - ",
2212 static_cast<KeyEntry*>(cancelationEventEntry));
2213 break;
2214 case EventEntry::TYPE_MOTION:
2215 logOutboundMotionDetailsLocked("cancel - ",
2216 static_cast<MotionEntry*>(cancelationEventEntry));
2217 break;
2218 }
2219
2220 int32_t xOffset, yOffset;
2221 const InputWindow* window = getWindowLocked(connection->inputChannel);
2222 if (window) {
2223 xOffset = -window->frameLeft;
2224 yOffset = -window->frameTop;
2225 } else {
2226 xOffset = 0;
2227 yOffset = 0;
2228 }
2229
2230 DispatchEntry* cancelationDispatchEntry =
2231 mAllocator.obtainDispatchEntry(cancelationEventEntry, // increments ref
2232 0, xOffset, yOffset);
2233 connection->outboundQueue.enqueueAtTail(cancelationDispatchEntry);
2234
2235 mAllocator.releaseEventEntry(cancelationEventEntry);
2236 }
2237
2238 if (!connection->outboundQueue.headSentinel.next->inProgress) {
2239 startDispatchCycleLocked(currentTime, connection);
2240 }
2241 }
2242}
2243
Jeff Brown01ce2e92010-09-26 22:20:12 -07002244InputDispatcher::MotionEntry*
2245InputDispatcher::splitMotionEvent(const MotionEntry* originalMotionEntry, BitSet32 pointerIds) {
Jeff Brownb6110c22011-04-01 16:15:13 -07002246 LOG_ASSERT(pointerIds.value != 0);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002247
2248 uint32_t splitPointerIndexMap[MAX_POINTERS];
2249 int32_t splitPointerIds[MAX_POINTERS];
2250 PointerCoords splitPointerCoords[MAX_POINTERS];
2251
2252 uint32_t originalPointerCount = originalMotionEntry->pointerCount;
2253 uint32_t splitPointerCount = 0;
2254
2255 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
2256 originalPointerIndex++) {
2257 int32_t pointerId = uint32_t(originalMotionEntry->pointerIds[originalPointerIndex]);
2258 if (pointerIds.hasBit(pointerId)) {
2259 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
2260 splitPointerIds[splitPointerCount] = pointerId;
Jeff Brownace13b12011-03-09 17:39:48 -08002261 splitPointerCoords[splitPointerCount].copyFrom(
2262 originalMotionEntry->firstSample.pointerCoords[originalPointerIndex]);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002263 splitPointerCount += 1;
2264 }
2265 }
Jeff Brown58a2da82011-01-25 16:02:22 -08002266
2267 if (splitPointerCount != pointerIds.count()) {
2268 // This is bad. We are missing some of the pointers that we expected to deliver.
2269 // Most likely this indicates that we received an ACTION_MOVE events that has
2270 // different pointer ids than we expected based on the previous ACTION_DOWN
2271 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
2272 // in this way.
2273 LOGW("Dropping split motion event because the pointer count is %d but "
2274 "we expected there to be %d pointers. This probably means we received "
2275 "a broken sequence of pointer ids from the input device.",
2276 splitPointerCount, pointerIds.count());
2277 return NULL;
2278 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07002279
2280 int32_t action = originalMotionEntry->action;
2281 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
2282 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
2283 || maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2284 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
2285 int32_t pointerId = originalMotionEntry->pointerIds[originalPointerIndex];
2286 if (pointerIds.hasBit(pointerId)) {
2287 if (pointerIds.count() == 1) {
2288 // The first/last pointer went down/up.
2289 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
2290 ? AMOTION_EVENT_ACTION_DOWN : AMOTION_EVENT_ACTION_UP;
Jeff Brown9a01d052010-09-27 16:35:11 -07002291 } else {
2292 // A secondary pointer went down/up.
2293 uint32_t splitPointerIndex = 0;
2294 while (pointerId != splitPointerIds[splitPointerIndex]) {
2295 splitPointerIndex += 1;
2296 }
2297 action = maskedAction | (splitPointerIndex
2298 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002299 }
2300 } else {
2301 // An unrelated pointer changed.
2302 action = AMOTION_EVENT_ACTION_MOVE;
2303 }
2304 }
2305
2306 MotionEntry* splitMotionEntry = mAllocator.obtainMotionEntry(
2307 originalMotionEntry->eventTime,
2308 originalMotionEntry->deviceId,
2309 originalMotionEntry->source,
2310 originalMotionEntry->policyFlags,
2311 action,
2312 originalMotionEntry->flags,
2313 originalMotionEntry->metaState,
2314 originalMotionEntry->edgeFlags,
2315 originalMotionEntry->xPrecision,
2316 originalMotionEntry->yPrecision,
2317 originalMotionEntry->downTime,
2318 splitPointerCount, splitPointerIds, splitPointerCoords);
2319
2320 for (MotionSample* originalMotionSample = originalMotionEntry->firstSample.next;
2321 originalMotionSample != NULL; originalMotionSample = originalMotionSample->next) {
2322 for (uint32_t splitPointerIndex = 0; splitPointerIndex < splitPointerCount;
2323 splitPointerIndex++) {
2324 uint32_t originalPointerIndex = splitPointerIndexMap[splitPointerIndex];
Jeff Brownace13b12011-03-09 17:39:48 -08002325 splitPointerCoords[splitPointerIndex].copyFrom(
2326 originalMotionSample->pointerCoords[originalPointerIndex]);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002327 }
2328
2329 mAllocator.appendMotionSample(splitMotionEntry, originalMotionSample->eventTime,
2330 splitPointerCoords);
2331 }
2332
Jeff Browna032cc02011-03-07 16:56:21 -08002333 if (originalMotionEntry->injectionState) {
2334 splitMotionEntry->injectionState = originalMotionEntry->injectionState;
2335 splitMotionEntry->injectionState->refCount += 1;
2336 }
2337
Jeff Brown01ce2e92010-09-26 22:20:12 -07002338 return splitMotionEntry;
2339}
2340
Jeff Brown9c3cda02010-06-15 01:31:58 -07002341void InputDispatcher::notifyConfigurationChanged(nsecs_t eventTime) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002342#if DEBUG_INBOUND_EVENT_DETAILS
Jeff Brown9c3cda02010-06-15 01:31:58 -07002343 LOGD("notifyConfigurationChanged - eventTime=%lld", eventTime);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002344#endif
2345
Jeff Brownb88102f2010-09-08 11:49:43 -07002346 bool needWake;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002347 { // acquire lock
2348 AutoMutex _l(mLock);
2349
Jeff Brown7fbdc842010-06-17 20:52:56 -07002350 ConfigurationChangedEntry* newEntry = mAllocator.obtainConfigurationChangedEntry(eventTime);
Jeff Brownb88102f2010-09-08 11:49:43 -07002351 needWake = enqueueInboundEventLocked(newEntry);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002352 } // release lock
2353
Jeff Brownb88102f2010-09-08 11:49:43 -07002354 if (needWake) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002355 mLooper->wake();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002356 }
2357}
2358
Jeff Brown58a2da82011-01-25 16:02:22 -08002359void InputDispatcher::notifyKey(nsecs_t eventTime, int32_t deviceId, uint32_t source,
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002360 uint32_t policyFlags, int32_t action, int32_t flags,
2361 int32_t keyCode, int32_t scanCode, int32_t metaState, nsecs_t downTime) {
2362#if DEBUG_INBOUND_EVENT_DETAILS
Jeff Brown90655042010-12-02 13:50:46 -08002363 LOGD("notifyKey - eventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, action=0x%x, "
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002364 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%lld",
Jeff Brownc5ed5912010-07-14 18:48:53 -07002365 eventTime, deviceId, source, policyFlags, action, flags,
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002366 keyCode, scanCode, metaState, downTime);
2367#endif
Jeff Brown01ce2e92010-09-26 22:20:12 -07002368 if (! validateKeyEvent(action)) {
2369 return;
2370 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002371
Jeff Brown1f245102010-11-18 20:53:46 -08002372 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
2373 policyFlags |= POLICY_FLAG_VIRTUAL;
2374 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
2375 }
Jeff Brown924c4d42011-03-07 16:40:47 -08002376 if (policyFlags & POLICY_FLAG_ALT) {
2377 metaState |= AMETA_ALT_ON | AMETA_ALT_LEFT_ON;
2378 }
2379 if (policyFlags & POLICY_FLAG_ALT_GR) {
2380 metaState |= AMETA_ALT_ON | AMETA_ALT_RIGHT_ON;
2381 }
2382 if (policyFlags & POLICY_FLAG_SHIFT) {
2383 metaState |= AMETA_SHIFT_ON | AMETA_SHIFT_LEFT_ON;
2384 }
2385 if (policyFlags & POLICY_FLAG_CAPS_LOCK) {
2386 metaState |= AMETA_CAPS_LOCK_ON;
2387 }
2388 if (policyFlags & POLICY_FLAG_FUNCTION) {
2389 metaState |= AMETA_FUNCTION_ON;
2390 }
Jeff Brown1f245102010-11-18 20:53:46 -08002391
Jeff Browne20c9e02010-10-11 14:20:19 -07002392 policyFlags |= POLICY_FLAG_TRUSTED;
Jeff Brown1f245102010-11-18 20:53:46 -08002393
2394 KeyEvent event;
2395 event.initialize(deviceId, source, action, flags, keyCode, scanCode,
2396 metaState, 0, downTime, eventTime);
2397
2398 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
2399
2400 if (policyFlags & POLICY_FLAG_WOKE_HERE) {
2401 flags |= AKEY_EVENT_FLAG_WOKE_HERE;
2402 }
Jeff Brownb6997262010-10-08 22:31:17 -07002403
Jeff Brownb88102f2010-09-08 11:49:43 -07002404 bool needWake;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002405 { // acquire lock
Jeff Brown0029c662011-03-30 02:25:18 -07002406 mLock.lock();
2407
2408 if (mInputFilterEnabled) {
2409 mLock.unlock();
2410
2411 policyFlags |= POLICY_FLAG_FILTERED;
2412 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2413 return; // event was consumed by the filter
2414 }
2415
2416 mLock.lock();
2417 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002418
Jeff Brown7fbdc842010-06-17 20:52:56 -07002419 int32_t repeatCount = 0;
2420 KeyEntry* newEntry = mAllocator.obtainKeyEntry(eventTime,
Jeff Brownc5ed5912010-07-14 18:48:53 -07002421 deviceId, source, policyFlags, action, flags, keyCode, scanCode,
Jeff Brown7fbdc842010-06-17 20:52:56 -07002422 metaState, repeatCount, downTime);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002423
Jeff Brownb88102f2010-09-08 11:49:43 -07002424 needWake = enqueueInboundEventLocked(newEntry);
Jeff Brown0029c662011-03-30 02:25:18 -07002425 mLock.unlock();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002426 } // release lock
2427
Jeff Brownb88102f2010-09-08 11:49:43 -07002428 if (needWake) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002429 mLooper->wake();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002430 }
2431}
2432
Jeff Brown58a2da82011-01-25 16:02:22 -08002433void InputDispatcher::notifyMotion(nsecs_t eventTime, int32_t deviceId, uint32_t source,
Jeff Brown85a31762010-09-01 17:01:00 -07002434 uint32_t policyFlags, int32_t action, int32_t flags, int32_t metaState, int32_t edgeFlags,
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002435 uint32_t pointerCount, const int32_t* pointerIds, const PointerCoords* pointerCoords,
2436 float xPrecision, float yPrecision, nsecs_t downTime) {
2437#if DEBUG_INBOUND_EVENT_DETAILS
Jeff Brown90655042010-12-02 13:50:46 -08002438 LOGD("notifyMotion - eventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, "
Jeff Brown85a31762010-09-01 17:01:00 -07002439 "action=0x%x, flags=0x%x, metaState=0x%x, edgeFlags=0x%x, "
2440 "xPrecision=%f, yPrecision=%f, downTime=%lld",
2441 eventTime, deviceId, source, policyFlags, action, flags, metaState, edgeFlags,
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002442 xPrecision, yPrecision, downTime);
2443 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brown8d608662010-08-30 03:02:23 -07002444 LOGD(" Pointer %d: id=%d, x=%f, y=%f, pressure=%f, size=%f, "
Jeff Brown85a31762010-09-01 17:01:00 -07002445 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
Jeff Brown8d608662010-08-30 03:02:23 -07002446 "orientation=%f",
Jeff Brown91c69ab2011-02-14 17:03:18 -08002447 i, pointerIds[i],
Jeff Brownebbd5d12011-02-17 13:01:34 -08002448 pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
2449 pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
2450 pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
2451 pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
2452 pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
2453 pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
2454 pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
2455 pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
2456 pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002457 }
2458#endif
Jeff Brown01ce2e92010-09-26 22:20:12 -07002459 if (! validateMotionEvent(action, pointerCount, pointerIds)) {
2460 return;
2461 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002462
Jeff Browne20c9e02010-10-11 14:20:19 -07002463 policyFlags |= POLICY_FLAG_TRUSTED;
Jeff Brown56194eb2011-03-02 19:23:13 -08002464 mPolicy->interceptMotionBeforeQueueing(eventTime, /*byref*/ policyFlags);
Jeff Brownb6997262010-10-08 22:31:17 -07002465
Jeff Brownb88102f2010-09-08 11:49:43 -07002466 bool needWake;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002467 { // acquire lock
Jeff Brown0029c662011-03-30 02:25:18 -07002468 mLock.lock();
2469
2470 if (mInputFilterEnabled) {
2471 mLock.unlock();
2472
2473 MotionEvent event;
2474 event.initialize(deviceId, source, action, flags, edgeFlags, metaState, 0, 0,
2475 xPrecision, yPrecision, downTime, eventTime,
2476 pointerCount, pointerIds, pointerCoords);
2477
2478 policyFlags |= POLICY_FLAG_FILTERED;
2479 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2480 return; // event was consumed by the filter
2481 }
2482
2483 mLock.lock();
2484 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002485
2486 // Attempt batching and streaming of move events.
Jeff Browncc0c1592011-02-19 05:07:28 -08002487 if (action == AMOTION_EVENT_ACTION_MOVE
2488 || action == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002489 // BATCHING CASE
2490 //
2491 // Try to append a move sample to the tail of the inbound queue for this device.
2492 // Give up if we encounter a non-move motion event for this device since that
2493 // means we cannot append any new samples until a new motion event has started.
Jeff Brownb88102f2010-09-08 11:49:43 -07002494 for (EventEntry* entry = mInboundQueue.tailSentinel.prev;
2495 entry != & mInboundQueue.headSentinel; entry = entry->prev) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002496 if (entry->type != EventEntry::TYPE_MOTION) {
2497 // Keep looking for motion events.
2498 continue;
2499 }
2500
2501 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
Jeff Brownefd32662011-03-08 15:13:06 -08002502 if (motionEntry->deviceId != deviceId
2503 || motionEntry->source != source) {
2504 // Keep looking for this device and source.
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002505 continue;
2506 }
2507
Jeff Browncc0c1592011-02-19 05:07:28 -08002508 if (motionEntry->action != action
Jeff Brown7fbdc842010-06-17 20:52:56 -07002509 || motionEntry->pointerCount != pointerCount
2510 || motionEntry->isInjected()) {
Jeff Brownefd32662011-03-08 15:13:06 -08002511 // Last motion event in the queue for this device and source is
2512 // not compatible for appending new samples. Stop here.
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002513 goto NoBatchingOrStreaming;
2514 }
2515
2516 // The last motion event is a move and is compatible for appending.
Jeff Brown9c3cda02010-06-15 01:31:58 -07002517 // Do the batching magic.
Jeff Brown7fbdc842010-06-17 20:52:56 -07002518 mAllocator.appendMotionSample(motionEntry, eventTime, pointerCoords);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002519#if DEBUG_BATCHING
2520 LOGD("Appended motion sample onto batch for most recent "
2521 "motion event for this device in the inbound queue.");
2522#endif
Jeff Brown0029c662011-03-30 02:25:18 -07002523 mLock.unlock();
Jeff Brown9c3cda02010-06-15 01:31:58 -07002524 return; // done!
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002525 }
2526
Jeff Brownf6989da2011-04-06 17:19:48 -07002527 // BATCHING ONTO PENDING EVENT CASE
2528 //
2529 // Try to append a move sample to the currently pending event, if there is one.
2530 // We can do this as long as we are still waiting to find the targets for the
2531 // event. Once the targets are locked-in we can only do streaming.
2532 if (mPendingEvent
2533 && (!mPendingEvent->dispatchInProgress || !mCurrentInputTargetsValid)
2534 && mPendingEvent->type == EventEntry::TYPE_MOTION) {
2535 MotionEntry* motionEntry = static_cast<MotionEntry*>(mPendingEvent);
2536 if (motionEntry->deviceId == deviceId && motionEntry->source == source) {
2537 if (motionEntry->action != action
2538 || motionEntry->pointerCount != pointerCount
2539 || motionEntry->isInjected()) {
2540 // Pending event is not compatible for appending new samples. Stop here.
2541 goto NoBatchingOrStreaming;
2542 }
2543
2544 // The pending motion event is a move and is compatible for appending.
2545 // Do the batching magic.
2546 mAllocator.appendMotionSample(motionEntry, eventTime, pointerCoords);
2547#if DEBUG_BATCHING
2548 LOGD("Appended motion sample onto batch for the pending motion event.");
2549#endif
2550 mLock.unlock();
2551 return; // done!
2552 }
2553 }
2554
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002555 // STREAMING CASE
2556 //
2557 // There is no pending motion event (of any kind) for this device in the inbound queue.
Jeff Brown519e0242010-09-15 15:18:56 -07002558 // Search the outbound queue for the current foreground targets to find a dispatched
2559 // motion event that is still in progress. If found, then, appen the new sample to
2560 // that event and push it out to all current targets. The logic in
2561 // prepareDispatchCycleLocked takes care of the case where some targets may
2562 // already have consumed the motion event by starting a new dispatch cycle if needed.
Jeff Brown9c3cda02010-06-15 01:31:58 -07002563 if (mCurrentInputTargetsValid) {
Jeff Brown519e0242010-09-15 15:18:56 -07002564 for (size_t i = 0; i < mCurrentInputTargets.size(); i++) {
2565 const InputTarget& inputTarget = mCurrentInputTargets[i];
2566 if ((inputTarget.flags & InputTarget::FLAG_FOREGROUND) == 0) {
2567 // Skip non-foreground targets. We only want to stream if there is at
2568 // least one foreground target whose dispatch is still in progress.
2569 continue;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002570 }
Jeff Brown519e0242010-09-15 15:18:56 -07002571
2572 ssize_t connectionIndex = getConnectionIndexLocked(inputTarget.inputChannel);
2573 if (connectionIndex < 0) {
2574 // Connection must no longer be valid.
2575 continue;
2576 }
2577
2578 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
2579 if (connection->outboundQueue.isEmpty()) {
2580 // This foreground target has an empty outbound queue.
2581 continue;
2582 }
2583
2584 DispatchEntry* dispatchEntry = connection->outboundQueue.headSentinel.next;
2585 if (! dispatchEntry->inProgress
Jeff Brown01ce2e92010-09-26 22:20:12 -07002586 || dispatchEntry->eventEntry->type != EventEntry::TYPE_MOTION
2587 || dispatchEntry->isSplit()) {
2588 // No motion event is being dispatched, or it is being split across
2589 // windows in which case we cannot stream.
Jeff Brown519e0242010-09-15 15:18:56 -07002590 continue;
2591 }
2592
2593 MotionEntry* motionEntry = static_cast<MotionEntry*>(
2594 dispatchEntry->eventEntry);
Jeff Browncc0c1592011-02-19 05:07:28 -08002595 if (motionEntry->action != action
Jeff Brown519e0242010-09-15 15:18:56 -07002596 || motionEntry->deviceId != deviceId
Jeff Brown58a2da82011-01-25 16:02:22 -08002597 || motionEntry->source != source
Jeff Brown519e0242010-09-15 15:18:56 -07002598 || motionEntry->pointerCount != pointerCount
2599 || motionEntry->isInjected()) {
2600 // The motion event is not compatible with this move.
2601 continue;
2602 }
2603
Jeff Browna032cc02011-03-07 16:56:21 -08002604 if (action == AMOTION_EVENT_ACTION_HOVER_MOVE) {
2605 if (!mLastHoverWindow) {
2606#if DEBUG_BATCHING
2607 LOGD("Not streaming hover move because there is no "
2608 "last hovered window.");
2609#endif
2610 goto NoBatchingOrStreaming;
2611 }
2612
2613 const InputWindow* hoverWindow = findTouchedWindowAtLocked(
2614 pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X),
2615 pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
2616 if (mLastHoverWindow != hoverWindow) {
2617#if DEBUG_BATCHING
2618 LOGD("Not streaming hover move because the last hovered window "
2619 "is '%s' but the currently hovered window is '%s'.",
2620 mLastHoverWindow->name.string(),
2621 hoverWindow ? hoverWindow->name.string() : "<null>");
2622#endif
2623 goto NoBatchingOrStreaming;
2624 }
2625 }
2626
Jeff Brown519e0242010-09-15 15:18:56 -07002627 // Hurray! This foreground target is currently dispatching a move event
2628 // that we can stream onto. Append the motion sample and resume dispatch.
2629 mAllocator.appendMotionSample(motionEntry, eventTime, pointerCoords);
2630#if DEBUG_BATCHING
2631 LOGD("Appended motion sample onto batch for most recently dispatched "
2632 "motion event for this device in the outbound queues. "
2633 "Attempting to stream the motion sample.");
2634#endif
2635 nsecs_t currentTime = now();
2636 dispatchEventToCurrentInputTargetsLocked(currentTime, motionEntry,
2637 true /*resumeWithAppendedMotionSample*/);
2638
2639 runCommandsLockedInterruptible();
Jeff Brown0029c662011-03-30 02:25:18 -07002640 mLock.unlock();
Jeff Brown519e0242010-09-15 15:18:56 -07002641 return; // done!
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002642 }
2643 }
2644
2645NoBatchingOrStreaming:;
2646 }
2647
2648 // Just enqueue a new motion event.
Jeff Brown7fbdc842010-06-17 20:52:56 -07002649 MotionEntry* newEntry = mAllocator.obtainMotionEntry(eventTime,
Jeff Brown85a31762010-09-01 17:01:00 -07002650 deviceId, source, policyFlags, action, flags, metaState, edgeFlags,
Jeff Brown7fbdc842010-06-17 20:52:56 -07002651 xPrecision, yPrecision, downTime,
2652 pointerCount, pointerIds, pointerCoords);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002653
Jeff Brownb88102f2010-09-08 11:49:43 -07002654 needWake = enqueueInboundEventLocked(newEntry);
Jeff Brown0029c662011-03-30 02:25:18 -07002655 mLock.unlock();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002656 } // release lock
2657
Jeff Brownb88102f2010-09-08 11:49:43 -07002658 if (needWake) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002659 mLooper->wake();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002660 }
2661}
2662
Jeff Brownb6997262010-10-08 22:31:17 -07002663void InputDispatcher::notifySwitch(nsecs_t when, int32_t switchCode, int32_t switchValue,
2664 uint32_t policyFlags) {
2665#if DEBUG_INBOUND_EVENT_DETAILS
2666 LOGD("notifySwitch - switchCode=%d, switchValue=%d, policyFlags=0x%x",
2667 switchCode, switchValue, policyFlags);
2668#endif
2669
Jeff Browne20c9e02010-10-11 14:20:19 -07002670 policyFlags |= POLICY_FLAG_TRUSTED;
Jeff Brownb6997262010-10-08 22:31:17 -07002671 mPolicy->notifySwitch(when, switchCode, switchValue, policyFlags);
2672}
2673
Jeff Brown7fbdc842010-06-17 20:52:56 -07002674int32_t InputDispatcher::injectInputEvent(const InputEvent* event,
Jeff Brown0029c662011-03-30 02:25:18 -07002675 int32_t injectorPid, int32_t injectorUid, int32_t syncMode, int32_t timeoutMillis,
2676 uint32_t policyFlags) {
Jeff Brown7fbdc842010-06-17 20:52:56 -07002677#if DEBUG_INBOUND_EVENT_DETAILS
2678 LOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Jeff Brown0029c662011-03-30 02:25:18 -07002679 "syncMode=%d, timeoutMillis=%d, policyFlags=0x%08x",
2680 event->getType(), injectorPid, injectorUid, syncMode, timeoutMillis, policyFlags);
Jeff Brown7fbdc842010-06-17 20:52:56 -07002681#endif
2682
2683 nsecs_t endTime = now() + milliseconds_to_nanoseconds(timeoutMillis);
Jeff Browne20c9e02010-10-11 14:20:19 -07002684
Jeff Brown0029c662011-03-30 02:25:18 -07002685 policyFlags |= POLICY_FLAG_INJECTED;
Jeff Browne20c9e02010-10-11 14:20:19 -07002686 if (hasInjectionPermission(injectorPid, injectorUid)) {
2687 policyFlags |= POLICY_FLAG_TRUSTED;
2688 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07002689
Jeff Brownb6997262010-10-08 22:31:17 -07002690 EventEntry* injectedEntry;
2691 switch (event->getType()) {
2692 case AINPUT_EVENT_TYPE_KEY: {
2693 const KeyEvent* keyEvent = static_cast<const KeyEvent*>(event);
2694 int32_t action = keyEvent->getAction();
2695 if (! validateKeyEvent(action)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07002696 return INPUT_EVENT_INJECTION_FAILED;
2697 }
2698
Jeff Brownb6997262010-10-08 22:31:17 -07002699 int32_t flags = keyEvent->getFlags();
Jeff Brown1f245102010-11-18 20:53:46 -08002700 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
2701 policyFlags |= POLICY_FLAG_VIRTUAL;
2702 }
2703
Jeff Brown0029c662011-03-30 02:25:18 -07002704 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
2705 mPolicy->interceptKeyBeforeQueueing(keyEvent, /*byref*/ policyFlags);
2706 }
Jeff Brown1f245102010-11-18 20:53:46 -08002707
2708 if (policyFlags & POLICY_FLAG_WOKE_HERE) {
2709 flags |= AKEY_EVENT_FLAG_WOKE_HERE;
2710 }
Jeff Brown6ec402b2010-07-28 15:48:59 -07002711
Jeff Brownb6997262010-10-08 22:31:17 -07002712 mLock.lock();
Jeff Brown1f245102010-11-18 20:53:46 -08002713 injectedEntry = mAllocator.obtainKeyEntry(keyEvent->getEventTime(),
2714 keyEvent->getDeviceId(), keyEvent->getSource(),
2715 policyFlags, action, flags,
2716 keyEvent->getKeyCode(), keyEvent->getScanCode(), keyEvent->getMetaState(),
Jeff Brownb6997262010-10-08 22:31:17 -07002717 keyEvent->getRepeatCount(), keyEvent->getDownTime());
2718 break;
2719 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07002720
Jeff Brownb6997262010-10-08 22:31:17 -07002721 case AINPUT_EVENT_TYPE_MOTION: {
2722 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
2723 int32_t action = motionEvent->getAction();
2724 size_t pointerCount = motionEvent->getPointerCount();
2725 const int32_t* pointerIds = motionEvent->getPointerIds();
2726 if (! validateMotionEvent(action, pointerCount, pointerIds)) {
2727 return INPUT_EVENT_INJECTION_FAILED;
2728 }
2729
Jeff Brown0029c662011-03-30 02:25:18 -07002730 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
2731 nsecs_t eventTime = motionEvent->getEventTime();
2732 mPolicy->interceptMotionBeforeQueueing(eventTime, /*byref*/ policyFlags);
2733 }
Jeff Brownb6997262010-10-08 22:31:17 -07002734
2735 mLock.lock();
2736 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
2737 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
2738 MotionEntry* motionEntry = mAllocator.obtainMotionEntry(*sampleEventTimes,
2739 motionEvent->getDeviceId(), motionEvent->getSource(), policyFlags,
2740 action, motionEvent->getFlags(),
2741 motionEvent->getMetaState(), motionEvent->getEdgeFlags(),
2742 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
2743 motionEvent->getDownTime(), uint32_t(pointerCount),
2744 pointerIds, samplePointerCoords);
2745 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
2746 sampleEventTimes += 1;
2747 samplePointerCoords += pointerCount;
2748 mAllocator.appendMotionSample(motionEntry, *sampleEventTimes, samplePointerCoords);
2749 }
2750 injectedEntry = motionEntry;
2751 break;
2752 }
2753
2754 default:
2755 LOGW("Cannot inject event of type %d", event->getType());
2756 return INPUT_EVENT_INJECTION_FAILED;
2757 }
2758
2759 InjectionState* injectionState = mAllocator.obtainInjectionState(injectorPid, injectorUid);
2760 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
2761 injectionState->injectionIsAsync = true;
2762 }
2763
2764 injectionState->refCount += 1;
2765 injectedEntry->injectionState = injectionState;
2766
2767 bool needWake = enqueueInboundEventLocked(injectedEntry);
2768 mLock.unlock();
Jeff Brown7fbdc842010-06-17 20:52:56 -07002769
Jeff Brownb88102f2010-09-08 11:49:43 -07002770 if (needWake) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002771 mLooper->wake();
Jeff Brown7fbdc842010-06-17 20:52:56 -07002772 }
2773
2774 int32_t injectionResult;
2775 { // acquire lock
2776 AutoMutex _l(mLock);
2777
Jeff Brown6ec402b2010-07-28 15:48:59 -07002778 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
2779 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
2780 } else {
2781 for (;;) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002782 injectionResult = injectionState->injectionResult;
Jeff Brown6ec402b2010-07-28 15:48:59 -07002783 if (injectionResult != INPUT_EVENT_INJECTION_PENDING) {
2784 break;
2785 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07002786
Jeff Brown7fbdc842010-06-17 20:52:56 -07002787 nsecs_t remainingTimeout = endTime - now();
2788 if (remainingTimeout <= 0) {
Jeff Brown6ec402b2010-07-28 15:48:59 -07002789#if DEBUG_INJECTION
2790 LOGD("injectInputEvent - Timed out waiting for injection result "
2791 "to become available.");
2792#endif
Jeff Brown7fbdc842010-06-17 20:52:56 -07002793 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
2794 break;
2795 }
2796
Jeff Brown6ec402b2010-07-28 15:48:59 -07002797 mInjectionResultAvailableCondition.waitRelative(mLock, remainingTimeout);
2798 }
2799
2800 if (injectionResult == INPUT_EVENT_INJECTION_SUCCEEDED
2801 && syncMode == INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002802 while (injectionState->pendingForegroundDispatches != 0) {
Jeff Brown6ec402b2010-07-28 15:48:59 -07002803#if DEBUG_INJECTION
Jeff Brown519e0242010-09-15 15:18:56 -07002804 LOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
Jeff Brown01ce2e92010-09-26 22:20:12 -07002805 injectionState->pendingForegroundDispatches);
Jeff Brown6ec402b2010-07-28 15:48:59 -07002806#endif
2807 nsecs_t remainingTimeout = endTime - now();
2808 if (remainingTimeout <= 0) {
2809#if DEBUG_INJECTION
Jeff Brown519e0242010-09-15 15:18:56 -07002810 LOGD("injectInputEvent - Timed out waiting for pending foreground "
Jeff Brown6ec402b2010-07-28 15:48:59 -07002811 "dispatches to finish.");
2812#endif
2813 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
2814 break;
2815 }
2816
2817 mInjectionSyncFinishedCondition.waitRelative(mLock, remainingTimeout);
2818 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07002819 }
2820 }
2821
Jeff Brown01ce2e92010-09-26 22:20:12 -07002822 mAllocator.releaseInjectionState(injectionState);
Jeff Brown7fbdc842010-06-17 20:52:56 -07002823 } // release lock
2824
Jeff Brown6ec402b2010-07-28 15:48:59 -07002825#if DEBUG_INJECTION
2826 LOGD("injectInputEvent - Finished with result %d. "
2827 "injectorPid=%d, injectorUid=%d",
2828 injectionResult, injectorPid, injectorUid);
2829#endif
2830
Jeff Brown7fbdc842010-06-17 20:52:56 -07002831 return injectionResult;
2832}
2833
Jeff Brownb6997262010-10-08 22:31:17 -07002834bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
2835 return injectorUid == 0
2836 || mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
2837}
2838
Jeff Brown7fbdc842010-06-17 20:52:56 -07002839void InputDispatcher::setInjectionResultLocked(EventEntry* entry, int32_t injectionResult) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002840 InjectionState* injectionState = entry->injectionState;
2841 if (injectionState) {
Jeff Brown7fbdc842010-06-17 20:52:56 -07002842#if DEBUG_INJECTION
2843 LOGD("Setting input event injection result to %d. "
2844 "injectorPid=%d, injectorUid=%d",
Jeff Brown01ce2e92010-09-26 22:20:12 -07002845 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
Jeff Brown7fbdc842010-06-17 20:52:56 -07002846#endif
2847
Jeff Brown0029c662011-03-30 02:25:18 -07002848 if (injectionState->injectionIsAsync
2849 && !(entry->policyFlags & POLICY_FLAG_FILTERED)) {
Jeff Brown6ec402b2010-07-28 15:48:59 -07002850 // Log the outcome since the injector did not wait for the injection result.
2851 switch (injectionResult) {
2852 case INPUT_EVENT_INJECTION_SUCCEEDED:
2853 LOGV("Asynchronous input event injection succeeded.");
2854 break;
2855 case INPUT_EVENT_INJECTION_FAILED:
2856 LOGW("Asynchronous input event injection failed.");
2857 break;
2858 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
2859 LOGW("Asynchronous input event injection permission denied.");
2860 break;
2861 case INPUT_EVENT_INJECTION_TIMED_OUT:
2862 LOGW("Asynchronous input event injection timed out.");
2863 break;
2864 }
2865 }
2866
Jeff Brown01ce2e92010-09-26 22:20:12 -07002867 injectionState->injectionResult = injectionResult;
Jeff Brown7fbdc842010-06-17 20:52:56 -07002868 mInjectionResultAvailableCondition.broadcast();
2869 }
2870}
2871
Jeff Brown01ce2e92010-09-26 22:20:12 -07002872void InputDispatcher::incrementPendingForegroundDispatchesLocked(EventEntry* entry) {
2873 InjectionState* injectionState = entry->injectionState;
2874 if (injectionState) {
2875 injectionState->pendingForegroundDispatches += 1;
2876 }
2877}
2878
Jeff Brown519e0242010-09-15 15:18:56 -07002879void InputDispatcher::decrementPendingForegroundDispatchesLocked(EventEntry* entry) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002880 InjectionState* injectionState = entry->injectionState;
2881 if (injectionState) {
2882 injectionState->pendingForegroundDispatches -= 1;
Jeff Brown6ec402b2010-07-28 15:48:59 -07002883
Jeff Brown01ce2e92010-09-26 22:20:12 -07002884 if (injectionState->pendingForegroundDispatches == 0) {
2885 mInjectionSyncFinishedCondition.broadcast();
2886 }
Jeff Brownb88102f2010-09-08 11:49:43 -07002887 }
2888}
2889
Jeff Brown01ce2e92010-09-26 22:20:12 -07002890const InputWindow* InputDispatcher::getWindowLocked(const sp<InputChannel>& inputChannel) {
2891 for (size_t i = 0; i < mWindows.size(); i++) {
2892 const InputWindow* window = & mWindows[i];
2893 if (window->inputChannel == inputChannel) {
2894 return window;
2895 }
2896 }
2897 return NULL;
2898}
2899
Jeff Brownb88102f2010-09-08 11:49:43 -07002900void InputDispatcher::setInputWindows(const Vector<InputWindow>& inputWindows) {
2901#if DEBUG_FOCUS
2902 LOGD("setInputWindows");
2903#endif
2904 { // acquire lock
2905 AutoMutex _l(mLock);
2906
Jeff Brown01ce2e92010-09-26 22:20:12 -07002907 // Clear old window pointers.
Jeff Brownb6997262010-10-08 22:31:17 -07002908 sp<InputChannel> oldFocusedWindowChannel;
2909 if (mFocusedWindow) {
2910 oldFocusedWindowChannel = mFocusedWindow->inputChannel;
2911 mFocusedWindow = NULL;
2912 }
Jeff Browna032cc02011-03-07 16:56:21 -08002913 sp<InputChannel> oldLastHoverWindowChannel;
2914 if (mLastHoverWindow) {
2915 oldLastHoverWindowChannel = mLastHoverWindow->inputChannel;
2916 mLastHoverWindow = NULL;
2917 }
Jeff Brownb6997262010-10-08 22:31:17 -07002918
Jeff Brownb88102f2010-09-08 11:49:43 -07002919 mWindows.clear();
Jeff Brown2a95c2a2010-09-16 12:31:46 -07002920
2921 // Loop over new windows and rebuild the necessary window pointers for
2922 // tracking focus and touch.
Jeff Brownb88102f2010-09-08 11:49:43 -07002923 mWindows.appendVector(inputWindows);
2924
2925 size_t numWindows = mWindows.size();
2926 for (size_t i = 0; i < numWindows; i++) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002927 const InputWindow* window = & mWindows.itemAt(i);
Jeff Brownb88102f2010-09-08 11:49:43 -07002928 if (window->hasFocus) {
2929 mFocusedWindow = window;
Jeff Brown01ce2e92010-09-26 22:20:12 -07002930 break;
Jeff Brownb88102f2010-09-08 11:49:43 -07002931 }
2932 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07002933
Jeff Brownb6997262010-10-08 22:31:17 -07002934 if (oldFocusedWindowChannel != NULL) {
2935 if (!mFocusedWindow || oldFocusedWindowChannel != mFocusedWindow->inputChannel) {
2936#if DEBUG_FOCUS
2937 LOGD("Focus left window: %s",
2938 oldFocusedWindowChannel->getName().string());
2939#endif
Jeff Brownda3d5a92011-03-29 15:11:34 -07002940 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
2941 "focus left window");
2942 synthesizeCancelationEventsForInputChannelLocked(oldFocusedWindowChannel, options);
Jeff Brownb6997262010-10-08 22:31:17 -07002943 oldFocusedWindowChannel.clear();
2944 }
2945 }
2946 if (mFocusedWindow && oldFocusedWindowChannel == NULL) {
2947#if DEBUG_FOCUS
2948 LOGD("Focus entered window: %s",
2949 mFocusedWindow->inputChannel->getName().string());
2950#endif
2951 }
2952
Jeff Brown01ce2e92010-09-26 22:20:12 -07002953 for (size_t i = 0; i < mTouchState.windows.size(); ) {
2954 TouchedWindow& touchedWindow = mTouchState.windows.editItemAt(i);
2955 const InputWindow* window = getWindowLocked(touchedWindow.channel);
2956 if (window) {
2957 touchedWindow.window = window;
2958 i += 1;
2959 } else {
Jeff Brownb6997262010-10-08 22:31:17 -07002960#if DEBUG_FOCUS
2961 LOGD("Touched window was removed: %s", touchedWindow.channel->getName().string());
2962#endif
Jeff Brownda3d5a92011-03-29 15:11:34 -07002963 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
2964 "touched window was removed");
2965 synthesizeCancelationEventsForInputChannelLocked(touchedWindow.channel, options);
Jeff Brownaf48cae2010-10-15 16:20:51 -07002966 mTouchState.windows.removeAt(i);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002967 }
2968 }
Jeff Brownb88102f2010-09-08 11:49:43 -07002969
Jeff Browna032cc02011-03-07 16:56:21 -08002970 // Recover the last hovered window.
2971 if (oldLastHoverWindowChannel != NULL) {
2972 mLastHoverWindow = getWindowLocked(oldLastHoverWindowChannel);
2973 oldLastHoverWindowChannel.clear();
2974 }
2975
Jeff Brownb88102f2010-09-08 11:49:43 -07002976#if DEBUG_FOCUS
Jeff Brownb6997262010-10-08 22:31:17 -07002977 //logDispatchStateLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -07002978#endif
2979 } // release lock
2980
2981 // Wake up poll loop since it may need to make new input dispatching choices.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002982 mLooper->wake();
Jeff Brownb88102f2010-09-08 11:49:43 -07002983}
2984
2985void InputDispatcher::setFocusedApplication(const InputApplication* inputApplication) {
2986#if DEBUG_FOCUS
2987 LOGD("setFocusedApplication");
2988#endif
2989 { // acquire lock
2990 AutoMutex _l(mLock);
2991
2992 releaseFocusedApplicationLocked();
2993
2994 if (inputApplication) {
2995 mFocusedApplicationStorage = *inputApplication;
2996 mFocusedApplication = & mFocusedApplicationStorage;
2997 }
2998
2999#if DEBUG_FOCUS
Jeff Brownb6997262010-10-08 22:31:17 -07003000 //logDispatchStateLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -07003001#endif
3002 } // release lock
3003
3004 // Wake up poll loop since it may need to make new input dispatching choices.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07003005 mLooper->wake();
Jeff Brownb88102f2010-09-08 11:49:43 -07003006}
3007
3008void InputDispatcher::releaseFocusedApplicationLocked() {
3009 if (mFocusedApplication) {
3010 mFocusedApplication = NULL;
Jeff Brown928e0542011-01-10 11:17:36 -08003011 mFocusedApplicationStorage.inputApplicationHandle.clear();
Jeff Brownb88102f2010-09-08 11:49:43 -07003012 }
3013}
3014
3015void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
3016#if DEBUG_FOCUS
3017 LOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
3018#endif
3019
3020 bool changed;
3021 { // acquire lock
3022 AutoMutex _l(mLock);
3023
3024 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
Jeff Brown120a4592010-10-27 18:43:51 -07003025 if (mDispatchFrozen && !frozen) {
Jeff Brownb88102f2010-09-08 11:49:43 -07003026 resetANRTimeoutsLocked();
3027 }
3028
Jeff Brown120a4592010-10-27 18:43:51 -07003029 if (mDispatchEnabled && !enabled) {
3030 resetAndDropEverythingLocked("dispatcher is being disabled");
3031 }
3032
Jeff Brownb88102f2010-09-08 11:49:43 -07003033 mDispatchEnabled = enabled;
3034 mDispatchFrozen = frozen;
3035 changed = true;
3036 } else {
3037 changed = false;
3038 }
3039
3040#if DEBUG_FOCUS
Jeff Brownb6997262010-10-08 22:31:17 -07003041 //logDispatchStateLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -07003042#endif
3043 } // release lock
3044
3045 if (changed) {
3046 // Wake up poll loop since it may need to make new input dispatching choices.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07003047 mLooper->wake();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003048 }
3049}
3050
Jeff Brown0029c662011-03-30 02:25:18 -07003051void InputDispatcher::setInputFilterEnabled(bool enabled) {
3052#if DEBUG_FOCUS
3053 LOGD("setInputFilterEnabled: enabled=%d", enabled);
3054#endif
3055
3056 { // acquire lock
3057 AutoMutex _l(mLock);
3058
3059 if (mInputFilterEnabled == enabled) {
3060 return;
3061 }
3062
3063 mInputFilterEnabled = enabled;
3064 resetAndDropEverythingLocked("input filter is being enabled or disabled");
3065 } // release lock
3066
3067 // Wake up poll loop since there might be work to do to drop everything.
3068 mLooper->wake();
3069}
3070
Jeff Browne6504122010-09-27 14:52:15 -07003071bool InputDispatcher::transferTouchFocus(const sp<InputChannel>& fromChannel,
3072 const sp<InputChannel>& toChannel) {
3073#if DEBUG_FOCUS
3074 LOGD("transferTouchFocus: fromChannel=%s, toChannel=%s",
3075 fromChannel->getName().string(), toChannel->getName().string());
3076#endif
3077 { // acquire lock
3078 AutoMutex _l(mLock);
3079
3080 const InputWindow* fromWindow = getWindowLocked(fromChannel);
3081 const InputWindow* toWindow = getWindowLocked(toChannel);
3082 if (! fromWindow || ! toWindow) {
3083#if DEBUG_FOCUS
3084 LOGD("Cannot transfer focus because from or to window not found.");
3085#endif
3086 return false;
3087 }
3088 if (fromWindow == toWindow) {
3089#if DEBUG_FOCUS
3090 LOGD("Trivial transfer to same window.");
3091#endif
3092 return true;
3093 }
3094
3095 bool found = false;
3096 for (size_t i = 0; i < mTouchState.windows.size(); i++) {
3097 const TouchedWindow& touchedWindow = mTouchState.windows[i];
3098 if (touchedWindow.window == fromWindow) {
3099 int32_t oldTargetFlags = touchedWindow.targetFlags;
3100 BitSet32 pointerIds = touchedWindow.pointerIds;
3101
3102 mTouchState.windows.removeAt(i);
3103
Jeff Brown46e75292010-11-10 16:53:45 -08003104 int32_t newTargetFlags = oldTargetFlags
Jeff Browna032cc02011-03-07 16:56:21 -08003105 & (InputTarget::FLAG_FOREGROUND
3106 | InputTarget::FLAG_SPLIT | InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Browne6504122010-09-27 14:52:15 -07003107 mTouchState.addOrUpdateWindow(toWindow, newTargetFlags, pointerIds);
3108
3109 found = true;
3110 break;
3111 }
3112 }
3113
3114 if (! found) {
3115#if DEBUG_FOCUS
3116 LOGD("Focus transfer failed because from window did not have focus.");
3117#endif
3118 return false;
3119 }
3120
Jeff Brown9c9f1a32010-10-11 18:32:20 -07003121 ssize_t fromConnectionIndex = getConnectionIndexLocked(fromChannel);
3122 ssize_t toConnectionIndex = getConnectionIndexLocked(toChannel);
3123 if (fromConnectionIndex >= 0 && toConnectionIndex >= 0) {
3124 sp<Connection> fromConnection = mConnectionsByReceiveFd.valueAt(fromConnectionIndex);
3125 sp<Connection> toConnection = mConnectionsByReceiveFd.valueAt(toConnectionIndex);
3126
3127 fromConnection->inputState.copyPointerStateTo(toConnection->inputState);
Jeff Brownda3d5a92011-03-29 15:11:34 -07003128 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Jeff Brown9c9f1a32010-10-11 18:32:20 -07003129 "transferring touch focus from this window to another window");
Jeff Brownda3d5a92011-03-29 15:11:34 -07003130 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Jeff Brown9c9f1a32010-10-11 18:32:20 -07003131 }
3132
Jeff Browne6504122010-09-27 14:52:15 -07003133#if DEBUG_FOCUS
3134 logDispatchStateLocked();
3135#endif
3136 } // release lock
3137
3138 // Wake up poll loop since it may need to make new input dispatching choices.
3139 mLooper->wake();
3140 return true;
3141}
3142
Jeff Brown120a4592010-10-27 18:43:51 -07003143void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
3144#if DEBUG_FOCUS
3145 LOGD("Resetting and dropping all events (%s).", reason);
3146#endif
3147
Jeff Brownda3d5a92011-03-29 15:11:34 -07003148 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
3149 synthesizeCancelationEventsForAllConnectionsLocked(options);
Jeff Brown120a4592010-10-27 18:43:51 -07003150
3151 resetKeyRepeatLocked();
3152 releasePendingEventLocked();
3153 drainInboundQueueLocked();
3154 resetTargetsLocked();
3155
3156 mTouchState.reset();
3157}
3158
Jeff Brownb88102f2010-09-08 11:49:43 -07003159void InputDispatcher::logDispatchStateLocked() {
3160 String8 dump;
3161 dumpDispatchStateLocked(dump);
Jeff Brown2a95c2a2010-09-16 12:31:46 -07003162
3163 char* text = dump.lockBuffer(dump.size());
3164 char* start = text;
3165 while (*start != '\0') {
3166 char* end = strchr(start, '\n');
3167 if (*end == '\n') {
3168 *(end++) = '\0';
3169 }
3170 LOGD("%s", start);
3171 start = end;
3172 }
Jeff Brownb88102f2010-09-08 11:49:43 -07003173}
3174
3175void InputDispatcher::dumpDispatchStateLocked(String8& dump) {
Jeff Brownf2f487182010-10-01 17:46:21 -07003176 dump.appendFormat(INDENT "DispatchEnabled: %d\n", mDispatchEnabled);
3177 dump.appendFormat(INDENT "DispatchFrozen: %d\n", mDispatchFrozen);
Jeff Brownb88102f2010-09-08 11:49:43 -07003178
3179 if (mFocusedApplication) {
Jeff Brownf2f487182010-10-01 17:46:21 -07003180 dump.appendFormat(INDENT "FocusedApplication: name='%s', dispatchingTimeout=%0.3fms\n",
Jeff Brownb88102f2010-09-08 11:49:43 -07003181 mFocusedApplication->name.string(),
3182 mFocusedApplication->dispatchingTimeout / 1000000.0);
3183 } else {
Jeff Brownf2f487182010-10-01 17:46:21 -07003184 dump.append(INDENT "FocusedApplication: <null>\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003185 }
Jeff Brownf2f487182010-10-01 17:46:21 -07003186 dump.appendFormat(INDENT "FocusedWindow: name='%s'\n",
Jeff Brown2a95c2a2010-09-16 12:31:46 -07003187 mFocusedWindow != NULL ? mFocusedWindow->name.string() : "<null>");
Jeff Brownf2f487182010-10-01 17:46:21 -07003188
3189 dump.appendFormat(INDENT "TouchDown: %s\n", toString(mTouchState.down));
3190 dump.appendFormat(INDENT "TouchSplit: %s\n", toString(mTouchState.split));
Jeff Brown95712852011-01-04 19:41:59 -08003191 dump.appendFormat(INDENT "TouchDeviceId: %d\n", mTouchState.deviceId);
Jeff Brown58a2da82011-01-25 16:02:22 -08003192 dump.appendFormat(INDENT "TouchSource: 0x%08x\n", mTouchState.source);
Jeff Brownf2f487182010-10-01 17:46:21 -07003193 if (!mTouchState.windows.isEmpty()) {
3194 dump.append(INDENT "TouchedWindows:\n");
3195 for (size_t i = 0; i < mTouchState.windows.size(); i++) {
3196 const TouchedWindow& touchedWindow = mTouchState.windows[i];
3197 dump.appendFormat(INDENT2 "%d: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
3198 i, touchedWindow.window->name.string(), touchedWindow.pointerIds.value,
3199 touchedWindow.targetFlags);
3200 }
3201 } else {
3202 dump.append(INDENT "TouchedWindows: <none>\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003203 }
3204
Jeff Brownf2f487182010-10-01 17:46:21 -07003205 if (!mWindows.isEmpty()) {
3206 dump.append(INDENT "Windows:\n");
3207 for (size_t i = 0; i < mWindows.size(); i++) {
3208 const InputWindow& window = mWindows[i];
3209 dump.appendFormat(INDENT2 "%d: name='%s', paused=%s, hasFocus=%s, hasWallpaper=%s, "
3210 "visible=%s, canReceiveKeys=%s, flags=0x%08x, type=0x%08x, layer=%d, "
3211 "frame=[%d,%d][%d,%d], "
Jeff Brownfbf09772011-01-16 14:06:57 -08003212 "touchableRegion=",
Jeff Brownf2f487182010-10-01 17:46:21 -07003213 i, window.name.string(),
3214 toString(window.paused),
3215 toString(window.hasFocus),
3216 toString(window.hasWallpaper),
3217 toString(window.visible),
3218 toString(window.canReceiveKeys),
3219 window.layoutParamsFlags, window.layoutParamsType,
3220 window.layer,
3221 window.frameLeft, window.frameTop,
Jeff Brownfbf09772011-01-16 14:06:57 -08003222 window.frameRight, window.frameBottom);
3223 dumpRegion(dump, window.touchableRegion);
3224 dump.appendFormat(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%0.3fms\n",
Jeff Brownf2f487182010-10-01 17:46:21 -07003225 window.ownerPid, window.ownerUid,
3226 window.dispatchingTimeout / 1000000.0);
3227 }
3228 } else {
3229 dump.append(INDENT "Windows: <none>\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003230 }
3231
Jeff Brownf2f487182010-10-01 17:46:21 -07003232 if (!mMonitoringChannels.isEmpty()) {
3233 dump.append(INDENT "MonitoringChannels:\n");
3234 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
3235 const sp<InputChannel>& channel = mMonitoringChannels[i];
3236 dump.appendFormat(INDENT2 "%d: '%s'\n", i, channel->getName().string());
3237 }
3238 } else {
3239 dump.append(INDENT "MonitoringChannels: <none>\n");
3240 }
Jeff Brown519e0242010-09-15 15:18:56 -07003241
Jeff Brownf2f487182010-10-01 17:46:21 -07003242 dump.appendFormat(INDENT "InboundQueue: length=%u\n", mInboundQueue.count());
3243
3244 if (!mActiveConnections.isEmpty()) {
3245 dump.append(INDENT "ActiveConnections:\n");
3246 for (size_t i = 0; i < mActiveConnections.size(); i++) {
3247 const Connection* connection = mActiveConnections[i];
Jeff Brown76860e32010-10-25 17:37:46 -07003248 dump.appendFormat(INDENT2 "%d: '%s', status=%s, outboundQueueLength=%u, "
Jeff Brownb6997262010-10-08 22:31:17 -07003249 "inputState.isNeutral=%s\n",
Jeff Brownf2f487182010-10-01 17:46:21 -07003250 i, connection->getInputChannelName(), connection->getStatusLabel(),
3251 connection->outboundQueue.count(),
Jeff Brownb6997262010-10-08 22:31:17 -07003252 toString(connection->inputState.isNeutral()));
Jeff Brownf2f487182010-10-01 17:46:21 -07003253 }
3254 } else {
3255 dump.append(INDENT "ActiveConnections: <none>\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003256 }
3257
3258 if (isAppSwitchPendingLocked()) {
Jeff Brownf2f487182010-10-01 17:46:21 -07003259 dump.appendFormat(INDENT "AppSwitch: pending, due in %01.1fms\n",
Jeff Brownb88102f2010-09-08 11:49:43 -07003260 (mAppSwitchDueTime - now()) / 1000000.0);
3261 } else {
Jeff Brownf2f487182010-10-01 17:46:21 -07003262 dump.append(INDENT "AppSwitch: not pending\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003263 }
3264}
3265
Jeff Brown928e0542011-01-10 11:17:36 -08003266status_t InputDispatcher::registerInputChannel(const sp<InputChannel>& inputChannel,
3267 const sp<InputWindowHandle>& inputWindowHandle, bool monitor) {
Jeff Brown9c3cda02010-06-15 01:31:58 -07003268#if DEBUG_REGISTRATION
Jeff Brownb88102f2010-09-08 11:49:43 -07003269 LOGD("channel '%s' ~ registerInputChannel - monitor=%s", inputChannel->getName().string(),
3270 toString(monitor));
Jeff Brown9c3cda02010-06-15 01:31:58 -07003271#endif
3272
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003273 { // acquire lock
3274 AutoMutex _l(mLock);
3275
Jeff Brown519e0242010-09-15 15:18:56 -07003276 if (getConnectionIndexLocked(inputChannel) >= 0) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003277 LOGW("Attempted to register already registered input channel '%s'",
3278 inputChannel->getName().string());
3279 return BAD_VALUE;
3280 }
3281
Jeff Brown928e0542011-01-10 11:17:36 -08003282 sp<Connection> connection = new Connection(inputChannel, inputWindowHandle);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003283 status_t status = connection->initialize();
3284 if (status) {
3285 LOGE("Failed to initialize input publisher for input channel '%s', status=%d",
3286 inputChannel->getName().string(), status);
3287 return status;
3288 }
3289
Jeff Brown2cbecea2010-08-17 15:59:26 -07003290 int32_t receiveFd = inputChannel->getReceivePipeFd();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003291 mConnectionsByReceiveFd.add(receiveFd, connection);
Jeff Brown9c3cda02010-06-15 01:31:58 -07003292
Jeff Brownb88102f2010-09-08 11:49:43 -07003293 if (monitor) {
3294 mMonitoringChannels.push(inputChannel);
3295 }
3296
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07003297 mLooper->addFd(receiveFd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
Jeff Brown2cbecea2010-08-17 15:59:26 -07003298
Jeff Brown9c3cda02010-06-15 01:31:58 -07003299 runCommandsLockedInterruptible();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003300 } // release lock
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003301 return OK;
3302}
3303
3304status_t InputDispatcher::unregisterInputChannel(const sp<InputChannel>& inputChannel) {
Jeff Brown9c3cda02010-06-15 01:31:58 -07003305#if DEBUG_REGISTRATION
Jeff Brown349703e2010-06-22 01:27:15 -07003306 LOGD("channel '%s' ~ unregisterInputChannel", inputChannel->getName().string());
Jeff Brown9c3cda02010-06-15 01:31:58 -07003307#endif
3308
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003309 { // acquire lock
3310 AutoMutex _l(mLock);
3311
Jeff Brown519e0242010-09-15 15:18:56 -07003312 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003313 if (connectionIndex < 0) {
3314 LOGW("Attempted to unregister already unregistered input channel '%s'",
3315 inputChannel->getName().string());
3316 return BAD_VALUE;
3317 }
3318
3319 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
3320 mConnectionsByReceiveFd.removeItemsAt(connectionIndex);
3321
3322 connection->status = Connection::STATUS_ZOMBIE;
3323
Jeff Brownb88102f2010-09-08 11:49:43 -07003324 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
3325 if (mMonitoringChannels[i] == inputChannel) {
3326 mMonitoringChannels.removeAt(i);
3327 break;
3328 }
3329 }
3330
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07003331 mLooper->removeFd(inputChannel->getReceivePipeFd());
Jeff Brown2cbecea2010-08-17 15:59:26 -07003332
Jeff Brown7fbdc842010-06-17 20:52:56 -07003333 nsecs_t currentTime = now();
Jeff Brownb6997262010-10-08 22:31:17 -07003334 abortBrokenDispatchCycleLocked(currentTime, connection);
Jeff Brown9c3cda02010-06-15 01:31:58 -07003335
3336 runCommandsLockedInterruptible();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003337 } // release lock
3338
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003339 // Wake the poll loop because removing the connection may have changed the current
3340 // synchronization state.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07003341 mLooper->wake();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003342 return OK;
3343}
3344
Jeff Brown519e0242010-09-15 15:18:56 -07003345ssize_t InputDispatcher::getConnectionIndexLocked(const sp<InputChannel>& inputChannel) {
Jeff Brown2cbecea2010-08-17 15:59:26 -07003346 ssize_t connectionIndex = mConnectionsByReceiveFd.indexOfKey(inputChannel->getReceivePipeFd());
3347 if (connectionIndex >= 0) {
3348 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
3349 if (connection->inputChannel.get() == inputChannel.get()) {
3350 return connectionIndex;
3351 }
3352 }
3353
3354 return -1;
3355}
3356
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003357void InputDispatcher::activateConnectionLocked(Connection* connection) {
3358 for (size_t i = 0; i < mActiveConnections.size(); i++) {
3359 if (mActiveConnections.itemAt(i) == connection) {
3360 return;
3361 }
3362 }
3363 mActiveConnections.add(connection);
3364}
3365
3366void InputDispatcher::deactivateConnectionLocked(Connection* connection) {
3367 for (size_t i = 0; i < mActiveConnections.size(); i++) {
3368 if (mActiveConnections.itemAt(i) == connection) {
3369 mActiveConnections.removeAt(i);
3370 return;
3371 }
3372 }
3373}
3374
Jeff Brown9c3cda02010-06-15 01:31:58 -07003375void InputDispatcher::onDispatchCycleStartedLocked(
Jeff Brown7fbdc842010-06-17 20:52:56 -07003376 nsecs_t currentTime, const sp<Connection>& connection) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003377}
3378
Jeff Brown9c3cda02010-06-15 01:31:58 -07003379void InputDispatcher::onDispatchCycleFinishedLocked(
Jeff Brown3915bb82010-11-05 15:02:16 -07003380 nsecs_t currentTime, const sp<Connection>& connection, bool handled) {
3381 CommandEntry* commandEntry = postCommandLocked(
3382 & InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
3383 commandEntry->connection = connection;
3384 commandEntry->handled = handled;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003385}
3386
Jeff Brown9c3cda02010-06-15 01:31:58 -07003387void InputDispatcher::onDispatchCycleBrokenLocked(
Jeff Brown7fbdc842010-06-17 20:52:56 -07003388 nsecs_t currentTime, const sp<Connection>& connection) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003389 LOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
3390 connection->getInputChannelName());
3391
Jeff Brown9c3cda02010-06-15 01:31:58 -07003392 CommandEntry* commandEntry = postCommandLocked(
3393 & InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
Jeff Brown7fbdc842010-06-17 20:52:56 -07003394 commandEntry->connection = connection;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003395}
3396
Jeff Brown519e0242010-09-15 15:18:56 -07003397void InputDispatcher::onANRLocked(
3398 nsecs_t currentTime, const InputApplication* application, const InputWindow* window,
3399 nsecs_t eventTime, nsecs_t waitStartTime) {
3400 LOGI("Application is not responding: %s. "
3401 "%01.1fms since event, %01.1fms since wait started",
3402 getApplicationWindowLabelLocked(application, window).string(),
3403 (currentTime - eventTime) / 1000000.0,
3404 (currentTime - waitStartTime) / 1000000.0);
3405
3406 CommandEntry* commandEntry = postCommandLocked(
3407 & InputDispatcher::doNotifyANRLockedInterruptible);
3408 if (application) {
Jeff Brown928e0542011-01-10 11:17:36 -08003409 commandEntry->inputApplicationHandle = application->inputApplicationHandle;
Jeff Brown519e0242010-09-15 15:18:56 -07003410 }
3411 if (window) {
Jeff Brown928e0542011-01-10 11:17:36 -08003412 commandEntry->inputWindowHandle = window->inputWindowHandle;
Jeff Brown519e0242010-09-15 15:18:56 -07003413 commandEntry->inputChannel = window->inputChannel;
3414 }
3415}
3416
Jeff Brownb88102f2010-09-08 11:49:43 -07003417void InputDispatcher::doNotifyConfigurationChangedInterruptible(
3418 CommandEntry* commandEntry) {
3419 mLock.unlock();
3420
3421 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
3422
3423 mLock.lock();
3424}
3425
Jeff Brown9c3cda02010-06-15 01:31:58 -07003426void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(
3427 CommandEntry* commandEntry) {
Jeff Brown7fbdc842010-06-17 20:52:56 -07003428 sp<Connection> connection = commandEntry->connection;
Jeff Brown9c3cda02010-06-15 01:31:58 -07003429
Jeff Brown7fbdc842010-06-17 20:52:56 -07003430 if (connection->status != Connection::STATUS_ZOMBIE) {
3431 mLock.unlock();
Jeff Brown9c3cda02010-06-15 01:31:58 -07003432
Jeff Brown928e0542011-01-10 11:17:36 -08003433 mPolicy->notifyInputChannelBroken(connection->inputWindowHandle);
Jeff Brown7fbdc842010-06-17 20:52:56 -07003434
3435 mLock.lock();
3436 }
Jeff Brown9c3cda02010-06-15 01:31:58 -07003437}
3438
Jeff Brown519e0242010-09-15 15:18:56 -07003439void InputDispatcher::doNotifyANRLockedInterruptible(
Jeff Brown9c3cda02010-06-15 01:31:58 -07003440 CommandEntry* commandEntry) {
Jeff Brown519e0242010-09-15 15:18:56 -07003441 mLock.unlock();
Jeff Brown9c3cda02010-06-15 01:31:58 -07003442
Jeff Brown519e0242010-09-15 15:18:56 -07003443 nsecs_t newTimeout = mPolicy->notifyANR(
Jeff Brown928e0542011-01-10 11:17:36 -08003444 commandEntry->inputApplicationHandle, commandEntry->inputWindowHandle);
Jeff Brown9c3cda02010-06-15 01:31:58 -07003445
Jeff Brown519e0242010-09-15 15:18:56 -07003446 mLock.lock();
Jeff Brown7fbdc842010-06-17 20:52:56 -07003447
Jeff Brown519e0242010-09-15 15:18:56 -07003448 resumeAfterTargetsNotReadyTimeoutLocked(newTimeout, commandEntry->inputChannel);
Jeff Brown9c3cda02010-06-15 01:31:58 -07003449}
3450
Jeff Brownb88102f2010-09-08 11:49:43 -07003451void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
3452 CommandEntry* commandEntry) {
3453 KeyEntry* entry = commandEntry->keyEntry;
Jeff Brown1f245102010-11-18 20:53:46 -08003454
3455 KeyEvent event;
3456 initializeKeyEvent(&event, entry);
Jeff Brownb88102f2010-09-08 11:49:43 -07003457
3458 mLock.unlock();
3459
Jeff Brown928e0542011-01-10 11:17:36 -08003460 bool consumed = mPolicy->interceptKeyBeforeDispatching(commandEntry->inputWindowHandle,
Jeff Brown1f245102010-11-18 20:53:46 -08003461 &event, entry->policyFlags);
Jeff Brownb88102f2010-09-08 11:49:43 -07003462
3463 mLock.lock();
3464
3465 entry->interceptKeyResult = consumed
3466 ? KeyEntry::INTERCEPT_KEY_RESULT_SKIP
3467 : KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
3468 mAllocator.releaseKeyEntry(entry);
3469}
3470
Jeff Brown3915bb82010-11-05 15:02:16 -07003471void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(
3472 CommandEntry* commandEntry) {
3473 sp<Connection> connection = commandEntry->connection;
3474 bool handled = commandEntry->handled;
3475
Jeff Brown49ed71d2010-12-06 17:13:33 -08003476 if (!connection->outboundQueue.isEmpty()) {
Jeff Brown3915bb82010-11-05 15:02:16 -07003477 DispatchEntry* dispatchEntry = connection->outboundQueue.headSentinel.next;
3478 if (dispatchEntry->inProgress
Jeff Brown3915bb82010-11-05 15:02:16 -07003479 && dispatchEntry->eventEntry->type == EventEntry::TYPE_KEY) {
3480 KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry);
Jeff Brown49ed71d2010-12-06 17:13:33 -08003481 if (!(keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK)) {
Jeff Brownda3d5a92011-03-29 15:11:34 -07003482 // Get the fallback key state.
3483 // Clear it out after dispatching the UP.
3484 int32_t originalKeyCode = keyEntry->keyCode;
3485 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
3486 if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
3487 connection->inputState.removeFallbackKey(originalKeyCode);
3488 }
3489
3490 if (handled || !dispatchEntry->hasForegroundTarget()) {
3491 // If the application handles the original key for which we previously
3492 // generated a fallback or if the window is not a foreground window,
3493 // then cancel the associated fallback key, if any.
3494 if (fallbackKeyCode != -1) {
3495 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
3496 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
3497 "application handled the original non-fallback key "
3498 "or is no longer a foreground target, "
3499 "canceling previously dispatched fallback key");
3500 options.keyCode = fallbackKeyCode;
3501 synthesizeCancelationEventsForConnectionLocked(connection, options);
3502 }
3503 connection->inputState.removeFallbackKey(originalKeyCode);
3504 }
Jeff Brown49ed71d2010-12-06 17:13:33 -08003505 } else {
Jeff Brownbfaf3b92011-02-22 15:00:50 -08003506 // If the application did not handle a non-fallback key, first check
Jeff Brownda3d5a92011-03-29 15:11:34 -07003507 // that we are in a good state to perform unhandled key event processing
3508 // Then ask the policy what to do with it.
3509 bool initialDown = keyEntry->action == AKEY_EVENT_ACTION_DOWN
3510 && keyEntry->repeatCount == 0;
3511 if (fallbackKeyCode == -1 && !initialDown) {
Jeff Brownbfaf3b92011-02-22 15:00:50 -08003512#if DEBUG_OUTBOUND_EVENT_DETAILS
Jeff Brownda3d5a92011-03-29 15:11:34 -07003513 LOGD("Unhandled key event: Skipping unhandled key event processing "
3514 "since this is not an initial down. "
3515 "keyCode=%d, action=%d, repeatCount=%d",
3516 originalKeyCode, keyEntry->action, keyEntry->repeatCount);
Jeff Brownbfaf3b92011-02-22 15:00:50 -08003517#endif
Jeff Brownda3d5a92011-03-29 15:11:34 -07003518 goto SkipFallback;
Jeff Brownbfaf3b92011-02-22 15:00:50 -08003519 }
3520
Jeff Brownda3d5a92011-03-29 15:11:34 -07003521 // Dispatch the unhandled key to the policy.
Jeff Brownbfaf3b92011-02-22 15:00:50 -08003522#if DEBUG_OUTBOUND_EVENT_DETAILS
3523 LOGD("Unhandled key event: Asking policy to perform fallback action. "
3524 "keyCode=%d, action=%d, repeatCount=%d",
3525 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount);
3526#endif
Jeff Brown49ed71d2010-12-06 17:13:33 -08003527 KeyEvent event;
3528 initializeKeyEvent(&event, keyEntry);
Jeff Brown3915bb82010-11-05 15:02:16 -07003529
Jeff Brown49ed71d2010-12-06 17:13:33 -08003530 mLock.unlock();
Jeff Brown3915bb82010-11-05 15:02:16 -07003531
Jeff Brown928e0542011-01-10 11:17:36 -08003532 bool fallback = mPolicy->dispatchUnhandledKey(connection->inputWindowHandle,
Jeff Brown49ed71d2010-12-06 17:13:33 -08003533 &event, keyEntry->policyFlags, &event);
Jeff Brown3915bb82010-11-05 15:02:16 -07003534
Jeff Brown49ed71d2010-12-06 17:13:33 -08003535 mLock.lock();
3536
Jeff Brown00045a72010-12-09 18:10:30 -08003537 if (connection->status != Connection::STATUS_NORMAL) {
Jeff Brownda3d5a92011-03-29 15:11:34 -07003538 connection->inputState.removeFallbackKey(originalKeyCode);
Jeff Brown00045a72010-12-09 18:10:30 -08003539 return;
3540 }
3541
Jeff Brownb6110c22011-04-01 16:15:13 -07003542 LOG_ASSERT(connection->outboundQueue.headSentinel.next == dispatchEntry);
Jeff Brown00045a72010-12-09 18:10:30 -08003543
Jeff Brownda3d5a92011-03-29 15:11:34 -07003544 // Latch the fallback keycode for this key on an initial down.
3545 // The fallback keycode cannot change at any other point in the lifecycle.
3546 if (initialDown) {
3547 if (fallback) {
3548 fallbackKeyCode = event.getKeyCode();
3549 } else {
3550 fallbackKeyCode = AKEYCODE_UNKNOWN;
3551 }
3552 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
3553 }
3554
Jeff Brownb6110c22011-04-01 16:15:13 -07003555 LOG_ASSERT(fallbackKeyCode != -1);
Jeff Brownda3d5a92011-03-29 15:11:34 -07003556
3557 // Cancel the fallback key if the policy decides not to send it anymore.
3558 // We will continue to dispatch the key to the policy but we will no
3559 // longer dispatch a fallback key to the application.
3560 if (fallbackKeyCode != AKEYCODE_UNKNOWN
3561 && (!fallback || fallbackKeyCode != event.getKeyCode())) {
3562#if DEBUG_OUTBOUND_EVENT_DETAILS
3563 if (fallback) {
3564 LOGD("Unhandled key event: Policy requested to send key %d"
3565 "as a fallback for %d, but on the DOWN it had requested "
3566 "to send %d instead. Fallback canceled.",
3567 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
3568 } else {
3569 LOGD("Unhandled key event: Policy did not request fallback for %d,"
3570 "but on the DOWN it had requested to send %d. "
3571 "Fallback canceled.",
3572 originalKeyCode, fallbackKeyCode);
3573 }
3574#endif
3575
3576 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
3577 "canceling fallback, policy no longer desires it");
3578 options.keyCode = fallbackKeyCode;
3579 synthesizeCancelationEventsForConnectionLocked(connection, options);
3580
3581 fallback = false;
3582 fallbackKeyCode = AKEYCODE_UNKNOWN;
3583 if (keyEntry->action != AKEY_EVENT_ACTION_UP) {
3584 connection->inputState.setFallbackKey(originalKeyCode,
3585 fallbackKeyCode);
3586 }
3587 }
3588
3589#if DEBUG_OUTBOUND_EVENT_DETAILS
3590 {
3591 String8 msg;
3592 const KeyedVector<int32_t, int32_t>& fallbackKeys =
3593 connection->inputState.getFallbackKeys();
3594 for (size_t i = 0; i < fallbackKeys.size(); i++) {
3595 msg.appendFormat(", %d->%d", fallbackKeys.keyAt(i),
3596 fallbackKeys.valueAt(i));
3597 }
3598 LOGD("Unhandled key event: %d currently tracked fallback keys%s.",
3599 fallbackKeys.size(), msg.string());
3600 }
3601#endif
3602
Jeff Brown49ed71d2010-12-06 17:13:33 -08003603 if (fallback) {
3604 // Restart the dispatch cycle using the fallback key.
3605 keyEntry->eventTime = event.getEventTime();
3606 keyEntry->deviceId = event.getDeviceId();
3607 keyEntry->source = event.getSource();
3608 keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
Jeff Brownda3d5a92011-03-29 15:11:34 -07003609 keyEntry->keyCode = fallbackKeyCode;
Jeff Brown49ed71d2010-12-06 17:13:33 -08003610 keyEntry->scanCode = event.getScanCode();
3611 keyEntry->metaState = event.getMetaState();
3612 keyEntry->repeatCount = event.getRepeatCount();
3613 keyEntry->downTime = event.getDownTime();
3614 keyEntry->syntheticRepeat = false;
3615
Jeff Brownbfaf3b92011-02-22 15:00:50 -08003616#if DEBUG_OUTBOUND_EVENT_DETAILS
3617 LOGD("Unhandled key event: Dispatching fallback key. "
Jeff Brownda3d5a92011-03-29 15:11:34 -07003618 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
3619 originalKeyCode, fallbackKeyCode, keyEntry->metaState);
Jeff Brownbfaf3b92011-02-22 15:00:50 -08003620#endif
3621
Jeff Brown49ed71d2010-12-06 17:13:33 -08003622 dispatchEntry->inProgress = false;
3623 startDispatchCycleLocked(now(), connection);
3624 return;
Jeff Brownda3d5a92011-03-29 15:11:34 -07003625 } else {
3626#if DEBUG_OUTBOUND_EVENT_DETAILS
3627 LOGD("Unhandled key event: No fallback key.");
3628#endif
Jeff Brown49ed71d2010-12-06 17:13:33 -08003629 }
3630 }
3631 }
Jeff Brown3915bb82010-11-05 15:02:16 -07003632 }
3633 }
3634
Jeff Brownbfaf3b92011-02-22 15:00:50 -08003635SkipFallback:
Jeff Brown3915bb82010-11-05 15:02:16 -07003636 startNextDispatchCycleLocked(now(), connection);
3637}
3638
Jeff Brownb88102f2010-09-08 11:49:43 -07003639void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
3640 mLock.unlock();
3641
Jeff Brown01ce2e92010-09-26 22:20:12 -07003642 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
Jeff Brownb88102f2010-09-08 11:49:43 -07003643
3644 mLock.lock();
3645}
3646
Jeff Brown3915bb82010-11-05 15:02:16 -07003647void InputDispatcher::initializeKeyEvent(KeyEvent* event, const KeyEntry* entry) {
3648 event->initialize(entry->deviceId, entry->source, entry->action, entry->flags,
3649 entry->keyCode, entry->scanCode, entry->metaState, entry->repeatCount,
3650 entry->downTime, entry->eventTime);
3651}
3652
Jeff Brown519e0242010-09-15 15:18:56 -07003653void InputDispatcher::updateDispatchStatisticsLocked(nsecs_t currentTime, const EventEntry* entry,
3654 int32_t injectionResult, nsecs_t timeSpentWaitingForApplication) {
3655 // TODO Write some statistics about how long we spend waiting.
Jeff Brownb88102f2010-09-08 11:49:43 -07003656}
3657
3658void InputDispatcher::dump(String8& dump) {
Jeff Brownf2f487182010-10-01 17:46:21 -07003659 dump.append("Input Dispatcher State:\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003660 dumpDispatchStateLocked(dump);
3661}
3662
Jeff Brown9c3cda02010-06-15 01:31:58 -07003663
Jeff Brown519e0242010-09-15 15:18:56 -07003664// --- InputDispatcher::Queue ---
3665
3666template <typename T>
3667uint32_t InputDispatcher::Queue<T>::count() const {
3668 uint32_t result = 0;
3669 for (const T* entry = headSentinel.next; entry != & tailSentinel; entry = entry->next) {
3670 result += 1;
3671 }
3672 return result;
3673}
3674
3675
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003676// --- InputDispatcher::Allocator ---
3677
3678InputDispatcher::Allocator::Allocator() {
3679}
3680
Jeff Brown01ce2e92010-09-26 22:20:12 -07003681InputDispatcher::InjectionState*
3682InputDispatcher::Allocator::obtainInjectionState(int32_t injectorPid, int32_t injectorUid) {
3683 InjectionState* injectionState = mInjectionStatePool.alloc();
3684 injectionState->refCount = 1;
3685 injectionState->injectorPid = injectorPid;
3686 injectionState->injectorUid = injectorUid;
3687 injectionState->injectionIsAsync = false;
3688 injectionState->injectionResult = INPUT_EVENT_INJECTION_PENDING;
3689 injectionState->pendingForegroundDispatches = 0;
3690 return injectionState;
3691}
3692
Jeff Brown7fbdc842010-06-17 20:52:56 -07003693void InputDispatcher::Allocator::initializeEventEntry(EventEntry* entry, int32_t type,
Jeff Brownb6997262010-10-08 22:31:17 -07003694 nsecs_t eventTime, uint32_t policyFlags) {
Jeff Brown7fbdc842010-06-17 20:52:56 -07003695 entry->type = type;
3696 entry->refCount = 1;
3697 entry->dispatchInProgress = false;
Christopher Tatee91a5db2010-06-23 16:50:30 -07003698 entry->eventTime = eventTime;
Jeff Brownb6997262010-10-08 22:31:17 -07003699 entry->policyFlags = policyFlags;
Jeff Brown01ce2e92010-09-26 22:20:12 -07003700 entry->injectionState = NULL;
3701}
3702
3703void InputDispatcher::Allocator::releaseEventEntryInjectionState(EventEntry* entry) {
3704 if (entry->injectionState) {
3705 releaseInjectionState(entry->injectionState);
3706 entry->injectionState = NULL;
3707 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07003708}
3709
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003710InputDispatcher::ConfigurationChangedEntry*
Jeff Brown7fbdc842010-06-17 20:52:56 -07003711InputDispatcher::Allocator::obtainConfigurationChangedEntry(nsecs_t eventTime) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003712 ConfigurationChangedEntry* entry = mConfigurationChangeEntryPool.alloc();
Jeff Brownb6997262010-10-08 22:31:17 -07003713 initializeEventEntry(entry, EventEntry::TYPE_CONFIGURATION_CHANGED, eventTime, 0);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003714 return entry;
3715}
3716
Jeff Brown7fbdc842010-06-17 20:52:56 -07003717InputDispatcher::KeyEntry* InputDispatcher::Allocator::obtainKeyEntry(nsecs_t eventTime,
Jeff Brown58a2da82011-01-25 16:02:22 -08003718 int32_t deviceId, uint32_t source, uint32_t policyFlags, int32_t action,
Jeff Brown7fbdc842010-06-17 20:52:56 -07003719 int32_t flags, int32_t keyCode, int32_t scanCode, int32_t metaState,
3720 int32_t repeatCount, nsecs_t downTime) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003721 KeyEntry* entry = mKeyEntryPool.alloc();
Jeff Brownb6997262010-10-08 22:31:17 -07003722 initializeEventEntry(entry, EventEntry::TYPE_KEY, eventTime, policyFlags);
Jeff Brown7fbdc842010-06-17 20:52:56 -07003723
3724 entry->deviceId = deviceId;
Jeff Brownc5ed5912010-07-14 18:48:53 -07003725 entry->source = source;
Jeff Brown7fbdc842010-06-17 20:52:56 -07003726 entry->action = action;
3727 entry->flags = flags;
3728 entry->keyCode = keyCode;
3729 entry->scanCode = scanCode;
3730 entry->metaState = metaState;
3731 entry->repeatCount = repeatCount;
3732 entry->downTime = downTime;
Jeff Brownb88102f2010-09-08 11:49:43 -07003733 entry->syntheticRepeat = false;
3734 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003735 return entry;
3736}
3737
Jeff Brown7fbdc842010-06-17 20:52:56 -07003738InputDispatcher::MotionEntry* InputDispatcher::Allocator::obtainMotionEntry(nsecs_t eventTime,
Jeff Brown58a2da82011-01-25 16:02:22 -08003739 int32_t deviceId, uint32_t source, uint32_t policyFlags, int32_t action, int32_t flags,
Jeff Brown7fbdc842010-06-17 20:52:56 -07003740 int32_t metaState, int32_t edgeFlags, float xPrecision, float yPrecision,
3741 nsecs_t downTime, uint32_t pointerCount,
3742 const int32_t* pointerIds, const PointerCoords* pointerCoords) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003743 MotionEntry* entry = mMotionEntryPool.alloc();
Jeff Brownb6997262010-10-08 22:31:17 -07003744 initializeEventEntry(entry, EventEntry::TYPE_MOTION, eventTime, policyFlags);
Jeff Brown7fbdc842010-06-17 20:52:56 -07003745
3746 entry->eventTime = eventTime;
3747 entry->deviceId = deviceId;
Jeff Brownc5ed5912010-07-14 18:48:53 -07003748 entry->source = source;
Jeff Brown7fbdc842010-06-17 20:52:56 -07003749 entry->action = action;
Jeff Brown85a31762010-09-01 17:01:00 -07003750 entry->flags = flags;
Jeff Brown7fbdc842010-06-17 20:52:56 -07003751 entry->metaState = metaState;
3752 entry->edgeFlags = edgeFlags;
3753 entry->xPrecision = xPrecision;
3754 entry->yPrecision = yPrecision;
3755 entry->downTime = downTime;
3756 entry->pointerCount = pointerCount;
3757 entry->firstSample.eventTime = eventTime;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003758 entry->firstSample.next = NULL;
Jeff Brown7fbdc842010-06-17 20:52:56 -07003759 entry->lastSample = & entry->firstSample;
3760 for (uint32_t i = 0; i < pointerCount; i++) {
3761 entry->pointerIds[i] = pointerIds[i];
Jeff Brownace13b12011-03-09 17:39:48 -08003762 entry->firstSample.pointerCoords[i].copyFrom(pointerCoords[i]);
Jeff Brown7fbdc842010-06-17 20:52:56 -07003763 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003764 return entry;
3765}
3766
3767InputDispatcher::DispatchEntry* InputDispatcher::Allocator::obtainDispatchEntry(
Jeff Brownb88102f2010-09-08 11:49:43 -07003768 EventEntry* eventEntry,
Jeff Brown519e0242010-09-15 15:18:56 -07003769 int32_t targetFlags, float xOffset, float yOffset) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003770 DispatchEntry* entry = mDispatchEntryPool.alloc();
3771 entry->eventEntry = eventEntry;
3772 eventEntry->refCount += 1;
Jeff Brownb88102f2010-09-08 11:49:43 -07003773 entry->targetFlags = targetFlags;
3774 entry->xOffset = xOffset;
3775 entry->yOffset = yOffset;
Jeff Brownb88102f2010-09-08 11:49:43 -07003776 entry->inProgress = false;
3777 entry->headMotionSample = NULL;
3778 entry->tailMotionSample = NULL;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003779 return entry;
3780}
3781
Jeff Brown9c3cda02010-06-15 01:31:58 -07003782InputDispatcher::CommandEntry* InputDispatcher::Allocator::obtainCommandEntry(Command command) {
3783 CommandEntry* entry = mCommandEntryPool.alloc();
3784 entry->command = command;
3785 return entry;
3786}
3787
Jeff Brown01ce2e92010-09-26 22:20:12 -07003788void InputDispatcher::Allocator::releaseInjectionState(InjectionState* injectionState) {
3789 injectionState->refCount -= 1;
3790 if (injectionState->refCount == 0) {
3791 mInjectionStatePool.free(injectionState);
3792 } else {
Jeff Brownb6110c22011-04-01 16:15:13 -07003793 LOG_ASSERT(injectionState->refCount > 0);
Jeff Brown01ce2e92010-09-26 22:20:12 -07003794 }
3795}
3796
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003797void InputDispatcher::Allocator::releaseEventEntry(EventEntry* entry) {
3798 switch (entry->type) {
3799 case EventEntry::TYPE_CONFIGURATION_CHANGED:
3800 releaseConfigurationChangedEntry(static_cast<ConfigurationChangedEntry*>(entry));
3801 break;
3802 case EventEntry::TYPE_KEY:
3803 releaseKeyEntry(static_cast<KeyEntry*>(entry));
3804 break;
3805 case EventEntry::TYPE_MOTION:
3806 releaseMotionEntry(static_cast<MotionEntry*>(entry));
3807 break;
3808 default:
Jeff Brownb6110c22011-04-01 16:15:13 -07003809 LOG_ASSERT(false);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003810 break;
3811 }
3812}
3813
3814void InputDispatcher::Allocator::releaseConfigurationChangedEntry(
3815 ConfigurationChangedEntry* entry) {
3816 entry->refCount -= 1;
3817 if (entry->refCount == 0) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07003818 releaseEventEntryInjectionState(entry);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003819 mConfigurationChangeEntryPool.free(entry);
3820 } else {
Jeff Brownb6110c22011-04-01 16:15:13 -07003821 LOG_ASSERT(entry->refCount > 0);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003822 }
3823}
3824
3825void InputDispatcher::Allocator::releaseKeyEntry(KeyEntry* entry) {
3826 entry->refCount -= 1;
3827 if (entry->refCount == 0) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07003828 releaseEventEntryInjectionState(entry);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003829 mKeyEntryPool.free(entry);
3830 } else {
Jeff Brownb6110c22011-04-01 16:15:13 -07003831 LOG_ASSERT(entry->refCount > 0);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003832 }
3833}
3834
3835void InputDispatcher::Allocator::releaseMotionEntry(MotionEntry* entry) {
3836 entry->refCount -= 1;
3837 if (entry->refCount == 0) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07003838 releaseEventEntryInjectionState(entry);
Jeff Brown9c3cda02010-06-15 01:31:58 -07003839 for (MotionSample* sample = entry->firstSample.next; sample != NULL; ) {
3840 MotionSample* next = sample->next;
3841 mMotionSamplePool.free(sample);
3842 sample = next;
3843 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003844 mMotionEntryPool.free(entry);
3845 } else {
Jeff Brownb6110c22011-04-01 16:15:13 -07003846 LOG_ASSERT(entry->refCount > 0);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003847 }
3848}
3849
Jeff Browna032cc02011-03-07 16:56:21 -08003850void InputDispatcher::Allocator::freeMotionSample(MotionSample* sample) {
3851 mMotionSamplePool.free(sample);
3852}
3853
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003854void InputDispatcher::Allocator::releaseDispatchEntry(DispatchEntry* entry) {
3855 releaseEventEntry(entry->eventEntry);
3856 mDispatchEntryPool.free(entry);
3857}
3858
Jeff Brown9c3cda02010-06-15 01:31:58 -07003859void InputDispatcher::Allocator::releaseCommandEntry(CommandEntry* entry) {
3860 mCommandEntryPool.free(entry);
3861}
3862
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003863void InputDispatcher::Allocator::appendMotionSample(MotionEntry* motionEntry,
Jeff Brown7fbdc842010-06-17 20:52:56 -07003864 nsecs_t eventTime, const PointerCoords* pointerCoords) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003865 MotionSample* sample = mMotionSamplePool.alloc();
3866 sample->eventTime = eventTime;
Jeff Brown7fbdc842010-06-17 20:52:56 -07003867 uint32_t pointerCount = motionEntry->pointerCount;
3868 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brownace13b12011-03-09 17:39:48 -08003869 sample->pointerCoords[i].copyFrom(pointerCoords[i]);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003870 }
3871
3872 sample->next = NULL;
3873 motionEntry->lastSample->next = sample;
3874 motionEntry->lastSample = sample;
3875}
3876
Jeff Brown01ce2e92010-09-26 22:20:12 -07003877void InputDispatcher::Allocator::recycleKeyEntry(KeyEntry* keyEntry) {
3878 releaseEventEntryInjectionState(keyEntry);
Jeff Brownb88102f2010-09-08 11:49:43 -07003879
Jeff Brown01ce2e92010-09-26 22:20:12 -07003880 keyEntry->dispatchInProgress = false;
3881 keyEntry->syntheticRepeat = false;
3882 keyEntry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
Jeff Brownb88102f2010-09-08 11:49:43 -07003883}
3884
3885
Jeff Brownae9fc032010-08-18 15:51:08 -07003886// --- InputDispatcher::MotionEntry ---
3887
3888uint32_t InputDispatcher::MotionEntry::countSamples() const {
3889 uint32_t count = 1;
3890 for (MotionSample* sample = firstSample.next; sample != NULL; sample = sample->next) {
3891 count += 1;
3892 }
3893 return count;
3894}
3895
Jeff Brownb88102f2010-09-08 11:49:43 -07003896
3897// --- InputDispatcher::InputState ---
3898
Jeff Brownb6997262010-10-08 22:31:17 -07003899InputDispatcher::InputState::InputState() {
Jeff Brownb88102f2010-09-08 11:49:43 -07003900}
3901
3902InputDispatcher::InputState::~InputState() {
3903}
3904
3905bool InputDispatcher::InputState::isNeutral() const {
3906 return mKeyMementos.isEmpty() && mMotionMementos.isEmpty();
3907}
3908
Jeff Browna032cc02011-03-07 16:56:21 -08003909void InputDispatcher::InputState::trackEvent(const EventEntry* entry, int32_t action) {
Jeff Brownb88102f2010-09-08 11:49:43 -07003910 switch (entry->type) {
3911 case EventEntry::TYPE_KEY:
Jeff Browna032cc02011-03-07 16:56:21 -08003912 trackKey(static_cast<const KeyEntry*>(entry), action);
Jeff Browncc0c1592011-02-19 05:07:28 -08003913 break;
Jeff Brownb88102f2010-09-08 11:49:43 -07003914
3915 case EventEntry::TYPE_MOTION:
Jeff Browna032cc02011-03-07 16:56:21 -08003916 trackMotion(static_cast<const MotionEntry*>(entry), action);
Jeff Browncc0c1592011-02-19 05:07:28 -08003917 break;
Jeff Brownb88102f2010-09-08 11:49:43 -07003918 }
3919}
3920
Jeff Browna032cc02011-03-07 16:56:21 -08003921void InputDispatcher::InputState::trackKey(const KeyEntry* entry, int32_t action) {
Jeff Brownda3d5a92011-03-29 15:11:34 -07003922 if (action == AKEY_EVENT_ACTION_UP
3923 && (entry->flags & AKEY_EVENT_FLAG_FALLBACK)) {
3924 for (size_t i = 0; i < mFallbackKeys.size(); ) {
3925 if (mFallbackKeys.valueAt(i) == entry->keyCode) {
3926 mFallbackKeys.removeItemsAt(i);
3927 } else {
3928 i += 1;
3929 }
3930 }
3931 }
3932
Jeff Brownb88102f2010-09-08 11:49:43 -07003933 for (size_t i = 0; i < mKeyMementos.size(); i++) {
3934 KeyMemento& memento = mKeyMementos.editItemAt(i);
3935 if (memento.deviceId == entry->deviceId
3936 && memento.source == entry->source
3937 && memento.keyCode == entry->keyCode
3938 && memento.scanCode == entry->scanCode) {
3939 switch (action) {
3940 case AKEY_EVENT_ACTION_UP:
3941 mKeyMementos.removeAt(i);
Jeff Browncc0c1592011-02-19 05:07:28 -08003942 return;
Jeff Brownb88102f2010-09-08 11:49:43 -07003943
3944 case AKEY_EVENT_ACTION_DOWN:
Jeff Browncc0c1592011-02-19 05:07:28 -08003945 mKeyMementos.removeAt(i);
3946 goto Found;
Jeff Brownb88102f2010-09-08 11:49:43 -07003947
3948 default:
Jeff Browncc0c1592011-02-19 05:07:28 -08003949 return;
Jeff Brownb88102f2010-09-08 11:49:43 -07003950 }
3951 }
3952 }
3953
Jeff Browncc0c1592011-02-19 05:07:28 -08003954Found:
3955 if (action == AKEY_EVENT_ACTION_DOWN) {
Jeff Brownb88102f2010-09-08 11:49:43 -07003956 mKeyMementos.push();
3957 KeyMemento& memento = mKeyMementos.editTop();
3958 memento.deviceId = entry->deviceId;
3959 memento.source = entry->source;
3960 memento.keyCode = entry->keyCode;
3961 memento.scanCode = entry->scanCode;
Jeff Brown49ed71d2010-12-06 17:13:33 -08003962 memento.flags = entry->flags;
Jeff Brownb88102f2010-09-08 11:49:43 -07003963 memento.downTime = entry->downTime;
Jeff Brownb88102f2010-09-08 11:49:43 -07003964 }
3965}
3966
Jeff Browna032cc02011-03-07 16:56:21 -08003967void InputDispatcher::InputState::trackMotion(const MotionEntry* entry, int32_t action) {
3968 int32_t actionMasked = action & AMOTION_EVENT_ACTION_MASK;
Jeff Brownb88102f2010-09-08 11:49:43 -07003969 for (size_t i = 0; i < mMotionMementos.size(); i++) {
3970 MotionMemento& memento = mMotionMementos.editItemAt(i);
3971 if (memento.deviceId == entry->deviceId
3972 && memento.source == entry->source) {
Jeff Browna032cc02011-03-07 16:56:21 -08003973 switch (actionMasked) {
Jeff Brownb88102f2010-09-08 11:49:43 -07003974 case AMOTION_EVENT_ACTION_UP:
3975 case AMOTION_EVENT_ACTION_CANCEL:
Jeff Browna032cc02011-03-07 16:56:21 -08003976 case AMOTION_EVENT_ACTION_HOVER_ENTER:
Jeff Browncc0c1592011-02-19 05:07:28 -08003977 case AMOTION_EVENT_ACTION_HOVER_MOVE:
Jeff Browna032cc02011-03-07 16:56:21 -08003978 case AMOTION_EVENT_ACTION_HOVER_EXIT:
Jeff Brownb88102f2010-09-08 11:49:43 -07003979 mMotionMementos.removeAt(i);
Jeff Browncc0c1592011-02-19 05:07:28 -08003980 return;
Jeff Brownb88102f2010-09-08 11:49:43 -07003981
3982 case AMOTION_EVENT_ACTION_DOWN:
Jeff Browncc0c1592011-02-19 05:07:28 -08003983 mMotionMementos.removeAt(i);
3984 goto Found;
Jeff Brownb88102f2010-09-08 11:49:43 -07003985
3986 case AMOTION_EVENT_ACTION_POINTER_UP:
Jeff Browncc0c1592011-02-19 05:07:28 -08003987 case AMOTION_EVENT_ACTION_POINTER_DOWN:
Jeff Brownb88102f2010-09-08 11:49:43 -07003988 case AMOTION_EVENT_ACTION_MOVE:
Jeff Browncc0c1592011-02-19 05:07:28 -08003989 memento.setPointers(entry);
3990 return;
Jeff Brownb88102f2010-09-08 11:49:43 -07003991
3992 default:
Jeff Browncc0c1592011-02-19 05:07:28 -08003993 return;
Jeff Brownb88102f2010-09-08 11:49:43 -07003994 }
3995 }
3996 }
3997
Jeff Browncc0c1592011-02-19 05:07:28 -08003998Found:
Jeff Browna032cc02011-03-07 16:56:21 -08003999 switch (actionMasked) {
4000 case AMOTION_EVENT_ACTION_DOWN:
4001 case AMOTION_EVENT_ACTION_HOVER_ENTER:
4002 case AMOTION_EVENT_ACTION_HOVER_MOVE:
4003 case AMOTION_EVENT_ACTION_HOVER_EXIT:
Jeff Brownb88102f2010-09-08 11:49:43 -07004004 mMotionMementos.push();
4005 MotionMemento& memento = mMotionMementos.editTop();
4006 memento.deviceId = entry->deviceId;
4007 memento.source = entry->source;
4008 memento.xPrecision = entry->xPrecision;
4009 memento.yPrecision = entry->yPrecision;
4010 memento.downTime = entry->downTime;
4011 memento.setPointers(entry);
Jeff Browna032cc02011-03-07 16:56:21 -08004012 memento.hovering = actionMasked != AMOTION_EVENT_ACTION_DOWN;
Jeff Brownb88102f2010-09-08 11:49:43 -07004013 }
4014}
4015
4016void InputDispatcher::InputState::MotionMemento::setPointers(const MotionEntry* entry) {
4017 pointerCount = entry->pointerCount;
4018 for (uint32_t i = 0; i < entry->pointerCount; i++) {
4019 pointerIds[i] = entry->pointerIds[i];
Jeff Brownace13b12011-03-09 17:39:48 -08004020 pointerCoords[i].copyFrom(entry->lastSample->pointerCoords[i]);
Jeff Brownb88102f2010-09-08 11:49:43 -07004021 }
4022}
4023
Jeff Brownb6997262010-10-08 22:31:17 -07004024void InputDispatcher::InputState::synthesizeCancelationEvents(nsecs_t currentTime,
4025 Allocator* allocator, Vector<EventEntry*>& outEvents,
Jeff Brownda3d5a92011-03-29 15:11:34 -07004026 const CancelationOptions& options) {
Jeff Brownb6997262010-10-08 22:31:17 -07004027 for (size_t i = 0; i < mKeyMementos.size(); ) {
Jeff Brownb88102f2010-09-08 11:49:43 -07004028 const KeyMemento& memento = mKeyMementos.itemAt(i);
Jeff Brown49ed71d2010-12-06 17:13:33 -08004029 if (shouldCancelKey(memento, options)) {
Jeff Brownb6997262010-10-08 22:31:17 -07004030 outEvents.push(allocator->obtainKeyEntry(currentTime,
4031 memento.deviceId, memento.source, 0,
Jeff Brown49ed71d2010-12-06 17:13:33 -08004032 AKEY_EVENT_ACTION_UP, memento.flags | AKEY_EVENT_FLAG_CANCELED,
Jeff Brownb6997262010-10-08 22:31:17 -07004033 memento.keyCode, memento.scanCode, 0, 0, memento.downTime));
4034 mKeyMementos.removeAt(i);
4035 } else {
4036 i += 1;
4037 }
Jeff Brownb88102f2010-09-08 11:49:43 -07004038 }
4039
Jeff Browna1160a72010-10-11 18:22:53 -07004040 for (size_t i = 0; i < mMotionMementos.size(); ) {
Jeff Brownb88102f2010-09-08 11:49:43 -07004041 const MotionMemento& memento = mMotionMementos.itemAt(i);
Jeff Brown49ed71d2010-12-06 17:13:33 -08004042 if (shouldCancelMotion(memento, options)) {
Jeff Brownb6997262010-10-08 22:31:17 -07004043 outEvents.push(allocator->obtainMotionEntry(currentTime,
4044 memento.deviceId, memento.source, 0,
Jeff Browna032cc02011-03-07 16:56:21 -08004045 memento.hovering
4046 ? AMOTION_EVENT_ACTION_HOVER_EXIT
4047 : AMOTION_EVENT_ACTION_CANCEL,
4048 0, 0, 0,
Jeff Brownb6997262010-10-08 22:31:17 -07004049 memento.xPrecision, memento.yPrecision, memento.downTime,
4050 memento.pointerCount, memento.pointerIds, memento.pointerCoords));
4051 mMotionMementos.removeAt(i);
4052 } else {
4053 i += 1;
4054 }
Jeff Brownb88102f2010-09-08 11:49:43 -07004055 }
4056}
4057
4058void InputDispatcher::InputState::clear() {
4059 mKeyMementos.clear();
4060 mMotionMementos.clear();
Jeff Brownda3d5a92011-03-29 15:11:34 -07004061 mFallbackKeys.clear();
Jeff Brownb6997262010-10-08 22:31:17 -07004062}
4063
Jeff Brown9c9f1a32010-10-11 18:32:20 -07004064void InputDispatcher::InputState::copyPointerStateTo(InputState& other) const {
4065 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4066 const MotionMemento& memento = mMotionMementos.itemAt(i);
4067 if (memento.source & AINPUT_SOURCE_CLASS_POINTER) {
4068 for (size_t j = 0; j < other.mMotionMementos.size(); ) {
4069 const MotionMemento& otherMemento = other.mMotionMementos.itemAt(j);
4070 if (memento.deviceId == otherMemento.deviceId
4071 && memento.source == otherMemento.source) {
4072 other.mMotionMementos.removeAt(j);
4073 } else {
4074 j += 1;
4075 }
4076 }
4077 other.mMotionMementos.push(memento);
4078 }
4079 }
4080}
4081
Jeff Brownda3d5a92011-03-29 15:11:34 -07004082int32_t InputDispatcher::InputState::getFallbackKey(int32_t originalKeyCode) {
4083 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
4084 return index >= 0 ? mFallbackKeys.valueAt(index) : -1;
4085}
4086
4087void InputDispatcher::InputState::setFallbackKey(int32_t originalKeyCode,
4088 int32_t fallbackKeyCode) {
4089 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
4090 if (index >= 0) {
4091 mFallbackKeys.replaceValueAt(index, fallbackKeyCode);
4092 } else {
4093 mFallbackKeys.add(originalKeyCode, fallbackKeyCode);
4094 }
4095}
4096
4097void InputDispatcher::InputState::removeFallbackKey(int32_t originalKeyCode) {
4098 mFallbackKeys.removeItem(originalKeyCode);
4099}
4100
Jeff Brown49ed71d2010-12-06 17:13:33 -08004101bool InputDispatcher::InputState::shouldCancelKey(const KeyMemento& memento,
Jeff Brownda3d5a92011-03-29 15:11:34 -07004102 const CancelationOptions& options) {
4103 if (options.keyCode != -1 && memento.keyCode != options.keyCode) {
4104 return false;
4105 }
4106
4107 switch (options.mode) {
4108 case CancelationOptions::CANCEL_ALL_EVENTS:
4109 case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
Jeff Brownb6997262010-10-08 22:31:17 -07004110 return true;
Jeff Brownda3d5a92011-03-29 15:11:34 -07004111 case CancelationOptions::CANCEL_FALLBACK_EVENTS:
Jeff Brown49ed71d2010-12-06 17:13:33 -08004112 return memento.flags & AKEY_EVENT_FLAG_FALLBACK;
4113 default:
4114 return false;
4115 }
4116}
4117
4118bool InputDispatcher::InputState::shouldCancelMotion(const MotionMemento& memento,
Jeff Brownda3d5a92011-03-29 15:11:34 -07004119 const CancelationOptions& options) {
4120 switch (options.mode) {
4121 case CancelationOptions::CANCEL_ALL_EVENTS:
Jeff Brown49ed71d2010-12-06 17:13:33 -08004122 return true;
Jeff Brownda3d5a92011-03-29 15:11:34 -07004123 case CancelationOptions::CANCEL_POINTER_EVENTS:
Jeff Brown49ed71d2010-12-06 17:13:33 -08004124 return memento.source & AINPUT_SOURCE_CLASS_POINTER;
Jeff Brownda3d5a92011-03-29 15:11:34 -07004125 case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
Jeff Brown49ed71d2010-12-06 17:13:33 -08004126 return !(memento.source & AINPUT_SOURCE_CLASS_POINTER);
4127 default:
4128 return false;
Jeff Brownb6997262010-10-08 22:31:17 -07004129 }
Jeff Brownb88102f2010-09-08 11:49:43 -07004130}
4131
4132
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004133// --- InputDispatcher::Connection ---
4134
Jeff Brown928e0542011-01-10 11:17:36 -08004135InputDispatcher::Connection::Connection(const sp<InputChannel>& inputChannel,
4136 const sp<InputWindowHandle>& inputWindowHandle) :
4137 status(STATUS_NORMAL), inputChannel(inputChannel), inputWindowHandle(inputWindowHandle),
4138 inputPublisher(inputChannel),
Jeff Brownda3d5a92011-03-29 15:11:34 -07004139 lastEventTime(LONG_LONG_MAX), lastDispatchTime(LONG_LONG_MAX) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004140}
4141
4142InputDispatcher::Connection::~Connection() {
4143}
4144
4145status_t InputDispatcher::Connection::initialize() {
4146 return inputPublisher.initialize();
4147}
4148
Jeff Brown9c3cda02010-06-15 01:31:58 -07004149const char* InputDispatcher::Connection::getStatusLabel() const {
4150 switch (status) {
4151 case STATUS_NORMAL:
4152 return "NORMAL";
4153
4154 case STATUS_BROKEN:
4155 return "BROKEN";
4156
Jeff Brown9c3cda02010-06-15 01:31:58 -07004157 case STATUS_ZOMBIE:
4158 return "ZOMBIE";
4159
4160 default:
4161 return "UNKNOWN";
4162 }
4163}
4164
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004165InputDispatcher::DispatchEntry* InputDispatcher::Connection::findQueuedDispatchEntryForEvent(
4166 const EventEntry* eventEntry) const {
Jeff Brownb88102f2010-09-08 11:49:43 -07004167 for (DispatchEntry* dispatchEntry = outboundQueue.tailSentinel.prev;
4168 dispatchEntry != & outboundQueue.headSentinel; dispatchEntry = dispatchEntry->prev) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004169 if (dispatchEntry->eventEntry == eventEntry) {
4170 return dispatchEntry;
4171 }
4172 }
4173 return NULL;
4174}
4175
Jeff Brownb88102f2010-09-08 11:49:43 -07004176
Jeff Brown9c3cda02010-06-15 01:31:58 -07004177// --- InputDispatcher::CommandEntry ---
4178
Jeff Brownb88102f2010-09-08 11:49:43 -07004179InputDispatcher::CommandEntry::CommandEntry() :
4180 keyEntry(NULL) {
Jeff Brown9c3cda02010-06-15 01:31:58 -07004181}
4182
4183InputDispatcher::CommandEntry::~CommandEntry() {
4184}
4185
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004186
Jeff Brown01ce2e92010-09-26 22:20:12 -07004187// --- InputDispatcher::TouchState ---
4188
4189InputDispatcher::TouchState::TouchState() :
Jeff Brown58a2da82011-01-25 16:02:22 -08004190 down(false), split(false), deviceId(-1), source(0) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07004191}
4192
4193InputDispatcher::TouchState::~TouchState() {
4194}
4195
4196void InputDispatcher::TouchState::reset() {
4197 down = false;
4198 split = false;
Jeff Brown95712852011-01-04 19:41:59 -08004199 deviceId = -1;
Jeff Brown58a2da82011-01-25 16:02:22 -08004200 source = 0;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004201 windows.clear();
4202}
4203
4204void InputDispatcher::TouchState::copyFrom(const TouchState& other) {
4205 down = other.down;
4206 split = other.split;
Jeff Brown95712852011-01-04 19:41:59 -08004207 deviceId = other.deviceId;
Jeff Brown58a2da82011-01-25 16:02:22 -08004208 source = other.source;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004209 windows.clear();
4210 windows.appendVector(other.windows);
4211}
4212
4213void InputDispatcher::TouchState::addOrUpdateWindow(const InputWindow* window,
4214 int32_t targetFlags, BitSet32 pointerIds) {
4215 if (targetFlags & InputTarget::FLAG_SPLIT) {
4216 split = true;
4217 }
4218
4219 for (size_t i = 0; i < windows.size(); i++) {
4220 TouchedWindow& touchedWindow = windows.editItemAt(i);
4221 if (touchedWindow.window == window) {
4222 touchedWindow.targetFlags |= targetFlags;
4223 touchedWindow.pointerIds.value |= pointerIds.value;
4224 return;
4225 }
4226 }
4227
4228 windows.push();
4229
4230 TouchedWindow& touchedWindow = windows.editTop();
4231 touchedWindow.window = window;
4232 touchedWindow.targetFlags = targetFlags;
4233 touchedWindow.pointerIds = pointerIds;
4234 touchedWindow.channel = window->inputChannel;
4235}
4236
Jeff Browna032cc02011-03-07 16:56:21 -08004237void InputDispatcher::TouchState::filterNonAsIsTouchWindows() {
Jeff Brown01ce2e92010-09-26 22:20:12 -07004238 for (size_t i = 0 ; i < windows.size(); ) {
Jeff Browna032cc02011-03-07 16:56:21 -08004239 TouchedWindow& window = windows.editItemAt(i);
4240 if (window.targetFlags & InputTarget::FLAG_DISPATCH_AS_IS) {
4241 window.targetFlags &= ~InputTarget::FLAG_DISPATCH_MASK;
4242 window.targetFlags |= InputTarget::FLAG_DISPATCH_AS_IS;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004243 i += 1;
Jeff Browna032cc02011-03-07 16:56:21 -08004244 } else {
4245 windows.removeAt(i);
Jeff Brown01ce2e92010-09-26 22:20:12 -07004246 }
4247 }
4248}
4249
4250const InputWindow* InputDispatcher::TouchState::getFirstForegroundWindow() {
4251 for (size_t i = 0; i < windows.size(); i++) {
4252 if (windows[i].targetFlags & InputTarget::FLAG_FOREGROUND) {
4253 return windows[i].window;
4254 }
4255 }
4256 return NULL;
4257}
4258
4259
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004260// --- InputDispatcherThread ---
4261
4262InputDispatcherThread::InputDispatcherThread(const sp<InputDispatcherInterface>& dispatcher) :
4263 Thread(/*canCallJava*/ true), mDispatcher(dispatcher) {
4264}
4265
4266InputDispatcherThread::~InputDispatcherThread() {
4267}
4268
4269bool InputDispatcherThread::threadLoop() {
4270 mDispatcher->dispatchOnce();
4271 return true;
4272}
4273
4274} // namespace android