blob: 9f0906203f84652fb2e6a0c5f847135977beb88a [file] [log] [blame]
Jeff Brownb4ff35d2011-01-02 16:37:43 -08001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070017#define LOG_TAG "InputDispatcher"
18
19//#define LOG_NDEBUG 0
20
21// Log detailed debug messages about each inbound event notification to the dispatcher.
Jeff Brown349703e2010-06-22 01:27:15 -070022#define DEBUG_INBOUND_EVENT_DETAILS 0
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070023
24// Log detailed debug messages about each outbound event processed by the dispatcher.
Jeff Brown349703e2010-06-22 01:27:15 -070025#define DEBUG_OUTBOUND_EVENT_DETAILS 0
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070026
27// Log debug messages about batching.
Jeff Brown349703e2010-06-22 01:27:15 -070028#define DEBUG_BATCHING 0
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070029
30// Log debug messages about the dispatch cycle.
Jeff Brown349703e2010-06-22 01:27:15 -070031#define DEBUG_DISPATCH_CYCLE 0
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070032
Jeff Brown9c3cda02010-06-15 01:31:58 -070033// Log debug messages about registrations.
Jeff Brown349703e2010-06-22 01:27:15 -070034#define DEBUG_REGISTRATION 0
Jeff Brown9c3cda02010-06-15 01:31:58 -070035
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070036// Log debug messages about performance statistics.
Jeff Brown349703e2010-06-22 01:27:15 -070037#define DEBUG_PERFORMANCE_STATISTICS 0
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070038
Jeff Brown7fbdc842010-06-17 20:52:56 -070039// Log debug messages about input event injection.
Jeff Brown349703e2010-06-22 01:27:15 -070040#define DEBUG_INJECTION 0
Jeff Brown7fbdc842010-06-17 20:52:56 -070041
Jeff Brownae9fc032010-08-18 15:51:08 -070042// Log debug messages about input event throttling.
43#define DEBUG_THROTTLING 0
44
Jeff Brownb88102f2010-09-08 11:49:43 -070045// Log debug messages about input focus tracking.
46#define DEBUG_FOCUS 0
47
48// Log debug messages about the app switch latency optimization.
49#define DEBUG_APP_SWITCH 0
50
Jeff Browna032cc02011-03-07 16:56:21 -080051// Log debug messages about hover events.
52#define DEBUG_HOVER 0
53
Jeff Brownb4ff35d2011-01-02 16:37:43 -080054#include "InputDispatcher.h"
55
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070056#include <cutils/log.h>
Jeff Brownb88102f2010-09-08 11:49:43 -070057#include <ui/PowerManager.h>
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070058
59#include <stddef.h>
60#include <unistd.h>
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070061#include <errno.h>
62#include <limits.h>
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070063
Jeff Brownf2f487182010-10-01 17:46:21 -070064#define INDENT " "
65#define INDENT2 " "
66
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070067namespace android {
68
Jeff Brownb88102f2010-09-08 11:49:43 -070069// Default input dispatching timeout if there is no focused application or paused window
70// from which to determine an appropriate dispatching timeout.
71const nsecs_t DEFAULT_INPUT_DISPATCHING_TIMEOUT = 5000 * 1000000LL; // 5 sec
72
73// Amount of time to allow for all pending events to be processed when an app switch
74// key is on the way. This is used to preempt input dispatch and drop input events
75// when an application takes too long to respond and the user has pressed an app switch key.
76const nsecs_t APP_SWITCH_TIMEOUT = 500 * 1000000LL; // 0.5sec
77
Jeff Brown928e0542011-01-10 11:17:36 -080078// Amount of time to allow for an event to be dispatched (measured since its eventTime)
79// before considering it stale and dropping it.
80const nsecs_t STALE_EVENT_TIMEOUT = 10000 * 1000000LL; // 10sec
81
Jeff Brown4e91a182011-04-07 11:38:09 -070082// Motion samples that are received within this amount of time are simply coalesced
83// when batched instead of being appended. This is done because some drivers update
84// the location of pointers one at a time instead of all at once.
85// For example, when there are 10 fingers down, the input dispatcher may receive 10
86// samples in quick succession with only one finger's location changed in each sample.
87//
88// This value effectively imposes an upper bound on the touch sampling rate.
89// Touch sensors typically have a 50Hz - 200Hz sampling rate, so we expect distinct
90// samples to become available 5-20ms apart but individual finger reports can trickle
91// in over a period of 2-4ms or so.
92//
93// Empirical testing shows that a 2ms coalescing interval (500Hz) is not enough,
94// a 3ms coalescing interval (333Hz) works well most of the time and doesn't introduce
95// significant quantization noise on current hardware.
96const nsecs_t MOTION_SAMPLE_COALESCE_INTERVAL = 3 * 1000000LL; // 3ms, 333Hz
97
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070098
Jeff Brown7fbdc842010-06-17 20:52:56 -070099static inline nsecs_t now() {
100 return systemTime(SYSTEM_TIME_MONOTONIC);
101}
102
Jeff Brownb88102f2010-09-08 11:49:43 -0700103static inline const char* toString(bool value) {
104 return value ? "true" : "false";
105}
106
Jeff Brown01ce2e92010-09-26 22:20:12 -0700107static inline int32_t getMotionEventActionPointerIndex(int32_t action) {
108 return (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK)
109 >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
110}
111
112static bool isValidKeyAction(int32_t action) {
113 switch (action) {
114 case AKEY_EVENT_ACTION_DOWN:
115 case AKEY_EVENT_ACTION_UP:
116 return true;
117 default:
118 return false;
119 }
120}
121
122static bool validateKeyEvent(int32_t action) {
123 if (! isValidKeyAction(action)) {
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 Brown46b9ac0a2010-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 Brown46b9ac0a2010-04-22 18:58:52 -0700209
Jeff Brown46b9ac0a2010-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 Brown46b9ac0a2010-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 Brown46b9ac0a2010-04-22 18:58:52 -0700231
232 while (mConnectionsByReceiveFd.size() != 0) {
233 unregisterInputChannel(mConnectionsByReceiveFd.valueAt(0)->inputChannel);
234 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700235}
236
237void InputDispatcher::dispatchOnce() {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700238 nsecs_t nextWakeupTime = LONG_LONG_MAX;
239 { // acquire lock
240 AutoMutex _l(mLock);
Jeff Brown214eaf42011-05-26 19:17:02 -0700241 dispatchOnceInnerLocked(&nextWakeupTime);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700242
Jeff Brownb88102f2010-09-08 11:49:43 -0700243 if (runCommandsLockedInterruptible()) {
244 nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700245 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700246 } // release lock
247
Jeff Brownb88102f2010-09-08 11:49:43 -0700248 // Wait for callback or timeout or wake. (make sure we round up, not down)
249 nsecs_t currentTime = now();
Jeff Brownaa3855d2011-03-17 01:34:19 -0700250 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
Jeff Brown4fe6c3e2010-09-13 23:17:30 -0700251 mLooper->pollOnce(timeoutMillis);
Jeff Brownb88102f2010-09-08 11:49:43 -0700252}
253
Jeff Brown214eaf42011-05-26 19:17:02 -0700254void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700255 nsecs_t currentTime = now();
256
257 // Reset the key repeat timer whenever we disallow key events, even if the next event
258 // is not a key. This is to ensure that we abort a key repeat if the device is just coming
259 // out of sleep.
Jeff Brown214eaf42011-05-26 19:17:02 -0700260 if (!mPolicy->isKeyRepeatEnabled()) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700261 resetKeyRepeatLocked();
262 }
263
Jeff Brownb88102f2010-09-08 11:49:43 -0700264 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
265 if (mDispatchFrozen) {
266#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +0000267 ALOGD("Dispatch frozen. Waiting some more.");
Jeff Brownb88102f2010-09-08 11:49:43 -0700268#endif
269 return;
270 }
271
272 // Optimize latency of app switches.
273 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
274 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
275 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
276 if (mAppSwitchDueTime < *nextWakeupTime) {
277 *nextWakeupTime = mAppSwitchDueTime;
278 }
279
Jeff Brownb88102f2010-09-08 11:49:43 -0700280 // Ready to start a new event.
281 // If we don't already have a pending event, go grab one.
282 if (! mPendingEvent) {
283 if (mInboundQueue.isEmpty()) {
284 if (isAppSwitchDue) {
285 // The inbound queue is empty so the app switch key we were waiting
286 // for will never arrive. Stop waiting for it.
287 resetPendingAppSwitchLocked(false);
288 isAppSwitchDue = false;
289 }
290
291 // Synthesize a key repeat if appropriate.
292 if (mKeyRepeatState.lastKeyEntry) {
293 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
Jeff Brown214eaf42011-05-26 19:17:02 -0700294 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700295 } else {
296 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
297 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
298 }
299 }
300 }
Jeff Browncc4f7db2011-08-30 20:34:48 -0700301
302 // Nothing to do if there is no pending event.
Jeff Brownb88102f2010-09-08 11:49:43 -0700303 if (! mPendingEvent) {
Jeff Browncc4f7db2011-08-30 20:34:48 -0700304 if (mActiveConnections.isEmpty()) {
305 dispatchIdleLocked();
306 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700307 return;
308 }
309 } else {
310 // Inbound queue has at least one entry.
Jeff Brownac386072011-07-20 15:19:50 -0700311 EventEntry* entry = mInboundQueue.head;
Jeff Brownb88102f2010-09-08 11:49:43 -0700312
313 // Throttle the entry if it is a move event and there are no
314 // other events behind it in the queue. Due to movement batching, additional
315 // samples may be appended to this event by the time the throttling timeout
316 // expires.
317 // TODO Make this smarter and consider throttling per device independently.
Jeff Brownb6997262010-10-08 22:31:17 -0700318 if (entry->type == EventEntry::TYPE_MOTION
319 && !isAppSwitchDue
320 && mDispatchEnabled
321 && (entry->policyFlags & POLICY_FLAG_PASS_TO_USER)
322 && !entry->isInjected()) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700323 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
324 int32_t deviceId = motionEntry->deviceId;
325 uint32_t source = motionEntry->source;
326 if (! isAppSwitchDue
Jeff Brownac386072011-07-20 15:19:50 -0700327 && !motionEntry->next // exactly one event, no successors
Jeff Browncc0c1592011-02-19 05:07:28 -0800328 && (motionEntry->action == AMOTION_EVENT_ACTION_MOVE
329 || motionEntry->action == AMOTION_EVENT_ACTION_HOVER_MOVE)
Jeff Brownb88102f2010-09-08 11:49:43 -0700330 && deviceId == mThrottleState.lastDeviceId
331 && source == mThrottleState.lastSource) {
332 nsecs_t nextTime = mThrottleState.lastEventTime
333 + mThrottleState.minTimeBetweenEvents;
334 if (currentTime < nextTime) {
335 // Throttle it!
336#if DEBUG_THROTTLING
Steve Block5baa3a62011-12-20 16:23:08 +0000337 ALOGD("Throttling - Delaying motion event for "
Jeff Brown90655042010-12-02 13:50:46 -0800338 "device %d, source 0x%08x by up to %0.3fms.",
Jeff Brownb88102f2010-09-08 11:49:43 -0700339 deviceId, source, (nextTime - currentTime) * 0.000001);
340#endif
341 if (nextTime < *nextWakeupTime) {
342 *nextWakeupTime = nextTime;
343 }
344 if (mThrottleState.originalSampleCount == 0) {
345 mThrottleState.originalSampleCount =
346 motionEntry->countSamples();
347 }
348 return;
349 }
350 }
351
352#if DEBUG_THROTTLING
353 if (mThrottleState.originalSampleCount != 0) {
354 uint32_t count = motionEntry->countSamples();
Steve Block5baa3a62011-12-20 16:23:08 +0000355 ALOGD("Throttling - Motion event sample count grew by %d from %d to %d.",
Jeff Brownb88102f2010-09-08 11:49:43 -0700356 count - mThrottleState.originalSampleCount,
357 mThrottleState.originalSampleCount, count);
358 mThrottleState.originalSampleCount = 0;
359 }
360#endif
361
makarand.karvekarf634ded2011-03-02 15:41:03 -0600362 mThrottleState.lastEventTime = currentTime;
Jeff Brownb88102f2010-09-08 11:49:43 -0700363 mThrottleState.lastDeviceId = deviceId;
364 mThrottleState.lastSource = source;
365 }
366
367 mInboundQueue.dequeue(entry);
368 mPendingEvent = entry;
369 }
Jeff Browne2fe69e2010-10-18 13:21:23 -0700370
371 // Poke user activity for this event.
372 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
373 pokeUserActivityLocked(mPendingEvent);
374 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700375 }
376
377 // Now we have an event to dispatch.
Jeff Brown928e0542011-01-10 11:17:36 -0800378 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Steve Blockec193de2012-01-09 18:35:44 +0000379 ALOG_ASSERT(mPendingEvent != NULL);
Jeff Brown54a18252010-09-16 14:07:33 -0700380 bool done = false;
Jeff Brownb6997262010-10-08 22:31:17 -0700381 DropReason dropReason = DROP_REASON_NOT_DROPPED;
382 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
383 dropReason = DROP_REASON_POLICY;
384 } else if (!mDispatchEnabled) {
385 dropReason = DROP_REASON_DISABLED;
386 }
Jeff Brown928e0542011-01-10 11:17:36 -0800387
388 if (mNextUnblockedEvent == mPendingEvent) {
389 mNextUnblockedEvent = NULL;
390 }
391
Jeff Brownb88102f2010-09-08 11:49:43 -0700392 switch (mPendingEvent->type) {
393 case EventEntry::TYPE_CONFIGURATION_CHANGED: {
394 ConfigurationChangedEntry* typedEntry =
395 static_cast<ConfigurationChangedEntry*>(mPendingEvent);
Jeff Brown54a18252010-09-16 14:07:33 -0700396 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Jeff Brownb6997262010-10-08 22:31:17 -0700397 dropReason = DROP_REASON_NOT_DROPPED; // configuration changes are never dropped
Jeff Brownb88102f2010-09-08 11:49:43 -0700398 break;
399 }
400
Jeff Brown65fd2512011-08-18 11:20:58 -0700401 case EventEntry::TYPE_DEVICE_RESET: {
402 DeviceResetEntry* typedEntry =
403 static_cast<DeviceResetEntry*>(mPendingEvent);
404 done = dispatchDeviceResetLocked(currentTime, typedEntry);
405 dropReason = DROP_REASON_NOT_DROPPED; // device resets are never dropped
406 break;
407 }
408
Jeff Brownb88102f2010-09-08 11:49:43 -0700409 case EventEntry::TYPE_KEY: {
410 KeyEntry* typedEntry = static_cast<KeyEntry*>(mPendingEvent);
Jeff Brownb6997262010-10-08 22:31:17 -0700411 if (isAppSwitchDue) {
412 if (isAppSwitchKeyEventLocked(typedEntry)) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700413 resetPendingAppSwitchLocked(true);
Jeff Brownb6997262010-10-08 22:31:17 -0700414 isAppSwitchDue = false;
415 } else if (dropReason == DROP_REASON_NOT_DROPPED) {
416 dropReason = DROP_REASON_APP_SWITCH;
Jeff Brownb88102f2010-09-08 11:49:43 -0700417 }
418 }
Jeff Brown928e0542011-01-10 11:17:36 -0800419 if (dropReason == DROP_REASON_NOT_DROPPED
420 && isStaleEventLocked(currentTime, typedEntry)) {
421 dropReason = DROP_REASON_STALE;
422 }
423 if (dropReason == DROP_REASON_NOT_DROPPED && mNextUnblockedEvent) {
424 dropReason = DROP_REASON_BLOCKED;
425 }
Jeff Brown214eaf42011-05-26 19:17:02 -0700426 done = dispatchKeyLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700427 break;
428 }
429
430 case EventEntry::TYPE_MOTION: {
431 MotionEntry* typedEntry = static_cast<MotionEntry*>(mPendingEvent);
Jeff Brownb6997262010-10-08 22:31:17 -0700432 if (dropReason == DROP_REASON_NOT_DROPPED && isAppSwitchDue) {
433 dropReason = DROP_REASON_APP_SWITCH;
Jeff Brownb88102f2010-09-08 11:49:43 -0700434 }
Jeff Brown928e0542011-01-10 11:17:36 -0800435 if (dropReason == DROP_REASON_NOT_DROPPED
436 && isStaleEventLocked(currentTime, typedEntry)) {
437 dropReason = DROP_REASON_STALE;
438 }
439 if (dropReason == DROP_REASON_NOT_DROPPED && mNextUnblockedEvent) {
440 dropReason = DROP_REASON_BLOCKED;
441 }
Jeff Brownb6997262010-10-08 22:31:17 -0700442 done = dispatchMotionLocked(currentTime, typedEntry,
Jeff Browne20c9e02010-10-11 14:20:19 -0700443 &dropReason, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700444 break;
445 }
446
447 default:
Steve Blockec193de2012-01-09 18:35:44 +0000448 ALOG_ASSERT(false);
Jeff Brownb88102f2010-09-08 11:49:43 -0700449 break;
450 }
451
Jeff Brown54a18252010-09-16 14:07:33 -0700452 if (done) {
Jeff Brownb6997262010-10-08 22:31:17 -0700453 if (dropReason != DROP_REASON_NOT_DROPPED) {
454 dropInboundEventLocked(mPendingEvent, dropReason);
455 }
456
Jeff Brown54a18252010-09-16 14:07:33 -0700457 releasePendingEventLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -0700458 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
459 }
460}
461
Jeff Browncc4f7db2011-08-30 20:34:48 -0700462void InputDispatcher::dispatchIdleLocked() {
463#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +0000464 ALOGD("Dispatcher idle. There are no pending events or active connections.");
Jeff Browncc4f7db2011-08-30 20:34:48 -0700465#endif
466
467 // Reset targets when idle, to release input channels and other resources
468 // they are holding onto.
469 resetTargetsLocked();
470}
471
Jeff Brownb88102f2010-09-08 11:49:43 -0700472bool InputDispatcher::enqueueInboundEventLocked(EventEntry* entry) {
473 bool needWake = mInboundQueue.isEmpty();
474 mInboundQueue.enqueueAtTail(entry);
475
476 switch (entry->type) {
Jeff Brownb6997262010-10-08 22:31:17 -0700477 case EventEntry::TYPE_KEY: {
Jeff Brown928e0542011-01-10 11:17:36 -0800478 // Optimize app switch latency.
479 // If the application takes too long to catch up then we drop all events preceding
480 // the app switch key.
Jeff Brownb6997262010-10-08 22:31:17 -0700481 KeyEntry* keyEntry = static_cast<KeyEntry*>(entry);
482 if (isAppSwitchKeyEventLocked(keyEntry)) {
483 if (keyEntry->action == AKEY_EVENT_ACTION_DOWN) {
484 mAppSwitchSawKeyDown = true;
485 } else if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
486 if (mAppSwitchSawKeyDown) {
487#if DEBUG_APP_SWITCH
Steve Block5baa3a62011-12-20 16:23:08 +0000488 ALOGD("App switch is pending!");
Jeff Brownb6997262010-10-08 22:31:17 -0700489#endif
490 mAppSwitchDueTime = keyEntry->eventTime + APP_SWITCH_TIMEOUT;
491 mAppSwitchSawKeyDown = false;
492 needWake = true;
493 }
494 }
495 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700496 break;
497 }
Jeff Brown928e0542011-01-10 11:17:36 -0800498
499 case EventEntry::TYPE_MOTION: {
500 // Optimize case where the current application is unresponsive and the user
501 // decides to touch a window in a different application.
502 // If the application takes too long to catch up then we drop all events preceding
503 // the touch into the other window.
504 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
Jeff Brown33bbfd22011-02-24 20:55:35 -0800505 if (motionEntry->action == AMOTION_EVENT_ACTION_DOWN
Jeff Brown928e0542011-01-10 11:17:36 -0800506 && (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER)
507 && mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY
Jeff Brown9302c872011-07-13 22:51:29 -0700508 && mInputTargetWaitApplicationHandle != NULL) {
Jeff Brown91c69ab2011-02-14 17:03:18 -0800509 int32_t x = int32_t(motionEntry->firstSample.pointerCoords[0].
Jeff Brownebbd5d12011-02-17 13:01:34 -0800510 getAxisValue(AMOTION_EVENT_AXIS_X));
Jeff Brown91c69ab2011-02-14 17:03:18 -0800511 int32_t y = int32_t(motionEntry->firstSample.pointerCoords[0].
Jeff Brownebbd5d12011-02-17 13:01:34 -0800512 getAxisValue(AMOTION_EVENT_AXIS_Y));
Jeff Brown9302c872011-07-13 22:51:29 -0700513 sp<InputWindowHandle> touchedWindowHandle = findTouchedWindowAtLocked(x, y);
514 if (touchedWindowHandle != NULL
515 && touchedWindowHandle->inputApplicationHandle
516 != mInputTargetWaitApplicationHandle) {
Jeff Brown928e0542011-01-10 11:17:36 -0800517 // User touched a different application than the one we are waiting on.
518 // Flag the event, and start pruning the input queue.
519 mNextUnblockedEvent = motionEntry;
520 needWake = true;
521 }
522 }
523 break;
524 }
Jeff Brownb6997262010-10-08 22:31:17 -0700525 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700526
527 return needWake;
528}
529
Jeff Brown9302c872011-07-13 22:51:29 -0700530sp<InputWindowHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t x, int32_t y) {
Jeff Brown928e0542011-01-10 11:17:36 -0800531 // Traverse windows from front to back to find touched window.
Jeff Brown9302c872011-07-13 22:51:29 -0700532 size_t numWindows = mWindowHandles.size();
Jeff Brown928e0542011-01-10 11:17:36 -0800533 for (size_t i = 0; i < numWindows; i++) {
Jeff Brown9302c872011-07-13 22:51:29 -0700534 sp<InputWindowHandle> windowHandle = mWindowHandles.itemAt(i);
Jeff Browncc4f7db2011-08-30 20:34:48 -0700535 const InputWindowInfo* windowInfo = windowHandle->getInfo();
536 int32_t flags = windowInfo->layoutParamsFlags;
Jeff Brown928e0542011-01-10 11:17:36 -0800537
Jeff Browncc4f7db2011-08-30 20:34:48 -0700538 if (windowInfo->visible) {
539 if (!(flags & InputWindowInfo::FLAG_NOT_TOUCHABLE)) {
540 bool isTouchModal = (flags & (InputWindowInfo::FLAG_NOT_FOCUSABLE
541 | InputWindowInfo::FLAG_NOT_TOUCH_MODAL)) == 0;
542 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
Jeff Brown928e0542011-01-10 11:17:36 -0800543 // Found window.
Jeff Brown9302c872011-07-13 22:51:29 -0700544 return windowHandle;
Jeff Brown928e0542011-01-10 11:17:36 -0800545 }
546 }
547 }
548
Jeff Browncc4f7db2011-08-30 20:34:48 -0700549 if (flags & InputWindowInfo::FLAG_SYSTEM_ERROR) {
Jeff Brown928e0542011-01-10 11:17:36 -0800550 // Error window is on top but not visible, so touch is dropped.
551 return NULL;
552 }
553 }
554 return NULL;
555}
556
Jeff Brownb6997262010-10-08 22:31:17 -0700557void InputDispatcher::dropInboundEventLocked(EventEntry* entry, DropReason dropReason) {
558 const char* reason;
559 switch (dropReason) {
560 case DROP_REASON_POLICY:
Jeff Browne20c9e02010-10-11 14:20:19 -0700561#if DEBUG_INBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +0000562 ALOGD("Dropped event because policy consumed it.");
Jeff Browne20c9e02010-10-11 14:20:19 -0700563#endif
Jeff Brown3122e442010-10-11 23:32:49 -0700564 reason = "inbound event was dropped because the policy consumed it";
Jeff Brownb6997262010-10-08 22:31:17 -0700565 break;
566 case DROP_REASON_DISABLED:
Steve Block6215d3f2012-01-04 20:05:49 +0000567 ALOGI("Dropped event because input dispatch is disabled.");
Jeff Brownb6997262010-10-08 22:31:17 -0700568 reason = "inbound event was dropped because input dispatch is disabled";
569 break;
570 case DROP_REASON_APP_SWITCH:
Steve Block6215d3f2012-01-04 20:05:49 +0000571 ALOGI("Dropped event because of pending overdue app switch.");
Jeff Brownb6997262010-10-08 22:31:17 -0700572 reason = "inbound event was dropped because of pending overdue app switch";
573 break;
Jeff Brown928e0542011-01-10 11:17:36 -0800574 case DROP_REASON_BLOCKED:
Steve Block6215d3f2012-01-04 20:05:49 +0000575 ALOGI("Dropped event because the current application is not responding and the user "
Jeff Brown81346812011-06-28 20:08:48 -0700576 "has started interacting with a different application.");
Jeff Brown928e0542011-01-10 11:17:36 -0800577 reason = "inbound event was dropped because the current application is not responding "
Jeff Brown81346812011-06-28 20:08:48 -0700578 "and the user has started interacting with a different application";
Jeff Brown928e0542011-01-10 11:17:36 -0800579 break;
580 case DROP_REASON_STALE:
Steve Block6215d3f2012-01-04 20:05:49 +0000581 ALOGI("Dropped event because it is stale.");
Jeff Brown928e0542011-01-10 11:17:36 -0800582 reason = "inbound event was dropped because it is stale";
583 break;
Jeff Brownb6997262010-10-08 22:31:17 -0700584 default:
Steve Blockec193de2012-01-09 18:35:44 +0000585 ALOG_ASSERT(false);
Jeff Brownb6997262010-10-08 22:31:17 -0700586 return;
587 }
588
589 switch (entry->type) {
Jeff Brownda3d5a92011-03-29 15:11:34 -0700590 case EventEntry::TYPE_KEY: {
591 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
592 synthesizeCancelationEventsForAllConnectionsLocked(options);
Jeff Brownb6997262010-10-08 22:31:17 -0700593 break;
Jeff Brownda3d5a92011-03-29 15:11:34 -0700594 }
Jeff Brownb6997262010-10-08 22:31:17 -0700595 case EventEntry::TYPE_MOTION: {
596 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
597 if (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) {
Jeff Brownda3d5a92011-03-29 15:11:34 -0700598 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
599 synthesizeCancelationEventsForAllConnectionsLocked(options);
Jeff Brownb6997262010-10-08 22:31:17 -0700600 } else {
Jeff Brownda3d5a92011-03-29 15:11:34 -0700601 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
602 synthesizeCancelationEventsForAllConnectionsLocked(options);
Jeff Brownb6997262010-10-08 22:31:17 -0700603 }
604 break;
605 }
606 }
607}
608
609bool InputDispatcher::isAppSwitchKeyCode(int32_t keyCode) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700610 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL;
611}
612
Jeff Brownb6997262010-10-08 22:31:17 -0700613bool InputDispatcher::isAppSwitchKeyEventLocked(KeyEntry* keyEntry) {
614 return ! (keyEntry->flags & AKEY_EVENT_FLAG_CANCELED)
615 && isAppSwitchKeyCode(keyEntry->keyCode)
Jeff Browne20c9e02010-10-11 14:20:19 -0700616 && (keyEntry->policyFlags & POLICY_FLAG_TRUSTED)
Jeff Brownb6997262010-10-08 22:31:17 -0700617 && (keyEntry->policyFlags & POLICY_FLAG_PASS_TO_USER);
618}
619
Jeff Brownb88102f2010-09-08 11:49:43 -0700620bool InputDispatcher::isAppSwitchPendingLocked() {
621 return mAppSwitchDueTime != LONG_LONG_MAX;
622}
623
Jeff Brownb88102f2010-09-08 11:49:43 -0700624void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
625 mAppSwitchDueTime = LONG_LONG_MAX;
626
627#if DEBUG_APP_SWITCH
628 if (handled) {
Steve Block5baa3a62011-12-20 16:23:08 +0000629 ALOGD("App switch has arrived.");
Jeff Brownb88102f2010-09-08 11:49:43 -0700630 } else {
Steve Block5baa3a62011-12-20 16:23:08 +0000631 ALOGD("App switch was abandoned.");
Jeff Brownb88102f2010-09-08 11:49:43 -0700632 }
633#endif
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700634}
635
Jeff Brown928e0542011-01-10 11:17:36 -0800636bool InputDispatcher::isStaleEventLocked(nsecs_t currentTime, EventEntry* entry) {
637 return currentTime - entry->eventTime >= STALE_EVENT_TIMEOUT;
638}
639
Jeff Brown9c3cda02010-06-15 01:31:58 -0700640bool InputDispatcher::runCommandsLockedInterruptible() {
641 if (mCommandQueue.isEmpty()) {
642 return false;
643 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700644
Jeff Brown9c3cda02010-06-15 01:31:58 -0700645 do {
646 CommandEntry* commandEntry = mCommandQueue.dequeueAtHead();
647
648 Command command = commandEntry->command;
649 (this->*command)(commandEntry); // commands are implicitly 'LockedInterruptible'
650
Jeff Brown7fbdc842010-06-17 20:52:56 -0700651 commandEntry->connection.clear();
Jeff Brownac386072011-07-20 15:19:50 -0700652 delete commandEntry;
Jeff Brown9c3cda02010-06-15 01:31:58 -0700653 } while (! mCommandQueue.isEmpty());
654 return true;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700655}
656
Jeff Brown9c3cda02010-06-15 01:31:58 -0700657InputDispatcher::CommandEntry* InputDispatcher::postCommandLocked(Command command) {
Jeff Brownac386072011-07-20 15:19:50 -0700658 CommandEntry* commandEntry = new CommandEntry(command);
Jeff Brown9c3cda02010-06-15 01:31:58 -0700659 mCommandQueue.enqueueAtTail(commandEntry);
660 return commandEntry;
661}
662
Jeff Brownb88102f2010-09-08 11:49:43 -0700663void InputDispatcher::drainInboundQueueLocked() {
664 while (! mInboundQueue.isEmpty()) {
665 EventEntry* entry = mInboundQueue.dequeueAtHead();
Jeff Brown54a18252010-09-16 14:07:33 -0700666 releaseInboundEventLocked(entry);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700667 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700668}
669
Jeff Brown54a18252010-09-16 14:07:33 -0700670void InputDispatcher::releasePendingEventLocked() {
Jeff Brownb88102f2010-09-08 11:49:43 -0700671 if (mPendingEvent) {
Jeff Brown54a18252010-09-16 14:07:33 -0700672 releaseInboundEventLocked(mPendingEvent);
Jeff Brownb88102f2010-09-08 11:49:43 -0700673 mPendingEvent = NULL;
674 }
675}
676
Jeff Brown54a18252010-09-16 14:07:33 -0700677void InputDispatcher::releaseInboundEventLocked(EventEntry* entry) {
Jeff Brown01ce2e92010-09-26 22:20:12 -0700678 InjectionState* injectionState = entry->injectionState;
679 if (injectionState && injectionState->injectionResult == INPUT_EVENT_INJECTION_PENDING) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700680#if DEBUG_DISPATCH_CYCLE
Steve Block5baa3a62011-12-20 16:23:08 +0000681 ALOGD("Injected inbound event was dropped.");
Jeff Brownb88102f2010-09-08 11:49:43 -0700682#endif
683 setInjectionResultLocked(entry, INPUT_EVENT_INJECTION_FAILED);
684 }
Jeff Brownabb4d442011-08-15 12:55:32 -0700685 if (entry == mNextUnblockedEvent) {
686 mNextUnblockedEvent = NULL;
687 }
Jeff Brownac386072011-07-20 15:19:50 -0700688 entry->release();
Jeff Brownb88102f2010-09-08 11:49:43 -0700689}
690
Jeff Brownb88102f2010-09-08 11:49:43 -0700691void InputDispatcher::resetKeyRepeatLocked() {
692 if (mKeyRepeatState.lastKeyEntry) {
Jeff Brownac386072011-07-20 15:19:50 -0700693 mKeyRepeatState.lastKeyEntry->release();
Jeff Brownb88102f2010-09-08 11:49:43 -0700694 mKeyRepeatState.lastKeyEntry = NULL;
695 }
696}
697
Jeff Brown214eaf42011-05-26 19:17:02 -0700698InputDispatcher::KeyEntry* InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
Jeff Brown349703e2010-06-22 01:27:15 -0700699 KeyEntry* entry = mKeyRepeatState.lastKeyEntry;
700
Jeff Brown349703e2010-06-22 01:27:15 -0700701 // Reuse the repeated key entry if it is otherwise unreferenced.
Jeff Browne20c9e02010-10-11 14:20:19 -0700702 uint32_t policyFlags = (entry->policyFlags & POLICY_FLAG_RAW_MASK)
703 | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700704 if (entry->refCount == 1) {
Jeff Brownac386072011-07-20 15:19:50 -0700705 entry->recycle();
Jeff Brown7fbdc842010-06-17 20:52:56 -0700706 entry->eventTime = currentTime;
Jeff Brown7fbdc842010-06-17 20:52:56 -0700707 entry->policyFlags = policyFlags;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700708 entry->repeatCount += 1;
709 } else {
Jeff Brownac386072011-07-20 15:19:50 -0700710 KeyEntry* newEntry = new KeyEntry(currentTime,
Jeff Brownc5ed5912010-07-14 18:48:53 -0700711 entry->deviceId, entry->source, policyFlags,
Jeff Brown7fbdc842010-06-17 20:52:56 -0700712 entry->action, entry->flags, entry->keyCode, entry->scanCode,
Jeff Brown00fa7bd2010-07-02 15:37:36 -0700713 entry->metaState, entry->repeatCount + 1, entry->downTime);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700714
715 mKeyRepeatState.lastKeyEntry = newEntry;
Jeff Brownac386072011-07-20 15:19:50 -0700716 entry->release();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700717
718 entry = newEntry;
719 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700720 entry->syntheticRepeat = true;
721
722 // Increment reference count since we keep a reference to the event in
723 // mKeyRepeatState.lastKeyEntry in addition to the one we return.
724 entry->refCount += 1;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700725
Jeff Brown214eaf42011-05-26 19:17:02 -0700726 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Jeff Brownb88102f2010-09-08 11:49:43 -0700727 return entry;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700728}
729
Jeff Brownb88102f2010-09-08 11:49:43 -0700730bool InputDispatcher::dispatchConfigurationChangedLocked(
731 nsecs_t currentTime, ConfigurationChangedEntry* entry) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700732#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +0000733 ALOGD("dispatchConfigurationChanged - eventTime=%lld", entry->eventTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700734#endif
735
736 // Reset key repeating in case a keyboard device was added or removed or something.
737 resetKeyRepeatLocked();
738
739 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
740 CommandEntry* commandEntry = postCommandLocked(
741 & InputDispatcher::doNotifyConfigurationChangedInterruptible);
742 commandEntry->eventTime = entry->eventTime;
743 return true;
744}
745
Jeff Brown65fd2512011-08-18 11:20:58 -0700746bool InputDispatcher::dispatchDeviceResetLocked(
747 nsecs_t currentTime, DeviceResetEntry* entry) {
748#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +0000749 ALOGD("dispatchDeviceReset - eventTime=%lld, deviceId=%d", entry->eventTime, entry->deviceId);
Jeff Brown65fd2512011-08-18 11:20:58 -0700750#endif
751
752 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
753 "device was reset");
754 options.deviceId = entry->deviceId;
755 synthesizeCancelationEventsForAllConnectionsLocked(options);
756 return true;
757}
758
Jeff Brown214eaf42011-05-26 19:17:02 -0700759bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, KeyEntry* entry,
Jeff Browne20c9e02010-10-11 14:20:19 -0700760 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Jeff Browne46a0a42010-11-02 17:58:22 -0700761 // Preprocessing.
762 if (! entry->dispatchInProgress) {
763 if (entry->repeatCount == 0
764 && entry->action == AKEY_EVENT_ACTION_DOWN
765 && (entry->policyFlags & POLICY_FLAG_TRUSTED)
Jeff Brown0029c662011-03-30 02:25:18 -0700766 && (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
Jeff Browne46a0a42010-11-02 17:58:22 -0700767 if (mKeyRepeatState.lastKeyEntry
768 && mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode) {
769 // We have seen two identical key downs in a row which indicates that the device
770 // driver is automatically generating key repeats itself. We take note of the
771 // repeat here, but we disable our own next key repeat timer since it is clear that
772 // we will not need to synthesize key repeats ourselves.
773 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
774 resetKeyRepeatLocked();
775 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
776 } else {
777 // Not a repeat. Save key down state in case we do see a repeat later.
778 resetKeyRepeatLocked();
Jeff Brown214eaf42011-05-26 19:17:02 -0700779 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
Jeff Browne46a0a42010-11-02 17:58:22 -0700780 }
781 mKeyRepeatState.lastKeyEntry = entry;
782 entry->refCount += 1;
783 } else if (! entry->syntheticRepeat) {
784 resetKeyRepeatLocked();
785 }
786
Jeff Browne2e01262011-03-02 20:34:30 -0800787 if (entry->repeatCount == 1) {
788 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
789 } else {
790 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
791 }
792
Jeff Browne46a0a42010-11-02 17:58:22 -0700793 entry->dispatchInProgress = true;
794 resetTargetsLocked();
795
796 logOutboundKeyDetailsLocked("dispatchKey - ", entry);
797 }
798
Jeff Brown905805a2011-10-12 13:57:59 -0700799 // Handle case where the policy asked us to try again later last time.
800 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
801 if (currentTime < entry->interceptKeyWakeupTime) {
802 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
803 *nextWakeupTime = entry->interceptKeyWakeupTime;
804 }
805 return false; // wait until next wakeup
806 }
807 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
808 entry->interceptKeyWakeupTime = 0;
809 }
810
Jeff Brown54a18252010-09-16 14:07:33 -0700811 // Give the policy a chance to intercept the key.
812 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
Jeff Browne20c9e02010-10-11 14:20:19 -0700813 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Jeff Brown54a18252010-09-16 14:07:33 -0700814 CommandEntry* commandEntry = postCommandLocked(
815 & InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
Jeff Brown9302c872011-07-13 22:51:29 -0700816 if (mFocusedWindowHandle != NULL) {
817 commandEntry->inputWindowHandle = mFocusedWindowHandle;
Jeff Brown54a18252010-09-16 14:07:33 -0700818 }
819 commandEntry->keyEntry = entry;
820 entry->refCount += 1;
821 return false; // wait for the command to run
822 } else {
823 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
824 }
825 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Jeff Browne20c9e02010-10-11 14:20:19 -0700826 if (*dropReason == DROP_REASON_NOT_DROPPED) {
827 *dropReason = DROP_REASON_POLICY;
828 }
Jeff Brown54a18252010-09-16 14:07:33 -0700829 }
830
831 // Clean up if dropping the event.
Jeff Browne20c9e02010-10-11 14:20:19 -0700832 if (*dropReason != DROP_REASON_NOT_DROPPED) {
Jeff Brown54a18252010-09-16 14:07:33 -0700833 resetTargetsLocked();
Jeff Brown3122e442010-10-11 23:32:49 -0700834 setInjectionResultLocked(entry, *dropReason == DROP_REASON_POLICY
835 ? INPUT_EVENT_INJECTION_SUCCEEDED : INPUT_EVENT_INJECTION_FAILED);
Jeff Brown54a18252010-09-16 14:07:33 -0700836 return true;
837 }
838
Jeff Brownb88102f2010-09-08 11:49:43 -0700839 // Identify targets.
840 if (! mCurrentInputTargetsValid) {
Jeff Brown01ce2e92010-09-26 22:20:12 -0700841 int32_t injectionResult = findFocusedWindowTargetsLocked(currentTime,
842 entry, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700843 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
844 return false;
845 }
846
847 setInjectionResultLocked(entry, injectionResult);
848 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
849 return true;
850 }
851
852 addMonitoringTargetsLocked();
Jeff Brown01ce2e92010-09-26 22:20:12 -0700853 commitTargetsLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -0700854 }
855
856 // Dispatch the key.
857 dispatchEventToCurrentInputTargetsLocked(currentTime, entry, false);
Jeff Brownb88102f2010-09-08 11:49:43 -0700858 return true;
859}
860
861void InputDispatcher::logOutboundKeyDetailsLocked(const char* prefix, const KeyEntry* entry) {
862#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +0000863 ALOGD("%seventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, "
Jeff Brownb88102f2010-09-08 11:49:43 -0700864 "action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, "
Jeff Browne46a0a42010-11-02 17:58:22 -0700865 "repeatCount=%d, downTime=%lld",
Jeff Brownb88102f2010-09-08 11:49:43 -0700866 prefix,
867 entry->eventTime, entry->deviceId, entry->source, entry->policyFlags,
868 entry->action, entry->flags, entry->keyCode, entry->scanCode, entry->metaState,
Jeff Browne46a0a42010-11-02 17:58:22 -0700869 entry->repeatCount, entry->downTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700870#endif
871}
872
873bool InputDispatcher::dispatchMotionLocked(
Jeff Browne20c9e02010-10-11 14:20:19 -0700874 nsecs_t currentTime, MotionEntry* entry, DropReason* dropReason, nsecs_t* nextWakeupTime) {
Jeff Browne46a0a42010-11-02 17:58:22 -0700875 // Preprocessing.
876 if (! entry->dispatchInProgress) {
877 entry->dispatchInProgress = true;
878 resetTargetsLocked();
879
880 logOutboundMotionDetailsLocked("dispatchMotion - ", entry);
881 }
882
Jeff Brown54a18252010-09-16 14:07:33 -0700883 // Clean up if dropping the event.
Jeff Browne20c9e02010-10-11 14:20:19 -0700884 if (*dropReason != DROP_REASON_NOT_DROPPED) {
Jeff Brown54a18252010-09-16 14:07:33 -0700885 resetTargetsLocked();
Jeff Brown3122e442010-10-11 23:32:49 -0700886 setInjectionResultLocked(entry, *dropReason == DROP_REASON_POLICY
887 ? INPUT_EVENT_INJECTION_SUCCEEDED : INPUT_EVENT_INJECTION_FAILED);
Jeff Brown54a18252010-09-16 14:07:33 -0700888 return true;
889 }
890
Jeff Brownb88102f2010-09-08 11:49:43 -0700891 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
892
893 // Identify targets.
Jeff Browncc0c1592011-02-19 05:07:28 -0800894 bool conflictingPointerActions = false;
Jeff Brownb88102f2010-09-08 11:49:43 -0700895 if (! mCurrentInputTargetsValid) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700896 int32_t injectionResult;
Jeff Browna032cc02011-03-07 16:56:21 -0800897 const MotionSample* splitBatchAfterSample = NULL;
Jeff Brownb88102f2010-09-08 11:49:43 -0700898 if (isPointerEvent) {
899 // Pointer event. (eg. touchscreen)
Jeff Brown01ce2e92010-09-26 22:20:12 -0700900 injectionResult = findTouchedWindowTargetsLocked(currentTime,
Jeff Browna032cc02011-03-07 16:56:21 -0800901 entry, nextWakeupTime, &conflictingPointerActions, &splitBatchAfterSample);
Jeff Brownb88102f2010-09-08 11:49:43 -0700902 } else {
903 // Non touch event. (eg. trackball)
Jeff Brown01ce2e92010-09-26 22:20:12 -0700904 injectionResult = findFocusedWindowTargetsLocked(currentTime,
905 entry, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700906 }
907 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
908 return false;
909 }
910
911 setInjectionResultLocked(entry, injectionResult);
912 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
913 return true;
914 }
915
916 addMonitoringTargetsLocked();
Jeff Brown01ce2e92010-09-26 22:20:12 -0700917 commitTargetsLocked();
Jeff Browna032cc02011-03-07 16:56:21 -0800918
919 // Unbatch the event if necessary by splitting it into two parts after the
920 // motion sample indicated by splitBatchAfterSample.
921 if (splitBatchAfterSample && splitBatchAfterSample->next) {
922#if DEBUG_BATCHING
923 uint32_t originalSampleCount = entry->countSamples();
924#endif
925 MotionSample* nextSample = splitBatchAfterSample->next;
Jeff Brownac386072011-07-20 15:19:50 -0700926 MotionEntry* nextEntry = new MotionEntry(nextSample->eventTime,
Jeff Browna032cc02011-03-07 16:56:21 -0800927 entry->deviceId, entry->source, entry->policyFlags,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700928 entry->action, entry->flags,
929 entry->metaState, entry->buttonState, entry->edgeFlags,
Jeff Browna032cc02011-03-07 16:56:21 -0800930 entry->xPrecision, entry->yPrecision, entry->downTime,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700931 entry->pointerCount, entry->pointerProperties, nextSample->pointerCoords);
Jeff Browna032cc02011-03-07 16:56:21 -0800932 if (nextSample != entry->lastSample) {
933 nextEntry->firstSample.next = nextSample->next;
934 nextEntry->lastSample = entry->lastSample;
935 }
Jeff Brownac386072011-07-20 15:19:50 -0700936 delete nextSample;
Jeff Browna032cc02011-03-07 16:56:21 -0800937
938 entry->lastSample = const_cast<MotionSample*>(splitBatchAfterSample);
939 entry->lastSample->next = NULL;
940
941 if (entry->injectionState) {
942 nextEntry->injectionState = entry->injectionState;
943 entry->injectionState->refCount += 1;
944 }
945
946#if DEBUG_BATCHING
Steve Block5baa3a62011-12-20 16:23:08 +0000947 ALOGD("Split batch of %d samples into two parts, first part has %d samples, "
Jeff Browna032cc02011-03-07 16:56:21 -0800948 "second part has %d samples.", originalSampleCount,
949 entry->countSamples(), nextEntry->countSamples());
950#endif
951
952 mInboundQueue.enqueueAtHead(nextEntry);
953 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700954 }
955
956 // Dispatch the motion.
Jeff Browncc0c1592011-02-19 05:07:28 -0800957 if (conflictingPointerActions) {
Jeff Brownda3d5a92011-03-29 15:11:34 -0700958 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
959 "conflicting pointer actions");
960 synthesizeCancelationEventsForAllConnectionsLocked(options);
Jeff Browncc0c1592011-02-19 05:07:28 -0800961 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700962 dispatchEventToCurrentInputTargetsLocked(currentTime, entry, false);
Jeff Brownb88102f2010-09-08 11:49:43 -0700963 return true;
964}
965
966
967void InputDispatcher::logOutboundMotionDetailsLocked(const char* prefix, const MotionEntry* entry) {
968#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +0000969 ALOGD("%seventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, "
Jeff Brown85a31762010-09-01 17:01:00 -0700970 "action=0x%x, flags=0x%x, "
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700971 "metaState=0x%x, buttonState=0x%x, "
972 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%lld",
Jeff Brownb88102f2010-09-08 11:49:43 -0700973 prefix,
Jeff Brown85a31762010-09-01 17:01:00 -0700974 entry->eventTime, entry->deviceId, entry->source, entry->policyFlags,
975 entry->action, entry->flags,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700976 entry->metaState, entry->buttonState,
977 entry->edgeFlags, entry->xPrecision, entry->yPrecision,
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700978 entry->downTime);
979
980 // Print the most recent sample that we have available, this may change due to batching.
981 size_t sampleCount = 1;
Jeff Brownb88102f2010-09-08 11:49:43 -0700982 const MotionSample* sample = & entry->firstSample;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700983 for (; sample->next != NULL; sample = sample->next) {
984 sampleCount += 1;
985 }
986 for (uint32_t i = 0; i < entry->pointerCount; i++) {
Steve Block5baa3a62011-12-20 16:23:08 +0000987 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700988 "x=%f, y=%f, pressure=%f, size=%f, "
Jeff Brown85a31762010-09-01 17:01:00 -0700989 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
Jeff Brown8d608662010-08-30 03:02:23 -0700990 "orientation=%f",
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700991 i, entry->pointerProperties[i].id,
992 entry->pointerProperties[i].toolType,
Jeff Brownebbd5d12011-02-17 13:01:34 -0800993 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
994 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
995 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
996 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
997 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
998 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
999 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1000 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1001 sample->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001002 }
1003
1004 // Keep in mind that due to batching, it is possible for the number of samples actually
1005 // dispatched to change before the application finally consumed them.
Jeff Brownc5ed5912010-07-14 18:48:53 -07001006 if (entry->action == AMOTION_EVENT_ACTION_MOVE) {
Steve Block5baa3a62011-12-20 16:23:08 +00001007 ALOGD(" ... Total movement samples currently batched %d ...", sampleCount);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001008 }
1009#endif
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001010}
1011
1012void InputDispatcher::dispatchEventToCurrentInputTargetsLocked(nsecs_t currentTime,
1013 EventEntry* eventEntry, bool resumeWithAppendedMotionSample) {
1014#if DEBUG_DISPATCH_CYCLE
Steve Block5baa3a62011-12-20 16:23:08 +00001015 ALOGD("dispatchEventToCurrentInputTargets - "
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001016 "resumeWithAppendedMotionSample=%s",
Jeff Brownb88102f2010-09-08 11:49:43 -07001017 toString(resumeWithAppendedMotionSample));
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001018#endif
1019
Steve Blockec193de2012-01-09 18:35:44 +00001020 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
Jeff Brown9c3cda02010-06-15 01:31:58 -07001021
Jeff Browne2fe69e2010-10-18 13:21:23 -07001022 pokeUserActivityLocked(eventEntry);
1023
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001024 for (size_t i = 0; i < mCurrentInputTargets.size(); i++) {
1025 const InputTarget& inputTarget = mCurrentInputTargets.itemAt(i);
1026
Jeff Brown519e0242010-09-15 15:18:56 -07001027 ssize_t connectionIndex = getConnectionIndexLocked(inputTarget.inputChannel);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001028 if (connectionIndex >= 0) {
1029 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
Jeff Brown7fbdc842010-06-17 20:52:56 -07001030 prepareDispatchCycleLocked(currentTime, connection, eventEntry, & inputTarget,
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001031 resumeWithAppendedMotionSample);
1032 } else {
Jeff Brownb6997262010-10-08 22:31:17 -07001033#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001034 ALOGD("Dropping event delivery to target with channel '%s' because it "
Jeff Brownb6997262010-10-08 22:31:17 -07001035 "is no longer registered with the input dispatcher.",
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001036 inputTarget.inputChannel->getName().string());
Jeff Brownb6997262010-10-08 22:31:17 -07001037#endif
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001038 }
1039 }
1040}
1041
Jeff Brown54a18252010-09-16 14:07:33 -07001042void InputDispatcher::resetTargetsLocked() {
Jeff Brownb88102f2010-09-08 11:49:43 -07001043 mCurrentInputTargetsValid = false;
1044 mCurrentInputTargets.clear();
Jeff Brown5ea29ab2011-07-27 11:50:51 -07001045 resetANRTimeoutsLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -07001046}
1047
Jeff Brown01ce2e92010-09-26 22:20:12 -07001048void InputDispatcher::commitTargetsLocked() {
Jeff Brownb88102f2010-09-08 11:49:43 -07001049 mCurrentInputTargetsValid = true;
1050}
1051
1052int32_t InputDispatcher::handleTargetsNotReadyLocked(nsecs_t currentTime,
Jeff Brown9302c872011-07-13 22:51:29 -07001053 const EventEntry* entry,
1054 const sp<InputApplicationHandle>& applicationHandle,
1055 const sp<InputWindowHandle>& windowHandle,
Jeff Brownb88102f2010-09-08 11:49:43 -07001056 nsecs_t* nextWakeupTime) {
Jeff Brown9302c872011-07-13 22:51:29 -07001057 if (applicationHandle == NULL && windowHandle == NULL) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001058 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY) {
1059#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001060 ALOGD("Waiting for system to become ready for input.");
Jeff Brownb88102f2010-09-08 11:49:43 -07001061#endif
1062 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY;
1063 mInputTargetWaitStartTime = currentTime;
1064 mInputTargetWaitTimeoutTime = LONG_LONG_MAX;
1065 mInputTargetWaitTimeoutExpired = false;
Jeff Brown9302c872011-07-13 22:51:29 -07001066 mInputTargetWaitApplicationHandle.clear();
Jeff Brownb88102f2010-09-08 11:49:43 -07001067 }
1068 } else {
1069 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
1070#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001071 ALOGD("Waiting for application to become ready for input: %s",
Jeff Brown9302c872011-07-13 22:51:29 -07001072 getApplicationWindowLabelLocked(applicationHandle, windowHandle).string());
Jeff Brownb88102f2010-09-08 11:49:43 -07001073#endif
Jeff Browncc4f7db2011-08-30 20:34:48 -07001074 nsecs_t timeout;
1075 if (windowHandle != NULL) {
1076 timeout = windowHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
1077 } else if (applicationHandle != NULL) {
1078 timeout = applicationHandle->getDispatchingTimeout(
1079 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
1080 } else {
1081 timeout = DEFAULT_INPUT_DISPATCHING_TIMEOUT;
1082 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001083
1084 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY;
1085 mInputTargetWaitStartTime = currentTime;
1086 mInputTargetWaitTimeoutTime = currentTime + timeout;
1087 mInputTargetWaitTimeoutExpired = false;
Jeff Brown9302c872011-07-13 22:51:29 -07001088 mInputTargetWaitApplicationHandle.clear();
Jeff Brown928e0542011-01-10 11:17:36 -08001089
Jeff Brown9302c872011-07-13 22:51:29 -07001090 if (windowHandle != NULL) {
1091 mInputTargetWaitApplicationHandle = windowHandle->inputApplicationHandle;
Jeff Brown928e0542011-01-10 11:17:36 -08001092 }
Jeff Brown9302c872011-07-13 22:51:29 -07001093 if (mInputTargetWaitApplicationHandle == NULL && applicationHandle != NULL) {
1094 mInputTargetWaitApplicationHandle = applicationHandle;
Jeff Brown928e0542011-01-10 11:17:36 -08001095 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001096 }
1097 }
1098
1099 if (mInputTargetWaitTimeoutExpired) {
1100 return INPUT_EVENT_INJECTION_TIMED_OUT;
1101 }
1102
1103 if (currentTime >= mInputTargetWaitTimeoutTime) {
Jeff Brown9302c872011-07-13 22:51:29 -07001104 onANRLocked(currentTime, applicationHandle, windowHandle,
1105 entry->eventTime, mInputTargetWaitStartTime);
Jeff Brownb88102f2010-09-08 11:49:43 -07001106
1107 // Force poll loop to wake up immediately on next iteration once we get the
1108 // ANR response back from the policy.
1109 *nextWakeupTime = LONG_LONG_MIN;
1110 return INPUT_EVENT_INJECTION_PENDING;
1111 } else {
1112 // Force poll loop to wake up when timeout is due.
1113 if (mInputTargetWaitTimeoutTime < *nextWakeupTime) {
1114 *nextWakeupTime = mInputTargetWaitTimeoutTime;
1115 }
1116 return INPUT_EVENT_INJECTION_PENDING;
1117 }
1118}
1119
Jeff Brown519e0242010-09-15 15:18:56 -07001120void InputDispatcher::resumeAfterTargetsNotReadyTimeoutLocked(nsecs_t newTimeout,
1121 const sp<InputChannel>& inputChannel) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001122 if (newTimeout > 0) {
1123 // Extend the timeout.
1124 mInputTargetWaitTimeoutTime = now() + newTimeout;
1125 } else {
1126 // Give up.
1127 mInputTargetWaitTimeoutExpired = true;
Jeff Brown519e0242010-09-15 15:18:56 -07001128
Jeff Brown01ce2e92010-09-26 22:20:12 -07001129 // Release the touch targets.
1130 mTouchState.reset();
Jeff Brown2a95c2a2010-09-16 12:31:46 -07001131
Jeff Brown519e0242010-09-15 15:18:56 -07001132 // Input state will not be realistic. Mark it out of sync.
Jeff Browndc3e0052010-09-16 11:02:16 -07001133 if (inputChannel.get()) {
1134 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
1135 if (connectionIndex >= 0) {
1136 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
Jeff Brown00045a72010-12-09 18:10:30 -08001137 if (connection->status == Connection::STATUS_NORMAL) {
Jeff Brownda3d5a92011-03-29 15:11:34 -07001138 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
Jeff Brown00045a72010-12-09 18:10:30 -08001139 "application not responding");
Jeff Brownda3d5a92011-03-29 15:11:34 -07001140 synthesizeCancelationEventsForConnectionLocked(connection, options);
Jeff Brown00045a72010-12-09 18:10:30 -08001141 }
Jeff Browndc3e0052010-09-16 11:02:16 -07001142 }
Jeff Brown519e0242010-09-15 15:18:56 -07001143 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001144 }
1145}
1146
Jeff Brown519e0242010-09-15 15:18:56 -07001147nsecs_t InputDispatcher::getTimeSpentWaitingForApplicationLocked(
Jeff Brownb88102f2010-09-08 11:49:43 -07001148 nsecs_t currentTime) {
1149 if (mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
1150 return currentTime - mInputTargetWaitStartTime;
1151 }
1152 return 0;
1153}
1154
1155void InputDispatcher::resetANRTimeoutsLocked() {
1156#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001157 ALOGD("Resetting ANR timeouts.");
Jeff Brownb88102f2010-09-08 11:49:43 -07001158#endif
1159
Jeff Brownb88102f2010-09-08 11:49:43 -07001160 // Reset input target wait timeout.
1161 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_NONE;
Jeff Brown5ea29ab2011-07-27 11:50:51 -07001162 mInputTargetWaitApplicationHandle.clear();
Jeff Brownb88102f2010-09-08 11:49:43 -07001163}
1164
Jeff Brown01ce2e92010-09-26 22:20:12 -07001165int32_t InputDispatcher::findFocusedWindowTargetsLocked(nsecs_t currentTime,
1166 const EventEntry* entry, nsecs_t* nextWakeupTime) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001167 mCurrentInputTargets.clear();
1168
1169 int32_t injectionResult;
1170
1171 // If there is no currently focused window and no focused application
1172 // then drop the event.
Jeff Brown9302c872011-07-13 22:51:29 -07001173 if (mFocusedWindowHandle == NULL) {
1174 if (mFocusedApplicationHandle != NULL) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001175#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001176 ALOGD("Waiting because there is no focused window but there is a "
Jeff Brown519e0242010-09-15 15:18:56 -07001177 "focused application that may eventually add a window: %s.",
Jeff Brown9302c872011-07-13 22:51:29 -07001178 getApplicationWindowLabelLocked(mFocusedApplicationHandle, NULL).string());
Jeff Brownb88102f2010-09-08 11:49:43 -07001179#endif
1180 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brown9302c872011-07-13 22:51:29 -07001181 mFocusedApplicationHandle, NULL, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -07001182 goto Unresponsive;
1183 }
1184
Steve Block6215d3f2012-01-04 20:05:49 +00001185 ALOGI("Dropping event because there is no focused window or focused application.");
Jeff Brownb88102f2010-09-08 11:49:43 -07001186 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1187 goto Failed;
1188 }
1189
1190 // Check permissions.
Jeff Brown9302c872011-07-13 22:51:29 -07001191 if (! checkInjectionPermission(mFocusedWindowHandle, entry->injectionState)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001192 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1193 goto Failed;
1194 }
1195
1196 // If the currently focused window is paused then keep waiting.
Jeff Browncc4f7db2011-08-30 20:34:48 -07001197 if (mFocusedWindowHandle->getInfo()->paused) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001198#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001199 ALOGD("Waiting because focused window is paused.");
Jeff Brownb88102f2010-09-08 11:49:43 -07001200#endif
1201 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brown9302c872011-07-13 22:51:29 -07001202 mFocusedApplicationHandle, mFocusedWindowHandle, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -07001203 goto Unresponsive;
1204 }
1205
Jeff Brown519e0242010-09-15 15:18:56 -07001206 // If the currently focused window is still working on previous events then keep waiting.
Jeff Brown9302c872011-07-13 22:51:29 -07001207 if (! isWindowFinishedWithPreviousInputLocked(mFocusedWindowHandle)) {
Jeff Brown519e0242010-09-15 15:18:56 -07001208#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001209 ALOGD("Waiting because focused window still processing previous input.");
Jeff Brown519e0242010-09-15 15:18:56 -07001210#endif
1211 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brown9302c872011-07-13 22:51:29 -07001212 mFocusedApplicationHandle, mFocusedWindowHandle, nextWakeupTime);
Jeff Brown519e0242010-09-15 15:18:56 -07001213 goto Unresponsive;
1214 }
1215
Jeff Brownb88102f2010-09-08 11:49:43 -07001216 // Success! Output targets.
1217 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
Jeff Brown9302c872011-07-13 22:51:29 -07001218 addWindowTargetLocked(mFocusedWindowHandle,
Jeff Browna032cc02011-03-07 16:56:21 -08001219 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS, BitSet32(0));
Jeff Brownb88102f2010-09-08 11:49:43 -07001220
1221 // Done.
1222Failed:
1223Unresponsive:
Jeff Brown519e0242010-09-15 15:18:56 -07001224 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
1225 updateDispatchStatisticsLocked(currentTime, entry,
1226 injectionResult, timeSpentWaitingForApplication);
Jeff Brownb88102f2010-09-08 11:49:43 -07001227#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001228 ALOGD("findFocusedWindow finished: injectionResult=%d, "
Jeff Brown519e0242010-09-15 15:18:56 -07001229 "timeSpendWaitingForApplication=%0.1fms",
1230 injectionResult, timeSpentWaitingForApplication / 1000000.0);
Jeff Brownb88102f2010-09-08 11:49:43 -07001231#endif
1232 return injectionResult;
1233}
1234
Jeff Brown01ce2e92010-09-26 22:20:12 -07001235int32_t InputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime,
Jeff Browna032cc02011-03-07 16:56:21 -08001236 const MotionEntry* entry, nsecs_t* nextWakeupTime, bool* outConflictingPointerActions,
1237 const MotionSample** outSplitBatchAfterSample) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001238 enum InjectionPermission {
1239 INJECTION_PERMISSION_UNKNOWN,
1240 INJECTION_PERMISSION_GRANTED,
1241 INJECTION_PERMISSION_DENIED
1242 };
1243
Jeff Brownb88102f2010-09-08 11:49:43 -07001244 mCurrentInputTargets.clear();
1245
1246 nsecs_t startTime = now();
1247
1248 // For security reasons, we defer updating the touch state until we are sure that
1249 // event injection will be allowed.
1250 //
1251 // FIXME In the original code, screenWasOff could never be set to true.
1252 // The reason is that the POLICY_FLAG_WOKE_HERE
1253 // and POLICY_FLAG_BRIGHT_HERE flags were set only when preprocessing raw
1254 // EV_KEY, EV_REL and EV_ABS events. As it happens, the touch event was
1255 // actually enqueued using the policyFlags that appeared in the final EV_SYN
1256 // events upon which no preprocessing took place. So policyFlags was always 0.
1257 // In the new native input dispatcher we're a bit more careful about event
1258 // preprocessing so the touches we receive can actually have non-zero policyFlags.
1259 // Unfortunately we obtain undesirable behavior.
1260 //
1261 // Here's what happens:
1262 //
1263 // When the device dims in anticipation of going to sleep, touches
1264 // in windows which have FLAG_TOUCHABLE_WHEN_WAKING cause
1265 // the device to brighten and reset the user activity timer.
1266 // Touches on other windows (such as the launcher window)
1267 // are dropped. Then after a moment, the device goes to sleep. Oops.
1268 //
1269 // Also notice how screenWasOff was being initialized using POLICY_FLAG_BRIGHT_HERE
1270 // instead of POLICY_FLAG_WOKE_HERE...
1271 //
1272 bool screenWasOff = false; // original policy: policyFlags & POLICY_FLAG_BRIGHT_HERE;
1273
1274 int32_t action = entry->action;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001275 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Jeff Brownb88102f2010-09-08 11:49:43 -07001276
1277 // Update the touch state as needed based on the properties of the touch event.
Jeff Brown01ce2e92010-09-26 22:20:12 -07001278 int32_t injectionResult = INPUT_EVENT_INJECTION_PENDING;
1279 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
Jeff Brown9302c872011-07-13 22:51:29 -07001280 sp<InputWindowHandle> newHoverWindowHandle;
Jeff Browncc0c1592011-02-19 05:07:28 -08001281
1282 bool isSplit = mTouchState.split;
Jeff Brown2717eff2011-06-30 23:53:07 -07001283 bool switchedDevice = mTouchState.deviceId >= 0
1284 && (mTouchState.deviceId != entry->deviceId
1285 || mTouchState.source != entry->source);
Jeff Browna032cc02011-03-07 16:56:21 -08001286 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE
1287 || maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER
1288 || maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1289 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN
1290 || maskedAction == AMOTION_EVENT_ACTION_SCROLL
1291 || isHoverAction);
Jeff Brown81346812011-06-28 20:08:48 -07001292 bool wrongDevice = false;
Jeff Browna032cc02011-03-07 16:56:21 -08001293 if (newGesture) {
Jeff Browncc0c1592011-02-19 05:07:28 -08001294 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Jeff Brown81346812011-06-28 20:08:48 -07001295 if (switchedDevice && mTouchState.down && !down) {
1296#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001297 ALOGD("Dropping event because a pointer for a different device is already down.");
Jeff Brown81346812011-06-28 20:08:48 -07001298#endif
Jeff Browncc0c1592011-02-19 05:07:28 -08001299 mTempTouchState.copyFrom(mTouchState);
Jeff Brown81346812011-06-28 20:08:48 -07001300 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1301 switchedDevice = false;
1302 wrongDevice = true;
1303 goto Failed;
Jeff Browncc0c1592011-02-19 05:07:28 -08001304 }
Jeff Brown81346812011-06-28 20:08:48 -07001305 mTempTouchState.reset();
1306 mTempTouchState.down = down;
1307 mTempTouchState.deviceId = entry->deviceId;
1308 mTempTouchState.source = entry->source;
1309 isSplit = false;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001310 } else {
1311 mTempTouchState.copyFrom(mTouchState);
Jeff Browncc0c1592011-02-19 05:07:28 -08001312 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001313
Jeff Browna032cc02011-03-07 16:56:21 -08001314 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
Jeff Brown33bbfd22011-02-24 20:55:35 -08001315 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
Jeff Brownb88102f2010-09-08 11:49:43 -07001316
Jeff Browna032cc02011-03-07 16:56:21 -08001317 const MotionSample* sample = &entry->firstSample;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001318 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Jeff Browna032cc02011-03-07 16:56:21 -08001319 int32_t x = int32_t(sample->pointerCoords[pointerIndex].
Jeff Brownebbd5d12011-02-17 13:01:34 -08001320 getAxisValue(AMOTION_EVENT_AXIS_X));
Jeff Browna032cc02011-03-07 16:56:21 -08001321 int32_t y = int32_t(sample->pointerCoords[pointerIndex].
Jeff Brownebbd5d12011-02-17 13:01:34 -08001322 getAxisValue(AMOTION_EVENT_AXIS_Y));
Jeff Brown9302c872011-07-13 22:51:29 -07001323 sp<InputWindowHandle> newTouchedWindowHandle;
1324 sp<InputWindowHandle> topErrorWindowHandle;
Jeff Browna032cc02011-03-07 16:56:21 -08001325 bool isTouchModal = false;
Jeff Brownb88102f2010-09-08 11:49:43 -07001326
1327 // Traverse windows from front to back to find touched window and outside targets.
Jeff Brown9302c872011-07-13 22:51:29 -07001328 size_t numWindows = mWindowHandles.size();
Jeff Brownb88102f2010-09-08 11:49:43 -07001329 for (size_t i = 0; i < numWindows; i++) {
Jeff Brown9302c872011-07-13 22:51:29 -07001330 sp<InputWindowHandle> windowHandle = mWindowHandles.itemAt(i);
Jeff Browncc4f7db2011-08-30 20:34:48 -07001331 const InputWindowInfo* windowInfo = windowHandle->getInfo();
1332 int32_t flags = windowInfo->layoutParamsFlags;
Jeff Brownb88102f2010-09-08 11:49:43 -07001333
Jeff Browncc4f7db2011-08-30 20:34:48 -07001334 if (flags & InputWindowInfo::FLAG_SYSTEM_ERROR) {
Jeff Brown9302c872011-07-13 22:51:29 -07001335 if (topErrorWindowHandle == NULL) {
1336 topErrorWindowHandle = windowHandle;
Jeff Brownb88102f2010-09-08 11:49:43 -07001337 }
1338 }
1339
Jeff Browncc4f7db2011-08-30 20:34:48 -07001340 if (windowInfo->visible) {
1341 if (! (flags & InputWindowInfo::FLAG_NOT_TOUCHABLE)) {
1342 isTouchModal = (flags & (InputWindowInfo::FLAG_NOT_FOCUSABLE
1343 | InputWindowInfo::FLAG_NOT_TOUCH_MODAL)) == 0;
1344 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
Jeff Brown9302c872011-07-13 22:51:29 -07001345 if (! screenWasOff
Jeff Browncc4f7db2011-08-30 20:34:48 -07001346 || (flags & InputWindowInfo::FLAG_TOUCHABLE_WHEN_WAKING)) {
Jeff Brown9302c872011-07-13 22:51:29 -07001347 newTouchedWindowHandle = windowHandle;
Jeff Brownb88102f2010-09-08 11:49:43 -07001348 }
1349 break; // found touched window, exit window loop
1350 }
1351 }
1352
Jeff Brown01ce2e92010-09-26 22:20:12 -07001353 if (maskedAction == AMOTION_EVENT_ACTION_DOWN
Jeff Browncc4f7db2011-08-30 20:34:48 -07001354 && (flags & InputWindowInfo::FLAG_WATCH_OUTSIDE_TOUCH)) {
Jeff Browna032cc02011-03-07 16:56:21 -08001355 int32_t outsideTargetFlags = InputTarget::FLAG_DISPATCH_AS_OUTSIDE;
Jeff Brown9302c872011-07-13 22:51:29 -07001356 if (isWindowObscuredAtPointLocked(windowHandle, x, y)) {
Jeff Brown19dfc832010-10-05 12:26:23 -07001357 outsideTargetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1358 }
1359
Jeff Brown9302c872011-07-13 22:51:29 -07001360 mTempTouchState.addOrUpdateWindow(
1361 windowHandle, outsideTargetFlags, BitSet32(0));
Jeff Brownb88102f2010-09-08 11:49:43 -07001362 }
1363 }
1364 }
1365
1366 // If there is an error window but it is not taking focus (typically because
1367 // it is invisible) then wait for it. Any other focused window may in
1368 // fact be in ANR state.
Jeff Brown9302c872011-07-13 22:51:29 -07001369 if (topErrorWindowHandle != NULL && newTouchedWindowHandle != topErrorWindowHandle) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001370#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001371 ALOGD("Waiting because system error window is pending.");
Jeff Brownb88102f2010-09-08 11:49:43 -07001372#endif
1373 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
1374 NULL, NULL, nextWakeupTime);
1375 injectionPermission = INJECTION_PERMISSION_UNKNOWN;
1376 goto Unresponsive;
1377 }
1378
Jeff Brown01ce2e92010-09-26 22:20:12 -07001379 // Figure out whether splitting will be allowed for this window.
Jeff Browncc4f7db2011-08-30 20:34:48 -07001380 if (newTouchedWindowHandle != NULL
1381 && newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001382 // New window supports splitting.
1383 isSplit = true;
1384 } else if (isSplit) {
1385 // New window does not support splitting but we have already split events.
1386 // Assign the pointer to the first foreground window we find.
1387 // (May be NULL which is why we put this code block before the next check.)
Jeff Brown9302c872011-07-13 22:51:29 -07001388 newTouchedWindowHandle = mTempTouchState.getFirstForegroundWindowHandle();
Jeff Brown01ce2e92010-09-26 22:20:12 -07001389 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001390
Jeff Brownb88102f2010-09-08 11:49:43 -07001391 // If we did not find a touched window then fail.
Jeff Brown9302c872011-07-13 22:51:29 -07001392 if (newTouchedWindowHandle == NULL) {
1393 if (mFocusedApplicationHandle != NULL) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001394#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001395 ALOGD("Waiting because there is no touched window but there is a "
Jeff Brown519e0242010-09-15 15:18:56 -07001396 "focused application that may eventually add a new window: %s.",
Jeff Brown9302c872011-07-13 22:51:29 -07001397 getApplicationWindowLabelLocked(mFocusedApplicationHandle, NULL).string());
Jeff Brownb88102f2010-09-08 11:49:43 -07001398#endif
1399 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brown9302c872011-07-13 22:51:29 -07001400 mFocusedApplicationHandle, NULL, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -07001401 goto Unresponsive;
1402 }
1403
Steve Block6215d3f2012-01-04 20:05:49 +00001404 ALOGI("Dropping event because there is no touched window or focused application.");
Jeff Brownb88102f2010-09-08 11:49:43 -07001405 injectionResult = INPUT_EVENT_INJECTION_FAILED;
Jeff Brownb88102f2010-09-08 11:49:43 -07001406 goto Failed;
1407 }
1408
Jeff Brown19dfc832010-10-05 12:26:23 -07001409 // Set target flags.
Jeff Browna032cc02011-03-07 16:56:21 -08001410 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
Jeff Brown19dfc832010-10-05 12:26:23 -07001411 if (isSplit) {
1412 targetFlags |= InputTarget::FLAG_SPLIT;
1413 }
Jeff Brown9302c872011-07-13 22:51:29 -07001414 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
Jeff Brown19dfc832010-10-05 12:26:23 -07001415 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1416 }
1417
Jeff Browna032cc02011-03-07 16:56:21 -08001418 // Update hover state.
1419 if (isHoverAction) {
Jeff Brown9302c872011-07-13 22:51:29 -07001420 newHoverWindowHandle = newTouchedWindowHandle;
Jeff Browna032cc02011-03-07 16:56:21 -08001421
1422 // Ensure all subsequent motion samples are also within the touched window.
1423 // Set *outSplitBatchAfterSample to the sample before the first one that is not
1424 // within the touched window.
1425 if (!isTouchModal) {
1426 while (sample->next) {
Jeff Browncc4f7db2011-08-30 20:34:48 -07001427 if (!newHoverWindowHandle->getInfo()->touchableRegionContainsPoint(
Jeff Browna032cc02011-03-07 16:56:21 -08001428 sample->next->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X),
1429 sample->next->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y))) {
1430 *outSplitBatchAfterSample = sample;
1431 break;
1432 }
1433 sample = sample->next;
1434 }
1435 }
1436 } else if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
Jeff Brown9302c872011-07-13 22:51:29 -07001437 newHoverWindowHandle = mLastHoverWindowHandle;
Jeff Browna032cc02011-03-07 16:56:21 -08001438 }
1439
Jeff Brown01ce2e92010-09-26 22:20:12 -07001440 // Update the temporary touch state.
1441 BitSet32 pointerIds;
1442 if (isSplit) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07001443 uint32_t pointerId = entry->pointerProperties[pointerIndex].id;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001444 pointerIds.markBit(pointerId);
Jeff Brownb88102f2010-09-08 11:49:43 -07001445 }
Jeff Brown9302c872011-07-13 22:51:29 -07001446 mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Jeff Brownb88102f2010-09-08 11:49:43 -07001447 } else {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001448 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
Jeff Brownb88102f2010-09-08 11:49:43 -07001449
1450 // If the pointer is not currently down, then ignore the event.
Jeff Brown01ce2e92010-09-26 22:20:12 -07001451 if (! mTempTouchState.down) {
Jeff Browna2cc28d2011-03-25 11:58:46 -07001452#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001453 ALOGD("Dropping event because the pointer is not down or we previously "
Jeff Brown76860e32010-10-25 17:37:46 -07001454 "dropped the pointer down event.");
1455#endif
Jeff Brownb88102f2010-09-08 11:49:43 -07001456 injectionResult = INPUT_EVENT_INJECTION_FAILED;
Jeff Brownb88102f2010-09-08 11:49:43 -07001457 goto Failed;
1458 }
Jeff Brown98db5fa2011-06-08 15:37:10 -07001459
1460 // Check whether touches should slip outside of the current foreground window.
1461 if (maskedAction == AMOTION_EVENT_ACTION_MOVE
1462 && entry->pointerCount == 1
1463 && mTempTouchState.isSlippery()) {
1464 const MotionSample* sample = &entry->firstSample;
1465 int32_t x = int32_t(sample->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
1466 int32_t y = int32_t(sample->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
1467
Jeff Brown9302c872011-07-13 22:51:29 -07001468 sp<InputWindowHandle> oldTouchedWindowHandle =
1469 mTempTouchState.getFirstForegroundWindowHandle();
1470 sp<InputWindowHandle> newTouchedWindowHandle = findTouchedWindowAtLocked(x, y);
1471 if (oldTouchedWindowHandle != newTouchedWindowHandle
1472 && newTouchedWindowHandle != NULL) {
Jeff Brown98db5fa2011-06-08 15:37:10 -07001473#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001474 ALOGD("Touch is slipping out of window %s into window %s.",
Jeff Browncc4f7db2011-08-30 20:34:48 -07001475 oldTouchedWindowHandle->getName().string(),
1476 newTouchedWindowHandle->getName().string());
Jeff Brown98db5fa2011-06-08 15:37:10 -07001477#endif
1478 // Make a slippery exit from the old window.
Jeff Brown9302c872011-07-13 22:51:29 -07001479 mTempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
Jeff Brown98db5fa2011-06-08 15:37:10 -07001480 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT, BitSet32(0));
1481
1482 // Make a slippery entrance into the new window.
Jeff Browncc4f7db2011-08-30 20:34:48 -07001483 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Jeff Brown98db5fa2011-06-08 15:37:10 -07001484 isSplit = true;
1485 }
1486
1487 int32_t targetFlags = InputTarget::FLAG_FOREGROUND
1488 | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
1489 if (isSplit) {
1490 targetFlags |= InputTarget::FLAG_SPLIT;
1491 }
Jeff Brown9302c872011-07-13 22:51:29 -07001492 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
Jeff Brown98db5fa2011-06-08 15:37:10 -07001493 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1494 }
1495
1496 BitSet32 pointerIds;
1497 if (isSplit) {
1498 pointerIds.markBit(entry->pointerProperties[0].id);
1499 }
Jeff Brown9302c872011-07-13 22:51:29 -07001500 mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Jeff Brown98db5fa2011-06-08 15:37:10 -07001501
1502 // Split the batch here so we send exactly one sample.
1503 *outSplitBatchAfterSample = &entry->firstSample;
1504 }
1505 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001506 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001507
Jeff Brown9302c872011-07-13 22:51:29 -07001508 if (newHoverWindowHandle != mLastHoverWindowHandle) {
Jeff Browna032cc02011-03-07 16:56:21 -08001509 // Split the batch here so we send exactly one sample as part of ENTER or EXIT.
1510 *outSplitBatchAfterSample = &entry->firstSample;
1511
1512 // Let the previous window know that the hover sequence is over.
Jeff Brown9302c872011-07-13 22:51:29 -07001513 if (mLastHoverWindowHandle != NULL) {
Jeff Browna032cc02011-03-07 16:56:21 -08001514#if DEBUG_HOVER
Steve Block5baa3a62011-12-20 16:23:08 +00001515 ALOGD("Sending hover exit event to window %s.",
Jeff Browncc4f7db2011-08-30 20:34:48 -07001516 mLastHoverWindowHandle->getName().string());
Jeff Browna032cc02011-03-07 16:56:21 -08001517#endif
Jeff Brown9302c872011-07-13 22:51:29 -07001518 mTempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
Jeff Browna032cc02011-03-07 16:56:21 -08001519 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
1520 }
1521
1522 // Let the new window know that the hover sequence is starting.
Jeff Brown9302c872011-07-13 22:51:29 -07001523 if (newHoverWindowHandle != NULL) {
Jeff Browna032cc02011-03-07 16:56:21 -08001524#if DEBUG_HOVER
Steve Block5baa3a62011-12-20 16:23:08 +00001525 ALOGD("Sending hover enter event to window %s.",
Jeff Browncc4f7db2011-08-30 20:34:48 -07001526 newHoverWindowHandle->getName().string());
Jeff Browna032cc02011-03-07 16:56:21 -08001527#endif
Jeff Brown9302c872011-07-13 22:51:29 -07001528 mTempTouchState.addOrUpdateWindow(newHoverWindowHandle,
Jeff Browna032cc02011-03-07 16:56:21 -08001529 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER, BitSet32(0));
1530 }
1531 }
1532
Jeff Brown01ce2e92010-09-26 22:20:12 -07001533 // Check permission to inject into all touched foreground windows and ensure there
1534 // is at least one touched foreground window.
1535 {
1536 bool haveForegroundWindow = false;
1537 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1538 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1539 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1540 haveForegroundWindow = true;
Jeff Brown9302c872011-07-13 22:51:29 -07001541 if (! checkInjectionPermission(touchedWindow.windowHandle,
1542 entry->injectionState)) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001543 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1544 injectionPermission = INJECTION_PERMISSION_DENIED;
1545 goto Failed;
1546 }
1547 }
1548 }
1549 if (! haveForegroundWindow) {
Jeff Browna2cc28d2011-03-25 11:58:46 -07001550#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001551 ALOGD("Dropping event because there is no touched foreground window to receive it.");
Jeff Brownb88102f2010-09-08 11:49:43 -07001552#endif
1553 injectionResult = INPUT_EVENT_INJECTION_FAILED;
Jeff Brownb88102f2010-09-08 11:49:43 -07001554 goto Failed;
1555 }
1556
Jeff Brown01ce2e92010-09-26 22:20:12 -07001557 // Permission granted to injection into all touched foreground windows.
1558 injectionPermission = INJECTION_PERMISSION_GRANTED;
1559 }
Jeff Brown519e0242010-09-15 15:18:56 -07001560
Kenny Root7a9db182011-06-02 15:16:05 -07001561 // Check whether windows listening for outside touches are owned by the same UID. If it is
1562 // set the policy flag that we will not reveal coordinate information to this window.
1563 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
Jeff Brown9302c872011-07-13 22:51:29 -07001564 sp<InputWindowHandle> foregroundWindowHandle =
1565 mTempTouchState.getFirstForegroundWindowHandle();
Jeff Browncc4f7db2011-08-30 20:34:48 -07001566 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Kenny Root7a9db182011-06-02 15:16:05 -07001567 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1568 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1569 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
Jeff Brown9302c872011-07-13 22:51:29 -07001570 sp<InputWindowHandle> inputWindowHandle = touchedWindow.windowHandle;
Jeff Browncc4f7db2011-08-30 20:34:48 -07001571 if (inputWindowHandle->getInfo()->ownerUid != foregroundWindowUid) {
Jeff Brown9302c872011-07-13 22:51:29 -07001572 mTempTouchState.addOrUpdateWindow(inputWindowHandle,
Kenny Root7a9db182011-06-02 15:16:05 -07001573 InputTarget::FLAG_ZERO_COORDS, BitSet32(0));
1574 }
1575 }
1576 }
1577 }
1578
Jeff Brown01ce2e92010-09-26 22:20:12 -07001579 // Ensure all touched foreground windows are ready for new input.
1580 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1581 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1582 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1583 // If the touched window is paused then keep waiting.
Jeff Browncc4f7db2011-08-30 20:34:48 -07001584 if (touchedWindow.windowHandle->getInfo()->paused) {
Jeff Browna2cc28d2011-03-25 11:58:46 -07001585#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001586 ALOGD("Waiting because touched window is paused.");
Jeff Brown519e0242010-09-15 15:18:56 -07001587#endif
Jeff Brown01ce2e92010-09-26 22:20:12 -07001588 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brown9302c872011-07-13 22:51:29 -07001589 NULL, touchedWindow.windowHandle, nextWakeupTime);
Jeff Brown01ce2e92010-09-26 22:20:12 -07001590 goto Unresponsive;
1591 }
1592
1593 // If the touched window is still working on previous events then keep waiting.
Jeff Brown9302c872011-07-13 22:51:29 -07001594 if (! isWindowFinishedWithPreviousInputLocked(touchedWindow.windowHandle)) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001595#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001596 ALOGD("Waiting because touched window still processing previous input.");
Jeff Brown01ce2e92010-09-26 22:20:12 -07001597#endif
1598 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brown9302c872011-07-13 22:51:29 -07001599 NULL, touchedWindow.windowHandle, nextWakeupTime);
Jeff Brown01ce2e92010-09-26 22:20:12 -07001600 goto Unresponsive;
1601 }
1602 }
1603 }
1604
1605 // If this is the first pointer going down and the touched window has a wallpaper
1606 // then also add the touched wallpaper windows so they are locked in for the duration
1607 // of the touch gesture.
Jeff Brown33bbfd22011-02-24 20:55:35 -08001608 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
1609 // engine only supports touch events. We would need to add a mechanism similar
1610 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
1611 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
Jeff Brown9302c872011-07-13 22:51:29 -07001612 sp<InputWindowHandle> foregroundWindowHandle =
1613 mTempTouchState.getFirstForegroundWindowHandle();
Jeff Browncc4f7db2011-08-30 20:34:48 -07001614 if (foregroundWindowHandle->getInfo()->hasWallpaper) {
Jeff Brown9302c872011-07-13 22:51:29 -07001615 for (size_t i = 0; i < mWindowHandles.size(); i++) {
1616 sp<InputWindowHandle> windowHandle = mWindowHandles.itemAt(i);
Jeff Browncc4f7db2011-08-30 20:34:48 -07001617 if (windowHandle->getInfo()->layoutParamsType
1618 == InputWindowInfo::TYPE_WALLPAPER) {
Jeff Brown9302c872011-07-13 22:51:29 -07001619 mTempTouchState.addOrUpdateWindow(windowHandle,
Jeff Browna032cc02011-03-07 16:56:21 -08001620 InputTarget::FLAG_WINDOW_IS_OBSCURED
1621 | InputTarget::FLAG_DISPATCH_AS_IS,
1622 BitSet32(0));
Jeff Brown01ce2e92010-09-26 22:20:12 -07001623 }
1624 }
1625 }
1626 }
1627
Jeff Brownb88102f2010-09-08 11:49:43 -07001628 // Success! Output targets.
1629 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
Jeff Brownb88102f2010-09-08 11:49:43 -07001630
Jeff Brown01ce2e92010-09-26 22:20:12 -07001631 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1632 const TouchedWindow& touchedWindow = mTempTouchState.windows.itemAt(i);
Jeff Brown9302c872011-07-13 22:51:29 -07001633 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Jeff Brown01ce2e92010-09-26 22:20:12 -07001634 touchedWindow.pointerIds);
Jeff Brownb88102f2010-09-08 11:49:43 -07001635 }
1636
Jeff Browna032cc02011-03-07 16:56:21 -08001637 // Drop the outside or hover touch windows since we will not care about them
1638 // in the next iteration.
1639 mTempTouchState.filterNonAsIsTouchWindows();
Jeff Brown01ce2e92010-09-26 22:20:12 -07001640
Jeff Brownb88102f2010-09-08 11:49:43 -07001641Failed:
1642 // Check injection permission once and for all.
1643 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001644 if (checkInjectionPermission(NULL, entry->injectionState)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001645 injectionPermission = INJECTION_PERMISSION_GRANTED;
1646 } else {
1647 injectionPermission = INJECTION_PERMISSION_DENIED;
1648 }
1649 }
1650
1651 // Update final pieces of touch state if the injector had permission.
1652 if (injectionPermission == INJECTION_PERMISSION_GRANTED) {
Jeff Brown95712852011-01-04 19:41:59 -08001653 if (!wrongDevice) {
Jeff Brown81346812011-06-28 20:08:48 -07001654 if (switchedDevice) {
1655#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001656 ALOGD("Conflicting pointer actions: Switched to a different device.");
Jeff Brown81346812011-06-28 20:08:48 -07001657#endif
1658 *outConflictingPointerActions = true;
1659 }
1660
1661 if (isHoverAction) {
1662 // Started hovering, therefore no longer down.
1663 if (mTouchState.down) {
1664#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001665 ALOGD("Conflicting pointer actions: Hover received while pointer was down.");
Jeff Brown81346812011-06-28 20:08:48 -07001666#endif
1667 *outConflictingPointerActions = true;
1668 }
1669 mTouchState.reset();
1670 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER
1671 || maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
1672 mTouchState.deviceId = entry->deviceId;
1673 mTouchState.source = entry->source;
1674 }
1675 } else if (maskedAction == AMOTION_EVENT_ACTION_UP
1676 || maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Jeff Brown95712852011-01-04 19:41:59 -08001677 // All pointers up or canceled.
Jeff Brown33bbfd22011-02-24 20:55:35 -08001678 mTouchState.reset();
Jeff Brown95712852011-01-04 19:41:59 -08001679 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1680 // First pointer went down.
1681 if (mTouchState.down) {
Jeff Brownb6997262010-10-08 22:31:17 -07001682#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001683 ALOGD("Conflicting pointer actions: Down received while already down.");
Jeff Brownb6997262010-10-08 22:31:17 -07001684#endif
Jeff Brown81346812011-06-28 20:08:48 -07001685 *outConflictingPointerActions = true;
Jeff Brown95712852011-01-04 19:41:59 -08001686 }
Jeff Brown33bbfd22011-02-24 20:55:35 -08001687 mTouchState.copyFrom(mTempTouchState);
Jeff Brown95712852011-01-04 19:41:59 -08001688 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
1689 // One pointer went up.
1690 if (isSplit) {
1691 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07001692 uint32_t pointerId = entry->pointerProperties[pointerIndex].id;
Jeff Brownb88102f2010-09-08 11:49:43 -07001693
Jeff Brown95712852011-01-04 19:41:59 -08001694 for (size_t i = 0; i < mTempTouchState.windows.size(); ) {
1695 TouchedWindow& touchedWindow = mTempTouchState.windows.editItemAt(i);
1696 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
1697 touchedWindow.pointerIds.clearBit(pointerId);
1698 if (touchedWindow.pointerIds.isEmpty()) {
1699 mTempTouchState.windows.removeAt(i);
1700 continue;
1701 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001702 }
Jeff Brown95712852011-01-04 19:41:59 -08001703 i += 1;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001704 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001705 }
Jeff Brown33bbfd22011-02-24 20:55:35 -08001706 mTouchState.copyFrom(mTempTouchState);
1707 } else if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
1708 // Discard temporary touch state since it was only valid for this action.
1709 } else {
1710 // Save changes to touch state as-is for all other actions.
1711 mTouchState.copyFrom(mTempTouchState);
Jeff Brownb88102f2010-09-08 11:49:43 -07001712 }
Jeff Browna032cc02011-03-07 16:56:21 -08001713
1714 // Update hover state.
Jeff Brown9302c872011-07-13 22:51:29 -07001715 mLastHoverWindowHandle = newHoverWindowHandle;
Jeff Brown95712852011-01-04 19:41:59 -08001716 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001717 } else {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001718#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001719 ALOGD("Not updating touch focus because injection was denied.");
Jeff Brown01ce2e92010-09-26 22:20:12 -07001720#endif
Jeff Brownb88102f2010-09-08 11:49:43 -07001721 }
1722
1723Unresponsive:
Jeff Brown120a4592010-10-27 18:43:51 -07001724 // Reset temporary touch state to ensure we release unnecessary references to input channels.
1725 mTempTouchState.reset();
1726
Jeff Brown519e0242010-09-15 15:18:56 -07001727 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
1728 updateDispatchStatisticsLocked(currentTime, entry,
1729 injectionResult, timeSpentWaitingForApplication);
Jeff Brownb88102f2010-09-08 11:49:43 -07001730#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001731 ALOGD("findTouchedWindow finished: injectionResult=%d, injectionPermission=%d, "
Jeff Brown01ce2e92010-09-26 22:20:12 -07001732 "timeSpentWaitingForApplication=%0.1fms",
Jeff Brown519e0242010-09-15 15:18:56 -07001733 injectionResult, injectionPermission, timeSpentWaitingForApplication / 1000000.0);
Jeff Brownb88102f2010-09-08 11:49:43 -07001734#endif
1735 return injectionResult;
1736}
1737
Jeff Brown9302c872011-07-13 22:51:29 -07001738void InputDispatcher::addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
1739 int32_t targetFlags, BitSet32 pointerIds) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001740 mCurrentInputTargets.push();
1741
Jeff Browncc4f7db2011-08-30 20:34:48 -07001742 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Jeff Brownb88102f2010-09-08 11:49:43 -07001743 InputTarget& target = mCurrentInputTargets.editTop();
Jeff Browncc4f7db2011-08-30 20:34:48 -07001744 target.inputChannel = windowInfo->inputChannel;
Jeff Brownb88102f2010-09-08 11:49:43 -07001745 target.flags = targetFlags;
Jeff Browncc4f7db2011-08-30 20:34:48 -07001746 target.xOffset = - windowInfo->frameLeft;
1747 target.yOffset = - windowInfo->frameTop;
1748 target.scaleFactor = windowInfo->scaleFactor;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001749 target.pointerIds = pointerIds;
Jeff Brownb88102f2010-09-08 11:49:43 -07001750}
1751
1752void InputDispatcher::addMonitoringTargetsLocked() {
1753 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
1754 mCurrentInputTargets.push();
1755
1756 InputTarget& target = mCurrentInputTargets.editTop();
1757 target.inputChannel = mMonitoringChannels[i];
Jeff Brownb6110c22011-04-01 16:15:13 -07001758 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
Jeff Brownb88102f2010-09-08 11:49:43 -07001759 target.xOffset = 0;
1760 target.yOffset = 0;
Jeff Brownb6110c22011-04-01 16:15:13 -07001761 target.pointerIds.clear();
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001762 target.scaleFactor = 1.0f;
Jeff Brownb88102f2010-09-08 11:49:43 -07001763 }
1764}
1765
Jeff Brown9302c872011-07-13 22:51:29 -07001766bool InputDispatcher::checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
Jeff Brown01ce2e92010-09-26 22:20:12 -07001767 const InjectionState* injectionState) {
1768 if (injectionState
Jeff Browncc4f7db2011-08-30 20:34:48 -07001769 && (windowHandle == NULL
1770 || windowHandle->getInfo()->ownerUid != injectionState->injectorUid)
Jeff Brownb6997262010-10-08 22:31:17 -07001771 && !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Jeff Brown9302c872011-07-13 22:51:29 -07001772 if (windowHandle != NULL) {
Steve Block8564c8d2012-01-05 23:22:43 +00001773 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
Jeff Brown9302c872011-07-13 22:51:29 -07001774 "owned by uid %d",
Jeff Brownb6997262010-10-08 22:31:17 -07001775 injectionState->injectorPid, injectionState->injectorUid,
Jeff Browncc4f7db2011-08-30 20:34:48 -07001776 windowHandle->getName().string(),
1777 windowHandle->getInfo()->ownerUid);
Jeff Brownb6997262010-10-08 22:31:17 -07001778 } else {
Steve Block8564c8d2012-01-05 23:22:43 +00001779 ALOGW("Permission denied: injecting event from pid %d uid %d",
Jeff Brownb6997262010-10-08 22:31:17 -07001780 injectionState->injectorPid, injectionState->injectorUid);
Jeff Brownb88102f2010-09-08 11:49:43 -07001781 }
Jeff Brownb6997262010-10-08 22:31:17 -07001782 return false;
Jeff Brownb88102f2010-09-08 11:49:43 -07001783 }
1784 return true;
1785}
1786
Jeff Brown19dfc832010-10-05 12:26:23 -07001787bool InputDispatcher::isWindowObscuredAtPointLocked(
Jeff Brown9302c872011-07-13 22:51:29 -07001788 const sp<InputWindowHandle>& windowHandle, int32_t x, int32_t y) const {
1789 size_t numWindows = mWindowHandles.size();
Jeff Brownb88102f2010-09-08 11:49:43 -07001790 for (size_t i = 0; i < numWindows; i++) {
Jeff Brown9302c872011-07-13 22:51:29 -07001791 sp<InputWindowHandle> otherHandle = mWindowHandles.itemAt(i);
1792 if (otherHandle == windowHandle) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001793 break;
1794 }
Jeff Browncc4f7db2011-08-30 20:34:48 -07001795
1796 const InputWindowInfo* otherInfo = otherHandle->getInfo();
1797 if (otherInfo->visible && ! otherInfo->isTrustedOverlay()
1798 && otherInfo->frameContainsPoint(x, y)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001799 return true;
1800 }
1801 }
1802 return false;
1803}
1804
Jeff Brown9302c872011-07-13 22:51:29 -07001805bool InputDispatcher::isWindowFinishedWithPreviousInputLocked(
1806 const sp<InputWindowHandle>& windowHandle) {
Jeff Browncc4f7db2011-08-30 20:34:48 -07001807 ssize_t connectionIndex = getConnectionIndexLocked(windowHandle->getInputChannel());
Jeff Brown519e0242010-09-15 15:18:56 -07001808 if (connectionIndex >= 0) {
1809 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
1810 return connection->outboundQueue.isEmpty();
1811 } else {
1812 return true;
1813 }
1814}
1815
Jeff Brown9302c872011-07-13 22:51:29 -07001816String8 InputDispatcher::getApplicationWindowLabelLocked(
1817 const sp<InputApplicationHandle>& applicationHandle,
1818 const sp<InputWindowHandle>& windowHandle) {
1819 if (applicationHandle != NULL) {
1820 if (windowHandle != NULL) {
Jeff Browncc4f7db2011-08-30 20:34:48 -07001821 String8 label(applicationHandle->getName());
Jeff Brown519e0242010-09-15 15:18:56 -07001822 label.append(" - ");
Jeff Browncc4f7db2011-08-30 20:34:48 -07001823 label.append(windowHandle->getName());
Jeff Brown519e0242010-09-15 15:18:56 -07001824 return label;
1825 } else {
Jeff Browncc4f7db2011-08-30 20:34:48 -07001826 return applicationHandle->getName();
Jeff Brown519e0242010-09-15 15:18:56 -07001827 }
Jeff Brown9302c872011-07-13 22:51:29 -07001828 } else if (windowHandle != NULL) {
Jeff Browncc4f7db2011-08-30 20:34:48 -07001829 return windowHandle->getName();
Jeff Brown519e0242010-09-15 15:18:56 -07001830 } else {
1831 return String8("<unknown application or window>");
1832 }
1833}
1834
Jeff Browne2fe69e2010-10-18 13:21:23 -07001835void InputDispatcher::pokeUserActivityLocked(const EventEntry* eventEntry) {
Jeff Brown56194eb2011-03-02 19:23:13 -08001836 int32_t eventType = POWER_MANAGER_OTHER_EVENT;
Jeff Brown4d396052010-10-29 21:50:21 -07001837 switch (eventEntry->type) {
1838 case EventEntry::TYPE_MOTION: {
Jeff Browne2fe69e2010-10-18 13:21:23 -07001839 const MotionEntry* motionEntry = static_cast<const MotionEntry*>(eventEntry);
Jeff Brown4d396052010-10-29 21:50:21 -07001840 if (motionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
1841 return;
1842 }
1843
Jeff Brown56194eb2011-03-02 19:23:13 -08001844 if (MotionEvent::isTouchEvent(motionEntry->source, motionEntry->action)) {
Joe Onorato1a542c72010-11-08 09:48:20 -08001845 eventType = POWER_MANAGER_TOUCH_EVENT;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001846 }
Jeff Brown4d396052010-10-29 21:50:21 -07001847 break;
1848 }
1849 case EventEntry::TYPE_KEY: {
1850 const KeyEntry* keyEntry = static_cast<const KeyEntry*>(eventEntry);
1851 if (keyEntry->flags & AKEY_EVENT_FLAG_CANCELED) {
1852 return;
1853 }
Jeff Brown56194eb2011-03-02 19:23:13 -08001854 eventType = POWER_MANAGER_BUTTON_EVENT;
Jeff Brown4d396052010-10-29 21:50:21 -07001855 break;
1856 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001857 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001858
Jeff Brownb88102f2010-09-08 11:49:43 -07001859 CommandEntry* commandEntry = postCommandLocked(
1860 & InputDispatcher::doPokeUserActivityLockedInterruptible);
Jeff Browne2fe69e2010-10-18 13:21:23 -07001861 commandEntry->eventTime = eventEntry->eventTime;
Jeff Brownb88102f2010-09-08 11:49:43 -07001862 commandEntry->userActivityEventType = eventType;
1863}
1864
Jeff Brown7fbdc842010-06-17 20:52:56 -07001865void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
1866 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget,
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001867 bool resumeWithAppendedMotionSample) {
1868#if DEBUG_DISPATCH_CYCLE
Steve Block5baa3a62011-12-20 16:23:08 +00001869 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
Jeff Brown9cc695c2011-08-23 18:35:04 -07001870 "xOffset=%f, yOffset=%f, scaleFactor=%f, "
Jeff Brown83c09682010-12-23 17:50:18 -08001871 "pointerIds=0x%x, "
Jeff Brown01ce2e92010-09-26 22:20:12 -07001872 "resumeWithAppendedMotionSample=%s",
Jeff Brown519e0242010-09-15 15:18:56 -07001873 connection->getInputChannelName(), inputTarget->flags,
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001874 inputTarget->xOffset, inputTarget->yOffset,
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001875 inputTarget->scaleFactor, inputTarget->pointerIds.value,
Jeff Brownb88102f2010-09-08 11:49:43 -07001876 toString(resumeWithAppendedMotionSample));
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001877#endif
1878
Jeff Brown01ce2e92010-09-26 22:20:12 -07001879 // Make sure we are never called for streaming when splitting across multiple windows.
1880 bool isSplit = inputTarget->flags & InputTarget::FLAG_SPLIT;
Steve Blockec193de2012-01-09 18:35:44 +00001881 ALOG_ASSERT(! (resumeWithAppendedMotionSample && isSplit));
Jeff Brown01ce2e92010-09-26 22:20:12 -07001882
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001883 // Skip this event if the connection status is not normal.
Jeff Brown519e0242010-09-15 15:18:56 -07001884 // We don't want to enqueue additional outbound events if the connection is broken.
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001885 if (connection->status != Connection::STATUS_NORMAL) {
Jeff Brownb6997262010-10-08 22:31:17 -07001886#if DEBUG_DISPATCH_CYCLE
Steve Block5baa3a62011-12-20 16:23:08 +00001887 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Jeff Brownb88102f2010-09-08 11:49:43 -07001888 connection->getInputChannelName(), connection->getStatusLabel());
Jeff Brownb6997262010-10-08 22:31:17 -07001889#endif
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001890 return;
1891 }
1892
Jeff Brown01ce2e92010-09-26 22:20:12 -07001893 // Split a motion event if needed.
1894 if (isSplit) {
Steve Blockec193de2012-01-09 18:35:44 +00001895 ALOG_ASSERT(eventEntry->type == EventEntry::TYPE_MOTION);
Jeff Brown01ce2e92010-09-26 22:20:12 -07001896
1897 MotionEntry* originalMotionEntry = static_cast<MotionEntry*>(eventEntry);
1898 if (inputTarget->pointerIds.count() != originalMotionEntry->pointerCount) {
1899 MotionEntry* splitMotionEntry = splitMotionEvent(
1900 originalMotionEntry, inputTarget->pointerIds);
Jeff Brown58a2da82011-01-25 16:02:22 -08001901 if (!splitMotionEntry) {
1902 return; // split event was dropped
1903 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001904#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001905 ALOGD("channel '%s' ~ Split motion event.",
Jeff Brown01ce2e92010-09-26 22:20:12 -07001906 connection->getInputChannelName());
1907 logOutboundMotionDetailsLocked(" ", splitMotionEntry);
1908#endif
Jeff Brownc0cb3dc2012-01-12 18:30:12 -08001909 enqueueDispatchEntriesLocked(currentTime, connection,
1910 splitMotionEntry, inputTarget, resumeWithAppendedMotionSample);
1911 splitMotionEntry->release();
1912 return;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001913 }
1914 }
1915
Jeff Brownc0cb3dc2012-01-12 18:30:12 -08001916 // Not splitting. Enqueue dispatch entries for the event as is.
1917 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget,
1918 resumeWithAppendedMotionSample);
1919}
1920
1921void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
1922 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget,
1923 bool resumeWithAppendedMotionSample) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001924 // Resume the dispatch cycle with a freshly appended motion sample.
1925 // First we check that the last dispatch entry in the outbound queue is for the same
1926 // motion event to which we appended the motion sample. If we find such a dispatch
1927 // entry, and if it is currently in progress then we try to stream the new sample.
1928 bool wasEmpty = connection->outboundQueue.isEmpty();
1929
1930 if (! wasEmpty && resumeWithAppendedMotionSample) {
1931 DispatchEntry* motionEventDispatchEntry =
1932 connection->findQueuedDispatchEntryForEvent(eventEntry);
1933 if (motionEventDispatchEntry) {
1934 // If the dispatch entry is not in progress, then we must be busy dispatching an
1935 // earlier event. Not a problem, the motion event is on the outbound queue and will
1936 // be dispatched later.
1937 if (! motionEventDispatchEntry->inProgress) {
1938#if DEBUG_BATCHING
Steve Block5baa3a62011-12-20 16:23:08 +00001939 ALOGD("channel '%s' ~ Not streaming because the motion event has "
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001940 "not yet been dispatched. "
1941 "(Waiting for earlier events to be consumed.)",
1942 connection->getInputChannelName());
1943#endif
1944 return;
1945 }
1946
1947 // If the dispatch entry is in progress but it already has a tail of pending
1948 // motion samples, then it must mean that the shared memory buffer filled up.
1949 // Not a problem, when this dispatch cycle is finished, we will eventually start
1950 // a new dispatch cycle to process the tail and that tail includes the newly
1951 // appended motion sample.
1952 if (motionEventDispatchEntry->tailMotionSample) {
1953#if DEBUG_BATCHING
Steve Block5baa3a62011-12-20 16:23:08 +00001954 ALOGD("channel '%s' ~ Not streaming because no new samples can "
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001955 "be appended to the motion event in this dispatch cycle. "
1956 "(Waiting for next dispatch cycle to start.)",
1957 connection->getInputChannelName());
1958#endif
1959 return;
1960 }
1961
Jeff Brown81346812011-06-28 20:08:48 -07001962 // If the motion event was modified in flight, then we cannot stream the sample.
1963 if ((motionEventDispatchEntry->targetFlags & InputTarget::FLAG_DISPATCH_MASK)
1964 != InputTarget::FLAG_DISPATCH_AS_IS) {
1965#if DEBUG_BATCHING
Steve Block5baa3a62011-12-20 16:23:08 +00001966 ALOGD("channel '%s' ~ Not streaming because the motion event was not "
Jeff Brown81346812011-06-28 20:08:48 -07001967 "being dispatched as-is. "
1968 "(Waiting for next dispatch cycle to start.)",
1969 connection->getInputChannelName());
1970#endif
1971 return;
1972 }
1973
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001974 // The dispatch entry is in progress and is still potentially open for streaming.
1975 // Try to stream the new motion sample. This might fail if the consumer has already
1976 // consumed the motion event (or if the channel is broken).
Jeff Brown01ce2e92010-09-26 22:20:12 -07001977 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
1978 MotionSample* appendedMotionSample = motionEntry->lastSample;
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001979 status_t status;
1980 if (motionEventDispatchEntry->scaleFactor == 1.0f) {
1981 status = connection->inputPublisher.appendMotionSample(
1982 appendedMotionSample->eventTime, appendedMotionSample->pointerCoords);
1983 } else {
1984 PointerCoords scaledCoords[MAX_POINTERS];
1985 for (size_t i = 0; i < motionEntry->pointerCount; i++) {
1986 scaledCoords[i] = appendedMotionSample->pointerCoords[i];
1987 scaledCoords[i].scale(motionEventDispatchEntry->scaleFactor);
1988 }
1989 status = connection->inputPublisher.appendMotionSample(
1990 appendedMotionSample->eventTime, scaledCoords);
1991 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001992 if (status == OK) {
1993#if DEBUG_BATCHING
Steve Block5baa3a62011-12-20 16:23:08 +00001994 ALOGD("channel '%s' ~ Successfully streamed new motion sample.",
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001995 connection->getInputChannelName());
1996#endif
1997 return;
1998 }
1999
2000#if DEBUG_BATCHING
2001 if (status == NO_MEMORY) {
Steve Block5baa3a62011-12-20 16:23:08 +00002002 ALOGD("channel '%s' ~ Could not append motion sample to currently "
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002003 "dispatched move event because the shared memory buffer is full. "
2004 "(Waiting for next dispatch cycle to start.)",
2005 connection->getInputChannelName());
2006 } else if (status == status_t(FAILED_TRANSACTION)) {
Steve Block5baa3a62011-12-20 16:23:08 +00002007 ALOGD("channel '%s' ~ Could not append motion sample to currently "
Jeff Brown349703e2010-06-22 01:27:15 -07002008 "dispatched move event because the event has already been consumed. "
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002009 "(Waiting for next dispatch cycle to start.)",
2010 connection->getInputChannelName());
2011 } else {
Steve Block5baa3a62011-12-20 16:23:08 +00002012 ALOGD("channel '%s' ~ Could not append motion sample to currently "
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002013 "dispatched move event due to an error, status=%d. "
2014 "(Waiting for next dispatch cycle to start.)",
2015 connection->getInputChannelName(), status);
2016 }
2017#endif
2018 // Failed to stream. Start a new tail of pending motion samples to dispatch
2019 // in the next cycle.
2020 motionEventDispatchEntry->tailMotionSample = appendedMotionSample;
2021 return;
2022 }
2023 }
2024
Jeff Browna032cc02011-03-07 16:56:21 -08002025 // Enqueue dispatch entries for the requested modes.
2026 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
2027 resumeWithAppendedMotionSample, InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
2028 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
2029 resumeWithAppendedMotionSample, InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
2030 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
2031 resumeWithAppendedMotionSample, InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
2032 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
2033 resumeWithAppendedMotionSample, InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brown98db5fa2011-06-08 15:37:10 -07002034 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
2035 resumeWithAppendedMotionSample, InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
2036 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
2037 resumeWithAppendedMotionSample, InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Jeff Browna032cc02011-03-07 16:56:21 -08002038
2039 // If the outbound queue was previously empty, start the dispatch cycle going.
Jeff Brownb6110c22011-04-01 16:15:13 -07002040 if (wasEmpty && !connection->outboundQueue.isEmpty()) {
Jeff Browna032cc02011-03-07 16:56:21 -08002041 activateConnectionLocked(connection.get());
2042 startDispatchCycleLocked(currentTime, connection);
2043 }
2044}
2045
2046void InputDispatcher::enqueueDispatchEntryLocked(
2047 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget,
2048 bool resumeWithAppendedMotionSample, int32_t dispatchMode) {
2049 int32_t inputTargetFlags = inputTarget->flags;
2050 if (!(inputTargetFlags & dispatchMode)) {
2051 return;
2052 }
2053 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
2054
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002055 // This is a new event.
2056 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Jeff Brownac386072011-07-20 15:19:50 -07002057 DispatchEntry* dispatchEntry = new DispatchEntry(eventEntry, // increments ref
Dianne Hackbornaa9d84c2011-05-09 19:00:59 -07002058 inputTargetFlags, inputTarget->xOffset, inputTarget->yOffset,
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002059 inputTarget->scaleFactor);
Jeff Brown6ec402b2010-07-28 15:48:59 -07002060
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002061 // Handle the case where we could not stream a new motion sample because the consumer has
2062 // already consumed the motion event (otherwise the corresponding dispatch entry would
2063 // still be in the outbound queue for this connection). We set the head motion sample
2064 // to the list starting with the newly appended motion sample.
2065 if (resumeWithAppendedMotionSample) {
2066#if DEBUG_BATCHING
Steve Block5baa3a62011-12-20 16:23:08 +00002067 ALOGD("channel '%s' ~ Preparing a new dispatch cycle for additional motion samples "
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002068 "that cannot be streamed because the motion event has already been consumed.",
2069 connection->getInputChannelName());
2070#endif
2071 MotionSample* appendedMotionSample = static_cast<MotionEntry*>(eventEntry)->lastSample;
2072 dispatchEntry->headMotionSample = appendedMotionSample;
2073 }
2074
Jeff Brown81346812011-06-28 20:08:48 -07002075 // Apply target flags and update the connection's input state.
2076 switch (eventEntry->type) {
2077 case EventEntry::TYPE_KEY: {
2078 KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
2079 dispatchEntry->resolvedAction = keyEntry->action;
2080 dispatchEntry->resolvedFlags = keyEntry->flags;
2081
2082 if (!connection->inputState.trackKey(keyEntry,
2083 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags)) {
2084#if DEBUG_DISPATCH_CYCLE
Steve Block5baa3a62011-12-20 16:23:08 +00002085 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
Jeff Brown81346812011-06-28 20:08:48 -07002086 connection->getInputChannelName());
2087#endif
Jeff Brownc0cb3dc2012-01-12 18:30:12 -08002088 delete dispatchEntry;
Jeff Brown81346812011-06-28 20:08:48 -07002089 return; // skip the inconsistent event
2090 }
2091 break;
2092 }
2093
2094 case EventEntry::TYPE_MOTION: {
2095 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
2096 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2097 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
2098 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
2099 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
2100 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
2101 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2102 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
2103 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
2104 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
2105 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
2106 } else {
2107 dispatchEntry->resolvedAction = motionEntry->action;
2108 }
2109 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE
2110 && !connection->inputState.isHovering(
2111 motionEntry->deviceId, motionEntry->source)) {
2112#if DEBUG_DISPATCH_CYCLE
Steve Block5baa3a62011-12-20 16:23:08 +00002113 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter event",
Jeff Brown81346812011-06-28 20:08:48 -07002114 connection->getInputChannelName());
2115#endif
2116 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2117 }
2118
2119 dispatchEntry->resolvedFlags = motionEntry->flags;
2120 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
2121 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
2122 }
2123
2124 if (!connection->inputState.trackMotion(motionEntry,
2125 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags)) {
2126#if DEBUG_DISPATCH_CYCLE
Steve Block5baa3a62011-12-20 16:23:08 +00002127 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion event",
Jeff Brown81346812011-06-28 20:08:48 -07002128 connection->getInputChannelName());
2129#endif
Jeff Brownc0cb3dc2012-01-12 18:30:12 -08002130 delete dispatchEntry;
Jeff Brown81346812011-06-28 20:08:48 -07002131 return; // skip the inconsistent event
2132 }
2133 break;
2134 }
2135 }
2136
Jeff Brownc0cb3dc2012-01-12 18:30:12 -08002137 // Remember that we are waiting for this dispatch to complete.
2138 if (dispatchEntry->hasForegroundTarget()) {
2139 incrementPendingForegroundDispatchesLocked(eventEntry);
2140 }
2141
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002142 // Enqueue the dispatch entry.
2143 connection->outboundQueue.enqueueAtTail(dispatchEntry);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002144}
2145
Jeff Brown7fbdc842010-06-17 20:52:56 -07002146void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Jeff Brown519e0242010-09-15 15:18:56 -07002147 const sp<Connection>& connection) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002148#if DEBUG_DISPATCH_CYCLE
Steve Block5baa3a62011-12-20 16:23:08 +00002149 ALOGD("channel '%s' ~ startDispatchCycle",
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002150 connection->getInputChannelName());
2151#endif
2152
Steve Blockec193de2012-01-09 18:35:44 +00002153 ALOG_ASSERT(connection->status == Connection::STATUS_NORMAL);
2154 ALOG_ASSERT(! connection->outboundQueue.isEmpty());
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002155
Jeff Brownac386072011-07-20 15:19:50 -07002156 DispatchEntry* dispatchEntry = connection->outboundQueue.head;
Steve Blockec193de2012-01-09 18:35:44 +00002157 ALOG_ASSERT(! dispatchEntry->inProgress);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002158
Jeff Brownb88102f2010-09-08 11:49:43 -07002159 // Mark the dispatch entry as in progress.
2160 dispatchEntry->inProgress = true;
2161
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002162 // Publish the event.
2163 status_t status;
Jeff Browna032cc02011-03-07 16:56:21 -08002164 EventEntry* eventEntry = dispatchEntry->eventEntry;
Jeff Brown01ce2e92010-09-26 22:20:12 -07002165 switch (eventEntry->type) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002166 case EventEntry::TYPE_KEY: {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002167 KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002168
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002169 // Publish the key event.
Jeff Brown81346812011-06-28 20:08:48 -07002170 status = connection->inputPublisher.publishKeyEvent(
2171 keyEntry->deviceId, keyEntry->source,
2172 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags,
2173 keyEntry->keyCode, keyEntry->scanCode,
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002174 keyEntry->metaState, keyEntry->repeatCount, keyEntry->downTime,
2175 keyEntry->eventTime);
2176
2177 if (status) {
Steve Block3762c312012-01-06 19:20:56 +00002178 ALOGE("channel '%s' ~ Could not publish key event, "
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002179 "status=%d", connection->getInputChannelName(), status);
Jeff Browncc4f7db2011-08-30 20:34:48 -07002180 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002181 return;
2182 }
2183 break;
2184 }
2185
2186 case EventEntry::TYPE_MOTION: {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002187 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002188
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002189 // If headMotionSample is non-NULL, then it points to the first new sample that we
2190 // were unable to dispatch during the previous cycle so we resume dispatching from
2191 // that point in the list of motion samples.
2192 // Otherwise, we just start from the first sample of the motion event.
2193 MotionSample* firstMotionSample = dispatchEntry->headMotionSample;
2194 if (! firstMotionSample) {
2195 firstMotionSample = & motionEntry->firstSample;
2196 }
2197
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002198 PointerCoords scaledCoords[MAX_POINTERS];
2199 const PointerCoords* usingCoords = firstMotionSample->pointerCoords;
2200
Jeff Brownd3616592010-07-16 17:21:06 -07002201 // Set the X and Y offset depending on the input source.
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002202 float xOffset, yOffset, scaleFactor;
Kenny Root7a9db182011-06-02 15:16:05 -07002203 if (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER
2204 && !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002205 scaleFactor = dispatchEntry->scaleFactor;
2206 xOffset = dispatchEntry->xOffset * scaleFactor;
2207 yOffset = dispatchEntry->yOffset * scaleFactor;
2208 if (scaleFactor != 1.0f) {
2209 for (size_t i = 0; i < motionEntry->pointerCount; i++) {
2210 scaledCoords[i] = firstMotionSample->pointerCoords[i];
2211 scaledCoords[i].scale(scaleFactor);
2212 }
2213 usingCoords = scaledCoords;
2214 }
Jeff Brownd3616592010-07-16 17:21:06 -07002215 } else {
2216 xOffset = 0.0f;
2217 yOffset = 0.0f;
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002218 scaleFactor = 1.0f;
Kenny Root7a9db182011-06-02 15:16:05 -07002219
2220 // We don't want the dispatch target to know.
2221 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
2222 for (size_t i = 0; i < motionEntry->pointerCount; i++) {
2223 scaledCoords[i].clear();
2224 }
2225 usingCoords = scaledCoords;
2226 }
Jeff Brownd3616592010-07-16 17:21:06 -07002227 }
2228
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002229 // Publish the motion event and the first motion sample.
Jeff Brown81346812011-06-28 20:08:48 -07002230 status = connection->inputPublisher.publishMotionEvent(
2231 motionEntry->deviceId, motionEntry->source,
2232 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags,
2233 motionEntry->edgeFlags, motionEntry->metaState, motionEntry->buttonState,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002234 xOffset, yOffset,
2235 motionEntry->xPrecision, motionEntry->yPrecision,
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002236 motionEntry->downTime, firstMotionSample->eventTime,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002237 motionEntry->pointerCount, motionEntry->pointerProperties,
2238 usingCoords);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002239
2240 if (status) {
Steve Block3762c312012-01-06 19:20:56 +00002241 ALOGE("channel '%s' ~ Could not publish motion event, "
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002242 "status=%d", connection->getInputChannelName(), status);
Jeff Browncc4f7db2011-08-30 20:34:48 -07002243 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002244 return;
2245 }
2246
Jeff Brown81346812011-06-28 20:08:48 -07002247 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_MOVE
2248 || dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Jeff Browna032cc02011-03-07 16:56:21 -08002249 // Append additional motion samples.
2250 MotionSample* nextMotionSample = firstMotionSample->next;
2251 for (; nextMotionSample != NULL; nextMotionSample = nextMotionSample->next) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002252 if (usingCoords == scaledCoords) {
Kenny Root7a9db182011-06-02 15:16:05 -07002253 if (!(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
2254 for (size_t i = 0; i < motionEntry->pointerCount; i++) {
2255 scaledCoords[i] = nextMotionSample->pointerCoords[i];
2256 scaledCoords[i].scale(scaleFactor);
2257 }
Dianne Hackborn2ba3e802011-05-11 10:59:54 -07002258 }
2259 } else {
2260 usingCoords = nextMotionSample->pointerCoords;
Dianne Hackborne7d25b72011-05-09 21:19:26 -07002261 }
Jeff Browna032cc02011-03-07 16:56:21 -08002262 status = connection->inputPublisher.appendMotionSample(
Dianne Hackbornaa9d84c2011-05-09 19:00:59 -07002263 nextMotionSample->eventTime, usingCoords);
Jeff Browna032cc02011-03-07 16:56:21 -08002264 if (status == NO_MEMORY) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002265#if DEBUG_DISPATCH_CYCLE
Steve Block5baa3a62011-12-20 16:23:08 +00002266 ALOGD("channel '%s' ~ Shared memory buffer full. Some motion samples will "
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002267 "be sent in the next dispatch cycle.",
2268 connection->getInputChannelName());
2269#endif
Jeff Browna032cc02011-03-07 16:56:21 -08002270 break;
2271 }
2272 if (status != OK) {
Steve Block3762c312012-01-06 19:20:56 +00002273 ALOGE("channel '%s' ~ Could not append motion sample "
Jeff Browna032cc02011-03-07 16:56:21 -08002274 "for a reason other than out of memory, status=%d",
2275 connection->getInputChannelName(), status);
Jeff Browncc4f7db2011-08-30 20:34:48 -07002276 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
Jeff Browna032cc02011-03-07 16:56:21 -08002277 return;
2278 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002279 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002280
Jeff Browna032cc02011-03-07 16:56:21 -08002281 // Remember the next motion sample that we could not dispatch, in case we ran out
2282 // of space in the shared memory buffer.
2283 dispatchEntry->tailMotionSample = nextMotionSample;
2284 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002285 break;
2286 }
2287
2288 default: {
Steve Blockec193de2012-01-09 18:35:44 +00002289 ALOG_ASSERT(false);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002290 }
2291 }
2292
2293 // Send the dispatch signal.
2294 status = connection->inputPublisher.sendDispatchSignal();
2295 if (status) {
Steve Block3762c312012-01-06 19:20:56 +00002296 ALOGE("channel '%s' ~ Could not send dispatch signal, status=%d",
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002297 connection->getInputChannelName(), status);
Jeff Browncc4f7db2011-08-30 20:34:48 -07002298 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002299 return;
2300 }
2301
2302 // Record information about the newly started dispatch cycle.
Jeff Brown01ce2e92010-09-26 22:20:12 -07002303 connection->lastEventTime = eventEntry->eventTime;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002304 connection->lastDispatchTime = currentTime;
2305
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002306 // Notify other system components.
2307 onDispatchCycleStartedLocked(currentTime, connection);
2308}
2309
Jeff Brown7fbdc842010-06-17 20:52:56 -07002310void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Jeff Brown3915bb82010-11-05 15:02:16 -07002311 const sp<Connection>& connection, bool handled) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002312#if DEBUG_DISPATCH_CYCLE
Steve Block5baa3a62011-12-20 16:23:08 +00002313 ALOGD("channel '%s' ~ finishDispatchCycle - %01.1fms since event, "
Jeff Brown3915bb82010-11-05 15:02:16 -07002314 "%01.1fms since dispatch, handled=%s",
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002315 connection->getInputChannelName(),
2316 connection->getEventLatencyMillis(currentTime),
Jeff Brown3915bb82010-11-05 15:02:16 -07002317 connection->getDispatchLatencyMillis(currentTime),
2318 toString(handled));
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002319#endif
2320
Jeff Brown9c3cda02010-06-15 01:31:58 -07002321 if (connection->status == Connection::STATUS_BROKEN
2322 || connection->status == Connection::STATUS_ZOMBIE) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002323 return;
2324 }
2325
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002326 // Reset the publisher since the event has been consumed.
2327 // We do this now so that the publisher can release some of its internal resources
2328 // while waiting for the next dispatch cycle to begin.
2329 status_t status = connection->inputPublisher.reset();
2330 if (status) {
Steve Block3762c312012-01-06 19:20:56 +00002331 ALOGE("channel '%s' ~ Could not reset publisher, status=%d",
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002332 connection->getInputChannelName(), status);
Jeff Browncc4f7db2011-08-30 20:34:48 -07002333 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002334 return;
2335 }
2336
Jeff Brown3915bb82010-11-05 15:02:16 -07002337 // Notify other system components and prepare to start the next dispatch cycle.
2338 onDispatchCycleFinishedLocked(currentTime, connection, handled);
Jeff Brownb88102f2010-09-08 11:49:43 -07002339}
2340
2341void InputDispatcher::startNextDispatchCycleLocked(nsecs_t currentTime,
2342 const sp<Connection>& connection) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002343 // Start the next dispatch cycle for this connection.
2344 while (! connection->outboundQueue.isEmpty()) {
Jeff Brownac386072011-07-20 15:19:50 -07002345 DispatchEntry* dispatchEntry = connection->outboundQueue.head;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002346 if (dispatchEntry->inProgress) {
2347 // Finish or resume current event in progress.
2348 if (dispatchEntry->tailMotionSample) {
2349 // We have a tail of undispatched motion samples.
2350 // Reuse the same DispatchEntry and start a new cycle.
2351 dispatchEntry->inProgress = false;
2352 dispatchEntry->headMotionSample = dispatchEntry->tailMotionSample;
2353 dispatchEntry->tailMotionSample = NULL;
Jeff Brown519e0242010-09-15 15:18:56 -07002354 startDispatchCycleLocked(currentTime, connection);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002355 return;
2356 }
2357 // Finished.
2358 connection->outboundQueue.dequeueAtHead();
Jeff Brown519e0242010-09-15 15:18:56 -07002359 if (dispatchEntry->hasForegroundTarget()) {
2360 decrementPendingForegroundDispatchesLocked(dispatchEntry->eventEntry);
Jeff Brown6ec402b2010-07-28 15:48:59 -07002361 }
Jeff Brownac386072011-07-20 15:19:50 -07002362 delete dispatchEntry;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002363 } else {
2364 // If the head is not in progress, then we must have already dequeued the in
Jeff Brown519e0242010-09-15 15:18:56 -07002365 // progress event, which means we actually aborted it.
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002366 // So just start the next event for this connection.
Jeff Brown519e0242010-09-15 15:18:56 -07002367 startDispatchCycleLocked(currentTime, connection);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002368 return;
2369 }
2370 }
2371
2372 // Outbound queue is empty, deactivate the connection.
Jeff Brown7fbdc842010-06-17 20:52:56 -07002373 deactivateConnectionLocked(connection.get());
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002374}
2375
Jeff Brownb6997262010-10-08 22:31:17 -07002376void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Jeff Browncc4f7db2011-08-30 20:34:48 -07002377 const sp<Connection>& connection, bool notify) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002378#if DEBUG_DISPATCH_CYCLE
Steve Block5baa3a62011-12-20 16:23:08 +00002379 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
Jeff Browncc4f7db2011-08-30 20:34:48 -07002380 connection->getInputChannelName(), toString(notify));
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002381#endif
2382
Jeff Brownb88102f2010-09-08 11:49:43 -07002383 // Clear the outbound queue.
Jeff Brown519e0242010-09-15 15:18:56 -07002384 drainOutboundQueueLocked(connection.get());
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002385
Jeff Brownb6997262010-10-08 22:31:17 -07002386 // The connection appears to be unrecoverably broken.
Jeff Brown9c3cda02010-06-15 01:31:58 -07002387 // Ignore already broken or zombie connections.
Jeff Brownb6997262010-10-08 22:31:17 -07002388 if (connection->status == Connection::STATUS_NORMAL) {
2389 connection->status = Connection::STATUS_BROKEN;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002390
Jeff Browncc4f7db2011-08-30 20:34:48 -07002391 if (notify) {
2392 // Notify other system components.
2393 onDispatchCycleBrokenLocked(currentTime, connection);
2394 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002395 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002396}
2397
Jeff Brown519e0242010-09-15 15:18:56 -07002398void InputDispatcher::drainOutboundQueueLocked(Connection* connection) {
2399 while (! connection->outboundQueue.isEmpty()) {
2400 DispatchEntry* dispatchEntry = connection->outboundQueue.dequeueAtHead();
2401 if (dispatchEntry->hasForegroundTarget()) {
2402 decrementPendingForegroundDispatchesLocked(dispatchEntry->eventEntry);
Jeff Brownb88102f2010-09-08 11:49:43 -07002403 }
Jeff Brownac386072011-07-20 15:19:50 -07002404 delete dispatchEntry;
Jeff Brownb88102f2010-09-08 11:49:43 -07002405 }
2406
Jeff Brown519e0242010-09-15 15:18:56 -07002407 deactivateConnectionLocked(connection);
Jeff Brownb88102f2010-09-08 11:49:43 -07002408}
2409
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002410int InputDispatcher::handleReceiveCallback(int receiveFd, int events, void* data) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002411 InputDispatcher* d = static_cast<InputDispatcher*>(data);
2412
2413 { // acquire lock
2414 AutoMutex _l(d->mLock);
2415
2416 ssize_t connectionIndex = d->mConnectionsByReceiveFd.indexOfKey(receiveFd);
2417 if (connectionIndex < 0) {
Steve Block3762c312012-01-06 19:20:56 +00002418 ALOGE("Received spurious receive callback for unknown input channel. "
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002419 "fd=%d, events=0x%x", receiveFd, events);
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002420 return 0; // remove the callback
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002421 }
2422
Jeff Browncc4f7db2011-08-30 20:34:48 -07002423 bool notify;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002424 sp<Connection> connection = d->mConnectionsByReceiveFd.valueAt(connectionIndex);
Jeff Browncc4f7db2011-08-30 20:34:48 -07002425 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
2426 if (!(events & ALOOPER_EVENT_INPUT)) {
Steve Block8564c8d2012-01-05 23:22:43 +00002427 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
Jeff Browncc4f7db2011-08-30 20:34:48 -07002428 "events=0x%x", connection->getInputChannelName(), events);
2429 return 1;
2430 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002431
Jeff Browncc4f7db2011-08-30 20:34:48 -07002432 bool handled = false;
2433 status_t status = connection->inputPublisher.receiveFinishedSignal(&handled);
2434 if (!status) {
2435 nsecs_t currentTime = now();
2436 d->finishDispatchCycleLocked(currentTime, connection, handled);
2437 d->runCommandsLockedInterruptible();
2438 return 1;
2439 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002440
Steve Block3762c312012-01-06 19:20:56 +00002441 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002442 connection->getInputChannelName(), status);
Jeff Browncc4f7db2011-08-30 20:34:48 -07002443 notify = true;
2444 } else {
2445 // Monitor channels are never explicitly unregistered.
2446 // We do it automatically when the remote endpoint is closed so don't warn
2447 // about them.
2448 notify = !connection->monitor;
2449 if (notify) {
Steve Block8564c8d2012-01-05 23:22:43 +00002450 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. "
Jeff Browncc4f7db2011-08-30 20:34:48 -07002451 "events=0x%x", connection->getInputChannelName(), events);
2452 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002453 }
2454
Jeff Browncc4f7db2011-08-30 20:34:48 -07002455 // Unregister the channel.
2456 d->unregisterInputChannelLocked(connection->inputChannel, notify);
2457 return 0; // remove the callback
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002458 } // release lock
2459}
2460
Jeff Brownb6997262010-10-08 22:31:17 -07002461void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Jeff Brownda3d5a92011-03-29 15:11:34 -07002462 const CancelationOptions& options) {
Jeff Brownb6997262010-10-08 22:31:17 -07002463 for (size_t i = 0; i < mConnectionsByReceiveFd.size(); i++) {
2464 synthesizeCancelationEventsForConnectionLocked(
Jeff Brownda3d5a92011-03-29 15:11:34 -07002465 mConnectionsByReceiveFd.valueAt(i), options);
Jeff Brownb6997262010-10-08 22:31:17 -07002466 }
2467}
2468
2469void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Jeff Brownda3d5a92011-03-29 15:11:34 -07002470 const sp<InputChannel>& channel, const CancelationOptions& options) {
Jeff Brownb6997262010-10-08 22:31:17 -07002471 ssize_t index = getConnectionIndexLocked(channel);
2472 if (index >= 0) {
2473 synthesizeCancelationEventsForConnectionLocked(
Jeff Brownda3d5a92011-03-29 15:11:34 -07002474 mConnectionsByReceiveFd.valueAt(index), options);
Jeff Brownb6997262010-10-08 22:31:17 -07002475 }
2476}
2477
2478void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
Jeff Brownda3d5a92011-03-29 15:11:34 -07002479 const sp<Connection>& connection, const CancelationOptions& options) {
Jeff Brownc0cb3dc2012-01-12 18:30:12 -08002480 if (connection->status == Connection::STATUS_BROKEN) {
2481 return;
2482 }
2483
Jeff Brownb6997262010-10-08 22:31:17 -07002484 nsecs_t currentTime = now();
2485
2486 mTempCancelationEvents.clear();
Jeff Brownac386072011-07-20 15:19:50 -07002487 connection->inputState.synthesizeCancelationEvents(currentTime,
Jeff Brownb6997262010-10-08 22:31:17 -07002488 mTempCancelationEvents, options);
2489
Jeff Brownc0cb3dc2012-01-12 18:30:12 -08002490 if (!mTempCancelationEvents.isEmpty()) {
Jeff Brownb6997262010-10-08 22:31:17 -07002491#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00002492 ALOGD("channel '%s' ~ Synthesized %d cancelation events to bring channel back in sync "
Jeff Brownda3d5a92011-03-29 15:11:34 -07002493 "with reality: %s, mode=%d.",
2494 connection->getInputChannelName(), mTempCancelationEvents.size(),
2495 options.reason, options.mode);
Jeff Brownb6997262010-10-08 22:31:17 -07002496#endif
2497 for (size_t i = 0; i < mTempCancelationEvents.size(); i++) {
2498 EventEntry* cancelationEventEntry = mTempCancelationEvents.itemAt(i);
2499 switch (cancelationEventEntry->type) {
2500 case EventEntry::TYPE_KEY:
2501 logOutboundKeyDetailsLocked("cancel - ",
2502 static_cast<KeyEntry*>(cancelationEventEntry));
2503 break;
2504 case EventEntry::TYPE_MOTION:
2505 logOutboundMotionDetailsLocked("cancel - ",
2506 static_cast<MotionEntry*>(cancelationEventEntry));
2507 break;
2508 }
2509
Jeff Brown81346812011-06-28 20:08:48 -07002510 InputTarget target;
Jeff Brown9302c872011-07-13 22:51:29 -07002511 sp<InputWindowHandle> windowHandle = getWindowHandleLocked(connection->inputChannel);
2512 if (windowHandle != NULL) {
Jeff Browncc4f7db2011-08-30 20:34:48 -07002513 const InputWindowInfo* windowInfo = windowHandle->getInfo();
2514 target.xOffset = -windowInfo->frameLeft;
2515 target.yOffset = -windowInfo->frameTop;
2516 target.scaleFactor = windowInfo->scaleFactor;
Jeff Brownb6997262010-10-08 22:31:17 -07002517 } else {
Jeff Brown81346812011-06-28 20:08:48 -07002518 target.xOffset = 0;
2519 target.yOffset = 0;
2520 target.scaleFactor = 1.0f;
Jeff Brownb6997262010-10-08 22:31:17 -07002521 }
Jeff Brown81346812011-06-28 20:08:48 -07002522 target.inputChannel = connection->inputChannel;
2523 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
Jeff Brownb6997262010-10-08 22:31:17 -07002524
Jeff Brown81346812011-06-28 20:08:48 -07002525 enqueueDispatchEntryLocked(connection, cancelationEventEntry, // increments ref
2526 &target, false, InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brownb6997262010-10-08 22:31:17 -07002527
Jeff Brownac386072011-07-20 15:19:50 -07002528 cancelationEventEntry->release();
Jeff Brownb6997262010-10-08 22:31:17 -07002529 }
2530
Jeff Brownac386072011-07-20 15:19:50 -07002531 if (!connection->outboundQueue.head->inProgress) {
Jeff Brownb6997262010-10-08 22:31:17 -07002532 startDispatchCycleLocked(currentTime, connection);
2533 }
2534 }
2535}
2536
Jeff Brown01ce2e92010-09-26 22:20:12 -07002537InputDispatcher::MotionEntry*
2538InputDispatcher::splitMotionEvent(const MotionEntry* originalMotionEntry, BitSet32 pointerIds) {
Steve Blockec193de2012-01-09 18:35:44 +00002539 ALOG_ASSERT(pointerIds.value != 0);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002540
2541 uint32_t splitPointerIndexMap[MAX_POINTERS];
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002542 PointerProperties splitPointerProperties[MAX_POINTERS];
Jeff Brown01ce2e92010-09-26 22:20:12 -07002543 PointerCoords splitPointerCoords[MAX_POINTERS];
2544
2545 uint32_t originalPointerCount = originalMotionEntry->pointerCount;
2546 uint32_t splitPointerCount = 0;
2547
2548 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
2549 originalPointerIndex++) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002550 const PointerProperties& pointerProperties =
2551 originalMotionEntry->pointerProperties[originalPointerIndex];
2552 uint32_t pointerId = uint32_t(pointerProperties.id);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002553 if (pointerIds.hasBit(pointerId)) {
2554 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002555 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
Jeff Brownace13b12011-03-09 17:39:48 -08002556 splitPointerCoords[splitPointerCount].copyFrom(
2557 originalMotionEntry->firstSample.pointerCoords[originalPointerIndex]);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002558 splitPointerCount += 1;
2559 }
2560 }
Jeff Brown58a2da82011-01-25 16:02:22 -08002561
2562 if (splitPointerCount != pointerIds.count()) {
2563 // This is bad. We are missing some of the pointers that we expected to deliver.
2564 // Most likely this indicates that we received an ACTION_MOVE events that has
2565 // different pointer ids than we expected based on the previous ACTION_DOWN
2566 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
2567 // in this way.
Steve Block8564c8d2012-01-05 23:22:43 +00002568 ALOGW("Dropping split motion event because the pointer count is %d but "
Jeff Brown58a2da82011-01-25 16:02:22 -08002569 "we expected there to be %d pointers. This probably means we received "
2570 "a broken sequence of pointer ids from the input device.",
2571 splitPointerCount, pointerIds.count());
2572 return NULL;
2573 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07002574
2575 int32_t action = originalMotionEntry->action;
2576 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
2577 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
2578 || maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2579 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002580 const PointerProperties& pointerProperties =
2581 originalMotionEntry->pointerProperties[originalPointerIndex];
2582 uint32_t pointerId = uint32_t(pointerProperties.id);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002583 if (pointerIds.hasBit(pointerId)) {
2584 if (pointerIds.count() == 1) {
2585 // The first/last pointer went down/up.
2586 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
2587 ? AMOTION_EVENT_ACTION_DOWN : AMOTION_EVENT_ACTION_UP;
Jeff Brown9a01d052010-09-27 16:35:11 -07002588 } else {
2589 // A secondary pointer went down/up.
2590 uint32_t splitPointerIndex = 0;
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002591 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
Jeff Brown9a01d052010-09-27 16:35:11 -07002592 splitPointerIndex += 1;
2593 }
2594 action = maskedAction | (splitPointerIndex
2595 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002596 }
2597 } else {
2598 // An unrelated pointer changed.
2599 action = AMOTION_EVENT_ACTION_MOVE;
2600 }
2601 }
2602
Jeff Brownac386072011-07-20 15:19:50 -07002603 MotionEntry* splitMotionEntry = new MotionEntry(
Jeff Brown01ce2e92010-09-26 22:20:12 -07002604 originalMotionEntry->eventTime,
2605 originalMotionEntry->deviceId,
2606 originalMotionEntry->source,
2607 originalMotionEntry->policyFlags,
2608 action,
2609 originalMotionEntry->flags,
2610 originalMotionEntry->metaState,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002611 originalMotionEntry->buttonState,
Jeff Brown01ce2e92010-09-26 22:20:12 -07002612 originalMotionEntry->edgeFlags,
2613 originalMotionEntry->xPrecision,
2614 originalMotionEntry->yPrecision,
2615 originalMotionEntry->downTime,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002616 splitPointerCount, splitPointerProperties, splitPointerCoords);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002617
2618 for (MotionSample* originalMotionSample = originalMotionEntry->firstSample.next;
2619 originalMotionSample != NULL; originalMotionSample = originalMotionSample->next) {
2620 for (uint32_t splitPointerIndex = 0; splitPointerIndex < splitPointerCount;
2621 splitPointerIndex++) {
2622 uint32_t originalPointerIndex = splitPointerIndexMap[splitPointerIndex];
Jeff Brownace13b12011-03-09 17:39:48 -08002623 splitPointerCoords[splitPointerIndex].copyFrom(
2624 originalMotionSample->pointerCoords[originalPointerIndex]);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002625 }
2626
Jeff Brownac386072011-07-20 15:19:50 -07002627 splitMotionEntry->appendSample(originalMotionSample->eventTime, splitPointerCoords);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002628 }
2629
Jeff Browna032cc02011-03-07 16:56:21 -08002630 if (originalMotionEntry->injectionState) {
2631 splitMotionEntry->injectionState = originalMotionEntry->injectionState;
2632 splitMotionEntry->injectionState->refCount += 1;
2633 }
2634
Jeff Brown01ce2e92010-09-26 22:20:12 -07002635 return splitMotionEntry;
2636}
2637
Jeff Brownbe1aa822011-07-27 16:04:54 -07002638void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002639#if DEBUG_INBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00002640 ALOGD("notifyConfigurationChanged - eventTime=%lld", args->eventTime);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002641#endif
2642
Jeff Brownb88102f2010-09-08 11:49:43 -07002643 bool needWake;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002644 { // acquire lock
2645 AutoMutex _l(mLock);
2646
Jeff Brownbe1aa822011-07-27 16:04:54 -07002647 ConfigurationChangedEntry* newEntry = new ConfigurationChangedEntry(args->eventTime);
Jeff Brownb88102f2010-09-08 11:49:43 -07002648 needWake = enqueueInboundEventLocked(newEntry);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002649 } // release lock
2650
Jeff Brownb88102f2010-09-08 11:49:43 -07002651 if (needWake) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002652 mLooper->wake();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002653 }
2654}
2655
Jeff Brownbe1aa822011-07-27 16:04:54 -07002656void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002657#if DEBUG_INBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00002658 ALOGD("notifyKey - eventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, action=0x%x, "
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002659 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%lld",
Jeff Brownbe1aa822011-07-27 16:04:54 -07002660 args->eventTime, args->deviceId, args->source, args->policyFlags,
2661 args->action, args->flags, args->keyCode, args->scanCode,
2662 args->metaState, args->downTime);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002663#endif
Jeff Brownbe1aa822011-07-27 16:04:54 -07002664 if (!validateKeyEvent(args->action)) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002665 return;
2666 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002667
Jeff Brownbe1aa822011-07-27 16:04:54 -07002668 uint32_t policyFlags = args->policyFlags;
2669 int32_t flags = args->flags;
2670 int32_t metaState = args->metaState;
Jeff Brown1f245102010-11-18 20:53:46 -08002671 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
2672 policyFlags |= POLICY_FLAG_VIRTUAL;
2673 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
2674 }
Jeff Brown924c4d42011-03-07 16:40:47 -08002675 if (policyFlags & POLICY_FLAG_ALT) {
2676 metaState |= AMETA_ALT_ON | AMETA_ALT_LEFT_ON;
2677 }
2678 if (policyFlags & POLICY_FLAG_ALT_GR) {
2679 metaState |= AMETA_ALT_ON | AMETA_ALT_RIGHT_ON;
2680 }
2681 if (policyFlags & POLICY_FLAG_SHIFT) {
2682 metaState |= AMETA_SHIFT_ON | AMETA_SHIFT_LEFT_ON;
2683 }
2684 if (policyFlags & POLICY_FLAG_CAPS_LOCK) {
2685 metaState |= AMETA_CAPS_LOCK_ON;
2686 }
2687 if (policyFlags & POLICY_FLAG_FUNCTION) {
2688 metaState |= AMETA_FUNCTION_ON;
2689 }
Jeff Brown1f245102010-11-18 20:53:46 -08002690
Jeff Browne20c9e02010-10-11 14:20:19 -07002691 policyFlags |= POLICY_FLAG_TRUSTED;
Jeff Brown1f245102010-11-18 20:53:46 -08002692
2693 KeyEvent event;
Jeff Brownbe1aa822011-07-27 16:04:54 -07002694 event.initialize(args->deviceId, args->source, args->action,
2695 flags, args->keyCode, args->scanCode, metaState, 0,
2696 args->downTime, args->eventTime);
Jeff Brown1f245102010-11-18 20:53:46 -08002697
2698 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
2699
2700 if (policyFlags & POLICY_FLAG_WOKE_HERE) {
2701 flags |= AKEY_EVENT_FLAG_WOKE_HERE;
2702 }
Jeff Brownb6997262010-10-08 22:31:17 -07002703
Jeff Brownb88102f2010-09-08 11:49:43 -07002704 bool needWake;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002705 { // acquire lock
Jeff Brown0029c662011-03-30 02:25:18 -07002706 mLock.lock();
2707
2708 if (mInputFilterEnabled) {
2709 mLock.unlock();
2710
2711 policyFlags |= POLICY_FLAG_FILTERED;
2712 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2713 return; // event was consumed by the filter
2714 }
2715
2716 mLock.lock();
2717 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002718
Jeff Brown7fbdc842010-06-17 20:52:56 -07002719 int32_t repeatCount = 0;
Jeff Brownbe1aa822011-07-27 16:04:54 -07002720 KeyEntry* newEntry = new KeyEntry(args->eventTime,
2721 args->deviceId, args->source, policyFlags,
2722 args->action, flags, args->keyCode, args->scanCode,
2723 metaState, repeatCount, args->downTime);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002724
Jeff Brownb88102f2010-09-08 11:49:43 -07002725 needWake = enqueueInboundEventLocked(newEntry);
Jeff Brown0029c662011-03-30 02:25:18 -07002726 mLock.unlock();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002727 } // release lock
2728
Jeff Brownb88102f2010-09-08 11:49:43 -07002729 if (needWake) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002730 mLooper->wake();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002731 }
2732}
2733
Jeff Brownbe1aa822011-07-27 16:04:54 -07002734void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002735#if DEBUG_INBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00002736 ALOGD("notifyMotion - eventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, "
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002737 "action=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, edgeFlags=0x%x, "
Jeff Brown85a31762010-09-01 17:01:00 -07002738 "xPrecision=%f, yPrecision=%f, downTime=%lld",
Jeff Brownbe1aa822011-07-27 16:04:54 -07002739 args->eventTime, args->deviceId, args->source, args->policyFlags,
2740 args->action, args->flags, args->metaState, args->buttonState,
2741 args->edgeFlags, args->xPrecision, args->yPrecision, args->downTime);
2742 for (uint32_t i = 0; i < args->pointerCount; i++) {
Steve Block5baa3a62011-12-20 16:23:08 +00002743 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002744 "x=%f, y=%f, pressure=%f, size=%f, "
Jeff Brown85a31762010-09-01 17:01:00 -07002745 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
Jeff Brown8d608662010-08-30 03:02:23 -07002746 "orientation=%f",
Jeff Brownbe1aa822011-07-27 16:04:54 -07002747 i, args->pointerProperties[i].id,
2748 args->pointerProperties[i].toolType,
2749 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
2750 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
2751 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
2752 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
2753 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
2754 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
2755 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
2756 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
2757 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002758 }
2759#endif
Jeff Brownbe1aa822011-07-27 16:04:54 -07002760 if (!validateMotionEvent(args->action, args->pointerCount, args->pointerProperties)) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002761 return;
2762 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002763
Jeff Brownbe1aa822011-07-27 16:04:54 -07002764 uint32_t policyFlags = args->policyFlags;
Jeff Browne20c9e02010-10-11 14:20:19 -07002765 policyFlags |= POLICY_FLAG_TRUSTED;
Jeff Brownbe1aa822011-07-27 16:04:54 -07002766 mPolicy->interceptMotionBeforeQueueing(args->eventTime, /*byref*/ policyFlags);
Jeff Brownb6997262010-10-08 22:31:17 -07002767
Jeff Brownb88102f2010-09-08 11:49:43 -07002768 bool needWake;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002769 { // acquire lock
Jeff Brown0029c662011-03-30 02:25:18 -07002770 mLock.lock();
2771
2772 if (mInputFilterEnabled) {
2773 mLock.unlock();
2774
2775 MotionEvent event;
Jeff Brownbe1aa822011-07-27 16:04:54 -07002776 event.initialize(args->deviceId, args->source, args->action, args->flags,
2777 args->edgeFlags, args->metaState, args->buttonState, 0, 0,
2778 args->xPrecision, args->yPrecision,
2779 args->downTime, args->eventTime,
2780 args->pointerCount, args->pointerProperties, args->pointerCoords);
Jeff Brown0029c662011-03-30 02:25:18 -07002781
2782 policyFlags |= POLICY_FLAG_FILTERED;
2783 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2784 return; // event was consumed by the filter
2785 }
2786
2787 mLock.lock();
2788 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002789
2790 // Attempt batching and streaming of move events.
Jeff Brownbe1aa822011-07-27 16:04:54 -07002791 if (args->action == AMOTION_EVENT_ACTION_MOVE
2792 || args->action == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002793 // BATCHING CASE
2794 //
2795 // Try to append a move sample to the tail of the inbound queue for this device.
2796 // Give up if we encounter a non-move motion event for this device since that
2797 // means we cannot append any new samples until a new motion event has started.
Jeff Brownac386072011-07-20 15:19:50 -07002798 for (EventEntry* entry = mInboundQueue.tail; entry; entry = entry->prev) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002799 if (entry->type != EventEntry::TYPE_MOTION) {
2800 // Keep looking for motion events.
2801 continue;
2802 }
2803
2804 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
Jeff Brownbe1aa822011-07-27 16:04:54 -07002805 if (motionEntry->deviceId != args->deviceId
2806 || motionEntry->source != args->source) {
Jeff Brownefd32662011-03-08 15:13:06 -08002807 // Keep looking for this device and source.
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002808 continue;
2809 }
2810
Jeff Brownbe1aa822011-07-27 16:04:54 -07002811 if (!motionEntry->canAppendSamples(args->action,
2812 args->pointerCount, args->pointerProperties)) {
Jeff Brownefd32662011-03-08 15:13:06 -08002813 // Last motion event in the queue for this device and source is
2814 // not compatible for appending new samples. Stop here.
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002815 goto NoBatchingOrStreaming;
2816 }
2817
Jeff Brown9c3cda02010-06-15 01:31:58 -07002818 // Do the batching magic.
Jeff Brownbe1aa822011-07-27 16:04:54 -07002819 batchMotionLocked(motionEntry, args->eventTime,
2820 args->metaState, args->pointerCoords,
Jeff Brown4e91a182011-04-07 11:38:09 -07002821 "most recent motion event for this device and source in the inbound queue");
Jeff Brown0029c662011-03-30 02:25:18 -07002822 mLock.unlock();
Jeff Brown9c3cda02010-06-15 01:31:58 -07002823 return; // done!
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002824 }
2825
Jeff Brownf6989da2011-04-06 17:19:48 -07002826 // BATCHING ONTO PENDING EVENT CASE
2827 //
2828 // Try to append a move sample to the currently pending event, if there is one.
2829 // We can do this as long as we are still waiting to find the targets for the
2830 // event. Once the targets are locked-in we can only do streaming.
2831 if (mPendingEvent
2832 && (!mPendingEvent->dispatchInProgress || !mCurrentInputTargetsValid)
2833 && mPendingEvent->type == EventEntry::TYPE_MOTION) {
2834 MotionEntry* motionEntry = static_cast<MotionEntry*>(mPendingEvent);
Jeff Brownbe1aa822011-07-27 16:04:54 -07002835 if (motionEntry->deviceId == args->deviceId
2836 && motionEntry->source == args->source) {
2837 if (!motionEntry->canAppendSamples(args->action,
2838 args->pointerCount, args->pointerProperties)) {
Jeff Brown4e91a182011-04-07 11:38:09 -07002839 // Pending motion event is for this device and source but it is
2840 // not compatible for appending new samples. Stop here.
Jeff Brownf6989da2011-04-06 17:19:48 -07002841 goto NoBatchingOrStreaming;
2842 }
2843
Jeff Brownf6989da2011-04-06 17:19:48 -07002844 // Do the batching magic.
Jeff Brownbe1aa822011-07-27 16:04:54 -07002845 batchMotionLocked(motionEntry, args->eventTime,
2846 args->metaState, args->pointerCoords,
Jeff Brown4e91a182011-04-07 11:38:09 -07002847 "pending motion event");
Jeff Brownf6989da2011-04-06 17:19:48 -07002848 mLock.unlock();
2849 return; // done!
2850 }
2851 }
2852
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002853 // STREAMING CASE
2854 //
2855 // There is no pending motion event (of any kind) for this device in the inbound queue.
Jeff Brown519e0242010-09-15 15:18:56 -07002856 // Search the outbound queue for the current foreground targets to find a dispatched
2857 // motion event that is still in progress. If found, then, appen the new sample to
2858 // that event and push it out to all current targets. The logic in
2859 // prepareDispatchCycleLocked takes care of the case where some targets may
2860 // already have consumed the motion event by starting a new dispatch cycle if needed.
Jeff Brown9c3cda02010-06-15 01:31:58 -07002861 if (mCurrentInputTargetsValid) {
Jeff Brown519e0242010-09-15 15:18:56 -07002862 for (size_t i = 0; i < mCurrentInputTargets.size(); i++) {
2863 const InputTarget& inputTarget = mCurrentInputTargets[i];
2864 if ((inputTarget.flags & InputTarget::FLAG_FOREGROUND) == 0) {
2865 // Skip non-foreground targets. We only want to stream if there is at
2866 // least one foreground target whose dispatch is still in progress.
2867 continue;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002868 }
Jeff Brown519e0242010-09-15 15:18:56 -07002869
2870 ssize_t connectionIndex = getConnectionIndexLocked(inputTarget.inputChannel);
2871 if (connectionIndex < 0) {
2872 // Connection must no longer be valid.
2873 continue;
2874 }
2875
2876 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
2877 if (connection->outboundQueue.isEmpty()) {
2878 // This foreground target has an empty outbound queue.
2879 continue;
2880 }
2881
Jeff Brownac386072011-07-20 15:19:50 -07002882 DispatchEntry* dispatchEntry = connection->outboundQueue.head;
Jeff Brown519e0242010-09-15 15:18:56 -07002883 if (! dispatchEntry->inProgress
Jeff Brown01ce2e92010-09-26 22:20:12 -07002884 || dispatchEntry->eventEntry->type != EventEntry::TYPE_MOTION
2885 || dispatchEntry->isSplit()) {
2886 // No motion event is being dispatched, or it is being split across
2887 // windows in which case we cannot stream.
Jeff Brown519e0242010-09-15 15:18:56 -07002888 continue;
2889 }
2890
2891 MotionEntry* motionEntry = static_cast<MotionEntry*>(
2892 dispatchEntry->eventEntry);
Jeff Brownbe1aa822011-07-27 16:04:54 -07002893 if (motionEntry->action != args->action
2894 || motionEntry->deviceId != args->deviceId
2895 || motionEntry->source != args->source
2896 || motionEntry->pointerCount != args->pointerCount
Jeff Brown519e0242010-09-15 15:18:56 -07002897 || motionEntry->isInjected()) {
2898 // The motion event is not compatible with this move.
2899 continue;
2900 }
2901
Jeff Brownbe1aa822011-07-27 16:04:54 -07002902 if (args->action == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Jeff Brown9302c872011-07-13 22:51:29 -07002903 if (mLastHoverWindowHandle == NULL) {
Jeff Browna032cc02011-03-07 16:56:21 -08002904#if DEBUG_BATCHING
Steve Block5baa3a62011-12-20 16:23:08 +00002905 ALOGD("Not streaming hover move because there is no "
Jeff Browna032cc02011-03-07 16:56:21 -08002906 "last hovered window.");
2907#endif
2908 goto NoBatchingOrStreaming;
2909 }
2910
Jeff Brown9302c872011-07-13 22:51:29 -07002911 sp<InputWindowHandle> hoverWindowHandle = findTouchedWindowAtLocked(
Jeff Brownbe1aa822011-07-27 16:04:54 -07002912 args->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X),
2913 args->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Jeff Brown9302c872011-07-13 22:51:29 -07002914 if (mLastHoverWindowHandle != hoverWindowHandle) {
Jeff Browna032cc02011-03-07 16:56:21 -08002915#if DEBUG_BATCHING
Steve Block5baa3a62011-12-20 16:23:08 +00002916 ALOGD("Not streaming hover move because the last hovered window "
Jeff Browna032cc02011-03-07 16:56:21 -08002917 "is '%s' but the currently hovered window is '%s'.",
Jeff Browncc4f7db2011-08-30 20:34:48 -07002918 mLastHoverWindowHandle->getName().string(),
Jeff Brown9302c872011-07-13 22:51:29 -07002919 hoverWindowHandle != NULL
Jeff Browncc4f7db2011-08-30 20:34:48 -07002920 ? hoverWindowHandle->getName().string() : "<null>");
Jeff Browna032cc02011-03-07 16:56:21 -08002921#endif
2922 goto NoBatchingOrStreaming;
2923 }
2924 }
2925
Jeff Brown519e0242010-09-15 15:18:56 -07002926 // Hurray! This foreground target is currently dispatching a move event
2927 // that we can stream onto. Append the motion sample and resume dispatch.
Jeff Brownbe1aa822011-07-27 16:04:54 -07002928 motionEntry->appendSample(args->eventTime, args->pointerCoords);
Jeff Brown519e0242010-09-15 15:18:56 -07002929#if DEBUG_BATCHING
Steve Block5baa3a62011-12-20 16:23:08 +00002930 ALOGD("Appended motion sample onto batch for most recently dispatched "
Jeff Brown4e91a182011-04-07 11:38:09 -07002931 "motion event for this device and source in the outbound queues. "
Jeff Brown519e0242010-09-15 15:18:56 -07002932 "Attempting to stream the motion sample.");
2933#endif
2934 nsecs_t currentTime = now();
2935 dispatchEventToCurrentInputTargetsLocked(currentTime, motionEntry,
2936 true /*resumeWithAppendedMotionSample*/);
2937
2938 runCommandsLockedInterruptible();
Jeff Brown0029c662011-03-30 02:25:18 -07002939 mLock.unlock();
Jeff Brown519e0242010-09-15 15:18:56 -07002940 return; // done!
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002941 }
2942 }
2943
2944NoBatchingOrStreaming:;
2945 }
2946
2947 // Just enqueue a new motion event.
Jeff Brownbe1aa822011-07-27 16:04:54 -07002948 MotionEntry* newEntry = new MotionEntry(args->eventTime,
2949 args->deviceId, args->source, policyFlags,
2950 args->action, args->flags, args->metaState, args->buttonState,
2951 args->edgeFlags, args->xPrecision, args->yPrecision, args->downTime,
2952 args->pointerCount, args->pointerProperties, args->pointerCoords);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002953
Jeff Brownb88102f2010-09-08 11:49:43 -07002954 needWake = enqueueInboundEventLocked(newEntry);
Jeff Brown0029c662011-03-30 02:25:18 -07002955 mLock.unlock();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002956 } // release lock
2957
Jeff Brownb88102f2010-09-08 11:49:43 -07002958 if (needWake) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002959 mLooper->wake();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002960 }
2961}
2962
Jeff Brown4e91a182011-04-07 11:38:09 -07002963void InputDispatcher::batchMotionLocked(MotionEntry* entry, nsecs_t eventTime,
2964 int32_t metaState, const PointerCoords* pointerCoords, const char* eventDescription) {
2965 // Combine meta states.
2966 entry->metaState |= metaState;
2967
2968 // Coalesce this sample if not enough time has elapsed since the last sample was
2969 // initially appended to the batch.
2970 MotionSample* lastSample = entry->lastSample;
2971 long interval = eventTime - lastSample->eventTimeBeforeCoalescing;
2972 if (interval <= MOTION_SAMPLE_COALESCE_INTERVAL) {
2973 uint32_t pointerCount = entry->pointerCount;
2974 for (uint32_t i = 0; i < pointerCount; i++) {
2975 lastSample->pointerCoords[i].copyFrom(pointerCoords[i]);
2976 }
2977 lastSample->eventTime = eventTime;
2978#if DEBUG_BATCHING
Steve Block5baa3a62011-12-20 16:23:08 +00002979 ALOGD("Coalesced motion into last sample of batch for %s, events were %0.3f ms apart",
Jeff Brown4e91a182011-04-07 11:38:09 -07002980 eventDescription, interval * 0.000001f);
2981#endif
2982 return;
2983 }
2984
2985 // Append the sample.
Jeff Brownac386072011-07-20 15:19:50 -07002986 entry->appendSample(eventTime, pointerCoords);
Jeff Brown4e91a182011-04-07 11:38:09 -07002987#if DEBUG_BATCHING
Steve Block5baa3a62011-12-20 16:23:08 +00002988 ALOGD("Appended motion sample onto batch for %s, events were %0.3f ms apart",
Jeff Brown4e91a182011-04-07 11:38:09 -07002989 eventDescription, interval * 0.000001f);
2990#endif
2991}
2992
Jeff Brownbe1aa822011-07-27 16:04:54 -07002993void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
Jeff Brownb6997262010-10-08 22:31:17 -07002994#if DEBUG_INBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00002995 ALOGD("notifySwitch - eventTime=%lld, policyFlags=0x%x, switchCode=%d, switchValue=%d",
Jeff Brownbe1aa822011-07-27 16:04:54 -07002996 args->eventTime, args->policyFlags,
2997 args->switchCode, args->switchValue);
Jeff Brownb6997262010-10-08 22:31:17 -07002998#endif
2999
Jeff Brownbe1aa822011-07-27 16:04:54 -07003000 uint32_t policyFlags = args->policyFlags;
Jeff Browne20c9e02010-10-11 14:20:19 -07003001 policyFlags |= POLICY_FLAG_TRUSTED;
Jeff Brownbe1aa822011-07-27 16:04:54 -07003002 mPolicy->notifySwitch(args->eventTime,
3003 args->switchCode, args->switchValue, policyFlags);
Jeff Brownb6997262010-10-08 22:31:17 -07003004}
3005
Jeff Brown65fd2512011-08-18 11:20:58 -07003006void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
3007#if DEBUG_INBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00003008 ALOGD("notifyDeviceReset - eventTime=%lld, deviceId=%d",
Jeff Brown65fd2512011-08-18 11:20:58 -07003009 args->eventTime, args->deviceId);
3010#endif
3011
3012 bool needWake;
3013 { // acquire lock
3014 AutoMutex _l(mLock);
3015
3016 DeviceResetEntry* newEntry = new DeviceResetEntry(args->eventTime, args->deviceId);
3017 needWake = enqueueInboundEventLocked(newEntry);
3018 } // release lock
3019
3020 if (needWake) {
3021 mLooper->wake();
3022 }
3023}
3024
Jeff Brown7fbdc842010-06-17 20:52:56 -07003025int32_t InputDispatcher::injectInputEvent(const InputEvent* event,
Jeff Brown0029c662011-03-30 02:25:18 -07003026 int32_t injectorPid, int32_t injectorUid, int32_t syncMode, int32_t timeoutMillis,
3027 uint32_t policyFlags) {
Jeff Brown7fbdc842010-06-17 20:52:56 -07003028#if DEBUG_INBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00003029 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Jeff Brown0029c662011-03-30 02:25:18 -07003030 "syncMode=%d, timeoutMillis=%d, policyFlags=0x%08x",
3031 event->getType(), injectorPid, injectorUid, syncMode, timeoutMillis, policyFlags);
Jeff Brown7fbdc842010-06-17 20:52:56 -07003032#endif
3033
3034 nsecs_t endTime = now() + milliseconds_to_nanoseconds(timeoutMillis);
Jeff Browne20c9e02010-10-11 14:20:19 -07003035
Jeff Brown0029c662011-03-30 02:25:18 -07003036 policyFlags |= POLICY_FLAG_INJECTED;
Jeff Browne20c9e02010-10-11 14:20:19 -07003037 if (hasInjectionPermission(injectorPid, injectorUid)) {
3038 policyFlags |= POLICY_FLAG_TRUSTED;
3039 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07003040
Jeff Brownb6997262010-10-08 22:31:17 -07003041 EventEntry* injectedEntry;
3042 switch (event->getType()) {
3043 case AINPUT_EVENT_TYPE_KEY: {
3044 const KeyEvent* keyEvent = static_cast<const KeyEvent*>(event);
3045 int32_t action = keyEvent->getAction();
3046 if (! validateKeyEvent(action)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07003047 return INPUT_EVENT_INJECTION_FAILED;
3048 }
3049
Jeff Brownb6997262010-10-08 22:31:17 -07003050 int32_t flags = keyEvent->getFlags();
Jeff Brown1f245102010-11-18 20:53:46 -08003051 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
3052 policyFlags |= POLICY_FLAG_VIRTUAL;
3053 }
3054
Jeff Brown0029c662011-03-30 02:25:18 -07003055 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3056 mPolicy->interceptKeyBeforeQueueing(keyEvent, /*byref*/ policyFlags);
3057 }
Jeff Brown1f245102010-11-18 20:53:46 -08003058
3059 if (policyFlags & POLICY_FLAG_WOKE_HERE) {
3060 flags |= AKEY_EVENT_FLAG_WOKE_HERE;
3061 }
Jeff Brown6ec402b2010-07-28 15:48:59 -07003062
Jeff Brownb6997262010-10-08 22:31:17 -07003063 mLock.lock();
Jeff Brownac386072011-07-20 15:19:50 -07003064 injectedEntry = new KeyEntry(keyEvent->getEventTime(),
Jeff Brown1f245102010-11-18 20:53:46 -08003065 keyEvent->getDeviceId(), keyEvent->getSource(),
3066 policyFlags, action, flags,
3067 keyEvent->getKeyCode(), keyEvent->getScanCode(), keyEvent->getMetaState(),
Jeff Brownb6997262010-10-08 22:31:17 -07003068 keyEvent->getRepeatCount(), keyEvent->getDownTime());
3069 break;
3070 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07003071
Jeff Brownb6997262010-10-08 22:31:17 -07003072 case AINPUT_EVENT_TYPE_MOTION: {
3073 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
3074 int32_t action = motionEvent->getAction();
3075 size_t pointerCount = motionEvent->getPointerCount();
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003076 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
3077 if (! validateMotionEvent(action, pointerCount, pointerProperties)) {
Jeff Brownb6997262010-10-08 22:31:17 -07003078 return INPUT_EVENT_INJECTION_FAILED;
3079 }
3080
Jeff Brown0029c662011-03-30 02:25:18 -07003081 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3082 nsecs_t eventTime = motionEvent->getEventTime();
3083 mPolicy->interceptMotionBeforeQueueing(eventTime, /*byref*/ policyFlags);
3084 }
Jeff Brownb6997262010-10-08 22:31:17 -07003085
3086 mLock.lock();
3087 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
3088 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
Jeff Brownac386072011-07-20 15:19:50 -07003089 MotionEntry* motionEntry = new MotionEntry(*sampleEventTimes,
Jeff Brownb6997262010-10-08 22:31:17 -07003090 motionEvent->getDeviceId(), motionEvent->getSource(), policyFlags,
3091 action, motionEvent->getFlags(),
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003092 motionEvent->getMetaState(), motionEvent->getButtonState(),
3093 motionEvent->getEdgeFlags(),
Jeff Brownb6997262010-10-08 22:31:17 -07003094 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
3095 motionEvent->getDownTime(), uint32_t(pointerCount),
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003096 pointerProperties, samplePointerCoords);
Jeff Brownb6997262010-10-08 22:31:17 -07003097 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
3098 sampleEventTimes += 1;
3099 samplePointerCoords += pointerCount;
Jeff Brownac386072011-07-20 15:19:50 -07003100 motionEntry->appendSample(*sampleEventTimes, samplePointerCoords);
Jeff Brownb6997262010-10-08 22:31:17 -07003101 }
3102 injectedEntry = motionEntry;
3103 break;
3104 }
3105
3106 default:
Steve Block8564c8d2012-01-05 23:22:43 +00003107 ALOGW("Cannot inject event of type %d", event->getType());
Jeff Brownb6997262010-10-08 22:31:17 -07003108 return INPUT_EVENT_INJECTION_FAILED;
3109 }
3110
Jeff Brownac386072011-07-20 15:19:50 -07003111 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
Jeff Brownb6997262010-10-08 22:31:17 -07003112 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
3113 injectionState->injectionIsAsync = true;
3114 }
3115
3116 injectionState->refCount += 1;
3117 injectedEntry->injectionState = injectionState;
3118
3119 bool needWake = enqueueInboundEventLocked(injectedEntry);
3120 mLock.unlock();
Jeff Brown7fbdc842010-06-17 20:52:56 -07003121
Jeff Brownb88102f2010-09-08 11:49:43 -07003122 if (needWake) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07003123 mLooper->wake();
Jeff Brown7fbdc842010-06-17 20:52:56 -07003124 }
3125
3126 int32_t injectionResult;
3127 { // acquire lock
3128 AutoMutex _l(mLock);
3129
Jeff Brown6ec402b2010-07-28 15:48:59 -07003130 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
3131 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
3132 } else {
3133 for (;;) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07003134 injectionResult = injectionState->injectionResult;
Jeff Brown6ec402b2010-07-28 15:48:59 -07003135 if (injectionResult != INPUT_EVENT_INJECTION_PENDING) {
3136 break;
3137 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07003138
Jeff Brown7fbdc842010-06-17 20:52:56 -07003139 nsecs_t remainingTimeout = endTime - now();
3140 if (remainingTimeout <= 0) {
Jeff Brown6ec402b2010-07-28 15:48:59 -07003141#if DEBUG_INJECTION
Steve Block5baa3a62011-12-20 16:23:08 +00003142 ALOGD("injectInputEvent - Timed out waiting for injection result "
Jeff Brown6ec402b2010-07-28 15:48:59 -07003143 "to become available.");
3144#endif
Jeff Brown7fbdc842010-06-17 20:52:56 -07003145 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
3146 break;
3147 }
3148
Jeff Brown6ec402b2010-07-28 15:48:59 -07003149 mInjectionResultAvailableCondition.waitRelative(mLock, remainingTimeout);
3150 }
3151
3152 if (injectionResult == INPUT_EVENT_INJECTION_SUCCEEDED
3153 && syncMode == INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07003154 while (injectionState->pendingForegroundDispatches != 0) {
Jeff Brown6ec402b2010-07-28 15:48:59 -07003155#if DEBUG_INJECTION
Steve Block5baa3a62011-12-20 16:23:08 +00003156 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
Jeff Brown01ce2e92010-09-26 22:20:12 -07003157 injectionState->pendingForegroundDispatches);
Jeff Brown6ec402b2010-07-28 15:48:59 -07003158#endif
3159 nsecs_t remainingTimeout = endTime - now();
3160 if (remainingTimeout <= 0) {
3161#if DEBUG_INJECTION
Steve Block5baa3a62011-12-20 16:23:08 +00003162 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
Jeff Brown6ec402b2010-07-28 15:48:59 -07003163 "dispatches to finish.");
3164#endif
3165 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
3166 break;
3167 }
3168
3169 mInjectionSyncFinishedCondition.waitRelative(mLock, remainingTimeout);
3170 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07003171 }
3172 }
3173
Jeff Brownac386072011-07-20 15:19:50 -07003174 injectionState->release();
Jeff Brown7fbdc842010-06-17 20:52:56 -07003175 } // release lock
3176
Jeff Brown6ec402b2010-07-28 15:48:59 -07003177#if DEBUG_INJECTION
Steve Block5baa3a62011-12-20 16:23:08 +00003178 ALOGD("injectInputEvent - Finished with result %d. "
Jeff Brown6ec402b2010-07-28 15:48:59 -07003179 "injectorPid=%d, injectorUid=%d",
3180 injectionResult, injectorPid, injectorUid);
3181#endif
3182
Jeff Brown7fbdc842010-06-17 20:52:56 -07003183 return injectionResult;
3184}
3185
Jeff Brownb6997262010-10-08 22:31:17 -07003186bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
3187 return injectorUid == 0
3188 || mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
3189}
3190
Jeff Brown7fbdc842010-06-17 20:52:56 -07003191void InputDispatcher::setInjectionResultLocked(EventEntry* entry, int32_t injectionResult) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07003192 InjectionState* injectionState = entry->injectionState;
3193 if (injectionState) {
Jeff Brown7fbdc842010-06-17 20:52:56 -07003194#if DEBUG_INJECTION
Steve Block5baa3a62011-12-20 16:23:08 +00003195 ALOGD("Setting input event injection result to %d. "
Jeff Brown7fbdc842010-06-17 20:52:56 -07003196 "injectorPid=%d, injectorUid=%d",
Jeff Brown01ce2e92010-09-26 22:20:12 -07003197 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
Jeff Brown7fbdc842010-06-17 20:52:56 -07003198#endif
3199
Jeff Brown0029c662011-03-30 02:25:18 -07003200 if (injectionState->injectionIsAsync
3201 && !(entry->policyFlags & POLICY_FLAG_FILTERED)) {
Jeff Brown6ec402b2010-07-28 15:48:59 -07003202 // Log the outcome since the injector did not wait for the injection result.
3203 switch (injectionResult) {
3204 case INPUT_EVENT_INJECTION_SUCCEEDED:
Steve Block71f2cf12011-10-20 11:56:00 +01003205 ALOGV("Asynchronous input event injection succeeded.");
Jeff Brown6ec402b2010-07-28 15:48:59 -07003206 break;
3207 case INPUT_EVENT_INJECTION_FAILED:
Steve Block8564c8d2012-01-05 23:22:43 +00003208 ALOGW("Asynchronous input event injection failed.");
Jeff Brown6ec402b2010-07-28 15:48:59 -07003209 break;
3210 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
Steve Block8564c8d2012-01-05 23:22:43 +00003211 ALOGW("Asynchronous input event injection permission denied.");
Jeff Brown6ec402b2010-07-28 15:48:59 -07003212 break;
3213 case INPUT_EVENT_INJECTION_TIMED_OUT:
Steve Block8564c8d2012-01-05 23:22:43 +00003214 ALOGW("Asynchronous input event injection timed out.");
Jeff Brown6ec402b2010-07-28 15:48:59 -07003215 break;
3216 }
3217 }
3218
Jeff Brown01ce2e92010-09-26 22:20:12 -07003219 injectionState->injectionResult = injectionResult;
Jeff Brown7fbdc842010-06-17 20:52:56 -07003220 mInjectionResultAvailableCondition.broadcast();
3221 }
3222}
3223
Jeff Brown01ce2e92010-09-26 22:20:12 -07003224void InputDispatcher::incrementPendingForegroundDispatchesLocked(EventEntry* entry) {
3225 InjectionState* injectionState = entry->injectionState;
3226 if (injectionState) {
3227 injectionState->pendingForegroundDispatches += 1;
3228 }
3229}
3230
Jeff Brown519e0242010-09-15 15:18:56 -07003231void InputDispatcher::decrementPendingForegroundDispatchesLocked(EventEntry* entry) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07003232 InjectionState* injectionState = entry->injectionState;
3233 if (injectionState) {
3234 injectionState->pendingForegroundDispatches -= 1;
Jeff Brown6ec402b2010-07-28 15:48:59 -07003235
Jeff Brown01ce2e92010-09-26 22:20:12 -07003236 if (injectionState->pendingForegroundDispatches == 0) {
3237 mInjectionSyncFinishedCondition.broadcast();
3238 }
Jeff Brownb88102f2010-09-08 11:49:43 -07003239 }
3240}
3241
Jeff Brown9302c872011-07-13 22:51:29 -07003242sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
3243 const sp<InputChannel>& inputChannel) const {
3244 size_t numWindows = mWindowHandles.size();
3245 for (size_t i = 0; i < numWindows; i++) {
3246 const sp<InputWindowHandle>& windowHandle = mWindowHandles.itemAt(i);
Jeff Browncc4f7db2011-08-30 20:34:48 -07003247 if (windowHandle->getInputChannel() == inputChannel) {
Jeff Brown9302c872011-07-13 22:51:29 -07003248 return windowHandle;
Jeff Brown01ce2e92010-09-26 22:20:12 -07003249 }
3250 }
3251 return NULL;
3252}
3253
Jeff Brown9302c872011-07-13 22:51:29 -07003254bool InputDispatcher::hasWindowHandleLocked(
3255 const sp<InputWindowHandle>& windowHandle) const {
3256 size_t numWindows = mWindowHandles.size();
3257 for (size_t i = 0; i < numWindows; i++) {
3258 if (mWindowHandles.itemAt(i) == windowHandle) {
3259 return true;
3260 }
3261 }
3262 return false;
3263}
3264
3265void InputDispatcher::setInputWindows(const Vector<sp<InputWindowHandle> >& inputWindowHandles) {
Jeff Brownb88102f2010-09-08 11:49:43 -07003266#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00003267 ALOGD("setInputWindows");
Jeff Brownb88102f2010-09-08 11:49:43 -07003268#endif
3269 { // acquire lock
3270 AutoMutex _l(mLock);
3271
Jeff Browncc4f7db2011-08-30 20:34:48 -07003272 Vector<sp<InputWindowHandle> > oldWindowHandles = mWindowHandles;
Jeff Brown9302c872011-07-13 22:51:29 -07003273 mWindowHandles = inputWindowHandles;
Jeff Brownb6997262010-10-08 22:31:17 -07003274
Jeff Brown9302c872011-07-13 22:51:29 -07003275 sp<InputWindowHandle> newFocusedWindowHandle;
3276 bool foundHoveredWindow = false;
3277 for (size_t i = 0; i < mWindowHandles.size(); i++) {
3278 const sp<InputWindowHandle>& windowHandle = mWindowHandles.itemAt(i);
Jeff Browncc4f7db2011-08-30 20:34:48 -07003279 if (!windowHandle->updateInfo() || windowHandle->getInputChannel() == NULL) {
Jeff Brown9302c872011-07-13 22:51:29 -07003280 mWindowHandles.removeAt(i--);
3281 continue;
3282 }
Jeff Browncc4f7db2011-08-30 20:34:48 -07003283 if (windowHandle->getInfo()->hasFocus) {
Jeff Brown9302c872011-07-13 22:51:29 -07003284 newFocusedWindowHandle = windowHandle;
3285 }
3286 if (windowHandle == mLastHoverWindowHandle) {
3287 foundHoveredWindow = true;
Jeff Brownb88102f2010-09-08 11:49:43 -07003288 }
3289 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07003290
Jeff Brown9302c872011-07-13 22:51:29 -07003291 if (!foundHoveredWindow) {
3292 mLastHoverWindowHandle = NULL;
3293 }
3294
3295 if (mFocusedWindowHandle != newFocusedWindowHandle) {
3296 if (mFocusedWindowHandle != NULL) {
Jeff Brownb6997262010-10-08 22:31:17 -07003297#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00003298 ALOGD("Focus left window: %s",
Jeff Browncc4f7db2011-08-30 20:34:48 -07003299 mFocusedWindowHandle->getName().string());
Jeff Brownb6997262010-10-08 22:31:17 -07003300#endif
Jeff Browncc4f7db2011-08-30 20:34:48 -07003301 sp<InputChannel> focusedInputChannel = mFocusedWindowHandle->getInputChannel();
3302 if (focusedInputChannel != NULL) {
Christopher Tated9be36c2011-08-16 16:09:33 -07003303 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
3304 "focus left window");
3305 synthesizeCancelationEventsForInputChannelLocked(
Jeff Browncc4f7db2011-08-30 20:34:48 -07003306 focusedInputChannel, options);
Christopher Tated9be36c2011-08-16 16:09:33 -07003307 }
Jeff Brownb6997262010-10-08 22:31:17 -07003308 }
Jeff Brown9302c872011-07-13 22:51:29 -07003309 if (newFocusedWindowHandle != NULL) {
Jeff Brownb6997262010-10-08 22:31:17 -07003310#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00003311 ALOGD("Focus entered window: %s",
Jeff Browncc4f7db2011-08-30 20:34:48 -07003312 newFocusedWindowHandle->getName().string());
Jeff Brownb6997262010-10-08 22:31:17 -07003313#endif
Jeff Brown9302c872011-07-13 22:51:29 -07003314 }
3315 mFocusedWindowHandle = newFocusedWindowHandle;
Jeff Brownb6997262010-10-08 22:31:17 -07003316 }
3317
Jeff Brown9302c872011-07-13 22:51:29 -07003318 for (size_t i = 0; i < mTouchState.windows.size(); i++) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07003319 TouchedWindow& touchedWindow = mTouchState.windows.editItemAt(i);
Jeff Brown9302c872011-07-13 22:51:29 -07003320 if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
Jeff Brownb6997262010-10-08 22:31:17 -07003321#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00003322 ALOGD("Touched window was removed: %s",
Jeff Browncc4f7db2011-08-30 20:34:48 -07003323 touchedWindow.windowHandle->getName().string());
Jeff Brownb6997262010-10-08 22:31:17 -07003324#endif
Jeff Browncc4f7db2011-08-30 20:34:48 -07003325 sp<InputChannel> touchedInputChannel =
3326 touchedWindow.windowHandle->getInputChannel();
3327 if (touchedInputChannel != NULL) {
Christopher Tated9be36c2011-08-16 16:09:33 -07003328 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
3329 "touched window was removed");
3330 synthesizeCancelationEventsForInputChannelLocked(
Jeff Browncc4f7db2011-08-30 20:34:48 -07003331 touchedInputChannel, options);
Christopher Tated9be36c2011-08-16 16:09:33 -07003332 }
Jeff Brown9302c872011-07-13 22:51:29 -07003333 mTouchState.windows.removeAt(i--);
Jeff Brown01ce2e92010-09-26 22:20:12 -07003334 }
3335 }
Jeff Browncc4f7db2011-08-30 20:34:48 -07003336
3337 // Release information for windows that are no longer present.
3338 // This ensures that unused input channels are released promptly.
3339 // Otherwise, they might stick around until the window handle is destroyed
3340 // which might not happen until the next GC.
3341 for (size_t i = 0; i < oldWindowHandles.size(); i++) {
3342 const sp<InputWindowHandle>& oldWindowHandle = oldWindowHandles.itemAt(i);
3343 if (!hasWindowHandleLocked(oldWindowHandle)) {
3344#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00003345 ALOGD("Window went away: %s", oldWindowHandle->getName().string());
Jeff Browncc4f7db2011-08-30 20:34:48 -07003346#endif
3347 oldWindowHandle->releaseInfo();
3348 }
3349 }
Jeff Brownb88102f2010-09-08 11:49:43 -07003350 } // release lock
3351
3352 // Wake up poll loop since it may need to make new input dispatching choices.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07003353 mLooper->wake();
Jeff Brownb88102f2010-09-08 11:49:43 -07003354}
3355
Jeff Brown9302c872011-07-13 22:51:29 -07003356void InputDispatcher::setFocusedApplication(
3357 const sp<InputApplicationHandle>& inputApplicationHandle) {
Jeff Brownb88102f2010-09-08 11:49:43 -07003358#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00003359 ALOGD("setFocusedApplication");
Jeff Brownb88102f2010-09-08 11:49:43 -07003360#endif
3361 { // acquire lock
3362 AutoMutex _l(mLock);
3363
Jeff Browncc4f7db2011-08-30 20:34:48 -07003364 if (inputApplicationHandle != NULL && inputApplicationHandle->updateInfo()) {
Jeff Brown5ea29ab2011-07-27 11:50:51 -07003365 if (mFocusedApplicationHandle != inputApplicationHandle) {
3366 if (mFocusedApplicationHandle != NULL) {
3367 resetTargetsLocked();
Jeff Browncc4f7db2011-08-30 20:34:48 -07003368 mFocusedApplicationHandle->releaseInfo();
Jeff Brown5ea29ab2011-07-27 11:50:51 -07003369 }
3370 mFocusedApplicationHandle = inputApplicationHandle;
3371 }
3372 } else if (mFocusedApplicationHandle != NULL) {
3373 resetTargetsLocked();
Jeff Browncc4f7db2011-08-30 20:34:48 -07003374 mFocusedApplicationHandle->releaseInfo();
Jeff Brown9302c872011-07-13 22:51:29 -07003375 mFocusedApplicationHandle.clear();
Jeff Brownb88102f2010-09-08 11:49:43 -07003376 }
3377
3378#if DEBUG_FOCUS
Jeff Brownb6997262010-10-08 22:31:17 -07003379 //logDispatchStateLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -07003380#endif
3381 } // release lock
3382
3383 // Wake up poll loop since it may need to make new input dispatching choices.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07003384 mLooper->wake();
Jeff Brownb88102f2010-09-08 11:49:43 -07003385}
3386
Jeff Brownb88102f2010-09-08 11:49:43 -07003387void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
3388#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00003389 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
Jeff Brownb88102f2010-09-08 11:49:43 -07003390#endif
3391
3392 bool changed;
3393 { // acquire lock
3394 AutoMutex _l(mLock);
3395
3396 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
Jeff Brown120a4592010-10-27 18:43:51 -07003397 if (mDispatchFrozen && !frozen) {
Jeff Brownb88102f2010-09-08 11:49:43 -07003398 resetANRTimeoutsLocked();
3399 }
3400
Jeff Brown120a4592010-10-27 18:43:51 -07003401 if (mDispatchEnabled && !enabled) {
3402 resetAndDropEverythingLocked("dispatcher is being disabled");
3403 }
3404
Jeff Brownb88102f2010-09-08 11:49:43 -07003405 mDispatchEnabled = enabled;
3406 mDispatchFrozen = frozen;
3407 changed = true;
3408 } else {
3409 changed = false;
3410 }
3411
3412#if DEBUG_FOCUS
Jeff Brownb6997262010-10-08 22:31:17 -07003413 //logDispatchStateLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -07003414#endif
3415 } // release lock
3416
3417 if (changed) {
3418 // Wake up poll loop since it may need to make new input dispatching choices.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07003419 mLooper->wake();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003420 }
3421}
3422
Jeff Brown0029c662011-03-30 02:25:18 -07003423void InputDispatcher::setInputFilterEnabled(bool enabled) {
3424#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00003425 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
Jeff Brown0029c662011-03-30 02:25:18 -07003426#endif
3427
3428 { // acquire lock
3429 AutoMutex _l(mLock);
3430
3431 if (mInputFilterEnabled == enabled) {
3432 return;
3433 }
3434
3435 mInputFilterEnabled = enabled;
3436 resetAndDropEverythingLocked("input filter is being enabled or disabled");
3437 } // release lock
3438
3439 // Wake up poll loop since there might be work to do to drop everything.
3440 mLooper->wake();
3441}
3442
Jeff Browne6504122010-09-27 14:52:15 -07003443bool InputDispatcher::transferTouchFocus(const sp<InputChannel>& fromChannel,
3444 const sp<InputChannel>& toChannel) {
3445#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00003446 ALOGD("transferTouchFocus: fromChannel=%s, toChannel=%s",
Jeff Browne6504122010-09-27 14:52:15 -07003447 fromChannel->getName().string(), toChannel->getName().string());
3448#endif
3449 { // acquire lock
3450 AutoMutex _l(mLock);
3451
Jeff Brown9302c872011-07-13 22:51:29 -07003452 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromChannel);
3453 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toChannel);
3454 if (fromWindowHandle == NULL || toWindowHandle == NULL) {
Jeff Browne6504122010-09-27 14:52:15 -07003455#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00003456 ALOGD("Cannot transfer focus because from or to window not found.");
Jeff Browne6504122010-09-27 14:52:15 -07003457#endif
3458 return false;
3459 }
Jeff Brown9302c872011-07-13 22:51:29 -07003460 if (fromWindowHandle == toWindowHandle) {
Jeff Browne6504122010-09-27 14:52:15 -07003461#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00003462 ALOGD("Trivial transfer to same window.");
Jeff Browne6504122010-09-27 14:52:15 -07003463#endif
3464 return true;
3465 }
3466
3467 bool found = false;
3468 for (size_t i = 0; i < mTouchState.windows.size(); i++) {
3469 const TouchedWindow& touchedWindow = mTouchState.windows[i];
Jeff Brown9302c872011-07-13 22:51:29 -07003470 if (touchedWindow.windowHandle == fromWindowHandle) {
Jeff Browne6504122010-09-27 14:52:15 -07003471 int32_t oldTargetFlags = touchedWindow.targetFlags;
3472 BitSet32 pointerIds = touchedWindow.pointerIds;
3473
3474 mTouchState.windows.removeAt(i);
3475
Jeff Brown46e75292010-11-10 16:53:45 -08003476 int32_t newTargetFlags = oldTargetFlags
Jeff Browna032cc02011-03-07 16:56:21 -08003477 & (InputTarget::FLAG_FOREGROUND
3478 | InputTarget::FLAG_SPLIT | InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brown9302c872011-07-13 22:51:29 -07003479 mTouchState.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Jeff Browne6504122010-09-27 14:52:15 -07003480
3481 found = true;
3482 break;
3483 }
3484 }
3485
3486 if (! found) {
3487#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00003488 ALOGD("Focus transfer failed because from window did not have focus.");
Jeff Browne6504122010-09-27 14:52:15 -07003489#endif
3490 return false;
3491 }
3492
Jeff Brown9c9f1a32010-10-11 18:32:20 -07003493 ssize_t fromConnectionIndex = getConnectionIndexLocked(fromChannel);
3494 ssize_t toConnectionIndex = getConnectionIndexLocked(toChannel);
3495 if (fromConnectionIndex >= 0 && toConnectionIndex >= 0) {
3496 sp<Connection> fromConnection = mConnectionsByReceiveFd.valueAt(fromConnectionIndex);
3497 sp<Connection> toConnection = mConnectionsByReceiveFd.valueAt(toConnectionIndex);
3498
3499 fromConnection->inputState.copyPointerStateTo(toConnection->inputState);
Jeff Brownda3d5a92011-03-29 15:11:34 -07003500 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Jeff Brown9c9f1a32010-10-11 18:32:20 -07003501 "transferring touch focus from this window to another window");
Jeff Brownda3d5a92011-03-29 15:11:34 -07003502 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Jeff Brown9c9f1a32010-10-11 18:32:20 -07003503 }
3504
Jeff Browne6504122010-09-27 14:52:15 -07003505#if DEBUG_FOCUS
3506 logDispatchStateLocked();
3507#endif
3508 } // release lock
3509
3510 // Wake up poll loop since it may need to make new input dispatching choices.
3511 mLooper->wake();
3512 return true;
3513}
3514
Jeff Brown120a4592010-10-27 18:43:51 -07003515void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
3516#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00003517 ALOGD("Resetting and dropping all events (%s).", reason);
Jeff Brown120a4592010-10-27 18:43:51 -07003518#endif
3519
Jeff Brownda3d5a92011-03-29 15:11:34 -07003520 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
3521 synthesizeCancelationEventsForAllConnectionsLocked(options);
Jeff Brown120a4592010-10-27 18:43:51 -07003522
3523 resetKeyRepeatLocked();
3524 releasePendingEventLocked();
3525 drainInboundQueueLocked();
3526 resetTargetsLocked();
3527
3528 mTouchState.reset();
Jeff Brown9302c872011-07-13 22:51:29 -07003529 mLastHoverWindowHandle.clear();
Jeff Brown120a4592010-10-27 18:43:51 -07003530}
3531
Jeff Brownb88102f2010-09-08 11:49:43 -07003532void InputDispatcher::logDispatchStateLocked() {
3533 String8 dump;
3534 dumpDispatchStateLocked(dump);
Jeff Brown2a95c2a2010-09-16 12:31:46 -07003535
3536 char* text = dump.lockBuffer(dump.size());
3537 char* start = text;
3538 while (*start != '\0') {
3539 char* end = strchr(start, '\n');
3540 if (*end == '\n') {
3541 *(end++) = '\0';
3542 }
Steve Block5baa3a62011-12-20 16:23:08 +00003543 ALOGD("%s", start);
Jeff Brown2a95c2a2010-09-16 12:31:46 -07003544 start = end;
3545 }
Jeff Brownb88102f2010-09-08 11:49:43 -07003546}
3547
3548void InputDispatcher::dumpDispatchStateLocked(String8& dump) {
Jeff Brownf2f487182010-10-01 17:46:21 -07003549 dump.appendFormat(INDENT "DispatchEnabled: %d\n", mDispatchEnabled);
3550 dump.appendFormat(INDENT "DispatchFrozen: %d\n", mDispatchFrozen);
Jeff Brownb88102f2010-09-08 11:49:43 -07003551
Jeff Brown9302c872011-07-13 22:51:29 -07003552 if (mFocusedApplicationHandle != NULL) {
Jeff Brownf2f487182010-10-01 17:46:21 -07003553 dump.appendFormat(INDENT "FocusedApplication: name='%s', dispatchingTimeout=%0.3fms\n",
Jeff Browncc4f7db2011-08-30 20:34:48 -07003554 mFocusedApplicationHandle->getName().string(),
3555 mFocusedApplicationHandle->getDispatchingTimeout(
3556 DEFAULT_INPUT_DISPATCHING_TIMEOUT) / 1000000.0);
Jeff Brownb88102f2010-09-08 11:49:43 -07003557 } else {
Jeff Brownf2f487182010-10-01 17:46:21 -07003558 dump.append(INDENT "FocusedApplication: <null>\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003559 }
Jeff Brownf2f487182010-10-01 17:46:21 -07003560 dump.appendFormat(INDENT "FocusedWindow: name='%s'\n",
Jeff Browncc4f7db2011-08-30 20:34:48 -07003561 mFocusedWindowHandle != NULL ? mFocusedWindowHandle->getName().string() : "<null>");
Jeff Brownf2f487182010-10-01 17:46:21 -07003562
3563 dump.appendFormat(INDENT "TouchDown: %s\n", toString(mTouchState.down));
3564 dump.appendFormat(INDENT "TouchSplit: %s\n", toString(mTouchState.split));
Jeff Brown95712852011-01-04 19:41:59 -08003565 dump.appendFormat(INDENT "TouchDeviceId: %d\n", mTouchState.deviceId);
Jeff Brown58a2da82011-01-25 16:02:22 -08003566 dump.appendFormat(INDENT "TouchSource: 0x%08x\n", mTouchState.source);
Jeff Brownf2f487182010-10-01 17:46:21 -07003567 if (!mTouchState.windows.isEmpty()) {
3568 dump.append(INDENT "TouchedWindows:\n");
3569 for (size_t i = 0; i < mTouchState.windows.size(); i++) {
3570 const TouchedWindow& touchedWindow = mTouchState.windows[i];
3571 dump.appendFormat(INDENT2 "%d: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
Jeff Browncc4f7db2011-08-30 20:34:48 -07003572 i, touchedWindow.windowHandle->getName().string(),
3573 touchedWindow.pointerIds.value,
Jeff Brownf2f487182010-10-01 17:46:21 -07003574 touchedWindow.targetFlags);
3575 }
3576 } else {
3577 dump.append(INDENT "TouchedWindows: <none>\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003578 }
3579
Jeff Brown9302c872011-07-13 22:51:29 -07003580 if (!mWindowHandles.isEmpty()) {
Jeff Brownf2f487182010-10-01 17:46:21 -07003581 dump.append(INDENT "Windows:\n");
Jeff Brown9302c872011-07-13 22:51:29 -07003582 for (size_t i = 0; i < mWindowHandles.size(); i++) {
3583 const sp<InputWindowHandle>& windowHandle = mWindowHandles.itemAt(i);
Jeff Browncc4f7db2011-08-30 20:34:48 -07003584 const InputWindowInfo* windowInfo = windowHandle->getInfo();
3585
Jeff Brownf2f487182010-10-01 17:46:21 -07003586 dump.appendFormat(INDENT2 "%d: name='%s', paused=%s, hasFocus=%s, hasWallpaper=%s, "
3587 "visible=%s, canReceiveKeys=%s, flags=0x%08x, type=0x%08x, layer=%d, "
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003588 "frame=[%d,%d][%d,%d], scale=%f, "
Jeff Brownfbf09772011-01-16 14:06:57 -08003589 "touchableRegion=",
Jeff Browncc4f7db2011-08-30 20:34:48 -07003590 i, windowInfo->name.string(),
3591 toString(windowInfo->paused),
3592 toString(windowInfo->hasFocus),
3593 toString(windowInfo->hasWallpaper),
3594 toString(windowInfo->visible),
3595 toString(windowInfo->canReceiveKeys),
3596 windowInfo->layoutParamsFlags, windowInfo->layoutParamsType,
3597 windowInfo->layer,
3598 windowInfo->frameLeft, windowInfo->frameTop,
3599 windowInfo->frameRight, windowInfo->frameBottom,
3600 windowInfo->scaleFactor);
3601 dumpRegion(dump, windowInfo->touchableRegion);
3602 dump.appendFormat(", inputFeatures=0x%08x", windowInfo->inputFeatures);
Jeff Brownfbf09772011-01-16 14:06:57 -08003603 dump.appendFormat(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%0.3fms\n",
Jeff Browncc4f7db2011-08-30 20:34:48 -07003604 windowInfo->ownerPid, windowInfo->ownerUid,
3605 windowInfo->dispatchingTimeout / 1000000.0);
Jeff Brownf2f487182010-10-01 17:46:21 -07003606 }
3607 } else {
3608 dump.append(INDENT "Windows: <none>\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003609 }
3610
Jeff Brownf2f487182010-10-01 17:46:21 -07003611 if (!mMonitoringChannels.isEmpty()) {
3612 dump.append(INDENT "MonitoringChannels:\n");
3613 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
3614 const sp<InputChannel>& channel = mMonitoringChannels[i];
3615 dump.appendFormat(INDENT2 "%d: '%s'\n", i, channel->getName().string());
3616 }
3617 } else {
3618 dump.append(INDENT "MonitoringChannels: <none>\n");
3619 }
Jeff Brown519e0242010-09-15 15:18:56 -07003620
Jeff Brownf2f487182010-10-01 17:46:21 -07003621 dump.appendFormat(INDENT "InboundQueue: length=%u\n", mInboundQueue.count());
3622
3623 if (!mActiveConnections.isEmpty()) {
3624 dump.append(INDENT "ActiveConnections:\n");
3625 for (size_t i = 0; i < mActiveConnections.size(); i++) {
3626 const Connection* connection = mActiveConnections[i];
Jeff Brown76860e32010-10-25 17:37:46 -07003627 dump.appendFormat(INDENT2 "%d: '%s', status=%s, outboundQueueLength=%u, "
Jeff Brownb6997262010-10-08 22:31:17 -07003628 "inputState.isNeutral=%s\n",
Jeff Brownf2f487182010-10-01 17:46:21 -07003629 i, connection->getInputChannelName(), connection->getStatusLabel(),
3630 connection->outboundQueue.count(),
Jeff Brownb6997262010-10-08 22:31:17 -07003631 toString(connection->inputState.isNeutral()));
Jeff Brownf2f487182010-10-01 17:46:21 -07003632 }
3633 } else {
3634 dump.append(INDENT "ActiveConnections: <none>\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003635 }
3636
3637 if (isAppSwitchPendingLocked()) {
Jeff Brownf2f487182010-10-01 17:46:21 -07003638 dump.appendFormat(INDENT "AppSwitch: pending, due in %01.1fms\n",
Jeff Brownb88102f2010-09-08 11:49:43 -07003639 (mAppSwitchDueTime - now()) / 1000000.0);
3640 } else {
Jeff Brownf2f487182010-10-01 17:46:21 -07003641 dump.append(INDENT "AppSwitch: not pending\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003642 }
3643}
3644
Jeff Brown928e0542011-01-10 11:17:36 -08003645status_t InputDispatcher::registerInputChannel(const sp<InputChannel>& inputChannel,
3646 const sp<InputWindowHandle>& inputWindowHandle, bool monitor) {
Jeff Brown9c3cda02010-06-15 01:31:58 -07003647#if DEBUG_REGISTRATION
Steve Block5baa3a62011-12-20 16:23:08 +00003648 ALOGD("channel '%s' ~ registerInputChannel - monitor=%s", inputChannel->getName().string(),
Jeff Brownb88102f2010-09-08 11:49:43 -07003649 toString(monitor));
Jeff Brown9c3cda02010-06-15 01:31:58 -07003650#endif
3651
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003652 { // acquire lock
3653 AutoMutex _l(mLock);
3654
Jeff Brown519e0242010-09-15 15:18:56 -07003655 if (getConnectionIndexLocked(inputChannel) >= 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00003656 ALOGW("Attempted to register already registered input channel '%s'",
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003657 inputChannel->getName().string());
3658 return BAD_VALUE;
3659 }
3660
Jeff Browncc4f7db2011-08-30 20:34:48 -07003661 sp<Connection> connection = new Connection(inputChannel, inputWindowHandle, monitor);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003662 status_t status = connection->initialize();
3663 if (status) {
Steve Block3762c312012-01-06 19:20:56 +00003664 ALOGE("Failed to initialize input publisher for input channel '%s', status=%d",
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003665 inputChannel->getName().string(), status);
3666 return status;
3667 }
3668
Jeff Brown2cbecea2010-08-17 15:59:26 -07003669 int32_t receiveFd = inputChannel->getReceivePipeFd();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003670 mConnectionsByReceiveFd.add(receiveFd, connection);
Jeff Brown9c3cda02010-06-15 01:31:58 -07003671
Jeff Brownb88102f2010-09-08 11:49:43 -07003672 if (monitor) {
3673 mMonitoringChannels.push(inputChannel);
3674 }
3675
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07003676 mLooper->addFd(receiveFd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
Jeff Brown2cbecea2010-08-17 15:59:26 -07003677
Jeff Brown9c3cda02010-06-15 01:31:58 -07003678 runCommandsLockedInterruptible();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003679 } // release lock
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003680 return OK;
3681}
3682
3683status_t InputDispatcher::unregisterInputChannel(const sp<InputChannel>& inputChannel) {
Jeff Brown9c3cda02010-06-15 01:31:58 -07003684#if DEBUG_REGISTRATION
Steve Block5baa3a62011-12-20 16:23:08 +00003685 ALOGD("channel '%s' ~ unregisterInputChannel", inputChannel->getName().string());
Jeff Brown9c3cda02010-06-15 01:31:58 -07003686#endif
3687
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003688 { // acquire lock
3689 AutoMutex _l(mLock);
3690
Jeff Browncc4f7db2011-08-30 20:34:48 -07003691 status_t status = unregisterInputChannelLocked(inputChannel, false /*notify*/);
3692 if (status) {
3693 return status;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003694 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003695 } // release lock
3696
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003697 // Wake the poll loop because removing the connection may have changed the current
3698 // synchronization state.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07003699 mLooper->wake();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003700 return OK;
3701}
3702
Jeff Browncc4f7db2011-08-30 20:34:48 -07003703status_t InputDispatcher::unregisterInputChannelLocked(const sp<InputChannel>& inputChannel,
3704 bool notify) {
3705 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
3706 if (connectionIndex < 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00003707 ALOGW("Attempted to unregister already unregistered input channel '%s'",
Jeff Browncc4f7db2011-08-30 20:34:48 -07003708 inputChannel->getName().string());
3709 return BAD_VALUE;
3710 }
3711
3712 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
3713 mConnectionsByReceiveFd.removeItemsAt(connectionIndex);
3714
3715 if (connection->monitor) {
3716 removeMonitorChannelLocked(inputChannel);
3717 }
3718
3719 mLooper->removeFd(inputChannel->getReceivePipeFd());
3720
3721 nsecs_t currentTime = now();
3722 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
3723
3724 runCommandsLockedInterruptible();
3725
3726 connection->status = Connection::STATUS_ZOMBIE;
3727 return OK;
3728}
3729
3730void InputDispatcher::removeMonitorChannelLocked(const sp<InputChannel>& inputChannel) {
3731 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
3732 if (mMonitoringChannels[i] == inputChannel) {
3733 mMonitoringChannels.removeAt(i);
3734 break;
3735 }
3736 }
3737}
3738
Jeff Brown519e0242010-09-15 15:18:56 -07003739ssize_t InputDispatcher::getConnectionIndexLocked(const sp<InputChannel>& inputChannel) {
Jeff Brown2cbecea2010-08-17 15:59:26 -07003740 ssize_t connectionIndex = mConnectionsByReceiveFd.indexOfKey(inputChannel->getReceivePipeFd());
3741 if (connectionIndex >= 0) {
3742 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
3743 if (connection->inputChannel.get() == inputChannel.get()) {
3744 return connectionIndex;
3745 }
3746 }
3747
3748 return -1;
3749}
3750
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003751void InputDispatcher::activateConnectionLocked(Connection* connection) {
3752 for (size_t i = 0; i < mActiveConnections.size(); i++) {
3753 if (mActiveConnections.itemAt(i) == connection) {
3754 return;
3755 }
3756 }
3757 mActiveConnections.add(connection);
3758}
3759
3760void InputDispatcher::deactivateConnectionLocked(Connection* connection) {
3761 for (size_t i = 0; i < mActiveConnections.size(); i++) {
3762 if (mActiveConnections.itemAt(i) == connection) {
3763 mActiveConnections.removeAt(i);
3764 return;
3765 }
3766 }
3767}
3768
Jeff Brown9c3cda02010-06-15 01:31:58 -07003769void InputDispatcher::onDispatchCycleStartedLocked(
Jeff Brown7fbdc842010-06-17 20:52:56 -07003770 nsecs_t currentTime, const sp<Connection>& connection) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003771}
3772
Jeff Brown9c3cda02010-06-15 01:31:58 -07003773void InputDispatcher::onDispatchCycleFinishedLocked(
Jeff Brown3915bb82010-11-05 15:02:16 -07003774 nsecs_t currentTime, const sp<Connection>& connection, bool handled) {
3775 CommandEntry* commandEntry = postCommandLocked(
3776 & InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
3777 commandEntry->connection = connection;
3778 commandEntry->handled = handled;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003779}
3780
Jeff Brown9c3cda02010-06-15 01:31:58 -07003781void InputDispatcher::onDispatchCycleBrokenLocked(
Jeff Brown7fbdc842010-06-17 20:52:56 -07003782 nsecs_t currentTime, const sp<Connection>& connection) {
Steve Block3762c312012-01-06 19:20:56 +00003783 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003784 connection->getInputChannelName());
3785
Jeff Brown9c3cda02010-06-15 01:31:58 -07003786 CommandEntry* commandEntry = postCommandLocked(
3787 & InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
Jeff Brown7fbdc842010-06-17 20:52:56 -07003788 commandEntry->connection = connection;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003789}
3790
Jeff Brown519e0242010-09-15 15:18:56 -07003791void InputDispatcher::onANRLocked(
Jeff Brown9302c872011-07-13 22:51:29 -07003792 nsecs_t currentTime, const sp<InputApplicationHandle>& applicationHandle,
3793 const sp<InputWindowHandle>& windowHandle,
Jeff Brown519e0242010-09-15 15:18:56 -07003794 nsecs_t eventTime, nsecs_t waitStartTime) {
Steve Block6215d3f2012-01-04 20:05:49 +00003795 ALOGI("Application is not responding: %s. "
Jeff Brown519e0242010-09-15 15:18:56 -07003796 "%01.1fms since event, %01.1fms since wait started",
Jeff Brown9302c872011-07-13 22:51:29 -07003797 getApplicationWindowLabelLocked(applicationHandle, windowHandle).string(),
Jeff Brown519e0242010-09-15 15:18:56 -07003798 (currentTime - eventTime) / 1000000.0,
3799 (currentTime - waitStartTime) / 1000000.0);
3800
3801 CommandEntry* commandEntry = postCommandLocked(
3802 & InputDispatcher::doNotifyANRLockedInterruptible);
Jeff Brown9302c872011-07-13 22:51:29 -07003803 commandEntry->inputApplicationHandle = applicationHandle;
3804 commandEntry->inputWindowHandle = windowHandle;
Jeff Brown519e0242010-09-15 15:18:56 -07003805}
3806
Jeff Brownb88102f2010-09-08 11:49:43 -07003807void InputDispatcher::doNotifyConfigurationChangedInterruptible(
3808 CommandEntry* commandEntry) {
3809 mLock.unlock();
3810
3811 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
3812
3813 mLock.lock();
3814}
3815
Jeff Brown9c3cda02010-06-15 01:31:58 -07003816void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(
3817 CommandEntry* commandEntry) {
Jeff Brown7fbdc842010-06-17 20:52:56 -07003818 sp<Connection> connection = commandEntry->connection;
Jeff Brown9c3cda02010-06-15 01:31:58 -07003819
Jeff Brown7fbdc842010-06-17 20:52:56 -07003820 if (connection->status != Connection::STATUS_ZOMBIE) {
3821 mLock.unlock();
Jeff Brown9c3cda02010-06-15 01:31:58 -07003822
Jeff Brown928e0542011-01-10 11:17:36 -08003823 mPolicy->notifyInputChannelBroken(connection->inputWindowHandle);
Jeff Brown7fbdc842010-06-17 20:52:56 -07003824
3825 mLock.lock();
3826 }
Jeff Brown9c3cda02010-06-15 01:31:58 -07003827}
3828
Jeff Brown519e0242010-09-15 15:18:56 -07003829void InputDispatcher::doNotifyANRLockedInterruptible(
Jeff Brown9c3cda02010-06-15 01:31:58 -07003830 CommandEntry* commandEntry) {
Jeff Brown519e0242010-09-15 15:18:56 -07003831 mLock.unlock();
Jeff Brown9c3cda02010-06-15 01:31:58 -07003832
Jeff Brown519e0242010-09-15 15:18:56 -07003833 nsecs_t newTimeout = mPolicy->notifyANR(
Jeff Brown928e0542011-01-10 11:17:36 -08003834 commandEntry->inputApplicationHandle, commandEntry->inputWindowHandle);
Jeff Brown9c3cda02010-06-15 01:31:58 -07003835
Jeff Brown519e0242010-09-15 15:18:56 -07003836 mLock.lock();
Jeff Brown7fbdc842010-06-17 20:52:56 -07003837
Jeff Brown9302c872011-07-13 22:51:29 -07003838 resumeAfterTargetsNotReadyTimeoutLocked(newTimeout,
3839 commandEntry->inputWindowHandle != NULL
Jeff Browncc4f7db2011-08-30 20:34:48 -07003840 ? commandEntry->inputWindowHandle->getInputChannel() : NULL);
Jeff Brown9c3cda02010-06-15 01:31:58 -07003841}
3842
Jeff Brownb88102f2010-09-08 11:49:43 -07003843void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
3844 CommandEntry* commandEntry) {
3845 KeyEntry* entry = commandEntry->keyEntry;
Jeff Brown1f245102010-11-18 20:53:46 -08003846
3847 KeyEvent event;
3848 initializeKeyEvent(&event, entry);
Jeff Brownb88102f2010-09-08 11:49:43 -07003849
3850 mLock.unlock();
3851
Jeff Brown905805a2011-10-12 13:57:59 -07003852 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(commandEntry->inputWindowHandle,
Jeff Brown1f245102010-11-18 20:53:46 -08003853 &event, entry->policyFlags);
Jeff Brownb88102f2010-09-08 11:49:43 -07003854
3855 mLock.lock();
3856
Jeff Brown905805a2011-10-12 13:57:59 -07003857 if (delay < 0) {
3858 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
3859 } else if (!delay) {
3860 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
3861 } else {
3862 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
3863 entry->interceptKeyWakeupTime = now() + delay;
3864 }
Jeff Brownac386072011-07-20 15:19:50 -07003865 entry->release();
Jeff Brownb88102f2010-09-08 11:49:43 -07003866}
3867
Jeff Brown3915bb82010-11-05 15:02:16 -07003868void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(
3869 CommandEntry* commandEntry) {
3870 sp<Connection> connection = commandEntry->connection;
3871 bool handled = commandEntry->handled;
3872
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003873 bool skipNext = false;
Jeff Brown49ed71d2010-12-06 17:13:33 -08003874 if (!connection->outboundQueue.isEmpty()) {
Jeff Brownac386072011-07-20 15:19:50 -07003875 DispatchEntry* dispatchEntry = connection->outboundQueue.head;
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003876 if (dispatchEntry->inProgress) {
3877 if (dispatchEntry->eventEntry->type == EventEntry::TYPE_KEY) {
3878 KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry);
3879 skipNext = afterKeyEventLockedInterruptible(connection,
3880 dispatchEntry, keyEntry, handled);
3881 } else if (dispatchEntry->eventEntry->type == EventEntry::TYPE_MOTION) {
3882 MotionEntry* motionEntry = static_cast<MotionEntry*>(dispatchEntry->eventEntry);
3883 skipNext = afterMotionEventLockedInterruptible(connection,
3884 dispatchEntry, motionEntry, handled);
Jeff Brown49ed71d2010-12-06 17:13:33 -08003885 }
Jeff Brown3915bb82010-11-05 15:02:16 -07003886 }
3887 }
3888
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003889 if (!skipNext) {
3890 startNextDispatchCycleLocked(now(), connection);
3891 }
3892}
3893
3894bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
3895 DispatchEntry* dispatchEntry, KeyEntry* keyEntry, bool handled) {
3896 if (!(keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK)) {
3897 // Get the fallback key state.
3898 // Clear it out after dispatching the UP.
3899 int32_t originalKeyCode = keyEntry->keyCode;
3900 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
3901 if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
3902 connection->inputState.removeFallbackKey(originalKeyCode);
3903 }
3904
3905 if (handled || !dispatchEntry->hasForegroundTarget()) {
3906 // If the application handles the original key for which we previously
3907 // generated a fallback or if the window is not a foreground window,
3908 // then cancel the associated fallback key, if any.
3909 if (fallbackKeyCode != -1) {
3910 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
3911 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
3912 "application handled the original non-fallback key "
3913 "or is no longer a foreground target, "
3914 "canceling previously dispatched fallback key");
3915 options.keyCode = fallbackKeyCode;
3916 synthesizeCancelationEventsForConnectionLocked(connection, options);
3917 }
3918 connection->inputState.removeFallbackKey(originalKeyCode);
3919 }
3920 } else {
3921 // If the application did not handle a non-fallback key, first check
3922 // that we are in a good state to perform unhandled key event processing
3923 // Then ask the policy what to do with it.
3924 bool initialDown = keyEntry->action == AKEY_EVENT_ACTION_DOWN
3925 && keyEntry->repeatCount == 0;
3926 if (fallbackKeyCode == -1 && !initialDown) {
3927#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00003928 ALOGD("Unhandled key event: Skipping unhandled key event processing "
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003929 "since this is not an initial down. "
3930 "keyCode=%d, action=%d, repeatCount=%d",
3931 originalKeyCode, keyEntry->action, keyEntry->repeatCount);
3932#endif
3933 return false;
3934 }
3935
3936 // Dispatch the unhandled key to the policy.
3937#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00003938 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003939 "keyCode=%d, action=%d, repeatCount=%d",
3940 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount);
3941#endif
3942 KeyEvent event;
3943 initializeKeyEvent(&event, keyEntry);
3944
3945 mLock.unlock();
3946
3947 bool fallback = mPolicy->dispatchUnhandledKey(connection->inputWindowHandle,
3948 &event, keyEntry->policyFlags, &event);
3949
3950 mLock.lock();
3951
3952 if (connection->status != Connection::STATUS_NORMAL) {
3953 connection->inputState.removeFallbackKey(originalKeyCode);
3954 return true; // skip next cycle
3955 }
3956
Steve Blockec193de2012-01-09 18:35:44 +00003957 ALOG_ASSERT(connection->outboundQueue.head == dispatchEntry);
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003958
3959 // Latch the fallback keycode for this key on an initial down.
3960 // The fallback keycode cannot change at any other point in the lifecycle.
3961 if (initialDown) {
3962 if (fallback) {
3963 fallbackKeyCode = event.getKeyCode();
3964 } else {
3965 fallbackKeyCode = AKEYCODE_UNKNOWN;
3966 }
3967 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
3968 }
3969
Steve Blockec193de2012-01-09 18:35:44 +00003970 ALOG_ASSERT(fallbackKeyCode != -1);
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003971
3972 // Cancel the fallback key if the policy decides not to send it anymore.
3973 // We will continue to dispatch the key to the policy but we will no
3974 // longer dispatch a fallback key to the application.
3975 if (fallbackKeyCode != AKEYCODE_UNKNOWN
3976 && (!fallback || fallbackKeyCode != event.getKeyCode())) {
3977#if DEBUG_OUTBOUND_EVENT_DETAILS
3978 if (fallback) {
Steve Block5baa3a62011-12-20 16:23:08 +00003979 ALOGD("Unhandled key event: Policy requested to send key %d"
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003980 "as a fallback for %d, but on the DOWN it had requested "
3981 "to send %d instead. Fallback canceled.",
3982 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
3983 } else {
Steve Block5baa3a62011-12-20 16:23:08 +00003984 ALOGD("Unhandled key event: Policy did not request fallback for %d,"
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003985 "but on the DOWN it had requested to send %d. "
3986 "Fallback canceled.",
3987 originalKeyCode, fallbackKeyCode);
3988 }
3989#endif
3990
3991 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
3992 "canceling fallback, policy no longer desires it");
3993 options.keyCode = fallbackKeyCode;
3994 synthesizeCancelationEventsForConnectionLocked(connection, options);
3995
3996 fallback = false;
3997 fallbackKeyCode = AKEYCODE_UNKNOWN;
3998 if (keyEntry->action != AKEY_EVENT_ACTION_UP) {
3999 connection->inputState.setFallbackKey(originalKeyCode,
4000 fallbackKeyCode);
4001 }
4002 }
4003
4004#if DEBUG_OUTBOUND_EVENT_DETAILS
4005 {
4006 String8 msg;
4007 const KeyedVector<int32_t, int32_t>& fallbackKeys =
4008 connection->inputState.getFallbackKeys();
4009 for (size_t i = 0; i < fallbackKeys.size(); i++) {
4010 msg.appendFormat(", %d->%d", fallbackKeys.keyAt(i),
4011 fallbackKeys.valueAt(i));
4012 }
Steve Block5baa3a62011-12-20 16:23:08 +00004013 ALOGD("Unhandled key event: %d currently tracked fallback keys%s.",
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07004014 fallbackKeys.size(), msg.string());
4015 }
4016#endif
4017
4018 if (fallback) {
4019 // Restart the dispatch cycle using the fallback key.
4020 keyEntry->eventTime = event.getEventTime();
4021 keyEntry->deviceId = event.getDeviceId();
4022 keyEntry->source = event.getSource();
4023 keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
4024 keyEntry->keyCode = fallbackKeyCode;
4025 keyEntry->scanCode = event.getScanCode();
4026 keyEntry->metaState = event.getMetaState();
4027 keyEntry->repeatCount = event.getRepeatCount();
4028 keyEntry->downTime = event.getDownTime();
4029 keyEntry->syntheticRepeat = false;
4030
4031#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00004032 ALOGD("Unhandled key event: Dispatching fallback key. "
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07004033 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
4034 originalKeyCode, fallbackKeyCode, keyEntry->metaState);
4035#endif
4036
4037 dispatchEntry->inProgress = false;
4038 startDispatchCycleLocked(now(), connection);
4039 return true; // already started next cycle
4040 } else {
4041#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00004042 ALOGD("Unhandled key event: No fallback key.");
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07004043#endif
4044 }
4045 }
4046 }
4047 return false;
4048}
4049
4050bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
4051 DispatchEntry* dispatchEntry, MotionEntry* motionEntry, bool handled) {
4052 return false;
Jeff Brown3915bb82010-11-05 15:02:16 -07004053}
4054
Jeff Brownb88102f2010-09-08 11:49:43 -07004055void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
4056 mLock.unlock();
4057
Jeff Brown01ce2e92010-09-26 22:20:12 -07004058 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
Jeff Brownb88102f2010-09-08 11:49:43 -07004059
4060 mLock.lock();
4061}
4062
Jeff Brown3915bb82010-11-05 15:02:16 -07004063void InputDispatcher::initializeKeyEvent(KeyEvent* event, const KeyEntry* entry) {
4064 event->initialize(entry->deviceId, entry->source, entry->action, entry->flags,
4065 entry->keyCode, entry->scanCode, entry->metaState, entry->repeatCount,
4066 entry->downTime, entry->eventTime);
4067}
4068
Jeff Brown519e0242010-09-15 15:18:56 -07004069void InputDispatcher::updateDispatchStatisticsLocked(nsecs_t currentTime, const EventEntry* entry,
4070 int32_t injectionResult, nsecs_t timeSpentWaitingForApplication) {
4071 // TODO Write some statistics about how long we spend waiting.
Jeff Brownb88102f2010-09-08 11:49:43 -07004072}
4073
4074void InputDispatcher::dump(String8& dump) {
Jeff Brown89ef0722011-08-10 16:25:21 -07004075 AutoMutex _l(mLock);
4076
Jeff Brownf2f487182010-10-01 17:46:21 -07004077 dump.append("Input Dispatcher State:\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07004078 dumpDispatchStateLocked(dump);
Jeff Brown214eaf42011-05-26 19:17:02 -07004079
4080 dump.append(INDENT "Configuration:\n");
4081 dump.appendFormat(INDENT2 "MaxEventsPerSecond: %d\n", mConfig.maxEventsPerSecond);
4082 dump.appendFormat(INDENT2 "KeyRepeatDelay: %0.1fms\n", mConfig.keyRepeatDelay * 0.000001f);
4083 dump.appendFormat(INDENT2 "KeyRepeatTimeout: %0.1fms\n", mConfig.keyRepeatTimeout * 0.000001f);
Jeff Brownb88102f2010-09-08 11:49:43 -07004084}
4085
Jeff Brown89ef0722011-08-10 16:25:21 -07004086void InputDispatcher::monitor() {
4087 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
4088 mLock.lock();
4089 mLock.unlock();
4090}
4091
Jeff Brown9c3cda02010-06-15 01:31:58 -07004092
Jeff Brown519e0242010-09-15 15:18:56 -07004093// --- InputDispatcher::Queue ---
4094
4095template <typename T>
4096uint32_t InputDispatcher::Queue<T>::count() const {
4097 uint32_t result = 0;
Jeff Brownac386072011-07-20 15:19:50 -07004098 for (const T* entry = head; entry; entry = entry->next) {
Jeff Brown519e0242010-09-15 15:18:56 -07004099 result += 1;
4100 }
4101 return result;
4102}
4103
4104
Jeff Brownac386072011-07-20 15:19:50 -07004105// --- InputDispatcher::InjectionState ---
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004106
Jeff Brownac386072011-07-20 15:19:50 -07004107InputDispatcher::InjectionState::InjectionState(int32_t injectorPid, int32_t injectorUid) :
4108 refCount(1),
4109 injectorPid(injectorPid), injectorUid(injectorUid),
4110 injectionResult(INPUT_EVENT_INJECTION_PENDING), injectionIsAsync(false),
4111 pendingForegroundDispatches(0) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004112}
4113
Jeff Brownac386072011-07-20 15:19:50 -07004114InputDispatcher::InjectionState::~InjectionState() {
Jeff Brown01ce2e92010-09-26 22:20:12 -07004115}
4116
Jeff Brownac386072011-07-20 15:19:50 -07004117void InputDispatcher::InjectionState::release() {
4118 refCount -= 1;
4119 if (refCount == 0) {
4120 delete this;
4121 } else {
Steve Blockec193de2012-01-09 18:35:44 +00004122 ALOG_ASSERT(refCount > 0);
Jeff Brown01ce2e92010-09-26 22:20:12 -07004123 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07004124}
4125
Jeff Brownac386072011-07-20 15:19:50 -07004126
4127// --- InputDispatcher::EventEntry ---
4128
4129InputDispatcher::EventEntry::EventEntry(int32_t type, nsecs_t eventTime, uint32_t policyFlags) :
4130 refCount(1), type(type), eventTime(eventTime), policyFlags(policyFlags),
4131 injectionState(NULL), dispatchInProgress(false) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004132}
4133
Jeff Brownac386072011-07-20 15:19:50 -07004134InputDispatcher::EventEntry::~EventEntry() {
4135 releaseInjectionState();
4136}
4137
4138void InputDispatcher::EventEntry::release() {
4139 refCount -= 1;
4140 if (refCount == 0) {
4141 delete this;
4142 } else {
Steve Blockec193de2012-01-09 18:35:44 +00004143 ALOG_ASSERT(refCount > 0);
Jeff Brownac386072011-07-20 15:19:50 -07004144 }
4145}
4146
4147void InputDispatcher::EventEntry::releaseInjectionState() {
4148 if (injectionState) {
4149 injectionState->release();
4150 injectionState = NULL;
4151 }
4152}
4153
4154
4155// --- InputDispatcher::ConfigurationChangedEntry ---
4156
4157InputDispatcher::ConfigurationChangedEntry::ConfigurationChangedEntry(nsecs_t eventTime) :
4158 EventEntry(TYPE_CONFIGURATION_CHANGED, eventTime, 0) {
4159}
4160
4161InputDispatcher::ConfigurationChangedEntry::~ConfigurationChangedEntry() {
4162}
4163
4164
Jeff Brown65fd2512011-08-18 11:20:58 -07004165// --- InputDispatcher::DeviceResetEntry ---
4166
4167InputDispatcher::DeviceResetEntry::DeviceResetEntry(nsecs_t eventTime, int32_t deviceId) :
4168 EventEntry(TYPE_DEVICE_RESET, eventTime, 0),
4169 deviceId(deviceId) {
4170}
4171
4172InputDispatcher::DeviceResetEntry::~DeviceResetEntry() {
4173}
4174
4175
Jeff Brownac386072011-07-20 15:19:50 -07004176// --- InputDispatcher::KeyEntry ---
4177
4178InputDispatcher::KeyEntry::KeyEntry(nsecs_t eventTime,
Jeff Brown58a2da82011-01-25 16:02:22 -08004179 int32_t deviceId, uint32_t source, uint32_t policyFlags, int32_t action,
Jeff Brown7fbdc842010-06-17 20:52:56 -07004180 int32_t flags, int32_t keyCode, int32_t scanCode, int32_t metaState,
Jeff Brownac386072011-07-20 15:19:50 -07004181 int32_t repeatCount, nsecs_t downTime) :
4182 EventEntry(TYPE_KEY, eventTime, policyFlags),
4183 deviceId(deviceId), source(source), action(action), flags(flags),
4184 keyCode(keyCode), scanCode(scanCode), metaState(metaState),
4185 repeatCount(repeatCount), downTime(downTime),
Jeff Brown905805a2011-10-12 13:57:59 -07004186 syntheticRepeat(false), interceptKeyResult(KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN),
4187 interceptKeyWakeupTime(0) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004188}
4189
Jeff Brownac386072011-07-20 15:19:50 -07004190InputDispatcher::KeyEntry::~KeyEntry() {
4191}
Jeff Brown7fbdc842010-06-17 20:52:56 -07004192
Jeff Brownac386072011-07-20 15:19:50 -07004193void InputDispatcher::KeyEntry::recycle() {
4194 releaseInjectionState();
4195
4196 dispatchInProgress = false;
4197 syntheticRepeat = false;
4198 interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
Jeff Brown905805a2011-10-12 13:57:59 -07004199 interceptKeyWakeupTime = 0;
Jeff Brownac386072011-07-20 15:19:50 -07004200}
4201
4202
4203// --- InputDispatcher::MotionSample ---
4204
4205InputDispatcher::MotionSample::MotionSample(nsecs_t eventTime,
4206 const PointerCoords* pointerCoords, uint32_t pointerCount) :
4207 next(NULL), eventTime(eventTime), eventTimeBeforeCoalescing(eventTime) {
Jeff Brown7fbdc842010-06-17 20:52:56 -07004208 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brownac386072011-07-20 15:19:50 -07004209 this->pointerCoords[i].copyFrom(pointerCoords[i]);
Jeff Brown7fbdc842010-06-17 20:52:56 -07004210 }
Jeff Brownb88102f2010-09-08 11:49:43 -07004211}
4212
4213
Jeff Brownae9fc032010-08-18 15:51:08 -07004214// --- InputDispatcher::MotionEntry ---
4215
Jeff Brownac386072011-07-20 15:19:50 -07004216InputDispatcher::MotionEntry::MotionEntry(nsecs_t eventTime,
4217 int32_t deviceId, uint32_t source, uint32_t policyFlags, int32_t action, int32_t flags,
4218 int32_t metaState, int32_t buttonState,
4219 int32_t edgeFlags, float xPrecision, float yPrecision,
4220 nsecs_t downTime, uint32_t pointerCount,
4221 const PointerProperties* pointerProperties, const PointerCoords* pointerCoords) :
4222 EventEntry(TYPE_MOTION, eventTime, policyFlags),
4223 deviceId(deviceId), source(source), action(action), flags(flags),
4224 metaState(metaState), buttonState(buttonState), edgeFlags(edgeFlags),
4225 xPrecision(xPrecision), yPrecision(yPrecision),
4226 downTime(downTime), pointerCount(pointerCount),
4227 firstSample(eventTime, pointerCoords, pointerCount),
4228 lastSample(&firstSample) {
4229 for (uint32_t i = 0; i < pointerCount; i++) {
4230 this->pointerProperties[i].copyFrom(pointerProperties[i]);
4231 }
4232}
4233
4234InputDispatcher::MotionEntry::~MotionEntry() {
4235 for (MotionSample* sample = firstSample.next; sample != NULL; ) {
4236 MotionSample* next = sample->next;
4237 delete sample;
4238 sample = next;
4239 }
4240}
4241
Jeff Brownae9fc032010-08-18 15:51:08 -07004242uint32_t InputDispatcher::MotionEntry::countSamples() const {
4243 uint32_t count = 1;
4244 for (MotionSample* sample = firstSample.next; sample != NULL; sample = sample->next) {
4245 count += 1;
4246 }
4247 return count;
4248}
4249
Jeff Brown4e91a182011-04-07 11:38:09 -07004250bool InputDispatcher::MotionEntry::canAppendSamples(int32_t action, uint32_t pointerCount,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07004251 const PointerProperties* pointerProperties) const {
Jeff Brown4e91a182011-04-07 11:38:09 -07004252 if (this->action != action
4253 || this->pointerCount != pointerCount
4254 || this->isInjected()) {
4255 return false;
4256 }
4257 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07004258 if (this->pointerProperties[i] != pointerProperties[i]) {
Jeff Brown4e91a182011-04-07 11:38:09 -07004259 return false;
4260 }
4261 }
4262 return true;
4263}
4264
Jeff Brownac386072011-07-20 15:19:50 -07004265void InputDispatcher::MotionEntry::appendSample(
4266 nsecs_t eventTime, const PointerCoords* pointerCoords) {
4267 MotionSample* sample = new MotionSample(eventTime, pointerCoords, pointerCount);
4268
4269 lastSample->next = sample;
4270 lastSample = sample;
4271}
4272
4273
4274// --- InputDispatcher::DispatchEntry ---
4275
4276InputDispatcher::DispatchEntry::DispatchEntry(EventEntry* eventEntry,
4277 int32_t targetFlags, float xOffset, float yOffset, float scaleFactor) :
4278 eventEntry(eventEntry), targetFlags(targetFlags),
4279 xOffset(xOffset), yOffset(yOffset), scaleFactor(scaleFactor),
4280 inProgress(false),
4281 resolvedAction(0), resolvedFlags(0),
4282 headMotionSample(NULL), tailMotionSample(NULL) {
4283 eventEntry->refCount += 1;
4284}
4285
4286InputDispatcher::DispatchEntry::~DispatchEntry() {
4287 eventEntry->release();
4288}
4289
Jeff Brownb88102f2010-09-08 11:49:43 -07004290
4291// --- InputDispatcher::InputState ---
4292
Jeff Brownb6997262010-10-08 22:31:17 -07004293InputDispatcher::InputState::InputState() {
Jeff Brownb88102f2010-09-08 11:49:43 -07004294}
4295
4296InputDispatcher::InputState::~InputState() {
4297}
4298
4299bool InputDispatcher::InputState::isNeutral() const {
4300 return mKeyMementos.isEmpty() && mMotionMementos.isEmpty();
4301}
4302
Jeff Brown81346812011-06-28 20:08:48 -07004303bool InputDispatcher::InputState::isHovering(int32_t deviceId, uint32_t source) const {
4304 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4305 const MotionMemento& memento = mMotionMementos.itemAt(i);
4306 if (memento.deviceId == deviceId
4307 && memento.source == source
4308 && memento.hovering) {
4309 return true;
4310 }
4311 }
4312 return false;
4313}
Jeff Brownb88102f2010-09-08 11:49:43 -07004314
Jeff Brown81346812011-06-28 20:08:48 -07004315bool InputDispatcher::InputState::trackKey(const KeyEntry* entry,
4316 int32_t action, int32_t flags) {
4317 switch (action) {
4318 case AKEY_EVENT_ACTION_UP: {
4319 if (entry->flags & AKEY_EVENT_FLAG_FALLBACK) {
4320 for (size_t i = 0; i < mFallbackKeys.size(); ) {
4321 if (mFallbackKeys.valueAt(i) == entry->keyCode) {
4322 mFallbackKeys.removeItemsAt(i);
4323 } else {
4324 i += 1;
4325 }
4326 }
4327 }
4328 ssize_t index = findKeyMemento(entry);
4329 if (index >= 0) {
4330 mKeyMementos.removeAt(index);
4331 return true;
4332 }
Jeff Brown68b909d2011-12-07 16:36:01 -08004333 /* FIXME: We can't just drop the key up event because that prevents creating
4334 * popup windows that are automatically shown when a key is held and then
4335 * dismissed when the key is released. The problem is that the popup will
4336 * not have received the original key down, so the key up will be considered
4337 * to be inconsistent with its observed state. We could perhaps handle this
4338 * by synthesizing a key down but that will cause other problems.
4339 *
4340 * So for now, allow inconsistent key up events to be dispatched.
4341 *
Jeff Brown81346812011-06-28 20:08:48 -07004342#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00004343 ALOGD("Dropping inconsistent key up event: deviceId=%d, source=%08x, "
Jeff Brown81346812011-06-28 20:08:48 -07004344 "keyCode=%d, scanCode=%d",
4345 entry->deviceId, entry->source, entry->keyCode, entry->scanCode);
4346#endif
4347 return false;
Jeff Brown68b909d2011-12-07 16:36:01 -08004348 */
4349 return true;
Jeff Brown81346812011-06-28 20:08:48 -07004350 }
4351
4352 case AKEY_EVENT_ACTION_DOWN: {
4353 ssize_t index = findKeyMemento(entry);
4354 if (index >= 0) {
4355 mKeyMementos.removeAt(index);
4356 }
4357 addKeyMemento(entry, flags);
4358 return true;
4359 }
4360
4361 default:
4362 return true;
Jeff Brownb88102f2010-09-08 11:49:43 -07004363 }
4364}
4365
Jeff Brown81346812011-06-28 20:08:48 -07004366bool InputDispatcher::InputState::trackMotion(const MotionEntry* entry,
4367 int32_t action, int32_t flags) {
4368 int32_t actionMasked = action & AMOTION_EVENT_ACTION_MASK;
4369 switch (actionMasked) {
4370 case AMOTION_EVENT_ACTION_UP:
4371 case AMOTION_EVENT_ACTION_CANCEL: {
4372 ssize_t index = findMotionMemento(entry, false /*hovering*/);
4373 if (index >= 0) {
4374 mMotionMementos.removeAt(index);
4375 return true;
Jeff Brownda3d5a92011-03-29 15:11:34 -07004376 }
Jeff Brown81346812011-06-28 20:08:48 -07004377#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00004378 ALOGD("Dropping inconsistent motion up or cancel event: deviceId=%d, source=%08x, "
Jeff Brown81346812011-06-28 20:08:48 -07004379 "actionMasked=%d",
4380 entry->deviceId, entry->source, actionMasked);
4381#endif
4382 return false;
Jeff Brownda3d5a92011-03-29 15:11:34 -07004383 }
4384
Jeff Brown81346812011-06-28 20:08:48 -07004385 case AMOTION_EVENT_ACTION_DOWN: {
4386 ssize_t index = findMotionMemento(entry, false /*hovering*/);
4387 if (index >= 0) {
4388 mMotionMementos.removeAt(index);
4389 }
4390 addMotionMemento(entry, flags, false /*hovering*/);
4391 return true;
4392 }
4393
4394 case AMOTION_EVENT_ACTION_POINTER_UP:
4395 case AMOTION_EVENT_ACTION_POINTER_DOWN:
4396 case AMOTION_EVENT_ACTION_MOVE: {
4397 ssize_t index = findMotionMemento(entry, false /*hovering*/);
4398 if (index >= 0) {
4399 MotionMemento& memento = mMotionMementos.editItemAt(index);
4400 memento.setPointers(entry);
4401 return true;
4402 }
Jeff Brown2e45fb62011-06-29 21:19:05 -07004403 if (actionMasked == AMOTION_EVENT_ACTION_MOVE
4404 && (entry->source & (AINPUT_SOURCE_CLASS_JOYSTICK
4405 | AINPUT_SOURCE_CLASS_NAVIGATION))) {
4406 // Joysticks and trackballs can send MOVE events without corresponding DOWN or UP.
4407 return true;
4408 }
Jeff Brown81346812011-06-28 20:08:48 -07004409#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00004410 ALOGD("Dropping inconsistent motion pointer up/down or move event: "
Jeff Brown81346812011-06-28 20:08:48 -07004411 "deviceId=%d, source=%08x, actionMasked=%d",
4412 entry->deviceId, entry->source, actionMasked);
4413#endif
4414 return false;
4415 }
4416
4417 case AMOTION_EVENT_ACTION_HOVER_EXIT: {
4418 ssize_t index = findMotionMemento(entry, true /*hovering*/);
4419 if (index >= 0) {
4420 mMotionMementos.removeAt(index);
4421 return true;
4422 }
4423#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00004424 ALOGD("Dropping inconsistent motion hover exit event: deviceId=%d, source=%08x",
Jeff Brown81346812011-06-28 20:08:48 -07004425 entry->deviceId, entry->source);
4426#endif
4427 return false;
4428 }
4429
4430 case AMOTION_EVENT_ACTION_HOVER_ENTER:
4431 case AMOTION_EVENT_ACTION_HOVER_MOVE: {
4432 ssize_t index = findMotionMemento(entry, true /*hovering*/);
4433 if (index >= 0) {
4434 mMotionMementos.removeAt(index);
4435 }
4436 addMotionMemento(entry, flags, true /*hovering*/);
4437 return true;
4438 }
4439
4440 default:
4441 return true;
4442 }
4443}
4444
4445ssize_t InputDispatcher::InputState::findKeyMemento(const KeyEntry* entry) const {
Jeff Brownb88102f2010-09-08 11:49:43 -07004446 for (size_t i = 0; i < mKeyMementos.size(); i++) {
Jeff Brown81346812011-06-28 20:08:48 -07004447 const KeyMemento& memento = mKeyMementos.itemAt(i);
Jeff Brownb88102f2010-09-08 11:49:43 -07004448 if (memento.deviceId == entry->deviceId
4449 && memento.source == entry->source
4450 && memento.keyCode == entry->keyCode
4451 && memento.scanCode == entry->scanCode) {
Jeff Brown81346812011-06-28 20:08:48 -07004452 return i;
Jeff Brownb88102f2010-09-08 11:49:43 -07004453 }
4454 }
Jeff Brown81346812011-06-28 20:08:48 -07004455 return -1;
Jeff Brownb88102f2010-09-08 11:49:43 -07004456}
4457
Jeff Brown81346812011-06-28 20:08:48 -07004458ssize_t InputDispatcher::InputState::findMotionMemento(const MotionEntry* entry,
4459 bool hovering) const {
Jeff Brownb88102f2010-09-08 11:49:43 -07004460 for (size_t i = 0; i < mMotionMementos.size(); i++) {
Jeff Brown81346812011-06-28 20:08:48 -07004461 const MotionMemento& memento = mMotionMementos.itemAt(i);
Jeff Brownb88102f2010-09-08 11:49:43 -07004462 if (memento.deviceId == entry->deviceId
Jeff Brown81346812011-06-28 20:08:48 -07004463 && memento.source == entry->source
4464 && memento.hovering == hovering) {
4465 return i;
Jeff Brownb88102f2010-09-08 11:49:43 -07004466 }
4467 }
Jeff Brown81346812011-06-28 20:08:48 -07004468 return -1;
4469}
Jeff Brownb88102f2010-09-08 11:49:43 -07004470
Jeff Brown81346812011-06-28 20:08:48 -07004471void InputDispatcher::InputState::addKeyMemento(const KeyEntry* entry, int32_t flags) {
4472 mKeyMementos.push();
4473 KeyMemento& memento = mKeyMementos.editTop();
4474 memento.deviceId = entry->deviceId;
4475 memento.source = entry->source;
4476 memento.keyCode = entry->keyCode;
4477 memento.scanCode = entry->scanCode;
4478 memento.flags = flags;
4479 memento.downTime = entry->downTime;
4480}
4481
4482void InputDispatcher::InputState::addMotionMemento(const MotionEntry* entry,
4483 int32_t flags, bool hovering) {
4484 mMotionMementos.push();
4485 MotionMemento& memento = mMotionMementos.editTop();
4486 memento.deviceId = entry->deviceId;
4487 memento.source = entry->source;
4488 memento.flags = flags;
4489 memento.xPrecision = entry->xPrecision;
4490 memento.yPrecision = entry->yPrecision;
4491 memento.downTime = entry->downTime;
4492 memento.setPointers(entry);
4493 memento.hovering = hovering;
Jeff Brownb88102f2010-09-08 11:49:43 -07004494}
4495
4496void InputDispatcher::InputState::MotionMemento::setPointers(const MotionEntry* entry) {
4497 pointerCount = entry->pointerCount;
4498 for (uint32_t i = 0; i < entry->pointerCount; i++) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07004499 pointerProperties[i].copyFrom(entry->pointerProperties[i]);
Jeff Brownace13b12011-03-09 17:39:48 -08004500 pointerCoords[i].copyFrom(entry->lastSample->pointerCoords[i]);
Jeff Brownb88102f2010-09-08 11:49:43 -07004501 }
4502}
4503
Jeff Brownb6997262010-10-08 22:31:17 -07004504void InputDispatcher::InputState::synthesizeCancelationEvents(nsecs_t currentTime,
Jeff Brownac386072011-07-20 15:19:50 -07004505 Vector<EventEntry*>& outEvents, const CancelationOptions& options) {
Jeff Brown81346812011-06-28 20:08:48 -07004506 for (size_t i = 0; i < mKeyMementos.size(); i++) {
Jeff Brownb88102f2010-09-08 11:49:43 -07004507 const KeyMemento& memento = mKeyMementos.itemAt(i);
Jeff Brown49ed71d2010-12-06 17:13:33 -08004508 if (shouldCancelKey(memento, options)) {
Jeff Brownac386072011-07-20 15:19:50 -07004509 outEvents.push(new KeyEntry(currentTime,
Jeff Brownb6997262010-10-08 22:31:17 -07004510 memento.deviceId, memento.source, 0,
Jeff Brown49ed71d2010-12-06 17:13:33 -08004511 AKEY_EVENT_ACTION_UP, memento.flags | AKEY_EVENT_FLAG_CANCELED,
Jeff Brownb6997262010-10-08 22:31:17 -07004512 memento.keyCode, memento.scanCode, 0, 0, memento.downTime));
Jeff Brownb6997262010-10-08 22:31:17 -07004513 }
Jeff Brownb88102f2010-09-08 11:49:43 -07004514 }
4515
Jeff Brown81346812011-06-28 20:08:48 -07004516 for (size_t i = 0; i < mMotionMementos.size(); i++) {
Jeff Brownb88102f2010-09-08 11:49:43 -07004517 const MotionMemento& memento = mMotionMementos.itemAt(i);
Jeff Brown49ed71d2010-12-06 17:13:33 -08004518 if (shouldCancelMotion(memento, options)) {
Jeff Brownac386072011-07-20 15:19:50 -07004519 outEvents.push(new MotionEntry(currentTime,
Jeff Brownb6997262010-10-08 22:31:17 -07004520 memento.deviceId, memento.source, 0,
Jeff Browna032cc02011-03-07 16:56:21 -08004521 memento.hovering
4522 ? AMOTION_EVENT_ACTION_HOVER_EXIT
4523 : AMOTION_EVENT_ACTION_CANCEL,
Jeff Brown81346812011-06-28 20:08:48 -07004524 memento.flags, 0, 0, 0,
Jeff Brownb6997262010-10-08 22:31:17 -07004525 memento.xPrecision, memento.yPrecision, memento.downTime,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07004526 memento.pointerCount, memento.pointerProperties, memento.pointerCoords));
Jeff Brownb6997262010-10-08 22:31:17 -07004527 }
Jeff Brownb88102f2010-09-08 11:49:43 -07004528 }
4529}
4530
4531void InputDispatcher::InputState::clear() {
4532 mKeyMementos.clear();
4533 mMotionMementos.clear();
Jeff Brownda3d5a92011-03-29 15:11:34 -07004534 mFallbackKeys.clear();
Jeff Brownb6997262010-10-08 22:31:17 -07004535}
4536
Jeff Brown9c9f1a32010-10-11 18:32:20 -07004537void InputDispatcher::InputState::copyPointerStateTo(InputState& other) const {
4538 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4539 const MotionMemento& memento = mMotionMementos.itemAt(i);
4540 if (memento.source & AINPUT_SOURCE_CLASS_POINTER) {
4541 for (size_t j = 0; j < other.mMotionMementos.size(); ) {
4542 const MotionMemento& otherMemento = other.mMotionMementos.itemAt(j);
4543 if (memento.deviceId == otherMemento.deviceId
4544 && memento.source == otherMemento.source) {
4545 other.mMotionMementos.removeAt(j);
4546 } else {
4547 j += 1;
4548 }
4549 }
4550 other.mMotionMementos.push(memento);
4551 }
4552 }
4553}
4554
Jeff Brownda3d5a92011-03-29 15:11:34 -07004555int32_t InputDispatcher::InputState::getFallbackKey(int32_t originalKeyCode) {
4556 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
4557 return index >= 0 ? mFallbackKeys.valueAt(index) : -1;
4558}
4559
4560void InputDispatcher::InputState::setFallbackKey(int32_t originalKeyCode,
4561 int32_t fallbackKeyCode) {
4562 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
4563 if (index >= 0) {
4564 mFallbackKeys.replaceValueAt(index, fallbackKeyCode);
4565 } else {
4566 mFallbackKeys.add(originalKeyCode, fallbackKeyCode);
4567 }
4568}
4569
4570void InputDispatcher::InputState::removeFallbackKey(int32_t originalKeyCode) {
4571 mFallbackKeys.removeItem(originalKeyCode);
4572}
4573
Jeff Brown49ed71d2010-12-06 17:13:33 -08004574bool InputDispatcher::InputState::shouldCancelKey(const KeyMemento& memento,
Jeff Brownda3d5a92011-03-29 15:11:34 -07004575 const CancelationOptions& options) {
4576 if (options.keyCode != -1 && memento.keyCode != options.keyCode) {
4577 return false;
4578 }
4579
Jeff Brown65fd2512011-08-18 11:20:58 -07004580 if (options.deviceId != -1 && memento.deviceId != options.deviceId) {
4581 return false;
4582 }
4583
Jeff Brownda3d5a92011-03-29 15:11:34 -07004584 switch (options.mode) {
4585 case CancelationOptions::CANCEL_ALL_EVENTS:
4586 case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
Jeff Brownb6997262010-10-08 22:31:17 -07004587 return true;
Jeff Brownda3d5a92011-03-29 15:11:34 -07004588 case CancelationOptions::CANCEL_FALLBACK_EVENTS:
Jeff Brown49ed71d2010-12-06 17:13:33 -08004589 return memento.flags & AKEY_EVENT_FLAG_FALLBACK;
4590 default:
4591 return false;
4592 }
4593}
4594
4595bool InputDispatcher::InputState::shouldCancelMotion(const MotionMemento& memento,
Jeff Brownda3d5a92011-03-29 15:11:34 -07004596 const CancelationOptions& options) {
Jeff Brown65fd2512011-08-18 11:20:58 -07004597 if (options.deviceId != -1 && memento.deviceId != options.deviceId) {
4598 return false;
4599 }
4600
Jeff Brownda3d5a92011-03-29 15:11:34 -07004601 switch (options.mode) {
4602 case CancelationOptions::CANCEL_ALL_EVENTS:
Jeff Brown49ed71d2010-12-06 17:13:33 -08004603 return true;
Jeff Brownda3d5a92011-03-29 15:11:34 -07004604 case CancelationOptions::CANCEL_POINTER_EVENTS:
Jeff Brown49ed71d2010-12-06 17:13:33 -08004605 return memento.source & AINPUT_SOURCE_CLASS_POINTER;
Jeff Brownda3d5a92011-03-29 15:11:34 -07004606 case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
Jeff Brown49ed71d2010-12-06 17:13:33 -08004607 return !(memento.source & AINPUT_SOURCE_CLASS_POINTER);
4608 default:
4609 return false;
Jeff Brownb6997262010-10-08 22:31:17 -07004610 }
Jeff Brownb88102f2010-09-08 11:49:43 -07004611}
4612
4613
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004614// --- InputDispatcher::Connection ---
4615
Jeff Brown928e0542011-01-10 11:17:36 -08004616InputDispatcher::Connection::Connection(const sp<InputChannel>& inputChannel,
Jeff Browncc4f7db2011-08-30 20:34:48 -07004617 const sp<InputWindowHandle>& inputWindowHandle, bool monitor) :
Jeff Brown928e0542011-01-10 11:17:36 -08004618 status(STATUS_NORMAL), inputChannel(inputChannel), inputWindowHandle(inputWindowHandle),
Jeff Browncc4f7db2011-08-30 20:34:48 -07004619 monitor(monitor),
Jeff Brown928e0542011-01-10 11:17:36 -08004620 inputPublisher(inputChannel),
Jeff Brownda3d5a92011-03-29 15:11:34 -07004621 lastEventTime(LONG_LONG_MAX), lastDispatchTime(LONG_LONG_MAX) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004622}
4623
4624InputDispatcher::Connection::~Connection() {
4625}
4626
4627status_t InputDispatcher::Connection::initialize() {
4628 return inputPublisher.initialize();
4629}
4630
Jeff Brown9c3cda02010-06-15 01:31:58 -07004631const char* InputDispatcher::Connection::getStatusLabel() const {
4632 switch (status) {
4633 case STATUS_NORMAL:
4634 return "NORMAL";
4635
4636 case STATUS_BROKEN:
4637 return "BROKEN";
4638
Jeff Brown9c3cda02010-06-15 01:31:58 -07004639 case STATUS_ZOMBIE:
4640 return "ZOMBIE";
4641
4642 default:
4643 return "UNKNOWN";
4644 }
4645}
4646
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004647InputDispatcher::DispatchEntry* InputDispatcher::Connection::findQueuedDispatchEntryForEvent(
4648 const EventEntry* eventEntry) const {
Jeff Brownac386072011-07-20 15:19:50 -07004649 for (DispatchEntry* dispatchEntry = outboundQueue.tail; dispatchEntry;
4650 dispatchEntry = dispatchEntry->prev) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004651 if (dispatchEntry->eventEntry == eventEntry) {
4652 return dispatchEntry;
4653 }
4654 }
4655 return NULL;
4656}
4657
Jeff Brownb88102f2010-09-08 11:49:43 -07004658
Jeff Brown9c3cda02010-06-15 01:31:58 -07004659// --- InputDispatcher::CommandEntry ---
4660
Jeff Brownac386072011-07-20 15:19:50 -07004661InputDispatcher::CommandEntry::CommandEntry(Command command) :
4662 command(command), eventTime(0), keyEntry(NULL), userActivityEventType(0), handled(false) {
Jeff Brown9c3cda02010-06-15 01:31:58 -07004663}
4664
4665InputDispatcher::CommandEntry::~CommandEntry() {
4666}
4667
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004668
Jeff Brown01ce2e92010-09-26 22:20:12 -07004669// --- InputDispatcher::TouchState ---
4670
4671InputDispatcher::TouchState::TouchState() :
Jeff Brown58a2da82011-01-25 16:02:22 -08004672 down(false), split(false), deviceId(-1), source(0) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07004673}
4674
4675InputDispatcher::TouchState::~TouchState() {
4676}
4677
4678void InputDispatcher::TouchState::reset() {
4679 down = false;
4680 split = false;
Jeff Brown95712852011-01-04 19:41:59 -08004681 deviceId = -1;
Jeff Brown58a2da82011-01-25 16:02:22 -08004682 source = 0;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004683 windows.clear();
4684}
4685
4686void InputDispatcher::TouchState::copyFrom(const TouchState& other) {
4687 down = other.down;
4688 split = other.split;
Jeff Brown95712852011-01-04 19:41:59 -08004689 deviceId = other.deviceId;
Jeff Brown58a2da82011-01-25 16:02:22 -08004690 source = other.source;
Jeff Brown9302c872011-07-13 22:51:29 -07004691 windows = other.windows;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004692}
4693
Jeff Brown9302c872011-07-13 22:51:29 -07004694void InputDispatcher::TouchState::addOrUpdateWindow(const sp<InputWindowHandle>& windowHandle,
Jeff Brown01ce2e92010-09-26 22:20:12 -07004695 int32_t targetFlags, BitSet32 pointerIds) {
4696 if (targetFlags & InputTarget::FLAG_SPLIT) {
4697 split = true;
4698 }
4699
4700 for (size_t i = 0; i < windows.size(); i++) {
4701 TouchedWindow& touchedWindow = windows.editItemAt(i);
Jeff Brown9302c872011-07-13 22:51:29 -07004702 if (touchedWindow.windowHandle == windowHandle) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07004703 touchedWindow.targetFlags |= targetFlags;
Jeff Brown98db5fa2011-06-08 15:37:10 -07004704 if (targetFlags & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
4705 touchedWindow.targetFlags &= ~InputTarget::FLAG_DISPATCH_AS_IS;
4706 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07004707 touchedWindow.pointerIds.value |= pointerIds.value;
4708 return;
4709 }
4710 }
4711
4712 windows.push();
4713
4714 TouchedWindow& touchedWindow = windows.editTop();
Jeff Brown9302c872011-07-13 22:51:29 -07004715 touchedWindow.windowHandle = windowHandle;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004716 touchedWindow.targetFlags = targetFlags;
4717 touchedWindow.pointerIds = pointerIds;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004718}
4719
Jeff Browna032cc02011-03-07 16:56:21 -08004720void InputDispatcher::TouchState::filterNonAsIsTouchWindows() {
Jeff Brown01ce2e92010-09-26 22:20:12 -07004721 for (size_t i = 0 ; i < windows.size(); ) {
Jeff Browna032cc02011-03-07 16:56:21 -08004722 TouchedWindow& window = windows.editItemAt(i);
Jeff Brown98db5fa2011-06-08 15:37:10 -07004723 if (window.targetFlags & (InputTarget::FLAG_DISPATCH_AS_IS
4724 | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER)) {
Jeff Browna032cc02011-03-07 16:56:21 -08004725 window.targetFlags &= ~InputTarget::FLAG_DISPATCH_MASK;
4726 window.targetFlags |= InputTarget::FLAG_DISPATCH_AS_IS;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004727 i += 1;
Jeff Browna032cc02011-03-07 16:56:21 -08004728 } else {
4729 windows.removeAt(i);
Jeff Brown01ce2e92010-09-26 22:20:12 -07004730 }
4731 }
4732}
4733
Jeff Brown9302c872011-07-13 22:51:29 -07004734sp<InputWindowHandle> InputDispatcher::TouchState::getFirstForegroundWindowHandle() const {
Jeff Brown01ce2e92010-09-26 22:20:12 -07004735 for (size_t i = 0; i < windows.size(); i++) {
Jeff Brown98db5fa2011-06-08 15:37:10 -07004736 const TouchedWindow& window = windows.itemAt(i);
4737 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
Jeff Brown9302c872011-07-13 22:51:29 -07004738 return window.windowHandle;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004739 }
4740 }
4741 return NULL;
4742}
4743
Jeff Brown98db5fa2011-06-08 15:37:10 -07004744bool InputDispatcher::TouchState::isSlippery() const {
4745 // Must have exactly one foreground window.
4746 bool haveSlipperyForegroundWindow = false;
4747 for (size_t i = 0; i < windows.size(); i++) {
4748 const TouchedWindow& window = windows.itemAt(i);
4749 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
Jeff Browncc4f7db2011-08-30 20:34:48 -07004750 if (haveSlipperyForegroundWindow
4751 || !(window.windowHandle->getInfo()->layoutParamsFlags
4752 & InputWindowInfo::FLAG_SLIPPERY)) {
Jeff Brown98db5fa2011-06-08 15:37:10 -07004753 return false;
4754 }
4755 haveSlipperyForegroundWindow = true;
4756 }
4757 }
4758 return haveSlipperyForegroundWindow;
4759}
4760
Jeff Brown01ce2e92010-09-26 22:20:12 -07004761
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004762// --- InputDispatcherThread ---
4763
4764InputDispatcherThread::InputDispatcherThread(const sp<InputDispatcherInterface>& dispatcher) :
4765 Thread(/*canCallJava*/ true), mDispatcher(dispatcher) {
4766}
4767
4768InputDispatcherThread::~InputDispatcherThread() {
4769}
4770
4771bool InputDispatcherThread::threadLoop() {
4772 mDispatcher->dispatchOnce();
4773 return true;
4774}
4775
4776} // namespace android