blob: 80a20c99f5151523c273ac9bd32682659a320fbb [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>
33
34
35namespace android {
36
Jeff Brown54bc2812010-06-15 01:31:58 -070037/*
38 * An input target specifies how an input event is to be dispatched to a particular window
39 * including the window's input channel, control flags, a timeout, and an X / Y offset to
40 * be added to input event coordinates to compensate for the absolute position of the
41 * window area.
42 */
43struct InputTarget {
44 enum {
45 /* This flag indicates that subsequent event delivery should be held until the
46 * current event is delivered to this target or a timeout occurs. */
47 FLAG_SYNC = 0x01,
48
49 /* This flag indicates that a MotionEvent with ACTION_DOWN falls outside of the area of
50 * this target and so should instead be delivered as an ACTION_OUTSIDE to this target. */
51 FLAG_OUTSIDE = 0x02,
52
53 /* This flag indicates that a KeyEvent or MotionEvent is being canceled.
54 * In the case of a key event, it should be delivered with KeyEvent.FLAG_CANCELED set.
55 * In the case of a motion event, it should be delivered as MotionEvent.ACTION_CANCEL. */
56 FLAG_CANCEL = 0x04
57 };
58
59 // The input channel to be targeted.
60 sp<InputChannel> inputChannel;
61
62 // Flags for the input target.
63 int32_t flags;
64
65 // The timeout for event delivery to this target in nanoseconds. Or -1 if none.
66 nsecs_t timeout;
67
68 // The x and y offset to add to a MotionEvent as it is delivered.
69 // (ignored for KeyEvents)
70 float xOffset, yOffset;
71};
72
73/*
74 * Input dispatcher policy interface.
75 *
76 * The input reader policy is used by the input reader to interact with the Window Manager
77 * and other system components.
78 *
79 * The actual implementation is partially supported by callbacks into the DVM
80 * via JNI. This interface is also mocked in the unit tests.
81 */
82class InputDispatcherPolicyInterface : public virtual RefBase {
83protected:
84 InputDispatcherPolicyInterface() { }
85 virtual ~InputDispatcherPolicyInterface() { }
86
87public:
88 /* Notifies the system that a configuration change has occurred. */
89 virtual void notifyConfigurationChanged(nsecs_t when) = 0;
90
91 /* Notifies the system that an input channel is unrecoverably broken. */
92 virtual void notifyInputChannelBroken(const sp<InputChannel>& inputChannel) = 0;
93
94 /* Notifies the system that an input channel is not responding. */
95 virtual void notifyInputChannelANR(const sp<InputChannel>& inputChannel) = 0;
96
97 /* Notifies the system that an input channel recovered from ANR. */
98 virtual void notifyInputChannelRecoveredFromANR(const sp<InputChannel>& inputChannel) = 0;
99
100 /* Gets the key repeat timeout or -1 if automatic key repeating is disabled. */
101 virtual nsecs_t getKeyRepeatTimeout() = 0;
102
103 /* Gets the input targets for a key event. */
104 virtual void getKeyEventTargets(KeyEvent* keyEvent, uint32_t policyFlags,
105 Vector<InputTarget>& outTargets) = 0;
106
107 /* Gets the input targets for a motion event. */
108 virtual void getMotionEventTargets(MotionEvent* motionEvent, uint32_t policyFlags,
109 Vector<InputTarget>& outTargets) = 0;
110};
111
112
Jeff Browne839a582010-04-22 18:58:52 -0700113/* Notifies the system about input events generated by the input reader.
114 * The dispatcher is expected to be mostly asynchronous. */
115class InputDispatcherInterface : public virtual RefBase {
116protected:
117 InputDispatcherInterface() { }
118 virtual ~InputDispatcherInterface() { }
119
120public:
121 /* Runs a single iteration of the dispatch loop.
122 * Nominally processes one queued event, a timeout, or a response from an input consumer.
123 *
124 * This method should only be called on the input dispatcher thread.
125 */
126 virtual void dispatchOnce() = 0;
127
128 /* Notifies the dispatcher about new events.
Jeff Browne839a582010-04-22 18:58:52 -0700129 *
130 * These methods should only be called on the input reader thread.
131 */
Jeff Brown54bc2812010-06-15 01:31:58 -0700132 virtual void notifyConfigurationChanged(nsecs_t eventTime) = 0;
Jeff Browne839a582010-04-22 18:58:52 -0700133 virtual void notifyAppSwitchComing(nsecs_t eventTime) = 0;
134 virtual void notifyKey(nsecs_t eventTime, int32_t deviceId, int32_t nature,
135 uint32_t policyFlags, int32_t action, int32_t flags, int32_t keyCode,
136 int32_t scanCode, int32_t metaState, nsecs_t downTime) = 0;
137 virtual void notifyMotion(nsecs_t eventTime, int32_t deviceId, int32_t nature,
138 uint32_t policyFlags, int32_t action, int32_t metaState, int32_t edgeFlags,
139 uint32_t pointerCount, const int32_t* pointerIds, const PointerCoords* pointerCoords,
140 float xPrecision, float yPrecision, nsecs_t downTime) = 0;
141
142 /* Registers or unregister input channels that may be used as targets for input events.
143 *
144 * These methods may be called on any thread (usually by the input manager).
145 */
146 virtual status_t registerInputChannel(const sp<InputChannel>& inputChannel) = 0;
147 virtual status_t unregisterInputChannel(const sp<InputChannel>& inputChannel) = 0;
148};
149
Jeff Brown54bc2812010-06-15 01:31:58 -0700150/* Dispatches events to input targets. Some functions of the input dispatcher, such as
151 * identifying input targets, are controlled by a separate policy object.
152 *
153 * IMPORTANT INVARIANT:
154 * Because the policy can potentially block or cause re-entrance into the input dispatcher,
155 * the input dispatcher never calls into the policy while holding its internal locks.
156 * The implementation is also carefully designed to recover from scenarios such as an
157 * input channel becoming unregistered while identifying input targets or processing timeouts.
158 *
159 * Methods marked 'Locked' must be called with the lock acquired.
160 *
161 * Methods marked 'LockedInterruptible' must be called with the lock acquired but
162 * may during the course of their execution release the lock, call into the policy, and
163 * then reacquire the lock. The caller is responsible for recovering gracefully.
164 *
165 * A 'LockedInterruptible' method may called a 'Locked' method, but NOT vice-versa.
166 */
Jeff Browne839a582010-04-22 18:58:52 -0700167class InputDispatcher : public InputDispatcherInterface {
168protected:
169 virtual ~InputDispatcher();
170
171public:
Jeff Brown54bc2812010-06-15 01:31:58 -0700172 explicit InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy);
Jeff Browne839a582010-04-22 18:58:52 -0700173
174 virtual void dispatchOnce();
175
Jeff Brown54bc2812010-06-15 01:31:58 -0700176 virtual void notifyConfigurationChanged(nsecs_t eventTime);
Jeff Browne839a582010-04-22 18:58:52 -0700177 virtual void notifyAppSwitchComing(nsecs_t eventTime);
178 virtual void notifyKey(nsecs_t eventTime, int32_t deviceId, int32_t nature,
179 uint32_t policyFlags, int32_t action, int32_t flags, int32_t keyCode,
180 int32_t scanCode, int32_t metaState, nsecs_t downTime);
181 virtual void notifyMotion(nsecs_t eventTime, int32_t deviceId, int32_t nature,
182 uint32_t policyFlags, int32_t action, int32_t metaState, int32_t edgeFlags,
183 uint32_t pointerCount, const int32_t* pointerIds, const PointerCoords* pointerCoords,
184 float xPrecision, float yPrecision, nsecs_t downTime);
185
186 virtual status_t registerInputChannel(const sp<InputChannel>& inputChannel);
187 virtual status_t unregisterInputChannel(const sp<InputChannel>& inputChannel);
188
189private:
190 template <typename T>
191 struct Link {
192 T* next;
193 T* prev;
194 };
195
196 struct EventEntry : Link<EventEntry> {
197 enum {
198 TYPE_SENTINEL,
199 TYPE_CONFIGURATION_CHANGED,
200 TYPE_KEY,
201 TYPE_MOTION
202 };
203
204 int32_t refCount;
205 int32_t type;
206 nsecs_t eventTime;
Jeff Brown54bc2812010-06-15 01:31:58 -0700207
208 bool dispatchInProgress; // initially false, set to true while dispatching
Jeff Browne839a582010-04-22 18:58:52 -0700209 };
210
211 struct ConfigurationChangedEntry : EventEntry {
Jeff Browne839a582010-04-22 18:58:52 -0700212 };
213
214 struct KeyEntry : EventEntry {
215 int32_t deviceId;
216 int32_t nature;
217 uint32_t policyFlags;
218 int32_t action;
219 int32_t flags;
220 int32_t keyCode;
221 int32_t scanCode;
222 int32_t metaState;
223 int32_t repeatCount;
224 nsecs_t downTime;
225 };
226
227 struct MotionSample {
228 MotionSample* next;
229
230 nsecs_t eventTime;
231 PointerCoords pointerCoords[MAX_POINTERS];
232 };
233
234 struct MotionEntry : EventEntry {
235 int32_t deviceId;
236 int32_t nature;
237 uint32_t policyFlags;
238 int32_t action;
239 int32_t metaState;
240 int32_t edgeFlags;
241 float xPrecision;
242 float yPrecision;
243 nsecs_t downTime;
244 uint32_t pointerCount;
245 int32_t pointerIds[MAX_POINTERS];
246
247 // Linked list of motion samples associated with this motion event.
248 MotionSample firstSample;
249 MotionSample* lastSample;
250 };
251
Jeff Brown54bc2812010-06-15 01:31:58 -0700252 // Tracks the progress of dispatching a particular event to a particular connection.
Jeff Browne839a582010-04-22 18:58:52 -0700253 struct DispatchEntry : Link<DispatchEntry> {
254 EventEntry* eventEntry; // the event to dispatch
255 int32_t targetFlags;
256 float xOffset;
257 float yOffset;
258 nsecs_t timeout;
259
260 // True if dispatch has started.
261 bool inProgress;
262
263 // For motion events:
264 // Pointer to the first motion sample to dispatch in this cycle.
265 // Usually NULL to indicate that the list of motion samples begins at
266 // MotionEntry::firstSample. Otherwise, some samples were dispatched in a previous
267 // cycle and this pointer indicates the location of the first remainining sample
268 // to dispatch during the current cycle.
269 MotionSample* headMotionSample;
270 // Pointer to a motion sample to dispatch in the next cycle if the dispatcher was
271 // unable to send all motion samples during this cycle. On the next cycle,
272 // headMotionSample will be initialized to tailMotionSample and tailMotionSample
273 // will be set to NULL.
274 MotionSample* tailMotionSample;
275 };
276
Jeff Brown54bc2812010-06-15 01:31:58 -0700277 // A command entry captures state and behavior for an action to be performed in the
278 // dispatch loop after the initial processing has taken place. It is essentially
279 // a kind of continuation used to postpone sensitive policy interactions to a point
280 // in the dispatch loop where it is safe to release the lock (generally after finishing
281 // the critical parts of the dispatch cycle).
282 //
283 // The special thing about commands is that they can voluntarily release and reacquire
284 // the dispatcher lock at will. Initially when the command starts running, the
285 // dispatcher lock is held. However, if the command needs to call into the policy to
286 // do some work, it can release the lock, do the work, then reacquire the lock again
287 // before returning.
288 //
289 // This mechanism is a bit clunky but it helps to preserve the invariant that the dispatch
290 // never calls into the policy while holding its lock.
291 //
292 // Commands are implicitly 'LockedInterruptible'.
293 struct CommandEntry;
294 typedef void (InputDispatcher::*Command)(CommandEntry* commandEntry);
295
296 struct CommandEntry : Link<CommandEntry> {
297 CommandEntry();
298 ~CommandEntry();
299
300 Command command;
301
302 // parameters for the command (usage varies by command)
303 sp<InputChannel> inputChannel;
304 };
305
306 // Generic queue implementation.
Jeff Browne839a582010-04-22 18:58:52 -0700307 template <typename T>
308 struct Queue {
309 T head;
310 T tail;
311
312 inline Queue() {
313 head.prev = NULL;
314 head.next = & tail;
315 tail.prev = & head;
316 tail.next = NULL;
317 }
318
319 inline bool isEmpty() {
320 return head.next == & tail;
321 }
322
323 inline void enqueueAtTail(T* entry) {
324 T* last = tail.prev;
325 last->next = entry;
326 entry->prev = last;
327 entry->next = & tail;
328 tail.prev = entry;
329 }
330
331 inline void enqueueAtHead(T* entry) {
332 T* first = head.next;
333 head.next = entry;
334 entry->prev = & head;
335 entry->next = first;
336 first->prev = entry;
337 }
338
339 inline void dequeue(T* entry) {
340 entry->prev->next = entry->next;
341 entry->next->prev = entry->prev;
342 }
343
344 inline T* dequeueAtHead() {
345 T* first = head.next;
346 dequeue(first);
347 return first;
348 }
349 };
350
351 /* Allocates queue entries and performs reference counting as needed. */
352 class Allocator {
353 public:
354 Allocator();
355
356 ConfigurationChangedEntry* obtainConfigurationChangedEntry();
357 KeyEntry* obtainKeyEntry();
358 MotionEntry* obtainMotionEntry();
359 DispatchEntry* obtainDispatchEntry(EventEntry* eventEntry);
Jeff Brown54bc2812010-06-15 01:31:58 -0700360 CommandEntry* obtainCommandEntry(Command command);
Jeff Browne839a582010-04-22 18:58:52 -0700361
362 void releaseEventEntry(EventEntry* entry);
363 void releaseConfigurationChangedEntry(ConfigurationChangedEntry* entry);
364 void releaseKeyEntry(KeyEntry* entry);
365 void releaseMotionEntry(MotionEntry* entry);
366 void releaseDispatchEntry(DispatchEntry* entry);
Jeff Brown54bc2812010-06-15 01:31:58 -0700367 void releaseCommandEntry(CommandEntry* entry);
Jeff Browne839a582010-04-22 18:58:52 -0700368
369 void appendMotionSample(MotionEntry* motionEntry,
370 nsecs_t eventTime, int32_t pointerCount, const PointerCoords* pointerCoords);
Jeff Browne839a582010-04-22 18:58:52 -0700371
372 private:
373 Pool<ConfigurationChangedEntry> mConfigurationChangeEntryPool;
374 Pool<KeyEntry> mKeyEntryPool;
375 Pool<MotionEntry> mMotionEntryPool;
376 Pool<MotionSample> mMotionSamplePool;
377 Pool<DispatchEntry> mDispatchEntryPool;
Jeff Brown54bc2812010-06-15 01:31:58 -0700378 Pool<CommandEntry> mCommandEntryPool;
Jeff Browne839a582010-04-22 18:58:52 -0700379 };
380
381 /* Manages the dispatch state associated with a single input channel. */
382 class Connection : public RefBase {
383 protected:
384 virtual ~Connection();
385
386 public:
387 enum Status {
388 // Everything is peachy.
389 STATUS_NORMAL,
390 // An unrecoverable communication error has occurred.
391 STATUS_BROKEN,
392 // The client is not responding.
393 STATUS_NOT_RESPONDING,
394 // The input channel has been unregistered.
395 STATUS_ZOMBIE
396 };
397
398 Status status;
399 sp<InputChannel> inputChannel;
400 InputPublisher inputPublisher;
401 Queue<DispatchEntry> outboundQueue;
402 nsecs_t nextTimeoutTime; // next timeout time (LONG_LONG_MAX if none)
403
404 nsecs_t lastEventTime; // the time when the event was originally captured
405 nsecs_t lastDispatchTime; // the time when the last event was dispatched
406 nsecs_t lastANRTime; // the time when the last ANR was recorded
407
408 explicit Connection(const sp<InputChannel>& inputChannel);
409
Jeff Brown54bc2812010-06-15 01:31:58 -0700410 inline const char* getInputChannelName() const { return inputChannel->getName().string(); }
411
412 const char* getStatusLabel() const;
Jeff Browne839a582010-04-22 18:58:52 -0700413
414 // Finds a DispatchEntry in the outbound queue associated with the specified event.
415 // Returns NULL if not found.
416 DispatchEntry* findQueuedDispatchEntryForEvent(const EventEntry* eventEntry) const;
417
418 // Determine whether this connection has a pending synchronous dispatch target.
419 // Since there can only ever be at most one such target at a time, if there is one,
420 // it must be at the tail because nothing else can be enqueued after it.
421 inline bool hasPendingSyncTarget() {
422 return ! outboundQueue.isEmpty()
423 && (outboundQueue.tail.prev->targetFlags & InputTarget::FLAG_SYNC);
424 }
425
426 // Gets the time since the current event was originally obtained from the input driver.
427 inline double getEventLatencyMillis(nsecs_t currentTime) {
428 return (currentTime - lastEventTime) / 1000000.0;
429 }
430
431 // Gets the time since the current event entered the outbound dispatch queue.
432 inline double getDispatchLatencyMillis(nsecs_t currentTime) {
433 return (currentTime - lastDispatchTime) / 1000000.0;
434 }
435
436 // Gets the time since the current event ANR was declared, if applicable.
437 inline double getANRLatencyMillis(nsecs_t currentTime) {
438 return (currentTime - lastANRTime) / 1000000.0;
439 }
440
441 status_t initialize();
442 };
443
Jeff Brown54bc2812010-06-15 01:31:58 -0700444 sp<InputDispatcherPolicyInterface> mPolicy;
Jeff Browne839a582010-04-22 18:58:52 -0700445
446 Mutex mLock;
447
Jeff Browne839a582010-04-22 18:58:52 -0700448 Allocator mAllocator;
Jeff Browne839a582010-04-22 18:58:52 -0700449 sp<PollLoop> mPollLoop;
450
Jeff Brown54bc2812010-06-15 01:31:58 -0700451 Queue<EventEntry> mInboundQueue;
452 Queue<CommandEntry> mCommandQueue;
453
Jeff Browne839a582010-04-22 18:58:52 -0700454 // All registered connections mapped by receive pipe file descriptor.
455 KeyedVector<int, sp<Connection> > mConnectionsByReceiveFd;
456
457 // Active connections are connections that have a non-empty outbound queue.
458 Vector<Connection*> mActiveConnections;
459
Jeff Brown54bc2812010-06-15 01:31:58 -0700460 // Preallocated key and motion event objects used only to ask the input dispatcher policy
Jeff Browne839a582010-04-22 18:58:52 -0700461 // for the targets of an event that is to be dispatched.
462 KeyEvent mReusableKeyEvent;
463 MotionEvent mReusableMotionEvent;
464
465 // The input targets that were most recently identified for dispatch.
466 // If there is a synchronous event dispatch in progress, the current input targets will
467 // remain unchanged until the dispatch has completed or been aborted.
468 Vector<InputTarget> mCurrentInputTargets;
Jeff Brown54bc2812010-06-15 01:31:58 -0700469 bool mCurrentInputTargetsValid; // false while targets are being recomputed
Jeff Browne839a582010-04-22 18:58:52 -0700470
471 // Key repeat tracking.
472 // XXX Move this up to the input reader instead.
473 struct KeyRepeatState {
474 KeyEntry* lastKeyEntry; // or null if no repeat
475 nsecs_t nextRepeatTime;
476 } mKeyRepeatState;
477
478 void resetKeyRepeatLocked();
479
Jeff Brown54bc2812010-06-15 01:31:58 -0700480 // Deferred command processing.
481 bool runCommandsLockedInterruptible();
482 CommandEntry* postCommandLocked(Command command);
483
Jeff Browne839a582010-04-22 18:58:52 -0700484 // Process events that have just been dequeued from the head of the input queue.
Jeff Brown54bc2812010-06-15 01:31:58 -0700485 void processConfigurationChangedLockedInterruptible(
486 nsecs_t currentTime, ConfigurationChangedEntry* entry);
487 void processKeyLockedInterruptible(
488 nsecs_t currentTime, KeyEntry* entry, nsecs_t keyRepeatTimeout);
489 void processKeyRepeatLockedInterruptible(
490 nsecs_t currentTime, nsecs_t keyRepeatTimeout);
491 void processMotionLockedInterruptible(
492 nsecs_t currentTime, MotionEntry* entry);
Jeff Browne839a582010-04-22 18:58:52 -0700493
494 // Identify input targets for an event and dispatch to them.
Jeff Brown54bc2812010-06-15 01:31:58 -0700495 void identifyInputTargetsAndDispatchKeyLockedInterruptible(
496 nsecs_t currentTime, KeyEntry* entry);
497 void identifyInputTargetsAndDispatchMotionLockedInterruptible(
498 nsecs_t currentTime, MotionEntry* entry);
499 void dispatchEventToCurrentInputTargetsLocked(
500 nsecs_t currentTime, EventEntry* entry, bool resumeWithAppendedMotionSample);
Jeff Browne839a582010-04-22 18:58:52 -0700501
502 // Manage the dispatch cycle for a single connection.
503 void prepareDispatchCycleLocked(nsecs_t currentTime, Connection* connection,
504 EventEntry* eventEntry, const InputTarget* inputTarget,
505 bool resumeWithAppendedMotionSample);
506 void startDispatchCycleLocked(nsecs_t currentTime, Connection* connection);
507 void finishDispatchCycleLocked(nsecs_t currentTime, Connection* connection);
508 bool timeoutDispatchCycleLocked(nsecs_t currentTime, Connection* connection);
509 bool abortDispatchCycleLocked(nsecs_t currentTime, Connection* connection,
510 bool broken);
511 static bool handleReceiveCallback(int receiveFd, int events, void* data);
512
513 // Add or remove a connection to the mActiveConnections vector.
514 void activateConnectionLocked(Connection* connection);
515 void deactivateConnectionLocked(Connection* connection);
516
Jeff Brown54bc2812010-06-15 01:31:58 -0700517 // Outbound policy interactions.
518 void doNotifyConfigurationChangedLockedInterruptible(CommandEntry* commandEntry);
519
Jeff Browne839a582010-04-22 18:58:52 -0700520 // Interesting events that we might like to log or tell the framework about.
Jeff Brown54bc2812010-06-15 01:31:58 -0700521 void onDispatchCycleStartedLocked(
522 nsecs_t currentTime, Connection* connection);
523 void onDispatchCycleFinishedLocked(
524 nsecs_t currentTime, Connection* connection, bool recoveredFromANR);
525 void onDispatchCycleANRLocked(
526 nsecs_t currentTime, Connection* connection);
527 void onDispatchCycleBrokenLocked(
528 nsecs_t currentTime, Connection* connection);
529
530 void doNotifyInputChannelBrokenLockedInterruptible(CommandEntry* commandEntry);
531 void doNotifyInputChannelANRLockedInterruptible(CommandEntry* commandEntry);
532 void doNotifyInputChannelRecoveredFromANRLockedInterruptible(CommandEntry* commandEntry);
Jeff Browne839a582010-04-22 18:58:52 -0700533};
534
535/* Enqueues and dispatches input events, endlessly. */
536class InputDispatcherThread : public Thread {
537public:
538 explicit InputDispatcherThread(const sp<InputDispatcherInterface>& dispatcher);
539 ~InputDispatcherThread();
540
541private:
542 virtual bool threadLoop();
543
544 sp<InputDispatcherInterface> mDispatcher;
545};
546
547} // namespace android
548
549#endif // _UI_INPUT_DISPATCHER_PRIV_H