|
| 1 | +package io.flutter.embedding.android; |
| 2 | + |
| 3 | +import android.util.LongSparseArray; |
| 4 | +import android.view.MotionEvent; |
| 5 | +import androidx.annotation.Nullable; |
| 6 | +import java.util.PriorityQueue; |
| 7 | +import java.util.concurrent.atomic.AtomicLong; |
| 8 | + |
| 9 | +/** Tracks the motion events received by the FlutterView. */ |
| 10 | +public final class MotionEventTracker { |
| 11 | + |
| 12 | + /** Represents a unique identifier corresponding to a motion event. */ |
| 13 | + public static class MotionEventId { |
| 14 | + private static final AtomicLong ID_COUNTER = new AtomicLong(0); |
| 15 | + private final long id; |
| 16 | + |
| 17 | + private MotionEventId(long id) { |
| 18 | + this.id = id; |
| 19 | + } |
| 20 | + |
| 21 | + public static MotionEventId from(long id) { |
| 22 | + return new MotionEventId(id); |
| 23 | + } |
| 24 | + |
| 25 | + public static MotionEventId createUnique() { |
| 26 | + return MotionEventId.from(ID_COUNTER.incrementAndGet()); |
| 27 | + } |
| 28 | + |
| 29 | + public long getId() { |
| 30 | + return id; |
| 31 | + } |
| 32 | + } |
| 33 | + |
| 34 | + private final LongSparseArray<MotionEvent> eventById; |
| 35 | + private final PriorityQueue<Long> unusedEvents; |
| 36 | + private static MotionEventTracker INSTANCE; |
| 37 | + |
| 38 | + public static MotionEventTracker getInstance() { |
| 39 | + if (INSTANCE == null) { |
| 40 | + INSTANCE = new MotionEventTracker(); |
| 41 | + } |
| 42 | + return INSTANCE; |
| 43 | + } |
| 44 | + |
| 45 | + private MotionEventTracker() { |
| 46 | + eventById = new LongSparseArray<>(); |
| 47 | + unusedEvents = new PriorityQueue<>(); |
| 48 | + } |
| 49 | + |
| 50 | + /** Tracks the event and returns a unique MotionEventId identifying the event. */ |
| 51 | + public MotionEventId track(MotionEvent event) { |
| 52 | + MotionEventId eventId = MotionEventId.createUnique(); |
| 53 | + eventById.put(eventId.id, event); |
| 54 | + unusedEvents.add(eventId.id); |
| 55 | + return eventId; |
| 56 | + } |
| 57 | + |
| 58 | + /** |
| 59 | + * Returns the MotionEvent corresponding to the eventId while discarding all the motion events |
| 60 | + * that occured prior to the event represented by the eventId. Returns null if this event was |
| 61 | + * popped or discarded. |
| 62 | + */ |
| 63 | + @Nullable |
| 64 | + public MotionEvent pop(MotionEventId eventId) { |
| 65 | + // remove all the older events. |
| 66 | + while (!unusedEvents.isEmpty() && unusedEvents.peek() < eventId.id) { |
| 67 | + eventById.remove(unusedEvents.poll()); |
| 68 | + } |
| 69 | + |
| 70 | + // remove the current event from the heap if it exists. |
| 71 | + if (!unusedEvents.isEmpty() && unusedEvents.peek() == eventId.id) { |
| 72 | + unusedEvents.poll(); |
| 73 | + } |
| 74 | + |
| 75 | + MotionEvent event = eventById.get(eventId.id); |
| 76 | + eventById.remove(eventId.id); |
| 77 | + return event; |
| 78 | + } |
| 79 | +} |
0 commit comments