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