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