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