blob: 1eb5f0e73e501d43e18ba0f1c391a636289ace73 [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 Brown46b9ac02010-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 Brown46b9ac02010-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 Brown46b9ac02010-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 Brown46b9ac02010-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 Brown46b9ac02010-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 Brown46b9ac02010-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 Brown46b9ac02010-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 Brown46b9ac02010-04-22 18:58:52 -070056#include <cutils/log.h>
Jeff Brownb88102f2010-09-08 11:49:43 -070057#include <ui/PowerManager.h>
Jeff Brown46b9ac02010-04-22 18:58:52 -070058
59#include <stddef.h>
60#include <unistd.h>
Jeff Brown46b9ac02010-04-22 18:58:52 -070061#include <errno.h>
62#include <limits.h>
Jeff Brown46b9ac02010-04-22 18:58:52 -070063
Jeff Brownf2f48712010-10-01 17:46:21 -070064#define INDENT " "
65#define INDENT2 " "
66
Jeff Brown46b9ac02010-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 Brown46b9ac02010-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 Brown46b9ac02010-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 Brown46b9ac02010-04-22 18:58:52 -0700217
Jeff Brown46b9ac02010-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 Brown46b9ac02010-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 Brown46b9ac02010-04-22 18:58:52 -0700239
240 while (mConnectionsByReceiveFd.size() != 0) {
241 unregisterInputChannel(mConnectionsByReceiveFd.valueAt(0)->inputChannel);
242 }
Jeff Brown46b9ac02010-04-22 18:58:52 -0700243}
244
245void InputDispatcher::dispatchOnce() {
Jeff Brown46b9ac02010-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 Brown46b9ac02010-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 Brown46b9ac02010-04-22 18:58:52 -0700253 }
Jeff Brown46b9ac02010-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 }
Jeff Browncc4f7db2011-08-30 20:34:48 -0700309
310 // Nothing to do if there is no pending event.
Jeff Brownb88102f2010-09-08 11:49:43 -0700311 if (! mPendingEvent) {
Jeff Browncc4f7db2011-08-30 20:34:48 -0700312 if (mActiveConnections.isEmpty()) {
313 dispatchIdleLocked();
314 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700315 return;
316 }
317 } else {
318 // Inbound queue has at least one entry.
Jeff Brownac386072011-07-20 15:19:50 -0700319 EventEntry* entry = mInboundQueue.head;
Jeff Brownb88102f2010-09-08 11:49:43 -0700320
321 // Throttle the entry if it is a move event and there are no
322 // other events behind it in the queue. Due to movement batching, additional
323 // samples may be appended to this event by the time the throttling timeout
324 // expires.
325 // TODO Make this smarter and consider throttling per device independently.
Jeff Brownb6997262010-10-08 22:31:17 -0700326 if (entry->type == EventEntry::TYPE_MOTION
327 && !isAppSwitchDue
328 && mDispatchEnabled
329 && (entry->policyFlags & POLICY_FLAG_PASS_TO_USER)
330 && !entry->isInjected()) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700331 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
332 int32_t deviceId = motionEntry->deviceId;
333 uint32_t source = motionEntry->source;
334 if (! isAppSwitchDue
Jeff Brownac386072011-07-20 15:19:50 -0700335 && !motionEntry->next // exactly one event, no successors
Jeff Browncc0c1592011-02-19 05:07:28 -0800336 && (motionEntry->action == AMOTION_EVENT_ACTION_MOVE
337 || motionEntry->action == AMOTION_EVENT_ACTION_HOVER_MOVE)
Jeff Brownb88102f2010-09-08 11:49:43 -0700338 && deviceId == mThrottleState.lastDeviceId
339 && source == mThrottleState.lastSource) {
340 nsecs_t nextTime = mThrottleState.lastEventTime
341 + mThrottleState.minTimeBetweenEvents;
342 if (currentTime < nextTime) {
343 // Throttle it!
344#if DEBUG_THROTTLING
345 LOGD("Throttling - Delaying motion event for "
Jeff Brown90655042010-12-02 13:50:46 -0800346 "device %d, source 0x%08x by up to %0.3fms.",
Jeff Brownb88102f2010-09-08 11:49:43 -0700347 deviceId, source, (nextTime - currentTime) * 0.000001);
348#endif
349 if (nextTime < *nextWakeupTime) {
350 *nextWakeupTime = nextTime;
351 }
352 if (mThrottleState.originalSampleCount == 0) {
353 mThrottleState.originalSampleCount =
354 motionEntry->countSamples();
355 }
356 return;
357 }
358 }
359
360#if DEBUG_THROTTLING
361 if (mThrottleState.originalSampleCount != 0) {
362 uint32_t count = motionEntry->countSamples();
363 LOGD("Throttling - Motion event sample count grew by %d from %d to %d.",
364 count - mThrottleState.originalSampleCount,
365 mThrottleState.originalSampleCount, count);
366 mThrottleState.originalSampleCount = 0;
367 }
368#endif
369
makarand.karvekarf634ded2011-03-02 15:41:03 -0600370 mThrottleState.lastEventTime = currentTime;
Jeff Brownb88102f2010-09-08 11:49:43 -0700371 mThrottleState.lastDeviceId = deviceId;
372 mThrottleState.lastSource = source;
373 }
374
375 mInboundQueue.dequeue(entry);
376 mPendingEvent = entry;
377 }
Jeff Browne2fe69e2010-10-18 13:21:23 -0700378
379 // Poke user activity for this event.
380 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
381 pokeUserActivityLocked(mPendingEvent);
382 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700383 }
384
385 // Now we have an event to dispatch.
Jeff Brown928e0542011-01-10 11:17:36 -0800386 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Jeff Brownb6110c22011-04-01 16:15:13 -0700387 LOG_ASSERT(mPendingEvent != NULL);
Jeff Brown54a18252010-09-16 14:07:33 -0700388 bool done = false;
Jeff Brownb6997262010-10-08 22:31:17 -0700389 DropReason dropReason = DROP_REASON_NOT_DROPPED;
390 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
391 dropReason = DROP_REASON_POLICY;
392 } else if (!mDispatchEnabled) {
393 dropReason = DROP_REASON_DISABLED;
394 }
Jeff Brown928e0542011-01-10 11:17:36 -0800395
396 if (mNextUnblockedEvent == mPendingEvent) {
397 mNextUnblockedEvent = NULL;
398 }
399
Jeff Brownb88102f2010-09-08 11:49:43 -0700400 switch (mPendingEvent->type) {
401 case EventEntry::TYPE_CONFIGURATION_CHANGED: {
402 ConfigurationChangedEntry* typedEntry =
403 static_cast<ConfigurationChangedEntry*>(mPendingEvent);
Jeff Brown54a18252010-09-16 14:07:33 -0700404 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Jeff Brownb6997262010-10-08 22:31:17 -0700405 dropReason = DROP_REASON_NOT_DROPPED; // configuration changes are never dropped
Jeff Brownb88102f2010-09-08 11:49:43 -0700406 break;
407 }
408
Jeff Brown65fd2512011-08-18 11:20:58 -0700409 case EventEntry::TYPE_DEVICE_RESET: {
410 DeviceResetEntry* typedEntry =
411 static_cast<DeviceResetEntry*>(mPendingEvent);
412 done = dispatchDeviceResetLocked(currentTime, typedEntry);
413 dropReason = DROP_REASON_NOT_DROPPED; // device resets are never dropped
414 break;
415 }
416
Jeff Brownb88102f2010-09-08 11:49:43 -0700417 case EventEntry::TYPE_KEY: {
418 KeyEntry* typedEntry = static_cast<KeyEntry*>(mPendingEvent);
Jeff Brownb6997262010-10-08 22:31:17 -0700419 if (isAppSwitchDue) {
420 if (isAppSwitchKeyEventLocked(typedEntry)) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700421 resetPendingAppSwitchLocked(true);
Jeff Brownb6997262010-10-08 22:31:17 -0700422 isAppSwitchDue = false;
423 } else if (dropReason == DROP_REASON_NOT_DROPPED) {
424 dropReason = DROP_REASON_APP_SWITCH;
Jeff Brownb88102f2010-09-08 11:49:43 -0700425 }
426 }
Jeff Brown928e0542011-01-10 11:17:36 -0800427 if (dropReason == DROP_REASON_NOT_DROPPED
428 && isStaleEventLocked(currentTime, typedEntry)) {
429 dropReason = DROP_REASON_STALE;
430 }
431 if (dropReason == DROP_REASON_NOT_DROPPED && mNextUnblockedEvent) {
432 dropReason = DROP_REASON_BLOCKED;
433 }
Jeff Brown214eaf42011-05-26 19:17:02 -0700434 done = dispatchKeyLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700435 break;
436 }
437
438 case EventEntry::TYPE_MOTION: {
439 MotionEntry* typedEntry = static_cast<MotionEntry*>(mPendingEvent);
Jeff Brownb6997262010-10-08 22:31:17 -0700440 if (dropReason == DROP_REASON_NOT_DROPPED && isAppSwitchDue) {
441 dropReason = DROP_REASON_APP_SWITCH;
Jeff Brownb88102f2010-09-08 11:49:43 -0700442 }
Jeff Brown928e0542011-01-10 11:17:36 -0800443 if (dropReason == DROP_REASON_NOT_DROPPED
444 && isStaleEventLocked(currentTime, typedEntry)) {
445 dropReason = DROP_REASON_STALE;
446 }
447 if (dropReason == DROP_REASON_NOT_DROPPED && mNextUnblockedEvent) {
448 dropReason = DROP_REASON_BLOCKED;
449 }
Jeff Brownb6997262010-10-08 22:31:17 -0700450 done = dispatchMotionLocked(currentTime, typedEntry,
Jeff Browne20c9e02010-10-11 14:20:19 -0700451 &dropReason, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700452 break;
453 }
454
455 default:
Jeff Brownb6110c22011-04-01 16:15:13 -0700456 LOG_ASSERT(false);
Jeff Brownb88102f2010-09-08 11:49:43 -0700457 break;
458 }
459
Jeff Brown54a18252010-09-16 14:07:33 -0700460 if (done) {
Jeff Brownb6997262010-10-08 22:31:17 -0700461 if (dropReason != DROP_REASON_NOT_DROPPED) {
462 dropInboundEventLocked(mPendingEvent, dropReason);
463 }
464
Jeff Brown54a18252010-09-16 14:07:33 -0700465 releasePendingEventLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -0700466 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
467 }
468}
469
Jeff Browncc4f7db2011-08-30 20:34:48 -0700470void InputDispatcher::dispatchIdleLocked() {
471#if DEBUG_FOCUS
472 LOGD("Dispatcher idle. There are no pending events or active connections.");
473#endif
474
475 // Reset targets when idle, to release input channels and other resources
476 // they are holding onto.
477 resetTargetsLocked();
478}
479
Jeff Brownb88102f2010-09-08 11:49:43 -0700480bool InputDispatcher::enqueueInboundEventLocked(EventEntry* entry) {
481 bool needWake = mInboundQueue.isEmpty();
482 mInboundQueue.enqueueAtTail(entry);
483
484 switch (entry->type) {
Jeff Brownb6997262010-10-08 22:31:17 -0700485 case EventEntry::TYPE_KEY: {
Jeff Brown928e0542011-01-10 11:17:36 -0800486 // Optimize app switch latency.
487 // If the application takes too long to catch up then we drop all events preceding
488 // the app switch key.
Jeff Brownb6997262010-10-08 22:31:17 -0700489 KeyEntry* keyEntry = static_cast<KeyEntry*>(entry);
490 if (isAppSwitchKeyEventLocked(keyEntry)) {
491 if (keyEntry->action == AKEY_EVENT_ACTION_DOWN) {
492 mAppSwitchSawKeyDown = true;
493 } else if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
494 if (mAppSwitchSawKeyDown) {
495#if DEBUG_APP_SWITCH
496 LOGD("App switch is pending!");
497#endif
498 mAppSwitchDueTime = keyEntry->eventTime + APP_SWITCH_TIMEOUT;
499 mAppSwitchSawKeyDown = false;
500 needWake = true;
501 }
502 }
503 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700504 break;
505 }
Jeff Brown928e0542011-01-10 11:17:36 -0800506
507 case EventEntry::TYPE_MOTION: {
508 // Optimize case where the current application is unresponsive and the user
509 // decides to touch a window in a different application.
510 // If the application takes too long to catch up then we drop all events preceding
511 // the touch into the other window.
512 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
Jeff Brown33bbfd22011-02-24 20:55:35 -0800513 if (motionEntry->action == AMOTION_EVENT_ACTION_DOWN
Jeff Brown928e0542011-01-10 11:17:36 -0800514 && (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER)
515 && mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY
Jeff Brown9302c872011-07-13 22:51:29 -0700516 && mInputTargetWaitApplicationHandle != NULL) {
Jeff Brown91c69ab2011-02-14 17:03:18 -0800517 int32_t x = int32_t(motionEntry->firstSample.pointerCoords[0].
Jeff Brownebbd5d12011-02-17 13:01:34 -0800518 getAxisValue(AMOTION_EVENT_AXIS_X));
Jeff Brown91c69ab2011-02-14 17:03:18 -0800519 int32_t y = int32_t(motionEntry->firstSample.pointerCoords[0].
Jeff Brownebbd5d12011-02-17 13:01:34 -0800520 getAxisValue(AMOTION_EVENT_AXIS_Y));
Jeff Brown9302c872011-07-13 22:51:29 -0700521 sp<InputWindowHandle> touchedWindowHandle = findTouchedWindowAtLocked(x, y);
522 if (touchedWindowHandle != NULL
523 && touchedWindowHandle->inputApplicationHandle
524 != mInputTargetWaitApplicationHandle) {
Jeff Brown928e0542011-01-10 11:17:36 -0800525 // User touched a different application than the one we are waiting on.
526 // Flag the event, and start pruning the input queue.
527 mNextUnblockedEvent = motionEntry;
528 needWake = true;
529 }
530 }
531 break;
532 }
Jeff Brownb6997262010-10-08 22:31:17 -0700533 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700534
535 return needWake;
536}
537
Jeff Brown9302c872011-07-13 22:51:29 -0700538sp<InputWindowHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t x, int32_t y) {
Jeff Brown928e0542011-01-10 11:17:36 -0800539 // Traverse windows from front to back to find touched window.
Jeff Brown9302c872011-07-13 22:51:29 -0700540 size_t numWindows = mWindowHandles.size();
Jeff Brown928e0542011-01-10 11:17:36 -0800541 for (size_t i = 0; i < numWindows; i++) {
Jeff Brown9302c872011-07-13 22:51:29 -0700542 sp<InputWindowHandle> windowHandle = mWindowHandles.itemAt(i);
Jeff Browncc4f7db2011-08-30 20:34:48 -0700543 const InputWindowInfo* windowInfo = windowHandle->getInfo();
544 int32_t flags = windowInfo->layoutParamsFlags;
Jeff Brown928e0542011-01-10 11:17:36 -0800545
Jeff Browncc4f7db2011-08-30 20:34:48 -0700546 if (windowInfo->visible) {
547 if (!(flags & InputWindowInfo::FLAG_NOT_TOUCHABLE)) {
548 bool isTouchModal = (flags & (InputWindowInfo::FLAG_NOT_FOCUSABLE
549 | InputWindowInfo::FLAG_NOT_TOUCH_MODAL)) == 0;
550 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
Jeff Brown928e0542011-01-10 11:17:36 -0800551 // Found window.
Jeff Brown9302c872011-07-13 22:51:29 -0700552 return windowHandle;
Jeff Brown928e0542011-01-10 11:17:36 -0800553 }
554 }
555 }
556
Jeff Browncc4f7db2011-08-30 20:34:48 -0700557 if (flags & InputWindowInfo::FLAG_SYSTEM_ERROR) {
Jeff Brown928e0542011-01-10 11:17:36 -0800558 // Error window is on top but not visible, so touch is dropped.
559 return NULL;
560 }
561 }
562 return NULL;
563}
564
Jeff Brownb6997262010-10-08 22:31:17 -0700565void InputDispatcher::dropInboundEventLocked(EventEntry* entry, DropReason dropReason) {
566 const char* reason;
567 switch (dropReason) {
568 case DROP_REASON_POLICY:
Jeff Browne20c9e02010-10-11 14:20:19 -0700569#if DEBUG_INBOUND_EVENT_DETAILS
Jeff Brown3122e442010-10-11 23:32:49 -0700570 LOGD("Dropped event because policy consumed it.");
Jeff Browne20c9e02010-10-11 14:20:19 -0700571#endif
Jeff Brown3122e442010-10-11 23:32:49 -0700572 reason = "inbound event was dropped because the policy consumed it";
Jeff Brownb6997262010-10-08 22:31:17 -0700573 break;
574 case DROP_REASON_DISABLED:
575 LOGI("Dropped event because input dispatch is disabled.");
576 reason = "inbound event was dropped because input dispatch is disabled";
577 break;
578 case DROP_REASON_APP_SWITCH:
579 LOGI("Dropped event because of pending overdue app switch.");
580 reason = "inbound event was dropped because of pending overdue app switch";
581 break;
Jeff Brown928e0542011-01-10 11:17:36 -0800582 case DROP_REASON_BLOCKED:
583 LOGI("Dropped event because the current application is not responding and the user "
Jeff Brown81346812011-06-28 20:08:48 -0700584 "has started interacting with a different application.");
Jeff Brown928e0542011-01-10 11:17:36 -0800585 reason = "inbound event was dropped because the current application is not responding "
Jeff Brown81346812011-06-28 20:08:48 -0700586 "and the user has started interacting with a different application";
Jeff Brown928e0542011-01-10 11:17:36 -0800587 break;
588 case DROP_REASON_STALE:
589 LOGI("Dropped event because it is stale.");
590 reason = "inbound event was dropped because it is stale";
591 break;
Jeff Brownb6997262010-10-08 22:31:17 -0700592 default:
Jeff Brownb6110c22011-04-01 16:15:13 -0700593 LOG_ASSERT(false);
Jeff Brownb6997262010-10-08 22:31:17 -0700594 return;
595 }
596
597 switch (entry->type) {
Jeff Brownda3d5a92011-03-29 15:11:34 -0700598 case EventEntry::TYPE_KEY: {
599 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
600 synthesizeCancelationEventsForAllConnectionsLocked(options);
Jeff Brownb6997262010-10-08 22:31:17 -0700601 break;
Jeff Brownda3d5a92011-03-29 15:11:34 -0700602 }
Jeff Brownb6997262010-10-08 22:31:17 -0700603 case EventEntry::TYPE_MOTION: {
604 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
605 if (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) {
Jeff Brownda3d5a92011-03-29 15:11:34 -0700606 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
607 synthesizeCancelationEventsForAllConnectionsLocked(options);
Jeff Brownb6997262010-10-08 22:31:17 -0700608 } else {
Jeff Brownda3d5a92011-03-29 15:11:34 -0700609 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
610 synthesizeCancelationEventsForAllConnectionsLocked(options);
Jeff Brownb6997262010-10-08 22:31:17 -0700611 }
612 break;
613 }
614 }
615}
616
617bool InputDispatcher::isAppSwitchKeyCode(int32_t keyCode) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700618 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL;
619}
620
Jeff Brownb6997262010-10-08 22:31:17 -0700621bool InputDispatcher::isAppSwitchKeyEventLocked(KeyEntry* keyEntry) {
622 return ! (keyEntry->flags & AKEY_EVENT_FLAG_CANCELED)
623 && isAppSwitchKeyCode(keyEntry->keyCode)
Jeff Browne20c9e02010-10-11 14:20:19 -0700624 && (keyEntry->policyFlags & POLICY_FLAG_TRUSTED)
Jeff Brownb6997262010-10-08 22:31:17 -0700625 && (keyEntry->policyFlags & POLICY_FLAG_PASS_TO_USER);
626}
627
Jeff Brownb88102f2010-09-08 11:49:43 -0700628bool InputDispatcher::isAppSwitchPendingLocked() {
629 return mAppSwitchDueTime != LONG_LONG_MAX;
630}
631
Jeff Brownb88102f2010-09-08 11:49:43 -0700632void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
633 mAppSwitchDueTime = LONG_LONG_MAX;
634
635#if DEBUG_APP_SWITCH
636 if (handled) {
637 LOGD("App switch has arrived.");
638 } else {
639 LOGD("App switch was abandoned.");
640 }
641#endif
Jeff Brown46b9ac02010-04-22 18:58:52 -0700642}
643
Jeff Brown928e0542011-01-10 11:17:36 -0800644bool InputDispatcher::isStaleEventLocked(nsecs_t currentTime, EventEntry* entry) {
645 return currentTime - entry->eventTime >= STALE_EVENT_TIMEOUT;
646}
647
Jeff Brown9c3cda02010-06-15 01:31:58 -0700648bool InputDispatcher::runCommandsLockedInterruptible() {
649 if (mCommandQueue.isEmpty()) {
650 return false;
651 }
Jeff Brown46b9ac02010-04-22 18:58:52 -0700652
Jeff Brown9c3cda02010-06-15 01:31:58 -0700653 do {
654 CommandEntry* commandEntry = mCommandQueue.dequeueAtHead();
655
656 Command command = commandEntry->command;
657 (this->*command)(commandEntry); // commands are implicitly 'LockedInterruptible'
658
Jeff Brown7fbdc842010-06-17 20:52:56 -0700659 commandEntry->connection.clear();
Jeff Brownac386072011-07-20 15:19:50 -0700660 delete commandEntry;
Jeff Brown9c3cda02010-06-15 01:31:58 -0700661 } while (! mCommandQueue.isEmpty());
662 return true;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700663}
664
Jeff Brown9c3cda02010-06-15 01:31:58 -0700665InputDispatcher::CommandEntry* InputDispatcher::postCommandLocked(Command command) {
Jeff Brownac386072011-07-20 15:19:50 -0700666 CommandEntry* commandEntry = new CommandEntry(command);
Jeff Brown9c3cda02010-06-15 01:31:58 -0700667 mCommandQueue.enqueueAtTail(commandEntry);
668 return commandEntry;
669}
670
Jeff Brownb88102f2010-09-08 11:49:43 -0700671void InputDispatcher::drainInboundQueueLocked() {
672 while (! mInboundQueue.isEmpty()) {
673 EventEntry* entry = mInboundQueue.dequeueAtHead();
Jeff Brown54a18252010-09-16 14:07:33 -0700674 releaseInboundEventLocked(entry);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700675 }
Jeff Brown46b9ac02010-04-22 18:58:52 -0700676}
677
Jeff Brown54a18252010-09-16 14:07:33 -0700678void InputDispatcher::releasePendingEventLocked() {
Jeff Brownb88102f2010-09-08 11:49:43 -0700679 if (mPendingEvent) {
Jeff Brown54a18252010-09-16 14:07:33 -0700680 releaseInboundEventLocked(mPendingEvent);
Jeff Brownb88102f2010-09-08 11:49:43 -0700681 mPendingEvent = NULL;
682 }
683}
684
Jeff Brown54a18252010-09-16 14:07:33 -0700685void InputDispatcher::releaseInboundEventLocked(EventEntry* entry) {
Jeff Brown01ce2e92010-09-26 22:20:12 -0700686 InjectionState* injectionState = entry->injectionState;
687 if (injectionState && injectionState->injectionResult == INPUT_EVENT_INJECTION_PENDING) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700688#if DEBUG_DISPATCH_CYCLE
Jeff Brown01ce2e92010-09-26 22:20:12 -0700689 LOGD("Injected inbound event was dropped.");
Jeff Brownb88102f2010-09-08 11:49:43 -0700690#endif
691 setInjectionResultLocked(entry, INPUT_EVENT_INJECTION_FAILED);
692 }
Jeff Brownabb4d442011-08-15 12:55:32 -0700693 if (entry == mNextUnblockedEvent) {
694 mNextUnblockedEvent = NULL;
695 }
Jeff Brownac386072011-07-20 15:19:50 -0700696 entry->release();
Jeff Brownb88102f2010-09-08 11:49:43 -0700697}
698
Jeff Brownb88102f2010-09-08 11:49:43 -0700699void InputDispatcher::resetKeyRepeatLocked() {
700 if (mKeyRepeatState.lastKeyEntry) {
Jeff Brownac386072011-07-20 15:19:50 -0700701 mKeyRepeatState.lastKeyEntry->release();
Jeff Brownb88102f2010-09-08 11:49:43 -0700702 mKeyRepeatState.lastKeyEntry = NULL;
703 }
704}
705
Jeff Brown214eaf42011-05-26 19:17:02 -0700706InputDispatcher::KeyEntry* InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
Jeff Brown349703e2010-06-22 01:27:15 -0700707 KeyEntry* entry = mKeyRepeatState.lastKeyEntry;
708
Jeff Brown349703e2010-06-22 01:27:15 -0700709 // Reuse the repeated key entry if it is otherwise unreferenced.
Jeff Browne20c9e02010-10-11 14:20:19 -0700710 uint32_t policyFlags = (entry->policyFlags & POLICY_FLAG_RAW_MASK)
711 | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700712 if (entry->refCount == 1) {
Jeff Brownac386072011-07-20 15:19:50 -0700713 entry->recycle();
Jeff Brown7fbdc842010-06-17 20:52:56 -0700714 entry->eventTime = currentTime;
Jeff Brown7fbdc842010-06-17 20:52:56 -0700715 entry->policyFlags = policyFlags;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700716 entry->repeatCount += 1;
717 } else {
Jeff Brownac386072011-07-20 15:19:50 -0700718 KeyEntry* newEntry = new KeyEntry(currentTime,
Jeff Brownc5ed5912010-07-14 18:48:53 -0700719 entry->deviceId, entry->source, policyFlags,
Jeff Brown7fbdc842010-06-17 20:52:56 -0700720 entry->action, entry->flags, entry->keyCode, entry->scanCode,
Jeff Brown00fa7bd2010-07-02 15:37:36 -0700721 entry->metaState, entry->repeatCount + 1, entry->downTime);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700722
723 mKeyRepeatState.lastKeyEntry = newEntry;
Jeff Brownac386072011-07-20 15:19:50 -0700724 entry->release();
Jeff Brown46b9ac02010-04-22 18:58:52 -0700725
726 entry = newEntry;
727 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700728 entry->syntheticRepeat = true;
729
730 // Increment reference count since we keep a reference to the event in
731 // mKeyRepeatState.lastKeyEntry in addition to the one we return.
732 entry->refCount += 1;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700733
Jeff Brown214eaf42011-05-26 19:17:02 -0700734 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Jeff Brownb88102f2010-09-08 11:49:43 -0700735 return entry;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700736}
737
Jeff Brownb88102f2010-09-08 11:49:43 -0700738bool InputDispatcher::dispatchConfigurationChangedLocked(
739 nsecs_t currentTime, ConfigurationChangedEntry* entry) {
Jeff Brown46b9ac02010-04-22 18:58:52 -0700740#if DEBUG_OUTBOUND_EVENT_DETAILS
Jeff Brownb88102f2010-09-08 11:49:43 -0700741 LOGD("dispatchConfigurationChanged - eventTime=%lld", entry->eventTime);
742#endif
743
744 // Reset key repeating in case a keyboard device was added or removed or something.
745 resetKeyRepeatLocked();
746
747 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
748 CommandEntry* commandEntry = postCommandLocked(
749 & InputDispatcher::doNotifyConfigurationChangedInterruptible);
750 commandEntry->eventTime = entry->eventTime;
751 return true;
752}
753
Jeff Brown65fd2512011-08-18 11:20:58 -0700754bool InputDispatcher::dispatchDeviceResetLocked(
755 nsecs_t currentTime, DeviceResetEntry* entry) {
756#if DEBUG_OUTBOUND_EVENT_DETAILS
757 LOGD("dispatchDeviceReset - eventTime=%lld, deviceId=%d", entry->eventTime, entry->deviceId);
758#endif
759
760 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
761 "device was reset");
762 options.deviceId = entry->deviceId;
763 synthesizeCancelationEventsForAllConnectionsLocked(options);
764 return true;
765}
766
Jeff Brown214eaf42011-05-26 19:17:02 -0700767bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, KeyEntry* entry,
Jeff Browne20c9e02010-10-11 14:20:19 -0700768 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Jeff Browne46a0a42010-11-02 17:58:22 -0700769 // Preprocessing.
770 if (! entry->dispatchInProgress) {
771 if (entry->repeatCount == 0
772 && entry->action == AKEY_EVENT_ACTION_DOWN
773 && (entry->policyFlags & POLICY_FLAG_TRUSTED)
Jeff Brown0029c662011-03-30 02:25:18 -0700774 && (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
Jeff Browne46a0a42010-11-02 17:58:22 -0700775 if (mKeyRepeatState.lastKeyEntry
776 && mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode) {
777 // We have seen two identical key downs in a row which indicates that the device
778 // driver is automatically generating key repeats itself. We take note of the
779 // repeat here, but we disable our own next key repeat timer since it is clear that
780 // we will not need to synthesize key repeats ourselves.
781 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
782 resetKeyRepeatLocked();
783 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
784 } else {
785 // Not a repeat. Save key down state in case we do see a repeat later.
786 resetKeyRepeatLocked();
Jeff Brown214eaf42011-05-26 19:17:02 -0700787 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
Jeff Browne46a0a42010-11-02 17:58:22 -0700788 }
789 mKeyRepeatState.lastKeyEntry = entry;
790 entry->refCount += 1;
791 } else if (! entry->syntheticRepeat) {
792 resetKeyRepeatLocked();
793 }
794
Jeff Browne2e01262011-03-02 20:34:30 -0800795 if (entry->repeatCount == 1) {
796 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
797 } else {
798 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
799 }
800
Jeff Browne46a0a42010-11-02 17:58:22 -0700801 entry->dispatchInProgress = true;
802 resetTargetsLocked();
803
804 logOutboundKeyDetailsLocked("dispatchKey - ", entry);
805 }
806
Jeff Brown54a18252010-09-16 14:07:33 -0700807 // Give the policy a chance to intercept the key.
808 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
Jeff Browne20c9e02010-10-11 14:20:19 -0700809 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Jeff Brown54a18252010-09-16 14:07:33 -0700810 CommandEntry* commandEntry = postCommandLocked(
811 & InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
Jeff Brown9302c872011-07-13 22:51:29 -0700812 if (mFocusedWindowHandle != NULL) {
813 commandEntry->inputWindowHandle = mFocusedWindowHandle;
Jeff Brown54a18252010-09-16 14:07:33 -0700814 }
815 commandEntry->keyEntry = entry;
816 entry->refCount += 1;
817 return false; // wait for the command to run
818 } else {
819 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
820 }
821 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Jeff Browne20c9e02010-10-11 14:20:19 -0700822 if (*dropReason == DROP_REASON_NOT_DROPPED) {
823 *dropReason = DROP_REASON_POLICY;
824 }
Jeff Brown54a18252010-09-16 14:07:33 -0700825 }
826
827 // Clean up if dropping the event.
Jeff Browne20c9e02010-10-11 14:20:19 -0700828 if (*dropReason != DROP_REASON_NOT_DROPPED) {
Jeff Brown54a18252010-09-16 14:07:33 -0700829 resetTargetsLocked();
Jeff Brown3122e442010-10-11 23:32:49 -0700830 setInjectionResultLocked(entry, *dropReason == DROP_REASON_POLICY
831 ? INPUT_EVENT_INJECTION_SUCCEEDED : INPUT_EVENT_INJECTION_FAILED);
Jeff Brown54a18252010-09-16 14:07:33 -0700832 return true;
833 }
834
Jeff Brownb88102f2010-09-08 11:49:43 -0700835 // Identify targets.
836 if (! mCurrentInputTargetsValid) {
Jeff Brown01ce2e92010-09-26 22:20:12 -0700837 int32_t injectionResult = findFocusedWindowTargetsLocked(currentTime,
838 entry, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700839 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
840 return false;
841 }
842
843 setInjectionResultLocked(entry, injectionResult);
844 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
845 return true;
846 }
847
848 addMonitoringTargetsLocked();
Jeff Brown01ce2e92010-09-26 22:20:12 -0700849 commitTargetsLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -0700850 }
851
852 // Dispatch the key.
853 dispatchEventToCurrentInputTargetsLocked(currentTime, entry, false);
Jeff Brownb88102f2010-09-08 11:49:43 -0700854 return true;
855}
856
857void InputDispatcher::logOutboundKeyDetailsLocked(const char* prefix, const KeyEntry* entry) {
858#if DEBUG_OUTBOUND_EVENT_DETAILS
Jeff Brown90655042010-12-02 13:50:46 -0800859 LOGD("%seventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, "
Jeff Brownb88102f2010-09-08 11:49:43 -0700860 "action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, "
Jeff Browne46a0a42010-11-02 17:58:22 -0700861 "repeatCount=%d, downTime=%lld",
Jeff Brownb88102f2010-09-08 11:49:43 -0700862 prefix,
863 entry->eventTime, entry->deviceId, entry->source, entry->policyFlags,
864 entry->action, entry->flags, entry->keyCode, entry->scanCode, entry->metaState,
Jeff Browne46a0a42010-11-02 17:58:22 -0700865 entry->repeatCount, entry->downTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700866#endif
867}
868
869bool InputDispatcher::dispatchMotionLocked(
Jeff Browne20c9e02010-10-11 14:20:19 -0700870 nsecs_t currentTime, MotionEntry* entry, DropReason* dropReason, nsecs_t* nextWakeupTime) {
Jeff Browne46a0a42010-11-02 17:58:22 -0700871 // Preprocessing.
872 if (! entry->dispatchInProgress) {
873 entry->dispatchInProgress = true;
874 resetTargetsLocked();
875
876 logOutboundMotionDetailsLocked("dispatchMotion - ", entry);
877 }
878
Jeff Brown54a18252010-09-16 14:07:33 -0700879 // Clean up if dropping the event.
Jeff Browne20c9e02010-10-11 14:20:19 -0700880 if (*dropReason != DROP_REASON_NOT_DROPPED) {
Jeff Brown54a18252010-09-16 14:07:33 -0700881 resetTargetsLocked();
Jeff Brown3122e442010-10-11 23:32:49 -0700882 setInjectionResultLocked(entry, *dropReason == DROP_REASON_POLICY
883 ? INPUT_EVENT_INJECTION_SUCCEEDED : INPUT_EVENT_INJECTION_FAILED);
Jeff Brown54a18252010-09-16 14:07:33 -0700884 return true;
885 }
886
Jeff Brownb88102f2010-09-08 11:49:43 -0700887 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
888
889 // Identify targets.
Jeff Browncc0c1592011-02-19 05:07:28 -0800890 bool conflictingPointerActions = false;
Jeff Brownb88102f2010-09-08 11:49:43 -0700891 if (! mCurrentInputTargetsValid) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700892 int32_t injectionResult;
Jeff Browna032cc02011-03-07 16:56:21 -0800893 const MotionSample* splitBatchAfterSample = NULL;
Jeff Brownb88102f2010-09-08 11:49:43 -0700894 if (isPointerEvent) {
895 // Pointer event. (eg. touchscreen)
Jeff Brown01ce2e92010-09-26 22:20:12 -0700896 injectionResult = findTouchedWindowTargetsLocked(currentTime,
Jeff Browna032cc02011-03-07 16:56:21 -0800897 entry, nextWakeupTime, &conflictingPointerActions, &splitBatchAfterSample);
Jeff Brownb88102f2010-09-08 11:49:43 -0700898 } else {
899 // Non touch event. (eg. trackball)
Jeff Brown01ce2e92010-09-26 22:20:12 -0700900 injectionResult = findFocusedWindowTargetsLocked(currentTime,
901 entry, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700902 }
903 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
904 return false;
905 }
906
907 setInjectionResultLocked(entry, injectionResult);
908 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
909 return true;
910 }
911
912 addMonitoringTargetsLocked();
Jeff Brown01ce2e92010-09-26 22:20:12 -0700913 commitTargetsLocked();
Jeff Browna032cc02011-03-07 16:56:21 -0800914
915 // Unbatch the event if necessary by splitting it into two parts after the
916 // motion sample indicated by splitBatchAfterSample.
917 if (splitBatchAfterSample && splitBatchAfterSample->next) {
918#if DEBUG_BATCHING
919 uint32_t originalSampleCount = entry->countSamples();
920#endif
921 MotionSample* nextSample = splitBatchAfterSample->next;
Jeff Brownac386072011-07-20 15:19:50 -0700922 MotionEntry* nextEntry = new MotionEntry(nextSample->eventTime,
Jeff Browna032cc02011-03-07 16:56:21 -0800923 entry->deviceId, entry->source, entry->policyFlags,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700924 entry->action, entry->flags,
925 entry->metaState, entry->buttonState, entry->edgeFlags,
Jeff Browna032cc02011-03-07 16:56:21 -0800926 entry->xPrecision, entry->yPrecision, entry->downTime,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700927 entry->pointerCount, entry->pointerProperties, nextSample->pointerCoords);
Jeff Browna032cc02011-03-07 16:56:21 -0800928 if (nextSample != entry->lastSample) {
929 nextEntry->firstSample.next = nextSample->next;
930 nextEntry->lastSample = entry->lastSample;
931 }
Jeff Brownac386072011-07-20 15:19:50 -0700932 delete nextSample;
Jeff Browna032cc02011-03-07 16:56:21 -0800933
934 entry->lastSample = const_cast<MotionSample*>(splitBatchAfterSample);
935 entry->lastSample->next = NULL;
936
937 if (entry->injectionState) {
938 nextEntry->injectionState = entry->injectionState;
939 entry->injectionState->refCount += 1;
940 }
941
942#if DEBUG_BATCHING
943 LOGD("Split batch of %d samples into two parts, first part has %d samples, "
944 "second part has %d samples.", originalSampleCount,
945 entry->countSamples(), nextEntry->countSamples());
946#endif
947
948 mInboundQueue.enqueueAtHead(nextEntry);
949 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700950 }
951
952 // Dispatch the motion.
Jeff Browncc0c1592011-02-19 05:07:28 -0800953 if (conflictingPointerActions) {
Jeff Brownda3d5a92011-03-29 15:11:34 -0700954 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
955 "conflicting pointer actions");
956 synthesizeCancelationEventsForAllConnectionsLocked(options);
Jeff Browncc0c1592011-02-19 05:07:28 -0800957 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700958 dispatchEventToCurrentInputTargetsLocked(currentTime, entry, false);
Jeff Brownb88102f2010-09-08 11:49:43 -0700959 return true;
960}
961
962
963void InputDispatcher::logOutboundMotionDetailsLocked(const char* prefix, const MotionEntry* entry) {
964#if DEBUG_OUTBOUND_EVENT_DETAILS
Jeff Brown90655042010-12-02 13:50:46 -0800965 LOGD("%seventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, "
Jeff Brown85a31762010-09-01 17:01:00 -0700966 "action=0x%x, flags=0x%x, "
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700967 "metaState=0x%x, buttonState=0x%x, "
968 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%lld",
Jeff Brownb88102f2010-09-08 11:49:43 -0700969 prefix,
Jeff Brown85a31762010-09-01 17:01:00 -0700970 entry->eventTime, entry->deviceId, entry->source, entry->policyFlags,
971 entry->action, entry->flags,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700972 entry->metaState, entry->buttonState,
973 entry->edgeFlags, entry->xPrecision, entry->yPrecision,
Jeff Brown46b9ac02010-04-22 18:58:52 -0700974 entry->downTime);
975
976 // Print the most recent sample that we have available, this may change due to batching.
977 size_t sampleCount = 1;
Jeff Brownb88102f2010-09-08 11:49:43 -0700978 const MotionSample* sample = & entry->firstSample;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700979 for (; sample->next != NULL; sample = sample->next) {
980 sampleCount += 1;
981 }
982 for (uint32_t i = 0; i < entry->pointerCount; i++) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700983 LOGD(" Pointer %d: id=%d, toolType=%d, "
984 "x=%f, y=%f, pressure=%f, size=%f, "
Jeff Brown85a31762010-09-01 17:01:00 -0700985 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
Jeff Brown8d608662010-08-30 03:02:23 -0700986 "orientation=%f",
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700987 i, entry->pointerProperties[i].id,
988 entry->pointerProperties[i].toolType,
Jeff Brownebbd5d12011-02-17 13:01:34 -0800989 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
990 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
991 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
992 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
993 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
994 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
995 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
996 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
997 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Jeff Brown46b9ac02010-04-22 18:58:52 -0700998 }
999
1000 // Keep in mind that due to batching, it is possible for the number of samples actually
1001 // dispatched to change before the application finally consumed them.
Jeff Brownc5ed5912010-07-14 18:48:53 -07001002 if (entry->action == AMOTION_EVENT_ACTION_MOVE) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07001003 LOGD(" ... Total movement samples currently batched %d ...", sampleCount);
1004 }
1005#endif
Jeff Brown46b9ac02010-04-22 18:58:52 -07001006}
1007
1008void InputDispatcher::dispatchEventToCurrentInputTargetsLocked(nsecs_t currentTime,
1009 EventEntry* eventEntry, bool resumeWithAppendedMotionSample) {
1010#if DEBUG_DISPATCH_CYCLE
Jeff Brown9c3cda02010-06-15 01:31:58 -07001011 LOGD("dispatchEventToCurrentInputTargets - "
Jeff Brown46b9ac02010-04-22 18:58:52 -07001012 "resumeWithAppendedMotionSample=%s",
Jeff Brownb88102f2010-09-08 11:49:43 -07001013 toString(resumeWithAppendedMotionSample));
Jeff Brown46b9ac02010-04-22 18:58:52 -07001014#endif
1015
Jeff Brownb6110c22011-04-01 16:15:13 -07001016 LOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
Jeff Brown9c3cda02010-06-15 01:31:58 -07001017
Jeff Browne2fe69e2010-10-18 13:21:23 -07001018 pokeUserActivityLocked(eventEntry);
1019
Jeff Brown46b9ac02010-04-22 18:58:52 -07001020 for (size_t i = 0; i < mCurrentInputTargets.size(); i++) {
1021 const InputTarget& inputTarget = mCurrentInputTargets.itemAt(i);
1022
Jeff Brown519e0242010-09-15 15:18:56 -07001023 ssize_t connectionIndex = getConnectionIndexLocked(inputTarget.inputChannel);
Jeff Brown46b9ac02010-04-22 18:58:52 -07001024 if (connectionIndex >= 0) {
1025 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
Jeff Brown7fbdc842010-06-17 20:52:56 -07001026 prepareDispatchCycleLocked(currentTime, connection, eventEntry, & inputTarget,
Jeff Brown46b9ac02010-04-22 18:58:52 -07001027 resumeWithAppendedMotionSample);
1028 } else {
Jeff Brownb6997262010-10-08 22:31:17 -07001029#if DEBUG_FOCUS
1030 LOGD("Dropping event delivery to target with channel '%s' because it "
1031 "is no longer registered with the input dispatcher.",
Jeff Brown46b9ac02010-04-22 18:58:52 -07001032 inputTarget.inputChannel->getName().string());
Jeff Brownb6997262010-10-08 22:31:17 -07001033#endif
Jeff Brown46b9ac02010-04-22 18:58:52 -07001034 }
1035 }
1036}
1037
Jeff Brown54a18252010-09-16 14:07:33 -07001038void InputDispatcher::resetTargetsLocked() {
Jeff Brownb88102f2010-09-08 11:49:43 -07001039 mCurrentInputTargetsValid = false;
1040 mCurrentInputTargets.clear();
Jeff Brown5ea29ab2011-07-27 11:50:51 -07001041 resetANRTimeoutsLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -07001042}
1043
Jeff Brown01ce2e92010-09-26 22:20:12 -07001044void InputDispatcher::commitTargetsLocked() {
Jeff Brownb88102f2010-09-08 11:49:43 -07001045 mCurrentInputTargetsValid = true;
1046}
1047
1048int32_t InputDispatcher::handleTargetsNotReadyLocked(nsecs_t currentTime,
Jeff Brown9302c872011-07-13 22:51:29 -07001049 const EventEntry* entry,
1050 const sp<InputApplicationHandle>& applicationHandle,
1051 const sp<InputWindowHandle>& windowHandle,
Jeff Brownb88102f2010-09-08 11:49:43 -07001052 nsecs_t* nextWakeupTime) {
Jeff Brown9302c872011-07-13 22:51:29 -07001053 if (applicationHandle == NULL && windowHandle == NULL) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001054 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY) {
1055#if DEBUG_FOCUS
1056 LOGD("Waiting for system to become ready for input.");
1057#endif
1058 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY;
1059 mInputTargetWaitStartTime = currentTime;
1060 mInputTargetWaitTimeoutTime = LONG_LONG_MAX;
1061 mInputTargetWaitTimeoutExpired = false;
Jeff Brown9302c872011-07-13 22:51:29 -07001062 mInputTargetWaitApplicationHandle.clear();
Jeff Brownb88102f2010-09-08 11:49:43 -07001063 }
1064 } else {
1065 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
1066#if DEBUG_FOCUS
Jeff Brown519e0242010-09-15 15:18:56 -07001067 LOGD("Waiting for application to become ready for input: %s",
Jeff Brown9302c872011-07-13 22:51:29 -07001068 getApplicationWindowLabelLocked(applicationHandle, windowHandle).string());
Jeff Brownb88102f2010-09-08 11:49:43 -07001069#endif
Jeff Browncc4f7db2011-08-30 20:34:48 -07001070 nsecs_t timeout;
1071 if (windowHandle != NULL) {
1072 timeout = windowHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
1073 } else if (applicationHandle != NULL) {
1074 timeout = applicationHandle->getDispatchingTimeout(
1075 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
1076 } else {
1077 timeout = DEFAULT_INPUT_DISPATCHING_TIMEOUT;
1078 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001079
1080 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY;
1081 mInputTargetWaitStartTime = currentTime;
1082 mInputTargetWaitTimeoutTime = currentTime + timeout;
1083 mInputTargetWaitTimeoutExpired = false;
Jeff Brown9302c872011-07-13 22:51:29 -07001084 mInputTargetWaitApplicationHandle.clear();
Jeff Brown928e0542011-01-10 11:17:36 -08001085
Jeff Brown9302c872011-07-13 22:51:29 -07001086 if (windowHandle != NULL) {
1087 mInputTargetWaitApplicationHandle = windowHandle->inputApplicationHandle;
Jeff Brown928e0542011-01-10 11:17:36 -08001088 }
Jeff Brown9302c872011-07-13 22:51:29 -07001089 if (mInputTargetWaitApplicationHandle == NULL && applicationHandle != NULL) {
1090 mInputTargetWaitApplicationHandle = applicationHandle;
Jeff Brown928e0542011-01-10 11:17:36 -08001091 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001092 }
1093 }
1094
1095 if (mInputTargetWaitTimeoutExpired) {
1096 return INPUT_EVENT_INJECTION_TIMED_OUT;
1097 }
1098
1099 if (currentTime >= mInputTargetWaitTimeoutTime) {
Jeff Brown9302c872011-07-13 22:51:29 -07001100 onANRLocked(currentTime, applicationHandle, windowHandle,
1101 entry->eventTime, mInputTargetWaitStartTime);
Jeff Brownb88102f2010-09-08 11:49:43 -07001102
1103 // Force poll loop to wake up immediately on next iteration once we get the
1104 // ANR response back from the policy.
1105 *nextWakeupTime = LONG_LONG_MIN;
1106 return INPUT_EVENT_INJECTION_PENDING;
1107 } else {
1108 // Force poll loop to wake up when timeout is due.
1109 if (mInputTargetWaitTimeoutTime < *nextWakeupTime) {
1110 *nextWakeupTime = mInputTargetWaitTimeoutTime;
1111 }
1112 return INPUT_EVENT_INJECTION_PENDING;
1113 }
1114}
1115
Jeff Brown519e0242010-09-15 15:18:56 -07001116void InputDispatcher::resumeAfterTargetsNotReadyTimeoutLocked(nsecs_t newTimeout,
1117 const sp<InputChannel>& inputChannel) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001118 if (newTimeout > 0) {
1119 // Extend the timeout.
1120 mInputTargetWaitTimeoutTime = now() + newTimeout;
1121 } else {
1122 // Give up.
1123 mInputTargetWaitTimeoutExpired = true;
Jeff Brown519e0242010-09-15 15:18:56 -07001124
Jeff Brown01ce2e92010-09-26 22:20:12 -07001125 // Release the touch targets.
1126 mTouchState.reset();
Jeff Brown2a95c2a2010-09-16 12:31:46 -07001127
Jeff Brown519e0242010-09-15 15:18:56 -07001128 // Input state will not be realistic. Mark it out of sync.
Jeff Browndc3e0052010-09-16 11:02:16 -07001129 if (inputChannel.get()) {
1130 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
1131 if (connectionIndex >= 0) {
1132 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
Jeff Brown00045a72010-12-09 18:10:30 -08001133 if (connection->status == Connection::STATUS_NORMAL) {
Jeff Brownda3d5a92011-03-29 15:11:34 -07001134 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
Jeff Brown00045a72010-12-09 18:10:30 -08001135 "application not responding");
Jeff Brownda3d5a92011-03-29 15:11:34 -07001136 synthesizeCancelationEventsForConnectionLocked(connection, options);
Jeff Brown00045a72010-12-09 18:10:30 -08001137 }
Jeff Browndc3e0052010-09-16 11:02:16 -07001138 }
Jeff Brown519e0242010-09-15 15:18:56 -07001139 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001140 }
1141}
1142
Jeff Brown519e0242010-09-15 15:18:56 -07001143nsecs_t InputDispatcher::getTimeSpentWaitingForApplicationLocked(
Jeff Brownb88102f2010-09-08 11:49:43 -07001144 nsecs_t currentTime) {
1145 if (mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
1146 return currentTime - mInputTargetWaitStartTime;
1147 }
1148 return 0;
1149}
1150
1151void InputDispatcher::resetANRTimeoutsLocked() {
1152#if DEBUG_FOCUS
1153 LOGD("Resetting ANR timeouts.");
1154#endif
1155
Jeff Brownb88102f2010-09-08 11:49:43 -07001156 // Reset input target wait timeout.
1157 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_NONE;
Jeff Brown5ea29ab2011-07-27 11:50:51 -07001158 mInputTargetWaitApplicationHandle.clear();
Jeff Brownb88102f2010-09-08 11:49:43 -07001159}
1160
Jeff Brown01ce2e92010-09-26 22:20:12 -07001161int32_t InputDispatcher::findFocusedWindowTargetsLocked(nsecs_t currentTime,
1162 const EventEntry* entry, nsecs_t* nextWakeupTime) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001163 mCurrentInputTargets.clear();
1164
1165 int32_t injectionResult;
1166
1167 // If there is no currently focused window and no focused application
1168 // then drop the event.
Jeff Brown9302c872011-07-13 22:51:29 -07001169 if (mFocusedWindowHandle == NULL) {
1170 if (mFocusedApplicationHandle != NULL) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001171#if DEBUG_FOCUS
1172 LOGD("Waiting because there is no focused window but there is a "
Jeff Brown519e0242010-09-15 15:18:56 -07001173 "focused application that may eventually add a window: %s.",
Jeff Brown9302c872011-07-13 22:51:29 -07001174 getApplicationWindowLabelLocked(mFocusedApplicationHandle, NULL).string());
Jeff Brownb88102f2010-09-08 11:49:43 -07001175#endif
1176 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brown9302c872011-07-13 22:51:29 -07001177 mFocusedApplicationHandle, NULL, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -07001178 goto Unresponsive;
1179 }
1180
1181 LOGI("Dropping event because there is no focused window or focused application.");
1182 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1183 goto Failed;
1184 }
1185
1186 // Check permissions.
Jeff Brown9302c872011-07-13 22:51:29 -07001187 if (! checkInjectionPermission(mFocusedWindowHandle, entry->injectionState)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001188 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1189 goto Failed;
1190 }
1191
1192 // If the currently focused window is paused then keep waiting.
Jeff Browncc4f7db2011-08-30 20:34:48 -07001193 if (mFocusedWindowHandle->getInfo()->paused) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001194#if DEBUG_FOCUS
1195 LOGD("Waiting because focused window is paused.");
1196#endif
1197 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brown9302c872011-07-13 22:51:29 -07001198 mFocusedApplicationHandle, mFocusedWindowHandle, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -07001199 goto Unresponsive;
1200 }
1201
Jeff Brown519e0242010-09-15 15:18:56 -07001202 // If the currently focused window is still working on previous events then keep waiting.
Jeff Brown9302c872011-07-13 22:51:29 -07001203 if (! isWindowFinishedWithPreviousInputLocked(mFocusedWindowHandle)) {
Jeff Brown519e0242010-09-15 15:18:56 -07001204#if DEBUG_FOCUS
1205 LOGD("Waiting because focused window still processing previous input.");
1206#endif
1207 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brown9302c872011-07-13 22:51:29 -07001208 mFocusedApplicationHandle, mFocusedWindowHandle, nextWakeupTime);
Jeff Brown519e0242010-09-15 15:18:56 -07001209 goto Unresponsive;
1210 }
1211
Jeff Brownb88102f2010-09-08 11:49:43 -07001212 // Success! Output targets.
1213 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
Jeff Brown9302c872011-07-13 22:51:29 -07001214 addWindowTargetLocked(mFocusedWindowHandle,
Jeff Browna032cc02011-03-07 16:56:21 -08001215 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS, BitSet32(0));
Jeff Brownb88102f2010-09-08 11:49:43 -07001216
1217 // Done.
1218Failed:
1219Unresponsive:
Jeff Brown519e0242010-09-15 15:18:56 -07001220 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
1221 updateDispatchStatisticsLocked(currentTime, entry,
1222 injectionResult, timeSpentWaitingForApplication);
Jeff Brownb88102f2010-09-08 11:49:43 -07001223#if DEBUG_FOCUS
Jeff Brown519e0242010-09-15 15:18:56 -07001224 LOGD("findFocusedWindow finished: injectionResult=%d, "
1225 "timeSpendWaitingForApplication=%0.1fms",
1226 injectionResult, timeSpentWaitingForApplication / 1000000.0);
Jeff Brownb88102f2010-09-08 11:49:43 -07001227#endif
1228 return injectionResult;
1229}
1230
Jeff Brown01ce2e92010-09-26 22:20:12 -07001231int32_t InputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime,
Jeff Browna032cc02011-03-07 16:56:21 -08001232 const MotionEntry* entry, nsecs_t* nextWakeupTime, bool* outConflictingPointerActions,
1233 const MotionSample** outSplitBatchAfterSample) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001234 enum InjectionPermission {
1235 INJECTION_PERMISSION_UNKNOWN,
1236 INJECTION_PERMISSION_GRANTED,
1237 INJECTION_PERMISSION_DENIED
1238 };
1239
Jeff Brownb88102f2010-09-08 11:49:43 -07001240 mCurrentInputTargets.clear();
1241
1242 nsecs_t startTime = now();
1243
1244 // For security reasons, we defer updating the touch state until we are sure that
1245 // event injection will be allowed.
1246 //
1247 // FIXME In the original code, screenWasOff could never be set to true.
1248 // The reason is that the POLICY_FLAG_WOKE_HERE
1249 // and POLICY_FLAG_BRIGHT_HERE flags were set only when preprocessing raw
1250 // EV_KEY, EV_REL and EV_ABS events. As it happens, the touch event was
1251 // actually enqueued using the policyFlags that appeared in the final EV_SYN
1252 // events upon which no preprocessing took place. So policyFlags was always 0.
1253 // In the new native input dispatcher we're a bit more careful about event
1254 // preprocessing so the touches we receive can actually have non-zero policyFlags.
1255 // Unfortunately we obtain undesirable behavior.
1256 //
1257 // Here's what happens:
1258 //
1259 // When the device dims in anticipation of going to sleep, touches
1260 // in windows which have FLAG_TOUCHABLE_WHEN_WAKING cause
1261 // the device to brighten and reset the user activity timer.
1262 // Touches on other windows (such as the launcher window)
1263 // are dropped. Then after a moment, the device goes to sleep. Oops.
1264 //
1265 // Also notice how screenWasOff was being initialized using POLICY_FLAG_BRIGHT_HERE
1266 // instead of POLICY_FLAG_WOKE_HERE...
1267 //
1268 bool screenWasOff = false; // original policy: policyFlags & POLICY_FLAG_BRIGHT_HERE;
1269
1270 int32_t action = entry->action;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001271 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Jeff Brownb88102f2010-09-08 11:49:43 -07001272
1273 // Update the touch state as needed based on the properties of the touch event.
Jeff Brown01ce2e92010-09-26 22:20:12 -07001274 int32_t injectionResult = INPUT_EVENT_INJECTION_PENDING;
1275 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
Jeff Brown9302c872011-07-13 22:51:29 -07001276 sp<InputWindowHandle> newHoverWindowHandle;
Jeff Browncc0c1592011-02-19 05:07:28 -08001277
1278 bool isSplit = mTouchState.split;
Jeff Brown2717eff2011-06-30 23:53:07 -07001279 bool switchedDevice = mTouchState.deviceId >= 0
1280 && (mTouchState.deviceId != entry->deviceId
1281 || mTouchState.source != entry->source);
Jeff Browna032cc02011-03-07 16:56:21 -08001282 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE
1283 || maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER
1284 || maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1285 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN
1286 || maskedAction == AMOTION_EVENT_ACTION_SCROLL
1287 || isHoverAction);
Jeff Brown81346812011-06-28 20:08:48 -07001288 bool wrongDevice = false;
Jeff Browna032cc02011-03-07 16:56:21 -08001289 if (newGesture) {
Jeff Browncc0c1592011-02-19 05:07:28 -08001290 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Jeff Brown81346812011-06-28 20:08:48 -07001291 if (switchedDevice && mTouchState.down && !down) {
1292#if DEBUG_FOCUS
1293 LOGD("Dropping event because a pointer for a different device is already down.");
1294#endif
Jeff Browncc0c1592011-02-19 05:07:28 -08001295 mTempTouchState.copyFrom(mTouchState);
Jeff Brown81346812011-06-28 20:08:48 -07001296 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1297 switchedDevice = false;
1298 wrongDevice = true;
1299 goto Failed;
Jeff Browncc0c1592011-02-19 05:07:28 -08001300 }
Jeff Brown81346812011-06-28 20:08:48 -07001301 mTempTouchState.reset();
1302 mTempTouchState.down = down;
1303 mTempTouchState.deviceId = entry->deviceId;
1304 mTempTouchState.source = entry->source;
1305 isSplit = false;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001306 } else {
1307 mTempTouchState.copyFrom(mTouchState);
Jeff Browncc0c1592011-02-19 05:07:28 -08001308 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001309
Jeff Browna032cc02011-03-07 16:56:21 -08001310 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
Jeff Brown33bbfd22011-02-24 20:55:35 -08001311 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
Jeff Brownb88102f2010-09-08 11:49:43 -07001312
Jeff Browna032cc02011-03-07 16:56:21 -08001313 const MotionSample* sample = &entry->firstSample;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001314 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Jeff Browna032cc02011-03-07 16:56:21 -08001315 int32_t x = int32_t(sample->pointerCoords[pointerIndex].
Jeff Brownebbd5d12011-02-17 13:01:34 -08001316 getAxisValue(AMOTION_EVENT_AXIS_X));
Jeff Browna032cc02011-03-07 16:56:21 -08001317 int32_t y = int32_t(sample->pointerCoords[pointerIndex].
Jeff Brownebbd5d12011-02-17 13:01:34 -08001318 getAxisValue(AMOTION_EVENT_AXIS_Y));
Jeff Brown9302c872011-07-13 22:51:29 -07001319 sp<InputWindowHandle> newTouchedWindowHandle;
1320 sp<InputWindowHandle> topErrorWindowHandle;
Jeff Browna032cc02011-03-07 16:56:21 -08001321 bool isTouchModal = false;
Jeff Brownb88102f2010-09-08 11:49:43 -07001322
1323 // Traverse windows from front to back to find touched window and outside targets.
Jeff Brown9302c872011-07-13 22:51:29 -07001324 size_t numWindows = mWindowHandles.size();
Jeff Brownb88102f2010-09-08 11:49:43 -07001325 for (size_t i = 0; i < numWindows; i++) {
Jeff Brown9302c872011-07-13 22:51:29 -07001326 sp<InputWindowHandle> windowHandle = mWindowHandles.itemAt(i);
Jeff Browncc4f7db2011-08-30 20:34:48 -07001327 const InputWindowInfo* windowInfo = windowHandle->getInfo();
1328 int32_t flags = windowInfo->layoutParamsFlags;
Jeff Brownb88102f2010-09-08 11:49:43 -07001329
Jeff Browncc4f7db2011-08-30 20:34:48 -07001330 if (flags & InputWindowInfo::FLAG_SYSTEM_ERROR) {
Jeff Brown9302c872011-07-13 22:51:29 -07001331 if (topErrorWindowHandle == NULL) {
1332 topErrorWindowHandle = windowHandle;
Jeff Brownb88102f2010-09-08 11:49:43 -07001333 }
1334 }
1335
Jeff Browncc4f7db2011-08-30 20:34:48 -07001336 if (windowInfo->visible) {
1337 if (! (flags & InputWindowInfo::FLAG_NOT_TOUCHABLE)) {
1338 isTouchModal = (flags & (InputWindowInfo::FLAG_NOT_FOCUSABLE
1339 | InputWindowInfo::FLAG_NOT_TOUCH_MODAL)) == 0;
1340 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
Jeff Brown9302c872011-07-13 22:51:29 -07001341 if (! screenWasOff
Jeff Browncc4f7db2011-08-30 20:34:48 -07001342 || (flags & InputWindowInfo::FLAG_TOUCHABLE_WHEN_WAKING)) {
Jeff Brown9302c872011-07-13 22:51:29 -07001343 newTouchedWindowHandle = windowHandle;
Jeff Brownb88102f2010-09-08 11:49:43 -07001344 }
1345 break; // found touched window, exit window loop
1346 }
1347 }
1348
Jeff Brown01ce2e92010-09-26 22:20:12 -07001349 if (maskedAction == AMOTION_EVENT_ACTION_DOWN
Jeff Browncc4f7db2011-08-30 20:34:48 -07001350 && (flags & InputWindowInfo::FLAG_WATCH_OUTSIDE_TOUCH)) {
Jeff Browna032cc02011-03-07 16:56:21 -08001351 int32_t outsideTargetFlags = InputTarget::FLAG_DISPATCH_AS_OUTSIDE;
Jeff Brown9302c872011-07-13 22:51:29 -07001352 if (isWindowObscuredAtPointLocked(windowHandle, x, y)) {
Jeff Brown19dfc832010-10-05 12:26:23 -07001353 outsideTargetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1354 }
1355
Jeff Brown9302c872011-07-13 22:51:29 -07001356 mTempTouchState.addOrUpdateWindow(
1357 windowHandle, outsideTargetFlags, BitSet32(0));
Jeff Brownb88102f2010-09-08 11:49:43 -07001358 }
1359 }
1360 }
1361
1362 // If there is an error window but it is not taking focus (typically because
1363 // it is invisible) then wait for it. Any other focused window may in
1364 // fact be in ANR state.
Jeff Brown9302c872011-07-13 22:51:29 -07001365 if (topErrorWindowHandle != NULL && newTouchedWindowHandle != topErrorWindowHandle) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001366#if DEBUG_FOCUS
1367 LOGD("Waiting because system error window is pending.");
1368#endif
1369 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
1370 NULL, NULL, nextWakeupTime);
1371 injectionPermission = INJECTION_PERMISSION_UNKNOWN;
1372 goto Unresponsive;
1373 }
1374
Jeff Brown01ce2e92010-09-26 22:20:12 -07001375 // Figure out whether splitting will be allowed for this window.
Jeff Browncc4f7db2011-08-30 20:34:48 -07001376 if (newTouchedWindowHandle != NULL
1377 && newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001378 // New window supports splitting.
1379 isSplit = true;
1380 } else if (isSplit) {
1381 // New window does not support splitting but we have already split events.
1382 // Assign the pointer to the first foreground window we find.
1383 // (May be NULL which is why we put this code block before the next check.)
Jeff Brown9302c872011-07-13 22:51:29 -07001384 newTouchedWindowHandle = mTempTouchState.getFirstForegroundWindowHandle();
Jeff Brown01ce2e92010-09-26 22:20:12 -07001385 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001386
Jeff Brownb88102f2010-09-08 11:49:43 -07001387 // If we did not find a touched window then fail.
Jeff Brown9302c872011-07-13 22:51:29 -07001388 if (newTouchedWindowHandle == NULL) {
1389 if (mFocusedApplicationHandle != NULL) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001390#if DEBUG_FOCUS
1391 LOGD("Waiting because there is no touched window but there is a "
Jeff Brown519e0242010-09-15 15:18:56 -07001392 "focused application that may eventually add a new window: %s.",
Jeff Brown9302c872011-07-13 22:51:29 -07001393 getApplicationWindowLabelLocked(mFocusedApplicationHandle, NULL).string());
Jeff Brownb88102f2010-09-08 11:49:43 -07001394#endif
1395 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brown9302c872011-07-13 22:51:29 -07001396 mFocusedApplicationHandle, NULL, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -07001397 goto Unresponsive;
1398 }
1399
1400 LOGI("Dropping event because there is no touched window or focused application.");
1401 injectionResult = INPUT_EVENT_INJECTION_FAILED;
Jeff Brownb88102f2010-09-08 11:49:43 -07001402 goto Failed;
1403 }
1404
Jeff Brown19dfc832010-10-05 12:26:23 -07001405 // Set target flags.
Jeff Browna032cc02011-03-07 16:56:21 -08001406 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
Jeff Brown19dfc832010-10-05 12:26:23 -07001407 if (isSplit) {
1408 targetFlags |= InputTarget::FLAG_SPLIT;
1409 }
Jeff Brown9302c872011-07-13 22:51:29 -07001410 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
Jeff Brown19dfc832010-10-05 12:26:23 -07001411 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1412 }
1413
Jeff Browna032cc02011-03-07 16:56:21 -08001414 // Update hover state.
1415 if (isHoverAction) {
Jeff Brown9302c872011-07-13 22:51:29 -07001416 newHoverWindowHandle = newTouchedWindowHandle;
Jeff Browna032cc02011-03-07 16:56:21 -08001417
1418 // Ensure all subsequent motion samples are also within the touched window.
1419 // Set *outSplitBatchAfterSample to the sample before the first one that is not
1420 // within the touched window.
1421 if (!isTouchModal) {
1422 while (sample->next) {
Jeff Browncc4f7db2011-08-30 20:34:48 -07001423 if (!newHoverWindowHandle->getInfo()->touchableRegionContainsPoint(
Jeff Browna032cc02011-03-07 16:56:21 -08001424 sample->next->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X),
1425 sample->next->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y))) {
1426 *outSplitBatchAfterSample = sample;
1427 break;
1428 }
1429 sample = sample->next;
1430 }
1431 }
1432 } else if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
Jeff Brown9302c872011-07-13 22:51:29 -07001433 newHoverWindowHandle = mLastHoverWindowHandle;
Jeff Browna032cc02011-03-07 16:56:21 -08001434 }
1435
Jeff Brown01ce2e92010-09-26 22:20:12 -07001436 // Update the temporary touch state.
1437 BitSet32 pointerIds;
1438 if (isSplit) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07001439 uint32_t pointerId = entry->pointerProperties[pointerIndex].id;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001440 pointerIds.markBit(pointerId);
Jeff Brownb88102f2010-09-08 11:49:43 -07001441 }
Jeff Brown9302c872011-07-13 22:51:29 -07001442 mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Jeff Brownb88102f2010-09-08 11:49:43 -07001443 } else {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001444 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
Jeff Brownb88102f2010-09-08 11:49:43 -07001445
1446 // If the pointer is not currently down, then ignore the event.
Jeff Brown01ce2e92010-09-26 22:20:12 -07001447 if (! mTempTouchState.down) {
Jeff Browna2cc28d2011-03-25 11:58:46 -07001448#if DEBUG_FOCUS
Jeff Brown76860e32010-10-25 17:37:46 -07001449 LOGD("Dropping event because the pointer is not down or we previously "
1450 "dropped the pointer down event.");
1451#endif
Jeff Brownb88102f2010-09-08 11:49:43 -07001452 injectionResult = INPUT_EVENT_INJECTION_FAILED;
Jeff Brownb88102f2010-09-08 11:49:43 -07001453 goto Failed;
1454 }
Jeff Brown98db5fa2011-06-08 15:37:10 -07001455
1456 // Check whether touches should slip outside of the current foreground window.
1457 if (maskedAction == AMOTION_EVENT_ACTION_MOVE
1458 && entry->pointerCount == 1
1459 && mTempTouchState.isSlippery()) {
1460 const MotionSample* sample = &entry->firstSample;
1461 int32_t x = int32_t(sample->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
1462 int32_t y = int32_t(sample->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
1463
Jeff Brown9302c872011-07-13 22:51:29 -07001464 sp<InputWindowHandle> oldTouchedWindowHandle =
1465 mTempTouchState.getFirstForegroundWindowHandle();
1466 sp<InputWindowHandle> newTouchedWindowHandle = findTouchedWindowAtLocked(x, y);
1467 if (oldTouchedWindowHandle != newTouchedWindowHandle
1468 && newTouchedWindowHandle != NULL) {
Jeff Brown98db5fa2011-06-08 15:37:10 -07001469#if DEBUG_FOCUS
1470 LOGD("Touch is slipping out of window %s into window %s.",
Jeff Browncc4f7db2011-08-30 20:34:48 -07001471 oldTouchedWindowHandle->getName().string(),
1472 newTouchedWindowHandle->getName().string());
Jeff Brown98db5fa2011-06-08 15:37:10 -07001473#endif
1474 // Make a slippery exit from the old window.
Jeff Brown9302c872011-07-13 22:51:29 -07001475 mTempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
Jeff Brown98db5fa2011-06-08 15:37:10 -07001476 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT, BitSet32(0));
1477
1478 // Make a slippery entrance into the new window.
Jeff Browncc4f7db2011-08-30 20:34:48 -07001479 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Jeff Brown98db5fa2011-06-08 15:37:10 -07001480 isSplit = true;
1481 }
1482
1483 int32_t targetFlags = InputTarget::FLAG_FOREGROUND
1484 | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
1485 if (isSplit) {
1486 targetFlags |= InputTarget::FLAG_SPLIT;
1487 }
Jeff Brown9302c872011-07-13 22:51:29 -07001488 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
Jeff Brown98db5fa2011-06-08 15:37:10 -07001489 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1490 }
1491
1492 BitSet32 pointerIds;
1493 if (isSplit) {
1494 pointerIds.markBit(entry->pointerProperties[0].id);
1495 }
Jeff Brown9302c872011-07-13 22:51:29 -07001496 mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Jeff Brown98db5fa2011-06-08 15:37:10 -07001497
1498 // Split the batch here so we send exactly one sample.
1499 *outSplitBatchAfterSample = &entry->firstSample;
1500 }
1501 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001502 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001503
Jeff Brown9302c872011-07-13 22:51:29 -07001504 if (newHoverWindowHandle != mLastHoverWindowHandle) {
Jeff Browna032cc02011-03-07 16:56:21 -08001505 // Split the batch here so we send exactly one sample as part of ENTER or EXIT.
1506 *outSplitBatchAfterSample = &entry->firstSample;
1507
1508 // Let the previous window know that the hover sequence is over.
Jeff Brown9302c872011-07-13 22:51:29 -07001509 if (mLastHoverWindowHandle != NULL) {
Jeff Browna032cc02011-03-07 16:56:21 -08001510#if DEBUG_HOVER
Jeff Browncc4f7db2011-08-30 20:34:48 -07001511 LOGD("Sending hover exit event to window %s.",
1512 mLastHoverWindowHandle->getName().string());
Jeff Browna032cc02011-03-07 16:56:21 -08001513#endif
Jeff Brown9302c872011-07-13 22:51:29 -07001514 mTempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
Jeff Browna032cc02011-03-07 16:56:21 -08001515 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
1516 }
1517
1518 // Let the new window know that the hover sequence is starting.
Jeff Brown9302c872011-07-13 22:51:29 -07001519 if (newHoverWindowHandle != NULL) {
Jeff Browna032cc02011-03-07 16:56:21 -08001520#if DEBUG_HOVER
Jeff Browncc4f7db2011-08-30 20:34:48 -07001521 LOGD("Sending hover enter event to window %s.",
1522 newHoverWindowHandle->getName().string());
Jeff Browna032cc02011-03-07 16:56:21 -08001523#endif
Jeff Brown9302c872011-07-13 22:51:29 -07001524 mTempTouchState.addOrUpdateWindow(newHoverWindowHandle,
Jeff Browna032cc02011-03-07 16:56:21 -08001525 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER, BitSet32(0));
1526 }
1527 }
1528
Jeff Brown01ce2e92010-09-26 22:20:12 -07001529 // Check permission to inject into all touched foreground windows and ensure there
1530 // is at least one touched foreground window.
1531 {
1532 bool haveForegroundWindow = false;
1533 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1534 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1535 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1536 haveForegroundWindow = true;
Jeff Brown9302c872011-07-13 22:51:29 -07001537 if (! checkInjectionPermission(touchedWindow.windowHandle,
1538 entry->injectionState)) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001539 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1540 injectionPermission = INJECTION_PERMISSION_DENIED;
1541 goto Failed;
1542 }
1543 }
1544 }
1545 if (! haveForegroundWindow) {
Jeff Browna2cc28d2011-03-25 11:58:46 -07001546#if DEBUG_FOCUS
Jeff Brown01ce2e92010-09-26 22:20:12 -07001547 LOGD("Dropping event because there is no touched foreground window to receive it.");
Jeff Brownb88102f2010-09-08 11:49:43 -07001548#endif
1549 injectionResult = INPUT_EVENT_INJECTION_FAILED;
Jeff Brownb88102f2010-09-08 11:49:43 -07001550 goto Failed;
1551 }
1552
Jeff Brown01ce2e92010-09-26 22:20:12 -07001553 // Permission granted to injection into all touched foreground windows.
1554 injectionPermission = INJECTION_PERMISSION_GRANTED;
1555 }
Jeff Brown519e0242010-09-15 15:18:56 -07001556
Kenny Root7a9db182011-06-02 15:16:05 -07001557 // Check whether windows listening for outside touches are owned by the same UID. If it is
1558 // set the policy flag that we will not reveal coordinate information to this window.
1559 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
Jeff Brown9302c872011-07-13 22:51:29 -07001560 sp<InputWindowHandle> foregroundWindowHandle =
1561 mTempTouchState.getFirstForegroundWindowHandle();
Jeff Browncc4f7db2011-08-30 20:34:48 -07001562 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Kenny Root7a9db182011-06-02 15:16:05 -07001563 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1564 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1565 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
Jeff Brown9302c872011-07-13 22:51:29 -07001566 sp<InputWindowHandle> inputWindowHandle = touchedWindow.windowHandle;
Jeff Browncc4f7db2011-08-30 20:34:48 -07001567 if (inputWindowHandle->getInfo()->ownerUid != foregroundWindowUid) {
Jeff Brown9302c872011-07-13 22:51:29 -07001568 mTempTouchState.addOrUpdateWindow(inputWindowHandle,
Kenny Root7a9db182011-06-02 15:16:05 -07001569 InputTarget::FLAG_ZERO_COORDS, BitSet32(0));
1570 }
1571 }
1572 }
1573 }
1574
Jeff Brown01ce2e92010-09-26 22:20:12 -07001575 // Ensure all touched foreground windows are ready for new input.
1576 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1577 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1578 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1579 // If the touched window is paused then keep waiting.
Jeff Browncc4f7db2011-08-30 20:34:48 -07001580 if (touchedWindow.windowHandle->getInfo()->paused) {
Jeff Browna2cc28d2011-03-25 11:58:46 -07001581#if DEBUG_FOCUS
Jeff Brown01ce2e92010-09-26 22:20:12 -07001582 LOGD("Waiting because touched window is paused.");
Jeff Brown519e0242010-09-15 15:18:56 -07001583#endif
Jeff Brown01ce2e92010-09-26 22:20:12 -07001584 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brown9302c872011-07-13 22:51:29 -07001585 NULL, touchedWindow.windowHandle, nextWakeupTime);
Jeff Brown01ce2e92010-09-26 22:20:12 -07001586 goto Unresponsive;
1587 }
1588
1589 // If the touched window is still working on previous events then keep waiting.
Jeff Brown9302c872011-07-13 22:51:29 -07001590 if (! isWindowFinishedWithPreviousInputLocked(touchedWindow.windowHandle)) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001591#if DEBUG_FOCUS
1592 LOGD("Waiting because touched window still processing previous input.");
1593#endif
1594 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brown9302c872011-07-13 22:51:29 -07001595 NULL, touchedWindow.windowHandle, nextWakeupTime);
Jeff Brown01ce2e92010-09-26 22:20:12 -07001596 goto Unresponsive;
1597 }
1598 }
1599 }
1600
1601 // If this is the first pointer going down and the touched window has a wallpaper
1602 // then also add the touched wallpaper windows so they are locked in for the duration
1603 // of the touch gesture.
Jeff Brown33bbfd22011-02-24 20:55:35 -08001604 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
1605 // engine only supports touch events. We would need to add a mechanism similar
1606 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
1607 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
Jeff Brown9302c872011-07-13 22:51:29 -07001608 sp<InputWindowHandle> foregroundWindowHandle =
1609 mTempTouchState.getFirstForegroundWindowHandle();
Jeff Browncc4f7db2011-08-30 20:34:48 -07001610 if (foregroundWindowHandle->getInfo()->hasWallpaper) {
Jeff Brown9302c872011-07-13 22:51:29 -07001611 for (size_t i = 0; i < mWindowHandles.size(); i++) {
1612 sp<InputWindowHandle> windowHandle = mWindowHandles.itemAt(i);
Jeff Browncc4f7db2011-08-30 20:34:48 -07001613 if (windowHandle->getInfo()->layoutParamsType
1614 == InputWindowInfo::TYPE_WALLPAPER) {
Jeff Brown9302c872011-07-13 22:51:29 -07001615 mTempTouchState.addOrUpdateWindow(windowHandle,
Jeff Browna032cc02011-03-07 16:56:21 -08001616 InputTarget::FLAG_WINDOW_IS_OBSCURED
1617 | InputTarget::FLAG_DISPATCH_AS_IS,
1618 BitSet32(0));
Jeff Brown01ce2e92010-09-26 22:20:12 -07001619 }
1620 }
1621 }
1622 }
1623
Jeff Brownb88102f2010-09-08 11:49:43 -07001624 // Success! Output targets.
1625 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
Jeff Brownb88102f2010-09-08 11:49:43 -07001626
Jeff Brown01ce2e92010-09-26 22:20:12 -07001627 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1628 const TouchedWindow& touchedWindow = mTempTouchState.windows.itemAt(i);
Jeff Brown9302c872011-07-13 22:51:29 -07001629 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Jeff Brown01ce2e92010-09-26 22:20:12 -07001630 touchedWindow.pointerIds);
Jeff Brownb88102f2010-09-08 11:49:43 -07001631 }
1632
Jeff Browna032cc02011-03-07 16:56:21 -08001633 // Drop the outside or hover touch windows since we will not care about them
1634 // in the next iteration.
1635 mTempTouchState.filterNonAsIsTouchWindows();
Jeff Brown01ce2e92010-09-26 22:20:12 -07001636
Jeff Brownb88102f2010-09-08 11:49:43 -07001637Failed:
1638 // Check injection permission once and for all.
1639 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001640 if (checkInjectionPermission(NULL, entry->injectionState)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001641 injectionPermission = INJECTION_PERMISSION_GRANTED;
1642 } else {
1643 injectionPermission = INJECTION_PERMISSION_DENIED;
1644 }
1645 }
1646
1647 // Update final pieces of touch state if the injector had permission.
1648 if (injectionPermission == INJECTION_PERMISSION_GRANTED) {
Jeff Brown95712852011-01-04 19:41:59 -08001649 if (!wrongDevice) {
Jeff Brown81346812011-06-28 20:08:48 -07001650 if (switchedDevice) {
1651#if DEBUG_FOCUS
1652 LOGD("Conflicting pointer actions: Switched to a different device.");
1653#endif
1654 *outConflictingPointerActions = true;
1655 }
1656
1657 if (isHoverAction) {
1658 // Started hovering, therefore no longer down.
1659 if (mTouchState.down) {
1660#if DEBUG_FOCUS
1661 LOGD("Conflicting pointer actions: Hover received while pointer was down.");
1662#endif
1663 *outConflictingPointerActions = true;
1664 }
1665 mTouchState.reset();
1666 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER
1667 || maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
1668 mTouchState.deviceId = entry->deviceId;
1669 mTouchState.source = entry->source;
1670 }
1671 } else if (maskedAction == AMOTION_EVENT_ACTION_UP
1672 || maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Jeff Brown95712852011-01-04 19:41:59 -08001673 // All pointers up or canceled.
Jeff Brown33bbfd22011-02-24 20:55:35 -08001674 mTouchState.reset();
Jeff Brown95712852011-01-04 19:41:59 -08001675 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1676 // First pointer went down.
1677 if (mTouchState.down) {
Jeff Brownb6997262010-10-08 22:31:17 -07001678#if DEBUG_FOCUS
Jeff Brown81346812011-06-28 20:08:48 -07001679 LOGD("Conflicting pointer actions: Down received while already down.");
Jeff Brownb6997262010-10-08 22:31:17 -07001680#endif
Jeff Brown81346812011-06-28 20:08:48 -07001681 *outConflictingPointerActions = true;
Jeff Brown95712852011-01-04 19:41:59 -08001682 }
Jeff Brown33bbfd22011-02-24 20:55:35 -08001683 mTouchState.copyFrom(mTempTouchState);
Jeff Brown95712852011-01-04 19:41:59 -08001684 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
1685 // One pointer went up.
1686 if (isSplit) {
1687 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07001688 uint32_t pointerId = entry->pointerProperties[pointerIndex].id;
Jeff Brownb88102f2010-09-08 11:49:43 -07001689
Jeff Brown95712852011-01-04 19:41:59 -08001690 for (size_t i = 0; i < mTempTouchState.windows.size(); ) {
1691 TouchedWindow& touchedWindow = mTempTouchState.windows.editItemAt(i);
1692 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
1693 touchedWindow.pointerIds.clearBit(pointerId);
1694 if (touchedWindow.pointerIds.isEmpty()) {
1695 mTempTouchState.windows.removeAt(i);
1696 continue;
1697 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001698 }
Jeff Brown95712852011-01-04 19:41:59 -08001699 i += 1;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001700 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001701 }
Jeff Brown33bbfd22011-02-24 20:55:35 -08001702 mTouchState.copyFrom(mTempTouchState);
1703 } else if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
1704 // Discard temporary touch state since it was only valid for this action.
1705 } else {
1706 // Save changes to touch state as-is for all other actions.
1707 mTouchState.copyFrom(mTempTouchState);
Jeff Brownb88102f2010-09-08 11:49:43 -07001708 }
Jeff Browna032cc02011-03-07 16:56:21 -08001709
1710 // Update hover state.
Jeff Brown9302c872011-07-13 22:51:29 -07001711 mLastHoverWindowHandle = newHoverWindowHandle;
Jeff Brown95712852011-01-04 19:41:59 -08001712 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001713 } else {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001714#if DEBUG_FOCUS
1715 LOGD("Not updating touch focus because injection was denied.");
1716#endif
Jeff Brownb88102f2010-09-08 11:49:43 -07001717 }
1718
1719Unresponsive:
Jeff Brown120a4592010-10-27 18:43:51 -07001720 // Reset temporary touch state to ensure we release unnecessary references to input channels.
1721 mTempTouchState.reset();
1722
Jeff Brown519e0242010-09-15 15:18:56 -07001723 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
1724 updateDispatchStatisticsLocked(currentTime, entry,
1725 injectionResult, timeSpentWaitingForApplication);
Jeff Brownb88102f2010-09-08 11:49:43 -07001726#if DEBUG_FOCUS
Jeff Brown01ce2e92010-09-26 22:20:12 -07001727 LOGD("findTouchedWindow finished: injectionResult=%d, injectionPermission=%d, "
1728 "timeSpentWaitingForApplication=%0.1fms",
Jeff Brown519e0242010-09-15 15:18:56 -07001729 injectionResult, injectionPermission, timeSpentWaitingForApplication / 1000000.0);
Jeff Brownb88102f2010-09-08 11:49:43 -07001730#endif
1731 return injectionResult;
1732}
1733
Jeff Brown9302c872011-07-13 22:51:29 -07001734void InputDispatcher::addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
1735 int32_t targetFlags, BitSet32 pointerIds) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001736 mCurrentInputTargets.push();
1737
Jeff Browncc4f7db2011-08-30 20:34:48 -07001738 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Jeff Brownb88102f2010-09-08 11:49:43 -07001739 InputTarget& target = mCurrentInputTargets.editTop();
Jeff Browncc4f7db2011-08-30 20:34:48 -07001740 target.inputChannel = windowInfo->inputChannel;
Jeff Brownb88102f2010-09-08 11:49:43 -07001741 target.flags = targetFlags;
Jeff Browncc4f7db2011-08-30 20:34:48 -07001742 target.xOffset = - windowInfo->frameLeft;
1743 target.yOffset = - windowInfo->frameTop;
1744 target.scaleFactor = windowInfo->scaleFactor;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001745 target.pointerIds = pointerIds;
Jeff Brownb88102f2010-09-08 11:49:43 -07001746}
1747
1748void InputDispatcher::addMonitoringTargetsLocked() {
1749 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
1750 mCurrentInputTargets.push();
1751
1752 InputTarget& target = mCurrentInputTargets.editTop();
1753 target.inputChannel = mMonitoringChannels[i];
Jeff Brownb6110c22011-04-01 16:15:13 -07001754 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
Jeff Brownb88102f2010-09-08 11:49:43 -07001755 target.xOffset = 0;
1756 target.yOffset = 0;
Jeff Brownb6110c22011-04-01 16:15:13 -07001757 target.pointerIds.clear();
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001758 target.scaleFactor = 1.0f;
Jeff Brownb88102f2010-09-08 11:49:43 -07001759 }
1760}
1761
Jeff Brown9302c872011-07-13 22:51:29 -07001762bool InputDispatcher::checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
Jeff Brown01ce2e92010-09-26 22:20:12 -07001763 const InjectionState* injectionState) {
1764 if (injectionState
Jeff Browncc4f7db2011-08-30 20:34:48 -07001765 && (windowHandle == NULL
1766 || windowHandle->getInfo()->ownerUid != injectionState->injectorUid)
Jeff Brownb6997262010-10-08 22:31:17 -07001767 && !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Jeff Brown9302c872011-07-13 22:51:29 -07001768 if (windowHandle != NULL) {
1769 LOGW("Permission denied: injecting event from pid %d uid %d to window %s "
1770 "owned by uid %d",
Jeff Brownb6997262010-10-08 22:31:17 -07001771 injectionState->injectorPid, injectionState->injectorUid,
Jeff Browncc4f7db2011-08-30 20:34:48 -07001772 windowHandle->getName().string(),
1773 windowHandle->getInfo()->ownerUid);
Jeff Brownb6997262010-10-08 22:31:17 -07001774 } else {
1775 LOGW("Permission denied: injecting event from pid %d uid %d",
1776 injectionState->injectorPid, injectionState->injectorUid);
Jeff Brownb88102f2010-09-08 11:49:43 -07001777 }
Jeff Brownb6997262010-10-08 22:31:17 -07001778 return false;
Jeff Brownb88102f2010-09-08 11:49:43 -07001779 }
1780 return true;
1781}
1782
Jeff Brown19dfc832010-10-05 12:26:23 -07001783bool InputDispatcher::isWindowObscuredAtPointLocked(
Jeff Brown9302c872011-07-13 22:51:29 -07001784 const sp<InputWindowHandle>& windowHandle, int32_t x, int32_t y) const {
1785 size_t numWindows = mWindowHandles.size();
Jeff Brownb88102f2010-09-08 11:49:43 -07001786 for (size_t i = 0; i < numWindows; i++) {
Jeff Brown9302c872011-07-13 22:51:29 -07001787 sp<InputWindowHandle> otherHandle = mWindowHandles.itemAt(i);
1788 if (otherHandle == windowHandle) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001789 break;
1790 }
Jeff Browncc4f7db2011-08-30 20:34:48 -07001791
1792 const InputWindowInfo* otherInfo = otherHandle->getInfo();
1793 if (otherInfo->visible && ! otherInfo->isTrustedOverlay()
1794 && otherInfo->frameContainsPoint(x, y)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001795 return true;
1796 }
1797 }
1798 return false;
1799}
1800
Jeff Brown9302c872011-07-13 22:51:29 -07001801bool InputDispatcher::isWindowFinishedWithPreviousInputLocked(
1802 const sp<InputWindowHandle>& windowHandle) {
Jeff Browncc4f7db2011-08-30 20:34:48 -07001803 ssize_t connectionIndex = getConnectionIndexLocked(windowHandle->getInputChannel());
Jeff Brown519e0242010-09-15 15:18:56 -07001804 if (connectionIndex >= 0) {
1805 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
1806 return connection->outboundQueue.isEmpty();
1807 } else {
1808 return true;
1809 }
1810}
1811
Jeff Brown9302c872011-07-13 22:51:29 -07001812String8 InputDispatcher::getApplicationWindowLabelLocked(
1813 const sp<InputApplicationHandle>& applicationHandle,
1814 const sp<InputWindowHandle>& windowHandle) {
1815 if (applicationHandle != NULL) {
1816 if (windowHandle != NULL) {
Jeff Browncc4f7db2011-08-30 20:34:48 -07001817 String8 label(applicationHandle->getName());
Jeff Brown519e0242010-09-15 15:18:56 -07001818 label.append(" - ");
Jeff Browncc4f7db2011-08-30 20:34:48 -07001819 label.append(windowHandle->getName());
Jeff Brown519e0242010-09-15 15:18:56 -07001820 return label;
1821 } else {
Jeff Browncc4f7db2011-08-30 20:34:48 -07001822 return applicationHandle->getName();
Jeff Brown519e0242010-09-15 15:18:56 -07001823 }
Jeff Brown9302c872011-07-13 22:51:29 -07001824 } else if (windowHandle != NULL) {
Jeff Browncc4f7db2011-08-30 20:34:48 -07001825 return windowHandle->getName();
Jeff Brown519e0242010-09-15 15:18:56 -07001826 } else {
1827 return String8("<unknown application or window>");
1828 }
1829}
1830
Jeff Browne2fe69e2010-10-18 13:21:23 -07001831void InputDispatcher::pokeUserActivityLocked(const EventEntry* eventEntry) {
Jeff Brown56194eb2011-03-02 19:23:13 -08001832 int32_t eventType = POWER_MANAGER_OTHER_EVENT;
Jeff Brown4d396052010-10-29 21:50:21 -07001833 switch (eventEntry->type) {
1834 case EventEntry::TYPE_MOTION: {
Jeff Browne2fe69e2010-10-18 13:21:23 -07001835 const MotionEntry* motionEntry = static_cast<const MotionEntry*>(eventEntry);
Jeff Brown4d396052010-10-29 21:50:21 -07001836 if (motionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
1837 return;
1838 }
1839
Jeff Brown56194eb2011-03-02 19:23:13 -08001840 if (MotionEvent::isTouchEvent(motionEntry->source, motionEntry->action)) {
Joe Onorato1a542c72010-11-08 09:48:20 -08001841 eventType = POWER_MANAGER_TOUCH_EVENT;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001842 }
Jeff Brown4d396052010-10-29 21:50:21 -07001843 break;
1844 }
1845 case EventEntry::TYPE_KEY: {
1846 const KeyEntry* keyEntry = static_cast<const KeyEntry*>(eventEntry);
1847 if (keyEntry->flags & AKEY_EVENT_FLAG_CANCELED) {
1848 return;
1849 }
Jeff Brown56194eb2011-03-02 19:23:13 -08001850 eventType = POWER_MANAGER_BUTTON_EVENT;
Jeff Brown4d396052010-10-29 21:50:21 -07001851 break;
1852 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001853 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001854
Jeff Brownb88102f2010-09-08 11:49:43 -07001855 CommandEntry* commandEntry = postCommandLocked(
1856 & InputDispatcher::doPokeUserActivityLockedInterruptible);
Jeff Browne2fe69e2010-10-18 13:21:23 -07001857 commandEntry->eventTime = eventEntry->eventTime;
Jeff Brownb88102f2010-09-08 11:49:43 -07001858 commandEntry->userActivityEventType = eventType;
1859}
1860
Jeff Brown7fbdc842010-06-17 20:52:56 -07001861void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
1862 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget,
Jeff Brown46b9ac02010-04-22 18:58:52 -07001863 bool resumeWithAppendedMotionSample) {
1864#if DEBUG_DISPATCH_CYCLE
Jeff Brown9cc695c2011-08-23 18:35:04 -07001865 LOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
1866 "xOffset=%f, yOffset=%f, scaleFactor=%f, "
Jeff Brown83c09682010-12-23 17:50:18 -08001867 "pointerIds=0x%x, "
Jeff Brown01ce2e92010-09-26 22:20:12 -07001868 "resumeWithAppendedMotionSample=%s",
Jeff Brown519e0242010-09-15 15:18:56 -07001869 connection->getInputChannelName(), inputTarget->flags,
Jeff Brown46b9ac02010-04-22 18:58:52 -07001870 inputTarget->xOffset, inputTarget->yOffset,
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001871 inputTarget->scaleFactor, inputTarget->pointerIds.value,
Jeff Brownb88102f2010-09-08 11:49:43 -07001872 toString(resumeWithAppendedMotionSample));
Jeff Brown46b9ac02010-04-22 18:58:52 -07001873#endif
1874
Jeff Brown01ce2e92010-09-26 22:20:12 -07001875 // Make sure we are never called for streaming when splitting across multiple windows.
1876 bool isSplit = inputTarget->flags & InputTarget::FLAG_SPLIT;
Jeff Brownb6110c22011-04-01 16:15:13 -07001877 LOG_ASSERT(! (resumeWithAppendedMotionSample && isSplit));
Jeff Brown01ce2e92010-09-26 22:20:12 -07001878
Jeff Brown46b9ac02010-04-22 18:58:52 -07001879 // Skip this event if the connection status is not normal.
Jeff Brown519e0242010-09-15 15:18:56 -07001880 // We don't want to enqueue additional outbound events if the connection is broken.
Jeff Brown46b9ac02010-04-22 18:58:52 -07001881 if (connection->status != Connection::STATUS_NORMAL) {
Jeff Brownb6997262010-10-08 22:31:17 -07001882#if DEBUG_DISPATCH_CYCLE
1883 LOGD("channel '%s' ~ Dropping event because the channel status is %s",
Jeff Brownb88102f2010-09-08 11:49:43 -07001884 connection->getInputChannelName(), connection->getStatusLabel());
Jeff Brownb6997262010-10-08 22:31:17 -07001885#endif
Jeff Brown46b9ac02010-04-22 18:58:52 -07001886 return;
1887 }
1888
Jeff Brown01ce2e92010-09-26 22:20:12 -07001889 // Split a motion event if needed.
1890 if (isSplit) {
Jeff Brownb6110c22011-04-01 16:15:13 -07001891 LOG_ASSERT(eventEntry->type == EventEntry::TYPE_MOTION);
Jeff Brown01ce2e92010-09-26 22:20:12 -07001892
1893 MotionEntry* originalMotionEntry = static_cast<MotionEntry*>(eventEntry);
1894 if (inputTarget->pointerIds.count() != originalMotionEntry->pointerCount) {
1895 MotionEntry* splitMotionEntry = splitMotionEvent(
1896 originalMotionEntry, inputTarget->pointerIds);
Jeff Brown58a2da82011-01-25 16:02:22 -08001897 if (!splitMotionEntry) {
1898 return; // split event was dropped
1899 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001900#if DEBUG_FOCUS
1901 LOGD("channel '%s' ~ Split motion event.",
1902 connection->getInputChannelName());
1903 logOutboundMotionDetailsLocked(" ", splitMotionEntry);
1904#endif
1905 eventEntry = splitMotionEntry;
1906 }
1907 }
1908
Jeff Brown46b9ac02010-04-22 18:58:52 -07001909 // Resume the dispatch cycle with a freshly appended motion sample.
1910 // First we check that the last dispatch entry in the outbound queue is for the same
1911 // motion event to which we appended the motion sample. If we find such a dispatch
1912 // entry, and if it is currently in progress then we try to stream the new sample.
1913 bool wasEmpty = connection->outboundQueue.isEmpty();
1914
1915 if (! wasEmpty && resumeWithAppendedMotionSample) {
1916 DispatchEntry* motionEventDispatchEntry =
1917 connection->findQueuedDispatchEntryForEvent(eventEntry);
1918 if (motionEventDispatchEntry) {
1919 // If the dispatch entry is not in progress, then we must be busy dispatching an
1920 // earlier event. Not a problem, the motion event is on the outbound queue and will
1921 // be dispatched later.
1922 if (! motionEventDispatchEntry->inProgress) {
1923#if DEBUG_BATCHING
1924 LOGD("channel '%s' ~ Not streaming because the motion event has "
1925 "not yet been dispatched. "
1926 "(Waiting for earlier events to be consumed.)",
1927 connection->getInputChannelName());
1928#endif
1929 return;
1930 }
1931
1932 // If the dispatch entry is in progress but it already has a tail of pending
1933 // motion samples, then it must mean that the shared memory buffer filled up.
1934 // Not a problem, when this dispatch cycle is finished, we will eventually start
1935 // a new dispatch cycle to process the tail and that tail includes the newly
1936 // appended motion sample.
1937 if (motionEventDispatchEntry->tailMotionSample) {
1938#if DEBUG_BATCHING
1939 LOGD("channel '%s' ~ Not streaming because no new samples can "
1940 "be appended to the motion event in this dispatch cycle. "
1941 "(Waiting for next dispatch cycle to start.)",
1942 connection->getInputChannelName());
1943#endif
1944 return;
1945 }
1946
Jeff Brown81346812011-06-28 20:08:48 -07001947 // If the motion event was modified in flight, then we cannot stream the sample.
1948 if ((motionEventDispatchEntry->targetFlags & InputTarget::FLAG_DISPATCH_MASK)
1949 != InputTarget::FLAG_DISPATCH_AS_IS) {
1950#if DEBUG_BATCHING
1951 LOGD("channel '%s' ~ Not streaming because the motion event was not "
1952 "being dispatched as-is. "
1953 "(Waiting for next dispatch cycle to start.)",
1954 connection->getInputChannelName());
1955#endif
1956 return;
1957 }
1958
Jeff Brown46b9ac02010-04-22 18:58:52 -07001959 // The dispatch entry is in progress and is still potentially open for streaming.
1960 // Try to stream the new motion sample. This might fail if the consumer has already
1961 // consumed the motion event (or if the channel is broken).
Jeff Brown01ce2e92010-09-26 22:20:12 -07001962 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
1963 MotionSample* appendedMotionSample = motionEntry->lastSample;
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001964 status_t status;
1965 if (motionEventDispatchEntry->scaleFactor == 1.0f) {
1966 status = connection->inputPublisher.appendMotionSample(
1967 appendedMotionSample->eventTime, appendedMotionSample->pointerCoords);
1968 } else {
1969 PointerCoords scaledCoords[MAX_POINTERS];
1970 for (size_t i = 0; i < motionEntry->pointerCount; i++) {
1971 scaledCoords[i] = appendedMotionSample->pointerCoords[i];
1972 scaledCoords[i].scale(motionEventDispatchEntry->scaleFactor);
1973 }
1974 status = connection->inputPublisher.appendMotionSample(
1975 appendedMotionSample->eventTime, scaledCoords);
1976 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07001977 if (status == OK) {
1978#if DEBUG_BATCHING
1979 LOGD("channel '%s' ~ Successfully streamed new motion sample.",
1980 connection->getInputChannelName());
1981#endif
1982 return;
1983 }
1984
1985#if DEBUG_BATCHING
1986 if (status == NO_MEMORY) {
1987 LOGD("channel '%s' ~ Could not append motion sample to currently "
1988 "dispatched move event because the shared memory buffer is full. "
1989 "(Waiting for next dispatch cycle to start.)",
1990 connection->getInputChannelName());
1991 } else if (status == status_t(FAILED_TRANSACTION)) {
1992 LOGD("channel '%s' ~ Could not append motion sample to currently "
Jeff Brown349703e2010-06-22 01:27:15 -07001993 "dispatched move event because the event has already been consumed. "
Jeff Brown46b9ac02010-04-22 18:58:52 -07001994 "(Waiting for next dispatch cycle to start.)",
1995 connection->getInputChannelName());
1996 } else {
1997 LOGD("channel '%s' ~ Could not append motion sample to currently "
1998 "dispatched move event due to an error, status=%d. "
1999 "(Waiting for next dispatch cycle to start.)",
2000 connection->getInputChannelName(), status);
2001 }
2002#endif
2003 // Failed to stream. Start a new tail of pending motion samples to dispatch
2004 // in the next cycle.
2005 motionEventDispatchEntry->tailMotionSample = appendedMotionSample;
2006 return;
2007 }
2008 }
2009
Jeff Browna032cc02011-03-07 16:56:21 -08002010 // Enqueue dispatch entries for the requested modes.
2011 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
2012 resumeWithAppendedMotionSample, InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
2013 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
2014 resumeWithAppendedMotionSample, InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
2015 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
2016 resumeWithAppendedMotionSample, InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
2017 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
2018 resumeWithAppendedMotionSample, InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brown98db5fa2011-06-08 15:37:10 -07002019 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
2020 resumeWithAppendedMotionSample, InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
2021 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
2022 resumeWithAppendedMotionSample, InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Jeff Browna032cc02011-03-07 16:56:21 -08002023
2024 // If the outbound queue was previously empty, start the dispatch cycle going.
Jeff Brownb6110c22011-04-01 16:15:13 -07002025 if (wasEmpty && !connection->outboundQueue.isEmpty()) {
Jeff Browna032cc02011-03-07 16:56:21 -08002026 activateConnectionLocked(connection.get());
2027 startDispatchCycleLocked(currentTime, connection);
2028 }
2029}
2030
2031void InputDispatcher::enqueueDispatchEntryLocked(
2032 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget,
2033 bool resumeWithAppendedMotionSample, int32_t dispatchMode) {
2034 int32_t inputTargetFlags = inputTarget->flags;
2035 if (!(inputTargetFlags & dispatchMode)) {
2036 return;
2037 }
2038 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
2039
Jeff Brown46b9ac02010-04-22 18:58:52 -07002040 // This is a new event.
2041 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Jeff Brownac386072011-07-20 15:19:50 -07002042 DispatchEntry* dispatchEntry = new DispatchEntry(eventEntry, // increments ref
Dianne Hackbornaa9d84c2011-05-09 19:00:59 -07002043 inputTargetFlags, inputTarget->xOffset, inputTarget->yOffset,
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002044 inputTarget->scaleFactor);
Jeff Brown519e0242010-09-15 15:18:56 -07002045 if (dispatchEntry->hasForegroundTarget()) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002046 incrementPendingForegroundDispatchesLocked(eventEntry);
Jeff Brown6ec402b2010-07-28 15:48:59 -07002047 }
2048
Jeff Brown46b9ac02010-04-22 18:58:52 -07002049 // Handle the case where we could not stream a new motion sample because the consumer has
2050 // already consumed the motion event (otherwise the corresponding dispatch entry would
2051 // still be in the outbound queue for this connection). We set the head motion sample
2052 // to the list starting with the newly appended motion sample.
2053 if (resumeWithAppendedMotionSample) {
2054#if DEBUG_BATCHING
2055 LOGD("channel '%s' ~ Preparing a new dispatch cycle for additional motion samples "
2056 "that cannot be streamed because the motion event has already been consumed.",
2057 connection->getInputChannelName());
2058#endif
2059 MotionSample* appendedMotionSample = static_cast<MotionEntry*>(eventEntry)->lastSample;
2060 dispatchEntry->headMotionSample = appendedMotionSample;
2061 }
2062
Jeff Brown81346812011-06-28 20:08:48 -07002063 // Apply target flags and update the connection's input state.
2064 switch (eventEntry->type) {
2065 case EventEntry::TYPE_KEY: {
2066 KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
2067 dispatchEntry->resolvedAction = keyEntry->action;
2068 dispatchEntry->resolvedFlags = keyEntry->flags;
2069
2070 if (!connection->inputState.trackKey(keyEntry,
2071 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags)) {
2072#if DEBUG_DISPATCH_CYCLE
2073 LOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
2074 connection->getInputChannelName());
2075#endif
2076 return; // skip the inconsistent event
2077 }
2078 break;
2079 }
2080
2081 case EventEntry::TYPE_MOTION: {
2082 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
2083 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2084 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
2085 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
2086 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
2087 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
2088 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2089 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
2090 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
2091 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
2092 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
2093 } else {
2094 dispatchEntry->resolvedAction = motionEntry->action;
2095 }
2096 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE
2097 && !connection->inputState.isHovering(
2098 motionEntry->deviceId, motionEntry->source)) {
2099#if DEBUG_DISPATCH_CYCLE
2100 LOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter event",
2101 connection->getInputChannelName());
2102#endif
2103 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2104 }
2105
2106 dispatchEntry->resolvedFlags = motionEntry->flags;
2107 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
2108 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
2109 }
2110
2111 if (!connection->inputState.trackMotion(motionEntry,
2112 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags)) {
2113#if DEBUG_DISPATCH_CYCLE
2114 LOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion event",
2115 connection->getInputChannelName());
2116#endif
2117 return; // skip the inconsistent event
2118 }
2119 break;
2120 }
2121 }
2122
Jeff Brown46b9ac02010-04-22 18:58:52 -07002123 // Enqueue the dispatch entry.
2124 connection->outboundQueue.enqueueAtTail(dispatchEntry);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002125}
2126
Jeff Brown7fbdc842010-06-17 20:52:56 -07002127void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Jeff Brown519e0242010-09-15 15:18:56 -07002128 const sp<Connection>& connection) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002129#if DEBUG_DISPATCH_CYCLE
2130 LOGD("channel '%s' ~ startDispatchCycle",
2131 connection->getInputChannelName());
2132#endif
2133
Jeff Brownb6110c22011-04-01 16:15:13 -07002134 LOG_ASSERT(connection->status == Connection::STATUS_NORMAL);
2135 LOG_ASSERT(! connection->outboundQueue.isEmpty());
Jeff Brown46b9ac02010-04-22 18:58:52 -07002136
Jeff Brownac386072011-07-20 15:19:50 -07002137 DispatchEntry* dispatchEntry = connection->outboundQueue.head;
Jeff Brownb6110c22011-04-01 16:15:13 -07002138 LOG_ASSERT(! dispatchEntry->inProgress);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002139
Jeff Brownb88102f2010-09-08 11:49:43 -07002140 // Mark the dispatch entry as in progress.
2141 dispatchEntry->inProgress = true;
2142
Jeff Brown46b9ac02010-04-22 18:58:52 -07002143 // Publish the event.
2144 status_t status;
Jeff Browna032cc02011-03-07 16:56:21 -08002145 EventEntry* eventEntry = dispatchEntry->eventEntry;
Jeff Brown01ce2e92010-09-26 22:20:12 -07002146 switch (eventEntry->type) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002147 case EventEntry::TYPE_KEY: {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002148 KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002149
Jeff Brown46b9ac02010-04-22 18:58:52 -07002150 // Publish the key event.
Jeff Brown81346812011-06-28 20:08:48 -07002151 status = connection->inputPublisher.publishKeyEvent(
2152 keyEntry->deviceId, keyEntry->source,
2153 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags,
2154 keyEntry->keyCode, keyEntry->scanCode,
Jeff Brown46b9ac02010-04-22 18:58:52 -07002155 keyEntry->metaState, keyEntry->repeatCount, keyEntry->downTime,
2156 keyEntry->eventTime);
2157
2158 if (status) {
2159 LOGE("channel '%s' ~ Could not publish key event, "
2160 "status=%d", connection->getInputChannelName(), status);
Jeff Browncc4f7db2011-08-30 20:34:48 -07002161 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002162 return;
2163 }
2164 break;
2165 }
2166
2167 case EventEntry::TYPE_MOTION: {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002168 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002169
Jeff Brown46b9ac02010-04-22 18:58:52 -07002170 // If headMotionSample is non-NULL, then it points to the first new sample that we
2171 // were unable to dispatch during the previous cycle so we resume dispatching from
2172 // that point in the list of motion samples.
2173 // Otherwise, we just start from the first sample of the motion event.
2174 MotionSample* firstMotionSample = dispatchEntry->headMotionSample;
2175 if (! firstMotionSample) {
2176 firstMotionSample = & motionEntry->firstSample;
2177 }
2178
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002179 PointerCoords scaledCoords[MAX_POINTERS];
2180 const PointerCoords* usingCoords = firstMotionSample->pointerCoords;
2181
Jeff Brownd3616592010-07-16 17:21:06 -07002182 // Set the X and Y offset depending on the input source.
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002183 float xOffset, yOffset, scaleFactor;
Kenny Root7a9db182011-06-02 15:16:05 -07002184 if (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER
2185 && !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002186 scaleFactor = dispatchEntry->scaleFactor;
2187 xOffset = dispatchEntry->xOffset * scaleFactor;
2188 yOffset = dispatchEntry->yOffset * scaleFactor;
2189 if (scaleFactor != 1.0f) {
2190 for (size_t i = 0; i < motionEntry->pointerCount; i++) {
2191 scaledCoords[i] = firstMotionSample->pointerCoords[i];
2192 scaledCoords[i].scale(scaleFactor);
2193 }
2194 usingCoords = scaledCoords;
2195 }
Jeff Brownd3616592010-07-16 17:21:06 -07002196 } else {
2197 xOffset = 0.0f;
2198 yOffset = 0.0f;
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002199 scaleFactor = 1.0f;
Kenny Root7a9db182011-06-02 15:16:05 -07002200
2201 // We don't want the dispatch target to know.
2202 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
2203 for (size_t i = 0; i < motionEntry->pointerCount; i++) {
2204 scaledCoords[i].clear();
2205 }
2206 usingCoords = scaledCoords;
2207 }
Jeff Brownd3616592010-07-16 17:21:06 -07002208 }
2209
Jeff Brown46b9ac02010-04-22 18:58:52 -07002210 // Publish the motion event and the first motion sample.
Jeff Brown81346812011-06-28 20:08:48 -07002211 status = connection->inputPublisher.publishMotionEvent(
2212 motionEntry->deviceId, motionEntry->source,
2213 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags,
2214 motionEntry->edgeFlags, motionEntry->metaState, motionEntry->buttonState,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002215 xOffset, yOffset,
2216 motionEntry->xPrecision, motionEntry->yPrecision,
Jeff Brown46b9ac02010-04-22 18:58:52 -07002217 motionEntry->downTime, firstMotionSample->eventTime,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002218 motionEntry->pointerCount, motionEntry->pointerProperties,
2219 usingCoords);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002220
2221 if (status) {
2222 LOGE("channel '%s' ~ Could not publish motion event, "
2223 "status=%d", connection->getInputChannelName(), status);
Jeff Browncc4f7db2011-08-30 20:34:48 -07002224 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002225 return;
2226 }
2227
Jeff Brown81346812011-06-28 20:08:48 -07002228 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_MOVE
2229 || dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Jeff Browna032cc02011-03-07 16:56:21 -08002230 // Append additional motion samples.
2231 MotionSample* nextMotionSample = firstMotionSample->next;
2232 for (; nextMotionSample != NULL; nextMotionSample = nextMotionSample->next) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002233 if (usingCoords == scaledCoords) {
Kenny Root7a9db182011-06-02 15:16:05 -07002234 if (!(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
2235 for (size_t i = 0; i < motionEntry->pointerCount; i++) {
2236 scaledCoords[i] = nextMotionSample->pointerCoords[i];
2237 scaledCoords[i].scale(scaleFactor);
2238 }
Dianne Hackborn2ba3e802011-05-11 10:59:54 -07002239 }
2240 } else {
2241 usingCoords = nextMotionSample->pointerCoords;
Dianne Hackborne7d25b72011-05-09 21:19:26 -07002242 }
Jeff Browna032cc02011-03-07 16:56:21 -08002243 status = connection->inputPublisher.appendMotionSample(
Dianne Hackbornaa9d84c2011-05-09 19:00:59 -07002244 nextMotionSample->eventTime, usingCoords);
Jeff Browna032cc02011-03-07 16:56:21 -08002245 if (status == NO_MEMORY) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002246#if DEBUG_DISPATCH_CYCLE
2247 LOGD("channel '%s' ~ Shared memory buffer full. Some motion samples will "
2248 "be sent in the next dispatch cycle.",
2249 connection->getInputChannelName());
2250#endif
Jeff Browna032cc02011-03-07 16:56:21 -08002251 break;
2252 }
2253 if (status != OK) {
2254 LOGE("channel '%s' ~ Could not append motion sample "
2255 "for a reason other than out of memory, status=%d",
2256 connection->getInputChannelName(), status);
Jeff Browncc4f7db2011-08-30 20:34:48 -07002257 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
Jeff Browna032cc02011-03-07 16:56:21 -08002258 return;
2259 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002260 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002261
Jeff Browna032cc02011-03-07 16:56:21 -08002262 // Remember the next motion sample that we could not dispatch, in case we ran out
2263 // of space in the shared memory buffer.
2264 dispatchEntry->tailMotionSample = nextMotionSample;
2265 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002266 break;
2267 }
2268
2269 default: {
Jeff Brownb6110c22011-04-01 16:15:13 -07002270 LOG_ASSERT(false);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002271 }
2272 }
2273
2274 // Send the dispatch signal.
2275 status = connection->inputPublisher.sendDispatchSignal();
2276 if (status) {
2277 LOGE("channel '%s' ~ Could not send dispatch signal, status=%d",
2278 connection->getInputChannelName(), status);
Jeff Browncc4f7db2011-08-30 20:34:48 -07002279 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002280 return;
2281 }
2282
2283 // Record information about the newly started dispatch cycle.
Jeff Brown01ce2e92010-09-26 22:20:12 -07002284 connection->lastEventTime = eventEntry->eventTime;
Jeff Brown46b9ac02010-04-22 18:58:52 -07002285 connection->lastDispatchTime = currentTime;
2286
Jeff Brown46b9ac02010-04-22 18:58:52 -07002287 // Notify other system components.
2288 onDispatchCycleStartedLocked(currentTime, connection);
2289}
2290
Jeff Brown7fbdc842010-06-17 20:52:56 -07002291void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Jeff Brown3915bb82010-11-05 15:02:16 -07002292 const sp<Connection>& connection, bool handled) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002293#if DEBUG_DISPATCH_CYCLE
Jeff Brown9c3cda02010-06-15 01:31:58 -07002294 LOGD("channel '%s' ~ finishDispatchCycle - %01.1fms since event, "
Jeff Brown3915bb82010-11-05 15:02:16 -07002295 "%01.1fms since dispatch, handled=%s",
Jeff Brown46b9ac02010-04-22 18:58:52 -07002296 connection->getInputChannelName(),
2297 connection->getEventLatencyMillis(currentTime),
Jeff Brown3915bb82010-11-05 15:02:16 -07002298 connection->getDispatchLatencyMillis(currentTime),
2299 toString(handled));
Jeff Brown46b9ac02010-04-22 18:58:52 -07002300#endif
2301
Jeff Brown9c3cda02010-06-15 01:31:58 -07002302 if (connection->status == Connection::STATUS_BROKEN
2303 || connection->status == Connection::STATUS_ZOMBIE) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002304 return;
2305 }
2306
Jeff Brown46b9ac02010-04-22 18:58:52 -07002307 // Reset the publisher since the event has been consumed.
2308 // We do this now so that the publisher can release some of its internal resources
2309 // while waiting for the next dispatch cycle to begin.
2310 status_t status = connection->inputPublisher.reset();
2311 if (status) {
2312 LOGE("channel '%s' ~ Could not reset publisher, status=%d",
2313 connection->getInputChannelName(), status);
Jeff Browncc4f7db2011-08-30 20:34:48 -07002314 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002315 return;
2316 }
2317
Jeff Brown3915bb82010-11-05 15:02:16 -07002318 // Notify other system components and prepare to start the next dispatch cycle.
2319 onDispatchCycleFinishedLocked(currentTime, connection, handled);
Jeff Brownb88102f2010-09-08 11:49:43 -07002320}
2321
2322void InputDispatcher::startNextDispatchCycleLocked(nsecs_t currentTime,
2323 const sp<Connection>& connection) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002324 // Start the next dispatch cycle for this connection.
2325 while (! connection->outboundQueue.isEmpty()) {
Jeff Brownac386072011-07-20 15:19:50 -07002326 DispatchEntry* dispatchEntry = connection->outboundQueue.head;
Jeff Brown46b9ac02010-04-22 18:58:52 -07002327 if (dispatchEntry->inProgress) {
2328 // Finish or resume current event in progress.
2329 if (dispatchEntry->tailMotionSample) {
2330 // We have a tail of undispatched motion samples.
2331 // Reuse the same DispatchEntry and start a new cycle.
2332 dispatchEntry->inProgress = false;
2333 dispatchEntry->headMotionSample = dispatchEntry->tailMotionSample;
2334 dispatchEntry->tailMotionSample = NULL;
Jeff Brown519e0242010-09-15 15:18:56 -07002335 startDispatchCycleLocked(currentTime, connection);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002336 return;
2337 }
2338 // Finished.
2339 connection->outboundQueue.dequeueAtHead();
Jeff Brown519e0242010-09-15 15:18:56 -07002340 if (dispatchEntry->hasForegroundTarget()) {
2341 decrementPendingForegroundDispatchesLocked(dispatchEntry->eventEntry);
Jeff Brown6ec402b2010-07-28 15:48:59 -07002342 }
Jeff Brownac386072011-07-20 15:19:50 -07002343 delete dispatchEntry;
Jeff Brown46b9ac02010-04-22 18:58:52 -07002344 } else {
2345 // If the head is not in progress, then we must have already dequeued the in
Jeff Brown519e0242010-09-15 15:18:56 -07002346 // progress event, which means we actually aborted it.
Jeff Brown46b9ac02010-04-22 18:58:52 -07002347 // So just start the next event for this connection.
Jeff Brown519e0242010-09-15 15:18:56 -07002348 startDispatchCycleLocked(currentTime, connection);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002349 return;
2350 }
2351 }
2352
2353 // Outbound queue is empty, deactivate the connection.
Jeff Brown7fbdc842010-06-17 20:52:56 -07002354 deactivateConnectionLocked(connection.get());
Jeff Brown46b9ac02010-04-22 18:58:52 -07002355}
2356
Jeff Brownb6997262010-10-08 22:31:17 -07002357void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Jeff Browncc4f7db2011-08-30 20:34:48 -07002358 const sp<Connection>& connection, bool notify) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002359#if DEBUG_DISPATCH_CYCLE
Jeff Browncc4f7db2011-08-30 20:34:48 -07002360 LOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
2361 connection->getInputChannelName(), toString(notify));
Jeff Brown46b9ac02010-04-22 18:58:52 -07002362#endif
2363
Jeff Brownb88102f2010-09-08 11:49:43 -07002364 // Clear the outbound queue.
Jeff Brown519e0242010-09-15 15:18:56 -07002365 drainOutboundQueueLocked(connection.get());
Jeff Brown46b9ac02010-04-22 18:58:52 -07002366
Jeff Brownb6997262010-10-08 22:31:17 -07002367 // The connection appears to be unrecoverably broken.
Jeff Brown9c3cda02010-06-15 01:31:58 -07002368 // Ignore already broken or zombie connections.
Jeff Brownb6997262010-10-08 22:31:17 -07002369 if (connection->status == Connection::STATUS_NORMAL) {
2370 connection->status = Connection::STATUS_BROKEN;
Jeff Brown46b9ac02010-04-22 18:58:52 -07002371
Jeff Browncc4f7db2011-08-30 20:34:48 -07002372 if (notify) {
2373 // Notify other system components.
2374 onDispatchCycleBrokenLocked(currentTime, connection);
2375 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002376 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002377}
2378
Jeff Brown519e0242010-09-15 15:18:56 -07002379void InputDispatcher::drainOutboundQueueLocked(Connection* connection) {
2380 while (! connection->outboundQueue.isEmpty()) {
2381 DispatchEntry* dispatchEntry = connection->outboundQueue.dequeueAtHead();
2382 if (dispatchEntry->hasForegroundTarget()) {
2383 decrementPendingForegroundDispatchesLocked(dispatchEntry->eventEntry);
Jeff Brownb88102f2010-09-08 11:49:43 -07002384 }
Jeff Brownac386072011-07-20 15:19:50 -07002385 delete dispatchEntry;
Jeff Brownb88102f2010-09-08 11:49:43 -07002386 }
2387
Jeff Brown519e0242010-09-15 15:18:56 -07002388 deactivateConnectionLocked(connection);
Jeff Brownb88102f2010-09-08 11:49:43 -07002389}
2390
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002391int InputDispatcher::handleReceiveCallback(int receiveFd, int events, void* data) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002392 InputDispatcher* d = static_cast<InputDispatcher*>(data);
2393
2394 { // acquire lock
2395 AutoMutex _l(d->mLock);
2396
2397 ssize_t connectionIndex = d->mConnectionsByReceiveFd.indexOfKey(receiveFd);
2398 if (connectionIndex < 0) {
2399 LOGE("Received spurious receive callback for unknown input channel. "
2400 "fd=%d, events=0x%x", receiveFd, events);
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002401 return 0; // remove the callback
Jeff Brown46b9ac02010-04-22 18:58:52 -07002402 }
2403
Jeff Browncc4f7db2011-08-30 20:34:48 -07002404 bool notify;
Jeff Brown46b9ac02010-04-22 18:58:52 -07002405 sp<Connection> connection = d->mConnectionsByReceiveFd.valueAt(connectionIndex);
Jeff Browncc4f7db2011-08-30 20:34:48 -07002406 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
2407 if (!(events & ALOOPER_EVENT_INPUT)) {
2408 LOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
2409 "events=0x%x", connection->getInputChannelName(), events);
2410 return 1;
2411 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002412
Jeff Browncc4f7db2011-08-30 20:34:48 -07002413 bool handled = false;
2414 status_t status = connection->inputPublisher.receiveFinishedSignal(&handled);
2415 if (!status) {
2416 nsecs_t currentTime = now();
2417 d->finishDispatchCycleLocked(currentTime, connection, handled);
2418 d->runCommandsLockedInterruptible();
2419 return 1;
2420 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002421
Jeff Brown46b9ac02010-04-22 18:58:52 -07002422 LOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
2423 connection->getInputChannelName(), status);
Jeff Browncc4f7db2011-08-30 20:34:48 -07002424 notify = true;
2425 } else {
2426 // Monitor channels are never explicitly unregistered.
2427 // We do it automatically when the remote endpoint is closed so don't warn
2428 // about them.
2429 notify = !connection->monitor;
2430 if (notify) {
2431 LOGW("channel '%s' ~ Consumer closed input channel or an error occurred. "
2432 "events=0x%x", connection->getInputChannelName(), events);
2433 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002434 }
2435
Jeff Browncc4f7db2011-08-30 20:34:48 -07002436 // Unregister the channel.
2437 d->unregisterInputChannelLocked(connection->inputChannel, notify);
2438 return 0; // remove the callback
Jeff Brown46b9ac02010-04-22 18:58:52 -07002439 } // release lock
2440}
2441
Jeff Brownb6997262010-10-08 22:31:17 -07002442void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Jeff Brownda3d5a92011-03-29 15:11:34 -07002443 const CancelationOptions& options) {
Jeff Brownb6997262010-10-08 22:31:17 -07002444 for (size_t i = 0; i < mConnectionsByReceiveFd.size(); i++) {
2445 synthesizeCancelationEventsForConnectionLocked(
Jeff Brownda3d5a92011-03-29 15:11:34 -07002446 mConnectionsByReceiveFd.valueAt(i), options);
Jeff Brownb6997262010-10-08 22:31:17 -07002447 }
2448}
2449
2450void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Jeff Brownda3d5a92011-03-29 15:11:34 -07002451 const sp<InputChannel>& channel, const CancelationOptions& options) {
Jeff Brownb6997262010-10-08 22:31:17 -07002452 ssize_t index = getConnectionIndexLocked(channel);
2453 if (index >= 0) {
2454 synthesizeCancelationEventsForConnectionLocked(
Jeff Brownda3d5a92011-03-29 15:11:34 -07002455 mConnectionsByReceiveFd.valueAt(index), options);
Jeff Brownb6997262010-10-08 22:31:17 -07002456 }
2457}
2458
2459void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
Jeff Brownda3d5a92011-03-29 15:11:34 -07002460 const sp<Connection>& connection, const CancelationOptions& options) {
Jeff Brownb6997262010-10-08 22:31:17 -07002461 nsecs_t currentTime = now();
2462
2463 mTempCancelationEvents.clear();
Jeff Brownac386072011-07-20 15:19:50 -07002464 connection->inputState.synthesizeCancelationEvents(currentTime,
Jeff Brownb6997262010-10-08 22:31:17 -07002465 mTempCancelationEvents, options);
2466
2467 if (! mTempCancelationEvents.isEmpty()
2468 && connection->status != Connection::STATUS_BROKEN) {
2469#if DEBUG_OUTBOUND_EVENT_DETAILS
2470 LOGD("channel '%s' ~ Synthesized %d cancelation events to bring channel back in sync "
Jeff Brownda3d5a92011-03-29 15:11:34 -07002471 "with reality: %s, mode=%d.",
2472 connection->getInputChannelName(), mTempCancelationEvents.size(),
2473 options.reason, options.mode);
Jeff Brownb6997262010-10-08 22:31:17 -07002474#endif
2475 for (size_t i = 0; i < mTempCancelationEvents.size(); i++) {
2476 EventEntry* cancelationEventEntry = mTempCancelationEvents.itemAt(i);
2477 switch (cancelationEventEntry->type) {
2478 case EventEntry::TYPE_KEY:
2479 logOutboundKeyDetailsLocked("cancel - ",
2480 static_cast<KeyEntry*>(cancelationEventEntry));
2481 break;
2482 case EventEntry::TYPE_MOTION:
2483 logOutboundMotionDetailsLocked("cancel - ",
2484 static_cast<MotionEntry*>(cancelationEventEntry));
2485 break;
2486 }
2487
Jeff Brown81346812011-06-28 20:08:48 -07002488 InputTarget target;
Jeff Brown9302c872011-07-13 22:51:29 -07002489 sp<InputWindowHandle> windowHandle = getWindowHandleLocked(connection->inputChannel);
2490 if (windowHandle != NULL) {
Jeff Browncc4f7db2011-08-30 20:34:48 -07002491 const InputWindowInfo* windowInfo = windowHandle->getInfo();
2492 target.xOffset = -windowInfo->frameLeft;
2493 target.yOffset = -windowInfo->frameTop;
2494 target.scaleFactor = windowInfo->scaleFactor;
Jeff Brownb6997262010-10-08 22:31:17 -07002495 } else {
Jeff Brown81346812011-06-28 20:08:48 -07002496 target.xOffset = 0;
2497 target.yOffset = 0;
2498 target.scaleFactor = 1.0f;
Jeff Brownb6997262010-10-08 22:31:17 -07002499 }
Jeff Brown81346812011-06-28 20:08:48 -07002500 target.inputChannel = connection->inputChannel;
2501 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
Jeff Brownb6997262010-10-08 22:31:17 -07002502
Jeff Brown81346812011-06-28 20:08:48 -07002503 enqueueDispatchEntryLocked(connection, cancelationEventEntry, // increments ref
2504 &target, false, InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brownb6997262010-10-08 22:31:17 -07002505
Jeff Brownac386072011-07-20 15:19:50 -07002506 cancelationEventEntry->release();
Jeff Brownb6997262010-10-08 22:31:17 -07002507 }
2508
Jeff Brownac386072011-07-20 15:19:50 -07002509 if (!connection->outboundQueue.head->inProgress) {
Jeff Brownb6997262010-10-08 22:31:17 -07002510 startDispatchCycleLocked(currentTime, connection);
2511 }
2512 }
2513}
2514
Jeff Brown01ce2e92010-09-26 22:20:12 -07002515InputDispatcher::MotionEntry*
2516InputDispatcher::splitMotionEvent(const MotionEntry* originalMotionEntry, BitSet32 pointerIds) {
Jeff Brownb6110c22011-04-01 16:15:13 -07002517 LOG_ASSERT(pointerIds.value != 0);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002518
2519 uint32_t splitPointerIndexMap[MAX_POINTERS];
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002520 PointerProperties splitPointerProperties[MAX_POINTERS];
Jeff Brown01ce2e92010-09-26 22:20:12 -07002521 PointerCoords splitPointerCoords[MAX_POINTERS];
2522
2523 uint32_t originalPointerCount = originalMotionEntry->pointerCount;
2524 uint32_t splitPointerCount = 0;
2525
2526 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
2527 originalPointerIndex++) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002528 const PointerProperties& pointerProperties =
2529 originalMotionEntry->pointerProperties[originalPointerIndex];
2530 uint32_t pointerId = uint32_t(pointerProperties.id);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002531 if (pointerIds.hasBit(pointerId)) {
2532 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002533 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
Jeff Brownace13b12011-03-09 17:39:48 -08002534 splitPointerCoords[splitPointerCount].copyFrom(
2535 originalMotionEntry->firstSample.pointerCoords[originalPointerIndex]);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002536 splitPointerCount += 1;
2537 }
2538 }
Jeff Brown58a2da82011-01-25 16:02:22 -08002539
2540 if (splitPointerCount != pointerIds.count()) {
2541 // This is bad. We are missing some of the pointers that we expected to deliver.
2542 // Most likely this indicates that we received an ACTION_MOVE events that has
2543 // different pointer ids than we expected based on the previous ACTION_DOWN
2544 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
2545 // in this way.
2546 LOGW("Dropping split motion event because the pointer count is %d but "
2547 "we expected there to be %d pointers. This probably means we received "
2548 "a broken sequence of pointer ids from the input device.",
2549 splitPointerCount, pointerIds.count());
2550 return NULL;
2551 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07002552
2553 int32_t action = originalMotionEntry->action;
2554 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
2555 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
2556 || maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2557 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002558 const PointerProperties& pointerProperties =
2559 originalMotionEntry->pointerProperties[originalPointerIndex];
2560 uint32_t pointerId = uint32_t(pointerProperties.id);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002561 if (pointerIds.hasBit(pointerId)) {
2562 if (pointerIds.count() == 1) {
2563 // The first/last pointer went down/up.
2564 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
2565 ? AMOTION_EVENT_ACTION_DOWN : AMOTION_EVENT_ACTION_UP;
Jeff Brown9a01d052010-09-27 16:35:11 -07002566 } else {
2567 // A secondary pointer went down/up.
2568 uint32_t splitPointerIndex = 0;
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002569 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
Jeff Brown9a01d052010-09-27 16:35:11 -07002570 splitPointerIndex += 1;
2571 }
2572 action = maskedAction | (splitPointerIndex
2573 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002574 }
2575 } else {
2576 // An unrelated pointer changed.
2577 action = AMOTION_EVENT_ACTION_MOVE;
2578 }
2579 }
2580
Jeff Brownac386072011-07-20 15:19:50 -07002581 MotionEntry* splitMotionEntry = new MotionEntry(
Jeff Brown01ce2e92010-09-26 22:20:12 -07002582 originalMotionEntry->eventTime,
2583 originalMotionEntry->deviceId,
2584 originalMotionEntry->source,
2585 originalMotionEntry->policyFlags,
2586 action,
2587 originalMotionEntry->flags,
2588 originalMotionEntry->metaState,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002589 originalMotionEntry->buttonState,
Jeff Brown01ce2e92010-09-26 22:20:12 -07002590 originalMotionEntry->edgeFlags,
2591 originalMotionEntry->xPrecision,
2592 originalMotionEntry->yPrecision,
2593 originalMotionEntry->downTime,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002594 splitPointerCount, splitPointerProperties, splitPointerCoords);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002595
2596 for (MotionSample* originalMotionSample = originalMotionEntry->firstSample.next;
2597 originalMotionSample != NULL; originalMotionSample = originalMotionSample->next) {
2598 for (uint32_t splitPointerIndex = 0; splitPointerIndex < splitPointerCount;
2599 splitPointerIndex++) {
2600 uint32_t originalPointerIndex = splitPointerIndexMap[splitPointerIndex];
Jeff Brownace13b12011-03-09 17:39:48 -08002601 splitPointerCoords[splitPointerIndex].copyFrom(
2602 originalMotionSample->pointerCoords[originalPointerIndex]);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002603 }
2604
Jeff Brownac386072011-07-20 15:19:50 -07002605 splitMotionEntry->appendSample(originalMotionSample->eventTime, splitPointerCoords);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002606 }
2607
Jeff Browna032cc02011-03-07 16:56:21 -08002608 if (originalMotionEntry->injectionState) {
2609 splitMotionEntry->injectionState = originalMotionEntry->injectionState;
2610 splitMotionEntry->injectionState->refCount += 1;
2611 }
2612
Jeff Brown01ce2e92010-09-26 22:20:12 -07002613 return splitMotionEntry;
2614}
2615
Jeff Brownbe1aa822011-07-27 16:04:54 -07002616void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002617#if DEBUG_INBOUND_EVENT_DETAILS
Jeff Brownbe1aa822011-07-27 16:04:54 -07002618 LOGD("notifyConfigurationChanged - eventTime=%lld", args->eventTime);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002619#endif
2620
Jeff Brownb88102f2010-09-08 11:49:43 -07002621 bool needWake;
Jeff Brown46b9ac02010-04-22 18:58:52 -07002622 { // acquire lock
2623 AutoMutex _l(mLock);
2624
Jeff Brownbe1aa822011-07-27 16:04:54 -07002625 ConfigurationChangedEntry* newEntry = new ConfigurationChangedEntry(args->eventTime);
Jeff Brownb88102f2010-09-08 11:49:43 -07002626 needWake = enqueueInboundEventLocked(newEntry);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002627 } // release lock
2628
Jeff Brownb88102f2010-09-08 11:49:43 -07002629 if (needWake) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002630 mLooper->wake();
Jeff Brown46b9ac02010-04-22 18:58:52 -07002631 }
2632}
2633
Jeff Brownbe1aa822011-07-27 16:04:54 -07002634void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002635#if DEBUG_INBOUND_EVENT_DETAILS
Jeff Brown90655042010-12-02 13:50:46 -08002636 LOGD("notifyKey - eventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, action=0x%x, "
Jeff Brown46b9ac02010-04-22 18:58:52 -07002637 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%lld",
Jeff Brownbe1aa822011-07-27 16:04:54 -07002638 args->eventTime, args->deviceId, args->source, args->policyFlags,
2639 args->action, args->flags, args->keyCode, args->scanCode,
2640 args->metaState, args->downTime);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002641#endif
Jeff Brownbe1aa822011-07-27 16:04:54 -07002642 if (!validateKeyEvent(args->action)) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002643 return;
2644 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002645
Jeff Brownbe1aa822011-07-27 16:04:54 -07002646 uint32_t policyFlags = args->policyFlags;
2647 int32_t flags = args->flags;
2648 int32_t metaState = args->metaState;
Jeff Brown1f245102010-11-18 20:53:46 -08002649 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
2650 policyFlags |= POLICY_FLAG_VIRTUAL;
2651 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
2652 }
Jeff Brown924c4d42011-03-07 16:40:47 -08002653 if (policyFlags & POLICY_FLAG_ALT) {
2654 metaState |= AMETA_ALT_ON | AMETA_ALT_LEFT_ON;
2655 }
2656 if (policyFlags & POLICY_FLAG_ALT_GR) {
2657 metaState |= AMETA_ALT_ON | AMETA_ALT_RIGHT_ON;
2658 }
2659 if (policyFlags & POLICY_FLAG_SHIFT) {
2660 metaState |= AMETA_SHIFT_ON | AMETA_SHIFT_LEFT_ON;
2661 }
2662 if (policyFlags & POLICY_FLAG_CAPS_LOCK) {
2663 metaState |= AMETA_CAPS_LOCK_ON;
2664 }
2665 if (policyFlags & POLICY_FLAG_FUNCTION) {
2666 metaState |= AMETA_FUNCTION_ON;
2667 }
Jeff Brown1f245102010-11-18 20:53:46 -08002668
Jeff Browne20c9e02010-10-11 14:20:19 -07002669 policyFlags |= POLICY_FLAG_TRUSTED;
Jeff Brown1f245102010-11-18 20:53:46 -08002670
2671 KeyEvent event;
Jeff Brownbe1aa822011-07-27 16:04:54 -07002672 event.initialize(args->deviceId, args->source, args->action,
2673 flags, args->keyCode, args->scanCode, metaState, 0,
2674 args->downTime, args->eventTime);
Jeff Brown1f245102010-11-18 20:53:46 -08002675
2676 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
2677
2678 if (policyFlags & POLICY_FLAG_WOKE_HERE) {
2679 flags |= AKEY_EVENT_FLAG_WOKE_HERE;
2680 }
Jeff Brownb6997262010-10-08 22:31:17 -07002681
Jeff Brownb88102f2010-09-08 11:49:43 -07002682 bool needWake;
Jeff Brown46b9ac02010-04-22 18:58:52 -07002683 { // acquire lock
Jeff Brown0029c662011-03-30 02:25:18 -07002684 mLock.lock();
2685
2686 if (mInputFilterEnabled) {
2687 mLock.unlock();
2688
2689 policyFlags |= POLICY_FLAG_FILTERED;
2690 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2691 return; // event was consumed by the filter
2692 }
2693
2694 mLock.lock();
2695 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002696
Jeff Brown7fbdc842010-06-17 20:52:56 -07002697 int32_t repeatCount = 0;
Jeff Brownbe1aa822011-07-27 16:04:54 -07002698 KeyEntry* newEntry = new KeyEntry(args->eventTime,
2699 args->deviceId, args->source, policyFlags,
2700 args->action, flags, args->keyCode, args->scanCode,
2701 metaState, repeatCount, args->downTime);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002702
Jeff Brownb88102f2010-09-08 11:49:43 -07002703 needWake = enqueueInboundEventLocked(newEntry);
Jeff Brown0029c662011-03-30 02:25:18 -07002704 mLock.unlock();
Jeff Brown46b9ac02010-04-22 18:58:52 -07002705 } // release lock
2706
Jeff Brownb88102f2010-09-08 11:49:43 -07002707 if (needWake) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002708 mLooper->wake();
Jeff Brown46b9ac02010-04-22 18:58:52 -07002709 }
2710}
2711
Jeff Brownbe1aa822011-07-27 16:04:54 -07002712void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002713#if DEBUG_INBOUND_EVENT_DETAILS
Jeff Brown90655042010-12-02 13:50:46 -08002714 LOGD("notifyMotion - eventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, "
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002715 "action=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, edgeFlags=0x%x, "
Jeff Brown85a31762010-09-01 17:01:00 -07002716 "xPrecision=%f, yPrecision=%f, downTime=%lld",
Jeff Brownbe1aa822011-07-27 16:04:54 -07002717 args->eventTime, args->deviceId, args->source, args->policyFlags,
2718 args->action, args->flags, args->metaState, args->buttonState,
2719 args->edgeFlags, args->xPrecision, args->yPrecision, args->downTime);
2720 for (uint32_t i = 0; i < args->pointerCount; i++) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002721 LOGD(" Pointer %d: id=%d, toolType=%d, "
2722 "x=%f, y=%f, pressure=%f, size=%f, "
Jeff Brown85a31762010-09-01 17:01:00 -07002723 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
Jeff Brown8d608662010-08-30 03:02:23 -07002724 "orientation=%f",
Jeff Brownbe1aa822011-07-27 16:04:54 -07002725 i, args->pointerProperties[i].id,
2726 args->pointerProperties[i].toolType,
2727 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
2728 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
2729 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
2730 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
2731 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
2732 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
2733 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
2734 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
2735 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Jeff Brown46b9ac02010-04-22 18:58:52 -07002736 }
2737#endif
Jeff Brownbe1aa822011-07-27 16:04:54 -07002738 if (!validateMotionEvent(args->action, args->pointerCount, args->pointerProperties)) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002739 return;
2740 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002741
Jeff Brownbe1aa822011-07-27 16:04:54 -07002742 uint32_t policyFlags = args->policyFlags;
Jeff Browne20c9e02010-10-11 14:20:19 -07002743 policyFlags |= POLICY_FLAG_TRUSTED;
Jeff Brownbe1aa822011-07-27 16:04:54 -07002744 mPolicy->interceptMotionBeforeQueueing(args->eventTime, /*byref*/ policyFlags);
Jeff Brownb6997262010-10-08 22:31:17 -07002745
Jeff Brownb88102f2010-09-08 11:49:43 -07002746 bool needWake;
Jeff Brown46b9ac02010-04-22 18:58:52 -07002747 { // acquire lock
Jeff Brown0029c662011-03-30 02:25:18 -07002748 mLock.lock();
2749
2750 if (mInputFilterEnabled) {
2751 mLock.unlock();
2752
2753 MotionEvent event;
Jeff Brownbe1aa822011-07-27 16:04:54 -07002754 event.initialize(args->deviceId, args->source, args->action, args->flags,
2755 args->edgeFlags, args->metaState, args->buttonState, 0, 0,
2756 args->xPrecision, args->yPrecision,
2757 args->downTime, args->eventTime,
2758 args->pointerCount, args->pointerProperties, args->pointerCoords);
Jeff Brown0029c662011-03-30 02:25:18 -07002759
2760 policyFlags |= POLICY_FLAG_FILTERED;
2761 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2762 return; // event was consumed by the filter
2763 }
2764
2765 mLock.lock();
2766 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002767
2768 // Attempt batching and streaming of move events.
Jeff Brownbe1aa822011-07-27 16:04:54 -07002769 if (args->action == AMOTION_EVENT_ACTION_MOVE
2770 || args->action == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002771 // BATCHING CASE
2772 //
2773 // Try to append a move sample to the tail of the inbound queue for this device.
2774 // Give up if we encounter a non-move motion event for this device since that
2775 // means we cannot append any new samples until a new motion event has started.
Jeff Brownac386072011-07-20 15:19:50 -07002776 for (EventEntry* entry = mInboundQueue.tail; entry; entry = entry->prev) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002777 if (entry->type != EventEntry::TYPE_MOTION) {
2778 // Keep looking for motion events.
2779 continue;
2780 }
2781
2782 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
Jeff Brownbe1aa822011-07-27 16:04:54 -07002783 if (motionEntry->deviceId != args->deviceId
2784 || motionEntry->source != args->source) {
Jeff Brownefd32662011-03-08 15:13:06 -08002785 // Keep looking for this device and source.
Jeff Brown46b9ac02010-04-22 18:58:52 -07002786 continue;
2787 }
2788
Jeff Brownbe1aa822011-07-27 16:04:54 -07002789 if (!motionEntry->canAppendSamples(args->action,
2790 args->pointerCount, args->pointerProperties)) {
Jeff Brownefd32662011-03-08 15:13:06 -08002791 // Last motion event in the queue for this device and source is
2792 // not compatible for appending new samples. Stop here.
Jeff Brown46b9ac02010-04-22 18:58:52 -07002793 goto NoBatchingOrStreaming;
2794 }
2795
Jeff Brown9c3cda02010-06-15 01:31:58 -07002796 // Do the batching magic.
Jeff Brownbe1aa822011-07-27 16:04:54 -07002797 batchMotionLocked(motionEntry, args->eventTime,
2798 args->metaState, args->pointerCoords,
Jeff Brown4e91a182011-04-07 11:38:09 -07002799 "most recent motion event for this device and source in the inbound queue");
Jeff Brown0029c662011-03-30 02:25:18 -07002800 mLock.unlock();
Jeff Brown9c3cda02010-06-15 01:31:58 -07002801 return; // done!
Jeff Brown46b9ac02010-04-22 18:58:52 -07002802 }
2803
Jeff Brownf6989da2011-04-06 17:19:48 -07002804 // BATCHING ONTO PENDING EVENT CASE
2805 //
2806 // Try to append a move sample to the currently pending event, if there is one.
2807 // We can do this as long as we are still waiting to find the targets for the
2808 // event. Once the targets are locked-in we can only do streaming.
2809 if (mPendingEvent
2810 && (!mPendingEvent->dispatchInProgress || !mCurrentInputTargetsValid)
2811 && mPendingEvent->type == EventEntry::TYPE_MOTION) {
2812 MotionEntry* motionEntry = static_cast<MotionEntry*>(mPendingEvent);
Jeff Brownbe1aa822011-07-27 16:04:54 -07002813 if (motionEntry->deviceId == args->deviceId
2814 && motionEntry->source == args->source) {
2815 if (!motionEntry->canAppendSamples(args->action,
2816 args->pointerCount, args->pointerProperties)) {
Jeff Brown4e91a182011-04-07 11:38:09 -07002817 // Pending motion event is for this device and source but it is
2818 // not compatible for appending new samples. Stop here.
Jeff Brownf6989da2011-04-06 17:19:48 -07002819 goto NoBatchingOrStreaming;
2820 }
2821
Jeff Brownf6989da2011-04-06 17:19:48 -07002822 // Do the batching magic.
Jeff Brownbe1aa822011-07-27 16:04:54 -07002823 batchMotionLocked(motionEntry, args->eventTime,
2824 args->metaState, args->pointerCoords,
Jeff Brown4e91a182011-04-07 11:38:09 -07002825 "pending motion event");
Jeff Brownf6989da2011-04-06 17:19:48 -07002826 mLock.unlock();
2827 return; // done!
2828 }
2829 }
2830
Jeff Brown46b9ac02010-04-22 18:58:52 -07002831 // STREAMING CASE
2832 //
2833 // There is no pending motion event (of any kind) for this device in the inbound queue.
Jeff Brown519e0242010-09-15 15:18:56 -07002834 // Search the outbound queue for the current foreground targets to find a dispatched
2835 // motion event that is still in progress. If found, then, appen the new sample to
2836 // that event and push it out to all current targets. The logic in
2837 // prepareDispatchCycleLocked takes care of the case where some targets may
2838 // already have consumed the motion event by starting a new dispatch cycle if needed.
Jeff Brown9c3cda02010-06-15 01:31:58 -07002839 if (mCurrentInputTargetsValid) {
Jeff Brown519e0242010-09-15 15:18:56 -07002840 for (size_t i = 0; i < mCurrentInputTargets.size(); i++) {
2841 const InputTarget& inputTarget = mCurrentInputTargets[i];
2842 if ((inputTarget.flags & InputTarget::FLAG_FOREGROUND) == 0) {
2843 // Skip non-foreground targets. We only want to stream if there is at
2844 // least one foreground target whose dispatch is still in progress.
2845 continue;
Jeff Brown46b9ac02010-04-22 18:58:52 -07002846 }
Jeff Brown519e0242010-09-15 15:18:56 -07002847
2848 ssize_t connectionIndex = getConnectionIndexLocked(inputTarget.inputChannel);
2849 if (connectionIndex < 0) {
2850 // Connection must no longer be valid.
2851 continue;
2852 }
2853
2854 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
2855 if (connection->outboundQueue.isEmpty()) {
2856 // This foreground target has an empty outbound queue.
2857 continue;
2858 }
2859
Jeff Brownac386072011-07-20 15:19:50 -07002860 DispatchEntry* dispatchEntry = connection->outboundQueue.head;
Jeff Brown519e0242010-09-15 15:18:56 -07002861 if (! dispatchEntry->inProgress
Jeff Brown01ce2e92010-09-26 22:20:12 -07002862 || dispatchEntry->eventEntry->type != EventEntry::TYPE_MOTION
2863 || dispatchEntry->isSplit()) {
2864 // No motion event is being dispatched, or it is being split across
2865 // windows in which case we cannot stream.
Jeff Brown519e0242010-09-15 15:18:56 -07002866 continue;
2867 }
2868
2869 MotionEntry* motionEntry = static_cast<MotionEntry*>(
2870 dispatchEntry->eventEntry);
Jeff Brownbe1aa822011-07-27 16:04:54 -07002871 if (motionEntry->action != args->action
2872 || motionEntry->deviceId != args->deviceId
2873 || motionEntry->source != args->source
2874 || motionEntry->pointerCount != args->pointerCount
Jeff Brown519e0242010-09-15 15:18:56 -07002875 || motionEntry->isInjected()) {
2876 // The motion event is not compatible with this move.
2877 continue;
2878 }
2879
Jeff Brownbe1aa822011-07-27 16:04:54 -07002880 if (args->action == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Jeff Brown9302c872011-07-13 22:51:29 -07002881 if (mLastHoverWindowHandle == NULL) {
Jeff Browna032cc02011-03-07 16:56:21 -08002882#if DEBUG_BATCHING
2883 LOGD("Not streaming hover move because there is no "
2884 "last hovered window.");
2885#endif
2886 goto NoBatchingOrStreaming;
2887 }
2888
Jeff Brown9302c872011-07-13 22:51:29 -07002889 sp<InputWindowHandle> hoverWindowHandle = findTouchedWindowAtLocked(
Jeff Brownbe1aa822011-07-27 16:04:54 -07002890 args->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X),
2891 args->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Jeff Brown9302c872011-07-13 22:51:29 -07002892 if (mLastHoverWindowHandle != hoverWindowHandle) {
Jeff Browna032cc02011-03-07 16:56:21 -08002893#if DEBUG_BATCHING
2894 LOGD("Not streaming hover move because the last hovered window "
2895 "is '%s' but the currently hovered window is '%s'.",
Jeff Browncc4f7db2011-08-30 20:34:48 -07002896 mLastHoverWindowHandle->getName().string(),
Jeff Brown9302c872011-07-13 22:51:29 -07002897 hoverWindowHandle != NULL
Jeff Browncc4f7db2011-08-30 20:34:48 -07002898 ? hoverWindowHandle->getName().string() : "<null>");
Jeff Browna032cc02011-03-07 16:56:21 -08002899#endif
2900 goto NoBatchingOrStreaming;
2901 }
2902 }
2903
Jeff Brown519e0242010-09-15 15:18:56 -07002904 // Hurray! This foreground target is currently dispatching a move event
2905 // that we can stream onto. Append the motion sample and resume dispatch.
Jeff Brownbe1aa822011-07-27 16:04:54 -07002906 motionEntry->appendSample(args->eventTime, args->pointerCoords);
Jeff Brown519e0242010-09-15 15:18:56 -07002907#if DEBUG_BATCHING
2908 LOGD("Appended motion sample onto batch for most recently dispatched "
Jeff Brown4e91a182011-04-07 11:38:09 -07002909 "motion event for this device and source in the outbound queues. "
Jeff Brown519e0242010-09-15 15:18:56 -07002910 "Attempting to stream the motion sample.");
2911#endif
2912 nsecs_t currentTime = now();
2913 dispatchEventToCurrentInputTargetsLocked(currentTime, motionEntry,
2914 true /*resumeWithAppendedMotionSample*/);
2915
2916 runCommandsLockedInterruptible();
Jeff Brown0029c662011-03-30 02:25:18 -07002917 mLock.unlock();
Jeff Brown519e0242010-09-15 15:18:56 -07002918 return; // done!
Jeff Brown46b9ac02010-04-22 18:58:52 -07002919 }
2920 }
2921
2922NoBatchingOrStreaming:;
2923 }
2924
2925 // Just enqueue a new motion event.
Jeff Brownbe1aa822011-07-27 16:04:54 -07002926 MotionEntry* newEntry = new MotionEntry(args->eventTime,
2927 args->deviceId, args->source, policyFlags,
2928 args->action, args->flags, args->metaState, args->buttonState,
2929 args->edgeFlags, args->xPrecision, args->yPrecision, args->downTime,
2930 args->pointerCount, args->pointerProperties, args->pointerCoords);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002931
Jeff Brownb88102f2010-09-08 11:49:43 -07002932 needWake = enqueueInboundEventLocked(newEntry);
Jeff Brown0029c662011-03-30 02:25:18 -07002933 mLock.unlock();
Jeff Brown46b9ac02010-04-22 18:58:52 -07002934 } // release lock
2935
Jeff Brownb88102f2010-09-08 11:49:43 -07002936 if (needWake) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002937 mLooper->wake();
Jeff Brown46b9ac02010-04-22 18:58:52 -07002938 }
2939}
2940
Jeff Brown4e91a182011-04-07 11:38:09 -07002941void InputDispatcher::batchMotionLocked(MotionEntry* entry, nsecs_t eventTime,
2942 int32_t metaState, const PointerCoords* pointerCoords, const char* eventDescription) {
2943 // Combine meta states.
2944 entry->metaState |= metaState;
2945
2946 // Coalesce this sample if not enough time has elapsed since the last sample was
2947 // initially appended to the batch.
2948 MotionSample* lastSample = entry->lastSample;
2949 long interval = eventTime - lastSample->eventTimeBeforeCoalescing;
2950 if (interval <= MOTION_SAMPLE_COALESCE_INTERVAL) {
2951 uint32_t pointerCount = entry->pointerCount;
2952 for (uint32_t i = 0; i < pointerCount; i++) {
2953 lastSample->pointerCoords[i].copyFrom(pointerCoords[i]);
2954 }
2955 lastSample->eventTime = eventTime;
2956#if DEBUG_BATCHING
2957 LOGD("Coalesced motion into last sample of batch for %s, events were %0.3f ms apart",
2958 eventDescription, interval * 0.000001f);
2959#endif
2960 return;
2961 }
2962
2963 // Append the sample.
Jeff Brownac386072011-07-20 15:19:50 -07002964 entry->appendSample(eventTime, pointerCoords);
Jeff Brown4e91a182011-04-07 11:38:09 -07002965#if DEBUG_BATCHING
2966 LOGD("Appended motion sample onto batch for %s, events were %0.3f ms apart",
2967 eventDescription, interval * 0.000001f);
2968#endif
2969}
2970
Jeff Brownbe1aa822011-07-27 16:04:54 -07002971void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
Jeff Brownb6997262010-10-08 22:31:17 -07002972#if DEBUG_INBOUND_EVENT_DETAILS
Jeff Brownbe1aa822011-07-27 16:04:54 -07002973 LOGD("notifySwitch - eventTime=%lld, policyFlags=0x%x, switchCode=%d, switchValue=%d",
2974 args->eventTime, args->policyFlags,
2975 args->switchCode, args->switchValue);
Jeff Brownb6997262010-10-08 22:31:17 -07002976#endif
2977
Jeff Brownbe1aa822011-07-27 16:04:54 -07002978 uint32_t policyFlags = args->policyFlags;
Jeff Browne20c9e02010-10-11 14:20:19 -07002979 policyFlags |= POLICY_FLAG_TRUSTED;
Jeff Brownbe1aa822011-07-27 16:04:54 -07002980 mPolicy->notifySwitch(args->eventTime,
2981 args->switchCode, args->switchValue, policyFlags);
Jeff Brownb6997262010-10-08 22:31:17 -07002982}
2983
Jeff Brown65fd2512011-08-18 11:20:58 -07002984void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
2985#if DEBUG_INBOUND_EVENT_DETAILS
2986 LOGD("notifyDeviceReset - eventTime=%lld, deviceId=%d",
2987 args->eventTime, args->deviceId);
2988#endif
2989
2990 bool needWake;
2991 { // acquire lock
2992 AutoMutex _l(mLock);
2993
2994 DeviceResetEntry* newEntry = new DeviceResetEntry(args->eventTime, args->deviceId);
2995 needWake = enqueueInboundEventLocked(newEntry);
2996 } // release lock
2997
2998 if (needWake) {
2999 mLooper->wake();
3000 }
3001}
3002
Jeff Brown7fbdc842010-06-17 20:52:56 -07003003int32_t InputDispatcher::injectInputEvent(const InputEvent* event,
Jeff Brown0029c662011-03-30 02:25:18 -07003004 int32_t injectorPid, int32_t injectorUid, int32_t syncMode, int32_t timeoutMillis,
3005 uint32_t policyFlags) {
Jeff Brown7fbdc842010-06-17 20:52:56 -07003006#if DEBUG_INBOUND_EVENT_DETAILS
3007 LOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Jeff Brown0029c662011-03-30 02:25:18 -07003008 "syncMode=%d, timeoutMillis=%d, policyFlags=0x%08x",
3009 event->getType(), injectorPid, injectorUid, syncMode, timeoutMillis, policyFlags);
Jeff Brown7fbdc842010-06-17 20:52:56 -07003010#endif
3011
3012 nsecs_t endTime = now() + milliseconds_to_nanoseconds(timeoutMillis);
Jeff Browne20c9e02010-10-11 14:20:19 -07003013
Jeff Brown0029c662011-03-30 02:25:18 -07003014 policyFlags |= POLICY_FLAG_INJECTED;
Jeff Browne20c9e02010-10-11 14:20:19 -07003015 if (hasInjectionPermission(injectorPid, injectorUid)) {
3016 policyFlags |= POLICY_FLAG_TRUSTED;
3017 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07003018
Jeff Brownb6997262010-10-08 22:31:17 -07003019 EventEntry* injectedEntry;
3020 switch (event->getType()) {
3021 case AINPUT_EVENT_TYPE_KEY: {
3022 const KeyEvent* keyEvent = static_cast<const KeyEvent*>(event);
3023 int32_t action = keyEvent->getAction();
3024 if (! validateKeyEvent(action)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07003025 return INPUT_EVENT_INJECTION_FAILED;
3026 }
3027
Jeff Brownb6997262010-10-08 22:31:17 -07003028 int32_t flags = keyEvent->getFlags();
Jeff Brown1f245102010-11-18 20:53:46 -08003029 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
3030 policyFlags |= POLICY_FLAG_VIRTUAL;
3031 }
3032
Jeff Brown0029c662011-03-30 02:25:18 -07003033 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3034 mPolicy->interceptKeyBeforeQueueing(keyEvent, /*byref*/ policyFlags);
3035 }
Jeff Brown1f245102010-11-18 20:53:46 -08003036
3037 if (policyFlags & POLICY_FLAG_WOKE_HERE) {
3038 flags |= AKEY_EVENT_FLAG_WOKE_HERE;
3039 }
Jeff Brown6ec402b2010-07-28 15:48:59 -07003040
Jeff Brownb6997262010-10-08 22:31:17 -07003041 mLock.lock();
Jeff Brownac386072011-07-20 15:19:50 -07003042 injectedEntry = new KeyEntry(keyEvent->getEventTime(),
Jeff Brown1f245102010-11-18 20:53:46 -08003043 keyEvent->getDeviceId(), keyEvent->getSource(),
3044 policyFlags, action, flags,
3045 keyEvent->getKeyCode(), keyEvent->getScanCode(), keyEvent->getMetaState(),
Jeff Brownb6997262010-10-08 22:31:17 -07003046 keyEvent->getRepeatCount(), keyEvent->getDownTime());
3047 break;
3048 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07003049
Jeff Brownb6997262010-10-08 22:31:17 -07003050 case AINPUT_EVENT_TYPE_MOTION: {
3051 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
3052 int32_t action = motionEvent->getAction();
3053 size_t pointerCount = motionEvent->getPointerCount();
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003054 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
3055 if (! validateMotionEvent(action, pointerCount, pointerProperties)) {
Jeff Brownb6997262010-10-08 22:31:17 -07003056 return INPUT_EVENT_INJECTION_FAILED;
3057 }
3058
Jeff Brown0029c662011-03-30 02:25:18 -07003059 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3060 nsecs_t eventTime = motionEvent->getEventTime();
3061 mPolicy->interceptMotionBeforeQueueing(eventTime, /*byref*/ policyFlags);
3062 }
Jeff Brownb6997262010-10-08 22:31:17 -07003063
3064 mLock.lock();
3065 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
3066 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
Jeff Brownac386072011-07-20 15:19:50 -07003067 MotionEntry* motionEntry = new MotionEntry(*sampleEventTimes,
Jeff Brownb6997262010-10-08 22:31:17 -07003068 motionEvent->getDeviceId(), motionEvent->getSource(), policyFlags,
3069 action, motionEvent->getFlags(),
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003070 motionEvent->getMetaState(), motionEvent->getButtonState(),
3071 motionEvent->getEdgeFlags(),
Jeff Brownb6997262010-10-08 22:31:17 -07003072 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
3073 motionEvent->getDownTime(), uint32_t(pointerCount),
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003074 pointerProperties, samplePointerCoords);
Jeff Brownb6997262010-10-08 22:31:17 -07003075 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
3076 sampleEventTimes += 1;
3077 samplePointerCoords += pointerCount;
Jeff Brownac386072011-07-20 15:19:50 -07003078 motionEntry->appendSample(*sampleEventTimes, samplePointerCoords);
Jeff Brownb6997262010-10-08 22:31:17 -07003079 }
3080 injectedEntry = motionEntry;
3081 break;
3082 }
3083
3084 default:
3085 LOGW("Cannot inject event of type %d", event->getType());
3086 return INPUT_EVENT_INJECTION_FAILED;
3087 }
3088
Jeff Brownac386072011-07-20 15:19:50 -07003089 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
Jeff Brownb6997262010-10-08 22:31:17 -07003090 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
3091 injectionState->injectionIsAsync = true;
3092 }
3093
3094 injectionState->refCount += 1;
3095 injectedEntry->injectionState = injectionState;
3096
3097 bool needWake = enqueueInboundEventLocked(injectedEntry);
3098 mLock.unlock();
Jeff Brown7fbdc842010-06-17 20:52:56 -07003099
Jeff Brownb88102f2010-09-08 11:49:43 -07003100 if (needWake) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07003101 mLooper->wake();
Jeff Brown7fbdc842010-06-17 20:52:56 -07003102 }
3103
3104 int32_t injectionResult;
3105 { // acquire lock
3106 AutoMutex _l(mLock);
3107
Jeff Brown6ec402b2010-07-28 15:48:59 -07003108 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
3109 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
3110 } else {
3111 for (;;) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07003112 injectionResult = injectionState->injectionResult;
Jeff Brown6ec402b2010-07-28 15:48:59 -07003113 if (injectionResult != INPUT_EVENT_INJECTION_PENDING) {
3114 break;
3115 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07003116
Jeff Brown7fbdc842010-06-17 20:52:56 -07003117 nsecs_t remainingTimeout = endTime - now();
3118 if (remainingTimeout <= 0) {
Jeff Brown6ec402b2010-07-28 15:48:59 -07003119#if DEBUG_INJECTION
3120 LOGD("injectInputEvent - Timed out waiting for injection result "
3121 "to become available.");
3122#endif
Jeff Brown7fbdc842010-06-17 20:52:56 -07003123 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
3124 break;
3125 }
3126
Jeff Brown6ec402b2010-07-28 15:48:59 -07003127 mInjectionResultAvailableCondition.waitRelative(mLock, remainingTimeout);
3128 }
3129
3130 if (injectionResult == INPUT_EVENT_INJECTION_SUCCEEDED
3131 && syncMode == INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07003132 while (injectionState->pendingForegroundDispatches != 0) {
Jeff Brown6ec402b2010-07-28 15:48:59 -07003133#if DEBUG_INJECTION
Jeff Brown519e0242010-09-15 15:18:56 -07003134 LOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
Jeff Brown01ce2e92010-09-26 22:20:12 -07003135 injectionState->pendingForegroundDispatches);
Jeff Brown6ec402b2010-07-28 15:48:59 -07003136#endif
3137 nsecs_t remainingTimeout = endTime - now();
3138 if (remainingTimeout <= 0) {
3139#if DEBUG_INJECTION
Jeff Brown519e0242010-09-15 15:18:56 -07003140 LOGD("injectInputEvent - Timed out waiting for pending foreground "
Jeff Brown6ec402b2010-07-28 15:48:59 -07003141 "dispatches to finish.");
3142#endif
3143 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
3144 break;
3145 }
3146
3147 mInjectionSyncFinishedCondition.waitRelative(mLock, remainingTimeout);
3148 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07003149 }
3150 }
3151
Jeff Brownac386072011-07-20 15:19:50 -07003152 injectionState->release();
Jeff Brown7fbdc842010-06-17 20:52:56 -07003153 } // release lock
3154
Jeff Brown6ec402b2010-07-28 15:48:59 -07003155#if DEBUG_INJECTION
3156 LOGD("injectInputEvent - Finished with result %d. "
3157 "injectorPid=%d, injectorUid=%d",
3158 injectionResult, injectorPid, injectorUid);
3159#endif
3160
Jeff Brown7fbdc842010-06-17 20:52:56 -07003161 return injectionResult;
3162}
3163
Jeff Brownb6997262010-10-08 22:31:17 -07003164bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
3165 return injectorUid == 0
3166 || mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
3167}
3168
Jeff Brown7fbdc842010-06-17 20:52:56 -07003169void InputDispatcher::setInjectionResultLocked(EventEntry* entry, int32_t injectionResult) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07003170 InjectionState* injectionState = entry->injectionState;
3171 if (injectionState) {
Jeff Brown7fbdc842010-06-17 20:52:56 -07003172#if DEBUG_INJECTION
3173 LOGD("Setting input event injection result to %d. "
3174 "injectorPid=%d, injectorUid=%d",
Jeff Brown01ce2e92010-09-26 22:20:12 -07003175 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
Jeff Brown7fbdc842010-06-17 20:52:56 -07003176#endif
3177
Jeff Brown0029c662011-03-30 02:25:18 -07003178 if (injectionState->injectionIsAsync
3179 && !(entry->policyFlags & POLICY_FLAG_FILTERED)) {
Jeff Brown6ec402b2010-07-28 15:48:59 -07003180 // Log the outcome since the injector did not wait for the injection result.
3181 switch (injectionResult) {
3182 case INPUT_EVENT_INJECTION_SUCCEEDED:
3183 LOGV("Asynchronous input event injection succeeded.");
3184 break;
3185 case INPUT_EVENT_INJECTION_FAILED:
3186 LOGW("Asynchronous input event injection failed.");
3187 break;
3188 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
3189 LOGW("Asynchronous input event injection permission denied.");
3190 break;
3191 case INPUT_EVENT_INJECTION_TIMED_OUT:
3192 LOGW("Asynchronous input event injection timed out.");
3193 break;
3194 }
3195 }
3196
Jeff Brown01ce2e92010-09-26 22:20:12 -07003197 injectionState->injectionResult = injectionResult;
Jeff Brown7fbdc842010-06-17 20:52:56 -07003198 mInjectionResultAvailableCondition.broadcast();
3199 }
3200}
3201
Jeff Brown01ce2e92010-09-26 22:20:12 -07003202void InputDispatcher::incrementPendingForegroundDispatchesLocked(EventEntry* entry) {
3203 InjectionState* injectionState = entry->injectionState;
3204 if (injectionState) {
3205 injectionState->pendingForegroundDispatches += 1;
3206 }
3207}
3208
Jeff Brown519e0242010-09-15 15:18:56 -07003209void InputDispatcher::decrementPendingForegroundDispatchesLocked(EventEntry* entry) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07003210 InjectionState* injectionState = entry->injectionState;
3211 if (injectionState) {
3212 injectionState->pendingForegroundDispatches -= 1;
Jeff Brown6ec402b2010-07-28 15:48:59 -07003213
Jeff Brown01ce2e92010-09-26 22:20:12 -07003214 if (injectionState->pendingForegroundDispatches == 0) {
3215 mInjectionSyncFinishedCondition.broadcast();
3216 }
Jeff Brownb88102f2010-09-08 11:49:43 -07003217 }
3218}
3219
Jeff Brown9302c872011-07-13 22:51:29 -07003220sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
3221 const sp<InputChannel>& inputChannel) const {
3222 size_t numWindows = mWindowHandles.size();
3223 for (size_t i = 0; i < numWindows; i++) {
3224 const sp<InputWindowHandle>& windowHandle = mWindowHandles.itemAt(i);
Jeff Browncc4f7db2011-08-30 20:34:48 -07003225 if (windowHandle->getInputChannel() == inputChannel) {
Jeff Brown9302c872011-07-13 22:51:29 -07003226 return windowHandle;
Jeff Brown01ce2e92010-09-26 22:20:12 -07003227 }
3228 }
3229 return NULL;
3230}
3231
Jeff Brown9302c872011-07-13 22:51:29 -07003232bool InputDispatcher::hasWindowHandleLocked(
3233 const sp<InputWindowHandle>& windowHandle) const {
3234 size_t numWindows = mWindowHandles.size();
3235 for (size_t i = 0; i < numWindows; i++) {
3236 if (mWindowHandles.itemAt(i) == windowHandle) {
3237 return true;
3238 }
3239 }
3240 return false;
3241}
3242
3243void InputDispatcher::setInputWindows(const Vector<sp<InputWindowHandle> >& inputWindowHandles) {
Jeff Brownb88102f2010-09-08 11:49:43 -07003244#if DEBUG_FOCUS
3245 LOGD("setInputWindows");
3246#endif
3247 { // acquire lock
3248 AutoMutex _l(mLock);
3249
Jeff Browncc4f7db2011-08-30 20:34:48 -07003250 Vector<sp<InputWindowHandle> > oldWindowHandles = mWindowHandles;
Jeff Brown9302c872011-07-13 22:51:29 -07003251 mWindowHandles = inputWindowHandles;
Jeff Brownb6997262010-10-08 22:31:17 -07003252
Jeff Brown9302c872011-07-13 22:51:29 -07003253 sp<InputWindowHandle> newFocusedWindowHandle;
3254 bool foundHoveredWindow = false;
3255 for (size_t i = 0; i < mWindowHandles.size(); i++) {
3256 const sp<InputWindowHandle>& windowHandle = mWindowHandles.itemAt(i);
Jeff Browncc4f7db2011-08-30 20:34:48 -07003257 if (!windowHandle->updateInfo() || windowHandle->getInputChannel() == NULL) {
Jeff Brown9302c872011-07-13 22:51:29 -07003258 mWindowHandles.removeAt(i--);
3259 continue;
3260 }
Jeff Browncc4f7db2011-08-30 20:34:48 -07003261 if (windowHandle->getInfo()->hasFocus) {
Jeff Brown9302c872011-07-13 22:51:29 -07003262 newFocusedWindowHandle = windowHandle;
3263 }
3264 if (windowHandle == mLastHoverWindowHandle) {
3265 foundHoveredWindow = true;
Jeff Brownb88102f2010-09-08 11:49:43 -07003266 }
3267 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07003268
Jeff Brown9302c872011-07-13 22:51:29 -07003269 if (!foundHoveredWindow) {
3270 mLastHoverWindowHandle = NULL;
3271 }
3272
3273 if (mFocusedWindowHandle != newFocusedWindowHandle) {
3274 if (mFocusedWindowHandle != NULL) {
Jeff Brownb6997262010-10-08 22:31:17 -07003275#if DEBUG_FOCUS
3276 LOGD("Focus left window: %s",
Jeff Browncc4f7db2011-08-30 20:34:48 -07003277 mFocusedWindowHandle->getName().string());
Jeff Brownb6997262010-10-08 22:31:17 -07003278#endif
Jeff Browncc4f7db2011-08-30 20:34:48 -07003279 sp<InputChannel> focusedInputChannel = mFocusedWindowHandle->getInputChannel();
3280 if (focusedInputChannel != NULL) {
Christopher Tated9be36c2011-08-16 16:09:33 -07003281 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
3282 "focus left window");
3283 synthesizeCancelationEventsForInputChannelLocked(
Jeff Browncc4f7db2011-08-30 20:34:48 -07003284 focusedInputChannel, options);
Christopher Tated9be36c2011-08-16 16:09:33 -07003285 }
Jeff Brownb6997262010-10-08 22:31:17 -07003286 }
Jeff Brown9302c872011-07-13 22:51:29 -07003287 if (newFocusedWindowHandle != NULL) {
Jeff Brownb6997262010-10-08 22:31:17 -07003288#if DEBUG_FOCUS
Jeff Brown9302c872011-07-13 22:51:29 -07003289 LOGD("Focus entered window: %s",
Jeff Browncc4f7db2011-08-30 20:34:48 -07003290 newFocusedWindowHandle->getName().string());
Jeff Brownb6997262010-10-08 22:31:17 -07003291#endif
Jeff Brown9302c872011-07-13 22:51:29 -07003292 }
3293 mFocusedWindowHandle = newFocusedWindowHandle;
Jeff Brownb6997262010-10-08 22:31:17 -07003294 }
3295
Jeff Brown9302c872011-07-13 22:51:29 -07003296 for (size_t i = 0; i < mTouchState.windows.size(); i++) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07003297 TouchedWindow& touchedWindow = mTouchState.windows.editItemAt(i);
Jeff Brown9302c872011-07-13 22:51:29 -07003298 if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
Jeff Brownb6997262010-10-08 22:31:17 -07003299#if DEBUG_FOCUS
Jeff Browncc4f7db2011-08-30 20:34:48 -07003300 LOGD("Touched window was removed: %s",
3301 touchedWindow.windowHandle->getName().string());
Jeff Brownb6997262010-10-08 22:31:17 -07003302#endif
Jeff Browncc4f7db2011-08-30 20:34:48 -07003303 sp<InputChannel> touchedInputChannel =
3304 touchedWindow.windowHandle->getInputChannel();
3305 if (touchedInputChannel != NULL) {
Christopher Tated9be36c2011-08-16 16:09:33 -07003306 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
3307 "touched window was removed");
3308 synthesizeCancelationEventsForInputChannelLocked(
Jeff Browncc4f7db2011-08-30 20:34:48 -07003309 touchedInputChannel, options);
Christopher Tated9be36c2011-08-16 16:09:33 -07003310 }
Jeff Brown9302c872011-07-13 22:51:29 -07003311 mTouchState.windows.removeAt(i--);
Jeff Brown01ce2e92010-09-26 22:20:12 -07003312 }
3313 }
Jeff Browncc4f7db2011-08-30 20:34:48 -07003314
3315 // Release information for windows that are no longer present.
3316 // This ensures that unused input channels are released promptly.
3317 // Otherwise, they might stick around until the window handle is destroyed
3318 // which might not happen until the next GC.
3319 for (size_t i = 0; i < oldWindowHandles.size(); i++) {
3320 const sp<InputWindowHandle>& oldWindowHandle = oldWindowHandles.itemAt(i);
3321 if (!hasWindowHandleLocked(oldWindowHandle)) {
3322#if DEBUG_FOCUS
3323 LOGD("Window went away: %s", oldWindowHandle->getName().string());
3324#endif
3325 oldWindowHandle->releaseInfo();
3326 }
3327 }
Jeff Brownb88102f2010-09-08 11:49:43 -07003328 } // release lock
3329
3330 // Wake up poll loop since it may need to make new input dispatching choices.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07003331 mLooper->wake();
Jeff Brownb88102f2010-09-08 11:49:43 -07003332}
3333
Jeff Brown9302c872011-07-13 22:51:29 -07003334void InputDispatcher::setFocusedApplication(
3335 const sp<InputApplicationHandle>& inputApplicationHandle) {
Jeff Brownb88102f2010-09-08 11:49:43 -07003336#if DEBUG_FOCUS
3337 LOGD("setFocusedApplication");
3338#endif
3339 { // acquire lock
3340 AutoMutex _l(mLock);
3341
Jeff Browncc4f7db2011-08-30 20:34:48 -07003342 if (inputApplicationHandle != NULL && inputApplicationHandle->updateInfo()) {
Jeff Brown5ea29ab2011-07-27 11:50:51 -07003343 if (mFocusedApplicationHandle != inputApplicationHandle) {
3344 if (mFocusedApplicationHandle != NULL) {
3345 resetTargetsLocked();
Jeff Browncc4f7db2011-08-30 20:34:48 -07003346 mFocusedApplicationHandle->releaseInfo();
Jeff Brown5ea29ab2011-07-27 11:50:51 -07003347 }
3348 mFocusedApplicationHandle = inputApplicationHandle;
3349 }
3350 } else if (mFocusedApplicationHandle != NULL) {
3351 resetTargetsLocked();
Jeff Browncc4f7db2011-08-30 20:34:48 -07003352 mFocusedApplicationHandle->releaseInfo();
Jeff Brown9302c872011-07-13 22:51:29 -07003353 mFocusedApplicationHandle.clear();
Jeff Brownb88102f2010-09-08 11:49:43 -07003354 }
3355
3356#if DEBUG_FOCUS
Jeff Brownb6997262010-10-08 22:31:17 -07003357 //logDispatchStateLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -07003358#endif
3359 } // release lock
3360
3361 // Wake up poll loop since it may need to make new input dispatching choices.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07003362 mLooper->wake();
Jeff Brownb88102f2010-09-08 11:49:43 -07003363}
3364
Jeff Brownb88102f2010-09-08 11:49:43 -07003365void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
3366#if DEBUG_FOCUS
3367 LOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
3368#endif
3369
3370 bool changed;
3371 { // acquire lock
3372 AutoMutex _l(mLock);
3373
3374 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
Jeff Brown120a4592010-10-27 18:43:51 -07003375 if (mDispatchFrozen && !frozen) {
Jeff Brownb88102f2010-09-08 11:49:43 -07003376 resetANRTimeoutsLocked();
3377 }
3378
Jeff Brown120a4592010-10-27 18:43:51 -07003379 if (mDispatchEnabled && !enabled) {
3380 resetAndDropEverythingLocked("dispatcher is being disabled");
3381 }
3382
Jeff Brownb88102f2010-09-08 11:49:43 -07003383 mDispatchEnabled = enabled;
3384 mDispatchFrozen = frozen;
3385 changed = true;
3386 } else {
3387 changed = false;
3388 }
3389
3390#if DEBUG_FOCUS
Jeff Brownb6997262010-10-08 22:31:17 -07003391 //logDispatchStateLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -07003392#endif
3393 } // release lock
3394
3395 if (changed) {
3396 // Wake up poll loop since it may need to make new input dispatching choices.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07003397 mLooper->wake();
Jeff Brown46b9ac02010-04-22 18:58:52 -07003398 }
3399}
3400
Jeff Brown0029c662011-03-30 02:25:18 -07003401void InputDispatcher::setInputFilterEnabled(bool enabled) {
3402#if DEBUG_FOCUS
3403 LOGD("setInputFilterEnabled: enabled=%d", enabled);
3404#endif
3405
3406 { // acquire lock
3407 AutoMutex _l(mLock);
3408
3409 if (mInputFilterEnabled == enabled) {
3410 return;
3411 }
3412
3413 mInputFilterEnabled = enabled;
3414 resetAndDropEverythingLocked("input filter is being enabled or disabled");
3415 } // release lock
3416
3417 // Wake up poll loop since there might be work to do to drop everything.
3418 mLooper->wake();
3419}
3420
Jeff Browne6504122010-09-27 14:52:15 -07003421bool InputDispatcher::transferTouchFocus(const sp<InputChannel>& fromChannel,
3422 const sp<InputChannel>& toChannel) {
3423#if DEBUG_FOCUS
3424 LOGD("transferTouchFocus: fromChannel=%s, toChannel=%s",
3425 fromChannel->getName().string(), toChannel->getName().string());
3426#endif
3427 { // acquire lock
3428 AutoMutex _l(mLock);
3429
Jeff Brown9302c872011-07-13 22:51:29 -07003430 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromChannel);
3431 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toChannel);
3432 if (fromWindowHandle == NULL || toWindowHandle == NULL) {
Jeff Browne6504122010-09-27 14:52:15 -07003433#if DEBUG_FOCUS
3434 LOGD("Cannot transfer focus because from or to window not found.");
3435#endif
3436 return false;
3437 }
Jeff Brown9302c872011-07-13 22:51:29 -07003438 if (fromWindowHandle == toWindowHandle) {
Jeff Browne6504122010-09-27 14:52:15 -07003439#if DEBUG_FOCUS
3440 LOGD("Trivial transfer to same window.");
3441#endif
3442 return true;
3443 }
3444
3445 bool found = false;
3446 for (size_t i = 0; i < mTouchState.windows.size(); i++) {
3447 const TouchedWindow& touchedWindow = mTouchState.windows[i];
Jeff Brown9302c872011-07-13 22:51:29 -07003448 if (touchedWindow.windowHandle == fromWindowHandle) {
Jeff Browne6504122010-09-27 14:52:15 -07003449 int32_t oldTargetFlags = touchedWindow.targetFlags;
3450 BitSet32 pointerIds = touchedWindow.pointerIds;
3451
3452 mTouchState.windows.removeAt(i);
3453
Jeff Brown46e75292010-11-10 16:53:45 -08003454 int32_t newTargetFlags = oldTargetFlags
Jeff Browna032cc02011-03-07 16:56:21 -08003455 & (InputTarget::FLAG_FOREGROUND
3456 | InputTarget::FLAG_SPLIT | InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brown9302c872011-07-13 22:51:29 -07003457 mTouchState.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Jeff Browne6504122010-09-27 14:52:15 -07003458
3459 found = true;
3460 break;
3461 }
3462 }
3463
3464 if (! found) {
3465#if DEBUG_FOCUS
3466 LOGD("Focus transfer failed because from window did not have focus.");
3467#endif
3468 return false;
3469 }
3470
Jeff Brown9c9f1a32010-10-11 18:32:20 -07003471 ssize_t fromConnectionIndex = getConnectionIndexLocked(fromChannel);
3472 ssize_t toConnectionIndex = getConnectionIndexLocked(toChannel);
3473 if (fromConnectionIndex >= 0 && toConnectionIndex >= 0) {
3474 sp<Connection> fromConnection = mConnectionsByReceiveFd.valueAt(fromConnectionIndex);
3475 sp<Connection> toConnection = mConnectionsByReceiveFd.valueAt(toConnectionIndex);
3476
3477 fromConnection->inputState.copyPointerStateTo(toConnection->inputState);
Jeff Brownda3d5a92011-03-29 15:11:34 -07003478 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Jeff Brown9c9f1a32010-10-11 18:32:20 -07003479 "transferring touch focus from this window to another window");
Jeff Brownda3d5a92011-03-29 15:11:34 -07003480 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Jeff Brown9c9f1a32010-10-11 18:32:20 -07003481 }
3482
Jeff Browne6504122010-09-27 14:52:15 -07003483#if DEBUG_FOCUS
3484 logDispatchStateLocked();
3485#endif
3486 } // release lock
3487
3488 // Wake up poll loop since it may need to make new input dispatching choices.
3489 mLooper->wake();
3490 return true;
3491}
3492
Jeff Brown120a4592010-10-27 18:43:51 -07003493void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
3494#if DEBUG_FOCUS
3495 LOGD("Resetting and dropping all events (%s).", reason);
3496#endif
3497
Jeff Brownda3d5a92011-03-29 15:11:34 -07003498 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
3499 synthesizeCancelationEventsForAllConnectionsLocked(options);
Jeff Brown120a4592010-10-27 18:43:51 -07003500
3501 resetKeyRepeatLocked();
3502 releasePendingEventLocked();
3503 drainInboundQueueLocked();
3504 resetTargetsLocked();
3505
3506 mTouchState.reset();
Jeff Brown9302c872011-07-13 22:51:29 -07003507 mLastHoverWindowHandle.clear();
Jeff Brown120a4592010-10-27 18:43:51 -07003508}
3509
Jeff Brownb88102f2010-09-08 11:49:43 -07003510void InputDispatcher::logDispatchStateLocked() {
3511 String8 dump;
3512 dumpDispatchStateLocked(dump);
Jeff Brown2a95c2a2010-09-16 12:31:46 -07003513
3514 char* text = dump.lockBuffer(dump.size());
3515 char* start = text;
3516 while (*start != '\0') {
3517 char* end = strchr(start, '\n');
3518 if (*end == '\n') {
3519 *(end++) = '\0';
3520 }
3521 LOGD("%s", start);
3522 start = end;
3523 }
Jeff Brownb88102f2010-09-08 11:49:43 -07003524}
3525
3526void InputDispatcher::dumpDispatchStateLocked(String8& dump) {
Jeff Brownf2f48712010-10-01 17:46:21 -07003527 dump.appendFormat(INDENT "DispatchEnabled: %d\n", mDispatchEnabled);
3528 dump.appendFormat(INDENT "DispatchFrozen: %d\n", mDispatchFrozen);
Jeff Brownb88102f2010-09-08 11:49:43 -07003529
Jeff Brown9302c872011-07-13 22:51:29 -07003530 if (mFocusedApplicationHandle != NULL) {
Jeff Brownf2f48712010-10-01 17:46:21 -07003531 dump.appendFormat(INDENT "FocusedApplication: name='%s', dispatchingTimeout=%0.3fms\n",
Jeff Browncc4f7db2011-08-30 20:34:48 -07003532 mFocusedApplicationHandle->getName().string(),
3533 mFocusedApplicationHandle->getDispatchingTimeout(
3534 DEFAULT_INPUT_DISPATCHING_TIMEOUT) / 1000000.0);
Jeff Brownb88102f2010-09-08 11:49:43 -07003535 } else {
Jeff Brownf2f48712010-10-01 17:46:21 -07003536 dump.append(INDENT "FocusedApplication: <null>\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003537 }
Jeff Brownf2f48712010-10-01 17:46:21 -07003538 dump.appendFormat(INDENT "FocusedWindow: name='%s'\n",
Jeff Browncc4f7db2011-08-30 20:34:48 -07003539 mFocusedWindowHandle != NULL ? mFocusedWindowHandle->getName().string() : "<null>");
Jeff Brownf2f48712010-10-01 17:46:21 -07003540
3541 dump.appendFormat(INDENT "TouchDown: %s\n", toString(mTouchState.down));
3542 dump.appendFormat(INDENT "TouchSplit: %s\n", toString(mTouchState.split));
Jeff Brown95712852011-01-04 19:41:59 -08003543 dump.appendFormat(INDENT "TouchDeviceId: %d\n", mTouchState.deviceId);
Jeff Brown58a2da82011-01-25 16:02:22 -08003544 dump.appendFormat(INDENT "TouchSource: 0x%08x\n", mTouchState.source);
Jeff Brownf2f48712010-10-01 17:46:21 -07003545 if (!mTouchState.windows.isEmpty()) {
3546 dump.append(INDENT "TouchedWindows:\n");
3547 for (size_t i = 0; i < mTouchState.windows.size(); i++) {
3548 const TouchedWindow& touchedWindow = mTouchState.windows[i];
3549 dump.appendFormat(INDENT2 "%d: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
Jeff Browncc4f7db2011-08-30 20:34:48 -07003550 i, touchedWindow.windowHandle->getName().string(),
3551 touchedWindow.pointerIds.value,
Jeff Brownf2f48712010-10-01 17:46:21 -07003552 touchedWindow.targetFlags);
3553 }
3554 } else {
3555 dump.append(INDENT "TouchedWindows: <none>\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003556 }
3557
Jeff Brown9302c872011-07-13 22:51:29 -07003558 if (!mWindowHandles.isEmpty()) {
Jeff Brownf2f48712010-10-01 17:46:21 -07003559 dump.append(INDENT "Windows:\n");
Jeff Brown9302c872011-07-13 22:51:29 -07003560 for (size_t i = 0; i < mWindowHandles.size(); i++) {
3561 const sp<InputWindowHandle>& windowHandle = mWindowHandles.itemAt(i);
Jeff Browncc4f7db2011-08-30 20:34:48 -07003562 const InputWindowInfo* windowInfo = windowHandle->getInfo();
3563
Jeff Brownf2f48712010-10-01 17:46:21 -07003564 dump.appendFormat(INDENT2 "%d: name='%s', paused=%s, hasFocus=%s, hasWallpaper=%s, "
3565 "visible=%s, canReceiveKeys=%s, flags=0x%08x, type=0x%08x, layer=%d, "
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003566 "frame=[%d,%d][%d,%d], scale=%f, "
Jeff Brownfbf09772011-01-16 14:06:57 -08003567 "touchableRegion=",
Jeff Browncc4f7db2011-08-30 20:34:48 -07003568 i, windowInfo->name.string(),
3569 toString(windowInfo->paused),
3570 toString(windowInfo->hasFocus),
3571 toString(windowInfo->hasWallpaper),
3572 toString(windowInfo->visible),
3573 toString(windowInfo->canReceiveKeys),
3574 windowInfo->layoutParamsFlags, windowInfo->layoutParamsType,
3575 windowInfo->layer,
3576 windowInfo->frameLeft, windowInfo->frameTop,
3577 windowInfo->frameRight, windowInfo->frameBottom,
3578 windowInfo->scaleFactor);
3579 dumpRegion(dump, windowInfo->touchableRegion);
3580 dump.appendFormat(", inputFeatures=0x%08x", windowInfo->inputFeatures);
Jeff Brownfbf09772011-01-16 14:06:57 -08003581 dump.appendFormat(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%0.3fms\n",
Jeff Browncc4f7db2011-08-30 20:34:48 -07003582 windowInfo->ownerPid, windowInfo->ownerUid,
3583 windowInfo->dispatchingTimeout / 1000000.0);
Jeff Brownf2f48712010-10-01 17:46:21 -07003584 }
3585 } else {
3586 dump.append(INDENT "Windows: <none>\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003587 }
3588
Jeff Brownf2f48712010-10-01 17:46:21 -07003589 if (!mMonitoringChannels.isEmpty()) {
3590 dump.append(INDENT "MonitoringChannels:\n");
3591 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
3592 const sp<InputChannel>& channel = mMonitoringChannels[i];
3593 dump.appendFormat(INDENT2 "%d: '%s'\n", i, channel->getName().string());
3594 }
3595 } else {
3596 dump.append(INDENT "MonitoringChannels: <none>\n");
3597 }
Jeff Brown519e0242010-09-15 15:18:56 -07003598
Jeff Brownf2f48712010-10-01 17:46:21 -07003599 dump.appendFormat(INDENT "InboundQueue: length=%u\n", mInboundQueue.count());
3600
3601 if (!mActiveConnections.isEmpty()) {
3602 dump.append(INDENT "ActiveConnections:\n");
3603 for (size_t i = 0; i < mActiveConnections.size(); i++) {
3604 const Connection* connection = mActiveConnections[i];
Jeff Brown76860e32010-10-25 17:37:46 -07003605 dump.appendFormat(INDENT2 "%d: '%s', status=%s, outboundQueueLength=%u, "
Jeff Brownb6997262010-10-08 22:31:17 -07003606 "inputState.isNeutral=%s\n",
Jeff Brownf2f48712010-10-01 17:46:21 -07003607 i, connection->getInputChannelName(), connection->getStatusLabel(),
3608 connection->outboundQueue.count(),
Jeff Brownb6997262010-10-08 22:31:17 -07003609 toString(connection->inputState.isNeutral()));
Jeff Brownf2f48712010-10-01 17:46:21 -07003610 }
3611 } else {
3612 dump.append(INDENT "ActiveConnections: <none>\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003613 }
3614
3615 if (isAppSwitchPendingLocked()) {
Jeff Brownf2f48712010-10-01 17:46:21 -07003616 dump.appendFormat(INDENT "AppSwitch: pending, due in %01.1fms\n",
Jeff Brownb88102f2010-09-08 11:49:43 -07003617 (mAppSwitchDueTime - now()) / 1000000.0);
3618 } else {
Jeff Brownf2f48712010-10-01 17:46:21 -07003619 dump.append(INDENT "AppSwitch: not pending\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003620 }
3621}
3622
Jeff Brown928e0542011-01-10 11:17:36 -08003623status_t InputDispatcher::registerInputChannel(const sp<InputChannel>& inputChannel,
3624 const sp<InputWindowHandle>& inputWindowHandle, bool monitor) {
Jeff Brown9c3cda02010-06-15 01:31:58 -07003625#if DEBUG_REGISTRATION
Jeff Brownb88102f2010-09-08 11:49:43 -07003626 LOGD("channel '%s' ~ registerInputChannel - monitor=%s", inputChannel->getName().string(),
3627 toString(monitor));
Jeff Brown9c3cda02010-06-15 01:31:58 -07003628#endif
3629
Jeff Brown46b9ac02010-04-22 18:58:52 -07003630 { // acquire lock
3631 AutoMutex _l(mLock);
3632
Jeff Brown519e0242010-09-15 15:18:56 -07003633 if (getConnectionIndexLocked(inputChannel) >= 0) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07003634 LOGW("Attempted to register already registered input channel '%s'",
3635 inputChannel->getName().string());
3636 return BAD_VALUE;
3637 }
3638
Jeff Browncc4f7db2011-08-30 20:34:48 -07003639 sp<Connection> connection = new Connection(inputChannel, inputWindowHandle, monitor);
Jeff Brown46b9ac02010-04-22 18:58:52 -07003640 status_t status = connection->initialize();
3641 if (status) {
3642 LOGE("Failed to initialize input publisher for input channel '%s', status=%d",
3643 inputChannel->getName().string(), status);
3644 return status;
3645 }
3646
Jeff Brown2cbecea2010-08-17 15:59:26 -07003647 int32_t receiveFd = inputChannel->getReceivePipeFd();
Jeff Brown46b9ac02010-04-22 18:58:52 -07003648 mConnectionsByReceiveFd.add(receiveFd, connection);
Jeff Brown9c3cda02010-06-15 01:31:58 -07003649
Jeff Brownb88102f2010-09-08 11:49:43 -07003650 if (monitor) {
3651 mMonitoringChannels.push(inputChannel);
3652 }
3653
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07003654 mLooper->addFd(receiveFd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
Jeff Brown2cbecea2010-08-17 15:59:26 -07003655
Jeff Brown9c3cda02010-06-15 01:31:58 -07003656 runCommandsLockedInterruptible();
Jeff Brown46b9ac02010-04-22 18:58:52 -07003657 } // release lock
Jeff Brown46b9ac02010-04-22 18:58:52 -07003658 return OK;
3659}
3660
3661status_t InputDispatcher::unregisterInputChannel(const sp<InputChannel>& inputChannel) {
Jeff Brown9c3cda02010-06-15 01:31:58 -07003662#if DEBUG_REGISTRATION
Jeff Brown349703e2010-06-22 01:27:15 -07003663 LOGD("channel '%s' ~ unregisterInputChannel", inputChannel->getName().string());
Jeff Brown9c3cda02010-06-15 01:31:58 -07003664#endif
3665
Jeff Brown46b9ac02010-04-22 18:58:52 -07003666 { // acquire lock
3667 AutoMutex _l(mLock);
3668
Jeff Browncc4f7db2011-08-30 20:34:48 -07003669 status_t status = unregisterInputChannelLocked(inputChannel, false /*notify*/);
3670 if (status) {
3671 return status;
Jeff Brown46b9ac02010-04-22 18:58:52 -07003672 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07003673 } // release lock
3674
Jeff Brown46b9ac02010-04-22 18:58:52 -07003675 // Wake the poll loop because removing the connection may have changed the current
3676 // synchronization state.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07003677 mLooper->wake();
Jeff Brown46b9ac02010-04-22 18:58:52 -07003678 return OK;
3679}
3680
Jeff Browncc4f7db2011-08-30 20:34:48 -07003681status_t InputDispatcher::unregisterInputChannelLocked(const sp<InputChannel>& inputChannel,
3682 bool notify) {
3683 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
3684 if (connectionIndex < 0) {
3685 LOGW("Attempted to unregister already unregistered input channel '%s'",
3686 inputChannel->getName().string());
3687 return BAD_VALUE;
3688 }
3689
3690 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
3691 mConnectionsByReceiveFd.removeItemsAt(connectionIndex);
3692
3693 if (connection->monitor) {
3694 removeMonitorChannelLocked(inputChannel);
3695 }
3696
3697 mLooper->removeFd(inputChannel->getReceivePipeFd());
3698
3699 nsecs_t currentTime = now();
3700 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
3701
3702 runCommandsLockedInterruptible();
3703
3704 connection->status = Connection::STATUS_ZOMBIE;
3705 return OK;
3706}
3707
3708void InputDispatcher::removeMonitorChannelLocked(const sp<InputChannel>& inputChannel) {
3709 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
3710 if (mMonitoringChannels[i] == inputChannel) {
3711 mMonitoringChannels.removeAt(i);
3712 break;
3713 }
3714 }
3715}
3716
Jeff Brown519e0242010-09-15 15:18:56 -07003717ssize_t InputDispatcher::getConnectionIndexLocked(const sp<InputChannel>& inputChannel) {
Jeff Brown2cbecea2010-08-17 15:59:26 -07003718 ssize_t connectionIndex = mConnectionsByReceiveFd.indexOfKey(inputChannel->getReceivePipeFd());
3719 if (connectionIndex >= 0) {
3720 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
3721 if (connection->inputChannel.get() == inputChannel.get()) {
3722 return connectionIndex;
3723 }
3724 }
3725
3726 return -1;
3727}
3728
Jeff Brown46b9ac02010-04-22 18:58:52 -07003729void InputDispatcher::activateConnectionLocked(Connection* connection) {
3730 for (size_t i = 0; i < mActiveConnections.size(); i++) {
3731 if (mActiveConnections.itemAt(i) == connection) {
3732 return;
3733 }
3734 }
3735 mActiveConnections.add(connection);
3736}
3737
3738void InputDispatcher::deactivateConnectionLocked(Connection* connection) {
3739 for (size_t i = 0; i < mActiveConnections.size(); i++) {
3740 if (mActiveConnections.itemAt(i) == connection) {
3741 mActiveConnections.removeAt(i);
3742 return;
3743 }
3744 }
3745}
3746
Jeff Brown9c3cda02010-06-15 01:31:58 -07003747void InputDispatcher::onDispatchCycleStartedLocked(
Jeff Brown7fbdc842010-06-17 20:52:56 -07003748 nsecs_t currentTime, const sp<Connection>& connection) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07003749}
3750
Jeff Brown9c3cda02010-06-15 01:31:58 -07003751void InputDispatcher::onDispatchCycleFinishedLocked(
Jeff Brown3915bb82010-11-05 15:02:16 -07003752 nsecs_t currentTime, const sp<Connection>& connection, bool handled) {
3753 CommandEntry* commandEntry = postCommandLocked(
3754 & InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
3755 commandEntry->connection = connection;
3756 commandEntry->handled = handled;
Jeff Brown46b9ac02010-04-22 18:58:52 -07003757}
3758
Jeff Brown9c3cda02010-06-15 01:31:58 -07003759void InputDispatcher::onDispatchCycleBrokenLocked(
Jeff Brown7fbdc842010-06-17 20:52:56 -07003760 nsecs_t currentTime, const sp<Connection>& connection) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07003761 LOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
3762 connection->getInputChannelName());
3763
Jeff Brown9c3cda02010-06-15 01:31:58 -07003764 CommandEntry* commandEntry = postCommandLocked(
3765 & InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
Jeff Brown7fbdc842010-06-17 20:52:56 -07003766 commandEntry->connection = connection;
Jeff Brown46b9ac02010-04-22 18:58:52 -07003767}
3768
Jeff Brown519e0242010-09-15 15:18:56 -07003769void InputDispatcher::onANRLocked(
Jeff Brown9302c872011-07-13 22:51:29 -07003770 nsecs_t currentTime, const sp<InputApplicationHandle>& applicationHandle,
3771 const sp<InputWindowHandle>& windowHandle,
Jeff Brown519e0242010-09-15 15:18:56 -07003772 nsecs_t eventTime, nsecs_t waitStartTime) {
3773 LOGI("Application is not responding: %s. "
3774 "%01.1fms since event, %01.1fms since wait started",
Jeff Brown9302c872011-07-13 22:51:29 -07003775 getApplicationWindowLabelLocked(applicationHandle, windowHandle).string(),
Jeff Brown519e0242010-09-15 15:18:56 -07003776 (currentTime - eventTime) / 1000000.0,
3777 (currentTime - waitStartTime) / 1000000.0);
3778
3779 CommandEntry* commandEntry = postCommandLocked(
3780 & InputDispatcher::doNotifyANRLockedInterruptible);
Jeff Brown9302c872011-07-13 22:51:29 -07003781 commandEntry->inputApplicationHandle = applicationHandle;
3782 commandEntry->inputWindowHandle = windowHandle;
Jeff Brown519e0242010-09-15 15:18:56 -07003783}
3784
Jeff Brownb88102f2010-09-08 11:49:43 -07003785void InputDispatcher::doNotifyConfigurationChangedInterruptible(
3786 CommandEntry* commandEntry) {
3787 mLock.unlock();
3788
3789 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
3790
3791 mLock.lock();
3792}
3793
Jeff Brown9c3cda02010-06-15 01:31:58 -07003794void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(
3795 CommandEntry* commandEntry) {
Jeff Brown7fbdc842010-06-17 20:52:56 -07003796 sp<Connection> connection = commandEntry->connection;
Jeff Brown9c3cda02010-06-15 01:31:58 -07003797
Jeff Brown7fbdc842010-06-17 20:52:56 -07003798 if (connection->status != Connection::STATUS_ZOMBIE) {
3799 mLock.unlock();
Jeff Brown9c3cda02010-06-15 01:31:58 -07003800
Jeff Brown928e0542011-01-10 11:17:36 -08003801 mPolicy->notifyInputChannelBroken(connection->inputWindowHandle);
Jeff Brown7fbdc842010-06-17 20:52:56 -07003802
3803 mLock.lock();
3804 }
Jeff Brown9c3cda02010-06-15 01:31:58 -07003805}
3806
Jeff Brown519e0242010-09-15 15:18:56 -07003807void InputDispatcher::doNotifyANRLockedInterruptible(
Jeff Brown9c3cda02010-06-15 01:31:58 -07003808 CommandEntry* commandEntry) {
Jeff Brown519e0242010-09-15 15:18:56 -07003809 mLock.unlock();
Jeff Brown9c3cda02010-06-15 01:31:58 -07003810
Jeff Brown519e0242010-09-15 15:18:56 -07003811 nsecs_t newTimeout = mPolicy->notifyANR(
Jeff Brown928e0542011-01-10 11:17:36 -08003812 commandEntry->inputApplicationHandle, commandEntry->inputWindowHandle);
Jeff Brown9c3cda02010-06-15 01:31:58 -07003813
Jeff Brown519e0242010-09-15 15:18:56 -07003814 mLock.lock();
Jeff Brown7fbdc842010-06-17 20:52:56 -07003815
Jeff Brown9302c872011-07-13 22:51:29 -07003816 resumeAfterTargetsNotReadyTimeoutLocked(newTimeout,
3817 commandEntry->inputWindowHandle != NULL
Jeff Browncc4f7db2011-08-30 20:34:48 -07003818 ? commandEntry->inputWindowHandle->getInputChannel() : NULL);
Jeff Brown9c3cda02010-06-15 01:31:58 -07003819}
3820
Jeff Brownb88102f2010-09-08 11:49:43 -07003821void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
3822 CommandEntry* commandEntry) {
3823 KeyEntry* entry = commandEntry->keyEntry;
Jeff Brown1f245102010-11-18 20:53:46 -08003824
3825 KeyEvent event;
3826 initializeKeyEvent(&event, entry);
Jeff Brownb88102f2010-09-08 11:49:43 -07003827
3828 mLock.unlock();
3829
Jeff Brown928e0542011-01-10 11:17:36 -08003830 bool consumed = mPolicy->interceptKeyBeforeDispatching(commandEntry->inputWindowHandle,
Jeff Brown1f245102010-11-18 20:53:46 -08003831 &event, entry->policyFlags);
Jeff Brownb88102f2010-09-08 11:49:43 -07003832
3833 mLock.lock();
3834
3835 entry->interceptKeyResult = consumed
3836 ? KeyEntry::INTERCEPT_KEY_RESULT_SKIP
3837 : KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
Jeff Brownac386072011-07-20 15:19:50 -07003838 entry->release();
Jeff Brownb88102f2010-09-08 11:49:43 -07003839}
3840
Jeff Brown3915bb82010-11-05 15:02:16 -07003841void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(
3842 CommandEntry* commandEntry) {
3843 sp<Connection> connection = commandEntry->connection;
3844 bool handled = commandEntry->handled;
3845
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003846 bool skipNext = false;
Jeff Brown49ed71d2010-12-06 17:13:33 -08003847 if (!connection->outboundQueue.isEmpty()) {
Jeff Brownac386072011-07-20 15:19:50 -07003848 DispatchEntry* dispatchEntry = connection->outboundQueue.head;
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003849 if (dispatchEntry->inProgress) {
3850 if (dispatchEntry->eventEntry->type == EventEntry::TYPE_KEY) {
3851 KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry);
3852 skipNext = afterKeyEventLockedInterruptible(connection,
3853 dispatchEntry, keyEntry, handled);
3854 } else if (dispatchEntry->eventEntry->type == EventEntry::TYPE_MOTION) {
3855 MotionEntry* motionEntry = static_cast<MotionEntry*>(dispatchEntry->eventEntry);
3856 skipNext = afterMotionEventLockedInterruptible(connection,
3857 dispatchEntry, motionEntry, handled);
Jeff Brown49ed71d2010-12-06 17:13:33 -08003858 }
Jeff Brown3915bb82010-11-05 15:02:16 -07003859 }
3860 }
3861
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003862 if (!skipNext) {
3863 startNextDispatchCycleLocked(now(), connection);
3864 }
3865}
3866
3867bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
3868 DispatchEntry* dispatchEntry, KeyEntry* keyEntry, bool handled) {
3869 if (!(keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK)) {
3870 // Get the fallback key state.
3871 // Clear it out after dispatching the UP.
3872 int32_t originalKeyCode = keyEntry->keyCode;
3873 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
3874 if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
3875 connection->inputState.removeFallbackKey(originalKeyCode);
3876 }
3877
3878 if (handled || !dispatchEntry->hasForegroundTarget()) {
3879 // If the application handles the original key for which we previously
3880 // generated a fallback or if the window is not a foreground window,
3881 // then cancel the associated fallback key, if any.
3882 if (fallbackKeyCode != -1) {
3883 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
3884 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
3885 "application handled the original non-fallback key "
3886 "or is no longer a foreground target, "
3887 "canceling previously dispatched fallback key");
3888 options.keyCode = fallbackKeyCode;
3889 synthesizeCancelationEventsForConnectionLocked(connection, options);
3890 }
3891 connection->inputState.removeFallbackKey(originalKeyCode);
3892 }
3893 } else {
3894 // If the application did not handle a non-fallback key, first check
3895 // that we are in a good state to perform unhandled key event processing
3896 // Then ask the policy what to do with it.
3897 bool initialDown = keyEntry->action == AKEY_EVENT_ACTION_DOWN
3898 && keyEntry->repeatCount == 0;
3899 if (fallbackKeyCode == -1 && !initialDown) {
3900#if DEBUG_OUTBOUND_EVENT_DETAILS
3901 LOGD("Unhandled key event: Skipping unhandled key event processing "
3902 "since this is not an initial down. "
3903 "keyCode=%d, action=%d, repeatCount=%d",
3904 originalKeyCode, keyEntry->action, keyEntry->repeatCount);
3905#endif
3906 return false;
3907 }
3908
3909 // Dispatch the unhandled key to the policy.
3910#if DEBUG_OUTBOUND_EVENT_DETAILS
3911 LOGD("Unhandled key event: Asking policy to perform fallback action. "
3912 "keyCode=%d, action=%d, repeatCount=%d",
3913 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount);
3914#endif
3915 KeyEvent event;
3916 initializeKeyEvent(&event, keyEntry);
3917
3918 mLock.unlock();
3919
3920 bool fallback = mPolicy->dispatchUnhandledKey(connection->inputWindowHandle,
3921 &event, keyEntry->policyFlags, &event);
3922
3923 mLock.lock();
3924
3925 if (connection->status != Connection::STATUS_NORMAL) {
3926 connection->inputState.removeFallbackKey(originalKeyCode);
3927 return true; // skip next cycle
3928 }
3929
Jeff Brownac386072011-07-20 15:19:50 -07003930 LOG_ASSERT(connection->outboundQueue.head == dispatchEntry);
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003931
3932 // Latch the fallback keycode for this key on an initial down.
3933 // The fallback keycode cannot change at any other point in the lifecycle.
3934 if (initialDown) {
3935 if (fallback) {
3936 fallbackKeyCode = event.getKeyCode();
3937 } else {
3938 fallbackKeyCode = AKEYCODE_UNKNOWN;
3939 }
3940 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
3941 }
3942
3943 LOG_ASSERT(fallbackKeyCode != -1);
3944
3945 // Cancel the fallback key if the policy decides not to send it anymore.
3946 // We will continue to dispatch the key to the policy but we will no
3947 // longer dispatch a fallback key to the application.
3948 if (fallbackKeyCode != AKEYCODE_UNKNOWN
3949 && (!fallback || fallbackKeyCode != event.getKeyCode())) {
3950#if DEBUG_OUTBOUND_EVENT_DETAILS
3951 if (fallback) {
3952 LOGD("Unhandled key event: Policy requested to send key %d"
3953 "as a fallback for %d, but on the DOWN it had requested "
3954 "to send %d instead. Fallback canceled.",
3955 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
3956 } else {
3957 LOGD("Unhandled key event: Policy did not request fallback for %d,"
3958 "but on the DOWN it had requested to send %d. "
3959 "Fallback canceled.",
3960 originalKeyCode, fallbackKeyCode);
3961 }
3962#endif
3963
3964 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
3965 "canceling fallback, policy no longer desires it");
3966 options.keyCode = fallbackKeyCode;
3967 synthesizeCancelationEventsForConnectionLocked(connection, options);
3968
3969 fallback = false;
3970 fallbackKeyCode = AKEYCODE_UNKNOWN;
3971 if (keyEntry->action != AKEY_EVENT_ACTION_UP) {
3972 connection->inputState.setFallbackKey(originalKeyCode,
3973 fallbackKeyCode);
3974 }
3975 }
3976
3977#if DEBUG_OUTBOUND_EVENT_DETAILS
3978 {
3979 String8 msg;
3980 const KeyedVector<int32_t, int32_t>& fallbackKeys =
3981 connection->inputState.getFallbackKeys();
3982 for (size_t i = 0; i < fallbackKeys.size(); i++) {
3983 msg.appendFormat(", %d->%d", fallbackKeys.keyAt(i),
3984 fallbackKeys.valueAt(i));
3985 }
3986 LOGD("Unhandled key event: %d currently tracked fallback keys%s.",
3987 fallbackKeys.size(), msg.string());
3988 }
3989#endif
3990
3991 if (fallback) {
3992 // Restart the dispatch cycle using the fallback key.
3993 keyEntry->eventTime = event.getEventTime();
3994 keyEntry->deviceId = event.getDeviceId();
3995 keyEntry->source = event.getSource();
3996 keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
3997 keyEntry->keyCode = fallbackKeyCode;
3998 keyEntry->scanCode = event.getScanCode();
3999 keyEntry->metaState = event.getMetaState();
4000 keyEntry->repeatCount = event.getRepeatCount();
4001 keyEntry->downTime = event.getDownTime();
4002 keyEntry->syntheticRepeat = false;
4003
4004#if DEBUG_OUTBOUND_EVENT_DETAILS
4005 LOGD("Unhandled key event: Dispatching fallback key. "
4006 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
4007 originalKeyCode, fallbackKeyCode, keyEntry->metaState);
4008#endif
4009
4010 dispatchEntry->inProgress = false;
4011 startDispatchCycleLocked(now(), connection);
4012 return true; // already started next cycle
4013 } else {
4014#if DEBUG_OUTBOUND_EVENT_DETAILS
4015 LOGD("Unhandled key event: No fallback key.");
4016#endif
4017 }
4018 }
4019 }
4020 return false;
4021}
4022
4023bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
4024 DispatchEntry* dispatchEntry, MotionEntry* motionEntry, bool handled) {
4025 return false;
Jeff Brown3915bb82010-11-05 15:02:16 -07004026}
4027
Jeff Brownb88102f2010-09-08 11:49:43 -07004028void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
4029 mLock.unlock();
4030
Jeff Brown01ce2e92010-09-26 22:20:12 -07004031 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
Jeff Brownb88102f2010-09-08 11:49:43 -07004032
4033 mLock.lock();
4034}
4035
Jeff Brown3915bb82010-11-05 15:02:16 -07004036void InputDispatcher::initializeKeyEvent(KeyEvent* event, const KeyEntry* entry) {
4037 event->initialize(entry->deviceId, entry->source, entry->action, entry->flags,
4038 entry->keyCode, entry->scanCode, entry->metaState, entry->repeatCount,
4039 entry->downTime, entry->eventTime);
4040}
4041
Jeff Brown519e0242010-09-15 15:18:56 -07004042void InputDispatcher::updateDispatchStatisticsLocked(nsecs_t currentTime, const EventEntry* entry,
4043 int32_t injectionResult, nsecs_t timeSpentWaitingForApplication) {
4044 // TODO Write some statistics about how long we spend waiting.
Jeff Brownb88102f2010-09-08 11:49:43 -07004045}
4046
4047void InputDispatcher::dump(String8& dump) {
Jeff Brown89ef0722011-08-10 16:25:21 -07004048 AutoMutex _l(mLock);
4049
Jeff Brownf2f48712010-10-01 17:46:21 -07004050 dump.append("Input Dispatcher State:\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07004051 dumpDispatchStateLocked(dump);
Jeff Brown214eaf42011-05-26 19:17:02 -07004052
4053 dump.append(INDENT "Configuration:\n");
4054 dump.appendFormat(INDENT2 "MaxEventsPerSecond: %d\n", mConfig.maxEventsPerSecond);
4055 dump.appendFormat(INDENT2 "KeyRepeatDelay: %0.1fms\n", mConfig.keyRepeatDelay * 0.000001f);
4056 dump.appendFormat(INDENT2 "KeyRepeatTimeout: %0.1fms\n", mConfig.keyRepeatTimeout * 0.000001f);
Jeff Brownb88102f2010-09-08 11:49:43 -07004057}
4058
Jeff Brown89ef0722011-08-10 16:25:21 -07004059void InputDispatcher::monitor() {
4060 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
4061 mLock.lock();
4062 mLock.unlock();
4063}
4064
Jeff Brown9c3cda02010-06-15 01:31:58 -07004065
Jeff Brown519e0242010-09-15 15:18:56 -07004066// --- InputDispatcher::Queue ---
4067
4068template <typename T>
4069uint32_t InputDispatcher::Queue<T>::count() const {
4070 uint32_t result = 0;
Jeff Brownac386072011-07-20 15:19:50 -07004071 for (const T* entry = head; entry; entry = entry->next) {
Jeff Brown519e0242010-09-15 15:18:56 -07004072 result += 1;
4073 }
4074 return result;
4075}
4076
4077
Jeff Brownac386072011-07-20 15:19:50 -07004078// --- InputDispatcher::InjectionState ---
Jeff Brown46b9ac02010-04-22 18:58:52 -07004079
Jeff Brownac386072011-07-20 15:19:50 -07004080InputDispatcher::InjectionState::InjectionState(int32_t injectorPid, int32_t injectorUid) :
4081 refCount(1),
4082 injectorPid(injectorPid), injectorUid(injectorUid),
4083 injectionResult(INPUT_EVENT_INJECTION_PENDING), injectionIsAsync(false),
4084 pendingForegroundDispatches(0) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07004085}
4086
Jeff Brownac386072011-07-20 15:19:50 -07004087InputDispatcher::InjectionState::~InjectionState() {
Jeff Brown01ce2e92010-09-26 22:20:12 -07004088}
4089
Jeff Brownac386072011-07-20 15:19:50 -07004090void InputDispatcher::InjectionState::release() {
4091 refCount -= 1;
4092 if (refCount == 0) {
4093 delete this;
4094 } else {
4095 LOG_ASSERT(refCount > 0);
Jeff Brown01ce2e92010-09-26 22:20:12 -07004096 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07004097}
4098
Jeff Brownac386072011-07-20 15:19:50 -07004099
4100// --- InputDispatcher::EventEntry ---
4101
4102InputDispatcher::EventEntry::EventEntry(int32_t type, nsecs_t eventTime, uint32_t policyFlags) :
4103 refCount(1), type(type), eventTime(eventTime), policyFlags(policyFlags),
4104 injectionState(NULL), dispatchInProgress(false) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07004105}
4106
Jeff Brownac386072011-07-20 15:19:50 -07004107InputDispatcher::EventEntry::~EventEntry() {
4108 releaseInjectionState();
4109}
4110
4111void InputDispatcher::EventEntry::release() {
4112 refCount -= 1;
4113 if (refCount == 0) {
4114 delete this;
4115 } else {
4116 LOG_ASSERT(refCount > 0);
4117 }
4118}
4119
4120void InputDispatcher::EventEntry::releaseInjectionState() {
4121 if (injectionState) {
4122 injectionState->release();
4123 injectionState = NULL;
4124 }
4125}
4126
4127
4128// --- InputDispatcher::ConfigurationChangedEntry ---
4129
4130InputDispatcher::ConfigurationChangedEntry::ConfigurationChangedEntry(nsecs_t eventTime) :
4131 EventEntry(TYPE_CONFIGURATION_CHANGED, eventTime, 0) {
4132}
4133
4134InputDispatcher::ConfigurationChangedEntry::~ConfigurationChangedEntry() {
4135}
4136
4137
Jeff Brown65fd2512011-08-18 11:20:58 -07004138// --- InputDispatcher::DeviceResetEntry ---
4139
4140InputDispatcher::DeviceResetEntry::DeviceResetEntry(nsecs_t eventTime, int32_t deviceId) :
4141 EventEntry(TYPE_DEVICE_RESET, eventTime, 0),
4142 deviceId(deviceId) {
4143}
4144
4145InputDispatcher::DeviceResetEntry::~DeviceResetEntry() {
4146}
4147
4148
Jeff Brownac386072011-07-20 15:19:50 -07004149// --- InputDispatcher::KeyEntry ---
4150
4151InputDispatcher::KeyEntry::KeyEntry(nsecs_t eventTime,
Jeff Brown58a2da82011-01-25 16:02:22 -08004152 int32_t deviceId, uint32_t source, uint32_t policyFlags, int32_t action,
Jeff Brown7fbdc842010-06-17 20:52:56 -07004153 int32_t flags, int32_t keyCode, int32_t scanCode, int32_t metaState,
Jeff Brownac386072011-07-20 15:19:50 -07004154 int32_t repeatCount, nsecs_t downTime) :
4155 EventEntry(TYPE_KEY, eventTime, policyFlags),
4156 deviceId(deviceId), source(source), action(action), flags(flags),
4157 keyCode(keyCode), scanCode(scanCode), metaState(metaState),
4158 repeatCount(repeatCount), downTime(downTime),
4159 syntheticRepeat(false), interceptKeyResult(KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07004160}
4161
Jeff Brownac386072011-07-20 15:19:50 -07004162InputDispatcher::KeyEntry::~KeyEntry() {
4163}
Jeff Brown7fbdc842010-06-17 20:52:56 -07004164
Jeff Brownac386072011-07-20 15:19:50 -07004165void InputDispatcher::KeyEntry::recycle() {
4166 releaseInjectionState();
4167
4168 dispatchInProgress = false;
4169 syntheticRepeat = false;
4170 interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
4171}
4172
4173
4174// --- InputDispatcher::MotionSample ---
4175
4176InputDispatcher::MotionSample::MotionSample(nsecs_t eventTime,
4177 const PointerCoords* pointerCoords, uint32_t pointerCount) :
4178 next(NULL), eventTime(eventTime), eventTimeBeforeCoalescing(eventTime) {
Jeff Brown7fbdc842010-06-17 20:52:56 -07004179 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brownac386072011-07-20 15:19:50 -07004180 this->pointerCoords[i].copyFrom(pointerCoords[i]);
Jeff Brown7fbdc842010-06-17 20:52:56 -07004181 }
Jeff Brownb88102f2010-09-08 11:49:43 -07004182}
4183
4184
Jeff Brownae9fc032010-08-18 15:51:08 -07004185// --- InputDispatcher::MotionEntry ---
4186
Jeff Brownac386072011-07-20 15:19:50 -07004187InputDispatcher::MotionEntry::MotionEntry(nsecs_t eventTime,
4188 int32_t deviceId, uint32_t source, uint32_t policyFlags, int32_t action, int32_t flags,
4189 int32_t metaState, int32_t buttonState,
4190 int32_t edgeFlags, float xPrecision, float yPrecision,
4191 nsecs_t downTime, uint32_t pointerCount,
4192 const PointerProperties* pointerProperties, const PointerCoords* pointerCoords) :
4193 EventEntry(TYPE_MOTION, eventTime, policyFlags),
4194 deviceId(deviceId), source(source), action(action), flags(flags),
4195 metaState(metaState), buttonState(buttonState), edgeFlags(edgeFlags),
4196 xPrecision(xPrecision), yPrecision(yPrecision),
4197 downTime(downTime), pointerCount(pointerCount),
4198 firstSample(eventTime, pointerCoords, pointerCount),
4199 lastSample(&firstSample) {
4200 for (uint32_t i = 0; i < pointerCount; i++) {
4201 this->pointerProperties[i].copyFrom(pointerProperties[i]);
4202 }
4203}
4204
4205InputDispatcher::MotionEntry::~MotionEntry() {
4206 for (MotionSample* sample = firstSample.next; sample != NULL; ) {
4207 MotionSample* next = sample->next;
4208 delete sample;
4209 sample = next;
4210 }
4211}
4212
Jeff Brownae9fc032010-08-18 15:51:08 -07004213uint32_t InputDispatcher::MotionEntry::countSamples() const {
4214 uint32_t count = 1;
4215 for (MotionSample* sample = firstSample.next; sample != NULL; sample = sample->next) {
4216 count += 1;
4217 }
4218 return count;
4219}
4220
Jeff Brown4e91a182011-04-07 11:38:09 -07004221bool InputDispatcher::MotionEntry::canAppendSamples(int32_t action, uint32_t pointerCount,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07004222 const PointerProperties* pointerProperties) const {
Jeff Brown4e91a182011-04-07 11:38:09 -07004223 if (this->action != action
4224 || this->pointerCount != pointerCount
4225 || this->isInjected()) {
4226 return false;
4227 }
4228 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07004229 if (this->pointerProperties[i] != pointerProperties[i]) {
Jeff Brown4e91a182011-04-07 11:38:09 -07004230 return false;
4231 }
4232 }
4233 return true;
4234}
4235
Jeff Brownac386072011-07-20 15:19:50 -07004236void InputDispatcher::MotionEntry::appendSample(
4237 nsecs_t eventTime, const PointerCoords* pointerCoords) {
4238 MotionSample* sample = new MotionSample(eventTime, pointerCoords, pointerCount);
4239
4240 lastSample->next = sample;
4241 lastSample = sample;
4242}
4243
4244
4245// --- InputDispatcher::DispatchEntry ---
4246
4247InputDispatcher::DispatchEntry::DispatchEntry(EventEntry* eventEntry,
4248 int32_t targetFlags, float xOffset, float yOffset, float scaleFactor) :
4249 eventEntry(eventEntry), targetFlags(targetFlags),
4250 xOffset(xOffset), yOffset(yOffset), scaleFactor(scaleFactor),
4251 inProgress(false),
4252 resolvedAction(0), resolvedFlags(0),
4253 headMotionSample(NULL), tailMotionSample(NULL) {
4254 eventEntry->refCount += 1;
4255}
4256
4257InputDispatcher::DispatchEntry::~DispatchEntry() {
4258 eventEntry->release();
4259}
4260
Jeff Brownb88102f2010-09-08 11:49:43 -07004261
4262// --- InputDispatcher::InputState ---
4263
Jeff Brownb6997262010-10-08 22:31:17 -07004264InputDispatcher::InputState::InputState() {
Jeff Brownb88102f2010-09-08 11:49:43 -07004265}
4266
4267InputDispatcher::InputState::~InputState() {
4268}
4269
4270bool InputDispatcher::InputState::isNeutral() const {
4271 return mKeyMementos.isEmpty() && mMotionMementos.isEmpty();
4272}
4273
Jeff Brown81346812011-06-28 20:08:48 -07004274bool InputDispatcher::InputState::isHovering(int32_t deviceId, uint32_t source) const {
4275 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4276 const MotionMemento& memento = mMotionMementos.itemAt(i);
4277 if (memento.deviceId == deviceId
4278 && memento.source == source
4279 && memento.hovering) {
4280 return true;
4281 }
4282 }
4283 return false;
4284}
Jeff Brownb88102f2010-09-08 11:49:43 -07004285
Jeff Brown81346812011-06-28 20:08:48 -07004286bool InputDispatcher::InputState::trackKey(const KeyEntry* entry,
4287 int32_t action, int32_t flags) {
4288 switch (action) {
4289 case AKEY_EVENT_ACTION_UP: {
4290 if (entry->flags & AKEY_EVENT_FLAG_FALLBACK) {
4291 for (size_t i = 0; i < mFallbackKeys.size(); ) {
4292 if (mFallbackKeys.valueAt(i) == entry->keyCode) {
4293 mFallbackKeys.removeItemsAt(i);
4294 } else {
4295 i += 1;
4296 }
4297 }
4298 }
4299 ssize_t index = findKeyMemento(entry);
4300 if (index >= 0) {
4301 mKeyMementos.removeAt(index);
4302 return true;
4303 }
4304#if DEBUG_OUTBOUND_EVENT_DETAILS
4305 LOGD("Dropping inconsistent key up event: deviceId=%d, source=%08x, "
4306 "keyCode=%d, scanCode=%d",
4307 entry->deviceId, entry->source, entry->keyCode, entry->scanCode);
4308#endif
4309 return false;
4310 }
4311
4312 case AKEY_EVENT_ACTION_DOWN: {
4313 ssize_t index = findKeyMemento(entry);
4314 if (index >= 0) {
4315 mKeyMementos.removeAt(index);
4316 }
4317 addKeyMemento(entry, flags);
4318 return true;
4319 }
4320
4321 default:
4322 return true;
Jeff Brownb88102f2010-09-08 11:49:43 -07004323 }
4324}
4325
Jeff Brown81346812011-06-28 20:08:48 -07004326bool InputDispatcher::InputState::trackMotion(const MotionEntry* entry,
4327 int32_t action, int32_t flags) {
4328 int32_t actionMasked = action & AMOTION_EVENT_ACTION_MASK;
4329 switch (actionMasked) {
4330 case AMOTION_EVENT_ACTION_UP:
4331 case AMOTION_EVENT_ACTION_CANCEL: {
4332 ssize_t index = findMotionMemento(entry, false /*hovering*/);
4333 if (index >= 0) {
4334 mMotionMementos.removeAt(index);
4335 return true;
Jeff Brownda3d5a92011-03-29 15:11:34 -07004336 }
Jeff Brown81346812011-06-28 20:08:48 -07004337#if DEBUG_OUTBOUND_EVENT_DETAILS
4338 LOGD("Dropping inconsistent motion up or cancel event: deviceId=%d, source=%08x, "
4339 "actionMasked=%d",
4340 entry->deviceId, entry->source, actionMasked);
4341#endif
4342 return false;
Jeff Brownda3d5a92011-03-29 15:11:34 -07004343 }
4344
Jeff Brown81346812011-06-28 20:08:48 -07004345 case AMOTION_EVENT_ACTION_DOWN: {
4346 ssize_t index = findMotionMemento(entry, false /*hovering*/);
4347 if (index >= 0) {
4348 mMotionMementos.removeAt(index);
4349 }
4350 addMotionMemento(entry, flags, false /*hovering*/);
4351 return true;
4352 }
4353
4354 case AMOTION_EVENT_ACTION_POINTER_UP:
4355 case AMOTION_EVENT_ACTION_POINTER_DOWN:
4356 case AMOTION_EVENT_ACTION_MOVE: {
4357 ssize_t index = findMotionMemento(entry, false /*hovering*/);
4358 if (index >= 0) {
4359 MotionMemento& memento = mMotionMementos.editItemAt(index);
4360 memento.setPointers(entry);
4361 return true;
4362 }
Jeff Brown2e45fb62011-06-29 21:19:05 -07004363 if (actionMasked == AMOTION_EVENT_ACTION_MOVE
4364 && (entry->source & (AINPUT_SOURCE_CLASS_JOYSTICK
4365 | AINPUT_SOURCE_CLASS_NAVIGATION))) {
4366 // Joysticks and trackballs can send MOVE events without corresponding DOWN or UP.
4367 return true;
4368 }
Jeff Brown81346812011-06-28 20:08:48 -07004369#if DEBUG_OUTBOUND_EVENT_DETAILS
4370 LOGD("Dropping inconsistent motion pointer up/down or move event: "
4371 "deviceId=%d, source=%08x, actionMasked=%d",
4372 entry->deviceId, entry->source, actionMasked);
4373#endif
4374 return false;
4375 }
4376
4377 case AMOTION_EVENT_ACTION_HOVER_EXIT: {
4378 ssize_t index = findMotionMemento(entry, true /*hovering*/);
4379 if (index >= 0) {
4380 mMotionMementos.removeAt(index);
4381 return true;
4382 }
4383#if DEBUG_OUTBOUND_EVENT_DETAILS
4384 LOGD("Dropping inconsistent motion hover exit event: deviceId=%d, source=%08x",
4385 entry->deviceId, entry->source);
4386#endif
4387 return false;
4388 }
4389
4390 case AMOTION_EVENT_ACTION_HOVER_ENTER:
4391 case AMOTION_EVENT_ACTION_HOVER_MOVE: {
4392 ssize_t index = findMotionMemento(entry, true /*hovering*/);
4393 if (index >= 0) {
4394 mMotionMementos.removeAt(index);
4395 }
4396 addMotionMemento(entry, flags, true /*hovering*/);
4397 return true;
4398 }
4399
4400 default:
4401 return true;
4402 }
4403}
4404
4405ssize_t InputDispatcher::InputState::findKeyMemento(const KeyEntry* entry) const {
Jeff Brownb88102f2010-09-08 11:49:43 -07004406 for (size_t i = 0; i < mKeyMementos.size(); i++) {
Jeff Brown81346812011-06-28 20:08:48 -07004407 const KeyMemento& memento = mKeyMementos.itemAt(i);
Jeff Brownb88102f2010-09-08 11:49:43 -07004408 if (memento.deviceId == entry->deviceId
4409 && memento.source == entry->source
4410 && memento.keyCode == entry->keyCode
4411 && memento.scanCode == entry->scanCode) {
Jeff Brown81346812011-06-28 20:08:48 -07004412 return i;
Jeff Brownb88102f2010-09-08 11:49:43 -07004413 }
4414 }
Jeff Brown81346812011-06-28 20:08:48 -07004415 return -1;
Jeff Brownb88102f2010-09-08 11:49:43 -07004416}
4417
Jeff Brown81346812011-06-28 20:08:48 -07004418ssize_t InputDispatcher::InputState::findMotionMemento(const MotionEntry* entry,
4419 bool hovering) const {
Jeff Brownb88102f2010-09-08 11:49:43 -07004420 for (size_t i = 0; i < mMotionMementos.size(); i++) {
Jeff Brown81346812011-06-28 20:08:48 -07004421 const MotionMemento& memento = mMotionMementos.itemAt(i);
Jeff Brownb88102f2010-09-08 11:49:43 -07004422 if (memento.deviceId == entry->deviceId
Jeff Brown81346812011-06-28 20:08:48 -07004423 && memento.source == entry->source
4424 && memento.hovering == hovering) {
4425 return i;
Jeff Brownb88102f2010-09-08 11:49:43 -07004426 }
4427 }
Jeff Brown81346812011-06-28 20:08:48 -07004428 return -1;
4429}
Jeff Brownb88102f2010-09-08 11:49:43 -07004430
Jeff Brown81346812011-06-28 20:08:48 -07004431void InputDispatcher::InputState::addKeyMemento(const KeyEntry* entry, int32_t flags) {
4432 mKeyMementos.push();
4433 KeyMemento& memento = mKeyMementos.editTop();
4434 memento.deviceId = entry->deviceId;
4435 memento.source = entry->source;
4436 memento.keyCode = entry->keyCode;
4437 memento.scanCode = entry->scanCode;
4438 memento.flags = flags;
4439 memento.downTime = entry->downTime;
4440}
4441
4442void InputDispatcher::InputState::addMotionMemento(const MotionEntry* entry,
4443 int32_t flags, bool hovering) {
4444 mMotionMementos.push();
4445 MotionMemento& memento = mMotionMementos.editTop();
4446 memento.deviceId = entry->deviceId;
4447 memento.source = entry->source;
4448 memento.flags = flags;
4449 memento.xPrecision = entry->xPrecision;
4450 memento.yPrecision = entry->yPrecision;
4451 memento.downTime = entry->downTime;
4452 memento.setPointers(entry);
4453 memento.hovering = hovering;
Jeff Brownb88102f2010-09-08 11:49:43 -07004454}
4455
4456void InputDispatcher::InputState::MotionMemento::setPointers(const MotionEntry* entry) {
4457 pointerCount = entry->pointerCount;
4458 for (uint32_t i = 0; i < entry->pointerCount; i++) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07004459 pointerProperties[i].copyFrom(entry->pointerProperties[i]);
Jeff Brownace13b12011-03-09 17:39:48 -08004460 pointerCoords[i].copyFrom(entry->lastSample->pointerCoords[i]);
Jeff Brownb88102f2010-09-08 11:49:43 -07004461 }
4462}
4463
Jeff Brownb6997262010-10-08 22:31:17 -07004464void InputDispatcher::InputState::synthesizeCancelationEvents(nsecs_t currentTime,
Jeff Brownac386072011-07-20 15:19:50 -07004465 Vector<EventEntry*>& outEvents, const CancelationOptions& options) {
Jeff Brown81346812011-06-28 20:08:48 -07004466 for (size_t i = 0; i < mKeyMementos.size(); i++) {
Jeff Brownb88102f2010-09-08 11:49:43 -07004467 const KeyMemento& memento = mKeyMementos.itemAt(i);
Jeff Brown49ed71d2010-12-06 17:13:33 -08004468 if (shouldCancelKey(memento, options)) {
Jeff Brownac386072011-07-20 15:19:50 -07004469 outEvents.push(new KeyEntry(currentTime,
Jeff Brownb6997262010-10-08 22:31:17 -07004470 memento.deviceId, memento.source, 0,
Jeff Brown49ed71d2010-12-06 17:13:33 -08004471 AKEY_EVENT_ACTION_UP, memento.flags | AKEY_EVENT_FLAG_CANCELED,
Jeff Brownb6997262010-10-08 22:31:17 -07004472 memento.keyCode, memento.scanCode, 0, 0, memento.downTime));
Jeff Brownb6997262010-10-08 22:31:17 -07004473 }
Jeff Brownb88102f2010-09-08 11:49:43 -07004474 }
4475
Jeff Brown81346812011-06-28 20:08:48 -07004476 for (size_t i = 0; i < mMotionMementos.size(); i++) {
Jeff Brownb88102f2010-09-08 11:49:43 -07004477 const MotionMemento& memento = mMotionMementos.itemAt(i);
Jeff Brown49ed71d2010-12-06 17:13:33 -08004478 if (shouldCancelMotion(memento, options)) {
Jeff Brownac386072011-07-20 15:19:50 -07004479 outEvents.push(new MotionEntry(currentTime,
Jeff Brownb6997262010-10-08 22:31:17 -07004480 memento.deviceId, memento.source, 0,
Jeff Browna032cc02011-03-07 16:56:21 -08004481 memento.hovering
4482 ? AMOTION_EVENT_ACTION_HOVER_EXIT
4483 : AMOTION_EVENT_ACTION_CANCEL,
Jeff Brown81346812011-06-28 20:08:48 -07004484 memento.flags, 0, 0, 0,
Jeff Brownb6997262010-10-08 22:31:17 -07004485 memento.xPrecision, memento.yPrecision, memento.downTime,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07004486 memento.pointerCount, memento.pointerProperties, memento.pointerCoords));
Jeff Brownb6997262010-10-08 22:31:17 -07004487 }
Jeff Brownb88102f2010-09-08 11:49:43 -07004488 }
4489}
4490
4491void InputDispatcher::InputState::clear() {
4492 mKeyMementos.clear();
4493 mMotionMementos.clear();
Jeff Brownda3d5a92011-03-29 15:11:34 -07004494 mFallbackKeys.clear();
Jeff Brownb6997262010-10-08 22:31:17 -07004495}
4496
Jeff Brown9c9f1a32010-10-11 18:32:20 -07004497void InputDispatcher::InputState::copyPointerStateTo(InputState& other) const {
4498 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4499 const MotionMemento& memento = mMotionMementos.itemAt(i);
4500 if (memento.source & AINPUT_SOURCE_CLASS_POINTER) {
4501 for (size_t j = 0; j < other.mMotionMementos.size(); ) {
4502 const MotionMemento& otherMemento = other.mMotionMementos.itemAt(j);
4503 if (memento.deviceId == otherMemento.deviceId
4504 && memento.source == otherMemento.source) {
4505 other.mMotionMementos.removeAt(j);
4506 } else {
4507 j += 1;
4508 }
4509 }
4510 other.mMotionMementos.push(memento);
4511 }
4512 }
4513}
4514
Jeff Brownda3d5a92011-03-29 15:11:34 -07004515int32_t InputDispatcher::InputState::getFallbackKey(int32_t originalKeyCode) {
4516 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
4517 return index >= 0 ? mFallbackKeys.valueAt(index) : -1;
4518}
4519
4520void InputDispatcher::InputState::setFallbackKey(int32_t originalKeyCode,
4521 int32_t fallbackKeyCode) {
4522 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
4523 if (index >= 0) {
4524 mFallbackKeys.replaceValueAt(index, fallbackKeyCode);
4525 } else {
4526 mFallbackKeys.add(originalKeyCode, fallbackKeyCode);
4527 }
4528}
4529
4530void InputDispatcher::InputState::removeFallbackKey(int32_t originalKeyCode) {
4531 mFallbackKeys.removeItem(originalKeyCode);
4532}
4533
Jeff Brown49ed71d2010-12-06 17:13:33 -08004534bool InputDispatcher::InputState::shouldCancelKey(const KeyMemento& memento,
Jeff Brownda3d5a92011-03-29 15:11:34 -07004535 const CancelationOptions& options) {
4536 if (options.keyCode != -1 && memento.keyCode != options.keyCode) {
4537 return false;
4538 }
4539
Jeff Brown65fd2512011-08-18 11:20:58 -07004540 if (options.deviceId != -1 && memento.deviceId != options.deviceId) {
4541 return false;
4542 }
4543
Jeff Brownda3d5a92011-03-29 15:11:34 -07004544 switch (options.mode) {
4545 case CancelationOptions::CANCEL_ALL_EVENTS:
4546 case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
Jeff Brownb6997262010-10-08 22:31:17 -07004547 return true;
Jeff Brownda3d5a92011-03-29 15:11:34 -07004548 case CancelationOptions::CANCEL_FALLBACK_EVENTS:
Jeff Brown49ed71d2010-12-06 17:13:33 -08004549 return memento.flags & AKEY_EVENT_FLAG_FALLBACK;
4550 default:
4551 return false;
4552 }
4553}
4554
4555bool InputDispatcher::InputState::shouldCancelMotion(const MotionMemento& memento,
Jeff Brownda3d5a92011-03-29 15:11:34 -07004556 const CancelationOptions& options) {
Jeff Brown65fd2512011-08-18 11:20:58 -07004557 if (options.deviceId != -1 && memento.deviceId != options.deviceId) {
4558 return false;
4559 }
4560
Jeff Brownda3d5a92011-03-29 15:11:34 -07004561 switch (options.mode) {
4562 case CancelationOptions::CANCEL_ALL_EVENTS:
Jeff Brown49ed71d2010-12-06 17:13:33 -08004563 return true;
Jeff Brownda3d5a92011-03-29 15:11:34 -07004564 case CancelationOptions::CANCEL_POINTER_EVENTS:
Jeff Brown49ed71d2010-12-06 17:13:33 -08004565 return memento.source & AINPUT_SOURCE_CLASS_POINTER;
Jeff Brownda3d5a92011-03-29 15:11:34 -07004566 case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
Jeff Brown49ed71d2010-12-06 17:13:33 -08004567 return !(memento.source & AINPUT_SOURCE_CLASS_POINTER);
4568 default:
4569 return false;
Jeff Brownb6997262010-10-08 22:31:17 -07004570 }
Jeff Brownb88102f2010-09-08 11:49:43 -07004571}
4572
4573
Jeff Brown46b9ac02010-04-22 18:58:52 -07004574// --- InputDispatcher::Connection ---
4575
Jeff Brown928e0542011-01-10 11:17:36 -08004576InputDispatcher::Connection::Connection(const sp<InputChannel>& inputChannel,
Jeff Browncc4f7db2011-08-30 20:34:48 -07004577 const sp<InputWindowHandle>& inputWindowHandle, bool monitor) :
Jeff Brown928e0542011-01-10 11:17:36 -08004578 status(STATUS_NORMAL), inputChannel(inputChannel), inputWindowHandle(inputWindowHandle),
Jeff Browncc4f7db2011-08-30 20:34:48 -07004579 monitor(monitor),
Jeff Brown928e0542011-01-10 11:17:36 -08004580 inputPublisher(inputChannel),
Jeff Brownda3d5a92011-03-29 15:11:34 -07004581 lastEventTime(LONG_LONG_MAX), lastDispatchTime(LONG_LONG_MAX) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07004582}
4583
4584InputDispatcher::Connection::~Connection() {
4585}
4586
4587status_t InputDispatcher::Connection::initialize() {
4588 return inputPublisher.initialize();
4589}
4590
Jeff Brown9c3cda02010-06-15 01:31:58 -07004591const char* InputDispatcher::Connection::getStatusLabel() const {
4592 switch (status) {
4593 case STATUS_NORMAL:
4594 return "NORMAL";
4595
4596 case STATUS_BROKEN:
4597 return "BROKEN";
4598
Jeff Brown9c3cda02010-06-15 01:31:58 -07004599 case STATUS_ZOMBIE:
4600 return "ZOMBIE";
4601
4602 default:
4603 return "UNKNOWN";
4604 }
4605}
4606
Jeff Brown46b9ac02010-04-22 18:58:52 -07004607InputDispatcher::DispatchEntry* InputDispatcher::Connection::findQueuedDispatchEntryForEvent(
4608 const EventEntry* eventEntry) const {
Jeff Brownac386072011-07-20 15:19:50 -07004609 for (DispatchEntry* dispatchEntry = outboundQueue.tail; dispatchEntry;
4610 dispatchEntry = dispatchEntry->prev) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07004611 if (dispatchEntry->eventEntry == eventEntry) {
4612 return dispatchEntry;
4613 }
4614 }
4615 return NULL;
4616}
4617
Jeff Brownb88102f2010-09-08 11:49:43 -07004618
Jeff Brown9c3cda02010-06-15 01:31:58 -07004619// --- InputDispatcher::CommandEntry ---
4620
Jeff Brownac386072011-07-20 15:19:50 -07004621InputDispatcher::CommandEntry::CommandEntry(Command command) :
4622 command(command), eventTime(0), keyEntry(NULL), userActivityEventType(0), handled(false) {
Jeff Brown9c3cda02010-06-15 01:31:58 -07004623}
4624
4625InputDispatcher::CommandEntry::~CommandEntry() {
4626}
4627
Jeff Brown46b9ac02010-04-22 18:58:52 -07004628
Jeff Brown01ce2e92010-09-26 22:20:12 -07004629// --- InputDispatcher::TouchState ---
4630
4631InputDispatcher::TouchState::TouchState() :
Jeff Brown58a2da82011-01-25 16:02:22 -08004632 down(false), split(false), deviceId(-1), source(0) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07004633}
4634
4635InputDispatcher::TouchState::~TouchState() {
4636}
4637
4638void InputDispatcher::TouchState::reset() {
4639 down = false;
4640 split = false;
Jeff Brown95712852011-01-04 19:41:59 -08004641 deviceId = -1;
Jeff Brown58a2da82011-01-25 16:02:22 -08004642 source = 0;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004643 windows.clear();
4644}
4645
4646void InputDispatcher::TouchState::copyFrom(const TouchState& other) {
4647 down = other.down;
4648 split = other.split;
Jeff Brown95712852011-01-04 19:41:59 -08004649 deviceId = other.deviceId;
Jeff Brown58a2da82011-01-25 16:02:22 -08004650 source = other.source;
Jeff Brown9302c872011-07-13 22:51:29 -07004651 windows = other.windows;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004652}
4653
Jeff Brown9302c872011-07-13 22:51:29 -07004654void InputDispatcher::TouchState::addOrUpdateWindow(const sp<InputWindowHandle>& windowHandle,
Jeff Brown01ce2e92010-09-26 22:20:12 -07004655 int32_t targetFlags, BitSet32 pointerIds) {
4656 if (targetFlags & InputTarget::FLAG_SPLIT) {
4657 split = true;
4658 }
4659
4660 for (size_t i = 0; i < windows.size(); i++) {
4661 TouchedWindow& touchedWindow = windows.editItemAt(i);
Jeff Brown9302c872011-07-13 22:51:29 -07004662 if (touchedWindow.windowHandle == windowHandle) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07004663 touchedWindow.targetFlags |= targetFlags;
Jeff Brown98db5fa2011-06-08 15:37:10 -07004664 if (targetFlags & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
4665 touchedWindow.targetFlags &= ~InputTarget::FLAG_DISPATCH_AS_IS;
4666 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07004667 touchedWindow.pointerIds.value |= pointerIds.value;
4668 return;
4669 }
4670 }
4671
4672 windows.push();
4673
4674 TouchedWindow& touchedWindow = windows.editTop();
Jeff Brown9302c872011-07-13 22:51:29 -07004675 touchedWindow.windowHandle = windowHandle;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004676 touchedWindow.targetFlags = targetFlags;
4677 touchedWindow.pointerIds = pointerIds;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004678}
4679
Jeff Browna032cc02011-03-07 16:56:21 -08004680void InputDispatcher::TouchState::filterNonAsIsTouchWindows() {
Jeff Brown01ce2e92010-09-26 22:20:12 -07004681 for (size_t i = 0 ; i < windows.size(); ) {
Jeff Browna032cc02011-03-07 16:56:21 -08004682 TouchedWindow& window = windows.editItemAt(i);
Jeff Brown98db5fa2011-06-08 15:37:10 -07004683 if (window.targetFlags & (InputTarget::FLAG_DISPATCH_AS_IS
4684 | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER)) {
Jeff Browna032cc02011-03-07 16:56:21 -08004685 window.targetFlags &= ~InputTarget::FLAG_DISPATCH_MASK;
4686 window.targetFlags |= InputTarget::FLAG_DISPATCH_AS_IS;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004687 i += 1;
Jeff Browna032cc02011-03-07 16:56:21 -08004688 } else {
4689 windows.removeAt(i);
Jeff Brown01ce2e92010-09-26 22:20:12 -07004690 }
4691 }
4692}
4693
Jeff Brown9302c872011-07-13 22:51:29 -07004694sp<InputWindowHandle> InputDispatcher::TouchState::getFirstForegroundWindowHandle() const {
Jeff Brown01ce2e92010-09-26 22:20:12 -07004695 for (size_t i = 0; i < windows.size(); i++) {
Jeff Brown98db5fa2011-06-08 15:37:10 -07004696 const TouchedWindow& window = windows.itemAt(i);
4697 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
Jeff Brown9302c872011-07-13 22:51:29 -07004698 return window.windowHandle;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004699 }
4700 }
4701 return NULL;
4702}
4703
Jeff Brown98db5fa2011-06-08 15:37:10 -07004704bool InputDispatcher::TouchState::isSlippery() const {
4705 // Must have exactly one foreground window.
4706 bool haveSlipperyForegroundWindow = false;
4707 for (size_t i = 0; i < windows.size(); i++) {
4708 const TouchedWindow& window = windows.itemAt(i);
4709 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
Jeff Browncc4f7db2011-08-30 20:34:48 -07004710 if (haveSlipperyForegroundWindow
4711 || !(window.windowHandle->getInfo()->layoutParamsFlags
4712 & InputWindowInfo::FLAG_SLIPPERY)) {
Jeff Brown98db5fa2011-06-08 15:37:10 -07004713 return false;
4714 }
4715 haveSlipperyForegroundWindow = true;
4716 }
4717 }
4718 return haveSlipperyForegroundWindow;
4719}
4720
Jeff Brown01ce2e92010-09-26 22:20:12 -07004721
Jeff Brown46b9ac02010-04-22 18:58:52 -07004722// --- InputDispatcherThread ---
4723
4724InputDispatcherThread::InputDispatcherThread(const sp<InputDispatcherInterface>& dispatcher) :
4725 Thread(/*canCallJava*/ true), mDispatcher(dispatcher) {
4726}
4727
4728InputDispatcherThread::~InputDispatcherThread() {
4729}
4730
4731bool InputDispatcherThread::threadLoop() {
4732 mDispatcher->dispatchOnce();
4733 return true;
4734}
4735
4736} // namespace android