1/* 2 * Copyright 2017 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 17package androidx.recyclerview.selection; 18 19import static androidx.core.util.Preconditions.checkArgument; 20import static androidx.core.util.Preconditions.checkState; 21 22import android.view.MotionEvent; 23 24import androidx.annotation.NonNull; 25import androidx.annotation.Nullable; 26 27import java.util.Arrays; 28import java.util.List; 29 30/** 31 * Registry for tool specific event handler. This provides map like functionality, 32 * along with fallback to a default handler, while avoiding auto-boxing of tool 33 * type values that would be necessitated where a Map used. 34 * 35 * @param <T> type of item being registered. 36 */ 37final class ToolHandlerRegistry<T> { 38 39 // Currently there are four known input types. ERASER is the last one, so has the 40 // highest value. UNKNOWN is zero, so we add one. This allows delegates to be 41 // registered by type, and avoid the auto-boxing that would be necessary were we 42 // to store delegates in a Map<Integer, Delegate>. 43 private static final int NUM_INPUT_TYPES = MotionEvent.TOOL_TYPE_ERASER + 1; 44 45 private final List<T> mHandlers = Arrays.asList(null, null, null, null, null); 46 private final T mDefault; 47 48 ToolHandlerRegistry(@NonNull T defaultDelegate) { 49 checkArgument(defaultDelegate != null); 50 mDefault = defaultDelegate; 51 52 // Initialize all values to null. 53 for (int i = 0; i < NUM_INPUT_TYPES; i++) { 54 mHandlers.set(i, null); 55 } 56 } 57 58 /** 59 * @param toolType 60 * @param delegate the delegate, or null to unregister. 61 * @throws IllegalStateException if an tooltype handler is already registered. 62 */ 63 void set(int toolType, @Nullable T delegate) { 64 checkArgument(toolType >= 0 && toolType <= MotionEvent.TOOL_TYPE_ERASER); 65 checkState(mHandlers.get(toolType) == null); 66 67 mHandlers.set(toolType, delegate); 68 } 69 70 T get(@NonNull MotionEvent e) { 71 T d = mHandlers.get(e.getToolType(0)); 72 return d != null ? d : mDefault; 73 } 74} 75