BinaryDictionary.java revision 8980bd4a25e2a4368441d575c91bcbe8c8624969
1/* 2 * Copyright (C) 2008 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); you may not 5 * use this file except in compliance with the License. You may obtain a copy of 6 * 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, WITHOUT 12 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 * License for the specific language governing permissions and limitations under 14 * the License. 15 */ 16 17package com.android.inputmethod.latin; 18 19import android.content.Context; 20 21import com.android.inputmethod.keyboard.ProximityInfo; 22 23import java.util.Arrays; 24 25/** 26 * Implements a static, compacted, binary dictionary of standard words. 27 */ 28public class BinaryDictionary extends Dictionary { 29 30 public static final String DICTIONARY_PACK_AUTHORITY = 31 "com.android.inputmethod.latin.dictionarypack"; 32 33 /** 34 * There is a difference between what java and native code can handle. 35 * This value should only be used in BinaryDictionary.java 36 * It is necessary to keep it at this value because some languages e.g. German have 37 * really long words. 38 */ 39 public static final int MAX_WORD_LENGTH = 48; 40 public static final int MAX_WORDS = 18; 41 42 private static final String TAG = "BinaryDictionary"; 43 private static final int MAX_PROXIMITY_CHARS_SIZE = ProximityInfo.MAX_PROXIMITY_CHARS_SIZE; 44 private static final int MAX_BIGRAMS = 60; 45 46 private static final int TYPED_LETTER_MULTIPLIER = 2; 47 48 private int mDicTypeId; 49 private long mNativeDict; 50 private final int[] mInputCodes = new int[MAX_WORD_LENGTH * MAX_PROXIMITY_CHARS_SIZE]; 51 private final char[] mOutputChars = new char[MAX_WORD_LENGTH * MAX_WORDS]; 52 private final char[] mOutputChars_bigrams = new char[MAX_WORD_LENGTH * MAX_BIGRAMS]; 53 private final int[] mScores = new int[MAX_WORDS]; 54 private final int[] mBigramScores = new int[MAX_BIGRAMS]; 55 56 public static final Flag FLAG_REQUIRES_GERMAN_UMLAUT_PROCESSING = 57 new Flag(R.bool.config_require_umlaut_processing, 0x1); 58 public static final Flag FLAG_REQUIRES_FRENCH_LIGATURES_PROCESSING = 59 new Flag(R.bool.config_require_ligatures_processing, 0x4); 60 61 // FULL_EDIT_DISTANCE is a flag that forces the dictionary to use full words 62 // when computing edit distance, instead of the default behavior of stopping 63 // the evaluation at the size the user typed. 64 public static final Flag FLAG_USE_FULL_EDIT_DISTANCE = new Flag(0x2); 65 66 // Can create a new flag from extravalue : 67 // public static final Flag FLAG_MYFLAG = 68 // new Flag("my_flag", 0x02); 69 70 // ALL_CONFIG_FLAGS is a collection of flags that enable reading all flags from configuration. 71 // This is but a mask - it does not mean the flags will be on, only that the configuration 72 // will be read for this particular flag. 73 public static final Flag[] ALL_CONFIG_FLAGS = { 74 // Here should reside all flags that trigger some special processing 75 // These *must* match the definition in UnigramDictionary enum in 76 // unigram_dictionary.h so please update both at the same time. 77 // Please note that flags created with a resource are of type CONFIG while flags 78 // created with a string are of type EXTRAVALUE. These behave like masks, and the 79 // actual value will be read from the configuration/extra value at run time for 80 // the configuration at dictionary creation time. 81 FLAG_REQUIRES_GERMAN_UMLAUT_PROCESSING, 82 FLAG_REQUIRES_FRENCH_LIGATURES_PROCESSING, 83 }; 84 85 private int mFlags = 0; 86 87 /** 88 * Constructor for the binary dictionary. This is supposed to be called from the 89 * dictionary factory. 90 * All implementations should pass null into flagArray, except for testing purposes. 91 * @param context the context to access the environment from. 92 * @param filename the name of the file to read through native code. 93 * @param offset the offset of the dictionary data within the file. 94 * @param length the length of the binary data. 95 * @param flagArray the flags to limit the dictionary to, or null for default. 96 */ 97 public BinaryDictionary(final Context context, 98 final String filename, final long offset, final long length, Flag[] flagArray) { 99 // Note: at the moment a binary dictionary is always of the "main" type. 100 // Initializing this here will help transitioning out of the scheme where 101 // the Suggest class knows everything about every single dictionary. 102 mDicTypeId = Suggest.DIC_MAIN; 103 // TODO: Stop relying on the state of SubtypeSwitcher, get it as a parameter 104 mFlags = Flag.initFlags(null == flagArray ? ALL_CONFIG_FLAGS : flagArray, context, 105 SubtypeSwitcher.getInstance()); 106 loadDictionary(filename, offset, length); 107 } 108 109 static { 110 JniUtils.loadNativeLibrary(); 111 } 112 113 private native long openNative(String sourceDir, long dictOffset, long dictSize, 114 int typedLetterMultiplier, int fullWordMultiplier, int maxWordLength, 115 int maxWords, int maxAlternatives); 116 private native void closeNative(long dict); 117 private native boolean isValidWordNative(long dict, char[] word, int wordLength); 118 private native int getSuggestionsNative(long dict, long proximityInfo, int[] xCoordinates, 119 int[] yCoordinates, int[] inputCodes, int codesSize, int flags, char[] outputChars, 120 int[] scores); 121 private native int getBigramsNative(long dict, char[] prevWord, int prevWordLength, 122 int[] inputCodes, int inputCodesLength, char[] outputChars, int[] scores, 123 int maxWordLength, int maxBigrams, int maxAlternatives); 124 private static native double calcNormalizedScoreNative( 125 char[] before, int beforeLength, char[] after, int afterLength, int score); 126 private static native int editDistanceNative( 127 char[] before, int beforeLength, char[] after, int afterLength); 128 129 private final void loadDictionary(String path, long startOffset, long length) { 130 mNativeDict = openNative(path, startOffset, length, 131 TYPED_LETTER_MULTIPLIER, FULL_WORD_SCORE_MULTIPLIER, 132 MAX_WORD_LENGTH, MAX_WORDS, MAX_PROXIMITY_CHARS_SIZE); 133 } 134 135 @Override 136 public void getBigrams(final WordComposer codes, final CharSequence previousWord, 137 final WordCallback callback) { 138 if (mNativeDict == 0) return; 139 140 char[] chars = previousWord.toString().toCharArray(); 141 Arrays.fill(mOutputChars_bigrams, (char) 0); 142 Arrays.fill(mBigramScores, 0); 143 144 int codesSize = codes.size(); 145 Arrays.fill(mInputCodes, -1); 146 if (codesSize > 0) { 147 int[] alternatives = codes.getCodesAt(0); 148 System.arraycopy(alternatives, 0, mInputCodes, 0, 149 Math.min(alternatives.length, MAX_PROXIMITY_CHARS_SIZE)); 150 } 151 152 int count = getBigramsNative(mNativeDict, chars, chars.length, mInputCodes, codesSize, 153 mOutputChars_bigrams, mBigramScores, MAX_WORD_LENGTH, MAX_BIGRAMS, 154 MAX_PROXIMITY_CHARS_SIZE); 155 if (count > MAX_BIGRAMS) { 156 count = MAX_BIGRAMS; 157 } 158 159 for (int j = 0; j < count; ++j) { 160 if (codesSize > 0 && mBigramScores[j] < 1) break; 161 final int start = j * MAX_WORD_LENGTH; 162 int len = 0; 163 while (len < MAX_WORD_LENGTH && mOutputChars_bigrams[start + len] != 0) { 164 ++len; 165 } 166 if (len > 0) { 167 callback.addWord(mOutputChars_bigrams, start, len, mBigramScores[j], 168 mDicTypeId, Dictionary.BIGRAM); 169 } 170 } 171 } 172 173 // proximityInfo may not be null. 174 @Override 175 public void getWords(final WordComposer codes, final WordCallback callback, 176 final ProximityInfo proximityInfo) { 177 final int count = getSuggestions(codes, proximityInfo, mOutputChars, mScores); 178 179 for (int j = 0; j < count; ++j) { 180 if (mScores[j] < 1) break; 181 final int start = j * MAX_WORD_LENGTH; 182 int len = 0; 183 while (len < MAX_WORD_LENGTH && mOutputChars[start + len] != 0) { 184 ++len; 185 } 186 if (len > 0) { 187 callback.addWord(mOutputChars, start, len, mScores[j], mDicTypeId, 188 Dictionary.UNIGRAM); 189 } 190 } 191 } 192 193 /* package for test */ boolean isValidDictionary() { 194 return mNativeDict != 0; 195 } 196 197 // proximityInfo may not be null. 198 /* package for test */ int getSuggestions(final WordComposer codes, 199 final ProximityInfo proximityInfo, char[] outputChars, int[] scores) { 200 if (!isValidDictionary()) return -1; 201 202 final int codesSize = codes.size(); 203 // Won't deal with really long words. 204 if (codesSize > MAX_WORD_LENGTH - 1) return -1; 205 206 Arrays.fill(mInputCodes, WordComposer.NOT_A_CODE); 207 for (int i = 0; i < codesSize; i++) { 208 final int[] alternatives = codes.getCodesAt(i); 209 if (alternatives == null || alternatives.length < 1) { 210 continue; 211 } 212 mInputCodes[i] = alternatives[0]; 213 } 214 Arrays.fill(outputChars, (char) 0); 215 Arrays.fill(scores, 0); 216 217 return getSuggestionsNative( 218 mNativeDict, proximityInfo.getNativeProximityInfo(), 219 codes.getXCoordinates(), codes.getYCoordinates(), mInputCodes, codesSize, 220 mFlags, outputChars, scores); 221 } 222 223 public static double calcNormalizedScore(String before, String after, int score) { 224 return calcNormalizedScoreNative(before.toCharArray(), before.length(), 225 after.toCharArray(), after.length(), score); 226 } 227 228 public static int editDistance(String before, String after) { 229 return editDistanceNative( 230 before.toCharArray(), before.length(), after.toCharArray(), after.length()); 231 } 232 233 @Override 234 public boolean isValidWord(CharSequence word) { 235 if (word == null) return false; 236 char[] chars = word.toString().toCharArray(); 237 return isValidWordNative(mNativeDict, chars, chars.length); 238 } 239 240 @Override 241 public synchronized void close() { 242 closeInternal(); 243 } 244 245 private void closeInternal() { 246 if (mNativeDict != 0) { 247 closeNative(mNativeDict); 248 mNativeDict = 0; 249 } 250 } 251 252 @Override 253 protected void finalize() throws Throwable { 254 try { 255 closeInternal(); 256 } finally { 257 super.finalize(); 258 } 259 } 260} 261