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