BinaryDictionary.java revision 30088259480130e5bac5c2028e2c7c3e6d4c51a2
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.util.Log;
21
22import java.io.IOException;
23import java.io.InputStream;
24import java.nio.ByteBuffer;
25import java.nio.ByteOrder;
26import java.nio.channels.Channels;
27import java.util.Arrays;
28
29/**
30 * Implements a static, compacted, binary dictionary of standard words.
31 */
32public class BinaryDictionary extends Dictionary {
33
34    /**
35     * There is 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    protected static final int MAX_WORD_LENGTH = 48;
41
42    private static final String TAG = "BinaryDictionary";
43    private static final int MAX_ALTERNATIVES = 16;
44    private static final int MAX_WORDS = 18;
45    private static final int MAX_BIGRAMS = 60;
46
47    private static final int TYPED_LETTER_MULTIPLIER = 2;
48
49    private int mDicTypeId;
50    private int mNativeDict;
51    private int mDictLength;
52    private final int[] mInputCodes = new int[MAX_WORD_LENGTH * MAX_ALTERNATIVES];
53    private final char[] mOutputChars = new char[MAX_WORD_LENGTH * MAX_WORDS];
54    private final char[] mOutputChars_bigrams = new char[MAX_WORD_LENGTH * MAX_BIGRAMS];
55    private final int[] mFrequencies = new int[MAX_WORDS];
56    private final int[] mFrequencies_bigrams = new int[MAX_BIGRAMS];
57    // Keep a reference to the native dict direct buffer in Java to avoid
58    // unexpected deallocation of the direct buffer.
59    private ByteBuffer mNativeDictDirectBuffer;
60
61    static {
62        try {
63            System.loadLibrary("jni_latinime");
64        } catch (UnsatisfiedLinkError ule) {
65            Log.e("BinaryDictionary", "Could not load native library jni_latinime");
66        }
67    }
68
69    /**
70     * Create a dictionary from a raw resource file
71     * @param context application context for reading resources
72     * @param resId the resource containing the raw binary dictionary
73     */
74    public BinaryDictionary(Context context, int[] resId, int dicTypeId) {
75        if (resId != null && resId.length > 0 && resId[0] != 0) {
76            loadDictionary(context, resId);
77        }
78        mDicTypeId = dicTypeId;
79    }
80
81    /**
82     * Create a dictionary from a byte buffer. This is used for testing.
83     * @param context application context for reading resources
84     * @param byteBuffer a ByteBuffer containing the binary dictionary
85     */
86    public BinaryDictionary(Context context, ByteBuffer byteBuffer, int dicTypeId) {
87        if (byteBuffer != null) {
88            if (byteBuffer.isDirect()) {
89                mNativeDictDirectBuffer = byteBuffer;
90            } else {
91                mNativeDictDirectBuffer = ByteBuffer.allocateDirect(byteBuffer.capacity());
92                byteBuffer.rewind();
93                mNativeDictDirectBuffer.put(byteBuffer);
94            }
95            mDictLength = byteBuffer.capacity();
96            mNativeDict = openNative(mNativeDictDirectBuffer,
97                    TYPED_LETTER_MULTIPLIER, FULL_WORD_FREQ_MULTIPLIER,
98                    MAX_WORD_LENGTH, MAX_WORDS, MAX_ALTERNATIVES);
99        }
100        mDicTypeId = dicTypeId;
101    }
102
103    private native int openNative(ByteBuffer bb, int typedLetterMultiplier,
104            int fullWordMultiplier, int maxWordLength, int maxWords, int maxAlternatives);
105    private native void closeNative(int dict);
106    private native boolean isValidWordNative(int nativeData, char[] word, int wordLength);
107    private native int getSuggestionsNative(int dict, int[] inputCodes, int codesSize,
108            char[] outputChars, int[] frequencies,
109            int[] nextLettersFrequencies, int nextLettersSize);
110    private native int getBigramsNative(int dict, char[] prevWord, int prevWordLength,
111            int[] inputCodes, int inputCodesLength, char[] outputChars, int[] frequencies,
112            int maxWordLength, int maxBigrams, int maxAlternatives);
113
114    private final void loadDictionary(Context context, int[] resId) {
115        InputStream[] is = null;
116        try {
117            // merging separated dictionary into one if dictionary is separated
118            int total = 0;
119            is = new InputStream[resId.length];
120            for (int i = 0; i < resId.length; i++) {
121                is[i] = context.getResources().openRawResource(resId[i]);
122                total += is[i].available();
123            }
124
125            mNativeDictDirectBuffer =
126                ByteBuffer.allocateDirect(total).order(ByteOrder.nativeOrder());
127            int got = 0;
128            for (int i = 0; i < resId.length; i++) {
129                 got += Channels.newChannel(is[i]).read(mNativeDictDirectBuffer);
130            }
131            if (got != total) {
132                Log.e(TAG, "Read " + got + " bytes, expected " + total);
133            } else {
134                mNativeDict = openNative(mNativeDictDirectBuffer,
135                        TYPED_LETTER_MULTIPLIER, FULL_WORD_FREQ_MULTIPLIER,
136                        MAX_WORD_LENGTH, MAX_WORDS, MAX_ALTERNATIVES);
137                mDictLength = total;
138            }
139        } catch (IOException e) {
140            Log.w(TAG, "No available memory for binary dictionary");
141        } finally {
142            try {
143                if (is != null) {
144                    for (int i = 0; i < is.length; i++) {
145                        is[i].close();
146                    }
147                }
148            } catch (IOException e) {
149                Log.w(TAG, "Failed to close input stream");
150            }
151        }
152    }
153
154
155    @Override
156    public void getBigrams(final WordComposer codes, final CharSequence previousWord,
157            final WordCallback callback, int[] nextLettersFrequencies) {
158
159        char[] chars = previousWord.toString().toCharArray();
160        Arrays.fill(mOutputChars_bigrams, (char) 0);
161        Arrays.fill(mFrequencies_bigrams, 0);
162
163        int codesSize = codes.size();
164        Arrays.fill(mInputCodes, -1);
165        int[] alternatives = codes.getCodesAt(0);
166        System.arraycopy(alternatives, 0, mInputCodes, 0,
167                Math.min(alternatives.length, MAX_ALTERNATIVES));
168
169        int count = getBigramsNative(mNativeDict, chars, chars.length, mInputCodes, codesSize,
170                mOutputChars_bigrams, mFrequencies_bigrams, MAX_WORD_LENGTH, MAX_BIGRAMS,
171                MAX_ALTERNATIVES);
172
173        for (int j = 0; j < count; j++) {
174            if (mFrequencies_bigrams[j] < 1) break;
175            int start = j * MAX_WORD_LENGTH;
176            int len = 0;
177            while (mOutputChars_bigrams[start + len] != 0) {
178                len++;
179            }
180            if (len > 0) {
181                callback.addWord(mOutputChars_bigrams, start, len, mFrequencies_bigrams[j],
182                        mDicTypeId, DataType.BIGRAM);
183            }
184        }
185    }
186
187    @Override
188    public void getWords(final WordComposer codes, final WordCallback callback,
189            int[] nextLettersFrequencies) {
190        final int codesSize = codes.size();
191        // Won't deal with really long words.
192        if (codesSize > MAX_WORD_LENGTH - 1) return;
193
194        Arrays.fill(mInputCodes, -1);
195        for (int i = 0; i < codesSize; i++) {
196            int[] alternatives = codes.getCodesAt(i);
197            System.arraycopy(alternatives, 0, mInputCodes, i * MAX_ALTERNATIVES,
198                    Math.min(alternatives.length, MAX_ALTERNATIVES));
199        }
200        Arrays.fill(mOutputChars, (char) 0);
201        Arrays.fill(mFrequencies, 0);
202
203        int count = getSuggestionsNative(mNativeDict, mInputCodes, codesSize, mOutputChars,
204                mFrequencies, nextLettersFrequencies,
205                nextLettersFrequencies != null ? nextLettersFrequencies.length : 0);
206
207        for (int j = 0; j < count; j++) {
208            if (mFrequencies[j] < 1) break;
209            int start = j * MAX_WORD_LENGTH;
210            int len = 0;
211            while (mOutputChars[start + len] != 0) {
212                len++;
213            }
214            if (len > 0) {
215                callback.addWord(mOutputChars, start, len, mFrequencies[j], mDicTypeId,
216                        DataType.UNIGRAM);
217            }
218        }
219    }
220
221    @Override
222    public boolean isValidWord(CharSequence word) {
223        if (word == null) return false;
224        char[] chars = word.toString().toCharArray();
225        return isValidWordNative(mNativeDict, chars, chars.length);
226    }
227
228    public int getSize() {
229        return mDictLength; // This value is initialized on the call to openNative()
230    }
231
232    @Override
233    public synchronized void close() {
234        if (mNativeDict != 0) {
235            closeNative(mNativeDict);
236            mNativeDict = 0;
237        }
238    }
239
240    @Override
241    protected void finalize() throws Throwable {
242        close();
243        super.finalize();
244    }
245}
246