BinaryDictionary.java revision ea98e026f1ad7732279aec6d06107f46ea0af93d
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.text.TextUtils;
21
22import com.android.inputmethod.keyboard.ProximityInfo;
23import com.android.inputmethod.latin.SuggestedWords.SuggestedWordInfo;
24
25import java.util.ArrayList;
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    public static final int MAX_SPACES = 16;
46
47    private static final String TAG = "BinaryDictionary";
48    private static final int MAX_BIGRAMS = 60;
49    private static final int MAX_RESULTS = MAX_BIGRAMS > MAX_WORDS ? MAX_BIGRAMS : MAX_WORDS;
50
51    private static final int TYPED_LETTER_MULTIPLIER = 2;
52
53    private long mNativeDict;
54    private final int[] mInputCodes = new int[MAX_WORD_LENGTH];
55    private final char[] mOutputChars = new char[MAX_WORD_LENGTH * MAX_RESULTS];
56    private final int[] mSpaceIndices = new int[MAX_SPACES];
57    private final int[] mOutputScores = new int[MAX_RESULTS];
58
59    private final boolean mUseFullEditDistance;
60
61    /**
62     * Constructor for the binary dictionary. This is supposed to be called from the
63     * dictionary factory.
64     * All implementations should pass null into flagArray, except for testing purposes.
65     * @param context the context to access the environment from.
66     * @param filename the name of the file to read through native code.
67     * @param offset the offset of the dictionary data within the file.
68     * @param length the length of the binary data.
69     * @param useFullEditDistance whether to use the full edit distance in suggestions
70     * @param dictType the dictionary type, as a human-readable string
71     */
72    public BinaryDictionary(final Context context,
73            final String filename, final long offset, final long length,
74            final boolean useFullEditDistance, final Locale locale, final String dictType) {
75        super(dictType);
76        mUseFullEditDistance = useFullEditDistance;
77        loadDictionary(filename, offset, length);
78    }
79
80    static {
81        JniUtils.loadNativeLibrary();
82    }
83
84    private native long openNative(String sourceDir, long dictOffset, long dictSize,
85            int typedLetterMultiplier, int fullWordMultiplier, int maxWordLength, int maxWords);
86    private native void closeNative(long dict);
87    private native int getFrequencyNative(long dict, int[] word, int wordLength);
88    private native boolean isValidBigramNative(long dict, int[] word1, int[] word2);
89    private native int getSuggestionsNative(long dict, long proximityInfo, int[] xCoordinates,
90            int[] yCoordinates, int[] times, int[] pointerIds, int[] inputCodes, int codesSize,
91            int commitPoint, boolean isGesture,
92            int[] prevWordCodePointArray, boolean useFullEditDistance, char[] outputChars,
93            int[] scores, int[] outputIndices);
94    private native int getBigramsNative(long dict, int[] prevWord, int prevWordLength,
95            int[] inputCodes, int inputCodesLength, char[] outputChars, int[] scores,
96            int maxWordLength, int maxBigrams);
97    private static native float calcNormalizedScoreNative(
98            char[] before, int beforeLength, char[] after, int afterLength, int score);
99    private static native int editDistanceNative(
100            char[] before, int beforeLength, char[] after, int afterLength);
101
102    private final void loadDictionary(String path, long startOffset, long length) {
103        mNativeDict = openNative(path, startOffset, length,
104                TYPED_LETTER_MULTIPLIER, FULL_WORD_SCORE_MULTIPLIER, MAX_WORD_LENGTH, MAX_WORDS);
105    }
106
107    @Override
108    public ArrayList<SuggestedWordInfo> getSuggestions(final WordComposer composer,
109            final CharSequence prevWord, final ProximityInfo proximityInfo) {
110        if (!isValidDictionary()) return null;
111        Arrays.fill(mInputCodes, WordComposer.NOT_A_CODE);
112        Arrays.fill(mOutputChars, (char) 0);
113        Arrays.fill(mOutputScores, 0);
114        // TODO: toLowerCase in the native code
115        final int[] prevWordCodePointArray = (null == prevWord)
116                ? null : StringUtils.toCodePointArray(prevWord.toString());
117        if (composer.size() <= 1) {
118            return TextUtils.isEmpty(prevWord) ? null : getBigramsInternal(composer,
119                    prevWordCodePointArray);
120        } else {
121            return getWordsInternal(composer, prevWordCodePointArray, proximityInfo);
122        }
123    }
124
125    // TODO: move to native code
126    private ArrayList<SuggestedWordInfo> getBigramsInternal(final WordComposer codes,
127            final int[] previousWord) {
128        int codesSize = codes.size();
129        if (codesSize > 0) {
130            mInputCodes[0] = codes.getCodeAt(0);
131        }
132
133        int count = getBigramsNative(mNativeDict, previousWord, previousWord.length, mInputCodes,
134                codesSize, mOutputChars, mOutputScores, MAX_WORD_LENGTH, MAX_BIGRAMS);
135        if (count > MAX_BIGRAMS) {
136            count = MAX_BIGRAMS;
137        }
138
139        final ArrayList<SuggestedWordInfo> suggestions = new ArrayList<SuggestedWordInfo>();
140        for (int j = 0; j < count; ++j) {
141            if (codesSize > 0 && mOutputScores[j] < 1) break;
142            final int start = j * MAX_WORD_LENGTH;
143            int len = 0;
144            while (len <  MAX_WORD_LENGTH && mOutputChars[start + len] != 0) {
145                ++len;
146            }
147            if (len > 0) {
148                suggestions.add(new SuggestedWordInfo(
149                        new String(mOutputChars, start, len),
150                        mOutputScores[j], SuggestedWordInfo.KIND_CORRECTION, mDictType));
151            }
152        }
153        return suggestions;
154    }
155
156    // TODO: move to native code
157    // proximityInfo and/or prevWordForBigrams may not be null.
158    private ArrayList<SuggestedWordInfo> getWordsInternal(final WordComposer codes,
159            final int[] prevWord, final ProximityInfo proximityInfo) {
160        final int count = getWordsInternalInternal(codes, prevWord, proximityInfo, mOutputChars,
161                mOutputScores, mSpaceIndices);
162
163        final ArrayList<SuggestedWordInfo> suggestions = new ArrayList<SuggestedWordInfo>();
164        for (int j = 0; j < count; ++j) {
165            if (mOutputScores[j] < 1) break;
166            final int start = j * MAX_WORD_LENGTH;
167            int len = 0;
168            while (len < MAX_WORD_LENGTH && mOutputChars[start + len] != 0) {
169                ++len;
170            }
171            if (len > 0) {
172                // TODO: actually get the kind from native code
173                suggestions.add(new SuggestedWordInfo(
174                        new String(mOutputChars, start, len),
175                        mOutputScores[j], SuggestedWordInfo.KIND_CORRECTION, mDictType));
176            }
177        }
178        return suggestions;
179    }
180
181    /* package for test */ boolean isValidDictionary() {
182        return mNativeDict != 0;
183    }
184
185    // proximityInfo may not be null.
186    // TODO: remove this method by inlining it into getWordsInternal
187    private int getWordsInternalInternal(final WordComposer codes,
188            final int[] prevWord, final ProximityInfo proximityInfo,
189            char[] outputChars, int[] scores, int[] spaceIndices) {
190        final InputPointers ips = codes.getInputPointers();
191        final boolean isGesture = codes.isBatchMode();
192        final int codesSize;
193        if (isGesture) {
194            codesSize = ips.getPointerSize();
195        } else {
196            codesSize = codes.size();
197            // Won't deal with really long words.
198            if (codesSize > MAX_WORD_LENGTH - 1) return -1;
199            for (int i = 0; i < codesSize; i++) {
200                mInputCodes[i] = codes.getCodeAt(i);
201            }
202        }
203
204        return getSuggestionsNative(mNativeDict, proximityInfo.getNativeProximityInfo(),
205            ips.getXCoordinates(), ips.getYCoordinates(), ips.getTimes(), ips.getPointerIds(),
206            mInputCodes, codesSize, 0 /* unused */, isGesture, prevWord,
207            mUseFullEditDistance, outputChars, scores, spaceIndices);
208    }
209
210    public static float calcNormalizedScore(String before, String after, int score) {
211        return calcNormalizedScoreNative(before.toCharArray(), before.length(),
212                after.toCharArray(), after.length(), score);
213    }
214
215    public static int editDistance(String before, String after) {
216        return editDistanceNative(
217                before.toCharArray(), before.length(), after.toCharArray(), after.length());
218    }
219
220    @Override
221    public boolean isValidWord(CharSequence word) {
222        return getFrequency(word) >= 0;
223    }
224
225    @Override
226    public int getFrequency(CharSequence word) {
227        if (word == null) return -1;
228        int[] chars = StringUtils.toCodePointArray(word.toString());
229        return getFrequencyNative(mNativeDict, chars, chars.length);
230    }
231
232    // TODO: Add a batch process version (isValidBigramMultiple?) to avoid excessive numbers of jni
233    // calls when checking for changes in an entire dictionary.
234    public boolean isValidBigram(CharSequence word1, CharSequence word2) {
235        if (TextUtils.isEmpty(word1) || TextUtils.isEmpty(word2)) return false;
236        int[] chars1 = StringUtils.toCodePointArray(word1.toString());
237        int[] chars2 = StringUtils.toCodePointArray(word2.toString());
238        return isValidBigramNative(mNativeDict, chars1, chars2);
239    }
240
241    @Override
242    public synchronized void close() {
243        closeInternal();
244    }
245
246    private void closeInternal() {
247        if (mNativeDict != 0) {
248            closeNative(mNativeDict);
249            mNativeDict = 0;
250        }
251    }
252
253    @Override
254    protected void finalize() throws Throwable {
255        try {
256            closeInternal();
257        } finally {
258            super.finalize();
259        }
260    }
261}
262