blob: af139452e27e9c1c250aa8557a4d9d6a5c289b2f [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 Brownac386072011-07-20 15:19:50 -0700669 entry->release();
Jeff Brownb88102f2010-09-08 11:49:43 -0700670}
671
Jeff Brownb88102f2010-09-08 11:49:43 -0700672void InputDispatcher::resetKeyRepeatLocked() {
673 if (mKeyRepeatState.lastKeyEntry) {
Jeff Brownac386072011-07-20 15:19:50 -0700674 mKeyRepeatState.lastKeyEntry->release();
Jeff Brownb88102f2010-09-08 11:49:43 -0700675 mKeyRepeatState.lastKeyEntry = NULL;
676 }
677}
678
Jeff Brown214eaf42011-05-26 19:17:02 -0700679InputDispatcher::KeyEntry* InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
Jeff Brown349703e2010-06-22 01:27:15 -0700680 KeyEntry* entry = mKeyRepeatState.lastKeyEntry;
681
Jeff Brown349703e2010-06-22 01:27:15 -0700682 // Reuse the repeated key entry if it is otherwise unreferenced.
Jeff Browne20c9e02010-10-11 14:20:19 -0700683 uint32_t policyFlags = (entry->policyFlags & POLICY_FLAG_RAW_MASK)
684 | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700685 if (entry->refCount == 1) {
Jeff Brownac386072011-07-20 15:19:50 -0700686 entry->recycle();
Jeff Brown7fbdc842010-06-17 20:52:56 -0700687 entry->eventTime = currentTime;
Jeff Brown7fbdc842010-06-17 20:52:56 -0700688 entry->policyFlags = policyFlags;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700689 entry->repeatCount += 1;
690 } else {
Jeff Brownac386072011-07-20 15:19:50 -0700691 KeyEntry* newEntry = new KeyEntry(currentTime,
Jeff Brownc5ed5912010-07-14 18:48:53 -0700692 entry->deviceId, entry->source, policyFlags,
Jeff Brown7fbdc842010-06-17 20:52:56 -0700693 entry->action, entry->flags, entry->keyCode, entry->scanCode,
Jeff Brown00fa7bd2010-07-02 15:37:36 -0700694 entry->metaState, entry->repeatCount + 1, entry->downTime);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700695
696 mKeyRepeatState.lastKeyEntry = newEntry;
Jeff Brownac386072011-07-20 15:19:50 -0700697 entry->release();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700698
699 entry = newEntry;
700 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700701 entry->syntheticRepeat = true;
702
703 // Increment reference count since we keep a reference to the event in
704 // mKeyRepeatState.lastKeyEntry in addition to the one we return.
705 entry->refCount += 1;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700706
Jeff Brown214eaf42011-05-26 19:17:02 -0700707 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Jeff Brownb88102f2010-09-08 11:49:43 -0700708 return entry;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700709}
710
Jeff Brownb88102f2010-09-08 11:49:43 -0700711bool InputDispatcher::dispatchConfigurationChangedLocked(
712 nsecs_t currentTime, ConfigurationChangedEntry* entry) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700713#if DEBUG_OUTBOUND_EVENT_DETAILS
Jeff Brownb88102f2010-09-08 11:49:43 -0700714 LOGD("dispatchConfigurationChanged - eventTime=%lld", entry->eventTime);
715#endif
716
717 // Reset key repeating in case a keyboard device was added or removed or something.
718 resetKeyRepeatLocked();
719
720 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
721 CommandEntry* commandEntry = postCommandLocked(
722 & InputDispatcher::doNotifyConfigurationChangedInterruptible);
723 commandEntry->eventTime = entry->eventTime;
724 return true;
725}
726
Jeff Brown214eaf42011-05-26 19:17:02 -0700727bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, KeyEntry* entry,
Jeff Browne20c9e02010-10-11 14:20:19 -0700728 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Jeff Browne46a0a42010-11-02 17:58:22 -0700729 // Preprocessing.
730 if (! entry->dispatchInProgress) {
731 if (entry->repeatCount == 0
732 && entry->action == AKEY_EVENT_ACTION_DOWN
733 && (entry->policyFlags & POLICY_FLAG_TRUSTED)
Jeff Brown0029c662011-03-30 02:25:18 -0700734 && (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
Jeff Browne46a0a42010-11-02 17:58:22 -0700735 if (mKeyRepeatState.lastKeyEntry
736 && mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode) {
737 // We have seen two identical key downs in a row which indicates that the device
738 // driver is automatically generating key repeats itself. We take note of the
739 // repeat here, but we disable our own next key repeat timer since it is clear that
740 // we will not need to synthesize key repeats ourselves.
741 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
742 resetKeyRepeatLocked();
743 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
744 } else {
745 // Not a repeat. Save key down state in case we do see a repeat later.
746 resetKeyRepeatLocked();
Jeff Brown214eaf42011-05-26 19:17:02 -0700747 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
Jeff Browne46a0a42010-11-02 17:58:22 -0700748 }
749 mKeyRepeatState.lastKeyEntry = entry;
750 entry->refCount += 1;
751 } else if (! entry->syntheticRepeat) {
752 resetKeyRepeatLocked();
753 }
754
Jeff Browne2e01262011-03-02 20:34:30 -0800755 if (entry->repeatCount == 1) {
756 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
757 } else {
758 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
759 }
760
Jeff Browne46a0a42010-11-02 17:58:22 -0700761 entry->dispatchInProgress = true;
762 resetTargetsLocked();
763
764 logOutboundKeyDetailsLocked("dispatchKey - ", entry);
765 }
766
Jeff Brown54a18252010-09-16 14:07:33 -0700767 // Give the policy a chance to intercept the key.
768 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
Jeff Browne20c9e02010-10-11 14:20:19 -0700769 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Jeff Brown54a18252010-09-16 14:07:33 -0700770 CommandEntry* commandEntry = postCommandLocked(
771 & InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
Jeff Brown9302c872011-07-13 22:51:29 -0700772 if (mFocusedWindowHandle != NULL) {
773 commandEntry->inputWindowHandle = mFocusedWindowHandle;
Jeff Brown54a18252010-09-16 14:07:33 -0700774 }
775 commandEntry->keyEntry = entry;
776 entry->refCount += 1;
777 return false; // wait for the command to run
778 } else {
779 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
780 }
781 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Jeff Browne20c9e02010-10-11 14:20:19 -0700782 if (*dropReason == DROP_REASON_NOT_DROPPED) {
783 *dropReason = DROP_REASON_POLICY;
784 }
Jeff Brown54a18252010-09-16 14:07:33 -0700785 }
786
787 // Clean up if dropping the event.
Jeff Browne20c9e02010-10-11 14:20:19 -0700788 if (*dropReason != DROP_REASON_NOT_DROPPED) {
Jeff Brown54a18252010-09-16 14:07:33 -0700789 resetTargetsLocked();
Jeff Brown3122e442010-10-11 23:32:49 -0700790 setInjectionResultLocked(entry, *dropReason == DROP_REASON_POLICY
791 ? INPUT_EVENT_INJECTION_SUCCEEDED : INPUT_EVENT_INJECTION_FAILED);
Jeff Brown54a18252010-09-16 14:07:33 -0700792 return true;
793 }
794
Jeff Brownb88102f2010-09-08 11:49:43 -0700795 // Identify targets.
796 if (! mCurrentInputTargetsValid) {
Jeff Brown01ce2e92010-09-26 22:20:12 -0700797 int32_t injectionResult = findFocusedWindowTargetsLocked(currentTime,
798 entry, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700799 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
800 return false;
801 }
802
803 setInjectionResultLocked(entry, injectionResult);
804 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
805 return true;
806 }
807
808 addMonitoringTargetsLocked();
Jeff Brown01ce2e92010-09-26 22:20:12 -0700809 commitTargetsLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -0700810 }
811
812 // Dispatch the key.
813 dispatchEventToCurrentInputTargetsLocked(currentTime, entry, false);
Jeff Brownb88102f2010-09-08 11:49:43 -0700814 return true;
815}
816
817void InputDispatcher::logOutboundKeyDetailsLocked(const char* prefix, const KeyEntry* entry) {
818#if DEBUG_OUTBOUND_EVENT_DETAILS
Jeff Brown90655042010-12-02 13:50:46 -0800819 LOGD("%seventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, "
Jeff Brownb88102f2010-09-08 11:49:43 -0700820 "action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, "
Jeff Browne46a0a42010-11-02 17:58:22 -0700821 "repeatCount=%d, downTime=%lld",
Jeff Brownb88102f2010-09-08 11:49:43 -0700822 prefix,
823 entry->eventTime, entry->deviceId, entry->source, entry->policyFlags,
824 entry->action, entry->flags, entry->keyCode, entry->scanCode, entry->metaState,
Jeff Browne46a0a42010-11-02 17:58:22 -0700825 entry->repeatCount, entry->downTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700826#endif
827}
828
829bool InputDispatcher::dispatchMotionLocked(
Jeff Browne20c9e02010-10-11 14:20:19 -0700830 nsecs_t currentTime, MotionEntry* entry, DropReason* dropReason, nsecs_t* nextWakeupTime) {
Jeff Browne46a0a42010-11-02 17:58:22 -0700831 // Preprocessing.
832 if (! entry->dispatchInProgress) {
833 entry->dispatchInProgress = true;
834 resetTargetsLocked();
835
836 logOutboundMotionDetailsLocked("dispatchMotion - ", entry);
837 }
838
Jeff Brown54a18252010-09-16 14:07:33 -0700839 // Clean up if dropping the event.
Jeff Browne20c9e02010-10-11 14:20:19 -0700840 if (*dropReason != DROP_REASON_NOT_DROPPED) {
Jeff Brown54a18252010-09-16 14:07:33 -0700841 resetTargetsLocked();
Jeff Brown3122e442010-10-11 23:32:49 -0700842 setInjectionResultLocked(entry, *dropReason == DROP_REASON_POLICY
843 ? INPUT_EVENT_INJECTION_SUCCEEDED : INPUT_EVENT_INJECTION_FAILED);
Jeff Brown54a18252010-09-16 14:07:33 -0700844 return true;
845 }
846
Jeff Brownb88102f2010-09-08 11:49:43 -0700847 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
848
849 // Identify targets.
Jeff Browncc0c1592011-02-19 05:07:28 -0800850 bool conflictingPointerActions = false;
Jeff Brownb88102f2010-09-08 11:49:43 -0700851 if (! mCurrentInputTargetsValid) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700852 int32_t injectionResult;
Jeff Browna032cc02011-03-07 16:56:21 -0800853 const MotionSample* splitBatchAfterSample = NULL;
Jeff Brownb88102f2010-09-08 11:49:43 -0700854 if (isPointerEvent) {
855 // Pointer event. (eg. touchscreen)
Jeff Brown01ce2e92010-09-26 22:20:12 -0700856 injectionResult = findTouchedWindowTargetsLocked(currentTime,
Jeff Browna032cc02011-03-07 16:56:21 -0800857 entry, nextWakeupTime, &conflictingPointerActions, &splitBatchAfterSample);
Jeff Brownb88102f2010-09-08 11:49:43 -0700858 } else {
859 // Non touch event. (eg. trackball)
Jeff Brown01ce2e92010-09-26 22:20:12 -0700860 injectionResult = findFocusedWindowTargetsLocked(currentTime,
861 entry, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700862 }
863 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
864 return false;
865 }
866
867 setInjectionResultLocked(entry, injectionResult);
868 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
869 return true;
870 }
871
872 addMonitoringTargetsLocked();
Jeff Brown01ce2e92010-09-26 22:20:12 -0700873 commitTargetsLocked();
Jeff Browna032cc02011-03-07 16:56:21 -0800874
875 // Unbatch the event if necessary by splitting it into two parts after the
876 // motion sample indicated by splitBatchAfterSample.
877 if (splitBatchAfterSample && splitBatchAfterSample->next) {
878#if DEBUG_BATCHING
879 uint32_t originalSampleCount = entry->countSamples();
880#endif
881 MotionSample* nextSample = splitBatchAfterSample->next;
Jeff Brownac386072011-07-20 15:19:50 -0700882 MotionEntry* nextEntry = new MotionEntry(nextSample->eventTime,
Jeff Browna032cc02011-03-07 16:56:21 -0800883 entry->deviceId, entry->source, entry->policyFlags,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700884 entry->action, entry->flags,
885 entry->metaState, entry->buttonState, entry->edgeFlags,
Jeff Browna032cc02011-03-07 16:56:21 -0800886 entry->xPrecision, entry->yPrecision, entry->downTime,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700887 entry->pointerCount, entry->pointerProperties, nextSample->pointerCoords);
Jeff Browna032cc02011-03-07 16:56:21 -0800888 if (nextSample != entry->lastSample) {
889 nextEntry->firstSample.next = nextSample->next;
890 nextEntry->lastSample = entry->lastSample;
891 }
Jeff Brownac386072011-07-20 15:19:50 -0700892 delete nextSample;
Jeff Browna032cc02011-03-07 16:56:21 -0800893
894 entry->lastSample = const_cast<MotionSample*>(splitBatchAfterSample);
895 entry->lastSample->next = NULL;
896
897 if (entry->injectionState) {
898 nextEntry->injectionState = entry->injectionState;
899 entry->injectionState->refCount += 1;
900 }
901
902#if DEBUG_BATCHING
903 LOGD("Split batch of %d samples into two parts, first part has %d samples, "
904 "second part has %d samples.", originalSampleCount,
905 entry->countSamples(), nextEntry->countSamples());
906#endif
907
908 mInboundQueue.enqueueAtHead(nextEntry);
909 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700910 }
911
912 // Dispatch the motion.
Jeff Browncc0c1592011-02-19 05:07:28 -0800913 if (conflictingPointerActions) {
Jeff Brownda3d5a92011-03-29 15:11:34 -0700914 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
915 "conflicting pointer actions");
916 synthesizeCancelationEventsForAllConnectionsLocked(options);
Jeff Browncc0c1592011-02-19 05:07:28 -0800917 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700918 dispatchEventToCurrentInputTargetsLocked(currentTime, entry, false);
Jeff Brownb88102f2010-09-08 11:49:43 -0700919 return true;
920}
921
922
923void InputDispatcher::logOutboundMotionDetailsLocked(const char* prefix, const MotionEntry* entry) {
924#if DEBUG_OUTBOUND_EVENT_DETAILS
Jeff Brown90655042010-12-02 13:50:46 -0800925 LOGD("%seventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, "
Jeff Brown85a31762010-09-01 17:01:00 -0700926 "action=0x%x, flags=0x%x, "
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700927 "metaState=0x%x, buttonState=0x%x, "
928 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%lld",
Jeff Brownb88102f2010-09-08 11:49:43 -0700929 prefix,
Jeff Brown85a31762010-09-01 17:01:00 -0700930 entry->eventTime, entry->deviceId, entry->source, entry->policyFlags,
931 entry->action, entry->flags,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700932 entry->metaState, entry->buttonState,
933 entry->edgeFlags, entry->xPrecision, entry->yPrecision,
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700934 entry->downTime);
935
936 // Print the most recent sample that we have available, this may change due to batching.
937 size_t sampleCount = 1;
Jeff Brownb88102f2010-09-08 11:49:43 -0700938 const MotionSample* sample = & entry->firstSample;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700939 for (; sample->next != NULL; sample = sample->next) {
940 sampleCount += 1;
941 }
942 for (uint32_t i = 0; i < entry->pointerCount; i++) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700943 LOGD(" Pointer %d: id=%d, toolType=%d, "
944 "x=%f, y=%f, pressure=%f, size=%f, "
Jeff Brown85a31762010-09-01 17:01:00 -0700945 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
Jeff Brown8d608662010-08-30 03:02:23 -0700946 "orientation=%f",
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700947 i, entry->pointerProperties[i].id,
948 entry->pointerProperties[i].toolType,
Jeff Brownebbd5d12011-02-17 13:01:34 -0800949 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
950 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
951 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
952 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
953 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
954 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
955 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
956 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
957 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700958 }
959
960 // Keep in mind that due to batching, it is possible for the number of samples actually
961 // dispatched to change before the application finally consumed them.
Jeff Brownc5ed5912010-07-14 18:48:53 -0700962 if (entry->action == AMOTION_EVENT_ACTION_MOVE) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700963 LOGD(" ... Total movement samples currently batched %d ...", sampleCount);
964 }
965#endif
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700966}
967
968void InputDispatcher::dispatchEventToCurrentInputTargetsLocked(nsecs_t currentTime,
969 EventEntry* eventEntry, bool resumeWithAppendedMotionSample) {
970#if DEBUG_DISPATCH_CYCLE
Jeff Brown9c3cda02010-06-15 01:31:58 -0700971 LOGD("dispatchEventToCurrentInputTargets - "
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700972 "resumeWithAppendedMotionSample=%s",
Jeff Brownb88102f2010-09-08 11:49:43 -0700973 toString(resumeWithAppendedMotionSample));
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700974#endif
975
Jeff Brownb6110c22011-04-01 16:15:13 -0700976 LOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
Jeff Brown9c3cda02010-06-15 01:31:58 -0700977
Jeff Browne2fe69e2010-10-18 13:21:23 -0700978 pokeUserActivityLocked(eventEntry);
979
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700980 for (size_t i = 0; i < mCurrentInputTargets.size(); i++) {
981 const InputTarget& inputTarget = mCurrentInputTargets.itemAt(i);
982
Jeff Brown519e0242010-09-15 15:18:56 -0700983 ssize_t connectionIndex = getConnectionIndexLocked(inputTarget.inputChannel);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700984 if (connectionIndex >= 0) {
985 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
Jeff Brown7fbdc842010-06-17 20:52:56 -0700986 prepareDispatchCycleLocked(currentTime, connection, eventEntry, & inputTarget,
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700987 resumeWithAppendedMotionSample);
988 } else {
Jeff Brownb6997262010-10-08 22:31:17 -0700989#if DEBUG_FOCUS
990 LOGD("Dropping event delivery to target with channel '%s' because it "
991 "is no longer registered with the input dispatcher.",
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700992 inputTarget.inputChannel->getName().string());
Jeff Brownb6997262010-10-08 22:31:17 -0700993#endif
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700994 }
995 }
996}
997
Jeff Brown54a18252010-09-16 14:07:33 -0700998void InputDispatcher::resetTargetsLocked() {
Jeff Brownb88102f2010-09-08 11:49:43 -0700999 mCurrentInputTargetsValid = false;
1000 mCurrentInputTargets.clear();
Jeff Brown5ea29ab2011-07-27 11:50:51 -07001001 resetANRTimeoutsLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -07001002}
1003
Jeff Brown01ce2e92010-09-26 22:20:12 -07001004void InputDispatcher::commitTargetsLocked() {
Jeff Brownb88102f2010-09-08 11:49:43 -07001005 mCurrentInputTargetsValid = true;
1006}
1007
1008int32_t InputDispatcher::handleTargetsNotReadyLocked(nsecs_t currentTime,
Jeff Brown9302c872011-07-13 22:51:29 -07001009 const EventEntry* entry,
1010 const sp<InputApplicationHandle>& applicationHandle,
1011 const sp<InputWindowHandle>& windowHandle,
Jeff Brownb88102f2010-09-08 11:49:43 -07001012 nsecs_t* nextWakeupTime) {
Jeff Brown9302c872011-07-13 22:51:29 -07001013 if (applicationHandle == NULL && windowHandle == NULL) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001014 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY) {
1015#if DEBUG_FOCUS
1016 LOGD("Waiting for system to become ready for input.");
1017#endif
1018 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY;
1019 mInputTargetWaitStartTime = currentTime;
1020 mInputTargetWaitTimeoutTime = LONG_LONG_MAX;
1021 mInputTargetWaitTimeoutExpired = false;
Jeff Brown9302c872011-07-13 22:51:29 -07001022 mInputTargetWaitApplicationHandle.clear();
Jeff Brownb88102f2010-09-08 11:49:43 -07001023 }
1024 } else {
1025 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
1026#if DEBUG_FOCUS
Jeff Brown519e0242010-09-15 15:18:56 -07001027 LOGD("Waiting for application to become ready for input: %s",
Jeff Brown9302c872011-07-13 22:51:29 -07001028 getApplicationWindowLabelLocked(applicationHandle, windowHandle).string());
Jeff Brownb88102f2010-09-08 11:49:43 -07001029#endif
Jeff Brown9302c872011-07-13 22:51:29 -07001030 nsecs_t timeout = windowHandle != NULL ? windowHandle->dispatchingTimeout :
1031 applicationHandle != NULL ?
1032 applicationHandle->dispatchingTimeout : DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Jeff Brownb88102f2010-09-08 11:49:43 -07001033
1034 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY;
1035 mInputTargetWaitStartTime = currentTime;
1036 mInputTargetWaitTimeoutTime = currentTime + timeout;
1037 mInputTargetWaitTimeoutExpired = false;
Jeff Brown9302c872011-07-13 22:51:29 -07001038 mInputTargetWaitApplicationHandle.clear();
Jeff Brown928e0542011-01-10 11:17:36 -08001039
Jeff Brown9302c872011-07-13 22:51:29 -07001040 if (windowHandle != NULL) {
1041 mInputTargetWaitApplicationHandle = windowHandle->inputApplicationHandle;
Jeff Brown928e0542011-01-10 11:17:36 -08001042 }
Jeff Brown9302c872011-07-13 22:51:29 -07001043 if (mInputTargetWaitApplicationHandle == NULL && applicationHandle != NULL) {
1044 mInputTargetWaitApplicationHandle = applicationHandle;
Jeff Brown928e0542011-01-10 11:17:36 -08001045 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001046 }
1047 }
1048
1049 if (mInputTargetWaitTimeoutExpired) {
1050 return INPUT_EVENT_INJECTION_TIMED_OUT;
1051 }
1052
1053 if (currentTime >= mInputTargetWaitTimeoutTime) {
Jeff Brown9302c872011-07-13 22:51:29 -07001054 onANRLocked(currentTime, applicationHandle, windowHandle,
1055 entry->eventTime, mInputTargetWaitStartTime);
Jeff Brownb88102f2010-09-08 11:49:43 -07001056
1057 // Force poll loop to wake up immediately on next iteration once we get the
1058 // ANR response back from the policy.
1059 *nextWakeupTime = LONG_LONG_MIN;
1060 return INPUT_EVENT_INJECTION_PENDING;
1061 } else {
1062 // Force poll loop to wake up when timeout is due.
1063 if (mInputTargetWaitTimeoutTime < *nextWakeupTime) {
1064 *nextWakeupTime = mInputTargetWaitTimeoutTime;
1065 }
1066 return INPUT_EVENT_INJECTION_PENDING;
1067 }
1068}
1069
Jeff Brown519e0242010-09-15 15:18:56 -07001070void InputDispatcher::resumeAfterTargetsNotReadyTimeoutLocked(nsecs_t newTimeout,
1071 const sp<InputChannel>& inputChannel) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001072 if (newTimeout > 0) {
1073 // Extend the timeout.
1074 mInputTargetWaitTimeoutTime = now() + newTimeout;
1075 } else {
1076 // Give up.
1077 mInputTargetWaitTimeoutExpired = true;
Jeff Brown519e0242010-09-15 15:18:56 -07001078
Jeff Brown01ce2e92010-09-26 22:20:12 -07001079 // Release the touch targets.
1080 mTouchState.reset();
Jeff Brown2a95c2a2010-09-16 12:31:46 -07001081
Jeff Brown519e0242010-09-15 15:18:56 -07001082 // Input state will not be realistic. Mark it out of sync.
Jeff Browndc3e0052010-09-16 11:02:16 -07001083 if (inputChannel.get()) {
1084 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
1085 if (connectionIndex >= 0) {
1086 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
Jeff Brown00045a72010-12-09 18:10:30 -08001087 if (connection->status == Connection::STATUS_NORMAL) {
Jeff Brownda3d5a92011-03-29 15:11:34 -07001088 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
Jeff Brown00045a72010-12-09 18:10:30 -08001089 "application not responding");
Jeff Brownda3d5a92011-03-29 15:11:34 -07001090 synthesizeCancelationEventsForConnectionLocked(connection, options);
Jeff Brown00045a72010-12-09 18:10:30 -08001091 }
Jeff Browndc3e0052010-09-16 11:02:16 -07001092 }
Jeff Brown519e0242010-09-15 15:18:56 -07001093 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001094 }
1095}
1096
Jeff Brown519e0242010-09-15 15:18:56 -07001097nsecs_t InputDispatcher::getTimeSpentWaitingForApplicationLocked(
Jeff Brownb88102f2010-09-08 11:49:43 -07001098 nsecs_t currentTime) {
1099 if (mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
1100 return currentTime - mInputTargetWaitStartTime;
1101 }
1102 return 0;
1103}
1104
1105void InputDispatcher::resetANRTimeoutsLocked() {
1106#if DEBUG_FOCUS
1107 LOGD("Resetting ANR timeouts.");
1108#endif
1109
Jeff Brownb88102f2010-09-08 11:49:43 -07001110 // Reset input target wait timeout.
1111 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_NONE;
Jeff Brown5ea29ab2011-07-27 11:50:51 -07001112 mInputTargetWaitApplicationHandle.clear();
Jeff Brownb88102f2010-09-08 11:49:43 -07001113}
1114
Jeff Brown01ce2e92010-09-26 22:20:12 -07001115int32_t InputDispatcher::findFocusedWindowTargetsLocked(nsecs_t currentTime,
1116 const EventEntry* entry, nsecs_t* nextWakeupTime) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001117 mCurrentInputTargets.clear();
1118
1119 int32_t injectionResult;
1120
1121 // If there is no currently focused window and no focused application
1122 // then drop the event.
Jeff Brown9302c872011-07-13 22:51:29 -07001123 if (mFocusedWindowHandle == NULL) {
1124 if (mFocusedApplicationHandle != NULL) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001125#if DEBUG_FOCUS
1126 LOGD("Waiting because there is no focused window but there is a "
Jeff Brown519e0242010-09-15 15:18:56 -07001127 "focused application that may eventually add a window: %s.",
Jeff Brown9302c872011-07-13 22:51:29 -07001128 getApplicationWindowLabelLocked(mFocusedApplicationHandle, NULL).string());
Jeff Brownb88102f2010-09-08 11:49:43 -07001129#endif
1130 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brown9302c872011-07-13 22:51:29 -07001131 mFocusedApplicationHandle, NULL, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -07001132 goto Unresponsive;
1133 }
1134
1135 LOGI("Dropping event because there is no focused window or focused application.");
1136 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1137 goto Failed;
1138 }
1139
1140 // Check permissions.
Jeff Brown9302c872011-07-13 22:51:29 -07001141 if (! checkInjectionPermission(mFocusedWindowHandle, entry->injectionState)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001142 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1143 goto Failed;
1144 }
1145
1146 // If the currently focused window is paused then keep waiting.
Jeff Brown9302c872011-07-13 22:51:29 -07001147 if (mFocusedWindowHandle->paused) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001148#if DEBUG_FOCUS
1149 LOGD("Waiting because focused window is paused.");
1150#endif
1151 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brown9302c872011-07-13 22:51:29 -07001152 mFocusedApplicationHandle, mFocusedWindowHandle, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -07001153 goto Unresponsive;
1154 }
1155
Jeff Brown519e0242010-09-15 15:18:56 -07001156 // If the currently focused window is still working on previous events then keep waiting.
Jeff Brown9302c872011-07-13 22:51:29 -07001157 if (! isWindowFinishedWithPreviousInputLocked(mFocusedWindowHandle)) {
Jeff Brown519e0242010-09-15 15:18:56 -07001158#if DEBUG_FOCUS
1159 LOGD("Waiting because focused window still processing previous input.");
1160#endif
1161 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brown9302c872011-07-13 22:51:29 -07001162 mFocusedApplicationHandle, mFocusedWindowHandle, nextWakeupTime);
Jeff Brown519e0242010-09-15 15:18:56 -07001163 goto Unresponsive;
1164 }
1165
Jeff Brownb88102f2010-09-08 11:49:43 -07001166 // Success! Output targets.
1167 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
Jeff Brown9302c872011-07-13 22:51:29 -07001168 addWindowTargetLocked(mFocusedWindowHandle,
Jeff Browna032cc02011-03-07 16:56:21 -08001169 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS, BitSet32(0));
Jeff Brownb88102f2010-09-08 11:49:43 -07001170
1171 // Done.
1172Failed:
1173Unresponsive:
Jeff Brown519e0242010-09-15 15:18:56 -07001174 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
1175 updateDispatchStatisticsLocked(currentTime, entry,
1176 injectionResult, timeSpentWaitingForApplication);
Jeff Brownb88102f2010-09-08 11:49:43 -07001177#if DEBUG_FOCUS
Jeff Brown519e0242010-09-15 15:18:56 -07001178 LOGD("findFocusedWindow finished: injectionResult=%d, "
1179 "timeSpendWaitingForApplication=%0.1fms",
1180 injectionResult, timeSpentWaitingForApplication / 1000000.0);
Jeff Brownb88102f2010-09-08 11:49:43 -07001181#endif
1182 return injectionResult;
1183}
1184
Jeff Brown01ce2e92010-09-26 22:20:12 -07001185int32_t InputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime,
Jeff Browna032cc02011-03-07 16:56:21 -08001186 const MotionEntry* entry, nsecs_t* nextWakeupTime, bool* outConflictingPointerActions,
1187 const MotionSample** outSplitBatchAfterSample) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001188 enum InjectionPermission {
1189 INJECTION_PERMISSION_UNKNOWN,
1190 INJECTION_PERMISSION_GRANTED,
1191 INJECTION_PERMISSION_DENIED
1192 };
1193
Jeff Brownb88102f2010-09-08 11:49:43 -07001194 mCurrentInputTargets.clear();
1195
1196 nsecs_t startTime = now();
1197
1198 // For security reasons, we defer updating the touch state until we are sure that
1199 // event injection will be allowed.
1200 //
1201 // FIXME In the original code, screenWasOff could never be set to true.
1202 // The reason is that the POLICY_FLAG_WOKE_HERE
1203 // and POLICY_FLAG_BRIGHT_HERE flags were set only when preprocessing raw
1204 // EV_KEY, EV_REL and EV_ABS events. As it happens, the touch event was
1205 // actually enqueued using the policyFlags that appeared in the final EV_SYN
1206 // events upon which no preprocessing took place. So policyFlags was always 0.
1207 // In the new native input dispatcher we're a bit more careful about event
1208 // preprocessing so the touches we receive can actually have non-zero policyFlags.
1209 // Unfortunately we obtain undesirable behavior.
1210 //
1211 // Here's what happens:
1212 //
1213 // When the device dims in anticipation of going to sleep, touches
1214 // in windows which have FLAG_TOUCHABLE_WHEN_WAKING cause
1215 // the device to brighten and reset the user activity timer.
1216 // Touches on other windows (such as the launcher window)
1217 // are dropped. Then after a moment, the device goes to sleep. Oops.
1218 //
1219 // Also notice how screenWasOff was being initialized using POLICY_FLAG_BRIGHT_HERE
1220 // instead of POLICY_FLAG_WOKE_HERE...
1221 //
1222 bool screenWasOff = false; // original policy: policyFlags & POLICY_FLAG_BRIGHT_HERE;
1223
1224 int32_t action = entry->action;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001225 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Jeff Brownb88102f2010-09-08 11:49:43 -07001226
1227 // Update the touch state as needed based on the properties of the touch event.
Jeff Brown01ce2e92010-09-26 22:20:12 -07001228 int32_t injectionResult = INPUT_EVENT_INJECTION_PENDING;
1229 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
Jeff Brown9302c872011-07-13 22:51:29 -07001230 sp<InputWindowHandle> newHoverWindowHandle;
Jeff Browncc0c1592011-02-19 05:07:28 -08001231
1232 bool isSplit = mTouchState.split;
Jeff Brown2717eff2011-06-30 23:53:07 -07001233 bool switchedDevice = mTouchState.deviceId >= 0
1234 && (mTouchState.deviceId != entry->deviceId
1235 || mTouchState.source != entry->source);
Jeff Browna032cc02011-03-07 16:56:21 -08001236 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE
1237 || maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER
1238 || maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1239 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN
1240 || maskedAction == AMOTION_EVENT_ACTION_SCROLL
1241 || isHoverAction);
Jeff Brown81346812011-06-28 20:08:48 -07001242 bool wrongDevice = false;
Jeff Browna032cc02011-03-07 16:56:21 -08001243 if (newGesture) {
Jeff Browncc0c1592011-02-19 05:07:28 -08001244 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Jeff Brown81346812011-06-28 20:08:48 -07001245 if (switchedDevice && mTouchState.down && !down) {
1246#if DEBUG_FOCUS
1247 LOGD("Dropping event because a pointer for a different device is already down.");
1248#endif
Jeff Browncc0c1592011-02-19 05:07:28 -08001249 mTempTouchState.copyFrom(mTouchState);
Jeff Brown81346812011-06-28 20:08:48 -07001250 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1251 switchedDevice = false;
1252 wrongDevice = true;
1253 goto Failed;
Jeff Browncc0c1592011-02-19 05:07:28 -08001254 }
Jeff Brown81346812011-06-28 20:08:48 -07001255 mTempTouchState.reset();
1256 mTempTouchState.down = down;
1257 mTempTouchState.deviceId = entry->deviceId;
1258 mTempTouchState.source = entry->source;
1259 isSplit = false;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001260 } else {
1261 mTempTouchState.copyFrom(mTouchState);
Jeff Browncc0c1592011-02-19 05:07:28 -08001262 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001263
Jeff Browna032cc02011-03-07 16:56:21 -08001264 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
Jeff Brown33bbfd22011-02-24 20:55:35 -08001265 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
Jeff Brownb88102f2010-09-08 11:49:43 -07001266
Jeff Browna032cc02011-03-07 16:56:21 -08001267 const MotionSample* sample = &entry->firstSample;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001268 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Jeff Browna032cc02011-03-07 16:56:21 -08001269 int32_t x = int32_t(sample->pointerCoords[pointerIndex].
Jeff Brownebbd5d12011-02-17 13:01:34 -08001270 getAxisValue(AMOTION_EVENT_AXIS_X));
Jeff Browna032cc02011-03-07 16:56:21 -08001271 int32_t y = int32_t(sample->pointerCoords[pointerIndex].
Jeff Brownebbd5d12011-02-17 13:01:34 -08001272 getAxisValue(AMOTION_EVENT_AXIS_Y));
Jeff Brown9302c872011-07-13 22:51:29 -07001273 sp<InputWindowHandle> newTouchedWindowHandle;
1274 sp<InputWindowHandle> topErrorWindowHandle;
Jeff Browna032cc02011-03-07 16:56:21 -08001275 bool isTouchModal = false;
Jeff Brownb88102f2010-09-08 11:49:43 -07001276
1277 // Traverse windows from front to back to find touched window and outside targets.
Jeff Brown9302c872011-07-13 22:51:29 -07001278 size_t numWindows = mWindowHandles.size();
Jeff Brownb88102f2010-09-08 11:49:43 -07001279 for (size_t i = 0; i < numWindows; i++) {
Jeff Brown9302c872011-07-13 22:51:29 -07001280 sp<InputWindowHandle> windowHandle = mWindowHandles.itemAt(i);
1281 int32_t flags = windowHandle->layoutParamsFlags;
Jeff Brownb88102f2010-09-08 11:49:43 -07001282
Jeff Brown9302c872011-07-13 22:51:29 -07001283 if (flags & InputWindowHandle::FLAG_SYSTEM_ERROR) {
1284 if (topErrorWindowHandle == NULL) {
1285 topErrorWindowHandle = windowHandle;
Jeff Brownb88102f2010-09-08 11:49:43 -07001286 }
1287 }
1288
Jeff Brown9302c872011-07-13 22:51:29 -07001289 if (windowHandle->visible) {
1290 if (! (flags & InputWindowHandle::FLAG_NOT_TOUCHABLE)) {
1291 isTouchModal = (flags & (InputWindowHandle::FLAG_NOT_FOCUSABLE
1292 | InputWindowHandle::FLAG_NOT_TOUCH_MODAL)) == 0;
1293 if (isTouchModal || windowHandle->touchableRegionContainsPoint(x, y)) {
1294 if (! screenWasOff
1295 || (flags & InputWindowHandle::FLAG_TOUCHABLE_WHEN_WAKING)) {
1296 newTouchedWindowHandle = windowHandle;
Jeff Brownb88102f2010-09-08 11:49:43 -07001297 }
1298 break; // found touched window, exit window loop
1299 }
1300 }
1301
Jeff Brown01ce2e92010-09-26 22:20:12 -07001302 if (maskedAction == AMOTION_EVENT_ACTION_DOWN
Jeff Brown9302c872011-07-13 22:51:29 -07001303 && (flags & InputWindowHandle::FLAG_WATCH_OUTSIDE_TOUCH)) {
Jeff Browna032cc02011-03-07 16:56:21 -08001304 int32_t outsideTargetFlags = InputTarget::FLAG_DISPATCH_AS_OUTSIDE;
Jeff Brown9302c872011-07-13 22:51:29 -07001305 if (isWindowObscuredAtPointLocked(windowHandle, x, y)) {
Jeff Brown19dfc832010-10-05 12:26:23 -07001306 outsideTargetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1307 }
1308
Jeff Brown9302c872011-07-13 22:51:29 -07001309 mTempTouchState.addOrUpdateWindow(
1310 windowHandle, outsideTargetFlags, BitSet32(0));
Jeff Brownb88102f2010-09-08 11:49:43 -07001311 }
1312 }
1313 }
1314
1315 // If there is an error window but it is not taking focus (typically because
1316 // it is invisible) then wait for it. Any other focused window may in
1317 // fact be in ANR state.
Jeff Brown9302c872011-07-13 22:51:29 -07001318 if (topErrorWindowHandle != NULL && newTouchedWindowHandle != topErrorWindowHandle) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001319#if DEBUG_FOCUS
1320 LOGD("Waiting because system error window is pending.");
1321#endif
1322 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
1323 NULL, NULL, nextWakeupTime);
1324 injectionPermission = INJECTION_PERMISSION_UNKNOWN;
1325 goto Unresponsive;
1326 }
1327
Jeff Brown01ce2e92010-09-26 22:20:12 -07001328 // Figure out whether splitting will be allowed for this window.
Jeff Brown9302c872011-07-13 22:51:29 -07001329 if (newTouchedWindowHandle != NULL && newTouchedWindowHandle->supportsSplitTouch()) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001330 // New window supports splitting.
1331 isSplit = true;
1332 } else if (isSplit) {
1333 // New window does not support splitting but we have already split events.
1334 // Assign the pointer to the first foreground window we find.
1335 // (May be NULL which is why we put this code block before the next check.)
Jeff Brown9302c872011-07-13 22:51:29 -07001336 newTouchedWindowHandle = mTempTouchState.getFirstForegroundWindowHandle();
Jeff Brown01ce2e92010-09-26 22:20:12 -07001337 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001338
Jeff Brownb88102f2010-09-08 11:49:43 -07001339 // If we did not find a touched window then fail.
Jeff Brown9302c872011-07-13 22:51:29 -07001340 if (newTouchedWindowHandle == NULL) {
1341 if (mFocusedApplicationHandle != NULL) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001342#if DEBUG_FOCUS
1343 LOGD("Waiting because there is no touched window but there is a "
Jeff Brown519e0242010-09-15 15:18:56 -07001344 "focused application that may eventually add a new window: %s.",
Jeff Brown9302c872011-07-13 22:51:29 -07001345 getApplicationWindowLabelLocked(mFocusedApplicationHandle, NULL).string());
Jeff Brownb88102f2010-09-08 11:49:43 -07001346#endif
1347 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brown9302c872011-07-13 22:51:29 -07001348 mFocusedApplicationHandle, NULL, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -07001349 goto Unresponsive;
1350 }
1351
1352 LOGI("Dropping event because there is no touched window or focused application.");
1353 injectionResult = INPUT_EVENT_INJECTION_FAILED;
Jeff Brownb88102f2010-09-08 11:49:43 -07001354 goto Failed;
1355 }
1356
Jeff Brown19dfc832010-10-05 12:26:23 -07001357 // Set target flags.
Jeff Browna032cc02011-03-07 16:56:21 -08001358 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
Jeff Brown19dfc832010-10-05 12:26:23 -07001359 if (isSplit) {
1360 targetFlags |= InputTarget::FLAG_SPLIT;
1361 }
Jeff Brown9302c872011-07-13 22:51:29 -07001362 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
Jeff Brown19dfc832010-10-05 12:26:23 -07001363 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1364 }
1365
Jeff Browna032cc02011-03-07 16:56:21 -08001366 // Update hover state.
1367 if (isHoverAction) {
Jeff Brown9302c872011-07-13 22:51:29 -07001368 newHoverWindowHandle = newTouchedWindowHandle;
Jeff Browna032cc02011-03-07 16:56:21 -08001369
1370 // Ensure all subsequent motion samples are also within the touched window.
1371 // Set *outSplitBatchAfterSample to the sample before the first one that is not
1372 // within the touched window.
1373 if (!isTouchModal) {
1374 while (sample->next) {
Jeff Brown9302c872011-07-13 22:51:29 -07001375 if (!newHoverWindowHandle->touchableRegionContainsPoint(
Jeff Browna032cc02011-03-07 16:56:21 -08001376 sample->next->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X),
1377 sample->next->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y))) {
1378 *outSplitBatchAfterSample = sample;
1379 break;
1380 }
1381 sample = sample->next;
1382 }
1383 }
1384 } else if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
Jeff Brown9302c872011-07-13 22:51:29 -07001385 newHoverWindowHandle = mLastHoverWindowHandle;
Jeff Browna032cc02011-03-07 16:56:21 -08001386 }
1387
Jeff Brown01ce2e92010-09-26 22:20:12 -07001388 // Update the temporary touch state.
1389 BitSet32 pointerIds;
1390 if (isSplit) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07001391 uint32_t pointerId = entry->pointerProperties[pointerIndex].id;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001392 pointerIds.markBit(pointerId);
Jeff Brownb88102f2010-09-08 11:49:43 -07001393 }
Jeff Brown9302c872011-07-13 22:51:29 -07001394 mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Jeff Brownb88102f2010-09-08 11:49:43 -07001395 } else {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001396 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
Jeff Brownb88102f2010-09-08 11:49:43 -07001397
1398 // If the pointer is not currently down, then ignore the event.
Jeff Brown01ce2e92010-09-26 22:20:12 -07001399 if (! mTempTouchState.down) {
Jeff Browna2cc28d2011-03-25 11:58:46 -07001400#if DEBUG_FOCUS
Jeff Brown76860e32010-10-25 17:37:46 -07001401 LOGD("Dropping event because the pointer is not down or we previously "
1402 "dropped the pointer down event.");
1403#endif
Jeff Brownb88102f2010-09-08 11:49:43 -07001404 injectionResult = INPUT_EVENT_INJECTION_FAILED;
Jeff Brownb88102f2010-09-08 11:49:43 -07001405 goto Failed;
1406 }
Jeff Brown98db5fa2011-06-08 15:37:10 -07001407
1408 // Check whether touches should slip outside of the current foreground window.
1409 if (maskedAction == AMOTION_EVENT_ACTION_MOVE
1410 && entry->pointerCount == 1
1411 && mTempTouchState.isSlippery()) {
1412 const MotionSample* sample = &entry->firstSample;
1413 int32_t x = int32_t(sample->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
1414 int32_t y = int32_t(sample->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
1415
Jeff Brown9302c872011-07-13 22:51:29 -07001416 sp<InputWindowHandle> oldTouchedWindowHandle =
1417 mTempTouchState.getFirstForegroundWindowHandle();
1418 sp<InputWindowHandle> newTouchedWindowHandle = findTouchedWindowAtLocked(x, y);
1419 if (oldTouchedWindowHandle != newTouchedWindowHandle
1420 && newTouchedWindowHandle != NULL) {
Jeff Brown98db5fa2011-06-08 15:37:10 -07001421#if DEBUG_FOCUS
1422 LOGD("Touch is slipping out of window %s into window %s.",
Jeff Brown9302c872011-07-13 22:51:29 -07001423 oldTouchedWindowHandle->name.string(),
1424 newTouchedWindowHandle->name.string());
Jeff Brown98db5fa2011-06-08 15:37:10 -07001425#endif
1426 // Make a slippery exit from the old window.
Jeff Brown9302c872011-07-13 22:51:29 -07001427 mTempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
Jeff Brown98db5fa2011-06-08 15:37:10 -07001428 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT, BitSet32(0));
1429
1430 // Make a slippery entrance into the new window.
Jeff Brown9302c872011-07-13 22:51:29 -07001431 if (newTouchedWindowHandle->supportsSplitTouch()) {
Jeff Brown98db5fa2011-06-08 15:37:10 -07001432 isSplit = true;
1433 }
1434
1435 int32_t targetFlags = InputTarget::FLAG_FOREGROUND
1436 | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
1437 if (isSplit) {
1438 targetFlags |= InputTarget::FLAG_SPLIT;
1439 }
Jeff Brown9302c872011-07-13 22:51:29 -07001440 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
Jeff Brown98db5fa2011-06-08 15:37:10 -07001441 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1442 }
1443
1444 BitSet32 pointerIds;
1445 if (isSplit) {
1446 pointerIds.markBit(entry->pointerProperties[0].id);
1447 }
Jeff Brown9302c872011-07-13 22:51:29 -07001448 mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Jeff Brown98db5fa2011-06-08 15:37:10 -07001449
1450 // Split the batch here so we send exactly one sample.
1451 *outSplitBatchAfterSample = &entry->firstSample;
1452 }
1453 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001454 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001455
Jeff Brown9302c872011-07-13 22:51:29 -07001456 if (newHoverWindowHandle != mLastHoverWindowHandle) {
Jeff Browna032cc02011-03-07 16:56:21 -08001457 // Split the batch here so we send exactly one sample as part of ENTER or EXIT.
1458 *outSplitBatchAfterSample = &entry->firstSample;
1459
1460 // Let the previous window know that the hover sequence is over.
Jeff Brown9302c872011-07-13 22:51:29 -07001461 if (mLastHoverWindowHandle != NULL) {
Jeff Browna032cc02011-03-07 16:56:21 -08001462#if DEBUG_HOVER
Jeff Brown9302c872011-07-13 22:51:29 -07001463 LOGD("Sending hover exit event to window %s.", mLastHoverWindowHandle->name.string());
Jeff Browna032cc02011-03-07 16:56:21 -08001464#endif
Jeff Brown9302c872011-07-13 22:51:29 -07001465 mTempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
Jeff Browna032cc02011-03-07 16:56:21 -08001466 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
1467 }
1468
1469 // Let the new window know that the hover sequence is starting.
Jeff Brown9302c872011-07-13 22:51:29 -07001470 if (newHoverWindowHandle != NULL) {
Jeff Browna032cc02011-03-07 16:56:21 -08001471#if DEBUG_HOVER
Jeff Brown9302c872011-07-13 22:51:29 -07001472 LOGD("Sending hover enter event to window %s.", newHoverWindowHandle->name.string());
Jeff Browna032cc02011-03-07 16:56:21 -08001473#endif
Jeff Brown9302c872011-07-13 22:51:29 -07001474 mTempTouchState.addOrUpdateWindow(newHoverWindowHandle,
Jeff Browna032cc02011-03-07 16:56:21 -08001475 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER, BitSet32(0));
1476 }
1477 }
1478
Jeff Brown01ce2e92010-09-26 22:20:12 -07001479 // Check permission to inject into all touched foreground windows and ensure there
1480 // is at least one touched foreground window.
1481 {
1482 bool haveForegroundWindow = false;
1483 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1484 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1485 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1486 haveForegroundWindow = true;
Jeff Brown9302c872011-07-13 22:51:29 -07001487 if (! checkInjectionPermission(touchedWindow.windowHandle,
1488 entry->injectionState)) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001489 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1490 injectionPermission = INJECTION_PERMISSION_DENIED;
1491 goto Failed;
1492 }
1493 }
1494 }
1495 if (! haveForegroundWindow) {
Jeff Browna2cc28d2011-03-25 11:58:46 -07001496#if DEBUG_FOCUS
Jeff Brown01ce2e92010-09-26 22:20:12 -07001497 LOGD("Dropping event because there is no touched foreground window to receive it.");
Jeff Brownb88102f2010-09-08 11:49:43 -07001498#endif
1499 injectionResult = INPUT_EVENT_INJECTION_FAILED;
Jeff Brownb88102f2010-09-08 11:49:43 -07001500 goto Failed;
1501 }
1502
Jeff Brown01ce2e92010-09-26 22:20:12 -07001503 // Permission granted to injection into all touched foreground windows.
1504 injectionPermission = INJECTION_PERMISSION_GRANTED;
1505 }
Jeff Brown519e0242010-09-15 15:18:56 -07001506
Kenny Root7a9db182011-06-02 15:16:05 -07001507 // Check whether windows listening for outside touches are owned by the same UID. If it is
1508 // set the policy flag that we will not reveal coordinate information to this window.
1509 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
Jeff Brown9302c872011-07-13 22:51:29 -07001510 sp<InputWindowHandle> foregroundWindowHandle =
1511 mTempTouchState.getFirstForegroundWindowHandle();
1512 const int32_t foregroundWindowUid = foregroundWindowHandle->ownerUid;
Kenny Root7a9db182011-06-02 15:16:05 -07001513 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1514 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1515 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
Jeff Brown9302c872011-07-13 22:51:29 -07001516 sp<InputWindowHandle> inputWindowHandle = touchedWindow.windowHandle;
1517 if (inputWindowHandle->ownerUid != foregroundWindowUid) {
1518 mTempTouchState.addOrUpdateWindow(inputWindowHandle,
Kenny Root7a9db182011-06-02 15:16:05 -07001519 InputTarget::FLAG_ZERO_COORDS, BitSet32(0));
1520 }
1521 }
1522 }
1523 }
1524
Jeff Brown01ce2e92010-09-26 22:20:12 -07001525 // Ensure all touched foreground windows are ready for new input.
1526 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1527 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1528 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1529 // If the touched window is paused then keep waiting.
Jeff Brown9302c872011-07-13 22:51:29 -07001530 if (touchedWindow.windowHandle->paused) {
Jeff Browna2cc28d2011-03-25 11:58:46 -07001531#if DEBUG_FOCUS
Jeff Brown01ce2e92010-09-26 22:20:12 -07001532 LOGD("Waiting because touched window is paused.");
Jeff Brown519e0242010-09-15 15:18:56 -07001533#endif
Jeff Brown01ce2e92010-09-26 22:20:12 -07001534 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brown9302c872011-07-13 22:51:29 -07001535 NULL, touchedWindow.windowHandle, nextWakeupTime);
Jeff Brown01ce2e92010-09-26 22:20:12 -07001536 goto Unresponsive;
1537 }
1538
1539 // If the touched window is still working on previous events then keep waiting.
Jeff Brown9302c872011-07-13 22:51:29 -07001540 if (! isWindowFinishedWithPreviousInputLocked(touchedWindow.windowHandle)) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001541#if DEBUG_FOCUS
1542 LOGD("Waiting because touched window still processing previous input.");
1543#endif
1544 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brown9302c872011-07-13 22:51:29 -07001545 NULL, touchedWindow.windowHandle, nextWakeupTime);
Jeff Brown01ce2e92010-09-26 22:20:12 -07001546 goto Unresponsive;
1547 }
1548 }
1549 }
1550
1551 // If this is the first pointer going down and the touched window has a wallpaper
1552 // then also add the touched wallpaper windows so they are locked in for the duration
1553 // of the touch gesture.
Jeff Brown33bbfd22011-02-24 20:55:35 -08001554 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
1555 // engine only supports touch events. We would need to add a mechanism similar
1556 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
1557 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
Jeff Brown9302c872011-07-13 22:51:29 -07001558 sp<InputWindowHandle> foregroundWindowHandle =
1559 mTempTouchState.getFirstForegroundWindowHandle();
1560 if (foregroundWindowHandle->hasWallpaper) {
1561 for (size_t i = 0; i < mWindowHandles.size(); i++) {
1562 sp<InputWindowHandle> windowHandle = mWindowHandles.itemAt(i);
1563 if (windowHandle->layoutParamsType == InputWindowHandle::TYPE_WALLPAPER) {
1564 mTempTouchState.addOrUpdateWindow(windowHandle,
Jeff Browna032cc02011-03-07 16:56:21 -08001565 InputTarget::FLAG_WINDOW_IS_OBSCURED
1566 | InputTarget::FLAG_DISPATCH_AS_IS,
1567 BitSet32(0));
Jeff Brown01ce2e92010-09-26 22:20:12 -07001568 }
1569 }
1570 }
1571 }
1572
Jeff Brownb88102f2010-09-08 11:49:43 -07001573 // Success! Output targets.
1574 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
Jeff Brownb88102f2010-09-08 11:49:43 -07001575
Jeff Brown01ce2e92010-09-26 22:20:12 -07001576 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1577 const TouchedWindow& touchedWindow = mTempTouchState.windows.itemAt(i);
Jeff Brown9302c872011-07-13 22:51:29 -07001578 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Jeff Brown01ce2e92010-09-26 22:20:12 -07001579 touchedWindow.pointerIds);
Jeff Brownb88102f2010-09-08 11:49:43 -07001580 }
1581
Jeff Browna032cc02011-03-07 16:56:21 -08001582 // Drop the outside or hover touch windows since we will not care about them
1583 // in the next iteration.
1584 mTempTouchState.filterNonAsIsTouchWindows();
Jeff Brown01ce2e92010-09-26 22:20:12 -07001585
Jeff Brownb88102f2010-09-08 11:49:43 -07001586Failed:
1587 // Check injection permission once and for all.
1588 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001589 if (checkInjectionPermission(NULL, entry->injectionState)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001590 injectionPermission = INJECTION_PERMISSION_GRANTED;
1591 } else {
1592 injectionPermission = INJECTION_PERMISSION_DENIED;
1593 }
1594 }
1595
1596 // Update final pieces of touch state if the injector had permission.
1597 if (injectionPermission == INJECTION_PERMISSION_GRANTED) {
Jeff Brown95712852011-01-04 19:41:59 -08001598 if (!wrongDevice) {
Jeff Brown81346812011-06-28 20:08:48 -07001599 if (switchedDevice) {
1600#if DEBUG_FOCUS
1601 LOGD("Conflicting pointer actions: Switched to a different device.");
1602#endif
1603 *outConflictingPointerActions = true;
1604 }
1605
1606 if (isHoverAction) {
1607 // Started hovering, therefore no longer down.
1608 if (mTouchState.down) {
1609#if DEBUG_FOCUS
1610 LOGD("Conflicting pointer actions: Hover received while pointer was down.");
1611#endif
1612 *outConflictingPointerActions = true;
1613 }
1614 mTouchState.reset();
1615 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER
1616 || maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
1617 mTouchState.deviceId = entry->deviceId;
1618 mTouchState.source = entry->source;
1619 }
1620 } else if (maskedAction == AMOTION_EVENT_ACTION_UP
1621 || maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Jeff Brown95712852011-01-04 19:41:59 -08001622 // All pointers up or canceled.
Jeff Brown33bbfd22011-02-24 20:55:35 -08001623 mTouchState.reset();
Jeff Brown95712852011-01-04 19:41:59 -08001624 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1625 // First pointer went down.
1626 if (mTouchState.down) {
Jeff Brownb6997262010-10-08 22:31:17 -07001627#if DEBUG_FOCUS
Jeff Brown81346812011-06-28 20:08:48 -07001628 LOGD("Conflicting pointer actions: Down received while already down.");
Jeff Brownb6997262010-10-08 22:31:17 -07001629#endif
Jeff Brown81346812011-06-28 20:08:48 -07001630 *outConflictingPointerActions = true;
Jeff Brown95712852011-01-04 19:41:59 -08001631 }
Jeff Brown33bbfd22011-02-24 20:55:35 -08001632 mTouchState.copyFrom(mTempTouchState);
Jeff Brown95712852011-01-04 19:41:59 -08001633 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
1634 // One pointer went up.
1635 if (isSplit) {
1636 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07001637 uint32_t pointerId = entry->pointerProperties[pointerIndex].id;
Jeff Brownb88102f2010-09-08 11:49:43 -07001638
Jeff Brown95712852011-01-04 19:41:59 -08001639 for (size_t i = 0; i < mTempTouchState.windows.size(); ) {
1640 TouchedWindow& touchedWindow = mTempTouchState.windows.editItemAt(i);
1641 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
1642 touchedWindow.pointerIds.clearBit(pointerId);
1643 if (touchedWindow.pointerIds.isEmpty()) {
1644 mTempTouchState.windows.removeAt(i);
1645 continue;
1646 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001647 }
Jeff Brown95712852011-01-04 19:41:59 -08001648 i += 1;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001649 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001650 }
Jeff Brown33bbfd22011-02-24 20:55:35 -08001651 mTouchState.copyFrom(mTempTouchState);
1652 } else if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
1653 // Discard temporary touch state since it was only valid for this action.
1654 } else {
1655 // Save changes to touch state as-is for all other actions.
1656 mTouchState.copyFrom(mTempTouchState);
Jeff Brownb88102f2010-09-08 11:49:43 -07001657 }
Jeff Browna032cc02011-03-07 16:56:21 -08001658
1659 // Update hover state.
Jeff Brown9302c872011-07-13 22:51:29 -07001660 mLastHoverWindowHandle = newHoverWindowHandle;
Jeff Brown95712852011-01-04 19:41:59 -08001661 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001662 } else {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001663#if DEBUG_FOCUS
1664 LOGD("Not updating touch focus because injection was denied.");
1665#endif
Jeff Brownb88102f2010-09-08 11:49:43 -07001666 }
1667
1668Unresponsive:
Jeff Brown120a4592010-10-27 18:43:51 -07001669 // Reset temporary touch state to ensure we release unnecessary references to input channels.
1670 mTempTouchState.reset();
1671
Jeff Brown519e0242010-09-15 15:18:56 -07001672 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
1673 updateDispatchStatisticsLocked(currentTime, entry,
1674 injectionResult, timeSpentWaitingForApplication);
Jeff Brownb88102f2010-09-08 11:49:43 -07001675#if DEBUG_FOCUS
Jeff Brown01ce2e92010-09-26 22:20:12 -07001676 LOGD("findTouchedWindow finished: injectionResult=%d, injectionPermission=%d, "
1677 "timeSpentWaitingForApplication=%0.1fms",
Jeff Brown519e0242010-09-15 15:18:56 -07001678 injectionResult, injectionPermission, timeSpentWaitingForApplication / 1000000.0);
Jeff Brownb88102f2010-09-08 11:49:43 -07001679#endif
1680 return injectionResult;
1681}
1682
Jeff Brown9302c872011-07-13 22:51:29 -07001683void InputDispatcher::addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
1684 int32_t targetFlags, BitSet32 pointerIds) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001685 mCurrentInputTargets.push();
1686
1687 InputTarget& target = mCurrentInputTargets.editTop();
Jeff Brown9302c872011-07-13 22:51:29 -07001688 target.inputChannel = windowHandle->inputChannel;
Jeff Brownb88102f2010-09-08 11:49:43 -07001689 target.flags = targetFlags;
Jeff Brown9302c872011-07-13 22:51:29 -07001690 target.xOffset = - windowHandle->frameLeft;
1691 target.yOffset = - windowHandle->frameTop;
1692 target.scaleFactor = windowHandle->scaleFactor;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001693 target.pointerIds = pointerIds;
Jeff Brownb88102f2010-09-08 11:49:43 -07001694}
1695
1696void InputDispatcher::addMonitoringTargetsLocked() {
1697 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
1698 mCurrentInputTargets.push();
1699
1700 InputTarget& target = mCurrentInputTargets.editTop();
1701 target.inputChannel = mMonitoringChannels[i];
Jeff Brownb6110c22011-04-01 16:15:13 -07001702 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
Jeff Brownb88102f2010-09-08 11:49:43 -07001703 target.xOffset = 0;
1704 target.yOffset = 0;
Jeff Brownb6110c22011-04-01 16:15:13 -07001705 target.pointerIds.clear();
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001706 target.scaleFactor = 1.0f;
Jeff Brownb88102f2010-09-08 11:49:43 -07001707 }
1708}
1709
Jeff Brown9302c872011-07-13 22:51:29 -07001710bool InputDispatcher::checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
Jeff Brown01ce2e92010-09-26 22:20:12 -07001711 const InjectionState* injectionState) {
1712 if (injectionState
Jeff Brown9302c872011-07-13 22:51:29 -07001713 && (windowHandle == NULL || windowHandle->ownerUid != injectionState->injectorUid)
Jeff Brownb6997262010-10-08 22:31:17 -07001714 && !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Jeff Brown9302c872011-07-13 22:51:29 -07001715 if (windowHandle != NULL) {
1716 LOGW("Permission denied: injecting event from pid %d uid %d to window %s "
1717 "owned by uid %d",
Jeff Brownb6997262010-10-08 22:31:17 -07001718 injectionState->injectorPid, injectionState->injectorUid,
Jeff Brown9302c872011-07-13 22:51:29 -07001719 windowHandle->name.string(),
1720 windowHandle->ownerUid);
Jeff Brownb6997262010-10-08 22:31:17 -07001721 } else {
1722 LOGW("Permission denied: injecting event from pid %d uid %d",
1723 injectionState->injectorPid, injectionState->injectorUid);
Jeff Brownb88102f2010-09-08 11:49:43 -07001724 }
Jeff Brownb6997262010-10-08 22:31:17 -07001725 return false;
Jeff Brownb88102f2010-09-08 11:49:43 -07001726 }
1727 return true;
1728}
1729
Jeff Brown19dfc832010-10-05 12:26:23 -07001730bool InputDispatcher::isWindowObscuredAtPointLocked(
Jeff Brown9302c872011-07-13 22:51:29 -07001731 const sp<InputWindowHandle>& windowHandle, int32_t x, int32_t y) const {
1732 size_t numWindows = mWindowHandles.size();
Jeff Brownb88102f2010-09-08 11:49:43 -07001733 for (size_t i = 0; i < numWindows; i++) {
Jeff Brown9302c872011-07-13 22:51:29 -07001734 sp<InputWindowHandle> otherHandle = mWindowHandles.itemAt(i);
1735 if (otherHandle == windowHandle) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001736 break;
1737 }
Jeff Brown9302c872011-07-13 22:51:29 -07001738 if (otherHandle->visible && ! otherHandle->isTrustedOverlay()
1739 && otherHandle->frameContainsPoint(x, y)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001740 return true;
1741 }
1742 }
1743 return false;
1744}
1745
Jeff Brown9302c872011-07-13 22:51:29 -07001746bool InputDispatcher::isWindowFinishedWithPreviousInputLocked(
1747 const sp<InputWindowHandle>& windowHandle) {
1748 ssize_t connectionIndex = getConnectionIndexLocked(windowHandle->inputChannel);
Jeff Brown519e0242010-09-15 15:18:56 -07001749 if (connectionIndex >= 0) {
1750 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
1751 return connection->outboundQueue.isEmpty();
1752 } else {
1753 return true;
1754 }
1755}
1756
Jeff Brown9302c872011-07-13 22:51:29 -07001757String8 InputDispatcher::getApplicationWindowLabelLocked(
1758 const sp<InputApplicationHandle>& applicationHandle,
1759 const sp<InputWindowHandle>& windowHandle) {
1760 if (applicationHandle != NULL) {
1761 if (windowHandle != NULL) {
1762 String8 label(applicationHandle->name);
Jeff Brown519e0242010-09-15 15:18:56 -07001763 label.append(" - ");
Jeff Brown9302c872011-07-13 22:51:29 -07001764 label.append(windowHandle->name);
Jeff Brown519e0242010-09-15 15:18:56 -07001765 return label;
1766 } else {
Jeff Brown9302c872011-07-13 22:51:29 -07001767 return applicationHandle->name;
Jeff Brown519e0242010-09-15 15:18:56 -07001768 }
Jeff Brown9302c872011-07-13 22:51:29 -07001769 } else if (windowHandle != NULL) {
1770 return windowHandle->name;
Jeff Brown519e0242010-09-15 15:18:56 -07001771 } else {
1772 return String8("<unknown application or window>");
1773 }
1774}
1775
Jeff Browne2fe69e2010-10-18 13:21:23 -07001776void InputDispatcher::pokeUserActivityLocked(const EventEntry* eventEntry) {
Jeff Brown56194eb2011-03-02 19:23:13 -08001777 int32_t eventType = POWER_MANAGER_OTHER_EVENT;
Jeff Brown4d396052010-10-29 21:50:21 -07001778 switch (eventEntry->type) {
1779 case EventEntry::TYPE_MOTION: {
Jeff Browne2fe69e2010-10-18 13:21:23 -07001780 const MotionEntry* motionEntry = static_cast<const MotionEntry*>(eventEntry);
Jeff Brown4d396052010-10-29 21:50:21 -07001781 if (motionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
1782 return;
1783 }
1784
Jeff Brown56194eb2011-03-02 19:23:13 -08001785 if (MotionEvent::isTouchEvent(motionEntry->source, motionEntry->action)) {
Joe Onorato1a542c72010-11-08 09:48:20 -08001786 eventType = POWER_MANAGER_TOUCH_EVENT;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001787 }
Jeff Brown4d396052010-10-29 21:50:21 -07001788 break;
1789 }
1790 case EventEntry::TYPE_KEY: {
1791 const KeyEntry* keyEntry = static_cast<const KeyEntry*>(eventEntry);
1792 if (keyEntry->flags & AKEY_EVENT_FLAG_CANCELED) {
1793 return;
1794 }
Jeff Brown56194eb2011-03-02 19:23:13 -08001795 eventType = POWER_MANAGER_BUTTON_EVENT;
Jeff Brown4d396052010-10-29 21:50:21 -07001796 break;
1797 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001798 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001799
Jeff Brownb88102f2010-09-08 11:49:43 -07001800 CommandEntry* commandEntry = postCommandLocked(
1801 & InputDispatcher::doPokeUserActivityLockedInterruptible);
Jeff Browne2fe69e2010-10-18 13:21:23 -07001802 commandEntry->eventTime = eventEntry->eventTime;
Jeff Brownb88102f2010-09-08 11:49:43 -07001803 commandEntry->userActivityEventType = eventType;
1804}
1805
Jeff Brown7fbdc842010-06-17 20:52:56 -07001806void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
1807 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget,
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001808 bool resumeWithAppendedMotionSample) {
1809#if DEBUG_DISPATCH_CYCLE
Jeff Brown519e0242010-09-15 15:18:56 -07001810 LOGD("channel '%s' ~ prepareDispatchCycle - flags=%d, "
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001811 "xOffset=%f, yOffset=%f, scaleFactor=%f"
Jeff Brown83c09682010-12-23 17:50:18 -08001812 "pointerIds=0x%x, "
Jeff Brown01ce2e92010-09-26 22:20:12 -07001813 "resumeWithAppendedMotionSample=%s",
Jeff Brown519e0242010-09-15 15:18:56 -07001814 connection->getInputChannelName(), inputTarget->flags,
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001815 inputTarget->xOffset, inputTarget->yOffset,
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001816 inputTarget->scaleFactor, inputTarget->pointerIds.value,
Jeff Brownb88102f2010-09-08 11:49:43 -07001817 toString(resumeWithAppendedMotionSample));
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001818#endif
1819
Jeff Brown01ce2e92010-09-26 22:20:12 -07001820 // Make sure we are never called for streaming when splitting across multiple windows.
1821 bool isSplit = inputTarget->flags & InputTarget::FLAG_SPLIT;
Jeff Brownb6110c22011-04-01 16:15:13 -07001822 LOG_ASSERT(! (resumeWithAppendedMotionSample && isSplit));
Jeff Brown01ce2e92010-09-26 22:20:12 -07001823
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001824 // Skip this event if the connection status is not normal.
Jeff Brown519e0242010-09-15 15:18:56 -07001825 // We don't want to enqueue additional outbound events if the connection is broken.
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001826 if (connection->status != Connection::STATUS_NORMAL) {
Jeff Brownb6997262010-10-08 22:31:17 -07001827#if DEBUG_DISPATCH_CYCLE
1828 LOGD("channel '%s' ~ Dropping event because the channel status is %s",
Jeff Brownb88102f2010-09-08 11:49:43 -07001829 connection->getInputChannelName(), connection->getStatusLabel());
Jeff Brownb6997262010-10-08 22:31:17 -07001830#endif
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001831 return;
1832 }
1833
Jeff Brown01ce2e92010-09-26 22:20:12 -07001834 // Split a motion event if needed.
1835 if (isSplit) {
Jeff Brownb6110c22011-04-01 16:15:13 -07001836 LOG_ASSERT(eventEntry->type == EventEntry::TYPE_MOTION);
Jeff Brown01ce2e92010-09-26 22:20:12 -07001837
1838 MotionEntry* originalMotionEntry = static_cast<MotionEntry*>(eventEntry);
1839 if (inputTarget->pointerIds.count() != originalMotionEntry->pointerCount) {
1840 MotionEntry* splitMotionEntry = splitMotionEvent(
1841 originalMotionEntry, inputTarget->pointerIds);
Jeff Brown58a2da82011-01-25 16:02:22 -08001842 if (!splitMotionEntry) {
1843 return; // split event was dropped
1844 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001845#if DEBUG_FOCUS
1846 LOGD("channel '%s' ~ Split motion event.",
1847 connection->getInputChannelName());
1848 logOutboundMotionDetailsLocked(" ", splitMotionEntry);
1849#endif
1850 eventEntry = splitMotionEntry;
1851 }
1852 }
1853
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001854 // Resume the dispatch cycle with a freshly appended motion sample.
1855 // First we check that the last dispatch entry in the outbound queue is for the same
1856 // motion event to which we appended the motion sample. If we find such a dispatch
1857 // entry, and if it is currently in progress then we try to stream the new sample.
1858 bool wasEmpty = connection->outboundQueue.isEmpty();
1859
1860 if (! wasEmpty && resumeWithAppendedMotionSample) {
1861 DispatchEntry* motionEventDispatchEntry =
1862 connection->findQueuedDispatchEntryForEvent(eventEntry);
1863 if (motionEventDispatchEntry) {
1864 // If the dispatch entry is not in progress, then we must be busy dispatching an
1865 // earlier event. Not a problem, the motion event is on the outbound queue and will
1866 // be dispatched later.
1867 if (! motionEventDispatchEntry->inProgress) {
1868#if DEBUG_BATCHING
1869 LOGD("channel '%s' ~ Not streaming because the motion event has "
1870 "not yet been dispatched. "
1871 "(Waiting for earlier events to be consumed.)",
1872 connection->getInputChannelName());
1873#endif
1874 return;
1875 }
1876
1877 // If the dispatch entry is in progress but it already has a tail of pending
1878 // motion samples, then it must mean that the shared memory buffer filled up.
1879 // Not a problem, when this dispatch cycle is finished, we will eventually start
1880 // a new dispatch cycle to process the tail and that tail includes the newly
1881 // appended motion sample.
1882 if (motionEventDispatchEntry->tailMotionSample) {
1883#if DEBUG_BATCHING
1884 LOGD("channel '%s' ~ Not streaming because no new samples can "
1885 "be appended to the motion event in this dispatch cycle. "
1886 "(Waiting for next dispatch cycle to start.)",
1887 connection->getInputChannelName());
1888#endif
1889 return;
1890 }
1891
Jeff Brown81346812011-06-28 20:08:48 -07001892 // If the motion event was modified in flight, then we cannot stream the sample.
1893 if ((motionEventDispatchEntry->targetFlags & InputTarget::FLAG_DISPATCH_MASK)
1894 != InputTarget::FLAG_DISPATCH_AS_IS) {
1895#if DEBUG_BATCHING
1896 LOGD("channel '%s' ~ Not streaming because the motion event was not "
1897 "being dispatched as-is. "
1898 "(Waiting for next dispatch cycle to start.)",
1899 connection->getInputChannelName());
1900#endif
1901 return;
1902 }
1903
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001904 // The dispatch entry is in progress and is still potentially open for streaming.
1905 // Try to stream the new motion sample. This might fail if the consumer has already
1906 // consumed the motion event (or if the channel is broken).
Jeff Brown01ce2e92010-09-26 22:20:12 -07001907 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
1908 MotionSample* appendedMotionSample = motionEntry->lastSample;
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001909 status_t status;
1910 if (motionEventDispatchEntry->scaleFactor == 1.0f) {
1911 status = connection->inputPublisher.appendMotionSample(
1912 appendedMotionSample->eventTime, appendedMotionSample->pointerCoords);
1913 } else {
1914 PointerCoords scaledCoords[MAX_POINTERS];
1915 for (size_t i = 0; i < motionEntry->pointerCount; i++) {
1916 scaledCoords[i] = appendedMotionSample->pointerCoords[i];
1917 scaledCoords[i].scale(motionEventDispatchEntry->scaleFactor);
1918 }
1919 status = connection->inputPublisher.appendMotionSample(
1920 appendedMotionSample->eventTime, scaledCoords);
1921 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001922 if (status == OK) {
1923#if DEBUG_BATCHING
1924 LOGD("channel '%s' ~ Successfully streamed new motion sample.",
1925 connection->getInputChannelName());
1926#endif
1927 return;
1928 }
1929
1930#if DEBUG_BATCHING
1931 if (status == NO_MEMORY) {
1932 LOGD("channel '%s' ~ Could not append motion sample to currently "
1933 "dispatched move event because the shared memory buffer is full. "
1934 "(Waiting for next dispatch cycle to start.)",
1935 connection->getInputChannelName());
1936 } else if (status == status_t(FAILED_TRANSACTION)) {
1937 LOGD("channel '%s' ~ Could not append motion sample to currently "
Jeff Brown349703e2010-06-22 01:27:15 -07001938 "dispatched move event because the event has already been consumed. "
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001939 "(Waiting for next dispatch cycle to start.)",
1940 connection->getInputChannelName());
1941 } else {
1942 LOGD("channel '%s' ~ Could not append motion sample to currently "
1943 "dispatched move event due to an error, status=%d. "
1944 "(Waiting for next dispatch cycle to start.)",
1945 connection->getInputChannelName(), status);
1946 }
1947#endif
1948 // Failed to stream. Start a new tail of pending motion samples to dispatch
1949 // in the next cycle.
1950 motionEventDispatchEntry->tailMotionSample = appendedMotionSample;
1951 return;
1952 }
1953 }
1954
Jeff Browna032cc02011-03-07 16:56:21 -08001955 // Enqueue dispatch entries for the requested modes.
1956 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1957 resumeWithAppendedMotionSample, InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
1958 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1959 resumeWithAppendedMotionSample, InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
1960 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1961 resumeWithAppendedMotionSample, InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
1962 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1963 resumeWithAppendedMotionSample, InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brown98db5fa2011-06-08 15:37:10 -07001964 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1965 resumeWithAppendedMotionSample, InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
1966 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1967 resumeWithAppendedMotionSample, InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Jeff Browna032cc02011-03-07 16:56:21 -08001968
1969 // If the outbound queue was previously empty, start the dispatch cycle going.
Jeff Brownb6110c22011-04-01 16:15:13 -07001970 if (wasEmpty && !connection->outboundQueue.isEmpty()) {
Jeff Browna032cc02011-03-07 16:56:21 -08001971 activateConnectionLocked(connection.get());
1972 startDispatchCycleLocked(currentTime, connection);
1973 }
1974}
1975
1976void InputDispatcher::enqueueDispatchEntryLocked(
1977 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget,
1978 bool resumeWithAppendedMotionSample, int32_t dispatchMode) {
1979 int32_t inputTargetFlags = inputTarget->flags;
1980 if (!(inputTargetFlags & dispatchMode)) {
1981 return;
1982 }
1983 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
1984
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001985 // This is a new event.
1986 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Jeff Brownac386072011-07-20 15:19:50 -07001987 DispatchEntry* dispatchEntry = new DispatchEntry(eventEntry, // increments ref
Dianne Hackbornaa9d84c2011-05-09 19:00:59 -07001988 inputTargetFlags, inputTarget->xOffset, inputTarget->yOffset,
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001989 inputTarget->scaleFactor);
Jeff Brown519e0242010-09-15 15:18:56 -07001990 if (dispatchEntry->hasForegroundTarget()) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001991 incrementPendingForegroundDispatchesLocked(eventEntry);
Jeff Brown6ec402b2010-07-28 15:48:59 -07001992 }
1993
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001994 // Handle the case where we could not stream a new motion sample because the consumer has
1995 // already consumed the motion event (otherwise the corresponding dispatch entry would
1996 // still be in the outbound queue for this connection). We set the head motion sample
1997 // to the list starting with the newly appended motion sample.
1998 if (resumeWithAppendedMotionSample) {
1999#if DEBUG_BATCHING
2000 LOGD("channel '%s' ~ Preparing a new dispatch cycle for additional motion samples "
2001 "that cannot be streamed because the motion event has already been consumed.",
2002 connection->getInputChannelName());
2003#endif
2004 MotionSample* appendedMotionSample = static_cast<MotionEntry*>(eventEntry)->lastSample;
2005 dispatchEntry->headMotionSample = appendedMotionSample;
2006 }
2007
Jeff Brown81346812011-06-28 20:08:48 -07002008 // Apply target flags and update the connection's input state.
2009 switch (eventEntry->type) {
2010 case EventEntry::TYPE_KEY: {
2011 KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
2012 dispatchEntry->resolvedAction = keyEntry->action;
2013 dispatchEntry->resolvedFlags = keyEntry->flags;
2014
2015 if (!connection->inputState.trackKey(keyEntry,
2016 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags)) {
2017#if DEBUG_DISPATCH_CYCLE
2018 LOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
2019 connection->getInputChannelName());
2020#endif
2021 return; // skip the inconsistent event
2022 }
2023 break;
2024 }
2025
2026 case EventEntry::TYPE_MOTION: {
2027 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
2028 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2029 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
2030 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
2031 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
2032 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
2033 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2034 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
2035 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
2036 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
2037 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
2038 } else {
2039 dispatchEntry->resolvedAction = motionEntry->action;
2040 }
2041 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE
2042 && !connection->inputState.isHovering(
2043 motionEntry->deviceId, motionEntry->source)) {
2044#if DEBUG_DISPATCH_CYCLE
2045 LOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter event",
2046 connection->getInputChannelName());
2047#endif
2048 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2049 }
2050
2051 dispatchEntry->resolvedFlags = motionEntry->flags;
2052 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
2053 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
2054 }
2055
2056 if (!connection->inputState.trackMotion(motionEntry,
2057 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags)) {
2058#if DEBUG_DISPATCH_CYCLE
2059 LOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion event",
2060 connection->getInputChannelName());
2061#endif
2062 return; // skip the inconsistent event
2063 }
2064 break;
2065 }
2066 }
2067
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002068 // Enqueue the dispatch entry.
2069 connection->outboundQueue.enqueueAtTail(dispatchEntry);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002070}
2071
Jeff Brown7fbdc842010-06-17 20:52:56 -07002072void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Jeff Brown519e0242010-09-15 15:18:56 -07002073 const sp<Connection>& connection) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002074#if DEBUG_DISPATCH_CYCLE
2075 LOGD("channel '%s' ~ startDispatchCycle",
2076 connection->getInputChannelName());
2077#endif
2078
Jeff Brownb6110c22011-04-01 16:15:13 -07002079 LOG_ASSERT(connection->status == Connection::STATUS_NORMAL);
2080 LOG_ASSERT(! connection->outboundQueue.isEmpty());
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002081
Jeff Brownac386072011-07-20 15:19:50 -07002082 DispatchEntry* dispatchEntry = connection->outboundQueue.head;
Jeff Brownb6110c22011-04-01 16:15:13 -07002083 LOG_ASSERT(! dispatchEntry->inProgress);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002084
Jeff Brownb88102f2010-09-08 11:49:43 -07002085 // Mark the dispatch entry as in progress.
2086 dispatchEntry->inProgress = true;
2087
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002088 // Publish the event.
2089 status_t status;
Jeff Browna032cc02011-03-07 16:56:21 -08002090 EventEntry* eventEntry = dispatchEntry->eventEntry;
Jeff Brown01ce2e92010-09-26 22:20:12 -07002091 switch (eventEntry->type) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002092 case EventEntry::TYPE_KEY: {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002093 KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002094
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002095 // Publish the key event.
Jeff Brown81346812011-06-28 20:08:48 -07002096 status = connection->inputPublisher.publishKeyEvent(
2097 keyEntry->deviceId, keyEntry->source,
2098 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags,
2099 keyEntry->keyCode, keyEntry->scanCode,
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002100 keyEntry->metaState, keyEntry->repeatCount, keyEntry->downTime,
2101 keyEntry->eventTime);
2102
2103 if (status) {
2104 LOGE("channel '%s' ~ Could not publish key event, "
2105 "status=%d", connection->getInputChannelName(), status);
Jeff Brownb6997262010-10-08 22:31:17 -07002106 abortBrokenDispatchCycleLocked(currentTime, connection);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002107 return;
2108 }
2109 break;
2110 }
2111
2112 case EventEntry::TYPE_MOTION: {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002113 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002114
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002115 // If headMotionSample is non-NULL, then it points to the first new sample that we
2116 // were unable to dispatch during the previous cycle so we resume dispatching from
2117 // that point in the list of motion samples.
2118 // Otherwise, we just start from the first sample of the motion event.
2119 MotionSample* firstMotionSample = dispatchEntry->headMotionSample;
2120 if (! firstMotionSample) {
2121 firstMotionSample = & motionEntry->firstSample;
2122 }
2123
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002124 PointerCoords scaledCoords[MAX_POINTERS];
2125 const PointerCoords* usingCoords = firstMotionSample->pointerCoords;
2126
Jeff Brownd3616592010-07-16 17:21:06 -07002127 // Set the X and Y offset depending on the input source.
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002128 float xOffset, yOffset, scaleFactor;
Kenny Root7a9db182011-06-02 15:16:05 -07002129 if (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER
2130 && !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002131 scaleFactor = dispatchEntry->scaleFactor;
2132 xOffset = dispatchEntry->xOffset * scaleFactor;
2133 yOffset = dispatchEntry->yOffset * scaleFactor;
2134 if (scaleFactor != 1.0f) {
2135 for (size_t i = 0; i < motionEntry->pointerCount; i++) {
2136 scaledCoords[i] = firstMotionSample->pointerCoords[i];
2137 scaledCoords[i].scale(scaleFactor);
2138 }
2139 usingCoords = scaledCoords;
2140 }
Jeff Brownd3616592010-07-16 17:21:06 -07002141 } else {
2142 xOffset = 0.0f;
2143 yOffset = 0.0f;
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002144 scaleFactor = 1.0f;
Kenny Root7a9db182011-06-02 15:16:05 -07002145
2146 // We don't want the dispatch target to know.
2147 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
2148 for (size_t i = 0; i < motionEntry->pointerCount; i++) {
2149 scaledCoords[i].clear();
2150 }
2151 usingCoords = scaledCoords;
2152 }
Jeff Brownd3616592010-07-16 17:21:06 -07002153 }
2154
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002155 // Publish the motion event and the first motion sample.
Jeff Brown81346812011-06-28 20:08:48 -07002156 status = connection->inputPublisher.publishMotionEvent(
2157 motionEntry->deviceId, motionEntry->source,
2158 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags,
2159 motionEntry->edgeFlags, motionEntry->metaState, motionEntry->buttonState,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002160 xOffset, yOffset,
2161 motionEntry->xPrecision, motionEntry->yPrecision,
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002162 motionEntry->downTime, firstMotionSample->eventTime,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002163 motionEntry->pointerCount, motionEntry->pointerProperties,
2164 usingCoords);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002165
2166 if (status) {
2167 LOGE("channel '%s' ~ Could not publish motion event, "
2168 "status=%d", connection->getInputChannelName(), status);
Jeff Brownb6997262010-10-08 22:31:17 -07002169 abortBrokenDispatchCycleLocked(currentTime, connection);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002170 return;
2171 }
2172
Jeff Brown81346812011-06-28 20:08:48 -07002173 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_MOVE
2174 || dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Jeff Browna032cc02011-03-07 16:56:21 -08002175 // Append additional motion samples.
2176 MotionSample* nextMotionSample = firstMotionSample->next;
2177 for (; nextMotionSample != NULL; nextMotionSample = nextMotionSample->next) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002178 if (usingCoords == scaledCoords) {
Kenny Root7a9db182011-06-02 15:16:05 -07002179 if (!(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
2180 for (size_t i = 0; i < motionEntry->pointerCount; i++) {
2181 scaledCoords[i] = nextMotionSample->pointerCoords[i];
2182 scaledCoords[i].scale(scaleFactor);
2183 }
Dianne Hackborn2ba3e802011-05-11 10:59:54 -07002184 }
2185 } else {
2186 usingCoords = nextMotionSample->pointerCoords;
Dianne Hackborne7d25b72011-05-09 21:19:26 -07002187 }
Jeff Browna032cc02011-03-07 16:56:21 -08002188 status = connection->inputPublisher.appendMotionSample(
Dianne Hackbornaa9d84c2011-05-09 19:00:59 -07002189 nextMotionSample->eventTime, usingCoords);
Jeff Browna032cc02011-03-07 16:56:21 -08002190 if (status == NO_MEMORY) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002191#if DEBUG_DISPATCH_CYCLE
2192 LOGD("channel '%s' ~ Shared memory buffer full. Some motion samples will "
2193 "be sent in the next dispatch cycle.",
2194 connection->getInputChannelName());
2195#endif
Jeff Browna032cc02011-03-07 16:56:21 -08002196 break;
2197 }
2198 if (status != OK) {
2199 LOGE("channel '%s' ~ Could not append motion sample "
2200 "for a reason other than out of memory, status=%d",
2201 connection->getInputChannelName(), status);
2202 abortBrokenDispatchCycleLocked(currentTime, connection);
2203 return;
2204 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002205 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002206
Jeff Browna032cc02011-03-07 16:56:21 -08002207 // Remember the next motion sample that we could not dispatch, in case we ran out
2208 // of space in the shared memory buffer.
2209 dispatchEntry->tailMotionSample = nextMotionSample;
2210 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002211 break;
2212 }
2213
2214 default: {
Jeff Brownb6110c22011-04-01 16:15:13 -07002215 LOG_ASSERT(false);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002216 }
2217 }
2218
2219 // Send the dispatch signal.
2220 status = connection->inputPublisher.sendDispatchSignal();
2221 if (status) {
2222 LOGE("channel '%s' ~ Could not send dispatch signal, status=%d",
2223 connection->getInputChannelName(), status);
Jeff Brownb6997262010-10-08 22:31:17 -07002224 abortBrokenDispatchCycleLocked(currentTime, connection);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002225 return;
2226 }
2227
2228 // Record information about the newly started dispatch cycle.
Jeff Brown01ce2e92010-09-26 22:20:12 -07002229 connection->lastEventTime = eventEntry->eventTime;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002230 connection->lastDispatchTime = currentTime;
2231
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002232 // Notify other system components.
2233 onDispatchCycleStartedLocked(currentTime, connection);
2234}
2235
Jeff Brown7fbdc842010-06-17 20:52:56 -07002236void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Jeff Brown3915bb82010-11-05 15:02:16 -07002237 const sp<Connection>& connection, bool handled) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002238#if DEBUG_DISPATCH_CYCLE
Jeff Brown9c3cda02010-06-15 01:31:58 -07002239 LOGD("channel '%s' ~ finishDispatchCycle - %01.1fms since event, "
Jeff Brown3915bb82010-11-05 15:02:16 -07002240 "%01.1fms since dispatch, handled=%s",
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002241 connection->getInputChannelName(),
2242 connection->getEventLatencyMillis(currentTime),
Jeff Brown3915bb82010-11-05 15:02:16 -07002243 connection->getDispatchLatencyMillis(currentTime),
2244 toString(handled));
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002245#endif
2246
Jeff Brown9c3cda02010-06-15 01:31:58 -07002247 if (connection->status == Connection::STATUS_BROKEN
2248 || connection->status == Connection::STATUS_ZOMBIE) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002249 return;
2250 }
2251
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002252 // Reset the publisher since the event has been consumed.
2253 // We do this now so that the publisher can release some of its internal resources
2254 // while waiting for the next dispatch cycle to begin.
2255 status_t status = connection->inputPublisher.reset();
2256 if (status) {
2257 LOGE("channel '%s' ~ Could not reset publisher, status=%d",
2258 connection->getInputChannelName(), status);
Jeff Brownb6997262010-10-08 22:31:17 -07002259 abortBrokenDispatchCycleLocked(currentTime, connection);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002260 return;
2261 }
2262
Jeff Brown3915bb82010-11-05 15:02:16 -07002263 // Notify other system components and prepare to start the next dispatch cycle.
2264 onDispatchCycleFinishedLocked(currentTime, connection, handled);
Jeff Brownb88102f2010-09-08 11:49:43 -07002265}
2266
2267void InputDispatcher::startNextDispatchCycleLocked(nsecs_t currentTime,
2268 const sp<Connection>& connection) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002269 // Start the next dispatch cycle for this connection.
2270 while (! connection->outboundQueue.isEmpty()) {
Jeff Brownac386072011-07-20 15:19:50 -07002271 DispatchEntry* dispatchEntry = connection->outboundQueue.head;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002272 if (dispatchEntry->inProgress) {
2273 // Finish or resume current event in progress.
2274 if (dispatchEntry->tailMotionSample) {
2275 // We have a tail of undispatched motion samples.
2276 // Reuse the same DispatchEntry and start a new cycle.
2277 dispatchEntry->inProgress = false;
2278 dispatchEntry->headMotionSample = dispatchEntry->tailMotionSample;
2279 dispatchEntry->tailMotionSample = NULL;
Jeff Brown519e0242010-09-15 15:18:56 -07002280 startDispatchCycleLocked(currentTime, connection);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002281 return;
2282 }
2283 // Finished.
2284 connection->outboundQueue.dequeueAtHead();
Jeff Brown519e0242010-09-15 15:18:56 -07002285 if (dispatchEntry->hasForegroundTarget()) {
2286 decrementPendingForegroundDispatchesLocked(dispatchEntry->eventEntry);
Jeff Brown6ec402b2010-07-28 15:48:59 -07002287 }
Jeff Brownac386072011-07-20 15:19:50 -07002288 delete dispatchEntry;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002289 } else {
2290 // If the head is not in progress, then we must have already dequeued the in
Jeff Brown519e0242010-09-15 15:18:56 -07002291 // progress event, which means we actually aborted it.
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002292 // So just start the next event for this connection.
Jeff Brown519e0242010-09-15 15:18:56 -07002293 startDispatchCycleLocked(currentTime, connection);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002294 return;
2295 }
2296 }
2297
2298 // Outbound queue is empty, deactivate the connection.
Jeff Brown7fbdc842010-06-17 20:52:56 -07002299 deactivateConnectionLocked(connection.get());
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002300}
2301
Jeff Brownb6997262010-10-08 22:31:17 -07002302void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
2303 const sp<Connection>& connection) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002304#if DEBUG_DISPATCH_CYCLE
Jeff Brown83c09682010-12-23 17:50:18 -08002305 LOGD("channel '%s' ~ abortBrokenDispatchCycle",
2306 connection->getInputChannelName());
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002307#endif
2308
Jeff Brownb88102f2010-09-08 11:49:43 -07002309 // Clear the outbound queue.
Jeff Brown519e0242010-09-15 15:18:56 -07002310 drainOutboundQueueLocked(connection.get());
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002311
Jeff Brownb6997262010-10-08 22:31:17 -07002312 // The connection appears to be unrecoverably broken.
Jeff Brown9c3cda02010-06-15 01:31:58 -07002313 // Ignore already broken or zombie connections.
Jeff Brownb6997262010-10-08 22:31:17 -07002314 if (connection->status == Connection::STATUS_NORMAL) {
2315 connection->status = Connection::STATUS_BROKEN;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002316
Jeff Brownb6997262010-10-08 22:31:17 -07002317 // Notify other system components.
2318 onDispatchCycleBrokenLocked(currentTime, connection);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002319 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002320}
2321
Jeff Brown519e0242010-09-15 15:18:56 -07002322void InputDispatcher::drainOutboundQueueLocked(Connection* connection) {
2323 while (! connection->outboundQueue.isEmpty()) {
2324 DispatchEntry* dispatchEntry = connection->outboundQueue.dequeueAtHead();
2325 if (dispatchEntry->hasForegroundTarget()) {
2326 decrementPendingForegroundDispatchesLocked(dispatchEntry->eventEntry);
Jeff Brownb88102f2010-09-08 11:49:43 -07002327 }
Jeff Brownac386072011-07-20 15:19:50 -07002328 delete dispatchEntry;
Jeff Brownb88102f2010-09-08 11:49:43 -07002329 }
2330
Jeff Brown519e0242010-09-15 15:18:56 -07002331 deactivateConnectionLocked(connection);
Jeff Brownb88102f2010-09-08 11:49:43 -07002332}
2333
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002334int InputDispatcher::handleReceiveCallback(int receiveFd, int events, void* data) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002335 InputDispatcher* d = static_cast<InputDispatcher*>(data);
2336
2337 { // acquire lock
2338 AutoMutex _l(d->mLock);
2339
2340 ssize_t connectionIndex = d->mConnectionsByReceiveFd.indexOfKey(receiveFd);
2341 if (connectionIndex < 0) {
2342 LOGE("Received spurious receive callback for unknown input channel. "
2343 "fd=%d, events=0x%x", receiveFd, events);
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002344 return 0; // remove the callback
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002345 }
2346
Jeff Brown7fbdc842010-06-17 20:52:56 -07002347 nsecs_t currentTime = now();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002348
2349 sp<Connection> connection = d->mConnectionsByReceiveFd.valueAt(connectionIndex);
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002350 if (events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP)) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002351 LOGE("channel '%s' ~ Consumer closed input channel or an error occurred. "
2352 "events=0x%x", connection->getInputChannelName(), events);
Jeff Brownb6997262010-10-08 22:31:17 -07002353 d->abortBrokenDispatchCycleLocked(currentTime, connection);
Jeff Brown9c3cda02010-06-15 01:31:58 -07002354 d->runCommandsLockedInterruptible();
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002355 return 0; // remove the callback
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002356 }
2357
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002358 if (! (events & ALOOPER_EVENT_INPUT)) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002359 LOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
2360 "events=0x%x", connection->getInputChannelName(), events);
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002361 return 1;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002362 }
2363
Jeff Brown3915bb82010-11-05 15:02:16 -07002364 bool handled = false;
Jeff Brown49ed71d2010-12-06 17:13:33 -08002365 status_t status = connection->inputPublisher.receiveFinishedSignal(&handled);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002366 if (status) {
2367 LOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
2368 connection->getInputChannelName(), status);
Jeff Brownb6997262010-10-08 22:31:17 -07002369 d->abortBrokenDispatchCycleLocked(currentTime, connection);
Jeff Brown9c3cda02010-06-15 01:31:58 -07002370 d->runCommandsLockedInterruptible();
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002371 return 0; // remove the callback
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002372 }
2373
Jeff Brown3915bb82010-11-05 15:02:16 -07002374 d->finishDispatchCycleLocked(currentTime, connection, handled);
Jeff Brown9c3cda02010-06-15 01:31:58 -07002375 d->runCommandsLockedInterruptible();
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002376 return 1;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002377 } // release lock
2378}
2379
Jeff Brownb6997262010-10-08 22:31:17 -07002380void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Jeff Brownda3d5a92011-03-29 15:11:34 -07002381 const CancelationOptions& options) {
Jeff Brownb6997262010-10-08 22:31:17 -07002382 for (size_t i = 0; i < mConnectionsByReceiveFd.size(); i++) {
2383 synthesizeCancelationEventsForConnectionLocked(
Jeff Brownda3d5a92011-03-29 15:11:34 -07002384 mConnectionsByReceiveFd.valueAt(i), options);
Jeff Brownb6997262010-10-08 22:31:17 -07002385 }
2386}
2387
2388void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Jeff Brownda3d5a92011-03-29 15:11:34 -07002389 const sp<InputChannel>& channel, const CancelationOptions& options) {
Jeff Brownb6997262010-10-08 22:31:17 -07002390 ssize_t index = getConnectionIndexLocked(channel);
2391 if (index >= 0) {
2392 synthesizeCancelationEventsForConnectionLocked(
Jeff Brownda3d5a92011-03-29 15:11:34 -07002393 mConnectionsByReceiveFd.valueAt(index), options);
Jeff Brownb6997262010-10-08 22:31:17 -07002394 }
2395}
2396
2397void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
Jeff Brownda3d5a92011-03-29 15:11:34 -07002398 const sp<Connection>& connection, const CancelationOptions& options) {
Jeff Brownb6997262010-10-08 22:31:17 -07002399 nsecs_t currentTime = now();
2400
2401 mTempCancelationEvents.clear();
Jeff Brownac386072011-07-20 15:19:50 -07002402 connection->inputState.synthesizeCancelationEvents(currentTime,
Jeff Brownb6997262010-10-08 22:31:17 -07002403 mTempCancelationEvents, options);
2404
2405 if (! mTempCancelationEvents.isEmpty()
2406 && connection->status != Connection::STATUS_BROKEN) {
2407#if DEBUG_OUTBOUND_EVENT_DETAILS
2408 LOGD("channel '%s' ~ Synthesized %d cancelation events to bring channel back in sync "
Jeff Brownda3d5a92011-03-29 15:11:34 -07002409 "with reality: %s, mode=%d.",
2410 connection->getInputChannelName(), mTempCancelationEvents.size(),
2411 options.reason, options.mode);
Jeff Brownb6997262010-10-08 22:31:17 -07002412#endif
2413 for (size_t i = 0; i < mTempCancelationEvents.size(); i++) {
2414 EventEntry* cancelationEventEntry = mTempCancelationEvents.itemAt(i);
2415 switch (cancelationEventEntry->type) {
2416 case EventEntry::TYPE_KEY:
2417 logOutboundKeyDetailsLocked("cancel - ",
2418 static_cast<KeyEntry*>(cancelationEventEntry));
2419 break;
2420 case EventEntry::TYPE_MOTION:
2421 logOutboundMotionDetailsLocked("cancel - ",
2422 static_cast<MotionEntry*>(cancelationEventEntry));
2423 break;
2424 }
2425
Jeff Brown81346812011-06-28 20:08:48 -07002426 InputTarget target;
Jeff Brown9302c872011-07-13 22:51:29 -07002427 sp<InputWindowHandle> windowHandle = getWindowHandleLocked(connection->inputChannel);
2428 if (windowHandle != NULL) {
2429 target.xOffset = -windowHandle->frameLeft;
2430 target.yOffset = -windowHandle->frameTop;
2431 target.scaleFactor = windowHandle->scaleFactor;
Jeff Brownb6997262010-10-08 22:31:17 -07002432 } else {
Jeff Brown81346812011-06-28 20:08:48 -07002433 target.xOffset = 0;
2434 target.yOffset = 0;
2435 target.scaleFactor = 1.0f;
Jeff Brownb6997262010-10-08 22:31:17 -07002436 }
Jeff Brown81346812011-06-28 20:08:48 -07002437 target.inputChannel = connection->inputChannel;
2438 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
Jeff Brownb6997262010-10-08 22:31:17 -07002439
Jeff Brown81346812011-06-28 20:08:48 -07002440 enqueueDispatchEntryLocked(connection, cancelationEventEntry, // increments ref
2441 &target, false, InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brownb6997262010-10-08 22:31:17 -07002442
Jeff Brownac386072011-07-20 15:19:50 -07002443 cancelationEventEntry->release();
Jeff Brownb6997262010-10-08 22:31:17 -07002444 }
2445
Jeff Brownac386072011-07-20 15:19:50 -07002446 if (!connection->outboundQueue.head->inProgress) {
Jeff Brownb6997262010-10-08 22:31:17 -07002447 startDispatchCycleLocked(currentTime, connection);
2448 }
2449 }
2450}
2451
Jeff Brown01ce2e92010-09-26 22:20:12 -07002452InputDispatcher::MotionEntry*
2453InputDispatcher::splitMotionEvent(const MotionEntry* originalMotionEntry, BitSet32 pointerIds) {
Jeff Brownb6110c22011-04-01 16:15:13 -07002454 LOG_ASSERT(pointerIds.value != 0);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002455
2456 uint32_t splitPointerIndexMap[MAX_POINTERS];
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002457 PointerProperties splitPointerProperties[MAX_POINTERS];
Jeff Brown01ce2e92010-09-26 22:20:12 -07002458 PointerCoords splitPointerCoords[MAX_POINTERS];
2459
2460 uint32_t originalPointerCount = originalMotionEntry->pointerCount;
2461 uint32_t splitPointerCount = 0;
2462
2463 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
2464 originalPointerIndex++) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002465 const PointerProperties& pointerProperties =
2466 originalMotionEntry->pointerProperties[originalPointerIndex];
2467 uint32_t pointerId = uint32_t(pointerProperties.id);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002468 if (pointerIds.hasBit(pointerId)) {
2469 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002470 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
Jeff Brownace13b12011-03-09 17:39:48 -08002471 splitPointerCoords[splitPointerCount].copyFrom(
2472 originalMotionEntry->firstSample.pointerCoords[originalPointerIndex]);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002473 splitPointerCount += 1;
2474 }
2475 }
Jeff Brown58a2da82011-01-25 16:02:22 -08002476
2477 if (splitPointerCount != pointerIds.count()) {
2478 // This is bad. We are missing some of the pointers that we expected to deliver.
2479 // Most likely this indicates that we received an ACTION_MOVE events that has
2480 // different pointer ids than we expected based on the previous ACTION_DOWN
2481 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
2482 // in this way.
2483 LOGW("Dropping split motion event because the pointer count is %d but "
2484 "we expected there to be %d pointers. This probably means we received "
2485 "a broken sequence of pointer ids from the input device.",
2486 splitPointerCount, pointerIds.count());
2487 return NULL;
2488 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07002489
2490 int32_t action = originalMotionEntry->action;
2491 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
2492 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
2493 || maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2494 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002495 const PointerProperties& pointerProperties =
2496 originalMotionEntry->pointerProperties[originalPointerIndex];
2497 uint32_t pointerId = uint32_t(pointerProperties.id);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002498 if (pointerIds.hasBit(pointerId)) {
2499 if (pointerIds.count() == 1) {
2500 // The first/last pointer went down/up.
2501 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
2502 ? AMOTION_EVENT_ACTION_DOWN : AMOTION_EVENT_ACTION_UP;
Jeff Brown9a01d052010-09-27 16:35:11 -07002503 } else {
2504 // A secondary pointer went down/up.
2505 uint32_t splitPointerIndex = 0;
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002506 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
Jeff Brown9a01d052010-09-27 16:35:11 -07002507 splitPointerIndex += 1;
2508 }
2509 action = maskedAction | (splitPointerIndex
2510 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002511 }
2512 } else {
2513 // An unrelated pointer changed.
2514 action = AMOTION_EVENT_ACTION_MOVE;
2515 }
2516 }
2517
Jeff Brownac386072011-07-20 15:19:50 -07002518 MotionEntry* splitMotionEntry = new MotionEntry(
Jeff Brown01ce2e92010-09-26 22:20:12 -07002519 originalMotionEntry->eventTime,
2520 originalMotionEntry->deviceId,
2521 originalMotionEntry->source,
2522 originalMotionEntry->policyFlags,
2523 action,
2524 originalMotionEntry->flags,
2525 originalMotionEntry->metaState,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002526 originalMotionEntry->buttonState,
Jeff Brown01ce2e92010-09-26 22:20:12 -07002527 originalMotionEntry->edgeFlags,
2528 originalMotionEntry->xPrecision,
2529 originalMotionEntry->yPrecision,
2530 originalMotionEntry->downTime,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002531 splitPointerCount, splitPointerProperties, splitPointerCoords);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002532
2533 for (MotionSample* originalMotionSample = originalMotionEntry->firstSample.next;
2534 originalMotionSample != NULL; originalMotionSample = originalMotionSample->next) {
2535 for (uint32_t splitPointerIndex = 0; splitPointerIndex < splitPointerCount;
2536 splitPointerIndex++) {
2537 uint32_t originalPointerIndex = splitPointerIndexMap[splitPointerIndex];
Jeff Brownace13b12011-03-09 17:39:48 -08002538 splitPointerCoords[splitPointerIndex].copyFrom(
2539 originalMotionSample->pointerCoords[originalPointerIndex]);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002540 }
2541
Jeff Brownac386072011-07-20 15:19:50 -07002542 splitMotionEntry->appendSample(originalMotionSample->eventTime, splitPointerCoords);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002543 }
2544
Jeff Browna032cc02011-03-07 16:56:21 -08002545 if (originalMotionEntry->injectionState) {
2546 splitMotionEntry->injectionState = originalMotionEntry->injectionState;
2547 splitMotionEntry->injectionState->refCount += 1;
2548 }
2549
Jeff Brown01ce2e92010-09-26 22:20:12 -07002550 return splitMotionEntry;
2551}
2552
Jeff Brown9c3cda02010-06-15 01:31:58 -07002553void InputDispatcher::notifyConfigurationChanged(nsecs_t eventTime) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002554#if DEBUG_INBOUND_EVENT_DETAILS
Jeff Brown9c3cda02010-06-15 01:31:58 -07002555 LOGD("notifyConfigurationChanged - eventTime=%lld", eventTime);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002556#endif
2557
Jeff Brownb88102f2010-09-08 11:49:43 -07002558 bool needWake;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002559 { // acquire lock
2560 AutoMutex _l(mLock);
2561
Jeff Brownac386072011-07-20 15:19:50 -07002562 ConfigurationChangedEntry* newEntry = new ConfigurationChangedEntry(eventTime);
Jeff Brownb88102f2010-09-08 11:49:43 -07002563 needWake = enqueueInboundEventLocked(newEntry);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002564 } // release lock
2565
Jeff Brownb88102f2010-09-08 11:49:43 -07002566 if (needWake) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002567 mLooper->wake();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002568 }
2569}
2570
Jeff Brown58a2da82011-01-25 16:02:22 -08002571void InputDispatcher::notifyKey(nsecs_t eventTime, int32_t deviceId, uint32_t source,
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002572 uint32_t policyFlags, int32_t action, int32_t flags,
2573 int32_t keyCode, int32_t scanCode, int32_t metaState, nsecs_t downTime) {
2574#if DEBUG_INBOUND_EVENT_DETAILS
Jeff Brown90655042010-12-02 13:50:46 -08002575 LOGD("notifyKey - eventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, action=0x%x, "
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002576 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%lld",
Jeff Brownc5ed5912010-07-14 18:48:53 -07002577 eventTime, deviceId, source, policyFlags, action, flags,
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002578 keyCode, scanCode, metaState, downTime);
2579#endif
Jeff Brown01ce2e92010-09-26 22:20:12 -07002580 if (! validateKeyEvent(action)) {
2581 return;
2582 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002583
Jeff Brown1f245102010-11-18 20:53:46 -08002584 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
2585 policyFlags |= POLICY_FLAG_VIRTUAL;
2586 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
2587 }
Jeff Brown924c4d42011-03-07 16:40:47 -08002588 if (policyFlags & POLICY_FLAG_ALT) {
2589 metaState |= AMETA_ALT_ON | AMETA_ALT_LEFT_ON;
2590 }
2591 if (policyFlags & POLICY_FLAG_ALT_GR) {
2592 metaState |= AMETA_ALT_ON | AMETA_ALT_RIGHT_ON;
2593 }
2594 if (policyFlags & POLICY_FLAG_SHIFT) {
2595 metaState |= AMETA_SHIFT_ON | AMETA_SHIFT_LEFT_ON;
2596 }
2597 if (policyFlags & POLICY_FLAG_CAPS_LOCK) {
2598 metaState |= AMETA_CAPS_LOCK_ON;
2599 }
2600 if (policyFlags & POLICY_FLAG_FUNCTION) {
2601 metaState |= AMETA_FUNCTION_ON;
2602 }
Jeff Brown1f245102010-11-18 20:53:46 -08002603
Jeff Browne20c9e02010-10-11 14:20:19 -07002604 policyFlags |= POLICY_FLAG_TRUSTED;
Jeff Brown1f245102010-11-18 20:53:46 -08002605
2606 KeyEvent event;
2607 event.initialize(deviceId, source, action, flags, keyCode, scanCode,
2608 metaState, 0, downTime, eventTime);
2609
2610 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
2611
2612 if (policyFlags & POLICY_FLAG_WOKE_HERE) {
2613 flags |= AKEY_EVENT_FLAG_WOKE_HERE;
2614 }
Jeff Brownb6997262010-10-08 22:31:17 -07002615
Jeff Brownb88102f2010-09-08 11:49:43 -07002616 bool needWake;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002617 { // acquire lock
Jeff Brown0029c662011-03-30 02:25:18 -07002618 mLock.lock();
2619
2620 if (mInputFilterEnabled) {
2621 mLock.unlock();
2622
2623 policyFlags |= POLICY_FLAG_FILTERED;
2624 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2625 return; // event was consumed by the filter
2626 }
2627
2628 mLock.lock();
2629 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002630
Jeff Brown7fbdc842010-06-17 20:52:56 -07002631 int32_t repeatCount = 0;
Jeff Brownac386072011-07-20 15:19:50 -07002632 KeyEntry* newEntry = new KeyEntry(eventTime,
Jeff Brownc5ed5912010-07-14 18:48:53 -07002633 deviceId, source, policyFlags, action, flags, keyCode, scanCode,
Jeff Brown7fbdc842010-06-17 20:52:56 -07002634 metaState, repeatCount, downTime);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002635
Jeff Brownb88102f2010-09-08 11:49:43 -07002636 needWake = enqueueInboundEventLocked(newEntry);
Jeff Brown0029c662011-03-30 02:25:18 -07002637 mLock.unlock();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002638 } // release lock
2639
Jeff Brownb88102f2010-09-08 11:49:43 -07002640 if (needWake) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002641 mLooper->wake();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002642 }
2643}
2644
Jeff Brown58a2da82011-01-25 16:02:22 -08002645void InputDispatcher::notifyMotion(nsecs_t eventTime, int32_t deviceId, uint32_t source,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002646 uint32_t policyFlags, int32_t action, int32_t flags,
2647 int32_t metaState, int32_t buttonState, int32_t edgeFlags,
2648 uint32_t pointerCount, const PointerProperties* pointerProperties,
2649 const PointerCoords* pointerCoords,
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002650 float xPrecision, float yPrecision, nsecs_t downTime) {
2651#if DEBUG_INBOUND_EVENT_DETAILS
Jeff Brown90655042010-12-02 13:50:46 -08002652 LOGD("notifyMotion - eventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, "
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002653 "action=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, edgeFlags=0x%x, "
Jeff Brown85a31762010-09-01 17:01:00 -07002654 "xPrecision=%f, yPrecision=%f, downTime=%lld",
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002655 eventTime, deviceId, source, policyFlags, action, flags,
2656 metaState, buttonState, edgeFlags,
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002657 xPrecision, yPrecision, downTime);
2658 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002659 LOGD(" Pointer %d: id=%d, toolType=%d, "
2660 "x=%f, y=%f, pressure=%f, size=%f, "
Jeff Brown85a31762010-09-01 17:01:00 -07002661 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
Jeff Brown8d608662010-08-30 03:02:23 -07002662 "orientation=%f",
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002663 i, pointerProperties[i].id,
2664 pointerProperties[i].toolType,
Jeff Brownebbd5d12011-02-17 13:01:34 -08002665 pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
2666 pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
2667 pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
2668 pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
2669 pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
2670 pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
2671 pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
2672 pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
2673 pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002674 }
2675#endif
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002676 if (! validateMotionEvent(action, pointerCount, pointerProperties)) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002677 return;
2678 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002679
Jeff Browne20c9e02010-10-11 14:20:19 -07002680 policyFlags |= POLICY_FLAG_TRUSTED;
Jeff Brown56194eb2011-03-02 19:23:13 -08002681 mPolicy->interceptMotionBeforeQueueing(eventTime, /*byref*/ policyFlags);
Jeff Brownb6997262010-10-08 22:31:17 -07002682
Jeff Brownb88102f2010-09-08 11:49:43 -07002683 bool needWake;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002684 { // acquire lock
Jeff Brown0029c662011-03-30 02:25:18 -07002685 mLock.lock();
2686
2687 if (mInputFilterEnabled) {
2688 mLock.unlock();
2689
2690 MotionEvent event;
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002691 event.initialize(deviceId, source, action, flags, edgeFlags, metaState,
2692 buttonState, 0, 0,
Jeff Brown0029c662011-03-30 02:25:18 -07002693 xPrecision, yPrecision, downTime, eventTime,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002694 pointerCount, pointerProperties, pointerCoords);
Jeff Brown0029c662011-03-30 02:25:18 -07002695
2696 policyFlags |= POLICY_FLAG_FILTERED;
2697 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2698 return; // event was consumed by the filter
2699 }
2700
2701 mLock.lock();
2702 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002703
2704 // Attempt batching and streaming of move events.
Jeff Browncc0c1592011-02-19 05:07:28 -08002705 if (action == AMOTION_EVENT_ACTION_MOVE
2706 || action == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002707 // BATCHING CASE
2708 //
2709 // Try to append a move sample to the tail of the inbound queue for this device.
2710 // Give up if we encounter a non-move motion event for this device since that
2711 // means we cannot append any new samples until a new motion event has started.
Jeff Brownac386072011-07-20 15:19:50 -07002712 for (EventEntry* entry = mInboundQueue.tail; entry; entry = entry->prev) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002713 if (entry->type != EventEntry::TYPE_MOTION) {
2714 // Keep looking for motion events.
2715 continue;
2716 }
2717
2718 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
Jeff Brownefd32662011-03-08 15:13:06 -08002719 if (motionEntry->deviceId != deviceId
2720 || motionEntry->source != source) {
2721 // Keep looking for this device and source.
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002722 continue;
2723 }
2724
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002725 if (!motionEntry->canAppendSamples(action, pointerCount, pointerProperties)) {
Jeff Brownefd32662011-03-08 15:13:06 -08002726 // Last motion event in the queue for this device and source is
2727 // not compatible for appending new samples. Stop here.
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002728 goto NoBatchingOrStreaming;
2729 }
2730
Jeff Brown9c3cda02010-06-15 01:31:58 -07002731 // Do the batching magic.
Jeff Brown4e91a182011-04-07 11:38:09 -07002732 batchMotionLocked(motionEntry, eventTime, metaState, pointerCoords,
2733 "most recent motion event for this device and source in the inbound queue");
Jeff Brown0029c662011-03-30 02:25:18 -07002734 mLock.unlock();
Jeff Brown9c3cda02010-06-15 01:31:58 -07002735 return; // done!
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002736 }
2737
Jeff Brownf6989da2011-04-06 17:19:48 -07002738 // BATCHING ONTO PENDING EVENT CASE
2739 //
2740 // Try to append a move sample to the currently pending event, if there is one.
2741 // We can do this as long as we are still waiting to find the targets for the
2742 // event. Once the targets are locked-in we can only do streaming.
2743 if (mPendingEvent
2744 && (!mPendingEvent->dispatchInProgress || !mCurrentInputTargetsValid)
2745 && mPendingEvent->type == EventEntry::TYPE_MOTION) {
2746 MotionEntry* motionEntry = static_cast<MotionEntry*>(mPendingEvent);
2747 if (motionEntry->deviceId == deviceId && motionEntry->source == source) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002748 if (!motionEntry->canAppendSamples(action, pointerCount, pointerProperties)) {
Jeff Brown4e91a182011-04-07 11:38:09 -07002749 // Pending motion event is for this device and source but it is
2750 // not compatible for appending new samples. Stop here.
Jeff Brownf6989da2011-04-06 17:19:48 -07002751 goto NoBatchingOrStreaming;
2752 }
2753
Jeff Brownf6989da2011-04-06 17:19:48 -07002754 // Do the batching magic.
Jeff Brown4e91a182011-04-07 11:38:09 -07002755 batchMotionLocked(motionEntry, eventTime, metaState, pointerCoords,
2756 "pending motion event");
Jeff Brownf6989da2011-04-06 17:19:48 -07002757 mLock.unlock();
2758 return; // done!
2759 }
2760 }
2761
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002762 // STREAMING CASE
2763 //
2764 // There is no pending motion event (of any kind) for this device in the inbound queue.
Jeff Brown519e0242010-09-15 15:18:56 -07002765 // Search the outbound queue for the current foreground targets to find a dispatched
2766 // motion event that is still in progress. If found, then, appen the new sample to
2767 // that event and push it out to all current targets. The logic in
2768 // prepareDispatchCycleLocked takes care of the case where some targets may
2769 // already have consumed the motion event by starting a new dispatch cycle if needed.
Jeff Brown9c3cda02010-06-15 01:31:58 -07002770 if (mCurrentInputTargetsValid) {
Jeff Brown519e0242010-09-15 15:18:56 -07002771 for (size_t i = 0; i < mCurrentInputTargets.size(); i++) {
2772 const InputTarget& inputTarget = mCurrentInputTargets[i];
2773 if ((inputTarget.flags & InputTarget::FLAG_FOREGROUND) == 0) {
2774 // Skip non-foreground targets. We only want to stream if there is at
2775 // least one foreground target whose dispatch is still in progress.
2776 continue;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002777 }
Jeff Brown519e0242010-09-15 15:18:56 -07002778
2779 ssize_t connectionIndex = getConnectionIndexLocked(inputTarget.inputChannel);
2780 if (connectionIndex < 0) {
2781 // Connection must no longer be valid.
2782 continue;
2783 }
2784
2785 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
2786 if (connection->outboundQueue.isEmpty()) {
2787 // This foreground target has an empty outbound queue.
2788 continue;
2789 }
2790
Jeff Brownac386072011-07-20 15:19:50 -07002791 DispatchEntry* dispatchEntry = connection->outboundQueue.head;
Jeff Brown519e0242010-09-15 15:18:56 -07002792 if (! dispatchEntry->inProgress
Jeff Brown01ce2e92010-09-26 22:20:12 -07002793 || dispatchEntry->eventEntry->type != EventEntry::TYPE_MOTION
2794 || dispatchEntry->isSplit()) {
2795 // No motion event is being dispatched, or it is being split across
2796 // windows in which case we cannot stream.
Jeff Brown519e0242010-09-15 15:18:56 -07002797 continue;
2798 }
2799
2800 MotionEntry* motionEntry = static_cast<MotionEntry*>(
2801 dispatchEntry->eventEntry);
Jeff Browncc0c1592011-02-19 05:07:28 -08002802 if (motionEntry->action != action
Jeff Brown519e0242010-09-15 15:18:56 -07002803 || motionEntry->deviceId != deviceId
Jeff Brown58a2da82011-01-25 16:02:22 -08002804 || motionEntry->source != source
Jeff Brown519e0242010-09-15 15:18:56 -07002805 || motionEntry->pointerCount != pointerCount
2806 || motionEntry->isInjected()) {
2807 // The motion event is not compatible with this move.
2808 continue;
2809 }
2810
Jeff Browna032cc02011-03-07 16:56:21 -08002811 if (action == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Jeff Brown9302c872011-07-13 22:51:29 -07002812 if (mLastHoverWindowHandle == NULL) {
Jeff Browna032cc02011-03-07 16:56:21 -08002813#if DEBUG_BATCHING
2814 LOGD("Not streaming hover move because there is no "
2815 "last hovered window.");
2816#endif
2817 goto NoBatchingOrStreaming;
2818 }
2819
Jeff Brown9302c872011-07-13 22:51:29 -07002820 sp<InputWindowHandle> hoverWindowHandle = findTouchedWindowAtLocked(
Jeff Browna032cc02011-03-07 16:56:21 -08002821 pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X),
2822 pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Jeff Brown9302c872011-07-13 22:51:29 -07002823 if (mLastHoverWindowHandle != hoverWindowHandle) {
Jeff Browna032cc02011-03-07 16:56:21 -08002824#if DEBUG_BATCHING
2825 LOGD("Not streaming hover move because the last hovered window "
2826 "is '%s' but the currently hovered window is '%s'.",
Jeff Brown9302c872011-07-13 22:51:29 -07002827 mLastHoverWindowHandle->name.string(),
2828 hoverWindowHandle != NULL
2829 ? hoverWindowHandle->name.string() : "<null>");
Jeff Browna032cc02011-03-07 16:56:21 -08002830#endif
2831 goto NoBatchingOrStreaming;
2832 }
2833 }
2834
Jeff Brown519e0242010-09-15 15:18:56 -07002835 // Hurray! This foreground target is currently dispatching a move event
2836 // that we can stream onto. Append the motion sample and resume dispatch.
Jeff Brownac386072011-07-20 15:19:50 -07002837 motionEntry->appendSample(eventTime, pointerCoords);
Jeff Brown519e0242010-09-15 15:18:56 -07002838#if DEBUG_BATCHING
2839 LOGD("Appended motion sample onto batch for most recently dispatched "
Jeff Brown4e91a182011-04-07 11:38:09 -07002840 "motion event for this device and source in the outbound queues. "
Jeff Brown519e0242010-09-15 15:18:56 -07002841 "Attempting to stream the motion sample.");
2842#endif
2843 nsecs_t currentTime = now();
2844 dispatchEventToCurrentInputTargetsLocked(currentTime, motionEntry,
2845 true /*resumeWithAppendedMotionSample*/);
2846
2847 runCommandsLockedInterruptible();
Jeff Brown0029c662011-03-30 02:25:18 -07002848 mLock.unlock();
Jeff Brown519e0242010-09-15 15:18:56 -07002849 return; // done!
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002850 }
2851 }
2852
2853NoBatchingOrStreaming:;
2854 }
2855
2856 // Just enqueue a new motion event.
Jeff Brownac386072011-07-20 15:19:50 -07002857 MotionEntry* newEntry = new MotionEntry(eventTime,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002858 deviceId, source, policyFlags, action, flags, metaState, buttonState, edgeFlags,
Jeff Brown7fbdc842010-06-17 20:52:56 -07002859 xPrecision, yPrecision, downTime,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002860 pointerCount, pointerProperties, pointerCoords);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002861
Jeff Brownb88102f2010-09-08 11:49:43 -07002862 needWake = enqueueInboundEventLocked(newEntry);
Jeff Brown0029c662011-03-30 02:25:18 -07002863 mLock.unlock();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002864 } // release lock
2865
Jeff Brownb88102f2010-09-08 11:49:43 -07002866 if (needWake) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002867 mLooper->wake();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002868 }
2869}
2870
Jeff Brown4e91a182011-04-07 11:38:09 -07002871void InputDispatcher::batchMotionLocked(MotionEntry* entry, nsecs_t eventTime,
2872 int32_t metaState, const PointerCoords* pointerCoords, const char* eventDescription) {
2873 // Combine meta states.
2874 entry->metaState |= metaState;
2875
2876 // Coalesce this sample if not enough time has elapsed since the last sample was
2877 // initially appended to the batch.
2878 MotionSample* lastSample = entry->lastSample;
2879 long interval = eventTime - lastSample->eventTimeBeforeCoalescing;
2880 if (interval <= MOTION_SAMPLE_COALESCE_INTERVAL) {
2881 uint32_t pointerCount = entry->pointerCount;
2882 for (uint32_t i = 0; i < pointerCount; i++) {
2883 lastSample->pointerCoords[i].copyFrom(pointerCoords[i]);
2884 }
2885 lastSample->eventTime = eventTime;
2886#if DEBUG_BATCHING
2887 LOGD("Coalesced motion into last sample of batch for %s, events were %0.3f ms apart",
2888 eventDescription, interval * 0.000001f);
2889#endif
2890 return;
2891 }
2892
2893 // Append the sample.
Jeff Brownac386072011-07-20 15:19:50 -07002894 entry->appendSample(eventTime, pointerCoords);
Jeff Brown4e91a182011-04-07 11:38:09 -07002895#if DEBUG_BATCHING
2896 LOGD("Appended motion sample onto batch for %s, events were %0.3f ms apart",
2897 eventDescription, interval * 0.000001f);
2898#endif
2899}
2900
Jeff Brownb6997262010-10-08 22:31:17 -07002901void InputDispatcher::notifySwitch(nsecs_t when, int32_t switchCode, int32_t switchValue,
2902 uint32_t policyFlags) {
2903#if DEBUG_INBOUND_EVENT_DETAILS
2904 LOGD("notifySwitch - switchCode=%d, switchValue=%d, policyFlags=0x%x",
2905 switchCode, switchValue, policyFlags);
2906#endif
2907
Jeff Browne20c9e02010-10-11 14:20:19 -07002908 policyFlags |= POLICY_FLAG_TRUSTED;
Jeff Brownb6997262010-10-08 22:31:17 -07002909 mPolicy->notifySwitch(when, switchCode, switchValue, policyFlags);
2910}
2911
Jeff Brown7fbdc842010-06-17 20:52:56 -07002912int32_t InputDispatcher::injectInputEvent(const InputEvent* event,
Jeff Brown0029c662011-03-30 02:25:18 -07002913 int32_t injectorPid, int32_t injectorUid, int32_t syncMode, int32_t timeoutMillis,
2914 uint32_t policyFlags) {
Jeff Brown7fbdc842010-06-17 20:52:56 -07002915#if DEBUG_INBOUND_EVENT_DETAILS
2916 LOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Jeff Brown0029c662011-03-30 02:25:18 -07002917 "syncMode=%d, timeoutMillis=%d, policyFlags=0x%08x",
2918 event->getType(), injectorPid, injectorUid, syncMode, timeoutMillis, policyFlags);
Jeff Brown7fbdc842010-06-17 20:52:56 -07002919#endif
2920
2921 nsecs_t endTime = now() + milliseconds_to_nanoseconds(timeoutMillis);
Jeff Browne20c9e02010-10-11 14:20:19 -07002922
Jeff Brown0029c662011-03-30 02:25:18 -07002923 policyFlags |= POLICY_FLAG_INJECTED;
Jeff Browne20c9e02010-10-11 14:20:19 -07002924 if (hasInjectionPermission(injectorPid, injectorUid)) {
2925 policyFlags |= POLICY_FLAG_TRUSTED;
2926 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07002927
Jeff Brownb6997262010-10-08 22:31:17 -07002928 EventEntry* injectedEntry;
2929 switch (event->getType()) {
2930 case AINPUT_EVENT_TYPE_KEY: {
2931 const KeyEvent* keyEvent = static_cast<const KeyEvent*>(event);
2932 int32_t action = keyEvent->getAction();
2933 if (! validateKeyEvent(action)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07002934 return INPUT_EVENT_INJECTION_FAILED;
2935 }
2936
Jeff Brownb6997262010-10-08 22:31:17 -07002937 int32_t flags = keyEvent->getFlags();
Jeff Brown1f245102010-11-18 20:53:46 -08002938 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
2939 policyFlags |= POLICY_FLAG_VIRTUAL;
2940 }
2941
Jeff Brown0029c662011-03-30 02:25:18 -07002942 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
2943 mPolicy->interceptKeyBeforeQueueing(keyEvent, /*byref*/ policyFlags);
2944 }
Jeff Brown1f245102010-11-18 20:53:46 -08002945
2946 if (policyFlags & POLICY_FLAG_WOKE_HERE) {
2947 flags |= AKEY_EVENT_FLAG_WOKE_HERE;
2948 }
Jeff Brown6ec402b2010-07-28 15:48:59 -07002949
Jeff Brownb6997262010-10-08 22:31:17 -07002950 mLock.lock();
Jeff Brownac386072011-07-20 15:19:50 -07002951 injectedEntry = new KeyEntry(keyEvent->getEventTime(),
Jeff Brown1f245102010-11-18 20:53:46 -08002952 keyEvent->getDeviceId(), keyEvent->getSource(),
2953 policyFlags, action, flags,
2954 keyEvent->getKeyCode(), keyEvent->getScanCode(), keyEvent->getMetaState(),
Jeff Brownb6997262010-10-08 22:31:17 -07002955 keyEvent->getRepeatCount(), keyEvent->getDownTime());
2956 break;
2957 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07002958
Jeff Brownb6997262010-10-08 22:31:17 -07002959 case AINPUT_EVENT_TYPE_MOTION: {
2960 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
2961 int32_t action = motionEvent->getAction();
2962 size_t pointerCount = motionEvent->getPointerCount();
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002963 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
2964 if (! validateMotionEvent(action, pointerCount, pointerProperties)) {
Jeff Brownb6997262010-10-08 22:31:17 -07002965 return INPUT_EVENT_INJECTION_FAILED;
2966 }
2967
Jeff Brown0029c662011-03-30 02:25:18 -07002968 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
2969 nsecs_t eventTime = motionEvent->getEventTime();
2970 mPolicy->interceptMotionBeforeQueueing(eventTime, /*byref*/ policyFlags);
2971 }
Jeff Brownb6997262010-10-08 22:31:17 -07002972
2973 mLock.lock();
2974 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
2975 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
Jeff Brownac386072011-07-20 15:19:50 -07002976 MotionEntry* motionEntry = new MotionEntry(*sampleEventTimes,
Jeff Brownb6997262010-10-08 22:31:17 -07002977 motionEvent->getDeviceId(), motionEvent->getSource(), policyFlags,
2978 action, motionEvent->getFlags(),
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002979 motionEvent->getMetaState(), motionEvent->getButtonState(),
2980 motionEvent->getEdgeFlags(),
Jeff Brownb6997262010-10-08 22:31:17 -07002981 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
2982 motionEvent->getDownTime(), uint32_t(pointerCount),
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002983 pointerProperties, samplePointerCoords);
Jeff Brownb6997262010-10-08 22:31:17 -07002984 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
2985 sampleEventTimes += 1;
2986 samplePointerCoords += pointerCount;
Jeff Brownac386072011-07-20 15:19:50 -07002987 motionEntry->appendSample(*sampleEventTimes, samplePointerCoords);
Jeff Brownb6997262010-10-08 22:31:17 -07002988 }
2989 injectedEntry = motionEntry;
2990 break;
2991 }
2992
2993 default:
2994 LOGW("Cannot inject event of type %d", event->getType());
2995 return INPUT_EVENT_INJECTION_FAILED;
2996 }
2997
Jeff Brownac386072011-07-20 15:19:50 -07002998 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
Jeff Brownb6997262010-10-08 22:31:17 -07002999 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
3000 injectionState->injectionIsAsync = true;
3001 }
3002
3003 injectionState->refCount += 1;
3004 injectedEntry->injectionState = injectionState;
3005
3006 bool needWake = enqueueInboundEventLocked(injectedEntry);
3007 mLock.unlock();
Jeff Brown7fbdc842010-06-17 20:52:56 -07003008
Jeff Brownb88102f2010-09-08 11:49:43 -07003009 if (needWake) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07003010 mLooper->wake();
Jeff Brown7fbdc842010-06-17 20:52:56 -07003011 }
3012
3013 int32_t injectionResult;
3014 { // acquire lock
3015 AutoMutex _l(mLock);
3016
Jeff Brown6ec402b2010-07-28 15:48:59 -07003017 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
3018 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
3019 } else {
3020 for (;;) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07003021 injectionResult = injectionState->injectionResult;
Jeff Brown6ec402b2010-07-28 15:48:59 -07003022 if (injectionResult != INPUT_EVENT_INJECTION_PENDING) {
3023 break;
3024 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07003025
Jeff Brown7fbdc842010-06-17 20:52:56 -07003026 nsecs_t remainingTimeout = endTime - now();
3027 if (remainingTimeout <= 0) {
Jeff Brown6ec402b2010-07-28 15:48:59 -07003028#if DEBUG_INJECTION
3029 LOGD("injectInputEvent - Timed out waiting for injection result "
3030 "to become available.");
3031#endif
Jeff Brown7fbdc842010-06-17 20:52:56 -07003032 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
3033 break;
3034 }
3035
Jeff Brown6ec402b2010-07-28 15:48:59 -07003036 mInjectionResultAvailableCondition.waitRelative(mLock, remainingTimeout);
3037 }
3038
3039 if (injectionResult == INPUT_EVENT_INJECTION_SUCCEEDED
3040 && syncMode == INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07003041 while (injectionState->pendingForegroundDispatches != 0) {
Jeff Brown6ec402b2010-07-28 15:48:59 -07003042#if DEBUG_INJECTION
Jeff Brown519e0242010-09-15 15:18:56 -07003043 LOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
Jeff Brown01ce2e92010-09-26 22:20:12 -07003044 injectionState->pendingForegroundDispatches);
Jeff Brown6ec402b2010-07-28 15:48:59 -07003045#endif
3046 nsecs_t remainingTimeout = endTime - now();
3047 if (remainingTimeout <= 0) {
3048#if DEBUG_INJECTION
Jeff Brown519e0242010-09-15 15:18:56 -07003049 LOGD("injectInputEvent - Timed out waiting for pending foreground "
Jeff Brown6ec402b2010-07-28 15:48:59 -07003050 "dispatches to finish.");
3051#endif
3052 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
3053 break;
3054 }
3055
3056 mInjectionSyncFinishedCondition.waitRelative(mLock, remainingTimeout);
3057 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07003058 }
3059 }
3060
Jeff Brownac386072011-07-20 15:19:50 -07003061 injectionState->release();
Jeff Brown7fbdc842010-06-17 20:52:56 -07003062 } // release lock
3063
Jeff Brown6ec402b2010-07-28 15:48:59 -07003064#if DEBUG_INJECTION
3065 LOGD("injectInputEvent - Finished with result %d. "
3066 "injectorPid=%d, injectorUid=%d",
3067 injectionResult, injectorPid, injectorUid);
3068#endif
3069
Jeff Brown7fbdc842010-06-17 20:52:56 -07003070 return injectionResult;
3071}
3072
Jeff Brownb6997262010-10-08 22:31:17 -07003073bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
3074 return injectorUid == 0
3075 || mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
3076}
3077
Jeff Brown7fbdc842010-06-17 20:52:56 -07003078void InputDispatcher::setInjectionResultLocked(EventEntry* entry, int32_t injectionResult) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07003079 InjectionState* injectionState = entry->injectionState;
3080 if (injectionState) {
Jeff Brown7fbdc842010-06-17 20:52:56 -07003081#if DEBUG_INJECTION
3082 LOGD("Setting input event injection result to %d. "
3083 "injectorPid=%d, injectorUid=%d",
Jeff Brown01ce2e92010-09-26 22:20:12 -07003084 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
Jeff Brown7fbdc842010-06-17 20:52:56 -07003085#endif
3086
Jeff Brown0029c662011-03-30 02:25:18 -07003087 if (injectionState->injectionIsAsync
3088 && !(entry->policyFlags & POLICY_FLAG_FILTERED)) {
Jeff Brown6ec402b2010-07-28 15:48:59 -07003089 // Log the outcome since the injector did not wait for the injection result.
3090 switch (injectionResult) {
3091 case INPUT_EVENT_INJECTION_SUCCEEDED:
3092 LOGV("Asynchronous input event injection succeeded.");
3093 break;
3094 case INPUT_EVENT_INJECTION_FAILED:
3095 LOGW("Asynchronous input event injection failed.");
3096 break;
3097 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
3098 LOGW("Asynchronous input event injection permission denied.");
3099 break;
3100 case INPUT_EVENT_INJECTION_TIMED_OUT:
3101 LOGW("Asynchronous input event injection timed out.");
3102 break;
3103 }
3104 }
3105
Jeff Brown01ce2e92010-09-26 22:20:12 -07003106 injectionState->injectionResult = injectionResult;
Jeff Brown7fbdc842010-06-17 20:52:56 -07003107 mInjectionResultAvailableCondition.broadcast();
3108 }
3109}
3110
Jeff Brown01ce2e92010-09-26 22:20:12 -07003111void InputDispatcher::incrementPendingForegroundDispatchesLocked(EventEntry* entry) {
3112 InjectionState* injectionState = entry->injectionState;
3113 if (injectionState) {
3114 injectionState->pendingForegroundDispatches += 1;
3115 }
3116}
3117
Jeff Brown519e0242010-09-15 15:18:56 -07003118void InputDispatcher::decrementPendingForegroundDispatchesLocked(EventEntry* entry) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07003119 InjectionState* injectionState = entry->injectionState;
3120 if (injectionState) {
3121 injectionState->pendingForegroundDispatches -= 1;
Jeff Brown6ec402b2010-07-28 15:48:59 -07003122
Jeff Brown01ce2e92010-09-26 22:20:12 -07003123 if (injectionState->pendingForegroundDispatches == 0) {
3124 mInjectionSyncFinishedCondition.broadcast();
3125 }
Jeff Brownb88102f2010-09-08 11:49:43 -07003126 }
3127}
3128
Jeff Brown9302c872011-07-13 22:51:29 -07003129sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
3130 const sp<InputChannel>& inputChannel) const {
3131 size_t numWindows = mWindowHandles.size();
3132 for (size_t i = 0; i < numWindows; i++) {
3133 const sp<InputWindowHandle>& windowHandle = mWindowHandles.itemAt(i);
3134 if (windowHandle->inputChannel == inputChannel) {
3135 return windowHandle;
Jeff Brown01ce2e92010-09-26 22:20:12 -07003136 }
3137 }
3138 return NULL;
3139}
3140
Jeff Brown9302c872011-07-13 22:51:29 -07003141bool InputDispatcher::hasWindowHandleLocked(
3142 const sp<InputWindowHandle>& windowHandle) const {
3143 size_t numWindows = mWindowHandles.size();
3144 for (size_t i = 0; i < numWindows; i++) {
3145 if (mWindowHandles.itemAt(i) == windowHandle) {
3146 return true;
3147 }
3148 }
3149 return false;
3150}
3151
3152void InputDispatcher::setInputWindows(const Vector<sp<InputWindowHandle> >& inputWindowHandles) {
Jeff Brownb88102f2010-09-08 11:49:43 -07003153#if DEBUG_FOCUS
3154 LOGD("setInputWindows");
3155#endif
3156 { // acquire lock
3157 AutoMutex _l(mLock);
3158
Jeff Brown9302c872011-07-13 22:51:29 -07003159 mWindowHandles = inputWindowHandles;
Jeff Brownb6997262010-10-08 22:31:17 -07003160
Jeff Brown9302c872011-07-13 22:51:29 -07003161 sp<InputWindowHandle> newFocusedWindowHandle;
3162 bool foundHoveredWindow = false;
3163 for (size_t i = 0; i < mWindowHandles.size(); i++) {
3164 const sp<InputWindowHandle>& windowHandle = mWindowHandles.itemAt(i);
3165 if (!windowHandle->update() || windowHandle->inputChannel == NULL) {
3166 mWindowHandles.removeAt(i--);
3167 continue;
3168 }
3169 if (windowHandle->hasFocus) {
3170 newFocusedWindowHandle = windowHandle;
3171 }
3172 if (windowHandle == mLastHoverWindowHandle) {
3173 foundHoveredWindow = true;
Jeff Brownb88102f2010-09-08 11:49:43 -07003174 }
3175 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07003176
Jeff Brown9302c872011-07-13 22:51:29 -07003177 if (!foundHoveredWindow) {
3178 mLastHoverWindowHandle = NULL;
3179 }
3180
3181 if (mFocusedWindowHandle != newFocusedWindowHandle) {
3182 if (mFocusedWindowHandle != NULL) {
Jeff Brownb6997262010-10-08 22:31:17 -07003183#if DEBUG_FOCUS
3184 LOGD("Focus left window: %s",
Jeff Brown9302c872011-07-13 22:51:29 -07003185 mFocusedWindowHandle->name.string());
Jeff Brownb6997262010-10-08 22:31:17 -07003186#endif
Jeff Brownda3d5a92011-03-29 15:11:34 -07003187 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
3188 "focus left window");
Jeff Brown9302c872011-07-13 22:51:29 -07003189 synthesizeCancelationEventsForInputChannelLocked(
3190 mFocusedWindowHandle->inputChannel, options);
Jeff Brownb6997262010-10-08 22:31:17 -07003191 }
Jeff Brown9302c872011-07-13 22:51:29 -07003192 if (newFocusedWindowHandle != NULL) {
Jeff Brownb6997262010-10-08 22:31:17 -07003193#if DEBUG_FOCUS
Jeff Brown9302c872011-07-13 22:51:29 -07003194 LOGD("Focus entered window: %s",
3195 newFocusedWindowHandle->name.string());
Jeff Brownb6997262010-10-08 22:31:17 -07003196#endif
Jeff Brown9302c872011-07-13 22:51:29 -07003197 }
3198 mFocusedWindowHandle = newFocusedWindowHandle;
Jeff Brownb6997262010-10-08 22:31:17 -07003199 }
3200
Jeff Brown9302c872011-07-13 22:51:29 -07003201 for (size_t i = 0; i < mTouchState.windows.size(); i++) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07003202 TouchedWindow& touchedWindow = mTouchState.windows.editItemAt(i);
Jeff Brown9302c872011-07-13 22:51:29 -07003203 if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
Jeff Brownb6997262010-10-08 22:31:17 -07003204#if DEBUG_FOCUS
Jeff Brown9302c872011-07-13 22:51:29 -07003205 LOGD("Touched window was removed: %s", touchedWindow.windowHandle->name.string());
Jeff Brownb6997262010-10-08 22:31:17 -07003206#endif
Jeff Brownda3d5a92011-03-29 15:11:34 -07003207 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
3208 "touched window was removed");
Jeff Brown9302c872011-07-13 22:51:29 -07003209 synthesizeCancelationEventsForInputChannelLocked(
3210 touchedWindow.windowHandle->inputChannel, options);
3211 mTouchState.windows.removeAt(i--);
Jeff Brown01ce2e92010-09-26 22:20:12 -07003212 }
3213 }
Jeff Brownb88102f2010-09-08 11:49:43 -07003214 } // release lock
3215
3216 // Wake up poll loop since it may need to make new input dispatching choices.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07003217 mLooper->wake();
Jeff Brownb88102f2010-09-08 11:49:43 -07003218}
3219
Jeff Brown9302c872011-07-13 22:51:29 -07003220void InputDispatcher::setFocusedApplication(
3221 const sp<InputApplicationHandle>& inputApplicationHandle) {
Jeff Brownb88102f2010-09-08 11:49:43 -07003222#if DEBUG_FOCUS
3223 LOGD("setFocusedApplication");
3224#endif
3225 { // acquire lock
3226 AutoMutex _l(mLock);
3227
Jeff Brown9302c872011-07-13 22:51:29 -07003228 if (inputApplicationHandle != NULL && inputApplicationHandle->update()) {
Jeff Brown5ea29ab2011-07-27 11:50:51 -07003229 if (mFocusedApplicationHandle != inputApplicationHandle) {
3230 if (mFocusedApplicationHandle != NULL) {
3231 resetTargetsLocked();
3232 }
3233 mFocusedApplicationHandle = inputApplicationHandle;
3234 }
3235 } else if (mFocusedApplicationHandle != NULL) {
3236 resetTargetsLocked();
Jeff Brown9302c872011-07-13 22:51:29 -07003237 mFocusedApplicationHandle.clear();
Jeff Brownb88102f2010-09-08 11:49:43 -07003238 }
3239
3240#if DEBUG_FOCUS
Jeff Brownb6997262010-10-08 22:31:17 -07003241 //logDispatchStateLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -07003242#endif
3243 } // release lock
3244
3245 // Wake up poll loop since it may need to make new input dispatching choices.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07003246 mLooper->wake();
Jeff Brownb88102f2010-09-08 11:49:43 -07003247}
3248
Jeff Brownb88102f2010-09-08 11:49:43 -07003249void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
3250#if DEBUG_FOCUS
3251 LOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
3252#endif
3253
3254 bool changed;
3255 { // acquire lock
3256 AutoMutex _l(mLock);
3257
3258 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
Jeff Brown120a4592010-10-27 18:43:51 -07003259 if (mDispatchFrozen && !frozen) {
Jeff Brownb88102f2010-09-08 11:49:43 -07003260 resetANRTimeoutsLocked();
3261 }
3262
Jeff Brown120a4592010-10-27 18:43:51 -07003263 if (mDispatchEnabled && !enabled) {
3264 resetAndDropEverythingLocked("dispatcher is being disabled");
3265 }
3266
Jeff Brownb88102f2010-09-08 11:49:43 -07003267 mDispatchEnabled = enabled;
3268 mDispatchFrozen = frozen;
3269 changed = true;
3270 } else {
3271 changed = false;
3272 }
3273
3274#if DEBUG_FOCUS
Jeff Brownb6997262010-10-08 22:31:17 -07003275 //logDispatchStateLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -07003276#endif
3277 } // release lock
3278
3279 if (changed) {
3280 // Wake up poll loop since it may need to make new input dispatching choices.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07003281 mLooper->wake();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003282 }
3283}
3284
Jeff Brown0029c662011-03-30 02:25:18 -07003285void InputDispatcher::setInputFilterEnabled(bool enabled) {
3286#if DEBUG_FOCUS
3287 LOGD("setInputFilterEnabled: enabled=%d", enabled);
3288#endif
3289
3290 { // acquire lock
3291 AutoMutex _l(mLock);
3292
3293 if (mInputFilterEnabled == enabled) {
3294 return;
3295 }
3296
3297 mInputFilterEnabled = enabled;
3298 resetAndDropEverythingLocked("input filter is being enabled or disabled");
3299 } // release lock
3300
3301 // Wake up poll loop since there might be work to do to drop everything.
3302 mLooper->wake();
3303}
3304
Jeff Browne6504122010-09-27 14:52:15 -07003305bool InputDispatcher::transferTouchFocus(const sp<InputChannel>& fromChannel,
3306 const sp<InputChannel>& toChannel) {
3307#if DEBUG_FOCUS
3308 LOGD("transferTouchFocus: fromChannel=%s, toChannel=%s",
3309 fromChannel->getName().string(), toChannel->getName().string());
3310#endif
3311 { // acquire lock
3312 AutoMutex _l(mLock);
3313
Jeff Brown9302c872011-07-13 22:51:29 -07003314 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromChannel);
3315 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toChannel);
3316 if (fromWindowHandle == NULL || toWindowHandle == NULL) {
Jeff Browne6504122010-09-27 14:52:15 -07003317#if DEBUG_FOCUS
3318 LOGD("Cannot transfer focus because from or to window not found.");
3319#endif
3320 return false;
3321 }
Jeff Brown9302c872011-07-13 22:51:29 -07003322 if (fromWindowHandle == toWindowHandle) {
Jeff Browne6504122010-09-27 14:52:15 -07003323#if DEBUG_FOCUS
3324 LOGD("Trivial transfer to same window.");
3325#endif
3326 return true;
3327 }
3328
3329 bool found = false;
3330 for (size_t i = 0; i < mTouchState.windows.size(); i++) {
3331 const TouchedWindow& touchedWindow = mTouchState.windows[i];
Jeff Brown9302c872011-07-13 22:51:29 -07003332 if (touchedWindow.windowHandle == fromWindowHandle) {
Jeff Browne6504122010-09-27 14:52:15 -07003333 int32_t oldTargetFlags = touchedWindow.targetFlags;
3334 BitSet32 pointerIds = touchedWindow.pointerIds;
3335
3336 mTouchState.windows.removeAt(i);
3337
Jeff Brown46e75292010-11-10 16:53:45 -08003338 int32_t newTargetFlags = oldTargetFlags
Jeff Browna032cc02011-03-07 16:56:21 -08003339 & (InputTarget::FLAG_FOREGROUND
3340 | InputTarget::FLAG_SPLIT | InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brown9302c872011-07-13 22:51:29 -07003341 mTouchState.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Jeff Browne6504122010-09-27 14:52:15 -07003342
3343 found = true;
3344 break;
3345 }
3346 }
3347
3348 if (! found) {
3349#if DEBUG_FOCUS
3350 LOGD("Focus transfer failed because from window did not have focus.");
3351#endif
3352 return false;
3353 }
3354
Jeff Brown9c9f1a32010-10-11 18:32:20 -07003355 ssize_t fromConnectionIndex = getConnectionIndexLocked(fromChannel);
3356 ssize_t toConnectionIndex = getConnectionIndexLocked(toChannel);
3357 if (fromConnectionIndex >= 0 && toConnectionIndex >= 0) {
3358 sp<Connection> fromConnection = mConnectionsByReceiveFd.valueAt(fromConnectionIndex);
3359 sp<Connection> toConnection = mConnectionsByReceiveFd.valueAt(toConnectionIndex);
3360
3361 fromConnection->inputState.copyPointerStateTo(toConnection->inputState);
Jeff Brownda3d5a92011-03-29 15:11:34 -07003362 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Jeff Brown9c9f1a32010-10-11 18:32:20 -07003363 "transferring touch focus from this window to another window");
Jeff Brownda3d5a92011-03-29 15:11:34 -07003364 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Jeff Brown9c9f1a32010-10-11 18:32:20 -07003365 }
3366
Jeff Browne6504122010-09-27 14:52:15 -07003367#if DEBUG_FOCUS
3368 logDispatchStateLocked();
3369#endif
3370 } // release lock
3371
3372 // Wake up poll loop since it may need to make new input dispatching choices.
3373 mLooper->wake();
3374 return true;
3375}
3376
Jeff Brown120a4592010-10-27 18:43:51 -07003377void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
3378#if DEBUG_FOCUS
3379 LOGD("Resetting and dropping all events (%s).", reason);
3380#endif
3381
Jeff Brownda3d5a92011-03-29 15:11:34 -07003382 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
3383 synthesizeCancelationEventsForAllConnectionsLocked(options);
Jeff Brown120a4592010-10-27 18:43:51 -07003384
3385 resetKeyRepeatLocked();
3386 releasePendingEventLocked();
3387 drainInboundQueueLocked();
3388 resetTargetsLocked();
3389
3390 mTouchState.reset();
Jeff Brown9302c872011-07-13 22:51:29 -07003391 mLastHoverWindowHandle.clear();
Jeff Brown120a4592010-10-27 18:43:51 -07003392}
3393
Jeff Brownb88102f2010-09-08 11:49:43 -07003394void InputDispatcher::logDispatchStateLocked() {
3395 String8 dump;
3396 dumpDispatchStateLocked(dump);
Jeff Brown2a95c2a2010-09-16 12:31:46 -07003397
3398 char* text = dump.lockBuffer(dump.size());
3399 char* start = text;
3400 while (*start != '\0') {
3401 char* end = strchr(start, '\n');
3402 if (*end == '\n') {
3403 *(end++) = '\0';
3404 }
3405 LOGD("%s", start);
3406 start = end;
3407 }
Jeff Brownb88102f2010-09-08 11:49:43 -07003408}
3409
3410void InputDispatcher::dumpDispatchStateLocked(String8& dump) {
Jeff Brownf2f487182010-10-01 17:46:21 -07003411 dump.appendFormat(INDENT "DispatchEnabled: %d\n", mDispatchEnabled);
3412 dump.appendFormat(INDENT "DispatchFrozen: %d\n", mDispatchFrozen);
Jeff Brownb88102f2010-09-08 11:49:43 -07003413
Jeff Brown9302c872011-07-13 22:51:29 -07003414 if (mFocusedApplicationHandle != NULL) {
Jeff Brownf2f487182010-10-01 17:46:21 -07003415 dump.appendFormat(INDENT "FocusedApplication: name='%s', dispatchingTimeout=%0.3fms\n",
Jeff Brown9302c872011-07-13 22:51:29 -07003416 mFocusedApplicationHandle->name.string(),
3417 mFocusedApplicationHandle->dispatchingTimeout / 1000000.0);
Jeff Brownb88102f2010-09-08 11:49:43 -07003418 } else {
Jeff Brownf2f487182010-10-01 17:46:21 -07003419 dump.append(INDENT "FocusedApplication: <null>\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003420 }
Jeff Brownf2f487182010-10-01 17:46:21 -07003421 dump.appendFormat(INDENT "FocusedWindow: name='%s'\n",
Jeff Brown9302c872011-07-13 22:51:29 -07003422 mFocusedWindowHandle != NULL ? mFocusedWindowHandle->name.string() : "<null>");
Jeff Brownf2f487182010-10-01 17:46:21 -07003423
3424 dump.appendFormat(INDENT "TouchDown: %s\n", toString(mTouchState.down));
3425 dump.appendFormat(INDENT "TouchSplit: %s\n", toString(mTouchState.split));
Jeff Brown95712852011-01-04 19:41:59 -08003426 dump.appendFormat(INDENT "TouchDeviceId: %d\n", mTouchState.deviceId);
Jeff Brown58a2da82011-01-25 16:02:22 -08003427 dump.appendFormat(INDENT "TouchSource: 0x%08x\n", mTouchState.source);
Jeff Brownf2f487182010-10-01 17:46:21 -07003428 if (!mTouchState.windows.isEmpty()) {
3429 dump.append(INDENT "TouchedWindows:\n");
3430 for (size_t i = 0; i < mTouchState.windows.size(); i++) {
3431 const TouchedWindow& touchedWindow = mTouchState.windows[i];
3432 dump.appendFormat(INDENT2 "%d: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
Jeff Brown9302c872011-07-13 22:51:29 -07003433 i, touchedWindow.windowHandle->name.string(), touchedWindow.pointerIds.value,
Jeff Brownf2f487182010-10-01 17:46:21 -07003434 touchedWindow.targetFlags);
3435 }
3436 } else {
3437 dump.append(INDENT "TouchedWindows: <none>\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003438 }
3439
Jeff Brown9302c872011-07-13 22:51:29 -07003440 if (!mWindowHandles.isEmpty()) {
Jeff Brownf2f487182010-10-01 17:46:21 -07003441 dump.append(INDENT "Windows:\n");
Jeff Brown9302c872011-07-13 22:51:29 -07003442 for (size_t i = 0; i < mWindowHandles.size(); i++) {
3443 const sp<InputWindowHandle>& windowHandle = mWindowHandles.itemAt(i);
Jeff Brownf2f487182010-10-01 17:46:21 -07003444 dump.appendFormat(INDENT2 "%d: name='%s', paused=%s, hasFocus=%s, hasWallpaper=%s, "
3445 "visible=%s, canReceiveKeys=%s, flags=0x%08x, type=0x%08x, layer=%d, "
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003446 "frame=[%d,%d][%d,%d], scale=%f, "
Jeff Brownfbf09772011-01-16 14:06:57 -08003447 "touchableRegion=",
Jeff Brown9302c872011-07-13 22:51:29 -07003448 i, windowHandle->name.string(),
3449 toString(windowHandle->paused),
3450 toString(windowHandle->hasFocus),
3451 toString(windowHandle->hasWallpaper),
3452 toString(windowHandle->visible),
3453 toString(windowHandle->canReceiveKeys),
3454 windowHandle->layoutParamsFlags, windowHandle->layoutParamsType,
3455 windowHandle->layer,
3456 windowHandle->frameLeft, windowHandle->frameTop,
3457 windowHandle->frameRight, windowHandle->frameBottom,
3458 windowHandle->scaleFactor);
3459 dumpRegion(dump, windowHandle->touchableRegion);
3460 dump.appendFormat(", inputFeatures=0x%08x", windowHandle->inputFeatures);
Jeff Brownfbf09772011-01-16 14:06:57 -08003461 dump.appendFormat(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%0.3fms\n",
Jeff Brown9302c872011-07-13 22:51:29 -07003462 windowHandle->ownerPid, windowHandle->ownerUid,
3463 windowHandle->dispatchingTimeout / 1000000.0);
Jeff Brownf2f487182010-10-01 17:46:21 -07003464 }
3465 } else {
3466 dump.append(INDENT "Windows: <none>\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003467 }
3468
Jeff Brownf2f487182010-10-01 17:46:21 -07003469 if (!mMonitoringChannels.isEmpty()) {
3470 dump.append(INDENT "MonitoringChannels:\n");
3471 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
3472 const sp<InputChannel>& channel = mMonitoringChannels[i];
3473 dump.appendFormat(INDENT2 "%d: '%s'\n", i, channel->getName().string());
3474 }
3475 } else {
3476 dump.append(INDENT "MonitoringChannels: <none>\n");
3477 }
Jeff Brown519e0242010-09-15 15:18:56 -07003478
Jeff Brownf2f487182010-10-01 17:46:21 -07003479 dump.appendFormat(INDENT "InboundQueue: length=%u\n", mInboundQueue.count());
3480
3481 if (!mActiveConnections.isEmpty()) {
3482 dump.append(INDENT "ActiveConnections:\n");
3483 for (size_t i = 0; i < mActiveConnections.size(); i++) {
3484 const Connection* connection = mActiveConnections[i];
Jeff Brown76860e32010-10-25 17:37:46 -07003485 dump.appendFormat(INDENT2 "%d: '%s', status=%s, outboundQueueLength=%u, "
Jeff Brownb6997262010-10-08 22:31:17 -07003486 "inputState.isNeutral=%s\n",
Jeff Brownf2f487182010-10-01 17:46:21 -07003487 i, connection->getInputChannelName(), connection->getStatusLabel(),
3488 connection->outboundQueue.count(),
Jeff Brownb6997262010-10-08 22:31:17 -07003489 toString(connection->inputState.isNeutral()));
Jeff Brownf2f487182010-10-01 17:46:21 -07003490 }
3491 } else {
3492 dump.append(INDENT "ActiveConnections: <none>\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003493 }
3494
3495 if (isAppSwitchPendingLocked()) {
Jeff Brownf2f487182010-10-01 17:46:21 -07003496 dump.appendFormat(INDENT "AppSwitch: pending, due in %01.1fms\n",
Jeff Brownb88102f2010-09-08 11:49:43 -07003497 (mAppSwitchDueTime - now()) / 1000000.0);
3498 } else {
Jeff Brownf2f487182010-10-01 17:46:21 -07003499 dump.append(INDENT "AppSwitch: not pending\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003500 }
3501}
3502
Jeff Brown928e0542011-01-10 11:17:36 -08003503status_t InputDispatcher::registerInputChannel(const sp<InputChannel>& inputChannel,
3504 const sp<InputWindowHandle>& inputWindowHandle, bool monitor) {
Jeff Brown9c3cda02010-06-15 01:31:58 -07003505#if DEBUG_REGISTRATION
Jeff Brownb88102f2010-09-08 11:49:43 -07003506 LOGD("channel '%s' ~ registerInputChannel - monitor=%s", inputChannel->getName().string(),
3507 toString(monitor));
Jeff Brown9c3cda02010-06-15 01:31:58 -07003508#endif
3509
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003510 { // acquire lock
3511 AutoMutex _l(mLock);
3512
Jeff Brown519e0242010-09-15 15:18:56 -07003513 if (getConnectionIndexLocked(inputChannel) >= 0) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003514 LOGW("Attempted to register already registered input channel '%s'",
3515 inputChannel->getName().string());
3516 return BAD_VALUE;
3517 }
3518
Jeff Brown928e0542011-01-10 11:17:36 -08003519 sp<Connection> connection = new Connection(inputChannel, inputWindowHandle);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003520 status_t status = connection->initialize();
3521 if (status) {
3522 LOGE("Failed to initialize input publisher for input channel '%s', status=%d",
3523 inputChannel->getName().string(), status);
3524 return status;
3525 }
3526
Jeff Brown2cbecea2010-08-17 15:59:26 -07003527 int32_t receiveFd = inputChannel->getReceivePipeFd();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003528 mConnectionsByReceiveFd.add(receiveFd, connection);
Jeff Brown9c3cda02010-06-15 01:31:58 -07003529
Jeff Brownb88102f2010-09-08 11:49:43 -07003530 if (monitor) {
3531 mMonitoringChannels.push(inputChannel);
3532 }
3533
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07003534 mLooper->addFd(receiveFd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
Jeff Brown2cbecea2010-08-17 15:59:26 -07003535
Jeff Brown9c3cda02010-06-15 01:31:58 -07003536 runCommandsLockedInterruptible();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003537 } // release lock
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003538 return OK;
3539}
3540
3541status_t InputDispatcher::unregisterInputChannel(const sp<InputChannel>& inputChannel) {
Jeff Brown9c3cda02010-06-15 01:31:58 -07003542#if DEBUG_REGISTRATION
Jeff Brown349703e2010-06-22 01:27:15 -07003543 LOGD("channel '%s' ~ unregisterInputChannel", inputChannel->getName().string());
Jeff Brown9c3cda02010-06-15 01:31:58 -07003544#endif
3545
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003546 { // acquire lock
3547 AutoMutex _l(mLock);
3548
Jeff Brown519e0242010-09-15 15:18:56 -07003549 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003550 if (connectionIndex < 0) {
3551 LOGW("Attempted to unregister already unregistered input channel '%s'",
3552 inputChannel->getName().string());
3553 return BAD_VALUE;
3554 }
3555
3556 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
3557 mConnectionsByReceiveFd.removeItemsAt(connectionIndex);
3558
3559 connection->status = Connection::STATUS_ZOMBIE;
3560
Jeff Brownb88102f2010-09-08 11:49:43 -07003561 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
3562 if (mMonitoringChannels[i] == inputChannel) {
3563 mMonitoringChannels.removeAt(i);
3564 break;
3565 }
3566 }
3567
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07003568 mLooper->removeFd(inputChannel->getReceivePipeFd());
Jeff Brown2cbecea2010-08-17 15:59:26 -07003569
Jeff Brown7fbdc842010-06-17 20:52:56 -07003570 nsecs_t currentTime = now();
Jeff Brownb6997262010-10-08 22:31:17 -07003571 abortBrokenDispatchCycleLocked(currentTime, connection);
Jeff Brown9c3cda02010-06-15 01:31:58 -07003572
3573 runCommandsLockedInterruptible();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003574 } // release lock
3575
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003576 // Wake the poll loop because removing the connection may have changed the current
3577 // synchronization state.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07003578 mLooper->wake();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003579 return OK;
3580}
3581
Jeff Brown519e0242010-09-15 15:18:56 -07003582ssize_t InputDispatcher::getConnectionIndexLocked(const sp<InputChannel>& inputChannel) {
Jeff Brown2cbecea2010-08-17 15:59:26 -07003583 ssize_t connectionIndex = mConnectionsByReceiveFd.indexOfKey(inputChannel->getReceivePipeFd());
3584 if (connectionIndex >= 0) {
3585 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
3586 if (connection->inputChannel.get() == inputChannel.get()) {
3587 return connectionIndex;
3588 }
3589 }
3590
3591 return -1;
3592}
3593
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003594void InputDispatcher::activateConnectionLocked(Connection* connection) {
3595 for (size_t i = 0; i < mActiveConnections.size(); i++) {
3596 if (mActiveConnections.itemAt(i) == connection) {
3597 return;
3598 }
3599 }
3600 mActiveConnections.add(connection);
3601}
3602
3603void InputDispatcher::deactivateConnectionLocked(Connection* connection) {
3604 for (size_t i = 0; i < mActiveConnections.size(); i++) {
3605 if (mActiveConnections.itemAt(i) == connection) {
3606 mActiveConnections.removeAt(i);
3607 return;
3608 }
3609 }
3610}
3611
Jeff Brown9c3cda02010-06-15 01:31:58 -07003612void InputDispatcher::onDispatchCycleStartedLocked(
Jeff Brown7fbdc842010-06-17 20:52:56 -07003613 nsecs_t currentTime, const sp<Connection>& connection) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003614}
3615
Jeff Brown9c3cda02010-06-15 01:31:58 -07003616void InputDispatcher::onDispatchCycleFinishedLocked(
Jeff Brown3915bb82010-11-05 15:02:16 -07003617 nsecs_t currentTime, const sp<Connection>& connection, bool handled) {
3618 CommandEntry* commandEntry = postCommandLocked(
3619 & InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
3620 commandEntry->connection = connection;
3621 commandEntry->handled = handled;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003622}
3623
Jeff Brown9c3cda02010-06-15 01:31:58 -07003624void InputDispatcher::onDispatchCycleBrokenLocked(
Jeff Brown7fbdc842010-06-17 20:52:56 -07003625 nsecs_t currentTime, const sp<Connection>& connection) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003626 LOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
3627 connection->getInputChannelName());
3628
Jeff Brown9c3cda02010-06-15 01:31:58 -07003629 CommandEntry* commandEntry = postCommandLocked(
3630 & InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
Jeff Brown7fbdc842010-06-17 20:52:56 -07003631 commandEntry->connection = connection;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003632}
3633
Jeff Brown519e0242010-09-15 15:18:56 -07003634void InputDispatcher::onANRLocked(
Jeff Brown9302c872011-07-13 22:51:29 -07003635 nsecs_t currentTime, const sp<InputApplicationHandle>& applicationHandle,
3636 const sp<InputWindowHandle>& windowHandle,
Jeff Brown519e0242010-09-15 15:18:56 -07003637 nsecs_t eventTime, nsecs_t waitStartTime) {
3638 LOGI("Application is not responding: %s. "
3639 "%01.1fms since event, %01.1fms since wait started",
Jeff Brown9302c872011-07-13 22:51:29 -07003640 getApplicationWindowLabelLocked(applicationHandle, windowHandle).string(),
Jeff Brown519e0242010-09-15 15:18:56 -07003641 (currentTime - eventTime) / 1000000.0,
3642 (currentTime - waitStartTime) / 1000000.0);
3643
3644 CommandEntry* commandEntry = postCommandLocked(
3645 & InputDispatcher::doNotifyANRLockedInterruptible);
Jeff Brown9302c872011-07-13 22:51:29 -07003646 commandEntry->inputApplicationHandle = applicationHandle;
3647 commandEntry->inputWindowHandle = windowHandle;
Jeff Brown519e0242010-09-15 15:18:56 -07003648}
3649
Jeff Brownb88102f2010-09-08 11:49:43 -07003650void InputDispatcher::doNotifyConfigurationChangedInterruptible(
3651 CommandEntry* commandEntry) {
3652 mLock.unlock();
3653
3654 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
3655
3656 mLock.lock();
3657}
3658
Jeff Brown9c3cda02010-06-15 01:31:58 -07003659void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(
3660 CommandEntry* commandEntry) {
Jeff Brown7fbdc842010-06-17 20:52:56 -07003661 sp<Connection> connection = commandEntry->connection;
Jeff Brown9c3cda02010-06-15 01:31:58 -07003662
Jeff Brown7fbdc842010-06-17 20:52:56 -07003663 if (connection->status != Connection::STATUS_ZOMBIE) {
3664 mLock.unlock();
Jeff Brown9c3cda02010-06-15 01:31:58 -07003665
Jeff Brown928e0542011-01-10 11:17:36 -08003666 mPolicy->notifyInputChannelBroken(connection->inputWindowHandle);
Jeff Brown7fbdc842010-06-17 20:52:56 -07003667
3668 mLock.lock();
3669 }
Jeff Brown9c3cda02010-06-15 01:31:58 -07003670}
3671
Jeff Brown519e0242010-09-15 15:18:56 -07003672void InputDispatcher::doNotifyANRLockedInterruptible(
Jeff Brown9c3cda02010-06-15 01:31:58 -07003673 CommandEntry* commandEntry) {
Jeff Brown519e0242010-09-15 15:18:56 -07003674 mLock.unlock();
Jeff Brown9c3cda02010-06-15 01:31:58 -07003675
Jeff Brown519e0242010-09-15 15:18:56 -07003676 nsecs_t newTimeout = mPolicy->notifyANR(
Jeff Brown928e0542011-01-10 11:17:36 -08003677 commandEntry->inputApplicationHandle, commandEntry->inputWindowHandle);
Jeff Brown9c3cda02010-06-15 01:31:58 -07003678
Jeff Brown519e0242010-09-15 15:18:56 -07003679 mLock.lock();
Jeff Brown7fbdc842010-06-17 20:52:56 -07003680
Jeff Brown9302c872011-07-13 22:51:29 -07003681 resumeAfterTargetsNotReadyTimeoutLocked(newTimeout,
3682 commandEntry->inputWindowHandle != NULL
3683 ? commandEntry->inputWindowHandle->inputChannel : NULL);
Jeff Brown9c3cda02010-06-15 01:31:58 -07003684}
3685
Jeff Brownb88102f2010-09-08 11:49:43 -07003686void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
3687 CommandEntry* commandEntry) {
3688 KeyEntry* entry = commandEntry->keyEntry;
Jeff Brown1f245102010-11-18 20:53:46 -08003689
3690 KeyEvent event;
3691 initializeKeyEvent(&event, entry);
Jeff Brownb88102f2010-09-08 11:49:43 -07003692
3693 mLock.unlock();
3694
Jeff Brown928e0542011-01-10 11:17:36 -08003695 bool consumed = mPolicy->interceptKeyBeforeDispatching(commandEntry->inputWindowHandle,
Jeff Brown1f245102010-11-18 20:53:46 -08003696 &event, entry->policyFlags);
Jeff Brownb88102f2010-09-08 11:49:43 -07003697
3698 mLock.lock();
3699
3700 entry->interceptKeyResult = consumed
3701 ? KeyEntry::INTERCEPT_KEY_RESULT_SKIP
3702 : KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
Jeff Brownac386072011-07-20 15:19:50 -07003703 entry->release();
Jeff Brownb88102f2010-09-08 11:49:43 -07003704}
3705
Jeff Brown3915bb82010-11-05 15:02:16 -07003706void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(
3707 CommandEntry* commandEntry) {
3708 sp<Connection> connection = commandEntry->connection;
3709 bool handled = commandEntry->handled;
3710
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003711 bool skipNext = false;
Jeff Brown49ed71d2010-12-06 17:13:33 -08003712 if (!connection->outboundQueue.isEmpty()) {
Jeff Brownac386072011-07-20 15:19:50 -07003713 DispatchEntry* dispatchEntry = connection->outboundQueue.head;
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003714 if (dispatchEntry->inProgress) {
3715 if (dispatchEntry->eventEntry->type == EventEntry::TYPE_KEY) {
3716 KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry);
3717 skipNext = afterKeyEventLockedInterruptible(connection,
3718 dispatchEntry, keyEntry, handled);
3719 } else if (dispatchEntry->eventEntry->type == EventEntry::TYPE_MOTION) {
3720 MotionEntry* motionEntry = static_cast<MotionEntry*>(dispatchEntry->eventEntry);
3721 skipNext = afterMotionEventLockedInterruptible(connection,
3722 dispatchEntry, motionEntry, handled);
Jeff Brown49ed71d2010-12-06 17:13:33 -08003723 }
Jeff Brown3915bb82010-11-05 15:02:16 -07003724 }
3725 }
3726
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003727 if (!skipNext) {
3728 startNextDispatchCycleLocked(now(), connection);
3729 }
3730}
3731
3732bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
3733 DispatchEntry* dispatchEntry, KeyEntry* keyEntry, bool handled) {
3734 if (!(keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK)) {
3735 // Get the fallback key state.
3736 // Clear it out after dispatching the UP.
3737 int32_t originalKeyCode = keyEntry->keyCode;
3738 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
3739 if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
3740 connection->inputState.removeFallbackKey(originalKeyCode);
3741 }
3742
3743 if (handled || !dispatchEntry->hasForegroundTarget()) {
3744 // If the application handles the original key for which we previously
3745 // generated a fallback or if the window is not a foreground window,
3746 // then cancel the associated fallback key, if any.
3747 if (fallbackKeyCode != -1) {
3748 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
3749 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
3750 "application handled the original non-fallback key "
3751 "or is no longer a foreground target, "
3752 "canceling previously dispatched fallback key");
3753 options.keyCode = fallbackKeyCode;
3754 synthesizeCancelationEventsForConnectionLocked(connection, options);
3755 }
3756 connection->inputState.removeFallbackKey(originalKeyCode);
3757 }
3758 } else {
3759 // If the application did not handle a non-fallback key, first check
3760 // that we are in a good state to perform unhandled key event processing
3761 // Then ask the policy what to do with it.
3762 bool initialDown = keyEntry->action == AKEY_EVENT_ACTION_DOWN
3763 && keyEntry->repeatCount == 0;
3764 if (fallbackKeyCode == -1 && !initialDown) {
3765#if DEBUG_OUTBOUND_EVENT_DETAILS
3766 LOGD("Unhandled key event: Skipping unhandled key event processing "
3767 "since this is not an initial down. "
3768 "keyCode=%d, action=%d, repeatCount=%d",
3769 originalKeyCode, keyEntry->action, keyEntry->repeatCount);
3770#endif
3771 return false;
3772 }
3773
3774 // Dispatch the unhandled key to the policy.
3775#if DEBUG_OUTBOUND_EVENT_DETAILS
3776 LOGD("Unhandled key event: Asking policy to perform fallback action. "
3777 "keyCode=%d, action=%d, repeatCount=%d",
3778 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount);
3779#endif
3780 KeyEvent event;
3781 initializeKeyEvent(&event, keyEntry);
3782
3783 mLock.unlock();
3784
3785 bool fallback = mPolicy->dispatchUnhandledKey(connection->inputWindowHandle,
3786 &event, keyEntry->policyFlags, &event);
3787
3788 mLock.lock();
3789
3790 if (connection->status != Connection::STATUS_NORMAL) {
3791 connection->inputState.removeFallbackKey(originalKeyCode);
3792 return true; // skip next cycle
3793 }
3794
Jeff Brownac386072011-07-20 15:19:50 -07003795 LOG_ASSERT(connection->outboundQueue.head == dispatchEntry);
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003796
3797 // Latch the fallback keycode for this key on an initial down.
3798 // The fallback keycode cannot change at any other point in the lifecycle.
3799 if (initialDown) {
3800 if (fallback) {
3801 fallbackKeyCode = event.getKeyCode();
3802 } else {
3803 fallbackKeyCode = AKEYCODE_UNKNOWN;
3804 }
3805 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
3806 }
3807
3808 LOG_ASSERT(fallbackKeyCode != -1);
3809
3810 // Cancel the fallback key if the policy decides not to send it anymore.
3811 // We will continue to dispatch the key to the policy but we will no
3812 // longer dispatch a fallback key to the application.
3813 if (fallbackKeyCode != AKEYCODE_UNKNOWN
3814 && (!fallback || fallbackKeyCode != event.getKeyCode())) {
3815#if DEBUG_OUTBOUND_EVENT_DETAILS
3816 if (fallback) {
3817 LOGD("Unhandled key event: Policy requested to send key %d"
3818 "as a fallback for %d, but on the DOWN it had requested "
3819 "to send %d instead. Fallback canceled.",
3820 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
3821 } else {
3822 LOGD("Unhandled key event: Policy did not request fallback for %d,"
3823 "but on the DOWN it had requested to send %d. "
3824 "Fallback canceled.",
3825 originalKeyCode, fallbackKeyCode);
3826 }
3827#endif
3828
3829 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
3830 "canceling fallback, policy no longer desires it");
3831 options.keyCode = fallbackKeyCode;
3832 synthesizeCancelationEventsForConnectionLocked(connection, options);
3833
3834 fallback = false;
3835 fallbackKeyCode = AKEYCODE_UNKNOWN;
3836 if (keyEntry->action != AKEY_EVENT_ACTION_UP) {
3837 connection->inputState.setFallbackKey(originalKeyCode,
3838 fallbackKeyCode);
3839 }
3840 }
3841
3842#if DEBUG_OUTBOUND_EVENT_DETAILS
3843 {
3844 String8 msg;
3845 const KeyedVector<int32_t, int32_t>& fallbackKeys =
3846 connection->inputState.getFallbackKeys();
3847 for (size_t i = 0; i < fallbackKeys.size(); i++) {
3848 msg.appendFormat(", %d->%d", fallbackKeys.keyAt(i),
3849 fallbackKeys.valueAt(i));
3850 }
3851 LOGD("Unhandled key event: %d currently tracked fallback keys%s.",
3852 fallbackKeys.size(), msg.string());
3853 }
3854#endif
3855
3856 if (fallback) {
3857 // Restart the dispatch cycle using the fallback key.
3858 keyEntry->eventTime = event.getEventTime();
3859 keyEntry->deviceId = event.getDeviceId();
3860 keyEntry->source = event.getSource();
3861 keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
3862 keyEntry->keyCode = fallbackKeyCode;
3863 keyEntry->scanCode = event.getScanCode();
3864 keyEntry->metaState = event.getMetaState();
3865 keyEntry->repeatCount = event.getRepeatCount();
3866 keyEntry->downTime = event.getDownTime();
3867 keyEntry->syntheticRepeat = false;
3868
3869#if DEBUG_OUTBOUND_EVENT_DETAILS
3870 LOGD("Unhandled key event: Dispatching fallback key. "
3871 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
3872 originalKeyCode, fallbackKeyCode, keyEntry->metaState);
3873#endif
3874
3875 dispatchEntry->inProgress = false;
3876 startDispatchCycleLocked(now(), connection);
3877 return true; // already started next cycle
3878 } else {
3879#if DEBUG_OUTBOUND_EVENT_DETAILS
3880 LOGD("Unhandled key event: No fallback key.");
3881#endif
3882 }
3883 }
3884 }
3885 return false;
3886}
3887
3888bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
3889 DispatchEntry* dispatchEntry, MotionEntry* motionEntry, bool handled) {
3890 return false;
Jeff Brown3915bb82010-11-05 15:02:16 -07003891}
3892
Jeff Brownb88102f2010-09-08 11:49:43 -07003893void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
3894 mLock.unlock();
3895
Jeff Brown01ce2e92010-09-26 22:20:12 -07003896 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
Jeff Brownb88102f2010-09-08 11:49:43 -07003897
3898 mLock.lock();
3899}
3900
Jeff Brown3915bb82010-11-05 15:02:16 -07003901void InputDispatcher::initializeKeyEvent(KeyEvent* event, const KeyEntry* entry) {
3902 event->initialize(entry->deviceId, entry->source, entry->action, entry->flags,
3903 entry->keyCode, entry->scanCode, entry->metaState, entry->repeatCount,
3904 entry->downTime, entry->eventTime);
3905}
3906
Jeff Brown519e0242010-09-15 15:18:56 -07003907void InputDispatcher::updateDispatchStatisticsLocked(nsecs_t currentTime, const EventEntry* entry,
3908 int32_t injectionResult, nsecs_t timeSpentWaitingForApplication) {
3909 // TODO Write some statistics about how long we spend waiting.
Jeff Brownb88102f2010-09-08 11:49:43 -07003910}
3911
3912void InputDispatcher::dump(String8& dump) {
Jeff Brownf2f487182010-10-01 17:46:21 -07003913 dump.append("Input Dispatcher State:\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003914 dumpDispatchStateLocked(dump);
Jeff Brown214eaf42011-05-26 19:17:02 -07003915
3916 dump.append(INDENT "Configuration:\n");
3917 dump.appendFormat(INDENT2 "MaxEventsPerSecond: %d\n", mConfig.maxEventsPerSecond);
3918 dump.appendFormat(INDENT2 "KeyRepeatDelay: %0.1fms\n", mConfig.keyRepeatDelay * 0.000001f);
3919 dump.appendFormat(INDENT2 "KeyRepeatTimeout: %0.1fms\n", mConfig.keyRepeatTimeout * 0.000001f);
Jeff Brownb88102f2010-09-08 11:49:43 -07003920}
3921
Jeff Brown9c3cda02010-06-15 01:31:58 -07003922
Jeff Brown519e0242010-09-15 15:18:56 -07003923// --- InputDispatcher::Queue ---
3924
3925template <typename T>
3926uint32_t InputDispatcher::Queue<T>::count() const {
3927 uint32_t result = 0;
Jeff Brownac386072011-07-20 15:19:50 -07003928 for (const T* entry = head; entry; entry = entry->next) {
Jeff Brown519e0242010-09-15 15:18:56 -07003929 result += 1;
3930 }
3931 return result;
3932}
3933
3934
Jeff Brownac386072011-07-20 15:19:50 -07003935// --- InputDispatcher::InjectionState ---
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003936
Jeff Brownac386072011-07-20 15:19:50 -07003937InputDispatcher::InjectionState::InjectionState(int32_t injectorPid, int32_t injectorUid) :
3938 refCount(1),
3939 injectorPid(injectorPid), injectorUid(injectorUid),
3940 injectionResult(INPUT_EVENT_INJECTION_PENDING), injectionIsAsync(false),
3941 pendingForegroundDispatches(0) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003942}
3943
Jeff Brownac386072011-07-20 15:19:50 -07003944InputDispatcher::InjectionState::~InjectionState() {
Jeff Brown01ce2e92010-09-26 22:20:12 -07003945}
3946
Jeff Brownac386072011-07-20 15:19:50 -07003947void InputDispatcher::InjectionState::release() {
3948 refCount -= 1;
3949 if (refCount == 0) {
3950 delete this;
3951 } else {
3952 LOG_ASSERT(refCount > 0);
Jeff Brown01ce2e92010-09-26 22:20:12 -07003953 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07003954}
3955
Jeff Brownac386072011-07-20 15:19:50 -07003956
3957// --- InputDispatcher::EventEntry ---
3958
3959InputDispatcher::EventEntry::EventEntry(int32_t type, nsecs_t eventTime, uint32_t policyFlags) :
3960 refCount(1), type(type), eventTime(eventTime), policyFlags(policyFlags),
3961 injectionState(NULL), dispatchInProgress(false) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003962}
3963
Jeff Brownac386072011-07-20 15:19:50 -07003964InputDispatcher::EventEntry::~EventEntry() {
3965 releaseInjectionState();
3966}
3967
3968void InputDispatcher::EventEntry::release() {
3969 refCount -= 1;
3970 if (refCount == 0) {
3971 delete this;
3972 } else {
3973 LOG_ASSERT(refCount > 0);
3974 }
3975}
3976
3977void InputDispatcher::EventEntry::releaseInjectionState() {
3978 if (injectionState) {
3979 injectionState->release();
3980 injectionState = NULL;
3981 }
3982}
3983
3984
3985// --- InputDispatcher::ConfigurationChangedEntry ---
3986
3987InputDispatcher::ConfigurationChangedEntry::ConfigurationChangedEntry(nsecs_t eventTime) :
3988 EventEntry(TYPE_CONFIGURATION_CHANGED, eventTime, 0) {
3989}
3990
3991InputDispatcher::ConfigurationChangedEntry::~ConfigurationChangedEntry() {
3992}
3993
3994
3995// --- InputDispatcher::KeyEntry ---
3996
3997InputDispatcher::KeyEntry::KeyEntry(nsecs_t eventTime,
Jeff Brown58a2da82011-01-25 16:02:22 -08003998 int32_t deviceId, uint32_t source, uint32_t policyFlags, int32_t action,
Jeff Brown7fbdc842010-06-17 20:52:56 -07003999 int32_t flags, int32_t keyCode, int32_t scanCode, int32_t metaState,
Jeff Brownac386072011-07-20 15:19:50 -07004000 int32_t repeatCount, nsecs_t downTime) :
4001 EventEntry(TYPE_KEY, eventTime, policyFlags),
4002 deviceId(deviceId), source(source), action(action), flags(flags),
4003 keyCode(keyCode), scanCode(scanCode), metaState(metaState),
4004 repeatCount(repeatCount), downTime(downTime),
4005 syntheticRepeat(false), interceptKeyResult(KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004006}
4007
Jeff Brownac386072011-07-20 15:19:50 -07004008InputDispatcher::KeyEntry::~KeyEntry() {
4009}
Jeff Brown7fbdc842010-06-17 20:52:56 -07004010
Jeff Brownac386072011-07-20 15:19:50 -07004011void InputDispatcher::KeyEntry::recycle() {
4012 releaseInjectionState();
4013
4014 dispatchInProgress = false;
4015 syntheticRepeat = false;
4016 interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
4017}
4018
4019
4020// --- InputDispatcher::MotionSample ---
4021
4022InputDispatcher::MotionSample::MotionSample(nsecs_t eventTime,
4023 const PointerCoords* pointerCoords, uint32_t pointerCount) :
4024 next(NULL), eventTime(eventTime), eventTimeBeforeCoalescing(eventTime) {
Jeff Brown7fbdc842010-06-17 20:52:56 -07004025 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brownac386072011-07-20 15:19:50 -07004026 this->pointerCoords[i].copyFrom(pointerCoords[i]);
Jeff Brown7fbdc842010-06-17 20:52:56 -07004027 }
Jeff Brownb88102f2010-09-08 11:49:43 -07004028}
4029
4030
Jeff Brownae9fc032010-08-18 15:51:08 -07004031// --- InputDispatcher::MotionEntry ---
4032
Jeff Brownac386072011-07-20 15:19:50 -07004033InputDispatcher::MotionEntry::MotionEntry(nsecs_t eventTime,
4034 int32_t deviceId, uint32_t source, uint32_t policyFlags, int32_t action, int32_t flags,
4035 int32_t metaState, int32_t buttonState,
4036 int32_t edgeFlags, float xPrecision, float yPrecision,
4037 nsecs_t downTime, uint32_t pointerCount,
4038 const PointerProperties* pointerProperties, const PointerCoords* pointerCoords) :
4039 EventEntry(TYPE_MOTION, eventTime, policyFlags),
4040 deviceId(deviceId), source(source), action(action), flags(flags),
4041 metaState(metaState), buttonState(buttonState), edgeFlags(edgeFlags),
4042 xPrecision(xPrecision), yPrecision(yPrecision),
4043 downTime(downTime), pointerCount(pointerCount),
4044 firstSample(eventTime, pointerCoords, pointerCount),
4045 lastSample(&firstSample) {
4046 for (uint32_t i = 0; i < pointerCount; i++) {
4047 this->pointerProperties[i].copyFrom(pointerProperties[i]);
4048 }
4049}
4050
4051InputDispatcher::MotionEntry::~MotionEntry() {
4052 for (MotionSample* sample = firstSample.next; sample != NULL; ) {
4053 MotionSample* next = sample->next;
4054 delete sample;
4055 sample = next;
4056 }
4057}
4058
Jeff Brownae9fc032010-08-18 15:51:08 -07004059uint32_t InputDispatcher::MotionEntry::countSamples() const {
4060 uint32_t count = 1;
4061 for (MotionSample* sample = firstSample.next; sample != NULL; sample = sample->next) {
4062 count += 1;
4063 }
4064 return count;
4065}
4066
Jeff Brown4e91a182011-04-07 11:38:09 -07004067bool InputDispatcher::MotionEntry::canAppendSamples(int32_t action, uint32_t pointerCount,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07004068 const PointerProperties* pointerProperties) const {
Jeff Brown4e91a182011-04-07 11:38:09 -07004069 if (this->action != action
4070 || this->pointerCount != pointerCount
4071 || this->isInjected()) {
4072 return false;
4073 }
4074 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07004075 if (this->pointerProperties[i] != pointerProperties[i]) {
Jeff Brown4e91a182011-04-07 11:38:09 -07004076 return false;
4077 }
4078 }
4079 return true;
4080}
4081
Jeff Brownac386072011-07-20 15:19:50 -07004082void InputDispatcher::MotionEntry::appendSample(
4083 nsecs_t eventTime, const PointerCoords* pointerCoords) {
4084 MotionSample* sample = new MotionSample(eventTime, pointerCoords, pointerCount);
4085
4086 lastSample->next = sample;
4087 lastSample = sample;
4088}
4089
4090
4091// --- InputDispatcher::DispatchEntry ---
4092
4093InputDispatcher::DispatchEntry::DispatchEntry(EventEntry* eventEntry,
4094 int32_t targetFlags, float xOffset, float yOffset, float scaleFactor) :
4095 eventEntry(eventEntry), targetFlags(targetFlags),
4096 xOffset(xOffset), yOffset(yOffset), scaleFactor(scaleFactor),
4097 inProgress(false),
4098 resolvedAction(0), resolvedFlags(0),
4099 headMotionSample(NULL), tailMotionSample(NULL) {
4100 eventEntry->refCount += 1;
4101}
4102
4103InputDispatcher::DispatchEntry::~DispatchEntry() {
4104 eventEntry->release();
4105}
4106
Jeff Brownb88102f2010-09-08 11:49:43 -07004107
4108// --- InputDispatcher::InputState ---
4109
Jeff Brownb6997262010-10-08 22:31:17 -07004110InputDispatcher::InputState::InputState() {
Jeff Brownb88102f2010-09-08 11:49:43 -07004111}
4112
4113InputDispatcher::InputState::~InputState() {
4114}
4115
4116bool InputDispatcher::InputState::isNeutral() const {
4117 return mKeyMementos.isEmpty() && mMotionMementos.isEmpty();
4118}
4119
Jeff Brown81346812011-06-28 20:08:48 -07004120bool InputDispatcher::InputState::isHovering(int32_t deviceId, uint32_t source) const {
4121 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4122 const MotionMemento& memento = mMotionMementos.itemAt(i);
4123 if (memento.deviceId == deviceId
4124 && memento.source == source
4125 && memento.hovering) {
4126 return true;
4127 }
4128 }
4129 return false;
4130}
Jeff Brownb88102f2010-09-08 11:49:43 -07004131
Jeff Brown81346812011-06-28 20:08:48 -07004132bool InputDispatcher::InputState::trackKey(const KeyEntry* entry,
4133 int32_t action, int32_t flags) {
4134 switch (action) {
4135 case AKEY_EVENT_ACTION_UP: {
4136 if (entry->flags & AKEY_EVENT_FLAG_FALLBACK) {
4137 for (size_t i = 0; i < mFallbackKeys.size(); ) {
4138 if (mFallbackKeys.valueAt(i) == entry->keyCode) {
4139 mFallbackKeys.removeItemsAt(i);
4140 } else {
4141 i += 1;
4142 }
4143 }
4144 }
4145 ssize_t index = findKeyMemento(entry);
4146 if (index >= 0) {
4147 mKeyMementos.removeAt(index);
4148 return true;
4149 }
4150#if DEBUG_OUTBOUND_EVENT_DETAILS
4151 LOGD("Dropping inconsistent key up event: deviceId=%d, source=%08x, "
4152 "keyCode=%d, scanCode=%d",
4153 entry->deviceId, entry->source, entry->keyCode, entry->scanCode);
4154#endif
4155 return false;
4156 }
4157
4158 case AKEY_EVENT_ACTION_DOWN: {
4159 ssize_t index = findKeyMemento(entry);
4160 if (index >= 0) {
4161 mKeyMementos.removeAt(index);
4162 }
4163 addKeyMemento(entry, flags);
4164 return true;
4165 }
4166
4167 default:
4168 return true;
Jeff Brownb88102f2010-09-08 11:49:43 -07004169 }
4170}
4171
Jeff Brown81346812011-06-28 20:08:48 -07004172bool InputDispatcher::InputState::trackMotion(const MotionEntry* entry,
4173 int32_t action, int32_t flags) {
4174 int32_t actionMasked = action & AMOTION_EVENT_ACTION_MASK;
4175 switch (actionMasked) {
4176 case AMOTION_EVENT_ACTION_UP:
4177 case AMOTION_EVENT_ACTION_CANCEL: {
4178 ssize_t index = findMotionMemento(entry, false /*hovering*/);
4179 if (index >= 0) {
4180 mMotionMementos.removeAt(index);
4181 return true;
Jeff Brownda3d5a92011-03-29 15:11:34 -07004182 }
Jeff Brown81346812011-06-28 20:08:48 -07004183#if DEBUG_OUTBOUND_EVENT_DETAILS
4184 LOGD("Dropping inconsistent motion up or cancel event: deviceId=%d, source=%08x, "
4185 "actionMasked=%d",
4186 entry->deviceId, entry->source, actionMasked);
4187#endif
4188 return false;
Jeff Brownda3d5a92011-03-29 15:11:34 -07004189 }
4190
Jeff Brown81346812011-06-28 20:08:48 -07004191 case AMOTION_EVENT_ACTION_DOWN: {
4192 ssize_t index = findMotionMemento(entry, false /*hovering*/);
4193 if (index >= 0) {
4194 mMotionMementos.removeAt(index);
4195 }
4196 addMotionMemento(entry, flags, false /*hovering*/);
4197 return true;
4198 }
4199
4200 case AMOTION_EVENT_ACTION_POINTER_UP:
4201 case AMOTION_EVENT_ACTION_POINTER_DOWN:
4202 case AMOTION_EVENT_ACTION_MOVE: {
4203 ssize_t index = findMotionMemento(entry, false /*hovering*/);
4204 if (index >= 0) {
4205 MotionMemento& memento = mMotionMementos.editItemAt(index);
4206 memento.setPointers(entry);
4207 return true;
4208 }
Jeff Brown2e45fb62011-06-29 21:19:05 -07004209 if (actionMasked == AMOTION_EVENT_ACTION_MOVE
4210 && (entry->source & (AINPUT_SOURCE_CLASS_JOYSTICK
4211 | AINPUT_SOURCE_CLASS_NAVIGATION))) {
4212 // Joysticks and trackballs can send MOVE events without corresponding DOWN or UP.
4213 return true;
4214 }
Jeff Brown81346812011-06-28 20:08:48 -07004215#if DEBUG_OUTBOUND_EVENT_DETAILS
4216 LOGD("Dropping inconsistent motion pointer up/down or move event: "
4217 "deviceId=%d, source=%08x, actionMasked=%d",
4218 entry->deviceId, entry->source, actionMasked);
4219#endif
4220 return false;
4221 }
4222
4223 case AMOTION_EVENT_ACTION_HOVER_EXIT: {
4224 ssize_t index = findMotionMemento(entry, true /*hovering*/);
4225 if (index >= 0) {
4226 mMotionMementos.removeAt(index);
4227 return true;
4228 }
4229#if DEBUG_OUTBOUND_EVENT_DETAILS
4230 LOGD("Dropping inconsistent motion hover exit event: deviceId=%d, source=%08x",
4231 entry->deviceId, entry->source);
4232#endif
4233 return false;
4234 }
4235
4236 case AMOTION_EVENT_ACTION_HOVER_ENTER:
4237 case AMOTION_EVENT_ACTION_HOVER_MOVE: {
4238 ssize_t index = findMotionMemento(entry, true /*hovering*/);
4239 if (index >= 0) {
4240 mMotionMementos.removeAt(index);
4241 }
4242 addMotionMemento(entry, flags, true /*hovering*/);
4243 return true;
4244 }
4245
4246 default:
4247 return true;
4248 }
4249}
4250
4251ssize_t InputDispatcher::InputState::findKeyMemento(const KeyEntry* entry) const {
Jeff Brownb88102f2010-09-08 11:49:43 -07004252 for (size_t i = 0; i < mKeyMementos.size(); i++) {
Jeff Brown81346812011-06-28 20:08:48 -07004253 const KeyMemento& memento = mKeyMementos.itemAt(i);
Jeff Brownb88102f2010-09-08 11:49:43 -07004254 if (memento.deviceId == entry->deviceId
4255 && memento.source == entry->source
4256 && memento.keyCode == entry->keyCode
4257 && memento.scanCode == entry->scanCode) {
Jeff Brown81346812011-06-28 20:08:48 -07004258 return i;
Jeff Brownb88102f2010-09-08 11:49:43 -07004259 }
4260 }
Jeff Brown81346812011-06-28 20:08:48 -07004261 return -1;
Jeff Brownb88102f2010-09-08 11:49:43 -07004262}
4263
Jeff Brown81346812011-06-28 20:08:48 -07004264ssize_t InputDispatcher::InputState::findMotionMemento(const MotionEntry* entry,
4265 bool hovering) const {
Jeff Brownb88102f2010-09-08 11:49:43 -07004266 for (size_t i = 0; i < mMotionMementos.size(); i++) {
Jeff Brown81346812011-06-28 20:08:48 -07004267 const MotionMemento& memento = mMotionMementos.itemAt(i);
Jeff Brownb88102f2010-09-08 11:49:43 -07004268 if (memento.deviceId == entry->deviceId
Jeff Brown81346812011-06-28 20:08:48 -07004269 && memento.source == entry->source
4270 && memento.hovering == hovering) {
4271 return i;
Jeff Brownb88102f2010-09-08 11:49:43 -07004272 }
4273 }
Jeff Brown81346812011-06-28 20:08:48 -07004274 return -1;
4275}
Jeff Brownb88102f2010-09-08 11:49:43 -07004276
Jeff Brown81346812011-06-28 20:08:48 -07004277void InputDispatcher::InputState::addKeyMemento(const KeyEntry* entry, int32_t flags) {
4278 mKeyMementos.push();
4279 KeyMemento& memento = mKeyMementos.editTop();
4280 memento.deviceId = entry->deviceId;
4281 memento.source = entry->source;
4282 memento.keyCode = entry->keyCode;
4283 memento.scanCode = entry->scanCode;
4284 memento.flags = flags;
4285 memento.downTime = entry->downTime;
4286}
4287
4288void InputDispatcher::InputState::addMotionMemento(const MotionEntry* entry,
4289 int32_t flags, bool hovering) {
4290 mMotionMementos.push();
4291 MotionMemento& memento = mMotionMementos.editTop();
4292 memento.deviceId = entry->deviceId;
4293 memento.source = entry->source;
4294 memento.flags = flags;
4295 memento.xPrecision = entry->xPrecision;
4296 memento.yPrecision = entry->yPrecision;
4297 memento.downTime = entry->downTime;
4298 memento.setPointers(entry);
4299 memento.hovering = hovering;
Jeff Brownb88102f2010-09-08 11:49:43 -07004300}
4301
4302void InputDispatcher::InputState::MotionMemento::setPointers(const MotionEntry* entry) {
4303 pointerCount = entry->pointerCount;
4304 for (uint32_t i = 0; i < entry->pointerCount; i++) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07004305 pointerProperties[i].copyFrom(entry->pointerProperties[i]);
Jeff Brownace13b12011-03-09 17:39:48 -08004306 pointerCoords[i].copyFrom(entry->lastSample->pointerCoords[i]);
Jeff Brownb88102f2010-09-08 11:49:43 -07004307 }
4308}
4309
Jeff Brownb6997262010-10-08 22:31:17 -07004310void InputDispatcher::InputState::synthesizeCancelationEvents(nsecs_t currentTime,
Jeff Brownac386072011-07-20 15:19:50 -07004311 Vector<EventEntry*>& outEvents, const CancelationOptions& options) {
Jeff Brown81346812011-06-28 20:08:48 -07004312 for (size_t i = 0; i < mKeyMementos.size(); i++) {
Jeff Brownb88102f2010-09-08 11:49:43 -07004313 const KeyMemento& memento = mKeyMementos.itemAt(i);
Jeff Brown49ed71d2010-12-06 17:13:33 -08004314 if (shouldCancelKey(memento, options)) {
Jeff Brownac386072011-07-20 15:19:50 -07004315 outEvents.push(new KeyEntry(currentTime,
Jeff Brownb6997262010-10-08 22:31:17 -07004316 memento.deviceId, memento.source, 0,
Jeff Brown49ed71d2010-12-06 17:13:33 -08004317 AKEY_EVENT_ACTION_UP, memento.flags | AKEY_EVENT_FLAG_CANCELED,
Jeff Brownb6997262010-10-08 22:31:17 -07004318 memento.keyCode, memento.scanCode, 0, 0, memento.downTime));
Jeff Brownb6997262010-10-08 22:31:17 -07004319 }
Jeff Brownb88102f2010-09-08 11:49:43 -07004320 }
4321
Jeff Brown81346812011-06-28 20:08:48 -07004322 for (size_t i = 0; i < mMotionMementos.size(); i++) {
Jeff Brownb88102f2010-09-08 11:49:43 -07004323 const MotionMemento& memento = mMotionMementos.itemAt(i);
Jeff Brown49ed71d2010-12-06 17:13:33 -08004324 if (shouldCancelMotion(memento, options)) {
Jeff Brownac386072011-07-20 15:19:50 -07004325 outEvents.push(new MotionEntry(currentTime,
Jeff Brownb6997262010-10-08 22:31:17 -07004326 memento.deviceId, memento.source, 0,
Jeff Browna032cc02011-03-07 16:56:21 -08004327 memento.hovering
4328 ? AMOTION_EVENT_ACTION_HOVER_EXIT
4329 : AMOTION_EVENT_ACTION_CANCEL,
Jeff Brown81346812011-06-28 20:08:48 -07004330 memento.flags, 0, 0, 0,
Jeff Brownb6997262010-10-08 22:31:17 -07004331 memento.xPrecision, memento.yPrecision, memento.downTime,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07004332 memento.pointerCount, memento.pointerProperties, memento.pointerCoords));
Jeff Brownb6997262010-10-08 22:31:17 -07004333 }
Jeff Brownb88102f2010-09-08 11:49:43 -07004334 }
4335}
4336
4337void InputDispatcher::InputState::clear() {
4338 mKeyMementos.clear();
4339 mMotionMementos.clear();
Jeff Brownda3d5a92011-03-29 15:11:34 -07004340 mFallbackKeys.clear();
Jeff Brownb6997262010-10-08 22:31:17 -07004341}
4342
Jeff Brown9c9f1a32010-10-11 18:32:20 -07004343void InputDispatcher::InputState::copyPointerStateTo(InputState& other) const {
4344 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4345 const MotionMemento& memento = mMotionMementos.itemAt(i);
4346 if (memento.source & AINPUT_SOURCE_CLASS_POINTER) {
4347 for (size_t j = 0; j < other.mMotionMementos.size(); ) {
4348 const MotionMemento& otherMemento = other.mMotionMementos.itemAt(j);
4349 if (memento.deviceId == otherMemento.deviceId
4350 && memento.source == otherMemento.source) {
4351 other.mMotionMementos.removeAt(j);
4352 } else {
4353 j += 1;
4354 }
4355 }
4356 other.mMotionMementos.push(memento);
4357 }
4358 }
4359}
4360
Jeff Brownda3d5a92011-03-29 15:11:34 -07004361int32_t InputDispatcher::InputState::getFallbackKey(int32_t originalKeyCode) {
4362 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
4363 return index >= 0 ? mFallbackKeys.valueAt(index) : -1;
4364}
4365
4366void InputDispatcher::InputState::setFallbackKey(int32_t originalKeyCode,
4367 int32_t fallbackKeyCode) {
4368 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
4369 if (index >= 0) {
4370 mFallbackKeys.replaceValueAt(index, fallbackKeyCode);
4371 } else {
4372 mFallbackKeys.add(originalKeyCode, fallbackKeyCode);
4373 }
4374}
4375
4376void InputDispatcher::InputState::removeFallbackKey(int32_t originalKeyCode) {
4377 mFallbackKeys.removeItem(originalKeyCode);
4378}
4379
Jeff Brown49ed71d2010-12-06 17:13:33 -08004380bool InputDispatcher::InputState::shouldCancelKey(const KeyMemento& memento,
Jeff Brownda3d5a92011-03-29 15:11:34 -07004381 const CancelationOptions& options) {
4382 if (options.keyCode != -1 && memento.keyCode != options.keyCode) {
4383 return false;
4384 }
4385
4386 switch (options.mode) {
4387 case CancelationOptions::CANCEL_ALL_EVENTS:
4388 case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
Jeff Brownb6997262010-10-08 22:31:17 -07004389 return true;
Jeff Brownda3d5a92011-03-29 15:11:34 -07004390 case CancelationOptions::CANCEL_FALLBACK_EVENTS:
Jeff Brown49ed71d2010-12-06 17:13:33 -08004391 return memento.flags & AKEY_EVENT_FLAG_FALLBACK;
4392 default:
4393 return false;
4394 }
4395}
4396
4397bool InputDispatcher::InputState::shouldCancelMotion(const MotionMemento& memento,
Jeff Brownda3d5a92011-03-29 15:11:34 -07004398 const CancelationOptions& options) {
4399 switch (options.mode) {
4400 case CancelationOptions::CANCEL_ALL_EVENTS:
Jeff Brown49ed71d2010-12-06 17:13:33 -08004401 return true;
Jeff Brownda3d5a92011-03-29 15:11:34 -07004402 case CancelationOptions::CANCEL_POINTER_EVENTS:
Jeff Brown49ed71d2010-12-06 17:13:33 -08004403 return memento.source & AINPUT_SOURCE_CLASS_POINTER;
Jeff Brownda3d5a92011-03-29 15:11:34 -07004404 case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
Jeff Brown49ed71d2010-12-06 17:13:33 -08004405 return !(memento.source & AINPUT_SOURCE_CLASS_POINTER);
4406 default:
4407 return false;
Jeff Brownb6997262010-10-08 22:31:17 -07004408 }
Jeff Brownb88102f2010-09-08 11:49:43 -07004409}
4410
4411
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004412// --- InputDispatcher::Connection ---
4413
Jeff Brown928e0542011-01-10 11:17:36 -08004414InputDispatcher::Connection::Connection(const sp<InputChannel>& inputChannel,
4415 const sp<InputWindowHandle>& inputWindowHandle) :
4416 status(STATUS_NORMAL), inputChannel(inputChannel), inputWindowHandle(inputWindowHandle),
4417 inputPublisher(inputChannel),
Jeff Brownda3d5a92011-03-29 15:11:34 -07004418 lastEventTime(LONG_LONG_MAX), lastDispatchTime(LONG_LONG_MAX) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004419}
4420
4421InputDispatcher::Connection::~Connection() {
4422}
4423
4424status_t InputDispatcher::Connection::initialize() {
4425 return inputPublisher.initialize();
4426}
4427
Jeff Brown9c3cda02010-06-15 01:31:58 -07004428const char* InputDispatcher::Connection::getStatusLabel() const {
4429 switch (status) {
4430 case STATUS_NORMAL:
4431 return "NORMAL";
4432
4433 case STATUS_BROKEN:
4434 return "BROKEN";
4435
Jeff Brown9c3cda02010-06-15 01:31:58 -07004436 case STATUS_ZOMBIE:
4437 return "ZOMBIE";
4438
4439 default:
4440 return "UNKNOWN";
4441 }
4442}
4443
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004444InputDispatcher::DispatchEntry* InputDispatcher::Connection::findQueuedDispatchEntryForEvent(
4445 const EventEntry* eventEntry) const {
Jeff Brownac386072011-07-20 15:19:50 -07004446 for (DispatchEntry* dispatchEntry = outboundQueue.tail; dispatchEntry;
4447 dispatchEntry = dispatchEntry->prev) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004448 if (dispatchEntry->eventEntry == eventEntry) {
4449 return dispatchEntry;
4450 }
4451 }
4452 return NULL;
4453}
4454
Jeff Brownb88102f2010-09-08 11:49:43 -07004455
Jeff Brown9c3cda02010-06-15 01:31:58 -07004456// --- InputDispatcher::CommandEntry ---
4457
Jeff Brownac386072011-07-20 15:19:50 -07004458InputDispatcher::CommandEntry::CommandEntry(Command command) :
4459 command(command), eventTime(0), keyEntry(NULL), userActivityEventType(0), handled(false) {
Jeff Brown9c3cda02010-06-15 01:31:58 -07004460}
4461
4462InputDispatcher::CommandEntry::~CommandEntry() {
4463}
4464
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004465
Jeff Brown01ce2e92010-09-26 22:20:12 -07004466// --- InputDispatcher::TouchState ---
4467
4468InputDispatcher::TouchState::TouchState() :
Jeff Brown58a2da82011-01-25 16:02:22 -08004469 down(false), split(false), deviceId(-1), source(0) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07004470}
4471
4472InputDispatcher::TouchState::~TouchState() {
4473}
4474
4475void InputDispatcher::TouchState::reset() {
4476 down = false;
4477 split = false;
Jeff Brown95712852011-01-04 19:41:59 -08004478 deviceId = -1;
Jeff Brown58a2da82011-01-25 16:02:22 -08004479 source = 0;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004480 windows.clear();
4481}
4482
4483void InputDispatcher::TouchState::copyFrom(const TouchState& other) {
4484 down = other.down;
4485 split = other.split;
Jeff Brown95712852011-01-04 19:41:59 -08004486 deviceId = other.deviceId;
Jeff Brown58a2da82011-01-25 16:02:22 -08004487 source = other.source;
Jeff Brown9302c872011-07-13 22:51:29 -07004488 windows = other.windows;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004489}
4490
Jeff Brown9302c872011-07-13 22:51:29 -07004491void InputDispatcher::TouchState::addOrUpdateWindow(const sp<InputWindowHandle>& windowHandle,
Jeff Brown01ce2e92010-09-26 22:20:12 -07004492 int32_t targetFlags, BitSet32 pointerIds) {
4493 if (targetFlags & InputTarget::FLAG_SPLIT) {
4494 split = true;
4495 }
4496
4497 for (size_t i = 0; i < windows.size(); i++) {
4498 TouchedWindow& touchedWindow = windows.editItemAt(i);
Jeff Brown9302c872011-07-13 22:51:29 -07004499 if (touchedWindow.windowHandle == windowHandle) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07004500 touchedWindow.targetFlags |= targetFlags;
Jeff Brown98db5fa2011-06-08 15:37:10 -07004501 if (targetFlags & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
4502 touchedWindow.targetFlags &= ~InputTarget::FLAG_DISPATCH_AS_IS;
4503 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07004504 touchedWindow.pointerIds.value |= pointerIds.value;
4505 return;
4506 }
4507 }
4508
4509 windows.push();
4510
4511 TouchedWindow& touchedWindow = windows.editTop();
Jeff Brown9302c872011-07-13 22:51:29 -07004512 touchedWindow.windowHandle = windowHandle;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004513 touchedWindow.targetFlags = targetFlags;
4514 touchedWindow.pointerIds = pointerIds;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004515}
4516
Jeff Browna032cc02011-03-07 16:56:21 -08004517void InputDispatcher::TouchState::filterNonAsIsTouchWindows() {
Jeff Brown01ce2e92010-09-26 22:20:12 -07004518 for (size_t i = 0 ; i < windows.size(); ) {
Jeff Browna032cc02011-03-07 16:56:21 -08004519 TouchedWindow& window = windows.editItemAt(i);
Jeff Brown98db5fa2011-06-08 15:37:10 -07004520 if (window.targetFlags & (InputTarget::FLAG_DISPATCH_AS_IS
4521 | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER)) {
Jeff Browna032cc02011-03-07 16:56:21 -08004522 window.targetFlags &= ~InputTarget::FLAG_DISPATCH_MASK;
4523 window.targetFlags |= InputTarget::FLAG_DISPATCH_AS_IS;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004524 i += 1;
Jeff Browna032cc02011-03-07 16:56:21 -08004525 } else {
4526 windows.removeAt(i);
Jeff Brown01ce2e92010-09-26 22:20:12 -07004527 }
4528 }
4529}
4530
Jeff Brown9302c872011-07-13 22:51:29 -07004531sp<InputWindowHandle> InputDispatcher::TouchState::getFirstForegroundWindowHandle() const {
Jeff Brown01ce2e92010-09-26 22:20:12 -07004532 for (size_t i = 0; i < windows.size(); i++) {
Jeff Brown98db5fa2011-06-08 15:37:10 -07004533 const TouchedWindow& window = windows.itemAt(i);
4534 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
Jeff Brown9302c872011-07-13 22:51:29 -07004535 return window.windowHandle;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004536 }
4537 }
4538 return NULL;
4539}
4540
Jeff Brown98db5fa2011-06-08 15:37:10 -07004541bool InputDispatcher::TouchState::isSlippery() const {
4542 // Must have exactly one foreground window.
4543 bool haveSlipperyForegroundWindow = false;
4544 for (size_t i = 0; i < windows.size(); i++) {
4545 const TouchedWindow& window = windows.itemAt(i);
4546 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
Jeff Brown9302c872011-07-13 22:51:29 -07004547 if (haveSlipperyForegroundWindow || !(window.windowHandle->layoutParamsFlags
4548 & InputWindowHandle::FLAG_SLIPPERY)) {
Jeff Brown98db5fa2011-06-08 15:37:10 -07004549 return false;
4550 }
4551 haveSlipperyForegroundWindow = true;
4552 }
4553 }
4554 return haveSlipperyForegroundWindow;
4555}
4556
Jeff Brown01ce2e92010-09-26 22:20:12 -07004557
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004558// --- InputDispatcherThread ---
4559
4560InputDispatcherThread::InputDispatcherThread(const sp<InputDispatcherInterface>& dispatcher) :
4561 Thread(/*canCallJava*/ true), mDispatcher(dispatcher) {
4562}
4563
4564InputDispatcherThread::~InputDispatcherThread() {
4565}
4566
4567bool InputDispatcherThread::threadLoop() {
4568 mDispatcher->dispatchOnce();
4569 return true;
4570}
4571
4572} // namespace android