diff options
Diffstat (limited to 'java/src/com/android/inputmethod/latin/BinaryDictionary.java')
-rw-r--r-- | java/src/com/android/inputmethod/latin/BinaryDictionary.java | 187 |
1 files changed, 70 insertions, 117 deletions
diff --git a/java/src/com/android/inputmethod/latin/BinaryDictionary.java b/java/src/com/android/inputmethod/latin/BinaryDictionary.java index d0e143dd0..813f7d32f 100644 --- a/java/src/com/android/inputmethod/latin/BinaryDictionary.java +++ b/java/src/com/android/inputmethod/latin/BinaryDictionary.java @@ -1,12 +1,12 @@ /* * Copyright (C) 2008 The Android Open Source Project - * + * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the @@ -16,16 +16,12 @@ package com.android.inputmethod.latin; -import java.io.InputStream; -import java.io.IOException; -import java.nio.ByteBuffer; -import java.nio.ByteOrder; -import java.nio.channels.Channels; -import java.util.Arrays; - import android.content.Context; +import android.content.res.AssetFileDescriptor; import android.util.Log; +import java.util.Arrays; + /** * Implements a static, compacted, binary dictionary of standard words. */ @@ -45,115 +41,79 @@ public class BinaryDictionary extends Dictionary { private static final int MAX_BIGRAMS = 60; private static final int TYPED_LETTER_MULTIPLIER = 2; - private static final boolean ENABLE_MISSED_CHARACTERS = true; + private static final BinaryDictionary sInstance = new BinaryDictionary(); private int mDicTypeId; private int mNativeDict; - private int mDictLength; - private int[] mInputCodes = new int[MAX_WORD_LENGTH * MAX_ALTERNATIVES]; - private char[] mOutputChars = new char[MAX_WORD_LENGTH * MAX_WORDS]; - private char[] mOutputChars_bigrams = new char[MAX_WORD_LENGTH * MAX_BIGRAMS]; - private int[] mFrequencies = new int[MAX_WORDS]; - private int[] mFrequencies_bigrams = new int[MAX_BIGRAMS]; - // Keep a reference to the native dict direct buffer in Java to avoid - // unexpected deallocation of the direct buffer. - private ByteBuffer mNativeDictDirectBuffer; + private long mDictLength; + private final int[] mInputCodes = new int[MAX_WORD_LENGTH * MAX_ALTERNATIVES]; + private final char[] mOutputChars = new char[MAX_WORD_LENGTH * MAX_WORDS]; + private final char[] mOutputChars_bigrams = new char[MAX_WORD_LENGTH * MAX_BIGRAMS]; + private final int[] mFrequencies = new int[MAX_WORDS]; + private final int[] mFrequencies_bigrams = new int[MAX_BIGRAMS]; static { try { System.loadLibrary("jni_latinime"); } catch (UnsatisfiedLinkError ule) { - Log.e("BinaryDictionary", "Could not load native library jni_latinime"); + Log.e(TAG, "Could not load native library jni_latinime"); } } - /** - * Create a dictionary from a raw resource file - * @param context application context for reading resources - * @param resId the resource containing the raw binary dictionary - */ - public BinaryDictionary(Context context, int[] resId, int dicTypeId) { - if (resId != null && resId.length > 0 && resId[0] != 0) { - loadDictionary(context, resId); - } - mDicTypeId = dicTypeId; + private BinaryDictionary() { } /** - * Create a dictionary from a byte buffer. This is used for testing. + * Initialize a dictionary from a raw resource file * @param context application context for reading resources - * @param byteBuffer a ByteBuffer containing the binary dictionary + * @param resId the resource containing the raw binary dictionary + * @return initialized instance of BinaryDictionary */ - public BinaryDictionary(Context context, ByteBuffer byteBuffer, int dicTypeId) { - if (byteBuffer != null) { - if (byteBuffer.isDirect()) { - mNativeDictDirectBuffer = byteBuffer; - } else { - mNativeDictDirectBuffer = ByteBuffer.allocateDirect(byteBuffer.capacity()); - byteBuffer.rewind(); - mNativeDictDirectBuffer.put(byteBuffer); + public static BinaryDictionary initDictionary(Context context, int resId, int dicTypeId) { + synchronized (sInstance) { + sInstance.closeInternal(); + if (resId != 0) { + sInstance.loadDictionary(context, resId); + sInstance.mDicTypeId = dicTypeId; } - mDictLength = byteBuffer.capacity(); - mNativeDict = openNative(mNativeDictDirectBuffer, - TYPED_LETTER_MULTIPLIER, FULL_WORD_FREQ_MULTIPLIER); } - mDicTypeId = dicTypeId; + return sInstance; } - private native int openNative(ByteBuffer bb, int typedLetterMultiplier, - int fullWordMultiplier); + private native int openNative(String sourceDir, long dictOffset, long dictSize, + int typedLetterMultiplier, int fullWordMultiplier, int maxWordLength, + int maxWords, int maxAlternatives); private native void closeNative(int dict); private native boolean isValidWordNative(int nativeData, char[] word, int wordLength); - private native int getSuggestionsNative(int dict, int[] inputCodes, int codesSize, - char[] outputChars, int[] frequencies, int maxWordLength, int maxWords, - int maxAlternatives, int skipPos, int[] nextLettersFrequencies, int nextLettersSize); + private native int getSuggestionsNative(int dict, int[] inputCodes, int codesSize, + char[] outputChars, int[] frequencies, + int[] nextLettersFrequencies, int nextLettersSize); private native int getBigramsNative(int dict, char[] prevWord, int prevWordLength, int[] inputCodes, int inputCodesLength, char[] outputChars, int[] frequencies, int maxWordLength, int maxBigrams, int maxAlternatives); - private final void loadDictionary(Context context, int[] resId) { - InputStream[] is = null; + private final void loadDictionary(Context context, int resId) { try { - // merging separated dictionary into one if dictionary is separated - int total = 0; - is = new InputStream[resId.length]; - for (int i = 0; i < resId.length; i++) { - is[i] = context.getResources().openRawResource(resId[i]); - total += is[i].available(); - } - - mNativeDictDirectBuffer = - ByteBuffer.allocateDirect(total).order(ByteOrder.nativeOrder()); - int got = 0; - for (int i = 0; i < resId.length; i++) { - got += Channels.newChannel(is[i]).read(mNativeDictDirectBuffer); - } - if (got != total) { - Log.e(TAG, "Read " + got + " bytes, expected " + total); - } else { - mNativeDict = openNative(mNativeDictDirectBuffer, - TYPED_LETTER_MULTIPLIER, FULL_WORD_FREQ_MULTIPLIER); - mDictLength = total; - } - } catch (IOException e) { - Log.w(TAG, "No available memory for binary dictionary"); - } finally { - try { - if (is != null) { - for (int i = 0; i < is.length; i++) { - is[i].close(); - } - } - } catch (IOException e) { - Log.w(TAG, "Failed to close input stream"); + final AssetFileDescriptor afd = context.getResources().openRawResourceFd(resId); + if (afd == null) { + Log.e(TAG, "Found the resource but it is compressed. resId=" + resId); + return; } + mNativeDict = openNative(context.getApplicationInfo().sourceDir, + afd.getStartOffset(), afd.getLength(), + TYPED_LETTER_MULTIPLIER, FULL_WORD_FREQ_MULTIPLIER, + MAX_WORD_LENGTH, MAX_WORDS, MAX_ALTERNATIVES); + mDictLength = afd.getLength(); + } catch (android.content.res.Resources.NotFoundException e) { + Log.e(TAG, "Could not find the resource. resId=" + resId); + return; } } - @Override public void getBigrams(final WordComposer codes, final CharSequence previousWord, final WordCallback callback, int[] nextLettersFrequencies) { + if (mNativeDict == 0) return; char[] chars = previousWord.toString().toCharArray(); Arrays.fill(mOutputChars_bigrams, (char) 0); @@ -169,12 +129,12 @@ public class BinaryDictionary extends Dictionary { mOutputChars_bigrams, mFrequencies_bigrams, MAX_WORD_LENGTH, MAX_BIGRAMS, MAX_ALTERNATIVES); - for (int j = 0; j < count; j++) { + for (int j = 0; j < count; ++j) { if (mFrequencies_bigrams[j] < 1) break; - int start = j * MAX_WORD_LENGTH; + final int start = j * MAX_WORD_LENGTH; int len = 0; - while (mOutputChars_bigrams[start + len] != 0) { - len++; + while (len < MAX_WORD_LENGTH && mOutputChars_bigrams[start + len] != 0) { + ++len; } if (len > 0) { callback.addWord(mOutputChars_bigrams, start, len, mFrequencies_bigrams[j], @@ -186,10 +146,12 @@ public class BinaryDictionary extends Dictionary { @Override public void getWords(final WordComposer codes, final WordCallback callback, int[] nextLettersFrequencies) { + if (mNativeDict == 0) return; + final int codesSize = codes.size(); // Won't deal with really long words. if (codesSize > MAX_WORD_LENGTH - 1) return; - + Arrays.fill(mInputCodes, -1); for (int i = 0; i < codesSize; i++) { int[] alternatives = codes.getCodesAt(i); @@ -199,33 +161,16 @@ public class BinaryDictionary extends Dictionary { Arrays.fill(mOutputChars, (char) 0); Arrays.fill(mFrequencies, 0); - int count = getSuggestionsNative(mNativeDict, mInputCodes, codesSize, - mOutputChars, mFrequencies, - MAX_WORD_LENGTH, MAX_WORDS, MAX_ALTERNATIVES, -1, - nextLettersFrequencies, + int count = getSuggestionsNative(mNativeDict, mInputCodes, codesSize, mOutputChars, + mFrequencies, nextLettersFrequencies, nextLettersFrequencies != null ? nextLettersFrequencies.length : 0); - // If there aren't sufficient suggestions, search for words by allowing wild cards at - // the different character positions. This feature is not ready for prime-time as we need - // to figure out the best ranking for such words compared to proximity corrections and - // completions. - if (ENABLE_MISSED_CHARACTERS && count < 5) { - for (int skip = 0; skip < codesSize; skip++) { - int tempCount = getSuggestionsNative(mNativeDict, mInputCodes, codesSize, - mOutputChars, mFrequencies, - MAX_WORD_LENGTH, MAX_WORDS, MAX_ALTERNATIVES, skip, - null, 0); - count = Math.max(count, tempCount); - if (tempCount > 0) break; - } - } - - for (int j = 0; j < count; j++) { + for (int j = 0; j < count; ++j) { if (mFrequencies[j] < 1) break; - int start = j * MAX_WORD_LENGTH; + final int start = j * MAX_WORD_LENGTH; int len = 0; - while (mOutputChars[start + len] != 0) { - len++; + while (len < MAX_WORD_LENGTH && mOutputChars[start + len] != 0) { + ++len; } if (len > 0) { callback.addWord(mOutputChars, start, len, mFrequencies[j], mDicTypeId, @@ -241,21 +186,29 @@ public class BinaryDictionary extends Dictionary { return isValidWordNative(mNativeDict, chars, chars.length); } - public int getSize() { - return mDictLength; // This value is initialized on the call to openNative() + public long getSize() { + return mDictLength; // This value is initialized in loadDictionary() } @Override public synchronized void close() { + closeInternal(); + } + + private void closeInternal() { if (mNativeDict != 0) { closeNative(mNativeDict); mNativeDict = 0; + mDictLength = 0; } } @Override protected void finalize() throws Throwable { - close(); - super.finalize(); + try { + closeInternal(); + } finally { + super.finalize(); + } } } |