InputDispatcher.h revision 8134681b25dfff814ffeaad8ff70e84316c1869f
1/*
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>
21#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/Looper.h>
29#include <utils/Pool.h>
30#include <utils/BitSet.h>
31
32#include <stddef.h>
33#include <unistd.h>
34#include <limits.h>
35
36#include "InputWindow.h"
37#include "InputApplication.h"
38
39
40namespace android {
41
42/*
43 * Constants used to report the outcome of input event injection.
44 */
45enum {
46    /* (INTERNAL USE ONLY) Specifies that injection is pending and its outcome is unknown. */
47    INPUT_EVENT_INJECTION_PENDING = -1,
48
49    /* Injection succeeded. */
50    INPUT_EVENT_INJECTION_SUCCEEDED = 0,
51
52    /* Injection failed because the injector did not have permission to inject
53     * into the application with input focus. */
54    INPUT_EVENT_INJECTION_PERMISSION_DENIED = 1,
55
56    /* Injection failed because there were no available input targets. */
57    INPUT_EVENT_INJECTION_FAILED = 2,
58
59    /* Injection failed due to a timeout. */
60    INPUT_EVENT_INJECTION_TIMED_OUT = 3
61};
62
63/*
64 * Constants used to determine the input event injection synchronization mode.
65 */
66enum {
67    /* Injection is asynchronous and is assumed always to be successful. */
68    INPUT_EVENT_INJECTION_SYNC_NONE = 0,
69
70    /* Waits for previous events to be dispatched so that the input dispatcher can determine
71     * whether input event injection willbe permitted based on the current input focus.
72     * Does not wait for the input event to finish processing. */
73    INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_RESULT = 1,
74
75    /* Waits for the input event to be completely processed. */
76    INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED = 2,
77};
78
79
80/*
81 * An input target specifies how an input event is to be dispatched to a particular window
82 * including the window's input channel, control flags, a timeout, and an X / Y offset to
83 * be added to input event coordinates to compensate for the absolute position of the
84 * window area.
85 */
86struct InputTarget {
87    enum {
88        /* This flag indicates that the event is being delivered to a foreground application. */
89        FLAG_FOREGROUND = 1 << 0,
90
91        /* This flag indicates that the target of a MotionEvent is partly or wholly
92         * obscured by another visible window above it.  The motion event should be
93         * delivered with flag AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED. */
94        FLAG_WINDOW_IS_OBSCURED = 1 << 1,
95
96        /* This flag indicates that a motion event is being split across multiple windows. */
97        FLAG_SPLIT = 1 << 2,
98
99        /* This flag indicates that the pointer coordinates dispatched to the application
100         * will be zeroed out to avoid revealing information to an application. This is
101         * used in conjunction with FLAG_DISPATCH_AS_OUTSIDE to prevent apps not sharing
102         * the same UID from watching all touches. */
103        FLAG_ZERO_COORDS = 1 << 3,
104
105        /* This flag indicates that the event should be sent as is.
106         * Should always be set unless the event is to be transmuted. */
107        FLAG_DISPATCH_AS_IS = 1 << 8,
108
109        /* This flag indicates that a MotionEvent with AMOTION_EVENT_ACTION_DOWN falls outside
110         * of the area of this target and so should instead be delivered as an
111         * AMOTION_EVENT_ACTION_OUTSIDE to this target. */
112        FLAG_DISPATCH_AS_OUTSIDE = 1 << 9,
113
114        /* This flag indicates that a hover sequence is starting in the given window.
115         * The event is transmuted into ACTION_HOVER_ENTER. */
116        FLAG_DISPATCH_AS_HOVER_ENTER = 1 << 10,
117
118        /* This flag indicates that a hover event happened outside of a window which handled
119         * previous hover events, signifying the end of the current hover sequence for that
120         * window.
121         * The event is transmuted into ACTION_HOVER_ENTER. */
122        FLAG_DISPATCH_AS_HOVER_EXIT = 1 << 11,
123
124        /* This flag indicates that the event should be canceled.
125         * It is used to transmute ACTION_MOVE into ACTION_CANCEL when a touch slips
126         * outside of a window. */
127        FLAG_DISPATCH_AS_SLIPPERY_EXIT = 1 << 12,
128
129        /* This flag indicates that the event should be dispatched as an initial down.
130         * It is used to transmute ACTION_MOVE into ACTION_DOWN when a touch slips
131         * into a new window. */
132        FLAG_DISPATCH_AS_SLIPPERY_ENTER = 1 << 13,
133
134        /* Mask for all dispatch modes. */
135        FLAG_DISPATCH_MASK = FLAG_DISPATCH_AS_IS
136                | FLAG_DISPATCH_AS_OUTSIDE
137                | FLAG_DISPATCH_AS_HOVER_ENTER
138                | FLAG_DISPATCH_AS_HOVER_EXIT
139                | FLAG_DISPATCH_AS_SLIPPERY_EXIT
140                | FLAG_DISPATCH_AS_SLIPPERY_ENTER,
141    };
142
143    // The input channel to be targeted.
144    sp<InputChannel> inputChannel;
145
146    // Flags for the input target.
147    int32_t flags;
148
149    // The x and y offset to add to a MotionEvent as it is delivered.
150    // (ignored for KeyEvents)
151    float xOffset, yOffset;
152
153    // Scaling factor to apply to MotionEvent as it is delivered.
154    // (ignored for KeyEvents)
155    float scaleFactor;
156
157    // The subset of pointer ids to include in motion events dispatched to this input target
158    // if FLAG_SPLIT is set.
159    BitSet32 pointerIds;
160};
161
162
163/*
164 * Input dispatcher configuration.
165 *
166 * Specifies various options that modify the behavior of the input dispatcher.
167 */
168struct InputDispatcherConfiguration {
169    // The key repeat initial timeout.
170    nsecs_t keyRepeatTimeout;
171
172    // The key repeat inter-key delay.
173    nsecs_t keyRepeatDelay;
174
175    // The maximum suggested event delivery rate per second.
176    // This value is used to throttle motion event movement actions on a per-device
177    // basis.  It is not intended to be a hard limit.
178    int32_t maxEventsPerSecond;
179
180    InputDispatcherConfiguration() :
181            keyRepeatTimeout(500 * 1000000LL),
182            keyRepeatDelay(50 * 1000000LL),
183            maxEventsPerSecond(60) { }
184};
185
186
187/*
188 * Input dispatcher policy interface.
189 *
190 * The input reader policy is used by the input reader to interact with the Window Manager
191 * and other system components.
192 *
193 * The actual implementation is partially supported by callbacks into the DVM
194 * via JNI.  This interface is also mocked in the unit tests.
195 */
196class InputDispatcherPolicyInterface : public virtual RefBase {
197protected:
198    InputDispatcherPolicyInterface() { }
199    virtual ~InputDispatcherPolicyInterface() { }
200
201public:
202    /* Notifies the system that a configuration change has occurred. */
203    virtual void notifyConfigurationChanged(nsecs_t when) = 0;
204
205    /* Notifies the system that an application is not responding.
206     * Returns a new timeout to continue waiting, or 0 to abort dispatch. */
207    virtual nsecs_t notifyANR(const sp<InputApplicationHandle>& inputApplicationHandle,
208            const sp<InputWindowHandle>& inputWindowHandle) = 0;
209
210    /* Notifies the system that an input channel is unrecoverably broken. */
211    virtual void notifyInputChannelBroken(const sp<InputWindowHandle>& inputWindowHandle) = 0;
212
213    /* Gets the input dispatcher configuration. */
214    virtual void getDispatcherConfiguration(InputDispatcherConfiguration* outConfig) = 0;
215
216    /* Returns true if automatic key repeating is enabled. */
217    virtual bool isKeyRepeatEnabled() = 0;
218
219    /* Filters an input event.
220     * Return true to dispatch the event unmodified, false to consume the event.
221     * A filter can also transform and inject events later by passing POLICY_FLAG_FILTERED
222     * to injectInputEvent.
223     */
224    virtual bool filterInputEvent(const InputEvent* inputEvent, uint32_t policyFlags) = 0;
225
226    /* Intercepts a key event immediately before queueing it.
227     * The policy can use this method as an opportunity to perform power management functions
228     * and early event preprocessing such as updating policy flags.
229     *
230     * This method is expected to set the POLICY_FLAG_PASS_TO_USER policy flag if the event
231     * should be dispatched to applications.
232     */
233    virtual void interceptKeyBeforeQueueing(const KeyEvent* keyEvent, uint32_t& policyFlags) = 0;
234
235    /* Intercepts a touch, trackball or other motion event before queueing it.
236     * The policy can use this method as an opportunity to perform power management functions
237     * and early event preprocessing such as updating policy flags.
238     *
239     * This method is expected to set the POLICY_FLAG_PASS_TO_USER policy flag if the event
240     * should be dispatched to applications.
241     */
242    virtual void interceptMotionBeforeQueueing(nsecs_t when, uint32_t& policyFlags) = 0;
243
244    /* Allows the policy a chance to intercept a key before dispatching. */
245    virtual bool interceptKeyBeforeDispatching(const sp<InputWindowHandle>& inputWindowHandle,
246            const KeyEvent* keyEvent, uint32_t policyFlags) = 0;
247
248    /* Allows the policy a chance to perform default processing for an unhandled key.
249     * Returns an alternate keycode to redispatch as a fallback, or 0 to give up. */
250    virtual bool dispatchUnhandledKey(const sp<InputWindowHandle>& inputWindowHandle,
251            const KeyEvent* keyEvent, uint32_t policyFlags, KeyEvent* outFallbackKeyEvent) = 0;
252
253    /* Notifies the policy about switch events.
254     */
255    virtual void notifySwitch(nsecs_t when,
256            int32_t switchCode, int32_t switchValue, uint32_t policyFlags) = 0;
257
258    /* Poke user activity for an event dispatched to a window. */
259    virtual void pokeUserActivity(nsecs_t eventTime, int32_t eventType) = 0;
260
261    /* Checks whether a given application pid/uid has permission to inject input events
262     * into other applications.
263     *
264     * This method is special in that its implementation promises to be non-reentrant and
265     * is safe to call while holding other locks.  (Most other methods make no such guarantees!)
266     */
267    virtual bool checkInjectEventsPermissionNonReentrant(
268            int32_t injectorPid, int32_t injectorUid) = 0;
269};
270
271
272/* Notifies the system about input events generated by the input reader.
273 * The dispatcher is expected to be mostly asynchronous. */
274class InputDispatcherInterface : public virtual RefBase {
275protected:
276    InputDispatcherInterface() { }
277    virtual ~InputDispatcherInterface() { }
278
279public:
280    /* Dumps the state of the input dispatcher.
281     *
282     * This method may be called on any thread (usually by the input manager). */
283    virtual void dump(String8& dump) = 0;
284
285    /* Runs a single iteration of the dispatch loop.
286     * Nominally processes one queued event, a timeout, or a response from an input consumer.
287     *
288     * This method should only be called on the input dispatcher thread.
289     */
290    virtual void dispatchOnce() = 0;
291
292    /* Notifies the dispatcher about new events.
293     *
294     * These methods should only be called on the input reader thread.
295     */
296    virtual void notifyConfigurationChanged(nsecs_t eventTime) = 0;
297    virtual void notifyKey(nsecs_t eventTime, int32_t deviceId, uint32_t source,
298            uint32_t policyFlags, int32_t action, int32_t flags, int32_t keyCode,
299            int32_t scanCode, int32_t metaState, nsecs_t downTime) = 0;
300    virtual void notifyMotion(nsecs_t eventTime, int32_t deviceId, uint32_t source,
301            uint32_t policyFlags, int32_t action, int32_t flags,
302            int32_t metaState, int32_t buttonState, int32_t edgeFlags,
303            uint32_t pointerCount, const PointerProperties* pointerProperties,
304            const PointerCoords* pointerCoords,
305            float xPrecision, float yPrecision, nsecs_t downTime) = 0;
306    virtual void notifySwitch(nsecs_t when,
307            int32_t switchCode, int32_t switchValue, uint32_t policyFlags) = 0;
308
309    /* Injects an input event and optionally waits for sync.
310     * The synchronization mode determines whether the method blocks while waiting for
311     * input injection to proceed.
312     * Returns one of the INPUT_EVENT_INJECTION_XXX constants.
313     *
314     * This method may be called on any thread (usually by the input manager).
315     */
316    virtual int32_t injectInputEvent(const InputEvent* event,
317            int32_t injectorPid, int32_t injectorUid, int32_t syncMode, int32_t timeoutMillis,
318            uint32_t policyFlags) = 0;
319
320    /* Sets the list of input windows.
321     *
322     * This method may be called on any thread (usually by the input manager).
323     */
324    virtual void setInputWindows(const Vector<InputWindow>& inputWindows) = 0;
325
326    /* Sets the focused application.
327     *
328     * This method may be called on any thread (usually by the input manager).
329     */
330    virtual void setFocusedApplication(const InputApplication* inputApplication) = 0;
331
332    /* Sets the input dispatching mode.
333     *
334     * This method may be called on any thread (usually by the input manager).
335     */
336    virtual void setInputDispatchMode(bool enabled, bool frozen) = 0;
337
338    /* Sets whether input event filtering is enabled.
339     * When enabled, incoming input events are sent to the policy's filterInputEvent
340     * method instead of being dispatched.  The filter is expected to use
341     * injectInputEvent to inject the events it would like to have dispatched.
342     * It should include POLICY_FLAG_FILTERED in the policy flags during injection.
343     */
344    virtual void setInputFilterEnabled(bool enabled) = 0;
345
346    /* Transfers touch focus from the window associated with one channel to the
347     * window associated with the other channel.
348     *
349     * Returns true on success.  False if the window did not actually have touch focus.
350     */
351    virtual bool transferTouchFocus(const sp<InputChannel>& fromChannel,
352            const sp<InputChannel>& toChannel) = 0;
353
354    /* Registers or unregister input channels that may be used as targets for input events.
355     * If monitor is true, the channel will receive a copy of all input events.
356     *
357     * These methods may be called on any thread (usually by the input manager).
358     */
359    virtual status_t registerInputChannel(const sp<InputChannel>& inputChannel,
360            const sp<InputWindowHandle>& inputWindowHandle, bool monitor) = 0;
361    virtual status_t unregisterInputChannel(const sp<InputChannel>& inputChannel) = 0;
362};
363
364/* Dispatches events to input targets.  Some functions of the input dispatcher, such as
365 * identifying input targets, are controlled by a separate policy object.
366 *
367 * IMPORTANT INVARIANT:
368 *     Because the policy can potentially block or cause re-entrance into the input dispatcher,
369 *     the input dispatcher never calls into the policy while holding its internal locks.
370 *     The implementation is also carefully designed to recover from scenarios such as an
371 *     input channel becoming unregistered while identifying input targets or processing timeouts.
372 *
373 *     Methods marked 'Locked' must be called with the lock acquired.
374 *
375 *     Methods marked 'LockedInterruptible' must be called with the lock acquired but
376 *     may during the course of their execution release the lock, call into the policy, and
377 *     then reacquire the lock.  The caller is responsible for recovering gracefully.
378 *
379 *     A 'LockedInterruptible' method may called a 'Locked' method, but NOT vice-versa.
380 */
381class InputDispatcher : public InputDispatcherInterface {
382protected:
383    virtual ~InputDispatcher();
384
385public:
386    explicit InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy);
387
388    virtual void dump(String8& dump);
389
390    virtual void dispatchOnce();
391
392    virtual void notifyConfigurationChanged(nsecs_t eventTime);
393    virtual void notifyKey(nsecs_t eventTime, int32_t deviceId, uint32_t source,
394            uint32_t policyFlags, int32_t action, int32_t flags, int32_t keyCode,
395            int32_t scanCode, int32_t metaState, nsecs_t downTime);
396    virtual void notifyMotion(nsecs_t eventTime, int32_t deviceId, uint32_t source,
397            uint32_t policyFlags, int32_t action, int32_t flags,
398            int32_t metaState, int32_t buttonState, int32_t edgeFlags,
399            uint32_t pointerCount, const PointerProperties* pointerProperties,
400            const PointerCoords* pointerCoords,
401            float xPrecision, float yPrecision, nsecs_t downTime);
402    virtual void notifySwitch(nsecs_t when,
403            int32_t switchCode, int32_t switchValue, uint32_t policyFlags) ;
404
405    virtual int32_t injectInputEvent(const InputEvent* event,
406            int32_t injectorPid, int32_t injectorUid, int32_t syncMode, int32_t timeoutMillis,
407            uint32_t policyFlags);
408
409    virtual void setInputWindows(const Vector<InputWindow>& inputWindows);
410    virtual void setFocusedApplication(const InputApplication* inputApplication);
411    virtual void setInputDispatchMode(bool enabled, bool frozen);
412    virtual void setInputFilterEnabled(bool enabled);
413
414    virtual bool transferTouchFocus(const sp<InputChannel>& fromChannel,
415            const sp<InputChannel>& toChannel);
416
417    virtual status_t registerInputChannel(const sp<InputChannel>& inputChannel,
418            const sp<InputWindowHandle>& inputWindowHandle, bool monitor);
419    virtual status_t unregisterInputChannel(const sp<InputChannel>& inputChannel);
420
421private:
422    template <typename T>
423    struct Link {
424        T* next;
425        T* prev;
426    };
427
428    struct InjectionState {
429        mutable int32_t refCount;
430
431        int32_t injectorPid;
432        int32_t injectorUid;
433        int32_t injectionResult;  // initially INPUT_EVENT_INJECTION_PENDING
434        bool injectionIsAsync; // set to true if injection is not waiting for the result
435        int32_t pendingForegroundDispatches; // the number of foreground dispatches in progress
436    };
437
438    struct EventEntry : Link<EventEntry> {
439        enum {
440            TYPE_SENTINEL,
441            TYPE_CONFIGURATION_CHANGED,
442            TYPE_KEY,
443            TYPE_MOTION
444        };
445
446        mutable int32_t refCount;
447        int32_t type;
448        nsecs_t eventTime;
449        uint32_t policyFlags;
450        InjectionState* injectionState;
451
452        bool dispatchInProgress; // initially false, set to true while dispatching
453
454        inline bool isInjected() const { return injectionState != NULL; }
455    };
456
457    struct ConfigurationChangedEntry : EventEntry {
458    };
459
460    struct KeyEntry : EventEntry {
461        int32_t deviceId;
462        uint32_t source;
463        int32_t action;
464        int32_t flags;
465        int32_t keyCode;
466        int32_t scanCode;
467        int32_t metaState;
468        int32_t repeatCount;
469        nsecs_t downTime;
470
471        bool syntheticRepeat; // set to true for synthetic key repeats
472
473        enum InterceptKeyResult {
474            INTERCEPT_KEY_RESULT_UNKNOWN,
475            INTERCEPT_KEY_RESULT_SKIP,
476            INTERCEPT_KEY_RESULT_CONTINUE,
477        };
478        InterceptKeyResult interceptKeyResult; // set based on the interception result
479    };
480
481    struct MotionSample {
482        MotionSample* next;
483
484        nsecs_t eventTime; // may be updated during coalescing
485        nsecs_t eventTimeBeforeCoalescing; // not updated during coalescing
486        PointerCoords pointerCoords[MAX_POINTERS];
487    };
488
489    struct MotionEntry : EventEntry {
490        int32_t deviceId;
491        uint32_t source;
492        int32_t action;
493        int32_t flags;
494        int32_t metaState;
495        int32_t buttonState;
496        int32_t edgeFlags;
497        float xPrecision;
498        float yPrecision;
499        nsecs_t downTime;
500        uint32_t pointerCount;
501        PointerProperties pointerProperties[MAX_POINTERS];
502
503        // Linked list of motion samples associated with this motion event.
504        MotionSample firstSample;
505        MotionSample* lastSample;
506
507        uint32_t countSamples() const;
508
509        // Checks whether we can append samples, assuming the device id and source are the same.
510        bool canAppendSamples(int32_t action, uint32_t pointerCount,
511                const PointerProperties* pointerProperties) const;
512    };
513
514    // Tracks the progress of dispatching a particular event to a particular connection.
515    struct DispatchEntry : Link<DispatchEntry> {
516        EventEntry* eventEntry; // the event to dispatch
517        int32_t targetFlags;
518        float xOffset;
519        float yOffset;
520        float scaleFactor;
521
522        // True if dispatch has started.
523        bool inProgress;
524
525        // Set to the resolved action and flags when the event is enqueued.
526        int32_t resolvedAction;
527        int32_t resolvedFlags;
528
529        // For motion events:
530        //   Pointer to the first motion sample to dispatch in this cycle.
531        //   Usually NULL to indicate that the list of motion samples begins at
532        //   MotionEntry::firstSample.  Otherwise, some samples were dispatched in a previous
533        //   cycle and this pointer indicates the location of the first remainining sample
534        //   to dispatch during the current cycle.
535        MotionSample* headMotionSample;
536        //   Pointer to a motion sample to dispatch in the next cycle if the dispatcher was
537        //   unable to send all motion samples during this cycle.  On the next cycle,
538        //   headMotionSample will be initialized to tailMotionSample and tailMotionSample
539        //   will be set to NULL.
540        MotionSample* tailMotionSample;
541
542        inline bool hasForegroundTarget() const {
543            return targetFlags & InputTarget::FLAG_FOREGROUND;
544        }
545
546        inline bool isSplit() const {
547            return targetFlags & InputTarget::FLAG_SPLIT;
548        }
549    };
550
551    // A command entry captures state and behavior for an action to be performed in the
552    // dispatch loop after the initial processing has taken place.  It is essentially
553    // a kind of continuation used to postpone sensitive policy interactions to a point
554    // in the dispatch loop where it is safe to release the lock (generally after finishing
555    // the critical parts of the dispatch cycle).
556    //
557    // The special thing about commands is that they can voluntarily release and reacquire
558    // the dispatcher lock at will.  Initially when the command starts running, the
559    // dispatcher lock is held.  However, if the command needs to call into the policy to
560    // do some work, it can release the lock, do the work, then reacquire the lock again
561    // before returning.
562    //
563    // This mechanism is a bit clunky but it helps to preserve the invariant that the dispatch
564    // never calls into the policy while holding its lock.
565    //
566    // Commands are implicitly 'LockedInterruptible'.
567    struct CommandEntry;
568    typedef void (InputDispatcher::*Command)(CommandEntry* commandEntry);
569
570    class Connection;
571    struct CommandEntry : Link<CommandEntry> {
572        CommandEntry();
573        ~CommandEntry();
574
575        Command command;
576
577        // parameters for the command (usage varies by command)
578        sp<Connection> connection;
579        nsecs_t eventTime;
580        KeyEntry* keyEntry;
581        sp<InputChannel> inputChannel;
582        sp<InputApplicationHandle> inputApplicationHandle;
583        sp<InputWindowHandle> inputWindowHandle;
584        int32_t userActivityEventType;
585        bool handled;
586    };
587
588    // Generic queue implementation.
589    template <typename T>
590    struct Queue {
591        T headSentinel;
592        T tailSentinel;
593
594        inline Queue() {
595            headSentinel.prev = NULL;
596            headSentinel.next = & tailSentinel;
597            tailSentinel.prev = & headSentinel;
598            tailSentinel.next = NULL;
599        }
600
601        inline bool isEmpty() const {
602            return headSentinel.next == & tailSentinel;
603        }
604
605        inline void enqueueAtTail(T* entry) {
606            T* last = tailSentinel.prev;
607            last->next = entry;
608            entry->prev = last;
609            entry->next = & tailSentinel;
610            tailSentinel.prev = entry;
611        }
612
613        inline void enqueueAtHead(T* entry) {
614            T* first = headSentinel.next;
615            headSentinel.next = entry;
616            entry->prev = & headSentinel;
617            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() {
627            T* first = headSentinel.next;
628            dequeue(first);
629            return first;
630        }
631
632        uint32_t count() const;
633    };
634
635    /* Allocates queue entries and performs reference counting as needed. */
636    class Allocator {
637    public:
638        Allocator();
639
640        InjectionState* obtainInjectionState(int32_t injectorPid, int32_t injectorUid);
641        ConfigurationChangedEntry* obtainConfigurationChangedEntry(nsecs_t eventTime);
642        KeyEntry* obtainKeyEntry(nsecs_t eventTime,
643                int32_t deviceId, uint32_t source, uint32_t policyFlags, int32_t action,
644                int32_t flags, int32_t keyCode, int32_t scanCode, int32_t metaState,
645                int32_t repeatCount, nsecs_t downTime);
646        MotionEntry* obtainMotionEntry(nsecs_t eventTime,
647                int32_t deviceId, uint32_t source, uint32_t policyFlags, int32_t action,
648                int32_t flags, int32_t metaState, int32_t buttonState, int32_t edgeFlags,
649                float xPrecision, float yPrecision,
650                nsecs_t downTime, uint32_t pointerCount,
651                const PointerProperties* pointerProperties, const PointerCoords* pointerCoords);
652        DispatchEntry* obtainDispatchEntry(EventEntry* eventEntry,
653                int32_t targetFlags, float xOffset, float yOffset, float scaleFactor);
654        CommandEntry* obtainCommandEntry(Command command);
655
656        void releaseInjectionState(InjectionState* injectionState);
657        void releaseEventEntry(EventEntry* entry);
658        void releaseConfigurationChangedEntry(ConfigurationChangedEntry* entry);
659        void releaseKeyEntry(KeyEntry* entry);
660        void releaseMotionEntry(MotionEntry* entry);
661        void freeMotionSample(MotionSample* sample);
662        void releaseDispatchEntry(DispatchEntry* entry);
663        void releaseCommandEntry(CommandEntry* entry);
664
665        void recycleKeyEntry(KeyEntry* entry);
666
667        void appendMotionSample(MotionEntry* motionEntry,
668                nsecs_t eventTime, const PointerCoords* pointerCoords);
669
670    private:
671        Pool<InjectionState> mInjectionStatePool;
672        Pool<ConfigurationChangedEntry> mConfigurationChangeEntryPool;
673        Pool<KeyEntry> mKeyEntryPool;
674        Pool<MotionEntry> mMotionEntryPool;
675        Pool<MotionSample> mMotionSamplePool;
676        Pool<DispatchEntry> mDispatchEntryPool;
677        Pool<CommandEntry> mCommandEntryPool;
678
679        void initializeEventEntry(EventEntry* entry, int32_t type, nsecs_t eventTime,
680                uint32_t policyFlags);
681        void releaseEventEntryInjectionState(EventEntry* entry);
682    };
683
684    /* Specifies which events are to be canceled and why. */
685    struct CancelationOptions {
686        enum Mode {
687            CANCEL_ALL_EVENTS = 0,
688            CANCEL_POINTER_EVENTS = 1,
689            CANCEL_NON_POINTER_EVENTS = 2,
690            CANCEL_FALLBACK_EVENTS = 3,
691        };
692
693        // The criterion to use to determine which events should be canceled.
694        Mode mode;
695
696        // Descriptive reason for the cancelation.
697        const char* reason;
698
699        // The specific keycode of the key event to cancel, or -1 to cancel any key event.
700        int32_t keyCode;
701
702        CancelationOptions(Mode mode, const char* reason) :
703                mode(mode), reason(reason), keyCode(-1) { }
704    };
705
706    /* Tracks dispatched key and motion event state so that cancelation events can be
707     * synthesized when events are dropped. */
708    class InputState {
709    public:
710        InputState();
711        ~InputState();
712
713        // Returns true if there is no state to be canceled.
714        bool isNeutral() const;
715
716        // Returns true if the specified source is known to have received a hover enter
717        // motion event.
718        bool isHovering(int32_t deviceId, uint32_t source) const;
719
720        // Records tracking information for a key event that has just been published.
721        // Returns true if the event should be delivered, false if it is inconsistent
722        // and should be skipped.
723        bool trackKey(const KeyEntry* entry, int32_t action, int32_t flags);
724
725        // Records tracking information for a motion event that has just been published.
726        // Returns true if the event should be delivered, false if it is inconsistent
727        // and should be skipped.
728        bool trackMotion(const MotionEntry* entry, int32_t action, int32_t flags);
729
730        // Synthesizes cancelation events for the current state and resets the tracked state.
731        void synthesizeCancelationEvents(nsecs_t currentTime, Allocator* allocator,
732                Vector<EventEntry*>& outEvents, const CancelationOptions& options);
733
734        // Clears the current state.
735        void clear();
736
737        // Copies pointer-related parts of the input state to another instance.
738        void copyPointerStateTo(InputState& other) const;
739
740        // Gets the fallback key associated with a keycode.
741        // Returns -1 if none.
742        // Returns AKEYCODE_UNKNOWN if we are only dispatching the unhandled key to the policy.
743        int32_t getFallbackKey(int32_t originalKeyCode);
744
745        // Sets the fallback key for a particular keycode.
746        void setFallbackKey(int32_t originalKeyCode, int32_t fallbackKeyCode);
747
748        // Removes the fallback key for a particular keycode.
749        void removeFallbackKey(int32_t originalKeyCode);
750
751        inline const KeyedVector<int32_t, int32_t>& getFallbackKeys() const {
752            return mFallbackKeys;
753        }
754
755    private:
756        struct KeyMemento {
757            int32_t deviceId;
758            uint32_t source;
759            int32_t keyCode;
760            int32_t scanCode;
761            int32_t flags;
762            nsecs_t downTime;
763        };
764
765        struct MotionMemento {
766            int32_t deviceId;
767            uint32_t source;
768            int32_t flags;
769            float xPrecision;
770            float yPrecision;
771            nsecs_t downTime;
772            uint32_t pointerCount;
773            PointerProperties pointerProperties[MAX_POINTERS];
774            PointerCoords pointerCoords[MAX_POINTERS];
775            bool hovering;
776
777            void setPointers(const MotionEntry* entry);
778        };
779
780        Vector<KeyMemento> mKeyMementos;
781        Vector<MotionMemento> mMotionMementos;
782        KeyedVector<int32_t, int32_t> mFallbackKeys;
783
784        ssize_t findKeyMemento(const KeyEntry* entry) const;
785        ssize_t findMotionMemento(const MotionEntry* entry, bool hovering) const;
786
787        void addKeyMemento(const KeyEntry* entry, int32_t flags);
788        void addMotionMemento(const MotionEntry* entry, int32_t flags, bool hovering);
789
790        static bool shouldCancelKey(const KeyMemento& memento,
791                const CancelationOptions& options);
792        static bool shouldCancelMotion(const MotionMemento& memento,
793                const CancelationOptions& options);
794    };
795
796    /* Manages the dispatch state associated with a single input channel. */
797    class Connection : public RefBase {
798    protected:
799        virtual ~Connection();
800
801    public:
802        enum Status {
803            // Everything is peachy.
804            STATUS_NORMAL,
805            // An unrecoverable communication error has occurred.
806            STATUS_BROKEN,
807            // The input channel has been unregistered.
808            STATUS_ZOMBIE
809        };
810
811        Status status;
812        sp<InputChannel> inputChannel; // never null
813        sp<InputWindowHandle> inputWindowHandle; // may be null
814        InputPublisher inputPublisher;
815        InputState inputState;
816        Queue<DispatchEntry> outboundQueue;
817
818        nsecs_t lastEventTime; // the time when the event was originally captured
819        nsecs_t lastDispatchTime; // the time when the last event was dispatched
820
821        explicit Connection(const sp<InputChannel>& inputChannel,
822                const sp<InputWindowHandle>& inputWindowHandle);
823
824        inline const char* getInputChannelName() const { return inputChannel->getName().string(); }
825
826        const char* getStatusLabel() const;
827
828        // Finds a DispatchEntry in the outbound queue associated with the specified event.
829        // Returns NULL if not found.
830        DispatchEntry* findQueuedDispatchEntryForEvent(const EventEntry* eventEntry) const;
831
832        // Gets the time since the current event was originally obtained from the input driver.
833        inline double getEventLatencyMillis(nsecs_t currentTime) const {
834            return (currentTime - lastEventTime) / 1000000.0;
835        }
836
837        // Gets the time since the current event entered the outbound dispatch queue.
838        inline double getDispatchLatencyMillis(nsecs_t currentTime) const {
839            return (currentTime - lastDispatchTime) / 1000000.0;
840        }
841
842        status_t initialize();
843    };
844
845    enum DropReason {
846        DROP_REASON_NOT_DROPPED = 0,
847        DROP_REASON_POLICY = 1,
848        DROP_REASON_APP_SWITCH = 2,
849        DROP_REASON_DISABLED = 3,
850        DROP_REASON_BLOCKED = 4,
851        DROP_REASON_STALE = 5,
852    };
853
854    sp<InputDispatcherPolicyInterface> mPolicy;
855    InputDispatcherConfiguration mConfig;
856
857    Mutex mLock;
858
859    Allocator mAllocator;
860    sp<Looper> mLooper;
861
862    EventEntry* mPendingEvent;
863    Queue<EventEntry> mInboundQueue;
864    Queue<CommandEntry> mCommandQueue;
865
866    Vector<EventEntry*> mTempCancelationEvents;
867
868    void dispatchOnceInnerLocked(nsecs_t* nextWakeupTime);
869
870    // Batches a new sample onto a motion entry.
871    // Assumes that the we have already checked that we can append samples.
872    void batchMotionLocked(MotionEntry* entry, nsecs_t eventTime, int32_t metaState,
873            const PointerCoords* pointerCoords, const char* eventDescription);
874
875    // Enqueues an inbound event.  Returns true if mLooper->wake() should be called.
876    bool enqueueInboundEventLocked(EventEntry* entry);
877
878    // Cleans up input state when dropping an inbound event.
879    void dropInboundEventLocked(EventEntry* entry, DropReason dropReason);
880
881    // App switch latency optimization.
882    bool mAppSwitchSawKeyDown;
883    nsecs_t mAppSwitchDueTime;
884
885    static bool isAppSwitchKeyCode(int32_t keyCode);
886    bool isAppSwitchKeyEventLocked(KeyEntry* keyEntry);
887    bool isAppSwitchPendingLocked();
888    void resetPendingAppSwitchLocked(bool handled);
889
890    // Stale event latency optimization.
891    static bool isStaleEventLocked(nsecs_t currentTime, EventEntry* entry);
892
893    // Blocked event latency optimization.  Drops old events when the user intends
894    // to transfer focus to a new application.
895    EventEntry* mNextUnblockedEvent;
896
897    const InputWindow* findTouchedWindowAtLocked(int32_t x, int32_t y);
898
899    // All registered connections mapped by receive pipe file descriptor.
900    KeyedVector<int, sp<Connection> > mConnectionsByReceiveFd;
901
902    ssize_t getConnectionIndexLocked(const sp<InputChannel>& inputChannel);
903
904    // Active connections are connections that have a non-empty outbound queue.
905    // We don't use a ref-counted pointer here because we explicitly abort connections
906    // during unregistration which causes the connection's outbound queue to be cleared
907    // and the connection itself to be deactivated.
908    Vector<Connection*> mActiveConnections;
909
910    // Input channels that will receive a copy of all input events.
911    Vector<sp<InputChannel> > mMonitoringChannels;
912
913    // Event injection and synchronization.
914    Condition mInjectionResultAvailableCondition;
915    bool hasInjectionPermission(int32_t injectorPid, int32_t injectorUid);
916    void setInjectionResultLocked(EventEntry* entry, int32_t injectionResult);
917
918    Condition mInjectionSyncFinishedCondition;
919    void incrementPendingForegroundDispatchesLocked(EventEntry* entry);
920    void decrementPendingForegroundDispatchesLocked(EventEntry* entry);
921
922    // Throttling state.
923    struct ThrottleState {
924        nsecs_t minTimeBetweenEvents;
925
926        nsecs_t lastEventTime;
927        int32_t lastDeviceId;
928        uint32_t lastSource;
929
930        uint32_t originalSampleCount; // only collected during debugging
931    } mThrottleState;
932
933    // Key repeat tracking.
934    struct KeyRepeatState {
935        KeyEntry* lastKeyEntry; // or null if no repeat
936        nsecs_t nextRepeatTime;
937    } mKeyRepeatState;
938
939    void resetKeyRepeatLocked();
940    KeyEntry* synthesizeKeyRepeatLocked(nsecs_t currentTime);
941
942    // Deferred command processing.
943    bool runCommandsLockedInterruptible();
944    CommandEntry* postCommandLocked(Command command);
945
946    // Inbound event processing.
947    void drainInboundQueueLocked();
948    void releasePendingEventLocked();
949    void releaseInboundEventLocked(EventEntry* entry);
950
951    // Dispatch state.
952    bool mDispatchEnabled;
953    bool mDispatchFrozen;
954    bool mInputFilterEnabled;
955
956    Vector<InputWindow> mWindows;
957
958    const InputWindow* getWindowLocked(const sp<InputChannel>& inputChannel);
959
960    // Focus tracking for keys, trackball, etc.
961    const InputWindow* mFocusedWindow;
962
963    // Focus tracking for touch.
964    struct TouchedWindow {
965        const InputWindow* window;
966        int32_t targetFlags;
967        BitSet32 pointerIds;        // zero unless target flag FLAG_SPLIT is set
968        sp<InputChannel> channel;
969    };
970    struct TouchState {
971        bool down;
972        bool split;
973        int32_t deviceId; // id of the device that is currently down, others are rejected
974        uint32_t source;  // source of the device that is current down, others are rejected
975        Vector<TouchedWindow> windows;
976
977        TouchState();
978        ~TouchState();
979        void reset();
980        void copyFrom(const TouchState& other);
981        void addOrUpdateWindow(const InputWindow* window,int32_t targetFlags, BitSet32 pointerIds);
982        void filterNonAsIsTouchWindows();
983        const InputWindow* getFirstForegroundWindow() const;
984        bool isSlippery() const;
985    };
986
987    TouchState mTouchState;
988    TouchState mTempTouchState;
989
990    // Focused application.
991    InputApplication* mFocusedApplication;
992    InputApplication mFocusedApplicationStorage; // preallocated storage for mFocusedApplication
993    void releaseFocusedApplicationLocked();
994
995    // Dispatch inbound events.
996    bool dispatchConfigurationChangedLocked(
997            nsecs_t currentTime, ConfigurationChangedEntry* entry);
998    bool dispatchKeyLocked(
999            nsecs_t currentTime, KeyEntry* entry,
1000            DropReason* dropReason, nsecs_t* nextWakeupTime);
1001    bool dispatchMotionLocked(
1002            nsecs_t currentTime, MotionEntry* entry,
1003            DropReason* dropReason, nsecs_t* nextWakeupTime);
1004    void dispatchEventToCurrentInputTargetsLocked(
1005            nsecs_t currentTime, EventEntry* entry, bool resumeWithAppendedMotionSample);
1006
1007    void logOutboundKeyDetailsLocked(const char* prefix, const KeyEntry* entry);
1008    void logOutboundMotionDetailsLocked(const char* prefix, const MotionEntry* entry);
1009
1010    // The input targets that were most recently identified for dispatch.
1011    bool mCurrentInputTargetsValid; // false while targets are being recomputed
1012    Vector<InputTarget> mCurrentInputTargets;
1013
1014    enum InputTargetWaitCause {
1015        INPUT_TARGET_WAIT_CAUSE_NONE,
1016        INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY,
1017        INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY,
1018    };
1019
1020    InputTargetWaitCause mInputTargetWaitCause;
1021    nsecs_t mInputTargetWaitStartTime;
1022    nsecs_t mInputTargetWaitTimeoutTime;
1023    bool mInputTargetWaitTimeoutExpired;
1024    sp<InputApplicationHandle> mInputTargetWaitApplication;
1025
1026    // Contains the last window which received a hover event.
1027    const InputWindow* mLastHoverWindow;
1028
1029    // Finding targets for input events.
1030    void resetTargetsLocked();
1031    void commitTargetsLocked();
1032    int32_t handleTargetsNotReadyLocked(nsecs_t currentTime, const EventEntry* entry,
1033            const InputApplication* application, const InputWindow* window,
1034            nsecs_t* nextWakeupTime);
1035    void resumeAfterTargetsNotReadyTimeoutLocked(nsecs_t newTimeout,
1036            const sp<InputChannel>& inputChannel);
1037    nsecs_t getTimeSpentWaitingForApplicationLocked(nsecs_t currentTime);
1038    void resetANRTimeoutsLocked();
1039
1040    int32_t findFocusedWindowTargetsLocked(nsecs_t currentTime, const EventEntry* entry,
1041            nsecs_t* nextWakeupTime);
1042    int32_t findTouchedWindowTargetsLocked(nsecs_t currentTime, const MotionEntry* entry,
1043            nsecs_t* nextWakeupTime, bool* outConflictingPointerActions,
1044            const MotionSample** outSplitBatchAfterSample);
1045
1046    void addWindowTargetLocked(const InputWindow* window, int32_t targetFlags,
1047            BitSet32 pointerIds);
1048    void addMonitoringTargetsLocked();
1049    void pokeUserActivityLocked(const EventEntry* eventEntry);
1050    bool checkInjectionPermission(const InputWindow* window, const InjectionState* injectionState);
1051    bool isWindowObscuredAtPointLocked(const InputWindow* window, int32_t x, int32_t y) const;
1052    bool isWindowFinishedWithPreviousInputLocked(const InputWindow* window);
1053    String8 getApplicationWindowLabelLocked(const InputApplication* application,
1054            const InputWindow* window);
1055
1056    // Manage the dispatch cycle for a single connection.
1057    // These methods are deliberately not Interruptible because doing all of the work
1058    // with the mutex held makes it easier to ensure that connection invariants are maintained.
1059    // If needed, the methods post commands to run later once the critical bits are done.
1060    void prepareDispatchCycleLocked(nsecs_t currentTime, const sp<Connection>& connection,
1061            EventEntry* eventEntry, const InputTarget* inputTarget,
1062            bool resumeWithAppendedMotionSample);
1063    void enqueueDispatchEntryLocked(const sp<Connection>& connection,
1064            EventEntry* eventEntry, const InputTarget* inputTarget,
1065            bool resumeWithAppendedMotionSample, int32_t dispatchMode);
1066    void startDispatchCycleLocked(nsecs_t currentTime, const sp<Connection>& connection);
1067    void finishDispatchCycleLocked(nsecs_t currentTime, const sp<Connection>& connection,
1068            bool handled);
1069    void startNextDispatchCycleLocked(nsecs_t currentTime, const sp<Connection>& connection);
1070    void abortBrokenDispatchCycleLocked(nsecs_t currentTime, const sp<Connection>& connection);
1071    void drainOutboundQueueLocked(Connection* connection);
1072    static int handleReceiveCallback(int receiveFd, int events, void* data);
1073
1074    void synthesizeCancelationEventsForAllConnectionsLocked(
1075            const CancelationOptions& options);
1076    void synthesizeCancelationEventsForInputChannelLocked(const sp<InputChannel>& channel,
1077            const CancelationOptions& options);
1078    void synthesizeCancelationEventsForConnectionLocked(const sp<Connection>& connection,
1079            const CancelationOptions& options);
1080
1081    // Splitting motion events across windows.
1082    MotionEntry* splitMotionEvent(const MotionEntry* originalMotionEntry, BitSet32 pointerIds);
1083
1084    // Reset and drop everything the dispatcher is doing.
1085    void resetAndDropEverythingLocked(const char* reason);
1086
1087    // Dump state.
1088    void dumpDispatchStateLocked(String8& dump);
1089    void logDispatchStateLocked();
1090
1091    // Add or remove a connection to the mActiveConnections vector.
1092    void activateConnectionLocked(Connection* connection);
1093    void deactivateConnectionLocked(Connection* connection);
1094
1095    // Interesting events that we might like to log or tell the framework about.
1096    void onDispatchCycleStartedLocked(
1097            nsecs_t currentTime, const sp<Connection>& connection);
1098    void onDispatchCycleFinishedLocked(
1099            nsecs_t currentTime, const sp<Connection>& connection, bool handled);
1100    void onDispatchCycleBrokenLocked(
1101            nsecs_t currentTime, const sp<Connection>& connection);
1102    void onANRLocked(
1103            nsecs_t currentTime, const InputApplication* application, const InputWindow* window,
1104            nsecs_t eventTime, nsecs_t waitStartTime);
1105
1106    // Outbound policy interactions.
1107    void doNotifyConfigurationChangedInterruptible(CommandEntry* commandEntry);
1108    void doNotifyInputChannelBrokenLockedInterruptible(CommandEntry* commandEntry);
1109    void doNotifyANRLockedInterruptible(CommandEntry* commandEntry);
1110    void doInterceptKeyBeforeDispatchingLockedInterruptible(CommandEntry* commandEntry);
1111    void doDispatchCycleFinishedLockedInterruptible(CommandEntry* commandEntry);
1112    bool afterKeyEventLockedInterruptible(const sp<Connection>& connection,
1113            DispatchEntry* dispatchEntry, KeyEntry* keyEntry, bool handled);
1114    bool afterMotionEventLockedInterruptible(const sp<Connection>& connection,
1115            DispatchEntry* dispatchEntry, MotionEntry* motionEntry, bool handled);
1116    void doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry);
1117    void initializeKeyEvent(KeyEvent* event, const KeyEntry* entry);
1118
1119    // Statistics gathering.
1120    void updateDispatchStatisticsLocked(nsecs_t currentTime, const EventEntry* entry,
1121            int32_t injectionResult, nsecs_t timeSpentWaitingForApplication);
1122};
1123
1124/* Enqueues and dispatches input events, endlessly. */
1125class InputDispatcherThread : public Thread {
1126public:
1127    explicit InputDispatcherThread(const sp<InputDispatcherInterface>& dispatcher);
1128    ~InputDispatcherThread();
1129
1130private:
1131    virtual bool threadLoop();
1132
1133    sp<InputDispatcherInterface> mDispatcher;
1134};
1135
1136} // namespace android
1137
1138#endif // _UI_INPUT_DISPATCHER_H
1139