blob: ad64ccd55f4fbb625c2f188e80b75ffc35e28a10 [file] [log] [blame]
Jeff Brownb4ff35d2011-01-02 16:37:43 -08001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Jeff Brown46b9ac02010-04-22 18:58:52 -070017#define LOG_TAG "InputDispatcher"
18
19//#define LOG_NDEBUG 0
20
21// Log detailed debug messages about each inbound event notification to the dispatcher.
Jeff Brown349703e2010-06-22 01:27:15 -070022#define DEBUG_INBOUND_EVENT_DETAILS 0
Jeff Brown46b9ac02010-04-22 18:58:52 -070023
24// Log detailed debug messages about each outbound event processed by the dispatcher.
Jeff Brown349703e2010-06-22 01:27:15 -070025#define DEBUG_OUTBOUND_EVENT_DETAILS 0
Jeff Brown46b9ac02010-04-22 18:58:52 -070026
27// Log debug messages about batching.
Jeff Brown349703e2010-06-22 01:27:15 -070028#define DEBUG_BATCHING 0
Jeff Brown46b9ac02010-04-22 18:58:52 -070029
30// Log debug messages about the dispatch cycle.
Jeff Brown349703e2010-06-22 01:27:15 -070031#define DEBUG_DISPATCH_CYCLE 0
Jeff Brown46b9ac02010-04-22 18:58:52 -070032
Jeff Brown9c3cda02010-06-15 01:31:58 -070033// Log debug messages about registrations.
Jeff Brown349703e2010-06-22 01:27:15 -070034#define DEBUG_REGISTRATION 0
Jeff Brown9c3cda02010-06-15 01:31:58 -070035
Jeff Brown46b9ac02010-04-22 18:58:52 -070036// Log debug messages about performance statistics.
Jeff Brown349703e2010-06-22 01:27:15 -070037#define DEBUG_PERFORMANCE_STATISTICS 0
Jeff Brown46b9ac02010-04-22 18:58:52 -070038
Jeff Brown7fbdc842010-06-17 20:52:56 -070039// Log debug messages about input event injection.
Jeff Brown349703e2010-06-22 01:27:15 -070040#define DEBUG_INJECTION 0
Jeff Brown7fbdc842010-06-17 20:52:56 -070041
Jeff Brownae9fc032010-08-18 15:51:08 -070042// Log debug messages about input event throttling.
43#define DEBUG_THROTTLING 0
44
Jeff Brownb88102f2010-09-08 11:49:43 -070045// Log debug messages about input focus tracking.
46#define DEBUG_FOCUS 0
47
48// Log debug messages about the app switch latency optimization.
49#define DEBUG_APP_SWITCH 0
50
Jeff Browna032cc02011-03-07 16:56:21 -080051// Log debug messages about hover events.
52#define DEBUG_HOVER 0
53
Jeff Brownb4ff35d2011-01-02 16:37:43 -080054#include "InputDispatcher.h"
55
Jeff Brown46b9ac02010-04-22 18:58:52 -070056#include <cutils/log.h>
Jeff Brownb88102f2010-09-08 11:49:43 -070057#include <ui/PowerManager.h>
Jeff Brown46b9ac02010-04-22 18:58:52 -070058
59#include <stddef.h>
60#include <unistd.h>
Jeff Brown46b9ac02010-04-22 18:58:52 -070061#include <errno.h>
62#include <limits.h>
Jeff Brown46b9ac02010-04-22 18:58:52 -070063
Jeff Brownf2f48712010-10-01 17:46:21 -070064#define INDENT " "
65#define INDENT2 " "
66
Jeff Brown46b9ac02010-04-22 18:58:52 -070067namespace android {
68
Jeff Brownb88102f2010-09-08 11:49:43 -070069// Default input dispatching timeout if there is no focused application or paused window
70// from which to determine an appropriate dispatching timeout.
71const nsecs_t DEFAULT_INPUT_DISPATCHING_TIMEOUT = 5000 * 1000000LL; // 5 sec
72
73// Amount of time to allow for all pending events to be processed when an app switch
74// key is on the way. This is used to preempt input dispatch and drop input events
75// when an application takes too long to respond and the user has pressed an app switch key.
76const nsecs_t APP_SWITCH_TIMEOUT = 500 * 1000000LL; // 0.5sec
77
Jeff Brown928e0542011-01-10 11:17:36 -080078// Amount of time to allow for an event to be dispatched (measured since its eventTime)
79// before considering it stale and dropping it.
80const nsecs_t STALE_EVENT_TIMEOUT = 10000 * 1000000LL; // 10sec
81
Jeff Brown4e91a182011-04-07 11:38:09 -070082// Motion samples that are received within this amount of time are simply coalesced
83// when batched instead of being appended. This is done because some drivers update
84// the location of pointers one at a time instead of all at once.
85// For example, when there are 10 fingers down, the input dispatcher may receive 10
86// samples in quick succession with only one finger's location changed in each sample.
87//
88// This value effectively imposes an upper bound on the touch sampling rate.
89// Touch sensors typically have a 50Hz - 200Hz sampling rate, so we expect distinct
90// samples to become available 5-20ms apart but individual finger reports can trickle
91// in over a period of 2-4ms or so.
92//
93// Empirical testing shows that a 2ms coalescing interval (500Hz) is not enough,
94// a 3ms coalescing interval (333Hz) works well most of the time and doesn't introduce
95// significant quantization noise on current hardware.
96const nsecs_t MOTION_SAMPLE_COALESCE_INTERVAL = 3 * 1000000LL; // 3ms, 333Hz
97
Jeff Brown46b9ac02010-04-22 18:58:52 -070098
Jeff Brown7fbdc842010-06-17 20:52:56 -070099static inline nsecs_t now() {
100 return systemTime(SYSTEM_TIME_MONOTONIC);
101}
102
Jeff Brownb88102f2010-09-08 11:49:43 -0700103static inline const char* toString(bool value) {
104 return value ? "true" : "false";
105}
106
Jeff Brown01ce2e92010-09-26 22:20:12 -0700107static inline int32_t getMotionEventActionPointerIndex(int32_t action) {
108 return (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK)
109 >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
110}
111
112static bool isValidKeyAction(int32_t action) {
113 switch (action) {
114 case AKEY_EVENT_ACTION_DOWN:
115 case AKEY_EVENT_ACTION_UP:
116 return true;
117 default:
118 return false;
119 }
120}
121
122static bool validateKeyEvent(int32_t action) {
123 if (! isValidKeyAction(action)) {
Steve Block3762c312012-01-06 19:20:56 +0000124 ALOGE("Key event has invalid action code 0x%x", action);
Jeff Brown01ce2e92010-09-26 22:20:12 -0700125 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)) {
Steve Block3762c312012-01-06 19:20:56 +0000155 ALOGE("Motion event has invalid action code 0x%x", action);
Jeff Brown01ce2e92010-09-26 22:20:12 -0700156 return false;
157 }
158 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Steve Block3762c312012-01-06 19:20:56 +0000159 ALOGE("Motion event has invalid pointer count %d; value must be between 1 and %d.",
Jeff Brown01ce2e92010-09-26 22:20:12 -0700160 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) {
Steve Block3762c312012-01-06 19:20:56 +0000167 ALOGE("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)) {
Steve Block3762c312012-01-06 19:20:56 +0000172 ALOGE("Motion event has duplicate pointer id %d", id);
Jeff Brownc3db8582010-10-20 15:33:38 -0700173 return false;
174 }
175 pointerIdBits.markBit(id);
Jeff Brown01ce2e92010-09-26 22:20:12 -0700176 }
177 return true;
178}
179
Jeff Brownfbf09772011-01-16 14:06:57 -0800180static void dumpRegion(String8& dump, const SkRegion& region) {
181 if (region.isEmpty()) {
182 dump.append("<empty>");
183 return;
184 }
185
186 bool first = true;
187 for (SkRegion::Iterator it(region); !it.done(); it.next()) {
188 if (first) {
189 first = false;
190 } else {
191 dump.append("|");
192 }
193 const SkIRect& rect = it.rect();
194 dump.appendFormat("[%d,%d][%d,%d]", rect.fLeft, rect.fTop, rect.fRight, rect.fBottom);
195 }
196}
197
Jeff Brownb88102f2010-09-08 11:49:43 -0700198
Jeff Brown46b9ac02010-04-22 18:58:52 -0700199// --- InputDispatcher ---
200
Jeff Brown9c3cda02010-06-15 01:31:58 -0700201InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy) :
Jeff Brownb88102f2010-09-08 11:49:43 -0700202 mPolicy(policy),
Jeff Brown928e0542011-01-10 11:17:36 -0800203 mPendingEvent(NULL), mAppSwitchSawKeyDown(false), mAppSwitchDueTime(LONG_LONG_MAX),
204 mNextUnblockedEvent(NULL),
Jeff Brown0029c662011-03-30 02:25:18 -0700205 mDispatchEnabled(true), mDispatchFrozen(false), mInputFilterEnabled(false),
Jeff Brownb88102f2010-09-08 11:49:43 -0700206 mCurrentInputTargetsValid(false),
Jeff Brown9302c872011-07-13 22:51:29 -0700207 mInputTargetWaitCause(INPUT_TARGET_WAIT_CAUSE_NONE) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -0700208 mLooper = new Looper(false);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700209
Jeff Brown46b9ac02010-04-22 18:58:52 -0700210 mKeyRepeatState.lastKeyEntry = NULL;
Jeff Brown9c3cda02010-06-15 01:31:58 -0700211
Jeff Brown214eaf42011-05-26 19:17:02 -0700212 policy->getDispatcherConfiguration(&mConfig);
213
214 mThrottleState.minTimeBetweenEvents = 1000000000LL / mConfig.maxEventsPerSecond;
Jeff Brownae9fc032010-08-18 15:51:08 -0700215 mThrottleState.lastDeviceId = -1;
216
217#if DEBUG_THROTTLING
218 mThrottleState.originalSampleCount = 0;
Steve Block5baa3a62011-12-20 16:23:08 +0000219 ALOGD("Throttling - Max events per second = %d", mConfig.maxEventsPerSecond);
Jeff Brownae9fc032010-08-18 15:51:08 -0700220#endif
Jeff Brown46b9ac02010-04-22 18:58:52 -0700221}
222
223InputDispatcher::~InputDispatcher() {
Jeff Brownb88102f2010-09-08 11:49:43 -0700224 { // acquire lock
225 AutoMutex _l(mLock);
226
227 resetKeyRepeatLocked();
Jeff Brown54a18252010-09-16 14:07:33 -0700228 releasePendingEventLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -0700229 drainInboundQueueLocked();
230 }
Jeff Brown46b9ac02010-04-22 18:58:52 -0700231
232 while (mConnectionsByReceiveFd.size() != 0) {
233 unregisterInputChannel(mConnectionsByReceiveFd.valueAt(0)->inputChannel);
234 }
Jeff Brown46b9ac02010-04-22 18:58:52 -0700235}
236
237void InputDispatcher::dispatchOnce() {
Jeff Brown46b9ac02010-04-22 18:58:52 -0700238 nsecs_t nextWakeupTime = LONG_LONG_MAX;
239 { // acquire lock
240 AutoMutex _l(mLock);
Jeff Brown112b5f52012-01-27 17:32:06 -0800241 mDispatcherIsAliveCondition.broadcast();
242
Jeff Brown214eaf42011-05-26 19:17:02 -0700243 dispatchOnceInnerLocked(&nextWakeupTime);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700244
Jeff Brownb88102f2010-09-08 11:49:43 -0700245 if (runCommandsLockedInterruptible()) {
246 nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
Jeff Brown46b9ac02010-04-22 18:58:52 -0700247 }
Jeff Brown46b9ac02010-04-22 18:58:52 -0700248 } // release lock
249
Jeff Brownb88102f2010-09-08 11:49:43 -0700250 // Wait for callback or timeout or wake. (make sure we round up, not down)
251 nsecs_t currentTime = now();
Jeff Brownaa3855d2011-03-17 01:34:19 -0700252 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
Jeff Brown4fe6c3e2010-09-13 23:17:30 -0700253 mLooper->pollOnce(timeoutMillis);
Jeff Brownb88102f2010-09-08 11:49:43 -0700254}
255
Jeff Brown214eaf42011-05-26 19:17:02 -0700256void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700257 nsecs_t currentTime = now();
258
259 // Reset the key repeat timer whenever we disallow key events, even if the next event
260 // is not a key. This is to ensure that we abort a key repeat if the device is just coming
261 // out of sleep.
Jeff Brown214eaf42011-05-26 19:17:02 -0700262 if (!mPolicy->isKeyRepeatEnabled()) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700263 resetKeyRepeatLocked();
264 }
265
Jeff Brownb88102f2010-09-08 11:49:43 -0700266 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
267 if (mDispatchFrozen) {
268#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +0000269 ALOGD("Dispatch frozen. Waiting some more.");
Jeff Brownb88102f2010-09-08 11:49:43 -0700270#endif
271 return;
272 }
273
274 // Optimize latency of app switches.
275 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
276 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
277 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
278 if (mAppSwitchDueTime < *nextWakeupTime) {
279 *nextWakeupTime = mAppSwitchDueTime;
280 }
281
Jeff Brownb88102f2010-09-08 11:49:43 -0700282 // Ready to start a new event.
283 // If we don't already have a pending event, go grab one.
284 if (! mPendingEvent) {
285 if (mInboundQueue.isEmpty()) {
286 if (isAppSwitchDue) {
287 // The inbound queue is empty so the app switch key we were waiting
288 // for will never arrive. Stop waiting for it.
289 resetPendingAppSwitchLocked(false);
290 isAppSwitchDue = false;
291 }
292
293 // Synthesize a key repeat if appropriate.
294 if (mKeyRepeatState.lastKeyEntry) {
295 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
Jeff Brown214eaf42011-05-26 19:17:02 -0700296 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700297 } else {
298 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
299 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
300 }
301 }
302 }
Jeff Browncc4f7db2011-08-30 20:34:48 -0700303
304 // Nothing to do if there is no pending event.
Jeff Brownb88102f2010-09-08 11:49:43 -0700305 if (! mPendingEvent) {
Jeff Browncc4f7db2011-08-30 20:34:48 -0700306 if (mActiveConnections.isEmpty()) {
307 dispatchIdleLocked();
308 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700309 return;
310 }
311 } else {
312 // Inbound queue has at least one entry.
Jeff Brownac386072011-07-20 15:19:50 -0700313 EventEntry* entry = mInboundQueue.head;
Jeff Brownb88102f2010-09-08 11:49:43 -0700314
315 // Throttle the entry if it is a move event and there are no
316 // other events behind it in the queue. Due to movement batching, additional
317 // samples may be appended to this event by the time the throttling timeout
318 // expires.
319 // TODO Make this smarter and consider throttling per device independently.
Jeff Brownb6997262010-10-08 22:31:17 -0700320 if (entry->type == EventEntry::TYPE_MOTION
321 && !isAppSwitchDue
322 && mDispatchEnabled
323 && (entry->policyFlags & POLICY_FLAG_PASS_TO_USER)
324 && !entry->isInjected()) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700325 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
326 int32_t deviceId = motionEntry->deviceId;
327 uint32_t source = motionEntry->source;
328 if (! isAppSwitchDue
Jeff Brownac386072011-07-20 15:19:50 -0700329 && !motionEntry->next // exactly one event, no successors
Jeff Browncc0c1592011-02-19 05:07:28 -0800330 && (motionEntry->action == AMOTION_EVENT_ACTION_MOVE
331 || motionEntry->action == AMOTION_EVENT_ACTION_HOVER_MOVE)
Jeff Brownb88102f2010-09-08 11:49:43 -0700332 && deviceId == mThrottleState.lastDeviceId
333 && source == mThrottleState.lastSource) {
334 nsecs_t nextTime = mThrottleState.lastEventTime
335 + mThrottleState.minTimeBetweenEvents;
336 if (currentTime < nextTime) {
337 // Throttle it!
338#if DEBUG_THROTTLING
Steve Block5baa3a62011-12-20 16:23:08 +0000339 ALOGD("Throttling - Delaying motion event for "
Jeff Brown90655042010-12-02 13:50:46 -0800340 "device %d, source 0x%08x by up to %0.3fms.",
Jeff Brownb88102f2010-09-08 11:49:43 -0700341 deviceId, source, (nextTime - currentTime) * 0.000001);
342#endif
343 if (nextTime < *nextWakeupTime) {
344 *nextWakeupTime = nextTime;
345 }
346 if (mThrottleState.originalSampleCount == 0) {
347 mThrottleState.originalSampleCount =
348 motionEntry->countSamples();
349 }
350 return;
351 }
352 }
353
354#if DEBUG_THROTTLING
355 if (mThrottleState.originalSampleCount != 0) {
356 uint32_t count = motionEntry->countSamples();
Steve Block5baa3a62011-12-20 16:23:08 +0000357 ALOGD("Throttling - Motion event sample count grew by %d from %d to %d.",
Jeff Brownb88102f2010-09-08 11:49:43 -0700358 count - mThrottleState.originalSampleCount,
359 mThrottleState.originalSampleCount, count);
360 mThrottleState.originalSampleCount = 0;
361 }
362#endif
363
makarand.karvekarf634ded2011-03-02 15:41:03 -0600364 mThrottleState.lastEventTime = currentTime;
Jeff Brownb88102f2010-09-08 11:49:43 -0700365 mThrottleState.lastDeviceId = deviceId;
366 mThrottleState.lastSource = source;
367 }
368
369 mInboundQueue.dequeue(entry);
370 mPendingEvent = entry;
371 }
Jeff Browne2fe69e2010-10-18 13:21:23 -0700372
373 // Poke user activity for this event.
374 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
375 pokeUserActivityLocked(mPendingEvent);
376 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700377 }
378
379 // Now we have an event to dispatch.
Jeff Brown928e0542011-01-10 11:17:36 -0800380 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Steve Blockec193de2012-01-09 18:35:44 +0000381 ALOG_ASSERT(mPendingEvent != NULL);
Jeff Brown54a18252010-09-16 14:07:33 -0700382 bool done = false;
Jeff Brownb6997262010-10-08 22:31:17 -0700383 DropReason dropReason = DROP_REASON_NOT_DROPPED;
384 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
385 dropReason = DROP_REASON_POLICY;
386 } else if (!mDispatchEnabled) {
387 dropReason = DROP_REASON_DISABLED;
388 }
Jeff Brown928e0542011-01-10 11:17:36 -0800389
390 if (mNextUnblockedEvent == mPendingEvent) {
391 mNextUnblockedEvent = NULL;
392 }
393
Jeff Brownb88102f2010-09-08 11:49:43 -0700394 switch (mPendingEvent->type) {
395 case EventEntry::TYPE_CONFIGURATION_CHANGED: {
396 ConfigurationChangedEntry* typedEntry =
397 static_cast<ConfigurationChangedEntry*>(mPendingEvent);
Jeff Brown54a18252010-09-16 14:07:33 -0700398 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Jeff Brownb6997262010-10-08 22:31:17 -0700399 dropReason = DROP_REASON_NOT_DROPPED; // configuration changes are never dropped
Jeff Brownb88102f2010-09-08 11:49:43 -0700400 break;
401 }
402
Jeff Brown65fd2512011-08-18 11:20:58 -0700403 case EventEntry::TYPE_DEVICE_RESET: {
404 DeviceResetEntry* typedEntry =
405 static_cast<DeviceResetEntry*>(mPendingEvent);
406 done = dispatchDeviceResetLocked(currentTime, typedEntry);
407 dropReason = DROP_REASON_NOT_DROPPED; // device resets are never dropped
408 break;
409 }
410
Jeff Brownb88102f2010-09-08 11:49:43 -0700411 case EventEntry::TYPE_KEY: {
412 KeyEntry* typedEntry = static_cast<KeyEntry*>(mPendingEvent);
Jeff Brownb6997262010-10-08 22:31:17 -0700413 if (isAppSwitchDue) {
414 if (isAppSwitchKeyEventLocked(typedEntry)) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700415 resetPendingAppSwitchLocked(true);
Jeff Brownb6997262010-10-08 22:31:17 -0700416 isAppSwitchDue = false;
417 } else if (dropReason == DROP_REASON_NOT_DROPPED) {
418 dropReason = DROP_REASON_APP_SWITCH;
Jeff Brownb88102f2010-09-08 11:49:43 -0700419 }
420 }
Jeff Brown928e0542011-01-10 11:17:36 -0800421 if (dropReason == DROP_REASON_NOT_DROPPED
422 && isStaleEventLocked(currentTime, typedEntry)) {
423 dropReason = DROP_REASON_STALE;
424 }
425 if (dropReason == DROP_REASON_NOT_DROPPED && mNextUnblockedEvent) {
426 dropReason = DROP_REASON_BLOCKED;
427 }
Jeff Brown214eaf42011-05-26 19:17:02 -0700428 done = dispatchKeyLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700429 break;
430 }
431
432 case EventEntry::TYPE_MOTION: {
433 MotionEntry* typedEntry = static_cast<MotionEntry*>(mPendingEvent);
Jeff Brownb6997262010-10-08 22:31:17 -0700434 if (dropReason == DROP_REASON_NOT_DROPPED && isAppSwitchDue) {
435 dropReason = DROP_REASON_APP_SWITCH;
Jeff Brownb88102f2010-09-08 11:49:43 -0700436 }
Jeff Brown928e0542011-01-10 11:17:36 -0800437 if (dropReason == DROP_REASON_NOT_DROPPED
438 && isStaleEventLocked(currentTime, typedEntry)) {
439 dropReason = DROP_REASON_STALE;
440 }
441 if (dropReason == DROP_REASON_NOT_DROPPED && mNextUnblockedEvent) {
442 dropReason = DROP_REASON_BLOCKED;
443 }
Jeff Brownb6997262010-10-08 22:31:17 -0700444 done = dispatchMotionLocked(currentTime, typedEntry,
Jeff Browne20c9e02010-10-11 14:20:19 -0700445 &dropReason, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700446 break;
447 }
448
449 default:
Steve Blockec193de2012-01-09 18:35:44 +0000450 ALOG_ASSERT(false);
Jeff Brownb88102f2010-09-08 11:49:43 -0700451 break;
452 }
453
Jeff Brown54a18252010-09-16 14:07:33 -0700454 if (done) {
Jeff Brownb6997262010-10-08 22:31:17 -0700455 if (dropReason != DROP_REASON_NOT_DROPPED) {
456 dropInboundEventLocked(mPendingEvent, dropReason);
457 }
458
Jeff Brown54a18252010-09-16 14:07:33 -0700459 releasePendingEventLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -0700460 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
461 }
462}
463
Jeff Browncc4f7db2011-08-30 20:34:48 -0700464void InputDispatcher::dispatchIdleLocked() {
465#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +0000466 ALOGD("Dispatcher idle. There are no pending events or active connections.");
Jeff Browncc4f7db2011-08-30 20:34:48 -0700467#endif
468
469 // Reset targets when idle, to release input channels and other resources
470 // they are holding onto.
471 resetTargetsLocked();
472}
473
Jeff Brownb88102f2010-09-08 11:49:43 -0700474bool InputDispatcher::enqueueInboundEventLocked(EventEntry* entry) {
475 bool needWake = mInboundQueue.isEmpty();
476 mInboundQueue.enqueueAtTail(entry);
477
478 switch (entry->type) {
Jeff Brownb6997262010-10-08 22:31:17 -0700479 case EventEntry::TYPE_KEY: {
Jeff Brown928e0542011-01-10 11:17:36 -0800480 // Optimize app switch latency.
481 // If the application takes too long to catch up then we drop all events preceding
482 // the app switch key.
Jeff Brownb6997262010-10-08 22:31:17 -0700483 KeyEntry* keyEntry = static_cast<KeyEntry*>(entry);
484 if (isAppSwitchKeyEventLocked(keyEntry)) {
485 if (keyEntry->action == AKEY_EVENT_ACTION_DOWN) {
486 mAppSwitchSawKeyDown = true;
487 } else if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
488 if (mAppSwitchSawKeyDown) {
489#if DEBUG_APP_SWITCH
Steve Block5baa3a62011-12-20 16:23:08 +0000490 ALOGD("App switch is pending!");
Jeff Brownb6997262010-10-08 22:31:17 -0700491#endif
492 mAppSwitchDueTime = keyEntry->eventTime + APP_SWITCH_TIMEOUT;
493 mAppSwitchSawKeyDown = false;
494 needWake = true;
495 }
496 }
497 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700498 break;
499 }
Jeff Brown928e0542011-01-10 11:17:36 -0800500
501 case EventEntry::TYPE_MOTION: {
502 // Optimize case where the current application is unresponsive and the user
503 // decides to touch a window in a different application.
504 // If the application takes too long to catch up then we drop all events preceding
505 // the touch into the other window.
506 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
Jeff Brown33bbfd22011-02-24 20:55:35 -0800507 if (motionEntry->action == AMOTION_EVENT_ACTION_DOWN
Jeff Brown928e0542011-01-10 11:17:36 -0800508 && (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER)
509 && mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY
Jeff Brown9302c872011-07-13 22:51:29 -0700510 && mInputTargetWaitApplicationHandle != NULL) {
Jeff Brown91c69ab2011-02-14 17:03:18 -0800511 int32_t x = int32_t(motionEntry->firstSample.pointerCoords[0].
Jeff Brownebbd5d12011-02-17 13:01:34 -0800512 getAxisValue(AMOTION_EVENT_AXIS_X));
Jeff Brown91c69ab2011-02-14 17:03:18 -0800513 int32_t y = int32_t(motionEntry->firstSample.pointerCoords[0].
Jeff Brownebbd5d12011-02-17 13:01:34 -0800514 getAxisValue(AMOTION_EVENT_AXIS_Y));
Jeff Brown9302c872011-07-13 22:51:29 -0700515 sp<InputWindowHandle> touchedWindowHandle = findTouchedWindowAtLocked(x, y);
516 if (touchedWindowHandle != NULL
517 && touchedWindowHandle->inputApplicationHandle
518 != mInputTargetWaitApplicationHandle) {
Jeff Brown928e0542011-01-10 11:17:36 -0800519 // User touched a different application than the one we are waiting on.
520 // Flag the event, and start pruning the input queue.
521 mNextUnblockedEvent = motionEntry;
522 needWake = true;
523 }
524 }
525 break;
526 }
Jeff Brownb6997262010-10-08 22:31:17 -0700527 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700528
529 return needWake;
530}
531
Jeff Brown9302c872011-07-13 22:51:29 -0700532sp<InputWindowHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t x, int32_t y) {
Jeff Brown928e0542011-01-10 11:17:36 -0800533 // Traverse windows from front to back to find touched window.
Jeff Brown9302c872011-07-13 22:51:29 -0700534 size_t numWindows = mWindowHandles.size();
Jeff Brown928e0542011-01-10 11:17:36 -0800535 for (size_t i = 0; i < numWindows; i++) {
Jeff Brown9302c872011-07-13 22:51:29 -0700536 sp<InputWindowHandle> windowHandle = mWindowHandles.itemAt(i);
Jeff Browncc4f7db2011-08-30 20:34:48 -0700537 const InputWindowInfo* windowInfo = windowHandle->getInfo();
538 int32_t flags = windowInfo->layoutParamsFlags;
Jeff Brown928e0542011-01-10 11:17:36 -0800539
Jeff Browncc4f7db2011-08-30 20:34:48 -0700540 if (windowInfo->visible) {
541 if (!(flags & InputWindowInfo::FLAG_NOT_TOUCHABLE)) {
542 bool isTouchModal = (flags & (InputWindowInfo::FLAG_NOT_FOCUSABLE
543 | InputWindowInfo::FLAG_NOT_TOUCH_MODAL)) == 0;
544 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
Jeff Brown928e0542011-01-10 11:17:36 -0800545 // Found window.
Jeff Brown9302c872011-07-13 22:51:29 -0700546 return windowHandle;
Jeff Brown928e0542011-01-10 11:17:36 -0800547 }
548 }
549 }
550
Jeff Browncc4f7db2011-08-30 20:34:48 -0700551 if (flags & InputWindowInfo::FLAG_SYSTEM_ERROR) {
Jeff Brown928e0542011-01-10 11:17:36 -0800552 // Error window is on top but not visible, so touch is dropped.
553 return NULL;
554 }
555 }
556 return NULL;
557}
558
Jeff Brownb6997262010-10-08 22:31:17 -0700559void InputDispatcher::dropInboundEventLocked(EventEntry* entry, DropReason dropReason) {
560 const char* reason;
561 switch (dropReason) {
562 case DROP_REASON_POLICY:
Jeff Browne20c9e02010-10-11 14:20:19 -0700563#if DEBUG_INBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +0000564 ALOGD("Dropped event because policy consumed it.");
Jeff Browne20c9e02010-10-11 14:20:19 -0700565#endif
Jeff Brown3122e442010-10-11 23:32:49 -0700566 reason = "inbound event was dropped because the policy consumed it";
Jeff Brownb6997262010-10-08 22:31:17 -0700567 break;
568 case DROP_REASON_DISABLED:
Steve Block6215d3f2012-01-04 20:05:49 +0000569 ALOGI("Dropped event because input dispatch is disabled.");
Jeff Brownb6997262010-10-08 22:31:17 -0700570 reason = "inbound event was dropped because input dispatch is disabled";
571 break;
572 case DROP_REASON_APP_SWITCH:
Steve Block6215d3f2012-01-04 20:05:49 +0000573 ALOGI("Dropped event because of pending overdue app switch.");
Jeff Brownb6997262010-10-08 22:31:17 -0700574 reason = "inbound event was dropped because of pending overdue app switch";
575 break;
Jeff Brown928e0542011-01-10 11:17:36 -0800576 case DROP_REASON_BLOCKED:
Steve Block6215d3f2012-01-04 20:05:49 +0000577 ALOGI("Dropped event because the current application is not responding and the user "
Jeff Brown81346812011-06-28 20:08:48 -0700578 "has started interacting with a different application.");
Jeff Brown928e0542011-01-10 11:17:36 -0800579 reason = "inbound event was dropped because the current application is not responding "
Jeff Brown81346812011-06-28 20:08:48 -0700580 "and the user has started interacting with a different application";
Jeff Brown928e0542011-01-10 11:17:36 -0800581 break;
582 case DROP_REASON_STALE:
Steve Block6215d3f2012-01-04 20:05:49 +0000583 ALOGI("Dropped event because it is stale.");
Jeff Brown928e0542011-01-10 11:17:36 -0800584 reason = "inbound event was dropped because it is stale";
585 break;
Jeff Brownb6997262010-10-08 22:31:17 -0700586 default:
Steve Blockec193de2012-01-09 18:35:44 +0000587 ALOG_ASSERT(false);
Jeff Brownb6997262010-10-08 22:31:17 -0700588 return;
589 }
590
591 switch (entry->type) {
Jeff Brownda3d5a92011-03-29 15:11:34 -0700592 case EventEntry::TYPE_KEY: {
593 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
594 synthesizeCancelationEventsForAllConnectionsLocked(options);
Jeff Brownb6997262010-10-08 22:31:17 -0700595 break;
Jeff Brownda3d5a92011-03-29 15:11:34 -0700596 }
Jeff Brownb6997262010-10-08 22:31:17 -0700597 case EventEntry::TYPE_MOTION: {
598 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
599 if (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) {
Jeff Brownda3d5a92011-03-29 15:11:34 -0700600 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
601 synthesizeCancelationEventsForAllConnectionsLocked(options);
Jeff Brownb6997262010-10-08 22:31:17 -0700602 } else {
Jeff Brownda3d5a92011-03-29 15:11:34 -0700603 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
604 synthesizeCancelationEventsForAllConnectionsLocked(options);
Jeff Brownb6997262010-10-08 22:31:17 -0700605 }
606 break;
607 }
608 }
609}
610
611bool InputDispatcher::isAppSwitchKeyCode(int32_t keyCode) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700612 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL;
613}
614
Jeff Brownb6997262010-10-08 22:31:17 -0700615bool InputDispatcher::isAppSwitchKeyEventLocked(KeyEntry* keyEntry) {
616 return ! (keyEntry->flags & AKEY_EVENT_FLAG_CANCELED)
617 && isAppSwitchKeyCode(keyEntry->keyCode)
Jeff Browne20c9e02010-10-11 14:20:19 -0700618 && (keyEntry->policyFlags & POLICY_FLAG_TRUSTED)
Jeff Brownb6997262010-10-08 22:31:17 -0700619 && (keyEntry->policyFlags & POLICY_FLAG_PASS_TO_USER);
620}
621
Jeff Brownb88102f2010-09-08 11:49:43 -0700622bool InputDispatcher::isAppSwitchPendingLocked() {
623 return mAppSwitchDueTime != LONG_LONG_MAX;
624}
625
Jeff Brownb88102f2010-09-08 11:49:43 -0700626void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
627 mAppSwitchDueTime = LONG_LONG_MAX;
628
629#if DEBUG_APP_SWITCH
630 if (handled) {
Steve Block5baa3a62011-12-20 16:23:08 +0000631 ALOGD("App switch has arrived.");
Jeff Brownb88102f2010-09-08 11:49:43 -0700632 } else {
Steve Block5baa3a62011-12-20 16:23:08 +0000633 ALOGD("App switch was abandoned.");
Jeff Brownb88102f2010-09-08 11:49:43 -0700634 }
635#endif
Jeff Brown46b9ac02010-04-22 18:58:52 -0700636}
637
Jeff Brown928e0542011-01-10 11:17:36 -0800638bool InputDispatcher::isStaleEventLocked(nsecs_t currentTime, EventEntry* entry) {
639 return currentTime - entry->eventTime >= STALE_EVENT_TIMEOUT;
640}
641
Jeff Brown9c3cda02010-06-15 01:31:58 -0700642bool InputDispatcher::runCommandsLockedInterruptible() {
643 if (mCommandQueue.isEmpty()) {
644 return false;
645 }
Jeff Brown46b9ac02010-04-22 18:58:52 -0700646
Jeff Brown9c3cda02010-06-15 01:31:58 -0700647 do {
648 CommandEntry* commandEntry = mCommandQueue.dequeueAtHead();
649
650 Command command = commandEntry->command;
651 (this->*command)(commandEntry); // commands are implicitly 'LockedInterruptible'
652
Jeff Brown7fbdc842010-06-17 20:52:56 -0700653 commandEntry->connection.clear();
Jeff Brownac386072011-07-20 15:19:50 -0700654 delete commandEntry;
Jeff Brown9c3cda02010-06-15 01:31:58 -0700655 } while (! mCommandQueue.isEmpty());
656 return true;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700657}
658
Jeff Brown9c3cda02010-06-15 01:31:58 -0700659InputDispatcher::CommandEntry* InputDispatcher::postCommandLocked(Command command) {
Jeff Brownac386072011-07-20 15:19:50 -0700660 CommandEntry* commandEntry = new CommandEntry(command);
Jeff Brown9c3cda02010-06-15 01:31:58 -0700661 mCommandQueue.enqueueAtTail(commandEntry);
662 return commandEntry;
663}
664
Jeff Brownb88102f2010-09-08 11:49:43 -0700665void InputDispatcher::drainInboundQueueLocked() {
666 while (! mInboundQueue.isEmpty()) {
667 EventEntry* entry = mInboundQueue.dequeueAtHead();
Jeff Brown54a18252010-09-16 14:07:33 -0700668 releaseInboundEventLocked(entry);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700669 }
Jeff Brown46b9ac02010-04-22 18:58:52 -0700670}
671
Jeff Brown54a18252010-09-16 14:07:33 -0700672void InputDispatcher::releasePendingEventLocked() {
Jeff Brownb88102f2010-09-08 11:49:43 -0700673 if (mPendingEvent) {
Jeff Brown54a18252010-09-16 14:07:33 -0700674 releaseInboundEventLocked(mPendingEvent);
Jeff Brownb88102f2010-09-08 11:49:43 -0700675 mPendingEvent = NULL;
676 }
677}
678
Jeff Brown54a18252010-09-16 14:07:33 -0700679void InputDispatcher::releaseInboundEventLocked(EventEntry* entry) {
Jeff Brown01ce2e92010-09-26 22:20:12 -0700680 InjectionState* injectionState = entry->injectionState;
681 if (injectionState && injectionState->injectionResult == INPUT_EVENT_INJECTION_PENDING) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700682#if DEBUG_DISPATCH_CYCLE
Steve Block5baa3a62011-12-20 16:23:08 +0000683 ALOGD("Injected inbound event was dropped.");
Jeff Brownb88102f2010-09-08 11:49:43 -0700684#endif
685 setInjectionResultLocked(entry, INPUT_EVENT_INJECTION_FAILED);
686 }
Jeff Brownabb4d442011-08-15 12:55:32 -0700687 if (entry == mNextUnblockedEvent) {
688 mNextUnblockedEvent = NULL;
689 }
Jeff Brownac386072011-07-20 15:19:50 -0700690 entry->release();
Jeff Brownb88102f2010-09-08 11:49:43 -0700691}
692
Jeff Brownb88102f2010-09-08 11:49:43 -0700693void InputDispatcher::resetKeyRepeatLocked() {
694 if (mKeyRepeatState.lastKeyEntry) {
Jeff Brownac386072011-07-20 15:19:50 -0700695 mKeyRepeatState.lastKeyEntry->release();
Jeff Brownb88102f2010-09-08 11:49:43 -0700696 mKeyRepeatState.lastKeyEntry = NULL;
697 }
698}
699
Jeff Brown214eaf42011-05-26 19:17:02 -0700700InputDispatcher::KeyEntry* InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
Jeff Brown349703e2010-06-22 01:27:15 -0700701 KeyEntry* entry = mKeyRepeatState.lastKeyEntry;
702
Jeff Brown349703e2010-06-22 01:27:15 -0700703 // Reuse the repeated key entry if it is otherwise unreferenced.
Jeff Browne20c9e02010-10-11 14:20:19 -0700704 uint32_t policyFlags = (entry->policyFlags & POLICY_FLAG_RAW_MASK)
705 | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700706 if (entry->refCount == 1) {
Jeff Brownac386072011-07-20 15:19:50 -0700707 entry->recycle();
Jeff Brown7fbdc842010-06-17 20:52:56 -0700708 entry->eventTime = currentTime;
Jeff Brown7fbdc842010-06-17 20:52:56 -0700709 entry->policyFlags = policyFlags;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700710 entry->repeatCount += 1;
711 } else {
Jeff Brownac386072011-07-20 15:19:50 -0700712 KeyEntry* newEntry = new KeyEntry(currentTime,
Jeff Brownc5ed5912010-07-14 18:48:53 -0700713 entry->deviceId, entry->source, policyFlags,
Jeff Brown7fbdc842010-06-17 20:52:56 -0700714 entry->action, entry->flags, entry->keyCode, entry->scanCode,
Jeff Brown00fa7bd2010-07-02 15:37:36 -0700715 entry->metaState, entry->repeatCount + 1, entry->downTime);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700716
717 mKeyRepeatState.lastKeyEntry = newEntry;
Jeff Brownac386072011-07-20 15:19:50 -0700718 entry->release();
Jeff Brown46b9ac02010-04-22 18:58:52 -0700719
720 entry = newEntry;
721 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700722 entry->syntheticRepeat = true;
723
724 // Increment reference count since we keep a reference to the event in
725 // mKeyRepeatState.lastKeyEntry in addition to the one we return.
726 entry->refCount += 1;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700727
Jeff Brown214eaf42011-05-26 19:17:02 -0700728 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Jeff Brownb88102f2010-09-08 11:49:43 -0700729 return entry;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700730}
731
Jeff Brownb88102f2010-09-08 11:49:43 -0700732bool InputDispatcher::dispatchConfigurationChangedLocked(
733 nsecs_t currentTime, ConfigurationChangedEntry* entry) {
Jeff Brown46b9ac02010-04-22 18:58:52 -0700734#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +0000735 ALOGD("dispatchConfigurationChanged - eventTime=%lld", entry->eventTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700736#endif
737
738 // Reset key repeating in case a keyboard device was added or removed or something.
739 resetKeyRepeatLocked();
740
741 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
742 CommandEntry* commandEntry = postCommandLocked(
743 & InputDispatcher::doNotifyConfigurationChangedInterruptible);
744 commandEntry->eventTime = entry->eventTime;
745 return true;
746}
747
Jeff Brown65fd2512011-08-18 11:20:58 -0700748bool InputDispatcher::dispatchDeviceResetLocked(
749 nsecs_t currentTime, DeviceResetEntry* entry) {
750#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +0000751 ALOGD("dispatchDeviceReset - eventTime=%lld, deviceId=%d", entry->eventTime, entry->deviceId);
Jeff Brown65fd2512011-08-18 11:20:58 -0700752#endif
753
754 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
755 "device was reset");
756 options.deviceId = entry->deviceId;
757 synthesizeCancelationEventsForAllConnectionsLocked(options);
758 return true;
759}
760
Jeff Brown214eaf42011-05-26 19:17:02 -0700761bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, KeyEntry* entry,
Jeff Browne20c9e02010-10-11 14:20:19 -0700762 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Jeff Browne46a0a42010-11-02 17:58:22 -0700763 // Preprocessing.
764 if (! entry->dispatchInProgress) {
765 if (entry->repeatCount == 0
766 && entry->action == AKEY_EVENT_ACTION_DOWN
767 && (entry->policyFlags & POLICY_FLAG_TRUSTED)
Jeff Brown0029c662011-03-30 02:25:18 -0700768 && (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
Jeff Browne46a0a42010-11-02 17:58:22 -0700769 if (mKeyRepeatState.lastKeyEntry
770 && mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode) {
771 // We have seen two identical key downs in a row which indicates that the device
772 // driver is automatically generating key repeats itself. We take note of the
773 // repeat here, but we disable our own next key repeat timer since it is clear that
774 // we will not need to synthesize key repeats ourselves.
775 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
776 resetKeyRepeatLocked();
777 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
778 } else {
779 // Not a repeat. Save key down state in case we do see a repeat later.
780 resetKeyRepeatLocked();
Jeff Brown214eaf42011-05-26 19:17:02 -0700781 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
Jeff Browne46a0a42010-11-02 17:58:22 -0700782 }
783 mKeyRepeatState.lastKeyEntry = entry;
784 entry->refCount += 1;
785 } else if (! entry->syntheticRepeat) {
786 resetKeyRepeatLocked();
787 }
788
Jeff Browne2e01262011-03-02 20:34:30 -0800789 if (entry->repeatCount == 1) {
790 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
791 } else {
792 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
793 }
794
Jeff Browne46a0a42010-11-02 17:58:22 -0700795 entry->dispatchInProgress = true;
796 resetTargetsLocked();
797
798 logOutboundKeyDetailsLocked("dispatchKey - ", entry);
799 }
800
Jeff Brown905805a2011-10-12 13:57:59 -0700801 // Handle case where the policy asked us to try again later last time.
802 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
803 if (currentTime < entry->interceptKeyWakeupTime) {
804 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
805 *nextWakeupTime = entry->interceptKeyWakeupTime;
806 }
807 return false; // wait until next wakeup
808 }
809 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
810 entry->interceptKeyWakeupTime = 0;
811 }
812
Jeff Brown54a18252010-09-16 14:07:33 -0700813 // Give the policy a chance to intercept the key.
814 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
Jeff Browne20c9e02010-10-11 14:20:19 -0700815 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Jeff Brown54a18252010-09-16 14:07:33 -0700816 CommandEntry* commandEntry = postCommandLocked(
817 & InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
Jeff Brown9302c872011-07-13 22:51:29 -0700818 if (mFocusedWindowHandle != NULL) {
819 commandEntry->inputWindowHandle = mFocusedWindowHandle;
Jeff Brown54a18252010-09-16 14:07:33 -0700820 }
821 commandEntry->keyEntry = entry;
822 entry->refCount += 1;
823 return false; // wait for the command to run
824 } else {
825 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
826 }
827 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Jeff Browne20c9e02010-10-11 14:20:19 -0700828 if (*dropReason == DROP_REASON_NOT_DROPPED) {
829 *dropReason = DROP_REASON_POLICY;
830 }
Jeff Brown54a18252010-09-16 14:07:33 -0700831 }
832
833 // Clean up if dropping the event.
Jeff Browne20c9e02010-10-11 14:20:19 -0700834 if (*dropReason != DROP_REASON_NOT_DROPPED) {
Jeff Brown54a18252010-09-16 14:07:33 -0700835 resetTargetsLocked();
Jeff Brown3122e442010-10-11 23:32:49 -0700836 setInjectionResultLocked(entry, *dropReason == DROP_REASON_POLICY
837 ? INPUT_EVENT_INJECTION_SUCCEEDED : INPUT_EVENT_INJECTION_FAILED);
Jeff Brown54a18252010-09-16 14:07:33 -0700838 return true;
839 }
840
Jeff Brownb88102f2010-09-08 11:49:43 -0700841 // Identify targets.
842 if (! mCurrentInputTargetsValid) {
Jeff Brown01ce2e92010-09-26 22:20:12 -0700843 int32_t injectionResult = findFocusedWindowTargetsLocked(currentTime,
844 entry, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700845 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
846 return false;
847 }
848
849 setInjectionResultLocked(entry, injectionResult);
850 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
851 return true;
852 }
853
854 addMonitoringTargetsLocked();
Jeff Brown01ce2e92010-09-26 22:20:12 -0700855 commitTargetsLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -0700856 }
857
858 // Dispatch the key.
859 dispatchEventToCurrentInputTargetsLocked(currentTime, entry, false);
Jeff Brownb88102f2010-09-08 11:49:43 -0700860 return true;
861}
862
863void InputDispatcher::logOutboundKeyDetailsLocked(const char* prefix, const KeyEntry* entry) {
864#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +0000865 ALOGD("%seventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, "
Jeff Brownb88102f2010-09-08 11:49:43 -0700866 "action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, "
Jeff Browne46a0a42010-11-02 17:58:22 -0700867 "repeatCount=%d, downTime=%lld",
Jeff Brownb88102f2010-09-08 11:49:43 -0700868 prefix,
869 entry->eventTime, entry->deviceId, entry->source, entry->policyFlags,
870 entry->action, entry->flags, entry->keyCode, entry->scanCode, entry->metaState,
Jeff Browne46a0a42010-11-02 17:58:22 -0700871 entry->repeatCount, entry->downTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700872#endif
873}
874
875bool InputDispatcher::dispatchMotionLocked(
Jeff Browne20c9e02010-10-11 14:20:19 -0700876 nsecs_t currentTime, MotionEntry* entry, DropReason* dropReason, nsecs_t* nextWakeupTime) {
Jeff Browne46a0a42010-11-02 17:58:22 -0700877 // Preprocessing.
878 if (! entry->dispatchInProgress) {
879 entry->dispatchInProgress = true;
880 resetTargetsLocked();
881
882 logOutboundMotionDetailsLocked("dispatchMotion - ", entry);
883 }
884
Jeff Brown54a18252010-09-16 14:07:33 -0700885 // Clean up if dropping the event.
Jeff Browne20c9e02010-10-11 14:20:19 -0700886 if (*dropReason != DROP_REASON_NOT_DROPPED) {
Jeff Brown54a18252010-09-16 14:07:33 -0700887 resetTargetsLocked();
Jeff Brown3122e442010-10-11 23:32:49 -0700888 setInjectionResultLocked(entry, *dropReason == DROP_REASON_POLICY
889 ? INPUT_EVENT_INJECTION_SUCCEEDED : INPUT_EVENT_INJECTION_FAILED);
Jeff Brown54a18252010-09-16 14:07:33 -0700890 return true;
891 }
892
Jeff Brownb88102f2010-09-08 11:49:43 -0700893 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
894
895 // Identify targets.
Jeff Browncc0c1592011-02-19 05:07:28 -0800896 bool conflictingPointerActions = false;
Jeff Brownb88102f2010-09-08 11:49:43 -0700897 if (! mCurrentInputTargetsValid) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700898 int32_t injectionResult;
Jeff Browna032cc02011-03-07 16:56:21 -0800899 const MotionSample* splitBatchAfterSample = NULL;
Jeff Brownb88102f2010-09-08 11:49:43 -0700900 if (isPointerEvent) {
901 // Pointer event. (eg. touchscreen)
Jeff Brown01ce2e92010-09-26 22:20:12 -0700902 injectionResult = findTouchedWindowTargetsLocked(currentTime,
Jeff Browna032cc02011-03-07 16:56:21 -0800903 entry, nextWakeupTime, &conflictingPointerActions, &splitBatchAfterSample);
Jeff Brownb88102f2010-09-08 11:49:43 -0700904 } else {
905 // Non touch event. (eg. trackball)
Jeff Brown01ce2e92010-09-26 22:20:12 -0700906 injectionResult = findFocusedWindowTargetsLocked(currentTime,
907 entry, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700908 }
909 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
910 return false;
911 }
912
913 setInjectionResultLocked(entry, injectionResult);
914 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
915 return true;
916 }
917
918 addMonitoringTargetsLocked();
Jeff Brown01ce2e92010-09-26 22:20:12 -0700919 commitTargetsLocked();
Jeff Browna032cc02011-03-07 16:56:21 -0800920
921 // Unbatch the event if necessary by splitting it into two parts after the
922 // motion sample indicated by splitBatchAfterSample.
923 if (splitBatchAfterSample && splitBatchAfterSample->next) {
924#if DEBUG_BATCHING
925 uint32_t originalSampleCount = entry->countSamples();
926#endif
927 MotionSample* nextSample = splitBatchAfterSample->next;
Jeff Brownac386072011-07-20 15:19:50 -0700928 MotionEntry* nextEntry = new MotionEntry(nextSample->eventTime,
Jeff Browna032cc02011-03-07 16:56:21 -0800929 entry->deviceId, entry->source, entry->policyFlags,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700930 entry->action, entry->flags,
931 entry->metaState, entry->buttonState, entry->edgeFlags,
Jeff Browna032cc02011-03-07 16:56:21 -0800932 entry->xPrecision, entry->yPrecision, entry->downTime,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700933 entry->pointerCount, entry->pointerProperties, nextSample->pointerCoords);
Jeff Browna032cc02011-03-07 16:56:21 -0800934 if (nextSample != entry->lastSample) {
935 nextEntry->firstSample.next = nextSample->next;
936 nextEntry->lastSample = entry->lastSample;
937 }
Jeff Brownac386072011-07-20 15:19:50 -0700938 delete nextSample;
Jeff Browna032cc02011-03-07 16:56:21 -0800939
940 entry->lastSample = const_cast<MotionSample*>(splitBatchAfterSample);
941 entry->lastSample->next = NULL;
942
943 if (entry->injectionState) {
944 nextEntry->injectionState = entry->injectionState;
945 entry->injectionState->refCount += 1;
946 }
947
948#if DEBUG_BATCHING
Steve Block5baa3a62011-12-20 16:23:08 +0000949 ALOGD("Split batch of %d samples into two parts, first part has %d samples, "
Jeff Browna032cc02011-03-07 16:56:21 -0800950 "second part has %d samples.", originalSampleCount,
951 entry->countSamples(), nextEntry->countSamples());
952#endif
953
954 mInboundQueue.enqueueAtHead(nextEntry);
955 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700956 }
957
958 // Dispatch the motion.
Jeff Browncc0c1592011-02-19 05:07:28 -0800959 if (conflictingPointerActions) {
Jeff Brownda3d5a92011-03-29 15:11:34 -0700960 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
961 "conflicting pointer actions");
962 synthesizeCancelationEventsForAllConnectionsLocked(options);
Jeff Browncc0c1592011-02-19 05:07:28 -0800963 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700964 dispatchEventToCurrentInputTargetsLocked(currentTime, entry, false);
Jeff Brownb88102f2010-09-08 11:49:43 -0700965 return true;
966}
967
968
969void InputDispatcher::logOutboundMotionDetailsLocked(const char* prefix, const MotionEntry* entry) {
970#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +0000971 ALOGD("%seventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, "
Jeff Brown85a31762010-09-01 17:01:00 -0700972 "action=0x%x, flags=0x%x, "
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700973 "metaState=0x%x, buttonState=0x%x, "
974 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%lld",
Jeff Brownb88102f2010-09-08 11:49:43 -0700975 prefix,
Jeff Brown85a31762010-09-01 17:01:00 -0700976 entry->eventTime, entry->deviceId, entry->source, entry->policyFlags,
977 entry->action, entry->flags,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700978 entry->metaState, entry->buttonState,
979 entry->edgeFlags, entry->xPrecision, entry->yPrecision,
Jeff Brown46b9ac02010-04-22 18:58:52 -0700980 entry->downTime);
981
982 // Print the most recent sample that we have available, this may change due to batching.
983 size_t sampleCount = 1;
Jeff Brownb88102f2010-09-08 11:49:43 -0700984 const MotionSample* sample = & entry->firstSample;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700985 for (; sample->next != NULL; sample = sample->next) {
986 sampleCount += 1;
987 }
988 for (uint32_t i = 0; i < entry->pointerCount; i++) {
Steve Block5baa3a62011-12-20 16:23:08 +0000989 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700990 "x=%f, y=%f, pressure=%f, size=%f, "
Jeff Brown85a31762010-09-01 17:01:00 -0700991 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
Jeff Brown8d608662010-08-30 03:02:23 -0700992 "orientation=%f",
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700993 i, entry->pointerProperties[i].id,
994 entry->pointerProperties[i].toolType,
Jeff Brownebbd5d12011-02-17 13:01:34 -0800995 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
996 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
997 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
998 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
999 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1000 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1001 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1002 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1003 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Jeff Brown46b9ac02010-04-22 18:58:52 -07001004 }
1005
1006 // Keep in mind that due to batching, it is possible for the number of samples actually
1007 // dispatched to change before the application finally consumed them.
Jeff Brownc5ed5912010-07-14 18:48:53 -07001008 if (entry->action == AMOTION_EVENT_ACTION_MOVE) {
Steve Block5baa3a62011-12-20 16:23:08 +00001009 ALOGD(" ... Total movement samples currently batched %d ...", sampleCount);
Jeff Brown46b9ac02010-04-22 18:58:52 -07001010 }
1011#endif
Jeff Brown46b9ac02010-04-22 18:58:52 -07001012}
1013
1014void InputDispatcher::dispatchEventToCurrentInputTargetsLocked(nsecs_t currentTime,
1015 EventEntry* eventEntry, bool resumeWithAppendedMotionSample) {
1016#if DEBUG_DISPATCH_CYCLE
Steve Block5baa3a62011-12-20 16:23:08 +00001017 ALOGD("dispatchEventToCurrentInputTargets - "
Jeff Brown46b9ac02010-04-22 18:58:52 -07001018 "resumeWithAppendedMotionSample=%s",
Jeff Brownb88102f2010-09-08 11:49:43 -07001019 toString(resumeWithAppendedMotionSample));
Jeff Brown46b9ac02010-04-22 18:58:52 -07001020#endif
1021
Steve Blockec193de2012-01-09 18:35:44 +00001022 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
Jeff Brown9c3cda02010-06-15 01:31:58 -07001023
Jeff Browne2fe69e2010-10-18 13:21:23 -07001024 pokeUserActivityLocked(eventEntry);
1025
Jeff Brown46b9ac02010-04-22 18:58:52 -07001026 for (size_t i = 0; i < mCurrentInputTargets.size(); i++) {
1027 const InputTarget& inputTarget = mCurrentInputTargets.itemAt(i);
1028
Jeff Brown519e0242010-09-15 15:18:56 -07001029 ssize_t connectionIndex = getConnectionIndexLocked(inputTarget.inputChannel);
Jeff Brown46b9ac02010-04-22 18:58:52 -07001030 if (connectionIndex >= 0) {
1031 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
Jeff Brown7fbdc842010-06-17 20:52:56 -07001032 prepareDispatchCycleLocked(currentTime, connection, eventEntry, & inputTarget,
Jeff Brown46b9ac02010-04-22 18:58:52 -07001033 resumeWithAppendedMotionSample);
1034 } else {
Jeff Brownb6997262010-10-08 22:31:17 -07001035#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001036 ALOGD("Dropping event delivery to target with channel '%s' because it "
Jeff Brownb6997262010-10-08 22:31:17 -07001037 "is no longer registered with the input dispatcher.",
Jeff Brown46b9ac02010-04-22 18:58:52 -07001038 inputTarget.inputChannel->getName().string());
Jeff Brownb6997262010-10-08 22:31:17 -07001039#endif
Jeff Brown46b9ac02010-04-22 18:58:52 -07001040 }
1041 }
1042}
1043
Jeff Brown54a18252010-09-16 14:07:33 -07001044void InputDispatcher::resetTargetsLocked() {
Jeff Brownb88102f2010-09-08 11:49:43 -07001045 mCurrentInputTargetsValid = false;
1046 mCurrentInputTargets.clear();
Jeff Brown5ea29ab2011-07-27 11:50:51 -07001047 resetANRTimeoutsLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -07001048}
1049
Jeff Brown01ce2e92010-09-26 22:20:12 -07001050void InputDispatcher::commitTargetsLocked() {
Jeff Brownb88102f2010-09-08 11:49:43 -07001051 mCurrentInputTargetsValid = true;
1052}
1053
1054int32_t InputDispatcher::handleTargetsNotReadyLocked(nsecs_t currentTime,
Jeff Brown9302c872011-07-13 22:51:29 -07001055 const EventEntry* entry,
1056 const sp<InputApplicationHandle>& applicationHandle,
1057 const sp<InputWindowHandle>& windowHandle,
Jeff Brownb88102f2010-09-08 11:49:43 -07001058 nsecs_t* nextWakeupTime) {
Jeff Brown9302c872011-07-13 22:51:29 -07001059 if (applicationHandle == NULL && windowHandle == NULL) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001060 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY) {
1061#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001062 ALOGD("Waiting for system to become ready for input.");
Jeff Brownb88102f2010-09-08 11:49:43 -07001063#endif
1064 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY;
1065 mInputTargetWaitStartTime = currentTime;
1066 mInputTargetWaitTimeoutTime = LONG_LONG_MAX;
1067 mInputTargetWaitTimeoutExpired = false;
Jeff Brown9302c872011-07-13 22:51:29 -07001068 mInputTargetWaitApplicationHandle.clear();
Jeff Brownb88102f2010-09-08 11:49:43 -07001069 }
1070 } else {
1071 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
1072#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001073 ALOGD("Waiting for application to become ready for input: %s",
Jeff Brown9302c872011-07-13 22:51:29 -07001074 getApplicationWindowLabelLocked(applicationHandle, windowHandle).string());
Jeff Brownb88102f2010-09-08 11:49:43 -07001075#endif
Jeff Browncc4f7db2011-08-30 20:34:48 -07001076 nsecs_t timeout;
1077 if (windowHandle != NULL) {
1078 timeout = windowHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
1079 } else if (applicationHandle != NULL) {
1080 timeout = applicationHandle->getDispatchingTimeout(
1081 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
1082 } else {
1083 timeout = DEFAULT_INPUT_DISPATCHING_TIMEOUT;
1084 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001085
1086 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY;
1087 mInputTargetWaitStartTime = currentTime;
1088 mInputTargetWaitTimeoutTime = currentTime + timeout;
1089 mInputTargetWaitTimeoutExpired = false;
Jeff Brown9302c872011-07-13 22:51:29 -07001090 mInputTargetWaitApplicationHandle.clear();
Jeff Brown928e0542011-01-10 11:17:36 -08001091
Jeff Brown9302c872011-07-13 22:51:29 -07001092 if (windowHandle != NULL) {
1093 mInputTargetWaitApplicationHandle = windowHandle->inputApplicationHandle;
Jeff Brown928e0542011-01-10 11:17:36 -08001094 }
Jeff Brown9302c872011-07-13 22:51:29 -07001095 if (mInputTargetWaitApplicationHandle == NULL && applicationHandle != NULL) {
1096 mInputTargetWaitApplicationHandle = applicationHandle;
Jeff Brown928e0542011-01-10 11:17:36 -08001097 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001098 }
1099 }
1100
1101 if (mInputTargetWaitTimeoutExpired) {
1102 return INPUT_EVENT_INJECTION_TIMED_OUT;
1103 }
1104
1105 if (currentTime >= mInputTargetWaitTimeoutTime) {
Jeff Brown9302c872011-07-13 22:51:29 -07001106 onANRLocked(currentTime, applicationHandle, windowHandle,
1107 entry->eventTime, mInputTargetWaitStartTime);
Jeff Brownb88102f2010-09-08 11:49:43 -07001108
1109 // Force poll loop to wake up immediately on next iteration once we get the
1110 // ANR response back from the policy.
1111 *nextWakeupTime = LONG_LONG_MIN;
1112 return INPUT_EVENT_INJECTION_PENDING;
1113 } else {
1114 // Force poll loop to wake up when timeout is due.
1115 if (mInputTargetWaitTimeoutTime < *nextWakeupTime) {
1116 *nextWakeupTime = mInputTargetWaitTimeoutTime;
1117 }
1118 return INPUT_EVENT_INJECTION_PENDING;
1119 }
1120}
1121
Jeff Brown519e0242010-09-15 15:18:56 -07001122void InputDispatcher::resumeAfterTargetsNotReadyTimeoutLocked(nsecs_t newTimeout,
1123 const sp<InputChannel>& inputChannel) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001124 if (newTimeout > 0) {
1125 // Extend the timeout.
1126 mInputTargetWaitTimeoutTime = now() + newTimeout;
1127 } else {
1128 // Give up.
1129 mInputTargetWaitTimeoutExpired = true;
Jeff Brown519e0242010-09-15 15:18:56 -07001130
Jeff Brown01ce2e92010-09-26 22:20:12 -07001131 // Release the touch targets.
1132 mTouchState.reset();
Jeff Brown2a95c2a2010-09-16 12:31:46 -07001133
Jeff Brown519e0242010-09-15 15:18:56 -07001134 // Input state will not be realistic. Mark it out of sync.
Jeff Browndc3e0052010-09-16 11:02:16 -07001135 if (inputChannel.get()) {
1136 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
1137 if (connectionIndex >= 0) {
1138 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
Jeff Brown00045a72010-12-09 18:10:30 -08001139 if (connection->status == Connection::STATUS_NORMAL) {
Jeff Brownda3d5a92011-03-29 15:11:34 -07001140 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
Jeff Brown00045a72010-12-09 18:10:30 -08001141 "application not responding");
Jeff Brownda3d5a92011-03-29 15:11:34 -07001142 synthesizeCancelationEventsForConnectionLocked(connection, options);
Jeff Brown00045a72010-12-09 18:10:30 -08001143 }
Jeff Browndc3e0052010-09-16 11:02:16 -07001144 }
Jeff Brown519e0242010-09-15 15:18:56 -07001145 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001146 }
1147}
1148
Jeff Brown519e0242010-09-15 15:18:56 -07001149nsecs_t InputDispatcher::getTimeSpentWaitingForApplicationLocked(
Jeff Brownb88102f2010-09-08 11:49:43 -07001150 nsecs_t currentTime) {
1151 if (mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
1152 return currentTime - mInputTargetWaitStartTime;
1153 }
1154 return 0;
1155}
1156
1157void InputDispatcher::resetANRTimeoutsLocked() {
1158#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001159 ALOGD("Resetting ANR timeouts.");
Jeff Brownb88102f2010-09-08 11:49:43 -07001160#endif
1161
Jeff Brownb88102f2010-09-08 11:49:43 -07001162 // Reset input target wait timeout.
1163 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_NONE;
Jeff Brown5ea29ab2011-07-27 11:50:51 -07001164 mInputTargetWaitApplicationHandle.clear();
Jeff Brownb88102f2010-09-08 11:49:43 -07001165}
1166
Jeff Brown01ce2e92010-09-26 22:20:12 -07001167int32_t InputDispatcher::findFocusedWindowTargetsLocked(nsecs_t currentTime,
1168 const EventEntry* entry, nsecs_t* nextWakeupTime) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001169 mCurrentInputTargets.clear();
1170
1171 int32_t injectionResult;
1172
1173 // If there is no currently focused window and no focused application
1174 // then drop the event.
Jeff Brown9302c872011-07-13 22:51:29 -07001175 if (mFocusedWindowHandle == NULL) {
1176 if (mFocusedApplicationHandle != NULL) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001177#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001178 ALOGD("Waiting because there is no focused window but there is a "
Jeff Brown519e0242010-09-15 15:18:56 -07001179 "focused application that may eventually add a window: %s.",
Jeff Brown9302c872011-07-13 22:51:29 -07001180 getApplicationWindowLabelLocked(mFocusedApplicationHandle, NULL).string());
Jeff Brownb88102f2010-09-08 11:49:43 -07001181#endif
1182 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brown9302c872011-07-13 22:51:29 -07001183 mFocusedApplicationHandle, NULL, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -07001184 goto Unresponsive;
1185 }
1186
Steve Block6215d3f2012-01-04 20:05:49 +00001187 ALOGI("Dropping event because there is no focused window or focused application.");
Jeff Brownb88102f2010-09-08 11:49:43 -07001188 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1189 goto Failed;
1190 }
1191
1192 // Check permissions.
Jeff Brown9302c872011-07-13 22:51:29 -07001193 if (! checkInjectionPermission(mFocusedWindowHandle, entry->injectionState)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001194 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1195 goto Failed;
1196 }
1197
1198 // If the currently focused window is paused then keep waiting.
Jeff Browncc4f7db2011-08-30 20:34:48 -07001199 if (mFocusedWindowHandle->getInfo()->paused) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001200#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001201 ALOGD("Waiting because focused window is paused.");
Jeff Brownb88102f2010-09-08 11:49:43 -07001202#endif
1203 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brown9302c872011-07-13 22:51:29 -07001204 mFocusedApplicationHandle, mFocusedWindowHandle, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -07001205 goto Unresponsive;
1206 }
1207
Jeff Brown519e0242010-09-15 15:18:56 -07001208 // If the currently focused window is still working on previous events then keep waiting.
Jeff Brown9302c872011-07-13 22:51:29 -07001209 if (! isWindowFinishedWithPreviousInputLocked(mFocusedWindowHandle)) {
Jeff Brown519e0242010-09-15 15:18:56 -07001210#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001211 ALOGD("Waiting because focused window still processing previous input.");
Jeff Brown519e0242010-09-15 15:18:56 -07001212#endif
1213 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brown9302c872011-07-13 22:51:29 -07001214 mFocusedApplicationHandle, mFocusedWindowHandle, nextWakeupTime);
Jeff Brown519e0242010-09-15 15:18:56 -07001215 goto Unresponsive;
1216 }
1217
Jeff Brownb88102f2010-09-08 11:49:43 -07001218 // Success! Output targets.
1219 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
Jeff Brown9302c872011-07-13 22:51:29 -07001220 addWindowTargetLocked(mFocusedWindowHandle,
Jeff Browna032cc02011-03-07 16:56:21 -08001221 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS, BitSet32(0));
Jeff Brownb88102f2010-09-08 11:49:43 -07001222
1223 // Done.
1224Failed:
1225Unresponsive:
Jeff Brown519e0242010-09-15 15:18:56 -07001226 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
1227 updateDispatchStatisticsLocked(currentTime, entry,
1228 injectionResult, timeSpentWaitingForApplication);
Jeff Brownb88102f2010-09-08 11:49:43 -07001229#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001230 ALOGD("findFocusedWindow finished: injectionResult=%d, "
Jeff Brown519e0242010-09-15 15:18:56 -07001231 "timeSpendWaitingForApplication=%0.1fms",
1232 injectionResult, timeSpentWaitingForApplication / 1000000.0);
Jeff Brownb88102f2010-09-08 11:49:43 -07001233#endif
1234 return injectionResult;
1235}
1236
Jeff Brown01ce2e92010-09-26 22:20:12 -07001237int32_t InputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime,
Jeff Browna032cc02011-03-07 16:56:21 -08001238 const MotionEntry* entry, nsecs_t* nextWakeupTime, bool* outConflictingPointerActions,
1239 const MotionSample** outSplitBatchAfterSample) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001240 enum InjectionPermission {
1241 INJECTION_PERMISSION_UNKNOWN,
1242 INJECTION_PERMISSION_GRANTED,
1243 INJECTION_PERMISSION_DENIED
1244 };
1245
Jeff Brownb88102f2010-09-08 11:49:43 -07001246 mCurrentInputTargets.clear();
1247
1248 nsecs_t startTime = now();
1249
1250 // For security reasons, we defer updating the touch state until we are sure that
1251 // event injection will be allowed.
1252 //
1253 // FIXME In the original code, screenWasOff could never be set to true.
1254 // The reason is that the POLICY_FLAG_WOKE_HERE
1255 // and POLICY_FLAG_BRIGHT_HERE flags were set only when preprocessing raw
1256 // EV_KEY, EV_REL and EV_ABS events. As it happens, the touch event was
1257 // actually enqueued using the policyFlags that appeared in the final EV_SYN
1258 // events upon which no preprocessing took place. So policyFlags was always 0.
1259 // In the new native input dispatcher we're a bit more careful about event
1260 // preprocessing so the touches we receive can actually have non-zero policyFlags.
1261 // Unfortunately we obtain undesirable behavior.
1262 //
1263 // Here's what happens:
1264 //
1265 // When the device dims in anticipation of going to sleep, touches
1266 // in windows which have FLAG_TOUCHABLE_WHEN_WAKING cause
1267 // the device to brighten and reset the user activity timer.
1268 // Touches on other windows (such as the launcher window)
1269 // are dropped. Then after a moment, the device goes to sleep. Oops.
1270 //
1271 // Also notice how screenWasOff was being initialized using POLICY_FLAG_BRIGHT_HERE
1272 // instead of POLICY_FLAG_WOKE_HERE...
1273 //
1274 bool screenWasOff = false; // original policy: policyFlags & POLICY_FLAG_BRIGHT_HERE;
1275
1276 int32_t action = entry->action;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001277 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Jeff Brownb88102f2010-09-08 11:49:43 -07001278
1279 // Update the touch state as needed based on the properties of the touch event.
Jeff Brown01ce2e92010-09-26 22:20:12 -07001280 int32_t injectionResult = INPUT_EVENT_INJECTION_PENDING;
1281 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
Jeff Brown9302c872011-07-13 22:51:29 -07001282 sp<InputWindowHandle> newHoverWindowHandle;
Jeff Browncc0c1592011-02-19 05:07:28 -08001283
1284 bool isSplit = mTouchState.split;
Jeff Brown2717eff2011-06-30 23:53:07 -07001285 bool switchedDevice = mTouchState.deviceId >= 0
1286 && (mTouchState.deviceId != entry->deviceId
1287 || mTouchState.source != entry->source);
Jeff Browna032cc02011-03-07 16:56:21 -08001288 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE
1289 || maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER
1290 || maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1291 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN
1292 || maskedAction == AMOTION_EVENT_ACTION_SCROLL
1293 || isHoverAction);
Jeff Brown81346812011-06-28 20:08:48 -07001294 bool wrongDevice = false;
Jeff Browna032cc02011-03-07 16:56:21 -08001295 if (newGesture) {
Jeff Browncc0c1592011-02-19 05:07:28 -08001296 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Jeff Brown81346812011-06-28 20:08:48 -07001297 if (switchedDevice && mTouchState.down && !down) {
1298#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001299 ALOGD("Dropping event because a pointer for a different device is already down.");
Jeff Brown81346812011-06-28 20:08:48 -07001300#endif
Jeff Browncc0c1592011-02-19 05:07:28 -08001301 mTempTouchState.copyFrom(mTouchState);
Jeff Brown81346812011-06-28 20:08:48 -07001302 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1303 switchedDevice = false;
1304 wrongDevice = true;
1305 goto Failed;
Jeff Browncc0c1592011-02-19 05:07:28 -08001306 }
Jeff Brown81346812011-06-28 20:08:48 -07001307 mTempTouchState.reset();
1308 mTempTouchState.down = down;
1309 mTempTouchState.deviceId = entry->deviceId;
1310 mTempTouchState.source = entry->source;
1311 isSplit = false;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001312 } else {
1313 mTempTouchState.copyFrom(mTouchState);
Jeff Browncc0c1592011-02-19 05:07:28 -08001314 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001315
Jeff Browna032cc02011-03-07 16:56:21 -08001316 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
Jeff Brown33bbfd22011-02-24 20:55:35 -08001317 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
Jeff Brownb88102f2010-09-08 11:49:43 -07001318
Jeff Browna032cc02011-03-07 16:56:21 -08001319 const MotionSample* sample = &entry->firstSample;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001320 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Jeff Browna032cc02011-03-07 16:56:21 -08001321 int32_t x = int32_t(sample->pointerCoords[pointerIndex].
Jeff Brownebbd5d12011-02-17 13:01:34 -08001322 getAxisValue(AMOTION_EVENT_AXIS_X));
Jeff Browna032cc02011-03-07 16:56:21 -08001323 int32_t y = int32_t(sample->pointerCoords[pointerIndex].
Jeff Brownebbd5d12011-02-17 13:01:34 -08001324 getAxisValue(AMOTION_EVENT_AXIS_Y));
Jeff Brown9302c872011-07-13 22:51:29 -07001325 sp<InputWindowHandle> newTouchedWindowHandle;
1326 sp<InputWindowHandle> topErrorWindowHandle;
Jeff Browna032cc02011-03-07 16:56:21 -08001327 bool isTouchModal = false;
Jeff Brownb88102f2010-09-08 11:49:43 -07001328
1329 // Traverse windows from front to back to find touched window and outside targets.
Jeff Brown9302c872011-07-13 22:51:29 -07001330 size_t numWindows = mWindowHandles.size();
Jeff Brownb88102f2010-09-08 11:49:43 -07001331 for (size_t i = 0; i < numWindows; i++) {
Jeff Brown9302c872011-07-13 22:51:29 -07001332 sp<InputWindowHandle> windowHandle = mWindowHandles.itemAt(i);
Jeff Browncc4f7db2011-08-30 20:34:48 -07001333 const InputWindowInfo* windowInfo = windowHandle->getInfo();
1334 int32_t flags = windowInfo->layoutParamsFlags;
Jeff Brownb88102f2010-09-08 11:49:43 -07001335
Jeff Browncc4f7db2011-08-30 20:34:48 -07001336 if (flags & InputWindowInfo::FLAG_SYSTEM_ERROR) {
Jeff Brown9302c872011-07-13 22:51:29 -07001337 if (topErrorWindowHandle == NULL) {
1338 topErrorWindowHandle = windowHandle;
Jeff Brownb88102f2010-09-08 11:49:43 -07001339 }
1340 }
1341
Jeff Browncc4f7db2011-08-30 20:34:48 -07001342 if (windowInfo->visible) {
1343 if (! (flags & InputWindowInfo::FLAG_NOT_TOUCHABLE)) {
1344 isTouchModal = (flags & (InputWindowInfo::FLAG_NOT_FOCUSABLE
1345 | InputWindowInfo::FLAG_NOT_TOUCH_MODAL)) == 0;
1346 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
Jeff Brown9302c872011-07-13 22:51:29 -07001347 if (! screenWasOff
Jeff Browncc4f7db2011-08-30 20:34:48 -07001348 || (flags & InputWindowInfo::FLAG_TOUCHABLE_WHEN_WAKING)) {
Jeff Brown9302c872011-07-13 22:51:29 -07001349 newTouchedWindowHandle = windowHandle;
Jeff Brownb88102f2010-09-08 11:49:43 -07001350 }
1351 break; // found touched window, exit window loop
1352 }
1353 }
1354
Jeff Brown01ce2e92010-09-26 22:20:12 -07001355 if (maskedAction == AMOTION_EVENT_ACTION_DOWN
Jeff Browncc4f7db2011-08-30 20:34:48 -07001356 && (flags & InputWindowInfo::FLAG_WATCH_OUTSIDE_TOUCH)) {
Jeff Browna032cc02011-03-07 16:56:21 -08001357 int32_t outsideTargetFlags = InputTarget::FLAG_DISPATCH_AS_OUTSIDE;
Jeff Brown9302c872011-07-13 22:51:29 -07001358 if (isWindowObscuredAtPointLocked(windowHandle, x, y)) {
Jeff Brown19dfc832010-10-05 12:26:23 -07001359 outsideTargetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1360 }
1361
Jeff Brown9302c872011-07-13 22:51:29 -07001362 mTempTouchState.addOrUpdateWindow(
1363 windowHandle, outsideTargetFlags, BitSet32(0));
Jeff Brownb88102f2010-09-08 11:49:43 -07001364 }
1365 }
1366 }
1367
1368 // If there is an error window but it is not taking focus (typically because
1369 // it is invisible) then wait for it. Any other focused window may in
1370 // fact be in ANR state.
Jeff Brown9302c872011-07-13 22:51:29 -07001371 if (topErrorWindowHandle != NULL && newTouchedWindowHandle != topErrorWindowHandle) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001372#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001373 ALOGD("Waiting because system error window is pending.");
Jeff Brownb88102f2010-09-08 11:49:43 -07001374#endif
1375 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
1376 NULL, NULL, nextWakeupTime);
1377 injectionPermission = INJECTION_PERMISSION_UNKNOWN;
1378 goto Unresponsive;
1379 }
1380
Jeff Brown01ce2e92010-09-26 22:20:12 -07001381 // Figure out whether splitting will be allowed for this window.
Jeff Browncc4f7db2011-08-30 20:34:48 -07001382 if (newTouchedWindowHandle != NULL
1383 && newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001384 // New window supports splitting.
1385 isSplit = true;
1386 } else if (isSplit) {
1387 // New window does not support splitting but we have already split events.
1388 // Assign the pointer to the first foreground window we find.
1389 // (May be NULL which is why we put this code block before the next check.)
Jeff Brown9302c872011-07-13 22:51:29 -07001390 newTouchedWindowHandle = mTempTouchState.getFirstForegroundWindowHandle();
Jeff Brown01ce2e92010-09-26 22:20:12 -07001391 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001392
Jeff Brownb88102f2010-09-08 11:49:43 -07001393 // If we did not find a touched window then fail.
Jeff Brown9302c872011-07-13 22:51:29 -07001394 if (newTouchedWindowHandle == NULL) {
1395 if (mFocusedApplicationHandle != NULL) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001396#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001397 ALOGD("Waiting because there is no touched window but there is a "
Jeff Brown519e0242010-09-15 15:18:56 -07001398 "focused application that may eventually add a new window: %s.",
Jeff Brown9302c872011-07-13 22:51:29 -07001399 getApplicationWindowLabelLocked(mFocusedApplicationHandle, NULL).string());
Jeff Brownb88102f2010-09-08 11:49:43 -07001400#endif
1401 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brown9302c872011-07-13 22:51:29 -07001402 mFocusedApplicationHandle, NULL, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -07001403 goto Unresponsive;
1404 }
1405
Steve Block6215d3f2012-01-04 20:05:49 +00001406 ALOGI("Dropping event because there is no touched window or focused application.");
Jeff Brownb88102f2010-09-08 11:49:43 -07001407 injectionResult = INPUT_EVENT_INJECTION_FAILED;
Jeff Brownb88102f2010-09-08 11:49:43 -07001408 goto Failed;
1409 }
1410
Jeff Brown19dfc832010-10-05 12:26:23 -07001411 // Set target flags.
Jeff Browna032cc02011-03-07 16:56:21 -08001412 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
Jeff Brown19dfc832010-10-05 12:26:23 -07001413 if (isSplit) {
1414 targetFlags |= InputTarget::FLAG_SPLIT;
1415 }
Jeff Brown9302c872011-07-13 22:51:29 -07001416 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
Jeff Brown19dfc832010-10-05 12:26:23 -07001417 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1418 }
1419
Jeff Browna032cc02011-03-07 16:56:21 -08001420 // Update hover state.
1421 if (isHoverAction) {
Jeff Brown9302c872011-07-13 22:51:29 -07001422 newHoverWindowHandle = newTouchedWindowHandle;
Jeff Browna032cc02011-03-07 16:56:21 -08001423
1424 // Ensure all subsequent motion samples are also within the touched window.
1425 // Set *outSplitBatchAfterSample to the sample before the first one that is not
1426 // within the touched window.
1427 if (!isTouchModal) {
1428 while (sample->next) {
Jeff Browncc4f7db2011-08-30 20:34:48 -07001429 if (!newHoverWindowHandle->getInfo()->touchableRegionContainsPoint(
Jeff Browna032cc02011-03-07 16:56:21 -08001430 sample->next->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X),
1431 sample->next->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y))) {
1432 *outSplitBatchAfterSample = sample;
1433 break;
1434 }
1435 sample = sample->next;
1436 }
1437 }
1438 } else if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
Jeff Brown9302c872011-07-13 22:51:29 -07001439 newHoverWindowHandle = mLastHoverWindowHandle;
Jeff Browna032cc02011-03-07 16:56:21 -08001440 }
1441
Jeff Brown01ce2e92010-09-26 22:20:12 -07001442 // Update the temporary touch state.
1443 BitSet32 pointerIds;
1444 if (isSplit) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07001445 uint32_t pointerId = entry->pointerProperties[pointerIndex].id;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001446 pointerIds.markBit(pointerId);
Jeff Brownb88102f2010-09-08 11:49:43 -07001447 }
Jeff Brown9302c872011-07-13 22:51:29 -07001448 mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Jeff Brownb88102f2010-09-08 11:49:43 -07001449 } else {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001450 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
Jeff Brownb88102f2010-09-08 11:49:43 -07001451
1452 // If the pointer is not currently down, then ignore the event.
Jeff Brown01ce2e92010-09-26 22:20:12 -07001453 if (! mTempTouchState.down) {
Jeff Browna2cc28d2011-03-25 11:58:46 -07001454#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001455 ALOGD("Dropping event because the pointer is not down or we previously "
Jeff Brown76860e32010-10-25 17:37:46 -07001456 "dropped the pointer down event.");
1457#endif
Jeff Brownb88102f2010-09-08 11:49:43 -07001458 injectionResult = INPUT_EVENT_INJECTION_FAILED;
Jeff Brownb88102f2010-09-08 11:49:43 -07001459 goto Failed;
1460 }
Jeff Brown98db5fa2011-06-08 15:37:10 -07001461
1462 // Check whether touches should slip outside of the current foreground window.
1463 if (maskedAction == AMOTION_EVENT_ACTION_MOVE
1464 && entry->pointerCount == 1
1465 && mTempTouchState.isSlippery()) {
1466 const MotionSample* sample = &entry->firstSample;
1467 int32_t x = int32_t(sample->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
1468 int32_t y = int32_t(sample->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
1469
Jeff Brown9302c872011-07-13 22:51:29 -07001470 sp<InputWindowHandle> oldTouchedWindowHandle =
1471 mTempTouchState.getFirstForegroundWindowHandle();
1472 sp<InputWindowHandle> newTouchedWindowHandle = findTouchedWindowAtLocked(x, y);
1473 if (oldTouchedWindowHandle != newTouchedWindowHandle
1474 && newTouchedWindowHandle != NULL) {
Jeff Brown98db5fa2011-06-08 15:37:10 -07001475#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001476 ALOGD("Touch is slipping out of window %s into window %s.",
Jeff Browncc4f7db2011-08-30 20:34:48 -07001477 oldTouchedWindowHandle->getName().string(),
1478 newTouchedWindowHandle->getName().string());
Jeff Brown98db5fa2011-06-08 15:37:10 -07001479#endif
1480 // Make a slippery exit from the old window.
Jeff Brown9302c872011-07-13 22:51:29 -07001481 mTempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
Jeff Brown98db5fa2011-06-08 15:37:10 -07001482 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT, BitSet32(0));
1483
1484 // Make a slippery entrance into the new window.
Jeff Browncc4f7db2011-08-30 20:34:48 -07001485 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Jeff Brown98db5fa2011-06-08 15:37:10 -07001486 isSplit = true;
1487 }
1488
1489 int32_t targetFlags = InputTarget::FLAG_FOREGROUND
1490 | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
1491 if (isSplit) {
1492 targetFlags |= InputTarget::FLAG_SPLIT;
1493 }
Jeff Brown9302c872011-07-13 22:51:29 -07001494 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
Jeff Brown98db5fa2011-06-08 15:37:10 -07001495 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1496 }
1497
1498 BitSet32 pointerIds;
1499 if (isSplit) {
1500 pointerIds.markBit(entry->pointerProperties[0].id);
1501 }
Jeff Brown9302c872011-07-13 22:51:29 -07001502 mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Jeff Brown98db5fa2011-06-08 15:37:10 -07001503
1504 // Split the batch here so we send exactly one sample.
1505 *outSplitBatchAfterSample = &entry->firstSample;
1506 }
1507 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001508 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001509
Jeff Brown9302c872011-07-13 22:51:29 -07001510 if (newHoverWindowHandle != mLastHoverWindowHandle) {
Jeff Browna032cc02011-03-07 16:56:21 -08001511 // Split the batch here so we send exactly one sample as part of ENTER or EXIT.
1512 *outSplitBatchAfterSample = &entry->firstSample;
1513
1514 // Let the previous window know that the hover sequence is over.
Jeff Brown9302c872011-07-13 22:51:29 -07001515 if (mLastHoverWindowHandle != NULL) {
Jeff Browna032cc02011-03-07 16:56:21 -08001516#if DEBUG_HOVER
Steve Block5baa3a62011-12-20 16:23:08 +00001517 ALOGD("Sending hover exit event to window %s.",
Jeff Browncc4f7db2011-08-30 20:34:48 -07001518 mLastHoverWindowHandle->getName().string());
Jeff Browna032cc02011-03-07 16:56:21 -08001519#endif
Jeff Brown9302c872011-07-13 22:51:29 -07001520 mTempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
Jeff Browna032cc02011-03-07 16:56:21 -08001521 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
1522 }
1523
1524 // Let the new window know that the hover sequence is starting.
Jeff Brown9302c872011-07-13 22:51:29 -07001525 if (newHoverWindowHandle != NULL) {
Jeff Browna032cc02011-03-07 16:56:21 -08001526#if DEBUG_HOVER
Steve Block5baa3a62011-12-20 16:23:08 +00001527 ALOGD("Sending hover enter event to window %s.",
Jeff Browncc4f7db2011-08-30 20:34:48 -07001528 newHoverWindowHandle->getName().string());
Jeff Browna032cc02011-03-07 16:56:21 -08001529#endif
Jeff Brown9302c872011-07-13 22:51:29 -07001530 mTempTouchState.addOrUpdateWindow(newHoverWindowHandle,
Jeff Browna032cc02011-03-07 16:56:21 -08001531 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER, BitSet32(0));
1532 }
1533 }
1534
Jeff Brown01ce2e92010-09-26 22:20:12 -07001535 // Check permission to inject into all touched foreground windows and ensure there
1536 // is at least one touched foreground window.
1537 {
1538 bool haveForegroundWindow = false;
1539 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1540 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1541 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1542 haveForegroundWindow = true;
Jeff Brown9302c872011-07-13 22:51:29 -07001543 if (! checkInjectionPermission(touchedWindow.windowHandle,
1544 entry->injectionState)) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001545 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1546 injectionPermission = INJECTION_PERMISSION_DENIED;
1547 goto Failed;
1548 }
1549 }
1550 }
1551 if (! haveForegroundWindow) {
Jeff Browna2cc28d2011-03-25 11:58:46 -07001552#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001553 ALOGD("Dropping event because there is no touched foreground window to receive it.");
Jeff Brownb88102f2010-09-08 11:49:43 -07001554#endif
1555 injectionResult = INPUT_EVENT_INJECTION_FAILED;
Jeff Brownb88102f2010-09-08 11:49:43 -07001556 goto Failed;
1557 }
1558
Jeff Brown01ce2e92010-09-26 22:20:12 -07001559 // Permission granted to injection into all touched foreground windows.
1560 injectionPermission = INJECTION_PERMISSION_GRANTED;
1561 }
Jeff Brown519e0242010-09-15 15:18:56 -07001562
Kenny Root7a9db182011-06-02 15:16:05 -07001563 // Check whether windows listening for outside touches are owned by the same UID. If it is
1564 // set the policy flag that we will not reveal coordinate information to this window.
1565 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
Jeff Brown9302c872011-07-13 22:51:29 -07001566 sp<InputWindowHandle> foregroundWindowHandle =
1567 mTempTouchState.getFirstForegroundWindowHandle();
Jeff Browncc4f7db2011-08-30 20:34:48 -07001568 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Kenny Root7a9db182011-06-02 15:16:05 -07001569 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1570 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1571 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
Jeff Brown9302c872011-07-13 22:51:29 -07001572 sp<InputWindowHandle> inputWindowHandle = touchedWindow.windowHandle;
Jeff Browncc4f7db2011-08-30 20:34:48 -07001573 if (inputWindowHandle->getInfo()->ownerUid != foregroundWindowUid) {
Jeff Brown9302c872011-07-13 22:51:29 -07001574 mTempTouchState.addOrUpdateWindow(inputWindowHandle,
Kenny Root7a9db182011-06-02 15:16:05 -07001575 InputTarget::FLAG_ZERO_COORDS, BitSet32(0));
1576 }
1577 }
1578 }
1579 }
1580
Jeff Brown01ce2e92010-09-26 22:20:12 -07001581 // Ensure all touched foreground windows are ready for new input.
1582 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1583 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1584 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1585 // If the touched window is paused then keep waiting.
Jeff Browncc4f7db2011-08-30 20:34:48 -07001586 if (touchedWindow.windowHandle->getInfo()->paused) {
Jeff Browna2cc28d2011-03-25 11:58:46 -07001587#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001588 ALOGD("Waiting because touched window is paused.");
Jeff Brown519e0242010-09-15 15:18:56 -07001589#endif
Jeff Brown01ce2e92010-09-26 22:20:12 -07001590 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brown9302c872011-07-13 22:51:29 -07001591 NULL, touchedWindow.windowHandle, nextWakeupTime);
Jeff Brown01ce2e92010-09-26 22:20:12 -07001592 goto Unresponsive;
1593 }
1594
1595 // If the touched window is still working on previous events then keep waiting.
Jeff Brown9302c872011-07-13 22:51:29 -07001596 if (! isWindowFinishedWithPreviousInputLocked(touchedWindow.windowHandle)) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001597#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001598 ALOGD("Waiting because touched window still processing previous input.");
Jeff Brown01ce2e92010-09-26 22:20:12 -07001599#endif
1600 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brown9302c872011-07-13 22:51:29 -07001601 NULL, touchedWindow.windowHandle, nextWakeupTime);
Jeff Brown01ce2e92010-09-26 22:20:12 -07001602 goto Unresponsive;
1603 }
1604 }
1605 }
1606
1607 // If this is the first pointer going down and the touched window has a wallpaper
1608 // then also add the touched wallpaper windows so they are locked in for the duration
1609 // of the touch gesture.
Jeff Brown33bbfd22011-02-24 20:55:35 -08001610 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
1611 // engine only supports touch events. We would need to add a mechanism similar
1612 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
1613 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
Jeff Brown9302c872011-07-13 22:51:29 -07001614 sp<InputWindowHandle> foregroundWindowHandle =
1615 mTempTouchState.getFirstForegroundWindowHandle();
Jeff Browncc4f7db2011-08-30 20:34:48 -07001616 if (foregroundWindowHandle->getInfo()->hasWallpaper) {
Jeff Brown9302c872011-07-13 22:51:29 -07001617 for (size_t i = 0; i < mWindowHandles.size(); i++) {
1618 sp<InputWindowHandle> windowHandle = mWindowHandles.itemAt(i);
Jeff Browncc4f7db2011-08-30 20:34:48 -07001619 if (windowHandle->getInfo()->layoutParamsType
1620 == InputWindowInfo::TYPE_WALLPAPER) {
Jeff Brown9302c872011-07-13 22:51:29 -07001621 mTempTouchState.addOrUpdateWindow(windowHandle,
Jeff Browna032cc02011-03-07 16:56:21 -08001622 InputTarget::FLAG_WINDOW_IS_OBSCURED
1623 | InputTarget::FLAG_DISPATCH_AS_IS,
1624 BitSet32(0));
Jeff Brown01ce2e92010-09-26 22:20:12 -07001625 }
1626 }
1627 }
1628 }
1629
Jeff Brownb88102f2010-09-08 11:49:43 -07001630 // Success! Output targets.
1631 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
Jeff Brownb88102f2010-09-08 11:49:43 -07001632
Jeff Brown01ce2e92010-09-26 22:20:12 -07001633 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1634 const TouchedWindow& touchedWindow = mTempTouchState.windows.itemAt(i);
Jeff Brown9302c872011-07-13 22:51:29 -07001635 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Jeff Brown01ce2e92010-09-26 22:20:12 -07001636 touchedWindow.pointerIds);
Jeff Brownb88102f2010-09-08 11:49:43 -07001637 }
1638
Jeff Browna032cc02011-03-07 16:56:21 -08001639 // Drop the outside or hover touch windows since we will not care about them
1640 // in the next iteration.
1641 mTempTouchState.filterNonAsIsTouchWindows();
Jeff Brown01ce2e92010-09-26 22:20:12 -07001642
Jeff Brownb88102f2010-09-08 11:49:43 -07001643Failed:
1644 // Check injection permission once and for all.
1645 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001646 if (checkInjectionPermission(NULL, entry->injectionState)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001647 injectionPermission = INJECTION_PERMISSION_GRANTED;
1648 } else {
1649 injectionPermission = INJECTION_PERMISSION_DENIED;
1650 }
1651 }
1652
1653 // Update final pieces of touch state if the injector had permission.
1654 if (injectionPermission == INJECTION_PERMISSION_GRANTED) {
Jeff Brown95712852011-01-04 19:41:59 -08001655 if (!wrongDevice) {
Jeff Brown81346812011-06-28 20:08:48 -07001656 if (switchedDevice) {
1657#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001658 ALOGD("Conflicting pointer actions: Switched to a different device.");
Jeff Brown81346812011-06-28 20:08:48 -07001659#endif
1660 *outConflictingPointerActions = true;
1661 }
1662
1663 if (isHoverAction) {
1664 // Started hovering, therefore no longer down.
1665 if (mTouchState.down) {
1666#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001667 ALOGD("Conflicting pointer actions: Hover received while pointer was down.");
Jeff Brown81346812011-06-28 20:08:48 -07001668#endif
1669 *outConflictingPointerActions = true;
1670 }
1671 mTouchState.reset();
1672 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER
1673 || maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
1674 mTouchState.deviceId = entry->deviceId;
1675 mTouchState.source = entry->source;
1676 }
1677 } else if (maskedAction == AMOTION_EVENT_ACTION_UP
1678 || maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Jeff Brown95712852011-01-04 19:41:59 -08001679 // All pointers up or canceled.
Jeff Brown33bbfd22011-02-24 20:55:35 -08001680 mTouchState.reset();
Jeff Brown95712852011-01-04 19:41:59 -08001681 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1682 // First pointer went down.
1683 if (mTouchState.down) {
Jeff Brownb6997262010-10-08 22:31:17 -07001684#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001685 ALOGD("Conflicting pointer actions: Down received while already down.");
Jeff Brownb6997262010-10-08 22:31:17 -07001686#endif
Jeff Brown81346812011-06-28 20:08:48 -07001687 *outConflictingPointerActions = true;
Jeff Brown95712852011-01-04 19:41:59 -08001688 }
Jeff Brown33bbfd22011-02-24 20:55:35 -08001689 mTouchState.copyFrom(mTempTouchState);
Jeff Brown95712852011-01-04 19:41:59 -08001690 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
1691 // One pointer went up.
1692 if (isSplit) {
1693 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07001694 uint32_t pointerId = entry->pointerProperties[pointerIndex].id;
Jeff Brownb88102f2010-09-08 11:49:43 -07001695
Jeff Brown95712852011-01-04 19:41:59 -08001696 for (size_t i = 0; i < mTempTouchState.windows.size(); ) {
1697 TouchedWindow& touchedWindow = mTempTouchState.windows.editItemAt(i);
1698 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
1699 touchedWindow.pointerIds.clearBit(pointerId);
1700 if (touchedWindow.pointerIds.isEmpty()) {
1701 mTempTouchState.windows.removeAt(i);
1702 continue;
1703 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001704 }
Jeff Brown95712852011-01-04 19:41:59 -08001705 i += 1;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001706 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001707 }
Jeff Brown33bbfd22011-02-24 20:55:35 -08001708 mTouchState.copyFrom(mTempTouchState);
1709 } else if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
1710 // Discard temporary touch state since it was only valid for this action.
1711 } else {
1712 // Save changes to touch state as-is for all other actions.
1713 mTouchState.copyFrom(mTempTouchState);
Jeff Brownb88102f2010-09-08 11:49:43 -07001714 }
Jeff Browna032cc02011-03-07 16:56:21 -08001715
1716 // Update hover state.
Jeff Brown9302c872011-07-13 22:51:29 -07001717 mLastHoverWindowHandle = newHoverWindowHandle;
Jeff Brown95712852011-01-04 19:41:59 -08001718 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001719 } else {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001720#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001721 ALOGD("Not updating touch focus because injection was denied.");
Jeff Brown01ce2e92010-09-26 22:20:12 -07001722#endif
Jeff Brownb88102f2010-09-08 11:49:43 -07001723 }
1724
1725Unresponsive:
Jeff Brown120a4592010-10-27 18:43:51 -07001726 // Reset temporary touch state to ensure we release unnecessary references to input channels.
1727 mTempTouchState.reset();
1728
Jeff Brown519e0242010-09-15 15:18:56 -07001729 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
1730 updateDispatchStatisticsLocked(currentTime, entry,
1731 injectionResult, timeSpentWaitingForApplication);
Jeff Brownb88102f2010-09-08 11:49:43 -07001732#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001733 ALOGD("findTouchedWindow finished: injectionResult=%d, injectionPermission=%d, "
Jeff Brown01ce2e92010-09-26 22:20:12 -07001734 "timeSpentWaitingForApplication=%0.1fms",
Jeff Brown519e0242010-09-15 15:18:56 -07001735 injectionResult, injectionPermission, timeSpentWaitingForApplication / 1000000.0);
Jeff Brownb88102f2010-09-08 11:49:43 -07001736#endif
1737 return injectionResult;
1738}
1739
Jeff Brown9302c872011-07-13 22:51:29 -07001740void InputDispatcher::addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
1741 int32_t targetFlags, BitSet32 pointerIds) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001742 mCurrentInputTargets.push();
1743
Jeff Browncc4f7db2011-08-30 20:34:48 -07001744 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Jeff Brownb88102f2010-09-08 11:49:43 -07001745 InputTarget& target = mCurrentInputTargets.editTop();
Jeff Browncc4f7db2011-08-30 20:34:48 -07001746 target.inputChannel = windowInfo->inputChannel;
Jeff Brownb88102f2010-09-08 11:49:43 -07001747 target.flags = targetFlags;
Jeff Browncc4f7db2011-08-30 20:34:48 -07001748 target.xOffset = - windowInfo->frameLeft;
1749 target.yOffset = - windowInfo->frameTop;
1750 target.scaleFactor = windowInfo->scaleFactor;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001751 target.pointerIds = pointerIds;
Jeff Brownb88102f2010-09-08 11:49:43 -07001752}
1753
1754void InputDispatcher::addMonitoringTargetsLocked() {
1755 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
1756 mCurrentInputTargets.push();
1757
1758 InputTarget& target = mCurrentInputTargets.editTop();
1759 target.inputChannel = mMonitoringChannels[i];
Jeff Brownb6110c22011-04-01 16:15:13 -07001760 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
Jeff Brownb88102f2010-09-08 11:49:43 -07001761 target.xOffset = 0;
1762 target.yOffset = 0;
Jeff Brownb6110c22011-04-01 16:15:13 -07001763 target.pointerIds.clear();
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001764 target.scaleFactor = 1.0f;
Jeff Brownb88102f2010-09-08 11:49:43 -07001765 }
1766}
1767
Jeff Brown9302c872011-07-13 22:51:29 -07001768bool InputDispatcher::checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
Jeff Brown01ce2e92010-09-26 22:20:12 -07001769 const InjectionState* injectionState) {
1770 if (injectionState
Jeff Browncc4f7db2011-08-30 20:34:48 -07001771 && (windowHandle == NULL
1772 || windowHandle->getInfo()->ownerUid != injectionState->injectorUid)
Jeff Brownb6997262010-10-08 22:31:17 -07001773 && !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Jeff Brown9302c872011-07-13 22:51:29 -07001774 if (windowHandle != NULL) {
Steve Block8564c8d2012-01-05 23:22:43 +00001775 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
Jeff Brown9302c872011-07-13 22:51:29 -07001776 "owned by uid %d",
Jeff Brownb6997262010-10-08 22:31:17 -07001777 injectionState->injectorPid, injectionState->injectorUid,
Jeff Browncc4f7db2011-08-30 20:34:48 -07001778 windowHandle->getName().string(),
1779 windowHandle->getInfo()->ownerUid);
Jeff Brownb6997262010-10-08 22:31:17 -07001780 } else {
Steve Block8564c8d2012-01-05 23:22:43 +00001781 ALOGW("Permission denied: injecting event from pid %d uid %d",
Jeff Brownb6997262010-10-08 22:31:17 -07001782 injectionState->injectorPid, injectionState->injectorUid);
Jeff Brownb88102f2010-09-08 11:49:43 -07001783 }
Jeff Brownb6997262010-10-08 22:31:17 -07001784 return false;
Jeff Brownb88102f2010-09-08 11:49:43 -07001785 }
1786 return true;
1787}
1788
Jeff Brown19dfc832010-10-05 12:26:23 -07001789bool InputDispatcher::isWindowObscuredAtPointLocked(
Jeff Brown9302c872011-07-13 22:51:29 -07001790 const sp<InputWindowHandle>& windowHandle, int32_t x, int32_t y) const {
1791 size_t numWindows = mWindowHandles.size();
Jeff Brownb88102f2010-09-08 11:49:43 -07001792 for (size_t i = 0; i < numWindows; i++) {
Jeff Brown9302c872011-07-13 22:51:29 -07001793 sp<InputWindowHandle> otherHandle = mWindowHandles.itemAt(i);
1794 if (otherHandle == windowHandle) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001795 break;
1796 }
Jeff Browncc4f7db2011-08-30 20:34:48 -07001797
1798 const InputWindowInfo* otherInfo = otherHandle->getInfo();
1799 if (otherInfo->visible && ! otherInfo->isTrustedOverlay()
1800 && otherInfo->frameContainsPoint(x, y)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001801 return true;
1802 }
1803 }
1804 return false;
1805}
1806
Jeff Brown9302c872011-07-13 22:51:29 -07001807bool InputDispatcher::isWindowFinishedWithPreviousInputLocked(
1808 const sp<InputWindowHandle>& windowHandle) {
Jeff Browncc4f7db2011-08-30 20:34:48 -07001809 ssize_t connectionIndex = getConnectionIndexLocked(windowHandle->getInputChannel());
Jeff Brown519e0242010-09-15 15:18:56 -07001810 if (connectionIndex >= 0) {
1811 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
1812 return connection->outboundQueue.isEmpty();
1813 } else {
1814 return true;
1815 }
1816}
1817
Jeff Brown9302c872011-07-13 22:51:29 -07001818String8 InputDispatcher::getApplicationWindowLabelLocked(
1819 const sp<InputApplicationHandle>& applicationHandle,
1820 const sp<InputWindowHandle>& windowHandle) {
1821 if (applicationHandle != NULL) {
1822 if (windowHandle != NULL) {
Jeff Browncc4f7db2011-08-30 20:34:48 -07001823 String8 label(applicationHandle->getName());
Jeff Brown519e0242010-09-15 15:18:56 -07001824 label.append(" - ");
Jeff Browncc4f7db2011-08-30 20:34:48 -07001825 label.append(windowHandle->getName());
Jeff Brown519e0242010-09-15 15:18:56 -07001826 return label;
1827 } else {
Jeff Browncc4f7db2011-08-30 20:34:48 -07001828 return applicationHandle->getName();
Jeff Brown519e0242010-09-15 15:18:56 -07001829 }
Jeff Brown9302c872011-07-13 22:51:29 -07001830 } else if (windowHandle != NULL) {
Jeff Browncc4f7db2011-08-30 20:34:48 -07001831 return windowHandle->getName();
Jeff Brown519e0242010-09-15 15:18:56 -07001832 } else {
1833 return String8("<unknown application or window>");
1834 }
1835}
1836
Jeff Browne2fe69e2010-10-18 13:21:23 -07001837void InputDispatcher::pokeUserActivityLocked(const EventEntry* eventEntry) {
Jeff Brown56194eb2011-03-02 19:23:13 -08001838 int32_t eventType = POWER_MANAGER_OTHER_EVENT;
Jeff Brown4d396052010-10-29 21:50:21 -07001839 switch (eventEntry->type) {
1840 case EventEntry::TYPE_MOTION: {
Jeff Browne2fe69e2010-10-18 13:21:23 -07001841 const MotionEntry* motionEntry = static_cast<const MotionEntry*>(eventEntry);
Jeff Brown4d396052010-10-29 21:50:21 -07001842 if (motionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
1843 return;
1844 }
1845
Jeff Brown56194eb2011-03-02 19:23:13 -08001846 if (MotionEvent::isTouchEvent(motionEntry->source, motionEntry->action)) {
Joe Onorato1a542c72010-11-08 09:48:20 -08001847 eventType = POWER_MANAGER_TOUCH_EVENT;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001848 }
Jeff Brown4d396052010-10-29 21:50:21 -07001849 break;
1850 }
1851 case EventEntry::TYPE_KEY: {
1852 const KeyEntry* keyEntry = static_cast<const KeyEntry*>(eventEntry);
1853 if (keyEntry->flags & AKEY_EVENT_FLAG_CANCELED) {
1854 return;
1855 }
Jeff Brown56194eb2011-03-02 19:23:13 -08001856 eventType = POWER_MANAGER_BUTTON_EVENT;
Jeff Brown4d396052010-10-29 21:50:21 -07001857 break;
1858 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001859 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001860
Jeff Brownb88102f2010-09-08 11:49:43 -07001861 CommandEntry* commandEntry = postCommandLocked(
1862 & InputDispatcher::doPokeUserActivityLockedInterruptible);
Jeff Browne2fe69e2010-10-18 13:21:23 -07001863 commandEntry->eventTime = eventEntry->eventTime;
Jeff Brownb88102f2010-09-08 11:49:43 -07001864 commandEntry->userActivityEventType = eventType;
1865}
1866
Jeff Brown7fbdc842010-06-17 20:52:56 -07001867void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
1868 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget,
Jeff Brown46b9ac02010-04-22 18:58:52 -07001869 bool resumeWithAppendedMotionSample) {
1870#if DEBUG_DISPATCH_CYCLE
Steve Block5baa3a62011-12-20 16:23:08 +00001871 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
Jeff Brown9cc695c2011-08-23 18:35:04 -07001872 "xOffset=%f, yOffset=%f, scaleFactor=%f, "
Jeff Brown83c09682010-12-23 17:50:18 -08001873 "pointerIds=0x%x, "
Jeff Brown01ce2e92010-09-26 22:20:12 -07001874 "resumeWithAppendedMotionSample=%s",
Jeff Brown519e0242010-09-15 15:18:56 -07001875 connection->getInputChannelName(), inputTarget->flags,
Jeff Brown46b9ac02010-04-22 18:58:52 -07001876 inputTarget->xOffset, inputTarget->yOffset,
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001877 inputTarget->scaleFactor, inputTarget->pointerIds.value,
Jeff Brownb88102f2010-09-08 11:49:43 -07001878 toString(resumeWithAppendedMotionSample));
Jeff Brown46b9ac02010-04-22 18:58:52 -07001879#endif
1880
Jeff Brown01ce2e92010-09-26 22:20:12 -07001881 // Make sure we are never called for streaming when splitting across multiple windows.
1882 bool isSplit = inputTarget->flags & InputTarget::FLAG_SPLIT;
Steve Blockec193de2012-01-09 18:35:44 +00001883 ALOG_ASSERT(! (resumeWithAppendedMotionSample && isSplit));
Jeff Brown01ce2e92010-09-26 22:20:12 -07001884
Jeff Brown46b9ac02010-04-22 18:58:52 -07001885 // Skip this event if the connection status is not normal.
Jeff Brown519e0242010-09-15 15:18:56 -07001886 // We don't want to enqueue additional outbound events if the connection is broken.
Jeff Brown46b9ac02010-04-22 18:58:52 -07001887 if (connection->status != Connection::STATUS_NORMAL) {
Jeff Brownb6997262010-10-08 22:31:17 -07001888#if DEBUG_DISPATCH_CYCLE
Steve Block5baa3a62011-12-20 16:23:08 +00001889 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Jeff Brownb88102f2010-09-08 11:49:43 -07001890 connection->getInputChannelName(), connection->getStatusLabel());
Jeff Brownb6997262010-10-08 22:31:17 -07001891#endif
Jeff Brown46b9ac02010-04-22 18:58:52 -07001892 return;
1893 }
1894
Jeff Brown01ce2e92010-09-26 22:20:12 -07001895 // Split a motion event if needed.
1896 if (isSplit) {
Steve Blockec193de2012-01-09 18:35:44 +00001897 ALOG_ASSERT(eventEntry->type == EventEntry::TYPE_MOTION);
Jeff Brown01ce2e92010-09-26 22:20:12 -07001898
1899 MotionEntry* originalMotionEntry = static_cast<MotionEntry*>(eventEntry);
1900 if (inputTarget->pointerIds.count() != originalMotionEntry->pointerCount) {
1901 MotionEntry* splitMotionEntry = splitMotionEvent(
1902 originalMotionEntry, inputTarget->pointerIds);
Jeff Brown58a2da82011-01-25 16:02:22 -08001903 if (!splitMotionEntry) {
1904 return; // split event was dropped
1905 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001906#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001907 ALOGD("channel '%s' ~ Split motion event.",
Jeff Brown01ce2e92010-09-26 22:20:12 -07001908 connection->getInputChannelName());
1909 logOutboundMotionDetailsLocked(" ", splitMotionEntry);
1910#endif
Jeff Brownc0cb3dc2012-01-12 18:30:12 -08001911 enqueueDispatchEntriesLocked(currentTime, connection,
1912 splitMotionEntry, inputTarget, resumeWithAppendedMotionSample);
1913 splitMotionEntry->release();
1914 return;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001915 }
1916 }
1917
Jeff Brownc0cb3dc2012-01-12 18:30:12 -08001918 // Not splitting. Enqueue dispatch entries for the event as is.
1919 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget,
1920 resumeWithAppendedMotionSample);
1921}
1922
1923void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
1924 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget,
1925 bool resumeWithAppendedMotionSample) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07001926 // Resume the dispatch cycle with a freshly appended motion sample.
1927 // First we check that the last dispatch entry in the outbound queue is for the same
1928 // motion event to which we appended the motion sample. If we find such a dispatch
1929 // entry, and if it is currently in progress then we try to stream the new sample.
1930 bool wasEmpty = connection->outboundQueue.isEmpty();
1931
1932 if (! wasEmpty && resumeWithAppendedMotionSample) {
1933 DispatchEntry* motionEventDispatchEntry =
1934 connection->findQueuedDispatchEntryForEvent(eventEntry);
1935 if (motionEventDispatchEntry) {
1936 // If the dispatch entry is not in progress, then we must be busy dispatching an
1937 // earlier event. Not a problem, the motion event is on the outbound queue and will
1938 // be dispatched later.
1939 if (! motionEventDispatchEntry->inProgress) {
1940#if DEBUG_BATCHING
Steve Block5baa3a62011-12-20 16:23:08 +00001941 ALOGD("channel '%s' ~ Not streaming because the motion event has "
Jeff Brown46b9ac02010-04-22 18:58:52 -07001942 "not yet been dispatched. "
1943 "(Waiting for earlier events to be consumed.)",
1944 connection->getInputChannelName());
1945#endif
1946 return;
1947 }
1948
1949 // If the dispatch entry is in progress but it already has a tail of pending
1950 // motion samples, then it must mean that the shared memory buffer filled up.
1951 // Not a problem, when this dispatch cycle is finished, we will eventually start
1952 // a new dispatch cycle to process the tail and that tail includes the newly
1953 // appended motion sample.
1954 if (motionEventDispatchEntry->tailMotionSample) {
1955#if DEBUG_BATCHING
Steve Block5baa3a62011-12-20 16:23:08 +00001956 ALOGD("channel '%s' ~ Not streaming because no new samples can "
Jeff Brown46b9ac02010-04-22 18:58:52 -07001957 "be appended to the motion event in this dispatch cycle. "
1958 "(Waiting for next dispatch cycle to start.)",
1959 connection->getInputChannelName());
1960#endif
1961 return;
1962 }
1963
Jeff Brown81346812011-06-28 20:08:48 -07001964 // If the motion event was modified in flight, then we cannot stream the sample.
1965 if ((motionEventDispatchEntry->targetFlags & InputTarget::FLAG_DISPATCH_MASK)
1966 != InputTarget::FLAG_DISPATCH_AS_IS) {
1967#if DEBUG_BATCHING
Steve Block5baa3a62011-12-20 16:23:08 +00001968 ALOGD("channel '%s' ~ Not streaming because the motion event was not "
Jeff Brown81346812011-06-28 20:08:48 -07001969 "being dispatched as-is. "
1970 "(Waiting for next dispatch cycle to start.)",
1971 connection->getInputChannelName());
1972#endif
1973 return;
1974 }
1975
Jeff Brown46b9ac02010-04-22 18:58:52 -07001976 // The dispatch entry is in progress and is still potentially open for streaming.
1977 // Try to stream the new motion sample. This might fail if the consumer has already
1978 // consumed the motion event (or if the channel is broken).
Jeff Brown01ce2e92010-09-26 22:20:12 -07001979 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
1980 MotionSample* appendedMotionSample = motionEntry->lastSample;
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001981 status_t status;
1982 if (motionEventDispatchEntry->scaleFactor == 1.0f) {
1983 status = connection->inputPublisher.appendMotionSample(
1984 appendedMotionSample->eventTime, appendedMotionSample->pointerCoords);
1985 } else {
1986 PointerCoords scaledCoords[MAX_POINTERS];
1987 for (size_t i = 0; i < motionEntry->pointerCount; i++) {
1988 scaledCoords[i] = appendedMotionSample->pointerCoords[i];
1989 scaledCoords[i].scale(motionEventDispatchEntry->scaleFactor);
1990 }
1991 status = connection->inputPublisher.appendMotionSample(
1992 appendedMotionSample->eventTime, scaledCoords);
1993 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07001994 if (status == OK) {
1995#if DEBUG_BATCHING
Steve Block5baa3a62011-12-20 16:23:08 +00001996 ALOGD("channel '%s' ~ Successfully streamed new motion sample.",
Jeff Brown46b9ac02010-04-22 18:58:52 -07001997 connection->getInputChannelName());
1998#endif
1999 return;
2000 }
2001
2002#if DEBUG_BATCHING
2003 if (status == NO_MEMORY) {
Steve Block5baa3a62011-12-20 16:23:08 +00002004 ALOGD("channel '%s' ~ Could not append motion sample to currently "
Jeff Brown46b9ac02010-04-22 18:58:52 -07002005 "dispatched move event because the shared memory buffer is full. "
2006 "(Waiting for next dispatch cycle to start.)",
2007 connection->getInputChannelName());
2008 } else if (status == status_t(FAILED_TRANSACTION)) {
Steve Block5baa3a62011-12-20 16:23:08 +00002009 ALOGD("channel '%s' ~ Could not append motion sample to currently "
Jeff Brown349703e2010-06-22 01:27:15 -07002010 "dispatched move event because the event has already been consumed. "
Jeff Brown46b9ac02010-04-22 18:58:52 -07002011 "(Waiting for next dispatch cycle to start.)",
2012 connection->getInputChannelName());
2013 } else {
Steve Block5baa3a62011-12-20 16:23:08 +00002014 ALOGD("channel '%s' ~ Could not append motion sample to currently "
Jeff Brown46b9ac02010-04-22 18:58:52 -07002015 "dispatched move event due to an error, status=%d. "
2016 "(Waiting for next dispatch cycle to start.)",
2017 connection->getInputChannelName(), status);
2018 }
2019#endif
2020 // Failed to stream. Start a new tail of pending motion samples to dispatch
2021 // in the next cycle.
2022 motionEventDispatchEntry->tailMotionSample = appendedMotionSample;
2023 return;
2024 }
2025 }
2026
Jeff Browna032cc02011-03-07 16:56:21 -08002027 // Enqueue dispatch entries for the requested modes.
2028 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
2029 resumeWithAppendedMotionSample, InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
2030 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
2031 resumeWithAppendedMotionSample, InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
2032 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
2033 resumeWithAppendedMotionSample, InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
2034 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
2035 resumeWithAppendedMotionSample, InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brown98db5fa2011-06-08 15:37:10 -07002036 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
2037 resumeWithAppendedMotionSample, InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
2038 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
2039 resumeWithAppendedMotionSample, InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Jeff Browna032cc02011-03-07 16:56:21 -08002040
2041 // If the outbound queue was previously empty, start the dispatch cycle going.
Jeff Brownb6110c22011-04-01 16:15:13 -07002042 if (wasEmpty && !connection->outboundQueue.isEmpty()) {
Jeff Browna032cc02011-03-07 16:56:21 -08002043 activateConnectionLocked(connection.get());
2044 startDispatchCycleLocked(currentTime, connection);
2045 }
2046}
2047
2048void InputDispatcher::enqueueDispatchEntryLocked(
2049 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget,
2050 bool resumeWithAppendedMotionSample, int32_t dispatchMode) {
2051 int32_t inputTargetFlags = inputTarget->flags;
2052 if (!(inputTargetFlags & dispatchMode)) {
2053 return;
2054 }
2055 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
2056
Jeff Brown46b9ac02010-04-22 18:58:52 -07002057 // This is a new event.
2058 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Jeff Brownac386072011-07-20 15:19:50 -07002059 DispatchEntry* dispatchEntry = new DispatchEntry(eventEntry, // increments ref
Dianne Hackbornaa9d84c2011-05-09 19:00:59 -07002060 inputTargetFlags, inputTarget->xOffset, inputTarget->yOffset,
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002061 inputTarget->scaleFactor);
Jeff Brown6ec402b2010-07-28 15:48:59 -07002062
Jeff Brown46b9ac02010-04-22 18:58:52 -07002063 // Handle the case where we could not stream a new motion sample because the consumer has
2064 // already consumed the motion event (otherwise the corresponding dispatch entry would
2065 // still be in the outbound queue for this connection). We set the head motion sample
2066 // to the list starting with the newly appended motion sample.
2067 if (resumeWithAppendedMotionSample) {
2068#if DEBUG_BATCHING
Steve Block5baa3a62011-12-20 16:23:08 +00002069 ALOGD("channel '%s' ~ Preparing a new dispatch cycle for additional motion samples "
Jeff Brown46b9ac02010-04-22 18:58:52 -07002070 "that cannot be streamed because the motion event has already been consumed.",
2071 connection->getInputChannelName());
2072#endif
2073 MotionSample* appendedMotionSample = static_cast<MotionEntry*>(eventEntry)->lastSample;
2074 dispatchEntry->headMotionSample = appendedMotionSample;
2075 }
2076
Jeff Brown81346812011-06-28 20:08:48 -07002077 // Apply target flags and update the connection's input state.
2078 switch (eventEntry->type) {
2079 case EventEntry::TYPE_KEY: {
2080 KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
2081 dispatchEntry->resolvedAction = keyEntry->action;
2082 dispatchEntry->resolvedFlags = keyEntry->flags;
2083
2084 if (!connection->inputState.trackKey(keyEntry,
2085 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags)) {
2086#if DEBUG_DISPATCH_CYCLE
Steve Block5baa3a62011-12-20 16:23:08 +00002087 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
Jeff Brown81346812011-06-28 20:08:48 -07002088 connection->getInputChannelName());
2089#endif
Jeff Brownc0cb3dc2012-01-12 18:30:12 -08002090 delete dispatchEntry;
Jeff Brown81346812011-06-28 20:08:48 -07002091 return; // skip the inconsistent event
2092 }
2093 break;
2094 }
2095
2096 case EventEntry::TYPE_MOTION: {
2097 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
2098 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2099 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
2100 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
2101 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
2102 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
2103 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2104 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
2105 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
2106 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
2107 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
2108 } else {
2109 dispatchEntry->resolvedAction = motionEntry->action;
2110 }
2111 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE
2112 && !connection->inputState.isHovering(
2113 motionEntry->deviceId, motionEntry->source)) {
2114#if DEBUG_DISPATCH_CYCLE
Steve Block5baa3a62011-12-20 16:23:08 +00002115 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter event",
Jeff Brown81346812011-06-28 20:08:48 -07002116 connection->getInputChannelName());
2117#endif
2118 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2119 }
2120
2121 dispatchEntry->resolvedFlags = motionEntry->flags;
2122 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
2123 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
2124 }
2125
2126 if (!connection->inputState.trackMotion(motionEntry,
2127 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags)) {
2128#if DEBUG_DISPATCH_CYCLE
Steve Block5baa3a62011-12-20 16:23:08 +00002129 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion event",
Jeff Brown81346812011-06-28 20:08:48 -07002130 connection->getInputChannelName());
2131#endif
Jeff Brownc0cb3dc2012-01-12 18:30:12 -08002132 delete dispatchEntry;
Jeff Brown81346812011-06-28 20:08:48 -07002133 return; // skip the inconsistent event
2134 }
2135 break;
2136 }
2137 }
2138
Jeff Brownc0cb3dc2012-01-12 18:30:12 -08002139 // Remember that we are waiting for this dispatch to complete.
2140 if (dispatchEntry->hasForegroundTarget()) {
2141 incrementPendingForegroundDispatchesLocked(eventEntry);
2142 }
2143
Jeff Brown46b9ac02010-04-22 18:58:52 -07002144 // Enqueue the dispatch entry.
2145 connection->outboundQueue.enqueueAtTail(dispatchEntry);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002146}
2147
Jeff Brown7fbdc842010-06-17 20:52:56 -07002148void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Jeff Brown519e0242010-09-15 15:18:56 -07002149 const sp<Connection>& connection) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002150#if DEBUG_DISPATCH_CYCLE
Steve Block5baa3a62011-12-20 16:23:08 +00002151 ALOGD("channel '%s' ~ startDispatchCycle",
Jeff Brown46b9ac02010-04-22 18:58:52 -07002152 connection->getInputChannelName());
2153#endif
2154
Steve Blockec193de2012-01-09 18:35:44 +00002155 ALOG_ASSERT(connection->status == Connection::STATUS_NORMAL);
2156 ALOG_ASSERT(! connection->outboundQueue.isEmpty());
Jeff Brown46b9ac02010-04-22 18:58:52 -07002157
Jeff Brownac386072011-07-20 15:19:50 -07002158 DispatchEntry* dispatchEntry = connection->outboundQueue.head;
Steve Blockec193de2012-01-09 18:35:44 +00002159 ALOG_ASSERT(! dispatchEntry->inProgress);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002160
Jeff Brownb88102f2010-09-08 11:49:43 -07002161 // Mark the dispatch entry as in progress.
2162 dispatchEntry->inProgress = true;
2163
Jeff Brown46b9ac02010-04-22 18:58:52 -07002164 // Publish the event.
2165 status_t status;
Jeff Browna032cc02011-03-07 16:56:21 -08002166 EventEntry* eventEntry = dispatchEntry->eventEntry;
Jeff Brown01ce2e92010-09-26 22:20:12 -07002167 switch (eventEntry->type) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002168 case EventEntry::TYPE_KEY: {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002169 KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002170
Jeff Brown46b9ac02010-04-22 18:58:52 -07002171 // Publish the key event.
Jeff Brown81346812011-06-28 20:08:48 -07002172 status = connection->inputPublisher.publishKeyEvent(
2173 keyEntry->deviceId, keyEntry->source,
2174 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags,
2175 keyEntry->keyCode, keyEntry->scanCode,
Jeff Brown46b9ac02010-04-22 18:58:52 -07002176 keyEntry->metaState, keyEntry->repeatCount, keyEntry->downTime,
2177 keyEntry->eventTime);
2178
2179 if (status) {
Steve Block3762c312012-01-06 19:20:56 +00002180 ALOGE("channel '%s' ~ Could not publish key event, "
Jeff Brown46b9ac02010-04-22 18:58:52 -07002181 "status=%d", connection->getInputChannelName(), status);
Jeff Browncc4f7db2011-08-30 20:34:48 -07002182 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002183 return;
2184 }
2185 break;
2186 }
2187
2188 case EventEntry::TYPE_MOTION: {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002189 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002190
Jeff Brown46b9ac02010-04-22 18:58:52 -07002191 // If headMotionSample is non-NULL, then it points to the first new sample that we
2192 // were unable to dispatch during the previous cycle so we resume dispatching from
2193 // that point in the list of motion samples.
2194 // Otherwise, we just start from the first sample of the motion event.
2195 MotionSample* firstMotionSample = dispatchEntry->headMotionSample;
2196 if (! firstMotionSample) {
2197 firstMotionSample = & motionEntry->firstSample;
2198 }
2199
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002200 PointerCoords scaledCoords[MAX_POINTERS];
2201 const PointerCoords* usingCoords = firstMotionSample->pointerCoords;
2202
Jeff Brownd3616592010-07-16 17:21:06 -07002203 // Set the X and Y offset depending on the input source.
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002204 float xOffset, yOffset, scaleFactor;
Kenny Root7a9db182011-06-02 15:16:05 -07002205 if (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER
2206 && !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002207 scaleFactor = dispatchEntry->scaleFactor;
2208 xOffset = dispatchEntry->xOffset * scaleFactor;
2209 yOffset = dispatchEntry->yOffset * scaleFactor;
2210 if (scaleFactor != 1.0f) {
2211 for (size_t i = 0; i < motionEntry->pointerCount; i++) {
2212 scaledCoords[i] = firstMotionSample->pointerCoords[i];
2213 scaledCoords[i].scale(scaleFactor);
2214 }
2215 usingCoords = scaledCoords;
2216 }
Jeff Brownd3616592010-07-16 17:21:06 -07002217 } else {
2218 xOffset = 0.0f;
2219 yOffset = 0.0f;
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002220 scaleFactor = 1.0f;
Kenny Root7a9db182011-06-02 15:16:05 -07002221
2222 // We don't want the dispatch target to know.
2223 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
2224 for (size_t i = 0; i < motionEntry->pointerCount; i++) {
2225 scaledCoords[i].clear();
2226 }
2227 usingCoords = scaledCoords;
2228 }
Jeff Brownd3616592010-07-16 17:21:06 -07002229 }
2230
Jeff Brown46b9ac02010-04-22 18:58:52 -07002231 // Publish the motion event and the first motion sample.
Jeff Brown81346812011-06-28 20:08:48 -07002232 status = connection->inputPublisher.publishMotionEvent(
2233 motionEntry->deviceId, motionEntry->source,
2234 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags,
2235 motionEntry->edgeFlags, motionEntry->metaState, motionEntry->buttonState,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002236 xOffset, yOffset,
2237 motionEntry->xPrecision, motionEntry->yPrecision,
Jeff Brown46b9ac02010-04-22 18:58:52 -07002238 motionEntry->downTime, firstMotionSample->eventTime,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002239 motionEntry->pointerCount, motionEntry->pointerProperties,
2240 usingCoords);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002241
2242 if (status) {
Steve Block3762c312012-01-06 19:20:56 +00002243 ALOGE("channel '%s' ~ Could not publish motion event, "
Jeff Brown46b9ac02010-04-22 18:58:52 -07002244 "status=%d", connection->getInputChannelName(), status);
Jeff Browncc4f7db2011-08-30 20:34:48 -07002245 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002246 return;
2247 }
2248
Jeff Brown81346812011-06-28 20:08:48 -07002249 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_MOVE
2250 || dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Jeff Browna032cc02011-03-07 16:56:21 -08002251 // Append additional motion samples.
2252 MotionSample* nextMotionSample = firstMotionSample->next;
2253 for (; nextMotionSample != NULL; nextMotionSample = nextMotionSample->next) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002254 if (usingCoords == scaledCoords) {
Kenny Root7a9db182011-06-02 15:16:05 -07002255 if (!(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
2256 for (size_t i = 0; i < motionEntry->pointerCount; i++) {
2257 scaledCoords[i] = nextMotionSample->pointerCoords[i];
2258 scaledCoords[i].scale(scaleFactor);
2259 }
Dianne Hackborn2ba3e802011-05-11 10:59:54 -07002260 }
2261 } else {
2262 usingCoords = nextMotionSample->pointerCoords;
Dianne Hackborne7d25b72011-05-09 21:19:26 -07002263 }
Jeff Browna032cc02011-03-07 16:56:21 -08002264 status = connection->inputPublisher.appendMotionSample(
Dianne Hackbornaa9d84c2011-05-09 19:00:59 -07002265 nextMotionSample->eventTime, usingCoords);
Jeff Browna032cc02011-03-07 16:56:21 -08002266 if (status == NO_MEMORY) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002267#if DEBUG_DISPATCH_CYCLE
Steve Block5baa3a62011-12-20 16:23:08 +00002268 ALOGD("channel '%s' ~ Shared memory buffer full. Some motion samples will "
Jeff Brown46b9ac02010-04-22 18:58:52 -07002269 "be sent in the next dispatch cycle.",
2270 connection->getInputChannelName());
2271#endif
Jeff Browna032cc02011-03-07 16:56:21 -08002272 break;
2273 }
2274 if (status != OK) {
Steve Block3762c312012-01-06 19:20:56 +00002275 ALOGE("channel '%s' ~ Could not append motion sample "
Jeff Browna032cc02011-03-07 16:56:21 -08002276 "for a reason other than out of memory, status=%d",
2277 connection->getInputChannelName(), status);
Jeff Browncc4f7db2011-08-30 20:34:48 -07002278 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
Jeff Browna032cc02011-03-07 16:56:21 -08002279 return;
2280 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002281 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002282
Jeff Browna032cc02011-03-07 16:56:21 -08002283 // Remember the next motion sample that we could not dispatch, in case we ran out
2284 // of space in the shared memory buffer.
2285 dispatchEntry->tailMotionSample = nextMotionSample;
2286 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002287 break;
2288 }
2289
2290 default: {
Steve Blockec193de2012-01-09 18:35:44 +00002291 ALOG_ASSERT(false);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002292 }
2293 }
2294
2295 // Send the dispatch signal.
2296 status = connection->inputPublisher.sendDispatchSignal();
2297 if (status) {
Steve Block3762c312012-01-06 19:20:56 +00002298 ALOGE("channel '%s' ~ Could not send dispatch signal, status=%d",
Jeff Brown46b9ac02010-04-22 18:58:52 -07002299 connection->getInputChannelName(), status);
Jeff Browncc4f7db2011-08-30 20:34:48 -07002300 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002301 return;
2302 }
2303
2304 // Record information about the newly started dispatch cycle.
Jeff Brown01ce2e92010-09-26 22:20:12 -07002305 connection->lastEventTime = eventEntry->eventTime;
Jeff Brown46b9ac02010-04-22 18:58:52 -07002306 connection->lastDispatchTime = currentTime;
2307
Jeff Brown46b9ac02010-04-22 18:58:52 -07002308 // Notify other system components.
2309 onDispatchCycleStartedLocked(currentTime, connection);
2310}
2311
Jeff Brown7fbdc842010-06-17 20:52:56 -07002312void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Jeff Brown3915bb82010-11-05 15:02:16 -07002313 const sp<Connection>& connection, bool handled) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002314#if DEBUG_DISPATCH_CYCLE
Steve Block5baa3a62011-12-20 16:23:08 +00002315 ALOGD("channel '%s' ~ finishDispatchCycle - %01.1fms since event, "
Jeff Brown3915bb82010-11-05 15:02:16 -07002316 "%01.1fms since dispatch, handled=%s",
Jeff Brown46b9ac02010-04-22 18:58:52 -07002317 connection->getInputChannelName(),
2318 connection->getEventLatencyMillis(currentTime),
Jeff Brown3915bb82010-11-05 15:02:16 -07002319 connection->getDispatchLatencyMillis(currentTime),
2320 toString(handled));
Jeff Brown46b9ac02010-04-22 18:58:52 -07002321#endif
2322
Jeff Brown9c3cda02010-06-15 01:31:58 -07002323 if (connection->status == Connection::STATUS_BROKEN
2324 || connection->status == Connection::STATUS_ZOMBIE) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002325 return;
2326 }
2327
Jeff Brown46b9ac02010-04-22 18:58:52 -07002328 // Reset the publisher since the event has been consumed.
2329 // We do this now so that the publisher can release some of its internal resources
2330 // while waiting for the next dispatch cycle to begin.
2331 status_t status = connection->inputPublisher.reset();
2332 if (status) {
Steve Block3762c312012-01-06 19:20:56 +00002333 ALOGE("channel '%s' ~ Could not reset publisher, status=%d",
Jeff Brown46b9ac02010-04-22 18:58:52 -07002334 connection->getInputChannelName(), status);
Jeff Browncc4f7db2011-08-30 20:34:48 -07002335 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002336 return;
2337 }
2338
Jeff Brown3915bb82010-11-05 15:02:16 -07002339 // Notify other system components and prepare to start the next dispatch cycle.
2340 onDispatchCycleFinishedLocked(currentTime, connection, handled);
Jeff Brownb88102f2010-09-08 11:49:43 -07002341}
2342
2343void InputDispatcher::startNextDispatchCycleLocked(nsecs_t currentTime,
2344 const sp<Connection>& connection) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002345 // Start the next dispatch cycle for this connection.
2346 while (! connection->outboundQueue.isEmpty()) {
Jeff Brownac386072011-07-20 15:19:50 -07002347 DispatchEntry* dispatchEntry = connection->outboundQueue.head;
Jeff Brown46b9ac02010-04-22 18:58:52 -07002348 if (dispatchEntry->inProgress) {
2349 // Finish or resume current event in progress.
2350 if (dispatchEntry->tailMotionSample) {
2351 // We have a tail of undispatched motion samples.
2352 // Reuse the same DispatchEntry and start a new cycle.
2353 dispatchEntry->inProgress = false;
2354 dispatchEntry->headMotionSample = dispatchEntry->tailMotionSample;
2355 dispatchEntry->tailMotionSample = NULL;
Jeff Brown519e0242010-09-15 15:18:56 -07002356 startDispatchCycleLocked(currentTime, connection);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002357 return;
2358 }
2359 // Finished.
2360 connection->outboundQueue.dequeueAtHead();
Jeff Brown519e0242010-09-15 15:18:56 -07002361 if (dispatchEntry->hasForegroundTarget()) {
2362 decrementPendingForegroundDispatchesLocked(dispatchEntry->eventEntry);
Jeff Brown6ec402b2010-07-28 15:48:59 -07002363 }
Jeff Brownac386072011-07-20 15:19:50 -07002364 delete dispatchEntry;
Jeff Brown46b9ac02010-04-22 18:58:52 -07002365 } else {
2366 // If the head is not in progress, then we must have already dequeued the in
Jeff Brown519e0242010-09-15 15:18:56 -07002367 // progress event, which means we actually aborted it.
Jeff Brown46b9ac02010-04-22 18:58:52 -07002368 // So just start the next event for this connection.
Jeff Brown519e0242010-09-15 15:18:56 -07002369 startDispatchCycleLocked(currentTime, connection);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002370 return;
2371 }
2372 }
2373
2374 // Outbound queue is empty, deactivate the connection.
Jeff Brown7fbdc842010-06-17 20:52:56 -07002375 deactivateConnectionLocked(connection.get());
Jeff Brown46b9ac02010-04-22 18:58:52 -07002376}
2377
Jeff Brownb6997262010-10-08 22:31:17 -07002378void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Jeff Browncc4f7db2011-08-30 20:34:48 -07002379 const sp<Connection>& connection, bool notify) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002380#if DEBUG_DISPATCH_CYCLE
Steve Block5baa3a62011-12-20 16:23:08 +00002381 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
Jeff Browncc4f7db2011-08-30 20:34:48 -07002382 connection->getInputChannelName(), toString(notify));
Jeff Brown46b9ac02010-04-22 18:58:52 -07002383#endif
2384
Jeff Brownb88102f2010-09-08 11:49:43 -07002385 // Clear the outbound queue.
Jeff Brown519e0242010-09-15 15:18:56 -07002386 drainOutboundQueueLocked(connection.get());
Jeff Brown46b9ac02010-04-22 18:58:52 -07002387
Jeff Brownb6997262010-10-08 22:31:17 -07002388 // The connection appears to be unrecoverably broken.
Jeff Brown9c3cda02010-06-15 01:31:58 -07002389 // Ignore already broken or zombie connections.
Jeff Brownb6997262010-10-08 22:31:17 -07002390 if (connection->status == Connection::STATUS_NORMAL) {
2391 connection->status = Connection::STATUS_BROKEN;
Jeff Brown46b9ac02010-04-22 18:58:52 -07002392
Jeff Browncc4f7db2011-08-30 20:34:48 -07002393 if (notify) {
2394 // Notify other system components.
2395 onDispatchCycleBrokenLocked(currentTime, connection);
2396 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002397 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002398}
2399
Jeff Brown519e0242010-09-15 15:18:56 -07002400void InputDispatcher::drainOutboundQueueLocked(Connection* connection) {
2401 while (! connection->outboundQueue.isEmpty()) {
2402 DispatchEntry* dispatchEntry = connection->outboundQueue.dequeueAtHead();
2403 if (dispatchEntry->hasForegroundTarget()) {
2404 decrementPendingForegroundDispatchesLocked(dispatchEntry->eventEntry);
Jeff Brownb88102f2010-09-08 11:49:43 -07002405 }
Jeff Brownac386072011-07-20 15:19:50 -07002406 delete dispatchEntry;
Jeff Brownb88102f2010-09-08 11:49:43 -07002407 }
2408
Jeff Brown519e0242010-09-15 15:18:56 -07002409 deactivateConnectionLocked(connection);
Jeff Brownb88102f2010-09-08 11:49:43 -07002410}
2411
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002412int InputDispatcher::handleReceiveCallback(int receiveFd, int events, void* data) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002413 InputDispatcher* d = static_cast<InputDispatcher*>(data);
2414
2415 { // acquire lock
2416 AutoMutex _l(d->mLock);
2417
2418 ssize_t connectionIndex = d->mConnectionsByReceiveFd.indexOfKey(receiveFd);
2419 if (connectionIndex < 0) {
Steve Block3762c312012-01-06 19:20:56 +00002420 ALOGE("Received spurious receive callback for unknown input channel. "
Jeff Brown46b9ac02010-04-22 18:58:52 -07002421 "fd=%d, events=0x%x", receiveFd, events);
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002422 return 0; // remove the callback
Jeff Brown46b9ac02010-04-22 18:58:52 -07002423 }
2424
Jeff Browncc4f7db2011-08-30 20:34:48 -07002425 bool notify;
Jeff Brown46b9ac02010-04-22 18:58:52 -07002426 sp<Connection> connection = d->mConnectionsByReceiveFd.valueAt(connectionIndex);
Jeff Browncc4f7db2011-08-30 20:34:48 -07002427 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
2428 if (!(events & ALOOPER_EVENT_INPUT)) {
Steve Block8564c8d2012-01-05 23:22:43 +00002429 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
Jeff Browncc4f7db2011-08-30 20:34:48 -07002430 "events=0x%x", connection->getInputChannelName(), events);
2431 return 1;
2432 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002433
Jeff Browncc4f7db2011-08-30 20:34:48 -07002434 bool handled = false;
2435 status_t status = connection->inputPublisher.receiveFinishedSignal(&handled);
2436 if (!status) {
2437 nsecs_t currentTime = now();
2438 d->finishDispatchCycleLocked(currentTime, connection, handled);
2439 d->runCommandsLockedInterruptible();
2440 return 1;
2441 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002442
Steve Block3762c312012-01-06 19:20:56 +00002443 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
Jeff Brown46b9ac02010-04-22 18:58:52 -07002444 connection->getInputChannelName(), status);
Jeff Browncc4f7db2011-08-30 20:34:48 -07002445 notify = true;
2446 } else {
2447 // Monitor channels are never explicitly unregistered.
2448 // We do it automatically when the remote endpoint is closed so don't warn
2449 // about them.
2450 notify = !connection->monitor;
2451 if (notify) {
Steve Block8564c8d2012-01-05 23:22:43 +00002452 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. "
Jeff Browncc4f7db2011-08-30 20:34:48 -07002453 "events=0x%x", connection->getInputChannelName(), events);
2454 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002455 }
2456
Jeff Browncc4f7db2011-08-30 20:34:48 -07002457 // Unregister the channel.
2458 d->unregisterInputChannelLocked(connection->inputChannel, notify);
2459 return 0; // remove the callback
Jeff Brown46b9ac02010-04-22 18:58:52 -07002460 } // release lock
2461}
2462
Jeff Brownb6997262010-10-08 22:31:17 -07002463void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Jeff Brownda3d5a92011-03-29 15:11:34 -07002464 const CancelationOptions& options) {
Jeff Brownb6997262010-10-08 22:31:17 -07002465 for (size_t i = 0; i < mConnectionsByReceiveFd.size(); i++) {
2466 synthesizeCancelationEventsForConnectionLocked(
Jeff Brownda3d5a92011-03-29 15:11:34 -07002467 mConnectionsByReceiveFd.valueAt(i), options);
Jeff Brownb6997262010-10-08 22:31:17 -07002468 }
2469}
2470
2471void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Jeff Brownda3d5a92011-03-29 15:11:34 -07002472 const sp<InputChannel>& channel, const CancelationOptions& options) {
Jeff Brownb6997262010-10-08 22:31:17 -07002473 ssize_t index = getConnectionIndexLocked(channel);
2474 if (index >= 0) {
2475 synthesizeCancelationEventsForConnectionLocked(
Jeff Brownda3d5a92011-03-29 15:11:34 -07002476 mConnectionsByReceiveFd.valueAt(index), options);
Jeff Brownb6997262010-10-08 22:31:17 -07002477 }
2478}
2479
2480void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
Jeff Brownda3d5a92011-03-29 15:11:34 -07002481 const sp<Connection>& connection, const CancelationOptions& options) {
Jeff Brownc0cb3dc2012-01-12 18:30:12 -08002482 if (connection->status == Connection::STATUS_BROKEN) {
2483 return;
2484 }
2485
Jeff Brownb6997262010-10-08 22:31:17 -07002486 nsecs_t currentTime = now();
2487
2488 mTempCancelationEvents.clear();
Jeff Brownac386072011-07-20 15:19:50 -07002489 connection->inputState.synthesizeCancelationEvents(currentTime,
Jeff Brownb6997262010-10-08 22:31:17 -07002490 mTempCancelationEvents, options);
2491
Jeff Brownc0cb3dc2012-01-12 18:30:12 -08002492 if (!mTempCancelationEvents.isEmpty()) {
Jeff Brownb6997262010-10-08 22:31:17 -07002493#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00002494 ALOGD("channel '%s' ~ Synthesized %d cancelation events to bring channel back in sync "
Jeff Brownda3d5a92011-03-29 15:11:34 -07002495 "with reality: %s, mode=%d.",
2496 connection->getInputChannelName(), mTempCancelationEvents.size(),
2497 options.reason, options.mode);
Jeff Brownb6997262010-10-08 22:31:17 -07002498#endif
2499 for (size_t i = 0; i < mTempCancelationEvents.size(); i++) {
2500 EventEntry* cancelationEventEntry = mTempCancelationEvents.itemAt(i);
2501 switch (cancelationEventEntry->type) {
2502 case EventEntry::TYPE_KEY:
2503 logOutboundKeyDetailsLocked("cancel - ",
2504 static_cast<KeyEntry*>(cancelationEventEntry));
2505 break;
2506 case EventEntry::TYPE_MOTION:
2507 logOutboundMotionDetailsLocked("cancel - ",
2508 static_cast<MotionEntry*>(cancelationEventEntry));
2509 break;
2510 }
2511
Jeff Brown81346812011-06-28 20:08:48 -07002512 InputTarget target;
Jeff Brown9302c872011-07-13 22:51:29 -07002513 sp<InputWindowHandle> windowHandle = getWindowHandleLocked(connection->inputChannel);
2514 if (windowHandle != NULL) {
Jeff Browncc4f7db2011-08-30 20:34:48 -07002515 const InputWindowInfo* windowInfo = windowHandle->getInfo();
2516 target.xOffset = -windowInfo->frameLeft;
2517 target.yOffset = -windowInfo->frameTop;
2518 target.scaleFactor = windowInfo->scaleFactor;
Jeff Brownb6997262010-10-08 22:31:17 -07002519 } else {
Jeff Brown81346812011-06-28 20:08:48 -07002520 target.xOffset = 0;
2521 target.yOffset = 0;
2522 target.scaleFactor = 1.0f;
Jeff Brownb6997262010-10-08 22:31:17 -07002523 }
Jeff Brown81346812011-06-28 20:08:48 -07002524 target.inputChannel = connection->inputChannel;
2525 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
Jeff Brownb6997262010-10-08 22:31:17 -07002526
Jeff Brown81346812011-06-28 20:08:48 -07002527 enqueueDispatchEntryLocked(connection, cancelationEventEntry, // increments ref
2528 &target, false, InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brownb6997262010-10-08 22:31:17 -07002529
Jeff Brownac386072011-07-20 15:19:50 -07002530 cancelationEventEntry->release();
Jeff Brownb6997262010-10-08 22:31:17 -07002531 }
2532
Jeff Brownac386072011-07-20 15:19:50 -07002533 if (!connection->outboundQueue.head->inProgress) {
Jeff Brownb6997262010-10-08 22:31:17 -07002534 startDispatchCycleLocked(currentTime, connection);
2535 }
2536 }
2537}
2538
Jeff Brown01ce2e92010-09-26 22:20:12 -07002539InputDispatcher::MotionEntry*
2540InputDispatcher::splitMotionEvent(const MotionEntry* originalMotionEntry, BitSet32 pointerIds) {
Steve Blockec193de2012-01-09 18:35:44 +00002541 ALOG_ASSERT(pointerIds.value != 0);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002542
2543 uint32_t splitPointerIndexMap[MAX_POINTERS];
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002544 PointerProperties splitPointerProperties[MAX_POINTERS];
Jeff Brown01ce2e92010-09-26 22:20:12 -07002545 PointerCoords splitPointerCoords[MAX_POINTERS];
2546
2547 uint32_t originalPointerCount = originalMotionEntry->pointerCount;
2548 uint32_t splitPointerCount = 0;
2549
2550 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
2551 originalPointerIndex++) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002552 const PointerProperties& pointerProperties =
2553 originalMotionEntry->pointerProperties[originalPointerIndex];
2554 uint32_t pointerId = uint32_t(pointerProperties.id);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002555 if (pointerIds.hasBit(pointerId)) {
2556 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002557 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
Jeff Brownace13b12011-03-09 17:39:48 -08002558 splitPointerCoords[splitPointerCount].copyFrom(
2559 originalMotionEntry->firstSample.pointerCoords[originalPointerIndex]);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002560 splitPointerCount += 1;
2561 }
2562 }
Jeff Brown58a2da82011-01-25 16:02:22 -08002563
2564 if (splitPointerCount != pointerIds.count()) {
2565 // This is bad. We are missing some of the pointers that we expected to deliver.
2566 // Most likely this indicates that we received an ACTION_MOVE events that has
2567 // different pointer ids than we expected based on the previous ACTION_DOWN
2568 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
2569 // in this way.
Steve Block8564c8d2012-01-05 23:22:43 +00002570 ALOGW("Dropping split motion event because the pointer count is %d but "
Jeff Brown58a2da82011-01-25 16:02:22 -08002571 "we expected there to be %d pointers. This probably means we received "
2572 "a broken sequence of pointer ids from the input device.",
2573 splitPointerCount, pointerIds.count());
2574 return NULL;
2575 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07002576
2577 int32_t action = originalMotionEntry->action;
2578 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
2579 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
2580 || maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2581 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002582 const PointerProperties& pointerProperties =
2583 originalMotionEntry->pointerProperties[originalPointerIndex];
2584 uint32_t pointerId = uint32_t(pointerProperties.id);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002585 if (pointerIds.hasBit(pointerId)) {
2586 if (pointerIds.count() == 1) {
2587 // The first/last pointer went down/up.
2588 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
2589 ? AMOTION_EVENT_ACTION_DOWN : AMOTION_EVENT_ACTION_UP;
Jeff Brown9a01d052010-09-27 16:35:11 -07002590 } else {
2591 // A secondary pointer went down/up.
2592 uint32_t splitPointerIndex = 0;
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002593 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
Jeff Brown9a01d052010-09-27 16:35:11 -07002594 splitPointerIndex += 1;
2595 }
2596 action = maskedAction | (splitPointerIndex
2597 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002598 }
2599 } else {
2600 // An unrelated pointer changed.
2601 action = AMOTION_EVENT_ACTION_MOVE;
2602 }
2603 }
2604
Jeff Brownac386072011-07-20 15:19:50 -07002605 MotionEntry* splitMotionEntry = new MotionEntry(
Jeff Brown01ce2e92010-09-26 22:20:12 -07002606 originalMotionEntry->eventTime,
2607 originalMotionEntry->deviceId,
2608 originalMotionEntry->source,
2609 originalMotionEntry->policyFlags,
2610 action,
2611 originalMotionEntry->flags,
2612 originalMotionEntry->metaState,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002613 originalMotionEntry->buttonState,
Jeff Brown01ce2e92010-09-26 22:20:12 -07002614 originalMotionEntry->edgeFlags,
2615 originalMotionEntry->xPrecision,
2616 originalMotionEntry->yPrecision,
2617 originalMotionEntry->downTime,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002618 splitPointerCount, splitPointerProperties, splitPointerCoords);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002619
2620 for (MotionSample* originalMotionSample = originalMotionEntry->firstSample.next;
2621 originalMotionSample != NULL; originalMotionSample = originalMotionSample->next) {
2622 for (uint32_t splitPointerIndex = 0; splitPointerIndex < splitPointerCount;
2623 splitPointerIndex++) {
2624 uint32_t originalPointerIndex = splitPointerIndexMap[splitPointerIndex];
Jeff Brownace13b12011-03-09 17:39:48 -08002625 splitPointerCoords[splitPointerIndex].copyFrom(
2626 originalMotionSample->pointerCoords[originalPointerIndex]);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002627 }
2628
Jeff Brownac386072011-07-20 15:19:50 -07002629 splitMotionEntry->appendSample(originalMotionSample->eventTime, splitPointerCoords);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002630 }
2631
Jeff Browna032cc02011-03-07 16:56:21 -08002632 if (originalMotionEntry->injectionState) {
2633 splitMotionEntry->injectionState = originalMotionEntry->injectionState;
2634 splitMotionEntry->injectionState->refCount += 1;
2635 }
2636
Jeff Brown01ce2e92010-09-26 22:20:12 -07002637 return splitMotionEntry;
2638}
2639
Jeff Brownbe1aa822011-07-27 16:04:54 -07002640void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002641#if DEBUG_INBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00002642 ALOGD("notifyConfigurationChanged - eventTime=%lld", args->eventTime);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002643#endif
2644
Jeff Brownb88102f2010-09-08 11:49:43 -07002645 bool needWake;
Jeff Brown46b9ac02010-04-22 18:58:52 -07002646 { // acquire lock
2647 AutoMutex _l(mLock);
2648
Jeff Brownbe1aa822011-07-27 16:04:54 -07002649 ConfigurationChangedEntry* newEntry = new ConfigurationChangedEntry(args->eventTime);
Jeff Brownb88102f2010-09-08 11:49:43 -07002650 needWake = enqueueInboundEventLocked(newEntry);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002651 } // release lock
2652
Jeff Brownb88102f2010-09-08 11:49:43 -07002653 if (needWake) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002654 mLooper->wake();
Jeff Brown46b9ac02010-04-22 18:58:52 -07002655 }
2656}
2657
Jeff Brownbe1aa822011-07-27 16:04:54 -07002658void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002659#if DEBUG_INBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00002660 ALOGD("notifyKey - eventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, action=0x%x, "
Jeff Brown46b9ac02010-04-22 18:58:52 -07002661 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%lld",
Jeff Brownbe1aa822011-07-27 16:04:54 -07002662 args->eventTime, args->deviceId, args->source, args->policyFlags,
2663 args->action, args->flags, args->keyCode, args->scanCode,
2664 args->metaState, args->downTime);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002665#endif
Jeff Brownbe1aa822011-07-27 16:04:54 -07002666 if (!validateKeyEvent(args->action)) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002667 return;
2668 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002669
Jeff Brownbe1aa822011-07-27 16:04:54 -07002670 uint32_t policyFlags = args->policyFlags;
2671 int32_t flags = args->flags;
2672 int32_t metaState = args->metaState;
Jeff Brown1f245102010-11-18 20:53:46 -08002673 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
2674 policyFlags |= POLICY_FLAG_VIRTUAL;
2675 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
2676 }
Jeff Brown924c4d42011-03-07 16:40:47 -08002677 if (policyFlags & POLICY_FLAG_ALT) {
2678 metaState |= AMETA_ALT_ON | AMETA_ALT_LEFT_ON;
2679 }
2680 if (policyFlags & POLICY_FLAG_ALT_GR) {
2681 metaState |= AMETA_ALT_ON | AMETA_ALT_RIGHT_ON;
2682 }
2683 if (policyFlags & POLICY_FLAG_SHIFT) {
2684 metaState |= AMETA_SHIFT_ON | AMETA_SHIFT_LEFT_ON;
2685 }
2686 if (policyFlags & POLICY_FLAG_CAPS_LOCK) {
2687 metaState |= AMETA_CAPS_LOCK_ON;
2688 }
2689 if (policyFlags & POLICY_FLAG_FUNCTION) {
2690 metaState |= AMETA_FUNCTION_ON;
2691 }
Jeff Brown1f245102010-11-18 20:53:46 -08002692
Jeff Browne20c9e02010-10-11 14:20:19 -07002693 policyFlags |= POLICY_FLAG_TRUSTED;
Jeff Brown1f245102010-11-18 20:53:46 -08002694
2695 KeyEvent event;
Jeff Brownbe1aa822011-07-27 16:04:54 -07002696 event.initialize(args->deviceId, args->source, args->action,
2697 flags, args->keyCode, args->scanCode, metaState, 0,
2698 args->downTime, args->eventTime);
Jeff Brown1f245102010-11-18 20:53:46 -08002699
2700 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
2701
2702 if (policyFlags & POLICY_FLAG_WOKE_HERE) {
2703 flags |= AKEY_EVENT_FLAG_WOKE_HERE;
2704 }
Jeff Brownb6997262010-10-08 22:31:17 -07002705
Jeff Brownb88102f2010-09-08 11:49:43 -07002706 bool needWake;
Jeff Brown46b9ac02010-04-22 18:58:52 -07002707 { // acquire lock
Jeff Brown0029c662011-03-30 02:25:18 -07002708 mLock.lock();
2709
2710 if (mInputFilterEnabled) {
2711 mLock.unlock();
2712
2713 policyFlags |= POLICY_FLAG_FILTERED;
2714 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2715 return; // event was consumed by the filter
2716 }
2717
2718 mLock.lock();
2719 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002720
Jeff Brown7fbdc842010-06-17 20:52:56 -07002721 int32_t repeatCount = 0;
Jeff Brownbe1aa822011-07-27 16:04:54 -07002722 KeyEntry* newEntry = new KeyEntry(args->eventTime,
2723 args->deviceId, args->source, policyFlags,
2724 args->action, flags, args->keyCode, args->scanCode,
2725 metaState, repeatCount, args->downTime);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002726
Jeff Brownb88102f2010-09-08 11:49:43 -07002727 needWake = enqueueInboundEventLocked(newEntry);
Jeff Brown0029c662011-03-30 02:25:18 -07002728 mLock.unlock();
Jeff Brown46b9ac02010-04-22 18:58:52 -07002729 } // release lock
2730
Jeff Brownb88102f2010-09-08 11:49:43 -07002731 if (needWake) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002732 mLooper->wake();
Jeff Brown46b9ac02010-04-22 18:58:52 -07002733 }
2734}
2735
Jeff Brownbe1aa822011-07-27 16:04:54 -07002736void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002737#if DEBUG_INBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00002738 ALOGD("notifyMotion - eventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, "
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002739 "action=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, edgeFlags=0x%x, "
Jeff Brown85a31762010-09-01 17:01:00 -07002740 "xPrecision=%f, yPrecision=%f, downTime=%lld",
Jeff Brownbe1aa822011-07-27 16:04:54 -07002741 args->eventTime, args->deviceId, args->source, args->policyFlags,
2742 args->action, args->flags, args->metaState, args->buttonState,
2743 args->edgeFlags, args->xPrecision, args->yPrecision, args->downTime);
2744 for (uint32_t i = 0; i < args->pointerCount; i++) {
Steve Block5baa3a62011-12-20 16:23:08 +00002745 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002746 "x=%f, y=%f, pressure=%f, size=%f, "
Jeff Brown85a31762010-09-01 17:01:00 -07002747 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
Jeff Brown8d608662010-08-30 03:02:23 -07002748 "orientation=%f",
Jeff Brownbe1aa822011-07-27 16:04:54 -07002749 i, args->pointerProperties[i].id,
2750 args->pointerProperties[i].toolType,
2751 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
2752 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
2753 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
2754 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
2755 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
2756 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
2757 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
2758 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
2759 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Jeff Brown46b9ac02010-04-22 18:58:52 -07002760 }
2761#endif
Jeff Brownbe1aa822011-07-27 16:04:54 -07002762 if (!validateMotionEvent(args->action, args->pointerCount, args->pointerProperties)) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002763 return;
2764 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002765
Jeff Brownbe1aa822011-07-27 16:04:54 -07002766 uint32_t policyFlags = args->policyFlags;
Jeff Browne20c9e02010-10-11 14:20:19 -07002767 policyFlags |= POLICY_FLAG_TRUSTED;
Jeff Brownbe1aa822011-07-27 16:04:54 -07002768 mPolicy->interceptMotionBeforeQueueing(args->eventTime, /*byref*/ policyFlags);
Jeff Brownb6997262010-10-08 22:31:17 -07002769
Jeff Brownb88102f2010-09-08 11:49:43 -07002770 bool needWake;
Jeff Brown46b9ac02010-04-22 18:58:52 -07002771 { // acquire lock
Jeff Brown0029c662011-03-30 02:25:18 -07002772 mLock.lock();
2773
2774 if (mInputFilterEnabled) {
2775 mLock.unlock();
2776
2777 MotionEvent event;
Jeff Brownbe1aa822011-07-27 16:04:54 -07002778 event.initialize(args->deviceId, args->source, args->action, args->flags,
2779 args->edgeFlags, args->metaState, args->buttonState, 0, 0,
2780 args->xPrecision, args->yPrecision,
2781 args->downTime, args->eventTime,
2782 args->pointerCount, args->pointerProperties, args->pointerCoords);
Jeff Brown0029c662011-03-30 02:25:18 -07002783
2784 policyFlags |= POLICY_FLAG_FILTERED;
2785 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2786 return; // event was consumed by the filter
2787 }
2788
2789 mLock.lock();
2790 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002791
2792 // Attempt batching and streaming of move events.
Jeff Brownbe1aa822011-07-27 16:04:54 -07002793 if (args->action == AMOTION_EVENT_ACTION_MOVE
2794 || args->action == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002795 // BATCHING CASE
2796 //
2797 // Try to append a move sample to the tail of the inbound queue for this device.
2798 // Give up if we encounter a non-move motion event for this device since that
2799 // means we cannot append any new samples until a new motion event has started.
Jeff Brownac386072011-07-20 15:19:50 -07002800 for (EventEntry* entry = mInboundQueue.tail; entry; entry = entry->prev) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002801 if (entry->type != EventEntry::TYPE_MOTION) {
2802 // Keep looking for motion events.
2803 continue;
2804 }
2805
2806 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
Jeff Brownbe1aa822011-07-27 16:04:54 -07002807 if (motionEntry->deviceId != args->deviceId
2808 || motionEntry->source != args->source) {
Jeff Brownefd32662011-03-08 15:13:06 -08002809 // Keep looking for this device and source.
Jeff Brown46b9ac02010-04-22 18:58:52 -07002810 continue;
2811 }
2812
Jeff Brownbe1aa822011-07-27 16:04:54 -07002813 if (!motionEntry->canAppendSamples(args->action,
2814 args->pointerCount, args->pointerProperties)) {
Jeff Brownefd32662011-03-08 15:13:06 -08002815 // Last motion event in the queue for this device and source is
2816 // not compatible for appending new samples. Stop here.
Jeff Brown46b9ac02010-04-22 18:58:52 -07002817 goto NoBatchingOrStreaming;
2818 }
2819
Jeff Brown9c3cda02010-06-15 01:31:58 -07002820 // Do the batching magic.
Jeff Brownbe1aa822011-07-27 16:04:54 -07002821 batchMotionLocked(motionEntry, args->eventTime,
2822 args->metaState, args->pointerCoords,
Jeff Brown4e91a182011-04-07 11:38:09 -07002823 "most recent motion event for this device and source in the inbound queue");
Jeff Brown0029c662011-03-30 02:25:18 -07002824 mLock.unlock();
Jeff Brown9c3cda02010-06-15 01:31:58 -07002825 return; // done!
Jeff Brown46b9ac02010-04-22 18:58:52 -07002826 }
2827
Jeff Brownf6989da2011-04-06 17:19:48 -07002828 // BATCHING ONTO PENDING EVENT CASE
2829 //
2830 // Try to append a move sample to the currently pending event, if there is one.
2831 // We can do this as long as we are still waiting to find the targets for the
2832 // event. Once the targets are locked-in we can only do streaming.
2833 if (mPendingEvent
2834 && (!mPendingEvent->dispatchInProgress || !mCurrentInputTargetsValid)
2835 && mPendingEvent->type == EventEntry::TYPE_MOTION) {
2836 MotionEntry* motionEntry = static_cast<MotionEntry*>(mPendingEvent);
Jeff Brownbe1aa822011-07-27 16:04:54 -07002837 if (motionEntry->deviceId == args->deviceId
2838 && motionEntry->source == args->source) {
2839 if (!motionEntry->canAppendSamples(args->action,
2840 args->pointerCount, args->pointerProperties)) {
Jeff Brown4e91a182011-04-07 11:38:09 -07002841 // Pending motion event is for this device and source but it is
2842 // not compatible for appending new samples. Stop here.
Jeff Brownf6989da2011-04-06 17:19:48 -07002843 goto NoBatchingOrStreaming;
2844 }
2845
Jeff Brownf6989da2011-04-06 17:19:48 -07002846 // Do the batching magic.
Jeff Brownbe1aa822011-07-27 16:04:54 -07002847 batchMotionLocked(motionEntry, args->eventTime,
2848 args->metaState, args->pointerCoords,
Jeff Brown4e91a182011-04-07 11:38:09 -07002849 "pending motion event");
Jeff Brownf6989da2011-04-06 17:19:48 -07002850 mLock.unlock();
2851 return; // done!
2852 }
2853 }
2854
Jeff Brown46b9ac02010-04-22 18:58:52 -07002855 // STREAMING CASE
2856 //
2857 // There is no pending motion event (of any kind) for this device in the inbound queue.
Jeff Brown519e0242010-09-15 15:18:56 -07002858 // Search the outbound queue for the current foreground targets to find a dispatched
2859 // motion event that is still in progress. If found, then, appen the new sample to
2860 // that event and push it out to all current targets. The logic in
2861 // prepareDispatchCycleLocked takes care of the case where some targets may
2862 // already have consumed the motion event by starting a new dispatch cycle if needed.
Jeff Brown9c3cda02010-06-15 01:31:58 -07002863 if (mCurrentInputTargetsValid) {
Jeff Brown519e0242010-09-15 15:18:56 -07002864 for (size_t i = 0; i < mCurrentInputTargets.size(); i++) {
2865 const InputTarget& inputTarget = mCurrentInputTargets[i];
2866 if ((inputTarget.flags & InputTarget::FLAG_FOREGROUND) == 0) {
2867 // Skip non-foreground targets. We only want to stream if there is at
2868 // least one foreground target whose dispatch is still in progress.
2869 continue;
Jeff Brown46b9ac02010-04-22 18:58:52 -07002870 }
Jeff Brown519e0242010-09-15 15:18:56 -07002871
2872 ssize_t connectionIndex = getConnectionIndexLocked(inputTarget.inputChannel);
2873 if (connectionIndex < 0) {
2874 // Connection must no longer be valid.
2875 continue;
2876 }
2877
2878 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
2879 if (connection->outboundQueue.isEmpty()) {
2880 // This foreground target has an empty outbound queue.
2881 continue;
2882 }
2883
Jeff Brownac386072011-07-20 15:19:50 -07002884 DispatchEntry* dispatchEntry = connection->outboundQueue.head;
Jeff Brown519e0242010-09-15 15:18:56 -07002885 if (! dispatchEntry->inProgress
Jeff Brown01ce2e92010-09-26 22:20:12 -07002886 || dispatchEntry->eventEntry->type != EventEntry::TYPE_MOTION
2887 || dispatchEntry->isSplit()) {
2888 // No motion event is being dispatched, or it is being split across
2889 // windows in which case we cannot stream.
Jeff Brown519e0242010-09-15 15:18:56 -07002890 continue;
2891 }
2892
2893 MotionEntry* motionEntry = static_cast<MotionEntry*>(
2894 dispatchEntry->eventEntry);
Jeff Brownbe1aa822011-07-27 16:04:54 -07002895 if (motionEntry->action != args->action
2896 || motionEntry->deviceId != args->deviceId
2897 || motionEntry->source != args->source
2898 || motionEntry->pointerCount != args->pointerCount
Jeff Brown519e0242010-09-15 15:18:56 -07002899 || motionEntry->isInjected()) {
2900 // The motion event is not compatible with this move.
2901 continue;
2902 }
2903
Jeff Brownbe1aa822011-07-27 16:04:54 -07002904 if (args->action == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Jeff Brown9302c872011-07-13 22:51:29 -07002905 if (mLastHoverWindowHandle == NULL) {
Jeff Browna032cc02011-03-07 16:56:21 -08002906#if DEBUG_BATCHING
Steve Block5baa3a62011-12-20 16:23:08 +00002907 ALOGD("Not streaming hover move because there is no "
Jeff Browna032cc02011-03-07 16:56:21 -08002908 "last hovered window.");
2909#endif
2910 goto NoBatchingOrStreaming;
2911 }
2912
Jeff Brown9302c872011-07-13 22:51:29 -07002913 sp<InputWindowHandle> hoverWindowHandle = findTouchedWindowAtLocked(
Jeff Brownbe1aa822011-07-27 16:04:54 -07002914 args->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X),
2915 args->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Jeff Brown9302c872011-07-13 22:51:29 -07002916 if (mLastHoverWindowHandle != hoverWindowHandle) {
Jeff Browna032cc02011-03-07 16:56:21 -08002917#if DEBUG_BATCHING
Steve Block5baa3a62011-12-20 16:23:08 +00002918 ALOGD("Not streaming hover move because the last hovered window "
Jeff Browna032cc02011-03-07 16:56:21 -08002919 "is '%s' but the currently hovered window is '%s'.",
Jeff Browncc4f7db2011-08-30 20:34:48 -07002920 mLastHoverWindowHandle->getName().string(),
Jeff Brown9302c872011-07-13 22:51:29 -07002921 hoverWindowHandle != NULL
Jeff Browncc4f7db2011-08-30 20:34:48 -07002922 ? hoverWindowHandle->getName().string() : "<null>");
Jeff Browna032cc02011-03-07 16:56:21 -08002923#endif
2924 goto NoBatchingOrStreaming;
2925 }
2926 }
2927
Jeff Brown519e0242010-09-15 15:18:56 -07002928 // Hurray! This foreground target is currently dispatching a move event
2929 // that we can stream onto. Append the motion sample and resume dispatch.
Jeff Brownbe1aa822011-07-27 16:04:54 -07002930 motionEntry->appendSample(args->eventTime, args->pointerCoords);
Jeff Brown519e0242010-09-15 15:18:56 -07002931#if DEBUG_BATCHING
Steve Block5baa3a62011-12-20 16:23:08 +00002932 ALOGD("Appended motion sample onto batch for most recently dispatched "
Jeff Brown4e91a182011-04-07 11:38:09 -07002933 "motion event for this device and source in the outbound queues. "
Jeff Brown519e0242010-09-15 15:18:56 -07002934 "Attempting to stream the motion sample.");
2935#endif
2936 nsecs_t currentTime = now();
2937 dispatchEventToCurrentInputTargetsLocked(currentTime, motionEntry,
2938 true /*resumeWithAppendedMotionSample*/);
2939
2940 runCommandsLockedInterruptible();
Jeff Brown0029c662011-03-30 02:25:18 -07002941 mLock.unlock();
Jeff Brown519e0242010-09-15 15:18:56 -07002942 return; // done!
Jeff Brown46b9ac02010-04-22 18:58:52 -07002943 }
2944 }
2945
2946NoBatchingOrStreaming:;
2947 }
2948
2949 // Just enqueue a new motion event.
Jeff Brownbe1aa822011-07-27 16:04:54 -07002950 MotionEntry* newEntry = new MotionEntry(args->eventTime,
2951 args->deviceId, args->source, policyFlags,
2952 args->action, args->flags, args->metaState, args->buttonState,
2953 args->edgeFlags, args->xPrecision, args->yPrecision, args->downTime,
2954 args->pointerCount, args->pointerProperties, args->pointerCoords);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002955
Jeff Brownb88102f2010-09-08 11:49:43 -07002956 needWake = enqueueInboundEventLocked(newEntry);
Jeff Brown0029c662011-03-30 02:25:18 -07002957 mLock.unlock();
Jeff Brown46b9ac02010-04-22 18:58:52 -07002958 } // release lock
2959
Jeff Brownb88102f2010-09-08 11:49:43 -07002960 if (needWake) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002961 mLooper->wake();
Jeff Brown46b9ac02010-04-22 18:58:52 -07002962 }
2963}
2964
Jeff Brown4e91a182011-04-07 11:38:09 -07002965void InputDispatcher::batchMotionLocked(MotionEntry* entry, nsecs_t eventTime,
2966 int32_t metaState, const PointerCoords* pointerCoords, const char* eventDescription) {
2967 // Combine meta states.
2968 entry->metaState |= metaState;
2969
2970 // Coalesce this sample if not enough time has elapsed since the last sample was
2971 // initially appended to the batch.
2972 MotionSample* lastSample = entry->lastSample;
2973 long interval = eventTime - lastSample->eventTimeBeforeCoalescing;
2974 if (interval <= MOTION_SAMPLE_COALESCE_INTERVAL) {
2975 uint32_t pointerCount = entry->pointerCount;
2976 for (uint32_t i = 0; i < pointerCount; i++) {
2977 lastSample->pointerCoords[i].copyFrom(pointerCoords[i]);
2978 }
2979 lastSample->eventTime = eventTime;
2980#if DEBUG_BATCHING
Steve Block5baa3a62011-12-20 16:23:08 +00002981 ALOGD("Coalesced motion into last sample of batch for %s, events were %0.3f ms apart",
Jeff Brown4e91a182011-04-07 11:38:09 -07002982 eventDescription, interval * 0.000001f);
2983#endif
2984 return;
2985 }
2986
2987 // Append the sample.
Jeff Brownac386072011-07-20 15:19:50 -07002988 entry->appendSample(eventTime, pointerCoords);
Jeff Brown4e91a182011-04-07 11:38:09 -07002989#if DEBUG_BATCHING
Steve Block5baa3a62011-12-20 16:23:08 +00002990 ALOGD("Appended motion sample onto batch for %s, events were %0.3f ms apart",
Jeff Brown4e91a182011-04-07 11:38:09 -07002991 eventDescription, interval * 0.000001f);
2992#endif
2993}
2994
Jeff Brownbe1aa822011-07-27 16:04:54 -07002995void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
Jeff Brownb6997262010-10-08 22:31:17 -07002996#if DEBUG_INBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00002997 ALOGD("notifySwitch - eventTime=%lld, policyFlags=0x%x, switchCode=%d, switchValue=%d",
Jeff Brownbe1aa822011-07-27 16:04:54 -07002998 args->eventTime, args->policyFlags,
2999 args->switchCode, args->switchValue);
Jeff Brownb6997262010-10-08 22:31:17 -07003000#endif
3001
Jeff Brownbe1aa822011-07-27 16:04:54 -07003002 uint32_t policyFlags = args->policyFlags;
Jeff Browne20c9e02010-10-11 14:20:19 -07003003 policyFlags |= POLICY_FLAG_TRUSTED;
Jeff Brownbe1aa822011-07-27 16:04:54 -07003004 mPolicy->notifySwitch(args->eventTime,
3005 args->switchCode, args->switchValue, policyFlags);
Jeff Brownb6997262010-10-08 22:31:17 -07003006}
3007
Jeff Brown65fd2512011-08-18 11:20:58 -07003008void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
3009#if DEBUG_INBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00003010 ALOGD("notifyDeviceReset - eventTime=%lld, deviceId=%d",
Jeff Brown65fd2512011-08-18 11:20:58 -07003011 args->eventTime, args->deviceId);
3012#endif
3013
3014 bool needWake;
3015 { // acquire lock
3016 AutoMutex _l(mLock);
3017
3018 DeviceResetEntry* newEntry = new DeviceResetEntry(args->eventTime, args->deviceId);
3019 needWake = enqueueInboundEventLocked(newEntry);
3020 } // release lock
3021
3022 if (needWake) {
3023 mLooper->wake();
3024 }
3025}
3026
Jeff Brown7fbdc842010-06-17 20:52:56 -07003027int32_t InputDispatcher::injectInputEvent(const InputEvent* event,
Jeff Brown0029c662011-03-30 02:25:18 -07003028 int32_t injectorPid, int32_t injectorUid, int32_t syncMode, int32_t timeoutMillis,
3029 uint32_t policyFlags) {
Jeff Brown7fbdc842010-06-17 20:52:56 -07003030#if DEBUG_INBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00003031 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Jeff Brown0029c662011-03-30 02:25:18 -07003032 "syncMode=%d, timeoutMillis=%d, policyFlags=0x%08x",
3033 event->getType(), injectorPid, injectorUid, syncMode, timeoutMillis, policyFlags);
Jeff Brown7fbdc842010-06-17 20:52:56 -07003034#endif
3035
3036 nsecs_t endTime = now() + milliseconds_to_nanoseconds(timeoutMillis);
Jeff Browne20c9e02010-10-11 14:20:19 -07003037
Jeff Brown0029c662011-03-30 02:25:18 -07003038 policyFlags |= POLICY_FLAG_INJECTED;
Jeff Browne20c9e02010-10-11 14:20:19 -07003039 if (hasInjectionPermission(injectorPid, injectorUid)) {
3040 policyFlags |= POLICY_FLAG_TRUSTED;
3041 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07003042
Jeff Brownb6997262010-10-08 22:31:17 -07003043 EventEntry* injectedEntry;
3044 switch (event->getType()) {
3045 case AINPUT_EVENT_TYPE_KEY: {
3046 const KeyEvent* keyEvent = static_cast<const KeyEvent*>(event);
3047 int32_t action = keyEvent->getAction();
3048 if (! validateKeyEvent(action)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07003049 return INPUT_EVENT_INJECTION_FAILED;
3050 }
3051
Jeff Brownb6997262010-10-08 22:31:17 -07003052 int32_t flags = keyEvent->getFlags();
Jeff Brown1f245102010-11-18 20:53:46 -08003053 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
3054 policyFlags |= POLICY_FLAG_VIRTUAL;
3055 }
3056
Jeff Brown0029c662011-03-30 02:25:18 -07003057 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3058 mPolicy->interceptKeyBeforeQueueing(keyEvent, /*byref*/ policyFlags);
3059 }
Jeff Brown1f245102010-11-18 20:53:46 -08003060
3061 if (policyFlags & POLICY_FLAG_WOKE_HERE) {
3062 flags |= AKEY_EVENT_FLAG_WOKE_HERE;
3063 }
Jeff Brown6ec402b2010-07-28 15:48:59 -07003064
Jeff Brownb6997262010-10-08 22:31:17 -07003065 mLock.lock();
Jeff Brownac386072011-07-20 15:19:50 -07003066 injectedEntry = new KeyEntry(keyEvent->getEventTime(),
Jeff Brown1f245102010-11-18 20:53:46 -08003067 keyEvent->getDeviceId(), keyEvent->getSource(),
3068 policyFlags, action, flags,
3069 keyEvent->getKeyCode(), keyEvent->getScanCode(), keyEvent->getMetaState(),
Jeff Brownb6997262010-10-08 22:31:17 -07003070 keyEvent->getRepeatCount(), keyEvent->getDownTime());
3071 break;
3072 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07003073
Jeff Brownb6997262010-10-08 22:31:17 -07003074 case AINPUT_EVENT_TYPE_MOTION: {
3075 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
3076 int32_t action = motionEvent->getAction();
3077 size_t pointerCount = motionEvent->getPointerCount();
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003078 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
3079 if (! validateMotionEvent(action, pointerCount, pointerProperties)) {
Jeff Brownb6997262010-10-08 22:31:17 -07003080 return INPUT_EVENT_INJECTION_FAILED;
3081 }
3082
Jeff Brown0029c662011-03-30 02:25:18 -07003083 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3084 nsecs_t eventTime = motionEvent->getEventTime();
3085 mPolicy->interceptMotionBeforeQueueing(eventTime, /*byref*/ policyFlags);
3086 }
Jeff Brownb6997262010-10-08 22:31:17 -07003087
3088 mLock.lock();
3089 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
3090 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
Jeff Brownac386072011-07-20 15:19:50 -07003091 MotionEntry* motionEntry = new MotionEntry(*sampleEventTimes,
Jeff Brownb6997262010-10-08 22:31:17 -07003092 motionEvent->getDeviceId(), motionEvent->getSource(), policyFlags,
3093 action, motionEvent->getFlags(),
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003094 motionEvent->getMetaState(), motionEvent->getButtonState(),
3095 motionEvent->getEdgeFlags(),
Jeff Brownb6997262010-10-08 22:31:17 -07003096 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
3097 motionEvent->getDownTime(), uint32_t(pointerCount),
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003098 pointerProperties, samplePointerCoords);
Jeff Brownb6997262010-10-08 22:31:17 -07003099 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
3100 sampleEventTimes += 1;
3101 samplePointerCoords += pointerCount;
Jeff Brownac386072011-07-20 15:19:50 -07003102 motionEntry->appendSample(*sampleEventTimes, samplePointerCoords);
Jeff Brownb6997262010-10-08 22:31:17 -07003103 }
3104 injectedEntry = motionEntry;
3105 break;
3106 }
3107
3108 default:
Steve Block8564c8d2012-01-05 23:22:43 +00003109 ALOGW("Cannot inject event of type %d", event->getType());
Jeff Brownb6997262010-10-08 22:31:17 -07003110 return INPUT_EVENT_INJECTION_FAILED;
3111 }
3112
Jeff Brownac386072011-07-20 15:19:50 -07003113 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
Jeff Brownb6997262010-10-08 22:31:17 -07003114 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
3115 injectionState->injectionIsAsync = true;
3116 }
3117
3118 injectionState->refCount += 1;
3119 injectedEntry->injectionState = injectionState;
3120
3121 bool needWake = enqueueInboundEventLocked(injectedEntry);
3122 mLock.unlock();
Jeff Brown7fbdc842010-06-17 20:52:56 -07003123
Jeff Brownb88102f2010-09-08 11:49:43 -07003124 if (needWake) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07003125 mLooper->wake();
Jeff Brown7fbdc842010-06-17 20:52:56 -07003126 }
3127
3128 int32_t injectionResult;
3129 { // acquire lock
3130 AutoMutex _l(mLock);
3131
Jeff Brown6ec402b2010-07-28 15:48:59 -07003132 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
3133 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
3134 } else {
3135 for (;;) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07003136 injectionResult = injectionState->injectionResult;
Jeff Brown6ec402b2010-07-28 15:48:59 -07003137 if (injectionResult != INPUT_EVENT_INJECTION_PENDING) {
3138 break;
3139 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07003140
Jeff Brown7fbdc842010-06-17 20:52:56 -07003141 nsecs_t remainingTimeout = endTime - now();
3142 if (remainingTimeout <= 0) {
Jeff Brown6ec402b2010-07-28 15:48:59 -07003143#if DEBUG_INJECTION
Steve Block5baa3a62011-12-20 16:23:08 +00003144 ALOGD("injectInputEvent - Timed out waiting for injection result "
Jeff Brown6ec402b2010-07-28 15:48:59 -07003145 "to become available.");
3146#endif
Jeff Brown7fbdc842010-06-17 20:52:56 -07003147 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
3148 break;
3149 }
3150
Jeff Brown6ec402b2010-07-28 15:48:59 -07003151 mInjectionResultAvailableCondition.waitRelative(mLock, remainingTimeout);
3152 }
3153
3154 if (injectionResult == INPUT_EVENT_INJECTION_SUCCEEDED
3155 && syncMode == INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07003156 while (injectionState->pendingForegroundDispatches != 0) {
Jeff Brown6ec402b2010-07-28 15:48:59 -07003157#if DEBUG_INJECTION
Steve Block5baa3a62011-12-20 16:23:08 +00003158 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
Jeff Brown01ce2e92010-09-26 22:20:12 -07003159 injectionState->pendingForegroundDispatches);
Jeff Brown6ec402b2010-07-28 15:48:59 -07003160#endif
3161 nsecs_t remainingTimeout = endTime - now();
3162 if (remainingTimeout <= 0) {
3163#if DEBUG_INJECTION
Steve Block5baa3a62011-12-20 16:23:08 +00003164 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
Jeff Brown6ec402b2010-07-28 15:48:59 -07003165 "dispatches to finish.");
3166#endif
3167 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
3168 break;
3169 }
3170
3171 mInjectionSyncFinishedCondition.waitRelative(mLock, remainingTimeout);
3172 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07003173 }
3174 }
3175
Jeff Brownac386072011-07-20 15:19:50 -07003176 injectionState->release();
Jeff Brown7fbdc842010-06-17 20:52:56 -07003177 } // release lock
3178
Jeff Brown6ec402b2010-07-28 15:48:59 -07003179#if DEBUG_INJECTION
Steve Block5baa3a62011-12-20 16:23:08 +00003180 ALOGD("injectInputEvent - Finished with result %d. "
Jeff Brown6ec402b2010-07-28 15:48:59 -07003181 "injectorPid=%d, injectorUid=%d",
3182 injectionResult, injectorPid, injectorUid);
3183#endif
3184
Jeff Brown7fbdc842010-06-17 20:52:56 -07003185 return injectionResult;
3186}
3187
Jeff Brownb6997262010-10-08 22:31:17 -07003188bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
3189 return injectorUid == 0
3190 || mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
3191}
3192
Jeff Brown7fbdc842010-06-17 20:52:56 -07003193void InputDispatcher::setInjectionResultLocked(EventEntry* entry, int32_t injectionResult) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07003194 InjectionState* injectionState = entry->injectionState;
3195 if (injectionState) {
Jeff Brown7fbdc842010-06-17 20:52:56 -07003196#if DEBUG_INJECTION
Steve Block5baa3a62011-12-20 16:23:08 +00003197 ALOGD("Setting input event injection result to %d. "
Jeff Brown7fbdc842010-06-17 20:52:56 -07003198 "injectorPid=%d, injectorUid=%d",
Jeff Brown01ce2e92010-09-26 22:20:12 -07003199 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
Jeff Brown7fbdc842010-06-17 20:52:56 -07003200#endif
3201
Jeff Brown0029c662011-03-30 02:25:18 -07003202 if (injectionState->injectionIsAsync
3203 && !(entry->policyFlags & POLICY_FLAG_FILTERED)) {
Jeff Brown6ec402b2010-07-28 15:48:59 -07003204 // Log the outcome since the injector did not wait for the injection result.
3205 switch (injectionResult) {
3206 case INPUT_EVENT_INJECTION_SUCCEEDED:
Steve Block71f2cf12011-10-20 11:56:00 +01003207 ALOGV("Asynchronous input event injection succeeded.");
Jeff Brown6ec402b2010-07-28 15:48:59 -07003208 break;
3209 case INPUT_EVENT_INJECTION_FAILED:
Steve Block8564c8d2012-01-05 23:22:43 +00003210 ALOGW("Asynchronous input event injection failed.");
Jeff Brown6ec402b2010-07-28 15:48:59 -07003211 break;
3212 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
Steve Block8564c8d2012-01-05 23:22:43 +00003213 ALOGW("Asynchronous input event injection permission denied.");
Jeff Brown6ec402b2010-07-28 15:48:59 -07003214 break;
3215 case INPUT_EVENT_INJECTION_TIMED_OUT:
Steve Block8564c8d2012-01-05 23:22:43 +00003216 ALOGW("Asynchronous input event injection timed out.");
Jeff Brown6ec402b2010-07-28 15:48:59 -07003217 break;
3218 }
3219 }
3220
Jeff Brown01ce2e92010-09-26 22:20:12 -07003221 injectionState->injectionResult = injectionResult;
Jeff Brown7fbdc842010-06-17 20:52:56 -07003222 mInjectionResultAvailableCondition.broadcast();
3223 }
3224}
3225
Jeff Brown01ce2e92010-09-26 22:20:12 -07003226void InputDispatcher::incrementPendingForegroundDispatchesLocked(EventEntry* entry) {
3227 InjectionState* injectionState = entry->injectionState;
3228 if (injectionState) {
3229 injectionState->pendingForegroundDispatches += 1;
3230 }
3231}
3232
Jeff Brown519e0242010-09-15 15:18:56 -07003233void InputDispatcher::decrementPendingForegroundDispatchesLocked(EventEntry* entry) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07003234 InjectionState* injectionState = entry->injectionState;
3235 if (injectionState) {
3236 injectionState->pendingForegroundDispatches -= 1;
Jeff Brown6ec402b2010-07-28 15:48:59 -07003237
Jeff Brown01ce2e92010-09-26 22:20:12 -07003238 if (injectionState->pendingForegroundDispatches == 0) {
3239 mInjectionSyncFinishedCondition.broadcast();
3240 }
Jeff Brownb88102f2010-09-08 11:49:43 -07003241 }
3242}
3243
Jeff Brown9302c872011-07-13 22:51:29 -07003244sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
3245 const sp<InputChannel>& inputChannel) const {
3246 size_t numWindows = mWindowHandles.size();
3247 for (size_t i = 0; i < numWindows; i++) {
3248 const sp<InputWindowHandle>& windowHandle = mWindowHandles.itemAt(i);
Jeff Browncc4f7db2011-08-30 20:34:48 -07003249 if (windowHandle->getInputChannel() == inputChannel) {
Jeff Brown9302c872011-07-13 22:51:29 -07003250 return windowHandle;
Jeff Brown01ce2e92010-09-26 22:20:12 -07003251 }
3252 }
3253 return NULL;
3254}
3255
Jeff Brown9302c872011-07-13 22:51:29 -07003256bool InputDispatcher::hasWindowHandleLocked(
3257 const sp<InputWindowHandle>& windowHandle) const {
3258 size_t numWindows = mWindowHandles.size();
3259 for (size_t i = 0; i < numWindows; i++) {
3260 if (mWindowHandles.itemAt(i) == windowHandle) {
3261 return true;
3262 }
3263 }
3264 return false;
3265}
3266
3267void InputDispatcher::setInputWindows(const Vector<sp<InputWindowHandle> >& inputWindowHandles) {
Jeff Brownb88102f2010-09-08 11:49:43 -07003268#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00003269 ALOGD("setInputWindows");
Jeff Brownb88102f2010-09-08 11:49:43 -07003270#endif
3271 { // acquire lock
3272 AutoMutex _l(mLock);
3273
Jeff Browncc4f7db2011-08-30 20:34:48 -07003274 Vector<sp<InputWindowHandle> > oldWindowHandles = mWindowHandles;
Jeff Brown9302c872011-07-13 22:51:29 -07003275 mWindowHandles = inputWindowHandles;
Jeff Brownb6997262010-10-08 22:31:17 -07003276
Jeff Brown9302c872011-07-13 22:51:29 -07003277 sp<InputWindowHandle> newFocusedWindowHandle;
3278 bool foundHoveredWindow = false;
3279 for (size_t i = 0; i < mWindowHandles.size(); i++) {
3280 const sp<InputWindowHandle>& windowHandle = mWindowHandles.itemAt(i);
Jeff Browncc4f7db2011-08-30 20:34:48 -07003281 if (!windowHandle->updateInfo() || windowHandle->getInputChannel() == NULL) {
Jeff Brown9302c872011-07-13 22:51:29 -07003282 mWindowHandles.removeAt(i--);
3283 continue;
3284 }
Jeff Browncc4f7db2011-08-30 20:34:48 -07003285 if (windowHandle->getInfo()->hasFocus) {
Jeff Brown9302c872011-07-13 22:51:29 -07003286 newFocusedWindowHandle = windowHandle;
3287 }
3288 if (windowHandle == mLastHoverWindowHandle) {
3289 foundHoveredWindow = true;
Jeff Brownb88102f2010-09-08 11:49:43 -07003290 }
3291 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07003292
Jeff Brown9302c872011-07-13 22:51:29 -07003293 if (!foundHoveredWindow) {
3294 mLastHoverWindowHandle = NULL;
3295 }
3296
3297 if (mFocusedWindowHandle != newFocusedWindowHandle) {
3298 if (mFocusedWindowHandle != NULL) {
Jeff Brownb6997262010-10-08 22:31:17 -07003299#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00003300 ALOGD("Focus left window: %s",
Jeff Browncc4f7db2011-08-30 20:34:48 -07003301 mFocusedWindowHandle->getName().string());
Jeff Brownb6997262010-10-08 22:31:17 -07003302#endif
Jeff Browncc4f7db2011-08-30 20:34:48 -07003303 sp<InputChannel> focusedInputChannel = mFocusedWindowHandle->getInputChannel();
3304 if (focusedInputChannel != NULL) {
Christopher Tated9be36c2011-08-16 16:09:33 -07003305 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
3306 "focus left window");
3307 synthesizeCancelationEventsForInputChannelLocked(
Jeff Browncc4f7db2011-08-30 20:34:48 -07003308 focusedInputChannel, options);
Christopher Tated9be36c2011-08-16 16:09:33 -07003309 }
Jeff Brownb6997262010-10-08 22:31:17 -07003310 }
Jeff Brown9302c872011-07-13 22:51:29 -07003311 if (newFocusedWindowHandle != NULL) {
Jeff Brownb6997262010-10-08 22:31:17 -07003312#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00003313 ALOGD("Focus entered window: %s",
Jeff Browncc4f7db2011-08-30 20:34:48 -07003314 newFocusedWindowHandle->getName().string());
Jeff Brownb6997262010-10-08 22:31:17 -07003315#endif
Jeff Brown9302c872011-07-13 22:51:29 -07003316 }
3317 mFocusedWindowHandle = newFocusedWindowHandle;
Jeff Brownb6997262010-10-08 22:31:17 -07003318 }
3319
Jeff Brown9302c872011-07-13 22:51:29 -07003320 for (size_t i = 0; i < mTouchState.windows.size(); i++) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07003321 TouchedWindow& touchedWindow = mTouchState.windows.editItemAt(i);
Jeff Brown9302c872011-07-13 22:51:29 -07003322 if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
Jeff Brownb6997262010-10-08 22:31:17 -07003323#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00003324 ALOGD("Touched window was removed: %s",
Jeff Browncc4f7db2011-08-30 20:34:48 -07003325 touchedWindow.windowHandle->getName().string());
Jeff Brownb6997262010-10-08 22:31:17 -07003326#endif
Jeff Browncc4f7db2011-08-30 20:34:48 -07003327 sp<InputChannel> touchedInputChannel =
3328 touchedWindow.windowHandle->getInputChannel();
3329 if (touchedInputChannel != NULL) {
Christopher Tated9be36c2011-08-16 16:09:33 -07003330 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
3331 "touched window was removed");
3332 synthesizeCancelationEventsForInputChannelLocked(
Jeff Browncc4f7db2011-08-30 20:34:48 -07003333 touchedInputChannel, options);
Christopher Tated9be36c2011-08-16 16:09:33 -07003334 }
Jeff Brown9302c872011-07-13 22:51:29 -07003335 mTouchState.windows.removeAt(i--);
Jeff Brown01ce2e92010-09-26 22:20:12 -07003336 }
3337 }
Jeff Browncc4f7db2011-08-30 20:34:48 -07003338
3339 // Release information for windows that are no longer present.
3340 // This ensures that unused input channels are released promptly.
3341 // Otherwise, they might stick around until the window handle is destroyed
3342 // which might not happen until the next GC.
3343 for (size_t i = 0; i < oldWindowHandles.size(); i++) {
3344 const sp<InputWindowHandle>& oldWindowHandle = oldWindowHandles.itemAt(i);
3345 if (!hasWindowHandleLocked(oldWindowHandle)) {
3346#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00003347 ALOGD("Window went away: %s", oldWindowHandle->getName().string());
Jeff Browncc4f7db2011-08-30 20:34:48 -07003348#endif
3349 oldWindowHandle->releaseInfo();
3350 }
3351 }
Jeff Brownb88102f2010-09-08 11:49:43 -07003352 } // release lock
3353
3354 // Wake up poll loop since it may need to make new input dispatching choices.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07003355 mLooper->wake();
Jeff Brownb88102f2010-09-08 11:49:43 -07003356}
3357
Jeff Brown9302c872011-07-13 22:51:29 -07003358void InputDispatcher::setFocusedApplication(
3359 const sp<InputApplicationHandle>& inputApplicationHandle) {
Jeff Brownb88102f2010-09-08 11:49:43 -07003360#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00003361 ALOGD("setFocusedApplication");
Jeff Brownb88102f2010-09-08 11:49:43 -07003362#endif
3363 { // acquire lock
3364 AutoMutex _l(mLock);
3365
Jeff Browncc4f7db2011-08-30 20:34:48 -07003366 if (inputApplicationHandle != NULL && inputApplicationHandle->updateInfo()) {
Jeff Brown5ea29ab2011-07-27 11:50:51 -07003367 if (mFocusedApplicationHandle != inputApplicationHandle) {
3368 if (mFocusedApplicationHandle != NULL) {
3369 resetTargetsLocked();
Jeff Browncc4f7db2011-08-30 20:34:48 -07003370 mFocusedApplicationHandle->releaseInfo();
Jeff Brown5ea29ab2011-07-27 11:50:51 -07003371 }
3372 mFocusedApplicationHandle = inputApplicationHandle;
3373 }
3374 } else if (mFocusedApplicationHandle != NULL) {
3375 resetTargetsLocked();
Jeff Browncc4f7db2011-08-30 20:34:48 -07003376 mFocusedApplicationHandle->releaseInfo();
Jeff Brown9302c872011-07-13 22:51:29 -07003377 mFocusedApplicationHandle.clear();
Jeff Brownb88102f2010-09-08 11:49:43 -07003378 }
3379
3380#if DEBUG_FOCUS
Jeff Brownb6997262010-10-08 22:31:17 -07003381 //logDispatchStateLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -07003382#endif
3383 } // release lock
3384
3385 // Wake up poll loop since it may need to make new input dispatching choices.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07003386 mLooper->wake();
Jeff Brownb88102f2010-09-08 11:49:43 -07003387}
3388
Jeff Brownb88102f2010-09-08 11:49:43 -07003389void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
3390#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00003391 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
Jeff Brownb88102f2010-09-08 11:49:43 -07003392#endif
3393
3394 bool changed;
3395 { // acquire lock
3396 AutoMutex _l(mLock);
3397
3398 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
Jeff Brown120a4592010-10-27 18:43:51 -07003399 if (mDispatchFrozen && !frozen) {
Jeff Brownb88102f2010-09-08 11:49:43 -07003400 resetANRTimeoutsLocked();
3401 }
3402
Jeff Brown120a4592010-10-27 18:43:51 -07003403 if (mDispatchEnabled && !enabled) {
3404 resetAndDropEverythingLocked("dispatcher is being disabled");
3405 }
3406
Jeff Brownb88102f2010-09-08 11:49:43 -07003407 mDispatchEnabled = enabled;
3408 mDispatchFrozen = frozen;
3409 changed = true;
3410 } else {
3411 changed = false;
3412 }
3413
3414#if DEBUG_FOCUS
Jeff Brownb6997262010-10-08 22:31:17 -07003415 //logDispatchStateLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -07003416#endif
3417 } // release lock
3418
3419 if (changed) {
3420 // Wake up poll loop since it may need to make new input dispatching choices.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07003421 mLooper->wake();
Jeff Brown46b9ac02010-04-22 18:58:52 -07003422 }
3423}
3424
Jeff Brown0029c662011-03-30 02:25:18 -07003425void InputDispatcher::setInputFilterEnabled(bool enabled) {
3426#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00003427 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
Jeff Brown0029c662011-03-30 02:25:18 -07003428#endif
3429
3430 { // acquire lock
3431 AutoMutex _l(mLock);
3432
3433 if (mInputFilterEnabled == enabled) {
3434 return;
3435 }
3436
3437 mInputFilterEnabled = enabled;
3438 resetAndDropEverythingLocked("input filter is being enabled or disabled");
3439 } // release lock
3440
3441 // Wake up poll loop since there might be work to do to drop everything.
3442 mLooper->wake();
3443}
3444
Jeff Browne6504122010-09-27 14:52:15 -07003445bool InputDispatcher::transferTouchFocus(const sp<InputChannel>& fromChannel,
3446 const sp<InputChannel>& toChannel) {
3447#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00003448 ALOGD("transferTouchFocus: fromChannel=%s, toChannel=%s",
Jeff Browne6504122010-09-27 14:52:15 -07003449 fromChannel->getName().string(), toChannel->getName().string());
3450#endif
3451 { // acquire lock
3452 AutoMutex _l(mLock);
3453
Jeff Brown9302c872011-07-13 22:51:29 -07003454 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromChannel);
3455 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toChannel);
3456 if (fromWindowHandle == NULL || toWindowHandle == NULL) {
Jeff Browne6504122010-09-27 14:52:15 -07003457#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00003458 ALOGD("Cannot transfer focus because from or to window not found.");
Jeff Browne6504122010-09-27 14:52:15 -07003459#endif
3460 return false;
3461 }
Jeff Brown9302c872011-07-13 22:51:29 -07003462 if (fromWindowHandle == toWindowHandle) {
Jeff Browne6504122010-09-27 14:52:15 -07003463#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00003464 ALOGD("Trivial transfer to same window.");
Jeff Browne6504122010-09-27 14:52:15 -07003465#endif
3466 return true;
3467 }
3468
3469 bool found = false;
3470 for (size_t i = 0; i < mTouchState.windows.size(); i++) {
3471 const TouchedWindow& touchedWindow = mTouchState.windows[i];
Jeff Brown9302c872011-07-13 22:51:29 -07003472 if (touchedWindow.windowHandle == fromWindowHandle) {
Jeff Browne6504122010-09-27 14:52:15 -07003473 int32_t oldTargetFlags = touchedWindow.targetFlags;
3474 BitSet32 pointerIds = touchedWindow.pointerIds;
3475
3476 mTouchState.windows.removeAt(i);
3477
Jeff Brown46e75292010-11-10 16:53:45 -08003478 int32_t newTargetFlags = oldTargetFlags
Jeff Browna032cc02011-03-07 16:56:21 -08003479 & (InputTarget::FLAG_FOREGROUND
3480 | InputTarget::FLAG_SPLIT | InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brown9302c872011-07-13 22:51:29 -07003481 mTouchState.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Jeff Browne6504122010-09-27 14:52:15 -07003482
3483 found = true;
3484 break;
3485 }
3486 }
3487
3488 if (! found) {
3489#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00003490 ALOGD("Focus transfer failed because from window did not have focus.");
Jeff Browne6504122010-09-27 14:52:15 -07003491#endif
3492 return false;
3493 }
3494
Jeff Brown9c9f1a32010-10-11 18:32:20 -07003495 ssize_t fromConnectionIndex = getConnectionIndexLocked(fromChannel);
3496 ssize_t toConnectionIndex = getConnectionIndexLocked(toChannel);
3497 if (fromConnectionIndex >= 0 && toConnectionIndex >= 0) {
3498 sp<Connection> fromConnection = mConnectionsByReceiveFd.valueAt(fromConnectionIndex);
3499 sp<Connection> toConnection = mConnectionsByReceiveFd.valueAt(toConnectionIndex);
3500
3501 fromConnection->inputState.copyPointerStateTo(toConnection->inputState);
Jeff Brownda3d5a92011-03-29 15:11:34 -07003502 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Jeff Brown9c9f1a32010-10-11 18:32:20 -07003503 "transferring touch focus from this window to another window");
Jeff Brownda3d5a92011-03-29 15:11:34 -07003504 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Jeff Brown9c9f1a32010-10-11 18:32:20 -07003505 }
3506
Jeff Browne6504122010-09-27 14:52:15 -07003507#if DEBUG_FOCUS
3508 logDispatchStateLocked();
3509#endif
3510 } // release lock
3511
3512 // Wake up poll loop since it may need to make new input dispatching choices.
3513 mLooper->wake();
3514 return true;
3515}
3516
Jeff Brown120a4592010-10-27 18:43:51 -07003517void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
3518#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00003519 ALOGD("Resetting and dropping all events (%s).", reason);
Jeff Brown120a4592010-10-27 18:43:51 -07003520#endif
3521
Jeff Brownda3d5a92011-03-29 15:11:34 -07003522 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
3523 synthesizeCancelationEventsForAllConnectionsLocked(options);
Jeff Brown120a4592010-10-27 18:43:51 -07003524
3525 resetKeyRepeatLocked();
3526 releasePendingEventLocked();
3527 drainInboundQueueLocked();
3528 resetTargetsLocked();
3529
3530 mTouchState.reset();
Jeff Brown9302c872011-07-13 22:51:29 -07003531 mLastHoverWindowHandle.clear();
Jeff Brown120a4592010-10-27 18:43:51 -07003532}
3533
Jeff Brownb88102f2010-09-08 11:49:43 -07003534void InputDispatcher::logDispatchStateLocked() {
3535 String8 dump;
3536 dumpDispatchStateLocked(dump);
Jeff Brown2a95c2a2010-09-16 12:31:46 -07003537
3538 char* text = dump.lockBuffer(dump.size());
3539 char* start = text;
3540 while (*start != '\0') {
3541 char* end = strchr(start, '\n');
3542 if (*end == '\n') {
3543 *(end++) = '\0';
3544 }
Steve Block5baa3a62011-12-20 16:23:08 +00003545 ALOGD("%s", start);
Jeff Brown2a95c2a2010-09-16 12:31:46 -07003546 start = end;
3547 }
Jeff Brownb88102f2010-09-08 11:49:43 -07003548}
3549
3550void InputDispatcher::dumpDispatchStateLocked(String8& dump) {
Jeff Brownf2f48712010-10-01 17:46:21 -07003551 dump.appendFormat(INDENT "DispatchEnabled: %d\n", mDispatchEnabled);
3552 dump.appendFormat(INDENT "DispatchFrozen: %d\n", mDispatchFrozen);
Jeff Brownb88102f2010-09-08 11:49:43 -07003553
Jeff Brown9302c872011-07-13 22:51:29 -07003554 if (mFocusedApplicationHandle != NULL) {
Jeff Brownf2f48712010-10-01 17:46:21 -07003555 dump.appendFormat(INDENT "FocusedApplication: name='%s', dispatchingTimeout=%0.3fms\n",
Jeff Browncc4f7db2011-08-30 20:34:48 -07003556 mFocusedApplicationHandle->getName().string(),
3557 mFocusedApplicationHandle->getDispatchingTimeout(
3558 DEFAULT_INPUT_DISPATCHING_TIMEOUT) / 1000000.0);
Jeff Brownb88102f2010-09-08 11:49:43 -07003559 } else {
Jeff Brownf2f48712010-10-01 17:46:21 -07003560 dump.append(INDENT "FocusedApplication: <null>\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003561 }
Jeff Brownf2f48712010-10-01 17:46:21 -07003562 dump.appendFormat(INDENT "FocusedWindow: name='%s'\n",
Jeff Browncc4f7db2011-08-30 20:34:48 -07003563 mFocusedWindowHandle != NULL ? mFocusedWindowHandle->getName().string() : "<null>");
Jeff Brownf2f48712010-10-01 17:46:21 -07003564
3565 dump.appendFormat(INDENT "TouchDown: %s\n", toString(mTouchState.down));
3566 dump.appendFormat(INDENT "TouchSplit: %s\n", toString(mTouchState.split));
Jeff Brown95712852011-01-04 19:41:59 -08003567 dump.appendFormat(INDENT "TouchDeviceId: %d\n", mTouchState.deviceId);
Jeff Brown58a2da82011-01-25 16:02:22 -08003568 dump.appendFormat(INDENT "TouchSource: 0x%08x\n", mTouchState.source);
Jeff Brownf2f48712010-10-01 17:46:21 -07003569 if (!mTouchState.windows.isEmpty()) {
3570 dump.append(INDENT "TouchedWindows:\n");
3571 for (size_t i = 0; i < mTouchState.windows.size(); i++) {
3572 const TouchedWindow& touchedWindow = mTouchState.windows[i];
3573 dump.appendFormat(INDENT2 "%d: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
Jeff Browncc4f7db2011-08-30 20:34:48 -07003574 i, touchedWindow.windowHandle->getName().string(),
3575 touchedWindow.pointerIds.value,
Jeff Brownf2f48712010-10-01 17:46:21 -07003576 touchedWindow.targetFlags);
3577 }
3578 } else {
3579 dump.append(INDENT "TouchedWindows: <none>\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003580 }
3581
Jeff Brown9302c872011-07-13 22:51:29 -07003582 if (!mWindowHandles.isEmpty()) {
Jeff Brownf2f48712010-10-01 17:46:21 -07003583 dump.append(INDENT "Windows:\n");
Jeff Brown9302c872011-07-13 22:51:29 -07003584 for (size_t i = 0; i < mWindowHandles.size(); i++) {
3585 const sp<InputWindowHandle>& windowHandle = mWindowHandles.itemAt(i);
Jeff Browncc4f7db2011-08-30 20:34:48 -07003586 const InputWindowInfo* windowInfo = windowHandle->getInfo();
3587
Jeff Brownf2f48712010-10-01 17:46:21 -07003588 dump.appendFormat(INDENT2 "%d: name='%s', paused=%s, hasFocus=%s, hasWallpaper=%s, "
3589 "visible=%s, canReceiveKeys=%s, flags=0x%08x, type=0x%08x, layer=%d, "
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003590 "frame=[%d,%d][%d,%d], scale=%f, "
Jeff Brownfbf09772011-01-16 14:06:57 -08003591 "touchableRegion=",
Jeff Browncc4f7db2011-08-30 20:34:48 -07003592 i, windowInfo->name.string(),
3593 toString(windowInfo->paused),
3594 toString(windowInfo->hasFocus),
3595 toString(windowInfo->hasWallpaper),
3596 toString(windowInfo->visible),
3597 toString(windowInfo->canReceiveKeys),
3598 windowInfo->layoutParamsFlags, windowInfo->layoutParamsType,
3599 windowInfo->layer,
3600 windowInfo->frameLeft, windowInfo->frameTop,
3601 windowInfo->frameRight, windowInfo->frameBottom,
3602 windowInfo->scaleFactor);
3603 dumpRegion(dump, windowInfo->touchableRegion);
3604 dump.appendFormat(", inputFeatures=0x%08x", windowInfo->inputFeatures);
Jeff Brownfbf09772011-01-16 14:06:57 -08003605 dump.appendFormat(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%0.3fms\n",
Jeff Browncc4f7db2011-08-30 20:34:48 -07003606 windowInfo->ownerPid, windowInfo->ownerUid,
3607 windowInfo->dispatchingTimeout / 1000000.0);
Jeff Brownf2f48712010-10-01 17:46:21 -07003608 }
3609 } else {
3610 dump.append(INDENT "Windows: <none>\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003611 }
3612
Jeff Brownf2f48712010-10-01 17:46:21 -07003613 if (!mMonitoringChannels.isEmpty()) {
3614 dump.append(INDENT "MonitoringChannels:\n");
3615 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
3616 const sp<InputChannel>& channel = mMonitoringChannels[i];
3617 dump.appendFormat(INDENT2 "%d: '%s'\n", i, channel->getName().string());
3618 }
3619 } else {
3620 dump.append(INDENT "MonitoringChannels: <none>\n");
3621 }
Jeff Brown519e0242010-09-15 15:18:56 -07003622
Jeff Brownf2f48712010-10-01 17:46:21 -07003623 dump.appendFormat(INDENT "InboundQueue: length=%u\n", mInboundQueue.count());
3624
3625 if (!mActiveConnections.isEmpty()) {
3626 dump.append(INDENT "ActiveConnections:\n");
3627 for (size_t i = 0; i < mActiveConnections.size(); i++) {
3628 const Connection* connection = mActiveConnections[i];
Jeff Brown76860e32010-10-25 17:37:46 -07003629 dump.appendFormat(INDENT2 "%d: '%s', status=%s, outboundQueueLength=%u, "
Jeff Brownb6997262010-10-08 22:31:17 -07003630 "inputState.isNeutral=%s\n",
Jeff Brownf2f48712010-10-01 17:46:21 -07003631 i, connection->getInputChannelName(), connection->getStatusLabel(),
3632 connection->outboundQueue.count(),
Jeff Brownb6997262010-10-08 22:31:17 -07003633 toString(connection->inputState.isNeutral()));
Jeff Brownf2f48712010-10-01 17:46:21 -07003634 }
3635 } else {
3636 dump.append(INDENT "ActiveConnections: <none>\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003637 }
3638
3639 if (isAppSwitchPendingLocked()) {
Jeff Brownf2f48712010-10-01 17:46:21 -07003640 dump.appendFormat(INDENT "AppSwitch: pending, due in %01.1fms\n",
Jeff Brownb88102f2010-09-08 11:49:43 -07003641 (mAppSwitchDueTime - now()) / 1000000.0);
3642 } else {
Jeff Brownf2f48712010-10-01 17:46:21 -07003643 dump.append(INDENT "AppSwitch: not pending\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003644 }
3645}
3646
Jeff Brown928e0542011-01-10 11:17:36 -08003647status_t InputDispatcher::registerInputChannel(const sp<InputChannel>& inputChannel,
3648 const sp<InputWindowHandle>& inputWindowHandle, bool monitor) {
Jeff Brown9c3cda02010-06-15 01:31:58 -07003649#if DEBUG_REGISTRATION
Steve Block5baa3a62011-12-20 16:23:08 +00003650 ALOGD("channel '%s' ~ registerInputChannel - monitor=%s", inputChannel->getName().string(),
Jeff Brownb88102f2010-09-08 11:49:43 -07003651 toString(monitor));
Jeff Brown9c3cda02010-06-15 01:31:58 -07003652#endif
3653
Jeff Brown46b9ac02010-04-22 18:58:52 -07003654 { // acquire lock
3655 AutoMutex _l(mLock);
3656
Jeff Brown519e0242010-09-15 15:18:56 -07003657 if (getConnectionIndexLocked(inputChannel) >= 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00003658 ALOGW("Attempted to register already registered input channel '%s'",
Jeff Brown46b9ac02010-04-22 18:58:52 -07003659 inputChannel->getName().string());
3660 return BAD_VALUE;
3661 }
3662
Jeff Browncc4f7db2011-08-30 20:34:48 -07003663 sp<Connection> connection = new Connection(inputChannel, inputWindowHandle, monitor);
Jeff Brown46b9ac02010-04-22 18:58:52 -07003664 status_t status = connection->initialize();
3665 if (status) {
Steve Block3762c312012-01-06 19:20:56 +00003666 ALOGE("Failed to initialize input publisher for input channel '%s', status=%d",
Jeff Brown46b9ac02010-04-22 18:58:52 -07003667 inputChannel->getName().string(), status);
3668 return status;
3669 }
3670
Jeff Brown2cbecea2010-08-17 15:59:26 -07003671 int32_t receiveFd = inputChannel->getReceivePipeFd();
Jeff Brown46b9ac02010-04-22 18:58:52 -07003672 mConnectionsByReceiveFd.add(receiveFd, connection);
Jeff Brown9c3cda02010-06-15 01:31:58 -07003673
Jeff Brownb88102f2010-09-08 11:49:43 -07003674 if (monitor) {
3675 mMonitoringChannels.push(inputChannel);
3676 }
3677
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07003678 mLooper->addFd(receiveFd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
Jeff Brown2cbecea2010-08-17 15:59:26 -07003679
Jeff Brown9c3cda02010-06-15 01:31:58 -07003680 runCommandsLockedInterruptible();
Jeff Brown46b9ac02010-04-22 18:58:52 -07003681 } // release lock
Jeff Brown46b9ac02010-04-22 18:58:52 -07003682 return OK;
3683}
3684
3685status_t InputDispatcher::unregisterInputChannel(const sp<InputChannel>& inputChannel) {
Jeff Brown9c3cda02010-06-15 01:31:58 -07003686#if DEBUG_REGISTRATION
Steve Block5baa3a62011-12-20 16:23:08 +00003687 ALOGD("channel '%s' ~ unregisterInputChannel", inputChannel->getName().string());
Jeff Brown9c3cda02010-06-15 01:31:58 -07003688#endif
3689
Jeff Brown46b9ac02010-04-22 18:58:52 -07003690 { // acquire lock
3691 AutoMutex _l(mLock);
3692
Jeff Browncc4f7db2011-08-30 20:34:48 -07003693 status_t status = unregisterInputChannelLocked(inputChannel, false /*notify*/);
3694 if (status) {
3695 return status;
Jeff Brown46b9ac02010-04-22 18:58:52 -07003696 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07003697 } // release lock
3698
Jeff Brown46b9ac02010-04-22 18:58:52 -07003699 // Wake the poll loop because removing the connection may have changed the current
3700 // synchronization state.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07003701 mLooper->wake();
Jeff Brown46b9ac02010-04-22 18:58:52 -07003702 return OK;
3703}
3704
Jeff Browncc4f7db2011-08-30 20:34:48 -07003705status_t InputDispatcher::unregisterInputChannelLocked(const sp<InputChannel>& inputChannel,
3706 bool notify) {
3707 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
3708 if (connectionIndex < 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00003709 ALOGW("Attempted to unregister already unregistered input channel '%s'",
Jeff Browncc4f7db2011-08-30 20:34:48 -07003710 inputChannel->getName().string());
3711 return BAD_VALUE;
3712 }
3713
3714 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
3715 mConnectionsByReceiveFd.removeItemsAt(connectionIndex);
3716
3717 if (connection->monitor) {
3718 removeMonitorChannelLocked(inputChannel);
3719 }
3720
3721 mLooper->removeFd(inputChannel->getReceivePipeFd());
3722
3723 nsecs_t currentTime = now();
3724 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
3725
3726 runCommandsLockedInterruptible();
3727
3728 connection->status = Connection::STATUS_ZOMBIE;
3729 return OK;
3730}
3731
3732void InputDispatcher::removeMonitorChannelLocked(const sp<InputChannel>& inputChannel) {
3733 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
3734 if (mMonitoringChannels[i] == inputChannel) {
3735 mMonitoringChannels.removeAt(i);
3736 break;
3737 }
3738 }
3739}
3740
Jeff Brown519e0242010-09-15 15:18:56 -07003741ssize_t InputDispatcher::getConnectionIndexLocked(const sp<InputChannel>& inputChannel) {
Jeff Brown2cbecea2010-08-17 15:59:26 -07003742 ssize_t connectionIndex = mConnectionsByReceiveFd.indexOfKey(inputChannel->getReceivePipeFd());
3743 if (connectionIndex >= 0) {
3744 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
3745 if (connection->inputChannel.get() == inputChannel.get()) {
3746 return connectionIndex;
3747 }
3748 }
3749
3750 return -1;
3751}
3752
Jeff Brown46b9ac02010-04-22 18:58:52 -07003753void InputDispatcher::activateConnectionLocked(Connection* connection) {
3754 for (size_t i = 0; i < mActiveConnections.size(); i++) {
3755 if (mActiveConnections.itemAt(i) == connection) {
3756 return;
3757 }
3758 }
3759 mActiveConnections.add(connection);
3760}
3761
3762void InputDispatcher::deactivateConnectionLocked(Connection* connection) {
3763 for (size_t i = 0; i < mActiveConnections.size(); i++) {
3764 if (mActiveConnections.itemAt(i) == connection) {
3765 mActiveConnections.removeAt(i);
3766 return;
3767 }
3768 }
3769}
3770
Jeff Brown9c3cda02010-06-15 01:31:58 -07003771void InputDispatcher::onDispatchCycleStartedLocked(
Jeff Brown7fbdc842010-06-17 20:52:56 -07003772 nsecs_t currentTime, const sp<Connection>& connection) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07003773}
3774
Jeff Brown9c3cda02010-06-15 01:31:58 -07003775void InputDispatcher::onDispatchCycleFinishedLocked(
Jeff Brown3915bb82010-11-05 15:02:16 -07003776 nsecs_t currentTime, const sp<Connection>& connection, bool handled) {
3777 CommandEntry* commandEntry = postCommandLocked(
3778 & InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
3779 commandEntry->connection = connection;
3780 commandEntry->handled = handled;
Jeff Brown46b9ac02010-04-22 18:58:52 -07003781}
3782
Jeff Brown9c3cda02010-06-15 01:31:58 -07003783void InputDispatcher::onDispatchCycleBrokenLocked(
Jeff Brown7fbdc842010-06-17 20:52:56 -07003784 nsecs_t currentTime, const sp<Connection>& connection) {
Steve Block3762c312012-01-06 19:20:56 +00003785 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Jeff Brown46b9ac02010-04-22 18:58:52 -07003786 connection->getInputChannelName());
3787
Jeff Brown9c3cda02010-06-15 01:31:58 -07003788 CommandEntry* commandEntry = postCommandLocked(
3789 & InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
Jeff Brown7fbdc842010-06-17 20:52:56 -07003790 commandEntry->connection = connection;
Jeff Brown46b9ac02010-04-22 18:58:52 -07003791}
3792
Jeff Brown519e0242010-09-15 15:18:56 -07003793void InputDispatcher::onANRLocked(
Jeff Brown9302c872011-07-13 22:51:29 -07003794 nsecs_t currentTime, const sp<InputApplicationHandle>& applicationHandle,
3795 const sp<InputWindowHandle>& windowHandle,
Jeff Brown519e0242010-09-15 15:18:56 -07003796 nsecs_t eventTime, nsecs_t waitStartTime) {
Steve Block6215d3f2012-01-04 20:05:49 +00003797 ALOGI("Application is not responding: %s. "
Jeff Brown519e0242010-09-15 15:18:56 -07003798 "%01.1fms since event, %01.1fms since wait started",
Jeff Brown9302c872011-07-13 22:51:29 -07003799 getApplicationWindowLabelLocked(applicationHandle, windowHandle).string(),
Jeff Brown519e0242010-09-15 15:18:56 -07003800 (currentTime - eventTime) / 1000000.0,
3801 (currentTime - waitStartTime) / 1000000.0);
3802
3803 CommandEntry* commandEntry = postCommandLocked(
3804 & InputDispatcher::doNotifyANRLockedInterruptible);
Jeff Brown9302c872011-07-13 22:51:29 -07003805 commandEntry->inputApplicationHandle = applicationHandle;
3806 commandEntry->inputWindowHandle = windowHandle;
Jeff Brown519e0242010-09-15 15:18:56 -07003807}
3808
Jeff Brownb88102f2010-09-08 11:49:43 -07003809void InputDispatcher::doNotifyConfigurationChangedInterruptible(
3810 CommandEntry* commandEntry) {
3811 mLock.unlock();
3812
3813 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
3814
3815 mLock.lock();
3816}
3817
Jeff Brown9c3cda02010-06-15 01:31:58 -07003818void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(
3819 CommandEntry* commandEntry) {
Jeff Brown7fbdc842010-06-17 20:52:56 -07003820 sp<Connection> connection = commandEntry->connection;
Jeff Brown9c3cda02010-06-15 01:31:58 -07003821
Jeff Brown7fbdc842010-06-17 20:52:56 -07003822 if (connection->status != Connection::STATUS_ZOMBIE) {
3823 mLock.unlock();
Jeff Brown9c3cda02010-06-15 01:31:58 -07003824
Jeff Brown928e0542011-01-10 11:17:36 -08003825 mPolicy->notifyInputChannelBroken(connection->inputWindowHandle);
Jeff Brown7fbdc842010-06-17 20:52:56 -07003826
3827 mLock.lock();
3828 }
Jeff Brown9c3cda02010-06-15 01:31:58 -07003829}
3830
Jeff Brown519e0242010-09-15 15:18:56 -07003831void InputDispatcher::doNotifyANRLockedInterruptible(
Jeff Brown9c3cda02010-06-15 01:31:58 -07003832 CommandEntry* commandEntry) {
Jeff Brown519e0242010-09-15 15:18:56 -07003833 mLock.unlock();
Jeff Brown9c3cda02010-06-15 01:31:58 -07003834
Jeff Brown519e0242010-09-15 15:18:56 -07003835 nsecs_t newTimeout = mPolicy->notifyANR(
Jeff Brown928e0542011-01-10 11:17:36 -08003836 commandEntry->inputApplicationHandle, commandEntry->inputWindowHandle);
Jeff Brown9c3cda02010-06-15 01:31:58 -07003837
Jeff Brown519e0242010-09-15 15:18:56 -07003838 mLock.lock();
Jeff Brown7fbdc842010-06-17 20:52:56 -07003839
Jeff Brown9302c872011-07-13 22:51:29 -07003840 resumeAfterTargetsNotReadyTimeoutLocked(newTimeout,
3841 commandEntry->inputWindowHandle != NULL
Jeff Browncc4f7db2011-08-30 20:34:48 -07003842 ? commandEntry->inputWindowHandle->getInputChannel() : NULL);
Jeff Brown9c3cda02010-06-15 01:31:58 -07003843}
3844
Jeff Brownb88102f2010-09-08 11:49:43 -07003845void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
3846 CommandEntry* commandEntry) {
3847 KeyEntry* entry = commandEntry->keyEntry;
Jeff Brown1f245102010-11-18 20:53:46 -08003848
3849 KeyEvent event;
3850 initializeKeyEvent(&event, entry);
Jeff Brownb88102f2010-09-08 11:49:43 -07003851
3852 mLock.unlock();
3853
Jeff Brown905805a2011-10-12 13:57:59 -07003854 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(commandEntry->inputWindowHandle,
Jeff Brown1f245102010-11-18 20:53:46 -08003855 &event, entry->policyFlags);
Jeff Brownb88102f2010-09-08 11:49:43 -07003856
3857 mLock.lock();
3858
Jeff Brown905805a2011-10-12 13:57:59 -07003859 if (delay < 0) {
3860 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
3861 } else if (!delay) {
3862 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
3863 } else {
3864 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
3865 entry->interceptKeyWakeupTime = now() + delay;
3866 }
Jeff Brownac386072011-07-20 15:19:50 -07003867 entry->release();
Jeff Brownb88102f2010-09-08 11:49:43 -07003868}
3869
Jeff Brown3915bb82010-11-05 15:02:16 -07003870void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(
3871 CommandEntry* commandEntry) {
3872 sp<Connection> connection = commandEntry->connection;
3873 bool handled = commandEntry->handled;
3874
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003875 bool skipNext = false;
Jeff Brown49ed71d2010-12-06 17:13:33 -08003876 if (!connection->outboundQueue.isEmpty()) {
Jeff Brownac386072011-07-20 15:19:50 -07003877 DispatchEntry* dispatchEntry = connection->outboundQueue.head;
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003878 if (dispatchEntry->inProgress) {
3879 if (dispatchEntry->eventEntry->type == EventEntry::TYPE_KEY) {
3880 KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry);
3881 skipNext = afterKeyEventLockedInterruptible(connection,
3882 dispatchEntry, keyEntry, handled);
3883 } else if (dispatchEntry->eventEntry->type == EventEntry::TYPE_MOTION) {
3884 MotionEntry* motionEntry = static_cast<MotionEntry*>(dispatchEntry->eventEntry);
3885 skipNext = afterMotionEventLockedInterruptible(connection,
3886 dispatchEntry, motionEntry, handled);
Jeff Brown49ed71d2010-12-06 17:13:33 -08003887 }
Jeff Brown3915bb82010-11-05 15:02:16 -07003888 }
3889 }
3890
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003891 if (!skipNext) {
3892 startNextDispatchCycleLocked(now(), connection);
3893 }
3894}
3895
3896bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
3897 DispatchEntry* dispatchEntry, KeyEntry* keyEntry, bool handled) {
3898 if (!(keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK)) {
3899 // Get the fallback key state.
3900 // Clear it out after dispatching the UP.
3901 int32_t originalKeyCode = keyEntry->keyCode;
3902 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
3903 if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
3904 connection->inputState.removeFallbackKey(originalKeyCode);
3905 }
3906
3907 if (handled || !dispatchEntry->hasForegroundTarget()) {
3908 // If the application handles the original key for which we previously
3909 // generated a fallback or if the window is not a foreground window,
3910 // then cancel the associated fallback key, if any.
3911 if (fallbackKeyCode != -1) {
3912 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
3913 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
3914 "application handled the original non-fallback key "
3915 "or is no longer a foreground target, "
3916 "canceling previously dispatched fallback key");
3917 options.keyCode = fallbackKeyCode;
3918 synthesizeCancelationEventsForConnectionLocked(connection, options);
3919 }
3920 connection->inputState.removeFallbackKey(originalKeyCode);
3921 }
3922 } else {
3923 // If the application did not handle a non-fallback key, first check
3924 // that we are in a good state to perform unhandled key event processing
3925 // Then ask the policy what to do with it.
3926 bool initialDown = keyEntry->action == AKEY_EVENT_ACTION_DOWN
3927 && keyEntry->repeatCount == 0;
3928 if (fallbackKeyCode == -1 && !initialDown) {
3929#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00003930 ALOGD("Unhandled key event: Skipping unhandled key event processing "
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003931 "since this is not an initial down. "
3932 "keyCode=%d, action=%d, repeatCount=%d",
3933 originalKeyCode, keyEntry->action, keyEntry->repeatCount);
3934#endif
3935 return false;
3936 }
3937
3938 // Dispatch the unhandled key to the policy.
3939#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00003940 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003941 "keyCode=%d, action=%d, repeatCount=%d",
3942 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount);
3943#endif
3944 KeyEvent event;
3945 initializeKeyEvent(&event, keyEntry);
3946
3947 mLock.unlock();
3948
3949 bool fallback = mPolicy->dispatchUnhandledKey(connection->inputWindowHandle,
3950 &event, keyEntry->policyFlags, &event);
3951
3952 mLock.lock();
3953
3954 if (connection->status != Connection::STATUS_NORMAL) {
3955 connection->inputState.removeFallbackKey(originalKeyCode);
3956 return true; // skip next cycle
3957 }
3958
Steve Blockec193de2012-01-09 18:35:44 +00003959 ALOG_ASSERT(connection->outboundQueue.head == dispatchEntry);
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003960
3961 // Latch the fallback keycode for this key on an initial down.
3962 // The fallback keycode cannot change at any other point in the lifecycle.
3963 if (initialDown) {
3964 if (fallback) {
3965 fallbackKeyCode = event.getKeyCode();
3966 } else {
3967 fallbackKeyCode = AKEYCODE_UNKNOWN;
3968 }
3969 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
3970 }
3971
Steve Blockec193de2012-01-09 18:35:44 +00003972 ALOG_ASSERT(fallbackKeyCode != -1);
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003973
3974 // Cancel the fallback key if the policy decides not to send it anymore.
3975 // We will continue to dispatch the key to the policy but we will no
3976 // longer dispatch a fallback key to the application.
3977 if (fallbackKeyCode != AKEYCODE_UNKNOWN
3978 && (!fallback || fallbackKeyCode != event.getKeyCode())) {
3979#if DEBUG_OUTBOUND_EVENT_DETAILS
3980 if (fallback) {
Steve Block5baa3a62011-12-20 16:23:08 +00003981 ALOGD("Unhandled key event: Policy requested to send key %d"
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003982 "as a fallback for %d, but on the DOWN it had requested "
3983 "to send %d instead. Fallback canceled.",
3984 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
3985 } else {
Steve Block5baa3a62011-12-20 16:23:08 +00003986 ALOGD("Unhandled key event: Policy did not request fallback for %d,"
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003987 "but on the DOWN it had requested to send %d. "
3988 "Fallback canceled.",
3989 originalKeyCode, fallbackKeyCode);
3990 }
3991#endif
3992
3993 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
3994 "canceling fallback, policy no longer desires it");
3995 options.keyCode = fallbackKeyCode;
3996 synthesizeCancelationEventsForConnectionLocked(connection, options);
3997
3998 fallback = false;
3999 fallbackKeyCode = AKEYCODE_UNKNOWN;
4000 if (keyEntry->action != AKEY_EVENT_ACTION_UP) {
4001 connection->inputState.setFallbackKey(originalKeyCode,
4002 fallbackKeyCode);
4003 }
4004 }
4005
4006#if DEBUG_OUTBOUND_EVENT_DETAILS
4007 {
4008 String8 msg;
4009 const KeyedVector<int32_t, int32_t>& fallbackKeys =
4010 connection->inputState.getFallbackKeys();
4011 for (size_t i = 0; i < fallbackKeys.size(); i++) {
4012 msg.appendFormat(", %d->%d", fallbackKeys.keyAt(i),
4013 fallbackKeys.valueAt(i));
4014 }
Steve Block5baa3a62011-12-20 16:23:08 +00004015 ALOGD("Unhandled key event: %d currently tracked fallback keys%s.",
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07004016 fallbackKeys.size(), msg.string());
4017 }
4018#endif
4019
4020 if (fallback) {
4021 // Restart the dispatch cycle using the fallback key.
4022 keyEntry->eventTime = event.getEventTime();
4023 keyEntry->deviceId = event.getDeviceId();
4024 keyEntry->source = event.getSource();
4025 keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
4026 keyEntry->keyCode = fallbackKeyCode;
4027 keyEntry->scanCode = event.getScanCode();
4028 keyEntry->metaState = event.getMetaState();
4029 keyEntry->repeatCount = event.getRepeatCount();
4030 keyEntry->downTime = event.getDownTime();
4031 keyEntry->syntheticRepeat = false;
4032
4033#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00004034 ALOGD("Unhandled key event: Dispatching fallback key. "
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07004035 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
4036 originalKeyCode, fallbackKeyCode, keyEntry->metaState);
4037#endif
4038
4039 dispatchEntry->inProgress = false;
4040 startDispatchCycleLocked(now(), connection);
4041 return true; // already started next cycle
4042 } else {
4043#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00004044 ALOGD("Unhandled key event: No fallback key.");
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07004045#endif
4046 }
4047 }
4048 }
4049 return false;
4050}
4051
4052bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
4053 DispatchEntry* dispatchEntry, MotionEntry* motionEntry, bool handled) {
4054 return false;
Jeff Brown3915bb82010-11-05 15:02:16 -07004055}
4056
Jeff Brownb88102f2010-09-08 11:49:43 -07004057void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
4058 mLock.unlock();
4059
Jeff Brown01ce2e92010-09-26 22:20:12 -07004060 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
Jeff Brownb88102f2010-09-08 11:49:43 -07004061
4062 mLock.lock();
4063}
4064
Jeff Brown3915bb82010-11-05 15:02:16 -07004065void InputDispatcher::initializeKeyEvent(KeyEvent* event, const KeyEntry* entry) {
4066 event->initialize(entry->deviceId, entry->source, entry->action, entry->flags,
4067 entry->keyCode, entry->scanCode, entry->metaState, entry->repeatCount,
4068 entry->downTime, entry->eventTime);
4069}
4070
Jeff Brown519e0242010-09-15 15:18:56 -07004071void InputDispatcher::updateDispatchStatisticsLocked(nsecs_t currentTime, const EventEntry* entry,
4072 int32_t injectionResult, nsecs_t timeSpentWaitingForApplication) {
4073 // TODO Write some statistics about how long we spend waiting.
Jeff Brownb88102f2010-09-08 11:49:43 -07004074}
4075
4076void InputDispatcher::dump(String8& dump) {
Jeff Brown89ef0722011-08-10 16:25:21 -07004077 AutoMutex _l(mLock);
4078
Jeff Brownf2f48712010-10-01 17:46:21 -07004079 dump.append("Input Dispatcher State:\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07004080 dumpDispatchStateLocked(dump);
Jeff Brown214eaf42011-05-26 19:17:02 -07004081
4082 dump.append(INDENT "Configuration:\n");
4083 dump.appendFormat(INDENT2 "MaxEventsPerSecond: %d\n", mConfig.maxEventsPerSecond);
4084 dump.appendFormat(INDENT2 "KeyRepeatDelay: %0.1fms\n", mConfig.keyRepeatDelay * 0.000001f);
4085 dump.appendFormat(INDENT2 "KeyRepeatTimeout: %0.1fms\n", mConfig.keyRepeatTimeout * 0.000001f);
Jeff Brownb88102f2010-09-08 11:49:43 -07004086}
4087
Jeff Brown89ef0722011-08-10 16:25:21 -07004088void InputDispatcher::monitor() {
4089 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
4090 mLock.lock();
Jeff Brown112b5f52012-01-27 17:32:06 -08004091 mLooper->wake();
4092 mDispatcherIsAliveCondition.wait(mLock);
Jeff Brown89ef0722011-08-10 16:25:21 -07004093 mLock.unlock();
4094}
4095
Jeff Brown9c3cda02010-06-15 01:31:58 -07004096
Jeff Brown519e0242010-09-15 15:18:56 -07004097// --- InputDispatcher::Queue ---
4098
4099template <typename T>
4100uint32_t InputDispatcher::Queue<T>::count() const {
4101 uint32_t result = 0;
Jeff Brownac386072011-07-20 15:19:50 -07004102 for (const T* entry = head; entry; entry = entry->next) {
Jeff Brown519e0242010-09-15 15:18:56 -07004103 result += 1;
4104 }
4105 return result;
4106}
4107
4108
Jeff Brownac386072011-07-20 15:19:50 -07004109// --- InputDispatcher::InjectionState ---
Jeff Brown46b9ac02010-04-22 18:58:52 -07004110
Jeff Brownac386072011-07-20 15:19:50 -07004111InputDispatcher::InjectionState::InjectionState(int32_t injectorPid, int32_t injectorUid) :
4112 refCount(1),
4113 injectorPid(injectorPid), injectorUid(injectorUid),
4114 injectionResult(INPUT_EVENT_INJECTION_PENDING), injectionIsAsync(false),
4115 pendingForegroundDispatches(0) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07004116}
4117
Jeff Brownac386072011-07-20 15:19:50 -07004118InputDispatcher::InjectionState::~InjectionState() {
Jeff Brown01ce2e92010-09-26 22:20:12 -07004119}
4120
Jeff Brownac386072011-07-20 15:19:50 -07004121void InputDispatcher::InjectionState::release() {
4122 refCount -= 1;
4123 if (refCount == 0) {
4124 delete this;
4125 } else {
Steve Blockec193de2012-01-09 18:35:44 +00004126 ALOG_ASSERT(refCount > 0);
Jeff Brown01ce2e92010-09-26 22:20:12 -07004127 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07004128}
4129
Jeff Brownac386072011-07-20 15:19:50 -07004130
4131// --- InputDispatcher::EventEntry ---
4132
4133InputDispatcher::EventEntry::EventEntry(int32_t type, nsecs_t eventTime, uint32_t policyFlags) :
4134 refCount(1), type(type), eventTime(eventTime), policyFlags(policyFlags),
4135 injectionState(NULL), dispatchInProgress(false) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07004136}
4137
Jeff Brownac386072011-07-20 15:19:50 -07004138InputDispatcher::EventEntry::~EventEntry() {
4139 releaseInjectionState();
4140}
4141
4142void InputDispatcher::EventEntry::release() {
4143 refCount -= 1;
4144 if (refCount == 0) {
4145 delete this;
4146 } else {
Steve Blockec193de2012-01-09 18:35:44 +00004147 ALOG_ASSERT(refCount > 0);
Jeff Brownac386072011-07-20 15:19:50 -07004148 }
4149}
4150
4151void InputDispatcher::EventEntry::releaseInjectionState() {
4152 if (injectionState) {
4153 injectionState->release();
4154 injectionState = NULL;
4155 }
4156}
4157
4158
4159// --- InputDispatcher::ConfigurationChangedEntry ---
4160
4161InputDispatcher::ConfigurationChangedEntry::ConfigurationChangedEntry(nsecs_t eventTime) :
4162 EventEntry(TYPE_CONFIGURATION_CHANGED, eventTime, 0) {
4163}
4164
4165InputDispatcher::ConfigurationChangedEntry::~ConfigurationChangedEntry() {
4166}
4167
4168
Jeff Brown65fd2512011-08-18 11:20:58 -07004169// --- InputDispatcher::DeviceResetEntry ---
4170
4171InputDispatcher::DeviceResetEntry::DeviceResetEntry(nsecs_t eventTime, int32_t deviceId) :
4172 EventEntry(TYPE_DEVICE_RESET, eventTime, 0),
4173 deviceId(deviceId) {
4174}
4175
4176InputDispatcher::DeviceResetEntry::~DeviceResetEntry() {
4177}
4178
4179
Jeff Brownac386072011-07-20 15:19:50 -07004180// --- InputDispatcher::KeyEntry ---
4181
4182InputDispatcher::KeyEntry::KeyEntry(nsecs_t eventTime,
Jeff Brown58a2da82011-01-25 16:02:22 -08004183 int32_t deviceId, uint32_t source, uint32_t policyFlags, int32_t action,
Jeff Brown7fbdc842010-06-17 20:52:56 -07004184 int32_t flags, int32_t keyCode, int32_t scanCode, int32_t metaState,
Jeff Brownac386072011-07-20 15:19:50 -07004185 int32_t repeatCount, nsecs_t downTime) :
4186 EventEntry(TYPE_KEY, eventTime, policyFlags),
4187 deviceId(deviceId), source(source), action(action), flags(flags),
4188 keyCode(keyCode), scanCode(scanCode), metaState(metaState),
4189 repeatCount(repeatCount), downTime(downTime),
Jeff Brown905805a2011-10-12 13:57:59 -07004190 syntheticRepeat(false), interceptKeyResult(KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN),
4191 interceptKeyWakeupTime(0) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07004192}
4193
Jeff Brownac386072011-07-20 15:19:50 -07004194InputDispatcher::KeyEntry::~KeyEntry() {
4195}
Jeff Brown7fbdc842010-06-17 20:52:56 -07004196
Jeff Brownac386072011-07-20 15:19:50 -07004197void InputDispatcher::KeyEntry::recycle() {
4198 releaseInjectionState();
4199
4200 dispatchInProgress = false;
4201 syntheticRepeat = false;
4202 interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
Jeff Brown905805a2011-10-12 13:57:59 -07004203 interceptKeyWakeupTime = 0;
Jeff Brownac386072011-07-20 15:19:50 -07004204}
4205
4206
4207// --- InputDispatcher::MotionSample ---
4208
4209InputDispatcher::MotionSample::MotionSample(nsecs_t eventTime,
4210 const PointerCoords* pointerCoords, uint32_t pointerCount) :
4211 next(NULL), eventTime(eventTime), eventTimeBeforeCoalescing(eventTime) {
Jeff Brown7fbdc842010-06-17 20:52:56 -07004212 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brownac386072011-07-20 15:19:50 -07004213 this->pointerCoords[i].copyFrom(pointerCoords[i]);
Jeff Brown7fbdc842010-06-17 20:52:56 -07004214 }
Jeff Brownb88102f2010-09-08 11:49:43 -07004215}
4216
4217
Jeff Brownae9fc032010-08-18 15:51:08 -07004218// --- InputDispatcher::MotionEntry ---
4219
Jeff Brownac386072011-07-20 15:19:50 -07004220InputDispatcher::MotionEntry::MotionEntry(nsecs_t eventTime,
4221 int32_t deviceId, uint32_t source, uint32_t policyFlags, int32_t action, int32_t flags,
4222 int32_t metaState, int32_t buttonState,
4223 int32_t edgeFlags, float xPrecision, float yPrecision,
4224 nsecs_t downTime, uint32_t pointerCount,
4225 const PointerProperties* pointerProperties, const PointerCoords* pointerCoords) :
4226 EventEntry(TYPE_MOTION, eventTime, policyFlags),
4227 deviceId(deviceId), source(source), action(action), flags(flags),
4228 metaState(metaState), buttonState(buttonState), edgeFlags(edgeFlags),
4229 xPrecision(xPrecision), yPrecision(yPrecision),
4230 downTime(downTime), pointerCount(pointerCount),
4231 firstSample(eventTime, pointerCoords, pointerCount),
4232 lastSample(&firstSample) {
4233 for (uint32_t i = 0; i < pointerCount; i++) {
4234 this->pointerProperties[i].copyFrom(pointerProperties[i]);
4235 }
4236}
4237
4238InputDispatcher::MotionEntry::~MotionEntry() {
4239 for (MotionSample* sample = firstSample.next; sample != NULL; ) {
4240 MotionSample* next = sample->next;
4241 delete sample;
4242 sample = next;
4243 }
4244}
4245
Jeff Brownae9fc032010-08-18 15:51:08 -07004246uint32_t InputDispatcher::MotionEntry::countSamples() const {
4247 uint32_t count = 1;
4248 for (MotionSample* sample = firstSample.next; sample != NULL; sample = sample->next) {
4249 count += 1;
4250 }
4251 return count;
4252}
4253
Jeff Brown4e91a182011-04-07 11:38:09 -07004254bool InputDispatcher::MotionEntry::canAppendSamples(int32_t action, uint32_t pointerCount,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07004255 const PointerProperties* pointerProperties) const {
Jeff Brown4e91a182011-04-07 11:38:09 -07004256 if (this->action != action
4257 || this->pointerCount != pointerCount
4258 || this->isInjected()) {
4259 return false;
4260 }
4261 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07004262 if (this->pointerProperties[i] != pointerProperties[i]) {
Jeff Brown4e91a182011-04-07 11:38:09 -07004263 return false;
4264 }
4265 }
4266 return true;
4267}
4268
Jeff Brownac386072011-07-20 15:19:50 -07004269void InputDispatcher::MotionEntry::appendSample(
4270 nsecs_t eventTime, const PointerCoords* pointerCoords) {
4271 MotionSample* sample = new MotionSample(eventTime, pointerCoords, pointerCount);
4272
4273 lastSample->next = sample;
4274 lastSample = sample;
4275}
4276
4277
4278// --- InputDispatcher::DispatchEntry ---
4279
4280InputDispatcher::DispatchEntry::DispatchEntry(EventEntry* eventEntry,
4281 int32_t targetFlags, float xOffset, float yOffset, float scaleFactor) :
4282 eventEntry(eventEntry), targetFlags(targetFlags),
4283 xOffset(xOffset), yOffset(yOffset), scaleFactor(scaleFactor),
4284 inProgress(false),
4285 resolvedAction(0), resolvedFlags(0),
4286 headMotionSample(NULL), tailMotionSample(NULL) {
4287 eventEntry->refCount += 1;
4288}
4289
4290InputDispatcher::DispatchEntry::~DispatchEntry() {
4291 eventEntry->release();
4292}
4293
Jeff Brownb88102f2010-09-08 11:49:43 -07004294
4295// --- InputDispatcher::InputState ---
4296
Jeff Brownb6997262010-10-08 22:31:17 -07004297InputDispatcher::InputState::InputState() {
Jeff Brownb88102f2010-09-08 11:49:43 -07004298}
4299
4300InputDispatcher::InputState::~InputState() {
4301}
4302
4303bool InputDispatcher::InputState::isNeutral() const {
4304 return mKeyMementos.isEmpty() && mMotionMementos.isEmpty();
4305}
4306
Jeff Brown81346812011-06-28 20:08:48 -07004307bool InputDispatcher::InputState::isHovering(int32_t deviceId, uint32_t source) const {
4308 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4309 const MotionMemento& memento = mMotionMementos.itemAt(i);
4310 if (memento.deviceId == deviceId
4311 && memento.source == source
4312 && memento.hovering) {
4313 return true;
4314 }
4315 }
4316 return false;
4317}
Jeff Brownb88102f2010-09-08 11:49:43 -07004318
Jeff Brown81346812011-06-28 20:08:48 -07004319bool InputDispatcher::InputState::trackKey(const KeyEntry* entry,
4320 int32_t action, int32_t flags) {
4321 switch (action) {
4322 case AKEY_EVENT_ACTION_UP: {
4323 if (entry->flags & AKEY_EVENT_FLAG_FALLBACK) {
4324 for (size_t i = 0; i < mFallbackKeys.size(); ) {
4325 if (mFallbackKeys.valueAt(i) == entry->keyCode) {
4326 mFallbackKeys.removeItemsAt(i);
4327 } else {
4328 i += 1;
4329 }
4330 }
4331 }
4332 ssize_t index = findKeyMemento(entry);
4333 if (index >= 0) {
4334 mKeyMementos.removeAt(index);
4335 return true;
4336 }
Jeff Brown68b909d2011-12-07 16:36:01 -08004337 /* FIXME: We can't just drop the key up event because that prevents creating
4338 * popup windows that are automatically shown when a key is held and then
4339 * dismissed when the key is released. The problem is that the popup will
4340 * not have received the original key down, so the key up will be considered
4341 * to be inconsistent with its observed state. We could perhaps handle this
4342 * by synthesizing a key down but that will cause other problems.
4343 *
4344 * So for now, allow inconsistent key up events to be dispatched.
4345 *
Jeff Brown81346812011-06-28 20:08:48 -07004346#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00004347 ALOGD("Dropping inconsistent key up event: deviceId=%d, source=%08x, "
Jeff Brown81346812011-06-28 20:08:48 -07004348 "keyCode=%d, scanCode=%d",
4349 entry->deviceId, entry->source, entry->keyCode, entry->scanCode);
4350#endif
4351 return false;
Jeff Brown68b909d2011-12-07 16:36:01 -08004352 */
4353 return true;
Jeff Brown81346812011-06-28 20:08:48 -07004354 }
4355
4356 case AKEY_EVENT_ACTION_DOWN: {
4357 ssize_t index = findKeyMemento(entry);
4358 if (index >= 0) {
4359 mKeyMementos.removeAt(index);
4360 }
4361 addKeyMemento(entry, flags);
4362 return true;
4363 }
4364
4365 default:
4366 return true;
Jeff Brownb88102f2010-09-08 11:49:43 -07004367 }
4368}
4369
Jeff Brown81346812011-06-28 20:08:48 -07004370bool InputDispatcher::InputState::trackMotion(const MotionEntry* entry,
4371 int32_t action, int32_t flags) {
4372 int32_t actionMasked = action & AMOTION_EVENT_ACTION_MASK;
4373 switch (actionMasked) {
4374 case AMOTION_EVENT_ACTION_UP:
4375 case AMOTION_EVENT_ACTION_CANCEL: {
4376 ssize_t index = findMotionMemento(entry, false /*hovering*/);
4377 if (index >= 0) {
4378 mMotionMementos.removeAt(index);
4379 return true;
Jeff Brownda3d5a92011-03-29 15:11:34 -07004380 }
Jeff Brown81346812011-06-28 20:08:48 -07004381#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00004382 ALOGD("Dropping inconsistent motion up or cancel event: deviceId=%d, source=%08x, "
Jeff Brown81346812011-06-28 20:08:48 -07004383 "actionMasked=%d",
4384 entry->deviceId, entry->source, actionMasked);
4385#endif
4386 return false;
Jeff Brownda3d5a92011-03-29 15:11:34 -07004387 }
4388
Jeff Brown81346812011-06-28 20:08:48 -07004389 case AMOTION_EVENT_ACTION_DOWN: {
4390 ssize_t index = findMotionMemento(entry, false /*hovering*/);
4391 if (index >= 0) {
4392 mMotionMementos.removeAt(index);
4393 }
4394 addMotionMemento(entry, flags, false /*hovering*/);
4395 return true;
4396 }
4397
4398 case AMOTION_EVENT_ACTION_POINTER_UP:
4399 case AMOTION_EVENT_ACTION_POINTER_DOWN:
4400 case AMOTION_EVENT_ACTION_MOVE: {
4401 ssize_t index = findMotionMemento(entry, false /*hovering*/);
4402 if (index >= 0) {
4403 MotionMemento& memento = mMotionMementos.editItemAt(index);
4404 memento.setPointers(entry);
4405 return true;
4406 }
Jeff Brown2e45fb62011-06-29 21:19:05 -07004407 if (actionMasked == AMOTION_EVENT_ACTION_MOVE
4408 && (entry->source & (AINPUT_SOURCE_CLASS_JOYSTICK
4409 | AINPUT_SOURCE_CLASS_NAVIGATION))) {
4410 // Joysticks and trackballs can send MOVE events without corresponding DOWN or UP.
4411 return true;
4412 }
Jeff Brown81346812011-06-28 20:08:48 -07004413#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00004414 ALOGD("Dropping inconsistent motion pointer up/down or move event: "
Jeff Brown81346812011-06-28 20:08:48 -07004415 "deviceId=%d, source=%08x, actionMasked=%d",
4416 entry->deviceId, entry->source, actionMasked);
4417#endif
4418 return false;
4419 }
4420
4421 case AMOTION_EVENT_ACTION_HOVER_EXIT: {
4422 ssize_t index = findMotionMemento(entry, true /*hovering*/);
4423 if (index >= 0) {
4424 mMotionMementos.removeAt(index);
4425 return true;
4426 }
4427#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00004428 ALOGD("Dropping inconsistent motion hover exit event: deviceId=%d, source=%08x",
Jeff Brown81346812011-06-28 20:08:48 -07004429 entry->deviceId, entry->source);
4430#endif
4431 return false;
4432 }
4433
4434 case AMOTION_EVENT_ACTION_HOVER_ENTER:
4435 case AMOTION_EVENT_ACTION_HOVER_MOVE: {
4436 ssize_t index = findMotionMemento(entry, true /*hovering*/);
4437 if (index >= 0) {
4438 mMotionMementos.removeAt(index);
4439 }
4440 addMotionMemento(entry, flags, true /*hovering*/);
4441 return true;
4442 }
4443
4444 default:
4445 return true;
4446 }
4447}
4448
4449ssize_t InputDispatcher::InputState::findKeyMemento(const KeyEntry* entry) const {
Jeff Brownb88102f2010-09-08 11:49:43 -07004450 for (size_t i = 0; i < mKeyMementos.size(); i++) {
Jeff Brown81346812011-06-28 20:08:48 -07004451 const KeyMemento& memento = mKeyMementos.itemAt(i);
Jeff Brownb88102f2010-09-08 11:49:43 -07004452 if (memento.deviceId == entry->deviceId
4453 && memento.source == entry->source
4454 && memento.keyCode == entry->keyCode
4455 && memento.scanCode == entry->scanCode) {
Jeff Brown81346812011-06-28 20:08:48 -07004456 return i;
Jeff Brownb88102f2010-09-08 11:49:43 -07004457 }
4458 }
Jeff Brown81346812011-06-28 20:08:48 -07004459 return -1;
Jeff Brownb88102f2010-09-08 11:49:43 -07004460}
4461
Jeff Brown81346812011-06-28 20:08:48 -07004462ssize_t InputDispatcher::InputState::findMotionMemento(const MotionEntry* entry,
4463 bool hovering) const {
Jeff Brownb88102f2010-09-08 11:49:43 -07004464 for (size_t i = 0; i < mMotionMementos.size(); i++) {
Jeff Brown81346812011-06-28 20:08:48 -07004465 const MotionMemento& memento = mMotionMementos.itemAt(i);
Jeff Brownb88102f2010-09-08 11:49:43 -07004466 if (memento.deviceId == entry->deviceId
Jeff Brown81346812011-06-28 20:08:48 -07004467 && memento.source == entry->source
4468 && memento.hovering == hovering) {
4469 return i;
Jeff Brownb88102f2010-09-08 11:49:43 -07004470 }
4471 }
Jeff Brown81346812011-06-28 20:08:48 -07004472 return -1;
4473}
Jeff Brownb88102f2010-09-08 11:49:43 -07004474
Jeff Brown81346812011-06-28 20:08:48 -07004475void InputDispatcher::InputState::addKeyMemento(const KeyEntry* entry, int32_t flags) {
4476 mKeyMementos.push();
4477 KeyMemento& memento = mKeyMementos.editTop();
4478 memento.deviceId = entry->deviceId;
4479 memento.source = entry->source;
4480 memento.keyCode = entry->keyCode;
4481 memento.scanCode = entry->scanCode;
4482 memento.flags = flags;
4483 memento.downTime = entry->downTime;
4484}
4485
4486void InputDispatcher::InputState::addMotionMemento(const MotionEntry* entry,
4487 int32_t flags, bool hovering) {
4488 mMotionMementos.push();
4489 MotionMemento& memento = mMotionMementos.editTop();
4490 memento.deviceId = entry->deviceId;
4491 memento.source = entry->source;
4492 memento.flags = flags;
4493 memento.xPrecision = entry->xPrecision;
4494 memento.yPrecision = entry->yPrecision;
4495 memento.downTime = entry->downTime;
4496 memento.setPointers(entry);
4497 memento.hovering = hovering;
Jeff Brownb88102f2010-09-08 11:49:43 -07004498}
4499
4500void InputDispatcher::InputState::MotionMemento::setPointers(const MotionEntry* entry) {
4501 pointerCount = entry->pointerCount;
4502 for (uint32_t i = 0; i < entry->pointerCount; i++) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07004503 pointerProperties[i].copyFrom(entry->pointerProperties[i]);
Jeff Brownace13b12011-03-09 17:39:48 -08004504 pointerCoords[i].copyFrom(entry->lastSample->pointerCoords[i]);
Jeff Brownb88102f2010-09-08 11:49:43 -07004505 }
4506}
4507
Jeff Brownb6997262010-10-08 22:31:17 -07004508void InputDispatcher::InputState::synthesizeCancelationEvents(nsecs_t currentTime,
Jeff Brownac386072011-07-20 15:19:50 -07004509 Vector<EventEntry*>& outEvents, const CancelationOptions& options) {
Jeff Brown81346812011-06-28 20:08:48 -07004510 for (size_t i = 0; i < mKeyMementos.size(); i++) {
Jeff Brownb88102f2010-09-08 11:49:43 -07004511 const KeyMemento& memento = mKeyMementos.itemAt(i);
Jeff Brown49ed71d2010-12-06 17:13:33 -08004512 if (shouldCancelKey(memento, options)) {
Jeff Brownac386072011-07-20 15:19:50 -07004513 outEvents.push(new KeyEntry(currentTime,
Jeff Brownb6997262010-10-08 22:31:17 -07004514 memento.deviceId, memento.source, 0,
Jeff Brown49ed71d2010-12-06 17:13:33 -08004515 AKEY_EVENT_ACTION_UP, memento.flags | AKEY_EVENT_FLAG_CANCELED,
Jeff Brownb6997262010-10-08 22:31:17 -07004516 memento.keyCode, memento.scanCode, 0, 0, memento.downTime));
Jeff Brownb6997262010-10-08 22:31:17 -07004517 }
Jeff Brownb88102f2010-09-08 11:49:43 -07004518 }
4519
Jeff Brown81346812011-06-28 20:08:48 -07004520 for (size_t i = 0; i < mMotionMementos.size(); i++) {
Jeff Brownb88102f2010-09-08 11:49:43 -07004521 const MotionMemento& memento = mMotionMementos.itemAt(i);
Jeff Brown49ed71d2010-12-06 17:13:33 -08004522 if (shouldCancelMotion(memento, options)) {
Jeff Brownac386072011-07-20 15:19:50 -07004523 outEvents.push(new MotionEntry(currentTime,
Jeff Brownb6997262010-10-08 22:31:17 -07004524 memento.deviceId, memento.source, 0,
Jeff Browna032cc02011-03-07 16:56:21 -08004525 memento.hovering
4526 ? AMOTION_EVENT_ACTION_HOVER_EXIT
4527 : AMOTION_EVENT_ACTION_CANCEL,
Jeff Brown81346812011-06-28 20:08:48 -07004528 memento.flags, 0, 0, 0,
Jeff Brownb6997262010-10-08 22:31:17 -07004529 memento.xPrecision, memento.yPrecision, memento.downTime,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07004530 memento.pointerCount, memento.pointerProperties, memento.pointerCoords));
Jeff Brownb6997262010-10-08 22:31:17 -07004531 }
Jeff Brownb88102f2010-09-08 11:49:43 -07004532 }
4533}
4534
4535void InputDispatcher::InputState::clear() {
4536 mKeyMementos.clear();
4537 mMotionMementos.clear();
Jeff Brownda3d5a92011-03-29 15:11:34 -07004538 mFallbackKeys.clear();
Jeff Brownb6997262010-10-08 22:31:17 -07004539}
4540
Jeff Brown9c9f1a32010-10-11 18:32:20 -07004541void InputDispatcher::InputState::copyPointerStateTo(InputState& other) const {
4542 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4543 const MotionMemento& memento = mMotionMementos.itemAt(i);
4544 if (memento.source & AINPUT_SOURCE_CLASS_POINTER) {
4545 for (size_t j = 0; j < other.mMotionMementos.size(); ) {
4546 const MotionMemento& otherMemento = other.mMotionMementos.itemAt(j);
4547 if (memento.deviceId == otherMemento.deviceId
4548 && memento.source == otherMemento.source) {
4549 other.mMotionMementos.removeAt(j);
4550 } else {
4551 j += 1;
4552 }
4553 }
4554 other.mMotionMementos.push(memento);
4555 }
4556 }
4557}
4558
Jeff Brownda3d5a92011-03-29 15:11:34 -07004559int32_t InputDispatcher::InputState::getFallbackKey(int32_t originalKeyCode) {
4560 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
4561 return index >= 0 ? mFallbackKeys.valueAt(index) : -1;
4562}
4563
4564void InputDispatcher::InputState::setFallbackKey(int32_t originalKeyCode,
4565 int32_t fallbackKeyCode) {
4566 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
4567 if (index >= 0) {
4568 mFallbackKeys.replaceValueAt(index, fallbackKeyCode);
4569 } else {
4570 mFallbackKeys.add(originalKeyCode, fallbackKeyCode);
4571 }
4572}
4573
4574void InputDispatcher::InputState::removeFallbackKey(int32_t originalKeyCode) {
4575 mFallbackKeys.removeItem(originalKeyCode);
4576}
4577
Jeff Brown49ed71d2010-12-06 17:13:33 -08004578bool InputDispatcher::InputState::shouldCancelKey(const KeyMemento& memento,
Jeff Brownda3d5a92011-03-29 15:11:34 -07004579 const CancelationOptions& options) {
4580 if (options.keyCode != -1 && memento.keyCode != options.keyCode) {
4581 return false;
4582 }
4583
Jeff Brown65fd2512011-08-18 11:20:58 -07004584 if (options.deviceId != -1 && memento.deviceId != options.deviceId) {
4585 return false;
4586 }
4587
Jeff Brownda3d5a92011-03-29 15:11:34 -07004588 switch (options.mode) {
4589 case CancelationOptions::CANCEL_ALL_EVENTS:
4590 case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
Jeff Brownb6997262010-10-08 22:31:17 -07004591 return true;
Jeff Brownda3d5a92011-03-29 15:11:34 -07004592 case CancelationOptions::CANCEL_FALLBACK_EVENTS:
Jeff Brown49ed71d2010-12-06 17:13:33 -08004593 return memento.flags & AKEY_EVENT_FLAG_FALLBACK;
4594 default:
4595 return false;
4596 }
4597}
4598
4599bool InputDispatcher::InputState::shouldCancelMotion(const MotionMemento& memento,
Jeff Brownda3d5a92011-03-29 15:11:34 -07004600 const CancelationOptions& options) {
Jeff Brown65fd2512011-08-18 11:20:58 -07004601 if (options.deviceId != -1 && memento.deviceId != options.deviceId) {
4602 return false;
4603 }
4604
Jeff Brownda3d5a92011-03-29 15:11:34 -07004605 switch (options.mode) {
4606 case CancelationOptions::CANCEL_ALL_EVENTS:
Jeff Brown49ed71d2010-12-06 17:13:33 -08004607 return true;
Jeff Brownda3d5a92011-03-29 15:11:34 -07004608 case CancelationOptions::CANCEL_POINTER_EVENTS:
Jeff Brown49ed71d2010-12-06 17:13:33 -08004609 return memento.source & AINPUT_SOURCE_CLASS_POINTER;
Jeff Brownda3d5a92011-03-29 15:11:34 -07004610 case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
Jeff Brown49ed71d2010-12-06 17:13:33 -08004611 return !(memento.source & AINPUT_SOURCE_CLASS_POINTER);
4612 default:
4613 return false;
Jeff Brownb6997262010-10-08 22:31:17 -07004614 }
Jeff Brownb88102f2010-09-08 11:49:43 -07004615}
4616
4617
Jeff Brown46b9ac02010-04-22 18:58:52 -07004618// --- InputDispatcher::Connection ---
4619
Jeff Brown928e0542011-01-10 11:17:36 -08004620InputDispatcher::Connection::Connection(const sp<InputChannel>& inputChannel,
Jeff Browncc4f7db2011-08-30 20:34:48 -07004621 const sp<InputWindowHandle>& inputWindowHandle, bool monitor) :
Jeff Brown928e0542011-01-10 11:17:36 -08004622 status(STATUS_NORMAL), inputChannel(inputChannel), inputWindowHandle(inputWindowHandle),
Jeff Browncc4f7db2011-08-30 20:34:48 -07004623 monitor(monitor),
Jeff Brown928e0542011-01-10 11:17:36 -08004624 inputPublisher(inputChannel),
Jeff Brownda3d5a92011-03-29 15:11:34 -07004625 lastEventTime(LONG_LONG_MAX), lastDispatchTime(LONG_LONG_MAX) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07004626}
4627
4628InputDispatcher::Connection::~Connection() {
4629}
4630
4631status_t InputDispatcher::Connection::initialize() {
4632 return inputPublisher.initialize();
4633}
4634
Jeff Brown9c3cda02010-06-15 01:31:58 -07004635const char* InputDispatcher::Connection::getStatusLabel() const {
4636 switch (status) {
4637 case STATUS_NORMAL:
4638 return "NORMAL";
4639
4640 case STATUS_BROKEN:
4641 return "BROKEN";
4642
Jeff Brown9c3cda02010-06-15 01:31:58 -07004643 case STATUS_ZOMBIE:
4644 return "ZOMBIE";
4645
4646 default:
4647 return "UNKNOWN";
4648 }
4649}
4650
Jeff Brown46b9ac02010-04-22 18:58:52 -07004651InputDispatcher::DispatchEntry* InputDispatcher::Connection::findQueuedDispatchEntryForEvent(
4652 const EventEntry* eventEntry) const {
Jeff Brownac386072011-07-20 15:19:50 -07004653 for (DispatchEntry* dispatchEntry = outboundQueue.tail; dispatchEntry;
4654 dispatchEntry = dispatchEntry->prev) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07004655 if (dispatchEntry->eventEntry == eventEntry) {
4656 return dispatchEntry;
4657 }
4658 }
4659 return NULL;
4660}
4661
Jeff Brownb88102f2010-09-08 11:49:43 -07004662
Jeff Brown9c3cda02010-06-15 01:31:58 -07004663// --- InputDispatcher::CommandEntry ---
4664
Jeff Brownac386072011-07-20 15:19:50 -07004665InputDispatcher::CommandEntry::CommandEntry(Command command) :
4666 command(command), eventTime(0), keyEntry(NULL), userActivityEventType(0), handled(false) {
Jeff Brown9c3cda02010-06-15 01:31:58 -07004667}
4668
4669InputDispatcher::CommandEntry::~CommandEntry() {
4670}
4671
Jeff Brown46b9ac02010-04-22 18:58:52 -07004672
Jeff Brown01ce2e92010-09-26 22:20:12 -07004673// --- InputDispatcher::TouchState ---
4674
4675InputDispatcher::TouchState::TouchState() :
Jeff Brown58a2da82011-01-25 16:02:22 -08004676 down(false), split(false), deviceId(-1), source(0) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07004677}
4678
4679InputDispatcher::TouchState::~TouchState() {
4680}
4681
4682void InputDispatcher::TouchState::reset() {
4683 down = false;
4684 split = false;
Jeff Brown95712852011-01-04 19:41:59 -08004685 deviceId = -1;
Jeff Brown58a2da82011-01-25 16:02:22 -08004686 source = 0;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004687 windows.clear();
4688}
4689
4690void InputDispatcher::TouchState::copyFrom(const TouchState& other) {
4691 down = other.down;
4692 split = other.split;
Jeff Brown95712852011-01-04 19:41:59 -08004693 deviceId = other.deviceId;
Jeff Brown58a2da82011-01-25 16:02:22 -08004694 source = other.source;
Jeff Brown9302c872011-07-13 22:51:29 -07004695 windows = other.windows;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004696}
4697
Jeff Brown9302c872011-07-13 22:51:29 -07004698void InputDispatcher::TouchState::addOrUpdateWindow(const sp<InputWindowHandle>& windowHandle,
Jeff Brown01ce2e92010-09-26 22:20:12 -07004699 int32_t targetFlags, BitSet32 pointerIds) {
4700 if (targetFlags & InputTarget::FLAG_SPLIT) {
4701 split = true;
4702 }
4703
4704 for (size_t i = 0; i < windows.size(); i++) {
4705 TouchedWindow& touchedWindow = windows.editItemAt(i);
Jeff Brown9302c872011-07-13 22:51:29 -07004706 if (touchedWindow.windowHandle == windowHandle) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07004707 touchedWindow.targetFlags |= targetFlags;
Jeff Brown98db5fa2011-06-08 15:37:10 -07004708 if (targetFlags & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
4709 touchedWindow.targetFlags &= ~InputTarget::FLAG_DISPATCH_AS_IS;
4710 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07004711 touchedWindow.pointerIds.value |= pointerIds.value;
4712 return;
4713 }
4714 }
4715
4716 windows.push();
4717
4718 TouchedWindow& touchedWindow = windows.editTop();
Jeff Brown9302c872011-07-13 22:51:29 -07004719 touchedWindow.windowHandle = windowHandle;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004720 touchedWindow.targetFlags = targetFlags;
4721 touchedWindow.pointerIds = pointerIds;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004722}
4723
Jeff Browna032cc02011-03-07 16:56:21 -08004724void InputDispatcher::TouchState::filterNonAsIsTouchWindows() {
Jeff Brown01ce2e92010-09-26 22:20:12 -07004725 for (size_t i = 0 ; i < windows.size(); ) {
Jeff Browna032cc02011-03-07 16:56:21 -08004726 TouchedWindow& window = windows.editItemAt(i);
Jeff Brown98db5fa2011-06-08 15:37:10 -07004727 if (window.targetFlags & (InputTarget::FLAG_DISPATCH_AS_IS
4728 | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER)) {
Jeff Browna032cc02011-03-07 16:56:21 -08004729 window.targetFlags &= ~InputTarget::FLAG_DISPATCH_MASK;
4730 window.targetFlags |= InputTarget::FLAG_DISPATCH_AS_IS;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004731 i += 1;
Jeff Browna032cc02011-03-07 16:56:21 -08004732 } else {
4733 windows.removeAt(i);
Jeff Brown01ce2e92010-09-26 22:20:12 -07004734 }
4735 }
4736}
4737
Jeff Brown9302c872011-07-13 22:51:29 -07004738sp<InputWindowHandle> InputDispatcher::TouchState::getFirstForegroundWindowHandle() const {
Jeff Brown01ce2e92010-09-26 22:20:12 -07004739 for (size_t i = 0; i < windows.size(); i++) {
Jeff Brown98db5fa2011-06-08 15:37:10 -07004740 const TouchedWindow& window = windows.itemAt(i);
4741 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
Jeff Brown9302c872011-07-13 22:51:29 -07004742 return window.windowHandle;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004743 }
4744 }
4745 return NULL;
4746}
4747
Jeff Brown98db5fa2011-06-08 15:37:10 -07004748bool InputDispatcher::TouchState::isSlippery() const {
4749 // Must have exactly one foreground window.
4750 bool haveSlipperyForegroundWindow = false;
4751 for (size_t i = 0; i < windows.size(); i++) {
4752 const TouchedWindow& window = windows.itemAt(i);
4753 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
Jeff Browncc4f7db2011-08-30 20:34:48 -07004754 if (haveSlipperyForegroundWindow
4755 || !(window.windowHandle->getInfo()->layoutParamsFlags
4756 & InputWindowInfo::FLAG_SLIPPERY)) {
Jeff Brown98db5fa2011-06-08 15:37:10 -07004757 return false;
4758 }
4759 haveSlipperyForegroundWindow = true;
4760 }
4761 }
4762 return haveSlipperyForegroundWindow;
4763}
4764
Jeff Brown01ce2e92010-09-26 22:20:12 -07004765
Jeff Brown46b9ac02010-04-22 18:58:52 -07004766// --- InputDispatcherThread ---
4767
4768InputDispatcherThread::InputDispatcherThread(const sp<InputDispatcherInterface>& dispatcher) :
4769 Thread(/*canCallJava*/ true), mDispatcher(dispatcher) {
4770}
4771
4772InputDispatcherThread::~InputDispatcherThread() {
4773}
4774
4775bool InputDispatcherThread::threadLoop() {
4776 mDispatcher->dispatchOnce();
4777 return true;
4778}
4779
4780} // namespace android