Added more robust tracking and cancelation of events.

This change fixes several issues where events would be dropped in the
input dispatch pipeline in such a way that the dispatcher could not
accurately track the state of the input device.

Given more robust tracking, we can now also provide robust cancelation
of input events in cases where an application might otherwise become
out of sync with the event stream due to ANR, app switch, policy decisions,
or forced focus transitions.

Pruned some of the input dispatcher log output.

Moved the responsibility for calling intercept*BeforeQueueing into
the input dispatcher instead of the input reader and added support for
early interception of injected events for events coming from trusted
sources.  This enables behaviors like injection of media keys while
the screen is off, haptic feedback of injected virtual keys, so injected
events become more "first class" in a way.

Change-Id: Iec6ff1dd21e5f3c7feb80ea4feb5382bd090dbd9
diff --git a/include/ui/Input.h b/include/ui/Input.h
index ee40b85..66061fd 100644
--- a/include/ui/Input.h
+++ b/include/ui/Input.h
@@ -71,6 +71,8 @@
 /*
  * Flags that flow alongside events in the input dispatch system to help with certain
  * policy decisions such as waking from device sleep.
+ *
+ * These flags are also defined in frameworks/base/core/java/android/view/WindowManagerPolicy.java.
  */
 enum {
     /* These flags originate in RawEvents and are generally set in the key map.
@@ -102,6 +104,11 @@
     // Indicates that the screen was dim when the event was received and the event
     // should brighten the device.
     POLICY_FLAG_BRIGHT_HERE = 0x20000000,
+
+    // Indicates that the event should be dispatched to applications.
+    // The input event should still be sent to the InputDispatcher so that it can see all
+    // input events received include those that it will not deliver.
+    POLICY_FLAG_PASS_TO_USER = 0x40000000,
 };
 
 /*
diff --git a/include/ui/InputDispatcher.h b/include/ui/InputDispatcher.h
index 47c5326..0834e86 100644
--- a/include/ui/InputDispatcher.h
+++ b/include/ui/InputDispatcher.h
@@ -282,10 +282,35 @@
      */
     virtual int32_t getMaxEventsPerSecond() = 0;
 
+    /* Intercepts a key event immediately before queueing it.
+     * The policy can use this method as an opportunity to perform power management functions
+     * and early event preprocessing such as updating policy flags.
+     *
+     * This method is expected to set the POLICY_FLAG_PASS_TO_USER policy flag if the event
+     * should be dispatched to applications.
+     */
+    virtual void interceptKeyBeforeQueueing(nsecs_t when, int32_t deviceId,
+            int32_t action, int32_t& flags, int32_t keyCode, int32_t scanCode,
+            uint32_t& policyFlags) = 0;
+
+    /* Intercepts a generic touch, trackball or other event before queueing it.
+     * The policy can use this method as an opportunity to perform power management functions
+     * and early event preprocessing such as updating policy flags.
+     *
+     * This method is expected to set the POLICY_FLAG_PASS_TO_USER policy flag if the event
+     * should be dispatched to applications.
+     */
+    virtual void interceptGenericBeforeQueueing(nsecs_t when, uint32_t& policyFlags) = 0;
+
     /* Allows the policy a chance to intercept a key before dispatching. */
     virtual bool interceptKeyBeforeDispatching(const sp<InputChannel>& inputChannel,
             const KeyEvent* keyEvent, uint32_t policyFlags) = 0;
 
+    /* Notifies the policy about switch events.
+     */
+    virtual void notifySwitch(nsecs_t when,
+            int32_t switchCode, int32_t switchValue, uint32_t policyFlags) = 0;
+
     /* Poke user activity for an event dispatched to a window. */
     virtual void pokeUserActivity(nsecs_t eventTime, int32_t eventType) = 0;
 
@@ -333,6 +358,8 @@
             int32_t metaState, int32_t edgeFlags,
             uint32_t pointerCount, const int32_t* pointerIds, const PointerCoords* pointerCoords,
             float xPrecision, float yPrecision, nsecs_t downTime) = 0;
