blob: cbdfe8c4ac38cab66777656fc0e5283118ed2a32 [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 Brown46b9ac0a2010-04-22 18:58:52 -0700218 mKeyRepeatState.lastKeyEntry = NULL;
Jeff Brown9c3cda02010-06-15 01:31:58 -0700219
Jeff Brown214eaf42011-05-26 19:17:02 -0700220 policy->getDispatcherConfiguration(&mConfig);
221
222 mThrottleState.minTimeBetweenEvents = 1000000000LL / mConfig.maxEventsPerSecond;
Jeff Brownae9fc032010-08-18 15:51:08 -0700223 mThrottleState.lastDeviceId = -1;
224
225#if DEBUG_THROTTLING
226 mThrottleState.originalSampleCount = 0;
Jeff Brown214eaf42011-05-26 19:17:02 -0700227 LOGD("Throttling - Max events per second = %d", mConfig.maxEventsPerSecond);
Jeff Brownae9fc032010-08-18 15:51:08 -0700228#endif
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700229}
230
231InputDispatcher::~InputDispatcher() {
Jeff Brownb88102f2010-09-08 11:49:43 -0700232 { // acquire lock
233 AutoMutex _l(mLock);
234
235 resetKeyRepeatLocked();
Jeff Brown54a18252010-09-16 14:07:33 -0700236 releasePendingEventLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -0700237 drainInboundQueueLocked();
238 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700239
240 while (mConnectionsByReceiveFd.size() != 0) {
241 unregisterInputChannel(mConnectionsByReceiveFd.valueAt(0)->inputChannel);
242 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700243}
244
245void InputDispatcher::dispatchOnce() {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700246 nsecs_t nextWakeupTime = LONG_LONG_MAX;
247 { // acquire lock
248 AutoMutex _l(mLock);
Jeff Brown214eaf42011-05-26 19:17:02 -0700249 dispatchOnceInnerLocked(&nextWakeupTime);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700250
Jeff Brownb88102f2010-09-08 11:49:43 -0700251 if (runCommandsLockedInterruptible()) {
252 nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700253 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700254 } // release lock
255
Jeff Brownb88102f2010-09-08 11:49:43 -0700256 // Wait for callback or timeout or wake. (make sure we round up, not down)
257 nsecs_t currentTime = now();
Jeff Brownaa3855d2011-03-17 01:34:19 -0700258 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
Jeff Brown4fe6c3e2010-09-13 23:17:30 -0700259 mLooper->pollOnce(timeoutMillis);
Jeff Brownb88102f2010-09-08 11:49:43 -0700260}
261
Jeff Brown214eaf42011-05-26 19:17:02 -0700262void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700263 nsecs_t currentTime = now();
264
265 // Reset the key repeat timer whenever we disallow key events, even if the next event
266 // is not a key. This is to ensure that we abort a key repeat if the device is just coming
267 // out of sleep.
Jeff Brown214eaf42011-05-26 19:17:02 -0700268 if (!mPolicy->isKeyRepeatEnabled()) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700269 resetKeyRepeatLocked();
270 }
271
Jeff Brownb88102f2010-09-08 11:49:43 -0700272 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
273 if (mDispatchFrozen) {
274#if DEBUG_FOCUS
275 LOGD("Dispatch frozen. Waiting some more.");
276#endif
277 return;
278 }
279
280 // Optimize latency of app switches.
281 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
282 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
283 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
284 if (mAppSwitchDueTime < *nextWakeupTime) {
285 *nextWakeupTime = mAppSwitchDueTime;
286 }
287
Jeff Brownb88102f2010-09-08 11:49:43 -0700288 // Ready to start a new event.
289 // If we don't already have a pending event, go grab one.
290 if (! mPendingEvent) {
291 if (mInboundQueue.isEmpty()) {
292 if (isAppSwitchDue) {
293 // The inbound queue is empty so the app switch key we were waiting
294 // for will never arrive. Stop waiting for it.
295 resetPendingAppSwitchLocked(false);
296 isAppSwitchDue = false;
297 }
298
299 // Synthesize a key repeat if appropriate.
300 if (mKeyRepeatState.lastKeyEntry) {
301 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
Jeff Brown214eaf42011-05-26 19:17:02 -0700302 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700303 } else {
304 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
305 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
306 }
307 }
308 }
309 if (! mPendingEvent) {
310 return;
311 }
312 } else {
313 // Inbound queue has at least one entry.
Jeff Brownac386072011-07-20 15:19:50 -0700314 EventEntry* entry = mInboundQueue.head;
Jeff Brownb88102f2010-09-08 11:49:43 -0700315
316 // Throttle the entry if it is a move event and there are no
317 // other events behind it in the queue. Due to movement batching, additional
318 // samples may be appended to this event by the time the throttling timeout
319 // expires.
320 // TODO Make this smarter and consider throttling per device independently.
Jeff Brownb6997262010-10-08 22:31:17 -0700321 if (entry->type == EventEntry::TYPE_MOTION
322 && !isAppSwitchDue
323 && mDispatchEnabled
324 && (entry->policyFlags & POLICY_FLAG_PASS_TO_USER)
325 && !entry->isInjected()) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700326 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
327 int32_t deviceId = motionEntry->deviceId;
328 uint32_t source = motionEntry->source;
329 if (! isAppSwitchDue
Jeff Brownac386072011-07-20 15:19:50 -0700330 && !motionEntry->next // exactly one event, no successors
Jeff Browncc0c1592011-02-19 05:07:28 -0800331 && (motionEntry->action == AMOTION_EVENT_ACTION_MOVE
332 || motionEntry->action == AMOTION_EVENT_ACTION_HOVER_MOVE)
Jeff Brownb88102f2010-09-08 11:49:43 -0700333 && deviceId == mThrottleState.lastDeviceId
334 && source == mThrottleState.lastSource) {
335 nsecs_t nextTime = mThrottleState.lastEventTime
336 + mThrottleState.minTimeBetweenEvents;
337 if (currentTime < nextTime) {
338 // Throttle it!
339#if DEBUG_THROTTLING
340 LOGD("Throttling - Delaying motion event for "
Jeff Brown90655042010-12-02 13:50:46 -0800341 "device %d, source 0x%08x by up to %0.3fms.",
Jeff Brownb88102f2010-09-08 11:49:43 -0700342 deviceId, source, (nextTime - currentTime) * 0.000001);
343#endif
344 if (nextTime < *nextWakeupTime) {
345 *nextWakeupTime = nextTime;
346 }
347 if (mThrottleState.originalSampleCount == 0) {
348 mThrottleState.originalSampleCount =
349 motionEntry->countSamples();
350 }
351 return;
352 }
353 }
354
355#if DEBUG_THROTTLING
356 if (mThrottleState.originalSampleCount != 0) {
357 uint32_t count = motionEntry->countSamples();
358 LOGD("Throttling - Motion event sample count grew by %d from %d to %d.",
359 count - mThrottleState.originalSampleCount,
360 mThrottleState.originalSampleCount, count);
361 mThrottleState.originalSampleCount = 0;
362 }
363#endif
364
makarand.karvekarf634ded2011-03-02 15:41:03 -0600365 mThrottleState.lastEventTime = currentTime;
Jeff Brownb88102f2010-09-08 11:49:43 -0700366 mThrottleState.lastDeviceId = deviceId;
367 mThrottleState.lastSource = source;
368 }
369
370 mInboundQueue.dequeue(entry);
371 mPendingEvent = entry;
372 }
Jeff Browne2fe69e2010-10-18 13:21:23 -0700373
374 // Poke user activity for this event.
375 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
376 pokeUserActivityLocked(mPendingEvent);
377 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700378 }
379
380 // Now we have an event to dispatch.
Jeff Brown928e0542011-01-10 11:17:36 -0800381 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Jeff Brownb6110c22011-04-01 16:15:13 -0700382 LOG_ASSERT(mPendingEvent != NULL);
Jeff Brown54a18252010-09-16 14:07:33 -0700383 bool done = false;
Jeff Brownb6997262010-10-08 22:31:17 -0700384 DropReason dropReason = DROP_REASON_NOT_DROPPED;
385 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
386 dropReason = DROP_REASON_POLICY;
387 } else if (!mDispatchEnabled) {
388 dropReason = DROP_REASON_DISABLED;
389 }
Jeff Brown928e0542011-01-10 11:17:36 -0800390
391 if (mNextUnblockedEvent == mPendingEvent) {
392 mNextUnblockedEvent = NULL;
393 }
394
Jeff Brownb88102f2010-09-08 11:49:43 -0700395 switch (mPendingEvent->type) {
396 case EventEntry::TYPE_CONFIGURATION_CHANGED: {
397 ConfigurationChangedEntry* typedEntry =
398 static_cast<ConfigurationChangedEntry*>(mPendingEvent);
Jeff Brown54a18252010-09-16 14:07:33 -0700399 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Jeff Brownb6997262010-10-08 22:31:17 -0700400 dropReason = DROP_REASON_NOT_DROPPED; // configuration changes are never dropped
Jeff Brownb88102f2010-09-08 11:49:43 -0700401 break;
402 }
403
404 case EventEntry::TYPE_KEY: {
405 KeyEntry* typedEntry = static_cast<KeyEntry*>(mPendingEvent);
Jeff Brownb6997262010-10-08 22:31:17 -0700406 if (isAppSwitchDue) {
407 if (isAppSwitchKeyEventLocked(typedEntry)) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700408 resetPendingAppSwitchLocked(true);
Jeff Brownb6997262010-10-08 22:31:17 -0700409 isAppSwitchDue = false;
410 } else if (dropReason == DROP_REASON_NOT_DROPPED) {
411 dropReason = DROP_REASON_APP_SWITCH;
Jeff Brownb88102f2010-09-08 11:49:43 -0700412 }
413 }
Jeff Brown928e0542011-01-10 11:17:36 -0800414 if (dropReason == DROP_REASON_NOT_DROPPED
415 && isStaleEventLocked(currentTime, typedEntry)) {
416 dropReason = DROP_REASON_STALE;
417 }
418 if (dropReason == DROP_REASON_NOT_DROPPED && mNextUnblockedEvent) {
419 dropReason = DROP_REASON_BLOCKED;
420 }
Jeff Brown214eaf42011-05-26 19:17:02 -0700421 done = dispatchKeyLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700422 break;
423 }
424
425 case EventEntry::TYPE_MOTION: {
426 MotionEntry* typedEntry = static_cast<MotionEntry*>(mPendingEvent);
Jeff Brownb6997262010-10-08 22:31:17 -0700427 if (dropReason == DROP_REASON_NOT_DROPPED && isAppSwitchDue) {
428 dropReason = DROP_REASON_APP_SWITCH;
Jeff Brownb88102f2010-09-08 11:49:43 -0700429 }
Jeff Brown928e0542011-01-10 11:17:36 -0800430 if (dropReason == DROP_REASON_NOT_DROPPED
431 && isStaleEventLocked(currentTime, typedEntry)) {
432 dropReason = DROP_REASON_STALE;
433 }
434 if (dropReason == DROP_REASON_NOT_DROPPED && mNextUnblockedEvent) {
435 dropReason = DROP_REASON_BLOCKED;
436 }
Jeff Brownb6997262010-10-08 22:31:17 -0700437 done = dispatchMotionLocked(currentTime, typedEntry,
Jeff Browne20c9e02010-10-11 14:20:19 -0700438 &dropReason, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700439 break;
440 }
441
442 default:
Jeff Brownb6110c22011-04-01 16:15:13 -0700443 LOG_ASSERT(false);
Jeff Brownb88102f2010-09-08 11:49:43 -0700444 break;
445 }
446
Jeff Brown54a18252010-09-16 14:07:33 -0700447 if (done) {
Jeff Brownb6997262010-10-08 22:31:17 -0700448 if (dropReason != DROP_REASON_NOT_DROPPED) {
449 dropInboundEventLocked(mPendingEvent, dropReason);
450 }
451
Jeff Brown54a18252010-09-16 14:07:33 -0700452 releasePendingEventLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -0700453 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
454 }
455}
456
457bool InputDispatcher::enqueueInboundEventLocked(EventEntry* entry) {
458 bool needWake = mInboundQueue.isEmpty();
459 mInboundQueue.enqueueAtTail(entry);
460
461 switch (entry->type) {
Jeff Brownb6997262010-10-08 22:31:17 -0700462 case EventEntry::TYPE_KEY: {
Jeff Brown928e0542011-01-10 11:17:36 -0800463 // Optimize app switch latency.
464 // If the application takes too long to catch up then we drop all events preceding
465 // the app switch key.
Jeff Brownb6997262010-10-08 22:31:17 -0700466 KeyEntry* keyEntry = static_cast<KeyEntry*>(entry);
467 if (isAppSwitchKeyEventLocked(keyEntry)) {
468 if (keyEntry->action == AKEY_EVENT_ACTION_DOWN) {
469 mAppSwitchSawKeyDown = true;
470 } else if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
471 if (mAppSwitchSawKeyDown) {
472#if DEBUG_APP_SWITCH
473 LOGD("App switch is pending!");
474#endif
475 mAppSwitchDueTime = keyEntry->eventTime + APP_SWITCH_TIMEOUT;
476 mAppSwitchSawKeyDown = false;
477 needWake = true;
478 }
479 }
480 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700481 break;
482 }
Jeff Brown928e0542011-01-10 11:17:36 -0800483
484 case EventEntry::TYPE_MOTION: {
485 // Optimize case where the current application is unresponsive and the user
486 // decides to touch a window in a different application.
487 // If the application takes too long to catch up then we drop all events preceding
488 // the touch into the other window.
489 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
Jeff Brown33bbfd22011-02-24 20:55:35 -0800490 if (motionEntry->action == AMOTION_EVENT_ACTION_DOWN
Jeff Brown928e0542011-01-10 11:17:36 -0800491 && (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER)
492 && mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY
Jeff Brown9302c872011-07-13 22:51:29 -0700493 && mInputTargetWaitApplicationHandle != NULL) {
Jeff Brown91c69ab2011-02-14 17:03:18 -0800494 int32_t x = int32_t(motionEntry->firstSample.pointerCoords[0].
Jeff Brownebbd5d12011-02-17 13:01:34 -0800495 getAxisValue(AMOTION_EVENT_AXIS_X));
Jeff Brown91c69ab2011-02-14 17:03:18 -0800496 int32_t y = int32_t(motionEntry->firstSample.pointerCoords[0].
Jeff Brownebbd5d12011-02-17 13:01:34 -0800497 getAxisValue(AMOTION_EVENT_AXIS_Y));
Jeff Brown9302c872011-07-13 22:51:29 -0700498 sp<InputWindowHandle> touchedWindowHandle = findTouchedWindowAtLocked(x, y);
499 if (touchedWindowHandle != NULL
500 && touchedWindowHandle->inputApplicationHandle
501 != mInputTargetWaitApplicationHandle) {
Jeff Brown928e0542011-01-10 11:17:36 -0800502 // User touched a different application than the one we are waiting on.
503 // Flag the event, and start pruning the input queue.
504 mNextUnblockedEvent = motionEntry;
505 needWake = true;
506 }
507 }
508 break;
509 }
Jeff Brownb6997262010-10-08 22:31:17 -0700510 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700511
512 return needWake;
513}
514
Jeff Brown9302c872011-07-13 22:51:29 -0700515sp<InputWindowHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t x, int32_t y) {
Jeff Brown928e0542011-01-10 11:17:36 -0800516 // Traverse windows from front to back to find touched window.
Jeff Brown9302c872011-07-13 22:51:29 -0700517 size_t numWindows = mWindowHandles.size();
Jeff Brown928e0542011-01-10 11:17:36 -0800518 for (size_t i = 0; i < numWindows; i++) {
Jeff Brown9302c872011-07-13 22:51:29 -0700519 sp<InputWindowHandle> windowHandle = mWindowHandles.itemAt(i);
520 int32_t flags = windowHandle->layoutParamsFlags;
Jeff Brown928e0542011-01-10 11:17:36 -0800521
Jeff Brown9302c872011-07-13 22:51:29 -0700522 if (windowHandle->visible) {
523 if (!(flags & InputWindowHandle::FLAG_NOT_TOUCHABLE)) {
524 bool isTouchModal = (flags & (InputWindowHandle::FLAG_NOT_FOCUSABLE
525 | InputWindowHandle::FLAG_NOT_TOUCH_MODAL)) == 0;
526 if (isTouchModal || windowHandle->touchableRegionContainsPoint(x, y)) {
Jeff Brown928e0542011-01-10 11:17:36 -0800527 // Found window.
Jeff Brown9302c872011-07-13 22:51:29 -0700528 return windowHandle;
Jeff Brown928e0542011-01-10 11:17:36 -0800529 }
530 }
531 }
532
Jeff Brown9302c872011-07-13 22:51:29 -0700533 if (flags & InputWindowHandle::FLAG_SYSTEM_ERROR) {
Jeff Brown928e0542011-01-10 11:17:36 -0800534 // Error window is on top but not visible, so touch is dropped.
535 return NULL;
536 }
537 }
538 return NULL;
539}
540
Jeff Brownb6997262010-10-08 22:31:17 -0700541void InputDispatcher::dropInboundEventLocked(EventEntry* entry, DropReason dropReason) {
542 const char* reason;
543 switch (dropReason) {
544 case DROP_REASON_POLICY:
Jeff Browne20c9e02010-10-11 14:20:19 -0700545#if DEBUG_INBOUND_EVENT_DETAILS
Jeff Brown3122e442010-10-11 23:32:49 -0700546 LOGD("Dropped event because policy consumed it.");
Jeff Browne20c9e02010-10-11 14:20:19 -0700547#endif
Jeff Brown3122e442010-10-11 23:32:49 -0700548 reason = "inbound event was dropped because the policy consumed it";
Jeff Brownb6997262010-10-08 22:31:17 -0700549 break;
550 case DROP_REASON_DISABLED:
551 LOGI("Dropped event because input dispatch is disabled.");
552 reason = "inbound event was dropped because input dispatch is disabled";
553 break;
554 case DROP_REASON_APP_SWITCH:
555 LOGI("Dropped event because of pending overdue app switch.");
556 reason = "inbound event was dropped because of pending overdue app switch";
557 break;
Jeff Brown928e0542011-01-10 11:17:36 -0800558 case DROP_REASON_BLOCKED:
559 LOGI("Dropped event because the current application is not responding and the user "
Jeff Brown81346812011-06-28 20:08:48 -0700560 "has started interacting with a different application.");
Jeff Brown928e0542011-01-10 11:17:36 -0800561 reason = "inbound event was dropped because the current application is not responding "
Jeff Brown81346812011-06-28 20:08:48 -0700562 "and the user has started interacting with a different application";
Jeff Brown928e0542011-01-10 11:17:36 -0800563 break;
564 case DROP_REASON_STALE:
565 LOGI("Dropped event because it is stale.");
566 reason = "inbound event was dropped because it is stale";
567 break;
Jeff Brownb6997262010-10-08 22:31:17 -0700568 default:
Jeff Brownb6110c22011-04-01 16:15:13 -0700569 LOG_ASSERT(false);
Jeff Brownb6997262010-10-08 22:31:17 -0700570 return;
571 }
572
573 switch (entry->type) {
Jeff Brownda3d5a92011-03-29 15:11:34 -0700574 case EventEntry::TYPE_KEY: {
575 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
576 synthesizeCancelationEventsForAllConnectionsLocked(options);
Jeff Brownb6997262010-10-08 22:31:17 -0700577 break;
Jeff Brownda3d5a92011-03-29 15:11:34 -0700578 }
Jeff Brownb6997262010-10-08 22:31:17 -0700579 case EventEntry::TYPE_MOTION: {
580 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
581 if (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) {
Jeff Brownda3d5a92011-03-29 15:11:34 -0700582 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
583 synthesizeCancelationEventsForAllConnectionsLocked(options);
Jeff Brownb6997262010-10-08 22:31:17 -0700584 } else {
Jeff Brownda3d5a92011-03-29 15:11:34 -0700585 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
586 synthesizeCancelationEventsForAllConnectionsLocked(options);
Jeff Brownb6997262010-10-08 22:31:17 -0700587 }
588 break;
589 }
590 }
591}
592
593bool InputDispatcher::isAppSwitchKeyCode(int32_t keyCode) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700594 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL;
595}
596
Jeff Brownb6997262010-10-08 22:31:17 -0700597bool InputDispatcher::isAppSwitchKeyEventLocked(KeyEntry* keyEntry) {
598 return ! (keyEntry->flags & AKEY_EVENT_FLAG_CANCELED)
599 && isAppSwitchKeyCode(keyEntry->keyCode)
Jeff Browne20c9e02010-10-11 14:20:19 -0700600 && (keyEntry->policyFlags & POLICY_FLAG_TRUSTED)
Jeff Brownb6997262010-10-08 22:31:17 -0700601 && (keyEntry->policyFlags & POLICY_FLAG_PASS_TO_USER);
602}
603
Jeff Brownb88102f2010-09-08 11:49:43 -0700604bool InputDispatcher::isAppSwitchPendingLocked() {
605 return mAppSwitchDueTime != LONG_LONG_MAX;
606}
607
Jeff Brownb88102f2010-09-08 11:49:43 -0700608void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
609 mAppSwitchDueTime = LONG_LONG_MAX;
610
611#if DEBUG_APP_SWITCH
612 if (handled) {
613 LOGD("App switch has arrived.");
614 } else {
615 LOGD("App switch was abandoned.");
616 }
617#endif
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700618}
619
Jeff Brown928e0542011-01-10 11:17:36 -0800620bool InputDispatcher::isStaleEventLocked(nsecs_t currentTime, EventEntry* entry) {
621 return currentTime - entry->eventTime >= STALE_EVENT_TIMEOUT;
622}
623
Jeff Brown9c3cda02010-06-15 01:31:58 -0700624bool InputDispatcher::runCommandsLockedInterruptible() {
625 if (mCommandQueue.isEmpty()) {
626 return false;
627 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700628
Jeff Brown9c3cda02010-06-15 01:31:58 -0700629 do {
630 CommandEntry* commandEntry = mCommandQueue.dequeueAtHead();
631
632 Command command = commandEntry->command;
633 (this->*command)(commandEntry); // commands are implicitly 'LockedInterruptible'
634
Jeff Brown7fbdc842010-06-17 20:52:56 -0700635 commandEntry->connection.clear();
Jeff Brownac386072011-07-20 15:19:50 -0700636 delete commandEntry;
Jeff Brown9c3cda02010-06-15 01:31:58 -0700637 } while (! mCommandQueue.isEmpty());
638 return true;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700639}
640
Jeff Brown9c3cda02010-06-15 01:31:58 -0700641InputDispatcher::CommandEntry* InputDispatcher::postCommandLocked(Command command) {
Jeff Brownac386072011-07-20 15:19:50 -0700642 CommandEntry* commandEntry = new CommandEntry(command);
Jeff Brown9c3cda02010-06-15 01:31:58 -0700643 mCommandQueue.enqueueAtTail(commandEntry);
644 return commandEntry;
645}
646
Jeff Brownb88102f2010-09-08 11:49:43 -0700647void InputDispatcher::drainInboundQueueLocked() {
648 while (! mInboundQueue.isEmpty()) {
649 EventEntry* entry = mInboundQueue.dequeueAtHead();
Jeff Brown54a18252010-09-16 14:07:33 -0700650 releaseInboundEventLocked(entry);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700651 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700652}
653
Jeff Brown54a18252010-09-16 14:07:33 -0700654void InputDispatcher::releasePendingEventLocked() {
Jeff Brownb88102f2010-09-08 11:49:43 -0700655 if (mPendingEvent) {
Jeff Brown54a18252010-09-16 14:07:33 -0700656 releaseInboundEventLocked(mPendingEvent);
Jeff Brownb88102f2010-09-08 11:49:43 -0700657 mPendingEvent = NULL;
658 }
659}
660
Jeff Brown54a18252010-09-16 14:07:33 -0700661void InputDispatcher::releaseInboundEventLocked(EventEntry* entry) {
Jeff Brown01ce2e92010-09-26 22:20:12 -0700662 InjectionState* injectionState = entry->injectionState;
663 if (injectionState && injectionState->injectionResult == INPUT_EVENT_INJECTION_PENDING) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700664#if DEBUG_DISPATCH_CYCLE
Jeff Brown01ce2e92010-09-26 22:20:12 -0700665 LOGD("Injected inbound event was dropped.");
Jeff Brownb88102f2010-09-08 11:49:43 -0700666#endif
667 setInjectionResultLocked(entry, INPUT_EVENT_INJECTION_FAILED);
668 }
Jeff Brownabb4d442011-08-15 12:55:32 -0700669 if (entry == mNextUnblockedEvent) {
670 mNextUnblockedEvent = NULL;
671 }
Jeff Brownac386072011-07-20 15:19:50 -0700672 entry->release();
Jeff Brownb88102f2010-09-08 11:49:43 -0700673}
674
Jeff Brownb88102f2010-09-08 11:49:43 -0700675void InputDispatcher::resetKeyRepeatLocked() {
676 if (mKeyRepeatState.lastKeyEntry) {
Jeff Brownac386072011-07-20 15:19:50 -0700677 mKeyRepeatState.lastKeyEntry->release();
Jeff Brownb88102f2010-09-08 11:49:43 -0700678 mKeyRepeatState.lastKeyEntry = NULL;
679 }
680}
681
Jeff Brown214eaf42011-05-26 19:17:02 -0700682InputDispatcher::KeyEntry* InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
Jeff Brown349703e2010-06-22 01:27:15 -0700683 KeyEntry* entry = mKeyRepeatState.lastKeyEntry;
684
Jeff Brown349703e2010-06-22 01:27:15 -0700685 // Reuse the repeated key entry if it is otherwise unreferenced.
Jeff Browne20c9e02010-10-11 14:20:19 -0700686 uint32_t policyFlags = (entry->policyFlags & POLICY_FLAG_RAW_MASK)
687 | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700688 if (entry->refCount == 1) {
Jeff Brownac386072011-07-20 15:19:50 -0700689 entry->recycle();
Jeff Brown7fbdc842010-06-17 20:52:56 -0700690 entry->eventTime = currentTime;
Jeff Brown7fbdc842010-06-17 20:52:56 -0700691 entry->policyFlags = policyFlags;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700692 entry->repeatCount += 1;
693 } else {
Jeff Brownac386072011-07-20 15:19:50 -0700694 KeyEntry* newEntry = new KeyEntry(currentTime,
Jeff Brownc5ed5912010-07-14 18:48:53 -0700695 entry->deviceId, entry->source, policyFlags,
Jeff Brown7fbdc842010-06-17 20:52:56 -0700696 entry->action, entry->flags, entry->keyCode, entry->scanCode,
Jeff Brown00fa7bd2010-07-02 15:37:36 -0700697 entry->metaState, entry->repeatCount + 1, entry->downTime);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700698
699 mKeyRepeatState.lastKeyEntry = newEntry;
Jeff Brownac386072011-07-20 15:19:50 -0700700 entry->release();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700701
702 entry = newEntry;
703 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700704 entry->syntheticRepeat = true;
705
706 // Increment reference count since we keep a reference to the event in
707 // mKeyRepeatState.lastKeyEntry in addition to the one we return.
708 entry->refCount += 1;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700709
Jeff Brown214eaf42011-05-26 19:17:02 -0700710 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Jeff Brownb88102f2010-09-08 11:49:43 -0700711 return entry;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700712}
713
Jeff Brownb88102f2010-09-08 11:49:43 -0700714bool InputDispatcher::dispatchConfigurationChangedLocked(
715 nsecs_t currentTime, ConfigurationChangedEntry* entry) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700716#if DEBUG_OUTBOUND_EVENT_DETAILS
Jeff Brownb88102f2010-09-08 11:49:43 -0700717 LOGD("dispatchConfigurationChanged - eventTime=%lld", entry->eventTime);
718#endif
719
720 // Reset key repeating in case a keyboard device was added or removed or something.
721 resetKeyRepeatLocked();
722
723 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
724 CommandEntry* commandEntry = postCommandLocked(
725 & InputDispatcher::doNotifyConfigurationChangedInterruptible);
726 commandEntry->eventTime = entry->eventTime;
727 return true;
728}
729
Jeff Brown214eaf42011-05-26 19:17:02 -0700730bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, KeyEntry* entry,
Jeff Browne20c9e02010-10-11 14:20:19 -0700731 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Jeff Browne46a0a42010-11-02 17:58:22 -0700732 // Preprocessing.
733 if (! entry->dispatchInProgress) {
734 if (entry->repeatCount == 0
735 && entry->action == AKEY_EVENT_ACTION_DOWN
736 && (entry->policyFlags & POLICY_FLAG_TRUSTED)
Jeff Brown0029c662011-03-30 02:25:18 -0700737 && (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
Jeff Browne46a0a42010-11-02 17:58:22 -0700738 if (mKeyRepeatState.lastKeyEntry
739 && mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode) {
740 // We have seen two identical key downs in a row which indicates that the device
741 // driver is automatically generating key repeats itself. We take note of the
742 // repeat here, but we disable our own next key repeat timer since it is clear that
743 // we will not need to synthesize key repeats ourselves.
744 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
745 resetKeyRepeatLocked();
746 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
747 } else {
748 // Not a repeat. Save key down state in case we do see a repeat later.
749 resetKeyRepeatLocked();
Jeff Brown214eaf42011-05-26 19:17:02 -0700750 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
Jeff Browne46a0a42010-11-02 17:58:22 -0700751 }
752 mKeyRepeatState.lastKeyEntry = entry;
753 entry->refCount += 1;
754 } else if (! entry->syntheticRepeat) {
755 resetKeyRepeatLocked();
756 }
757
Jeff Browne2e01262011-03-02 20:34:30 -0800758 if (entry->repeatCount == 1) {
759 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
760 } else {
761 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
762 }
763
Jeff Browne46a0a42010-11-02 17:58:22 -0700764 entry->dispatchInProgress = true;
765 resetTargetsLocked();
766
767 logOutboundKeyDetailsLocked("dispatchKey - ", entry);
768 }
769
Jeff Brown54a18252010-09-16 14:07:33 -0700770 // Give the policy a chance to intercept the key.
771 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
Jeff Browne20c9e02010-10-11 14:20:19 -0700772 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Jeff Brown54a18252010-09-16 14:07:33 -0700773 CommandEntry* commandEntry = postCommandLocked(
774 & InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
Jeff Brown9302c872011-07-13 22:51:29 -0700775 if (mFocusedWindowHandle != NULL) {
776 commandEntry->inputWindowHandle = mFocusedWindowHandle;
Jeff Brown54a18252010-09-16 14:07:33 -0700777 }
778 commandEntry->keyEntry = entry;
779 entry->refCount += 1;
780 return false; // wait for the command to run
781 } else {
782 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
783 }
784 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Jeff Browne20c9e02010-10-11 14:20:19 -0700785 if (*dropReason == DROP_REASON_NOT_DROPPED) {
786 *dropReason = DROP_REASON_POLICY;
787 }
Jeff Brown54a18252010-09-16 14:07:33 -0700788 }
789
790 // Clean up if dropping the event.
Jeff Browne20c9e02010-10-11 14:20:19 -0700791 if (*dropReason != DROP_REASON_NOT_DROPPED) {
Jeff Brown54a18252010-09-16 14:07:33 -0700792 resetTargetsLocked();
Jeff Brown3122e442010-10-11 23:32:49 -0700793 setInjectionResultLocked(entry, *dropReason == DROP_REASON_POLICY
794 ? INPUT_EVENT_INJECTION_SUCCEEDED : INPUT_EVENT_INJECTION_FAILED);
Jeff Brown54a18252010-09-16 14:07:33 -0700795 return true;
796 }
797
Jeff Brownb88102f2010-09-08 11:49:43 -0700798 // Identify targets.
799 if (! mCurrentInputTargetsValid) {
Jeff Brown01ce2e92010-09-26 22:20:12 -0700800 int32_t injectionResult = findFocusedWindowTargetsLocked(currentTime,
801 entry, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700802 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
803 return false;
804 }
805
806 setInjectionResultLocked(entry, injectionResult);
807 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
808 return true;
809 }
810
811 addMonitoringTargetsLocked();
Jeff Brown01ce2e92010-09-26 22:20:12 -0700812 commitTargetsLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -0700813 }
814
815 // Dispatch the key.
816 dispatchEventToCurrentInputTargetsLocked(currentTime, entry, false);
Jeff Brownb88102f2010-09-08 11:49:43 -0700817 return true;
818}
819
820void InputDispatcher::logOutboundKeyDetailsLocked(const char* prefix, const KeyEntry* entry) {
821#if DEBUG_OUTBOUND_EVENT_DETAILS
Jeff Brown90655042010-12-02 13:50:46 -0800822 LOGD("%seventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, "
Jeff Brownb88102f2010-09-08 11:49:43 -0700823 "action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, "
Jeff Browne46a0a42010-11-02 17:58:22 -0700824 "repeatCount=%d, downTime=%lld",
Jeff Brownb88102f2010-09-08 11:49:43 -0700825 prefix,
826 entry->eventTime, entry->deviceId, entry->source, entry->policyFlags,
827 entry->action, entry->flags, entry->keyCode, entry->scanCode, entry->metaState,
Jeff Browne46a0a42010-11-02 17:58:22 -0700828 entry->repeatCount, entry->downTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700829#endif
830}
831
832bool InputDispatcher::dispatchMotionLocked(
Jeff Browne20c9e02010-10-11 14:20:19 -0700833 nsecs_t currentTime, MotionEntry* entry, DropReason* dropReason, nsecs_t* nextWakeupTime) {
Jeff Browne46a0a42010-11-02 17:58:22 -0700834 // Preprocessing.
835 if (! entry->dispatchInProgress) {
836 entry->dispatchInProgress = true;
837 resetTargetsLocked();
838
839 logOutboundMotionDetailsLocked("dispatchMotion - ", entry);
840 }
841
Jeff Brown54a18252010-09-16 14:07:33 -0700842 // Clean up if dropping the event.
Jeff Browne20c9e02010-10-11 14:20:19 -0700843 if (*dropReason != DROP_REASON_NOT_DROPPED) {
Jeff Brown54a18252010-09-16 14:07:33 -0700844 resetTargetsLocked();
Jeff Brown3122e442010-10-11 23:32:49 -0700845 setInjectionResultLocked(entry, *dropReason == DROP_REASON_POLICY
846 ? INPUT_EVENT_INJECTION_SUCCEEDED : INPUT_EVENT_INJECTION_FAILED);
Jeff Brown54a18252010-09-16 14:07:33 -0700847 return true;
848 }
849
Jeff Brownb88102f2010-09-08 11:49:43 -0700850 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
851
852 // Identify targets.
Jeff Browncc0c1592011-02-19 05:07:28 -0800853 bool conflictingPointerActions = false;
Jeff Brownb88102f2010-09-08 11:49:43 -0700854 if (! mCurrentInputTargetsValid) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700855 int32_t injectionResult;
Jeff Browna032cc02011-03-07 16:56:21 -0800856 const MotionSample* splitBatchAfterSample = NULL;
Jeff Brownb88102f2010-09-08 11:49:43 -0700857 if (isPointerEvent) {
858 // Pointer event. (eg. touchscreen)
Jeff Brown01ce2e92010-09-26 22:20:12 -0700859 injectionResult = findTouchedWindowTargetsLocked(currentTime,
Jeff Browna032cc02011-03-07 16:56:21 -0800860 entry, nextWakeupTime, &conflictingPointerActions, &splitBatchAfterSample);
Jeff Brownb88102f2010-09-08 11:49:43 -0700861 } else {
862 // Non touch event. (eg. trackball)
Jeff Brown01ce2e92010-09-26 22:20:12 -0700863 injectionResult = findFocusedWindowTargetsLocked(currentTime,
864 entry, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700865 }
866 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
867 return false;
868 }
869
870 setInjectionResultLocked(entry, injectionResult);
871 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
872 return true;
873 }
874
875 addMonitoringTargetsLocked();
Jeff Brown01ce2e92010-09-26 22:20:12 -0700876 commitTargetsLocked();
Jeff Browna032cc02011-03-07 16:56:21 -0800877
878 // Unbatch the event if necessary by splitting it into two parts after the
879 // motion sample indicated by splitBatchAfterSample.
880 if (splitBatchAfterSample && splitBatchAfterSample->next) {
881#if DEBUG_BATCHING
882 uint32_t originalSampleCount = entry->countSamples();
883#endif
884 MotionSample* nextSample = splitBatchAfterSample->next;
Jeff Brownac386072011-07-20 15:19:50 -0700885 MotionEntry* nextEntry = new MotionEntry(nextSample->eventTime,
Jeff Browna032cc02011-03-07 16:56:21 -0800886 entry->deviceId, entry->source, entry->policyFlags,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700887 entry->action, entry->flags,
888 entry->metaState, entry->buttonState, entry->edgeFlags,
Jeff Browna032cc02011-03-07 16:56:21 -0800889 entry->xPrecision, entry->yPrecision, entry->downTime,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700890 entry->pointerCount, entry->pointerProperties, nextSample->pointerCoords);
Jeff Browna032cc02011-03-07 16:56:21 -0800891 if (nextSample != entry->lastSample) {
892 nextEntry->firstSample.next = nextSample->next;
893 nextEntry->lastSample = entry->lastSample;
894 }
Jeff Brownac386072011-07-20 15:19:50 -0700895 delete nextSample;
Jeff Browna032cc02011-03-07 16:56:21 -0800896
897 entry->lastSample = const_cast<MotionSample*>(splitBatchAfterSample);
898 entry->lastSample->next = NULL;
899
900 if (entry->injectionState) {
901 nextEntry->injectionState = entry->injectionState;
902 entry->injectionState->refCount += 1;
903 }
904
905#if DEBUG_BATCHING
906 LOGD("Split batch of %d samples into two parts, first part has %d samples, "
907 "second part has %d samples.", originalSampleCount,
908 entry->countSamples(), nextEntry->countSamples());
909#endif
910
911 mInboundQueue.enqueueAtHead(nextEntry);
912 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700913 }
914
915 // Dispatch the motion.
Jeff Browncc0c1592011-02-19 05:07:28 -0800916 if (conflictingPointerActions) {
Jeff Brownda3d5a92011-03-29 15:11:34 -0700917 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
918 "conflicting pointer actions");
919 synthesizeCancelationEventsForAllConnectionsLocked(options);
Jeff Browncc0c1592011-02-19 05:07:28 -0800920 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700921 dispatchEventToCurrentInputTargetsLocked(currentTime, entry, false);
Jeff Brownb88102f2010-09-08 11:49:43 -0700922 return true;
923}
924
925
926void InputDispatcher::logOutboundMotionDetailsLocked(const char* prefix, const MotionEntry* entry) {
927#if DEBUG_OUTBOUND_EVENT_DETAILS
Jeff Brown90655042010-12-02 13:50:46 -0800928 LOGD("%seventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, "
Jeff Brown85a31762010-09-01 17:01:00 -0700929 "action=0x%x, flags=0x%x, "
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700930 "metaState=0x%x, buttonState=0x%x, "
931 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%lld",
Jeff Brownb88102f2010-09-08 11:49:43 -0700932 prefix,
Jeff Brown85a31762010-09-01 17:01:00 -0700933 entry->eventTime, entry->deviceId, entry->source, entry->policyFlags,
934 entry->action, entry->flags,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700935 entry->metaState, entry->buttonState,
936 entry->edgeFlags, entry->xPrecision, entry->yPrecision,
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700937 entry->downTime);
938
939 // Print the most recent sample that we have available, this may change due to batching.
940 size_t sampleCount = 1;
Jeff Brownb88102f2010-09-08 11:49:43 -0700941 const MotionSample* sample = & entry->firstSample;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700942 for (; sample->next != NULL; sample = sample->next) {
943 sampleCount += 1;
944 }
945 for (uint32_t i = 0; i < entry->pointerCount; i++) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700946 LOGD(" Pointer %d: id=%d, toolType=%d, "
947 "x=%f, y=%f, pressure=%f, size=%f, "
Jeff Brown85a31762010-09-01 17:01:00 -0700948 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
Jeff Brown8d608662010-08-30 03:02:23 -0700949 "orientation=%f",
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700950 i, entry->pointerProperties[i].id,
951 entry->pointerProperties[i].toolType,
Jeff Brownebbd5d12011-02-17 13:01:34 -0800952 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
953 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
954 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
955 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
956 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
957 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
958 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
959 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
960 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700961 }
962
963 // Keep in mind that due to batching, it is possible for the number of samples actually
964 // dispatched to change before the application finally consumed them.
Jeff Brownc5ed5912010-07-14 18:48:53 -0700965 if (entry->action == AMOTION_EVENT_ACTION_MOVE) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700966 LOGD(" ... Total movement samples currently batched %d ...", sampleCount);
967 }
968#endif
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700969}
970
971void InputDispatcher::dispatchEventToCurrentInputTargetsLocked(nsecs_t currentTime,
972 EventEntry* eventEntry, bool resumeWithAppendedMotionSample) {
973#if DEBUG_DISPATCH_CYCLE
Jeff Brown9c3cda02010-06-15 01:31:58 -0700974 LOGD("dispatchEventToCurrentInputTargets - "
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700975 "resumeWithAppendedMotionSample=%s",
Jeff Brownb88102f2010-09-08 11:49:43 -0700976 toString(resumeWithAppendedMotionSample));
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700977#endif
978
Jeff Brownb6110c22011-04-01 16:15:13 -0700979 LOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
Jeff Brown9c3cda02010-06-15 01:31:58 -0700980
Jeff Browne2fe69e2010-10-18 13:21:23 -0700981 pokeUserActivityLocked(eventEntry);
982
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700983 for (size_t i = 0; i < mCurrentInputTargets.size(); i++) {
984 const InputTarget& inputTarget = mCurrentInputTargets.itemAt(i);
985
Jeff Brown519e0242010-09-15 15:18:56 -0700986 ssize_t connectionIndex = getConnectionIndexLocked(inputTarget.inputChannel);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700987 if (connectionIndex >= 0) {
988 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
Jeff Brown7fbdc842010-06-17 20:52:56 -0700989 prepareDispatchCycleLocked(currentTime, connection, eventEntry, & inputTarget,
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700990 resumeWithAppendedMotionSample);
991 } else {
Jeff Brownb6997262010-10-08 22:31:17 -0700992#if DEBUG_FOCUS
993 LOGD("Dropping event delivery to target with channel '%s' because it "
994 "is no longer registered with the input dispatcher.",
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700995 inputTarget.inputChannel->getName().string());
Jeff Brownb6997262010-10-08 22:31:17 -0700996#endif
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700997 }
998 }
999}
1000
Jeff Brown54a18252010-09-16 14:07:33 -07001001void InputDispatcher::resetTargetsLocked() {
Jeff Brownb88102f2010-09-08 11:49:43 -07001002 mCurrentInputTargetsValid = false;
1003 mCurrentInputTargets.clear();
Jeff Brown5ea29ab2011-07-27 11:50:51 -07001004 resetANRTimeoutsLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -07001005}
1006
Jeff Brown01ce2e92010-09-26 22:20:12 -07001007void InputDispatcher::commitTargetsLocked() {
Jeff Brownb88102f2010-09-08 11:49:43 -07001008 mCurrentInputTargetsValid = true;
1009}
1010
1011int32_t InputDispatcher::handleTargetsNotReadyLocked(nsecs_t currentTime,
Jeff Brown9302c872011-07-13 22:51:29 -07001012 const EventEntry* entry,
1013 const sp<InputApplicationHandle>& applicationHandle,
1014 const sp<InputWindowHandle>& windowHandle,
Jeff Brownb88102f2010-09-08 11:49:43 -07001015 nsecs_t* nextWakeupTime) {
Jeff Brown9302c872011-07-13 22:51:29 -07001016 if (applicationHandle == NULL && windowHandle == NULL) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001017 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY) {
1018#if DEBUG_FOCUS
1019 LOGD("Waiting for system to become ready for input.");
1020#endif
1021 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY;
1022 mInputTargetWaitStartTime = currentTime;
1023 mInputTargetWaitTimeoutTime = LONG_LONG_MAX;
1024 mInputTargetWaitTimeoutExpired = false;
Jeff Brown9302c872011-07-13 22:51:29 -07001025 mInputTargetWaitApplicationHandle.clear();
Jeff Brownb88102f2010-09-08 11:49:43 -07001026 }
1027 } else {
1028 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
1029#if DEBUG_FOCUS
Jeff Brown519e0242010-09-15 15:18:56 -07001030 LOGD("Waiting for application to become ready for input: %s",
Jeff Brown9302c872011-07-13 22:51:29 -07001031 getApplicationWindowLabelLocked(applicationHandle, windowHandle).string());
Jeff Brownb88102f2010-09-08 11:49:43 -07001032#endif
Jeff Brown9302c872011-07-13 22:51:29 -07001033 nsecs_t timeout = windowHandle != NULL ? windowHandle->dispatchingTimeout :
1034 applicationHandle != NULL ?
1035 applicationHandle->dispatchingTimeout : DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Jeff Brownb88102f2010-09-08 11:49:43 -07001036
1037 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY;
1038 mInputTargetWaitStartTime = currentTime;
1039 mInputTargetWaitTimeoutTime = currentTime + timeout;
1040 mInputTargetWaitTimeoutExpired = false;
Jeff Brown9302c872011-07-13 22:51:29 -07001041 mInputTargetWaitApplicationHandle.clear();
Jeff Brown928e0542011-01-10 11:17:36 -08001042
Jeff Brown9302c872011-07-13 22:51:29 -07001043 if (windowHandle != NULL) {
1044 mInputTargetWaitApplicationHandle = windowHandle->inputApplicationHandle;
Jeff Brown928e0542011-01-10 11:17:36 -08001045 }
Jeff Brown9302c872011-07-13 22:51:29 -07001046 if (mInputTargetWaitApplicationHandle == NULL && applicationHandle != NULL) {
1047 mInputTargetWaitApplicationHandle = applicationHandle;
Jeff Brown928e0542011-01-10 11:17:36 -08001048 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001049 }
1050 }
1051
1052 if (mInputTargetWaitTimeoutExpired) {
1053 return INPUT_EVENT_INJECTION_TIMED_OUT;
1054 }
1055
1056 if (currentTime >= mInputTargetWaitTimeoutTime) {
Jeff Brown9302c872011-07-13 22:51:29 -07001057 onANRLocked(currentTime, applicationHandle, windowHandle,
1058 entry->eventTime, mInputTargetWaitStartTime);
Jeff Brownb88102f2010-09-08 11:49:43 -07001059
1060 // Force poll loop to wake up immediately on next iteration once we get the
1061 // ANR response back from the policy.
1062 *nextWakeupTime = LONG_LONG_MIN;
1063 return INPUT_EVENT_INJECTION_PENDING;
1064 } else {
1065 // Force poll loop to wake up when timeout is due.
1066 if (mInputTargetWaitTimeoutTime < *nextWakeupTime) {
1067 *nextWakeupTime = mInputTargetWaitTimeoutTime;
1068 }
1069 return INPUT_EVENT_INJECTION_PENDING;
1070 }
1071}
1072
Jeff Brown519e0242010-09-15 15:18:56 -07001073void InputDispatcher::resumeAfterTargetsNotReadyTimeoutLocked(nsecs_t newTimeout,
1074 const sp<InputChannel>& inputChannel) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001075 if (newTimeout > 0) {
1076 // Extend the timeout.
1077 mInputTargetWaitTimeoutTime = now() + newTimeout;
1078 } else {
1079 // Give up.
1080 mInputTargetWaitTimeoutExpired = true;
Jeff Brown519e0242010-09-15 15:18:56 -07001081
Jeff Brown01ce2e92010-09-26 22:20:12 -07001082 // Release the touch targets.
1083 mTouchState.reset();
Jeff Brown2a95c2a2010-09-16 12:31:46 -07001084
Jeff Brown519e0242010-09-15 15:18:56 -07001085 // Input state will not be realistic. Mark it out of sync.
Jeff Browndc3e0052010-09-16 11:02:16 -07001086 if (inputChannel.get()) {
1087 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
1088 if (connectionIndex >= 0) {
1089 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
Jeff Brown00045a72010-12-09 18:10:30 -08001090 if (connection->status == Connection::STATUS_NORMAL) {
Jeff Brownda3d5a92011-03-29 15:11:34 -07001091 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
Jeff Brown00045a72010-12-09 18:10:30 -08001092 "application not responding");
Jeff Brownda3d5a92011-03-29 15:11:34 -07001093 synthesizeCancelationEventsForConnectionLocked(connection, options);
Jeff Brown00045a72010-12-09 18:10:30 -08001094 }
Jeff Browndc3e0052010-09-16 11:02:16 -07001095 }
Jeff Brown519e0242010-09-15 15:18:56 -07001096 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001097 }
1098}
1099
Jeff Brown519e0242010-09-15 15:18:56 -07001100nsecs_t InputDispatcher::getTimeSpentWaitingForApplicationLocked(
Jeff Brownb88102f2010-09-08 11:49:43 -07001101 nsecs_t currentTime) {
1102 if (mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
1103 return currentTime - mInputTargetWaitStartTime;
1104 }
1105 return 0;
1106}
1107
1108void InputDispatcher::resetANRTimeoutsLocked() {
1109#if DEBUG_FOCUS
1110 LOGD("Resetting ANR timeouts.");
1111#endif
1112
Jeff Brownb88102f2010-09-08 11:49:43 -07001113 // Reset input target wait timeout.
1114 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_NONE;
Jeff Brown5ea29ab2011-07-27 11:50:51 -07001115 mInputTargetWaitApplicationHandle.clear();
Jeff Brownb88102f2010-09-08 11:49:43 -07001116}
1117
Jeff Brown01ce2e92010-09-26 22:20:12 -07001118int32_t InputDispatcher::findFocusedWindowTargetsLocked(nsecs_t currentTime,
1119 const EventEntry* entry, nsecs_t* nextWakeupTime) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001120 mCurrentInputTargets.clear();
1121
1122 int32_t injectionResult;
1123
1124 // If there is no currently focused window and no focused application
1125 // then drop the event.
Jeff Brown9302c872011-07-13 22:51:29 -07001126 if (mFocusedWindowHandle == NULL) {
1127 if (mFocusedApplicationHandle != NULL) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001128#if DEBUG_FOCUS
1129 LOGD("Waiting because there is no focused window but there is a "
Jeff Brown519e0242010-09-15 15:18:56 -07001130 "focused application that may eventually add a window: %s.",
Jeff Brown9302c872011-07-13 22:51:29 -07001131 getApplicationWindowLabelLocked(mFocusedApplicationHandle, NULL).string());
Jeff Brownb88102f2010-09-08 11:49:43 -07001132#endif
1133 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brown9302c872011-07-13 22:51:29 -07001134 mFocusedApplicationHandle, NULL, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -07001135 goto Unresponsive;
1136 }
1137
1138 LOGI("Dropping event because there is no focused window or focused application.");
1139 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1140 goto Failed;
1141 }
1142
1143 // Check permissions.
Jeff Brown9302c872011-07-13 22:51:29 -07001144 if (! checkInjectionPermission(mFocusedWindowHandle, entry->injectionState)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001145 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1146 goto Failed;
1147 }
1148
1149 // If the currently focused window is paused then keep waiting.
Jeff Brown9302c872011-07-13 22:51:29 -07001150 if (mFocusedWindowHandle->paused) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001151#if DEBUG_FOCUS
1152 LOGD("Waiting because focused window is paused.");
1153#endif
1154 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brown9302c872011-07-13 22:51:29 -07001155 mFocusedApplicationHandle, mFocusedWindowHandle, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -07001156 goto Unresponsive;
1157 }
1158
Jeff Brown519e0242010-09-15 15:18:56 -07001159 // If the currently focused window is still working on previous events then keep waiting.
Jeff Brown9302c872011-07-13 22:51:29 -07001160 if (! isWindowFinishedWithPreviousInputLocked(mFocusedWindowHandle)) {
Jeff Brown519e0242010-09-15 15:18:56 -07001161#if DEBUG_FOCUS
1162 LOGD("Waiting because focused window still processing previous input.");
1163#endif
1164 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brown9302c872011-07-13 22:51:29 -07001165 mFocusedApplicationHandle, mFocusedWindowHandle, nextWakeupTime);
Jeff Brown519e0242010-09-15 15:18:56 -07001166 goto Unresponsive;
1167 }
1168
Jeff Brownb88102f2010-09-08 11:49:43 -07001169 // Success! Output targets.
1170 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
Jeff Brown9302c872011-07-13 22:51:29 -07001171 addWindowTargetLocked(mFocusedWindowHandle,
Jeff Browna032cc02011-03-07 16:56:21 -08001172 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS, BitSet32(0));
Jeff Brownb88102f2010-09-08 11:49:43 -07001173
1174 // Done.
1175Failed:
1176Unresponsive:
Jeff Brown519e0242010-09-15 15:18:56 -07001177 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
1178 updateDispatchStatisticsLocked(currentTime, entry,
1179 injectionResult, timeSpentWaitingForApplication);
Jeff Brownb88102f2010-09-08 11:49:43 -07001180#if DEBUG_FOCUS
Jeff Brown519e0242010-09-15 15:18:56 -07001181 LOGD("findFocusedWindow finished: injectionResult=%d, "
1182 "timeSpendWaitingForApplication=%0.1fms",
1183 injectionResult, timeSpentWaitingForApplication / 1000000.0);
Jeff Brownb88102f2010-09-08 11:49:43 -07001184#endif
1185 return injectionResult;
1186}
1187
Jeff Brown01ce2e92010-09-26 22:20:12 -07001188int32_t InputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime,
Jeff Browna032cc02011-03-07 16:56:21 -08001189 const MotionEntry* entry, nsecs_t* nextWakeupTime, bool* outConflictingPointerActions,
1190 const MotionSample** outSplitBatchAfterSample) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001191 enum InjectionPermission {
1192 INJECTION_PERMISSION_UNKNOWN,
1193 INJECTION_PERMISSION_GRANTED,
1194 INJECTION_PERMISSION_DENIED
1195 };
1196
Jeff Brownb88102f2010-09-08 11:49:43 -07001197 mCurrentInputTargets.clear();
1198
1199 nsecs_t startTime = now();
1200
1201 // For security reasons, we defer updating the touch state until we are sure that
1202 // event injection will be allowed.
1203 //
1204 // FIXME In the original code, screenWasOff could never be set to true.
1205 // The reason is that the POLICY_FLAG_WOKE_HERE
1206 // and POLICY_FLAG_BRIGHT_HERE flags were set only when preprocessing raw
1207 // EV_KEY, EV_REL and EV_ABS events. As it happens, the touch event was
1208 // actually enqueued using the policyFlags that appeared in the final EV_SYN
1209 // events upon which no preprocessing took place. So policyFlags was always 0.
1210 // In the new native input dispatcher we're a bit more careful about event
1211 // preprocessing so the touches we receive can actually have non-zero policyFlags.
1212 // Unfortunately we obtain undesirable behavior.
1213 //
1214 // Here's what happens:
1215 //
1216 // When the device dims in anticipation of going to sleep, touches
1217 // in windows which have FLAG_TOUCHABLE_WHEN_WAKING cause
1218 // the device to brighten and reset the user activity timer.
1219 // Touches on other windows (such as the launcher window)
1220 // are dropped. Then after a moment, the device goes to sleep. Oops.
1221 //
1222 // Also notice how screenWasOff was being initialized using POLICY_FLAG_BRIGHT_HERE
1223 // instead of POLICY_FLAG_WOKE_HERE...
1224 //
1225 bool screenWasOff = false; // original policy: policyFlags & POLICY_FLAG_BRIGHT_HERE;
1226
1227 int32_t action = entry->action;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001228 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Jeff Brownb88102f2010-09-08 11:49:43 -07001229
1230 // Update the touch state as needed based on the properties of the touch event.
Jeff Brown01ce2e92010-09-26 22:20:12 -07001231 int32_t injectionResult = INPUT_EVENT_INJECTION_PENDING;
1232 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
Jeff Brown9302c872011-07-13 22:51:29 -07001233 sp<InputWindowHandle> newHoverWindowHandle;
Jeff Browncc0c1592011-02-19 05:07:28 -08001234
1235 bool isSplit = mTouchState.split;
Jeff Brown2717eff2011-06-30 23:53:07 -07001236 bool switchedDevice = mTouchState.deviceId >= 0
1237 && (mTouchState.deviceId != entry->deviceId
1238 || mTouchState.source != entry->source);
Jeff Browna032cc02011-03-07 16:56:21 -08001239 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE
1240 || maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER
1241 || maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1242 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN
1243 || maskedAction == AMOTION_EVENT_ACTION_SCROLL
1244 || isHoverAction);
Jeff Brown81346812011-06-28 20:08:48 -07001245 bool wrongDevice = false;
Jeff Browna032cc02011-03-07 16:56:21 -08001246 if (newGesture) {
Jeff Browncc0c1592011-02-19 05:07:28 -08001247 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Jeff Brown81346812011-06-28 20:08:48 -07001248 if (switchedDevice && mTouchState.down && !down) {
1249#if DEBUG_FOCUS
1250 LOGD("Dropping event because a pointer for a different device is already down.");
1251#endif
Jeff Browncc0c1592011-02-19 05:07:28 -08001252 mTempTouchState.copyFrom(mTouchState);
Jeff Brown81346812011-06-28 20:08:48 -07001253 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1254 switchedDevice = false;
1255 wrongDevice = true;
1256 goto Failed;
Jeff Browncc0c1592011-02-19 05:07:28 -08001257 }
Jeff Brown81346812011-06-28 20:08:48 -07001258 mTempTouchState.reset();
1259 mTempTouchState.down = down;
1260 mTempTouchState.deviceId = entry->deviceId;
1261 mTempTouchState.source = entry->source;
1262 isSplit = false;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001263 } else {
1264 mTempTouchState.copyFrom(mTouchState);
Jeff Browncc0c1592011-02-19 05:07:28 -08001265 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001266
Jeff Browna032cc02011-03-07 16:56:21 -08001267 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
Jeff Brown33bbfd22011-02-24 20:55:35 -08001268 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
Jeff Brownb88102f2010-09-08 11:49:43 -07001269
Jeff Browna032cc02011-03-07 16:56:21 -08001270 const MotionSample* sample = &entry->firstSample;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001271 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Jeff Browna032cc02011-03-07 16:56:21 -08001272 int32_t x = int32_t(sample->pointerCoords[pointerIndex].
Jeff Brownebbd5d12011-02-17 13:01:34 -08001273 getAxisValue(AMOTION_EVENT_AXIS_X));
Jeff Browna032cc02011-03-07 16:56:21 -08001274 int32_t y = int32_t(sample->pointerCoords[pointerIndex].
Jeff Brownebbd5d12011-02-17 13:01:34 -08001275 getAxisValue(AMOTION_EVENT_AXIS_Y));
Jeff Brown9302c872011-07-13 22:51:29 -07001276 sp<InputWindowHandle> newTouchedWindowHandle;
1277 sp<InputWindowHandle> topErrorWindowHandle;
Jeff Browna032cc02011-03-07 16:56:21 -08001278 bool isTouchModal = false;
Jeff Brownb88102f2010-09-08 11:49:43 -07001279
1280 // Traverse windows from front to back to find touched window and outside targets.
Jeff Brown9302c872011-07-13 22:51:29 -07001281 size_t numWindows = mWindowHandles.size();
Jeff Brownb88102f2010-09-08 11:49:43 -07001282 for (size_t i = 0; i < numWindows; i++) {
Jeff Brown9302c872011-07-13 22:51:29 -07001283 sp<InputWindowHandle> windowHandle = mWindowHandles.itemAt(i);
1284 int32_t flags = windowHandle->layoutParamsFlags;
Jeff Brownb88102f2010-09-08 11:49:43 -07001285
Jeff Brown9302c872011-07-13 22:51:29 -07001286 if (flags & InputWindowHandle::FLAG_SYSTEM_ERROR) {
1287 if (topErrorWindowHandle == NULL) {
1288 topErrorWindowHandle = windowHandle;
Jeff Brownb88102f2010-09-08 11:49:43 -07001289 }
1290 }
1291
Jeff Brown9302c872011-07-13 22:51:29 -07001292 if (windowHandle->visible) {
1293 if (! (flags & InputWindowHandle::FLAG_NOT_TOUCHABLE)) {
1294 isTouchModal = (flags & (InputWindowHandle::FLAG_NOT_FOCUSABLE
1295 | InputWindowHandle::FLAG_NOT_TOUCH_MODAL)) == 0;
1296 if (isTouchModal || windowHandle->touchableRegionContainsPoint(x, y)) {
1297 if (! screenWasOff
1298 || (flags & InputWindowHandle::FLAG_TOUCHABLE_WHEN_WAKING)) {
1299 newTouchedWindowHandle = windowHandle;
Jeff Brownb88102f2010-09-08 11:49:43 -07001300 }
1301 break; // found touched window, exit window loop
1302 }
1303 }
1304
Jeff Brown01ce2e92010-09-26 22:20:12 -07001305 if (maskedAction == AMOTION_EVENT_ACTION_DOWN
Jeff Brown9302c872011-07-13 22:51:29 -07001306 && (flags & InputWindowHandle::FLAG_WATCH_OUTSIDE_TOUCH)) {
Jeff Browna032cc02011-03-07 16:56:21 -08001307 int32_t outsideTargetFlags = InputTarget::FLAG_DISPATCH_AS_OUTSIDE;
Jeff Brown9302c872011-07-13 22:51:29 -07001308 if (isWindowObscuredAtPointLocked(windowHandle, x, y)) {
Jeff Brown19dfc832010-10-05 12:26:23 -07001309 outsideTargetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1310 }
1311
Jeff Brown9302c872011-07-13 22:51:29 -07001312 mTempTouchState.addOrUpdateWindow(
1313 windowHandle, outsideTargetFlags, BitSet32(0));
Jeff Brownb88102f2010-09-08 11:49:43 -07001314 }
1315 }
1316 }
1317
1318 // If there is an error window but it is not taking focus (typically because
1319 // it is invisible) then wait for it. Any other focused window may in
1320 // fact be in ANR state.
Jeff Brown9302c872011-07-13 22:51:29 -07001321 if (topErrorWindowHandle != NULL && newTouchedWindowHandle != topErrorWindowHandle) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001322#if DEBUG_FOCUS
1323 LOGD("Waiting because system error window is pending.");
1324#endif
1325 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
1326 NULL, NULL, nextWakeupTime);
1327 injectionPermission = INJECTION_PERMISSION_UNKNOWN;
1328 goto Unresponsive;
1329 }
1330
Jeff Brown01ce2e92010-09-26 22:20:12 -07001331 // Figure out whether splitting will be allowed for this window.
Jeff Brown9302c872011-07-13 22:51:29 -07001332 if (newTouchedWindowHandle != NULL && newTouchedWindowHandle->supportsSplitTouch()) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001333 // New window supports splitting.
1334 isSplit = true;
1335 } else if (isSplit) {
1336 // New window does not support splitting but we have already split events.
1337 // Assign the pointer to the first foreground window we find.
1338 // (May be NULL which is why we put this code block before the next check.)
Jeff Brown9302c872011-07-13 22:51:29 -07001339 newTouchedWindowHandle = mTempTouchState.getFirstForegroundWindowHandle();
Jeff Brown01ce2e92010-09-26 22:20:12 -07001340 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001341
Jeff Brownb88102f2010-09-08 11:49:43 -07001342 // If we did not find a touched window then fail.
Jeff Brown9302c872011-07-13 22:51:29 -07001343 if (newTouchedWindowHandle == NULL) {
1344 if (mFocusedApplicationHandle != NULL) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001345#if DEBUG_FOCUS
1346 LOGD("Waiting because there is no touched window but there is a "
Jeff Brown519e0242010-09-15 15:18:56 -07001347 "focused application that may eventually add a new window: %s.",
Jeff Brown9302c872011-07-13 22:51:29 -07001348 getApplicationWindowLabelLocked(mFocusedApplicationHandle, NULL).string());
Jeff Brownb88102f2010-09-08 11:49:43 -07001349#endif
1350 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brown9302c872011-07-13 22:51:29 -07001351 mFocusedApplicationHandle, NULL, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -07001352 goto Unresponsive;
1353 }
1354
1355 LOGI("Dropping event because there is no touched window or focused application.");
1356 injectionResult = INPUT_EVENT_INJECTION_FAILED;
Jeff Brownb88102f2010-09-08 11:49:43 -07001357 goto Failed;
1358 }
1359
Jeff Brown19dfc832010-10-05 12:26:23 -07001360 // Set target flags.
Jeff Browna032cc02011-03-07 16:56:21 -08001361 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
Jeff Brown19dfc832010-10-05 12:26:23 -07001362 if (isSplit) {
1363 targetFlags |= InputTarget::FLAG_SPLIT;
1364 }
Jeff Brown9302c872011-07-13 22:51:29 -07001365 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
Jeff Brown19dfc832010-10-05 12:26:23 -07001366 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1367 }
1368
Jeff Browna032cc02011-03-07 16:56:21 -08001369 // Update hover state.
1370 if (isHoverAction) {
Jeff Brown9302c872011-07-13 22:51:29 -07001371 newHoverWindowHandle = newTouchedWindowHandle;
Jeff Browna032cc02011-03-07 16:56:21 -08001372
1373 // Ensure all subsequent motion samples are also within the touched window.
1374 // Set *outSplitBatchAfterSample to the sample before the first one that is not
1375 // within the touched window.
1376 if (!isTouchModal) {
1377 while (sample->next) {
Jeff Brown9302c872011-07-13 22:51:29 -07001378 if (!newHoverWindowHandle->touchableRegionContainsPoint(
Jeff Browna032cc02011-03-07 16:56:21 -08001379 sample->next->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X),
1380 sample->next->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y))) {
1381 *outSplitBatchAfterSample = sample;
1382 break;
1383 }
1384 sample = sample->next;
1385 }
1386 }
1387 } else if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
Jeff Brown9302c872011-07-13 22:51:29 -07001388 newHoverWindowHandle = mLastHoverWindowHandle;
Jeff Browna032cc02011-03-07 16:56:21 -08001389 }
1390
Jeff Brown01ce2e92010-09-26 22:20:12 -07001391 // Update the temporary touch state.
1392 BitSet32 pointerIds;
1393 if (isSplit) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07001394 uint32_t pointerId = entry->pointerProperties[pointerIndex].id;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001395 pointerIds.markBit(pointerId);
Jeff Brownb88102f2010-09-08 11:49:43 -07001396 }
Jeff Brown9302c872011-07-13 22:51:29 -07001397 mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Jeff Brownb88102f2010-09-08 11:49:43 -07001398 } else {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001399 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
Jeff Brownb88102f2010-09-08 11:49:43 -07001400
1401 // If the pointer is not currently down, then ignore the event.
Jeff Brown01ce2e92010-09-26 22:20:12 -07001402 if (! mTempTouchState.down) {
Jeff Browna2cc28d2011-03-25 11:58:46 -07001403#if DEBUG_FOCUS
Jeff Brown76860e32010-10-25 17:37:46 -07001404 LOGD("Dropping event because the pointer is not down or we previously "
1405 "dropped the pointer down event.");
1406#endif
Jeff Brownb88102f2010-09-08 11:49:43 -07001407 injectionResult = INPUT_EVENT_INJECTION_FAILED;
Jeff Brownb88102f2010-09-08 11:49:43 -07001408 goto Failed;
1409 }
Jeff Brown98db5fa2011-06-08 15:37:10 -07001410
1411 // Check whether touches should slip outside of the current foreground window.
1412 if (maskedAction == AMOTION_EVENT_ACTION_MOVE
1413 && entry->pointerCount == 1
1414 && mTempTouchState.isSlippery()) {
1415 const MotionSample* sample = &entry->firstSample;
1416 int32_t x = int32_t(sample->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
1417 int32_t y = int32_t(sample->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
1418
Jeff Brown9302c872011-07-13 22:51:29 -07001419 sp<InputWindowHandle> oldTouchedWindowHandle =
1420 mTempTouchState.getFirstForegroundWindowHandle();
1421 sp<InputWindowHandle> newTouchedWindowHandle = findTouchedWindowAtLocked(x, y);
1422 if (oldTouchedWindowHandle != newTouchedWindowHandle
1423 && newTouchedWindowHandle != NULL) {
Jeff Brown98db5fa2011-06-08 15:37:10 -07001424#if DEBUG_FOCUS
1425 LOGD("Touch is slipping out of window %s into window %s.",
Jeff Brown9302c872011-07-13 22:51:29 -07001426 oldTouchedWindowHandle->name.string(),
1427 newTouchedWindowHandle->name.string());
Jeff Brown98db5fa2011-06-08 15:37:10 -07001428#endif
1429 // Make a slippery exit from the old window.
Jeff Brown9302c872011-07-13 22:51:29 -07001430 mTempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
Jeff Brown98db5fa2011-06-08 15:37:10 -07001431 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT, BitSet32(0));
1432
1433 // Make a slippery entrance into the new window.
Jeff Brown9302c872011-07-13 22:51:29 -07001434 if (newTouchedWindowHandle->supportsSplitTouch()) {
Jeff Brown98db5fa2011-06-08 15:37:10 -07001435 isSplit = true;
1436 }
1437
1438 int32_t targetFlags = InputTarget::FLAG_FOREGROUND
1439 | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
1440 if (isSplit) {
1441 targetFlags |= InputTarget::FLAG_SPLIT;
1442 }
Jeff Brown9302c872011-07-13 22:51:29 -07001443 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
Jeff Brown98db5fa2011-06-08 15:37:10 -07001444 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1445 }
1446
1447 BitSet32 pointerIds;
1448 if (isSplit) {
1449 pointerIds.markBit(entry->pointerProperties[0].id);
1450 }
Jeff Brown9302c872011-07-13 22:51:29 -07001451 mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Jeff Brown98db5fa2011-06-08 15:37:10 -07001452
1453 // Split the batch here so we send exactly one sample.
1454 *outSplitBatchAfterSample = &entry->firstSample;
1455 }
1456 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001457 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001458
Jeff Brown9302c872011-07-13 22:51:29 -07001459 if (newHoverWindowHandle != mLastHoverWindowHandle) {
Jeff Browna032cc02011-03-07 16:56:21 -08001460 // Split the batch here so we send exactly one sample as part of ENTER or EXIT.
1461 *outSplitBatchAfterSample = &entry->firstSample;
1462
1463 // Let the previous window know that the hover sequence is over.
Jeff Brown9302c872011-07-13 22:51:29 -07001464 if (mLastHoverWindowHandle != NULL) {
Jeff Browna032cc02011-03-07 16:56:21 -08001465#if DEBUG_HOVER
Jeff Brown9302c872011-07-13 22:51:29 -07001466 LOGD("Sending hover exit event to window %s.", mLastHoverWindowHandle->name.string());
Jeff Browna032cc02011-03-07 16:56:21 -08001467#endif
Jeff Brown9302c872011-07-13 22:51:29 -07001468 mTempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
Jeff Browna032cc02011-03-07 16:56:21 -08001469 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
1470 }
1471
1472 // Let the new window know that the hover sequence is starting.
Jeff Brown9302c872011-07-13 22:51:29 -07001473 if (newHoverWindowHandle != NULL) {
Jeff Browna032cc02011-03-07 16:56:21 -08001474#if DEBUG_HOVER
Jeff Brown9302c872011-07-13 22:51:29 -07001475 LOGD("Sending hover enter event to window %s.", newHoverWindowHandle->name.string());
Jeff Browna032cc02011-03-07 16:56:21 -08001476#endif
Jeff Brown9302c872011-07-13 22:51:29 -07001477 mTempTouchState.addOrUpdateWindow(newHoverWindowHandle,
Jeff Browna032cc02011-03-07 16:56:21 -08001478 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER, BitSet32(0));
1479 }
1480 }
1481
Jeff Brown01ce2e92010-09-26 22:20:12 -07001482 // Check permission to inject into all touched foreground windows and ensure there
1483 // is at least one touched foreground window.
1484 {
1485 bool haveForegroundWindow = false;
1486 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1487 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1488 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1489 haveForegroundWindow = true;
Jeff Brown9302c872011-07-13 22:51:29 -07001490 if (! checkInjectionPermission(touchedWindow.windowHandle,
1491 entry->injectionState)) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001492 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1493 injectionPermission = INJECTION_PERMISSION_DENIED;
1494 goto Failed;
1495 }
1496 }
1497 }
1498 if (! haveForegroundWindow) {
Jeff Browna2cc28d2011-03-25 11:58:46 -07001499#if DEBUG_FOCUS
Jeff Brown01ce2e92010-09-26 22:20:12 -07001500 LOGD("Dropping event because there is no touched foreground window to receive it.");
Jeff Brownb88102f2010-09-08 11:49:43 -07001501#endif
1502 injectionResult = INPUT_EVENT_INJECTION_FAILED;
Jeff Brownb88102f2010-09-08 11:49:43 -07001503 goto Failed;
1504 }
1505
Jeff Brown01ce2e92010-09-26 22:20:12 -07001506 // Permission granted to injection into all touched foreground windows.
1507 injectionPermission = INJECTION_PERMISSION_GRANTED;
1508 }
Jeff Brown519e0242010-09-15 15:18:56 -07001509
Kenny Root7a9db182011-06-02 15:16:05 -07001510 // Check whether windows listening for outside touches are owned by the same UID. If it is
1511 // set the policy flag that we will not reveal coordinate information to this window.
1512 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
Jeff Brown9302c872011-07-13 22:51:29 -07001513 sp<InputWindowHandle> foregroundWindowHandle =
1514 mTempTouchState.getFirstForegroundWindowHandle();
1515 const int32_t foregroundWindowUid = foregroundWindowHandle->ownerUid;
Kenny Root7a9db182011-06-02 15:16:05 -07001516 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1517 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1518 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
Jeff Brown9302c872011-07-13 22:51:29 -07001519 sp<InputWindowHandle> inputWindowHandle = touchedWindow.windowHandle;
1520 if (inputWindowHandle->ownerUid != foregroundWindowUid) {
1521 mTempTouchState.addOrUpdateWindow(inputWindowHandle,
Kenny Root7a9db182011-06-02 15:16:05 -07001522 InputTarget::FLAG_ZERO_COORDS, BitSet32(0));
1523 }
1524 }
1525 }
1526 }
1527
Jeff Brown01ce2e92010-09-26 22:20:12 -07001528 // Ensure all touched foreground windows are ready for new input.
1529 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1530 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1531 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1532 // If the touched window is paused then keep waiting.
Jeff Brown9302c872011-07-13 22:51:29 -07001533 if (touchedWindow.windowHandle->paused) {
Jeff Browna2cc28d2011-03-25 11:58:46 -07001534#if DEBUG_FOCUS
Jeff Brown01ce2e92010-09-26 22:20:12 -07001535 LOGD("Waiting because touched window is paused.");
Jeff Brown519e0242010-09-15 15:18:56 -07001536#endif
Jeff Brown01ce2e92010-09-26 22:20:12 -07001537 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brown9302c872011-07-13 22:51:29 -07001538 NULL, touchedWindow.windowHandle, nextWakeupTime);
Jeff Brown01ce2e92010-09-26 22:20:12 -07001539 goto Unresponsive;
1540 }
1541
1542 // If the touched window is still working on previous events then keep waiting.
Jeff Brown9302c872011-07-13 22:51:29 -07001543 if (! isWindowFinishedWithPreviousInputLocked(touchedWindow.windowHandle)) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001544#if DEBUG_FOCUS
1545 LOGD("Waiting because touched window still processing previous input.");
1546#endif
1547 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brown9302c872011-07-13 22:51:29 -07001548 NULL, touchedWindow.windowHandle, nextWakeupTime);
Jeff Brown01ce2e92010-09-26 22:20:12 -07001549 goto Unresponsive;
1550 }
1551 }
1552 }
1553
1554 // If this is the first pointer going down and the touched window has a wallpaper
1555 // then also add the touched wallpaper windows so they are locked in for the duration
1556 // of the touch gesture.
Jeff Brown33bbfd22011-02-24 20:55:35 -08001557 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
1558 // engine only supports touch events. We would need to add a mechanism similar
1559 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
1560 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
Jeff Brown9302c872011-07-13 22:51:29 -07001561 sp<InputWindowHandle> foregroundWindowHandle =
1562 mTempTouchState.getFirstForegroundWindowHandle();
1563 if (foregroundWindowHandle->hasWallpaper) {
1564 for (size_t i = 0; i < mWindowHandles.size(); i++) {
1565 sp<InputWindowHandle> windowHandle = mWindowHandles.itemAt(i);
1566 if (windowHandle->layoutParamsType == InputWindowHandle::TYPE_WALLPAPER) {
1567 mTempTouchState.addOrUpdateWindow(windowHandle,
Jeff Browna032cc02011-03-07 16:56:21 -08001568 InputTarget::FLAG_WINDOW_IS_OBSCURED
1569 | InputTarget::FLAG_DISPATCH_AS_IS,
1570 BitSet32(0));
Jeff Brown01ce2e92010-09-26 22:20:12 -07001571 }
1572 }
1573 }
1574 }
1575
Jeff Brownb88102f2010-09-08 11:49:43 -07001576 // Success! Output targets.
1577 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
Jeff Brownb88102f2010-09-08 11:49:43 -07001578
Jeff Brown01ce2e92010-09-26 22:20:12 -07001579 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1580 const TouchedWindow& touchedWindow = mTempTouchState.windows.itemAt(i);
Jeff Brown9302c872011-07-13 22:51:29 -07001581 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Jeff Brown01ce2e92010-09-26 22:20:12 -07001582 touchedWindow.pointerIds);
Jeff Brownb88102f2010-09-08 11:49:43 -07001583 }
1584
Jeff Browna032cc02011-03-07 16:56:21 -08001585 // Drop the outside or hover touch windows since we will not care about them
1586 // in the next iteration.
1587 mTempTouchState.filterNonAsIsTouchWindows();
Jeff Brown01ce2e92010-09-26 22:20:12 -07001588
Jeff Brownb88102f2010-09-08 11:49:43 -07001589Failed:
1590 // Check injection permission once and for all.
1591 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001592 if (checkInjectionPermission(NULL, entry->injectionState)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001593 injectionPermission = INJECTION_PERMISSION_GRANTED;
1594 } else {
1595 injectionPermission = INJECTION_PERMISSION_DENIED;
1596 }
1597 }
1598
1599 // Update final pieces of touch state if the injector had permission.
1600 if (injectionPermission == INJECTION_PERMISSION_GRANTED) {
Jeff Brown95712852011-01-04 19:41:59 -08001601 if (!wrongDevice) {
Jeff Brown81346812011-06-28 20:08:48 -07001602 if (switchedDevice) {
1603#if DEBUG_FOCUS
1604 LOGD("Conflicting pointer actions: Switched to a different device.");
1605#endif
1606 *outConflictingPointerActions = true;
1607 }
1608
1609 if (isHoverAction) {
1610 // Started hovering, therefore no longer down.
1611 if (mTouchState.down) {
1612#if DEBUG_FOCUS
1613 LOGD("Conflicting pointer actions: Hover received while pointer was down.");
1614#endif
1615 *outConflictingPointerActions = true;
1616 }
1617 mTouchState.reset();
1618 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER
1619 || maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
1620 mTouchState.deviceId = entry->deviceId;
1621 mTouchState.source = entry->source;
1622 }
1623 } else if (maskedAction == AMOTION_EVENT_ACTION_UP
1624 || maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Jeff Brown95712852011-01-04 19:41:59 -08001625 // All pointers up or canceled.
Jeff Brown33bbfd22011-02-24 20:55:35 -08001626 mTouchState.reset();
Jeff Brown95712852011-01-04 19:41:59 -08001627 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1628 // First pointer went down.
1629 if (mTouchState.down) {
Jeff Brownb6997262010-10-08 22:31:17 -07001630#if DEBUG_FOCUS
Jeff Brown81346812011-06-28 20:08:48 -07001631 LOGD("Conflicting pointer actions: Down received while already down.");
Jeff Brownb6997262010-10-08 22:31:17 -07001632#endif
Jeff Brown81346812011-06-28 20:08:48 -07001633 *outConflictingPointerActions = true;
Jeff Brown95712852011-01-04 19:41:59 -08001634 }
Jeff Brown33bbfd22011-02-24 20:55:35 -08001635 mTouchState.copyFrom(mTempTouchState);
Jeff Brown95712852011-01-04 19:41:59 -08001636 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
1637 // One pointer went up.
1638 if (isSplit) {
1639 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07001640 uint32_t pointerId = entry->pointerProperties[pointerIndex].id;
Jeff Brownb88102f2010-09-08 11:49:43 -07001641
Jeff Brown95712852011-01-04 19:41:59 -08001642 for (size_t i = 0; i < mTempTouchState.windows.size(); ) {
1643 TouchedWindow& touchedWindow = mTempTouchState.windows.editItemAt(i);
1644 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
1645 touchedWindow.pointerIds.clearBit(pointerId);
1646 if (touchedWindow.pointerIds.isEmpty()) {
1647 mTempTouchState.windows.removeAt(i);
1648 continue;
1649 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001650 }
Jeff Brown95712852011-01-04 19:41:59 -08001651 i += 1;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001652 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001653 }
Jeff Brown33bbfd22011-02-24 20:55:35 -08001654 mTouchState.copyFrom(mTempTouchState);
1655 } else if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
1656 // Discard temporary touch state since it was only valid for this action.
1657 } else {
1658 // Save changes to touch state as-is for all other actions.
1659 mTouchState.copyFrom(mTempTouchState);
Jeff Brownb88102f2010-09-08 11:49:43 -07001660 }
Jeff Browna032cc02011-03-07 16:56:21 -08001661
1662 // Update hover state.
Jeff Brown9302c872011-07-13 22:51:29 -07001663 mLastHoverWindowHandle = newHoverWindowHandle;
Jeff Brown95712852011-01-04 19:41:59 -08001664 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001665 } else {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001666#if DEBUG_FOCUS
1667 LOGD("Not updating touch focus because injection was denied.");
1668#endif
Jeff Brownb88102f2010-09-08 11:49:43 -07001669 }
1670
1671Unresponsive:
Jeff Brown120a4592010-10-27 18:43:51 -07001672 // Reset temporary touch state to ensure we release unnecessary references to input channels.
1673 mTempTouchState.reset();
1674
Jeff Brown519e0242010-09-15 15:18:56 -07001675 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
1676 updateDispatchStatisticsLocked(currentTime, entry,
1677 injectionResult, timeSpentWaitingForApplication);
Jeff Brownb88102f2010-09-08 11:49:43 -07001678#if DEBUG_FOCUS
Jeff Brown01ce2e92010-09-26 22:20:12 -07001679 LOGD("findTouchedWindow finished: injectionResult=%d, injectionPermission=%d, "
1680 "timeSpentWaitingForApplication=%0.1fms",
Jeff Brown519e0242010-09-15 15:18:56 -07001681 injectionResult, injectionPermission, timeSpentWaitingForApplication / 1000000.0);
Jeff Brownb88102f2010-09-08 11:49:43 -07001682#endif
1683 return injectionResult;
1684}
1685
Jeff Brown9302c872011-07-13 22:51:29 -07001686void InputDispatcher::addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
1687 int32_t targetFlags, BitSet32 pointerIds) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001688 mCurrentInputTargets.push();
1689
1690 InputTarget& target = mCurrentInputTargets.editTop();
Jeff Brown9302c872011-07-13 22:51:29 -07001691 target.inputChannel = windowHandle->inputChannel;
Jeff Brownb88102f2010-09-08 11:49:43 -07001692 target.flags = targetFlags;
Jeff Brown9302c872011-07-13 22:51:29 -07001693 target.xOffset = - windowHandle->frameLeft;
1694 target.yOffset = - windowHandle->frameTop;
1695 target.scaleFactor = windowHandle->scaleFactor;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001696 target.pointerIds = pointerIds;
Jeff Brownb88102f2010-09-08 11:49:43 -07001697}
1698
1699void InputDispatcher::addMonitoringTargetsLocked() {
1700 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
1701 mCurrentInputTargets.push();
1702
1703 InputTarget& target = mCurrentInputTargets.editTop();
1704 target.inputChannel = mMonitoringChannels[i];
Jeff Brownb6110c22011-04-01 16:15:13 -07001705 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
Jeff Brownb88102f2010-09-08 11:49:43 -07001706 target.xOffset = 0;
1707 target.yOffset = 0;
Jeff Brownb6110c22011-04-01 16:15:13 -07001708 target.pointerIds.clear();
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001709 target.scaleFactor = 1.0f;
Jeff Brownb88102f2010-09-08 11:49:43 -07001710 }
1711}
1712
Jeff Brown9302c872011-07-13 22:51:29 -07001713bool InputDispatcher::checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
Jeff Brown01ce2e92010-09-26 22:20:12 -07001714 const InjectionState* injectionState) {
1715 if (injectionState
Jeff Brown9302c872011-07-13 22:51:29 -07001716 && (windowHandle == NULL || windowHandle->ownerUid != injectionState->injectorUid)
Jeff Brownb6997262010-10-08 22:31:17 -07001717 && !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Jeff Brown9302c872011-07-13 22:51:29 -07001718 if (windowHandle != NULL) {
1719 LOGW("Permission denied: injecting event from pid %d uid %d to window %s "
1720 "owned by uid %d",
Jeff Brownb6997262010-10-08 22:31:17 -07001721 injectionState->injectorPid, injectionState->injectorUid,
Jeff Brown9302c872011-07-13 22:51:29 -07001722 windowHandle->name.string(),
1723 windowHandle->ownerUid);
Jeff Brownb6997262010-10-08 22:31:17 -07001724 } else {
1725 LOGW("Permission denied: injecting event from pid %d uid %d",
1726 injectionState->injectorPid, injectionState->injectorUid);
Jeff Brownb88102f2010-09-08 11:49:43 -07001727 }
Jeff Brownb6997262010-10-08 22:31:17 -07001728 return false;
Jeff Brownb88102f2010-09-08 11:49:43 -07001729 }
1730 return true;
1731}
1732
Jeff Brown19dfc832010-10-05 12:26:23 -07001733bool InputDispatcher::isWindowObscuredAtPointLocked(
Jeff Brown9302c872011-07-13 22:51:29 -07001734 const sp<InputWindowHandle>& windowHandle, int32_t x, int32_t y) const {
1735 size_t numWindows = mWindowHandles.size();
Jeff Brownb88102f2010-09-08 11:49:43 -07001736 for (size_t i = 0; i < numWindows; i++) {
Jeff Brown9302c872011-07-13 22:51:29 -07001737 sp<InputWindowHandle> otherHandle = mWindowHandles.itemAt(i);
1738 if (otherHandle == windowHandle) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001739 break;
1740 }
Jeff Brown9302c872011-07-13 22:51:29 -07001741 if (otherHandle->visible && ! otherHandle->isTrustedOverlay()
1742 && otherHandle->frameContainsPoint(x, y)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001743 return true;
1744 }
1745 }
1746 return false;
1747}
1748
Jeff Brown9302c872011-07-13 22:51:29 -07001749bool InputDispatcher::isWindowFinishedWithPreviousInputLocked(
1750 const sp<InputWindowHandle>& windowHandle) {
1751 ssize_t connectionIndex = getConnectionIndexLocked(windowHandle->inputChannel);
Jeff Brown519e0242010-09-15 15:18:56 -07001752 if (connectionIndex >= 0) {
1753 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
1754 return connection->outboundQueue.isEmpty();
1755 } else {
1756 return true;
1757 }
1758}
1759
Jeff Brown9302c872011-07-13 22:51:29 -07001760String8 InputDispatcher::getApplicationWindowLabelLocked(
1761 const sp<InputApplicationHandle>& applicationHandle,
1762 const sp<InputWindowHandle>& windowHandle) {
1763 if (applicationHandle != NULL) {
1764 if (windowHandle != NULL) {
1765 String8 label(applicationHandle->name);
Jeff Brown519e0242010-09-15 15:18:56 -07001766 label.append(" - ");
Jeff Brown9302c872011-07-13 22:51:29 -07001767 label.append(windowHandle->name);
Jeff Brown519e0242010-09-15 15:18:56 -07001768 return label;
1769 } else {
Jeff Brown9302c872011-07-13 22:51:29 -07001770 return applicationHandle->name;
Jeff Brown519e0242010-09-15 15:18:56 -07001771 }
Jeff Brown9302c872011-07-13 22:51:29 -07001772 } else if (windowHandle != NULL) {
1773 return windowHandle->name;
Jeff Brown519e0242010-09-15 15:18:56 -07001774 } else {
1775 return String8("<unknown application or window>");
1776 }
1777}
1778
Jeff Browne2fe69e2010-10-18 13:21:23 -07001779void InputDispatcher::pokeUserActivityLocked(const EventEntry* eventEntry) {
Jeff Brown56194eb2011-03-02 19:23:13 -08001780 int32_t eventType = POWER_MANAGER_OTHER_EVENT;
Jeff Brown4d396052010-10-29 21:50:21 -07001781 switch (eventEntry->type) {
1782 case EventEntry::TYPE_MOTION: {
Jeff Browne2fe69e2010-10-18 13:21:23 -07001783 const MotionEntry* motionEntry = static_cast<const MotionEntry*>(eventEntry);
Jeff Brown4d396052010-10-29 21:50:21 -07001784 if (motionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
1785 return;
1786 }
1787
Jeff Brown56194eb2011-03-02 19:23:13 -08001788 if (MotionEvent::isTouchEvent(motionEntry->source, motionEntry->action)) {
Joe Onorato1a542c72010-11-08 09:48:20 -08001789 eventType = POWER_MANAGER_TOUCH_EVENT;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001790 }
Jeff Brown4d396052010-10-29 21:50:21 -07001791 break;
1792 }
1793 case EventEntry::TYPE_KEY: {
1794 const KeyEntry* keyEntry = static_cast<const KeyEntry*>(eventEntry);
1795 if (keyEntry->flags & AKEY_EVENT_FLAG_CANCELED) {
1796 return;
1797 }
Jeff Brown56194eb2011-03-02 19:23:13 -08001798 eventType = POWER_MANAGER_BUTTON_EVENT;
Jeff Brown4d396052010-10-29 21:50:21 -07001799 break;
1800 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001801 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001802
Jeff Brownb88102f2010-09-08 11:49:43 -07001803 CommandEntry* commandEntry = postCommandLocked(
1804 & InputDispatcher::doPokeUserActivityLockedInterruptible);
Jeff Browne2fe69e2010-10-18 13:21:23 -07001805 commandEntry->eventTime = eventEntry->eventTime;
Jeff Brownb88102f2010-09-08 11:49:43 -07001806 commandEntry->userActivityEventType = eventType;
1807}
1808
Jeff Brown7fbdc842010-06-17 20:52:56 -07001809void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
1810 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget,
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001811 bool resumeWithAppendedMotionSample) {
1812#if DEBUG_DISPATCH_CYCLE
Jeff Brown519e0242010-09-15 15:18:56 -07001813 LOGD("channel '%s' ~ prepareDispatchCycle - flags=%d, "
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001814 "xOffset=%f, yOffset=%f, scaleFactor=%f"
Jeff Brown83c09682010-12-23 17:50:18 -08001815 "pointerIds=0x%x, "
Jeff Brown01ce2e92010-09-26 22:20:12 -07001816 "resumeWithAppendedMotionSample=%s",
Jeff Brown519e0242010-09-15 15:18:56 -07001817 connection->getInputChannelName(), inputTarget->flags,
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001818 inputTarget->xOffset, inputTarget->yOffset,
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001819 inputTarget->scaleFactor, inputTarget->pointerIds.value,
Jeff Brownb88102f2010-09-08 11:49:43 -07001820 toString(resumeWithAppendedMotionSample));
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001821#endif
1822
Jeff Brown01ce2e92010-09-26 22:20:12 -07001823 // Make sure we are never called for streaming when splitting across multiple windows.
1824 bool isSplit = inputTarget->flags & InputTarget::FLAG_SPLIT;
Jeff Brownb6110c22011-04-01 16:15:13 -07001825 LOG_ASSERT(! (resumeWithAppendedMotionSample && isSplit));
Jeff Brown01ce2e92010-09-26 22:20:12 -07001826
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001827 // Skip this event if the connection status is not normal.
Jeff Brown519e0242010-09-15 15:18:56 -07001828 // We don't want to enqueue additional outbound events if the connection is broken.
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001829 if (connection->status != Connection::STATUS_NORMAL) {
Jeff Brownb6997262010-10-08 22:31:17 -07001830#if DEBUG_DISPATCH_CYCLE
1831 LOGD("channel '%s' ~ Dropping event because the channel status is %s",
Jeff Brownb88102f2010-09-08 11:49:43 -07001832 connection->getInputChannelName(), connection->getStatusLabel());
Jeff Brownb6997262010-10-08 22:31:17 -07001833#endif
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001834 return;
1835 }
1836
Jeff Brown01ce2e92010-09-26 22:20:12 -07001837 // Split a motion event if needed.
1838 if (isSplit) {
Jeff Brownb6110c22011-04-01 16:15:13 -07001839 LOG_ASSERT(eventEntry->type == EventEntry::TYPE_MOTION);
Jeff Brown01ce2e92010-09-26 22:20:12 -07001840
1841 MotionEntry* originalMotionEntry = static_cast<MotionEntry*>(eventEntry);
1842 if (inputTarget->pointerIds.count() != originalMotionEntry->pointerCount) {
1843 MotionEntry* splitMotionEntry = splitMotionEvent(
1844 originalMotionEntry, inputTarget->pointerIds);
Jeff Brown58a2da82011-01-25 16:02:22 -08001845 if (!splitMotionEntry) {
1846 return; // split event was dropped
1847 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001848#if DEBUG_FOCUS
1849 LOGD("channel '%s' ~ Split motion event.",
1850 connection->getInputChannelName());
1851 logOutboundMotionDetailsLocked(" ", splitMotionEntry);
1852#endif
1853 eventEntry = splitMotionEntry;
1854 }
1855 }
1856
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001857 // Resume the dispatch cycle with a freshly appended motion sample.
1858 // First we check that the last dispatch entry in the outbound queue is for the same
1859 // motion event to which we appended the motion sample. If we find such a dispatch
1860 // entry, and if it is currently in progress then we try to stream the new sample.
1861 bool wasEmpty = connection->outboundQueue.isEmpty();
1862
1863 if (! wasEmpty && resumeWithAppendedMotionSample) {
1864 DispatchEntry* motionEventDispatchEntry =
1865 connection->findQueuedDispatchEntryForEvent(eventEntry);
1866 if (motionEventDispatchEntry) {
1867 // If the dispatch entry is not in progress, then we must be busy dispatching an
1868 // earlier event. Not a problem, the motion event is on the outbound queue and will
1869 // be dispatched later.
1870 if (! motionEventDispatchEntry->inProgress) {
1871#if DEBUG_BATCHING
1872 LOGD("channel '%s' ~ Not streaming because the motion event has "
1873 "not yet been dispatched. "
1874 "(Waiting for earlier events to be consumed.)",
1875 connection->getInputChannelName());
1876#endif
1877 return;
1878 }
1879
1880 // If the dispatch entry is in progress but it already has a tail of pending
1881 // motion samples, then it must mean that the shared memory buffer filled up.
1882 // Not a problem, when this dispatch cycle is finished, we will eventually start
1883 // a new dispatch cycle to process the tail and that tail includes the newly
1884 // appended motion sample.
1885 if (motionEventDispatchEntry->tailMotionSample) {
1886#if DEBUG_BATCHING
1887 LOGD("channel '%s' ~ Not streaming because no new samples can "
1888 "be appended to the motion event in this dispatch cycle. "
1889 "(Waiting for next dispatch cycle to start.)",
1890 connection->getInputChannelName());
1891#endif
1892 return;
1893 }
1894
Jeff Brown81346812011-06-28 20:08:48 -07001895 // If the motion event was modified in flight, then we cannot stream the sample.
1896 if ((motionEventDispatchEntry->targetFlags & InputTarget::FLAG_DISPATCH_MASK)
1897 != InputTarget::FLAG_DISPATCH_AS_IS) {
1898#if DEBUG_BATCHING
1899 LOGD("channel '%s' ~ Not streaming because the motion event was not "
1900 "being dispatched as-is. "
1901 "(Waiting for next dispatch cycle to start.)",
1902 connection->getInputChannelName());
1903#endif
1904 return;
1905 }
1906
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001907 // The dispatch entry is in progress and is still potentially open for streaming.
1908 // Try to stream the new motion sample. This might fail if the consumer has already
1909 // consumed the motion event (or if the channel is broken).
Jeff Brown01ce2e92010-09-26 22:20:12 -07001910 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
1911 MotionSample* appendedMotionSample = motionEntry->lastSample;
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001912 status_t status;
1913 if (motionEventDispatchEntry->scaleFactor == 1.0f) {
1914 status = connection->inputPublisher.appendMotionSample(
1915 appendedMotionSample->eventTime, appendedMotionSample->pointerCoords);
1916 } else {
1917 PointerCoords scaledCoords[MAX_POINTERS];
1918 for (size_t i = 0; i < motionEntry->pointerCount; i++) {
1919 scaledCoords[i] = appendedMotionSample->pointerCoords[i];
1920 scaledCoords[i].scale(motionEventDispatchEntry->scaleFactor);
1921 }
1922 status = connection->inputPublisher.appendMotionSample(
1923 appendedMotionSample->eventTime, scaledCoords);
1924 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001925 if (status == OK) {
1926#if DEBUG_BATCHING
1927 LOGD("channel '%s' ~ Successfully streamed new motion sample.",
1928 connection->getInputChannelName());
1929#endif
1930 return;
1931 }
1932
1933#if DEBUG_BATCHING
1934 if (status == NO_MEMORY) {
1935 LOGD("channel '%s' ~ Could not append motion sample to currently "
1936 "dispatched move event because the shared memory buffer is full. "
1937 "(Waiting for next dispatch cycle to start.)",
1938 connection->getInputChannelName());
1939 } else if (status == status_t(FAILED_TRANSACTION)) {
1940 LOGD("channel '%s' ~ Could not append motion sample to currently "
Jeff Brown349703e2010-06-22 01:27:15 -07001941 "dispatched move event because the event has already been consumed. "
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001942 "(Waiting for next dispatch cycle to start.)",
1943 connection->getInputChannelName());
1944 } else {
1945 LOGD("channel '%s' ~ Could not append motion sample to currently "
1946 "dispatched move event due to an error, status=%d. "
1947 "(Waiting for next dispatch cycle to start.)",
1948 connection->getInputChannelName(), status);
1949 }
1950#endif
1951 // Failed to stream. Start a new tail of pending motion samples to dispatch
1952 // in the next cycle.
1953 motionEventDispatchEntry->tailMotionSample = appendedMotionSample;
1954 return;
1955 }
1956 }
1957
Jeff Browna032cc02011-03-07 16:56:21 -08001958 // Enqueue dispatch entries for the requested modes.
1959 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1960 resumeWithAppendedMotionSample, InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
1961 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1962 resumeWithAppendedMotionSample, InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
1963 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1964 resumeWithAppendedMotionSample, InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
1965 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1966 resumeWithAppendedMotionSample, InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brown98db5fa2011-06-08 15:37:10 -07001967 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1968 resumeWithAppendedMotionSample, InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
1969 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1970 resumeWithAppendedMotionSample, InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Jeff Browna032cc02011-03-07 16:56:21 -08001971
1972 // If the outbound queue was previously empty, start the dispatch cycle going.
Jeff Brownb6110c22011-04-01 16:15:13 -07001973 if (wasEmpty && !connection->outboundQueue.isEmpty()) {
Jeff Browna032cc02011-03-07 16:56:21 -08001974 activateConnectionLocked(connection.get());
1975 startDispatchCycleLocked(currentTime, connection);
1976 }
1977}
1978
1979void InputDispatcher::enqueueDispatchEntryLocked(
1980 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget,
1981 bool resumeWithAppendedMotionSample, int32_t dispatchMode) {
1982 int32_t inputTargetFlags = inputTarget->flags;
1983 if (!(inputTargetFlags & dispatchMode)) {
1984 return;
1985 }
1986 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
1987
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001988 // This is a new event.
1989 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Jeff Brownac386072011-07-20 15:19:50 -07001990 DispatchEntry* dispatchEntry = new DispatchEntry(eventEntry, // increments ref
Dianne Hackbornaa9d84c2011-05-09 19:00:59 -07001991 inputTargetFlags, inputTarget->xOffset, inputTarget->yOffset,
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001992 inputTarget->scaleFactor);
Jeff Brown519e0242010-09-15 15:18:56 -07001993 if (dispatchEntry->hasForegroundTarget()) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001994 incrementPendingForegroundDispatchesLocked(eventEntry);
Jeff Brown6ec402b2010-07-28 15:48:59 -07001995 }
1996
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001997 // Handle the case where we could not stream a new motion sample because the consumer has
1998 // already consumed the motion event (otherwise the corresponding dispatch entry would
1999 // still be in the outbound queue for this connection). We set the head motion sample
2000 // to the list starting with the newly appended motion sample.
2001 if (resumeWithAppendedMotionSample) {
2002#if DEBUG_BATCHING
2003 LOGD("channel '%s' ~ Preparing a new dispatch cycle for additional motion samples "
2004 "that cannot be streamed because the motion event has already been consumed.",
2005 connection->getInputChannelName());
2006#endif
2007 MotionSample* appendedMotionSample = static_cast<MotionEntry*>(eventEntry)->lastSample;
2008 dispatchEntry->headMotionSample = appendedMotionSample;
2009 }
2010
Jeff Brown81346812011-06-28 20:08:48 -07002011 // Apply target flags and update the connection's input state.
2012 switch (eventEntry->type) {
2013 case EventEntry::TYPE_KEY: {
2014 KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
2015 dispatchEntry->resolvedAction = keyEntry->action;
2016 dispatchEntry->resolvedFlags = keyEntry->flags;
2017
2018 if (!connection->inputState.trackKey(keyEntry,
2019 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags)) {
2020#if DEBUG_DISPATCH_CYCLE
2021 LOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
2022 connection->getInputChannelName());
2023#endif
2024 return; // skip the inconsistent event
2025 }
2026 break;
2027 }
2028
2029 case EventEntry::TYPE_MOTION: {
2030 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
2031 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2032 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
2033 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
2034 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
2035 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
2036 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2037 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
2038 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
2039 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
2040 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
2041 } else {
2042 dispatchEntry->resolvedAction = motionEntry->action;
2043 }
2044 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE
2045 && !connection->inputState.isHovering(
2046 motionEntry->deviceId, motionEntry->source)) {
2047#if DEBUG_DISPATCH_CYCLE
2048 LOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter event",
2049 connection->getInputChannelName());
2050#endif
2051 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2052 }
2053
2054 dispatchEntry->resolvedFlags = motionEntry->flags;
2055 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
2056 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
2057 }
2058
2059 if (!connection->inputState.trackMotion(motionEntry,
2060 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags)) {
2061#if DEBUG_DISPATCH_CYCLE
2062 LOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion event",
2063 connection->getInputChannelName());
2064#endif
2065 return; // skip the inconsistent event
2066 }
2067 break;
2068 }
2069 }
2070
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002071 // Enqueue the dispatch entry.
2072 connection->outboundQueue.enqueueAtTail(dispatchEntry);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002073}
2074
Jeff Brown7fbdc842010-06-17 20:52:56 -07002075void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Jeff Brown519e0242010-09-15 15:18:56 -07002076 const sp<Connection>& connection) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002077#if DEBUG_DISPATCH_CYCLE
2078 LOGD("channel '%s' ~ startDispatchCycle",
2079 connection->getInputChannelName());
2080#endif
2081
Jeff Brownb6110c22011-04-01 16:15:13 -07002082 LOG_ASSERT(connection->status == Connection::STATUS_NORMAL);
2083 LOG_ASSERT(! connection->outboundQueue.isEmpty());
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002084
Jeff Brownac386072011-07-20 15:19:50 -07002085 DispatchEntry* dispatchEntry = connection->outboundQueue.head;
Jeff Brownb6110c22011-04-01 16:15:13 -07002086 LOG_ASSERT(! dispatchEntry->inProgress);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002087
Jeff Brownb88102f2010-09-08 11:49:43 -07002088 // Mark the dispatch entry as in progress.
2089 dispatchEntry->inProgress = true;
2090
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002091 // Publish the event.
2092 status_t status;
Jeff Browna032cc02011-03-07 16:56:21 -08002093 EventEntry* eventEntry = dispatchEntry->eventEntry;
Jeff Brown01ce2e92010-09-26 22:20:12 -07002094 switch (eventEntry->type) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002095 case EventEntry::TYPE_KEY: {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002096 KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002097
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002098 // Publish the key event.
Jeff Brown81346812011-06-28 20:08:48 -07002099 status = connection->inputPublisher.publishKeyEvent(
2100 keyEntry->deviceId, keyEntry->source,
2101 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags,
2102 keyEntry->keyCode, keyEntry->scanCode,
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002103 keyEntry->metaState, keyEntry->repeatCount, keyEntry->downTime,
2104 keyEntry->eventTime);
2105
2106 if (status) {
2107 LOGE("channel '%s' ~ Could not publish key event, "
2108 "status=%d", connection->getInputChannelName(), status);
Jeff Brownb6997262010-10-08 22:31:17 -07002109 abortBrokenDispatchCycleLocked(currentTime, connection);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002110 return;
2111 }
2112 break;
2113 }
2114
2115 case EventEntry::TYPE_MOTION: {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002116 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002117
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002118 // If headMotionSample is non-NULL, then it points to the first new sample that we
2119 // were unable to dispatch during the previous cycle so we resume dispatching from
2120 // that point in the list of motion samples.
2121 // Otherwise, we just start from the first sample of the motion event.
2122 MotionSample* firstMotionSample = dispatchEntry->headMotionSample;
2123 if (! firstMotionSample) {
2124 firstMotionSample = & motionEntry->firstSample;
2125 }
2126
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002127 PointerCoords scaledCoords[MAX_POINTERS];
2128 const PointerCoords* usingCoords = firstMotionSample->pointerCoords;
2129
Jeff Brownd3616592010-07-16 17:21:06 -07002130 // Set the X and Y offset depending on the input source.
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002131 float xOffset, yOffset, scaleFactor;
Kenny Root7a9db182011-06-02 15:16:05 -07002132 if (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER
2133 && !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002134 scaleFactor = dispatchEntry->scaleFactor;
2135 xOffset = dispatchEntry->xOffset * scaleFactor;
2136 yOffset = dispatchEntry->yOffset * scaleFactor;
2137 if (scaleFactor != 1.0f) {
2138 for (size_t i = 0; i < motionEntry->pointerCount; i++) {
2139 scaledCoords[i] = firstMotionSample->pointerCoords[i];
2140 scaledCoords[i].scale(scaleFactor);
2141 }
2142 usingCoords = scaledCoords;
2143 }
Jeff Brownd3616592010-07-16 17:21:06 -07002144 } else {
2145 xOffset = 0.0f;
2146 yOffset = 0.0f;
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002147 scaleFactor = 1.0f;
Kenny Root7a9db182011-06-02 15:16:05 -07002148
2149 // We don't want the dispatch target to know.
2150 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
2151 for (size_t i = 0; i < motionEntry->pointerCount; i++) {
2152 scaledCoords[i].clear();
2153 }
2154 usingCoords = scaledCoords;
2155 }
Jeff Brownd3616592010-07-16 17:21:06 -07002156 }
2157
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002158 // Publish the motion event and the first motion sample.
Jeff Brown81346812011-06-28 20:08:48 -07002159 status = connection->inputPublisher.publishMotionEvent(
2160 motionEntry->deviceId, motionEntry->source,
2161 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags,
2162 motionEntry->edgeFlags, motionEntry->metaState, motionEntry->buttonState,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002163 xOffset, yOffset,
2164 motionEntry->xPrecision, motionEntry->yPrecision,
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002165 motionEntry->downTime, firstMotionSample->eventTime,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002166 motionEntry->pointerCount, motionEntry->pointerProperties,
2167 usingCoords);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002168
2169 if (status) {
2170 LOGE("channel '%s' ~ Could not publish motion event, "
2171 "status=%d", connection->getInputChannelName(), status);
Jeff Brownb6997262010-10-08 22:31:17 -07002172 abortBrokenDispatchCycleLocked(currentTime, connection);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002173 return;
2174 }
2175
Jeff Brown81346812011-06-28 20:08:48 -07002176 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_MOVE
2177 || dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Jeff Browna032cc02011-03-07 16:56:21 -08002178 // Append additional motion samples.
2179 MotionSample* nextMotionSample = firstMotionSample->next;
2180 for (; nextMotionSample != NULL; nextMotionSample = nextMotionSample->next) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002181 if (usingCoords == scaledCoords) {
Kenny Root7a9db182011-06-02 15:16:05 -07002182 if (!(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
2183 for (size_t i = 0; i < motionEntry->pointerCount; i++) {
2184 scaledCoords[i] = nextMotionSample->pointerCoords[i];
2185 scaledCoords[i].scale(scaleFactor);
2186 }
Dianne Hackborn2ba3e802011-05-11 10:59:54 -07002187 }
2188 } else {
2189 usingCoords = nextMotionSample->pointerCoords;
Dianne Hackborne7d25b72011-05-09 21:19:26 -07002190 }
Jeff Browna032cc02011-03-07 16:56:21 -08002191 status = connection->inputPublisher.appendMotionSample(
Dianne Hackbornaa9d84c2011-05-09 19:00:59 -07002192 nextMotionSample->eventTime, usingCoords);
Jeff Browna032cc02011-03-07 16:56:21 -08002193 if (status == NO_MEMORY) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002194#if DEBUG_DISPATCH_CYCLE
2195 LOGD("channel '%s' ~ Shared memory buffer full. Some motion samples will "
2196 "be sent in the next dispatch cycle.",
2197 connection->getInputChannelName());
2198#endif
Jeff Browna032cc02011-03-07 16:56:21 -08002199 break;
2200 }
2201 if (status != OK) {
2202 LOGE("channel '%s' ~ Could not append motion sample "
2203 "for a reason other than out of memory, status=%d",
2204 connection->getInputChannelName(), status);
2205 abortBrokenDispatchCycleLocked(currentTime, connection);
2206 return;
2207 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002208 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002209
Jeff Browna032cc02011-03-07 16:56:21 -08002210 // Remember the next motion sample that we could not dispatch, in case we ran out
2211 // of space in the shared memory buffer.
2212 dispatchEntry->tailMotionSample = nextMotionSample;
2213 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002214 break;
2215 }
2216
2217 default: {
Jeff Brownb6110c22011-04-01 16:15:13 -07002218 LOG_ASSERT(false);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002219 }
2220 }
2221
2222 // Send the dispatch signal.
2223 status = connection->inputPublisher.sendDispatchSignal();
2224 if (status) {
2225 LOGE("channel '%s' ~ Could not send dispatch signal, status=%d",
2226 connection->getInputChannelName(), status);
Jeff Brownb6997262010-10-08 22:31:17 -07002227 abortBrokenDispatchCycleLocked(currentTime, connection);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002228 return;
2229 }
2230
2231 // Record information about the newly started dispatch cycle.
Jeff Brown01ce2e92010-09-26 22:20:12 -07002232 connection->lastEventTime = eventEntry->eventTime;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002233 connection->lastDispatchTime = currentTime;
2234
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002235 // Notify other system components.
2236 onDispatchCycleStartedLocked(currentTime, connection);
2237}
2238
Jeff Brown7fbdc842010-06-17 20:52:56 -07002239void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Jeff Brown3915bb82010-11-05 15:02:16 -07002240 const sp<Connection>& connection, bool handled) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002241#if DEBUG_DISPATCH_CYCLE
Jeff Brown9c3cda02010-06-15 01:31:58 -07002242 LOGD("channel '%s' ~ finishDispatchCycle - %01.1fms since event, "
Jeff Brown3915bb82010-11-05 15:02:16 -07002243 "%01.1fms since dispatch, handled=%s",
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002244 connection->getInputChannelName(),
2245 connection->getEventLatencyMillis(currentTime),
Jeff Brown3915bb82010-11-05 15:02:16 -07002246 connection->getDispatchLatencyMillis(currentTime),
2247 toString(handled));
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002248#endif
2249
Jeff Brown9c3cda02010-06-15 01:31:58 -07002250 if (connection->status == Connection::STATUS_BROKEN
2251 || connection->status == Connection::STATUS_ZOMBIE) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002252 return;
2253 }
2254
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002255 // Reset the publisher since the event has been consumed.
2256 // We do this now so that the publisher can release some of its internal resources
2257 // while waiting for the next dispatch cycle to begin.
2258 status_t status = connection->inputPublisher.reset();
2259 if (status) {
2260 LOGE("channel '%s' ~ Could not reset publisher, status=%d",
2261 connection->getInputChannelName(), status);
Jeff Brownb6997262010-10-08 22:31:17 -07002262 abortBrokenDispatchCycleLocked(currentTime, connection);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002263 return;
2264 }
2265
Jeff Brown3915bb82010-11-05 15:02:16 -07002266 // Notify other system components and prepare to start the next dispatch cycle.
2267 onDispatchCycleFinishedLocked(currentTime, connection, handled);
Jeff Brownb88102f2010-09-08 11:49:43 -07002268}
2269
2270void InputDispatcher::startNextDispatchCycleLocked(nsecs_t currentTime,
2271 const sp<Connection>& connection) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002272 // Start the next dispatch cycle for this connection.
2273 while (! connection->outboundQueue.isEmpty()) {
Jeff Brownac386072011-07-20 15:19:50 -07002274 DispatchEntry* dispatchEntry = connection->outboundQueue.head;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002275 if (dispatchEntry->inProgress) {
2276 // Finish or resume current event in progress.
2277 if (dispatchEntry->tailMotionSample) {
2278 // We have a tail of undispatched motion samples.
2279 // Reuse the same DispatchEntry and start a new cycle.
2280 dispatchEntry->inProgress = false;
2281 dispatchEntry->headMotionSample = dispatchEntry->tailMotionSample;
2282 dispatchEntry->tailMotionSample = NULL;
Jeff Brown519e0242010-09-15 15:18:56 -07002283 startDispatchCycleLocked(currentTime, connection);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002284 return;
2285 }
2286 // Finished.
2287 connection->outboundQueue.dequeueAtHead();
Jeff Brown519e0242010-09-15 15:18:56 -07002288 if (dispatchEntry->hasForegroundTarget()) {
2289 decrementPendingForegroundDispatchesLocked(dispatchEntry->eventEntry);
Jeff Brown6ec402b2010-07-28 15:48:59 -07002290 }
Jeff Brownac386072011-07-20 15:19:50 -07002291 delete dispatchEntry;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002292 } else {
2293 // If the head is not in progress, then we must have already dequeued the in
Jeff Brown519e0242010-09-15 15:18:56 -07002294 // progress event, which means we actually aborted it.
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002295 // So just start the next event for this connection.
Jeff Brown519e0242010-09-15 15:18:56 -07002296 startDispatchCycleLocked(currentTime, connection);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002297 return;
2298 }
2299 }
2300
2301 // Outbound queue is empty, deactivate the connection.
Jeff Brown7fbdc842010-06-17 20:52:56 -07002302 deactivateConnectionLocked(connection.get());
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002303}
2304
Jeff Brownb6997262010-10-08 22:31:17 -07002305void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
2306 const sp<Connection>& connection) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002307#if DEBUG_DISPATCH_CYCLE
Jeff Brown83c09682010-12-23 17:50:18 -08002308 LOGD("channel '%s' ~ abortBrokenDispatchCycle",
2309 connection->getInputChannelName());
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002310#endif
2311
Jeff Brownb88102f2010-09-08 11:49:43 -07002312 // Clear the outbound queue.
Jeff Brown519e0242010-09-15 15:18:56 -07002313 drainOutboundQueueLocked(connection.get());
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002314
Jeff Brownb6997262010-10-08 22:31:17 -07002315 // The connection appears to be unrecoverably broken.
Jeff Brown9c3cda02010-06-15 01:31:58 -07002316 // Ignore already broken or zombie connections.
Jeff Brownb6997262010-10-08 22:31:17 -07002317 if (connection->status == Connection::STATUS_NORMAL) {
2318 connection->status = Connection::STATUS_BROKEN;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002319
Jeff Brownb6997262010-10-08 22:31:17 -07002320 // Notify other system components.
2321 onDispatchCycleBrokenLocked(currentTime, connection);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002322 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002323}
2324
Jeff Brown519e0242010-09-15 15:18:56 -07002325void InputDispatcher::drainOutboundQueueLocked(Connection* connection) {
2326 while (! connection->outboundQueue.isEmpty()) {
2327 DispatchEntry* dispatchEntry = connection->outboundQueue.dequeueAtHead();
2328 if (dispatchEntry->hasForegroundTarget()) {
2329 decrementPendingForegroundDispatchesLocked(dispatchEntry->eventEntry);
Jeff Brownb88102f2010-09-08 11:49:43 -07002330 }
Jeff Brownac386072011-07-20 15:19:50 -07002331 delete dispatchEntry;
Jeff Brownb88102f2010-09-08 11:49:43 -07002332 }
2333
Jeff Brown519e0242010-09-15 15:18:56 -07002334 deactivateConnectionLocked(connection);
Jeff Brownb88102f2010-09-08 11:49:43 -07002335}
2336
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002337int InputDispatcher::handleReceiveCallback(int receiveFd, int events, void* data) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002338 InputDispatcher* d = static_cast<InputDispatcher*>(data);
2339
2340 { // acquire lock
2341 AutoMutex _l(d->mLock);
2342
2343 ssize_t connectionIndex = d->mConnectionsByReceiveFd.indexOfKey(receiveFd);
2344 if (connectionIndex < 0) {
2345 LOGE("Received spurious receive callback for unknown input channel. "
2346 "fd=%d, events=0x%x", receiveFd, events);
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002347 return 0; // remove the callback
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002348 }
2349
Jeff Brown7fbdc842010-06-17 20:52:56 -07002350 nsecs_t currentTime = now();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002351
2352 sp<Connection> connection = d->mConnectionsByReceiveFd.valueAt(connectionIndex);
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002353 if (events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP)) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002354 LOGE("channel '%s' ~ Consumer closed input channel or an error occurred. "
2355 "events=0x%x", connection->getInputChannelName(), events);
Jeff Brownb6997262010-10-08 22:31:17 -07002356 d->abortBrokenDispatchCycleLocked(currentTime, connection);
Jeff Brown9c3cda02010-06-15 01:31:58 -07002357 d->runCommandsLockedInterruptible();
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002358 return 0; // remove the callback
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002359 }
2360
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002361 if (! (events & ALOOPER_EVENT_INPUT)) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002362 LOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
2363 "events=0x%x", connection->getInputChannelName(), events);
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002364 return 1;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002365 }
2366
Jeff Brown3915bb82010-11-05 15:02:16 -07002367 bool handled = false;
Jeff Brown49ed71d2010-12-06 17:13:33 -08002368 status_t status = connection->inputPublisher.receiveFinishedSignal(&handled);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002369 if (status) {
2370 LOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
2371 connection->getInputChannelName(), status);
Jeff Brownb6997262010-10-08 22:31:17 -07002372 d->abortBrokenDispatchCycleLocked(currentTime, connection);
Jeff Brown9c3cda02010-06-15 01:31:58 -07002373 d->runCommandsLockedInterruptible();
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002374 return 0; // remove the callback
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002375 }
2376
Jeff Brown3915bb82010-11-05 15:02:16 -07002377 d->finishDispatchCycleLocked(currentTime, connection, handled);
Jeff Brown9c3cda02010-06-15 01:31:58 -07002378 d->runCommandsLockedInterruptible();
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002379 return 1;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002380 } // release lock
2381}
2382
Jeff Brownb6997262010-10-08 22:31:17 -07002383void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Jeff Brownda3d5a92011-03-29 15:11:34 -07002384 const CancelationOptions& options) {
Jeff Brownb6997262010-10-08 22:31:17 -07002385 for (size_t i = 0; i < mConnectionsByReceiveFd.size(); i++) {
2386 synthesizeCancelationEventsForConnectionLocked(
Jeff Brownda3d5a92011-03-29 15:11:34 -07002387 mConnectionsByReceiveFd.valueAt(i), options);
Jeff Brownb6997262010-10-08 22:31:17 -07002388 }
2389}
2390
2391void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Jeff Brownda3d5a92011-03-29 15:11:34 -07002392 const sp<InputChannel>& channel, const CancelationOptions& options) {
Jeff Brownb6997262010-10-08 22:31:17 -07002393 ssize_t index = getConnectionIndexLocked(channel);
2394 if (index >= 0) {
2395 synthesizeCancelationEventsForConnectionLocked(
Jeff Brownda3d5a92011-03-29 15:11:34 -07002396 mConnectionsByReceiveFd.valueAt(index), options);
Jeff Brownb6997262010-10-08 22:31:17 -07002397 }
2398}
2399
2400void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
Jeff Brownda3d5a92011-03-29 15:11:34 -07002401 const sp<Connection>& connection, const CancelationOptions& options) {
Jeff Brownb6997262010-10-08 22:31:17 -07002402 nsecs_t currentTime = now();
2403
2404 mTempCancelationEvents.clear();
Jeff Brownac386072011-07-20 15:19:50 -07002405 connection->inputState.synthesizeCancelationEvents(currentTime,
Jeff Brownb6997262010-10-08 22:31:17 -07002406 mTempCancelationEvents, options);
2407
2408 if (! mTempCancelationEvents.isEmpty()
2409 && connection->status != Connection::STATUS_BROKEN) {
2410#if DEBUG_OUTBOUND_EVENT_DETAILS
2411 LOGD("channel '%s' ~ Synthesized %d cancelation events to bring channel back in sync "
Jeff Brownda3d5a92011-03-29 15:11:34 -07002412 "with reality: %s, mode=%d.",
2413 connection->getInputChannelName(), mTempCancelationEvents.size(),
2414 options.reason, options.mode);
Jeff Brownb6997262010-10-08 22:31:17 -07002415#endif
2416 for (size_t i = 0; i < mTempCancelationEvents.size(); i++) {
2417 EventEntry* cancelationEventEntry = mTempCancelationEvents.itemAt(i);
2418 switch (cancelationEventEntry->type) {
2419 case EventEntry::TYPE_KEY:
2420 logOutboundKeyDetailsLocked("cancel - ",
2421 static_cast<KeyEntry*>(cancelationEventEntry));
2422 break;
2423 case EventEntry::TYPE_MOTION:
2424 logOutboundMotionDetailsLocked("cancel - ",
2425 static_cast<MotionEntry*>(cancelationEventEntry));
2426 break;
2427 }
2428
Jeff Brown81346812011-06-28 20:08:48 -07002429 InputTarget target;
Jeff Brown9302c872011-07-13 22:51:29 -07002430 sp<InputWindowHandle> windowHandle = getWindowHandleLocked(connection->inputChannel);
2431 if (windowHandle != NULL) {
2432 target.xOffset = -windowHandle->frameLeft;
2433 target.yOffset = -windowHandle->frameTop;
2434 target.scaleFactor = windowHandle->scaleFactor;
Jeff Brownb6997262010-10-08 22:31:17 -07002435 } else {
Jeff Brown81346812011-06-28 20:08:48 -07002436 target.xOffset = 0;
2437 target.yOffset = 0;
2438 target.scaleFactor = 1.0f;
Jeff Brownb6997262010-10-08 22:31:17 -07002439 }
Jeff Brown81346812011-06-28 20:08:48 -07002440 target.inputChannel = connection->inputChannel;
2441 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
Jeff Brownb6997262010-10-08 22:31:17 -07002442
Jeff Brown81346812011-06-28 20:08:48 -07002443 enqueueDispatchEntryLocked(connection, cancelationEventEntry, // increments ref
2444 &target, false, InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brownb6997262010-10-08 22:31:17 -07002445
Jeff Brownac386072011-07-20 15:19:50 -07002446 cancelationEventEntry->release();
Jeff Brownb6997262010-10-08 22:31:17 -07002447 }
2448
Jeff Brownac386072011-07-20 15:19:50 -07002449 if (!connection->outboundQueue.head->inProgress) {
Jeff Brownb6997262010-10-08 22:31:17 -07002450 startDispatchCycleLocked(currentTime, connection);
2451 }
2452 }
2453}
2454
Jeff Brown01ce2e92010-09-26 22:20:12 -07002455InputDispatcher::MotionEntry*
2456InputDispatcher::splitMotionEvent(const MotionEntry* originalMotionEntry, BitSet32 pointerIds) {
Jeff Brownb6110c22011-04-01 16:15:13 -07002457 LOG_ASSERT(pointerIds.value != 0);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002458
2459 uint32_t splitPointerIndexMap[MAX_POINTERS];
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002460 PointerProperties splitPointerProperties[MAX_POINTERS];
Jeff Brown01ce2e92010-09-26 22:20:12 -07002461 PointerCoords splitPointerCoords[MAX_POINTERS];
2462
2463 uint32_t originalPointerCount = originalMotionEntry->pointerCount;
2464 uint32_t splitPointerCount = 0;
2465
2466 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
2467 originalPointerIndex++) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002468 const PointerProperties& pointerProperties =
2469 originalMotionEntry->pointerProperties[originalPointerIndex];
2470 uint32_t pointerId = uint32_t(pointerProperties.id);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002471 if (pointerIds.hasBit(pointerId)) {
2472 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002473 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
Jeff Brownace13b12011-03-09 17:39:48 -08002474 splitPointerCoords[splitPointerCount].copyFrom(
2475 originalMotionEntry->firstSample.pointerCoords[originalPointerIndex]);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002476 splitPointerCount += 1;
2477 }
2478 }
Jeff Brown58a2da82011-01-25 16:02:22 -08002479
2480 if (splitPointerCount != pointerIds.count()) {
2481 // This is bad. We are missing some of the pointers that we expected to deliver.
2482 // Most likely this indicates that we received an ACTION_MOVE events that has
2483 // different pointer ids than we expected based on the previous ACTION_DOWN
2484 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
2485 // in this way.
2486 LOGW("Dropping split motion event because the pointer count is %d but "
2487 "we expected there to be %d pointers. This probably means we received "
2488 "a broken sequence of pointer ids from the input device.",
2489 splitPointerCount, pointerIds.count());
2490 return NULL;
2491 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07002492
2493 int32_t action = originalMotionEntry->action;
2494 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
2495 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
2496 || maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2497 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002498 const PointerProperties& pointerProperties =
2499 originalMotionEntry->pointerProperties[originalPointerIndex];
2500 uint32_t pointerId = uint32_t(pointerProperties.id);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002501 if (pointerIds.hasBit(pointerId)) {
2502 if (pointerIds.count() == 1) {
2503 // The first/last pointer went down/up.
2504 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
2505 ? AMOTION_EVENT_ACTION_DOWN : AMOTION_EVENT_ACTION_UP;
Jeff Brown9a01d052010-09-27 16:35:11 -07002506 } else {
2507 // A secondary pointer went down/up.
2508 uint32_t splitPointerIndex = 0;
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002509 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
Jeff Brown9a01d052010-09-27 16:35:11 -07002510 splitPointerIndex += 1;
2511 }
2512 action = maskedAction | (splitPointerIndex
2513 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002514 }
2515 } else {
2516 // An unrelated pointer changed.
2517 action = AMOTION_EVENT_ACTION_MOVE;
2518 }
2519 }
2520
Jeff Brownac386072011-07-20 15:19:50 -07002521 MotionEntry* splitMotionEntry = new MotionEntry(
Jeff Brown01ce2e92010-09-26 22:20:12 -07002522 originalMotionEntry->eventTime,
2523 originalMotionEntry->deviceId,
2524 originalMotionEntry->source,
2525 originalMotionEntry->policyFlags,
2526 action,
2527 originalMotionEntry->flags,
2528 originalMotionEntry->metaState,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002529 originalMotionEntry->buttonState,
Jeff Brown01ce2e92010-09-26 22:20:12 -07002530 originalMotionEntry->edgeFlags,
2531 originalMotionEntry->xPrecision,
2532 originalMotionEntry->yPrecision,
2533 originalMotionEntry->downTime,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002534 splitPointerCount, splitPointerProperties, splitPointerCoords);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002535
2536 for (MotionSample* originalMotionSample = originalMotionEntry->firstSample.next;
2537 originalMotionSample != NULL; originalMotionSample = originalMotionSample->next) {
2538 for (uint32_t splitPointerIndex = 0; splitPointerIndex < splitPointerCount;
2539 splitPointerIndex++) {
2540 uint32_t originalPointerIndex = splitPointerIndexMap[splitPointerIndex];
Jeff Brownace13b12011-03-09 17:39:48 -08002541 splitPointerCoords[splitPointerIndex].copyFrom(
2542 originalMotionSample->pointerCoords[originalPointerIndex]);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002543 }
2544
Jeff Brownac386072011-07-20 15:19:50 -07002545 splitMotionEntry->appendSample(originalMotionSample->eventTime, splitPointerCoords);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002546 }
2547
Jeff Browna032cc02011-03-07 16:56:21 -08002548 if (originalMotionEntry->injectionState) {
2549 splitMotionEntry->injectionState = originalMotionEntry->injectionState;
2550 splitMotionEntry->injectionState->refCount += 1;
2551 }
2552
Jeff Brown01ce2e92010-09-26 22:20:12 -07002553 return splitMotionEntry;
2554}
2555
Jeff Brownbe1aa822011-07-27 16:04:54 -07002556void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002557#if DEBUG_INBOUND_EVENT_DETAILS
Jeff Brownbe1aa822011-07-27 16:04:54 -07002558 LOGD("notifyConfigurationChanged - eventTime=%lld", args->eventTime);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002559#endif
2560
Jeff Brownb88102f2010-09-08 11:49:43 -07002561 bool needWake;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002562 { // acquire lock
2563 AutoMutex _l(mLock);
2564
Jeff Brownbe1aa822011-07-27 16:04:54 -07002565 ConfigurationChangedEntry* newEntry = new ConfigurationChangedEntry(args->eventTime);
Jeff Brownb88102f2010-09-08 11:49:43 -07002566 needWake = enqueueInboundEventLocked(newEntry);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002567 } // release lock
2568
Jeff Brownb88102f2010-09-08 11:49:43 -07002569 if (needWake) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002570 mLooper->wake();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002571 }
2572}
2573
Jeff Brownbe1aa822011-07-27 16:04:54 -07002574void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002575#if DEBUG_INBOUND_EVENT_DETAILS
Jeff Brown90655042010-12-02 13:50:46 -08002576 LOGD("notifyKey - eventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, action=0x%x, "
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002577 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%lld",
Jeff Brownbe1aa822011-07-27 16:04:54 -07002578 args->eventTime, args->deviceId, args->source, args->policyFlags,
2579 args->action, args->flags, args->keyCode, args->scanCode,
2580 args->metaState, args->downTime);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002581#endif
Jeff Brownbe1aa822011-07-27 16:04:54 -07002582 if (!validateKeyEvent(args->action)) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002583 return;
2584 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002585
Jeff Brownbe1aa822011-07-27 16:04:54 -07002586 uint32_t policyFlags = args->policyFlags;
2587 int32_t flags = args->flags;
2588 int32_t metaState = args->metaState;
Jeff Brown1f245102010-11-18 20:53:46 -08002589 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
2590 policyFlags |= POLICY_FLAG_VIRTUAL;
2591 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
2592 }
Jeff Brown924c4d42011-03-07 16:40:47 -08002593 if (policyFlags & POLICY_FLAG_ALT) {
2594 metaState |= AMETA_ALT_ON | AMETA_ALT_LEFT_ON;
2595 }
2596 if (policyFlags & POLICY_FLAG_ALT_GR) {
2597 metaState |= AMETA_ALT_ON | AMETA_ALT_RIGHT_ON;
2598 }
2599 if (policyFlags & POLICY_FLAG_SHIFT) {
2600 metaState |= AMETA_SHIFT_ON | AMETA_SHIFT_LEFT_ON;
2601 }
2602 if (policyFlags & POLICY_FLAG_CAPS_LOCK) {
2603 metaState |= AMETA_CAPS_LOCK_ON;
2604 }
2605 if (policyFlags & POLICY_FLAG_FUNCTION) {
2606 metaState |= AMETA_FUNCTION_ON;
2607 }
Jeff Brown1f245102010-11-18 20:53:46 -08002608
Jeff Browne20c9e02010-10-11 14:20:19 -07002609 policyFlags |= POLICY_FLAG_TRUSTED;
Jeff Brown1f245102010-11-18 20:53:46 -08002610
2611 KeyEvent event;
Jeff Brownbe1aa822011-07-27 16:04:54 -07002612 event.initialize(args->deviceId, args->source, args->action,
2613 flags, args->keyCode, args->scanCode, metaState, 0,
2614 args->downTime, args->eventTime);
Jeff Brown1f245102010-11-18 20:53:46 -08002615
2616 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
2617
2618 if (policyFlags & POLICY_FLAG_WOKE_HERE) {
2619 flags |= AKEY_EVENT_FLAG_WOKE_HERE;
2620 }
Jeff Brownb6997262010-10-08 22:31:17 -07002621
Jeff Brownb88102f2010-09-08 11:49:43 -07002622 bool needWake;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002623 { // acquire lock
Jeff Brown0029c662011-03-30 02:25:18 -07002624 mLock.lock();
2625
2626 if (mInputFilterEnabled) {
2627 mLock.unlock();
2628
2629 policyFlags |= POLICY_FLAG_FILTERED;
2630 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2631 return; // event was consumed by the filter
2632 }
2633
2634 mLock.lock();
2635 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002636
Jeff Brown7fbdc842010-06-17 20:52:56 -07002637 int32_t repeatCount = 0;
Jeff Brownbe1aa822011-07-27 16:04:54 -07002638 KeyEntry* newEntry = new KeyEntry(args->eventTime,
2639 args->deviceId, args->source, policyFlags,
2640 args->action, flags, args->keyCode, args->scanCode,
2641 metaState, repeatCount, args->downTime);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002642
Jeff Brownb88102f2010-09-08 11:49:43 -07002643 needWake = enqueueInboundEventLocked(newEntry);
Jeff Brown0029c662011-03-30 02:25:18 -07002644 mLock.unlock();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002645 } // release lock
2646
Jeff Brownb88102f2010-09-08 11:49:43 -07002647 if (needWake) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002648 mLooper->wake();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002649 }
2650}
2651
Jeff Brownbe1aa822011-07-27 16:04:54 -07002652void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002653#if DEBUG_INBOUND_EVENT_DETAILS
Jeff Brown90655042010-12-02 13:50:46 -08002654 LOGD("notifyMotion - eventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, "
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002655 "action=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, edgeFlags=0x%x, "
Jeff Brown85a31762010-09-01 17:01:00 -07002656 "xPrecision=%f, yPrecision=%f, downTime=%lld",
Jeff Brownbe1aa822011-07-27 16:04:54 -07002657 args->eventTime, args->deviceId, args->source, args->policyFlags,
2658 args->action, args->flags, args->metaState, args->buttonState,
2659 args->edgeFlags, args->xPrecision, args->yPrecision, args->downTime);
2660 for (uint32_t i = 0; i < args->pointerCount; i++) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002661 LOGD(" Pointer %d: id=%d, toolType=%d, "
2662 "x=%f, y=%f, pressure=%f, size=%f, "
Jeff Brown85a31762010-09-01 17:01:00 -07002663 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
Jeff Brown8d608662010-08-30 03:02:23 -07002664 "orientation=%f",
Jeff Brownbe1aa822011-07-27 16:04:54 -07002665 i, args->pointerProperties[i].id,
2666 args->pointerProperties[i].toolType,
2667 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
2668 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
2669 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
2670 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
2671 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
2672 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
2673 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
2674 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
2675 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002676 }
2677#endif
Jeff Brownbe1aa822011-07-27 16:04:54 -07002678 if (!validateMotionEvent(args->action, args->pointerCount, args->pointerProperties)) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002679 return;
2680 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002681
Jeff Brownbe1aa822011-07-27 16:04:54 -07002682 uint32_t policyFlags = args->policyFlags;
Jeff Browne20c9e02010-10-11 14:20:19 -07002683 policyFlags |= POLICY_FLAG_TRUSTED;
Jeff Brownbe1aa822011-07-27 16:04:54 -07002684 mPolicy->interceptMotionBeforeQueueing(args->eventTime, /*byref*/ policyFlags);
Jeff Brownb6997262010-10-08 22:31:17 -07002685
Jeff Brownb88102f2010-09-08 11:49:43 -07002686 bool needWake;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002687 { // acquire lock
Jeff Brown0029c662011-03-30 02:25:18 -07002688 mLock.lock();
2689
2690 if (mInputFilterEnabled) {
2691 mLock.unlock();
2692
2693 MotionEvent event;
Jeff Brownbe1aa822011-07-27 16:04:54 -07002694 event.initialize(args->deviceId, args->source, args->action, args->flags,
2695 args->edgeFlags, args->metaState, args->buttonState, 0, 0,
2696 args->xPrecision, args->yPrecision,
2697 args->downTime, args->eventTime,
2698 args->pointerCount, args->pointerProperties, args->pointerCoords);
Jeff Brown0029c662011-03-30 02:25:18 -07002699
2700 policyFlags |= POLICY_FLAG_FILTERED;
2701 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2702 return; // event was consumed by the filter
2703 }
2704
2705 mLock.lock();
2706 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002707
2708 // Attempt batching and streaming of move events.
Jeff Brownbe1aa822011-07-27 16:04:54 -07002709 if (args->action == AMOTION_EVENT_ACTION_MOVE
2710 || args->action == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002711 // BATCHING CASE
2712 //
2713 // Try to append a move sample to the tail of the inbound queue for this device.
2714 // Give up if we encounter a non-move motion event for this device since that
2715 // means we cannot append any new samples until a new motion event has started.
Jeff Brownac386072011-07-20 15:19:50 -07002716 for (EventEntry* entry = mInboundQueue.tail; entry; entry = entry->prev) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002717 if (entry->type != EventEntry::TYPE_MOTION) {
2718 // Keep looking for motion events.
2719 continue;
2720 }
2721
2722 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
Jeff Brownbe1aa822011-07-27 16:04:54 -07002723 if (motionEntry->deviceId != args->deviceId
2724 || motionEntry->source != args->source) {
Jeff Brownefd32662011-03-08 15:13:06 -08002725 // Keep looking for this device and source.
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002726 continue;
2727 }
2728
Jeff Brownbe1aa822011-07-27 16:04:54 -07002729 if (!motionEntry->canAppendSamples(args->action,
2730 args->pointerCount, args->pointerProperties)) {
Jeff Brownefd32662011-03-08 15:13:06 -08002731 // Last motion event in the queue for this device and source is
2732 // not compatible for appending new samples. Stop here.
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002733 goto NoBatchingOrStreaming;
2734 }
2735
Jeff Brown9c3cda02010-06-15 01:31:58 -07002736 // Do the batching magic.
Jeff Brownbe1aa822011-07-27 16:04:54 -07002737 batchMotionLocked(motionEntry, args->eventTime,
2738 args->metaState, args->pointerCoords,
Jeff Brown4e91a182011-04-07 11:38:09 -07002739 "most recent motion event for this device and source in the inbound queue");
Jeff Brown0029c662011-03-30 02:25:18 -07002740 mLock.unlock();
Jeff Brown9c3cda02010-06-15 01:31:58 -07002741 return; // done!
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002742 }
2743
Jeff Brownf6989da2011-04-06 17:19:48 -07002744 // BATCHING ONTO PENDING EVENT CASE
2745 //
2746 // Try to append a move sample to the currently pending event, if there is one.
2747 // We can do this as long as we are still waiting to find the targets for the
2748 // event. Once the targets are locked-in we can only do streaming.
2749 if (mPendingEvent
2750 && (!mPendingEvent->dispatchInProgress || !mCurrentInputTargetsValid)
2751 && mPendingEvent->type == EventEntry::TYPE_MOTION) {
2752 MotionEntry* motionEntry = static_cast<MotionEntry*>(mPendingEvent);
Jeff Brownbe1aa822011-07-27 16:04:54 -07002753 if (motionEntry->deviceId == args->deviceId
2754 && motionEntry->source == args->source) {
2755 if (!motionEntry->canAppendSamples(args->action,
2756 args->pointerCount, args->pointerProperties)) {
Jeff Brown4e91a182011-04-07 11:38:09 -07002757 // Pending motion event is for this device and source but it is
2758 // not compatible for appending new samples. Stop here.
Jeff Brownf6989da2011-04-06 17:19:48 -07002759 goto NoBatchingOrStreaming;
2760 }
2761
Jeff Brownf6989da2011-04-06 17:19:48 -07002762 // Do the batching magic.
Jeff Brownbe1aa822011-07-27 16:04:54 -07002763 batchMotionLocked(motionEntry, args->eventTime,
2764 args->metaState, args->pointerCoords,
Jeff Brown4e91a182011-04-07 11:38:09 -07002765 "pending motion event");
Jeff Brownf6989da2011-04-06 17:19:48 -07002766 mLock.unlock();
2767 return; // done!
2768 }
2769 }
2770
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002771 // STREAMING CASE
2772 //
2773 // There is no pending motion event (of any kind) for this device in the inbound queue.
Jeff Brown519e0242010-09-15 15:18:56 -07002774 // Search the outbound queue for the current foreground targets to find a dispatched
2775 // motion event that is still in progress. If found, then, appen the new sample to
2776 // that event and push it out to all current targets. The logic in
2777 // prepareDispatchCycleLocked takes care of the case where some targets may
2778 // already have consumed the motion event by starting a new dispatch cycle if needed.
Jeff Brown9c3cda02010-06-15 01:31:58 -07002779 if (mCurrentInputTargetsValid) {
Jeff Brown519e0242010-09-15 15:18:56 -07002780 for (size_t i = 0; i < mCurrentInputTargets.size(); i++) {
2781 const InputTarget& inputTarget = mCurrentInputTargets[i];
2782 if ((inputTarget.flags & InputTarget::FLAG_FOREGROUND) == 0) {
2783 // Skip non-foreground targets. We only want to stream if there is at
2784 // least one foreground target whose dispatch is still in progress.
2785 continue;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002786 }
Jeff Brown519e0242010-09-15 15:18:56 -07002787
2788 ssize_t connectionIndex = getConnectionIndexLocked(inputTarget.inputChannel);
2789 if (connectionIndex < 0) {
2790 // Connection must no longer be valid.
2791 continue;
2792 }
2793
2794 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
2795 if (connection->outboundQueue.isEmpty()) {
2796 // This foreground target has an empty outbound queue.
2797 continue;
2798 }
2799
Jeff Brownac386072011-07-20 15:19:50 -07002800 DispatchEntry* dispatchEntry = connection->outboundQueue.head;
Jeff Brown519e0242010-09-15 15:18:56 -07002801 if (! dispatchEntry->inProgress
Jeff Brown01ce2e92010-09-26 22:20:12 -07002802 || dispatchEntry->eventEntry->type != EventEntry::TYPE_MOTION
2803 || dispatchEntry->isSplit()) {
2804 // No motion event is being dispatched, or it is being split across
2805 // windows in which case we cannot stream.
Jeff Brown519e0242010-09-15 15:18:56 -07002806 continue;
2807 }
2808
2809 MotionEntry* motionEntry = static_cast<MotionEntry*>(
2810 dispatchEntry->eventEntry);
Jeff Brownbe1aa822011-07-27 16:04:54 -07002811 if (motionEntry->action != args->action
2812 || motionEntry->deviceId != args->deviceId
2813 || motionEntry->source != args->source
2814 || motionEntry->pointerCount != args->pointerCount
Jeff Brown519e0242010-09-15 15:18:56 -07002815 || motionEntry->isInjected()) {
2816 // The motion event is not compatible with this move.
2817 continue;
2818 }
2819
Jeff Brownbe1aa822011-07-27 16:04:54 -07002820 if (args->action == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Jeff Brown9302c872011-07-13 22:51:29 -07002821 if (mLastHoverWindowHandle == NULL) {
Jeff Browna032cc02011-03-07 16:56:21 -08002822#if DEBUG_BATCHING
2823 LOGD("Not streaming hover move because there is no "
2824 "last hovered window.");
2825#endif
2826 goto NoBatchingOrStreaming;
2827 }
2828
Jeff Brown9302c872011-07-13 22:51:29 -07002829 sp<InputWindowHandle> hoverWindowHandle = findTouchedWindowAtLocked(
Jeff Brownbe1aa822011-07-27 16:04:54 -07002830 args->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X),
2831 args->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Jeff Brown9302c872011-07-13 22:51:29 -07002832 if (mLastHoverWindowHandle != hoverWindowHandle) {
Jeff Browna032cc02011-03-07 16:56:21 -08002833#if DEBUG_BATCHING
2834 LOGD("Not streaming hover move because the last hovered window "
2835 "is '%s' but the currently hovered window is '%s'.",
Jeff Brown9302c872011-07-13 22:51:29 -07002836 mLastHoverWindowHandle->name.string(),
2837 hoverWindowHandle != NULL
2838 ? hoverWindowHandle->name.string() : "<null>");
Jeff Browna032cc02011-03-07 16:56:21 -08002839#endif
2840 goto NoBatchingOrStreaming;
2841 }
2842 }
2843
Jeff Brown519e0242010-09-15 15:18:56 -07002844 // Hurray! This foreground target is currently dispatching a move event
2845 // that we can stream onto. Append the motion sample and resume dispatch.
Jeff Brownbe1aa822011-07-27 16:04:54 -07002846 motionEntry->appendSample(args->eventTime, args->pointerCoords);
Jeff Brown519e0242010-09-15 15:18:56 -07002847#if DEBUG_BATCHING
2848 LOGD("Appended motion sample onto batch for most recently dispatched "
Jeff Brown4e91a182011-04-07 11:38:09 -07002849 "motion event for this device and source in the outbound queues. "
Jeff Brown519e0242010-09-15 15:18:56 -07002850 "Attempting to stream the motion sample.");
2851#endif
2852 nsecs_t currentTime = now();
2853 dispatchEventToCurrentInputTargetsLocked(currentTime, motionEntry,
2854 true /*resumeWithAppendedMotionSample*/);
2855
2856 runCommandsLockedInterruptible();
Jeff Brown0029c662011-03-30 02:25:18 -07002857 mLock.unlock();
Jeff Brown519e0242010-09-15 15:18:56 -07002858 return; // done!
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002859 }
2860 }
2861
2862NoBatchingOrStreaming:;
2863 }
2864
2865 // Just enqueue a new motion event.
Jeff Brownbe1aa822011-07-27 16:04:54 -07002866 MotionEntry* newEntry = new MotionEntry(args->eventTime,
2867 args->deviceId, args->source, policyFlags,
2868 args->action, args->flags, args->metaState, args->buttonState,
2869 args->edgeFlags, args->xPrecision, args->yPrecision, args->downTime,
2870 args->pointerCount, args->pointerProperties, args->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.
Jeff Brownac386072011-07-20 15:19:50 -07002904 entry->appendSample(eventTime, pointerCoords);
Jeff Brown4e91a182011-04-07 11:38:09 -07002905#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 Brownbe1aa822011-07-27 16:04:54 -07002911void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
Jeff Brownb6997262010-10-08 22:31:17 -07002912#if DEBUG_INBOUND_EVENT_DETAILS
Jeff Brownbe1aa822011-07-27 16:04:54 -07002913 LOGD("notifySwitch - eventTime=%lld, policyFlags=0x%x, switchCode=%d, switchValue=%d",
2914 args->eventTime, args->policyFlags,
2915 args->switchCode, args->switchValue);
Jeff Brownb6997262010-10-08 22:31:17 -07002916#endif
2917
Jeff Brownbe1aa822011-07-27 16:04:54 -07002918 uint32_t policyFlags = args->policyFlags;
Jeff Browne20c9e02010-10-11 14:20:19 -07002919 policyFlags |= POLICY_FLAG_TRUSTED;
Jeff Brownbe1aa822011-07-27 16:04:54 -07002920 mPolicy->notifySwitch(args->eventTime,
2921 args->switchCode, args->switchValue, policyFlags);
Jeff Brownb6997262010-10-08 22:31:17 -07002922}
2923
Jeff Brown7fbdc842010-06-17 20:52:56 -07002924int32_t InputDispatcher::injectInputEvent(const InputEvent* event,
Jeff Brown0029c662011-03-30 02:25:18 -07002925 int32_t injectorPid, int32_t injectorUid, int32_t syncMode, int32_t timeoutMillis,
2926 uint32_t policyFlags) {
Jeff Brown7fbdc842010-06-17 20:52:56 -07002927#if DEBUG_INBOUND_EVENT_DETAILS
2928 LOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Jeff Brown0029c662011-03-30 02:25:18 -07002929 "syncMode=%d, timeoutMillis=%d, policyFlags=0x%08x",
2930 event->getType(), injectorPid, injectorUid, syncMode, timeoutMillis, policyFlags);
Jeff Brown7fbdc842010-06-17 20:52:56 -07002931#endif
2932
2933 nsecs_t endTime = now() + milliseconds_to_nanoseconds(timeoutMillis);
Jeff Browne20c9e02010-10-11 14:20:19 -07002934
Jeff Brown0029c662011-03-30 02:25:18 -07002935 policyFlags |= POLICY_FLAG_INJECTED;
Jeff Browne20c9e02010-10-11 14:20:19 -07002936 if (hasInjectionPermission(injectorPid, injectorUid)) {
2937 policyFlags |= POLICY_FLAG_TRUSTED;
2938 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07002939
Jeff Brownb6997262010-10-08 22:31:17 -07002940 EventEntry* injectedEntry;
2941 switch (event->getType()) {
2942 case AINPUT_EVENT_TYPE_KEY: {
2943 const KeyEvent* keyEvent = static_cast<const KeyEvent*>(event);
2944 int32_t action = keyEvent->getAction();
2945 if (! validateKeyEvent(action)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07002946 return INPUT_EVENT_INJECTION_FAILED;
2947 }
2948
Jeff Brownb6997262010-10-08 22:31:17 -07002949 int32_t flags = keyEvent->getFlags();
Jeff Brown1f245102010-11-18 20:53:46 -08002950 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
2951 policyFlags |= POLICY_FLAG_VIRTUAL;
2952 }
2953
Jeff Brown0029c662011-03-30 02:25:18 -07002954 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
2955 mPolicy->interceptKeyBeforeQueueing(keyEvent, /*byref*/ policyFlags);
2956 }
Jeff Brown1f245102010-11-18 20:53:46 -08002957
2958 if (policyFlags & POLICY_FLAG_WOKE_HERE) {
2959 flags |= AKEY_EVENT_FLAG_WOKE_HERE;
2960 }
Jeff Brown6ec402b2010-07-28 15:48:59 -07002961
Jeff Brownb6997262010-10-08 22:31:17 -07002962 mLock.lock();
Jeff Brownac386072011-07-20 15:19:50 -07002963 injectedEntry = new KeyEntry(keyEvent->getEventTime(),
Jeff Brown1f245102010-11-18 20:53:46 -08002964 keyEvent->getDeviceId(), keyEvent->getSource(),
2965 policyFlags, action, flags,
2966 keyEvent->getKeyCode(), keyEvent->getScanCode(), keyEvent->getMetaState(),
Jeff Brownb6997262010-10-08 22:31:17 -07002967 keyEvent->getRepeatCount(), keyEvent->getDownTime());
2968 break;
2969 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07002970
Jeff Brownb6997262010-10-08 22:31:17 -07002971 case AINPUT_EVENT_TYPE_MOTION: {
2972 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
2973 int32_t action = motionEvent->getAction();
2974 size_t pointerCount = motionEvent->getPointerCount();
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002975 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
2976 if (! validateMotionEvent(action, pointerCount, pointerProperties)) {
Jeff Brownb6997262010-10-08 22:31:17 -07002977 return INPUT_EVENT_INJECTION_FAILED;
2978 }
2979
Jeff Brown0029c662011-03-30 02:25:18 -07002980 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
2981 nsecs_t eventTime = motionEvent->getEventTime();
2982 mPolicy->interceptMotionBeforeQueueing(eventTime, /*byref*/ policyFlags);
2983 }
Jeff Brownb6997262010-10-08 22:31:17 -07002984
2985 mLock.lock();
2986 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
2987 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
Jeff Brownac386072011-07-20 15:19:50 -07002988 MotionEntry* motionEntry = new MotionEntry(*sampleEventTimes,
Jeff Brownb6997262010-10-08 22:31:17 -07002989 motionEvent->getDeviceId(), motionEvent->getSource(), policyFlags,
2990 action, motionEvent->getFlags(),
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002991 motionEvent->getMetaState(), motionEvent->getButtonState(),
2992 motionEvent->getEdgeFlags(),
Jeff Brownb6997262010-10-08 22:31:17 -07002993 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
2994 motionEvent->getDownTime(), uint32_t(pointerCount),
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002995 pointerProperties, samplePointerCoords);
Jeff Brownb6997262010-10-08 22:31:17 -07002996 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
2997 sampleEventTimes += 1;
2998 samplePointerCoords += pointerCount;
Jeff Brownac386072011-07-20 15:19:50 -07002999 motionEntry->appendSample(*sampleEventTimes, samplePointerCoords);
Jeff Brownb6997262010-10-08 22:31:17 -07003000 }
3001 injectedEntry = motionEntry;
3002 break;
3003 }
3004
3005 default:
3006 LOGW("Cannot inject event of type %d", event->getType());
3007 return INPUT_EVENT_INJECTION_FAILED;
3008 }
3009
Jeff Brownac386072011-07-20 15:19:50 -07003010 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
Jeff Brownb6997262010-10-08 22:31:17 -07003011 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
3012 injectionState->injectionIsAsync = true;
3013 }
3014
3015 injectionState->refCount += 1;
3016 injectedEntry->injectionState = injectionState;
3017
3018 bool needWake = enqueueInboundEventLocked(injectedEntry);
3019 mLock.unlock();
Jeff Brown7fbdc842010-06-17 20:52:56 -07003020
Jeff Brownb88102f2010-09-08 11:49:43 -07003021 if (needWake) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07003022 mLooper->wake();
Jeff Brown7fbdc842010-06-17 20:52:56 -07003023 }
3024
3025 int32_t injectionResult;
3026 { // acquire lock
3027 AutoMutex _l(mLock);
3028
Jeff Brown6ec402b2010-07-28 15:48:59 -07003029 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
3030 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
3031 } else {
3032 for (;;) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07003033 injectionResult = injectionState->injectionResult;
Jeff Brown6ec402b2010-07-28 15:48:59 -07003034 if (injectionResult != INPUT_EVENT_INJECTION_PENDING) {
3035 break;
3036 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07003037
Jeff Brown7fbdc842010-06-17 20:52:56 -07003038 nsecs_t remainingTimeout = endTime - now();
3039 if (remainingTimeout <= 0) {
Jeff Brown6ec402b2010-07-28 15:48:59 -07003040#if DEBUG_INJECTION
3041 LOGD("injectInputEvent - Timed out waiting for injection result "
3042 "to become available.");
3043#endif
Jeff Brown7fbdc842010-06-17 20:52:56 -07003044 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
3045 break;
3046 }
3047
Jeff Brown6ec402b2010-07-28 15:48:59 -07003048 mInjectionResultAvailableCondition.waitRelative(mLock, remainingTimeout);
3049 }
3050
3051 if (injectionResult == INPUT_EVENT_INJECTION_SUCCEEDED
3052 && syncMode == INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07003053 while (injectionState->pendingForegroundDispatches != 0) {
Jeff Brown6ec402b2010-07-28 15:48:59 -07003054#if DEBUG_INJECTION
Jeff Brown519e0242010-09-15 15:18:56 -07003055 LOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
Jeff Brown01ce2e92010-09-26 22:20:12 -07003056 injectionState->pendingForegroundDispatches);
Jeff Brown6ec402b2010-07-28 15:48:59 -07003057#endif
3058 nsecs_t remainingTimeout = endTime - now();
3059 if (remainingTimeout <= 0) {
3060#if DEBUG_INJECTION
Jeff Brown519e0242010-09-15 15:18:56 -07003061 LOGD("injectInputEvent - Timed out waiting for pending foreground "
Jeff Brown6ec402b2010-07-28 15:48:59 -07003062 "dispatches to finish.");
3063#endif
3064 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
3065 break;
3066 }
3067
3068 mInjectionSyncFinishedCondition.waitRelative(mLock, remainingTimeout);
3069 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07003070 }
3071 }
3072
Jeff Brownac386072011-07-20 15:19:50 -07003073 injectionState->release();
Jeff Brown7fbdc842010-06-17 20:52:56 -07003074 } // release lock
3075
Jeff Brown6ec402b2010-07-28 15:48:59 -07003076#if DEBUG_INJECTION
3077 LOGD("injectInputEvent - Finished with result %d. "
3078 "injectorPid=%d, injectorUid=%d",
3079 injectionResult, injectorPid, injectorUid);
3080#endif
3081
Jeff Brown7fbdc842010-06-17 20:52:56 -07003082 return injectionResult;
3083}
3084
Jeff Brownb6997262010-10-08 22:31:17 -07003085bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
3086 return injectorUid == 0
3087 || mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
3088}
3089
Jeff Brown7fbdc842010-06-17 20:52:56 -07003090void InputDispatcher::setInjectionResultLocked(EventEntry* entry, int32_t injectionResult) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07003091 InjectionState* injectionState = entry->injectionState;
3092 if (injectionState) {
Jeff Brown7fbdc842010-06-17 20:52:56 -07003093#if DEBUG_INJECTION
3094 LOGD("Setting input event injection result to %d. "
3095 "injectorPid=%d, injectorUid=%d",
Jeff Brown01ce2e92010-09-26 22:20:12 -07003096 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
Jeff Brown7fbdc842010-06-17 20:52:56 -07003097#endif
3098
Jeff Brown0029c662011-03-30 02:25:18 -07003099 if (injectionState->injectionIsAsync
3100 && !(entry->policyFlags & POLICY_FLAG_FILTERED)) {
Jeff Brown6ec402b2010-07-28 15:48:59 -07003101 // Log the outcome since the injector did not wait for the injection result.
3102 switch (injectionResult) {
3103 case INPUT_EVENT_INJECTION_SUCCEEDED:
3104 LOGV("Asynchronous input event injection succeeded.");
3105 break;
3106 case INPUT_EVENT_INJECTION_FAILED:
3107 LOGW("Asynchronous input event injection failed.");
3108 break;
3109 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
3110 LOGW("Asynchronous input event injection permission denied.");
3111 break;
3112 case INPUT_EVENT_INJECTION_TIMED_OUT:
3113 LOGW("Asynchronous input event injection timed out.");
3114 break;
3115 }
3116 }
3117
Jeff Brown01ce2e92010-09-26 22:20:12 -07003118 injectionState->injectionResult = injectionResult;
Jeff Brown7fbdc842010-06-17 20:52:56 -07003119 mInjectionResultAvailableCondition.broadcast();
3120 }
3121}
3122
Jeff Brown01ce2e92010-09-26 22:20:12 -07003123void InputDispatcher::incrementPendingForegroundDispatchesLocked(EventEntry* entry) {
3124 InjectionState* injectionState = entry->injectionState;
3125 if (injectionState) {
3126 injectionState->pendingForegroundDispatches += 1;
3127 }
3128}
3129
Jeff Brown519e0242010-09-15 15:18:56 -07003130void InputDispatcher::decrementPendingForegroundDispatchesLocked(EventEntry* entry) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07003131 InjectionState* injectionState = entry->injectionState;
3132 if (injectionState) {
3133 injectionState->pendingForegroundDispatches -= 1;
Jeff Brown6ec402b2010-07-28 15:48:59 -07003134
Jeff Brown01ce2e92010-09-26 22:20:12 -07003135 if (injectionState->pendingForegroundDispatches == 0) {
3136 mInjectionSyncFinishedCondition.broadcast();
3137 }
Jeff Brownb88102f2010-09-08 11:49:43 -07003138 }
3139}
3140
Jeff Brown9302c872011-07-13 22:51:29 -07003141sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
3142 const sp<InputChannel>& inputChannel) const {
3143 size_t numWindows = mWindowHandles.size();
3144 for (size_t i = 0; i < numWindows; i++) {
3145 const sp<InputWindowHandle>& windowHandle = mWindowHandles.itemAt(i);
3146 if (windowHandle->inputChannel == inputChannel) {
3147 return windowHandle;
Jeff Brown01ce2e92010-09-26 22:20:12 -07003148 }
3149 }
3150 return NULL;
3151}
3152
Jeff Brown9302c872011-07-13 22:51:29 -07003153bool InputDispatcher::hasWindowHandleLocked(
3154 const sp<InputWindowHandle>& windowHandle) const {
3155 size_t numWindows = mWindowHandles.size();
3156 for (size_t i = 0; i < numWindows; i++) {
3157 if (mWindowHandles.itemAt(i) == windowHandle) {
3158 return true;
3159 }
3160 }
3161 return false;
3162}
3163
3164void InputDispatcher::setInputWindows(const Vector<sp<InputWindowHandle> >& inputWindowHandles) {
Jeff Brownb88102f2010-09-08 11:49:43 -07003165#if DEBUG_FOCUS
3166 LOGD("setInputWindows");
3167#endif
3168 { // acquire lock
3169 AutoMutex _l(mLock);
3170
Jeff Brown9302c872011-07-13 22:51:29 -07003171 mWindowHandles = inputWindowHandles;
Jeff Brownb6997262010-10-08 22:31:17 -07003172
Jeff Brown9302c872011-07-13 22:51:29 -07003173 sp<InputWindowHandle> newFocusedWindowHandle;
3174 bool foundHoveredWindow = false;
3175 for (size_t i = 0; i < mWindowHandles.size(); i++) {
3176 const sp<InputWindowHandle>& windowHandle = mWindowHandles.itemAt(i);
3177 if (!windowHandle->update() || windowHandle->inputChannel == NULL) {
3178 mWindowHandles.removeAt(i--);
3179 continue;
3180 }
3181 if (windowHandle->hasFocus) {
3182 newFocusedWindowHandle = windowHandle;
3183 }
3184 if (windowHandle == mLastHoverWindowHandle) {
3185 foundHoveredWindow = true;
Jeff Brownb88102f2010-09-08 11:49:43 -07003186 }
3187 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07003188
Jeff Brown9302c872011-07-13 22:51:29 -07003189 if (!foundHoveredWindow) {
3190 mLastHoverWindowHandle = NULL;
3191 }
3192
3193 if (mFocusedWindowHandle != newFocusedWindowHandle) {
3194 if (mFocusedWindowHandle != NULL) {
Jeff Brownb6997262010-10-08 22:31:17 -07003195#if DEBUG_FOCUS
3196 LOGD("Focus left window: %s",
Jeff Brown9302c872011-07-13 22:51:29 -07003197 mFocusedWindowHandle->name.string());
Jeff Brownb6997262010-10-08 22:31:17 -07003198#endif
Jeff Brownda3d5a92011-03-29 15:11:34 -07003199 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
3200 "focus left window");
Jeff Brown9302c872011-07-13 22:51:29 -07003201 synthesizeCancelationEventsForInputChannelLocked(
3202 mFocusedWindowHandle->inputChannel, options);
Jeff Brownb6997262010-10-08 22:31:17 -07003203 }
Jeff Brown9302c872011-07-13 22:51:29 -07003204 if (newFocusedWindowHandle != NULL) {
Jeff Brownb6997262010-10-08 22:31:17 -07003205#if DEBUG_FOCUS
Jeff Brown9302c872011-07-13 22:51:29 -07003206 LOGD("Focus entered window: %s",
3207 newFocusedWindowHandle->name.string());
Jeff Brownb6997262010-10-08 22:31:17 -07003208#endif
Jeff Brown9302c872011-07-13 22:51:29 -07003209 }
3210 mFocusedWindowHandle = newFocusedWindowHandle;
Jeff Brownb6997262010-10-08 22:31:17 -07003211 }
3212
Jeff Brown9302c872011-07-13 22:51:29 -07003213 for (size_t i = 0; i < mTouchState.windows.size(); i++) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07003214 TouchedWindow& touchedWindow = mTouchState.windows.editItemAt(i);
Jeff Brown9302c872011-07-13 22:51:29 -07003215 if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
Jeff Brownb6997262010-10-08 22:31:17 -07003216#if DEBUG_FOCUS
Jeff Brown9302c872011-07-13 22:51:29 -07003217 LOGD("Touched window was removed: %s", touchedWindow.windowHandle->name.string());
Jeff Brownb6997262010-10-08 22:31:17 -07003218#endif
Jeff Brownda3d5a92011-03-29 15:11:34 -07003219 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
3220 "touched window was removed");
Jeff Brown9302c872011-07-13 22:51:29 -07003221 synthesizeCancelationEventsForInputChannelLocked(
3222 touchedWindow.windowHandle->inputChannel, options);
3223 mTouchState.windows.removeAt(i--);
Jeff Brown01ce2e92010-09-26 22:20:12 -07003224 }
3225 }
Jeff Brownb88102f2010-09-08 11:49:43 -07003226 } // release lock
3227
3228 // Wake up poll loop since it may need to make new input dispatching choices.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07003229 mLooper->wake();
Jeff Brownb88102f2010-09-08 11:49:43 -07003230}
3231
Jeff Brown9302c872011-07-13 22:51:29 -07003232void InputDispatcher::setFocusedApplication(
3233 const sp<InputApplicationHandle>& inputApplicationHandle) {
Jeff Brownb88102f2010-09-08 11:49:43 -07003234#if DEBUG_FOCUS
3235 LOGD("setFocusedApplication");
3236#endif
3237 { // acquire lock
3238 AutoMutex _l(mLock);
3239
Jeff Brown9302c872011-07-13 22:51:29 -07003240 if (inputApplicationHandle != NULL && inputApplicationHandle->update()) {
Jeff Brown5ea29ab2011-07-27 11:50:51 -07003241 if (mFocusedApplicationHandle != inputApplicationHandle) {
3242 if (mFocusedApplicationHandle != NULL) {
3243 resetTargetsLocked();
3244 }
3245 mFocusedApplicationHandle = inputApplicationHandle;
3246 }
3247 } else if (mFocusedApplicationHandle != NULL) {
3248 resetTargetsLocked();
Jeff Brown9302c872011-07-13 22:51:29 -07003249 mFocusedApplicationHandle.clear();
Jeff Brownb88102f2010-09-08 11:49:43 -07003250 }
3251
3252#if DEBUG_FOCUS
Jeff Brownb6997262010-10-08 22:31:17 -07003253 //logDispatchStateLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -07003254#endif
3255 } // release lock
3256
3257 // Wake up poll loop since it may need to make new input dispatching choices.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07003258 mLooper->wake();
Jeff Brownb88102f2010-09-08 11:49:43 -07003259}
3260
Jeff Brownb88102f2010-09-08 11:49:43 -07003261void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
3262#if DEBUG_FOCUS
3263 LOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
3264#endif
3265
3266 bool changed;
3267 { // acquire lock
3268 AutoMutex _l(mLock);
3269
3270 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
Jeff Brown120a4592010-10-27 18:43:51 -07003271 if (mDispatchFrozen && !frozen) {
Jeff Brownb88102f2010-09-08 11:49:43 -07003272 resetANRTimeoutsLocked();
3273 }
3274
Jeff Brown120a4592010-10-27 18:43:51 -07003275 if (mDispatchEnabled && !enabled) {
3276 resetAndDropEverythingLocked("dispatcher is being disabled");
3277 }
3278
Jeff Brownb88102f2010-09-08 11:49:43 -07003279 mDispatchEnabled = enabled;
3280 mDispatchFrozen = frozen;
3281 changed = true;
3282 } else {
3283 changed = false;
3284 }
3285
3286#if DEBUG_FOCUS
Jeff Brownb6997262010-10-08 22:31:17 -07003287 //logDispatchStateLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -07003288#endif
3289 } // release lock
3290
3291 if (changed) {
3292 // Wake up poll loop since it may need to make new input dispatching choices.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07003293 mLooper->wake();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003294 }
3295}
3296
Jeff Brown0029c662011-03-30 02:25:18 -07003297void InputDispatcher::setInputFilterEnabled(bool enabled) {
3298#if DEBUG_FOCUS
3299 LOGD("setInputFilterEnabled: enabled=%d", enabled);
3300#endif
3301
3302 { // acquire lock
3303 AutoMutex _l(mLock);
3304
3305 if (mInputFilterEnabled == enabled) {
3306 return;
3307 }
3308
3309 mInputFilterEnabled = enabled;
3310 resetAndDropEverythingLocked("input filter is being enabled or disabled");
3311 } // release lock
3312
3313 // Wake up poll loop since there might be work to do to drop everything.
3314 mLooper->wake();
3315}
3316
Jeff Browne6504122010-09-27 14:52:15 -07003317bool InputDispatcher::transferTouchFocus(const sp<InputChannel>& fromChannel,
3318 const sp<InputChannel>& toChannel) {
3319#if DEBUG_FOCUS
3320 LOGD("transferTouchFocus: fromChannel=%s, toChannel=%s",
3321 fromChannel->getName().string(), toChannel->getName().string());
3322#endif
3323 { // acquire lock
3324 AutoMutex _l(mLock);
3325
Jeff Brown9302c872011-07-13 22:51:29 -07003326 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromChannel);
3327 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toChannel);
3328 if (fromWindowHandle == NULL || toWindowHandle == NULL) {
Jeff Browne6504122010-09-27 14:52:15 -07003329#if DEBUG_FOCUS
3330 LOGD("Cannot transfer focus because from or to window not found.");
3331#endif
3332 return false;
3333 }
Jeff Brown9302c872011-07-13 22:51:29 -07003334 if (fromWindowHandle == toWindowHandle) {
Jeff Browne6504122010-09-27 14:52:15 -07003335#if DEBUG_FOCUS
3336 LOGD("Trivial transfer to same window.");
3337#endif
3338 return true;
3339 }
3340
3341 bool found = false;
3342 for (size_t i = 0; i < mTouchState.windows.size(); i++) {
3343 const TouchedWindow& touchedWindow = mTouchState.windows[i];
Jeff Brown9302c872011-07-13 22:51:29 -07003344 if (touchedWindow.windowHandle == fromWindowHandle) {
Jeff Browne6504122010-09-27 14:52:15 -07003345 int32_t oldTargetFlags = touchedWindow.targetFlags;
3346 BitSet32 pointerIds = touchedWindow.pointerIds;
3347
3348 mTouchState.windows.removeAt(i);
3349
Jeff Brown46e75292010-11-10 16:53:45 -08003350 int32_t newTargetFlags = oldTargetFlags
Jeff Browna032cc02011-03-07 16:56:21 -08003351 & (InputTarget::FLAG_FOREGROUND
3352 | InputTarget::FLAG_SPLIT | InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brown9302c872011-07-13 22:51:29 -07003353 mTouchState.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Jeff Browne6504122010-09-27 14:52:15 -07003354
3355 found = true;
3356 break;
3357 }
3358 }
3359
3360 if (! found) {
3361#if DEBUG_FOCUS
3362 LOGD("Focus transfer failed because from window did not have focus.");
3363#endif
3364 return false;
3365 }
3366
Jeff Brown9c9f1a32010-10-11 18:32:20 -07003367 ssize_t fromConnectionIndex = getConnectionIndexLocked(fromChannel);
3368 ssize_t toConnectionIndex = getConnectionIndexLocked(toChannel);
3369 if (fromConnectionIndex >= 0 && toConnectionIndex >= 0) {
3370 sp<Connection> fromConnection = mConnectionsByReceiveFd.valueAt(fromConnectionIndex);
3371 sp<Connection> toConnection = mConnectionsByReceiveFd.valueAt(toConnectionIndex);
3372
3373 fromConnection->inputState.copyPointerStateTo(toConnection->inputState);
Jeff Brownda3d5a92011-03-29 15:11:34 -07003374 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Jeff Brown9c9f1a32010-10-11 18:32:20 -07003375 "transferring touch focus from this window to another window");
Jeff Brownda3d5a92011-03-29 15:11:34 -07003376 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Jeff Brown9c9f1a32010-10-11 18:32:20 -07003377 }
3378
Jeff Browne6504122010-09-27 14:52:15 -07003379#if DEBUG_FOCUS
3380 logDispatchStateLocked();
3381#endif
3382 } // release lock
3383
3384 // Wake up poll loop since it may need to make new input dispatching choices.
3385 mLooper->wake();
3386 return true;
3387}
3388
Jeff Brown120a4592010-10-27 18:43:51 -07003389void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
3390#if DEBUG_FOCUS
3391 LOGD("Resetting and dropping all events (%s).", reason);
3392#endif
3393
Jeff Brownda3d5a92011-03-29 15:11:34 -07003394 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
3395 synthesizeCancelationEventsForAllConnectionsLocked(options);
Jeff Brown120a4592010-10-27 18:43:51 -07003396
3397 resetKeyRepeatLocked();
3398 releasePendingEventLocked();
3399 drainInboundQueueLocked();
3400 resetTargetsLocked();
3401
3402 mTouchState.reset();
Jeff Brown9302c872011-07-13 22:51:29 -07003403 mLastHoverWindowHandle.clear();
Jeff Brown120a4592010-10-27 18:43:51 -07003404}
3405
Jeff Brownb88102f2010-09-08 11:49:43 -07003406void InputDispatcher::logDispatchStateLocked() {
3407 String8 dump;
3408 dumpDispatchStateLocked(dump);
Jeff Brown2a95c2a2010-09-16 12:31:46 -07003409
3410 char* text = dump.lockBuffer(dump.size());
3411 char* start = text;
3412 while (*start != '\0') {
3413 char* end = strchr(start, '\n');
3414 if (*end == '\n') {
3415 *(end++) = '\0';
3416 }
3417 LOGD("%s", start);
3418 start = end;
3419 }
Jeff Brownb88102f2010-09-08 11:49:43 -07003420}
3421
3422void InputDispatcher::dumpDispatchStateLocked(String8& dump) {
Jeff Brownf2f487182010-10-01 17:46:21 -07003423 dump.appendFormat(INDENT "DispatchEnabled: %d\n", mDispatchEnabled);
3424 dump.appendFormat(INDENT "DispatchFrozen: %d\n", mDispatchFrozen);
Jeff Brownb88102f2010-09-08 11:49:43 -07003425
Jeff Brown9302c872011-07-13 22:51:29 -07003426 if (mFocusedApplicationHandle != NULL) {
Jeff Brownf2f487182010-10-01 17:46:21 -07003427 dump.appendFormat(INDENT "FocusedApplication: name='%s', dispatchingTimeout=%0.3fms\n",
Jeff Brown9302c872011-07-13 22:51:29 -07003428 mFocusedApplicationHandle->name.string(),
3429 mFocusedApplicationHandle->dispatchingTimeout / 1000000.0);
Jeff Brownb88102f2010-09-08 11:49:43 -07003430 } else {
Jeff Brownf2f487182010-10-01 17:46:21 -07003431 dump.append(INDENT "FocusedApplication: <null>\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003432 }
Jeff Brownf2f487182010-10-01 17:46:21 -07003433 dump.appendFormat(INDENT "FocusedWindow: name='%s'\n",
Jeff Brown9302c872011-07-13 22:51:29 -07003434 mFocusedWindowHandle != NULL ? mFocusedWindowHandle->name.string() : "<null>");
Jeff Brownf2f487182010-10-01 17:46:21 -07003435
3436 dump.appendFormat(INDENT "TouchDown: %s\n", toString(mTouchState.down));
3437 dump.appendFormat(INDENT "TouchSplit: %s\n", toString(mTouchState.split));
Jeff Brown95712852011-01-04 19:41:59 -08003438 dump.appendFormat(INDENT "TouchDeviceId: %d\n", mTouchState.deviceId);
Jeff Brown58a2da82011-01-25 16:02:22 -08003439 dump.appendFormat(INDENT "TouchSource: 0x%08x\n", mTouchState.source);
Jeff Brownf2f487182010-10-01 17:46:21 -07003440 if (!mTouchState.windows.isEmpty()) {
3441 dump.append(INDENT "TouchedWindows:\n");
3442 for (size_t i = 0; i < mTouchState.windows.size(); i++) {
3443 const TouchedWindow& touchedWindow = mTouchState.windows[i];
3444 dump.appendFormat(INDENT2 "%d: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
Jeff Brown9302c872011-07-13 22:51:29 -07003445 i, touchedWindow.windowHandle->name.string(), touchedWindow.pointerIds.value,
Jeff Brownf2f487182010-10-01 17:46:21 -07003446 touchedWindow.targetFlags);
3447 }
3448 } else {
3449 dump.append(INDENT "TouchedWindows: <none>\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003450 }
3451
Jeff Brown9302c872011-07-13 22:51:29 -07003452 if (!mWindowHandles.isEmpty()) {
Jeff Brownf2f487182010-10-01 17:46:21 -07003453 dump.append(INDENT "Windows:\n");
Jeff Brown9302c872011-07-13 22:51:29 -07003454 for (size_t i = 0; i < mWindowHandles.size(); i++) {
3455 const sp<InputWindowHandle>& windowHandle = mWindowHandles.itemAt(i);
Jeff Brownf2f487182010-10-01 17:46:21 -07003456 dump.appendFormat(INDENT2 "%d: name='%s', paused=%s, hasFocus=%s, hasWallpaper=%s, "
3457 "visible=%s, canReceiveKeys=%s, flags=0x%08x, type=0x%08x, layer=%d, "
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003458 "frame=[%d,%d][%d,%d], scale=%f, "
Jeff Brownfbf09772011-01-16 14:06:57 -08003459 "touchableRegion=",
Jeff Brown9302c872011-07-13 22:51:29 -07003460 i, windowHandle->name.string(),
3461 toString(windowHandle->paused),
3462 toString(windowHandle->hasFocus),
3463 toString(windowHandle->hasWallpaper),
3464 toString(windowHandle->visible),
3465 toString(windowHandle->canReceiveKeys),
3466 windowHandle->layoutParamsFlags, windowHandle->layoutParamsType,
3467 windowHandle->layer,
3468 windowHandle->frameLeft, windowHandle->frameTop,
3469 windowHandle->frameRight, windowHandle->frameBottom,
3470 windowHandle->scaleFactor);
3471 dumpRegion(dump, windowHandle->touchableRegion);
3472 dump.appendFormat(", inputFeatures=0x%08x", windowHandle->inputFeatures);
Jeff Brownfbf09772011-01-16 14:06:57 -08003473 dump.appendFormat(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%0.3fms\n",
Jeff Brown9302c872011-07-13 22:51:29 -07003474 windowHandle->ownerPid, windowHandle->ownerUid,
3475 windowHandle->dispatchingTimeout / 1000000.0);
Jeff Brownf2f487182010-10-01 17:46:21 -07003476 }
3477 } else {
3478 dump.append(INDENT "Windows: <none>\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003479 }
3480
Jeff Brownf2f487182010-10-01 17:46:21 -07003481 if (!mMonitoringChannels.isEmpty()) {
3482 dump.append(INDENT "MonitoringChannels:\n");
3483 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
3484 const sp<InputChannel>& channel = mMonitoringChannels[i];
3485 dump.appendFormat(INDENT2 "%d: '%s'\n", i, channel->getName().string());
3486 }
3487 } else {
3488 dump.append(INDENT "MonitoringChannels: <none>\n");
3489 }
Jeff Brown519e0242010-09-15 15:18:56 -07003490
Jeff Brownf2f487182010-10-01 17:46:21 -07003491 dump.appendFormat(INDENT "InboundQueue: length=%u\n", mInboundQueue.count());
3492
3493 if (!mActiveConnections.isEmpty()) {
3494 dump.append(INDENT "ActiveConnections:\n");
3495 for (size_t i = 0; i < mActiveConnections.size(); i++) {
3496 const Connection* connection = mActiveConnections[i];
Jeff Brown76860e32010-10-25 17:37:46 -07003497 dump.appendFormat(INDENT2 "%d: '%s', status=%s, outboundQueueLength=%u, "
Jeff Brownb6997262010-10-08 22:31:17 -07003498 "inputState.isNeutral=%s\n",
Jeff Brownf2f487182010-10-01 17:46:21 -07003499 i, connection->getInputChannelName(), connection->getStatusLabel(),
3500 connection->outboundQueue.count(),
Jeff Brownb6997262010-10-08 22:31:17 -07003501 toString(connection->inputState.isNeutral()));
Jeff Brownf2f487182010-10-01 17:46:21 -07003502 }
3503 } else {
3504 dump.append(INDENT "ActiveConnections: <none>\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003505 }
3506
3507 if (isAppSwitchPendingLocked()) {
Jeff Brownf2f487182010-10-01 17:46:21 -07003508 dump.appendFormat(INDENT "AppSwitch: pending, due in %01.1fms\n",
Jeff Brownb88102f2010-09-08 11:49:43 -07003509 (mAppSwitchDueTime - now()) / 1000000.0);
3510 } else {
Jeff Brownf2f487182010-10-01 17:46:21 -07003511 dump.append(INDENT "AppSwitch: not pending\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003512 }
3513}
3514
Jeff Brown928e0542011-01-10 11:17:36 -08003515status_t InputDispatcher::registerInputChannel(const sp<InputChannel>& inputChannel,
3516 const sp<InputWindowHandle>& inputWindowHandle, bool monitor) {
Jeff Brown9c3cda02010-06-15 01:31:58 -07003517#if DEBUG_REGISTRATION
Jeff Brownb88102f2010-09-08 11:49:43 -07003518 LOGD("channel '%s' ~ registerInputChannel - monitor=%s", inputChannel->getName().string(),
3519 toString(monitor));
Jeff Brown9c3cda02010-06-15 01:31:58 -07003520#endif
3521
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003522 { // acquire lock
3523 AutoMutex _l(mLock);
3524
Jeff Brown519e0242010-09-15 15:18:56 -07003525 if (getConnectionIndexLocked(inputChannel) >= 0) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003526 LOGW("Attempted to register already registered input channel '%s'",
3527 inputChannel->getName().string());
3528 return BAD_VALUE;
3529 }
3530
Jeff Brown928e0542011-01-10 11:17:36 -08003531 sp<Connection> connection = new Connection(inputChannel, inputWindowHandle);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003532 status_t status = connection->initialize();
3533 if (status) {
3534 LOGE("Failed to initialize input publisher for input channel '%s', status=%d",
3535 inputChannel->getName().string(), status);
3536 return status;
3537 }
3538
Jeff Brown2cbecea2010-08-17 15:59:26 -07003539 int32_t receiveFd = inputChannel->getReceivePipeFd();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003540 mConnectionsByReceiveFd.add(receiveFd, connection);
Jeff Brown9c3cda02010-06-15 01:31:58 -07003541
Jeff Brownb88102f2010-09-08 11:49:43 -07003542 if (monitor) {
3543 mMonitoringChannels.push(inputChannel);
3544 }
3545
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07003546 mLooper->addFd(receiveFd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
Jeff Brown2cbecea2010-08-17 15:59:26 -07003547
Jeff Brown9c3cda02010-06-15 01:31:58 -07003548 runCommandsLockedInterruptible();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003549 } // release lock
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003550 return OK;
3551}
3552
3553status_t InputDispatcher::unregisterInputChannel(const sp<InputChannel>& inputChannel) {
Jeff Brown9c3cda02010-06-15 01:31:58 -07003554#if DEBUG_REGISTRATION
Jeff Brown349703e2010-06-22 01:27:15 -07003555 LOGD("channel '%s' ~ unregisterInputChannel", inputChannel->getName().string());
Jeff Brown9c3cda02010-06-15 01:31:58 -07003556#endif
3557
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003558 { // acquire lock
3559 AutoMutex _l(mLock);
3560
Jeff Brown519e0242010-09-15 15:18:56 -07003561 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003562 if (connectionIndex < 0) {
3563 LOGW("Attempted to unregister already unregistered input channel '%s'",
3564 inputChannel->getName().string());
3565 return BAD_VALUE;
3566 }
3567
3568 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
3569 mConnectionsByReceiveFd.removeItemsAt(connectionIndex);
3570
3571 connection->status = Connection::STATUS_ZOMBIE;
3572
Jeff Brownb88102f2010-09-08 11:49:43 -07003573 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
3574 if (mMonitoringChannels[i] == inputChannel) {
3575 mMonitoringChannels.removeAt(i);
3576 break;
3577 }
3578 }
3579
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07003580 mLooper->removeFd(inputChannel->getReceivePipeFd());
Jeff Brown2cbecea2010-08-17 15:59:26 -07003581
Jeff Brown7fbdc842010-06-17 20:52:56 -07003582 nsecs_t currentTime = now();
Jeff Brownb6997262010-10-08 22:31:17 -07003583 abortBrokenDispatchCycleLocked(currentTime, connection);
Jeff Brown9c3cda02010-06-15 01:31:58 -07003584
3585 runCommandsLockedInterruptible();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003586 } // release lock
3587
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003588 // Wake the poll loop because removing the connection may have changed the current
3589 // synchronization state.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07003590 mLooper->wake();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003591 return OK;
3592}
3593
Jeff Brown519e0242010-09-15 15:18:56 -07003594ssize_t InputDispatcher::getConnectionIndexLocked(const sp<InputChannel>& inputChannel) {
Jeff Brown2cbecea2010-08-17 15:59:26 -07003595 ssize_t connectionIndex = mConnectionsByReceiveFd.indexOfKey(inputChannel->getReceivePipeFd());
3596 if (connectionIndex >= 0) {
3597 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
3598 if (connection->inputChannel.get() == inputChannel.get()) {
3599 return connectionIndex;
3600 }
3601 }
3602
3603 return -1;
3604}
3605
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003606void InputDispatcher::activateConnectionLocked(Connection* connection) {
3607 for (size_t i = 0; i < mActiveConnections.size(); i++) {
3608 if (mActiveConnections.itemAt(i) == connection) {
3609 return;
3610 }
3611 }
3612 mActiveConnections.add(connection);
3613}
3614
3615void InputDispatcher::deactivateConnectionLocked(Connection* connection) {
3616 for (size_t i = 0; i < mActiveConnections.size(); i++) {
3617 if (mActiveConnections.itemAt(i) == connection) {
3618 mActiveConnections.removeAt(i);
3619 return;
3620 }
3621 }
3622}
3623
Jeff Brown9c3cda02010-06-15 01:31:58 -07003624void InputDispatcher::onDispatchCycleStartedLocked(
Jeff Brown7fbdc842010-06-17 20:52:56 -07003625 nsecs_t currentTime, const sp<Connection>& connection) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003626}
3627
Jeff Brown9c3cda02010-06-15 01:31:58 -07003628void InputDispatcher::onDispatchCycleFinishedLocked(
Jeff Brown3915bb82010-11-05 15:02:16 -07003629 nsecs_t currentTime, const sp<Connection>& connection, bool handled) {
3630 CommandEntry* commandEntry = postCommandLocked(
3631 & InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
3632 commandEntry->connection = connection;
3633 commandEntry->handled = handled;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003634}
3635
Jeff Brown9c3cda02010-06-15 01:31:58 -07003636void InputDispatcher::onDispatchCycleBrokenLocked(
Jeff Brown7fbdc842010-06-17 20:52:56 -07003637 nsecs_t currentTime, const sp<Connection>& connection) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003638 LOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
3639 connection->getInputChannelName());
3640
Jeff Brown9c3cda02010-06-15 01:31:58 -07003641 CommandEntry* commandEntry = postCommandLocked(
3642 & InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
Jeff Brown7fbdc842010-06-17 20:52:56 -07003643 commandEntry->connection = connection;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003644}
3645
Jeff Brown519e0242010-09-15 15:18:56 -07003646void InputDispatcher::onANRLocked(
Jeff Brown9302c872011-07-13 22:51:29 -07003647 nsecs_t currentTime, const sp<InputApplicationHandle>& applicationHandle,
3648 const sp<InputWindowHandle>& windowHandle,
Jeff Brown519e0242010-09-15 15:18:56 -07003649 nsecs_t eventTime, nsecs_t waitStartTime) {
3650 LOGI("Application is not responding: %s. "
3651 "%01.1fms since event, %01.1fms since wait started",
Jeff Brown9302c872011-07-13 22:51:29 -07003652 getApplicationWindowLabelLocked(applicationHandle, windowHandle).string(),
Jeff Brown519e0242010-09-15 15:18:56 -07003653 (currentTime - eventTime) / 1000000.0,
3654 (currentTime - waitStartTime) / 1000000.0);
3655
3656 CommandEntry* commandEntry = postCommandLocked(
3657 & InputDispatcher::doNotifyANRLockedInterruptible);
Jeff Brown9302c872011-07-13 22:51:29 -07003658 commandEntry->inputApplicationHandle = applicationHandle;
3659 commandEntry->inputWindowHandle = windowHandle;
Jeff Brown519e0242010-09-15 15:18:56 -07003660}
3661
Jeff Brownb88102f2010-09-08 11:49:43 -07003662void InputDispatcher::doNotifyConfigurationChangedInterruptible(
3663 CommandEntry* commandEntry) {
3664 mLock.unlock();
3665
3666 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
3667
3668 mLock.lock();
3669}
3670
Jeff Brown9c3cda02010-06-15 01:31:58 -07003671void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(
3672 CommandEntry* commandEntry) {
Jeff Brown7fbdc842010-06-17 20:52:56 -07003673 sp<Connection> connection = commandEntry->connection;
Jeff Brown9c3cda02010-06-15 01:31:58 -07003674
Jeff Brown7fbdc842010-06-17 20:52:56 -07003675 if (connection->status != Connection::STATUS_ZOMBIE) {
3676 mLock.unlock();
Jeff Brown9c3cda02010-06-15 01:31:58 -07003677
Jeff Brown928e0542011-01-10 11:17:36 -08003678 mPolicy->notifyInputChannelBroken(connection->inputWindowHandle);
Jeff Brown7fbdc842010-06-17 20:52:56 -07003679
3680 mLock.lock();
3681 }
Jeff Brown9c3cda02010-06-15 01:31:58 -07003682}
3683
Jeff Brown519e0242010-09-15 15:18:56 -07003684void InputDispatcher::doNotifyANRLockedInterruptible(
Jeff Brown9c3cda02010-06-15 01:31:58 -07003685 CommandEntry* commandEntry) {
Jeff Brown519e0242010-09-15 15:18:56 -07003686 mLock.unlock();
Jeff Brown9c3cda02010-06-15 01:31:58 -07003687
Jeff Brown519e0242010-09-15 15:18:56 -07003688 nsecs_t newTimeout = mPolicy->notifyANR(
Jeff Brown928e0542011-01-10 11:17:36 -08003689 commandEntry->inputApplicationHandle, commandEntry->inputWindowHandle);
Jeff Brown9c3cda02010-06-15 01:31:58 -07003690
Jeff Brown519e0242010-09-15 15:18:56 -07003691 mLock.lock();
Jeff Brown7fbdc842010-06-17 20:52:56 -07003692
Jeff Brown9302c872011-07-13 22:51:29 -07003693 resumeAfterTargetsNotReadyTimeoutLocked(newTimeout,
3694 commandEntry->inputWindowHandle != NULL
3695 ? commandEntry->inputWindowHandle->inputChannel : NULL);
Jeff Brown9c3cda02010-06-15 01:31:58 -07003696}
3697
Jeff Brownb88102f2010-09-08 11:49:43 -07003698void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
3699 CommandEntry* commandEntry) {
3700 KeyEntry* entry = commandEntry->keyEntry;
Jeff Brown1f245102010-11-18 20:53:46 -08003701
3702 KeyEvent event;
3703 initializeKeyEvent(&event, entry);
Jeff Brownb88102f2010-09-08 11:49:43 -07003704
3705 mLock.unlock();
3706
Jeff Brown928e0542011-01-10 11:17:36 -08003707 bool consumed = mPolicy->interceptKeyBeforeDispatching(commandEntry->inputWindowHandle,
Jeff Brown1f245102010-11-18 20:53:46 -08003708 &event, entry->policyFlags);
Jeff Brownb88102f2010-09-08 11:49:43 -07003709
3710 mLock.lock();
3711
3712 entry->interceptKeyResult = consumed
3713 ? KeyEntry::INTERCEPT_KEY_RESULT_SKIP
3714 : KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
Jeff Brownac386072011-07-20 15:19:50 -07003715 entry->release();
Jeff Brownb88102f2010-09-08 11:49:43 -07003716}
3717
Jeff Brown3915bb82010-11-05 15:02:16 -07003718void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(
3719 CommandEntry* commandEntry) {
3720 sp<Connection> connection = commandEntry->connection;
3721 bool handled = commandEntry->handled;
3722
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003723 bool skipNext = false;
Jeff Brown49ed71d2010-12-06 17:13:33 -08003724 if (!connection->outboundQueue.isEmpty()) {
Jeff Brownac386072011-07-20 15:19:50 -07003725 DispatchEntry* dispatchEntry = connection->outboundQueue.head;
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003726 if (dispatchEntry->inProgress) {
3727 if (dispatchEntry->eventEntry->type == EventEntry::TYPE_KEY) {
3728 KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry);
3729 skipNext = afterKeyEventLockedInterruptible(connection,
3730 dispatchEntry, keyEntry, handled);
3731 } else if (dispatchEntry->eventEntry->type == EventEntry::TYPE_MOTION) {
3732 MotionEntry* motionEntry = static_cast<MotionEntry*>(dispatchEntry->eventEntry);
3733 skipNext = afterMotionEventLockedInterruptible(connection,
3734 dispatchEntry, motionEntry, handled);
Jeff Brown49ed71d2010-12-06 17:13:33 -08003735 }
Jeff Brown3915bb82010-11-05 15:02:16 -07003736 }
3737 }
3738
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003739 if (!skipNext) {
3740 startNextDispatchCycleLocked(now(), connection);
3741 }
3742}
3743
3744bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
3745 DispatchEntry* dispatchEntry, KeyEntry* keyEntry, bool handled) {
3746 if (!(keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK)) {
3747 // Get the fallback key state.
3748 // Clear it out after dispatching the UP.
3749 int32_t originalKeyCode = keyEntry->keyCode;
3750 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
3751 if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
3752 connection->inputState.removeFallbackKey(originalKeyCode);
3753 }
3754
3755 if (handled || !dispatchEntry->hasForegroundTarget()) {
3756 // If the application handles the original key for which we previously
3757 // generated a fallback or if the window is not a foreground window,
3758 // then cancel the associated fallback key, if any.
3759 if (fallbackKeyCode != -1) {
3760 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
3761 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
3762 "application handled the original non-fallback key "
3763 "or is no longer a foreground target, "
3764 "canceling previously dispatched fallback key");
3765 options.keyCode = fallbackKeyCode;
3766 synthesizeCancelationEventsForConnectionLocked(connection, options);
3767 }
3768 connection->inputState.removeFallbackKey(originalKeyCode);
3769 }
3770 } else {
3771 // If the application did not handle a non-fallback key, first check
3772 // that we are in a good state to perform unhandled key event processing
3773 // Then ask the policy what to do with it.
3774 bool initialDown = keyEntry->action == AKEY_EVENT_ACTION_DOWN
3775 && keyEntry->repeatCount == 0;
3776 if (fallbackKeyCode == -1 && !initialDown) {
3777#if DEBUG_OUTBOUND_EVENT_DETAILS
3778 LOGD("Unhandled key event: Skipping unhandled key event processing "
3779 "since this is not an initial down. "
3780 "keyCode=%d, action=%d, repeatCount=%d",
3781 originalKeyCode, keyEntry->action, keyEntry->repeatCount);
3782#endif
3783 return false;
3784 }
3785
3786 // Dispatch the unhandled key to the policy.
3787#if DEBUG_OUTBOUND_EVENT_DETAILS
3788 LOGD("Unhandled key event: Asking policy to perform fallback action. "
3789 "keyCode=%d, action=%d, repeatCount=%d",
3790 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount);
3791#endif
3792 KeyEvent event;
3793 initializeKeyEvent(&event, keyEntry);
3794
3795 mLock.unlock();
3796
3797 bool fallback = mPolicy->dispatchUnhandledKey(connection->inputWindowHandle,
3798 &event, keyEntry->policyFlags, &event);
3799
3800 mLock.lock();
3801
3802 if (connection->status != Connection::STATUS_NORMAL) {
3803 connection->inputState.removeFallbackKey(originalKeyCode);
3804 return true; // skip next cycle
3805 }
3806
Jeff Brownac386072011-07-20 15:19:50 -07003807 LOG_ASSERT(connection->outboundQueue.head == dispatchEntry);
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003808
3809 // Latch the fallback keycode for this key on an initial down.
3810 // The fallback keycode cannot change at any other point in the lifecycle.
3811 if (initialDown) {
3812 if (fallback) {
3813 fallbackKeyCode = event.getKeyCode();
3814 } else {
3815 fallbackKeyCode = AKEYCODE_UNKNOWN;
3816 }
3817 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
3818 }
3819
3820 LOG_ASSERT(fallbackKeyCode != -1);
3821
3822 // Cancel the fallback key if the policy decides not to send it anymore.
3823 // We will continue to dispatch the key to the policy but we will no
3824 // longer dispatch a fallback key to the application.
3825 if (fallbackKeyCode != AKEYCODE_UNKNOWN
3826 && (!fallback || fallbackKeyCode != event.getKeyCode())) {
3827#if DEBUG_OUTBOUND_EVENT_DETAILS
3828 if (fallback) {
3829 LOGD("Unhandled key event: Policy requested to send key %d"
3830 "as a fallback for %d, but on the DOWN it had requested "
3831 "to send %d instead. Fallback canceled.",
3832 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
3833 } else {
3834 LOGD("Unhandled key event: Policy did not request fallback for %d,"
3835 "but on the DOWN it had requested to send %d. "
3836 "Fallback canceled.",
3837 originalKeyCode, fallbackKeyCode);
3838 }
3839#endif
3840
3841 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
3842 "canceling fallback, policy no longer desires it");
3843 options.keyCode = fallbackKeyCode;
3844 synthesizeCancelationEventsForConnectionLocked(connection, options);
3845
3846 fallback = false;
3847 fallbackKeyCode = AKEYCODE_UNKNOWN;
3848 if (keyEntry->action != AKEY_EVENT_ACTION_UP) {
3849 connection->inputState.setFallbackKey(originalKeyCode,
3850 fallbackKeyCode);
3851 }
3852 }
3853
3854#if DEBUG_OUTBOUND_EVENT_DETAILS
3855 {
3856 String8 msg;
3857 const KeyedVector<int32_t, int32_t>& fallbackKeys =
3858 connection->inputState.getFallbackKeys();
3859 for (size_t i = 0; i < fallbackKeys.size(); i++) {
3860 msg.appendFormat(", %d->%d", fallbackKeys.keyAt(i),
3861 fallbackKeys.valueAt(i));
3862 }
3863 LOGD("Unhandled key event: %d currently tracked fallback keys%s.",
3864 fallbackKeys.size(), msg.string());
3865 }
3866#endif
3867
3868 if (fallback) {
3869 // Restart the dispatch cycle using the fallback key.
3870 keyEntry->eventTime = event.getEventTime();
3871 keyEntry->deviceId = event.getDeviceId();
3872 keyEntry->source = event.getSource();
3873 keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
3874 keyEntry->keyCode = fallbackKeyCode;
3875 keyEntry->scanCode = event.getScanCode();
3876 keyEntry->metaState = event.getMetaState();
3877 keyEntry->repeatCount = event.getRepeatCount();
3878 keyEntry->downTime = event.getDownTime();
3879 keyEntry->syntheticRepeat = false;
3880
3881#if DEBUG_OUTBOUND_EVENT_DETAILS
3882 LOGD("Unhandled key event: Dispatching fallback key. "
3883 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
3884 originalKeyCode, fallbackKeyCode, keyEntry->metaState);
3885#endif
3886
3887 dispatchEntry->inProgress = false;
3888 startDispatchCycleLocked(now(), connection);
3889 return true; // already started next cycle
3890 } else {
3891#if DEBUG_OUTBOUND_EVENT_DETAILS
3892 LOGD("Unhandled key event: No fallback key.");
3893#endif
3894 }
3895 }
3896 }
3897 return false;
3898}
3899
3900bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
3901 DispatchEntry* dispatchEntry, MotionEntry* motionEntry, bool handled) {
3902 return false;
Jeff Brown3915bb82010-11-05 15:02:16 -07003903}
3904
Jeff Brownb88102f2010-09-08 11:49:43 -07003905void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
3906 mLock.unlock();
3907
Jeff Brown01ce2e92010-09-26 22:20:12 -07003908 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
Jeff Brownb88102f2010-09-08 11:49:43 -07003909
3910 mLock.lock();
3911}
3912
Jeff Brown3915bb82010-11-05 15:02:16 -07003913void InputDispatcher::initializeKeyEvent(KeyEvent* event, const KeyEntry* entry) {
3914 event->initialize(entry->deviceId, entry->source, entry->action, entry->flags,
3915 entry->keyCode, entry->scanCode, entry->metaState, entry->repeatCount,
3916 entry->downTime, entry->eventTime);
3917}
3918
Jeff Brown519e0242010-09-15 15:18:56 -07003919void InputDispatcher::updateDispatchStatisticsLocked(nsecs_t currentTime, const EventEntry* entry,
3920 int32_t injectionResult, nsecs_t timeSpentWaitingForApplication) {
3921 // TODO Write some statistics about how long we spend waiting.
Jeff Brownb88102f2010-09-08 11:49:43 -07003922}
3923
3924void InputDispatcher::dump(String8& dump) {
Jeff Brown89ef0722011-08-10 16:25:21 -07003925 AutoMutex _l(mLock);
3926
Jeff Brownf2f487182010-10-01 17:46:21 -07003927 dump.append("Input Dispatcher State:\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003928 dumpDispatchStateLocked(dump);
Jeff Brown214eaf42011-05-26 19:17:02 -07003929
3930 dump.append(INDENT "Configuration:\n");
3931 dump.appendFormat(INDENT2 "MaxEventsPerSecond: %d\n", mConfig.maxEventsPerSecond);
3932 dump.appendFormat(INDENT2 "KeyRepeatDelay: %0.1fms\n", mConfig.keyRepeatDelay * 0.000001f);
3933 dump.appendFormat(INDENT2 "KeyRepeatTimeout: %0.1fms\n", mConfig.keyRepeatTimeout * 0.000001f);
Jeff Brownb88102f2010-09-08 11:49:43 -07003934}
3935
Jeff Brown89ef0722011-08-10 16:25:21 -07003936void InputDispatcher::monitor() {
3937 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
3938 mLock.lock();
3939 mLock.unlock();
3940}
3941
Jeff Brown9c3cda02010-06-15 01:31:58 -07003942
Jeff Brown519e0242010-09-15 15:18:56 -07003943// --- InputDispatcher::Queue ---
3944
3945template <typename T>
3946uint32_t InputDispatcher::Queue<T>::count() const {
3947 uint32_t result = 0;
Jeff Brownac386072011-07-20 15:19:50 -07003948 for (const T* entry = head; entry; entry = entry->next) {
Jeff Brown519e0242010-09-15 15:18:56 -07003949 result += 1;
3950 }
3951 return result;
3952}
3953
3954
Jeff Brownac386072011-07-20 15:19:50 -07003955// --- InputDispatcher::InjectionState ---
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003956
Jeff Brownac386072011-07-20 15:19:50 -07003957InputDispatcher::InjectionState::InjectionState(int32_t injectorPid, int32_t injectorUid) :
3958 refCount(1),
3959 injectorPid(injectorPid), injectorUid(injectorUid),
3960 injectionResult(INPUT_EVENT_INJECTION_PENDING), injectionIsAsync(false),
3961 pendingForegroundDispatches(0) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003962}
3963
Jeff Brownac386072011-07-20 15:19:50 -07003964InputDispatcher::InjectionState::~InjectionState() {
Jeff Brown01ce2e92010-09-26 22:20:12 -07003965}
3966
Jeff Brownac386072011-07-20 15:19:50 -07003967void InputDispatcher::InjectionState::release() {
3968 refCount -= 1;
3969 if (refCount == 0) {
3970 delete this;
3971 } else {
3972 LOG_ASSERT(refCount > 0);
Jeff Brown01ce2e92010-09-26 22:20:12 -07003973 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07003974}
3975
Jeff Brownac386072011-07-20 15:19:50 -07003976
3977// --- InputDispatcher::EventEntry ---
3978
3979InputDispatcher::EventEntry::EventEntry(int32_t type, nsecs_t eventTime, uint32_t policyFlags) :
3980 refCount(1), type(type), eventTime(eventTime), policyFlags(policyFlags),
3981 injectionState(NULL), dispatchInProgress(false) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003982}
3983
Jeff Brownac386072011-07-20 15:19:50 -07003984InputDispatcher::EventEntry::~EventEntry() {
3985 releaseInjectionState();
3986}
3987
3988void InputDispatcher::EventEntry::release() {
3989 refCount -= 1;
3990 if (refCount == 0) {
3991 delete this;
3992 } else {
3993 LOG_ASSERT(refCount > 0);
3994 }
3995}
3996
3997void InputDispatcher::EventEntry::releaseInjectionState() {
3998 if (injectionState) {
3999 injectionState->release();
4000 injectionState = NULL;
4001 }
4002}
4003
4004
4005// --- InputDispatcher::ConfigurationChangedEntry ---
4006
4007InputDispatcher::ConfigurationChangedEntry::ConfigurationChangedEntry(nsecs_t eventTime) :
4008 EventEntry(TYPE_CONFIGURATION_CHANGED, eventTime, 0) {
4009}
4010
4011InputDispatcher::ConfigurationChangedEntry::~ConfigurationChangedEntry() {
4012}
4013
4014
4015// --- InputDispatcher::KeyEntry ---
4016
4017InputDispatcher::KeyEntry::KeyEntry(nsecs_t eventTime,
Jeff Brown58a2da82011-01-25 16:02:22 -08004018 int32_t deviceId, uint32_t source, uint32_t policyFlags, int32_t action,
Jeff Brown7fbdc842010-06-17 20:52:56 -07004019 int32_t flags, int32_t keyCode, int32_t scanCode, int32_t metaState,
Jeff Brownac386072011-07-20 15:19:50 -07004020 int32_t repeatCount, nsecs_t downTime) :
4021 EventEntry(TYPE_KEY, eventTime, policyFlags),
4022 deviceId(deviceId), source(source), action(action), flags(flags),
4023 keyCode(keyCode), scanCode(scanCode), metaState(metaState),
4024 repeatCount(repeatCount), downTime(downTime),
4025 syntheticRepeat(false), interceptKeyResult(KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004026}
4027
Jeff Brownac386072011-07-20 15:19:50 -07004028InputDispatcher::KeyEntry::~KeyEntry() {
4029}
Jeff Brown7fbdc842010-06-17 20:52:56 -07004030
Jeff Brownac386072011-07-20 15:19:50 -07004031void InputDispatcher::KeyEntry::recycle() {
4032 releaseInjectionState();
4033
4034 dispatchInProgress = false;
4035 syntheticRepeat = false;
4036 interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
4037}
4038
4039
4040// --- InputDispatcher::MotionSample ---
4041
4042InputDispatcher::MotionSample::MotionSample(nsecs_t eventTime,
4043 const PointerCoords* pointerCoords, uint32_t pointerCount) :
4044 next(NULL), eventTime(eventTime), eventTimeBeforeCoalescing(eventTime) {
Jeff Brown7fbdc842010-06-17 20:52:56 -07004045 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brownac386072011-07-20 15:19:50 -07004046 this->pointerCoords[i].copyFrom(pointerCoords[i]);
Jeff Brown7fbdc842010-06-17 20:52:56 -07004047 }
Jeff Brownb88102f2010-09-08 11:49:43 -07004048}
4049
4050
Jeff Brownae9fc032010-08-18 15:51:08 -07004051// --- InputDispatcher::MotionEntry ---
4052
Jeff Brownac386072011-07-20 15:19:50 -07004053InputDispatcher::MotionEntry::MotionEntry(nsecs_t eventTime,
4054 int32_t deviceId, uint32_t source, uint32_t policyFlags, int32_t action, int32_t flags,
4055 int32_t metaState, int32_t buttonState,
4056 int32_t edgeFlags, float xPrecision, float yPrecision,
4057 nsecs_t downTime, uint32_t pointerCount,
4058 const PointerProperties* pointerProperties, const PointerCoords* pointerCoords) :
4059 EventEntry(TYPE_MOTION, eventTime, policyFlags),
4060 deviceId(deviceId), source(source), action(action), flags(flags),
4061 metaState(metaState), buttonState(buttonState), edgeFlags(edgeFlags),
4062 xPrecision(xPrecision), yPrecision(yPrecision),
4063 downTime(downTime), pointerCount(pointerCount),
4064 firstSample(eventTime, pointerCoords, pointerCount),
4065 lastSample(&firstSample) {
4066 for (uint32_t i = 0; i < pointerCount; i++) {
4067 this->pointerProperties[i].copyFrom(pointerProperties[i]);
4068 }
4069}
4070
4071InputDispatcher::MotionEntry::~MotionEntry() {
4072 for (MotionSample* sample = firstSample.next; sample != NULL; ) {
4073 MotionSample* next = sample->next;
4074 delete sample;
4075 sample = next;
4076 }
4077}
4078
Jeff Brownae9fc032010-08-18 15:51:08 -07004079uint32_t InputDispatcher::MotionEntry::countSamples() const {
4080 uint32_t count = 1;
4081 for (MotionSample* sample = firstSample.next; sample != NULL; sample = sample->next) {
4082 count += 1;
4083 }
4084 return count;
4085}
4086
Jeff Brown4e91a182011-04-07 11:38:09 -07004087bool InputDispatcher::MotionEntry::canAppendSamples(int32_t action, uint32_t pointerCount,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07004088 const PointerProperties* pointerProperties) const {
Jeff Brown4e91a182011-04-07 11:38:09 -07004089 if (this->action != action
4090 || this->pointerCount != pointerCount
4091 || this->isInjected()) {
4092 return false;
4093 }
4094 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07004095 if (this->pointerProperties[i] != pointerProperties[i]) {
Jeff Brown4e91a182011-04-07 11:38:09 -07004096 return false;
4097 }
4098 }
4099 return true;
4100}
4101
Jeff Brownac386072011-07-20 15:19:50 -07004102void InputDispatcher::MotionEntry::appendSample(
4103 nsecs_t eventTime, const PointerCoords* pointerCoords) {
4104 MotionSample* sample = new MotionSample(eventTime, pointerCoords, pointerCount);
4105
4106 lastSample->next = sample;
4107 lastSample = sample;
4108}
4109
4110
4111// --- InputDispatcher::DispatchEntry ---
4112
4113InputDispatcher::DispatchEntry::DispatchEntry(EventEntry* eventEntry,
4114 int32_t targetFlags, float xOffset, float yOffset, float scaleFactor) :
4115 eventEntry(eventEntry), targetFlags(targetFlags),
4116 xOffset(xOffset), yOffset(yOffset), scaleFactor(scaleFactor),
4117 inProgress(false),
4118 resolvedAction(0), resolvedFlags(0),
4119 headMotionSample(NULL), tailMotionSample(NULL) {
4120 eventEntry->refCount += 1;
4121}
4122
4123InputDispatcher::DispatchEntry::~DispatchEntry() {
4124 eventEntry->release();
4125}
4126
Jeff Brownb88102f2010-09-08 11:49:43 -07004127
4128// --- InputDispatcher::InputState ---
4129
Jeff Brownb6997262010-10-08 22:31:17 -07004130InputDispatcher::InputState::InputState() {
Jeff Brownb88102f2010-09-08 11:49:43 -07004131}
4132
4133InputDispatcher::InputState::~InputState() {
4134}
4135
4136bool InputDispatcher::InputState::isNeutral() const {
4137 return mKeyMementos.isEmpty() && mMotionMementos.isEmpty();
4138}
4139
Jeff Brown81346812011-06-28 20:08:48 -07004140bool InputDispatcher::InputState::isHovering(int32_t deviceId, uint32_t source) const {
4141 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4142 const MotionMemento& memento = mMotionMementos.itemAt(i);
4143 if (memento.deviceId == deviceId
4144 && memento.source == source
4145 && memento.hovering) {
4146 return true;
4147 }
4148 }
4149 return false;
4150}
Jeff Brownb88102f2010-09-08 11:49:43 -07004151
Jeff Brown81346812011-06-28 20:08:48 -07004152bool InputDispatcher::InputState::trackKey(const KeyEntry* entry,
4153 int32_t action, int32_t flags) {
4154 switch (action) {
4155 case AKEY_EVENT_ACTION_UP: {
4156 if (entry->flags & AKEY_EVENT_FLAG_FALLBACK) {
4157 for (size_t i = 0; i < mFallbackKeys.size(); ) {
4158 if (mFallbackKeys.valueAt(i) == entry->keyCode) {
4159 mFallbackKeys.removeItemsAt(i);
4160 } else {
4161 i += 1;
4162 }
4163 }
4164 }
4165 ssize_t index = findKeyMemento(entry);
4166 if (index >= 0) {
4167 mKeyMementos.removeAt(index);
4168 return true;
4169 }
4170#if DEBUG_OUTBOUND_EVENT_DETAILS
4171 LOGD("Dropping inconsistent key up event: deviceId=%d, source=%08x, "
4172 "keyCode=%d, scanCode=%d",
4173 entry->deviceId, entry->source, entry->keyCode, entry->scanCode);
4174#endif
4175 return false;
4176 }
4177
4178 case AKEY_EVENT_ACTION_DOWN: {
4179 ssize_t index = findKeyMemento(entry);
4180 if (index >= 0) {
4181 mKeyMementos.removeAt(index);
4182 }
4183 addKeyMemento(entry, flags);
4184 return true;
4185 }
4186
4187 default:
4188 return true;
Jeff Brownb88102f2010-09-08 11:49:43 -07004189 }
4190}
4191
Jeff Brown81346812011-06-28 20:08:48 -07004192bool InputDispatcher::InputState::trackMotion(const MotionEntry* entry,
4193 int32_t action, int32_t flags) {
4194 int32_t actionMasked = action & AMOTION_EVENT_ACTION_MASK;
4195 switch (actionMasked) {
4196 case AMOTION_EVENT_ACTION_UP:
4197 case AMOTION_EVENT_ACTION_CANCEL: {
4198 ssize_t index = findMotionMemento(entry, false /*hovering*/);
4199 if (index >= 0) {
4200 mMotionMementos.removeAt(index);
4201 return true;
Jeff Brownda3d5a92011-03-29 15:11:34 -07004202 }
Jeff Brown81346812011-06-28 20:08:48 -07004203#if DEBUG_OUTBOUND_EVENT_DETAILS
4204 LOGD("Dropping inconsistent motion up or cancel event: deviceId=%d, source=%08x, "
4205 "actionMasked=%d",
4206 entry->deviceId, entry->source, actionMasked);
4207#endif
4208 return false;
Jeff Brownda3d5a92011-03-29 15:11:34 -07004209 }
4210
Jeff Brown81346812011-06-28 20:08:48 -07004211 case AMOTION_EVENT_ACTION_DOWN: {
4212 ssize_t index = findMotionMemento(entry, false /*hovering*/);
4213 if (index >= 0) {
4214 mMotionMementos.removeAt(index);
4215 }
4216 addMotionMemento(entry, flags, false /*hovering*/);
4217 return true;
4218 }
4219
4220 case AMOTION_EVENT_ACTION_POINTER_UP:
4221 case AMOTION_EVENT_ACTION_POINTER_DOWN:
4222 case AMOTION_EVENT_ACTION_MOVE: {
4223 ssize_t index = findMotionMemento(entry, false /*hovering*/);
4224 if (index >= 0) {
4225 MotionMemento& memento = mMotionMementos.editItemAt(index);
4226 memento.setPointers(entry);
4227 return true;
4228 }
Jeff Brown2e45fb62011-06-29 21:19:05 -07004229 if (actionMasked == AMOTION_EVENT_ACTION_MOVE
4230 && (entry->source & (AINPUT_SOURCE_CLASS_JOYSTICK
4231 | AINPUT_SOURCE_CLASS_NAVIGATION))) {
4232 // Joysticks and trackballs can send MOVE events without corresponding DOWN or UP.
4233 return true;
4234 }
Jeff Brown81346812011-06-28 20:08:48 -07004235#if DEBUG_OUTBOUND_EVENT_DETAILS
4236 LOGD("Dropping inconsistent motion pointer up/down or move event: "
4237 "deviceId=%d, source=%08x, actionMasked=%d",
4238 entry->deviceId, entry->source, actionMasked);
4239#endif
4240 return false;
4241 }
4242
4243 case AMOTION_EVENT_ACTION_HOVER_EXIT: {
4244 ssize_t index = findMotionMemento(entry, true /*hovering*/);
4245 if (index >= 0) {
4246 mMotionMementos.removeAt(index);
4247 return true;
4248 }
4249#if DEBUG_OUTBOUND_EVENT_DETAILS
4250 LOGD("Dropping inconsistent motion hover exit event: deviceId=%d, source=%08x",
4251 entry->deviceId, entry->source);
4252#endif
4253 return false;
4254 }
4255
4256 case AMOTION_EVENT_ACTION_HOVER_ENTER:
4257 case AMOTION_EVENT_ACTION_HOVER_MOVE: {
4258 ssize_t index = findMotionMemento(entry, true /*hovering*/);
4259 if (index >= 0) {
4260 mMotionMementos.removeAt(index);
4261 }
4262 addMotionMemento(entry, flags, true /*hovering*/);
4263 return true;
4264 }
4265
4266 default:
4267 return true;
4268 }
4269}
4270
4271ssize_t InputDispatcher::InputState::findKeyMemento(const KeyEntry* entry) const {
Jeff Brownb88102f2010-09-08 11:49:43 -07004272 for (size_t i = 0; i < mKeyMementos.size(); i++) {
Jeff Brown81346812011-06-28 20:08:48 -07004273 const KeyMemento& memento = mKeyMementos.itemAt(i);
Jeff Brownb88102f2010-09-08 11:49:43 -07004274 if (memento.deviceId == entry->deviceId
4275 && memento.source == entry->source
4276 && memento.keyCode == entry->keyCode
4277 && memento.scanCode == entry->scanCode) {
Jeff Brown81346812011-06-28 20:08:48 -07004278 return i;
Jeff Brownb88102f2010-09-08 11:49:43 -07004279 }
4280 }
Jeff Brown81346812011-06-28 20:08:48 -07004281 return -1;
Jeff Brownb88102f2010-09-08 11:49:43 -07004282}
4283
Jeff Brown81346812011-06-28 20:08:48 -07004284ssize_t InputDispatcher::InputState::findMotionMemento(const MotionEntry* entry,
4285 bool hovering) const {
Jeff Brownb88102f2010-09-08 11:49:43 -07004286 for (size_t i = 0; i < mMotionMementos.size(); i++) {
Jeff Brown81346812011-06-28 20:08:48 -07004287 const MotionMemento& memento = mMotionMementos.itemAt(i);
Jeff Brownb88102f2010-09-08 11:49:43 -07004288 if (memento.deviceId == entry->deviceId
Jeff Brown81346812011-06-28 20:08:48 -07004289 && memento.source == entry->source
4290 && memento.hovering == hovering) {
4291 return i;
Jeff Brownb88102f2010-09-08 11:49:43 -07004292 }
4293 }
Jeff Brown81346812011-06-28 20:08:48 -07004294 return -1;
4295}
Jeff Brownb88102f2010-09-08 11:49:43 -07004296
Jeff Brown81346812011-06-28 20:08:48 -07004297void InputDispatcher::InputState::addKeyMemento(const KeyEntry* entry, int32_t flags) {
4298 mKeyMementos.push();
4299 KeyMemento& memento = mKeyMementos.editTop();
4300 memento.deviceId = entry->deviceId;
4301 memento.source = entry->source;
4302 memento.keyCode = entry->keyCode;
4303 memento.scanCode = entry->scanCode;
4304 memento.flags = flags;
4305 memento.downTime = entry->downTime;
4306}
4307
4308void InputDispatcher::InputState::addMotionMemento(const MotionEntry* entry,
4309 int32_t flags, bool hovering) {
4310 mMotionMementos.push();
4311 MotionMemento& memento = mMotionMementos.editTop();
4312 memento.deviceId = entry->deviceId;
4313 memento.source = entry->source;
4314 memento.flags = flags;
4315 memento.xPrecision = entry->xPrecision;
4316 memento.yPrecision = entry->yPrecision;
4317 memento.downTime = entry->downTime;
4318 memento.setPointers(entry);
4319 memento.hovering = hovering;
Jeff Brownb88102f2010-09-08 11:49:43 -07004320}
4321
4322void InputDispatcher::InputState::MotionMemento::setPointers(const MotionEntry* entry) {
4323 pointerCount = entry->pointerCount;
4324 for (uint32_t i = 0; i < entry->pointerCount; i++) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07004325 pointerProperties[i].copyFrom(entry->pointerProperties[i]);
Jeff Brownace13b12011-03-09 17:39:48 -08004326 pointerCoords[i].copyFrom(entry->lastSample->pointerCoords[i]);
Jeff Brownb88102f2010-09-08 11:49:43 -07004327 }
4328}
4329
Jeff Brownb6997262010-10-08 22:31:17 -07004330void InputDispatcher::InputState::synthesizeCancelationEvents(nsecs_t currentTime,
Jeff Brownac386072011-07-20 15:19:50 -07004331 Vector<EventEntry*>& outEvents, const CancelationOptions& options) {
Jeff Brown81346812011-06-28 20:08:48 -07004332 for (size_t i = 0; i < mKeyMementos.size(); i++) {
Jeff Brownb88102f2010-09-08 11:49:43 -07004333 const KeyMemento& memento = mKeyMementos.itemAt(i);
Jeff Brown49ed71d2010-12-06 17:13:33 -08004334 if (shouldCancelKey(memento, options)) {
Jeff Brownac386072011-07-20 15:19:50 -07004335 outEvents.push(new KeyEntry(currentTime,
Jeff Brownb6997262010-10-08 22:31:17 -07004336 memento.deviceId, memento.source, 0,
Jeff Brown49ed71d2010-12-06 17:13:33 -08004337 AKEY_EVENT_ACTION_UP, memento.flags | AKEY_EVENT_FLAG_CANCELED,
Jeff Brownb6997262010-10-08 22:31:17 -07004338 memento.keyCode, memento.scanCode, 0, 0, memento.downTime));
Jeff Brownb6997262010-10-08 22:31:17 -07004339 }
Jeff Brownb88102f2010-09-08 11:49:43 -07004340 }
4341
Jeff Brown81346812011-06-28 20:08:48 -07004342 for (size_t i = 0; i < mMotionMementos.size(); i++) {
Jeff Brownb88102f2010-09-08 11:49:43 -07004343 const MotionMemento& memento = mMotionMementos.itemAt(i);
Jeff Brown49ed71d2010-12-06 17:13:33 -08004344 if (shouldCancelMotion(memento, options)) {
Jeff Brownac386072011-07-20 15:19:50 -07004345 outEvents.push(new MotionEntry(currentTime,
Jeff Brownb6997262010-10-08 22:31:17 -07004346 memento.deviceId, memento.source, 0,
Jeff Browna032cc02011-03-07 16:56:21 -08004347 memento.hovering
4348 ? AMOTION_EVENT_ACTION_HOVER_EXIT
4349 : AMOTION_EVENT_ACTION_CANCEL,
Jeff Brown81346812011-06-28 20:08:48 -07004350 memento.flags, 0, 0, 0,
Jeff Brownb6997262010-10-08 22:31:17 -07004351 memento.xPrecision, memento.yPrecision, memento.downTime,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07004352 memento.pointerCount, memento.pointerProperties, memento.pointerCoords));
Jeff Brownb6997262010-10-08 22:31:17 -07004353 }
Jeff Brownb88102f2010-09-08 11:49:43 -07004354 }
4355}
4356
4357void InputDispatcher::InputState::clear() {
4358 mKeyMementos.clear();
4359 mMotionMementos.clear();
Jeff Brownda3d5a92011-03-29 15:11:34 -07004360 mFallbackKeys.clear();
Jeff Brownb6997262010-10-08 22:31:17 -07004361}
4362
Jeff Brown9c9f1a32010-10-11 18:32:20 -07004363void InputDispatcher::InputState::copyPointerStateTo(InputState& other) const {
4364 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4365 const MotionMemento& memento = mMotionMementos.itemAt(i);
4366 if (memento.source & AINPUT_SOURCE_CLASS_POINTER) {
4367 for (size_t j = 0; j < other.mMotionMementos.size(); ) {
4368 const MotionMemento& otherMemento = other.mMotionMementos.itemAt(j);
4369 if (memento.deviceId == otherMemento.deviceId
4370 && memento.source == otherMemento.source) {
4371 other.mMotionMementos.removeAt(j);
4372 } else {
4373 j += 1;
4374 }
4375 }
4376 other.mMotionMementos.push(memento);
4377 }
4378 }
4379}
4380
Jeff Brownda3d5a92011-03-29 15:11:34 -07004381int32_t InputDispatcher::InputState::getFallbackKey(int32_t originalKeyCode) {
4382 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
4383 return index >= 0 ? mFallbackKeys.valueAt(index) : -1;
4384}
4385
4386void InputDispatcher::InputState::setFallbackKey(int32_t originalKeyCode,
4387 int32_t fallbackKeyCode) {
4388 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
4389 if (index >= 0) {
4390 mFallbackKeys.replaceValueAt(index, fallbackKeyCode);
4391 } else {
4392 mFallbackKeys.add(originalKeyCode, fallbackKeyCode);
4393 }
4394}
4395
4396void InputDispatcher::InputState::removeFallbackKey(int32_t originalKeyCode) {
4397 mFallbackKeys.removeItem(originalKeyCode);
4398}
4399
Jeff Brown49ed71d2010-12-06 17:13:33 -08004400bool InputDispatcher::InputState::shouldCancelKey(const KeyMemento& memento,
Jeff Brownda3d5a92011-03-29 15:11:34 -07004401 const CancelationOptions& options) {
4402 if (options.keyCode != -1 && memento.keyCode != options.keyCode) {
4403 return false;
4404 }
4405
4406 switch (options.mode) {
4407 case CancelationOptions::CANCEL_ALL_EVENTS:
4408 case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
Jeff Brownb6997262010-10-08 22:31:17 -07004409 return true;
Jeff Brownda3d5a92011-03-29 15:11:34 -07004410 case CancelationOptions::CANCEL_FALLBACK_EVENTS:
Jeff Brown49ed71d2010-12-06 17:13:33 -08004411 return memento.flags & AKEY_EVENT_FLAG_FALLBACK;
4412 default:
4413 return false;
4414 }
4415}
4416
4417bool InputDispatcher::InputState::shouldCancelMotion(const MotionMemento& memento,
Jeff Brownda3d5a92011-03-29 15:11:34 -07004418 const CancelationOptions& options) {
4419 switch (options.mode) {
4420 case CancelationOptions::CANCEL_ALL_EVENTS:
Jeff Brown49ed71d2010-12-06 17:13:33 -08004421 return true;
Jeff Brownda3d5a92011-03-29 15:11:34 -07004422 case CancelationOptions::CANCEL_POINTER_EVENTS:
Jeff Brown49ed71d2010-12-06 17:13:33 -08004423 return memento.source & AINPUT_SOURCE_CLASS_POINTER;
Jeff Brownda3d5a92011-03-29 15:11:34 -07004424 case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
Jeff Brown49ed71d2010-12-06 17:13:33 -08004425 return !(memento.source & AINPUT_SOURCE_CLASS_POINTER);
4426 default:
4427 return false;
Jeff Brownb6997262010-10-08 22:31:17 -07004428 }
Jeff Brownb88102f2010-09-08 11:49:43 -07004429}
4430
4431
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004432// --- InputDispatcher::Connection ---
4433
Jeff Brown928e0542011-01-10 11:17:36 -08004434InputDispatcher::Connection::Connection(const sp<InputChannel>& inputChannel,
4435 const sp<InputWindowHandle>& inputWindowHandle) :
4436 status(STATUS_NORMAL), inputChannel(inputChannel), inputWindowHandle(inputWindowHandle),
4437 inputPublisher(inputChannel),
Jeff Brownda3d5a92011-03-29 15:11:34 -07004438 lastEventTime(LONG_LONG_MAX), lastDispatchTime(LONG_LONG_MAX) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004439}
4440
4441InputDispatcher::Connection::~Connection() {
4442}
4443
4444status_t InputDispatcher::Connection::initialize() {
4445 return inputPublisher.initialize();
4446}
4447
Jeff Brown9c3cda02010-06-15 01:31:58 -07004448const char* InputDispatcher::Connection::getStatusLabel() const {
4449 switch (status) {
4450 case STATUS_NORMAL:
4451 return "NORMAL";
4452
4453 case STATUS_BROKEN:
4454 return "BROKEN";
4455
Jeff Brown9c3cda02010-06-15 01:31:58 -07004456 case STATUS_ZOMBIE:
4457 return "ZOMBIE";
4458
4459 default:
4460 return "UNKNOWN";
4461 }
4462}
4463
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004464InputDispatcher::DispatchEntry* InputDispatcher::Connection::findQueuedDispatchEntryForEvent(
4465 const EventEntry* eventEntry) const {
Jeff Brownac386072011-07-20 15:19:50 -07004466 for (DispatchEntry* dispatchEntry = outboundQueue.tail; dispatchEntry;
4467 dispatchEntry = dispatchEntry->prev) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004468 if (dispatchEntry->eventEntry == eventEntry) {
4469 return dispatchEntry;
4470 }
4471 }
4472 return NULL;
4473}
4474
Jeff Brownb88102f2010-09-08 11:49:43 -07004475
Jeff Brown9c3cda02010-06-15 01:31:58 -07004476// --- InputDispatcher::CommandEntry ---
4477
Jeff Brownac386072011-07-20 15:19:50 -07004478InputDispatcher::CommandEntry::CommandEntry(Command command) :
4479 command(command), eventTime(0), keyEntry(NULL), userActivityEventType(0), handled(false) {
Jeff Brown9c3cda02010-06-15 01:31:58 -07004480}
4481
4482InputDispatcher::CommandEntry::~CommandEntry() {
4483}
4484
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004485
Jeff Brown01ce2e92010-09-26 22:20:12 -07004486// --- InputDispatcher::TouchState ---
4487
4488InputDispatcher::TouchState::TouchState() :
Jeff Brown58a2da82011-01-25 16:02:22 -08004489 down(false), split(false), deviceId(-1), source(0) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07004490}
4491
4492InputDispatcher::TouchState::~TouchState() {
4493}
4494
4495void InputDispatcher::TouchState::reset() {
4496 down = false;
4497 split = false;
Jeff Brown95712852011-01-04 19:41:59 -08004498 deviceId = -1;
Jeff Brown58a2da82011-01-25 16:02:22 -08004499 source = 0;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004500 windows.clear();
4501}
4502
4503void InputDispatcher::TouchState::copyFrom(const TouchState& other) {
4504 down = other.down;
4505 split = other.split;
Jeff Brown95712852011-01-04 19:41:59 -08004506 deviceId = other.deviceId;
Jeff Brown58a2da82011-01-25 16:02:22 -08004507 source = other.source;
Jeff Brown9302c872011-07-13 22:51:29 -07004508 windows = other.windows;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004509}
4510
Jeff Brown9302c872011-07-13 22:51:29 -07004511void InputDispatcher::TouchState::addOrUpdateWindow(const sp<InputWindowHandle>& windowHandle,
Jeff Brown01ce2e92010-09-26 22:20:12 -07004512 int32_t targetFlags, BitSet32 pointerIds) {
4513 if (targetFlags & InputTarget::FLAG_SPLIT) {
4514 split = true;
4515 }
4516
4517 for (size_t i = 0; i < windows.size(); i++) {
4518 TouchedWindow& touchedWindow = windows.editItemAt(i);
Jeff Brown9302c872011-07-13 22:51:29 -07004519 if (touchedWindow.windowHandle == windowHandle) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07004520 touchedWindow.targetFlags |= targetFlags;
Jeff Brown98db5fa2011-06-08 15:37:10 -07004521 if (targetFlags & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
4522 touchedWindow.targetFlags &= ~InputTarget::FLAG_DISPATCH_AS_IS;
4523 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07004524 touchedWindow.pointerIds.value |= pointerIds.value;
4525 return;
4526 }
4527 }
4528
4529 windows.push();
4530
4531 TouchedWindow& touchedWindow = windows.editTop();
Jeff Brown9302c872011-07-13 22:51:29 -07004532 touchedWindow.windowHandle = windowHandle;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004533 touchedWindow.targetFlags = targetFlags;
4534 touchedWindow.pointerIds = pointerIds;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004535}
4536
Jeff Browna032cc02011-03-07 16:56:21 -08004537void InputDispatcher::TouchState::filterNonAsIsTouchWindows() {
Jeff Brown01ce2e92010-09-26 22:20:12 -07004538 for (size_t i = 0 ; i < windows.size(); ) {
Jeff Browna032cc02011-03-07 16:56:21 -08004539 TouchedWindow& window = windows.editItemAt(i);
Jeff Brown98db5fa2011-06-08 15:37:10 -07004540 if (window.targetFlags & (InputTarget::FLAG_DISPATCH_AS_IS
4541 | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER)) {
Jeff Browna032cc02011-03-07 16:56:21 -08004542 window.targetFlags &= ~InputTarget::FLAG_DISPATCH_MASK;
4543 window.targetFlags |= InputTarget::FLAG_DISPATCH_AS_IS;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004544 i += 1;
Jeff Browna032cc02011-03-07 16:56:21 -08004545 } else {
4546 windows.removeAt(i);
Jeff Brown01ce2e92010-09-26 22:20:12 -07004547 }
4548 }
4549}
4550
Jeff Brown9302c872011-07-13 22:51:29 -07004551sp<InputWindowHandle> InputDispatcher::TouchState::getFirstForegroundWindowHandle() const {
Jeff Brown01ce2e92010-09-26 22:20:12 -07004552 for (size_t i = 0; i < windows.size(); i++) {
Jeff Brown98db5fa2011-06-08 15:37:10 -07004553 const TouchedWindow& window = windows.itemAt(i);
4554 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
Jeff Brown9302c872011-07-13 22:51:29 -07004555 return window.windowHandle;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004556 }
4557 }
4558 return NULL;
4559}
4560
Jeff Brown98db5fa2011-06-08 15:37:10 -07004561bool InputDispatcher::TouchState::isSlippery() const {
4562 // Must have exactly one foreground window.
4563 bool haveSlipperyForegroundWindow = false;
4564 for (size_t i = 0; i < windows.size(); i++) {
4565 const TouchedWindow& window = windows.itemAt(i);
4566 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
Jeff Brown9302c872011-07-13 22:51:29 -07004567 if (haveSlipperyForegroundWindow || !(window.windowHandle->layoutParamsFlags
4568 & InputWindowHandle::FLAG_SLIPPERY)) {
Jeff Brown98db5fa2011-06-08 15:37:10 -07004569 return false;
4570 }
4571 haveSlipperyForegroundWindow = true;
4572 }
4573 }
4574 return haveSlipperyForegroundWindow;
4575}
4576
Jeff Brown01ce2e92010-09-26 22:20:12 -07004577
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004578// --- InputDispatcherThread ---
4579
4580InputDispatcherThread::InputDispatcherThread(const sp<InputDispatcherInterface>& dispatcher) :
4581 Thread(/*canCallJava*/ true), mDispatcher(dispatcher) {
4582}
4583
4584InputDispatcherThread::~InputDispatcherThread() {
4585}
4586
4587bool InputDispatcherThread::threadLoop() {
4588 mDispatcher->dispatchOnce();
4589 return true;
4590}
4591
4592} // namespace android