BinaryDictionary.java revision ac27e4544b5b5ff7b4f365a4bde5c288d511ae13
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;
20
21import com.android.inputmethod.keyboard.ProximityInfo;
22
23import java.util.Arrays;
24import java.util.Locale;
25
26/**
27 * Implements a static, compacted, binary dictionary of standard words.
28 */
29public class BinaryDictionary extends Dictionary {
30
31    public static final String DICTIONARY_PACK_AUTHORITY =
32            "com.android.inputmethod.latin.dictionarypack";
33
34    /**
35     * There is a difference between what java and native code can handle.
36     * This value should only be used in BinaryDictionary.java
37     * It is necessary to keep it at this value because some languages e.g. German have
38     * really long words.
39     */
40    public static final int MAX_WORD_LENGTH = 48;
41    public static final int MAX_WORDS = 18;
42
43    private static final String TAG = "BinaryDictionary";
44    private static final int MAX_BIGRAMS = 60;
45
46    private static final int TYPED_LETTER_MULTIPLIER = 2;
47
48    private int mDicTypeId;
49    private long mNativeDict;
50    private final int[] mInputCodes = new int[MAX_WORD_LENGTH];
51    private final char[] mOutputChars = new char[MAX_WORD_LENGTH * MAX_WORDS];
52    private final char[] mOutputChars_bigrams = new char[MAX_WORD_LENGTH * MAX_BIGRAMS];
53    private final int[] mScores = new int[MAX_WORDS];
54    private final int[] mBigramScores = new int[MAX_BIGRAMS];
55
56    private final boolean mUseFullEditDistance;
57
58    /**
59     * Constructor for the binary dictionary. This is supposed to be called from the
60     * dictionary factory.
61     * All implementations should pass null into flagArray, except for testing purposes.
62     * @param context the context to access the environment from.
63     * @param filename the name of the file to read through native code.
64     * @param offset the offset of the dictionary data within the file.
65     * @param length the length of the binary data.
66     * @param useFullEditDistance whether to use the full edit distance in suggestions
67     */
68    public BinaryDictionary(final Context context,
69            final String filename, final long offset, final long length,
70            final boolean useFullEditDistance, final Locale locale) {
71        // Note: at the moment a binary dictionary is always of the "main" type.
72        // Initializing this here will help transitioning out of the scheme where
73        // the Suggest class knows everything about every single dictionary.
74        mDicTypeId = Suggest.DIC_MAIN;
75        mUseFullEditDistance = useFullEditDistance;
76        loadDictionary(filename, offset, length);
77    }
78
79    static {
80        JniUtils.loadNativeLibrary();
81    }
82
83    private native long openNative(String sourceDir, long dictOffset, long dictSize,
84            int typedLetterMultiplier, int fullWordMultiplier, int maxWordLength, int maxWords);
85    private native void closeNative(long dict);
86    private native boolean isValidWordNative(long dict, char[] word, int wordLength);
87    private native int getSuggestionsNative(long dict, long proximityInfo, int[] xCoordinates,
88            int[] yCoordinates, int[] inputCodes, int codesSize, boolean useFullEditDistance,
89            char[] outputChars, int[] scores);
90    private native int getBigramsNative(long dict, char[] prevWord, int prevWordLength,
91            int[] inputCodes, int inputCodesLength, char[] outputChars, int[] scores,
92            int maxWordLength, int maxBigrams);
93    private static native double calcNormalizedScoreNative(
94            char[] before, int beforeLength, char[] after, int afterLength, int score);
95    private static native int editDistanceNative(
96            char[] before, int beforeLength, char[] after, int afterLength);
97
98    private final void loadDictionary(String path, long startOffset, long length) {
99        mNativeDict = openNative(path, startOffset, length,
100                TYPED_LETTER_MULTIPLIER, FULL_WORD_SCORE_MULTIPLIER, MAX_WORD_LENGTH, MAX_WORDS);
101    }
102
103    @Override
104    public void getBigrams(final WordComposer codes, final CharSequence previousWord,
105            final WordCallback callback) {
106        if (mNativeDict == 0) return;
107
108        char[] chars = previousWord.toString().toCharArray();
109        Arrays.fill(mOutputChars_bigrams, (char) 0);
110        Arrays.fill(mBigramScores, 0);
111
112        int codesSize = codes.size();
113        Arrays.fill(mInputCodes, -1);
114        if (codesSize > 0) {
115            mInputCodes[0] = codes.getCodeAt(0);
116        }
117
118        int count = getBigramsNative(mNativeDict, chars, chars.length, mInputCodes, codesSize,
119                mOutputChars_bigrams, mBigramScores, MAX_WORD_LENGTH, MAX_BIGRAMS);
120        if (count > MAX_BIGRAMS) {
121            count = MAX_BIGRAMS;
122        }
123
124        for (int j = 0; j < count; ++j) {
125            if (codesSize > 0 && mBigramScores[j] < 1) break;
126            final int start = j * MAX_WORD_LENGTH;
127            int len = 0;
128            while (len <  MAX_WORD_LENGTH && mOutputChars_bigrams[start + len] != 0) {
129                ++len;
130            }
131            if (len > 0) {
132                callback.addWord(mOutputChars_bigrams, start, len, mBigramScores[j],
133                        mDicTypeId, Dictionary.BIGRAM);
134            }
135        }
136    }
137
138    // proximityInfo and/or prevWordForBigrams may not be null.
139    @Override
140    public void getWords(final WordComposer codes, final CharSequence prevWordForBigrams,
141            final WordCallback callback, final ProximityInfo proximityInfo) {
142        final int count = getSuggestions(codes, prevWordForBigrams, proximityInfo, mOutputChars,
143                mScores);
144
145        for (int j = 0; j < count; ++j) {
146            if (mScores[j] < 1) break;
147            final int start = j * MAX_WORD_LENGTH;
148            int len = 0;
149            while (len < MAX_WORD_LENGTH && mOutputChars[start + len] != 0) {
150                ++len;
151            }
152            if (len > 0) {
153                callback.addWord(mOutputChars, start, len, mScores[j], mDicTypeId,
154                        Dictionary.UNIGRAM);
155            }
156        }
157    }
158
159    /* package for test */ boolean isValidDictionary() {
160        return mNativeDict != 0;
161    }
162
163    // proximityInfo may not be null.
164    /* package for test */ int getSuggestions(final WordComposer codes,
165            final CharSequence prevWordForBigrams, final ProximityInfo proximityInfo,
166            char[] outputChars, int[] scores) {
167        if (!isValidDictionary()) return -1;
168
169        final int codesSize = codes.size();
170        // Won't deal with really long words.
171        if (codesSize > MAX_WORD_LENGTH - 1) return -1;
172
173        Arrays.fill(mInputCodes, WordComposer.NOT_A_CODE);
174        for (int i = 0; i < codesSize; i++) {
175            mInputCodes[i] = codes.getCodeAt(i);
176        }
177        Arrays.fill(outputChars, (char) 0);
178        Arrays.fill(scores, 0);
179
180        // TODO: pass the previous word to native code
181        return getSuggestionsNative(
182                mNativeDict, proximityInfo.getNativeProximityInfo(),
183                codes.getXCoordinates(), codes.getYCoordinates(), mInputCodes, codesSize,
184                mUseFullEditDistance, outputChars, scores);
185    }
186
187    public static double calcNormalizedScore(String before, String after, int score) {
188        return calcNormalizedScoreNative(before.toCharArray(), before.length(),
189                after.toCharArray(), after.length(), score);
190    }
191
192    public static int editDistance(String before, String after) {
193        return editDistanceNative(
194                before.toCharArray(), before.length(), after.toCharArray(), after.length());
195    }
196
197    @Override
198    public boolean isValidWord(CharSequence word) {
199        if (word == null) return false;
200        char[] chars = word.toString().toCharArray();
201        return isValidWordNative(mNativeDict, chars, chars.length);
202    }
203
204    @Override
205    public synchronized void close() {
206        closeInternal();
207    }
208
209    private void closeInternal() {
210        if (mNativeDict != 0) {
211            closeNative(mNativeDict);
212            mNativeDict = 0;
213        }
214    }
215
216    @Override
217    protected void finalize() throws Throwable {
218        try {
219            closeInternal();
220        } finally {
221            super.finalize();
222        }
223    }
224}
225