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