1/*
2 * Copyright (C) 2012 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.makedict;
18
19import com.android.inputmethod.annotations.UsedForTesting;
20import com.android.inputmethod.latin.Constants;
21import com.android.inputmethod.latin.makedict.DictDecoder.DictionaryBufferFactory;
22import com.android.inputmethod.latin.makedict.FusionDictionary.DictionaryOptions;
23
24import java.io.File;
25
26/**
27 * Dictionary File Format Specification.
28 */
29public final class FormatSpec {
30
31    /*
32     * File header layout is as follows:
33     *
34     * v |
35     * e | MAGIC_NUMBER + version of the file format, 2 bytes.
36     * r |
37     * sion
38     *
39     * o |
40     * p | not used                                4 bits
41     * t | has bigrams ?                           1 bit, 1 = yes, 0 = no : CONTAINS_BIGRAMS_FLAG
42     * i | FRENCH_LIGATURE_PROCESSING_FLAG
43     * o | supports dynamic updates ?              1 bit, 1 = yes, 0 = no : SUPPORTS_DYNAMIC_UPDATE
44     * n | GERMAN_UMLAUT_PROCESSING_FLAG
45     * f |
46     * lags
47     *
48     * h |
49     * e | size of the file header, 4bytes
50     * a |   including the size of the magic number, the option flags and the header size
51     * d |
52     * ersize
53     *
54     *   | attributes list
55     *
56     * attributes list is:
57     * <key>   = | string of characters at the char format described below, with the terminator used
58     *           | to signal the end of the string.
59     * <value> = | string of characters at the char format described below, with the terminator used
60     *           | to signal the end of the string.
61     * if the size of already read < headersize, goto key.
62     *
63     */
64
65    /*
66     * Node array (FusionDictionary.PtNodeArray) layout is as follows:
67     *
68     * n |
69     * o | the number of PtNodes, 1 or 2 bytes.
70     * d | 1 byte = bbbbbbbb match
71     * e |   case 1xxxxxxx => xxxxxxx << 8 + next byte
72     * c |   otherwise => bbbbbbbb
73     * o |
74     * unt
75     *
76     * n |
77     * o | sequence of PtNodes,
78     * d | the layout of each PtNode is described below.
79     * e |
80     * s
81     *
82     * f |
83     * o | IF SUPPORTS_DYNAMIC_UPDATE (defined in the file header)
84     * r |     forward link address, 3byte
85     * w | 1 byte = bbbbbbbb match
86     * a |   case 1xxxxxxx => -((xxxxxxx << 16) + (next byte << 8) + next byte)
87     * r |   otherwise => (xxxxxxx << 16) + (next byte << 8) + next byte
88     * d |
89     * linkaddress
90     */
91
92    /* Node (FusionDictionary.PtNode) layout is as follows:
93     *   | IF !SUPPORTS_DYNAMIC_UPDATE
94     *   |   addressType                    xx               : mask with MASK_CHILDREN_ADDRESS_TYPE
95     *   |                          2 bits, 00 = no children : FLAG_CHILDREN_ADDRESS_TYPE_NOADDRESS
96     * f |                                  01 = 1 byte      : FLAG_CHILDREN_ADDRESS_TYPE_ONEBYTE
97     * l |                                  10 = 2 bytes     : FLAG_CHILDREN_ADDRESS_TYPE_TWOBYTES
98     * a |                                  11 = 3 bytes     : FLAG_CHILDREN_ADDRESS_TYPE_THREEBYTES
99     * g | ELSE
100     * s |   is moved ?             2 bits, 11 = no          : FLAG_IS_NOT_MOVED
101     *   |                            This must be the same as FLAG_CHILDREN_ADDRESS_TYPE_THREEBYTES
102     *   |                                  01 = yes         : FLAG_IS_MOVED
103     *   |                        the new address is stored in the same place as the parent address
104     *   |   is deleted?                    10 = yes         : FLAG_IS_DELETED
105     *   | has several chars ?         1 bit, 1 = yes, 0 = no   : FLAG_HAS_MULTIPLE_CHARS
106     *   | has a terminal ?            1 bit, 1 = yes, 0 = no   : FLAG_IS_TERMINAL
107     *   | has shortcut targets ?      1 bit, 1 = yes, 0 = no   : FLAG_HAS_SHORTCUT_TARGETS
108     *   | has bigrams ?               1 bit, 1 = yes, 0 = no   : FLAG_HAS_BIGRAMS
109     *   | is not a word ?             1 bit, 1 = yes, 0 = no   : FLAG_IS_NOT_A_WORD
110     *   | is blacklisted ?            1 bit, 1 = yes, 0 = no   : FLAG_IS_BLACKLISTED
111     *
112     * p |
113     * a | IF SUPPORTS_DYNAMIC_UPDATE (defined in the file header)
114     * r |     parent address, 3byte
115     * e | 1 byte = bbbbbbbb match
116     * n |   case 1xxxxxxx => -((0xxxxxxx << 16) + (next byte << 8) + next byte)
117     * t |   otherwise => (bbbbbbbb << 16) + (next byte << 8) + next byte
118     * a | This address is relative to the head of the PtNode.
119     * d | If the node doesn't have a parent, this field is set to 0.
120     * d |
121     * ress
122     *
123     * c | IF FLAG_HAS_MULTIPLE_CHARS
124     * h |   char, char, char, char    n * (1 or 3 bytes) : use PtNodeInfo for i/o helpers
125     * a |   end                       1 byte, = 0
126     * r | ELSE
127     * s |   char                      1 or 3 bytes
128     *   | END
129     *
130     * f |
131     * r | IF FLAG_IS_TERMINAL
132     * e |   frequency                 1 byte
133     * q |
134     *
135     * c | IF SUPPORTS_DYNAMIC_UPDATE
136     * h |   children address, 3 bytes
137     * i |   1 byte = bbbbbbbb match
138     * l |     case 1xxxxxxx => -((0xxxxxxx << 16) + (next byte << 8) + next byte)
139     * d |     otherwise => (bbbbbbbb<<16) + (next byte << 8) + next byte
140     * r |   if this node doesn't have children, this field is set to 0.
141     * e |     (see BinaryDictEncoderUtils#writeVariableSignedAddress)
142     * n | ELSIF 00 = FLAG_CHILDREN_ADDRESS_TYPE_NOADDRESS == addressType
143     * a |   // nothing
144     * d | ELSIF 01 = FLAG_CHILDREN_ADDRESS_TYPE_ONEBYTE == addressType
145     * d |   children address, 1 byte
146     * r | ELSIF 10 = FLAG_CHILDREN_ADDRESS_TYPE_TWOBYTES == addressType
147     * e |   children address, 2 bytes
148     * s | ELSE // 11 = FLAG_CHILDREN_ADDRESS_TYPE_THREEBYTES = addressType
149     * s |   children address, 3 bytes
150     *   | END
151     *   | This address is relative to the position of this field.
152     *
153     *   | IF FLAG_IS_TERMINAL && FLAG_HAS_SHORTCUT_TARGETS
154     *   | shortcut string list
155     *   | IF FLAG_IS_TERMINAL && FLAG_HAS_BIGRAMS
156     *   | bigrams address list
157     *
158     * Char format is:
159     * 1 byte = bbbbbbbb match
160     * case 000xxxxx: xxxxx << 16 + next byte << 8 + next byte
161     * else: if 00011111 (= 0x1F) : this is the terminator. This is a relevant choice because
162     *       unicode code points range from 0 to 0x10FFFF, so any 3-byte value starting with
163     *       00011111 would be outside unicode.
164     * else: iso-latin-1 code
165     * This allows for the whole unicode range to be encoded, including chars outside of
166     * the BMP. Also everything in the iso-latin-1 charset is only 1 byte, except control
167     * characters which should never happen anyway (and still work, but take 3 bytes).
168     *
169     * bigram address list is:
170     * <flags> = | hasNext = 1 bit, 1 = yes, 0 = no     : FLAG_BIGRAM_SHORTCUT_ATTR_HAS_NEXT
171     *           | addressSign = 1 bit,                 : FLAG_BIGRAM_ATTR_OFFSET_NEGATIVE
172     *           |                      1 = must take -address, 0 = must take +address
173     *           |                         xx : mask with MASK_BIGRAM_ATTR_ADDRESS_TYPE
174     *           | addressFormat = 2 bits, 00 = unused  : FLAG_BIGRAM_ATTR_ADDRESS_TYPE_ONEBYTE
175     *           |                         01 = 1 byte  : FLAG_BIGRAM_ATTR_ADDRESS_TYPE_ONEBYTE
176     *           |                         10 = 2 bytes : FLAG_BIGRAM_ATTR_ADDRESS_TYPE_TWOBYTES
177     *           |                         11 = 3 bytes : FLAG_BIGRAM_ATTR_ADDRESS_TYPE_THREEBYTES
178     *           | 4 bits : frequency         : mask with FLAG_BIGRAM_SHORTCUT_ATTR_FREQUENCY
179     * <address> | IF (01 == FLAG_BIGRAM_ATTR_ADDRESS_TYPE_ONEBYTE == addressFormat)
180     *           |   read 1 byte, add top 4 bits
181     *           | ELSIF (10 == FLAG_BIGRAM_ATTR_ADDRESS_TYPE_TWOBYTES == addressFormat)
182     *           |   read 2 bytes, add top 4 bits
183     *           | ELSE // 11 == FLAG_BIGRAM_ATTR_ADDRESS_TYPE_THREEBYTES == addressFormat
184     *           |   read 3 bytes, add top 4 bits
185     *           | END
186     *           | if (FLAG_BIGRAM_ATTR_OFFSET_NEGATIVE) then address = -address
187     * if (FLAG_BIGRAM_SHORTCUT_ATTR_HAS_NEXT) goto bigram_and_shortcut_address_list_is
188     *
189     * shortcut string list is:
190     * <byte size> = PTNODE_SHORTCUT_LIST_SIZE_SIZE bytes, big-endian: size of the list, in bytes.
191     * <flags>     = | hasNext = 1 bit, 1 = yes, 0 = no : FLAG_BIGRAM_SHORTCUT_ATTR_HAS_NEXT
192     *               | reserved = 3 bits, must be 0
193     *               | 4 bits : frequency : mask with FLAG_BIGRAM_SHORTCUT_ATTR_FREQUENCY
194     * <shortcut>  = | string of characters at the char format described above, with the terminator
195     *               | used to signal the end of the string.
196     * if (FLAG_BIGRAM_SHORTCUT_ATTR_HAS_NEXT goto flags
197     */
198
199    public static final int MAGIC_NUMBER = 0x9BC13AFE;
200    static final int MINIMUM_SUPPORTED_VERSION = 2;
201    static final int MAXIMUM_SUPPORTED_VERSION = 4;
202    static final int NOT_A_VERSION_NUMBER = -1;
203    static final int FIRST_VERSION_WITH_DYNAMIC_UPDATE = 3;
204    static final int FIRST_VERSION_WITH_TERMINAL_ID = 4;
205    static final int VERSION3 = 3;
206    static final int VERSION4 = 4;
207
208    // These options need to be the same numeric values as the one in the native reading code.
209    static final int GERMAN_UMLAUT_PROCESSING_FLAG = 0x1;
210    // TODO: Make the native reading code read this variable.
211    static final int SUPPORTS_DYNAMIC_UPDATE = 0x2;
212    static final int FRENCH_LIGATURE_PROCESSING_FLAG = 0x4;
213    static final int CONTAINS_BIGRAMS_FLAG = 0x8;
214
215    // TODO: Make this value adaptative to content data, store it in the header, and
216    // use it in the reading code.
217    static final int MAX_WORD_LENGTH = Constants.DICTIONARY_MAX_WORD_LENGTH;
218
219    static final int PARENT_ADDRESS_SIZE = 3;
220    static final int FORWARD_LINK_ADDRESS_SIZE = 3;
221
222    // These flags are used only in the static dictionary.
223    static final int MASK_CHILDREN_ADDRESS_TYPE = 0xC0;
224    static final int FLAG_CHILDREN_ADDRESS_TYPE_NOADDRESS = 0x00;
225    static final int FLAG_CHILDREN_ADDRESS_TYPE_ONEBYTE = 0x40;
226    static final int FLAG_CHILDREN_ADDRESS_TYPE_TWOBYTES = 0x80;
227    static final int FLAG_CHILDREN_ADDRESS_TYPE_THREEBYTES = 0xC0;
228
229    static final int FLAG_HAS_MULTIPLE_CHARS = 0x20;
230
231    static final int FLAG_IS_TERMINAL = 0x10;
232    static final int FLAG_HAS_SHORTCUT_TARGETS = 0x08;
233    static final int FLAG_HAS_BIGRAMS = 0x04;
234    static final int FLAG_IS_NOT_A_WORD = 0x02;
235    static final int FLAG_IS_BLACKLISTED = 0x01;
236
237    // These flags are used only in the dynamic dictionary.
238    static final int MASK_MOVE_AND_DELETE_FLAG = 0xC0;
239    static final int FIXED_BIT_OF_DYNAMIC_UPDATE_MOVE = 0x40;
240    static final int FLAG_IS_MOVED = 0x00 | FIXED_BIT_OF_DYNAMIC_UPDATE_MOVE;
241    static final int FLAG_IS_NOT_MOVED = 0x80 | FIXED_BIT_OF_DYNAMIC_UPDATE_MOVE;
242    static final int FLAG_IS_DELETED = 0x80;
243
244    static final int FLAG_BIGRAM_SHORTCUT_ATTR_HAS_NEXT = 0x80;
245    static final int FLAG_BIGRAM_ATTR_OFFSET_NEGATIVE = 0x40;
246    static final int MASK_BIGRAM_ATTR_ADDRESS_TYPE = 0x30;
247    static final int FLAG_BIGRAM_ATTR_ADDRESS_TYPE_ONEBYTE = 0x10;
248    static final int FLAG_BIGRAM_ATTR_ADDRESS_TYPE_TWOBYTES = 0x20;
249    static final int FLAG_BIGRAM_ATTR_ADDRESS_TYPE_THREEBYTES = 0x30;
250    static final int FLAG_BIGRAM_SHORTCUT_ATTR_FREQUENCY = 0x0F;
251
252    static final int PTNODE_CHARACTERS_TERMINATOR = 0x1F;
253
254    static final int PTNODE_TERMINATOR_SIZE = 1;
255    static final int PTNODE_FLAGS_SIZE = 1;
256    static final int PTNODE_FREQUENCY_SIZE = 1;
257    static final int PTNODE_TERMINAL_ID_SIZE = 4;
258    static final int PTNODE_MAX_ADDRESS_SIZE = 3;
259    static final int PTNODE_ATTRIBUTE_FLAGS_SIZE = 1;
260    static final int PTNODE_ATTRIBUTE_MAX_ADDRESS_SIZE = 3;
261    static final int PTNODE_SHORTCUT_LIST_SIZE_SIZE = 2;
262
263    // These values are used only by version 4 or later.
264    static final String TRIE_FILE_EXTENSION = ".trie";
265    static final String FREQ_FILE_EXTENSION = ".freq";
266    // tat = Terminal Address Table
267    static final String TERMINAL_ADDRESS_TABLE_FILE_EXTENSION = ".tat";
268    static final String BIGRAM_FILE_EXTENSION = ".bigram";
269    static final String SHORTCUT_FILE_EXTENSION = ".shortcut";
270    static final String LOOKUP_TABLE_FILE_SUFFIX = "_lookup";
271    static final String CONTENT_TABLE_FILE_SUFFIX = "_index";
272    static final int FREQUENCY_AND_FLAGS_SIZE = 2;
273    static final int TERMINAL_ADDRESS_TABLE_ADDRESS_SIZE = 3;
274
275    // With the English main dictionary as of October 2013, the size of bigram address table is
276    // is 584KB with the block size being 4.
277    // This is 91% of that of full address table.
278    static final int BIGRAM_ADDRESS_TABLE_BLOCK_SIZE = 4;
279    static final int BIGRAM_CONTENT_COUNT = 1;
280    static final int BIGRAM_FREQ_CONTENT_INDEX = 0;
281    static final String BIGRAM_FREQ_CONTENT_ID = "_freq";
282
283    static final int SHORTCUT_CONTENT_COUNT = 1;
284    static final int SHORTCUT_CONTENT_INDEX = 0;
285    // With the English main dictionary as of October 2013, the size of shortcut address table is
286    // 29KB with the block size being 64.
287    // This is only 4.4% of that of full address table.
288    static final int SHORTCUT_ADDRESS_TABLE_BLOCK_SIZE = 64;
289    static final String SHORTCUT_CONTENT_ID = "_shortcut";
290
291    static final int NO_CHILDREN_ADDRESS = Integer.MIN_VALUE;
292    static final int NO_PARENT_ADDRESS = 0;
293    static final int NO_FORWARD_LINK_ADDRESS = 0;
294    static final int INVALID_CHARACTER = -1;
295
296    static final int MAX_PTNODES_FOR_ONE_BYTE_PTNODE_COUNT = 0x7F; // 127
297    static final int MAX_PTNODES_IN_A_PT_NODE_ARRAY = 0x7FFF; // 32767
298    static final int MAX_BIGRAMS_IN_A_PTNODE = 10000;
299    static final int MAX_SHORTCUT_LIST_SIZE_IN_A_PTNODE = 0xFFFF;
300
301    static final int MAX_TERMINAL_FREQUENCY = 255;
302    static final int MAX_BIGRAM_FREQUENCY = 15;
303
304    public static final int SHORTCUT_WHITELIST_FREQUENCY = 15;
305
306    // This option needs to be the same numeric value as the one in binary_format.h.
307    static final int NOT_VALID_WORD = -99;
308    static final int SIGNED_CHILDREN_ADDRESS_SIZE = 3;
309
310    static final int UINT8_MAX = 0xFF;
311    static final int UINT16_MAX = 0xFFFF;
312    static final int UINT24_MAX = 0xFFFFFF;
313    static final int SINT24_MAX = 0x7FFFFF;
314    static final int MSB8 = 0x80;
315    static final int MSB24 = 0x800000;
316
317    /**
318     * Options about file format.
319     */
320    public static final class FormatOptions {
321        public final int mVersion;
322        public final boolean mSupportsDynamicUpdate;
323        public final boolean mHasTerminalId;
324        @UsedForTesting
325        public FormatOptions(final int version) {
326            this(version, false);
327        }
328
329        @UsedForTesting
330        public FormatOptions(final int version, final boolean supportsDynamicUpdate) {
331            mVersion = version;
332            if (version < FIRST_VERSION_WITH_DYNAMIC_UPDATE && supportsDynamicUpdate) {
333                throw new RuntimeException("Dynamic updates are only supported with versions "
334                        + FIRST_VERSION_WITH_DYNAMIC_UPDATE + " and ulterior.");
335            }
336            mSupportsDynamicUpdate = supportsDynamicUpdate;
337            mHasTerminalId = (version >= FIRST_VERSION_WITH_TERMINAL_ID);
338        }
339    }
340
341    /**
342     * Class representing file header.
343     */
344    public static final class FileHeader {
345        public final int mHeaderSize;
346        public final DictionaryOptions mDictionaryOptions;
347        public final FormatOptions mFormatOptions;
348        // Note that these are corresponding definitions in native code in latinime::HeaderPolicy
349        // and latinime::HeaderReadWriteUtils.
350        public static final String SUPPORTS_DYNAMIC_UPDATE_ATTRIBUTE = "SUPPORTS_DYNAMIC_UPDATE";
351        public static final String USES_FORGETTING_CURVE_ATTRIBUTE = "USES_FORGETTING_CURVE";
352        public static final String ATTRIBUTE_VALUE_TRUE = "1";
353
354        public static final String DICTIONARY_VERSION_ATTRIBUTE = "version";
355        public static final String DICTIONARY_LOCALE_ATTRIBUTE = "locale";
356        public static final String DICTIONARY_ID_ATTRIBUTE = "dictionary";
357        private static final String DICTIONARY_DESCRIPTION_ATTRIBUTE = "description";
358        public FileHeader(final int headerSize, final DictionaryOptions dictionaryOptions,
359                final FormatOptions formatOptions) {
360            mHeaderSize = headerSize;
361            mDictionaryOptions = dictionaryOptions;
362            mFormatOptions = formatOptions;
363        }
364
365        // Helper method to get the locale as a String
366        public String getLocaleString() {
367            return mDictionaryOptions.mAttributes.get(FileHeader.DICTIONARY_LOCALE_ATTRIBUTE);
368        }
369
370        // Helper method to get the version String
371        public String getVersion() {
372            return mDictionaryOptions.mAttributes.get(FileHeader.DICTIONARY_VERSION_ATTRIBUTE);
373        }
374
375        // Helper method to get the dictionary ID as a String
376        public String getId() {
377            return mDictionaryOptions.mAttributes.get(FileHeader.DICTIONARY_ID_ATTRIBUTE);
378        }
379
380        // Helper method to get the description
381        public String getDescription() {
382            // TODO: Right now each dictionary file comes with a description in its own language.
383            // It will display as is no matter the device's locale. It should be internationalized.
384            return mDictionaryOptions.mAttributes.get(FileHeader.DICTIONARY_DESCRIPTION_ATTRIBUTE);
385        }
386    }
387
388    /**
389     * Returns new dictionary decoder.
390     *
391     * @param dictFile the dictionary file.
392     * @param bufferType The type of buffer, as one of USE_* in DictDecoder.
393     * @return new dictionary decoder if the dictionary file exists, otherwise null.
394     */
395    public static DictDecoder getDictDecoder(final File dictFile, final int bufferType) {
396        if (dictFile.isDirectory()) {
397            return new Ver4DictDecoder(dictFile, bufferType);
398        } else if (dictFile.isFile()) {
399            return new Ver3DictDecoder(dictFile, bufferType);
400        }
401        return null;
402    }
403
404    public static DictDecoder getDictDecoder(final File dictFile,
405            final DictionaryBufferFactory factory) {
406        if (dictFile.isDirectory()) {
407            return new Ver4DictDecoder(dictFile, factory);
408        } else if (dictFile.isFile()) {
409            return new Ver3DictDecoder(dictFile, factory);
410        }
411        return null;
412    }
413
414    public static DictDecoder getDictDecoder(final File dictFile) {
415        return getDictDecoder(dictFile, DictDecoder.USE_READONLY_BYTEBUFFER);
416    }
417
418    private FormatSpec() {
419        // This utility class is not publicly instantiable.
420    }
421}
422