blob: f6ce44c8200c66255aec3bf2c8583e8b21587282 [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
Jeff Brown65fd2512011-08-18 11:20:58 -0700404 case EventEntry::TYPE_DEVICE_RESET: {
405 DeviceResetEntry* typedEntry =
406 static_cast<DeviceResetEntry*>(mPendingEvent);
407 done = dispatchDeviceResetLocked(currentTime, typedEntry);
408 dropReason = DROP_REASON_NOT_DROPPED; // device resets are never dropped
409 break;
410 }
411
Jeff Brownb88102f2010-09-08 11:49:43 -0700412 case EventEntry::TYPE_KEY: {
413 KeyEntry* typedEntry = static_cast<KeyEntry*>(mPendingEvent);
Jeff Brownb6997262010-10-08 22:31:17 -0700414 if (isAppSwitchDue) {
415 if (isAppSwitchKeyEventLocked(typedEntry)) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700416 resetPendingAppSwitchLocked(true);
Jeff Brownb6997262010-10-08 22:31:17 -0700417 isAppSwitchDue = false;
418 } else if (dropReason == DROP_REASON_NOT_DROPPED) {
419 dropReason = DROP_REASON_APP_SWITCH;
Jeff Brownb88102f2010-09-08 11:49:43 -0700420 }
421 }
Jeff Brown928e0542011-01-10 11:17:36 -0800422 if (dropReason == DROP_REASON_NOT_DROPPED
423 && isStaleEventLocked(currentTime, typedEntry)) {
424 dropReason = DROP_REASON_STALE;
425 }
426 if (dropReason == DROP_REASON_NOT_DROPPED && mNextUnblockedEvent) {
427 dropReason = DROP_REASON_BLOCKED;
428 }
Jeff Brown214eaf42011-05-26 19:17:02 -0700429 done = dispatchKeyLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700430 break;
431 }
432
433 case EventEntry::TYPE_MOTION: {
434 MotionEntry* typedEntry = static_cast<MotionEntry*>(mPendingEvent);
Jeff Brownb6997262010-10-08 22:31:17 -0700435 if (dropReason == DROP_REASON_NOT_DROPPED && isAppSwitchDue) {
436 dropReason = DROP_REASON_APP_SWITCH;
Jeff Brownb88102f2010-09-08 11:49:43 -0700437 }
Jeff Brown928e0542011-01-10 11:17:36 -0800438 if (dropReason == DROP_REASON_NOT_DROPPED
439 && isStaleEventLocked(currentTime, typedEntry)) {
440 dropReason = DROP_REASON_STALE;
441 }
442 if (dropReason == DROP_REASON_NOT_DROPPED && mNextUnblockedEvent) {
443 dropReason = DROP_REASON_BLOCKED;
444 }
Jeff Brownb6997262010-10-08 22:31:17 -0700445 done = dispatchMotionLocked(currentTime, typedEntry,
Jeff Browne20c9e02010-10-11 14:20:19 -0700446 &dropReason, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700447 break;
448 }
449
450 default:
Jeff Brownb6110c22011-04-01 16:15:13 -0700451 LOG_ASSERT(false);
Jeff Brownb88102f2010-09-08 11:49:43 -0700452 break;
453 }
454
Jeff Brown54a18252010-09-16 14:07:33 -0700455 if (done) {
Jeff Brownb6997262010-10-08 22:31:17 -0700456 if (dropReason != DROP_REASON_NOT_DROPPED) {
457 dropInboundEventLocked(mPendingEvent, dropReason);
458 }
459
Jeff Brown54a18252010-09-16 14:07:33 -0700460 releasePendingEventLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -0700461 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
462 }
463}
464
465bool InputDispatcher::enqueueInboundEventLocked(EventEntry* entry) {
466 bool needWake = mInboundQueue.isEmpty();
467 mInboundQueue.enqueueAtTail(entry);
468
469 switch (entry->type) {
Jeff Brownb6997262010-10-08 22:31:17 -0700470 case EventEntry::TYPE_KEY: {
Jeff Brown928e0542011-01-10 11:17:36 -0800471 // Optimize app switch latency.
472 // If the application takes too long to catch up then we drop all events preceding
473 // the app switch key.
Jeff Brownb6997262010-10-08 22:31:17 -0700474 KeyEntry* keyEntry = static_cast<KeyEntry*>(entry);
475 if (isAppSwitchKeyEventLocked(keyEntry)) {
476 if (keyEntry->action == AKEY_EVENT_ACTION_DOWN) {
477 mAppSwitchSawKeyDown = true;
478 } else if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
479 if (mAppSwitchSawKeyDown) {
480#if DEBUG_APP_SWITCH
481 LOGD("App switch is pending!");
482#endif
483 mAppSwitchDueTime = keyEntry->eventTime + APP_SWITCH_TIMEOUT;
484 mAppSwitchSawKeyDown = false;
485 needWake = true;
486 }
487 }
488 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700489 break;
490 }
Jeff Brown928e0542011-01-10 11:17:36 -0800491
492 case EventEntry::TYPE_MOTION: {
493 // Optimize case where the current application is unresponsive and the user
494 // decides to touch a window in a different application.
495 // If the application takes too long to catch up then we drop all events preceding
496 // the touch into the other window.
497 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
Jeff Brown33bbfd22011-02-24 20:55:35 -0800498 if (motionEntry->action == AMOTION_EVENT_ACTION_DOWN
Jeff Brown928e0542011-01-10 11:17:36 -0800499 && (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER)
500 && mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY
Jeff Brown9302c872011-07-13 22:51:29 -0700501 && mInputTargetWaitApplicationHandle != NULL) {
Jeff Brown91c69ab2011-02-14 17:03:18 -0800502 int32_t x = int32_t(motionEntry->firstSample.pointerCoords[0].
Jeff Brownebbd5d12011-02-17 13:01:34 -0800503 getAxisValue(AMOTION_EVENT_AXIS_X));
Jeff Brown91c69ab2011-02-14 17:03:18 -0800504 int32_t y = int32_t(motionEntry->firstSample.pointerCoords[0].
Jeff Brownebbd5d12011-02-17 13:01:34 -0800505 getAxisValue(AMOTION_EVENT_AXIS_Y));
Jeff Brown9302c872011-07-13 22:51:29 -0700506 sp<InputWindowHandle> touchedWindowHandle = findTouchedWindowAtLocked(x, y);
507 if (touchedWindowHandle != NULL
508 && touchedWindowHandle->inputApplicationHandle
509 != mInputTargetWaitApplicationHandle) {
Jeff Brown928e0542011-01-10 11:17:36 -0800510 // User touched a different application than the one we are waiting on.
511 // Flag the event, and start pruning the input queue.
512 mNextUnblockedEvent = motionEntry;
513 needWake = true;
514 }
515 }
516 break;
517 }
Jeff Brownb6997262010-10-08 22:31:17 -0700518 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700519
520 return needWake;
521}
522
Jeff Brown9302c872011-07-13 22:51:29 -0700523sp<InputWindowHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t x, int32_t y) {
Jeff Brown928e0542011-01-10 11:17:36 -0800524 // Traverse windows from front to back to find touched window.
Jeff Brown9302c872011-07-13 22:51:29 -0700525 size_t numWindows = mWindowHandles.size();
Jeff Brown928e0542011-01-10 11:17:36 -0800526 for (size_t i = 0; i < numWindows; i++) {
Jeff Brown9302c872011-07-13 22:51:29 -0700527 sp<InputWindowHandle> windowHandle = mWindowHandles.itemAt(i);
528 int32_t flags = windowHandle->layoutParamsFlags;
Jeff Brown928e0542011-01-10 11:17:36 -0800529
Jeff Brown9302c872011-07-13 22:51:29 -0700530 if (windowHandle->visible) {
531 if (!(flags & InputWindowHandle::FLAG_NOT_TOUCHABLE)) {
532 bool isTouchModal = (flags & (InputWindowHandle::FLAG_NOT_FOCUSABLE
533 | InputWindowHandle::FLAG_NOT_TOUCH_MODAL)) == 0;
534 if (isTouchModal || windowHandle->touchableRegionContainsPoint(x, y)) {
Jeff Brown928e0542011-01-10 11:17:36 -0800535 // Found window.
Jeff Brown9302c872011-07-13 22:51:29 -0700536 return windowHandle;
Jeff Brown928e0542011-01-10 11:17:36 -0800537 }
538 }
539 }
540
Jeff Brown9302c872011-07-13 22:51:29 -0700541 if (flags & InputWindowHandle::FLAG_SYSTEM_ERROR) {
Jeff Brown928e0542011-01-10 11:17:36 -0800542 // Error window is on top but not visible, so touch is dropped.
543 return NULL;
544 }
545 }
546 return NULL;
547}
548
Jeff Brownb6997262010-10-08 22:31:17 -0700549void InputDispatcher::dropInboundEventLocked(EventEntry* entry, DropReason dropReason) {
550 const char* reason;
551 switch (dropReason) {
552 case DROP_REASON_POLICY:
Jeff Browne20c9e02010-10-11 14:20:19 -0700553#if DEBUG_INBOUND_EVENT_DETAILS
Jeff Brown3122e442010-10-11 23:32:49 -0700554 LOGD("Dropped event because policy consumed it.");
Jeff Browne20c9e02010-10-11 14:20:19 -0700555#endif
Jeff Brown3122e442010-10-11 23:32:49 -0700556 reason = "inbound event was dropped because the policy consumed it";
Jeff Brownb6997262010-10-08 22:31:17 -0700557 break;
558 case DROP_REASON_DISABLED:
559 LOGI("Dropped event because input dispatch is disabled.");
560 reason = "inbound event was dropped because input dispatch is disabled";
561 break;
562 case DROP_REASON_APP_SWITCH:
563 LOGI("Dropped event because of pending overdue app switch.");
564 reason = "inbound event was dropped because of pending overdue app switch";
565 break;
Jeff Brown928e0542011-01-10 11:17:36 -0800566 case DROP_REASON_BLOCKED:
567 LOGI("Dropped event because the current application is not responding and the user "
Jeff Brown81346812011-06-28 20:08:48 -0700568 "has started interacting with a different application.");
Jeff Brown928e0542011-01-10 11:17:36 -0800569 reason = "inbound event was dropped because the current application is not responding "
Jeff Brown81346812011-06-28 20:08:48 -0700570 "and the user has started interacting with a different application";
Jeff Brown928e0542011-01-10 11:17:36 -0800571 break;
572 case DROP_REASON_STALE:
573 LOGI("Dropped event because it is stale.");
574 reason = "inbound event was dropped because it is stale";
575 break;
Jeff Brownb6997262010-10-08 22:31:17 -0700576 default:
Jeff Brownb6110c22011-04-01 16:15:13 -0700577 LOG_ASSERT(false);
Jeff Brownb6997262010-10-08 22:31:17 -0700578 return;
579 }
580
581 switch (entry->type) {
Jeff Brownda3d5a92011-03-29 15:11:34 -0700582 case EventEntry::TYPE_KEY: {
583 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
584 synthesizeCancelationEventsForAllConnectionsLocked(options);
Jeff Brownb6997262010-10-08 22:31:17 -0700585 break;
Jeff Brownda3d5a92011-03-29 15:11:34 -0700586 }
Jeff Brownb6997262010-10-08 22:31:17 -0700587 case EventEntry::TYPE_MOTION: {
588 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
589 if (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) {
Jeff Brownda3d5a92011-03-29 15:11:34 -0700590 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
591 synthesizeCancelationEventsForAllConnectionsLocked(options);
Jeff Brownb6997262010-10-08 22:31:17 -0700592 } else {
Jeff Brownda3d5a92011-03-29 15:11:34 -0700593 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
594 synthesizeCancelationEventsForAllConnectionsLocked(options);
Jeff Brownb6997262010-10-08 22:31:17 -0700595 }
596 break;
597 }
598 }
599}
600
601bool InputDispatcher::isAppSwitchKeyCode(int32_t keyCode) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700602 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL;
603}
604
Jeff Brownb6997262010-10-08 22:31:17 -0700605bool InputDispatcher::isAppSwitchKeyEventLocked(KeyEntry* keyEntry) {
606 return ! (keyEntry->flags & AKEY_EVENT_FLAG_CANCELED)
607 && isAppSwitchKeyCode(keyEntry->keyCode)
Jeff Browne20c9e02010-10-11 14:20:19 -0700608 && (keyEntry->policyFlags & POLICY_FLAG_TRUSTED)
Jeff Brownb6997262010-10-08 22:31:17 -0700609 && (keyEntry->policyFlags & POLICY_FLAG_PASS_TO_USER);
610}
611
Jeff Brownb88102f2010-09-08 11:49:43 -0700612bool InputDispatcher::isAppSwitchPendingLocked() {
613 return mAppSwitchDueTime != LONG_LONG_MAX;
614}
615
Jeff Brownb88102f2010-09-08 11:49:43 -0700616void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
617 mAppSwitchDueTime = LONG_LONG_MAX;
618
619#if DEBUG_APP_SWITCH
620 if (handled) {
621 LOGD("App switch has arrived.");
622 } else {
623 LOGD("App switch was abandoned.");
624 }
625#endif
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700626}
627
Jeff Brown928e0542011-01-10 11:17:36 -0800628bool InputDispatcher::isStaleEventLocked(nsecs_t currentTime, EventEntry* entry) {
629 return currentTime - entry->eventTime >= STALE_EVENT_TIMEOUT;
630}
631
Jeff Brown9c3cda02010-06-15 01:31:58 -0700632bool InputDispatcher::runCommandsLockedInterruptible() {
633 if (mCommandQueue.isEmpty()) {
634 return false;
635 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700636
Jeff Brown9c3cda02010-06-15 01:31:58 -0700637 do {
638 CommandEntry* commandEntry = mCommandQueue.dequeueAtHead();
639
640 Command command = commandEntry->command;
641 (this->*command)(commandEntry); // commands are implicitly 'LockedInterruptible'
642
Jeff Brown7fbdc842010-06-17 20:52:56 -0700643 commandEntry->connection.clear();
Jeff Brownac386072011-07-20 15:19:50 -0700644 delete commandEntry;
Jeff Brown9c3cda02010-06-15 01:31:58 -0700645 } while (! mCommandQueue.isEmpty());
646 return true;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700647}
648
Jeff Brown9c3cda02010-06-15 01:31:58 -0700649InputDispatcher::CommandEntry* InputDispatcher::postCommandLocked(Command command) {
Jeff Brownac386072011-07-20 15:19:50 -0700650 CommandEntry* commandEntry = new CommandEntry(command);
Jeff Brown9c3cda02010-06-15 01:31:58 -0700651 mCommandQueue.enqueueAtTail(commandEntry);
652 return commandEntry;
653}
654
Jeff Brownb88102f2010-09-08 11:49:43 -0700655void InputDispatcher::drainInboundQueueLocked() {
656 while (! mInboundQueue.isEmpty()) {
657 EventEntry* entry = mInboundQueue.dequeueAtHead();
Jeff Brown54a18252010-09-16 14:07:33 -0700658 releaseInboundEventLocked(entry);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700659 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700660}
661
Jeff Brown54a18252010-09-16 14:07:33 -0700662void InputDispatcher::releasePendingEventLocked() {
Jeff Brownb88102f2010-09-08 11:49:43 -0700663 if (mPendingEvent) {
Jeff Brown54a18252010-09-16 14:07:33 -0700664 releaseInboundEventLocked(mPendingEvent);
Jeff Brownb88102f2010-09-08 11:49:43 -0700665 mPendingEvent = NULL;
666 }
667}
668
Jeff Brown54a18252010-09-16 14:07:33 -0700669void InputDispatcher::releaseInboundEventLocked(EventEntry* entry) {
Jeff Brown01ce2e92010-09-26 22:20:12 -0700670 InjectionState* injectionState = entry->injectionState;
671 if (injectionState && injectionState->injectionResult == INPUT_EVENT_INJECTION_PENDING) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700672#if DEBUG_DISPATCH_CYCLE
Jeff Brown01ce2e92010-09-26 22:20:12 -0700673 LOGD("Injected inbound event was dropped.");
Jeff Brownb88102f2010-09-08 11:49:43 -0700674#endif
675 setInjectionResultLocked(entry, INPUT_EVENT_INJECTION_FAILED);
676 }
Jeff Brownabb4d442011-08-15 12:55:32 -0700677 if (entry == mNextUnblockedEvent) {
678 mNextUnblockedEvent = NULL;
679 }
Jeff Brownac386072011-07-20 15:19:50 -0700680 entry->release();
Jeff Brownb88102f2010-09-08 11:49:43 -0700681}
682
Jeff Brownb88102f2010-09-08 11:49:43 -0700683void InputDispatcher::resetKeyRepeatLocked() {
684 if (mKeyRepeatState.lastKeyEntry) {
Jeff Brownac386072011-07-20 15:19:50 -0700685 mKeyRepeatState.lastKeyEntry->release();
Jeff Brownb88102f2010-09-08 11:49:43 -0700686 mKeyRepeatState.lastKeyEntry = NULL;
687 }
688}
689
Jeff Brown214eaf42011-05-26 19:17:02 -0700690InputDispatcher::KeyEntry* InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
Jeff Brown349703e2010-06-22 01:27:15 -0700691 KeyEntry* entry = mKeyRepeatState.lastKeyEntry;
692
Jeff Brown349703e2010-06-22 01:27:15 -0700693 // Reuse the repeated key entry if it is otherwise unreferenced.
Jeff Browne20c9e02010-10-11 14:20:19 -0700694 uint32_t policyFlags = (entry->policyFlags & POLICY_FLAG_RAW_MASK)
695 | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700696 if (entry->refCount == 1) {
Jeff Brownac386072011-07-20 15:19:50 -0700697 entry->recycle();
Jeff Brown7fbdc842010-06-17 20:52:56 -0700698 entry->eventTime = currentTime;
Jeff Brown7fbdc842010-06-17 20:52:56 -0700699 entry->policyFlags = policyFlags;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700700 entry->repeatCount += 1;
701 } else {
Jeff Brownac386072011-07-20 15:19:50 -0700702 KeyEntry* newEntry = new KeyEntry(currentTime,
Jeff Brownc5ed5912010-07-14 18:48:53 -0700703 entry->deviceId, entry->source, policyFlags,
Jeff Brown7fbdc842010-06-17 20:52:56 -0700704 entry->action, entry->flags, entry->keyCode, entry->scanCode,
Jeff Brown00fa7bd2010-07-02 15:37:36 -0700705 entry->metaState, entry->repeatCount + 1, entry->downTime);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700706
707 mKeyRepeatState.lastKeyEntry = newEntry;
Jeff Brownac386072011-07-20 15:19:50 -0700708 entry->release();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700709
710 entry = newEntry;
711 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700712 entry->syntheticRepeat = true;
713
714 // Increment reference count since we keep a reference to the event in
715 // mKeyRepeatState.lastKeyEntry in addition to the one we return.
716 entry->refCount += 1;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700717
Jeff Brown214eaf42011-05-26 19:17:02 -0700718 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Jeff Brownb88102f2010-09-08 11:49:43 -0700719 return entry;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700720}
721
Jeff Brownb88102f2010-09-08 11:49:43 -0700722bool InputDispatcher::dispatchConfigurationChangedLocked(
723 nsecs_t currentTime, ConfigurationChangedEntry* entry) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700724#if DEBUG_OUTBOUND_EVENT_DETAILS
Jeff Brownb88102f2010-09-08 11:49:43 -0700725 LOGD("dispatchConfigurationChanged - eventTime=%lld", entry->eventTime);
726#endif
727
728 // Reset key repeating in case a keyboard device was added or removed or something.
729 resetKeyRepeatLocked();
730
731 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
732 CommandEntry* commandEntry = postCommandLocked(
733 & InputDispatcher::doNotifyConfigurationChangedInterruptible);
734 commandEntry->eventTime = entry->eventTime;
735 return true;
736}
737
Jeff Brown65fd2512011-08-18 11:20:58 -0700738bool InputDispatcher::dispatchDeviceResetLocked(
739 nsecs_t currentTime, DeviceResetEntry* entry) {
740#if DEBUG_OUTBOUND_EVENT_DETAILS
741 LOGD("dispatchDeviceReset - eventTime=%lld, deviceId=%d", entry->eventTime, entry->deviceId);
742#endif
743
744 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
745 "device was reset");
746 options.deviceId = entry->deviceId;
747 synthesizeCancelationEventsForAllConnectionsLocked(options);
748 return true;
749}
750
Jeff Brown214eaf42011-05-26 19:17:02 -0700751bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, KeyEntry* entry,
Jeff Browne20c9e02010-10-11 14:20:19 -0700752 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Jeff Browne46a0a42010-11-02 17:58:22 -0700753 // Preprocessing.
754 if (! entry->dispatchInProgress) {
755 if (entry->repeatCount == 0
756 && entry->action == AKEY_EVENT_ACTION_DOWN
757 && (entry->policyFlags & POLICY_FLAG_TRUSTED)
Jeff Brown0029c662011-03-30 02:25:18 -0700758 && (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
Jeff Browne46a0a42010-11-02 17:58:22 -0700759 if (mKeyRepeatState.lastKeyEntry
760 && mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode) {
761 // We have seen two identical key downs in a row which indicates that the device
762 // driver is automatically generating key repeats itself. We take note of the
763 // repeat here, but we disable our own next key repeat timer since it is clear that
764 // we will not need to synthesize key repeats ourselves.
765 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
766 resetKeyRepeatLocked();
767 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
768 } else {
769 // Not a repeat. Save key down state in case we do see a repeat later.
770 resetKeyRepeatLocked();
Jeff Brown214eaf42011-05-26 19:17:02 -0700771 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
Jeff Browne46a0a42010-11-02 17:58:22 -0700772 }
773 mKeyRepeatState.lastKeyEntry = entry;
774 entry->refCount += 1;
775 } else if (! entry->syntheticRepeat) {
776 resetKeyRepeatLocked();
777 }
778
Jeff Browne2e01262011-03-02 20:34:30 -0800779 if (entry->repeatCount == 1) {
780 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
781 } else {
782 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
783 }
784
Jeff Browne46a0a42010-11-02 17:58:22 -0700785 entry->dispatchInProgress = true;
786 resetTargetsLocked();
787
788 logOutboundKeyDetailsLocked("dispatchKey - ", entry);
789 }
790
Jeff Brown54a18252010-09-16 14:07:33 -0700791 // Give the policy a chance to intercept the key.
792 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
Jeff Browne20c9e02010-10-11 14:20:19 -0700793 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Jeff Brown54a18252010-09-16 14:07:33 -0700794 CommandEntry* commandEntry = postCommandLocked(
795 & InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
Jeff Brown9302c872011-07-13 22:51:29 -0700796 if (mFocusedWindowHandle != NULL) {
797 commandEntry->inputWindowHandle = mFocusedWindowHandle;
Jeff Brown54a18252010-09-16 14:07:33 -0700798 }
799 commandEntry->keyEntry = entry;
800 entry->refCount += 1;
801 return false; // wait for the command to run
802 } else {
803 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
804 }
805 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Jeff Browne20c9e02010-10-11 14:20:19 -0700806 if (*dropReason == DROP_REASON_NOT_DROPPED) {
807 *dropReason = DROP_REASON_POLICY;
808 }
Jeff Brown54a18252010-09-16 14:07:33 -0700809 }
810
811 // Clean up if dropping the event.
Jeff Browne20c9e02010-10-11 14:20:19 -0700812 if (*dropReason != DROP_REASON_NOT_DROPPED) {
Jeff Brown54a18252010-09-16 14:07:33 -0700813 resetTargetsLocked();
Jeff Brown3122e442010-10-11 23:32:49 -0700814 setInjectionResultLocked(entry, *dropReason == DROP_REASON_POLICY
815 ? INPUT_EVENT_INJECTION_SUCCEEDED : INPUT_EVENT_INJECTION_FAILED);
Jeff Brown54a18252010-09-16 14:07:33 -0700816 return true;
817 }
818
Jeff Brownb88102f2010-09-08 11:49:43 -0700819 // Identify targets.
820 if (! mCurrentInputTargetsValid) {
Jeff Brown01ce2e92010-09-26 22:20:12 -0700821 int32_t injectionResult = findFocusedWindowTargetsLocked(currentTime,
822 entry, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700823 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
824 return false;
825 }
826
827 setInjectionResultLocked(entry, injectionResult);
828 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
829 return true;
830 }
831
832 addMonitoringTargetsLocked();
Jeff Brown01ce2e92010-09-26 22:20:12 -0700833 commitTargetsLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -0700834 }
835
836 // Dispatch the key.
837 dispatchEventToCurrentInputTargetsLocked(currentTime, entry, false);
Jeff Brownb88102f2010-09-08 11:49:43 -0700838 return true;
839}
840
841void InputDispatcher::logOutboundKeyDetailsLocked(const char* prefix, const KeyEntry* entry) {
842#if DEBUG_OUTBOUND_EVENT_DETAILS
Jeff Brown90655042010-12-02 13:50:46 -0800843 LOGD("%seventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, "
Jeff Brownb88102f2010-09-08 11:49:43 -0700844 "action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, "
Jeff Browne46a0a42010-11-02 17:58:22 -0700845 "repeatCount=%d, downTime=%lld",
Jeff Brownb88102f2010-09-08 11:49:43 -0700846 prefix,
847 entry->eventTime, entry->deviceId, entry->source, entry->policyFlags,
848 entry->action, entry->flags, entry->keyCode, entry->scanCode, entry->metaState,
Jeff Browne46a0a42010-11-02 17:58:22 -0700849 entry->repeatCount, entry->downTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700850#endif
851}
852
853bool InputDispatcher::dispatchMotionLocked(
Jeff Browne20c9e02010-10-11 14:20:19 -0700854 nsecs_t currentTime, MotionEntry* entry, DropReason* dropReason, nsecs_t* nextWakeupTime) {
Jeff Browne46a0a42010-11-02 17:58:22 -0700855 // Preprocessing.
856 if (! entry->dispatchInProgress) {
857 entry->dispatchInProgress = true;
858 resetTargetsLocked();
859
860 logOutboundMotionDetailsLocked("dispatchMotion - ", entry);
861 }
862
Jeff Brown54a18252010-09-16 14:07:33 -0700863 // Clean up if dropping the event.
Jeff Browne20c9e02010-10-11 14:20:19 -0700864 if (*dropReason != DROP_REASON_NOT_DROPPED) {
Jeff Brown54a18252010-09-16 14:07:33 -0700865 resetTargetsLocked();
Jeff Brown3122e442010-10-11 23:32:49 -0700866 setInjectionResultLocked(entry, *dropReason == DROP_REASON_POLICY
867 ? INPUT_EVENT_INJECTION_SUCCEEDED : INPUT_EVENT_INJECTION_FAILED);
Jeff Brown54a18252010-09-16 14:07:33 -0700868 return true;
869 }
870
Jeff Brownb88102f2010-09-08 11:49:43 -0700871 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
872
873 // Identify targets.
Jeff Browncc0c1592011-02-19 05:07:28 -0800874 bool conflictingPointerActions = false;
Jeff Brownb88102f2010-09-08 11:49:43 -0700875 if (! mCurrentInputTargetsValid) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700876 int32_t injectionResult;
Jeff Browna032cc02011-03-07 16:56:21 -0800877 const MotionSample* splitBatchAfterSample = NULL;
Jeff Brownb88102f2010-09-08 11:49:43 -0700878 if (isPointerEvent) {
879 // Pointer event. (eg. touchscreen)
Jeff Brown01ce2e92010-09-26 22:20:12 -0700880 injectionResult = findTouchedWindowTargetsLocked(currentTime,
Jeff Browna032cc02011-03-07 16:56:21 -0800881 entry, nextWakeupTime, &conflictingPointerActions, &splitBatchAfterSample);
Jeff Brownb88102f2010-09-08 11:49:43 -0700882 } else {
883 // Non touch event. (eg. trackball)
Jeff Brown01ce2e92010-09-26 22:20:12 -0700884 injectionResult = findFocusedWindowTargetsLocked(currentTime,
885 entry, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700886 }
887 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
888 return false;
889 }
890
891 setInjectionResultLocked(entry, injectionResult);
892 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
893 return true;
894 }
895
896 addMonitoringTargetsLocked();
Jeff Brown01ce2e92010-09-26 22:20:12 -0700897 commitTargetsLocked();
Jeff Browna032cc02011-03-07 16:56:21 -0800898
899 // Unbatch the event if necessary by splitting it into two parts after the
900 // motion sample indicated by splitBatchAfterSample.
901 if (splitBatchAfterSample && splitBatchAfterSample->next) {
902#if DEBUG_BATCHING
903 uint32_t originalSampleCount = entry->countSamples();
904#endif
905 MotionSample* nextSample = splitBatchAfterSample->next;
Jeff Brownac386072011-07-20 15:19:50 -0700906 MotionEntry* nextEntry = new MotionEntry(nextSample->eventTime,
Jeff Browna032cc02011-03-07 16:56:21 -0800907 entry->deviceId, entry->source, entry->policyFlags,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700908 entry->action, entry->flags,
909 entry->metaState, entry->buttonState, entry->edgeFlags,
Jeff Browna032cc02011-03-07 16:56:21 -0800910 entry->xPrecision, entry->yPrecision, entry->downTime,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700911 entry->pointerCount, entry->pointerProperties, nextSample->pointerCoords);
Jeff Browna032cc02011-03-07 16:56:21 -0800912 if (nextSample != entry->lastSample) {
913 nextEntry->firstSample.next = nextSample->next;
914 nextEntry->lastSample = entry->lastSample;
915 }
Jeff Brownac386072011-07-20 15:19:50 -0700916 delete nextSample;
Jeff Browna032cc02011-03-07 16:56:21 -0800917
918 entry->lastSample = const_cast<MotionSample*>(splitBatchAfterSample);
919 entry->lastSample->next = NULL;
920
921 if (entry->injectionState) {
922 nextEntry->injectionState = entry->injectionState;
923 entry->injectionState->refCount += 1;
924 }
925
926#if DEBUG_BATCHING
927 LOGD("Split batch of %d samples into two parts, first part has %d samples, "
928 "second part has %d samples.", originalSampleCount,
929 entry->countSamples(), nextEntry->countSamples());
930#endif
931
932 mInboundQueue.enqueueAtHead(nextEntry);
933 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700934 }
935
936 // Dispatch the motion.
Jeff Browncc0c1592011-02-19 05:07:28 -0800937 if (conflictingPointerActions) {
Jeff Brownda3d5a92011-03-29 15:11:34 -0700938 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
939 "conflicting pointer actions");
940 synthesizeCancelationEventsForAllConnectionsLocked(options);
Jeff Browncc0c1592011-02-19 05:07:28 -0800941 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700942 dispatchEventToCurrentInputTargetsLocked(currentTime, entry, false);
Jeff Brownb88102f2010-09-08 11:49:43 -0700943 return true;
944}
945
946
947void InputDispatcher::logOutboundMotionDetailsLocked(const char* prefix, const MotionEntry* entry) {
948#if DEBUG_OUTBOUND_EVENT_DETAILS
Jeff Brown90655042010-12-02 13:50:46 -0800949 LOGD("%seventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, "
Jeff Brown85a31762010-09-01 17:01:00 -0700950 "action=0x%x, flags=0x%x, "
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700951 "metaState=0x%x, buttonState=0x%x, "
952 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%lld",
Jeff Brownb88102f2010-09-08 11:49:43 -0700953 prefix,
Jeff Brown85a31762010-09-01 17:01:00 -0700954 entry->eventTime, entry->deviceId, entry->source, entry->policyFlags,
955 entry->action, entry->flags,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700956 entry->metaState, entry->buttonState,
957 entry->edgeFlags, entry->xPrecision, entry->yPrecision,
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700958 entry->downTime);
959
960 // Print the most recent sample that we have available, this may change due to batching.
961 size_t sampleCount = 1;
Jeff Brownb88102f2010-09-08 11:49:43 -0700962 const MotionSample* sample = & entry->firstSample;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700963 for (; sample->next != NULL; sample = sample->next) {
964 sampleCount += 1;
965 }
966 for (uint32_t i = 0; i < entry->pointerCount; i++) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700967 LOGD(" Pointer %d: id=%d, toolType=%d, "
968 "x=%f, y=%f, pressure=%f, size=%f, "
Jeff Brown85a31762010-09-01 17:01:00 -0700969 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
Jeff Brown8d608662010-08-30 03:02:23 -0700970 "orientation=%f",
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700971 i, entry->pointerProperties[i].id,
972 entry->pointerProperties[i].toolType,
Jeff Brownebbd5d12011-02-17 13:01:34 -0800973 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
974 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
975 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
976 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
977 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
978 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
979 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
980 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
981 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700982 }
983
984 // Keep in mind that due to batching, it is possible for the number of samples actually
985 // dispatched to change before the application finally consumed them.
Jeff Brownc5ed5912010-07-14 18:48:53 -0700986 if (entry->action == AMOTION_EVENT_ACTION_MOVE) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700987 LOGD(" ... Total movement samples currently batched %d ...", sampleCount);
988 }
989#endif
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700990}
991
992void InputDispatcher::dispatchEventToCurrentInputTargetsLocked(nsecs_t currentTime,
993 EventEntry* eventEntry, bool resumeWithAppendedMotionSample) {
994#if DEBUG_DISPATCH_CYCLE
Jeff Brown9c3cda02010-06-15 01:31:58 -0700995 LOGD("dispatchEventToCurrentInputTargets - "
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700996 "resumeWithAppendedMotionSample=%s",
Jeff Brownb88102f2010-09-08 11:49:43 -0700997 toString(resumeWithAppendedMotionSample));
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700998#endif
999
Jeff Brownb6110c22011-04-01 16:15:13 -07001000 LOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
Jeff Brown9c3cda02010-06-15 01:31:58 -07001001
Jeff Browne2fe69e2010-10-18 13:21:23 -07001002 pokeUserActivityLocked(eventEntry);
1003
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001004 for (size_t i = 0; i < mCurrentInputTargets.size(); i++) {
1005 const InputTarget& inputTarget = mCurrentInputTargets.itemAt(i);
1006
Jeff Brown519e0242010-09-15 15:18:56 -07001007 ssize_t connectionIndex = getConnectionIndexLocked(inputTarget.inputChannel);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001008 if (connectionIndex >= 0) {
1009 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
Jeff Brown7fbdc842010-06-17 20:52:56 -07001010 prepareDispatchCycleLocked(currentTime, connection, eventEntry, & inputTarget,
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001011 resumeWithAppendedMotionSample);
1012 } else {
Jeff Brownb6997262010-10-08 22:31:17 -07001013#if DEBUG_FOCUS
1014 LOGD("Dropping event delivery to target with channel '%s' because it "
1015 "is no longer registered with the input dispatcher.",
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001016 inputTarget.inputChannel->getName().string());
Jeff Brownb6997262010-10-08 22:31:17 -07001017#endif
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001018 }
1019 }
1020}
1021
Jeff Brown54a18252010-09-16 14:07:33 -07001022void InputDispatcher::resetTargetsLocked() {
Jeff Brownb88102f2010-09-08 11:49:43 -07001023 mCurrentInputTargetsValid = false;
1024 mCurrentInputTargets.clear();
Jeff Brown5ea29ab2011-07-27 11:50:51 -07001025 resetANRTimeoutsLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -07001026}
1027
Jeff Brown01ce2e92010-09-26 22:20:12 -07001028void InputDispatcher::commitTargetsLocked() {
Jeff Brownb88102f2010-09-08 11:49:43 -07001029 mCurrentInputTargetsValid = true;
1030}
1031
1032int32_t InputDispatcher::handleTargetsNotReadyLocked(nsecs_t currentTime,
Jeff Brown9302c872011-07-13 22:51:29 -07001033 const EventEntry* entry,
1034 const sp<InputApplicationHandle>& applicationHandle,
1035 const sp<InputWindowHandle>& windowHandle,
Jeff Brownb88102f2010-09-08 11:49:43 -07001036 nsecs_t* nextWakeupTime) {
Jeff Brown9302c872011-07-13 22:51:29 -07001037 if (applicationHandle == NULL && windowHandle == NULL) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001038 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY) {
1039#if DEBUG_FOCUS
1040 LOGD("Waiting for system to become ready for input.");
1041#endif
1042 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY;
1043 mInputTargetWaitStartTime = currentTime;
1044 mInputTargetWaitTimeoutTime = LONG_LONG_MAX;
1045 mInputTargetWaitTimeoutExpired = false;
Jeff Brown9302c872011-07-13 22:51:29 -07001046 mInputTargetWaitApplicationHandle.clear();
Jeff Brownb88102f2010-09-08 11:49:43 -07001047 }
1048 } else {
1049 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
1050#if DEBUG_FOCUS
Jeff Brown519e0242010-09-15 15:18:56 -07001051 LOGD("Waiting for application to become ready for input: %s",
Jeff Brown9302c872011-07-13 22:51:29 -07001052 getApplicationWindowLabelLocked(applicationHandle, windowHandle).string());
Jeff Brownb88102f2010-09-08 11:49:43 -07001053#endif
Jeff Brown9302c872011-07-13 22:51:29 -07001054 nsecs_t timeout = windowHandle != NULL ? windowHandle->dispatchingTimeout :
1055 applicationHandle != NULL ?
1056 applicationHandle->dispatchingTimeout : DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Jeff Brownb88102f2010-09-08 11:49:43 -07001057
1058 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY;
1059 mInputTargetWaitStartTime = currentTime;
1060 mInputTargetWaitTimeoutTime = currentTime + timeout;
1061 mInputTargetWaitTimeoutExpired = false;
Jeff Brown9302c872011-07-13 22:51:29 -07001062 mInputTargetWaitApplicationHandle.clear();
Jeff Brown928e0542011-01-10 11:17:36 -08001063
Jeff Brown9302c872011-07-13 22:51:29 -07001064 if (windowHandle != NULL) {
1065 mInputTargetWaitApplicationHandle = windowHandle->inputApplicationHandle;
Jeff Brown928e0542011-01-10 11:17:36 -08001066 }
Jeff Brown9302c872011-07-13 22:51:29 -07001067 if (mInputTargetWaitApplicationHandle == NULL && applicationHandle != NULL) {
1068 mInputTargetWaitApplicationHandle = applicationHandle;
Jeff Brown928e0542011-01-10 11:17:36 -08001069 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001070 }
1071 }
1072
1073 if (mInputTargetWaitTimeoutExpired) {
1074 return INPUT_EVENT_INJECTION_TIMED_OUT;
1075 }
1076
1077 if (currentTime >= mInputTargetWaitTimeoutTime) {
Jeff Brown9302c872011-07-13 22:51:29 -07001078 onANRLocked(currentTime, applicationHandle, windowHandle,
1079 entry->eventTime, mInputTargetWaitStartTime);
Jeff Brownb88102f2010-09-08 11:49:43 -07001080
1081 // Force poll loop to wake up immediately on next iteration once we get the
1082 // ANR response back from the policy.
1083 *nextWakeupTime = LONG_LONG_MIN;
1084 return INPUT_EVENT_INJECTION_PENDING;
1085 } else {
1086 // Force poll loop to wake up when timeout is due.
1087 if (mInputTargetWaitTimeoutTime < *nextWakeupTime) {
1088 *nextWakeupTime = mInputTargetWaitTimeoutTime;
1089 }
1090 return INPUT_EVENT_INJECTION_PENDING;
1091 }
1092}
1093
Jeff Brown519e0242010-09-15 15:18:56 -07001094void InputDispatcher::resumeAfterTargetsNotReadyTimeoutLocked(nsecs_t newTimeout,
1095 const sp<InputChannel>& inputChannel) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001096 if (newTimeout > 0) {
1097 // Extend the timeout.
1098 mInputTargetWaitTimeoutTime = now() + newTimeout;
1099 } else {
1100 // Give up.
1101 mInputTargetWaitTimeoutExpired = true;
Jeff Brown519e0242010-09-15 15:18:56 -07001102
Jeff Brown01ce2e92010-09-26 22:20:12 -07001103 // Release the touch targets.
1104 mTouchState.reset();
Jeff Brown2a95c2a2010-09-16 12:31:46 -07001105
Jeff Brown519e0242010-09-15 15:18:56 -07001106 // Input state will not be realistic. Mark it out of sync.
Jeff Browndc3e0052010-09-16 11:02:16 -07001107 if (inputChannel.get()) {
1108 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
1109 if (connectionIndex >= 0) {
1110 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
Jeff Brown00045a72010-12-09 18:10:30 -08001111 if (connection->status == Connection::STATUS_NORMAL) {
Jeff Brownda3d5a92011-03-29 15:11:34 -07001112 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
Jeff Brown00045a72010-12-09 18:10:30 -08001113 "application not responding");
Jeff Brownda3d5a92011-03-29 15:11:34 -07001114 synthesizeCancelationEventsForConnectionLocked(connection, options);
Jeff Brown00045a72010-12-09 18:10:30 -08001115 }
Jeff Browndc3e0052010-09-16 11:02:16 -07001116 }
Jeff Brown519e0242010-09-15 15:18:56 -07001117 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001118 }
1119}
1120
Jeff Brown519e0242010-09-15 15:18:56 -07001121nsecs_t InputDispatcher::getTimeSpentWaitingForApplicationLocked(
Jeff Brownb88102f2010-09-08 11:49:43 -07001122 nsecs_t currentTime) {
1123 if (mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
1124 return currentTime - mInputTargetWaitStartTime;
1125 }
1126 return 0;
1127}
1128
1129void InputDispatcher::resetANRTimeoutsLocked() {
1130#if DEBUG_FOCUS
1131 LOGD("Resetting ANR timeouts.");
1132#endif
1133
Jeff Brownb88102f2010-09-08 11:49:43 -07001134 // Reset input target wait timeout.
1135 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_NONE;
Jeff Brown5ea29ab2011-07-27 11:50:51 -07001136 mInputTargetWaitApplicationHandle.clear();
Jeff Brownb88102f2010-09-08 11:49:43 -07001137}
1138
Jeff Brown01ce2e92010-09-26 22:20:12 -07001139int32_t InputDispatcher::findFocusedWindowTargetsLocked(nsecs_t currentTime,
1140 const EventEntry* entry, nsecs_t* nextWakeupTime) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001141 mCurrentInputTargets.clear();
1142
1143 int32_t injectionResult;
1144
1145 // If there is no currently focused window and no focused application
1146 // then drop the event.
Jeff Brown9302c872011-07-13 22:51:29 -07001147 if (mFocusedWindowHandle == NULL) {
1148 if (mFocusedApplicationHandle != NULL) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001149#if DEBUG_FOCUS
1150 LOGD("Waiting because there is no focused window but there is a "
Jeff Brown519e0242010-09-15 15:18:56 -07001151 "focused application that may eventually add a window: %s.",
Jeff Brown9302c872011-07-13 22:51:29 -07001152 getApplicationWindowLabelLocked(mFocusedApplicationHandle, NULL).string());
Jeff Brownb88102f2010-09-08 11:49:43 -07001153#endif
1154 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brown9302c872011-07-13 22:51:29 -07001155 mFocusedApplicationHandle, NULL, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -07001156 goto Unresponsive;
1157 }
1158
1159 LOGI("Dropping event because there is no focused window or focused application.");
1160 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1161 goto Failed;
1162 }
1163
1164 // Check permissions.
Jeff Brown9302c872011-07-13 22:51:29 -07001165 if (! checkInjectionPermission(mFocusedWindowHandle, entry->injectionState)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001166 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1167 goto Failed;
1168 }
1169
1170 // If the currently focused window is paused then keep waiting.
Jeff Brown9302c872011-07-13 22:51:29 -07001171 if (mFocusedWindowHandle->paused) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001172#if DEBUG_FOCUS
1173 LOGD("Waiting because focused window is paused.");
1174#endif
1175 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brown9302c872011-07-13 22:51:29 -07001176 mFocusedApplicationHandle, mFocusedWindowHandle, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -07001177 goto Unresponsive;
1178 }
1179
Jeff Brown519e0242010-09-15 15:18:56 -07001180 // If the currently focused window is still working on previous events then keep waiting.
Jeff Brown9302c872011-07-13 22:51:29 -07001181 if (! isWindowFinishedWithPreviousInputLocked(mFocusedWindowHandle)) {
Jeff Brown519e0242010-09-15 15:18:56 -07001182#if DEBUG_FOCUS
1183 LOGD("Waiting because focused window still processing previous input.");
1184#endif
1185 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brown9302c872011-07-13 22:51:29 -07001186 mFocusedApplicationHandle, mFocusedWindowHandle, nextWakeupTime);
Jeff Brown519e0242010-09-15 15:18:56 -07001187 goto Unresponsive;
1188 }
1189
Jeff Brownb88102f2010-09-08 11:49:43 -07001190 // Success! Output targets.
1191 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
Jeff Brown9302c872011-07-13 22:51:29 -07001192 addWindowTargetLocked(mFocusedWindowHandle,
Jeff Browna032cc02011-03-07 16:56:21 -08001193 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS, BitSet32(0));
Jeff Brownb88102f2010-09-08 11:49:43 -07001194
1195 // Done.
1196Failed:
1197Unresponsive:
Jeff Brown519e0242010-09-15 15:18:56 -07001198 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
1199 updateDispatchStatisticsLocked(currentTime, entry,
1200 injectionResult, timeSpentWaitingForApplication);
Jeff Brownb88102f2010-09-08 11:49:43 -07001201#if DEBUG_FOCUS
Jeff Brown519e0242010-09-15 15:18:56 -07001202 LOGD("findFocusedWindow finished: injectionResult=%d, "
1203 "timeSpendWaitingForApplication=%0.1fms",
1204 injectionResult, timeSpentWaitingForApplication / 1000000.0);
Jeff Brownb88102f2010-09-08 11:49:43 -07001205#endif
1206 return injectionResult;
1207}
1208
Jeff Brown01ce2e92010-09-26 22:20:12 -07001209int32_t InputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime,
Jeff Browna032cc02011-03-07 16:56:21 -08001210 const MotionEntry* entry, nsecs_t* nextWakeupTime, bool* outConflictingPointerActions,
1211 const MotionSample** outSplitBatchAfterSample) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001212 enum InjectionPermission {
1213 INJECTION_PERMISSION_UNKNOWN,
1214 INJECTION_PERMISSION_GRANTED,
1215 INJECTION_PERMISSION_DENIED
1216 };
1217
Jeff Brownb88102f2010-09-08 11:49:43 -07001218 mCurrentInputTargets.clear();
1219
1220 nsecs_t startTime = now();
1221
1222 // For security reasons, we defer updating the touch state until we are sure that
1223 // event injection will be allowed.
1224 //
1225 // FIXME In the original code, screenWasOff could never be set to true.
1226 // The reason is that the POLICY_FLAG_WOKE_HERE
1227 // and POLICY_FLAG_BRIGHT_HERE flags were set only when preprocessing raw
1228 // EV_KEY, EV_REL and EV_ABS events. As it happens, the touch event was
1229 // actually enqueued using the policyFlags that appeared in the final EV_SYN
1230 // events upon which no preprocessing took place. So policyFlags was always 0.
1231 // In the new native input dispatcher we're a bit more careful about event
1232 // preprocessing so the touches we receive can actually have non-zero policyFlags.
1233 // Unfortunately we obtain undesirable behavior.
1234 //
1235 // Here's what happens:
1236 //
1237 // When the device dims in anticipation of going to sleep, touches
1238 // in windows which have FLAG_TOUCHABLE_WHEN_WAKING cause
1239 // the device to brighten and reset the user activity timer.
1240 // Touches on other windows (such as the launcher window)
1241 // are dropped. Then after a moment, the device goes to sleep. Oops.
1242 //
1243 // Also notice how screenWasOff was being initialized using POLICY_FLAG_BRIGHT_HERE
1244 // instead of POLICY_FLAG_WOKE_HERE...
1245 //
1246 bool screenWasOff = false; // original policy: policyFlags & POLICY_FLAG_BRIGHT_HERE;
1247
1248 int32_t action = entry->action;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001249 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Jeff Brownb88102f2010-09-08 11:49:43 -07001250
1251 // Update the touch state as needed based on the properties of the touch event.
Jeff Brown01ce2e92010-09-26 22:20:12 -07001252 int32_t injectionResult = INPUT_EVENT_INJECTION_PENDING;
1253 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
Jeff Brown9302c872011-07-13 22:51:29 -07001254 sp<InputWindowHandle> newHoverWindowHandle;
Jeff Browncc0c1592011-02-19 05:07:28 -08001255
1256 bool isSplit = mTouchState.split;
Jeff Brown2717eff2011-06-30 23:53:07 -07001257 bool switchedDevice = mTouchState.deviceId >= 0
1258 && (mTouchState.deviceId != entry->deviceId
1259 || mTouchState.source != entry->source);
Jeff Browna032cc02011-03-07 16:56:21 -08001260 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE
1261 || maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER
1262 || maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1263 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN
1264 || maskedAction == AMOTION_EVENT_ACTION_SCROLL
1265 || isHoverAction);
Jeff Brown81346812011-06-28 20:08:48 -07001266 bool wrongDevice = false;
Jeff Browna032cc02011-03-07 16:56:21 -08001267 if (newGesture) {
Jeff Browncc0c1592011-02-19 05:07:28 -08001268 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Jeff Brown81346812011-06-28 20:08:48 -07001269 if (switchedDevice && mTouchState.down && !down) {
1270#if DEBUG_FOCUS
1271 LOGD("Dropping event because a pointer for a different device is already down.");
1272#endif
Jeff Browncc0c1592011-02-19 05:07:28 -08001273 mTempTouchState.copyFrom(mTouchState);
Jeff Brown81346812011-06-28 20:08:48 -07001274 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1275 switchedDevice = false;
1276 wrongDevice = true;
1277 goto Failed;
Jeff Browncc0c1592011-02-19 05:07:28 -08001278 }
Jeff Brown81346812011-06-28 20:08:48 -07001279 mTempTouchState.reset();
1280 mTempTouchState.down = down;
1281 mTempTouchState.deviceId = entry->deviceId;
1282 mTempTouchState.source = entry->source;
1283 isSplit = false;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001284 } else {
1285 mTempTouchState.copyFrom(mTouchState);
Jeff Browncc0c1592011-02-19 05:07:28 -08001286 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001287
Jeff Browna032cc02011-03-07 16:56:21 -08001288 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
Jeff Brown33bbfd22011-02-24 20:55:35 -08001289 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
Jeff Brownb88102f2010-09-08 11:49:43 -07001290
Jeff Browna032cc02011-03-07 16:56:21 -08001291 const MotionSample* sample = &entry->firstSample;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001292 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Jeff Browna032cc02011-03-07 16:56:21 -08001293 int32_t x = int32_t(sample->pointerCoords[pointerIndex].
Jeff Brownebbd5d12011-02-17 13:01:34 -08001294 getAxisValue(AMOTION_EVENT_AXIS_X));
Jeff Browna032cc02011-03-07 16:56:21 -08001295 int32_t y = int32_t(sample->pointerCoords[pointerIndex].
Jeff Brownebbd5d12011-02-17 13:01:34 -08001296 getAxisValue(AMOTION_EVENT_AXIS_Y));
Jeff Brown9302c872011-07-13 22:51:29 -07001297 sp<InputWindowHandle> newTouchedWindowHandle;
1298 sp<InputWindowHandle> topErrorWindowHandle;
Jeff Browna032cc02011-03-07 16:56:21 -08001299 bool isTouchModal = false;
Jeff Brownb88102f2010-09-08 11:49:43 -07001300
1301 // Traverse windows from front to back to find touched window and outside targets.
Jeff Brown9302c872011-07-13 22:51:29 -07001302 size_t numWindows = mWindowHandles.size();
Jeff Brownb88102f2010-09-08 11:49:43 -07001303 for (size_t i = 0; i < numWindows; i++) {
Jeff Brown9302c872011-07-13 22:51:29 -07001304 sp<InputWindowHandle> windowHandle = mWindowHandles.itemAt(i);
1305 int32_t flags = windowHandle->layoutParamsFlags;
Jeff Brownb88102f2010-09-08 11:49:43 -07001306
Jeff Brown9302c872011-07-13 22:51:29 -07001307 if (flags & InputWindowHandle::FLAG_SYSTEM_ERROR) {
1308 if (topErrorWindowHandle == NULL) {
1309 topErrorWindowHandle = windowHandle;
Jeff Brownb88102f2010-09-08 11:49:43 -07001310 }
1311 }
1312
Jeff Brown9302c872011-07-13 22:51:29 -07001313 if (windowHandle->visible) {
1314 if (! (flags & InputWindowHandle::FLAG_NOT_TOUCHABLE)) {
1315 isTouchModal = (flags & (InputWindowHandle::FLAG_NOT_FOCUSABLE
1316 | InputWindowHandle::FLAG_NOT_TOUCH_MODAL)) == 0;
1317 if (isTouchModal || windowHandle->touchableRegionContainsPoint(x, y)) {
1318 if (! screenWasOff
1319 || (flags & InputWindowHandle::FLAG_TOUCHABLE_WHEN_WAKING)) {
1320 newTouchedWindowHandle = windowHandle;
Jeff Brownb88102f2010-09-08 11:49:43 -07001321 }
1322 break; // found touched window, exit window loop
1323 }
1324 }
1325
Jeff Brown01ce2e92010-09-26 22:20:12 -07001326 if (maskedAction == AMOTION_EVENT_ACTION_DOWN
Jeff Brown9302c872011-07-13 22:51:29 -07001327 && (flags & InputWindowHandle::FLAG_WATCH_OUTSIDE_TOUCH)) {
Jeff Browna032cc02011-03-07 16:56:21 -08001328 int32_t outsideTargetFlags = InputTarget::FLAG_DISPATCH_AS_OUTSIDE;
Jeff Brown9302c872011-07-13 22:51:29 -07001329 if (isWindowObscuredAtPointLocked(windowHandle, x, y)) {
Jeff Brown19dfc832010-10-05 12:26:23 -07001330 outsideTargetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1331 }
1332
Jeff Brown9302c872011-07-13 22:51:29 -07001333 mTempTouchState.addOrUpdateWindow(
1334 windowHandle, outsideTargetFlags, BitSet32(0));
Jeff Brownb88102f2010-09-08 11:49:43 -07001335 }
1336 }
1337 }
1338
1339 // If there is an error window but it is not taking focus (typically because
1340 // it is invisible) then wait for it. Any other focused window may in
1341 // fact be in ANR state.
Jeff Brown9302c872011-07-13 22:51:29 -07001342 if (topErrorWindowHandle != NULL && newTouchedWindowHandle != topErrorWindowHandle) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001343#if DEBUG_FOCUS
1344 LOGD("Waiting because system error window is pending.");
1345#endif
1346 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
1347 NULL, NULL, nextWakeupTime);
1348 injectionPermission = INJECTION_PERMISSION_UNKNOWN;
1349 goto Unresponsive;
1350 }
1351
Jeff Brown01ce2e92010-09-26 22:20:12 -07001352 // Figure out whether splitting will be allowed for this window.
Jeff Brown9302c872011-07-13 22:51:29 -07001353 if (newTouchedWindowHandle != NULL && newTouchedWindowHandle->supportsSplitTouch()) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001354 // New window supports splitting.
1355 isSplit = true;
1356 } else if (isSplit) {
1357 // New window does not support splitting but we have already split events.
1358 // Assign the pointer to the first foreground window we find.
1359 // (May be NULL which is why we put this code block before the next check.)
Jeff Brown9302c872011-07-13 22:51:29 -07001360 newTouchedWindowHandle = mTempTouchState.getFirstForegroundWindowHandle();
Jeff Brown01ce2e92010-09-26 22:20:12 -07001361 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001362
Jeff Brownb88102f2010-09-08 11:49:43 -07001363 // If we did not find a touched window then fail.
Jeff Brown9302c872011-07-13 22:51:29 -07001364 if (newTouchedWindowHandle == NULL) {
1365 if (mFocusedApplicationHandle != NULL) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001366#if DEBUG_FOCUS
1367 LOGD("Waiting because there is no touched window but there is a "
Jeff Brown519e0242010-09-15 15:18:56 -07001368 "focused application that may eventually add a new window: %s.",
Jeff Brown9302c872011-07-13 22:51:29 -07001369 getApplicationWindowLabelLocked(mFocusedApplicationHandle, NULL).string());
Jeff Brownb88102f2010-09-08 11:49:43 -07001370#endif
1371 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brown9302c872011-07-13 22:51:29 -07001372 mFocusedApplicationHandle, NULL, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -07001373 goto Unresponsive;
1374 }
1375
1376 LOGI("Dropping event because there is no touched window or focused application.");
1377 injectionResult = INPUT_EVENT_INJECTION_FAILED;
Jeff Brownb88102f2010-09-08 11:49:43 -07001378 goto Failed;
1379 }
1380
Jeff Brown19dfc832010-10-05 12:26:23 -07001381 // Set target flags.
Jeff Browna032cc02011-03-07 16:56:21 -08001382 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
Jeff Brown19dfc832010-10-05 12:26:23 -07001383 if (isSplit) {
1384 targetFlags |= InputTarget::FLAG_SPLIT;
1385 }
Jeff Brown9302c872011-07-13 22:51:29 -07001386 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
Jeff Brown19dfc832010-10-05 12:26:23 -07001387 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1388 }
1389
Jeff Browna032cc02011-03-07 16:56:21 -08001390 // Update hover state.
1391 if (isHoverAction) {
Jeff Brown9302c872011-07-13 22:51:29 -07001392 newHoverWindowHandle = newTouchedWindowHandle;
Jeff Browna032cc02011-03-07 16:56:21 -08001393
1394 // Ensure all subsequent motion samples are also within the touched window.
1395 // Set *outSplitBatchAfterSample to the sample before the first one that is not
1396 // within the touched window.
1397 if (!isTouchModal) {
1398 while (sample->next) {
Jeff Brown9302c872011-07-13 22:51:29 -07001399 if (!newHoverWindowHandle->touchableRegionContainsPoint(
Jeff Browna032cc02011-03-07 16:56:21 -08001400 sample->next->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X),
1401 sample->next->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y))) {
1402 *outSplitBatchAfterSample = sample;
1403 break;
1404 }
1405 sample = sample->next;
1406 }
1407 }
1408 } else if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
Jeff Brown9302c872011-07-13 22:51:29 -07001409 newHoverWindowHandle = mLastHoverWindowHandle;
Jeff Browna032cc02011-03-07 16:56:21 -08001410 }
1411
Jeff Brown01ce2e92010-09-26 22:20:12 -07001412 // Update the temporary touch state.
1413 BitSet32 pointerIds;
1414 if (isSplit) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07001415 uint32_t pointerId = entry->pointerProperties[pointerIndex].id;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001416 pointerIds.markBit(pointerId);
Jeff Brownb88102f2010-09-08 11:49:43 -07001417 }
Jeff Brown9302c872011-07-13 22:51:29 -07001418 mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Jeff Brownb88102f2010-09-08 11:49:43 -07001419 } else {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001420 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
Jeff Brownb88102f2010-09-08 11:49:43 -07001421
1422 // If the pointer is not currently down, then ignore the event.
Jeff Brown01ce2e92010-09-26 22:20:12 -07001423 if (! mTempTouchState.down) {
Jeff Browna2cc28d2011-03-25 11:58:46 -07001424#if DEBUG_FOCUS
Jeff Brown76860e32010-10-25 17:37:46 -07001425 LOGD("Dropping event because the pointer is not down or we previously "
1426 "dropped the pointer down event.");
1427#endif
Jeff Brownb88102f2010-09-08 11:49:43 -07001428 injectionResult = INPUT_EVENT_INJECTION_FAILED;
Jeff Brownb88102f2010-09-08 11:49:43 -07001429 goto Failed;
1430 }
Jeff Brown98db5fa2011-06-08 15:37:10 -07001431
1432 // Check whether touches should slip outside of the current foreground window.
1433 if (maskedAction == AMOTION_EVENT_ACTION_MOVE
1434 && entry->pointerCount == 1
1435 && mTempTouchState.isSlippery()) {
1436 const MotionSample* sample = &entry->firstSample;
1437 int32_t x = int32_t(sample->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
1438 int32_t y = int32_t(sample->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
1439
Jeff Brown9302c872011-07-13 22:51:29 -07001440 sp<InputWindowHandle> oldTouchedWindowHandle =
1441 mTempTouchState.getFirstForegroundWindowHandle();
1442 sp<InputWindowHandle> newTouchedWindowHandle = findTouchedWindowAtLocked(x, y);
1443 if (oldTouchedWindowHandle != newTouchedWindowHandle
1444 && newTouchedWindowHandle != NULL) {
Jeff Brown98db5fa2011-06-08 15:37:10 -07001445#if DEBUG_FOCUS
1446 LOGD("Touch is slipping out of window %s into window %s.",
Jeff Brown9302c872011-07-13 22:51:29 -07001447 oldTouchedWindowHandle->name.string(),
1448 newTouchedWindowHandle->name.string());
Jeff Brown98db5fa2011-06-08 15:37:10 -07001449#endif
1450 // Make a slippery exit from the old window.
Jeff Brown9302c872011-07-13 22:51:29 -07001451 mTempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
Jeff Brown98db5fa2011-06-08 15:37:10 -07001452 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT, BitSet32(0));
1453
1454 // Make a slippery entrance into the new window.
Jeff Brown9302c872011-07-13 22:51:29 -07001455 if (newTouchedWindowHandle->supportsSplitTouch()) {
Jeff Brown98db5fa2011-06-08 15:37:10 -07001456 isSplit = true;
1457 }
1458
1459 int32_t targetFlags = InputTarget::FLAG_FOREGROUND
1460 | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
1461 if (isSplit) {
1462 targetFlags |= InputTarget::FLAG_SPLIT;
1463 }
Jeff Brown9302c872011-07-13 22:51:29 -07001464 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
Jeff Brown98db5fa2011-06-08 15:37:10 -07001465 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1466 }
1467
1468 BitSet32 pointerIds;
1469 if (isSplit) {
1470 pointerIds.markBit(entry->pointerProperties[0].id);
1471 }
Jeff Brown9302c872011-07-13 22:51:29 -07001472 mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Jeff Brown98db5fa2011-06-08 15:37:10 -07001473
1474 // Split the batch here so we send exactly one sample.
1475 *outSplitBatchAfterSample = &entry->firstSample;
1476 }
1477 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001478 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001479
Jeff Brown9302c872011-07-13 22:51:29 -07001480 if (newHoverWindowHandle != mLastHoverWindowHandle) {
Jeff Browna032cc02011-03-07 16:56:21 -08001481 // Split the batch here so we send exactly one sample as part of ENTER or EXIT.
1482 *outSplitBatchAfterSample = &entry->firstSample;
1483
1484 // Let the previous window know that the hover sequence is over.
Jeff Brown9302c872011-07-13 22:51:29 -07001485 if (mLastHoverWindowHandle != NULL) {
Jeff Browna032cc02011-03-07 16:56:21 -08001486#if DEBUG_HOVER
Jeff Brown9302c872011-07-13 22:51:29 -07001487 LOGD("Sending hover exit event to window %s.", mLastHoverWindowHandle->name.string());
Jeff Browna032cc02011-03-07 16:56:21 -08001488#endif
Jeff Brown9302c872011-07-13 22:51:29 -07001489 mTempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
Jeff Browna032cc02011-03-07 16:56:21 -08001490 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
1491 }
1492
1493 // Let the new window know that the hover sequence is starting.
Jeff Brown9302c872011-07-13 22:51:29 -07001494 if (newHoverWindowHandle != NULL) {
Jeff Browna032cc02011-03-07 16:56:21 -08001495#if DEBUG_HOVER
Jeff Brown9302c872011-07-13 22:51:29 -07001496 LOGD("Sending hover enter event to window %s.", newHoverWindowHandle->name.string());
Jeff Browna032cc02011-03-07 16:56:21 -08001497#endif
Jeff Brown9302c872011-07-13 22:51:29 -07001498 mTempTouchState.addOrUpdateWindow(newHoverWindowHandle,
Jeff Browna032cc02011-03-07 16:56:21 -08001499 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER, BitSet32(0));
1500 }
1501 }
1502
Jeff Brown01ce2e92010-09-26 22:20:12 -07001503 // Check permission to inject into all touched foreground windows and ensure there
1504 // is at least one touched foreground window.
1505 {
1506 bool haveForegroundWindow = false;
1507 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1508 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1509 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1510 haveForegroundWindow = true;
Jeff Brown9302c872011-07-13 22:51:29 -07001511 if (! checkInjectionPermission(touchedWindow.windowHandle,
1512 entry->injectionState)) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001513 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1514 injectionPermission = INJECTION_PERMISSION_DENIED;
1515 goto Failed;
1516 }
1517 }
1518 }
1519 if (! haveForegroundWindow) {
Jeff Browna2cc28d2011-03-25 11:58:46 -07001520#if DEBUG_FOCUS
Jeff Brown01ce2e92010-09-26 22:20:12 -07001521 LOGD("Dropping event because there is no touched foreground window to receive it.");
Jeff Brownb88102f2010-09-08 11:49:43 -07001522#endif
1523 injectionResult = INPUT_EVENT_INJECTION_FAILED;
Jeff Brownb88102f2010-09-08 11:49:43 -07001524 goto Failed;
1525 }
1526
Jeff Brown01ce2e92010-09-26 22:20:12 -07001527 // Permission granted to injection into all touched foreground windows.
1528 injectionPermission = INJECTION_PERMISSION_GRANTED;
1529 }
Jeff Brown519e0242010-09-15 15:18:56 -07001530
Kenny Root7a9db182011-06-02 15:16:05 -07001531 // Check whether windows listening for outside touches are owned by the same UID. If it is
1532 // set the policy flag that we will not reveal coordinate information to this window.
1533 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
Jeff Brown9302c872011-07-13 22:51:29 -07001534 sp<InputWindowHandle> foregroundWindowHandle =
1535 mTempTouchState.getFirstForegroundWindowHandle();
1536 const int32_t foregroundWindowUid = foregroundWindowHandle->ownerUid;
Kenny Root7a9db182011-06-02 15:16:05 -07001537 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1538 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1539 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
Jeff Brown9302c872011-07-13 22:51:29 -07001540 sp<InputWindowHandle> inputWindowHandle = touchedWindow.windowHandle;
1541 if (inputWindowHandle->ownerUid != foregroundWindowUid) {
1542 mTempTouchState.addOrUpdateWindow(inputWindowHandle,
Kenny Root7a9db182011-06-02 15:16:05 -07001543 InputTarget::FLAG_ZERO_COORDS, BitSet32(0));
1544 }
1545 }
1546 }
1547 }
1548
Jeff Brown01ce2e92010-09-26 22:20:12 -07001549 // Ensure all touched foreground windows are ready for new input.
1550 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1551 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1552 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1553 // If the touched window is paused then keep waiting.
Jeff Brown9302c872011-07-13 22:51:29 -07001554 if (touchedWindow.windowHandle->paused) {
Jeff Browna2cc28d2011-03-25 11:58:46 -07001555#if DEBUG_FOCUS
Jeff Brown01ce2e92010-09-26 22:20:12 -07001556 LOGD("Waiting because touched window is paused.");
Jeff Brown519e0242010-09-15 15:18:56 -07001557#endif
Jeff Brown01ce2e92010-09-26 22:20:12 -07001558 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brown9302c872011-07-13 22:51:29 -07001559 NULL, touchedWindow.windowHandle, nextWakeupTime);
Jeff Brown01ce2e92010-09-26 22:20:12 -07001560 goto Unresponsive;
1561 }
1562
1563 // If the touched window is still working on previous events then keep waiting.
Jeff Brown9302c872011-07-13 22:51:29 -07001564 if (! isWindowFinishedWithPreviousInputLocked(touchedWindow.windowHandle)) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001565#if DEBUG_FOCUS
1566 LOGD("Waiting because touched window still processing previous input.");
1567#endif
1568 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brown9302c872011-07-13 22:51:29 -07001569 NULL, touchedWindow.windowHandle, nextWakeupTime);
Jeff Brown01ce2e92010-09-26 22:20:12 -07001570 goto Unresponsive;
1571 }
1572 }
1573 }
1574
1575 // If this is the first pointer going down and the touched window has a wallpaper
1576 // then also add the touched wallpaper windows so they are locked in for the duration
1577 // of the touch gesture.
Jeff Brown33bbfd22011-02-24 20:55:35 -08001578 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
1579 // engine only supports touch events. We would need to add a mechanism similar
1580 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
1581 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
Jeff Brown9302c872011-07-13 22:51:29 -07001582 sp<InputWindowHandle> foregroundWindowHandle =
1583 mTempTouchState.getFirstForegroundWindowHandle();
1584 if (foregroundWindowHandle->hasWallpaper) {
1585 for (size_t i = 0; i < mWindowHandles.size(); i++) {
1586 sp<InputWindowHandle> windowHandle = mWindowHandles.itemAt(i);
1587 if (windowHandle->layoutParamsType == InputWindowHandle::TYPE_WALLPAPER) {
1588 mTempTouchState.addOrUpdateWindow(windowHandle,
Jeff Browna032cc02011-03-07 16:56:21 -08001589 InputTarget::FLAG_WINDOW_IS_OBSCURED
1590 | InputTarget::FLAG_DISPATCH_AS_IS,
1591 BitSet32(0));
Jeff Brown01ce2e92010-09-26 22:20:12 -07001592 }
1593 }
1594 }
1595 }
1596
Jeff Brownb88102f2010-09-08 11:49:43 -07001597 // Success! Output targets.
1598 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
Jeff Brownb88102f2010-09-08 11:49:43 -07001599
Jeff Brown01ce2e92010-09-26 22:20:12 -07001600 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1601 const TouchedWindow& touchedWindow = mTempTouchState.windows.itemAt(i);
Jeff Brown9302c872011-07-13 22:51:29 -07001602 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Jeff Brown01ce2e92010-09-26 22:20:12 -07001603 touchedWindow.pointerIds);
Jeff Brownb88102f2010-09-08 11:49:43 -07001604 }
1605
Jeff Browna032cc02011-03-07 16:56:21 -08001606 // Drop the outside or hover touch windows since we will not care about them
1607 // in the next iteration.
1608 mTempTouchState.filterNonAsIsTouchWindows();
Jeff Brown01ce2e92010-09-26 22:20:12 -07001609
Jeff Brownb88102f2010-09-08 11:49:43 -07001610Failed:
1611 // Check injection permission once and for all.
1612 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001613 if (checkInjectionPermission(NULL, entry->injectionState)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001614 injectionPermission = INJECTION_PERMISSION_GRANTED;
1615 } else {
1616 injectionPermission = INJECTION_PERMISSION_DENIED;
1617 }
1618 }
1619
1620 // Update final pieces of touch state if the injector had permission.
1621 if (injectionPermission == INJECTION_PERMISSION_GRANTED) {
Jeff Brown95712852011-01-04 19:41:59 -08001622 if (!wrongDevice) {
Jeff Brown81346812011-06-28 20:08:48 -07001623 if (switchedDevice) {
1624#if DEBUG_FOCUS
1625 LOGD("Conflicting pointer actions: Switched to a different device.");
1626#endif
1627 *outConflictingPointerActions = true;
1628 }
1629
1630 if (isHoverAction) {
1631 // Started hovering, therefore no longer down.
1632 if (mTouchState.down) {
1633#if DEBUG_FOCUS
1634 LOGD("Conflicting pointer actions: Hover received while pointer was down.");
1635#endif
1636 *outConflictingPointerActions = true;
1637 }
1638 mTouchState.reset();
1639 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER
1640 || maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
1641 mTouchState.deviceId = entry->deviceId;
1642 mTouchState.source = entry->source;
1643 }
1644 } else if (maskedAction == AMOTION_EVENT_ACTION_UP
1645 || maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Jeff Brown95712852011-01-04 19:41:59 -08001646 // All pointers up or canceled.
Jeff Brown33bbfd22011-02-24 20:55:35 -08001647 mTouchState.reset();
Jeff Brown95712852011-01-04 19:41:59 -08001648 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1649 // First pointer went down.
1650 if (mTouchState.down) {
Jeff Brownb6997262010-10-08 22:31:17 -07001651#if DEBUG_FOCUS
Jeff Brown81346812011-06-28 20:08:48 -07001652 LOGD("Conflicting pointer actions: Down received while already down.");
Jeff Brownb6997262010-10-08 22:31:17 -07001653#endif
Jeff Brown81346812011-06-28 20:08:48 -07001654 *outConflictingPointerActions = true;
Jeff Brown95712852011-01-04 19:41:59 -08001655 }
Jeff Brown33bbfd22011-02-24 20:55:35 -08001656 mTouchState.copyFrom(mTempTouchState);
Jeff Brown95712852011-01-04 19:41:59 -08001657 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
1658 // One pointer went up.
1659 if (isSplit) {
1660 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07001661 uint32_t pointerId = entry->pointerProperties[pointerIndex].id;
Jeff Brownb88102f2010-09-08 11:49:43 -07001662
Jeff Brown95712852011-01-04 19:41:59 -08001663 for (size_t i = 0; i < mTempTouchState.windows.size(); ) {
1664 TouchedWindow& touchedWindow = mTempTouchState.windows.editItemAt(i);
1665 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
1666 touchedWindow.pointerIds.clearBit(pointerId);
1667 if (touchedWindow.pointerIds.isEmpty()) {
1668 mTempTouchState.windows.removeAt(i);
1669 continue;
1670 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001671 }
Jeff Brown95712852011-01-04 19:41:59 -08001672 i += 1;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001673 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001674 }
Jeff Brown33bbfd22011-02-24 20:55:35 -08001675 mTouchState.copyFrom(mTempTouchState);
1676 } else if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
1677 // Discard temporary touch state since it was only valid for this action.
1678 } else {
1679 // Save changes to touch state as-is for all other actions.
1680 mTouchState.copyFrom(mTempTouchState);
Jeff Brownb88102f2010-09-08 11:49:43 -07001681 }
Jeff Browna032cc02011-03-07 16:56:21 -08001682
1683 // Update hover state.
Jeff Brown9302c872011-07-13 22:51:29 -07001684 mLastHoverWindowHandle = newHoverWindowHandle;
Jeff Brown95712852011-01-04 19:41:59 -08001685 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001686 } else {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001687#if DEBUG_FOCUS
1688 LOGD("Not updating touch focus because injection was denied.");
1689#endif
Jeff Brownb88102f2010-09-08 11:49:43 -07001690 }
1691
1692Unresponsive:
Jeff Brown120a4592010-10-27 18:43:51 -07001693 // Reset temporary touch state to ensure we release unnecessary references to input channels.
1694 mTempTouchState.reset();
1695
Jeff Brown519e0242010-09-15 15:18:56 -07001696 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
1697 updateDispatchStatisticsLocked(currentTime, entry,
1698 injectionResult, timeSpentWaitingForApplication);
Jeff Brownb88102f2010-09-08 11:49:43 -07001699#if DEBUG_FOCUS
Jeff Brown01ce2e92010-09-26 22:20:12 -07001700 LOGD("findTouchedWindow finished: injectionResult=%d, injectionPermission=%d, "
1701 "timeSpentWaitingForApplication=%0.1fms",
Jeff Brown519e0242010-09-15 15:18:56 -07001702 injectionResult, injectionPermission, timeSpentWaitingForApplication / 1000000.0);
Jeff Brownb88102f2010-09-08 11:49:43 -07001703#endif
1704 return injectionResult;
1705}
1706
Jeff Brown9302c872011-07-13 22:51:29 -07001707void InputDispatcher::addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
1708 int32_t targetFlags, BitSet32 pointerIds) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001709 mCurrentInputTargets.push();
1710
1711 InputTarget& target = mCurrentInputTargets.editTop();
Jeff Brown9302c872011-07-13 22:51:29 -07001712 target.inputChannel = windowHandle->inputChannel;
Jeff Brownb88102f2010-09-08 11:49:43 -07001713 target.flags = targetFlags;
Jeff Brown9302c872011-07-13 22:51:29 -07001714 target.xOffset = - windowHandle->frameLeft;
1715 target.yOffset = - windowHandle->frameTop;
1716 target.scaleFactor = windowHandle->scaleFactor;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001717 target.pointerIds = pointerIds;
Jeff Brownb88102f2010-09-08 11:49:43 -07001718}
1719
1720void InputDispatcher::addMonitoringTargetsLocked() {
1721 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
1722 mCurrentInputTargets.push();
1723
1724 InputTarget& target = mCurrentInputTargets.editTop();
1725 target.inputChannel = mMonitoringChannels[i];
Jeff Brownb6110c22011-04-01 16:15:13 -07001726 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
Jeff Brownb88102f2010-09-08 11:49:43 -07001727 target.xOffset = 0;
1728 target.yOffset = 0;
Jeff Brownb6110c22011-04-01 16:15:13 -07001729 target.pointerIds.clear();
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001730 target.scaleFactor = 1.0f;
Jeff Brownb88102f2010-09-08 11:49:43 -07001731 }
1732}
1733
Jeff Brown9302c872011-07-13 22:51:29 -07001734bool InputDispatcher::checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
Jeff Brown01ce2e92010-09-26 22:20:12 -07001735 const InjectionState* injectionState) {
1736 if (injectionState
Jeff Brown9302c872011-07-13 22:51:29 -07001737 && (windowHandle == NULL || windowHandle->ownerUid != injectionState->injectorUid)
Jeff Brownb6997262010-10-08 22:31:17 -07001738 && !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Jeff Brown9302c872011-07-13 22:51:29 -07001739 if (windowHandle != NULL) {
1740 LOGW("Permission denied: injecting event from pid %d uid %d to window %s "
1741 "owned by uid %d",
Jeff Brownb6997262010-10-08 22:31:17 -07001742 injectionState->injectorPid, injectionState->injectorUid,
Jeff Brown9302c872011-07-13 22:51:29 -07001743 windowHandle->name.string(),
1744 windowHandle->ownerUid);
Jeff Brownb6997262010-10-08 22:31:17 -07001745 } else {
1746 LOGW("Permission denied: injecting event from pid %d uid %d",
1747 injectionState->injectorPid, injectionState->injectorUid);
Jeff Brownb88102f2010-09-08 11:49:43 -07001748 }
Jeff Brownb6997262010-10-08 22:31:17 -07001749 return false;
Jeff Brownb88102f2010-09-08 11:49:43 -07001750 }
1751 return true;
1752}
1753
Jeff Brown19dfc832010-10-05 12:26:23 -07001754bool InputDispatcher::isWindowObscuredAtPointLocked(
Jeff Brown9302c872011-07-13 22:51:29 -07001755 const sp<InputWindowHandle>& windowHandle, int32_t x, int32_t y) const {
1756 size_t numWindows = mWindowHandles.size();
Jeff Brownb88102f2010-09-08 11:49:43 -07001757 for (size_t i = 0; i < numWindows; i++) {
Jeff Brown9302c872011-07-13 22:51:29 -07001758 sp<InputWindowHandle> otherHandle = mWindowHandles.itemAt(i);
1759 if (otherHandle == windowHandle) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001760 break;
1761 }
Jeff Brown9302c872011-07-13 22:51:29 -07001762 if (otherHandle->visible && ! otherHandle->isTrustedOverlay()
1763 && otherHandle->frameContainsPoint(x, y)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001764 return true;
1765 }
1766 }
1767 return false;
1768}
1769
Jeff Brown9302c872011-07-13 22:51:29 -07001770bool InputDispatcher::isWindowFinishedWithPreviousInputLocked(
1771 const sp<InputWindowHandle>& windowHandle) {
1772 ssize_t connectionIndex = getConnectionIndexLocked(windowHandle->inputChannel);
Jeff Brown519e0242010-09-15 15:18:56 -07001773 if (connectionIndex >= 0) {
1774 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
1775 return connection->outboundQueue.isEmpty();
1776 } else {
1777 return true;
1778 }
1779}
1780
Jeff Brown9302c872011-07-13 22:51:29 -07001781String8 InputDispatcher::getApplicationWindowLabelLocked(
1782 const sp<InputApplicationHandle>& applicationHandle,
1783 const sp<InputWindowHandle>& windowHandle) {
1784 if (applicationHandle != NULL) {
1785 if (windowHandle != NULL) {
1786 String8 label(applicationHandle->name);
Jeff Brown519e0242010-09-15 15:18:56 -07001787 label.append(" - ");
Jeff Brown9302c872011-07-13 22:51:29 -07001788 label.append(windowHandle->name);
Jeff Brown519e0242010-09-15 15:18:56 -07001789 return label;
1790 } else {
Jeff Brown9302c872011-07-13 22:51:29 -07001791 return applicationHandle->name;
Jeff Brown519e0242010-09-15 15:18:56 -07001792 }
Jeff Brown9302c872011-07-13 22:51:29 -07001793 } else if (windowHandle != NULL) {
1794 return windowHandle->name;
Jeff Brown519e0242010-09-15 15:18:56 -07001795 } else {
1796 return String8("<unknown application or window>");
1797 }
1798}
1799
Jeff Browne2fe69e2010-10-18 13:21:23 -07001800void InputDispatcher::pokeUserActivityLocked(const EventEntry* eventEntry) {
Jeff Brown56194eb2011-03-02 19:23:13 -08001801 int32_t eventType = POWER_MANAGER_OTHER_EVENT;
Jeff Brown4d396052010-10-29 21:50:21 -07001802 switch (eventEntry->type) {
1803 case EventEntry::TYPE_MOTION: {
Jeff Browne2fe69e2010-10-18 13:21:23 -07001804 const MotionEntry* motionEntry = static_cast<const MotionEntry*>(eventEntry);
Jeff Brown4d396052010-10-29 21:50:21 -07001805 if (motionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
1806 return;
1807 }
1808
Jeff Brown56194eb2011-03-02 19:23:13 -08001809 if (MotionEvent::isTouchEvent(motionEntry->source, motionEntry->action)) {
Joe Onorato1a542c72010-11-08 09:48:20 -08001810 eventType = POWER_MANAGER_TOUCH_EVENT;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001811 }
Jeff Brown4d396052010-10-29 21:50:21 -07001812 break;
1813 }
1814 case EventEntry::TYPE_KEY: {
1815 const KeyEntry* keyEntry = static_cast<const KeyEntry*>(eventEntry);
1816 if (keyEntry->flags & AKEY_EVENT_FLAG_CANCELED) {
1817 return;
1818 }
Jeff Brown56194eb2011-03-02 19:23:13 -08001819 eventType = POWER_MANAGER_BUTTON_EVENT;
Jeff Brown4d396052010-10-29 21:50:21 -07001820 break;
1821 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001822 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001823
Jeff Brownb88102f2010-09-08 11:49:43 -07001824 CommandEntry* commandEntry = postCommandLocked(
1825 & InputDispatcher::doPokeUserActivityLockedInterruptible);
Jeff Browne2fe69e2010-10-18 13:21:23 -07001826 commandEntry->eventTime = eventEntry->eventTime;
Jeff Brownb88102f2010-09-08 11:49:43 -07001827 commandEntry->userActivityEventType = eventType;
1828}
1829
Jeff Brown7fbdc842010-06-17 20:52:56 -07001830void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
1831 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget,
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001832 bool resumeWithAppendedMotionSample) {
1833#if DEBUG_DISPATCH_CYCLE
Jeff Brown519e0242010-09-15 15:18:56 -07001834 LOGD("channel '%s' ~ prepareDispatchCycle - flags=%d, "
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001835 "xOffset=%f, yOffset=%f, scaleFactor=%f"
Jeff Brown83c09682010-12-23 17:50:18 -08001836 "pointerIds=0x%x, "
Jeff Brown01ce2e92010-09-26 22:20:12 -07001837 "resumeWithAppendedMotionSample=%s",
Jeff Brown519e0242010-09-15 15:18:56 -07001838 connection->getInputChannelName(), inputTarget->flags,
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001839 inputTarget->xOffset, inputTarget->yOffset,
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001840 inputTarget->scaleFactor, inputTarget->pointerIds.value,
Jeff Brownb88102f2010-09-08 11:49:43 -07001841 toString(resumeWithAppendedMotionSample));
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001842#endif
1843
Jeff Brown01ce2e92010-09-26 22:20:12 -07001844 // Make sure we are never called for streaming when splitting across multiple windows.
1845 bool isSplit = inputTarget->flags & InputTarget::FLAG_SPLIT;
Jeff Brownb6110c22011-04-01 16:15:13 -07001846 LOG_ASSERT(! (resumeWithAppendedMotionSample && isSplit));
Jeff Brown01ce2e92010-09-26 22:20:12 -07001847
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001848 // Skip this event if the connection status is not normal.
Jeff Brown519e0242010-09-15 15:18:56 -07001849 // We don't want to enqueue additional outbound events if the connection is broken.
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001850 if (connection->status != Connection::STATUS_NORMAL) {
Jeff Brownb6997262010-10-08 22:31:17 -07001851#if DEBUG_DISPATCH_CYCLE
1852 LOGD("channel '%s' ~ Dropping event because the channel status is %s",
Jeff Brownb88102f2010-09-08 11:49:43 -07001853 connection->getInputChannelName(), connection->getStatusLabel());
Jeff Brownb6997262010-10-08 22:31:17 -07001854#endif
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001855 return;
1856 }
1857
Jeff Brown01ce2e92010-09-26 22:20:12 -07001858 // Split a motion event if needed.
1859 if (isSplit) {
Jeff Brownb6110c22011-04-01 16:15:13 -07001860 LOG_ASSERT(eventEntry->type == EventEntry::TYPE_MOTION);
Jeff Brown01ce2e92010-09-26 22:20:12 -07001861
1862 MotionEntry* originalMotionEntry = static_cast<MotionEntry*>(eventEntry);
1863 if (inputTarget->pointerIds.count() != originalMotionEntry->pointerCount) {
1864 MotionEntry* splitMotionEntry = splitMotionEvent(
1865 originalMotionEntry, inputTarget->pointerIds);
Jeff Brown58a2da82011-01-25 16:02:22 -08001866 if (!splitMotionEntry) {
1867 return; // split event was dropped
1868 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001869#if DEBUG_FOCUS
1870 LOGD("channel '%s' ~ Split motion event.",
1871 connection->getInputChannelName());
1872 logOutboundMotionDetailsLocked(" ", splitMotionEntry);
1873#endif
1874 eventEntry = splitMotionEntry;
1875 }
1876 }
1877
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001878 // Resume the dispatch cycle with a freshly appended motion sample.
1879 // First we check that the last dispatch entry in the outbound queue is for the same
1880 // motion event to which we appended the motion sample. If we find such a dispatch
1881 // entry, and if it is currently in progress then we try to stream the new sample.
1882 bool wasEmpty = connection->outboundQueue.isEmpty();
1883
1884 if (! wasEmpty && resumeWithAppendedMotionSample) {
1885 DispatchEntry* motionEventDispatchEntry =
1886 connection->findQueuedDispatchEntryForEvent(eventEntry);
1887 if (motionEventDispatchEntry) {
1888 // If the dispatch entry is not in progress, then we must be busy dispatching an
1889 // earlier event. Not a problem, the motion event is on the outbound queue and will
1890 // be dispatched later.
1891 if (! motionEventDispatchEntry->inProgress) {
1892#if DEBUG_BATCHING
1893 LOGD("channel '%s' ~ Not streaming because the motion event has "
1894 "not yet been dispatched. "
1895 "(Waiting for earlier events to be consumed.)",
1896 connection->getInputChannelName());
1897#endif
1898 return;
1899 }
1900
1901 // If the dispatch entry is in progress but it already has a tail of pending
1902 // motion samples, then it must mean that the shared memory buffer filled up.
1903 // Not a problem, when this dispatch cycle is finished, we will eventually start
1904 // a new dispatch cycle to process the tail and that tail includes the newly
1905 // appended motion sample.
1906 if (motionEventDispatchEntry->tailMotionSample) {
1907#if DEBUG_BATCHING
1908 LOGD("channel '%s' ~ Not streaming because no new samples can "
1909 "be appended to the motion event in this dispatch cycle. "
1910 "(Waiting for next dispatch cycle to start.)",
1911 connection->getInputChannelName());
1912#endif
1913 return;
1914 }
1915
Jeff Brown81346812011-06-28 20:08:48 -07001916 // If the motion event was modified in flight, then we cannot stream the sample.
1917 if ((motionEventDispatchEntry->targetFlags & InputTarget::FLAG_DISPATCH_MASK)
1918 != InputTarget::FLAG_DISPATCH_AS_IS) {
1919#if DEBUG_BATCHING
1920 LOGD("channel '%s' ~ Not streaming because the motion event was not "
1921 "being dispatched as-is. "
1922 "(Waiting for next dispatch cycle to start.)",
1923 connection->getInputChannelName());
1924#endif
1925 return;
1926 }
1927
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001928 // The dispatch entry is in progress and is still potentially open for streaming.
1929 // Try to stream the new motion sample. This might fail if the consumer has already
1930 // consumed the motion event (or if the channel is broken).
Jeff Brown01ce2e92010-09-26 22:20:12 -07001931 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
1932 MotionSample* appendedMotionSample = motionEntry->lastSample;
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001933 status_t status;
1934 if (motionEventDispatchEntry->scaleFactor == 1.0f) {
1935 status = connection->inputPublisher.appendMotionSample(
1936 appendedMotionSample->eventTime, appendedMotionSample->pointerCoords);
1937 } else {
1938 PointerCoords scaledCoords[MAX_POINTERS];
1939 for (size_t i = 0; i < motionEntry->pointerCount; i++) {
1940 scaledCoords[i] = appendedMotionSample->pointerCoords[i];
1941 scaledCoords[i].scale(motionEventDispatchEntry->scaleFactor);
1942 }
1943 status = connection->inputPublisher.appendMotionSample(
1944 appendedMotionSample->eventTime, scaledCoords);
1945 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001946 if (status == OK) {
1947#if DEBUG_BATCHING
1948 LOGD("channel '%s' ~ Successfully streamed new motion sample.",
1949 connection->getInputChannelName());
1950#endif
1951 return;
1952 }
1953
1954#if DEBUG_BATCHING
1955 if (status == NO_MEMORY) {
1956 LOGD("channel '%s' ~ Could not append motion sample to currently "
1957 "dispatched move event because the shared memory buffer is full. "
1958 "(Waiting for next dispatch cycle to start.)",
1959 connection->getInputChannelName());
1960 } else if (status == status_t(FAILED_TRANSACTION)) {
1961 LOGD("channel '%s' ~ Could not append motion sample to currently "
Jeff Brown349703e2010-06-22 01:27:15 -07001962 "dispatched move event because the event has already been consumed. "
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001963 "(Waiting for next dispatch cycle to start.)",
1964 connection->getInputChannelName());
1965 } else {
1966 LOGD("channel '%s' ~ Could not append motion sample to currently "
1967 "dispatched move event due to an error, status=%d. "
1968 "(Waiting for next dispatch cycle to start.)",
1969 connection->getInputChannelName(), status);
1970 }
1971#endif
1972 // Failed to stream. Start a new tail of pending motion samples to dispatch
1973 // in the next cycle.
1974 motionEventDispatchEntry->tailMotionSample = appendedMotionSample;
1975 return;
1976 }
1977 }
1978
Jeff Browna032cc02011-03-07 16:56:21 -08001979 // Enqueue dispatch entries for the requested modes.
1980 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1981 resumeWithAppendedMotionSample, InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
1982 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1983 resumeWithAppendedMotionSample, InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
1984 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1985 resumeWithAppendedMotionSample, InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
1986 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1987 resumeWithAppendedMotionSample, InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brown98db5fa2011-06-08 15:37:10 -07001988 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1989 resumeWithAppendedMotionSample, InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
1990 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1991 resumeWithAppendedMotionSample, InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Jeff Browna032cc02011-03-07 16:56:21 -08001992
1993 // If the outbound queue was previously empty, start the dispatch cycle going.
Jeff Brownb6110c22011-04-01 16:15:13 -07001994 if (wasEmpty && !connection->outboundQueue.isEmpty()) {
Jeff Browna032cc02011-03-07 16:56:21 -08001995 activateConnectionLocked(connection.get());
1996 startDispatchCycleLocked(currentTime, connection);
1997 }
1998}
1999
2000void InputDispatcher::enqueueDispatchEntryLocked(
2001 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget,
2002 bool resumeWithAppendedMotionSample, int32_t dispatchMode) {
2003 int32_t inputTargetFlags = inputTarget->flags;
2004 if (!(inputTargetFlags & dispatchMode)) {
2005 return;
2006 }
2007 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
2008
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002009 // This is a new event.
2010 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Jeff Brownac386072011-07-20 15:19:50 -07002011 DispatchEntry* dispatchEntry = new DispatchEntry(eventEntry, // increments ref
Dianne Hackbornaa9d84c2011-05-09 19:00:59 -07002012 inputTargetFlags, inputTarget->xOffset, inputTarget->yOffset,
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002013 inputTarget->scaleFactor);
Jeff Brown519e0242010-09-15 15:18:56 -07002014 if (dispatchEntry->hasForegroundTarget()) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002015 incrementPendingForegroundDispatchesLocked(eventEntry);
Jeff Brown6ec402b2010-07-28 15:48:59 -07002016 }
2017
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002018 // Handle the case where we could not stream a new motion sample because the consumer has
2019 // already consumed the motion event (otherwise the corresponding dispatch entry would
2020 // still be in the outbound queue for this connection). We set the head motion sample
2021 // to the list starting with the newly appended motion sample.
2022 if (resumeWithAppendedMotionSample) {
2023#if DEBUG_BATCHING
2024 LOGD("channel '%s' ~ Preparing a new dispatch cycle for additional motion samples "
2025 "that cannot be streamed because the motion event has already been consumed.",
2026 connection->getInputChannelName());
2027#endif
2028 MotionSample* appendedMotionSample = static_cast<MotionEntry*>(eventEntry)->lastSample;
2029 dispatchEntry->headMotionSample = appendedMotionSample;
2030 }
2031
Jeff Brown81346812011-06-28 20:08:48 -07002032 // Apply target flags and update the connection's input state.
2033 switch (eventEntry->type) {
2034 case EventEntry::TYPE_KEY: {
2035 KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
2036 dispatchEntry->resolvedAction = keyEntry->action;
2037 dispatchEntry->resolvedFlags = keyEntry->flags;
2038
2039 if (!connection->inputState.trackKey(keyEntry,
2040 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags)) {
2041#if DEBUG_DISPATCH_CYCLE
2042 LOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
2043 connection->getInputChannelName());
2044#endif
2045 return; // skip the inconsistent event
2046 }
2047 break;
2048 }
2049
2050 case EventEntry::TYPE_MOTION: {
2051 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
2052 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2053 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
2054 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
2055 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
2056 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
2057 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2058 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
2059 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
2060 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
2061 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
2062 } else {
2063 dispatchEntry->resolvedAction = motionEntry->action;
2064 }
2065 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE
2066 && !connection->inputState.isHovering(
2067 motionEntry->deviceId, motionEntry->source)) {
2068#if DEBUG_DISPATCH_CYCLE
2069 LOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter event",
2070 connection->getInputChannelName());
2071#endif
2072 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2073 }
2074
2075 dispatchEntry->resolvedFlags = motionEntry->flags;
2076 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
2077 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
2078 }
2079
2080 if (!connection->inputState.trackMotion(motionEntry,
2081 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags)) {
2082#if DEBUG_DISPATCH_CYCLE
2083 LOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion event",
2084 connection->getInputChannelName());
2085#endif
2086 return; // skip the inconsistent event
2087 }
2088 break;
2089 }
2090 }
2091
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002092 // Enqueue the dispatch entry.
2093 connection->outboundQueue.enqueueAtTail(dispatchEntry);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002094}
2095
Jeff Brown7fbdc842010-06-17 20:52:56 -07002096void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Jeff Brown519e0242010-09-15 15:18:56 -07002097 const sp<Connection>& connection) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002098#if DEBUG_DISPATCH_CYCLE
2099 LOGD("channel '%s' ~ startDispatchCycle",
2100 connection->getInputChannelName());
2101#endif
2102
Jeff Brownb6110c22011-04-01 16:15:13 -07002103 LOG_ASSERT(connection->status == Connection::STATUS_NORMAL);
2104 LOG_ASSERT(! connection->outboundQueue.isEmpty());
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002105
Jeff Brownac386072011-07-20 15:19:50 -07002106 DispatchEntry* dispatchEntry = connection->outboundQueue.head;
Jeff Brownb6110c22011-04-01 16:15:13 -07002107 LOG_ASSERT(! dispatchEntry->inProgress);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002108
Jeff Brownb88102f2010-09-08 11:49:43 -07002109 // Mark the dispatch entry as in progress.
2110 dispatchEntry->inProgress = true;
2111
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002112 // Publish the event.
2113 status_t status;
Jeff Browna032cc02011-03-07 16:56:21 -08002114 EventEntry* eventEntry = dispatchEntry->eventEntry;
Jeff Brown01ce2e92010-09-26 22:20:12 -07002115 switch (eventEntry->type) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002116 case EventEntry::TYPE_KEY: {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002117 KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002118
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002119 // Publish the key event.
Jeff Brown81346812011-06-28 20:08:48 -07002120 status = connection->inputPublisher.publishKeyEvent(
2121 keyEntry->deviceId, keyEntry->source,
2122 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags,
2123 keyEntry->keyCode, keyEntry->scanCode,
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002124 keyEntry->metaState, keyEntry->repeatCount, keyEntry->downTime,
2125 keyEntry->eventTime);
2126
2127 if (status) {
2128 LOGE("channel '%s' ~ Could not publish key event, "
2129 "status=%d", connection->getInputChannelName(), status);
Jeff Brownb6997262010-10-08 22:31:17 -07002130 abortBrokenDispatchCycleLocked(currentTime, connection);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002131 return;
2132 }
2133 break;
2134 }
2135
2136 case EventEntry::TYPE_MOTION: {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002137 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002138
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002139 // If headMotionSample is non-NULL, then it points to the first new sample that we
2140 // were unable to dispatch during the previous cycle so we resume dispatching from
2141 // that point in the list of motion samples.
2142 // Otherwise, we just start from the first sample of the motion event.
2143 MotionSample* firstMotionSample = dispatchEntry->headMotionSample;
2144 if (! firstMotionSample) {
2145 firstMotionSample = & motionEntry->firstSample;
2146 }
2147
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002148 PointerCoords scaledCoords[MAX_POINTERS];
2149 const PointerCoords* usingCoords = firstMotionSample->pointerCoords;
2150
Jeff Brownd3616592010-07-16 17:21:06 -07002151 // Set the X and Y offset depending on the input source.
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002152 float xOffset, yOffset, scaleFactor;
Kenny Root7a9db182011-06-02 15:16:05 -07002153 if (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER
2154 && !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002155 scaleFactor = dispatchEntry->scaleFactor;
2156 xOffset = dispatchEntry->xOffset * scaleFactor;
2157 yOffset = dispatchEntry->yOffset * scaleFactor;
2158 if (scaleFactor != 1.0f) {
2159 for (size_t i = 0; i < motionEntry->pointerCount; i++) {
2160 scaledCoords[i] = firstMotionSample->pointerCoords[i];
2161 scaledCoords[i].scale(scaleFactor);
2162 }
2163 usingCoords = scaledCoords;
2164 }
Jeff Brownd3616592010-07-16 17:21:06 -07002165 } else {
2166 xOffset = 0.0f;
2167 yOffset = 0.0f;
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002168 scaleFactor = 1.0f;
Kenny Root7a9db182011-06-02 15:16:05 -07002169
2170 // We don't want the dispatch target to know.
2171 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
2172 for (size_t i = 0; i < motionEntry->pointerCount; i++) {
2173 scaledCoords[i].clear();
2174 }
2175 usingCoords = scaledCoords;
2176 }
Jeff Brownd3616592010-07-16 17:21:06 -07002177 }
2178
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002179 // Publish the motion event and the first motion sample.
Jeff Brown81346812011-06-28 20:08:48 -07002180 status = connection->inputPublisher.publishMotionEvent(
2181 motionEntry->deviceId, motionEntry->source,
2182 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags,
2183 motionEntry->edgeFlags, motionEntry->metaState, motionEntry->buttonState,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002184 xOffset, yOffset,
2185 motionEntry->xPrecision, motionEntry->yPrecision,
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002186 motionEntry->downTime, firstMotionSample->eventTime,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002187 motionEntry->pointerCount, motionEntry->pointerProperties,
2188 usingCoords);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002189
2190 if (status) {
2191 LOGE("channel '%s' ~ Could not publish motion event, "
2192 "status=%d", connection->getInputChannelName(), status);
Jeff Brownb6997262010-10-08 22:31:17 -07002193 abortBrokenDispatchCycleLocked(currentTime, connection);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002194 return;
2195 }
2196
Jeff Brown81346812011-06-28 20:08:48 -07002197 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_MOVE
2198 || dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Jeff Browna032cc02011-03-07 16:56:21 -08002199 // Append additional motion samples.
2200 MotionSample* nextMotionSample = firstMotionSample->next;
2201 for (; nextMotionSample != NULL; nextMotionSample = nextMotionSample->next) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002202 if (usingCoords == scaledCoords) {
Kenny Root7a9db182011-06-02 15:16:05 -07002203 if (!(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
2204 for (size_t i = 0; i < motionEntry->pointerCount; i++) {
2205 scaledCoords[i] = nextMotionSample->pointerCoords[i];
2206 scaledCoords[i].scale(scaleFactor);
2207 }
Dianne Hackborn2ba3e802011-05-11 10:59:54 -07002208 }
2209 } else {
2210 usingCoords = nextMotionSample->pointerCoords;
Dianne Hackborne7d25b72011-05-09 21:19:26 -07002211 }
Jeff Browna032cc02011-03-07 16:56:21 -08002212 status = connection->inputPublisher.appendMotionSample(
Dianne Hackbornaa9d84c2011-05-09 19:00:59 -07002213 nextMotionSample->eventTime, usingCoords);
Jeff Browna032cc02011-03-07 16:56:21 -08002214 if (status == NO_MEMORY) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002215#if DEBUG_DISPATCH_CYCLE
2216 LOGD("channel '%s' ~ Shared memory buffer full. Some motion samples will "
2217 "be sent in the next dispatch cycle.",
2218 connection->getInputChannelName());
2219#endif
Jeff Browna032cc02011-03-07 16:56:21 -08002220 break;
2221 }
2222 if (status != OK) {
2223 LOGE("channel '%s' ~ Could not append motion sample "
2224 "for a reason other than out of memory, status=%d",
2225 connection->getInputChannelName(), status);
2226 abortBrokenDispatchCycleLocked(currentTime, connection);
2227 return;
2228 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002229 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002230
Jeff Browna032cc02011-03-07 16:56:21 -08002231 // Remember the next motion sample that we could not dispatch, in case we ran out
2232 // of space in the shared memory buffer.
2233 dispatchEntry->tailMotionSample = nextMotionSample;
2234 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002235 break;
2236 }
2237
2238 default: {
Jeff Brownb6110c22011-04-01 16:15:13 -07002239 LOG_ASSERT(false);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002240 }
2241 }
2242
2243 // Send the dispatch signal.
2244 status = connection->inputPublisher.sendDispatchSignal();
2245 if (status) {
2246 LOGE("channel '%s' ~ Could not send dispatch signal, status=%d",
2247 connection->getInputChannelName(), status);
Jeff Brownb6997262010-10-08 22:31:17 -07002248 abortBrokenDispatchCycleLocked(currentTime, connection);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002249 return;
2250 }
2251
2252 // Record information about the newly started dispatch cycle.
Jeff Brown01ce2e92010-09-26 22:20:12 -07002253 connection->lastEventTime = eventEntry->eventTime;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002254 connection->lastDispatchTime = currentTime;
2255
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002256 // Notify other system components.
2257 onDispatchCycleStartedLocked(currentTime, connection);
2258}
2259
Jeff Brown7fbdc842010-06-17 20:52:56 -07002260void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Jeff Brown3915bb82010-11-05 15:02:16 -07002261 const sp<Connection>& connection, bool handled) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002262#if DEBUG_DISPATCH_CYCLE
Jeff Brown9c3cda02010-06-15 01:31:58 -07002263 LOGD("channel '%s' ~ finishDispatchCycle - %01.1fms since event, "
Jeff Brown3915bb82010-11-05 15:02:16 -07002264 "%01.1fms since dispatch, handled=%s",
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002265 connection->getInputChannelName(),
2266 connection->getEventLatencyMillis(currentTime),
Jeff Brown3915bb82010-11-05 15:02:16 -07002267 connection->getDispatchLatencyMillis(currentTime),
2268 toString(handled));
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002269#endif
2270
Jeff Brown9c3cda02010-06-15 01:31:58 -07002271 if (connection->status == Connection::STATUS_BROKEN
2272 || connection->status == Connection::STATUS_ZOMBIE) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002273 return;
2274 }
2275
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002276 // Reset the publisher since the event has been consumed.
2277 // We do this now so that the publisher can release some of its internal resources
2278 // while waiting for the next dispatch cycle to begin.
2279 status_t status = connection->inputPublisher.reset();
2280 if (status) {
2281 LOGE("channel '%s' ~ Could not reset publisher, status=%d",
2282 connection->getInputChannelName(), status);
Jeff Brownb6997262010-10-08 22:31:17 -07002283 abortBrokenDispatchCycleLocked(currentTime, connection);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002284 return;
2285 }
2286
Jeff Brown3915bb82010-11-05 15:02:16 -07002287 // Notify other system components and prepare to start the next dispatch cycle.
2288 onDispatchCycleFinishedLocked(currentTime, connection, handled);
Jeff Brownb88102f2010-09-08 11:49:43 -07002289}
2290
2291void InputDispatcher::startNextDispatchCycleLocked(nsecs_t currentTime,
2292 const sp<Connection>& connection) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002293 // Start the next dispatch cycle for this connection.
2294 while (! connection->outboundQueue.isEmpty()) {
Jeff Brownac386072011-07-20 15:19:50 -07002295 DispatchEntry* dispatchEntry = connection->outboundQueue.head;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002296 if (dispatchEntry->inProgress) {
2297 // Finish or resume current event in progress.
2298 if (dispatchEntry->tailMotionSample) {
2299 // We have a tail of undispatched motion samples.
2300 // Reuse the same DispatchEntry and start a new cycle.
2301 dispatchEntry->inProgress = false;
2302 dispatchEntry->headMotionSample = dispatchEntry->tailMotionSample;
2303 dispatchEntry->tailMotionSample = NULL;
Jeff Brown519e0242010-09-15 15:18:56 -07002304 startDispatchCycleLocked(currentTime, connection);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002305 return;
2306 }
2307 // Finished.
2308 connection->outboundQueue.dequeueAtHead();
Jeff Brown519e0242010-09-15 15:18:56 -07002309 if (dispatchEntry->hasForegroundTarget()) {
2310 decrementPendingForegroundDispatchesLocked(dispatchEntry->eventEntry);
Jeff Brown6ec402b2010-07-28 15:48:59 -07002311 }
Jeff Brownac386072011-07-20 15:19:50 -07002312 delete dispatchEntry;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002313 } else {
2314 // If the head is not in progress, then we must have already dequeued the in
Jeff Brown519e0242010-09-15 15:18:56 -07002315 // progress event, which means we actually aborted it.
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002316 // So just start the next event for this connection.
Jeff Brown519e0242010-09-15 15:18:56 -07002317 startDispatchCycleLocked(currentTime, connection);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002318 return;
2319 }
2320 }
2321
2322 // Outbound queue is empty, deactivate the connection.
Jeff Brown7fbdc842010-06-17 20:52:56 -07002323 deactivateConnectionLocked(connection.get());
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002324}
2325
Jeff Brownb6997262010-10-08 22:31:17 -07002326void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
2327 const sp<Connection>& connection) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002328#if DEBUG_DISPATCH_CYCLE
Jeff Brown83c09682010-12-23 17:50:18 -08002329 LOGD("channel '%s' ~ abortBrokenDispatchCycle",
2330 connection->getInputChannelName());
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002331#endif
2332
Jeff Brownb88102f2010-09-08 11:49:43 -07002333 // Clear the outbound queue.
Jeff Brown519e0242010-09-15 15:18:56 -07002334 drainOutboundQueueLocked(connection.get());
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002335
Jeff Brownb6997262010-10-08 22:31:17 -07002336 // The connection appears to be unrecoverably broken.
Jeff Brown9c3cda02010-06-15 01:31:58 -07002337 // Ignore already broken or zombie connections.
Jeff Brownb6997262010-10-08 22:31:17 -07002338 if (connection->status == Connection::STATUS_NORMAL) {
2339 connection->status = Connection::STATUS_BROKEN;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002340
Jeff Brownb6997262010-10-08 22:31:17 -07002341 // Notify other system components.
2342 onDispatchCycleBrokenLocked(currentTime, connection);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002343 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002344}
2345
Jeff Brown519e0242010-09-15 15:18:56 -07002346void InputDispatcher::drainOutboundQueueLocked(Connection* connection) {
2347 while (! connection->outboundQueue.isEmpty()) {
2348 DispatchEntry* dispatchEntry = connection->outboundQueue.dequeueAtHead();
2349 if (dispatchEntry->hasForegroundTarget()) {
2350 decrementPendingForegroundDispatchesLocked(dispatchEntry->eventEntry);
Jeff Brownb88102f2010-09-08 11:49:43 -07002351 }
Jeff Brownac386072011-07-20 15:19:50 -07002352 delete dispatchEntry;
Jeff Brownb88102f2010-09-08 11:49:43 -07002353 }
2354
Jeff Brown519e0242010-09-15 15:18:56 -07002355 deactivateConnectionLocked(connection);
Jeff Brownb88102f2010-09-08 11:49:43 -07002356}
2357
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002358int InputDispatcher::handleReceiveCallback(int receiveFd, int events, void* data) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002359 InputDispatcher* d = static_cast<InputDispatcher*>(data);
2360
2361 { // acquire lock
2362 AutoMutex _l(d->mLock);
2363
2364 ssize_t connectionIndex = d->mConnectionsByReceiveFd.indexOfKey(receiveFd);
2365 if (connectionIndex < 0) {
2366 LOGE("Received spurious receive callback for unknown input channel. "
2367 "fd=%d, events=0x%x", receiveFd, events);
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002368 return 0; // remove the callback
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002369 }
2370
Jeff Brown7fbdc842010-06-17 20:52:56 -07002371 nsecs_t currentTime = now();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002372
2373 sp<Connection> connection = d->mConnectionsByReceiveFd.valueAt(connectionIndex);
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002374 if (events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP)) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002375 LOGE("channel '%s' ~ Consumer closed input channel or an error occurred. "
2376 "events=0x%x", connection->getInputChannelName(), events);
Jeff Brownb6997262010-10-08 22:31:17 -07002377 d->abortBrokenDispatchCycleLocked(currentTime, connection);
Jeff Brown9c3cda02010-06-15 01:31:58 -07002378 d->runCommandsLockedInterruptible();
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002379 return 0; // remove the callback
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002380 }
2381
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002382 if (! (events & ALOOPER_EVENT_INPUT)) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002383 LOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
2384 "events=0x%x", connection->getInputChannelName(), events);
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002385 return 1;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002386 }
2387
Jeff Brown3915bb82010-11-05 15:02:16 -07002388 bool handled = false;
Jeff Brown49ed71d2010-12-06 17:13:33 -08002389 status_t status = connection->inputPublisher.receiveFinishedSignal(&handled);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002390 if (status) {
2391 LOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
2392 connection->getInputChannelName(), status);
Jeff Brownb6997262010-10-08 22:31:17 -07002393 d->abortBrokenDispatchCycleLocked(currentTime, connection);
Jeff Brown9c3cda02010-06-15 01:31:58 -07002394 d->runCommandsLockedInterruptible();
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002395 return 0; // remove the callback
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002396 }
2397
Jeff Brown3915bb82010-11-05 15:02:16 -07002398 d->finishDispatchCycleLocked(currentTime, connection, handled);
Jeff Brown9c3cda02010-06-15 01:31:58 -07002399 d->runCommandsLockedInterruptible();
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002400 return 1;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002401 } // release lock
2402}
2403
Jeff Brownb6997262010-10-08 22:31:17 -07002404void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Jeff Brownda3d5a92011-03-29 15:11:34 -07002405 const CancelationOptions& options) {
Jeff Brownb6997262010-10-08 22:31:17 -07002406 for (size_t i = 0; i < mConnectionsByReceiveFd.size(); i++) {
2407 synthesizeCancelationEventsForConnectionLocked(
Jeff Brownda3d5a92011-03-29 15:11:34 -07002408 mConnectionsByReceiveFd.valueAt(i), options);
Jeff Brownb6997262010-10-08 22:31:17 -07002409 }
2410}
2411
2412void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Jeff Brownda3d5a92011-03-29 15:11:34 -07002413 const sp<InputChannel>& channel, const CancelationOptions& options) {
Jeff Brownb6997262010-10-08 22:31:17 -07002414 ssize_t index = getConnectionIndexLocked(channel);
2415 if (index >= 0) {
2416 synthesizeCancelationEventsForConnectionLocked(
Jeff Brownda3d5a92011-03-29 15:11:34 -07002417 mConnectionsByReceiveFd.valueAt(index), options);
Jeff Brownb6997262010-10-08 22:31:17 -07002418 }
2419}
2420
2421void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
Jeff Brownda3d5a92011-03-29 15:11:34 -07002422 const sp<Connection>& connection, const CancelationOptions& options) {
Jeff Brownb6997262010-10-08 22:31:17 -07002423 nsecs_t currentTime = now();
2424
2425 mTempCancelationEvents.clear();
Jeff Brownac386072011-07-20 15:19:50 -07002426 connection->inputState.synthesizeCancelationEvents(currentTime,
Jeff Brownb6997262010-10-08 22:31:17 -07002427 mTempCancelationEvents, options);
2428
2429 if (! mTempCancelationEvents.isEmpty()
2430 && connection->status != Connection::STATUS_BROKEN) {
2431#if DEBUG_OUTBOUND_EVENT_DETAILS
2432 LOGD("channel '%s' ~ Synthesized %d cancelation events to bring channel back in sync "
Jeff Brownda3d5a92011-03-29 15:11:34 -07002433 "with reality: %s, mode=%d.",
2434 connection->getInputChannelName(), mTempCancelationEvents.size(),
2435 options.reason, options.mode);
Jeff Brownb6997262010-10-08 22:31:17 -07002436#endif
2437 for (size_t i = 0; i < mTempCancelationEvents.size(); i++) {
2438 EventEntry* cancelationEventEntry = mTempCancelationEvents.itemAt(i);
2439 switch (cancelationEventEntry->type) {
2440 case EventEntry::TYPE_KEY:
2441 logOutboundKeyDetailsLocked("cancel - ",
2442 static_cast<KeyEntry*>(cancelationEventEntry));
2443 break;
2444 case EventEntry::TYPE_MOTION:
2445 logOutboundMotionDetailsLocked("cancel - ",
2446 static_cast<MotionEntry*>(cancelationEventEntry));
2447 break;
2448 }
2449
Jeff Brown81346812011-06-28 20:08:48 -07002450 InputTarget target;
Jeff Brown9302c872011-07-13 22:51:29 -07002451 sp<InputWindowHandle> windowHandle = getWindowHandleLocked(connection->inputChannel);
2452 if (windowHandle != NULL) {
2453 target.xOffset = -windowHandle->frameLeft;
2454 target.yOffset = -windowHandle->frameTop;
2455 target.scaleFactor = windowHandle->scaleFactor;
Jeff Brownb6997262010-10-08 22:31:17 -07002456 } else {
Jeff Brown81346812011-06-28 20:08:48 -07002457 target.xOffset = 0;
2458 target.yOffset = 0;
2459 target.scaleFactor = 1.0f;
Jeff Brownb6997262010-10-08 22:31:17 -07002460 }
Jeff Brown81346812011-06-28 20:08:48 -07002461 target.inputChannel = connection->inputChannel;
2462 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
Jeff Brownb6997262010-10-08 22:31:17 -07002463
Jeff Brown81346812011-06-28 20:08:48 -07002464 enqueueDispatchEntryLocked(connection, cancelationEventEntry, // increments ref
2465 &target, false, InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brownb6997262010-10-08 22:31:17 -07002466
Jeff Brownac386072011-07-20 15:19:50 -07002467 cancelationEventEntry->release();
Jeff Brownb6997262010-10-08 22:31:17 -07002468 }
2469
Jeff Brownac386072011-07-20 15:19:50 -07002470 if (!connection->outboundQueue.head->inProgress) {
Jeff Brownb6997262010-10-08 22:31:17 -07002471 startDispatchCycleLocked(currentTime, connection);
2472 }
2473 }
2474}
2475
Jeff Brown01ce2e92010-09-26 22:20:12 -07002476InputDispatcher::MotionEntry*
2477InputDispatcher::splitMotionEvent(const MotionEntry* originalMotionEntry, BitSet32 pointerIds) {
Jeff Brownb6110c22011-04-01 16:15:13 -07002478 LOG_ASSERT(pointerIds.value != 0);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002479
2480 uint32_t splitPointerIndexMap[MAX_POINTERS];
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002481 PointerProperties splitPointerProperties[MAX_POINTERS];
Jeff Brown01ce2e92010-09-26 22:20:12 -07002482 PointerCoords splitPointerCoords[MAX_POINTERS];
2483
2484 uint32_t originalPointerCount = originalMotionEntry->pointerCount;
2485 uint32_t splitPointerCount = 0;
2486
2487 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
2488 originalPointerIndex++) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002489 const PointerProperties& pointerProperties =
2490 originalMotionEntry->pointerProperties[originalPointerIndex];
2491 uint32_t pointerId = uint32_t(pointerProperties.id);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002492 if (pointerIds.hasBit(pointerId)) {
2493 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002494 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
Jeff Brownace13b12011-03-09 17:39:48 -08002495 splitPointerCoords[splitPointerCount].copyFrom(
2496 originalMotionEntry->firstSample.pointerCoords[originalPointerIndex]);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002497 splitPointerCount += 1;
2498 }
2499 }
Jeff Brown58a2da82011-01-25 16:02:22 -08002500
2501 if (splitPointerCount != pointerIds.count()) {
2502 // This is bad. We are missing some of the pointers that we expected to deliver.
2503 // Most likely this indicates that we received an ACTION_MOVE events that has
2504 // different pointer ids than we expected based on the previous ACTION_DOWN
2505 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
2506 // in this way.
2507 LOGW("Dropping split motion event because the pointer count is %d but "
2508 "we expected there to be %d pointers. This probably means we received "
2509 "a broken sequence of pointer ids from the input device.",
2510 splitPointerCount, pointerIds.count());
2511 return NULL;
2512 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07002513
2514 int32_t action = originalMotionEntry->action;
2515 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
2516 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
2517 || maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2518 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002519 const PointerProperties& pointerProperties =
2520 originalMotionEntry->pointerProperties[originalPointerIndex];
2521 uint32_t pointerId = uint32_t(pointerProperties.id);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002522 if (pointerIds.hasBit(pointerId)) {
2523 if (pointerIds.count() == 1) {
2524 // The first/last pointer went down/up.
2525 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
2526 ? AMOTION_EVENT_ACTION_DOWN : AMOTION_EVENT_ACTION_UP;
Jeff Brown9a01d052010-09-27 16:35:11 -07002527 } else {
2528 // A secondary pointer went down/up.
2529 uint32_t splitPointerIndex = 0;
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002530 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
Jeff Brown9a01d052010-09-27 16:35:11 -07002531 splitPointerIndex += 1;
2532 }
2533 action = maskedAction | (splitPointerIndex
2534 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002535 }
2536 } else {
2537 // An unrelated pointer changed.
2538 action = AMOTION_EVENT_ACTION_MOVE;
2539 }
2540 }
2541
Jeff Brownac386072011-07-20 15:19:50 -07002542 MotionEntry* splitMotionEntry = new MotionEntry(
Jeff Brown01ce2e92010-09-26 22:20:12 -07002543 originalMotionEntry->eventTime,
2544 originalMotionEntry->deviceId,
2545 originalMotionEntry->source,
2546 originalMotionEntry->policyFlags,
2547 action,
2548 originalMotionEntry->flags,
2549 originalMotionEntry->metaState,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002550 originalMotionEntry->buttonState,
Jeff Brown01ce2e92010-09-26 22:20:12 -07002551 originalMotionEntry->edgeFlags,
2552 originalMotionEntry->xPrecision,
2553 originalMotionEntry->yPrecision,
2554 originalMotionEntry->downTime,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002555 splitPointerCount, splitPointerProperties, splitPointerCoords);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002556
2557 for (MotionSample* originalMotionSample = originalMotionEntry->firstSample.next;
2558 originalMotionSample != NULL; originalMotionSample = originalMotionSample->next) {
2559 for (uint32_t splitPointerIndex = 0; splitPointerIndex < splitPointerCount;
2560 splitPointerIndex++) {
2561 uint32_t originalPointerIndex = splitPointerIndexMap[splitPointerIndex];
Jeff Brownace13b12011-03-09 17:39:48 -08002562 splitPointerCoords[splitPointerIndex].copyFrom(
2563 originalMotionSample->pointerCoords[originalPointerIndex]);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002564 }
2565
Jeff Brownac386072011-07-20 15:19:50 -07002566 splitMotionEntry->appendSample(originalMotionSample->eventTime, splitPointerCoords);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002567 }
2568
Jeff Browna032cc02011-03-07 16:56:21 -08002569 if (originalMotionEntry->injectionState) {
2570 splitMotionEntry->injectionState = originalMotionEntry->injectionState;
2571 splitMotionEntry->injectionState->refCount += 1;
2572 }
2573
Jeff Brown01ce2e92010-09-26 22:20:12 -07002574 return splitMotionEntry;
2575}
2576
Jeff Brownbe1aa822011-07-27 16:04:54 -07002577void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002578#if DEBUG_INBOUND_EVENT_DETAILS
Jeff Brownbe1aa822011-07-27 16:04:54 -07002579 LOGD("notifyConfigurationChanged - eventTime=%lld", args->eventTime);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002580#endif
2581
Jeff Brownb88102f2010-09-08 11:49:43 -07002582 bool needWake;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002583 { // acquire lock
2584 AutoMutex _l(mLock);
2585
Jeff Brownbe1aa822011-07-27 16:04:54 -07002586 ConfigurationChangedEntry* newEntry = new ConfigurationChangedEntry(args->eventTime);
Jeff Brownb88102f2010-09-08 11:49:43 -07002587 needWake = enqueueInboundEventLocked(newEntry);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002588 } // release lock
2589
Jeff Brownb88102f2010-09-08 11:49:43 -07002590 if (needWake) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002591 mLooper->wake();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002592 }
2593}
2594
Jeff Brownbe1aa822011-07-27 16:04:54 -07002595void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002596#if DEBUG_INBOUND_EVENT_DETAILS
Jeff Brown90655042010-12-02 13:50:46 -08002597 LOGD("notifyKey - eventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, action=0x%x, "
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002598 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%lld",
Jeff Brownbe1aa822011-07-27 16:04:54 -07002599 args->eventTime, args->deviceId, args->source, args->policyFlags,
2600 args->action, args->flags, args->keyCode, args->scanCode,
2601 args->metaState, args->downTime);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002602#endif
Jeff Brownbe1aa822011-07-27 16:04:54 -07002603 if (!validateKeyEvent(args->action)) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002604 return;
2605 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002606
Jeff Brownbe1aa822011-07-27 16:04:54 -07002607 uint32_t policyFlags = args->policyFlags;
2608 int32_t flags = args->flags;
2609 int32_t metaState = args->metaState;
Jeff Brown1f245102010-11-18 20:53:46 -08002610 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
2611 policyFlags |= POLICY_FLAG_VIRTUAL;
2612 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
2613 }
Jeff Brown924c4d42011-03-07 16:40:47 -08002614 if (policyFlags & POLICY_FLAG_ALT) {
2615 metaState |= AMETA_ALT_ON | AMETA_ALT_LEFT_ON;
2616 }
2617 if (policyFlags & POLICY_FLAG_ALT_GR) {
2618 metaState |= AMETA_ALT_ON | AMETA_ALT_RIGHT_ON;
2619 }
2620 if (policyFlags & POLICY_FLAG_SHIFT) {
2621 metaState |= AMETA_SHIFT_ON | AMETA_SHIFT_LEFT_ON;
2622 }
2623 if (policyFlags & POLICY_FLAG_CAPS_LOCK) {
2624 metaState |= AMETA_CAPS_LOCK_ON;
2625 }
2626 if (policyFlags & POLICY_FLAG_FUNCTION) {
2627 metaState |= AMETA_FUNCTION_ON;
2628 }
Jeff Brown1f245102010-11-18 20:53:46 -08002629
Jeff Browne20c9e02010-10-11 14:20:19 -07002630 policyFlags |= POLICY_FLAG_TRUSTED;
Jeff Brown1f245102010-11-18 20:53:46 -08002631
2632 KeyEvent event;
Jeff Brownbe1aa822011-07-27 16:04:54 -07002633 event.initialize(args->deviceId, args->source, args->action,
2634 flags, args->keyCode, args->scanCode, metaState, 0,
2635 args->downTime, args->eventTime);
Jeff Brown1f245102010-11-18 20:53:46 -08002636
2637 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
2638
2639 if (policyFlags & POLICY_FLAG_WOKE_HERE) {
2640 flags |= AKEY_EVENT_FLAG_WOKE_HERE;
2641 }
Jeff Brownb6997262010-10-08 22:31:17 -07002642
Jeff Brownb88102f2010-09-08 11:49:43 -07002643 bool needWake;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002644 { // acquire lock
Jeff Brown0029c662011-03-30 02:25:18 -07002645 mLock.lock();
2646
2647 if (mInputFilterEnabled) {
2648 mLock.unlock();
2649
2650 policyFlags |= POLICY_FLAG_FILTERED;
2651 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2652 return; // event was consumed by the filter
2653 }
2654
2655 mLock.lock();
2656 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002657
Jeff Brown7fbdc842010-06-17 20:52:56 -07002658 int32_t repeatCount = 0;
Jeff Brownbe1aa822011-07-27 16:04:54 -07002659 KeyEntry* newEntry = new KeyEntry(args->eventTime,
2660 args->deviceId, args->source, policyFlags,
2661 args->action, flags, args->keyCode, args->scanCode,
2662 metaState, repeatCount, args->downTime);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002663
Jeff Brownb88102f2010-09-08 11:49:43 -07002664 needWake = enqueueInboundEventLocked(newEntry);
Jeff Brown0029c662011-03-30 02:25:18 -07002665 mLock.unlock();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002666 } // release lock
2667
Jeff Brownb88102f2010-09-08 11:49:43 -07002668 if (needWake) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002669 mLooper->wake();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002670 }
2671}
2672
Jeff Brownbe1aa822011-07-27 16:04:54 -07002673void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002674#if DEBUG_INBOUND_EVENT_DETAILS
Jeff Brown90655042010-12-02 13:50:46 -08002675 LOGD("notifyMotion - eventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, "
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002676 "action=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, edgeFlags=0x%x, "
Jeff Brown85a31762010-09-01 17:01:00 -07002677 "xPrecision=%f, yPrecision=%f, downTime=%lld",
Jeff Brownbe1aa822011-07-27 16:04:54 -07002678 args->eventTime, args->deviceId, args->source, args->policyFlags,
2679 args->action, args->flags, args->metaState, args->buttonState,
2680 args->edgeFlags, args->xPrecision, args->yPrecision, args->downTime);
2681 for (uint32_t i = 0; i < args->pointerCount; i++) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002682 LOGD(" Pointer %d: id=%d, toolType=%d, "
2683 "x=%f, y=%f, pressure=%f, size=%f, "
Jeff Brown85a31762010-09-01 17:01:00 -07002684 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
Jeff Brown8d608662010-08-30 03:02:23 -07002685 "orientation=%f",
Jeff Brownbe1aa822011-07-27 16:04:54 -07002686 i, args->pointerProperties[i].id,
2687 args->pointerProperties[i].toolType,
2688 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
2689 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
2690 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
2691 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
2692 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
2693 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
2694 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
2695 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
2696 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002697 }
2698#endif
Jeff Brownbe1aa822011-07-27 16:04:54 -07002699 if (!validateMotionEvent(args->action, args->pointerCount, args->pointerProperties)) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002700 return;
2701 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002702
Jeff Brownbe1aa822011-07-27 16:04:54 -07002703 uint32_t policyFlags = args->policyFlags;
Jeff Browne20c9e02010-10-11 14:20:19 -07002704 policyFlags |= POLICY_FLAG_TRUSTED;
Jeff Brownbe1aa822011-07-27 16:04:54 -07002705 mPolicy->interceptMotionBeforeQueueing(args->eventTime, /*byref*/ policyFlags);
Jeff Brownb6997262010-10-08 22:31:17 -07002706
Jeff Brownb88102f2010-09-08 11:49:43 -07002707 bool needWake;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002708 { // acquire lock
Jeff Brown0029c662011-03-30 02:25:18 -07002709 mLock.lock();
2710
2711 if (mInputFilterEnabled) {
2712 mLock.unlock();
2713
2714 MotionEvent event;
Jeff Brownbe1aa822011-07-27 16:04:54 -07002715 event.initialize(args->deviceId, args->source, args->action, args->flags,
2716 args->edgeFlags, args->metaState, args->buttonState, 0, 0,
2717 args->xPrecision, args->yPrecision,
2718 args->downTime, args->eventTime,
2719 args->pointerCount, args->pointerProperties, args->pointerCoords);
Jeff Brown0029c662011-03-30 02:25:18 -07002720
2721 policyFlags |= POLICY_FLAG_FILTERED;
2722 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2723 return; // event was consumed by the filter
2724 }
2725
2726 mLock.lock();
2727 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002728
2729 // Attempt batching and streaming of move events.
Jeff Brownbe1aa822011-07-27 16:04:54 -07002730 if (args->action == AMOTION_EVENT_ACTION_MOVE
2731 || args->action == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002732 // BATCHING CASE
2733 //
2734 // Try to append a move sample to the tail of the inbound queue for this device.
2735 // Give up if we encounter a non-move motion event for this device since that
2736 // means we cannot append any new samples until a new motion event has started.
Jeff Brownac386072011-07-20 15:19:50 -07002737 for (EventEntry* entry = mInboundQueue.tail; entry; entry = entry->prev) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002738 if (entry->type != EventEntry::TYPE_MOTION) {
2739 // Keep looking for motion events.
2740 continue;
2741 }
2742
2743 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
Jeff Brownbe1aa822011-07-27 16:04:54 -07002744 if (motionEntry->deviceId != args->deviceId
2745 || motionEntry->source != args->source) {
Jeff Brownefd32662011-03-08 15:13:06 -08002746 // Keep looking for this device and source.
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002747 continue;
2748 }
2749
Jeff Brownbe1aa822011-07-27 16:04:54 -07002750 if (!motionEntry->canAppendSamples(args->action,
2751 args->pointerCount, args->pointerProperties)) {
Jeff Brownefd32662011-03-08 15:13:06 -08002752 // Last motion event in the queue for this device and source is
2753 // not compatible for appending new samples. Stop here.
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002754 goto NoBatchingOrStreaming;
2755 }
2756
Jeff Brown9c3cda02010-06-15 01:31:58 -07002757 // Do the batching magic.
Jeff Brownbe1aa822011-07-27 16:04:54 -07002758 batchMotionLocked(motionEntry, args->eventTime,
2759 args->metaState, args->pointerCoords,
Jeff Brown4e91a182011-04-07 11:38:09 -07002760 "most recent motion event for this device and source in the inbound queue");
Jeff Brown0029c662011-03-30 02:25:18 -07002761 mLock.unlock();
Jeff Brown9c3cda02010-06-15 01:31:58 -07002762 return; // done!
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002763 }
2764
Jeff Brownf6989da2011-04-06 17:19:48 -07002765 // BATCHING ONTO PENDING EVENT CASE
2766 //
2767 // Try to append a move sample to the currently pending event, if there is one.
2768 // We can do this as long as we are still waiting to find the targets for the
2769 // event. Once the targets are locked-in we can only do streaming.
2770 if (mPendingEvent
2771 && (!mPendingEvent->dispatchInProgress || !mCurrentInputTargetsValid)
2772 && mPendingEvent->type == EventEntry::TYPE_MOTION) {
2773 MotionEntry* motionEntry = static_cast<MotionEntry*>(mPendingEvent);
Jeff Brownbe1aa822011-07-27 16:04:54 -07002774 if (motionEntry->deviceId == args->deviceId
2775 && motionEntry->source == args->source) {
2776 if (!motionEntry->canAppendSamples(args->action,
2777 args->pointerCount, args->pointerProperties)) {
Jeff Brown4e91a182011-04-07 11:38:09 -07002778 // Pending motion event is for this device and source but it is
2779 // not compatible for appending new samples. Stop here.
Jeff Brownf6989da2011-04-06 17:19:48 -07002780 goto NoBatchingOrStreaming;
2781 }
2782
Jeff Brownf6989da2011-04-06 17:19:48 -07002783 // Do the batching magic.
Jeff Brownbe1aa822011-07-27 16:04:54 -07002784 batchMotionLocked(motionEntry, args->eventTime,
2785 args->metaState, args->pointerCoords,
Jeff Brown4e91a182011-04-07 11:38:09 -07002786 "pending motion event");
Jeff Brownf6989da2011-04-06 17:19:48 -07002787 mLock.unlock();
2788 return; // done!
2789 }
2790 }
2791
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002792 // STREAMING CASE
2793 //
2794 // There is no pending motion event (of any kind) for this device in the inbound queue.
Jeff Brown519e0242010-09-15 15:18:56 -07002795 // Search the outbound queue for the current foreground targets to find a dispatched
2796 // motion event that is still in progress. If found, then, appen the new sample to
2797 // that event and push it out to all current targets. The logic in
2798 // prepareDispatchCycleLocked takes care of the case where some targets may
2799 // already have consumed the motion event by starting a new dispatch cycle if needed.
Jeff Brown9c3cda02010-06-15 01:31:58 -07002800 if (mCurrentInputTargetsValid) {
Jeff Brown519e0242010-09-15 15:18:56 -07002801 for (size_t i = 0; i < mCurrentInputTargets.size(); i++) {
2802 const InputTarget& inputTarget = mCurrentInputTargets[i];
2803 if ((inputTarget.flags & InputTarget::FLAG_FOREGROUND) == 0) {
2804 // Skip non-foreground targets. We only want to stream if there is at
2805 // least one foreground target whose dispatch is still in progress.
2806 continue;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002807 }
Jeff Brown519e0242010-09-15 15:18:56 -07002808
2809 ssize_t connectionIndex = getConnectionIndexLocked(inputTarget.inputChannel);
2810 if (connectionIndex < 0) {
2811 // Connection must no longer be valid.
2812 continue;
2813 }
2814
2815 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
2816 if (connection->outboundQueue.isEmpty()) {
2817 // This foreground target has an empty outbound queue.
2818 continue;
2819 }
2820
Jeff Brownac386072011-07-20 15:19:50 -07002821 DispatchEntry* dispatchEntry = connection->outboundQueue.head;
Jeff Brown519e0242010-09-15 15:18:56 -07002822 if (! dispatchEntry->inProgress
Jeff Brown01ce2e92010-09-26 22:20:12 -07002823 || dispatchEntry->eventEntry->type != EventEntry::TYPE_MOTION
2824 || dispatchEntry->isSplit()) {
2825 // No motion event is being dispatched, or it is being split across
2826 // windows in which case we cannot stream.
Jeff Brown519e0242010-09-15 15:18:56 -07002827 continue;
2828 }
2829
2830 MotionEntry* motionEntry = static_cast<MotionEntry*>(
2831 dispatchEntry->eventEntry);
Jeff Brownbe1aa822011-07-27 16:04:54 -07002832 if (motionEntry->action != args->action
2833 || motionEntry->deviceId != args->deviceId
2834 || motionEntry->source != args->source
2835 || motionEntry->pointerCount != args->pointerCount
Jeff Brown519e0242010-09-15 15:18:56 -07002836 || motionEntry->isInjected()) {
2837 // The motion event is not compatible with this move.
2838 continue;
2839 }
2840
Jeff Brownbe1aa822011-07-27 16:04:54 -07002841 if (args->action == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Jeff Brown9302c872011-07-13 22:51:29 -07002842 if (mLastHoverWindowHandle == NULL) {
Jeff Browna032cc02011-03-07 16:56:21 -08002843#if DEBUG_BATCHING
2844 LOGD("Not streaming hover move because there is no "
2845 "last hovered window.");
2846#endif
2847 goto NoBatchingOrStreaming;
2848 }
2849
Jeff Brown9302c872011-07-13 22:51:29 -07002850 sp<InputWindowHandle> hoverWindowHandle = findTouchedWindowAtLocked(
Jeff Brownbe1aa822011-07-27 16:04:54 -07002851 args->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X),
2852 args->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Jeff Brown9302c872011-07-13 22:51:29 -07002853 if (mLastHoverWindowHandle != hoverWindowHandle) {
Jeff Browna032cc02011-03-07 16:56:21 -08002854#if DEBUG_BATCHING
2855 LOGD("Not streaming hover move because the last hovered window "
2856 "is '%s' but the currently hovered window is '%s'.",
Jeff Brown9302c872011-07-13 22:51:29 -07002857 mLastHoverWindowHandle->name.string(),
2858 hoverWindowHandle != NULL
2859 ? hoverWindowHandle->name.string() : "<null>");
Jeff Browna032cc02011-03-07 16:56:21 -08002860#endif
2861 goto NoBatchingOrStreaming;
2862 }
2863 }
2864
Jeff Brown519e0242010-09-15 15:18:56 -07002865 // Hurray! This foreground target is currently dispatching a move event
2866 // that we can stream onto. Append the motion sample and resume dispatch.
Jeff Brownbe1aa822011-07-27 16:04:54 -07002867 motionEntry->appendSample(args->eventTime, args->pointerCoords);
Jeff Brown519e0242010-09-15 15:18:56 -07002868#if DEBUG_BATCHING
2869 LOGD("Appended motion sample onto batch for most recently dispatched "
Jeff Brown4e91a182011-04-07 11:38:09 -07002870 "motion event for this device and source in the outbound queues. "
Jeff Brown519e0242010-09-15 15:18:56 -07002871 "Attempting to stream the motion sample.");
2872#endif
2873 nsecs_t currentTime = now();
2874 dispatchEventToCurrentInputTargetsLocked(currentTime, motionEntry,
2875 true /*resumeWithAppendedMotionSample*/);
2876
2877 runCommandsLockedInterruptible();
Jeff Brown0029c662011-03-30 02:25:18 -07002878 mLock.unlock();
Jeff Brown519e0242010-09-15 15:18:56 -07002879 return; // done!
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002880 }
2881 }
2882
2883NoBatchingOrStreaming:;
2884 }
2885
2886 // Just enqueue a new motion event.
Jeff Brownbe1aa822011-07-27 16:04:54 -07002887 MotionEntry* newEntry = new MotionEntry(args->eventTime,
2888 args->deviceId, args->source, policyFlags,
2889 args->action, args->flags, args->metaState, args->buttonState,
2890 args->edgeFlags, args->xPrecision, args->yPrecision, args->downTime,
2891 args->pointerCount, args->pointerProperties, args->pointerCoords);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002892
Jeff Brownb88102f2010-09-08 11:49:43 -07002893 needWake = enqueueInboundEventLocked(newEntry);
Jeff Brown0029c662011-03-30 02:25:18 -07002894 mLock.unlock();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002895 } // release lock
2896
Jeff Brownb88102f2010-09-08 11:49:43 -07002897 if (needWake) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002898 mLooper->wake();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002899 }
2900}
2901
Jeff Brown4e91a182011-04-07 11:38:09 -07002902void InputDispatcher::batchMotionLocked(MotionEntry* entry, nsecs_t eventTime,
2903 int32_t metaState, const PointerCoords* pointerCoords, const char* eventDescription) {
2904 // Combine meta states.
2905 entry->metaState |= metaState;
2906
2907 // Coalesce this sample if not enough time has elapsed since the last sample was
2908 // initially appended to the batch.
2909 MotionSample* lastSample = entry->lastSample;
2910 long interval = eventTime - lastSample->eventTimeBeforeCoalescing;
2911 if (interval <= MOTION_SAMPLE_COALESCE_INTERVAL) {
2912 uint32_t pointerCount = entry->pointerCount;
2913 for (uint32_t i = 0; i < pointerCount; i++) {
2914 lastSample->pointerCoords[i].copyFrom(pointerCoords[i]);
2915 }
2916 lastSample->eventTime = eventTime;
2917#if DEBUG_BATCHING
2918 LOGD("Coalesced motion into last sample of batch for %s, events were %0.3f ms apart",
2919 eventDescription, interval * 0.000001f);
2920#endif
2921 return;
2922 }
2923
2924 // Append the sample.
Jeff Brownac386072011-07-20 15:19:50 -07002925 entry->appendSample(eventTime, pointerCoords);
Jeff Brown4e91a182011-04-07 11:38:09 -07002926#if DEBUG_BATCHING
2927 LOGD("Appended motion sample onto batch for %s, events were %0.3f ms apart",
2928 eventDescription, interval * 0.000001f);
2929#endif
2930}
2931
Jeff Brownbe1aa822011-07-27 16:04:54 -07002932void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
Jeff Brownb6997262010-10-08 22:31:17 -07002933#if DEBUG_INBOUND_EVENT_DETAILS
Jeff Brownbe1aa822011-07-27 16:04:54 -07002934 LOGD("notifySwitch - eventTime=%lld, policyFlags=0x%x, switchCode=%d, switchValue=%d",
2935 args->eventTime, args->policyFlags,
2936 args->switchCode, args->switchValue);
Jeff Brownb6997262010-10-08 22:31:17 -07002937#endif
2938
Jeff Brownbe1aa822011-07-27 16:04:54 -07002939 uint32_t policyFlags = args->policyFlags;
Jeff Browne20c9e02010-10-11 14:20:19 -07002940 policyFlags |= POLICY_FLAG_TRUSTED;
Jeff Brownbe1aa822011-07-27 16:04:54 -07002941 mPolicy->notifySwitch(args->eventTime,
2942 args->switchCode, args->switchValue, policyFlags);
Jeff Brownb6997262010-10-08 22:31:17 -07002943}
2944
Jeff Brown65fd2512011-08-18 11:20:58 -07002945void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
2946#if DEBUG_INBOUND_EVENT_DETAILS
2947 LOGD("notifyDeviceReset - eventTime=%lld, deviceId=%d",
2948 args->eventTime, args->deviceId);
2949#endif
2950
2951 bool needWake;
2952 { // acquire lock
2953 AutoMutex _l(mLock);
2954
2955 DeviceResetEntry* newEntry = new DeviceResetEntry(args->eventTime, args->deviceId);
2956 needWake = enqueueInboundEventLocked(newEntry);
2957 } // release lock
2958
2959 if (needWake) {
2960 mLooper->wake();
2961 }
2962}
2963
Jeff Brown7fbdc842010-06-17 20:52:56 -07002964int32_t InputDispatcher::injectInputEvent(const InputEvent* event,
Jeff Brown0029c662011-03-30 02:25:18 -07002965 int32_t injectorPid, int32_t injectorUid, int32_t syncMode, int32_t timeoutMillis,
2966 uint32_t policyFlags) {
Jeff Brown7fbdc842010-06-17 20:52:56 -07002967#if DEBUG_INBOUND_EVENT_DETAILS
2968 LOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Jeff Brown0029c662011-03-30 02:25:18 -07002969 "syncMode=%d, timeoutMillis=%d, policyFlags=0x%08x",
2970 event->getType(), injectorPid, injectorUid, syncMode, timeoutMillis, policyFlags);
Jeff Brown7fbdc842010-06-17 20:52:56 -07002971#endif
2972
2973 nsecs_t endTime = now() + milliseconds_to_nanoseconds(timeoutMillis);
Jeff Browne20c9e02010-10-11 14:20:19 -07002974
Jeff Brown0029c662011-03-30 02:25:18 -07002975 policyFlags |= POLICY_FLAG_INJECTED;
Jeff Browne20c9e02010-10-11 14:20:19 -07002976 if (hasInjectionPermission(injectorPid, injectorUid)) {
2977 policyFlags |= POLICY_FLAG_TRUSTED;
2978 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07002979
Jeff Brownb6997262010-10-08 22:31:17 -07002980 EventEntry* injectedEntry;
2981 switch (event->getType()) {
2982 case AINPUT_EVENT_TYPE_KEY: {
2983 const KeyEvent* keyEvent = static_cast<const KeyEvent*>(event);
2984 int32_t action = keyEvent->getAction();
2985 if (! validateKeyEvent(action)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07002986 return INPUT_EVENT_INJECTION_FAILED;
2987 }
2988
Jeff Brownb6997262010-10-08 22:31:17 -07002989 int32_t flags = keyEvent->getFlags();
Jeff Brown1f245102010-11-18 20:53:46 -08002990 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
2991 policyFlags |= POLICY_FLAG_VIRTUAL;
2992 }
2993
Jeff Brown0029c662011-03-30 02:25:18 -07002994 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
2995 mPolicy->interceptKeyBeforeQueueing(keyEvent, /*byref*/ policyFlags);
2996 }
Jeff Brown1f245102010-11-18 20:53:46 -08002997
2998 if (policyFlags & POLICY_FLAG_WOKE_HERE) {
2999 flags |= AKEY_EVENT_FLAG_WOKE_HERE;
3000 }
Jeff Brown6ec402b2010-07-28 15:48:59 -07003001
Jeff Brownb6997262010-10-08 22:31:17 -07003002 mLock.lock();
Jeff Brownac386072011-07-20 15:19:50 -07003003 injectedEntry = new KeyEntry(keyEvent->getEventTime(),
Jeff Brown1f245102010-11-18 20:53:46 -08003004 keyEvent->getDeviceId(), keyEvent->getSource(),
3005 policyFlags, action, flags,
3006 keyEvent->getKeyCode(), keyEvent->getScanCode(), keyEvent->getMetaState(),
Jeff Brownb6997262010-10-08 22:31:17 -07003007 keyEvent->getRepeatCount(), keyEvent->getDownTime());
3008 break;
3009 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07003010
Jeff Brownb6997262010-10-08 22:31:17 -07003011 case AINPUT_EVENT_TYPE_MOTION: {
3012 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
3013 int32_t action = motionEvent->getAction();
3014 size_t pointerCount = motionEvent->getPointerCount();
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003015 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
3016 if (! validateMotionEvent(action, pointerCount, pointerProperties)) {
Jeff Brownb6997262010-10-08 22:31:17 -07003017 return INPUT_EVENT_INJECTION_FAILED;
3018 }
3019
Jeff Brown0029c662011-03-30 02:25:18 -07003020 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3021 nsecs_t eventTime = motionEvent->getEventTime();
3022 mPolicy->interceptMotionBeforeQueueing(eventTime, /*byref*/ policyFlags);
3023 }
Jeff Brownb6997262010-10-08 22:31:17 -07003024
3025 mLock.lock();
3026 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
3027 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
Jeff Brownac386072011-07-20 15:19:50 -07003028 MotionEntry* motionEntry = new MotionEntry(*sampleEventTimes,
Jeff Brownb6997262010-10-08 22:31:17 -07003029 motionEvent->getDeviceId(), motionEvent->getSource(), policyFlags,
3030 action, motionEvent->getFlags(),
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003031 motionEvent->getMetaState(), motionEvent->getButtonState(),
3032 motionEvent->getEdgeFlags(),
Jeff Brownb6997262010-10-08 22:31:17 -07003033 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
3034 motionEvent->getDownTime(), uint32_t(pointerCount),
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003035 pointerProperties, samplePointerCoords);
Jeff Brownb6997262010-10-08 22:31:17 -07003036 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
3037 sampleEventTimes += 1;
3038 samplePointerCoords += pointerCount;
Jeff Brownac386072011-07-20 15:19:50 -07003039 motionEntry->appendSample(*sampleEventTimes, samplePointerCoords);
Jeff Brownb6997262010-10-08 22:31:17 -07003040 }
3041 injectedEntry = motionEntry;
3042 break;
3043 }
3044
3045 default:
3046 LOGW("Cannot inject event of type %d", event->getType());
3047 return INPUT_EVENT_INJECTION_FAILED;
3048 }
3049
Jeff Brownac386072011-07-20 15:19:50 -07003050 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
Jeff Brownb6997262010-10-08 22:31:17 -07003051 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
3052 injectionState->injectionIsAsync = true;
3053 }
3054
3055 injectionState->refCount += 1;
3056 injectedEntry->injectionState = injectionState;
3057
3058 bool needWake = enqueueInboundEventLocked(injectedEntry);
3059 mLock.unlock();
Jeff Brown7fbdc842010-06-17 20:52:56 -07003060
Jeff Brownb88102f2010-09-08 11:49:43 -07003061 if (needWake) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07003062 mLooper->wake();
Jeff Brown7fbdc842010-06-17 20:52:56 -07003063 }
3064
3065 int32_t injectionResult;
3066 { // acquire lock
3067 AutoMutex _l(mLock);
3068
Jeff Brown6ec402b2010-07-28 15:48:59 -07003069 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
3070 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
3071 } else {
3072 for (;;) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07003073 injectionResult = injectionState->injectionResult;
Jeff Brown6ec402b2010-07-28 15:48:59 -07003074 if (injectionResult != INPUT_EVENT_INJECTION_PENDING) {
3075 break;
3076 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07003077
Jeff Brown7fbdc842010-06-17 20:52:56 -07003078 nsecs_t remainingTimeout = endTime - now();
3079 if (remainingTimeout <= 0) {
Jeff Brown6ec402b2010-07-28 15:48:59 -07003080#if DEBUG_INJECTION
3081 LOGD("injectInputEvent - Timed out waiting for injection result "
3082 "to become available.");
3083#endif
Jeff Brown7fbdc842010-06-17 20:52:56 -07003084 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
3085 break;
3086 }
3087
Jeff Brown6ec402b2010-07-28 15:48:59 -07003088 mInjectionResultAvailableCondition.waitRelative(mLock, remainingTimeout);
3089 }
3090
3091 if (injectionResult == INPUT_EVENT_INJECTION_SUCCEEDED
3092 && syncMode == INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07003093 while (injectionState->pendingForegroundDispatches != 0) {
Jeff Brown6ec402b2010-07-28 15:48:59 -07003094#if DEBUG_INJECTION
Jeff Brown519e0242010-09-15 15:18:56 -07003095 LOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
Jeff Brown01ce2e92010-09-26 22:20:12 -07003096 injectionState->pendingForegroundDispatches);
Jeff Brown6ec402b2010-07-28 15:48:59 -07003097#endif
3098 nsecs_t remainingTimeout = endTime - now();
3099 if (remainingTimeout <= 0) {
3100#if DEBUG_INJECTION
Jeff Brown519e0242010-09-15 15:18:56 -07003101 LOGD("injectInputEvent - Timed out waiting for pending foreground "
Jeff Brown6ec402b2010-07-28 15:48:59 -07003102 "dispatches to finish.");
3103#endif
3104 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
3105 break;
3106 }
3107
3108 mInjectionSyncFinishedCondition.waitRelative(mLock, remainingTimeout);
3109 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07003110 }
3111 }
3112
Jeff Brownac386072011-07-20 15:19:50 -07003113 injectionState->release();
Jeff Brown7fbdc842010-06-17 20:52:56 -07003114 } // release lock
3115
Jeff Brown6ec402b2010-07-28 15:48:59 -07003116#if DEBUG_INJECTION
3117 LOGD("injectInputEvent - Finished with result %d. "
3118 "injectorPid=%d, injectorUid=%d",
3119 injectionResult, injectorPid, injectorUid);
3120#endif
3121
Jeff Brown7fbdc842010-06-17 20:52:56 -07003122 return injectionResult;
3123}
3124
Jeff Brownb6997262010-10-08 22:31:17 -07003125bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
3126 return injectorUid == 0
3127 || mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
3128}
3129
Jeff Brown7fbdc842010-06-17 20:52:56 -07003130void InputDispatcher::setInjectionResultLocked(EventEntry* entry, int32_t injectionResult) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07003131 InjectionState* injectionState = entry->injectionState;
3132 if (injectionState) {
Jeff Brown7fbdc842010-06-17 20:52:56 -07003133#if DEBUG_INJECTION
3134 LOGD("Setting input event injection result to %d. "
3135 "injectorPid=%d, injectorUid=%d",
Jeff Brown01ce2e92010-09-26 22:20:12 -07003136 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
Jeff Brown7fbdc842010-06-17 20:52:56 -07003137#endif
3138
Jeff Brown0029c662011-03-30 02:25:18 -07003139 if (injectionState->injectionIsAsync
3140 && !(entry->policyFlags & POLICY_FLAG_FILTERED)) {
Jeff Brown6ec402b2010-07-28 15:48:59 -07003141 // Log the outcome since the injector did not wait for the injection result.
3142 switch (injectionResult) {
3143 case INPUT_EVENT_INJECTION_SUCCEEDED:
3144 LOGV("Asynchronous input event injection succeeded.");
3145 break;
3146 case INPUT_EVENT_INJECTION_FAILED:
3147 LOGW("Asynchronous input event injection failed.");
3148 break;
3149 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
3150 LOGW("Asynchronous input event injection permission denied.");
3151 break;
3152 case INPUT_EVENT_INJECTION_TIMED_OUT:
3153 LOGW("Asynchronous input event injection timed out.");
3154 break;
3155 }
3156 }
3157
Jeff Brown01ce2e92010-09-26 22:20:12 -07003158 injectionState->injectionResult = injectionResult;
Jeff Brown7fbdc842010-06-17 20:52:56 -07003159 mInjectionResultAvailableCondition.broadcast();
3160 }
3161}
3162
Jeff Brown01ce2e92010-09-26 22:20:12 -07003163void InputDispatcher::incrementPendingForegroundDispatchesLocked(EventEntry* entry) {
3164 InjectionState* injectionState = entry->injectionState;
3165 if (injectionState) {
3166 injectionState->pendingForegroundDispatches += 1;
3167 }
3168}
3169
Jeff Brown519e0242010-09-15 15:18:56 -07003170void InputDispatcher::decrementPendingForegroundDispatchesLocked(EventEntry* entry) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07003171 InjectionState* injectionState = entry->injectionState;
3172 if (injectionState) {
3173 injectionState->pendingForegroundDispatches -= 1;
Jeff Brown6ec402b2010-07-28 15:48:59 -07003174
Jeff Brown01ce2e92010-09-26 22:20:12 -07003175 if (injectionState->pendingForegroundDispatches == 0) {
3176 mInjectionSyncFinishedCondition.broadcast();
3177 }
Jeff Brownb88102f2010-09-08 11:49:43 -07003178 }
3179}
3180
Jeff Brown9302c872011-07-13 22:51:29 -07003181sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
3182 const sp<InputChannel>& inputChannel) const {
3183 size_t numWindows = mWindowHandles.size();
3184 for (size_t i = 0; i < numWindows; i++) {
3185 const sp<InputWindowHandle>& windowHandle = mWindowHandles.itemAt(i);
3186 if (windowHandle->inputChannel == inputChannel) {
3187 return windowHandle;
Jeff Brown01ce2e92010-09-26 22:20:12 -07003188 }
3189 }
3190 return NULL;
3191}
3192
Jeff Brown9302c872011-07-13 22:51:29 -07003193bool InputDispatcher::hasWindowHandleLocked(
3194 const sp<InputWindowHandle>& windowHandle) const {
3195 size_t numWindows = mWindowHandles.size();
3196 for (size_t i = 0; i < numWindows; i++) {
3197 if (mWindowHandles.itemAt(i) == windowHandle) {
3198 return true;
3199 }
3200 }
3201 return false;
3202}
3203
3204void InputDispatcher::setInputWindows(const Vector<sp<InputWindowHandle> >& inputWindowHandles) {
Jeff Brownb88102f2010-09-08 11:49:43 -07003205#if DEBUG_FOCUS
3206 LOGD("setInputWindows");
3207#endif
3208 { // acquire lock
3209 AutoMutex _l(mLock);
3210
Jeff Brown9302c872011-07-13 22:51:29 -07003211 mWindowHandles = inputWindowHandles;
Jeff Brownb6997262010-10-08 22:31:17 -07003212
Jeff Brown9302c872011-07-13 22:51:29 -07003213 sp<InputWindowHandle> newFocusedWindowHandle;
3214 bool foundHoveredWindow = false;
3215 for (size_t i = 0; i < mWindowHandles.size(); i++) {
3216 const sp<InputWindowHandle>& windowHandle = mWindowHandles.itemAt(i);
3217 if (!windowHandle->update() || windowHandle->inputChannel == NULL) {
3218 mWindowHandles.removeAt(i--);
3219 continue;
3220 }
3221 if (windowHandle->hasFocus) {
3222 newFocusedWindowHandle = windowHandle;
3223 }
3224 if (windowHandle == mLastHoverWindowHandle) {
3225 foundHoveredWindow = true;
Jeff Brownb88102f2010-09-08 11:49:43 -07003226 }
3227 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07003228
Jeff Brown9302c872011-07-13 22:51:29 -07003229 if (!foundHoveredWindow) {
3230 mLastHoverWindowHandle = NULL;
3231 }
3232
3233 if (mFocusedWindowHandle != newFocusedWindowHandle) {
3234 if (mFocusedWindowHandle != NULL) {
Jeff Brownb6997262010-10-08 22:31:17 -07003235#if DEBUG_FOCUS
3236 LOGD("Focus left window: %s",
Jeff Brown9302c872011-07-13 22:51:29 -07003237 mFocusedWindowHandle->name.string());
Jeff Brownb6997262010-10-08 22:31:17 -07003238#endif
Christopher Tated9be36c2011-08-16 16:09:33 -07003239 if (mFocusedWindowHandle->inputChannel != NULL) {
3240 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
3241 "focus left window");
3242 synthesizeCancelationEventsForInputChannelLocked(
3243 mFocusedWindowHandle->inputChannel, options);
3244 }
Jeff Brownb6997262010-10-08 22:31:17 -07003245 }
Jeff Brown9302c872011-07-13 22:51:29 -07003246 if (newFocusedWindowHandle != NULL) {
Jeff Brownb6997262010-10-08 22:31:17 -07003247#if DEBUG_FOCUS
Jeff Brown9302c872011-07-13 22:51:29 -07003248 LOGD("Focus entered window: %s",
3249 newFocusedWindowHandle->name.string());
Jeff Brownb6997262010-10-08 22:31:17 -07003250#endif
Jeff Brown9302c872011-07-13 22:51:29 -07003251 }
3252 mFocusedWindowHandle = newFocusedWindowHandle;
Jeff Brownb6997262010-10-08 22:31:17 -07003253 }
3254
Jeff Brown9302c872011-07-13 22:51:29 -07003255 for (size_t i = 0; i < mTouchState.windows.size(); i++) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07003256 TouchedWindow& touchedWindow = mTouchState.windows.editItemAt(i);
Jeff Brown9302c872011-07-13 22:51:29 -07003257 if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
Jeff Brownb6997262010-10-08 22:31:17 -07003258#if DEBUG_FOCUS
Jeff Brown9302c872011-07-13 22:51:29 -07003259 LOGD("Touched window was removed: %s", touchedWindow.windowHandle->name.string());
Jeff Brownb6997262010-10-08 22:31:17 -07003260#endif
Christopher Tated9be36c2011-08-16 16:09:33 -07003261 if (touchedWindow.windowHandle->inputChannel != NULL) {
3262 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
3263 "touched window was removed");
3264 synthesizeCancelationEventsForInputChannelLocked(
3265 touchedWindow.windowHandle->inputChannel, options);
3266 }
Jeff Brown9302c872011-07-13 22:51:29 -07003267 mTouchState.windows.removeAt(i--);
Jeff Brown01ce2e92010-09-26 22:20:12 -07003268 }
3269 }
Jeff Brownb88102f2010-09-08 11:49:43 -07003270 } // release lock
3271
3272 // Wake up poll loop since it may need to make new input dispatching choices.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07003273 mLooper->wake();
Jeff Brownb88102f2010-09-08 11:49:43 -07003274}
3275
Jeff Brown9302c872011-07-13 22:51:29 -07003276void InputDispatcher::setFocusedApplication(
3277 const sp<InputApplicationHandle>& inputApplicationHandle) {
Jeff Brownb88102f2010-09-08 11:49:43 -07003278#if DEBUG_FOCUS
3279 LOGD("setFocusedApplication");
3280#endif
3281 { // acquire lock
3282 AutoMutex _l(mLock);
3283
Jeff Brown9302c872011-07-13 22:51:29 -07003284 if (inputApplicationHandle != NULL && inputApplicationHandle->update()) {
Jeff Brown5ea29ab2011-07-27 11:50:51 -07003285 if (mFocusedApplicationHandle != inputApplicationHandle) {
3286 if (mFocusedApplicationHandle != NULL) {
3287 resetTargetsLocked();
3288 }
3289 mFocusedApplicationHandle = inputApplicationHandle;
3290 }
3291 } else if (mFocusedApplicationHandle != NULL) {
3292 resetTargetsLocked();
Jeff Brown9302c872011-07-13 22:51:29 -07003293 mFocusedApplicationHandle.clear();
Jeff Brownb88102f2010-09-08 11:49:43 -07003294 }
3295
3296#if DEBUG_FOCUS
Jeff Brownb6997262010-10-08 22:31:17 -07003297 //logDispatchStateLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -07003298#endif
3299 } // release lock
3300
3301 // Wake up poll loop since it may need to make new input dispatching choices.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07003302 mLooper->wake();
Jeff Brownb88102f2010-09-08 11:49:43 -07003303}
3304
Jeff Brownb88102f2010-09-08 11:49:43 -07003305void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
3306#if DEBUG_FOCUS
3307 LOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
3308#endif
3309
3310 bool changed;
3311 { // acquire lock
3312 AutoMutex _l(mLock);
3313
3314 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
Jeff Brown120a4592010-10-27 18:43:51 -07003315 if (mDispatchFrozen && !frozen) {
Jeff Brownb88102f2010-09-08 11:49:43 -07003316 resetANRTimeoutsLocked();
3317 }
3318
Jeff Brown120a4592010-10-27 18:43:51 -07003319 if (mDispatchEnabled && !enabled) {
3320 resetAndDropEverythingLocked("dispatcher is being disabled");
3321 }
3322
Jeff Brownb88102f2010-09-08 11:49:43 -07003323 mDispatchEnabled = enabled;
3324 mDispatchFrozen = frozen;
3325 changed = true;
3326 } else {
3327 changed = false;
3328 }
3329
3330#if DEBUG_FOCUS
Jeff Brownb6997262010-10-08 22:31:17 -07003331 //logDispatchStateLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -07003332#endif
3333 } // release lock
3334
3335 if (changed) {
3336 // Wake up poll loop since it may need to make new input dispatching choices.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07003337 mLooper->wake();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003338 }
3339}
3340
Jeff Brown0029c662011-03-30 02:25:18 -07003341void InputDispatcher::setInputFilterEnabled(bool enabled) {
3342#if DEBUG_FOCUS
3343 LOGD("setInputFilterEnabled: enabled=%d", enabled);
3344#endif
3345
3346 { // acquire lock
3347 AutoMutex _l(mLock);
3348
3349 if (mInputFilterEnabled == enabled) {
3350 return;
3351 }
3352
3353 mInputFilterEnabled = enabled;
3354 resetAndDropEverythingLocked("input filter is being enabled or disabled");
3355 } // release lock
3356
3357 // Wake up poll loop since there might be work to do to drop everything.
3358 mLooper->wake();
3359}
3360
Jeff Browne6504122010-09-27 14:52:15 -07003361bool InputDispatcher::transferTouchFocus(const sp<InputChannel>& fromChannel,
3362 const sp<InputChannel>& toChannel) {
3363#if DEBUG_FOCUS
3364 LOGD("transferTouchFocus: fromChannel=%s, toChannel=%s",
3365 fromChannel->getName().string(), toChannel->getName().string());
3366#endif
3367 { // acquire lock
3368 AutoMutex _l(mLock);
3369
Jeff Brown9302c872011-07-13 22:51:29 -07003370 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromChannel);
3371 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toChannel);
3372 if (fromWindowHandle == NULL || toWindowHandle == NULL) {
Jeff Browne6504122010-09-27 14:52:15 -07003373#if DEBUG_FOCUS
3374 LOGD("Cannot transfer focus because from or to window not found.");
3375#endif
3376 return false;
3377 }
Jeff Brown9302c872011-07-13 22:51:29 -07003378 if (fromWindowHandle == toWindowHandle) {
Jeff Browne6504122010-09-27 14:52:15 -07003379#if DEBUG_FOCUS
3380 LOGD("Trivial transfer to same window.");
3381#endif
3382 return true;
3383 }
3384
3385 bool found = false;
3386 for (size_t i = 0; i < mTouchState.windows.size(); i++) {
3387 const TouchedWindow& touchedWindow = mTouchState.windows[i];
Jeff Brown9302c872011-07-13 22:51:29 -07003388 if (touchedWindow.windowHandle == fromWindowHandle) {
Jeff Browne6504122010-09-27 14:52:15 -07003389 int32_t oldTargetFlags = touchedWindow.targetFlags;
3390 BitSet32 pointerIds = touchedWindow.pointerIds;
3391
3392 mTouchState.windows.removeAt(i);
3393
Jeff Brown46e75292010-11-10 16:53:45 -08003394 int32_t newTargetFlags = oldTargetFlags
Jeff Browna032cc02011-03-07 16:56:21 -08003395 & (InputTarget::FLAG_FOREGROUND
3396 | InputTarget::FLAG_SPLIT | InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brown9302c872011-07-13 22:51:29 -07003397 mTouchState.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Jeff Browne6504122010-09-27 14:52:15 -07003398
3399 found = true;
3400 break;
3401 }
3402 }
3403
3404 if (! found) {
3405#if DEBUG_FOCUS
3406 LOGD("Focus transfer failed because from window did not have focus.");
3407#endif
3408 return false;
3409 }
3410
Jeff Brown9c9f1a32010-10-11 18:32:20 -07003411 ssize_t fromConnectionIndex = getConnectionIndexLocked(fromChannel);
3412 ssize_t toConnectionIndex = getConnectionIndexLocked(toChannel);
3413 if (fromConnectionIndex >= 0 && toConnectionIndex >= 0) {
3414 sp<Connection> fromConnection = mConnectionsByReceiveFd.valueAt(fromConnectionIndex);
3415 sp<Connection> toConnection = mConnectionsByReceiveFd.valueAt(toConnectionIndex);
3416
3417 fromConnection->inputState.copyPointerStateTo(toConnection->inputState);
Jeff Brownda3d5a92011-03-29 15:11:34 -07003418 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Jeff Brown9c9f1a32010-10-11 18:32:20 -07003419 "transferring touch focus from this window to another window");
Jeff Brownda3d5a92011-03-29 15:11:34 -07003420 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Jeff Brown9c9f1a32010-10-11 18:32:20 -07003421 }
3422
Jeff Browne6504122010-09-27 14:52:15 -07003423#if DEBUG_FOCUS
3424 logDispatchStateLocked();
3425#endif
3426 } // release lock
3427
3428 // Wake up poll loop since it may need to make new input dispatching choices.
3429 mLooper->wake();
3430 return true;
3431}
3432
Jeff Brown120a4592010-10-27 18:43:51 -07003433void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
3434#if DEBUG_FOCUS
3435 LOGD("Resetting and dropping all events (%s).", reason);
3436#endif
3437
Jeff Brownda3d5a92011-03-29 15:11:34 -07003438 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
3439 synthesizeCancelationEventsForAllConnectionsLocked(options);
Jeff Brown120a4592010-10-27 18:43:51 -07003440
3441 resetKeyRepeatLocked();
3442 releasePendingEventLocked();
3443 drainInboundQueueLocked();
3444 resetTargetsLocked();
3445
3446 mTouchState.reset();
Jeff Brown9302c872011-07-13 22:51:29 -07003447 mLastHoverWindowHandle.clear();
Jeff Brown120a4592010-10-27 18:43:51 -07003448}
3449
Jeff Brownb88102f2010-09-08 11:49:43 -07003450void InputDispatcher::logDispatchStateLocked() {
3451 String8 dump;
3452 dumpDispatchStateLocked(dump);
Jeff Brown2a95c2a2010-09-16 12:31:46 -07003453
3454 char* text = dump.lockBuffer(dump.size());
3455 char* start = text;
3456 while (*start != '\0') {
3457 char* end = strchr(start, '\n');
3458 if (*end == '\n') {
3459 *(end++) = '\0';
3460 }
3461 LOGD("%s", start);
3462 start = end;
3463 }
Jeff Brownb88102f2010-09-08 11:49:43 -07003464}
3465
3466void InputDispatcher::dumpDispatchStateLocked(String8& dump) {
Jeff Brownf2f487182010-10-01 17:46:21 -07003467 dump.appendFormat(INDENT "DispatchEnabled: %d\n", mDispatchEnabled);
3468 dump.appendFormat(INDENT "DispatchFrozen: %d\n", mDispatchFrozen);
Jeff Brownb88102f2010-09-08 11:49:43 -07003469
Jeff Brown9302c872011-07-13 22:51:29 -07003470 if (mFocusedApplicationHandle != NULL) {
Jeff Brownf2f487182010-10-01 17:46:21 -07003471 dump.appendFormat(INDENT "FocusedApplication: name='%s', dispatchingTimeout=%0.3fms\n",
Jeff Brown9302c872011-07-13 22:51:29 -07003472 mFocusedApplicationHandle->name.string(),
3473 mFocusedApplicationHandle->dispatchingTimeout / 1000000.0);
Jeff Brownb88102f2010-09-08 11:49:43 -07003474 } else {
Jeff Brownf2f487182010-10-01 17:46:21 -07003475 dump.append(INDENT "FocusedApplication: <null>\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003476 }
Jeff Brownf2f487182010-10-01 17:46:21 -07003477 dump.appendFormat(INDENT "FocusedWindow: name='%s'\n",
Jeff Brown9302c872011-07-13 22:51:29 -07003478 mFocusedWindowHandle != NULL ? mFocusedWindowHandle->name.string() : "<null>");
Jeff Brownf2f487182010-10-01 17:46:21 -07003479
3480 dump.appendFormat(INDENT "TouchDown: %s\n", toString(mTouchState.down));
3481 dump.appendFormat(INDENT "TouchSplit: %s\n", toString(mTouchState.split));
Jeff Brown95712852011-01-04 19:41:59 -08003482 dump.appendFormat(INDENT "TouchDeviceId: %d\n", mTouchState.deviceId);
Jeff Brown58a2da82011-01-25 16:02:22 -08003483 dump.appendFormat(INDENT "TouchSource: 0x%08x\n", mTouchState.source);
Jeff Brownf2f487182010-10-01 17:46:21 -07003484 if (!mTouchState.windows.isEmpty()) {
3485 dump.append(INDENT "TouchedWindows:\n");
3486 for (size_t i = 0; i < mTouchState.windows.size(); i++) {
3487 const TouchedWindow& touchedWindow = mTouchState.windows[i];
3488 dump.appendFormat(INDENT2 "%d: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
Jeff Brown9302c872011-07-13 22:51:29 -07003489 i, touchedWindow.windowHandle->name.string(), touchedWindow.pointerIds.value,
Jeff Brownf2f487182010-10-01 17:46:21 -07003490 touchedWindow.targetFlags);
3491 }
3492 } else {
3493 dump.append(INDENT "TouchedWindows: <none>\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003494 }
3495
Jeff Brown9302c872011-07-13 22:51:29 -07003496 if (!mWindowHandles.isEmpty()) {
Jeff Brownf2f487182010-10-01 17:46:21 -07003497 dump.append(INDENT "Windows:\n");
Jeff Brown9302c872011-07-13 22:51:29 -07003498 for (size_t i = 0; i < mWindowHandles.size(); i++) {
3499 const sp<InputWindowHandle>& windowHandle = mWindowHandles.itemAt(i);
Jeff Brownf2f487182010-10-01 17:46:21 -07003500 dump.appendFormat(INDENT2 "%d: name='%s', paused=%s, hasFocus=%s, hasWallpaper=%s, "
3501 "visible=%s, canReceiveKeys=%s, flags=0x%08x, type=0x%08x, layer=%d, "
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003502 "frame=[%d,%d][%d,%d], scale=%f, "
Jeff Brownfbf09772011-01-16 14:06:57 -08003503 "touchableRegion=",
Jeff Brown9302c872011-07-13 22:51:29 -07003504 i, windowHandle->name.string(),
3505 toString(windowHandle->paused),
3506 toString(windowHandle->hasFocus),
3507 toString(windowHandle->hasWallpaper),
3508 toString(windowHandle->visible),
3509 toString(windowHandle->canReceiveKeys),
3510 windowHandle->layoutParamsFlags, windowHandle->layoutParamsType,
3511 windowHandle->layer,
3512 windowHandle->frameLeft, windowHandle->frameTop,
3513 windowHandle->frameRight, windowHandle->frameBottom,
3514 windowHandle->scaleFactor);
3515 dumpRegion(dump, windowHandle->touchableRegion);
3516 dump.appendFormat(", inputFeatures=0x%08x", windowHandle->inputFeatures);
Jeff Brownfbf09772011-01-16 14:06:57 -08003517 dump.appendFormat(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%0.3fms\n",
Jeff Brown9302c872011-07-13 22:51:29 -07003518 windowHandle->ownerPid, windowHandle->ownerUid,
3519 windowHandle->dispatchingTimeout / 1000000.0);
Jeff Brownf2f487182010-10-01 17:46:21 -07003520 }
3521 } else {
3522 dump.append(INDENT "Windows: <none>\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003523 }
3524
Jeff Brownf2f487182010-10-01 17:46:21 -07003525 if (!mMonitoringChannels.isEmpty()) {
3526 dump.append(INDENT "MonitoringChannels:\n");
3527 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
3528 const sp<InputChannel>& channel = mMonitoringChannels[i];
3529 dump.appendFormat(INDENT2 "%d: '%s'\n", i, channel->getName().string());
3530 }
3531 } else {
3532 dump.append(INDENT "MonitoringChannels: <none>\n");
3533 }
Jeff Brown519e0242010-09-15 15:18:56 -07003534
Jeff Brownf2f487182010-10-01 17:46:21 -07003535 dump.appendFormat(INDENT "InboundQueue: length=%u\n", mInboundQueue.count());
3536
3537 if (!mActiveConnections.isEmpty()) {
3538 dump.append(INDENT "ActiveConnections:\n");
3539 for (size_t i = 0; i < mActiveConnections.size(); i++) {
3540 const Connection* connection = mActiveConnections[i];
Jeff Brown76860e32010-10-25 17:37:46 -07003541 dump.appendFormat(INDENT2 "%d: '%s', status=%s, outboundQueueLength=%u, "
Jeff Brownb6997262010-10-08 22:31:17 -07003542 "inputState.isNeutral=%s\n",
Jeff Brownf2f487182010-10-01 17:46:21 -07003543 i, connection->getInputChannelName(), connection->getStatusLabel(),
3544 connection->outboundQueue.count(),
Jeff Brownb6997262010-10-08 22:31:17 -07003545 toString(connection->inputState.isNeutral()));
Jeff Brownf2f487182010-10-01 17:46:21 -07003546 }
3547 } else {
3548 dump.append(INDENT "ActiveConnections: <none>\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003549 }
3550
3551 if (isAppSwitchPendingLocked()) {
Jeff Brownf2f487182010-10-01 17:46:21 -07003552 dump.appendFormat(INDENT "AppSwitch: pending, due in %01.1fms\n",
Jeff Brownb88102f2010-09-08 11:49:43 -07003553 (mAppSwitchDueTime - now()) / 1000000.0);
3554 } else {
Jeff Brownf2f487182010-10-01 17:46:21 -07003555 dump.append(INDENT "AppSwitch: not pending\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003556 }
3557}
3558
Jeff Brown928e0542011-01-10 11:17:36 -08003559status_t InputDispatcher::registerInputChannel(const sp<InputChannel>& inputChannel,
3560 const sp<InputWindowHandle>& inputWindowHandle, bool monitor) {
Jeff Brown9c3cda02010-06-15 01:31:58 -07003561#if DEBUG_REGISTRATION
Jeff Brownb88102f2010-09-08 11:49:43 -07003562 LOGD("channel '%s' ~ registerInputChannel - monitor=%s", inputChannel->getName().string(),
3563 toString(monitor));
Jeff Brown9c3cda02010-06-15 01:31:58 -07003564#endif
3565
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003566 { // acquire lock
3567 AutoMutex _l(mLock);
3568
Jeff Brown519e0242010-09-15 15:18:56 -07003569 if (getConnectionIndexLocked(inputChannel) >= 0) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003570 LOGW("Attempted to register already registered input channel '%s'",
3571 inputChannel->getName().string());
3572 return BAD_VALUE;
3573 }
3574
Jeff Brown928e0542011-01-10 11:17:36 -08003575 sp<Connection> connection = new Connection(inputChannel, inputWindowHandle);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003576 status_t status = connection->initialize();
3577 if (status) {
3578 LOGE("Failed to initialize input publisher for input channel '%s', status=%d",
3579 inputChannel->getName().string(), status);
3580 return status;
3581 }
3582
Jeff Brown2cbecea2010-08-17 15:59:26 -07003583 int32_t receiveFd = inputChannel->getReceivePipeFd();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003584 mConnectionsByReceiveFd.add(receiveFd, connection);
Jeff Brown9c3cda02010-06-15 01:31:58 -07003585
Jeff Brownb88102f2010-09-08 11:49:43 -07003586 if (monitor) {
3587 mMonitoringChannels.push(inputChannel);
3588 }
3589
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07003590 mLooper->addFd(receiveFd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
Jeff Brown2cbecea2010-08-17 15:59:26 -07003591
Jeff Brown9c3cda02010-06-15 01:31:58 -07003592 runCommandsLockedInterruptible();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003593 } // release lock
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003594 return OK;
3595}
3596
3597status_t InputDispatcher::unregisterInputChannel(const sp<InputChannel>& inputChannel) {
Jeff Brown9c3cda02010-06-15 01:31:58 -07003598#if DEBUG_REGISTRATION
Jeff Brown349703e2010-06-22 01:27:15 -07003599 LOGD("channel '%s' ~ unregisterInputChannel", inputChannel->getName().string());
Jeff Brown9c3cda02010-06-15 01:31:58 -07003600#endif
3601
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003602 { // acquire lock
3603 AutoMutex _l(mLock);
3604
Jeff Brown519e0242010-09-15 15:18:56 -07003605 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003606 if (connectionIndex < 0) {
3607 LOGW("Attempted to unregister already unregistered input channel '%s'",
3608 inputChannel->getName().string());
3609 return BAD_VALUE;
3610 }
3611
3612 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
3613 mConnectionsByReceiveFd.removeItemsAt(connectionIndex);
3614
3615 connection->status = Connection::STATUS_ZOMBIE;
3616
Jeff Brownb88102f2010-09-08 11:49:43 -07003617 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
3618 if (mMonitoringChannels[i] == inputChannel) {
3619 mMonitoringChannels.removeAt(i);
3620 break;
3621 }
3622 }
3623
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07003624 mLooper->removeFd(inputChannel->getReceivePipeFd());
Jeff Brown2cbecea2010-08-17 15:59:26 -07003625
Jeff Brown7fbdc842010-06-17 20:52:56 -07003626 nsecs_t currentTime = now();
Jeff Brownb6997262010-10-08 22:31:17 -07003627 abortBrokenDispatchCycleLocked(currentTime, connection);
Jeff Brown9c3cda02010-06-15 01:31:58 -07003628
3629 runCommandsLockedInterruptible();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003630 } // release lock
3631
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003632 // Wake the poll loop because removing the connection may have changed the current
3633 // synchronization state.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07003634 mLooper->wake();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003635 return OK;
3636}
3637
Jeff Brown519e0242010-09-15 15:18:56 -07003638ssize_t InputDispatcher::getConnectionIndexLocked(const sp<InputChannel>& inputChannel) {
Jeff Brown2cbecea2010-08-17 15:59:26 -07003639 ssize_t connectionIndex = mConnectionsByReceiveFd.indexOfKey(inputChannel->getReceivePipeFd());
3640 if (connectionIndex >= 0) {
3641 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
3642 if (connection->inputChannel.get() == inputChannel.get()) {
3643 return connectionIndex;
3644 }
3645 }
3646
3647 return -1;
3648}
3649
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003650void InputDispatcher::activateConnectionLocked(Connection* connection) {
3651 for (size_t i = 0; i < mActiveConnections.size(); i++) {
3652 if (mActiveConnections.itemAt(i) == connection) {
3653 return;
3654 }
3655 }
3656 mActiveConnections.add(connection);
3657}
3658
3659void InputDispatcher::deactivateConnectionLocked(Connection* connection) {
3660 for (size_t i = 0; i < mActiveConnections.size(); i++) {
3661 if (mActiveConnections.itemAt(i) == connection) {
3662 mActiveConnections.removeAt(i);
3663 return;
3664 }
3665 }
3666}
3667
Jeff Brown9c3cda02010-06-15 01:31:58 -07003668void InputDispatcher::onDispatchCycleStartedLocked(
Jeff Brown7fbdc842010-06-17 20:52:56 -07003669 nsecs_t currentTime, const sp<Connection>& connection) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003670}
3671
Jeff Brown9c3cda02010-06-15 01:31:58 -07003672void InputDispatcher::onDispatchCycleFinishedLocked(
Jeff Brown3915bb82010-11-05 15:02:16 -07003673 nsecs_t currentTime, const sp<Connection>& connection, bool handled) {
3674 CommandEntry* commandEntry = postCommandLocked(
3675 & InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
3676 commandEntry->connection = connection;
3677 commandEntry->handled = handled;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003678}
3679
Jeff Brown9c3cda02010-06-15 01:31:58 -07003680void InputDispatcher::onDispatchCycleBrokenLocked(
Jeff Brown7fbdc842010-06-17 20:52:56 -07003681 nsecs_t currentTime, const sp<Connection>& connection) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003682 LOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
3683 connection->getInputChannelName());
3684
Jeff Brown9c3cda02010-06-15 01:31:58 -07003685 CommandEntry* commandEntry = postCommandLocked(
3686 & InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
Jeff Brown7fbdc842010-06-17 20:52:56 -07003687 commandEntry->connection = connection;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003688}
3689
Jeff Brown519e0242010-09-15 15:18:56 -07003690void InputDispatcher::onANRLocked(
Jeff Brown9302c872011-07-13 22:51:29 -07003691 nsecs_t currentTime, const sp<InputApplicationHandle>& applicationHandle,
3692 const sp<InputWindowHandle>& windowHandle,
Jeff Brown519e0242010-09-15 15:18:56 -07003693 nsecs_t eventTime, nsecs_t waitStartTime) {
3694 LOGI("Application is not responding: %s. "
3695 "%01.1fms since event, %01.1fms since wait started",
Jeff Brown9302c872011-07-13 22:51:29 -07003696 getApplicationWindowLabelLocked(applicationHandle, windowHandle).string(),
Jeff Brown519e0242010-09-15 15:18:56 -07003697 (currentTime - eventTime) / 1000000.0,
3698 (currentTime - waitStartTime) / 1000000.0);
3699
3700 CommandEntry* commandEntry = postCommandLocked(
3701 & InputDispatcher::doNotifyANRLockedInterruptible);
Jeff Brown9302c872011-07-13 22:51:29 -07003702 commandEntry->inputApplicationHandle = applicationHandle;
3703 commandEntry->inputWindowHandle = windowHandle;
Jeff Brown519e0242010-09-15 15:18:56 -07003704}
3705
Jeff Brownb88102f2010-09-08 11:49:43 -07003706void InputDispatcher::doNotifyConfigurationChangedInterruptible(
3707 CommandEntry* commandEntry) {
3708 mLock.unlock();
3709
3710 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
3711
3712 mLock.lock();
3713}
3714
Jeff Brown9c3cda02010-06-15 01:31:58 -07003715void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(
3716 CommandEntry* commandEntry) {
Jeff Brown7fbdc842010-06-17 20:52:56 -07003717 sp<Connection> connection = commandEntry->connection;
Jeff Brown9c3cda02010-06-15 01:31:58 -07003718
Jeff Brown7fbdc842010-06-17 20:52:56 -07003719 if (connection->status != Connection::STATUS_ZOMBIE) {
3720 mLock.unlock();
Jeff Brown9c3cda02010-06-15 01:31:58 -07003721
Jeff Brown928e0542011-01-10 11:17:36 -08003722 mPolicy->notifyInputChannelBroken(connection->inputWindowHandle);
Jeff Brown7fbdc842010-06-17 20:52:56 -07003723
3724 mLock.lock();
3725 }
Jeff Brown9c3cda02010-06-15 01:31:58 -07003726}
3727
Jeff Brown519e0242010-09-15 15:18:56 -07003728void InputDispatcher::doNotifyANRLockedInterruptible(
Jeff Brown9c3cda02010-06-15 01:31:58 -07003729 CommandEntry* commandEntry) {
Jeff Brown519e0242010-09-15 15:18:56 -07003730 mLock.unlock();
Jeff Brown9c3cda02010-06-15 01:31:58 -07003731
Jeff Brown519e0242010-09-15 15:18:56 -07003732 nsecs_t newTimeout = mPolicy->notifyANR(
Jeff Brown928e0542011-01-10 11:17:36 -08003733 commandEntry->inputApplicationHandle, commandEntry->inputWindowHandle);
Jeff Brown9c3cda02010-06-15 01:31:58 -07003734
Jeff Brown519e0242010-09-15 15:18:56 -07003735 mLock.lock();
Jeff Brown7fbdc842010-06-17 20:52:56 -07003736
Jeff Brown9302c872011-07-13 22:51:29 -07003737 resumeAfterTargetsNotReadyTimeoutLocked(newTimeout,
3738 commandEntry->inputWindowHandle != NULL
3739 ? commandEntry->inputWindowHandle->inputChannel : NULL);
Jeff Brown9c3cda02010-06-15 01:31:58 -07003740}
3741
Jeff Brownb88102f2010-09-08 11:49:43 -07003742void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
3743 CommandEntry* commandEntry) {
3744 KeyEntry* entry = commandEntry->keyEntry;
Jeff Brown1f245102010-11-18 20:53:46 -08003745
3746 KeyEvent event;
3747 initializeKeyEvent(&event, entry);
Jeff Brownb88102f2010-09-08 11:49:43 -07003748
3749 mLock.unlock();
3750
Jeff Brown928e0542011-01-10 11:17:36 -08003751 bool consumed = mPolicy->interceptKeyBeforeDispatching(commandEntry->inputWindowHandle,
Jeff Brown1f245102010-11-18 20:53:46 -08003752 &event, entry->policyFlags);
Jeff Brownb88102f2010-09-08 11:49:43 -07003753
3754 mLock.lock();
3755
3756 entry->interceptKeyResult = consumed
3757 ? KeyEntry::INTERCEPT_KEY_RESULT_SKIP
3758 : KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
Jeff Brownac386072011-07-20 15:19:50 -07003759 entry->release();
Jeff Brownb88102f2010-09-08 11:49:43 -07003760}
3761
Jeff Brown3915bb82010-11-05 15:02:16 -07003762void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(
3763 CommandEntry* commandEntry) {
3764 sp<Connection> connection = commandEntry->connection;
3765 bool handled = commandEntry->handled;
3766
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003767 bool skipNext = false;
Jeff Brown49ed71d2010-12-06 17:13:33 -08003768 if (!connection->outboundQueue.isEmpty()) {
Jeff Brownac386072011-07-20 15:19:50 -07003769 DispatchEntry* dispatchEntry = connection->outboundQueue.head;
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003770 if (dispatchEntry->inProgress) {
3771 if (dispatchEntry->eventEntry->type == EventEntry::TYPE_KEY) {
3772 KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry);
3773 skipNext = afterKeyEventLockedInterruptible(connection,
3774 dispatchEntry, keyEntry, handled);
3775 } else if (dispatchEntry->eventEntry->type == EventEntry::TYPE_MOTION) {
3776 MotionEntry* motionEntry = static_cast<MotionEntry*>(dispatchEntry->eventEntry);
3777 skipNext = afterMotionEventLockedInterruptible(connection,
3778 dispatchEntry, motionEntry, handled);
Jeff Brown49ed71d2010-12-06 17:13:33 -08003779 }
Jeff Brown3915bb82010-11-05 15:02:16 -07003780 }
3781 }
3782
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003783 if (!skipNext) {
3784 startNextDispatchCycleLocked(now(), connection);
3785 }
3786}
3787
3788bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
3789 DispatchEntry* dispatchEntry, KeyEntry* keyEntry, bool handled) {
3790 if (!(keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK)) {
3791 // Get the fallback key state.
3792 // Clear it out after dispatching the UP.
3793 int32_t originalKeyCode = keyEntry->keyCode;
3794 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
3795 if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
3796 connection->inputState.removeFallbackKey(originalKeyCode);
3797 }
3798
3799 if (handled || !dispatchEntry->hasForegroundTarget()) {
3800 // If the application handles the original key for which we previously
3801 // generated a fallback or if the window is not a foreground window,
3802 // then cancel the associated fallback key, if any.
3803 if (fallbackKeyCode != -1) {
3804 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
3805 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
3806 "application handled the original non-fallback key "
3807 "or is no longer a foreground target, "
3808 "canceling previously dispatched fallback key");
3809 options.keyCode = fallbackKeyCode;
3810 synthesizeCancelationEventsForConnectionLocked(connection, options);
3811 }
3812 connection->inputState.removeFallbackKey(originalKeyCode);
3813 }
3814 } else {
3815 // If the application did not handle a non-fallback key, first check
3816 // that we are in a good state to perform unhandled key event processing
3817 // Then ask the policy what to do with it.
3818 bool initialDown = keyEntry->action == AKEY_EVENT_ACTION_DOWN
3819 && keyEntry->repeatCount == 0;
3820 if (fallbackKeyCode == -1 && !initialDown) {
3821#if DEBUG_OUTBOUND_EVENT_DETAILS
3822 LOGD("Unhandled key event: Skipping unhandled key event processing "
3823 "since this is not an initial down. "
3824 "keyCode=%d, action=%d, repeatCount=%d",
3825 originalKeyCode, keyEntry->action, keyEntry->repeatCount);
3826#endif
3827 return false;
3828 }
3829
3830 // Dispatch the unhandled key to the policy.
3831#if DEBUG_OUTBOUND_EVENT_DETAILS
3832 LOGD("Unhandled key event: Asking policy to perform fallback action. "
3833 "keyCode=%d, action=%d, repeatCount=%d",
3834 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount);
3835#endif
3836 KeyEvent event;
3837 initializeKeyEvent(&event, keyEntry);
3838
3839 mLock.unlock();
3840
3841 bool fallback = mPolicy->dispatchUnhandledKey(connection->inputWindowHandle,
3842 &event, keyEntry->policyFlags, &event);
3843
3844 mLock.lock();
3845
3846 if (connection->status != Connection::STATUS_NORMAL) {
3847 connection->inputState.removeFallbackKey(originalKeyCode);
3848 return true; // skip next cycle
3849 }
3850
Jeff Brownac386072011-07-20 15:19:50 -07003851 LOG_ASSERT(connection->outboundQueue.head == dispatchEntry);
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003852
3853 // Latch the fallback keycode for this key on an initial down.
3854 // The fallback keycode cannot change at any other point in the lifecycle.
3855 if (initialDown) {
3856 if (fallback) {
3857 fallbackKeyCode = event.getKeyCode();
3858 } else {
3859 fallbackKeyCode = AKEYCODE_UNKNOWN;
3860 }
3861 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
3862 }
3863
3864 LOG_ASSERT(fallbackKeyCode != -1);
3865
3866 // Cancel the fallback key if the policy decides not to send it anymore.
3867 // We will continue to dispatch the key to the policy but we will no
3868 // longer dispatch a fallback key to the application.
3869 if (fallbackKeyCode != AKEYCODE_UNKNOWN
3870 && (!fallback || fallbackKeyCode != event.getKeyCode())) {
3871#if DEBUG_OUTBOUND_EVENT_DETAILS
3872 if (fallback) {
3873 LOGD("Unhandled key event: Policy requested to send key %d"
3874 "as a fallback for %d, but on the DOWN it had requested "
3875 "to send %d instead. Fallback canceled.",
3876 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
3877 } else {
3878 LOGD("Unhandled key event: Policy did not request fallback for %d,"
3879 "but on the DOWN it had requested to send %d. "
3880 "Fallback canceled.",
3881 originalKeyCode, fallbackKeyCode);
3882 }
3883#endif
3884
3885 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
3886 "canceling fallback, policy no longer desires it");
3887 options.keyCode = fallbackKeyCode;
3888 synthesizeCancelationEventsForConnectionLocked(connection, options);
3889
3890 fallback = false;
3891 fallbackKeyCode = AKEYCODE_UNKNOWN;
3892 if (keyEntry->action != AKEY_EVENT_ACTION_UP) {
3893 connection->inputState.setFallbackKey(originalKeyCode,
3894 fallbackKeyCode);
3895 }
3896 }
3897
3898#if DEBUG_OUTBOUND_EVENT_DETAILS
3899 {
3900 String8 msg;
3901 const KeyedVector<int32_t, int32_t>& fallbackKeys =
3902 connection->inputState.getFallbackKeys();
3903 for (size_t i = 0; i < fallbackKeys.size(); i++) {
3904 msg.appendFormat(", %d->%d", fallbackKeys.keyAt(i),
3905 fallbackKeys.valueAt(i));
3906 }
3907 LOGD("Unhandled key event: %d currently tracked fallback keys%s.",
3908 fallbackKeys.size(), msg.string());
3909 }
3910#endif
3911
3912 if (fallback) {
3913 // Restart the dispatch cycle using the fallback key.
3914 keyEntry->eventTime = event.getEventTime();
3915 keyEntry->deviceId = event.getDeviceId();
3916 keyEntry->source = event.getSource();
3917 keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
3918 keyEntry->keyCode = fallbackKeyCode;
3919 keyEntry->scanCode = event.getScanCode();
3920 keyEntry->metaState = event.getMetaState();
3921 keyEntry->repeatCount = event.getRepeatCount();
3922 keyEntry->downTime = event.getDownTime();
3923 keyEntry->syntheticRepeat = false;
3924
3925#if DEBUG_OUTBOUND_EVENT_DETAILS
3926 LOGD("Unhandled key event: Dispatching fallback key. "
3927 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
3928 originalKeyCode, fallbackKeyCode, keyEntry->metaState);
3929#endif
3930
3931 dispatchEntry->inProgress = false;
3932 startDispatchCycleLocked(now(), connection);
3933 return true; // already started next cycle
3934 } else {
3935#if DEBUG_OUTBOUND_EVENT_DETAILS
3936 LOGD("Unhandled key event: No fallback key.");
3937#endif
3938 }
3939 }
3940 }
3941 return false;
3942}
3943
3944bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
3945 DispatchEntry* dispatchEntry, MotionEntry* motionEntry, bool handled) {
3946 return false;
Jeff Brown3915bb82010-11-05 15:02:16 -07003947}
3948
Jeff Brownb88102f2010-09-08 11:49:43 -07003949void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
3950 mLock.unlock();
3951
Jeff Brown01ce2e92010-09-26 22:20:12 -07003952 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
Jeff Brownb88102f2010-09-08 11:49:43 -07003953
3954 mLock.lock();
3955}
3956
Jeff Brown3915bb82010-11-05 15:02:16 -07003957void InputDispatcher::initializeKeyEvent(KeyEvent* event, const KeyEntry* entry) {
3958 event->initialize(entry->deviceId, entry->source, entry->action, entry->flags,
3959 entry->keyCode, entry->scanCode, entry->metaState, entry->repeatCount,
3960 entry->downTime, entry->eventTime);
3961}
3962
Jeff Brown519e0242010-09-15 15:18:56 -07003963void InputDispatcher::updateDispatchStatisticsLocked(nsecs_t currentTime, const EventEntry* entry,
3964 int32_t injectionResult, nsecs_t timeSpentWaitingForApplication) {
3965 // TODO Write some statistics about how long we spend waiting.
Jeff Brownb88102f2010-09-08 11:49:43 -07003966}
3967
3968void InputDispatcher::dump(String8& dump) {
Jeff Brown89ef0722011-08-10 16:25:21 -07003969 AutoMutex _l(mLock);
3970
Jeff Brownf2f487182010-10-01 17:46:21 -07003971 dump.append("Input Dispatcher State:\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003972 dumpDispatchStateLocked(dump);
Jeff Brown214eaf42011-05-26 19:17:02 -07003973
3974 dump.append(INDENT "Configuration:\n");
3975 dump.appendFormat(INDENT2 "MaxEventsPerSecond: %d\n", mConfig.maxEventsPerSecond);
3976 dump.appendFormat(INDENT2 "KeyRepeatDelay: %0.1fms\n", mConfig.keyRepeatDelay * 0.000001f);
3977 dump.appendFormat(INDENT2 "KeyRepeatTimeout: %0.1fms\n", mConfig.keyRepeatTimeout * 0.000001f);
Jeff Brownb88102f2010-09-08 11:49:43 -07003978}
3979
Jeff Brown89ef0722011-08-10 16:25:21 -07003980void InputDispatcher::monitor() {
3981 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
3982 mLock.lock();
3983 mLock.unlock();
3984}
3985
Jeff Brown9c3cda02010-06-15 01:31:58 -07003986
Jeff Brown519e0242010-09-15 15:18:56 -07003987// --- InputDispatcher::Queue ---
3988
3989template <typename T>
3990uint32_t InputDispatcher::Queue<T>::count() const {
3991 uint32_t result = 0;
Jeff Brownac386072011-07-20 15:19:50 -07003992 for (const T* entry = head; entry; entry = entry->next) {
Jeff Brown519e0242010-09-15 15:18:56 -07003993 result += 1;
3994 }
3995 return result;
3996}
3997
3998
Jeff Brownac386072011-07-20 15:19:50 -07003999// --- InputDispatcher::InjectionState ---
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004000
Jeff Brownac386072011-07-20 15:19:50 -07004001InputDispatcher::InjectionState::InjectionState(int32_t injectorPid, int32_t injectorUid) :
4002 refCount(1),
4003 injectorPid(injectorPid), injectorUid(injectorUid),
4004 injectionResult(INPUT_EVENT_INJECTION_PENDING), injectionIsAsync(false),
4005 pendingForegroundDispatches(0) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004006}
4007
Jeff Brownac386072011-07-20 15:19:50 -07004008InputDispatcher::InjectionState::~InjectionState() {
Jeff Brown01ce2e92010-09-26 22:20:12 -07004009}
4010
Jeff Brownac386072011-07-20 15:19:50 -07004011void InputDispatcher::InjectionState::release() {
4012 refCount -= 1;
4013 if (refCount == 0) {
4014 delete this;
4015 } else {
4016 LOG_ASSERT(refCount > 0);
Jeff Brown01ce2e92010-09-26 22:20:12 -07004017 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07004018}
4019
Jeff Brownac386072011-07-20 15:19:50 -07004020
4021// --- InputDispatcher::EventEntry ---
4022
4023InputDispatcher::EventEntry::EventEntry(int32_t type, nsecs_t eventTime, uint32_t policyFlags) :
4024 refCount(1), type(type), eventTime(eventTime), policyFlags(policyFlags),
4025 injectionState(NULL), dispatchInProgress(false) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004026}
4027
Jeff Brownac386072011-07-20 15:19:50 -07004028InputDispatcher::EventEntry::~EventEntry() {
4029 releaseInjectionState();
4030}
4031
4032void InputDispatcher::EventEntry::release() {
4033 refCount -= 1;
4034 if (refCount == 0) {
4035 delete this;
4036 } else {
4037 LOG_ASSERT(refCount > 0);
4038 }
4039}
4040
4041void InputDispatcher::EventEntry::releaseInjectionState() {
4042 if (injectionState) {
4043 injectionState->release();
4044 injectionState = NULL;
4045 }
4046}
4047
4048
4049// --- InputDispatcher::ConfigurationChangedEntry ---
4050
4051InputDispatcher::ConfigurationChangedEntry::ConfigurationChangedEntry(nsecs_t eventTime) :
4052 EventEntry(TYPE_CONFIGURATION_CHANGED, eventTime, 0) {
4053}
4054
4055InputDispatcher::ConfigurationChangedEntry::~ConfigurationChangedEntry() {
4056}
4057
4058
Jeff Brown65fd2512011-08-18 11:20:58 -07004059// --- InputDispatcher::DeviceResetEntry ---
4060
4061InputDispatcher::DeviceResetEntry::DeviceResetEntry(nsecs_t eventTime, int32_t deviceId) :
4062 EventEntry(TYPE_DEVICE_RESET, eventTime, 0),
4063 deviceId(deviceId) {
4064}
4065
4066InputDispatcher::DeviceResetEntry::~DeviceResetEntry() {
4067}
4068
4069
Jeff Brownac386072011-07-20 15:19:50 -07004070// --- InputDispatcher::KeyEntry ---
4071
4072InputDispatcher::KeyEntry::KeyEntry(nsecs_t eventTime,
Jeff Brown58a2da82011-01-25 16:02:22 -08004073 int32_t deviceId, uint32_t source, uint32_t policyFlags, int32_t action,
Jeff Brown7fbdc842010-06-17 20:52:56 -07004074 int32_t flags, int32_t keyCode, int32_t scanCode, int32_t metaState,
Jeff Brownac386072011-07-20 15:19:50 -07004075 int32_t repeatCount, nsecs_t downTime) :
4076 EventEntry(TYPE_KEY, eventTime, policyFlags),
4077 deviceId(deviceId), source(source), action(action), flags(flags),
4078 keyCode(keyCode), scanCode(scanCode), metaState(metaState),
4079 repeatCount(repeatCount), downTime(downTime),
4080 syntheticRepeat(false), interceptKeyResult(KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004081}
4082
Jeff Brownac386072011-07-20 15:19:50 -07004083InputDispatcher::KeyEntry::~KeyEntry() {
4084}
Jeff Brown7fbdc842010-06-17 20:52:56 -07004085
Jeff Brownac386072011-07-20 15:19:50 -07004086void InputDispatcher::KeyEntry::recycle() {
4087 releaseInjectionState();
4088
4089 dispatchInProgress = false;
4090 syntheticRepeat = false;
4091 interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
4092}
4093
4094
4095// --- InputDispatcher::MotionSample ---
4096
4097InputDispatcher::MotionSample::MotionSample(nsecs_t eventTime,
4098 const PointerCoords* pointerCoords, uint32_t pointerCount) :
4099 next(NULL), eventTime(eventTime), eventTimeBeforeCoalescing(eventTime) {
Jeff Brown7fbdc842010-06-17 20:52:56 -07004100 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brownac386072011-07-20 15:19:50 -07004101 this->pointerCoords[i].copyFrom(pointerCoords[i]);
Jeff Brown7fbdc842010-06-17 20:52:56 -07004102 }
Jeff Brownb88102f2010-09-08 11:49:43 -07004103}
4104
4105
Jeff Brownae9fc032010-08-18 15:51:08 -07004106// --- InputDispatcher::MotionEntry ---
4107
Jeff Brownac386072011-07-20 15:19:50 -07004108InputDispatcher::MotionEntry::MotionEntry(nsecs_t eventTime,
4109 int32_t deviceId, uint32_t source, uint32_t policyFlags, int32_t action, int32_t flags,
4110 int32_t metaState, int32_t buttonState,
4111 int32_t edgeFlags, float xPrecision, float yPrecision,
4112 nsecs_t downTime, uint32_t pointerCount,
4113 const PointerProperties* pointerProperties, const PointerCoords* pointerCoords) :
4114 EventEntry(TYPE_MOTION, eventTime, policyFlags),
4115 deviceId(deviceId), source(source), action(action), flags(flags),
4116 metaState(metaState), buttonState(buttonState), edgeFlags(edgeFlags),
4117 xPrecision(xPrecision), yPrecision(yPrecision),
4118 downTime(downTime), pointerCount(pointerCount),
4119 firstSample(eventTime, pointerCoords, pointerCount),
4120 lastSample(&firstSample) {
4121 for (uint32_t i = 0; i < pointerCount; i++) {
4122 this->pointerProperties[i].copyFrom(pointerProperties[i]);
4123 }
4124}
4125
4126InputDispatcher::MotionEntry::~MotionEntry() {
4127 for (MotionSample* sample = firstSample.next; sample != NULL; ) {
4128 MotionSample* next = sample->next;
4129 delete sample;
4130 sample = next;
4131 }
4132}
4133
Jeff Brownae9fc032010-08-18 15:51:08 -07004134uint32_t InputDispatcher::MotionEntry::countSamples() const {
4135 uint32_t count = 1;
4136 for (MotionSample* sample = firstSample.next; sample != NULL; sample = sample->next) {
4137 count += 1;
4138 }
4139 return count;
4140}
4141
Jeff Brown4e91a182011-04-07 11:38:09 -07004142bool InputDispatcher::MotionEntry::canAppendSamples(int32_t action, uint32_t pointerCount,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07004143 const PointerProperties* pointerProperties) const {
Jeff Brown4e91a182011-04-07 11:38:09 -07004144 if (this->action != action
4145 || this->pointerCount != pointerCount
4146 || this->isInjected()) {
4147 return false;
4148 }
4149 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07004150 if (this->pointerProperties[i] != pointerProperties[i]) {
Jeff Brown4e91a182011-04-07 11:38:09 -07004151 return false;
4152 }
4153 }
4154 return true;
4155}
4156
Jeff Brownac386072011-07-20 15:19:50 -07004157void InputDispatcher::MotionEntry::appendSample(
4158 nsecs_t eventTime, const PointerCoords* pointerCoords) {
4159 MotionSample* sample = new MotionSample(eventTime, pointerCoords, pointerCount);
4160
4161 lastSample->next = sample;
4162 lastSample = sample;
4163}
4164
4165
4166// --- InputDispatcher::DispatchEntry ---
4167
4168InputDispatcher::DispatchEntry::DispatchEntry(EventEntry* eventEntry,
4169 int32_t targetFlags, float xOffset, float yOffset, float scaleFactor) :
4170 eventEntry(eventEntry), targetFlags(targetFlags),
4171 xOffset(xOffset), yOffset(yOffset), scaleFactor(scaleFactor),
4172 inProgress(false),
4173 resolvedAction(0), resolvedFlags(0),
4174 headMotionSample(NULL), tailMotionSample(NULL) {
4175 eventEntry->refCount += 1;
4176}
4177
4178InputDispatcher::DispatchEntry::~DispatchEntry() {
4179 eventEntry->release();
4180}
4181
Jeff Brownb88102f2010-09-08 11:49:43 -07004182
4183// --- InputDispatcher::InputState ---
4184
Jeff Brownb6997262010-10-08 22:31:17 -07004185InputDispatcher::InputState::InputState() {
Jeff Brownb88102f2010-09-08 11:49:43 -07004186}
4187
4188InputDispatcher::InputState::~InputState() {
4189}
4190
4191bool InputDispatcher::InputState::isNeutral() const {
4192 return mKeyMementos.isEmpty() && mMotionMementos.isEmpty();
4193}
4194
Jeff Brown81346812011-06-28 20:08:48 -07004195bool InputDispatcher::InputState::isHovering(int32_t deviceId, uint32_t source) const {
4196 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4197 const MotionMemento& memento = mMotionMementos.itemAt(i);
4198 if (memento.deviceId == deviceId
4199 && memento.source == source
4200 && memento.hovering) {
4201 return true;
4202 }
4203 }
4204 return false;
4205}
Jeff Brownb88102f2010-09-08 11:49:43 -07004206
Jeff Brown81346812011-06-28 20:08:48 -07004207bool InputDispatcher::InputState::trackKey(const KeyEntry* entry,
4208 int32_t action, int32_t flags) {
4209 switch (action) {
4210 case AKEY_EVENT_ACTION_UP: {
4211 if (entry->flags & AKEY_EVENT_FLAG_FALLBACK) {
4212 for (size_t i = 0; i < mFallbackKeys.size(); ) {
4213 if (mFallbackKeys.valueAt(i) == entry->keyCode) {
4214 mFallbackKeys.removeItemsAt(i);
4215 } else {
4216 i += 1;
4217 }
4218 }
4219 }
4220 ssize_t index = findKeyMemento(entry);
4221 if (index >= 0) {
4222 mKeyMementos.removeAt(index);
4223 return true;
4224 }
4225#if DEBUG_OUTBOUND_EVENT_DETAILS
4226 LOGD("Dropping inconsistent key up event: deviceId=%d, source=%08x, "
4227 "keyCode=%d, scanCode=%d",
4228 entry->deviceId, entry->source, entry->keyCode, entry->scanCode);
4229#endif
4230 return false;
4231 }
4232
4233 case AKEY_EVENT_ACTION_DOWN: {
4234 ssize_t index = findKeyMemento(entry);
4235 if (index >= 0) {
4236 mKeyMementos.removeAt(index);
4237 }
4238 addKeyMemento(entry, flags);
4239 return true;
4240 }
4241
4242 default:
4243 return true;
Jeff Brownb88102f2010-09-08 11:49:43 -07004244 }
4245}
4246
Jeff Brown81346812011-06-28 20:08:48 -07004247bool InputDispatcher::InputState::trackMotion(const MotionEntry* entry,
4248 int32_t action, int32_t flags) {
4249 int32_t actionMasked = action & AMOTION_EVENT_ACTION_MASK;
4250 switch (actionMasked) {
4251 case AMOTION_EVENT_ACTION_UP:
4252 case AMOTION_EVENT_ACTION_CANCEL: {
4253 ssize_t index = findMotionMemento(entry, false /*hovering*/);
4254 if (index >= 0) {
4255 mMotionMementos.removeAt(index);
4256 return true;
Jeff Brownda3d5a92011-03-29 15:11:34 -07004257 }
Jeff Brown81346812011-06-28 20:08:48 -07004258#if DEBUG_OUTBOUND_EVENT_DETAILS
4259 LOGD("Dropping inconsistent motion up or cancel event: deviceId=%d, source=%08x, "
4260 "actionMasked=%d",
4261 entry->deviceId, entry->source, actionMasked);
4262#endif
4263 return false;
Jeff Brownda3d5a92011-03-29 15:11:34 -07004264 }
4265
Jeff Brown81346812011-06-28 20:08:48 -07004266 case AMOTION_EVENT_ACTION_DOWN: {
4267 ssize_t index = findMotionMemento(entry, false /*hovering*/);
4268 if (index >= 0) {
4269 mMotionMementos.removeAt(index);
4270 }
4271 addMotionMemento(entry, flags, false /*hovering*/);
4272 return true;
4273 }
4274
4275 case AMOTION_EVENT_ACTION_POINTER_UP:
4276 case AMOTION_EVENT_ACTION_POINTER_DOWN:
4277 case AMOTION_EVENT_ACTION_MOVE: {
4278 ssize_t index = findMotionMemento(entry, false /*hovering*/);
4279 if (index >= 0) {
4280 MotionMemento& memento = mMotionMementos.editItemAt(index);
4281 memento.setPointers(entry);
4282 return true;
4283 }
Jeff Brown2e45fb62011-06-29 21:19:05 -07004284 if (actionMasked == AMOTION_EVENT_ACTION_MOVE
4285 && (entry->source & (AINPUT_SOURCE_CLASS_JOYSTICK
4286 | AINPUT_SOURCE_CLASS_NAVIGATION))) {
4287 // Joysticks and trackballs can send MOVE events without corresponding DOWN or UP.
4288 return true;
4289 }
Jeff Brown81346812011-06-28 20:08:48 -07004290#if DEBUG_OUTBOUND_EVENT_DETAILS
4291 LOGD("Dropping inconsistent motion pointer up/down or move event: "
4292 "deviceId=%d, source=%08x, actionMasked=%d",
4293 entry->deviceId, entry->source, actionMasked);
4294#endif
4295 return false;
4296 }
4297
4298 case AMOTION_EVENT_ACTION_HOVER_EXIT: {
4299 ssize_t index = findMotionMemento(entry, true /*hovering*/);
4300 if (index >= 0) {
4301 mMotionMementos.removeAt(index);
4302 return true;
4303 }
4304#if DEBUG_OUTBOUND_EVENT_DETAILS
4305 LOGD("Dropping inconsistent motion hover exit event: deviceId=%d, source=%08x",
4306 entry->deviceId, entry->source);
4307#endif
4308 return false;
4309 }
4310
4311 case AMOTION_EVENT_ACTION_HOVER_ENTER:
4312 case AMOTION_EVENT_ACTION_HOVER_MOVE: {
4313 ssize_t index = findMotionMemento(entry, true /*hovering*/);
4314 if (index >= 0) {
4315 mMotionMementos.removeAt(index);
4316 }
4317 addMotionMemento(entry, flags, true /*hovering*/);
4318 return true;
4319 }
4320
4321 default:
4322 return true;
4323 }
4324}
4325
4326ssize_t InputDispatcher::InputState::findKeyMemento(const KeyEntry* entry) const {
Jeff Brownb88102f2010-09-08 11:49:43 -07004327 for (size_t i = 0; i < mKeyMementos.size(); i++) {
Jeff Brown81346812011-06-28 20:08:48 -07004328 const KeyMemento& memento = mKeyMementos.itemAt(i);
Jeff Brownb88102f2010-09-08 11:49:43 -07004329 if (memento.deviceId == entry->deviceId
4330 && memento.source == entry->source
4331 && memento.keyCode == entry->keyCode
4332 && memento.scanCode == entry->scanCode) {
Jeff Brown81346812011-06-28 20:08:48 -07004333 return i;
Jeff Brownb88102f2010-09-08 11:49:43 -07004334 }
4335 }
Jeff Brown81346812011-06-28 20:08:48 -07004336 return -1;
Jeff Brownb88102f2010-09-08 11:49:43 -07004337}
4338
Jeff Brown81346812011-06-28 20:08:48 -07004339ssize_t InputDispatcher::InputState::findMotionMemento(const MotionEntry* entry,
4340 bool hovering) const {
Jeff Brownb88102f2010-09-08 11:49:43 -07004341 for (size_t i = 0; i < mMotionMementos.size(); i++) {
Jeff Brown81346812011-06-28 20:08:48 -07004342 const MotionMemento& memento = mMotionMementos.itemAt(i);
Jeff Brownb88102f2010-09-08 11:49:43 -07004343 if (memento.deviceId == entry->deviceId
Jeff Brown81346812011-06-28 20:08:48 -07004344 && memento.source == entry->source
4345 && memento.hovering == hovering) {
4346 return i;
Jeff Brownb88102f2010-09-08 11:49:43 -07004347 }
4348 }
Jeff Brown81346812011-06-28 20:08:48 -07004349 return -1;
4350}
Jeff Brownb88102f2010-09-08 11:49:43 -07004351
Jeff Brown81346812011-06-28 20:08:48 -07004352void InputDispatcher::InputState::addKeyMemento(const KeyEntry* entry, int32_t flags) {
4353 mKeyMementos.push();
4354 KeyMemento& memento = mKeyMementos.editTop();
4355 memento.deviceId = entry->deviceId;
4356 memento.source = entry->source;
4357 memento.keyCode = entry->keyCode;
4358 memento.scanCode = entry->scanCode;
4359 memento.flags = flags;
4360 memento.downTime = entry->downTime;
4361}
4362
4363void InputDispatcher::InputState::addMotionMemento(const MotionEntry* entry,
4364 int32_t flags, bool hovering) {
4365 mMotionMementos.push();
4366 MotionMemento& memento = mMotionMementos.editTop();
4367 memento.deviceId = entry->deviceId;
4368 memento.source = entry->source;
4369 memento.flags = flags;
4370 memento.xPrecision = entry->xPrecision;
4371 memento.yPrecision = entry->yPrecision;
4372 memento.downTime = entry->downTime;
4373 memento.setPointers(entry);
4374 memento.hovering = hovering;
Jeff Brownb88102f2010-09-08 11:49:43 -07004375}
4376
4377void InputDispatcher::InputState::MotionMemento::setPointers(const MotionEntry* entry) {
4378 pointerCount = entry->pointerCount;
4379 for (uint32_t i = 0; i < entry->pointerCount; i++) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07004380 pointerProperties[i].copyFrom(entry->pointerProperties[i]);
Jeff Brownace13b12011-03-09 17:39:48 -08004381 pointerCoords[i].copyFrom(entry->lastSample->pointerCoords[i]);
Jeff Brownb88102f2010-09-08 11:49:43 -07004382 }
4383}
4384
Jeff Brownb6997262010-10-08 22:31:17 -07004385void InputDispatcher::InputState::synthesizeCancelationEvents(nsecs_t currentTime,
Jeff Brownac386072011-07-20 15:19:50 -07004386 Vector<EventEntry*>& outEvents, const CancelationOptions& options) {
Jeff Brown81346812011-06-28 20:08:48 -07004387 for (size_t i = 0; i < mKeyMementos.size(); i++) {
Jeff Brownb88102f2010-09-08 11:49:43 -07004388 const KeyMemento& memento = mKeyMementos.itemAt(i);
Jeff Brown49ed71d2010-12-06 17:13:33 -08004389 if (shouldCancelKey(memento, options)) {
Jeff Brownac386072011-07-20 15:19:50 -07004390 outEvents.push(new KeyEntry(currentTime,
Jeff Brownb6997262010-10-08 22:31:17 -07004391 memento.deviceId, memento.source, 0,
Jeff Brown49ed71d2010-12-06 17:13:33 -08004392 AKEY_EVENT_ACTION_UP, memento.flags | AKEY_EVENT_FLAG_CANCELED,
Jeff Brownb6997262010-10-08 22:31:17 -07004393 memento.keyCode, memento.scanCode, 0, 0, memento.downTime));
Jeff Brownb6997262010-10-08 22:31:17 -07004394 }
Jeff Brownb88102f2010-09-08 11:49:43 -07004395 }
4396
Jeff Brown81346812011-06-28 20:08:48 -07004397 for (size_t i = 0; i < mMotionMementos.size(); i++) {
Jeff Brownb88102f2010-09-08 11:49:43 -07004398 const MotionMemento& memento = mMotionMementos.itemAt(i);
Jeff Brown49ed71d2010-12-06 17:13:33 -08004399 if (shouldCancelMotion(memento, options)) {
Jeff Brownac386072011-07-20 15:19:50 -07004400 outEvents.push(new MotionEntry(currentTime,
Jeff Brownb6997262010-10-08 22:31:17 -07004401 memento.deviceId, memento.source, 0,
Jeff Browna032cc02011-03-07 16:56:21 -08004402 memento.hovering
4403 ? AMOTION_EVENT_ACTION_HOVER_EXIT
4404 : AMOTION_EVENT_ACTION_CANCEL,
Jeff Brown81346812011-06-28 20:08:48 -07004405 memento.flags, 0, 0, 0,
Jeff Brownb6997262010-10-08 22:31:17 -07004406 memento.xPrecision, memento.yPrecision, memento.downTime,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07004407 memento.pointerCount, memento.pointerProperties, memento.pointerCoords));
Jeff Brownb6997262010-10-08 22:31:17 -07004408 }
Jeff Brownb88102f2010-09-08 11:49:43 -07004409 }
4410}
4411
4412void InputDispatcher::InputState::clear() {
4413 mKeyMementos.clear();
4414 mMotionMementos.clear();
Jeff Brownda3d5a92011-03-29 15:11:34 -07004415 mFallbackKeys.clear();
Jeff Brownb6997262010-10-08 22:31:17 -07004416}
4417
Jeff Brown9c9f1a32010-10-11 18:32:20 -07004418void InputDispatcher::InputState::copyPointerStateTo(InputState& other) const {
4419 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4420 const MotionMemento& memento = mMotionMementos.itemAt(i);
4421 if (memento.source & AINPUT_SOURCE_CLASS_POINTER) {
4422 for (size_t j = 0; j < other.mMotionMementos.size(); ) {
4423 const MotionMemento& otherMemento = other.mMotionMementos.itemAt(j);
4424 if (memento.deviceId == otherMemento.deviceId
4425 && memento.source == otherMemento.source) {
4426 other.mMotionMementos.removeAt(j);
4427 } else {
4428 j += 1;
4429 }
4430 }
4431 other.mMotionMementos.push(memento);
4432 }
4433 }
4434}
4435
Jeff Brownda3d5a92011-03-29 15:11:34 -07004436int32_t InputDispatcher::InputState::getFallbackKey(int32_t originalKeyCode) {
4437 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
4438 return index >= 0 ? mFallbackKeys.valueAt(index) : -1;
4439}
4440
4441void InputDispatcher::InputState::setFallbackKey(int32_t originalKeyCode,
4442 int32_t fallbackKeyCode) {
4443 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
4444 if (index >= 0) {
4445 mFallbackKeys.replaceValueAt(index, fallbackKeyCode);
4446 } else {
4447 mFallbackKeys.add(originalKeyCode, fallbackKeyCode);
4448 }
4449}
4450
4451void InputDispatcher::InputState::removeFallbackKey(int32_t originalKeyCode) {
4452 mFallbackKeys.removeItem(originalKeyCode);
4453}
4454
Jeff Brown49ed71d2010-12-06 17:13:33 -08004455bool InputDispatcher::InputState::shouldCancelKey(const KeyMemento& memento,
Jeff Brownda3d5a92011-03-29 15:11:34 -07004456 const CancelationOptions& options) {
4457 if (options.keyCode != -1 && memento.keyCode != options.keyCode) {
4458 return false;
4459 }
4460
Jeff Brown65fd2512011-08-18 11:20:58 -07004461 if (options.deviceId != -1 && memento.deviceId != options.deviceId) {
4462 return false;
4463 }
4464
Jeff Brownda3d5a92011-03-29 15:11:34 -07004465 switch (options.mode) {
4466 case CancelationOptions::CANCEL_ALL_EVENTS:
4467 case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
Jeff Brownb6997262010-10-08 22:31:17 -07004468 return true;
Jeff Brownda3d5a92011-03-29 15:11:34 -07004469 case CancelationOptions::CANCEL_FALLBACK_EVENTS:
Jeff Brown49ed71d2010-12-06 17:13:33 -08004470 return memento.flags & AKEY_EVENT_FLAG_FALLBACK;
4471 default:
4472 return false;
4473 }
4474}
4475
4476bool InputDispatcher::InputState::shouldCancelMotion(const MotionMemento& memento,
Jeff Brownda3d5a92011-03-29 15:11:34 -07004477 const CancelationOptions& options) {
Jeff Brown65fd2512011-08-18 11:20:58 -07004478 if (options.deviceId != -1 && memento.deviceId != options.deviceId) {
4479 return false;
4480 }
4481
Jeff Brownda3d5a92011-03-29 15:11:34 -07004482 switch (options.mode) {
4483 case CancelationOptions::CANCEL_ALL_EVENTS:
Jeff Brown49ed71d2010-12-06 17:13:33 -08004484 return true;
Jeff Brownda3d5a92011-03-29 15:11:34 -07004485 case CancelationOptions::CANCEL_POINTER_EVENTS:
Jeff Brown49ed71d2010-12-06 17:13:33 -08004486 return memento.source & AINPUT_SOURCE_CLASS_POINTER;
Jeff Brownda3d5a92011-03-29 15:11:34 -07004487 case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
Jeff Brown49ed71d2010-12-06 17:13:33 -08004488 return !(memento.source & AINPUT_SOURCE_CLASS_POINTER);
4489 default:
4490 return false;
Jeff Brownb6997262010-10-08 22:31:17 -07004491 }
Jeff Brownb88102f2010-09-08 11:49:43 -07004492}
4493
4494
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004495// --- InputDispatcher::Connection ---
4496
Jeff Brown928e0542011-01-10 11:17:36 -08004497InputDispatcher::Connection::Connection(const sp<InputChannel>& inputChannel,
4498 const sp<InputWindowHandle>& inputWindowHandle) :
4499 status(STATUS_NORMAL), inputChannel(inputChannel), inputWindowHandle(inputWindowHandle),
4500 inputPublisher(inputChannel),
Jeff Brownda3d5a92011-03-29 15:11:34 -07004501 lastEventTime(LONG_LONG_MAX), lastDispatchTime(LONG_LONG_MAX) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004502}
4503
4504InputDispatcher::Connection::~Connection() {
4505}
4506
4507status_t InputDispatcher::Connection::initialize() {
4508 return inputPublisher.initialize();
4509}
4510
Jeff Brown9c3cda02010-06-15 01:31:58 -07004511const char* InputDispatcher::Connection::getStatusLabel() const {
4512 switch (status) {
4513 case STATUS_NORMAL:
4514 return "NORMAL";
4515
4516 case STATUS_BROKEN:
4517 return "BROKEN";
4518
Jeff Brown9c3cda02010-06-15 01:31:58 -07004519 case STATUS_ZOMBIE:
4520 return "ZOMBIE";
4521
4522 default:
4523 return "UNKNOWN";
4524 }
4525}
4526
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004527InputDispatcher::DispatchEntry* InputDispatcher::Connection::findQueuedDispatchEntryForEvent(
4528 const EventEntry* eventEntry) const {
Jeff Brownac386072011-07-20 15:19:50 -07004529 for (DispatchEntry* dispatchEntry = outboundQueue.tail; dispatchEntry;
4530 dispatchEntry = dispatchEntry->prev) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004531 if (dispatchEntry->eventEntry == eventEntry) {
4532 return dispatchEntry;
4533 }
4534 }
4535 return NULL;
4536}
4537
Jeff Brownb88102f2010-09-08 11:49:43 -07004538
Jeff Brown9c3cda02010-06-15 01:31:58 -07004539// --- InputDispatcher::CommandEntry ---
4540
Jeff Brownac386072011-07-20 15:19:50 -07004541InputDispatcher::CommandEntry::CommandEntry(Command command) :
4542 command(command), eventTime(0), keyEntry(NULL), userActivityEventType(0), handled(false) {
Jeff Brown9c3cda02010-06-15 01:31:58 -07004543}
4544
4545InputDispatcher::CommandEntry::~CommandEntry() {
4546}
4547
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004548
Jeff Brown01ce2e92010-09-26 22:20:12 -07004549// --- InputDispatcher::TouchState ---
4550
4551InputDispatcher::TouchState::TouchState() :
Jeff Brown58a2da82011-01-25 16:02:22 -08004552 down(false), split(false), deviceId(-1), source(0) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07004553}
4554
4555InputDispatcher::TouchState::~TouchState() {
4556}
4557
4558void InputDispatcher::TouchState::reset() {
4559 down = false;
4560 split = false;
Jeff Brown95712852011-01-04 19:41:59 -08004561 deviceId = -1;
Jeff Brown58a2da82011-01-25 16:02:22 -08004562 source = 0;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004563 windows.clear();
4564}
4565
4566void InputDispatcher::TouchState::copyFrom(const TouchState& other) {
4567 down = other.down;
4568 split = other.split;
Jeff Brown95712852011-01-04 19:41:59 -08004569 deviceId = other.deviceId;
Jeff Brown58a2da82011-01-25 16:02:22 -08004570 source = other.source;
Jeff Brown9302c872011-07-13 22:51:29 -07004571 windows = other.windows;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004572}
4573
Jeff Brown9302c872011-07-13 22:51:29 -07004574void InputDispatcher::TouchState::addOrUpdateWindow(const sp<InputWindowHandle>& windowHandle,
Jeff Brown01ce2e92010-09-26 22:20:12 -07004575 int32_t targetFlags, BitSet32 pointerIds) {
4576 if (targetFlags & InputTarget::FLAG_SPLIT) {
4577 split = true;
4578 }
4579
4580 for (size_t i = 0; i < windows.size(); i++) {
4581 TouchedWindow& touchedWindow = windows.editItemAt(i);
Jeff Brown9302c872011-07-13 22:51:29 -07004582 if (touchedWindow.windowHandle == windowHandle) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07004583 touchedWindow.targetFlags |= targetFlags;
Jeff Brown98db5fa2011-06-08 15:37:10 -07004584 if (targetFlags & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
4585 touchedWindow.targetFlags &= ~InputTarget::FLAG_DISPATCH_AS_IS;
4586 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07004587 touchedWindow.pointerIds.value |= pointerIds.value;
4588 return;
4589 }
4590 }
4591
4592 windows.push();
4593
4594 TouchedWindow& touchedWindow = windows.editTop();
Jeff Brown9302c872011-07-13 22:51:29 -07004595 touchedWindow.windowHandle = windowHandle;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004596 touchedWindow.targetFlags = targetFlags;
4597 touchedWindow.pointerIds = pointerIds;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004598}
4599
Jeff Browna032cc02011-03-07 16:56:21 -08004600void InputDispatcher::TouchState::filterNonAsIsTouchWindows() {
Jeff Brown01ce2e92010-09-26 22:20:12 -07004601 for (size_t i = 0 ; i < windows.size(); ) {
Jeff Browna032cc02011-03-07 16:56:21 -08004602 TouchedWindow& window = windows.editItemAt(i);
Jeff Brown98db5fa2011-06-08 15:37:10 -07004603 if (window.targetFlags & (InputTarget::FLAG_DISPATCH_AS_IS
4604 | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER)) {
Jeff Browna032cc02011-03-07 16:56:21 -08004605 window.targetFlags &= ~InputTarget::FLAG_DISPATCH_MASK;
4606 window.targetFlags |= InputTarget::FLAG_DISPATCH_AS_IS;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004607 i += 1;
Jeff Browna032cc02011-03-07 16:56:21 -08004608 } else {
4609 windows.removeAt(i);
Jeff Brown01ce2e92010-09-26 22:20:12 -07004610 }
4611 }
4612}
4613
Jeff Brown9302c872011-07-13 22:51:29 -07004614sp<InputWindowHandle> InputDispatcher::TouchState::getFirstForegroundWindowHandle() const {
Jeff Brown01ce2e92010-09-26 22:20:12 -07004615 for (size_t i = 0; i < windows.size(); i++) {
Jeff Brown98db5fa2011-06-08 15:37:10 -07004616 const TouchedWindow& window = windows.itemAt(i);
4617 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
Jeff Brown9302c872011-07-13 22:51:29 -07004618 return window.windowHandle;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004619 }
4620 }
4621 return NULL;
4622}
4623
Jeff Brown98db5fa2011-06-08 15:37:10 -07004624bool InputDispatcher::TouchState::isSlippery() const {
4625 // Must have exactly one foreground window.
4626 bool haveSlipperyForegroundWindow = false;
4627 for (size_t i = 0; i < windows.size(); i++) {
4628 const TouchedWindow& window = windows.itemAt(i);
4629 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
Jeff Brown9302c872011-07-13 22:51:29 -07004630 if (haveSlipperyForegroundWindow || !(window.windowHandle->layoutParamsFlags
4631 & InputWindowHandle::FLAG_SLIPPERY)) {
Jeff Brown98db5fa2011-06-08 15:37:10 -07004632 return false;
4633 }
4634 haveSlipperyForegroundWindow = true;
4635 }
4636 }
4637 return haveSlipperyForegroundWindow;
4638}
4639
Jeff Brown01ce2e92010-09-26 22:20:12 -07004640
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004641// --- InputDispatcherThread ---
4642
4643InputDispatcherThread::InputDispatcherThread(const sp<InputDispatcherInterface>& dispatcher) :
4644 Thread(/*canCallJava*/ true), mDispatcher(dispatcher) {
4645}
4646
4647InputDispatcherThread::~InputDispatcherThread() {
4648}
4649
4650bool InputDispatcherThread::threadLoop() {
4651 mDispatcher->dispatchOnce();
4652 return true;
4653}
4654
4655} // namespace android