1 /* 2 * Copyright (C) 2019 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 package com.android.quickstep.util; 17 18 import static com.android.systemui.shared.system.InputChannelCompat.mergeMotionEvent; 19 20 import android.view.MotionEvent; 21 22 import java.util.ArrayList; 23 import java.util.function.Consumer; 24 25 /** 26 * Utility class to dispatch touch events to a different class. It stores the events locally 27 * until a valid dispatcher is available. 28 */ 29 public class CachedEventDispatcher { 30 31 private Consumer<MotionEvent> mConsumer; 32 33 private ArrayList<MotionEvent> mCache; 34 private MotionEvent mLastEvent; 35 dispatchEvent(MotionEvent event)36 public void dispatchEvent(MotionEvent event) { 37 if (mConsumer != null) { 38 mConsumer.accept(event); 39 } else { 40 if (mLastEvent == null || !mergeMotionEvent(event, mLastEvent)) { 41 // Queue event. 42 if (mCache == null) { 43 mCache = new ArrayList<>(); 44 } 45 mLastEvent = MotionEvent.obtain(event); 46 mCache.add(mLastEvent); 47 } 48 } 49 } 50 setConsumer(Consumer<MotionEvent> consumer)51 public void setConsumer(Consumer<MotionEvent> consumer) { 52 if (consumer == null) { 53 return; 54 } 55 mConsumer = consumer; 56 int cacheCount = mCache == null ? 0 : mCache.size(); 57 for (int i = 0; i < cacheCount; i++) { 58 MotionEvent ev = mCache.get(i); 59 mConsumer.accept(ev); 60 ev.recycle(); 61 } 62 mCache = null; 63 mLastEvent = null; 64 } 65 hasConsumer()66 public boolean hasConsumer() { 67 return mConsumer != null; 68 } 69 } 70