+    virtual void notifySwitch(nsecs_t when,
+            int32_t switchCode, int32_t switchValue, uint32_t policyFlags) = 0;
 
     /* Injects an input event and optionally waits for sync.
      * The synchronization mode determines whether the method blocks while waiting for
@@ -408,6 +435,8 @@
             int32_t metaState, int32_t edgeFlags,
             uint32_t pointerCount, const int32_t* pointerIds, const PointerCoords* pointerCoords,
             float xPrecision, float yPrecision, nsecs_t downTime);
+    virtual void notifySwitch(nsecs_t when,
+            int32_t switchCode, int32_t switchValue, uint32_t policyFlags) ;
 
     virtual int32_t injectInputEvent(const InputEvent* event,
             int32_t injectorPid, int32_t injectorUid, int32_t syncMode, int32_t timeoutMillis);
@@ -447,6 +476,7 @@
         mutable int32_t refCount;
         int32_t type;
         nsecs_t eventTime;
+        uint32_t policyFlags;
         InjectionState* injectionState;
 
         bool dispatchInProgress; // initially false, set to true while dispatching
@@ -460,7 +490,6 @@
     struct KeyEntry : EventEntry {
         int32_t deviceId;
         int32_t source;
-        uint32_t policyFlags;
         int32_t action;
         int32_t flags;
         int32_t keyCode;
@@ -489,7 +518,6 @@
     struct MotionEntry : EventEntry {
         int32_t deviceId;
         int32_t source;
-        uint32_t policyFlags;
         int32_t action;
         int32_t flags;
         int32_t metaState;
@@ -664,7 +692,8 @@
         Pool<DispatchEntry> mDispatchEntryPool;
         Pool<CommandEntry> mCommandEntryPool;
 
-        void initializeEventEntry(EventEntry* entry, int32_t type, nsecs_t eventTime);
+        void initializeEventEntry(EventEntry* entry, int32_t type, nsecs_t eventTime,
+                uint32_t policyFlags);
         void releaseEventEntryInjectionState(EventEntry* entry);
     };
 
@@ -685,21 +714,19 @@
             BROKEN
         };
 
+        // Specifies the sources to cancel.
+        enum CancelationOptions {
+            CANCEL_ALL_EVENTS = 0,
+            CANCEL_POINTER_EVENTS = 1,
+            CANCEL_NON_POINTER_EVENTS = 2,
+        };
+
         InputState();
         ~InputState();
 
         // Returns true if there is no state to be canceled.
         bool isNeutral() const;
 
-        // Returns true if the input state believes it is out of sync.
-        bool isOutOfSync() const;
-
-        // Sets the input state to be out of sync if it is not neutral.
-        void setOutOfSync();
-
-        // Resets the input state out of sync flag.
-        void resetOutOfSync();
-
         // Records tracking information for an event that has just been published.
         // Returns whether the event is consistent with the current input state.
         Consistency trackEvent(const EventEntry* entry);
@@ -712,16 +739,14 @@
         // Returns whether the event is consistent with the current input state.
         Consistency trackMotion(const MotionEntry* entry);
 
-        // Synthesizes cancelation events for the current state.
-        void synthesizeCancelationEvents(Allocator* allocator,
-                Vector<EventEntry*>& outEvents) const;
+        // Synthesizes cancelation events for the current state and resets the tracked state.
+        void synthesizeCancelationEvents(nsecs_t currentTime, Allocator* allocator,
+                Vector<EventEntry*>& outEvents, CancelationOptions options);
 
         // Clears the current state.
         void clear();
 
     private:
-        bool mIsOutOfSync;
-
         struct KeyMemento {
             int32_t deviceId;
             int32_t source;
@@ -745,6 +770,8 @@
 
         Vector<KeyMemento> mKeyMementos;
         Vector<MotionMemento> mMotionMementos;
+
+        static bool shouldCancelEvent(int32_t eventSource, CancelationOptions options);
     };
 
     /* Manages the dispatch state associated with a single input channel. */
@@ -794,6 +821,13 @@
         status_t initialize();
     };
 
+    enum DropReason {
+        DROP_REASON_NOT_DROPPED = 0,
+        DROP_REASON_POLICY = 1,
+        DROP_REASON_APP_SWITCH = 2,
+        DROP_REASON_DISABLED = 3,
+    };
+
     sp<InputDispatcherPolicyInterface> mPolicy;
 
     Mutex mLock;
@@ -813,12 +847,16 @@
     // Enqueues an inbound event.  Returns true if mLooper->wake() should be called.
     bool enqueueInboundEventLocked(EventEntry* entry);
 
+    // Cleans up input state when dropping an inbound event.
+    void dropInboundEventLocked(EventEntry* entry, DropReason dropReason);
+
     // App switch latency optimization.
+    bool mAppSwitchSawKeyDown;
     nsecs_t mAppSwitchDueTime;
 
-    static bool isAppSwitchKey(int32_t keyCode);
+    static bool isAppSwitchKeyCode(int32_t keyCode);
+    bool isAppSwitchKeyEventLocked(KeyEntry* keyEntry);
     bool isAppSwitchPendingLocked();
-    bool detectPendingAppSwitchLocked(KeyEntry* inboundKeyEntry);
     void resetPendingAppSwitchLocked(bool handled);
 
     // All registered connections mapped by receive pipe file descriptor.
@@ -840,7 +878,7 @@
 
     // Event injection and synchronization.
     Condition mInjectionResultAvailableCondition;
-    EventEntry* createEntryFromInjectedInputEventLocked(const InputEvent* event);
+    bool hasInjectionPermission(int32_t injectorPid, int32_t injectorUid);
     void setInjectionResultLocked(EventEntry* entry, int32_t injectionResult);
 
     Condition mInjectionSyncFinishedCondition;
@@ -875,7 +913,7 @@
     void drainInboundQueueLocked();
     void releasePendingEventLocked();
     void releaseInboundEventLocked(EventEntry* entry);
-    bool isEventFromReliableSourceLocked(EventEntry* entry);
+    bool isEventFromTrustedSourceLocked(EventEntry* entry);
 
     // Dispatch state.
     bool mDispatchEnabled;
