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