BinaryDictionary.java revision 73680097996ea2ddbca3f84144a00ce3ba66b763
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;
23
24import java.util.Arrays;
25import java.util.Locale;
26
27/**
28 * Implements a static, compacted, binary dictionary of standard words.
29 */
30public class BinaryDictionary extends Dictionary {
31
32    public static final String DICTIONARY_PACK_AUTHORITY =
33            "com.android.inputmethod.latin.dictionarypack";
34
35    /**
36     * There is a difference between what java and native code can handle.
37     * This value should only be used in BinaryDictionary.java
38     * It is necessary to keep it at this value because some languages e.g. German have
39     * really long words.
40     */
41    public static final int MAX_WORD_LENGTH = 48;
42    public static final int MAX_WORDS = 18;
43    public static final int MAX_SPACES = 16;
44
45    private static final String TAG = "BinaryDictionary";
46    private static final int MAX_BIGRAMS = 60;
47
48    private static final int TYPED_LETTER_MULTIPLIER = 2;
49
50    private int mDicTypeId;
51    private long mNativeDict;
52    private final int[] mInputCodes = new int[MAX_WORD_LENGTH];
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[] mSpaceIndices = new int[MAX_SPACES];
56    private final int[] mScores = new int[MAX_WORDS];
57    private final int[] mBigramScores = new int[MAX_BIGRAMS];
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 dicTypeId the dictionary type id of the dictionary
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 int dicTypeId) {
75        mDicTypeId = dicTypeId;
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, int dicTypeId,
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 void getBigrams(final WordComposer codes, final CharSequence previousWord,
109            final WordCallback callback) {
110        if (mNativeDict == 0) return;
111
112        int[] codePoints = StringUtils.toCodePointArray(previousWord.toString());
113        Arrays.fill(mOutputChars_bigrams, (char) 0);
114        Arrays.fill(mBigramScores, 0);
115
116        int codesSize = codes.size();
117        Arrays.fill(mInputCodes, -1);
118        if (codesSize > 0) {
119            mInputCodes[0] = codes.getCodeAt(0);
120        }
121
122        int count = getBigramsNative(mNativeDict, codePoints, codePoints.length, mInputCodes,
123                codesSize, mOutputChars_bigrams, mBigramScores, MAX_WORD_LENGTH, MAX_BIGRAMS);
124        if (count > MAX_BIGRAMS) {
125            count = MAX_BIGRAMS;
126        }
127
128        for (int j = 0; j < count; ++j) {
129            if (codesSize > 0 && mBigramScores[j] < 1) break;
130            final int start = j * MAX_WORD_LENGTH;
131            int len = 0;
132            while (len <  MAX_WORD_LENGTH && mOutputChars_bigrams[start + len] != 0) {
133                ++len;
134            }
135            if (len > 0) {
136                callback.addWord(mOutputChars_bigrams, null, start, len, mBigramScores[j],
137                        mDicTypeId, Dictionary.BIGRAM);
138            }
139        }
140    }
141
142    // proximityInfo and/or prevWordForBigrams may not be null.
143    @Override
144    public void getWords(final WordComposer codes, final CharSequence prevWordForBigrams,
145            final WordCallback callback, final ProximityInfo proximityInfo) {
146
147        final int count = getSuggestions(codes, prevWordForBigrams, proximityInfo, mOutputChars,
148                mScores, mSpaceIndices);
149        for (int j = 0; j < count; ++j) {
150            if (mScores[j] < 1) break;
151            final int start = j * MAX_WORD_LENGTH;
152            int len = 0;
153            while (len < MAX_WORD_LENGTH && mOutputChars[start + len] != 0) {
154                ++len;
155            }
156            if (len > 0) {
157                callback.addWord(mOutputChars, null, start, len, mScores[j], mDicTypeId,
158                        Dictionary.UNIGRAM);
159            }
160        }
161    }
162
163    /* package for test */ boolean isValidDictionary() {
164        return mNativeDict != 0;
165    }
166
167    // proximityInfo may not be null.
168    /* package for test */ int getSuggestions(final WordComposer codes,
169            final CharSequence prevWordForBigrams, final ProximityInfo proximityInfo,
170            char[] outputChars, int[] scores, int[] spaceIndices) {
171        if (!isValidDictionary()) return -1;
172
173        final int codesSize = codes.size();
174        // Won't deal with really long words.
175        if (codesSize > MAX_WORD_LENGTH - 1) return -1;
176
177        Arrays.fill(mInputCodes, WordComposer.NOT_A_CODE);
178        for (int i = 0; i < codesSize; i++) {
179            mInputCodes[i] = codes.getCodeAt(i);
180        }
181        Arrays.fill(outputChars, (char) 0);
182        Arrays.fill(scores, 0);
183
184        // TODO: toLowerCase in the native code
185        final int[] prevWordCodePointArray = (null == prevWordForBigrams)
186                ? null : StringUtils.toCodePointArray(prevWordForBigrams.toString());
187
188        int[] emptyArray = new int[codesSize];
189        Arrays.fill(emptyArray, 0);
190
191        //final int commitPoint = codes.getCommitPoint();
192        //codes.clearCommitPoint();
193
194        return getSuggestionsNative(mNativeDict, proximityInfo.getNativeProximityInfo(),
195            codes.getXCoordinates(), codes.getYCoordinates(), emptyArray, emptyArray, mInputCodes,
196            codesSize, 0 /* unused */, false, mDicTypeId,
197            prevWordCodePointArray, mUseFullEditDistance,
198            outputChars, scores, spaceIndices);
199    }
200
201    public static float calcNormalizedScore(String before, String after, int score) {
202        return calcNormalizedScoreNative(before.toCharArray(), before.length(),
203                after.toCharArray(), after.length(), score);
204    }
205
206    public static int editDistance(String before, String after) {
207        return editDistanceNative(
208                before.toCharArray(), before.length(), after.toCharArray(), after.length());
209    }
210
211    @Override
212    public boolean isValidWord(CharSequence word) {
213        return getFrequency(word) >= 0;
214    }
215
216    @Override
217    public int getFrequency(CharSequence word) {
218        if (word == null) return -1;
219        int[] chars = StringUtils.toCodePointArray(word.toString());
220        return getFrequencyNative(mNativeDict, chars, chars.length);
221    }
222
223    // TODO: Add a batch process version (isValidBigramMultiple?) to avoid excessive numbers of jni
224    // calls when checking for changes in an entire dictionary.
225    public boolean isValidBigram(CharSequence word1, CharSequence word2) {
226        if (TextUtils.isEmpty(word1) || TextUtils.isEmpty(word2)) return false;
227        int[] chars1 = StringUtils.toCodePointArray(word1.toString());
228        int[] chars2 = StringUtils.toCodePointArray(word2.toString());
229        return isValidBigramNative(mNativeDict, chars1, chars2);
230    }
231
232    @Override
233    public synchronized void close() {
234        closeInternal();
235    }
236
237    private void closeInternal() {
238        if (mNativeDict != 0) {
239            closeNative(mNativeDict);
240            mNativeDict = 0;
241        }
242    }
243
244    @Override
245    protected void finalize() throws Throwable {
246        try {
247            closeInternal();
248        } finally {
249            super.finalize();
250        }
251    }
252}
253