@@ -984,11 +1022,17 @@
     void startDispatchCycleLocked(nsecs_t currentTime, const sp<Connection>& connection);
     void finishDispatchCycleLocked(nsecs_t currentTime, const sp<Connection>& connection);
     void startNextDispatchCycleLocked(nsecs_t currentTime, const sp<Connection>& connection);
-    void abortDispatchCycleLocked(nsecs_t currentTime, const sp<Connection>& connection,
-            bool broken);
+    void abortBrokenDispatchCycleLocked(nsecs_t currentTime, const sp<Connection>& connection);
     void drainOutboundQueueLocked(Connection* connection);
     static int handleReceiveCallback(int receiveFd, int events, void* data);
 
+    void synthesizeCancelationEventsForAllConnectionsLocked(
+            InputState::CancelationOptions options, const char* reason);
+    void synthesizeCancelationEventsForInputChannelLocked(const sp<InputChannel>& channel,
+            InputState::CancelationOptions options, const char* reason);
+    void synthesizeCancelationEventsForConnectionLocked(const sp<Connection>& connection,
+            InputState::CancelationOptions options, const char* reason);
+
     // Splitting motion events across windows.
     MotionEntry* splitMotionEvent(const MotionEntry* originalMotionEntry, BitSet32 pointerIds);
 
diff --git a/include/ui/InputReader.h b/include/ui/InputReader.h
index 3619189..c15e382 100644
--- a/include/ui/InputReader.h
+++ b/include/ui/InputReader.h
@@ -87,49 +87,12 @@
         ROTATION_270 = 3
     };
 
-    /* Actions returned by interceptXXX methods. */
-    enum {
-        // The input dispatcher should do nothing and discard the input unless other
-        // flags are set.
-        ACTION_NONE = 0,
-
-        // The input dispatcher should dispatch the input to the application.
-        ACTION_DISPATCH = 0x00000001,
-    };
-
     /* Gets information about the display with the specified id.
      * Returns true if the display info is available, false otherwise.
      */
     virtual bool getDisplayInfo(int32_t displayId,
             int32_t* width, int32_t* height, int32_t* orientation) = 0;
 
-    /* Intercepts a key event.
-     * The policy can use this method as an opportunity to perform power management functions
-     * and early event preprocessing such as updating policy flags.
-     *
-     * Returns a policy action constant such as ACTION_DISPATCH.
-     */
-    virtual int32_t interceptKey(nsecs_t when, int32_t deviceId,
-            bool down, int32_t keyCode, int32_t scanCode, uint32_t& policyFlags) = 0;
-
-    /* Intercepts a switch event.
-     * The policy can use this method as an opportunity to perform power management functions
-     * and early event preprocessing such as updating policy flags.
-     *
-     * Switches are not dispatched to applications so this method should
-     * usually return ACTION_NONE.
-     */
-    virtual int32_t interceptSwitch(nsecs_t when, int32_t switchCode, int32_t switchValue,
-            uint32_t& policyFlags) = 0;
-
-    /* Intercepts a generic touch, trackball or other event.
-     * The policy can use this method as an opportunity to perform power management functions
-     * and early event preprocessing such as updating policy flags.
-     *
-     * Returns a policy action constant such as ACTION_DISPATCH.
-     */
-    virtual int32_t interceptGeneric(nsecs_t when, uint32_t& policyFlags) = 0;
-
     /* Determines whether to turn on some hacks we have to improve the touch interaction with a
      * certain device whose screen currently is not all that good.
      */
@@ -403,8 +366,6 @@
 protected:
     InputDevice* mDevice;
     InputReaderContext* mContext;
-
-    bool applyStandardPolicyActions(nsecs_t when, int32_t policyActions);
 };
 
 
@@ -466,8 +427,6 @@
 
     void processKey(nsecs_t when, bool down, int32_t keyCode, int32_t scanCode,
             uint32_t policyFlags);
-    void applyPolicyAndDispatch(nsecs_t when, uint32_t policyFlags,
-            bool down, int32_t keyCode, int32_t scanCode, int32_t metaState, nsecs_t downTime);
 
     ssize_t findKeyDownLocked(int32_t scanCode);
 };
@@ -525,8 +484,6 @@
     void initializeLocked();
 
     void sync(nsecs_t when);
-    void applyPolicyAndDispatch(nsecs_t when, int32_t motionEventAction,
-            PointerCoords* pointerCoords, nsecs_t downTime);
 };
 
 
@@ -829,10 +786,6 @@
             BitSet32 idBits, uint32_t changedId, uint32_t pointerCount,
             int32_t motionEventAction);
 
-    void applyPolicyAndDispatchVirtualKey(nsecs_t when, uint32_t policyFlags,
-            int32_t keyEventAction, int32_t keyEventFlags,
-            int32_t keyCode, int32_t scanCode, nsecs_t downTime);
-
     bool isPointInsideSurfaceLocked(int32_t x, int32_t y);
     const VirtualKey* findVirtualKeyHitLocked(int32_t x, int32_t y);