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