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