BinaryDictionary.java revision e28eba5074664d5716b8e58b8d0a235746b261eb
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.utils.AdditionalFeaturesSettingUtils;
25import com.android.inputmethod.latin.utils.CollectionUtils;
26import com.android.inputmethod.latin.utils.JniUtils;
27import com.android.inputmethod.latin.utils.StringUtils;
28
29import java.util.ArrayList;
30import java.util.Arrays;
31import java.util.Locale;
32
33/**
34 * Implements a static, compacted, binary dictionary of standard words.
35 */
36public final class BinaryDictionary extends Dictionary {
37    private static final String TAG = BinaryDictionary.class.getSimpleName();
38
39    // Must be equal to MAX_WORD_LENGTH in native/jni/src/defines.h
40    private static final int MAX_WORD_LENGTH = Constants.Dictionary.MAX_WORD_LENGTH;
41    // Must be equal to MAX_RESULTS in native/jni/src/defines.h
42    private static final int MAX_RESULTS = 18;
43
44    private long mNativeDict;
45    private final Locale mLocale;
46    private final int[] mInputCodePoints = new int[MAX_WORD_LENGTH];
47    private final int[] mOutputCodePoints = new int[MAX_WORD_LENGTH * MAX_RESULTS];
48    private final int[] mSpaceIndices = new int[MAX_RESULTS];
49    private final int[] mOutputScores = new int[MAX_RESULTS];
50    private final int[] mOutputTypes = new int[MAX_RESULTS];
51
52    private final NativeSuggestOptions mNativeSuggestOptions = new NativeSuggestOptions();
53
54    private final SparseArray<DicTraverseSession> mDicTraverseSessions =
55            CollectionUtils.newSparseArray();
56
57    // TODO: There should be a way to remove used DicTraverseSession objects from
58    // {@code mDicTraverseSessions}.
59    private DicTraverseSession getTraverseSession(final int traverseSessionId) {
60        synchronized(mDicTraverseSessions) {
61            DicTraverseSession traverseSession = mDicTraverseSessions.get(traverseSessionId);
62            if (traverseSession == null) {
63                traverseSession = mDicTraverseSessions.get(traverseSessionId);
64                if (traverseSession == null) {
65                    traverseSession = new DicTraverseSession(mLocale, mNativeDict);
66                    mDicTraverseSessions.put(traverseSessionId, traverseSession);
67                }
68            }
69            return traverseSession;
70        }
71    }
72
73    /**
74     * Constructor for the binary dictionary. This is supposed to be called from the
75     * dictionary factory.
76     * @param filename the name of the file to read through native code.
77     * @param offset the offset of the dictionary data within the file.
78     * @param length the length of the binary data.
79     * @param useFullEditDistance whether to use the full edit distance in suggestions
80     * @param dictType the dictionary type, as a human-readable string
81     */
82    public BinaryDictionary(final String filename, final long offset, final long length,
83            final boolean useFullEditDistance, final Locale locale, final String dictType) {
84        super(dictType);
85        mLocale = locale;
86        mNativeSuggestOptions.setUseFullEditDistance(useFullEditDistance);
87        loadDictionary(filename, offset, length);
88    }
89
90    static {
91        JniUtils.loadNativeLibrary();
92    }
93
94    private static native long openNative(String sourceDir, long dictOffset, long dictSize);
95    private static native void closeNative(long dict);
96    private static native int getProbabilityNative(long dict, int[] word);
97    private static native boolean isValidBigramNative(long dict, int[] word1, int[] word2);
98    private static native int getSuggestionsNative(long dict, long proximityInfo,
99            long traverseSession, int[] xCoordinates, int[] yCoordinates, int[] times,
100            int[] pointerIds, int[] inputCodePoints, int inputSize, int commitPoint,
101            int[] suggestOptions, int[] prevWordCodePointArray,
102            int[] outputCodePoints, int[] outputScores, int[] outputIndices, int[] outputTypes);
103    private static native float calcNormalizedScoreNative(int[] before, int[] after, int score);
104    private static native int editDistanceNative(int[] before, int[] after);
105
106    // TODO: Move native dict into session
107    private final void loadDictionary(final String path, final long startOffset,
108            final long length) {
109        mNativeDict = openNative(path, startOffset, length);
110    }
111
112    @Override
113    public ArrayList<SuggestedWordInfo> getSuggestions(final WordComposer composer,
114            final String prevWord, final ProximityInfo proximityInfo,
115            final boolean blockOffensiveWords) {
116        return getSuggestionsWithSessionId(composer, prevWord, proximityInfo, blockOffensiveWords,
117                0 /* sessionId */);
118    }
119
120    @Override
121    public ArrayList<SuggestedWordInfo> getSuggestionsWithSessionId(final WordComposer composer,
122            final String prevWord, final ProximityInfo proximityInfo,
123            final boolean blockOffensiveWords, final int sessionId) {
124        if (!isValidDictionary()) return null;
125
126        Arrays.fill(mInputCodePoints, Constants.NOT_A_CODE);
127        // TODO: toLowerCase in the native code
128        final int[] prevWordCodePointArray = (null == prevWord)
129                ? null : StringUtils.toCodePointArray(prevWord);
130        final int composerSize = composer.size();
131
132        final boolean isGesture = composer.isBatchMode();
133        if (composerSize <= 1 || !isGesture) {
134            if (composerSize > MAX_WORD_LENGTH - 1) return null;
135            for (int i = 0; i < composerSize; i++) {
136                mInputCodePoints[i] = composer.getCodeAt(i);
137            }
138        }
139
140        final InputPointers ips = composer.getInputPointers();
141        final int inputSize = isGesture ? ips.getPointerSize() : composerSize;
142        mNativeSuggestOptions.setIsGesture(isGesture);
143        mNativeSuggestOptions.setAdditionalFeaturesOptions(
144                AdditionalFeaturesSettingUtils.getAdditionalNativeSuggestOptions());
145        // proximityInfo and/or prevWordForBigrams may not be null.
146        final int count = getSuggestionsNative(mNativeDict, proximityInfo.getNativeProximityInfo(),
147                getTraverseSession(sessionId).getSession(), ips.getXCoordinates(),
148                ips.getYCoordinates(), ips.getTimes(), ips.getPointerIds(), mInputCodePoints,
149                inputSize, 0 /* commitPoint */, mNativeSuggestOptions.getOptions(),
150                prevWordCodePointArray, mOutputCodePoints, mOutputScores, mSpaceIndices,
151                mOutputTypes);
152        final ArrayList<SuggestedWordInfo> suggestions = CollectionUtils.newArrayList();
153        for (int j = 0; j < count; ++j) {
154            final int start = j * MAX_WORD_LENGTH;
155            int len = 0;
156            while (len < MAX_WORD_LENGTH && mOutputCodePoints[start + len] != 0) {
157                ++len;
158            }
159            if (len > 0) {
160                final int flags = mOutputTypes[j] & SuggestedWordInfo.KIND_MASK_FLAGS;
161                if (blockOffensiveWords
162                        && 0 != (flags & SuggestedWordInfo.KIND_FLAG_POSSIBLY_OFFENSIVE)
163                        && 0 == (flags & SuggestedWordInfo.KIND_FLAG_EXACT_MATCH)) {
164                    // If we block potentially offensive words, and if the word is possibly
165                    // offensive, then we don't output it unless it's also an exact match.
166                    continue;
167                }
168                final int kind = mOutputTypes[j] & SuggestedWordInfo.KIND_MASK_KIND;
169                final int score = SuggestedWordInfo.KIND_WHITELIST == kind
170                        ? SuggestedWordInfo.MAX_SCORE : mOutputScores[j];
171                // TODO: check that all users of the `kind' parameter are ready to accept
172                // flags too and pass mOutputTypes[j] instead of kind
173                suggestions.add(new SuggestedWordInfo(new String(mOutputCodePoints, start, len),
174                        score, kind, mDictType));
175            }
176        }
177        return suggestions;
178    }
179
180    public boolean isValidDictionary() {
181        return mNativeDict != 0;
182    }
183
184    public static float calcNormalizedScore(final String before, final String after,
185            final int score) {
186        return calcNormalizedScoreNative(StringUtils.toCodePointArray(before),
187                StringUtils.toCodePointArray(after), score);
188    }
189
190    public static int editDistance(final String before, final String after) {
191        if (before == null || after == null) {
192            throw new IllegalArgumentException();
193        }
194        return editDistanceNative(StringUtils.toCodePointArray(before),
195                StringUtils.toCodePointArray(after));
196    }
197
198    @Override
199    public boolean isValidWord(final String word) {
200        return getFrequency(word) >= 0;
201    }
202
203    @Override
204    public int getFrequency(final String word) {
205        if (word == null) return -1;
206        int[] codePoints = StringUtils.toCodePointArray(word);
207        return getProbabilityNative(mNativeDict, codePoints);
208    }
209
210    // TODO: Add a batch process version (isValidBigramMultiple?) to avoid excessive numbers of jni
211    // calls when checking for changes in an entire dictionary.
212    public boolean isValidBigram(final String word1, final String word2) {
213        if (TextUtils.isEmpty(word1) || TextUtils.isEmpty(word2)) return false;
214        final int[] codePoints1 = StringUtils.toCodePointArray(word1);
215        final int[] codePoints2 = StringUtils.toCodePointArray(word2);
216        return isValidBigramNative(mNativeDict, codePoints1, codePoints2);
217    }
218
219    @Override
220    public void close() {
221        synchronized (mDicTraverseSessions) {
222            final int sessionsSize = mDicTraverseSessions.size();
223            for (int index = 0; index < sessionsSize; ++index) {
224                final DicTraverseSession traverseSession = mDicTraverseSessions.valueAt(index);
225                if (traverseSession != null) {
226                    traverseSession.close();
227                }
228            }
229        }
230        closeInternal();
231    }
232
233    private synchronized 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