BinaryDictionary.java revision e8ef09567077211da034a77b457fd5f87e70f6f0
1/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of 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,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.inputmethod.latin;
18
19import android.text.TextUtils;
20import android.util.SparseArray;
21
22import com.android.inputmethod.keyboard.ProximityInfo;
23import com.android.inputmethod.latin.SuggestedWords.SuggestedWordInfo;
24import com.android.inputmethod.latin.settings.AdditionalFeaturesSettingUtils;
25import com.android.inputmethod.latin.settings.NativeSuggestOptions;
26import com.android.inputmethod.latin.utils.CollectionUtils;
27import com.android.inputmethod.latin.utils.JniUtils;
28import com.android.inputmethod.latin.utils.StringUtils;
29
30import java.util.ArrayList;
31import java.util.Arrays;
32import java.util.Locale;
33
34/**
35 * Implements a static, compacted, binary dictionary of standard words.
36 */
37public final class BinaryDictionary extends Dictionary {
38    private static final String TAG = BinaryDictionary.class.getSimpleName();
39
40    // Must be equal to MAX_WORD_LENGTH in native/jni/src/defines.h
41    private static final int MAX_WORD_LENGTH = Constants.DICTIONARY_MAX_WORD_LENGTH;
42    // Must be equal to MAX_RESULTS in native/jni/src/defines.h
43    private static final int MAX_RESULTS = 18;
44
45    private long mNativeDict;
46    private final Locale mLocale;
47    private final int[] mInputCodePoints = new int[MAX_WORD_LENGTH];
48    private final int[] mOutputCodePoints = new int[MAX_WORD_LENGTH * MAX_RESULTS];
49    private final int[] mSpaceIndices = new int[MAX_RESULTS];
50    private final int[] mOutputScores = new int[MAX_RESULTS];
51    private final int[] mOutputTypes = new int[MAX_RESULTS];
52
53    private final NativeSuggestOptions mNativeSuggestOptions = new NativeSuggestOptions();
54
55    private final SparseArray<DicTraverseSession> mDicTraverseSessions =
56            CollectionUtils.newSparseArray();
57
58    // TODO: There should be a way to remove used DicTraverseSession objects from
59    // {@code mDicTraverseSessions}.
60    private DicTraverseSession getTraverseSession(final int traverseSessionId) {
61        synchronized(mDicTraverseSessions) {
62            DicTraverseSession traverseSession = mDicTraverseSessions.get(traverseSessionId);
63            if (traverseSession == null) {
64                traverseSession = mDicTraverseSessions.get(traverseSessionId);
65                if (traverseSession == null) {
66                    traverseSession = new DicTraverseSession(mLocale, mNativeDict);
67                    mDicTraverseSessions.put(traverseSessionId, traverseSession);
68                }
69            }
70            return traverseSession;
71        }
72    }
73
74    /**
75     * Constructor for the binary dictionary. This is supposed to be called from the
76     * dictionary factory.
77     * @param filename the name of the file to read through native code.
78     * @param offset the offset of the dictionary data within the file.
79     * @param length the length of the binary data.
80     * @param useFullEditDistance whether to use the full edit distance in suggestions
81     * @param dictType the dictionary type, as a human-readable string
82     * @param isUpdatable whether to open the dictionary file in writable mode.
83     */
84    public BinaryDictionary(final String filename, final long offset, final long length,
85            final boolean useFullEditDistance, final Locale locale, final String dictType,
86            final boolean isUpdatable) {
87        super(dictType);
88        mLocale = locale;
89        mNativeSuggestOptions.setUseFullEditDistance(useFullEditDistance);
90        loadDictionary(filename, offset, length, isUpdatable);
91    }
92
93    static {
94        JniUtils.loadNativeLibrary();
95    }
96
97    private static native long openNative(String sourceDir, long dictOffset, long dictSize,
98            boolean isUpdatable);
99    private static native void closeNative(long dict);
100    private static native int getProbabilityNative(long dict, int[] word);
101    private static native boolean isValidBigramNative(long dict, int[] word0, int[] word1);
102    private static native int getSuggestionsNative(long dict, long proximityInfo,
103            long traverseSession, int[] xCoordinates, int[] yCoordinates, int[] times,
104            int[] pointerIds, int[] inputCodePoints, int inputSize, int commitPoint,
105            int[] suggestOptions, int[] prevWordCodePointArray,
106            int[] outputCodePoints, int[] outputScores, int[] outputIndices, int[] outputTypes);
107    private static native float calcNormalizedScoreNative(int[] before, int[] after, int score);
108    private static native int editDistanceNative(int[] before, int[] after);
109    private static native void addUnigramWordNative(long dict, int[] word, int probability);
110    private static native void addBigramWordsNative(long dict, int[] word0, int[] word1,
111            int probability);
112    private static native void removeBigramWordsNative(long dict, int[] word0, int[] word1);
113
114    // TODO: Move native dict into session
115    private final void loadDictionary(final String path, final long startOffset,
116            final long length, final boolean isUpdatable) {
117        mNativeDict = openNative(path, startOffset, length, isUpdatable);
118    }
119
120    @Override
121    public ArrayList<SuggestedWordInfo> getSuggestions(final WordComposer composer,
122            final String prevWord, final ProximityInfo proximityInfo,
123            final boolean blockOffensiveWords) {
124        return getSuggestionsWithSessionId(composer, prevWord, proximityInfo, blockOffensiveWords,
125                0 /* sessionId */);
126    }
127
128    @Override
129    public ArrayList<SuggestedWordInfo> getSuggestionsWithSessionId(final WordComposer composer,
130            final String prevWord, final ProximityInfo proximityInfo,
131            final boolean blockOffensiveWords, final int sessionId) {
132        if (!isValidDictionary()) return null;
133
134        Arrays.fill(mInputCodePoints, Constants.NOT_A_CODE);
135        // TODO: toLowerCase in the native code
136        final int[] prevWordCodePointArray = (null == prevWord)
137                ? null : StringUtils.toCodePointArray(prevWord);
138        final int composerSize = composer.size();
139
140        final boolean isGesture = composer.isBatchMode();
141        if (composerSize <= 1 || !isGesture) {
142            if (composerSize > MAX_WORD_LENGTH - 1) return null;
143            for (int i = 0; i < composerSize; i++) {
144                mInputCodePoints[i] = composer.getCodeAt(i);
145            }
146        }
147
148        final InputPointers ips = composer.getInputPointers();
149        final int inputSize = isGesture ? ips.getPointerSize() : composerSize;
150        mNativeSuggestOptions.setIsGesture(isGesture);
151        mNativeSuggestOptions.setAdditionalFeaturesOptions(
152                AdditionalFeaturesSettingUtils.getAdditionalNativeSuggestOptions());
153        // proximityInfo and/or prevWordForBigrams may not be null.
154        final int count = getSuggestionsNative(mNativeDict, proximityInfo.getNativeProximityInfo(),
155                getTraverseSession(sessionId).getSession(), ips.getXCoordinates(),
156                ips.getYCoordinates(), ips.getTimes(), ips.getPointerIds(), mInputCodePoints,
157                inputSize, 0 /* commitPoint */, mNativeSuggestOptions.getOptions(),
158                prevWordCodePointArray, mOutputCodePoints, mOutputScores, mSpaceIndices,
159                mOutputTypes);
160        final ArrayList<SuggestedWordInfo> suggestions = CollectionUtils.newArrayList();
161        for (int j = 0; j < count; ++j) {
162            final int start = j * MAX_WORD_LENGTH;
163            int len = 0;
164            while (len < MAX_WORD_LENGTH && mOutputCodePoints[start + len] != 0) {
165                ++len;
166            }
167            if (len > 0) {
168                final int flags = mOutputTypes[j] & SuggestedWordInfo.KIND_MASK_FLAGS;
169                if (blockOffensiveWords
170                        && 0 != (flags & SuggestedWordInfo.KIND_FLAG_POSSIBLY_OFFENSIVE)
171                        && 0 == (flags & SuggestedWordInfo.KIND_FLAG_EXACT_MATCH)) {
172                    // If we block potentially offensive words, and if the word is possibly
173                    // offensive, then we don't output it unless it's also an exact match.
174                    continue;
175                }
176                final int kind = mOutputTypes[j] & SuggestedWordInfo.KIND_MASK_KIND;
177                final int score = SuggestedWordInfo.KIND_WHITELIST == kind
178                        ? SuggestedWordInfo.MAX_SCORE : mOutputScores[j];
179                // TODO: check that all users of the `kind' parameter are ready to accept
180                // flags too and pass mOutputTypes[j] instead of kind
181                suggestions.add(new SuggestedWordInfo(new String(mOutputCodePoints, start, len),
182                        score, kind, this /* sourceDict */,
183                        mSpaceIndices[0] /* indexOfTouchPointOfSecondWord */));
184            }
185        }
186        return suggestions;
187    }
188
189    public boolean isValidDictionary() {
190        return mNativeDict != 0;
191    }
192
193    public static float calcNormalizedScore(final String before, final String after,
194            final int score) {
195        return calcNormalizedScoreNative(StringUtils.toCodePointArray(before),
196                StringUtils.toCodePointArray(after), score);
197    }
198
199    public static int editDistance(final String before, final String after) {
200        if (before == null || after == null) {
201            throw new IllegalArgumentException();
202        }
203        return editDistanceNative(StringUtils.toCodePointArray(before),
204                StringUtils.toCodePointArray(after));
205    }
206
207    @Override
208    public boolean isValidWord(final String word) {
209        return getFrequency(word) >= 0;
210    }
211
212    @Override
213    public int getFrequency(final String word) {
214        if (word == null) return -1;
215        int[] codePoints = StringUtils.toCodePointArray(word);
216        return getProbabilityNative(mNativeDict, codePoints);
217    }
218
219    // TODO: Add a batch process version (isValidBigramMultiple?) to avoid excessive numbers of jni
220    // calls when checking for changes in an entire dictionary.
221    public boolean isValidBigram(final String word0, final String word1) {
222        if (TextUtils.isEmpty(word0) || TextUtils.isEmpty(word1)) return false;
223        final int[] codePoints0 = StringUtils.toCodePointArray(word0);
224        final int[] codePoints1 = StringUtils.toCodePointArray(word1);
225        return isValidBigramNative(mNativeDict, codePoints0, codePoints1);
226    }
227
228    // Add a unigram entry to binary dictionary in native code.
229    public void addUnigramWord(final String word, final int probability) {
230        if (TextUtils.isEmpty(word)) {
231            return;
232        }
233        final int[] codePoints = StringUtils.toCodePointArray(word);
234        addUnigramWordNative(mNativeDict, codePoints, probability);
235    }
236
237    // Add a bigram entry to binary dictionary in native code.
238    public void addBigramWords(final String word0, final String word1, final int probability) {
239        if (TextUtils.isEmpty(word0) || TextUtils.isEmpty(word1)) {
240            return;
241        }
242        final int[] codePoints0 = StringUtils.toCodePointArray(word0);
243        final int[] codePoints1 = StringUtils.toCodePointArray(word1);
244        addBigramWordsNative(mNativeDict, codePoints0, codePoints1, probability);
245    }
246
247    // Remove a bigram entry form binary dictionary in native code.
248    public void removeBigramWords(final String word0, final String word1) {
249        if (TextUtils.isEmpty(word0) || TextUtils.isEmpty(word1)) {
250            return;
251        }
252        final int[] codePoints0 = StringUtils.toCodePointArray(word0);
253        final int[] codePoints1 = StringUtils.toCodePointArray(word1);
254        removeBigramWordsNative(mNativeDict, codePoints0, codePoints1);
255    }
256
257    @Override
258    public void close() {
259        synchronized (mDicTraverseSessions) {
260            final int sessionsSize = mDicTraverseSessions.size();
261            for (int index = 0; index < sessionsSize; ++index) {
262                final DicTraverseSession traverseSession = mDicTraverseSessions.valueAt(index);
263                if (traverseSession != null) {
264                    traverseSession.close();
265                }
266            }
267        }
268        closeInternal();
269    }
270
271    private synchronized void closeInternal() {
272        if (mNativeDict != 0) {
273            closeNative(mNativeDict);
274            mNativeDict = 0;
275        }
276    }
277
278    @Override
279    protected void finalize() throws Throwable {
280        try {
281            closeInternal();
282        } finally {
283            super.finalize();
284        }
285    }
286}
287