blob: 04b4855d623875b4445466e556ab2858cece6892 [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 Brownd5bb82d2011-10-12 13:57:59 -0700807 // Handle case where the policy asked us to try again later last time.
808 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
809 if (currentTime < entry->interceptKeyWakeupTime) {
810 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
811 *nextWakeupTime = entry->interceptKeyWakeupTime;
812 }
813 return false; // wait until next wakeup
814 }
815 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
816 entry->interceptKeyWakeupTime = 0;
817 }
818
Jeff Brown54a18252010-09-16 14:07:33 -0700819 // Give the policy a chance to intercept the key.
820 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
Jeff Browne20c9e02010-10-11 14:20:19 -0700821 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Jeff Brown54a18252010-09-16 14:07:33 -0700822 CommandEntry* commandEntry = postCommandLocked(
823 & InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
Jeff Brown9302c872011-07-13 22:51:29 -0700824 if (mFocusedWindowHandle != NULL) {
825 commandEntry->inputWindowHandle = mFocusedWindowHandle;
Jeff Brown54a18252010-09-16 14:07:33 -0700826 }
827 commandEntry->keyEntry = entry;
828 entry->refCount += 1;
829 return false; // wait for the command to run
830 } else {
831 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
832 }
833 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Jeff Browne20c9e02010-10-11 14:20:19 -0700834 if (*dropReason == DROP_REASON_NOT_DROPPED) {
835 *dropReason = DROP_REASON_POLICY;
836 }
Jeff Brown54a18252010-09-16 14:07:33 -0700837 }
838
839 // Clean up if dropping the event.
Jeff Browne20c9e02010-10-11 14:20:19 -0700840 if (*dropReason != DROP_REASON_NOT_DROPPED) {
Jeff Brown54a18252010-09-16 14:07:33 -0700841 resetTargetsLocked();
Jeff Brown3122e442010-10-11 23:32:49 -0700842 setInjectionResultLocked(entry, *dropReason == DROP_REASON_POLICY
843 ? INPUT_EVENT_INJECTION_SUCCEEDED : INPUT_EVENT_INJECTION_FAILED);
Jeff Brown54a18252010-09-16 14:07:33 -0700844 return true;
845 }
846
Jeff Brownb88102f2010-09-08 11:49:43 -0700847 // Identify targets.
848 if (! mCurrentInputTargetsValid) {
Jeff Brown01ce2e92010-09-26 22:20:12 -0700849 int32_t injectionResult = findFocusedWindowTargetsLocked(currentTime,
850 entry, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700851 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
852 return false;
853 }
854
855 setInjectionResultLocked(entry, injectionResult);
856 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
857 return true;
858 }
859
860 addMonitoringTargetsLocked();
Jeff Brown01ce2e92010-09-26 22:20:12 -0700861 commitTargetsLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -0700862 }
863
864 // Dispatch the key.
865 dispatchEventToCurrentInputTargetsLocked(currentTime, entry, false);
Jeff Brownb88102f2010-09-08 11:49:43 -0700866 return true;
867}
868
869void InputDispatcher::logOutboundKeyDetailsLocked(const char* prefix, const KeyEntry* entry) {
870#if DEBUG_OUTBOUND_EVENT_DETAILS
Jeff Brown90655042010-12-02 13:50:46 -0800871 LOGD("%seventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, "
Jeff Brownb88102f2010-09-08 11:49:43 -0700872 "action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, "
Jeff Browne46a0a42010-11-02 17:58:22 -0700873 "repeatCount=%d, downTime=%lld",
Jeff Brownb88102f2010-09-08 11:49:43 -0700874 prefix,
875 entry->eventTime, entry->deviceId, entry->source, entry->policyFlags,
876 entry->action, entry->flags, entry->keyCode, entry->scanCode, entry->metaState,
Jeff Browne46a0a42010-11-02 17:58:22 -0700877 entry->repeatCount, entry->downTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700878#endif
879}
880
881bool InputDispatcher::dispatchMotionLocked(
Jeff Browne20c9e02010-10-11 14:20:19 -0700882 nsecs_t currentTime, MotionEntry* entry, DropReason* dropReason, nsecs_t* nextWakeupTime) {
Jeff Browne46a0a42010-11-02 17:58:22 -0700883 // Preprocessing.
884 if (! entry->dispatchInProgress) {
885 entry->dispatchInProgress = true;
886 resetTargetsLocked();
887
888 logOutboundMotionDetailsLocked("dispatchMotion - ", entry);
889 }
890
Jeff Brown54a18252010-09-16 14:07:33 -0700891 // Clean up if dropping the event.
Jeff Browne20c9e02010-10-11 14:20:19 -0700892 if (*dropReason != DROP_REASON_NOT_DROPPED) {
Jeff Brown54a18252010-09-16 14:07:33 -0700893 resetTargetsLocked();
Jeff Brown3122e442010-10-11 23:32:49 -0700894 setInjectionResultLocked(entry, *dropReason == DROP_REASON_POLICY
895 ? INPUT_EVENT_INJECTION_SUCCEEDED : INPUT_EVENT_INJECTION_FAILED);
Jeff Brown54a18252010-09-16 14:07:33 -0700896 return true;
897 }
898
Jeff Brownb88102f2010-09-08 11:49:43 -0700899 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
900
901 // Identify targets.
Jeff Browncc0c1592011-02-19 05:07:28 -0800902 bool conflictingPointerActions = false;
Jeff Brownb88102f2010-09-08 11:49:43 -0700903 if (! mCurrentInputTargetsValid) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700904 int32_t injectionResult;
Jeff Browna032cc02011-03-07 16:56:21 -0800905 const MotionSample* splitBatchAfterSample = NULL;
Jeff Brownb88102f2010-09-08 11:49:43 -0700906 if (isPointerEvent) {
907 // Pointer event. (eg. touchscreen)
Jeff Brown01ce2e92010-09-26 22:20:12 -0700908 injectionResult = findTouchedWindowTargetsLocked(currentTime,
Jeff Browna032cc02011-03-07 16:56:21 -0800909 entry, nextWakeupTime, &conflictingPointerActions, &splitBatchAfterSample);
Jeff Brownb88102f2010-09-08 11:49:43 -0700910 } else {
911 // Non touch event. (eg. trackball)
Jeff Brown01ce2e92010-09-26 22:20:12 -0700912 injectionResult = findFocusedWindowTargetsLocked(currentTime,
913 entry, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700914 }
915 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
916 return false;
917 }
918
919 setInjectionResultLocked(entry, injectionResult);
920 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
921 return true;
922 }
923
924 addMonitoringTargetsLocked();
Jeff Brown01ce2e92010-09-26 22:20:12 -0700925 commitTargetsLocked();
Jeff Browna032cc02011-03-07 16:56:21 -0800926
927 // Unbatch the event if necessary by splitting it into two parts after the
928 // motion sample indicated by splitBatchAfterSample.
929 if (splitBatchAfterSample && splitBatchAfterSample->next) {
930#if DEBUG_BATCHING
931 uint32_t originalSampleCount = entry->countSamples();
932#endif
933 MotionSample* nextSample = splitBatchAfterSample->next;
Jeff Brownac386072011-07-20 15:19:50 -0700934 MotionEntry* nextEntry = new MotionEntry(nextSample->eventTime,
Jeff Browna032cc02011-03-07 16:56:21 -0800935 entry->deviceId, entry->source, entry->policyFlags,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700936 entry->action, entry->flags,
937 entry->metaState, entry->buttonState, entry->edgeFlags,
Jeff Browna032cc02011-03-07 16:56:21 -0800938 entry->xPrecision, entry->yPrecision, entry->downTime,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700939 entry->pointerCount, entry->pointerProperties, nextSample->pointerCoords);
Jeff Browna032cc02011-03-07 16:56:21 -0800940 if (nextSample != entry->lastSample) {
941 nextEntry->firstSample.next = nextSample->next;
942 nextEntry->lastSample = entry->lastSample;
943 }
Jeff Brownac386072011-07-20 15:19:50 -0700944 delete nextSample;
Jeff Browna032cc02011-03-07 16:56:21 -0800945
946 entry->lastSample = const_cast<MotionSample*>(splitBatchAfterSample);
947 entry->lastSample->next = NULL;
948
949 if (entry->injectionState) {
950 nextEntry->injectionState = entry->injectionState;
951 entry->injectionState->refCount += 1;
952 }
953
954#if DEBUG_BATCHING
955 LOGD("Split batch of %d samples into two parts, first part has %d samples, "
956 "second part has %d samples.", originalSampleCount,
957 entry->countSamples(), nextEntry->countSamples());
958#endif
959
960 mInboundQueue.enqueueAtHead(nextEntry);
961 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700962 }
963
964 // Dispatch the motion.
Jeff Browncc0c1592011-02-19 05:07:28 -0800965 if (conflictingPointerActions) {
Jeff Brownda3d5a92011-03-29 15:11:34 -0700966 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
967 "conflicting pointer actions");
968 synthesizeCancelationEventsForAllConnectionsLocked(options);
Jeff Browncc0c1592011-02-19 05:07:28 -0800969 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700970 dispatchEventToCurrentInputTargetsLocked(currentTime, entry, false);
Jeff Brownb88102f2010-09-08 11:49:43 -0700971 return true;
972}
973
974
975void InputDispatcher::logOutboundMotionDetailsLocked(const char* prefix, const MotionEntry* entry) {
976#if DEBUG_OUTBOUND_EVENT_DETAILS
Jeff Brown90655042010-12-02 13:50:46 -0800977 LOGD("%seventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, "
Jeff Brown85a31762010-09-01 17:01:00 -0700978 "action=0x%x, flags=0x%x, "
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700979 "metaState=0x%x, buttonState=0x%x, "
980 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%lld",
Jeff Brownb88102f2010-09-08 11:49:43 -0700981 prefix,
Jeff Brown85a31762010-09-01 17:01:00 -0700982 entry->eventTime, entry->deviceId, entry->source, entry->policyFlags,
983 entry->action, entry->flags,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700984 entry->metaState, entry->buttonState,
985 entry->edgeFlags, entry->xPrecision, entry->yPrecision,
Jeff Brown46b9ac02010-04-22 18:58:52 -0700986 entry->downTime);
987
988 // Print the most recent sample that we have available, this may change due to batching.
989 size_t sampleCount = 1;
Jeff Brownb88102f2010-09-08 11:49:43 -0700990 const MotionSample* sample = & entry->firstSample;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700991 for (; sample->next != NULL; sample = sample->next) {
992 sampleCount += 1;
993 }
994 for (uint32_t i = 0; i < entry->pointerCount; i++) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700995 LOGD(" Pointer %d: id=%d, toolType=%d, "
996 "x=%f, y=%f, pressure=%f, size=%f, "
Jeff Brown85a31762010-09-01 17:01:00 -0700997 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
Jeff Brown8d608662010-08-30 03:02:23 -0700998 "orientation=%f",
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700999 i, entry->pointerProperties[i].id,
1000 entry->pointerProperties[i].toolType,
Jeff Brownebbd5d12011-02-17 13:01:34 -08001001 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1002 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1003 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1004 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1005 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1006 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1007 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1008 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1009 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Jeff Brown46b9ac02010-04-22 18:58:52 -07001010 }
1011
1012 // Keep in mind that due to batching, it is possible for the number of samples actually
1013 // dispatched to change before the application finally consumed them.
Jeff Brownc5ed5912010-07-14 18:48:53 -07001014 if (entry->action == AMOTION_EVENT_ACTION_MOVE) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07001015 LOGD(" ... Total movement samples currently batched %d ...", sampleCount);
1016 }
1017#endif
Jeff Brown46b9ac02010-04-22 18:58:52 -07001018}
1019
1020void InputDispatcher::dispatchEventToCurrentInputTargetsLocked(nsecs_t currentTime,
1021 EventEntry* eventEntry, bool resumeWithAppendedMotionSample) {
1022#if DEBUG_DISPATCH_CYCLE
Jeff Brown9c3cda02010-06-15 01:31:58 -07001023 LOGD("dispatchEventToCurrentInputTargets - "
Jeff Brown46b9ac02010-04-22 18:58:52 -07001024 "resumeWithAppendedMotionSample=%s",
Jeff Brownb88102f2010-09-08 11:49:43 -07001025 toString(resumeWithAppendedMotionSample));
Jeff Brown46b9ac02010-04-22 18:58:52 -07001026#endif
1027
Jeff Brownb6110c22011-04-01 16:15:13 -07001028 LOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
Jeff Brown9c3cda02010-06-15 01:31:58 -07001029
Jeff Browne2fe69e2010-10-18 13:21:23 -07001030 pokeUserActivityLocked(eventEntry);
1031
Jeff Brown46b9ac02010-04-22 18:58:52 -07001032 for (size_t i = 0; i < mCurrentInputTargets.size(); i++) {
1033 const InputTarget& inputTarget = mCurrentInputTargets.itemAt(i);
1034
Jeff Brown519e0242010-09-15 15:18:56 -07001035 ssize_t connectionIndex = getConnectionIndexLocked(inputTarget.inputChannel);
Jeff Brown46b9ac02010-04-22 18:58:52 -07001036 if (connectionIndex >= 0) {
1037 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
Jeff Brown7fbdc842010-06-17 20:52:56 -07001038 prepareDispatchCycleLocked(currentTime, connection, eventEntry, & inputTarget,
Jeff Brown46b9ac02010-04-22 18:58:52 -07001039 resumeWithAppendedMotionSample);
1040 } else {
Jeff Brownb6997262010-10-08 22:31:17 -07001041#if DEBUG_FOCUS
1042 LOGD("Dropping event delivery to target with channel '%s' because it "
1043 "is no longer registered with the input dispatcher.",
Jeff Brown46b9ac02010-04-22 18:58:52 -07001044 inputTarget.inputChannel->getName().string());
Jeff Brownb6997262010-10-08 22:31:17 -07001045#endif
Jeff Brown46b9ac02010-04-22 18:58:52 -07001046 }
1047 }
1048}
1049
Jeff Brown54a18252010-09-16 14:07:33 -07001050void InputDispatcher::resetTargetsLocked() {
Jeff Brownb88102f2010-09-08 11:49:43 -07001051 mCurrentInputTargetsValid = false;
1052 mCurrentInputTargets.clear();
Jeff Brown5ea29ab2011-07-27 11:50:51 -07001053 resetANRTimeoutsLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -07001054}
1055
Jeff Brown01ce2e92010-09-26 22:20:12 -07001056void InputDispatcher::commitTargetsLocked() {
Jeff Brownb88102f2010-09-08 11:49:43 -07001057 mCurrentInputTargetsValid = true;
1058}
1059
1060int32_t InputDispatcher::handleTargetsNotReadyLocked(nsecs_t currentTime,
Jeff Brown9302c872011-07-13 22:51:29 -07001061 const EventEntry* entry,
1062 const sp<InputApplicationHandle>& applicationHandle,
1063 const sp<InputWindowHandle>& windowHandle,
Jeff Brownb88102f2010-09-08 11:49:43 -07001064 nsecs_t* nextWakeupTime) {
Jeff Brown9302c872011-07-13 22:51:29 -07001065 if (applicationHandle == NULL && windowHandle == NULL) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001066 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY) {
1067#if DEBUG_FOCUS
1068 LOGD("Waiting for system to become ready for input.");
1069#endif
1070 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY;
1071 mInputTargetWaitStartTime = currentTime;
1072 mInputTargetWaitTimeoutTime = LONG_LONG_MAX;
1073 mInputTargetWaitTimeoutExpired = false;
Jeff Brown9302c872011-07-13 22:51:29 -07001074 mInputTargetWaitApplicationHandle.clear();
Jeff Brownb88102f2010-09-08 11:49:43 -07001075 }
1076 } else {
1077 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
1078#if DEBUG_FOCUS
Jeff Brown519e0242010-09-15 15:18:56 -07001079 LOGD("Waiting for application to become ready for input: %s",
Jeff Brown9302c872011-07-13 22:51:29 -07001080 getApplicationWindowLabelLocked(applicationHandle, windowHandle).string());
Jeff Brownb88102f2010-09-08 11:49:43 -07001081#endif
Jeff Browncc4f7db2011-08-30 20:34:48 -07001082 nsecs_t timeout;
1083 if (windowHandle != NULL) {
1084 timeout = windowHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
1085 } else if (applicationHandle != NULL) {
1086 timeout = applicationHandle->getDispatchingTimeout(
1087 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
1088 } else {
1089 timeout = DEFAULT_INPUT_DISPATCHING_TIMEOUT;
1090 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001091
1092 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY;
1093 mInputTargetWaitStartTime = currentTime;
1094 mInputTargetWaitTimeoutTime = currentTime + timeout;
1095 mInputTargetWaitTimeoutExpired = false;
Jeff Brown9302c872011-07-13 22:51:29 -07001096 mInputTargetWaitApplicationHandle.clear();
Jeff Brown928e0542011-01-10 11:17:36 -08001097
Jeff Brown9302c872011-07-13 22:51:29 -07001098 if (windowHandle != NULL) {
1099 mInputTargetWaitApplicationHandle = windowHandle->inputApplicationHandle;
Jeff Brown928e0542011-01-10 11:17:36 -08001100 }
Jeff Brown9302c872011-07-13 22:51:29 -07001101 if (mInputTargetWaitApplicationHandle == NULL && applicationHandle != NULL) {
1102 mInputTargetWaitApplicationHandle = applicationHandle;
Jeff Brown928e0542011-01-10 11:17:36 -08001103 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001104 }
1105 }
1106
1107 if (mInputTargetWaitTimeoutExpired) {
1108 return INPUT_EVENT_INJECTION_TIMED_OUT;
1109 }
1110
1111 if (currentTime >= mInputTargetWaitTimeoutTime) {
Jeff Brown9302c872011-07-13 22:51:29 -07001112 onANRLocked(currentTime, applicationHandle, windowHandle,
1113 entry->eventTime, mInputTargetWaitStartTime);
Jeff Brownb88102f2010-09-08 11:49:43 -07001114
1115 // Force poll loop to wake up immediately on next iteration once we get the
1116 // ANR response back from the policy.
1117 *nextWakeupTime = LONG_LONG_MIN;
1118 return INPUT_EVENT_INJECTION_PENDING;
1119 } else {
1120 // Force poll loop to wake up when timeout is due.
1121 if (mInputTargetWaitTimeoutTime < *nextWakeupTime) {
1122 *nextWakeupTime = mInputTargetWaitTimeoutTime;
1123 }
1124 return INPUT_EVENT_INJECTION_PENDING;
1125 }
1126}
1127
Jeff Brown519e0242010-09-15 15:18:56 -07001128void InputDispatcher::resumeAfterTargetsNotReadyTimeoutLocked(nsecs_t newTimeout,
1129 const sp<InputChannel>& inputChannel) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001130 if (newTimeout > 0) {
1131 // Extend the timeout.
1132 mInputTargetWaitTimeoutTime = now() + newTimeout;
1133 } else {
1134 // Give up.
1135 mInputTargetWaitTimeoutExpired = true;
Jeff Brown519e0242010-09-15 15:18:56 -07001136
Jeff Brown01ce2e92010-09-26 22:20:12 -07001137 // Release the touch targets.
1138 mTouchState.reset();
Jeff Brown2a95c2a2010-09-16 12:31:46 -07001139
Jeff Brown519e0242010-09-15 15:18:56 -07001140 // Input state will not be realistic. Mark it out of sync.
Jeff Browndc3e0052010-09-16 11:02:16 -07001141 if (inputChannel.get()) {
1142 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
1143 if (connectionIndex >= 0) {
1144 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
Jeff Brown00045a72010-12-09 18:10:30 -08001145 if (connection->status == Connection::STATUS_NORMAL) {
Jeff Brownda3d5a92011-03-29 15:11:34 -07001146 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
Jeff Brown00045a72010-12-09 18:10:30 -08001147 "application not responding");
Jeff Brownda3d5a92011-03-29 15:11:34 -07001148 synthesizeCancelationEventsForConnectionLocked(connection, options);
Jeff Brown00045a72010-12-09 18:10:30 -08001149 }
Jeff Browndc3e0052010-09-16 11:02:16 -07001150 }
Jeff Brown519e0242010-09-15 15:18:56 -07001151 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001152 }
1153}
1154
Jeff Brown519e0242010-09-15 15:18:56 -07001155nsecs_t InputDispatcher::getTimeSpentWaitingForApplicationLocked(
Jeff Brownb88102f2010-09-08 11:49:43 -07001156 nsecs_t currentTime) {
1157 if (mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
1158 return currentTime - mInputTargetWaitStartTime;
1159 }
1160 return 0;
1161}
1162
1163void InputDispatcher::resetANRTimeoutsLocked() {
1164#if DEBUG_FOCUS
1165 LOGD("Resetting ANR timeouts.");
1166#endif
1167
Jeff Brownb88102f2010-09-08 11:49:43 -07001168 // Reset input target wait timeout.
1169 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_NONE;
Jeff Brown5ea29ab2011-07-27 11:50:51 -07001170 mInputTargetWaitApplicationHandle.clear();
Jeff Brownb88102f2010-09-08 11:49:43 -07001171}
1172
Jeff Brown01ce2e92010-09-26 22:20:12 -07001173int32_t InputDispatcher::findFocusedWindowTargetsLocked(nsecs_t currentTime,
1174 const EventEntry* entry, nsecs_t* nextWakeupTime) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001175 mCurrentInputTargets.clear();
1176
1177 int32_t injectionResult;
1178
1179 // If there is no currently focused window and no focused application
1180 // then drop the event.
Jeff Brown9302c872011-07-13 22:51:29 -07001181 if (mFocusedWindowHandle == NULL) {
1182 if (mFocusedApplicationHandle != NULL) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001183#if DEBUG_FOCUS
1184 LOGD("Waiting because there is no focused window but there is a "
Jeff Brown519e0242010-09-15 15:18:56 -07001185 "focused application that may eventually add a window: %s.",
Jeff Brown9302c872011-07-13 22:51:29 -07001186 getApplicationWindowLabelLocked(mFocusedApplicationHandle, NULL).string());
Jeff Brownb88102f2010-09-08 11:49:43 -07001187#endif
1188 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brown9302c872011-07-13 22:51:29 -07001189 mFocusedApplicationHandle, NULL, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -07001190 goto Unresponsive;
1191 }
1192
1193 LOGI("Dropping event because there is no focused window or focused application.");
1194 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1195 goto Failed;
1196 }
1197
1198 // Check permissions.
Jeff Brown9302c872011-07-13 22:51:29 -07001199 if (! checkInjectionPermission(mFocusedWindowHandle, entry->injectionState)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001200 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1201 goto Failed;
1202 }
1203
1204 // If the currently focused window is paused then keep waiting.
Jeff Browncc4f7db2011-08-30 20:34:48 -07001205 if (mFocusedWindowHandle->getInfo()->paused) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001206#if DEBUG_FOCUS
1207 LOGD("Waiting because focused window is paused.");
1208#endif
1209 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brown9302c872011-07-13 22:51:29 -07001210 mFocusedApplicationHandle, mFocusedWindowHandle, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -07001211 goto Unresponsive;
1212 }
1213
Jeff Brown519e0242010-09-15 15:18:56 -07001214 // If the currently focused window is still working on previous events then keep waiting.
Jeff Brown9302c872011-07-13 22:51:29 -07001215 if (! isWindowFinishedWithPreviousInputLocked(mFocusedWindowHandle)) {
Jeff Brown519e0242010-09-15 15:18:56 -07001216#if DEBUG_FOCUS
1217 LOGD("Waiting because focused window still processing previous input.");
1218#endif
1219 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brown9302c872011-07-13 22:51:29 -07001220 mFocusedApplicationHandle, mFocusedWindowHandle, nextWakeupTime);
Jeff Brown519e0242010-09-15 15:18:56 -07001221 goto Unresponsive;
1222 }
1223
Jeff Brownb88102f2010-09-08 11:49:43 -07001224 // Success! Output targets.
1225 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
Jeff Brown9302c872011-07-13 22:51:29 -07001226 addWindowTargetLocked(mFocusedWindowHandle,
Jeff Browna032cc02011-03-07 16:56:21 -08001227 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS, BitSet32(0));
Jeff Brownb88102f2010-09-08 11:49:43 -07001228
1229 // Done.
1230Failed:
1231Unresponsive:
Jeff Brown519e0242010-09-15 15:18:56 -07001232 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
1233 updateDispatchStatisticsLocked(currentTime, entry,
1234 injectionResult, timeSpentWaitingForApplication);
Jeff Brownb88102f2010-09-08 11:49:43 -07001235#if DEBUG_FOCUS
Jeff Brown519e0242010-09-15 15:18:56 -07001236 LOGD("findFocusedWindow finished: injectionResult=%d, "
1237 "timeSpendWaitingForApplication=%0.1fms",
1238 injectionResult, timeSpentWaitingForApplication / 1000000.0);
Jeff Brownb88102f2010-09-08 11:49:43 -07001239#endif
1240 return injectionResult;
1241}
1242
Jeff Brown01ce2e92010-09-26 22:20:12 -07001243int32_t InputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime,
Jeff Browna032cc02011-03-07 16:56:21 -08001244 const MotionEntry* entry, nsecs_t* nextWakeupTime, bool* outConflictingPointerActions,
1245 const MotionSample** outSplitBatchAfterSample) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001246 enum InjectionPermission {
1247 INJECTION_PERMISSION_UNKNOWN,
1248 INJECTION_PERMISSION_GRANTED,
1249 INJECTION_PERMISSION_DENIED
1250 };
1251
Jeff Brownb88102f2010-09-08 11:49:43 -07001252 mCurrentInputTargets.clear();
1253
1254 nsecs_t startTime = now();
1255
1256 // For security reasons, we defer updating the touch state until we are sure that
1257 // event injection will be allowed.
1258 //
1259 // FIXME In the original code, screenWasOff could never be set to true.
1260 // The reason is that the POLICY_FLAG_WOKE_HERE
1261 // and POLICY_FLAG_BRIGHT_HERE flags were set only when preprocessing raw
1262 // EV_KEY, EV_REL and EV_ABS events. As it happens, the touch event was
1263 // actually enqueued using the policyFlags that appeared in the final EV_SYN
1264 // events upon which no preprocessing took place. So policyFlags was always 0.
1265 // In the new native input dispatcher we're a bit more careful about event
1266 // preprocessing so the touches we receive can actually have non-zero policyFlags.
1267 // Unfortunately we obtain undesirable behavior.
1268 //
1269 // Here's what happens:
1270 //
1271 // When the device dims in anticipation of going to sleep, touches
1272 // in windows which have FLAG_TOUCHABLE_WHEN_WAKING cause
1273 // the device to brighten and reset the user activity timer.
1274 // Touches on other windows (such as the launcher window)
1275 // are dropped. Then after a moment, the device goes to sleep. Oops.
1276 //
1277 // Also notice how screenWasOff was being initialized using POLICY_FLAG_BRIGHT_HERE
1278 // instead of POLICY_FLAG_WOKE_HERE...
1279 //
1280 bool screenWasOff = false; // original policy: policyFlags & POLICY_FLAG_BRIGHT_HERE;
1281
1282 int32_t action = entry->action;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001283 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Jeff Brownb88102f2010-09-08 11:49:43 -07001284
1285 // Update the touch state as needed based on the properties of the touch event.
Jeff Brown01ce2e92010-09-26 22:20:12 -07001286 int32_t injectionResult = INPUT_EVENT_INJECTION_PENDING;
1287 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
Jeff Brown9302c872011-07-13 22:51:29 -07001288 sp<InputWindowHandle> newHoverWindowHandle;
Jeff Browncc0c1592011-02-19 05:07:28 -08001289
1290 bool isSplit = mTouchState.split;
Jeff Brown2717eff2011-06-30 23:53:07 -07001291 bool switchedDevice = mTouchState.deviceId >= 0
1292 && (mTouchState.deviceId != entry->deviceId
1293 || mTouchState.source != entry->source);
Jeff Browna032cc02011-03-07 16:56:21 -08001294 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE
1295 || maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER
1296 || maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1297 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN
1298 || maskedAction == AMOTION_EVENT_ACTION_SCROLL
1299 || isHoverAction);
Jeff Brown81346812011-06-28 20:08:48 -07001300 bool wrongDevice = false;
Jeff Browna032cc02011-03-07 16:56:21 -08001301 if (newGesture) {
Jeff Browncc0c1592011-02-19 05:07:28 -08001302 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Jeff Brown81346812011-06-28 20:08:48 -07001303 if (switchedDevice && mTouchState.down && !down) {
1304#if DEBUG_FOCUS
1305 LOGD("Dropping event because a pointer for a different device is already down.");
1306#endif
Jeff Browncc0c1592011-02-19 05:07:28 -08001307 mTempTouchState.copyFrom(mTouchState);
Jeff Brown81346812011-06-28 20:08:48 -07001308 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1309 switchedDevice = false;
1310 wrongDevice = true;
1311 goto Failed;
Jeff Browncc0c1592011-02-19 05:07:28 -08001312 }
Jeff Brown81346812011-06-28 20:08:48 -07001313 mTempTouchState.reset();
1314 mTempTouchState.down = down;
1315 mTempTouchState.deviceId = entry->deviceId;
1316 mTempTouchState.source = entry->source;
1317 isSplit = false;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001318 } else {
1319 mTempTouchState.copyFrom(mTouchState);
Jeff Browncc0c1592011-02-19 05:07:28 -08001320 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001321
Jeff Browna032cc02011-03-07 16:56:21 -08001322 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
Jeff Brown33bbfd22011-02-24 20:55:35 -08001323 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
Jeff Brownb88102f2010-09-08 11:49:43 -07001324
Jeff Browna032cc02011-03-07 16:56:21 -08001325 const MotionSample* sample = &entry->firstSample;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001326 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Jeff Browna032cc02011-03-07 16:56:21 -08001327 int32_t x = int32_t(sample->pointerCoords[pointerIndex].
Jeff Brownebbd5d12011-02-17 13:01:34 -08001328 getAxisValue(AMOTION_EVENT_AXIS_X));
Jeff Browna032cc02011-03-07 16:56:21 -08001329 int32_t y = int32_t(sample->pointerCoords[pointerIndex].
Jeff Brownebbd5d12011-02-17 13:01:34 -08001330 getAxisValue(AMOTION_EVENT_AXIS_Y));
Jeff Brown9302c872011-07-13 22:51:29 -07001331 sp<InputWindowHandle> newTouchedWindowHandle;
1332 sp<InputWindowHandle> topErrorWindowHandle;
Jeff Browna032cc02011-03-07 16:56:21 -08001333 bool isTouchModal = false;
Jeff Brownb88102f2010-09-08 11:49:43 -07001334
1335 // Traverse windows from front to back to find touched window and outside targets.
Jeff Brown9302c872011-07-13 22:51:29 -07001336 size_t numWindows = mWindowHandles.size();
Jeff Brownb88102f2010-09-08 11:49:43 -07001337 for (size_t i = 0; i < numWindows; i++) {
Jeff Brown9302c872011-07-13 22:51:29 -07001338 sp<InputWindowHandle> windowHandle = mWindowHandles.itemAt(i);
Jeff Browncc4f7db2011-08-30 20:34:48 -07001339 const InputWindowInfo* windowInfo = windowHandle->getInfo();
1340 int32_t flags = windowInfo->layoutParamsFlags;
Jeff Brownb88102f2010-09-08 11:49:43 -07001341
Jeff Browncc4f7db2011-08-30 20:34:48 -07001342 if (flags & InputWindowInfo::FLAG_SYSTEM_ERROR) {
Jeff Brown9302c872011-07-13 22:51:29 -07001343 if (topErrorWindowHandle == NULL) {
1344 topErrorWindowHandle = windowHandle;
Jeff Brownb88102f2010-09-08 11:49:43 -07001345 }
1346 }
1347
Jeff Browncc4f7db2011-08-30 20:34:48 -07001348 if (windowInfo->visible) {
1349 if (! (flags & InputWindowInfo::FLAG_NOT_TOUCHABLE)) {
1350 isTouchModal = (flags & (InputWindowInfo::FLAG_NOT_FOCUSABLE
1351 | InputWindowInfo::FLAG_NOT_TOUCH_MODAL)) == 0;
1352 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
Jeff Brown9302c872011-07-13 22:51:29 -07001353 if (! screenWasOff
Jeff Browncc4f7db2011-08-30 20:34:48 -07001354 || (flags & InputWindowInfo::FLAG_TOUCHABLE_WHEN_WAKING)) {
Jeff Brown9302c872011-07-13 22:51:29 -07001355 newTouchedWindowHandle = windowHandle;
Jeff Brownb88102f2010-09-08 11:49:43 -07001356 }
1357 break; // found touched window, exit window loop
1358 }
1359 }
1360
Jeff Brown01ce2e92010-09-26 22:20:12 -07001361 if (maskedAction == AMOTION_EVENT_ACTION_DOWN
Jeff Browncc4f7db2011-08-30 20:34:48 -07001362 && (flags & InputWindowInfo::FLAG_WATCH_OUTSIDE_TOUCH)) {
Jeff Browna032cc02011-03-07 16:56:21 -08001363 int32_t outsideTargetFlags = InputTarget::FLAG_DISPATCH_AS_OUTSIDE;
Jeff Brown9302c872011-07-13 22:51:29 -07001364 if (isWindowObscuredAtPointLocked(windowHandle, x, y)) {
Jeff Brown19dfc832010-10-05 12:26:23 -07001365 outsideTargetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1366 }
1367
Jeff Brown9302c872011-07-13 22:51:29 -07001368 mTempTouchState.addOrUpdateWindow(
1369 windowHandle, outsideTargetFlags, BitSet32(0));
Jeff Brownb88102f2010-09-08 11:49:43 -07001370 }
1371 }
1372 }
1373
1374 // If there is an error window but it is not taking focus (typically because
1375 // it is invisible) then wait for it. Any other focused window may in
1376 // fact be in ANR state.
Jeff Brown9302c872011-07-13 22:51:29 -07001377 if (topErrorWindowHandle != NULL && newTouchedWindowHandle != topErrorWindowHandle) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001378#if DEBUG_FOCUS
1379 LOGD("Waiting because system error window is pending.");
1380#endif
1381 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
1382 NULL, NULL, nextWakeupTime);
1383 injectionPermission = INJECTION_PERMISSION_UNKNOWN;
1384 goto Unresponsive;
1385 }
1386
Jeff Brown01ce2e92010-09-26 22:20:12 -07001387 // Figure out whether splitting will be allowed for this window.
Jeff Browncc4f7db2011-08-30 20:34:48 -07001388 if (newTouchedWindowHandle != NULL
1389 && newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001390 // New window supports splitting.
1391 isSplit = true;
1392 } else if (isSplit) {
1393 // New window does not support splitting but we have already split events.
1394 // Assign the pointer to the first foreground window we find.
1395 // (May be NULL which is why we put this code block before the next check.)
Jeff Brown9302c872011-07-13 22:51:29 -07001396 newTouchedWindowHandle = mTempTouchState.getFirstForegroundWindowHandle();
Jeff Brown01ce2e92010-09-26 22:20:12 -07001397 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001398
Jeff Brownb88102f2010-09-08 11:49:43 -07001399 // If we did not find a touched window then fail.
Jeff Brown9302c872011-07-13 22:51:29 -07001400 if (newTouchedWindowHandle == NULL) {
1401 if (mFocusedApplicationHandle != NULL) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001402#if DEBUG_FOCUS
1403 LOGD("Waiting because there is no touched window but there is a "
Jeff Brown519e0242010-09-15 15:18:56 -07001404 "focused application that may eventually add a new window: %s.",
Jeff Brown9302c872011-07-13 22:51:29 -07001405 getApplicationWindowLabelLocked(mFocusedApplicationHandle, NULL).string());
Jeff Brownb88102f2010-09-08 11:49:43 -07001406#endif
1407 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brown9302c872011-07-13 22:51:29 -07001408 mFocusedApplicationHandle, NULL, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -07001409 goto Unresponsive;
1410 }
1411
1412 LOGI("Dropping event because there is no touched window or focused application.");
1413 injectionResult = INPUT_EVENT_INJECTION_FAILED;
Jeff Brownb88102f2010-09-08 11:49:43 -07001414 goto Failed;
1415 }
1416
Jeff Brown19dfc832010-10-05 12:26:23 -07001417 // Set target flags.
Jeff Browna032cc02011-03-07 16:56:21 -08001418 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
Jeff Brown19dfc832010-10-05 12:26:23 -07001419 if (isSplit) {
1420 targetFlags |= InputTarget::FLAG_SPLIT;
1421 }
Jeff Brown9302c872011-07-13 22:51:29 -07001422 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
Jeff Brown19dfc832010-10-05 12:26:23 -07001423 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1424 }
1425
Jeff Browna032cc02011-03-07 16:56:21 -08001426 // Update hover state.
1427 if (isHoverAction) {
Jeff Brown9302c872011-07-13 22:51:29 -07001428 newHoverWindowHandle = newTouchedWindowHandle;
Jeff Browna032cc02011-03-07 16:56:21 -08001429
1430 // Ensure all subsequent motion samples are also within the touched window.
1431 // Set *outSplitBatchAfterSample to the sample before the first one that is not
1432 // within the touched window.
1433 if (!isTouchModal) {
1434 while (sample->next) {
Jeff Browncc4f7db2011-08-30 20:34:48 -07001435 if (!newHoverWindowHandle->getInfo()->touchableRegionContainsPoint(
Jeff Browna032cc02011-03-07 16:56:21 -08001436 sample->next->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X),
1437 sample->next->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y))) {
1438 *outSplitBatchAfterSample = sample;
1439 break;
1440 }
1441 sample = sample->next;
1442 }
1443 }
1444 } else if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
Jeff Brown9302c872011-07-13 22:51:29 -07001445 newHoverWindowHandle = mLastHoverWindowHandle;
Jeff Browna032cc02011-03-07 16:56:21 -08001446 }
1447
Jeff Brown01ce2e92010-09-26 22:20:12 -07001448 // Update the temporary touch state.
1449 BitSet32 pointerIds;
1450 if (isSplit) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07001451 uint32_t pointerId = entry->pointerProperties[pointerIndex].id;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001452 pointerIds.markBit(pointerId);
Jeff Brownb88102f2010-09-08 11:49:43 -07001453 }
Jeff Brown9302c872011-07-13 22:51:29 -07001454 mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Jeff Brownb88102f2010-09-08 11:49:43 -07001455 } else {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001456 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
Jeff Brownb88102f2010-09-08 11:49:43 -07001457
1458 // If the pointer is not currently down, then ignore the event.
Jeff Brown01ce2e92010-09-26 22:20:12 -07001459 if (! mTempTouchState.down) {
Jeff Browna2cc28d2011-03-25 11:58:46 -07001460#if DEBUG_FOCUS
Jeff Brown76860e32010-10-25 17:37:46 -07001461 LOGD("Dropping event because the pointer is not down or we previously "
1462 "dropped the pointer down event.");
1463#endif
Jeff Brownb88102f2010-09-08 11:49:43 -07001464 injectionResult = INPUT_EVENT_INJECTION_FAILED;
Jeff Brownb88102f2010-09-08 11:49:43 -07001465 goto Failed;
1466 }
Jeff Brown98db5fa2011-06-08 15:37:10 -07001467
1468 // Check whether touches should slip outside of the current foreground window.
1469 if (maskedAction == AMOTION_EVENT_ACTION_MOVE
1470 && entry->pointerCount == 1
1471 && mTempTouchState.isSlippery()) {
1472 const MotionSample* sample = &entry->firstSample;
1473 int32_t x = int32_t(sample->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
1474 int32_t y = int32_t(sample->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
1475
Jeff Brown9302c872011-07-13 22:51:29 -07001476 sp<InputWindowHandle> oldTouchedWindowHandle =
1477 mTempTouchState.getFirstForegroundWindowHandle();
1478 sp<InputWindowHandle> newTouchedWindowHandle = findTouchedWindowAtLocked(x, y);
1479 if (oldTouchedWindowHandle != newTouchedWindowHandle
1480 && newTouchedWindowHandle != NULL) {
Jeff Brown98db5fa2011-06-08 15:37:10 -07001481#if DEBUG_FOCUS
1482 LOGD("Touch is slipping out of window %s into window %s.",
Jeff Browncc4f7db2011-08-30 20:34:48 -07001483 oldTouchedWindowHandle->getName().string(),
1484 newTouchedWindowHandle->getName().string());
Jeff Brown98db5fa2011-06-08 15:37:10 -07001485#endif
1486 // Make a slippery exit from the old window.
Jeff Brown9302c872011-07-13 22:51:29 -07001487 mTempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
Jeff Brown98db5fa2011-06-08 15:37:10 -07001488 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT, BitSet32(0));
1489
1490 // Make a slippery entrance into the new window.
Jeff Browncc4f7db2011-08-30 20:34:48 -07001491 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Jeff Brown98db5fa2011-06-08 15:37:10 -07001492 isSplit = true;
1493 }
1494
1495 int32_t targetFlags = InputTarget::FLAG_FOREGROUND
1496 | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
1497 if (isSplit) {
1498 targetFlags |= InputTarget::FLAG_SPLIT;
1499 }
Jeff Brown9302c872011-07-13 22:51:29 -07001500 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
Jeff Brown98db5fa2011-06-08 15:37:10 -07001501 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1502 }
1503
1504 BitSet32 pointerIds;
1505 if (isSplit) {
1506 pointerIds.markBit(entry->pointerProperties[0].id);
1507 }
Jeff Brown9302c872011-07-13 22:51:29 -07001508 mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Jeff Brown98db5fa2011-06-08 15:37:10 -07001509
1510 // Split the batch here so we send exactly one sample.
1511 *outSplitBatchAfterSample = &entry->firstSample;
1512 }
1513 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001514 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001515
Jeff Brown9302c872011-07-13 22:51:29 -07001516 if (newHoverWindowHandle != mLastHoverWindowHandle) {
Jeff Browna032cc02011-03-07 16:56:21 -08001517 // Split the batch here so we send exactly one sample as part of ENTER or EXIT.
1518 *outSplitBatchAfterSample = &entry->firstSample;
1519
1520 // Let the previous window know that the hover sequence is over.
Jeff Brown9302c872011-07-13 22:51:29 -07001521 if (mLastHoverWindowHandle != NULL) {
Jeff Browna032cc02011-03-07 16:56:21 -08001522#if DEBUG_HOVER
Jeff Browncc4f7db2011-08-30 20:34:48 -07001523 LOGD("Sending hover exit event to window %s.",
1524 mLastHoverWindowHandle->getName().string());
Jeff Browna032cc02011-03-07 16:56:21 -08001525#endif
Jeff Brown9302c872011-07-13 22:51:29 -07001526 mTempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
Jeff Browna032cc02011-03-07 16:56:21 -08001527 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
1528 }
1529
1530 // Let the new window know that the hover sequence is starting.
Jeff Brown9302c872011-07-13 22:51:29 -07001531 if (newHoverWindowHandle != NULL) {
Jeff Browna032cc02011-03-07 16:56:21 -08001532#if DEBUG_HOVER
Jeff Browncc4f7db2011-08-30 20:34:48 -07001533 LOGD("Sending hover enter event to window %s.",
1534 newHoverWindowHandle->getName().string());
Jeff Browna032cc02011-03-07 16:56:21 -08001535#endif
Jeff Brown9302c872011-07-13 22:51:29 -07001536 mTempTouchState.addOrUpdateWindow(newHoverWindowHandle,
Jeff Browna032cc02011-03-07 16:56:21 -08001537 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER, BitSet32(0));
1538 }
1539 }
1540
Jeff Brown01ce2e92010-09-26 22:20:12 -07001541 // Check permission to inject into all touched foreground windows and ensure there
1542 // is at least one touched foreground window.
1543 {
1544 bool haveForegroundWindow = false;
1545 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1546 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1547 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1548 haveForegroundWindow = true;
Jeff Brown9302c872011-07-13 22:51:29 -07001549 if (! checkInjectionPermission(touchedWindow.windowHandle,
1550 entry->injectionState)) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001551 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1552 injectionPermission = INJECTION_PERMISSION_DENIED;
1553 goto Failed;
1554 }
1555 }
1556 }
1557 if (! haveForegroundWindow) {
Jeff Browna2cc28d2011-03-25 11:58:46 -07001558#if DEBUG_FOCUS
Jeff Brown01ce2e92010-09-26 22:20:12 -07001559 LOGD("Dropping event because there is no touched foreground window to receive it.");
Jeff Brownb88102f2010-09-08 11:49:43 -07001560#endif
1561 injectionResult = INPUT_EVENT_INJECTION_FAILED;
Jeff Brownb88102f2010-09-08 11:49:43 -07001562 goto Failed;
1563 }
1564
Jeff Brown01ce2e92010-09-26 22:20:12 -07001565 // Permission granted to injection into all touched foreground windows.
1566 injectionPermission = INJECTION_PERMISSION_GRANTED;
1567 }
Jeff Brown519e0242010-09-15 15:18:56 -07001568
Kenny Root7a9db182011-06-02 15:16:05 -07001569 // Check whether windows listening for outside touches are owned by the same UID. If it is
1570 // set the policy flag that we will not reveal coordinate information to this window.
1571 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
Jeff Brown9302c872011-07-13 22:51:29 -07001572 sp<InputWindowHandle> foregroundWindowHandle =
1573 mTempTouchState.getFirstForegroundWindowHandle();
Jeff Browncc4f7db2011-08-30 20:34:48 -07001574 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Kenny Root7a9db182011-06-02 15:16:05 -07001575 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1576 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1577 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
Jeff Brown9302c872011-07-13 22:51:29 -07001578 sp<InputWindowHandle> inputWindowHandle = touchedWindow.windowHandle;
Jeff Browncc4f7db2011-08-30 20:34:48 -07001579 if (inputWindowHandle->getInfo()->ownerUid != foregroundWindowUid) {
Jeff Brown9302c872011-07-13 22:51:29 -07001580 mTempTouchState.addOrUpdateWindow(inputWindowHandle,
Kenny Root7a9db182011-06-02 15:16:05 -07001581 InputTarget::FLAG_ZERO_COORDS, BitSet32(0));
1582 }
1583 }
1584 }
1585 }
1586
Jeff Brown01ce2e92010-09-26 22:20:12 -07001587 // Ensure all touched foreground windows are ready for new input.
1588 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1589 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1590 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1591 // If the touched window is paused then keep waiting.
Jeff Browncc4f7db2011-08-30 20:34:48 -07001592 if (touchedWindow.windowHandle->getInfo()->paused) {
Jeff Browna2cc28d2011-03-25 11:58:46 -07001593#if DEBUG_FOCUS
Jeff Brown01ce2e92010-09-26 22:20:12 -07001594 LOGD("Waiting because touched window is paused.");
Jeff Brown519e0242010-09-15 15:18:56 -07001595#endif
Jeff Brown01ce2e92010-09-26 22:20:12 -07001596 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brown9302c872011-07-13 22:51:29 -07001597 NULL, touchedWindow.windowHandle, nextWakeupTime);
Jeff Brown01ce2e92010-09-26 22:20:12 -07001598 goto Unresponsive;
1599 }
1600
1601 // If the touched window is still working on previous events then keep waiting.
Jeff Brown9302c872011-07-13 22:51:29 -07001602 if (! isWindowFinishedWithPreviousInputLocked(touchedWindow.windowHandle)) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001603#if DEBUG_FOCUS
1604 LOGD("Waiting because touched window still processing previous input.");
1605#endif
1606 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brown9302c872011-07-13 22:51:29 -07001607 NULL, touchedWindow.windowHandle, nextWakeupTime);
Jeff Brown01ce2e92010-09-26 22:20:12 -07001608 goto Unresponsive;
1609 }
1610 }
1611 }
1612
1613 // If this is the first pointer going down and the touched window has a wallpaper
1614 // then also add the touched wallpaper windows so they are locked in for the duration
1615 // of the touch gesture.
Jeff Brown33bbfd22011-02-24 20:55:35 -08001616 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
1617 // engine only supports touch events. We would need to add a mechanism similar
1618 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
1619 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
Jeff Brown9302c872011-07-13 22:51:29 -07001620 sp<InputWindowHandle> foregroundWindowHandle =
1621 mTempTouchState.getFirstForegroundWindowHandle();
Jeff Browncc4f7db2011-08-30 20:34:48 -07001622 if (foregroundWindowHandle->getInfo()->hasWallpaper) {
Jeff Brown9302c872011-07-13 22:51:29 -07001623 for (size_t i = 0; i < mWindowHandles.size(); i++) {
1624 sp<InputWindowHandle> windowHandle = mWindowHandles.itemAt(i);
Jeff Browncc4f7db2011-08-30 20:34:48 -07001625 if (windowHandle->getInfo()->layoutParamsType
1626 == InputWindowInfo::TYPE_WALLPAPER) {
Jeff Brown9302c872011-07-13 22:51:29 -07001627 mTempTouchState.addOrUpdateWindow(windowHandle,
Jeff Browna032cc02011-03-07 16:56:21 -08001628 InputTarget::FLAG_WINDOW_IS_OBSCURED
1629 | InputTarget::FLAG_DISPATCH_AS_IS,
1630 BitSet32(0));
Jeff Brown01ce2e92010-09-26 22:20:12 -07001631 }
1632 }
1633 }
1634 }
1635
Jeff Brownb88102f2010-09-08 11:49:43 -07001636 // Success! Output targets.
1637 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
Jeff Brownb88102f2010-09-08 11:49:43 -07001638
Jeff Brown01ce2e92010-09-26 22:20:12 -07001639 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1640 const TouchedWindow& touchedWindow = mTempTouchState.windows.itemAt(i);
Jeff Brown9302c872011-07-13 22:51:29 -07001641 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Jeff Brown01ce2e92010-09-26 22:20:12 -07001642 touchedWindow.pointerIds);
Jeff Brownb88102f2010-09-08 11:49:43 -07001643 }
1644
Jeff Browna032cc02011-03-07 16:56:21 -08001645 // Drop the outside or hover touch windows since we will not care about them
1646 // in the next iteration.
1647 mTempTouchState.filterNonAsIsTouchWindows();
Jeff Brown01ce2e92010-09-26 22:20:12 -07001648
Jeff Brownb88102f2010-09-08 11:49:43 -07001649Failed:
1650 // Check injection permission once and for all.
1651 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001652 if (checkInjectionPermission(NULL, entry->injectionState)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001653 injectionPermission = INJECTION_PERMISSION_GRANTED;
1654 } else {
1655 injectionPermission = INJECTION_PERMISSION_DENIED;
1656 }
1657 }
1658
1659 // Update final pieces of touch state if the injector had permission.
1660 if (injectionPermission == INJECTION_PERMISSION_GRANTED) {
Jeff Brown95712852011-01-04 19:41:59 -08001661 if (!wrongDevice) {
Jeff Brown81346812011-06-28 20:08:48 -07001662 if (switchedDevice) {
1663#if DEBUG_FOCUS
1664 LOGD("Conflicting pointer actions: Switched to a different device.");
1665#endif
1666 *outConflictingPointerActions = true;
1667 }
1668
1669 if (isHoverAction) {
1670 // Started hovering, therefore no longer down.
1671 if (mTouchState.down) {
1672#if DEBUG_FOCUS
1673 LOGD("Conflicting pointer actions: Hover received while pointer was down.");
1674#endif
1675 *outConflictingPointerActions = true;
1676 }
1677 mTouchState.reset();
1678 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER
1679 || maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
1680 mTouchState.deviceId = entry->deviceId;
1681 mTouchState.source = entry->source;
1682 }
1683 } else if (maskedAction == AMOTION_EVENT_ACTION_UP
1684 || maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Jeff Brown95712852011-01-04 19:41:59 -08001685 // All pointers up or canceled.
Jeff Brown33bbfd22011-02-24 20:55:35 -08001686 mTouchState.reset();
Jeff Brown95712852011-01-04 19:41:59 -08001687 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1688 // First pointer went down.
1689 if (mTouchState.down) {
Jeff Brownb6997262010-10-08 22:31:17 -07001690#if DEBUG_FOCUS
Jeff Brown81346812011-06-28 20:08:48 -07001691 LOGD("Conflicting pointer actions: Down received while already down.");
Jeff Brownb6997262010-10-08 22:31:17 -07001692#endif
Jeff Brown81346812011-06-28 20:08:48 -07001693 *outConflictingPointerActions = true;
Jeff Brown95712852011-01-04 19:41:59 -08001694 }
Jeff Brown33bbfd22011-02-24 20:55:35 -08001695 mTouchState.copyFrom(mTempTouchState);
Jeff Brown95712852011-01-04 19:41:59 -08001696 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
1697 // One pointer went up.
1698 if (isSplit) {
1699 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07001700 uint32_t pointerId = entry->pointerProperties[pointerIndex].id;
Jeff Brownb88102f2010-09-08 11:49:43 -07001701
Jeff Brown95712852011-01-04 19:41:59 -08001702 for (size_t i = 0; i < mTempTouchState.windows.size(); ) {
1703 TouchedWindow& touchedWindow = mTempTouchState.windows.editItemAt(i);
1704 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
1705 touchedWindow.pointerIds.clearBit(pointerId);
1706 if (touchedWindow.pointerIds.isEmpty()) {
1707 mTempTouchState.windows.removeAt(i);
1708 continue;
1709 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001710 }
Jeff Brown95712852011-01-04 19:41:59 -08001711 i += 1;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001712 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001713 }
Jeff Brown33bbfd22011-02-24 20:55:35 -08001714 mTouchState.copyFrom(mTempTouchState);
1715 } else if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
1716 // Discard temporary touch state since it was only valid for this action.
1717 } else {
1718 // Save changes to touch state as-is for all other actions.
1719 mTouchState.copyFrom(mTempTouchState);
Jeff Brownb88102f2010-09-08 11:49:43 -07001720 }
Jeff Browna032cc02011-03-07 16:56:21 -08001721
1722 // Update hover state.
Jeff Brown9302c872011-07-13 22:51:29 -07001723 mLastHoverWindowHandle = newHoverWindowHandle;
Jeff Brown95712852011-01-04 19:41:59 -08001724 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001725 } else {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001726#if DEBUG_FOCUS
1727 LOGD("Not updating touch focus because injection was denied.");
1728#endif
Jeff Brownb88102f2010-09-08 11:49:43 -07001729 }
1730
1731Unresponsive:
Jeff Brown120a4592010-10-27 18:43:51 -07001732 // Reset temporary touch state to ensure we release unnecessary references to input channels.
1733 mTempTouchState.reset();
1734
Jeff Brown519e0242010-09-15 15:18:56 -07001735 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
1736 updateDispatchStatisticsLocked(currentTime, entry,
1737 injectionResult, timeSpentWaitingForApplication);
Jeff Brownb88102f2010-09-08 11:49:43 -07001738#if DEBUG_FOCUS
Jeff Brown01ce2e92010-09-26 22:20:12 -07001739 LOGD("findTouchedWindow finished: injectionResult=%d, injectionPermission=%d, "
1740 "timeSpentWaitingForApplication=%0.1fms",
Jeff Brown519e0242010-09-15 15:18:56 -07001741 injectionResult, injectionPermission, timeSpentWaitingForApplication / 1000000.0);
Jeff Brownb88102f2010-09-08 11:49:43 -07001742#endif
1743 return injectionResult;
1744}
1745
Jeff Brown9302c872011-07-13 22:51:29 -07001746void InputDispatcher::addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
1747 int32_t targetFlags, BitSet32 pointerIds) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001748 mCurrentInputTargets.push();
1749
Jeff Browncc4f7db2011-08-30 20:34:48 -07001750 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Jeff Brownb88102f2010-09-08 11:49:43 -07001751 InputTarget& target = mCurrentInputTargets.editTop();
Jeff Browncc4f7db2011-08-30 20:34:48 -07001752 target.inputChannel = windowInfo->inputChannel;
Jeff Brownb88102f2010-09-08 11:49:43 -07001753 target.flags = targetFlags;
Jeff Browncc4f7db2011-08-30 20:34:48 -07001754 target.xOffset = - windowInfo->frameLeft;
1755 target.yOffset = - windowInfo->frameTop;
1756 target.scaleFactor = windowInfo->scaleFactor;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001757 target.pointerIds = pointerIds;
Jeff Brownb88102f2010-09-08 11:49:43 -07001758}
1759
1760void InputDispatcher::addMonitoringTargetsLocked() {
1761 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
1762 mCurrentInputTargets.push();
1763
1764 InputTarget& target = mCurrentInputTargets.editTop();
1765 target.inputChannel = mMonitoringChannels[i];
Jeff Brownb6110c22011-04-01 16:15:13 -07001766 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
Jeff Brownb88102f2010-09-08 11:49:43 -07001767 target.xOffset = 0;
1768 target.yOffset = 0;
Jeff Brownb6110c22011-04-01 16:15:13 -07001769 target.pointerIds.clear();
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001770 target.scaleFactor = 1.0f;
Jeff Brownb88102f2010-09-08 11:49:43 -07001771 }
1772}
1773
Jeff Brown9302c872011-07-13 22:51:29 -07001774bool InputDispatcher::checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
Jeff Brown01ce2e92010-09-26 22:20:12 -07001775 const InjectionState* injectionState) {
1776 if (injectionState
Jeff Browncc4f7db2011-08-30 20:34:48 -07001777 && (windowHandle == NULL
1778 || windowHandle->getInfo()->ownerUid != injectionState->injectorUid)
Jeff Brownb6997262010-10-08 22:31:17 -07001779 && !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Jeff Brown9302c872011-07-13 22:51:29 -07001780 if (windowHandle != NULL) {
1781 LOGW("Permission denied: injecting event from pid %d uid %d to window %s "
1782 "owned by uid %d",
Jeff Brownb6997262010-10-08 22:31:17 -07001783 injectionState->injectorPid, injectionState->injectorUid,
Jeff Browncc4f7db2011-08-30 20:34:48 -07001784 windowHandle->getName().string(),
1785 windowHandle->getInfo()->ownerUid);
Jeff Brownb6997262010-10-08 22:31:17 -07001786 } else {
1787 LOGW("Permission denied: injecting event from pid %d uid %d",
1788 injectionState->injectorPid, injectionState->injectorUid);
Jeff Brownb88102f2010-09-08 11:49:43 -07001789 }
Jeff Brownb6997262010-10-08 22:31:17 -07001790 return false;
Jeff Brownb88102f2010-09-08 11:49:43 -07001791 }
1792 return true;
1793}
1794
Jeff Brown19dfc832010-10-05 12:26:23 -07001795bool InputDispatcher::isWindowObscuredAtPointLocked(
Jeff Brown9302c872011-07-13 22:51:29 -07001796 const sp<InputWindowHandle>& windowHandle, int32_t x, int32_t y) const {
1797 size_t numWindows = mWindowHandles.size();
Jeff Brownb88102f2010-09-08 11:49:43 -07001798 for (size_t i = 0; i < numWindows; i++) {
Jeff Brown9302c872011-07-13 22:51:29 -07001799 sp<InputWindowHandle> otherHandle = mWindowHandles.itemAt(i);
1800 if (otherHandle == windowHandle) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001801 break;
1802 }
Jeff Browncc4f7db2011-08-30 20:34:48 -07001803
1804 const InputWindowInfo* otherInfo = otherHandle->getInfo();
1805 if (otherInfo->visible && ! otherInfo->isTrustedOverlay()
1806 && otherInfo->frameContainsPoint(x, y)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001807 return true;
1808 }
1809 }
1810 return false;
1811}
1812
Jeff Brown9302c872011-07-13 22:51:29 -07001813bool InputDispatcher::isWindowFinishedWithPreviousInputLocked(
1814 const sp<InputWindowHandle>& windowHandle) {
Jeff Browncc4f7db2011-08-30 20:34:48 -07001815 ssize_t connectionIndex = getConnectionIndexLocked(windowHandle->getInputChannel());
Jeff Brown519e0242010-09-15 15:18:56 -07001816 if (connectionIndex >= 0) {
1817 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
1818 return connection->outboundQueue.isEmpty();
1819 } else {
1820 return true;
1821 }
1822}
1823
Jeff Brown9302c872011-07-13 22:51:29 -07001824String8 InputDispatcher::getApplicationWindowLabelLocked(
1825 const sp<InputApplicationHandle>& applicationHandle,
1826 const sp<InputWindowHandle>& windowHandle) {
1827 if (applicationHandle != NULL) {
1828 if (windowHandle != NULL) {
Jeff Browncc4f7db2011-08-30 20:34:48 -07001829 String8 label(applicationHandle->getName());
Jeff Brown519e0242010-09-15 15:18:56 -07001830 label.append(" - ");
Jeff Browncc4f7db2011-08-30 20:34:48 -07001831 label.append(windowHandle->getName());
Jeff Brown519e0242010-09-15 15:18:56 -07001832 return label;
1833 } else {
Jeff Browncc4f7db2011-08-30 20:34:48 -07001834 return applicationHandle->getName();
Jeff Brown519e0242010-09-15 15:18:56 -07001835 }
Jeff Brown9302c872011-07-13 22:51:29 -07001836 } else if (windowHandle != NULL) {
Jeff Browncc4f7db2011-08-30 20:34:48 -07001837 return windowHandle->getName();
Jeff Brown519e0242010-09-15 15:18:56 -07001838 } else {
1839 return String8("<unknown application or window>");
1840 }
1841}
1842
Jeff Browne2fe69e2010-10-18 13:21:23 -07001843void InputDispatcher::pokeUserActivityLocked(const EventEntry* eventEntry) {
Jeff Brown56194eb2011-03-02 19:23:13 -08001844 int32_t eventType = POWER_MANAGER_OTHER_EVENT;
Jeff Brown4d396052010-10-29 21:50:21 -07001845 switch (eventEntry->type) {
1846 case EventEntry::TYPE_MOTION: {
Jeff Browne2fe69e2010-10-18 13:21:23 -07001847 const MotionEntry* motionEntry = static_cast<const MotionEntry*>(eventEntry);
Jeff Brown4d396052010-10-29 21:50:21 -07001848 if (motionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
1849 return;
1850 }
1851
Jeff Brown56194eb2011-03-02 19:23:13 -08001852 if (MotionEvent::isTouchEvent(motionEntry->source, motionEntry->action)) {
Joe Onorato1a542c72010-11-08 09:48:20 -08001853 eventType = POWER_MANAGER_TOUCH_EVENT;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001854 }
Jeff Brown4d396052010-10-29 21:50:21 -07001855 break;
1856 }
1857 case EventEntry::TYPE_KEY: {
1858 const KeyEntry* keyEntry = static_cast<const KeyEntry*>(eventEntry);
1859 if (keyEntry->flags & AKEY_EVENT_FLAG_CANCELED) {
1860 return;
1861 }
Jeff Brown56194eb2011-03-02 19:23:13 -08001862 eventType = POWER_MANAGER_BUTTON_EVENT;
Jeff Brown4d396052010-10-29 21:50:21 -07001863 break;
1864 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001865 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001866
Jeff Brownb88102f2010-09-08 11:49:43 -07001867 CommandEntry* commandEntry = postCommandLocked(
1868 & InputDispatcher::doPokeUserActivityLockedInterruptible);
Jeff Browne2fe69e2010-10-18 13:21:23 -07001869 commandEntry->eventTime = eventEntry->eventTime;
Jeff Brownb88102f2010-09-08 11:49:43 -07001870 commandEntry->userActivityEventType = eventType;
1871}
1872
Jeff Brown7fbdc842010-06-17 20:52:56 -07001873void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
1874 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget,
Jeff Brown46b9ac02010-04-22 18:58:52 -07001875 bool resumeWithAppendedMotionSample) {
1876#if DEBUG_DISPATCH_CYCLE
Jeff Brown9cc695c2011-08-23 18:35:04 -07001877 LOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
1878 "xOffset=%f, yOffset=%f, scaleFactor=%f, "
Jeff Brown83c09682010-12-23 17:50:18 -08001879 "pointerIds=0x%x, "
Jeff Brown01ce2e92010-09-26 22:20:12 -07001880 "resumeWithAppendedMotionSample=%s",
Jeff Brown519e0242010-09-15 15:18:56 -07001881 connection->getInputChannelName(), inputTarget->flags,
Jeff Brown46b9ac02010-04-22 18:58:52 -07001882 inputTarget->xOffset, inputTarget->yOffset,
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001883 inputTarget->scaleFactor, inputTarget->pointerIds.value,
Jeff Brownb88102f2010-09-08 11:49:43 -07001884 toString(resumeWithAppendedMotionSample));
Jeff Brown46b9ac02010-04-22 18:58:52 -07001885#endif
1886
Jeff Brown01ce2e92010-09-26 22:20:12 -07001887 // Make sure we are never called for streaming when splitting across multiple windows.
1888 bool isSplit = inputTarget->flags & InputTarget::FLAG_SPLIT;
Jeff Brownb6110c22011-04-01 16:15:13 -07001889 LOG_ASSERT(! (resumeWithAppendedMotionSample && isSplit));
Jeff Brown01ce2e92010-09-26 22:20:12 -07001890
Jeff Brown46b9ac02010-04-22 18:58:52 -07001891 // Skip this event if the connection status is not normal.
Jeff Brown519e0242010-09-15 15:18:56 -07001892 // We don't want to enqueue additional outbound events if the connection is broken.
Jeff Brown46b9ac02010-04-22 18:58:52 -07001893 if (connection->status != Connection::STATUS_NORMAL) {
Jeff Brownb6997262010-10-08 22:31:17 -07001894#if DEBUG_DISPATCH_CYCLE
1895 LOGD("channel '%s' ~ Dropping event because the channel status is %s",
Jeff Brownb88102f2010-09-08 11:49:43 -07001896 connection->getInputChannelName(), connection->getStatusLabel());
Jeff Brownb6997262010-10-08 22:31:17 -07001897#endif
Jeff Brown46b9ac02010-04-22 18:58:52 -07001898 return;
1899 }
1900
Jeff Brown01ce2e92010-09-26 22:20:12 -07001901 // Split a motion event if needed.
1902 if (isSplit) {
Jeff Brownb6110c22011-04-01 16:15:13 -07001903 LOG_ASSERT(eventEntry->type == EventEntry::TYPE_MOTION);
Jeff Brown01ce2e92010-09-26 22:20:12 -07001904
1905 MotionEntry* originalMotionEntry = static_cast<MotionEntry*>(eventEntry);
1906 if (inputTarget->pointerIds.count() != originalMotionEntry->pointerCount) {
1907 MotionEntry* splitMotionEntry = splitMotionEvent(
1908 originalMotionEntry, inputTarget->pointerIds);
Jeff Brown58a2da82011-01-25 16:02:22 -08001909 if (!splitMotionEntry) {
1910 return; // split event was dropped
1911 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001912#if DEBUG_FOCUS
1913 LOGD("channel '%s' ~ Split motion event.",
1914 connection->getInputChannelName());
1915 logOutboundMotionDetailsLocked(" ", splitMotionEntry);
1916#endif
1917 eventEntry = splitMotionEntry;
1918 }
1919 }
1920
Jeff Brown46b9ac02010-04-22 18:58:52 -07001921 // Resume the dispatch cycle with a freshly appended motion sample.
1922 // First we check that the last dispatch entry in the outbound queue is for the same
1923 // motion event to which we appended the motion sample. If we find such a dispatch
1924 // entry, and if it is currently in progress then we try to stream the new sample.
1925 bool wasEmpty = connection->outboundQueue.isEmpty();
1926
1927 if (! wasEmpty && resumeWithAppendedMotionSample) {
1928 DispatchEntry* motionEventDispatchEntry =
1929 connection->findQueuedDispatchEntryForEvent(eventEntry);
1930 if (motionEventDispatchEntry) {
1931 // If the dispatch entry is not in progress, then we must be busy dispatching an
1932 // earlier event. Not a problem, the motion event is on the outbound queue and will
1933 // be dispatched later.
1934 if (! motionEventDispatchEntry->inProgress) {
1935#if DEBUG_BATCHING
1936 LOGD("channel '%s' ~ Not streaming because the motion event has "
1937 "not yet been dispatched. "
1938 "(Waiting for earlier events to be consumed.)",
1939 connection->getInputChannelName());
1940#endif
1941 return;
1942 }
1943
1944 // If the dispatch entry is in progress but it already has a tail of pending
1945 // motion samples, then it must mean that the shared memory buffer filled up.
1946 // Not a problem, when this dispatch cycle is finished, we will eventually start
1947 // a new dispatch cycle to process the tail and that tail includes the newly
1948 // appended motion sample.
1949 if (motionEventDispatchEntry->tailMotionSample) {
1950#if DEBUG_BATCHING
1951 LOGD("channel '%s' ~ Not streaming because no new samples can "
1952 "be appended to the motion event in this dispatch cycle. "
1953 "(Waiting for next dispatch cycle to start.)",
1954 connection->getInputChannelName());
1955#endif
1956 return;
1957 }
1958
Jeff Brown81346812011-06-28 20:08:48 -07001959 // If the motion event was modified in flight, then we cannot stream the sample.
1960 if ((motionEventDispatchEntry->targetFlags & InputTarget::FLAG_DISPATCH_MASK)
1961 != InputTarget::FLAG_DISPATCH_AS_IS) {
1962#if DEBUG_BATCHING
1963 LOGD("channel '%s' ~ Not streaming because the motion event was not "
1964 "being dispatched as-is. "
1965 "(Waiting for next dispatch cycle to start.)",
1966 connection->getInputChannelName());
1967#endif
1968 return;
1969 }
1970
Jeff Brown46b9ac02010-04-22 18:58:52 -07001971 // The dispatch entry is in progress and is still potentially open for streaming.
1972 // Try to stream the new motion sample. This might fail if the consumer has already
1973 // consumed the motion event (or if the channel is broken).
Jeff Brown01ce2e92010-09-26 22:20:12 -07001974 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
1975 MotionSample* appendedMotionSample = motionEntry->lastSample;
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001976 status_t status;
1977 if (motionEventDispatchEntry->scaleFactor == 1.0f) {
1978 status = connection->inputPublisher.appendMotionSample(
1979 appendedMotionSample->eventTime, appendedMotionSample->pointerCoords);
1980 } else {
1981 PointerCoords scaledCoords[MAX_POINTERS];
1982 for (size_t i = 0; i < motionEntry->pointerCount; i++) {
1983 scaledCoords[i] = appendedMotionSample->pointerCoords[i];
1984 scaledCoords[i].scale(motionEventDispatchEntry->scaleFactor);
1985 }
1986 status = connection->inputPublisher.appendMotionSample(
1987 appendedMotionSample->eventTime, scaledCoords);
1988 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07001989 if (status == OK) {
1990#if DEBUG_BATCHING
1991 LOGD("channel '%s' ~ Successfully streamed new motion sample.",
1992 connection->getInputChannelName());
1993#endif
1994 return;
1995 }
1996
1997#if DEBUG_BATCHING
1998 if (status == NO_MEMORY) {
1999 LOGD("channel '%s' ~ Could not append motion sample to currently "
2000 "dispatched move event because the shared memory buffer is full. "
2001 "(Waiting for next dispatch cycle to start.)",
2002 connection->getInputChannelName());
2003 } else if (status == status_t(FAILED_TRANSACTION)) {
2004 LOGD("channel '%s' ~ Could not append motion sample to currently "
Jeff Brown349703e2010-06-22 01:27:15 -07002005 "dispatched move event because the event has already been consumed. "
Jeff Brown46b9ac02010-04-22 18:58:52 -07002006 "(Waiting for next dispatch cycle to start.)",
2007 connection->getInputChannelName());
2008 } else {
2009 LOGD("channel '%s' ~ Could not append motion sample to currently "
2010 "dispatched move event due to an error, status=%d. "
2011 "(Waiting for next dispatch cycle to start.)",
2012 connection->getInputChannelName(), status);
2013 }
2014#endif
2015 // Failed to stream. Start a new tail of pending motion samples to dispatch
2016 // in the next cycle.
2017 motionEventDispatchEntry->tailMotionSample = appendedMotionSample;
2018 return;
2019 }
2020 }
2021
Jeff Browna032cc02011-03-07 16:56:21 -08002022 // Enqueue dispatch entries for the requested modes.
2023 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
2024 resumeWithAppendedMotionSample, InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
2025 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
2026 resumeWithAppendedMotionSample, InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
2027 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
2028 resumeWithAppendedMotionSample, InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
2029 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
2030 resumeWithAppendedMotionSample, InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brown98db5fa2011-06-08 15:37:10 -07002031 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
2032 resumeWithAppendedMotionSample, InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
2033 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
2034 resumeWithAppendedMotionSample, InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Jeff Browna032cc02011-03-07 16:56:21 -08002035
2036 // If the outbound queue was previously empty, start the dispatch cycle going.
Jeff Brownb6110c22011-04-01 16:15:13 -07002037 if (wasEmpty && !connection->outboundQueue.isEmpty()) {
Jeff Browna032cc02011-03-07 16:56:21 -08002038 activateConnectionLocked(connection.get());
2039 startDispatchCycleLocked(currentTime, connection);
2040 }
2041}
2042
2043void InputDispatcher::enqueueDispatchEntryLocked(
2044 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget,
2045 bool resumeWithAppendedMotionSample, int32_t dispatchMode) {
2046 int32_t inputTargetFlags = inputTarget->flags;
2047 if (!(inputTargetFlags & dispatchMode)) {
2048 return;
2049 }
2050 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
2051
Jeff Brown46b9ac02010-04-22 18:58:52 -07002052 // This is a new event.
2053 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Jeff Brownac386072011-07-20 15:19:50 -07002054 DispatchEntry* dispatchEntry = new DispatchEntry(eventEntry, // increments ref
Dianne Hackbornaa9d84c2011-05-09 19:00:59 -07002055 inputTargetFlags, inputTarget->xOffset, inputTarget->yOffset,
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002056 inputTarget->scaleFactor);
Jeff Brown519e0242010-09-15 15:18:56 -07002057 if (dispatchEntry->hasForegroundTarget()) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002058 incrementPendingForegroundDispatchesLocked(eventEntry);
Jeff Brown6ec402b2010-07-28 15:48:59 -07002059 }
2060
Jeff Brown46b9ac02010-04-22 18:58:52 -07002061 // Handle the case where we could not stream a new motion sample because the consumer has
2062 // already consumed the motion event (otherwise the corresponding dispatch entry would
2063 // still be in the outbound queue for this connection). We set the head motion sample
2064 // to the list starting with the newly appended motion sample.
2065 if (resumeWithAppendedMotionSample) {
2066#if DEBUG_BATCHING
2067 LOGD("channel '%s' ~ Preparing a new dispatch cycle for additional motion samples "
2068 "that cannot be streamed because the motion event has already been consumed.",
2069 connection->getInputChannelName());
2070#endif
2071 MotionSample* appendedMotionSample = static_cast<MotionEntry*>(eventEntry)->lastSample;
2072 dispatchEntry->headMotionSample = appendedMotionSample;
2073 }
2074
Jeff Brown81346812011-06-28 20:08:48 -07002075 // Apply target flags and update the connection's input state.
2076 switch (eventEntry->type) {
2077 case EventEntry::TYPE_KEY: {
2078 KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
2079 dispatchEntry->resolvedAction = keyEntry->action;
2080 dispatchEntry->resolvedFlags = keyEntry->flags;
2081
2082 if (!connection->inputState.trackKey(keyEntry,
2083 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags)) {
2084#if DEBUG_DISPATCH_CYCLE
2085 LOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
2086 connection->getInputChannelName());
2087#endif
2088 return; // skip the inconsistent event
2089 }
2090 break;
2091 }
2092
2093 case EventEntry::TYPE_MOTION: {
2094 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
2095 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2096 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
2097 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
2098 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
2099 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
2100 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2101 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
2102 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
2103 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
2104 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
2105 } else {
2106 dispatchEntry->resolvedAction = motionEntry->action;
2107 }
2108 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE
2109 && !connection->inputState.isHovering(
2110 motionEntry->deviceId, motionEntry->source)) {
2111#if DEBUG_DISPATCH_CYCLE
2112 LOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter event",
2113 connection->getInputChannelName());
2114#endif
2115 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2116 }
2117
2118 dispatchEntry->resolvedFlags = motionEntry->flags;
2119 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
2120 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
2121 }
2122
2123 if (!connection->inputState.trackMotion(motionEntry,
2124 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags)) {
2125#if DEBUG_DISPATCH_CYCLE
2126 LOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion event",
2127 connection->getInputChannelName());
2128#endif
2129 return; // skip the inconsistent event
2130 }
2131 break;
2132 }
2133 }
2134
Jeff Brown46b9ac02010-04-22 18:58:52 -07002135 // Enqueue the dispatch entry.
2136 connection->outboundQueue.enqueueAtTail(dispatchEntry);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002137}
2138
Jeff Brown7fbdc842010-06-17 20:52:56 -07002139void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Jeff Brown519e0242010-09-15 15:18:56 -07002140 const sp<Connection>& connection) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002141#if DEBUG_DISPATCH_CYCLE
2142 LOGD("channel '%s' ~ startDispatchCycle",
2143 connection->getInputChannelName());
2144#endif
2145
Jeff Brownb6110c22011-04-01 16:15:13 -07002146 LOG_ASSERT(connection->status == Connection::STATUS_NORMAL);
2147 LOG_ASSERT(! connection->outboundQueue.isEmpty());
Jeff Brown46b9ac02010-04-22 18:58:52 -07002148
Jeff Brownac386072011-07-20 15:19:50 -07002149 DispatchEntry* dispatchEntry = connection->outboundQueue.head;
Jeff Brownb6110c22011-04-01 16:15:13 -07002150 LOG_ASSERT(! dispatchEntry->inProgress);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002151
Jeff Brownb88102f2010-09-08 11:49:43 -07002152 // Mark the dispatch entry as in progress.
2153 dispatchEntry->inProgress = true;
2154
Jeff Brown46b9ac02010-04-22 18:58:52 -07002155 // Publish the event.
2156 status_t status;
Jeff Browna032cc02011-03-07 16:56:21 -08002157 EventEntry* eventEntry = dispatchEntry->eventEntry;
Jeff Brown01ce2e92010-09-26 22:20:12 -07002158 switch (eventEntry->type) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002159 case EventEntry::TYPE_KEY: {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002160 KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002161
Jeff Brown46b9ac02010-04-22 18:58:52 -07002162 // Publish the key event.
Jeff Brown81346812011-06-28 20:08:48 -07002163 status = connection->inputPublisher.publishKeyEvent(
2164 keyEntry->deviceId, keyEntry->source,
2165 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags,
2166 keyEntry->keyCode, keyEntry->scanCode,
Jeff Brown46b9ac02010-04-22 18:58:52 -07002167 keyEntry->metaState, keyEntry->repeatCount, keyEntry->downTime,
2168 keyEntry->eventTime);
2169
2170 if (status) {
2171 LOGE("channel '%s' ~ Could not publish key event, "
2172 "status=%d", connection->getInputChannelName(), status);
Jeff Browncc4f7db2011-08-30 20:34:48 -07002173 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002174 return;
2175 }
2176 break;
2177 }
2178
2179 case EventEntry::TYPE_MOTION: {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002180 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002181
Jeff Brown46b9ac02010-04-22 18:58:52 -07002182 // If headMotionSample is non-NULL, then it points to the first new sample that we
2183 // were unable to dispatch during the previous cycle so we resume dispatching from
2184 // that point in the list of motion samples.
2185 // Otherwise, we just start from the first sample of the motion event.
2186 MotionSample* firstMotionSample = dispatchEntry->headMotionSample;
2187 if (! firstMotionSample) {
2188 firstMotionSample = & motionEntry->firstSample;
2189 }
2190
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002191 PointerCoords scaledCoords[MAX_POINTERS];
2192 const PointerCoords* usingCoords = firstMotionSample->pointerCoords;
2193
Jeff Brownd3616592010-07-16 17:21:06 -07002194 // Set the X and Y offset depending on the input source.
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002195 float xOffset, yOffset, scaleFactor;
Kenny Root7a9db182011-06-02 15:16:05 -07002196 if (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER
2197 && !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002198 scaleFactor = dispatchEntry->scaleFactor;
2199 xOffset = dispatchEntry->xOffset * scaleFactor;
2200 yOffset = dispatchEntry->yOffset * scaleFactor;
2201 if (scaleFactor != 1.0f) {
2202 for (size_t i = 0; i < motionEntry->pointerCount; i++) {
2203 scaledCoords[i] = firstMotionSample->pointerCoords[i];
2204 scaledCoords[i].scale(scaleFactor);
2205 }
2206 usingCoords = scaledCoords;
2207 }
Jeff Brownd3616592010-07-16 17:21:06 -07002208 } else {
2209 xOffset = 0.0f;
2210 yOffset = 0.0f;
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002211 scaleFactor = 1.0f;
Kenny Root7a9db182011-06-02 15:16:05 -07002212
2213 // We don't want the dispatch target to know.
2214 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
2215 for (size_t i = 0; i < motionEntry->pointerCount; i++) {
2216 scaledCoords[i].clear();
2217 }
2218 usingCoords = scaledCoords;
2219 }
Jeff Brownd3616592010-07-16 17:21:06 -07002220 }
2221
Jeff Brown46b9ac02010-04-22 18:58:52 -07002222 // Publish the motion event and the first motion sample.
Jeff Brown81346812011-06-28 20:08:48 -07002223 status = connection->inputPublisher.publishMotionEvent(
2224 motionEntry->deviceId, motionEntry->source,
2225 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags,
2226 motionEntry->edgeFlags, motionEntry->metaState, motionEntry->buttonState,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002227 xOffset, yOffset,
2228 motionEntry->xPrecision, motionEntry->yPrecision,
Jeff Brown46b9ac02010-04-22 18:58:52 -07002229 motionEntry->downTime, firstMotionSample->eventTime,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002230 motionEntry->pointerCount, motionEntry->pointerProperties,
2231 usingCoords);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002232
2233 if (status) {
2234 LOGE("channel '%s' ~ Could not publish motion event, "
2235 "status=%d", connection->getInputChannelName(), status);
Jeff Browncc4f7db2011-08-30 20:34:48 -07002236 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002237 return;
2238 }
2239
Jeff Brown81346812011-06-28 20:08:48 -07002240 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_MOVE
2241 || dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Jeff Browna032cc02011-03-07 16:56:21 -08002242 // Append additional motion samples.
2243 MotionSample* nextMotionSample = firstMotionSample->next;
2244 for (; nextMotionSample != NULL; nextMotionSample = nextMotionSample->next) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002245 if (usingCoords == scaledCoords) {
Kenny Root7a9db182011-06-02 15:16:05 -07002246 if (!(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
2247 for (size_t i = 0; i < motionEntry->pointerCount; i++) {
2248 scaledCoords[i] = nextMotionSample->pointerCoords[i];
2249 scaledCoords[i].scale(scaleFactor);
2250 }
Dianne Hackborn2ba3e802011-05-11 10:59:54 -07002251 }
2252 } else {
2253 usingCoords = nextMotionSample->pointerCoords;
Dianne Hackborne7d25b72011-05-09 21:19:26 -07002254 }
Jeff Browna032cc02011-03-07 16:56:21 -08002255 status = connection->inputPublisher.appendMotionSample(
Dianne Hackbornaa9d84c2011-05-09 19:00:59 -07002256 nextMotionSample->eventTime, usingCoords);
Jeff Browna032cc02011-03-07 16:56:21 -08002257 if (status == NO_MEMORY) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002258#if DEBUG_DISPATCH_CYCLE
2259 LOGD("channel '%s' ~ Shared memory buffer full. Some motion samples will "
2260 "be sent in the next dispatch cycle.",
2261 connection->getInputChannelName());
2262#endif
Jeff Browna032cc02011-03-07 16:56:21 -08002263 break;
2264 }
2265 if (status != OK) {
2266 LOGE("channel '%s' ~ Could not append motion sample "
2267 "for a reason other than out of memory, status=%d",
2268 connection->getInputChannelName(), status);
Jeff Browncc4f7db2011-08-30 20:34:48 -07002269 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
Jeff Browna032cc02011-03-07 16:56:21 -08002270 return;
2271 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002272 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002273
Jeff Browna032cc02011-03-07 16:56:21 -08002274 // Remember the next motion sample that we could not dispatch, in case we ran out
2275 // of space in the shared memory buffer.
2276 dispatchEntry->tailMotionSample = nextMotionSample;
2277 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002278 break;
2279 }
2280
2281 default: {
Jeff Brownb6110c22011-04-01 16:15:13 -07002282 LOG_ASSERT(false);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002283 }
2284 }
2285
2286 // Send the dispatch signal.
2287 status = connection->inputPublisher.sendDispatchSignal();
2288 if (status) {
2289 LOGE("channel '%s' ~ Could not send dispatch signal, status=%d",
2290 connection->getInputChannelName(), status);
Jeff Browncc4f7db2011-08-30 20:34:48 -07002291 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002292 return;
2293 }
2294
2295 // Record information about the newly started dispatch cycle.
Jeff Brown01ce2e92010-09-26 22:20:12 -07002296 connection->lastEventTime = eventEntry->eventTime;
Jeff Brown46b9ac02010-04-22 18:58:52 -07002297 connection->lastDispatchTime = currentTime;
2298
Jeff Brown46b9ac02010-04-22 18:58:52 -07002299 // Notify other system components.
2300 onDispatchCycleStartedLocked(currentTime, connection);
2301}
2302
Jeff Brown7fbdc842010-06-17 20:52:56 -07002303void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Jeff Brown3915bb82010-11-05 15:02:16 -07002304 const sp<Connection>& connection, bool handled) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002305#if DEBUG_DISPATCH_CYCLE
Jeff Brown9c3cda02010-06-15 01:31:58 -07002306 LOGD("channel '%s' ~ finishDispatchCycle - %01.1fms since event, "
Jeff Brown3915bb82010-11-05 15:02:16 -07002307 "%01.1fms since dispatch, handled=%s",
Jeff Brown46b9ac02010-04-22 18:58:52 -07002308 connection->getInputChannelName(),
2309 connection->getEventLatencyMillis(currentTime),
Jeff Brown3915bb82010-11-05 15:02:16 -07002310 connection->getDispatchLatencyMillis(currentTime),
2311 toString(handled));
Jeff Brown46b9ac02010-04-22 18:58:52 -07002312#endif
2313
Jeff Brown9c3cda02010-06-15 01:31:58 -07002314 if (connection->status == Connection::STATUS_BROKEN
2315 || connection->status == Connection::STATUS_ZOMBIE) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002316 return;
2317 }
2318
Jeff Brown46b9ac02010-04-22 18:58:52 -07002319 // Reset the publisher since the event has been consumed.
2320 // We do this now so that the publisher can release some of its internal resources
2321 // while waiting for the next dispatch cycle to begin.
2322 status_t status = connection->inputPublisher.reset();
2323 if (status) {
2324 LOGE("channel '%s' ~ Could not reset publisher, status=%d",
2325 connection->getInputChannelName(), status);
Jeff Browncc4f7db2011-08-30 20:34:48 -07002326 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002327 return;
2328 }
2329
Jeff Brown3915bb82010-11-05 15:02:16 -07002330 // Notify other system components and prepare to start the next dispatch cycle.
2331 onDispatchCycleFinishedLocked(currentTime, connection, handled);
Jeff Brownb88102f2010-09-08 11:49:43 -07002332}
2333
2334void InputDispatcher::startNextDispatchCycleLocked(nsecs_t currentTime,
2335 const sp<Connection>& connection) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002336 // Start the next dispatch cycle for this connection.
2337 while (! connection->outboundQueue.isEmpty()) {
Jeff Brownac386072011-07-20 15:19:50 -07002338 DispatchEntry* dispatchEntry = connection->outboundQueue.head;
Jeff Brown46b9ac02010-04-22 18:58:52 -07002339 if (dispatchEntry->inProgress) {
2340 // Finish or resume current event in progress.
2341 if (dispatchEntry->tailMotionSample) {
2342 // We have a tail of undispatched motion samples.
2343 // Reuse the same DispatchEntry and start a new cycle.
2344 dispatchEntry->inProgress = false;
2345 dispatchEntry->headMotionSample = dispatchEntry->tailMotionSample;
2346 dispatchEntry->tailMotionSample = NULL;
Jeff Brown519e0242010-09-15 15:18:56 -07002347 startDispatchCycleLocked(currentTime, connection);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002348 return;
2349 }
2350 // Finished.
2351 connection->outboundQueue.dequeueAtHead();
Jeff Brown519e0242010-09-15 15:18:56 -07002352 if (dispatchEntry->hasForegroundTarget()) {
2353 decrementPendingForegroundDispatchesLocked(dispatchEntry->eventEntry);
Jeff Brown6ec402b2010-07-28 15:48:59 -07002354 }
Jeff Brownac386072011-07-20 15:19:50 -07002355 delete dispatchEntry;
Jeff Brown46b9ac02010-04-22 18:58:52 -07002356 } else {
2357 // If the head is not in progress, then we must have already dequeued the in
Jeff Brown519e0242010-09-15 15:18:56 -07002358 // progress event, which means we actually aborted it.
Jeff Brown46b9ac02010-04-22 18:58:52 -07002359 // So just start the next event for this connection.
Jeff Brown519e0242010-09-15 15:18:56 -07002360 startDispatchCycleLocked(currentTime, connection);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002361 return;
2362 }
2363 }
2364
2365 // Outbound queue is empty, deactivate the connection.
Jeff Brown7fbdc842010-06-17 20:52:56 -07002366 deactivateConnectionLocked(connection.get());
Jeff Brown46b9ac02010-04-22 18:58:52 -07002367}
2368
Jeff Brownb6997262010-10-08 22:31:17 -07002369void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Jeff Browncc4f7db2011-08-30 20:34:48 -07002370 const sp<Connection>& connection, bool notify) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002371#if DEBUG_DISPATCH_CYCLE
Jeff Browncc4f7db2011-08-30 20:34:48 -07002372 LOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
2373 connection->getInputChannelName(), toString(notify));
Jeff Brown46b9ac02010-04-22 18:58:52 -07002374#endif
2375
Jeff Brownb88102f2010-09-08 11:49:43 -07002376 // Clear the outbound queue.
Jeff Brown519e0242010-09-15 15:18:56 -07002377 drainOutboundQueueLocked(connection.get());
Jeff Brown46b9ac02010-04-22 18:58:52 -07002378
Jeff Brownb6997262010-10-08 22:31:17 -07002379 // The connection appears to be unrecoverably broken.
Jeff Brown9c3cda02010-06-15 01:31:58 -07002380 // Ignore already broken or zombie connections.
Jeff Brownb6997262010-10-08 22:31:17 -07002381 if (connection->status == Connection::STATUS_NORMAL) {
2382 connection->status = Connection::STATUS_BROKEN;
Jeff Brown46b9ac02010-04-22 18:58:52 -07002383
Jeff Browncc4f7db2011-08-30 20:34:48 -07002384 if (notify) {
2385 // Notify other system components.
2386 onDispatchCycleBrokenLocked(currentTime, connection);
2387 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002388 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002389}
2390
Jeff Brown519e0242010-09-15 15:18:56 -07002391void InputDispatcher::drainOutboundQueueLocked(Connection* connection) {
2392 while (! connection->outboundQueue.isEmpty()) {
2393 DispatchEntry* dispatchEntry = connection->outboundQueue.dequeueAtHead();
2394 if (dispatchEntry->hasForegroundTarget()) {
2395 decrementPendingForegroundDispatchesLocked(dispatchEntry->eventEntry);
Jeff Brownb88102f2010-09-08 11:49:43 -07002396 }
Jeff Brownac386072011-07-20 15:19:50 -07002397 delete dispatchEntry;
Jeff Brownb88102f2010-09-08 11:49:43 -07002398 }
2399
Jeff Brown519e0242010-09-15 15:18:56 -07002400 deactivateConnectionLocked(connection);
Jeff Brownb88102f2010-09-08 11:49:43 -07002401}
2402
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002403int InputDispatcher::handleReceiveCallback(int receiveFd, int events, void* data) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002404 InputDispatcher* d = static_cast<InputDispatcher*>(data);
2405
2406 { // acquire lock
2407 AutoMutex _l(d->mLock);
2408
2409 ssize_t connectionIndex = d->mConnectionsByReceiveFd.indexOfKey(receiveFd);
2410 if (connectionIndex < 0) {
2411 LOGE("Received spurious receive callback for unknown input channel. "
2412 "fd=%d, events=0x%x", receiveFd, events);
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002413 return 0; // remove the callback
Jeff Brown46b9ac02010-04-22 18:58:52 -07002414 }
2415
Jeff Browncc4f7db2011-08-30 20:34:48 -07002416 bool notify;
Jeff Brown46b9ac02010-04-22 18:58:52 -07002417 sp<Connection> connection = d->mConnectionsByReceiveFd.valueAt(connectionIndex);
Jeff Browncc4f7db2011-08-30 20:34:48 -07002418 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
2419 if (!(events & ALOOPER_EVENT_INPUT)) {
2420 LOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
2421 "events=0x%x", connection->getInputChannelName(), events);
2422 return 1;
2423 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002424
Jeff Browncc4f7db2011-08-30 20:34:48 -07002425 bool handled = false;
2426 status_t status = connection->inputPublisher.receiveFinishedSignal(&handled);
2427 if (!status) {
2428 nsecs_t currentTime = now();
2429 d->finishDispatchCycleLocked(currentTime, connection, handled);
2430 d->runCommandsLockedInterruptible();
2431 return 1;
2432 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002433
Jeff Brown46b9ac02010-04-22 18:58:52 -07002434 LOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
2435 connection->getInputChannelName(), status);
Jeff Browncc4f7db2011-08-30 20:34:48 -07002436 notify = true;
2437 } else {
2438 // Monitor channels are never explicitly unregistered.
2439 // We do it automatically when the remote endpoint is closed so don't warn
2440 // about them.
2441 notify = !connection->monitor;
2442 if (notify) {
2443 LOGW("channel '%s' ~ Consumer closed input channel or an error occurred. "
2444 "events=0x%x", connection->getInputChannelName(), events);
2445 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002446 }
2447
Jeff Browncc4f7db2011-08-30 20:34:48 -07002448 // Unregister the channel.
2449 d->unregisterInputChannelLocked(connection->inputChannel, notify);
2450 return 0; // remove the callback
Jeff Brown46b9ac02010-04-22 18:58:52 -07002451 } // release lock
2452}
2453
Jeff Brownb6997262010-10-08 22:31:17 -07002454void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Jeff Brownda3d5a92011-03-29 15:11:34 -07002455 const CancelationOptions& options) {
Jeff Brownb6997262010-10-08 22:31:17 -07002456 for (size_t i = 0; i < mConnectionsByReceiveFd.size(); i++) {
2457 synthesizeCancelationEventsForConnectionLocked(
Jeff Brownda3d5a92011-03-29 15:11:34 -07002458 mConnectionsByReceiveFd.valueAt(i), options);
Jeff Brownb6997262010-10-08 22:31:17 -07002459 }
2460}
2461
2462void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Jeff Brownda3d5a92011-03-29 15:11:34 -07002463 const sp<InputChannel>& channel, const CancelationOptions& options) {
Jeff Brownb6997262010-10-08 22:31:17 -07002464 ssize_t index = getConnectionIndexLocked(channel);
2465 if (index >= 0) {
2466 synthesizeCancelationEventsForConnectionLocked(
Jeff Brownda3d5a92011-03-29 15:11:34 -07002467 mConnectionsByReceiveFd.valueAt(index), options);
Jeff Brownb6997262010-10-08 22:31:17 -07002468 }
2469}
2470
2471void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
Jeff Brownda3d5a92011-03-29 15:11:34 -07002472 const sp<Connection>& connection, const CancelationOptions& options) {
Jeff Brownb6997262010-10-08 22:31:17 -07002473 nsecs_t currentTime = now();
2474
2475 mTempCancelationEvents.clear();
Jeff Brownac386072011-07-20 15:19:50 -07002476 connection->inputState.synthesizeCancelationEvents(currentTime,
Jeff Brownb6997262010-10-08 22:31:17 -07002477 mTempCancelationEvents, options);
2478
2479 if (! mTempCancelationEvents.isEmpty()
2480 && connection->status != Connection::STATUS_BROKEN) {
2481#if DEBUG_OUTBOUND_EVENT_DETAILS
2482 LOGD("channel '%s' ~ Synthesized %d cancelation events to bring channel back in sync "
Jeff Brownda3d5a92011-03-29 15:11:34 -07002483 "with reality: %s, mode=%d.",
2484 connection->getInputChannelName(), mTempCancelationEvents.size(),
2485 options.reason, options.mode);
Jeff Brownb6997262010-10-08 22:31:17 -07002486#endif
2487 for (size_t i = 0; i < mTempCancelationEvents.size(); i++) {
2488 EventEntry* cancelationEventEntry = mTempCancelationEvents.itemAt(i);
2489 switch (cancelationEventEntry->type) {
2490 case EventEntry::TYPE_KEY:
2491 logOutboundKeyDetailsLocked("cancel - ",
2492 static_cast<KeyEntry*>(cancelationEventEntry));
2493 break;
2494 case EventEntry::TYPE_MOTION:
2495 logOutboundMotionDetailsLocked("cancel - ",
2496 static_cast<MotionEntry*>(cancelationEventEntry));
2497 break;
2498 }
2499
Jeff Brown81346812011-06-28 20:08:48 -07002500 InputTarget target;
Jeff Brown9302c872011-07-13 22:51:29 -07002501 sp<InputWindowHandle> windowHandle = getWindowHandleLocked(connection->inputChannel);
2502 if (windowHandle != NULL) {
Jeff Browncc4f7db2011-08-30 20:34:48 -07002503 const InputWindowInfo* windowInfo = windowHandle->getInfo();
2504 target.xOffset = -windowInfo->frameLeft;
2505 target.yOffset = -windowInfo->frameTop;
2506 target.scaleFactor = windowInfo->scaleFactor;
Jeff Brownb6997262010-10-08 22:31:17 -07002507 } else {
Jeff Brown81346812011-06-28 20:08:48 -07002508 target.xOffset = 0;
2509 target.yOffset = 0;
2510 target.scaleFactor = 1.0f;
Jeff Brownb6997262010-10-08 22:31:17 -07002511 }
Jeff Brown81346812011-06-28 20:08:48 -07002512 target.inputChannel = connection->inputChannel;
2513 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
Jeff Brownb6997262010-10-08 22:31:17 -07002514
Jeff Brown81346812011-06-28 20:08:48 -07002515 enqueueDispatchEntryLocked(connection, cancelationEventEntry, // increments ref
2516 &target, false, InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brownb6997262010-10-08 22:31:17 -07002517
Jeff Brownac386072011-07-20 15:19:50 -07002518 cancelationEventEntry->release();
Jeff Brownb6997262010-10-08 22:31:17 -07002519 }
2520
Jeff Brownac386072011-07-20 15:19:50 -07002521 if (!connection->outboundQueue.head->inProgress) {
Jeff Brownb6997262010-10-08 22:31:17 -07002522 startDispatchCycleLocked(currentTime, connection);
2523 }
2524 }
2525}
2526
Jeff Brown01ce2e92010-09-26 22:20:12 -07002527InputDispatcher::MotionEntry*
2528InputDispatcher::splitMotionEvent(const MotionEntry* originalMotionEntry, BitSet32 pointerIds) {
Jeff Brownb6110c22011-04-01 16:15:13 -07002529 LOG_ASSERT(pointerIds.value != 0);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002530
2531 uint32_t splitPointerIndexMap[MAX_POINTERS];
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002532 PointerProperties splitPointerProperties[MAX_POINTERS];
Jeff Brown01ce2e92010-09-26 22:20:12 -07002533 PointerCoords splitPointerCoords[MAX_POINTERS];
2534
2535 uint32_t originalPointerCount = originalMotionEntry->pointerCount;
2536 uint32_t splitPointerCount = 0;
2537
2538 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
2539 originalPointerIndex++) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002540 const PointerProperties& pointerProperties =
2541 originalMotionEntry->pointerProperties[originalPointerIndex];
2542 uint32_t pointerId = uint32_t(pointerProperties.id);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002543 if (pointerIds.hasBit(pointerId)) {
2544 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002545 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
Jeff Brownace13b12011-03-09 17:39:48 -08002546 splitPointerCoords[splitPointerCount].copyFrom(
2547 originalMotionEntry->firstSample.pointerCoords[originalPointerIndex]);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002548 splitPointerCount += 1;
2549 }
2550 }
Jeff Brown58a2da82011-01-25 16:02:22 -08002551
2552 if (splitPointerCount != pointerIds.count()) {
2553 // This is bad. We are missing some of the pointers that we expected to deliver.
2554 // Most likely this indicates that we received an ACTION_MOVE events that has
2555 // different pointer ids than we expected based on the previous ACTION_DOWN
2556 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
2557 // in this way.
2558 LOGW("Dropping split motion event because the pointer count is %d but "
2559 "we expected there to be %d pointers. This probably means we received "
2560 "a broken sequence of pointer ids from the input device.",
2561 splitPointerCount, pointerIds.count());
2562 return NULL;
2563 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07002564
2565 int32_t action = originalMotionEntry->action;
2566 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
2567 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
2568 || maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2569 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002570 const PointerProperties& pointerProperties =
2571 originalMotionEntry->pointerProperties[originalPointerIndex];
2572 uint32_t pointerId = uint32_t(pointerProperties.id);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002573 if (pointerIds.hasBit(pointerId)) {
2574 if (pointerIds.count() == 1) {
2575 // The first/last pointer went down/up.
2576 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
2577 ? AMOTION_EVENT_ACTION_DOWN : AMOTION_EVENT_ACTION_UP;
Jeff Brown9a01d052010-09-27 16:35:11 -07002578 } else {
2579 // A secondary pointer went down/up.
2580 uint32_t splitPointerIndex = 0;
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002581 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
Jeff Brown9a01d052010-09-27 16:35:11 -07002582 splitPointerIndex += 1;
2583 }
2584 action = maskedAction | (splitPointerIndex
2585 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002586 }
2587 } else {
2588 // An unrelated pointer changed.
2589 action = AMOTION_EVENT_ACTION_MOVE;
2590 }
2591 }
2592
Jeff Brownac386072011-07-20 15:19:50 -07002593 MotionEntry* splitMotionEntry = new MotionEntry(
Jeff Brown01ce2e92010-09-26 22:20:12 -07002594 originalMotionEntry->eventTime,
2595 originalMotionEntry->deviceId,
2596 originalMotionEntry->source,
2597 originalMotionEntry->policyFlags,
2598 action,
2599 originalMotionEntry->flags,
2600 originalMotionEntry->metaState,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002601 originalMotionEntry->buttonState,
Jeff Brown01ce2e92010-09-26 22:20:12 -07002602 originalMotionEntry->edgeFlags,
2603 originalMotionEntry->xPrecision,
2604 originalMotionEntry->yPrecision,
2605 originalMotionEntry->downTime,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002606 splitPointerCount, splitPointerProperties, splitPointerCoords);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002607
2608 for (MotionSample* originalMotionSample = originalMotionEntry->firstSample.next;
2609 originalMotionSample != NULL; originalMotionSample = originalMotionSample->next) {
2610 for (uint32_t splitPointerIndex = 0; splitPointerIndex < splitPointerCount;
2611 splitPointerIndex++) {
2612 uint32_t originalPointerIndex = splitPointerIndexMap[splitPointerIndex];
Jeff Brownace13b12011-03-09 17:39:48 -08002613 splitPointerCoords[splitPointerIndex].copyFrom(
2614 originalMotionSample->pointerCoords[originalPointerIndex]);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002615 }
2616
Jeff Brownac386072011-07-20 15:19:50 -07002617 splitMotionEntry->appendSample(originalMotionSample->eventTime, splitPointerCoords);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002618 }
2619
Jeff Browna032cc02011-03-07 16:56:21 -08002620 if (originalMotionEntry->injectionState) {
2621 splitMotionEntry->injectionState = originalMotionEntry->injectionState;
2622 splitMotionEntry->injectionState->refCount += 1;
2623 }
2624
Jeff Brown01ce2e92010-09-26 22:20:12 -07002625 return splitMotionEntry;
2626}
2627
Jeff Brownbe1aa822011-07-27 16:04:54 -07002628void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002629#if DEBUG_INBOUND_EVENT_DETAILS
Jeff Brownbe1aa822011-07-27 16:04:54 -07002630 LOGD("notifyConfigurationChanged - eventTime=%lld", args->eventTime);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002631#endif
2632
Jeff Brownb88102f2010-09-08 11:49:43 -07002633 bool needWake;
Jeff Brown46b9ac02010-04-22 18:58:52 -07002634 { // acquire lock
2635 AutoMutex _l(mLock);
2636
Jeff Brownbe1aa822011-07-27 16:04:54 -07002637 ConfigurationChangedEntry* newEntry = new ConfigurationChangedEntry(args->eventTime);
Jeff Brownb88102f2010-09-08 11:49:43 -07002638 needWake = enqueueInboundEventLocked(newEntry);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002639 } // release lock
2640
Jeff Brownb88102f2010-09-08 11:49:43 -07002641 if (needWake) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002642 mLooper->wake();
Jeff Brown46b9ac02010-04-22 18:58:52 -07002643 }
2644}
2645
Jeff Brownbe1aa822011-07-27 16:04:54 -07002646void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002647#if DEBUG_INBOUND_EVENT_DETAILS
Jeff Brown90655042010-12-02 13:50:46 -08002648 LOGD("notifyKey - eventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, action=0x%x, "
Jeff Brown46b9ac02010-04-22 18:58:52 -07002649 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%lld",
Jeff Brownbe1aa822011-07-27 16:04:54 -07002650 args->eventTime, args->deviceId, args->source, args->policyFlags,
2651 args->action, args->flags, args->keyCode, args->scanCode,
2652 args->metaState, args->downTime);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002653#endif
Jeff Brownbe1aa822011-07-27 16:04:54 -07002654 if (!validateKeyEvent(args->action)) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002655 return;
2656 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002657
Jeff Brownbe1aa822011-07-27 16:04:54 -07002658 uint32_t policyFlags = args->policyFlags;
2659 int32_t flags = args->flags;
2660 int32_t metaState = args->metaState;
Jeff Brown1f245102010-11-18 20:53:46 -08002661 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
2662 policyFlags |= POLICY_FLAG_VIRTUAL;
2663 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
2664 }
Jeff Brown924c4d42011-03-07 16:40:47 -08002665 if (policyFlags & POLICY_FLAG_ALT) {
2666 metaState |= AMETA_ALT_ON | AMETA_ALT_LEFT_ON;
2667 }
2668 if (policyFlags & POLICY_FLAG_ALT_GR) {
2669 metaState |= AMETA_ALT_ON | AMETA_ALT_RIGHT_ON;
2670 }
2671 if (policyFlags & POLICY_FLAG_SHIFT) {
2672 metaState |= AMETA_SHIFT_ON | AMETA_SHIFT_LEFT_ON;
2673 }
2674 if (policyFlags & POLICY_FLAG_CAPS_LOCK) {
2675 metaState |= AMETA_CAPS_LOCK_ON;
2676 }
2677 if (policyFlags & POLICY_FLAG_FUNCTION) {
2678 metaState |= AMETA_FUNCTION_ON;
2679 }
Jeff Brown1f245102010-11-18 20:53:46 -08002680
Jeff Browne20c9e02010-10-11 14:20:19 -07002681 policyFlags |= POLICY_FLAG_TRUSTED;
Jeff Brown1f245102010-11-18 20:53:46 -08002682
2683 KeyEvent event;
Jeff Brownbe1aa822011-07-27 16:04:54 -07002684 event.initialize(args->deviceId, args->source, args->action,
2685 flags, args->keyCode, args->scanCode, metaState, 0,
2686 args->downTime, args->eventTime);
Jeff Brown1f245102010-11-18 20:53:46 -08002687
2688 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
2689
2690 if (policyFlags & POLICY_FLAG_WOKE_HERE) {
2691 flags |= AKEY_EVENT_FLAG_WOKE_HERE;
2692 }
Jeff Brownb6997262010-10-08 22:31:17 -07002693
Jeff Brownb88102f2010-09-08 11:49:43 -07002694 bool needWake;
Jeff Brown46b9ac02010-04-22 18:58:52 -07002695 { // acquire lock
Jeff Brown0029c662011-03-30 02:25:18 -07002696 mLock.lock();
2697
2698 if (mInputFilterEnabled) {
2699 mLock.unlock();
2700
2701 policyFlags |= POLICY_FLAG_FILTERED;
2702 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2703 return; // event was consumed by the filter
2704 }
2705
2706 mLock.lock();
2707 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002708
Jeff Brown7fbdc842010-06-17 20:52:56 -07002709 int32_t repeatCount = 0;
Jeff Brownbe1aa822011-07-27 16:04:54 -07002710 KeyEntry* newEntry = new KeyEntry(args->eventTime,
2711 args->deviceId, args->source, policyFlags,
2712 args->action, flags, args->keyCode, args->scanCode,
2713 metaState, repeatCount, args->downTime);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002714
Jeff Brownb88102f2010-09-08 11:49:43 -07002715 needWake = enqueueInboundEventLocked(newEntry);
Jeff Brown0029c662011-03-30 02:25:18 -07002716 mLock.unlock();
Jeff Brown46b9ac02010-04-22 18:58:52 -07002717 } // release lock
2718
Jeff Brownb88102f2010-09-08 11:49:43 -07002719 if (needWake) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002720 mLooper->wake();
Jeff Brown46b9ac02010-04-22 18:58:52 -07002721 }
2722}
2723
Jeff Brownbe1aa822011-07-27 16:04:54 -07002724void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002725#if DEBUG_INBOUND_EVENT_DETAILS
Jeff Brown90655042010-12-02 13:50:46 -08002726 LOGD("notifyMotion - eventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, "
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002727 "action=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, edgeFlags=0x%x, "
Jeff Brown85a31762010-09-01 17:01:00 -07002728 "xPrecision=%f, yPrecision=%f, downTime=%lld",
Jeff Brownbe1aa822011-07-27 16:04:54 -07002729 args->eventTime, args->deviceId, args->source, args->policyFlags,
2730 args->action, args->flags, args->metaState, args->buttonState,
2731 args->edgeFlags, args->xPrecision, args->yPrecision, args->downTime);
2732 for (uint32_t i = 0; i < args->pointerCount; i++) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002733 LOGD(" Pointer %d: id=%d, toolType=%d, "
2734 "x=%f, y=%f, pressure=%f, size=%f, "
Jeff Brown85a31762010-09-01 17:01:00 -07002735 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
Jeff Brown8d608662010-08-30 03:02:23 -07002736 "orientation=%f",
Jeff Brownbe1aa822011-07-27 16:04:54 -07002737 i, args->pointerProperties[i].id,
2738 args->pointerProperties[i].toolType,
2739 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
2740 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
2741 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
2742 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
2743 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
2744 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
2745 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
2746 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
2747 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Jeff Brown46b9ac02010-04-22 18:58:52 -07002748 }
2749#endif
Jeff Brownbe1aa822011-07-27 16:04:54 -07002750 if (!validateMotionEvent(args->action, args->pointerCount, args->pointerProperties)) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002751 return;
2752 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002753
Jeff Brownbe1aa822011-07-27 16:04:54 -07002754 uint32_t policyFlags = args->policyFlags;
Jeff Browne20c9e02010-10-11 14:20:19 -07002755 policyFlags |= POLICY_FLAG_TRUSTED;
Jeff Brownbe1aa822011-07-27 16:04:54 -07002756 mPolicy->interceptMotionBeforeQueueing(args->eventTime, /*byref*/ policyFlags);
Jeff Brownb6997262010-10-08 22:31:17 -07002757
Jeff Brownb88102f2010-09-08 11:49:43 -07002758 bool needWake;
Jeff Brown46b9ac02010-04-22 18:58:52 -07002759 { // acquire lock
Jeff Brown0029c662011-03-30 02:25:18 -07002760 mLock.lock();
2761
2762 if (mInputFilterEnabled) {
2763 mLock.unlock();
2764
2765 MotionEvent event;
Jeff Brownbe1aa822011-07-27 16:04:54 -07002766 event.initialize(args->deviceId, args->source, args->action, args->flags,
2767 args->edgeFlags, args->metaState, args->buttonState, 0, 0,
2768 args->xPrecision, args->yPrecision,
2769 args->downTime, args->eventTime,
2770 args->pointerCount, args->pointerProperties, args->pointerCoords);
Jeff Brown0029c662011-03-30 02:25:18 -07002771
2772 policyFlags |= POLICY_FLAG_FILTERED;
2773 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2774 return; // event was consumed by the filter
2775 }
2776
2777 mLock.lock();
2778 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002779
2780 // Attempt batching and streaming of move events.
Jeff Brownbe1aa822011-07-27 16:04:54 -07002781 if (args->action == AMOTION_EVENT_ACTION_MOVE
2782 || args->action == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002783 // BATCHING CASE
2784 //
2785 // Try to append a move sample to the tail of the inbound queue for this device.
2786 // Give up if we encounter a non-move motion event for this device since that
2787 // means we cannot append any new samples until a new motion event has started.
Jeff Brownac386072011-07-20 15:19:50 -07002788 for (EventEntry* entry = mInboundQueue.tail; entry; entry = entry->prev) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002789 if (entry->type != EventEntry::TYPE_MOTION) {
2790 // Keep looking for motion events.
2791 continue;
2792 }
2793
2794 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
Jeff Brownbe1aa822011-07-27 16:04:54 -07002795 if (motionEntry->deviceId != args->deviceId
2796 || motionEntry->source != args->source) {
Jeff Brownefd32662011-03-08 15:13:06 -08002797 // Keep looking for this device and source.
Jeff Brown46b9ac02010-04-22 18:58:52 -07002798 continue;
2799 }
2800
Jeff Brownbe1aa822011-07-27 16:04:54 -07002801 if (!motionEntry->canAppendSamples(args->action,
2802 args->pointerCount, args->pointerProperties)) {
Jeff Brownefd32662011-03-08 15:13:06 -08002803 // Last motion event in the queue for this device and source is
2804 // not compatible for appending new samples. Stop here.
Jeff Brown46b9ac02010-04-22 18:58:52 -07002805 goto NoBatchingOrStreaming;
2806 }
2807
Jeff Brown9c3cda02010-06-15 01:31:58 -07002808 // Do the batching magic.
Jeff Brownbe1aa822011-07-27 16:04:54 -07002809 batchMotionLocked(motionEntry, args->eventTime,
2810 args->metaState, args->pointerCoords,
Jeff Brown4e91a182011-04-07 11:38:09 -07002811 "most recent motion event for this device and source in the inbound queue");
Jeff Brown0029c662011-03-30 02:25:18 -07002812 mLock.unlock();
Jeff Brown9c3cda02010-06-15 01:31:58 -07002813 return; // done!
Jeff Brown46b9ac02010-04-22 18:58:52 -07002814 }
2815
Jeff Brownf6989da2011-04-06 17:19:48 -07002816 // BATCHING ONTO PENDING EVENT CASE
2817 //
2818 // Try to append a move sample to the currently pending event, if there is one.
2819 // We can do this as long as we are still waiting to find the targets for the
2820 // event. Once the targets are locked-in we can only do streaming.
2821 if (mPendingEvent
2822 && (!mPendingEvent->dispatchInProgress || !mCurrentInputTargetsValid)
2823 && mPendingEvent->type == EventEntry::TYPE_MOTION) {
2824 MotionEntry* motionEntry = static_cast<MotionEntry*>(mPendingEvent);
Jeff Brownbe1aa822011-07-27 16:04:54 -07002825 if (motionEntry->deviceId == args->deviceId
2826 && motionEntry->source == args->source) {
2827 if (!motionEntry->canAppendSamples(args->action,
2828 args->pointerCount, args->pointerProperties)) {
Jeff Brown4e91a182011-04-07 11:38:09 -07002829 // Pending motion event is for this device and source but it is
2830 // not compatible for appending new samples. Stop here.
Jeff Brownf6989da2011-04-06 17:19:48 -07002831 goto NoBatchingOrStreaming;
2832 }
2833
Jeff Brownf6989da2011-04-06 17:19:48 -07002834 // Do the batching magic.
Jeff Brownbe1aa822011-07-27 16:04:54 -07002835 batchMotionLocked(motionEntry, args->eventTime,
2836 args->metaState, args->pointerCoords,
Jeff Brown4e91a182011-04-07 11:38:09 -07002837 "pending motion event");
Jeff Brownf6989da2011-04-06 17:19:48 -07002838 mLock.unlock();
2839 return; // done!
2840 }
2841 }
2842
Jeff Brown46b9ac02010-04-22 18:58:52 -07002843 // STREAMING CASE
2844 //
2845 // There is no pending motion event (of any kind) for this device in the inbound queue.
Jeff Brown519e0242010-09-15 15:18:56 -07002846 // Search the outbound queue for the current foreground targets to find a dispatched
2847 // motion event that is still in progress. If found, then, appen the new sample to
2848 // that event and push it out to all current targets. The logic in
2849 // prepareDispatchCycleLocked takes care of the case where some targets may
2850 // already have consumed the motion event by starting a new dispatch cycle if needed.
Jeff Brown9c3cda02010-06-15 01:31:58 -07002851 if (mCurrentInputTargetsValid) {
Jeff Brown519e0242010-09-15 15:18:56 -07002852 for (size_t i = 0; i < mCurrentInputTargets.size(); i++) {
2853 const InputTarget& inputTarget = mCurrentInputTargets[i];
2854 if ((inputTarget.flags & InputTarget::FLAG_FOREGROUND) == 0) {
2855 // Skip non-foreground targets. We only want to stream if there is at
2856 // least one foreground target whose dispatch is still in progress.
2857 continue;
Jeff Brown46b9ac02010-04-22 18:58:52 -07002858 }
Jeff Brown519e0242010-09-15 15:18:56 -07002859
2860 ssize_t connectionIndex = getConnectionIndexLocked(inputTarget.inputChannel);
2861 if (connectionIndex < 0) {
2862 // Connection must no longer be valid.
2863 continue;
2864 }
2865
2866 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
2867 if (connection->outboundQueue.isEmpty()) {
2868 // This foreground target has an empty outbound queue.
2869 continue;
2870 }
2871
Jeff Brownac386072011-07-20 15:19:50 -07002872 DispatchEntry* dispatchEntry = connection->outboundQueue.head;
Jeff Brown519e0242010-09-15 15:18:56 -07002873 if (! dispatchEntry->inProgress
Jeff Brown01ce2e92010-09-26 22:20:12 -07002874 || dispatchEntry->eventEntry->type != EventEntry::TYPE_MOTION
2875 || dispatchEntry->isSplit()) {
2876 // No motion event is being dispatched, or it is being split across
2877 // windows in which case we cannot stream.
Jeff Brown519e0242010-09-15 15:18:56 -07002878 continue;
2879 }
2880
2881 MotionEntry* motionEntry = static_cast<MotionEntry*>(
2882 dispatchEntry->eventEntry);
Jeff Brownbe1aa822011-07-27 16:04:54 -07002883 if (motionEntry->action != args->action
2884 || motionEntry->deviceId != args->deviceId
2885 || motionEntry->source != args->source
2886 || motionEntry->pointerCount != args->pointerCount
Jeff Brown519e0242010-09-15 15:18:56 -07002887 || motionEntry->isInjected()) {
2888 // The motion event is not compatible with this move.
2889 continue;
2890 }
2891
Jeff Brownbe1aa822011-07-27 16:04:54 -07002892 if (args->action == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Jeff Brown9302c872011-07-13 22:51:29 -07002893 if (mLastHoverWindowHandle == NULL) {
Jeff Browna032cc02011-03-07 16:56:21 -08002894#if DEBUG_BATCHING
2895 LOGD("Not streaming hover move because there is no "
2896 "last hovered window.");
2897#endif
2898 goto NoBatchingOrStreaming;
2899 }
2900
Jeff Brown9302c872011-07-13 22:51:29 -07002901 sp<InputWindowHandle> hoverWindowHandle = findTouchedWindowAtLocked(
Jeff Brownbe1aa822011-07-27 16:04:54 -07002902 args->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X),
2903 args->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Jeff Brown9302c872011-07-13 22:51:29 -07002904 if (mLastHoverWindowHandle != hoverWindowHandle) {
Jeff Browna032cc02011-03-07 16:56:21 -08002905#if DEBUG_BATCHING
2906 LOGD("Not streaming hover move because the last hovered window "
2907 "is '%s' but the currently hovered window is '%s'.",
Jeff Browncc4f7db2011-08-30 20:34:48 -07002908 mLastHoverWindowHandle->getName().string(),
Jeff Brown9302c872011-07-13 22:51:29 -07002909 hoverWindowHandle != NULL
Jeff Browncc4f7db2011-08-30 20:34:48 -07002910 ? hoverWindowHandle->getName().string() : "<null>");
Jeff Browna032cc02011-03-07 16:56:21 -08002911#endif
2912 goto NoBatchingOrStreaming;
2913 }
2914 }
2915
Jeff Brown519e0242010-09-15 15:18:56 -07002916 // Hurray! This foreground target is currently dispatching a move event
2917 // that we can stream onto. Append the motion sample and resume dispatch.
Jeff Brownbe1aa822011-07-27 16:04:54 -07002918 motionEntry->appendSample(args->eventTime, args->pointerCoords);
Jeff Brown519e0242010-09-15 15:18:56 -07002919#if DEBUG_BATCHING
2920 LOGD("Appended motion sample onto batch for most recently dispatched "
Jeff Brown4e91a182011-04-07 11:38:09 -07002921 "motion event for this device and source in the outbound queues. "
Jeff Brown519e0242010-09-15 15:18:56 -07002922 "Attempting to stream the motion sample.");
2923#endif
2924 nsecs_t currentTime = now();
2925 dispatchEventToCurrentInputTargetsLocked(currentTime, motionEntry,
2926 true /*resumeWithAppendedMotionSample*/);
2927
2928 runCommandsLockedInterruptible();
Jeff Brown0029c662011-03-30 02:25:18 -07002929 mLock.unlock();
Jeff Brown519e0242010-09-15 15:18:56 -07002930 return; // done!
Jeff Brown46b9ac02010-04-22 18:58:52 -07002931 }
2932 }
2933
2934NoBatchingOrStreaming:;
2935 }
2936
2937 // Just enqueue a new motion event.
Jeff Brownbe1aa822011-07-27 16:04:54 -07002938 MotionEntry* newEntry = new MotionEntry(args->eventTime,
2939 args->deviceId, args->source, policyFlags,
2940 args->action, args->flags, args->metaState, args->buttonState,
2941 args->edgeFlags, args->xPrecision, args->yPrecision, args->downTime,
2942 args->pointerCount, args->pointerProperties, args->pointerCoords);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002943
Jeff Brownb88102f2010-09-08 11:49:43 -07002944 needWake = enqueueInboundEventLocked(newEntry);
Jeff Brown0029c662011-03-30 02:25:18 -07002945 mLock.unlock();
Jeff Brown46b9ac02010-04-22 18:58:52 -07002946 } // release lock
2947
Jeff Brownb88102f2010-09-08 11:49:43 -07002948 if (needWake) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002949 mLooper->wake();
Jeff Brown46b9ac02010-04-22 18:58:52 -07002950 }
2951}
2952
Jeff Brown4e91a182011-04-07 11:38:09 -07002953void InputDispatcher::batchMotionLocked(MotionEntry* entry, nsecs_t eventTime,
2954 int32_t metaState, const PointerCoords* pointerCoords, const char* eventDescription) {
2955 // Combine meta states.
2956 entry->metaState |= metaState;
2957
2958 // Coalesce this sample if not enough time has elapsed since the last sample was
2959 // initially appended to the batch.
2960 MotionSample* lastSample = entry->lastSample;
2961 long interval = eventTime - lastSample->eventTimeBeforeCoalescing;
2962 if (interval <= MOTION_SAMPLE_COALESCE_INTERVAL) {
2963 uint32_t pointerCount = entry->pointerCount;
2964 for (uint32_t i = 0; i < pointerCount; i++) {
2965 lastSample->pointerCoords[i].copyFrom(pointerCoords[i]);
2966 }
2967 lastSample->eventTime = eventTime;
2968#if DEBUG_BATCHING
2969 LOGD("Coalesced motion into last sample of batch for %s, events were %0.3f ms apart",
2970 eventDescription, interval * 0.000001f);
2971#endif
2972 return;
2973 }
2974
2975 // Append the sample.
Jeff Brownac386072011-07-20 15:19:50 -07002976 entry->appendSample(eventTime, pointerCoords);
Jeff Brown4e91a182011-04-07 11:38:09 -07002977#if DEBUG_BATCHING
2978 LOGD("Appended motion sample onto batch for %s, events were %0.3f ms apart",
2979 eventDescription, interval * 0.000001f);
2980#endif
2981}
2982
Jeff Brownbe1aa822011-07-27 16:04:54 -07002983void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
Jeff Brownb6997262010-10-08 22:31:17 -07002984#if DEBUG_INBOUND_EVENT_DETAILS
Jeff Brownbe1aa822011-07-27 16:04:54 -07002985 LOGD("notifySwitch - eventTime=%lld, policyFlags=0x%x, switchCode=%d, switchValue=%d",
2986 args->eventTime, args->policyFlags,
2987 args->switchCode, args->switchValue);
Jeff Brownb6997262010-10-08 22:31:17 -07002988#endif
2989
Jeff Brownbe1aa822011-07-27 16:04:54 -07002990 uint32_t policyFlags = args->policyFlags;
Jeff Browne20c9e02010-10-11 14:20:19 -07002991 policyFlags |= POLICY_FLAG_TRUSTED;
Jeff Brownbe1aa822011-07-27 16:04:54 -07002992 mPolicy->notifySwitch(args->eventTime,
2993 args->switchCode, args->switchValue, policyFlags);
Jeff Brownb6997262010-10-08 22:31:17 -07002994}
2995
Jeff Brown65fd2512011-08-18 11:20:58 -07002996void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
2997#if DEBUG_INBOUND_EVENT_DETAILS
2998 LOGD("notifyDeviceReset - eventTime=%lld, deviceId=%d",
2999 args->eventTime, args->deviceId);
3000#endif
3001
3002 bool needWake;
3003 { // acquire lock
3004 AutoMutex _l(mLock);
3005
3006 DeviceResetEntry* newEntry = new DeviceResetEntry(args->eventTime, args->deviceId);
3007 needWake = enqueueInboundEventLocked(newEntry);
3008 } // release lock
3009
3010 if (needWake) {
3011 mLooper->wake();
3012 }
3013}
3014
Jeff Brown7fbdc842010-06-17 20:52:56 -07003015int32_t InputDispatcher::injectInputEvent(const InputEvent* event,
Jeff Brown0029c662011-03-30 02:25:18 -07003016 int32_t injectorPid, int32_t injectorUid, int32_t syncMode, int32_t timeoutMillis,
3017 uint32_t policyFlags) {
Jeff Brown7fbdc842010-06-17 20:52:56 -07003018#if DEBUG_INBOUND_EVENT_DETAILS
3019 LOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Jeff Brown0029c662011-03-30 02:25:18 -07003020 "syncMode=%d, timeoutMillis=%d, policyFlags=0x%08x",
3021 event->getType(), injectorPid, injectorUid, syncMode, timeoutMillis, policyFlags);
Jeff Brown7fbdc842010-06-17 20:52:56 -07003022#endif
3023
3024 nsecs_t endTime = now() + milliseconds_to_nanoseconds(timeoutMillis);
Jeff Browne20c9e02010-10-11 14:20:19 -07003025
Jeff Brown0029c662011-03-30 02:25:18 -07003026 policyFlags |= POLICY_FLAG_INJECTED;
Jeff Browne20c9e02010-10-11 14:20:19 -07003027 if (hasInjectionPermission(injectorPid, injectorUid)) {
3028 policyFlags |= POLICY_FLAG_TRUSTED;
3029 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07003030
Jeff Brownb6997262010-10-08 22:31:17 -07003031 EventEntry* injectedEntry;
3032 switch (event->getType()) {
3033 case AINPUT_EVENT_TYPE_KEY: {
3034 const KeyEvent* keyEvent = static_cast<const KeyEvent*>(event);
3035 int32_t action = keyEvent->getAction();
3036 if (! validateKeyEvent(action)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07003037 return INPUT_EVENT_INJECTION_FAILED;
3038 }
3039
Jeff Brownb6997262010-10-08 22:31:17 -07003040 int32_t flags = keyEvent->getFlags();
Jeff Brown1f245102010-11-18 20:53:46 -08003041 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
3042 policyFlags |= POLICY_FLAG_VIRTUAL;
3043 }
3044
Jeff Brown0029c662011-03-30 02:25:18 -07003045 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3046 mPolicy->interceptKeyBeforeQueueing(keyEvent, /*byref*/ policyFlags);
3047 }
Jeff Brown1f245102010-11-18 20:53:46 -08003048
3049 if (policyFlags & POLICY_FLAG_WOKE_HERE) {
3050 flags |= AKEY_EVENT_FLAG_WOKE_HERE;
3051 }
Jeff Brown6ec402b2010-07-28 15:48:59 -07003052
Jeff Brownb6997262010-10-08 22:31:17 -07003053 mLock.lock();
Jeff Brownac386072011-07-20 15:19:50 -07003054 injectedEntry = new KeyEntry(keyEvent->getEventTime(),
Jeff Brown1f245102010-11-18 20:53:46 -08003055 keyEvent->getDeviceId(), keyEvent->getSource(),
3056 policyFlags, action, flags,
3057 keyEvent->getKeyCode(), keyEvent->getScanCode(), keyEvent->getMetaState(),
Jeff Brownb6997262010-10-08 22:31:17 -07003058 keyEvent->getRepeatCount(), keyEvent->getDownTime());
3059 break;
3060 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07003061
Jeff Brownb6997262010-10-08 22:31:17 -07003062 case AINPUT_EVENT_TYPE_MOTION: {
3063 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
3064 int32_t action = motionEvent->getAction();
3065 size_t pointerCount = motionEvent->getPointerCount();
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003066 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
3067 if (! validateMotionEvent(action, pointerCount, pointerProperties)) {
Jeff Brownb6997262010-10-08 22:31:17 -07003068 return INPUT_EVENT_INJECTION_FAILED;
3069 }
3070
Jeff Brown0029c662011-03-30 02:25:18 -07003071 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3072 nsecs_t eventTime = motionEvent->getEventTime();
3073 mPolicy->interceptMotionBeforeQueueing(eventTime, /*byref*/ policyFlags);
3074 }
Jeff Brownb6997262010-10-08 22:31:17 -07003075
3076 mLock.lock();
3077 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
3078 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
Jeff Brownac386072011-07-20 15:19:50 -07003079 MotionEntry* motionEntry = new MotionEntry(*sampleEventTimes,
Jeff Brownb6997262010-10-08 22:31:17 -07003080 motionEvent->getDeviceId(), motionEvent->getSource(), policyFlags,
3081 action, motionEvent->getFlags(),
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003082 motionEvent->getMetaState(), motionEvent->getButtonState(),
3083 motionEvent->getEdgeFlags(),
Jeff Brownb6997262010-10-08 22:31:17 -07003084 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
3085 motionEvent->getDownTime(), uint32_t(pointerCount),
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003086 pointerProperties, samplePointerCoords);
Jeff Brownb6997262010-10-08 22:31:17 -07003087 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
3088 sampleEventTimes += 1;
3089 samplePointerCoords += pointerCount;
Jeff Brownac386072011-07-20 15:19:50 -07003090 motionEntry->appendSample(*sampleEventTimes, samplePointerCoords);
Jeff Brownb6997262010-10-08 22:31:17 -07003091 }
3092 injectedEntry = motionEntry;
3093 break;
3094 }
3095
3096 default:
3097 LOGW("Cannot inject event of type %d", event->getType());
3098 return INPUT_EVENT_INJECTION_FAILED;
3099 }
3100
Jeff Brownac386072011-07-20 15:19:50 -07003101 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
Jeff Brownb6997262010-10-08 22:31:17 -07003102 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
3103 injectionState->injectionIsAsync = true;
3104 }
3105
3106 injectionState->refCount += 1;
3107 injectedEntry->injectionState = injectionState;
3108
3109 bool needWake = enqueueInboundEventLocked(injectedEntry);
3110 mLock.unlock();
Jeff Brown7fbdc842010-06-17 20:52:56 -07003111
Jeff Brownb88102f2010-09-08 11:49:43 -07003112 if (needWake) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07003113 mLooper->wake();
Jeff Brown7fbdc842010-06-17 20:52:56 -07003114 }
3115
3116 int32_t injectionResult;
3117 { // acquire lock
3118 AutoMutex _l(mLock);
3119
Jeff Brown6ec402b2010-07-28 15:48:59 -07003120 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
3121 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
3122 } else {
3123 for (;;) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07003124 injectionResult = injectionState->injectionResult;
Jeff Brown6ec402b2010-07-28 15:48:59 -07003125 if (injectionResult != INPUT_EVENT_INJECTION_PENDING) {
3126 break;
3127 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07003128
Jeff Brown7fbdc842010-06-17 20:52:56 -07003129 nsecs_t remainingTimeout = endTime - now();
3130 if (remainingTimeout <= 0) {
Jeff Brown6ec402b2010-07-28 15:48:59 -07003131#if DEBUG_INJECTION
3132 LOGD("injectInputEvent - Timed out waiting for injection result "
3133 "to become available.");
3134#endif
Jeff Brown7fbdc842010-06-17 20:52:56 -07003135 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
3136 break;
3137 }
3138
Jeff Brown6ec402b2010-07-28 15:48:59 -07003139 mInjectionResultAvailableCondition.waitRelative(mLock, remainingTimeout);
3140 }
3141
3142 if (injectionResult == INPUT_EVENT_INJECTION_SUCCEEDED
3143 && syncMode == INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07003144 while (injectionState->pendingForegroundDispatches != 0) {
Jeff Brown6ec402b2010-07-28 15:48:59 -07003145#if DEBUG_INJECTION
Jeff Brown519e0242010-09-15 15:18:56 -07003146 LOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
Jeff Brown01ce2e92010-09-26 22:20:12 -07003147 injectionState->pendingForegroundDispatches);
Jeff Brown6ec402b2010-07-28 15:48:59 -07003148#endif
3149 nsecs_t remainingTimeout = endTime - now();
3150 if (remainingTimeout <= 0) {
3151#if DEBUG_INJECTION
Jeff Brown519e0242010-09-15 15:18:56 -07003152 LOGD("injectInputEvent - Timed out waiting for pending foreground "
Jeff Brown6ec402b2010-07-28 15:48:59 -07003153 "dispatches to finish.");
3154#endif
3155 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
3156 break;
3157 }
3158
3159 mInjectionSyncFinishedCondition.waitRelative(mLock, remainingTimeout);
3160 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07003161 }
3162 }
3163
Jeff Brownac386072011-07-20 15:19:50 -07003164 injectionState->release();
Jeff Brown7fbdc842010-06-17 20:52:56 -07003165 } // release lock
3166
Jeff Brown6ec402b2010-07-28 15:48:59 -07003167#if DEBUG_INJECTION
3168 LOGD("injectInputEvent - Finished with result %d. "
3169 "injectorPid=%d, injectorUid=%d",
3170 injectionResult, injectorPid, injectorUid);
3171#endif
3172
Jeff Brown7fbdc842010-06-17 20:52:56 -07003173 return injectionResult;
3174}
3175
Jeff Brownb6997262010-10-08 22:31:17 -07003176bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
3177 return injectorUid == 0
3178 || mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
3179}
3180
Jeff Brown7fbdc842010-06-17 20:52:56 -07003181void InputDispatcher::setInjectionResultLocked(EventEntry* entry, int32_t injectionResult) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07003182 InjectionState* injectionState = entry->injectionState;
3183 if (injectionState) {
Jeff Brown7fbdc842010-06-17 20:52:56 -07003184#if DEBUG_INJECTION
3185 LOGD("Setting input event injection result to %d. "
3186 "injectorPid=%d, injectorUid=%d",
Jeff Brown01ce2e92010-09-26 22:20:12 -07003187 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
Jeff Brown7fbdc842010-06-17 20:52:56 -07003188#endif
3189
Jeff Brown0029c662011-03-30 02:25:18 -07003190 if (injectionState->injectionIsAsync
3191 && !(entry->policyFlags & POLICY_FLAG_FILTERED)) {
Jeff Brown6ec402b2010-07-28 15:48:59 -07003192 // Log the outcome since the injector did not wait for the injection result.
3193 switch (injectionResult) {
3194 case INPUT_EVENT_INJECTION_SUCCEEDED:
3195 LOGV("Asynchronous input event injection succeeded.");
3196 break;
3197 case INPUT_EVENT_INJECTION_FAILED:
3198 LOGW("Asynchronous input event injection failed.");
3199 break;
3200 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
3201 LOGW("Asynchronous input event injection permission denied.");
3202 break;
3203 case INPUT_EVENT_INJECTION_TIMED_OUT:
3204 LOGW("Asynchronous input event injection timed out.");
3205 break;
3206 }
3207 }
3208
Jeff Brown01ce2e92010-09-26 22:20:12 -07003209 injectionState->injectionResult = injectionResult;
Jeff Brown7fbdc842010-06-17 20:52:56 -07003210 mInjectionResultAvailableCondition.broadcast();
3211 }
3212}
3213
Jeff Brown01ce2e92010-09-26 22:20:12 -07003214void InputDispatcher::incrementPendingForegroundDispatchesLocked(EventEntry* entry) {
3215 InjectionState* injectionState = entry->injectionState;
3216 if (injectionState) {
3217 injectionState->pendingForegroundDispatches += 1;
3218 }
3219}
3220
Jeff Brown519e0242010-09-15 15:18:56 -07003221void InputDispatcher::decrementPendingForegroundDispatchesLocked(EventEntry* entry) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07003222 InjectionState* injectionState = entry->injectionState;
3223 if (injectionState) {
3224 injectionState->pendingForegroundDispatches -= 1;
Jeff Brown6ec402b2010-07-28 15:48:59 -07003225
Jeff Brown01ce2e92010-09-26 22:20:12 -07003226 if (injectionState->pendingForegroundDispatches == 0) {
3227 mInjectionSyncFinishedCondition.broadcast();
3228 }
Jeff Brownb88102f2010-09-08 11:49:43 -07003229 }
3230}
3231
Jeff Brown9302c872011-07-13 22:51:29 -07003232sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
3233 const sp<InputChannel>& inputChannel) const {
3234 size_t numWindows = mWindowHandles.size();
3235 for (size_t i = 0; i < numWindows; i++) {
3236 const sp<InputWindowHandle>& windowHandle = mWindowHandles.itemAt(i);
Jeff Browncc4f7db2011-08-30 20:34:48 -07003237 if (windowHandle->getInputChannel() == inputChannel) {
Jeff Brown9302c872011-07-13 22:51:29 -07003238 return windowHandle;
Jeff Brown01ce2e92010-09-26 22:20:12 -07003239 }
3240 }
3241 return NULL;
3242}
3243
Jeff Brown9302c872011-07-13 22:51:29 -07003244bool InputDispatcher::hasWindowHandleLocked(
3245 const sp<InputWindowHandle>& windowHandle) const {
3246 size_t numWindows = mWindowHandles.size();
3247 for (size_t i = 0; i < numWindows; i++) {
3248 if (mWindowHandles.itemAt(i) == windowHandle) {
3249 return true;
3250 }
3251 }
3252 return false;
3253}
3254
3255void InputDispatcher::setInputWindows(const Vector<sp<InputWindowHandle> >& inputWindowHandles) {
Jeff Brownb88102f2010-09-08 11:49:43 -07003256#if DEBUG_FOCUS
3257 LOGD("setInputWindows");
3258#endif
3259 { // acquire lock
3260 AutoMutex _l(mLock);
3261
Jeff Browncc4f7db2011-08-30 20:34:48 -07003262 Vector<sp<InputWindowHandle> > oldWindowHandles = mWindowHandles;
Jeff Brown9302c872011-07-13 22:51:29 -07003263 mWindowHandles = inputWindowHandles;
Jeff Brownb6997262010-10-08 22:31:17 -07003264
Jeff Brown9302c872011-07-13 22:51:29 -07003265 sp<InputWindowHandle> newFocusedWindowHandle;
3266 bool foundHoveredWindow = false;
3267 for (size_t i = 0; i < mWindowHandles.size(); i++) {
3268 const sp<InputWindowHandle>& windowHandle = mWindowHandles.itemAt(i);
Jeff Browncc4f7db2011-08-30 20:34:48 -07003269 if (!windowHandle->updateInfo() || windowHandle->getInputChannel() == NULL) {
Jeff Brown9302c872011-07-13 22:51:29 -07003270 mWindowHandles.removeAt(i--);
3271 continue;
3272 }
Jeff Browncc4f7db2011-08-30 20:34:48 -07003273 if (windowHandle->getInfo()->hasFocus) {
Jeff Brown9302c872011-07-13 22:51:29 -07003274 newFocusedWindowHandle = windowHandle;
3275 }
3276 if (windowHandle == mLastHoverWindowHandle) {
3277 foundHoveredWindow = true;
Jeff Brownb88102f2010-09-08 11:49:43 -07003278 }
3279 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07003280
Jeff Brown9302c872011-07-13 22:51:29 -07003281 if (!foundHoveredWindow) {
3282 mLastHoverWindowHandle = NULL;
3283 }
3284
3285 if (mFocusedWindowHandle != newFocusedWindowHandle) {
3286 if (mFocusedWindowHandle != NULL) {
Jeff Brownb6997262010-10-08 22:31:17 -07003287#if DEBUG_FOCUS
3288 LOGD("Focus left window: %s",
Jeff Browncc4f7db2011-08-30 20:34:48 -07003289 mFocusedWindowHandle->getName().string());
Jeff Brownb6997262010-10-08 22:31:17 -07003290#endif
Jeff Browncc4f7db2011-08-30 20:34:48 -07003291 sp<InputChannel> focusedInputChannel = mFocusedWindowHandle->getInputChannel();
3292 if (focusedInputChannel != NULL) {
Christopher Tated9be36c2011-08-16 16:09:33 -07003293 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
3294 "focus left window");
3295 synthesizeCancelationEventsForInputChannelLocked(
Jeff Browncc4f7db2011-08-30 20:34:48 -07003296 focusedInputChannel, options);
Christopher Tated9be36c2011-08-16 16:09:33 -07003297 }
Jeff Brownb6997262010-10-08 22:31:17 -07003298 }
Jeff Brown9302c872011-07-13 22:51:29 -07003299 if (newFocusedWindowHandle != NULL) {
Jeff Brownb6997262010-10-08 22:31:17 -07003300#if DEBUG_FOCUS
Jeff Brown9302c872011-07-13 22:51:29 -07003301 LOGD("Focus entered window: %s",
Jeff Browncc4f7db2011-08-30 20:34:48 -07003302 newFocusedWindowHandle->getName().string());
Jeff Brownb6997262010-10-08 22:31:17 -07003303#endif
Jeff Brown9302c872011-07-13 22:51:29 -07003304 }
3305 mFocusedWindowHandle = newFocusedWindowHandle;
Jeff Brownb6997262010-10-08 22:31:17 -07003306 }
3307
Jeff Brown9302c872011-07-13 22:51:29 -07003308 for (size_t i = 0; i < mTouchState.windows.size(); i++) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07003309 TouchedWindow& touchedWindow = mTouchState.windows.editItemAt(i);
Jeff Brown9302c872011-07-13 22:51:29 -07003310 if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
Jeff Brownb6997262010-10-08 22:31:17 -07003311#if DEBUG_FOCUS
Jeff Browncc4f7db2011-08-30 20:34:48 -07003312 LOGD("Touched window was removed: %s",
3313 touchedWindow.windowHandle->getName().string());
Jeff Brownb6997262010-10-08 22:31:17 -07003314#endif
Jeff Browncc4f7db2011-08-30 20:34:48 -07003315 sp<InputChannel> touchedInputChannel =
3316 touchedWindow.windowHandle->getInputChannel();
3317 if (touchedInputChannel != NULL) {
Christopher Tated9be36c2011-08-16 16:09:33 -07003318 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
3319 "touched window was removed");
3320 synthesizeCancelationEventsForInputChannelLocked(
Jeff Browncc4f7db2011-08-30 20:34:48 -07003321 touchedInputChannel, options);
Christopher Tated9be36c2011-08-16 16:09:33 -07003322 }
Jeff Brown9302c872011-07-13 22:51:29 -07003323 mTouchState.windows.removeAt(i--);
Jeff Brown01ce2e92010-09-26 22:20:12 -07003324 }
3325 }
Jeff Browncc4f7db2011-08-30 20:34:48 -07003326
3327 // Release information for windows that are no longer present.
3328 // This ensures that unused input channels are released promptly.
3329 // Otherwise, they might stick around until the window handle is destroyed
3330 // which might not happen until the next GC.
3331 for (size_t i = 0; i < oldWindowHandles.size(); i++) {
3332 const sp<InputWindowHandle>& oldWindowHandle = oldWindowHandles.itemAt(i);
3333 if (!hasWindowHandleLocked(oldWindowHandle)) {
3334#if DEBUG_FOCUS
3335 LOGD("Window went away: %s", oldWindowHandle->getName().string());
3336#endif
3337 oldWindowHandle->releaseInfo();
3338 }
3339 }
Jeff Brownb88102f2010-09-08 11:49:43 -07003340 } // release lock
3341
3342 // Wake up poll loop since it may need to make new input dispatching choices.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07003343 mLooper->wake();
Jeff Brownb88102f2010-09-08 11:49:43 -07003344}
3345
Jeff Brown9302c872011-07-13 22:51:29 -07003346void InputDispatcher::setFocusedApplication(
3347 const sp<InputApplicationHandle>& inputApplicationHandle) {
Jeff Brownb88102f2010-09-08 11:49:43 -07003348#if DEBUG_FOCUS
3349 LOGD("setFocusedApplication");
3350#endif
3351 { // acquire lock
3352 AutoMutex _l(mLock);
3353
Jeff Browncc4f7db2011-08-30 20:34:48 -07003354 if (inputApplicationHandle != NULL && inputApplicationHandle->updateInfo()) {
Jeff Brown5ea29ab2011-07-27 11:50:51 -07003355 if (mFocusedApplicationHandle != inputApplicationHandle) {
3356 if (mFocusedApplicationHandle != NULL) {
3357 resetTargetsLocked();
Jeff Browncc4f7db2011-08-30 20:34:48 -07003358 mFocusedApplicationHandle->releaseInfo();
Jeff Brown5ea29ab2011-07-27 11:50:51 -07003359 }
3360 mFocusedApplicationHandle = inputApplicationHandle;
3361 }
3362 } else if (mFocusedApplicationHandle != NULL) {
3363 resetTargetsLocked();
Jeff Browncc4f7db2011-08-30 20:34:48 -07003364 mFocusedApplicationHandle->releaseInfo();
Jeff Brown9302c872011-07-13 22:51:29 -07003365 mFocusedApplicationHandle.clear();
Jeff Brownb88102f2010-09-08 11:49:43 -07003366 }
3367
3368#if DEBUG_FOCUS
Jeff Brownb6997262010-10-08 22:31:17 -07003369 //logDispatchStateLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -07003370#endif
3371 } // release lock
3372
3373 // Wake up poll loop since it may need to make new input dispatching choices.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07003374 mLooper->wake();
Jeff Brownb88102f2010-09-08 11:49:43 -07003375}
3376
Jeff Brownb88102f2010-09-08 11:49:43 -07003377void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
3378#if DEBUG_FOCUS
3379 LOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
3380#endif
3381
3382 bool changed;
3383 { // acquire lock
3384 AutoMutex _l(mLock);
3385
3386 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
Jeff Brown120a4592010-10-27 18:43:51 -07003387 if (mDispatchFrozen && !frozen) {
Jeff Brownb88102f2010-09-08 11:49:43 -07003388 resetANRTimeoutsLocked();
3389 }
3390
Jeff Brown120a4592010-10-27 18:43:51 -07003391 if (mDispatchEnabled && !enabled) {
3392 resetAndDropEverythingLocked("dispatcher is being disabled");
3393 }
3394
Jeff Brownb88102f2010-09-08 11:49:43 -07003395 mDispatchEnabled = enabled;
3396 mDispatchFrozen = frozen;
3397 changed = true;
3398 } else {
3399 changed = false;
3400 }
3401
3402#if DEBUG_FOCUS
Jeff Brownb6997262010-10-08 22:31:17 -07003403 //logDispatchStateLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -07003404#endif
3405 } // release lock
3406
3407 if (changed) {
3408 // Wake up poll loop since it may need to make new input dispatching choices.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07003409 mLooper->wake();
Jeff Brown46b9ac02010-04-22 18:58:52 -07003410 }
3411}
3412
Jeff Brown0029c662011-03-30 02:25:18 -07003413void InputDispatcher::setInputFilterEnabled(bool enabled) {
3414#if DEBUG_FOCUS
3415 LOGD("setInputFilterEnabled: enabled=%d", enabled);
3416#endif
3417
3418 { // acquire lock
3419 AutoMutex _l(mLock);
3420
3421 if (mInputFilterEnabled == enabled) {
3422 return;
3423 }
3424
3425 mInputFilterEnabled = enabled;
3426 resetAndDropEverythingLocked("input filter is being enabled or disabled");
3427 } // release lock
3428
3429 // Wake up poll loop since there might be work to do to drop everything.
3430 mLooper->wake();
3431}
3432
Jeff Browne6504122010-09-27 14:52:15 -07003433bool InputDispatcher::transferTouchFocus(const sp<InputChannel>& fromChannel,
3434 const sp<InputChannel>& toChannel) {
3435#if DEBUG_FOCUS
3436 LOGD("transferTouchFocus: fromChannel=%s, toChannel=%s",
3437 fromChannel->getName().string(), toChannel->getName().string());
3438#endif
3439 { // acquire lock
3440 AutoMutex _l(mLock);
3441
Jeff Brown9302c872011-07-13 22:51:29 -07003442 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromChannel);
3443 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toChannel);
3444 if (fromWindowHandle == NULL || toWindowHandle == NULL) {
Jeff Browne6504122010-09-27 14:52:15 -07003445#if DEBUG_FOCUS
3446 LOGD("Cannot transfer focus because from or to window not found.");
3447#endif
3448 return false;
3449 }
Jeff Brown9302c872011-07-13 22:51:29 -07003450 if (fromWindowHandle == toWindowHandle) {
Jeff Browne6504122010-09-27 14:52:15 -07003451#if DEBUG_FOCUS
3452 LOGD("Trivial transfer to same window.");
3453#endif
3454 return true;
3455 }
3456
3457 bool found = false;
3458 for (size_t i = 0; i < mTouchState.windows.size(); i++) {
3459 const TouchedWindow& touchedWindow = mTouchState.windows[i];
Jeff Brown9302c872011-07-13 22:51:29 -07003460 if (touchedWindow.windowHandle == fromWindowHandle) {
Jeff Browne6504122010-09-27 14:52:15 -07003461 int32_t oldTargetFlags = touchedWindow.targetFlags;
3462 BitSet32 pointerIds = touchedWindow.pointerIds;
3463
3464 mTouchState.windows.removeAt(i);
3465
Jeff Brown46e75292010-11-10 16:53:45 -08003466 int32_t newTargetFlags = oldTargetFlags
Jeff Browna032cc02011-03-07 16:56:21 -08003467 & (InputTarget::FLAG_FOREGROUND
3468 | InputTarget::FLAG_SPLIT | InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brown9302c872011-07-13 22:51:29 -07003469 mTouchState.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Jeff Browne6504122010-09-27 14:52:15 -07003470
3471 found = true;
3472 break;
3473 }
3474 }
3475
3476 if (! found) {
3477#if DEBUG_FOCUS
3478 LOGD("Focus transfer failed because from window did not have focus.");
3479#endif
3480 return false;
3481 }
3482
Jeff Brown9c9f1a32010-10-11 18:32:20 -07003483 ssize_t fromConnectionIndex = getConnectionIndexLocked(fromChannel);
3484 ssize_t toConnectionIndex = getConnectionIndexLocked(toChannel);
3485 if (fromConnectionIndex >= 0 && toConnectionIndex >= 0) {
3486 sp<Connection> fromConnection = mConnectionsByReceiveFd.valueAt(fromConnectionIndex);
3487 sp<Connection> toConnection = mConnectionsByReceiveFd.valueAt(toConnectionIndex);
3488
3489 fromConnection->inputState.copyPointerStateTo(toConnection->inputState);
Jeff Brownda3d5a92011-03-29 15:11:34 -07003490 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Jeff Brown9c9f1a32010-10-11 18:32:20 -07003491 "transferring touch focus from this window to another window");
Jeff Brownda3d5a92011-03-29 15:11:34 -07003492 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Jeff Brown9c9f1a32010-10-11 18:32:20 -07003493 }
3494
Jeff Browne6504122010-09-27 14:52:15 -07003495#if DEBUG_FOCUS
3496 logDispatchStateLocked();
3497#endif
3498 } // release lock
3499
3500 // Wake up poll loop since it may need to make new input dispatching choices.
3501 mLooper->wake();
3502 return true;
3503}
3504
Jeff Brown120a4592010-10-27 18:43:51 -07003505void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
3506#if DEBUG_FOCUS
3507 LOGD("Resetting and dropping all events (%s).", reason);
3508#endif
3509
Jeff Brownda3d5a92011-03-29 15:11:34 -07003510 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
3511 synthesizeCancelationEventsForAllConnectionsLocked(options);
Jeff Brown120a4592010-10-27 18:43:51 -07003512
3513 resetKeyRepeatLocked();
3514 releasePendingEventLocked();
3515 drainInboundQueueLocked();
3516 resetTargetsLocked();
3517
3518 mTouchState.reset();
Jeff Brown9302c872011-07-13 22:51:29 -07003519 mLastHoverWindowHandle.clear();
Jeff Brown120a4592010-10-27 18:43:51 -07003520}
3521
Jeff Brownb88102f2010-09-08 11:49:43 -07003522void InputDispatcher::logDispatchStateLocked() {
3523 String8 dump;
3524 dumpDispatchStateLocked(dump);
Jeff Brown2a95c2a2010-09-16 12:31:46 -07003525
3526 char* text = dump.lockBuffer(dump.size());
3527 char* start = text;
3528 while (*start != '\0') {
3529 char* end = strchr(start, '\n');
3530 if (*end == '\n') {
3531 *(end++) = '\0';
3532 }
3533 LOGD("%s", start);
3534 start = end;
3535 }
Jeff Brownb88102f2010-09-08 11:49:43 -07003536}
3537
3538void InputDispatcher::dumpDispatchStateLocked(String8& dump) {
Jeff Brownf2f48712010-10-01 17:46:21 -07003539 dump.appendFormat(INDENT "DispatchEnabled: %d\n", mDispatchEnabled);
3540 dump.appendFormat(INDENT "DispatchFrozen: %d\n", mDispatchFrozen);
Jeff Brownb88102f2010-09-08 11:49:43 -07003541
Jeff Brown9302c872011-07-13 22:51:29 -07003542 if (mFocusedApplicationHandle != NULL) {
Jeff Brownf2f48712010-10-01 17:46:21 -07003543 dump.appendFormat(INDENT "FocusedApplication: name='%s', dispatchingTimeout=%0.3fms\n",
Jeff Browncc4f7db2011-08-30 20:34:48 -07003544 mFocusedApplicationHandle->getName().string(),
3545 mFocusedApplicationHandle->getDispatchingTimeout(
3546 DEFAULT_INPUT_DISPATCHING_TIMEOUT) / 1000000.0);
Jeff Brownb88102f2010-09-08 11:49:43 -07003547 } else {
Jeff Brownf2f48712010-10-01 17:46:21 -07003548 dump.append(INDENT "FocusedApplication: <null>\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003549 }
Jeff Brownf2f48712010-10-01 17:46:21 -07003550 dump.appendFormat(INDENT "FocusedWindow: name='%s'\n",
Jeff Browncc4f7db2011-08-30 20:34:48 -07003551 mFocusedWindowHandle != NULL ? mFocusedWindowHandle->getName().string() : "<null>");
Jeff Brownf2f48712010-10-01 17:46:21 -07003552
3553 dump.appendFormat(INDENT "TouchDown: %s\n", toString(mTouchState.down));
3554 dump.appendFormat(INDENT "TouchSplit: %s\n", toString(mTouchState.split));
Jeff Brown95712852011-01-04 19:41:59 -08003555 dump.appendFormat(INDENT "TouchDeviceId: %d\n", mTouchState.deviceId);
Jeff Brown58a2da82011-01-25 16:02:22 -08003556 dump.appendFormat(INDENT "TouchSource: 0x%08x\n", mTouchState.source);
Jeff Brownf2f48712010-10-01 17:46:21 -07003557 if (!mTouchState.windows.isEmpty()) {
3558 dump.append(INDENT "TouchedWindows:\n");
3559 for (size_t i = 0; i < mTouchState.windows.size(); i++) {
3560 const TouchedWindow& touchedWindow = mTouchState.windows[i];
3561 dump.appendFormat(INDENT2 "%d: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
Jeff Browncc4f7db2011-08-30 20:34:48 -07003562 i, touchedWindow.windowHandle->getName().string(),
3563 touchedWindow.pointerIds.value,
Jeff Brownf2f48712010-10-01 17:46:21 -07003564 touchedWindow.targetFlags);
3565 }
3566 } else {
3567 dump.append(INDENT "TouchedWindows: <none>\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003568 }
3569
Jeff Brown9302c872011-07-13 22:51:29 -07003570 if (!mWindowHandles.isEmpty()) {
Jeff Brownf2f48712010-10-01 17:46:21 -07003571 dump.append(INDENT "Windows:\n");
Jeff Brown9302c872011-07-13 22:51:29 -07003572 for (size_t i = 0; i < mWindowHandles.size(); i++) {
3573 const sp<InputWindowHandle>& windowHandle = mWindowHandles.itemAt(i);
Jeff Browncc4f7db2011-08-30 20:34:48 -07003574 const InputWindowInfo* windowInfo = windowHandle->getInfo();
3575
Jeff Brownf2f48712010-10-01 17:46:21 -07003576 dump.appendFormat(INDENT2 "%d: name='%s', paused=%s, hasFocus=%s, hasWallpaper=%s, "
3577 "visible=%s, canReceiveKeys=%s, flags=0x%08x, type=0x%08x, layer=%d, "
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003578 "frame=[%d,%d][%d,%d], scale=%f, "
Jeff Brownfbf09772011-01-16 14:06:57 -08003579 "touchableRegion=",
Jeff Browncc4f7db2011-08-30 20:34:48 -07003580 i, windowInfo->name.string(),
3581 toString(windowInfo->paused),
3582 toString(windowInfo->hasFocus),
3583 toString(windowInfo->hasWallpaper),
3584 toString(windowInfo->visible),
3585 toString(windowInfo->canReceiveKeys),
3586 windowInfo->layoutParamsFlags, windowInfo->layoutParamsType,
3587 windowInfo->layer,
3588 windowInfo->frameLeft, windowInfo->frameTop,
3589 windowInfo->frameRight, windowInfo->frameBottom,
3590 windowInfo->scaleFactor);
3591 dumpRegion(dump, windowInfo->touchableRegion);
3592 dump.appendFormat(", inputFeatures=0x%08x", windowInfo->inputFeatures);
Jeff Brownfbf09772011-01-16 14:06:57 -08003593 dump.appendFormat(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%0.3fms\n",
Jeff Browncc4f7db2011-08-30 20:34:48 -07003594 windowInfo->ownerPid, windowInfo->ownerUid,
3595 windowInfo->dispatchingTimeout / 1000000.0);
Jeff Brownf2f48712010-10-01 17:46:21 -07003596 }
3597 } else {
3598 dump.append(INDENT "Windows: <none>\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003599 }
3600
Jeff Brownf2f48712010-10-01 17:46:21 -07003601 if (!mMonitoringChannels.isEmpty()) {
3602 dump.append(INDENT "MonitoringChannels:\n");
3603 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
3604 const sp<InputChannel>& channel = mMonitoringChannels[i];
3605 dump.appendFormat(INDENT2 "%d: '%s'\n", i, channel->getName().string());
3606 }
3607 } else {
3608 dump.append(INDENT "MonitoringChannels: <none>\n");
3609 }
Jeff Brown519e0242010-09-15 15:18:56 -07003610
Jeff Brownf2f48712010-10-01 17:46:21 -07003611 dump.appendFormat(INDENT "InboundQueue: length=%u\n", mInboundQueue.count());
3612
3613 if (!mActiveConnections.isEmpty()) {
3614 dump.append(INDENT "ActiveConnections:\n");
3615 for (size_t i = 0; i < mActiveConnections.size(); i++) {
3616 const Connection* connection = mActiveConnections[i];
Jeff Brown76860e32010-10-25 17:37:46 -07003617 dump.appendFormat(INDENT2 "%d: '%s', status=%s, outboundQueueLength=%u, "
Jeff Brownb6997262010-10-08 22:31:17 -07003618 "inputState.isNeutral=%s\n",
Jeff Brownf2f48712010-10-01 17:46:21 -07003619 i, connection->getInputChannelName(), connection->getStatusLabel(),
3620 connection->outboundQueue.count(),
Jeff Brownb6997262010-10-08 22:31:17 -07003621 toString(connection->inputState.isNeutral()));
Jeff Brownf2f48712010-10-01 17:46:21 -07003622 }
3623 } else {
3624 dump.append(INDENT "ActiveConnections: <none>\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003625 }
3626
3627 if (isAppSwitchPendingLocked()) {
Jeff Brownf2f48712010-10-01 17:46:21 -07003628 dump.appendFormat(INDENT "AppSwitch: pending, due in %01.1fms\n",
Jeff Brownb88102f2010-09-08 11:49:43 -07003629 (mAppSwitchDueTime - now()) / 1000000.0);
3630 } else {
Jeff Brownf2f48712010-10-01 17:46:21 -07003631 dump.append(INDENT "AppSwitch: not pending\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003632 }
3633}
3634
Jeff Brown928e0542011-01-10 11:17:36 -08003635status_t InputDispatcher::registerInputChannel(const sp<InputChannel>& inputChannel,
3636 const sp<InputWindowHandle>& inputWindowHandle, bool monitor) {
Jeff Brown9c3cda02010-06-15 01:31:58 -07003637#if DEBUG_REGISTRATION
Jeff Brownb88102f2010-09-08 11:49:43 -07003638 LOGD("channel '%s' ~ registerInputChannel - monitor=%s", inputChannel->getName().string(),
3639 toString(monitor));
Jeff Brown9c3cda02010-06-15 01:31:58 -07003640#endif
3641
Jeff Brown46b9ac02010-04-22 18:58:52 -07003642 { // acquire lock
3643 AutoMutex _l(mLock);
3644
Jeff Brown519e0242010-09-15 15:18:56 -07003645 if (getConnectionIndexLocked(inputChannel) >= 0) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07003646 LOGW("Attempted to register already registered input channel '%s'",
3647 inputChannel->getName().string());
3648 return BAD_VALUE;
3649 }
3650
Jeff Browncc4f7db2011-08-30 20:34:48 -07003651 sp<Connection> connection = new Connection(inputChannel, inputWindowHandle, monitor);
Jeff Brown46b9ac02010-04-22 18:58:52 -07003652 status_t status = connection->initialize();
3653 if (status) {
3654 LOGE("Failed to initialize input publisher for input channel '%s', status=%d",
3655 inputChannel->getName().string(), status);
3656 return status;
3657 }
3658
Jeff Brown2cbecea2010-08-17 15:59:26 -07003659 int32_t receiveFd = inputChannel->getReceivePipeFd();
Jeff Brown46b9ac02010-04-22 18:58:52 -07003660 mConnectionsByReceiveFd.add(receiveFd, connection);
Jeff Brown9c3cda02010-06-15 01:31:58 -07003661
Jeff Brownb88102f2010-09-08 11:49:43 -07003662 if (monitor) {
3663 mMonitoringChannels.push(inputChannel);
3664 }
3665
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07003666 mLooper->addFd(receiveFd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
Jeff Brown2cbecea2010-08-17 15:59:26 -07003667
Jeff Brown9c3cda02010-06-15 01:31:58 -07003668 runCommandsLockedInterruptible();
Jeff Brown46b9ac02010-04-22 18:58:52 -07003669 } // release lock
Jeff Brown46b9ac02010-04-22 18:58:52 -07003670 return OK;
3671}
3672
3673status_t InputDispatcher::unregisterInputChannel(const sp<InputChannel>& inputChannel) {
Jeff Brown9c3cda02010-06-15 01:31:58 -07003674#if DEBUG_REGISTRATION
Jeff Brown349703e2010-06-22 01:27:15 -07003675 LOGD("channel '%s' ~ unregisterInputChannel", inputChannel->getName().string());
Jeff Brown9c3cda02010-06-15 01:31:58 -07003676#endif
3677
Jeff Brown46b9ac02010-04-22 18:58:52 -07003678 { // acquire lock
3679 AutoMutex _l(mLock);
3680
Jeff Browncc4f7db2011-08-30 20:34:48 -07003681 status_t status = unregisterInputChannelLocked(inputChannel, false /*notify*/);
3682 if (status) {
3683 return status;
Jeff Brown46b9ac02010-04-22 18:58:52 -07003684 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07003685 } // release lock
3686
Jeff Brown46b9ac02010-04-22 18:58:52 -07003687 // Wake the poll loop because removing the connection may have changed the current
3688 // synchronization state.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07003689 mLooper->wake();
Jeff Brown46b9ac02010-04-22 18:58:52 -07003690 return OK;
3691}
3692
Jeff Browncc4f7db2011-08-30 20:34:48 -07003693status_t InputDispatcher::unregisterInputChannelLocked(const sp<InputChannel>& inputChannel,
3694 bool notify) {
3695 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
3696 if (connectionIndex < 0) {
3697 LOGW("Attempted to unregister already unregistered input channel '%s'",
3698 inputChannel->getName().string());
3699 return BAD_VALUE;
3700 }
3701
3702 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
3703 mConnectionsByReceiveFd.removeItemsAt(connectionIndex);
3704
3705 if (connection->monitor) {
3706 removeMonitorChannelLocked(inputChannel);
3707 }
3708
3709 mLooper->removeFd(inputChannel->getReceivePipeFd());
3710
3711 nsecs_t currentTime = now();
3712 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
3713
3714 runCommandsLockedInterruptible();
3715
3716 connection->status = Connection::STATUS_ZOMBIE;
3717 return OK;
3718}
3719
3720void InputDispatcher::removeMonitorChannelLocked(const sp<InputChannel>& inputChannel) {
3721 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
3722 if (mMonitoringChannels[i] == inputChannel) {
3723 mMonitoringChannels.removeAt(i);
3724 break;
3725 }
3726 }
3727}
3728
Jeff Brown519e0242010-09-15 15:18:56 -07003729ssize_t InputDispatcher::getConnectionIndexLocked(const sp<InputChannel>& inputChannel) {
Jeff Brown2cbecea2010-08-17 15:59:26 -07003730 ssize_t connectionIndex = mConnectionsByReceiveFd.indexOfKey(inputChannel->getReceivePipeFd());
3731 if (connectionIndex >= 0) {
3732 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
3733 if (connection->inputChannel.get() == inputChannel.get()) {
3734 return connectionIndex;
3735 }
3736 }
3737
3738 return -1;
3739}
3740
Jeff Brown46b9ac02010-04-22 18:58:52 -07003741void InputDispatcher::activateConnectionLocked(Connection* connection) {
3742 for (size_t i = 0; i < mActiveConnections.size(); i++) {
3743 if (mActiveConnections.itemAt(i) == connection) {
3744 return;
3745 }
3746 }
3747 mActiveConnections.add(connection);
3748}
3749
3750void InputDispatcher::deactivateConnectionLocked(Connection* connection) {
3751 for (size_t i = 0; i < mActiveConnections.size(); i++) {
3752 if (mActiveConnections.itemAt(i) == connection) {
3753 mActiveConnections.removeAt(i);
3754 return;
3755 }
3756 }
3757}
3758
Jeff Brown9c3cda02010-06-15 01:31:58 -07003759void InputDispatcher::onDispatchCycleStartedLocked(
Jeff Brown7fbdc842010-06-17 20:52:56 -07003760 nsecs_t currentTime, const sp<Connection>& connection) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07003761}
3762
Jeff Brown9c3cda02010-06-15 01:31:58 -07003763void InputDispatcher::onDispatchCycleFinishedLocked(
Jeff Brown3915bb82010-11-05 15:02:16 -07003764 nsecs_t currentTime, const sp<Connection>& connection, bool handled) {
3765 CommandEntry* commandEntry = postCommandLocked(
3766 & InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
3767 commandEntry->connection = connection;
3768 commandEntry->handled = handled;
Jeff Brown46b9ac02010-04-22 18:58:52 -07003769}
3770
Jeff Brown9c3cda02010-06-15 01:31:58 -07003771void InputDispatcher::onDispatchCycleBrokenLocked(
Jeff Brown7fbdc842010-06-17 20:52:56 -07003772 nsecs_t currentTime, const sp<Connection>& connection) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07003773 LOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
3774 connection->getInputChannelName());
3775
Jeff Brown9c3cda02010-06-15 01:31:58 -07003776 CommandEntry* commandEntry = postCommandLocked(
3777 & InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
Jeff Brown7fbdc842010-06-17 20:52:56 -07003778 commandEntry->connection = connection;
Jeff Brown46b9ac02010-04-22 18:58:52 -07003779}
3780
Jeff Brown519e0242010-09-15 15:18:56 -07003781void InputDispatcher::onANRLocked(
Jeff Brown9302c872011-07-13 22:51:29 -07003782 nsecs_t currentTime, const sp<InputApplicationHandle>& applicationHandle,
3783 const sp<InputWindowHandle>& windowHandle,
Jeff Brown519e0242010-09-15 15:18:56 -07003784 nsecs_t eventTime, nsecs_t waitStartTime) {
3785 LOGI("Application is not responding: %s. "
3786 "%01.1fms since event, %01.1fms since wait started",
Jeff Brown9302c872011-07-13 22:51:29 -07003787 getApplicationWindowLabelLocked(applicationHandle, windowHandle).string(),
Jeff Brown519e0242010-09-15 15:18:56 -07003788 (currentTime - eventTime) / 1000000.0,
3789 (currentTime - waitStartTime) / 1000000.0);
3790
3791 CommandEntry* commandEntry = postCommandLocked(
3792 & InputDispatcher::doNotifyANRLockedInterruptible);
Jeff Brown9302c872011-07-13 22:51:29 -07003793 commandEntry->inputApplicationHandle = applicationHandle;
3794 commandEntry->inputWindowHandle = windowHandle;
Jeff Brown519e0242010-09-15 15:18:56 -07003795}
3796
Jeff Brownb88102f2010-09-08 11:49:43 -07003797void InputDispatcher::doNotifyConfigurationChangedInterruptible(
3798 CommandEntry* commandEntry) {
3799 mLock.unlock();
3800
3801 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
3802
3803 mLock.lock();
3804}
3805
Jeff Brown9c3cda02010-06-15 01:31:58 -07003806void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(
3807 CommandEntry* commandEntry) {
Jeff Brown7fbdc842010-06-17 20:52:56 -07003808 sp<Connection> connection = commandEntry->connection;
Jeff Brown9c3cda02010-06-15 01:31:58 -07003809
Jeff Brown7fbdc842010-06-17 20:52:56 -07003810 if (connection->status != Connection::STATUS_ZOMBIE) {
3811 mLock.unlock();
Jeff Brown9c3cda02010-06-15 01:31:58 -07003812
Jeff Brown928e0542011-01-10 11:17:36 -08003813 mPolicy->notifyInputChannelBroken(connection->inputWindowHandle);
Jeff Brown7fbdc842010-06-17 20:52:56 -07003814
3815 mLock.lock();
3816 }
Jeff Brown9c3cda02010-06-15 01:31:58 -07003817}
3818
Jeff Brown519e0242010-09-15 15:18:56 -07003819void InputDispatcher::doNotifyANRLockedInterruptible(
Jeff Brown9c3cda02010-06-15 01:31:58 -07003820 CommandEntry* commandEntry) {
Jeff Brown519e0242010-09-15 15:18:56 -07003821 mLock.unlock();
Jeff Brown9c3cda02010-06-15 01:31:58 -07003822
Jeff Brown519e0242010-09-15 15:18:56 -07003823 nsecs_t newTimeout = mPolicy->notifyANR(
Jeff Brown928e0542011-01-10 11:17:36 -08003824 commandEntry->inputApplicationHandle, commandEntry->inputWindowHandle);
Jeff Brown9c3cda02010-06-15 01:31:58 -07003825
Jeff Brown519e0242010-09-15 15:18:56 -07003826 mLock.lock();
Jeff Brown7fbdc842010-06-17 20:52:56 -07003827
Jeff Brown9302c872011-07-13 22:51:29 -07003828 resumeAfterTargetsNotReadyTimeoutLocked(newTimeout,
3829 commandEntry->inputWindowHandle != NULL
Jeff Browncc4f7db2011-08-30 20:34:48 -07003830 ? commandEntry->inputWindowHandle->getInputChannel() : NULL);
Jeff Brown9c3cda02010-06-15 01:31:58 -07003831}
3832
Jeff Brownb88102f2010-09-08 11:49:43 -07003833void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
3834 CommandEntry* commandEntry) {
3835 KeyEntry* entry = commandEntry->keyEntry;
Jeff Brown1f245102010-11-18 20:53:46 -08003836
3837 KeyEvent event;
3838 initializeKeyEvent(&event, entry);
Jeff Brownb88102f2010-09-08 11:49:43 -07003839
3840 mLock.unlock();
3841
Jeff Brownd5bb82d2011-10-12 13:57:59 -07003842 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(commandEntry->inputWindowHandle,
Jeff Brown1f245102010-11-18 20:53:46 -08003843 &event, entry->policyFlags);
Jeff Brownb88102f2010-09-08 11:49:43 -07003844
3845 mLock.lock();
3846
Jeff Brownd5bb82d2011-10-12 13:57:59 -07003847 if (delay < 0) {
3848 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
3849 } else if (!delay) {
3850 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
3851 } else {
3852 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
3853 entry->interceptKeyWakeupTime = now() + delay;
3854 }
Jeff Brownac386072011-07-20 15:19:50 -07003855 entry->release();
Jeff Brownb88102f2010-09-08 11:49:43 -07003856}
3857
Jeff Brown3915bb82010-11-05 15:02:16 -07003858void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(
3859 CommandEntry* commandEntry) {
3860 sp<Connection> connection = commandEntry->connection;
3861 bool handled = commandEntry->handled;
3862
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003863 bool skipNext = false;
Jeff Brown49ed71d2010-12-06 17:13:33 -08003864 if (!connection->outboundQueue.isEmpty()) {
Jeff Brownac386072011-07-20 15:19:50 -07003865 DispatchEntry* dispatchEntry = connection->outboundQueue.head;
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003866 if (dispatchEntry->inProgress) {
3867 if (dispatchEntry->eventEntry->type == EventEntry::TYPE_KEY) {
3868 KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry);
3869 skipNext = afterKeyEventLockedInterruptible(connection,
3870 dispatchEntry, keyEntry, handled);
3871 } else if (dispatchEntry->eventEntry->type == EventEntry::TYPE_MOTION) {
3872 MotionEntry* motionEntry = static_cast<MotionEntry*>(dispatchEntry->eventEntry);
3873 skipNext = afterMotionEventLockedInterruptible(connection,
3874 dispatchEntry, motionEntry, handled);
Jeff Brown49ed71d2010-12-06 17:13:33 -08003875 }
Jeff Brown3915bb82010-11-05 15:02:16 -07003876 }
3877 }
3878
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003879 if (!skipNext) {
3880 startNextDispatchCycleLocked(now(), connection);
3881 }
3882}
3883
3884bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
3885 DispatchEntry* dispatchEntry, KeyEntry* keyEntry, bool handled) {
3886 if (!(keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK)) {
3887 // Get the fallback key state.
3888 // Clear it out after dispatching the UP.
3889 int32_t originalKeyCode = keyEntry->keyCode;
3890 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
3891 if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
3892 connection->inputState.removeFallbackKey(originalKeyCode);
3893 }
3894
3895 if (handled || !dispatchEntry->hasForegroundTarget()) {
3896 // If the application handles the original key for which we previously
3897 // generated a fallback or if the window is not a foreground window,
3898 // then cancel the associated fallback key, if any.
3899 if (fallbackKeyCode != -1) {
3900 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
3901 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
3902 "application handled the original non-fallback key "
3903 "or is no longer a foreground target, "
3904 "canceling previously dispatched fallback key");
3905 options.keyCode = fallbackKeyCode;
3906 synthesizeCancelationEventsForConnectionLocked(connection, options);
3907 }
3908 connection->inputState.removeFallbackKey(originalKeyCode);
3909 }
3910 } else {
3911 // If the application did not handle a non-fallback key, first check
3912 // that we are in a good state to perform unhandled key event processing
3913 // Then ask the policy what to do with it.
3914 bool initialDown = keyEntry->action == AKEY_EVENT_ACTION_DOWN
3915 && keyEntry->repeatCount == 0;
3916 if (fallbackKeyCode == -1 && !initialDown) {
3917#if DEBUG_OUTBOUND_EVENT_DETAILS
3918 LOGD("Unhandled key event: Skipping unhandled key event processing "
3919 "since this is not an initial down. "
3920 "keyCode=%d, action=%d, repeatCount=%d",
3921 originalKeyCode, keyEntry->action, keyEntry->repeatCount);
3922#endif
3923 return false;
3924 }
3925
3926 // Dispatch the unhandled key to the policy.
3927#if DEBUG_OUTBOUND_EVENT_DETAILS
3928 LOGD("Unhandled key event: Asking policy to perform fallback action. "
3929 "keyCode=%d, action=%d, repeatCount=%d",
3930 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount);
3931#endif
3932 KeyEvent event;
3933 initializeKeyEvent(&event, keyEntry);
3934
3935 mLock.unlock();
3936
3937 bool fallback = mPolicy->dispatchUnhandledKey(connection->inputWindowHandle,
3938 &event, keyEntry->policyFlags, &event);
3939
3940 mLock.lock();
3941
3942 if (connection->status != Connection::STATUS_NORMAL) {
3943 connection->inputState.removeFallbackKey(originalKeyCode);
3944 return true; // skip next cycle
3945 }
3946
Jeff Brownac386072011-07-20 15:19:50 -07003947 LOG_ASSERT(connection->outboundQueue.head == dispatchEntry);
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003948
3949 // Latch the fallback keycode for this key on an initial down.
3950 // The fallback keycode cannot change at any other point in the lifecycle.
3951 if (initialDown) {
3952 if (fallback) {
3953 fallbackKeyCode = event.getKeyCode();
3954 } else {
3955 fallbackKeyCode = AKEYCODE_UNKNOWN;
3956 }
3957 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
3958 }
3959
3960 LOG_ASSERT(fallbackKeyCode != -1);
3961
3962 // Cancel the fallback key if the policy decides not to send it anymore.
3963 // We will continue to dispatch the key to the policy but we will no
3964 // longer dispatch a fallback key to the application.
3965 if (fallbackKeyCode != AKEYCODE_UNKNOWN
3966 && (!fallback || fallbackKeyCode != event.getKeyCode())) {
3967#if DEBUG_OUTBOUND_EVENT_DETAILS
3968 if (fallback) {
3969 LOGD("Unhandled key event: Policy requested to send key %d"
3970 "as a fallback for %d, but on the DOWN it had requested "
3971 "to send %d instead. Fallback canceled.",
3972 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
3973 } else {
3974 LOGD("Unhandled key event: Policy did not request fallback for %d,"
3975 "but on the DOWN it had requested to send %d. "
3976 "Fallback canceled.",
3977 originalKeyCode, fallbackKeyCode);
3978 }
3979#endif
3980
3981 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
3982 "canceling fallback, policy no longer desires it");
3983 options.keyCode = fallbackKeyCode;
3984 synthesizeCancelationEventsForConnectionLocked(connection, options);
3985
3986 fallback = false;
3987 fallbackKeyCode = AKEYCODE_UNKNOWN;
3988 if (keyEntry->action != AKEY_EVENT_ACTION_UP) {
3989 connection->inputState.setFallbackKey(originalKeyCode,
3990 fallbackKeyCode);
3991 }
3992 }
3993
3994#if DEBUG_OUTBOUND_EVENT_DETAILS
3995 {
3996 String8 msg;
3997 const KeyedVector<int32_t, int32_t>& fallbackKeys =
3998 connection->inputState.getFallbackKeys();
3999 for (size_t i = 0; i < fallbackKeys.size(); i++) {
4000 msg.appendFormat(", %d->%d", fallbackKeys.keyAt(i),
4001 fallbackKeys.valueAt(i));
4002 }
4003 LOGD("Unhandled key event: %d currently tracked fallback keys%s.",
4004 fallbackKeys.size(), msg.string());
4005 }
4006#endif
4007
4008 if (fallback) {
4009 // Restart the dispatch cycle using the fallback key.
4010 keyEntry->eventTime = event.getEventTime();
4011 keyEntry->deviceId = event.getDeviceId();
4012 keyEntry->source = event.getSource();
4013 keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
4014 keyEntry->keyCode = fallbackKeyCode;
4015 keyEntry->scanCode = event.getScanCode();
4016 keyEntry->metaState = event.getMetaState();
4017 keyEntry->repeatCount = event.getRepeatCount();
4018 keyEntry->downTime = event.getDownTime();
4019 keyEntry->syntheticRepeat = false;
4020
4021#if DEBUG_OUTBOUND_EVENT_DETAILS
4022 LOGD("Unhandled key event: Dispatching fallback key. "
4023 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
4024 originalKeyCode, fallbackKeyCode, keyEntry->metaState);
4025#endif
4026
4027 dispatchEntry->inProgress = false;
4028 startDispatchCycleLocked(now(), connection);
4029 return true; // already started next cycle
4030 } else {
4031#if DEBUG_OUTBOUND_EVENT_DETAILS
4032 LOGD("Unhandled key event: No fallback key.");
4033#endif
4034 }
4035 }
4036 }
4037 return false;
4038}
4039
4040bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
4041 DispatchEntry* dispatchEntry, MotionEntry* motionEntry, bool handled) {
4042 return false;
Jeff Brown3915bb82010-11-05 15:02:16 -07004043}
4044
Jeff Brownb88102f2010-09-08 11:49:43 -07004045void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
4046 mLock.unlock();
4047
Jeff Brown01ce2e92010-09-26 22:20:12 -07004048 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
Jeff Brownb88102f2010-09-08 11:49:43 -07004049
4050 mLock.lock();
4051}
4052
Jeff Brown3915bb82010-11-05 15:02:16 -07004053void InputDispatcher::initializeKeyEvent(KeyEvent* event, const KeyEntry* entry) {
4054 event->initialize(entry->deviceId, entry->source, entry->action, entry->flags,
4055 entry->keyCode, entry->scanCode, entry->metaState, entry->repeatCount,
4056 entry->downTime, entry->eventTime);
4057}
4058
Jeff Brown519e0242010-09-15 15:18:56 -07004059void InputDispatcher::updateDispatchStatisticsLocked(nsecs_t currentTime, const EventEntry* entry,
4060 int32_t injectionResult, nsecs_t timeSpentWaitingForApplication) {
4061 // TODO Write some statistics about how long we spend waiting.
Jeff Brownb88102f2010-09-08 11:49:43 -07004062}
4063
4064void InputDispatcher::dump(String8& dump) {
Jeff Brown89ef0722011-08-10 16:25:21 -07004065 AutoMutex _l(mLock);
4066
Jeff Brownf2f48712010-10-01 17:46:21 -07004067 dump.append("Input Dispatcher State:\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07004068 dumpDispatchStateLocked(dump);
Jeff Brown214eaf42011-05-26 19:17:02 -07004069
4070 dump.append(INDENT "Configuration:\n");
4071 dump.appendFormat(INDENT2 "MaxEventsPerSecond: %d\n", mConfig.maxEventsPerSecond);
4072 dump.appendFormat(INDENT2 "KeyRepeatDelay: %0.1fms\n", mConfig.keyRepeatDelay * 0.000001f);
4073 dump.appendFormat(INDENT2 "KeyRepeatTimeout: %0.1fms\n", mConfig.keyRepeatTimeout * 0.000001f);
Jeff Brownb88102f2010-09-08 11:49:43 -07004074}
4075
Jeff Brown89ef0722011-08-10 16:25:21 -07004076void InputDispatcher::monitor() {
4077 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
4078 mLock.lock();
4079 mLock.unlock();
4080}
4081
Jeff Brown9c3cda02010-06-15 01:31:58 -07004082
Jeff Brown519e0242010-09-15 15:18:56 -07004083// --- InputDispatcher::Queue ---
4084
4085template <typename T>
4086uint32_t InputDispatcher::Queue<T>::count() const {
4087 uint32_t result = 0;
Jeff Brownac386072011-07-20 15:19:50 -07004088 for (const T* entry = head; entry; entry = entry->next) {
Jeff Brown519e0242010-09-15 15:18:56 -07004089 result += 1;
4090 }
4091 return result;
4092}
4093
4094
Jeff Brownac386072011-07-20 15:19:50 -07004095// --- InputDispatcher::InjectionState ---
Jeff Brown46b9ac02010-04-22 18:58:52 -07004096
Jeff Brownac386072011-07-20 15:19:50 -07004097InputDispatcher::InjectionState::InjectionState(int32_t injectorPid, int32_t injectorUid) :
4098 refCount(1),
4099 injectorPid(injectorPid), injectorUid(injectorUid),
4100 injectionResult(INPUT_EVENT_INJECTION_PENDING), injectionIsAsync(false),
4101 pendingForegroundDispatches(0) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07004102}
4103
Jeff Brownac386072011-07-20 15:19:50 -07004104InputDispatcher::InjectionState::~InjectionState() {
Jeff Brown01ce2e92010-09-26 22:20:12 -07004105}
4106
Jeff Brownac386072011-07-20 15:19:50 -07004107void InputDispatcher::InjectionState::release() {
4108 refCount -= 1;
4109 if (refCount == 0) {
4110 delete this;
4111 } else {
4112 LOG_ASSERT(refCount > 0);
Jeff Brown01ce2e92010-09-26 22:20:12 -07004113 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07004114}
4115
Jeff Brownac386072011-07-20 15:19:50 -07004116
4117// --- InputDispatcher::EventEntry ---
4118
4119InputDispatcher::EventEntry::EventEntry(int32_t type, nsecs_t eventTime, uint32_t policyFlags) :
4120 refCount(1), type(type), eventTime(eventTime), policyFlags(policyFlags),
4121 injectionState(NULL), dispatchInProgress(false) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07004122}
4123
Jeff Brownac386072011-07-20 15:19:50 -07004124InputDispatcher::EventEntry::~EventEntry() {
4125 releaseInjectionState();
4126}
4127
4128void InputDispatcher::EventEntry::release() {
4129 refCount -= 1;
4130 if (refCount == 0) {
4131 delete this;
4132 } else {
4133 LOG_ASSERT(refCount > 0);
4134 }
4135}
4136
4137void InputDispatcher::EventEntry::releaseInjectionState() {
4138 if (injectionState) {
4139 injectionState->release();
4140 injectionState = NULL;
4141 }
4142}
4143
4144
4145// --- InputDispatcher::ConfigurationChangedEntry ---
4146
4147InputDispatcher::ConfigurationChangedEntry::ConfigurationChangedEntry(nsecs_t eventTime) :
4148 EventEntry(TYPE_CONFIGURATION_CHANGED, eventTime, 0) {
4149}
4150
4151InputDispatcher::ConfigurationChangedEntry::~ConfigurationChangedEntry() {
4152}
4153
4154
Jeff Brown65fd2512011-08-18 11:20:58 -07004155// --- InputDispatcher::DeviceResetEntry ---
4156
4157InputDispatcher::DeviceResetEntry::DeviceResetEntry(nsecs_t eventTime, int32_t deviceId) :
4158 EventEntry(TYPE_DEVICE_RESET, eventTime, 0),
4159 deviceId(deviceId) {
4160}
4161
4162InputDispatcher::DeviceResetEntry::~DeviceResetEntry() {
4163}
4164
4165
Jeff Brownac386072011-07-20 15:19:50 -07004166// --- InputDispatcher::KeyEntry ---
4167
4168InputDispatcher::KeyEntry::KeyEntry(nsecs_t eventTime,
Jeff Brown58a2da82011-01-25 16:02:22 -08004169 int32_t deviceId, uint32_t source, uint32_t policyFlags, int32_t action,
Jeff Brown7fbdc842010-06-17 20:52:56 -07004170 int32_t flags, int32_t keyCode, int32_t scanCode, int32_t metaState,
Jeff Brownac386072011-07-20 15:19:50 -07004171 int32_t repeatCount, nsecs_t downTime) :
4172 EventEntry(TYPE_KEY, eventTime, policyFlags),
4173 deviceId(deviceId), source(source), action(action), flags(flags),
4174 keyCode(keyCode), scanCode(scanCode), metaState(metaState),
4175 repeatCount(repeatCount), downTime(downTime),
Jeff Brownd5bb82d2011-10-12 13:57:59 -07004176 syntheticRepeat(false), interceptKeyResult(KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN),
4177 interceptKeyWakeupTime(0) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07004178}
4179
Jeff Brownac386072011-07-20 15:19:50 -07004180InputDispatcher::KeyEntry::~KeyEntry() {
4181}
Jeff Brown7fbdc842010-06-17 20:52:56 -07004182
Jeff Brownac386072011-07-20 15:19:50 -07004183void InputDispatcher::KeyEntry::recycle() {
4184 releaseInjectionState();
4185
4186 dispatchInProgress = false;
4187 syntheticRepeat = false;
4188 interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
Jeff Brownd5bb82d2011-10-12 13:57:59 -07004189 interceptKeyWakeupTime = 0;
Jeff Brownac386072011-07-20 15:19:50 -07004190}
4191
4192
4193// --- InputDispatcher::MotionSample ---
4194
4195InputDispatcher::MotionSample::MotionSample(nsecs_t eventTime,
4196 const PointerCoords* pointerCoords, uint32_t pointerCount) :
4197 next(NULL), eventTime(eventTime), eventTimeBeforeCoalescing(eventTime) {
Jeff Brown7fbdc842010-06-17 20:52:56 -07004198 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brownac386072011-07-20 15:19:50 -07004199 this->pointerCoords[i].copyFrom(pointerCoords[i]);
Jeff Brown7fbdc842010-06-17 20:52:56 -07004200 }
Jeff Brownb88102f2010-09-08 11:49:43 -07004201}
4202
4203
Jeff Brownae9fc032010-08-18 15:51:08 -07004204// --- InputDispatcher::MotionEntry ---
4205
Jeff Brownac386072011-07-20 15:19:50 -07004206InputDispatcher::MotionEntry::MotionEntry(nsecs_t eventTime,
4207 int32_t deviceId, uint32_t source, uint32_t policyFlags, int32_t action, int32_t flags,
4208 int32_t metaState, int32_t buttonState,
4209 int32_t edgeFlags, float xPrecision, float yPrecision,
4210 nsecs_t downTime, uint32_t pointerCount,
4211 const PointerProperties* pointerProperties, const PointerCoords* pointerCoords) :
4212 EventEntry(TYPE_MOTION, eventTime, policyFlags),
4213 deviceId(deviceId), source(source), action(action), flags(flags),
4214 metaState(metaState), buttonState(buttonState), edgeFlags(edgeFlags),
4215 xPrecision(xPrecision), yPrecision(yPrecision),
4216 downTime(downTime), pointerCount(pointerCount),
4217 firstSample(eventTime, pointerCoords, pointerCount),
4218 lastSample(&firstSample) {
4219 for (uint32_t i = 0; i < pointerCount; i++) {
4220 this->pointerProperties[i].copyFrom(pointerProperties[i]);
4221 }
4222}
4223
4224InputDispatcher::MotionEntry::~MotionEntry() {
4225 for (MotionSample* sample = firstSample.next; sample != NULL; ) {
4226 MotionSample* next = sample->next;
4227 delete sample;
4228 sample = next;
4229 }
4230}
4231
Jeff Brownae9fc032010-08-18 15:51:08 -07004232uint32_t InputDispatcher::MotionEntry::countSamples() const {
4233 uint32_t count = 1;
4234 for (MotionSample* sample = firstSample.next; sample != NULL; sample = sample->next) {
4235 count += 1;
4236 }
4237 return count;
4238}
4239
Jeff Brown4e91a182011-04-07 11:38:09 -07004240bool InputDispatcher::MotionEntry::canAppendSamples(int32_t action, uint32_t pointerCount,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07004241 const PointerProperties* pointerProperties) const {
Jeff Brown4e91a182011-04-07 11:38:09 -07004242 if (this->action != action
4243 || this->pointerCount != pointerCount
4244 || this->isInjected()) {
4245 return false;
4246 }
4247 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07004248 if (this->pointerProperties[i] != pointerProperties[i]) {
Jeff Brown4e91a182011-04-07 11:38:09 -07004249 return false;
4250 }
4251 }
4252 return true;
4253}
4254
Jeff Brownac386072011-07-20 15:19:50 -07004255void InputDispatcher::MotionEntry::appendSample(
4256 nsecs_t eventTime, const PointerCoords* pointerCoords) {
4257 MotionSample* sample = new MotionSample(eventTime, pointerCoords, pointerCount);
4258
4259 lastSample->next = sample;
4260 lastSample = sample;
4261}
4262
4263
4264// --- InputDispatcher::DispatchEntry ---
4265
4266InputDispatcher::DispatchEntry::DispatchEntry(EventEntry* eventEntry,
4267 int32_t targetFlags, float xOffset, float yOffset, float scaleFactor) :
4268 eventEntry(eventEntry), targetFlags(targetFlags),
4269 xOffset(xOffset), yOffset(yOffset), scaleFactor(scaleFactor),
4270 inProgress(false),
4271 resolvedAction(0), resolvedFlags(0),
4272 headMotionSample(NULL), tailMotionSample(NULL) {
4273 eventEntry->refCount += 1;
4274}
4275
4276InputDispatcher::DispatchEntry::~DispatchEntry() {
4277 eventEntry->release();
4278}
4279
Jeff Brownb88102f2010-09-08 11:49:43 -07004280
4281// --- InputDispatcher::InputState ---
4282
Jeff Brownb6997262010-10-08 22:31:17 -07004283InputDispatcher::InputState::InputState() {
Jeff Brownb88102f2010-09-08 11:49:43 -07004284}
4285
4286InputDispatcher::InputState::~InputState() {
4287}
4288
4289bool InputDispatcher::InputState::isNeutral() const {
4290 return mKeyMementos.isEmpty() && mMotionMementos.isEmpty();
4291}
4292
Jeff Brown81346812011-06-28 20:08:48 -07004293bool InputDispatcher::InputState::isHovering(int32_t deviceId, uint32_t source) const {
4294 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4295 const MotionMemento& memento = mMotionMementos.itemAt(i);
4296 if (memento.deviceId == deviceId
4297 && memento.source == source
4298 && memento.hovering) {
4299 return true;
4300 }
4301 }
4302 return false;
4303}
Jeff Brownb88102f2010-09-08 11:49:43 -07004304
Jeff Brown81346812011-06-28 20:08:48 -07004305bool InputDispatcher::InputState::trackKey(const KeyEntry* entry,
4306 int32_t action, int32_t flags) {
4307 switch (action) {
4308 case AKEY_EVENT_ACTION_UP: {
4309 if (entry->flags & AKEY_EVENT_FLAG_FALLBACK) {
4310 for (size_t i = 0; i < mFallbackKeys.size(); ) {
4311 if (mFallbackKeys.valueAt(i) == entry->keyCode) {
4312 mFallbackKeys.removeItemsAt(i);
4313 } else {
4314 i += 1;
4315 }
4316 }
4317 }
4318 ssize_t index = findKeyMemento(entry);
4319 if (index >= 0) {
4320 mKeyMementos.removeAt(index);
4321 return true;
4322 }
4323#if DEBUG_OUTBOUND_EVENT_DETAILS
4324 LOGD("Dropping inconsistent key up event: deviceId=%d, source=%08x, "
4325 "keyCode=%d, scanCode=%d",
4326 entry->deviceId, entry->source, entry->keyCode, entry->scanCode);
4327#endif
4328 return false;
4329 }
4330
4331 case AKEY_EVENT_ACTION_DOWN: {
4332 ssize_t index = findKeyMemento(entry);
4333 if (index >= 0) {
4334 mKeyMementos.removeAt(index);
4335 }
4336 addKeyMemento(entry, flags);
4337 return true;
4338 }
4339
4340 default:
4341 return true;
Jeff Brownb88102f2010-09-08 11:49:43 -07004342 }
4343}
4344
Jeff Brown81346812011-06-28 20:08:48 -07004345bool InputDispatcher::InputState::trackMotion(const MotionEntry* entry,
4346 int32_t action, int32_t flags) {
4347 int32_t actionMasked = action & AMOTION_EVENT_ACTION_MASK;
4348 switch (actionMasked) {
4349 case AMOTION_EVENT_ACTION_UP:
4350 case AMOTION_EVENT_ACTION_CANCEL: {
4351 ssize_t index = findMotionMemento(entry, false /*hovering*/);
4352 if (index >= 0) {
4353 mMotionMementos.removeAt(index);
4354 return true;
Jeff Brownda3d5a92011-03-29 15:11:34 -07004355 }
Jeff Brown81346812011-06-28 20:08:48 -07004356#if DEBUG_OUTBOUND_EVENT_DETAILS
4357 LOGD("Dropping inconsistent motion up or cancel event: deviceId=%d, source=%08x, "
4358 "actionMasked=%d",
4359 entry->deviceId, entry->source, actionMasked);
4360#endif
4361 return false;
Jeff Brownda3d5a92011-03-29 15:11:34 -07004362 }
4363
Jeff Brown81346812011-06-28 20:08:48 -07004364 case AMOTION_EVENT_ACTION_DOWN: {
4365 ssize_t index = findMotionMemento(entry, false /*hovering*/);
4366 if (index >= 0) {
4367 mMotionMementos.removeAt(index);
4368 }
4369 addMotionMemento(entry, flags, false /*hovering*/);
4370 return true;
4371 }
4372
4373 case AMOTION_EVENT_ACTION_POINTER_UP:
4374 case AMOTION_EVENT_ACTION_POINTER_DOWN:
4375 case AMOTION_EVENT_ACTION_MOVE: {
4376 ssize_t index = findMotionMemento(entry, false /*hovering*/);
4377 if (index >= 0) {
4378 MotionMemento& memento = mMotionMementos.editItemAt(index);
4379 memento.setPointers(entry);
4380 return true;
4381 }
Jeff Brown2e45fb62011-06-29 21:19:05 -07004382 if (actionMasked == AMOTION_EVENT_ACTION_MOVE
4383 && (entry->source & (AINPUT_SOURCE_CLASS_JOYSTICK
4384 | AINPUT_SOURCE_CLASS_NAVIGATION))) {
4385 // Joysticks and trackballs can send MOVE events without corresponding DOWN or UP.
4386 return true;
4387 }
Jeff Brown81346812011-06-28 20:08:48 -07004388#if DEBUG_OUTBOUND_EVENT_DETAILS
4389 LOGD("Dropping inconsistent motion pointer up/down or move event: "
4390 "deviceId=%d, source=%08x, actionMasked=%d",
4391 entry->deviceId, entry->source, actionMasked);
4392#endif
4393 return false;
4394 }
4395
4396 case AMOTION_EVENT_ACTION_HOVER_EXIT: {
4397 ssize_t index = findMotionMemento(entry, true /*hovering*/);
4398 if (index >= 0) {
4399 mMotionMementos.removeAt(index);
4400 return true;
4401 }
4402#if DEBUG_OUTBOUND_EVENT_DETAILS
4403 LOGD("Dropping inconsistent motion hover exit event: deviceId=%d, source=%08x",
4404 entry->deviceId, entry->source);
4405#endif
4406 return false;
4407 }
4408
4409 case AMOTION_EVENT_ACTION_HOVER_ENTER:
4410 case AMOTION_EVENT_ACTION_HOVER_MOVE: {
4411 ssize_t index = findMotionMemento(entry, true /*hovering*/);
4412 if (index >= 0) {
4413 mMotionMementos.removeAt(index);
4414 }
4415 addMotionMemento(entry, flags, true /*hovering*/);
4416 return true;
4417 }
4418
4419 default:
4420 return true;
4421 }
4422}
4423
4424ssize_t InputDispatcher::InputState::findKeyMemento(const KeyEntry* entry) const {
Jeff Brownb88102f2010-09-08 11:49:43 -07004425 for (size_t i = 0; i < mKeyMementos.size(); i++) {
Jeff Brown81346812011-06-28 20:08:48 -07004426 const KeyMemento& memento = mKeyMementos.itemAt(i);
Jeff Brownb88102f2010-09-08 11:49:43 -07004427 if (memento.deviceId == entry->deviceId
4428 && memento.source == entry->source
4429 && memento.keyCode == entry->keyCode
4430 && memento.scanCode == entry->scanCode) {
Jeff Brown81346812011-06-28 20:08:48 -07004431 return i;
Jeff Brownb88102f2010-09-08 11:49:43 -07004432 }
4433 }
Jeff Brown81346812011-06-28 20:08:48 -07004434 return -1;
Jeff Brownb88102f2010-09-08 11:49:43 -07004435}
4436
Jeff Brown81346812011-06-28 20:08:48 -07004437ssize_t InputDispatcher::InputState::findMotionMemento(const MotionEntry* entry,
4438 bool hovering) const {
Jeff Brownb88102f2010-09-08 11:49:43 -07004439 for (size_t i = 0; i < mMotionMementos.size(); i++) {
Jeff Brown81346812011-06-28 20:08:48 -07004440 const MotionMemento& memento = mMotionMementos.itemAt(i);
Jeff Brownb88102f2010-09-08 11:49:43 -07004441 if (memento.deviceId == entry->deviceId
Jeff Brown81346812011-06-28 20:08:48 -07004442 && memento.source == entry->source
4443 && memento.hovering == hovering) {
4444 return i;
Jeff Brownb88102f2010-09-08 11:49:43 -07004445 }
4446 }
Jeff Brown81346812011-06-28 20:08:48 -07004447 return -1;
4448}
Jeff Brownb88102f2010-09-08 11:49:43 -07004449
Jeff Brown81346812011-06-28 20:08:48 -07004450void InputDispatcher::InputState::addKeyMemento(const KeyEntry* entry, int32_t flags) {
4451 mKeyMementos.push();
4452 KeyMemento& memento = mKeyMementos.editTop();
4453 memento.deviceId = entry->deviceId;
4454 memento.source = entry->source;
4455 memento.keyCode = entry->keyCode;
4456 memento.scanCode = entry->scanCode;
4457 memento.flags = flags;
4458 memento.downTime = entry->downTime;
4459}
4460
4461void InputDispatcher::InputState::addMotionMemento(const MotionEntry* entry,
4462 int32_t flags, bool hovering) {
4463 mMotionMementos.push();
4464 MotionMemento& memento = mMotionMementos.editTop();
4465 memento.deviceId = entry->deviceId;
4466 memento.source = entry->source;
4467 memento.flags = flags;
4468 memento.xPrecision = entry->xPrecision;
4469 memento.yPrecision = entry->yPrecision;
4470 memento.downTime = entry->downTime;
4471 memento.setPointers(entry);
4472 memento.hovering = hovering;
Jeff Brownb88102f2010-09-08 11:49:43 -07004473}
4474
4475void InputDispatcher::InputState::MotionMemento::setPointers(const MotionEntry* entry) {
4476 pointerCount = entry->pointerCount;
4477 for (uint32_t i = 0; i < entry->pointerCount; i++) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07004478 pointerProperties[i].copyFrom(entry->pointerProperties[i]);
Jeff Brownace13b12011-03-09 17:39:48 -08004479 pointerCoords[i].copyFrom(entry->lastSample->pointerCoords[i]);
Jeff Brownb88102f2010-09-08 11:49:43 -07004480 }
4481}
4482
Jeff Brownb6997262010-10-08 22:31:17 -07004483void InputDispatcher::InputState::synthesizeCancelationEvents(nsecs_t currentTime,
Jeff Brownac386072011-07-20 15:19:50 -07004484 Vector<EventEntry*>& outEvents, const CancelationOptions& options) {
Jeff Brown81346812011-06-28 20:08:48 -07004485 for (size_t i = 0; i < mKeyMementos.size(); i++) {
Jeff Brownb88102f2010-09-08 11:49:43 -07004486 const KeyMemento& memento = mKeyMementos.itemAt(i);
Jeff Brown49ed71d2010-12-06 17:13:33 -08004487 if (shouldCancelKey(memento, options)) {
Jeff Brownac386072011-07-20 15:19:50 -07004488 outEvents.push(new KeyEntry(currentTime,
Jeff Brownb6997262010-10-08 22:31:17 -07004489 memento.deviceId, memento.source, 0,
Jeff Brown49ed71d2010-12-06 17:13:33 -08004490 AKEY_EVENT_ACTION_UP, memento.flags | AKEY_EVENT_FLAG_CANCELED,
Jeff Brownb6997262010-10-08 22:31:17 -07004491 memento.keyCode, memento.scanCode, 0, 0, memento.downTime));
Jeff Brownb6997262010-10-08 22:31:17 -07004492 }
Jeff Brownb88102f2010-09-08 11:49:43 -07004493 }
4494
Jeff Brown81346812011-06-28 20:08:48 -07004495 for (size_t i = 0; i < mMotionMementos.size(); i++) {
Jeff Brownb88102f2010-09-08 11:49:43 -07004496 const MotionMemento& memento = mMotionMementos.itemAt(i);
Jeff Brown49ed71d2010-12-06 17:13:33 -08004497 if (shouldCancelMotion(memento, options)) {
Jeff Brownac386072011-07-20 15:19:50 -07004498 outEvents.push(new MotionEntry(currentTime,
Jeff Brownb6997262010-10-08 22:31:17 -07004499 memento.deviceId, memento.source, 0,
Jeff Browna032cc02011-03-07 16:56:21 -08004500 memento.hovering
4501 ? AMOTION_EVENT_ACTION_HOVER_EXIT
4502 : AMOTION_EVENT_ACTION_CANCEL,
Jeff Brown81346812011-06-28 20:08:48 -07004503 memento.flags, 0, 0, 0,
Jeff Brownb6997262010-10-08 22:31:17 -07004504 memento.xPrecision, memento.yPrecision, memento.downTime,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07004505 memento.pointerCount, memento.pointerProperties, memento.pointerCoords));
Jeff Brownb6997262010-10-08 22:31:17 -07004506 }
Jeff Brownb88102f2010-09-08 11:49:43 -07004507 }
4508}
4509
4510void InputDispatcher::InputState::clear() {
4511 mKeyMementos.clear();
4512 mMotionMementos.clear();
Jeff Brownda3d5a92011-03-29 15:11:34 -07004513 mFallbackKeys.clear();
Jeff Brownb6997262010-10-08 22:31:17 -07004514}
4515
Jeff Brown9c9f1a32010-10-11 18:32:20 -07004516void InputDispatcher::InputState::copyPointerStateTo(InputState& other) const {
4517 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4518 const MotionMemento& memento = mMotionMementos.itemAt(i);
4519 if (memento.source & AINPUT_SOURCE_CLASS_POINTER) {
4520 for (size_t j = 0; j < other.mMotionMementos.size(); ) {
4521 const MotionMemento& otherMemento = other.mMotionMementos.itemAt(j);
4522 if (memento.deviceId == otherMemento.deviceId
4523 && memento.source == otherMemento.source) {
4524 other.mMotionMementos.removeAt(j);
4525 } else {
4526 j += 1;
4527 }
4528 }
4529 other.mMotionMementos.push(memento);
4530 }
4531 }
4532}
4533
Jeff Brownda3d5a92011-03-29 15:11:34 -07004534int32_t InputDispatcher::InputState::getFallbackKey(int32_t originalKeyCode) {
4535 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
4536 return index >= 0 ? mFallbackKeys.valueAt(index) : -1;
4537}
4538
4539void InputDispatcher::InputState::setFallbackKey(int32_t originalKeyCode,
4540 int32_t fallbackKeyCode) {
4541 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
4542 if (index >= 0) {
4543 mFallbackKeys.replaceValueAt(index, fallbackKeyCode);
4544 } else {
4545 mFallbackKeys.add(originalKeyCode, fallbackKeyCode);
4546 }
4547}
4548
4549void InputDispatcher::InputState::removeFallbackKey(int32_t originalKeyCode) {
4550 mFallbackKeys.removeItem(originalKeyCode);
4551}
4552
Jeff Brown49ed71d2010-12-06 17:13:33 -08004553bool InputDispatcher::InputState::shouldCancelKey(const KeyMemento& memento,
Jeff Brownda3d5a92011-03-29 15:11:34 -07004554 const CancelationOptions& options) {
4555 if (options.keyCode != -1 && memento.keyCode != options.keyCode) {
4556 return false;
4557 }
4558
Jeff Brown65fd2512011-08-18 11:20:58 -07004559 if (options.deviceId != -1 && memento.deviceId != options.deviceId) {
4560 return false;
4561 }
4562
Jeff Brownda3d5a92011-03-29 15:11:34 -07004563 switch (options.mode) {
4564 case CancelationOptions::CANCEL_ALL_EVENTS:
4565 case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
Jeff Brownb6997262010-10-08 22:31:17 -07004566 return true;
Jeff Brownda3d5a92011-03-29 15:11:34 -07004567 case CancelationOptions::CANCEL_FALLBACK_EVENTS:
Jeff Brown49ed71d2010-12-06 17:13:33 -08004568 return memento.flags & AKEY_EVENT_FLAG_FALLBACK;
4569 default:
4570 return false;
4571 }
4572}
4573
4574bool InputDispatcher::InputState::shouldCancelMotion(const MotionMemento& memento,
Jeff Brownda3d5a92011-03-29 15:11:34 -07004575 const CancelationOptions& options) {
Jeff Brown65fd2512011-08-18 11:20:58 -07004576 if (options.deviceId != -1 && memento.deviceId != options.deviceId) {
4577 return false;
4578 }
4579
Jeff Brownda3d5a92011-03-29 15:11:34 -07004580 switch (options.mode) {
4581 case CancelationOptions::CANCEL_ALL_EVENTS:
Jeff Brown49ed71d2010-12-06 17:13:33 -08004582 return true;
Jeff Brownda3d5a92011-03-29 15:11:34 -07004583 case CancelationOptions::CANCEL_POINTER_EVENTS:
Jeff Brown49ed71d2010-12-06 17:13:33 -08004584 return memento.source & AINPUT_SOURCE_CLASS_POINTER;
Jeff Brownda3d5a92011-03-29 15:11:34 -07004585 case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
Jeff Brown49ed71d2010-12-06 17:13:33 -08004586 return !(memento.source & AINPUT_SOURCE_CLASS_POINTER);
4587 default:
4588 return false;
Jeff Brownb6997262010-10-08 22:31:17 -07004589 }
Jeff Brownb88102f2010-09-08 11:49:43 -07004590}
4591
4592
Jeff Brown46b9ac02010-04-22 18:58:52 -07004593// --- InputDispatcher::Connection ---
4594
Jeff Brown928e0542011-01-10 11:17:36 -08004595InputDispatcher::Connection::Connection(const sp<InputChannel>& inputChannel,
Jeff Browncc4f7db2011-08-30 20:34:48 -07004596 const sp<InputWindowHandle>& inputWindowHandle, bool monitor) :
Jeff Brown928e0542011-01-10 11:17:36 -08004597 status(STATUS_NORMAL), inputChannel(inputChannel), inputWindowHandle(inputWindowHandle),
Jeff Browncc4f7db2011-08-30 20:34:48 -07004598 monitor(monitor),
Jeff Brown928e0542011-01-10 11:17:36 -08004599 inputPublisher(inputChannel),
Jeff Brownda3d5a92011-03-29 15:11:34 -07004600 lastEventTime(LONG_LONG_MAX), lastDispatchTime(LONG_LONG_MAX) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07004601}
4602
4603InputDispatcher::Connection::~Connection() {
4604}
4605
4606status_t InputDispatcher::Connection::initialize() {
4607 return inputPublisher.initialize();
4608}
4609
Jeff Brown9c3cda02010-06-15 01:31:58 -07004610const char* InputDispatcher::Connection::getStatusLabel() const {
4611 switch (status) {
4612 case STATUS_NORMAL:
4613 return "NORMAL";
4614
4615 case STATUS_BROKEN:
4616 return "BROKEN";
4617
Jeff Brown9c3cda02010-06-15 01:31:58 -07004618 case STATUS_ZOMBIE:
4619 return "ZOMBIE";
4620
4621 default:
4622 return "UNKNOWN";
4623 }
4624}
4625
Jeff Brown46b9ac02010-04-22 18:58:52 -07004626InputDispatcher::DispatchEntry* InputDispatcher::Connection::findQueuedDispatchEntryForEvent(
4627 const EventEntry* eventEntry) const {
Jeff Brownac386072011-07-20 15:19:50 -07004628 for (DispatchEntry* dispatchEntry = outboundQueue.tail; dispatchEntry;
4629 dispatchEntry = dispatchEntry->prev) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07004630 if (dispatchEntry->eventEntry == eventEntry) {
4631 return dispatchEntry;
4632 }
4633 }
4634 return NULL;
4635}
4636
Jeff Brownb88102f2010-09-08 11:49:43 -07004637
Jeff Brown9c3cda02010-06-15 01:31:58 -07004638// --- InputDispatcher::CommandEntry ---
4639
Jeff Brownac386072011-07-20 15:19:50 -07004640InputDispatcher::CommandEntry::CommandEntry(Command command) :
4641 command(command), eventTime(0), keyEntry(NULL), userActivityEventType(0), handled(false) {
Jeff Brown9c3cda02010-06-15 01:31:58 -07004642}
4643
4644InputDispatcher::CommandEntry::~CommandEntry() {
4645}
4646
Jeff Brown46b9ac02010-04-22 18:58:52 -07004647
Jeff Brown01ce2e92010-09-26 22:20:12 -07004648// --- InputDispatcher::TouchState ---
4649
4650InputDispatcher::TouchState::TouchState() :
Jeff Brown58a2da82011-01-25 16:02:22 -08004651 down(false), split(false), deviceId(-1), source(0) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07004652}
4653
4654InputDispatcher::TouchState::~TouchState() {
4655}
4656
4657void InputDispatcher::TouchState::reset() {
4658 down = false;
4659 split = false;
Jeff Brown95712852011-01-04 19:41:59 -08004660 deviceId = -1;
Jeff Brown58a2da82011-01-25 16:02:22 -08004661 source = 0;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004662 windows.clear();
4663}
4664
4665void InputDispatcher::TouchState::copyFrom(const TouchState& other) {
4666 down = other.down;
4667 split = other.split;
Jeff Brown95712852011-01-04 19:41:59 -08004668 deviceId = other.deviceId;
Jeff Brown58a2da82011-01-25 16:02:22 -08004669 source = other.source;
Jeff Brown9302c872011-07-13 22:51:29 -07004670 windows = other.windows;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004671}
4672
Jeff Brown9302c872011-07-13 22:51:29 -07004673void InputDispatcher::TouchState::addOrUpdateWindow(const sp<InputWindowHandle>& windowHandle,
Jeff Brown01ce2e92010-09-26 22:20:12 -07004674 int32_t targetFlags, BitSet32 pointerIds) {
4675 if (targetFlags & InputTarget::FLAG_SPLIT) {
4676 split = true;
4677 }
4678
4679 for (size_t i = 0; i < windows.size(); i++) {
4680 TouchedWindow& touchedWindow = windows.editItemAt(i);
Jeff Brown9302c872011-07-13 22:51:29 -07004681 if (touchedWindow.windowHandle == windowHandle) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07004682 touchedWindow.targetFlags |= targetFlags;
Jeff Brown98db5fa2011-06-08 15:37:10 -07004683 if (targetFlags & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
4684 touchedWindow.targetFlags &= ~InputTarget::FLAG_DISPATCH_AS_IS;
4685 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07004686 touchedWindow.pointerIds.value |= pointerIds.value;
4687 return;
4688 }
4689 }
4690
4691 windows.push();
4692
4693 TouchedWindow& touchedWindow = windows.editTop();
Jeff Brown9302c872011-07-13 22:51:29 -07004694 touchedWindow.windowHandle = windowHandle;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004695 touchedWindow.targetFlags = targetFlags;
4696 touchedWindow.pointerIds = pointerIds;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004697}
4698
Jeff Browna032cc02011-03-07 16:56:21 -08004699void InputDispatcher::TouchState::filterNonAsIsTouchWindows() {
Jeff Brown01ce2e92010-09-26 22:20:12 -07004700 for (size_t i = 0 ; i < windows.size(); ) {
Jeff Browna032cc02011-03-07 16:56:21 -08004701 TouchedWindow& window = windows.editItemAt(i);
Jeff Brown98db5fa2011-06-08 15:37:10 -07004702 if (window.targetFlags & (InputTarget::FLAG_DISPATCH_AS_IS
4703 | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER)) {
Jeff Browna032cc02011-03-07 16:56:21 -08004704 window.targetFlags &= ~InputTarget::FLAG_DISPATCH_MASK;
4705 window.targetFlags |= InputTarget::FLAG_DISPATCH_AS_IS;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004706 i += 1;
Jeff Browna032cc02011-03-07 16:56:21 -08004707 } else {
4708 windows.removeAt(i);
Jeff Brown01ce2e92010-09-26 22:20:12 -07004709 }
4710 }
4711}
4712
Jeff Brown9302c872011-07-13 22:51:29 -07004713sp<InputWindowHandle> InputDispatcher::TouchState::getFirstForegroundWindowHandle() const {
Jeff Brown01ce2e92010-09-26 22:20:12 -07004714 for (size_t i = 0; i < windows.size(); i++) {
Jeff Brown98db5fa2011-06-08 15:37:10 -07004715 const TouchedWindow& window = windows.itemAt(i);
4716 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
Jeff Brown9302c872011-07-13 22:51:29 -07004717 return window.windowHandle;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004718 }
4719 }
4720 return NULL;
4721}
4722
Jeff Brown98db5fa2011-06-08 15:37:10 -07004723bool InputDispatcher::TouchState::isSlippery() const {
4724 // Must have exactly one foreground window.
4725 bool haveSlipperyForegroundWindow = false;
4726 for (size_t i = 0; i < windows.size(); i++) {
4727 const TouchedWindow& window = windows.itemAt(i);
4728 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
Jeff Browncc4f7db2011-08-30 20:34:48 -07004729 if (haveSlipperyForegroundWindow
4730 || !(window.windowHandle->getInfo()->layoutParamsFlags
4731 & InputWindowInfo::FLAG_SLIPPERY)) {
Jeff Brown98db5fa2011-06-08 15:37:10 -07004732 return false;
4733 }
4734 haveSlipperyForegroundWindow = true;
4735 }
4736 }
4737 return haveSlipperyForegroundWindow;
4738}
4739
Jeff Brown01ce2e92010-09-26 22:20:12 -07004740
Jeff Brown46b9ac02010-04-22 18:58:52 -07004741// --- InputDispatcherThread ---
4742
4743InputDispatcherThread::InputDispatcherThread(const sp<InputDispatcherInterface>& dispatcher) :
4744 Thread(/*canCallJava*/ true), mDispatcher(dispatcher) {
4745}
4746
4747InputDispatcherThread::~InputDispatcherThread() {
4748}
4749
4750bool InputDispatcherThread::threadLoop() {
4751 mDispatcher->dispatchOnce();
4752 return true;
4753}
4754
4755} // namespace android