blob: eff65c2c6965f27bca40f1f2376a001ebc00b16a [file] [log] [blame]
Jeff Brownb4ff35d2011-01-02 16:37:43 -08001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070017#define LOG_TAG "InputDispatcher"
18
19//#define LOG_NDEBUG 0
20
21// Log detailed debug messages about each inbound event notification to the dispatcher.
Jeff Brown349703e2010-06-22 01:27:15 -070022#define DEBUG_INBOUND_EVENT_DETAILS 0
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070023
24// Log detailed debug messages about each outbound event processed by the dispatcher.
Jeff Brown349703e2010-06-22 01:27:15 -070025#define DEBUG_OUTBOUND_EVENT_DETAILS 0
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070026
27// Log debug messages about batching.
Jeff Brown349703e2010-06-22 01:27:15 -070028#define DEBUG_BATCHING 0
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070029
30// Log debug messages about the dispatch cycle.
Jeff Brown349703e2010-06-22 01:27:15 -070031#define DEBUG_DISPATCH_CYCLE 0
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070032
Jeff Brown9c3cda02010-06-15 01:31:58 -070033// Log debug messages about registrations.
Jeff Brown349703e2010-06-22 01:27:15 -070034#define DEBUG_REGISTRATION 0
Jeff Brown9c3cda02010-06-15 01:31:58 -070035
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070036// Log debug messages about performance statistics.
Jeff Brown349703e2010-06-22 01:27:15 -070037#define DEBUG_PERFORMANCE_STATISTICS 0
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070038
Jeff Brown7fbdc842010-06-17 20:52:56 -070039// Log debug messages about input event injection.
Jeff Brown349703e2010-06-22 01:27:15 -070040#define DEBUG_INJECTION 0
Jeff Brown7fbdc842010-06-17 20:52:56 -070041
Jeff Brownae9fc032010-08-18 15:51:08 -070042// Log debug messages about input event throttling.
43#define DEBUG_THROTTLING 0
44
Jeff Brownb88102f2010-09-08 11:49:43 -070045// Log debug messages about input focus tracking.
46#define DEBUG_FOCUS 0
47
48// Log debug messages about the app switch latency optimization.
49#define DEBUG_APP_SWITCH 0
50
Jeff Browna032cc02011-03-07 16:56:21 -080051// Log debug messages about hover events.
52#define DEBUG_HOVER 0
53
Jeff Brownb4ff35d2011-01-02 16:37:43 -080054#include "InputDispatcher.h"
55
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070056#include <cutils/log.h>
Jeff Brownb88102f2010-09-08 11:49:43 -070057#include <ui/PowerManager.h>
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070058
59#include <stddef.h>
60#include <unistd.h>
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070061#include <errno.h>
62#include <limits.h>
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070063
Jeff Brownf2f487182010-10-01 17:46:21 -070064#define INDENT " "
65#define INDENT2 " "
66
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070067namespace android {
68
Jeff Brownb88102f2010-09-08 11:49:43 -070069// Default input dispatching timeout if there is no focused application or paused window
70// from which to determine an appropriate dispatching timeout.
71const nsecs_t DEFAULT_INPUT_DISPATCHING_TIMEOUT = 5000 * 1000000LL; // 5 sec
72
73// Amount of time to allow for all pending events to be processed when an app switch
74// key is on the way. This is used to preempt input dispatch and drop input events
75// when an application takes too long to respond and the user has pressed an app switch key.
76const nsecs_t APP_SWITCH_TIMEOUT = 500 * 1000000LL; // 0.5sec
77
Jeff Brown928e0542011-01-10 11:17:36 -080078// Amount of time to allow for an event to be dispatched (measured since its eventTime)
79// before considering it stale and dropping it.
80const nsecs_t STALE_EVENT_TIMEOUT = 10000 * 1000000LL; // 10sec
81
Jeff Brown4e91a182011-04-07 11:38:09 -070082// Motion samples that are received within this amount of time are simply coalesced
83// when batched instead of being appended. This is done because some drivers update
84// the location of pointers one at a time instead of all at once.
85// For example, when there are 10 fingers down, the input dispatcher may receive 10
86// samples in quick succession with only one finger's location changed in each sample.
87//
88// This value effectively imposes an upper bound on the touch sampling rate.
89// Touch sensors typically have a 50Hz - 200Hz sampling rate, so we expect distinct
90// samples to become available 5-20ms apart but individual finger reports can trickle
91// in over a period of 2-4ms or so.
92//
93// Empirical testing shows that a 2ms coalescing interval (500Hz) is not enough,
94// a 3ms coalescing interval (333Hz) works well most of the time and doesn't introduce
95// significant quantization noise on current hardware.
96const nsecs_t MOTION_SAMPLE_COALESCE_INTERVAL = 3 * 1000000LL; // 3ms, 333Hz
97
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070098
Jeff Brown7fbdc842010-06-17 20:52:56 -070099static inline nsecs_t now() {
100 return systemTime(SYSTEM_TIME_MONOTONIC);
101}
102
Jeff Brownb88102f2010-09-08 11:49:43 -0700103static inline const char* toString(bool value) {
104 return value ? "true" : "false";
105}
106
Jeff Brown01ce2e92010-09-26 22:20:12 -0700107static inline int32_t getMotionEventActionPointerIndex(int32_t action) {
108 return (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK)
109 >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
110}
111
112static bool isValidKeyAction(int32_t action) {
113 switch (action) {
114 case AKEY_EVENT_ACTION_DOWN:
115 case AKEY_EVENT_ACTION_UP:
116 return true;
117 default:
118 return false;
119 }
120}
121
122static bool validateKeyEvent(int32_t action) {
123 if (! isValidKeyAction(action)) {
124 LOGE("Key event has invalid action code 0x%x", action);
125 return false;
126 }
127 return true;
128}
129
Jeff Brownb6997262010-10-08 22:31:17 -0700130static bool isValidMotionAction(int32_t action, size_t pointerCount) {
Jeff Brown01ce2e92010-09-26 22:20:12 -0700131 switch (action & AMOTION_EVENT_ACTION_MASK) {
132 case AMOTION_EVENT_ACTION_DOWN:
133 case AMOTION_EVENT_ACTION_UP:
134 case AMOTION_EVENT_ACTION_CANCEL:
135 case AMOTION_EVENT_ACTION_MOVE:
Jeff Brown01ce2e92010-09-26 22:20:12 -0700136 case AMOTION_EVENT_ACTION_OUTSIDE:
Jeff Browna032cc02011-03-07 16:56:21 -0800137 case AMOTION_EVENT_ACTION_HOVER_ENTER:
Jeff Browncc0c1592011-02-19 05:07:28 -0800138 case AMOTION_EVENT_ACTION_HOVER_MOVE:
Jeff Browna032cc02011-03-07 16:56:21 -0800139 case AMOTION_EVENT_ACTION_HOVER_EXIT:
Jeff Brown33bbfd22011-02-24 20:55:35 -0800140 case AMOTION_EVENT_ACTION_SCROLL:
Jeff Brown01ce2e92010-09-26 22:20:12 -0700141 return true;
Jeff Brownb6997262010-10-08 22:31:17 -0700142 case AMOTION_EVENT_ACTION_POINTER_DOWN:
143 case AMOTION_EVENT_ACTION_POINTER_UP: {
144 int32_t index = getMotionEventActionPointerIndex(action);
145 return index >= 0 && size_t(index) < pointerCount;
146 }
Jeff Brown01ce2e92010-09-26 22:20:12 -0700147 default:
148 return false;
149 }
150}
151
152static bool validateMotionEvent(int32_t action, size_t pointerCount,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700153 const PointerProperties* pointerProperties) {
Jeff Brownb6997262010-10-08 22:31:17 -0700154 if (! isValidMotionAction(action, pointerCount)) {
Jeff Brown01ce2e92010-09-26 22:20:12 -0700155 LOGE("Motion event has invalid action code 0x%x", action);
156 return false;
157 }
158 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
159 LOGE("Motion event has invalid pointer count %d; value must be between 1 and %d.",
160 pointerCount, MAX_POINTERS);
161 return false;
162 }
Jeff Brownc3db8582010-10-20 15:33:38 -0700163 BitSet32 pointerIdBits;
Jeff Brown01ce2e92010-09-26 22:20:12 -0700164 for (size_t i = 0; i < pointerCount; i++) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700165 int32_t id = pointerProperties[i].id;
Jeff Brownc3db8582010-10-20 15:33:38 -0700166 if (id < 0 || id > MAX_POINTER_ID) {
Jeff Brown01ce2e92010-09-26 22:20:12 -0700167 LOGE("Motion event has invalid pointer id %d; value must be between 0 and %d",
Jeff Brownc3db8582010-10-20 15:33:38 -0700168 id, MAX_POINTER_ID);
Jeff Brown01ce2e92010-09-26 22:20:12 -0700169 return false;
170 }
Jeff Brownc3db8582010-10-20 15:33:38 -0700171 if (pointerIdBits.hasBit(id)) {
172 LOGE("Motion event has duplicate pointer id %d", id);
173 return false;
174 }
175 pointerIdBits.markBit(id);
Jeff Brown01ce2e92010-09-26 22:20:12 -0700176 }
177 return true;
178}
179
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400180static void scalePointerCoords(const PointerCoords* inCoords, size_t count, float scaleFactor,
181 PointerCoords* outCoords) {
182 for (size_t i = 0; i < count; i++) {
183 outCoords[i] = inCoords[i];
184 outCoords[i].scale(scaleFactor);
185 }
186}
187
Jeff Brownfbf09772011-01-16 14:06:57 -0800188static void dumpRegion(String8& dump, const SkRegion& region) {
189 if (region.isEmpty()) {
190 dump.append("<empty>");
191 return;
192 }
193
194 bool first = true;
195 for (SkRegion::Iterator it(region); !it.done(); it.next()) {
196 if (first) {
197 first = false;
198 } else {
199 dump.append("|");
200 }
201 const SkIRect& rect = it.rect();
202 dump.appendFormat("[%d,%d][%d,%d]", rect.fLeft, rect.fTop, rect.fRight, rect.fBottom);
203 }
204}
205
Jeff Brownb88102f2010-09-08 11:49:43 -0700206
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700207// --- InputDispatcher ---
208
Jeff Brown9c3cda02010-06-15 01:31:58 -0700209InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy) :
Jeff Brownb88102f2010-09-08 11:49:43 -0700210 mPolicy(policy),
Jeff Brown928e0542011-01-10 11:17:36 -0800211 mPendingEvent(NULL), mAppSwitchSawKeyDown(false), mAppSwitchDueTime(LONG_LONG_MAX),
212 mNextUnblockedEvent(NULL),
Jeff Brown0029c662011-03-30 02:25:18 -0700213 mDispatchEnabled(true), mDispatchFrozen(false), mInputFilterEnabled(false),
Jeff Brown01ce2e92010-09-26 22:20:12 -0700214 mFocusedWindow(NULL),
Jeff Brownb88102f2010-09-08 11:49:43 -0700215 mFocusedApplication(NULL),
216 mCurrentInputTargetsValid(false),
Jeff Browna032cc02011-03-07 16:56:21 -0800217 mInputTargetWaitCause(INPUT_TARGET_WAIT_CAUSE_NONE),
218 mLastHoverWindow(NULL) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -0700219 mLooper = new Looper(false);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700220
Jeff Brownb88102f2010-09-08 11:49:43 -0700221 mInboundQueue.headSentinel.refCount = -1;
222 mInboundQueue.headSentinel.type = EventEntry::TYPE_SENTINEL;
223 mInboundQueue.headSentinel.eventTime = LONG_LONG_MIN;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700224
Jeff Brownb88102f2010-09-08 11:49:43 -0700225 mInboundQueue.tailSentinel.refCount = -1;
226 mInboundQueue.tailSentinel.type = EventEntry::TYPE_SENTINEL;
227 mInboundQueue.tailSentinel.eventTime = LONG_LONG_MAX;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700228
229 mKeyRepeatState.lastKeyEntry = NULL;
Jeff Brown9c3cda02010-06-15 01:31:58 -0700230
Jeff Brown214eaf42011-05-26 19:17:02 -0700231 policy->getDispatcherConfiguration(&mConfig);
232
233 mThrottleState.minTimeBetweenEvents = 1000000000LL / mConfig.maxEventsPerSecond;
Jeff Brownae9fc032010-08-18 15:51:08 -0700234 mThrottleState.lastDeviceId = -1;
235
236#if DEBUG_THROTTLING
237 mThrottleState.originalSampleCount = 0;
Jeff Brown214eaf42011-05-26 19:17:02 -0700238 LOGD("Throttling - Max events per second = %d", mConfig.maxEventsPerSecond);
Jeff Brownae9fc032010-08-18 15:51:08 -0700239#endif
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700240}
241
242InputDispatcher::~InputDispatcher() {
Jeff Brownb88102f2010-09-08 11:49:43 -0700243 { // acquire lock
244 AutoMutex _l(mLock);
245
246 resetKeyRepeatLocked();
Jeff Brown54a18252010-09-16 14:07:33 -0700247 releasePendingEventLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -0700248 drainInboundQueueLocked();
249 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700250
251 while (mConnectionsByReceiveFd.size() != 0) {
252 unregisterInputChannel(mConnectionsByReceiveFd.valueAt(0)->inputChannel);
253 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700254}
255
256void InputDispatcher::dispatchOnce() {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700257 nsecs_t nextWakeupTime = LONG_LONG_MAX;
258 { // acquire lock
259 AutoMutex _l(mLock);
Jeff Brown214eaf42011-05-26 19:17:02 -0700260 dispatchOnceInnerLocked(&nextWakeupTime);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700261
Jeff Brownb88102f2010-09-08 11:49:43 -0700262 if (runCommandsLockedInterruptible()) {
263 nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700264 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700265 } // release lock
266
Jeff Brownb88102f2010-09-08 11:49:43 -0700267 // Wait for callback or timeout or wake. (make sure we round up, not down)
268 nsecs_t currentTime = now();
Jeff Brownaa3855d2011-03-17 01:34:19 -0700269 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
Jeff Brown4fe6c3e2010-09-13 23:17:30 -0700270 mLooper->pollOnce(timeoutMillis);
Jeff Brownb88102f2010-09-08 11:49:43 -0700271}
272
Jeff Brown214eaf42011-05-26 19:17:02 -0700273void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700274 nsecs_t currentTime = now();
275
276 // Reset the key repeat timer whenever we disallow key events, even if the next event
277 // is not a key. This is to ensure that we abort a key repeat if the device is just coming
278 // out of sleep.
Jeff Brown214eaf42011-05-26 19:17:02 -0700279 if (!mPolicy->isKeyRepeatEnabled()) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700280 resetKeyRepeatLocked();
281 }
282
Jeff Brownb88102f2010-09-08 11:49:43 -0700283 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
284 if (mDispatchFrozen) {
285#if DEBUG_FOCUS
286 LOGD("Dispatch frozen. Waiting some more.");
287#endif
288 return;
289 }
290
291 // Optimize latency of app switches.
292 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
293 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
294 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
295 if (mAppSwitchDueTime < *nextWakeupTime) {
296 *nextWakeupTime = mAppSwitchDueTime;
297 }
298
Jeff Brownb88102f2010-09-08 11:49:43 -0700299 // Ready to start a new event.
300 // If we don't already have a pending event, go grab one.
301 if (! mPendingEvent) {
302 if (mInboundQueue.isEmpty()) {
303 if (isAppSwitchDue) {
304 // The inbound queue is empty so the app switch key we were waiting
305 // for will never arrive. Stop waiting for it.
306 resetPendingAppSwitchLocked(false);
307 isAppSwitchDue = false;
308 }
309
310 // Synthesize a key repeat if appropriate.
311 if (mKeyRepeatState.lastKeyEntry) {
312 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
Jeff Brown214eaf42011-05-26 19:17:02 -0700313 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700314 } else {
315 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
316 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
317 }
318 }
319 }
320 if (! mPendingEvent) {
321 return;
322 }
323 } else {
324 // Inbound queue has at least one entry.
325 EventEntry* entry = mInboundQueue.headSentinel.next;
326
327 // Throttle the entry if it is a move event and there are no
328 // other events behind it in the queue. Due to movement batching, additional
329 // samples may be appended to this event by the time the throttling timeout
330 // expires.
331 // TODO Make this smarter and consider throttling per device independently.
Jeff Brownb6997262010-10-08 22:31:17 -0700332 if (entry->type == EventEntry::TYPE_MOTION
333 && !isAppSwitchDue
334 && mDispatchEnabled
335 && (entry->policyFlags & POLICY_FLAG_PASS_TO_USER)
336 && !entry->isInjected()) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700337 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
338 int32_t deviceId = motionEntry->deviceId;
339 uint32_t source = motionEntry->source;
340 if (! isAppSwitchDue
341 && motionEntry->next == & mInboundQueue.tailSentinel // exactly one event
Jeff Browncc0c1592011-02-19 05:07:28 -0800342 && (motionEntry->action == AMOTION_EVENT_ACTION_MOVE
343 || motionEntry->action == AMOTION_EVENT_ACTION_HOVER_MOVE)
Jeff Brownb88102f2010-09-08 11:49:43 -0700344 && deviceId == mThrottleState.lastDeviceId
345 && source == mThrottleState.lastSource) {
346 nsecs_t nextTime = mThrottleState.lastEventTime
347 + mThrottleState.minTimeBetweenEvents;
348 if (currentTime < nextTime) {
349 // Throttle it!
350#if DEBUG_THROTTLING
351 LOGD("Throttling - Delaying motion event for "
Jeff Brown90655042010-12-02 13:50:46 -0800352 "device %d, source 0x%08x by up to %0.3fms.",
Jeff Brownb88102f2010-09-08 11:49:43 -0700353 deviceId, source, (nextTime - currentTime) * 0.000001);
354#endif
355 if (nextTime < *nextWakeupTime) {
356 *nextWakeupTime = nextTime;
357 }
358 if (mThrottleState.originalSampleCount == 0) {
359 mThrottleState.originalSampleCount =
360 motionEntry->countSamples();
361 }
362 return;
363 }
364 }
365
366#if DEBUG_THROTTLING
367 if (mThrottleState.originalSampleCount != 0) {
368 uint32_t count = motionEntry->countSamples();
369 LOGD("Throttling - Motion event sample count grew by %d from %d to %d.",
370 count - mThrottleState.originalSampleCount,
371 mThrottleState.originalSampleCount, count);
372 mThrottleState.originalSampleCount = 0;
373 }
374#endif
375
makarand.karvekarf634ded2011-03-02 15:41:03 -0600376 mThrottleState.lastEventTime = currentTime;
Jeff Brownb88102f2010-09-08 11:49:43 -0700377 mThrottleState.lastDeviceId = deviceId;
378 mThrottleState.lastSource = source;
379 }
380
381 mInboundQueue.dequeue(entry);
382 mPendingEvent = entry;
383 }
Jeff Browne2fe69e2010-10-18 13:21:23 -0700384
385 // Poke user activity for this event.
386 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
387 pokeUserActivityLocked(mPendingEvent);
388 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700389 }
390
391 // Now we have an event to dispatch.
Jeff Brown928e0542011-01-10 11:17:36 -0800392 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Jeff Brownb6110c22011-04-01 16:15:13 -0700393 LOG_ASSERT(mPendingEvent != NULL);
Jeff Brown54a18252010-09-16 14:07:33 -0700394 bool done = false;
Jeff Brownb6997262010-10-08 22:31:17 -0700395 DropReason dropReason = DROP_REASON_NOT_DROPPED;
396 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
397 dropReason = DROP_REASON_POLICY;
398 } else if (!mDispatchEnabled) {
399 dropReason = DROP_REASON_DISABLED;
400 }
Jeff Brown928e0542011-01-10 11:17:36 -0800401
402 if (mNextUnblockedEvent == mPendingEvent) {
403 mNextUnblockedEvent = NULL;
404 }
405
Jeff Brownb88102f2010-09-08 11:49:43 -0700406 switch (mPendingEvent->type) {
407 case EventEntry::TYPE_CONFIGURATION_CHANGED: {
408 ConfigurationChangedEntry* typedEntry =
409 static_cast<ConfigurationChangedEntry*>(mPendingEvent);
Jeff Brown54a18252010-09-16 14:07:33 -0700410 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Jeff Brownb6997262010-10-08 22:31:17 -0700411 dropReason = DROP_REASON_NOT_DROPPED; // configuration changes are never dropped
Jeff Brownb88102f2010-09-08 11:49:43 -0700412 break;
413 }
414
415 case EventEntry::TYPE_KEY: {
416 KeyEntry* typedEntry = static_cast<KeyEntry*>(mPendingEvent);
Jeff Brownb6997262010-10-08 22:31:17 -0700417 if (isAppSwitchDue) {
418 if (isAppSwitchKeyEventLocked(typedEntry)) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700419 resetPendingAppSwitchLocked(true);
Jeff Brownb6997262010-10-08 22:31:17 -0700420 isAppSwitchDue = false;
421 } else if (dropReason == DROP_REASON_NOT_DROPPED) {
422 dropReason = DROP_REASON_APP_SWITCH;
Jeff Brownb88102f2010-09-08 11:49:43 -0700423 }
424 }
Jeff Brown928e0542011-01-10 11:17:36 -0800425 if (dropReason == DROP_REASON_NOT_DROPPED
426 && isStaleEventLocked(currentTime, typedEntry)) {
427 dropReason = DROP_REASON_STALE;
428 }
429 if (dropReason == DROP_REASON_NOT_DROPPED && mNextUnblockedEvent) {
430 dropReason = DROP_REASON_BLOCKED;
431 }
Jeff Brown214eaf42011-05-26 19:17:02 -0700432 done = dispatchKeyLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700433 break;
434 }
435
436 case EventEntry::TYPE_MOTION: {
437 MotionEntry* typedEntry = static_cast<MotionEntry*>(mPendingEvent);
Jeff Brownb6997262010-10-08 22:31:17 -0700438 if (dropReason == DROP_REASON_NOT_DROPPED && isAppSwitchDue) {
439 dropReason = DROP_REASON_APP_SWITCH;
Jeff Brownb88102f2010-09-08 11:49:43 -0700440 }
Jeff Brown928e0542011-01-10 11:17:36 -0800441 if (dropReason == DROP_REASON_NOT_DROPPED
442 && isStaleEventLocked(currentTime, typedEntry)) {
443 dropReason = DROP_REASON_STALE;
444 }
445 if (dropReason == DROP_REASON_NOT_DROPPED && mNextUnblockedEvent) {
446 dropReason = DROP_REASON_BLOCKED;
447 }
Jeff Brownb6997262010-10-08 22:31:17 -0700448 done = dispatchMotionLocked(currentTime, typedEntry,
Jeff Browne20c9e02010-10-11 14:20:19 -0700449 &dropReason, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700450 break;
451 }
452
453 default:
Jeff Brownb6110c22011-04-01 16:15:13 -0700454 LOG_ASSERT(false);
Jeff Brownb88102f2010-09-08 11:49:43 -0700455 break;
456 }
457
Jeff Brown54a18252010-09-16 14:07:33 -0700458 if (done) {
Jeff Brownb6997262010-10-08 22:31:17 -0700459 if (dropReason != DROP_REASON_NOT_DROPPED) {
460 dropInboundEventLocked(mPendingEvent, dropReason);
461 }
462
Jeff Brown54a18252010-09-16 14:07:33 -0700463 releasePendingEventLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -0700464 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
465 }
466}
467
468bool InputDispatcher::enqueueInboundEventLocked(EventEntry* entry) {
469 bool needWake = mInboundQueue.isEmpty();
470 mInboundQueue.enqueueAtTail(entry);
471
472 switch (entry->type) {
Jeff Brownb6997262010-10-08 22:31:17 -0700473 case EventEntry::TYPE_KEY: {
Jeff Brown928e0542011-01-10 11:17:36 -0800474 // Optimize app switch latency.
475 // If the application takes too long to catch up then we drop all events preceding
476 // the app switch key.
Jeff Brownb6997262010-10-08 22:31:17 -0700477 KeyEntry* keyEntry = static_cast<KeyEntry*>(entry);
478 if (isAppSwitchKeyEventLocked(keyEntry)) {
479 if (keyEntry->action == AKEY_EVENT_ACTION_DOWN) {
480 mAppSwitchSawKeyDown = true;
481 } else if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
482 if (mAppSwitchSawKeyDown) {
483#if DEBUG_APP_SWITCH
484 LOGD("App switch is pending!");
485#endif
486 mAppSwitchDueTime = keyEntry->eventTime + APP_SWITCH_TIMEOUT;
487 mAppSwitchSawKeyDown = false;
488 needWake = true;
489 }
490 }
491 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700492 break;
493 }
Jeff Brown928e0542011-01-10 11:17:36 -0800494
495 case EventEntry::TYPE_MOTION: {
496 // Optimize case where the current application is unresponsive and the user
497 // decides to touch a window in a different application.
498 // If the application takes too long to catch up then we drop all events preceding
499 // the touch into the other window.
500 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
Jeff Brown33bbfd22011-02-24 20:55:35 -0800501 if (motionEntry->action == AMOTION_EVENT_ACTION_DOWN
Jeff Brown928e0542011-01-10 11:17:36 -0800502 && (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER)
503 && mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY
504 && mInputTargetWaitApplication != NULL) {
Jeff Brown91c69ab2011-02-14 17:03:18 -0800505 int32_t x = int32_t(motionEntry->firstSample.pointerCoords[0].
Jeff Brownebbd5d12011-02-17 13:01:34 -0800506 getAxisValue(AMOTION_EVENT_AXIS_X));
Jeff Brown91c69ab2011-02-14 17:03:18 -0800507 int32_t y = int32_t(motionEntry->firstSample.pointerCoords[0].
Jeff Brownebbd5d12011-02-17 13:01:34 -0800508 getAxisValue(AMOTION_EVENT_AXIS_Y));
Jeff Brown928e0542011-01-10 11:17:36 -0800509 const InputWindow* touchedWindow = findTouchedWindowAtLocked(x, y);
510 if (touchedWindow
511 && touchedWindow->inputWindowHandle != NULL
512 && touchedWindow->inputWindowHandle->getInputApplicationHandle()
513 != mInputTargetWaitApplication) {
514 // User touched a different application than the one we are waiting on.
515 // Flag the event, and start pruning the input queue.
516 mNextUnblockedEvent = motionEntry;
517 needWake = true;
518 }
519 }
520 break;
521 }
Jeff Brownb6997262010-10-08 22:31:17 -0700522 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700523
524 return needWake;
525}
526
Jeff Brown928e0542011-01-10 11:17:36 -0800527const InputWindow* InputDispatcher::findTouchedWindowAtLocked(int32_t x, int32_t y) {
528 // Traverse windows from front to back to find touched window.
529 size_t numWindows = mWindows.size();
530 for (size_t i = 0; i < numWindows; i++) {
531 const InputWindow* window = & mWindows.editItemAt(i);
532 int32_t flags = window->layoutParamsFlags;
533
534 if (window->visible) {
535 if (!(flags & InputWindow::FLAG_NOT_TOUCHABLE)) {
536 bool isTouchModal = (flags & (InputWindow::FLAG_NOT_FOCUSABLE
537 | InputWindow::FLAG_NOT_TOUCH_MODAL)) == 0;
Jeff Brownfbf09772011-01-16 14:06:57 -0800538 if (isTouchModal || window->touchableRegionContainsPoint(x, y)) {
Jeff Brown928e0542011-01-10 11:17:36 -0800539 // Found window.
540 return window;
541 }
542 }
543 }
544
545 if (flags & InputWindow::FLAG_SYSTEM_ERROR) {
546 // Error window is on top but not visible, so touch is dropped.
547 return NULL;
548 }
549 }
550 return NULL;
551}
552
Jeff Brownb6997262010-10-08 22:31:17 -0700553void InputDispatcher::dropInboundEventLocked(EventEntry* entry, DropReason dropReason) {
554 const char* reason;
555 switch (dropReason) {
556 case DROP_REASON_POLICY:
Jeff Browne20c9e02010-10-11 14:20:19 -0700557#if DEBUG_INBOUND_EVENT_DETAILS
Jeff Brown3122e442010-10-11 23:32:49 -0700558 LOGD("Dropped event because policy consumed it.");
Jeff Browne20c9e02010-10-11 14:20:19 -0700559#endif
Jeff Brown3122e442010-10-11 23:32:49 -0700560 reason = "inbound event was dropped because the policy consumed it";
Jeff Brownb6997262010-10-08 22:31:17 -0700561 break;
562 case DROP_REASON_DISABLED:
563 LOGI("Dropped event because input dispatch is disabled.");
564 reason = "inbound event was dropped because input dispatch is disabled";
565 break;
566 case DROP_REASON_APP_SWITCH:
567 LOGI("Dropped event because of pending overdue app switch.");
568 reason = "inbound event was dropped because of pending overdue app switch";
569 break;
Jeff Brown928e0542011-01-10 11:17:36 -0800570 case DROP_REASON_BLOCKED:
571 LOGI("Dropped event because the current application is not responding and the user "
572 "has started interating with a different application.");
573 reason = "inbound event was dropped because the current application is not responding "
574 "and the user has started interating with a different application";
575 break;
576 case DROP_REASON_STALE:
577 LOGI("Dropped event because it is stale.");
578 reason = "inbound event was dropped because it is stale";
579 break;
Jeff Brownb6997262010-10-08 22:31:17 -0700580 default:
Jeff Brownb6110c22011-04-01 16:15:13 -0700581 LOG_ASSERT(false);
Jeff Brownb6997262010-10-08 22:31:17 -0700582 return;
583 }
584
585 switch (entry->type) {
Jeff Brownda3d5a92011-03-29 15:11:34 -0700586 case EventEntry::TYPE_KEY: {
587 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
588 synthesizeCancelationEventsForAllConnectionsLocked(options);
Jeff Brownb6997262010-10-08 22:31:17 -0700589 break;
Jeff Brownda3d5a92011-03-29 15:11:34 -0700590 }
Jeff Brownb6997262010-10-08 22:31:17 -0700591 case EventEntry::TYPE_MOTION: {
592 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
593 if (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) {
Jeff Brownda3d5a92011-03-29 15:11:34 -0700594 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
595 synthesizeCancelationEventsForAllConnectionsLocked(options);
Jeff Brownb6997262010-10-08 22:31:17 -0700596 } else {
Jeff Brownda3d5a92011-03-29 15:11:34 -0700597 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
598 synthesizeCancelationEventsForAllConnectionsLocked(options);
Jeff Brownb6997262010-10-08 22:31:17 -0700599 }
600 break;
601 }
602 }
603}
604
605bool InputDispatcher::isAppSwitchKeyCode(int32_t keyCode) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700606 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL;
607}
608
Jeff Brownb6997262010-10-08 22:31:17 -0700609bool InputDispatcher::isAppSwitchKeyEventLocked(KeyEntry* keyEntry) {
610 return ! (keyEntry->flags & AKEY_EVENT_FLAG_CANCELED)
611 && isAppSwitchKeyCode(keyEntry->keyCode)
Jeff Browne20c9e02010-10-11 14:20:19 -0700612 && (keyEntry->policyFlags & POLICY_FLAG_TRUSTED)
Jeff Brownb6997262010-10-08 22:31:17 -0700613 && (keyEntry->policyFlags & POLICY_FLAG_PASS_TO_USER);
614}
615
Jeff Brownb88102f2010-09-08 11:49:43 -0700616bool InputDispatcher::isAppSwitchPendingLocked() {
617 return mAppSwitchDueTime != LONG_LONG_MAX;
618}
619
Jeff Brownb88102f2010-09-08 11:49:43 -0700620void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
621 mAppSwitchDueTime = LONG_LONG_MAX;
622
623#if DEBUG_APP_SWITCH
624 if (handled) {
625 LOGD("App switch has arrived.");
626 } else {
627 LOGD("App switch was abandoned.");
628 }
629#endif
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700630}
631
Jeff Brown928e0542011-01-10 11:17:36 -0800632bool InputDispatcher::isStaleEventLocked(nsecs_t currentTime, EventEntry* entry) {
633 return currentTime - entry->eventTime >= STALE_EVENT_TIMEOUT;
634}
635
Jeff Brown9c3cda02010-06-15 01:31:58 -0700636bool InputDispatcher::runCommandsLockedInterruptible() {
637 if (mCommandQueue.isEmpty()) {
638 return false;
639 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700640
Jeff Brown9c3cda02010-06-15 01:31:58 -0700641 do {
642 CommandEntry* commandEntry = mCommandQueue.dequeueAtHead();
643
644 Command command = commandEntry->command;
645 (this->*command)(commandEntry); // commands are implicitly 'LockedInterruptible'
646
Jeff Brown7fbdc842010-06-17 20:52:56 -0700647 commandEntry->connection.clear();
Jeff Brown9c3cda02010-06-15 01:31:58 -0700648 mAllocator.releaseCommandEntry(commandEntry);
649 } while (! mCommandQueue.isEmpty());
650 return true;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700651}
652
Jeff Brown9c3cda02010-06-15 01:31:58 -0700653InputDispatcher::CommandEntry* InputDispatcher::postCommandLocked(Command command) {
654 CommandEntry* commandEntry = mAllocator.obtainCommandEntry(command);
655 mCommandQueue.enqueueAtTail(commandEntry);
656 return commandEntry;
657}
658
Jeff Brownb88102f2010-09-08 11:49:43 -0700659void InputDispatcher::drainInboundQueueLocked() {
660 while (! mInboundQueue.isEmpty()) {
661 EventEntry* entry = mInboundQueue.dequeueAtHead();
Jeff Brown54a18252010-09-16 14:07:33 -0700662 releaseInboundEventLocked(entry);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700663 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700664}
665
Jeff Brown54a18252010-09-16 14:07:33 -0700666void InputDispatcher::releasePendingEventLocked() {
Jeff Brownb88102f2010-09-08 11:49:43 -0700667 if (mPendingEvent) {
Jeff Brown54a18252010-09-16 14:07:33 -0700668 releaseInboundEventLocked(mPendingEvent);
Jeff Brownb88102f2010-09-08 11:49:43 -0700669 mPendingEvent = NULL;
670 }
671}
672
Jeff Brown54a18252010-09-16 14:07:33 -0700673void InputDispatcher::releaseInboundEventLocked(EventEntry* entry) {
Jeff Brown01ce2e92010-09-26 22:20:12 -0700674 InjectionState* injectionState = entry->injectionState;
675 if (injectionState && injectionState->injectionResult == INPUT_EVENT_INJECTION_PENDING) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700676#if DEBUG_DISPATCH_CYCLE
Jeff Brown01ce2e92010-09-26 22:20:12 -0700677 LOGD("Injected inbound event was dropped.");
Jeff Brownb88102f2010-09-08 11:49:43 -0700678#endif
679 setInjectionResultLocked(entry, INPUT_EVENT_INJECTION_FAILED);
680 }
681 mAllocator.releaseEventEntry(entry);
682}
683
Jeff Brownb88102f2010-09-08 11:49:43 -0700684void InputDispatcher::resetKeyRepeatLocked() {
685 if (mKeyRepeatState.lastKeyEntry) {
686 mAllocator.releaseKeyEntry(mKeyRepeatState.lastKeyEntry);
687 mKeyRepeatState.lastKeyEntry = NULL;
688 }
689}
690
Jeff Brown214eaf42011-05-26 19:17:02 -0700691InputDispatcher::KeyEntry* InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
Jeff Brown349703e2010-06-22 01:27:15 -0700692 KeyEntry* entry = mKeyRepeatState.lastKeyEntry;
693
Jeff Brown349703e2010-06-22 01:27:15 -0700694 // Reuse the repeated key entry if it is otherwise unreferenced.
Jeff Browne20c9e02010-10-11 14:20:19 -0700695 uint32_t policyFlags = (entry->policyFlags & POLICY_FLAG_RAW_MASK)
696 | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700697 if (entry->refCount == 1) {
Jeff Brown01ce2e92010-09-26 22:20:12 -0700698 mAllocator.recycleKeyEntry(entry);
Jeff Brown7fbdc842010-06-17 20:52:56 -0700699 entry->eventTime = currentTime;
Jeff Brown7fbdc842010-06-17 20:52:56 -0700700 entry->policyFlags = policyFlags;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700701 entry->repeatCount += 1;
702 } else {
Jeff Brown7fbdc842010-06-17 20:52:56 -0700703 KeyEntry* newEntry = mAllocator.obtainKeyEntry(currentTime,
Jeff Brownc5ed5912010-07-14 18:48:53 -0700704 entry->deviceId, entry->source, policyFlags,
Jeff Brown7fbdc842010-06-17 20:52:56 -0700705 entry->action, entry->flags, entry->keyCode, entry->scanCode,
Jeff Brown00fa7bd2010-07-02 15:37:36 -0700706 entry->metaState, entry->repeatCount + 1, entry->downTime);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700707
708 mKeyRepeatState.lastKeyEntry = newEntry;
709 mAllocator.releaseKeyEntry(entry);
710
711 entry = newEntry;
712 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700713 entry->syntheticRepeat = true;
714
715 // Increment reference count since we keep a reference to the event in
716 // mKeyRepeatState.lastKeyEntry in addition to the one we return.
717 entry->refCount += 1;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700718
Jeff Brown214eaf42011-05-26 19:17:02 -0700719 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Jeff Brownb88102f2010-09-08 11:49:43 -0700720 return entry;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700721}
722
Jeff Brownb88102f2010-09-08 11:49:43 -0700723bool InputDispatcher::dispatchConfigurationChangedLocked(
724 nsecs_t currentTime, ConfigurationChangedEntry* entry) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700725#if DEBUG_OUTBOUND_EVENT_DETAILS
Jeff Brownb88102f2010-09-08 11:49:43 -0700726 LOGD("dispatchConfigurationChanged - eventTime=%lld", entry->eventTime);
727#endif
728
729 // Reset key repeating in case a keyboard device was added or removed or something.
730 resetKeyRepeatLocked();
731
732 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
733 CommandEntry* commandEntry = postCommandLocked(
734 & InputDispatcher::doNotifyConfigurationChangedInterruptible);
735 commandEntry->eventTime = entry->eventTime;
736 return true;
737}
738
Jeff Brown214eaf42011-05-26 19:17:02 -0700739bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, KeyEntry* entry,
Jeff Browne20c9e02010-10-11 14:20:19 -0700740 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Jeff Browne46a0a42010-11-02 17:58:22 -0700741 // Preprocessing.
742 if (! entry->dispatchInProgress) {
743 if (entry->repeatCount == 0
744 && entry->action == AKEY_EVENT_ACTION_DOWN
745 && (entry->policyFlags & POLICY_FLAG_TRUSTED)
Jeff Brown0029c662011-03-30 02:25:18 -0700746 && (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
Jeff Browne46a0a42010-11-02 17:58:22 -0700747 if (mKeyRepeatState.lastKeyEntry
748 && mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode) {
749 // We have seen two identical key downs in a row which indicates that the device
750 // driver is automatically generating key repeats itself. We take note of the
751 // repeat here, but we disable our own next key repeat timer since it is clear that
752 // we will not need to synthesize key repeats ourselves.
753 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
754 resetKeyRepeatLocked();
755 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
756 } else {
757 // Not a repeat. Save key down state in case we do see a repeat later.
758 resetKeyRepeatLocked();
Jeff Brown214eaf42011-05-26 19:17:02 -0700759 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
Jeff Browne46a0a42010-11-02 17:58:22 -0700760 }
761 mKeyRepeatState.lastKeyEntry = entry;
762 entry->refCount += 1;
763 } else if (! entry->syntheticRepeat) {
764 resetKeyRepeatLocked();
765 }
766
Jeff Browne2e01262011-03-02 20:34:30 -0800767 if (entry->repeatCount == 1) {
768 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
769 } else {
770 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
771 }
772
Jeff Browne46a0a42010-11-02 17:58:22 -0700773 entry->dispatchInProgress = true;
774 resetTargetsLocked();
775
776 logOutboundKeyDetailsLocked("dispatchKey - ", entry);
777 }
778
Jeff Brown54a18252010-09-16 14:07:33 -0700779 // Give the policy a chance to intercept the key.
780 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
Jeff Browne20c9e02010-10-11 14:20:19 -0700781 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Jeff Brown54a18252010-09-16 14:07:33 -0700782 CommandEntry* commandEntry = postCommandLocked(
783 & InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
Jeff Browne20c9e02010-10-11 14:20:19 -0700784 if (mFocusedWindow) {
Jeff Brown928e0542011-01-10 11:17:36 -0800785 commandEntry->inputWindowHandle = mFocusedWindow->inputWindowHandle;
Jeff Brown54a18252010-09-16 14:07:33 -0700786 }
787 commandEntry->keyEntry = entry;
788 entry->refCount += 1;
789 return false; // wait for the command to run
790 } else {
791 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
792 }
793 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Jeff Browne20c9e02010-10-11 14:20:19 -0700794 if (*dropReason == DROP_REASON_NOT_DROPPED) {
795 *dropReason = DROP_REASON_POLICY;
796 }
Jeff Brown54a18252010-09-16 14:07:33 -0700797 }
798
799 // Clean up if dropping the event.
Jeff Browne20c9e02010-10-11 14:20:19 -0700800 if (*dropReason != DROP_REASON_NOT_DROPPED) {
Jeff Brown54a18252010-09-16 14:07:33 -0700801 resetTargetsLocked();
Jeff Brown3122e442010-10-11 23:32:49 -0700802 setInjectionResultLocked(entry, *dropReason == DROP_REASON_POLICY
803 ? INPUT_EVENT_INJECTION_SUCCEEDED : INPUT_EVENT_INJECTION_FAILED);
Jeff Brown54a18252010-09-16 14:07:33 -0700804 return true;
805 }
806
Jeff Brownb88102f2010-09-08 11:49:43 -0700807 // Identify targets.
808 if (! mCurrentInputTargetsValid) {
Jeff Brown01ce2e92010-09-26 22:20:12 -0700809 int32_t injectionResult = findFocusedWindowTargetsLocked(currentTime,
810 entry, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700811 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
812 return false;
813 }
814
815 setInjectionResultLocked(entry, injectionResult);
816 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
817 return true;
818 }
819
820 addMonitoringTargetsLocked();
Jeff Brown01ce2e92010-09-26 22:20:12 -0700821 commitTargetsLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -0700822 }
823
824 // Dispatch the key.
825 dispatchEventToCurrentInputTargetsLocked(currentTime, entry, false);
Jeff Brownb88102f2010-09-08 11:49:43 -0700826 return true;
827}
828
829void InputDispatcher::logOutboundKeyDetailsLocked(const char* prefix, const KeyEntry* entry) {
830#if DEBUG_OUTBOUND_EVENT_DETAILS
Jeff Brown90655042010-12-02 13:50:46 -0800831 LOGD("%seventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, "
Jeff Brownb88102f2010-09-08 11:49:43 -0700832 "action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, "
Jeff Browne46a0a42010-11-02 17:58:22 -0700833 "repeatCount=%d, downTime=%lld",
Jeff Brownb88102f2010-09-08 11:49:43 -0700834 prefix,
835 entry->eventTime, entry->deviceId, entry->source, entry->policyFlags,
836 entry->action, entry->flags, entry->keyCode, entry->scanCode, entry->metaState,
Jeff Browne46a0a42010-11-02 17:58:22 -0700837 entry->repeatCount, entry->downTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700838#endif
839}
840
841bool InputDispatcher::dispatchMotionLocked(
Jeff Browne20c9e02010-10-11 14:20:19 -0700842 nsecs_t currentTime, MotionEntry* entry, DropReason* dropReason, nsecs_t* nextWakeupTime) {
Jeff Browne46a0a42010-11-02 17:58:22 -0700843 // Preprocessing.
844 if (! entry->dispatchInProgress) {
845 entry->dispatchInProgress = true;
846 resetTargetsLocked();
847
848 logOutboundMotionDetailsLocked("dispatchMotion - ", entry);
849 }
850
Jeff Brown54a18252010-09-16 14:07:33 -0700851 // Clean up if dropping the event.
Jeff Browne20c9e02010-10-11 14:20:19 -0700852 if (*dropReason != DROP_REASON_NOT_DROPPED) {
Jeff Brown54a18252010-09-16 14:07:33 -0700853 resetTargetsLocked();
Jeff Brown3122e442010-10-11 23:32:49 -0700854 setInjectionResultLocked(entry, *dropReason == DROP_REASON_POLICY
855 ? INPUT_EVENT_INJECTION_SUCCEEDED : INPUT_EVENT_INJECTION_FAILED);
Jeff Brown54a18252010-09-16 14:07:33 -0700856 return true;
857 }
858
Jeff Brownb88102f2010-09-08 11:49:43 -0700859 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
860
861 // Identify targets.
Jeff Browncc0c1592011-02-19 05:07:28 -0800862 bool conflictingPointerActions = false;
Jeff Brownb88102f2010-09-08 11:49:43 -0700863 if (! mCurrentInputTargetsValid) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700864 int32_t injectionResult;
Jeff Browna032cc02011-03-07 16:56:21 -0800865 const MotionSample* splitBatchAfterSample = NULL;
Jeff Brownb88102f2010-09-08 11:49:43 -0700866 if (isPointerEvent) {
867 // Pointer event. (eg. touchscreen)
Jeff Brown01ce2e92010-09-26 22:20:12 -0700868 injectionResult = findTouchedWindowTargetsLocked(currentTime,
Jeff Browna032cc02011-03-07 16:56:21 -0800869 entry, nextWakeupTime, &conflictingPointerActions, &splitBatchAfterSample);
Jeff Brownb88102f2010-09-08 11:49:43 -0700870 } else {
871 // Non touch event. (eg. trackball)
Jeff Brown01ce2e92010-09-26 22:20:12 -0700872 injectionResult = findFocusedWindowTargetsLocked(currentTime,
873 entry, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700874 }
875 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
876 return false;
877 }
878
879 setInjectionResultLocked(entry, injectionResult);
880 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
881 return true;
882 }
883
884 addMonitoringTargetsLocked();
Jeff Brown01ce2e92010-09-26 22:20:12 -0700885 commitTargetsLocked();
Jeff Browna032cc02011-03-07 16:56:21 -0800886
887 // Unbatch the event if necessary by splitting it into two parts after the
888 // motion sample indicated by splitBatchAfterSample.
889 if (splitBatchAfterSample && splitBatchAfterSample->next) {
890#if DEBUG_BATCHING
891 uint32_t originalSampleCount = entry->countSamples();
892#endif
893 MotionSample* nextSample = splitBatchAfterSample->next;
894 MotionEntry* nextEntry = mAllocator.obtainMotionEntry(nextSample->eventTime,
895 entry->deviceId, entry->source, entry->policyFlags,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700896 entry->action, entry->flags,
897 entry->metaState, entry->buttonState, entry->edgeFlags,
Jeff Browna032cc02011-03-07 16:56:21 -0800898 entry->xPrecision, entry->yPrecision, entry->downTime,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700899 entry->pointerCount, entry->pointerProperties, nextSample->pointerCoords);
Jeff Browna032cc02011-03-07 16:56:21 -0800900 if (nextSample != entry->lastSample) {
901 nextEntry->firstSample.next = nextSample->next;
902 nextEntry->lastSample = entry->lastSample;
903 }
904 mAllocator.freeMotionSample(nextSample);
905
906 entry->lastSample = const_cast<MotionSample*>(splitBatchAfterSample);
907 entry->lastSample->next = NULL;
908
909 if (entry->injectionState) {
910 nextEntry->injectionState = entry->injectionState;
911 entry->injectionState->refCount += 1;
912 }
913
914#if DEBUG_BATCHING
915 LOGD("Split batch of %d samples into two parts, first part has %d samples, "
916 "second part has %d samples.", originalSampleCount,
917 entry->countSamples(), nextEntry->countSamples());
918#endif
919
920 mInboundQueue.enqueueAtHead(nextEntry);
921 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700922 }
923
924 // Dispatch the motion.
Jeff Browncc0c1592011-02-19 05:07:28 -0800925 if (conflictingPointerActions) {
Jeff Brownda3d5a92011-03-29 15:11:34 -0700926 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
927 "conflicting pointer actions");
928 synthesizeCancelationEventsForAllConnectionsLocked(options);
Jeff Browncc0c1592011-02-19 05:07:28 -0800929 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700930 dispatchEventToCurrentInputTargetsLocked(currentTime, entry, false);
Jeff Brownb88102f2010-09-08 11:49:43 -0700931 return true;
932}
933
934
935void InputDispatcher::logOutboundMotionDetailsLocked(const char* prefix, const MotionEntry* entry) {
936#if DEBUG_OUTBOUND_EVENT_DETAILS
Jeff Brown90655042010-12-02 13:50:46 -0800937 LOGD("%seventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, "
Jeff Brown85a31762010-09-01 17:01:00 -0700938 "action=0x%x, flags=0x%x, "
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700939 "metaState=0x%x, buttonState=0x%x, "
940 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%lld",
Jeff Brownb88102f2010-09-08 11:49:43 -0700941 prefix,
Jeff Brown85a31762010-09-01 17:01:00 -0700942 entry->eventTime, entry->deviceId, entry->source, entry->policyFlags,
943 entry->action, entry->flags,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700944 entry->metaState, entry->buttonState,
945 entry->edgeFlags, entry->xPrecision, entry->yPrecision,
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700946 entry->downTime);
947
948 // Print the most recent sample that we have available, this may change due to batching.
949 size_t sampleCount = 1;
Jeff Brownb88102f2010-09-08 11:49:43 -0700950 const MotionSample* sample = & entry->firstSample;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700951 for (; sample->next != NULL; sample = sample->next) {
952 sampleCount += 1;
953 }
954 for (uint32_t i = 0; i < entry->pointerCount; i++) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700955 LOGD(" Pointer %d: id=%d, toolType=%d, "
956 "x=%f, y=%f, pressure=%f, size=%f, "
Jeff Brown85a31762010-09-01 17:01:00 -0700957 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
Jeff Brown8d608662010-08-30 03:02:23 -0700958 "orientation=%f",
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700959 i, entry->pointerProperties[i].id,
960 entry->pointerProperties[i].toolType,
Jeff Brownebbd5d12011-02-17 13:01:34 -0800961 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
962 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
963 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
964 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
965 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
966 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
967 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
968 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
969 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700970 }
971
972 // Keep in mind that due to batching, it is possible for the number of samples actually
973 // dispatched to change before the application finally consumed them.
Jeff Brownc5ed5912010-07-14 18:48:53 -0700974 if (entry->action == AMOTION_EVENT_ACTION_MOVE) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700975 LOGD(" ... Total movement samples currently batched %d ...", sampleCount);
976 }
977#endif
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700978}
979
980void InputDispatcher::dispatchEventToCurrentInputTargetsLocked(nsecs_t currentTime,
981 EventEntry* eventEntry, bool resumeWithAppendedMotionSample) {
982#if DEBUG_DISPATCH_CYCLE
Jeff Brown9c3cda02010-06-15 01:31:58 -0700983 LOGD("dispatchEventToCurrentInputTargets - "
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700984 "resumeWithAppendedMotionSample=%s",
Jeff Brownb88102f2010-09-08 11:49:43 -0700985 toString(resumeWithAppendedMotionSample));
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700986#endif
987
Jeff Brownb6110c22011-04-01 16:15:13 -0700988 LOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
Jeff Brown9c3cda02010-06-15 01:31:58 -0700989
Jeff Browne2fe69e2010-10-18 13:21:23 -0700990 pokeUserActivityLocked(eventEntry);
991
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700992 for (size_t i = 0; i < mCurrentInputTargets.size(); i++) {
993 const InputTarget& inputTarget = mCurrentInputTargets.itemAt(i);
994
Jeff Brown519e0242010-09-15 15:18:56 -0700995 ssize_t connectionIndex = getConnectionIndexLocked(inputTarget.inputChannel);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700996 if (connectionIndex >= 0) {
997 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
Jeff Brown7fbdc842010-06-17 20:52:56 -0700998 prepareDispatchCycleLocked(currentTime, connection, eventEntry, & inputTarget,
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700999 resumeWithAppendedMotionSample);
1000 } else {
Jeff Brownb6997262010-10-08 22:31:17 -07001001#if DEBUG_FOCUS
1002 LOGD("Dropping event delivery to target with channel '%s' because it "
1003 "is no longer registered with the input dispatcher.",
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001004 inputTarget.inputChannel->getName().string());
Jeff Brownb6997262010-10-08 22:31:17 -07001005#endif
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001006 }
1007 }
1008}
1009
Jeff Brown54a18252010-09-16 14:07:33 -07001010void InputDispatcher::resetTargetsLocked() {
Jeff Brownb88102f2010-09-08 11:49:43 -07001011 mCurrentInputTargetsValid = false;
1012 mCurrentInputTargets.clear();
Jeff Brownb88102f2010-09-08 11:49:43 -07001013 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_NONE;
Jeff Brown928e0542011-01-10 11:17:36 -08001014 mInputTargetWaitApplication.clear();
Jeff Brownb88102f2010-09-08 11:49:43 -07001015}
1016
Jeff Brown01ce2e92010-09-26 22:20:12 -07001017void InputDispatcher::commitTargetsLocked() {
Jeff Brownb88102f2010-09-08 11:49:43 -07001018 mCurrentInputTargetsValid = true;
1019}
1020
1021int32_t InputDispatcher::handleTargetsNotReadyLocked(nsecs_t currentTime,
1022 const EventEntry* entry, const InputApplication* application, const InputWindow* window,
1023 nsecs_t* nextWakeupTime) {
1024 if (application == NULL && window == NULL) {
1025 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY) {
1026#if DEBUG_FOCUS
1027 LOGD("Waiting for system to become ready for input.");
1028#endif
1029 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY;
1030 mInputTargetWaitStartTime = currentTime;
1031 mInputTargetWaitTimeoutTime = LONG_LONG_MAX;
1032 mInputTargetWaitTimeoutExpired = false;
Jeff Brown928e0542011-01-10 11:17:36 -08001033 mInputTargetWaitApplication.clear();
Jeff Brownb88102f2010-09-08 11:49:43 -07001034 }
1035 } else {
1036 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
1037#if DEBUG_FOCUS
Jeff Brown519e0242010-09-15 15:18:56 -07001038 LOGD("Waiting for application to become ready for input: %s",
1039 getApplicationWindowLabelLocked(application, window).string());
Jeff Brownb88102f2010-09-08 11:49:43 -07001040#endif
1041 nsecs_t timeout = window ? window->dispatchingTimeout :
1042 application ? application->dispatchingTimeout : DEFAULT_INPUT_DISPATCHING_TIMEOUT;
1043
1044 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY;
1045 mInputTargetWaitStartTime = currentTime;
1046 mInputTargetWaitTimeoutTime = currentTime + timeout;
1047 mInputTargetWaitTimeoutExpired = false;
Jeff Brown928e0542011-01-10 11:17:36 -08001048 mInputTargetWaitApplication.clear();
1049
1050 if (window && window->inputWindowHandle != NULL) {
1051 mInputTargetWaitApplication =
1052 window->inputWindowHandle->getInputApplicationHandle();
1053 }
1054 if (mInputTargetWaitApplication == NULL && application) {
1055 mInputTargetWaitApplication = application->inputApplicationHandle;
1056 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001057 }
1058 }
1059
1060 if (mInputTargetWaitTimeoutExpired) {
1061 return INPUT_EVENT_INJECTION_TIMED_OUT;
1062 }
1063
1064 if (currentTime >= mInputTargetWaitTimeoutTime) {
Jeff Brown519e0242010-09-15 15:18:56 -07001065 onANRLocked(currentTime, application, window, entry->eventTime, mInputTargetWaitStartTime);
Jeff Brownb88102f2010-09-08 11:49:43 -07001066
1067 // Force poll loop to wake up immediately on next iteration once we get the
1068 // ANR response back from the policy.
1069 *nextWakeupTime = LONG_LONG_MIN;
1070 return INPUT_EVENT_INJECTION_PENDING;
1071 } else {
1072 // Force poll loop to wake up when timeout is due.
1073 if (mInputTargetWaitTimeoutTime < *nextWakeupTime) {
1074 *nextWakeupTime = mInputTargetWaitTimeoutTime;
1075 }
1076 return INPUT_EVENT_INJECTION_PENDING;
1077 }
1078}
1079
Jeff Brown519e0242010-09-15 15:18:56 -07001080void InputDispatcher::resumeAfterTargetsNotReadyTimeoutLocked(nsecs_t newTimeout,
1081 const sp<InputChannel>& inputChannel) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001082 if (newTimeout > 0) {
1083 // Extend the timeout.
1084 mInputTargetWaitTimeoutTime = now() + newTimeout;
1085 } else {
1086 // Give up.
1087 mInputTargetWaitTimeoutExpired = true;
Jeff Brown519e0242010-09-15 15:18:56 -07001088
Jeff Brown01ce2e92010-09-26 22:20:12 -07001089 // Release the touch targets.
1090 mTouchState.reset();
Jeff Brown2a95c2a2010-09-16 12:31:46 -07001091
Jeff Brown519e0242010-09-15 15:18:56 -07001092 // Input state will not be realistic. Mark it out of sync.
Jeff Browndc3e0052010-09-16 11:02:16 -07001093 if (inputChannel.get()) {
1094 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
1095 if (connectionIndex >= 0) {
1096 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
Jeff Brown00045a72010-12-09 18:10:30 -08001097 if (connection->status == Connection::STATUS_NORMAL) {
Jeff Brownda3d5a92011-03-29 15:11:34 -07001098 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
Jeff Brown00045a72010-12-09 18:10:30 -08001099 "application not responding");
Jeff Brownda3d5a92011-03-29 15:11:34 -07001100 synthesizeCancelationEventsForConnectionLocked(connection, options);
Jeff Brown00045a72010-12-09 18:10:30 -08001101 }
Jeff Browndc3e0052010-09-16 11:02:16 -07001102 }
Jeff Brown519e0242010-09-15 15:18:56 -07001103 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001104 }
1105}
1106
Jeff Brown519e0242010-09-15 15:18:56 -07001107nsecs_t InputDispatcher::getTimeSpentWaitingForApplicationLocked(
Jeff Brownb88102f2010-09-08 11:49:43 -07001108 nsecs_t currentTime) {
1109 if (mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
1110 return currentTime - mInputTargetWaitStartTime;
1111 }
1112 return 0;
1113}
1114
1115void InputDispatcher::resetANRTimeoutsLocked() {
1116#if DEBUG_FOCUS
1117 LOGD("Resetting ANR timeouts.");
1118#endif
1119
Jeff Brownb88102f2010-09-08 11:49:43 -07001120 // Reset input target wait timeout.
1121 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_NONE;
1122}
1123
Jeff Brown01ce2e92010-09-26 22:20:12 -07001124int32_t InputDispatcher::findFocusedWindowTargetsLocked(nsecs_t currentTime,
1125 const EventEntry* entry, nsecs_t* nextWakeupTime) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001126 mCurrentInputTargets.clear();
1127
1128 int32_t injectionResult;
1129
1130 // If there is no currently focused window and no focused application
1131 // then drop the event.
1132 if (! mFocusedWindow) {
1133 if (mFocusedApplication) {
1134#if DEBUG_FOCUS
1135 LOGD("Waiting because there is no focused window but there is a "
Jeff Brown519e0242010-09-15 15:18:56 -07001136 "focused application that may eventually add a window: %s.",
1137 getApplicationWindowLabelLocked(mFocusedApplication, NULL).string());
Jeff Brownb88102f2010-09-08 11:49:43 -07001138#endif
1139 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
1140 mFocusedApplication, NULL, nextWakeupTime);
1141 goto Unresponsive;
1142 }
1143
1144 LOGI("Dropping event because there is no focused window or focused application.");
1145 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1146 goto Failed;
1147 }
1148
1149 // Check permissions.
Jeff Brown01ce2e92010-09-26 22:20:12 -07001150 if (! checkInjectionPermission(mFocusedWindow, entry->injectionState)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001151 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1152 goto Failed;
1153 }
1154
1155 // If the currently focused window is paused then keep waiting.
1156 if (mFocusedWindow->paused) {
1157#if DEBUG_FOCUS
1158 LOGD("Waiting because focused window is paused.");
1159#endif
1160 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
1161 mFocusedApplication, mFocusedWindow, nextWakeupTime);
1162 goto Unresponsive;
1163 }
1164
Jeff Brown519e0242010-09-15 15:18:56 -07001165 // If the currently focused window is still working on previous events then keep waiting.
1166 if (! isWindowFinishedWithPreviousInputLocked(mFocusedWindow)) {
1167#if DEBUG_FOCUS
1168 LOGD("Waiting because focused window still processing previous input.");
1169#endif
1170 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
1171 mFocusedApplication, mFocusedWindow, nextWakeupTime);
1172 goto Unresponsive;
1173 }
1174
Jeff Brownb88102f2010-09-08 11:49:43 -07001175 // Success! Output targets.
1176 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
Jeff Browna032cc02011-03-07 16:56:21 -08001177 addWindowTargetLocked(mFocusedWindow,
1178 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS, BitSet32(0));
Jeff Brownb88102f2010-09-08 11:49:43 -07001179
1180 // Done.
1181Failed:
1182Unresponsive:
Jeff Brown519e0242010-09-15 15:18:56 -07001183 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
1184 updateDispatchStatisticsLocked(currentTime, entry,
1185 injectionResult, timeSpentWaitingForApplication);
Jeff Brownb88102f2010-09-08 11:49:43 -07001186#if DEBUG_FOCUS
Jeff Brown519e0242010-09-15 15:18:56 -07001187 LOGD("findFocusedWindow finished: injectionResult=%d, "
1188 "timeSpendWaitingForApplication=%0.1fms",
1189 injectionResult, timeSpentWaitingForApplication / 1000000.0);
Jeff Brownb88102f2010-09-08 11:49:43 -07001190#endif
1191 return injectionResult;
1192}
1193
Jeff Brown01ce2e92010-09-26 22:20:12 -07001194int32_t InputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime,
Jeff Browna032cc02011-03-07 16:56:21 -08001195 const MotionEntry* entry, nsecs_t* nextWakeupTime, bool* outConflictingPointerActions,
1196 const MotionSample** outSplitBatchAfterSample) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001197 enum InjectionPermission {
1198 INJECTION_PERMISSION_UNKNOWN,
1199 INJECTION_PERMISSION_GRANTED,
1200 INJECTION_PERMISSION_DENIED
1201 };
1202
Jeff Brownb88102f2010-09-08 11:49:43 -07001203 mCurrentInputTargets.clear();
1204
1205 nsecs_t startTime = now();
1206
1207 // For security reasons, we defer updating the touch state until we are sure that
1208 // event injection will be allowed.
1209 //
1210 // FIXME In the original code, screenWasOff could never be set to true.
1211 // The reason is that the POLICY_FLAG_WOKE_HERE
1212 // and POLICY_FLAG_BRIGHT_HERE flags were set only when preprocessing raw
1213 // EV_KEY, EV_REL and EV_ABS events. As it happens, the touch event was
1214 // actually enqueued using the policyFlags that appeared in the final EV_SYN
1215 // events upon which no preprocessing took place. So policyFlags was always 0.
1216 // In the new native input dispatcher we're a bit more careful about event
1217 // preprocessing so the touches we receive can actually have non-zero policyFlags.
1218 // Unfortunately we obtain undesirable behavior.
1219 //
1220 // Here's what happens:
1221 //
1222 // When the device dims in anticipation of going to sleep, touches
1223 // in windows which have FLAG_TOUCHABLE_WHEN_WAKING cause
1224 // the device to brighten and reset the user activity timer.
1225 // Touches on other windows (such as the launcher window)
1226 // are dropped. Then after a moment, the device goes to sleep. Oops.
1227 //
1228 // Also notice how screenWasOff was being initialized using POLICY_FLAG_BRIGHT_HERE
1229 // instead of POLICY_FLAG_WOKE_HERE...
1230 //
1231 bool screenWasOff = false; // original policy: policyFlags & POLICY_FLAG_BRIGHT_HERE;
1232
1233 int32_t action = entry->action;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001234 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Jeff Brownb88102f2010-09-08 11:49:43 -07001235
1236 // Update the touch state as needed based on the properties of the touch event.
Jeff Brown01ce2e92010-09-26 22:20:12 -07001237 int32_t injectionResult = INPUT_EVENT_INJECTION_PENDING;
1238 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
Jeff Browna032cc02011-03-07 16:56:21 -08001239 const InputWindow* newHoverWindow = NULL;
Jeff Browncc0c1592011-02-19 05:07:28 -08001240
1241 bool isSplit = mTouchState.split;
1242 bool wrongDevice = mTouchState.down
1243 && (mTouchState.deviceId != entry->deviceId
1244 || mTouchState.source != entry->source);
Jeff Browna032cc02011-03-07 16:56:21 -08001245 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE
1246 || maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER
1247 || maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1248 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN
1249 || maskedAction == AMOTION_EVENT_ACTION_SCROLL
1250 || isHoverAction);
1251 if (newGesture) {
Jeff Browncc0c1592011-02-19 05:07:28 -08001252 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
1253 if (wrongDevice && !down) {
1254 mTempTouchState.copyFrom(mTouchState);
1255 } else {
1256 mTempTouchState.reset();
1257 mTempTouchState.down = down;
1258 mTempTouchState.deviceId = entry->deviceId;
1259 mTempTouchState.source = entry->source;
1260 isSplit = false;
1261 wrongDevice = false;
1262 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001263 } else {
1264 mTempTouchState.copyFrom(mTouchState);
Jeff Browncc0c1592011-02-19 05:07:28 -08001265 }
1266 if (wrongDevice) {
Jeff Browna2cc28d2011-03-25 11:58:46 -07001267#if DEBUG_FOCUS
Jeff Browncc0c1592011-02-19 05:07:28 -08001268 LOGD("Dropping event because a pointer for a different device is already down.");
Jeff Brown95712852011-01-04 19:41:59 -08001269#endif
Jeff Browncc0c1592011-02-19 05:07:28 -08001270 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1271 goto Failed;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001272 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001273
Jeff Browna032cc02011-03-07 16:56:21 -08001274 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
Jeff Brown33bbfd22011-02-24 20:55:35 -08001275 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
Jeff Brownb88102f2010-09-08 11:49:43 -07001276
Jeff Browna032cc02011-03-07 16:56:21 -08001277 const MotionSample* sample = &entry->firstSample;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001278 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Jeff Browna032cc02011-03-07 16:56:21 -08001279 int32_t x = int32_t(sample->pointerCoords[pointerIndex].
Jeff Brownebbd5d12011-02-17 13:01:34 -08001280 getAxisValue(AMOTION_EVENT_AXIS_X));
Jeff Browna032cc02011-03-07 16:56:21 -08001281 int32_t y = int32_t(sample->pointerCoords[pointerIndex].
Jeff Brownebbd5d12011-02-17 13:01:34 -08001282 getAxisValue(AMOTION_EVENT_AXIS_Y));
Jeff Brown01ce2e92010-09-26 22:20:12 -07001283 const InputWindow* newTouchedWindow = NULL;
1284 const InputWindow* topErrorWindow = NULL;
Jeff Browna032cc02011-03-07 16:56:21 -08001285 bool isTouchModal = false;
Jeff Brownb88102f2010-09-08 11:49:43 -07001286
1287 // Traverse windows from front to back to find touched window and outside targets.
1288 size_t numWindows = mWindows.size();
1289 for (size_t i = 0; i < numWindows; i++) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001290 const InputWindow* window = & mWindows.editItemAt(i);
Jeff Brownb88102f2010-09-08 11:49:43 -07001291 int32_t flags = window->layoutParamsFlags;
1292
1293 if (flags & InputWindow::FLAG_SYSTEM_ERROR) {
1294 if (! topErrorWindow) {
1295 topErrorWindow = window;
1296 }
1297 }
1298
1299 if (window->visible) {
1300 if (! (flags & InputWindow::FLAG_NOT_TOUCHABLE)) {
Jeff Browna032cc02011-03-07 16:56:21 -08001301 isTouchModal = (flags & (InputWindow::FLAG_NOT_FOCUSABLE
Jeff Brownb88102f2010-09-08 11:49:43 -07001302 | InputWindow::FLAG_NOT_TOUCH_MODAL)) == 0;
Jeff Brownfbf09772011-01-16 14:06:57 -08001303 if (isTouchModal || window->touchableRegionContainsPoint(x, y)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001304 if (! screenWasOff || flags & InputWindow::FLAG_TOUCHABLE_WHEN_WAKING) {
1305 newTouchedWindow = window;
Jeff Brownb88102f2010-09-08 11:49:43 -07001306 }
1307 break; // found touched window, exit window loop
1308 }
1309 }
1310
Jeff Brown01ce2e92010-09-26 22:20:12 -07001311 if (maskedAction == AMOTION_EVENT_ACTION_DOWN
1312 && (flags & InputWindow::FLAG_WATCH_OUTSIDE_TOUCH)) {
Jeff Browna032cc02011-03-07 16:56:21 -08001313 int32_t outsideTargetFlags = InputTarget::FLAG_DISPATCH_AS_OUTSIDE;
Jeff Brown19dfc832010-10-05 12:26:23 -07001314 if (isWindowObscuredAtPointLocked(window, x, y)) {
1315 outsideTargetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1316 }
1317
1318 mTempTouchState.addOrUpdateWindow(window, outsideTargetFlags, BitSet32(0));
Jeff Brownb88102f2010-09-08 11:49:43 -07001319 }
1320 }
1321 }
1322
1323 // If there is an error window but it is not taking focus (typically because
1324 // it is invisible) then wait for it. Any other focused window may in
1325 // fact be in ANR state.
1326 if (topErrorWindow && newTouchedWindow != topErrorWindow) {
1327#if DEBUG_FOCUS
1328 LOGD("Waiting because system error window is pending.");
1329#endif
1330 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
1331 NULL, NULL, nextWakeupTime);
1332 injectionPermission = INJECTION_PERMISSION_UNKNOWN;
1333 goto Unresponsive;
1334 }
1335
Jeff Brown01ce2e92010-09-26 22:20:12 -07001336 // Figure out whether splitting will be allowed for this window.
Jeff Brown46e75292010-11-10 16:53:45 -08001337 if (newTouchedWindow && newTouchedWindow->supportsSplitTouch()) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001338 // New window supports splitting.
1339 isSplit = true;
1340 } else if (isSplit) {
1341 // New window does not support splitting but we have already split events.
1342 // Assign the pointer to the first foreground window we find.
1343 // (May be NULL which is why we put this code block before the next check.)
1344 newTouchedWindow = mTempTouchState.getFirstForegroundWindow();
1345 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001346
Jeff Brownb88102f2010-09-08 11:49:43 -07001347 // If we did not find a touched window then fail.
1348 if (! newTouchedWindow) {
1349 if (mFocusedApplication) {
1350#if DEBUG_FOCUS
1351 LOGD("Waiting because there is no touched window but there is a "
Jeff Brown519e0242010-09-15 15:18:56 -07001352 "focused application that may eventually add a new window: %s.",
1353 getApplicationWindowLabelLocked(mFocusedApplication, NULL).string());
Jeff Brownb88102f2010-09-08 11:49:43 -07001354#endif
1355 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
1356 mFocusedApplication, NULL, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -07001357 goto Unresponsive;
1358 }
1359
1360 LOGI("Dropping event because there is no touched window or focused application.");
1361 injectionResult = INPUT_EVENT_INJECTION_FAILED;
Jeff Brownb88102f2010-09-08 11:49:43 -07001362 goto Failed;
1363 }
1364
Jeff Brown19dfc832010-10-05 12:26:23 -07001365 // Set target flags.
Jeff Browna032cc02011-03-07 16:56:21 -08001366 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
Jeff Brown19dfc832010-10-05 12:26:23 -07001367 if (isSplit) {
1368 targetFlags |= InputTarget::FLAG_SPLIT;
1369 }
1370 if (isWindowObscuredAtPointLocked(newTouchedWindow, x, y)) {
1371 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1372 }
1373
Jeff Browna032cc02011-03-07 16:56:21 -08001374 // Update hover state.
1375 if (isHoverAction) {
1376 newHoverWindow = newTouchedWindow;
1377
1378 // Ensure all subsequent motion samples are also within the touched window.
1379 // Set *outSplitBatchAfterSample to the sample before the first one that is not
1380 // within the touched window.
1381 if (!isTouchModal) {
1382 while (sample->next) {
1383 if (!newHoverWindow->touchableRegionContainsPoint(
1384 sample->next->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X),
1385 sample->next->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y))) {
1386 *outSplitBatchAfterSample = sample;
1387 break;
1388 }
1389 sample = sample->next;
1390 }
1391 }
1392 } else if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
1393 newHoverWindow = mLastHoverWindow;
1394 }
1395
Jeff Brown01ce2e92010-09-26 22:20:12 -07001396 // Update the temporary touch state.
1397 BitSet32 pointerIds;
1398 if (isSplit) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07001399 uint32_t pointerId = entry->pointerProperties[pointerIndex].id;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001400 pointerIds.markBit(pointerId);
Jeff Brownb88102f2010-09-08 11:49:43 -07001401 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001402 mTempTouchState.addOrUpdateWindow(newTouchedWindow, targetFlags, pointerIds);
Jeff Brownb88102f2010-09-08 11:49:43 -07001403 } else {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001404 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
Jeff Brownb88102f2010-09-08 11:49:43 -07001405
1406 // If the pointer is not currently down, then ignore the event.
Jeff Brown01ce2e92010-09-26 22:20:12 -07001407 if (! mTempTouchState.down) {
Jeff Browna2cc28d2011-03-25 11:58:46 -07001408#if DEBUG_FOCUS
Jeff Brown76860e32010-10-25 17:37:46 -07001409 LOGD("Dropping event because the pointer is not down or we previously "
1410 "dropped the pointer down event.");
1411#endif
Jeff Brownb88102f2010-09-08 11:49:43 -07001412 injectionResult = INPUT_EVENT_INJECTION_FAILED;
Jeff Brownb88102f2010-09-08 11:49:43 -07001413 goto Failed;
1414 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001415 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001416
Jeff Browna032cc02011-03-07 16:56:21 -08001417 if (newHoverWindow != mLastHoverWindow) {
1418 // Split the batch here so we send exactly one sample as part of ENTER or EXIT.
1419 *outSplitBatchAfterSample = &entry->firstSample;
1420
1421 // Let the previous window know that the hover sequence is over.
1422 if (mLastHoverWindow) {
1423#if DEBUG_HOVER
1424 LOGD("Sending hover exit event to window %s.", mLastHoverWindow->name.string());
1425#endif
1426 mTempTouchState.addOrUpdateWindow(mLastHoverWindow,
1427 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
1428 }
1429
1430 // Let the new window know that the hover sequence is starting.
1431 if (newHoverWindow) {
1432#if DEBUG_HOVER
1433 LOGD("Sending hover enter event to window %s.", newHoverWindow->name.string());
1434#endif
1435 mTempTouchState.addOrUpdateWindow(newHoverWindow,
1436 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER, BitSet32(0));
1437 }
1438 }
1439
Jeff Brown01ce2e92010-09-26 22:20:12 -07001440 // Check permission to inject into all touched foreground windows and ensure there
1441 // is at least one touched foreground window.
1442 {
1443 bool haveForegroundWindow = false;
1444 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1445 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1446 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1447 haveForegroundWindow = true;
1448 if (! checkInjectionPermission(touchedWindow.window, entry->injectionState)) {
1449 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1450 injectionPermission = INJECTION_PERMISSION_DENIED;
1451 goto Failed;
1452 }
1453 }
1454 }
1455 if (! haveForegroundWindow) {
Jeff Browna2cc28d2011-03-25 11:58:46 -07001456#if DEBUG_FOCUS
Jeff Brown01ce2e92010-09-26 22:20:12 -07001457 LOGD("Dropping event because there is no touched foreground window to receive it.");
Jeff Brownb88102f2010-09-08 11:49:43 -07001458#endif
1459 injectionResult = INPUT_EVENT_INJECTION_FAILED;
Jeff Brownb88102f2010-09-08 11:49:43 -07001460 goto Failed;
1461 }
1462
Jeff Brown01ce2e92010-09-26 22:20:12 -07001463 // Permission granted to injection into all touched foreground windows.
1464 injectionPermission = INJECTION_PERMISSION_GRANTED;
1465 }
Jeff Brown519e0242010-09-15 15:18:56 -07001466
Kenny Root7a9db182011-06-02 15:16:05 -07001467 // Check whether windows listening for outside touches are owned by the same UID. If it is
1468 // set the policy flag that we will not reveal coordinate information to this window.
1469 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1470 const InputWindow* foregroundWindow = mTempTouchState.getFirstForegroundWindow();
1471 const int32_t foregroundWindowUid = foregroundWindow->ownerUid;
1472 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1473 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1474 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
1475 const InputWindow* inputWindow = touchedWindow.window;
1476 if (inputWindow->ownerUid != foregroundWindowUid) {
1477 mTempTouchState.addOrUpdateWindow(inputWindow,
1478 InputTarget::FLAG_ZERO_COORDS, BitSet32(0));
1479 }
1480 }
1481 }
1482 }
1483
Jeff Brown01ce2e92010-09-26 22:20:12 -07001484 // Ensure all touched foreground windows are ready for new input.
1485 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1486 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1487 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1488 // If the touched window is paused then keep waiting.
1489 if (touchedWindow.window->paused) {
Jeff Browna2cc28d2011-03-25 11:58:46 -07001490#if DEBUG_FOCUS
Jeff Brown01ce2e92010-09-26 22:20:12 -07001491 LOGD("Waiting because touched window is paused.");
Jeff Brown519e0242010-09-15 15:18:56 -07001492#endif
Jeff Brown01ce2e92010-09-26 22:20:12 -07001493 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
1494 NULL, touchedWindow.window, nextWakeupTime);
1495 goto Unresponsive;
1496 }
1497
1498 // If the touched window is still working on previous events then keep waiting.
1499 if (! isWindowFinishedWithPreviousInputLocked(touchedWindow.window)) {
1500#if DEBUG_FOCUS
1501 LOGD("Waiting because touched window still processing previous input.");
1502#endif
1503 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
1504 NULL, touchedWindow.window, nextWakeupTime);
1505 goto Unresponsive;
1506 }
1507 }
1508 }
1509
1510 // If this is the first pointer going down and the touched window has a wallpaper
1511 // then also add the touched wallpaper windows so they are locked in for the duration
1512 // of the touch gesture.
Jeff Brown33bbfd22011-02-24 20:55:35 -08001513 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
1514 // engine only supports touch events. We would need to add a mechanism similar
1515 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
1516 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001517 const InputWindow* foregroundWindow = mTempTouchState.getFirstForegroundWindow();
1518 if (foregroundWindow->hasWallpaper) {
1519 for (size_t i = 0; i < mWindows.size(); i++) {
1520 const InputWindow* window = & mWindows[i];
1521 if (window->layoutParamsType == InputWindow::TYPE_WALLPAPER) {
Jeff Brown19dfc832010-10-05 12:26:23 -07001522 mTempTouchState.addOrUpdateWindow(window,
Jeff Browna032cc02011-03-07 16:56:21 -08001523 InputTarget::FLAG_WINDOW_IS_OBSCURED
1524 | InputTarget::FLAG_DISPATCH_AS_IS,
1525 BitSet32(0));
Jeff Brown01ce2e92010-09-26 22:20:12 -07001526 }
1527 }
1528 }
1529 }
1530
Jeff Brownb88102f2010-09-08 11:49:43 -07001531 // Success! Output targets.
1532 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
Jeff Brownb88102f2010-09-08 11:49:43 -07001533
Jeff Brown01ce2e92010-09-26 22:20:12 -07001534 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1535 const TouchedWindow& touchedWindow = mTempTouchState.windows.itemAt(i);
1536 addWindowTargetLocked(touchedWindow.window, touchedWindow.targetFlags,
1537 touchedWindow.pointerIds);
Jeff Brownb88102f2010-09-08 11:49:43 -07001538 }
1539
Jeff Browna032cc02011-03-07 16:56:21 -08001540 // Drop the outside or hover touch windows since we will not care about them
1541 // in the next iteration.
1542 mTempTouchState.filterNonAsIsTouchWindows();
Jeff Brown01ce2e92010-09-26 22:20:12 -07001543
Jeff Brownb88102f2010-09-08 11:49:43 -07001544Failed:
1545 // Check injection permission once and for all.
1546 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001547 if (checkInjectionPermission(NULL, entry->injectionState)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001548 injectionPermission = INJECTION_PERMISSION_GRANTED;
1549 } else {
1550 injectionPermission = INJECTION_PERMISSION_DENIED;
1551 }
1552 }
1553
1554 // Update final pieces of touch state if the injector had permission.
1555 if (injectionPermission == INJECTION_PERMISSION_GRANTED) {
Jeff Brown95712852011-01-04 19:41:59 -08001556 if (!wrongDevice) {
1557 if (maskedAction == AMOTION_EVENT_ACTION_UP
Jeff Browncc0c1592011-02-19 05:07:28 -08001558 || maskedAction == AMOTION_EVENT_ACTION_CANCEL
Jeff Browna032cc02011-03-07 16:56:21 -08001559 || isHoverAction) {
Jeff Brown95712852011-01-04 19:41:59 -08001560 // All pointers up or canceled.
Jeff Brown33bbfd22011-02-24 20:55:35 -08001561 mTouchState.reset();
Jeff Brown95712852011-01-04 19:41:59 -08001562 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1563 // First pointer went down.
1564 if (mTouchState.down) {
Jeff Browncc0c1592011-02-19 05:07:28 -08001565 *outConflictingPointerActions = true;
Jeff Brownb6997262010-10-08 22:31:17 -07001566#if DEBUG_FOCUS
Jeff Brown95712852011-01-04 19:41:59 -08001567 LOGD("Pointer down received while already down.");
Jeff Brownb6997262010-10-08 22:31:17 -07001568#endif
Jeff Brown95712852011-01-04 19:41:59 -08001569 }
Jeff Brown33bbfd22011-02-24 20:55:35 -08001570 mTouchState.copyFrom(mTempTouchState);
Jeff Brown95712852011-01-04 19:41:59 -08001571 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
1572 // One pointer went up.
1573 if (isSplit) {
1574 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07001575 uint32_t pointerId = entry->pointerProperties[pointerIndex].id;
Jeff Brownb88102f2010-09-08 11:49:43 -07001576
Jeff Brown95712852011-01-04 19:41:59 -08001577 for (size_t i = 0; i < mTempTouchState.windows.size(); ) {
1578 TouchedWindow& touchedWindow = mTempTouchState.windows.editItemAt(i);
1579 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
1580 touchedWindow.pointerIds.clearBit(pointerId);
1581 if (touchedWindow.pointerIds.isEmpty()) {
1582 mTempTouchState.windows.removeAt(i);
1583 continue;
1584 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001585 }
Jeff Brown95712852011-01-04 19:41:59 -08001586 i += 1;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001587 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001588 }
Jeff Brown33bbfd22011-02-24 20:55:35 -08001589 mTouchState.copyFrom(mTempTouchState);
1590 } else if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
1591 // Discard temporary touch state since it was only valid for this action.
1592 } else {
1593 // Save changes to touch state as-is for all other actions.
1594 mTouchState.copyFrom(mTempTouchState);
Jeff Brownb88102f2010-09-08 11:49:43 -07001595 }
Jeff Browna032cc02011-03-07 16:56:21 -08001596
1597 // Update hover state.
1598 mLastHoverWindow = newHoverWindow;
Jeff Brown95712852011-01-04 19:41:59 -08001599 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001600 } else {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001601#if DEBUG_FOCUS
1602 LOGD("Not updating touch focus because injection was denied.");
1603#endif
Jeff Brownb88102f2010-09-08 11:49:43 -07001604 }
1605
1606Unresponsive:
Jeff Brown120a4592010-10-27 18:43:51 -07001607 // Reset temporary touch state to ensure we release unnecessary references to input channels.
1608 mTempTouchState.reset();
1609
Jeff Brown519e0242010-09-15 15:18:56 -07001610 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
1611 updateDispatchStatisticsLocked(currentTime, entry,
1612 injectionResult, timeSpentWaitingForApplication);
Jeff Brownb88102f2010-09-08 11:49:43 -07001613#if DEBUG_FOCUS
Jeff Brown01ce2e92010-09-26 22:20:12 -07001614 LOGD("findTouchedWindow finished: injectionResult=%d, injectionPermission=%d, "
1615 "timeSpentWaitingForApplication=%0.1fms",
Jeff Brown519e0242010-09-15 15:18:56 -07001616 injectionResult, injectionPermission, timeSpentWaitingForApplication / 1000000.0);
Jeff Brownb88102f2010-09-08 11:49:43 -07001617#endif
1618 return injectionResult;
1619}
1620
Jeff Brown01ce2e92010-09-26 22:20:12 -07001621void InputDispatcher::addWindowTargetLocked(const InputWindow* window, int32_t targetFlags,
1622 BitSet32 pointerIds) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001623 mCurrentInputTargets.push();
1624
1625 InputTarget& target = mCurrentInputTargets.editTop();
1626 target.inputChannel = window->inputChannel;
1627 target.flags = targetFlags;
Jeff Brownb88102f2010-09-08 11:49:43 -07001628 target.xOffset = - window->frameLeft;
1629 target.yOffset = - window->frameTop;
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001630 target.scaleFactor = window->scaleFactor;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001631 target.pointerIds = pointerIds;
Jeff Brownb88102f2010-09-08 11:49:43 -07001632}
1633
1634void InputDispatcher::addMonitoringTargetsLocked() {
1635 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
1636 mCurrentInputTargets.push();
1637
1638 InputTarget& target = mCurrentInputTargets.editTop();
1639 target.inputChannel = mMonitoringChannels[i];
Jeff Brownb6110c22011-04-01 16:15:13 -07001640 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
Jeff Brownb88102f2010-09-08 11:49:43 -07001641 target.xOffset = 0;
1642 target.yOffset = 0;
Jeff Brownb6110c22011-04-01 16:15:13 -07001643 target.pointerIds.clear();
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001644 target.scaleFactor = 1.0f;
Jeff Brownb88102f2010-09-08 11:49:43 -07001645 }
1646}
1647
1648bool InputDispatcher::checkInjectionPermission(const InputWindow* window,
Jeff Brown01ce2e92010-09-26 22:20:12 -07001649 const InjectionState* injectionState) {
1650 if (injectionState
Jeff Brownb6997262010-10-08 22:31:17 -07001651 && (window == NULL || window->ownerUid != injectionState->injectorUid)
1652 && !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
1653 if (window) {
1654 LOGW("Permission denied: injecting event from pid %d uid %d to window "
1655 "with input channel %s owned by uid %d",
1656 injectionState->injectorPid, injectionState->injectorUid,
1657 window->inputChannel->getName().string(),
1658 window->ownerUid);
1659 } else {
1660 LOGW("Permission denied: injecting event from pid %d uid %d",
1661 injectionState->injectorPid, injectionState->injectorUid);
Jeff Brownb88102f2010-09-08 11:49:43 -07001662 }
Jeff Brownb6997262010-10-08 22:31:17 -07001663 return false;
Jeff Brownb88102f2010-09-08 11:49:43 -07001664 }
1665 return true;
1666}
1667
Jeff Brown19dfc832010-10-05 12:26:23 -07001668bool InputDispatcher::isWindowObscuredAtPointLocked(
1669 const InputWindow* window, int32_t x, int32_t y) const {
Jeff Brownb88102f2010-09-08 11:49:43 -07001670 size_t numWindows = mWindows.size();
1671 for (size_t i = 0; i < numWindows; i++) {
1672 const InputWindow* other = & mWindows.itemAt(i);
1673 if (other == window) {
1674 break;
1675 }
Jeff Brown19dfc832010-10-05 12:26:23 -07001676 if (other->visible && ! other->isTrustedOverlay() && other->frameContainsPoint(x, y)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001677 return true;
1678 }
1679 }
1680 return false;
1681}
1682
Jeff Brown519e0242010-09-15 15:18:56 -07001683bool InputDispatcher::isWindowFinishedWithPreviousInputLocked(const InputWindow* window) {
1684 ssize_t connectionIndex = getConnectionIndexLocked(window->inputChannel);
1685 if (connectionIndex >= 0) {
1686 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
1687 return connection->outboundQueue.isEmpty();
1688 } else {
1689 return true;
1690 }
1691}
1692
1693String8 InputDispatcher::getApplicationWindowLabelLocked(const InputApplication* application,
1694 const InputWindow* window) {
1695 if (application) {
1696 if (window) {
1697 String8 label(application->name);
1698 label.append(" - ");
1699 label.append(window->name);
1700 return label;
1701 } else {
1702 return application->name;
1703 }
1704 } else if (window) {
1705 return window->name;
1706 } else {
1707 return String8("<unknown application or window>");
1708 }
1709}
1710
Jeff Browne2fe69e2010-10-18 13:21:23 -07001711void InputDispatcher::pokeUserActivityLocked(const EventEntry* eventEntry) {
Jeff Brown56194eb2011-03-02 19:23:13 -08001712 int32_t eventType = POWER_MANAGER_OTHER_EVENT;
Jeff Brown4d396052010-10-29 21:50:21 -07001713 switch (eventEntry->type) {
1714 case EventEntry::TYPE_MOTION: {
Jeff Browne2fe69e2010-10-18 13:21:23 -07001715 const MotionEntry* motionEntry = static_cast<const MotionEntry*>(eventEntry);
Jeff Brown4d396052010-10-29 21:50:21 -07001716 if (motionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
1717 return;
1718 }
1719
Jeff Brown56194eb2011-03-02 19:23:13 -08001720 if (MotionEvent::isTouchEvent(motionEntry->source, motionEntry->action)) {
Joe Onorato1a542c72010-11-08 09:48:20 -08001721 eventType = POWER_MANAGER_TOUCH_EVENT;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001722 }
Jeff Brown4d396052010-10-29 21:50:21 -07001723 break;
1724 }
1725 case EventEntry::TYPE_KEY: {
1726 const KeyEntry* keyEntry = static_cast<const KeyEntry*>(eventEntry);
1727 if (keyEntry->flags & AKEY_EVENT_FLAG_CANCELED) {
1728 return;
1729 }
Jeff Brown56194eb2011-03-02 19:23:13 -08001730 eventType = POWER_MANAGER_BUTTON_EVENT;
Jeff Brown4d396052010-10-29 21:50:21 -07001731 break;
1732 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001733 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001734
Jeff Brownb88102f2010-09-08 11:49:43 -07001735 CommandEntry* commandEntry = postCommandLocked(
1736 & InputDispatcher::doPokeUserActivityLockedInterruptible);
Jeff Browne2fe69e2010-10-18 13:21:23 -07001737 commandEntry->eventTime = eventEntry->eventTime;
Jeff Brownb88102f2010-09-08 11:49:43 -07001738 commandEntry->userActivityEventType = eventType;
1739}
1740
Jeff Brown7fbdc842010-06-17 20:52:56 -07001741void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
1742 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget,
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001743 bool resumeWithAppendedMotionSample) {
1744#if DEBUG_DISPATCH_CYCLE
Jeff Brown519e0242010-09-15 15:18:56 -07001745 LOGD("channel '%s' ~ prepareDispatchCycle - flags=%d, "
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001746 "xOffset=%f, yOffset=%f, scaleFactor=%f"
Jeff Brown83c09682010-12-23 17:50:18 -08001747 "pointerIds=0x%x, "
Jeff Brown01ce2e92010-09-26 22:20:12 -07001748 "resumeWithAppendedMotionSample=%s",
Jeff Brown519e0242010-09-15 15:18:56 -07001749 connection->getInputChannelName(), inputTarget->flags,
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001750 inputTarget->xOffset, inputTarget->yOffset,
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001751 inputTarget->scaleFactor, inputTarget->pointerIds.value,
Jeff Brownb88102f2010-09-08 11:49:43 -07001752 toString(resumeWithAppendedMotionSample));
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001753#endif
1754
Jeff Brown01ce2e92010-09-26 22:20:12 -07001755 // Make sure we are never called for streaming when splitting across multiple windows.
1756 bool isSplit = inputTarget->flags & InputTarget::FLAG_SPLIT;
Jeff Brownb6110c22011-04-01 16:15:13 -07001757 LOG_ASSERT(! (resumeWithAppendedMotionSample && isSplit));
Jeff Brown01ce2e92010-09-26 22:20:12 -07001758
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001759 // Skip this event if the connection status is not normal.
Jeff Brown519e0242010-09-15 15:18:56 -07001760 // We don't want to enqueue additional outbound events if the connection is broken.
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001761 if (connection->status != Connection::STATUS_NORMAL) {
Jeff Brownb6997262010-10-08 22:31:17 -07001762#if DEBUG_DISPATCH_CYCLE
1763 LOGD("channel '%s' ~ Dropping event because the channel status is %s",
Jeff Brownb88102f2010-09-08 11:49:43 -07001764 connection->getInputChannelName(), connection->getStatusLabel());
Jeff Brownb6997262010-10-08 22:31:17 -07001765#endif
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001766 return;
1767 }
1768
Jeff Brown01ce2e92010-09-26 22:20:12 -07001769 // Split a motion event if needed.
1770 if (isSplit) {
Jeff Brownb6110c22011-04-01 16:15:13 -07001771 LOG_ASSERT(eventEntry->type == EventEntry::TYPE_MOTION);
Jeff Brown01ce2e92010-09-26 22:20:12 -07001772
1773 MotionEntry* originalMotionEntry = static_cast<MotionEntry*>(eventEntry);
1774 if (inputTarget->pointerIds.count() != originalMotionEntry->pointerCount) {
1775 MotionEntry* splitMotionEntry = splitMotionEvent(
1776 originalMotionEntry, inputTarget->pointerIds);
Jeff Brown58a2da82011-01-25 16:02:22 -08001777 if (!splitMotionEntry) {
1778 return; // split event was dropped
1779 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001780#if DEBUG_FOCUS
1781 LOGD("channel '%s' ~ Split motion event.",
1782 connection->getInputChannelName());
1783 logOutboundMotionDetailsLocked(" ", splitMotionEntry);
1784#endif
1785 eventEntry = splitMotionEntry;
1786 }
1787 }
1788
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001789 // Resume the dispatch cycle with a freshly appended motion sample.
1790 // First we check that the last dispatch entry in the outbound queue is for the same
1791 // motion event to which we appended the motion sample. If we find such a dispatch
1792 // entry, and if it is currently in progress then we try to stream the new sample.
1793 bool wasEmpty = connection->outboundQueue.isEmpty();
1794
1795 if (! wasEmpty && resumeWithAppendedMotionSample) {
1796 DispatchEntry* motionEventDispatchEntry =
1797 connection->findQueuedDispatchEntryForEvent(eventEntry);
1798 if (motionEventDispatchEntry) {
1799 // If the dispatch entry is not in progress, then we must be busy dispatching an
1800 // earlier event. Not a problem, the motion event is on the outbound queue and will
1801 // be dispatched later.
1802 if (! motionEventDispatchEntry->inProgress) {
1803#if DEBUG_BATCHING
1804 LOGD("channel '%s' ~ Not streaming because the motion event has "
1805 "not yet been dispatched. "
1806 "(Waiting for earlier events to be consumed.)",
1807 connection->getInputChannelName());
1808#endif
1809 return;
1810 }
1811
1812 // If the dispatch entry is in progress but it already has a tail of pending
1813 // motion samples, then it must mean that the shared memory buffer filled up.
1814 // Not a problem, when this dispatch cycle is finished, we will eventually start
1815 // a new dispatch cycle to process the tail and that tail includes the newly
1816 // appended motion sample.
1817 if (motionEventDispatchEntry->tailMotionSample) {
1818#if DEBUG_BATCHING
1819 LOGD("channel '%s' ~ Not streaming because no new samples can "
1820 "be appended to the motion event in this dispatch cycle. "
1821 "(Waiting for next dispatch cycle to start.)",
1822 connection->getInputChannelName());
1823#endif
1824 return;
1825 }
1826
1827 // The dispatch entry is in progress and is still potentially open for streaming.
1828 // Try to stream the new motion sample. This might fail if the consumer has already
1829 // consumed the motion event (or if the channel is broken).
Jeff Brown01ce2e92010-09-26 22:20:12 -07001830 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
1831 MotionSample* appendedMotionSample = motionEntry->lastSample;
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001832 status_t status;
1833 if (motionEventDispatchEntry->scaleFactor == 1.0f) {
1834 status = connection->inputPublisher.appendMotionSample(
1835 appendedMotionSample->eventTime, appendedMotionSample->pointerCoords);
1836 } else {
1837 PointerCoords scaledCoords[MAX_POINTERS];
1838 for (size_t i = 0; i < motionEntry->pointerCount; i++) {
1839 scaledCoords[i] = appendedMotionSample->pointerCoords[i];
1840 scaledCoords[i].scale(motionEventDispatchEntry->scaleFactor);
1841 }
1842 status = connection->inputPublisher.appendMotionSample(
1843 appendedMotionSample->eventTime, scaledCoords);
1844 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001845 if (status == OK) {
1846#if DEBUG_BATCHING
1847 LOGD("channel '%s' ~ Successfully streamed new motion sample.",
1848 connection->getInputChannelName());
1849#endif
1850 return;
1851 }
1852
1853#if DEBUG_BATCHING
1854 if (status == NO_MEMORY) {
1855 LOGD("channel '%s' ~ Could not append motion sample to currently "
1856 "dispatched move event because the shared memory buffer is full. "
1857 "(Waiting for next dispatch cycle to start.)",
1858 connection->getInputChannelName());
1859 } else if (status == status_t(FAILED_TRANSACTION)) {
1860 LOGD("channel '%s' ~ Could not append motion sample to currently "
Jeff Brown349703e2010-06-22 01:27:15 -07001861 "dispatched move event because the event has already been consumed. "
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001862 "(Waiting for next dispatch cycle to start.)",
1863 connection->getInputChannelName());
1864 } else {
1865 LOGD("channel '%s' ~ Could not append motion sample to currently "
1866 "dispatched move event due to an error, status=%d. "
1867 "(Waiting for next dispatch cycle to start.)",
1868 connection->getInputChannelName(), status);
1869 }
1870#endif
1871 // Failed to stream. Start a new tail of pending motion samples to dispatch
1872 // in the next cycle.
1873 motionEventDispatchEntry->tailMotionSample = appendedMotionSample;
1874 return;
1875 }
1876 }
1877
Jeff Browna032cc02011-03-07 16:56:21 -08001878 // Enqueue dispatch entries for the requested modes.
1879 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1880 resumeWithAppendedMotionSample, InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
1881 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1882 resumeWithAppendedMotionSample, InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
1883 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1884 resumeWithAppendedMotionSample, InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
1885 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1886 resumeWithAppendedMotionSample, InputTarget::FLAG_DISPATCH_AS_IS);
1887
1888 // If the outbound queue was previously empty, start the dispatch cycle going.
Jeff Brownb6110c22011-04-01 16:15:13 -07001889 if (wasEmpty && !connection->outboundQueue.isEmpty()) {
Jeff Browna032cc02011-03-07 16:56:21 -08001890 activateConnectionLocked(connection.get());
1891 startDispatchCycleLocked(currentTime, connection);
1892 }
1893}
1894
1895void InputDispatcher::enqueueDispatchEntryLocked(
1896 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget,
1897 bool resumeWithAppendedMotionSample, int32_t dispatchMode) {
1898 int32_t inputTargetFlags = inputTarget->flags;
1899 if (!(inputTargetFlags & dispatchMode)) {
1900 return;
1901 }
1902 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
1903
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001904 // This is a new event.
1905 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Jeff Brownb88102f2010-09-08 11:49:43 -07001906 DispatchEntry* dispatchEntry = mAllocator.obtainDispatchEntry(eventEntry, // increments ref
Dianne Hackbornaa9d84c2011-05-09 19:00:59 -07001907 inputTargetFlags, inputTarget->xOffset, inputTarget->yOffset,
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001908 inputTarget->scaleFactor);
Jeff Brown519e0242010-09-15 15:18:56 -07001909 if (dispatchEntry->hasForegroundTarget()) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001910 incrementPendingForegroundDispatchesLocked(eventEntry);
Jeff Brown6ec402b2010-07-28 15:48:59 -07001911 }
1912
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001913 // Handle the case where we could not stream a new motion sample because the consumer has
1914 // already consumed the motion event (otherwise the corresponding dispatch entry would
1915 // still be in the outbound queue for this connection). We set the head motion sample
1916 // to the list starting with the newly appended motion sample.
1917 if (resumeWithAppendedMotionSample) {
1918#if DEBUG_BATCHING
1919 LOGD("channel '%s' ~ Preparing a new dispatch cycle for additional motion samples "
1920 "that cannot be streamed because the motion event has already been consumed.",
1921 connection->getInputChannelName());
1922#endif
1923 MotionSample* appendedMotionSample = static_cast<MotionEntry*>(eventEntry)->lastSample;
1924 dispatchEntry->headMotionSample = appendedMotionSample;
1925 }
1926
1927 // Enqueue the dispatch entry.
1928 connection->outboundQueue.enqueueAtTail(dispatchEntry);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001929}
1930
Jeff Brown7fbdc842010-06-17 20:52:56 -07001931void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Jeff Brown519e0242010-09-15 15:18:56 -07001932 const sp<Connection>& connection) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001933#if DEBUG_DISPATCH_CYCLE
1934 LOGD("channel '%s' ~ startDispatchCycle",
1935 connection->getInputChannelName());
1936#endif
1937
Jeff Brownb6110c22011-04-01 16:15:13 -07001938 LOG_ASSERT(connection->status == Connection::STATUS_NORMAL);
1939 LOG_ASSERT(! connection->outboundQueue.isEmpty());
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001940
Jeff Brownb88102f2010-09-08 11:49:43 -07001941 DispatchEntry* dispatchEntry = connection->outboundQueue.headSentinel.next;
Jeff Brownb6110c22011-04-01 16:15:13 -07001942 LOG_ASSERT(! dispatchEntry->inProgress);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001943
Jeff Brownb88102f2010-09-08 11:49:43 -07001944 // Mark the dispatch entry as in progress.
1945 dispatchEntry->inProgress = true;
1946
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001947 // Publish the event.
1948 status_t status;
Jeff Browna032cc02011-03-07 16:56:21 -08001949 EventEntry* eventEntry = dispatchEntry->eventEntry;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001950 switch (eventEntry->type) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001951 case EventEntry::TYPE_KEY: {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001952 KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001953
1954 // Apply target flags.
1955 int32_t action = keyEntry->action;
1956 int32_t flags = keyEntry->flags;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001957
Jeff Browna032cc02011-03-07 16:56:21 -08001958 // Update the connection's input state.
1959 connection->inputState.trackKey(keyEntry, action);
1960
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001961 // Publish the key event.
Jeff Brownc5ed5912010-07-14 18:48:53 -07001962 status = connection->inputPublisher.publishKeyEvent(keyEntry->deviceId, keyEntry->source,
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001963 action, flags, keyEntry->keyCode, keyEntry->scanCode,
1964 keyEntry->metaState, keyEntry->repeatCount, keyEntry->downTime,
1965 keyEntry->eventTime);
1966
1967 if (status) {
1968 LOGE("channel '%s' ~ Could not publish key event, "
1969 "status=%d", connection->getInputChannelName(), status);
Jeff Brownb6997262010-10-08 22:31:17 -07001970 abortBrokenDispatchCycleLocked(currentTime, connection);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001971 return;
1972 }
1973 break;
1974 }
1975
1976 case EventEntry::TYPE_MOTION: {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001977 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001978
1979 // Apply target flags.
1980 int32_t action = motionEntry->action;
Jeff Brown85a31762010-09-01 17:01:00 -07001981 int32_t flags = motionEntry->flags;
Jeff Browna032cc02011-03-07 16:56:21 -08001982 if (dispatchEntry->targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001983 action = AMOTION_EVENT_ACTION_OUTSIDE;
Jeff Browna032cc02011-03-07 16:56:21 -08001984 } else if (dispatchEntry->targetFlags & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
1985 action = AMOTION_EVENT_ACTION_HOVER_EXIT;
1986 } else if (dispatchEntry->targetFlags & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
1987 action = AMOTION_EVENT_ACTION_HOVER_ENTER;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001988 }
Jeff Brown85a31762010-09-01 17:01:00 -07001989 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
1990 flags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
1991 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001992
1993 // If headMotionSample is non-NULL, then it points to the first new sample that we
1994 // were unable to dispatch during the previous cycle so we resume dispatching from
1995 // that point in the list of motion samples.
1996 // Otherwise, we just start from the first sample of the motion event.
1997 MotionSample* firstMotionSample = dispatchEntry->headMotionSample;
1998 if (! firstMotionSample) {
1999 firstMotionSample = & motionEntry->firstSample;
2000 }
2001
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002002 PointerCoords scaledCoords[MAX_POINTERS];
2003 const PointerCoords* usingCoords = firstMotionSample->pointerCoords;
2004
Jeff Brownd3616592010-07-16 17:21:06 -07002005 // Set the X and Y offset depending on the input source.
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002006 float xOffset, yOffset, scaleFactor;
Kenny Root7a9db182011-06-02 15:16:05 -07002007 if (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER
2008 && !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002009 scaleFactor = dispatchEntry->scaleFactor;
2010 xOffset = dispatchEntry->xOffset * scaleFactor;
2011 yOffset = dispatchEntry->yOffset * scaleFactor;
2012 if (scaleFactor != 1.0f) {
2013 for (size_t i = 0; i < motionEntry->pointerCount; i++) {
2014 scaledCoords[i] = firstMotionSample->pointerCoords[i];
2015 scaledCoords[i].scale(scaleFactor);
2016 }
2017 usingCoords = scaledCoords;
2018 }
Jeff Brownd3616592010-07-16 17:21:06 -07002019 } else {
2020 xOffset = 0.0f;
2021 yOffset = 0.0f;
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002022 scaleFactor = 1.0f;
Kenny Root7a9db182011-06-02 15:16:05 -07002023
2024 // We don't want the dispatch target to know.
2025 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
2026 for (size_t i = 0; i < motionEntry->pointerCount; i++) {
2027 scaledCoords[i].clear();
2028 }
2029 usingCoords = scaledCoords;
2030 }
Jeff Brownd3616592010-07-16 17:21:06 -07002031 }
2032
Jeff Browna032cc02011-03-07 16:56:21 -08002033 // Update the connection's input state.
2034 connection->inputState.trackMotion(motionEntry, action);
2035
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002036 // Publish the motion event and the first motion sample.
2037 status = connection->inputPublisher.publishMotionEvent(motionEntry->deviceId,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002038 motionEntry->source, action, flags, motionEntry->edgeFlags,
2039 motionEntry->metaState, motionEntry->buttonState,
2040 xOffset, yOffset,
2041 motionEntry->xPrecision, motionEntry->yPrecision,
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002042 motionEntry->downTime, firstMotionSample->eventTime,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002043 motionEntry->pointerCount, motionEntry->pointerProperties,
2044 usingCoords);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002045
2046 if (status) {
2047 LOGE("channel '%s' ~ Could not publish motion event, "
2048 "status=%d", connection->getInputChannelName(), status);
Jeff Brownb6997262010-10-08 22:31:17 -07002049 abortBrokenDispatchCycleLocked(currentTime, connection);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002050 return;
2051 }
2052
Jeff Browna032cc02011-03-07 16:56:21 -08002053 if (action == AMOTION_EVENT_ACTION_MOVE
2054 || action == AMOTION_EVENT_ACTION_HOVER_MOVE) {
2055 // Append additional motion samples.
2056 MotionSample* nextMotionSample = firstMotionSample->next;
2057 for (; nextMotionSample != NULL; nextMotionSample = nextMotionSample->next) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002058 if (usingCoords == scaledCoords) {
Kenny Root7a9db182011-06-02 15:16:05 -07002059 if (!(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
2060 for (size_t i = 0; i < motionEntry->pointerCount; i++) {
2061 scaledCoords[i] = nextMotionSample->pointerCoords[i];
2062 scaledCoords[i].scale(scaleFactor);
2063 }
Dianne Hackborn2ba3e802011-05-11 10:59:54 -07002064 }
2065 } else {
2066 usingCoords = nextMotionSample->pointerCoords;
Dianne Hackborne7d25b72011-05-09 21:19:26 -07002067 }
Jeff Browna032cc02011-03-07 16:56:21 -08002068 status = connection->inputPublisher.appendMotionSample(
Dianne Hackbornaa9d84c2011-05-09 19:00:59 -07002069 nextMotionSample->eventTime, usingCoords);
Jeff Browna032cc02011-03-07 16:56:21 -08002070 if (status == NO_MEMORY) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002071#if DEBUG_DISPATCH_CYCLE
2072 LOGD("channel '%s' ~ Shared memory buffer full. Some motion samples will "
2073 "be sent in the next dispatch cycle.",
2074 connection->getInputChannelName());
2075#endif
Jeff Browna032cc02011-03-07 16:56:21 -08002076 break;
2077 }
2078 if (status != OK) {
2079 LOGE("channel '%s' ~ Could not append motion sample "
2080 "for a reason other than out of memory, status=%d",
2081 connection->getInputChannelName(), status);
2082 abortBrokenDispatchCycleLocked(currentTime, connection);
2083 return;
2084 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002085 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002086
Jeff Browna032cc02011-03-07 16:56:21 -08002087 // Remember the next motion sample that we could not dispatch, in case we ran out
2088 // of space in the shared memory buffer.
2089 dispatchEntry->tailMotionSample = nextMotionSample;
2090 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002091 break;
2092 }
2093
2094 default: {
Jeff Brownb6110c22011-04-01 16:15:13 -07002095 LOG_ASSERT(false);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002096 }
2097 }
2098
2099 // Send the dispatch signal.
2100 status = connection->inputPublisher.sendDispatchSignal();
2101 if (status) {
2102 LOGE("channel '%s' ~ Could not send dispatch signal, status=%d",
2103 connection->getInputChannelName(), status);
Jeff Brownb6997262010-10-08 22:31:17 -07002104 abortBrokenDispatchCycleLocked(currentTime, connection);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002105 return;
2106 }
2107
2108 // Record information about the newly started dispatch cycle.
Jeff Brown01ce2e92010-09-26 22:20:12 -07002109 connection->lastEventTime = eventEntry->eventTime;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002110 connection->lastDispatchTime = currentTime;
2111
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002112 // Notify other system components.
2113 onDispatchCycleStartedLocked(currentTime, connection);
2114}
2115
Jeff Brown7fbdc842010-06-17 20:52:56 -07002116void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Jeff Brown3915bb82010-11-05 15:02:16 -07002117 const sp<Connection>& connection, bool handled) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002118#if DEBUG_DISPATCH_CYCLE
Jeff Brown9c3cda02010-06-15 01:31:58 -07002119 LOGD("channel '%s' ~ finishDispatchCycle - %01.1fms since event, "
Jeff Brown3915bb82010-11-05 15:02:16 -07002120 "%01.1fms since dispatch, handled=%s",
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002121 connection->getInputChannelName(),
2122 connection->getEventLatencyMillis(currentTime),
Jeff Brown3915bb82010-11-05 15:02:16 -07002123 connection->getDispatchLatencyMillis(currentTime),
2124 toString(handled));
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002125#endif
2126
Jeff Brown9c3cda02010-06-15 01:31:58 -07002127 if (connection->status == Connection::STATUS_BROKEN
2128 || connection->status == Connection::STATUS_ZOMBIE) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002129 return;
2130 }
2131
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002132 // Reset the publisher since the event has been consumed.
2133 // We do this now so that the publisher can release some of its internal resources
2134 // while waiting for the next dispatch cycle to begin.
2135 status_t status = connection->inputPublisher.reset();
2136 if (status) {
2137 LOGE("channel '%s' ~ Could not reset publisher, status=%d",
2138 connection->getInputChannelName(), status);
Jeff Brownb6997262010-10-08 22:31:17 -07002139 abortBrokenDispatchCycleLocked(currentTime, connection);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002140 return;
2141 }
2142
Jeff Brown3915bb82010-11-05 15:02:16 -07002143 // Notify other system components and prepare to start the next dispatch cycle.
2144 onDispatchCycleFinishedLocked(currentTime, connection, handled);
Jeff Brownb88102f2010-09-08 11:49:43 -07002145}
2146
2147void InputDispatcher::startNextDispatchCycleLocked(nsecs_t currentTime,
2148 const sp<Connection>& connection) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002149 // Start the next dispatch cycle for this connection.
2150 while (! connection->outboundQueue.isEmpty()) {
Jeff Brownb88102f2010-09-08 11:49:43 -07002151 DispatchEntry* dispatchEntry = connection->outboundQueue.headSentinel.next;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002152 if (dispatchEntry->inProgress) {
2153 // Finish or resume current event in progress.
2154 if (dispatchEntry->tailMotionSample) {
2155 // We have a tail of undispatched motion samples.
2156 // Reuse the same DispatchEntry and start a new cycle.
2157 dispatchEntry->inProgress = false;
2158 dispatchEntry->headMotionSample = dispatchEntry->tailMotionSample;
2159 dispatchEntry->tailMotionSample = NULL;
Jeff Brown519e0242010-09-15 15:18:56 -07002160 startDispatchCycleLocked(currentTime, connection);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002161 return;
2162 }
2163 // Finished.
2164 connection->outboundQueue.dequeueAtHead();
Jeff Brown519e0242010-09-15 15:18:56 -07002165 if (dispatchEntry->hasForegroundTarget()) {
2166 decrementPendingForegroundDispatchesLocked(dispatchEntry->eventEntry);
Jeff Brown6ec402b2010-07-28 15:48:59 -07002167 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002168 mAllocator.releaseDispatchEntry(dispatchEntry);
2169 } else {
2170 // If the head is not in progress, then we must have already dequeued the in
Jeff Brown519e0242010-09-15 15:18:56 -07002171 // progress event, which means we actually aborted it.
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002172 // So just start the next event for this connection.
Jeff Brown519e0242010-09-15 15:18:56 -07002173 startDispatchCycleLocked(currentTime, connection);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002174 return;
2175 }
2176 }
2177
2178 // Outbound queue is empty, deactivate the connection.
Jeff Brown7fbdc842010-06-17 20:52:56 -07002179 deactivateConnectionLocked(connection.get());
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002180}
2181
Jeff Brownb6997262010-10-08 22:31:17 -07002182void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
2183 const sp<Connection>& connection) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002184#if DEBUG_DISPATCH_CYCLE
Jeff Brown83c09682010-12-23 17:50:18 -08002185 LOGD("channel '%s' ~ abortBrokenDispatchCycle",
2186 connection->getInputChannelName());
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002187#endif
2188
Jeff Brownb88102f2010-09-08 11:49:43 -07002189 // Clear the outbound queue.
Jeff Brown519e0242010-09-15 15:18:56 -07002190 drainOutboundQueueLocked(connection.get());
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002191
Jeff Brownb6997262010-10-08 22:31:17 -07002192 // The connection appears to be unrecoverably broken.
Jeff Brown9c3cda02010-06-15 01:31:58 -07002193 // Ignore already broken or zombie connections.
Jeff Brownb6997262010-10-08 22:31:17 -07002194 if (connection->status == Connection::STATUS_NORMAL) {
2195 connection->status = Connection::STATUS_BROKEN;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002196
Jeff Brownb6997262010-10-08 22:31:17 -07002197 // Notify other system components.
2198 onDispatchCycleBrokenLocked(currentTime, connection);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002199 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002200}
2201
Jeff Brown519e0242010-09-15 15:18:56 -07002202void InputDispatcher::drainOutboundQueueLocked(Connection* connection) {
2203 while (! connection->outboundQueue.isEmpty()) {
2204 DispatchEntry* dispatchEntry = connection->outboundQueue.dequeueAtHead();
2205 if (dispatchEntry->hasForegroundTarget()) {
2206 decrementPendingForegroundDispatchesLocked(dispatchEntry->eventEntry);
Jeff Brownb88102f2010-09-08 11:49:43 -07002207 }
2208 mAllocator.releaseDispatchEntry(dispatchEntry);
Jeff Brownb88102f2010-09-08 11:49:43 -07002209 }
2210
Jeff Brown519e0242010-09-15 15:18:56 -07002211 deactivateConnectionLocked(connection);
Jeff Brownb88102f2010-09-08 11:49:43 -07002212}
2213
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002214int InputDispatcher::handleReceiveCallback(int receiveFd, int events, void* data) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002215 InputDispatcher* d = static_cast<InputDispatcher*>(data);
2216
2217 { // acquire lock
2218 AutoMutex _l(d->mLock);
2219
2220 ssize_t connectionIndex = d->mConnectionsByReceiveFd.indexOfKey(receiveFd);
2221 if (connectionIndex < 0) {
2222 LOGE("Received spurious receive callback for unknown input channel. "
2223 "fd=%d, events=0x%x", receiveFd, events);
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002224 return 0; // remove the callback
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002225 }
2226
Jeff Brown7fbdc842010-06-17 20:52:56 -07002227 nsecs_t currentTime = now();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002228
2229 sp<Connection> connection = d->mConnectionsByReceiveFd.valueAt(connectionIndex);
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002230 if (events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP)) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002231 LOGE("channel '%s' ~ Consumer closed input channel or an error occurred. "
2232 "events=0x%x", connection->getInputChannelName(), events);
Jeff Brownb6997262010-10-08 22:31:17 -07002233 d->abortBrokenDispatchCycleLocked(currentTime, connection);
Jeff Brown9c3cda02010-06-15 01:31:58 -07002234 d->runCommandsLockedInterruptible();
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002235 return 0; // remove the callback
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002236 }
2237
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002238 if (! (events & ALOOPER_EVENT_INPUT)) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002239 LOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
2240 "events=0x%x", connection->getInputChannelName(), events);
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002241 return 1;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002242 }
2243
Jeff Brown3915bb82010-11-05 15:02:16 -07002244 bool handled = false;
Jeff Brown49ed71d2010-12-06 17:13:33 -08002245 status_t status = connection->inputPublisher.receiveFinishedSignal(&handled);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002246 if (status) {
2247 LOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
2248 connection->getInputChannelName(), status);
Jeff Brownb6997262010-10-08 22:31:17 -07002249 d->abortBrokenDispatchCycleLocked(currentTime, connection);
Jeff Brown9c3cda02010-06-15 01:31:58 -07002250 d->runCommandsLockedInterruptible();
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002251 return 0; // remove the callback
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002252 }
2253
Jeff Brown3915bb82010-11-05 15:02:16 -07002254 d->finishDispatchCycleLocked(currentTime, connection, handled);
Jeff Brown9c3cda02010-06-15 01:31:58 -07002255 d->runCommandsLockedInterruptible();
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002256 return 1;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002257 } // release lock
2258}
2259
Jeff Brownb6997262010-10-08 22:31:17 -07002260void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Jeff Brownda3d5a92011-03-29 15:11:34 -07002261 const CancelationOptions& options) {
Jeff Brownb6997262010-10-08 22:31:17 -07002262 for (size_t i = 0; i < mConnectionsByReceiveFd.size(); i++) {
2263 synthesizeCancelationEventsForConnectionLocked(
Jeff Brownda3d5a92011-03-29 15:11:34 -07002264 mConnectionsByReceiveFd.valueAt(i), options);
Jeff Brownb6997262010-10-08 22:31:17 -07002265 }
2266}
2267
2268void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Jeff Brownda3d5a92011-03-29 15:11:34 -07002269 const sp<InputChannel>& channel, const CancelationOptions& options) {
Jeff Brownb6997262010-10-08 22:31:17 -07002270 ssize_t index = getConnectionIndexLocked(channel);
2271 if (index >= 0) {
2272 synthesizeCancelationEventsForConnectionLocked(
Jeff Brownda3d5a92011-03-29 15:11:34 -07002273 mConnectionsByReceiveFd.valueAt(index), options);
Jeff Brownb6997262010-10-08 22:31:17 -07002274 }
2275}
2276
2277void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
Jeff Brownda3d5a92011-03-29 15:11:34 -07002278 const sp<Connection>& connection, const CancelationOptions& options) {
Jeff Brownb6997262010-10-08 22:31:17 -07002279 nsecs_t currentTime = now();
2280
2281 mTempCancelationEvents.clear();
2282 connection->inputState.synthesizeCancelationEvents(currentTime, & mAllocator,
2283 mTempCancelationEvents, options);
2284
2285 if (! mTempCancelationEvents.isEmpty()
2286 && connection->status != Connection::STATUS_BROKEN) {
2287#if DEBUG_OUTBOUND_EVENT_DETAILS
2288 LOGD("channel '%s' ~ Synthesized %d cancelation events to bring channel back in sync "
Jeff Brownda3d5a92011-03-29 15:11:34 -07002289 "with reality: %s, mode=%d.",
2290 connection->getInputChannelName(), mTempCancelationEvents.size(),
2291 options.reason, options.mode);
Jeff Brownb6997262010-10-08 22:31:17 -07002292#endif
2293 for (size_t i = 0; i < mTempCancelationEvents.size(); i++) {
2294 EventEntry* cancelationEventEntry = mTempCancelationEvents.itemAt(i);
2295 switch (cancelationEventEntry->type) {
2296 case EventEntry::TYPE_KEY:
2297 logOutboundKeyDetailsLocked("cancel - ",
2298 static_cast<KeyEntry*>(cancelationEventEntry));
2299 break;
2300 case EventEntry::TYPE_MOTION:
2301 logOutboundMotionDetailsLocked("cancel - ",
2302 static_cast<MotionEntry*>(cancelationEventEntry));
2303 break;
2304 }
2305
2306 int32_t xOffset, yOffset;
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002307 float scaleFactor;
Jeff Brownb6997262010-10-08 22:31:17 -07002308 const InputWindow* window = getWindowLocked(connection->inputChannel);
2309 if (window) {
2310 xOffset = -window->frameLeft;
2311 yOffset = -window->frameTop;
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002312 scaleFactor = window->scaleFactor;
Jeff Brownb6997262010-10-08 22:31:17 -07002313 } else {
2314 xOffset = 0;
2315 yOffset = 0;
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002316 scaleFactor = 1.0f;
Jeff Brownb6997262010-10-08 22:31:17 -07002317 }
2318
2319 DispatchEntry* cancelationDispatchEntry =
2320 mAllocator.obtainDispatchEntry(cancelationEventEntry, // increments ref
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002321 0, xOffset, yOffset, scaleFactor);
Jeff Brownb6997262010-10-08 22:31:17 -07002322 connection->outboundQueue.enqueueAtTail(cancelationDispatchEntry);
2323
2324 mAllocator.releaseEventEntry(cancelationEventEntry);
2325 }
2326
2327 if (!connection->outboundQueue.headSentinel.next->inProgress) {
2328 startDispatchCycleLocked(currentTime, connection);
2329 }
2330 }
2331}
2332
Jeff Brown01ce2e92010-09-26 22:20:12 -07002333InputDispatcher::MotionEntry*
2334InputDispatcher::splitMotionEvent(const MotionEntry* originalMotionEntry, BitSet32 pointerIds) {
Jeff Brownb6110c22011-04-01 16:15:13 -07002335 LOG_ASSERT(pointerIds.value != 0);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002336
2337 uint32_t splitPointerIndexMap[MAX_POINTERS];
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002338 PointerProperties splitPointerProperties[MAX_POINTERS];
Jeff Brown01ce2e92010-09-26 22:20:12 -07002339 PointerCoords splitPointerCoords[MAX_POINTERS];
2340
2341 uint32_t originalPointerCount = originalMotionEntry->pointerCount;
2342 uint32_t splitPointerCount = 0;
2343
2344 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
2345 originalPointerIndex++) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002346 const PointerProperties& pointerProperties =
2347 originalMotionEntry->pointerProperties[originalPointerIndex];
2348 uint32_t pointerId = uint32_t(pointerProperties.id);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002349 if (pointerIds.hasBit(pointerId)) {
2350 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002351 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
Jeff Brownace13b12011-03-09 17:39:48 -08002352 splitPointerCoords[splitPointerCount].copyFrom(
2353 originalMotionEntry->firstSample.pointerCoords[originalPointerIndex]);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002354 splitPointerCount += 1;
2355 }
2356 }
Jeff Brown58a2da82011-01-25 16:02:22 -08002357
2358 if (splitPointerCount != pointerIds.count()) {
2359 // This is bad. We are missing some of the pointers that we expected to deliver.
2360 // Most likely this indicates that we received an ACTION_MOVE events that has
2361 // different pointer ids than we expected based on the previous ACTION_DOWN
2362 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
2363 // in this way.
2364 LOGW("Dropping split motion event because the pointer count is %d but "
2365 "we expected there to be %d pointers. This probably means we received "
2366 "a broken sequence of pointer ids from the input device.",
2367 splitPointerCount, pointerIds.count());
2368 return NULL;
2369 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07002370
2371 int32_t action = originalMotionEntry->action;
2372 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
2373 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
2374 || maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2375 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002376 const PointerProperties& pointerProperties =
2377 originalMotionEntry->pointerProperties[originalPointerIndex];
2378 uint32_t pointerId = uint32_t(pointerProperties.id);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002379 if (pointerIds.hasBit(pointerId)) {
2380 if (pointerIds.count() == 1) {
2381 // The first/last pointer went down/up.
2382 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
2383 ? AMOTION_EVENT_ACTION_DOWN : AMOTION_EVENT_ACTION_UP;
Jeff Brown9a01d052010-09-27 16:35:11 -07002384 } else {
2385 // A secondary pointer went down/up.
2386 uint32_t splitPointerIndex = 0;
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002387 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
Jeff Brown9a01d052010-09-27 16:35:11 -07002388 splitPointerIndex += 1;
2389 }
2390 action = maskedAction | (splitPointerIndex
2391 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002392 }
2393 } else {
2394 // An unrelated pointer changed.
2395 action = AMOTION_EVENT_ACTION_MOVE;
2396 }
2397 }
2398
2399 MotionEntry* splitMotionEntry = mAllocator.obtainMotionEntry(
2400 originalMotionEntry->eventTime,
2401 originalMotionEntry->deviceId,
2402 originalMotionEntry->source,
2403 originalMotionEntry->policyFlags,
2404 action,
2405 originalMotionEntry->flags,
2406 originalMotionEntry->metaState,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002407 originalMotionEntry->buttonState,
Jeff Brown01ce2e92010-09-26 22:20:12 -07002408 originalMotionEntry->edgeFlags,
2409 originalMotionEntry->xPrecision,
2410 originalMotionEntry->yPrecision,
2411 originalMotionEntry->downTime,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002412 splitPointerCount, splitPointerProperties, splitPointerCoords);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002413
2414 for (MotionSample* originalMotionSample = originalMotionEntry->firstSample.next;
2415 originalMotionSample != NULL; originalMotionSample = originalMotionSample->next) {
2416 for (uint32_t splitPointerIndex = 0; splitPointerIndex < splitPointerCount;
2417 splitPointerIndex++) {
2418 uint32_t originalPointerIndex = splitPointerIndexMap[splitPointerIndex];
Jeff Brownace13b12011-03-09 17:39:48 -08002419 splitPointerCoords[splitPointerIndex].copyFrom(
2420 originalMotionSample->pointerCoords[originalPointerIndex]);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002421 }
2422
2423 mAllocator.appendMotionSample(splitMotionEntry, originalMotionSample->eventTime,
2424 splitPointerCoords);
2425 }
2426
Jeff Browna032cc02011-03-07 16:56:21 -08002427 if (originalMotionEntry->injectionState) {
2428 splitMotionEntry->injectionState = originalMotionEntry->injectionState;
2429 splitMotionEntry->injectionState->refCount += 1;
2430 }
2431
Jeff Brown01ce2e92010-09-26 22:20:12 -07002432 return splitMotionEntry;
2433}
2434
Jeff Brown9c3cda02010-06-15 01:31:58 -07002435void InputDispatcher::notifyConfigurationChanged(nsecs_t eventTime) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002436#if DEBUG_INBOUND_EVENT_DETAILS
Jeff Brown9c3cda02010-06-15 01:31:58 -07002437 LOGD("notifyConfigurationChanged - eventTime=%lld", eventTime);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002438#endif
2439
Jeff Brownb88102f2010-09-08 11:49:43 -07002440 bool needWake;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002441 { // acquire lock
2442 AutoMutex _l(mLock);
2443
Jeff Brown7fbdc842010-06-17 20:52:56 -07002444 ConfigurationChangedEntry* newEntry = mAllocator.obtainConfigurationChangedEntry(eventTime);
Jeff Brownb88102f2010-09-08 11:49:43 -07002445 needWake = enqueueInboundEventLocked(newEntry);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002446 } // release lock
2447
Jeff Brownb88102f2010-09-08 11:49:43 -07002448 if (needWake) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002449 mLooper->wake();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002450 }
2451}
2452
Jeff Brown58a2da82011-01-25 16:02:22 -08002453void InputDispatcher::notifyKey(nsecs_t eventTime, int32_t deviceId, uint32_t source,
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002454 uint32_t policyFlags, int32_t action, int32_t flags,
2455 int32_t keyCode, int32_t scanCode, int32_t metaState, nsecs_t downTime) {
2456#if DEBUG_INBOUND_EVENT_DETAILS
Jeff Brown90655042010-12-02 13:50:46 -08002457 LOGD("notifyKey - eventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, action=0x%x, "
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002458 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%lld",
Jeff Brownc5ed5912010-07-14 18:48:53 -07002459 eventTime, deviceId, source, policyFlags, action, flags,
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002460 keyCode, scanCode, metaState, downTime);
2461#endif
Jeff Brown01ce2e92010-09-26 22:20:12 -07002462 if (! validateKeyEvent(action)) {
2463 return;
2464 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002465
Jeff Brown1f245102010-11-18 20:53:46 -08002466 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
2467 policyFlags |= POLICY_FLAG_VIRTUAL;
2468 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
2469 }
Jeff Brown924c4d42011-03-07 16:40:47 -08002470 if (policyFlags & POLICY_FLAG_ALT) {
2471 metaState |= AMETA_ALT_ON | AMETA_ALT_LEFT_ON;
2472 }
2473 if (policyFlags & POLICY_FLAG_ALT_GR) {
2474 metaState |= AMETA_ALT_ON | AMETA_ALT_RIGHT_ON;
2475 }
2476 if (policyFlags & POLICY_FLAG_SHIFT) {
2477 metaState |= AMETA_SHIFT_ON | AMETA_SHIFT_LEFT_ON;
2478 }
2479 if (policyFlags & POLICY_FLAG_CAPS_LOCK) {
2480 metaState |= AMETA_CAPS_LOCK_ON;
2481 }
2482 if (policyFlags & POLICY_FLAG_FUNCTION) {
2483 metaState |= AMETA_FUNCTION_ON;
2484 }
Jeff Brown1f245102010-11-18 20:53:46 -08002485
Jeff Browne20c9e02010-10-11 14:20:19 -07002486 policyFlags |= POLICY_FLAG_TRUSTED;
Jeff Brown1f245102010-11-18 20:53:46 -08002487
2488 KeyEvent event;
2489 event.initialize(deviceId, source, action, flags, keyCode, scanCode,
2490 metaState, 0, downTime, eventTime);
2491
2492 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
2493
2494 if (policyFlags & POLICY_FLAG_WOKE_HERE) {
2495 flags |= AKEY_EVENT_FLAG_WOKE_HERE;
2496 }
Jeff Brownb6997262010-10-08 22:31:17 -07002497
Jeff Brownb88102f2010-09-08 11:49:43 -07002498 bool needWake;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002499 { // acquire lock
Jeff Brown0029c662011-03-30 02:25:18 -07002500 mLock.lock();
2501
2502 if (mInputFilterEnabled) {
2503 mLock.unlock();
2504
2505 policyFlags |= POLICY_FLAG_FILTERED;
2506 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2507 return; // event was consumed by the filter
2508 }
2509
2510 mLock.lock();
2511 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002512
Jeff Brown7fbdc842010-06-17 20:52:56 -07002513 int32_t repeatCount = 0;
2514 KeyEntry* newEntry = mAllocator.obtainKeyEntry(eventTime,
Jeff Brownc5ed5912010-07-14 18:48:53 -07002515 deviceId, source, policyFlags, action, flags, keyCode, scanCode,
Jeff Brown7fbdc842010-06-17 20:52:56 -07002516 metaState, repeatCount, downTime);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002517
Jeff Brownb88102f2010-09-08 11:49:43 -07002518 needWake = enqueueInboundEventLocked(newEntry);
Jeff Brown0029c662011-03-30 02:25:18 -07002519 mLock.unlock();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002520 } // release lock
2521
Jeff Brownb88102f2010-09-08 11:49:43 -07002522 if (needWake) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002523 mLooper->wake();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002524 }
2525}
2526
Jeff Brown58a2da82011-01-25 16:02:22 -08002527void InputDispatcher::notifyMotion(nsecs_t eventTime, int32_t deviceId, uint32_t source,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002528 uint32_t policyFlags, int32_t action, int32_t flags,
2529 int32_t metaState, int32_t buttonState, int32_t edgeFlags,
2530 uint32_t pointerCount, const PointerProperties* pointerProperties,
2531 const PointerCoords* pointerCoords,
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002532 float xPrecision, float yPrecision, nsecs_t downTime) {
2533#if DEBUG_INBOUND_EVENT_DETAILS
Jeff Brown90655042010-12-02 13:50:46 -08002534 LOGD("notifyMotion - eventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, "
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002535 "action=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, edgeFlags=0x%x, "
Jeff Brown85a31762010-09-01 17:01:00 -07002536 "xPrecision=%f, yPrecision=%f, downTime=%lld",
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002537 eventTime, deviceId, source, policyFlags, action, flags,
2538 metaState, buttonState, edgeFlags,
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002539 xPrecision, yPrecision, downTime);
2540 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002541 LOGD(" Pointer %d: id=%d, toolType=%d, "
2542 "x=%f, y=%f, pressure=%f, size=%f, "
Jeff Brown85a31762010-09-01 17:01:00 -07002543 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
Jeff Brown8d608662010-08-30 03:02:23 -07002544 "orientation=%f",
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002545 i, pointerProperties[i].id,
2546 pointerProperties[i].toolType,
Jeff Brownebbd5d12011-02-17 13:01:34 -08002547 pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
2548 pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
2549 pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
2550 pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
2551 pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
2552 pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
2553 pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
2554 pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
2555 pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002556 }
2557#endif
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002558 if (! validateMotionEvent(action, pointerCount, pointerProperties)) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002559 return;
2560 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002561
Jeff Browne20c9e02010-10-11 14:20:19 -07002562 policyFlags |= POLICY_FLAG_TRUSTED;
Jeff Brown56194eb2011-03-02 19:23:13 -08002563 mPolicy->interceptMotionBeforeQueueing(eventTime, /*byref*/ policyFlags);
Jeff Brownb6997262010-10-08 22:31:17 -07002564
Jeff Brownb88102f2010-09-08 11:49:43 -07002565 bool needWake;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002566 { // acquire lock
Jeff Brown0029c662011-03-30 02:25:18 -07002567 mLock.lock();
2568
2569 if (mInputFilterEnabled) {
2570 mLock.unlock();
2571
2572 MotionEvent event;
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002573 event.initialize(deviceId, source, action, flags, edgeFlags, metaState,
2574 buttonState, 0, 0,
Jeff Brown0029c662011-03-30 02:25:18 -07002575 xPrecision, yPrecision, downTime, eventTime,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002576 pointerCount, pointerProperties, pointerCoords);
Jeff Brown0029c662011-03-30 02:25:18 -07002577
2578 policyFlags |= POLICY_FLAG_FILTERED;
2579 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2580 return; // event was consumed by the filter
2581 }
2582
2583 mLock.lock();
2584 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002585
2586 // Attempt batching and streaming of move events.
Jeff Browncc0c1592011-02-19 05:07:28 -08002587 if (action == AMOTION_EVENT_ACTION_MOVE
2588 || action == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002589 // BATCHING CASE
2590 //
2591 // Try to append a move sample to the tail of the inbound queue for this device.
2592 // Give up if we encounter a non-move motion event for this device since that
2593 // means we cannot append any new samples until a new motion event has started.
Jeff Brownb88102f2010-09-08 11:49:43 -07002594 for (EventEntry* entry = mInboundQueue.tailSentinel.prev;
2595 entry != & mInboundQueue.headSentinel; entry = entry->prev) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002596 if (entry->type != EventEntry::TYPE_MOTION) {
2597 // Keep looking for motion events.
2598 continue;
2599 }
2600
2601 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
Jeff Brownefd32662011-03-08 15:13:06 -08002602 if (motionEntry->deviceId != deviceId
2603 || motionEntry->source != source) {
2604 // Keep looking for this device and source.
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002605 continue;
2606 }
2607
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002608 if (!motionEntry->canAppendSamples(action, pointerCount, pointerProperties)) {
Jeff Brownefd32662011-03-08 15:13:06 -08002609 // Last motion event in the queue for this device and source is
2610 // not compatible for appending new samples. Stop here.
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002611 goto NoBatchingOrStreaming;
2612 }
2613
Jeff Brown9c3cda02010-06-15 01:31:58 -07002614 // Do the batching magic.
Jeff Brown4e91a182011-04-07 11:38:09 -07002615 batchMotionLocked(motionEntry, eventTime, metaState, pointerCoords,
2616 "most recent motion event for this device and source in the inbound queue");
Jeff Brown0029c662011-03-30 02:25:18 -07002617 mLock.unlock();
Jeff Brown9c3cda02010-06-15 01:31:58 -07002618 return; // done!
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002619 }
2620
Jeff Brownf6989da2011-04-06 17:19:48 -07002621 // BATCHING ONTO PENDING EVENT CASE
2622 //
2623 // Try to append a move sample to the currently pending event, if there is one.
2624 // We can do this as long as we are still waiting to find the targets for the
2625 // event. Once the targets are locked-in we can only do streaming.
2626 if (mPendingEvent
2627 && (!mPendingEvent->dispatchInProgress || !mCurrentInputTargetsValid)
2628 && mPendingEvent->type == EventEntry::TYPE_MOTION) {
2629 MotionEntry* motionEntry = static_cast<MotionEntry*>(mPendingEvent);
2630 if (motionEntry->deviceId == deviceId && motionEntry->source == source) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002631 if (!motionEntry->canAppendSamples(action, pointerCount, pointerProperties)) {
Jeff Brown4e91a182011-04-07 11:38:09 -07002632 // Pending motion event is for this device and source but it is
2633 // not compatible for appending new samples. Stop here.
Jeff Brownf6989da2011-04-06 17:19:48 -07002634 goto NoBatchingOrStreaming;
2635 }
2636
Jeff Brownf6989da2011-04-06 17:19:48 -07002637 // Do the batching magic.
Jeff Brown4e91a182011-04-07 11:38:09 -07002638 batchMotionLocked(motionEntry, eventTime, metaState, pointerCoords,
2639 "pending motion event");
Jeff Brownf6989da2011-04-06 17:19:48 -07002640 mLock.unlock();
2641 return; // done!
2642 }
2643 }
2644
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002645 // STREAMING CASE
2646 //
2647 // There is no pending motion event (of any kind) for this device in the inbound queue.
Jeff Brown519e0242010-09-15 15:18:56 -07002648 // Search the outbound queue for the current foreground targets to find a dispatched
2649 // motion event that is still in progress. If found, then, appen the new sample to
2650 // that event and push it out to all current targets. The logic in
2651 // prepareDispatchCycleLocked takes care of the case where some targets may
2652 // already have consumed the motion event by starting a new dispatch cycle if needed.
Jeff Brown9c3cda02010-06-15 01:31:58 -07002653 if (mCurrentInputTargetsValid) {
Jeff Brown519e0242010-09-15 15:18:56 -07002654 for (size_t i = 0; i < mCurrentInputTargets.size(); i++) {
2655 const InputTarget& inputTarget = mCurrentInputTargets[i];
2656 if ((inputTarget.flags & InputTarget::FLAG_FOREGROUND) == 0) {
2657 // Skip non-foreground targets. We only want to stream if there is at
2658 // least one foreground target whose dispatch is still in progress.
2659 continue;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002660 }
Jeff Brown519e0242010-09-15 15:18:56 -07002661
2662 ssize_t connectionIndex = getConnectionIndexLocked(inputTarget.inputChannel);
2663 if (connectionIndex < 0) {
2664 // Connection must no longer be valid.
2665 continue;
2666 }
2667
2668 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
2669 if (connection->outboundQueue.isEmpty()) {
2670 // This foreground target has an empty outbound queue.
2671 continue;
2672 }
2673
2674 DispatchEntry* dispatchEntry = connection->outboundQueue.headSentinel.next;
2675 if (! dispatchEntry->inProgress
Jeff Brown01ce2e92010-09-26 22:20:12 -07002676 || dispatchEntry->eventEntry->type != EventEntry::TYPE_MOTION
2677 || dispatchEntry->isSplit()) {
2678 // No motion event is being dispatched, or it is being split across
2679 // windows in which case we cannot stream.
Jeff Brown519e0242010-09-15 15:18:56 -07002680 continue;
2681 }
2682
2683 MotionEntry* motionEntry = static_cast<MotionEntry*>(
2684 dispatchEntry->eventEntry);
Jeff Browncc0c1592011-02-19 05:07:28 -08002685 if (motionEntry->action != action
Jeff Brown519e0242010-09-15 15:18:56 -07002686 || motionEntry->deviceId != deviceId
Jeff Brown58a2da82011-01-25 16:02:22 -08002687 || motionEntry->source != source
Jeff Brown519e0242010-09-15 15:18:56 -07002688 || motionEntry->pointerCount != pointerCount
2689 || motionEntry->isInjected()) {
2690 // The motion event is not compatible with this move.
2691 continue;
2692 }
2693
Jeff Browna032cc02011-03-07 16:56:21 -08002694 if (action == AMOTION_EVENT_ACTION_HOVER_MOVE) {
2695 if (!mLastHoverWindow) {
2696#if DEBUG_BATCHING
2697 LOGD("Not streaming hover move because there is no "
2698 "last hovered window.");
2699#endif
2700 goto NoBatchingOrStreaming;
2701 }
2702
2703 const InputWindow* hoverWindow = findTouchedWindowAtLocked(
2704 pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X),
2705 pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
2706 if (mLastHoverWindow != hoverWindow) {
2707#if DEBUG_BATCHING
2708 LOGD("Not streaming hover move because the last hovered window "
2709 "is '%s' but the currently hovered window is '%s'.",
2710 mLastHoverWindow->name.string(),
2711 hoverWindow ? hoverWindow->name.string() : "<null>");
2712#endif
2713 goto NoBatchingOrStreaming;
2714 }
2715 }
2716
Jeff Brown519e0242010-09-15 15:18:56 -07002717 // Hurray! This foreground target is currently dispatching a move event
2718 // that we can stream onto. Append the motion sample and resume dispatch.
2719 mAllocator.appendMotionSample(motionEntry, eventTime, pointerCoords);
2720#if DEBUG_BATCHING
2721 LOGD("Appended motion sample onto batch for most recently dispatched "
Jeff Brown4e91a182011-04-07 11:38:09 -07002722 "motion event for this device and source in the outbound queues. "
Jeff Brown519e0242010-09-15 15:18:56 -07002723 "Attempting to stream the motion sample.");
2724#endif
2725 nsecs_t currentTime = now();
2726 dispatchEventToCurrentInputTargetsLocked(currentTime, motionEntry,
2727 true /*resumeWithAppendedMotionSample*/);
2728
2729 runCommandsLockedInterruptible();
Jeff Brown0029c662011-03-30 02:25:18 -07002730 mLock.unlock();
Jeff Brown519e0242010-09-15 15:18:56 -07002731 return; // done!
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002732 }
2733 }
2734
2735NoBatchingOrStreaming:;
2736 }
2737
2738 // Just enqueue a new motion event.
Jeff Brown7fbdc842010-06-17 20:52:56 -07002739 MotionEntry* newEntry = mAllocator.obtainMotionEntry(eventTime,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002740 deviceId, source, policyFlags, action, flags, metaState, buttonState, edgeFlags,
Jeff Brown7fbdc842010-06-17 20:52:56 -07002741 xPrecision, yPrecision, downTime,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002742 pointerCount, pointerProperties, pointerCoords);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002743
Jeff Brownb88102f2010-09-08 11:49:43 -07002744 needWake = enqueueInboundEventLocked(newEntry);
Jeff Brown0029c662011-03-30 02:25:18 -07002745 mLock.unlock();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002746 } // release lock
2747
Jeff Brownb88102f2010-09-08 11:49:43 -07002748 if (needWake) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002749 mLooper->wake();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002750 }
2751}
2752
Jeff Brown4e91a182011-04-07 11:38:09 -07002753void InputDispatcher::batchMotionLocked(MotionEntry* entry, nsecs_t eventTime,
2754 int32_t metaState, const PointerCoords* pointerCoords, const char* eventDescription) {
2755 // Combine meta states.
2756 entry->metaState |= metaState;
2757
2758 // Coalesce this sample if not enough time has elapsed since the last sample was
2759 // initially appended to the batch.
2760 MotionSample* lastSample = entry->lastSample;
2761 long interval = eventTime - lastSample->eventTimeBeforeCoalescing;
2762 if (interval <= MOTION_SAMPLE_COALESCE_INTERVAL) {
2763 uint32_t pointerCount = entry->pointerCount;
2764 for (uint32_t i = 0; i < pointerCount; i++) {
2765 lastSample->pointerCoords[i].copyFrom(pointerCoords[i]);
2766 }
2767 lastSample->eventTime = eventTime;
2768#if DEBUG_BATCHING
2769 LOGD("Coalesced motion into last sample of batch for %s, events were %0.3f ms apart",
2770 eventDescription, interval * 0.000001f);
2771#endif
2772 return;
2773 }
2774
2775 // Append the sample.
2776 mAllocator.appendMotionSample(entry, eventTime, pointerCoords);
2777#if DEBUG_BATCHING
2778 LOGD("Appended motion sample onto batch for %s, events were %0.3f ms apart",
2779 eventDescription, interval * 0.000001f);
2780#endif
2781}
2782
Jeff Brownb6997262010-10-08 22:31:17 -07002783void InputDispatcher::notifySwitch(nsecs_t when, int32_t switchCode, int32_t switchValue,
2784 uint32_t policyFlags) {
2785#if DEBUG_INBOUND_EVENT_DETAILS
2786 LOGD("notifySwitch - switchCode=%d, switchValue=%d, policyFlags=0x%x",
2787 switchCode, switchValue, policyFlags);
2788#endif
2789
Jeff Browne20c9e02010-10-11 14:20:19 -07002790 policyFlags |= POLICY_FLAG_TRUSTED;
Jeff Brownb6997262010-10-08 22:31:17 -07002791 mPolicy->notifySwitch(when, switchCode, switchValue, policyFlags);
2792}
2793
Jeff Brown7fbdc842010-06-17 20:52:56 -07002794int32_t InputDispatcher::injectInputEvent(const InputEvent* event,
Jeff Brown0029c662011-03-30 02:25:18 -07002795 int32_t injectorPid, int32_t injectorUid, int32_t syncMode, int32_t timeoutMillis,
2796 uint32_t policyFlags) {
Jeff Brown7fbdc842010-06-17 20:52:56 -07002797#if DEBUG_INBOUND_EVENT_DETAILS
2798 LOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Jeff Brown0029c662011-03-30 02:25:18 -07002799 "syncMode=%d, timeoutMillis=%d, policyFlags=0x%08x",
2800 event->getType(), injectorPid, injectorUid, syncMode, timeoutMillis, policyFlags);
Jeff Brown7fbdc842010-06-17 20:52:56 -07002801#endif
2802
2803 nsecs_t endTime = now() + milliseconds_to_nanoseconds(timeoutMillis);
Jeff Browne20c9e02010-10-11 14:20:19 -07002804
Jeff Brown0029c662011-03-30 02:25:18 -07002805 policyFlags |= POLICY_FLAG_INJECTED;
Jeff Browne20c9e02010-10-11 14:20:19 -07002806 if (hasInjectionPermission(injectorPid, injectorUid)) {
2807 policyFlags |= POLICY_FLAG_TRUSTED;
2808 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07002809
Jeff Brownb6997262010-10-08 22:31:17 -07002810 EventEntry* injectedEntry;
2811 switch (event->getType()) {
2812 case AINPUT_EVENT_TYPE_KEY: {
2813 const KeyEvent* keyEvent = static_cast<const KeyEvent*>(event);
2814 int32_t action = keyEvent->getAction();
2815 if (! validateKeyEvent(action)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07002816 return INPUT_EVENT_INJECTION_FAILED;
2817 }
2818
Jeff Brownb6997262010-10-08 22:31:17 -07002819 int32_t flags = keyEvent->getFlags();
Jeff Brown1f245102010-11-18 20:53:46 -08002820 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
2821 policyFlags |= POLICY_FLAG_VIRTUAL;
2822 }
2823
Jeff Brown0029c662011-03-30 02:25:18 -07002824 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
2825 mPolicy->interceptKeyBeforeQueueing(keyEvent, /*byref*/ policyFlags);
2826 }
Jeff Brown1f245102010-11-18 20:53:46 -08002827
2828 if (policyFlags & POLICY_FLAG_WOKE_HERE) {
2829 flags |= AKEY_EVENT_FLAG_WOKE_HERE;
2830 }
Jeff Brown6ec402b2010-07-28 15:48:59 -07002831
Jeff Brownb6997262010-10-08 22:31:17 -07002832 mLock.lock();
Jeff Brown1f245102010-11-18 20:53:46 -08002833 injectedEntry = mAllocator.obtainKeyEntry(keyEvent->getEventTime(),
2834 keyEvent->getDeviceId(), keyEvent->getSource(),
2835 policyFlags, action, flags,
2836 keyEvent->getKeyCode(), keyEvent->getScanCode(), keyEvent->getMetaState(),
Jeff Brownb6997262010-10-08 22:31:17 -07002837 keyEvent->getRepeatCount(), keyEvent->getDownTime());
2838 break;
2839 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07002840
Jeff Brownb6997262010-10-08 22:31:17 -07002841 case AINPUT_EVENT_TYPE_MOTION: {
2842 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
2843 int32_t action = motionEvent->getAction();
2844 size_t pointerCount = motionEvent->getPointerCount();
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002845 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
2846 if (! validateMotionEvent(action, pointerCount, pointerProperties)) {
Jeff Brownb6997262010-10-08 22:31:17 -07002847 return INPUT_EVENT_INJECTION_FAILED;
2848 }
2849
Jeff Brown0029c662011-03-30 02:25:18 -07002850 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
2851 nsecs_t eventTime = motionEvent->getEventTime();
2852 mPolicy->interceptMotionBeforeQueueing(eventTime, /*byref*/ policyFlags);
2853 }
Jeff Brownb6997262010-10-08 22:31:17 -07002854
2855 mLock.lock();
2856 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
2857 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
2858 MotionEntry* motionEntry = mAllocator.obtainMotionEntry(*sampleEventTimes,
2859 motionEvent->getDeviceId(), motionEvent->getSource(), policyFlags,
2860 action, motionEvent->getFlags(),
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002861 motionEvent->getMetaState(), motionEvent->getButtonState(),
2862 motionEvent->getEdgeFlags(),
Jeff Brownb6997262010-10-08 22:31:17 -07002863 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
2864 motionEvent->getDownTime(), uint32_t(pointerCount),
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002865 pointerProperties, samplePointerCoords);
Jeff Brownb6997262010-10-08 22:31:17 -07002866 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
2867 sampleEventTimes += 1;
2868 samplePointerCoords += pointerCount;
2869 mAllocator.appendMotionSample(motionEntry, *sampleEventTimes, samplePointerCoords);
2870 }
2871 injectedEntry = motionEntry;
2872 break;
2873 }
2874
2875 default:
2876 LOGW("Cannot inject event of type %d", event->getType());
2877 return INPUT_EVENT_INJECTION_FAILED;
2878 }
2879
2880 InjectionState* injectionState = mAllocator.obtainInjectionState(injectorPid, injectorUid);
2881 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
2882 injectionState->injectionIsAsync = true;
2883 }
2884
2885 injectionState->refCount += 1;
2886 injectedEntry->injectionState = injectionState;
2887
2888 bool needWake = enqueueInboundEventLocked(injectedEntry);
2889 mLock.unlock();
Jeff Brown7fbdc842010-06-17 20:52:56 -07002890
Jeff Brownb88102f2010-09-08 11:49:43 -07002891 if (needWake) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002892 mLooper->wake();
Jeff Brown7fbdc842010-06-17 20:52:56 -07002893 }
2894
2895 int32_t injectionResult;
2896 { // acquire lock
2897 AutoMutex _l(mLock);
2898
Jeff Brown6ec402b2010-07-28 15:48:59 -07002899 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
2900 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
2901 } else {
2902 for (;;) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002903 injectionResult = injectionState->injectionResult;
Jeff Brown6ec402b2010-07-28 15:48:59 -07002904 if (injectionResult != INPUT_EVENT_INJECTION_PENDING) {
2905 break;
2906 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07002907
Jeff Brown7fbdc842010-06-17 20:52:56 -07002908 nsecs_t remainingTimeout = endTime - now();
2909 if (remainingTimeout <= 0) {
Jeff Brown6ec402b2010-07-28 15:48:59 -07002910#if DEBUG_INJECTION
2911 LOGD("injectInputEvent - Timed out waiting for injection result "
2912 "to become available.");
2913#endif
Jeff Brown7fbdc842010-06-17 20:52:56 -07002914 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
2915 break;
2916 }
2917
Jeff Brown6ec402b2010-07-28 15:48:59 -07002918 mInjectionResultAvailableCondition.waitRelative(mLock, remainingTimeout);
2919 }
2920
2921 if (injectionResult == INPUT_EVENT_INJECTION_SUCCEEDED
2922 && syncMode == INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002923 while (injectionState->pendingForegroundDispatches != 0) {
Jeff Brown6ec402b2010-07-28 15:48:59 -07002924#if DEBUG_INJECTION
Jeff Brown519e0242010-09-15 15:18:56 -07002925 LOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
Jeff Brown01ce2e92010-09-26 22:20:12 -07002926 injectionState->pendingForegroundDispatches);
Jeff Brown6ec402b2010-07-28 15:48:59 -07002927#endif
2928 nsecs_t remainingTimeout = endTime - now();
2929 if (remainingTimeout <= 0) {
2930#if DEBUG_INJECTION
Jeff Brown519e0242010-09-15 15:18:56 -07002931 LOGD("injectInputEvent - Timed out waiting for pending foreground "
Jeff Brown6ec402b2010-07-28 15:48:59 -07002932 "dispatches to finish.");
2933#endif
2934 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
2935 break;
2936 }
2937
2938 mInjectionSyncFinishedCondition.waitRelative(mLock, remainingTimeout);
2939 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07002940 }
2941 }
2942
Jeff Brown01ce2e92010-09-26 22:20:12 -07002943 mAllocator.releaseInjectionState(injectionState);
Jeff Brown7fbdc842010-06-17 20:52:56 -07002944 } // release lock
2945
Jeff Brown6ec402b2010-07-28 15:48:59 -07002946#if DEBUG_INJECTION
2947 LOGD("injectInputEvent - Finished with result %d. "
2948 "injectorPid=%d, injectorUid=%d",
2949 injectionResult, injectorPid, injectorUid);
2950#endif
2951
Jeff Brown7fbdc842010-06-17 20:52:56 -07002952 return injectionResult;
2953}
2954
Jeff Brownb6997262010-10-08 22:31:17 -07002955bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
2956 return injectorUid == 0
2957 || mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
2958}
2959
Jeff Brown7fbdc842010-06-17 20:52:56 -07002960void InputDispatcher::setInjectionResultLocked(EventEntry* entry, int32_t injectionResult) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002961 InjectionState* injectionState = entry->injectionState;
2962 if (injectionState) {
Jeff Brown7fbdc842010-06-17 20:52:56 -07002963#if DEBUG_INJECTION
2964 LOGD("Setting input event injection result to %d. "
2965 "injectorPid=%d, injectorUid=%d",
Jeff Brown01ce2e92010-09-26 22:20:12 -07002966 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
Jeff Brown7fbdc842010-06-17 20:52:56 -07002967#endif
2968
Jeff Brown0029c662011-03-30 02:25:18 -07002969 if (injectionState->injectionIsAsync
2970 && !(entry->policyFlags & POLICY_FLAG_FILTERED)) {
Jeff Brown6ec402b2010-07-28 15:48:59 -07002971 // Log the outcome since the injector did not wait for the injection result.
2972 switch (injectionResult) {
2973 case INPUT_EVENT_INJECTION_SUCCEEDED:
2974 LOGV("Asynchronous input event injection succeeded.");
2975 break;
2976 case INPUT_EVENT_INJECTION_FAILED:
2977 LOGW("Asynchronous input event injection failed.");
2978 break;
2979 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
2980 LOGW("Asynchronous input event injection permission denied.");
2981 break;
2982 case INPUT_EVENT_INJECTION_TIMED_OUT:
2983 LOGW("Asynchronous input event injection timed out.");
2984 break;
2985 }
2986 }
2987
Jeff Brown01ce2e92010-09-26 22:20:12 -07002988 injectionState->injectionResult = injectionResult;
Jeff Brown7fbdc842010-06-17 20:52:56 -07002989 mInjectionResultAvailableCondition.broadcast();
2990 }
2991}
2992
Jeff Brown01ce2e92010-09-26 22:20:12 -07002993void InputDispatcher::incrementPendingForegroundDispatchesLocked(EventEntry* entry) {
2994 InjectionState* injectionState = entry->injectionState;
2995 if (injectionState) {
2996 injectionState->pendingForegroundDispatches += 1;
2997 }
2998}
2999
Jeff Brown519e0242010-09-15 15:18:56 -07003000void InputDispatcher::decrementPendingForegroundDispatchesLocked(EventEntry* entry) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07003001 InjectionState* injectionState = entry->injectionState;
3002 if (injectionState) {
3003 injectionState->pendingForegroundDispatches -= 1;
Jeff Brown6ec402b2010-07-28 15:48:59 -07003004
Jeff Brown01ce2e92010-09-26 22:20:12 -07003005 if (injectionState->pendingForegroundDispatches == 0) {
3006 mInjectionSyncFinishedCondition.broadcast();
3007 }
Jeff Brownb88102f2010-09-08 11:49:43 -07003008 }
3009}
3010
Jeff Brown01ce2e92010-09-26 22:20:12 -07003011const InputWindow* InputDispatcher::getWindowLocked(const sp<InputChannel>& inputChannel) {
3012 for (size_t i = 0; i < mWindows.size(); i++) {
3013 const InputWindow* window = & mWindows[i];
3014 if (window->inputChannel == inputChannel) {
3015 return window;
3016 }
3017 }
3018 return NULL;
3019}
3020
Jeff Brownb88102f2010-09-08 11:49:43 -07003021void InputDispatcher::setInputWindows(const Vector<InputWindow>& inputWindows) {
3022#if DEBUG_FOCUS
3023 LOGD("setInputWindows");
3024#endif
3025 { // acquire lock
3026 AutoMutex _l(mLock);
3027
Jeff Brown01ce2e92010-09-26 22:20:12 -07003028 // Clear old window pointers.
Jeff Brownb6997262010-10-08 22:31:17 -07003029 sp<InputChannel> oldFocusedWindowChannel;
3030 if (mFocusedWindow) {
3031 oldFocusedWindowChannel = mFocusedWindow->inputChannel;
3032 mFocusedWindow = NULL;
3033 }
Jeff Browna032cc02011-03-07 16:56:21 -08003034 sp<InputChannel> oldLastHoverWindowChannel;
3035 if (mLastHoverWindow) {
3036 oldLastHoverWindowChannel = mLastHoverWindow->inputChannel;
3037 mLastHoverWindow = NULL;
3038 }
Jeff Brownb6997262010-10-08 22:31:17 -07003039
Jeff Brownb88102f2010-09-08 11:49:43 -07003040 mWindows.clear();
Jeff Brown2a95c2a2010-09-16 12:31:46 -07003041
3042 // Loop over new windows and rebuild the necessary window pointers for
3043 // tracking focus and touch.
Jeff Brownb88102f2010-09-08 11:49:43 -07003044 mWindows.appendVector(inputWindows);
3045
3046 size_t numWindows = mWindows.size();
3047 for (size_t i = 0; i < numWindows; i++) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07003048 const InputWindow* window = & mWindows.itemAt(i);
Jeff Brownb88102f2010-09-08 11:49:43 -07003049 if (window->hasFocus) {
3050 mFocusedWindow = window;
Jeff Brown01ce2e92010-09-26 22:20:12 -07003051 break;
Jeff Brownb88102f2010-09-08 11:49:43 -07003052 }
3053 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07003054
Jeff Brownb6997262010-10-08 22:31:17 -07003055 if (oldFocusedWindowChannel != NULL) {
3056 if (!mFocusedWindow || oldFocusedWindowChannel != mFocusedWindow->inputChannel) {
3057#if DEBUG_FOCUS
3058 LOGD("Focus left window: %s",
3059 oldFocusedWindowChannel->getName().string());
3060#endif
Jeff Brownda3d5a92011-03-29 15:11:34 -07003061 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
3062 "focus left window");
3063 synthesizeCancelationEventsForInputChannelLocked(oldFocusedWindowChannel, options);
Jeff Brownb6997262010-10-08 22:31:17 -07003064 oldFocusedWindowChannel.clear();
3065 }
3066 }
3067 if (mFocusedWindow && oldFocusedWindowChannel == NULL) {
3068#if DEBUG_FOCUS
3069 LOGD("Focus entered window: %s",
3070 mFocusedWindow->inputChannel->getName().string());
3071#endif
3072 }
3073
Jeff Brown01ce2e92010-09-26 22:20:12 -07003074 for (size_t i = 0; i < mTouchState.windows.size(); ) {
3075 TouchedWindow& touchedWindow = mTouchState.windows.editItemAt(i);
3076 const InputWindow* window = getWindowLocked(touchedWindow.channel);
3077 if (window) {
3078 touchedWindow.window = window;
3079 i += 1;
3080 } else {
Jeff Brownb6997262010-10-08 22:31:17 -07003081#if DEBUG_FOCUS
3082 LOGD("Touched window was removed: %s", touchedWindow.channel->getName().string());
3083#endif
Jeff Brownda3d5a92011-03-29 15:11:34 -07003084 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
3085 "touched window was removed");
3086 synthesizeCancelationEventsForInputChannelLocked(touchedWindow.channel, options);
Jeff Brownaf48cae2010-10-15 16:20:51 -07003087 mTouchState.windows.removeAt(i);
Jeff Brown01ce2e92010-09-26 22:20:12 -07003088 }
3089 }
Jeff Brownb88102f2010-09-08 11:49:43 -07003090
Jeff Browna032cc02011-03-07 16:56:21 -08003091 // Recover the last hovered window.
3092 if (oldLastHoverWindowChannel != NULL) {
3093 mLastHoverWindow = getWindowLocked(oldLastHoverWindowChannel);
3094 oldLastHoverWindowChannel.clear();
3095 }
3096
Jeff Brownb88102f2010-09-08 11:49:43 -07003097#if DEBUG_FOCUS
Jeff Brownb6997262010-10-08 22:31:17 -07003098 //logDispatchStateLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -07003099#endif
3100 } // release lock
3101
3102 // Wake up poll loop since it may need to make new input dispatching choices.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07003103 mLooper->wake();
Jeff Brownb88102f2010-09-08 11:49:43 -07003104}
3105
3106void InputDispatcher::setFocusedApplication(const InputApplication* inputApplication) {
3107#if DEBUG_FOCUS
3108 LOGD("setFocusedApplication");
3109#endif
3110 { // acquire lock
3111 AutoMutex _l(mLock);
3112
3113 releaseFocusedApplicationLocked();
3114
3115 if (inputApplication) {
3116 mFocusedApplicationStorage = *inputApplication;
3117 mFocusedApplication = & mFocusedApplicationStorage;
3118 }
3119
3120#if DEBUG_FOCUS
Jeff Brownb6997262010-10-08 22:31:17 -07003121 //logDispatchStateLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -07003122#endif
3123 } // release lock
3124
3125 // Wake up poll loop since it may need to make new input dispatching choices.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07003126 mLooper->wake();
Jeff Brownb88102f2010-09-08 11:49:43 -07003127}
3128
3129void InputDispatcher::releaseFocusedApplicationLocked() {
3130 if (mFocusedApplication) {
3131 mFocusedApplication = NULL;
Jeff Brown928e0542011-01-10 11:17:36 -08003132 mFocusedApplicationStorage.inputApplicationHandle.clear();
Jeff Brownb88102f2010-09-08 11:49:43 -07003133 }
3134}
3135
3136void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
3137#if DEBUG_FOCUS
3138 LOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
3139#endif
3140
3141 bool changed;
3142 { // acquire lock
3143 AutoMutex _l(mLock);
3144
3145 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
Jeff Brown120a4592010-10-27 18:43:51 -07003146 if (mDispatchFrozen && !frozen) {
Jeff Brownb88102f2010-09-08 11:49:43 -07003147 resetANRTimeoutsLocked();
3148 }
3149
Jeff Brown120a4592010-10-27 18:43:51 -07003150 if (mDispatchEnabled && !enabled) {
3151 resetAndDropEverythingLocked("dispatcher is being disabled");
3152 }
3153
Jeff Brownb88102f2010-09-08 11:49:43 -07003154 mDispatchEnabled = enabled;
3155 mDispatchFrozen = frozen;
3156 changed = true;
3157 } else {
3158 changed = false;
3159 }
3160
3161#if DEBUG_FOCUS
Jeff Brownb6997262010-10-08 22:31:17 -07003162 //logDispatchStateLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -07003163#endif
3164 } // release lock
3165
3166 if (changed) {
3167 // Wake up poll loop since it may need to make new input dispatching choices.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07003168 mLooper->wake();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003169 }
3170}
3171
Jeff Brown0029c662011-03-30 02:25:18 -07003172void InputDispatcher::setInputFilterEnabled(bool enabled) {
3173#if DEBUG_FOCUS
3174 LOGD("setInputFilterEnabled: enabled=%d", enabled);
3175#endif
3176
3177 { // acquire lock
3178 AutoMutex _l(mLock);
3179
3180 if (mInputFilterEnabled == enabled) {
3181 return;
3182 }
3183
3184 mInputFilterEnabled = enabled;
3185 resetAndDropEverythingLocked("input filter is being enabled or disabled");
3186 } // release lock
3187
3188 // Wake up poll loop since there might be work to do to drop everything.
3189 mLooper->wake();
3190}
3191
Jeff Browne6504122010-09-27 14:52:15 -07003192bool InputDispatcher::transferTouchFocus(const sp<InputChannel>& fromChannel,
3193 const sp<InputChannel>& toChannel) {
3194#if DEBUG_FOCUS
3195 LOGD("transferTouchFocus: fromChannel=%s, toChannel=%s",
3196 fromChannel->getName().string(), toChannel->getName().string());
3197#endif
3198 { // acquire lock
3199 AutoMutex _l(mLock);
3200
3201 const InputWindow* fromWindow = getWindowLocked(fromChannel);
3202 const InputWindow* toWindow = getWindowLocked(toChannel);
3203 if (! fromWindow || ! toWindow) {
3204#if DEBUG_FOCUS
3205 LOGD("Cannot transfer focus because from or to window not found.");
3206#endif
3207 return false;
3208 }
3209 if (fromWindow == toWindow) {
3210#if DEBUG_FOCUS
3211 LOGD("Trivial transfer to same window.");
3212#endif
3213 return true;
3214 }
3215
3216 bool found = false;
3217 for (size_t i = 0; i < mTouchState.windows.size(); i++) {
3218 const TouchedWindow& touchedWindow = mTouchState.windows[i];
3219 if (touchedWindow.window == fromWindow) {
3220 int32_t oldTargetFlags = touchedWindow.targetFlags;
3221 BitSet32 pointerIds = touchedWindow.pointerIds;
3222
3223 mTouchState.windows.removeAt(i);
3224
Jeff Brown46e75292010-11-10 16:53:45 -08003225 int32_t newTargetFlags = oldTargetFlags
Jeff Browna032cc02011-03-07 16:56:21 -08003226 & (InputTarget::FLAG_FOREGROUND
3227 | InputTarget::FLAG_SPLIT | InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Browne6504122010-09-27 14:52:15 -07003228 mTouchState.addOrUpdateWindow(toWindow, newTargetFlags, pointerIds);
3229
3230 found = true;
3231 break;
3232 }
3233 }
3234
3235 if (! found) {
3236#if DEBUG_FOCUS
3237 LOGD("Focus transfer failed because from window did not have focus.");
3238#endif
3239 return false;
3240 }
3241
Jeff Brown9c9f1a32010-10-11 18:32:20 -07003242 ssize_t fromConnectionIndex = getConnectionIndexLocked(fromChannel);
3243 ssize_t toConnectionIndex = getConnectionIndexLocked(toChannel);
3244 if (fromConnectionIndex >= 0 && toConnectionIndex >= 0) {
3245 sp<Connection> fromConnection = mConnectionsByReceiveFd.valueAt(fromConnectionIndex);
3246 sp<Connection> toConnection = mConnectionsByReceiveFd.valueAt(toConnectionIndex);
3247
3248 fromConnection->inputState.copyPointerStateTo(toConnection->inputState);
Jeff Brownda3d5a92011-03-29 15:11:34 -07003249 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Jeff Brown9c9f1a32010-10-11 18:32:20 -07003250 "transferring touch focus from this window to another window");
Jeff Brownda3d5a92011-03-29 15:11:34 -07003251 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Jeff Brown9c9f1a32010-10-11 18:32:20 -07003252 }
3253
Jeff Browne6504122010-09-27 14:52:15 -07003254#if DEBUG_FOCUS
3255 logDispatchStateLocked();
3256#endif
3257 } // release lock
3258
3259 // Wake up poll loop since it may need to make new input dispatching choices.
3260 mLooper->wake();
3261 return true;
3262}
3263
Jeff Brown120a4592010-10-27 18:43:51 -07003264void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
3265#if DEBUG_FOCUS
3266 LOGD("Resetting and dropping all events (%s).", reason);
3267#endif
3268
Jeff Brownda3d5a92011-03-29 15:11:34 -07003269 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
3270 synthesizeCancelationEventsForAllConnectionsLocked(options);
Jeff Brown120a4592010-10-27 18:43:51 -07003271
3272 resetKeyRepeatLocked();
3273 releasePendingEventLocked();
3274 drainInboundQueueLocked();
3275 resetTargetsLocked();
3276
3277 mTouchState.reset();
3278}
3279
Jeff Brownb88102f2010-09-08 11:49:43 -07003280void InputDispatcher::logDispatchStateLocked() {
3281 String8 dump;
3282 dumpDispatchStateLocked(dump);
Jeff Brown2a95c2a2010-09-16 12:31:46 -07003283
3284 char* text = dump.lockBuffer(dump.size());
3285 char* start = text;
3286 while (*start != '\0') {
3287 char* end = strchr(start, '\n');
3288 if (*end == '\n') {
3289 *(end++) = '\0';
3290 }
3291 LOGD("%s", start);
3292 start = end;
3293 }
Jeff Brownb88102f2010-09-08 11:49:43 -07003294}
3295
3296void InputDispatcher::dumpDispatchStateLocked(String8& dump) {
Jeff Brownf2f487182010-10-01 17:46:21 -07003297 dump.appendFormat(INDENT "DispatchEnabled: %d\n", mDispatchEnabled);
3298 dump.appendFormat(INDENT "DispatchFrozen: %d\n", mDispatchFrozen);
Jeff Brownb88102f2010-09-08 11:49:43 -07003299
3300 if (mFocusedApplication) {
Jeff Brownf2f487182010-10-01 17:46:21 -07003301 dump.appendFormat(INDENT "FocusedApplication: name='%s', dispatchingTimeout=%0.3fms\n",
Jeff Brownb88102f2010-09-08 11:49:43 -07003302 mFocusedApplication->name.string(),
3303 mFocusedApplication->dispatchingTimeout / 1000000.0);
3304 } else {
Jeff Brownf2f487182010-10-01 17:46:21 -07003305 dump.append(INDENT "FocusedApplication: <null>\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003306 }
Jeff Brownf2f487182010-10-01 17:46:21 -07003307 dump.appendFormat(INDENT "FocusedWindow: name='%s'\n",
Jeff Brown2a95c2a2010-09-16 12:31:46 -07003308 mFocusedWindow != NULL ? mFocusedWindow->name.string() : "<null>");
Jeff Brownf2f487182010-10-01 17:46:21 -07003309
3310 dump.appendFormat(INDENT "TouchDown: %s\n", toString(mTouchState.down));
3311 dump.appendFormat(INDENT "TouchSplit: %s\n", toString(mTouchState.split));
Jeff Brown95712852011-01-04 19:41:59 -08003312 dump.appendFormat(INDENT "TouchDeviceId: %d\n", mTouchState.deviceId);
Jeff Brown58a2da82011-01-25 16:02:22 -08003313 dump.appendFormat(INDENT "TouchSource: 0x%08x\n", mTouchState.source);
Jeff Brownf2f487182010-10-01 17:46:21 -07003314 if (!mTouchState.windows.isEmpty()) {
3315 dump.append(INDENT "TouchedWindows:\n");
3316 for (size_t i = 0; i < mTouchState.windows.size(); i++) {
3317 const TouchedWindow& touchedWindow = mTouchState.windows[i];
3318 dump.appendFormat(INDENT2 "%d: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
3319 i, touchedWindow.window->name.string(), touchedWindow.pointerIds.value,
3320 touchedWindow.targetFlags);
3321 }
3322 } else {
3323 dump.append(INDENT "TouchedWindows: <none>\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003324 }
3325
Jeff Brownf2f487182010-10-01 17:46:21 -07003326 if (!mWindows.isEmpty()) {
3327 dump.append(INDENT "Windows:\n");
3328 for (size_t i = 0; i < mWindows.size(); i++) {
3329 const InputWindow& window = mWindows[i];
3330 dump.appendFormat(INDENT2 "%d: name='%s', paused=%s, hasFocus=%s, hasWallpaper=%s, "
3331 "visible=%s, canReceiveKeys=%s, flags=0x%08x, type=0x%08x, layer=%d, "
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003332 "frame=[%d,%d][%d,%d], scale=%f, "
Jeff Brownfbf09772011-01-16 14:06:57 -08003333 "touchableRegion=",
Jeff Brownf2f487182010-10-01 17:46:21 -07003334 i, window.name.string(),
3335 toString(window.paused),
3336 toString(window.hasFocus),
3337 toString(window.hasWallpaper),
3338 toString(window.visible),
3339 toString(window.canReceiveKeys),
3340 window.layoutParamsFlags, window.layoutParamsType,
3341 window.layer,
3342 window.frameLeft, window.frameTop,
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003343 window.frameRight, window.frameBottom,
3344 window.scaleFactor);
Jeff Brownfbf09772011-01-16 14:06:57 -08003345 dumpRegion(dump, window.touchableRegion);
3346 dump.appendFormat(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%0.3fms\n",
Jeff Brownf2f487182010-10-01 17:46:21 -07003347 window.ownerPid, window.ownerUid,
3348 window.dispatchingTimeout / 1000000.0);
3349 }
3350 } else {
3351 dump.append(INDENT "Windows: <none>\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003352 }
3353
Jeff Brownf2f487182010-10-01 17:46:21 -07003354 if (!mMonitoringChannels.isEmpty()) {
3355 dump.append(INDENT "MonitoringChannels:\n");
3356 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
3357 const sp<InputChannel>& channel = mMonitoringChannels[i];
3358 dump.appendFormat(INDENT2 "%d: '%s'\n", i, channel->getName().string());
3359 }
3360 } else {
3361 dump.append(INDENT "MonitoringChannels: <none>\n");
3362 }
Jeff Brown519e0242010-09-15 15:18:56 -07003363
Jeff Brownf2f487182010-10-01 17:46:21 -07003364 dump.appendFormat(INDENT "InboundQueue: length=%u\n", mInboundQueue.count());
3365
3366 if (!mActiveConnections.isEmpty()) {
3367 dump.append(INDENT "ActiveConnections:\n");
3368 for (size_t i = 0; i < mActiveConnections.size(); i++) {
3369 const Connection* connection = mActiveConnections[i];
Jeff Brown76860e32010-10-25 17:37:46 -07003370 dump.appendFormat(INDENT2 "%d: '%s', status=%s, outboundQueueLength=%u, "
Jeff Brownb6997262010-10-08 22:31:17 -07003371 "inputState.isNeutral=%s\n",
Jeff Brownf2f487182010-10-01 17:46:21 -07003372 i, connection->getInputChannelName(), connection->getStatusLabel(),
3373 connection->outboundQueue.count(),
Jeff Brownb6997262010-10-08 22:31:17 -07003374 toString(connection->inputState.isNeutral()));
Jeff Brownf2f487182010-10-01 17:46:21 -07003375 }
3376 } else {
3377 dump.append(INDENT "ActiveConnections: <none>\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003378 }
3379
3380 if (isAppSwitchPendingLocked()) {
Jeff Brownf2f487182010-10-01 17:46:21 -07003381 dump.appendFormat(INDENT "AppSwitch: pending, due in %01.1fms\n",
Jeff Brownb88102f2010-09-08 11:49:43 -07003382 (mAppSwitchDueTime - now()) / 1000000.0);
3383 } else {
Jeff Brownf2f487182010-10-01 17:46:21 -07003384 dump.append(INDENT "AppSwitch: not pending\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003385 }
3386}
3387
Jeff Brown928e0542011-01-10 11:17:36 -08003388status_t InputDispatcher::registerInputChannel(const sp<InputChannel>& inputChannel,
3389 const sp<InputWindowHandle>& inputWindowHandle, bool monitor) {
Jeff Brown9c3cda02010-06-15 01:31:58 -07003390#if DEBUG_REGISTRATION
Jeff Brownb88102f2010-09-08 11:49:43 -07003391 LOGD("channel '%s' ~ registerInputChannel - monitor=%s", inputChannel->getName().string(),
3392 toString(monitor));
Jeff Brown9c3cda02010-06-15 01:31:58 -07003393#endif
3394
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003395 { // acquire lock
3396 AutoMutex _l(mLock);
3397
Jeff Brown519e0242010-09-15 15:18:56 -07003398 if (getConnectionIndexLocked(inputChannel) >= 0) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003399 LOGW("Attempted to register already registered input channel '%s'",
3400 inputChannel->getName().string());
3401 return BAD_VALUE;
3402 }
3403
Jeff Brown928e0542011-01-10 11:17:36 -08003404 sp<Connection> connection = new Connection(inputChannel, inputWindowHandle);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003405 status_t status = connection->initialize();
3406 if (status) {
3407 LOGE("Failed to initialize input publisher for input channel '%s', status=%d",
3408 inputChannel->getName().string(), status);
3409 return status;
3410 }
3411
Jeff Brown2cbecea2010-08-17 15:59:26 -07003412 int32_t receiveFd = inputChannel->getReceivePipeFd();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003413 mConnectionsByReceiveFd.add(receiveFd, connection);
Jeff Brown9c3cda02010-06-15 01:31:58 -07003414
Jeff Brownb88102f2010-09-08 11:49:43 -07003415 if (monitor) {
3416 mMonitoringChannels.push(inputChannel);
3417 }
3418
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07003419 mLooper->addFd(receiveFd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
Jeff Brown2cbecea2010-08-17 15:59:26 -07003420
Jeff Brown9c3cda02010-06-15 01:31:58 -07003421 runCommandsLockedInterruptible();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003422 } // release lock
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003423 return OK;
3424}
3425
3426status_t InputDispatcher::unregisterInputChannel(const sp<InputChannel>& inputChannel) {
Jeff Brown9c3cda02010-06-15 01:31:58 -07003427#if DEBUG_REGISTRATION
Jeff Brown349703e2010-06-22 01:27:15 -07003428 LOGD("channel '%s' ~ unregisterInputChannel", inputChannel->getName().string());
Jeff Brown9c3cda02010-06-15 01:31:58 -07003429#endif
3430
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003431 { // acquire lock
3432 AutoMutex _l(mLock);
3433
Jeff Brown519e0242010-09-15 15:18:56 -07003434 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003435 if (connectionIndex < 0) {
3436 LOGW("Attempted to unregister already unregistered input channel '%s'",
3437 inputChannel->getName().string());
3438 return BAD_VALUE;
3439 }
3440
3441 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
3442 mConnectionsByReceiveFd.removeItemsAt(connectionIndex);
3443
3444 connection->status = Connection::STATUS_ZOMBIE;
3445
Jeff Brownb88102f2010-09-08 11:49:43 -07003446 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
3447 if (mMonitoringChannels[i] == inputChannel) {
3448 mMonitoringChannels.removeAt(i);
3449 break;
3450 }
3451 }
3452
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07003453 mLooper->removeFd(inputChannel->getReceivePipeFd());
Jeff Brown2cbecea2010-08-17 15:59:26 -07003454
Jeff Brown7fbdc842010-06-17 20:52:56 -07003455 nsecs_t currentTime = now();
Jeff Brownb6997262010-10-08 22:31:17 -07003456 abortBrokenDispatchCycleLocked(currentTime, connection);
Jeff Brown9c3cda02010-06-15 01:31:58 -07003457
3458 runCommandsLockedInterruptible();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003459 } // release lock
3460
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003461 // Wake the poll loop because removing the connection may have changed the current
3462 // synchronization state.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07003463 mLooper->wake();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003464 return OK;
3465}
3466
Jeff Brown519e0242010-09-15 15:18:56 -07003467ssize_t InputDispatcher::getConnectionIndexLocked(const sp<InputChannel>& inputChannel) {
Jeff Brown2cbecea2010-08-17 15:59:26 -07003468 ssize_t connectionIndex = mConnectionsByReceiveFd.indexOfKey(inputChannel->getReceivePipeFd());
3469 if (connectionIndex >= 0) {
3470 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
3471 if (connection->inputChannel.get() == inputChannel.get()) {
3472 return connectionIndex;
3473 }
3474 }
3475
3476 return -1;
3477}
3478
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003479void InputDispatcher::activateConnectionLocked(Connection* connection) {
3480 for (size_t i = 0; i < mActiveConnections.size(); i++) {
3481 if (mActiveConnections.itemAt(i) == connection) {
3482 return;
3483 }
3484 }
3485 mActiveConnections.add(connection);
3486}
3487
3488void InputDispatcher::deactivateConnectionLocked(Connection* connection) {
3489 for (size_t i = 0; i < mActiveConnections.size(); i++) {
3490 if (mActiveConnections.itemAt(i) == connection) {
3491 mActiveConnections.removeAt(i);
3492 return;
3493 }
3494 }
3495}
3496
Jeff Brown9c3cda02010-06-15 01:31:58 -07003497void InputDispatcher::onDispatchCycleStartedLocked(
Jeff Brown7fbdc842010-06-17 20:52:56 -07003498 nsecs_t currentTime, const sp<Connection>& connection) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003499}
3500
Jeff Brown9c3cda02010-06-15 01:31:58 -07003501void InputDispatcher::onDispatchCycleFinishedLocked(
Jeff Brown3915bb82010-11-05 15:02:16 -07003502 nsecs_t currentTime, const sp<Connection>& connection, bool handled) {
3503 CommandEntry* commandEntry = postCommandLocked(
3504 & InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
3505 commandEntry->connection = connection;
3506 commandEntry->handled = handled;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003507}
3508
Jeff Brown9c3cda02010-06-15 01:31:58 -07003509void InputDispatcher::onDispatchCycleBrokenLocked(
Jeff Brown7fbdc842010-06-17 20:52:56 -07003510 nsecs_t currentTime, const sp<Connection>& connection) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003511 LOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
3512 connection->getInputChannelName());
3513
Jeff Brown9c3cda02010-06-15 01:31:58 -07003514 CommandEntry* commandEntry = postCommandLocked(
3515 & InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
Jeff Brown7fbdc842010-06-17 20:52:56 -07003516 commandEntry->connection = connection;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003517}
3518
Jeff Brown519e0242010-09-15 15:18:56 -07003519void InputDispatcher::onANRLocked(
3520 nsecs_t currentTime, const InputApplication* application, const InputWindow* window,
3521 nsecs_t eventTime, nsecs_t waitStartTime) {
3522 LOGI("Application is not responding: %s. "
3523 "%01.1fms since event, %01.1fms since wait started",
3524 getApplicationWindowLabelLocked(application, window).string(),
3525 (currentTime - eventTime) / 1000000.0,
3526 (currentTime - waitStartTime) / 1000000.0);
3527
3528 CommandEntry* commandEntry = postCommandLocked(
3529 & InputDispatcher::doNotifyANRLockedInterruptible);
3530 if (application) {
Jeff Brown928e0542011-01-10 11:17:36 -08003531 commandEntry->inputApplicationHandle = application->inputApplicationHandle;
Jeff Brown519e0242010-09-15 15:18:56 -07003532 }
3533 if (window) {
Jeff Brown928e0542011-01-10 11:17:36 -08003534 commandEntry->inputWindowHandle = window->inputWindowHandle;
Jeff Brown519e0242010-09-15 15:18:56 -07003535 commandEntry->inputChannel = window->inputChannel;
3536 }
3537}
3538
Jeff Brownb88102f2010-09-08 11:49:43 -07003539void InputDispatcher::doNotifyConfigurationChangedInterruptible(
3540 CommandEntry* commandEntry) {
3541 mLock.unlock();
3542
3543 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
3544
3545 mLock.lock();
3546}
3547
Jeff Brown9c3cda02010-06-15 01:31:58 -07003548void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(
3549 CommandEntry* commandEntry) {
Jeff Brown7fbdc842010-06-17 20:52:56 -07003550 sp<Connection> connection = commandEntry->connection;
Jeff Brown9c3cda02010-06-15 01:31:58 -07003551
Jeff Brown7fbdc842010-06-17 20:52:56 -07003552 if (connection->status != Connection::STATUS_ZOMBIE) {
3553 mLock.unlock();
Jeff Brown9c3cda02010-06-15 01:31:58 -07003554
Jeff Brown928e0542011-01-10 11:17:36 -08003555 mPolicy->notifyInputChannelBroken(connection->inputWindowHandle);
Jeff Brown7fbdc842010-06-17 20:52:56 -07003556
3557 mLock.lock();
3558 }
Jeff Brown9c3cda02010-06-15 01:31:58 -07003559}
3560
Jeff Brown519e0242010-09-15 15:18:56 -07003561void InputDispatcher::doNotifyANRLockedInterruptible(
Jeff Brown9c3cda02010-06-15 01:31:58 -07003562 CommandEntry* commandEntry) {
Jeff Brown519e0242010-09-15 15:18:56 -07003563 mLock.unlock();
Jeff Brown9c3cda02010-06-15 01:31:58 -07003564
Jeff Brown519e0242010-09-15 15:18:56 -07003565 nsecs_t newTimeout = mPolicy->notifyANR(
Jeff Brown928e0542011-01-10 11:17:36 -08003566 commandEntry->inputApplicationHandle, commandEntry->inputWindowHandle);
Jeff Brown9c3cda02010-06-15 01:31:58 -07003567
Jeff Brown519e0242010-09-15 15:18:56 -07003568 mLock.lock();
Jeff Brown7fbdc842010-06-17 20:52:56 -07003569
Jeff Brown519e0242010-09-15 15:18:56 -07003570 resumeAfterTargetsNotReadyTimeoutLocked(newTimeout, commandEntry->inputChannel);
Jeff Brown9c3cda02010-06-15 01:31:58 -07003571}
3572
Jeff Brownb88102f2010-09-08 11:49:43 -07003573void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
3574 CommandEntry* commandEntry) {
3575 KeyEntry* entry = commandEntry->keyEntry;
Jeff Brown1f245102010-11-18 20:53:46 -08003576
3577 KeyEvent event;
3578 initializeKeyEvent(&event, entry);
Jeff Brownb88102f2010-09-08 11:49:43 -07003579
3580 mLock.unlock();
3581
Jeff Brown928e0542011-01-10 11:17:36 -08003582 bool consumed = mPolicy->interceptKeyBeforeDispatching(commandEntry->inputWindowHandle,
Jeff Brown1f245102010-11-18 20:53:46 -08003583 &event, entry->policyFlags);
Jeff Brownb88102f2010-09-08 11:49:43 -07003584
3585 mLock.lock();
3586
3587 entry->interceptKeyResult = consumed
3588 ? KeyEntry::INTERCEPT_KEY_RESULT_SKIP
3589 : KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
3590 mAllocator.releaseKeyEntry(entry);
3591}
3592
Jeff Brown3915bb82010-11-05 15:02:16 -07003593void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(
3594 CommandEntry* commandEntry) {
3595 sp<Connection> connection = commandEntry->connection;
3596 bool handled = commandEntry->handled;
3597
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003598 bool skipNext = false;
Jeff Brown49ed71d2010-12-06 17:13:33 -08003599 if (!connection->outboundQueue.isEmpty()) {
Jeff Brown3915bb82010-11-05 15:02:16 -07003600 DispatchEntry* dispatchEntry = connection->outboundQueue.headSentinel.next;
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003601 if (dispatchEntry->inProgress) {
3602 if (dispatchEntry->eventEntry->type == EventEntry::TYPE_KEY) {
3603 KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry);
3604 skipNext = afterKeyEventLockedInterruptible(connection,
3605 dispatchEntry, keyEntry, handled);
3606 } else if (dispatchEntry->eventEntry->type == EventEntry::TYPE_MOTION) {
3607 MotionEntry* motionEntry = static_cast<MotionEntry*>(dispatchEntry->eventEntry);
3608 skipNext = afterMotionEventLockedInterruptible(connection,
3609 dispatchEntry, motionEntry, handled);
Jeff Brown49ed71d2010-12-06 17:13:33 -08003610 }
Jeff Brown3915bb82010-11-05 15:02:16 -07003611 }
3612 }
3613
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003614 if (!skipNext) {
3615 startNextDispatchCycleLocked(now(), connection);
3616 }
3617}
3618
3619bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
3620 DispatchEntry* dispatchEntry, KeyEntry* keyEntry, bool handled) {
3621 if (!(keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK)) {
3622 // Get the fallback key state.
3623 // Clear it out after dispatching the UP.
3624 int32_t originalKeyCode = keyEntry->keyCode;
3625 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
3626 if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
3627 connection->inputState.removeFallbackKey(originalKeyCode);
3628 }
3629
3630 if (handled || !dispatchEntry->hasForegroundTarget()) {
3631 // If the application handles the original key for which we previously
3632 // generated a fallback or if the window is not a foreground window,
3633 // then cancel the associated fallback key, if any.
3634 if (fallbackKeyCode != -1) {
3635 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
3636 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
3637 "application handled the original non-fallback key "
3638 "or is no longer a foreground target, "
3639 "canceling previously dispatched fallback key");
3640 options.keyCode = fallbackKeyCode;
3641 synthesizeCancelationEventsForConnectionLocked(connection, options);
3642 }
3643 connection->inputState.removeFallbackKey(originalKeyCode);
3644 }
3645 } else {
3646 // If the application did not handle a non-fallback key, first check
3647 // that we are in a good state to perform unhandled key event processing
3648 // Then ask the policy what to do with it.
3649 bool initialDown = keyEntry->action == AKEY_EVENT_ACTION_DOWN
3650 && keyEntry->repeatCount == 0;
3651 if (fallbackKeyCode == -1 && !initialDown) {
3652#if DEBUG_OUTBOUND_EVENT_DETAILS
3653 LOGD("Unhandled key event: Skipping unhandled key event processing "
3654 "since this is not an initial down. "
3655 "keyCode=%d, action=%d, repeatCount=%d",
3656 originalKeyCode, keyEntry->action, keyEntry->repeatCount);
3657#endif
3658 return false;
3659 }
3660
3661 // Dispatch the unhandled key to the policy.
3662#if DEBUG_OUTBOUND_EVENT_DETAILS
3663 LOGD("Unhandled key event: Asking policy to perform fallback action. "
3664 "keyCode=%d, action=%d, repeatCount=%d",
3665 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount);
3666#endif
3667 KeyEvent event;
3668 initializeKeyEvent(&event, keyEntry);
3669
3670 mLock.unlock();
3671
3672 bool fallback = mPolicy->dispatchUnhandledKey(connection->inputWindowHandle,
3673 &event, keyEntry->policyFlags, &event);
3674
3675 mLock.lock();
3676
3677 if (connection->status != Connection::STATUS_NORMAL) {
3678 connection->inputState.removeFallbackKey(originalKeyCode);
3679 return true; // skip next cycle
3680 }
3681
3682 LOG_ASSERT(connection->outboundQueue.headSentinel.next == dispatchEntry);
3683
3684 // Latch the fallback keycode for this key on an initial down.
3685 // The fallback keycode cannot change at any other point in the lifecycle.
3686 if (initialDown) {
3687 if (fallback) {
3688 fallbackKeyCode = event.getKeyCode();
3689 } else {
3690 fallbackKeyCode = AKEYCODE_UNKNOWN;
3691 }
3692 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
3693 }
3694
3695 LOG_ASSERT(fallbackKeyCode != -1);
3696
3697 // Cancel the fallback key if the policy decides not to send it anymore.
3698 // We will continue to dispatch the key to the policy but we will no
3699 // longer dispatch a fallback key to the application.
3700 if (fallbackKeyCode != AKEYCODE_UNKNOWN
3701 && (!fallback || fallbackKeyCode != event.getKeyCode())) {
3702#if DEBUG_OUTBOUND_EVENT_DETAILS
3703 if (fallback) {
3704 LOGD("Unhandled key event: Policy requested to send key %d"
3705 "as a fallback for %d, but on the DOWN it had requested "
3706 "to send %d instead. Fallback canceled.",
3707 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
3708 } else {
3709 LOGD("Unhandled key event: Policy did not request fallback for %d,"
3710 "but on the DOWN it had requested to send %d. "
3711 "Fallback canceled.",
3712 originalKeyCode, fallbackKeyCode);
3713 }
3714#endif
3715
3716 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
3717 "canceling fallback, policy no longer desires it");
3718 options.keyCode = fallbackKeyCode;
3719 synthesizeCancelationEventsForConnectionLocked(connection, options);
3720
3721 fallback = false;
3722 fallbackKeyCode = AKEYCODE_UNKNOWN;
3723 if (keyEntry->action != AKEY_EVENT_ACTION_UP) {
3724 connection->inputState.setFallbackKey(originalKeyCode,
3725 fallbackKeyCode);
3726 }
3727 }
3728
3729#if DEBUG_OUTBOUND_EVENT_DETAILS
3730 {
3731 String8 msg;
3732 const KeyedVector<int32_t, int32_t>& fallbackKeys =
3733 connection->inputState.getFallbackKeys();
3734 for (size_t i = 0; i < fallbackKeys.size(); i++) {
3735 msg.appendFormat(", %d->%d", fallbackKeys.keyAt(i),
3736 fallbackKeys.valueAt(i));
3737 }
3738 LOGD("Unhandled key event: %d currently tracked fallback keys%s.",
3739 fallbackKeys.size(), msg.string());
3740 }
3741#endif
3742
3743 if (fallback) {
3744 // Restart the dispatch cycle using the fallback key.
3745 keyEntry->eventTime = event.getEventTime();
3746 keyEntry->deviceId = event.getDeviceId();
3747 keyEntry->source = event.getSource();
3748 keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
3749 keyEntry->keyCode = fallbackKeyCode;
3750 keyEntry->scanCode = event.getScanCode();
3751 keyEntry->metaState = event.getMetaState();
3752 keyEntry->repeatCount = event.getRepeatCount();
3753 keyEntry->downTime = event.getDownTime();
3754 keyEntry->syntheticRepeat = false;
3755
3756#if DEBUG_OUTBOUND_EVENT_DETAILS
3757 LOGD("Unhandled key event: Dispatching fallback key. "
3758 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
3759 originalKeyCode, fallbackKeyCode, keyEntry->metaState);
3760#endif
3761
3762 dispatchEntry->inProgress = false;
3763 startDispatchCycleLocked(now(), connection);
3764 return true; // already started next cycle
3765 } else {
3766#if DEBUG_OUTBOUND_EVENT_DETAILS
3767 LOGD("Unhandled key event: No fallback key.");
3768#endif
3769 }
3770 }
3771 }
3772 return false;
3773}
3774
3775bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
3776 DispatchEntry* dispatchEntry, MotionEntry* motionEntry, bool handled) {
3777 return false;
Jeff Brown3915bb82010-11-05 15:02:16 -07003778}
3779
Jeff Brownb88102f2010-09-08 11:49:43 -07003780void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
3781 mLock.unlock();
3782
Jeff Brown01ce2e92010-09-26 22:20:12 -07003783 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
Jeff Brownb88102f2010-09-08 11:49:43 -07003784
3785 mLock.lock();
3786}
3787
Jeff Brown3915bb82010-11-05 15:02:16 -07003788void InputDispatcher::initializeKeyEvent(KeyEvent* event, const KeyEntry* entry) {
3789 event->initialize(entry->deviceId, entry->source, entry->action, entry->flags,
3790 entry->keyCode, entry->scanCode, entry->metaState, entry->repeatCount,
3791 entry->downTime, entry->eventTime);
3792}
3793
Jeff Brown519e0242010-09-15 15:18:56 -07003794void InputDispatcher::updateDispatchStatisticsLocked(nsecs_t currentTime, const EventEntry* entry,
3795 int32_t injectionResult, nsecs_t timeSpentWaitingForApplication) {
3796 // TODO Write some statistics about how long we spend waiting.
Jeff Brownb88102f2010-09-08 11:49:43 -07003797}
3798
3799void InputDispatcher::dump(String8& dump) {
Jeff Brownf2f487182010-10-01 17:46:21 -07003800 dump.append("Input Dispatcher State:\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003801 dumpDispatchStateLocked(dump);
Jeff Brown214eaf42011-05-26 19:17:02 -07003802
3803 dump.append(INDENT "Configuration:\n");
3804 dump.appendFormat(INDENT2 "MaxEventsPerSecond: %d\n", mConfig.maxEventsPerSecond);
3805 dump.appendFormat(INDENT2 "KeyRepeatDelay: %0.1fms\n", mConfig.keyRepeatDelay * 0.000001f);
3806 dump.appendFormat(INDENT2 "KeyRepeatTimeout: %0.1fms\n", mConfig.keyRepeatTimeout * 0.000001f);
Jeff Brownb88102f2010-09-08 11:49:43 -07003807}
3808
Jeff Brown9c3cda02010-06-15 01:31:58 -07003809
Jeff Brown519e0242010-09-15 15:18:56 -07003810// --- InputDispatcher::Queue ---
3811
3812template <typename T>
3813uint32_t InputDispatcher::Queue<T>::count() const {
3814 uint32_t result = 0;
3815 for (const T* entry = headSentinel.next; entry != & tailSentinel; entry = entry->next) {
3816 result += 1;
3817 }
3818 return result;
3819}
3820
3821
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003822// --- InputDispatcher::Allocator ---
3823
3824InputDispatcher::Allocator::Allocator() {
3825}
3826
Jeff Brown01ce2e92010-09-26 22:20:12 -07003827InputDispatcher::InjectionState*
3828InputDispatcher::Allocator::obtainInjectionState(int32_t injectorPid, int32_t injectorUid) {
3829 InjectionState* injectionState = mInjectionStatePool.alloc();
3830 injectionState->refCount = 1;
3831 injectionState->injectorPid = injectorPid;
3832 injectionState->injectorUid = injectorUid;
3833 injectionState->injectionIsAsync = false;
3834 injectionState->injectionResult = INPUT_EVENT_INJECTION_PENDING;
3835 injectionState->pendingForegroundDispatches = 0;
3836 return injectionState;
3837}
3838
Jeff Brown7fbdc842010-06-17 20:52:56 -07003839void InputDispatcher::Allocator::initializeEventEntry(EventEntry* entry, int32_t type,
Jeff Brownb6997262010-10-08 22:31:17 -07003840 nsecs_t eventTime, uint32_t policyFlags) {
Jeff Brown7fbdc842010-06-17 20:52:56 -07003841 entry->type = type;
3842 entry->refCount = 1;
3843 entry->dispatchInProgress = false;
Christopher Tatee91a5db2010-06-23 16:50:30 -07003844 entry->eventTime = eventTime;
Jeff Brownb6997262010-10-08 22:31:17 -07003845 entry->policyFlags = policyFlags;
Jeff Brown01ce2e92010-09-26 22:20:12 -07003846 entry->injectionState = NULL;
3847}
3848
3849void InputDispatcher::Allocator::releaseEventEntryInjectionState(EventEntry* entry) {
3850 if (entry->injectionState) {
3851 releaseInjectionState(entry->injectionState);
3852 entry->injectionState = NULL;
3853 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07003854}
3855
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003856InputDispatcher::ConfigurationChangedEntry*
Jeff Brown7fbdc842010-06-17 20:52:56 -07003857InputDispatcher::Allocator::obtainConfigurationChangedEntry(nsecs_t eventTime) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003858 ConfigurationChangedEntry* entry = mConfigurationChangeEntryPool.alloc();
Jeff Brownb6997262010-10-08 22:31:17 -07003859 initializeEventEntry(entry, EventEntry::TYPE_CONFIGURATION_CHANGED, eventTime, 0);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003860 return entry;
3861}
3862
Jeff Brown7fbdc842010-06-17 20:52:56 -07003863InputDispatcher::KeyEntry* InputDispatcher::Allocator::obtainKeyEntry(nsecs_t eventTime,
Jeff Brown58a2da82011-01-25 16:02:22 -08003864 int32_t deviceId, uint32_t source, uint32_t policyFlags, int32_t action,
Jeff Brown7fbdc842010-06-17 20:52:56 -07003865 int32_t flags, int32_t keyCode, int32_t scanCode, int32_t metaState,
3866 int32_t repeatCount, nsecs_t downTime) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003867 KeyEntry* entry = mKeyEntryPool.alloc();
Jeff Brownb6997262010-10-08 22:31:17 -07003868 initializeEventEntry(entry, EventEntry::TYPE_KEY, eventTime, policyFlags);
Jeff Brown7fbdc842010-06-17 20:52:56 -07003869
3870 entry->deviceId = deviceId;
Jeff Brownc5ed5912010-07-14 18:48:53 -07003871 entry->source = source;
Jeff Brown7fbdc842010-06-17 20:52:56 -07003872 entry->action = action;
3873 entry->flags = flags;
3874 entry->keyCode = keyCode;
3875 entry->scanCode = scanCode;
3876 entry->metaState = metaState;
3877 entry->repeatCount = repeatCount;
3878 entry->downTime = downTime;
Jeff Brownb88102f2010-09-08 11:49:43 -07003879 entry->syntheticRepeat = false;
3880 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003881 return entry;
3882}
3883
Jeff Brown7fbdc842010-06-17 20:52:56 -07003884InputDispatcher::MotionEntry* InputDispatcher::Allocator::obtainMotionEntry(nsecs_t eventTime,
Jeff Brown58a2da82011-01-25 16:02:22 -08003885 int32_t deviceId, uint32_t source, uint32_t policyFlags, int32_t action, int32_t flags,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003886 int32_t metaState, int32_t buttonState,
3887 int32_t edgeFlags, float xPrecision, float yPrecision,
Jeff Brown7fbdc842010-06-17 20:52:56 -07003888 nsecs_t downTime, uint32_t pointerCount,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003889 const PointerProperties* pointerProperties, const PointerCoords* pointerCoords) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003890 MotionEntry* entry = mMotionEntryPool.alloc();
Jeff Brownb6997262010-10-08 22:31:17 -07003891 initializeEventEntry(entry, EventEntry::TYPE_MOTION, eventTime, policyFlags);
Jeff Brown7fbdc842010-06-17 20:52:56 -07003892
3893 entry->eventTime = eventTime;
3894 entry->deviceId = deviceId;
Jeff Brownc5ed5912010-07-14 18:48:53 -07003895 entry->source = source;
Jeff Brown7fbdc842010-06-17 20:52:56 -07003896 entry->action = action;
Jeff Brown85a31762010-09-01 17:01:00 -07003897 entry->flags = flags;
Jeff Brown7fbdc842010-06-17 20:52:56 -07003898 entry->metaState = metaState;
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003899 entry->buttonState = buttonState;
Jeff Brown7fbdc842010-06-17 20:52:56 -07003900 entry->edgeFlags = edgeFlags;
3901 entry->xPrecision = xPrecision;
3902 entry->yPrecision = yPrecision;
3903 entry->downTime = downTime;
3904 entry->pointerCount = pointerCount;
3905 entry->firstSample.eventTime = eventTime;
Jeff Brown4e91a182011-04-07 11:38:09 -07003906 entry->firstSample.eventTimeBeforeCoalescing = eventTime;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003907 entry->firstSample.next = NULL;
Jeff Brown7fbdc842010-06-17 20:52:56 -07003908 entry->lastSample = & entry->firstSample;
3909 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003910 entry->pointerProperties[i].copyFrom(pointerProperties[i]);
Jeff Brownace13b12011-03-09 17:39:48 -08003911 entry->firstSample.pointerCoords[i].copyFrom(pointerCoords[i]);
Jeff Brown7fbdc842010-06-17 20:52:56 -07003912 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003913 return entry;
3914}
3915
3916InputDispatcher::DispatchEntry* InputDispatcher::Allocator::obtainDispatchEntry(
Jeff Brownb88102f2010-09-08 11:49:43 -07003917 EventEntry* eventEntry,
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003918 int32_t targetFlags, float xOffset, float yOffset, float scaleFactor) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003919 DispatchEntry* entry = mDispatchEntryPool.alloc();
3920 entry->eventEntry = eventEntry;
3921 eventEntry->refCount += 1;
Jeff Brownb88102f2010-09-08 11:49:43 -07003922 entry->targetFlags = targetFlags;
3923 entry->xOffset = xOffset;
3924 entry->yOffset = yOffset;
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003925 entry->scaleFactor = scaleFactor;
Jeff Brownb88102f2010-09-08 11:49:43 -07003926 entry->inProgress = false;
3927 entry->headMotionSample = NULL;
3928 entry->tailMotionSample = NULL;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003929 return entry;
3930}
3931
Jeff Brown9c3cda02010-06-15 01:31:58 -07003932InputDispatcher::CommandEntry* InputDispatcher::Allocator::obtainCommandEntry(Command command) {
3933 CommandEntry* entry = mCommandEntryPool.alloc();
3934 entry->command = command;
3935 return entry;
3936}
3937
Jeff Brown01ce2e92010-09-26 22:20:12 -07003938void InputDispatcher::Allocator::releaseInjectionState(InjectionState* injectionState) {
3939 injectionState->refCount -= 1;
3940 if (injectionState->refCount == 0) {
3941 mInjectionStatePool.free(injectionState);
3942 } else {
Jeff Brownb6110c22011-04-01 16:15:13 -07003943 LOG_ASSERT(injectionState->refCount > 0);
Jeff Brown01ce2e92010-09-26 22:20:12 -07003944 }
3945}
3946
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003947void InputDispatcher::Allocator::releaseEventEntry(EventEntry* entry) {
3948 switch (entry->type) {
3949 case EventEntry::TYPE_CONFIGURATION_CHANGED:
3950 releaseConfigurationChangedEntry(static_cast<ConfigurationChangedEntry*>(entry));
3951 break;
3952 case EventEntry::TYPE_KEY:
3953 releaseKeyEntry(static_cast<KeyEntry*>(entry));
3954 break;
3955 case EventEntry::TYPE_MOTION:
3956 releaseMotionEntry(static_cast<MotionEntry*>(entry));
3957 break;
3958 default:
Jeff Brownb6110c22011-04-01 16:15:13 -07003959 LOG_ASSERT(false);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003960 break;
3961 }
3962}
3963
3964void InputDispatcher::Allocator::releaseConfigurationChangedEntry(
3965 ConfigurationChangedEntry* entry) {
3966 entry->refCount -= 1;
3967 if (entry->refCount == 0) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07003968 releaseEventEntryInjectionState(entry);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003969 mConfigurationChangeEntryPool.free(entry);
3970 } else {
Jeff Brownb6110c22011-04-01 16:15:13 -07003971 LOG_ASSERT(entry->refCount > 0);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003972 }
3973}
3974
3975void InputDispatcher::Allocator::releaseKeyEntry(KeyEntry* entry) {
3976 entry->refCount -= 1;
3977 if (entry->refCount == 0) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07003978 releaseEventEntryInjectionState(entry);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003979 mKeyEntryPool.free(entry);
3980 } else {
Jeff Brownb6110c22011-04-01 16:15:13 -07003981 LOG_ASSERT(entry->refCount > 0);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003982 }
3983}
3984
3985void InputDispatcher::Allocator::releaseMotionEntry(MotionEntry* entry) {
3986 entry->refCount -= 1;
3987 if (entry->refCount == 0) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07003988 releaseEventEntryInjectionState(entry);
Jeff Brown9c3cda02010-06-15 01:31:58 -07003989 for (MotionSample* sample = entry->firstSample.next; sample != NULL; ) {
3990 MotionSample* next = sample->next;
3991 mMotionSamplePool.free(sample);
3992 sample = next;
3993 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003994 mMotionEntryPool.free(entry);
3995 } else {
Jeff Brownb6110c22011-04-01 16:15:13 -07003996 LOG_ASSERT(entry->refCount > 0);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003997 }
3998}
3999
Jeff Browna032cc02011-03-07 16:56:21 -08004000void InputDispatcher::Allocator::freeMotionSample(MotionSample* sample) {
4001 mMotionSamplePool.free(sample);
4002}
4003
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004004void InputDispatcher::Allocator::releaseDispatchEntry(DispatchEntry* entry) {
4005 releaseEventEntry(entry->eventEntry);
4006 mDispatchEntryPool.free(entry);
4007}
4008
Jeff Brown9c3cda02010-06-15 01:31:58 -07004009void InputDispatcher::Allocator::releaseCommandEntry(CommandEntry* entry) {
4010 mCommandEntryPool.free(entry);
4011}
4012
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004013void InputDispatcher::Allocator::appendMotionSample(MotionEntry* motionEntry,
Jeff Brown7fbdc842010-06-17 20:52:56 -07004014 nsecs_t eventTime, const PointerCoords* pointerCoords) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004015 MotionSample* sample = mMotionSamplePool.alloc();
4016 sample->eventTime = eventTime;
Jeff Brown4e91a182011-04-07 11:38:09 -07004017 sample->eventTimeBeforeCoalescing = eventTime;
Jeff Brown7fbdc842010-06-17 20:52:56 -07004018 uint32_t pointerCount = motionEntry->pointerCount;
4019 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brownace13b12011-03-09 17:39:48 -08004020 sample->pointerCoords[i].copyFrom(pointerCoords[i]);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004021 }
4022
4023 sample->next = NULL;
4024 motionEntry->lastSample->next = sample;
4025 motionEntry->lastSample = sample;
4026}
4027
Jeff Brown01ce2e92010-09-26 22:20:12 -07004028void InputDispatcher::Allocator::recycleKeyEntry(KeyEntry* keyEntry) {
4029 releaseEventEntryInjectionState(keyEntry);
Jeff Brownb88102f2010-09-08 11:49:43 -07004030
Jeff Brown01ce2e92010-09-26 22:20:12 -07004031 keyEntry->dispatchInProgress = false;
4032 keyEntry->syntheticRepeat = false;
4033 keyEntry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
Jeff Brownb88102f2010-09-08 11:49:43 -07004034}
4035
4036
Jeff Brownae9fc032010-08-18 15:51:08 -07004037// --- InputDispatcher::MotionEntry ---
4038
4039uint32_t InputDispatcher::MotionEntry::countSamples() const {
4040 uint32_t count = 1;
4041 for (MotionSample* sample = firstSample.next; sample != NULL; sample = sample->next) {
4042 count += 1;
4043 }
4044 return count;
4045}
4046
Jeff Brown4e91a182011-04-07 11:38:09 -07004047bool InputDispatcher::MotionEntry::canAppendSamples(int32_t action, uint32_t pointerCount,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07004048 const PointerProperties* pointerProperties) const {
Jeff Brown4e91a182011-04-07 11:38:09 -07004049 if (this->action != action
4050 || this->pointerCount != pointerCount
4051 || this->isInjected()) {
4052 return false;
4053 }
4054 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07004055 if (this->pointerProperties[i] != pointerProperties[i]) {
Jeff Brown4e91a182011-04-07 11:38:09 -07004056 return false;
4057 }
4058 }
4059 return true;
4060}
4061
Jeff Brownb88102f2010-09-08 11:49:43 -07004062
4063// --- InputDispatcher::InputState ---
4064
Jeff Brownb6997262010-10-08 22:31:17 -07004065InputDispatcher::InputState::InputState() {
Jeff Brownb88102f2010-09-08 11:49:43 -07004066}
4067
4068InputDispatcher::InputState::~InputState() {
4069}
4070
4071bool InputDispatcher::InputState::isNeutral() const {
4072 return mKeyMementos.isEmpty() && mMotionMementos.isEmpty();
4073}
4074
Jeff Browna032cc02011-03-07 16:56:21 -08004075void InputDispatcher::InputState::trackEvent(const EventEntry* entry, int32_t action) {
Jeff Brownb88102f2010-09-08 11:49:43 -07004076 switch (entry->type) {
4077 case EventEntry::TYPE_KEY:
Jeff Browna032cc02011-03-07 16:56:21 -08004078 trackKey(static_cast<const KeyEntry*>(entry), action);
Jeff Browncc0c1592011-02-19 05:07:28 -08004079 break;
Jeff Brownb88102f2010-09-08 11:49:43 -07004080
4081 case EventEntry::TYPE_MOTION:
Jeff Browna032cc02011-03-07 16:56:21 -08004082 trackMotion(static_cast<const MotionEntry*>(entry), action);
Jeff Browncc0c1592011-02-19 05:07:28 -08004083 break;
Jeff Brownb88102f2010-09-08 11:49:43 -07004084 }
4085}
4086
Jeff Browna032cc02011-03-07 16:56:21 -08004087void InputDispatcher::InputState::trackKey(const KeyEntry* entry, int32_t action) {
Jeff Brownda3d5a92011-03-29 15:11:34 -07004088 if (action == AKEY_EVENT_ACTION_UP
4089 && (entry->flags & AKEY_EVENT_FLAG_FALLBACK)) {
4090 for (size_t i = 0; i < mFallbackKeys.size(); ) {
4091 if (mFallbackKeys.valueAt(i) == entry->keyCode) {
4092 mFallbackKeys.removeItemsAt(i);
4093 } else {
4094 i += 1;
4095 }
4096 }
4097 }
4098
Jeff Brownb88102f2010-09-08 11:49:43 -07004099 for (size_t i = 0; i < mKeyMementos.size(); i++) {
4100 KeyMemento& memento = mKeyMementos.editItemAt(i);
4101 if (memento.deviceId == entry->deviceId
4102 && memento.source == entry->source
4103 && memento.keyCode == entry->keyCode
4104 && memento.scanCode == entry->scanCode) {
4105 switch (action) {
4106 case AKEY_EVENT_ACTION_UP:
4107 mKeyMementos.removeAt(i);
Jeff Browncc0c1592011-02-19 05:07:28 -08004108 return;
Jeff Brownb88102f2010-09-08 11:49:43 -07004109
4110 case AKEY_EVENT_ACTION_DOWN:
Jeff Browncc0c1592011-02-19 05:07:28 -08004111 mKeyMementos.removeAt(i);
4112 goto Found;
Jeff Brownb88102f2010-09-08 11:49:43 -07004113
4114 default:
Jeff Browncc0c1592011-02-19 05:07:28 -08004115 return;
Jeff Brownb88102f2010-09-08 11:49:43 -07004116 }
4117 }
4118 }
4119
Jeff Browncc0c1592011-02-19 05:07:28 -08004120Found:
4121 if (action == AKEY_EVENT_ACTION_DOWN) {
Jeff Brownb88102f2010-09-08 11:49:43 -07004122 mKeyMementos.push();
4123 KeyMemento& memento = mKeyMementos.editTop();
4124 memento.deviceId = entry->deviceId;
4125 memento.source = entry->source;
4126 memento.keyCode = entry->keyCode;
4127 memento.scanCode = entry->scanCode;
Jeff Brown49ed71d2010-12-06 17:13:33 -08004128 memento.flags = entry->flags;
Jeff Brownb88102f2010-09-08 11:49:43 -07004129 memento.downTime = entry->downTime;
Jeff Brownb88102f2010-09-08 11:49:43 -07004130 }
4131}
4132
Jeff Browna032cc02011-03-07 16:56:21 -08004133void InputDispatcher::InputState::trackMotion(const MotionEntry* entry, int32_t action) {
4134 int32_t actionMasked = action & AMOTION_EVENT_ACTION_MASK;
Jeff Brownb88102f2010-09-08 11:49:43 -07004135 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4136 MotionMemento& memento = mMotionMementos.editItemAt(i);
4137 if (memento.deviceId == entry->deviceId
4138 && memento.source == entry->source) {
Jeff Browna032cc02011-03-07 16:56:21 -08004139 switch (actionMasked) {
Jeff Brownb88102f2010-09-08 11:49:43 -07004140 case AMOTION_EVENT_ACTION_UP:
4141 case AMOTION_EVENT_ACTION_CANCEL:
Jeff Browna032cc02011-03-07 16:56:21 -08004142 case AMOTION_EVENT_ACTION_HOVER_ENTER:
Jeff Browncc0c1592011-02-19 05:07:28 -08004143 case AMOTION_EVENT_ACTION_HOVER_MOVE:
Jeff Browna032cc02011-03-07 16:56:21 -08004144 case AMOTION_EVENT_ACTION_HOVER_EXIT:
Jeff Brownb88102f2010-09-08 11:49:43 -07004145 mMotionMementos.removeAt(i);
Jeff Browncc0c1592011-02-19 05:07:28 -08004146 return;
Jeff Brownb88102f2010-09-08 11:49:43 -07004147
4148 case AMOTION_EVENT_ACTION_DOWN:
Jeff Browncc0c1592011-02-19 05:07:28 -08004149 mMotionMementos.removeAt(i);
4150 goto Found;
Jeff Brownb88102f2010-09-08 11:49:43 -07004151
4152 case AMOTION_EVENT_ACTION_POINTER_UP:
Jeff Browncc0c1592011-02-19 05:07:28 -08004153 case AMOTION_EVENT_ACTION_POINTER_DOWN:
Jeff Brownb88102f2010-09-08 11:49:43 -07004154 case AMOTION_EVENT_ACTION_MOVE:
Jeff Browncc0c1592011-02-19 05:07:28 -08004155 memento.setPointers(entry);
4156 return;
Jeff Brownb88102f2010-09-08 11:49:43 -07004157
4158 default:
Jeff Browncc0c1592011-02-19 05:07:28 -08004159 return;
Jeff Brownb88102f2010-09-08 11:49:43 -07004160 }
4161 }
4162 }
4163
Jeff Browncc0c1592011-02-19 05:07:28 -08004164Found:
Jeff Browna032cc02011-03-07 16:56:21 -08004165 switch (actionMasked) {
4166 case AMOTION_EVENT_ACTION_DOWN:
4167 case AMOTION_EVENT_ACTION_HOVER_ENTER:
4168 case AMOTION_EVENT_ACTION_HOVER_MOVE:
4169 case AMOTION_EVENT_ACTION_HOVER_EXIT:
Jeff Brownb88102f2010-09-08 11:49:43 -07004170 mMotionMementos.push();
4171 MotionMemento& memento = mMotionMementos.editTop();
4172 memento.deviceId = entry->deviceId;
4173 memento.source = entry->source;
4174 memento.xPrecision = entry->xPrecision;
4175 memento.yPrecision = entry->yPrecision;
4176 memento.downTime = entry->downTime;
4177 memento.setPointers(entry);
Jeff Browna032cc02011-03-07 16:56:21 -08004178 memento.hovering = actionMasked != AMOTION_EVENT_ACTION_DOWN;
Jeff Brownb88102f2010-09-08 11:49:43 -07004179 }
4180}
4181
4182void InputDispatcher::InputState::MotionMemento::setPointers(const MotionEntry* entry) {
4183 pointerCount = entry->pointerCount;
4184 for (uint32_t i = 0; i < entry->pointerCount; i++) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07004185 pointerProperties[i].copyFrom(entry->pointerProperties[i]);
Jeff Brownace13b12011-03-09 17:39:48 -08004186 pointerCoords[i].copyFrom(entry->lastSample->pointerCoords[i]);
Jeff Brownb88102f2010-09-08 11:49:43 -07004187 }
4188}
4189
Jeff Brownb6997262010-10-08 22:31:17 -07004190void InputDispatcher::InputState::synthesizeCancelationEvents(nsecs_t currentTime,
4191 Allocator* allocator, Vector<EventEntry*>& outEvents,
Jeff Brownda3d5a92011-03-29 15:11:34 -07004192 const CancelationOptions& options) {
Jeff Brownb6997262010-10-08 22:31:17 -07004193 for (size_t i = 0; i < mKeyMementos.size(); ) {
Jeff Brownb88102f2010-09-08 11:49:43 -07004194 const KeyMemento& memento = mKeyMementos.itemAt(i);
Jeff Brown49ed71d2010-12-06 17:13:33 -08004195 if (shouldCancelKey(memento, options)) {
Jeff Brownb6997262010-10-08 22:31:17 -07004196 outEvents.push(allocator->obtainKeyEntry(currentTime,
4197 memento.deviceId, memento.source, 0,
Jeff Brown49ed71d2010-12-06 17:13:33 -08004198 AKEY_EVENT_ACTION_UP, memento.flags | AKEY_EVENT_FLAG_CANCELED,
Jeff Brownb6997262010-10-08 22:31:17 -07004199 memento.keyCode, memento.scanCode, 0, 0, memento.downTime));
4200 mKeyMementos.removeAt(i);
4201 } else {
4202 i += 1;
4203 }
Jeff Brownb88102f2010-09-08 11:49:43 -07004204 }
4205
Jeff Browna1160a72010-10-11 18:22:53 -07004206 for (size_t i = 0; i < mMotionMementos.size(); ) {
Jeff Brownb88102f2010-09-08 11:49:43 -07004207 const MotionMemento& memento = mMotionMementos.itemAt(i);
Jeff Brown49ed71d2010-12-06 17:13:33 -08004208 if (shouldCancelMotion(memento, options)) {
Jeff Brownb6997262010-10-08 22:31:17 -07004209 outEvents.push(allocator->obtainMotionEntry(currentTime,
4210 memento.deviceId, memento.source, 0,
Jeff Browna032cc02011-03-07 16:56:21 -08004211 memento.hovering
4212 ? AMOTION_EVENT_ACTION_HOVER_EXIT
4213 : AMOTION_EVENT_ACTION_CANCEL,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07004214 0, 0, 0, 0,
Jeff Brownb6997262010-10-08 22:31:17 -07004215 memento.xPrecision, memento.yPrecision, memento.downTime,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07004216 memento.pointerCount, memento.pointerProperties, memento.pointerCoords));
Jeff Brownb6997262010-10-08 22:31:17 -07004217 mMotionMementos.removeAt(i);
4218 } else {
4219 i += 1;
4220 }
Jeff Brownb88102f2010-09-08 11:49:43 -07004221 }
4222}
4223
4224void InputDispatcher::InputState::clear() {
4225 mKeyMementos.clear();
4226 mMotionMementos.clear();
Jeff Brownda3d5a92011-03-29 15:11:34 -07004227 mFallbackKeys.clear();
Jeff Brownb6997262010-10-08 22:31:17 -07004228}
4229
Jeff Brown9c9f1a32010-10-11 18:32:20 -07004230void InputDispatcher::InputState::copyPointerStateTo(InputState& other) const {
4231 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4232 const MotionMemento& memento = mMotionMementos.itemAt(i);
4233 if (memento.source & AINPUT_SOURCE_CLASS_POINTER) {
4234 for (size_t j = 0; j < other.mMotionMementos.size(); ) {
4235 const MotionMemento& otherMemento = other.mMotionMementos.itemAt(j);
4236 if (memento.deviceId == otherMemento.deviceId
4237 && memento.source == otherMemento.source) {
4238 other.mMotionMementos.removeAt(j);
4239 } else {
4240 j += 1;
4241 }
4242 }
4243 other.mMotionMementos.push(memento);
4244 }
4245 }
4246}
4247
Jeff Brownda3d5a92011-03-29 15:11:34 -07004248int32_t InputDispatcher::InputState::getFallbackKey(int32_t originalKeyCode) {
4249 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
4250 return index >= 0 ? mFallbackKeys.valueAt(index) : -1;
4251}
4252
4253void InputDispatcher::InputState::setFallbackKey(int32_t originalKeyCode,
4254 int32_t fallbackKeyCode) {
4255 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
4256 if (index >= 0) {
4257 mFallbackKeys.replaceValueAt(index, fallbackKeyCode);
4258 } else {
4259 mFallbackKeys.add(originalKeyCode, fallbackKeyCode);
4260 }
4261}
4262
4263void InputDispatcher::InputState::removeFallbackKey(int32_t originalKeyCode) {
4264 mFallbackKeys.removeItem(originalKeyCode);
4265}
4266
Jeff Brown49ed71d2010-12-06 17:13:33 -08004267bool InputDispatcher::InputState::shouldCancelKey(const KeyMemento& memento,
Jeff Brownda3d5a92011-03-29 15:11:34 -07004268 const CancelationOptions& options) {
4269 if (options.keyCode != -1 && memento.keyCode != options.keyCode) {
4270 return false;
4271 }
4272
4273 switch (options.mode) {
4274 case CancelationOptions::CANCEL_ALL_EVENTS:
4275 case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
Jeff Brownb6997262010-10-08 22:31:17 -07004276 return true;
Jeff Brownda3d5a92011-03-29 15:11:34 -07004277 case CancelationOptions::CANCEL_FALLBACK_EVENTS:
Jeff Brown49ed71d2010-12-06 17:13:33 -08004278 return memento.flags & AKEY_EVENT_FLAG_FALLBACK;
4279 default:
4280 return false;
4281 }
4282}
4283
4284bool InputDispatcher::InputState::shouldCancelMotion(const MotionMemento& memento,
Jeff Brownda3d5a92011-03-29 15:11:34 -07004285 const CancelationOptions& options) {
4286 switch (options.mode) {
4287 case CancelationOptions::CANCEL_ALL_EVENTS:
Jeff Brown49ed71d2010-12-06 17:13:33 -08004288 return true;
Jeff Brownda3d5a92011-03-29 15:11:34 -07004289 case CancelationOptions::CANCEL_POINTER_EVENTS:
Jeff Brown49ed71d2010-12-06 17:13:33 -08004290 return memento.source & AINPUT_SOURCE_CLASS_POINTER;
Jeff Brownda3d5a92011-03-29 15:11:34 -07004291 case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
Jeff Brown49ed71d2010-12-06 17:13:33 -08004292 return !(memento.source & AINPUT_SOURCE_CLASS_POINTER);
4293 default:
4294 return false;
Jeff Brownb6997262010-10-08 22:31:17 -07004295 }
Jeff Brownb88102f2010-09-08 11:49:43 -07004296}
4297
4298
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004299// --- InputDispatcher::Connection ---
4300
Jeff Brown928e0542011-01-10 11:17:36 -08004301InputDispatcher::Connection::Connection(const sp<InputChannel>& inputChannel,
4302 const sp<InputWindowHandle>& inputWindowHandle) :
4303 status(STATUS_NORMAL), inputChannel(inputChannel), inputWindowHandle(inputWindowHandle),
4304 inputPublisher(inputChannel),
Jeff Brownda3d5a92011-03-29 15:11:34 -07004305 lastEventTime(LONG_LONG_MAX), lastDispatchTime(LONG_LONG_MAX) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004306}
4307
4308InputDispatcher::Connection::~Connection() {
4309}
4310
4311status_t InputDispatcher::Connection::initialize() {
4312 return inputPublisher.initialize();
4313}
4314
Jeff Brown9c3cda02010-06-15 01:31:58 -07004315const char* InputDispatcher::Connection::getStatusLabel() const {
4316 switch (status) {
4317 case STATUS_NORMAL:
4318 return "NORMAL";
4319
4320 case STATUS_BROKEN:
4321 return "BROKEN";
4322
Jeff Brown9c3cda02010-06-15 01:31:58 -07004323 case STATUS_ZOMBIE:
4324 return "ZOMBIE";
4325
4326 default:
4327 return "UNKNOWN";
4328 }
4329}
4330
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004331InputDispatcher::DispatchEntry* InputDispatcher::Connection::findQueuedDispatchEntryForEvent(
4332 const EventEntry* eventEntry) const {
Jeff Brownb88102f2010-09-08 11:49:43 -07004333 for (DispatchEntry* dispatchEntry = outboundQueue.tailSentinel.prev;
4334 dispatchEntry != & outboundQueue.headSentinel; dispatchEntry = dispatchEntry->prev) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004335 if (dispatchEntry->eventEntry == eventEntry) {
4336 return dispatchEntry;
4337 }
4338 }
4339 return NULL;
4340}
4341
Jeff Brownb88102f2010-09-08 11:49:43 -07004342
Jeff Brown9c3cda02010-06-15 01:31:58 -07004343// --- InputDispatcher::CommandEntry ---
4344
Jeff Brownb88102f2010-09-08 11:49:43 -07004345InputDispatcher::CommandEntry::CommandEntry() :
4346 keyEntry(NULL) {
Jeff Brown9c3cda02010-06-15 01:31:58 -07004347}
4348
4349InputDispatcher::CommandEntry::~CommandEntry() {
4350}
4351
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004352
Jeff Brown01ce2e92010-09-26 22:20:12 -07004353// --- InputDispatcher::TouchState ---
4354
4355InputDispatcher::TouchState::TouchState() :
Jeff Brown58a2da82011-01-25 16:02:22 -08004356 down(false), split(false), deviceId(-1), source(0) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07004357}
4358
4359InputDispatcher::TouchState::~TouchState() {
4360}
4361
4362void InputDispatcher::TouchState::reset() {
4363 down = false;
4364 split = false;
Jeff Brown95712852011-01-04 19:41:59 -08004365 deviceId = -1;
Jeff Brown58a2da82011-01-25 16:02:22 -08004366 source = 0;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004367 windows.clear();
4368}
4369
4370void InputDispatcher::TouchState::copyFrom(const TouchState& other) {
4371 down = other.down;
4372 split = other.split;
Jeff Brown95712852011-01-04 19:41:59 -08004373 deviceId = other.deviceId;
Jeff Brown58a2da82011-01-25 16:02:22 -08004374 source = other.source;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004375 windows.clear();
4376 windows.appendVector(other.windows);
4377}
4378
4379void InputDispatcher::TouchState::addOrUpdateWindow(const InputWindow* window,
4380 int32_t targetFlags, BitSet32 pointerIds) {
4381 if (targetFlags & InputTarget::FLAG_SPLIT) {
4382 split = true;
4383 }
4384
4385 for (size_t i = 0; i < windows.size(); i++) {
4386 TouchedWindow& touchedWindow = windows.editItemAt(i);
4387 if (touchedWindow.window == window) {
4388 touchedWindow.targetFlags |= targetFlags;
4389 touchedWindow.pointerIds.value |= pointerIds.value;
4390 return;
4391 }
4392 }
4393
4394 windows.push();
4395
4396 TouchedWindow& touchedWindow = windows.editTop();
4397 touchedWindow.window = window;
4398 touchedWindow.targetFlags = targetFlags;
4399 touchedWindow.pointerIds = pointerIds;
4400 touchedWindow.channel = window->inputChannel;
4401}
4402
Jeff Browna032cc02011-03-07 16:56:21 -08004403void InputDispatcher::TouchState::filterNonAsIsTouchWindows() {
Jeff Brown01ce2e92010-09-26 22:20:12 -07004404 for (size_t i = 0 ; i < windows.size(); ) {
Jeff Browna032cc02011-03-07 16:56:21 -08004405 TouchedWindow& window = windows.editItemAt(i);
4406 if (window.targetFlags & InputTarget::FLAG_DISPATCH_AS_IS) {
4407 window.targetFlags &= ~InputTarget::FLAG_DISPATCH_MASK;
4408 window.targetFlags |= InputTarget::FLAG_DISPATCH_AS_IS;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004409 i += 1;
Jeff Browna032cc02011-03-07 16:56:21 -08004410 } else {
4411 windows.removeAt(i);
Jeff Brown01ce2e92010-09-26 22:20:12 -07004412 }
4413 }
4414}
4415
4416const InputWindow* InputDispatcher::TouchState::getFirstForegroundWindow() {
4417 for (size_t i = 0; i < windows.size(); i++) {
4418 if (windows[i].targetFlags & InputTarget::FLAG_FOREGROUND) {
4419 return windows[i].window;
4420 }
4421 }
4422 return NULL;
4423}
4424
4425
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004426// --- InputDispatcherThread ---
4427
4428InputDispatcherThread::InputDispatcherThread(const sp<InputDispatcherInterface>& dispatcher) :
4429 Thread(/*canCallJava*/ true), mDispatcher(dispatcher) {
4430}
4431
4432InputDispatcherThread::~InputDispatcherThread() {
4433}
4434
4435bool InputDispatcherThread::threadLoop() {
4436 mDispatcher->dispatchOnce();
4437 return true;
4438}
4439
4440} // namespace android