BinaryDictionary.java revision 458249e703bded3a1cbd25a2ab2249f9366a8188
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; 20import android.util.Log; 21 22import java.io.IOException; 23import java.io.InputStream; 24import java.nio.ByteBuffer; 25import java.nio.ByteOrder; 26import java.nio.channels.Channels; 27import java.util.Arrays; 28 29/** 30 * Implements a static, compacted, binary dictionary of standard words. 31 */ 32public class BinaryDictionary extends Dictionary { 33 34 /** 35 * There is difference between what java and native code can handle. 36 * This value should only be used in BinaryDictionary.java 37 * It is necessary to keep it at this value because some languages e.g. German have 38 * really long words. 39 */ 40 protected static final int MAX_WORD_LENGTH = 48; 41 42 private static final String TAG = "BinaryDictionary"; 43 private static final int MAX_ALTERNATIVES = 16; 44 private static final int MAX_WORDS = 18; 45 private static final int MAX_BIGRAMS = 60; 46 47 private static final int TYPED_LETTER_MULTIPLIER = 2; 48 49 private int mDicTypeId; 50 private int mNativeDict; 51 private int mDictLength; 52 private final int[] mInputCodes = new int[MAX_WORD_LENGTH * MAX_ALTERNATIVES]; 53 private final char[] mOutputChars = new char[MAX_WORD_LENGTH * MAX_WORDS]; 54 private final char[] mOutputChars_bigrams = new char[MAX_WORD_LENGTH * MAX_BIGRAMS]; 55 private final int[] mFrequencies = new int[MAX_WORDS]; 56 private final int[] mFrequencies_bigrams = new int[MAX_BIGRAMS]; 57 // Keep a reference to the native dict direct buffer in Java to avoid 58 // unexpected deallocation of the direct buffer. 59 private ByteBuffer mNativeDictDirectBuffer; 60 61 static { 62 try { 63 System.loadLibrary("jni_latinime"); 64 } catch (UnsatisfiedLinkError ule) { 65 Log.e("BinaryDictionary", "Could not load native library jni_latinime"); 66 } 67 } 68 69 /** 70 * Create a dictionary from a raw resource file 71 * @param context application context for reading resources 72 * @param resId the resource containing the raw binary dictionary 73 */ 74 public BinaryDictionary(Context context, int resId, int dicTypeId) { 75 if (resId != 0) { 76 loadDictionary(context, resId); 77 } 78 mDicTypeId = dicTypeId; 79 } 80 81 /** 82 * Create a dictionary from a byte buffer. This is used for testing. 83 * @param context application context for reading resources 84 * @param byteBuffer a ByteBuffer containing the binary dictionary 85 */ 86 public BinaryDictionary(Context context, ByteBuffer byteBuffer, int dicTypeId) { 87 if (byteBuffer != null) { 88 if (byteBuffer.isDirect()) { 89 mNativeDictDirectBuffer = byteBuffer; 90 } else { 91 mNativeDictDirectBuffer = ByteBuffer.allocateDirect(byteBuffer.capacity()); 92 byteBuffer.rewind(); 93 mNativeDictDirectBuffer.put(byteBuffer); 94 } 95 mDictLength = byteBuffer.capacity(); 96 mNativeDict = openNative(mNativeDictDirectBuffer, 97 TYPED_LETTER_MULTIPLIER, FULL_WORD_FREQ_MULTIPLIER, 98 MAX_WORD_LENGTH, MAX_WORDS, MAX_ALTERNATIVES); 99 } 100 mDicTypeId = dicTypeId; 101 } 102 103 private native int openNative(ByteBuffer bb, int typedLetterMultiplier, 104 int fullWordMultiplier, int maxWordLength, int maxWords, int maxAlternatives); 105 private native void closeNative(int dict); 106 private native boolean isValidWordNative(int nativeData, char[] word, int wordLength); 107 private native int getSuggestionsNative(int dict, int[] inputCodes, int codesSize, 108 char[] outputChars, int[] frequencies, 109 int[] nextLettersFrequencies, int nextLettersSize); 110 private native int getBigramsNative(int dict, char[] prevWord, int prevWordLength, 111 int[] inputCodes, int inputCodesLength, char[] outputChars, int[] frequencies, 112 int maxWordLength, int maxBigrams, int maxAlternatives); 113 114 private final void loadDictionary(Context context, int resId) { 115 InputStream is = null; 116 try { 117 is = context.getResources().openRawResource(resId); 118 final int total = is.available(); 119 mNativeDictDirectBuffer = 120 ByteBuffer.allocateDirect(total).order(ByteOrder.nativeOrder()); 121 final int got = Channels.newChannel(is).read(mNativeDictDirectBuffer); 122 if (got != total) { 123 Log.e(TAG, "Read " + got + " bytes, expected " + total); 124 } else { 125 mNativeDict = openNative(mNativeDictDirectBuffer, 126 TYPED_LETTER_MULTIPLIER, FULL_WORD_FREQ_MULTIPLIER, 127 MAX_WORD_LENGTH, MAX_WORDS, MAX_ALTERNATIVES); 128 mDictLength = total; 129 } 130 } catch (IOException e) { 131 Log.w(TAG, "No available memory for binary dictionary"); 132 } finally { 133 try { 134 if (is != null) is.close(); 135 } catch (IOException e) { 136 Log.w(TAG, "Failed to close input stream"); 137 } 138 } 139 } 140 141 142 @Override 143 public void getBigrams(final WordComposer codes, final CharSequence previousWord, 144 final WordCallback callback, int[] nextLettersFrequencies) { 145 146 char[] chars = previousWord.toString().toCharArray(); 147 Arrays.fill(mOutputChars_bigrams, (char) 0); 148 Arrays.fill(mFrequencies_bigrams, 0); 149 150 int codesSize = codes.size(); 151 Arrays.fill(mInputCodes, -1); 152 int[] alternatives = codes.getCodesAt(0); 153 System.arraycopy(alternatives, 0, mInputCodes, 0, 154 Math.min(alternatives.length, MAX_ALTERNATIVES)); 155 156 int count = getBigramsNative(mNativeDict, chars, chars.length, mInputCodes, codesSize, 157 mOutputChars_bigrams, mFrequencies_bigrams, MAX_WORD_LENGTH, MAX_BIGRAMS, 158 MAX_ALTERNATIVES); 159 160 for (int j = 0; j < count; ++j) { 161 if (mFrequencies_bigrams[j] < 1) break; 162 final int start = j * MAX_WORD_LENGTH; 163 int len = 0; 164 while (len < MAX_WORD_LENGTH && mOutputChars_bigrams[start + len] != 0) { 165 ++len; 166 } 167 if (len > 0) { 168 callback.addWord(mOutputChars_bigrams, start, len, mFrequencies_bigrams[j], 169 mDicTypeId, DataType.BIGRAM); 170 } 171 } 172 } 173 174 @Override 175 public void getWords(final WordComposer codes, final WordCallback callback, 176 int[] nextLettersFrequencies) { 177 final int codesSize = codes.size(); 178 // Won't deal with really long words. 179 if (codesSize > MAX_WORD_LENGTH - 1) return; 180 181 Arrays.fill(mInputCodes, -1); 182 for (int i = 0; i < codesSize; i++) { 183 int[] alternatives = codes.getCodesAt(i); 184 System.arraycopy(alternatives, 0, mInputCodes, i * MAX_ALTERNATIVES, 185 Math.min(alternatives.length, MAX_ALTERNATIVES)); 186 } 187 Arrays.fill(mOutputChars, (char) 0); 188 Arrays.fill(mFrequencies, 0); 189 190 int count = getSuggestionsNative(mNativeDict, mInputCodes, codesSize, mOutputChars, 191 mFrequencies, nextLettersFrequencies, 192 nextLettersFrequencies != null ? nextLettersFrequencies.length : 0); 193 194 for (int j = 0; j < count; ++j) { 195 if (mFrequencies[j] < 1) break; 196 final int start = j * MAX_WORD_LENGTH; 197 int len = 0; 198 while (len < MAX_WORD_LENGTH && mOutputChars[start + len] != 0) { 199 ++len; 200 } 201 if (len > 0) { 202 callback.addWord(mOutputChars, start, len, mFrequencies[j], mDicTypeId, 203 DataType.UNIGRAM); 204 } 205 } 206 } 207 208 @Override 209 public boolean isValidWord(CharSequence word) { 210 if (word == null) return false; 211 char[] chars = word.toString().toCharArray(); 212 return isValidWordNative(mNativeDict, chars, chars.length); 213 } 214 215 public int getSize() { 216 return mDictLength; // This value is initialized on the call to openNative() 217 } 218 219 @Override 220 public synchronized void close() { 221 if (mNativeDict != 0) { 222 closeNative(mNativeDict); 223 mNativeDict = 0; 224 } 225 } 226 227 @Override 228 protected void finalize() throws Throwable { 229 close(); 230 super.finalize(); 231 } 232} 233