InputDispatcher.h revision 308028049a75b36d5ed525c0bcef441da850c2a5
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/BitSet.h>
30
31#include <stddef.h>
32#include <unistd.h>
33#include <limits.h>
34
35#include "InputWindow.h"
36#include "InputApplication.h"
37#include "InputListener.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    InputDispatcherConfiguration() :
176            keyRepeatTimeout(500 * 1000000LL),
177            keyRepeatDelay(50 * 1000000LL) { }
178};
179
180
181/*
182 * Input dispatcher policy interface.
183 *
184 * The input reader policy is used by the input reader to interact with the Window Manager
185 * and other system components.
186 *
187 * The actual implementation is partially supported by callbacks into the DVM
188 * via JNI.  This interface is also mocked in the unit tests.
189 */
190class InputDispatcherPolicyInterface : public virtual RefBase {
191protected:
192    InputDispatcherPolicyInterface() { }
193    virtual ~InputDispatcherPolicyInterface() { }
194
195public:
196    /* Notifies the system that a configuration change has occurred. */
197    virtual void notifyConfigurationChanged(nsecs_t when) = 0;
198
199    /* Notifies the system that an application is not responding.
200     * Returns a new timeout to continue waiting, or 0 to abort dispatch. */
201    virtual nsecs_t notifyANR(const sp<InputApplicationHandle>& inputApplicationHandle,
202            const sp<InputWindowHandle>& inputWindowHandle) = 0;
203
204    /* Notifies the system that an input channel is unrecoverably broken. */
205    virtual void notifyInputChannelBroken(const sp<InputWindowHandle>& inputWindowHandle) = 0;
206
207    /* Gets the input dispatcher configuration. */
208    virtual void getDispatcherConfiguration(InputDispatcherConfiguration* outConfig) = 0;
209
210    /* Returns true if automatic key repeating is enabled. */
211    virtual bool isKeyRepeatEnabled() = 0;
212
213    /* Filters an input event.
214     * Return true to dispatch the event unmodified, false to consume the event.
215     * A filter can also transform and inject events later by passing POLICY_FLAG_FILTERED
216     * to injectInputEvent.
217     */
218    virtual bool filterInputEvent(const InputEvent* inputEvent, uint32_t policyFlags) = 0;
219
220    /* Intercepts a key event immediately before queueing it.
221     * The policy can use this method as an opportunity to perform power management functions
222     * and early event preprocessing such as updating policy flags.
223     *
224     * This method is expected to set the POLICY_FLAG_PASS_TO_USER policy flag if the event
225     * should be dispatched to applications.
226     */
227    virtual void interceptKeyBeforeQueueing(const KeyEvent* keyEvent, uint32_t& policyFlags) = 0;
228
229    /* Intercepts a touch, trackball or other motion event before queueing it.
230     * The policy can use this method as an opportunity to perform power management functions
231     * and early event preprocessing such as updating policy flags.
232     *
233     * This method is expected to set the POLICY_FLAG_PASS_TO_USER policy flag if the event
234     * should be dispatched to applications.
235     */
236    virtual void interceptMotionBeforeQueueing(nsecs_t when, uint32_t& policyFlags) = 0;
237
238    /* Allows the policy a chance to intercept a key before dispatching. */
239    virtual nsecs_t interceptKeyBeforeDispatching(const sp<InputWindowHandle>& inputWindowHandle,
240            const KeyEvent* keyEvent, uint32_t policyFlags) = 0;
241
242    /* Allows the policy a chance to perform default processing for an unhandled key.
243     * Returns an alternate keycode to redispatch as a fallback, or 0 to give up. */
244    virtual bool dispatchUnhandledKey(const sp<InputWindowHandle>& inputWindowHandle,
245            const KeyEvent* keyEvent, uint32_t policyFlags, KeyEvent* outFallbackKeyEvent) = 0;
246
247    /* Notifies the policy about switch events.
248     */
249    virtual void notifySwitch(nsecs_t when,
250            int32_t switchCode, int32_t switchValue, uint32_t policyFlags) = 0;
251
252    /* Poke user activity for an event dispatched to a window. */
253    virtual void pokeUserActivity(nsecs_t eventTime, int32_t eventType) = 0;
254
255    /* Checks whether a given application pid/uid has permission to inject input events
256     * into other applications.
257     *
258     * This method is special in that its implementation promises to be non-reentrant and
259     * is safe to call while holding other locks.  (Most other methods make no such guarantees!)
260     */
261    virtual bool checkInjectEventsPermissionNonReentrant(
262            int32_t injectorPid, int32_t injectorUid) = 0;
263};
264
265
266/* Notifies the system about input events generated by the input reader.
267 * The dispatcher is expected to be mostly asynchronous. */
268class InputDispatcherInterface : public virtual RefBase, public InputListenerInterface {
269protected:
270    InputDispatcherInterface() { }
271    virtual ~InputDispatcherInterface() { }
272
273public:
274    /* Dumps the state of the input dispatcher.
275     *
276     * This method may be called on any thread (usually by the input manager). */
277    virtual void dump(String8& dump) = 0;
278
279    /* Called by the heatbeat to ensures that the dispatcher has not deadlocked. */
280    virtual void monitor() = 0;
281
282    /* Runs a single iteration of the dispatch loop.
283     * Nominally processes one queued event, a timeout, or a response from an input consumer.
284     *
285     * This method should only be called on the input dispatcher thread.
286     */
287    virtual void dispatchOnce() = 0;
288
289    /* Injects an input event and optionally waits for sync.
290     * The synchronization mode determines whether the method blocks while waiting for
291     * input injection to proceed.
292     * Returns one of the INPUT_EVENT_INJECTION_XXX constants.
293     *
294     * This method may be called on any thread (usually by the input manager).
295     */
296    virtual int32_t injectInputEvent(const InputEvent* event,
297            int32_t injectorPid, int32_t injectorUid, int32_t syncMode, int32_t timeoutMillis,
298            uint32_t policyFlags) = 0;
299
300    /* Sets the list of input windows.
301     *
302     * This method may be called on any thread (usually by the input manager).
303     */
304    virtual void setInputWindows(const Vector<sp<InputWindowHandle> >& inputWindowHandles) = 0;
305
306    /* Sets the focused application.
307     *
308     * This method may be called on any thread (usually by the input manager).
309     */
310    virtual void setFocusedApplication(
311            const sp<InputApplicationHandle>& inputApplicationHandle) = 0;
312
313    /* Sets the input dispatching mode.
314     *
315     * This method may be called on any thread (usually by the input manager).
316     */
317    virtual void setInputDispatchMode(bool enabled, bool frozen) = 0;
318
319    /* Sets whether input event filtering is enabled.
320     * When enabled, incoming input events are sent to the policy's filterInputEvent
321     * method instead of being dispatched.  The filter is expected to use
322     * injectInputEvent to inject the events it would like to have dispatched.
323     * It should include POLICY_FLAG_FILTERED in the policy flags during injection.
324     */
325    virtual void setInputFilterEnabled(bool enabled) = 0;
326
327    /* Transfers touch focus from the window associated with one channel to the
328     * window associated with the other channel.
329     *
330     * Returns true on success.  False if the window did not actually have touch focus.
331     */
332    virtual bool transferTouchFocus(const sp<InputChannel>& fromChannel,
333            const sp<InputChannel>& toChannel) = 0;
334
335    /* Registers or unregister input channels that may be used as targets for input events.
336     * If monitor is true, the channel will receive a copy of all input events.
337     *
338     * These methods may be called on any thread (usually by the input manager).
339     */
340    virtual status_t registerInputChannel(const sp<InputChannel>& inputChannel,
341            const sp<InputWindowHandle>& inputWindowHandle, bool monitor) = 0;
342    virtual status_t unregisterInputChannel(const sp<InputChannel>& inputChannel) = 0;
343};
344
345/* Dispatches events to input targets.  Some functions of the input dispatcher, such as
346 * identifying input targets, are controlled by a separate policy object.
347 *
348 * IMPORTANT INVARIANT:
349 *     Because the policy can potentially block or cause re-entrance into the input dispatcher,
350 *     the input dispatcher never calls into the policy while holding its internal locks.
351 *     The implementation is also carefully designed to recover from scenarios such as an
352 *     input channel becoming unregistered while identifying input targets or processing timeouts.
353 *
354 *     Methods marked 'Locked' must be called with the lock acquired.
355 *
356 *     Methods marked 'LockedInterruptible' must be called with the lock acquired but
357 *     may during the course of their execution release the lock, call into the policy, and
358 *     then reacquire the lock.  The caller is responsible for recovering gracefully.
359 *
360 *     A 'LockedInterruptible' method may called a 'Locked' method, but NOT vice-versa.
361 */
362class InputDispatcher : public InputDispatcherInterface {
363protected:
364    virtual ~InputDispatcher();
365
366public:
367    explicit InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy);
368
369    virtual void dump(String8& dump);
370    virtual void monitor();
371
372    virtual void dispatchOnce();
373
374    virtual void notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args);
375    virtual void notifyKey(const NotifyKeyArgs* args);
376    virtual void notifyMotion(const NotifyMotionArgs* args);
377    virtual void notifySwitch(const NotifySwitchArgs* args);
378    virtual void notifyDeviceReset(const NotifyDeviceResetArgs* args);
379
380    virtual int32_t injectInputEvent(const InputEvent* event,
381            int32_t injectorPid, int32_t injectorUid, int32_t syncMode, int32_t timeoutMillis,
382            uint32_t policyFlags);
383
384    virtual void setInputWindows(const Vector<sp<InputWindowHandle> >& inputWindowHandles);
385    virtual void setFocusedApplication(const sp<InputApplicationHandle>& inputApplicationHandle);
386    virtual void setInputDispatchMode(bool enabled, bool frozen);
387    virtual void setInputFilterEnabled(bool enabled);
388
389    virtual bool transferTouchFocus(const sp<InputChannel>& fromChannel,
390            const sp<InputChannel>& toChannel);
391
392    virtual status_t registerInputChannel(const sp<InputChannel>& inputChannel,
393            const sp<InputWindowHandle>& inputWindowHandle, bool monitor);
394    virtual status_t unregisterInputChannel(const sp<InputChannel>& inputChannel);
395
396private:
397    template <typename T>
398    struct Link {
399        T* next;
400        T* prev;
401    };
402
403    struct InjectionState {
404        mutable int32_t refCount;
405
406        int32_t injectorPid;
407        int32_t injectorUid;
408        int32_t injectionResult;  // initially INPUT_EVENT_INJECTION_PENDING
409        bool injectionIsAsync; // set to true if injection is not waiting for the result
410        int32_t pendingForegroundDispatches; // the number of foreground dispatches in progress
411
412        InjectionState(int32_t injectorPid, int32_t injectorUid);
413        void release();
414
415    private:
416        ~InjectionState();
417    };
418
419    struct EventEntry : Link<EventEntry> {
420        enum {
421            TYPE_CONFIGURATION_CHANGED,
422            TYPE_DEVICE_RESET,
423            TYPE_KEY,
424            TYPE_MOTION
425        };
426
427        mutable int32_t refCount;
428        int32_t type;
429        nsecs_t eventTime;
430        uint32_t policyFlags;
431        InjectionState* injectionState;
432
433        bool dispatchInProgress; // initially false, set to true while dispatching
434
435        inline bool isInjected() const { return injectionState != NULL; }
436
437        void release();
438
439    protected:
440        EventEntry(int32_t type, nsecs_t eventTime, uint32_t policyFlags);
441        virtual ~EventEntry();
442        void releaseInjectionState();
443    };
444
445    struct ConfigurationChangedEntry : EventEntry {
446        ConfigurationChangedEntry(nsecs_t eventTime);
447
448    protected:
449        virtual ~ConfigurationChangedEntry();
450    };
451
452    struct DeviceResetEntry : EventEntry {
453        int32_t deviceId;
454
455        DeviceResetEntry(nsecs_t eventTime, int32_t deviceId);
456
457    protected:
458        virtual ~DeviceResetEntry();
459    };
460
461    struct KeyEntry : EventEntry {
462        int32_t deviceId;
463        uint32_t source;
464        int32_t action;
465        int32_t flags;
466        int32_t keyCode;
467        int32_t scanCode;
468        int32_t metaState;
469        int32_t repeatCount;
470        nsecs_t downTime;
471
472        bool syntheticRepeat; // set to true for synthetic key repeats
473
474        enum InterceptKeyResult {
475            INTERCEPT_KEY_RESULT_UNKNOWN,
476            INTERCEPT_KEY_RESULT_SKIP,
477            INTERCEPT_KEY_RESULT_CONTINUE,
478            INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER,
479        };
480        InterceptKeyResult interceptKeyResult; // set based on the interception result
481        nsecs_t interceptKeyWakeupTime; // used with INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER
482
483        KeyEntry(nsecs_t eventTime,
484                int32_t deviceId, uint32_t source, uint32_t policyFlags, int32_t action,
485                int32_t flags, int32_t keyCode, int32_t scanCode, int32_t metaState,
486                int32_t repeatCount, nsecs_t downTime);
487        void recycle();
488
489    protected:
490        virtual ~KeyEntry();
491    };
492
493    struct MotionSample {
494        MotionSample* next;
495
496        nsecs_t eventTime; // may be updated during coalescing
497        nsecs_t eventTimeBeforeCoalescing; // not updated during coalescing
498        PointerCoords pointerCoords[MAX_POINTERS];
499
500        MotionSample(nsecs_t eventTime, const PointerCoords* pointerCoords,
501                uint32_t pointerCount);
502    };
503
504    struct MotionEntry : EventEntry {
505        int32_t deviceId;
506        uint32_t source;
507        int32_t action;
508        int32_t flags;
509        int32_t metaState;
510        int32_t buttonState;
511        int32_t edgeFlags;
512        float xPrecision;
513        float yPrecision;
514        nsecs_t downTime;
515        uint32_t pointerCount;
516        PointerProperties pointerProperties[MAX_POINTERS];
517
518        // Linked list of motion samples associated with this motion event.
519        MotionSample firstSample;
520        MotionSample* lastSample;
521
522        MotionEntry(nsecs_t eventTime,
523                int32_t deviceId, uint32_t source, uint32_t policyFlags, int32_t action,
524                int32_t flags, int32_t metaState, int32_t buttonState, int32_t edgeFlags,
525                float xPrecision, float yPrecision,
526                nsecs_t downTime, uint32_t pointerCount,
527                const PointerProperties* pointerProperties, const PointerCoords* pointerCoords);
528
529        uint32_t countSamples() const;
530
531        // Checks whether we can append samples, assuming the device id and source are the same.
532        bool canAppendSamples(int32_t action, uint32_t pointerCount,
533                const PointerProperties* pointerProperties) const;
534
535        void appendSample(nsecs_t eventTime, const PointerCoords* pointerCoords);
536
537    protected:
538        virtual ~MotionEntry();
539    };
540
541    // Tracks the progress of dispatching a particular event to a particular connection.
542    struct DispatchEntry : Link<DispatchEntry> {
543        EventEntry* eventEntry; // the event to dispatch
544        int32_t targetFlags;
545        float xOffset;
546        float yOffset;
547        float scaleFactor;
548
549        // True if dispatch has started.
550        bool inProgress;
551
552        // Set to the resolved action and flags when the event is enqueued.
553        int32_t resolvedAction;
554        int32_t resolvedFlags;
555
556        // For motion events:
557        //   Pointer to the first motion sample to dispatch in this cycle.
558        //   Usually NULL to indicate that the list of motion samples begins at
559        //   MotionEntry::firstSample.  Otherwise, some samples were dispatched in a previous
560        //   cycle and this pointer indicates the location of the first remainining sample
561        //   to dispatch during the current cycle.
562        MotionSample* headMotionSample;
563        //   Pointer to a motion sample to dispatch in the next cycle if the dispatcher was
564        //   unable to send all motion samples during this cycle.  On the next cycle,
565        //   headMotionSample will be initialized to tailMotionSample and tailMotionSample
566        //   will be set to NULL.
567        MotionSample* tailMotionSample;
568
569        DispatchEntry(EventEntry* eventEntry,
570                int32_t targetFlags, float xOffset, float yOffset, float scaleFactor);
571        ~DispatchEntry();
572
573        inline bool hasForegroundTarget() const {
574            return targetFlags & InputTarget::FLAG_FOREGROUND;
575        }
576
577        inline bool isSplit() const {
578            return targetFlags & InputTarget::FLAG_SPLIT;
579        }
580    };
581
582    // A command entry captures state and behavior for an action to be performed in the
583    // dispatch loop after the initial processing has taken place.  It is essentially
584    // a kind of continuation used to postpone sensitive policy interactions to a point
585    // in the dispatch loop where it is safe to release the lock (generally after finishing
586    // the critical parts of the dispatch cycle).
587    //
588    // The special thing about commands is that they can voluntarily release and reacquire
589    // the dispatcher lock at will.  Initially when the command starts running, the
590    // dispatcher lock is held.  However, if the command needs to call into the policy to
591    // do some work, it can release the lock, do the work, then reacquire the lock again
592    // before returning.
593    //
594    // This mechanism is a bit clunky but it helps to preserve the invariant that the dispatch
595    // never calls into the policy while holding its lock.
596    //
597    // Commands are implicitly 'LockedInterruptible'.
598    struct CommandEntry;
599    typedef void (InputDispatcher::*Command)(CommandEntry* commandEntry);
600
601    class Connection;
602    struct CommandEntry : Link<CommandEntry> {
603        CommandEntry(Command command);
604        ~CommandEntry();
605
606        Command command;
607
608        // parameters for the command (usage varies by command)
609        sp<Connection> connection;
610        nsecs_t eventTime;
611        KeyEntry* keyEntry;
612        sp<InputApplicationHandle> inputApplicationHandle;
613        sp<InputWindowHandle> inputWindowHandle;
614        int32_t userActivityEventType;
615        bool handled;
616    };
617
618    // Generic queue implementation.
619    template <typename T>
620    struct Queue {
621        T* head;
622        T* tail;
623
624        inline Queue() : head(NULL), tail(NULL) {
625        }
626
627        inline bool isEmpty() const {
628            return !head;
629        }
630
631        inline void enqueueAtTail(T* entry) {
632            entry->prev = tail;
633            if (tail) {
634                tail->next = entry;
635            } else {
636                head = entry;
637            }
638            entry->next = NULL;
639            tail = entry;
640        }
641
642        inline void enqueueAtHead(T* entry) {
643            entry->next = head;
644            if (head) {
645                head->prev = entry;
646            } else {
647                tail = entry;
648            }
649            entry->prev = NULL;
650            head = entry;
651        }
652
653        inline void dequeue(T* entry) {
654            if (entry->prev) {
655                entry->prev->next = entry->next;
656            } else {
657                head = entry->next;
658            }
659            if (entry->next) {
660                entry->next->prev = entry->prev;
661            } else {
662                tail = entry->prev;
663            }
664        }
665
666        inline T* dequeueAtHead() {
667            T* entry = head;
668            head = entry->next;
669            if (head) {
670                head->prev = NULL;
671            } else {
672                tail = NULL;
673            }
674            return entry;
675        }
676
677        uint32_t count() const;
678    };
679
680    /* Specifies which events are to be canceled and why. */
681    struct CancelationOptions {
682        enum Mode {
683            CANCEL_ALL_EVENTS = 0,
684            CANCEL_POINTER_EVENTS = 1,
685            CANCEL_NON_POINTER_EVENTS = 2,
686            CANCEL_FALLBACK_EVENTS = 3,
687        };
688
689        // The criterion to use to determine which events should be canceled.
690        Mode mode;
691
692        // Descriptive reason for the cancelation.
693        const char* reason;
694
695        // The specific keycode of the key event to cancel, or -1 to cancel any key event.
696        int32_t keyCode;
697
698        // The specific device id of events to cancel, or -1 to cancel events from any device.
699        int32_t deviceId;
700
701        CancelationOptions(Mode mode, const char* reason) :
702                mode(mode), reason(reason), keyCode(-1), deviceId(-1) { }
703    };
704
705    /* Tracks dispatched key and motion event state so that cancelation events can be
706     * synthesized when events are dropped. */
707    class InputState {
708    public:
709        InputState();
710        ~InputState();
711
712        // Returns true if there is no state to be canceled.
713        bool isNeutral() const;
714
715        // Returns true if the specified source is known to have received a hover enter
716        // motion event.
717        bool isHovering(int32_t deviceId, uint32_t source) const;
718
719        // Records tracking information for a key event that has just been published.
720        // Returns true if the event should be delivered, false if it is inconsistent
721        // and should be skipped.
722        bool trackKey(const KeyEntry* entry, int32_t action, int32_t flags);
723
724        // Records tracking information for a motion event that has just been published.
725        // Returns true if the event should be delivered, false if it is inconsistent
726        // and should be skipped.
727        bool trackMotion(const MotionEntry* entry, int32_t action, int32_t flags);
728
729        // Synthesizes cancelation events for the current state and resets the tracked state.
730        void synthesizeCancelationEvents(nsecs_t currentTime,
731                Vector<EventEntry*>& outEvents, const CancelationOptions& options);
732
733        // Clears the current state.
734        void clear();
735
736        // Copies pointer-related parts of the input state to another instance.
737        void copyPointerStateTo(InputState& other) const;
738
739        // Gets the fallback key associated with a keycode.
740        // Returns -1 if none.
741        // Returns AKEYCODE_UNKNOWN if we are only dispatching the unhandled key to the policy.
742        int32_t getFallbackKey(int32_t originalKeyCode);
743
744        // Sets the fallback key for a particular keycode.
745        void setFallbackKey(int32_t originalKeyCode, int32_t fallbackKeyCode);
746
747        // Removes the fallback key for a particular keycode.
748        void removeFallbackKey(int32_t originalKeyCode);
749
750        inline const KeyedVector<int32_t, int32_t>& getFallbackKeys() const {
751            return mFallbackKeys;
752        }
753
754    private:
755        struct KeyMemento {
756            int32_t deviceId;
757            uint32_t source;
758            int32_t keyCode;
759            int32_t scanCode;
760            int32_t flags;
761            nsecs_t downTime;
762        };
763
764        struct MotionMemento {
765            int32_t deviceId;
766            uint32_t source;
767            int32_t flags;
768            float xPrecision;
769            float yPrecision;
770            nsecs_t downTime;
771            uint32_t pointerCount;
772            PointerProperties pointerProperties[MAX_POINTERS];
773            PointerCoords pointerCoords[MAX_POINTERS];
774            bool hovering;
775
776            void setPointers(const MotionEntry* entry);
777        };
778
779        Vector<KeyMemento> mKeyMementos;
780        Vector<MotionMemento> mMotionMementos;
781        KeyedVector<int32_t, int32_t> mFallbackKeys;
782
783        ssize_t findKeyMemento(const KeyEntry* entry) const;
784        ssize_t findMotionMemento(const MotionEntry* entry, bool hovering) const;
785
786        void addKeyMemento(const KeyEntry* entry, int32_t flags);
787        void addMotionMemento(const MotionEntry* entry, int32_t flags, bool hovering);
788
789        static bool shouldCancelKey(const KeyMemento& memento,
790                const CancelationOptions& options);
791        static bool shouldCancelMotion(const MotionMemento& memento,
792                const CancelationOptions& options);
793    };
794
795    /* Manages the dispatch state associated with a single input channel. */
796    class Connection : public RefBase {
797    protected:
798        virtual ~Connection();
799
800    public:
801        enum Status {
802            // Everything is peachy.
803            STATUS_NORMAL,
804            // An unrecoverable communication error has occurred.
805            STATUS_BROKEN,
806            // The input channel has been unregistered.
807            STATUS_ZOMBIE
808        };
809
810        Status status;
811        sp<InputChannel> inputChannel; // never null
812        sp<InputWindowHandle> inputWindowHandle; // may be null
813        bool monitor;
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, bool monitor);
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    Condition mDispatcherIsAliveCondition;
860
861    sp<Looper> mLooper;
862
863    EventEntry* mPendingEvent;
864    Queue<EventEntry> mInboundQueue;
865    Queue<CommandEntry> mCommandQueue;
866
867    Vector<EventEntry*> mTempCancelationEvents;
868
869    void dispatchOnceInnerLocked(nsecs_t* nextWakeupTime);
870    void dispatchIdleLocked();
871
872    // Batches a new sample onto a motion entry.
873    // Assumes that the we have already checked that we can append samples.
874    void batchMotionLocked(MotionEntry* entry, nsecs_t eventTime, int32_t metaState,
875            const PointerCoords* pointerCoords, const char* eventDescription);
876
877    // Enqueues an inbound event.  Returns true if mLooper->wake() should be called.
878    bool enqueueInboundEventLocked(EventEntry* entry);
879
880    // Cleans up input state when dropping an inbound event.
881    void dropInboundEventLocked(EventEntry* entry, DropReason dropReason);
882
883    // App switch latency optimization.
884    bool mAppSwitchSawKeyDown;
885    nsecs_t mAppSwitchDueTime;
886
887    static bool isAppSwitchKeyCode(int32_t keyCode);
888    bool isAppSwitchKeyEventLocked(KeyEntry* keyEntry);
889    bool isAppSwitchPendingLocked();
890    void resetPendingAppSwitchLocked(bool handled);
891
892    // Stale event latency optimization.
893    static bool isStaleEventLocked(nsecs_t currentTime, EventEntry* entry);
894
895    // Blocked event latency optimization.  Drops old events when the user intends
896    // to transfer focus to a new application.
897    EventEntry* mNextUnblockedEvent;
898
899    sp<InputWindowHandle> findTouchedWindowAtLocked(int32_t x, int32_t y);
900
901    // All registered connections mapped by receive pipe file descriptor.
902    KeyedVector<int, sp<Connection> > mConnectionsByReceiveFd;
903
904    ssize_t getConnectionIndexLocked(const sp<InputChannel>& inputChannel);
905
906    // Active connections are connections that have a non-empty outbound queue.
907    // We don't use a ref-counted pointer here because we explicitly abort connections
908    // during unregistration which causes the connection's outbound queue to be cleared
909    // and the connection itself to be deactivated.
910    Vector<Connection*> mActiveConnections;
911
912    // Input channels that will receive a copy of all input events.
913    Vector<sp<InputChannel> > mMonitoringChannels;
914
915    // Event injection and synchronization.
916    Condition mInjectionResultAvailableCondition;
917    bool hasInjectionPermission(int32_t injectorPid, int32_t injectorUid);
918    void setInjectionResultLocked(EventEntry* entry, int32_t injectionResult);
919
920    Condition mInjectionSyncFinishedCondition;
921    void incrementPendingForegroundDispatchesLocked(EventEntry* entry);
922    void decrementPendingForegroundDispatchesLocked(EventEntry* entry);
923
924    // Key repeat tracking.
925    struct KeyRepeatState {
926        KeyEntry* lastKeyEntry; // or null if no repeat
927        nsecs_t nextRepeatTime;
928    } mKeyRepeatState;
929
930    void resetKeyRepeatLocked();
931    KeyEntry* synthesizeKeyRepeatLocked(nsecs_t currentTime);
932
933    // Deferred command processing.
934    bool runCommandsLockedInterruptible();
935    CommandEntry* postCommandLocked(Command command);
936
937    // Inbound event processing.
938    void drainInboundQueueLocked();
939    void releasePendingEventLocked();
940    void releaseInboundEventLocked(EventEntry* entry);
941
942    // Dispatch state.
943    bool mDispatchEnabled;
944    bool mDispatchFrozen;
945    bool mInputFilterEnabled;
946
947    Vector<sp<InputWindowHandle> > mWindowHandles;
948
949    sp<InputWindowHandle> getWindowHandleLocked(const sp<InputChannel>& inputChannel) const;
950    bool hasWindowHandleLocked(const sp<InputWindowHandle>& windowHandle) const;
951
952    // Focus tracking for keys, trackball, etc.
953    sp<InputWindowHandle> mFocusedWindowHandle;
954
955    // Focus tracking for touch.
956    struct TouchedWindow {
957        sp<InputWindowHandle> windowHandle;
958        int32_t targetFlags;
959        BitSet32 pointerIds;        // zero unless target flag FLAG_SPLIT is set
960    };
961    struct TouchState {
962        bool down;
963        bool split;
964        int32_t deviceId; // id of the device that is currently down, others are rejected
965        uint32_t source;  // source of the device that is current down, others are rejected
966        Vector<TouchedWindow> windows;
967
968        TouchState();
969        ~TouchState();
970        void reset();
971        void copyFrom(const TouchState& other);
972        void addOrUpdateWindow(const sp<InputWindowHandle>& windowHandle,
973                int32_t targetFlags, BitSet32 pointerIds);
974        void filterNonAsIsTouchWindows();
975        sp<InputWindowHandle> getFirstForegroundWindowHandle() const;
976        bool isSlippery() const;
977    };
978
979    TouchState mTouchState;
980    TouchState mTempTouchState;
981
982    // Focused application.
983    sp<InputApplicationHandle> mFocusedApplicationHandle;
984
985    // Dispatch inbound events.
986    bool dispatchConfigurationChangedLocked(
987            nsecs_t currentTime, ConfigurationChangedEntry* entry);
988    bool dispatchDeviceResetLocked(
989            nsecs_t currentTime, DeviceResetEntry* entry);
990    bool dispatchKeyLocked(
991            nsecs_t currentTime, KeyEntry* entry,
992            DropReason* dropReason, nsecs_t* nextWakeupTime);
993    bool dispatchMotionLocked(
994            nsecs_t currentTime, MotionEntry* entry,
995            DropReason* dropReason, nsecs_t* nextWakeupTime);
996    void dispatchEventToCurrentInputTargetsLocked(
997            nsecs_t currentTime, EventEntry* entry, bool resumeWithAppendedMotionSample);
998
999    void logOutboundKeyDetailsLocked(const char* prefix, const KeyEntry* entry);
1000    void logOutboundMotionDetailsLocked(const char* prefix, const MotionEntry* entry);
1001
1002    // The input targets that were most recently identified for dispatch.
1003    bool mCurrentInputTargetsValid; // false while targets are being recomputed
1004    Vector<InputTarget> mCurrentInputTargets;
1005
1006    enum InputTargetWaitCause {
1007        INPUT_TARGET_WAIT_CAUSE_NONE,
1008        INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY,
1009        INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY,
1010    };
1011
1012    InputTargetWaitCause mInputTargetWaitCause;
1013    nsecs_t mInputTargetWaitStartTime;
1014    nsecs_t mInputTargetWaitTimeoutTime;
1015    bool mInputTargetWaitTimeoutExpired;
1016    sp<InputApplicationHandle> mInputTargetWaitApplicationHandle;
1017
1018    // Contains the last window which received a hover event.
1019    sp<InputWindowHandle> mLastHoverWindowHandle;
1020
1021    // Finding targets for input events.
1022    void resetTargetsLocked();
1023    void commitTargetsLocked();
1024    int32_t handleTargetsNotReadyLocked(nsecs_t currentTime, const EventEntry* entry,
1025            const sp<InputApplicationHandle>& applicationHandle,
1026            const sp<InputWindowHandle>& windowHandle,
1027            nsecs_t* nextWakeupTime);
1028    void resumeAfterTargetsNotReadyTimeoutLocked(nsecs_t newTimeout,
1029            const sp<InputChannel>& inputChannel);
1030    nsecs_t getTimeSpentWaitingForApplicationLocked(nsecs_t currentTime);
1031    void resetANRTimeoutsLocked();
1032
1033    int32_t findFocusedWindowTargetsLocked(nsecs_t currentTime, const EventEntry* entry,
1034            nsecs_t* nextWakeupTime);
1035    int32_t findTouchedWindowTargetsLocked(nsecs_t currentTime, const MotionEntry* entry,
1036            nsecs_t* nextWakeupTime, bool* outConflictingPointerActions,
1037            const MotionSample** outSplitBatchAfterSample);
1038
1039    void addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
1040            int32_t targetFlags, BitSet32 pointerIds);
1041    void addMonitoringTargetsLocked();
1042    void pokeUserActivityLocked(const EventEntry* eventEntry);
1043    bool checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
1044            const InjectionState* injectionState);
1045    bool isWindowObscuredAtPointLocked(const sp<InputWindowHandle>& windowHandle,
1046            int32_t x, int32_t y) const;
1047    bool isWindowFinishedWithPreviousInputLocked(const sp<InputWindowHandle>& windowHandle);
1048    String8 getApplicationWindowLabelLocked(const sp<InputApplicationHandle>& applicationHandle,
1049            const sp<InputWindowHandle>& windowHandle);
1050
1051    // Manage the dispatch cycle for a single connection.
1052    // These methods are deliberately not Interruptible because doing all of the work
1053    // with the mutex held makes it easier to ensure that connection invariants are maintained.
1054    // If needed, the methods post commands to run later once the critical bits are done.
1055    void prepareDispatchCycleLocked(nsecs_t currentTime, const sp<Connection>& connection,
1056            EventEntry* eventEntry, const InputTarget* inputTarget,
1057            bool resumeWithAppendedMotionSample);
1058    void enqueueDispatchEntriesLocked(nsecs_t currentTime, const sp<Connection>& connection,
1059            EventEntry* eventEntry, const InputTarget* inputTarget,
1060            bool resumeWithAppendedMotionSample);
1061    void enqueueDispatchEntryLocked(const sp<Connection>& connection,
1062            EventEntry* eventEntry, const InputTarget* inputTarget,
1063            bool resumeWithAppendedMotionSample, int32_t dispatchMode);
1064    void startDispatchCycleLocked(nsecs_t currentTime, const sp<Connection>& connection);
1065    void finishDispatchCycleLocked(nsecs_t currentTime, const sp<Connection>& connection,
1066            bool handled);
1067    void startNextDispatchCycleLocked(nsecs_t currentTime, const sp<Connection>& connection);
1068    void abortBrokenDispatchCycleLocked(nsecs_t currentTime, const sp<Connection>& connection,
1069            bool notify);
1070    void drainOutboundQueueLocked(Connection* connection);
1071    static int handleReceiveCallback(int receiveFd, int events, void* data);
1072
1073    void synthesizeCancelationEventsForAllConnectionsLocked(
1074            const CancelationOptions& options);
1075    void synthesizeCancelationEventsForInputChannelLocked(const sp<InputChannel>& channel,
1076            const CancelationOptions& options);
1077    void synthesizeCancelationEventsForConnectionLocked(const sp<Connection>& connection,
1078            const CancelationOptions& options);
1079
1080    // Splitting motion events across windows.
1081    MotionEntry* splitMotionEvent(const MotionEntry* originalMotionEntry, BitSet32 pointerIds);
1082
1083    // Reset and drop everything the dispatcher is doing.
1084    void resetAndDropEverythingLocked(const char* reason);
1085
1086    // Dump state.
1087    void dumpDispatchStateLocked(String8& dump);
1088    void logDispatchStateLocked();
1089
1090    // Registration.
1091    void removeMonitorChannelLocked(const sp<InputChannel>& inputChannel);
1092    status_t unregisterInputChannelLocked(const sp<InputChannel>& inputChannel, bool notify);
1093
1094    // Add or remove a connection to the mActiveConnections vector.
1095    void activateConnectionLocked(Connection* connection);
1096    void deactivateConnectionLocked(Connection* connection);
1097
1098    // Interesting events that we might like to log or tell the framework about.
1099    void onDispatchCycleStartedLocked(
1100            nsecs_t currentTime, const sp<Connection>& connection);
1101    void onDispatchCycleFinishedLocked(
1102            nsecs_t currentTime, const sp<Connection>& connection, bool handled);
1103    void onDispatchCycleBrokenLocked(
1104            nsecs_t currentTime, const sp<Connection>& connection);
1105    void onANRLocked(
1106            nsecs_t currentTime, const sp<InputApplicationHandle>& applicationHandle,
1107            const sp<InputWindowHandle>& windowHandle,
1108            nsecs_t eventTime, nsecs_t waitStartTime);
1109
1110    // Outbound policy interactions.
1111    void doNotifyConfigurationChangedInterruptible(CommandEntry* commandEntry);
1112    void doNotifyInputChannelBrokenLockedInterruptible(CommandEntry* commandEntry);
1113    void doNotifyANRLockedInterruptible(CommandEntry* commandEntry);
1114    void doInterceptKeyBeforeDispatchingLockedInterruptible(CommandEntry* commandEntry);
1115    void doDispatchCycleFinishedLockedInterruptible(CommandEntry* commandEntry);
1116    bool afterKeyEventLockedInterruptible(const sp<Connection>& connection,
1117            DispatchEntry* dispatchEntry, KeyEntry* keyEntry, bool handled);
1118    bool afterMotionEventLockedInterruptible(const sp<Connection>& connection,
1119            DispatchEntry* dispatchEntry, MotionEntry* motionEntry, bool handled);
1120    void doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry);
1121    void initializeKeyEvent(KeyEvent* event, const KeyEntry* entry);
1122
1123    // Statistics gathering.
1124    void updateDispatchStatisticsLocked(nsecs_t currentTime, const EventEntry* entry,
1125            int32_t injectionResult, nsecs_t timeSpentWaitingForApplication);
1126};
1127
1128/* Enqueues and dispatches input events, endlessly. */
1129class InputDispatcherThread : public Thread {
1130public:
1131    explicit InputDispatcherThread(const sp<InputDispatcherInterface>& dispatcher);
1132    ~InputDispatcherThread();
1133
1134private:
1135    virtual bool threadLoop();
1136
1137    sp<InputDispatcherInterface> mDispatcher;
1138};
1139
1140} // namespace android
1141
1142#endif // _UI_INPUT_DISPATCHER_H
1143