blob: a06208a949c263755a49e6cda03e560de1f3fb02 [file] [log] [blame]
Jeff Browne839a582010-04-22 18:58:52 -07001/*
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
17#ifndef _UI_INPUT_DISPATCHER_H
18#define _UI_INPUT_DISPATCHER_H
19
20#include <ui/Input.h>
Jeff Browne839a582010-04-22 18:58:52 -070021#include <ui/InputTransport.h>
22#include <utils/KeyedVector.h>
23#include <utils/Vector.h>
24#include <utils/threads.h>
25#include <utils/Timers.h>
26#include <utils/RefBase.h>
27#include <utils/String8.h>
28#include <utils/PollLoop.h>
29#include <utils/Pool.h>
30
31#include <stddef.h>
32#include <unistd.h>
Jeff Browna665ca82010-09-08 11:49:43 -070033#include <limits.h>
Jeff Browne839a582010-04-22 18:58:52 -070034
35
36namespace android {
37
Jeff Brown54bc2812010-06-15 01:31:58 -070038/*
Jeff Brown51d45a72010-06-17 20:52:56 -070039 * Constants used to report the outcome of input event injection.
40 */
41enum {
42 /* (INTERNAL USE ONLY) Specifies that injection is pending and its outcome is unknown. */
43 INPUT_EVENT_INJECTION_PENDING = -1,
44
45 /* Injection succeeded. */
46 INPUT_EVENT_INJECTION_SUCCEEDED = 0,
47
48 /* Injection failed because the injector did not have permission to inject
49 * into the application with input focus. */
50 INPUT_EVENT_INJECTION_PERMISSION_DENIED = 1,
51
52 /* Injection failed because there were no available input targets. */
53 INPUT_EVENT_INJECTION_FAILED = 2,
54
55 /* Injection failed due to a timeout. */
56 INPUT_EVENT_INJECTION_TIMED_OUT = 3
57};
58
Jeff Brownf67c53e2010-07-28 15:48:59 -070059/*
60 * Constants used to determine the input event injection synchronization mode.
61 */
62enum {
63 /* Injection is asynchronous and is assumed always to be successful. */
64 INPUT_EVENT_INJECTION_SYNC_NONE = 0,
65
66 /* Waits for previous events to be dispatched so that the input dispatcher can determine
67 * whether input event injection willbe permitted based on the current input focus.
68 * Does not wait for the input event to finish processing. */
69 INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_RESULT = 1,
70
71 /* Waits for the input event to be completely processed. */
72 INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED = 2,
73};
74
Jeff Brown51d45a72010-06-17 20:52:56 -070075
76/*
Jeff Brown54bc2812010-06-15 01:31:58 -070077 * An input target specifies how an input event is to be dispatched to a particular window
78 * including the window's input channel, control flags, a timeout, and an X / Y offset to
79 * be added to input event coordinates to compensate for the absolute position of the
80 * window area.
81 */
82struct InputTarget {
83 enum {
84 /* This flag indicates that subsequent event delivery should be held until the
85 * current event is delivered to this target or a timeout occurs. */
86 FLAG_SYNC = 0x01,
87
Jeff Brownaf30ff62010-09-01 17:01:00 -070088 /* This flag indicates that a MotionEvent with AMOTION_EVENT_ACTION_DOWN falls outside
89 * of the area of this target and so should instead be delivered as an
90 * AMOTION_EVENT_ACTION_OUTSIDE to this target. */
Jeff Brown54bc2812010-06-15 01:31:58 -070091 FLAG_OUTSIDE = 0x02,
92
93 /* This flag indicates that a KeyEvent or MotionEvent is being canceled.
Jeff Brownaf30ff62010-09-01 17:01:00 -070094 * In the case of a key event, it should be delivered with flag
95 * AKEY_EVENT_FLAG_CANCELED set.
96 * In the case of a motion event, it should be delivered with action
97 * AMOTION_EVENT_ACTION_CANCEL instead. */
98 FLAG_CANCEL = 0x04,
99
100 /* This flag indicates that the target of a MotionEvent is partly or wholly
101 * obscured by another visible window above it. The motion event should be
102 * delivered with flag AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED. */
103 FLAG_WINDOW_IS_OBSCURED = 0x08,
Jeff Brown54bc2812010-06-15 01:31:58 -0700104 };
105
106 // The input channel to be targeted.
107 sp<InputChannel> inputChannel;
108
109 // Flags for the input target.
110 int32_t flags;
111
Jeff Browna665ca82010-09-08 11:49:43 -0700112 // The timeout for event delivery to this target in nanoseconds, or -1 to wait indefinitely.
Jeff Brown54bc2812010-06-15 01:31:58 -0700113 nsecs_t timeout;
114
Jeff Browna665ca82010-09-08 11:49:43 -0700115 // The time already spent waiting for this target in nanoseconds, or 0 if none.
116 nsecs_t timeSpentWaitingForApplication;
117
Jeff Brown54bc2812010-06-15 01:31:58 -0700118 // The x and y offset to add to a MotionEvent as it is delivered.
119 // (ignored for KeyEvents)
120 float xOffset, yOffset;
121};
122
Jeff Brown51d45a72010-06-17 20:52:56 -0700123
Jeff Brown54bc2812010-06-15 01:31:58 -0700124/*
Jeff Browna665ca82010-09-08 11:49:43 -0700125 * An input window describes the bounds of a window that can receive input.
126 */
127struct InputWindow {
128 // Window flags from WindowManager.LayoutParams
129 enum {
130 FLAG_ALLOW_LOCK_WHILE_SCREEN_ON = 0x00000001,
131 FLAG_DIM_BEHIND = 0x00000002,
132 FLAG_BLUR_BEHIND = 0x00000004,
133 FLAG_NOT_FOCUSABLE = 0x00000008,
134 FLAG_NOT_TOUCHABLE = 0x00000010,
135 FLAG_NOT_TOUCH_MODAL = 0x00000020,
136 FLAG_TOUCHABLE_WHEN_WAKING = 0x00000040,
137 FLAG_KEEP_SCREEN_ON = 0x00000080,
138 FLAG_LAYOUT_IN_SCREEN = 0x00000100,
139 FLAG_LAYOUT_NO_LIMITS = 0x00000200,
140 FLAG_FULLSCREEN = 0x00000400,
141 FLAG_FORCE_NOT_FULLSCREEN = 0x00000800,
142 FLAG_DITHER = 0x00001000,
143 FLAG_SECURE = 0x00002000,
144 FLAG_SCALED = 0x00004000,
145 FLAG_IGNORE_CHEEK_PRESSES = 0x00008000,
146 FLAG_LAYOUT_INSET_DECOR = 0x00010000,
147 FLAG_ALT_FOCUSABLE_IM = 0x00020000,
148 FLAG_WATCH_OUTSIDE_TOUCH = 0x00040000,
149 FLAG_SHOW_WHEN_LOCKED = 0x00080000,
150 FLAG_SHOW_WALLPAPER = 0x00100000,
151 FLAG_TURN_SCREEN_ON = 0x00200000,
152 FLAG_DISMISS_KEYGUARD = 0x00400000,
153 FLAG_IMMERSIVE = 0x00800000,
154 FLAG_KEEP_SURFACE_WHILE_ANIMATING = 0x10000000,
155 FLAG_COMPATIBLE_WINDOW = 0x20000000,
156 FLAG_SYSTEM_ERROR = 0x40000000,
157 };
158
159 // Window types from WindowManager.LayoutParams
160 enum {
161 FIRST_APPLICATION_WINDOW = 1,
162 TYPE_BASE_APPLICATION = 1,
163 TYPE_APPLICATION = 2,
164 TYPE_APPLICATION_STARTING = 3,
165 LAST_APPLICATION_WINDOW = 99,
166 FIRST_SUB_WINDOW = 1000,
167 TYPE_APPLICATION_PANEL = FIRST_SUB_WINDOW,
168 TYPE_APPLICATION_MEDIA = FIRST_SUB_WINDOW+1,
169 TYPE_APPLICATION_SUB_PANEL = FIRST_SUB_WINDOW+2,
170 TYPE_APPLICATION_ATTACHED_DIALOG = FIRST_SUB_WINDOW+3,
171 TYPE_APPLICATION_MEDIA_OVERLAY = FIRST_SUB_WINDOW+4,
172 LAST_SUB_WINDOW = 1999,
173 FIRST_SYSTEM_WINDOW = 2000,
174 TYPE_STATUS_BAR = FIRST_SYSTEM_WINDOW,
175 TYPE_SEARCH_BAR = FIRST_SYSTEM_WINDOW+1,
176 TYPE_PHONE = FIRST_SYSTEM_WINDOW+2,
177 TYPE_SYSTEM_ALERT = FIRST_SYSTEM_WINDOW+3,
178 TYPE_KEYGUARD = FIRST_SYSTEM_WINDOW+4,
179 TYPE_TOAST = FIRST_SYSTEM_WINDOW+5,
180 TYPE_SYSTEM_OVERLAY = FIRST_SYSTEM_WINDOW+6,
181 TYPE_PRIORITY_PHONE = FIRST_SYSTEM_WINDOW+7,
182 TYPE_SYSTEM_DIALOG = FIRST_SYSTEM_WINDOW+8,
183 TYPE_KEYGUARD_DIALOG = FIRST_SYSTEM_WINDOW+9,
184 TYPE_SYSTEM_ERROR = FIRST_SYSTEM_WINDOW+10,
185 TYPE_INPUT_METHOD = FIRST_SYSTEM_WINDOW+11,
186 TYPE_INPUT_METHOD_DIALOG= FIRST_SYSTEM_WINDOW+12,
187 TYPE_WALLPAPER = FIRST_SYSTEM_WINDOW+13,
188 TYPE_STATUS_BAR_PANEL = FIRST_SYSTEM_WINDOW+14,
189 LAST_SYSTEM_WINDOW = 2999,
190 };
191
192 sp<InputChannel> inputChannel;
193 int32_t layoutParamsFlags;
194 int32_t layoutParamsType;
195 nsecs_t dispatchingTimeout;
196 int32_t frameLeft;
197 int32_t frameTop;
198 int32_t frameRight;
199 int32_t frameBottom;
200 int32_t visibleFrameLeft;
201 int32_t visibleFrameTop;
202 int32_t visibleFrameRight;
203 int32_t visibleFrameBottom;
204 int32_t touchableAreaLeft;
205 int32_t touchableAreaTop;
206 int32_t touchableAreaRight;
207 int32_t touchableAreaBottom;
208 bool visible;
209 bool hasFocus;
210 bool hasWallpaper;
211 bool paused;
212 int32_t ownerPid;
213 int32_t ownerUid;
214
215 bool visibleFrameIntersects(const InputWindow* other) const;
216 bool touchableAreaContainsPoint(int32_t x, int32_t y) const;
217};
218
219
220/*
221 * A private handle type used by the input manager to track the window.
222 */
223class InputApplicationHandle : public RefBase {
224protected:
225 InputApplicationHandle() { }
226 virtual ~InputApplicationHandle() { }
227};
228
229
230/*
231 * An input application describes properties of an application that can receive input.
232 */
233struct InputApplication {
234 String8 name;
235 nsecs_t dispatchingTimeout;
236 sp<InputApplicationHandle> handle;
237};
238
239
240/*
Jeff Brown54bc2812010-06-15 01:31:58 -0700241 * Input dispatcher policy interface.
242 *
243 * The input reader policy is used by the input reader to interact with the Window Manager
244 * and other system components.
245 *
246 * The actual implementation is partially supported by callbacks into the DVM
247 * via JNI. This interface is also mocked in the unit tests.
248 */
249class InputDispatcherPolicyInterface : public virtual RefBase {
250protected:
251 InputDispatcherPolicyInterface() { }
252 virtual ~InputDispatcherPolicyInterface() { }
253
254public:
255 /* Notifies the system that a configuration change has occurred. */
256 virtual void notifyConfigurationChanged(nsecs_t when) = 0;
257
Jeff Browna665ca82010-09-08 11:49:43 -0700258 /* Notifies the system that an application is not responding.
259 * Returns a new timeout to continue waiting, or 0 to abort dispatch. */
260 virtual nsecs_t notifyANR(const sp<InputApplicationHandle>& inputApplicationHandle) = 0;
261
Jeff Brown54bc2812010-06-15 01:31:58 -0700262 /* Notifies the system that an input channel is unrecoverably broken. */
263 virtual void notifyInputChannelBroken(const sp<InputChannel>& inputChannel) = 0;
264
Jeff Brown51d45a72010-06-17 20:52:56 -0700265 /* Notifies the system that an input channel is not responding.
Jeff Browna665ca82010-09-08 11:49:43 -0700266 * Returns a new timeout to continue waiting, or 0 to abort dispatch. */
267 virtual nsecs_t notifyInputChannelANR(const sp<InputChannel>& inputChannel) = 0;
Jeff Brown54bc2812010-06-15 01:31:58 -0700268
269 /* Notifies the system that an input channel recovered from ANR. */
270 virtual void notifyInputChannelRecoveredFromANR(const sp<InputChannel>& inputChannel) = 0;
271
Jeff Brown61ce3982010-09-07 10:44:57 -0700272 /* Gets the key repeat initial timeout or -1 if automatic key repeating is disabled. */
Jeff Brown54bc2812010-06-15 01:31:58 -0700273 virtual nsecs_t getKeyRepeatTimeout() = 0;
274
Jeff Brown61ce3982010-09-07 10:44:57 -0700275 /* Gets the key repeat inter-key delay. */
276 virtual nsecs_t getKeyRepeatDelay() = 0;
277
Jeff Brown542412c2010-08-18 15:51:08 -0700278 /* Gets the maximum suggested event delivery rate per second.
279 * This value is used to throttle motion event movement actions on a per-device
280 * basis. It is not intended to be a hard limit.
281 */
282 virtual int32_t getMaxEventsPerSecond() = 0;
Jeff Browna665ca82010-09-08 11:49:43 -0700283
284 /* Allows the policy a chance to intercept a key before dispatching. */
285 virtual bool interceptKeyBeforeDispatching(const sp<InputChannel>& inputChannel,
286 const KeyEvent* keyEvent, uint32_t policyFlags) = 0;
287
288 /* Poke user activity for an event dispatched to a window. */
289 virtual void pokeUserActivity(nsecs_t eventTime, int32_t windowType, int32_t eventType) = 0;
290
291 /* Checks whether a given application pid/uid has permission to inject input events
292 * into other applications.
293 *
294 * This method is special in that its implementation promises to be non-reentrant and
295 * is safe to call while holding other locks. (Most other methods make no such guarantees!)
296 */
297 virtual bool checkInjectEventsPermissionNonReentrant(
298 int32_t injectorPid, int32_t injectorUid) = 0;
Jeff Brown54bc2812010-06-15 01:31:58 -0700299};
300
301
Jeff Browne839a582010-04-22 18:58:52 -0700302/* Notifies the system about input events generated by the input reader.
303 * The dispatcher is expected to be mostly asynchronous. */
304class InputDispatcherInterface : public virtual RefBase {
305protected:
306 InputDispatcherInterface() { }
307 virtual ~InputDispatcherInterface() { }
308
309public:
Jeff Browna665ca82010-09-08 11:49:43 -0700310 /* Dumps the state of the input dispatcher.
311 *
312 * This method may be called on any thread (usually by the input manager). */
313 virtual void dump(String8& dump) = 0;
314
Jeff Browne839a582010-04-22 18:58:52 -0700315 /* Runs a single iteration of the dispatch loop.
316 * Nominally processes one queued event, a timeout, or a response from an input consumer.
317 *
318 * This method should only be called on the input dispatcher thread.
319 */
320 virtual void dispatchOnce() = 0;
321
322 /* Notifies the dispatcher about new events.
Jeff Browne839a582010-04-22 18:58:52 -0700323 *
324 * These methods should only be called on the input reader thread.
325 */
Jeff Brown54bc2812010-06-15 01:31:58 -0700326 virtual void notifyConfigurationChanged(nsecs_t eventTime) = 0;
Jeff Brown5c1ed842010-07-14 18:48:53 -0700327 virtual void notifyKey(nsecs_t eventTime, int32_t deviceId, int32_t source,
Jeff Browne839a582010-04-22 18:58:52 -0700328 uint32_t policyFlags, int32_t action, int32_t flags, int32_t keyCode,
329 int32_t scanCode, int32_t metaState, nsecs_t downTime) = 0;
Jeff Brown5c1ed842010-07-14 18:48:53 -0700330 virtual void notifyMotion(nsecs_t eventTime, int32_t deviceId, int32_t source,
Jeff Brownaf30ff62010-09-01 17:01:00 -0700331 uint32_t policyFlags, int32_t action, int32_t flags,
332 int32_t metaState, int32_t edgeFlags,
Jeff Browne839a582010-04-22 18:58:52 -0700333 uint32_t pointerCount, const int32_t* pointerIds, const PointerCoords* pointerCoords,
334 float xPrecision, float yPrecision, nsecs_t downTime) = 0;
335
Jeff Brown51d45a72010-06-17 20:52:56 -0700336 /* Injects an input event and optionally waits for sync.
Jeff Brownf67c53e2010-07-28 15:48:59 -0700337 * The synchronization mode determines whether the method blocks while waiting for
338 * input injection to proceed.
Jeff Brown51d45a72010-06-17 20:52:56 -0700339 * Returns one of the INPUT_EVENT_INJECTION_XXX constants.
340 *
341 * This method may be called on any thread (usually by the input manager).
342 */
343 virtual int32_t injectInputEvent(const InputEvent* event,
Jeff Brownf67c53e2010-07-28 15:48:59 -0700344 int32_t injectorPid, int32_t injectorUid, int32_t syncMode, int32_t timeoutMillis) = 0;
Jeff Brown51d45a72010-06-17 20:52:56 -0700345
Jeff Browna665ca82010-09-08 11:49:43 -0700346 /* Sets the list of input windows.
347 *
348 * This method may be called on any thread (usually by the input manager).
349 */
350 virtual void setInputWindows(const Vector<InputWindow>& inputWindows) = 0;
351
352 /* Sets the focused application.
353 *
354 * This method may be called on any thread (usually by the input manager).
355 */
356 virtual void setFocusedApplication(const InputApplication* inputApplication) = 0;
357
358 /* Sets the input dispatching mode.
359 *
360 * This method may be called on any thread (usually by the input manager).
361 */
362 virtual void setInputDispatchMode(bool enabled, bool frozen) = 0;
363
Jeff Brown50de30a2010-06-22 01:27:15 -0700364 /* Preempts input dispatch in progress by making pending synchronous
365 * dispatches asynchronous instead. This method is generally called during a focus
366 * transition from one application to the next so as to enable the new application
367 * to start receiving input as soon as possible without having to wait for the
368 * old application to finish up.
369 *
370 * This method may be called on any thread (usually by the input manager).
371 */
372 virtual void preemptInputDispatch() = 0;
373
Jeff Browne839a582010-04-22 18:58:52 -0700374 /* Registers or unregister input channels that may be used as targets for input events.
Jeff Browna665ca82010-09-08 11:49:43 -0700375 * If monitor is true, the channel will receive a copy of all input events.
Jeff Browne839a582010-04-22 18:58:52 -0700376 *
377 * These methods may be called on any thread (usually by the input manager).
378 */
Jeff Browna665ca82010-09-08 11:49:43 -0700379 virtual status_t registerInputChannel(const sp<InputChannel>& inputChannel, bool monitor) = 0;
Jeff Browne839a582010-04-22 18:58:52 -0700380 virtual status_t unregisterInputChannel(const sp<InputChannel>& inputChannel) = 0;
381};
382
Jeff Brown54bc2812010-06-15 01:31:58 -0700383/* Dispatches events to input targets. Some functions of the input dispatcher, such as
384 * identifying input targets, are controlled by a separate policy object.
385 *
386 * IMPORTANT INVARIANT:
387 * Because the policy can potentially block or cause re-entrance into the input dispatcher,
388 * the input dispatcher never calls into the policy while holding its internal locks.
389 * The implementation is also carefully designed to recover from scenarios such as an
390 * input channel becoming unregistered while identifying input targets or processing timeouts.
391 *
392 * Methods marked 'Locked' must be called with the lock acquired.
393 *
394 * Methods marked 'LockedInterruptible' must be called with the lock acquired but
395 * may during the course of their execution release the lock, call into the policy, and
396 * then reacquire the lock. The caller is responsible for recovering gracefully.
397 *
398 * A 'LockedInterruptible' method may called a 'Locked' method, but NOT vice-versa.
399 */
Jeff Browne839a582010-04-22 18:58:52 -0700400class InputDispatcher : public InputDispatcherInterface {
401protected:
402 virtual ~InputDispatcher();
403
404public:
Jeff Brown54bc2812010-06-15 01:31:58 -0700405 explicit InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy);
Jeff Browne839a582010-04-22 18:58:52 -0700406
Jeff Browna665ca82010-09-08 11:49:43 -0700407 virtual void dump(String8& dump);
408
Jeff Browne839a582010-04-22 18:58:52 -0700409 virtual void dispatchOnce();
410
Jeff Brown54bc2812010-06-15 01:31:58 -0700411 virtual void notifyConfigurationChanged(nsecs_t eventTime);
Jeff Brown5c1ed842010-07-14 18:48:53 -0700412 virtual void notifyKey(nsecs_t eventTime, int32_t deviceId, int32_t source,
Jeff Browne839a582010-04-22 18:58:52 -0700413 uint32_t policyFlags, int32_t action, int32_t flags, int32_t keyCode,
414 int32_t scanCode, int32_t metaState, nsecs_t downTime);
Jeff Brown5c1ed842010-07-14 18:48:53 -0700415 virtual void notifyMotion(nsecs_t eventTime, int32_t deviceId, int32_t source,
Jeff Brownaf30ff62010-09-01 17:01:00 -0700416 uint32_t policyFlags, int32_t action, int32_t flags,
417 int32_t metaState, int32_t edgeFlags,
Jeff Browne839a582010-04-22 18:58:52 -0700418 uint32_t pointerCount, const int32_t* pointerIds, const PointerCoords* pointerCoords,
419 float xPrecision, float yPrecision, nsecs_t downTime);
420
Jeff Brown51d45a72010-06-17 20:52:56 -0700421 virtual int32_t injectInputEvent(const InputEvent* event,
Jeff Brownf67c53e2010-07-28 15:48:59 -0700422 int32_t injectorPid, int32_t injectorUid, int32_t syncMode, int32_t timeoutMillis);
Jeff Brown51d45a72010-06-17 20:52:56 -0700423
Jeff Browna665ca82010-09-08 11:49:43 -0700424 virtual void setInputWindows(const Vector<InputWindow>& inputWindows);
425 virtual void setFocusedApplication(const InputApplication* inputApplication);
426 virtual void setInputDispatchMode(bool enabled, bool frozen);
Jeff Brown50de30a2010-06-22 01:27:15 -0700427 virtual void preemptInputDispatch();
428
Jeff Browna665ca82010-09-08 11:49:43 -0700429 virtual status_t registerInputChannel(const sp<InputChannel>& inputChannel, bool monitor);
Jeff Browne839a582010-04-22 18:58:52 -0700430 virtual status_t unregisterInputChannel(const sp<InputChannel>& inputChannel);
431
432private:
433 template <typename T>
434 struct Link {
435 T* next;
436 T* prev;
437 };
438
439 struct EventEntry : Link<EventEntry> {
440 enum {
441 TYPE_SENTINEL,
442 TYPE_CONFIGURATION_CHANGED,
443 TYPE_KEY,
444 TYPE_MOTION
445 };
446
447 int32_t refCount;
448 int32_t type;
449 nsecs_t eventTime;
Jeff Brown54bc2812010-06-15 01:31:58 -0700450
Jeff Brownf67c53e2010-07-28 15:48:59 -0700451 int32_t injectionResult; // initially INPUT_EVENT_INJECTION_PENDING
452 bool injectionIsAsync; // set to true if injection is not waiting for the result
453 int32_t injectorPid; // -1 if not injected
454 int32_t injectorUid; // -1 if not injected
Jeff Brown51d45a72010-06-17 20:52:56 -0700455
Jeff Brown54bc2812010-06-15 01:31:58 -0700456 bool dispatchInProgress; // initially false, set to true while dispatching
Jeff Brownf67c53e2010-07-28 15:48:59 -0700457 int32_t pendingSyncDispatches; // the number of synchronous dispatches in progress
Jeff Brown51d45a72010-06-17 20:52:56 -0700458
459 inline bool isInjected() { return injectorPid >= 0; }
Jeff Browna665ca82010-09-08 11:49:43 -0700460
461 void recycle();
Jeff Browne839a582010-04-22 18:58:52 -0700462 };
463
464 struct ConfigurationChangedEntry : EventEntry {
Jeff Browne839a582010-04-22 18:58:52 -0700465 };
466
467 struct KeyEntry : EventEntry {
468 int32_t deviceId;
Jeff Brown5c1ed842010-07-14 18:48:53 -0700469 int32_t source;
Jeff Browne839a582010-04-22 18:58:52 -0700470 uint32_t policyFlags;
471 int32_t action;
472 int32_t flags;
473 int32_t keyCode;
474 int32_t scanCode;
475 int32_t metaState;
476 int32_t repeatCount;
477 nsecs_t downTime;
Jeff Browna665ca82010-09-08 11:49:43 -0700478
479 bool syntheticRepeat; // set to true for synthetic key repeats
480
481 enum InterceptKeyResult {
482 INTERCEPT_KEY_RESULT_UNKNOWN,
483 INTERCEPT_KEY_RESULT_SKIP,
484 INTERCEPT_KEY_RESULT_CONTINUE,
485 };
486 InterceptKeyResult interceptKeyResult; // set based on the interception result
487
488 void recycle();
Jeff Browne839a582010-04-22 18:58:52 -0700489 };
490
491 struct MotionSample {
492 MotionSample* next;
493
494 nsecs_t eventTime;
495 PointerCoords pointerCoords[MAX_POINTERS];
496 };
497
498 struct MotionEntry : EventEntry {
499 int32_t deviceId;
Jeff Brown5c1ed842010-07-14 18:48:53 -0700500 int32_t source;
Jeff Browne839a582010-04-22 18:58:52 -0700501 uint32_t policyFlags;
502 int32_t action;
Jeff Brownaf30ff62010-09-01 17:01:00 -0700503 int32_t flags;
Jeff Browne839a582010-04-22 18:58:52 -0700504 int32_t metaState;
505 int32_t edgeFlags;
506 float xPrecision;
507 float yPrecision;
508 nsecs_t downTime;
509 uint32_t pointerCount;
510 int32_t pointerIds[MAX_POINTERS];
511
512 // Linked list of motion samples associated with this motion event.
513 MotionSample firstSample;
514 MotionSample* lastSample;
Jeff Brown542412c2010-08-18 15:51:08 -0700515
516 uint32_t countSamples() const;
Jeff Browne839a582010-04-22 18:58:52 -0700517 };
518
Jeff Brown54bc2812010-06-15 01:31:58 -0700519 // Tracks the progress of dispatching a particular event to a particular connection.
Jeff Browne839a582010-04-22 18:58:52 -0700520 struct DispatchEntry : Link<DispatchEntry> {
521 EventEntry* eventEntry; // the event to dispatch
522 int32_t targetFlags;
523 float xOffset;
524 float yOffset;
525 nsecs_t timeout;
526
527 // True if dispatch has started.
528 bool inProgress;
529
530 // For motion events:
531 // Pointer to the first motion sample to dispatch in this cycle.
532 // Usually NULL to indicate that the list of motion samples begins at
533 // MotionEntry::firstSample. Otherwise, some samples were dispatched in a previous
534 // cycle and this pointer indicates the location of the first remainining sample
535 // to dispatch during the current cycle.
536 MotionSample* headMotionSample;
537 // Pointer to a motion sample to dispatch in the next cycle if the dispatcher was
538 // unable to send all motion samples during this cycle. On the next cycle,
539 // headMotionSample will be initialized to tailMotionSample and tailMotionSample
540 // will be set to NULL.
541 MotionSample* tailMotionSample;
Jeff Brownf67c53e2010-07-28 15:48:59 -0700542
Jeff Browna665ca82010-09-08 11:49:43 -0700543 inline bool isSyncTarget() const {
Jeff Brownf67c53e2010-07-28 15:48:59 -0700544 return targetFlags & InputTarget::FLAG_SYNC;
545 }
Jeff Browna665ca82010-09-08 11:49:43 -0700546
547 inline void preemptSyncTarget() {
548 targetFlags &= ~ InputTarget::FLAG_SYNC;
549 }
Jeff Browne839a582010-04-22 18:58:52 -0700550 };
551
Jeff Brown54bc2812010-06-15 01:31:58 -0700552 // A command entry captures state and behavior for an action to be performed in the
553 // dispatch loop after the initial processing has taken place. It is essentially
554 // a kind of continuation used to postpone sensitive policy interactions to a point
555 // in the dispatch loop where it is safe to release the lock (generally after finishing
556 // the critical parts of the dispatch cycle).
557 //
558 // The special thing about commands is that they can voluntarily release and reacquire
559 // the dispatcher lock at will. Initially when the command starts running, the
560 // dispatcher lock is held. However, if the command needs to call into the policy to
561 // do some work, it can release the lock, do the work, then reacquire the lock again
562 // before returning.
563 //
564 // This mechanism is a bit clunky but it helps to preserve the invariant that the dispatch
565 // never calls into the policy while holding its lock.
566 //
567 // Commands are implicitly 'LockedInterruptible'.
568 struct CommandEntry;
569 typedef void (InputDispatcher::*Command)(CommandEntry* commandEntry);
570
Jeff Brown51d45a72010-06-17 20:52:56 -0700571 class Connection;
Jeff Brown54bc2812010-06-15 01:31:58 -0700572 struct CommandEntry : Link<CommandEntry> {
573 CommandEntry();
574 ~CommandEntry();
575
576 Command command;
577
578 // parameters for the command (usage varies by command)
Jeff Brown51d45a72010-06-17 20:52:56 -0700579 sp<Connection> connection;
Jeff Browna665ca82010-09-08 11:49:43 -0700580 nsecs_t eventTime;
581 KeyEntry* keyEntry;
582 sp<InputChannel> inputChannel;
583 sp<InputApplicationHandle> inputApplicationHandle;
584 int32_t windowType;
585 int32_t userActivityEventType;
Jeff Brown54bc2812010-06-15 01:31:58 -0700586 };
587
588 // Generic queue implementation.
Jeff Browne839a582010-04-22 18:58:52 -0700589 template <typename T>
590 struct Queue {
Jeff Browna665ca82010-09-08 11:49:43 -0700591 T headSentinel;
592 T tailSentinel;
Jeff Browne839a582010-04-22 18:58:52 -0700593
594 inline Queue() {
Jeff Browna665ca82010-09-08 11:49:43 -0700595 headSentinel.prev = NULL;
596 headSentinel.next = & tailSentinel;
597 tailSentinel.prev = & headSentinel;
598 tailSentinel.next = NULL;
Jeff Browne839a582010-04-22 18:58:52 -0700599 }
600
Jeff Browna665ca82010-09-08 11:49:43 -0700601 inline bool isEmpty() const {
602 return headSentinel.next == & tailSentinel;
Jeff Browne839a582010-04-22 18:58:52 -0700603 }
604
605 inline void enqueueAtTail(T* entry) {
Jeff Browna665ca82010-09-08 11:49:43 -0700606 T* last = tailSentinel.prev;
Jeff Browne839a582010-04-22 18:58:52 -0700607 last->next = entry;
608 entry->prev = last;
Jeff Browna665ca82010-09-08 11:49:43 -0700609 entry->next = & tailSentinel;
610 tailSentinel.prev = entry;
Jeff Browne839a582010-04-22 18:58:52 -0700611 }
612
613 inline void enqueueAtHead(T* entry) {
Jeff Browna665ca82010-09-08 11:49:43 -0700614 T* first = headSentinel.next;
615 headSentinel.next = entry;
616 entry->prev = & headSentinel;
Jeff Browne839a582010-04-22 18:58:52 -0700617 entry->next = first;
618 first->prev = entry;
619 }
620
621 inline void dequeue(T* entry) {
622 entry->prev->next = entry->next;
623 entry->next->prev = entry->prev;
624 }
625
626 inline T* dequeueAtHead() {
Jeff Browna665ca82010-09-08 11:49:43 -0700627 T* first = headSentinel.next;
Jeff Browne839a582010-04-22 18:58:52 -0700628 dequeue(first);
629 return first;
630 }
631 };
632
633 /* Allocates queue entries and performs reference counting as needed. */
634 class Allocator {
635 public:
636 Allocator();
637
Jeff Brown51d45a72010-06-17 20:52:56 -0700638 ConfigurationChangedEntry* obtainConfigurationChangedEntry(nsecs_t eventTime);
639 KeyEntry* obtainKeyEntry(nsecs_t eventTime,
Jeff Brown5c1ed842010-07-14 18:48:53 -0700640 int32_t deviceId, int32_t source, uint32_t policyFlags, int32_t action,
Jeff Brown51d45a72010-06-17 20:52:56 -0700641 int32_t flags, int32_t keyCode, int32_t scanCode, int32_t metaState,
642 int32_t repeatCount, nsecs_t downTime);
643 MotionEntry* obtainMotionEntry(nsecs_t eventTime,
Jeff Brown5c1ed842010-07-14 18:48:53 -0700644 int32_t deviceId, int32_t source, uint32_t policyFlags, int32_t action,
Jeff Brownaf30ff62010-09-01 17:01:00 -0700645 int32_t flags, int32_t metaState, int32_t edgeFlags,
646 float xPrecision, float yPrecision,
Jeff Brown51d45a72010-06-17 20:52:56 -0700647 nsecs_t downTime, uint32_t pointerCount,
648 const int32_t* pointerIds, const PointerCoords* pointerCoords);
Jeff Browna665ca82010-09-08 11:49:43 -0700649 DispatchEntry* obtainDispatchEntry(EventEntry* eventEntry,
650 int32_t targetFlags, float xOffset, float yOffset, nsecs_t timeout);
Jeff Brown54bc2812010-06-15 01:31:58 -0700651 CommandEntry* obtainCommandEntry(Command command);
Jeff Browne839a582010-04-22 18:58:52 -0700652
653 void releaseEventEntry(EventEntry* entry);
654 void releaseConfigurationChangedEntry(ConfigurationChangedEntry* entry);
655 void releaseKeyEntry(KeyEntry* entry);
656 void releaseMotionEntry(MotionEntry* entry);
657 void releaseDispatchEntry(DispatchEntry* entry);
Jeff Brown54bc2812010-06-15 01:31:58 -0700658 void releaseCommandEntry(CommandEntry* entry);
Jeff Browne839a582010-04-22 18:58:52 -0700659
660 void appendMotionSample(MotionEntry* motionEntry,
Jeff Brown51d45a72010-06-17 20:52:56 -0700661 nsecs_t eventTime, const PointerCoords* pointerCoords);
Jeff Browne839a582010-04-22 18:58:52 -0700662
663 private:
664 Pool<ConfigurationChangedEntry> mConfigurationChangeEntryPool;
665 Pool<KeyEntry> mKeyEntryPool;
666 Pool<MotionEntry> mMotionEntryPool;
667 Pool<MotionSample> mMotionSamplePool;
668 Pool<DispatchEntry> mDispatchEntryPool;
Jeff Brown54bc2812010-06-15 01:31:58 -0700669 Pool<CommandEntry> mCommandEntryPool;
Jeff Brown51d45a72010-06-17 20:52:56 -0700670
671 void initializeEventEntry(EventEntry* entry, int32_t type, nsecs_t eventTime);
Jeff Browne839a582010-04-22 18:58:52 -0700672 };
673
Jeff Browna665ca82010-09-08 11:49:43 -0700674 /* Tracks dispatched key and motion event state so that cancelation events can be
675 * synthesized when events are dropped. */
676 class InputState {
677 public:
678 // Specifies whether a given event will violate input state consistency.
679 enum Consistency {
680 // The event is consistent with the current input state.
681 CONSISTENT,
682 // The event is inconsistent with the current input state but applications
683 // will tolerate it. eg. Down followed by another down.
684 TOLERABLE,
685 // The event is inconsistent with the current input state and will probably
686 // cause applications to crash. eg. Up without prior down, move with
687 // unexpected number of pointers.
688 BROKEN
689 };
690
691 InputState();
692 ~InputState();
693
694 // Returns true if there is no state to be canceled.
695 bool isNeutral() const;
696
697 // Returns true if the input state believes it is out of sync.
698 bool isOutOfSync() const;
699
700 // Sets the input state to be out of sync if it is not neutral.
701 void setOutOfSync();
702
703 // Resets the input state out of sync flag.
704 void resetOutOfSync();
705
706 // Records tracking information for an event that has just been published.
707 // Returns whether the event is consistent with the current input state.
708 Consistency trackEvent(const EventEntry* entry);
709
710 // Records tracking information for a key event that has just been published.
711 // Returns whether the event is consistent with the current input state.
712 Consistency trackKey(const KeyEntry* entry);
713
714 // Records tracking information for a motion event that has just been published.
715 // Returns whether the event is consistent with the current input state.
716 Consistency trackMotion(const MotionEntry* entry);
717
718 // Synthesizes cancelation events for the current state.
719 void synthesizeCancelationEvents(Allocator* allocator,
720 Vector<EventEntry*>& outEvents) const;
721
722 // Clears the current state.
723 void clear();
724
725 private:
726 bool mIsOutOfSync;
727
728 struct KeyMemento {
729 int32_t deviceId;
730 int32_t source;
731 int32_t keyCode;
732 int32_t scanCode;
733 nsecs_t downTime;
734 };
735
736 struct MotionMemento {
737 int32_t deviceId;
738 int32_t source;
739 float xPrecision;
740 float yPrecision;
741 nsecs_t downTime;
742 uint32_t pointerCount;
743 int32_t pointerIds[MAX_POINTERS];
744 PointerCoords pointerCoords[MAX_POINTERS];
745
746 void setPointers(const MotionEntry* entry);
747 };
748
749 Vector<KeyMemento> mKeyMementos;
750 Vector<MotionMemento> mMotionMementos;
751 };
752
Jeff Browne839a582010-04-22 18:58:52 -0700753 /* Manages the dispatch state associated with a single input channel. */
754 class Connection : public RefBase {
755 protected:
756 virtual ~Connection();
757
758 public:
759 enum Status {
760 // Everything is peachy.
761 STATUS_NORMAL,
762 // An unrecoverable communication error has occurred.
763 STATUS_BROKEN,
764 // The client is not responding.
765 STATUS_NOT_RESPONDING,
766 // The input channel has been unregistered.
767 STATUS_ZOMBIE
768 };
769
770 Status status;
771 sp<InputChannel> inputChannel;
772 InputPublisher inputPublisher;
Jeff Browna665ca82010-09-08 11:49:43 -0700773 InputState inputState;
Jeff Browne839a582010-04-22 18:58:52 -0700774 Queue<DispatchEntry> outboundQueue;
775 nsecs_t nextTimeoutTime; // next timeout time (LONG_LONG_MAX if none)
776
777 nsecs_t lastEventTime; // the time when the event was originally captured
778 nsecs_t lastDispatchTime; // the time when the last event was dispatched
779 nsecs_t lastANRTime; // the time when the last ANR was recorded
780
781 explicit Connection(const sp<InputChannel>& inputChannel);
782
Jeff Brown54bc2812010-06-15 01:31:58 -0700783 inline const char* getInputChannelName() const { return inputChannel->getName().string(); }
784
785 const char* getStatusLabel() const;
Jeff Browne839a582010-04-22 18:58:52 -0700786
787 // Finds a DispatchEntry in the outbound queue associated with the specified event.
788 // Returns NULL if not found.
789 DispatchEntry* findQueuedDispatchEntryForEvent(const EventEntry* eventEntry) const;
790
791 // Determine whether this connection has a pending synchronous dispatch target.
792 // Since there can only ever be at most one such target at a time, if there is one,
793 // it must be at the tail because nothing else can be enqueued after it.
Jeff Browna665ca82010-09-08 11:49:43 -0700794 inline bool hasPendingSyncTarget() const {
795 return ! outboundQueue.isEmpty() && outboundQueue.tailSentinel.prev->isSyncTarget();
796 }
797
798 // Assuming there is a pending sync target, make it async.
799 inline void preemptSyncTarget() {
800 outboundQueue.tailSentinel.prev->preemptSyncTarget();
Jeff Browne839a582010-04-22 18:58:52 -0700801 }
802
803 // Gets the time since the current event was originally obtained from the input driver.
Jeff Browna665ca82010-09-08 11:49:43 -0700804 inline double getEventLatencyMillis(nsecs_t currentTime) const {
Jeff Browne839a582010-04-22 18:58:52 -0700805 return (currentTime - lastEventTime) / 1000000.0;
806 }
807
808 // Gets the time since the current event entered the outbound dispatch queue.
Jeff Browna665ca82010-09-08 11:49:43 -0700809 inline double getDispatchLatencyMillis(nsecs_t currentTime) const {
Jeff Browne839a582010-04-22 18:58:52 -0700810 return (currentTime - lastDispatchTime) / 1000000.0;
811 }
812
813 // Gets the time since the current event ANR was declared, if applicable.
Jeff Browna665ca82010-09-08 11:49:43 -0700814 inline double getANRLatencyMillis(nsecs_t currentTime) const {
Jeff Browne839a582010-04-22 18:58:52 -0700815 return (currentTime - lastANRTime) / 1000000.0;
816 }
817
818 status_t initialize();
Jeff Brown51d45a72010-06-17 20:52:56 -0700819
820 void setNextTimeoutTime(nsecs_t currentTime, nsecs_t timeout);
Jeff Browna665ca82010-09-08 11:49:43 -0700821 void resetTimeout(nsecs_t currentTime);
Jeff Browne839a582010-04-22 18:58:52 -0700822 };
823
Jeff Brown54bc2812010-06-15 01:31:58 -0700824 sp<InputDispatcherPolicyInterface> mPolicy;
Jeff Browne839a582010-04-22 18:58:52 -0700825
826 Mutex mLock;
827
Jeff Browne839a582010-04-22 18:58:52 -0700828 Allocator mAllocator;
Jeff Browne839a582010-04-22 18:58:52 -0700829 sp<PollLoop> mPollLoop;
830
Jeff Browna665ca82010-09-08 11:49:43 -0700831 EventEntry* mPendingEvent;
Jeff Brown54bc2812010-06-15 01:31:58 -0700832 Queue<EventEntry> mInboundQueue;
833 Queue<CommandEntry> mCommandQueue;
834
Jeff Browna665ca82010-09-08 11:49:43 -0700835 Vector<EventEntry*> mTempCancelationEvents;
836
837 void dispatchOnceInnerLocked(nsecs_t keyRepeatTimeout, nsecs_t keyRepeatDelay,
838 nsecs_t* nextWakeupTime);
839
840 // Enqueues an inbound event. Returns true if mPollLoop->wake() should be called.
841 bool enqueueInboundEventLocked(EventEntry* entry);
842
843 // App switch latency optimization.
844 nsecs_t mAppSwitchDueTime;
845
846 static bool isAppSwitchKey(int32_t keyCode);
847 bool isAppSwitchPendingLocked();
848 bool detectPendingAppSwitchLocked(KeyEntry* inboundKeyEntry);
849 void resetPendingAppSwitchLocked(bool handled);
850
Jeff Browne839a582010-04-22 18:58:52 -0700851 // All registered connections mapped by receive pipe file descriptor.
852 KeyedVector<int, sp<Connection> > mConnectionsByReceiveFd;
853
Jeff Brown0cacb872010-08-17 15:59:26 -0700854 ssize_t getConnectionIndex(const sp<InputChannel>& inputChannel);
855
Jeff Browne839a582010-04-22 18:58:52 -0700856 // Active connections are connections that have a non-empty outbound queue.
Jeff Brown51d45a72010-06-17 20:52:56 -0700857 // We don't use a ref-counted pointer here because we explicitly abort connections
858 // during unregistration which causes the connection's outbound queue to be cleared
859 // and the connection itself to be deactivated.
Jeff Browne839a582010-04-22 18:58:52 -0700860 Vector<Connection*> mActiveConnections;
861
Jeff Brown51d45a72010-06-17 20:52:56 -0700862 // List of connections that have timed out. Only used by dispatchOnce()
863 // We don't use a ref-counted pointer here because it is not possible for a connection
864 // to be unregistered while processing timed out connections since we hold the lock for
865 // the duration.
866 Vector<Connection*> mTimedOutConnections;
867
Jeff Browna665ca82010-09-08 11:49:43 -0700868 // Input channels that will receive a copy of all input events.
869 Vector<sp<InputChannel> > mMonitoringChannels;
Jeff Browne839a582010-04-22 18:58:52 -0700870
Jeff Browna665ca82010-09-08 11:49:43 -0700871 // Preallocated key event object used for policy inquiries.
872 KeyEvent mReusableKeyEvent;
Jeff Browne839a582010-04-22 18:58:52 -0700873
Jeff Brown51d45a72010-06-17 20:52:56 -0700874 // Event injection and synchronization.
875 Condition mInjectionResultAvailableCondition;
Jeff Browna665ca82010-09-08 11:49:43 -0700876 EventEntry* createEntryFromInjectedInputEventLocked(const InputEvent* event);
Jeff Brown51d45a72010-06-17 20:52:56 -0700877 void setInjectionResultLocked(EventEntry* entry, int32_t injectionResult);
878
Jeff Brownf67c53e2010-07-28 15:48:59 -0700879 Condition mInjectionSyncFinishedCondition;
880 void decrementPendingSyncDispatchesLocked(EventEntry* entry);
881
Jeff Brown542412c2010-08-18 15:51:08 -0700882 // Throttling state.
883 struct ThrottleState {
884 nsecs_t minTimeBetweenEvents;
885
886 nsecs_t lastEventTime;
887 int32_t lastDeviceId;
888 uint32_t lastSource;
889
890 uint32_t originalSampleCount; // only collected during debugging
891 } mThrottleState;
892
Jeff Browne839a582010-04-22 18:58:52 -0700893 // Key repeat tracking.
Jeff Browne839a582010-04-22 18:58:52 -0700894 struct KeyRepeatState {
895 KeyEntry* lastKeyEntry; // or null if no repeat
896 nsecs_t nextRepeatTime;
897 } mKeyRepeatState;
898
899 void resetKeyRepeatLocked();
Jeff Browna665ca82010-09-08 11:49:43 -0700900 KeyEntry* synthesizeKeyRepeatLocked(nsecs_t currentTime, nsecs_t keyRepeatTimeout);
Jeff Browne839a582010-04-22 18:58:52 -0700901
Jeff Brown54bc2812010-06-15 01:31:58 -0700902 // Deferred command processing.
903 bool runCommandsLockedInterruptible();
904 CommandEntry* postCommandLocked(Command command);
905
Jeff Browna665ca82010-09-08 11:49:43 -0700906 // Inbound event processing.
907 void drainInboundQueueLocked();
908 void releasePendingEventLocked(bool wasDropped);
909 void releaseInboundEventLocked(EventEntry* entry, bool wasDropped);
910 bool isEventFromReliableSourceLocked(EventEntry* entry);
Jeff Browne839a582010-04-22 18:58:52 -0700911
Jeff Browna665ca82010-09-08 11:49:43 -0700912 // Dispatch state.
913 bool mDispatchEnabled;
914 bool mDispatchFrozen;
915 Vector<InputWindow> mWindows;
916 Vector<InputWindow*> mWallpaperWindows;
917
918 // Focus tracking for keys, trackball, etc.
919 InputWindow* mFocusedWindow;
920
921 // Focus tracking for touch.
922 bool mTouchDown;
923 InputWindow* mTouchedWindow; // primary target for current down
924 bool mTouchedWindowIsObscured; // true if other windows may obscure the target
925 Vector<InputWindow*> mTouchedWallpaperWindows; // wallpaper targets
926 struct OutsideTarget {
927 InputWindow* window;
928 bool obscured;
929 };
930 Vector<OutsideTarget> mTempTouchedOutsideTargets; // temporary outside touch targets
931 Vector<sp<InputChannel> > mTempTouchedWallpaperChannels; // temporary wallpaper targets
932
933 // Focused application.
934 InputApplication* mFocusedApplication;
935 InputApplication mFocusedApplicationStorage; // preallocated storage for mFocusedApplication
936 void releaseFocusedApplicationLocked();
937
938 // Dispatch inbound events.
939 bool dispatchConfigurationChangedLocked(
940 nsecs_t currentTime, ConfigurationChangedEntry* entry);
941 bool dispatchKeyLocked(
942 nsecs_t currentTime, KeyEntry* entry, nsecs_t keyRepeatTimeout,
943 nsecs_t* nextWakeupTime);
944 bool dispatchMotionLocked(
945 nsecs_t currentTime, MotionEntry* entry,
946 nsecs_t* nextWakeupTime);
Jeff Brown54bc2812010-06-15 01:31:58 -0700947 void dispatchEventToCurrentInputTargetsLocked(
948 nsecs_t currentTime, EventEntry* entry, bool resumeWithAppendedMotionSample);
Jeff Browne839a582010-04-22 18:58:52 -0700949
Jeff Browna665ca82010-09-08 11:49:43 -0700950 void logOutboundKeyDetailsLocked(const char* prefix, const KeyEntry* entry);
951 void logOutboundMotionDetailsLocked(const char* prefix, const MotionEntry* entry);
952
953 // The input targets that were most recently identified for dispatch.
954 // If there is a synchronous event dispatch in progress, the current input targets will
955 // remain unchanged until the dispatch has completed or been aborted.
956 bool mCurrentInputTargetsValid; // false while targets are being recomputed
957 Vector<InputTarget> mCurrentInputTargets;
958 int32_t mCurrentInputWindowType;
959 sp<InputChannel> mCurrentInputChannel;
960
961 enum InputTargetWaitCause {
962 INPUT_TARGET_WAIT_CAUSE_NONE,
963 INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY,
964 INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY,
965 };
966
967 InputTargetWaitCause mInputTargetWaitCause;
968 nsecs_t mInputTargetWaitStartTime;
969 nsecs_t mInputTargetWaitTimeoutTime;
970 bool mInputTargetWaitTimeoutExpired;
971
972 // Finding targets for input events.
973 void startFindingTargetsLocked();
974 void finishFindingTargetsLocked(const InputWindow* window);
975 int32_t handleTargetsNotReadyLocked(nsecs_t currentTime, const EventEntry* entry,
976 const InputApplication* application, const InputWindow* window,
977 nsecs_t* nextWakeupTime);
978 void resumeAfterTargetsNotReadyTimeoutLocked(nsecs_t newTimeout);
979 nsecs_t getTimeSpentWaitingForApplicationWhileFindingTargetsLocked(nsecs_t currentTime);
980 void resetANRTimeoutsLocked();
981
982 int32_t findFocusedWindowLocked(nsecs_t currentTime, const EventEntry* entry,
983 nsecs_t* nextWakeupTime, InputWindow** outWindow);
984 int32_t findTouchedWindowLocked(nsecs_t currentTime, const MotionEntry* entry,
985 nsecs_t* nextWakeupTime, InputWindow** outWindow);
986
987 void addWindowTargetLocked(const InputWindow* window, int32_t targetFlags,
988 nsecs_t timeSpentWaitingForApplication);
989 void addMonitoringTargetsLocked();
990 void pokeUserActivityLocked(nsecs_t eventTime, int32_t windowType, int32_t eventType);
991 bool checkInjectionPermission(const InputWindow* window,
992 int32_t injectorPid, int32_t injectorUid);
993 bool isWindowObscuredLocked(const InputWindow* window);
994 void releaseTouchedWindowLocked();
995
Jeff Browne839a582010-04-22 18:58:52 -0700996 // Manage the dispatch cycle for a single connection.
Jeff Brown51d45a72010-06-17 20:52:56 -0700997 // These methods are deliberately not Interruptible because doing all of the work
998 // with the mutex held makes it easier to ensure that connection invariants are maintained.
999 // If needed, the methods post commands to run later once the critical bits are done.
1000 void prepareDispatchCycleLocked(nsecs_t currentTime, const sp<Connection>& connection,
Jeff Browne839a582010-04-22 18:58:52 -07001001 EventEntry* eventEntry, const InputTarget* inputTarget,
1002 bool resumeWithAppendedMotionSample);
Jeff Browna665ca82010-09-08 11:49:43 -07001003 void startDispatchCycleLocked(nsecs_t currentTime, const sp<Connection>& connection,
1004 nsecs_t timeSpentWaitingForApplication);
Jeff Brown51d45a72010-06-17 20:52:56 -07001005 void finishDispatchCycleLocked(nsecs_t currentTime, const sp<Connection>& connection);
Jeff Browna665ca82010-09-08 11:49:43 -07001006 void startNextDispatchCycleLocked(nsecs_t currentTime, const sp<Connection>& connection);
Jeff Brown51d45a72010-06-17 20:52:56 -07001007 void timeoutDispatchCycleLocked(nsecs_t currentTime, const sp<Connection>& connection);
1008 void resumeAfterTimeoutDispatchCycleLocked(nsecs_t currentTime,
1009 const sp<Connection>& connection, nsecs_t newTimeout);
1010 void abortDispatchCycleLocked(nsecs_t currentTime, const sp<Connection>& connection,
Jeff Browne839a582010-04-22 18:58:52 -07001011 bool broken);
Jeff Browna665ca82010-09-08 11:49:43 -07001012 void drainOutboundQueueLocked(Connection* connection, DispatchEntry* firstDispatchEntryToDrain);
Jeff Browne839a582010-04-22 18:58:52 -07001013 static bool handleReceiveCallback(int receiveFd, int events, void* data);
1014
Jeff Browna665ca82010-09-08 11:49:43 -07001015 // Preempting input dispatch.
1016 bool preemptInputDispatchInnerLocked();
1017
1018 // Dump state.
1019 void dumpDispatchStateLocked(String8& dump);
1020 void logDispatchStateLocked();
1021
Jeff Browne839a582010-04-22 18:58:52 -07001022 // Add or remove a connection to the mActiveConnections vector.
1023 void activateConnectionLocked(Connection* connection);
1024 void deactivateConnectionLocked(Connection* connection);
1025
1026 // Interesting events that we might like to log or tell the framework about.
Jeff Brown54bc2812010-06-15 01:31:58 -07001027 void onDispatchCycleStartedLocked(
Jeff Brown51d45a72010-06-17 20:52:56 -07001028 nsecs_t currentTime, const sp<Connection>& connection);
Jeff Brown54bc2812010-06-15 01:31:58 -07001029 void onDispatchCycleFinishedLocked(
Jeff Brown51d45a72010-06-17 20:52:56 -07001030 nsecs_t currentTime, const sp<Connection>& connection, bool recoveredFromANR);
Jeff Brown54bc2812010-06-15 01:31:58 -07001031 void onDispatchCycleANRLocked(
Jeff Brown51d45a72010-06-17 20:52:56 -07001032 nsecs_t currentTime, const sp<Connection>& connection);
Jeff Brown54bc2812010-06-15 01:31:58 -07001033 void onDispatchCycleBrokenLocked(
Jeff Brown51d45a72010-06-17 20:52:56 -07001034 nsecs_t currentTime, const sp<Connection>& connection);
Jeff Brown54bc2812010-06-15 01:31:58 -07001035
Jeff Brown51d45a72010-06-17 20:52:56 -07001036 // Outbound policy interactions.
Jeff Browna665ca82010-09-08 11:49:43 -07001037 void doNotifyConfigurationChangedInterruptible(CommandEntry* commandEntry);
Jeff Brown54bc2812010-06-15 01:31:58 -07001038 void doNotifyInputChannelBrokenLockedInterruptible(CommandEntry* commandEntry);
1039 void doNotifyInputChannelANRLockedInterruptible(CommandEntry* commandEntry);
1040 void doNotifyInputChannelRecoveredFromANRLockedInterruptible(CommandEntry* commandEntry);
Jeff Browna665ca82010-09-08 11:49:43 -07001041 void doInterceptKeyBeforeDispatchingLockedInterruptible(CommandEntry* commandEntry);
1042 void doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry);
1043 void doTargetsNotReadyTimeoutLockedInterruptible(CommandEntry* commandEntry);
Jeff Browne839a582010-04-22 18:58:52 -07001044};
1045
1046/* Enqueues and dispatches input events, endlessly. */
1047class InputDispatcherThread : public Thread {
1048public:
1049 explicit InputDispatcherThread(const sp<InputDispatcherInterface>& dispatcher);
1050 ~InputDispatcherThread();
1051
1052private:
1053 virtual bool threadLoop();
1054
1055 sp<InputDispatcherInterface> mDispatcher;
1056};
1057
1058} // namespace android
1059
Jeff Browna665ca82010-09-08 11:49:43 -07001060#endif // _UI_INPUT_DISPATCHER_H