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