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