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