blob: 1cac502562be9163c985c7a8e9d470cc8e063f7f [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 Brown4e91a182011-04-07 11:38:09 -070082// Motion samples that are received within this amount of time are simply coalesced
83// when batched instead of being appended. This is done because some drivers update
84// the location of pointers one at a time instead of all at once.
85// For example, when there are 10 fingers down, the input dispatcher may receive 10
86// samples in quick succession with only one finger's location changed in each sample.
87//
88// This value effectively imposes an upper bound on the touch sampling rate.
89// Touch sensors typically have a 50Hz - 200Hz sampling rate, so we expect distinct
90// samples to become available 5-20ms apart but individual finger reports can trickle
91// in over a period of 2-4ms or so.
92//
93// Empirical testing shows that a 2ms coalescing interval (500Hz) is not enough,
94// a 3ms coalescing interval (333Hz) works well most of the time and doesn't introduce
95// significant quantization noise on current hardware.
96const nsecs_t MOTION_SAMPLE_COALESCE_INTERVAL = 3 * 1000000LL; // 3ms, 333Hz
97
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070098
Jeff Brown7fbdc842010-06-17 20:52:56 -070099static inline nsecs_t now() {
100 return systemTime(SYSTEM_TIME_MONOTONIC);
101}
102
Jeff Brownb88102f2010-09-08 11:49:43 -0700103static inline const char* toString(bool value) {
104 return value ? "true" : "false";
105}
106
Jeff Brown01ce2e92010-09-26 22:20:12 -0700107static inline int32_t getMotionEventActionPointerIndex(int32_t action) {
108 return (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK)
109 >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
110}
111
112static bool isValidKeyAction(int32_t action) {
113 switch (action) {
114 case AKEY_EVENT_ACTION_DOWN:
115 case AKEY_EVENT_ACTION_UP:
116 return true;
117 default:
118 return false;
119 }
120}
121
122static bool validateKeyEvent(int32_t action) {
123 if (! isValidKeyAction(action)) {
124 LOGE("Key event has invalid action code 0x%x", action);
125 return false;
126 }
127 return true;
128}
129
Jeff Brownb6997262010-10-08 22:31:17 -0700130static bool isValidMotionAction(int32_t action, size_t pointerCount) {
Jeff Brown01ce2e92010-09-26 22:20:12 -0700131 switch (action & AMOTION_EVENT_ACTION_MASK) {
132 case AMOTION_EVENT_ACTION_DOWN:
133 case AMOTION_EVENT_ACTION_UP:
134 case AMOTION_EVENT_ACTION_CANCEL:
135 case AMOTION_EVENT_ACTION_MOVE:
Jeff Brown01ce2e92010-09-26 22:20:12 -0700136 case AMOTION_EVENT_ACTION_OUTSIDE:
Jeff Browna032cc02011-03-07 16:56:21 -0800137 case AMOTION_EVENT_ACTION_HOVER_ENTER:
Jeff Browncc0c1592011-02-19 05:07:28 -0800138 case AMOTION_EVENT_ACTION_HOVER_MOVE:
Jeff Browna032cc02011-03-07 16:56:21 -0800139 case AMOTION_EVENT_ACTION_HOVER_EXIT:
Jeff Brown33bbfd22011-02-24 20:55:35 -0800140 case AMOTION_EVENT_ACTION_SCROLL:
Jeff Brown01ce2e92010-09-26 22:20:12 -0700141 return true;
Jeff Brownb6997262010-10-08 22:31:17 -0700142 case AMOTION_EVENT_ACTION_POINTER_DOWN:
143 case AMOTION_EVENT_ACTION_POINTER_UP: {
144 int32_t index = getMotionEventActionPointerIndex(action);
145 return index >= 0 && size_t(index) < pointerCount;
146 }
Jeff Brown01ce2e92010-09-26 22:20:12 -0700147 default:
148 return false;
149 }
150}
151
152static bool validateMotionEvent(int32_t action, size_t pointerCount,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700153 const PointerProperties* pointerProperties) {
Jeff Brownb6997262010-10-08 22:31:17 -0700154 if (! isValidMotionAction(action, pointerCount)) {
Jeff Brown01ce2e92010-09-26 22:20:12 -0700155 LOGE("Motion event has invalid action code 0x%x", action);
156 return false;
157 }
158 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
159 LOGE("Motion event has invalid pointer count %d; value must be between 1 and %d.",
160 pointerCount, MAX_POINTERS);
161 return false;
162 }
Jeff Brownc3db8582010-10-20 15:33:38 -0700163 BitSet32 pointerIdBits;
Jeff Brown01ce2e92010-09-26 22:20:12 -0700164 for (size_t i = 0; i < pointerCount; i++) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700165 int32_t id = pointerProperties[i].id;
Jeff Brownc3db8582010-10-20 15:33:38 -0700166 if (id < 0 || id > MAX_POINTER_ID) {
Jeff Brown01ce2e92010-09-26 22:20:12 -0700167 LOGE("Motion event has invalid pointer id %d; value must be between 0 and %d",
Jeff Brownc3db8582010-10-20 15:33:38 -0700168 id, MAX_POINTER_ID);
Jeff Brown01ce2e92010-09-26 22:20:12 -0700169 return false;
170 }
Jeff Brownc3db8582010-10-20 15:33:38 -0700171 if (pointerIdBits.hasBit(id)) {
172 LOGE("Motion event has duplicate pointer id %d", id);
173 return false;
174 }
175 pointerIdBits.markBit(id);
Jeff Brown01ce2e92010-09-26 22:20:12 -0700176 }
177 return true;
178}
179
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400180static void scalePointerCoords(const PointerCoords* inCoords, size_t count, float scaleFactor,
181 PointerCoords* outCoords) {
182 for (size_t i = 0; i < count; i++) {
183 outCoords[i] = inCoords[i];
184 outCoords[i].scale(scaleFactor);
185 }
186}
187
Jeff Brownfbf09772011-01-16 14:06:57 -0800188static void dumpRegion(String8& dump, const SkRegion& region) {
189 if (region.isEmpty()) {
190 dump.append("<empty>");
191 return;
192 }
193
194 bool first = true;
195 for (SkRegion::Iterator it(region); !it.done(); it.next()) {
196 if (first) {
197 first = false;
198 } else {
199 dump.append("|");
200 }
201 const SkIRect& rect = it.rect();
202 dump.appendFormat("[%d,%d][%d,%d]", rect.fLeft, rect.fTop, rect.fRight, rect.fBottom);
203 }
204}
205
Jeff Brownb88102f2010-09-08 11:49:43 -0700206
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700207// --- InputDispatcher ---
208
Jeff Brown9c3cda02010-06-15 01:31:58 -0700209InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy) :
Jeff Brownb88102f2010-09-08 11:49:43 -0700210 mPolicy(policy),
Jeff Brown928e0542011-01-10 11:17:36 -0800211 mPendingEvent(NULL), mAppSwitchSawKeyDown(false), mAppSwitchDueTime(LONG_LONG_MAX),
212 mNextUnblockedEvent(NULL),
Jeff Brown0029c662011-03-30 02:25:18 -0700213 mDispatchEnabled(true), mDispatchFrozen(false), mInputFilterEnabled(false),
Jeff Brownb88102f2010-09-08 11:49:43 -0700214 mCurrentInputTargetsValid(false),
Jeff Brown9302c872011-07-13 22:51:29 -0700215 mInputTargetWaitCause(INPUT_TARGET_WAIT_CAUSE_NONE) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -0700216 mLooper = new Looper(false);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700217
Jeff Brownb88102f2010-09-08 11:49:43 -0700218 mInboundQueue.headSentinel.refCount = -1;
219 mInboundQueue.headSentinel.type = EventEntry::TYPE_SENTINEL;
220 mInboundQueue.headSentinel.eventTime = LONG_LONG_MIN;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700221
Jeff Brownb88102f2010-09-08 11:49:43 -0700222 mInboundQueue.tailSentinel.refCount = -1;
223 mInboundQueue.tailSentinel.type = EventEntry::TYPE_SENTINEL;
224 mInboundQueue.tailSentinel.eventTime = LONG_LONG_MAX;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700225
226 mKeyRepeatState.lastKeyEntry = NULL;
Jeff Brown9c3cda02010-06-15 01:31:58 -0700227
Jeff Brown214eaf42011-05-26 19:17:02 -0700228 policy->getDispatcherConfiguration(&mConfig);
229
230 mThrottleState.minTimeBetweenEvents = 1000000000LL / mConfig.maxEventsPerSecond;
Jeff Brownae9fc032010-08-18 15:51:08 -0700231 mThrottleState.lastDeviceId = -1;
232
233#if DEBUG_THROTTLING
234 mThrottleState.originalSampleCount = 0;
Jeff Brown214eaf42011-05-26 19:17:02 -0700235 LOGD("Throttling - Max events per second = %d", mConfig.maxEventsPerSecond);
Jeff Brownae9fc032010-08-18 15:51:08 -0700236#endif
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700237}
238
239InputDispatcher::~InputDispatcher() {
Jeff Brownb88102f2010-09-08 11:49:43 -0700240 { // acquire lock
241 AutoMutex _l(mLock);
242
243 resetKeyRepeatLocked();
Jeff Brown54a18252010-09-16 14:07:33 -0700244 releasePendingEventLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -0700245 drainInboundQueueLocked();
246 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700247
248 while (mConnectionsByReceiveFd.size() != 0) {
249 unregisterInputChannel(mConnectionsByReceiveFd.valueAt(0)->inputChannel);
250 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700251}
252
253void InputDispatcher::dispatchOnce() {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700254 nsecs_t nextWakeupTime = LONG_LONG_MAX;
255 { // acquire lock
256 AutoMutex _l(mLock);
Jeff Brown214eaf42011-05-26 19:17:02 -0700257 dispatchOnceInnerLocked(&nextWakeupTime);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700258
Jeff Brownb88102f2010-09-08 11:49:43 -0700259 if (runCommandsLockedInterruptible()) {
260 nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700261 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700262 } // release lock
263
Jeff Brownb88102f2010-09-08 11:49:43 -0700264 // Wait for callback or timeout or wake. (make sure we round up, not down)
265 nsecs_t currentTime = now();
Jeff Brownaa3855d2011-03-17 01:34:19 -0700266 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
Jeff Brown4fe6c3e2010-09-13 23:17:30 -0700267 mLooper->pollOnce(timeoutMillis);
Jeff Brownb88102f2010-09-08 11:49:43 -0700268}
269
Jeff Brown214eaf42011-05-26 19:17:02 -0700270void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700271 nsecs_t currentTime = now();
272
273 // Reset the key repeat timer whenever we disallow key events, even if the next event
274 // is not a key. This is to ensure that we abort a key repeat if the device is just coming
275 // out of sleep.
Jeff Brown214eaf42011-05-26 19:17:02 -0700276 if (!mPolicy->isKeyRepeatEnabled()) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700277 resetKeyRepeatLocked();
278 }
279
Jeff Brownb88102f2010-09-08 11:49:43 -0700280 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
281 if (mDispatchFrozen) {
282#if DEBUG_FOCUS
283 LOGD("Dispatch frozen. Waiting some more.");
284#endif
285 return;
286 }
287
288 // Optimize latency of app switches.
289 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
290 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
291 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
292 if (mAppSwitchDueTime < *nextWakeupTime) {
293 *nextWakeupTime = mAppSwitchDueTime;
294 }
295
Jeff Brownb88102f2010-09-08 11:49:43 -0700296 // Ready to start a new event.
297 // If we don't already have a pending event, go grab one.
298 if (! mPendingEvent) {
299 if (mInboundQueue.isEmpty()) {
300 if (isAppSwitchDue) {
301 // The inbound queue is empty so the app switch key we were waiting
302 // for will never arrive. Stop waiting for it.
303 resetPendingAppSwitchLocked(false);
304 isAppSwitchDue = false;
305 }
306
307 // Synthesize a key repeat if appropriate.
308 if (mKeyRepeatState.lastKeyEntry) {
309 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
Jeff Brown214eaf42011-05-26 19:17:02 -0700310 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700311 } else {
312 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
313 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
314 }
315 }
316 }
317 if (! mPendingEvent) {
318 return;
319 }
320 } else {
321 // Inbound queue has at least one entry.
322 EventEntry* entry = mInboundQueue.headSentinel.next;
323
324 // Throttle the entry if it is a move event and there are no
325 // other events behind it in the queue. Due to movement batching, additional
326 // samples may be appended to this event by the time the throttling timeout
327 // expires.
328 // TODO Make this smarter and consider throttling per device independently.
Jeff Brownb6997262010-10-08 22:31:17 -0700329 if (entry->type == EventEntry::TYPE_MOTION
330 && !isAppSwitchDue
331 && mDispatchEnabled
332 && (entry->policyFlags & POLICY_FLAG_PASS_TO_USER)
333 && !entry->isInjected()) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700334 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
335 int32_t deviceId = motionEntry->deviceId;
336 uint32_t source = motionEntry->source;
337 if (! isAppSwitchDue
338 && motionEntry->next == & mInboundQueue.tailSentinel // exactly one event
Jeff Browncc0c1592011-02-19 05:07:28 -0800339 && (motionEntry->action == AMOTION_EVENT_ACTION_MOVE
340 || motionEntry->action == AMOTION_EVENT_ACTION_HOVER_MOVE)
Jeff Brownb88102f2010-09-08 11:49:43 -0700341 && deviceId == mThrottleState.lastDeviceId
342 && source == mThrottleState.lastSource) {
343 nsecs_t nextTime = mThrottleState.lastEventTime
344 + mThrottleState.minTimeBetweenEvents;
345 if (currentTime < nextTime) {
346 // Throttle it!
347#if DEBUG_THROTTLING
348 LOGD("Throttling - Delaying motion event for "
Jeff Brown90655042010-12-02 13:50:46 -0800349 "device %d, source 0x%08x by up to %0.3fms.",
Jeff Brownb88102f2010-09-08 11:49:43 -0700350 deviceId, source, (nextTime - currentTime) * 0.000001);
351#endif
352 if (nextTime < *nextWakeupTime) {
353 *nextWakeupTime = nextTime;
354 }
355 if (mThrottleState.originalSampleCount == 0) {
356 mThrottleState.originalSampleCount =
357 motionEntry->countSamples();
358 }
359 return;
360 }
361 }
362
363#if DEBUG_THROTTLING
364 if (mThrottleState.originalSampleCount != 0) {
365 uint32_t count = motionEntry->countSamples();
366 LOGD("Throttling - Motion event sample count grew by %d from %d to %d.",
367 count - mThrottleState.originalSampleCount,
368 mThrottleState.originalSampleCount, count);
369 mThrottleState.originalSampleCount = 0;
370 }
371#endif
372
makarand.karvekarf634ded2011-03-02 15:41:03 -0600373 mThrottleState.lastEventTime = currentTime;
Jeff Brownb88102f2010-09-08 11:49:43 -0700374 mThrottleState.lastDeviceId = deviceId;
375 mThrottleState.lastSource = source;
376 }
377
378 mInboundQueue.dequeue(entry);
379 mPendingEvent = entry;
380 }
Jeff Browne2fe69e2010-10-18 13:21:23 -0700381
382 // Poke user activity for this event.
383 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
384 pokeUserActivityLocked(mPendingEvent);
385 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700386 }
387
388 // Now we have an event to dispatch.
Jeff Brown928e0542011-01-10 11:17:36 -0800389 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Jeff Brownb6110c22011-04-01 16:15:13 -0700390 LOG_ASSERT(mPendingEvent != NULL);
Jeff Brown54a18252010-09-16 14:07:33 -0700391 bool done = false;
Jeff Brownb6997262010-10-08 22:31:17 -0700392 DropReason dropReason = DROP_REASON_NOT_DROPPED;
393 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
394 dropReason = DROP_REASON_POLICY;
395 } else if (!mDispatchEnabled) {
396 dropReason = DROP_REASON_DISABLED;
397 }
Jeff Brown928e0542011-01-10 11:17:36 -0800398
399 if (mNextUnblockedEvent == mPendingEvent) {
400 mNextUnblockedEvent = NULL;
401 }
402
Jeff Brownb88102f2010-09-08 11:49:43 -0700403 switch (mPendingEvent->type) {
404 case EventEntry::TYPE_CONFIGURATION_CHANGED: {
405 ConfigurationChangedEntry* typedEntry =
406 static_cast<ConfigurationChangedEntry*>(mPendingEvent);
Jeff Brown54a18252010-09-16 14:07:33 -0700407 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Jeff Brownb6997262010-10-08 22:31:17 -0700408 dropReason = DROP_REASON_NOT_DROPPED; // configuration changes are never dropped
Jeff Brownb88102f2010-09-08 11:49:43 -0700409 break;
410 }
411
412 case EventEntry::TYPE_KEY: {
413 KeyEntry* typedEntry = static_cast<KeyEntry*>(mPendingEvent);
Jeff Brownb6997262010-10-08 22:31:17 -0700414 if (isAppSwitchDue) {
415 if (isAppSwitchKeyEventLocked(typedEntry)) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700416 resetPendingAppSwitchLocked(true);
Jeff Brownb6997262010-10-08 22:31:17 -0700417 isAppSwitchDue = false;
418 } else if (dropReason == DROP_REASON_NOT_DROPPED) {
419 dropReason = DROP_REASON_APP_SWITCH;
Jeff Brownb88102f2010-09-08 11:49:43 -0700420 }
421 }
Jeff Brown928e0542011-01-10 11:17:36 -0800422 if (dropReason == DROP_REASON_NOT_DROPPED
423 && isStaleEventLocked(currentTime, typedEntry)) {
424 dropReason = DROP_REASON_STALE;
425 }
426 if (dropReason == DROP_REASON_NOT_DROPPED && mNextUnblockedEvent) {
427 dropReason = DROP_REASON_BLOCKED;
428 }
Jeff Brown214eaf42011-05-26 19:17:02 -0700429 done = dispatchKeyLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700430 break;
431 }
432
433 case EventEntry::TYPE_MOTION: {
434 MotionEntry* typedEntry = static_cast<MotionEntry*>(mPendingEvent);
Jeff Brownb6997262010-10-08 22:31:17 -0700435 if (dropReason == DROP_REASON_NOT_DROPPED && isAppSwitchDue) {
436 dropReason = DROP_REASON_APP_SWITCH;
Jeff Brownb88102f2010-09-08 11:49:43 -0700437 }
Jeff Brown928e0542011-01-10 11:17:36 -0800438 if (dropReason == DROP_REASON_NOT_DROPPED
439 && isStaleEventLocked(currentTime, typedEntry)) {
440 dropReason = DROP_REASON_STALE;
441 }
442 if (dropReason == DROP_REASON_NOT_DROPPED && mNextUnblockedEvent) {
443 dropReason = DROP_REASON_BLOCKED;
444 }
Jeff Brownb6997262010-10-08 22:31:17 -0700445 done = dispatchMotionLocked(currentTime, typedEntry,
Jeff Browne20c9e02010-10-11 14:20:19 -0700446 &dropReason, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700447 break;
448 }
449
450 default:
Jeff Brownb6110c22011-04-01 16:15:13 -0700451 LOG_ASSERT(false);
Jeff Brownb88102f2010-09-08 11:49:43 -0700452 break;
453 }
454
Jeff Brown54a18252010-09-16 14:07:33 -0700455 if (done) {
Jeff Brownb6997262010-10-08 22:31:17 -0700456 if (dropReason != DROP_REASON_NOT_DROPPED) {
457 dropInboundEventLocked(mPendingEvent, dropReason);
458 }
459
Jeff Brown54a18252010-09-16 14:07:33 -0700460 releasePendingEventLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -0700461 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
462 }
463}
464
465bool InputDispatcher::enqueueInboundEventLocked(EventEntry* entry) {
466 bool needWake = mInboundQueue.isEmpty();
467 mInboundQueue.enqueueAtTail(entry);
468
469 switch (entry->type) {
Jeff Brownb6997262010-10-08 22:31:17 -0700470 case EventEntry::TYPE_KEY: {
Jeff Brown928e0542011-01-10 11:17:36 -0800471 // Optimize app switch latency.
472 // If the application takes too long to catch up then we drop all events preceding
473 // the app switch key.
Jeff Brownb6997262010-10-08 22:31:17 -0700474 KeyEntry* keyEntry = static_cast<KeyEntry*>(entry);
475 if (isAppSwitchKeyEventLocked(keyEntry)) {
476 if (keyEntry->action == AKEY_EVENT_ACTION_DOWN) {
477 mAppSwitchSawKeyDown = true;
478 } else if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
479 if (mAppSwitchSawKeyDown) {
480#if DEBUG_APP_SWITCH
481 LOGD("App switch is pending!");
482#endif
483 mAppSwitchDueTime = keyEntry->eventTime + APP_SWITCH_TIMEOUT;
484 mAppSwitchSawKeyDown = false;
485 needWake = true;
486 }
487 }
488 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700489 break;
490 }
Jeff Brown928e0542011-01-10 11:17:36 -0800491
492 case EventEntry::TYPE_MOTION: {
493 // Optimize case where the current application is unresponsive and the user
494 // decides to touch a window in a different application.
495 // If the application takes too long to catch up then we drop all events preceding
496 // the touch into the other window.
497 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
Jeff Brown33bbfd22011-02-24 20:55:35 -0800498 if (motionEntry->action == AMOTION_EVENT_ACTION_DOWN
Jeff Brown928e0542011-01-10 11:17:36 -0800499 && (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER)
500 && mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY
Jeff Brown9302c872011-07-13 22:51:29 -0700501 && mInputTargetWaitApplicationHandle != NULL) {
Jeff Brown91c69ab2011-02-14 17:03:18 -0800502 int32_t x = int32_t(motionEntry->firstSample.pointerCoords[0].
Jeff Brownebbd5d12011-02-17 13:01:34 -0800503 getAxisValue(AMOTION_EVENT_AXIS_X));
Jeff Brown91c69ab2011-02-14 17:03:18 -0800504 int32_t y = int32_t(motionEntry->firstSample.pointerCoords[0].
Jeff Brownebbd5d12011-02-17 13:01:34 -0800505 getAxisValue(AMOTION_EVENT_AXIS_Y));
Jeff Brown9302c872011-07-13 22:51:29 -0700506 sp<InputWindowHandle> touchedWindowHandle = findTouchedWindowAtLocked(x, y);
507 if (touchedWindowHandle != NULL
508 && touchedWindowHandle->inputApplicationHandle
509 != mInputTargetWaitApplicationHandle) {
Jeff Brown928e0542011-01-10 11:17:36 -0800510 // User touched a different application than the one we are waiting on.
511 // Flag the event, and start pruning the input queue.
512 mNextUnblockedEvent = motionEntry;
513 needWake = true;
514 }
515 }
516 break;
517 }
Jeff Brownb6997262010-10-08 22:31:17 -0700518 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700519
520 return needWake;
521}
522
Jeff Brown9302c872011-07-13 22:51:29 -0700523sp<InputWindowHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t x, int32_t y) {
Jeff Brown928e0542011-01-10 11:17:36 -0800524 // Traverse windows from front to back to find touched window.
Jeff Brown9302c872011-07-13 22:51:29 -0700525 size_t numWindows = mWindowHandles.size();
Jeff Brown928e0542011-01-10 11:17:36 -0800526 for (size_t i = 0; i < numWindows; i++) {
Jeff Brown9302c872011-07-13 22:51:29 -0700527 sp<InputWindowHandle> windowHandle = mWindowHandles.itemAt(i);
528 int32_t flags = windowHandle->layoutParamsFlags;
Jeff Brown928e0542011-01-10 11:17:36 -0800529
Jeff Brown9302c872011-07-13 22:51:29 -0700530 if (windowHandle->visible) {
531 if (!(flags & InputWindowHandle::FLAG_NOT_TOUCHABLE)) {
532 bool isTouchModal = (flags & (InputWindowHandle::FLAG_NOT_FOCUSABLE
533 | InputWindowHandle::FLAG_NOT_TOUCH_MODAL)) == 0;
534 if (isTouchModal || windowHandle->touchableRegionContainsPoint(x, y)) {
Jeff Brown928e0542011-01-10 11:17:36 -0800535 // Found window.
Jeff Brown9302c872011-07-13 22:51:29 -0700536 return windowHandle;
Jeff Brown928e0542011-01-10 11:17:36 -0800537 }
538 }
539 }
540
Jeff Brown9302c872011-07-13 22:51:29 -0700541 if (flags & InputWindowHandle::FLAG_SYSTEM_ERROR) {
Jeff Brown928e0542011-01-10 11:17:36 -0800542 // Error window is on top but not visible, so touch is dropped.
543 return NULL;
544 }
545 }
546 return NULL;
547}
548
Jeff Brownb6997262010-10-08 22:31:17 -0700549void InputDispatcher::dropInboundEventLocked(EventEntry* entry, DropReason dropReason) {
550 const char* reason;
551 switch (dropReason) {
552 case DROP_REASON_POLICY:
Jeff Browne20c9e02010-10-11 14:20:19 -0700553#if DEBUG_INBOUND_EVENT_DETAILS
Jeff Brown3122e442010-10-11 23:32:49 -0700554 LOGD("Dropped event because policy consumed it.");
Jeff Browne20c9e02010-10-11 14:20:19 -0700555#endif
Jeff Brown3122e442010-10-11 23:32:49 -0700556 reason = "inbound event was dropped because the policy consumed it";
Jeff Brownb6997262010-10-08 22:31:17 -0700557 break;
558 case DROP_REASON_DISABLED:
559 LOGI("Dropped event because input dispatch is disabled.");
560 reason = "inbound event was dropped because input dispatch is disabled";
561 break;
562 case DROP_REASON_APP_SWITCH:
563 LOGI("Dropped event because of pending overdue app switch.");
564 reason = "inbound event was dropped because of pending overdue app switch";
565 break;
Jeff Brown928e0542011-01-10 11:17:36 -0800566 case DROP_REASON_BLOCKED:
567 LOGI("Dropped event because the current application is not responding and the user "
Jeff Brown81346812011-06-28 20:08:48 -0700568 "has started interacting with a different application.");
Jeff Brown928e0542011-01-10 11:17:36 -0800569 reason = "inbound event was dropped because the current application is not responding "
Jeff Brown81346812011-06-28 20:08:48 -0700570 "and the user has started interacting with a different application";
Jeff Brown928e0542011-01-10 11:17:36 -0800571 break;
572 case DROP_REASON_STALE:
573 LOGI("Dropped event because it is stale.");
574 reason = "inbound event was dropped because it is stale";
575 break;
Jeff Brownb6997262010-10-08 22:31:17 -0700576 default:
Jeff Brownb6110c22011-04-01 16:15:13 -0700577 LOG_ASSERT(false);
Jeff Brownb6997262010-10-08 22:31:17 -0700578 return;
579 }
580
581 switch (entry->type) {
Jeff Brownda3d5a92011-03-29 15:11:34 -0700582 case EventEntry::TYPE_KEY: {
583 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
584 synthesizeCancelationEventsForAllConnectionsLocked(options);
Jeff Brownb6997262010-10-08 22:31:17 -0700585 break;
Jeff Brownda3d5a92011-03-29 15:11:34 -0700586 }
Jeff Brownb6997262010-10-08 22:31:17 -0700587 case EventEntry::TYPE_MOTION: {
588 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
589 if (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) {
Jeff Brownda3d5a92011-03-29 15:11:34 -0700590 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
591 synthesizeCancelationEventsForAllConnectionsLocked(options);
Jeff Brownb6997262010-10-08 22:31:17 -0700592 } else {
Jeff Brownda3d5a92011-03-29 15:11:34 -0700593 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
594 synthesizeCancelationEventsForAllConnectionsLocked(options);
Jeff Brownb6997262010-10-08 22:31:17 -0700595 }
596 break;
597 }
598 }
599}
600
601bool InputDispatcher::isAppSwitchKeyCode(int32_t keyCode) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700602 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL;
603}
604
Jeff Brownb6997262010-10-08 22:31:17 -0700605bool InputDispatcher::isAppSwitchKeyEventLocked(KeyEntry* keyEntry) {
606 return ! (keyEntry->flags & AKEY_EVENT_FLAG_CANCELED)
607 && isAppSwitchKeyCode(keyEntry->keyCode)
Jeff Browne20c9e02010-10-11 14:20:19 -0700608 && (keyEntry->policyFlags & POLICY_FLAG_TRUSTED)
Jeff Brownb6997262010-10-08 22:31:17 -0700609 && (keyEntry->policyFlags & POLICY_FLAG_PASS_TO_USER);
610}
611
Jeff Brownb88102f2010-09-08 11:49:43 -0700612bool InputDispatcher::isAppSwitchPendingLocked() {
613 return mAppSwitchDueTime != LONG_LONG_MAX;
614}
615
Jeff Brownb88102f2010-09-08 11:49:43 -0700616void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
617 mAppSwitchDueTime = LONG_LONG_MAX;
618
619#if DEBUG_APP_SWITCH
620 if (handled) {
621 LOGD("App switch has arrived.");
622 } else {
623 LOGD("App switch was abandoned.");
624 }
625#endif
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700626}
627
Jeff Brown928e0542011-01-10 11:17:36 -0800628bool InputDispatcher::isStaleEventLocked(nsecs_t currentTime, EventEntry* entry) {
629 return currentTime - entry->eventTime >= STALE_EVENT_TIMEOUT;
630}
631
Jeff Brown9c3cda02010-06-15 01:31:58 -0700632bool InputDispatcher::runCommandsLockedInterruptible() {
633 if (mCommandQueue.isEmpty()) {
634 return false;
635 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700636
Jeff Brown9c3cda02010-06-15 01:31:58 -0700637 do {
638 CommandEntry* commandEntry = mCommandQueue.dequeueAtHead();
639
640 Command command = commandEntry->command;
641 (this->*command)(commandEntry); // commands are implicitly 'LockedInterruptible'
642
Jeff Brown7fbdc842010-06-17 20:52:56 -0700643 commandEntry->connection.clear();
Jeff Brown9c3cda02010-06-15 01:31:58 -0700644 mAllocator.releaseCommandEntry(commandEntry);
645 } while (! mCommandQueue.isEmpty());
646 return true;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700647}
648
Jeff Brown9c3cda02010-06-15 01:31:58 -0700649InputDispatcher::CommandEntry* InputDispatcher::postCommandLocked(Command command) {
650 CommandEntry* commandEntry = mAllocator.obtainCommandEntry(command);
651 mCommandQueue.enqueueAtTail(commandEntry);
652 return commandEntry;
653}
654
Jeff Brownb88102f2010-09-08 11:49:43 -0700655void InputDispatcher::drainInboundQueueLocked() {
656 while (! mInboundQueue.isEmpty()) {
657 EventEntry* entry = mInboundQueue.dequeueAtHead();
Jeff Brown54a18252010-09-16 14:07:33 -0700658 releaseInboundEventLocked(entry);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700659 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700660}
661
Jeff Brown54a18252010-09-16 14:07:33 -0700662void InputDispatcher::releasePendingEventLocked() {
Jeff Brownb88102f2010-09-08 11:49:43 -0700663 if (mPendingEvent) {
Jeff Brown54a18252010-09-16 14:07:33 -0700664 releaseInboundEventLocked(mPendingEvent);
Jeff Brownb88102f2010-09-08 11:49:43 -0700665 mPendingEvent = NULL;
666 }
667}
668
Jeff Brown54a18252010-09-16 14:07:33 -0700669void InputDispatcher::releaseInboundEventLocked(EventEntry* entry) {
Jeff Brown01ce2e92010-09-26 22:20:12 -0700670 InjectionState* injectionState = entry->injectionState;
671 if (injectionState && injectionState->injectionResult == INPUT_EVENT_INJECTION_PENDING) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700672#if DEBUG_DISPATCH_CYCLE
Jeff Brown01ce2e92010-09-26 22:20:12 -0700673 LOGD("Injected inbound event was dropped.");
Jeff Brownb88102f2010-09-08 11:49:43 -0700674#endif
675 setInjectionResultLocked(entry, INPUT_EVENT_INJECTION_FAILED);
676 }
677 mAllocator.releaseEventEntry(entry);
678}
679
Jeff Brownb88102f2010-09-08 11:49:43 -0700680void InputDispatcher::resetKeyRepeatLocked() {
681 if (mKeyRepeatState.lastKeyEntry) {
682 mAllocator.releaseKeyEntry(mKeyRepeatState.lastKeyEntry);
683 mKeyRepeatState.lastKeyEntry = NULL;
684 }
685}
686
Jeff Brown214eaf42011-05-26 19:17:02 -0700687InputDispatcher::KeyEntry* InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
Jeff Brown349703e2010-06-22 01:27:15 -0700688 KeyEntry* entry = mKeyRepeatState.lastKeyEntry;
689
Jeff Brown349703e2010-06-22 01:27:15 -0700690 // Reuse the repeated key entry if it is otherwise unreferenced.
Jeff Browne20c9e02010-10-11 14:20:19 -0700691 uint32_t policyFlags = (entry->policyFlags & POLICY_FLAG_RAW_MASK)
692 | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700693 if (entry->refCount == 1) {
Jeff Brown01ce2e92010-09-26 22:20:12 -0700694 mAllocator.recycleKeyEntry(entry);
Jeff Brown7fbdc842010-06-17 20:52:56 -0700695 entry->eventTime = currentTime;
Jeff Brown7fbdc842010-06-17 20:52:56 -0700696 entry->policyFlags = policyFlags;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700697 entry->repeatCount += 1;
698 } else {
Jeff Brown7fbdc842010-06-17 20:52:56 -0700699 KeyEntry* newEntry = mAllocator.obtainKeyEntry(currentTime,
Jeff Brownc5ed5912010-07-14 18:48:53 -0700700 entry->deviceId, entry->source, policyFlags,
Jeff Brown7fbdc842010-06-17 20:52:56 -0700701 entry->action, entry->flags, entry->keyCode, entry->scanCode,
Jeff Brown00fa7bd2010-07-02 15:37:36 -0700702 entry->metaState, entry->repeatCount + 1, entry->downTime);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700703
704 mKeyRepeatState.lastKeyEntry = newEntry;
705 mAllocator.releaseKeyEntry(entry);
706
707 entry = newEntry;
708 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700709 entry->syntheticRepeat = true;
710
711 // Increment reference count since we keep a reference to the event in
712 // mKeyRepeatState.lastKeyEntry in addition to the one we return.
713 entry->refCount += 1;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700714
Jeff Brown214eaf42011-05-26 19:17:02 -0700715 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Jeff Brownb88102f2010-09-08 11:49:43 -0700716 return entry;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700717}
718
Jeff Brownb88102f2010-09-08 11:49:43 -0700719bool InputDispatcher::dispatchConfigurationChangedLocked(
720 nsecs_t currentTime, ConfigurationChangedEntry* entry) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700721#if DEBUG_OUTBOUND_EVENT_DETAILS
Jeff Brownb88102f2010-09-08 11:49:43 -0700722 LOGD("dispatchConfigurationChanged - eventTime=%lld", entry->eventTime);
723#endif
724
725 // Reset key repeating in case a keyboard device was added or removed or something.
726 resetKeyRepeatLocked();
727
728 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
729 CommandEntry* commandEntry = postCommandLocked(
730 & InputDispatcher::doNotifyConfigurationChangedInterruptible);
731 commandEntry->eventTime = entry->eventTime;
732 return true;
733}
734
Jeff Brown214eaf42011-05-26 19:17:02 -0700735bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, KeyEntry* entry,
Jeff Browne20c9e02010-10-11 14:20:19 -0700736 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Jeff Browne46a0a42010-11-02 17:58:22 -0700737 // Preprocessing.
738 if (! entry->dispatchInProgress) {
739 if (entry->repeatCount == 0
740 && entry->action == AKEY_EVENT_ACTION_DOWN
741 && (entry->policyFlags & POLICY_FLAG_TRUSTED)
Jeff Brown0029c662011-03-30 02:25:18 -0700742 && (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
Jeff Browne46a0a42010-11-02 17:58:22 -0700743 if (mKeyRepeatState.lastKeyEntry
744 && mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode) {
745 // We have seen two identical key downs in a row which indicates that the device
746 // driver is automatically generating key repeats itself. We take note of the
747 // repeat here, but we disable our own next key repeat timer since it is clear that
748 // we will not need to synthesize key repeats ourselves.
749 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
750 resetKeyRepeatLocked();
751 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
752 } else {
753 // Not a repeat. Save key down state in case we do see a repeat later.
754 resetKeyRepeatLocked();
Jeff Brown214eaf42011-05-26 19:17:02 -0700755 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
Jeff Browne46a0a42010-11-02 17:58:22 -0700756 }
757 mKeyRepeatState.lastKeyEntry = entry;
758 entry->refCount += 1;
759 } else if (! entry->syntheticRepeat) {
760 resetKeyRepeatLocked();
761 }
762
Jeff Browne2e01262011-03-02 20:34:30 -0800763 if (entry->repeatCount == 1) {
764 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
765 } else {
766 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
767 }
768
Jeff Browne46a0a42010-11-02 17:58:22 -0700769 entry->dispatchInProgress = true;
770 resetTargetsLocked();
771
772 logOutboundKeyDetailsLocked("dispatchKey - ", entry);
773 }
774
Jeff Brown54a18252010-09-16 14:07:33 -0700775 // Give the policy a chance to intercept the key.
776 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
Jeff Browne20c9e02010-10-11 14:20:19 -0700777 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Jeff Brown54a18252010-09-16 14:07:33 -0700778 CommandEntry* commandEntry = postCommandLocked(
779 & InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
Jeff Brown9302c872011-07-13 22:51:29 -0700780 if (mFocusedWindowHandle != NULL) {
781 commandEntry->inputWindowHandle = mFocusedWindowHandle;
Jeff Brown54a18252010-09-16 14:07:33 -0700782 }
783 commandEntry->keyEntry = entry;
784 entry->refCount += 1;
785 return false; // wait for the command to run
786 } else {
787 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
788 }
789 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Jeff Browne20c9e02010-10-11 14:20:19 -0700790 if (*dropReason == DROP_REASON_NOT_DROPPED) {
791 *dropReason = DROP_REASON_POLICY;
792 }
Jeff Brown54a18252010-09-16 14:07:33 -0700793 }
794
795 // Clean up if dropping the event.
Jeff Browne20c9e02010-10-11 14:20:19 -0700796 if (*dropReason != DROP_REASON_NOT_DROPPED) {
Jeff Brown54a18252010-09-16 14:07:33 -0700797 resetTargetsLocked();
Jeff Brown3122e442010-10-11 23:32:49 -0700798 setInjectionResultLocked(entry, *dropReason == DROP_REASON_POLICY
799 ? INPUT_EVENT_INJECTION_SUCCEEDED : INPUT_EVENT_INJECTION_FAILED);
Jeff Brown54a18252010-09-16 14:07:33 -0700800 return true;
801 }
802
Jeff Brownb88102f2010-09-08 11:49:43 -0700803 // Identify targets.
804 if (! mCurrentInputTargetsValid) {
Jeff Brown01ce2e92010-09-26 22:20:12 -0700805 int32_t injectionResult = findFocusedWindowTargetsLocked(currentTime,
806 entry, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700807 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
808 return false;
809 }
810
811 setInjectionResultLocked(entry, injectionResult);
812 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
813 return true;
814 }
815
816 addMonitoringTargetsLocked();
Jeff Brown01ce2e92010-09-26 22:20:12 -0700817 commitTargetsLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -0700818 }
819
820 // Dispatch the key.
821 dispatchEventToCurrentInputTargetsLocked(currentTime, entry, false);
Jeff Brownb88102f2010-09-08 11:49:43 -0700822 return true;
823}
824
825void InputDispatcher::logOutboundKeyDetailsLocked(const char* prefix, const KeyEntry* entry) {
826#if DEBUG_OUTBOUND_EVENT_DETAILS
Jeff Brown90655042010-12-02 13:50:46 -0800827 LOGD("%seventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, "
Jeff Brownb88102f2010-09-08 11:49:43 -0700828 "action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, "
Jeff Browne46a0a42010-11-02 17:58:22 -0700829 "repeatCount=%d, downTime=%lld",
Jeff Brownb88102f2010-09-08 11:49:43 -0700830 prefix,
831 entry->eventTime, entry->deviceId, entry->source, entry->policyFlags,
832 entry->action, entry->flags, entry->keyCode, entry->scanCode, entry->metaState,
Jeff Browne46a0a42010-11-02 17:58:22 -0700833 entry->repeatCount, entry->downTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700834#endif
835}
836
837bool InputDispatcher::dispatchMotionLocked(
Jeff Browne20c9e02010-10-11 14:20:19 -0700838 nsecs_t currentTime, MotionEntry* entry, DropReason* dropReason, nsecs_t* nextWakeupTime) {
Jeff Browne46a0a42010-11-02 17:58:22 -0700839 // Preprocessing.
840 if (! entry->dispatchInProgress) {
841 entry->dispatchInProgress = true;
842 resetTargetsLocked();
843
844 logOutboundMotionDetailsLocked("dispatchMotion - ", entry);
845 }
846
Jeff Brown54a18252010-09-16 14:07:33 -0700847 // Clean up if dropping the event.
Jeff Browne20c9e02010-10-11 14:20:19 -0700848 if (*dropReason != DROP_REASON_NOT_DROPPED) {
Jeff Brown54a18252010-09-16 14:07:33 -0700849 resetTargetsLocked();
Jeff Brown3122e442010-10-11 23:32:49 -0700850 setInjectionResultLocked(entry, *dropReason == DROP_REASON_POLICY
851 ? INPUT_EVENT_INJECTION_SUCCEEDED : INPUT_EVENT_INJECTION_FAILED);
Jeff Brown54a18252010-09-16 14:07:33 -0700852 return true;
853 }
854
Jeff Brownb88102f2010-09-08 11:49:43 -0700855 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
856
857 // Identify targets.
Jeff Browncc0c1592011-02-19 05:07:28 -0800858 bool conflictingPointerActions = false;
Jeff Brownb88102f2010-09-08 11:49:43 -0700859 if (! mCurrentInputTargetsValid) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700860 int32_t injectionResult;
Jeff Browna032cc02011-03-07 16:56:21 -0800861 const MotionSample* splitBatchAfterSample = NULL;
Jeff Brownb88102f2010-09-08 11:49:43 -0700862 if (isPointerEvent) {
863 // Pointer event. (eg. touchscreen)
Jeff Brown01ce2e92010-09-26 22:20:12 -0700864 injectionResult = findTouchedWindowTargetsLocked(currentTime,
Jeff Browna032cc02011-03-07 16:56:21 -0800865 entry, nextWakeupTime, &conflictingPointerActions, &splitBatchAfterSample);
Jeff Brownb88102f2010-09-08 11:49:43 -0700866 } else {
867 // Non touch event. (eg. trackball)
Jeff Brown01ce2e92010-09-26 22:20:12 -0700868 injectionResult = findFocusedWindowTargetsLocked(currentTime,
869 entry, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700870 }
871 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
872 return false;
873 }
874
875 setInjectionResultLocked(entry, injectionResult);
876 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
877 return true;
878 }
879
880 addMonitoringTargetsLocked();
Jeff Brown01ce2e92010-09-26 22:20:12 -0700881 commitTargetsLocked();
Jeff Browna032cc02011-03-07 16:56:21 -0800882
883 // Unbatch the event if necessary by splitting it into two parts after the
884 // motion sample indicated by splitBatchAfterSample.
885 if (splitBatchAfterSample && splitBatchAfterSample->next) {
886#if DEBUG_BATCHING
887 uint32_t originalSampleCount = entry->countSamples();
888#endif
889 MotionSample* nextSample = splitBatchAfterSample->next;
890 MotionEntry* nextEntry = mAllocator.obtainMotionEntry(nextSample->eventTime,
891 entry->deviceId, entry->source, entry->policyFlags,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700892 entry->action, entry->flags,
893 entry->metaState, entry->buttonState, entry->edgeFlags,
Jeff Browna032cc02011-03-07 16:56:21 -0800894 entry->xPrecision, entry->yPrecision, entry->downTime,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700895 entry->pointerCount, entry->pointerProperties, nextSample->pointerCoords);
Jeff Browna032cc02011-03-07 16:56:21 -0800896 if (nextSample != entry->lastSample) {
897 nextEntry->firstSample.next = nextSample->next;
898 nextEntry->lastSample = entry->lastSample;
899 }
900 mAllocator.freeMotionSample(nextSample);
901
902 entry->lastSample = const_cast<MotionSample*>(splitBatchAfterSample);
903 entry->lastSample->next = NULL;
904
905 if (entry->injectionState) {
906 nextEntry->injectionState = entry->injectionState;
907 entry->injectionState->refCount += 1;
908 }
909
910#if DEBUG_BATCHING
911 LOGD("Split batch of %d samples into two parts, first part has %d samples, "
912 "second part has %d samples.", originalSampleCount,
913 entry->countSamples(), nextEntry->countSamples());
914#endif
915
916 mInboundQueue.enqueueAtHead(nextEntry);
917 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700918 }
919
920 // Dispatch the motion.
Jeff Browncc0c1592011-02-19 05:07:28 -0800921 if (conflictingPointerActions) {
Jeff Brownda3d5a92011-03-29 15:11:34 -0700922 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
923 "conflicting pointer actions");
924 synthesizeCancelationEventsForAllConnectionsLocked(options);
Jeff Browncc0c1592011-02-19 05:07:28 -0800925 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700926 dispatchEventToCurrentInputTargetsLocked(currentTime, entry, false);
Jeff Brownb88102f2010-09-08 11:49:43 -0700927 return true;
928}
929
930
931void InputDispatcher::logOutboundMotionDetailsLocked(const char* prefix, const MotionEntry* entry) {
932#if DEBUG_OUTBOUND_EVENT_DETAILS
Jeff Brown90655042010-12-02 13:50:46 -0800933 LOGD("%seventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, "
Jeff Brown85a31762010-09-01 17:01:00 -0700934 "action=0x%x, flags=0x%x, "
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700935 "metaState=0x%x, buttonState=0x%x, "
936 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%lld",
Jeff Brownb88102f2010-09-08 11:49:43 -0700937 prefix,
Jeff Brown85a31762010-09-01 17:01:00 -0700938 entry->eventTime, entry->deviceId, entry->source, entry->policyFlags,
939 entry->action, entry->flags,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700940 entry->metaState, entry->buttonState,
941 entry->edgeFlags, entry->xPrecision, entry->yPrecision,
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700942 entry->downTime);
943
944 // Print the most recent sample that we have available, this may change due to batching.
945 size_t sampleCount = 1;
Jeff Brownb88102f2010-09-08 11:49:43 -0700946 const MotionSample* sample = & entry->firstSample;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700947 for (; sample->next != NULL; sample = sample->next) {
948 sampleCount += 1;
949 }
950 for (uint32_t i = 0; i < entry->pointerCount; i++) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700951 LOGD(" Pointer %d: id=%d, toolType=%d, "
952 "x=%f, y=%f, pressure=%f, size=%f, "
Jeff Brown85a31762010-09-01 17:01:00 -0700953 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
Jeff Brown8d608662010-08-30 03:02:23 -0700954 "orientation=%f",
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700955 i, entry->pointerProperties[i].id,
956 entry->pointerProperties[i].toolType,
Jeff Brownebbd5d12011-02-17 13:01:34 -0800957 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
958 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
959 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
960 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
961 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
962 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
963 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
964 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
965 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700966 }
967
968 // Keep in mind that due to batching, it is possible for the number of samples actually
969 // dispatched to change before the application finally consumed them.
Jeff Brownc5ed5912010-07-14 18:48:53 -0700970 if (entry->action == AMOTION_EVENT_ACTION_MOVE) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700971 LOGD(" ... Total movement samples currently batched %d ...", sampleCount);
972 }
973#endif
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700974}
975
976void InputDispatcher::dispatchEventToCurrentInputTargetsLocked(nsecs_t currentTime,
977 EventEntry* eventEntry, bool resumeWithAppendedMotionSample) {
978#if DEBUG_DISPATCH_CYCLE
Jeff Brown9c3cda02010-06-15 01:31:58 -0700979 LOGD("dispatchEventToCurrentInputTargets - "
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700980 "resumeWithAppendedMotionSample=%s",
Jeff Brownb88102f2010-09-08 11:49:43 -0700981 toString(resumeWithAppendedMotionSample));
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700982#endif
983
Jeff Brownb6110c22011-04-01 16:15:13 -0700984 LOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
Jeff Brown9c3cda02010-06-15 01:31:58 -0700985
Jeff Browne2fe69e2010-10-18 13:21:23 -0700986 pokeUserActivityLocked(eventEntry);
987
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700988 for (size_t i = 0; i < mCurrentInputTargets.size(); i++) {
989 const InputTarget& inputTarget = mCurrentInputTargets.itemAt(i);
990
Jeff Brown519e0242010-09-15 15:18:56 -0700991 ssize_t connectionIndex = getConnectionIndexLocked(inputTarget.inputChannel);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700992 if (connectionIndex >= 0) {
993 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
Jeff Brown7fbdc842010-06-17 20:52:56 -0700994 prepareDispatchCycleLocked(currentTime, connection, eventEntry, & inputTarget,
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700995 resumeWithAppendedMotionSample);
996 } else {
Jeff Brownb6997262010-10-08 22:31:17 -0700997#if DEBUG_FOCUS
998 LOGD("Dropping event delivery to target with channel '%s' because it "
999 "is no longer registered with the input dispatcher.",
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001000 inputTarget.inputChannel->getName().string());
Jeff Brownb6997262010-10-08 22:31:17 -07001001#endif
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001002 }
1003 }
1004}
1005
Jeff Brown54a18252010-09-16 14:07:33 -07001006void InputDispatcher::resetTargetsLocked() {
Jeff Brownb88102f2010-09-08 11:49:43 -07001007 mCurrentInputTargetsValid = false;
1008 mCurrentInputTargets.clear();
Jeff Brownb88102f2010-09-08 11:49:43 -07001009 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_NONE;
Jeff Brown9302c872011-07-13 22:51:29 -07001010 mInputTargetWaitApplicationHandle.clear();
Jeff Brownb88102f2010-09-08 11:49:43 -07001011}
1012
Jeff Brown01ce2e92010-09-26 22:20:12 -07001013void InputDispatcher::commitTargetsLocked() {
Jeff Brownb88102f2010-09-08 11:49:43 -07001014 mCurrentInputTargetsValid = true;
1015}
1016
1017int32_t InputDispatcher::handleTargetsNotReadyLocked(nsecs_t currentTime,
Jeff Brown9302c872011-07-13 22:51:29 -07001018 const EventEntry* entry,
1019 const sp<InputApplicationHandle>& applicationHandle,
1020 const sp<InputWindowHandle>& windowHandle,
Jeff Brownb88102f2010-09-08 11:49:43 -07001021 nsecs_t* nextWakeupTime) {
Jeff Brown9302c872011-07-13 22:51:29 -07001022 if (applicationHandle == NULL && windowHandle == NULL) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001023 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY) {
1024#if DEBUG_FOCUS
1025 LOGD("Waiting for system to become ready for input.");
1026#endif
1027 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY;
1028 mInputTargetWaitStartTime = currentTime;
1029 mInputTargetWaitTimeoutTime = LONG_LONG_MAX;
1030 mInputTargetWaitTimeoutExpired = false;
Jeff Brown9302c872011-07-13 22:51:29 -07001031 mInputTargetWaitApplicationHandle.clear();
Jeff Brownb88102f2010-09-08 11:49:43 -07001032 }
1033 } else {
1034 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
1035#if DEBUG_FOCUS
Jeff Brown519e0242010-09-15 15:18:56 -07001036 LOGD("Waiting for application to become ready for input: %s",
Jeff Brown9302c872011-07-13 22:51:29 -07001037 getApplicationWindowLabelLocked(applicationHandle, windowHandle).string());
Jeff Brownb88102f2010-09-08 11:49:43 -07001038#endif
Jeff Brown9302c872011-07-13 22:51:29 -07001039 nsecs_t timeout = windowHandle != NULL ? windowHandle->dispatchingTimeout :
1040 applicationHandle != NULL ?
1041 applicationHandle->dispatchingTimeout : DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Jeff Brownb88102f2010-09-08 11:49:43 -07001042
1043 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY;
1044 mInputTargetWaitStartTime = currentTime;
1045 mInputTargetWaitTimeoutTime = currentTime + timeout;
1046 mInputTargetWaitTimeoutExpired = false;
Jeff Brown9302c872011-07-13 22:51:29 -07001047 mInputTargetWaitApplicationHandle.clear();
Jeff Brown928e0542011-01-10 11:17:36 -08001048
Jeff Brown9302c872011-07-13 22:51:29 -07001049 if (windowHandle != NULL) {
1050 mInputTargetWaitApplicationHandle = windowHandle->inputApplicationHandle;
Jeff Brown928e0542011-01-10 11:17:36 -08001051 }
Jeff Brown9302c872011-07-13 22:51:29 -07001052 if (mInputTargetWaitApplicationHandle == NULL && applicationHandle != NULL) {
1053 mInputTargetWaitApplicationHandle = applicationHandle;
Jeff Brown928e0542011-01-10 11:17:36 -08001054 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001055 }
1056 }
1057
1058 if (mInputTargetWaitTimeoutExpired) {
1059 return INPUT_EVENT_INJECTION_TIMED_OUT;
1060 }
1061
1062 if (currentTime >= mInputTargetWaitTimeoutTime) {
Jeff Brown9302c872011-07-13 22:51:29 -07001063 onANRLocked(currentTime, applicationHandle, windowHandle,
1064 entry->eventTime, mInputTargetWaitStartTime);
Jeff Brownb88102f2010-09-08 11:49:43 -07001065
1066 // Force poll loop to wake up immediately on next iteration once we get the
1067 // ANR response back from the policy.
1068 *nextWakeupTime = LONG_LONG_MIN;
1069 return INPUT_EVENT_INJECTION_PENDING;
1070 } else {
1071 // Force poll loop to wake up when timeout is due.
1072 if (mInputTargetWaitTimeoutTime < *nextWakeupTime) {
1073 *nextWakeupTime = mInputTargetWaitTimeoutTime;
1074 }
1075 return INPUT_EVENT_INJECTION_PENDING;
1076 }
1077}
1078
Jeff Brown519e0242010-09-15 15:18:56 -07001079void InputDispatcher::resumeAfterTargetsNotReadyTimeoutLocked(nsecs_t newTimeout,
1080 const sp<InputChannel>& inputChannel) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001081 if (newTimeout > 0) {
1082 // Extend the timeout.
1083 mInputTargetWaitTimeoutTime = now() + newTimeout;
1084 } else {
1085 // Give up.
1086 mInputTargetWaitTimeoutExpired = true;
Jeff Brown519e0242010-09-15 15:18:56 -07001087
Jeff Brown01ce2e92010-09-26 22:20:12 -07001088 // Release the touch targets.
1089 mTouchState.reset();
Jeff Brown2a95c2a2010-09-16 12:31:46 -07001090
Jeff Brown519e0242010-09-15 15:18:56 -07001091 // Input state will not be realistic. Mark it out of sync.
Jeff Browndc3e0052010-09-16 11:02:16 -07001092 if (inputChannel.get()) {
1093 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
1094 if (connectionIndex >= 0) {
1095 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
Jeff Brown00045a72010-12-09 18:10:30 -08001096 if (connection->status == Connection::STATUS_NORMAL) {
Jeff Brownda3d5a92011-03-29 15:11:34 -07001097 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
Jeff Brown00045a72010-12-09 18:10:30 -08001098 "application not responding");
Jeff Brownda3d5a92011-03-29 15:11:34 -07001099 synthesizeCancelationEventsForConnectionLocked(connection, options);
Jeff Brown00045a72010-12-09 18:10:30 -08001100 }
Jeff Browndc3e0052010-09-16 11:02:16 -07001101 }
Jeff Brown519e0242010-09-15 15:18:56 -07001102 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001103 }
1104}
1105
Jeff Brown519e0242010-09-15 15:18:56 -07001106nsecs_t InputDispatcher::getTimeSpentWaitingForApplicationLocked(
Jeff Brownb88102f2010-09-08 11:49:43 -07001107 nsecs_t currentTime) {
1108 if (mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
1109 return currentTime - mInputTargetWaitStartTime;
1110 }
1111 return 0;
1112}
1113
1114void InputDispatcher::resetANRTimeoutsLocked() {
1115#if DEBUG_FOCUS
1116 LOGD("Resetting ANR timeouts.");
1117#endif
1118
Jeff Brownb88102f2010-09-08 11:49:43 -07001119 // Reset input target wait timeout.
1120 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_NONE;
1121}
1122
Jeff Brown01ce2e92010-09-26 22:20:12 -07001123int32_t InputDispatcher::findFocusedWindowTargetsLocked(nsecs_t currentTime,
1124 const EventEntry* entry, nsecs_t* nextWakeupTime) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001125 mCurrentInputTargets.clear();
1126
1127 int32_t injectionResult;
1128
1129 // If there is no currently focused window and no focused application
1130 // then drop the event.
Jeff Brown9302c872011-07-13 22:51:29 -07001131 if (mFocusedWindowHandle == NULL) {
1132 if (mFocusedApplicationHandle != NULL) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001133#if DEBUG_FOCUS
1134 LOGD("Waiting because there is no focused window but there is a "
Jeff Brown519e0242010-09-15 15:18:56 -07001135 "focused application that may eventually add a window: %s.",
Jeff Brown9302c872011-07-13 22:51:29 -07001136 getApplicationWindowLabelLocked(mFocusedApplicationHandle, NULL).string());
Jeff Brownb88102f2010-09-08 11:49:43 -07001137#endif
1138 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brown9302c872011-07-13 22:51:29 -07001139 mFocusedApplicationHandle, NULL, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -07001140 goto Unresponsive;
1141 }
1142
1143 LOGI("Dropping event because there is no focused window or focused application.");
1144 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1145 goto Failed;
1146 }
1147
1148 // Check permissions.
Jeff Brown9302c872011-07-13 22:51:29 -07001149 if (! checkInjectionPermission(mFocusedWindowHandle, entry->injectionState)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001150 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1151 goto Failed;
1152 }
1153
1154 // If the currently focused window is paused then keep waiting.
Jeff Brown9302c872011-07-13 22:51:29 -07001155 if (mFocusedWindowHandle->paused) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001156#if DEBUG_FOCUS
1157 LOGD("Waiting because focused window is paused.");
1158#endif
1159 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brown9302c872011-07-13 22:51:29 -07001160 mFocusedApplicationHandle, mFocusedWindowHandle, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -07001161 goto Unresponsive;
1162 }
1163
Jeff Brown519e0242010-09-15 15:18:56 -07001164 // If the currently focused window is still working on previous events then keep waiting.
Jeff Brown9302c872011-07-13 22:51:29 -07001165 if (! isWindowFinishedWithPreviousInputLocked(mFocusedWindowHandle)) {
Jeff Brown519e0242010-09-15 15:18:56 -07001166#if DEBUG_FOCUS
1167 LOGD("Waiting because focused window still processing previous input.");
1168#endif
1169 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brown9302c872011-07-13 22:51:29 -07001170 mFocusedApplicationHandle, mFocusedWindowHandle, nextWakeupTime);
Jeff Brown519e0242010-09-15 15:18:56 -07001171 goto Unresponsive;
1172 }
1173
Jeff Brownb88102f2010-09-08 11:49:43 -07001174 // Success! Output targets.
1175 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
Jeff Brown9302c872011-07-13 22:51:29 -07001176 addWindowTargetLocked(mFocusedWindowHandle,
Jeff Browna032cc02011-03-07 16:56:21 -08001177 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS, BitSet32(0));
Jeff Brownb88102f2010-09-08 11:49:43 -07001178
1179 // Done.
1180Failed:
1181Unresponsive:
Jeff Brown519e0242010-09-15 15:18:56 -07001182 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
1183 updateDispatchStatisticsLocked(currentTime, entry,
1184 injectionResult, timeSpentWaitingForApplication);
Jeff Brownb88102f2010-09-08 11:49:43 -07001185#if DEBUG_FOCUS
Jeff Brown519e0242010-09-15 15:18:56 -07001186 LOGD("findFocusedWindow finished: injectionResult=%d, "
1187 "timeSpendWaitingForApplication=%0.1fms",
1188 injectionResult, timeSpentWaitingForApplication / 1000000.0);
Jeff Brownb88102f2010-09-08 11:49:43 -07001189#endif
1190 return injectionResult;
1191}
1192
Jeff Brown01ce2e92010-09-26 22:20:12 -07001193int32_t InputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime,
Jeff Browna032cc02011-03-07 16:56:21 -08001194 const MotionEntry* entry, nsecs_t* nextWakeupTime, bool* outConflictingPointerActions,
1195 const MotionSample** outSplitBatchAfterSample) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001196 enum InjectionPermission {
1197 INJECTION_PERMISSION_UNKNOWN,
1198 INJECTION_PERMISSION_GRANTED,
1199 INJECTION_PERMISSION_DENIED
1200 };
1201
Jeff Brownb88102f2010-09-08 11:49:43 -07001202 mCurrentInputTargets.clear();
1203
1204 nsecs_t startTime = now();
1205
1206 // For security reasons, we defer updating the touch state until we are sure that
1207 // event injection will be allowed.
1208 //
1209 // FIXME In the original code, screenWasOff could never be set to true.
1210 // The reason is that the POLICY_FLAG_WOKE_HERE
1211 // and POLICY_FLAG_BRIGHT_HERE flags were set only when preprocessing raw
1212 // EV_KEY, EV_REL and EV_ABS events. As it happens, the touch event was
1213 // actually enqueued using the policyFlags that appeared in the final EV_SYN
1214 // events upon which no preprocessing took place. So policyFlags was always 0.
1215 // In the new native input dispatcher we're a bit more careful about event
1216 // preprocessing so the touches we receive can actually have non-zero policyFlags.
1217 // Unfortunately we obtain undesirable behavior.
1218 //
1219 // Here's what happens:
1220 //
1221 // When the device dims in anticipation of going to sleep, touches
1222 // in windows which have FLAG_TOUCHABLE_WHEN_WAKING cause
1223 // the device to brighten and reset the user activity timer.
1224 // Touches on other windows (such as the launcher window)
1225 // are dropped. Then after a moment, the device goes to sleep. Oops.
1226 //
1227 // Also notice how screenWasOff was being initialized using POLICY_FLAG_BRIGHT_HERE
1228 // instead of POLICY_FLAG_WOKE_HERE...
1229 //
1230 bool screenWasOff = false; // original policy: policyFlags & POLICY_FLAG_BRIGHT_HERE;
1231
1232 int32_t action = entry->action;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001233 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Jeff Brownb88102f2010-09-08 11:49:43 -07001234
1235 // Update the touch state as needed based on the properties of the touch event.
Jeff Brown01ce2e92010-09-26 22:20:12 -07001236 int32_t injectionResult = INPUT_EVENT_INJECTION_PENDING;
1237 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
Jeff Brown9302c872011-07-13 22:51:29 -07001238 sp<InputWindowHandle> newHoverWindowHandle;
Jeff Browncc0c1592011-02-19 05:07:28 -08001239
1240 bool isSplit = mTouchState.split;
Jeff Brown2717eff2011-06-30 23:53:07 -07001241 bool switchedDevice = mTouchState.deviceId >= 0
1242 && (mTouchState.deviceId != entry->deviceId
1243 || mTouchState.source != entry->source);
Jeff Browna032cc02011-03-07 16:56:21 -08001244 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE
1245 || maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER
1246 || maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1247 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN
1248 || maskedAction == AMOTION_EVENT_ACTION_SCROLL
1249 || isHoverAction);
Jeff Brown81346812011-06-28 20:08:48 -07001250 bool wrongDevice = false;
Jeff Browna032cc02011-03-07 16:56:21 -08001251 if (newGesture) {
Jeff Browncc0c1592011-02-19 05:07:28 -08001252 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Jeff Brown81346812011-06-28 20:08:48 -07001253 if (switchedDevice && mTouchState.down && !down) {
1254#if DEBUG_FOCUS
1255 LOGD("Dropping event because a pointer for a different device is already down.");
1256#endif
Jeff Browncc0c1592011-02-19 05:07:28 -08001257 mTempTouchState.copyFrom(mTouchState);
Jeff Brown81346812011-06-28 20:08:48 -07001258 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1259 switchedDevice = false;
1260 wrongDevice = true;
1261 goto Failed;
Jeff Browncc0c1592011-02-19 05:07:28 -08001262 }
Jeff Brown81346812011-06-28 20:08:48 -07001263 mTempTouchState.reset();
1264 mTempTouchState.down = down;
1265 mTempTouchState.deviceId = entry->deviceId;
1266 mTempTouchState.source = entry->source;
1267 isSplit = false;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001268 } else {
1269 mTempTouchState.copyFrom(mTouchState);
Jeff Browncc0c1592011-02-19 05:07:28 -08001270 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001271
Jeff Browna032cc02011-03-07 16:56:21 -08001272 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
Jeff Brown33bbfd22011-02-24 20:55:35 -08001273 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
Jeff Brownb88102f2010-09-08 11:49:43 -07001274
Jeff Browna032cc02011-03-07 16:56:21 -08001275 const MotionSample* sample = &entry->firstSample;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001276 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Jeff Browna032cc02011-03-07 16:56:21 -08001277 int32_t x = int32_t(sample->pointerCoords[pointerIndex].
Jeff Brownebbd5d12011-02-17 13:01:34 -08001278 getAxisValue(AMOTION_EVENT_AXIS_X));
Jeff Browna032cc02011-03-07 16:56:21 -08001279 int32_t y = int32_t(sample->pointerCoords[pointerIndex].
Jeff Brownebbd5d12011-02-17 13:01:34 -08001280 getAxisValue(AMOTION_EVENT_AXIS_Y));
Jeff Brown9302c872011-07-13 22:51:29 -07001281 sp<InputWindowHandle> newTouchedWindowHandle;
1282 sp<InputWindowHandle> topErrorWindowHandle;
Jeff Browna032cc02011-03-07 16:56:21 -08001283 bool isTouchModal = false;
Jeff Brownb88102f2010-09-08 11:49:43 -07001284
1285 // Traverse windows from front to back to find touched window and outside targets.
Jeff Brown9302c872011-07-13 22:51:29 -07001286 size_t numWindows = mWindowHandles.size();
Jeff Brownb88102f2010-09-08 11:49:43 -07001287 for (size_t i = 0; i < numWindows; i++) {
Jeff Brown9302c872011-07-13 22:51:29 -07001288 sp<InputWindowHandle> windowHandle = mWindowHandles.itemAt(i);
1289 int32_t flags = windowHandle->layoutParamsFlags;
Jeff Brownb88102f2010-09-08 11:49:43 -07001290
Jeff Brown9302c872011-07-13 22:51:29 -07001291 if (flags & InputWindowHandle::FLAG_SYSTEM_ERROR) {
1292 if (topErrorWindowHandle == NULL) {
1293 topErrorWindowHandle = windowHandle;
Jeff Brownb88102f2010-09-08 11:49:43 -07001294 }
1295 }
1296
Jeff Brown9302c872011-07-13 22:51:29 -07001297 if (windowHandle->visible) {
1298 if (! (flags & InputWindowHandle::FLAG_NOT_TOUCHABLE)) {
1299 isTouchModal = (flags & (InputWindowHandle::FLAG_NOT_FOCUSABLE
1300 | InputWindowHandle::FLAG_NOT_TOUCH_MODAL)) == 0;
1301 if (isTouchModal || windowHandle->touchableRegionContainsPoint(x, y)) {
1302 if (! screenWasOff
1303 || (flags & InputWindowHandle::FLAG_TOUCHABLE_WHEN_WAKING)) {
1304 newTouchedWindowHandle = windowHandle;
Jeff Brownb88102f2010-09-08 11:49:43 -07001305 }
1306 break; // found touched window, exit window loop
1307 }
1308 }
1309
Jeff Brown01ce2e92010-09-26 22:20:12 -07001310 if (maskedAction == AMOTION_EVENT_ACTION_DOWN
Jeff Brown9302c872011-07-13 22:51:29 -07001311 && (flags & InputWindowHandle::FLAG_WATCH_OUTSIDE_TOUCH)) {
Jeff Browna032cc02011-03-07 16:56:21 -08001312 int32_t outsideTargetFlags = InputTarget::FLAG_DISPATCH_AS_OUTSIDE;
Jeff Brown9302c872011-07-13 22:51:29 -07001313 if (isWindowObscuredAtPointLocked(windowHandle, x, y)) {
Jeff Brown19dfc832010-10-05 12:26:23 -07001314 outsideTargetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1315 }
1316
Jeff Brown9302c872011-07-13 22:51:29 -07001317 mTempTouchState.addOrUpdateWindow(
1318 windowHandle, outsideTargetFlags, BitSet32(0));
Jeff Brownb88102f2010-09-08 11:49:43 -07001319 }
1320 }
1321 }
1322
1323 // If there is an error window but it is not taking focus (typically because
1324 // it is invisible) then wait for it. Any other focused window may in
1325 // fact be in ANR state.
Jeff Brown9302c872011-07-13 22:51:29 -07001326 if (topErrorWindowHandle != NULL && newTouchedWindowHandle != topErrorWindowHandle) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001327#if DEBUG_FOCUS
1328 LOGD("Waiting because system error window is pending.");
1329#endif
1330 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
1331 NULL, NULL, nextWakeupTime);
1332 injectionPermission = INJECTION_PERMISSION_UNKNOWN;
1333 goto Unresponsive;
1334 }
1335
Jeff Brown01ce2e92010-09-26 22:20:12 -07001336 // Figure out whether splitting will be allowed for this window.
Jeff Brown9302c872011-07-13 22:51:29 -07001337 if (newTouchedWindowHandle != NULL && newTouchedWindowHandle->supportsSplitTouch()) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001338 // New window supports splitting.
1339 isSplit = true;
1340 } else if (isSplit) {
1341 // New window does not support splitting but we have already split events.
1342 // Assign the pointer to the first foreground window we find.
1343 // (May be NULL which is why we put this code block before the next check.)
Jeff Brown9302c872011-07-13 22:51:29 -07001344 newTouchedWindowHandle = mTempTouchState.getFirstForegroundWindowHandle();
Jeff Brown01ce2e92010-09-26 22:20:12 -07001345 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001346
Jeff Brownb88102f2010-09-08 11:49:43 -07001347 // If we did not find a touched window then fail.
Jeff Brown9302c872011-07-13 22:51:29 -07001348 if (newTouchedWindowHandle == NULL) {
1349 if (mFocusedApplicationHandle != NULL) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001350#if DEBUG_FOCUS
1351 LOGD("Waiting because there is no touched window but there is a "
Jeff Brown519e0242010-09-15 15:18:56 -07001352 "focused application that may eventually add a new window: %s.",
Jeff Brown9302c872011-07-13 22:51:29 -07001353 getApplicationWindowLabelLocked(mFocusedApplicationHandle, NULL).string());
Jeff Brownb88102f2010-09-08 11:49:43 -07001354#endif
1355 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brown9302c872011-07-13 22:51:29 -07001356 mFocusedApplicationHandle, NULL, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -07001357 goto Unresponsive;
1358 }
1359
1360 LOGI("Dropping event because there is no touched window or focused application.");
1361 injectionResult = INPUT_EVENT_INJECTION_FAILED;
Jeff Brownb88102f2010-09-08 11:49:43 -07001362 goto Failed;
1363 }
1364
Jeff Brown19dfc832010-10-05 12:26:23 -07001365 // Set target flags.
Jeff Browna032cc02011-03-07 16:56:21 -08001366 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
Jeff Brown19dfc832010-10-05 12:26:23 -07001367 if (isSplit) {
1368 targetFlags |= InputTarget::FLAG_SPLIT;
1369 }
Jeff Brown9302c872011-07-13 22:51:29 -07001370 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
Jeff Brown19dfc832010-10-05 12:26:23 -07001371 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1372 }
1373
Jeff Browna032cc02011-03-07 16:56:21 -08001374 // Update hover state.
1375 if (isHoverAction) {
Jeff Brown9302c872011-07-13 22:51:29 -07001376 newHoverWindowHandle = newTouchedWindowHandle;
Jeff Browna032cc02011-03-07 16:56:21 -08001377
1378 // Ensure all subsequent motion samples are also within the touched window.
1379 // Set *outSplitBatchAfterSample to the sample before the first one that is not
1380 // within the touched window.
1381 if (!isTouchModal) {
1382 while (sample->next) {
Jeff Brown9302c872011-07-13 22:51:29 -07001383 if (!newHoverWindowHandle->touchableRegionContainsPoint(
Jeff Browna032cc02011-03-07 16:56:21 -08001384 sample->next->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X),
1385 sample->next->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y))) {
1386 *outSplitBatchAfterSample = sample;
1387 break;
1388 }
1389 sample = sample->next;
1390 }
1391 }
1392 } else if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
Jeff Brown9302c872011-07-13 22:51:29 -07001393 newHoverWindowHandle = mLastHoverWindowHandle;
Jeff Browna032cc02011-03-07 16:56:21 -08001394 }
1395
Jeff Brown01ce2e92010-09-26 22:20:12 -07001396 // Update the temporary touch state.
1397 BitSet32 pointerIds;
1398 if (isSplit) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07001399 uint32_t pointerId = entry->pointerProperties[pointerIndex].id;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001400 pointerIds.markBit(pointerId);
Jeff Brownb88102f2010-09-08 11:49:43 -07001401 }
Jeff Brown9302c872011-07-13 22:51:29 -07001402 mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Jeff Brownb88102f2010-09-08 11:49:43 -07001403 } else {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001404 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
Jeff Brownb88102f2010-09-08 11:49:43 -07001405
1406 // If the pointer is not currently down, then ignore the event.
Jeff Brown01ce2e92010-09-26 22:20:12 -07001407 if (! mTempTouchState.down) {
Jeff Browna2cc28d2011-03-25 11:58:46 -07001408#if DEBUG_FOCUS
Jeff Brown76860e32010-10-25 17:37:46 -07001409 LOGD("Dropping event because the pointer is not down or we previously "
1410 "dropped the pointer down event.");
1411#endif
Jeff Brownb88102f2010-09-08 11:49:43 -07001412 injectionResult = INPUT_EVENT_INJECTION_FAILED;
Jeff Brownb88102f2010-09-08 11:49:43 -07001413 goto Failed;
1414 }
Jeff Brown98db5fa2011-06-08 15:37:10 -07001415
1416 // Check whether touches should slip outside of the current foreground window.
1417 if (maskedAction == AMOTION_EVENT_ACTION_MOVE
1418 && entry->pointerCount == 1
1419 && mTempTouchState.isSlippery()) {
1420 const MotionSample* sample = &entry->firstSample;
1421 int32_t x = int32_t(sample->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
1422 int32_t y = int32_t(sample->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
1423
Jeff Brown9302c872011-07-13 22:51:29 -07001424 sp<InputWindowHandle> oldTouchedWindowHandle =
1425 mTempTouchState.getFirstForegroundWindowHandle();
1426 sp<InputWindowHandle> newTouchedWindowHandle = findTouchedWindowAtLocked(x, y);
1427 if (oldTouchedWindowHandle != newTouchedWindowHandle
1428 && newTouchedWindowHandle != NULL) {
Jeff Brown98db5fa2011-06-08 15:37:10 -07001429#if DEBUG_FOCUS
1430 LOGD("Touch is slipping out of window %s into window %s.",
Jeff Brown9302c872011-07-13 22:51:29 -07001431 oldTouchedWindowHandle->name.string(),
1432 newTouchedWindowHandle->name.string());
Jeff Brown98db5fa2011-06-08 15:37:10 -07001433#endif
1434 // Make a slippery exit from the old window.
Jeff Brown9302c872011-07-13 22:51:29 -07001435 mTempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
Jeff Brown98db5fa2011-06-08 15:37:10 -07001436 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT, BitSet32(0));
1437
1438 // Make a slippery entrance into the new window.
Jeff Brown9302c872011-07-13 22:51:29 -07001439 if (newTouchedWindowHandle->supportsSplitTouch()) {
Jeff Brown98db5fa2011-06-08 15:37:10 -07001440 isSplit = true;
1441 }
1442
1443 int32_t targetFlags = InputTarget::FLAG_FOREGROUND
1444 | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
1445 if (isSplit) {
1446 targetFlags |= InputTarget::FLAG_SPLIT;
1447 }
Jeff Brown9302c872011-07-13 22:51:29 -07001448 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
Jeff Brown98db5fa2011-06-08 15:37:10 -07001449 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1450 }
1451
1452 BitSet32 pointerIds;
1453 if (isSplit) {
1454 pointerIds.markBit(entry->pointerProperties[0].id);
1455 }
Jeff Brown9302c872011-07-13 22:51:29 -07001456 mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Jeff Brown98db5fa2011-06-08 15:37:10 -07001457
1458 // Split the batch here so we send exactly one sample.
1459 *outSplitBatchAfterSample = &entry->firstSample;
1460 }
1461 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001462 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001463
Jeff Brown9302c872011-07-13 22:51:29 -07001464 if (newHoverWindowHandle != mLastHoverWindowHandle) {
Jeff Browna032cc02011-03-07 16:56:21 -08001465 // Split the batch here so we send exactly one sample as part of ENTER or EXIT.
1466 *outSplitBatchAfterSample = &entry->firstSample;
1467
1468 // Let the previous window know that the hover sequence is over.
Jeff Brown9302c872011-07-13 22:51:29 -07001469 if (mLastHoverWindowHandle != NULL) {
Jeff Browna032cc02011-03-07 16:56:21 -08001470#if DEBUG_HOVER
Jeff Brown9302c872011-07-13 22:51:29 -07001471 LOGD("Sending hover exit event to window %s.", mLastHoverWindowHandle->name.string());
Jeff Browna032cc02011-03-07 16:56:21 -08001472#endif
Jeff Brown9302c872011-07-13 22:51:29 -07001473 mTempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
Jeff Browna032cc02011-03-07 16:56:21 -08001474 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
1475 }
1476
1477 // Let the new window know that the hover sequence is starting.
Jeff Brown9302c872011-07-13 22:51:29 -07001478 if (newHoverWindowHandle != NULL) {
Jeff Browna032cc02011-03-07 16:56:21 -08001479#if DEBUG_HOVER
Jeff Brown9302c872011-07-13 22:51:29 -07001480 LOGD("Sending hover enter event to window %s.", newHoverWindowHandle->name.string());
Jeff Browna032cc02011-03-07 16:56:21 -08001481#endif
Jeff Brown9302c872011-07-13 22:51:29 -07001482 mTempTouchState.addOrUpdateWindow(newHoverWindowHandle,
Jeff Browna032cc02011-03-07 16:56:21 -08001483 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER, BitSet32(0));
1484 }
1485 }
1486
Jeff Brown01ce2e92010-09-26 22:20:12 -07001487 // Check permission to inject into all touched foreground windows and ensure there
1488 // is at least one touched foreground window.
1489 {
1490 bool haveForegroundWindow = false;
1491 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1492 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1493 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1494 haveForegroundWindow = true;
Jeff Brown9302c872011-07-13 22:51:29 -07001495 if (! checkInjectionPermission(touchedWindow.windowHandle,
1496 entry->injectionState)) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001497 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1498 injectionPermission = INJECTION_PERMISSION_DENIED;
1499 goto Failed;
1500 }
1501 }
1502 }
1503 if (! haveForegroundWindow) {
Jeff Browna2cc28d2011-03-25 11:58:46 -07001504#if DEBUG_FOCUS
Jeff Brown01ce2e92010-09-26 22:20:12 -07001505 LOGD("Dropping event because there is no touched foreground window to receive it.");
Jeff Brownb88102f2010-09-08 11:49:43 -07001506#endif
1507 injectionResult = INPUT_EVENT_INJECTION_FAILED;
Jeff Brownb88102f2010-09-08 11:49:43 -07001508 goto Failed;
1509 }
1510
Jeff Brown01ce2e92010-09-26 22:20:12 -07001511 // Permission granted to injection into all touched foreground windows.
1512 injectionPermission = INJECTION_PERMISSION_GRANTED;
1513 }
Jeff Brown519e0242010-09-15 15:18:56 -07001514
Kenny Root7a9db182011-06-02 15:16:05 -07001515 // Check whether windows listening for outside touches are owned by the same UID. If it is
1516 // set the policy flag that we will not reveal coordinate information to this window.
1517 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
Jeff Brown9302c872011-07-13 22:51:29 -07001518 sp<InputWindowHandle> foregroundWindowHandle =
1519 mTempTouchState.getFirstForegroundWindowHandle();
1520 const int32_t foregroundWindowUid = foregroundWindowHandle->ownerUid;
Kenny Root7a9db182011-06-02 15:16:05 -07001521 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1522 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1523 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
Jeff Brown9302c872011-07-13 22:51:29 -07001524 sp<InputWindowHandle> inputWindowHandle = touchedWindow.windowHandle;
1525 if (inputWindowHandle->ownerUid != foregroundWindowUid) {
1526 mTempTouchState.addOrUpdateWindow(inputWindowHandle,
Kenny Root7a9db182011-06-02 15:16:05 -07001527 InputTarget::FLAG_ZERO_COORDS, BitSet32(0));
1528 }
1529 }
1530 }
1531 }
1532
Jeff Brown01ce2e92010-09-26 22:20:12 -07001533 // Ensure all touched foreground windows are ready for new input.
1534 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1535 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1536 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1537 // If the touched window is paused then keep waiting.
Jeff Brown9302c872011-07-13 22:51:29 -07001538 if (touchedWindow.windowHandle->paused) {
Jeff Browna2cc28d2011-03-25 11:58:46 -07001539#if DEBUG_FOCUS
Jeff Brown01ce2e92010-09-26 22:20:12 -07001540 LOGD("Waiting because touched window is paused.");
Jeff Brown519e0242010-09-15 15:18:56 -07001541#endif
Jeff Brown01ce2e92010-09-26 22:20:12 -07001542 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brown9302c872011-07-13 22:51:29 -07001543 NULL, touchedWindow.windowHandle, nextWakeupTime);
Jeff Brown01ce2e92010-09-26 22:20:12 -07001544 goto Unresponsive;
1545 }
1546
1547 // If the touched window is still working on previous events then keep waiting.
Jeff Brown9302c872011-07-13 22:51:29 -07001548 if (! isWindowFinishedWithPreviousInputLocked(touchedWindow.windowHandle)) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001549#if DEBUG_FOCUS
1550 LOGD("Waiting because touched window still processing previous input.");
1551#endif
1552 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brown9302c872011-07-13 22:51:29 -07001553 NULL, touchedWindow.windowHandle, nextWakeupTime);
Jeff Brown01ce2e92010-09-26 22:20:12 -07001554 goto Unresponsive;
1555 }
1556 }
1557 }
1558
1559 // If this is the first pointer going down and the touched window has a wallpaper
1560 // then also add the touched wallpaper windows so they are locked in for the duration
1561 // of the touch gesture.
Jeff Brown33bbfd22011-02-24 20:55:35 -08001562 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
1563 // engine only supports touch events. We would need to add a mechanism similar
1564 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
1565 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
Jeff Brown9302c872011-07-13 22:51:29 -07001566 sp<InputWindowHandle> foregroundWindowHandle =
1567 mTempTouchState.getFirstForegroundWindowHandle();
1568 if (foregroundWindowHandle->hasWallpaper) {
1569 for (size_t i = 0; i < mWindowHandles.size(); i++) {
1570 sp<InputWindowHandle> windowHandle = mWindowHandles.itemAt(i);
1571 if (windowHandle->layoutParamsType == InputWindowHandle::TYPE_WALLPAPER) {
1572 mTempTouchState.addOrUpdateWindow(windowHandle,
Jeff Browna032cc02011-03-07 16:56:21 -08001573 InputTarget::FLAG_WINDOW_IS_OBSCURED
1574 | InputTarget::FLAG_DISPATCH_AS_IS,
1575 BitSet32(0));
Jeff Brown01ce2e92010-09-26 22:20:12 -07001576 }
1577 }
1578 }
1579 }
1580
Jeff Brownb88102f2010-09-08 11:49:43 -07001581 // Success! Output targets.
1582 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
Jeff Brownb88102f2010-09-08 11:49:43 -07001583
Jeff Brown01ce2e92010-09-26 22:20:12 -07001584 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1585 const TouchedWindow& touchedWindow = mTempTouchState.windows.itemAt(i);
Jeff Brown9302c872011-07-13 22:51:29 -07001586 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Jeff Brown01ce2e92010-09-26 22:20:12 -07001587 touchedWindow.pointerIds);
Jeff Brownb88102f2010-09-08 11:49:43 -07001588 }
1589
Jeff Browna032cc02011-03-07 16:56:21 -08001590 // Drop the outside or hover touch windows since we will not care about them
1591 // in the next iteration.
1592 mTempTouchState.filterNonAsIsTouchWindows();
Jeff Brown01ce2e92010-09-26 22:20:12 -07001593
Jeff Brownb88102f2010-09-08 11:49:43 -07001594Failed:
1595 // Check injection permission once and for all.
1596 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001597 if (checkInjectionPermission(NULL, entry->injectionState)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001598 injectionPermission = INJECTION_PERMISSION_GRANTED;
1599 } else {
1600 injectionPermission = INJECTION_PERMISSION_DENIED;
1601 }
1602 }
1603
1604 // Update final pieces of touch state if the injector had permission.
1605 if (injectionPermission == INJECTION_PERMISSION_GRANTED) {
Jeff Brown95712852011-01-04 19:41:59 -08001606 if (!wrongDevice) {
Jeff Brown81346812011-06-28 20:08:48 -07001607 if (switchedDevice) {
1608#if DEBUG_FOCUS
1609 LOGD("Conflicting pointer actions: Switched to a different device.");
1610#endif
1611 *outConflictingPointerActions = true;
1612 }
1613
1614 if (isHoverAction) {
1615 // Started hovering, therefore no longer down.
1616 if (mTouchState.down) {
1617#if DEBUG_FOCUS
1618 LOGD("Conflicting pointer actions: Hover received while pointer was down.");
1619#endif
1620 *outConflictingPointerActions = true;
1621 }
1622 mTouchState.reset();
1623 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER
1624 || maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
1625 mTouchState.deviceId = entry->deviceId;
1626 mTouchState.source = entry->source;
1627 }
1628 } else if (maskedAction == AMOTION_EVENT_ACTION_UP
1629 || maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Jeff Brown95712852011-01-04 19:41:59 -08001630 // All pointers up or canceled.
Jeff Brown33bbfd22011-02-24 20:55:35 -08001631 mTouchState.reset();
Jeff Brown95712852011-01-04 19:41:59 -08001632 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1633 // First pointer went down.
1634 if (mTouchState.down) {
Jeff Brownb6997262010-10-08 22:31:17 -07001635#if DEBUG_FOCUS
Jeff Brown81346812011-06-28 20:08:48 -07001636 LOGD("Conflicting pointer actions: Down received while already down.");
Jeff Brownb6997262010-10-08 22:31:17 -07001637#endif
Jeff Brown81346812011-06-28 20:08:48 -07001638 *outConflictingPointerActions = true;
Jeff Brown95712852011-01-04 19:41:59 -08001639 }
Jeff Brown33bbfd22011-02-24 20:55:35 -08001640 mTouchState.copyFrom(mTempTouchState);
Jeff Brown95712852011-01-04 19:41:59 -08001641 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
1642 // One pointer went up.
1643 if (isSplit) {
1644 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07001645 uint32_t pointerId = entry->pointerProperties[pointerIndex].id;
Jeff Brownb88102f2010-09-08 11:49:43 -07001646
Jeff Brown95712852011-01-04 19:41:59 -08001647 for (size_t i = 0; i < mTempTouchState.windows.size(); ) {
1648 TouchedWindow& touchedWindow = mTempTouchState.windows.editItemAt(i);
1649 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
1650 touchedWindow.pointerIds.clearBit(pointerId);
1651 if (touchedWindow.pointerIds.isEmpty()) {
1652 mTempTouchState.windows.removeAt(i);
1653 continue;
1654 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001655 }
Jeff Brown95712852011-01-04 19:41:59 -08001656 i += 1;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001657 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001658 }
Jeff Brown33bbfd22011-02-24 20:55:35 -08001659 mTouchState.copyFrom(mTempTouchState);
1660 } else if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
1661 // Discard temporary touch state since it was only valid for this action.
1662 } else {
1663 // Save changes to touch state as-is for all other actions.
1664 mTouchState.copyFrom(mTempTouchState);
Jeff Brownb88102f2010-09-08 11:49:43 -07001665 }
Jeff Browna032cc02011-03-07 16:56:21 -08001666
1667 // Update hover state.
Jeff Brown9302c872011-07-13 22:51:29 -07001668 mLastHoverWindowHandle = newHoverWindowHandle;
Jeff Brown95712852011-01-04 19:41:59 -08001669 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001670 } else {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001671#if DEBUG_FOCUS
1672 LOGD("Not updating touch focus because injection was denied.");
1673#endif
Jeff Brownb88102f2010-09-08 11:49:43 -07001674 }
1675
1676Unresponsive:
Jeff Brown120a4592010-10-27 18:43:51 -07001677 // Reset temporary touch state to ensure we release unnecessary references to input channels.
1678 mTempTouchState.reset();
1679
Jeff Brown519e0242010-09-15 15:18:56 -07001680 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
1681 updateDispatchStatisticsLocked(currentTime, entry,
1682 injectionResult, timeSpentWaitingForApplication);
Jeff Brownb88102f2010-09-08 11:49:43 -07001683#if DEBUG_FOCUS
Jeff Brown01ce2e92010-09-26 22:20:12 -07001684 LOGD("findTouchedWindow finished: injectionResult=%d, injectionPermission=%d, "
1685 "timeSpentWaitingForApplication=%0.1fms",
Jeff Brown519e0242010-09-15 15:18:56 -07001686 injectionResult, injectionPermission, timeSpentWaitingForApplication / 1000000.0);
Jeff Brownb88102f2010-09-08 11:49:43 -07001687#endif
1688 return injectionResult;
1689}
1690
Jeff Brown9302c872011-07-13 22:51:29 -07001691void InputDispatcher::addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
1692 int32_t targetFlags, BitSet32 pointerIds) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001693 mCurrentInputTargets.push();
1694
1695 InputTarget& target = mCurrentInputTargets.editTop();
Jeff Brown9302c872011-07-13 22:51:29 -07001696 target.inputChannel = windowHandle->inputChannel;
Jeff Brownb88102f2010-09-08 11:49:43 -07001697 target.flags = targetFlags;
Jeff Brown9302c872011-07-13 22:51:29 -07001698 target.xOffset = - windowHandle->frameLeft;
1699 target.yOffset = - windowHandle->frameTop;
1700 target.scaleFactor = windowHandle->scaleFactor;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001701 target.pointerIds = pointerIds;
Jeff Brownb88102f2010-09-08 11:49:43 -07001702}
1703
1704void InputDispatcher::addMonitoringTargetsLocked() {
1705 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
1706 mCurrentInputTargets.push();
1707
1708 InputTarget& target = mCurrentInputTargets.editTop();
1709 target.inputChannel = mMonitoringChannels[i];
Jeff Brownb6110c22011-04-01 16:15:13 -07001710 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
Jeff Brownb88102f2010-09-08 11:49:43 -07001711 target.xOffset = 0;
1712 target.yOffset = 0;
Jeff Brownb6110c22011-04-01 16:15:13 -07001713 target.pointerIds.clear();
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001714 target.scaleFactor = 1.0f;
Jeff Brownb88102f2010-09-08 11:49:43 -07001715 }
1716}
1717
Jeff Brown9302c872011-07-13 22:51:29 -07001718bool InputDispatcher::checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
Jeff Brown01ce2e92010-09-26 22:20:12 -07001719 const InjectionState* injectionState) {
1720 if (injectionState
Jeff Brown9302c872011-07-13 22:51:29 -07001721 && (windowHandle == NULL || windowHandle->ownerUid != injectionState->injectorUid)
Jeff Brownb6997262010-10-08 22:31:17 -07001722 && !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Jeff Brown9302c872011-07-13 22:51:29 -07001723 if (windowHandle != NULL) {
1724 LOGW("Permission denied: injecting event from pid %d uid %d to window %s "
1725 "owned by uid %d",
Jeff Brownb6997262010-10-08 22:31:17 -07001726 injectionState->injectorPid, injectionState->injectorUid,
Jeff Brown9302c872011-07-13 22:51:29 -07001727 windowHandle->name.string(),
1728 windowHandle->ownerUid);
Jeff Brownb6997262010-10-08 22:31:17 -07001729 } else {
1730 LOGW("Permission denied: injecting event from pid %d uid %d",
1731 injectionState->injectorPid, injectionState->injectorUid);
Jeff Brownb88102f2010-09-08 11:49:43 -07001732 }
Jeff Brownb6997262010-10-08 22:31:17 -07001733 return false;
Jeff Brownb88102f2010-09-08 11:49:43 -07001734 }
1735 return true;
1736}
1737
Jeff Brown19dfc832010-10-05 12:26:23 -07001738bool InputDispatcher::isWindowObscuredAtPointLocked(
Jeff Brown9302c872011-07-13 22:51:29 -07001739 const sp<InputWindowHandle>& windowHandle, int32_t x, int32_t y) const {
1740 size_t numWindows = mWindowHandles.size();
Jeff Brownb88102f2010-09-08 11:49:43 -07001741 for (size_t i = 0; i < numWindows; i++) {
Jeff Brown9302c872011-07-13 22:51:29 -07001742 sp<InputWindowHandle> otherHandle = mWindowHandles.itemAt(i);
1743 if (otherHandle == windowHandle) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001744 break;
1745 }
Jeff Brown9302c872011-07-13 22:51:29 -07001746 if (otherHandle->visible && ! otherHandle->isTrustedOverlay()
1747 && otherHandle->frameContainsPoint(x, y)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001748 return true;
1749 }
1750 }
1751 return false;
1752}
1753
Jeff Brown9302c872011-07-13 22:51:29 -07001754bool InputDispatcher::isWindowFinishedWithPreviousInputLocked(
1755 const sp<InputWindowHandle>& windowHandle) {
1756 ssize_t connectionIndex = getConnectionIndexLocked(windowHandle->inputChannel);
Jeff Brown519e0242010-09-15 15:18:56 -07001757 if (connectionIndex >= 0) {
1758 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
1759 return connection->outboundQueue.isEmpty();
1760 } else {
1761 return true;
1762 }
1763}
1764
Jeff Brown9302c872011-07-13 22:51:29 -07001765String8 InputDispatcher::getApplicationWindowLabelLocked(
1766 const sp<InputApplicationHandle>& applicationHandle,
1767 const sp<InputWindowHandle>& windowHandle) {
1768 if (applicationHandle != NULL) {
1769 if (windowHandle != NULL) {
1770 String8 label(applicationHandle->name);
Jeff Brown519e0242010-09-15 15:18:56 -07001771 label.append(" - ");
Jeff Brown9302c872011-07-13 22:51:29 -07001772 label.append(windowHandle->name);
Jeff Brown519e0242010-09-15 15:18:56 -07001773 return label;
1774 } else {
Jeff Brown9302c872011-07-13 22:51:29 -07001775 return applicationHandle->name;
Jeff Brown519e0242010-09-15 15:18:56 -07001776 }
Jeff Brown9302c872011-07-13 22:51:29 -07001777 } else if (windowHandle != NULL) {
1778 return windowHandle->name;
Jeff Brown519e0242010-09-15 15:18:56 -07001779 } else {
1780 return String8("<unknown application or window>");
1781 }
1782}
1783
Jeff Browne2fe69e2010-10-18 13:21:23 -07001784void InputDispatcher::pokeUserActivityLocked(const EventEntry* eventEntry) {
Jeff Brown56194eb2011-03-02 19:23:13 -08001785 int32_t eventType = POWER_MANAGER_OTHER_EVENT;
Jeff Brown4d396052010-10-29 21:50:21 -07001786 switch (eventEntry->type) {
1787 case EventEntry::TYPE_MOTION: {
Jeff Browne2fe69e2010-10-18 13:21:23 -07001788 const MotionEntry* motionEntry = static_cast<const MotionEntry*>(eventEntry);
Jeff Brown4d396052010-10-29 21:50:21 -07001789 if (motionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
1790 return;
1791 }
1792
Jeff Brown56194eb2011-03-02 19:23:13 -08001793 if (MotionEvent::isTouchEvent(motionEntry->source, motionEntry->action)) {
Joe Onorato1a542c72010-11-08 09:48:20 -08001794 eventType = POWER_MANAGER_TOUCH_EVENT;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001795 }
Jeff Brown4d396052010-10-29 21:50:21 -07001796 break;
1797 }
1798 case EventEntry::TYPE_KEY: {
1799 const KeyEntry* keyEntry = static_cast<const KeyEntry*>(eventEntry);
1800 if (keyEntry->flags & AKEY_EVENT_FLAG_CANCELED) {
1801 return;
1802 }
Jeff Brown56194eb2011-03-02 19:23:13 -08001803 eventType = POWER_MANAGER_BUTTON_EVENT;
Jeff Brown4d396052010-10-29 21:50:21 -07001804 break;
1805 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001806 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001807
Jeff Brownb88102f2010-09-08 11:49:43 -07001808 CommandEntry* commandEntry = postCommandLocked(
1809 & InputDispatcher::doPokeUserActivityLockedInterruptible);
Jeff Browne2fe69e2010-10-18 13:21:23 -07001810 commandEntry->eventTime = eventEntry->eventTime;
Jeff Brownb88102f2010-09-08 11:49:43 -07001811 commandEntry->userActivityEventType = eventType;
1812}
1813
Jeff Brown7fbdc842010-06-17 20:52:56 -07001814void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
1815 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget,
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001816 bool resumeWithAppendedMotionSample) {
1817#if DEBUG_DISPATCH_CYCLE
Jeff Brown519e0242010-09-15 15:18:56 -07001818 LOGD("channel '%s' ~ prepareDispatchCycle - flags=%d, "
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001819 "xOffset=%f, yOffset=%f, scaleFactor=%f"
Jeff Brown83c09682010-12-23 17:50:18 -08001820 "pointerIds=0x%x, "
Jeff Brown01ce2e92010-09-26 22:20:12 -07001821 "resumeWithAppendedMotionSample=%s",
Jeff Brown519e0242010-09-15 15:18:56 -07001822 connection->getInputChannelName(), inputTarget->flags,
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001823 inputTarget->xOffset, inputTarget->yOffset,
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001824 inputTarget->scaleFactor, inputTarget->pointerIds.value,
Jeff Brownb88102f2010-09-08 11:49:43 -07001825 toString(resumeWithAppendedMotionSample));
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001826#endif
1827
Jeff Brown01ce2e92010-09-26 22:20:12 -07001828 // Make sure we are never called for streaming when splitting across multiple windows.
1829 bool isSplit = inputTarget->flags & InputTarget::FLAG_SPLIT;
Jeff Brownb6110c22011-04-01 16:15:13 -07001830 LOG_ASSERT(! (resumeWithAppendedMotionSample && isSplit));
Jeff Brown01ce2e92010-09-26 22:20:12 -07001831
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001832 // Skip this event if the connection status is not normal.
Jeff Brown519e0242010-09-15 15:18:56 -07001833 // We don't want to enqueue additional outbound events if the connection is broken.
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001834 if (connection->status != Connection::STATUS_NORMAL) {
Jeff Brownb6997262010-10-08 22:31:17 -07001835#if DEBUG_DISPATCH_CYCLE
1836 LOGD("channel '%s' ~ Dropping event because the channel status is %s",
Jeff Brownb88102f2010-09-08 11:49:43 -07001837 connection->getInputChannelName(), connection->getStatusLabel());
Jeff Brownb6997262010-10-08 22:31:17 -07001838#endif
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001839 return;
1840 }
1841
Jeff Brown01ce2e92010-09-26 22:20:12 -07001842 // Split a motion event if needed.
1843 if (isSplit) {
Jeff Brownb6110c22011-04-01 16:15:13 -07001844 LOG_ASSERT(eventEntry->type == EventEntry::TYPE_MOTION);
Jeff Brown01ce2e92010-09-26 22:20:12 -07001845
1846 MotionEntry* originalMotionEntry = static_cast<MotionEntry*>(eventEntry);
1847 if (inputTarget->pointerIds.count() != originalMotionEntry->pointerCount) {
1848 MotionEntry* splitMotionEntry = splitMotionEvent(
1849 originalMotionEntry, inputTarget->pointerIds);
Jeff Brown58a2da82011-01-25 16:02:22 -08001850 if (!splitMotionEntry) {
1851 return; // split event was dropped
1852 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001853#if DEBUG_FOCUS
1854 LOGD("channel '%s' ~ Split motion event.",
1855 connection->getInputChannelName());
1856 logOutboundMotionDetailsLocked(" ", splitMotionEntry);
1857#endif
1858 eventEntry = splitMotionEntry;
1859 }
1860 }
1861
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001862 // Resume the dispatch cycle with a freshly appended motion sample.
1863 // First we check that the last dispatch entry in the outbound queue is for the same
1864 // motion event to which we appended the motion sample. If we find such a dispatch
1865 // entry, and if it is currently in progress then we try to stream the new sample.
1866 bool wasEmpty = connection->outboundQueue.isEmpty();
1867
1868 if (! wasEmpty && resumeWithAppendedMotionSample) {
1869 DispatchEntry* motionEventDispatchEntry =
1870 connection->findQueuedDispatchEntryForEvent(eventEntry);
1871 if (motionEventDispatchEntry) {
1872 // If the dispatch entry is not in progress, then we must be busy dispatching an
1873 // earlier event. Not a problem, the motion event is on the outbound queue and will
1874 // be dispatched later.
1875 if (! motionEventDispatchEntry->inProgress) {
1876#if DEBUG_BATCHING
1877 LOGD("channel '%s' ~ Not streaming because the motion event has "
1878 "not yet been dispatched. "
1879 "(Waiting for earlier events to be consumed.)",
1880 connection->getInputChannelName());
1881#endif
1882 return;
1883 }
1884
1885 // If the dispatch entry is in progress but it already has a tail of pending
1886 // motion samples, then it must mean that the shared memory buffer filled up.
1887 // Not a problem, when this dispatch cycle is finished, we will eventually start
1888 // a new dispatch cycle to process the tail and that tail includes the newly
1889 // appended motion sample.
1890 if (motionEventDispatchEntry->tailMotionSample) {
1891#if DEBUG_BATCHING
1892 LOGD("channel '%s' ~ Not streaming because no new samples can "
1893 "be appended to the motion event in this dispatch cycle. "
1894 "(Waiting for next dispatch cycle to start.)",
1895 connection->getInputChannelName());
1896#endif
1897 return;
1898 }
1899
Jeff Brown81346812011-06-28 20:08:48 -07001900 // If the motion event was modified in flight, then we cannot stream the sample.
1901 if ((motionEventDispatchEntry->targetFlags & InputTarget::FLAG_DISPATCH_MASK)
1902 != InputTarget::FLAG_DISPATCH_AS_IS) {
1903#if DEBUG_BATCHING
1904 LOGD("channel '%s' ~ Not streaming because the motion event was not "
1905 "being dispatched as-is. "
1906 "(Waiting for next dispatch cycle to start.)",
1907 connection->getInputChannelName());
1908#endif
1909 return;
1910 }
1911
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001912 // The dispatch entry is in progress and is still potentially open for streaming.
1913 // Try to stream the new motion sample. This might fail if the consumer has already
1914 // consumed the motion event (or if the channel is broken).
Jeff Brown01ce2e92010-09-26 22:20:12 -07001915 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
1916 MotionSample* appendedMotionSample = motionEntry->lastSample;
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001917 status_t status;
1918 if (motionEventDispatchEntry->scaleFactor == 1.0f) {
1919 status = connection->inputPublisher.appendMotionSample(
1920 appendedMotionSample->eventTime, appendedMotionSample->pointerCoords);
1921 } else {
1922 PointerCoords scaledCoords[MAX_POINTERS];
1923 for (size_t i = 0; i < motionEntry->pointerCount; i++) {
1924 scaledCoords[i] = appendedMotionSample->pointerCoords[i];
1925 scaledCoords[i].scale(motionEventDispatchEntry->scaleFactor);
1926 }
1927 status = connection->inputPublisher.appendMotionSample(
1928 appendedMotionSample->eventTime, scaledCoords);
1929 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001930 if (status == OK) {
1931#if DEBUG_BATCHING
1932 LOGD("channel '%s' ~ Successfully streamed new motion sample.",
1933 connection->getInputChannelName());
1934#endif
1935 return;
1936 }
1937
1938#if DEBUG_BATCHING
1939 if (status == NO_MEMORY) {
1940 LOGD("channel '%s' ~ Could not append motion sample to currently "
1941 "dispatched move event because the shared memory buffer is full. "
1942 "(Waiting for next dispatch cycle to start.)",
1943 connection->getInputChannelName());
1944 } else if (status == status_t(FAILED_TRANSACTION)) {
1945 LOGD("channel '%s' ~ Could not append motion sample to currently "
Jeff Brown349703e2010-06-22 01:27:15 -07001946 "dispatched move event because the event has already been consumed. "
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001947 "(Waiting for next dispatch cycle to start.)",
1948 connection->getInputChannelName());
1949 } else {
1950 LOGD("channel '%s' ~ Could not append motion sample to currently "
1951 "dispatched move event due to an error, status=%d. "
1952 "(Waiting for next dispatch cycle to start.)",
1953 connection->getInputChannelName(), status);
1954 }
1955#endif
1956 // Failed to stream. Start a new tail of pending motion samples to dispatch
1957 // in the next cycle.
1958 motionEventDispatchEntry->tailMotionSample = appendedMotionSample;
1959 return;
1960 }
1961 }
1962
Jeff Browna032cc02011-03-07 16:56:21 -08001963 // Enqueue dispatch entries for the requested modes.
1964 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1965 resumeWithAppendedMotionSample, InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
1966 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1967 resumeWithAppendedMotionSample, InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
1968 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1969 resumeWithAppendedMotionSample, InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
1970 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1971 resumeWithAppendedMotionSample, InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brown98db5fa2011-06-08 15:37:10 -07001972 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1973 resumeWithAppendedMotionSample, InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
1974 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1975 resumeWithAppendedMotionSample, InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Jeff Browna032cc02011-03-07 16:56:21 -08001976
1977 // If the outbound queue was previously empty, start the dispatch cycle going.
Jeff Brownb6110c22011-04-01 16:15:13 -07001978 if (wasEmpty && !connection->outboundQueue.isEmpty()) {
Jeff Browna032cc02011-03-07 16:56:21 -08001979 activateConnectionLocked(connection.get());
1980 startDispatchCycleLocked(currentTime, connection);
1981 }
1982}
1983
1984void InputDispatcher::enqueueDispatchEntryLocked(
1985 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget,
1986 bool resumeWithAppendedMotionSample, int32_t dispatchMode) {
1987 int32_t inputTargetFlags = inputTarget->flags;
1988 if (!(inputTargetFlags & dispatchMode)) {
1989 return;
1990 }
1991 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
1992
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001993 // This is a new event.
1994 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Jeff Brownb88102f2010-09-08 11:49:43 -07001995 DispatchEntry* dispatchEntry = mAllocator.obtainDispatchEntry(eventEntry, // increments ref
Dianne Hackbornaa9d84c2011-05-09 19:00:59 -07001996 inputTargetFlags, inputTarget->xOffset, inputTarget->yOffset,
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001997 inputTarget->scaleFactor);
Jeff Brown519e0242010-09-15 15:18:56 -07001998 if (dispatchEntry->hasForegroundTarget()) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001999 incrementPendingForegroundDispatchesLocked(eventEntry);
Jeff Brown6ec402b2010-07-28 15:48:59 -07002000 }
2001
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002002 // Handle the case where we could not stream a new motion sample because the consumer has
2003 // already consumed the motion event (otherwise the corresponding dispatch entry would
2004 // still be in the outbound queue for this connection). We set the head motion sample
2005 // to the list starting with the newly appended motion sample.
2006 if (resumeWithAppendedMotionSample) {
2007#if DEBUG_BATCHING
2008 LOGD("channel '%s' ~ Preparing a new dispatch cycle for additional motion samples "
2009 "that cannot be streamed because the motion event has already been consumed.",
2010 connection->getInputChannelName());
2011#endif
2012 MotionSample* appendedMotionSample = static_cast<MotionEntry*>(eventEntry)->lastSample;
2013 dispatchEntry->headMotionSample = appendedMotionSample;
2014 }
2015
Jeff Brown81346812011-06-28 20:08:48 -07002016 // Apply target flags and update the connection's input state.
2017 switch (eventEntry->type) {
2018 case EventEntry::TYPE_KEY: {
2019 KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
2020 dispatchEntry->resolvedAction = keyEntry->action;
2021 dispatchEntry->resolvedFlags = keyEntry->flags;
2022
2023 if (!connection->inputState.trackKey(keyEntry,
2024 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags)) {
2025#if DEBUG_DISPATCH_CYCLE
2026 LOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
2027 connection->getInputChannelName());
2028#endif
2029 return; // skip the inconsistent event
2030 }
2031 break;
2032 }
2033
2034 case EventEntry::TYPE_MOTION: {
2035 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
2036 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2037 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
2038 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
2039 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
2040 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
2041 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2042 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
2043 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
2044 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
2045 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
2046 } else {
2047 dispatchEntry->resolvedAction = motionEntry->action;
2048 }
2049 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE
2050 && !connection->inputState.isHovering(
2051 motionEntry->deviceId, motionEntry->source)) {
2052#if DEBUG_DISPATCH_CYCLE
2053 LOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter event",
2054 connection->getInputChannelName());
2055#endif
2056 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2057 }
2058
2059 dispatchEntry->resolvedFlags = motionEntry->flags;
2060 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
2061 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
2062 }
2063
2064 if (!connection->inputState.trackMotion(motionEntry,
2065 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags)) {
2066#if DEBUG_DISPATCH_CYCLE
2067 LOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion event",
2068 connection->getInputChannelName());
2069#endif
2070 return; // skip the inconsistent event
2071 }
2072 break;
2073 }
2074 }
2075
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002076 // Enqueue the dispatch entry.
2077 connection->outboundQueue.enqueueAtTail(dispatchEntry);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002078}
2079
Jeff Brown7fbdc842010-06-17 20:52:56 -07002080void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Jeff Brown519e0242010-09-15 15:18:56 -07002081 const sp<Connection>& connection) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002082#if DEBUG_DISPATCH_CYCLE
2083 LOGD("channel '%s' ~ startDispatchCycle",
2084 connection->getInputChannelName());
2085#endif
2086
Jeff Brownb6110c22011-04-01 16:15:13 -07002087 LOG_ASSERT(connection->status == Connection::STATUS_NORMAL);
2088 LOG_ASSERT(! connection->outboundQueue.isEmpty());
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002089
Jeff Brownb88102f2010-09-08 11:49:43 -07002090 DispatchEntry* dispatchEntry = connection->outboundQueue.headSentinel.next;
Jeff Brownb6110c22011-04-01 16:15:13 -07002091 LOG_ASSERT(! dispatchEntry->inProgress);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002092
Jeff Brownb88102f2010-09-08 11:49:43 -07002093 // Mark the dispatch entry as in progress.
2094 dispatchEntry->inProgress = true;
2095
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002096 // Publish the event.
2097 status_t status;
Jeff Browna032cc02011-03-07 16:56:21 -08002098 EventEntry* eventEntry = dispatchEntry->eventEntry;
Jeff Brown01ce2e92010-09-26 22:20:12 -07002099 switch (eventEntry->type) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002100 case EventEntry::TYPE_KEY: {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002101 KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002102
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002103 // Publish the key event.
Jeff Brown81346812011-06-28 20:08:48 -07002104 status = connection->inputPublisher.publishKeyEvent(
2105 keyEntry->deviceId, keyEntry->source,
2106 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags,
2107 keyEntry->keyCode, keyEntry->scanCode,
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002108 keyEntry->metaState, keyEntry->repeatCount, keyEntry->downTime,
2109 keyEntry->eventTime);
2110
2111 if (status) {
2112 LOGE("channel '%s' ~ Could not publish key event, "
2113 "status=%d", connection->getInputChannelName(), status);
Jeff Brownb6997262010-10-08 22:31:17 -07002114 abortBrokenDispatchCycleLocked(currentTime, connection);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002115 return;
2116 }
2117 break;
2118 }
2119
2120 case EventEntry::TYPE_MOTION: {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002121 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002122
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002123 // If headMotionSample is non-NULL, then it points to the first new sample that we
2124 // were unable to dispatch during the previous cycle so we resume dispatching from
2125 // that point in the list of motion samples.
2126 // Otherwise, we just start from the first sample of the motion event.
2127 MotionSample* firstMotionSample = dispatchEntry->headMotionSample;
2128 if (! firstMotionSample) {
2129 firstMotionSample = & motionEntry->firstSample;
2130 }
2131
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002132 PointerCoords scaledCoords[MAX_POINTERS];
2133 const PointerCoords* usingCoords = firstMotionSample->pointerCoords;
2134
Jeff Brownd3616592010-07-16 17:21:06 -07002135 // Set the X and Y offset depending on the input source.
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002136 float xOffset, yOffset, scaleFactor;
Kenny Root7a9db182011-06-02 15:16:05 -07002137 if (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER
2138 && !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002139 scaleFactor = dispatchEntry->scaleFactor;
2140 xOffset = dispatchEntry->xOffset * scaleFactor;
2141 yOffset = dispatchEntry->yOffset * scaleFactor;
2142 if (scaleFactor != 1.0f) {
2143 for (size_t i = 0; i < motionEntry->pointerCount; i++) {
2144 scaledCoords[i] = firstMotionSample->pointerCoords[i];
2145 scaledCoords[i].scale(scaleFactor);
2146 }
2147 usingCoords = scaledCoords;
2148 }
Jeff Brownd3616592010-07-16 17:21:06 -07002149 } else {
2150 xOffset = 0.0f;
2151 yOffset = 0.0f;
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002152 scaleFactor = 1.0f;
Kenny Root7a9db182011-06-02 15:16:05 -07002153
2154 // We don't want the dispatch target to know.
2155 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
2156 for (size_t i = 0; i < motionEntry->pointerCount; i++) {
2157 scaledCoords[i].clear();
2158 }
2159 usingCoords = scaledCoords;
2160 }
Jeff Brownd3616592010-07-16 17:21:06 -07002161 }
2162
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002163 // Publish the motion event and the first motion sample.
Jeff Brown81346812011-06-28 20:08:48 -07002164 status = connection->inputPublisher.publishMotionEvent(
2165 motionEntry->deviceId, motionEntry->source,
2166 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags,
2167 motionEntry->edgeFlags, motionEntry->metaState, motionEntry->buttonState,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002168 xOffset, yOffset,
2169 motionEntry->xPrecision, motionEntry->yPrecision,
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002170 motionEntry->downTime, firstMotionSample->eventTime,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002171 motionEntry->pointerCount, motionEntry->pointerProperties,
2172 usingCoords);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002173
2174 if (status) {
2175 LOGE("channel '%s' ~ Could not publish motion event, "
2176 "status=%d", connection->getInputChannelName(), status);
Jeff Brownb6997262010-10-08 22:31:17 -07002177 abortBrokenDispatchCycleLocked(currentTime, connection);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002178 return;
2179 }
2180
Jeff Brown81346812011-06-28 20:08:48 -07002181 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_MOVE
2182 || dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Jeff Browna032cc02011-03-07 16:56:21 -08002183 // Append additional motion samples.
2184 MotionSample* nextMotionSample = firstMotionSample->next;
2185 for (; nextMotionSample != NULL; nextMotionSample = nextMotionSample->next) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002186 if (usingCoords == scaledCoords) {
Kenny Root7a9db182011-06-02 15:16:05 -07002187 if (!(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
2188 for (size_t i = 0; i < motionEntry->pointerCount; i++) {
2189 scaledCoords[i] = nextMotionSample->pointerCoords[i];
2190 scaledCoords[i].scale(scaleFactor);
2191 }
Dianne Hackborn2ba3e802011-05-11 10:59:54 -07002192 }
2193 } else {
2194 usingCoords = nextMotionSample->pointerCoords;
Dianne Hackborne7d25b72011-05-09 21:19:26 -07002195 }
Jeff Browna032cc02011-03-07 16:56:21 -08002196 status = connection->inputPublisher.appendMotionSample(
Dianne Hackbornaa9d84c2011-05-09 19:00:59 -07002197 nextMotionSample->eventTime, usingCoords);
Jeff Browna032cc02011-03-07 16:56:21 -08002198 if (status == NO_MEMORY) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002199#if DEBUG_DISPATCH_CYCLE
2200 LOGD("channel '%s' ~ Shared memory buffer full. Some motion samples will "
2201 "be sent in the next dispatch cycle.",
2202 connection->getInputChannelName());
2203#endif
Jeff Browna032cc02011-03-07 16:56:21 -08002204 break;
2205 }
2206 if (status != OK) {
2207 LOGE("channel '%s' ~ Could not append motion sample "
2208 "for a reason other than out of memory, status=%d",
2209 connection->getInputChannelName(), status);
2210 abortBrokenDispatchCycleLocked(currentTime, connection);
2211 return;
2212 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002213 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002214
Jeff Browna032cc02011-03-07 16:56:21 -08002215 // Remember the next motion sample that we could not dispatch, in case we ran out
2216 // of space in the shared memory buffer.
2217 dispatchEntry->tailMotionSample = nextMotionSample;
2218 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002219 break;
2220 }
2221
2222 default: {
Jeff Brownb6110c22011-04-01 16:15:13 -07002223 LOG_ASSERT(false);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002224 }
2225 }
2226
2227 // Send the dispatch signal.
2228 status = connection->inputPublisher.sendDispatchSignal();
2229 if (status) {
2230 LOGE("channel '%s' ~ Could not send dispatch signal, status=%d",
2231 connection->getInputChannelName(), status);
Jeff Brownb6997262010-10-08 22:31:17 -07002232 abortBrokenDispatchCycleLocked(currentTime, connection);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002233 return;
2234 }
2235
2236 // Record information about the newly started dispatch cycle.
Jeff Brown01ce2e92010-09-26 22:20:12 -07002237 connection->lastEventTime = eventEntry->eventTime;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002238 connection->lastDispatchTime = currentTime;
2239
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002240 // Notify other system components.
2241 onDispatchCycleStartedLocked(currentTime, connection);
2242}
2243
Jeff Brown7fbdc842010-06-17 20:52:56 -07002244void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Jeff Brown3915bb82010-11-05 15:02:16 -07002245 const sp<Connection>& connection, bool handled) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002246#if DEBUG_DISPATCH_CYCLE
Jeff Brown9c3cda02010-06-15 01:31:58 -07002247 LOGD("channel '%s' ~ finishDispatchCycle - %01.1fms since event, "
Jeff Brown3915bb82010-11-05 15:02:16 -07002248 "%01.1fms since dispatch, handled=%s",
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002249 connection->getInputChannelName(),
2250 connection->getEventLatencyMillis(currentTime),
Jeff Brown3915bb82010-11-05 15:02:16 -07002251 connection->getDispatchLatencyMillis(currentTime),
2252 toString(handled));
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002253#endif
2254
Jeff Brown9c3cda02010-06-15 01:31:58 -07002255 if (connection->status == Connection::STATUS_BROKEN
2256 || connection->status == Connection::STATUS_ZOMBIE) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002257 return;
2258 }
2259
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002260 // Reset the publisher since the event has been consumed.
2261 // We do this now so that the publisher can release some of its internal resources
2262 // while waiting for the next dispatch cycle to begin.
2263 status_t status = connection->inputPublisher.reset();
2264 if (status) {
2265 LOGE("channel '%s' ~ Could not reset publisher, status=%d",
2266 connection->getInputChannelName(), status);
Jeff Brownb6997262010-10-08 22:31:17 -07002267 abortBrokenDispatchCycleLocked(currentTime, connection);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002268 return;
2269 }
2270
Jeff Brown3915bb82010-11-05 15:02:16 -07002271 // Notify other system components and prepare to start the next dispatch cycle.
2272 onDispatchCycleFinishedLocked(currentTime, connection, handled);
Jeff Brownb88102f2010-09-08 11:49:43 -07002273}
2274
2275void InputDispatcher::startNextDispatchCycleLocked(nsecs_t currentTime,
2276 const sp<Connection>& connection) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002277 // Start the next dispatch cycle for this connection.
2278 while (! connection->outboundQueue.isEmpty()) {
Jeff Brownb88102f2010-09-08 11:49:43 -07002279 DispatchEntry* dispatchEntry = connection->outboundQueue.headSentinel.next;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002280 if (dispatchEntry->inProgress) {
2281 // Finish or resume current event in progress.
2282 if (dispatchEntry->tailMotionSample) {
2283 // We have a tail of undispatched motion samples.
2284 // Reuse the same DispatchEntry and start a new cycle.
2285 dispatchEntry->inProgress = false;
2286 dispatchEntry->headMotionSample = dispatchEntry->tailMotionSample;
2287 dispatchEntry->tailMotionSample = NULL;
Jeff Brown519e0242010-09-15 15:18:56 -07002288 startDispatchCycleLocked(currentTime, connection);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002289 return;
2290 }
2291 // Finished.
2292 connection->outboundQueue.dequeueAtHead();
Jeff Brown519e0242010-09-15 15:18:56 -07002293 if (dispatchEntry->hasForegroundTarget()) {
2294 decrementPendingForegroundDispatchesLocked(dispatchEntry->eventEntry);
Jeff Brown6ec402b2010-07-28 15:48:59 -07002295 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002296 mAllocator.releaseDispatchEntry(dispatchEntry);
2297 } else {
2298 // If the head is not in progress, then we must have already dequeued the in
Jeff Brown519e0242010-09-15 15:18:56 -07002299 // progress event, which means we actually aborted it.
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002300 // So just start the next event for this connection.
Jeff Brown519e0242010-09-15 15:18:56 -07002301 startDispatchCycleLocked(currentTime, connection);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002302 return;
2303 }
2304 }
2305
2306 // Outbound queue is empty, deactivate the connection.
Jeff Brown7fbdc842010-06-17 20:52:56 -07002307 deactivateConnectionLocked(connection.get());
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002308}
2309
Jeff Brownb6997262010-10-08 22:31:17 -07002310void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
2311 const sp<Connection>& connection) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002312#if DEBUG_DISPATCH_CYCLE
Jeff Brown83c09682010-12-23 17:50:18 -08002313 LOGD("channel '%s' ~ abortBrokenDispatchCycle",
2314 connection->getInputChannelName());
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002315#endif
2316
Jeff Brownb88102f2010-09-08 11:49:43 -07002317 // Clear the outbound queue.
Jeff Brown519e0242010-09-15 15:18:56 -07002318 drainOutboundQueueLocked(connection.get());
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002319
Jeff Brownb6997262010-10-08 22:31:17 -07002320 // The connection appears to be unrecoverably broken.
Jeff Brown9c3cda02010-06-15 01:31:58 -07002321 // Ignore already broken or zombie connections.
Jeff Brownb6997262010-10-08 22:31:17 -07002322 if (connection->status == Connection::STATUS_NORMAL) {
2323 connection->status = Connection::STATUS_BROKEN;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002324
Jeff Brownb6997262010-10-08 22:31:17 -07002325 // Notify other system components.
2326 onDispatchCycleBrokenLocked(currentTime, connection);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002327 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002328}
2329
Jeff Brown519e0242010-09-15 15:18:56 -07002330void InputDispatcher::drainOutboundQueueLocked(Connection* connection) {
2331 while (! connection->outboundQueue.isEmpty()) {
2332 DispatchEntry* dispatchEntry = connection->outboundQueue.dequeueAtHead();
2333 if (dispatchEntry->hasForegroundTarget()) {
2334 decrementPendingForegroundDispatchesLocked(dispatchEntry->eventEntry);
Jeff Brownb88102f2010-09-08 11:49:43 -07002335 }
2336 mAllocator.releaseDispatchEntry(dispatchEntry);
Jeff Brownb88102f2010-09-08 11:49:43 -07002337 }
2338
Jeff Brown519e0242010-09-15 15:18:56 -07002339 deactivateConnectionLocked(connection);
Jeff Brownb88102f2010-09-08 11:49:43 -07002340}
2341
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002342int InputDispatcher::handleReceiveCallback(int receiveFd, int events, void* data) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002343 InputDispatcher* d = static_cast<InputDispatcher*>(data);
2344
2345 { // acquire lock
2346 AutoMutex _l(d->mLock);
2347
2348 ssize_t connectionIndex = d->mConnectionsByReceiveFd.indexOfKey(receiveFd);
2349 if (connectionIndex < 0) {
2350 LOGE("Received spurious receive callback for unknown input channel. "
2351 "fd=%d, events=0x%x", receiveFd, events);
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002352 return 0; // remove the callback
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002353 }
2354
Jeff Brown7fbdc842010-06-17 20:52:56 -07002355 nsecs_t currentTime = now();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002356
2357 sp<Connection> connection = d->mConnectionsByReceiveFd.valueAt(connectionIndex);
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002358 if (events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP)) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002359 LOGE("channel '%s' ~ Consumer closed input channel or an error occurred. "
2360 "events=0x%x", connection->getInputChannelName(), events);
Jeff Brownb6997262010-10-08 22:31:17 -07002361 d->abortBrokenDispatchCycleLocked(currentTime, connection);
Jeff Brown9c3cda02010-06-15 01:31:58 -07002362 d->runCommandsLockedInterruptible();
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002363 return 0; // remove the callback
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002364 }
2365
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002366 if (! (events & ALOOPER_EVENT_INPUT)) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002367 LOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
2368 "events=0x%x", connection->getInputChannelName(), events);
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002369 return 1;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002370 }
2371
Jeff Brown3915bb82010-11-05 15:02:16 -07002372 bool handled = false;
Jeff Brown49ed71d2010-12-06 17:13:33 -08002373 status_t status = connection->inputPublisher.receiveFinishedSignal(&handled);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002374 if (status) {
2375 LOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
2376 connection->getInputChannelName(), status);
Jeff Brownb6997262010-10-08 22:31:17 -07002377 d->abortBrokenDispatchCycleLocked(currentTime, connection);
Jeff Brown9c3cda02010-06-15 01:31:58 -07002378 d->runCommandsLockedInterruptible();
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002379 return 0; // remove the callback
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002380 }
2381
Jeff Brown3915bb82010-11-05 15:02:16 -07002382 d->finishDispatchCycleLocked(currentTime, connection, handled);
Jeff Brown9c3cda02010-06-15 01:31:58 -07002383 d->runCommandsLockedInterruptible();
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002384 return 1;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002385 } // release lock
2386}
2387
Jeff Brownb6997262010-10-08 22:31:17 -07002388void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Jeff Brownda3d5a92011-03-29 15:11:34 -07002389 const CancelationOptions& options) {
Jeff Brownb6997262010-10-08 22:31:17 -07002390 for (size_t i = 0; i < mConnectionsByReceiveFd.size(); i++) {
2391 synthesizeCancelationEventsForConnectionLocked(
Jeff Brownda3d5a92011-03-29 15:11:34 -07002392 mConnectionsByReceiveFd.valueAt(i), options);
Jeff Brownb6997262010-10-08 22:31:17 -07002393 }
2394}
2395
2396void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Jeff Brownda3d5a92011-03-29 15:11:34 -07002397 const sp<InputChannel>& channel, const CancelationOptions& options) {
Jeff Brownb6997262010-10-08 22:31:17 -07002398 ssize_t index = getConnectionIndexLocked(channel);
2399 if (index >= 0) {
2400 synthesizeCancelationEventsForConnectionLocked(
Jeff Brownda3d5a92011-03-29 15:11:34 -07002401 mConnectionsByReceiveFd.valueAt(index), options);
Jeff Brownb6997262010-10-08 22:31:17 -07002402 }
2403}
2404
2405void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
Jeff Brownda3d5a92011-03-29 15:11:34 -07002406 const sp<Connection>& connection, const CancelationOptions& options) {
Jeff Brownb6997262010-10-08 22:31:17 -07002407 nsecs_t currentTime = now();
2408
2409 mTempCancelationEvents.clear();
2410 connection->inputState.synthesizeCancelationEvents(currentTime, & mAllocator,
2411 mTempCancelationEvents, options);
2412
2413 if (! mTempCancelationEvents.isEmpty()
2414 && connection->status != Connection::STATUS_BROKEN) {
2415#if DEBUG_OUTBOUND_EVENT_DETAILS
2416 LOGD("channel '%s' ~ Synthesized %d cancelation events to bring channel back in sync "
Jeff Brownda3d5a92011-03-29 15:11:34 -07002417 "with reality: %s, mode=%d.",
2418 connection->getInputChannelName(), mTempCancelationEvents.size(),
2419 options.reason, options.mode);
Jeff Brownb6997262010-10-08 22:31:17 -07002420#endif
2421 for (size_t i = 0; i < mTempCancelationEvents.size(); i++) {
2422 EventEntry* cancelationEventEntry = mTempCancelationEvents.itemAt(i);
2423 switch (cancelationEventEntry->type) {
2424 case EventEntry::TYPE_KEY:
2425 logOutboundKeyDetailsLocked("cancel - ",
2426 static_cast<KeyEntry*>(cancelationEventEntry));
2427 break;
2428 case EventEntry::TYPE_MOTION:
2429 logOutboundMotionDetailsLocked("cancel - ",
2430 static_cast<MotionEntry*>(cancelationEventEntry));
2431 break;
2432 }
2433
Jeff Brown81346812011-06-28 20:08:48 -07002434 InputTarget target;
Jeff Brown9302c872011-07-13 22:51:29 -07002435 sp<InputWindowHandle> windowHandle = getWindowHandleLocked(connection->inputChannel);
2436 if (windowHandle != NULL) {
2437 target.xOffset = -windowHandle->frameLeft;
2438 target.yOffset = -windowHandle->frameTop;
2439 target.scaleFactor = windowHandle->scaleFactor;
Jeff Brownb6997262010-10-08 22:31:17 -07002440 } else {
Jeff Brown81346812011-06-28 20:08:48 -07002441 target.xOffset = 0;
2442 target.yOffset = 0;
2443 target.scaleFactor = 1.0f;
Jeff Brownb6997262010-10-08 22:31:17 -07002444 }
Jeff Brown81346812011-06-28 20:08:48 -07002445 target.inputChannel = connection->inputChannel;
2446 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
Jeff Brownb6997262010-10-08 22:31:17 -07002447
Jeff Brown81346812011-06-28 20:08:48 -07002448 enqueueDispatchEntryLocked(connection, cancelationEventEntry, // increments ref
2449 &target, false, InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brownb6997262010-10-08 22:31:17 -07002450
2451 mAllocator.releaseEventEntry(cancelationEventEntry);
2452 }
2453
2454 if (!connection->outboundQueue.headSentinel.next->inProgress) {
2455 startDispatchCycleLocked(currentTime, connection);
2456 }
2457 }
2458}
2459
Jeff Brown01ce2e92010-09-26 22:20:12 -07002460InputDispatcher::MotionEntry*
2461InputDispatcher::splitMotionEvent(const MotionEntry* originalMotionEntry, BitSet32 pointerIds) {
Jeff Brownb6110c22011-04-01 16:15:13 -07002462 LOG_ASSERT(pointerIds.value != 0);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002463
2464 uint32_t splitPointerIndexMap[MAX_POINTERS];
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002465 PointerProperties splitPointerProperties[MAX_POINTERS];
Jeff Brown01ce2e92010-09-26 22:20:12 -07002466 PointerCoords splitPointerCoords[MAX_POINTERS];
2467
2468 uint32_t originalPointerCount = originalMotionEntry->pointerCount;
2469 uint32_t splitPointerCount = 0;
2470
2471 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
2472 originalPointerIndex++) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002473 const PointerProperties& pointerProperties =
2474 originalMotionEntry->pointerProperties[originalPointerIndex];
2475 uint32_t pointerId = uint32_t(pointerProperties.id);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002476 if (pointerIds.hasBit(pointerId)) {
2477 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002478 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
Jeff Brownace13b12011-03-09 17:39:48 -08002479 splitPointerCoords[splitPointerCount].copyFrom(
2480 originalMotionEntry->firstSample.pointerCoords[originalPointerIndex]);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002481 splitPointerCount += 1;
2482 }
2483 }
Jeff Brown58a2da82011-01-25 16:02:22 -08002484
2485 if (splitPointerCount != pointerIds.count()) {
2486 // This is bad. We are missing some of the pointers that we expected to deliver.
2487 // Most likely this indicates that we received an ACTION_MOVE events that has
2488 // different pointer ids than we expected based on the previous ACTION_DOWN
2489 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
2490 // in this way.
2491 LOGW("Dropping split motion event because the pointer count is %d but "
2492 "we expected there to be %d pointers. This probably means we received "
2493 "a broken sequence of pointer ids from the input device.",
2494 splitPointerCount, pointerIds.count());
2495 return NULL;
2496 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07002497
2498 int32_t action = originalMotionEntry->action;
2499 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
2500 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
2501 || maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2502 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002503 const PointerProperties& pointerProperties =
2504 originalMotionEntry->pointerProperties[originalPointerIndex];
2505 uint32_t pointerId = uint32_t(pointerProperties.id);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002506 if (pointerIds.hasBit(pointerId)) {
2507 if (pointerIds.count() == 1) {
2508 // The first/last pointer went down/up.
2509 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
2510 ? AMOTION_EVENT_ACTION_DOWN : AMOTION_EVENT_ACTION_UP;
Jeff Brown9a01d052010-09-27 16:35:11 -07002511 } else {
2512 // A secondary pointer went down/up.
2513 uint32_t splitPointerIndex = 0;
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002514 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
Jeff Brown9a01d052010-09-27 16:35:11 -07002515 splitPointerIndex += 1;
2516 }
2517 action = maskedAction | (splitPointerIndex
2518 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002519 }
2520 } else {
2521 // An unrelated pointer changed.
2522 action = AMOTION_EVENT_ACTION_MOVE;
2523 }
2524 }
2525
2526 MotionEntry* splitMotionEntry = mAllocator.obtainMotionEntry(
2527 originalMotionEntry->eventTime,
2528 originalMotionEntry->deviceId,
2529 originalMotionEntry->source,
2530 originalMotionEntry->policyFlags,
2531 action,
2532 originalMotionEntry->flags,
2533 originalMotionEntry->metaState,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002534 originalMotionEntry->buttonState,
Jeff Brown01ce2e92010-09-26 22:20:12 -07002535 originalMotionEntry->edgeFlags,
2536 originalMotionEntry->xPrecision,
2537 originalMotionEntry->yPrecision,
2538 originalMotionEntry->downTime,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002539 splitPointerCount, splitPointerProperties, splitPointerCoords);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002540
2541 for (MotionSample* originalMotionSample = originalMotionEntry->firstSample.next;
2542 originalMotionSample != NULL; originalMotionSample = originalMotionSample->next) {
2543 for (uint32_t splitPointerIndex = 0; splitPointerIndex < splitPointerCount;
2544 splitPointerIndex++) {
2545 uint32_t originalPointerIndex = splitPointerIndexMap[splitPointerIndex];
Jeff Brownace13b12011-03-09 17:39:48 -08002546 splitPointerCoords[splitPointerIndex].copyFrom(
2547 originalMotionSample->pointerCoords[originalPointerIndex]);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002548 }
2549
2550 mAllocator.appendMotionSample(splitMotionEntry, originalMotionSample->eventTime,
2551 splitPointerCoords);
2552 }
2553
Jeff Browna032cc02011-03-07 16:56:21 -08002554 if (originalMotionEntry->injectionState) {
2555 splitMotionEntry->injectionState = originalMotionEntry->injectionState;
2556 splitMotionEntry->injectionState->refCount += 1;
2557 }
2558
Jeff Brown01ce2e92010-09-26 22:20:12 -07002559 return splitMotionEntry;
2560}
2561
Jeff Brown9c3cda02010-06-15 01:31:58 -07002562void InputDispatcher::notifyConfigurationChanged(nsecs_t eventTime) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002563#if DEBUG_INBOUND_EVENT_DETAILS
Jeff Brown9c3cda02010-06-15 01:31:58 -07002564 LOGD("notifyConfigurationChanged - eventTime=%lld", eventTime);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002565#endif
2566
Jeff Brownb88102f2010-09-08 11:49:43 -07002567 bool needWake;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002568 { // acquire lock
2569 AutoMutex _l(mLock);
2570
Jeff Brown7fbdc842010-06-17 20:52:56 -07002571 ConfigurationChangedEntry* newEntry = mAllocator.obtainConfigurationChangedEntry(eventTime);
Jeff Brownb88102f2010-09-08 11:49:43 -07002572 needWake = enqueueInboundEventLocked(newEntry);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002573 } // release lock
2574
Jeff Brownb88102f2010-09-08 11:49:43 -07002575 if (needWake) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002576 mLooper->wake();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002577 }
2578}
2579
Jeff Brown58a2da82011-01-25 16:02:22 -08002580void InputDispatcher::notifyKey(nsecs_t eventTime, int32_t deviceId, uint32_t source,
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002581 uint32_t policyFlags, int32_t action, int32_t flags,
2582 int32_t keyCode, int32_t scanCode, int32_t metaState, nsecs_t downTime) {
2583#if DEBUG_INBOUND_EVENT_DETAILS
Jeff Brown90655042010-12-02 13:50:46 -08002584 LOGD("notifyKey - eventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, action=0x%x, "
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002585 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%lld",
Jeff Brownc5ed5912010-07-14 18:48:53 -07002586 eventTime, deviceId, source, policyFlags, action, flags,
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002587 keyCode, scanCode, metaState, downTime);
2588#endif
Jeff Brown01ce2e92010-09-26 22:20:12 -07002589 if (! validateKeyEvent(action)) {
2590 return;
2591 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002592
Jeff Brown1f245102010-11-18 20:53:46 -08002593 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
2594 policyFlags |= POLICY_FLAG_VIRTUAL;
2595 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
2596 }
Jeff Brown924c4d42011-03-07 16:40:47 -08002597 if (policyFlags & POLICY_FLAG_ALT) {
2598 metaState |= AMETA_ALT_ON | AMETA_ALT_LEFT_ON;
2599 }
2600 if (policyFlags & POLICY_FLAG_ALT_GR) {
2601 metaState |= AMETA_ALT_ON | AMETA_ALT_RIGHT_ON;
2602 }
2603 if (policyFlags & POLICY_FLAG_SHIFT) {
2604 metaState |= AMETA_SHIFT_ON | AMETA_SHIFT_LEFT_ON;
2605 }
2606 if (policyFlags & POLICY_FLAG_CAPS_LOCK) {
2607 metaState |= AMETA_CAPS_LOCK_ON;
2608 }
2609 if (policyFlags & POLICY_FLAG_FUNCTION) {
2610 metaState |= AMETA_FUNCTION_ON;
2611 }
Jeff Brown1f245102010-11-18 20:53:46 -08002612
Jeff Browne20c9e02010-10-11 14:20:19 -07002613 policyFlags |= POLICY_FLAG_TRUSTED;
Jeff Brown1f245102010-11-18 20:53:46 -08002614
2615 KeyEvent event;
2616 event.initialize(deviceId, source, action, flags, keyCode, scanCode,
2617 metaState, 0, downTime, eventTime);
2618
2619 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
2620
2621 if (policyFlags & POLICY_FLAG_WOKE_HERE) {
2622 flags |= AKEY_EVENT_FLAG_WOKE_HERE;
2623 }
Jeff Brownb6997262010-10-08 22:31:17 -07002624
Jeff Brownb88102f2010-09-08 11:49:43 -07002625 bool needWake;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002626 { // acquire lock
Jeff Brown0029c662011-03-30 02:25:18 -07002627 mLock.lock();
2628
2629 if (mInputFilterEnabled) {
2630 mLock.unlock();
2631
2632 policyFlags |= POLICY_FLAG_FILTERED;
2633 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2634 return; // event was consumed by the filter
2635 }
2636
2637 mLock.lock();
2638 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002639
Jeff Brown7fbdc842010-06-17 20:52:56 -07002640 int32_t repeatCount = 0;
2641 KeyEntry* newEntry = mAllocator.obtainKeyEntry(eventTime,
Jeff Brownc5ed5912010-07-14 18:48:53 -07002642 deviceId, source, policyFlags, action, flags, keyCode, scanCode,
Jeff Brown7fbdc842010-06-17 20:52:56 -07002643 metaState, repeatCount, downTime);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002644
Jeff Brownb88102f2010-09-08 11:49:43 -07002645 needWake = enqueueInboundEventLocked(newEntry);
Jeff Brown0029c662011-03-30 02:25:18 -07002646 mLock.unlock();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002647 } // release lock
2648
Jeff Brownb88102f2010-09-08 11:49:43 -07002649 if (needWake) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002650 mLooper->wake();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002651 }
2652}
2653
Jeff Brown58a2da82011-01-25 16:02:22 -08002654void InputDispatcher::notifyMotion(nsecs_t eventTime, int32_t deviceId, uint32_t source,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002655 uint32_t policyFlags, int32_t action, int32_t flags,
2656 int32_t metaState, int32_t buttonState, int32_t edgeFlags,
2657 uint32_t pointerCount, const PointerProperties* pointerProperties,
2658 const PointerCoords* pointerCoords,
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002659 float xPrecision, float yPrecision, nsecs_t downTime) {
2660#if DEBUG_INBOUND_EVENT_DETAILS
Jeff Brown90655042010-12-02 13:50:46 -08002661 LOGD("notifyMotion - eventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, "
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002662 "action=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, edgeFlags=0x%x, "
Jeff Brown85a31762010-09-01 17:01:00 -07002663 "xPrecision=%f, yPrecision=%f, downTime=%lld",
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002664 eventTime, deviceId, source, policyFlags, action, flags,
2665 metaState, buttonState, edgeFlags,
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002666 xPrecision, yPrecision, downTime);
2667 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002668 LOGD(" Pointer %d: id=%d, toolType=%d, "
2669 "x=%f, y=%f, pressure=%f, size=%f, "
Jeff Brown85a31762010-09-01 17:01:00 -07002670 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
Jeff Brown8d608662010-08-30 03:02:23 -07002671 "orientation=%f",
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002672 i, pointerProperties[i].id,
2673 pointerProperties[i].toolType,
Jeff Brownebbd5d12011-02-17 13:01:34 -08002674 pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
2675 pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
2676 pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
2677 pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
2678 pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
2679 pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
2680 pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
2681 pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
2682 pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002683 }
2684#endif
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002685 if (! validateMotionEvent(action, pointerCount, pointerProperties)) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002686 return;
2687 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002688
Jeff Browne20c9e02010-10-11 14:20:19 -07002689 policyFlags |= POLICY_FLAG_TRUSTED;
Jeff Brown56194eb2011-03-02 19:23:13 -08002690 mPolicy->interceptMotionBeforeQueueing(eventTime, /*byref*/ policyFlags);
Jeff Brownb6997262010-10-08 22:31:17 -07002691
Jeff Brownb88102f2010-09-08 11:49:43 -07002692 bool needWake;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002693 { // acquire lock
Jeff Brown0029c662011-03-30 02:25:18 -07002694 mLock.lock();
2695
2696 if (mInputFilterEnabled) {
2697 mLock.unlock();
2698
2699 MotionEvent event;
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002700 event.initialize(deviceId, source, action, flags, edgeFlags, metaState,
2701 buttonState, 0, 0,
Jeff Brown0029c662011-03-30 02:25:18 -07002702 xPrecision, yPrecision, downTime, eventTime,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002703 pointerCount, pointerProperties, pointerCoords);
Jeff Brown0029c662011-03-30 02:25:18 -07002704
2705 policyFlags |= POLICY_FLAG_FILTERED;
2706 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2707 return; // event was consumed by the filter
2708 }
2709
2710 mLock.lock();
2711 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002712
2713 // Attempt batching and streaming of move events.
Jeff Browncc0c1592011-02-19 05:07:28 -08002714 if (action == AMOTION_EVENT_ACTION_MOVE
2715 || action == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002716 // BATCHING CASE
2717 //
2718 // Try to append a move sample to the tail of the inbound queue for this device.
2719 // Give up if we encounter a non-move motion event for this device since that
2720 // means we cannot append any new samples until a new motion event has started.
Jeff Brownb88102f2010-09-08 11:49:43 -07002721 for (EventEntry* entry = mInboundQueue.tailSentinel.prev;
2722 entry != & mInboundQueue.headSentinel; entry = entry->prev) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002723 if (entry->type != EventEntry::TYPE_MOTION) {
2724 // Keep looking for motion events.
2725 continue;
2726 }
2727
2728 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
Jeff Brownefd32662011-03-08 15:13:06 -08002729 if (motionEntry->deviceId != deviceId
2730 || motionEntry->source != source) {
2731 // Keep looking for this device and source.
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002732 continue;
2733 }
2734
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002735 if (!motionEntry->canAppendSamples(action, pointerCount, pointerProperties)) {
Jeff Brownefd32662011-03-08 15:13:06 -08002736 // Last motion event in the queue for this device and source is
2737 // not compatible for appending new samples. Stop here.
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002738 goto NoBatchingOrStreaming;
2739 }
2740
Jeff Brown9c3cda02010-06-15 01:31:58 -07002741 // Do the batching magic.
Jeff Brown4e91a182011-04-07 11:38:09 -07002742 batchMotionLocked(motionEntry, eventTime, metaState, pointerCoords,
2743 "most recent motion event for this device and source in the inbound queue");
Jeff Brown0029c662011-03-30 02:25:18 -07002744 mLock.unlock();
Jeff Brown9c3cda02010-06-15 01:31:58 -07002745 return; // done!
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002746 }
2747
Jeff Brownf6989da2011-04-06 17:19:48 -07002748 // BATCHING ONTO PENDING EVENT CASE
2749 //
2750 // Try to append a move sample to the currently pending event, if there is one.
2751 // We can do this as long as we are still waiting to find the targets for the
2752 // event. Once the targets are locked-in we can only do streaming.
2753 if (mPendingEvent
2754 && (!mPendingEvent->dispatchInProgress || !mCurrentInputTargetsValid)
2755 && mPendingEvent->type == EventEntry::TYPE_MOTION) {
2756 MotionEntry* motionEntry = static_cast<MotionEntry*>(mPendingEvent);
2757 if (motionEntry->deviceId == deviceId && motionEntry->source == source) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002758 if (!motionEntry->canAppendSamples(action, pointerCount, pointerProperties)) {
Jeff Brown4e91a182011-04-07 11:38:09 -07002759 // Pending motion event is for this device and source but it is
2760 // not compatible for appending new samples. Stop here.
Jeff Brownf6989da2011-04-06 17:19:48 -07002761 goto NoBatchingOrStreaming;
2762 }
2763
Jeff Brownf6989da2011-04-06 17:19:48 -07002764 // Do the batching magic.
Jeff Brown4e91a182011-04-07 11:38:09 -07002765 batchMotionLocked(motionEntry, eventTime, metaState, pointerCoords,
2766 "pending motion event");
Jeff Brownf6989da2011-04-06 17:19:48 -07002767 mLock.unlock();
2768 return; // done!
2769 }
2770 }
2771
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002772 // STREAMING CASE
2773 //
2774 // There is no pending motion event (of any kind) for this device in the inbound queue.
Jeff Brown519e0242010-09-15 15:18:56 -07002775 // Search the outbound queue for the current foreground targets to find a dispatched
2776 // motion event that is still in progress. If found, then, appen the new sample to
2777 // that event and push it out to all current targets. The logic in
2778 // prepareDispatchCycleLocked takes care of the case where some targets may
2779 // already have consumed the motion event by starting a new dispatch cycle if needed.
Jeff Brown9c3cda02010-06-15 01:31:58 -07002780 if (mCurrentInputTargetsValid) {
Jeff Brown519e0242010-09-15 15:18:56 -07002781 for (size_t i = 0; i < mCurrentInputTargets.size(); i++) {
2782 const InputTarget& inputTarget = mCurrentInputTargets[i];
2783 if ((inputTarget.flags & InputTarget::FLAG_FOREGROUND) == 0) {
2784 // Skip non-foreground targets. We only want to stream if there is at
2785 // least one foreground target whose dispatch is still in progress.
2786 continue;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002787 }
Jeff Brown519e0242010-09-15 15:18:56 -07002788
2789 ssize_t connectionIndex = getConnectionIndexLocked(inputTarget.inputChannel);
2790 if (connectionIndex < 0) {
2791 // Connection must no longer be valid.
2792 continue;
2793 }
2794
2795 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
2796 if (connection->outboundQueue.isEmpty()) {
2797 // This foreground target has an empty outbound queue.
2798 continue;
2799 }
2800
2801 DispatchEntry* dispatchEntry = connection->outboundQueue.headSentinel.next;
2802 if (! dispatchEntry->inProgress
Jeff Brown01ce2e92010-09-26 22:20:12 -07002803 || dispatchEntry->eventEntry->type != EventEntry::TYPE_MOTION
2804 || dispatchEntry->isSplit()) {
2805 // No motion event is being dispatched, or it is being split across
2806 // windows in which case we cannot stream.
Jeff Brown519e0242010-09-15 15:18:56 -07002807 continue;
2808 }
2809
2810 MotionEntry* motionEntry = static_cast<MotionEntry*>(
2811 dispatchEntry->eventEntry);
Jeff Browncc0c1592011-02-19 05:07:28 -08002812 if (motionEntry->action != action
Jeff Brown519e0242010-09-15 15:18:56 -07002813 || motionEntry->deviceId != deviceId
Jeff Brown58a2da82011-01-25 16:02:22 -08002814 || motionEntry->source != source
Jeff Brown519e0242010-09-15 15:18:56 -07002815 || motionEntry->pointerCount != pointerCount
2816 || motionEntry->isInjected()) {
2817 // The motion event is not compatible with this move.
2818 continue;
2819 }
2820
Jeff Browna032cc02011-03-07 16:56:21 -08002821 if (action == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Jeff Brown9302c872011-07-13 22:51:29 -07002822 if (mLastHoverWindowHandle == NULL) {
Jeff Browna032cc02011-03-07 16:56:21 -08002823#if DEBUG_BATCHING
2824 LOGD("Not streaming hover move because there is no "
2825 "last hovered window.");
2826#endif
2827 goto NoBatchingOrStreaming;
2828 }
2829
Jeff Brown9302c872011-07-13 22:51:29 -07002830 sp<InputWindowHandle> hoverWindowHandle = findTouchedWindowAtLocked(
Jeff Browna032cc02011-03-07 16:56:21 -08002831 pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X),
2832 pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Jeff Brown9302c872011-07-13 22:51:29 -07002833 if (mLastHoverWindowHandle != hoverWindowHandle) {
Jeff Browna032cc02011-03-07 16:56:21 -08002834#if DEBUG_BATCHING
2835 LOGD("Not streaming hover move because the last hovered window "
2836 "is '%s' but the currently hovered window is '%s'.",
Jeff Brown9302c872011-07-13 22:51:29 -07002837 mLastHoverWindowHandle->name.string(),
2838 hoverWindowHandle != NULL
2839 ? hoverWindowHandle->name.string() : "<null>");
Jeff Browna032cc02011-03-07 16:56:21 -08002840#endif
2841 goto NoBatchingOrStreaming;
2842 }
2843 }
2844
Jeff Brown519e0242010-09-15 15:18:56 -07002845 // Hurray! This foreground target is currently dispatching a move event
2846 // that we can stream onto. Append the motion sample and resume dispatch.
2847 mAllocator.appendMotionSample(motionEntry, eventTime, pointerCoords);
2848#if DEBUG_BATCHING
2849 LOGD("Appended motion sample onto batch for most recently dispatched "
Jeff Brown4e91a182011-04-07 11:38:09 -07002850 "motion event for this device and source in the outbound queues. "
Jeff Brown519e0242010-09-15 15:18:56 -07002851 "Attempting to stream the motion sample.");
2852#endif
2853 nsecs_t currentTime = now();
2854 dispatchEventToCurrentInputTargetsLocked(currentTime, motionEntry,
2855 true /*resumeWithAppendedMotionSample*/);
2856
2857 runCommandsLockedInterruptible();
Jeff Brown0029c662011-03-30 02:25:18 -07002858 mLock.unlock();
Jeff Brown519e0242010-09-15 15:18:56 -07002859 return; // done!
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002860 }
2861 }
2862
2863NoBatchingOrStreaming:;
2864 }
2865
2866 // Just enqueue a new motion event.
Jeff Brown7fbdc842010-06-17 20:52:56 -07002867 MotionEntry* newEntry = mAllocator.obtainMotionEntry(eventTime,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002868 deviceId, source, policyFlags, action, flags, metaState, buttonState, edgeFlags,
Jeff Brown7fbdc842010-06-17 20:52:56 -07002869 xPrecision, yPrecision, downTime,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002870 pointerCount, pointerProperties, pointerCoords);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002871
Jeff Brownb88102f2010-09-08 11:49:43 -07002872 needWake = enqueueInboundEventLocked(newEntry);
Jeff Brown0029c662011-03-30 02:25:18 -07002873 mLock.unlock();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002874 } // release lock
2875
Jeff Brownb88102f2010-09-08 11:49:43 -07002876 if (needWake) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002877 mLooper->wake();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002878 }
2879}
2880
Jeff Brown4e91a182011-04-07 11:38:09 -07002881void InputDispatcher::batchMotionLocked(MotionEntry* entry, nsecs_t eventTime,
2882 int32_t metaState, const PointerCoords* pointerCoords, const char* eventDescription) {
2883 // Combine meta states.
2884 entry->metaState |= metaState;
2885
2886 // Coalesce this sample if not enough time has elapsed since the last sample was
2887 // initially appended to the batch.
2888 MotionSample* lastSample = entry->lastSample;
2889 long interval = eventTime - lastSample->eventTimeBeforeCoalescing;
2890 if (interval <= MOTION_SAMPLE_COALESCE_INTERVAL) {
2891 uint32_t pointerCount = entry->pointerCount;
2892 for (uint32_t i = 0; i < pointerCount; i++) {
2893 lastSample->pointerCoords[i].copyFrom(pointerCoords[i]);
2894 }
2895 lastSample->eventTime = eventTime;
2896#if DEBUG_BATCHING
2897 LOGD("Coalesced motion into last sample of batch for %s, events were %0.3f ms apart",
2898 eventDescription, interval * 0.000001f);
2899#endif
2900 return;
2901 }
2902
2903 // Append the sample.
2904 mAllocator.appendMotionSample(entry, eventTime, pointerCoords);
2905#if DEBUG_BATCHING
2906 LOGD("Appended motion sample onto batch for %s, events were %0.3f ms apart",
2907 eventDescription, interval * 0.000001f);
2908#endif
2909}
2910
Jeff Brownb6997262010-10-08 22:31:17 -07002911void InputDispatcher::notifySwitch(nsecs_t when, int32_t switchCode, int32_t switchValue,
2912 uint32_t policyFlags) {
2913#if DEBUG_INBOUND_EVENT_DETAILS
2914 LOGD("notifySwitch - switchCode=%d, switchValue=%d, policyFlags=0x%x",
2915 switchCode, switchValue, policyFlags);
2916#endif
2917
Jeff Browne20c9e02010-10-11 14:20:19 -07002918 policyFlags |= POLICY_FLAG_TRUSTED;
Jeff Brownb6997262010-10-08 22:31:17 -07002919 mPolicy->notifySwitch(when, switchCode, switchValue, policyFlags);
2920}
2921
Jeff Brown7fbdc842010-06-17 20:52:56 -07002922int32_t InputDispatcher::injectInputEvent(const InputEvent* event,
Jeff Brown0029c662011-03-30 02:25:18 -07002923 int32_t injectorPid, int32_t injectorUid, int32_t syncMode, int32_t timeoutMillis,
2924 uint32_t policyFlags) {
Jeff Brown7fbdc842010-06-17 20:52:56 -07002925#if DEBUG_INBOUND_EVENT_DETAILS
2926 LOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Jeff Brown0029c662011-03-30 02:25:18 -07002927 "syncMode=%d, timeoutMillis=%d, policyFlags=0x%08x",
2928 event->getType(), injectorPid, injectorUid, syncMode, timeoutMillis, policyFlags);
Jeff Brown7fbdc842010-06-17 20:52:56 -07002929#endif
2930
2931 nsecs_t endTime = now() + milliseconds_to_nanoseconds(timeoutMillis);
Jeff Browne20c9e02010-10-11 14:20:19 -07002932
Jeff Brown0029c662011-03-30 02:25:18 -07002933 policyFlags |= POLICY_FLAG_INJECTED;
Jeff Browne20c9e02010-10-11 14:20:19 -07002934 if (hasInjectionPermission(injectorPid, injectorUid)) {
2935 policyFlags |= POLICY_FLAG_TRUSTED;
2936 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07002937
Jeff Brownb6997262010-10-08 22:31:17 -07002938 EventEntry* injectedEntry;
2939 switch (event->getType()) {
2940 case AINPUT_EVENT_TYPE_KEY: {
2941 const KeyEvent* keyEvent = static_cast<const KeyEvent*>(event);
2942 int32_t action = keyEvent->getAction();
2943 if (! validateKeyEvent(action)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07002944 return INPUT_EVENT_INJECTION_FAILED;
2945 }
2946
Jeff Brownb6997262010-10-08 22:31:17 -07002947 int32_t flags = keyEvent->getFlags();
Jeff Brown1f245102010-11-18 20:53:46 -08002948 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
2949 policyFlags |= POLICY_FLAG_VIRTUAL;
2950 }
2951
Jeff Brown0029c662011-03-30 02:25:18 -07002952 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
2953 mPolicy->interceptKeyBeforeQueueing(keyEvent, /*byref*/ policyFlags);
2954 }
Jeff Brown1f245102010-11-18 20:53:46 -08002955
2956 if (policyFlags & POLICY_FLAG_WOKE_HERE) {
2957 flags |= AKEY_EVENT_FLAG_WOKE_HERE;
2958 }
Jeff Brown6ec402b2010-07-28 15:48:59 -07002959
Jeff Brownb6997262010-10-08 22:31:17 -07002960 mLock.lock();
Jeff Brown1f245102010-11-18 20:53:46 -08002961 injectedEntry = mAllocator.obtainKeyEntry(keyEvent->getEventTime(),
2962 keyEvent->getDeviceId(), keyEvent->getSource(),
2963 policyFlags, action, flags,
2964 keyEvent->getKeyCode(), keyEvent->getScanCode(), keyEvent->getMetaState(),
Jeff Brownb6997262010-10-08 22:31:17 -07002965 keyEvent->getRepeatCount(), keyEvent->getDownTime());
2966 break;
2967 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07002968
Jeff Brownb6997262010-10-08 22:31:17 -07002969 case AINPUT_EVENT_TYPE_MOTION: {
2970 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
2971 int32_t action = motionEvent->getAction();
2972 size_t pointerCount = motionEvent->getPointerCount();
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002973 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
2974 if (! validateMotionEvent(action, pointerCount, pointerProperties)) {
Jeff Brownb6997262010-10-08 22:31:17 -07002975 return INPUT_EVENT_INJECTION_FAILED;
2976 }
2977
Jeff Brown0029c662011-03-30 02:25:18 -07002978 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
2979 nsecs_t eventTime = motionEvent->getEventTime();
2980 mPolicy->interceptMotionBeforeQueueing(eventTime, /*byref*/ policyFlags);
2981 }
Jeff Brownb6997262010-10-08 22:31:17 -07002982
2983 mLock.lock();
2984 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
2985 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
2986 MotionEntry* motionEntry = mAllocator.obtainMotionEntry(*sampleEventTimes,
2987 motionEvent->getDeviceId(), motionEvent->getSource(), policyFlags,
2988 action, motionEvent->getFlags(),
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002989 motionEvent->getMetaState(), motionEvent->getButtonState(),
2990 motionEvent->getEdgeFlags(),
Jeff Brownb6997262010-10-08 22:31:17 -07002991 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
2992 motionEvent->getDownTime(), uint32_t(pointerCount),
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002993 pointerProperties, samplePointerCoords);
Jeff Brownb6997262010-10-08 22:31:17 -07002994 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
2995 sampleEventTimes += 1;
2996 samplePointerCoords += pointerCount;
2997 mAllocator.appendMotionSample(motionEntry, *sampleEventTimes, samplePointerCoords);
2998 }
2999 injectedEntry = motionEntry;
3000 break;
3001 }
3002
3003 default:
3004 LOGW("Cannot inject event of type %d", event->getType());
3005 return INPUT_EVENT_INJECTION_FAILED;
3006 }
3007
3008 InjectionState* injectionState = mAllocator.obtainInjectionState(injectorPid, injectorUid);
3009 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
3010 injectionState->injectionIsAsync = true;
3011 }
3012
3013 injectionState->refCount += 1;
3014 injectedEntry->injectionState = injectionState;
3015
3016 bool needWake = enqueueInboundEventLocked(injectedEntry);
3017 mLock.unlock();
Jeff Brown7fbdc842010-06-17 20:52:56 -07003018
Jeff Brownb88102f2010-09-08 11:49:43 -07003019 if (needWake) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07003020 mLooper->wake();
Jeff Brown7fbdc842010-06-17 20:52:56 -07003021 }
3022
3023 int32_t injectionResult;
3024 { // acquire lock
3025 AutoMutex _l(mLock);
3026
Jeff Brown6ec402b2010-07-28 15:48:59 -07003027 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
3028 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
3029 } else {
3030 for (;;) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07003031 injectionResult = injectionState->injectionResult;
Jeff Brown6ec402b2010-07-28 15:48:59 -07003032 if (injectionResult != INPUT_EVENT_INJECTION_PENDING) {
3033 break;
3034 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07003035
Jeff Brown7fbdc842010-06-17 20:52:56 -07003036 nsecs_t remainingTimeout = endTime - now();
3037 if (remainingTimeout <= 0) {
Jeff Brown6ec402b2010-07-28 15:48:59 -07003038#if DEBUG_INJECTION
3039 LOGD("injectInputEvent - Timed out waiting for injection result "
3040 "to become available.");
3041#endif
Jeff Brown7fbdc842010-06-17 20:52:56 -07003042 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
3043 break;
3044 }
3045
Jeff Brown6ec402b2010-07-28 15:48:59 -07003046 mInjectionResultAvailableCondition.waitRelative(mLock, remainingTimeout);
3047 }
3048
3049 if (injectionResult == INPUT_EVENT_INJECTION_SUCCEEDED
3050 && syncMode == INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07003051 while (injectionState->pendingForegroundDispatches != 0) {
Jeff Brown6ec402b2010-07-28 15:48:59 -07003052#if DEBUG_INJECTION
Jeff Brown519e0242010-09-15 15:18:56 -07003053 LOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
Jeff Brown01ce2e92010-09-26 22:20:12 -07003054 injectionState->pendingForegroundDispatches);
Jeff Brown6ec402b2010-07-28 15:48:59 -07003055#endif
3056 nsecs_t remainingTimeout = endTime - now();
3057 if (remainingTimeout <= 0) {
3058#if DEBUG_INJECTION
Jeff Brown519e0242010-09-15 15:18:56 -07003059 LOGD("injectInputEvent - Timed out waiting for pending foreground "
Jeff Brown6ec402b2010-07-28 15:48:59 -07003060 "dispatches to finish.");
3061#endif
3062 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
3063 break;
3064 }
3065
3066 mInjectionSyncFinishedCondition.waitRelative(mLock, remainingTimeout);
3067 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07003068 }
3069 }
3070
Jeff Brown01ce2e92010-09-26 22:20:12 -07003071 mAllocator.releaseInjectionState(injectionState);
Jeff Brown7fbdc842010-06-17 20:52:56 -07003072 } // release lock
3073
Jeff Brown6ec402b2010-07-28 15:48:59 -07003074#if DEBUG_INJECTION
3075 LOGD("injectInputEvent - Finished with result %d. "
3076 "injectorPid=%d, injectorUid=%d",
3077 injectionResult, injectorPid, injectorUid);
3078#endif
3079
Jeff Brown7fbdc842010-06-17 20:52:56 -07003080 return injectionResult;
3081}
3082
Jeff Brownb6997262010-10-08 22:31:17 -07003083bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
3084 return injectorUid == 0
3085 || mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
3086}
3087
Jeff Brown7fbdc842010-06-17 20:52:56 -07003088void InputDispatcher::setInjectionResultLocked(EventEntry* entry, int32_t injectionResult) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07003089 InjectionState* injectionState = entry->injectionState;
3090 if (injectionState) {
Jeff Brown7fbdc842010-06-17 20:52:56 -07003091#if DEBUG_INJECTION
3092 LOGD("Setting input event injection result to %d. "
3093 "injectorPid=%d, injectorUid=%d",
Jeff Brown01ce2e92010-09-26 22:20:12 -07003094 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
Jeff Brown7fbdc842010-06-17 20:52:56 -07003095#endif
3096
Jeff Brown0029c662011-03-30 02:25:18 -07003097 if (injectionState->injectionIsAsync
3098 && !(entry->policyFlags & POLICY_FLAG_FILTERED)) {
Jeff Brown6ec402b2010-07-28 15:48:59 -07003099 // Log the outcome since the injector did not wait for the injection result.
3100 switch (injectionResult) {
3101 case INPUT_EVENT_INJECTION_SUCCEEDED:
3102 LOGV("Asynchronous input event injection succeeded.");
3103 break;
3104 case INPUT_EVENT_INJECTION_FAILED:
3105 LOGW("Asynchronous input event injection failed.");
3106 break;
3107 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
3108 LOGW("Asynchronous input event injection permission denied.");
3109 break;
3110 case INPUT_EVENT_INJECTION_TIMED_OUT:
3111 LOGW("Asynchronous input event injection timed out.");
3112 break;
3113 }
3114 }
3115
Jeff Brown01ce2e92010-09-26 22:20:12 -07003116 injectionState->injectionResult = injectionResult;
Jeff Brown7fbdc842010-06-17 20:52:56 -07003117 mInjectionResultAvailableCondition.broadcast();
3118 }
3119}
3120
Jeff Brown01ce2e92010-09-26 22:20:12 -07003121void InputDispatcher::incrementPendingForegroundDispatchesLocked(EventEntry* entry) {
3122 InjectionState* injectionState = entry->injectionState;
3123 if (injectionState) {
3124 injectionState->pendingForegroundDispatches += 1;
3125 }
3126}
3127
Jeff Brown519e0242010-09-15 15:18:56 -07003128void InputDispatcher::decrementPendingForegroundDispatchesLocked(EventEntry* entry) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07003129 InjectionState* injectionState = entry->injectionState;
3130 if (injectionState) {
3131 injectionState->pendingForegroundDispatches -= 1;
Jeff Brown6ec402b2010-07-28 15:48:59 -07003132
Jeff Brown01ce2e92010-09-26 22:20:12 -07003133 if (injectionState->pendingForegroundDispatches == 0) {
3134 mInjectionSyncFinishedCondition.broadcast();
3135 }
Jeff Brownb88102f2010-09-08 11:49:43 -07003136 }
3137}
3138
Jeff Brown9302c872011-07-13 22:51:29 -07003139sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
3140 const sp<InputChannel>& inputChannel) const {
3141 size_t numWindows = mWindowHandles.size();
3142 for (size_t i = 0; i < numWindows; i++) {
3143 const sp<InputWindowHandle>& windowHandle = mWindowHandles.itemAt(i);
3144 if (windowHandle->inputChannel == inputChannel) {
3145 return windowHandle;
Jeff Brown01ce2e92010-09-26 22:20:12 -07003146 }
3147 }
3148 return NULL;
3149}
3150
Jeff Brown9302c872011-07-13 22:51:29 -07003151bool InputDispatcher::hasWindowHandleLocked(
3152 const sp<InputWindowHandle>& windowHandle) const {
3153 size_t numWindows = mWindowHandles.size();
3154 for (size_t i = 0; i < numWindows; i++) {
3155 if (mWindowHandles.itemAt(i) == windowHandle) {
3156 return true;
3157 }
3158 }
3159 return false;
3160}
3161
3162void InputDispatcher::setInputWindows(const Vector<sp<InputWindowHandle> >& inputWindowHandles) {
Jeff Brownb88102f2010-09-08 11:49:43 -07003163#if DEBUG_FOCUS
3164 LOGD("setInputWindows");
3165#endif
3166 { // acquire lock
3167 AutoMutex _l(mLock);
3168
Jeff Brown9302c872011-07-13 22:51:29 -07003169 mWindowHandles = inputWindowHandles;
Jeff Brownb6997262010-10-08 22:31:17 -07003170
Jeff Brown9302c872011-07-13 22:51:29 -07003171 sp<InputWindowHandle> newFocusedWindowHandle;
3172 bool foundHoveredWindow = false;
3173 for (size_t i = 0; i < mWindowHandles.size(); i++) {
3174 const sp<InputWindowHandle>& windowHandle = mWindowHandles.itemAt(i);
3175 if (!windowHandle->update() || windowHandle->inputChannel == NULL) {
3176 mWindowHandles.removeAt(i--);
3177 continue;
3178 }
3179 if (windowHandle->hasFocus) {
3180 newFocusedWindowHandle = windowHandle;
3181 }
3182 if (windowHandle == mLastHoverWindowHandle) {
3183 foundHoveredWindow = true;
Jeff Brownb88102f2010-09-08 11:49:43 -07003184 }
3185 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07003186
Jeff Brown9302c872011-07-13 22:51:29 -07003187 if (!foundHoveredWindow) {
3188 mLastHoverWindowHandle = NULL;
3189 }
3190
3191 if (mFocusedWindowHandle != newFocusedWindowHandle) {
3192 if (mFocusedWindowHandle != NULL) {
Jeff Brownb6997262010-10-08 22:31:17 -07003193#if DEBUG_FOCUS
3194 LOGD("Focus left window: %s",
Jeff Brown9302c872011-07-13 22:51:29 -07003195 mFocusedWindowHandle->name.string());
Jeff Brownb6997262010-10-08 22:31:17 -07003196#endif
Jeff Brownda3d5a92011-03-29 15:11:34 -07003197 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
3198 "focus left window");
Jeff Brown9302c872011-07-13 22:51:29 -07003199 synthesizeCancelationEventsForInputChannelLocked(
3200 mFocusedWindowHandle->inputChannel, options);
Jeff Brownb6997262010-10-08 22:31:17 -07003201 }
Jeff Brown9302c872011-07-13 22:51:29 -07003202 if (newFocusedWindowHandle != NULL) {
Jeff Brownb6997262010-10-08 22:31:17 -07003203#if DEBUG_FOCUS
Jeff Brown9302c872011-07-13 22:51:29 -07003204 LOGD("Focus entered window: %s",
3205 newFocusedWindowHandle->name.string());
Jeff Brownb6997262010-10-08 22:31:17 -07003206#endif
Jeff Brown9302c872011-07-13 22:51:29 -07003207 }
3208 mFocusedWindowHandle = newFocusedWindowHandle;
Jeff Brownb6997262010-10-08 22:31:17 -07003209 }
3210
Jeff Brown9302c872011-07-13 22:51:29 -07003211 for (size_t i = 0; i < mTouchState.windows.size(); i++) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07003212 TouchedWindow& touchedWindow = mTouchState.windows.editItemAt(i);
Jeff Brown9302c872011-07-13 22:51:29 -07003213 if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
Jeff Brownb6997262010-10-08 22:31:17 -07003214#if DEBUG_FOCUS
Jeff Brown9302c872011-07-13 22:51:29 -07003215 LOGD("Touched window was removed: %s", touchedWindow.windowHandle->name.string());
Jeff Brownb6997262010-10-08 22:31:17 -07003216#endif
Jeff Brownda3d5a92011-03-29 15:11:34 -07003217 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
3218 "touched window was removed");
Jeff Brown9302c872011-07-13 22:51:29 -07003219 synthesizeCancelationEventsForInputChannelLocked(
3220 touchedWindow.windowHandle->inputChannel, options);
3221 mTouchState.windows.removeAt(i--);
Jeff Brown01ce2e92010-09-26 22:20:12 -07003222 }
3223 }
Jeff Brownb88102f2010-09-08 11:49:43 -07003224 } // release lock
3225
3226 // Wake up poll loop since it may need to make new input dispatching choices.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07003227 mLooper->wake();
Jeff Brownb88102f2010-09-08 11:49:43 -07003228}
3229
Jeff Brown9302c872011-07-13 22:51:29 -07003230void InputDispatcher::setFocusedApplication(
3231 const sp<InputApplicationHandle>& inputApplicationHandle) {
Jeff Brownb88102f2010-09-08 11:49:43 -07003232#if DEBUG_FOCUS
3233 LOGD("setFocusedApplication");
3234#endif
3235 { // acquire lock
3236 AutoMutex _l(mLock);
3237
Jeff Brown9302c872011-07-13 22:51:29 -07003238 if (inputApplicationHandle != NULL && inputApplicationHandle->update()) {
3239 mFocusedApplicationHandle = inputApplicationHandle;
3240 } else {
3241 mFocusedApplicationHandle.clear();
Jeff Brownb88102f2010-09-08 11:49:43 -07003242 }
3243
3244#if DEBUG_FOCUS
Jeff Brownb6997262010-10-08 22:31:17 -07003245 //logDispatchStateLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -07003246#endif
3247 } // release lock
3248
3249 // Wake up poll loop since it may need to make new input dispatching choices.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07003250 mLooper->wake();
Jeff Brownb88102f2010-09-08 11:49:43 -07003251}
3252
Jeff Brownb88102f2010-09-08 11:49:43 -07003253void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
3254#if DEBUG_FOCUS
3255 LOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
3256#endif
3257
3258 bool changed;
3259 { // acquire lock
3260 AutoMutex _l(mLock);
3261
3262 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
Jeff Brown120a4592010-10-27 18:43:51 -07003263 if (mDispatchFrozen && !frozen) {
Jeff Brownb88102f2010-09-08 11:49:43 -07003264 resetANRTimeoutsLocked();
3265 }
3266
Jeff Brown120a4592010-10-27 18:43:51 -07003267 if (mDispatchEnabled && !enabled) {
3268 resetAndDropEverythingLocked("dispatcher is being disabled");
3269 }
3270
Jeff Brownb88102f2010-09-08 11:49:43 -07003271 mDispatchEnabled = enabled;
3272 mDispatchFrozen = frozen;
3273 changed = true;
3274 } else {
3275 changed = false;
3276 }
3277
3278#if DEBUG_FOCUS
Jeff Brownb6997262010-10-08 22:31:17 -07003279 //logDispatchStateLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -07003280#endif
3281 } // release lock
3282
3283 if (changed) {
3284 // Wake up poll loop since it may need to make new input dispatching choices.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07003285 mLooper->wake();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003286 }
3287}
3288
Jeff Brown0029c662011-03-30 02:25:18 -07003289void InputDispatcher::setInputFilterEnabled(bool enabled) {
3290#if DEBUG_FOCUS
3291 LOGD("setInputFilterEnabled: enabled=%d", enabled);
3292#endif
3293
3294 { // acquire lock
3295 AutoMutex _l(mLock);
3296
3297 if (mInputFilterEnabled == enabled) {
3298 return;
3299 }
3300
3301 mInputFilterEnabled = enabled;
3302 resetAndDropEverythingLocked("input filter is being enabled or disabled");
3303 } // release lock
3304
3305 // Wake up poll loop since there might be work to do to drop everything.
3306 mLooper->wake();
3307}
3308
Jeff Browne6504122010-09-27 14:52:15 -07003309bool InputDispatcher::transferTouchFocus(const sp<InputChannel>& fromChannel,
3310 const sp<InputChannel>& toChannel) {
3311#if DEBUG_FOCUS
3312 LOGD("transferTouchFocus: fromChannel=%s, toChannel=%s",
3313 fromChannel->getName().string(), toChannel->getName().string());
3314#endif
3315 { // acquire lock
3316 AutoMutex _l(mLock);
3317
Jeff Brown9302c872011-07-13 22:51:29 -07003318 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromChannel);
3319 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toChannel);
3320 if (fromWindowHandle == NULL || toWindowHandle == NULL) {
Jeff Browne6504122010-09-27 14:52:15 -07003321#if DEBUG_FOCUS
3322 LOGD("Cannot transfer focus because from or to window not found.");
3323#endif
3324 return false;
3325 }
Jeff Brown9302c872011-07-13 22:51:29 -07003326 if (fromWindowHandle == toWindowHandle) {
Jeff Browne6504122010-09-27 14:52:15 -07003327#if DEBUG_FOCUS
3328 LOGD("Trivial transfer to same window.");
3329#endif
3330 return true;
3331 }
3332
3333 bool found = false;
3334 for (size_t i = 0; i < mTouchState.windows.size(); i++) {
3335 const TouchedWindow& touchedWindow = mTouchState.windows[i];
Jeff Brown9302c872011-07-13 22:51:29 -07003336 if (touchedWindow.windowHandle == fromWindowHandle) {
Jeff Browne6504122010-09-27 14:52:15 -07003337 int32_t oldTargetFlags = touchedWindow.targetFlags;
3338 BitSet32 pointerIds = touchedWindow.pointerIds;
3339
3340 mTouchState.windows.removeAt(i);
3341
Jeff Brown46e75292010-11-10 16:53:45 -08003342 int32_t newTargetFlags = oldTargetFlags
Jeff Browna032cc02011-03-07 16:56:21 -08003343 & (InputTarget::FLAG_FOREGROUND
3344 | InputTarget::FLAG_SPLIT | InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brown9302c872011-07-13 22:51:29 -07003345 mTouchState.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Jeff Browne6504122010-09-27 14:52:15 -07003346
3347 found = true;
3348 break;
3349 }
3350 }
3351
3352 if (! found) {
3353#if DEBUG_FOCUS
3354 LOGD("Focus transfer failed because from window did not have focus.");
3355#endif
3356 return false;
3357 }
3358
Jeff Brown9c9f1a32010-10-11 18:32:20 -07003359 ssize_t fromConnectionIndex = getConnectionIndexLocked(fromChannel);
3360 ssize_t toConnectionIndex = getConnectionIndexLocked(toChannel);
3361 if (fromConnectionIndex >= 0 && toConnectionIndex >= 0) {
3362 sp<Connection> fromConnection = mConnectionsByReceiveFd.valueAt(fromConnectionIndex);
3363 sp<Connection> toConnection = mConnectionsByReceiveFd.valueAt(toConnectionIndex);
3364
3365 fromConnection->inputState.copyPointerStateTo(toConnection->inputState);
Jeff Brownda3d5a92011-03-29 15:11:34 -07003366 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Jeff Brown9c9f1a32010-10-11 18:32:20 -07003367 "transferring touch focus from this window to another window");
Jeff Brownda3d5a92011-03-29 15:11:34 -07003368 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Jeff Brown9c9f1a32010-10-11 18:32:20 -07003369 }
3370
Jeff Browne6504122010-09-27 14:52:15 -07003371#if DEBUG_FOCUS
3372 logDispatchStateLocked();
3373#endif
3374 } // release lock
3375
3376 // Wake up poll loop since it may need to make new input dispatching choices.
3377 mLooper->wake();
3378 return true;
3379}
3380
Jeff Brown120a4592010-10-27 18:43:51 -07003381void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
3382#if DEBUG_FOCUS
3383 LOGD("Resetting and dropping all events (%s).", reason);
3384#endif
3385
Jeff Brownda3d5a92011-03-29 15:11:34 -07003386 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
3387 synthesizeCancelationEventsForAllConnectionsLocked(options);
Jeff Brown120a4592010-10-27 18:43:51 -07003388
3389 resetKeyRepeatLocked();
3390 releasePendingEventLocked();
3391 drainInboundQueueLocked();
3392 resetTargetsLocked();
3393
3394 mTouchState.reset();
Jeff Brown9302c872011-07-13 22:51:29 -07003395 mLastHoverWindowHandle.clear();
Jeff Brown120a4592010-10-27 18:43:51 -07003396}
3397
Jeff Brownb88102f2010-09-08 11:49:43 -07003398void InputDispatcher::logDispatchStateLocked() {
3399 String8 dump;
3400 dumpDispatchStateLocked(dump);
Jeff Brown2a95c2a2010-09-16 12:31:46 -07003401
3402 char* text = dump.lockBuffer(dump.size());
3403 char* start = text;
3404 while (*start != '\0') {
3405 char* end = strchr(start, '\n');
3406 if (*end == '\n') {
3407 *(end++) = '\0';
3408 }
3409 LOGD("%s", start);
3410 start = end;
3411 }
Jeff Brownb88102f2010-09-08 11:49:43 -07003412}
3413
3414void InputDispatcher::dumpDispatchStateLocked(String8& dump) {
Jeff Brownf2f487182010-10-01 17:46:21 -07003415 dump.appendFormat(INDENT "DispatchEnabled: %d\n", mDispatchEnabled);
3416 dump.appendFormat(INDENT "DispatchFrozen: %d\n", mDispatchFrozen);
Jeff Brownb88102f2010-09-08 11:49:43 -07003417
Jeff Brown9302c872011-07-13 22:51:29 -07003418 if (mFocusedApplicationHandle != NULL) {
Jeff Brownf2f487182010-10-01 17:46:21 -07003419 dump.appendFormat(INDENT "FocusedApplication: name='%s', dispatchingTimeout=%0.3fms\n",
Jeff Brown9302c872011-07-13 22:51:29 -07003420 mFocusedApplicationHandle->name.string(),
3421 mFocusedApplicationHandle->dispatchingTimeout / 1000000.0);
Jeff Brownb88102f2010-09-08 11:49:43 -07003422 } else {
Jeff Brownf2f487182010-10-01 17:46:21 -07003423 dump.append(INDENT "FocusedApplication: <null>\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003424 }
Jeff Brownf2f487182010-10-01 17:46:21 -07003425 dump.appendFormat(INDENT "FocusedWindow: name='%s'\n",
Jeff Brown9302c872011-07-13 22:51:29 -07003426 mFocusedWindowHandle != NULL ? mFocusedWindowHandle->name.string() : "<null>");
Jeff Brownf2f487182010-10-01 17:46:21 -07003427
3428 dump.appendFormat(INDENT "TouchDown: %s\n", toString(mTouchState.down));
3429 dump.appendFormat(INDENT "TouchSplit: %s\n", toString(mTouchState.split));
Jeff Brown95712852011-01-04 19:41:59 -08003430 dump.appendFormat(INDENT "TouchDeviceId: %d\n", mTouchState.deviceId);
Jeff Brown58a2da82011-01-25 16:02:22 -08003431 dump.appendFormat(INDENT "TouchSource: 0x%08x\n", mTouchState.source);
Jeff Brownf2f487182010-10-01 17:46:21 -07003432 if (!mTouchState.windows.isEmpty()) {
3433 dump.append(INDENT "TouchedWindows:\n");
3434 for (size_t i = 0; i < mTouchState.windows.size(); i++) {
3435 const TouchedWindow& touchedWindow = mTouchState.windows[i];
3436 dump.appendFormat(INDENT2 "%d: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
Jeff Brown9302c872011-07-13 22:51:29 -07003437 i, touchedWindow.windowHandle->name.string(), touchedWindow.pointerIds.value,
Jeff Brownf2f487182010-10-01 17:46:21 -07003438 touchedWindow.targetFlags);
3439 }
3440 } else {
3441 dump.append(INDENT "TouchedWindows: <none>\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003442 }
3443
Jeff Brown9302c872011-07-13 22:51:29 -07003444 if (!mWindowHandles.isEmpty()) {
Jeff Brownf2f487182010-10-01 17:46:21 -07003445 dump.append(INDENT "Windows:\n");
Jeff Brown9302c872011-07-13 22:51:29 -07003446 for (size_t i = 0; i < mWindowHandles.size(); i++) {
3447 const sp<InputWindowHandle>& windowHandle = mWindowHandles.itemAt(i);
Jeff Brownf2f487182010-10-01 17:46:21 -07003448 dump.appendFormat(INDENT2 "%d: name='%s', paused=%s, hasFocus=%s, hasWallpaper=%s, "
3449 "visible=%s, canReceiveKeys=%s, flags=0x%08x, type=0x%08x, layer=%d, "
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003450 "frame=[%d,%d][%d,%d], scale=%f, "
Jeff Brownfbf09772011-01-16 14:06:57 -08003451 "touchableRegion=",
Jeff Brown9302c872011-07-13 22:51:29 -07003452 i, windowHandle->name.string(),
3453 toString(windowHandle->paused),
3454 toString(windowHandle->hasFocus),
3455 toString(windowHandle->hasWallpaper),
3456 toString(windowHandle->visible),
3457 toString(windowHandle->canReceiveKeys),
3458 windowHandle->layoutParamsFlags, windowHandle->layoutParamsType,
3459 windowHandle->layer,
3460 windowHandle->frameLeft, windowHandle->frameTop,
3461 windowHandle->frameRight, windowHandle->frameBottom,
3462 windowHandle->scaleFactor);
3463 dumpRegion(dump, windowHandle->touchableRegion);
3464 dump.appendFormat(", inputFeatures=0x%08x", windowHandle->inputFeatures);
Jeff Brownfbf09772011-01-16 14:06:57 -08003465 dump.appendFormat(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%0.3fms\n",
Jeff Brown9302c872011-07-13 22:51:29 -07003466 windowHandle->ownerPid, windowHandle->ownerUid,
3467 windowHandle->dispatchingTimeout / 1000000.0);
Jeff Brownf2f487182010-10-01 17:46:21 -07003468 }
3469 } else {
3470 dump.append(INDENT "Windows: <none>\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003471 }
3472
Jeff Brownf2f487182010-10-01 17:46:21 -07003473 if (!mMonitoringChannels.isEmpty()) {
3474 dump.append(INDENT "MonitoringChannels:\n");
3475 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
3476 const sp<InputChannel>& channel = mMonitoringChannels[i];
3477 dump.appendFormat(INDENT2 "%d: '%s'\n", i, channel->getName().string());
3478 }
3479 } else {
3480 dump.append(INDENT "MonitoringChannels: <none>\n");
3481 }
Jeff Brown519e0242010-09-15 15:18:56 -07003482
Jeff Brownf2f487182010-10-01 17:46:21 -07003483 dump.appendFormat(INDENT "InboundQueue: length=%u\n", mInboundQueue.count());
3484
3485 if (!mActiveConnections.isEmpty()) {
3486 dump.append(INDENT "ActiveConnections:\n");
3487 for (size_t i = 0; i < mActiveConnections.size(); i++) {
3488 const Connection* connection = mActiveConnections[i];
Jeff Brown76860e32010-10-25 17:37:46 -07003489 dump.appendFormat(INDENT2 "%d: '%s', status=%s, outboundQueueLength=%u, "
Jeff Brownb6997262010-10-08 22:31:17 -07003490 "inputState.isNeutral=%s\n",
Jeff Brownf2f487182010-10-01 17:46:21 -07003491 i, connection->getInputChannelName(), connection->getStatusLabel(),
3492 connection->outboundQueue.count(),
Jeff Brownb6997262010-10-08 22:31:17 -07003493 toString(connection->inputState.isNeutral()));
Jeff Brownf2f487182010-10-01 17:46:21 -07003494 }
3495 } else {
3496 dump.append(INDENT "ActiveConnections: <none>\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003497 }
3498
3499 if (isAppSwitchPendingLocked()) {
Jeff Brownf2f487182010-10-01 17:46:21 -07003500 dump.appendFormat(INDENT "AppSwitch: pending, due in %01.1fms\n",
Jeff Brownb88102f2010-09-08 11:49:43 -07003501 (mAppSwitchDueTime - now()) / 1000000.0);
3502 } else {
Jeff Brownf2f487182010-10-01 17:46:21 -07003503 dump.append(INDENT "AppSwitch: not pending\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003504 }
3505}
3506
Jeff Brown928e0542011-01-10 11:17:36 -08003507status_t InputDispatcher::registerInputChannel(const sp<InputChannel>& inputChannel,
3508 const sp<InputWindowHandle>& inputWindowHandle, bool monitor) {
Jeff Brown9c3cda02010-06-15 01:31:58 -07003509#if DEBUG_REGISTRATION
Jeff Brownb88102f2010-09-08 11:49:43 -07003510 LOGD("channel '%s' ~ registerInputChannel - monitor=%s", inputChannel->getName().string(),
3511 toString(monitor));
Jeff Brown9c3cda02010-06-15 01:31:58 -07003512#endif
3513
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003514 { // acquire lock
3515 AutoMutex _l(mLock);
3516
Jeff Brown519e0242010-09-15 15:18:56 -07003517 if (getConnectionIndexLocked(inputChannel) >= 0) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003518 LOGW("Attempted to register already registered input channel '%s'",
3519 inputChannel->getName().string());
3520 return BAD_VALUE;
3521 }
3522
Jeff Brown928e0542011-01-10 11:17:36 -08003523 sp<Connection> connection = new Connection(inputChannel, inputWindowHandle);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003524 status_t status = connection->initialize();
3525 if (status) {
3526 LOGE("Failed to initialize input publisher for input channel '%s', status=%d",
3527 inputChannel->getName().string(), status);
3528 return status;
3529 }
3530
Jeff Brown2cbecea2010-08-17 15:59:26 -07003531 int32_t receiveFd = inputChannel->getReceivePipeFd();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003532 mConnectionsByReceiveFd.add(receiveFd, connection);
Jeff Brown9c3cda02010-06-15 01:31:58 -07003533
Jeff Brownb88102f2010-09-08 11:49:43 -07003534 if (monitor) {
3535 mMonitoringChannels.push(inputChannel);
3536 }
3537
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07003538 mLooper->addFd(receiveFd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
Jeff Brown2cbecea2010-08-17 15:59:26 -07003539
Jeff Brown9c3cda02010-06-15 01:31:58 -07003540 runCommandsLockedInterruptible();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003541 } // release lock
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003542 return OK;
3543}
3544
3545status_t InputDispatcher::unregisterInputChannel(const sp<InputChannel>& inputChannel) {
Jeff Brown9c3cda02010-06-15 01:31:58 -07003546#if DEBUG_REGISTRATION
Jeff Brown349703e2010-06-22 01:27:15 -07003547 LOGD("channel '%s' ~ unregisterInputChannel", inputChannel->getName().string());
Jeff Brown9c3cda02010-06-15 01:31:58 -07003548#endif
3549
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003550 { // acquire lock
3551 AutoMutex _l(mLock);
3552
Jeff Brown519e0242010-09-15 15:18:56 -07003553 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003554 if (connectionIndex < 0) {
3555 LOGW("Attempted to unregister already unregistered input channel '%s'",
3556 inputChannel->getName().string());
3557 return BAD_VALUE;
3558 }
3559
3560 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
3561 mConnectionsByReceiveFd.removeItemsAt(connectionIndex);
3562
3563 connection->status = Connection::STATUS_ZOMBIE;
3564
Jeff Brownb88102f2010-09-08 11:49:43 -07003565 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
3566 if (mMonitoringChannels[i] == inputChannel) {
3567 mMonitoringChannels.removeAt(i);
3568 break;
3569 }
3570 }
3571
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07003572 mLooper->removeFd(inputChannel->getReceivePipeFd());
Jeff Brown2cbecea2010-08-17 15:59:26 -07003573
Jeff Brown7fbdc842010-06-17 20:52:56 -07003574 nsecs_t currentTime = now();
Jeff Brownb6997262010-10-08 22:31:17 -07003575 abortBrokenDispatchCycleLocked(currentTime, connection);
Jeff Brown9c3cda02010-06-15 01:31:58 -07003576
3577 runCommandsLockedInterruptible();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003578 } // release lock
3579
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003580 // Wake the poll loop because removing the connection may have changed the current
3581 // synchronization state.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07003582 mLooper->wake();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003583 return OK;
3584}
3585
Jeff Brown519e0242010-09-15 15:18:56 -07003586ssize_t InputDispatcher::getConnectionIndexLocked(const sp<InputChannel>& inputChannel) {
Jeff Brown2cbecea2010-08-17 15:59:26 -07003587 ssize_t connectionIndex = mConnectionsByReceiveFd.indexOfKey(inputChannel->getReceivePipeFd());
3588 if (connectionIndex >= 0) {
3589 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
3590 if (connection->inputChannel.get() == inputChannel.get()) {
3591 return connectionIndex;
3592 }
3593 }
3594
3595 return -1;
3596}
3597
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003598void InputDispatcher::activateConnectionLocked(Connection* connection) {
3599 for (size_t i = 0; i < mActiveConnections.size(); i++) {
3600 if (mActiveConnections.itemAt(i) == connection) {
3601 return;
3602 }
3603 }
3604 mActiveConnections.add(connection);
3605}
3606
3607void InputDispatcher::deactivateConnectionLocked(Connection* connection) {
3608 for (size_t i = 0; i < mActiveConnections.size(); i++) {
3609 if (mActiveConnections.itemAt(i) == connection) {
3610 mActiveConnections.removeAt(i);
3611 return;
3612 }
3613 }
3614}
3615
Jeff Brown9c3cda02010-06-15 01:31:58 -07003616void InputDispatcher::onDispatchCycleStartedLocked(
Jeff Brown7fbdc842010-06-17 20:52:56 -07003617 nsecs_t currentTime, const sp<Connection>& connection) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003618}
3619
Jeff Brown9c3cda02010-06-15 01:31:58 -07003620void InputDispatcher::onDispatchCycleFinishedLocked(
Jeff Brown3915bb82010-11-05 15:02:16 -07003621 nsecs_t currentTime, const sp<Connection>& connection, bool handled) {
3622 CommandEntry* commandEntry = postCommandLocked(
3623 & InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
3624 commandEntry->connection = connection;
3625 commandEntry->handled = handled;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003626}
3627
Jeff Brown9c3cda02010-06-15 01:31:58 -07003628void InputDispatcher::onDispatchCycleBrokenLocked(
Jeff Brown7fbdc842010-06-17 20:52:56 -07003629 nsecs_t currentTime, const sp<Connection>& connection) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003630 LOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
3631 connection->getInputChannelName());
3632
Jeff Brown9c3cda02010-06-15 01:31:58 -07003633 CommandEntry* commandEntry = postCommandLocked(
3634 & InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
Jeff Brown7fbdc842010-06-17 20:52:56 -07003635 commandEntry->connection = connection;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003636}
3637
Jeff Brown519e0242010-09-15 15:18:56 -07003638void InputDispatcher::onANRLocked(
Jeff Brown9302c872011-07-13 22:51:29 -07003639 nsecs_t currentTime, const sp<InputApplicationHandle>& applicationHandle,
3640 const sp<InputWindowHandle>& windowHandle,
Jeff Brown519e0242010-09-15 15:18:56 -07003641 nsecs_t eventTime, nsecs_t waitStartTime) {
3642 LOGI("Application is not responding: %s. "
3643 "%01.1fms since event, %01.1fms since wait started",
Jeff Brown9302c872011-07-13 22:51:29 -07003644 getApplicationWindowLabelLocked(applicationHandle, windowHandle).string(),
Jeff Brown519e0242010-09-15 15:18:56 -07003645 (currentTime - eventTime) / 1000000.0,
3646 (currentTime - waitStartTime) / 1000000.0);
3647
3648 CommandEntry* commandEntry = postCommandLocked(
3649 & InputDispatcher::doNotifyANRLockedInterruptible);
Jeff Brown9302c872011-07-13 22:51:29 -07003650 commandEntry->inputApplicationHandle = applicationHandle;
3651 commandEntry->inputWindowHandle = windowHandle;
Jeff Brown519e0242010-09-15 15:18:56 -07003652}
3653
Jeff Brownb88102f2010-09-08 11:49:43 -07003654void InputDispatcher::doNotifyConfigurationChangedInterruptible(
3655 CommandEntry* commandEntry) {
3656 mLock.unlock();
3657
3658 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
3659
3660 mLock.lock();
3661}
3662
Jeff Brown9c3cda02010-06-15 01:31:58 -07003663void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(
3664 CommandEntry* commandEntry) {
Jeff Brown7fbdc842010-06-17 20:52:56 -07003665 sp<Connection> connection = commandEntry->connection;
Jeff Brown9c3cda02010-06-15 01:31:58 -07003666
Jeff Brown7fbdc842010-06-17 20:52:56 -07003667 if (connection->status != Connection::STATUS_ZOMBIE) {
3668 mLock.unlock();
Jeff Brown9c3cda02010-06-15 01:31:58 -07003669
Jeff Brown928e0542011-01-10 11:17:36 -08003670 mPolicy->notifyInputChannelBroken(connection->inputWindowHandle);
Jeff Brown7fbdc842010-06-17 20:52:56 -07003671
3672 mLock.lock();
3673 }
Jeff Brown9c3cda02010-06-15 01:31:58 -07003674}
3675
Jeff Brown519e0242010-09-15 15:18:56 -07003676void InputDispatcher::doNotifyANRLockedInterruptible(
Jeff Brown9c3cda02010-06-15 01:31:58 -07003677 CommandEntry* commandEntry) {
Jeff Brown519e0242010-09-15 15:18:56 -07003678 mLock.unlock();
Jeff Brown9c3cda02010-06-15 01:31:58 -07003679
Jeff Brown519e0242010-09-15 15:18:56 -07003680 nsecs_t newTimeout = mPolicy->notifyANR(
Jeff Brown928e0542011-01-10 11:17:36 -08003681 commandEntry->inputApplicationHandle, commandEntry->inputWindowHandle);
Jeff Brown9c3cda02010-06-15 01:31:58 -07003682
Jeff Brown519e0242010-09-15 15:18:56 -07003683 mLock.lock();
Jeff Brown7fbdc842010-06-17 20:52:56 -07003684
Jeff Brown9302c872011-07-13 22:51:29 -07003685 resumeAfterTargetsNotReadyTimeoutLocked(newTimeout,
3686 commandEntry->inputWindowHandle != NULL
3687 ? commandEntry->inputWindowHandle->inputChannel : NULL);
Jeff Brown9c3cda02010-06-15 01:31:58 -07003688}
3689
Jeff Brownb88102f2010-09-08 11:49:43 -07003690void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
3691 CommandEntry* commandEntry) {
3692 KeyEntry* entry = commandEntry->keyEntry;
Jeff Brown1f245102010-11-18 20:53:46 -08003693
3694 KeyEvent event;
3695 initializeKeyEvent(&event, entry);
Jeff Brownb88102f2010-09-08 11:49:43 -07003696
3697 mLock.unlock();
3698
Jeff Brown928e0542011-01-10 11:17:36 -08003699 bool consumed = mPolicy->interceptKeyBeforeDispatching(commandEntry->inputWindowHandle,
Jeff Brown1f245102010-11-18 20:53:46 -08003700 &event, entry->policyFlags);
Jeff Brownb88102f2010-09-08 11:49:43 -07003701
3702 mLock.lock();
3703
3704 entry->interceptKeyResult = consumed
3705 ? KeyEntry::INTERCEPT_KEY_RESULT_SKIP
3706 : KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
3707 mAllocator.releaseKeyEntry(entry);
3708}
3709
Jeff Brown3915bb82010-11-05 15:02:16 -07003710void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(
3711 CommandEntry* commandEntry) {
3712 sp<Connection> connection = commandEntry->connection;
3713 bool handled = commandEntry->handled;
3714
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003715 bool skipNext = false;
Jeff Brown49ed71d2010-12-06 17:13:33 -08003716 if (!connection->outboundQueue.isEmpty()) {
Jeff Brown3915bb82010-11-05 15:02:16 -07003717 DispatchEntry* dispatchEntry = connection->outboundQueue.headSentinel.next;
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003718 if (dispatchEntry->inProgress) {
3719 if (dispatchEntry->eventEntry->type == EventEntry::TYPE_KEY) {
3720 KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry);
3721 skipNext = afterKeyEventLockedInterruptible(connection,
3722 dispatchEntry, keyEntry, handled);
3723 } else if (dispatchEntry->eventEntry->type == EventEntry::TYPE_MOTION) {
3724 MotionEntry* motionEntry = static_cast<MotionEntry*>(dispatchEntry->eventEntry);
3725 skipNext = afterMotionEventLockedInterruptible(connection,
3726 dispatchEntry, motionEntry, handled);
Jeff Brown49ed71d2010-12-06 17:13:33 -08003727 }
Jeff Brown3915bb82010-11-05 15:02:16 -07003728 }
3729 }
3730
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003731 if (!skipNext) {
3732 startNextDispatchCycleLocked(now(), connection);
3733 }
3734}
3735
3736bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
3737 DispatchEntry* dispatchEntry, KeyEntry* keyEntry, bool handled) {
3738 if (!(keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK)) {
3739 // Get the fallback key state.
3740 // Clear it out after dispatching the UP.
3741 int32_t originalKeyCode = keyEntry->keyCode;
3742 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
3743 if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
3744 connection->inputState.removeFallbackKey(originalKeyCode);
3745 }
3746
3747 if (handled || !dispatchEntry->hasForegroundTarget()) {
3748 // If the application handles the original key for which we previously
3749 // generated a fallback or if the window is not a foreground window,
3750 // then cancel the associated fallback key, if any.
3751 if (fallbackKeyCode != -1) {
3752 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
3753 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
3754 "application handled the original non-fallback key "
3755 "or is no longer a foreground target, "
3756 "canceling previously dispatched fallback key");
3757 options.keyCode = fallbackKeyCode;
3758 synthesizeCancelationEventsForConnectionLocked(connection, options);
3759 }
3760 connection->inputState.removeFallbackKey(originalKeyCode);
3761 }
3762 } else {
3763 // If the application did not handle a non-fallback key, first check
3764 // that we are in a good state to perform unhandled key event processing
3765 // Then ask the policy what to do with it.
3766 bool initialDown = keyEntry->action == AKEY_EVENT_ACTION_DOWN
3767 && keyEntry->repeatCount == 0;
3768 if (fallbackKeyCode == -1 && !initialDown) {
3769#if DEBUG_OUTBOUND_EVENT_DETAILS
3770 LOGD("Unhandled key event: Skipping unhandled key event processing "
3771 "since this is not an initial down. "
3772 "keyCode=%d, action=%d, repeatCount=%d",
3773 originalKeyCode, keyEntry->action, keyEntry->repeatCount);
3774#endif
3775 return false;
3776 }
3777
3778 // Dispatch the unhandled key to the policy.
3779#if DEBUG_OUTBOUND_EVENT_DETAILS
3780 LOGD("Unhandled key event: Asking policy to perform fallback action. "
3781 "keyCode=%d, action=%d, repeatCount=%d",
3782 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount);
3783#endif
3784 KeyEvent event;
3785 initializeKeyEvent(&event, keyEntry);
3786
3787 mLock.unlock();
3788
3789 bool fallback = mPolicy->dispatchUnhandledKey(connection->inputWindowHandle,
3790 &event, keyEntry->policyFlags, &event);
3791
3792 mLock.lock();
3793
3794 if (connection->status != Connection::STATUS_NORMAL) {
3795 connection->inputState.removeFallbackKey(originalKeyCode);
3796 return true; // skip next cycle
3797 }
3798
3799 LOG_ASSERT(connection->outboundQueue.headSentinel.next == dispatchEntry);
3800
3801 // Latch the fallback keycode for this key on an initial down.
3802 // The fallback keycode cannot change at any other point in the lifecycle.
3803 if (initialDown) {
3804 if (fallback) {
3805 fallbackKeyCode = event.getKeyCode();
3806 } else {
3807 fallbackKeyCode = AKEYCODE_UNKNOWN;
3808 }
3809 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
3810 }
3811
3812 LOG_ASSERT(fallbackKeyCode != -1);
3813
3814 // Cancel the fallback key if the policy decides not to send it anymore.
3815 // We will continue to dispatch the key to the policy but we will no
3816 // longer dispatch a fallback key to the application.
3817 if (fallbackKeyCode != AKEYCODE_UNKNOWN
3818 && (!fallback || fallbackKeyCode != event.getKeyCode())) {
3819#if DEBUG_OUTBOUND_EVENT_DETAILS
3820 if (fallback) {
3821 LOGD("Unhandled key event: Policy requested to send key %d"
3822 "as a fallback for %d, but on the DOWN it had requested "
3823 "to send %d instead. Fallback canceled.",
3824 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
3825 } else {
3826 LOGD("Unhandled key event: Policy did not request fallback for %d,"
3827 "but on the DOWN it had requested to send %d. "
3828 "Fallback canceled.",
3829 originalKeyCode, fallbackKeyCode);
3830 }
3831#endif
3832
3833 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
3834 "canceling fallback, policy no longer desires it");
3835 options.keyCode = fallbackKeyCode;
3836 synthesizeCancelationEventsForConnectionLocked(connection, options);
3837
3838 fallback = false;
3839 fallbackKeyCode = AKEYCODE_UNKNOWN;
3840 if (keyEntry->action != AKEY_EVENT_ACTION_UP) {
3841 connection->inputState.setFallbackKey(originalKeyCode,
3842 fallbackKeyCode);
3843 }
3844 }
3845
3846#if DEBUG_OUTBOUND_EVENT_DETAILS
3847 {
3848 String8 msg;
3849 const KeyedVector<int32_t, int32_t>& fallbackKeys =
3850 connection->inputState.getFallbackKeys();
3851 for (size_t i = 0; i < fallbackKeys.size(); i++) {
3852 msg.appendFormat(", %d->%d", fallbackKeys.keyAt(i),
3853 fallbackKeys.valueAt(i));
3854 }
3855 LOGD("Unhandled key event: %d currently tracked fallback keys%s.",
3856 fallbackKeys.size(), msg.string());
3857 }
3858#endif
3859
3860 if (fallback) {
3861 // Restart the dispatch cycle using the fallback key.
3862 keyEntry->eventTime = event.getEventTime();
3863 keyEntry->deviceId = event.getDeviceId();
3864 keyEntry->source = event.getSource();
3865 keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
3866 keyEntry->keyCode = fallbackKeyCode;
3867 keyEntry->scanCode = event.getScanCode();
3868 keyEntry->metaState = event.getMetaState();
3869 keyEntry->repeatCount = event.getRepeatCount();
3870 keyEntry->downTime = event.getDownTime();
3871 keyEntry->syntheticRepeat = false;
3872
3873#if DEBUG_OUTBOUND_EVENT_DETAILS
3874 LOGD("Unhandled key event: Dispatching fallback key. "
3875 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
3876 originalKeyCode, fallbackKeyCode, keyEntry->metaState);
3877#endif
3878
3879 dispatchEntry->inProgress = false;
3880 startDispatchCycleLocked(now(), connection);
3881 return true; // already started next cycle
3882 } else {
3883#if DEBUG_OUTBOUND_EVENT_DETAILS
3884 LOGD("Unhandled key event: No fallback key.");
3885#endif
3886 }
3887 }
3888 }
3889 return false;
3890}
3891
3892bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
3893 DispatchEntry* dispatchEntry, MotionEntry* motionEntry, bool handled) {
3894 return false;
Jeff Brown3915bb82010-11-05 15:02:16 -07003895}
3896
Jeff Brownb88102f2010-09-08 11:49:43 -07003897void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
3898 mLock.unlock();
3899
Jeff Brown01ce2e92010-09-26 22:20:12 -07003900 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
Jeff Brownb88102f2010-09-08 11:49:43 -07003901
3902 mLock.lock();
3903}
3904
Jeff Brown3915bb82010-11-05 15:02:16 -07003905void InputDispatcher::initializeKeyEvent(KeyEvent* event, const KeyEntry* entry) {
3906 event->initialize(entry->deviceId, entry->source, entry->action, entry->flags,
3907 entry->keyCode, entry->scanCode, entry->metaState, entry->repeatCount,
3908 entry->downTime, entry->eventTime);
3909}
3910
Jeff Brown519e0242010-09-15 15:18:56 -07003911void InputDispatcher::updateDispatchStatisticsLocked(nsecs_t currentTime, const EventEntry* entry,
3912 int32_t injectionResult, nsecs_t timeSpentWaitingForApplication) {
3913 // TODO Write some statistics about how long we spend waiting.
Jeff Brownb88102f2010-09-08 11:49:43 -07003914}
3915
3916void InputDispatcher::dump(String8& dump) {
Jeff Brownf2f487182010-10-01 17:46:21 -07003917 dump.append("Input Dispatcher State:\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003918 dumpDispatchStateLocked(dump);
Jeff Brown214eaf42011-05-26 19:17:02 -07003919
3920 dump.append(INDENT "Configuration:\n");
3921 dump.appendFormat(INDENT2 "MaxEventsPerSecond: %d\n", mConfig.maxEventsPerSecond);
3922 dump.appendFormat(INDENT2 "KeyRepeatDelay: %0.1fms\n", mConfig.keyRepeatDelay * 0.000001f);
3923 dump.appendFormat(INDENT2 "KeyRepeatTimeout: %0.1fms\n", mConfig.keyRepeatTimeout * 0.000001f);
Jeff Brownb88102f2010-09-08 11:49:43 -07003924}
3925
Jeff Brown9c3cda02010-06-15 01:31:58 -07003926
Jeff Brown519e0242010-09-15 15:18:56 -07003927// --- InputDispatcher::Queue ---
3928
3929template <typename T>
3930uint32_t InputDispatcher::Queue<T>::count() const {
3931 uint32_t result = 0;
3932 for (const T* entry = headSentinel.next; entry != & tailSentinel; entry = entry->next) {
3933 result += 1;
3934 }
3935 return result;
3936}
3937
3938
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003939// --- InputDispatcher::Allocator ---
3940
3941InputDispatcher::Allocator::Allocator() {
3942}
3943
Jeff Brown01ce2e92010-09-26 22:20:12 -07003944InputDispatcher::InjectionState*
3945InputDispatcher::Allocator::obtainInjectionState(int32_t injectorPid, int32_t injectorUid) {
3946 InjectionState* injectionState = mInjectionStatePool.alloc();
3947 injectionState->refCount = 1;
3948 injectionState->injectorPid = injectorPid;
3949 injectionState->injectorUid = injectorUid;
3950 injectionState->injectionIsAsync = false;
3951 injectionState->injectionResult = INPUT_EVENT_INJECTION_PENDING;
3952 injectionState->pendingForegroundDispatches = 0;
3953 return injectionState;
3954}
3955
Jeff Brown7fbdc842010-06-17 20:52:56 -07003956void InputDispatcher::Allocator::initializeEventEntry(EventEntry* entry, int32_t type,
Jeff Brownb6997262010-10-08 22:31:17 -07003957 nsecs_t eventTime, uint32_t policyFlags) {
Jeff Brown7fbdc842010-06-17 20:52:56 -07003958 entry->type = type;
3959 entry->refCount = 1;
3960 entry->dispatchInProgress = false;
Christopher Tatee91a5db2010-06-23 16:50:30 -07003961 entry->eventTime = eventTime;
Jeff Brownb6997262010-10-08 22:31:17 -07003962 entry->policyFlags = policyFlags;
Jeff Brown01ce2e92010-09-26 22:20:12 -07003963 entry->injectionState = NULL;
3964}
3965
3966void InputDispatcher::Allocator::releaseEventEntryInjectionState(EventEntry* entry) {
3967 if (entry->injectionState) {
3968 releaseInjectionState(entry->injectionState);
3969 entry->injectionState = NULL;
3970 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07003971}
3972
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003973InputDispatcher::ConfigurationChangedEntry*
Jeff Brown7fbdc842010-06-17 20:52:56 -07003974InputDispatcher::Allocator::obtainConfigurationChangedEntry(nsecs_t eventTime) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003975 ConfigurationChangedEntry* entry = mConfigurationChangeEntryPool.alloc();
Jeff Brownb6997262010-10-08 22:31:17 -07003976 initializeEventEntry(entry, EventEntry::TYPE_CONFIGURATION_CHANGED, eventTime, 0);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003977 return entry;
3978}
3979
Jeff Brown7fbdc842010-06-17 20:52:56 -07003980InputDispatcher::KeyEntry* InputDispatcher::Allocator::obtainKeyEntry(nsecs_t eventTime,
Jeff Brown58a2da82011-01-25 16:02:22 -08003981 int32_t deviceId, uint32_t source, uint32_t policyFlags, int32_t action,
Jeff Brown7fbdc842010-06-17 20:52:56 -07003982 int32_t flags, int32_t keyCode, int32_t scanCode, int32_t metaState,
3983 int32_t repeatCount, nsecs_t downTime) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003984 KeyEntry* entry = mKeyEntryPool.alloc();
Jeff Brownb6997262010-10-08 22:31:17 -07003985 initializeEventEntry(entry, EventEntry::TYPE_KEY, eventTime, policyFlags);
Jeff Brown7fbdc842010-06-17 20:52:56 -07003986
3987 entry->deviceId = deviceId;
Jeff Brownc5ed5912010-07-14 18:48:53 -07003988 entry->source = source;
Jeff Brown7fbdc842010-06-17 20:52:56 -07003989 entry->action = action;
3990 entry->flags = flags;
3991 entry->keyCode = keyCode;
3992 entry->scanCode = scanCode;
3993 entry->metaState = metaState;
3994 entry->repeatCount = repeatCount;
3995 entry->downTime = downTime;
Jeff Brownb88102f2010-09-08 11:49:43 -07003996 entry->syntheticRepeat = false;
3997 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003998 return entry;
3999}
4000
Jeff Brown7fbdc842010-06-17 20:52:56 -07004001InputDispatcher::MotionEntry* InputDispatcher::Allocator::obtainMotionEntry(nsecs_t eventTime,
Jeff Brown58a2da82011-01-25 16:02:22 -08004002 int32_t deviceId, uint32_t source, uint32_t policyFlags, int32_t action, int32_t flags,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07004003 int32_t metaState, int32_t buttonState,
4004 int32_t edgeFlags, float xPrecision, float yPrecision,
Jeff Brown7fbdc842010-06-17 20:52:56 -07004005 nsecs_t downTime, uint32_t pointerCount,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07004006 const PointerProperties* pointerProperties, const PointerCoords* pointerCoords) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004007 MotionEntry* entry = mMotionEntryPool.alloc();
Jeff Brownb6997262010-10-08 22:31:17 -07004008 initializeEventEntry(entry, EventEntry::TYPE_MOTION, eventTime, policyFlags);
Jeff Brown7fbdc842010-06-17 20:52:56 -07004009
4010 entry->eventTime = eventTime;
4011 entry->deviceId = deviceId;
Jeff Brownc5ed5912010-07-14 18:48:53 -07004012 entry->source = source;
Jeff Brown7fbdc842010-06-17 20:52:56 -07004013 entry->action = action;
Jeff Brown85a31762010-09-01 17:01:00 -07004014 entry->flags = flags;
Jeff Brown7fbdc842010-06-17 20:52:56 -07004015 entry->metaState = metaState;
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07004016 entry->buttonState = buttonState;
Jeff Brown7fbdc842010-06-17 20:52:56 -07004017 entry->edgeFlags = edgeFlags;
4018 entry->xPrecision = xPrecision;
4019 entry->yPrecision = yPrecision;
4020 entry->downTime = downTime;
4021 entry->pointerCount = pointerCount;
4022 entry->firstSample.eventTime = eventTime;
Jeff Brown4e91a182011-04-07 11:38:09 -07004023 entry->firstSample.eventTimeBeforeCoalescing = eventTime;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004024 entry->firstSample.next = NULL;
Jeff Brown7fbdc842010-06-17 20:52:56 -07004025 entry->lastSample = & entry->firstSample;
4026 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07004027 entry->pointerProperties[i].copyFrom(pointerProperties[i]);
Jeff Brownace13b12011-03-09 17:39:48 -08004028 entry->firstSample.pointerCoords[i].copyFrom(pointerCoords[i]);
Jeff Brown7fbdc842010-06-17 20:52:56 -07004029 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004030 return entry;
4031}
4032
4033InputDispatcher::DispatchEntry* InputDispatcher::Allocator::obtainDispatchEntry(
Jeff Brownb88102f2010-09-08 11:49:43 -07004034 EventEntry* eventEntry,
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004035 int32_t targetFlags, float xOffset, float yOffset, float scaleFactor) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004036 DispatchEntry* entry = mDispatchEntryPool.alloc();
4037 entry->eventEntry = eventEntry;
4038 eventEntry->refCount += 1;
Jeff Brownb88102f2010-09-08 11:49:43 -07004039 entry->targetFlags = targetFlags;
4040 entry->xOffset = xOffset;
4041 entry->yOffset = yOffset;
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004042 entry->scaleFactor = scaleFactor;
Jeff Brownb88102f2010-09-08 11:49:43 -07004043 entry->inProgress = false;
4044 entry->headMotionSample = NULL;
4045 entry->tailMotionSample = NULL;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004046 return entry;
4047}
4048
Jeff Brown9c3cda02010-06-15 01:31:58 -07004049InputDispatcher::CommandEntry* InputDispatcher::Allocator::obtainCommandEntry(Command command) {
4050 CommandEntry* entry = mCommandEntryPool.alloc();
4051 entry->command = command;
4052 return entry;
4053}
4054
Jeff Brown01ce2e92010-09-26 22:20:12 -07004055void InputDispatcher::Allocator::releaseInjectionState(InjectionState* injectionState) {
4056 injectionState->refCount -= 1;
4057 if (injectionState->refCount == 0) {
4058 mInjectionStatePool.free(injectionState);
4059 } else {
Jeff Brownb6110c22011-04-01 16:15:13 -07004060 LOG_ASSERT(injectionState->refCount > 0);
Jeff Brown01ce2e92010-09-26 22:20:12 -07004061 }
4062}
4063
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004064void InputDispatcher::Allocator::releaseEventEntry(EventEntry* entry) {
4065 switch (entry->type) {
4066 case EventEntry::TYPE_CONFIGURATION_CHANGED:
4067 releaseConfigurationChangedEntry(static_cast<ConfigurationChangedEntry*>(entry));
4068 break;
4069 case EventEntry::TYPE_KEY:
4070 releaseKeyEntry(static_cast<KeyEntry*>(entry));
4071 break;
4072 case EventEntry::TYPE_MOTION:
4073 releaseMotionEntry(static_cast<MotionEntry*>(entry));
4074 break;
4075 default:
Jeff Brownb6110c22011-04-01 16:15:13 -07004076 LOG_ASSERT(false);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004077 break;
4078 }
4079}
4080
4081void InputDispatcher::Allocator::releaseConfigurationChangedEntry(
4082 ConfigurationChangedEntry* entry) {
4083 entry->refCount -= 1;
4084 if (entry->refCount == 0) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07004085 releaseEventEntryInjectionState(entry);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004086 mConfigurationChangeEntryPool.free(entry);
4087 } else {
Jeff Brownb6110c22011-04-01 16:15:13 -07004088 LOG_ASSERT(entry->refCount > 0);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004089 }
4090}
4091
4092void InputDispatcher::Allocator::releaseKeyEntry(KeyEntry* entry) {
4093 entry->refCount -= 1;
4094 if (entry->refCount == 0) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07004095 releaseEventEntryInjectionState(entry);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004096 mKeyEntryPool.free(entry);
4097 } else {
Jeff Brownb6110c22011-04-01 16:15:13 -07004098 LOG_ASSERT(entry->refCount > 0);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004099 }
4100}
4101
4102void InputDispatcher::Allocator::releaseMotionEntry(MotionEntry* entry) {
4103 entry->refCount -= 1;
4104 if (entry->refCount == 0) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07004105 releaseEventEntryInjectionState(entry);
Jeff Brown9c3cda02010-06-15 01:31:58 -07004106 for (MotionSample* sample = entry->firstSample.next; sample != NULL; ) {
4107 MotionSample* next = sample->next;
4108 mMotionSamplePool.free(sample);
4109 sample = next;
4110 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004111 mMotionEntryPool.free(entry);
4112 } else {
Jeff Brownb6110c22011-04-01 16:15:13 -07004113 LOG_ASSERT(entry->refCount > 0);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004114 }
4115}
4116
Jeff Browna032cc02011-03-07 16:56:21 -08004117void InputDispatcher::Allocator::freeMotionSample(MotionSample* sample) {
4118 mMotionSamplePool.free(sample);
4119}
4120
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004121void InputDispatcher::Allocator::releaseDispatchEntry(DispatchEntry* entry) {
4122 releaseEventEntry(entry->eventEntry);
4123 mDispatchEntryPool.free(entry);
4124}
4125
Jeff Brown9c3cda02010-06-15 01:31:58 -07004126void InputDispatcher::Allocator::releaseCommandEntry(CommandEntry* entry) {
4127 mCommandEntryPool.free(entry);
4128}
4129
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004130void InputDispatcher::Allocator::appendMotionSample(MotionEntry* motionEntry,
Jeff Brown7fbdc842010-06-17 20:52:56 -07004131 nsecs_t eventTime, const PointerCoords* pointerCoords) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004132 MotionSample* sample = mMotionSamplePool.alloc();
4133 sample->eventTime = eventTime;
Jeff Brown4e91a182011-04-07 11:38:09 -07004134 sample->eventTimeBeforeCoalescing = eventTime;
Jeff Brown7fbdc842010-06-17 20:52:56 -07004135 uint32_t pointerCount = motionEntry->pointerCount;
4136 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brownace13b12011-03-09 17:39:48 -08004137 sample->pointerCoords[i].copyFrom(pointerCoords[i]);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004138 }
4139
4140 sample->next = NULL;
4141 motionEntry->lastSample->next = sample;
4142 motionEntry->lastSample = sample;
4143}
4144
Jeff Brown01ce2e92010-09-26 22:20:12 -07004145void InputDispatcher::Allocator::recycleKeyEntry(KeyEntry* keyEntry) {
4146 releaseEventEntryInjectionState(keyEntry);
Jeff Brownb88102f2010-09-08 11:49:43 -07004147
Jeff Brown01ce2e92010-09-26 22:20:12 -07004148 keyEntry->dispatchInProgress = false;
4149 keyEntry->syntheticRepeat = false;
4150 keyEntry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
Jeff Brownb88102f2010-09-08 11:49:43 -07004151}
4152
4153
Jeff Brownae9fc032010-08-18 15:51:08 -07004154// --- InputDispatcher::MotionEntry ---
4155
4156uint32_t InputDispatcher::MotionEntry::countSamples() const {
4157 uint32_t count = 1;
4158 for (MotionSample* sample = firstSample.next; sample != NULL; sample = sample->next) {
4159 count += 1;
4160 }
4161 return count;
4162}
4163
Jeff Brown4e91a182011-04-07 11:38:09 -07004164bool InputDispatcher::MotionEntry::canAppendSamples(int32_t action, uint32_t pointerCount,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07004165 const PointerProperties* pointerProperties) const {
Jeff Brown4e91a182011-04-07 11:38:09 -07004166 if (this->action != action
4167 || this->pointerCount != pointerCount
4168 || this->isInjected()) {
4169 return false;
4170 }
4171 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07004172 if (this->pointerProperties[i] != pointerProperties[i]) {
Jeff Brown4e91a182011-04-07 11:38:09 -07004173 return false;
4174 }
4175 }
4176 return true;
4177}
4178
Jeff Brownb88102f2010-09-08 11:49:43 -07004179
4180// --- InputDispatcher::InputState ---
4181
Jeff Brownb6997262010-10-08 22:31:17 -07004182InputDispatcher::InputState::InputState() {
Jeff Brownb88102f2010-09-08 11:49:43 -07004183}
4184
4185InputDispatcher::InputState::~InputState() {
4186}
4187
4188bool InputDispatcher::InputState::isNeutral() const {
4189 return mKeyMementos.isEmpty() && mMotionMementos.isEmpty();
4190}
4191
Jeff Brown81346812011-06-28 20:08:48 -07004192bool InputDispatcher::InputState::isHovering(int32_t deviceId, uint32_t source) const {
4193 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4194 const MotionMemento& memento = mMotionMementos.itemAt(i);
4195 if (memento.deviceId == deviceId
4196 && memento.source == source
4197 && memento.hovering) {
4198 return true;
4199 }
4200 }
4201 return false;
4202}
Jeff Brownb88102f2010-09-08 11:49:43 -07004203
Jeff Brown81346812011-06-28 20:08:48 -07004204bool InputDispatcher::InputState::trackKey(const KeyEntry* entry,
4205 int32_t action, int32_t flags) {
4206 switch (action) {
4207 case AKEY_EVENT_ACTION_UP: {
4208 if (entry->flags & AKEY_EVENT_FLAG_FALLBACK) {
4209 for (size_t i = 0; i < mFallbackKeys.size(); ) {
4210 if (mFallbackKeys.valueAt(i) == entry->keyCode) {
4211 mFallbackKeys.removeItemsAt(i);
4212 } else {
4213 i += 1;
4214 }
4215 }
4216 }
4217 ssize_t index = findKeyMemento(entry);
4218 if (index >= 0) {
4219 mKeyMementos.removeAt(index);
4220 return true;
4221 }
4222#if DEBUG_OUTBOUND_EVENT_DETAILS
4223 LOGD("Dropping inconsistent key up event: deviceId=%d, source=%08x, "
4224 "keyCode=%d, scanCode=%d",
4225 entry->deviceId, entry->source, entry->keyCode, entry->scanCode);
4226#endif
4227 return false;
4228 }
4229
4230 case AKEY_EVENT_ACTION_DOWN: {
4231 ssize_t index = findKeyMemento(entry);
4232 if (index >= 0) {
4233 mKeyMementos.removeAt(index);
4234 }
4235 addKeyMemento(entry, flags);
4236 return true;
4237 }
4238
4239 default:
4240 return true;
Jeff Brownb88102f2010-09-08 11:49:43 -07004241 }
4242}
4243
Jeff Brown81346812011-06-28 20:08:48 -07004244bool InputDispatcher::InputState::trackMotion(const MotionEntry* entry,
4245 int32_t action, int32_t flags) {
4246 int32_t actionMasked = action & AMOTION_EVENT_ACTION_MASK;
4247 switch (actionMasked) {
4248 case AMOTION_EVENT_ACTION_UP:
4249 case AMOTION_EVENT_ACTION_CANCEL: {
4250 ssize_t index = findMotionMemento(entry, false /*hovering*/);
4251 if (index >= 0) {
4252 mMotionMementos.removeAt(index);
4253 return true;
Jeff Brownda3d5a92011-03-29 15:11:34 -07004254 }
Jeff Brown81346812011-06-28 20:08:48 -07004255#if DEBUG_OUTBOUND_EVENT_DETAILS
4256 LOGD("Dropping inconsistent motion up or cancel event: deviceId=%d, source=%08x, "
4257 "actionMasked=%d",
4258 entry->deviceId, entry->source, actionMasked);
4259#endif
4260 return false;
Jeff Brownda3d5a92011-03-29 15:11:34 -07004261 }
4262
Jeff Brown81346812011-06-28 20:08:48 -07004263 case AMOTION_EVENT_ACTION_DOWN: {
4264 ssize_t index = findMotionMemento(entry, false /*hovering*/);
4265 if (index >= 0) {
4266 mMotionMementos.removeAt(index);
4267 }
4268 addMotionMemento(entry, flags, false /*hovering*/);
4269 return true;
4270 }
4271
4272 case AMOTION_EVENT_ACTION_POINTER_UP:
4273 case AMOTION_EVENT_ACTION_POINTER_DOWN:
4274 case AMOTION_EVENT_ACTION_MOVE: {
4275 ssize_t index = findMotionMemento(entry, false /*hovering*/);
4276 if (index >= 0) {
4277 MotionMemento& memento = mMotionMementos.editItemAt(index);
4278 memento.setPointers(entry);
4279 return true;
4280 }
Jeff Brown2e45fb62011-06-29 21:19:05 -07004281 if (actionMasked == AMOTION_EVENT_ACTION_MOVE
4282 && (entry->source & (AINPUT_SOURCE_CLASS_JOYSTICK
4283 | AINPUT_SOURCE_CLASS_NAVIGATION))) {
4284 // Joysticks and trackballs can send MOVE events without corresponding DOWN or UP.
4285 return true;
4286 }
Jeff Brown81346812011-06-28 20:08:48 -07004287#if DEBUG_OUTBOUND_EVENT_DETAILS
4288 LOGD("Dropping inconsistent motion pointer up/down or move event: "
4289 "deviceId=%d, source=%08x, actionMasked=%d",
4290 entry->deviceId, entry->source, actionMasked);
4291#endif
4292 return false;
4293 }
4294
4295 case AMOTION_EVENT_ACTION_HOVER_EXIT: {
4296 ssize_t index = findMotionMemento(entry, true /*hovering*/);
4297 if (index >= 0) {
4298 mMotionMementos.removeAt(index);
4299 return true;
4300 }
4301#if DEBUG_OUTBOUND_EVENT_DETAILS
4302 LOGD("Dropping inconsistent motion hover exit event: deviceId=%d, source=%08x",
4303 entry->deviceId, entry->source);
4304#endif
4305 return false;
4306 }
4307
4308 case AMOTION_EVENT_ACTION_HOVER_ENTER:
4309 case AMOTION_EVENT_ACTION_HOVER_MOVE: {
4310 ssize_t index = findMotionMemento(entry, true /*hovering*/);
4311 if (index >= 0) {
4312 mMotionMementos.removeAt(index);
4313 }
4314 addMotionMemento(entry, flags, true /*hovering*/);
4315 return true;
4316 }
4317
4318 default:
4319 return true;
4320 }
4321}
4322
4323ssize_t InputDispatcher::InputState::findKeyMemento(const KeyEntry* entry) const {
Jeff Brownb88102f2010-09-08 11:49:43 -07004324 for (size_t i = 0; i < mKeyMementos.size(); i++) {
Jeff Brown81346812011-06-28 20:08:48 -07004325 const KeyMemento& memento = mKeyMementos.itemAt(i);
Jeff Brownb88102f2010-09-08 11:49:43 -07004326 if (memento.deviceId == entry->deviceId
4327 && memento.source == entry->source
4328 && memento.keyCode == entry->keyCode
4329 && memento.scanCode == entry->scanCode) {
Jeff Brown81346812011-06-28 20:08:48 -07004330 return i;
Jeff Brownb88102f2010-09-08 11:49:43 -07004331 }
4332 }
Jeff Brown81346812011-06-28 20:08:48 -07004333 return -1;
Jeff Brownb88102f2010-09-08 11:49:43 -07004334}
4335
Jeff Brown81346812011-06-28 20:08:48 -07004336ssize_t InputDispatcher::InputState::findMotionMemento(const MotionEntry* entry,
4337 bool hovering) const {
Jeff Brownb88102f2010-09-08 11:49:43 -07004338 for (size_t i = 0; i < mMotionMementos.size(); i++) {
Jeff Brown81346812011-06-28 20:08:48 -07004339 const MotionMemento& memento = mMotionMementos.itemAt(i);
Jeff Brownb88102f2010-09-08 11:49:43 -07004340 if (memento.deviceId == entry->deviceId
Jeff Brown81346812011-06-28 20:08:48 -07004341 && memento.source == entry->source
4342 && memento.hovering == hovering) {
4343 return i;
Jeff Brownb88102f2010-09-08 11:49:43 -07004344 }
4345 }
Jeff Brown81346812011-06-28 20:08:48 -07004346 return -1;
4347}
Jeff Brownb88102f2010-09-08 11:49:43 -07004348
Jeff Brown81346812011-06-28 20:08:48 -07004349void InputDispatcher::InputState::addKeyMemento(const KeyEntry* entry, int32_t flags) {
4350 mKeyMementos.push();
4351 KeyMemento& memento = mKeyMementos.editTop();
4352 memento.deviceId = entry->deviceId;
4353 memento.source = entry->source;
4354 memento.keyCode = entry->keyCode;
4355 memento.scanCode = entry->scanCode;
4356 memento.flags = flags;
4357 memento.downTime = entry->downTime;
4358}
4359
4360void InputDispatcher::InputState::addMotionMemento(const MotionEntry* entry,
4361 int32_t flags, bool hovering) {
4362 mMotionMementos.push();
4363 MotionMemento& memento = mMotionMementos.editTop();
4364 memento.deviceId = entry->deviceId;
4365 memento.source = entry->source;
4366 memento.flags = flags;
4367 memento.xPrecision = entry->xPrecision;
4368 memento.yPrecision = entry->yPrecision;
4369 memento.downTime = entry->downTime;
4370 memento.setPointers(entry);
4371 memento.hovering = hovering;
Jeff Brownb88102f2010-09-08 11:49:43 -07004372}
4373
4374void InputDispatcher::InputState::MotionMemento::setPointers(const MotionEntry* entry) {
4375 pointerCount = entry->pointerCount;
4376 for (uint32_t i = 0; i < entry->pointerCount; i++) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07004377 pointerProperties[i].copyFrom(entry->pointerProperties[i]);
Jeff Brownace13b12011-03-09 17:39:48 -08004378 pointerCoords[i].copyFrom(entry->lastSample->pointerCoords[i]);
Jeff Brownb88102f2010-09-08 11:49:43 -07004379 }
4380}
4381
Jeff Brownb6997262010-10-08 22:31:17 -07004382void InputDispatcher::InputState::synthesizeCancelationEvents(nsecs_t currentTime,
4383 Allocator* allocator, Vector<EventEntry*>& outEvents,
Jeff Brownda3d5a92011-03-29 15:11:34 -07004384 const CancelationOptions& options) {
Jeff Brown81346812011-06-28 20:08:48 -07004385 for (size_t i = 0; i < mKeyMementos.size(); i++) {
Jeff Brownb88102f2010-09-08 11:49:43 -07004386 const KeyMemento& memento = mKeyMementos.itemAt(i);
Jeff Brown49ed71d2010-12-06 17:13:33 -08004387 if (shouldCancelKey(memento, options)) {
Jeff Brownb6997262010-10-08 22:31:17 -07004388 outEvents.push(allocator->obtainKeyEntry(currentTime,
4389 memento.deviceId, memento.source, 0,
Jeff Brown49ed71d2010-12-06 17:13:33 -08004390 AKEY_EVENT_ACTION_UP, memento.flags | AKEY_EVENT_FLAG_CANCELED,
Jeff Brownb6997262010-10-08 22:31:17 -07004391 memento.keyCode, memento.scanCode, 0, 0, memento.downTime));
Jeff Brownb6997262010-10-08 22:31:17 -07004392 }
Jeff Brownb88102f2010-09-08 11:49:43 -07004393 }
4394
Jeff Brown81346812011-06-28 20:08:48 -07004395 for (size_t i = 0; i < mMotionMementos.size(); i++) {
Jeff Brownb88102f2010-09-08 11:49:43 -07004396 const MotionMemento& memento = mMotionMementos.itemAt(i);
Jeff Brown49ed71d2010-12-06 17:13:33 -08004397 if (shouldCancelMotion(memento, options)) {
Jeff Brownb6997262010-10-08 22:31:17 -07004398 outEvents.push(allocator->obtainMotionEntry(currentTime,
4399 memento.deviceId, memento.source, 0,
Jeff Browna032cc02011-03-07 16:56:21 -08004400 memento.hovering
4401 ? AMOTION_EVENT_ACTION_HOVER_EXIT
4402 : AMOTION_EVENT_ACTION_CANCEL,
Jeff Brown81346812011-06-28 20:08:48 -07004403 memento.flags, 0, 0, 0,
Jeff Brownb6997262010-10-08 22:31:17 -07004404 memento.xPrecision, memento.yPrecision, memento.downTime,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07004405 memento.pointerCount, memento.pointerProperties, memento.pointerCoords));
Jeff Brownb6997262010-10-08 22:31:17 -07004406 }
Jeff Brownb88102f2010-09-08 11:49:43 -07004407 }
4408}
4409
4410void InputDispatcher::InputState::clear() {
4411 mKeyMementos.clear();
4412 mMotionMementos.clear();
Jeff Brownda3d5a92011-03-29 15:11:34 -07004413 mFallbackKeys.clear();
Jeff Brownb6997262010-10-08 22:31:17 -07004414}
4415
Jeff Brown9c9f1a32010-10-11 18:32:20 -07004416void InputDispatcher::InputState::copyPointerStateTo(InputState& other) const {
4417 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4418 const MotionMemento& memento = mMotionMementos.itemAt(i);
4419 if (memento.source & AINPUT_SOURCE_CLASS_POINTER) {
4420 for (size_t j = 0; j < other.mMotionMementos.size(); ) {
4421 const MotionMemento& otherMemento = other.mMotionMementos.itemAt(j);
4422 if (memento.deviceId == otherMemento.deviceId
4423 && memento.source == otherMemento.source) {
4424 other.mMotionMementos.removeAt(j);
4425 } else {
4426 j += 1;
4427 }
4428 }
4429 other.mMotionMementos.push(memento);
4430 }
4431 }
4432}
4433
Jeff Brownda3d5a92011-03-29 15:11:34 -07004434int32_t InputDispatcher::InputState::getFallbackKey(int32_t originalKeyCode) {
4435 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
4436 return index >= 0 ? mFallbackKeys.valueAt(index) : -1;
4437}
4438
4439void InputDispatcher::InputState::setFallbackKey(int32_t originalKeyCode,
4440 int32_t fallbackKeyCode) {
4441 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
4442 if (index >= 0) {
4443 mFallbackKeys.replaceValueAt(index, fallbackKeyCode);
4444 } else {
4445 mFallbackKeys.add(originalKeyCode, fallbackKeyCode);
4446 }
4447}
4448
4449void InputDispatcher::InputState::removeFallbackKey(int32_t originalKeyCode) {
4450 mFallbackKeys.removeItem(originalKeyCode);
4451}
4452
Jeff Brown49ed71d2010-12-06 17:13:33 -08004453bool InputDispatcher::InputState::shouldCancelKey(const KeyMemento& memento,
Jeff Brownda3d5a92011-03-29 15:11:34 -07004454 const CancelationOptions& options) {
4455 if (options.keyCode != -1 && memento.keyCode != options.keyCode) {
4456 return false;
4457 }
4458
4459 switch (options.mode) {
4460 case CancelationOptions::CANCEL_ALL_EVENTS:
4461 case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
Jeff Brownb6997262010-10-08 22:31:17 -07004462 return true;
Jeff Brownda3d5a92011-03-29 15:11:34 -07004463 case CancelationOptions::CANCEL_FALLBACK_EVENTS:
Jeff Brown49ed71d2010-12-06 17:13:33 -08004464 return memento.flags & AKEY_EVENT_FLAG_FALLBACK;
4465 default:
4466 return false;
4467 }
4468}
4469
4470bool InputDispatcher::InputState::shouldCancelMotion(const MotionMemento& memento,
Jeff Brownda3d5a92011-03-29 15:11:34 -07004471 const CancelationOptions& options) {
4472 switch (options.mode) {
4473 case CancelationOptions::CANCEL_ALL_EVENTS:
Jeff Brown49ed71d2010-12-06 17:13:33 -08004474 return true;
Jeff Brownda3d5a92011-03-29 15:11:34 -07004475 case CancelationOptions::CANCEL_POINTER_EVENTS:
Jeff Brown49ed71d2010-12-06 17:13:33 -08004476 return memento.source & AINPUT_SOURCE_CLASS_POINTER;
Jeff Brownda3d5a92011-03-29 15:11:34 -07004477 case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
Jeff Brown49ed71d2010-12-06 17:13:33 -08004478 return !(memento.source & AINPUT_SOURCE_CLASS_POINTER);
4479 default:
4480 return false;
Jeff Brownb6997262010-10-08 22:31:17 -07004481 }
Jeff Brownb88102f2010-09-08 11:49:43 -07004482}
4483
4484
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004485// --- InputDispatcher::Connection ---
4486
Jeff Brown928e0542011-01-10 11:17:36 -08004487InputDispatcher::Connection::Connection(const sp<InputChannel>& inputChannel,
4488 const sp<InputWindowHandle>& inputWindowHandle) :
4489 status(STATUS_NORMAL), inputChannel(inputChannel), inputWindowHandle(inputWindowHandle),
4490 inputPublisher(inputChannel),
Jeff Brownda3d5a92011-03-29 15:11:34 -07004491 lastEventTime(LONG_LONG_MAX), lastDispatchTime(LONG_LONG_MAX) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004492}
4493
4494InputDispatcher::Connection::~Connection() {
4495}
4496
4497status_t InputDispatcher::Connection::initialize() {
4498 return inputPublisher.initialize();
4499}
4500
Jeff Brown9c3cda02010-06-15 01:31:58 -07004501const char* InputDispatcher::Connection::getStatusLabel() const {
4502 switch (status) {
4503 case STATUS_NORMAL:
4504 return "NORMAL";
4505
4506 case STATUS_BROKEN:
4507 return "BROKEN";
4508
Jeff Brown9c3cda02010-06-15 01:31:58 -07004509 case STATUS_ZOMBIE:
4510 return "ZOMBIE";
4511
4512 default:
4513 return "UNKNOWN";
4514 }
4515}
4516
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004517InputDispatcher::DispatchEntry* InputDispatcher::Connection::findQueuedDispatchEntryForEvent(
4518 const EventEntry* eventEntry) const {
Jeff Brownb88102f2010-09-08 11:49:43 -07004519 for (DispatchEntry* dispatchEntry = outboundQueue.tailSentinel.prev;
4520 dispatchEntry != & outboundQueue.headSentinel; dispatchEntry = dispatchEntry->prev) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004521 if (dispatchEntry->eventEntry == eventEntry) {
4522 return dispatchEntry;
4523 }
4524 }
4525 return NULL;
4526}
4527
Jeff Brownb88102f2010-09-08 11:49:43 -07004528
Jeff Brown9c3cda02010-06-15 01:31:58 -07004529// --- InputDispatcher::CommandEntry ---
4530
Jeff Brownb88102f2010-09-08 11:49:43 -07004531InputDispatcher::CommandEntry::CommandEntry() :
4532 keyEntry(NULL) {
Jeff Brown9c3cda02010-06-15 01:31:58 -07004533}
4534
4535InputDispatcher::CommandEntry::~CommandEntry() {
4536}
4537
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004538
Jeff Brown01ce2e92010-09-26 22:20:12 -07004539// --- InputDispatcher::TouchState ---
4540
4541InputDispatcher::TouchState::TouchState() :
Jeff Brown58a2da82011-01-25 16:02:22 -08004542 down(false), split(false), deviceId(-1), source(0) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07004543}
4544
4545InputDispatcher::TouchState::~TouchState() {
4546}
4547
4548void InputDispatcher::TouchState::reset() {
4549 down = false;
4550 split = false;
Jeff Brown95712852011-01-04 19:41:59 -08004551 deviceId = -1;
Jeff Brown58a2da82011-01-25 16:02:22 -08004552 source = 0;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004553 windows.clear();
4554}
4555
4556void InputDispatcher::TouchState::copyFrom(const TouchState& other) {
4557 down = other.down;
4558 split = other.split;
Jeff Brown95712852011-01-04 19:41:59 -08004559 deviceId = other.deviceId;
Jeff Brown58a2da82011-01-25 16:02:22 -08004560 source = other.source;
Jeff Brown9302c872011-07-13 22:51:29 -07004561 windows = other.windows;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004562}
4563
Jeff Brown9302c872011-07-13 22:51:29 -07004564void InputDispatcher::TouchState::addOrUpdateWindow(const sp<InputWindowHandle>& windowHandle,
Jeff Brown01ce2e92010-09-26 22:20:12 -07004565 int32_t targetFlags, BitSet32 pointerIds) {
4566 if (targetFlags & InputTarget::FLAG_SPLIT) {
4567 split = true;
4568 }
4569
4570 for (size_t i = 0; i < windows.size(); i++) {
4571 TouchedWindow& touchedWindow = windows.editItemAt(i);
Jeff Brown9302c872011-07-13 22:51:29 -07004572 if (touchedWindow.windowHandle == windowHandle) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07004573 touchedWindow.targetFlags |= targetFlags;
Jeff Brown98db5fa2011-06-08 15:37:10 -07004574 if (targetFlags & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
4575 touchedWindow.targetFlags &= ~InputTarget::FLAG_DISPATCH_AS_IS;
4576 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07004577 touchedWindow.pointerIds.value |= pointerIds.value;
4578 return;
4579 }
4580 }
4581
4582 windows.push();
4583
4584 TouchedWindow& touchedWindow = windows.editTop();
Jeff Brown9302c872011-07-13 22:51:29 -07004585 touchedWindow.windowHandle = windowHandle;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004586 touchedWindow.targetFlags = targetFlags;
4587 touchedWindow.pointerIds = pointerIds;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004588}
4589
Jeff Browna032cc02011-03-07 16:56:21 -08004590void InputDispatcher::TouchState::filterNonAsIsTouchWindows() {
Jeff Brown01ce2e92010-09-26 22:20:12 -07004591 for (size_t i = 0 ; i < windows.size(); ) {
Jeff Browna032cc02011-03-07 16:56:21 -08004592 TouchedWindow& window = windows.editItemAt(i);
Jeff Brown98db5fa2011-06-08 15:37:10 -07004593 if (window.targetFlags & (InputTarget::FLAG_DISPATCH_AS_IS
4594 | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER)) {
Jeff Browna032cc02011-03-07 16:56:21 -08004595 window.targetFlags &= ~InputTarget::FLAG_DISPATCH_MASK;
4596 window.targetFlags |= InputTarget::FLAG_DISPATCH_AS_IS;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004597 i += 1;
Jeff Browna032cc02011-03-07 16:56:21 -08004598 } else {
4599 windows.removeAt(i);
Jeff Brown01ce2e92010-09-26 22:20:12 -07004600 }
4601 }
4602}
4603
Jeff Brown9302c872011-07-13 22:51:29 -07004604sp<InputWindowHandle> InputDispatcher::TouchState::getFirstForegroundWindowHandle() const {
Jeff Brown01ce2e92010-09-26 22:20:12 -07004605 for (size_t i = 0; i < windows.size(); i++) {
Jeff Brown98db5fa2011-06-08 15:37:10 -07004606 const TouchedWindow& window = windows.itemAt(i);
4607 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
Jeff Brown9302c872011-07-13 22:51:29 -07004608 return window.windowHandle;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004609 }
4610 }
4611 return NULL;
4612}
4613
Jeff Brown98db5fa2011-06-08 15:37:10 -07004614bool InputDispatcher::TouchState::isSlippery() const {
4615 // Must have exactly one foreground window.
4616 bool haveSlipperyForegroundWindow = false;
4617 for (size_t i = 0; i < windows.size(); i++) {
4618 const TouchedWindow& window = windows.itemAt(i);
4619 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
Jeff Brown9302c872011-07-13 22:51:29 -07004620 if (haveSlipperyForegroundWindow || !(window.windowHandle->layoutParamsFlags
4621 & InputWindowHandle::FLAG_SLIPPERY)) {
Jeff Brown98db5fa2011-06-08 15:37:10 -07004622 return false;
4623 }
4624 haveSlipperyForegroundWindow = true;
4625 }
4626 }
4627 return haveSlipperyForegroundWindow;
4628}
4629
Jeff Brown01ce2e92010-09-26 22:20:12 -07004630
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004631// --- InputDispatcherThread ---
4632
4633InputDispatcherThread::InputDispatcherThread(const sp<InputDispatcherInterface>& dispatcher) :
4634 Thread(/*canCallJava*/ true), mDispatcher(dispatcher) {
4635}
4636
4637InputDispatcherThread::~InputDispatcherThread() {
4638}
4639
4640bool InputDispatcherThread::threadLoop() {
4641 mDispatcher->dispatchOnce();
4642 return true;
4643}
4644
4645} // namespace android