BinaryDictionary.java revision f3850e554389dc3012584f9d81a4f2d3d4c89e44
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;
23import com.android.inputmethod.latin.SuggestedWords.SuggestedWordInfo;
24
25import java.util.ArrayList;
26import java.util.Arrays;
27import java.util.Locale;
28
29/**
30 * Implements a static, compacted, binary dictionary of standard words.
31 */
32public class BinaryDictionary extends Dictionary {
33
34    public static final String DICTIONARY_PACK_AUTHORITY =
35            "com.android.inputmethod.latin.dictionarypack";
36
37    /**
38     * There is a difference between what java and native code can handle.
39     * This value should only be used in BinaryDictionary.java
40     * It is necessary to keep it at this value because some languages e.g. German have
41     * really long words.
42     */
43    public static final int MAX_WORD_LENGTH = 48;
44    public static final int MAX_WORDS = 18;
45    public static final int MAX_SPACES = 16;
46
47    private static final String TAG = "BinaryDictionary";
48    private static final int MAX_PREDICTIONS = 60;
49    private static final int MAX_RESULTS = Math.max(MAX_PREDICTIONS, MAX_WORDS);
50
51    private static final int TYPED_LETTER_MULTIPLIER = 2;
52
53    private long mNativeDict;
54    private final int[] mInputCodePoints = new int[MAX_WORD_LENGTH];
55    // TODO: The below should be int[] mOutputCodePoints
56    private final char[] mOutputChars = new char[MAX_WORD_LENGTH * MAX_RESULTS];
57    private final int[] mSpaceIndices = new int[MAX_SPACES];
58    private final int[] mOutputScores = new int[MAX_RESULTS];
59    private final int[] mOutputTypes = new int[MAX_RESULTS];
60
61    private final boolean mUseFullEditDistance;
62    private final DicTraverseSession mDicTraverseSession;
63
64    /**
65     * Constructor for the binary dictionary. This is supposed to be called from the
66     * dictionary factory.
67     * All implementations should pass null into flagArray, except for testing purposes.
68     * @param context the context to access the environment from.
69     * @param filename the name of the file to read through native code.
70     * @param offset the offset of the dictionary data within the file.
71     * @param length the length of the binary data.
72     * @param useFullEditDistance whether to use the full edit distance in suggestions
73     * @param dictType the dictionary type, as a human-readable string
74     */
75    public BinaryDictionary(final Context context,
76            final String filename, final long offset, final long length,
77            final boolean useFullEditDistance, final Locale locale, final String dictType) {
78        super(dictType);
79        mUseFullEditDistance = useFullEditDistance;
80        loadDictionary(filename, offset, length);
81        mDicTraverseSession = new DicTraverseSession(locale);
82    }
83
84    static {
85        JniUtils.loadNativeLibrary();
86    }
87
88    private native long openNative(String sourceDir, long dictOffset, long dictSize,
89            int typedLetterMultiplier, int fullWordMultiplier, int maxWordLength, int maxWords,
90            int maxPredictions);
91    private native void closeNative(long dict);
92    private native int getFrequencyNative(long dict, int[] word);
93    private native boolean isValidBigramNative(long dict, int[] word1, int[] word2);
94    private native int getSuggestionsNative(long dict, long proximityInfo, long traverseSession,
95            int[] xCoordinates, int[] yCoordinates, int[] times, int[] pointerIds,
96            int[] inputCodePoints, int codesSize, int commitPoint, boolean isGesture,
97            int[] prevWordCodePointArray, boolean useFullEditDistance, char[] outputChars,
98            int[] outputScores, int[] outputIndices, int[] outputTypes);
99    private static native float calcNormalizedScoreNative(char[] before, char[] after, int score);
100    private static native int editDistanceNative(char[] before, char[] after);
101
102    // TODO: Move native dict into session
103    private final void loadDictionary(String path, long startOffset, long length) {
104        mNativeDict = openNative(path, startOffset, length, TYPED_LETTER_MULTIPLIER,
105                FULL_WORD_SCORE_MULTIPLIER, MAX_WORD_LENGTH, MAX_WORDS, MAX_PREDICTIONS);
106    }
107
108    @Override
109    public ArrayList<SuggestedWordInfo> getSuggestions(final WordComposer composer,
110            final CharSequence prevWord, final ProximityInfo proximityInfo) {
111        if (!isValidDictionary()) return null;
112        Arrays.fill(mInputCodePoints, WordComposer.NOT_A_CODE);
113        // TODO: toLowerCase in the native code
114        final int[] prevWordCodePointArray = (null == prevWord)
115                ? null : StringUtils.toCodePointArray(prevWord.toString());
116        final int composerSize = composer.size();
117
118        final boolean isGesture = composer.isBatchMode();
119        if (composerSize <= 1 || !isGesture) {
120            if (composerSize > MAX_WORD_LENGTH - 1) return null;
121            for (int i = 0; i < composerSize; i++) {
122                mInputCodePoints[i] = composer.getCodeAt(i);
123            }
124        }
125
126        final InputPointers ips = composer.getInputPointers();
127        final int codesSize = isGesture ? ips.getPointerSize() : composerSize;
128        // proximityInfo and/or prevWordForBigrams may not be null.
129        final int tmpCount = getSuggestionsNative(mNativeDict,
130                proximityInfo.getNativeProximityInfo(), mDicTraverseSession.getSession(),
131                ips.getXCoordinates(), ips.getYCoordinates(), ips.getTimes(), ips.getPointerIds(),
132                mInputCodePoints, codesSize, 0 /* commitPoint */, isGesture, prevWordCodePointArray,
133                mUseFullEditDistance, mOutputChars, mOutputScores, mSpaceIndices, mOutputTypes);
134        final int count = Math.min(tmpCount, MAX_PREDICTIONS);
135
136        final ArrayList<SuggestedWordInfo> suggestions = new ArrayList<SuggestedWordInfo>();
137        for (int j = 0; j < count; ++j) {
138            if (composerSize > 0 && mOutputScores[j] < 1) break;
139            final int start = j * MAX_WORD_LENGTH;
140            int len = 0;
141            while (len <  MAX_WORD_LENGTH && mOutputChars[start + len] != 0) {
142                ++len;
143            }
144            if (len > 0) {
145                final int score = SuggestedWordInfo.KIND_WHITELIST == mOutputTypes[j]
146                        ? SuggestedWordInfo.MAX_SCORE : mOutputScores[j];
147                suggestions.add(new SuggestedWordInfo(
148                        new String(mOutputChars, start, len), score, mOutputTypes[j], mDictType));
149            }
150        }
151        return suggestions;
152    }
153
154    /* package for test */ boolean isValidDictionary() {
155        return mNativeDict != 0;
156    }
157
158    public static float calcNormalizedScore(String before, String after, int score) {
159        return calcNormalizedScoreNative(before.toCharArray(), after.toCharArray(), score);
160    }
161
162    public static int editDistance(String before, String after) {
163        return editDistanceNative(before.toCharArray(), after.toCharArray());
164    }
165
166    @Override
167    public boolean isValidWord(CharSequence word) {
168        return getFrequency(word) >= 0;
169    }
170
171    @Override
172    public int getFrequency(CharSequence word) {
173        if (word == null) return -1;
174        int[] codePoints = StringUtils.toCodePointArray(word.toString());
175        return getFrequencyNative(mNativeDict, codePoints);
176    }
177
178    // TODO: Add a batch process version (isValidBigramMultiple?) to avoid excessive numbers of jni
179    // calls when checking for changes in an entire dictionary.
180    public boolean isValidBigram(CharSequence word1, CharSequence word2) {
181        if (TextUtils.isEmpty(word1) || TextUtils.isEmpty(word2)) return false;
182        int[] chars1 = StringUtils.toCodePointArray(word1.toString());
183        int[] chars2 = StringUtils.toCodePointArray(word2.toString());
184        return isValidBigramNative(mNativeDict, chars1, chars2);
185    }
186
187    @Override
188    public synchronized void close() {
189        mDicTraverseSession.close();
190        closeInternal();
191    }
192
193    private void closeInternal() {
194        if (mNativeDict != 0) {
195            closeNative(mNativeDict);
196            mNativeDict = 0;
197        }
198    }
199
200    @Override
201    protected void finalize() throws Throwable {
202        try {
203            closeInternal();
204        } finally {
205            super.finalize();
206        }
207    }
208}
209