blob: 7303392dbbabda23f446698ad25dbc788adf1c57 [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 Brown905805a2011-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
Jeff Brown9f63f122012-01-12 18:30:12 -08001917 enqueueDispatchEntriesLocked(currentTime, connection,
1918 splitMotionEntry, inputTarget, resumeWithAppendedMotionSample);
1919 splitMotionEntry->release();
1920 return;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001921 }
1922 }
1923
Jeff Brown9f63f122012-01-12 18:30:12 -08001924 // Not splitting. Enqueue dispatch entries for the event as is.
1925 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget,
1926 resumeWithAppendedMotionSample);
1927}
1928
1929void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
1930 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget,
1931 bool resumeWithAppendedMotionSample) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07001932 // Resume the dispatch cycle with a freshly appended motion sample.
1933 // First we check that the last dispatch entry in the outbound queue is for the same
1934 // motion event to which we appended the motion sample. If we find such a dispatch
1935 // entry, and if it is currently in progress then we try to stream the new sample.
1936 bool wasEmpty = connection->outboundQueue.isEmpty();
1937
1938 if (! wasEmpty && resumeWithAppendedMotionSample) {
1939 DispatchEntry* motionEventDispatchEntry =
1940 connection->findQueuedDispatchEntryForEvent(eventEntry);
1941 if (motionEventDispatchEntry) {
1942 // If the dispatch entry is not in progress, then we must be busy dispatching an
1943 // earlier event. Not a problem, the motion event is on the outbound queue and will
1944 // be dispatched later.
1945 if (! motionEventDispatchEntry->inProgress) {
1946#if DEBUG_BATCHING
1947 LOGD("channel '%s' ~ Not streaming because the motion event has "
1948 "not yet been dispatched. "
1949 "(Waiting for earlier events to be consumed.)",
1950 connection->getInputChannelName());
1951#endif
1952 return;
1953 }
1954
1955 // If the dispatch entry is in progress but it already has a tail of pending
1956 // motion samples, then it must mean that the shared memory buffer filled up.
1957 // Not a problem, when this dispatch cycle is finished, we will eventually start
1958 // a new dispatch cycle to process the tail and that tail includes the newly
1959 // appended motion sample.
1960 if (motionEventDispatchEntry->tailMotionSample) {
1961#if DEBUG_BATCHING
1962 LOGD("channel '%s' ~ Not streaming because no new samples can "
1963 "be appended to the motion event in this dispatch cycle. "
1964 "(Waiting for next dispatch cycle to start.)",
1965 connection->getInputChannelName());
1966#endif
1967 return;
1968 }
1969
Jeff Brown81346812011-06-28 20:08:48 -07001970 // If the motion event was modified in flight, then we cannot stream the sample.
1971 if ((motionEventDispatchEntry->targetFlags & InputTarget::FLAG_DISPATCH_MASK)
1972 != InputTarget::FLAG_DISPATCH_AS_IS) {
1973#if DEBUG_BATCHING
1974 LOGD("channel '%s' ~ Not streaming because the motion event was not "
1975 "being dispatched as-is. "
1976 "(Waiting for next dispatch cycle to start.)",
1977 connection->getInputChannelName());
1978#endif
1979 return;
1980 }
1981
Jeff Brown46b9ac02010-04-22 18:58:52 -07001982 // The dispatch entry is in progress and is still potentially open for streaming.
1983 // Try to stream the new motion sample. This might fail if the consumer has already
1984 // consumed the motion event (or if the channel is broken).
Jeff Brown01ce2e92010-09-26 22:20:12 -07001985 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
1986 MotionSample* appendedMotionSample = motionEntry->lastSample;
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001987 status_t status;
1988 if (motionEventDispatchEntry->scaleFactor == 1.0f) {
1989 status = connection->inputPublisher.appendMotionSample(
1990 appendedMotionSample->eventTime, appendedMotionSample->pointerCoords);
1991 } else {
1992 PointerCoords scaledCoords[MAX_POINTERS];
1993 for (size_t i = 0; i < motionEntry->pointerCount; i++) {
1994 scaledCoords[i] = appendedMotionSample->pointerCoords[i];
1995 scaledCoords[i].scale(motionEventDispatchEntry->scaleFactor);
1996 }
1997 status = connection->inputPublisher.appendMotionSample(
1998 appendedMotionSample->eventTime, scaledCoords);
1999 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002000 if (status == OK) {
2001#if DEBUG_BATCHING
2002 LOGD("channel '%s' ~ Successfully streamed new motion sample.",
2003 connection->getInputChannelName());
2004#endif
2005 return;
2006 }
2007
2008#if DEBUG_BATCHING
2009 if (status == NO_MEMORY) {
2010 LOGD("channel '%s' ~ Could not append motion sample to currently "
2011 "dispatched move event because the shared memory buffer is full. "
2012 "(Waiting for next dispatch cycle to start.)",
2013 connection->getInputChannelName());
2014 } else if (status == status_t(FAILED_TRANSACTION)) {
2015 LOGD("channel '%s' ~ Could not append motion sample to currently "
Jeff Brown349703e2010-06-22 01:27:15 -07002016 "dispatched move event because the event has already been consumed. "
Jeff Brown46b9ac02010-04-22 18:58:52 -07002017 "(Waiting for next dispatch cycle to start.)",
2018 connection->getInputChannelName());
2019 } else {
2020 LOGD("channel '%s' ~ Could not append motion sample to currently "
2021 "dispatched move event due to an error, status=%d. "
2022 "(Waiting for next dispatch cycle to start.)",
2023 connection->getInputChannelName(), status);
2024 }
2025#endif
2026 // Failed to stream. Start a new tail of pending motion samples to dispatch
2027 // in the next cycle.
2028 motionEventDispatchEntry->tailMotionSample = appendedMotionSample;
2029 return;
2030 }
2031 }
2032
Jeff Browna032cc02011-03-07 16:56:21 -08002033 // Enqueue dispatch entries for the requested modes.
2034 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
2035 resumeWithAppendedMotionSample, InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
2036 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
2037 resumeWithAppendedMotionSample, InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
2038 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
2039 resumeWithAppendedMotionSample, InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
2040 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
2041 resumeWithAppendedMotionSample, InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brown98db5fa2011-06-08 15:37:10 -07002042 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
2043 resumeWithAppendedMotionSample, InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
2044 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
2045 resumeWithAppendedMotionSample, InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Jeff Browna032cc02011-03-07 16:56:21 -08002046
2047 // If the outbound queue was previously empty, start the dispatch cycle going.
Jeff Brownb6110c22011-04-01 16:15:13 -07002048 if (wasEmpty && !connection->outboundQueue.isEmpty()) {
Jeff Browna032cc02011-03-07 16:56:21 -08002049 activateConnectionLocked(connection.get());
2050 startDispatchCycleLocked(currentTime, connection);
2051 }
2052}
2053
2054void InputDispatcher::enqueueDispatchEntryLocked(
2055 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget,
2056 bool resumeWithAppendedMotionSample, int32_t dispatchMode) {
2057 int32_t inputTargetFlags = inputTarget->flags;
2058 if (!(inputTargetFlags & dispatchMode)) {
2059 return;
2060 }
2061 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
2062
Jeff Brown46b9ac02010-04-22 18:58:52 -07002063 // This is a new event.
2064 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Jeff Brownac386072011-07-20 15:19:50 -07002065 DispatchEntry* dispatchEntry = new DispatchEntry(eventEntry, // increments ref
Dianne Hackbornaa9d84c2011-05-09 19:00:59 -07002066 inputTargetFlags, inputTarget->xOffset, inputTarget->yOffset,
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002067 inputTarget->scaleFactor);
Jeff Brown6ec402b2010-07-28 15:48:59 -07002068
Jeff Brown46b9ac02010-04-22 18:58:52 -07002069 // Handle the case where we could not stream a new motion sample because the consumer has
2070 // already consumed the motion event (otherwise the corresponding dispatch entry would
2071 // still be in the outbound queue for this connection). We set the head motion sample
2072 // to the list starting with the newly appended motion sample.
2073 if (resumeWithAppendedMotionSample) {
2074#if DEBUG_BATCHING
2075 LOGD("channel '%s' ~ Preparing a new dispatch cycle for additional motion samples "
2076 "that cannot be streamed because the motion event has already been consumed.",
2077 connection->getInputChannelName());
2078#endif
2079 MotionSample* appendedMotionSample = static_cast<MotionEntry*>(eventEntry)->lastSample;
2080 dispatchEntry->headMotionSample = appendedMotionSample;
2081 }
2082
Jeff Brown81346812011-06-28 20:08:48 -07002083 // Apply target flags and update the connection's input state.
2084 switch (eventEntry->type) {
2085 case EventEntry::TYPE_KEY: {
2086 KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
2087 dispatchEntry->resolvedAction = keyEntry->action;
2088 dispatchEntry->resolvedFlags = keyEntry->flags;
2089
2090 if (!connection->inputState.trackKey(keyEntry,
2091 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags)) {
2092#if DEBUG_DISPATCH_CYCLE
2093 LOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
2094 connection->getInputChannelName());
2095#endif
Jeff Brown9f63f122012-01-12 18:30:12 -08002096 delete dispatchEntry;
Jeff Brown81346812011-06-28 20:08:48 -07002097 return; // skip the inconsistent event
2098 }
2099 break;
2100 }
2101
2102 case EventEntry::TYPE_MOTION: {
2103 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
2104 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2105 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
2106 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
2107 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
2108 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
2109 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2110 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
2111 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
2112 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
2113 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
2114 } else {
2115 dispatchEntry->resolvedAction = motionEntry->action;
2116 }
2117 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE
2118 && !connection->inputState.isHovering(
2119 motionEntry->deviceId, motionEntry->source)) {
2120#if DEBUG_DISPATCH_CYCLE
2121 LOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter event",
2122 connection->getInputChannelName());
2123#endif
2124 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2125 }
2126
2127 dispatchEntry->resolvedFlags = motionEntry->flags;
2128 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
2129 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
2130 }
2131
2132 if (!connection->inputState.trackMotion(motionEntry,
2133 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags)) {
2134#if DEBUG_DISPATCH_CYCLE
2135 LOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion event",
2136 connection->getInputChannelName());
2137#endif
Jeff Brown9f63f122012-01-12 18:30:12 -08002138 delete dispatchEntry;
Jeff Brown81346812011-06-28 20:08:48 -07002139 return; // skip the inconsistent event
2140 }
2141 break;
2142 }
2143 }
2144
Jeff Brown9f63f122012-01-12 18:30:12 -08002145 // Remember that we are waiting for this dispatch to complete.
2146 if (dispatchEntry->hasForegroundTarget()) {
2147 incrementPendingForegroundDispatchesLocked(eventEntry);
2148 }
2149
Jeff Brown46b9ac02010-04-22 18:58:52 -07002150 // Enqueue the dispatch entry.
2151 connection->outboundQueue.enqueueAtTail(dispatchEntry);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002152}
2153
Jeff Brown7fbdc842010-06-17 20:52:56 -07002154void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Jeff Brown519e0242010-09-15 15:18:56 -07002155 const sp<Connection>& connection) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002156#if DEBUG_DISPATCH_CYCLE
2157 LOGD("channel '%s' ~ startDispatchCycle",
2158 connection->getInputChannelName());
2159#endif
2160
Jeff Brownb6110c22011-04-01 16:15:13 -07002161 LOG_ASSERT(connection->status == Connection::STATUS_NORMAL);
2162 LOG_ASSERT(! connection->outboundQueue.isEmpty());
Jeff Brown46b9ac02010-04-22 18:58:52 -07002163
Jeff Brownac386072011-07-20 15:19:50 -07002164 DispatchEntry* dispatchEntry = connection->outboundQueue.head;
Jeff Brownb6110c22011-04-01 16:15:13 -07002165 LOG_ASSERT(! dispatchEntry->inProgress);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002166
Jeff Brownb88102f2010-09-08 11:49:43 -07002167 // Mark the dispatch entry as in progress.
2168 dispatchEntry->inProgress = true;
2169
Jeff Brown46b9ac02010-04-22 18:58:52 -07002170 // Publish the event.
2171 status_t status;
Jeff Browna032cc02011-03-07 16:56:21 -08002172 EventEntry* eventEntry = dispatchEntry->eventEntry;
Jeff Brown01ce2e92010-09-26 22:20:12 -07002173 switch (eventEntry->type) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002174 case EventEntry::TYPE_KEY: {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002175 KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002176
Jeff Brown46b9ac02010-04-22 18:58:52 -07002177 // Publish the key event.
Jeff Brown81346812011-06-28 20:08:48 -07002178 status = connection->inputPublisher.publishKeyEvent(
2179 keyEntry->deviceId, keyEntry->source,
2180 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags,
2181 keyEntry->keyCode, keyEntry->scanCode,
Jeff Brown46b9ac02010-04-22 18:58:52 -07002182 keyEntry->metaState, keyEntry->repeatCount, keyEntry->downTime,
2183 keyEntry->eventTime);
2184
2185 if (status) {
2186 LOGE("channel '%s' ~ Could not publish key event, "
2187 "status=%d", connection->getInputChannelName(), status);
Jeff Browncc4f7db2011-08-30 20:34:48 -07002188 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002189 return;
2190 }
2191 break;
2192 }
2193
2194 case EventEntry::TYPE_MOTION: {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002195 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002196
Jeff Brown46b9ac02010-04-22 18:58:52 -07002197 // If headMotionSample is non-NULL, then it points to the first new sample that we
2198 // were unable to dispatch during the previous cycle so we resume dispatching from
2199 // that point in the list of motion samples.
2200 // Otherwise, we just start from the first sample of the motion event.
2201 MotionSample* firstMotionSample = dispatchEntry->headMotionSample;
2202 if (! firstMotionSample) {
2203 firstMotionSample = & motionEntry->firstSample;
2204 }
2205
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002206 PointerCoords scaledCoords[MAX_POINTERS];
2207 const PointerCoords* usingCoords = firstMotionSample->pointerCoords;
2208
Jeff Brownd3616592010-07-16 17:21:06 -07002209 // Set the X and Y offset depending on the input source.
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002210 float xOffset, yOffset, scaleFactor;
Kenny Root7a9db182011-06-02 15:16:05 -07002211 if (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER
2212 && !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002213 scaleFactor = dispatchEntry->scaleFactor;
2214 xOffset = dispatchEntry->xOffset * scaleFactor;
2215 yOffset = dispatchEntry->yOffset * scaleFactor;
2216 if (scaleFactor != 1.0f) {
2217 for (size_t i = 0; i < motionEntry->pointerCount; i++) {
2218 scaledCoords[i] = firstMotionSample->pointerCoords[i];
2219 scaledCoords[i].scale(scaleFactor);
2220 }
2221 usingCoords = scaledCoords;
2222 }
Jeff Brownd3616592010-07-16 17:21:06 -07002223 } else {
2224 xOffset = 0.0f;
2225 yOffset = 0.0f;
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002226 scaleFactor = 1.0f;
Kenny Root7a9db182011-06-02 15:16:05 -07002227
2228 // We don't want the dispatch target to know.
2229 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
2230 for (size_t i = 0; i < motionEntry->pointerCount; i++) {
2231 scaledCoords[i].clear();
2232 }
2233 usingCoords = scaledCoords;
2234 }
Jeff Brownd3616592010-07-16 17:21:06 -07002235 }
2236
Jeff Brown46b9ac02010-04-22 18:58:52 -07002237 // Publish the motion event and the first motion sample.
Jeff Brown81346812011-06-28 20:08:48 -07002238 status = connection->inputPublisher.publishMotionEvent(
2239 motionEntry->deviceId, motionEntry->source,
2240 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags,
2241 motionEntry->edgeFlags, motionEntry->metaState, motionEntry->buttonState,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002242 xOffset, yOffset,
2243 motionEntry->xPrecision, motionEntry->yPrecision,
Jeff Brown46b9ac02010-04-22 18:58:52 -07002244 motionEntry->downTime, firstMotionSample->eventTime,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002245 motionEntry->pointerCount, motionEntry->pointerProperties,
2246 usingCoords);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002247
2248 if (status) {
2249 LOGE("channel '%s' ~ Could not publish motion event, "
2250 "status=%d", connection->getInputChannelName(), status);
Jeff Browncc4f7db2011-08-30 20:34:48 -07002251 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002252 return;
2253 }
2254
Jeff Brown81346812011-06-28 20:08:48 -07002255 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_MOVE
2256 || dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Jeff Browna032cc02011-03-07 16:56:21 -08002257 // Append additional motion samples.
2258 MotionSample* nextMotionSample = firstMotionSample->next;
2259 for (; nextMotionSample != NULL; nextMotionSample = nextMotionSample->next) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002260 if (usingCoords == scaledCoords) {
Kenny Root7a9db182011-06-02 15:16:05 -07002261 if (!(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
2262 for (size_t i = 0; i < motionEntry->pointerCount; i++) {
2263 scaledCoords[i] = nextMotionSample->pointerCoords[i];
2264 scaledCoords[i].scale(scaleFactor);
2265 }
Dianne Hackborn2ba3e802011-05-11 10:59:54 -07002266 }
2267 } else {
2268 usingCoords = nextMotionSample->pointerCoords;
Dianne Hackborne7d25b72011-05-09 21:19:26 -07002269 }
Jeff Browna032cc02011-03-07 16:56:21 -08002270 status = connection->inputPublisher.appendMotionSample(
Dianne Hackbornaa9d84c2011-05-09 19:00:59 -07002271 nextMotionSample->eventTime, usingCoords);
Jeff Browna032cc02011-03-07 16:56:21 -08002272 if (status == NO_MEMORY) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002273#if DEBUG_DISPATCH_CYCLE
2274 LOGD("channel '%s' ~ Shared memory buffer full. Some motion samples will "
2275 "be sent in the next dispatch cycle.",
2276 connection->getInputChannelName());
2277#endif
Jeff Browna032cc02011-03-07 16:56:21 -08002278 break;
2279 }
2280 if (status != OK) {
2281 LOGE("channel '%s' ~ Could not append motion sample "
2282 "for a reason other than out of memory, status=%d",
2283 connection->getInputChannelName(), status);
Jeff Browncc4f7db2011-08-30 20:34:48 -07002284 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
Jeff Browna032cc02011-03-07 16:56:21 -08002285 return;
2286 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002287 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002288
Jeff Browna032cc02011-03-07 16:56:21 -08002289 // Remember the next motion sample that we could not dispatch, in case we ran out
2290 // of space in the shared memory buffer.
2291 dispatchEntry->tailMotionSample = nextMotionSample;
2292 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002293 break;
2294 }
2295
2296 default: {
Jeff Brownb6110c22011-04-01 16:15:13 -07002297 LOG_ASSERT(false);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002298 }
2299 }
2300
2301 // Send the dispatch signal.
2302 status = connection->inputPublisher.sendDispatchSignal();
2303 if (status) {
2304 LOGE("channel '%s' ~ Could not send dispatch signal, status=%d",
2305 connection->getInputChannelName(), status);
Jeff Browncc4f7db2011-08-30 20:34:48 -07002306 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002307 return;
2308 }
2309
2310 // Record information about the newly started dispatch cycle.
Jeff Brown01ce2e92010-09-26 22:20:12 -07002311 connection->lastEventTime = eventEntry->eventTime;
Jeff Brown46b9ac02010-04-22 18:58:52 -07002312 connection->lastDispatchTime = currentTime;
2313
Jeff Brown46b9ac02010-04-22 18:58:52 -07002314 // Notify other system components.
2315 onDispatchCycleStartedLocked(currentTime, connection);
2316}
2317
Jeff Brown7fbdc842010-06-17 20:52:56 -07002318void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Jeff Brown3915bb82010-11-05 15:02:16 -07002319 const sp<Connection>& connection, bool handled) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002320#if DEBUG_DISPATCH_CYCLE
Jeff Brown9c3cda02010-06-15 01:31:58 -07002321 LOGD("channel '%s' ~ finishDispatchCycle - %01.1fms since event, "
Jeff Brown3915bb82010-11-05 15:02:16 -07002322 "%01.1fms since dispatch, handled=%s",
Jeff Brown46b9ac02010-04-22 18:58:52 -07002323 connection->getInputChannelName(),
2324 connection->getEventLatencyMillis(currentTime),
Jeff Brown3915bb82010-11-05 15:02:16 -07002325 connection->getDispatchLatencyMillis(currentTime),
2326 toString(handled));
Jeff Brown46b9ac02010-04-22 18:58:52 -07002327#endif
2328
Jeff Brown9c3cda02010-06-15 01:31:58 -07002329 if (connection->status == Connection::STATUS_BROKEN
2330 || connection->status == Connection::STATUS_ZOMBIE) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002331 return;
2332 }
2333
Jeff Brown46b9ac02010-04-22 18:58:52 -07002334 // Reset the publisher since the event has been consumed.
2335 // We do this now so that the publisher can release some of its internal resources
2336 // while waiting for the next dispatch cycle to begin.
2337 status_t status = connection->inputPublisher.reset();
2338 if (status) {
2339 LOGE("channel '%s' ~ Could not reset publisher, status=%d",
2340 connection->getInputChannelName(), status);
Jeff Browncc4f7db2011-08-30 20:34:48 -07002341 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002342 return;
2343 }
2344
Jeff Brown3915bb82010-11-05 15:02:16 -07002345 // Notify other system components and prepare to start the next dispatch cycle.
2346 onDispatchCycleFinishedLocked(currentTime, connection, handled);
Jeff Brownb88102f2010-09-08 11:49:43 -07002347}
2348
2349void InputDispatcher::startNextDispatchCycleLocked(nsecs_t currentTime,
2350 const sp<Connection>& connection) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002351 // Start the next dispatch cycle for this connection.
2352 while (! connection->outboundQueue.isEmpty()) {
Jeff Brownac386072011-07-20 15:19:50 -07002353 DispatchEntry* dispatchEntry = connection->outboundQueue.head;
Jeff Brown46b9ac02010-04-22 18:58:52 -07002354 if (dispatchEntry->inProgress) {
2355 // Finish or resume current event in progress.
2356 if (dispatchEntry->tailMotionSample) {
2357 // We have a tail of undispatched motion samples.
2358 // Reuse the same DispatchEntry and start a new cycle.
2359 dispatchEntry->inProgress = false;
2360 dispatchEntry->headMotionSample = dispatchEntry->tailMotionSample;
2361 dispatchEntry->tailMotionSample = NULL;
Jeff Brown519e0242010-09-15 15:18:56 -07002362 startDispatchCycleLocked(currentTime, connection);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002363 return;
2364 }
2365 // Finished.
2366 connection->outboundQueue.dequeueAtHead();
Jeff Brown519e0242010-09-15 15:18:56 -07002367 if (dispatchEntry->hasForegroundTarget()) {
2368 decrementPendingForegroundDispatchesLocked(dispatchEntry->eventEntry);
Jeff Brown6ec402b2010-07-28 15:48:59 -07002369 }
Jeff Brownac386072011-07-20 15:19:50 -07002370 delete dispatchEntry;
Jeff Brown46b9ac02010-04-22 18:58:52 -07002371 } else {
2372 // If the head is not in progress, then we must have already dequeued the in
Jeff Brown519e0242010-09-15 15:18:56 -07002373 // progress event, which means we actually aborted it.
Jeff Brown46b9ac02010-04-22 18:58:52 -07002374 // So just start the next event for this connection.
Jeff Brown519e0242010-09-15 15:18:56 -07002375 startDispatchCycleLocked(currentTime, connection);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002376 return;
2377 }
2378 }
2379
2380 // Outbound queue is empty, deactivate the connection.
Jeff Brown7fbdc842010-06-17 20:52:56 -07002381 deactivateConnectionLocked(connection.get());
Jeff Brown46b9ac02010-04-22 18:58:52 -07002382}
2383
Jeff Brownb6997262010-10-08 22:31:17 -07002384void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Jeff Browncc4f7db2011-08-30 20:34:48 -07002385 const sp<Connection>& connection, bool notify) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002386#if DEBUG_DISPATCH_CYCLE
Jeff Browncc4f7db2011-08-30 20:34:48 -07002387 LOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
2388 connection->getInputChannelName(), toString(notify));
Jeff Brown46b9ac02010-04-22 18:58:52 -07002389#endif
2390
Jeff Brownb88102f2010-09-08 11:49:43 -07002391 // Clear the outbound queue.
Jeff Brown519e0242010-09-15 15:18:56 -07002392 drainOutboundQueueLocked(connection.get());
Jeff Brown46b9ac02010-04-22 18:58:52 -07002393
Jeff Brownb6997262010-10-08 22:31:17 -07002394 // The connection appears to be unrecoverably broken.
Jeff Brown9c3cda02010-06-15 01:31:58 -07002395 // Ignore already broken or zombie connections.
Jeff Brownb6997262010-10-08 22:31:17 -07002396 if (connection->status == Connection::STATUS_NORMAL) {
2397 connection->status = Connection::STATUS_BROKEN;
Jeff Brown46b9ac02010-04-22 18:58:52 -07002398
Jeff Browncc4f7db2011-08-30 20:34:48 -07002399 if (notify) {
2400 // Notify other system components.
2401 onDispatchCycleBrokenLocked(currentTime, connection);
2402 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002403 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002404}
2405
Jeff Brown519e0242010-09-15 15:18:56 -07002406void InputDispatcher::drainOutboundQueueLocked(Connection* connection) {
2407 while (! connection->outboundQueue.isEmpty()) {
2408 DispatchEntry* dispatchEntry = connection->outboundQueue.dequeueAtHead();
2409 if (dispatchEntry->hasForegroundTarget()) {
2410 decrementPendingForegroundDispatchesLocked(dispatchEntry->eventEntry);
Jeff Brownb88102f2010-09-08 11:49:43 -07002411 }
Jeff Brownac386072011-07-20 15:19:50 -07002412 delete dispatchEntry;
Jeff Brownb88102f2010-09-08 11:49:43 -07002413 }
2414
Jeff Brown519e0242010-09-15 15:18:56 -07002415 deactivateConnectionLocked(connection);
Jeff Brownb88102f2010-09-08 11:49:43 -07002416}
2417
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002418int InputDispatcher::handleReceiveCallback(int receiveFd, int events, void* data) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002419 InputDispatcher* d = static_cast<InputDispatcher*>(data);
2420
2421 { // acquire lock
2422 AutoMutex _l(d->mLock);
2423
2424 ssize_t connectionIndex = d->mConnectionsByReceiveFd.indexOfKey(receiveFd);
2425 if (connectionIndex < 0) {
2426 LOGE("Received spurious receive callback for unknown input channel. "
2427 "fd=%d, events=0x%x", receiveFd, events);
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002428 return 0; // remove the callback
Jeff Brown46b9ac02010-04-22 18:58:52 -07002429 }
2430
Jeff Browncc4f7db2011-08-30 20:34:48 -07002431 bool notify;
Jeff Brown46b9ac02010-04-22 18:58:52 -07002432 sp<Connection> connection = d->mConnectionsByReceiveFd.valueAt(connectionIndex);
Jeff Browncc4f7db2011-08-30 20:34:48 -07002433 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
2434 if (!(events & ALOOPER_EVENT_INPUT)) {
2435 LOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
2436 "events=0x%x", connection->getInputChannelName(), events);
2437 return 1;
2438 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002439
Jeff Browncc4f7db2011-08-30 20:34:48 -07002440 bool handled = false;
2441 status_t status = connection->inputPublisher.receiveFinishedSignal(&handled);
2442 if (!status) {
2443 nsecs_t currentTime = now();
2444 d->finishDispatchCycleLocked(currentTime, connection, handled);
2445 d->runCommandsLockedInterruptible();
2446 return 1;
2447 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002448
Jeff Brown46b9ac02010-04-22 18:58:52 -07002449 LOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
2450 connection->getInputChannelName(), status);
Jeff Browncc4f7db2011-08-30 20:34:48 -07002451 notify = true;
2452 } else {
2453 // Monitor channels are never explicitly unregistered.
2454 // We do it automatically when the remote endpoint is closed so don't warn
2455 // about them.
2456 notify = !connection->monitor;
2457 if (notify) {
2458 LOGW("channel '%s' ~ Consumer closed input channel or an error occurred. "
2459 "events=0x%x", connection->getInputChannelName(), events);
2460 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002461 }
2462
Jeff Browncc4f7db2011-08-30 20:34:48 -07002463 // Unregister the channel.
2464 d->unregisterInputChannelLocked(connection->inputChannel, notify);
2465 return 0; // remove the callback
Jeff Brown46b9ac02010-04-22 18:58:52 -07002466 } // release lock
2467}
2468
Jeff Brownb6997262010-10-08 22:31:17 -07002469void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Jeff Brownda3d5a92011-03-29 15:11:34 -07002470 const CancelationOptions& options) {
Jeff Brownb6997262010-10-08 22:31:17 -07002471 for (size_t i = 0; i < mConnectionsByReceiveFd.size(); i++) {
2472 synthesizeCancelationEventsForConnectionLocked(
Jeff Brownda3d5a92011-03-29 15:11:34 -07002473 mConnectionsByReceiveFd.valueAt(i), options);
Jeff Brownb6997262010-10-08 22:31:17 -07002474 }
2475}
2476
2477void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Jeff Brownda3d5a92011-03-29 15:11:34 -07002478 const sp<InputChannel>& channel, const CancelationOptions& options) {
Jeff Brownb6997262010-10-08 22:31:17 -07002479 ssize_t index = getConnectionIndexLocked(channel);
2480 if (index >= 0) {
2481 synthesizeCancelationEventsForConnectionLocked(
Jeff Brownda3d5a92011-03-29 15:11:34 -07002482 mConnectionsByReceiveFd.valueAt(index), options);
Jeff Brownb6997262010-10-08 22:31:17 -07002483 }
2484}
2485
2486void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
Jeff Brownda3d5a92011-03-29 15:11:34 -07002487 const sp<Connection>& connection, const CancelationOptions& options) {
Jeff Brown9f63f122012-01-12 18:30:12 -08002488 if (connection->status == Connection::STATUS_BROKEN) {
2489 return;
2490 }
2491
Jeff Brownb6997262010-10-08 22:31:17 -07002492 nsecs_t currentTime = now();
2493
2494 mTempCancelationEvents.clear();
Jeff Brownac386072011-07-20 15:19:50 -07002495 connection->inputState.synthesizeCancelationEvents(currentTime,
Jeff Brownb6997262010-10-08 22:31:17 -07002496 mTempCancelationEvents, options);
2497
Jeff Brown9f63f122012-01-12 18:30:12 -08002498 if (!mTempCancelationEvents.isEmpty()) {
Jeff Brownb6997262010-10-08 22:31:17 -07002499#if DEBUG_OUTBOUND_EVENT_DETAILS
2500 LOGD("channel '%s' ~ Synthesized %d cancelation events to bring channel back in sync "
Jeff Brownda3d5a92011-03-29 15:11:34 -07002501 "with reality: %s, mode=%d.",
2502 connection->getInputChannelName(), mTempCancelationEvents.size(),
2503 options.reason, options.mode);
Jeff Brownb6997262010-10-08 22:31:17 -07002504#endif
2505 for (size_t i = 0; i < mTempCancelationEvents.size(); i++) {
2506 EventEntry* cancelationEventEntry = mTempCancelationEvents.itemAt(i);
2507 switch (cancelationEventEntry->type) {
2508 case EventEntry::TYPE_KEY:
2509 logOutboundKeyDetailsLocked("cancel - ",
2510 static_cast<KeyEntry*>(cancelationEventEntry));
2511 break;
2512 case EventEntry::TYPE_MOTION:
2513 logOutboundMotionDetailsLocked("cancel - ",
2514 static_cast<MotionEntry*>(cancelationEventEntry));
2515 break;
2516 }
2517
Jeff Brown81346812011-06-28 20:08:48 -07002518 InputTarget target;
Jeff Brown9302c872011-07-13 22:51:29 -07002519 sp<InputWindowHandle> windowHandle = getWindowHandleLocked(connection->inputChannel);
2520 if (windowHandle != NULL) {
Jeff Browncc4f7db2011-08-30 20:34:48 -07002521 const InputWindowInfo* windowInfo = windowHandle->getInfo();
2522 target.xOffset = -windowInfo->frameLeft;
2523 target.yOffset = -windowInfo->frameTop;
2524 target.scaleFactor = windowInfo->scaleFactor;
Jeff Brownb6997262010-10-08 22:31:17 -07002525 } else {
Jeff Brown81346812011-06-28 20:08:48 -07002526 target.xOffset = 0;
2527 target.yOffset = 0;
2528 target.scaleFactor = 1.0f;
Jeff Brownb6997262010-10-08 22:31:17 -07002529 }
Jeff Brown81346812011-06-28 20:08:48 -07002530 target.inputChannel = connection->inputChannel;
2531 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
Jeff Brownb6997262010-10-08 22:31:17 -07002532
Jeff Brown81346812011-06-28 20:08:48 -07002533 enqueueDispatchEntryLocked(connection, cancelationEventEntry, // increments ref
2534 &target, false, InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brownb6997262010-10-08 22:31:17 -07002535
Jeff Brownac386072011-07-20 15:19:50 -07002536 cancelationEventEntry->release();
Jeff Brownb6997262010-10-08 22:31:17 -07002537 }
2538
Jeff Brownac386072011-07-20 15:19:50 -07002539 if (!connection->outboundQueue.head->inProgress) {
Jeff Brownb6997262010-10-08 22:31:17 -07002540 startDispatchCycleLocked(currentTime, connection);
2541 }
2542 }
2543}
2544
Jeff Brown01ce2e92010-09-26 22:20:12 -07002545InputDispatcher::MotionEntry*
2546InputDispatcher::splitMotionEvent(const MotionEntry* originalMotionEntry, BitSet32 pointerIds) {
Jeff Brownb6110c22011-04-01 16:15:13 -07002547 LOG_ASSERT(pointerIds.value != 0);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002548
2549 uint32_t splitPointerIndexMap[MAX_POINTERS];
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002550 PointerProperties splitPointerProperties[MAX_POINTERS];
Jeff Brown01ce2e92010-09-26 22:20:12 -07002551 PointerCoords splitPointerCoords[MAX_POINTERS];
2552
2553 uint32_t originalPointerCount = originalMotionEntry->pointerCount;
2554 uint32_t splitPointerCount = 0;
2555
2556 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
2557 originalPointerIndex++) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002558 const PointerProperties& pointerProperties =
2559 originalMotionEntry->pointerProperties[originalPointerIndex];
2560 uint32_t pointerId = uint32_t(pointerProperties.id);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002561 if (pointerIds.hasBit(pointerId)) {
2562 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002563 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
Jeff Brownace13b12011-03-09 17:39:48 -08002564 splitPointerCoords[splitPointerCount].copyFrom(
2565 originalMotionEntry->firstSample.pointerCoords[originalPointerIndex]);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002566 splitPointerCount += 1;
2567 }
2568 }
Jeff Brown58a2da82011-01-25 16:02:22 -08002569
2570 if (splitPointerCount != pointerIds.count()) {
2571 // This is bad. We are missing some of the pointers that we expected to deliver.
2572 // Most likely this indicates that we received an ACTION_MOVE events that has
2573 // different pointer ids than we expected based on the previous ACTION_DOWN
2574 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
2575 // in this way.
2576 LOGW("Dropping split motion event because the pointer count is %d but "
2577 "we expected there to be %d pointers. This probably means we received "
2578 "a broken sequence of pointer ids from the input device.",
2579 splitPointerCount, pointerIds.count());
2580 return NULL;
2581 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07002582
2583 int32_t action = originalMotionEntry->action;
2584 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
2585 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
2586 || maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2587 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002588 const PointerProperties& pointerProperties =
2589 originalMotionEntry->pointerProperties[originalPointerIndex];
2590 uint32_t pointerId = uint32_t(pointerProperties.id);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002591 if (pointerIds.hasBit(pointerId)) {
2592 if (pointerIds.count() == 1) {
2593 // The first/last pointer went down/up.
2594 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
2595 ? AMOTION_EVENT_ACTION_DOWN : AMOTION_EVENT_ACTION_UP;
Jeff Brown9a01d052010-09-27 16:35:11 -07002596 } else {
2597 // A secondary pointer went down/up.
2598 uint32_t splitPointerIndex = 0;
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002599 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
Jeff Brown9a01d052010-09-27 16:35:11 -07002600 splitPointerIndex += 1;
2601 }
2602 action = maskedAction | (splitPointerIndex
2603 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002604 }
2605 } else {
2606 // An unrelated pointer changed.
2607 action = AMOTION_EVENT_ACTION_MOVE;
2608 }
2609 }
2610
Jeff Brownac386072011-07-20 15:19:50 -07002611 MotionEntry* splitMotionEntry = new MotionEntry(
Jeff Brown01ce2e92010-09-26 22:20:12 -07002612 originalMotionEntry->eventTime,
2613 originalMotionEntry->deviceId,
2614 originalMotionEntry->source,
2615 originalMotionEntry->policyFlags,
2616 action,
2617 originalMotionEntry->flags,
2618 originalMotionEntry->metaState,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002619 originalMotionEntry->buttonState,
Jeff Brown01ce2e92010-09-26 22:20:12 -07002620 originalMotionEntry->edgeFlags,
2621 originalMotionEntry->xPrecision,
2622 originalMotionEntry->yPrecision,
2623 originalMotionEntry->downTime,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002624 splitPointerCount, splitPointerProperties, splitPointerCoords);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002625
2626 for (MotionSample* originalMotionSample = originalMotionEntry->firstSample.next;
2627 originalMotionSample != NULL; originalMotionSample = originalMotionSample->next) {
2628 for (uint32_t splitPointerIndex = 0; splitPointerIndex < splitPointerCount;
2629 splitPointerIndex++) {
2630 uint32_t originalPointerIndex = splitPointerIndexMap[splitPointerIndex];
Jeff Brownace13b12011-03-09 17:39:48 -08002631 splitPointerCoords[splitPointerIndex].copyFrom(
2632 originalMotionSample->pointerCoords[originalPointerIndex]);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002633 }
2634
Jeff Brownac386072011-07-20 15:19:50 -07002635 splitMotionEntry->appendSample(originalMotionSample->eventTime, splitPointerCoords);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002636 }
2637
Jeff Browna032cc02011-03-07 16:56:21 -08002638 if (originalMotionEntry->injectionState) {
2639 splitMotionEntry->injectionState = originalMotionEntry->injectionState;
2640 splitMotionEntry->injectionState->refCount += 1;
2641 }
2642
Jeff Brown01ce2e92010-09-26 22:20:12 -07002643 return splitMotionEntry;
2644}
2645
Jeff Brownbe1aa822011-07-27 16:04:54 -07002646void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002647#if DEBUG_INBOUND_EVENT_DETAILS
Jeff Brownbe1aa822011-07-27 16:04:54 -07002648 LOGD("notifyConfigurationChanged - eventTime=%lld", args->eventTime);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002649#endif
2650
Jeff Brownb88102f2010-09-08 11:49:43 -07002651 bool needWake;
Jeff Brown46b9ac02010-04-22 18:58:52 -07002652 { // acquire lock
2653 AutoMutex _l(mLock);
2654
Jeff Brownbe1aa822011-07-27 16:04:54 -07002655 ConfigurationChangedEntry* newEntry = new ConfigurationChangedEntry(args->eventTime);
Jeff Brownb88102f2010-09-08 11:49:43 -07002656 needWake = enqueueInboundEventLocked(newEntry);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002657 } // release lock
2658
Jeff Brownb88102f2010-09-08 11:49:43 -07002659 if (needWake) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002660 mLooper->wake();
Jeff Brown46b9ac02010-04-22 18:58:52 -07002661 }
2662}
2663
Jeff Brownbe1aa822011-07-27 16:04:54 -07002664void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002665#if DEBUG_INBOUND_EVENT_DETAILS
Jeff Brown90655042010-12-02 13:50:46 -08002666 LOGD("notifyKey - eventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, action=0x%x, "
Jeff Brown46b9ac02010-04-22 18:58:52 -07002667 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%lld",
Jeff Brownbe1aa822011-07-27 16:04:54 -07002668 args->eventTime, args->deviceId, args->source, args->policyFlags,
2669 args->action, args->flags, args->keyCode, args->scanCode,
2670 args->metaState, args->downTime);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002671#endif
Jeff Brownbe1aa822011-07-27 16:04:54 -07002672 if (!validateKeyEvent(args->action)) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002673 return;
2674 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002675
Jeff Brownbe1aa822011-07-27 16:04:54 -07002676 uint32_t policyFlags = args->policyFlags;
2677 int32_t flags = args->flags;
2678 int32_t metaState = args->metaState;
Jeff Brown1f245102010-11-18 20:53:46 -08002679 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
2680 policyFlags |= POLICY_FLAG_VIRTUAL;
2681 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
2682 }
Jeff Brown924c4d42011-03-07 16:40:47 -08002683 if (policyFlags & POLICY_FLAG_ALT) {
2684 metaState |= AMETA_ALT_ON | AMETA_ALT_LEFT_ON;
2685 }
2686 if (policyFlags & POLICY_FLAG_ALT_GR) {
2687 metaState |= AMETA_ALT_ON | AMETA_ALT_RIGHT_ON;
2688 }
2689 if (policyFlags & POLICY_FLAG_SHIFT) {
2690 metaState |= AMETA_SHIFT_ON | AMETA_SHIFT_LEFT_ON;
2691 }
2692 if (policyFlags & POLICY_FLAG_CAPS_LOCK) {
2693 metaState |= AMETA_CAPS_LOCK_ON;
2694 }
2695 if (policyFlags & POLICY_FLAG_FUNCTION) {
2696 metaState |= AMETA_FUNCTION_ON;
2697 }
Jeff Brown1f245102010-11-18 20:53:46 -08002698
Jeff Browne20c9e02010-10-11 14:20:19 -07002699 policyFlags |= POLICY_FLAG_TRUSTED;
Jeff Brown1f245102010-11-18 20:53:46 -08002700
2701 KeyEvent event;
Jeff Brownbe1aa822011-07-27 16:04:54 -07002702 event.initialize(args->deviceId, args->source, args->action,
2703 flags, args->keyCode, args->scanCode, metaState, 0,
2704 args->downTime, args->eventTime);
Jeff Brown1f245102010-11-18 20:53:46 -08002705
2706 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
2707
2708 if (policyFlags & POLICY_FLAG_WOKE_HERE) {
2709 flags |= AKEY_EVENT_FLAG_WOKE_HERE;
2710 }
Jeff Brownb6997262010-10-08 22:31:17 -07002711
Jeff Brownb88102f2010-09-08 11:49:43 -07002712 bool needWake;
Jeff Brown46b9ac02010-04-22 18:58:52 -07002713 { // acquire lock
Jeff Brown0029c662011-03-30 02:25:18 -07002714 mLock.lock();
2715
2716 if (mInputFilterEnabled) {
2717 mLock.unlock();
2718
2719 policyFlags |= POLICY_FLAG_FILTERED;
2720 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2721 return; // event was consumed by the filter
2722 }
2723
2724 mLock.lock();
2725 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002726
Jeff Brown7fbdc842010-06-17 20:52:56 -07002727 int32_t repeatCount = 0;
Jeff Brownbe1aa822011-07-27 16:04:54 -07002728 KeyEntry* newEntry = new KeyEntry(args->eventTime,
2729 args->deviceId, args->source, policyFlags,
2730 args->action, flags, args->keyCode, args->scanCode,
2731 metaState, repeatCount, args->downTime);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002732
Jeff Brownb88102f2010-09-08 11:49:43 -07002733 needWake = enqueueInboundEventLocked(newEntry);
Jeff Brown0029c662011-03-30 02:25:18 -07002734 mLock.unlock();
Jeff Brown46b9ac02010-04-22 18:58:52 -07002735 } // release lock
2736
Jeff Brownb88102f2010-09-08 11:49:43 -07002737 if (needWake) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002738 mLooper->wake();
Jeff Brown46b9ac02010-04-22 18:58:52 -07002739 }
2740}
2741
Jeff Brownbe1aa822011-07-27 16:04:54 -07002742void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002743#if DEBUG_INBOUND_EVENT_DETAILS
Jeff Brown90655042010-12-02 13:50:46 -08002744 LOGD("notifyMotion - eventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, "
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002745 "action=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, edgeFlags=0x%x, "
Jeff Brown85a31762010-09-01 17:01:00 -07002746 "xPrecision=%f, yPrecision=%f, downTime=%lld",
Jeff Brownbe1aa822011-07-27 16:04:54 -07002747 args->eventTime, args->deviceId, args->source, args->policyFlags,
2748 args->action, args->flags, args->metaState, args->buttonState,
2749 args->edgeFlags, args->xPrecision, args->yPrecision, args->downTime);
2750 for (uint32_t i = 0; i < args->pointerCount; i++) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002751 LOGD(" Pointer %d: id=%d, toolType=%d, "
2752 "x=%f, y=%f, pressure=%f, size=%f, "
Jeff Brown85a31762010-09-01 17:01:00 -07002753 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
Jeff Brown8d608662010-08-30 03:02:23 -07002754 "orientation=%f",
Jeff Brownbe1aa822011-07-27 16:04:54 -07002755 i, args->pointerProperties[i].id,
2756 args->pointerProperties[i].toolType,
2757 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
2758 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
2759 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
2760 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
2761 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
2762 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
2763 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
2764 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
2765 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Jeff Brown46b9ac02010-04-22 18:58:52 -07002766 }
2767#endif
Jeff Brownbe1aa822011-07-27 16:04:54 -07002768 if (!validateMotionEvent(args->action, args->pointerCount, args->pointerProperties)) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002769 return;
2770 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002771
Jeff Brownbe1aa822011-07-27 16:04:54 -07002772 uint32_t policyFlags = args->policyFlags;
Jeff Browne20c9e02010-10-11 14:20:19 -07002773 policyFlags |= POLICY_FLAG_TRUSTED;
Jeff Brownbe1aa822011-07-27 16:04:54 -07002774 mPolicy->interceptMotionBeforeQueueing(args->eventTime, /*byref*/ policyFlags);
Jeff Brownb6997262010-10-08 22:31:17 -07002775
Jeff Brownb88102f2010-09-08 11:49:43 -07002776 bool needWake;
Jeff Brown46b9ac02010-04-22 18:58:52 -07002777 { // acquire lock
Jeff Brown0029c662011-03-30 02:25:18 -07002778 mLock.lock();
2779
2780 if (mInputFilterEnabled) {
2781 mLock.unlock();
2782
2783 MotionEvent event;
Jeff Brownbe1aa822011-07-27 16:04:54 -07002784 event.initialize(args->deviceId, args->source, args->action, args->flags,
2785 args->edgeFlags, args->metaState, args->buttonState, 0, 0,
2786 args->xPrecision, args->yPrecision,
2787 args->downTime, args->eventTime,
2788 args->pointerCount, args->pointerProperties, args->pointerCoords);
Jeff Brown0029c662011-03-30 02:25:18 -07002789
2790 policyFlags |= POLICY_FLAG_FILTERED;
2791 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2792 return; // event was consumed by the filter
2793 }
2794
2795 mLock.lock();
2796 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002797
2798 // Attempt batching and streaming of move events.
Jeff Brownbe1aa822011-07-27 16:04:54 -07002799 if (args->action == AMOTION_EVENT_ACTION_MOVE
2800 || args->action == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002801 // BATCHING CASE
2802 //
2803 // Try to append a move sample to the tail of the inbound queue for this device.
2804 // Give up if we encounter a non-move motion event for this device since that
2805 // means we cannot append any new samples until a new motion event has started.
Jeff Brownac386072011-07-20 15:19:50 -07002806 for (EventEntry* entry = mInboundQueue.tail; entry; entry = entry->prev) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002807 if (entry->type != EventEntry::TYPE_MOTION) {
2808 // Keep looking for motion events.
2809 continue;
2810 }
2811
2812 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
Jeff Brownbe1aa822011-07-27 16:04:54 -07002813 if (motionEntry->deviceId != args->deviceId
2814 || motionEntry->source != args->source) {
Jeff Brownefd32662011-03-08 15:13:06 -08002815 // Keep looking for this device and source.
Jeff Brown46b9ac02010-04-22 18:58:52 -07002816 continue;
2817 }
2818
Jeff Brownbe1aa822011-07-27 16:04:54 -07002819 if (!motionEntry->canAppendSamples(args->action,
2820 args->pointerCount, args->pointerProperties)) {
Jeff Brownefd32662011-03-08 15:13:06 -08002821 // Last motion event in the queue for this device and source is
2822 // not compatible for appending new samples. Stop here.
Jeff Brown46b9ac02010-04-22 18:58:52 -07002823 goto NoBatchingOrStreaming;
2824 }
2825
Jeff Brown9c3cda02010-06-15 01:31:58 -07002826 // Do the batching magic.
Jeff Brownbe1aa822011-07-27 16:04:54 -07002827 batchMotionLocked(motionEntry, args->eventTime,
2828 args->metaState, args->pointerCoords,
Jeff Brown4e91a182011-04-07 11:38:09 -07002829 "most recent motion event for this device and source in the inbound queue");
Jeff Brown0029c662011-03-30 02:25:18 -07002830 mLock.unlock();
Jeff Brown9c3cda02010-06-15 01:31:58 -07002831 return; // done!
Jeff Brown46b9ac02010-04-22 18:58:52 -07002832 }
2833
Jeff Brownf6989da2011-04-06 17:19:48 -07002834 // BATCHING ONTO PENDING EVENT CASE
2835 //
2836 // Try to append a move sample to the currently pending event, if there is one.
2837 // We can do this as long as we are still waiting to find the targets for the
2838 // event. Once the targets are locked-in we can only do streaming.
2839 if (mPendingEvent
2840 && (!mPendingEvent->dispatchInProgress || !mCurrentInputTargetsValid)
2841 && mPendingEvent->type == EventEntry::TYPE_MOTION) {
2842 MotionEntry* motionEntry = static_cast<MotionEntry*>(mPendingEvent);
Jeff Brownbe1aa822011-07-27 16:04:54 -07002843 if (motionEntry->deviceId == args->deviceId
2844 && motionEntry->source == args->source) {
2845 if (!motionEntry->canAppendSamples(args->action,
2846 args->pointerCount, args->pointerProperties)) {
Jeff Brown4e91a182011-04-07 11:38:09 -07002847 // Pending motion event is for this device and source but it is
2848 // not compatible for appending new samples. Stop here.
Jeff Brownf6989da2011-04-06 17:19:48 -07002849 goto NoBatchingOrStreaming;
2850 }
2851
Jeff Brownf6989da2011-04-06 17:19:48 -07002852 // Do the batching magic.
Jeff Brownbe1aa822011-07-27 16:04:54 -07002853 batchMotionLocked(motionEntry, args->eventTime,
2854 args->metaState, args->pointerCoords,
Jeff Brown4e91a182011-04-07 11:38:09 -07002855 "pending motion event");
Jeff Brownf6989da2011-04-06 17:19:48 -07002856 mLock.unlock();
2857 return; // done!
2858 }
2859 }
2860
Jeff Brown46b9ac02010-04-22 18:58:52 -07002861 // STREAMING CASE
2862 //
2863 // There is no pending motion event (of any kind) for this device in the inbound queue.
Jeff Brown519e0242010-09-15 15:18:56 -07002864 // Search the outbound queue for the current foreground targets to find a dispatched
2865 // motion event that is still in progress. If found, then, appen the new sample to
2866 // that event and push it out to all current targets. The logic in
2867 // prepareDispatchCycleLocked takes care of the case where some targets may
2868 // already have consumed the motion event by starting a new dispatch cycle if needed.
Jeff Brown9c3cda02010-06-15 01:31:58 -07002869 if (mCurrentInputTargetsValid) {
Jeff Brown519e0242010-09-15 15:18:56 -07002870 for (size_t i = 0; i < mCurrentInputTargets.size(); i++) {
2871 const InputTarget& inputTarget = mCurrentInputTargets[i];
2872 if ((inputTarget.flags & InputTarget::FLAG_FOREGROUND) == 0) {
2873 // Skip non-foreground targets. We only want to stream if there is at
2874 // least one foreground target whose dispatch is still in progress.
2875 continue;
Jeff Brown46b9ac02010-04-22 18:58:52 -07002876 }
Jeff Brown519e0242010-09-15 15:18:56 -07002877
2878 ssize_t connectionIndex = getConnectionIndexLocked(inputTarget.inputChannel);
2879 if (connectionIndex < 0) {
2880 // Connection must no longer be valid.
2881 continue;
2882 }
2883
2884 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
2885 if (connection->outboundQueue.isEmpty()) {
2886 // This foreground target has an empty outbound queue.
2887 continue;
2888 }
2889
Jeff Brownac386072011-07-20 15:19:50 -07002890 DispatchEntry* dispatchEntry = connection->outboundQueue.head;
Jeff Brown519e0242010-09-15 15:18:56 -07002891 if (! dispatchEntry->inProgress
Jeff Brown01ce2e92010-09-26 22:20:12 -07002892 || dispatchEntry->eventEntry->type != EventEntry::TYPE_MOTION
2893 || dispatchEntry->isSplit()) {
2894 // No motion event is being dispatched, or it is being split across
2895 // windows in which case we cannot stream.
Jeff Brown519e0242010-09-15 15:18:56 -07002896 continue;
2897 }
2898
2899 MotionEntry* motionEntry = static_cast<MotionEntry*>(
2900 dispatchEntry->eventEntry);
Jeff Brownbe1aa822011-07-27 16:04:54 -07002901 if (motionEntry->action != args->action
2902 || motionEntry->deviceId != args->deviceId
2903 || motionEntry->source != args->source
2904 || motionEntry->pointerCount != args->pointerCount
Jeff Brown519e0242010-09-15 15:18:56 -07002905 || motionEntry->isInjected()) {
2906 // The motion event is not compatible with this move.
2907 continue;
2908 }
2909
Jeff Brownbe1aa822011-07-27 16:04:54 -07002910 if (args->action == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Jeff Brown9302c872011-07-13 22:51:29 -07002911 if (mLastHoverWindowHandle == NULL) {
Jeff Browna032cc02011-03-07 16:56:21 -08002912#if DEBUG_BATCHING
2913 LOGD("Not streaming hover move because there is no "
2914 "last hovered window.");
2915#endif
2916 goto NoBatchingOrStreaming;
2917 }
2918
Jeff Brown9302c872011-07-13 22:51:29 -07002919 sp<InputWindowHandle> hoverWindowHandle = findTouchedWindowAtLocked(
Jeff Brownbe1aa822011-07-27 16:04:54 -07002920 args->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X),
2921 args->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Jeff Brown9302c872011-07-13 22:51:29 -07002922 if (mLastHoverWindowHandle != hoverWindowHandle) {
Jeff Browna032cc02011-03-07 16:56:21 -08002923#if DEBUG_BATCHING
2924 LOGD("Not streaming hover move because the last hovered window "
2925 "is '%s' but the currently hovered window is '%s'.",
Jeff Browncc4f7db2011-08-30 20:34:48 -07002926 mLastHoverWindowHandle->getName().string(),
Jeff Brown9302c872011-07-13 22:51:29 -07002927 hoverWindowHandle != NULL
Jeff Browncc4f7db2011-08-30 20:34:48 -07002928 ? hoverWindowHandle->getName().string() : "<null>");
Jeff Browna032cc02011-03-07 16:56:21 -08002929#endif
2930 goto NoBatchingOrStreaming;
2931 }
2932 }
2933
Jeff Brown519e0242010-09-15 15:18:56 -07002934 // Hurray! This foreground target is currently dispatching a move event
2935 // that we can stream onto. Append the motion sample and resume dispatch.
Jeff Brownbe1aa822011-07-27 16:04:54 -07002936 motionEntry->appendSample(args->eventTime, args->pointerCoords);
Jeff Brown519e0242010-09-15 15:18:56 -07002937#if DEBUG_BATCHING
2938 LOGD("Appended motion sample onto batch for most recently dispatched "
Jeff Brown4e91a182011-04-07 11:38:09 -07002939 "motion event for this device and source in the outbound queues. "
Jeff Brown519e0242010-09-15 15:18:56 -07002940 "Attempting to stream the motion sample.");
2941#endif
2942 nsecs_t currentTime = now();
2943 dispatchEventToCurrentInputTargetsLocked(currentTime, motionEntry,
2944 true /*resumeWithAppendedMotionSample*/);
2945
2946 runCommandsLockedInterruptible();
Jeff Brown0029c662011-03-30 02:25:18 -07002947 mLock.unlock();
Jeff Brown519e0242010-09-15 15:18:56 -07002948 return; // done!
Jeff Brown46b9ac02010-04-22 18:58:52 -07002949 }
2950 }
2951
2952NoBatchingOrStreaming:;
2953 }
2954
2955 // Just enqueue a new motion event.
Jeff Brownbe1aa822011-07-27 16:04:54 -07002956 MotionEntry* newEntry = new MotionEntry(args->eventTime,
2957 args->deviceId, args->source, policyFlags,
2958 args->action, args->flags, args->metaState, args->buttonState,
2959 args->edgeFlags, args->xPrecision, args->yPrecision, args->downTime,
2960 args->pointerCount, args->pointerProperties, args->pointerCoords);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002961
Jeff Brownb88102f2010-09-08 11:49:43 -07002962 needWake = enqueueInboundEventLocked(newEntry);
Jeff Brown0029c662011-03-30 02:25:18 -07002963 mLock.unlock();
Jeff Brown46b9ac02010-04-22 18:58:52 -07002964 } // release lock
2965
Jeff Brownb88102f2010-09-08 11:49:43 -07002966 if (needWake) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002967 mLooper->wake();
Jeff Brown46b9ac02010-04-22 18:58:52 -07002968 }
2969}
2970
Jeff Brown4e91a182011-04-07 11:38:09 -07002971void InputDispatcher::batchMotionLocked(MotionEntry* entry, nsecs_t eventTime,
2972 int32_t metaState, const PointerCoords* pointerCoords, const char* eventDescription) {
2973 // Combine meta states.
2974 entry->metaState |= metaState;
2975
2976 // Coalesce this sample if not enough time has elapsed since the last sample was
2977 // initially appended to the batch.
2978 MotionSample* lastSample = entry->lastSample;
2979 long interval = eventTime - lastSample->eventTimeBeforeCoalescing;
2980 if (interval <= MOTION_SAMPLE_COALESCE_INTERVAL) {
2981 uint32_t pointerCount = entry->pointerCount;
2982 for (uint32_t i = 0; i < pointerCount; i++) {
2983 lastSample->pointerCoords[i].copyFrom(pointerCoords[i]);
2984 }
2985 lastSample->eventTime = eventTime;
2986#if DEBUG_BATCHING
2987 LOGD("Coalesced motion into last sample of batch for %s, events were %0.3f ms apart",
2988 eventDescription, interval * 0.000001f);
2989#endif
2990 return;
2991 }
2992
2993 // Append the sample.
Jeff Brownac386072011-07-20 15:19:50 -07002994 entry->appendSample(eventTime, pointerCoords);
Jeff Brown4e91a182011-04-07 11:38:09 -07002995#if DEBUG_BATCHING
2996 LOGD("Appended motion sample onto batch for %s, events were %0.3f ms apart",
2997 eventDescription, interval * 0.000001f);
2998#endif
2999}
3000
Jeff Brownbe1aa822011-07-27 16:04:54 -07003001void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
Jeff Brownb6997262010-10-08 22:31:17 -07003002#if DEBUG_INBOUND_EVENT_DETAILS
Jeff Brownbe1aa822011-07-27 16:04:54 -07003003 LOGD("notifySwitch - eventTime=%lld, policyFlags=0x%x, switchCode=%d, switchValue=%d",
3004 args->eventTime, args->policyFlags,
3005 args->switchCode, args->switchValue);
Jeff Brownb6997262010-10-08 22:31:17 -07003006#endif
3007
Jeff Brownbe1aa822011-07-27 16:04:54 -07003008 uint32_t policyFlags = args->policyFlags;
Jeff Browne20c9e02010-10-11 14:20:19 -07003009 policyFlags |= POLICY_FLAG_TRUSTED;
Jeff Brownbe1aa822011-07-27 16:04:54 -07003010 mPolicy->notifySwitch(args->eventTime,
3011 args->switchCode, args->switchValue, policyFlags);
Jeff Brownb6997262010-10-08 22:31:17 -07003012}
3013
Jeff Brown65fd2512011-08-18 11:20:58 -07003014void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
3015#if DEBUG_INBOUND_EVENT_DETAILS
3016 LOGD("notifyDeviceReset - eventTime=%lld, deviceId=%d",
3017 args->eventTime, args->deviceId);
3018#endif
3019
3020 bool needWake;
3021 { // acquire lock
3022 AutoMutex _l(mLock);
3023
3024 DeviceResetEntry* newEntry = new DeviceResetEntry(args->eventTime, args->deviceId);
3025 needWake = enqueueInboundEventLocked(newEntry);
3026 } // release lock
3027
3028 if (needWake) {
3029 mLooper->wake();
3030 }
3031}
3032
Jeff Brown7fbdc842010-06-17 20:52:56 -07003033int32_t InputDispatcher::injectInputEvent(const InputEvent* event,
Jeff Brown0029c662011-03-30 02:25:18 -07003034 int32_t injectorPid, int32_t injectorUid, int32_t syncMode, int32_t timeoutMillis,
3035 uint32_t policyFlags) {
Jeff Brown7fbdc842010-06-17 20:52:56 -07003036#if DEBUG_INBOUND_EVENT_DETAILS
3037 LOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Jeff Brown0029c662011-03-30 02:25:18 -07003038 "syncMode=%d, timeoutMillis=%d, policyFlags=0x%08x",
3039 event->getType(), injectorPid, injectorUid, syncMode, timeoutMillis, policyFlags);
Jeff Brown7fbdc842010-06-17 20:52:56 -07003040#endif
3041
3042 nsecs_t endTime = now() + milliseconds_to_nanoseconds(timeoutMillis);
Jeff Browne20c9e02010-10-11 14:20:19 -07003043
Jeff Brown0029c662011-03-30 02:25:18 -07003044 policyFlags |= POLICY_FLAG_INJECTED;
Jeff Browne20c9e02010-10-11 14:20:19 -07003045 if (hasInjectionPermission(injectorPid, injectorUid)) {
3046 policyFlags |= POLICY_FLAG_TRUSTED;
3047 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07003048
Jeff Brownb6997262010-10-08 22:31:17 -07003049 EventEntry* injectedEntry;
3050 switch (event->getType()) {
3051 case AINPUT_EVENT_TYPE_KEY: {
3052 const KeyEvent* keyEvent = static_cast<const KeyEvent*>(event);
3053 int32_t action = keyEvent->getAction();
3054 if (! validateKeyEvent(action)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07003055 return INPUT_EVENT_INJECTION_FAILED;
3056 }
3057
Jeff Brownb6997262010-10-08 22:31:17 -07003058 int32_t flags = keyEvent->getFlags();
Jeff Brown1f245102010-11-18 20:53:46 -08003059 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
3060 policyFlags |= POLICY_FLAG_VIRTUAL;
3061 }
3062
Jeff Brown0029c662011-03-30 02:25:18 -07003063 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3064 mPolicy->interceptKeyBeforeQueueing(keyEvent, /*byref*/ policyFlags);
3065 }
Jeff Brown1f245102010-11-18 20:53:46 -08003066
3067 if (policyFlags & POLICY_FLAG_WOKE_HERE) {
3068 flags |= AKEY_EVENT_FLAG_WOKE_HERE;
3069 }
Jeff Brown6ec402b2010-07-28 15:48:59 -07003070
Jeff Brownb6997262010-10-08 22:31:17 -07003071 mLock.lock();
Jeff Brownac386072011-07-20 15:19:50 -07003072 injectedEntry = new KeyEntry(keyEvent->getEventTime(),
Jeff Brown1f245102010-11-18 20:53:46 -08003073 keyEvent->getDeviceId(), keyEvent->getSource(),
3074 policyFlags, action, flags,
3075 keyEvent->getKeyCode(), keyEvent->getScanCode(), keyEvent->getMetaState(),
Jeff Brownb6997262010-10-08 22:31:17 -07003076 keyEvent->getRepeatCount(), keyEvent->getDownTime());
3077 break;
3078 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07003079
Jeff Brownb6997262010-10-08 22:31:17 -07003080 case AINPUT_EVENT_TYPE_MOTION: {
3081 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
3082 int32_t action = motionEvent->getAction();
3083 size_t pointerCount = motionEvent->getPointerCount();
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003084 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
3085 if (! validateMotionEvent(action, pointerCount, pointerProperties)) {
Jeff Brownb6997262010-10-08 22:31:17 -07003086 return INPUT_EVENT_INJECTION_FAILED;
3087 }
3088
Jeff Brown0029c662011-03-30 02:25:18 -07003089 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3090 nsecs_t eventTime = motionEvent->getEventTime();
3091 mPolicy->interceptMotionBeforeQueueing(eventTime, /*byref*/ policyFlags);
3092 }
Jeff Brownb6997262010-10-08 22:31:17 -07003093
3094 mLock.lock();
3095 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
3096 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
Jeff Brownac386072011-07-20 15:19:50 -07003097 MotionEntry* motionEntry = new MotionEntry(*sampleEventTimes,
Jeff Brownb6997262010-10-08 22:31:17 -07003098 motionEvent->getDeviceId(), motionEvent->getSource(), policyFlags,
3099 action, motionEvent->getFlags(),
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003100 motionEvent->getMetaState(), motionEvent->getButtonState(),
3101 motionEvent->getEdgeFlags(),
Jeff Brownb6997262010-10-08 22:31:17 -07003102 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
3103 motionEvent->getDownTime(), uint32_t(pointerCount),
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003104 pointerProperties, samplePointerCoords);
Jeff Brownb6997262010-10-08 22:31:17 -07003105 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
3106 sampleEventTimes += 1;
3107 samplePointerCoords += pointerCount;
Jeff Brownac386072011-07-20 15:19:50 -07003108 motionEntry->appendSample(*sampleEventTimes, samplePointerCoords);
Jeff Brownb6997262010-10-08 22:31:17 -07003109 }
3110 injectedEntry = motionEntry;
3111 break;
3112 }
3113
3114 default:
3115 LOGW("Cannot inject event of type %d", event->getType());
3116 return INPUT_EVENT_INJECTION_FAILED;
3117 }
3118
Jeff Brownac386072011-07-20 15:19:50 -07003119 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
Jeff Brownb6997262010-10-08 22:31:17 -07003120 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
3121 injectionState->injectionIsAsync = true;
3122 }
3123
3124 injectionState->refCount += 1;
3125 injectedEntry->injectionState = injectionState;
3126
3127 bool needWake = enqueueInboundEventLocked(injectedEntry);
3128 mLock.unlock();
Jeff Brown7fbdc842010-06-17 20:52:56 -07003129
Jeff Brownb88102f2010-09-08 11:49:43 -07003130 if (needWake) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07003131 mLooper->wake();
Jeff Brown7fbdc842010-06-17 20:52:56 -07003132 }
3133
3134 int32_t injectionResult;
3135 { // acquire lock
3136 AutoMutex _l(mLock);
3137
Jeff Brown6ec402b2010-07-28 15:48:59 -07003138 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
3139 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
3140 } else {
3141 for (;;) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07003142 injectionResult = injectionState->injectionResult;
Jeff Brown6ec402b2010-07-28 15:48:59 -07003143 if (injectionResult != INPUT_EVENT_INJECTION_PENDING) {
3144 break;
3145 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07003146
Jeff Brown7fbdc842010-06-17 20:52:56 -07003147 nsecs_t remainingTimeout = endTime - now();
3148 if (remainingTimeout <= 0) {
Jeff Brown6ec402b2010-07-28 15:48:59 -07003149#if DEBUG_INJECTION
3150 LOGD("injectInputEvent - Timed out waiting for injection result "
3151 "to become available.");
3152#endif
Jeff Brown7fbdc842010-06-17 20:52:56 -07003153 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
3154 break;
3155 }
3156
Jeff Brown6ec402b2010-07-28 15:48:59 -07003157 mInjectionResultAvailableCondition.waitRelative(mLock, remainingTimeout);
3158 }
3159
3160 if (injectionResult == INPUT_EVENT_INJECTION_SUCCEEDED
3161 && syncMode == INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07003162 while (injectionState->pendingForegroundDispatches != 0) {
Jeff Brown6ec402b2010-07-28 15:48:59 -07003163#if DEBUG_INJECTION
Jeff Brown519e0242010-09-15 15:18:56 -07003164 LOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
Jeff Brown01ce2e92010-09-26 22:20:12 -07003165 injectionState->pendingForegroundDispatches);
Jeff Brown6ec402b2010-07-28 15:48:59 -07003166#endif
3167 nsecs_t remainingTimeout = endTime - now();
3168 if (remainingTimeout <= 0) {
3169#if DEBUG_INJECTION
Jeff Brown519e0242010-09-15 15:18:56 -07003170 LOGD("injectInputEvent - Timed out waiting for pending foreground "
Jeff Brown6ec402b2010-07-28 15:48:59 -07003171 "dispatches to finish.");
3172#endif
3173 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
3174 break;
3175 }
3176
3177 mInjectionSyncFinishedCondition.waitRelative(mLock, remainingTimeout);
3178 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07003179 }
3180 }
3181
Jeff Brownac386072011-07-20 15:19:50 -07003182 injectionState->release();
Jeff Brown7fbdc842010-06-17 20:52:56 -07003183 } // release lock
3184
Jeff Brown6ec402b2010-07-28 15:48:59 -07003185#if DEBUG_INJECTION
3186 LOGD("injectInputEvent - Finished with result %d. "
3187 "injectorPid=%d, injectorUid=%d",
3188 injectionResult, injectorPid, injectorUid);
3189#endif
3190
Jeff Brown7fbdc842010-06-17 20:52:56 -07003191 return injectionResult;
3192}
3193
Jeff Brownb6997262010-10-08 22:31:17 -07003194bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
3195 return injectorUid == 0
3196 || mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
3197}
3198
Jeff Brown7fbdc842010-06-17 20:52:56 -07003199void InputDispatcher::setInjectionResultLocked(EventEntry* entry, int32_t injectionResult) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07003200 InjectionState* injectionState = entry->injectionState;
3201 if (injectionState) {
Jeff Brown7fbdc842010-06-17 20:52:56 -07003202#if DEBUG_INJECTION
3203 LOGD("Setting input event injection result to %d. "
3204 "injectorPid=%d, injectorUid=%d",
Jeff Brown01ce2e92010-09-26 22:20:12 -07003205 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
Jeff Brown7fbdc842010-06-17 20:52:56 -07003206#endif
3207
Jeff Brown0029c662011-03-30 02:25:18 -07003208 if (injectionState->injectionIsAsync
3209 && !(entry->policyFlags & POLICY_FLAG_FILTERED)) {
Jeff Brown6ec402b2010-07-28 15:48:59 -07003210 // Log the outcome since the injector did not wait for the injection result.
3211 switch (injectionResult) {
3212 case INPUT_EVENT_INJECTION_SUCCEEDED:
3213 LOGV("Asynchronous input event injection succeeded.");
3214 break;
3215 case INPUT_EVENT_INJECTION_FAILED:
3216 LOGW("Asynchronous input event injection failed.");
3217 break;
3218 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
3219 LOGW("Asynchronous input event injection permission denied.");
3220 break;
3221 case INPUT_EVENT_INJECTION_TIMED_OUT:
3222 LOGW("Asynchronous input event injection timed out.");
3223 break;
3224 }
3225 }
3226
Jeff Brown01ce2e92010-09-26 22:20:12 -07003227 injectionState->injectionResult = injectionResult;
Jeff Brown7fbdc842010-06-17 20:52:56 -07003228 mInjectionResultAvailableCondition.broadcast();
3229 }
3230}
3231
Jeff Brown01ce2e92010-09-26 22:20:12 -07003232void InputDispatcher::incrementPendingForegroundDispatchesLocked(EventEntry* entry) {
3233 InjectionState* injectionState = entry->injectionState;
3234 if (injectionState) {
3235 injectionState->pendingForegroundDispatches += 1;
3236 }
3237}
3238
Jeff Brown519e0242010-09-15 15:18:56 -07003239void InputDispatcher::decrementPendingForegroundDispatchesLocked(EventEntry* entry) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07003240 InjectionState* injectionState = entry->injectionState;
3241 if (injectionState) {
3242 injectionState->pendingForegroundDispatches -= 1;
Jeff Brown6ec402b2010-07-28 15:48:59 -07003243
Jeff Brown01ce2e92010-09-26 22:20:12 -07003244 if (injectionState->pendingForegroundDispatches == 0) {
3245 mInjectionSyncFinishedCondition.broadcast();
3246 }
Jeff Brownb88102f2010-09-08 11:49:43 -07003247 }
3248}
3249
Jeff Brown9302c872011-07-13 22:51:29 -07003250sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
3251 const sp<InputChannel>& inputChannel) const {
3252 size_t numWindows = mWindowHandles.size();
3253 for (size_t i = 0; i < numWindows; i++) {
3254 const sp<InputWindowHandle>& windowHandle = mWindowHandles.itemAt(i);
Jeff Browncc4f7db2011-08-30 20:34:48 -07003255 if (windowHandle->getInputChannel() == inputChannel) {
Jeff Brown9302c872011-07-13 22:51:29 -07003256 return windowHandle;
Jeff Brown01ce2e92010-09-26 22:20:12 -07003257 }
3258 }
3259 return NULL;
3260}
3261
Jeff Brown9302c872011-07-13 22:51:29 -07003262bool InputDispatcher::hasWindowHandleLocked(
3263 const sp<InputWindowHandle>& windowHandle) const {
3264 size_t numWindows = mWindowHandles.size();
3265 for (size_t i = 0; i < numWindows; i++) {
3266 if (mWindowHandles.itemAt(i) == windowHandle) {
3267 return true;
3268 }
3269 }
3270 return false;
3271}
3272
3273void InputDispatcher::setInputWindows(const Vector<sp<InputWindowHandle> >& inputWindowHandles) {
Jeff Brownb88102f2010-09-08 11:49:43 -07003274#if DEBUG_FOCUS
3275 LOGD("setInputWindows");
3276#endif
3277 { // acquire lock
3278 AutoMutex _l(mLock);
3279
Jeff Browncc4f7db2011-08-30 20:34:48 -07003280 Vector<sp<InputWindowHandle> > oldWindowHandles = mWindowHandles;
Jeff Brown9302c872011-07-13 22:51:29 -07003281 mWindowHandles = inputWindowHandles;
Jeff Brownb6997262010-10-08 22:31:17 -07003282
Jeff Brown9302c872011-07-13 22:51:29 -07003283 sp<InputWindowHandle> newFocusedWindowHandle;
3284 bool foundHoveredWindow = false;
3285 for (size_t i = 0; i < mWindowHandles.size(); i++) {
3286 const sp<InputWindowHandle>& windowHandle = mWindowHandles.itemAt(i);
Jeff Browncc4f7db2011-08-30 20:34:48 -07003287 if (!windowHandle->updateInfo() || windowHandle->getInputChannel() == NULL) {
Jeff Brown9302c872011-07-13 22:51:29 -07003288 mWindowHandles.removeAt(i--);
3289 continue;
3290 }
Jeff Browncc4f7db2011-08-30 20:34:48 -07003291 if (windowHandle->getInfo()->hasFocus) {
Jeff Brown9302c872011-07-13 22:51:29 -07003292 newFocusedWindowHandle = windowHandle;
3293 }
3294 if (windowHandle == mLastHoverWindowHandle) {
3295 foundHoveredWindow = true;
Jeff Brownb88102f2010-09-08 11:49:43 -07003296 }
3297 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07003298
Jeff Brown9302c872011-07-13 22:51:29 -07003299 if (!foundHoveredWindow) {
3300 mLastHoverWindowHandle = NULL;
3301 }
3302
3303 if (mFocusedWindowHandle != newFocusedWindowHandle) {
3304 if (mFocusedWindowHandle != NULL) {
Jeff Brownb6997262010-10-08 22:31:17 -07003305#if DEBUG_FOCUS
3306 LOGD("Focus left window: %s",
Jeff Browncc4f7db2011-08-30 20:34:48 -07003307 mFocusedWindowHandle->getName().string());
Jeff Brownb6997262010-10-08 22:31:17 -07003308#endif
Jeff Browncc4f7db2011-08-30 20:34:48 -07003309 sp<InputChannel> focusedInputChannel = mFocusedWindowHandle->getInputChannel();
3310 if (focusedInputChannel != NULL) {
Christopher Tated9be36c2011-08-16 16:09:33 -07003311 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
3312 "focus left window");
3313 synthesizeCancelationEventsForInputChannelLocked(
Jeff Browncc4f7db2011-08-30 20:34:48 -07003314 focusedInputChannel, options);
Christopher Tated9be36c2011-08-16 16:09:33 -07003315 }
Jeff Brownb6997262010-10-08 22:31:17 -07003316 }
Jeff Brown9302c872011-07-13 22:51:29 -07003317 if (newFocusedWindowHandle != NULL) {
Jeff Brownb6997262010-10-08 22:31:17 -07003318#if DEBUG_FOCUS
Jeff Brown9302c872011-07-13 22:51:29 -07003319 LOGD("Focus entered window: %s",
Jeff Browncc4f7db2011-08-30 20:34:48 -07003320 newFocusedWindowHandle->getName().string());
Jeff Brownb6997262010-10-08 22:31:17 -07003321#endif
Jeff Brown9302c872011-07-13 22:51:29 -07003322 }
3323 mFocusedWindowHandle = newFocusedWindowHandle;
Jeff Brownb6997262010-10-08 22:31:17 -07003324 }
3325
Jeff Brown9302c872011-07-13 22:51:29 -07003326 for (size_t i = 0; i < mTouchState.windows.size(); i++) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07003327 TouchedWindow& touchedWindow = mTouchState.windows.editItemAt(i);
Jeff Brown9302c872011-07-13 22:51:29 -07003328 if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
Jeff Brownb6997262010-10-08 22:31:17 -07003329#if DEBUG_FOCUS
Jeff Browncc4f7db2011-08-30 20:34:48 -07003330 LOGD("Touched window was removed: %s",
3331 touchedWindow.windowHandle->getName().string());
Jeff Brownb6997262010-10-08 22:31:17 -07003332#endif
Jeff Browncc4f7db2011-08-30 20:34:48 -07003333 sp<InputChannel> touchedInputChannel =
3334 touchedWindow.windowHandle->getInputChannel();
3335 if (touchedInputChannel != NULL) {
Christopher Tated9be36c2011-08-16 16:09:33 -07003336 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
3337 "touched window was removed");
3338 synthesizeCancelationEventsForInputChannelLocked(
Jeff Browncc4f7db2011-08-30 20:34:48 -07003339 touchedInputChannel, options);
Christopher Tated9be36c2011-08-16 16:09:33 -07003340 }
Jeff Brown9302c872011-07-13 22:51:29 -07003341 mTouchState.windows.removeAt(i--);
Jeff Brown01ce2e92010-09-26 22:20:12 -07003342 }
3343 }
Jeff Browncc4f7db2011-08-30 20:34:48 -07003344
3345 // Release information for windows that are no longer present.
3346 // This ensures that unused input channels are released promptly.
3347 // Otherwise, they might stick around until the window handle is destroyed
3348 // which might not happen until the next GC.
3349 for (size_t i = 0; i < oldWindowHandles.size(); i++) {
3350 const sp<InputWindowHandle>& oldWindowHandle = oldWindowHandles.itemAt(i);
3351 if (!hasWindowHandleLocked(oldWindowHandle)) {
3352#if DEBUG_FOCUS
3353 LOGD("Window went away: %s", oldWindowHandle->getName().string());
3354#endif
3355 oldWindowHandle->releaseInfo();
3356 }
3357 }
Jeff Brownb88102f2010-09-08 11:49:43 -07003358 } // release lock
3359
3360 // Wake up poll loop since it may need to make new input dispatching choices.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07003361 mLooper->wake();
Jeff Brownb88102f2010-09-08 11:49:43 -07003362}
3363
Jeff Brown9302c872011-07-13 22:51:29 -07003364void InputDispatcher::setFocusedApplication(
3365 const sp<InputApplicationHandle>& inputApplicationHandle) {
Jeff Brownb88102f2010-09-08 11:49:43 -07003366#if DEBUG_FOCUS
3367 LOGD("setFocusedApplication");
3368#endif
3369 { // acquire lock
3370 AutoMutex _l(mLock);
3371
Jeff Browncc4f7db2011-08-30 20:34:48 -07003372 if (inputApplicationHandle != NULL && inputApplicationHandle->updateInfo()) {
Jeff Brown5ea29ab2011-07-27 11:50:51 -07003373 if (mFocusedApplicationHandle != inputApplicationHandle) {
3374 if (mFocusedApplicationHandle != NULL) {
3375 resetTargetsLocked();
Jeff Browncc4f7db2011-08-30 20:34:48 -07003376 mFocusedApplicationHandle->releaseInfo();
Jeff Brown5ea29ab2011-07-27 11:50:51 -07003377 }
3378 mFocusedApplicationHandle = inputApplicationHandle;
3379 }
3380 } else if (mFocusedApplicationHandle != NULL) {
3381 resetTargetsLocked();
Jeff Browncc4f7db2011-08-30 20:34:48 -07003382 mFocusedApplicationHandle->releaseInfo();
Jeff Brown9302c872011-07-13 22:51:29 -07003383 mFocusedApplicationHandle.clear();
Jeff Brownb88102f2010-09-08 11:49:43 -07003384 }
3385
3386#if DEBUG_FOCUS
Jeff Brownb6997262010-10-08 22:31:17 -07003387 //logDispatchStateLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -07003388#endif
3389 } // release lock
3390
3391 // Wake up poll loop since it may need to make new input dispatching choices.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07003392 mLooper->wake();
Jeff Brownb88102f2010-09-08 11:49:43 -07003393}
3394
Jeff Brownb88102f2010-09-08 11:49:43 -07003395void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
3396#if DEBUG_FOCUS
3397 LOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
3398#endif
3399
3400 bool changed;
3401 { // acquire lock
3402 AutoMutex _l(mLock);
3403
3404 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
Jeff Brown120a4592010-10-27 18:43:51 -07003405 if (mDispatchFrozen && !frozen) {
Jeff Brownb88102f2010-09-08 11:49:43 -07003406 resetANRTimeoutsLocked();
3407 }
3408
Jeff Brown120a4592010-10-27 18:43:51 -07003409 if (mDispatchEnabled && !enabled) {
3410 resetAndDropEverythingLocked("dispatcher is being disabled");
3411 }
3412
Jeff Brownb88102f2010-09-08 11:49:43 -07003413 mDispatchEnabled = enabled;
3414 mDispatchFrozen = frozen;
3415 changed = true;
3416 } else {
3417 changed = false;
3418 }
3419
3420#if DEBUG_FOCUS
Jeff Brownb6997262010-10-08 22:31:17 -07003421 //logDispatchStateLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -07003422#endif
3423 } // release lock
3424
3425 if (changed) {
3426 // Wake up poll loop since it may need to make new input dispatching choices.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07003427 mLooper->wake();
Jeff Brown46b9ac02010-04-22 18:58:52 -07003428 }
3429}
3430
Jeff Brown0029c662011-03-30 02:25:18 -07003431void InputDispatcher::setInputFilterEnabled(bool enabled) {
3432#if DEBUG_FOCUS
3433 LOGD("setInputFilterEnabled: enabled=%d", enabled);
3434#endif
3435
3436 { // acquire lock
3437 AutoMutex _l(mLock);
3438
3439 if (mInputFilterEnabled == enabled) {
3440 return;
3441 }
3442
3443 mInputFilterEnabled = enabled;
3444 resetAndDropEverythingLocked("input filter is being enabled or disabled");
3445 } // release lock
3446
3447 // Wake up poll loop since there might be work to do to drop everything.
3448 mLooper->wake();
3449}
3450
Jeff Browne6504122010-09-27 14:52:15 -07003451bool InputDispatcher::transferTouchFocus(const sp<InputChannel>& fromChannel,
3452 const sp<InputChannel>& toChannel) {
3453#if DEBUG_FOCUS
3454 LOGD("transferTouchFocus: fromChannel=%s, toChannel=%s",
3455 fromChannel->getName().string(), toChannel->getName().string());
3456#endif
3457 { // acquire lock
3458 AutoMutex _l(mLock);
3459
Jeff Brown9302c872011-07-13 22:51:29 -07003460 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromChannel);
3461 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toChannel);
3462 if (fromWindowHandle == NULL || toWindowHandle == NULL) {
Jeff Browne6504122010-09-27 14:52:15 -07003463#if DEBUG_FOCUS
3464 LOGD("Cannot transfer focus because from or to window not found.");
3465#endif
3466 return false;
3467 }
Jeff Brown9302c872011-07-13 22:51:29 -07003468 if (fromWindowHandle == toWindowHandle) {
Jeff Browne6504122010-09-27 14:52:15 -07003469#if DEBUG_FOCUS
3470 LOGD("Trivial transfer to same window.");
3471#endif
3472 return true;
3473 }
3474
3475 bool found = false;
3476 for (size_t i = 0; i < mTouchState.windows.size(); i++) {
3477 const TouchedWindow& touchedWindow = mTouchState.windows[i];
Jeff Brown9302c872011-07-13 22:51:29 -07003478 if (touchedWindow.windowHandle == fromWindowHandle) {
Jeff Browne6504122010-09-27 14:52:15 -07003479 int32_t oldTargetFlags = touchedWindow.targetFlags;
3480 BitSet32 pointerIds = touchedWindow.pointerIds;
3481
3482 mTouchState.windows.removeAt(i);
3483
Jeff Brown46e75292010-11-10 16:53:45 -08003484 int32_t newTargetFlags = oldTargetFlags
Jeff Browna032cc02011-03-07 16:56:21 -08003485 & (InputTarget::FLAG_FOREGROUND
3486 | InputTarget::FLAG_SPLIT | InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brown9302c872011-07-13 22:51:29 -07003487 mTouchState.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Jeff Browne6504122010-09-27 14:52:15 -07003488
3489 found = true;
3490 break;
3491 }
3492 }
3493
3494 if (! found) {
3495#if DEBUG_FOCUS
3496 LOGD("Focus transfer failed because from window did not have focus.");
3497#endif
3498 return false;
3499 }
3500
Jeff Brown9c9f1a32010-10-11 18:32:20 -07003501 ssize_t fromConnectionIndex = getConnectionIndexLocked(fromChannel);
3502 ssize_t toConnectionIndex = getConnectionIndexLocked(toChannel);
3503 if (fromConnectionIndex >= 0 && toConnectionIndex >= 0) {
3504 sp<Connection> fromConnection = mConnectionsByReceiveFd.valueAt(fromConnectionIndex);
3505 sp<Connection> toConnection = mConnectionsByReceiveFd.valueAt(toConnectionIndex);
3506
3507 fromConnection->inputState.copyPointerStateTo(toConnection->inputState);
Jeff Brownda3d5a92011-03-29 15:11:34 -07003508 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Jeff Brown9c9f1a32010-10-11 18:32:20 -07003509 "transferring touch focus from this window to another window");
Jeff Brownda3d5a92011-03-29 15:11:34 -07003510 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Jeff Brown9c9f1a32010-10-11 18:32:20 -07003511 }
3512
Jeff Browne6504122010-09-27 14:52:15 -07003513#if DEBUG_FOCUS
3514 logDispatchStateLocked();
3515#endif
3516 } // release lock
3517
3518 // Wake up poll loop since it may need to make new input dispatching choices.
3519 mLooper->wake();
3520 return true;
3521}
3522
Jeff Brown120a4592010-10-27 18:43:51 -07003523void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
3524#if DEBUG_FOCUS
3525 LOGD("Resetting and dropping all events (%s).", reason);
3526#endif
3527
Jeff Brownda3d5a92011-03-29 15:11:34 -07003528 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
3529 synthesizeCancelationEventsForAllConnectionsLocked(options);
Jeff Brown120a4592010-10-27 18:43:51 -07003530
3531 resetKeyRepeatLocked();
3532 releasePendingEventLocked();
3533 drainInboundQueueLocked();
3534 resetTargetsLocked();
3535
3536 mTouchState.reset();
Jeff Brown9302c872011-07-13 22:51:29 -07003537 mLastHoverWindowHandle.clear();
Jeff Brown120a4592010-10-27 18:43:51 -07003538}
3539
Jeff Brownb88102f2010-09-08 11:49:43 -07003540void InputDispatcher::logDispatchStateLocked() {
3541 String8 dump;
3542 dumpDispatchStateLocked(dump);
Jeff Brown2a95c2a2010-09-16 12:31:46 -07003543
3544 char* text = dump.lockBuffer(dump.size());
3545 char* start = text;
3546 while (*start != '\0') {
3547 char* end = strchr(start, '\n');
3548 if (*end == '\n') {
3549 *(end++) = '\0';
3550 }
3551 LOGD("%s", start);
3552 start = end;
3553 }
Jeff Brownb88102f2010-09-08 11:49:43 -07003554}
3555
3556void InputDispatcher::dumpDispatchStateLocked(String8& dump) {
Jeff Brownf2f48712010-10-01 17:46:21 -07003557 dump.appendFormat(INDENT "DispatchEnabled: %d\n", mDispatchEnabled);
3558 dump.appendFormat(INDENT "DispatchFrozen: %d\n", mDispatchFrozen);
Jeff Brownb88102f2010-09-08 11:49:43 -07003559
Jeff Brown9302c872011-07-13 22:51:29 -07003560 if (mFocusedApplicationHandle != NULL) {
Jeff Brownf2f48712010-10-01 17:46:21 -07003561 dump.appendFormat(INDENT "FocusedApplication: name='%s', dispatchingTimeout=%0.3fms\n",
Jeff Browncc4f7db2011-08-30 20:34:48 -07003562 mFocusedApplicationHandle->getName().string(),
3563 mFocusedApplicationHandle->getDispatchingTimeout(
3564 DEFAULT_INPUT_DISPATCHING_TIMEOUT) / 1000000.0);
Jeff Brownb88102f2010-09-08 11:49:43 -07003565 } else {
Jeff Brownf2f48712010-10-01 17:46:21 -07003566 dump.append(INDENT "FocusedApplication: <null>\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003567 }
Jeff Brownf2f48712010-10-01 17:46:21 -07003568 dump.appendFormat(INDENT "FocusedWindow: name='%s'\n",
Jeff Browncc4f7db2011-08-30 20:34:48 -07003569 mFocusedWindowHandle != NULL ? mFocusedWindowHandle->getName().string() : "<null>");
Jeff Brownf2f48712010-10-01 17:46:21 -07003570
3571 dump.appendFormat(INDENT "TouchDown: %s\n", toString(mTouchState.down));
3572 dump.appendFormat(INDENT "TouchSplit: %s\n", toString(mTouchState.split));
Jeff Brown95712852011-01-04 19:41:59 -08003573 dump.appendFormat(INDENT "TouchDeviceId: %d\n", mTouchState.deviceId);
Jeff Brown58a2da82011-01-25 16:02:22 -08003574 dump.appendFormat(INDENT "TouchSource: 0x%08x\n", mTouchState.source);
Jeff Brownf2f48712010-10-01 17:46:21 -07003575 if (!mTouchState.windows.isEmpty()) {
3576 dump.append(INDENT "TouchedWindows:\n");
3577 for (size_t i = 0; i < mTouchState.windows.size(); i++) {
3578 const TouchedWindow& touchedWindow = mTouchState.windows[i];
3579 dump.appendFormat(INDENT2 "%d: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
Jeff Browncc4f7db2011-08-30 20:34:48 -07003580 i, touchedWindow.windowHandle->getName().string(),
3581 touchedWindow.pointerIds.value,
Jeff Brownf2f48712010-10-01 17:46:21 -07003582 touchedWindow.targetFlags);
3583 }
3584 } else {
3585 dump.append(INDENT "TouchedWindows: <none>\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003586 }
3587
Jeff Brown9302c872011-07-13 22:51:29 -07003588 if (!mWindowHandles.isEmpty()) {
Jeff Brownf2f48712010-10-01 17:46:21 -07003589 dump.append(INDENT "Windows:\n");
Jeff Brown9302c872011-07-13 22:51:29 -07003590 for (size_t i = 0; i < mWindowHandles.size(); i++) {
3591 const sp<InputWindowHandle>& windowHandle = mWindowHandles.itemAt(i);
Jeff Browncc4f7db2011-08-30 20:34:48 -07003592 const InputWindowInfo* windowInfo = windowHandle->getInfo();
3593
Jeff Brownf2f48712010-10-01 17:46:21 -07003594 dump.appendFormat(INDENT2 "%d: name='%s', paused=%s, hasFocus=%s, hasWallpaper=%s, "
3595 "visible=%s, canReceiveKeys=%s, flags=0x%08x, type=0x%08x, layer=%d, "
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003596 "frame=[%d,%d][%d,%d], scale=%f, "
Jeff Brownfbf09772011-01-16 14:06:57 -08003597 "touchableRegion=",
Jeff Browncc4f7db2011-08-30 20:34:48 -07003598 i, windowInfo->name.string(),
3599 toString(windowInfo->paused),
3600 toString(windowInfo->hasFocus),
3601 toString(windowInfo->hasWallpaper),
3602 toString(windowInfo->visible),
3603 toString(windowInfo->canReceiveKeys),
3604 windowInfo->layoutParamsFlags, windowInfo->layoutParamsType,
3605 windowInfo->layer,
3606 windowInfo->frameLeft, windowInfo->frameTop,
3607 windowInfo->frameRight, windowInfo->frameBottom,
3608 windowInfo->scaleFactor);
3609 dumpRegion(dump, windowInfo->touchableRegion);
3610 dump.appendFormat(", inputFeatures=0x%08x", windowInfo->inputFeatures);
Jeff Brownfbf09772011-01-16 14:06:57 -08003611 dump.appendFormat(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%0.3fms\n",
Jeff Browncc4f7db2011-08-30 20:34:48 -07003612 windowInfo->ownerPid, windowInfo->ownerUid,
3613 windowInfo->dispatchingTimeout / 1000000.0);
Jeff Brownf2f48712010-10-01 17:46:21 -07003614 }
3615 } else {
3616 dump.append(INDENT "Windows: <none>\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003617 }
3618
Jeff Brownf2f48712010-10-01 17:46:21 -07003619 if (!mMonitoringChannels.isEmpty()) {
3620 dump.append(INDENT "MonitoringChannels:\n");
3621 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
3622 const sp<InputChannel>& channel = mMonitoringChannels[i];
3623 dump.appendFormat(INDENT2 "%d: '%s'\n", i, channel->getName().string());
3624 }
3625 } else {
3626 dump.append(INDENT "MonitoringChannels: <none>\n");
3627 }
Jeff Brown519e0242010-09-15 15:18:56 -07003628
Jeff Brownf2f48712010-10-01 17:46:21 -07003629 dump.appendFormat(INDENT "InboundQueue: length=%u\n", mInboundQueue.count());
3630
3631 if (!mActiveConnections.isEmpty()) {
3632 dump.append(INDENT "ActiveConnections:\n");
3633 for (size_t i = 0; i < mActiveConnections.size(); i++) {
3634 const Connection* connection = mActiveConnections[i];
Jeff Brown76860e32010-10-25 17:37:46 -07003635 dump.appendFormat(INDENT2 "%d: '%s', status=%s, outboundQueueLength=%u, "
Jeff Brownb6997262010-10-08 22:31:17 -07003636 "inputState.isNeutral=%s\n",
Jeff Brownf2f48712010-10-01 17:46:21 -07003637 i, connection->getInputChannelName(), connection->getStatusLabel(),
3638 connection->outboundQueue.count(),
Jeff Brownb6997262010-10-08 22:31:17 -07003639 toString(connection->inputState.isNeutral()));
Jeff Brownf2f48712010-10-01 17:46:21 -07003640 }
3641 } else {
3642 dump.append(INDENT "ActiveConnections: <none>\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003643 }
3644
3645 if (isAppSwitchPendingLocked()) {
Jeff Brownf2f48712010-10-01 17:46:21 -07003646 dump.appendFormat(INDENT "AppSwitch: pending, due in %01.1fms\n",
Jeff Brownb88102f2010-09-08 11:49:43 -07003647 (mAppSwitchDueTime - now()) / 1000000.0);
3648 } else {
Jeff Brownf2f48712010-10-01 17:46:21 -07003649 dump.append(INDENT "AppSwitch: not pending\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003650 }
3651}
3652
Jeff Brown928e0542011-01-10 11:17:36 -08003653status_t InputDispatcher::registerInputChannel(const sp<InputChannel>& inputChannel,
3654 const sp<InputWindowHandle>& inputWindowHandle, bool monitor) {
Jeff Brown9c3cda02010-06-15 01:31:58 -07003655#if DEBUG_REGISTRATION
Jeff Brownb88102f2010-09-08 11:49:43 -07003656 LOGD("channel '%s' ~ registerInputChannel - monitor=%s", inputChannel->getName().string(),
3657 toString(monitor));
Jeff Brown9c3cda02010-06-15 01:31:58 -07003658#endif
3659
Jeff Brown46b9ac02010-04-22 18:58:52 -07003660 { // acquire lock
3661 AutoMutex _l(mLock);
3662
Jeff Brown519e0242010-09-15 15:18:56 -07003663 if (getConnectionIndexLocked(inputChannel) >= 0) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07003664 LOGW("Attempted to register already registered input channel '%s'",
3665 inputChannel->getName().string());
3666 return BAD_VALUE;
3667 }
3668
Jeff Browncc4f7db2011-08-30 20:34:48 -07003669 sp<Connection> connection = new Connection(inputChannel, inputWindowHandle, monitor);
Jeff Brown46b9ac02010-04-22 18:58:52 -07003670 status_t status = connection->initialize();
3671 if (status) {
3672 LOGE("Failed to initialize input publisher for input channel '%s', status=%d",
3673 inputChannel->getName().string(), status);
3674 return status;
3675 }
3676
Jeff Brown2cbecea2010-08-17 15:59:26 -07003677 int32_t receiveFd = inputChannel->getReceivePipeFd();
Jeff Brown46b9ac02010-04-22 18:58:52 -07003678 mConnectionsByReceiveFd.add(receiveFd, connection);
Jeff Brown9c3cda02010-06-15 01:31:58 -07003679
Jeff Brownb88102f2010-09-08 11:49:43 -07003680 if (monitor) {
3681 mMonitoringChannels.push(inputChannel);
3682 }
3683
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07003684 mLooper->addFd(receiveFd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
Jeff Brown2cbecea2010-08-17 15:59:26 -07003685
Jeff Brown9c3cda02010-06-15 01:31:58 -07003686 runCommandsLockedInterruptible();
Jeff Brown46b9ac02010-04-22 18:58:52 -07003687 } // release lock
Jeff Brown46b9ac02010-04-22 18:58:52 -07003688 return OK;
3689}
3690
3691status_t InputDispatcher::unregisterInputChannel(const sp<InputChannel>& inputChannel) {
Jeff Brown9c3cda02010-06-15 01:31:58 -07003692#if DEBUG_REGISTRATION
Jeff Brown349703e2010-06-22 01:27:15 -07003693 LOGD("channel '%s' ~ unregisterInputChannel", inputChannel->getName().string());
Jeff Brown9c3cda02010-06-15 01:31:58 -07003694#endif
3695
Jeff Brown46b9ac02010-04-22 18:58:52 -07003696 { // acquire lock
3697 AutoMutex _l(mLock);
3698
Jeff Browncc4f7db2011-08-30 20:34:48 -07003699 status_t status = unregisterInputChannelLocked(inputChannel, false /*notify*/);
3700 if (status) {
3701 return status;
Jeff Brown46b9ac02010-04-22 18:58:52 -07003702 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07003703 } // release lock
3704
Jeff Brown46b9ac02010-04-22 18:58:52 -07003705 // Wake the poll loop because removing the connection may have changed the current
3706 // synchronization state.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07003707 mLooper->wake();
Jeff Brown46b9ac02010-04-22 18:58:52 -07003708 return OK;
3709}
3710
Jeff Browncc4f7db2011-08-30 20:34:48 -07003711status_t InputDispatcher::unregisterInputChannelLocked(const sp<InputChannel>& inputChannel,
3712 bool notify) {
3713 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
3714 if (connectionIndex < 0) {
3715 LOGW("Attempted to unregister already unregistered input channel '%s'",
3716 inputChannel->getName().string());
3717 return BAD_VALUE;
3718 }
3719
3720 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
3721 mConnectionsByReceiveFd.removeItemsAt(connectionIndex);
3722
3723 if (connection->monitor) {
3724 removeMonitorChannelLocked(inputChannel);
3725 }
3726
3727 mLooper->removeFd(inputChannel->getReceivePipeFd());
3728
3729 nsecs_t currentTime = now();
3730 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
3731
3732 runCommandsLockedInterruptible();
3733
3734 connection->status = Connection::STATUS_ZOMBIE;
3735 return OK;
3736}
3737
3738void InputDispatcher::removeMonitorChannelLocked(const sp<InputChannel>& inputChannel) {
3739 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
3740 if (mMonitoringChannels[i] == inputChannel) {
3741 mMonitoringChannels.removeAt(i);
3742 break;
3743 }
3744 }
3745}
3746
Jeff Brown519e0242010-09-15 15:18:56 -07003747ssize_t InputDispatcher::getConnectionIndexLocked(const sp<InputChannel>& inputChannel) {
Jeff Brown2cbecea2010-08-17 15:59:26 -07003748 ssize_t connectionIndex = mConnectionsByReceiveFd.indexOfKey(inputChannel->getReceivePipeFd());
3749 if (connectionIndex >= 0) {
3750 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
3751 if (connection->inputChannel.get() == inputChannel.get()) {
3752 return connectionIndex;
3753 }
3754 }
3755
3756 return -1;
3757}
3758
Jeff Brown46b9ac02010-04-22 18:58:52 -07003759void InputDispatcher::activateConnectionLocked(Connection* connection) {
3760 for (size_t i = 0; i < mActiveConnections.size(); i++) {
3761 if (mActiveConnections.itemAt(i) == connection) {
3762 return;
3763 }
3764 }
3765 mActiveConnections.add(connection);
3766}
3767
3768void InputDispatcher::deactivateConnectionLocked(Connection* connection) {
3769 for (size_t i = 0; i < mActiveConnections.size(); i++) {
3770 if (mActiveConnections.itemAt(i) == connection) {
3771 mActiveConnections.removeAt(i);
3772 return;
3773 }
3774 }
3775}
3776
Jeff Brown9c3cda02010-06-15 01:31:58 -07003777void InputDispatcher::onDispatchCycleStartedLocked(
Jeff Brown7fbdc842010-06-17 20:52:56 -07003778 nsecs_t currentTime, const sp<Connection>& connection) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07003779}
3780
Jeff Brown9c3cda02010-06-15 01:31:58 -07003781void InputDispatcher::onDispatchCycleFinishedLocked(
Jeff Brown3915bb82010-11-05 15:02:16 -07003782 nsecs_t currentTime, const sp<Connection>& connection, bool handled) {
3783 CommandEntry* commandEntry = postCommandLocked(
3784 & InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
3785 commandEntry->connection = connection;
3786 commandEntry->handled = handled;
Jeff Brown46b9ac02010-04-22 18:58:52 -07003787}
3788
Jeff Brown9c3cda02010-06-15 01:31:58 -07003789void InputDispatcher::onDispatchCycleBrokenLocked(
Jeff Brown7fbdc842010-06-17 20:52:56 -07003790 nsecs_t currentTime, const sp<Connection>& connection) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07003791 LOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
3792 connection->getInputChannelName());
3793
Jeff Brown9c3cda02010-06-15 01:31:58 -07003794 CommandEntry* commandEntry = postCommandLocked(
3795 & InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
Jeff Brown7fbdc842010-06-17 20:52:56 -07003796 commandEntry->connection = connection;
Jeff Brown46b9ac02010-04-22 18:58:52 -07003797}
3798
Jeff Brown519e0242010-09-15 15:18:56 -07003799void InputDispatcher::onANRLocked(
Jeff Brown9302c872011-07-13 22:51:29 -07003800 nsecs_t currentTime, const sp<InputApplicationHandle>& applicationHandle,
3801 const sp<InputWindowHandle>& windowHandle,
Jeff Brown519e0242010-09-15 15:18:56 -07003802 nsecs_t eventTime, nsecs_t waitStartTime) {
3803 LOGI("Application is not responding: %s. "
3804 "%01.1fms since event, %01.1fms since wait started",
Jeff Brown9302c872011-07-13 22:51:29 -07003805 getApplicationWindowLabelLocked(applicationHandle, windowHandle).string(),
Jeff Brown519e0242010-09-15 15:18:56 -07003806 (currentTime - eventTime) / 1000000.0,
3807 (currentTime - waitStartTime) / 1000000.0);
3808
3809 CommandEntry* commandEntry = postCommandLocked(
3810 & InputDispatcher::doNotifyANRLockedInterruptible);
Jeff Brown9302c872011-07-13 22:51:29 -07003811 commandEntry->inputApplicationHandle = applicationHandle;
3812 commandEntry->inputWindowHandle = windowHandle;
Jeff Brown519e0242010-09-15 15:18:56 -07003813}
3814
Jeff Brownb88102f2010-09-08 11:49:43 -07003815void InputDispatcher::doNotifyConfigurationChangedInterruptible(
3816 CommandEntry* commandEntry) {
3817 mLock.unlock();
3818
3819 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
3820
3821 mLock.lock();
3822}
3823
Jeff Brown9c3cda02010-06-15 01:31:58 -07003824void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(
3825 CommandEntry* commandEntry) {
Jeff Brown7fbdc842010-06-17 20:52:56 -07003826 sp<Connection> connection = commandEntry->connection;
Jeff Brown9c3cda02010-06-15 01:31:58 -07003827
Jeff Brown7fbdc842010-06-17 20:52:56 -07003828 if (connection->status != Connection::STATUS_ZOMBIE) {
3829 mLock.unlock();
Jeff Brown9c3cda02010-06-15 01:31:58 -07003830
Jeff Brown928e0542011-01-10 11:17:36 -08003831 mPolicy->notifyInputChannelBroken(connection->inputWindowHandle);
Jeff Brown7fbdc842010-06-17 20:52:56 -07003832
3833 mLock.lock();
3834 }
Jeff Brown9c3cda02010-06-15 01:31:58 -07003835}
3836
Jeff Brown519e0242010-09-15 15:18:56 -07003837void InputDispatcher::doNotifyANRLockedInterruptible(
Jeff Brown9c3cda02010-06-15 01:31:58 -07003838 CommandEntry* commandEntry) {
Jeff Brown519e0242010-09-15 15:18:56 -07003839 mLock.unlock();
Jeff Brown9c3cda02010-06-15 01:31:58 -07003840
Jeff Brown519e0242010-09-15 15:18:56 -07003841 nsecs_t newTimeout = mPolicy->notifyANR(
Jeff Brown928e0542011-01-10 11:17:36 -08003842 commandEntry->inputApplicationHandle, commandEntry->inputWindowHandle);
Jeff Brown9c3cda02010-06-15 01:31:58 -07003843
Jeff Brown519e0242010-09-15 15:18:56 -07003844 mLock.lock();
Jeff Brown7fbdc842010-06-17 20:52:56 -07003845
Jeff Brown9302c872011-07-13 22:51:29 -07003846 resumeAfterTargetsNotReadyTimeoutLocked(newTimeout,
3847 commandEntry->inputWindowHandle != NULL
Jeff Browncc4f7db2011-08-30 20:34:48 -07003848 ? commandEntry->inputWindowHandle->getInputChannel() : NULL);
Jeff Brown9c3cda02010-06-15 01:31:58 -07003849}
3850
Jeff Brownb88102f2010-09-08 11:49:43 -07003851void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
3852 CommandEntry* commandEntry) {
3853 KeyEntry* entry = commandEntry->keyEntry;
Jeff Brown1f245102010-11-18 20:53:46 -08003854
3855 KeyEvent event;
3856 initializeKeyEvent(&event, entry);
Jeff Brownb88102f2010-09-08 11:49:43 -07003857
3858 mLock.unlock();
3859
Jeff Brown905805a2011-10-12 13:57:59 -07003860 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(commandEntry->inputWindowHandle,
Jeff Brown1f245102010-11-18 20:53:46 -08003861 &event, entry->policyFlags);
Jeff Brownb88102f2010-09-08 11:49:43 -07003862
3863 mLock.lock();
3864
Jeff Brown905805a2011-10-12 13:57:59 -07003865 if (delay < 0) {
3866 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
3867 } else if (!delay) {
3868 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
3869 } else {
3870 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
3871 entry->interceptKeyWakeupTime = now() + delay;
3872 }
Jeff Brownac386072011-07-20 15:19:50 -07003873 entry->release();
Jeff Brownb88102f2010-09-08 11:49:43 -07003874}
3875
Jeff Brown3915bb82010-11-05 15:02:16 -07003876void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(
3877 CommandEntry* commandEntry) {
3878 sp<Connection> connection = commandEntry->connection;
3879 bool handled = commandEntry->handled;
3880
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003881 bool skipNext = false;
Jeff Brown49ed71d2010-12-06 17:13:33 -08003882 if (!connection->outboundQueue.isEmpty()) {
Jeff Brownac386072011-07-20 15:19:50 -07003883 DispatchEntry* dispatchEntry = connection->outboundQueue.head;
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003884 if (dispatchEntry->inProgress) {
3885 if (dispatchEntry->eventEntry->type == EventEntry::TYPE_KEY) {
3886 KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry);
3887 skipNext = afterKeyEventLockedInterruptible(connection,
3888 dispatchEntry, keyEntry, handled);
3889 } else if (dispatchEntry->eventEntry->type == EventEntry::TYPE_MOTION) {
3890 MotionEntry* motionEntry = static_cast<MotionEntry*>(dispatchEntry->eventEntry);
3891 skipNext = afterMotionEventLockedInterruptible(connection,
3892 dispatchEntry, motionEntry, handled);
Jeff Brown49ed71d2010-12-06 17:13:33 -08003893 }
Jeff Brown3915bb82010-11-05 15:02:16 -07003894 }
3895 }
3896
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003897 if (!skipNext) {
3898 startNextDispatchCycleLocked(now(), connection);
3899 }
3900}
3901
3902bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
3903 DispatchEntry* dispatchEntry, KeyEntry* keyEntry, bool handled) {
3904 if (!(keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK)) {
3905 // Get the fallback key state.
3906 // Clear it out after dispatching the UP.
3907 int32_t originalKeyCode = keyEntry->keyCode;
3908 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
3909 if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
3910 connection->inputState.removeFallbackKey(originalKeyCode);
3911 }
3912
3913 if (handled || !dispatchEntry->hasForegroundTarget()) {
3914 // If the application handles the original key for which we previously
3915 // generated a fallback or if the window is not a foreground window,
3916 // then cancel the associated fallback key, if any.
3917 if (fallbackKeyCode != -1) {
3918 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
3919 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
3920 "application handled the original non-fallback key "
3921 "or is no longer a foreground target, "
3922 "canceling previously dispatched fallback key");
3923 options.keyCode = fallbackKeyCode;
3924 synthesizeCancelationEventsForConnectionLocked(connection, options);
3925 }
3926 connection->inputState.removeFallbackKey(originalKeyCode);
3927 }
3928 } else {
3929 // If the application did not handle a non-fallback key, first check
3930 // that we are in a good state to perform unhandled key event processing
3931 // Then ask the policy what to do with it.
3932 bool initialDown = keyEntry->action == AKEY_EVENT_ACTION_DOWN
3933 && keyEntry->repeatCount == 0;
3934 if (fallbackKeyCode == -1 && !initialDown) {
3935#if DEBUG_OUTBOUND_EVENT_DETAILS
3936 LOGD("Unhandled key event: Skipping unhandled key event processing "
3937 "since this is not an initial down. "
3938 "keyCode=%d, action=%d, repeatCount=%d",
3939 originalKeyCode, keyEntry->action, keyEntry->repeatCount);
3940#endif
3941 return false;
3942 }
3943
3944 // Dispatch the unhandled key to the policy.
3945#if DEBUG_OUTBOUND_EVENT_DETAILS
3946 LOGD("Unhandled key event: Asking policy to perform fallback action. "
3947 "keyCode=%d, action=%d, repeatCount=%d",
3948 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount);
3949#endif
3950 KeyEvent event;
3951 initializeKeyEvent(&event, keyEntry);
3952
3953 mLock.unlock();
3954
3955 bool fallback = mPolicy->dispatchUnhandledKey(connection->inputWindowHandle,
3956 &event, keyEntry->policyFlags, &event);
3957
3958 mLock.lock();
3959
3960 if (connection->status != Connection::STATUS_NORMAL) {
3961 connection->inputState.removeFallbackKey(originalKeyCode);
3962 return true; // skip next cycle
3963 }
3964
Jeff Brownac386072011-07-20 15:19:50 -07003965 LOG_ASSERT(connection->outboundQueue.head == dispatchEntry);
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003966
3967 // Latch the fallback keycode for this key on an initial down.
3968 // The fallback keycode cannot change at any other point in the lifecycle.
3969 if (initialDown) {
3970 if (fallback) {
3971 fallbackKeyCode = event.getKeyCode();
3972 } else {
3973 fallbackKeyCode = AKEYCODE_UNKNOWN;
3974 }
3975 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
3976 }
3977
3978 LOG_ASSERT(fallbackKeyCode != -1);
3979
3980 // Cancel the fallback key if the policy decides not to send it anymore.
3981 // We will continue to dispatch the key to the policy but we will no
3982 // longer dispatch a fallback key to the application.
3983 if (fallbackKeyCode != AKEYCODE_UNKNOWN
3984 && (!fallback || fallbackKeyCode != event.getKeyCode())) {
3985#if DEBUG_OUTBOUND_EVENT_DETAILS
3986 if (fallback) {
3987 LOGD("Unhandled key event: Policy requested to send key %d"
3988 "as a fallback for %d, but on the DOWN it had requested "
3989 "to send %d instead. Fallback canceled.",
3990 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
3991 } else {
3992 LOGD("Unhandled key event: Policy did not request fallback for %d,"
3993 "but on the DOWN it had requested to send %d. "
3994 "Fallback canceled.",
3995 originalKeyCode, fallbackKeyCode);
3996 }
3997#endif
3998
3999 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
4000 "canceling fallback, policy no longer desires it");
4001 options.keyCode = fallbackKeyCode;
4002 synthesizeCancelationEventsForConnectionLocked(connection, options);
4003
4004 fallback = false;
4005 fallbackKeyCode = AKEYCODE_UNKNOWN;
4006 if (keyEntry->action != AKEY_EVENT_ACTION_UP) {
4007 connection->inputState.setFallbackKey(originalKeyCode,
4008 fallbackKeyCode);
4009 }
4010 }
4011
4012#if DEBUG_OUTBOUND_EVENT_DETAILS
4013 {
4014 String8 msg;
4015 const KeyedVector<int32_t, int32_t>& fallbackKeys =
4016 connection->inputState.getFallbackKeys();
4017 for (size_t i = 0; i < fallbackKeys.size(); i++) {
4018 msg.appendFormat(", %d->%d", fallbackKeys.keyAt(i),
4019 fallbackKeys.valueAt(i));
4020 }
4021 LOGD("Unhandled key event: %d currently tracked fallback keys%s.",
4022 fallbackKeys.size(), msg.string());
4023 }
4024#endif
4025
4026 if (fallback) {
4027 // Restart the dispatch cycle using the fallback key.
4028 keyEntry->eventTime = event.getEventTime();
4029 keyEntry->deviceId = event.getDeviceId();
4030 keyEntry->source = event.getSource();
4031 keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
4032 keyEntry->keyCode = fallbackKeyCode;
4033 keyEntry->scanCode = event.getScanCode();
4034 keyEntry->metaState = event.getMetaState();
4035 keyEntry->repeatCount = event.getRepeatCount();
4036 keyEntry->downTime = event.getDownTime();
4037 keyEntry->syntheticRepeat = false;
4038
4039#if DEBUG_OUTBOUND_EVENT_DETAILS
4040 LOGD("Unhandled key event: Dispatching fallback key. "
4041 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
4042 originalKeyCode, fallbackKeyCode, keyEntry->metaState);
4043#endif
4044
4045 dispatchEntry->inProgress = false;
4046 startDispatchCycleLocked(now(), connection);
4047 return true; // already started next cycle
4048 } else {
4049#if DEBUG_OUTBOUND_EVENT_DETAILS
4050 LOGD("Unhandled key event: No fallback key.");
4051#endif
4052 }
4053 }
4054 }
4055 return false;
4056}
4057
4058bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
4059 DispatchEntry* dispatchEntry, MotionEntry* motionEntry, bool handled) {
4060 return false;
Jeff Brown3915bb82010-11-05 15:02:16 -07004061}
4062
Jeff Brownb88102f2010-09-08 11:49:43 -07004063void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
4064 mLock.unlock();
4065
Jeff Brown01ce2e92010-09-26 22:20:12 -07004066 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
Jeff Brownb88102f2010-09-08 11:49:43 -07004067
4068 mLock.lock();
4069}
4070
Jeff Brown3915bb82010-11-05 15:02:16 -07004071void InputDispatcher::initializeKeyEvent(KeyEvent* event, const KeyEntry* entry) {
4072 event->initialize(entry->deviceId, entry->source, entry->action, entry->flags,
4073 entry->keyCode, entry->scanCode, entry->metaState, entry->repeatCount,
4074 entry->downTime, entry->eventTime);
4075}
4076
Jeff Brown519e0242010-09-15 15:18:56 -07004077void InputDispatcher::updateDispatchStatisticsLocked(nsecs_t currentTime, const EventEntry* entry,
4078 int32_t injectionResult, nsecs_t timeSpentWaitingForApplication) {
4079 // TODO Write some statistics about how long we spend waiting.
Jeff Brownb88102f2010-09-08 11:49:43 -07004080}
4081
4082void InputDispatcher::dump(String8& dump) {
Jeff Brown89ef0722011-08-10 16:25:21 -07004083 AutoMutex _l(mLock);
4084
Jeff Brownf2f48712010-10-01 17:46:21 -07004085 dump.append("Input Dispatcher State:\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07004086 dumpDispatchStateLocked(dump);
Jeff Brown214eaf42011-05-26 19:17:02 -07004087
4088 dump.append(INDENT "Configuration:\n");
4089 dump.appendFormat(INDENT2 "MaxEventsPerSecond: %d\n", mConfig.maxEventsPerSecond);
4090 dump.appendFormat(INDENT2 "KeyRepeatDelay: %0.1fms\n", mConfig.keyRepeatDelay * 0.000001f);
4091 dump.appendFormat(INDENT2 "KeyRepeatTimeout: %0.1fms\n", mConfig.keyRepeatTimeout * 0.000001f);
Jeff Brownb88102f2010-09-08 11:49:43 -07004092}
4093
Jeff Brown89ef0722011-08-10 16:25:21 -07004094void InputDispatcher::monitor() {
4095 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
4096 mLock.lock();
4097 mLock.unlock();
4098}
4099
Jeff Brown9c3cda02010-06-15 01:31:58 -07004100
Jeff Brown519e0242010-09-15 15:18:56 -07004101// --- InputDispatcher::Queue ---
4102
4103template <typename T>
4104uint32_t InputDispatcher::Queue<T>::count() const {
4105 uint32_t result = 0;
Jeff Brownac386072011-07-20 15:19:50 -07004106 for (const T* entry = head; entry; entry = entry->next) {
Jeff Brown519e0242010-09-15 15:18:56 -07004107 result += 1;
4108 }
4109 return result;
4110}
4111
4112
Jeff Brownac386072011-07-20 15:19:50 -07004113// --- InputDispatcher::InjectionState ---
Jeff Brown46b9ac02010-04-22 18:58:52 -07004114
Jeff Brownac386072011-07-20 15:19:50 -07004115InputDispatcher::InjectionState::InjectionState(int32_t injectorPid, int32_t injectorUid) :
4116 refCount(1),
4117 injectorPid(injectorPid), injectorUid(injectorUid),
4118 injectionResult(INPUT_EVENT_INJECTION_PENDING), injectionIsAsync(false),
4119 pendingForegroundDispatches(0) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07004120}
4121
Jeff Brownac386072011-07-20 15:19:50 -07004122InputDispatcher::InjectionState::~InjectionState() {
Jeff Brown01ce2e92010-09-26 22:20:12 -07004123}
4124
Jeff Brownac386072011-07-20 15:19:50 -07004125void InputDispatcher::InjectionState::release() {
4126 refCount -= 1;
4127 if (refCount == 0) {
4128 delete this;
4129 } else {
4130 LOG_ASSERT(refCount > 0);
Jeff Brown01ce2e92010-09-26 22:20:12 -07004131 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07004132}
4133
Jeff Brownac386072011-07-20 15:19:50 -07004134
4135// --- InputDispatcher::EventEntry ---
4136
4137InputDispatcher::EventEntry::EventEntry(int32_t type, nsecs_t eventTime, uint32_t policyFlags) :
4138 refCount(1), type(type), eventTime(eventTime), policyFlags(policyFlags),
4139 injectionState(NULL), dispatchInProgress(false) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07004140}
4141
Jeff Brownac386072011-07-20 15:19:50 -07004142InputDispatcher::EventEntry::~EventEntry() {
4143 releaseInjectionState();
4144}
4145
4146void InputDispatcher::EventEntry::release() {
4147 refCount -= 1;
4148 if (refCount == 0) {
4149 delete this;
4150 } else {
4151 LOG_ASSERT(refCount > 0);
4152 }
4153}
4154
4155void InputDispatcher::EventEntry::releaseInjectionState() {
4156 if (injectionState) {
4157 injectionState->release();
4158 injectionState = NULL;
4159 }
4160}
4161
4162
4163// --- InputDispatcher::ConfigurationChangedEntry ---
4164
4165InputDispatcher::ConfigurationChangedEntry::ConfigurationChangedEntry(nsecs_t eventTime) :
4166 EventEntry(TYPE_CONFIGURATION_CHANGED, eventTime, 0) {
4167}
4168
4169InputDispatcher::ConfigurationChangedEntry::~ConfigurationChangedEntry() {
4170}
4171
4172
Jeff Brown65fd2512011-08-18 11:20:58 -07004173// --- InputDispatcher::DeviceResetEntry ---
4174
4175InputDispatcher::DeviceResetEntry::DeviceResetEntry(nsecs_t eventTime, int32_t deviceId) :
4176 EventEntry(TYPE_DEVICE_RESET, eventTime, 0),
4177 deviceId(deviceId) {
4178}
4179
4180InputDispatcher::DeviceResetEntry::~DeviceResetEntry() {
4181}
4182
4183
Jeff Brownac386072011-07-20 15:19:50 -07004184// --- InputDispatcher::KeyEntry ---
4185
4186InputDispatcher::KeyEntry::KeyEntry(nsecs_t eventTime,
Jeff Brown58a2da82011-01-25 16:02:22 -08004187 int32_t deviceId, uint32_t source, uint32_t policyFlags, int32_t action,
Jeff Brown7fbdc842010-06-17 20:52:56 -07004188 int32_t flags, int32_t keyCode, int32_t scanCode, int32_t metaState,
Jeff Brownac386072011-07-20 15:19:50 -07004189 int32_t repeatCount, nsecs_t downTime) :
4190 EventEntry(TYPE_KEY, eventTime, policyFlags),
4191 deviceId(deviceId), source(source), action(action), flags(flags),
4192 keyCode(keyCode), scanCode(scanCode), metaState(metaState),
4193 repeatCount(repeatCount), downTime(downTime),
Jeff Brown905805a2011-10-12 13:57:59 -07004194 syntheticRepeat(false), interceptKeyResult(KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN),
4195 interceptKeyWakeupTime(0) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07004196}
4197
Jeff Brownac386072011-07-20 15:19:50 -07004198InputDispatcher::KeyEntry::~KeyEntry() {
4199}
Jeff Brown7fbdc842010-06-17 20:52:56 -07004200
Jeff Brownac386072011-07-20 15:19:50 -07004201void InputDispatcher::KeyEntry::recycle() {
4202 releaseInjectionState();
4203
4204 dispatchInProgress = false;
4205 syntheticRepeat = false;
4206 interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
Jeff Brown905805a2011-10-12 13:57:59 -07004207 interceptKeyWakeupTime = 0;
Jeff Brownac386072011-07-20 15:19:50 -07004208}
4209
4210
4211// --- InputDispatcher::MotionSample ---
4212
4213InputDispatcher::MotionSample::MotionSample(nsecs_t eventTime,
4214 const PointerCoords* pointerCoords, uint32_t pointerCount) :
4215 next(NULL), eventTime(eventTime), eventTimeBeforeCoalescing(eventTime) {
Jeff Brown7fbdc842010-06-17 20:52:56 -07004216 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brownac386072011-07-20 15:19:50 -07004217 this->pointerCoords[i].copyFrom(pointerCoords[i]);
Jeff Brown7fbdc842010-06-17 20:52:56 -07004218 }
Jeff Brownb88102f2010-09-08 11:49:43 -07004219}
4220
4221
Jeff Brownae9fc032010-08-18 15:51:08 -07004222// --- InputDispatcher::MotionEntry ---
4223
Jeff Brownac386072011-07-20 15:19:50 -07004224InputDispatcher::MotionEntry::MotionEntry(nsecs_t eventTime,
4225 int32_t deviceId, uint32_t source, uint32_t policyFlags, int32_t action, int32_t flags,
4226 int32_t metaState, int32_t buttonState,
4227 int32_t edgeFlags, float xPrecision, float yPrecision,
4228 nsecs_t downTime, uint32_t pointerCount,
4229 const PointerProperties* pointerProperties, const PointerCoords* pointerCoords) :
4230 EventEntry(TYPE_MOTION, eventTime, policyFlags),
4231 deviceId(deviceId), source(source), action(action), flags(flags),
4232 metaState(metaState), buttonState(buttonState), edgeFlags(edgeFlags),
4233 xPrecision(xPrecision), yPrecision(yPrecision),
4234 downTime(downTime), pointerCount(pointerCount),
4235 firstSample(eventTime, pointerCoords, pointerCount),
4236 lastSample(&firstSample) {
4237 for (uint32_t i = 0; i < pointerCount; i++) {
4238 this->pointerProperties[i].copyFrom(pointerProperties[i]);
4239 }
4240}
4241
4242InputDispatcher::MotionEntry::~MotionEntry() {
4243 for (MotionSample* sample = firstSample.next; sample != NULL; ) {
4244 MotionSample* next = sample->next;
4245 delete sample;
4246 sample = next;
4247 }
4248}
4249
Jeff Brownae9fc032010-08-18 15:51:08 -07004250uint32_t InputDispatcher::MotionEntry::countSamples() const {
4251 uint32_t count = 1;
4252 for (MotionSample* sample = firstSample.next; sample != NULL; sample = sample->next) {
4253 count += 1;
4254 }
4255 return count;
4256}
4257
Jeff Brown4e91a182011-04-07 11:38:09 -07004258bool InputDispatcher::MotionEntry::canAppendSamples(int32_t action, uint32_t pointerCount,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07004259 const PointerProperties* pointerProperties) const {
Jeff Brown4e91a182011-04-07 11:38:09 -07004260 if (this->action != action
4261 || this->pointerCount != pointerCount
4262 || this->isInjected()) {
4263 return false;
4264 }
4265 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07004266 if (this->pointerProperties[i] != pointerProperties[i]) {
Jeff Brown4e91a182011-04-07 11:38:09 -07004267 return false;
4268 }
4269 }
4270 return true;
4271}
4272
Jeff Brownac386072011-07-20 15:19:50 -07004273void InputDispatcher::MotionEntry::appendSample(
4274 nsecs_t eventTime, const PointerCoords* pointerCoords) {
4275 MotionSample* sample = new MotionSample(eventTime, pointerCoords, pointerCount);
4276
4277 lastSample->next = sample;
4278 lastSample = sample;
4279}
4280
4281
4282// --- InputDispatcher::DispatchEntry ---
4283
4284InputDispatcher::DispatchEntry::DispatchEntry(EventEntry* eventEntry,
4285 int32_t targetFlags, float xOffset, float yOffset, float scaleFactor) :
4286 eventEntry(eventEntry), targetFlags(targetFlags),
4287 xOffset(xOffset), yOffset(yOffset), scaleFactor(scaleFactor),
4288 inProgress(false),
4289 resolvedAction(0), resolvedFlags(0),
4290 headMotionSample(NULL), tailMotionSample(NULL) {
4291 eventEntry->refCount += 1;
4292}
4293
4294InputDispatcher::DispatchEntry::~DispatchEntry() {
4295 eventEntry->release();
4296}
4297
Jeff Brownb88102f2010-09-08 11:49:43 -07004298
4299// --- InputDispatcher::InputState ---
4300
Jeff Brownb6997262010-10-08 22:31:17 -07004301InputDispatcher::InputState::InputState() {
Jeff Brownb88102f2010-09-08 11:49:43 -07004302}
4303
4304InputDispatcher::InputState::~InputState() {
4305}
4306
4307bool InputDispatcher::InputState::isNeutral() const {
4308 return mKeyMementos.isEmpty() && mMotionMementos.isEmpty();
4309}
4310
Jeff Brown81346812011-06-28 20:08:48 -07004311bool InputDispatcher::InputState::isHovering(int32_t deviceId, uint32_t source) const {
4312 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4313 const MotionMemento& memento = mMotionMementos.itemAt(i);
4314 if (memento.deviceId == deviceId
4315 && memento.source == source
4316 && memento.hovering) {
4317 return true;
4318 }
4319 }
4320 return false;
4321}
Jeff Brownb88102f2010-09-08 11:49:43 -07004322
Jeff Brown81346812011-06-28 20:08:48 -07004323bool InputDispatcher::InputState::trackKey(const KeyEntry* entry,
4324 int32_t action, int32_t flags) {
4325 switch (action) {
4326 case AKEY_EVENT_ACTION_UP: {
4327 if (entry->flags & AKEY_EVENT_FLAG_FALLBACK) {
4328 for (size_t i = 0; i < mFallbackKeys.size(); ) {
4329 if (mFallbackKeys.valueAt(i) == entry->keyCode) {
4330 mFallbackKeys.removeItemsAt(i);
4331 } else {
4332 i += 1;
4333 }
4334 }
4335 }
4336 ssize_t index = findKeyMemento(entry);
4337 if (index >= 0) {
4338 mKeyMementos.removeAt(index);
4339 return true;
4340 }
Jeff Brown68b909d2011-12-07 16:36:01 -08004341 /* FIXME: We can't just drop the key up event because that prevents creating
4342 * popup windows that are automatically shown when a key is held and then
4343 * dismissed when the key is released. The problem is that the popup will
4344 * not have received the original key down, so the key up will be considered
4345 * to be inconsistent with its observed state. We could perhaps handle this
4346 * by synthesizing a key down but that will cause other problems.
4347 *
4348 * So for now, allow inconsistent key up events to be dispatched.
4349 *
Jeff Brown81346812011-06-28 20:08:48 -07004350#if DEBUG_OUTBOUND_EVENT_DETAILS
4351 LOGD("Dropping inconsistent key up event: deviceId=%d, source=%08x, "
4352 "keyCode=%d, scanCode=%d",
4353 entry->deviceId, entry->source, entry->keyCode, entry->scanCode);
4354#endif
4355 return false;
Jeff Brown68b909d2011-12-07 16:36:01 -08004356 */
4357 return true;
Jeff Brown81346812011-06-28 20:08:48 -07004358 }
4359
4360 case AKEY_EVENT_ACTION_DOWN: {
4361 ssize_t index = findKeyMemento(entry);
4362 if (index >= 0) {
4363 mKeyMementos.removeAt(index);
4364 }
4365 addKeyMemento(entry, flags);
4366 return true;
4367 }
4368
4369 default:
4370 return true;
Jeff Brownb88102f2010-09-08 11:49:43 -07004371 }
4372}
4373
Jeff Brown81346812011-06-28 20:08:48 -07004374bool InputDispatcher::InputState::trackMotion(const MotionEntry* entry,
4375 int32_t action, int32_t flags) {
4376 int32_t actionMasked = action & AMOTION_EVENT_ACTION_MASK;
4377 switch (actionMasked) {
4378 case AMOTION_EVENT_ACTION_UP:
4379 case AMOTION_EVENT_ACTION_CANCEL: {
4380 ssize_t index = findMotionMemento(entry, false /*hovering*/);
4381 if (index >= 0) {
4382 mMotionMementos.removeAt(index);
4383 return true;
Jeff Brownda3d5a92011-03-29 15:11:34 -07004384 }
Jeff Brown81346812011-06-28 20:08:48 -07004385#if DEBUG_OUTBOUND_EVENT_DETAILS
4386 LOGD("Dropping inconsistent motion up or cancel event: deviceId=%d, source=%08x, "
4387 "actionMasked=%d",
4388 entry->deviceId, entry->source, actionMasked);
4389#endif
4390 return false;
Jeff Brownda3d5a92011-03-29 15:11:34 -07004391 }
4392
Jeff Brown81346812011-06-28 20:08:48 -07004393 case AMOTION_EVENT_ACTION_DOWN: {
4394 ssize_t index = findMotionMemento(entry, false /*hovering*/);
4395 if (index >= 0) {
4396 mMotionMementos.removeAt(index);
4397 }
4398 addMotionMemento(entry, flags, false /*hovering*/);
4399 return true;
4400 }
4401
4402 case AMOTION_EVENT_ACTION_POINTER_UP:
4403 case AMOTION_EVENT_ACTION_POINTER_DOWN:
4404 case AMOTION_EVENT_ACTION_MOVE: {
4405 ssize_t index = findMotionMemento(entry, false /*hovering*/);
4406 if (index >= 0) {
4407 MotionMemento& memento = mMotionMementos.editItemAt(index);
4408 memento.setPointers(entry);
4409 return true;
4410 }
Jeff Brown2e45fb62011-06-29 21:19:05 -07004411 if (actionMasked == AMOTION_EVENT_ACTION_MOVE
4412 && (entry->source & (AINPUT_SOURCE_CLASS_JOYSTICK
4413 | AINPUT_SOURCE_CLASS_NAVIGATION))) {
4414 // Joysticks and trackballs can send MOVE events without corresponding DOWN or UP.
4415 return true;
4416 }
Jeff Brown81346812011-06-28 20:08:48 -07004417#if DEBUG_OUTBOUND_EVENT_DETAILS
4418 LOGD("Dropping inconsistent motion pointer up/down or move event: "
4419 "deviceId=%d, source=%08x, actionMasked=%d",
4420 entry->deviceId, entry->source, actionMasked);
4421#endif
4422 return false;
4423 }
4424
4425 case AMOTION_EVENT_ACTION_HOVER_EXIT: {
4426 ssize_t index = findMotionMemento(entry, true /*hovering*/);
4427 if (index >= 0) {
4428 mMotionMementos.removeAt(index);
4429 return true;
4430 }
4431#if DEBUG_OUTBOUND_EVENT_DETAILS
4432 LOGD("Dropping inconsistent motion hover exit event: deviceId=%d, source=%08x",
4433 entry->deviceId, entry->source);
4434#endif
4435 return false;
4436 }
4437
4438 case AMOTION_EVENT_ACTION_HOVER_ENTER:
4439 case AMOTION_EVENT_ACTION_HOVER_MOVE: {
4440 ssize_t index = findMotionMemento(entry, true /*hovering*/);
4441 if (index >= 0) {
4442 mMotionMementos.removeAt(index);
4443 }
4444 addMotionMemento(entry, flags, true /*hovering*/);
4445 return true;
4446 }
4447
4448 default:
4449 return true;
4450 }
4451}
4452
4453ssize_t InputDispatcher::InputState::findKeyMemento(const KeyEntry* entry) const {
Jeff Brownb88102f2010-09-08 11:49:43 -07004454 for (size_t i = 0; i < mKeyMementos.size(); i++) {
Jeff Brown81346812011-06-28 20:08:48 -07004455 const KeyMemento& memento = mKeyMementos.itemAt(i);
Jeff Brownb88102f2010-09-08 11:49:43 -07004456 if (memento.deviceId == entry->deviceId
4457 && memento.source == entry->source
4458 && memento.keyCode == entry->keyCode
4459 && memento.scanCode == entry->scanCode) {
Jeff Brown81346812011-06-28 20:08:48 -07004460 return i;
Jeff Brownb88102f2010-09-08 11:49:43 -07004461 }
4462 }
Jeff Brown81346812011-06-28 20:08:48 -07004463 return -1;
Jeff Brownb88102f2010-09-08 11:49:43 -07004464}
4465
Jeff Brown81346812011-06-28 20:08:48 -07004466ssize_t InputDispatcher::InputState::findMotionMemento(const MotionEntry* entry,
4467 bool hovering) const {
Jeff Brownb88102f2010-09-08 11:49:43 -07004468 for (size_t i = 0; i < mMotionMementos.size(); i++) {
Jeff Brown81346812011-06-28 20:08:48 -07004469 const MotionMemento& memento = mMotionMementos.itemAt(i);
Jeff Brownb88102f2010-09-08 11:49:43 -07004470 if (memento.deviceId == entry->deviceId
Jeff Brown81346812011-06-28 20:08:48 -07004471 && memento.source == entry->source
4472 && memento.hovering == hovering) {
4473 return i;
Jeff Brownb88102f2010-09-08 11:49:43 -07004474 }
4475 }
Jeff Brown81346812011-06-28 20:08:48 -07004476 return -1;
4477}
Jeff Brownb88102f2010-09-08 11:49:43 -07004478
Jeff Brown81346812011-06-28 20:08:48 -07004479void InputDispatcher::InputState::addKeyMemento(const KeyEntry* entry, int32_t flags) {
4480 mKeyMementos.push();
4481 KeyMemento& memento = mKeyMementos.editTop();
4482 memento.deviceId = entry->deviceId;
4483 memento.source = entry->source;
4484 memento.keyCode = entry->keyCode;
4485 memento.scanCode = entry->scanCode;
4486 memento.flags = flags;
4487 memento.downTime = entry->downTime;
4488}
4489
4490void InputDispatcher::InputState::addMotionMemento(const MotionEntry* entry,
4491 int32_t flags, bool hovering) {
4492 mMotionMementos.push();
4493 MotionMemento& memento = mMotionMementos.editTop();
4494 memento.deviceId = entry->deviceId;
4495 memento.source = entry->source;
4496 memento.flags = flags;
4497 memento.xPrecision = entry->xPrecision;
4498 memento.yPrecision = entry->yPrecision;
4499 memento.downTime = entry->downTime;
4500 memento.setPointers(entry);
4501 memento.hovering = hovering;
Jeff Brownb88102f2010-09-08 11:49:43 -07004502}
4503
4504void InputDispatcher::InputState::MotionMemento::setPointers(const MotionEntry* entry) {
4505 pointerCount = entry->pointerCount;
4506 for (uint32_t i = 0; i < entry->pointerCount; i++) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07004507 pointerProperties[i].copyFrom(entry->pointerProperties[i]);
Jeff Brownace13b12011-03-09 17:39:48 -08004508 pointerCoords[i].copyFrom(entry->lastSample->pointerCoords[i]);
Jeff Brownb88102f2010-09-08 11:49:43 -07004509 }
4510}
4511
Jeff Brownb6997262010-10-08 22:31:17 -07004512void InputDispatcher::InputState::synthesizeCancelationEvents(nsecs_t currentTime,
Jeff Brownac386072011-07-20 15:19:50 -07004513 Vector<EventEntry*>& outEvents, const CancelationOptions& options) {
Jeff Brown81346812011-06-28 20:08:48 -07004514 for (size_t i = 0; i < mKeyMementos.size(); i++) {
Jeff Brownb88102f2010-09-08 11:49:43 -07004515 const KeyMemento& memento = mKeyMementos.itemAt(i);
Jeff Brown49ed71d2010-12-06 17:13:33 -08004516 if (shouldCancelKey(memento, options)) {
Jeff Brownac386072011-07-20 15:19:50 -07004517 outEvents.push(new KeyEntry(currentTime,
Jeff Brownb6997262010-10-08 22:31:17 -07004518 memento.deviceId, memento.source, 0,
Jeff Brown49ed71d2010-12-06 17:13:33 -08004519 AKEY_EVENT_ACTION_UP, memento.flags | AKEY_EVENT_FLAG_CANCELED,
Jeff Brownb6997262010-10-08 22:31:17 -07004520 memento.keyCode, memento.scanCode, 0, 0, memento.downTime));
Jeff Brownb6997262010-10-08 22:31:17 -07004521 }
Jeff Brownb88102f2010-09-08 11:49:43 -07004522 }
4523
Jeff Brown81346812011-06-28 20:08:48 -07004524 for (size_t i = 0; i < mMotionMementos.size(); i++) {
Jeff Brownb88102f2010-09-08 11:49:43 -07004525 const MotionMemento& memento = mMotionMementos.itemAt(i);
Jeff Brown49ed71d2010-12-06 17:13:33 -08004526 if (shouldCancelMotion(memento, options)) {
Jeff Brownac386072011-07-20 15:19:50 -07004527 outEvents.push(new MotionEntry(currentTime,
Jeff Brownb6997262010-10-08 22:31:17 -07004528 memento.deviceId, memento.source, 0,
Jeff Browna032cc02011-03-07 16:56:21 -08004529 memento.hovering
4530 ? AMOTION_EVENT_ACTION_HOVER_EXIT
4531 : AMOTION_EVENT_ACTION_CANCEL,
Jeff Brown81346812011-06-28 20:08:48 -07004532 memento.flags, 0, 0, 0,
Jeff Brownb6997262010-10-08 22:31:17 -07004533 memento.xPrecision, memento.yPrecision, memento.downTime,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07004534 memento.pointerCount, memento.pointerProperties, memento.pointerCoords));
Jeff Brownb6997262010-10-08 22:31:17 -07004535 }
Jeff Brownb88102f2010-09-08 11:49:43 -07004536 }
4537}
4538
4539void InputDispatcher::InputState::clear() {
4540 mKeyMementos.clear();
4541 mMotionMementos.clear();
Jeff Brownda3d5a92011-03-29 15:11:34 -07004542 mFallbackKeys.clear();
Jeff Brownb6997262010-10-08 22:31:17 -07004543}
4544
Jeff Brown9c9f1a32010-10-11 18:32:20 -07004545void InputDispatcher::InputState::copyPointerStateTo(InputState& other) const {
4546 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4547 const MotionMemento& memento = mMotionMementos.itemAt(i);
4548 if (memento.source & AINPUT_SOURCE_CLASS_POINTER) {
4549 for (size_t j = 0; j < other.mMotionMementos.size(); ) {
4550 const MotionMemento& otherMemento = other.mMotionMementos.itemAt(j);
4551 if (memento.deviceId == otherMemento.deviceId
4552 && memento.source == otherMemento.source) {
4553 other.mMotionMementos.removeAt(j);
4554 } else {
4555 j += 1;
4556 }
4557 }
4558 other.mMotionMementos.push(memento);
4559 }
4560 }
4561}
4562
Jeff Brownda3d5a92011-03-29 15:11:34 -07004563int32_t InputDispatcher::InputState::getFallbackKey(int32_t originalKeyCode) {
4564 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
4565 return index >= 0 ? mFallbackKeys.valueAt(index) : -1;
4566}
4567
4568void InputDispatcher::InputState::setFallbackKey(int32_t originalKeyCode,
4569 int32_t fallbackKeyCode) {
4570 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
4571 if (index >= 0) {
4572 mFallbackKeys.replaceValueAt(index, fallbackKeyCode);
4573 } else {
4574 mFallbackKeys.add(originalKeyCode, fallbackKeyCode);
4575 }
4576}
4577
4578void InputDispatcher::InputState::removeFallbackKey(int32_t originalKeyCode) {
4579 mFallbackKeys.removeItem(originalKeyCode);
4580}
4581
Jeff Brown49ed71d2010-12-06 17:13:33 -08004582bool InputDispatcher::InputState::shouldCancelKey(const KeyMemento& memento,
Jeff Brownda3d5a92011-03-29 15:11:34 -07004583 const CancelationOptions& options) {
4584 if (options.keyCode != -1 && memento.keyCode != options.keyCode) {
4585 return false;
4586 }
4587
Jeff Brown65fd2512011-08-18 11:20:58 -07004588 if (options.deviceId != -1 && memento.deviceId != options.deviceId) {
4589 return false;
4590 }
4591
Jeff Brownda3d5a92011-03-29 15:11:34 -07004592 switch (options.mode) {
4593 case CancelationOptions::CANCEL_ALL_EVENTS:
4594 case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
Jeff Brownb6997262010-10-08 22:31:17 -07004595 return true;
Jeff Brownda3d5a92011-03-29 15:11:34 -07004596 case CancelationOptions::CANCEL_FALLBACK_EVENTS:
Jeff Brown49ed71d2010-12-06 17:13:33 -08004597 return memento.flags & AKEY_EVENT_FLAG_FALLBACK;
4598 default:
4599 return false;
4600 }
4601}
4602
4603bool InputDispatcher::InputState::shouldCancelMotion(const MotionMemento& memento,
Jeff Brownda3d5a92011-03-29 15:11:34 -07004604 const CancelationOptions& options) {
Jeff Brown65fd2512011-08-18 11:20:58 -07004605 if (options.deviceId != -1 && memento.deviceId != options.deviceId) {
4606 return false;
4607 }
4608
Jeff Brownda3d5a92011-03-29 15:11:34 -07004609 switch (options.mode) {
4610 case CancelationOptions::CANCEL_ALL_EVENTS:
Jeff Brown49ed71d2010-12-06 17:13:33 -08004611 return true;
Jeff Brownda3d5a92011-03-29 15:11:34 -07004612 case CancelationOptions::CANCEL_POINTER_EVENTS:
Jeff Brown49ed71d2010-12-06 17:13:33 -08004613 return memento.source & AINPUT_SOURCE_CLASS_POINTER;
Jeff Brownda3d5a92011-03-29 15:11:34 -07004614 case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
Jeff Brown49ed71d2010-12-06 17:13:33 -08004615 return !(memento.source & AINPUT_SOURCE_CLASS_POINTER);
4616 default:
4617 return false;
Jeff Brownb6997262010-10-08 22:31:17 -07004618 }
Jeff Brownb88102f2010-09-08 11:49:43 -07004619}
4620
4621
Jeff Brown46b9ac02010-04-22 18:58:52 -07004622// --- InputDispatcher::Connection ---
4623
Jeff Brown928e0542011-01-10 11:17:36 -08004624InputDispatcher::Connection::Connection(const sp<InputChannel>& inputChannel,
Jeff Browncc4f7db2011-08-30 20:34:48 -07004625 const sp<InputWindowHandle>& inputWindowHandle, bool monitor) :
Jeff Brown928e0542011-01-10 11:17:36 -08004626 status(STATUS_NORMAL), inputChannel(inputChannel), inputWindowHandle(inputWindowHandle),
Jeff Browncc4f7db2011-08-30 20:34:48 -07004627 monitor(monitor),
Jeff Brown928e0542011-01-10 11:17:36 -08004628 inputPublisher(inputChannel),
Jeff Brownda3d5a92011-03-29 15:11:34 -07004629 lastEventTime(LONG_LONG_MAX), lastDispatchTime(LONG_LONG_MAX) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07004630}
4631
4632InputDispatcher::Connection::~Connection() {
4633}
4634
4635status_t InputDispatcher::Connection::initialize() {
4636 return inputPublisher.initialize();
4637}
4638
Jeff Brown9c3cda02010-06-15 01:31:58 -07004639const char* InputDispatcher::Connection::getStatusLabel() const {
4640 switch (status) {
4641 case STATUS_NORMAL:
4642 return "NORMAL";
4643
4644 case STATUS_BROKEN:
4645 return "BROKEN";
4646
Jeff Brown9c3cda02010-06-15 01:31:58 -07004647 case STATUS_ZOMBIE:
4648 return "ZOMBIE";
4649
4650 default:
4651 return "UNKNOWN";
4652 }
4653}
4654
Jeff Brown46b9ac02010-04-22 18:58:52 -07004655InputDispatcher::DispatchEntry* InputDispatcher::Connection::findQueuedDispatchEntryForEvent(
4656 const EventEntry* eventEntry) const {
Jeff Brownac386072011-07-20 15:19:50 -07004657 for (DispatchEntry* dispatchEntry = outboundQueue.tail; dispatchEntry;
4658 dispatchEntry = dispatchEntry->prev) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07004659 if (dispatchEntry->eventEntry == eventEntry) {
4660 return dispatchEntry;
4661 }
4662 }
4663 return NULL;
4664}
4665
Jeff Brownb88102f2010-09-08 11:49:43 -07004666
Jeff Brown9c3cda02010-06-15 01:31:58 -07004667// --- InputDispatcher::CommandEntry ---
4668
Jeff Brownac386072011-07-20 15:19:50 -07004669InputDispatcher::CommandEntry::CommandEntry(Command command) :
4670 command(command), eventTime(0), keyEntry(NULL), userActivityEventType(0), handled(false) {
Jeff Brown9c3cda02010-06-15 01:31:58 -07004671}
4672
4673InputDispatcher::CommandEntry::~CommandEntry() {
4674}
4675
Jeff Brown46b9ac02010-04-22 18:58:52 -07004676
Jeff Brown01ce2e92010-09-26 22:20:12 -07004677// --- InputDispatcher::TouchState ---
4678
4679InputDispatcher::TouchState::TouchState() :
Jeff Brown58a2da82011-01-25 16:02:22 -08004680 down(false), split(false), deviceId(-1), source(0) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07004681}
4682
4683InputDispatcher::TouchState::~TouchState() {
4684}
4685
4686void InputDispatcher::TouchState::reset() {
4687 down = false;
4688 split = false;
Jeff Brown95712852011-01-04 19:41:59 -08004689 deviceId = -1;
Jeff Brown58a2da82011-01-25 16:02:22 -08004690 source = 0;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004691 windows.clear();
4692}
4693
4694void InputDispatcher::TouchState::copyFrom(const TouchState& other) {
4695 down = other.down;
4696 split = other.split;
Jeff Brown95712852011-01-04 19:41:59 -08004697 deviceId = other.deviceId;
Jeff Brown58a2da82011-01-25 16:02:22 -08004698 source = other.source;
Jeff Brown9302c872011-07-13 22:51:29 -07004699 windows = other.windows;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004700}
4701
Jeff Brown9302c872011-07-13 22:51:29 -07004702void InputDispatcher::TouchState::addOrUpdateWindow(const sp<InputWindowHandle>& windowHandle,
Jeff Brown01ce2e92010-09-26 22:20:12 -07004703 int32_t targetFlags, BitSet32 pointerIds) {
4704 if (targetFlags & InputTarget::FLAG_SPLIT) {
4705 split = true;
4706 }
4707
4708 for (size_t i = 0; i < windows.size(); i++) {
4709 TouchedWindow& touchedWindow = windows.editItemAt(i);
Jeff Brown9302c872011-07-13 22:51:29 -07004710 if (touchedWindow.windowHandle == windowHandle) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07004711 touchedWindow.targetFlags |= targetFlags;
Jeff Brown98db5fa2011-06-08 15:37:10 -07004712 if (targetFlags & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
4713 touchedWindow.targetFlags &= ~InputTarget::FLAG_DISPATCH_AS_IS;
4714 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07004715 touchedWindow.pointerIds.value |= pointerIds.value;
4716 return;
4717 }
4718 }
4719
4720 windows.push();
4721
4722 TouchedWindow& touchedWindow = windows.editTop();
Jeff Brown9302c872011-07-13 22:51:29 -07004723 touchedWindow.windowHandle = windowHandle;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004724 touchedWindow.targetFlags = targetFlags;
4725 touchedWindow.pointerIds = pointerIds;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004726}
4727
Jeff Browna032cc02011-03-07 16:56:21 -08004728void InputDispatcher::TouchState::filterNonAsIsTouchWindows() {
Jeff Brown01ce2e92010-09-26 22:20:12 -07004729 for (size_t i = 0 ; i < windows.size(); ) {
Jeff Browna032cc02011-03-07 16:56:21 -08004730 TouchedWindow& window = windows.editItemAt(i);
Jeff Brown98db5fa2011-06-08 15:37:10 -07004731 if (window.targetFlags & (InputTarget::FLAG_DISPATCH_AS_IS
4732 | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER)) {
Jeff Browna032cc02011-03-07 16:56:21 -08004733 window.targetFlags &= ~InputTarget::FLAG_DISPATCH_MASK;
4734 window.targetFlags |= InputTarget::FLAG_DISPATCH_AS_IS;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004735 i += 1;
Jeff Browna032cc02011-03-07 16:56:21 -08004736 } else {
4737 windows.removeAt(i);
Jeff Brown01ce2e92010-09-26 22:20:12 -07004738 }
4739 }
4740}
4741
Jeff Brown9302c872011-07-13 22:51:29 -07004742sp<InputWindowHandle> InputDispatcher::TouchState::getFirstForegroundWindowHandle() const {
Jeff Brown01ce2e92010-09-26 22:20:12 -07004743 for (size_t i = 0; i < windows.size(); i++) {
Jeff Brown98db5fa2011-06-08 15:37:10 -07004744 const TouchedWindow& window = windows.itemAt(i);
4745 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
Jeff Brown9302c872011-07-13 22:51:29 -07004746 return window.windowHandle;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004747 }
4748 }
4749 return NULL;
4750}
4751
Jeff Brown98db5fa2011-06-08 15:37:10 -07004752bool InputDispatcher::TouchState::isSlippery() const {
4753 // Must have exactly one foreground window.
4754 bool haveSlipperyForegroundWindow = false;
4755 for (size_t i = 0; i < windows.size(); i++) {
4756 const TouchedWindow& window = windows.itemAt(i);
4757 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
Jeff Browncc4f7db2011-08-30 20:34:48 -07004758 if (haveSlipperyForegroundWindow
4759 || !(window.windowHandle->getInfo()->layoutParamsFlags
4760 & InputWindowInfo::FLAG_SLIPPERY)) {
Jeff Brown98db5fa2011-06-08 15:37:10 -07004761 return false;
4762 }
4763 haveSlipperyForegroundWindow = true;
4764 }
4765 }
4766 return haveSlipperyForegroundWindow;
4767}
4768
Jeff Brown01ce2e92010-09-26 22:20:12 -07004769
Jeff Brown46b9ac02010-04-22 18:58:52 -07004770// --- InputDispatcherThread ---
4771
4772InputDispatcherThread::InputDispatcherThread(const sp<InputDispatcherInterface>& dispatcher) :
4773 Thread(/*canCallJava*/ true), mDispatcher(dispatcher) {
4774}
4775
4776InputDispatcherThread::~InputDispatcherThread() {
4777}
4778
4779bool InputDispatcherThread::threadLoop() {
4780 mDispatcher->dispatchOnce();
4781 return true;
4782}
4783
4784} // namespace android