Workaround apps that make assumptions about pointer ids.

Modified the touch input mapper to assign pointer ids sequentially
starting from 0 instead of using the tracking id or slot index
supplied by the driver.  Applications should not depend on this
ordering but some do.  (sigh)

Bug: 4980884
Change-Id: I0dfeb3ac27c57a7102a13c960c760e2a02eb7669
diff --git a/services/input/InputReader.cpp b/services/input/InputReader.cpp
index 79218a5..6a6e72e 100644
--- a/services/input/InputReader.cpp
+++ b/services/input/InputReader.cpp
@@ -5403,6 +5403,7 @@
     mAccumulator.clearSlots(mSlotCount);
     mAccumulator.clearButtons();
     mButtonState = 0;
+    mPointerIdBits.clear();
 
     if (mUsingSlotsProtocol) {
         // Query the driver for the current slot index and use it as the initial slot
@@ -5627,28 +5628,32 @@
 
         // Assign pointer id using tracking id if available.
         if (havePointerIds) {
-            int32_t id;
-            if (mUsingSlotsProtocol) {
-                id = inIndex;
-            } else if (fields & Accumulator::FIELD_ABS_MT_TRACKING_ID) {
-                id = inSlot.absMTTrackingId;
-            } else {
-                id = -1;
-            }
+            int32_t id = -1;
+            if (fields & Accumulator::FIELD_ABS_MT_TRACKING_ID) {
+                int32_t trackingId = inSlot.absMTTrackingId;
 
-            if (id >= 0 && id <= MAX_POINTER_ID) {
+                for (BitSet32 idBits(mPointerIdBits); !idBits.isEmpty(); ) {
+                    uint32_t n = idBits.firstMarkedBit();
+                    idBits.clearBit(n);
+
+                    if (mPointerTrackingIdMap[n] == trackingId) {
+                        id = n;
+                    }
+                }
+
+                if (id < 0 && !mPointerIdBits.isFull()) {
+                    id = mPointerIdBits.firstUnmarkedBit();
+                    mPointerIdBits.markBit(id);
+                    mPointerTrackingIdMap[id] = trackingId;
+                }
+            }
+            if (id < 0) {
+                havePointerIds = false;
+                mCurrentTouch.idBits.clear();
+            } else {
                 outPointer.id = id;
                 mCurrentTouch.idToIndex[id] = outCount;
                 mCurrentTouch.idBits.markBit(id);
-            } else {
-                if (id >= 0) {
-#if DEBUG_POINTERS
-                    LOGD("Pointers: Ignoring driver provided slot index or tracking id %d because "
-                            "it is larger than the maximum supported pointer id %d",
-                            id, MAX_POINTER_ID);
-#endif
-                }
-                havePointerIds = false;
             }
         }
 
@@ -5660,6 +5665,8 @@
     mButtonState = (mButtonState | mAccumulator.buttonDown) & ~mAccumulator.buttonUp;
     mCurrentTouch.buttonState = mButtonState;
 
+    mPointerIdBits = mCurrentTouch.idBits;
+
     syncTouch(when, havePointerIds);
 
     if (!mUsingSlotsProtocol) {