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