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