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