1/* 2 * Copyright (C) 2014 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 com.android.inputmethod.keyboard.internal; 18 19import com.android.inputmethod.keyboard.Key; 20 21import java.util.HashMap; 22 23import javax.annotation.Nonnull; 24 25public abstract class UniqueKeysCache { 26 public abstract void setEnabled(boolean enabled); 27 public abstract void clear(); 28 public abstract @Nonnull Key getUniqueKey(@Nonnull Key key); 29 30 @Nonnull 31 public static final UniqueKeysCache NO_CACHE = new UniqueKeysCache() { 32 @Override 33 public void setEnabled(boolean enabled) {} 34 35 @Override 36 public void clear() {} 37 38 @Override 39 public Key getUniqueKey(Key key) { return key; } 40 }; 41 42 @Nonnull 43 public static UniqueKeysCache newInstance() { 44 return new UniqueKeysCacheImpl(); 45 } 46 47 private static final class UniqueKeysCacheImpl extends UniqueKeysCache { 48 private final HashMap<Key, Key> mCache; 49 50 private boolean mEnabled; 51 52 UniqueKeysCacheImpl() { 53 mCache = new HashMap<>(); 54 } 55 56 @Override 57 public void setEnabled(final boolean enabled) { 58 mEnabled = enabled; 59 } 60 61 @Override 62 public void clear() { 63 mCache.clear(); 64 } 65 66 @Override 67 public Key getUniqueKey(final Key key) { 68 if (!mEnabled) { 69 return key; 70 } 71 final Key existingKey = mCache.get(key); 72 if (existingKey != null) { 73 // Reuse the existing object that equals to "key" without adding "key" to 74 // the cache. 75 return existingKey; 76 } 77 mCache.put(key, key); 78 return key; 79 } 80 } 81} 82