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