blob: 5f31f0506f6c350aa03f08cd416569339b98ed37 [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
Jeff Brownfbf09772011-01-16 14:06:57 -0800180static void dumpRegion(String8& dump, const SkRegion& region) {
181 if (region.isEmpty()) {
182 dump.append("<empty>");
183 return;
184 }
185
186 bool first = true;
187 for (SkRegion::Iterator it(region); !it.done(); it.next()) {
188 if (first) {
189 first = false;
190 } else {
191 dump.append("|");
192 }
193 const SkIRect& rect = it.rect();
194 dump.appendFormat("[%d,%d][%d,%d]", rect.fLeft, rect.fTop, rect.fRight, rect.fBottom);
195 }
196}
197
Jeff Brownb88102f2010-09-08 11:49:43 -0700198
Jeff Brown46b9ac02010-04-22 18:58:52 -0700199// --- InputDispatcher ---
200
Jeff Brown9c3cda02010-06-15 01:31:58 -0700201InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy) :
Jeff Brownb88102f2010-09-08 11:49:43 -0700202 mPolicy(policy),
Jeff Brown928e0542011-01-10 11:17:36 -0800203 mPendingEvent(NULL), mAppSwitchSawKeyDown(false), mAppSwitchDueTime(LONG_LONG_MAX),
204 mNextUnblockedEvent(NULL),
Jeff Brown0029c662011-03-30 02:25:18 -0700205 mDispatchEnabled(true), mDispatchFrozen(false), mInputFilterEnabled(false),
Jeff Brownb88102f2010-09-08 11:49:43 -0700206 mCurrentInputTargetsValid(false),
Jeff Brown9302c872011-07-13 22:51:29 -0700207 mInputTargetWaitCause(INPUT_TARGET_WAIT_CAUSE_NONE) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -0700208 mLooper = new Looper(false);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700209
Jeff Brown46b9ac02010-04-22 18:58:52 -0700210 mKeyRepeatState.lastKeyEntry = NULL;
Jeff Brown9c3cda02010-06-15 01:31:58 -0700211
Jeff Brown214eaf42011-05-26 19:17:02 -0700212 policy->getDispatcherConfiguration(&mConfig);
213
214 mThrottleState.minTimeBetweenEvents = 1000000000LL / mConfig.maxEventsPerSecond;
Jeff Brownae9fc032010-08-18 15:51:08 -0700215 mThrottleState.lastDeviceId = -1;
216
217#if DEBUG_THROTTLING
218 mThrottleState.originalSampleCount = 0;
Jeff Brown214eaf42011-05-26 19:17:02 -0700219 LOGD("Throttling - Max events per second = %d", mConfig.maxEventsPerSecond);
Jeff Brownae9fc032010-08-18 15:51:08 -0700220#endif
Jeff Brown46b9ac02010-04-22 18:58:52 -0700221}
222
223InputDispatcher::~InputDispatcher() {
Jeff Brownb88102f2010-09-08 11:49:43 -0700224 { // acquire lock
225 AutoMutex _l(mLock);
226
227 resetKeyRepeatLocked();
Jeff Brown54a18252010-09-16 14:07:33 -0700228 releasePendingEventLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -0700229 drainInboundQueueLocked();
230 }
Jeff Brown46b9ac02010-04-22 18:58:52 -0700231
232 while (mConnectionsByReceiveFd.size() != 0) {
233 unregisterInputChannel(mConnectionsByReceiveFd.valueAt(0)->inputChannel);
234 }
Jeff Brown46b9ac02010-04-22 18:58:52 -0700235}
236
237void InputDispatcher::dispatchOnce() {
Jeff Brown46b9ac02010-04-22 18:58:52 -0700238 nsecs_t nextWakeupTime = LONG_LONG_MAX;
239 { // acquire lock
240 AutoMutex _l(mLock);
Jeff Brown214eaf42011-05-26 19:17:02 -0700241 dispatchOnceInnerLocked(&nextWakeupTime);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700242
Jeff Brownb88102f2010-09-08 11:49:43 -0700243 if (runCommandsLockedInterruptible()) {
244 nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
Jeff Brown46b9ac02010-04-22 18:58:52 -0700245 }
Jeff Brown46b9ac02010-04-22 18:58:52 -0700246 } // release lock
247
Jeff Brownb88102f2010-09-08 11:49:43 -0700248 // Wait for callback or timeout or wake. (make sure we round up, not down)
249 nsecs_t currentTime = now();
Jeff Brownaa3855d2011-03-17 01:34:19 -0700250 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
Jeff Brown4fe6c3e2010-09-13 23:17:30 -0700251 mLooper->pollOnce(timeoutMillis);
Jeff Brownb88102f2010-09-08 11:49:43 -0700252}
253
Jeff Brown214eaf42011-05-26 19:17:02 -0700254void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700255 nsecs_t currentTime = now();
256
257 // Reset the key repeat timer whenever we disallow key events, even if the next event
258 // is not a key. This is to ensure that we abort a key repeat if the device is just coming
259 // out of sleep.
Jeff Brown214eaf42011-05-26 19:17:02 -0700260 if (!mPolicy->isKeyRepeatEnabled()) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700261 resetKeyRepeatLocked();
262 }
263
Jeff Brownb88102f2010-09-08 11:49:43 -0700264 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
265 if (mDispatchFrozen) {
266#if DEBUG_FOCUS
267 LOGD("Dispatch frozen. Waiting some more.");
268#endif
269 return;
270 }
271
272 // Optimize latency of app switches.
273 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
274 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
275 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
276 if (mAppSwitchDueTime < *nextWakeupTime) {
277 *nextWakeupTime = mAppSwitchDueTime;
278 }
279
Jeff Brownb88102f2010-09-08 11:49:43 -0700280 // Ready to start a new event.
281 // If we don't already have a pending event, go grab one.
282 if (! mPendingEvent) {
283 if (mInboundQueue.isEmpty()) {
284 if (isAppSwitchDue) {
285 // The inbound queue is empty so the app switch key we were waiting
286 // for will never arrive. Stop waiting for it.
287 resetPendingAppSwitchLocked(false);
288 isAppSwitchDue = false;
289 }
290
291 // Synthesize a key repeat if appropriate.
292 if (mKeyRepeatState.lastKeyEntry) {
293 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
Jeff Brown214eaf42011-05-26 19:17:02 -0700294 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700295 } else {
296 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
297 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
298 }
299 }
300 }
Jeff Browncc4f7db2011-08-30 20:34:48 -0700301
302 // Nothing to do if there is no pending event.
Jeff Brownb88102f2010-09-08 11:49:43 -0700303 if (! mPendingEvent) {
Jeff Browncc4f7db2011-08-30 20:34:48 -0700304 if (mActiveConnections.isEmpty()) {
305 dispatchIdleLocked();
306 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700307 return;
308 }
309 } else {
310 // Inbound queue has at least one entry.
Jeff Brownac386072011-07-20 15:19:50 -0700311 EventEntry* entry = mInboundQueue.head;
Jeff Brownb88102f2010-09-08 11:49:43 -0700312
313 // Throttle the entry if it is a move event and there are no
314 // other events behind it in the queue. Due to movement batching, additional
315 // samples may be appended to this event by the time the throttling timeout
316 // expires.
317 // TODO Make this smarter and consider throttling per device independently.
Jeff Brownb6997262010-10-08 22:31:17 -0700318 if (entry->type == EventEntry::TYPE_MOTION
319 && !isAppSwitchDue
320 && mDispatchEnabled
321 && (entry->policyFlags & POLICY_FLAG_PASS_TO_USER)
322 && !entry->isInjected()) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700323 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
324 int32_t deviceId = motionEntry->deviceId;
325 uint32_t source = motionEntry->source;
326 if (! isAppSwitchDue
Jeff Brownac386072011-07-20 15:19:50 -0700327 && !motionEntry->next // exactly one event, no successors
Jeff Browncc0c1592011-02-19 05:07:28 -0800328 && (motionEntry->action == AMOTION_EVENT_ACTION_MOVE
329 || motionEntry->action == AMOTION_EVENT_ACTION_HOVER_MOVE)
Jeff Brownb88102f2010-09-08 11:49:43 -0700330 && deviceId == mThrottleState.lastDeviceId
331 && source == mThrottleState.lastSource) {
332 nsecs_t nextTime = mThrottleState.lastEventTime
333 + mThrottleState.minTimeBetweenEvents;
334 if (currentTime < nextTime) {
335 // Throttle it!
336#if DEBUG_THROTTLING
337 LOGD("Throttling - Delaying motion event for "
Jeff Brown90655042010-12-02 13:50:46 -0800338 "device %d, source 0x%08x by up to %0.3fms.",
Jeff Brownb88102f2010-09-08 11:49:43 -0700339 deviceId, source, (nextTime - currentTime) * 0.000001);
340#endif
341 if (nextTime < *nextWakeupTime) {
342 *nextWakeupTime = nextTime;
343 }
344 if (mThrottleState.originalSampleCount == 0) {
345 mThrottleState.originalSampleCount =
346 motionEntry->countSamples();
347 }
348 return;
349 }
350 }
351
352#if DEBUG_THROTTLING
353 if (mThrottleState.originalSampleCount != 0) {
354 uint32_t count = motionEntry->countSamples();
355 LOGD("Throttling - Motion event sample count grew by %d from %d to %d.",
356 count - mThrottleState.originalSampleCount,
357 mThrottleState.originalSampleCount, count);
358 mThrottleState.originalSampleCount = 0;
359 }
360#endif
361
makarand.karvekarf634ded2011-03-02 15:41:03 -0600362 mThrottleState.lastEventTime = currentTime;
Jeff Brownb88102f2010-09-08 11:49:43 -0700363 mThrottleState.lastDeviceId = deviceId;
364 mThrottleState.lastSource = source;
365 }
366
367 mInboundQueue.dequeue(entry);
368 mPendingEvent = entry;
369 }
Jeff Browne2fe69e2010-10-18 13:21:23 -0700370
371 // Poke user activity for this event.
372 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
373 pokeUserActivityLocked(mPendingEvent);
374 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700375 }
376
377 // Now we have an event to dispatch.
Jeff Brown928e0542011-01-10 11:17:36 -0800378 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Jeff Brownb6110c22011-04-01 16:15:13 -0700379 LOG_ASSERT(mPendingEvent != NULL);
Jeff Brown54a18252010-09-16 14:07:33 -0700380 bool done = false;
Jeff Brownb6997262010-10-08 22:31:17 -0700381 DropReason dropReason = DROP_REASON_NOT_DROPPED;
382 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
383 dropReason = DROP_REASON_POLICY;
384 } else if (!mDispatchEnabled) {
385 dropReason = DROP_REASON_DISABLED;
386 }
Jeff Brown928e0542011-01-10 11:17:36 -0800387
388 if (mNextUnblockedEvent == mPendingEvent) {
389 mNextUnblockedEvent = NULL;
390 }
391
Jeff Brownb88102f2010-09-08 11:49:43 -0700392 switch (mPendingEvent->type) {
393 case EventEntry::TYPE_CONFIGURATION_CHANGED: {
394 ConfigurationChangedEntry* typedEntry =
395 static_cast<ConfigurationChangedEntry*>(mPendingEvent);
Jeff Brown54a18252010-09-16 14:07:33 -0700396 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Jeff Brownb6997262010-10-08 22:31:17 -0700397 dropReason = DROP_REASON_NOT_DROPPED; // configuration changes are never dropped
Jeff Brownb88102f2010-09-08 11:49:43 -0700398 break;
399 }
400
Jeff Brown65fd2512011-08-18 11:20:58 -0700401 case EventEntry::TYPE_DEVICE_RESET: {
402 DeviceResetEntry* typedEntry =
403 static_cast<DeviceResetEntry*>(mPendingEvent);
404 done = dispatchDeviceResetLocked(currentTime, typedEntry);
405 dropReason = DROP_REASON_NOT_DROPPED; // device resets are never dropped
406 break;
407 }
408
Jeff Brownb88102f2010-09-08 11:49:43 -0700409 case EventEntry::TYPE_KEY: {
410 KeyEntry* typedEntry = static_cast<KeyEntry*>(mPendingEvent);
Jeff Brownb6997262010-10-08 22:31:17 -0700411 if (isAppSwitchDue) {
412 if (isAppSwitchKeyEventLocked(typedEntry)) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700413 resetPendingAppSwitchLocked(true);
Jeff Brownb6997262010-10-08 22:31:17 -0700414 isAppSwitchDue = false;
415 } else if (dropReason == DROP_REASON_NOT_DROPPED) {
416 dropReason = DROP_REASON_APP_SWITCH;
Jeff Brownb88102f2010-09-08 11:49:43 -0700417 }
418 }
Jeff Brown928e0542011-01-10 11:17:36 -0800419 if (dropReason == DROP_REASON_NOT_DROPPED
420 && isStaleEventLocked(currentTime, typedEntry)) {
421 dropReason = DROP_REASON_STALE;
422 }
423 if (dropReason == DROP_REASON_NOT_DROPPED && mNextUnblockedEvent) {
424 dropReason = DROP_REASON_BLOCKED;
425 }
Jeff Brown214eaf42011-05-26 19:17:02 -0700426 done = dispatchKeyLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700427 break;
428 }
429
430 case EventEntry::TYPE_MOTION: {
431 MotionEntry* typedEntry = static_cast<MotionEntry*>(mPendingEvent);
Jeff Brownb6997262010-10-08 22:31:17 -0700432 if (dropReason == DROP_REASON_NOT_DROPPED && isAppSwitchDue) {
433 dropReason = DROP_REASON_APP_SWITCH;
Jeff Brownb88102f2010-09-08 11:49:43 -0700434 }
Jeff Brown928e0542011-01-10 11:17:36 -0800435 if (dropReason == DROP_REASON_NOT_DROPPED
436 && isStaleEventLocked(currentTime, typedEntry)) {
437 dropReason = DROP_REASON_STALE;
438 }
439 if (dropReason == DROP_REASON_NOT_DROPPED && mNextUnblockedEvent) {
440 dropReason = DROP_REASON_BLOCKED;
441 }
Jeff Brownb6997262010-10-08 22:31:17 -0700442 done = dispatchMotionLocked(currentTime, typedEntry,
Jeff Browne20c9e02010-10-11 14:20:19 -0700443 &dropReason, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700444 break;
445 }
446
447 default:
Jeff Brownb6110c22011-04-01 16:15:13 -0700448 LOG_ASSERT(false);
Jeff Brownb88102f2010-09-08 11:49:43 -0700449 break;
450 }
451
Jeff Brown54a18252010-09-16 14:07:33 -0700452 if (done) {
Jeff Brownb6997262010-10-08 22:31:17 -0700453 if (dropReason != DROP_REASON_NOT_DROPPED) {
454 dropInboundEventLocked(mPendingEvent, dropReason);
455 }
456
Jeff Brown54a18252010-09-16 14:07:33 -0700457 releasePendingEventLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -0700458 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
459 }
460}
461
Jeff Browncc4f7db2011-08-30 20:34:48 -0700462void InputDispatcher::dispatchIdleLocked() {
463#if DEBUG_FOCUS
464 LOGD("Dispatcher idle. There are no pending events or active connections.");
465#endif
466
467 // Reset targets when idle, to release input channels and other resources
468 // they are holding onto.
469 resetTargetsLocked();
470}
471
Jeff Brownb88102f2010-09-08 11:49:43 -0700472bool InputDispatcher::enqueueInboundEventLocked(EventEntry* entry) {
473 bool needWake = mInboundQueue.isEmpty();
474 mInboundQueue.enqueueAtTail(entry);
475
476 switch (entry->type) {
Jeff Brownb6997262010-10-08 22:31:17 -0700477 case EventEntry::TYPE_KEY: {
Jeff Brown928e0542011-01-10 11:17:36 -0800478 // Optimize app switch latency.
479 // If the application takes too long to catch up then we drop all events preceding
480 // the app switch key.
Jeff Brownb6997262010-10-08 22:31:17 -0700481 KeyEntry* keyEntry = static_cast<KeyEntry*>(entry);
482 if (isAppSwitchKeyEventLocked(keyEntry)) {
483 if (keyEntry->action == AKEY_EVENT_ACTION_DOWN) {
484 mAppSwitchSawKeyDown = true;
485 } else if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
486 if (mAppSwitchSawKeyDown) {
487#if DEBUG_APP_SWITCH
488 LOGD("App switch is pending!");
489#endif
490 mAppSwitchDueTime = keyEntry->eventTime + APP_SWITCH_TIMEOUT;
491 mAppSwitchSawKeyDown = false;
492 needWake = true;
493 }
494 }
495 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700496 break;
497 }
Jeff Brown928e0542011-01-10 11:17:36 -0800498
499 case EventEntry::TYPE_MOTION: {
500 // Optimize case where the current application is unresponsive and the user
501 // decides to touch a window in a different application.
502 // If the application takes too long to catch up then we drop all events preceding
503 // the touch into the other window.
504 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
Jeff Brown33bbfd22011-02-24 20:55:35 -0800505 if (motionEntry->action == AMOTION_EVENT_ACTION_DOWN
Jeff Brown928e0542011-01-10 11:17:36 -0800506 && (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER)
507 && mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY
Jeff Brown9302c872011-07-13 22:51:29 -0700508 && mInputTargetWaitApplicationHandle != NULL) {
Jeff Brown91c69ab2011-02-14 17:03:18 -0800509 int32_t x = int32_t(motionEntry->firstSample.pointerCoords[0].
Jeff Brownebbd5d12011-02-17 13:01:34 -0800510 getAxisValue(AMOTION_EVENT_AXIS_X));
Jeff Brown91c69ab2011-02-14 17:03:18 -0800511 int32_t y = int32_t(motionEntry->firstSample.pointerCoords[0].
Jeff Brownebbd5d12011-02-17 13:01:34 -0800512 getAxisValue(AMOTION_EVENT_AXIS_Y));
Jeff Brown9302c872011-07-13 22:51:29 -0700513 sp<InputWindowHandle> touchedWindowHandle = findTouchedWindowAtLocked(x, y);
514 if (touchedWindowHandle != NULL
515 && touchedWindowHandle->inputApplicationHandle
516 != mInputTargetWaitApplicationHandle) {
Jeff Brown928e0542011-01-10 11:17:36 -0800517 // User touched a different application than the one we are waiting on.
518 // Flag the event, and start pruning the input queue.
519 mNextUnblockedEvent = motionEntry;
520 needWake = true;
521 }
522 }
523 break;
524 }
Jeff Brownb6997262010-10-08 22:31:17 -0700525 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700526
527 return needWake;
528}
529
Jeff Brown9302c872011-07-13 22:51:29 -0700530sp<InputWindowHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t x, int32_t y) {
Jeff Brown928e0542011-01-10 11:17:36 -0800531 // Traverse windows from front to back to find touched window.
Jeff Brown9302c872011-07-13 22:51:29 -0700532 size_t numWindows = mWindowHandles.size();
Jeff Brown928e0542011-01-10 11:17:36 -0800533 for (size_t i = 0; i < numWindows; i++) {
Jeff Brown9302c872011-07-13 22:51:29 -0700534 sp<InputWindowHandle> windowHandle = mWindowHandles.itemAt(i);
Jeff Browncc4f7db2011-08-30 20:34:48 -0700535 const InputWindowInfo* windowInfo = windowHandle->getInfo();
536 int32_t flags = windowInfo->layoutParamsFlags;
Jeff Brown928e0542011-01-10 11:17:36 -0800537
Jeff Browncc4f7db2011-08-30 20:34:48 -0700538 if (windowInfo->visible) {
539 if (!(flags & InputWindowInfo::FLAG_NOT_TOUCHABLE)) {
540 bool isTouchModal = (flags & (InputWindowInfo::FLAG_NOT_FOCUSABLE
541 | InputWindowInfo::FLAG_NOT_TOUCH_MODAL)) == 0;
542 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
Jeff Brown928e0542011-01-10 11:17:36 -0800543 // Found window.
Jeff Brown9302c872011-07-13 22:51:29 -0700544 return windowHandle;
Jeff Brown928e0542011-01-10 11:17:36 -0800545 }
546 }
547 }
548
Jeff Browncc4f7db2011-08-30 20:34:48 -0700549 if (flags & InputWindowInfo::FLAG_SYSTEM_ERROR) {
Jeff Brown928e0542011-01-10 11:17:36 -0800550 // Error window is on top but not visible, so touch is dropped.
551 return NULL;
552 }
553 }
554 return NULL;
555}
556
Jeff Brownb6997262010-10-08 22:31:17 -0700557void InputDispatcher::dropInboundEventLocked(EventEntry* entry, DropReason dropReason) {
558 const char* reason;
559 switch (dropReason) {
560 case DROP_REASON_POLICY:
Jeff Browne20c9e02010-10-11 14:20:19 -0700561#if DEBUG_INBOUND_EVENT_DETAILS
Jeff Brown3122e442010-10-11 23:32:49 -0700562 LOGD("Dropped event because policy consumed it.");
Jeff Browne20c9e02010-10-11 14:20:19 -0700563#endif
Jeff Brown3122e442010-10-11 23:32:49 -0700564 reason = "inbound event was dropped because the policy consumed it";
Jeff Brownb6997262010-10-08 22:31:17 -0700565 break;
566 case DROP_REASON_DISABLED:
567 LOGI("Dropped event because input dispatch is disabled.");
568 reason = "inbound event was dropped because input dispatch is disabled";
569 break;
570 case DROP_REASON_APP_SWITCH:
571 LOGI("Dropped event because of pending overdue app switch.");
572 reason = "inbound event was dropped because of pending overdue app switch";
573 break;
Jeff Brown928e0542011-01-10 11:17:36 -0800574 case DROP_REASON_BLOCKED:
575 LOGI("Dropped event because the current application is not responding and the user "
Jeff Brown81346812011-06-28 20:08:48 -0700576 "has started interacting with a different application.");
Jeff Brown928e0542011-01-10 11:17:36 -0800577 reason = "inbound event was dropped because the current application is not responding "
Jeff Brown81346812011-06-28 20:08:48 -0700578 "and the user has started interacting with a different application";
Jeff Brown928e0542011-01-10 11:17:36 -0800579 break;
580 case DROP_REASON_STALE:
581 LOGI("Dropped event because it is stale.");
582 reason = "inbound event was dropped because it is stale";
583 break;
Jeff Brownb6997262010-10-08 22:31:17 -0700584 default:
Jeff Brownb6110c22011-04-01 16:15:13 -0700585 LOG_ASSERT(false);
Jeff Brownb6997262010-10-08 22:31:17 -0700586 return;
587 }
588
589 switch (entry->type) {
Jeff Brownda3d5a92011-03-29 15:11:34 -0700590 case EventEntry::TYPE_KEY: {
591 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
592 synthesizeCancelationEventsForAllConnectionsLocked(options);
Jeff Brownb6997262010-10-08 22:31:17 -0700593 break;
Jeff Brownda3d5a92011-03-29 15:11:34 -0700594 }
Jeff Brownb6997262010-10-08 22:31:17 -0700595 case EventEntry::TYPE_MOTION: {
596 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
597 if (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) {
Jeff Brownda3d5a92011-03-29 15:11:34 -0700598 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
599 synthesizeCancelationEventsForAllConnectionsLocked(options);
Jeff Brownb6997262010-10-08 22:31:17 -0700600 } else {
Jeff Brownda3d5a92011-03-29 15:11:34 -0700601 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
602 synthesizeCancelationEventsForAllConnectionsLocked(options);
Jeff Brownb6997262010-10-08 22:31:17 -0700603 }
604 break;
605 }
606 }
607}
608
609bool InputDispatcher::isAppSwitchKeyCode(int32_t keyCode) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700610 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL;
611}
612
Jeff Brownb6997262010-10-08 22:31:17 -0700613bool InputDispatcher::isAppSwitchKeyEventLocked(KeyEntry* keyEntry) {
614 return ! (keyEntry->flags & AKEY_EVENT_FLAG_CANCELED)
615 && isAppSwitchKeyCode(keyEntry->keyCode)
Jeff Browne20c9e02010-10-11 14:20:19 -0700616 && (keyEntry->policyFlags & POLICY_FLAG_TRUSTED)
Jeff Brownb6997262010-10-08 22:31:17 -0700617 && (keyEntry->policyFlags & POLICY_FLAG_PASS_TO_USER);
618}
619
Jeff Brownb88102f2010-09-08 11:49:43 -0700620bool InputDispatcher::isAppSwitchPendingLocked() {
621 return mAppSwitchDueTime != LONG_LONG_MAX;
622}
623
Jeff Brownb88102f2010-09-08 11:49:43 -0700624void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
625 mAppSwitchDueTime = LONG_LONG_MAX;
626
627#if DEBUG_APP_SWITCH
628 if (handled) {
629 LOGD("App switch has arrived.");
630 } else {
631 LOGD("App switch was abandoned.");
632 }
633#endif
Jeff Brown46b9ac02010-04-22 18:58:52 -0700634}
635
Jeff Brown928e0542011-01-10 11:17:36 -0800636bool InputDispatcher::isStaleEventLocked(nsecs_t currentTime, EventEntry* entry) {
637 return currentTime - entry->eventTime >= STALE_EVENT_TIMEOUT;
638}
639
Jeff Brown9c3cda02010-06-15 01:31:58 -0700640bool InputDispatcher::runCommandsLockedInterruptible() {
641 if (mCommandQueue.isEmpty()) {
642 return false;
643 }
Jeff Brown46b9ac02010-04-22 18:58:52 -0700644
Jeff Brown9c3cda02010-06-15 01:31:58 -0700645 do {
646 CommandEntry* commandEntry = mCommandQueue.dequeueAtHead();
647
648 Command command = commandEntry->command;
649 (this->*command)(commandEntry); // commands are implicitly 'LockedInterruptible'
650
Jeff Brown7fbdc842010-06-17 20:52:56 -0700651 commandEntry->connection.clear();
Jeff Brownac386072011-07-20 15:19:50 -0700652 delete commandEntry;
Jeff Brown9c3cda02010-06-15 01:31:58 -0700653 } while (! mCommandQueue.isEmpty());
654 return true;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700655}
656
Jeff Brown9c3cda02010-06-15 01:31:58 -0700657InputDispatcher::CommandEntry* InputDispatcher::postCommandLocked(Command command) {
Jeff Brownac386072011-07-20 15:19:50 -0700658 CommandEntry* commandEntry = new CommandEntry(command);
Jeff Brown9c3cda02010-06-15 01:31:58 -0700659 mCommandQueue.enqueueAtTail(commandEntry);
660 return commandEntry;
661}
662
Jeff Brownb88102f2010-09-08 11:49:43 -0700663void InputDispatcher::drainInboundQueueLocked() {
664 while (! mInboundQueue.isEmpty()) {
665 EventEntry* entry = mInboundQueue.dequeueAtHead();
Jeff Brown54a18252010-09-16 14:07:33 -0700666 releaseInboundEventLocked(entry);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700667 }
Jeff Brown46b9ac02010-04-22 18:58:52 -0700668}
669
Jeff Brown54a18252010-09-16 14:07:33 -0700670void InputDispatcher::releasePendingEventLocked() {
Jeff Brownb88102f2010-09-08 11:49:43 -0700671 if (mPendingEvent) {
Jeff Brown54a18252010-09-16 14:07:33 -0700672 releaseInboundEventLocked(mPendingEvent);
Jeff Brownb88102f2010-09-08 11:49:43 -0700673 mPendingEvent = NULL;
674 }
675}
676
Jeff Brown54a18252010-09-16 14:07:33 -0700677void InputDispatcher::releaseInboundEventLocked(EventEntry* entry) {
Jeff Brown01ce2e92010-09-26 22:20:12 -0700678 InjectionState* injectionState = entry->injectionState;
679 if (injectionState && injectionState->injectionResult == INPUT_EVENT_INJECTION_PENDING) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700680#if DEBUG_DISPATCH_CYCLE
Jeff Brown01ce2e92010-09-26 22:20:12 -0700681 LOGD("Injected inbound event was dropped.");
Jeff Brownb88102f2010-09-08 11:49:43 -0700682#endif
683 setInjectionResultLocked(entry, INPUT_EVENT_INJECTION_FAILED);
684 }
Jeff Brownabb4d442011-08-15 12:55:32 -0700685 if (entry == mNextUnblockedEvent) {
686 mNextUnblockedEvent = NULL;
687 }
Jeff Brownac386072011-07-20 15:19:50 -0700688 entry->release();
Jeff Brownb88102f2010-09-08 11:49:43 -0700689}
690
Jeff Brownb88102f2010-09-08 11:49:43 -0700691void InputDispatcher::resetKeyRepeatLocked() {
692 if (mKeyRepeatState.lastKeyEntry) {
Jeff Brownac386072011-07-20 15:19:50 -0700693 mKeyRepeatState.lastKeyEntry->release();
Jeff Brownb88102f2010-09-08 11:49:43 -0700694 mKeyRepeatState.lastKeyEntry = NULL;
695 }
696}
697
Jeff Brown214eaf42011-05-26 19:17:02 -0700698InputDispatcher::KeyEntry* InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
Jeff Brown349703e2010-06-22 01:27:15 -0700699 KeyEntry* entry = mKeyRepeatState.lastKeyEntry;
700
Jeff Brown349703e2010-06-22 01:27:15 -0700701 // Reuse the repeated key entry if it is otherwise unreferenced.
Jeff Browne20c9e02010-10-11 14:20:19 -0700702 uint32_t policyFlags = (entry->policyFlags & POLICY_FLAG_RAW_MASK)
703 | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700704 if (entry->refCount == 1) {
Jeff Brownac386072011-07-20 15:19:50 -0700705 entry->recycle();
Jeff Brown7fbdc842010-06-17 20:52:56 -0700706 entry->eventTime = currentTime;
Jeff Brown7fbdc842010-06-17 20:52:56 -0700707 entry->policyFlags = policyFlags;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700708 entry->repeatCount += 1;
709 } else {
Jeff Brownac386072011-07-20 15:19:50 -0700710 KeyEntry* newEntry = new KeyEntry(currentTime,
Jeff Brownc5ed5912010-07-14 18:48:53 -0700711 entry->deviceId, entry->source, policyFlags,
Jeff Brown7fbdc842010-06-17 20:52:56 -0700712 entry->action, entry->flags, entry->keyCode, entry->scanCode,
Jeff Brown00fa7bd2010-07-02 15:37:36 -0700713 entry->metaState, entry->repeatCount + 1, entry->downTime);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700714
715 mKeyRepeatState.lastKeyEntry = newEntry;
Jeff Brownac386072011-07-20 15:19:50 -0700716 entry->release();
Jeff Brown46b9ac02010-04-22 18:58:52 -0700717
718 entry = newEntry;
719 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700720 entry->syntheticRepeat = true;
721
722 // Increment reference count since we keep a reference to the event in
723 // mKeyRepeatState.lastKeyEntry in addition to the one we return.
724 entry->refCount += 1;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700725
Jeff Brown214eaf42011-05-26 19:17:02 -0700726 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Jeff Brownb88102f2010-09-08 11:49:43 -0700727 return entry;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700728}
729
Jeff Brownb88102f2010-09-08 11:49:43 -0700730bool InputDispatcher::dispatchConfigurationChangedLocked(
731 nsecs_t currentTime, ConfigurationChangedEntry* entry) {
Jeff Brown46b9ac02010-04-22 18:58:52 -0700732#if DEBUG_OUTBOUND_EVENT_DETAILS
Jeff Brownb88102f2010-09-08 11:49:43 -0700733 LOGD("dispatchConfigurationChanged - eventTime=%lld", entry->eventTime);
734#endif
735
736 // Reset key repeating in case a keyboard device was added or removed or something.
737 resetKeyRepeatLocked();
738
739 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
740 CommandEntry* commandEntry = postCommandLocked(
741 & InputDispatcher::doNotifyConfigurationChangedInterruptible);
742 commandEntry->eventTime = entry->eventTime;
743 return true;
744}
745
Jeff Brown65fd2512011-08-18 11:20:58 -0700746bool InputDispatcher::dispatchDeviceResetLocked(
747 nsecs_t currentTime, DeviceResetEntry* entry) {
748#if DEBUG_OUTBOUND_EVENT_DETAILS
749 LOGD("dispatchDeviceReset - eventTime=%lld, deviceId=%d", entry->eventTime, entry->deviceId);
750#endif
751
752 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
753 "device was reset");
754 options.deviceId = entry->deviceId;
755 synthesizeCancelationEventsForAllConnectionsLocked(options);
756 return true;
757}
758
Jeff Brown214eaf42011-05-26 19:17:02 -0700759bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, KeyEntry* entry,
Jeff Browne20c9e02010-10-11 14:20:19 -0700760 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Jeff Browne46a0a42010-11-02 17:58:22 -0700761 // Preprocessing.
762 if (! entry->dispatchInProgress) {
763 if (entry->repeatCount == 0
764 && entry->action == AKEY_EVENT_ACTION_DOWN
765 && (entry->policyFlags & POLICY_FLAG_TRUSTED)
Jeff Brown0029c662011-03-30 02:25:18 -0700766 && (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
Jeff Browne46a0a42010-11-02 17:58:22 -0700767 if (mKeyRepeatState.lastKeyEntry
768 && mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode) {
769 // We have seen two identical key downs in a row which indicates that the device
770 // driver is automatically generating key repeats itself. We take note of the
771 // repeat here, but we disable our own next key repeat timer since it is clear that
772 // we will not need to synthesize key repeats ourselves.
773 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
774 resetKeyRepeatLocked();
775 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
776 } else {
777 // Not a repeat. Save key down state in case we do see a repeat later.
778 resetKeyRepeatLocked();
Jeff Brown214eaf42011-05-26 19:17:02 -0700779 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
Jeff Browne46a0a42010-11-02 17:58:22 -0700780 }
781 mKeyRepeatState.lastKeyEntry = entry;
782 entry->refCount += 1;
783 } else if (! entry->syntheticRepeat) {
784 resetKeyRepeatLocked();
785 }
786
Jeff Browne2e01262011-03-02 20:34:30 -0800787 if (entry->repeatCount == 1) {
788 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
789 } else {
790 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
791 }
792
Jeff Browne46a0a42010-11-02 17:58:22 -0700793 entry->dispatchInProgress = true;
794 resetTargetsLocked();
795
796 logOutboundKeyDetailsLocked("dispatchKey - ", entry);
797 }
798
Jeff Brown905805a2011-10-12 13:57:59 -0700799 // Handle case where the policy asked us to try again later last time.
800 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
801 if (currentTime < entry->interceptKeyWakeupTime) {
802 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
803 *nextWakeupTime = entry->interceptKeyWakeupTime;
804 }
805 return false; // wait until next wakeup
806 }
807 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
808 entry->interceptKeyWakeupTime = 0;
809 }
810
Jeff Brown54a18252010-09-16 14:07:33 -0700811 // Give the policy a chance to intercept the key.
812 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
Jeff Browne20c9e02010-10-11 14:20:19 -0700813 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Jeff Brown54a18252010-09-16 14:07:33 -0700814 CommandEntry* commandEntry = postCommandLocked(
815 & InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
Jeff Brown9302c872011-07-13 22:51:29 -0700816 if (mFocusedWindowHandle != NULL) {
817 commandEntry->inputWindowHandle = mFocusedWindowHandle;
Jeff Brown54a18252010-09-16 14:07:33 -0700818 }
819 commandEntry->keyEntry = entry;
820 entry->refCount += 1;
821 return false; // wait for the command to run
822 } else {
823 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
824 }
825 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Jeff Browne20c9e02010-10-11 14:20:19 -0700826 if (*dropReason == DROP_REASON_NOT_DROPPED) {
827 *dropReason = DROP_REASON_POLICY;
828 }
Jeff Brown54a18252010-09-16 14:07:33 -0700829 }
830
831 // Clean up if dropping the event.
Jeff Browne20c9e02010-10-11 14:20:19 -0700832 if (*dropReason != DROP_REASON_NOT_DROPPED) {
Jeff Brown54a18252010-09-16 14:07:33 -0700833 resetTargetsLocked();
Jeff Brown3122e442010-10-11 23:32:49 -0700834 setInjectionResultLocked(entry, *dropReason == DROP_REASON_POLICY
835 ? INPUT_EVENT_INJECTION_SUCCEEDED : INPUT_EVENT_INJECTION_FAILED);
Jeff Brown54a18252010-09-16 14:07:33 -0700836 return true;
837 }
838
Jeff Brownb88102f2010-09-08 11:49:43 -0700839 // Identify targets.
840 if (! mCurrentInputTargetsValid) {
Jeff Brown01ce2e92010-09-26 22:20:12 -0700841 int32_t injectionResult = findFocusedWindowTargetsLocked(currentTime,
842 entry, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700843 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
844 return false;
845 }
846
847 setInjectionResultLocked(entry, injectionResult);
848 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
849 return true;
850 }
851
852 addMonitoringTargetsLocked();
Jeff Brown01ce2e92010-09-26 22:20:12 -0700853 commitTargetsLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -0700854 }
855
856 // Dispatch the key.
857 dispatchEventToCurrentInputTargetsLocked(currentTime, entry, false);
Jeff Brownb88102f2010-09-08 11:49:43 -0700858 return true;
859}
860
861void InputDispatcher::logOutboundKeyDetailsLocked(const char* prefix, const KeyEntry* entry) {
862#if DEBUG_OUTBOUND_EVENT_DETAILS
Jeff Brown90655042010-12-02 13:50:46 -0800863 LOGD("%seventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, "
Jeff Brownb88102f2010-09-08 11:49:43 -0700864 "action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, "
Jeff Browne46a0a42010-11-02 17:58:22 -0700865 "repeatCount=%d, downTime=%lld",
Jeff Brownb88102f2010-09-08 11:49:43 -0700866 prefix,
867 entry->eventTime, entry->deviceId, entry->source, entry->policyFlags,
868 entry->action, entry->flags, entry->keyCode, entry->scanCode, entry->metaState,
Jeff Browne46a0a42010-11-02 17:58:22 -0700869 entry->repeatCount, entry->downTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700870#endif
871}
872
873bool InputDispatcher::dispatchMotionLocked(
Jeff Browne20c9e02010-10-11 14:20:19 -0700874 nsecs_t currentTime, MotionEntry* entry, DropReason* dropReason, nsecs_t* nextWakeupTime) {
Jeff Browne46a0a42010-11-02 17:58:22 -0700875 // Preprocessing.
876 if (! entry->dispatchInProgress) {
877 entry->dispatchInProgress = true;
878 resetTargetsLocked();
879
880 logOutboundMotionDetailsLocked("dispatchMotion - ", entry);
881 }
882
Jeff Brown54a18252010-09-16 14:07:33 -0700883 // Clean up if dropping the event.
Jeff Browne20c9e02010-10-11 14:20:19 -0700884 if (*dropReason != DROP_REASON_NOT_DROPPED) {
Jeff Brown54a18252010-09-16 14:07:33 -0700885 resetTargetsLocked();
Jeff Brown3122e442010-10-11 23:32:49 -0700886 setInjectionResultLocked(entry, *dropReason == DROP_REASON_POLICY
887 ? INPUT_EVENT_INJECTION_SUCCEEDED : INPUT_EVENT_INJECTION_FAILED);
Jeff Brown54a18252010-09-16 14:07:33 -0700888 return true;
889 }
890
Jeff Brownb88102f2010-09-08 11:49:43 -0700891 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
892
893 // Identify targets.
Jeff Browncc0c1592011-02-19 05:07:28 -0800894 bool conflictingPointerActions = false;
Jeff Brownb88102f2010-09-08 11:49:43 -0700895 if (! mCurrentInputTargetsValid) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700896 int32_t injectionResult;
Jeff Browna032cc02011-03-07 16:56:21 -0800897 const MotionSample* splitBatchAfterSample = NULL;
Jeff Brownb88102f2010-09-08 11:49:43 -0700898 if (isPointerEvent) {
899 // Pointer event. (eg. touchscreen)
Jeff Brown01ce2e92010-09-26 22:20:12 -0700900 injectionResult = findTouchedWindowTargetsLocked(currentTime,
Jeff Browna032cc02011-03-07 16:56:21 -0800901 entry, nextWakeupTime, &conflictingPointerActions, &splitBatchAfterSample);
Jeff Brownb88102f2010-09-08 11:49:43 -0700902 } else {
903 // Non touch event. (eg. trackball)
Jeff Brown01ce2e92010-09-26 22:20:12 -0700904 injectionResult = findFocusedWindowTargetsLocked(currentTime,
905 entry, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700906 }
907 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
908 return false;
909 }
910
911 setInjectionResultLocked(entry, injectionResult);
912 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
913 return true;
914 }
915
916 addMonitoringTargetsLocked();
Jeff Brown01ce2e92010-09-26 22:20:12 -0700917 commitTargetsLocked();
Jeff Browna032cc02011-03-07 16:56:21 -0800918
919 // Unbatch the event if necessary by splitting it into two parts after the
920 // motion sample indicated by splitBatchAfterSample.
921 if (splitBatchAfterSample && splitBatchAfterSample->next) {
922#if DEBUG_BATCHING
923 uint32_t originalSampleCount = entry->countSamples();
924#endif
925 MotionSample* nextSample = splitBatchAfterSample->next;
Jeff Brownac386072011-07-20 15:19:50 -0700926 MotionEntry* nextEntry = new MotionEntry(nextSample->eventTime,
Jeff Browna032cc02011-03-07 16:56:21 -0800927 entry->deviceId, entry->source, entry->policyFlags,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700928 entry->action, entry->flags,
929 entry->metaState, entry->buttonState, entry->edgeFlags,
Jeff Browna032cc02011-03-07 16:56:21 -0800930 entry->xPrecision, entry->yPrecision, entry->downTime,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700931 entry->pointerCount, entry->pointerProperties, nextSample->pointerCoords);
Jeff Browna032cc02011-03-07 16:56:21 -0800932 if (nextSample != entry->lastSample) {
933 nextEntry->firstSample.next = nextSample->next;
934 nextEntry->lastSample = entry->lastSample;
935 }
Jeff Brownac386072011-07-20 15:19:50 -0700936 delete nextSample;
Jeff Browna032cc02011-03-07 16:56:21 -0800937
938 entry->lastSample = const_cast<MotionSample*>(splitBatchAfterSample);
939 entry->lastSample->next = NULL;
940
941 if (entry->injectionState) {
942 nextEntry->injectionState = entry->injectionState;
943 entry->injectionState->refCount += 1;
944 }
945
946#if DEBUG_BATCHING
947 LOGD("Split batch of %d samples into two parts, first part has %d samples, "
948 "second part has %d samples.", originalSampleCount,
949 entry->countSamples(), nextEntry->countSamples());
950#endif
951
952 mInboundQueue.enqueueAtHead(nextEntry);
953 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700954 }
955
956 // Dispatch the motion.
Jeff Browncc0c1592011-02-19 05:07:28 -0800957 if (conflictingPointerActions) {
Jeff Brownda3d5a92011-03-29 15:11:34 -0700958 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
959 "conflicting pointer actions");
960 synthesizeCancelationEventsForAllConnectionsLocked(options);
Jeff Browncc0c1592011-02-19 05:07:28 -0800961 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700962 dispatchEventToCurrentInputTargetsLocked(currentTime, entry, false);
Jeff Brownb88102f2010-09-08 11:49:43 -0700963 return true;
964}
965
966
967void InputDispatcher::logOutboundMotionDetailsLocked(const char* prefix, const MotionEntry* entry) {
968#if DEBUG_OUTBOUND_EVENT_DETAILS
Jeff Brown90655042010-12-02 13:50:46 -0800969 LOGD("%seventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, "
Jeff Brown85a31762010-09-01 17:01:00 -0700970 "action=0x%x, flags=0x%x, "
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700971 "metaState=0x%x, buttonState=0x%x, "
972 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%lld",
Jeff Brownb88102f2010-09-08 11:49:43 -0700973 prefix,
Jeff Brown85a31762010-09-01 17:01:00 -0700974 entry->eventTime, entry->deviceId, entry->source, entry->policyFlags,
975 entry->action, entry->flags,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700976 entry->metaState, entry->buttonState,
977 entry->edgeFlags, entry->xPrecision, entry->yPrecision,
Jeff Brown46b9ac02010-04-22 18:58:52 -0700978 entry->downTime);
979
980 // Print the most recent sample that we have available, this may change due to batching.
981 size_t sampleCount = 1;
Jeff Brownb88102f2010-09-08 11:49:43 -0700982 const MotionSample* sample = & entry->firstSample;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700983 for (; sample->next != NULL; sample = sample->next) {
984 sampleCount += 1;
985 }
986 for (uint32_t i = 0; i < entry->pointerCount; i++) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700987 LOGD(" Pointer %d: id=%d, toolType=%d, "
988 "x=%f, y=%f, pressure=%f, size=%f, "
Jeff Brown85a31762010-09-01 17:01:00 -0700989 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
Jeff Brown8d608662010-08-30 03:02:23 -0700990 "orientation=%f",
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700991 i, entry->pointerProperties[i].id,
992 entry->pointerProperties[i].toolType,
Jeff Brownebbd5d12011-02-17 13:01:34 -0800993 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
994 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
995 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
996 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
997 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
998 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
999 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1000 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1001 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Jeff Brown46b9ac02010-04-22 18:58:52 -07001002 }
1003
1004 // Keep in mind that due to batching, it is possible for the number of samples actually
1005 // dispatched to change before the application finally consumed them.
Jeff Brownc5ed5912010-07-14 18:48:53 -07001006 if (entry->action == AMOTION_EVENT_ACTION_MOVE) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07001007 LOGD(" ... Total movement samples currently batched %d ...", sampleCount);
1008 }
1009#endif
Jeff Brown46b9ac02010-04-22 18:58:52 -07001010}
1011
1012void InputDispatcher::dispatchEventToCurrentInputTargetsLocked(nsecs_t currentTime,
1013 EventEntry* eventEntry, bool resumeWithAppendedMotionSample) {
1014#if DEBUG_DISPATCH_CYCLE
Jeff Brown9c3cda02010-06-15 01:31:58 -07001015 LOGD("dispatchEventToCurrentInputTargets - "
Jeff Brown46b9ac02010-04-22 18:58:52 -07001016 "resumeWithAppendedMotionSample=%s",
Jeff Brownb88102f2010-09-08 11:49:43 -07001017 toString(resumeWithAppendedMotionSample));
Jeff Brown46b9ac02010-04-22 18:58:52 -07001018#endif
1019
Jeff Brownb6110c22011-04-01 16:15:13 -07001020 LOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
Jeff Brown9c3cda02010-06-15 01:31:58 -07001021
Jeff Browne2fe69e2010-10-18 13:21:23 -07001022 pokeUserActivityLocked(eventEntry);
1023
Jeff Brown46b9ac02010-04-22 18:58:52 -07001024 for (size_t i = 0; i < mCurrentInputTargets.size(); i++) {
1025 const InputTarget& inputTarget = mCurrentInputTargets.itemAt(i);
1026
Jeff Brown519e0242010-09-15 15:18:56 -07001027 ssize_t connectionIndex = getConnectionIndexLocked(inputTarget.inputChannel);
Jeff Brown46b9ac02010-04-22 18:58:52 -07001028 if (connectionIndex >= 0) {
1029 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
Jeff Brown7fbdc842010-06-17 20:52:56 -07001030 prepareDispatchCycleLocked(currentTime, connection, eventEntry, & inputTarget,
Jeff Brown46b9ac02010-04-22 18:58:52 -07001031 resumeWithAppendedMotionSample);
1032 } else {
Jeff Brownb6997262010-10-08 22:31:17 -07001033#if DEBUG_FOCUS
1034 LOGD("Dropping event delivery to target with channel '%s' because it "
1035 "is no longer registered with the input dispatcher.",
Jeff Brown46b9ac02010-04-22 18:58:52 -07001036 inputTarget.inputChannel->getName().string());
Jeff Brownb6997262010-10-08 22:31:17 -07001037#endif
Jeff Brown46b9ac02010-04-22 18:58:52 -07001038 }
1039 }
1040}
1041
Jeff Brown54a18252010-09-16 14:07:33 -07001042void InputDispatcher::resetTargetsLocked() {
Jeff Brownb88102f2010-09-08 11:49:43 -07001043 mCurrentInputTargetsValid = false;
1044 mCurrentInputTargets.clear();
Jeff Brown5ea29ab2011-07-27 11:50:51 -07001045 resetANRTimeoutsLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -07001046}
1047
Jeff Brown01ce2e92010-09-26 22:20:12 -07001048void InputDispatcher::commitTargetsLocked() {
Jeff Brownb88102f2010-09-08 11:49:43 -07001049 mCurrentInputTargetsValid = true;
1050}
1051
1052int32_t InputDispatcher::handleTargetsNotReadyLocked(nsecs_t currentTime,
Jeff Brown9302c872011-07-13 22:51:29 -07001053 const EventEntry* entry,
1054 const sp<InputApplicationHandle>& applicationHandle,
1055 const sp<InputWindowHandle>& windowHandle,
Jeff Brownb88102f2010-09-08 11:49:43 -07001056 nsecs_t* nextWakeupTime) {
Jeff Brown9302c872011-07-13 22:51:29 -07001057 if (applicationHandle == NULL && windowHandle == NULL) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001058 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY) {
1059#if DEBUG_FOCUS
1060 LOGD("Waiting for system to become ready for input.");
1061#endif
1062 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY;
1063 mInputTargetWaitStartTime = currentTime;
1064 mInputTargetWaitTimeoutTime = LONG_LONG_MAX;
1065 mInputTargetWaitTimeoutExpired = false;
Jeff Brown9302c872011-07-13 22:51:29 -07001066 mInputTargetWaitApplicationHandle.clear();
Jeff Brownb88102f2010-09-08 11:49:43 -07001067 }
1068 } else {
1069 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
1070#if DEBUG_FOCUS
Jeff Brown519e0242010-09-15 15:18:56 -07001071 LOGD("Waiting for application to become ready for input: %s",
Jeff Brown9302c872011-07-13 22:51:29 -07001072 getApplicationWindowLabelLocked(applicationHandle, windowHandle).string());
Jeff Brownb88102f2010-09-08 11:49:43 -07001073#endif
Jeff Browncc4f7db2011-08-30 20:34:48 -07001074 nsecs_t timeout;
1075 if (windowHandle != NULL) {
1076 timeout = windowHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
1077 } else if (applicationHandle != NULL) {
1078 timeout = applicationHandle->getDispatchingTimeout(
1079 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
1080 } else {
1081 timeout = DEFAULT_INPUT_DISPATCHING_TIMEOUT;
1082 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001083
1084 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY;
1085 mInputTargetWaitStartTime = currentTime;
1086 mInputTargetWaitTimeoutTime = currentTime + timeout;
1087 mInputTargetWaitTimeoutExpired = false;
Jeff Brown9302c872011-07-13 22:51:29 -07001088 mInputTargetWaitApplicationHandle.clear();
Jeff Brown928e0542011-01-10 11:17:36 -08001089
Jeff Brown9302c872011-07-13 22:51:29 -07001090 if (windowHandle != NULL) {
1091 mInputTargetWaitApplicationHandle = windowHandle->inputApplicationHandle;
Jeff Brown928e0542011-01-10 11:17:36 -08001092 }
Jeff Brown9302c872011-07-13 22:51:29 -07001093 if (mInputTargetWaitApplicationHandle == NULL && applicationHandle != NULL) {
1094 mInputTargetWaitApplicationHandle = applicationHandle;
Jeff Brown928e0542011-01-10 11:17:36 -08001095 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001096 }
1097 }
1098
1099 if (mInputTargetWaitTimeoutExpired) {
1100 return INPUT_EVENT_INJECTION_TIMED_OUT;
1101 }
1102
1103 if (currentTime >= mInputTargetWaitTimeoutTime) {
Jeff Brown9302c872011-07-13 22:51:29 -07001104 onANRLocked(currentTime, applicationHandle, windowHandle,
1105 entry->eventTime, mInputTargetWaitStartTime);
Jeff Brownb88102f2010-09-08 11:49:43 -07001106
1107 // Force poll loop to wake up immediately on next iteration once we get the
1108 // ANR response back from the policy.
1109 *nextWakeupTime = LONG_LONG_MIN;
1110 return INPUT_EVENT_INJECTION_PENDING;
1111 } else {
1112 // Force poll loop to wake up when timeout is due.
1113 if (mInputTargetWaitTimeoutTime < *nextWakeupTime) {
1114 *nextWakeupTime = mInputTargetWaitTimeoutTime;
1115 }
1116 return INPUT_EVENT_INJECTION_PENDING;
1117 }
1118}
1119
Jeff Brown519e0242010-09-15 15:18:56 -07001120void InputDispatcher::resumeAfterTargetsNotReadyTimeoutLocked(nsecs_t newTimeout,
1121 const sp<InputChannel>& inputChannel) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001122 if (newTimeout > 0) {
1123 // Extend the timeout.
1124 mInputTargetWaitTimeoutTime = now() + newTimeout;
1125 } else {
1126 // Give up.
1127 mInputTargetWaitTimeoutExpired = true;
Jeff Brown519e0242010-09-15 15:18:56 -07001128
Jeff Brown01ce2e92010-09-26 22:20:12 -07001129 // Release the touch targets.
1130 mTouchState.reset();
Jeff Brown2a95c2a2010-09-16 12:31:46 -07001131
Jeff Brown519e0242010-09-15 15:18:56 -07001132 // Input state will not be realistic. Mark it out of sync.
Jeff Browndc3e0052010-09-16 11:02:16 -07001133 if (inputChannel.get()) {
1134 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
1135 if (connectionIndex >= 0) {
1136 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
Jeff Brown00045a72010-12-09 18:10:30 -08001137 if (connection->status == Connection::STATUS_NORMAL) {
Jeff Brownda3d5a92011-03-29 15:11:34 -07001138 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
Jeff Brown00045a72010-12-09 18:10:30 -08001139 "application not responding");
Jeff Brownda3d5a92011-03-29 15:11:34 -07001140 synthesizeCancelationEventsForConnectionLocked(connection, options);
Jeff Brown00045a72010-12-09 18:10:30 -08001141 }
Jeff Browndc3e0052010-09-16 11:02:16 -07001142 }
Jeff Brown519e0242010-09-15 15:18:56 -07001143 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001144 }
1145}
1146
Jeff Brown519e0242010-09-15 15:18:56 -07001147nsecs_t InputDispatcher::getTimeSpentWaitingForApplicationLocked(
Jeff Brownb88102f2010-09-08 11:49:43 -07001148 nsecs_t currentTime) {
1149 if (mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
1150 return currentTime - mInputTargetWaitStartTime;
1151 }
1152 return 0;
1153}
1154
1155void InputDispatcher::resetANRTimeoutsLocked() {
1156#if DEBUG_FOCUS
1157 LOGD("Resetting ANR timeouts.");
1158#endif
1159
Jeff Brownb88102f2010-09-08 11:49:43 -07001160 // Reset input target wait timeout.
1161 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_NONE;
Jeff Brown5ea29ab2011-07-27 11:50:51 -07001162 mInputTargetWaitApplicationHandle.clear();
Jeff Brownb88102f2010-09-08 11:49:43 -07001163}
1164
Jeff Brown01ce2e92010-09-26 22:20:12 -07001165int32_t InputDispatcher::findFocusedWindowTargetsLocked(nsecs_t currentTime,
1166 const EventEntry* entry, nsecs_t* nextWakeupTime) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001167 mCurrentInputTargets.clear();
1168
1169 int32_t injectionResult;
1170
1171 // If there is no currently focused window and no focused application
1172 // then drop the event.
Jeff Brown9302c872011-07-13 22:51:29 -07001173 if (mFocusedWindowHandle == NULL) {
1174 if (mFocusedApplicationHandle != NULL) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001175#if DEBUG_FOCUS
1176 LOGD("Waiting because there is no focused window but there is a "
Jeff Brown519e0242010-09-15 15:18:56 -07001177 "focused application that may eventually add a window: %s.",
Jeff Brown9302c872011-07-13 22:51:29 -07001178 getApplicationWindowLabelLocked(mFocusedApplicationHandle, NULL).string());
Jeff Brownb88102f2010-09-08 11:49:43 -07001179#endif
1180 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brown9302c872011-07-13 22:51:29 -07001181 mFocusedApplicationHandle, NULL, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -07001182 goto Unresponsive;
1183 }
1184
1185 LOGI("Dropping event because there is no focused window or focused application.");
1186 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1187 goto Failed;
1188 }
1189
1190 // Check permissions.
Jeff Brown9302c872011-07-13 22:51:29 -07001191 if (! checkInjectionPermission(mFocusedWindowHandle, entry->injectionState)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001192 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1193 goto Failed;
1194 }
1195
1196 // If the currently focused window is paused then keep waiting.
Jeff Browncc4f7db2011-08-30 20:34:48 -07001197 if (mFocusedWindowHandle->getInfo()->paused) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001198#if DEBUG_FOCUS
1199 LOGD("Waiting because focused window is paused.");
1200#endif
1201 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brown9302c872011-07-13 22:51:29 -07001202 mFocusedApplicationHandle, mFocusedWindowHandle, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -07001203 goto Unresponsive;
1204 }
1205
Jeff Brown519e0242010-09-15 15:18:56 -07001206 // If the currently focused window is still working on previous events then keep waiting.
Jeff Brown9302c872011-07-13 22:51:29 -07001207 if (! isWindowFinishedWithPreviousInputLocked(mFocusedWindowHandle)) {
Jeff Brown519e0242010-09-15 15:18:56 -07001208#if DEBUG_FOCUS
1209 LOGD("Waiting because focused window still processing previous input.");
1210#endif
1211 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brown9302c872011-07-13 22:51:29 -07001212 mFocusedApplicationHandle, mFocusedWindowHandle, nextWakeupTime);
Jeff Brown519e0242010-09-15 15:18:56 -07001213 goto Unresponsive;
1214 }
1215
Jeff Brownb88102f2010-09-08 11:49:43 -07001216 // Success! Output targets.
1217 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
Jeff Brown9302c872011-07-13 22:51:29 -07001218 addWindowTargetLocked(mFocusedWindowHandle,
Jeff Browna032cc02011-03-07 16:56:21 -08001219 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS, BitSet32(0));
Jeff Brownb88102f2010-09-08 11:49:43 -07001220
1221 // Done.
1222Failed:
1223Unresponsive:
Jeff Brown519e0242010-09-15 15:18:56 -07001224 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
1225 updateDispatchStatisticsLocked(currentTime, entry,
1226 injectionResult, timeSpentWaitingForApplication);
Jeff Brownb88102f2010-09-08 11:49:43 -07001227#if DEBUG_FOCUS
Jeff Brown519e0242010-09-15 15:18:56 -07001228 LOGD("findFocusedWindow finished: injectionResult=%d, "
1229 "timeSpendWaitingForApplication=%0.1fms",
1230 injectionResult, timeSpentWaitingForApplication / 1000000.0);
Jeff Brownb88102f2010-09-08 11:49:43 -07001231#endif
1232 return injectionResult;
1233}
1234
Jeff Brown01ce2e92010-09-26 22:20:12 -07001235int32_t InputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime,
Jeff Browna032cc02011-03-07 16:56:21 -08001236 const MotionEntry* entry, nsecs_t* nextWakeupTime, bool* outConflictingPointerActions,
1237 const MotionSample** outSplitBatchAfterSample) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001238 enum InjectionPermission {
1239 INJECTION_PERMISSION_UNKNOWN,
1240 INJECTION_PERMISSION_GRANTED,
1241 INJECTION_PERMISSION_DENIED
1242 };
1243
Jeff Brownb88102f2010-09-08 11:49:43 -07001244 mCurrentInputTargets.clear();
1245
1246 nsecs_t startTime = now();
1247
1248 // For security reasons, we defer updating the touch state until we are sure that
1249 // event injection will be allowed.
1250 //
1251 // FIXME In the original code, screenWasOff could never be set to true.
1252 // The reason is that the POLICY_FLAG_WOKE_HERE
1253 // and POLICY_FLAG_BRIGHT_HERE flags were set only when preprocessing raw
1254 // EV_KEY, EV_REL and EV_ABS events. As it happens, the touch event was
1255 // actually enqueued using the policyFlags that appeared in the final EV_SYN
1256 // events upon which no preprocessing took place. So policyFlags was always 0.
1257 // In the new native input dispatcher we're a bit more careful about event
1258 // preprocessing so the touches we receive can actually have non-zero policyFlags.
1259 // Unfortunately we obtain undesirable behavior.
1260 //
1261 // Here's what happens:
1262 //
1263 // When the device dims in anticipation of going to sleep, touches
1264 // in windows which have FLAG_TOUCHABLE_WHEN_WAKING cause
1265 // the device to brighten and reset the user activity timer.
1266 // Touches on other windows (such as the launcher window)
1267 // are dropped. Then after a moment, the device goes to sleep. Oops.
1268 //
1269 // Also notice how screenWasOff was being initialized using POLICY_FLAG_BRIGHT_HERE
1270 // instead of POLICY_FLAG_WOKE_HERE...
1271 //
1272 bool screenWasOff = false; // original policy: policyFlags & POLICY_FLAG_BRIGHT_HERE;
1273
1274 int32_t action = entry->action;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001275 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Jeff Brownb88102f2010-09-08 11:49:43 -07001276
1277 // Update the touch state as needed based on the properties of the touch event.
Jeff Brown01ce2e92010-09-26 22:20:12 -07001278 int32_t injectionResult = INPUT_EVENT_INJECTION_PENDING;
1279 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
Jeff Brown9302c872011-07-13 22:51:29 -07001280 sp<InputWindowHandle> newHoverWindowHandle;
Jeff Browncc0c1592011-02-19 05:07:28 -08001281
1282 bool isSplit = mTouchState.split;
Jeff Brown2717eff2011-06-30 23:53:07 -07001283 bool switchedDevice = mTouchState.deviceId >= 0
1284 && (mTouchState.deviceId != entry->deviceId
1285 || mTouchState.source != entry->source);
Jeff Browna032cc02011-03-07 16:56:21 -08001286 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE
1287 || maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER
1288 || maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1289 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN
1290 || maskedAction == AMOTION_EVENT_ACTION_SCROLL
1291 || isHoverAction);
Jeff Brown81346812011-06-28 20:08:48 -07001292 bool wrongDevice = false;
Jeff Browna032cc02011-03-07 16:56:21 -08001293 if (newGesture) {
Jeff Browncc0c1592011-02-19 05:07:28 -08001294 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Jeff Brown81346812011-06-28 20:08:48 -07001295 if (switchedDevice && mTouchState.down && !down) {
1296#if DEBUG_FOCUS
1297 LOGD("Dropping event because a pointer for a different device is already down.");
1298#endif
Jeff Browncc0c1592011-02-19 05:07:28 -08001299 mTempTouchState.copyFrom(mTouchState);
Jeff Brown81346812011-06-28 20:08:48 -07001300 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1301 switchedDevice = false;
1302 wrongDevice = true;
1303 goto Failed;
Jeff Browncc0c1592011-02-19 05:07:28 -08001304 }
Jeff Brown81346812011-06-28 20:08:48 -07001305 mTempTouchState.reset();
1306 mTempTouchState.down = down;
1307 mTempTouchState.deviceId = entry->deviceId;
1308 mTempTouchState.source = entry->source;
1309 isSplit = false;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001310 } else {
1311 mTempTouchState.copyFrom(mTouchState);
Jeff Browncc0c1592011-02-19 05:07:28 -08001312 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001313
Jeff Browna032cc02011-03-07 16:56:21 -08001314 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
Jeff Brown33bbfd22011-02-24 20:55:35 -08001315 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
Jeff Brownb88102f2010-09-08 11:49:43 -07001316
Jeff Browna032cc02011-03-07 16:56:21 -08001317 const MotionSample* sample = &entry->firstSample;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001318 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Jeff Browna032cc02011-03-07 16:56:21 -08001319 int32_t x = int32_t(sample->pointerCoords[pointerIndex].
Jeff Brownebbd5d12011-02-17 13:01:34 -08001320 getAxisValue(AMOTION_EVENT_AXIS_X));
Jeff Browna032cc02011-03-07 16:56:21 -08001321 int32_t y = int32_t(sample->pointerCoords[pointerIndex].
Jeff Brownebbd5d12011-02-17 13:01:34 -08001322 getAxisValue(AMOTION_EVENT_AXIS_Y));
Jeff Brown9302c872011-07-13 22:51:29 -07001323 sp<InputWindowHandle> newTouchedWindowHandle;
1324 sp<InputWindowHandle> topErrorWindowHandle;
Jeff Browna032cc02011-03-07 16:56:21 -08001325 bool isTouchModal = false;
Jeff Brownb88102f2010-09-08 11:49:43 -07001326
1327 // Traverse windows from front to back to find touched window and outside targets.
Jeff Brown9302c872011-07-13 22:51:29 -07001328 size_t numWindows = mWindowHandles.size();
Jeff Brownb88102f2010-09-08 11:49:43 -07001329 for (size_t i = 0; i < numWindows; i++) {
Jeff Brown9302c872011-07-13 22:51:29 -07001330 sp<InputWindowHandle> windowHandle = mWindowHandles.itemAt(i);
Jeff Browncc4f7db2011-08-30 20:34:48 -07001331 const InputWindowInfo* windowInfo = windowHandle->getInfo();
1332 int32_t flags = windowInfo->layoutParamsFlags;
Jeff Brownb88102f2010-09-08 11:49:43 -07001333
Jeff Browncc4f7db2011-08-30 20:34:48 -07001334 if (flags & InputWindowInfo::FLAG_SYSTEM_ERROR) {
Jeff Brown9302c872011-07-13 22:51:29 -07001335 if (topErrorWindowHandle == NULL) {
1336 topErrorWindowHandle = windowHandle;
Jeff Brownb88102f2010-09-08 11:49:43 -07001337 }
1338 }
1339
Jeff Browncc4f7db2011-08-30 20:34:48 -07001340 if (windowInfo->visible) {
1341 if (! (flags & InputWindowInfo::FLAG_NOT_TOUCHABLE)) {
1342 isTouchModal = (flags & (InputWindowInfo::FLAG_NOT_FOCUSABLE
1343 | InputWindowInfo::FLAG_NOT_TOUCH_MODAL)) == 0;
1344 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
Jeff Brown9302c872011-07-13 22:51:29 -07001345 if (! screenWasOff
Jeff Browncc4f7db2011-08-30 20:34:48 -07001346 || (flags & InputWindowInfo::FLAG_TOUCHABLE_WHEN_WAKING)) {
Jeff Brown9302c872011-07-13 22:51:29 -07001347 newTouchedWindowHandle = windowHandle;
Jeff Brownb88102f2010-09-08 11:49:43 -07001348 }
1349 break; // found touched window, exit window loop
1350 }
1351 }
1352
Jeff Brown01ce2e92010-09-26 22:20:12 -07001353 if (maskedAction == AMOTION_EVENT_ACTION_DOWN
Jeff Browncc4f7db2011-08-30 20:34:48 -07001354 && (flags & InputWindowInfo::FLAG_WATCH_OUTSIDE_TOUCH)) {
Jeff Browna032cc02011-03-07 16:56:21 -08001355 int32_t outsideTargetFlags = InputTarget::FLAG_DISPATCH_AS_OUTSIDE;
Jeff Brown9302c872011-07-13 22:51:29 -07001356 if (isWindowObscuredAtPointLocked(windowHandle, x, y)) {
Jeff Brown19dfc832010-10-05 12:26:23 -07001357 outsideTargetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1358 }
1359
Jeff Brown9302c872011-07-13 22:51:29 -07001360 mTempTouchState.addOrUpdateWindow(
1361 windowHandle, outsideTargetFlags, BitSet32(0));
Jeff Brownb88102f2010-09-08 11:49:43 -07001362 }
1363 }
1364 }
1365
1366 // If there is an error window but it is not taking focus (typically because
1367 // it is invisible) then wait for it. Any other focused window may in
1368 // fact be in ANR state.
Jeff Brown9302c872011-07-13 22:51:29 -07001369 if (topErrorWindowHandle != NULL && newTouchedWindowHandle != topErrorWindowHandle) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001370#if DEBUG_FOCUS
1371 LOGD("Waiting because system error window is pending.");
1372#endif
1373 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
1374 NULL, NULL, nextWakeupTime);
1375 injectionPermission = INJECTION_PERMISSION_UNKNOWN;
1376 goto Unresponsive;
1377 }
1378
Jeff Brown01ce2e92010-09-26 22:20:12 -07001379 // Figure out whether splitting will be allowed for this window.
Jeff Browncc4f7db2011-08-30 20:34:48 -07001380 if (newTouchedWindowHandle != NULL
1381 && newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001382 // New window supports splitting.
1383 isSplit = true;
1384 } else if (isSplit) {
1385 // New window does not support splitting but we have already split events.
1386 // Assign the pointer to the first foreground window we find.
1387 // (May be NULL which is why we put this code block before the next check.)
Jeff Brown9302c872011-07-13 22:51:29 -07001388 newTouchedWindowHandle = mTempTouchState.getFirstForegroundWindowHandle();
Jeff Brown01ce2e92010-09-26 22:20:12 -07001389 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001390
Jeff Brownb88102f2010-09-08 11:49:43 -07001391 // If we did not find a touched window then fail.
Jeff Brown9302c872011-07-13 22:51:29 -07001392 if (newTouchedWindowHandle == NULL) {
1393 if (mFocusedApplicationHandle != NULL) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001394#if DEBUG_FOCUS
1395 LOGD("Waiting because there is no touched window but there is a "
Jeff Brown519e0242010-09-15 15:18:56 -07001396 "focused application that may eventually add a new window: %s.",
Jeff Brown9302c872011-07-13 22:51:29 -07001397 getApplicationWindowLabelLocked(mFocusedApplicationHandle, NULL).string());
Jeff Brownb88102f2010-09-08 11:49:43 -07001398#endif
1399 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brown9302c872011-07-13 22:51:29 -07001400 mFocusedApplicationHandle, NULL, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -07001401 goto Unresponsive;
1402 }
1403
1404 LOGI("Dropping event because there is no touched window or focused application.");
1405 injectionResult = INPUT_EVENT_INJECTION_FAILED;
Jeff Brownb88102f2010-09-08 11:49:43 -07001406 goto Failed;
1407 }
1408
Jeff Brown19dfc832010-10-05 12:26:23 -07001409 // Set target flags.
Jeff Browna032cc02011-03-07 16:56:21 -08001410 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
Jeff Brown19dfc832010-10-05 12:26:23 -07001411 if (isSplit) {
1412 targetFlags |= InputTarget::FLAG_SPLIT;
1413 }
Jeff Brown9302c872011-07-13 22:51:29 -07001414 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
Jeff Brown19dfc832010-10-05 12:26:23 -07001415 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1416 }
1417
Jeff Browna032cc02011-03-07 16:56:21 -08001418 // Update hover state.
1419 if (isHoverAction) {
Jeff Brown9302c872011-07-13 22:51:29 -07001420 newHoverWindowHandle = newTouchedWindowHandle;
Jeff Browna032cc02011-03-07 16:56:21 -08001421
1422 // Ensure all subsequent motion samples are also within the touched window.
1423 // Set *outSplitBatchAfterSample to the sample before the first one that is not
1424 // within the touched window.
1425 if (!isTouchModal) {
1426 while (sample->next) {
Jeff Browncc4f7db2011-08-30 20:34:48 -07001427 if (!newHoverWindowHandle->getInfo()->touchableRegionContainsPoint(
Jeff Browna032cc02011-03-07 16:56:21 -08001428 sample->next->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X),
1429 sample->next->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y))) {
1430 *outSplitBatchAfterSample = sample;
1431 break;
1432 }
1433 sample = sample->next;
1434 }
1435 }
1436 } else if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
Jeff Brown9302c872011-07-13 22:51:29 -07001437 newHoverWindowHandle = mLastHoverWindowHandle;
Jeff Browna032cc02011-03-07 16:56:21 -08001438 }
1439
Jeff Brown01ce2e92010-09-26 22:20:12 -07001440 // Update the temporary touch state.
1441 BitSet32 pointerIds;
1442 if (isSplit) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07001443 uint32_t pointerId = entry->pointerProperties[pointerIndex].id;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001444 pointerIds.markBit(pointerId);
Jeff Brownb88102f2010-09-08 11:49:43 -07001445 }
Jeff Brown9302c872011-07-13 22:51:29 -07001446 mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Jeff Brownb88102f2010-09-08 11:49:43 -07001447 } else {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001448 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
Jeff Brownb88102f2010-09-08 11:49:43 -07001449
1450 // If the pointer is not currently down, then ignore the event.
Jeff Brown01ce2e92010-09-26 22:20:12 -07001451 if (! mTempTouchState.down) {
Jeff Browna2cc28d2011-03-25 11:58:46 -07001452#if DEBUG_FOCUS
Jeff Brown76860e32010-10-25 17:37:46 -07001453 LOGD("Dropping event because the pointer is not down or we previously "
1454 "dropped the pointer down event.");
1455#endif
Jeff Brownb88102f2010-09-08 11:49:43 -07001456 injectionResult = INPUT_EVENT_INJECTION_FAILED;
Jeff Brownb88102f2010-09-08 11:49:43 -07001457 goto Failed;
1458 }
Jeff Brown98db5fa2011-06-08 15:37:10 -07001459
1460 // Check whether touches should slip outside of the current foreground window.
1461 if (maskedAction == AMOTION_EVENT_ACTION_MOVE
1462 && entry->pointerCount == 1
1463 && mTempTouchState.isSlippery()) {
1464 const MotionSample* sample = &entry->firstSample;
1465 int32_t x = int32_t(sample->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
1466 int32_t y = int32_t(sample->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
1467
Jeff Brown9302c872011-07-13 22:51:29 -07001468 sp<InputWindowHandle> oldTouchedWindowHandle =
1469 mTempTouchState.getFirstForegroundWindowHandle();
1470 sp<InputWindowHandle> newTouchedWindowHandle = findTouchedWindowAtLocked(x, y);
1471 if (oldTouchedWindowHandle != newTouchedWindowHandle
1472 && newTouchedWindowHandle != NULL) {
Jeff Brown98db5fa2011-06-08 15:37:10 -07001473#if DEBUG_FOCUS
1474 LOGD("Touch is slipping out of window %s into window %s.",
Jeff Browncc4f7db2011-08-30 20:34:48 -07001475 oldTouchedWindowHandle->getName().string(),
1476 newTouchedWindowHandle->getName().string());
Jeff Brown98db5fa2011-06-08 15:37:10 -07001477#endif
1478 // Make a slippery exit from the old window.
Jeff Brown9302c872011-07-13 22:51:29 -07001479 mTempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
Jeff Brown98db5fa2011-06-08 15:37:10 -07001480 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT, BitSet32(0));
1481
1482 // Make a slippery entrance into the new window.
Jeff Browncc4f7db2011-08-30 20:34:48 -07001483 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Jeff Brown98db5fa2011-06-08 15:37:10 -07001484 isSplit = true;
1485 }
1486
1487 int32_t targetFlags = InputTarget::FLAG_FOREGROUND
1488 | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
1489 if (isSplit) {
1490 targetFlags |= InputTarget::FLAG_SPLIT;
1491 }
Jeff Brown9302c872011-07-13 22:51:29 -07001492 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
Jeff Brown98db5fa2011-06-08 15:37:10 -07001493 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1494 }
1495
1496 BitSet32 pointerIds;
1497 if (isSplit) {
1498 pointerIds.markBit(entry->pointerProperties[0].id);
1499 }
Jeff Brown9302c872011-07-13 22:51:29 -07001500 mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Jeff Brown98db5fa2011-06-08 15:37:10 -07001501
1502 // Split the batch here so we send exactly one sample.
1503 *outSplitBatchAfterSample = &entry->firstSample;
1504 }
1505 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001506 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001507
Jeff Brown9302c872011-07-13 22:51:29 -07001508 if (newHoverWindowHandle != mLastHoverWindowHandle) {
Jeff Browna032cc02011-03-07 16:56:21 -08001509 // Split the batch here so we send exactly one sample as part of ENTER or EXIT.
1510 *outSplitBatchAfterSample = &entry->firstSample;
1511
1512 // Let the previous window know that the hover sequence is over.
Jeff Brown9302c872011-07-13 22:51:29 -07001513 if (mLastHoverWindowHandle != NULL) {
Jeff Browna032cc02011-03-07 16:56:21 -08001514#if DEBUG_HOVER
Jeff Browncc4f7db2011-08-30 20:34:48 -07001515 LOGD("Sending hover exit event to window %s.",
1516 mLastHoverWindowHandle->getName().string());
Jeff Browna032cc02011-03-07 16:56:21 -08001517#endif
Jeff Brown9302c872011-07-13 22:51:29 -07001518 mTempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
Jeff Browna032cc02011-03-07 16:56:21 -08001519 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
1520 }
1521
1522 // Let the new window know that the hover sequence is starting.
Jeff Brown9302c872011-07-13 22:51:29 -07001523 if (newHoverWindowHandle != NULL) {
Jeff Browna032cc02011-03-07 16:56:21 -08001524#if DEBUG_HOVER
Jeff Browncc4f7db2011-08-30 20:34:48 -07001525 LOGD("Sending hover enter event to window %s.",
1526 newHoverWindowHandle->getName().string());
Jeff Browna032cc02011-03-07 16:56:21 -08001527#endif
Jeff Brown9302c872011-07-13 22:51:29 -07001528 mTempTouchState.addOrUpdateWindow(newHoverWindowHandle,
Jeff Browna032cc02011-03-07 16:56:21 -08001529 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER, BitSet32(0));
1530 }
1531 }
1532
Jeff Brown01ce2e92010-09-26 22:20:12 -07001533 // Check permission to inject into all touched foreground windows and ensure there
1534 // is at least one touched foreground window.
1535 {
1536 bool haveForegroundWindow = false;
1537 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1538 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1539 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1540 haveForegroundWindow = true;
Jeff Brown9302c872011-07-13 22:51:29 -07001541 if (! checkInjectionPermission(touchedWindow.windowHandle,
1542 entry->injectionState)) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001543 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1544 injectionPermission = INJECTION_PERMISSION_DENIED;
1545 goto Failed;
1546 }
1547 }
1548 }
1549 if (! haveForegroundWindow) {
Jeff Browna2cc28d2011-03-25 11:58:46 -07001550#if DEBUG_FOCUS
Jeff Brown01ce2e92010-09-26 22:20:12 -07001551 LOGD("Dropping event because there is no touched foreground window to receive it.");
Jeff Brownb88102f2010-09-08 11:49:43 -07001552#endif
1553 injectionResult = INPUT_EVENT_INJECTION_FAILED;
Jeff Brownb88102f2010-09-08 11:49:43 -07001554 goto Failed;
1555 }
1556
Jeff Brown01ce2e92010-09-26 22:20:12 -07001557 // Permission granted to injection into all touched foreground windows.
1558 injectionPermission = INJECTION_PERMISSION_GRANTED;
1559 }
Jeff Brown519e0242010-09-15 15:18:56 -07001560
Kenny Root7a9db182011-06-02 15:16:05 -07001561 // Check whether windows listening for outside touches are owned by the same UID. If it is
1562 // set the policy flag that we will not reveal coordinate information to this window.
1563 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
Jeff Brown9302c872011-07-13 22:51:29 -07001564 sp<InputWindowHandle> foregroundWindowHandle =
1565 mTempTouchState.getFirstForegroundWindowHandle();
Jeff Browncc4f7db2011-08-30 20:34:48 -07001566 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Kenny Root7a9db182011-06-02 15:16:05 -07001567 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1568 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1569 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
Jeff Brown9302c872011-07-13 22:51:29 -07001570 sp<InputWindowHandle> inputWindowHandle = touchedWindow.windowHandle;
Jeff Browncc4f7db2011-08-30 20:34:48 -07001571 if (inputWindowHandle->getInfo()->ownerUid != foregroundWindowUid) {
Jeff Brown9302c872011-07-13 22:51:29 -07001572 mTempTouchState.addOrUpdateWindow(inputWindowHandle,
Kenny Root7a9db182011-06-02 15:16:05 -07001573 InputTarget::FLAG_ZERO_COORDS, BitSet32(0));
1574 }
1575 }
1576 }
1577 }
1578
Jeff Brown01ce2e92010-09-26 22:20:12 -07001579 // Ensure all touched foreground windows are ready for new input.
1580 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1581 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1582 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1583 // If the touched window is paused then keep waiting.
Jeff Browncc4f7db2011-08-30 20:34:48 -07001584 if (touchedWindow.windowHandle->getInfo()->paused) {
Jeff Browna2cc28d2011-03-25 11:58:46 -07001585#if DEBUG_FOCUS
Jeff Brown01ce2e92010-09-26 22:20:12 -07001586 LOGD("Waiting because touched window is paused.");
Jeff Brown519e0242010-09-15 15:18:56 -07001587#endif
Jeff Brown01ce2e92010-09-26 22:20:12 -07001588 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brown9302c872011-07-13 22:51:29 -07001589 NULL, touchedWindow.windowHandle, nextWakeupTime);
Jeff Brown01ce2e92010-09-26 22:20:12 -07001590 goto Unresponsive;
1591 }
1592
1593 // If the touched window is still working on previous events then keep waiting.
Jeff Brown9302c872011-07-13 22:51:29 -07001594 if (! isWindowFinishedWithPreviousInputLocked(touchedWindow.windowHandle)) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001595#if DEBUG_FOCUS
1596 LOGD("Waiting because touched window still processing previous input.");
1597#endif
1598 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brown9302c872011-07-13 22:51:29 -07001599 NULL, touchedWindow.windowHandle, nextWakeupTime);
Jeff Brown01ce2e92010-09-26 22:20:12 -07001600 goto Unresponsive;
1601 }
1602 }
1603 }
1604
1605 // If this is the first pointer going down and the touched window has a wallpaper
1606 // then also add the touched wallpaper windows so they are locked in for the duration
1607 // of the touch gesture.
Jeff Brown33bbfd22011-02-24 20:55:35 -08001608 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
1609 // engine only supports touch events. We would need to add a mechanism similar
1610 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
1611 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
Jeff Brown9302c872011-07-13 22:51:29 -07001612 sp<InputWindowHandle> foregroundWindowHandle =
1613 mTempTouchState.getFirstForegroundWindowHandle();
Jeff Browncc4f7db2011-08-30 20:34:48 -07001614 if (foregroundWindowHandle->getInfo()->hasWallpaper) {
Jeff Brown9302c872011-07-13 22:51:29 -07001615 for (size_t i = 0; i < mWindowHandles.size(); i++) {
1616 sp<InputWindowHandle> windowHandle = mWindowHandles.itemAt(i);
Jeff Browncc4f7db2011-08-30 20:34:48 -07001617 if (windowHandle->getInfo()->layoutParamsType
1618 == InputWindowInfo::TYPE_WALLPAPER) {
Jeff Brown9302c872011-07-13 22:51:29 -07001619 mTempTouchState.addOrUpdateWindow(windowHandle,
Jeff Browna032cc02011-03-07 16:56:21 -08001620 InputTarget::FLAG_WINDOW_IS_OBSCURED
1621 | InputTarget::FLAG_DISPATCH_AS_IS,
1622 BitSet32(0));
Jeff Brown01ce2e92010-09-26 22:20:12 -07001623 }
1624 }
1625 }
1626 }
1627
Jeff Brownb88102f2010-09-08 11:49:43 -07001628 // Success! Output targets.
1629 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
Jeff Brownb88102f2010-09-08 11:49:43 -07001630
Jeff Brown01ce2e92010-09-26 22:20:12 -07001631 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1632 const TouchedWindow& touchedWindow = mTempTouchState.windows.itemAt(i);
Jeff Brown9302c872011-07-13 22:51:29 -07001633 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Jeff Brown01ce2e92010-09-26 22:20:12 -07001634 touchedWindow.pointerIds);
Jeff Brownb88102f2010-09-08 11:49:43 -07001635 }
1636
Jeff Browna032cc02011-03-07 16:56:21 -08001637 // Drop the outside or hover touch windows since we will not care about them
1638 // in the next iteration.
1639 mTempTouchState.filterNonAsIsTouchWindows();
Jeff Brown01ce2e92010-09-26 22:20:12 -07001640
Jeff Brownb88102f2010-09-08 11:49:43 -07001641Failed:
1642 // Check injection permission once and for all.
1643 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001644 if (checkInjectionPermission(NULL, entry->injectionState)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001645 injectionPermission = INJECTION_PERMISSION_GRANTED;
1646 } else {
1647 injectionPermission = INJECTION_PERMISSION_DENIED;
1648 }
1649 }
1650
1651 // Update final pieces of touch state if the injector had permission.
1652 if (injectionPermission == INJECTION_PERMISSION_GRANTED) {
Jeff Brown95712852011-01-04 19:41:59 -08001653 if (!wrongDevice) {
Jeff Brown81346812011-06-28 20:08:48 -07001654 if (switchedDevice) {
1655#if DEBUG_FOCUS
1656 LOGD("Conflicting pointer actions: Switched to a different device.");
1657#endif
1658 *outConflictingPointerActions = true;
1659 }
1660
1661 if (isHoverAction) {
1662 // Started hovering, therefore no longer down.
1663 if (mTouchState.down) {
1664#if DEBUG_FOCUS
1665 LOGD("Conflicting pointer actions: Hover received while pointer was down.");
1666#endif
1667 *outConflictingPointerActions = true;
1668 }
1669 mTouchState.reset();
1670 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER
1671 || maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
1672 mTouchState.deviceId = entry->deviceId;
1673 mTouchState.source = entry->source;
1674 }
1675 } else if (maskedAction == AMOTION_EVENT_ACTION_UP
1676 || maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Jeff Brown95712852011-01-04 19:41:59 -08001677 // All pointers up or canceled.
Jeff Brown33bbfd22011-02-24 20:55:35 -08001678 mTouchState.reset();
Jeff Brown95712852011-01-04 19:41:59 -08001679 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1680 // First pointer went down.
1681 if (mTouchState.down) {
Jeff Brownb6997262010-10-08 22:31:17 -07001682#if DEBUG_FOCUS
Jeff Brown81346812011-06-28 20:08:48 -07001683 LOGD("Conflicting pointer actions: Down received while already down.");
Jeff Brownb6997262010-10-08 22:31:17 -07001684#endif
Jeff Brown81346812011-06-28 20:08:48 -07001685 *outConflictingPointerActions = true;
Jeff Brown95712852011-01-04 19:41:59 -08001686 }
Jeff Brown33bbfd22011-02-24 20:55:35 -08001687 mTouchState.copyFrom(mTempTouchState);
Jeff Brown95712852011-01-04 19:41:59 -08001688 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
1689 // One pointer went up.
1690 if (isSplit) {
1691 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07001692 uint32_t pointerId = entry->pointerProperties[pointerIndex].id;
Jeff Brownb88102f2010-09-08 11:49:43 -07001693
Jeff Brown95712852011-01-04 19:41:59 -08001694 for (size_t i = 0; i < mTempTouchState.windows.size(); ) {
1695 TouchedWindow& touchedWindow = mTempTouchState.windows.editItemAt(i);
1696 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
1697 touchedWindow.pointerIds.clearBit(pointerId);
1698 if (touchedWindow.pointerIds.isEmpty()) {
1699 mTempTouchState.windows.removeAt(i);
1700 continue;
1701 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001702 }
Jeff Brown95712852011-01-04 19:41:59 -08001703 i += 1;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001704 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001705 }
Jeff Brown33bbfd22011-02-24 20:55:35 -08001706 mTouchState.copyFrom(mTempTouchState);
1707 } else if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
1708 // Discard temporary touch state since it was only valid for this action.
1709 } else {
1710 // Save changes to touch state as-is for all other actions.
1711 mTouchState.copyFrom(mTempTouchState);
Jeff Brownb88102f2010-09-08 11:49:43 -07001712 }
Jeff Browna032cc02011-03-07 16:56:21 -08001713
1714 // Update hover state.
Jeff Brown9302c872011-07-13 22:51:29 -07001715 mLastHoverWindowHandle = newHoverWindowHandle;
Jeff Brown95712852011-01-04 19:41:59 -08001716 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001717 } else {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001718#if DEBUG_FOCUS
1719 LOGD("Not updating touch focus because injection was denied.");
1720#endif
Jeff Brownb88102f2010-09-08 11:49:43 -07001721 }
1722
1723Unresponsive:
Jeff Brown120a4592010-10-27 18:43:51 -07001724 // Reset temporary touch state to ensure we release unnecessary references to input channels.
1725 mTempTouchState.reset();
1726
Jeff Brown519e0242010-09-15 15:18:56 -07001727 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
1728 updateDispatchStatisticsLocked(currentTime, entry,
1729 injectionResult, timeSpentWaitingForApplication);
Jeff Brownb88102f2010-09-08 11:49:43 -07001730#if DEBUG_FOCUS
Jeff Brown01ce2e92010-09-26 22:20:12 -07001731 LOGD("findTouchedWindow finished: injectionResult=%d, injectionPermission=%d, "
1732 "timeSpentWaitingForApplication=%0.1fms",
Jeff Brown519e0242010-09-15 15:18:56 -07001733 injectionResult, injectionPermission, timeSpentWaitingForApplication / 1000000.0);
Jeff Brownb88102f2010-09-08 11:49:43 -07001734#endif
1735 return injectionResult;
1736}
1737
Jeff Brown9302c872011-07-13 22:51:29 -07001738void InputDispatcher::addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
1739 int32_t targetFlags, BitSet32 pointerIds) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001740 mCurrentInputTargets.push();
1741
Jeff Browncc4f7db2011-08-30 20:34:48 -07001742 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Jeff Brownb88102f2010-09-08 11:49:43 -07001743 InputTarget& target = mCurrentInputTargets.editTop();
Jeff Browncc4f7db2011-08-30 20:34:48 -07001744 target.inputChannel = windowInfo->inputChannel;
Jeff Brownb88102f2010-09-08 11:49:43 -07001745 target.flags = targetFlags;
Jeff Browncc4f7db2011-08-30 20:34:48 -07001746 target.xOffset = - windowInfo->frameLeft;
1747 target.yOffset = - windowInfo->frameTop;
1748 target.scaleFactor = windowInfo->scaleFactor;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001749 target.pointerIds = pointerIds;
Jeff Brownb88102f2010-09-08 11:49:43 -07001750}
1751
1752void InputDispatcher::addMonitoringTargetsLocked() {
1753 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
1754 mCurrentInputTargets.push();
1755
1756 InputTarget& target = mCurrentInputTargets.editTop();
1757 target.inputChannel = mMonitoringChannels[i];
Jeff Brownb6110c22011-04-01 16:15:13 -07001758 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
Jeff Brownb88102f2010-09-08 11:49:43 -07001759 target.xOffset = 0;
1760 target.yOffset = 0;
Jeff Brownb6110c22011-04-01 16:15:13 -07001761 target.pointerIds.clear();
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001762 target.scaleFactor = 1.0f;
Jeff Brownb88102f2010-09-08 11:49:43 -07001763 }
1764}
1765
Jeff Brown9302c872011-07-13 22:51:29 -07001766bool InputDispatcher::checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
Jeff Brown01ce2e92010-09-26 22:20:12 -07001767 const InjectionState* injectionState) {
1768 if (injectionState
Jeff Browncc4f7db2011-08-30 20:34:48 -07001769 && (windowHandle == NULL
1770 || windowHandle->getInfo()->ownerUid != injectionState->injectorUid)
Jeff Brownb6997262010-10-08 22:31:17 -07001771 && !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Jeff Brown9302c872011-07-13 22:51:29 -07001772 if (windowHandle != NULL) {
1773 LOGW("Permission denied: injecting event from pid %d uid %d to window %s "
1774 "owned by uid %d",
Jeff Brownb6997262010-10-08 22:31:17 -07001775 injectionState->injectorPid, injectionState->injectorUid,
Jeff Browncc4f7db2011-08-30 20:34:48 -07001776 windowHandle->getName().string(),
1777 windowHandle->getInfo()->ownerUid);
Jeff Brownb6997262010-10-08 22:31:17 -07001778 } else {
1779 LOGW("Permission denied: injecting event from pid %d uid %d",
1780 injectionState->injectorPid, injectionState->injectorUid);
Jeff Brownb88102f2010-09-08 11:49:43 -07001781 }
Jeff Brownb6997262010-10-08 22:31:17 -07001782 return false;
Jeff Brownb88102f2010-09-08 11:49:43 -07001783 }
1784 return true;
1785}
1786
Jeff Brown19dfc832010-10-05 12:26:23 -07001787bool InputDispatcher::isWindowObscuredAtPointLocked(
Jeff Brown9302c872011-07-13 22:51:29 -07001788 const sp<InputWindowHandle>& windowHandle, int32_t x, int32_t y) const {
1789 size_t numWindows = mWindowHandles.size();
Jeff Brownb88102f2010-09-08 11:49:43 -07001790 for (size_t i = 0; i < numWindows; i++) {
Jeff Brown9302c872011-07-13 22:51:29 -07001791 sp<InputWindowHandle> otherHandle = mWindowHandles.itemAt(i);
1792 if (otherHandle == windowHandle) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001793 break;
1794 }
Jeff Browncc4f7db2011-08-30 20:34:48 -07001795
1796 const InputWindowInfo* otherInfo = otherHandle->getInfo();
1797 if (otherInfo->visible && ! otherInfo->isTrustedOverlay()
1798 && otherInfo->frameContainsPoint(x, y)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001799 return true;
1800 }
1801 }
1802 return false;
1803}
1804
Jeff Brown9302c872011-07-13 22:51:29 -07001805bool InputDispatcher::isWindowFinishedWithPreviousInputLocked(
1806 const sp<InputWindowHandle>& windowHandle) {
Jeff Browncc4f7db2011-08-30 20:34:48 -07001807 ssize_t connectionIndex = getConnectionIndexLocked(windowHandle->getInputChannel());
Jeff Brown519e0242010-09-15 15:18:56 -07001808 if (connectionIndex >= 0) {
1809 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
1810 return connection->outboundQueue.isEmpty();
1811 } else {
1812 return true;
1813 }
1814}
1815
Jeff Brown9302c872011-07-13 22:51:29 -07001816String8 InputDispatcher::getApplicationWindowLabelLocked(
1817 const sp<InputApplicationHandle>& applicationHandle,
1818 const sp<InputWindowHandle>& windowHandle) {
1819 if (applicationHandle != NULL) {
1820 if (windowHandle != NULL) {
Jeff Browncc4f7db2011-08-30 20:34:48 -07001821 String8 label(applicationHandle->getName());
Jeff Brown519e0242010-09-15 15:18:56 -07001822 label.append(" - ");
Jeff Browncc4f7db2011-08-30 20:34:48 -07001823 label.append(windowHandle->getName());
Jeff Brown519e0242010-09-15 15:18:56 -07001824 return label;
1825 } else {
Jeff Browncc4f7db2011-08-30 20:34:48 -07001826 return applicationHandle->getName();
Jeff Brown519e0242010-09-15 15:18:56 -07001827 }
Jeff Brown9302c872011-07-13 22:51:29 -07001828 } else if (windowHandle != NULL) {
Jeff Browncc4f7db2011-08-30 20:34:48 -07001829 return windowHandle->getName();
Jeff Brown519e0242010-09-15 15:18:56 -07001830 } else {
1831 return String8("<unknown application or window>");
1832 }
1833}
1834
Jeff Browne2fe69e2010-10-18 13:21:23 -07001835void InputDispatcher::pokeUserActivityLocked(const EventEntry* eventEntry) {
Jeff Brown56194eb2011-03-02 19:23:13 -08001836 int32_t eventType = POWER_MANAGER_OTHER_EVENT;
Jeff Brown4d396052010-10-29 21:50:21 -07001837 switch (eventEntry->type) {
1838 case EventEntry::TYPE_MOTION: {
Jeff Browne2fe69e2010-10-18 13:21:23 -07001839 const MotionEntry* motionEntry = static_cast<const MotionEntry*>(eventEntry);
Jeff Brown4d396052010-10-29 21:50:21 -07001840 if (motionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
1841 return;
1842 }
1843
Jeff Brown56194eb2011-03-02 19:23:13 -08001844 if (MotionEvent::isTouchEvent(motionEntry->source, motionEntry->action)) {
Joe Onorato1a542c72010-11-08 09:48:20 -08001845 eventType = POWER_MANAGER_TOUCH_EVENT;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001846 }
Jeff Brown4d396052010-10-29 21:50:21 -07001847 break;
1848 }
1849 case EventEntry::TYPE_KEY: {
1850 const KeyEntry* keyEntry = static_cast<const KeyEntry*>(eventEntry);
1851 if (keyEntry->flags & AKEY_EVENT_FLAG_CANCELED) {
1852 return;
1853 }
Jeff Brown56194eb2011-03-02 19:23:13 -08001854 eventType = POWER_MANAGER_BUTTON_EVENT;
Jeff Brown4d396052010-10-29 21:50:21 -07001855 break;
1856 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001857 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001858
Jeff Brownb88102f2010-09-08 11:49:43 -07001859 CommandEntry* commandEntry = postCommandLocked(
1860 & InputDispatcher::doPokeUserActivityLockedInterruptible);
Jeff Browne2fe69e2010-10-18 13:21:23 -07001861 commandEntry->eventTime = eventEntry->eventTime;
Jeff Brownb88102f2010-09-08 11:49:43 -07001862 commandEntry->userActivityEventType = eventType;
1863}
1864
Jeff Brown7fbdc842010-06-17 20:52:56 -07001865void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
1866 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget,
Jeff Brown46b9ac02010-04-22 18:58:52 -07001867 bool resumeWithAppendedMotionSample) {
1868#if DEBUG_DISPATCH_CYCLE
Jeff Brown9cc695c2011-08-23 18:35:04 -07001869 LOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
1870 "xOffset=%f, yOffset=%f, scaleFactor=%f, "
Jeff Brown83c09682010-12-23 17:50:18 -08001871 "pointerIds=0x%x, "
Jeff Brown01ce2e92010-09-26 22:20:12 -07001872 "resumeWithAppendedMotionSample=%s",
Jeff Brown519e0242010-09-15 15:18:56 -07001873 connection->getInputChannelName(), inputTarget->flags,
Jeff Brown46b9ac02010-04-22 18:58:52 -07001874 inputTarget->xOffset, inputTarget->yOffset,
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001875 inputTarget->scaleFactor, inputTarget->pointerIds.value,
Jeff Brownb88102f2010-09-08 11:49:43 -07001876 toString(resumeWithAppendedMotionSample));
Jeff Brown46b9ac02010-04-22 18:58:52 -07001877#endif
1878
Jeff Brown01ce2e92010-09-26 22:20:12 -07001879 // Make sure we are never called for streaming when splitting across multiple windows.
1880 bool isSplit = inputTarget->flags & InputTarget::FLAG_SPLIT;
Jeff Brownb6110c22011-04-01 16:15:13 -07001881 LOG_ASSERT(! (resumeWithAppendedMotionSample && isSplit));
Jeff Brown01ce2e92010-09-26 22:20:12 -07001882
Jeff Brown46b9ac02010-04-22 18:58:52 -07001883 // Skip this event if the connection status is not normal.
Jeff Brown519e0242010-09-15 15:18:56 -07001884 // We don't want to enqueue additional outbound events if the connection is broken.
Jeff Brown46b9ac02010-04-22 18:58:52 -07001885 if (connection->status != Connection::STATUS_NORMAL) {
Jeff Brownb6997262010-10-08 22:31:17 -07001886#if DEBUG_DISPATCH_CYCLE
1887 LOGD("channel '%s' ~ Dropping event because the channel status is %s",
Jeff Brownb88102f2010-09-08 11:49:43 -07001888 connection->getInputChannelName(), connection->getStatusLabel());
Jeff Brownb6997262010-10-08 22:31:17 -07001889#endif
Jeff Brown46b9ac02010-04-22 18:58:52 -07001890 return;
1891 }
1892
Jeff Brown01ce2e92010-09-26 22:20:12 -07001893 // Split a motion event if needed.
1894 if (isSplit) {
Jeff Brownb6110c22011-04-01 16:15:13 -07001895 LOG_ASSERT(eventEntry->type == EventEntry::TYPE_MOTION);
Jeff Brown01ce2e92010-09-26 22:20:12 -07001896
1897 MotionEntry* originalMotionEntry = static_cast<MotionEntry*>(eventEntry);
1898 if (inputTarget->pointerIds.count() != originalMotionEntry->pointerCount) {
1899 MotionEntry* splitMotionEntry = splitMotionEvent(
1900 originalMotionEntry, inputTarget->pointerIds);
Jeff Brown58a2da82011-01-25 16:02:22 -08001901 if (!splitMotionEntry) {
1902 return; // split event was dropped
1903 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001904#if DEBUG_FOCUS
1905 LOGD("channel '%s' ~ Split motion event.",
1906 connection->getInputChannelName());
1907 logOutboundMotionDetailsLocked(" ", splitMotionEntry);
1908#endif
1909 eventEntry = splitMotionEntry;
1910 }
1911 }
1912
Jeff Brown46b9ac02010-04-22 18:58:52 -07001913 // Resume the dispatch cycle with a freshly appended motion sample.
1914 // First we check that the last dispatch entry in the outbound queue is for the same
1915 // motion event to which we appended the motion sample. If we find such a dispatch
1916 // entry, and if it is currently in progress then we try to stream the new sample.
1917 bool wasEmpty = connection->outboundQueue.isEmpty();
1918
1919 if (! wasEmpty && resumeWithAppendedMotionSample) {
1920 DispatchEntry* motionEventDispatchEntry =
1921 connection->findQueuedDispatchEntryForEvent(eventEntry);
1922 if (motionEventDispatchEntry) {
1923 // If the dispatch entry is not in progress, then we must be busy dispatching an
1924 // earlier event. Not a problem, the motion event is on the outbound queue and will
1925 // be dispatched later.
1926 if (! motionEventDispatchEntry->inProgress) {
1927#if DEBUG_BATCHING
1928 LOGD("channel '%s' ~ Not streaming because the motion event has "
1929 "not yet been dispatched. "
1930 "(Waiting for earlier events to be consumed.)",
1931 connection->getInputChannelName());
1932#endif
1933 return;
1934 }
1935
1936 // If the dispatch entry is in progress but it already has a tail of pending
1937 // motion samples, then it must mean that the shared memory buffer filled up.
1938 // Not a problem, when this dispatch cycle is finished, we will eventually start
1939 // a new dispatch cycle to process the tail and that tail includes the newly
1940 // appended motion sample.
1941 if (motionEventDispatchEntry->tailMotionSample) {
1942#if DEBUG_BATCHING
1943 LOGD("channel '%s' ~ Not streaming because no new samples can "
1944 "be appended to the motion event in this dispatch cycle. "
1945 "(Waiting for next dispatch cycle to start.)",
1946 connection->getInputChannelName());
1947#endif
1948 return;
1949 }
1950
Jeff Brown81346812011-06-28 20:08:48 -07001951 // If the motion event was modified in flight, then we cannot stream the sample.
1952 if ((motionEventDispatchEntry->targetFlags & InputTarget::FLAG_DISPATCH_MASK)
1953 != InputTarget::FLAG_DISPATCH_AS_IS) {
1954#if DEBUG_BATCHING
1955 LOGD("channel '%s' ~ Not streaming because the motion event was not "
1956 "being dispatched as-is. "
1957 "(Waiting for next dispatch cycle to start.)",
1958 connection->getInputChannelName());
1959#endif
1960 return;
1961 }
1962
Jeff Brown46b9ac02010-04-22 18:58:52 -07001963 // The dispatch entry is in progress and is still potentially open for streaming.
1964 // Try to stream the new motion sample. This might fail if the consumer has already
1965 // consumed the motion event (or if the channel is broken).
Jeff Brown01ce2e92010-09-26 22:20:12 -07001966 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
1967 MotionSample* appendedMotionSample = motionEntry->lastSample;
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001968 status_t status;
1969 if (motionEventDispatchEntry->scaleFactor == 1.0f) {
1970 status = connection->inputPublisher.appendMotionSample(
1971 appendedMotionSample->eventTime, appendedMotionSample->pointerCoords);
1972 } else {
1973 PointerCoords scaledCoords[MAX_POINTERS];
1974 for (size_t i = 0; i < motionEntry->pointerCount; i++) {
1975 scaledCoords[i] = appendedMotionSample->pointerCoords[i];
1976 scaledCoords[i].scale(motionEventDispatchEntry->scaleFactor);
1977 }
1978 status = connection->inputPublisher.appendMotionSample(
1979 appendedMotionSample->eventTime, scaledCoords);
1980 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07001981 if (status == OK) {
1982#if DEBUG_BATCHING
1983 LOGD("channel '%s' ~ Successfully streamed new motion sample.",
1984 connection->getInputChannelName());
1985#endif
1986 return;
1987 }
1988
1989#if DEBUG_BATCHING
1990 if (status == NO_MEMORY) {
1991 LOGD("channel '%s' ~ Could not append motion sample to currently "
1992 "dispatched move event because the shared memory buffer is full. "
1993 "(Waiting for next dispatch cycle to start.)",
1994 connection->getInputChannelName());
1995 } else if (status == status_t(FAILED_TRANSACTION)) {
1996 LOGD("channel '%s' ~ Could not append motion sample to currently "
Jeff Brown349703e2010-06-22 01:27:15 -07001997 "dispatched move event because the event has already been consumed. "
Jeff Brown46b9ac02010-04-22 18:58:52 -07001998 "(Waiting for next dispatch cycle to start.)",
1999 connection->getInputChannelName());
2000 } else {
2001 LOGD("channel '%s' ~ Could not append motion sample to currently "
2002 "dispatched move event due to an error, status=%d. "
2003 "(Waiting for next dispatch cycle to start.)",
2004 connection->getInputChannelName(), status);
2005 }
2006#endif
2007 // Failed to stream. Start a new tail of pending motion samples to dispatch
2008 // in the next cycle.
2009 motionEventDispatchEntry->tailMotionSample = appendedMotionSample;
2010 return;
2011 }
2012 }
2013
Jeff Browna032cc02011-03-07 16:56:21 -08002014 // Enqueue dispatch entries for the requested modes.
2015 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
2016 resumeWithAppendedMotionSample, InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
2017 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
2018 resumeWithAppendedMotionSample, InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
2019 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
2020 resumeWithAppendedMotionSample, InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
2021 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
2022 resumeWithAppendedMotionSample, InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brown98db5fa2011-06-08 15:37:10 -07002023 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
2024 resumeWithAppendedMotionSample, InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
2025 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
2026 resumeWithAppendedMotionSample, InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Jeff Browna032cc02011-03-07 16:56:21 -08002027
2028 // If the outbound queue was previously empty, start the dispatch cycle going.
Jeff Brownb6110c22011-04-01 16:15:13 -07002029 if (wasEmpty && !connection->outboundQueue.isEmpty()) {
Jeff Browna032cc02011-03-07 16:56:21 -08002030 activateConnectionLocked(connection.get());
2031 startDispatchCycleLocked(currentTime, connection);
2032 }
2033}
2034
2035void InputDispatcher::enqueueDispatchEntryLocked(
2036 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget,
2037 bool resumeWithAppendedMotionSample, int32_t dispatchMode) {
2038 int32_t inputTargetFlags = inputTarget->flags;
2039 if (!(inputTargetFlags & dispatchMode)) {
2040 return;
2041 }
2042 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
2043
Jeff Brown46b9ac02010-04-22 18:58:52 -07002044 // This is a new event.
2045 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Jeff Brownac386072011-07-20 15:19:50 -07002046 DispatchEntry* dispatchEntry = new DispatchEntry(eventEntry, // increments ref
Dianne Hackbornaa9d84c2011-05-09 19:00:59 -07002047 inputTargetFlags, inputTarget->xOffset, inputTarget->yOffset,
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002048 inputTarget->scaleFactor);
Jeff Brown519e0242010-09-15 15:18:56 -07002049 if (dispatchEntry->hasForegroundTarget()) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002050 incrementPendingForegroundDispatchesLocked(eventEntry);
Jeff Brown6ec402b2010-07-28 15:48:59 -07002051 }
2052
Jeff Brown46b9ac02010-04-22 18:58:52 -07002053 // Handle the case where we could not stream a new motion sample because the consumer has
2054 // already consumed the motion event (otherwise the corresponding dispatch entry would
2055 // still be in the outbound queue for this connection). We set the head motion sample
2056 // to the list starting with the newly appended motion sample.
2057 if (resumeWithAppendedMotionSample) {
2058#if DEBUG_BATCHING
2059 LOGD("channel '%s' ~ Preparing a new dispatch cycle for additional motion samples "
2060 "that cannot be streamed because the motion event has already been consumed.",
2061 connection->getInputChannelName());
2062#endif
2063 MotionSample* appendedMotionSample = static_cast<MotionEntry*>(eventEntry)->lastSample;
2064 dispatchEntry->headMotionSample = appendedMotionSample;
2065 }
2066
Jeff Brown81346812011-06-28 20:08:48 -07002067 // Apply target flags and update the connection's input state.
2068 switch (eventEntry->type) {
2069 case EventEntry::TYPE_KEY: {
2070 KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
2071 dispatchEntry->resolvedAction = keyEntry->action;
2072 dispatchEntry->resolvedFlags = keyEntry->flags;
2073
2074 if (!connection->inputState.trackKey(keyEntry,
2075 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags)) {
2076#if DEBUG_DISPATCH_CYCLE
2077 LOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
2078 connection->getInputChannelName());
2079#endif
2080 return; // skip the inconsistent event
2081 }
2082 break;
2083 }
2084
2085 case EventEntry::TYPE_MOTION: {
2086 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
2087 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2088 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
2089 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
2090 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
2091 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
2092 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2093 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
2094 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
2095 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
2096 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
2097 } else {
2098 dispatchEntry->resolvedAction = motionEntry->action;
2099 }
2100 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE
2101 && !connection->inputState.isHovering(
2102 motionEntry->deviceId, motionEntry->source)) {
2103#if DEBUG_DISPATCH_CYCLE
2104 LOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter event",
2105 connection->getInputChannelName());
2106#endif
2107 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2108 }
2109
2110 dispatchEntry->resolvedFlags = motionEntry->flags;
2111 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
2112 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
2113 }
2114
2115 if (!connection->inputState.trackMotion(motionEntry,
2116 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags)) {
2117#if DEBUG_DISPATCH_CYCLE
2118 LOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion event",
2119 connection->getInputChannelName());
2120#endif
2121 return; // skip the inconsistent event
2122 }
2123 break;
2124 }
2125 }
2126
Jeff Brown46b9ac02010-04-22 18:58:52 -07002127 // Enqueue the dispatch entry.
2128 connection->outboundQueue.enqueueAtTail(dispatchEntry);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002129}
2130
Jeff Brown7fbdc842010-06-17 20:52:56 -07002131void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Jeff Brown519e0242010-09-15 15:18:56 -07002132 const sp<Connection>& connection) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002133#if DEBUG_DISPATCH_CYCLE
2134 LOGD("channel '%s' ~ startDispatchCycle",
2135 connection->getInputChannelName());
2136#endif
2137
Jeff Brownb6110c22011-04-01 16:15:13 -07002138 LOG_ASSERT(connection->status == Connection::STATUS_NORMAL);
2139 LOG_ASSERT(! connection->outboundQueue.isEmpty());
Jeff Brown46b9ac02010-04-22 18:58:52 -07002140
Jeff Brownac386072011-07-20 15:19:50 -07002141 DispatchEntry* dispatchEntry = connection->outboundQueue.head;
Jeff Brownb6110c22011-04-01 16:15:13 -07002142 LOG_ASSERT(! dispatchEntry->inProgress);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002143
Jeff Brownb88102f2010-09-08 11:49:43 -07002144 // Mark the dispatch entry as in progress.
2145 dispatchEntry->inProgress = true;
2146
Jeff Brown46b9ac02010-04-22 18:58:52 -07002147 // Publish the event.
2148 status_t status;
Jeff Browna032cc02011-03-07 16:56:21 -08002149 EventEntry* eventEntry = dispatchEntry->eventEntry;
Jeff Brown01ce2e92010-09-26 22:20:12 -07002150 switch (eventEntry->type) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002151 case EventEntry::TYPE_KEY: {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002152 KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002153
Jeff Brown46b9ac02010-04-22 18:58:52 -07002154 // Publish the key event.
Jeff Brown81346812011-06-28 20:08:48 -07002155 status = connection->inputPublisher.publishKeyEvent(
2156 keyEntry->deviceId, keyEntry->source,
2157 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags,
2158 keyEntry->keyCode, keyEntry->scanCode,
Jeff Brown46b9ac02010-04-22 18:58:52 -07002159 keyEntry->metaState, keyEntry->repeatCount, keyEntry->downTime,
2160 keyEntry->eventTime);
2161
2162 if (status) {
2163 LOGE("channel '%s' ~ Could not publish key event, "
2164 "status=%d", connection->getInputChannelName(), status);
Jeff Browncc4f7db2011-08-30 20:34:48 -07002165 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002166 return;
2167 }
2168 break;
2169 }
2170
2171 case EventEntry::TYPE_MOTION: {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002172 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002173
Jeff Brown46b9ac02010-04-22 18:58:52 -07002174 // If headMotionSample is non-NULL, then it points to the first new sample that we
2175 // were unable to dispatch during the previous cycle so we resume dispatching from
2176 // that point in the list of motion samples.
2177 // Otherwise, we just start from the first sample of the motion event.
2178 MotionSample* firstMotionSample = dispatchEntry->headMotionSample;
2179 if (! firstMotionSample) {
2180 firstMotionSample = & motionEntry->firstSample;
2181 }
2182
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002183 PointerCoords scaledCoords[MAX_POINTERS];
2184 const PointerCoords* usingCoords = firstMotionSample->pointerCoords;
2185
Jeff Brownd3616592010-07-16 17:21:06 -07002186 // Set the X and Y offset depending on the input source.
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002187 float xOffset, yOffset, scaleFactor;
Kenny Root7a9db182011-06-02 15:16:05 -07002188 if (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER
2189 && !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002190 scaleFactor = dispatchEntry->scaleFactor;
2191 xOffset = dispatchEntry->xOffset * scaleFactor;
2192 yOffset = dispatchEntry->yOffset * scaleFactor;
2193 if (scaleFactor != 1.0f) {
2194 for (size_t i = 0; i < motionEntry->pointerCount; i++) {
2195 scaledCoords[i] = firstMotionSample->pointerCoords[i];
2196 scaledCoords[i].scale(scaleFactor);
2197 }
2198 usingCoords = scaledCoords;
2199 }
Jeff Brownd3616592010-07-16 17:21:06 -07002200 } else {
2201 xOffset = 0.0f;
2202 yOffset = 0.0f;
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002203 scaleFactor = 1.0f;
Kenny Root7a9db182011-06-02 15:16:05 -07002204
2205 // We don't want the dispatch target to know.
2206 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
2207 for (size_t i = 0; i < motionEntry->pointerCount; i++) {
2208 scaledCoords[i].clear();
2209 }
2210 usingCoords = scaledCoords;
2211 }
Jeff Brownd3616592010-07-16 17:21:06 -07002212 }
2213
Jeff Brown46b9ac02010-04-22 18:58:52 -07002214 // Publish the motion event and the first motion sample.
Jeff Brown81346812011-06-28 20:08:48 -07002215 status = connection->inputPublisher.publishMotionEvent(
2216 motionEntry->deviceId, motionEntry->source,
2217 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags,
2218 motionEntry->edgeFlags, motionEntry->metaState, motionEntry->buttonState,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002219 xOffset, yOffset,
2220 motionEntry->xPrecision, motionEntry->yPrecision,
Jeff Brown46b9ac02010-04-22 18:58:52 -07002221 motionEntry->downTime, firstMotionSample->eventTime,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002222 motionEntry->pointerCount, motionEntry->pointerProperties,
2223 usingCoords);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002224
2225 if (status) {
2226 LOGE("channel '%s' ~ Could not publish motion event, "
2227 "status=%d", connection->getInputChannelName(), status);
Jeff Browncc4f7db2011-08-30 20:34:48 -07002228 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002229 return;
2230 }
2231
Jeff Brown81346812011-06-28 20:08:48 -07002232 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_MOVE
2233 || dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Jeff Browna032cc02011-03-07 16:56:21 -08002234 // Append additional motion samples.
2235 MotionSample* nextMotionSample = firstMotionSample->next;
2236 for (; nextMotionSample != NULL; nextMotionSample = nextMotionSample->next) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002237 if (usingCoords == scaledCoords) {
Kenny Root7a9db182011-06-02 15:16:05 -07002238 if (!(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
2239 for (size_t i = 0; i < motionEntry->pointerCount; i++) {
2240 scaledCoords[i] = nextMotionSample->pointerCoords[i];
2241 scaledCoords[i].scale(scaleFactor);
2242 }
Dianne Hackborn2ba3e802011-05-11 10:59:54 -07002243 }
2244 } else {
2245 usingCoords = nextMotionSample->pointerCoords;
Dianne Hackborne7d25b72011-05-09 21:19:26 -07002246 }
Jeff Browna032cc02011-03-07 16:56:21 -08002247 status = connection->inputPublisher.appendMotionSample(
Dianne Hackbornaa9d84c2011-05-09 19:00:59 -07002248 nextMotionSample->eventTime, usingCoords);
Jeff Browna032cc02011-03-07 16:56:21 -08002249 if (status == NO_MEMORY) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002250#if DEBUG_DISPATCH_CYCLE
2251 LOGD("channel '%s' ~ Shared memory buffer full. Some motion samples will "
2252 "be sent in the next dispatch cycle.",
2253 connection->getInputChannelName());
2254#endif
Jeff Browna032cc02011-03-07 16:56:21 -08002255 break;
2256 }
2257 if (status != OK) {
2258 LOGE("channel '%s' ~ Could not append motion sample "
2259 "for a reason other than out of memory, status=%d",
2260 connection->getInputChannelName(), status);
Jeff Browncc4f7db2011-08-30 20:34:48 -07002261 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
Jeff Browna032cc02011-03-07 16:56:21 -08002262 return;
2263 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002264 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002265
Jeff Browna032cc02011-03-07 16:56:21 -08002266 // Remember the next motion sample that we could not dispatch, in case we ran out
2267 // of space in the shared memory buffer.
2268 dispatchEntry->tailMotionSample = nextMotionSample;
2269 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002270 break;
2271 }
2272
2273 default: {
Jeff Brownb6110c22011-04-01 16:15:13 -07002274 LOG_ASSERT(false);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002275 }
2276 }
2277
2278 // Send the dispatch signal.
2279 status = connection->inputPublisher.sendDispatchSignal();
2280 if (status) {
2281 LOGE("channel '%s' ~ Could not send dispatch signal, status=%d",
2282 connection->getInputChannelName(), status);
Jeff Browncc4f7db2011-08-30 20:34:48 -07002283 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002284 return;
2285 }
2286
2287 // Record information about the newly started dispatch cycle.
Jeff Brown01ce2e92010-09-26 22:20:12 -07002288 connection->lastEventTime = eventEntry->eventTime;
Jeff Brown46b9ac02010-04-22 18:58:52 -07002289 connection->lastDispatchTime = currentTime;
2290
Jeff Brown46b9ac02010-04-22 18:58:52 -07002291 // Notify other system components.
2292 onDispatchCycleStartedLocked(currentTime, connection);
2293}
2294
Jeff Brown7fbdc842010-06-17 20:52:56 -07002295void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Jeff Brown3915bb82010-11-05 15:02:16 -07002296 const sp<Connection>& connection, bool handled) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002297#if DEBUG_DISPATCH_CYCLE
Jeff Brown9c3cda02010-06-15 01:31:58 -07002298 LOGD("channel '%s' ~ finishDispatchCycle - %01.1fms since event, "
Jeff Brown3915bb82010-11-05 15:02:16 -07002299 "%01.1fms since dispatch, handled=%s",
Jeff Brown46b9ac02010-04-22 18:58:52 -07002300 connection->getInputChannelName(),
2301 connection->getEventLatencyMillis(currentTime),
Jeff Brown3915bb82010-11-05 15:02:16 -07002302 connection->getDispatchLatencyMillis(currentTime),
2303 toString(handled));
Jeff Brown46b9ac02010-04-22 18:58:52 -07002304#endif
2305
Jeff Brown9c3cda02010-06-15 01:31:58 -07002306 if (connection->status == Connection::STATUS_BROKEN
2307 || connection->status == Connection::STATUS_ZOMBIE) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002308 return;
2309 }
2310
Jeff Brown46b9ac02010-04-22 18:58:52 -07002311 // Reset the publisher since the event has been consumed.
2312 // We do this now so that the publisher can release some of its internal resources
2313 // while waiting for the next dispatch cycle to begin.
2314 status_t status = connection->inputPublisher.reset();
2315 if (status) {
2316 LOGE("channel '%s' ~ Could not reset publisher, status=%d",
2317 connection->getInputChannelName(), status);
Jeff Browncc4f7db2011-08-30 20:34:48 -07002318 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002319 return;
2320 }
2321
Jeff Brown3915bb82010-11-05 15:02:16 -07002322 // Notify other system components and prepare to start the next dispatch cycle.
2323 onDispatchCycleFinishedLocked(currentTime, connection, handled);
Jeff Brownb88102f2010-09-08 11:49:43 -07002324}
2325
2326void InputDispatcher::startNextDispatchCycleLocked(nsecs_t currentTime,
2327 const sp<Connection>& connection) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002328 // Start the next dispatch cycle for this connection.
2329 while (! connection->outboundQueue.isEmpty()) {
Jeff Brownac386072011-07-20 15:19:50 -07002330 DispatchEntry* dispatchEntry = connection->outboundQueue.head;
Jeff Brown46b9ac02010-04-22 18:58:52 -07002331 if (dispatchEntry->inProgress) {
2332 // Finish or resume current event in progress.
2333 if (dispatchEntry->tailMotionSample) {
2334 // We have a tail of undispatched motion samples.
2335 // Reuse the same DispatchEntry and start a new cycle.
2336 dispatchEntry->inProgress = false;
2337 dispatchEntry->headMotionSample = dispatchEntry->tailMotionSample;
2338 dispatchEntry->tailMotionSample = NULL;
Jeff Brown519e0242010-09-15 15:18:56 -07002339 startDispatchCycleLocked(currentTime, connection);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002340 return;
2341 }
2342 // Finished.
2343 connection->outboundQueue.dequeueAtHead();
Jeff Brown519e0242010-09-15 15:18:56 -07002344 if (dispatchEntry->hasForegroundTarget()) {
2345 decrementPendingForegroundDispatchesLocked(dispatchEntry->eventEntry);
Jeff Brown6ec402b2010-07-28 15:48:59 -07002346 }
Jeff Brownac386072011-07-20 15:19:50 -07002347 delete dispatchEntry;
Jeff Brown46b9ac02010-04-22 18:58:52 -07002348 } else {
2349 // If the head is not in progress, then we must have already dequeued the in
Jeff Brown519e0242010-09-15 15:18:56 -07002350 // progress event, which means we actually aborted it.
Jeff Brown46b9ac02010-04-22 18:58:52 -07002351 // So just start the next event for this connection.
Jeff Brown519e0242010-09-15 15:18:56 -07002352 startDispatchCycleLocked(currentTime, connection);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002353 return;
2354 }
2355 }
2356
2357 // Outbound queue is empty, deactivate the connection.
Jeff Brown7fbdc842010-06-17 20:52:56 -07002358 deactivateConnectionLocked(connection.get());
Jeff Brown46b9ac02010-04-22 18:58:52 -07002359}
2360
Jeff Brownb6997262010-10-08 22:31:17 -07002361void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Jeff Browncc4f7db2011-08-30 20:34:48 -07002362 const sp<Connection>& connection, bool notify) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002363#if DEBUG_DISPATCH_CYCLE
Jeff Browncc4f7db2011-08-30 20:34:48 -07002364 LOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
2365 connection->getInputChannelName(), toString(notify));
Jeff Brown46b9ac02010-04-22 18:58:52 -07002366#endif
2367
Jeff Brownb88102f2010-09-08 11:49:43 -07002368 // Clear the outbound queue.
Jeff Brown519e0242010-09-15 15:18:56 -07002369 drainOutboundQueueLocked(connection.get());
Jeff Brown46b9ac02010-04-22 18:58:52 -07002370
Jeff Brownb6997262010-10-08 22:31:17 -07002371 // The connection appears to be unrecoverably broken.
Jeff Brown9c3cda02010-06-15 01:31:58 -07002372 // Ignore already broken or zombie connections.
Jeff Brownb6997262010-10-08 22:31:17 -07002373 if (connection->status == Connection::STATUS_NORMAL) {
2374 connection->status = Connection::STATUS_BROKEN;
Jeff Brown46b9ac02010-04-22 18:58:52 -07002375
Jeff Browncc4f7db2011-08-30 20:34:48 -07002376 if (notify) {
2377 // Notify other system components.
2378 onDispatchCycleBrokenLocked(currentTime, connection);
2379 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002380 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002381}
2382
Jeff Brown519e0242010-09-15 15:18:56 -07002383void InputDispatcher::drainOutboundQueueLocked(Connection* connection) {
2384 while (! connection->outboundQueue.isEmpty()) {
2385 DispatchEntry* dispatchEntry = connection->outboundQueue.dequeueAtHead();
2386 if (dispatchEntry->hasForegroundTarget()) {
2387 decrementPendingForegroundDispatchesLocked(dispatchEntry->eventEntry);
Jeff Brownb88102f2010-09-08 11:49:43 -07002388 }
Jeff Brownac386072011-07-20 15:19:50 -07002389 delete dispatchEntry;
Jeff Brownb88102f2010-09-08 11:49:43 -07002390 }
2391
Jeff Brown519e0242010-09-15 15:18:56 -07002392 deactivateConnectionLocked(connection);
Jeff Brownb88102f2010-09-08 11:49:43 -07002393}
2394
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002395int InputDispatcher::handleReceiveCallback(int receiveFd, int events, void* data) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002396 InputDispatcher* d = static_cast<InputDispatcher*>(data);
2397
2398 { // acquire lock
2399 AutoMutex _l(d->mLock);
2400
2401 ssize_t connectionIndex = d->mConnectionsByReceiveFd.indexOfKey(receiveFd);
2402 if (connectionIndex < 0) {
2403 LOGE("Received spurious receive callback for unknown input channel. "
2404 "fd=%d, events=0x%x", receiveFd, events);
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002405 return 0; // remove the callback
Jeff Brown46b9ac02010-04-22 18:58:52 -07002406 }
2407
Jeff Browncc4f7db2011-08-30 20:34:48 -07002408 bool notify;
Jeff Brown46b9ac02010-04-22 18:58:52 -07002409 sp<Connection> connection = d->mConnectionsByReceiveFd.valueAt(connectionIndex);
Jeff Browncc4f7db2011-08-30 20:34:48 -07002410 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
2411 if (!(events & ALOOPER_EVENT_INPUT)) {
2412 LOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
2413 "events=0x%x", connection->getInputChannelName(), events);
2414 return 1;
2415 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002416
Jeff Browncc4f7db2011-08-30 20:34:48 -07002417 bool handled = false;
2418 status_t status = connection->inputPublisher.receiveFinishedSignal(&handled);
2419 if (!status) {
2420 nsecs_t currentTime = now();
2421 d->finishDispatchCycleLocked(currentTime, connection, handled);
2422 d->runCommandsLockedInterruptible();
2423 return 1;
2424 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002425
Jeff Brown46b9ac02010-04-22 18:58:52 -07002426 LOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
2427 connection->getInputChannelName(), status);
Jeff Browncc4f7db2011-08-30 20:34:48 -07002428 notify = true;
2429 } else {
2430 // Monitor channels are never explicitly unregistered.
2431 // We do it automatically when the remote endpoint is closed so don't warn
2432 // about them.
2433 notify = !connection->monitor;
2434 if (notify) {
2435 LOGW("channel '%s' ~ Consumer closed input channel or an error occurred. "
2436 "events=0x%x", connection->getInputChannelName(), events);
2437 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002438 }
2439
Jeff Browncc4f7db2011-08-30 20:34:48 -07002440 // Unregister the channel.
2441 d->unregisterInputChannelLocked(connection->inputChannel, notify);
2442 return 0; // remove the callback
Jeff Brown46b9ac02010-04-22 18:58:52 -07002443 } // release lock
2444}
2445
Jeff Brownb6997262010-10-08 22:31:17 -07002446void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Jeff Brownda3d5a92011-03-29 15:11:34 -07002447 const CancelationOptions& options) {
Jeff Brownb6997262010-10-08 22:31:17 -07002448 for (size_t i = 0; i < mConnectionsByReceiveFd.size(); i++) {
2449 synthesizeCancelationEventsForConnectionLocked(
Jeff Brownda3d5a92011-03-29 15:11:34 -07002450 mConnectionsByReceiveFd.valueAt(i), options);
Jeff Brownb6997262010-10-08 22:31:17 -07002451 }
2452}
2453
2454void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Jeff Brownda3d5a92011-03-29 15:11:34 -07002455 const sp<InputChannel>& channel, const CancelationOptions& options) {
Jeff Brownb6997262010-10-08 22:31:17 -07002456 ssize_t index = getConnectionIndexLocked(channel);
2457 if (index >= 0) {
2458 synthesizeCancelationEventsForConnectionLocked(
Jeff Brownda3d5a92011-03-29 15:11:34 -07002459 mConnectionsByReceiveFd.valueAt(index), options);
Jeff Brownb6997262010-10-08 22:31:17 -07002460 }
2461}
2462
2463void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
Jeff Brownda3d5a92011-03-29 15:11:34 -07002464 const sp<Connection>& connection, const CancelationOptions& options) {
Jeff Brownb6997262010-10-08 22:31:17 -07002465 nsecs_t currentTime = now();
2466
2467 mTempCancelationEvents.clear();
Jeff Brownac386072011-07-20 15:19:50 -07002468 connection->inputState.synthesizeCancelationEvents(currentTime,
Jeff Brownb6997262010-10-08 22:31:17 -07002469 mTempCancelationEvents, options);
2470
2471 if (! mTempCancelationEvents.isEmpty()
2472 && connection->status != Connection::STATUS_BROKEN) {
2473#if DEBUG_OUTBOUND_EVENT_DETAILS
2474 LOGD("channel '%s' ~ Synthesized %d cancelation events to bring channel back in sync "
Jeff Brownda3d5a92011-03-29 15:11:34 -07002475 "with reality: %s, mode=%d.",
2476 connection->getInputChannelName(), mTempCancelationEvents.size(),
2477 options.reason, options.mode);
Jeff Brownb6997262010-10-08 22:31:17 -07002478#endif
2479 for (size_t i = 0; i < mTempCancelationEvents.size(); i++) {
2480 EventEntry* cancelationEventEntry = mTempCancelationEvents.itemAt(i);
2481 switch (cancelationEventEntry->type) {
2482 case EventEntry::TYPE_KEY:
2483 logOutboundKeyDetailsLocked("cancel - ",
2484 static_cast<KeyEntry*>(cancelationEventEntry));
2485 break;
2486 case EventEntry::TYPE_MOTION:
2487 logOutboundMotionDetailsLocked("cancel - ",
2488 static_cast<MotionEntry*>(cancelationEventEntry));
2489 break;
2490 }
2491
Jeff Brown81346812011-06-28 20:08:48 -07002492 InputTarget target;
Jeff Brown9302c872011-07-13 22:51:29 -07002493 sp<InputWindowHandle> windowHandle = getWindowHandleLocked(connection->inputChannel);
2494 if (windowHandle != NULL) {
Jeff Browncc4f7db2011-08-30 20:34:48 -07002495 const InputWindowInfo* windowInfo = windowHandle->getInfo();
2496 target.xOffset = -windowInfo->frameLeft;
2497 target.yOffset = -windowInfo->frameTop;
2498 target.scaleFactor = windowInfo->scaleFactor;
Jeff Brownb6997262010-10-08 22:31:17 -07002499 } else {
Jeff Brown81346812011-06-28 20:08:48 -07002500 target.xOffset = 0;
2501 target.yOffset = 0;
2502 target.scaleFactor = 1.0f;
Jeff Brownb6997262010-10-08 22:31:17 -07002503 }
Jeff Brown81346812011-06-28 20:08:48 -07002504 target.inputChannel = connection->inputChannel;
2505 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
Jeff Brownb6997262010-10-08 22:31:17 -07002506
Jeff Brown81346812011-06-28 20:08:48 -07002507 enqueueDispatchEntryLocked(connection, cancelationEventEntry, // increments ref
2508 &target, false, InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brownb6997262010-10-08 22:31:17 -07002509
Jeff Brownac386072011-07-20 15:19:50 -07002510 cancelationEventEntry->release();
Jeff Brownb6997262010-10-08 22:31:17 -07002511 }
2512
Jeff Brownac386072011-07-20 15:19:50 -07002513 if (!connection->outboundQueue.head->inProgress) {
Jeff Brownb6997262010-10-08 22:31:17 -07002514 startDispatchCycleLocked(currentTime, connection);
2515 }
2516 }
2517}
2518
Jeff Brown01ce2e92010-09-26 22:20:12 -07002519InputDispatcher::MotionEntry*
2520InputDispatcher::splitMotionEvent(const MotionEntry* originalMotionEntry, BitSet32 pointerIds) {
Jeff Brownb6110c22011-04-01 16:15:13 -07002521 LOG_ASSERT(pointerIds.value != 0);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002522
2523 uint32_t splitPointerIndexMap[MAX_POINTERS];
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002524 PointerProperties splitPointerProperties[MAX_POINTERS];
Jeff Brown01ce2e92010-09-26 22:20:12 -07002525 PointerCoords splitPointerCoords[MAX_POINTERS];
2526
2527 uint32_t originalPointerCount = originalMotionEntry->pointerCount;
2528 uint32_t splitPointerCount = 0;
2529
2530 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
2531 originalPointerIndex++) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002532 const PointerProperties& pointerProperties =
2533 originalMotionEntry->pointerProperties[originalPointerIndex];
2534 uint32_t pointerId = uint32_t(pointerProperties.id);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002535 if (pointerIds.hasBit(pointerId)) {
2536 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002537 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
Jeff Brownace13b12011-03-09 17:39:48 -08002538 splitPointerCoords[splitPointerCount].copyFrom(
2539 originalMotionEntry->firstSample.pointerCoords[originalPointerIndex]);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002540 splitPointerCount += 1;
2541 }
2542 }
Jeff Brown58a2da82011-01-25 16:02:22 -08002543
2544 if (splitPointerCount != pointerIds.count()) {
2545 // This is bad. We are missing some of the pointers that we expected to deliver.
2546 // Most likely this indicates that we received an ACTION_MOVE events that has
2547 // different pointer ids than we expected based on the previous ACTION_DOWN
2548 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
2549 // in this way.
2550 LOGW("Dropping split motion event because the pointer count is %d but "
2551 "we expected there to be %d pointers. This probably means we received "
2552 "a broken sequence of pointer ids from the input device.",
2553 splitPointerCount, pointerIds.count());
2554 return NULL;
2555 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07002556
2557 int32_t action = originalMotionEntry->action;
2558 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
2559 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
2560 || maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2561 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002562 const PointerProperties& pointerProperties =
2563 originalMotionEntry->pointerProperties[originalPointerIndex];
2564 uint32_t pointerId = uint32_t(pointerProperties.id);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002565 if (pointerIds.hasBit(pointerId)) {
2566 if (pointerIds.count() == 1) {
2567 // The first/last pointer went down/up.
2568 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
2569 ? AMOTION_EVENT_ACTION_DOWN : AMOTION_EVENT_ACTION_UP;
Jeff Brown9a01d052010-09-27 16:35:11 -07002570 } else {
2571 // A secondary pointer went down/up.
2572 uint32_t splitPointerIndex = 0;
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002573 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
Jeff Brown9a01d052010-09-27 16:35:11 -07002574 splitPointerIndex += 1;
2575 }
2576 action = maskedAction | (splitPointerIndex
2577 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002578 }
2579 } else {
2580 // An unrelated pointer changed.
2581 action = AMOTION_EVENT_ACTION_MOVE;
2582 }
2583 }
2584
Jeff Brownac386072011-07-20 15:19:50 -07002585 MotionEntry* splitMotionEntry = new MotionEntry(
Jeff Brown01ce2e92010-09-26 22:20:12 -07002586 originalMotionEntry->eventTime,
2587 originalMotionEntry->deviceId,
2588 originalMotionEntry->source,
2589 originalMotionEntry->policyFlags,
2590 action,
2591 originalMotionEntry->flags,
2592 originalMotionEntry->metaState,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002593 originalMotionEntry->buttonState,
Jeff Brown01ce2e92010-09-26 22:20:12 -07002594 originalMotionEntry->edgeFlags,
2595 originalMotionEntry->xPrecision,
2596 originalMotionEntry->yPrecision,
2597 originalMotionEntry->downTime,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002598 splitPointerCount, splitPointerProperties, splitPointerCoords);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002599
2600 for (MotionSample* originalMotionSample = originalMotionEntry->firstSample.next;
2601 originalMotionSample != NULL; originalMotionSample = originalMotionSample->next) {
2602 for (uint32_t splitPointerIndex = 0; splitPointerIndex < splitPointerCount;
2603 splitPointerIndex++) {
2604 uint32_t originalPointerIndex = splitPointerIndexMap[splitPointerIndex];
Jeff Brownace13b12011-03-09 17:39:48 -08002605 splitPointerCoords[splitPointerIndex].copyFrom(
2606 originalMotionSample->pointerCoords[originalPointerIndex]);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002607 }
2608
Jeff Brownac386072011-07-20 15:19:50 -07002609 splitMotionEntry->appendSample(originalMotionSample->eventTime, splitPointerCoords);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002610 }
2611
Jeff Browna032cc02011-03-07 16:56:21 -08002612 if (originalMotionEntry->injectionState) {
2613 splitMotionEntry->injectionState = originalMotionEntry->injectionState;
2614 splitMotionEntry->injectionState->refCount += 1;
2615 }
2616
Jeff Brown01ce2e92010-09-26 22:20:12 -07002617 return splitMotionEntry;
2618}
2619
Jeff Brownbe1aa822011-07-27 16:04:54 -07002620void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002621#if DEBUG_INBOUND_EVENT_DETAILS
Jeff Brownbe1aa822011-07-27 16:04:54 -07002622 LOGD("notifyConfigurationChanged - eventTime=%lld", args->eventTime);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002623#endif
2624
Jeff Brownb88102f2010-09-08 11:49:43 -07002625 bool needWake;
Jeff Brown46b9ac02010-04-22 18:58:52 -07002626 { // acquire lock
2627 AutoMutex _l(mLock);
2628
Jeff Brownbe1aa822011-07-27 16:04:54 -07002629 ConfigurationChangedEntry* newEntry = new ConfigurationChangedEntry(args->eventTime);
Jeff Brownb88102f2010-09-08 11:49:43 -07002630 needWake = enqueueInboundEventLocked(newEntry);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002631 } // release lock
2632
Jeff Brownb88102f2010-09-08 11:49:43 -07002633 if (needWake) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002634 mLooper->wake();
Jeff Brown46b9ac02010-04-22 18:58:52 -07002635 }
2636}
2637
Jeff Brownbe1aa822011-07-27 16:04:54 -07002638void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002639#if DEBUG_INBOUND_EVENT_DETAILS
Jeff Brown90655042010-12-02 13:50:46 -08002640 LOGD("notifyKey - eventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, action=0x%x, "
Jeff Brown46b9ac02010-04-22 18:58:52 -07002641 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%lld",
Jeff Brownbe1aa822011-07-27 16:04:54 -07002642 args->eventTime, args->deviceId, args->source, args->policyFlags,
2643 args->action, args->flags, args->keyCode, args->scanCode,
2644 args->metaState, args->downTime);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002645#endif
Jeff Brownbe1aa822011-07-27 16:04:54 -07002646 if (!validateKeyEvent(args->action)) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002647 return;
2648 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002649
Jeff Brownbe1aa822011-07-27 16:04:54 -07002650 uint32_t policyFlags = args->policyFlags;
2651 int32_t flags = args->flags;
2652 int32_t metaState = args->metaState;
Jeff Brown1f245102010-11-18 20:53:46 -08002653 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
2654 policyFlags |= POLICY_FLAG_VIRTUAL;
2655 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
2656 }
Jeff Brown924c4d42011-03-07 16:40:47 -08002657 if (policyFlags & POLICY_FLAG_ALT) {
2658 metaState |= AMETA_ALT_ON | AMETA_ALT_LEFT_ON;
2659 }
2660 if (policyFlags & POLICY_FLAG_ALT_GR) {
2661 metaState |= AMETA_ALT_ON | AMETA_ALT_RIGHT_ON;
2662 }
2663 if (policyFlags & POLICY_FLAG_SHIFT) {
2664 metaState |= AMETA_SHIFT_ON | AMETA_SHIFT_LEFT_ON;
2665 }
2666 if (policyFlags & POLICY_FLAG_CAPS_LOCK) {
2667 metaState |= AMETA_CAPS_LOCK_ON;
2668 }
2669 if (policyFlags & POLICY_FLAG_FUNCTION) {
2670 metaState |= AMETA_FUNCTION_ON;
2671 }
Jeff Brown1f245102010-11-18 20:53:46 -08002672
Jeff Browne20c9e02010-10-11 14:20:19 -07002673 policyFlags |= POLICY_FLAG_TRUSTED;
Jeff Brown1f245102010-11-18 20:53:46 -08002674
2675 KeyEvent event;
Jeff Brownbe1aa822011-07-27 16:04:54 -07002676 event.initialize(args->deviceId, args->source, args->action,
2677 flags, args->keyCode, args->scanCode, metaState, 0,
2678 args->downTime, args->eventTime);
Jeff Brown1f245102010-11-18 20:53:46 -08002679
2680 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
2681
2682 if (policyFlags & POLICY_FLAG_WOKE_HERE) {
2683 flags |= AKEY_EVENT_FLAG_WOKE_HERE;
2684 }
Jeff Brownb6997262010-10-08 22:31:17 -07002685
Jeff Brownb88102f2010-09-08 11:49:43 -07002686 bool needWake;
Jeff Brown46b9ac02010-04-22 18:58:52 -07002687 { // acquire lock
Jeff Brown0029c662011-03-30 02:25:18 -07002688 mLock.lock();
2689
2690 if (mInputFilterEnabled) {
2691 mLock.unlock();
2692
2693 policyFlags |= POLICY_FLAG_FILTERED;
2694 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2695 return; // event was consumed by the filter
2696 }
2697
2698 mLock.lock();
2699 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002700
Jeff Brown7fbdc842010-06-17 20:52:56 -07002701 int32_t repeatCount = 0;
Jeff Brownbe1aa822011-07-27 16:04:54 -07002702 KeyEntry* newEntry = new KeyEntry(args->eventTime,
2703 args->deviceId, args->source, policyFlags,
2704 args->action, flags, args->keyCode, args->scanCode,
2705 metaState, repeatCount, args->downTime);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002706
Jeff Brownb88102f2010-09-08 11:49:43 -07002707 needWake = enqueueInboundEventLocked(newEntry);
Jeff Brown0029c662011-03-30 02:25:18 -07002708 mLock.unlock();
Jeff Brown46b9ac02010-04-22 18:58:52 -07002709 } // release lock
2710
Jeff Brownb88102f2010-09-08 11:49:43 -07002711 if (needWake) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002712 mLooper->wake();
Jeff Brown46b9ac02010-04-22 18:58:52 -07002713 }
2714}
2715
Jeff Brownbe1aa822011-07-27 16:04:54 -07002716void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002717#if DEBUG_INBOUND_EVENT_DETAILS
Jeff Brown90655042010-12-02 13:50:46 -08002718 LOGD("notifyMotion - eventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, "
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002719 "action=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, edgeFlags=0x%x, "
Jeff Brown85a31762010-09-01 17:01:00 -07002720 "xPrecision=%f, yPrecision=%f, downTime=%lld",
Jeff Brownbe1aa822011-07-27 16:04:54 -07002721 args->eventTime, args->deviceId, args->source, args->policyFlags,
2722 args->action, args->flags, args->metaState, args->buttonState,
2723 args->edgeFlags, args->xPrecision, args->yPrecision, args->downTime);
2724 for (uint32_t i = 0; i < args->pointerCount; i++) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002725 LOGD(" Pointer %d: id=%d, toolType=%d, "
2726 "x=%f, y=%f, pressure=%f, size=%f, "
Jeff Brown85a31762010-09-01 17:01:00 -07002727 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
Jeff Brown8d608662010-08-30 03:02:23 -07002728 "orientation=%f",
Jeff Brownbe1aa822011-07-27 16:04:54 -07002729 i, args->pointerProperties[i].id,
2730 args->pointerProperties[i].toolType,
2731 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
2732 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
2733 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
2734 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
2735 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
2736 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
2737 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
2738 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
2739 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Jeff Brown46b9ac02010-04-22 18:58:52 -07002740 }
2741#endif
Jeff Brownbe1aa822011-07-27 16:04:54 -07002742 if (!validateMotionEvent(args->action, args->pointerCount, args->pointerProperties)) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002743 return;
2744 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002745
Jeff Brownbe1aa822011-07-27 16:04:54 -07002746 uint32_t policyFlags = args->policyFlags;
Jeff Browne20c9e02010-10-11 14:20:19 -07002747 policyFlags |= POLICY_FLAG_TRUSTED;
Jeff Brownbe1aa822011-07-27 16:04:54 -07002748 mPolicy->interceptMotionBeforeQueueing(args->eventTime, /*byref*/ policyFlags);
Jeff Brownb6997262010-10-08 22:31:17 -07002749
Jeff Brownb88102f2010-09-08 11:49:43 -07002750 bool needWake;
Jeff Brown46b9ac02010-04-22 18:58:52 -07002751 { // acquire lock
Jeff Brown0029c662011-03-30 02:25:18 -07002752 mLock.lock();
2753
2754 if (mInputFilterEnabled) {
2755 mLock.unlock();
2756
2757 MotionEvent event;
Jeff Brownbe1aa822011-07-27 16:04:54 -07002758 event.initialize(args->deviceId, args->source, args->action, args->flags,
2759 args->edgeFlags, args->metaState, args->buttonState, 0, 0,
2760 args->xPrecision, args->yPrecision,
2761 args->downTime, args->eventTime,
2762 args->pointerCount, args->pointerProperties, args->pointerCoords);
Jeff Brown0029c662011-03-30 02:25:18 -07002763
2764 policyFlags |= POLICY_FLAG_FILTERED;
2765 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2766 return; // event was consumed by the filter
2767 }
2768
2769 mLock.lock();
2770 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002771
2772 // Attempt batching and streaming of move events.
Jeff Brownbe1aa822011-07-27 16:04:54 -07002773 if (args->action == AMOTION_EVENT_ACTION_MOVE
2774 || args->action == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002775 // BATCHING CASE
2776 //
2777 // Try to append a move sample to the tail of the inbound queue for this device.
2778 // Give up if we encounter a non-move motion event for this device since that
2779 // means we cannot append any new samples until a new motion event has started.
Jeff Brownac386072011-07-20 15:19:50 -07002780 for (EventEntry* entry = mInboundQueue.tail; entry; entry = entry->prev) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002781 if (entry->type != EventEntry::TYPE_MOTION) {
2782 // Keep looking for motion events.
2783 continue;
2784 }
2785
2786 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
Jeff Brownbe1aa822011-07-27 16:04:54 -07002787 if (motionEntry->deviceId != args->deviceId
2788 || motionEntry->source != args->source) {
Jeff Brownefd32662011-03-08 15:13:06 -08002789 // Keep looking for this device and source.
Jeff Brown46b9ac02010-04-22 18:58:52 -07002790 continue;
2791 }
2792
Jeff Brownbe1aa822011-07-27 16:04:54 -07002793 if (!motionEntry->canAppendSamples(args->action,
2794 args->pointerCount, args->pointerProperties)) {
Jeff Brownefd32662011-03-08 15:13:06 -08002795 // Last motion event in the queue for this device and source is
2796 // not compatible for appending new samples. Stop here.
Jeff Brown46b9ac02010-04-22 18:58:52 -07002797 goto NoBatchingOrStreaming;
2798 }
2799
Jeff Brown9c3cda02010-06-15 01:31:58 -07002800 // Do the batching magic.
Jeff Brownbe1aa822011-07-27 16:04:54 -07002801 batchMotionLocked(motionEntry, args->eventTime,
2802 args->metaState, args->pointerCoords,
Jeff Brown4e91a182011-04-07 11:38:09 -07002803 "most recent motion event for this device and source in the inbound queue");
Jeff Brown0029c662011-03-30 02:25:18 -07002804 mLock.unlock();
Jeff Brown9c3cda02010-06-15 01:31:58 -07002805 return; // done!
Jeff Brown46b9ac02010-04-22 18:58:52 -07002806 }
2807
Jeff Brownf6989da2011-04-06 17:19:48 -07002808 // BATCHING ONTO PENDING EVENT CASE
2809 //
2810 // Try to append a move sample to the currently pending event, if there is one.
2811 // We can do this as long as we are still waiting to find the targets for the
2812 // event. Once the targets are locked-in we can only do streaming.
2813 if (mPendingEvent
2814 && (!mPendingEvent->dispatchInProgress || !mCurrentInputTargetsValid)
2815 && mPendingEvent->type == EventEntry::TYPE_MOTION) {
2816 MotionEntry* motionEntry = static_cast<MotionEntry*>(mPendingEvent);
Jeff Brownbe1aa822011-07-27 16:04:54 -07002817 if (motionEntry->deviceId == args->deviceId
2818 && motionEntry->source == args->source) {
2819 if (!motionEntry->canAppendSamples(args->action,
2820 args->pointerCount, args->pointerProperties)) {
Jeff Brown4e91a182011-04-07 11:38:09 -07002821 // Pending motion event is for this device and source but it is
2822 // not compatible for appending new samples. Stop here.
Jeff Brownf6989da2011-04-06 17:19:48 -07002823 goto NoBatchingOrStreaming;
2824 }
2825
Jeff Brownf6989da2011-04-06 17:19:48 -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 "pending motion event");
Jeff Brownf6989da2011-04-06 17:19:48 -07002830 mLock.unlock();
2831 return; // done!
2832 }
2833 }
2834
Jeff Brown46b9ac02010-04-22 18:58:52 -07002835 // STREAMING CASE
2836 //
2837 // There is no pending motion event (of any kind) for this device in the inbound queue.
Jeff Brown519e0242010-09-15 15:18:56 -07002838 // Search the outbound queue for the current foreground targets to find a dispatched
2839 // motion event that is still in progress. If found, then, appen the new sample to
2840 // that event and push it out to all current targets. The logic in
2841 // prepareDispatchCycleLocked takes care of the case where some targets may
2842 // already have consumed the motion event by starting a new dispatch cycle if needed.
Jeff Brown9c3cda02010-06-15 01:31:58 -07002843 if (mCurrentInputTargetsValid) {
Jeff Brown519e0242010-09-15 15:18:56 -07002844 for (size_t i = 0; i < mCurrentInputTargets.size(); i++) {
2845 const InputTarget& inputTarget = mCurrentInputTargets[i];
2846 if ((inputTarget.flags & InputTarget::FLAG_FOREGROUND) == 0) {
2847 // Skip non-foreground targets. We only want to stream if there is at
2848 // least one foreground target whose dispatch is still in progress.
2849 continue;
Jeff Brown46b9ac02010-04-22 18:58:52 -07002850 }
Jeff Brown519e0242010-09-15 15:18:56 -07002851
2852 ssize_t connectionIndex = getConnectionIndexLocked(inputTarget.inputChannel);
2853 if (connectionIndex < 0) {
2854 // Connection must no longer be valid.
2855 continue;
2856 }
2857
2858 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
2859 if (connection->outboundQueue.isEmpty()) {
2860 // This foreground target has an empty outbound queue.
2861 continue;
2862 }
2863
Jeff Brownac386072011-07-20 15:19:50 -07002864 DispatchEntry* dispatchEntry = connection->outboundQueue.head;
Jeff Brown519e0242010-09-15 15:18:56 -07002865 if (! dispatchEntry->inProgress
Jeff Brown01ce2e92010-09-26 22:20:12 -07002866 || dispatchEntry->eventEntry->type != EventEntry::TYPE_MOTION
2867 || dispatchEntry->isSplit()) {
2868 // No motion event is being dispatched, or it is being split across
2869 // windows in which case we cannot stream.
Jeff Brown519e0242010-09-15 15:18:56 -07002870 continue;
2871 }
2872
2873 MotionEntry* motionEntry = static_cast<MotionEntry*>(
2874 dispatchEntry->eventEntry);
Jeff Brownbe1aa822011-07-27 16:04:54 -07002875 if (motionEntry->action != args->action
2876 || motionEntry->deviceId != args->deviceId
2877 || motionEntry->source != args->source
2878 || motionEntry->pointerCount != args->pointerCount
Jeff Brown519e0242010-09-15 15:18:56 -07002879 || motionEntry->isInjected()) {
2880 // The motion event is not compatible with this move.
2881 continue;
2882 }
2883
Jeff Brownbe1aa822011-07-27 16:04:54 -07002884 if (args->action == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Jeff Brown9302c872011-07-13 22:51:29 -07002885 if (mLastHoverWindowHandle == NULL) {
Jeff Browna032cc02011-03-07 16:56:21 -08002886#if DEBUG_BATCHING
2887 LOGD("Not streaming hover move because there is no "
2888 "last hovered window.");
2889#endif
2890 goto NoBatchingOrStreaming;
2891 }
2892
Jeff Brown9302c872011-07-13 22:51:29 -07002893 sp<InputWindowHandle> hoverWindowHandle = findTouchedWindowAtLocked(
Jeff Brownbe1aa822011-07-27 16:04:54 -07002894 args->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X),
2895 args->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Jeff Brown9302c872011-07-13 22:51:29 -07002896 if (mLastHoverWindowHandle != hoverWindowHandle) {
Jeff Browna032cc02011-03-07 16:56:21 -08002897#if DEBUG_BATCHING
2898 LOGD("Not streaming hover move because the last hovered window "
2899 "is '%s' but the currently hovered window is '%s'.",
Jeff Browncc4f7db2011-08-30 20:34:48 -07002900 mLastHoverWindowHandle->getName().string(),
Jeff Brown9302c872011-07-13 22:51:29 -07002901 hoverWindowHandle != NULL
Jeff Browncc4f7db2011-08-30 20:34:48 -07002902 ? hoverWindowHandle->getName().string() : "<null>");
Jeff Browna032cc02011-03-07 16:56:21 -08002903#endif
2904 goto NoBatchingOrStreaming;
2905 }
2906 }
2907
Jeff Brown519e0242010-09-15 15:18:56 -07002908 // Hurray! This foreground target is currently dispatching a move event
2909 // that we can stream onto. Append the motion sample and resume dispatch.
Jeff Brownbe1aa822011-07-27 16:04:54 -07002910 motionEntry->appendSample(args->eventTime, args->pointerCoords);
Jeff Brown519e0242010-09-15 15:18:56 -07002911#if DEBUG_BATCHING
2912 LOGD("Appended motion sample onto batch for most recently dispatched "
Jeff Brown4e91a182011-04-07 11:38:09 -07002913 "motion event for this device and source in the outbound queues. "
Jeff Brown519e0242010-09-15 15:18:56 -07002914 "Attempting to stream the motion sample.");
2915#endif
2916 nsecs_t currentTime = now();
2917 dispatchEventToCurrentInputTargetsLocked(currentTime, motionEntry,
2918 true /*resumeWithAppendedMotionSample*/);
2919
2920 runCommandsLockedInterruptible();
Jeff Brown0029c662011-03-30 02:25:18 -07002921 mLock.unlock();
Jeff Brown519e0242010-09-15 15:18:56 -07002922 return; // done!
Jeff Brown46b9ac02010-04-22 18:58:52 -07002923 }
2924 }
2925
2926NoBatchingOrStreaming:;
2927 }
2928
2929 // Just enqueue a new motion event.
Jeff Brownbe1aa822011-07-27 16:04:54 -07002930 MotionEntry* newEntry = new MotionEntry(args->eventTime,
2931 args->deviceId, args->source, policyFlags,
2932 args->action, args->flags, args->metaState, args->buttonState,
2933 args->edgeFlags, args->xPrecision, args->yPrecision, args->downTime,
2934 args->pointerCount, args->pointerProperties, args->pointerCoords);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002935
Jeff Brownb88102f2010-09-08 11:49:43 -07002936 needWake = enqueueInboundEventLocked(newEntry);
Jeff Brown0029c662011-03-30 02:25:18 -07002937 mLock.unlock();
Jeff Brown46b9ac02010-04-22 18:58:52 -07002938 } // release lock
2939
Jeff Brownb88102f2010-09-08 11:49:43 -07002940 if (needWake) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002941 mLooper->wake();
Jeff Brown46b9ac02010-04-22 18:58:52 -07002942 }
2943}
2944
Jeff Brown4e91a182011-04-07 11:38:09 -07002945void InputDispatcher::batchMotionLocked(MotionEntry* entry, nsecs_t eventTime,
2946 int32_t metaState, const PointerCoords* pointerCoords, const char* eventDescription) {
2947 // Combine meta states.
2948 entry->metaState |= metaState;
2949
2950 // Coalesce this sample if not enough time has elapsed since the last sample was
2951 // initially appended to the batch.
2952 MotionSample* lastSample = entry->lastSample;
2953 long interval = eventTime - lastSample->eventTimeBeforeCoalescing;
2954 if (interval <= MOTION_SAMPLE_COALESCE_INTERVAL) {
2955 uint32_t pointerCount = entry->pointerCount;
2956 for (uint32_t i = 0; i < pointerCount; i++) {
2957 lastSample->pointerCoords[i].copyFrom(pointerCoords[i]);
2958 }
2959 lastSample->eventTime = eventTime;
2960#if DEBUG_BATCHING
2961 LOGD("Coalesced motion into last sample of batch for %s, events were %0.3f ms apart",
2962 eventDescription, interval * 0.000001f);
2963#endif
2964 return;
2965 }
2966
2967 // Append the sample.
Jeff Brownac386072011-07-20 15:19:50 -07002968 entry->appendSample(eventTime, pointerCoords);
Jeff Brown4e91a182011-04-07 11:38:09 -07002969#if DEBUG_BATCHING
2970 LOGD("Appended motion sample onto batch for %s, events were %0.3f ms apart",
2971 eventDescription, interval * 0.000001f);
2972#endif
2973}
2974
Jeff Brownbe1aa822011-07-27 16:04:54 -07002975void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
Jeff Brownb6997262010-10-08 22:31:17 -07002976#if DEBUG_INBOUND_EVENT_DETAILS
Jeff Brownbe1aa822011-07-27 16:04:54 -07002977 LOGD("notifySwitch - eventTime=%lld, policyFlags=0x%x, switchCode=%d, switchValue=%d",
2978 args->eventTime, args->policyFlags,
2979 args->switchCode, args->switchValue);
Jeff Brownb6997262010-10-08 22:31:17 -07002980#endif
2981
Jeff Brownbe1aa822011-07-27 16:04:54 -07002982 uint32_t policyFlags = args->policyFlags;
Jeff Browne20c9e02010-10-11 14:20:19 -07002983 policyFlags |= POLICY_FLAG_TRUSTED;
Jeff Brownbe1aa822011-07-27 16:04:54 -07002984 mPolicy->notifySwitch(args->eventTime,
2985 args->switchCode, args->switchValue, policyFlags);
Jeff Brownb6997262010-10-08 22:31:17 -07002986}
2987
Jeff Brown65fd2512011-08-18 11:20:58 -07002988void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
2989#if DEBUG_INBOUND_EVENT_DETAILS
2990 LOGD("notifyDeviceReset - eventTime=%lld, deviceId=%d",
2991 args->eventTime, args->deviceId);
2992#endif
2993
2994 bool needWake;
2995 { // acquire lock
2996 AutoMutex _l(mLock);
2997
2998 DeviceResetEntry* newEntry = new DeviceResetEntry(args->eventTime, args->deviceId);
2999 needWake = enqueueInboundEventLocked(newEntry);
3000 } // release lock
3001
3002 if (needWake) {
3003 mLooper->wake();
3004 }
3005}
3006
Jeff Brown7fbdc842010-06-17 20:52:56 -07003007int32_t InputDispatcher::injectInputEvent(const InputEvent* event,
Jeff Brown0029c662011-03-30 02:25:18 -07003008 int32_t injectorPid, int32_t injectorUid, int32_t syncMode, int32_t timeoutMillis,
3009 uint32_t policyFlags) {
Jeff Brown7fbdc842010-06-17 20:52:56 -07003010#if DEBUG_INBOUND_EVENT_DETAILS
3011 LOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Jeff Brown0029c662011-03-30 02:25:18 -07003012 "syncMode=%d, timeoutMillis=%d, policyFlags=0x%08x",
3013 event->getType(), injectorPid, injectorUid, syncMode, timeoutMillis, policyFlags);
Jeff Brown7fbdc842010-06-17 20:52:56 -07003014#endif
3015
3016 nsecs_t endTime = now() + milliseconds_to_nanoseconds(timeoutMillis);
Jeff Browne20c9e02010-10-11 14:20:19 -07003017
Jeff Brown0029c662011-03-30 02:25:18 -07003018 policyFlags |= POLICY_FLAG_INJECTED;
Jeff Browne20c9e02010-10-11 14:20:19 -07003019 if (hasInjectionPermission(injectorPid, injectorUid)) {
3020 policyFlags |= POLICY_FLAG_TRUSTED;
3021 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07003022
Jeff Brownb6997262010-10-08 22:31:17 -07003023 EventEntry* injectedEntry;
3024 switch (event->getType()) {
3025 case AINPUT_EVENT_TYPE_KEY: {
3026 const KeyEvent* keyEvent = static_cast<const KeyEvent*>(event);
3027 int32_t action = keyEvent->getAction();
3028 if (! validateKeyEvent(action)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07003029 return INPUT_EVENT_INJECTION_FAILED;
3030 }
3031
Jeff Brownb6997262010-10-08 22:31:17 -07003032 int32_t flags = keyEvent->getFlags();
Jeff Brown1f245102010-11-18 20:53:46 -08003033 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
3034 policyFlags |= POLICY_FLAG_VIRTUAL;
3035 }
3036
Jeff Brown0029c662011-03-30 02:25:18 -07003037 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3038 mPolicy->interceptKeyBeforeQueueing(keyEvent, /*byref*/ policyFlags);
3039 }
Jeff Brown1f245102010-11-18 20:53:46 -08003040
3041 if (policyFlags & POLICY_FLAG_WOKE_HERE) {
3042 flags |= AKEY_EVENT_FLAG_WOKE_HERE;
3043 }
Jeff Brown6ec402b2010-07-28 15:48:59 -07003044
Jeff Brownb6997262010-10-08 22:31:17 -07003045 mLock.lock();
Jeff Brownac386072011-07-20 15:19:50 -07003046 injectedEntry = new KeyEntry(keyEvent->getEventTime(),
Jeff Brown1f245102010-11-18 20:53:46 -08003047 keyEvent->getDeviceId(), keyEvent->getSource(),
3048 policyFlags, action, flags,
3049 keyEvent->getKeyCode(), keyEvent->getScanCode(), keyEvent->getMetaState(),
Jeff Brownb6997262010-10-08 22:31:17 -07003050 keyEvent->getRepeatCount(), keyEvent->getDownTime());
3051 break;
3052 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07003053
Jeff Brownb6997262010-10-08 22:31:17 -07003054 case AINPUT_EVENT_TYPE_MOTION: {
3055 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
3056 int32_t action = motionEvent->getAction();
3057 size_t pointerCount = motionEvent->getPointerCount();
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003058 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
3059 if (! validateMotionEvent(action, pointerCount, pointerProperties)) {
Jeff Brownb6997262010-10-08 22:31:17 -07003060 return INPUT_EVENT_INJECTION_FAILED;
3061 }
3062
Jeff Brown0029c662011-03-30 02:25:18 -07003063 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3064 nsecs_t eventTime = motionEvent->getEventTime();
3065 mPolicy->interceptMotionBeforeQueueing(eventTime, /*byref*/ policyFlags);
3066 }
Jeff Brownb6997262010-10-08 22:31:17 -07003067
3068 mLock.lock();
3069 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
3070 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
Jeff Brownac386072011-07-20 15:19:50 -07003071 MotionEntry* motionEntry = new MotionEntry(*sampleEventTimes,
Jeff Brownb6997262010-10-08 22:31:17 -07003072 motionEvent->getDeviceId(), motionEvent->getSource(), policyFlags,
3073 action, motionEvent->getFlags(),
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003074 motionEvent->getMetaState(), motionEvent->getButtonState(),
3075 motionEvent->getEdgeFlags(),
Jeff Brownb6997262010-10-08 22:31:17 -07003076 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
3077 motionEvent->getDownTime(), uint32_t(pointerCount),
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003078 pointerProperties, samplePointerCoords);
Jeff Brownb6997262010-10-08 22:31:17 -07003079 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
3080 sampleEventTimes += 1;
3081 samplePointerCoords += pointerCount;
Jeff Brownac386072011-07-20 15:19:50 -07003082 motionEntry->appendSample(*sampleEventTimes, samplePointerCoords);
Jeff Brownb6997262010-10-08 22:31:17 -07003083 }
3084 injectedEntry = motionEntry;
3085 break;
3086 }
3087
3088 default:
3089 LOGW("Cannot inject event of type %d", event->getType());
3090 return INPUT_EVENT_INJECTION_FAILED;
3091 }
3092
Jeff Brownac386072011-07-20 15:19:50 -07003093 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
Jeff Brownb6997262010-10-08 22:31:17 -07003094 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
3095 injectionState->injectionIsAsync = true;
3096 }
3097
3098 injectionState->refCount += 1;
3099 injectedEntry->injectionState = injectionState;
3100
3101 bool needWake = enqueueInboundEventLocked(injectedEntry);
3102 mLock.unlock();
Jeff Brown7fbdc842010-06-17 20:52:56 -07003103
Jeff Brownb88102f2010-09-08 11:49:43 -07003104 if (needWake) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07003105 mLooper->wake();
Jeff Brown7fbdc842010-06-17 20:52:56 -07003106 }
3107
3108 int32_t injectionResult;
3109 { // acquire lock
3110 AutoMutex _l(mLock);
3111
Jeff Brown6ec402b2010-07-28 15:48:59 -07003112 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
3113 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
3114 } else {
3115 for (;;) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07003116 injectionResult = injectionState->injectionResult;
Jeff Brown6ec402b2010-07-28 15:48:59 -07003117 if (injectionResult != INPUT_EVENT_INJECTION_PENDING) {
3118 break;
3119 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07003120
Jeff Brown7fbdc842010-06-17 20:52:56 -07003121 nsecs_t remainingTimeout = endTime - now();
3122 if (remainingTimeout <= 0) {
Jeff Brown6ec402b2010-07-28 15:48:59 -07003123#if DEBUG_INJECTION
3124 LOGD("injectInputEvent - Timed out waiting for injection result "
3125 "to become available.");
3126#endif
Jeff Brown7fbdc842010-06-17 20:52:56 -07003127 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
3128 break;
3129 }
3130
Jeff Brown6ec402b2010-07-28 15:48:59 -07003131 mInjectionResultAvailableCondition.waitRelative(mLock, remainingTimeout);
3132 }
3133
3134 if (injectionResult == INPUT_EVENT_INJECTION_SUCCEEDED
3135 && syncMode == INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07003136 while (injectionState->pendingForegroundDispatches != 0) {
Jeff Brown6ec402b2010-07-28 15:48:59 -07003137#if DEBUG_INJECTION
Jeff Brown519e0242010-09-15 15:18:56 -07003138 LOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
Jeff Brown01ce2e92010-09-26 22:20:12 -07003139 injectionState->pendingForegroundDispatches);
Jeff Brown6ec402b2010-07-28 15:48:59 -07003140#endif
3141 nsecs_t remainingTimeout = endTime - now();
3142 if (remainingTimeout <= 0) {
3143#if DEBUG_INJECTION
Jeff Brown519e0242010-09-15 15:18:56 -07003144 LOGD("injectInputEvent - Timed out waiting for pending foreground "
Jeff Brown6ec402b2010-07-28 15:48:59 -07003145 "dispatches to finish.");
3146#endif
3147 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
3148 break;
3149 }
3150
3151 mInjectionSyncFinishedCondition.waitRelative(mLock, remainingTimeout);
3152 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07003153 }
3154 }
3155
Jeff Brownac386072011-07-20 15:19:50 -07003156 injectionState->release();
Jeff Brown7fbdc842010-06-17 20:52:56 -07003157 } // release lock
3158
Jeff Brown6ec402b2010-07-28 15:48:59 -07003159#if DEBUG_INJECTION
3160 LOGD("injectInputEvent - Finished with result %d. "
3161 "injectorPid=%d, injectorUid=%d",
3162 injectionResult, injectorPid, injectorUid);
3163#endif
3164
Jeff Brown7fbdc842010-06-17 20:52:56 -07003165 return injectionResult;
3166}
3167
Jeff Brownb6997262010-10-08 22:31:17 -07003168bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
3169 return injectorUid == 0
3170 || mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
3171}
3172
Jeff Brown7fbdc842010-06-17 20:52:56 -07003173void InputDispatcher::setInjectionResultLocked(EventEntry* entry, int32_t injectionResult) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07003174 InjectionState* injectionState = entry->injectionState;
3175 if (injectionState) {
Jeff Brown7fbdc842010-06-17 20:52:56 -07003176#if DEBUG_INJECTION
3177 LOGD("Setting input event injection result to %d. "
3178 "injectorPid=%d, injectorUid=%d",
Jeff Brown01ce2e92010-09-26 22:20:12 -07003179 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
Jeff Brown7fbdc842010-06-17 20:52:56 -07003180#endif
3181
Jeff Brown0029c662011-03-30 02:25:18 -07003182 if (injectionState->injectionIsAsync
3183 && !(entry->policyFlags & POLICY_FLAG_FILTERED)) {
Jeff Brown6ec402b2010-07-28 15:48:59 -07003184 // Log the outcome since the injector did not wait for the injection result.
3185 switch (injectionResult) {
3186 case INPUT_EVENT_INJECTION_SUCCEEDED:
Steve Block71f2cf12011-10-20 11:56:00 +01003187 ALOGV("Asynchronous input event injection succeeded.");
Jeff Brown6ec402b2010-07-28 15:48:59 -07003188 break;
3189 case INPUT_EVENT_INJECTION_FAILED:
3190 LOGW("Asynchronous input event injection failed.");
3191 break;
3192 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
3193 LOGW("Asynchronous input event injection permission denied.");
3194 break;
3195 case INPUT_EVENT_INJECTION_TIMED_OUT:
3196 LOGW("Asynchronous input event injection timed out.");
3197 break;
3198 }
3199 }
3200
Jeff Brown01ce2e92010-09-26 22:20:12 -07003201 injectionState->injectionResult = injectionResult;
Jeff Brown7fbdc842010-06-17 20:52:56 -07003202 mInjectionResultAvailableCondition.broadcast();
3203 }
3204}
3205
Jeff Brown01ce2e92010-09-26 22:20:12 -07003206void InputDispatcher::incrementPendingForegroundDispatchesLocked(EventEntry* entry) {
3207 InjectionState* injectionState = entry->injectionState;
3208 if (injectionState) {
3209 injectionState->pendingForegroundDispatches += 1;
3210 }
3211}
3212
Jeff Brown519e0242010-09-15 15:18:56 -07003213void InputDispatcher::decrementPendingForegroundDispatchesLocked(EventEntry* entry) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07003214 InjectionState* injectionState = entry->injectionState;
3215 if (injectionState) {
3216 injectionState->pendingForegroundDispatches -= 1;
Jeff Brown6ec402b2010-07-28 15:48:59 -07003217
Jeff Brown01ce2e92010-09-26 22:20:12 -07003218 if (injectionState->pendingForegroundDispatches == 0) {
3219 mInjectionSyncFinishedCondition.broadcast();
3220 }
Jeff Brownb88102f2010-09-08 11:49:43 -07003221 }
3222}
3223
Jeff Brown9302c872011-07-13 22:51:29 -07003224sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
3225 const sp<InputChannel>& inputChannel) const {
3226 size_t numWindows = mWindowHandles.size();
3227 for (size_t i = 0; i < numWindows; i++) {
3228 const sp<InputWindowHandle>& windowHandle = mWindowHandles.itemAt(i);
Jeff Browncc4f7db2011-08-30 20:34:48 -07003229 if (windowHandle->getInputChannel() == inputChannel) {
Jeff Brown9302c872011-07-13 22:51:29 -07003230 return windowHandle;
Jeff Brown01ce2e92010-09-26 22:20:12 -07003231 }
3232 }
3233 return NULL;
3234}
3235
Jeff Brown9302c872011-07-13 22:51:29 -07003236bool InputDispatcher::hasWindowHandleLocked(
3237 const sp<InputWindowHandle>& windowHandle) const {
3238 size_t numWindows = mWindowHandles.size();
3239 for (size_t i = 0; i < numWindows; i++) {
3240 if (mWindowHandles.itemAt(i) == windowHandle) {
3241 return true;
3242 }
3243 }
3244 return false;
3245}
3246
3247void InputDispatcher::setInputWindows(const Vector<sp<InputWindowHandle> >& inputWindowHandles) {
Jeff Brownb88102f2010-09-08 11:49:43 -07003248#if DEBUG_FOCUS
3249 LOGD("setInputWindows");
3250#endif
3251 { // acquire lock
3252 AutoMutex _l(mLock);
3253
Jeff Browncc4f7db2011-08-30 20:34:48 -07003254 Vector<sp<InputWindowHandle> > oldWindowHandles = mWindowHandles;
Jeff Brown9302c872011-07-13 22:51:29 -07003255 mWindowHandles = inputWindowHandles;
Jeff Brownb6997262010-10-08 22:31:17 -07003256
Jeff Brown9302c872011-07-13 22:51:29 -07003257 sp<InputWindowHandle> newFocusedWindowHandle;
3258 bool foundHoveredWindow = false;
3259 for (size_t i = 0; i < mWindowHandles.size(); i++) {
3260 const sp<InputWindowHandle>& windowHandle = mWindowHandles.itemAt(i);
Jeff Browncc4f7db2011-08-30 20:34:48 -07003261 if (!windowHandle->updateInfo() || windowHandle->getInputChannel() == NULL) {
Jeff Brown9302c872011-07-13 22:51:29 -07003262 mWindowHandles.removeAt(i--);
3263 continue;
3264 }
Jeff Browncc4f7db2011-08-30 20:34:48 -07003265 if (windowHandle->getInfo()->hasFocus) {
Jeff Brown9302c872011-07-13 22:51:29 -07003266 newFocusedWindowHandle = windowHandle;
3267 }
3268 if (windowHandle == mLastHoverWindowHandle) {
3269 foundHoveredWindow = true;
Jeff Brownb88102f2010-09-08 11:49:43 -07003270 }
3271 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07003272
Jeff Brown9302c872011-07-13 22:51:29 -07003273 if (!foundHoveredWindow) {
3274 mLastHoverWindowHandle = NULL;
3275 }
3276
3277 if (mFocusedWindowHandle != newFocusedWindowHandle) {
3278 if (mFocusedWindowHandle != NULL) {
Jeff Brownb6997262010-10-08 22:31:17 -07003279#if DEBUG_FOCUS
3280 LOGD("Focus left window: %s",
Jeff Browncc4f7db2011-08-30 20:34:48 -07003281 mFocusedWindowHandle->getName().string());
Jeff Brownb6997262010-10-08 22:31:17 -07003282#endif
Jeff Browncc4f7db2011-08-30 20:34:48 -07003283 sp<InputChannel> focusedInputChannel = mFocusedWindowHandle->getInputChannel();
3284 if (focusedInputChannel != NULL) {
Christopher Tated9be36c2011-08-16 16:09:33 -07003285 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
3286 "focus left window");
3287 synthesizeCancelationEventsForInputChannelLocked(
Jeff Browncc4f7db2011-08-30 20:34:48 -07003288 focusedInputChannel, options);
Christopher Tated9be36c2011-08-16 16:09:33 -07003289 }
Jeff Brownb6997262010-10-08 22:31:17 -07003290 }
Jeff Brown9302c872011-07-13 22:51:29 -07003291 if (newFocusedWindowHandle != NULL) {
Jeff Brownb6997262010-10-08 22:31:17 -07003292#if DEBUG_FOCUS
Jeff Brown9302c872011-07-13 22:51:29 -07003293 LOGD("Focus entered window: %s",
Jeff Browncc4f7db2011-08-30 20:34:48 -07003294 newFocusedWindowHandle->getName().string());
Jeff Brownb6997262010-10-08 22:31:17 -07003295#endif
Jeff Brown9302c872011-07-13 22:51:29 -07003296 }
3297 mFocusedWindowHandle = newFocusedWindowHandle;
Jeff Brownb6997262010-10-08 22:31:17 -07003298 }
3299
Jeff Brown9302c872011-07-13 22:51:29 -07003300 for (size_t i = 0; i < mTouchState.windows.size(); i++) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07003301 TouchedWindow& touchedWindow = mTouchState.windows.editItemAt(i);
Jeff Brown9302c872011-07-13 22:51:29 -07003302 if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
Jeff Brownb6997262010-10-08 22:31:17 -07003303#if DEBUG_FOCUS
Jeff Browncc4f7db2011-08-30 20:34:48 -07003304 LOGD("Touched window was removed: %s",
3305 touchedWindow.windowHandle->getName().string());
Jeff Brownb6997262010-10-08 22:31:17 -07003306#endif
Jeff Browncc4f7db2011-08-30 20:34:48 -07003307 sp<InputChannel> touchedInputChannel =
3308 touchedWindow.windowHandle->getInputChannel();
3309 if (touchedInputChannel != NULL) {
Christopher Tated9be36c2011-08-16 16:09:33 -07003310 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
3311 "touched window was removed");
3312 synthesizeCancelationEventsForInputChannelLocked(
Jeff Browncc4f7db2011-08-30 20:34:48 -07003313 touchedInputChannel, options);
Christopher Tated9be36c2011-08-16 16:09:33 -07003314 }
Jeff Brown9302c872011-07-13 22:51:29 -07003315 mTouchState.windows.removeAt(i--);
Jeff Brown01ce2e92010-09-26 22:20:12 -07003316 }
3317 }
Jeff Browncc4f7db2011-08-30 20:34:48 -07003318
3319 // Release information for windows that are no longer present.
3320 // This ensures that unused input channels are released promptly.
3321 // Otherwise, they might stick around until the window handle is destroyed
3322 // which might not happen until the next GC.
3323 for (size_t i = 0; i < oldWindowHandles.size(); i++) {
3324 const sp<InputWindowHandle>& oldWindowHandle = oldWindowHandles.itemAt(i);
3325 if (!hasWindowHandleLocked(oldWindowHandle)) {
3326#if DEBUG_FOCUS
3327 LOGD("Window went away: %s", oldWindowHandle->getName().string());
3328#endif
3329 oldWindowHandle->releaseInfo();
3330 }
3331 }
Jeff Brownb88102f2010-09-08 11:49:43 -07003332 } // release lock
3333
3334 // Wake up poll loop since it may need to make new input dispatching choices.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07003335 mLooper->wake();
Jeff Brownb88102f2010-09-08 11:49:43 -07003336}
3337
Jeff Brown9302c872011-07-13 22:51:29 -07003338void InputDispatcher::setFocusedApplication(
3339 const sp<InputApplicationHandle>& inputApplicationHandle) {
Jeff Brownb88102f2010-09-08 11:49:43 -07003340#if DEBUG_FOCUS
3341 LOGD("setFocusedApplication");
3342#endif
3343 { // acquire lock
3344 AutoMutex _l(mLock);
3345
Jeff Browncc4f7db2011-08-30 20:34:48 -07003346 if (inputApplicationHandle != NULL && inputApplicationHandle->updateInfo()) {
Jeff Brown5ea29ab2011-07-27 11:50:51 -07003347 if (mFocusedApplicationHandle != inputApplicationHandle) {
3348 if (mFocusedApplicationHandle != NULL) {
3349 resetTargetsLocked();
Jeff Browncc4f7db2011-08-30 20:34:48 -07003350 mFocusedApplicationHandle->releaseInfo();
Jeff Brown5ea29ab2011-07-27 11:50:51 -07003351 }
3352 mFocusedApplicationHandle = inputApplicationHandle;
3353 }
3354 } else if (mFocusedApplicationHandle != NULL) {
3355 resetTargetsLocked();
Jeff Browncc4f7db2011-08-30 20:34:48 -07003356 mFocusedApplicationHandle->releaseInfo();
Jeff Brown9302c872011-07-13 22:51:29 -07003357 mFocusedApplicationHandle.clear();
Jeff Brownb88102f2010-09-08 11:49:43 -07003358 }
3359
3360#if DEBUG_FOCUS
Jeff Brownb6997262010-10-08 22:31:17 -07003361 //logDispatchStateLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -07003362#endif
3363 } // release lock
3364
3365 // Wake up poll loop since it may need to make new input dispatching choices.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07003366 mLooper->wake();
Jeff Brownb88102f2010-09-08 11:49:43 -07003367}
3368
Jeff Brownb88102f2010-09-08 11:49:43 -07003369void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
3370#if DEBUG_FOCUS
3371 LOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
3372#endif
3373
3374 bool changed;
3375 { // acquire lock
3376 AutoMutex _l(mLock);
3377
3378 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
Jeff Brown120a4592010-10-27 18:43:51 -07003379 if (mDispatchFrozen && !frozen) {
Jeff Brownb88102f2010-09-08 11:49:43 -07003380 resetANRTimeoutsLocked();
3381 }
3382
Jeff Brown120a4592010-10-27 18:43:51 -07003383 if (mDispatchEnabled && !enabled) {
3384 resetAndDropEverythingLocked("dispatcher is being disabled");
3385 }
3386
Jeff Brownb88102f2010-09-08 11:49:43 -07003387 mDispatchEnabled = enabled;
3388 mDispatchFrozen = frozen;
3389 changed = true;
3390 } else {
3391 changed = false;
3392 }
3393
3394#if DEBUG_FOCUS
Jeff Brownb6997262010-10-08 22:31:17 -07003395 //logDispatchStateLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -07003396#endif
3397 } // release lock
3398
3399 if (changed) {
3400 // Wake up poll loop since it may need to make new input dispatching choices.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07003401 mLooper->wake();
Jeff Brown46b9ac02010-04-22 18:58:52 -07003402 }
3403}
3404
Jeff Brown0029c662011-03-30 02:25:18 -07003405void InputDispatcher::setInputFilterEnabled(bool enabled) {
3406#if DEBUG_FOCUS
3407 LOGD("setInputFilterEnabled: enabled=%d", enabled);
3408#endif
3409
3410 { // acquire lock
3411 AutoMutex _l(mLock);
3412
3413 if (mInputFilterEnabled == enabled) {
3414 return;
3415 }
3416
3417 mInputFilterEnabled = enabled;
3418 resetAndDropEverythingLocked("input filter is being enabled or disabled");
3419 } // release lock
3420
3421 // Wake up poll loop since there might be work to do to drop everything.
3422 mLooper->wake();
3423}
3424
Jeff Browne6504122010-09-27 14:52:15 -07003425bool InputDispatcher::transferTouchFocus(const sp<InputChannel>& fromChannel,
3426 const sp<InputChannel>& toChannel) {
3427#if DEBUG_FOCUS
3428 LOGD("transferTouchFocus: fromChannel=%s, toChannel=%s",
3429 fromChannel->getName().string(), toChannel->getName().string());
3430#endif
3431 { // acquire lock
3432 AutoMutex _l(mLock);
3433
Jeff Brown9302c872011-07-13 22:51:29 -07003434 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromChannel);
3435 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toChannel);
3436 if (fromWindowHandle == NULL || toWindowHandle == NULL) {
Jeff Browne6504122010-09-27 14:52:15 -07003437#if DEBUG_FOCUS
3438 LOGD("Cannot transfer focus because from or to window not found.");
3439#endif
3440 return false;
3441 }
Jeff Brown9302c872011-07-13 22:51:29 -07003442 if (fromWindowHandle == toWindowHandle) {
Jeff Browne6504122010-09-27 14:52:15 -07003443#if DEBUG_FOCUS
3444 LOGD("Trivial transfer to same window.");
3445#endif
3446 return true;
3447 }
3448
3449 bool found = false;
3450 for (size_t i = 0; i < mTouchState.windows.size(); i++) {
3451 const TouchedWindow& touchedWindow = mTouchState.windows[i];
Jeff Brown9302c872011-07-13 22:51:29 -07003452 if (touchedWindow.windowHandle == fromWindowHandle) {
Jeff Browne6504122010-09-27 14:52:15 -07003453 int32_t oldTargetFlags = touchedWindow.targetFlags;
3454 BitSet32 pointerIds = touchedWindow.pointerIds;
3455
3456 mTouchState.windows.removeAt(i);
3457
Jeff Brown46e75292010-11-10 16:53:45 -08003458 int32_t newTargetFlags = oldTargetFlags
Jeff Browna032cc02011-03-07 16:56:21 -08003459 & (InputTarget::FLAG_FOREGROUND
3460 | InputTarget::FLAG_SPLIT | InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brown9302c872011-07-13 22:51:29 -07003461 mTouchState.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Jeff Browne6504122010-09-27 14:52:15 -07003462
3463 found = true;
3464 break;
3465 }
3466 }
3467
3468 if (! found) {
3469#if DEBUG_FOCUS
3470 LOGD("Focus transfer failed because from window did not have focus.");
3471#endif
3472 return false;
3473 }
3474
Jeff Brown9c9f1a32010-10-11 18:32:20 -07003475 ssize_t fromConnectionIndex = getConnectionIndexLocked(fromChannel);
3476 ssize_t toConnectionIndex = getConnectionIndexLocked(toChannel);
3477 if (fromConnectionIndex >= 0 && toConnectionIndex >= 0) {
3478 sp<Connection> fromConnection = mConnectionsByReceiveFd.valueAt(fromConnectionIndex);
3479 sp<Connection> toConnection = mConnectionsByReceiveFd.valueAt(toConnectionIndex);
3480
3481 fromConnection->inputState.copyPointerStateTo(toConnection->inputState);
Jeff Brownda3d5a92011-03-29 15:11:34 -07003482 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Jeff Brown9c9f1a32010-10-11 18:32:20 -07003483 "transferring touch focus from this window to another window");
Jeff Brownda3d5a92011-03-29 15:11:34 -07003484 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Jeff Brown9c9f1a32010-10-11 18:32:20 -07003485 }
3486
Jeff Browne6504122010-09-27 14:52:15 -07003487#if DEBUG_FOCUS
3488 logDispatchStateLocked();
3489#endif
3490 } // release lock
3491
3492 // Wake up poll loop since it may need to make new input dispatching choices.
3493 mLooper->wake();
3494 return true;
3495}
3496
Jeff Brown120a4592010-10-27 18:43:51 -07003497void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
3498#if DEBUG_FOCUS
3499 LOGD("Resetting and dropping all events (%s).", reason);
3500#endif
3501
Jeff Brownda3d5a92011-03-29 15:11:34 -07003502 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
3503 synthesizeCancelationEventsForAllConnectionsLocked(options);
Jeff Brown120a4592010-10-27 18:43:51 -07003504
3505 resetKeyRepeatLocked();
3506 releasePendingEventLocked();
3507 drainInboundQueueLocked();
3508 resetTargetsLocked();
3509
3510 mTouchState.reset();
Jeff Brown9302c872011-07-13 22:51:29 -07003511 mLastHoverWindowHandle.clear();
Jeff Brown120a4592010-10-27 18:43:51 -07003512}
3513
Jeff Brownb88102f2010-09-08 11:49:43 -07003514void InputDispatcher::logDispatchStateLocked() {
3515 String8 dump;
3516 dumpDispatchStateLocked(dump);
Jeff Brown2a95c2a2010-09-16 12:31:46 -07003517
3518 char* text = dump.lockBuffer(dump.size());
3519 char* start = text;
3520 while (*start != '\0') {
3521 char* end = strchr(start, '\n');
3522 if (*end == '\n') {
3523 *(end++) = '\0';
3524 }
3525 LOGD("%s", start);
3526 start = end;
3527 }
Jeff Brownb88102f2010-09-08 11:49:43 -07003528}
3529
3530void InputDispatcher::dumpDispatchStateLocked(String8& dump) {
Jeff Brownf2f48712010-10-01 17:46:21 -07003531 dump.appendFormat(INDENT "DispatchEnabled: %d\n", mDispatchEnabled);
3532 dump.appendFormat(INDENT "DispatchFrozen: %d\n", mDispatchFrozen);
Jeff Brownb88102f2010-09-08 11:49:43 -07003533
Jeff Brown9302c872011-07-13 22:51:29 -07003534 if (mFocusedApplicationHandle != NULL) {
Jeff Brownf2f48712010-10-01 17:46:21 -07003535 dump.appendFormat(INDENT "FocusedApplication: name='%s', dispatchingTimeout=%0.3fms\n",
Jeff Browncc4f7db2011-08-30 20:34:48 -07003536 mFocusedApplicationHandle->getName().string(),
3537 mFocusedApplicationHandle->getDispatchingTimeout(
3538 DEFAULT_INPUT_DISPATCHING_TIMEOUT) / 1000000.0);
Jeff Brownb88102f2010-09-08 11:49:43 -07003539 } else {
Jeff Brownf2f48712010-10-01 17:46:21 -07003540 dump.append(INDENT "FocusedApplication: <null>\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003541 }
Jeff Brownf2f48712010-10-01 17:46:21 -07003542 dump.appendFormat(INDENT "FocusedWindow: name='%s'\n",
Jeff Browncc4f7db2011-08-30 20:34:48 -07003543 mFocusedWindowHandle != NULL ? mFocusedWindowHandle->getName().string() : "<null>");
Jeff Brownf2f48712010-10-01 17:46:21 -07003544
3545 dump.appendFormat(INDENT "TouchDown: %s\n", toString(mTouchState.down));
3546 dump.appendFormat(INDENT "TouchSplit: %s\n", toString(mTouchState.split));
Jeff Brown95712852011-01-04 19:41:59 -08003547 dump.appendFormat(INDENT "TouchDeviceId: %d\n", mTouchState.deviceId);
Jeff Brown58a2da82011-01-25 16:02:22 -08003548 dump.appendFormat(INDENT "TouchSource: 0x%08x\n", mTouchState.source);
Jeff Brownf2f48712010-10-01 17:46:21 -07003549 if (!mTouchState.windows.isEmpty()) {
3550 dump.append(INDENT "TouchedWindows:\n");
3551 for (size_t i = 0; i < mTouchState.windows.size(); i++) {
3552 const TouchedWindow& touchedWindow = mTouchState.windows[i];
3553 dump.appendFormat(INDENT2 "%d: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
Jeff Browncc4f7db2011-08-30 20:34:48 -07003554 i, touchedWindow.windowHandle->getName().string(),
3555 touchedWindow.pointerIds.value,
Jeff Brownf2f48712010-10-01 17:46:21 -07003556 touchedWindow.targetFlags);
3557 }
3558 } else {
3559 dump.append(INDENT "TouchedWindows: <none>\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003560 }
3561
Jeff Brown9302c872011-07-13 22:51:29 -07003562 if (!mWindowHandles.isEmpty()) {
Jeff Brownf2f48712010-10-01 17:46:21 -07003563 dump.append(INDENT "Windows:\n");
Jeff Brown9302c872011-07-13 22:51:29 -07003564 for (size_t i = 0; i < mWindowHandles.size(); i++) {
3565 const sp<InputWindowHandle>& windowHandle = mWindowHandles.itemAt(i);
Jeff Browncc4f7db2011-08-30 20:34:48 -07003566 const InputWindowInfo* windowInfo = windowHandle->getInfo();
3567
Jeff Brownf2f48712010-10-01 17:46:21 -07003568 dump.appendFormat(INDENT2 "%d: name='%s', paused=%s, hasFocus=%s, hasWallpaper=%s, "
3569 "visible=%s, canReceiveKeys=%s, flags=0x%08x, type=0x%08x, layer=%d, "
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003570 "frame=[%d,%d][%d,%d], scale=%f, "
Jeff Brownfbf09772011-01-16 14:06:57 -08003571 "touchableRegion=",
Jeff Browncc4f7db2011-08-30 20:34:48 -07003572 i, windowInfo->name.string(),
3573 toString(windowInfo->paused),
3574 toString(windowInfo->hasFocus),
3575 toString(windowInfo->hasWallpaper),
3576 toString(windowInfo->visible),
3577 toString(windowInfo->canReceiveKeys),
3578 windowInfo->layoutParamsFlags, windowInfo->layoutParamsType,
3579 windowInfo->layer,
3580 windowInfo->frameLeft, windowInfo->frameTop,
3581 windowInfo->frameRight, windowInfo->frameBottom,
3582 windowInfo->scaleFactor);
3583 dumpRegion(dump, windowInfo->touchableRegion);
3584 dump.appendFormat(", inputFeatures=0x%08x", windowInfo->inputFeatures);
Jeff Brownfbf09772011-01-16 14:06:57 -08003585 dump.appendFormat(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%0.3fms\n",
Jeff Browncc4f7db2011-08-30 20:34:48 -07003586 windowInfo->ownerPid, windowInfo->ownerUid,
3587 windowInfo->dispatchingTimeout / 1000000.0);
Jeff Brownf2f48712010-10-01 17:46:21 -07003588 }
3589 } else {
3590 dump.append(INDENT "Windows: <none>\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003591 }
3592
Jeff Brownf2f48712010-10-01 17:46:21 -07003593 if (!mMonitoringChannels.isEmpty()) {
3594 dump.append(INDENT "MonitoringChannels:\n");
3595 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
3596 const sp<InputChannel>& channel = mMonitoringChannels[i];
3597 dump.appendFormat(INDENT2 "%d: '%s'\n", i, channel->getName().string());
3598 }
3599 } else {
3600 dump.append(INDENT "MonitoringChannels: <none>\n");
3601 }
Jeff Brown519e0242010-09-15 15:18:56 -07003602
Jeff Brownf2f48712010-10-01 17:46:21 -07003603 dump.appendFormat(INDENT "InboundQueue: length=%u\n", mInboundQueue.count());
3604
3605 if (!mActiveConnections.isEmpty()) {
3606 dump.append(INDENT "ActiveConnections:\n");
3607 for (size_t i = 0; i < mActiveConnections.size(); i++) {
3608 const Connection* connection = mActiveConnections[i];
Jeff Brown76860e32010-10-25 17:37:46 -07003609 dump.appendFormat(INDENT2 "%d: '%s', status=%s, outboundQueueLength=%u, "
Jeff Brownb6997262010-10-08 22:31:17 -07003610 "inputState.isNeutral=%s\n",
Jeff Brownf2f48712010-10-01 17:46:21 -07003611 i, connection->getInputChannelName(), connection->getStatusLabel(),
3612 connection->outboundQueue.count(),
Jeff Brownb6997262010-10-08 22:31:17 -07003613 toString(connection->inputState.isNeutral()));
Jeff Brownf2f48712010-10-01 17:46:21 -07003614 }
3615 } else {
3616 dump.append(INDENT "ActiveConnections: <none>\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003617 }
3618
3619 if (isAppSwitchPendingLocked()) {
Jeff Brownf2f48712010-10-01 17:46:21 -07003620 dump.appendFormat(INDENT "AppSwitch: pending, due in %01.1fms\n",
Jeff Brownb88102f2010-09-08 11:49:43 -07003621 (mAppSwitchDueTime - now()) / 1000000.0);
3622 } else {
Jeff Brownf2f48712010-10-01 17:46:21 -07003623 dump.append(INDENT "AppSwitch: not pending\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003624 }
3625}
3626
Jeff Brown928e0542011-01-10 11:17:36 -08003627status_t InputDispatcher::registerInputChannel(const sp<InputChannel>& inputChannel,
3628 const sp<InputWindowHandle>& inputWindowHandle, bool monitor) {
Jeff Brown9c3cda02010-06-15 01:31:58 -07003629#if DEBUG_REGISTRATION
Jeff Brownb88102f2010-09-08 11:49:43 -07003630 LOGD("channel '%s' ~ registerInputChannel - monitor=%s", inputChannel->getName().string(),
3631 toString(monitor));
Jeff Brown9c3cda02010-06-15 01:31:58 -07003632#endif
3633
Jeff Brown46b9ac02010-04-22 18:58:52 -07003634 { // acquire lock
3635 AutoMutex _l(mLock);
3636
Jeff Brown519e0242010-09-15 15:18:56 -07003637 if (getConnectionIndexLocked(inputChannel) >= 0) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07003638 LOGW("Attempted to register already registered input channel '%s'",
3639 inputChannel->getName().string());
3640 return BAD_VALUE;
3641 }
3642
Jeff Browncc4f7db2011-08-30 20:34:48 -07003643 sp<Connection> connection = new Connection(inputChannel, inputWindowHandle, monitor);
Jeff Brown46b9ac02010-04-22 18:58:52 -07003644 status_t status = connection->initialize();
3645 if (status) {
3646 LOGE("Failed to initialize input publisher for input channel '%s', status=%d",
3647 inputChannel->getName().string(), status);
3648 return status;
3649 }
3650
Jeff Brown2cbecea2010-08-17 15:59:26 -07003651 int32_t receiveFd = inputChannel->getReceivePipeFd();
Jeff Brown46b9ac02010-04-22 18:58:52 -07003652 mConnectionsByReceiveFd.add(receiveFd, connection);
Jeff Brown9c3cda02010-06-15 01:31:58 -07003653
Jeff Brownb88102f2010-09-08 11:49:43 -07003654 if (monitor) {
3655 mMonitoringChannels.push(inputChannel);
3656 }
3657
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07003658 mLooper->addFd(receiveFd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
Jeff Brown2cbecea2010-08-17 15:59:26 -07003659
Jeff Brown9c3cda02010-06-15 01:31:58 -07003660 runCommandsLockedInterruptible();
Jeff Brown46b9ac02010-04-22 18:58:52 -07003661 } // release lock
Jeff Brown46b9ac02010-04-22 18:58:52 -07003662 return OK;
3663}
3664
3665status_t InputDispatcher::unregisterInputChannel(const sp<InputChannel>& inputChannel) {
Jeff Brown9c3cda02010-06-15 01:31:58 -07003666#if DEBUG_REGISTRATION
Jeff Brown349703e2010-06-22 01:27:15 -07003667 LOGD("channel '%s' ~ unregisterInputChannel", inputChannel->getName().string());
Jeff Brown9c3cda02010-06-15 01:31:58 -07003668#endif
3669
Jeff Brown46b9ac02010-04-22 18:58:52 -07003670 { // acquire lock
3671 AutoMutex _l(mLock);
3672
Jeff Browncc4f7db2011-08-30 20:34:48 -07003673 status_t status = unregisterInputChannelLocked(inputChannel, false /*notify*/);
3674 if (status) {
3675 return status;
Jeff Brown46b9ac02010-04-22 18:58:52 -07003676 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07003677 } // release lock
3678
Jeff Brown46b9ac02010-04-22 18:58:52 -07003679 // Wake the poll loop because removing the connection may have changed the current
3680 // synchronization state.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07003681 mLooper->wake();
Jeff Brown46b9ac02010-04-22 18:58:52 -07003682 return OK;
3683}
3684
Jeff Browncc4f7db2011-08-30 20:34:48 -07003685status_t InputDispatcher::unregisterInputChannelLocked(const sp<InputChannel>& inputChannel,
3686 bool notify) {
3687 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
3688 if (connectionIndex < 0) {
3689 LOGW("Attempted to unregister already unregistered input channel '%s'",
3690 inputChannel->getName().string());
3691 return BAD_VALUE;
3692 }
3693
3694 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
3695 mConnectionsByReceiveFd.removeItemsAt(connectionIndex);
3696
3697 if (connection->monitor) {
3698 removeMonitorChannelLocked(inputChannel);
3699 }
3700
3701 mLooper->removeFd(inputChannel->getReceivePipeFd());
3702
3703 nsecs_t currentTime = now();
3704 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
3705
3706 runCommandsLockedInterruptible();
3707
3708 connection->status = Connection::STATUS_ZOMBIE;
3709 return OK;
3710}
3711
3712void InputDispatcher::removeMonitorChannelLocked(const sp<InputChannel>& inputChannel) {
3713 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
3714 if (mMonitoringChannels[i] == inputChannel) {
3715 mMonitoringChannels.removeAt(i);
3716 break;
3717 }
3718 }
3719}
3720
Jeff Brown519e0242010-09-15 15:18:56 -07003721ssize_t InputDispatcher::getConnectionIndexLocked(const sp<InputChannel>& inputChannel) {
Jeff Brown2cbecea2010-08-17 15:59:26 -07003722 ssize_t connectionIndex = mConnectionsByReceiveFd.indexOfKey(inputChannel->getReceivePipeFd());
3723 if (connectionIndex >= 0) {
3724 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
3725 if (connection->inputChannel.get() == inputChannel.get()) {
3726 return connectionIndex;
3727 }
3728 }
3729
3730 return -1;
3731}
3732
Jeff Brown46b9ac02010-04-22 18:58:52 -07003733void InputDispatcher::activateConnectionLocked(Connection* connection) {
3734 for (size_t i = 0; i < mActiveConnections.size(); i++) {
3735 if (mActiveConnections.itemAt(i) == connection) {
3736 return;
3737 }
3738 }
3739 mActiveConnections.add(connection);
3740}
3741
3742void InputDispatcher::deactivateConnectionLocked(Connection* connection) {
3743 for (size_t i = 0; i < mActiveConnections.size(); i++) {
3744 if (mActiveConnections.itemAt(i) == connection) {
3745 mActiveConnections.removeAt(i);
3746 return;
3747 }
3748 }
3749}
3750
Jeff Brown9c3cda02010-06-15 01:31:58 -07003751void InputDispatcher::onDispatchCycleStartedLocked(
Jeff Brown7fbdc842010-06-17 20:52:56 -07003752 nsecs_t currentTime, const sp<Connection>& connection) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07003753}
3754
Jeff Brown9c3cda02010-06-15 01:31:58 -07003755void InputDispatcher::onDispatchCycleFinishedLocked(
Jeff Brown3915bb82010-11-05 15:02:16 -07003756 nsecs_t currentTime, const sp<Connection>& connection, bool handled) {
3757 CommandEntry* commandEntry = postCommandLocked(
3758 & InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
3759 commandEntry->connection = connection;
3760 commandEntry->handled = handled;
Jeff Brown46b9ac02010-04-22 18:58:52 -07003761}
3762
Jeff Brown9c3cda02010-06-15 01:31:58 -07003763void InputDispatcher::onDispatchCycleBrokenLocked(
Jeff Brown7fbdc842010-06-17 20:52:56 -07003764 nsecs_t currentTime, const sp<Connection>& connection) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07003765 LOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
3766 connection->getInputChannelName());
3767
Jeff Brown9c3cda02010-06-15 01:31:58 -07003768 CommandEntry* commandEntry = postCommandLocked(
3769 & InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
Jeff Brown7fbdc842010-06-17 20:52:56 -07003770 commandEntry->connection = connection;
Jeff Brown46b9ac02010-04-22 18:58:52 -07003771}
3772
Jeff Brown519e0242010-09-15 15:18:56 -07003773void InputDispatcher::onANRLocked(
Jeff Brown9302c872011-07-13 22:51:29 -07003774 nsecs_t currentTime, const sp<InputApplicationHandle>& applicationHandle,
3775 const sp<InputWindowHandle>& windowHandle,
Jeff Brown519e0242010-09-15 15:18:56 -07003776 nsecs_t eventTime, nsecs_t waitStartTime) {
3777 LOGI("Application is not responding: %s. "
3778 "%01.1fms since event, %01.1fms since wait started",
Jeff Brown9302c872011-07-13 22:51:29 -07003779 getApplicationWindowLabelLocked(applicationHandle, windowHandle).string(),
Jeff Brown519e0242010-09-15 15:18:56 -07003780 (currentTime - eventTime) / 1000000.0,
3781 (currentTime - waitStartTime) / 1000000.0);
3782
3783 CommandEntry* commandEntry = postCommandLocked(
3784 & InputDispatcher::doNotifyANRLockedInterruptible);
Jeff Brown9302c872011-07-13 22:51:29 -07003785 commandEntry->inputApplicationHandle = applicationHandle;
3786 commandEntry->inputWindowHandle = windowHandle;
Jeff Brown519e0242010-09-15 15:18:56 -07003787}
3788
Jeff Brownb88102f2010-09-08 11:49:43 -07003789void InputDispatcher::doNotifyConfigurationChangedInterruptible(
3790 CommandEntry* commandEntry) {
3791 mLock.unlock();
3792
3793 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
3794
3795 mLock.lock();
3796}
3797
Jeff Brown9c3cda02010-06-15 01:31:58 -07003798void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(
3799 CommandEntry* commandEntry) {
Jeff Brown7fbdc842010-06-17 20:52:56 -07003800 sp<Connection> connection = commandEntry->connection;
Jeff Brown9c3cda02010-06-15 01:31:58 -07003801
Jeff Brown7fbdc842010-06-17 20:52:56 -07003802 if (connection->status != Connection::STATUS_ZOMBIE) {
3803 mLock.unlock();
Jeff Brown9c3cda02010-06-15 01:31:58 -07003804
Jeff Brown928e0542011-01-10 11:17:36 -08003805 mPolicy->notifyInputChannelBroken(connection->inputWindowHandle);
Jeff Brown7fbdc842010-06-17 20:52:56 -07003806
3807 mLock.lock();
3808 }
Jeff Brown9c3cda02010-06-15 01:31:58 -07003809}
3810
Jeff Brown519e0242010-09-15 15:18:56 -07003811void InputDispatcher::doNotifyANRLockedInterruptible(
Jeff Brown9c3cda02010-06-15 01:31:58 -07003812 CommandEntry* commandEntry) {
Jeff Brown519e0242010-09-15 15:18:56 -07003813 mLock.unlock();
Jeff Brown9c3cda02010-06-15 01:31:58 -07003814
Jeff Brown519e0242010-09-15 15:18:56 -07003815 nsecs_t newTimeout = mPolicy->notifyANR(
Jeff Brown928e0542011-01-10 11:17:36 -08003816 commandEntry->inputApplicationHandle, commandEntry->inputWindowHandle);
Jeff Brown9c3cda02010-06-15 01:31:58 -07003817
Jeff Brown519e0242010-09-15 15:18:56 -07003818 mLock.lock();
Jeff Brown7fbdc842010-06-17 20:52:56 -07003819
Jeff Brown9302c872011-07-13 22:51:29 -07003820 resumeAfterTargetsNotReadyTimeoutLocked(newTimeout,
3821 commandEntry->inputWindowHandle != NULL
Jeff Browncc4f7db2011-08-30 20:34:48 -07003822 ? commandEntry->inputWindowHandle->getInputChannel() : NULL);
Jeff Brown9c3cda02010-06-15 01:31:58 -07003823}
3824
Jeff Brownb88102f2010-09-08 11:49:43 -07003825void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
3826 CommandEntry* commandEntry) {
3827 KeyEntry* entry = commandEntry->keyEntry;
Jeff Brown1f245102010-11-18 20:53:46 -08003828
3829 KeyEvent event;
3830 initializeKeyEvent(&event, entry);
Jeff Brownb88102f2010-09-08 11:49:43 -07003831
3832 mLock.unlock();
3833
Jeff Brown905805a2011-10-12 13:57:59 -07003834 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(commandEntry->inputWindowHandle,
Jeff Brown1f245102010-11-18 20:53:46 -08003835 &event, entry->policyFlags);
Jeff Brownb88102f2010-09-08 11:49:43 -07003836
3837 mLock.lock();
3838
Jeff Brown905805a2011-10-12 13:57:59 -07003839 if (delay < 0) {
3840 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
3841 } else if (!delay) {
3842 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
3843 } else {
3844 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
3845 entry->interceptKeyWakeupTime = now() + delay;
3846 }
Jeff Brownac386072011-07-20 15:19:50 -07003847 entry->release();
Jeff Brownb88102f2010-09-08 11:49:43 -07003848}
3849
Jeff Brown3915bb82010-11-05 15:02:16 -07003850void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(
3851 CommandEntry* commandEntry) {
3852 sp<Connection> connection = commandEntry->connection;
3853 bool handled = commandEntry->handled;
3854
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003855 bool skipNext = false;
Jeff Brown49ed71d2010-12-06 17:13:33 -08003856 if (!connection->outboundQueue.isEmpty()) {
Jeff Brownac386072011-07-20 15:19:50 -07003857 DispatchEntry* dispatchEntry = connection->outboundQueue.head;
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003858 if (dispatchEntry->inProgress) {
3859 if (dispatchEntry->eventEntry->type == EventEntry::TYPE_KEY) {
3860 KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry);
3861 skipNext = afterKeyEventLockedInterruptible(connection,
3862 dispatchEntry, keyEntry, handled);
3863 } else if (dispatchEntry->eventEntry->type == EventEntry::TYPE_MOTION) {
3864 MotionEntry* motionEntry = static_cast<MotionEntry*>(dispatchEntry->eventEntry);
3865 skipNext = afterMotionEventLockedInterruptible(connection,
3866 dispatchEntry, motionEntry, handled);
Jeff Brown49ed71d2010-12-06 17:13:33 -08003867 }
Jeff Brown3915bb82010-11-05 15:02:16 -07003868 }
3869 }
3870
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003871 if (!skipNext) {
3872 startNextDispatchCycleLocked(now(), connection);
3873 }
3874}
3875
3876bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
3877 DispatchEntry* dispatchEntry, KeyEntry* keyEntry, bool handled) {
3878 if (!(keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK)) {
3879 // Get the fallback key state.
3880 // Clear it out after dispatching the UP.
3881 int32_t originalKeyCode = keyEntry->keyCode;
3882 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
3883 if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
3884 connection->inputState.removeFallbackKey(originalKeyCode);
3885 }
3886
3887 if (handled || !dispatchEntry->hasForegroundTarget()) {
3888 // If the application handles the original key for which we previously
3889 // generated a fallback or if the window is not a foreground window,
3890 // then cancel the associated fallback key, if any.
3891 if (fallbackKeyCode != -1) {
3892 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
3893 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
3894 "application handled the original non-fallback key "
3895 "or is no longer a foreground target, "
3896 "canceling previously dispatched fallback key");
3897 options.keyCode = fallbackKeyCode;
3898 synthesizeCancelationEventsForConnectionLocked(connection, options);
3899 }
3900 connection->inputState.removeFallbackKey(originalKeyCode);
3901 }
3902 } else {
3903 // If the application did not handle a non-fallback key, first check
3904 // that we are in a good state to perform unhandled key event processing
3905 // Then ask the policy what to do with it.
3906 bool initialDown = keyEntry->action == AKEY_EVENT_ACTION_DOWN
3907 && keyEntry->repeatCount == 0;
3908 if (fallbackKeyCode == -1 && !initialDown) {
3909#if DEBUG_OUTBOUND_EVENT_DETAILS
3910 LOGD("Unhandled key event: Skipping unhandled key event processing "
3911 "since this is not an initial down. "
3912 "keyCode=%d, action=%d, repeatCount=%d",
3913 originalKeyCode, keyEntry->action, keyEntry->repeatCount);
3914#endif
3915 return false;
3916 }
3917
3918 // Dispatch the unhandled key to the policy.
3919#if DEBUG_OUTBOUND_EVENT_DETAILS
3920 LOGD("Unhandled key event: Asking policy to perform fallback action. "
3921 "keyCode=%d, action=%d, repeatCount=%d",
3922 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount);
3923#endif
3924 KeyEvent event;
3925 initializeKeyEvent(&event, keyEntry);
3926
3927 mLock.unlock();
3928
3929 bool fallback = mPolicy->dispatchUnhandledKey(connection->inputWindowHandle,
3930 &event, keyEntry->policyFlags, &event);
3931
3932 mLock.lock();
3933
3934 if (connection->status != Connection::STATUS_NORMAL) {
3935 connection->inputState.removeFallbackKey(originalKeyCode);
3936 return true; // skip next cycle
3937 }
3938
Jeff Brownac386072011-07-20 15:19:50 -07003939 LOG_ASSERT(connection->outboundQueue.head == dispatchEntry);
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003940
3941 // Latch the fallback keycode for this key on an initial down.
3942 // The fallback keycode cannot change at any other point in the lifecycle.
3943 if (initialDown) {
3944 if (fallback) {
3945 fallbackKeyCode = event.getKeyCode();
3946 } else {
3947 fallbackKeyCode = AKEYCODE_UNKNOWN;
3948 }
3949 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
3950 }
3951
3952 LOG_ASSERT(fallbackKeyCode != -1);
3953
3954 // Cancel the fallback key if the policy decides not to send it anymore.
3955 // We will continue to dispatch the key to the policy but we will no
3956 // longer dispatch a fallback key to the application.
3957 if (fallbackKeyCode != AKEYCODE_UNKNOWN
3958 && (!fallback || fallbackKeyCode != event.getKeyCode())) {
3959#if DEBUG_OUTBOUND_EVENT_DETAILS
3960 if (fallback) {
3961 LOGD("Unhandled key event: Policy requested to send key %d"
3962 "as a fallback for %d, but on the DOWN it had requested "
3963 "to send %d instead. Fallback canceled.",
3964 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
3965 } else {
3966 LOGD("Unhandled key event: Policy did not request fallback for %d,"
3967 "but on the DOWN it had requested to send %d. "
3968 "Fallback canceled.",
3969 originalKeyCode, fallbackKeyCode);
3970 }
3971#endif
3972
3973 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
3974 "canceling fallback, policy no longer desires it");
3975 options.keyCode = fallbackKeyCode;
3976 synthesizeCancelationEventsForConnectionLocked(connection, options);
3977
3978 fallback = false;
3979 fallbackKeyCode = AKEYCODE_UNKNOWN;
3980 if (keyEntry->action != AKEY_EVENT_ACTION_UP) {
3981 connection->inputState.setFallbackKey(originalKeyCode,
3982 fallbackKeyCode);
3983 }
3984 }
3985
3986#if DEBUG_OUTBOUND_EVENT_DETAILS
3987 {
3988 String8 msg;
3989 const KeyedVector<int32_t, int32_t>& fallbackKeys =
3990 connection->inputState.getFallbackKeys();
3991 for (size_t i = 0; i < fallbackKeys.size(); i++) {
3992 msg.appendFormat(", %d->%d", fallbackKeys.keyAt(i),
3993 fallbackKeys.valueAt(i));
3994 }
3995 LOGD("Unhandled key event: %d currently tracked fallback keys%s.",
3996 fallbackKeys.size(), msg.string());
3997 }
3998#endif
3999
4000 if (fallback) {
4001 // Restart the dispatch cycle using the fallback key.
4002 keyEntry->eventTime = event.getEventTime();
4003 keyEntry->deviceId = event.getDeviceId();
4004 keyEntry->source = event.getSource();
4005 keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
4006 keyEntry->keyCode = fallbackKeyCode;
4007 keyEntry->scanCode = event.getScanCode();
4008 keyEntry->metaState = event.getMetaState();
4009 keyEntry->repeatCount = event.getRepeatCount();
4010 keyEntry->downTime = event.getDownTime();
4011 keyEntry->syntheticRepeat = false;
4012
4013#if DEBUG_OUTBOUND_EVENT_DETAILS
4014 LOGD("Unhandled key event: Dispatching fallback key. "
4015 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
4016 originalKeyCode, fallbackKeyCode, keyEntry->metaState);
4017#endif
4018
4019 dispatchEntry->inProgress = false;
4020 startDispatchCycleLocked(now(), connection);
4021 return true; // already started next cycle
4022 } else {
4023#if DEBUG_OUTBOUND_EVENT_DETAILS
4024 LOGD("Unhandled key event: No fallback key.");
4025#endif
4026 }
4027 }
4028 }
4029 return false;
4030}
4031
4032bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
4033 DispatchEntry* dispatchEntry, MotionEntry* motionEntry, bool handled) {
4034 return false;
Jeff Brown3915bb82010-11-05 15:02:16 -07004035}
4036
Jeff Brownb88102f2010-09-08 11:49:43 -07004037void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
4038 mLock.unlock();
4039
Jeff Brown01ce2e92010-09-26 22:20:12 -07004040 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
Jeff Brownb88102f2010-09-08 11:49:43 -07004041
4042 mLock.lock();
4043}
4044
Jeff Brown3915bb82010-11-05 15:02:16 -07004045void InputDispatcher::initializeKeyEvent(KeyEvent* event, const KeyEntry* entry) {
4046 event->initialize(entry->deviceId, entry->source, entry->action, entry->flags,
4047 entry->keyCode, entry->scanCode, entry->metaState, entry->repeatCount,
4048 entry->downTime, entry->eventTime);
4049}
4050
Jeff Brown519e0242010-09-15 15:18:56 -07004051void InputDispatcher::updateDispatchStatisticsLocked(nsecs_t currentTime, const EventEntry* entry,
4052 int32_t injectionResult, nsecs_t timeSpentWaitingForApplication) {
4053 // TODO Write some statistics about how long we spend waiting.
Jeff Brownb88102f2010-09-08 11:49:43 -07004054}
4055
4056void InputDispatcher::dump(String8& dump) {
Jeff Brown89ef0722011-08-10 16:25:21 -07004057 AutoMutex _l(mLock);
4058
Jeff Brownf2f48712010-10-01 17:46:21 -07004059 dump.append("Input Dispatcher State:\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07004060 dumpDispatchStateLocked(dump);
Jeff Brown214eaf42011-05-26 19:17:02 -07004061
4062 dump.append(INDENT "Configuration:\n");
4063 dump.appendFormat(INDENT2 "MaxEventsPerSecond: %d\n", mConfig.maxEventsPerSecond);
4064 dump.appendFormat(INDENT2 "KeyRepeatDelay: %0.1fms\n", mConfig.keyRepeatDelay * 0.000001f);
4065 dump.appendFormat(INDENT2 "KeyRepeatTimeout: %0.1fms\n", mConfig.keyRepeatTimeout * 0.000001f);
Jeff Brownb88102f2010-09-08 11:49:43 -07004066}
4067
Jeff Brown89ef0722011-08-10 16:25:21 -07004068void InputDispatcher::monitor() {
4069 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
4070 mLock.lock();
4071 mLock.unlock();
4072}
4073
Jeff Brown9c3cda02010-06-15 01:31:58 -07004074
Jeff Brown519e0242010-09-15 15:18:56 -07004075// --- InputDispatcher::Queue ---
4076
4077template <typename T>
4078uint32_t InputDispatcher::Queue<T>::count() const {
4079 uint32_t result = 0;
Jeff Brownac386072011-07-20 15:19:50 -07004080 for (const T* entry = head; entry; entry = entry->next) {
Jeff Brown519e0242010-09-15 15:18:56 -07004081 result += 1;
4082 }
4083 return result;
4084}
4085
4086
Jeff Brownac386072011-07-20 15:19:50 -07004087// --- InputDispatcher::InjectionState ---
Jeff Brown46b9ac02010-04-22 18:58:52 -07004088
Jeff Brownac386072011-07-20 15:19:50 -07004089InputDispatcher::InjectionState::InjectionState(int32_t injectorPid, int32_t injectorUid) :
4090 refCount(1),
4091 injectorPid(injectorPid), injectorUid(injectorUid),
4092 injectionResult(INPUT_EVENT_INJECTION_PENDING), injectionIsAsync(false),
4093 pendingForegroundDispatches(0) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07004094}
4095
Jeff Brownac386072011-07-20 15:19:50 -07004096InputDispatcher::InjectionState::~InjectionState() {
Jeff Brown01ce2e92010-09-26 22:20:12 -07004097}
4098
Jeff Brownac386072011-07-20 15:19:50 -07004099void InputDispatcher::InjectionState::release() {
4100 refCount -= 1;
4101 if (refCount == 0) {
4102 delete this;
4103 } else {
4104 LOG_ASSERT(refCount > 0);
Jeff Brown01ce2e92010-09-26 22:20:12 -07004105 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07004106}
4107
Jeff Brownac386072011-07-20 15:19:50 -07004108
4109// --- InputDispatcher::EventEntry ---
4110
4111InputDispatcher::EventEntry::EventEntry(int32_t type, nsecs_t eventTime, uint32_t policyFlags) :
4112 refCount(1), type(type), eventTime(eventTime), policyFlags(policyFlags),
4113 injectionState(NULL), dispatchInProgress(false) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07004114}
4115
Jeff Brownac386072011-07-20 15:19:50 -07004116InputDispatcher::EventEntry::~EventEntry() {
4117 releaseInjectionState();
4118}
4119
4120void InputDispatcher::EventEntry::release() {
4121 refCount -= 1;
4122 if (refCount == 0) {
4123 delete this;
4124 } else {
4125 LOG_ASSERT(refCount > 0);
4126 }
4127}
4128
4129void InputDispatcher::EventEntry::releaseInjectionState() {
4130 if (injectionState) {
4131 injectionState->release();
4132 injectionState = NULL;
4133 }
4134}
4135
4136
4137// --- InputDispatcher::ConfigurationChangedEntry ---
4138
4139InputDispatcher::ConfigurationChangedEntry::ConfigurationChangedEntry(nsecs_t eventTime) :
4140 EventEntry(TYPE_CONFIGURATION_CHANGED, eventTime, 0) {
4141}
4142
4143InputDispatcher::ConfigurationChangedEntry::~ConfigurationChangedEntry() {
4144}
4145
4146
Jeff Brown65fd2512011-08-18 11:20:58 -07004147// --- InputDispatcher::DeviceResetEntry ---
4148
4149InputDispatcher::DeviceResetEntry::DeviceResetEntry(nsecs_t eventTime, int32_t deviceId) :
4150 EventEntry(TYPE_DEVICE_RESET, eventTime, 0),
4151 deviceId(deviceId) {
4152}
4153
4154InputDispatcher::DeviceResetEntry::~DeviceResetEntry() {
4155}
4156
4157
Jeff Brownac386072011-07-20 15:19:50 -07004158// --- InputDispatcher::KeyEntry ---
4159
4160InputDispatcher::KeyEntry::KeyEntry(nsecs_t eventTime,
Jeff Brown58a2da82011-01-25 16:02:22 -08004161 int32_t deviceId, uint32_t source, uint32_t policyFlags, int32_t action,
Jeff Brown7fbdc842010-06-17 20:52:56 -07004162 int32_t flags, int32_t keyCode, int32_t scanCode, int32_t metaState,
Jeff Brownac386072011-07-20 15:19:50 -07004163 int32_t repeatCount, nsecs_t downTime) :
4164 EventEntry(TYPE_KEY, eventTime, policyFlags),
4165 deviceId(deviceId), source(source), action(action), flags(flags),
4166 keyCode(keyCode), scanCode(scanCode), metaState(metaState),
4167 repeatCount(repeatCount), downTime(downTime),
Jeff Brown905805a2011-10-12 13:57:59 -07004168 syntheticRepeat(false), interceptKeyResult(KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN),
4169 interceptKeyWakeupTime(0) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07004170}
4171
Jeff Brownac386072011-07-20 15:19:50 -07004172InputDispatcher::KeyEntry::~KeyEntry() {
4173}
Jeff Brown7fbdc842010-06-17 20:52:56 -07004174
Jeff Brownac386072011-07-20 15:19:50 -07004175void InputDispatcher::KeyEntry::recycle() {
4176 releaseInjectionState();
4177
4178 dispatchInProgress = false;
4179 syntheticRepeat = false;
4180 interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
Jeff Brown905805a2011-10-12 13:57:59 -07004181 interceptKeyWakeupTime = 0;
Jeff Brownac386072011-07-20 15:19:50 -07004182}
4183
4184
4185// --- InputDispatcher::MotionSample ---
4186
4187InputDispatcher::MotionSample::MotionSample(nsecs_t eventTime,
4188 const PointerCoords* pointerCoords, uint32_t pointerCount) :
4189 next(NULL), eventTime(eventTime), eventTimeBeforeCoalescing(eventTime) {
Jeff Brown7fbdc842010-06-17 20:52:56 -07004190 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brownac386072011-07-20 15:19:50 -07004191 this->pointerCoords[i].copyFrom(pointerCoords[i]);
Jeff Brown7fbdc842010-06-17 20:52:56 -07004192 }
Jeff Brownb88102f2010-09-08 11:49:43 -07004193}
4194
4195
Jeff Brownae9fc032010-08-18 15:51:08 -07004196// --- InputDispatcher::MotionEntry ---
4197
Jeff Brownac386072011-07-20 15:19:50 -07004198InputDispatcher::MotionEntry::MotionEntry(nsecs_t eventTime,
4199 int32_t deviceId, uint32_t source, uint32_t policyFlags, int32_t action, int32_t flags,
4200 int32_t metaState, int32_t buttonState,
4201 int32_t edgeFlags, float xPrecision, float yPrecision,
4202 nsecs_t downTime, uint32_t pointerCount,
4203 const PointerProperties* pointerProperties, const PointerCoords* pointerCoords) :
4204 EventEntry(TYPE_MOTION, eventTime, policyFlags),
4205 deviceId(deviceId), source(source), action(action), flags(flags),
4206 metaState(metaState), buttonState(buttonState), edgeFlags(edgeFlags),
4207 xPrecision(xPrecision), yPrecision(yPrecision),
4208 downTime(downTime), pointerCount(pointerCount),
4209 firstSample(eventTime, pointerCoords, pointerCount),
4210 lastSample(&firstSample) {
4211 for (uint32_t i = 0; i < pointerCount; i++) {
4212 this->pointerProperties[i].copyFrom(pointerProperties[i]);
4213 }
4214}
4215
4216InputDispatcher::MotionEntry::~MotionEntry() {
4217 for (MotionSample* sample = firstSample.next; sample != NULL; ) {
4218 MotionSample* next = sample->next;
4219 delete sample;
4220 sample = next;
4221 }
4222}
4223
Jeff Brownae9fc032010-08-18 15:51:08 -07004224uint32_t InputDispatcher::MotionEntry::countSamples() const {
4225 uint32_t count = 1;
4226 for (MotionSample* sample = firstSample.next; sample != NULL; sample = sample->next) {
4227 count += 1;
4228 }
4229 return count;
4230}
4231
Jeff Brown4e91a182011-04-07 11:38:09 -07004232bool InputDispatcher::MotionEntry::canAppendSamples(int32_t action, uint32_t pointerCount,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07004233 const PointerProperties* pointerProperties) const {
Jeff Brown4e91a182011-04-07 11:38:09 -07004234 if (this->action != action
4235 || this->pointerCount != pointerCount
4236 || this->isInjected()) {
4237 return false;
4238 }
4239 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07004240 if (this->pointerProperties[i] != pointerProperties[i]) {
Jeff Brown4e91a182011-04-07 11:38:09 -07004241 return false;
4242 }
4243 }
4244 return true;
4245}
4246
Jeff Brownac386072011-07-20 15:19:50 -07004247void InputDispatcher::MotionEntry::appendSample(
4248 nsecs_t eventTime, const PointerCoords* pointerCoords) {
4249 MotionSample* sample = new MotionSample(eventTime, pointerCoords, pointerCount);
4250
4251 lastSample->next = sample;
4252 lastSample = sample;
4253}
4254
4255
4256// --- InputDispatcher::DispatchEntry ---
4257
4258InputDispatcher::DispatchEntry::DispatchEntry(EventEntry* eventEntry,
4259 int32_t targetFlags, float xOffset, float yOffset, float scaleFactor) :
4260 eventEntry(eventEntry), targetFlags(targetFlags),
4261 xOffset(xOffset), yOffset(yOffset), scaleFactor(scaleFactor),
4262 inProgress(false),
4263 resolvedAction(0), resolvedFlags(0),
4264 headMotionSample(NULL), tailMotionSample(NULL) {
4265 eventEntry->refCount += 1;
4266}
4267
4268InputDispatcher::DispatchEntry::~DispatchEntry() {
4269 eventEntry->release();
4270}
4271
Jeff Brownb88102f2010-09-08 11:49:43 -07004272
4273// --- InputDispatcher::InputState ---
4274
Jeff Brownb6997262010-10-08 22:31:17 -07004275InputDispatcher::InputState::InputState() {
Jeff Brownb88102f2010-09-08 11:49:43 -07004276}
4277
4278InputDispatcher::InputState::~InputState() {
4279}
4280
4281bool InputDispatcher::InputState::isNeutral() const {
4282 return mKeyMementos.isEmpty() && mMotionMementos.isEmpty();
4283}
4284
Jeff Brown81346812011-06-28 20:08:48 -07004285bool InputDispatcher::InputState::isHovering(int32_t deviceId, uint32_t source) const {
4286 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4287 const MotionMemento& memento = mMotionMementos.itemAt(i);
4288 if (memento.deviceId == deviceId
4289 && memento.source == source
4290 && memento.hovering) {
4291 return true;
4292 }
4293 }
4294 return false;
4295}
Jeff Brownb88102f2010-09-08 11:49:43 -07004296
Jeff Brown81346812011-06-28 20:08:48 -07004297bool InputDispatcher::InputState::trackKey(const KeyEntry* entry,
4298 int32_t action, int32_t flags) {
4299 switch (action) {
4300 case AKEY_EVENT_ACTION_UP: {
4301 if (entry->flags & AKEY_EVENT_FLAG_FALLBACK) {
4302 for (size_t i = 0; i < mFallbackKeys.size(); ) {
4303 if (mFallbackKeys.valueAt(i) == entry->keyCode) {
4304 mFallbackKeys.removeItemsAt(i);
4305 } else {
4306 i += 1;
4307 }
4308 }
4309 }
4310 ssize_t index = findKeyMemento(entry);
4311 if (index >= 0) {
4312 mKeyMementos.removeAt(index);
4313 return true;
4314 }
Jeff Brown68b909d2011-12-07 16:36:01 -08004315 /* FIXME: We can't just drop the key up event because that prevents creating
4316 * popup windows that are automatically shown when a key is held and then
4317 * dismissed when the key is released. The problem is that the popup will
4318 * not have received the original key down, so the key up will be considered
4319 * to be inconsistent with its observed state. We could perhaps handle this
4320 * by synthesizing a key down but that will cause other problems.
4321 *
4322 * So for now, allow inconsistent key up events to be dispatched.
4323 *
Jeff Brown81346812011-06-28 20:08:48 -07004324#if DEBUG_OUTBOUND_EVENT_DETAILS
4325 LOGD("Dropping inconsistent key up event: deviceId=%d, source=%08x, "
4326 "keyCode=%d, scanCode=%d",
4327 entry->deviceId, entry->source, entry->keyCode, entry->scanCode);
4328#endif
4329 return false;
Jeff Brown68b909d2011-12-07 16:36:01 -08004330 */
4331 return true;
Jeff Brown81346812011-06-28 20:08:48 -07004332 }
4333
4334 case AKEY_EVENT_ACTION_DOWN: {
4335 ssize_t index = findKeyMemento(entry);
4336 if (index >= 0) {
4337 mKeyMementos.removeAt(index);
4338 }
4339 addKeyMemento(entry, flags);
4340 return true;
4341 }
4342
4343 default:
4344 return true;
Jeff Brownb88102f2010-09-08 11:49:43 -07004345 }
4346}
4347
Jeff Brown81346812011-06-28 20:08:48 -07004348bool InputDispatcher::InputState::trackMotion(const MotionEntry* entry,
4349 int32_t action, int32_t flags) {
4350 int32_t actionMasked = action & AMOTION_EVENT_ACTION_MASK;
4351 switch (actionMasked) {
4352 case AMOTION_EVENT_ACTION_UP:
4353 case AMOTION_EVENT_ACTION_CANCEL: {
4354 ssize_t index = findMotionMemento(entry, false /*hovering*/);
4355 if (index >= 0) {
4356 mMotionMementos.removeAt(index);
4357 return true;
Jeff Brownda3d5a92011-03-29 15:11:34 -07004358 }
Jeff Brown81346812011-06-28 20:08:48 -07004359#if DEBUG_OUTBOUND_EVENT_DETAILS
4360 LOGD("Dropping inconsistent motion up or cancel event: deviceId=%d, source=%08x, "
4361 "actionMasked=%d",
4362 entry->deviceId, entry->source, actionMasked);
4363#endif
4364 return false;
Jeff Brownda3d5a92011-03-29 15:11:34 -07004365 }
4366
Jeff Brown81346812011-06-28 20:08:48 -07004367 case AMOTION_EVENT_ACTION_DOWN: {
4368 ssize_t index = findMotionMemento(entry, false /*hovering*/);
4369 if (index >= 0) {
4370 mMotionMementos.removeAt(index);
4371 }
4372 addMotionMemento(entry, flags, false /*hovering*/);
4373 return true;
4374 }
4375
4376 case AMOTION_EVENT_ACTION_POINTER_UP:
4377 case AMOTION_EVENT_ACTION_POINTER_DOWN:
4378 case AMOTION_EVENT_ACTION_MOVE: {
4379 ssize_t index = findMotionMemento(entry, false /*hovering*/);
4380 if (index >= 0) {
4381 MotionMemento& memento = mMotionMementos.editItemAt(index);
4382 memento.setPointers(entry);
4383 return true;
4384 }
Jeff Brown2e45fb62011-06-29 21:19:05 -07004385 if (actionMasked == AMOTION_EVENT_ACTION_MOVE
4386 && (entry->source & (AINPUT_SOURCE_CLASS_JOYSTICK
4387 | AINPUT_SOURCE_CLASS_NAVIGATION))) {
4388 // Joysticks and trackballs can send MOVE events without corresponding DOWN or UP.
4389 return true;
4390 }
Jeff Brown81346812011-06-28 20:08:48 -07004391#if DEBUG_OUTBOUND_EVENT_DETAILS
4392 LOGD("Dropping inconsistent motion pointer up/down or move event: "
4393 "deviceId=%d, source=%08x, actionMasked=%d",
4394 entry->deviceId, entry->source, actionMasked);
4395#endif
4396 return false;
4397 }
4398
4399 case AMOTION_EVENT_ACTION_HOVER_EXIT: {
4400 ssize_t index = findMotionMemento(entry, true /*hovering*/);
4401 if (index >= 0) {
4402 mMotionMementos.removeAt(index);
4403 return true;
4404 }
4405#if DEBUG_OUTBOUND_EVENT_DETAILS
4406 LOGD("Dropping inconsistent motion hover exit event: deviceId=%d, source=%08x",
4407 entry->deviceId, entry->source);
4408#endif
4409 return false;
4410 }
4411
4412 case AMOTION_EVENT_ACTION_HOVER_ENTER:
4413 case AMOTION_EVENT_ACTION_HOVER_MOVE: {
4414 ssize_t index = findMotionMemento(entry, true /*hovering*/);
4415 if (index >= 0) {
4416 mMotionMementos.removeAt(index);
4417 }
4418 addMotionMemento(entry, flags, true /*hovering*/);
4419 return true;
4420 }
4421
4422 default:
4423 return true;
4424 }
4425}
4426
4427ssize_t InputDispatcher::InputState::findKeyMemento(const KeyEntry* entry) const {
Jeff Brownb88102f2010-09-08 11:49:43 -07004428 for (size_t i = 0; i < mKeyMementos.size(); i++) {
Jeff Brown81346812011-06-28 20:08:48 -07004429 const KeyMemento& memento = mKeyMementos.itemAt(i);
Jeff Brownb88102f2010-09-08 11:49:43 -07004430 if (memento.deviceId == entry->deviceId
4431 && memento.source == entry->source
4432 && memento.keyCode == entry->keyCode
4433 && memento.scanCode == entry->scanCode) {
Jeff Brown81346812011-06-28 20:08:48 -07004434 return i;
Jeff Brownb88102f2010-09-08 11:49:43 -07004435 }
4436 }
Jeff Brown81346812011-06-28 20:08:48 -07004437 return -1;
Jeff Brownb88102f2010-09-08 11:49:43 -07004438}
4439
Jeff Brown81346812011-06-28 20:08:48 -07004440ssize_t InputDispatcher::InputState::findMotionMemento(const MotionEntry* entry,
4441 bool hovering) const {
Jeff Brownb88102f2010-09-08 11:49:43 -07004442 for (size_t i = 0; i < mMotionMementos.size(); i++) {
Jeff Brown81346812011-06-28 20:08:48 -07004443 const MotionMemento& memento = mMotionMementos.itemAt(i);
Jeff Brownb88102f2010-09-08 11:49:43 -07004444 if (memento.deviceId == entry->deviceId
Jeff Brown81346812011-06-28 20:08:48 -07004445 && memento.source == entry->source
4446 && memento.hovering == hovering) {
4447 return i;
Jeff Brownb88102f2010-09-08 11:49:43 -07004448 }
4449 }
Jeff Brown81346812011-06-28 20:08:48 -07004450 return -1;
4451}
Jeff Brownb88102f2010-09-08 11:49:43 -07004452
Jeff Brown81346812011-06-28 20:08:48 -07004453void InputDispatcher::InputState::addKeyMemento(const KeyEntry* entry, int32_t flags) {
4454 mKeyMementos.push();
4455 KeyMemento& memento = mKeyMementos.editTop();
4456 memento.deviceId = entry->deviceId;
4457 memento.source = entry->source;
4458 memento.keyCode = entry->keyCode;
4459 memento.scanCode = entry->scanCode;
4460 memento.flags = flags;
4461 memento.downTime = entry->downTime;
4462}
4463
4464void InputDispatcher::InputState::addMotionMemento(const MotionEntry* entry,
4465 int32_t flags, bool hovering) {
4466 mMotionMementos.push();
4467 MotionMemento& memento = mMotionMementos.editTop();
4468 memento.deviceId = entry->deviceId;
4469 memento.source = entry->source;
4470 memento.flags = flags;
4471 memento.xPrecision = entry->xPrecision;
4472 memento.yPrecision = entry->yPrecision;
4473 memento.downTime = entry->downTime;
4474 memento.setPointers(entry);
4475 memento.hovering = hovering;
Jeff Brownb88102f2010-09-08 11:49:43 -07004476}
4477
4478void InputDispatcher::InputState::MotionMemento::setPointers(const MotionEntry* entry) {
4479 pointerCount = entry->pointerCount;
4480 for (uint32_t i = 0; i < entry->pointerCount; i++) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07004481 pointerProperties[i].copyFrom(entry->pointerProperties[i]);
Jeff Brownace13b12011-03-09 17:39:48 -08004482 pointerCoords[i].copyFrom(entry->lastSample->pointerCoords[i]);
Jeff Brownb88102f2010-09-08 11:49:43 -07004483 }
4484}
4485
Jeff Brownb6997262010-10-08 22:31:17 -07004486void InputDispatcher::InputState::synthesizeCancelationEvents(nsecs_t currentTime,
Jeff Brownac386072011-07-20 15:19:50 -07004487 Vector<EventEntry*>& outEvents, const CancelationOptions& options) {
Jeff Brown81346812011-06-28 20:08:48 -07004488 for (size_t i = 0; i < mKeyMementos.size(); i++) {
Jeff Brownb88102f2010-09-08 11:49:43 -07004489 const KeyMemento& memento = mKeyMementos.itemAt(i);
Jeff Brown49ed71d2010-12-06 17:13:33 -08004490 if (shouldCancelKey(memento, options)) {
Jeff Brownac386072011-07-20 15:19:50 -07004491 outEvents.push(new KeyEntry(currentTime,
Jeff Brownb6997262010-10-08 22:31:17 -07004492 memento.deviceId, memento.source, 0,
Jeff Brown49ed71d2010-12-06 17:13:33 -08004493 AKEY_EVENT_ACTION_UP, memento.flags | AKEY_EVENT_FLAG_CANCELED,
Jeff Brownb6997262010-10-08 22:31:17 -07004494 memento.keyCode, memento.scanCode, 0, 0, memento.downTime));
Jeff Brownb6997262010-10-08 22:31:17 -07004495 }
Jeff Brownb88102f2010-09-08 11:49:43 -07004496 }
4497
Jeff Brown81346812011-06-28 20:08:48 -07004498 for (size_t i = 0; i < mMotionMementos.size(); i++) {
Jeff Brownb88102f2010-09-08 11:49:43 -07004499 const MotionMemento& memento = mMotionMementos.itemAt(i);
Jeff Brown49ed71d2010-12-06 17:13:33 -08004500 if (shouldCancelMotion(memento, options)) {
Jeff Brownac386072011-07-20 15:19:50 -07004501 outEvents.push(new MotionEntry(currentTime,
Jeff Brownb6997262010-10-08 22:31:17 -07004502 memento.deviceId, memento.source, 0,
Jeff Browna032cc02011-03-07 16:56:21 -08004503 memento.hovering
4504 ? AMOTION_EVENT_ACTION_HOVER_EXIT
4505 : AMOTION_EVENT_ACTION_CANCEL,
Jeff Brown81346812011-06-28 20:08:48 -07004506 memento.flags, 0, 0, 0,
Jeff Brownb6997262010-10-08 22:31:17 -07004507 memento.xPrecision, memento.yPrecision, memento.downTime,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07004508 memento.pointerCount, memento.pointerProperties, memento.pointerCoords));
Jeff Brownb6997262010-10-08 22:31:17 -07004509 }
Jeff Brownb88102f2010-09-08 11:49:43 -07004510 }
4511}
4512
4513void InputDispatcher::InputState::clear() {
4514 mKeyMementos.clear();
4515 mMotionMementos.clear();
Jeff Brownda3d5a92011-03-29 15:11:34 -07004516 mFallbackKeys.clear();
Jeff Brownb6997262010-10-08 22:31:17 -07004517}
4518
Jeff Brown9c9f1a32010-10-11 18:32:20 -07004519void InputDispatcher::InputState::copyPointerStateTo(InputState& other) const {
4520 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4521 const MotionMemento& memento = mMotionMementos.itemAt(i);
4522 if (memento.source & AINPUT_SOURCE_CLASS_POINTER) {
4523 for (size_t j = 0; j < other.mMotionMementos.size(); ) {
4524 const MotionMemento& otherMemento = other.mMotionMementos.itemAt(j);
4525 if (memento.deviceId == otherMemento.deviceId
4526 && memento.source == otherMemento.source) {
4527 other.mMotionMementos.removeAt(j);
4528 } else {
4529 j += 1;
4530 }
4531 }
4532 other.mMotionMementos.push(memento);
4533 }
4534 }
4535}
4536
Jeff Brownda3d5a92011-03-29 15:11:34 -07004537int32_t InputDispatcher::InputState::getFallbackKey(int32_t originalKeyCode) {
4538 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
4539 return index >= 0 ? mFallbackKeys.valueAt(index) : -1;
4540}
4541
4542void InputDispatcher::InputState::setFallbackKey(int32_t originalKeyCode,
4543 int32_t fallbackKeyCode) {
4544 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
4545 if (index >= 0) {
4546 mFallbackKeys.replaceValueAt(index, fallbackKeyCode);
4547 } else {
4548 mFallbackKeys.add(originalKeyCode, fallbackKeyCode);
4549 }
4550}
4551
4552void InputDispatcher::InputState::removeFallbackKey(int32_t originalKeyCode) {
4553 mFallbackKeys.removeItem(originalKeyCode);
4554}
4555
Jeff Brown49ed71d2010-12-06 17:13:33 -08004556bool InputDispatcher::InputState::shouldCancelKey(const KeyMemento& memento,
Jeff Brownda3d5a92011-03-29 15:11:34 -07004557 const CancelationOptions& options) {
4558 if (options.keyCode != -1 && memento.keyCode != options.keyCode) {
4559 return false;
4560 }
4561
Jeff Brown65fd2512011-08-18 11:20:58 -07004562 if (options.deviceId != -1 && memento.deviceId != options.deviceId) {
4563 return false;
4564 }
4565
Jeff Brownda3d5a92011-03-29 15:11:34 -07004566 switch (options.mode) {
4567 case CancelationOptions::CANCEL_ALL_EVENTS:
4568 case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
Jeff Brownb6997262010-10-08 22:31:17 -07004569 return true;
Jeff Brownda3d5a92011-03-29 15:11:34 -07004570 case CancelationOptions::CANCEL_FALLBACK_EVENTS:
Jeff Brown49ed71d2010-12-06 17:13:33 -08004571 return memento.flags & AKEY_EVENT_FLAG_FALLBACK;
4572 default:
4573 return false;
4574 }
4575}
4576
4577bool InputDispatcher::InputState::shouldCancelMotion(const MotionMemento& memento,
Jeff Brownda3d5a92011-03-29 15:11:34 -07004578 const CancelationOptions& options) {
Jeff Brown65fd2512011-08-18 11:20:58 -07004579 if (options.deviceId != -1 && memento.deviceId != options.deviceId) {
4580 return false;
4581 }
4582
Jeff Brownda3d5a92011-03-29 15:11:34 -07004583 switch (options.mode) {
4584 case CancelationOptions::CANCEL_ALL_EVENTS:
Jeff Brown49ed71d2010-12-06 17:13:33 -08004585 return true;
Jeff Brownda3d5a92011-03-29 15:11:34 -07004586 case CancelationOptions::CANCEL_POINTER_EVENTS:
Jeff Brown49ed71d2010-12-06 17:13:33 -08004587 return memento.source & AINPUT_SOURCE_CLASS_POINTER;
Jeff Brownda3d5a92011-03-29 15:11:34 -07004588 case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
Jeff Brown49ed71d2010-12-06 17:13:33 -08004589 return !(memento.source & AINPUT_SOURCE_CLASS_POINTER);
4590 default:
4591 return false;
Jeff Brownb6997262010-10-08 22:31:17 -07004592 }
Jeff Brownb88102f2010-09-08 11:49:43 -07004593}
4594
4595
Jeff Brown46b9ac02010-04-22 18:58:52 -07004596// --- InputDispatcher::Connection ---
4597
Jeff Brown928e0542011-01-10 11:17:36 -08004598InputDispatcher::Connection::Connection(const sp<InputChannel>& inputChannel,
Jeff Browncc4f7db2011-08-30 20:34:48 -07004599 const sp<InputWindowHandle>& inputWindowHandle, bool monitor) :
Jeff Brown928e0542011-01-10 11:17:36 -08004600 status(STATUS_NORMAL), inputChannel(inputChannel), inputWindowHandle(inputWindowHandle),
Jeff Browncc4f7db2011-08-30 20:34:48 -07004601 monitor(monitor),
Jeff Brown928e0542011-01-10 11:17:36 -08004602 inputPublisher(inputChannel),
Jeff Brownda3d5a92011-03-29 15:11:34 -07004603 lastEventTime(LONG_LONG_MAX), lastDispatchTime(LONG_LONG_MAX) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07004604}
4605
4606InputDispatcher::Connection::~Connection() {
4607}
4608
4609status_t InputDispatcher::Connection::initialize() {
4610 return inputPublisher.initialize();
4611}
4612
Jeff Brown9c3cda02010-06-15 01:31:58 -07004613const char* InputDispatcher::Connection::getStatusLabel() const {
4614 switch (status) {
4615 case STATUS_NORMAL:
4616 return "NORMAL";
4617
4618 case STATUS_BROKEN:
4619 return "BROKEN";
4620
Jeff Brown9c3cda02010-06-15 01:31:58 -07004621 case STATUS_ZOMBIE:
4622 return "ZOMBIE";
4623
4624 default:
4625 return "UNKNOWN";
4626 }
4627}
4628
Jeff Brown46b9ac02010-04-22 18:58:52 -07004629InputDispatcher::DispatchEntry* InputDispatcher::Connection::findQueuedDispatchEntryForEvent(
4630 const EventEntry* eventEntry) const {
Jeff Brownac386072011-07-20 15:19:50 -07004631 for (DispatchEntry* dispatchEntry = outboundQueue.tail; dispatchEntry;
4632 dispatchEntry = dispatchEntry->prev) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07004633 if (dispatchEntry->eventEntry == eventEntry) {
4634 return dispatchEntry;
4635 }
4636 }
4637 return NULL;
4638}
4639
Jeff Brownb88102f2010-09-08 11:49:43 -07004640
Jeff Brown9c3cda02010-06-15 01:31:58 -07004641// --- InputDispatcher::CommandEntry ---
4642
Jeff Brownac386072011-07-20 15:19:50 -07004643InputDispatcher::CommandEntry::CommandEntry(Command command) :
4644 command(command), eventTime(0), keyEntry(NULL), userActivityEventType(0), handled(false) {
Jeff Brown9c3cda02010-06-15 01:31:58 -07004645}
4646
4647InputDispatcher::CommandEntry::~CommandEntry() {
4648}
4649
Jeff Brown46b9ac02010-04-22 18:58:52 -07004650
Jeff Brown01ce2e92010-09-26 22:20:12 -07004651// --- InputDispatcher::TouchState ---
4652
4653InputDispatcher::TouchState::TouchState() :
Jeff Brown58a2da82011-01-25 16:02:22 -08004654 down(false), split(false), deviceId(-1), source(0) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07004655}
4656
4657InputDispatcher::TouchState::~TouchState() {
4658}
4659
4660void InputDispatcher::TouchState::reset() {
4661 down = false;
4662 split = false;
Jeff Brown95712852011-01-04 19:41:59 -08004663 deviceId = -1;
Jeff Brown58a2da82011-01-25 16:02:22 -08004664 source = 0;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004665 windows.clear();
4666}
4667
4668void InputDispatcher::TouchState::copyFrom(const TouchState& other) {
4669 down = other.down;
4670 split = other.split;
Jeff Brown95712852011-01-04 19:41:59 -08004671 deviceId = other.deviceId;
Jeff Brown58a2da82011-01-25 16:02:22 -08004672 source = other.source;
Jeff Brown9302c872011-07-13 22:51:29 -07004673 windows = other.windows;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004674}
4675
Jeff Brown9302c872011-07-13 22:51:29 -07004676void InputDispatcher::TouchState::addOrUpdateWindow(const sp<InputWindowHandle>& windowHandle,
Jeff Brown01ce2e92010-09-26 22:20:12 -07004677 int32_t targetFlags, BitSet32 pointerIds) {
4678 if (targetFlags & InputTarget::FLAG_SPLIT) {
4679 split = true;
4680 }
4681
4682 for (size_t i = 0; i < windows.size(); i++) {
4683 TouchedWindow& touchedWindow = windows.editItemAt(i);
Jeff Brown9302c872011-07-13 22:51:29 -07004684 if (touchedWindow.windowHandle == windowHandle) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07004685 touchedWindow.targetFlags |= targetFlags;
Jeff Brown98db5fa2011-06-08 15:37:10 -07004686 if (targetFlags & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
4687 touchedWindow.targetFlags &= ~InputTarget::FLAG_DISPATCH_AS_IS;
4688 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07004689 touchedWindow.pointerIds.value |= pointerIds.value;
4690 return;
4691 }
4692 }
4693
4694 windows.push();
4695
4696 TouchedWindow& touchedWindow = windows.editTop();
Jeff Brown9302c872011-07-13 22:51:29 -07004697 touchedWindow.windowHandle = windowHandle;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004698 touchedWindow.targetFlags = targetFlags;
4699 touchedWindow.pointerIds = pointerIds;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004700}
4701
Jeff Browna032cc02011-03-07 16:56:21 -08004702void InputDispatcher::TouchState::filterNonAsIsTouchWindows() {
Jeff Brown01ce2e92010-09-26 22:20:12 -07004703 for (size_t i = 0 ; i < windows.size(); ) {
Jeff Browna032cc02011-03-07 16:56:21 -08004704 TouchedWindow& window = windows.editItemAt(i);
Jeff Brown98db5fa2011-06-08 15:37:10 -07004705 if (window.targetFlags & (InputTarget::FLAG_DISPATCH_AS_IS
4706 | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER)) {
Jeff Browna032cc02011-03-07 16:56:21 -08004707 window.targetFlags &= ~InputTarget::FLAG_DISPATCH_MASK;
4708 window.targetFlags |= InputTarget::FLAG_DISPATCH_AS_IS;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004709 i += 1;
Jeff Browna032cc02011-03-07 16:56:21 -08004710 } else {
4711 windows.removeAt(i);
Jeff Brown01ce2e92010-09-26 22:20:12 -07004712 }
4713 }
4714}
4715
Jeff Brown9302c872011-07-13 22:51:29 -07004716sp<InputWindowHandle> InputDispatcher::TouchState::getFirstForegroundWindowHandle() const {
Jeff Brown01ce2e92010-09-26 22:20:12 -07004717 for (size_t i = 0; i < windows.size(); i++) {
Jeff Brown98db5fa2011-06-08 15:37:10 -07004718 const TouchedWindow& window = windows.itemAt(i);
4719 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
Jeff Brown9302c872011-07-13 22:51:29 -07004720 return window.windowHandle;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004721 }
4722 }
4723 return NULL;
4724}
4725
Jeff Brown98db5fa2011-06-08 15:37:10 -07004726bool InputDispatcher::TouchState::isSlippery() const {
4727 // Must have exactly one foreground window.
4728 bool haveSlipperyForegroundWindow = false;
4729 for (size_t i = 0; i < windows.size(); i++) {
4730 const TouchedWindow& window = windows.itemAt(i);
4731 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
Jeff Browncc4f7db2011-08-30 20:34:48 -07004732 if (haveSlipperyForegroundWindow
4733 || !(window.windowHandle->getInfo()->layoutParamsFlags
4734 & InputWindowInfo::FLAG_SLIPPERY)) {
Jeff Brown98db5fa2011-06-08 15:37:10 -07004735 return false;
4736 }
4737 haveSlipperyForegroundWindow = true;
4738 }
4739 }
4740 return haveSlipperyForegroundWindow;
4741}
4742
Jeff Brown01ce2e92010-09-26 22:20:12 -07004743
Jeff Brown46b9ac02010-04-22 18:58:52 -07004744// --- InputDispatcherThread ---
4745
4746InputDispatcherThread::InputDispatcherThread(const sp<InputDispatcherInterface>& dispatcher) :
4747 Thread(/*canCallJava*/ true), mDispatcher(dispatcher) {
4748}
4749
4750InputDispatcherThread::~InputDispatcherThread() {
4751}
4752
4753bool InputDispatcherThread::threadLoop() {
4754 mDispatcher->dispatchOnce();
4755 return true;
4756}
4757
4758} // namespace android