InputDispatcher.h revision 928e054931d357326613c78e62f4d850b7c442ff
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 generic touch, trackball or other 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 interceptGenericBeforeQueueing(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, int32_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, int32_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, int32_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, int32_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        int32_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        int32_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, int32_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, int32_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 whether a given event will violate input state consistency.
597        enum Consistency {
598            // The event is consistent with the current input state.
599            CONSISTENT,
600            // The event is inconsistent with the current input state but applications
601            // will tolerate it.  eg. Down followed by another down.
602            TOLERABLE,
603            // The event is inconsistent with the current input state and will probably
604            // cause applications to crash.  eg. Up without prior down, move with
605            // unexpected number of pointers.
606            BROKEN
607        };
608
609        // Specifies the sources to cancel.
610        enum CancelationOptions {
611            CANCEL_ALL_EVENTS = 0,
612            CANCEL_POINTER_EVENTS = 1,
613            CANCEL_NON_POINTER_EVENTS = 2,
614            CANCEL_FALLBACK_EVENTS = 3,
615        };
616
617        InputState();
618        ~InputState();
619
620        // Returns true if there is no state to be canceled.
621        bool isNeutral() const;
622
623        // Records tracking information for an event that has just been published.
624        // Returns whether the event is consistent with the current input state.
625        Consistency trackEvent(const EventEntry* entry);
626
627        // Records tracking information for a key event that has just been published.
628        // Returns whether the event is consistent with the current input state.
629        Consistency trackKey(const KeyEntry* entry);
630
631        // Records tracking information for a motion event that has just been published.
632        // Returns whether the event is consistent with the current input state.
633        Consistency trackMotion(const MotionEntry* entry);
634
635        // Synthesizes cancelation events for the current state and resets the tracked state.
636        void synthesizeCancelationEvents(nsecs_t currentTime, Allocator* allocator,
637                Vector<EventEntry*>& outEvents, CancelationOptions options);
638
639        // Clears the current state.
640        void clear();
641
642        // Copies pointer-related parts of the input state to another instance.
643        void copyPointerStateTo(InputState& other) const;
644
645    private:
646        struct KeyMemento {
647            int32_t deviceId;
648            int32_t source;
649            int32_t keyCode;
650            int32_t scanCode;
651            int32_t flags;
652            nsecs_t downTime;
653        };
654
655        struct MotionMemento {
656            int32_t deviceId;
657            int32_t source;
658            float xPrecision;
659            float yPrecision;
660            nsecs_t downTime;
661            uint32_t pointerCount;
662            int32_t pointerIds[MAX_POINTERS];
663            PointerCoords pointerCoords[MAX_POINTERS];
664
665            void setPointers(const MotionEntry* entry);
666        };
667
668        Vector<KeyMemento> mKeyMementos;
669        Vector<MotionMemento> mMotionMementos;
670
671        static bool shouldCancelKey(const KeyMemento& memento,
672                CancelationOptions options);
673        static bool shouldCancelMotion(const MotionMemento& memento,
674                CancelationOptions options);
675    };
676
677    /* Manages the dispatch state associated with a single input channel. */
678    class Connection : public RefBase {
679    protected:
680        virtual ~Connection();
681
682    public:
683        enum Status {
684            // Everything is peachy.
685            STATUS_NORMAL,
686            // An unrecoverable communication error has occurred.
687            STATUS_BROKEN,
688            // The input channel has been unregistered.
689            STATUS_ZOMBIE
690        };
691
692        Status status;
693        sp<InputChannel> inputChannel; // never null
694        sp<InputWindowHandle> inputWindowHandle; // may be null
695        InputPublisher inputPublisher;
696        InputState inputState;
697        Queue<DispatchEntry> outboundQueue;
698
699        nsecs_t lastEventTime; // the time when the event was originally captured
700        nsecs_t lastDispatchTime; // the time when the last event was dispatched
701
702        explicit Connection(const sp<InputChannel>& inputChannel,
703                const sp<InputWindowHandle>& inputWindowHandle);
704
705        inline const char* getInputChannelName() const { return inputChannel->getName().string(); }
706
707        const char* getStatusLabel() const;
708
709        // Finds a DispatchEntry in the outbound queue associated with the specified event.
710        // Returns NULL if not found.
711        DispatchEntry* findQueuedDispatchEntryForEvent(const EventEntry* eventEntry) const;
712
713        // Gets the time since the current event was originally obtained from the input driver.
714        inline double getEventLatencyMillis(nsecs_t currentTime) const {
715            return (currentTime - lastEventTime) / 1000000.0;
716        }
717
718        // Gets the time since the current event entered the outbound dispatch queue.
719        inline double getDispatchLatencyMillis(nsecs_t currentTime) const {
720            return (currentTime - lastDispatchTime) / 1000000.0;
721        }
722
723        status_t initialize();
724    };
725
726    enum DropReason {
727        DROP_REASON_NOT_DROPPED = 0,
728        DROP_REASON_POLICY = 1,
729        DROP_REASON_APP_SWITCH = 2,
730        DROP_REASON_DISABLED = 3,
731        DROP_REASON_BLOCKED = 4,
732        DROP_REASON_STALE = 5,
733    };
734
735    sp<InputDispatcherPolicyInterface> mPolicy;
736
737    Mutex mLock;
738
739    Allocator mAllocator;
740    sp<Looper> mLooper;
741
742    EventEntry* mPendingEvent;
743    Queue<EventEntry> mInboundQueue;
744    Queue<CommandEntry> mCommandQueue;
745
746    Vector<EventEntry*> mTempCancelationEvents;
747
748    void dispatchOnceInnerLocked(nsecs_t keyRepeatTimeout, nsecs_t keyRepeatDelay,
749            nsecs_t* nextWakeupTime);
750
751    // Enqueues an inbound event.  Returns true if mLooper->wake() should be called.
752    bool enqueueInboundEventLocked(EventEntry* entry);
753
754    // Cleans up input state when dropping an inbound event.
755    void dropInboundEventLocked(EventEntry* entry, DropReason dropReason);
756
757    // App switch latency optimization.
758    bool mAppSwitchSawKeyDown;
759    nsecs_t mAppSwitchDueTime;
760
761    static bool isAppSwitchKeyCode(int32_t keyCode);
762    bool isAppSwitchKeyEventLocked(KeyEntry* keyEntry);
763    bool isAppSwitchPendingLocked();
764    void resetPendingAppSwitchLocked(bool handled);
765
766    // Stale event latency optimization.
767    static bool isStaleEventLocked(nsecs_t currentTime, EventEntry* entry);
768
769    // Blocked event latency optimization.  Drops old events when the user intends
770    // to transfer focus to a new application.
771    EventEntry* mNextUnblockedEvent;
772
773    const InputWindow* findTouchedWindowAtLocked(int32_t x, int32_t y);
774
775    // All registered connections mapped by receive pipe file descriptor.
776    KeyedVector<int, sp<Connection> > mConnectionsByReceiveFd;
777
778    ssize_t getConnectionIndexLocked(const sp<InputChannel>& inputChannel);
779
780    // Active connections are connections that have a non-empty outbound queue.
781    // We don't use a ref-counted pointer here because we explicitly abort connections
782    // during unregistration which causes the connection's outbound queue to be cleared
783    // and the connection itself to be deactivated.
784    Vector<Connection*> mActiveConnections;
785
786    // Input channels that will receive a copy of all input events.
787    Vector<sp<InputChannel> > mMonitoringChannels;
788
789    // Event injection and synchronization.
790    Condition mInjectionResultAvailableCondition;
791    bool hasInjectionPermission(int32_t injectorPid, int32_t injectorUid);
792    void setInjectionResultLocked(EventEntry* entry, int32_t injectionResult);
793
794    Condition mInjectionSyncFinishedCondition;
795    void incrementPendingForegroundDispatchesLocked(EventEntry* entry);
796    void decrementPendingForegroundDispatchesLocked(EventEntry* entry);
797
798    // Throttling state.
799    struct ThrottleState {
800        nsecs_t minTimeBetweenEvents;
801
802        nsecs_t lastEventTime;
803        int32_t lastDeviceId;
804        uint32_t lastSource;
805
806        uint32_t originalSampleCount; // only collected during debugging
807    } mThrottleState;
808
809    // Key repeat tracking.
810    struct KeyRepeatState {
811        KeyEntry* lastKeyEntry; // or null if no repeat
812        nsecs_t nextRepeatTime;
813    } mKeyRepeatState;
814
815    void resetKeyRepeatLocked();
816    KeyEntry* synthesizeKeyRepeatLocked(nsecs_t currentTime, nsecs_t keyRepeatTimeout);
817
818    // Deferred command processing.
819    bool runCommandsLockedInterruptible();
820    CommandEntry* postCommandLocked(Command command);
821
822    // Inbound event processing.
823    void drainInboundQueueLocked();
824    void releasePendingEventLocked();
825    void releaseInboundEventLocked(EventEntry* entry);
826
827    // Dispatch state.
828    bool mDispatchEnabled;
829    bool mDispatchFrozen;
830
831    Vector<InputWindow> mWindows;
832
833    const InputWindow* getWindowLocked(const sp<InputChannel>& inputChannel);
834
835    // Focus tracking for keys, trackball, etc.
836    const InputWindow* mFocusedWindow;
837
838    // Focus tracking for touch.
839    struct TouchedWindow {
840        const InputWindow* window;
841        int32_t targetFlags;
842        BitSet32 pointerIds;        // zero unless target flag FLAG_SPLIT is set
843        sp<InputChannel> channel;
844    };
845    struct TouchState {
846        bool down;
847        bool split;
848        int32_t deviceId; // id of the device that is currently down, others are rejected
849        Vector<TouchedWindow> windows;
850
851        TouchState();
852        ~TouchState();
853        void reset();
854        void copyFrom(const TouchState& other);
855        void addOrUpdateWindow(const InputWindow* window, int32_t targetFlags, BitSet32 pointerIds);
856        void removeOutsideTouchWindows();
857        const InputWindow* getFirstForegroundWindow();
858    };
859
860    TouchState mTouchState;
861    TouchState mTempTouchState;
862
863    // Focused application.
864    InputApplication* mFocusedApplication;
865    InputApplication mFocusedApplicationStorage; // preallocated storage for mFocusedApplication
866    void releaseFocusedApplicationLocked();
867
868    // Dispatch inbound events.
869    bool dispatchConfigurationChangedLocked(
870            nsecs_t currentTime, ConfigurationChangedEntry* entry);
871    bool dispatchKeyLocked(
872            nsecs_t currentTime, KeyEntry* entry, nsecs_t keyRepeatTimeout,
873            DropReason* dropReason, nsecs_t* nextWakeupTime);
874    bool dispatchMotionLocked(
875            nsecs_t currentTime, MotionEntry* entry,
876            DropReason* dropReason, nsecs_t* nextWakeupTime);
877    void dispatchEventToCurrentInputTargetsLocked(
878            nsecs_t currentTime, EventEntry* entry, bool resumeWithAppendedMotionSample);
879
880    void logOutboundKeyDetailsLocked(const char* prefix, const KeyEntry* entry);
881    void logOutboundMotionDetailsLocked(const char* prefix, const MotionEntry* entry);
882
883    // The input targets that were most recently identified for dispatch.
884    bool mCurrentInputTargetsValid; // false while targets are being recomputed
885    Vector<InputTarget> mCurrentInputTargets;
886
887    enum InputTargetWaitCause {
888        INPUT_TARGET_WAIT_CAUSE_NONE,
889        INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY,
890        INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY,
891    };
892
893    InputTargetWaitCause mInputTargetWaitCause;
894    nsecs_t mInputTargetWaitStartTime;
895    nsecs_t mInputTargetWaitTimeoutTime;
896    bool mInputTargetWaitTimeoutExpired;
897    sp<InputApplicationHandle> mInputTargetWaitApplication;
898
899    // Finding targets for input events.
900    void resetTargetsLocked();
901    void commitTargetsLocked();
902    int32_t handleTargetsNotReadyLocked(nsecs_t currentTime, const EventEntry* entry,
903            const InputApplication* application, const InputWindow* window,
904            nsecs_t* nextWakeupTime);
905    void resumeAfterTargetsNotReadyTimeoutLocked(nsecs_t newTimeout,
906            const sp<InputChannel>& inputChannel);
907    nsecs_t getTimeSpentWaitingForApplicationLocked(nsecs_t currentTime);
908    void resetANRTimeoutsLocked();
909
910    int32_t findFocusedWindowTargetsLocked(nsecs_t currentTime, const EventEntry* entry,
911            nsecs_t* nextWakeupTime);
912    int32_t findTouchedWindowTargetsLocked(nsecs_t currentTime, const MotionEntry* entry,
913            nsecs_t* nextWakeupTime);
914
915    void addWindowTargetLocked(const InputWindow* window, int32_t targetFlags,
916            BitSet32 pointerIds);
917    void addMonitoringTargetsLocked();
918    void pokeUserActivityLocked(const EventEntry* eventEntry);
919    bool checkInjectionPermission(const InputWindow* window, const InjectionState* injectionState);
920    bool isWindowObscuredAtPointLocked(const InputWindow* window, int32_t x, int32_t y) const;
921    bool isWindowFinishedWithPreviousInputLocked(const InputWindow* window);
922    String8 getApplicationWindowLabelLocked(const InputApplication* application,
923            const InputWindow* window);
924
925    // Manage the dispatch cycle for a single connection.
926    // These methods are deliberately not Interruptible because doing all of the work
927    // with the mutex held makes it easier to ensure that connection invariants are maintained.
928    // If needed, the methods post commands to run later once the critical bits are done.
929    void prepareDispatchCycleLocked(nsecs_t currentTime, const sp<Connection>& connection,
930            EventEntry* eventEntry, const InputTarget* inputTarget,
931            bool resumeWithAppendedMotionSample);
932    void startDispatchCycleLocked(nsecs_t currentTime, const sp<Connection>& connection);
933    void finishDispatchCycleLocked(nsecs_t currentTime, const sp<Connection>& connection,
934            bool handled);
935    void startNextDispatchCycleLocked(nsecs_t currentTime, const sp<Connection>& connection);
936    void abortBrokenDispatchCycleLocked(nsecs_t currentTime, const sp<Connection>& connection);
937    void drainOutboundQueueLocked(Connection* connection);
938    static int handleReceiveCallback(int receiveFd, int events, void* data);
939
940    void synthesizeCancelationEventsForAllConnectionsLocked(
941            InputState::CancelationOptions options, const char* reason);
942    void synthesizeCancelationEventsForInputChannelLocked(const sp<InputChannel>& channel,
943            InputState::CancelationOptions options, const char* reason);
944    void synthesizeCancelationEventsForConnectionLocked(const sp<Connection>& connection,
945            InputState::CancelationOptions options, const char* reason);
946
947    // Splitting motion events across windows.
948    MotionEntry* splitMotionEvent(const MotionEntry* originalMotionEntry, BitSet32 pointerIds);
949
950    // Reset and drop everything the dispatcher is doing.
951    void resetAndDropEverythingLocked(const char* reason);
952
953    // Dump state.
954    void dumpDispatchStateLocked(String8& dump);
955    void logDispatchStateLocked();
956
957    // Add or remove a connection to the mActiveConnections vector.
958    void activateConnectionLocked(Connection* connection);
959    void deactivateConnectionLocked(Connection* connection);
960
961    // Interesting events that we might like to log or tell the framework about.
962    void onDispatchCycleStartedLocked(
963            nsecs_t currentTime, const sp<Connection>& connection);
964    void onDispatchCycleFinishedLocked(
965            nsecs_t currentTime, const sp<Connection>& connection, bool handled);
966    void onDispatchCycleBrokenLocked(
967            nsecs_t currentTime, const sp<Connection>& connection);
968    void onANRLocked(
969            nsecs_t currentTime, const InputApplication* application, const InputWindow* window,
970            nsecs_t eventTime, nsecs_t waitStartTime);
971
972    // Outbound policy interactions.
973    void doNotifyConfigurationChangedInterruptible(CommandEntry* commandEntry);
974    void doNotifyInputChannelBrokenLockedInterruptible(CommandEntry* commandEntry);
975    void doNotifyANRLockedInterruptible(CommandEntry* commandEntry);
976    void doInterceptKeyBeforeDispatchingLockedInterruptible(CommandEntry* commandEntry);
977    void doDispatchCycleFinishedLockedInterruptible(CommandEntry* commandEntry);
978    void doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry);
979    void initializeKeyEvent(KeyEvent* event, const KeyEntry* entry);
980
981    // Statistics gathering.
982    void updateDispatchStatisticsLocked(nsecs_t currentTime, const EventEntry* entry,
983            int32_t injectionResult, nsecs_t timeSpentWaitingForApplication);
984};
985
986/* Enqueues and dispatches input events, endlessly. */
987class InputDispatcherThread : public Thread {
988public:
989    explicit InputDispatcherThread(const sp<InputDispatcherInterface>& dispatcher);
990    ~InputDispatcherThread();
991
992private:
993    virtual bool threadLoop();
994
995    sp<InputDispatcherInterface> mDispatcher;
996};
997
998} // namespace android
999
1000#endif // _UI_INPUT_DISPATCHER_H
1001